class zzzTestRuleDisablePrelinking(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = DisablePrelinking(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.ph = Pkghelper(self.logdispatch, self.environ) self.prelinkInstalled = False def tearDown(self): if not self.prelinkInstalled: self.ph.remove("prelink") def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): '''Configure system for the unit test :param self: essential if you override this definition :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' success = True if self.ph.check("prelink"): self.prelinkInstalled = True elif self.ph.checkAvailable("prelink"): self.ph.install("prelink") else: return True path = "/usr/sbin/prelink" cmd = [path, "/bin/ls"] if os.path.exists(path): self.ch.executeCommand(cmd) if re.search("debian|ubuntu", self.environ.getostype().lower()): path = "/etc/default/prelink" else: path = "/etc/sysconfig/prelink" if os.path.exists(path): tmppath = path + ".tmp" data = {"PRELINKING": "yes"} self.editor = KVEditorStonix(self.statechglogger, self.logdispatch, "conf", path, tmppath, data, "present", "closedeq") if not self.editor.report(): if self.editor.fix(): if not self.editor.commit(): success = False self.logdispatch.log(LogPriority.ERROR, "KVEditor failed to commit.") else: success = False self.logdispatch.log(LogPriority.ERROR, "KVEditor failed to fix.") else: writeFile(path, "PRELINKING=yes", self.logdispatch) return success def checkReportForRule(self, pCompliance, pRuleSuccess): '''check on whether report was correct :param self: essential if you override this definition :param pCompliance: the self.iscompliant value of rule :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkFixForRule(self, pRuleSuccess): '''check on whether fix was correct :param self: essential if you override this definition :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkUndoForRule(self, pRuleSuccess): '''check on whether undo was correct :param self: essential if you override this definition :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success
class zzzTestRuleSecureMTA(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = SecureMTA(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) if self.environ.operatingsystem == "Mac OS X": self.isMac = True else: self.isMac = False if not self.isMac: self.ph = Pkghelper(self.logdispatch, self.environ) self.origState = [False, False, False, False] self.smPath = "/etc/mail/sendmail.cf" self.smTmp = "/tmp/" + os.path.split(self.smPath)[1] + ".utmp" self.pfPathlist = ['/etc/postfix/main.cf', '/private/etc/postfix/main.cf', '/usr/lib/postfix/main.cf'] self.pfPath = "" for path in self.pfPathlist: if os.path.exists(path): self.pfPath = path if self.pfPath == "": self.pfPath = "/etc/postfix/main.cf" self.pfTmp = "/tmp/" + os.path.split(self.pfPath)[1] + ".utmp" def tearDown(self): if not self.isMac: if self.origState[0] is True and not self.ph.check("sendmail"): self.ph.install("sendmail") elif self.origState[0] is False and self.ph.check("sendmail"): self.ph.remove("sendmail") if self.origState[1] is True and not self.ph.check("postfix"): self.ph.install("postfix") elif self.origState[1] is False and self.ph.check("postfix"): self.ph.remove("postfix") if self.origState[2] is True and os.path.exists(self.smTmp): smDir = os.path.split(self.smPath)[0] if not os.path.exists(smDir): os.makedirs(smDir) os.rename(self.smTmp, self.smPath) elif self.origState[2] is False and os.path.exists(self.smPath): os.remove(self.smPath) if self.origState[3] is True and os.path.exists(self.pfTmp): pfDir = os.path.split(self.pfPath)[0] if not os.path.exists(pfDir): os.makedirs(pfDir) os.rename(self.pfTmp, self.pfPath) elif self.origState[3] is False and os.path.exists(self.pfPath): os.remove(self.pfPath) def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): ''' Configure system for the unit test @param self: essential if you override this definition @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' success = True if not self.isMac: if self.ph.check("sendmail"): self.origState[0] = True if self.ph.check("postfix"): self.origState[1] = True if os.path.exists(self.smPath): self.origState[2] = True os.rename(self.smPath, self.smTmp) if os.path.exists(self.pfPath): self.origState[3] = True os.rename(self.pfPath, self.pfTmp) return success def testFalseFalseFalseFalse(self): if not self.isMac: if self.ph.check("sendmail"): self.ph.remove("sendmail") if self.ph.check("postfix"): self.ph.remove("postfix") if os.path.exists(self.smPath): os.remove(self.smPath) if os.path.exists(self.pfPath): os.remove(self.pfPath) self.simpleRuleTest() def testTrueFalseFalseFalse(self): if not self.isMac: if not self.ph.check("sendmail"): self.ph.install("sendmail") if self.ph.check("postfix"): self.ph.remove("postfix") if os.path.exists(self.smPath): os.remove(self.smPath) if os.path.exists(self.pfPath): os.remove(self.pfPath) self.simpleRuleTest() def testTrueTrueFalseFalse(self): if not self.isMac: if not self.ph.check("sendmail"): self.ph.install("sendmail") if not self.ph.check("postfix"): self.ph.install("postfix") if os.path.exists(self.smPath): os.remove(self.smPath) if os.path.exists(self.pfPath): os.remove(self.pfPath) self.simpleRuleTest() def testTrueTrueTrueFalse(self): if not self.isMac: if not self.ph.check("sendmail"): self.ph.install("sendmail") if not self.ph.check("postfix"): self.ph.install("postfix") if not os.path.exists(self.smPath): open(self.smPath, "w") if os.path.exists(self.pfPath): os.remove(self.pfPath) self.simpleRuleTest() def testTrueTrueTrueTrue(self): if not self.isMac: if not self.ph.check("sendmail"): self.ph.install("sendmail") if not self.ph.check("postfix"): self.ph.install("postfix") if not os.path.exists(self.smPath): open(self.smPath, "w") if not os.path.exists(self.pfPath): open(self.pfPath, "w") self.simpleRuleTest() def testTrueFalseTrueFalse(self): if not self.isMac: if not self.ph.check("sendmail"): self.ph.install("sendmail") if self.ph.check("postfix"): self.ph.remove("postfix") if not os.path.exists(self.smPath): open(self.smPath, "w") if os.path.exists(self.pfPath): os.remove(self.pfPath) self.simpleRuleTest() def testFalseTrueFalseFalse(self): if not self.isMac: if self.ph.check("sendmail"): self.ph.remove("sendmail") if not self.ph.check("postfix"): self.ph.install("postfix") if os.path.exists(self.smPath): os.remove(self.smPath) if os.path.exists(self.pfPath): os.remove(self.pfPath) self.simpleRuleTest() def testFalseTrueFalseTrue(self): if not self.isMac: if self.ph.check("sendmail"): self.ph.remove("sendmail") if not self.ph.check("postfix"): self.ph.install("postfix") if os.path.exists(self.smPath): os.remove(self.smPath) if not os.path.exists(self.pfPath): open(self.pfPath, "w") self.simpleRuleTest() def checkReportForRule(self, pCompliance, pRuleSuccess): ''' check on whether report was correct @param self: essential if you override this definition @param pCompliance: the self.iscompliant value of rule @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkFixForRule(self, pRuleSuccess): ''' check on whether fix was correct @param self: essential if you override this definition @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkUndoForRule(self, pRuleSuccess): ''' check on whether undo was correct @param self: essential if you override this definition @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success
class zzzTestRuleRestrictMounting(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = RestrictMounting(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.ph = Pkghelper(self.logdispatch, self.environ) self.sh = ServiceHelper(self.environ, self.logdispatch) def tearDown(self): pass def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): ''' Configure system for the unit test @param self: essential if you override this definition @return: boolean - If successful True; If failure False @author: Eric Ball ''' success = True # Enable CIs datatype = "bool" key = "RESTRICTCONSOLEACCESS" instructions = "Unit test" default = True self.rule.consoleCi = self.rule.initCi(datatype, key, instructions, default) key = "DISABLEAUTOFS" self.rule.autofsCi = self.rule.initCi(datatype, key, instructions, default) key = "DISABLEGNOMEAUTOMOUNT" self.rule.gnomeCi = self.rule.initCi(datatype, key, instructions, default) self.path1 = "/etc/security/console.perms.d/50-default.perms" self.path2 = "/etc/security/console.perms" self.data1 = ["<floppy>=/dev/fd[0-1]* \\", "<scanner>=/dev/scanner* /dev/usb/scanner*", "<flash>=/mnt/flash* /dev/flash*", "# permission definitions", "<console> 0660 <floppy> 0660 root.floppy", "<console> 0600 <scanner> 0600 root", "<console> 0600 <flash> 0600 root.disk"] self.data2 = ["<console>=tty[0-9][0-9]* vc/[0-9][0-9]* :[0-9]+\.[0-9]+ :[0-9]+", "<xconsole>=:[0-9]+\.[0-9]+ :[0-9]+"] if os.path.exists(self.path1): self.tmpfile1 = self.path1 + ".tmp" os.rename(self.path1, self.tmpfile1) try: defaultPermsFile = open(self.path1, "w") except IOError: debug = "Could not open file " + self.path1 + "\n" self.logger.log(LogPriority.DEBUG, debug) success = False try: defaultPermsFile.writelines(self.data1) except IOError: debug = "Could not write to file " + self.path1 + "\n" self.logger.log(LogPriority.DEBUG, debug) success = False if os.path.exists(self.path2): self.tmpfile2 = self.path2 + ".tmp" os.rename(self.path2, self.tmpfile2) try: permsFile = open(self.path2, "w") except IOError: debug = "Could not open file " + self.path2 + "\n" self.logger.log(LogPriority.DEBUG, debug) success = False try: permsFile.writelines(self.data2) except IOError: debug = "Could not write to file " + self.path2 + "\n" self.logger.log(LogPriority.DEBUG, debug) success = False # If autofs is installed, enable and start it. If it is not # installed, it will not be tested. if self.ph.check("autofs"): if not self.sh.enableservice("autofs"): debug = "Could not enable autofs\n" self.logger.log(LogPriority.DEBUG, debug) success = False cmd = ["gconftool-2", "--direct", "--config-source", "xml:readwrite:/etc/gconf/gconf.xml.mandatory", "--type", "bool", "--set", "/desktop/gnome/volume_manager/automount_media", "true"] cmdSuccess = self.ch.executeCommand(cmd) cmd = ["gconftool-2", "--direct", "--config-source", "xml:readwrite:/etc/gconf/gconf.xml.mandatory", "--type", "bool", "--set", "/desktop/gnome/volume_manager/automount_drives", "true"] cmdSuccess &= self.ch.executeCommand(cmd) if not cmdSuccess: success = False return success def checkReportForRule(self, pCompliance, pRuleSuccess): ''' check on whether report was correct @param self: essential if you override this definition @param pCompliance: the self.iscompliant value of rule @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkFixForRule(self, pRuleSuccess): ''' check on whether fix was correct @param self: essential if you override this definition @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' # Cleanup: put original perms files back if os.path.exists(self.path1) and os.path.exists(self.tmpfile1): os.remove(self.path1) os.rename(self.tmpfile1, self.path1) if os.path.exists(self.path2) and os.path.exists(self.tmpfile2): os.remove(self.path2) os.rename(self.tmpfile2, self.path2) self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkUndoForRule(self, pRuleSuccess): ''' check on whether undo was correct @param self: essential if you override this definition @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success
class zzzTestRuleDisableRemoveableStorage(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = DisableRemoveableStorage(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.rule.storageci.updatecurrvalue(True) self.logger = self.logdispatch self.ignoreresults = True def tearDown(self): pass def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): '''Configure system for the unit test :param self: essential if you override this definition :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' success = True if self.environ.getostype() == "Mac OS X": success = self.setConditionsForMac() else: success = self.setConditionsForLinux() return success def setConditionsForMac(self): '''Method to configure mac non compliant for unit test @author: dwalker :returns: boolean ''' success = True daemonpath = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]))) + "/src/stonix_resources/disablestorage.py" plistpath = "/Library/LaunchDaemons/gov.lanl.stonix.disablestorage.plist" self.rule.daemonpath = daemonpath if re.search("^10.11", self.environ.getosver()): usb = "IOUSBMassStorageDriver" else: usb = "IOUSBMassStorageClass" kernelmods = [usb, "IOFireWireFamily", "AppleThunderboltUTDM", "AppleSDXC"] check = "/usr/sbin/kextstat" load = "/sbin/kextload" '''Remove plist file for launch job if exists''' if os.path.exists(plistpath): os.remove(plistpath) '''Remove daemon file if exists''' if os.path.exists(daemonpath): os.remove(daemonpath) for kmod in kernelmods: cmd = check + "| grep " + kmod self.ch.executeCommand(cmd) if self.ch.getReturnCode() != 0: '''kernel mod is not loaded, load to make non-compliant''' cmd = load + " /System/Library/Extensions/" + kmod + ".kext" if not self.ch.executeCommand(cmd): debug = "Unable to load kernel module " + kmod + " for unit test\n" self.logdispatch.log(LogPriority.DEBUG, debug) success = False return success def setConditionsForLinux(self): '''Method to configure mac non compliant for unit test @author: dwalker :returns: boolean ''' success = True self.ph = Pkghelper(self.logger, self.environ) # check compliance of grub file(s) if files exist if re.search("Red Hat", self.environ.getostype()) and \ re.search("^6", self.environ.getosver()): self.grubperms = [0, 0, 0o600] elif self.ph.manager is "apt-get": self.grubperms = [0, 0, 0o400] else: self.grubperms = [0, 0, 0o644] grubfiles = ["/boot/grub2/grub.cfg", "/boot/grub/grub.cfg" "/boot/grub/grub.conf"] for grub in grubfiles: if os.path.exists(grub): if self.grubperms: if checkPerms(grub, self.grubperms, self.logger): if not setPerms(grub, [0, 0, 0o777], self.logger): success = False contents = readFile(grub, self.logger) if contents: for line in contents: if re.search("^kernel", line.strip()) or re.search("^linux", line.strip()) \ or re.search("^linux16", line.strip()): if re.search("\s+nousb\s*", line): if not re.sub("nousb", "", line): success = False if re.search("\s+usbcore\.authorized_default=0\s*", line): if not re.sub("usbcore\.authorized_default=0", "", line): success = False pcmcialist = ['pcmcia-cs', 'kernel-pcmcia-cs', 'pcmciautils'] # check for existence of certain usb packages, non-compliant # if any exist for item in pcmcialist: if not self.ph.check(item): self.ph.install(item) removeables = [] found1 = True blacklist = {"blacklist usb_storage": False, "install usbcore /bin/true": False, "install usb-storage /bin/true": False, "blacklist uas": False, "blacklist firewire-ohci": False, "blacklist firewire-sbp2": False} if os.path.exists("/etc/modprobe.d"): dirs = glob.glob("/etc/modprobe.d/*") for directory in dirs: if os.path.isdir(directory): continue tempstring = "" contents = readFile(directory, self.logger) for line in contents: if line.strip() in blacklist: continue else: tempstring += line if not writeFile(directory, tempstring, self.logger): success = False if os.path.exists("/etc/modprobe.conf"): contents = readFile("/etc/modprobe.conf", self.logger) tempstring = "" for line in contents: if line.strip() in blacklist: continue else: tempstring += line if not writeFile("/etc/modprobe.conf", tempstring, self.logger): success = False udevfile = "/etc/udev/rules.d/10-local.rules" if os.path.exists(udevfile): if checkPerms(udevfile, [0, 0, 0o644], self.logger): if not setPerms(udevfile, [0 ,0, 0o777], self.logger): success = False contents = readFile(udevfile, self.logger) tempstring = "" for line in contents: if re.search("ACTION\=\=\"add\"\, SUBSYSTEMS\=\=\"usb\"\, RUN\+\=\"/bin/sh \-c \'for host in /sys/bus/usb/devices/usb\*\; do echo 0 \> \$host/authorized\_default\; done\'\"", line.strip()): continue else: tempstring += line if not writeFile(udevfile, tempstring, self.logger): success = False return success def checkReportForRule(self, pCompliance, pRuleSuccess): '''check on whether report was correct :param self: essential if you override this definition :param pCompliance: the self.iscompliant value of rule :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + \ str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = True return success def checkFixForRule(self, pRuleSuccess): '''check on whether fix was correct :param self: essential if you override this definition :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = True return success def checkUndoForRule(self, pRuleSuccess): '''check on whether undo was correct :param self: essential if you override this definition :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = True return success
class zzzTestRuleAuditFirefoxUsage(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = AuditFirefoxUsage(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.ph = Pkghelper(self.logdispatch, self.environ) self.initMozDir = False self.moveMozDir = False self.mozPath = "/root/.mozilla/firefox" self.profilePath = "/root/.mozilla/firefox/profiles.ini" def tearDown(self): mozPath = self.mozPath if self.initMozDir and os.path.exists(mozPath): shutil.rmtree(mozPath) elif self.moveMozDir: if os.path.exists(mozPath): shutil.rmtree(mozPath) if os.path.exists(mozPath + ".stonixtmp"): os.rename(mozPath + ".stonixtmp", mozPath) def runTest(self): profilePath = self.profilePath if self.ph.check("firefox"): self.browser = "/usr/bin/firefox" self.setConditionsForRule() # setConditionsForRule will not work on a remote terminal. If the # path doesn't exist, we will skip the test. if os.path.exists(profilePath): self.assertFalse(self.rule.report(), "Report was not false " + "after test conditions were set") else: self.logdispatch.log(LogPriority.DEBUG, "Firefox directory was not created. " + "Skipping test.") elif self.ph.check("iceweasel"): self.browser = "/usr/bin/iceweasel" self.setConditionsForRule() # setConditionsForRule will not work on a remote terminal. If the # path doesn't exist, we will skip the test. if os.path.exists(profilePath): self.assertFalse(self.rule.report(), "Report was not false " + "after test conditions were set") else: self.logdispatch.log(LogPriority.DEBUG, "Firefox directory was not created. " + "Skipping test.") else: debug = "Firefox not installed. Unit test will not make " + \ "any changes." self.logdispatch.log(LogPriority.DEBUG, debug) return True def setConditionsForRule(self): ''' Configure system for the unit test @param self: essential if you override this definition @return: boolean - If successful True; If failure False @author: Eric Ball ''' success = True browser = self.browser mozPath = self.mozPath if not os.path.exists(mozPath): self.ch.wait = False command = [browser, "google.com"] self.ch.executeCommand(command) sleep(15) self.initMozDir = True else: self.ch.wait = False os.rename(mozPath, mozPath + ".stonixtmp") command = [browser, "google.com"] self.ch.executeCommand(command) sleep(15) self.moveMozDir = True command = ["/usr/bin/killall", "-q", "-u", "root", browser] self.ch.executeCommand(command) return success def checkReportForRule(self, pCompliance, pRuleSuccess): ''' check on whether report was correct @param self: essential if you override this definition @param pCompliance: the self.iscompliant value of rule @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkFixForRule(self, pRuleSuccess): ''' check on whether fix was correct @param self: essential if you override this definition @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkUndoForRule(self, pRuleSuccess): ''' check on whether undo was correct @param self: essential if you override this definition @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success
class zzzTestRuleAuditFirefoxUsage(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = AuditFirefoxUsage(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.ph = Pkghelper(self.logdispatch, self.environ) self.initMozDir = False self.moveMozDir = False self.mozPath = "/root/.mozilla/firefox" self.profilePath = "/root/.mozilla/firefox/profiles.ini" def tearDown(self): mozPath = self.mozPath if self.initMozDir and os.path.exists(mozPath): shutil.rmtree(mozPath) elif self.moveMozDir: if os.path.exists(mozPath): shutil.rmtree(mozPath) if os.path.exists(mozPath + ".stonixtmp"): os.rename(mozPath + ".stonixtmp", mozPath) def runTest(self): profilePath = self.profilePath if self.ph.check("firefox"): self.browser = "/usr/bin/firefox" self.setConditionsForRule() # setConditionsForRule will not work on a remote terminal. If the # path doesn't exist, we will skip the test. if os.path.exists(profilePath): self.assertFalse( self.rule.report(), "Report was not false " + "after test conditions were set") else: self.logdispatch.log( LogPriority.DEBUG, "Firefox directory was not created. " + "Skipping test.") elif self.ph.check("iceweasel"): self.browser = "/usr/bin/iceweasel" self.setConditionsForRule() # setConditionsForRule will not work on a remote terminal. If the # path doesn't exist, we will skip the test. if os.path.exists(profilePath): self.assertFalse( self.rule.report(), "Report was not false " + "after test conditions were set") else: self.logdispatch.log( LogPriority.DEBUG, "Firefox directory was not created. " + "Skipping test.") else: debug = "Firefox not installed. Unit test will not make " + \ "any changes." self.logdispatch.log(LogPriority.DEBUG, debug) return True def setConditionsForRule(self): '''Configure system for the unit test :param self: essential if you override this definition :returns: boolean - If successful True; If failure False @author: Eric Ball ''' success = True browser = self.browser mozPath = self.mozPath if not os.path.exists(mozPath): self.ch.wait = False command = [browser, "google.com"] self.ch.executeCommand(command) sleep(15) self.initMozDir = True else: self.ch.wait = False os.rename(mozPath, mozPath + ".stonixtmp") command = [browser, "google.com"] self.ch.executeCommand(command) sleep(15) self.moveMozDir = True command = ["/usr/bin/killall", "-q", "-u", "root", browser] self.ch.executeCommand(command) return success def checkReportForRule(self, pCompliance, pRuleSuccess): '''check on whether report was correct :param self: essential if you override this definition :param pCompliance: the self.iscompliant value of rule :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkFixForRule(self, pRuleSuccess): '''check on whether fix was correct :param self: essential if you override this definition :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkUndoForRule(self, pRuleSuccess): '''check on whether undo was correct :param self: essential if you override this definition :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success
class zzzTestRuleDisableIPV6(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = DisableIPV6(self.config, self.environ, self.logdispatch, self.statechglogger) self.logger = self.logdispatch self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.checkUndo = True def tearDown(self): pass def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): '''Configure system for the unit test :param self: essential if you override this definition :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' success = True if self.environ.getosfamily() == "linux": success = self.setLinuxConditions() elif self.environ.getosfamily() == "darwin": success = self.setMacConditions() return success def setLinuxConditions(self): success = True self.ph = Pkghelper(self.logger, self.environ) if not self.messupNetconfigFile(): success = False if not self.messupSysctl(): success = False if not self.messupModprobeFiles(): success = False if not self.messupInterfaceFile(): success = False if self.ph.manager == "apt-get": if not self.messupSSHDFile(): success = False return success def setMacConditions(self): success = True debug = "" networksetup = "/usr/sbin/networksetup" listnetworkservices = networksetup + " -listallnetworkservices" ipv6status = "^IPv6:\s+On" getinfo = networksetup + " -getinfo" self.ch.executeCommand(listnetworkservices) retcode = self.ch.getReturnCode() if retcode != 0: success = False debug = "Failed to get list of network services" self.logger.log(LogPriority.DEBUG, debug) else: networkservices = self.ch.getOutput() for ns in networkservices: # ignore non-network service output lines if re.search("denotes that", ns, re.IGNORECASE): continue else: self.ch.executeCommand(networksetup + ' -setv6automatic ' + '"' + ns + '"') retcode = self.ch.getReturnCode() if retcode != 0: success = False debug = "Failed to get information for network service: " + ns self.logger.log(LogPriority.DEBUG, debug) return success def messupNetconfigFile(self): success = True # stig portion, check netconfig file for correct contents if self.ph.manager == "apt-get": nfspkg = "nfs-common" else: nfspkg = "nfs-utils.x86_64" if self.ph.check(nfspkg): if not self.ph.remove(nfspkg): success = False debug = "Unable to remove nfs package for preconditions" self.logger.log(LogPriority.DEBUG, debug) if os.path.exists("/etc/netconfig"): item1 = "udp6 tpi_clts v inet6 udp - -" item2 = "tcp6 tpi_cots_ord v inet6 tcp - -" item1found, item2found, fixFile = False, False, False writestring = "" contents = readFile("/etc/netconfig", self.logger) for line in contents: writestring += line line = re.sub("\s+", " ", line.strip()) if re.search(item1, line): item1found = True if re.search(item2, line): item2found = True if not item1found: writestring += item1 fixFile = True if not item2found: writestring += item2 fixFile = True if fixFile: if not writeFile("/etc/netconfig", writestring, self.logger): success = False debug = "Unable tomess up /etc/netconfig file for preconditions" self.logger.log(LogPriority.DEBUG, debug) return success def messupSysctl(self): success = True sysctlcmd = "" sysctl = "/etc/sysctl.conf" directives = [ "net.ipv6.conf.all.disable_ipv6=0", "net.ipv6.conf.default.disable_ipv6=0" ] filedirectives = { "net.ipv6.conf.all.disable_ipv6": "0", "net.ipv6.conf.default.disable_ipv6": "0" } tmpfile = sysctl + ".tmp" if os.path.exists(sysctl): editor = KVEditorStonix(self.statechglogger, self.logger, "conf", sysctl, tmpfile, filedirectives, "present", "openeq") if not editor.report(): if not editor.fix(): success = False debug = "Unable to mess up " + sysctl + " file for preconditions" self.logger.log(LogPriority.DEBUG, debug) elif not editor.commit(): success = False debug = "Unable to mess up " + sysctl + " file for preconditions" self.logger.log(LogPriority.DEBUG, debug) sysctllocs = ["/sbin/sysctl", "/usr/sbin/sysctl"] for loc in sysctllocs: if os.path.exists(loc): sysctlcmd = loc if sysctlcmd: for d in directives: setbadopt = sysctlcmd + " -w " + d self.ch.executeCommand(setbadopt) retcode = self.ch.getReturnCode() if retcode != 0: success = False debug = "Failed to write configuration change: " + d + "\n" self.logger.log(LogPriority.DEBUG, debug) else: debug = "sysctl command not found on system\n" self.logger.log(LogPriority.DEBUG, debug) success = False return success def messupModprobeFiles(self): success = True modprobes = { "options": "ipv6 disable=1", "install": "ipv6 /bin/true", "helloworld": "" } if os.path.exists("/etc/modprobe.d/"): modprobefiles = glob.glob("/etc/modprobe.d/*") for modfile in modprobefiles: tmpfile = modfile + ".tmp" editor = KVEditorStonix(self.statechglogger, self.logger, "conf", modfile, tmpfile, modprobes, "notpresent", "space") if not editor.report(): if not editor.fix(): success = False debug = "Unable to mess up " + modfile + " file for preconditions" self.logger.log(LogPriority.DEBUG, debug) elif not editor.commit(): success = False debug = "Unable to mess up " + modfile + " file for preconditions" self.logger.log(LogPriority.DEBUG, debug) return success def messupInterfaceFile(self): success = True interface = {"IPV6INIT": '"yes"', "NETWORKING_IPV6": '"yes"'} # Check for existence of interface and network files to be configured if self.ph.manager == "yum": ifacefile = "/etc/sysconfig/network-scripts/" if not os.path.exists(ifacefile): ifacefile = "" netwrkfile = "/etc/sysconfig/network" if not os.path.exists(netwrkfile): netwrkfile = "" elif self.ph.manager == "zypper": ifacefile = "/etc/sysconfig/network/" if not os.path.exists(ifacefile): ifacefile = "" if ifacefile: dirs = glob.glob(ifacefile + "*") for loc in dirs: contents = [] if re.search('^' + ifacefile + 'ifcfg', loc): tmpfile = loc + ".tmp" editor = KVEditorStonix(self.statechglogger, self.logger, "conf", loc, tmpfile, interface, "present", "closedeq") if not editor.report(): if not editor.fix(): success = False debug = "Unable to mess up " + loc + " file for preconditions" self.logger.log(LogPriority.DEBUG, debug) elif not editor.commit(): success = False debug = "Unable to mess up " + loc + " file for preconditions" self.logger.log(LogPriority.DEBUG, debug) return success def messupSSHDFile(self): success = True sshfile = "/etc/ssh/sshd_config" if os.path.exists(sshfile): tmpfile = sshfile + ".tmp" data = {"AddressFamily": "inet"} editor = KVEditorStonix(self.statechglogger, self.logger, "conf", sshfile, tmpfile, data, "notpresent", "space") if not editor.report(): if not editor.fix(): success = False debug = "Unable to mess up " + sshfile + " file for preconditions" self.logger.log(LogPriority.DEBUG, debug) elif not editor.commit(): success = False debug = "Unable to mess up " + sshfile + " file for preconditions" self.logger.log(LogPriority.DEBUG, debug) return success def checkReportForRule(self, pCompliance, pRuleSuccess): '''check on whether report was correct :param self: essential if you override this definition :param pCompliance: the self.iscompliant value of rule :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + \ str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = True return success def checkFixForRule(self, pRuleSuccess): '''check on whether fix was correct :param self: essential if you override this definition :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = True return success def checkUndoForRule(self, pRuleSuccess): '''check on whether undo was correct :param self: essential if you override this definition :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = True return success
class zzzTestRuleSystemAccounting(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = SystemAccounting(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.ph = Pkghelper(self.logdispatch, self.environ) self.rule.ci.updatecurrvalue(True) def tearDown(self): pass def runTest(self): result = self.simpleRuleTest() self.assertTrue( result, "SystemAccounting(9): rule.iscompliant() is " + "'False' after rule.fix() and rule.report() have " + "run. This may be due to a proxy error; if the " + "proper proxy is not set in localize.py, set it and " + "run this test again.") def test_default_sysstat_empty(self): """ test correction of /etc/default/sysstat if it has no entry in it :return: """ file = "/etc/default/sysstat" backup = "/etc/default/sysstat.stonix_test_bak" if os.path.isfile(file): self._backup_file(file) f = open(file, "w") f.write("") f.close() self.rule._set_paths() self.assertFalse(self.rule._report_configuration()) self.rule._fix_configuration() self.assertTrue(self.rule._report_configuration()) self._restore_file(backup) else: return True def test_default_sysstat_comment(self): """ test correction of /etc/default/sysstat if it has the entry commented out :return: """ file = "/etc/default/sysstat" backup = "/etc/default/sysstat.stonix_test_bak" if os.path.isfile(file): self._backup_file(file) f = open(file, "w") f.write('# ENABLED="true"') f.close() self.rule._set_paths() self.assertFalse(self.rule._report_configuration()) self.rule._fix_configuration() self.assertTrue(self.rule._report_configuration()) self._restore_file(backup) else: return True def test_default_sysstat_wrongvalue(self): """ test correction of /etc/default/sysstat if it has the entry set to the wrong value :return: """ file = "/etc/default/sysstat" backup = "/etc/default/sysstat.stonix_test_bak" if os.path.isfile(file): self._backup_file(file) f = open(file, "w") f.write('ENABLED="false"') f.close() self.rule._set_paths() self.assertFalse(self.rule._report_configuration()) self.rule._fix_configuration() self.assertTrue(self.rule._report_configuration()) self._restore_file(backup) else: return True def test_default_sysstat_rightvalue(self): """ test correction of /etc/default/sysstat if it has the entry set to the right value :return: """ file = "/etc/default/sysstat" backup = "/etc/default/sysstat.stonix_test_bak" if os.path.isfile(file): self._backup_file(file) f = open(file, "w") f.write('ENABLED="true"') f.close() self.rule._set_paths() self.assertTrue(self.rule._report_configuration()) self.rule._fix_configuration() self.assertTrue(self.rule._report_configuration()) self._restore_file(backup) else: return True def test_installation_installed(self): """ test installation report/fix if package already installed applies to Linux only :return: """ if self.rule.ostype == "Mac OS X": return True package = "sysstat" if self.ph.check(package): self.rule._set_paths() self.assertTrue(self.rule._report_installation()) self.rule._fix_installation() self.assertTrue(self.rule._report_installation()) else: return True def test_installation_missing(self): """ test installation report/fix if package not installed applies to Linux only :return: """ if self.rule.ostype == "Mac OS X": return True package = "sysstat" if not self.ph.check(package): self.rule._set_paths() self.assertFalse(self.rule._report_installation()) self.rule._fix_installation() self.assertTrue(self.rule._report_installation()) else: return True def test_set_paths(self): """ test that all paths and necessary variables for the class are able to be properly determined and set once package is installed :return: """ package = "sysstat" self.ph.install(package) self.rule._set_paths() self.assertTrue(self.rule.sysstat_package) self.assertTrue(self.rule.sysstat_service_file) self.assertTrue(self.rule.sa1) self.assertTrue(self.rule.sa2) self.assertTrue(self.rule.sysstat_service_contents) self.assertTrue(self.rule.sysstat_cron_contents) self.assertTrue(self.rule.ostype) self.ph.remove(package) def _restore_file(self, backup): """ :param backup: :return: """ if os.path.isfile(backup): if re.search("\.stonix_test_bak", backup): shutil.copy2(backup, backup.replace(".stonix_test_bak", "")) def _backup_file(self, original): """ :param original: :return: """ if os.path.isfile(original): shutil.copy2(original, original + ".stonix_test_bak") def setConditionsForRule(self): """Configure system for the unit test :param self: essential if you override this definition :returns: boolean - If successful True; If failure False @author: Breen Malmberg """ success = True self.rule.ci.updatecurrvalue(True) return success def checkReportForRule(self, pCompliance, pRuleSuccess): """check on whether report was correct :param self: essential if you override this definition :param pCompliance: the self.iscompliant value of rule :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: Breen Malmberg """ self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkFixForRule(self, pRuleSuccess): """check on whether fix was correct :param self: essential if you override this definition :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: Breen Malmberg """ self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkUndoForRule(self, pRuleSuccess): """check on whether undo was correct :param self: essential if you override this definition :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: Breen Malmberg """ self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success
class zzzTestRuleDisableUbuntuDataCollection(RuleTest): def setUp(self): ''' @return: None @author: ekkehard j. koch, Breen Malmberg ''' RuleTest.setUp(self) self.rule = DisableUbuntuDataCollection(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ph = Pkghelper(self.logdispatch, self.environ) self.datacollectionpkgs = ["popularity-contest", "apport", "ubuntu-report"] self.teardownpkgs = [] def tearDown(self): ''' @return: None ''' for pkg in self.teardownpkgs: self.ph.remove(pkg) self.teardownpkgs.remove(pkg) def runTest(self): ''' @return: None ''' self.simpleRuleTest() def setConditionsForRule(self): ''' Configure system for the unit test @return: success @rtype: bool @author: ekkehard j. koch, Breen Malmberg ''' success = True self.rule.enabledCI.updatecurrvalue(True) for pkg in self.datacollectionpkgs: if not self.ph.check(pkg): self.ph.install(pkg) self.teardownpkgs.append(pkg) return success def checkReportForRule(self, pCompliance, pRuleSuccess): ''' check on whether report was correct @param pCompliance: the self.iscompliant value of rule @param pRuleSuccess: did report run successfully @return: success @rtype: bool @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkFixForRule(self, pRuleSuccess): ''' check on whether fix was correct @param pRuleSuccess: did report run successfully @return: success @rtype: bool @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkUndoForRule(self, pRuleSuccess): ''' check on whether undo was correct @param pRuleSuccess: did report run successfully @return: success @rtype: bool @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success
class zzzTestRuleRestrictMounting(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = RestrictMounting(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.ph = Pkghelper(self.logdispatch, self.environ) self.sh = ServiceHelper(self.environ, self.logdispatch) def tearDown(self): pass def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): ''' Configure system for the unit test @param self: essential if you override this definition @return: boolean - If successful True; If failure False @author: Eric Ball ''' success = True # Enable CIs datatype = "bool" key = "RESTRICTCONSOLEACCESS" instructions = "Unit test" default = True self.rule.consoleCi = self.rule.initCi(datatype, key, instructions, default) key = "DISABLEAUTOFS" self.rule.autofsCi = self.rule.initCi(datatype, key, instructions, default) key = "DISABLEGNOMEAUTOMOUNT" self.rule.gnomeCi = self.rule.initCi(datatype, key, instructions, default) self.path1 = "/etc/security/console.perms.d/50-default.perms" self.path2 = "/etc/security/console.perms" self.data1 = [ "<floppy>=/dev/fd[0-1]* \\", "<scanner>=/dev/scanner* /dev/usb/scanner*", "<flash>=/mnt/flash* /dev/flash*", "# permission definitions", "<console> 0660 <floppy> 0660 root.floppy", "<console> 0600 <scanner> 0600 root", "<console> 0600 <flash> 0600 root.disk" ] self.data2 = [ "<console>=tty[0-9][0-9]* vc/[0-9][0-9]* :[0-9]+\.[0-9]+ :[0-9]+", "<xconsole>=:[0-9]+\.[0-9]+ :[0-9]+" ] if os.path.exists(self.path1): self.tmpfile1 = self.path1 + ".tmp" os.rename(self.path1, self.tmpfile1) try: defaultPermsFile = open(self.path1, "w") except IOError: debug = "Could not open file " + self.path1 + "\n" self.logger.log(LogPriority.DEBUG, debug) success = False try: defaultPermsFile.writelines(self.data1) except IOError: debug = "Could not write to file " + self.path1 + "\n" self.logger.log(LogPriority.DEBUG, debug) success = False if os.path.exists(self.path2): self.tmpfile2 = self.path2 + ".tmp" os.rename(self.path2, self.tmpfile2) try: permsFile = open(self.path2, "w") except IOError: debug = "Could not open file " + self.path2 + "\n" self.logger.log(LogPriority.DEBUG, debug) success = False try: permsFile.writelines(self.data2) except IOError: debug = "Could not write to file " + self.path2 + "\n" self.logger.log(LogPriority.DEBUG, debug) success = False # If autofs is installed, enable and start it. If it is not # installed, it will not be tested. if self.ph.check("autofs"): if not self.sh.enableservice("autofs"): debug = "Could not enable autofs\n" self.logger.log(LogPriority.DEBUG, debug) success = False cmd = [ "gconftool-2", "--direct", "--config-source", "xml:readwrite:/etc/gconf/gconf.xml.mandatory", "--type", "bool", "--set", "/desktop/gnome/volume_manager/automount_media", "true" ] cmdSuccess = self.ch.executeCommand(cmd) cmd = [ "gconftool-2", "--direct", "--config-source", "xml:readwrite:/etc/gconf/gconf.xml.mandatory", "--type", "bool", "--set", "/desktop/gnome/volume_manager/automount_drives", "true" ] cmdSuccess &= self.ch.executeCommand(cmd) if not cmdSuccess: success = False return success def checkReportForRule(self, pCompliance, pRuleSuccess): ''' check on whether report was correct @param self: essential if you override this definition @param pCompliance: the self.iscompliant value of rule @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkFixForRule(self, pRuleSuccess): ''' check on whether fix was correct @param self: essential if you override this definition @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' # Cleanup: put original perms files back if os.path.exists(self.path1) and os.path.exists(self.tmpfile1): os.remove(self.path1) os.rename(self.tmpfile1, self.path1) if os.path.exists(self.path2) and os.path.exists(self.tmpfile2): os.remove(self.path2) os.rename(self.tmpfile2, self.path2) self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkUndoForRule(self, pRuleSuccess): ''' check on whether undo was correct @param self: essential if you override this definition @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success
def setConditionsForRule(self): '''Configure system for the unit test :param self: essential if you override this definition :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' success = True if self.environ.getosfamily() == "darwin": success = False osxversion = str(self.environ.getosver()) if osxversion.startswith("10.10.0") or \ osxversion.startswith("10.10.1") or \ osxversion.startswith("10.10.2") or \ osxversion.startswith("10.10.3"): debug = "Using discoveryd LaunchDaemon" self.logdispatch.log(LogPriority.DEBUG, debug) service = \ "/System/Library/LaunchDaemons/com.apple.discoveryd.plist" servicename = "com.apple.networking.discoveryd" parameter = "--no-multicast" plistText = readFile(service, self.logdispatch) newPlistText = re.sub("<string>" + parameter + "</string>", "", "".join(plistText)) success = True else: debug = "Using mDNSResponder LaunchDaemon" self.logdispatch.log(LogPriority.DEBUG, debug) service = "/System/Library/LaunchDaemons/" + \ "com.apple.mDNSResponder.plist" if osxversion.startswith("10.10"): servicename = "com.apple.mDNSResponder.reloaded" parameter = "-NoMulticastAdvertisements" else: servicename = "com.apple.mDNSResponder" parameter = "-NoMulticastAdvertisements" plistText = readFile(service, self.logdispatch) newPlistText = re.sub("<string>" + parameter + "</string>", "", "".join(plistText)) success = True self.service = service if success and self.sh.auditService(service, serviceTarget=servicename): success = writeFile(service + ".stonixtmp", "".join(plistText), self.logdispatch) success = writeFile(service, newPlistText, self.logdispatch) if success and self.sh.auditService(service, serviceTarget=servicename): success = self.sh.reloadService(service, serviceTarget=servicename) else: ph = Pkghelper(self.logdispatch, self.environ) package = "avahi-daemon" service = "avahi-daemon" if (ph.determineMgr() == "yum" or ph.determineMgr() == "dnf"): package = "avahi" path = "/etc/sysconfig/network" if os.path.exists(path): tmppath = path + ".tmp" data = {"NOZEROCONF": "yes"} editor = KVEditorStonix(self.statechglogger, self.logdispatch, "conf", path, tmppath, data, "notpresent", "closedeq") if not editor.report(): if editor.fix(): if not editor.commit(): success = False else: success = False elif ph.determineMgr() == "zypper": package = "avahi" if not ph.check(package) and ph.checkAvailable(package): success = ph.install(package) if success and not self.sh.auditService( service, serviceTarget=self.serviceTarget): self.sh.enableService(service, serviceTarget=self.serviceTarget) return success
class zzzTestRuleDisablePrelinking(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = DisablePrelinking(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.ph = Pkghelper(self.logdispatch, self.environ) self.prelinkInstalled = False def tearDown(self): if not self.prelinkInstalled: self.ph.remove("prelink") def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): ''' Configure system for the unit test @param self: essential if you override this definition @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' success = True if self.ph.check("prelink"): self.prelinkInstalled = True elif self.ph.checkAvailable("prelink"): self.ph.install("prelink") else: return True path = "/usr/sbin/prelink" cmd = [path, "/bin/ls"] if os.path.exists(path): self.ch.executeCommand(cmd) if re.search("debian|ubuntu", self.environ.getostype().lower()): path = "/etc/default/prelink" else: path = "/etc/sysconfig/prelink" if os.path.exists(path): tmppath = path + ".tmp" data = {"PRELINKING": "yes"} self.editor = KVEditorStonix(self.statechglogger, self.logdispatch, "conf", path, tmppath, data, "present", "closedeq") if not self.editor.report(): if self.editor.fix(): if not self.editor.commit(): success = False self.logdispatch.log(LogPriority.ERROR, "KVEditor failed to commit.") else: success = False self.logdispatch.log(LogPriority.ERROR, "KVEditor failed to fix.") else: writeFile(path, "PRELINKING=yes", self.logdispatch) return success def checkReportForRule(self, pCompliance, pRuleSuccess): ''' check on whether report was correct @param self: essential if you override this definition @param pCompliance: the self.iscompliant value of rule @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkFixForRule(self, pRuleSuccess): ''' check on whether fix was correct @param self: essential if you override this definition @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkUndoForRule(self, pRuleSuccess): ''' check on whether undo was correct @param self: essential if you override this definition @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success
class zzzTestRuleSecureMTA(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = SecureMTA(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.logger = self.logdispatch self.ch = CommandHelper(self.logdispatch) if self.environ.operatingsystem == "Mac OS X": self.isMac = True else: self.isMac = False def tearDown(self): pass # if not self.isMac: # if self.origState[0] is True and not self.ph.check("sendmail"): # self.ph.install("sendmail") # elif self.origState[0] is False and self.ph.check("sendmail"): # self.ph.remove("sendmail") # # if self.origState[1] is True and not self.ph.check(self.postfixpkg): # self.ph.install(self.postfixpkg) # elif self.origState[1] is False and self.ph.check(self.postfixpkg): # self.ph.remove(self.postfixpkg) # # if self.origState[2] is True and os.path.exists(self.smTmp): # smDir = os.path.split(self.smPath)[0] # if not os.path.exists(smDir): # os.makedirs(smDir) # os.rename(self.smTmp, self.smPath) # elif self.origState[2] is False and os.path.exists(self.smPath): # os.remove(self.smPath) # # if self.origState[3] is True and os.path.exists(self.pfTmp): # pfDir = os.path.split(self.pfPath)[0] # if not os.path.exists(pfDir): # os.makedirs(pfDir) # os.rename(self.pfTmp, self.pfPath) # elif self.origState[3] is False and os.path.exists(self.pfPath): # os.remove(self.pfPath) def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): ''' Configure system for the unit test @param self: essential if you override this definition @return: boolean - If successful True; If failure False @author: dwalker ''' success = True pfdata = {'inet_interfaces': 'localhost', 'default_process_limit': '100', 'smtpd_client_connection_count_limit': '10', 'smtpd_client_connection_rate_limit': '30', 'queue_minfree': '20971520', 'header_size_limit': '51200', 'message_size_limit': '10485760', 'smtpd_recipient_limit': '100', 'smtpd_banner': '$myhostname ESMTP', 'mynetworks_style': 'host', 'smtpd_recipient_restrictions': 'permit_mynetworks, reject_unauth_destination', 'relayhost': MAILRELAYSERVER} if not self.isMac: smdata = {"O SmtpGreetingMessage": "", "O PrivacyOptions": "goaway"} self.ph = Pkghelper(self.logdispatch, self.environ) self.origState = [False, False, False, False] self.smPath = "/etc/mail/sendmail.cf" self.smTmp = self.smPath + ".stonixUT" self.pfPathlist = ['/etc/postfix/main.cf', '/usr/lib/postfix/main.cf'] self.postfixpkg = "postfix" self.pfPath = "" for path in self.pfPathlist: if os.path.exists(path): self.pfPath = path break self.pfTmp = self.pfPath + ".stonixUT" #if postfix file exists, remove any correct contents if self.pfPath: self.postfixed = KVEditorStonix(self.statechglogger, self.logger, "conf", self.pfPath, self.pfTmp, pfdata, "notpresent", "openeq") if not self.postfixed.report(): if self.postfixed.removeables: print "kveditor has removeables\n" if not self.postfixed.fix(): success = False if os.path.exists(self.smPath): self.sndmailed = KVEditorStonix(self.statechglogger, self.logger, "conf", self.smPath, self.smTmp, smdata, "notpresent", "closedeq") if not self.sndmailed.report(): if self.postfixed.removeables: if not self.postfixed.fix(): success = False #remove postfix if installed if self.ph.check("postfix"): if not self.ph.remove("postfix"): success = False #remove sendmail if installed if not self.ph.checkAvailable("postfix"): if self.ph.check("sendmail"): if not self.ph.remove("sendmail"): success = False else: self.pfPath = "/private/etc/postfix/main.cf" self.pfTmp = self.pfPath + ".stonixUT" if os.path.exists(self.pfPath): self.postfixed = KVEditorStonix(self.statechglogger, self.logger, "conf", self.pfPath, self.pfTmp, pfdata, "notpresent", "openeq") if not self.postfixed.report(): if self.postfixed.removeables: if not self.postfixed.fix(): success = False # if self.ph.check("sendmail"): # self.origState[0] = True # if self.ph.check(self.postfixpkg): # self.origState[1] = True # if os.path.exists(self.smPath): # self.origState[2] = True # os.rename(self.smPath, self.smTmp) # if os.path.exists(self.pfPath): # self.origState[3] = True # os.rename(self.pfPath, self.pfTmp) return success # def testFalseFalseFalseFalse(self): # if not self.isMac: # if self.ph.check("sendmail"): # self.ph.remove("sendmail") # if self.ph.check(self.postfixpkg): # self.ph.remove(self.postfixpkg) # if os.path.exists(self.smPath): # os.remove(self.smPath) # if os.path.exists(self.pfPath): # os.remove(self.pfPath) # self.simpleRuleTest() # # def testTrueFalseFalseFalse(self): # if not self.isMac: # if not self.ph.check("sendmail"): # self.ph.install("sendmail") # if self.ph.check(self.postfixpkg): # self.ph.remove(self.postfixpkg) # if os.path.exists(self.smPath): # os.remove(self.smPath) # if os.path.exists(self.pfPath): # os.remove(self.pfPath) # self.simpleRuleTest() # # def testTrueTrueFalseFalse(self): # if not self.isMac: # if not self.ph.check("sendmail"): # self.ph.install("sendmail") # if not self.ph.check(self.postfixpkg): # self.ph.install(self.postfixpkg) # if os.path.exists(self.smPath): # os.remove(self.smPath) # if os.path.exists(self.pfPath): # os.remove(self.pfPath) # self.simpleRuleTest() # # def testTrueTrueTrueFalse(self): # if not self.isMac: # if not self.ph.check("sendmail"): # self.ph.install("sendmail") # if not self.ph.check(self.postfixpkg): # self.ph.install(self.postfixpkg) # if not os.path.exists(self.smPath): # splitpath = self.smPath.split('/') # del splitpath[-1] # subdir = "/".join(splitpath) # if not os.path.exists(subdir): # os.makedirs(subdir, 0755) # open(self.smPath, "w") # if os.path.exists(self.pfPath): # os.remove(self.pfPath) # self.simpleRuleTest() # # def testTrueTrueTrueTrue(self): # if not self.isMac: # if not self.ph.check("sendmail"): # self.ph.install("sendmail") # if not self.ph.check(self.postfixpkg): # self.ph.install(self.postfixpkg) # if not os.path.exists(self.smPath): # splitpath = self.smPath.split('/') # del splitpath[-1] # subdir = "/".join(splitpath) # if not os.path.exists(subdir): # os.makedirs(subdir, 0755) # open(self.smPath, "w") # if not os.path.exists(self.pfPath): # splitpath = self.pfPath.split('/') # del splitpath[-1] # subdir = "/".join(splitpath) # if not os.path.exists(subdir): # os.makedirs(subdir, 0755) # open(self.pfPath, "w") # self.simpleRuleTest() # # def testTrueFalseTrueFalse(self): # if not self.isMac: # if not self.ph.check("sendmail"): # self.ph.install("sendmail") # if self.ph.check(self.postfixpkg): # self.ph.remove(self.postfixpkg) # if not os.path.exists(self.smPath): # splitpath = self.smPath.split('/') # del splitpath[-1] # subdir = "/".join(splitpath) # if not os.path.exists(subdir): # os.makedirs(subdir, 0755) # open(self.smPath, "w") # if os.path.exists(self.pfPath): # os.remove(self.pfPath) # self.simpleRuleTest() # # def testFalseTrueFalseFalse(self): # if not self.isMac: # if self.ph.check("sendmail"): # self.ph.remove("sendmail") # if not self.ph.check(self.postfixpkg): # self.ph.install(self.postfixpkg) # if os.path.exists(self.smPath): # os.remove(self.smPath) # if os.path.exists(self.pfPath): # os.remove(self.pfPath) # self.simpleRuleTest() # # def testFalseTrueFalseTrue(self): # if not self.isMac: # if self.ph.check("sendmail"): # self.ph.remove("sendmail") # if not self.ph.check(self.postfixpkg): # self.ph.install(self.postfixpkg) # if os.path.exists(self.smPath): # os.remove(self.smPath) # if not os.path.exists(self.pfPath): # splitpath = self.pfPath.split('/') # del splitpath[-1] # subdir = "/".join(splitpath) # if not os.path.exists(subdir): # os.makedirs(subdir, 0755) # open(self.pfPath, "w") # self.simpleRuleTest() def checkReportForRule(self, pCompliance, pRuleSuccess): ''' check on whether report was correct @param self: essential if you override this definition @param pCompliance: the self.iscompliant value of rule @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkFixForRule(self, pRuleSuccess): ''' check on whether fix was correct @param self: essential if you override this definition @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkUndoForRule(self, pRuleSuccess): ''' check on whether undo was correct @param self: essential if you override this definition @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success
class zzzTestRuleRemoveSoftware(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = RemoveSoftware(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.ph = Pkghelper(self.logdispatch, self.environ) self.checkUndo = True def tearDown(self): for pkg in self.installed: self.ph.install(pkg) def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): '''Configure system for the unit test :param self: essential if you override this definition :returns: boolean - If successful True; If failure False @author: dwalker ''' success = True self.rule.ci.updatecurrvalue(True) self.installed = [] default = [ "squid", "telnet-server", "rsh-server", "rsh", "rsh-client", "talk", "talk-server", "talkd", "tftp-server", "tftp", "tftpd" ] for pkg in default: if not self.ph.check(pkg) and self.ph.checkAvailable(pkg): self.ph.install(pkg) elif self.ph.check(pkg) and self.ph.checkAvailable(pkg): self.installed.append(pkg) return success def checkReportForRule(self, pCompliance, pRuleSuccess): '''check on whether report was correct :param self: essential if you override this definition :param pCompliance: the self.iscompliant value of rule :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: dwalker ''' self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkFixForRule(self, pRuleSuccess): '''check on whether fix was correct :param self: essential if you override this definition :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: dwalker ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkUndoForRule(self, pRuleSuccess): '''check on whether undo was correct :param self: essential if you override this definition :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: dwalker ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success
class zzzTestRuleDisableRemoveableStorage(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = DisableRemoveableStorage(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.rule.storageci.updatecurrvalue(True) self.logger = self.logdispatch self.ignoreresults = True def tearDown(self): pass def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): ''' Configure system for the unit test @param self: essential if you override this definition @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' success = True if self.environ.getostype() == "Mac OS X": success = self.setConditionsForMac() else: success = self.setConditionsForLinux() return success def setConditionsForMac(self): ''' Method to configure mac non compliant for unit test @author: dwalker @return: boolean ''' success = True daemonpath = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]))) + "/src/stonix_resources/disablestorage" plistpath = "/Library/LaunchDaemons/gov.lanl.stonix.disablestorage.plist" self.rule.daemonpath = daemonpath if re.search("^10.11", self.environ.getosver()): usb = "IOUSBMassStorageDriver" else: usb = "IOUSBMassStorageClass" kernelmods = [usb, "IOFireWireFamily", "AppleThunderboltUTDM", "AppleSDXC"] check = "/usr/sbin/kextstat" load = "/sbin/kextload" '''Remove plist file for launch job if exists''' if os.path.exists(plistpath): os.remove(plistpath) '''Remove daemon file if exists''' if os.path.exists(daemonpath): os.remove(daemonpath) for kmod in kernelmods: cmd = check + "| grep " + kmod self.ch.executeCommand(cmd) if self.ch.getReturnCode() != 0: '''kernel mod is not loaded, load to make non-compliant''' cmd = load + " /System/Library/Extensions/" + kmod + ".kext" if not self.ch.executeCommand(cmd): debug = "Unable to load kernel module " + kmod + " for unit test\n" self.logdispatch.log(LogPriority.DEBUG, debug) success = False return success def setConditionsForLinux(self): ''' Method to configure mac non compliant for unit test @author: dwalker @return: boolean ''' success = True self.ph = Pkghelper(self.logger, self.environ) # check compliance of grub file(s) if files exist if re.search("Red Hat", self.environ.getostype()) and \ re.search("^6", self.environ.getosver()): self.grubperms = [0, 0, 0o600] elif self.ph.manager is "apt-get": self.grubperms = [0, 0, 0o400] else: self.grubperms = [0, 0, 0o644] grubfiles = ["/boot/grub2/grub.cfg", "/boot/grub/grub.cfg" "/boot/grub/grub.conf"] for grub in grubfiles: if os.path.exists(grub): if self.grubperms: if checkPerms(grub, self.grubperms, self.logger): if not setPerms(grub, [0, 0, 0o777], self.logger): success = False contents = readFile(grub, self.logger) if contents: for line in contents: if re.search("^kernel", line.strip()) or re.search("^linux", line.strip()) \ or re.search("^linux16", line.strip()): if re.search("\s+nousb\s*", line): if not re.sub("nousb", "", line): success = False if re.search("\s+usbcore\.authorized_default=0\s*", line): if not re.sub("usbcore\.authorized_default=0", "", line): success = False pcmcialist = ['pcmcia-cs', 'kernel-pcmcia-cs', 'pcmciautils'] # check for existence of certain usb packages, non-compliant # if any exist for item in pcmcialist: if not self.ph.check(item): self.ph.install(item) removeables = [] found1 = True blacklist = {"blacklist usb_storage": False, "install usbcore /bin/true": False, "install usb-storage /bin/true": False, "blacklist uas": False, "blacklist firewire-ohci": False, "blacklist firewire-sbp2": False} if os.path.exists("/etc/modprobe.d"): dirs = glob.glob("/etc/modprobe.d/*") for directory in dirs: if os.path.isdir(directory): continue tempstring = "" contents = readFile(directory, self.logger) for line in contents: if line.strip() in blacklist: continue else: tempstring += line if not writeFile(directory, tempstring, self.logger): success = False if os.path.exists("/etc/modprobe.conf"): contents = readFile("/etc/modprobe.conf", self.logger) tempstring = "" for line in contents: if line.strip() in blacklist: continue else: tempstring += line if not writeFile("/etc/modprobe.conf", tempstring, self.logger): success = False udevfile = "/etc/udev/rules.d/10-local.rules" if os.path.exists(udevfile): if checkPerms(udevfile, [0, 0, 0o644], self.logger): if not setPerms(udevfile, [0 ,0, 0o777], self.logger): success = False contents = readFile(udevfile, self.logger) tempstring = "" for line in contents: if re.search("ACTION\=\=\"add\"\, SUBSYSTEMS\=\=\"usb\"\, RUN\+\=\"/bin/sh \-c \'for host in /sys/bus/usb/devices/usb\*\; do echo 0 \> \$host/authorized\_default\; done\'\"", line.strip()): continue else: tempstring += line if not writeFile(udevfile, tempstring, self.logger): success = False return success def checkReportForRule(self, pCompliance, pRuleSuccess): ''' check on whether report was correct @param self: essential if you override this definition @param pCompliance: the self.iscompliant value of rule @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + \ str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = True return success def checkFixForRule(self, pRuleSuccess): ''' check on whether fix was correct @param self: essential if you override this definition @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = True return success def checkUndoForRule(self, pRuleSuccess): ''' check on whether undo was correct @param self: essential if you override this definition @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = True return success
class zzzTestRuleRemoveSoftware(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = RemoveSoftware(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.ph = Pkghelper(self.logdispatch, self.environ) self.checkUndo = True def tearDown(self): for pkg in self.installed: self.ph.install(pkg) def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): ''' Configure system for the unit test @param self: essential if you override this definition @return: boolean - If successful True; If failure False @author: dwalker ''' success = True self.rule.ci.updatecurrvalue(True) self.installed = [] default = ["squid", "telnet-server", "rsh-server", "rsh", "rsh-client", "talk", "talk-server", "talkd", "tftp-server", "tftp", "tftpd"] for pkg in default: if not self.ph.check(pkg) and self.ph.checkAvailable(pkg): self.ph.install(pkg) elif self.ph.check(pkg) and self.ph.checkAvailable(pkg): self.installed.append(pkg) return success def checkReportForRule(self, pCompliance, pRuleSuccess): ''' check on whether report was correct @param self: essential if you override this definition @param pCompliance: the self.iscompliant value of rule @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: dwalker ''' self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkFixForRule(self, pRuleSuccess): ''' check on whether fix was correct @param self: essential if you override this definition @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: dwalker ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkUndoForRule(self, pRuleSuccess): ''' check on whether undo was correct @param self: essential if you override this definition @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: dwalker ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success
class zzzTestRuleForceIdleLogout(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = ForceIdleLogout(self.config, self.environ, self.logdispatch, self.statechglogger) self.logger = self.logdispatch self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.rule.filci.updatecurrvalue(True) self.checkUndo = True self.cmdhelper = CommandHelper(self.logger) self.ph = Pkghelper(self.logger, self.environ) self.gnomesettingpath = "/etc/dconf/db/local.d/00-autologout" self.gnomelockpath = "/etc/dconf/db/local.d/locks/autologout" self.undotimeout = "" self.undoforcelogout = "" self.kdesddm = False myos = self.environ.getostype().lower() if re.search("red hat", myos) or re.search("centos", myos): self.gconf = "GConf2" else: self.gconf = "gconf2" self.timeoutci = self.rule.timeoutci.getcurrvalue() def tearDown(self): pass def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): '''Configure system for the unit test :param self: essential if you override this definition :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' success = True if self.environ.osfamily == 'linux': try: self.seconds = self.timeoutci * 60 except (TypeError): debug = "FORCEIDLELOGOUTTIMEOUT value is not " + \ "valid!\n" self.logger.log(LogPriority.DEBUG, debug) return False self.kdesddm = self.ph.check("sddm") self.gnomesettingpath = "/etc/dconf/db/local.d/00-autologout" desktopmgr = False desktopmgrs = [ "gdm", "gdm3", "kdm", "kde-workspace", "sddm", "patterns-kde-kde_yast" ] if self.ph.check("gdm") or self.ph.check("gdm3"): desktopmgr = True if self.ph.check("kdm") or self.ph.check("kde-workspace")or \ self.ph.check("sddm") or self.ph.check("patterns-kde-kde_yast"): desktopmgr = True if not desktopmgr: for mgr in desktopmgrs: if self.ph.checkAvailable(mgr): if self.ph.install(mgr): desktopmgr = True if not desktopmgr: success = False debug = "Unable to install a desktop manager for testing\n" self.logger.log(LogPriority.DEBUG, debug) success = self.setgnome() success = self.setkde() elif self.environ.getosfamily() == 'darwin': if not self.setosx(): success = False return success def setgnome(self): ''' @author: dwalker @return: bool - success ''' debug = "" if self.environ.geteuid() != 0: debug = "Unable to set gnome conditions in unit " + \ "test because user is not root." success = True if os.path.exists('/etc/dconf/db/local.d'): if os.path.exists(self.gnomesettingpath): if not os.remove(self.gnomesettingpath): success = False debug = "Unable to remove " + self.gnomesettingpath + \ " for unit test preconditions\n" self.logger.log(LogPriority.DEBUG, debug) if self.ph.check(self.gconf): get = "/usr/bin/gconftool-2 --direct --config-source " + \ "xml:readwrite:/etc/gconf/gconf.xml.mandatory --get " set = "/usr/bin/gconftool-2 --direct --config-source " + \ "xml:readwrite:/etc/gconf/gconf.xml.mandatory --set " unset = "/usr/bin/gconftool-2 --direct --config-source " + \ "xml/readwrite:/etc/gconf/gconf.xml.mandatory --unset " idletimecmd = get + "/desktop/gnome/session/max_idle_time" if self.cmdhelper.executeCommand(idletimecmd): output = self.cmdhelper.getOutput() if output: try: if int(output[0].strip()) == self.seconds: timeout = int(self.seconds) + 5 idletimecmd = set + "--type integer /desktop/gnome/session/max_idle_time " + \ str(timeout) if not self.cmdhelper.executeCommand(idletimecmd): success = False debug = "Unable to set incorrect timeout value for " + \ "unit test preconditions\n" self.logger.log(LogPriority.DEBUG, debug) except (IndexError): debug = "No output to display timeout value\n" self.logger.log(LogPriority.DEBUG, debug) else: success = False debug = "Unable to obtain the timeout value\n" self.logger.log(LogPriority.DEBUG, debug) idleactcmd = get + "/desktop/gnome/session/max_idle_action" if self.cmdhelper.executeCommand(idleactcmd): output = self.cmdhelper.getOutput() if output: if re.search("forced-logout", output[0]): idleact = unset + "/desktop/gnome/session/max_idle_action" if not self.cmdhelper.executeCommand(idleact): success = False debug = "Unable to unset max_idle_action for " + \ "unit test preconditions\n" self.logger.log(LogPriority.DEBUG, debug) return success def setkde(self): ''' @author: dwalker @return: bool - success ''' success = True debug = "" if self.kdesddm: self.kdecheck = ".config/kdeglobals" self.rcpath = ".config/kscreenlockerrc" self.kdeprops = {"ScreenSaver": {"Timeout": str(self.seconds)}} else: self.kdecheck = ".kde" self.rcpath = ".kde/share/config/kscreensaverrc" self.kdeprops = { "ScreenSaver": { "AutoLogout": "true", "AutoLogoutTimeout": str(self.seconds) } } contents = readFile("/etc/passwd", self.logger) for line in contents: username = "" homepath = "" temp = line.split(":") try: username = temp[0] homepath = temp[5] except (IndexError): continue kdeparent = os.path.join(homepath, self.kdecheck) kdefile = os.path.join(homepath, self.rcpath) if not os.path.exists(kdeparent): continue elif os.path.exists(kdefile): if self.searchFile(kdefile): if not self.messFile(kdefile): success = False debug = "Unable to set incorrect values for kde " + \ "for user " + username + " in " + \ "unit test preconditions\n" self.logger.log(LogPriority.DEBUG, debug) return success def searchFile(self, filehandle): '''temporary method to separate the code to find directives from the rest of the code. Will put back all in one method eventually @author: dwalker @return: bool @param filehandle: string ''' self.editor = "" kvt = "tagconf" intent = "present" tpath = filehandle + ".tmp" conftype = "closedeq" self.editor = KVEditorStonix(self.statechglogger, self.logger, kvt, filehandle, tpath, self.kdeprops, intent, conftype) if not self.editor.report(): return False else: return True def messFile(self, filehandle): success = True self.editor = "" garbagevalue = "" while True: garbagevalue = randint(0, 200) if garbagevalue != self.timeoutci: break kvt = "tagconf" intent = "present" tpath = filehandle + ".tmp" conftype = "closedeq" if self.kdesddm: self.kdecheck = ".config/kdeglobals" self.rcpath = ".config/kscreenlockerrc" self.kdeprops = {"ScreenSaver": {"Timeout": str(garbagevalue)}} else: self.kdecheck = ".kde" self.rcpath = ".kde/share/config/kscreensaverrc" self.kdeprops = { "ScreenSaver": { "AutoLogout": "true", "AutoLogoutTimeout": str(garbagevalue) } } self.editor = KVEditorStonix(self.statechglogger, self.logger, kvt, filehandle, tpath, self.kdeprops, intent, conftype) self.editor.report() if not self.editor.fix(): success = False elif not self.editor.commit(): success = False return success def checkReportForRule(self, pCompliance, pRuleSuccess): '''check on whether report was correct :param self: essential if you override this definition :param pCompliance: the self.iscompliant value of rule :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkFixForRule(self, pRuleSuccess): '''check on whether fix was correct :param self: essential if you override this definition :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkUndoForRule(self, pRuleSuccess): '''check on whether undo was correct :param self: essential if you override this definition :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success
class zzzTestRuleSecureMTA(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = SecureMTA(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.logger = self.logdispatch self.ch = CommandHelper(self.logdispatch) if self.environ.operatingsystem == "Mac OS X": self.isMac = True else: self.isMac = False def tearDown(self): pass # if not self.isMac: # if self.origState[0] is True and not self.ph.check("sendmail"): # self.ph.install("sendmail") # elif self.origState[0] is False and self.ph.check("sendmail"): # self.ph.remove("sendmail") # # if self.origState[1] is True and not self.ph.check(self.postfixpkg): # self.ph.install(self.postfixpkg) # elif self.origState[1] is False and self.ph.check(self.postfixpkg): # self.ph.remove(self.postfixpkg) # # if self.origState[2] is True and os.path.exists(self.smTmp): # smDir = os.path.split(self.smPath)[0] # if not os.path.exists(smDir): # os.makedirs(smDir) # os.rename(self.smTmp, self.smPath) # elif self.origState[2] is False and os.path.exists(self.smPath): # os.remove(self.smPath) # # if self.origState[3] is True and os.path.exists(self.pfTmp): # pfDir = os.path.split(self.pfPath)[0] # if not os.path.exists(pfDir): # os.makedirs(pfDir) # os.rename(self.pfTmp, self.pfPath) # elif self.origState[3] is False and os.path.exists(self.pfPath): # os.remove(self.pfPath) def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): '''Configure system for the unit test :param self: essential if you override this definition :returns: boolean - If successful True; If failure False @author: dwalker ''' success = True pfdata = { 'inet_interfaces': 'localhost', 'default_process_limit': '100', 'smtpd_client_connection_count_limit': '10', 'smtpd_client_connection_rate_limit': '30', 'queue_minfree': '20971520', 'header_size_limit': '51200', 'message_size_limit': '10485760', 'smtpd_recipient_limit': '100', 'smtpd_banner': '$myhostname ESMTP', 'mynetworks_style': 'host', 'smtpd_recipient_restrictions': 'permit_mynetworks, reject_unauth_destination', 'relayhost': MAILRELAYSERVER } if not self.isMac: smdata = { "O SmtpGreetingMessage": "", "O PrivacyOptions": "goaway" } self.ph = Pkghelper(self.logdispatch, self.environ) self.origState = [False, False, False, False] self.smPath = "/etc/mail/sendmail.cf" self.smTmp = self.smPath + ".stonixUT" self.pfPathlist = [ '/etc/postfix/main.cf', '/usr/lib/postfix/main.cf' ] self.postfixpkg = "postfix" self.pfPath = "" for path in self.pfPathlist: if os.path.exists(path): self.pfPath = path break self.pfTmp = self.pfPath + ".stonixUT" #if postfix file exists, remove any correct contents if self.pfPath: self.postfixed = KVEditorStonix(self.statechglogger, self.logger, "conf", self.pfPath, self.pfTmp, pfdata, "notpresent", "openeq") if not self.postfixed.report(): if self.postfixed.removeables: print("kveditor has removeables\n") if not self.postfixed.fix(): success = False if os.path.exists(self.smPath): self.sndmailed = KVEditorStonix(self.statechglogger, self.logger, "conf", self.smPath, self.smTmp, smdata, "notpresent", "closedeq") if not self.sndmailed.report(): if self.postfixed.removeables: if not self.postfixed.fix(): success = False #remove postfix if installed if self.ph.check("postfix"): if not self.ph.remove("postfix"): success = False #remove sendmail if installed if not self.ph.checkAvailable("postfix"): if self.ph.check("sendmail"): if not self.ph.remove("sendmail"): success = False else: self.pfPath = "/private/etc/postfix/main.cf" self.pfTmp = self.pfPath + ".stonixUT" if os.path.exists(self.pfPath): self.postfixed = KVEditorStonix(self.statechglogger, self.logger, "conf", self.pfPath, self.pfTmp, pfdata, "notpresent", "openeq") if not self.postfixed.report(): if self.postfixed.removeables: if not self.postfixed.fix(): success = False # if self.ph.check("sendmail"): # self.origState[0] = True # if self.ph.check(self.postfixpkg): # self.origState[1] = True # if os.path.exists(self.smPath): # self.origState[2] = True # os.rename(self.smPath, self.smTmp) # if os.path.exists(self.pfPath): # self.origState[3] = True # os.rename(self.pfPath, self.pfTmp) return success # def testFalseFalseFalseFalse(self): # if not self.isMac: # if self.ph.check("sendmail"): # self.ph.remove("sendmail") # if self.ph.check(self.postfixpkg): # self.ph.remove(self.postfixpkg) # if os.path.exists(self.smPath): # os.remove(self.smPath) # if os.path.exists(self.pfPath): # os.remove(self.pfPath) # self.simpleRuleTest() # # def testTrueFalseFalseFalse(self): # if not self.isMac: # if not self.ph.check("sendmail"): # self.ph.install("sendmail") # if self.ph.check(self.postfixpkg): # self.ph.remove(self.postfixpkg) # if os.path.exists(self.smPath): # os.remove(self.smPath) # if os.path.exists(self.pfPath): # os.remove(self.pfPath) # self.simpleRuleTest() # # def testTrueTrueFalseFalse(self): # if not self.isMac: # if not self.ph.check("sendmail"): # self.ph.install("sendmail") # if not self.ph.check(self.postfixpkg): # self.ph.install(self.postfixpkg) # if os.path.exists(self.smPath): # os.remove(self.smPath) # if os.path.exists(self.pfPath): # os.remove(self.pfPath) # self.simpleRuleTest() # # def testTrueTrueTrueFalse(self): # if not self.isMac: # if not self.ph.check("sendmail"): # self.ph.install("sendmail") # if not self.ph.check(self.postfixpkg): # self.ph.install(self.postfixpkg) # if not os.path.exists(self.smPath): # splitpath = self.smPath.split('/') # del splitpath[-1] # subdir = "/".join(splitpath) # if not os.path.exists(subdir): # os.makedirs(subdir, 0755) # open(self.smPath, "w") # if os.path.exists(self.pfPath): # os.remove(self.pfPath) # self.simpleRuleTest() # # def testTrueTrueTrueTrue(self): # if not self.isMac: # if not self.ph.check("sendmail"): # self.ph.install("sendmail") # if not self.ph.check(self.postfixpkg): # self.ph.install(self.postfixpkg) # if not os.path.exists(self.smPath): # splitpath = self.smPath.split('/') # del splitpath[-1] # subdir = "/".join(splitpath) # if not os.path.exists(subdir): # os.makedirs(subdir, 0755) # open(self.smPath, "w") # if not os.path.exists(self.pfPath): # splitpath = self.pfPath.split('/') # del splitpath[-1] # subdir = "/".join(splitpath) # if not os.path.exists(subdir): # os.makedirs(subdir, 0755) # open(self.pfPath, "w") # self.simpleRuleTest() # # def testTrueFalseTrueFalse(self): # if not self.isMac: # if not self.ph.check("sendmail"): # self.ph.install("sendmail") # if self.ph.check(self.postfixpkg): # self.ph.remove(self.postfixpkg) # if not os.path.exists(self.smPath): # splitpath = self.smPath.split('/') # del splitpath[-1] # subdir = "/".join(splitpath) # if not os.path.exists(subdir): # os.makedirs(subdir, 0755) # open(self.smPath, "w") # if os.path.exists(self.pfPath): # os.remove(self.pfPath) # self.simpleRuleTest() # # def testFalseTrueFalseFalse(self): # if not self.isMac: # if self.ph.check("sendmail"): # self.ph.remove("sendmail") # if not self.ph.check(self.postfixpkg): # self.ph.install(self.postfixpkg) # if os.path.exists(self.smPath): # os.remove(self.smPath) # if os.path.exists(self.pfPath): # os.remove(self.pfPath) # self.simpleRuleTest() # # def testFalseTrueFalseTrue(self): # if not self.isMac: # if self.ph.check("sendmail"): # self.ph.remove("sendmail") # if not self.ph.check(self.postfixpkg): # self.ph.install(self.postfixpkg) # if os.path.exists(self.smPath): # os.remove(self.smPath) # if not os.path.exists(self.pfPath): # splitpath = self.pfPath.split('/') # del splitpath[-1] # subdir = "/".join(splitpath) # if not os.path.exists(subdir): # os.makedirs(subdir, 0755) # open(self.pfPath, "w") # self.simpleRuleTest() def checkReportForRule(self, pCompliance, pRuleSuccess): '''check on whether report was correct :param self: essential if you override this definition :param pCompliance: the self.iscompliant value of rule :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkFixForRule(self, pRuleSuccess): '''check on whether fix was correct :param self: essential if you override this definition :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkUndoForRule(self, pRuleSuccess): '''check on whether undo was correct :param self: essential if you override this definition :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success
class zzzTestRuleSecureMTA(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = SecureMTA(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) if self.environ.operatingsystem == "Mac OS X": self.isMac = True else: self.isMac = False if not self.isMac: self.ph = Pkghelper(self.logdispatch, self.environ) self.origState = [False, False, False, False] self.smPath = "/etc/mail/sendmail.cf" self.smTmp = "/tmp/" + os.path.split(self.smPath)[1] + ".utmp" self.pfPathlist = [ '/etc/postfix/main.cf', '/private/etc/postfix/main.cf', '/usr/lib/postfix/main.cf' ] self.pfPath = "" for path in self.pfPathlist: if os.path.exists(path): self.pfPath = path if self.pfPath == "": self.pfPath = "/etc/postfix/main.cf" self.pfTmp = "/tmp/" + os.path.split(self.pfPath)[1] + ".utmp" def tearDown(self): if os.path.exists(self.smTmp): os.rename(self.smTmp, self.smPath) if os.path.exists(self.pfTmp): os.rename(self.pfTmp, self.pfPath) def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): ''' Configure system for the unit test @param self: essential if you override this definition @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' success = True # origState variables are not currently used if not self.isMac: if self.ph.check("sendmail"): self.origState[0] = True if self.ph.check("postfix"): self.origState[1] = True if os.path.exists(self.smPath): self.origState[2] = True os.rename(self.smPath, self.smTmp) if os.path.exists(self.pfPath): self.origState[3] = True os.rename(self.pfPath, self.pfTmp) return success def testFalseFalseFalseFalse(self): if not self.isMac: if self.ph.check("sendmail"): self.ph.remove("sendmail") if self.ph.check("postfix"): self.ph.remove("postfix") if os.path.exists(self.smPath): os.remove(self.smPath) if os.path.exists(self.pfPath): os.remove(self.pfPath) self.simpleRuleTest() def testTrueFalseFalseFalse(self): if not self.isMac: if not self.ph.check("sendmail"): self.ph.install("sendmail") if self.ph.check("postfix"): self.ph.remove("postfix") if os.path.exists(self.smPath): os.remove(self.smPath) if os.path.exists(self.pfPath): os.remove(self.pfPath) self.simpleRuleTest() def testTrueTrueFalseFalse(self): if not self.isMac: if not self.ph.check("sendmail"): self.ph.install("sendmail") if not self.ph.check("postfix"): self.ph.install("postfix") if os.path.exists(self.smPath): os.remove(self.smPath) if os.path.exists(self.pfPath): os.remove(self.pfPath) self.simpleRuleTest() def testTrueTrueTrueFalse(self): if not self.isMac: if not self.ph.check("sendmail"): self.ph.install("sendmail") if not self.ph.check("postfix"): self.ph.install("postfix") if not os.path.exists(self.smPath): open(self.smPath, "w") if os.path.exists(self.pfPath): os.remove(self.pfPath) self.simpleRuleTest() def testTrueTrueTrueTrue(self): if not self.isMac: if not self.ph.check("sendmail"): self.ph.install("sendmail") if not self.ph.check("postfix"): self.ph.install("postfix") if not os.path.exists(self.smPath): open(self.smPath, "w") if not os.path.exists(self.pfPath): open(self.pfPath, "w") self.simpleRuleTest() def testTrueFalseTrueFalse(self): if not self.isMac: if not self.ph.check("sendmail"): self.ph.install("sendmail") if self.ph.check("postfix"): self.ph.remove("postfix") if not os.path.exists(self.smPath): open(self.smPath, "w") if os.path.exists(self.pfPath): os.remove(self.pfPath) self.simpleRuleTest() def testFalseTrueFalseFalse(self): if not self.isMac: if self.ph.check("sendmail"): self.ph.remove("sendmail") if not self.ph.check("postfix"): self.ph.install("postfix") if os.path.exists(self.smPath): os.remove(self.smPath) if os.path.exists(self.pfPath): os.remove(self.pfPath) self.simpleRuleTest() def testFalseTrueFalseTrue(self): if not self.isMac: if self.ph.check("sendmail"): self.ph.remove("sendmail") if not self.ph.check("postfix"): self.ph.install("postfix") if os.path.exists(self.smPath): os.remove(self.smPath) if not os.path.exists(self.pfPath): open(self.pfPath, "w") self.simpleRuleTest() def checkReportForRule(self, pCompliance, pRuleSuccess): ''' check on whether report was correct @param self: essential if you override this definition @param pCompliance: the self.iscompliant value of rule @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkFixForRule(self, pRuleSuccess): ''' check on whether fix was correct @param self: essential if you override this definition @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkUndoForRule(self, pRuleSuccess): ''' check on whether undo was correct @param self: essential if you override this definition @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success
class zzzTestRuleDisableUbuntuDataCollection(RuleTest): def setUp(self): ''' :returns: None @author: ekkehard j. koch, Breen Malmberg ''' RuleTest.setUp(self) self.rule = DisableUbuntuDataCollection(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ph = Pkghelper(self.logdispatch, self.environ) self.datacollectionpkgs = [ "popularity-contest", "apport", "ubuntu-report" ] self.teardownpkgs = [] def tearDown(self): ''' :returns: None ''' for pkg in self.teardownpkgs: self.ph.remove(pkg) self.teardownpkgs.remove(pkg) def runTest(self): ''' :returns: None ''' self.simpleRuleTest() def setConditionsForRule(self): '''Configure system for the unit test :returns: success :rtype: bool @author: ekkehard j. koch, Breen Malmberg ''' success = True self.rule.enabledCI.updatecurrvalue(True) for pkg in self.datacollectionpkgs: if not self.ph.check(pkg): self.ph.install(pkg) self.teardownpkgs.append(pkg) return success def checkReportForRule(self, pCompliance, pRuleSuccess): '''check on whether report was correct :param pCompliance: the self.iscompliant value of rule :param pRuleSuccess: did report run successfully :returns: success :rtype: bool @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkFixForRule(self, pRuleSuccess): '''check on whether fix was correct :param pRuleSuccess: did report run successfully :returns: success :rtype: bool @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success def checkUndoForRule(self, pRuleSuccess): '''check on whether undo was correct :param pRuleSuccess: did report run successfully :returns: success :rtype: bool @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success
def setConditionsForRule(self): ''' Configure system for the unit test @param self: essential if you override this definition @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' success = True if self.environ.getosfamily() == "darwin": success = False osxversion = str(self.environ.getosver()) if osxversion.startswith("10.10.0") or \ osxversion.startswith("10.10.1") or \ osxversion.startswith("10.10.2") or \ osxversion.startswith("10.10.3"): debug = "Using discoveryd LaunchDaemon" self.logdispatch.log(LogPriority.DEBUG, debug) service = \ "/System/Library/LaunchDaemons/com.apple.discoveryd.plist" servicename = "com.apple.networking.discoveryd" parameter = "--no-multicast" plistText = readFile(service, self.logdispatch) newPlistText = re.sub("<string>" + parameter + "</string>", "", "".join(plistText)) success = True else: debug = "Using mDNSResponder LaunchDaemon" self.logdispatch.log(LogPriority.DEBUG, debug) service = "/System/Library/LaunchDaemons/" + \ "com.apple.mDNSResponder.plist" if osxversion.startswith("10.10"): servicename = "com.apple.mDNSResponder.reloaded" parameter = "-NoMulticastAdvertisements" else: servicename = "com.apple.mDNSResponder" parameter = "-NoMulticastAdvertisements" plistText = readFile(service, self.logdispatch) newPlistText = re.sub("<string>" + parameter + "</string>", "", "".join(plistText)) success = True self.service = service if success and self.sh.auditService(service, serviceTarget=servicename): success = writeFile(service + ".stonixtmp", "".join(plistText), self.logdispatch) success = writeFile(service, newPlistText, self.logdispatch) if success and self.sh.auditService(service, serviceTarget=servicename): success = self.sh.reloadService(service, serviceTarget=servicename) else: ph = Pkghelper(self.logdispatch, self.environ) package = "avahi-daemon" service = "avahi-daemon" if (ph.determineMgr() == "yum" or ph.determineMgr() == "dnf"): package = "avahi" path = "/etc/sysconfig/network" if os.path.exists(path): tmppath = path + ".tmp" data = {"NOZEROCONF": "yes"} editor = KVEditorStonix(self.statechglogger, self.logdispatch, "conf", path, tmppath, data, "notpresent", "closedeq") if not editor.report(): if editor.fix(): if not editor.commit(): success = False else: success = False elif ph.determineMgr() == "zypper": package = "avahi" if not ph.check(package) and ph.checkAvailable(package): success = ph.install(package) if success and not self.sh.auditService(service, serviceTarget=self.serviceTarget): self.sh.enableService(service, serviceTarget=self.serviceTarget) return success
class zzzTestRuleSecureSquidProxy(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = SecureSquidProxy(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.ph = Pkghelper(self.logdispatch, self.environ) self.fileexisted = True def tearDown(self): pass def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): ''' Configure system for the unit test @param self: essential if you override this definition @return: boolean - If successful True; If failure False @author: dwalker ''' success = True if self.ph.check("squid"): if self.ph.manager == "apt-get": self.squidfile = "/etc/squid3/squid.conf" else: self.squidfile = "/etc/squid/squid.conf" self.backup = self.squidfile + ".original" self.data1 = {"ftp_passive": "on", "ftp_sanitycheck": "on", "check_hostnames": "on", "request_header_max_size": "20 KB", "reply_header_max_size": "20 KB", "cache_effective_user": "******", "cache_effective_group": "squid", "ignore_unknown_nameservers": "on", "allow_underscore": "off", "httpd_suppress_version_string": "on", "forwarded_for": "off", "log_mime_hdrs": "on", "http_access": "deny to_localhost"} #make sure these aren't in the file self.denied = ["acl Safe_ports port 70", "acl Safe_ports port 210", "acl Safe_ports port 280", "acl Safe_ports port 488", "acl Safe_ports port 591", "acl Safe_ports port 777"] if os.path.exists(self.squidfile): if checkPerms(self.squidfile, [0, 0, 420], self.logdispatch): if not setPerms(self.squidfile, [0, 0, 416], self.logdispatch): success = False copyfile(self.squidfile, self.backup) tempstring = "" contents = readFile(self.squidfile, self.logdispatch) if contents: for line in contents: if re.search("^ftp_passive", line.strip()): '''Delete this line''' continue else: tempstring += line '''insert line with incorrect value''' tempstring += "request_header_max_size 64 KB\n" '''insert line with no value''' tempstring += "ignore_unknown_nameservers\n" '''insert these two lines we don't want in there''' tempstring += "acl Safe_ports port 70\nacl Safe_ports port 210\n" if not writeFile(self.squidfile, tempstring, self.logdispatch): success = False return success def checkReportForRule(self, pCompliance, pRuleSuccess): ''' check on whether report was correct @param self: essential if you override this definition @param pCompliance: the self.iscompliant value of rule @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + \ str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = True return success def checkFixForRule(self, pRuleSuccess): ''' check on whether fix was correct @param self: essential if you override this definition @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = True if not self.fileexisted: os.remove(self.path) return success def checkUndoForRule(self, pRuleSuccess): ''' check on whether undo was correct @param self: essential if you override this definition @param pRuleSuccess: did report run successfully @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = True return success