class zzzTestRuleNoDirectRootLogin(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = NoDirectRootLogin(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.checkUndo = True self.ch = CommandHelper(self.logdispatch) self.securettypath = "/etc/securetty" def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): ''' Configure system to fail before the unit test @param self: essential if you override this definition @return: boolean - If successful True; If failure False @author: Brandon R. Gonzales ''' success = True if os.path.exists(self.securettypath): cmd = ["rm", self.securettypath] self.ch.executeCommand(cmd) return success
class zzzTestRuleNoDirectRootLogin(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = NoDirectRootLogin(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.checkUndo = True self.ch = CommandHelper(self.logdispatch) self.securettypath = "/etc/securetty" def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): '''Configure system to fail before the unit test :param self: essential if you override this definition :returns: boolean - If successful True; If failure False @author: Brandon R. Gonzales ''' success = True if os.path.exists(self.securettypath): cmd = ["rm", self.securettypath] self.ch.executeCommand(cmd) return success
class zzzTestRuleEncryptSwap(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = EncryptSwap(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) def tearDown(self): pass def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): '''This method runs the following command to make sure system is in a non compliant state before rule runs: sudo defaults write /Library/Preferences/com.apple.virtualMemory UseEncryptedSwap -bool no @author: dwalker :returns: bool - True if successful, False if not ''' cmd = [ "/usr/bin/defaults", "write", "/Library/Preferences/com.apple.virtualMemory", "-bool", "no" ] if self.ch.executeCommand(cmd): return True else: return False
class zzzTestRuleEncryptSwap(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = EncryptSwap(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) def tearDown(self): pass def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): ''' This method runs the following command to make sure system is in a non compliant state before rule runs: sudo defaults write /Library/Preferences/com.apple.virtualMemory UseEncryptedSwap -bool no @author: dwalker @return: bool - True if successful, False if not ''' cmd = ["/usr/bin/defaults", "write", "/Library/Preferences/com.apple.virtualMemory", "-bool", "no"] if self.ch.executeCommand(cmd): return True else: return False
class zzzTestFrameworkCommandHelper(unittest.TestCase): ''' Perform tests on different parts of the functionality for framework CommandHelper @param unittest.TestCase: unittest TestCase class inheritance object reference @author: ekkehard @change: Breen Malmberg - 04/11/2018 - removed assertion tests - you can't test for exception assertions in code that is wrapped by try except because the try except intercepts the exception and throws it and it never gets back to the assertraises call (see tf ticket for documentation) ''' def setUp(self): ''' ''' self.enviro = Environment() self.enviro.setdebugmode(True) self.logger = LogDispatcher(self.enviro) self.commandhelper = CommandHelper(self.logger) def tearDown(self): ''' ''' pass def testExecuteValidCommand(self): ''' ''' self.assertTrue(self.commandhelper.executeCommand("ls -l /"), "Execute Valid Command string Failed!") self.assertTrue(self.commandhelper.executeCommand(["ls", "-l", "/"]), "Execute Valid Command List Failed!") def testSetLogPriority(self): ''' ''' self.assertTrue(self.commandhelper.setLogPriority(LogPriority.INFO), "Execute setLogPriority(0) Command string Failed!") self.assertTrue(self.commandhelper.executeCommand(["ls", "-l", "/"]), "Execute commandhelper.executeCommand(['ls','-l','/'])" + " Command List Failed!")
class zzzTestFrameworkCommandHelper(unittest.TestCase): def setUp(self): self.enviro = Environment() self.enviro.setdebugmode(True) self.logger = LogDispatcher(self.enviro) self.commandhelper = CommandHelper(self.logger) def tearDown(self): pass def testBlankCommand(self): self.assertRaises(ValueError, self.commandhelper.setCommand, "") self.assertRaises(TypeError, self.commandhelper.executeCommand, None) self.assertRaises(ValueError, self.commandhelper.executeCommand, "") self.assertRaises(ValueError, self.commandhelper.setCommand, []) self.assertRaises(TypeError, self.commandhelper.executeCommand, None) self.assertRaises(ValueError, self.commandhelper.executeCommand, []) def testExecuteValidCommand(self): self.assertTrue(self.commandhelper.executeCommand("ls -l /"), "Execute Valid Command string Failed!") self.assertTrue(self.commandhelper.executeCommand(["ls", "-l", "/"]), "Execute Valid Command List Failed!") def testExecuteInvalidCommand(self): self.assertRaises(TypeError, self.commandhelper.executeCommand, 0) self.assertRaises(TypeError, self.commandhelper.executeCommand, ['ls', 0, '/']) def testSetLogPriority(self): self.assertRaises(TypeError, self.commandhelper.setLogPriority, 0) self.assertTrue(self.commandhelper.setLogPriority(LogPriority.INFO), "Execute setLogPriority(0) Command string Failed!") self.assertTrue(self.commandhelper.executeCommand(["ls", "-l", "/"]), "Execute commandhelper.executeCommand(['ls','-l','/'])" + " Command List Failed!")
class zzzTestFrameworkCommandHelper(unittest.TestCase): def setUp(self): self.enviro = Environment() self.enviro.setdebugmode(True) self.logger = LogDispatcher(self.enviro) self.commandhelper = CommandHelper(self.logger) def tearDown(self): pass def testBlankCommand(self): self.assertRaises(ValueError, self.commandhelper.setCommand, "") self.assertRaises(TypeError, self.commandhelper.executeCommand, None) self.assertRaises(ValueError, self.commandhelper.executeCommand, "") self.assertRaises(ValueError, self.commandhelper.setCommand, []) self.assertRaises(TypeError, self.commandhelper.executeCommand, None) self.assertRaises(ValueError, self.commandhelper.executeCommand, []) def testExecuteValidCommand(self): self.assertTrue(self.commandhelper.executeCommand("ls -l /"), "Execute Valid Command string Failed!") self.assertTrue(self.commandhelper.executeCommand(["ls", "-l", "/"]), "Execute Valid Command List Failed!") def testExecuteInvalidCommand(self): self.assertRaises(TypeError, self.commandhelper.executeCommand, 0) self.assertRaises(TypeError, self.commandhelper.executeCommand, ['ls', 0, '/']) def testSetLogPriority(self): self.assertRaises(TypeError, self.commandhelper.setLogPriority, 0) self.assertTrue(self.commandhelper.setLogPriority(LogPriority.INFO), "Execute setLogPriority(0) Command string Failed!") self.assertTrue( self.commandhelper.executeCommand(["ls", "-l", "/"]), "Execute commandhelper.executeCommand(['ls','-l','/'])" + " Command List Failed!")
class zzzTestFrameworkCommandHelper(unittest.TestCase): '''Perform tests on different parts of the functionality for framework CommandHelper :param unittest: TestCase: unittest TestCase class inheritance object reference @author: ekkehard @change: Breen Malmberg - 04/11/2018 - removed assertion tests - you can't test for exception assertions in code that is wrapped by try except because the try except intercepts the exception and throws it and it never gets back to the assertraises call (see tf ticket for documentation) ''' def setUp(self): ''' ''' self.enviro = Environment() self.enviro.setdebugmode(True) self.logger = LogDispatcher(self.enviro) self.commandhelper = CommandHelper(self.logger) def tearDown(self): ''' ''' pass def testExecuteValidCommand(self): ''' ''' self.assertTrue(self.commandhelper.executeCommand("ls -l /"), "Execute Valid Command string Failed!") self.assertTrue(self.commandhelper.executeCommand(["ls", "-l", "/"]), "Execute Valid Command List Failed!") def testSetLogPriority(self): ''' ''' self.assertTrue(self.commandhelper.setLogPriority(LogPriority.INFO), "Execute setLogPriority(0) Command string Failed!") self.assertTrue( self.commandhelper.executeCommand(["ls", "-l", "/"]), "Execute commandhelper.executeCommand(['ls','-l','/'])" + " Command List Failed!")
class zzzTestRuleShowBluetoothIcon(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = ShowBluetoothIcon(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.setCheckUndo(True) self.ch = CommandHelper(self.logdispatch) self.dc = "/usr/bin/defaults" def runTest(self): # This rule is only intended to be ran in user mode if self.environ.geteuid() != 0: self.simpleRuleTest() def setConditionsForRule(self): '''This makes sure the initial report fails by executing the following command: defaults -currentHost delete /Users/(username)/Library/Preferences/com.apple.systemuiserver menuExtras :param self: essential if you override this definition :returns: boolean - If successful True; If failure False @author: Brandon R. Gonzales ''' success = True if success: user = pwd.getpwuid(os.getuid())[0] self.systemuiserver = "/Users/" + user + "/Library/Preferences/com.apple.systemuiserver" if os.path.exists(self.systemuiserver): command = [ self.dc, "-currentHost", "delete", self.systemuiserver, "menuExtras" ] success = self.ch.executeCommand(command) if success: success = self.checkReportForRule(False, True) return success
class zzzTestRuleShowBluetoothIcon(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = ShowBluetoothIcon(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.setCheckUndo(True) self.ch = CommandHelper(self.logdispatch) self.dc = "/usr/bin/defaults" def runTest(self): # This rule is only intended to be ran in user mode if self.environ.geteuid() != 0: self.simpleRuleTest() def setConditionsForRule(self): ''' This makes sure the initial report fails by executing the following command: defaults -currentHost delete /Users/(username)/Library/Preferences/com.apple.systemuiserver menuExtras @param self: essential if you override this definition @return: boolean - If successful True; If failure False @author: Brandon R. Gonzales ''' success = True if success: user = pwd.getpwuid(os.getuid())[0] self.systemuiserver = "/Users/" + user + "/Library/Preferences/com.apple.systemuiserver" if os.path.exists(self.systemuiserver): command = [self.dc, "-currentHost", "delete", self.systemuiserver, "menuExtras"] success = self.ch.executeCommand(command) if success: success = self.checkReportForRule(False, True) return success
class zzzTestRuleConfigureLinuxFirewall(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = ConfigureLinuxFirewall(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.logger) self.servicehelper = ServiceHelper(self.environ, self.logger) self.checkUndo = True self.isfirewalld = False self.isufw = False if os.path.exists('/bin/firewall-cmd'): self.isfirewalld = True if os.path.exists('/usr/sbin/ufw'): self.isufw = True # mostly pertains to RHEL6, Centos6 self.iptables = "/usr/sbin/iptables" if not os.path.exists(self.iptables): self.iptables = '/sbin/iptables' self.ip6tables = "/usr/sbin/ip6tables" if not os.path.exists(self.ip6tables): self.ip6tables = '/sbin/ip6tables' if os.path.exists("/usr/sbin/iptables-restore"): self.iprestore = "/usr/sbin/iptables-restore" elif os.path.exists("/sbin/iptables-restore"): self.iprestore = "/sbin/iptables-restore" if os.path.exists("/usr/sbin/ip6tables-restore"): self.ip6restore = "/usr/sbin/ip6tables-restore" elif os.path.exists("/sbin/ip6tables-restore"): self.ip6restore = "/sbin/ip6tables-restore" self.scriptType = "" 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 self.detailedresults = "" self.iptScriptPath = "" scriptExists = "" debug = "" if self.isfirewalld: if self.servicehelper.auditService('firewalld.service'): if not self.servicehelper.disableService('firewalld.service'): success = False if self.isufw: cmdufw = '/usr/sbin/ufw status' if not self.ch.executeCommand(cmdufw): debug = "Unable to run ufw status command in unit test\n" self.logger.log(LogPriority.DEBUG, debug) success = False else: outputufw = self.ch.getOutputString() if re.search('Status: active', outputufw): ufwcmd = '/usr/sbin/ufw --force disable' if not self.ch.executeCommand(ufwcmd): debug = "Unable to disable firewall for unit test\n" self.logger.log(LogPriority.DEBUG, debug) success = False else: cmdufw = "/usr/sbin/ufw status verbose" if not self.ch.executeCommand(cmdufw): debug = "Unable to get verbose status for unit test\n" self.logger.log(LogPriority.DEBUG, debug) success = False else: outputfw = self.cmdhelper.getOutputString() if re.search("Default\:\ deny\ \(incoming\)", outputfw): ufwcmd = "/usr/sbin/ufw default allow incoming" if not self.ch.executeCommand(ufwcmd): debug = "Unable to set allow status for unit test\n" self.logger.log(LogPriority.DEBUG, debug) success = False elif os.path.exists('/usr/bin/system-config-firewall') or \ os.path.exists('/usr/bin/system-config-firewall-tui'): print "system-config-firewall commands exist\n" fwpath = '/etc/sysconfig/system-config-firewall' iptpath = '/etc/sysconfig/iptables' ip6tpath = '/etc/sysconfig/ip6tables' if os.path.exists(fwpath): os.remove(fwpath) if os.path.exists(iptpath): os.remove(iptpath) if os.path.exists(ip6tpath): os.remove(ip6tpath) if not self.servicehelper.disableService('iptables'): print "unable to disable iptables\n" success = False debug = "Could not disable iptables in unit test\n" self.logger.log(LogPriority.DEBUG, debug) if not self.servicehelper.disableService('ip6tables'): print "unable to disable ip6tables\n" success = False debug = "Could not disable ip6tables in unit test\n" self.logger.log(LogPriority.DEBUG, debug) cmd = "/sbin/service iptables stop" if not self.ch.executeCommand(cmd): success = False debug = "Unable to stop iptables in unit test\n" print "unable to stop iptables in unit test\n" self.logger.log(LogPriority.DEBUG, debug) cmd = "/sbin/service ip6tables stop" if not self.ch.executeCommand(cmd): success = False debug = "Unable to stop ip6tables in unit test\n" print "unable to stop iop6tables in unit test\n" self.logger.log(LogPriority.DEBUG, debug) elif os.path.exists(self.iprestore) and \ os.path.exists(self.ip6restore): if os.path.exists(self.iptScriptPath): if not os.remove(self.iptScriptPath): debug = "Unable to remove " + self.iptScriptPath + " for setConditionsForRule\n" self.logger.log(LogPriority.DEBUG, debug) 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 def getScriptValues(self, scriptname): if scriptname == "iptscript": iptScript = '''fw_custom_after_chain_creation() { *filter :INPUT ACCEPT [0:0] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [0:0] -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT -A INPUT -p icmp -j ACCEPT -A INPUT -i lo -j ACCEPT -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT -A INPUT -j REJECT --reject-with icmp-host-prohibited -A FORWARD -j REJECT --reject-with icmp-host-prohibited -A INPUT -p ipv6-icmp -j ACCEPT -A INPUT -m state --state NEW -m udp -p udp --dport 546 -d fe80::/64 -j ACCEPT -A INPUT -j REJECT --reject-with icmp6-adm-prohibited -A FORWARD -j REJECT --reject-with icmp6-adm-prohibited true } fw_custom_before_port_handling() { true } fw_custom_before_masq() { true } fw_custom_before_denyall() { true } fw_custom_after_finished() { true } ''' return iptScript elif scriptname == "iptables": iptables = '''*filter :INPUT ACCEPT [0:0] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [0:0] -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT -A INPUT -p icmp -j ACCEPT -A INPUT -i lo -j ACCEPT -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT -A INPUT -j REJECT --reject-with icmp-host-prohibited -A FORWARD -j REJECT --reject-with icmp-host-prohibited COMMIT ''' return iptables elif scriptname == "ip6tables": ip6tables = '''*filter :INPUT ACCEPT [0:0] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [0:0] -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT -A INPUT -p ipv6-icmp -j ACCEPT -A INPUT -i lo -j ACCEPT -A INPUT -m state --state NEW -m udp -p udp --dport 546 -d fe80::/64 -j ACCEPT -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT -A INPUT -j REJECT --reject-with icmp6-adm-prohibited -A FORWARD -j REJECT --reject-with icmp6-adm-prohibited COMMIT ''' return ip6tables elif scriptname == "systemconfigurefirewall": systemconfigfirewall = '''# Configuration file for system-config-firewall --enabled --service=ssh ''' return systemconfigfirewall elif scriptname == "sysconfigiptables": sysconfigiptables = '''# Firewall configuration written by system-config-firewall # Manual customization of this file is not recommended. *filter :INPUT ACCEPT [0:0] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [0:0] -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT -A INPUT -p icmp -j ACCEPT -A INPUT -i lo -j ACCEPT -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT -A INPUT -j REJECT --reject-with icmp-host-prohibited -A FORWARD -j REJECT --reject-with icmp-host-prohibited COMMIT ''' return sysconfigiptables elif scriptname == "sysconfigip6tables": sysconfigip6tables = '''# Firewall configuration written by system-config-firewall # Manual customization of this file is not recommended. *filter :INPUT ACCEPT [0:0] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [0:0] -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT -A INPUT -p ipv6-icmp -j ACCEPT -A INPUT -i lo -j ACCEPT -A INPUT -m state --state NEW -m udp -p udp --dport 546 -d fe80::/64 -j ACCEPT -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT -A INPUT -j REJECT --reject-with icmp6-adm-prohibited -A FORWARD -j REJECT --reject-with icmp6-adm-prohibited COMMIT ''' return sysconfigip6tables
class zzzTestConfigureRemoteManagement(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = ConfigureRemoteManagement(self.config, self.environ, self.logdispatch, self.statechglogger) self.cmdhelper = CommandHelper(self.logdispatch) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber 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 setupdict = {"ARD_AllLocalUsers": "True", "ScreenSharingReqPermEnabled": "False", "VNCLegacyConnectionsEnabled": "True", "LoadRemoteManagementMenuExtra": "False"} for key in setupdict: self.cmdhelper.executeCommand("defaults write /Library/Preferences/com.apple.RemoteManagement " + key + " -bool " + setupdict[key]) errorout = self.cmdhelper.getError() if errorout: 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 zzzTestRuleConfigureAppleSoftwareUpdate(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = ConfigureAppleSoftwareUpdate(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.dc = "/usr/bin/defaults" def tearDown(self): pass def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): ''' This makes sure the intial report fails by executing the following commands: defaults -currentHost delete /Library/Preferences/com.apple.SoftwareUpdate CatalogURL defaults -currentHost write /Library/Preferences/com.apple.SoftwareUpdate AutomaticDownload -bool yes defaults -currentHost write /Library/Preferences/com.apple.SoftwareUpdate AutomaticCheckEnabled -bool yes defaults -currentHost write /Library/Preferences/com.apple.SoftwareUpdate ConfigDataInstall -bool yes defaults -currentHost write /Library/Preferences/com.apple.SoftwareUpdate DisableCriticalUpdateInstall -bool yes defaults -currentHost delete /Library/Preferences/com.apple.SoftwareUpdate AllowPreReleaseInstallation @param self: essential if you override this definition @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' success = True if success: command = [self.dc, "-currentHost", "delete", "/Library/Preferences/com.apple.SoftwareUpdate", "CatalogURL"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [self.dc, "-currentHost", "write", "/Library/Preferences/com.apple.SoftwareUpdate", "AutomaticDownload", "-bool", "yes"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [self.dc, "-currentHost", "write", "/Library/Preferences/com.apple.SoftwareUpdate", "AutomaticCheckEnabled", "-bool", "yes"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [self.dc, "-currentHost", "write", "/Library/Preferences/com.apple.SoftwareUpdate", "ConfigDataInstall", "-bool", "yes"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [self.dc, "-currentHost", "write", "/Library/Preferences/com.apple.SoftwareUpdate", "DisableCriticalUpdateInstall", "-bool", "yes"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [self.dc, "-currentHost", "delete", "/Library/Preferences/com.apple.SoftwareUpdate", "AllowPreReleaseInstallation"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: success = self.checkReportForRule(False, True) return success def checkReportForRule(self, pCompliance, pRuleSuccess): ''' To see what happended run these commans: defaults -currentHost read /Library/Preferences/com.apple.SoftwareUpdate CatalogURL defaults -currentHost read /Library/Preferences/com.apple.SoftwareUpdate AutomaticDownload defaults -currentHost read /Library/Preferences/com.apple.SoftwareUpdate AutomaticCheckEnabled defaults -currentHost read /Library/Preferences/com.apple.SoftwareUpdate ConfigDataInstall defaults -currentHost read /Library/Preferences/com.apple.SoftwareUpdate DisableCriticalUpdateInstall @param self: essential if you override this definition @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 if success: command = [self.dc, "-currentHost", "read", "/Library/Preferences/com.apple.SoftwareUpdate", "CatalogURL"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [self.dc, "-currentHost", "read", "/Library/Preferences/com.apple.SoftwareUpdate", "AutomaticDownload"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [self.dc, "-currentHost", "read", "/Library/Preferences/com.apple.SoftwareUpdate", "AutomaticCheckEnabled"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [self.dc, "-currentHost", "read", "/Library/Preferences/com.apple.SoftwareUpdate", "ConfigDataInstall"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [self.dc, "-currentHost", "read", "/Library/Preferences/com.apple.SoftwareUpdate", "DisableCriticalUpdateInstall"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) return success def checkFixForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = self.checkReportForRule(True, pRuleSuccess) return success def checkUndoForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = self.checkReportForRule(False, pRuleSuccess) return success
class zzzTestDisableAFPFileSharing(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = DisableAFPFileSharing(self.config, self.environ, self.logdispatch, self.statechglogger) self.cmdhelper = CommandHelper(self.logdispatch) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber 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: Breen Malmberg ''' success = True try: cmd = '/bin/launchctl enable system/com.apple.AppleFileServer' self.cmdhelper.executeCommand(cmd) retcode = self.cmdhelper.getReturnCode() if retcode != 0: errstr = self.cmdhelper.getErrorString() self.logdispatch.log(LogPriority.DEBUG, errstr) success = False except Exception: raise 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 zzzTestRuleSTIGConfigureLoginWindowPolicy(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = STIGConfigureLoginWindowPolicy(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.identifier = "mil.disa.STIG.loginwindow.alacarte" if search("10\.10.*", self.environ.getosver()): self.rule.profile = "/Users/vagrant/stonix/src/stonix_resources/files/" + \ "U_Apple_OS_X_10-10_Workstation_V1R2_STIG_Login_Window_Policy.mobileconfig" elif search("10\.11\.*", self.environ.getosver()): self.rule.profile = "/Users/vagrant/stonix/src/stonix_resources/files/" + \ "U_Apple_OS_X_10-11_V1R1_STIG_Login_Window_Policy.mobileconfig" else: self.rule.profile = "/Users/vagrant/stonix/src/stonix_resources/files/" + \ "U_Apple_macOS_10-12_V1R1_STIG_Login_Window_Policy.mobileconfig" def tearDown(self): pass def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): success = True self.detailedresults = "" cmd = ["/usr/bin/profiles", "-P"] if not self.ch.executeCommand(cmd): success = False self.detailedresults += "Unable to run profiles command\n" else: output = self.ch.getOutput() if output: for line in output: if search("mil\.disa\.STIG\.loginwindow\.alacarte$", line.strip()): cmd = [ "/usr/bin/profiles", "-R", "-p", self.identifier ] if not self.ch.executeCommand(cmd): 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 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.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 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: Breen Malmberg ''' success = True self.rule.ci.updatecurrvalue(True) try: if re.search("debian|ubuntu", self.environ.getostype().lower()): sysstat = "/etc/default/sysstat" if os.path.exists(sysstat): settings = open(sysstat, "r").read() settings = re.sub(r"ENABLED=.+\n", "ENABLED=false\n", settings) else: settings = "ENABLED=false\n" open(sysstat, "w").write(settings) # apt does a very poor job installing packages when it hasn't # been updated in a while, which is problematic with VMs. These # next few lines are intended to deal with that issue. if not re.search("foo.bar", PROXY): os.environ["http_proxy"] = PROXY os.environ["https_proxy"] = PROXY cmd = ["/usr/bin/apt-get", "update"] self.ch.executeCommand(cmd) else: path1 = "/etc/rc.conf" path2 = "/var/account/acct" if os.path.exists(path1): contentlines = open(path1, "r").readlines() for line in contentlines: if re.search('accounting_enable=', line): contentlines = [c.replace(line, 'accounting_enable=NO\n') for c in contentlines] if 'accounting_enable=NO\n' not in contentlines: contentlines.append('accounting_enable=NO\n') open(path1, "w").writelines(contentlines) if os.path.exists(path2): os.remove(path2) except Exception: 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: 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 @return: 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 @return: boolean - If successful True; If failure False @author: Breen Malmberg ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success
class zzzTestRuleDisablePasswordHints(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = DisablePasswordHints(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.dc = "/usr/bin/defaults" def tearDown(self): pass def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): ''' This makes sure the intial report fails by executing the following commands: defaults -currentHost write /Library/Preferences/com.apple.loginwindow RetriesUntilHint -int 1 @param self: essential if you override this definition @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' success = True if success: command = [self.dc, "-currentHost", "write", "/Library/Preferences/com.apple.loginwindow", "RetriesUntilHint", "-int", "1"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: success = self.checkReportForRule(False, True) return success def checkReportForRule(self, pCompliance, pRuleSuccess): ''' To see what happended run these commans: defaults -currentHost read /Library/Preferences/com.apple.AppleFileServer guestAccess defaults -currentHost read /Library/Preferences/SystemConfiguration/com.apple.smb.server AllowGuestAccess @param self: essential if you override this definition @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 if success: command = [self.dc, "-currentHost", "read", "/Library/Preferences/com.apple.loginwindow", "RetriesUntilHint"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) return success def checkFixForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = self.checkReportForRule(True, pRuleSuccess) return success def checkUndoForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = self.checkReportForRule(False, pRuleSuccess) return success
class zzzTestRuleDisableInactiveAccounts(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = DisableInactiveAccounts(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) def tearDown(self): pass def runTest(self): self.setConditionsForRule() 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: Breen Malmberg ''' success = True return success def test_dscl_path(self): '''test for valid location of dscl command path @author: Breen Malmberg ''' found = False if os.path.exists('/usr/bin/dscl'): found = True self.assertTrue(found, True) def test_get_users(self): '''test the command to get the list of users @author: Breen Malmberg ''' self.ch.executeCommand('/usr/bin/dscl . -ls /Users') rc = self.ch.getReturnCode() # rc should always be 0 after this command is run (means it ran successfully) # however 0 is interpreted as false by python, so.. assertFalse self.assertFalse(rc, "The return code for getting the list of users should always be 0 (success)") def test_pwpolicy_path(self): '''test for valid location of pwpolicy command path @author: Breen Malmberg ''' found = False if os.path.exists('/usr/bin/pwpolicy'): found = True self.assertTrue(found, True) def test_initobjs(self): '''test whether the private method initobjs works @author: Breen Malmberg ''' self.rule.initobjs() self.assertTrue(self.rule.cmdhelper, "CommandHelper object should always initialize after initobjs() is run") 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 zzzTestRuleDisableRoot(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = DisableRoot(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(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: ekkehard j. koch ''' success = True create = ["/usr/bin/dscl",".","-create","/Users/root", "AuthenticationAuthority", "whatever"] self.ch.executeCommand(create) 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 zzzTestRuleConfigureAppleSoftwareUpdate(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = ConfigureAppleSoftwareUpdate(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.dc = "/usr/bin/defaults" def tearDown(self): pass def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): '''This makes sure the intial report fails by executing the following commands: defaults -currentHost delete /Library/Preferences/com.apple.SoftwareUpdate CatalogURL defaults -currentHost write /Library/Preferences/com.apple.SoftwareUpdate AutomaticDownload -bool yes defaults -currentHost write /Library/Preferences/com.apple.SoftwareUpdate AutomaticCheckEnabled -bool yes defaults -currentHost write /Library/Preferences/com.apple.SoftwareUpdate ConfigDataInstall -bool yes defaults -currentHost write /Library/Preferences/com.apple.SoftwareUpdate DisableCriticalUpdateInstall -bool yes defaults -currentHost delete /Library/Preferences/com.apple.SoftwareUpdate AllowPreReleaseInstallation :param self: essential if you override this definition :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' success = True if success: command = [self.dc, "-currentHost", "delete", "/Library/Preferences/com.apple.SoftwareUpdate", "CatalogURL"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [self.dc, "-currentHost", "write", "/Library/Preferences/com.apple.SoftwareUpdate", "AutomaticDownload", "-bool", "yes"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [self.dc, "-currentHost", "write", "/Library/Preferences/com.apple.SoftwareUpdate", "AutomaticCheckEnabled", "-bool", "yes"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [self.dc, "-currentHost", "write", "/Library/Preferences/com.apple.SoftwareUpdate", "ConfigDataInstall", "-bool", "yes"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [self.dc, "-currentHost", "write", "/Library/Preferences/com.apple.SoftwareUpdate", "DisableCriticalUpdateInstall", "-bool", "yes"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [self.dc, "-currentHost", "delete", "/Library/Preferences/com.apple.SoftwareUpdate", "AllowPreReleaseInstallation"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [self.dc, "-currentHost", "write", "/Library/Preferences/com.apple.commerce", "AutoUpdateRestartRequired", "-bool", "yes"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: success = self.checkReportForRule(False, True) return success def checkReportForRule(self, pCompliance, pRuleSuccess): '''Did the first rule report do what it was supposed to :param self: essential if you override this definition :param pCompliance: compliance of first rule report boolean :param pRuleSuccess: success of first report execution boolean :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 if pCompliance: success = False self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + \ str(pCompliance) + " it should be false!") if not pRuleSuccess: success = False self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + " it should be true!") return success def checkFixForRule(self, pRuleSuccess): '''Did the rule fix do what it was supposed to :param self: essential if you override this definition :param pRuleSuccess: success of fix execution boolean :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = True if not pRuleSuccess: success = False self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + " it should be true!") return success def checkReportFinalForRule(self, pCompliance, pRuleSuccess): '''Did the final rule report do what it was supposed to :param self: essential if you override this definition :param pCompliance: compliance of final rule report boolean :param pRuleSuccess: success of final report execution boolean :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 if not pCompliance: success = False self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + \ str(pCompliance) + " it should be true!") if not pRuleSuccess: success = False self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + " it should be true!") return success def checkUndoForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") if not pRuleSuccess: success = False self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + " it should be 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 zzzTestRuleConfigurePasswordPolicy(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = ConfigurePasswordPolicy(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) def tearDown(self): pass def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): '''@author: dwalker @note: This unit test will install two incorrect profiles on purpose to force system non-compliancy ''' success = True goodprofiles = {} pwprofile = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]))) + \ "/src/stonix_resources/files/stonix4macPasscodeProfileFor" + \ "OSXElCapitan10.11.mobileconfig" secprofile = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]))) + \ "/src/stonix_resources/files/stonix4macSecurity&Privacy" + \ "ForOSXElcapitan10.11.mobileconfig" pwprofiledict = { "com.apple.mobiledevice.passwordpolicy": { "allowSimple": ["1", "bool"], "forcePIN": ["1", "bool"], "maxFailedAttempts": ["5", "int", "less"], "maxPINAgeInDays": ["180", "int", "more"], "minComplexChars": ["1", "int", "more"], "minLength": ["8", "int", "more"], "minutesUntilFailedLoginReset": ["15", "int", "more"], "pinHistory": ["5", "int", "more"], "requireAlphanumeric": ["1", "bool"] } } spprofiledict = { "com.apple.screensaver": "", "com.apple.loginwindow": "", "com.apple.systempolicy.managed": "", "com.apple.SubmitDiagInfo": "", "com.apple.preference.security": "", "com.apple.MCX": "", "com.apple.applicationaccess": "", "com.apple.systempolicy.control": "" } self.rule.pwprofile = pwprofile self.rule.secprofile = secprofile goodprofiles[pwprofile] = pwprofiledict goodprofiles[secprofile] = spprofiledict cmd = ["/usr/sbin/system_profiler", "SPConfigurationProfileDataType"] if self.ch.executeCommand(cmd): output = self.ch.getOutput() if output: for item, values in list(goodprofiles.items()): self.editor = KVEditorStonix(self.statechglogger, self.logdispatch, "profiles", "", "", values, "", "", output) if self.editor.report(): cmd = ["/usr/bin/profiles", "-R", "-F", item] if not self.ch.executeCommand(cmd): success = False else: cmd = [ "/usr/bin/profiles", "-I", "-F,", item + "fake" ] if not self.ch.executeCommand(cmd): success = False else: 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 zzzTestRuleConfigureLinuxFirewall(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = ConfigureLinuxFirewall(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.logger) self.servicehelper = ServiceHelper(self.environ, self.logger) self.checkUndo = True self.isfirewalld = False self.isufw = False if os.path.exists('/bin/firewall-cmd'): self.isfirewalld = True if os.path.exists('/usr/sbin/ufw'): self.isufw = True # mostly pertains to RHEL6, Centos6 self.iptables = "/usr/sbin/iptables" if not os.path.exists(self.iptables): self.iptables = '/sbin/iptables' self.ip6tables = "/usr/sbin/ip6tables" if not os.path.exists(self.ip6tables): self.ip6tables = '/sbin/ip6tables' if os.path.exists("/usr/sbin/iptables-restore"): self.iprestore = "/usr/sbin/iptables-restore" elif os.path.exists("/sbin/iptables-restore"): self.iprestore = "/sbin/iptables-restore" if os.path.exists("/usr/sbin/ip6tables-restore"): self.ip6restore = "/usr/sbin/ip6tables-restore" elif os.path.exists("/sbin/ip6tables-restore"): self.ip6restore = "/sbin/ip6tables-restore" self.scriptType = "" 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 self.detailedresults = "" self.iptScriptPath = "" scriptExists = "" debug = "" if self.isfirewalld: if self.servicehelper.auditService('firewalld.service'): if not self.servicehelper.disableService('firewalld.service'): success = False if self.isufw: cmdufw = '/usr/sbin/ufw status' if not self.ch.executeCommand(cmdufw): debug = "Unable to run ufw status command in unit test\n" self.logger.log(LogPriority.DEBUG, debug) success = False else: outputufw = self.ch.getOutputString() if re.search('Status: active', outputufw): ufwcmd = '/usr/sbin/ufw --force disable' if not self.ch.executeCommand(ufwcmd): debug = "Unable to disable firewall for unit test\n" self.logger.log(LogPriority.DEBUG, debug) success = False else: cmdufw = "/usr/sbin/ufw status verbose" if not self.ch.executeCommand(cmdufw): debug = "Unable to get verbose status for unit test\n" self.logger.log(LogPriority.DEBUG, debug) success = False else: outputfw = self.cmdhelper.getOutputString() if re.search("Default\:\ deny\ \(incoming\)", outputfw): ufwcmd = "/usr/sbin/ufw default allow incoming" if not self.ch.executeCommand(ufwcmd): debug = "Unable to set allow status for unit test\n" self.logger.log(LogPriority.DEBUG, debug) success = False elif os.path.exists('/usr/bin/system-config-firewall') or \ os.path.exists('/usr/bin/system-config-firewall-tui'): print("system-config-firewall commands exist\n") fwpath = '/etc/sysconfig/system-config-firewall' iptpath = '/etc/sysconfig/iptables' ip6tpath = '/etc/sysconfig/ip6tables' if os.path.exists(fwpath): os.remove(fwpath) if os.path.exists(iptpath): os.remove(iptpath) if os.path.exists(ip6tpath): os.remove(ip6tpath) if not self.servicehelper.disableService('iptables'): print("unable to disable iptables\n") success = False debug = "Could not disable iptables in unit test\n" self.logger.log(LogPriority.DEBUG, debug) if not self.servicehelper.disableService('ip6tables'): print("unable to disable ip6tables\n") success = False debug = "Could not disable ip6tables in unit test\n" self.logger.log(LogPriority.DEBUG, debug) cmd = "/sbin/service iptables stop" if not self.ch.executeCommand(cmd): success = False debug = "Unable to stop iptables in unit test\n" print("unable to stop iptables in unit test\n") self.logger.log(LogPriority.DEBUG, debug) cmd = "/sbin/service ip6tables stop" if not self.ch.executeCommand(cmd): success = False debug = "Unable to stop ip6tables in unit test\n" print("unable to stop iop6tables in unit test\n") self.logger.log(LogPriority.DEBUG, debug) elif os.path.exists(self.iprestore) and \ os.path.exists(self.ip6restore): if os.path.exists(self.iptScriptPath): if not os.remove(self.iptScriptPath): debug = "Unable to remove " + self.iptScriptPath + " for setConditionsForRule\n" self.logger.log(LogPriority.DEBUG, debug) 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 def getScriptValues(self, scriptname): if scriptname == "iptscript": iptScript = '''fw_custom_after_chain_creation() { *filter :INPUT ACCEPT [0:0] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [0:0] -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT -A INPUT -p icmp -j ACCEPT -A INPUT -i lo -j ACCEPT -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT -A INPUT -j REJECT --reject-with icmp-host-prohibited -A FORWARD -j REJECT --reject-with icmp-host-prohibited -A INPUT -p ipv6-icmp -j ACCEPT -A INPUT -m state --state NEW -m udp -p udp --dport 546 -d fe80::/64 -j ACCEPT -A INPUT -j REJECT --reject-with icmp6-adm-prohibited -A FORWARD -j REJECT --reject-with icmp6-adm-prohibited true } fw_custom_before_port_handling() { true } fw_custom_before_masq() { true } fw_custom_before_denyall() { true } fw_custom_after_finished() { true } ''' return iptScript elif scriptname == "iptables": iptables = '''*filter :INPUT ACCEPT [0:0] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [0:0] -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT -A INPUT -p icmp -j ACCEPT -A INPUT -i lo -j ACCEPT -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT -A INPUT -j REJECT --reject-with icmp-host-prohibited -A FORWARD -j REJECT --reject-with icmp-host-prohibited COMMIT ''' return iptables elif scriptname == "ip6tables": ip6tables = '''*filter :INPUT ACCEPT [0:0] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [0:0] -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT -A INPUT -p ipv6-icmp -j ACCEPT -A INPUT -i lo -j ACCEPT -A INPUT -m state --state NEW -m udp -p udp --dport 546 -d fe80::/64 -j ACCEPT -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT -A INPUT -j REJECT --reject-with icmp6-adm-prohibited -A FORWARD -j REJECT --reject-with icmp6-adm-prohibited COMMIT ''' return ip6tables elif scriptname == "systemconfigurefirewall": systemconfigfirewall = '''# Configuration file for system-config-firewall --enabled --service=ssh ''' return systemconfigfirewall elif scriptname == "sysconfigiptables": sysconfigiptables = '''# Firewall configuration written by system-config-firewall # Manual customization of this file is not recommended. *filter :INPUT ACCEPT [0:0] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [0:0] -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT -A INPUT -p icmp -j ACCEPT -A INPUT -i lo -j ACCEPT -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT -A INPUT -j REJECT --reject-with icmp-host-prohibited -A FORWARD -j REJECT --reject-with icmp-host-prohibited COMMIT ''' return sysconfigiptables elif scriptname == "sysconfigip6tables": sysconfigip6tables = '''# Firewall configuration written by system-config-firewall # Manual customization of this file is not recommended. *filter :INPUT ACCEPT [0:0] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [0:0] -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT -A INPUT -p ipv6-icmp -j ACCEPT -A INPUT -i lo -j ACCEPT -A INPUT -m state --state NEW -m udp -p udp --dport 546 -d fe80::/64 -j ACCEPT -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT -A INPUT -j REJECT --reject-with icmp6-adm-prohibited -A FORWARD -j REJECT --reject-with icmp6-adm-prohibited COMMIT ''' return sysconfigip6tables
class zzzTestRuleInstallBanners(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = InstallBanners(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.dc = "/usr/bin/defaults" self.checkUndo = True def tearDown(self): pass def test_initobjs(self): ''' ''' self.rule.initobjs() try: self.assertIsNotNone(self.rule.ph) self.assertIsNotNone(self.rule.ch) except AttributeError: pass except: raise self.assertFalse(self.rule.linux) self.assertFalse(self.rule.mac) self.assertFalse(self.rule.gnome2) self.assertFalse(self.rule.gnome3) self.assertFalse(self.rule.kde) self.assertFalse(self.rule.lightdm) self.assertFalse(self.rule.badline) def test_setgnome3(self): ''' ''' self.rule.setgnome3() self.assertTrue(self.rule.gnome3) self.assertEqual(self.rule.gnome3bannertext, GDM3WARNINGBANNER) def test_setgnome2(self): ''' ''' self.rule.setgnome2() self.assertTrue(self.rule.gnome2) self.assertEqual(self.rule.gnome2bannertext, GDMWARNINGBANNER) def test_setkde(self): ''' ''' self.rule.setkde() self.assertTrue(self.rule.kde) self.assertEqual(self.rule.kdebannertext, ALTWARNINGBANNER) try: self.assertIsNotNone(self.rule.kdeditor) except AttributeError: pass except: raise def test_setlightdm(self): ''' ''' self.rule.setlightdm() self.assertTrue(self.rule.lightdm) self.assertEqual(self.rule.ldmbannertext, ALTWARNINGBANNER) def test_setcommon(self): ''' ''' self.rule.setcommon() try: self.assertIsNotNone(self.rule.loginbannerfile) self.assertNotEqual(self.rule.loginbannerfile, "") self.assertIsNotNone(self.rule.sshdfile) self.assertNotEqual(self.rule.sshdfile, "") except AttributeError: pass except: raise def test_getfilecontents(self): ''' ''' self.assertEqual(self.rule.getFileContents(''), []) self.assertEqual(self.rule.getFileContents('', 'unknown'), '') try: self.assertNotEqual( self.rule.getFileContents( os.path.dirname(os.path.abspath(__file__)) + "/" + __file__), []) self.assertIsInstance( self.rule.getFileContents( os.path.dirname(os.path.abspath(__file__)) + "/" + __file__), list) except AttributeError: pass except: raise def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): '''This makes sure the intial report fails by executing the following commands: defaults -currentHost delete /Library/Preferences/com.apple.AppleFileServer loginGreeting defaults -currentHost delete /Library/Preferences/com.apple.loginwindow LoginWindowText :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": if success: command = [ self.dc, "-currentHost", "delete", "/Library/Preferences/com.apple.AppleFileServer", "loginGreeting" ] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [ self.dc, "-currentHost", "delete", "/Library/Preferences/com.apple.loginwindow", "LoginWindowText" ] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: success = self.checkReportForRule(False, True) return success def checkReportForRule(self, pCompliance, pRuleSuccess): '''To see what happended run these commans: defaults -currentHost read /Library/Preferences/com.apple.AppleFileServer loginGreeting defaults -currentHost read /Library/Preferences/com.apple.loginwindow LoginWindowText :param self: essential if you override this definition :param pCompliance: :param pRuleSuccess: :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 if self.environ.getosfamily() == "darwin": if success: command = [ self.dc, "-currentHost", "read", "/Library/Preferences/com.apple.AppleFileServer", "loginGreeting" ] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [ self.dc, "-currentHost", "read", "/Library/Preferences/com.apple.loginwindow", "LoginWindowText" ] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) return success def checkFixForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = self.checkReportForRule(True, pRuleSuccess) return success def checkUndoForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = self.checkReportForRule(False, pRuleSuccess) return success
class zzzTestRuleEnableKernelAuditing(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = EnableKernelAuditing(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) def tearDown(self): # restore backups of original files, made before testing # if self.environ.getosfamily() == 'darwin': # auditcontrolbak = '/etc/security/audit_control.stonixbak' # audituserbak = '/etc/security/audit_user.stonixbak' # if os.path.exists(auditcontrolbak): # os.rename(auditcontrolbak, '/etc/security/audit_control') # if os.path.exists(audituserbak): # os.rename(audituserbak, '/etc/security/audit_user') # else: # auditdbaks =['/etc/audit/auditd.conf.stonixbak', '/etc/auditd.conf.stonixbak'] # auditrulesbaks = ['/etc/audit/audit.rules.stonixbak', '/etc/audit/rules.d/audit.rules.stonixbak'] # for bak in auditdbaks: # if os.path.exists(bak): # os.rename(bak, bak[:-10]) # for bak in auditrulesbaks: # if os.path.exists(bak): # os.rename(bak, bak[:-10]) 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 # # # make backups of any original files, before testing # if self.environ.getosfamily() == 'darwin': # if os.path.exists('/etc/security/audit_control'): # os.rename('/etc/security/audit_control', '/etc/security/audit_control.stonixbak') # if os.path.exists('/etc/security/audit_user'): # os.rename('/etc/security/audit_user', '/etc/security/audit_user.stonixbak') # else: # auditdpaths = ['/etc/audit/auditd.conf', '/etc/auditd.conf'] # for path in auditdpaths: # if os.path.exists(path): # os.rename(path, path + '.stonixbak') # if os.path.exists('/etc/audisp/audispd.conf'): # os.rename('/etc/audisp/audispd.conf', '/etc/audisp/audispd.conf.stonixbak') # auditruleslocs = ['/etc/audit/audit.rules', '/etc/audit/rules.d/audit.rules'] # for loc in auditruleslocs: # if os.path.exists(loc): # os.rename(loc, loc + '.stonixbak') return success def test_freqci_in_range(self): ''' test if the frequency ci value is within range @author: Breen Malmberg ''' allowable_freq_range = range(1,100) self.assertTrue(self.rule.freqci.getcurrvalue() in allowable_freq_range) def test_flushtype_valid(self): ''' test if the flush type ci value is a valid flush type @author: Breen Malmberg ''' allowable_flush_types = ['data', 'incremental', 'sync'] self.assertTrue(self.rule.flushtypeci.getcurrvalue() in allowable_flush_types) def test_get_system_arch(self): ''' test the command to get the system arch @author: Breen Malmberg ''' found = False self.ch.executeCommand('/usr/bin/uname -m') self.assertEqual(0, self.ch.getReturnCode()) outputlines = self.ch.getOutput() self.assertFalse(outputlines == '') for line in outputlines: if re.search('^x86\_64', line): found = True for line in outputlines: if re.search('^x86', line): found = True self.assertEqual(found, True) def test_get_suid_files(self): ''' test the command to find suid files @author: Breen Malmberg ''' self.ch.executeCommand('/usr/bin/find / -xdev -type f -perm -4000 -o -type f -perm -2000') self.assertEqual(0, self.ch.getReturnCode()) def test_release_file_exists(self): ''' does at least one of the release file paths that the code relies on exist? linux-only @author: Breen Malmberg ''' if self.environ.getosfamily() == 'darwin': return True found = False releasefilelocs = ['/etc/os-release', '/etc/redhat-release'] for loc in releasefilelocs: if os.path.exists(loc): found = True self.assertEqual(found, True) def test_grub_cfg_file_exists(self): ''' does at least one of the grub config file paths that the code relies on exist? linux-only @author: Breen Malmberg ''' if self.environ.getosfamily() == 'darwin': return True found = False grubcfglocs = ['/boot/grub/grub.conf', '/etc/default/grub'] for loc in grubcfglocs: if os.path.exists(loc): found = True self.assertEqual(found, True) 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 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 zzzTestReqPassSysPref(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = ReqPassSysPref(self.config, self.environ, self.logdispatch, self.statechglogger) self.cmdhelper = CommandHelper(self.logdispatch) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber 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 setuplist = ["system.preferences", "system.preferences.accessibility", "system.preferences.accounts", "system.preferences.datetime", "system.preferences.energysaver", "system.preferences.location", "system.preferences.network", "system.preferences.nvram", "system.preferences.parental-controls", "system.preferences.printing", "system.preferences.security", "system.preferences.security.remotepair", "system.preferences.sharing", "system.preferences.softwareupdate", "system.preferences.startupdisk", "system.preferences.timemachine", "system.preferences.version-cue"] plistfile = "/System/Library/Security/authorization.plist" plistbuddy = "/usr/libexec/PlistBuddy" for option in setuplist: self.cmdhelper.executeCommand(plistbuddy + " -c 'Set rights:" + option + ":shared 1 " + plistfile) errorout = self.cmdhelper.getErrorString() if errorout: if re.search("Does Not Exist", errorout): self.cmdhelper.executeCommand(plistbuddy + " -c 'Add rights:" + option + ":shared bool true " + plistfile) erradd = self.cmdhelper.getErrorString() if erradd: 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 zzzTestRuleConfigureGatekeeper(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = ConfigureGatekeeper(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) def tearDown(self): pass def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): success = True cmd = ["/usr/bin/profiles", "-L"] #change this to actual gatkeeper profile number profilenum = "C873806E-E634-4E58-B960-62817F398E11" if self.ch.executeCommand(cmd): output = self.ch.getOutput() if output: for line in output: if re.search(profilenum, line): cmd = ["/usr/bin/profiles", "-r", profilenum] if not self.ch.executeCommand(cmd): 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 MacOSUser(ManageUser): """ Class to manage users on Mac OS. @method findUniqueUid @method setUserShell @method setUserComment @method setUserUid @method setUserPriGid @method setUserHomeDir @method addUserToGroup @method rmUserFromGroup @method setUserPassword @method setUserLoginKeychainPassword @method createHomeDirectory @method rmUser @method rmUserHome @author: Roy Nielsen """ def __init__(self, userName="", userShell="/bin/bash", userComment="", userUid=1000, userPriGid=20, userHomeDir="/tmp", logger=False): super(MacOSUser, self).__init__(userName, userShell, userComment, userUid, userPriGid, userHomeDir, logger) self.module_version = '20160225.125554.540679' self.dscl = "/usr/bin/dscl" self.cmdh = CommandHelper(self.logger) #---------------------------------------------------------------------- def createStandardUser(self, userName, password): """ Creates a user that has the "next" uid in line to be used, then puts in in a group of the same id. Uses /bin/bash as the standard shell. The userComment is left empty. Primary use is managing a user during test automation, when requiring a "user" context. It does not set a login keychain password as that is created on first login to the GUI. @author: Roy Nielsen """ self.createBasicUser(userName) newUserID = self.findUniqueUid() newUserGID = newUserID self.setUserUid(userName, newUserID) self.setUserPriGid(userName, newUserID) self.setUserHomeDir(userName) self.setUserShell(userName, "/bin/bash") self.setUserPassword(userName, password) ##### # Don't need to set the user login keychain password as it should be # created on first login. #---------------------------------------------------------------------- def setDscl(self, directory=".", action="", object="", property="", value=""): """ Using dscl to set a value in a directory... @author: Roy Nielsen """ success = False reterr = "" if directory and action and object and property and value: cmd = [self.dscl, directory, action, object, property, value] self.cmdh.executeCommand(cmd) output = self.cmdh.getOutput() reterr = self.cmdh.getErrorString() if not reterr: success = True else: raise DsclError("Error trying to set a value with dscl (" + \ str(reterr).strip() + ")") return success def getDscl(self, directory="", action="", dirobj="", property=""): """ Using dscl to retrieve a value from the directory @author: Roy Nielsen """ success = False reterr = "" retval = "" ##### # FIRST VALIDATE INPUT!! if isinstance(directory, basestring) and re.match("^[/\.][A-Za-z0-9/]*", directory): success = True else: success = False if isinstance(action, basestring) and re.match("^[-]*[a-z]+", action) and success: success = True else: success = False if isinstance(dirobj, basestring) and re.match("^[A-Za-z0=9/]+", dirobj) and success: success = True else: success = False if isinstance(property, basestring) and re.match("^[A-Za-z0-9]+", property) and success: success = True else: success = False ##### # Now do the directory lookup. if success: cmd = [self.dscl, directory, action, object, property] self.cmdh.executeCommand(cmd) retval = self.cmdh.getOutput() reterr = self.cmdh.getErrorString() if reterr: raise DsclError("Error trying to get a value with dscl (" + \ str(reterr).strip() + ")") return ("\n").join(retval) def findUniqueUid(self): """ We need to make sure to find an unused uid (unique ID) for the user, $ dscl . -list /Users UniqueID will list all the existing users, an unused number above 500 is good. @author: Roy Nielsen """ success = False maxUserID = 0 newUserID = 0 userList = self.getDscl(".", "-list", "/Users", "UniqueID") ##### # Sort the list, add one to the highest value and return that # value for user in str(userList).split("\n"): if int(user.split()[1]) > maxUserID: maxUserID = int(user.split()[1]) newUserID = str(int(maxUserID + 1)) return newUserID #---------------------------------------------------------------------- def uidTaken(self, uid): """ See if the UID requested has been taken. Only approve uid's over 1k $ dscl . -list /Users UniqueID @author: Roy Nielsen """ uidList = [] success = False userList = self.getDscl(".", "-list", "/Users", "UniqueID") ##### # Sort the list, add one to the highest value and return that # value for user in str(userList).split("\n"): uidList.append(str(user.split()[1])) if str(uid) in uidList: success = True return success #---------------------------------------------------------------------- def createBasicUser(self, userName=""): """ Create a username with just a moniker. Allow the system to take care of the rest. Only allow usernames with letters and numbers. On the MacOS platform, all other steps must also be done. @author: Roy Nielsen """ success = False reterr = "" if isinstance(userName, basestring)\ and re.match("^[A-Za-z][A-Za-z0-9]*$", userName): cmd = [self.dscl, ".", "-create", "/Users/" + str(userName)] self.cmdh.executeCommand(cmd) output = self.cmdh.getOutput() reterr = self.cmdh.getErrorString() if not reterr: success = True else: raise DsclError("Error trying to set a value with dscl (" + \ str(reterr).strip() + ")") return success #---------------------------------------------------------------------- def setUserShell(self, user="", shell=""): """ dscl . -create /Users/luser UserShell /bin/bash @author: Roy Nielsen """ success = False if self.isSaneUserName(user) and self.isSaneUserShell(shell): isSetDSL = self.setDscl(".", "-create", "/Users/" + str(user), "UserShell", str(shell)) if isSetDSL: success = True return success #---------------------------------------------------------------------- def setUserComment(self, user="", comment=""): """ dscl . -create /Users/luser RealName "Real A. Name" @author: Roy Nielsen """ success = False if self.isSaneUserName(user) and comment: isSetDSL = self.setDscl(".", "-create", "/Users/" + str(user), "RealName", str(comment)) if isSetDSL: success = True return success #---------------------------------------------------------------------- def setUserUid(self, user="", uid=""): """ dscl . -create /Users/luser UniqueID "503" @author: Roy Nielsen """ success = False if self.isSaneUserName(user) and uid: isSetDSL = self.setDscl(".", "-create", "/Users/" + str(user), "UniqueID", str(uid)) if isSetDSL: success = True return success #---------------------------------------------------------------------- def setUserPriGid(self, user="", priGid=""): """ dscl . -create /Users/luser PrimaryGroupID 20 @author: Roy Nielsen """ success = False if self.isSaneUserName(user) and priGid: isSetDSL = self.setDscl(".", "-create", "/Users/" + str(user), "PrimaryGroupID", str(priGid)) if isSetDSL: success = True return success #---------------------------------------------------------------------- def setUserHomeDir(self, user="", userHome=""): """ Create a "local" home directory dscl . -create /Users/luser NFSHomeDirectory /Users/luser better yet: createhomedir -l -u <username> @author: Roy Nielsen """ success = False ##### # Creating a non-standard userHome is not currently permitted #if self.saneUserName(user) and self.saneUserHomeDir(userHome): if self.isSaneUserName(user): isSetDSCL = self.setDscl(".", "-create", "/Users/" + str(user), "NFSHomeDirectory", str("/Users/" + str(user))) if isSetDSCL: success = True return success #---------------------------------------------------------------------- def createHomeDirectory(self, user=""): """ createhomedir -c -u luser This should use the system "User Template" for standard system user settings. @author: Roy Nielsen """ success = False reterr = "" if user: cmd = ["/usr/sbin/createhomedir", "-c", " -u", + str(user)] self.cmdh.executeCommand(cmd) self.cmdh.getOutput() reterr = self.cmdh.getErrorString() if not reterr: success = True else: raise CreateHomeDirError("Error trying to create user home (" + \ str(reterr).strip() + ")") return success #---------------------------------------------------------------------- def addUserToGroup(self, user="", group=""): """ dscl . -append /Groups/admin GroupMembership luser @author: Roy Nielsen """ success = False if self.isSaneUserName(user) and self.isSaneGroupName(group): isSetDSCL = self.setDscl(".", "-append", "/Groups/" + str(group), "GroupMembership", str(user)) if isSetDSCL: success = True return success #---------------------------------------------------------------------- def rmUserFromGroup(self, user="", group=""): """ """ success = False if self.isSaneUserName(user) and self.isSaneGroupName(group): isSetDSCL = self.setDscl(".", "-delete", "/Groups/" + str(group), "GroupMembership", str(user)) if isSetDSCL: success = True return success #---------------------------------------------------------------------- def setUserPassword(self, user="", password=""): """ dscl . -passwd /Users/luser password @author: Roy Nielsen """ success = False if self.isSaneUserName(user) and isinstance(password, basestring): isSetDSCL = self.setDscl("."", -passwd", "/Users/" + str(user), password) if not isSetDSCL: success = False else: success = True return success #---------------------------------------------------------------------- def setUserLoginKeychainPassword(self, user="", password=""): """ Use the "security" command to set the login keychain. If it has not been created, create the login keychain. Needs research.. Not sure if a sudo'd admin can use the security command to change another user's keychain password... possibly: security set-keychain-password -o oldpassword -p newpassword file.keychain where file.keychain is the default login.keychain of another user? @author: Roy Nielsen """ pass """ self.sec = "/usr/bin/security" success = False keychainpath = "" if self.isSaneUserName(user) and isinstance(password, basestring): pass ##### # Input validation ##### # Check if login keychain exists ##### # if it does not exist, create it if not os.path.exists(keychainpath): cmd = ["Create Keychain Command Here"] self.cmdh.executeCommand(cmd) output = self.cmdh.getOutput() reterr = self.cmdh.getErrorString() if not reterr: success = True else: self.logger.log(lp.INFO, "Unsuccessful attempt to create the " + \ "keychain...(" + str(reterr) + ")") ##### # else set the login keychain password pass """ #---------------------------------------------------------------------- def rmUser(self, user=""): """ dscl . delete /Users/<user> @author: Roy Nielsen """ success = False if self.isSaneUserName(user): cmd = [self.dscl, ".", "-delete", "/Users/" + str(user)] self.cmdh.executeCommand(cmd) output = self.cmdh.getOutput() reterr = self.cmdh.getErrorString() if not reterr: success = True else: raise Exception("Error trying to remove a user (" + \ str(reterr).strip() + ")") return success #---------------------------------------------------------------------- def rmUserHome(self, user=""): """ Remove the user home... right now only default location, but should look up the user home in the directory service and remove that specifically. @author: Roy Nielsen """ success = False if self.isSaneUserName(user): ##### # # ***** WARNING WILL ROBINSON ***** # # Please refactor to do a lookup of the user in the directory # service, and use the home directory specified there.. # try: shutil.rmtree("/Users/" + str(user)) except IOError or OSError, err: self.logger.log(lp.INFO, "Exception trying to remove user home...") self.logger.log(lp.INFO, "Exception: " + str(err)) raise err else: success = True return success
class zzzTestRuleDisableCamera(RuleTest): def setUp(self): ''' @change: Breen Malmberg - 06102015 - updated self.cmd and paths to work with updated unit test functionality ''' RuleTest.setUp(self) self.rule = DisableCamera(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.cmd = 'chmod a+r ' self.paths = [ '/System/Library/QuickTime/QuickTimeUSBVDCDigitizer.component/Contents/MacOS/QuickTimeUSBVDCDigitizer', '/System/Library/PrivateFrameworks/CoreMediaIOServicesPrivate.framework/Versions/A/Resources/VDC.plugin/Contents/MacOS/VDC', '/System/Library/PrivateFrameworks/CoreMediaIOServices.framework/Versions/A/Resources/VDC.plugin/Contents/MacOS/VDC', '/System/Library/Frameworks/CoreMediaIO.framework/Versions/A/Resources/VDC.plugin/Contents/MacOS/VDC', '/Library/CoreMediaIO/Plug-Ins/DAL/AppleCamera.plugin/Contents/MacOS/AppleCamera' ] 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 @change: Breen Malmberg - 06102015 - changed this method to reflect the new functionality of DisableCamera.py ''' success = True for path in self.paths: if os.path.exists(path): self.ch.executeCommand(self.cmd + path) error = self.ch.getErrorString() if error: 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 zzzTestRuleConfigureScreenLocking(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = ConfigureScreenLocking(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.effectiveUserID = self.environ.geteuid() self.ch = CommandHelper(self.logdispatch) self.dc = "/usr/bin/defaults" 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.getosfamily() == "darwin": if self.effectiveUserID == 0: if success: command = [ self.dc, "-currentHost", "delete", "/Library/Preferences/com.apple.screensaver", "askForPassword" ] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [ self.dc, "-currentHost", "delete", "/Library/Preferences/com.apple.screensaver", "idleTime" ] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [ self.dc, "-currentHost", "delete", "/Library/Preferences/com.apple.screensaver", "loginWindowIdleTime" ] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) else: if success: command = [ self.dc, "-currentHost", "delete", "~/Library/Preferences/com.apple.screensaver", "askForPassword" ] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [ self.dc, "-currentHost", "delete", "~/Library/Preferences/com.apple.screensaver", "askForPasswordDelay" ] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = 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 zzzTestRuleDisableFTP(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = DisableFTP(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.dc = "/usr/bin/defaults" def tearDown(self): pass def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): ''' This makes sure the intial report fails by executing the following commands: defaults write /System/Library/LaunchDaemons/ftp.plist Disabled 0 @param self: essential if you override this definition @return: boolean - If successful True; If failure False @author: Eric Ball ''' success = True if self.environ.getosfamily() == "darwin": if success: command = [self.dc, "write", "/System/Library/LaunchDaemons/ftp.plist", "Disabled", "0"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = 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): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = self.checkReportForRule(True, pRuleSuccess) return success def checkUndoForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = self.checkReportForRule(False, pRuleSuccess) return success
class zzzTestRuleDisableCamera(RuleTest): def setUp(self): ''' @change: Breen Malmberg - 06102015 - updated self.cmd and paths to work with updated unit test functionality ''' RuleTest.setUp(self) self.rule = DisableCamera(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.cmd = 'chmod a+r ' self.paths = ['/System/Library/QuickTime/QuickTimeUSBVDCDigitizer.component/Contents/MacOS/QuickTimeUSBVDCDigitizer', '/System/Library/PrivateFrameworks/CoreMediaIOServicesPrivate.framework/Versions/A/Resources/VDC.plugin/Contents/MacOS/VDC', '/System/Library/PrivateFrameworks/CoreMediaIOServices.framework/Versions/A/Resources/VDC.plugin/Contents/MacOS/VDC', '/System/Library/Frameworks/CoreMediaIO.framework/Versions/A/Resources/VDC.plugin/Contents/MacOS/VDC', '/Library/CoreMediaIO/Plug-Ins/DAL/AppleCamera.plugin/Contents/MacOS/AppleCamera'] 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 @change: Breen Malmberg - 06102015 - changed this method to reflect the new functionality of DisableCamera.py ''' success = True for path in self.paths: if os.path.exists(path): self.ch.executeCommand(self.cmd + path) error = self.ch.getErrorString() if error: 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 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 zzzTestRuleDisableRoot(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = DisableRoot(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(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 :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' success = True create = [ "/usr/bin/dscl", ".", "-create", "/Users/root", "AuthenticationAuthority", "whatever" ] self.ch.executeCommand(create) 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 zzzTestRuleDisableInactiveAccounts(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = DisableInactiveAccounts(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) def tearDown(self): pass def runTest(self): self.setConditionsForRule() 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: Breen Malmberg ''' success = True return success def test_dscl_path(self): ''' test for valid location of dscl command path @author: Breen Malmberg ''' found = False if os.path.exists('/usr/bin/dscl'): found = True self.assertTrue(found, True) def test_get_users(self): ''' test the command to get the list of users @author: Breen Malmberg ''' self.ch.executeCommand('/usr/bin/dscl . -ls /Users') rc = self.ch.getReturnCode() # rc should always be 0 after this command is run (means it ran successfully) # however 0 is interpreted as false by python, so.. assertFalse self.assertFalse(rc, "The return code for getting the list of users should always be 0 (success)") def test_pwpolicy_path(self): ''' test for valid location of pwpolicy command path @author: Breen Malmberg ''' found = False if os.path.exists('/usr/bin/pwpolicy'): found = True self.assertTrue(found, True) def test_initobjs(self): ''' test whether the private method initobjs works @author: Breen Malmberg ''' self.rule.initobjs() self.assertTrue(self.rule.cmdhelper, "CommandHelper object should always initialize after initobjs() is run") 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: 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 @return: 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 @return: boolean - If successful True; If failure False @author: Breen Malmberg ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = True return success
class zzzTestRuleSetSSCorners(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = SetSSCorners(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(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: Breen Malmberg """ success = True self.cmdhelper = CommandHelper(self.logdispatch) optdict = {"wvous-tr-corner": 6} cmd = "defaults write " + '"' + self.environ.geteuidhome() + '/Library/Preferences/com.apple.dock.plist" ' for item in optdict: self.cmdhelper.executeCommand(cmd + item + " -int " + str(optdict[item])) errout = self.cmdhelper.getErrorString() if errout: 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: 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 @return: 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 @return: boolean - If successful True; If failure False @author: Breen Malmberg """ self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") success = True return success
class zzzTestDisableAFPFileSharing(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = DisableAFPFileSharing(self.config, self.environ, self.logdispatch, self.statechglogger) self.cmdhelper = CommandHelper(self.logdispatch) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber 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: Breen Malmberg ''' success = True try: cmd = '/bin/launchctl enable system/com.apple.AppleFileServer' self.cmdhelper.executeCommand(cmd) retcode = self.cmdhelper.getReturnCode() if retcode != 0: errstr = self.cmdhelper.getErrorString() self.logdispatch.log(LogPriority.DEBUG, errstr) success = False except Exception: raise 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 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 zzzTestRuleInstallBanners(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = InstallBanners(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.dc = "/usr/bin/defaults" def tearDown(self): pass def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): ''' This makes sure the intial report fails by executing the following commands: defaults -currentHost delete /Library/Preferences/com.apple.AppleFileServer loginGreeting defaults -currentHost delete /Library/Preferences/com.apple.loginwindow LoginWindowText @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": if success: command = [self.dc, "-currentHost", "delete", "/Library/Preferences/com.apple.AppleFileServer", "loginGreeting"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [self.dc, "-currentHost", "delete", "/Library/Preferences/com.apple.loginwindow", "LoginWindowText"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: success = self.checkReportForRule(False, True) return success def checkReportForRule(self, pCompliance, pRuleSuccess): ''' To see what happended run these commans: defaults -currentHost read /Library/Preferences/com.apple.AppleFileServer loginGreeting defaults -currentHost read /Library/Preferences/com.apple.loginwindow LoginWindowText @param self: essential if you override this definition @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 if self.environ.getosfamily() == "darwin": if success: command = [self.dc, "-currentHost", "read", "/Library/Preferences/com.apple.AppleFileServer", "loginGreeting"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [self.dc, "-currentHost", "read", "/Library/Preferences/com.apple.loginwindow", "LoginWindowText"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) return success def checkFixForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = self.checkReportForRule(True, pRuleSuccess) return success def checkUndoForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = self.checkReportForRule(False, pRuleSuccess) 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 :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 zzzTestRuleDisableInternetSharing(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = DisableInternetSharing(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.dc = "/usr/bin/defaults" def tearDown(self): pass def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): '''This makes sure the intial report fails by executing the following commands: defaults -currentHost write /Library/Preferences/SystemConfiguration/com.apple.nat NAT -dict Enabled -int 1 :param self: essential if you override this definition :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' success = True if success: command = [ self.dc, "-currentHost", "write", "/Library/Preferences/SystemConfiguration/com.apple.nat", "NAT", "-dict", "Enabled", "-int", "1" ] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: success = self.checkReportForRule(False, True) return success def checkReportForRule(self, pCompliance, pRuleSuccess): '''To see what happended run these commans: defaults -currentHost read /Library/Preferences/SystemConfiguration/com.apple.nat NAT :param self: essential if you override this definition :param pCompliance: :param pRuleSuccess: :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 if success: command = [ self.dc, "-currentHost", "read", "/Library/Preferences/SystemConfiguration/com.apple.nat", "NAT" ] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) return success def checkFixForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = self.checkReportForRule(True, pRuleSuccess) return success def checkUndoForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = self.checkReportForRule(False, pRuleSuccess) return success
class zzzTestRuleSecureMailClient(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = SecureMailClient(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.dc = "/usr/bin/defaults" 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 success: command = [self.dc, "-currentHost", "write", "~/Library/Preferences/com.apple.mail.plist", "DisableURLLoading", "-bool", "no"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [self.dc, "-currentHost", "write", "~/Library/Preferences/com.apple.mail.plist", "DisableInlineAttachmentViewing", "-bool", "no"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [self.dc, "-currentHost", "write", "~/Library/Preferences/com.apple.mail.plist", "AlertForNonmatchingDomains", "-bool", "no"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [self.dc, "-currentHost", "delete", "~/Library/Preferences/com.apple.mail.plist", "DomainForMatching"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = 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 zzzTestConfigureRemoteManagement(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = ConfigureRemoteManagement(self.config, self.environ, self.logdispatch, self.statechglogger) self.cmdhelper = CommandHelper(self.logdispatch) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber 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 setupdict = {"ARD_AllLocalUsers": "True", "ScreenSharingReqPermEnabled": "False", "VNCLegacyConnectionsEnabled": "True", "LoadRemoteManagementMenuExtra": "False"} for key in setupdict: self.cmdhelper.executeCommand("defaults write /Library/Preferences/com.apple.RemoteManagement " + key + " -bool " + setupdict[key]) errorout = self.cmdhelper.getError() if errorout: 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 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 zzzTestRuleDisableOpenSafeSafari(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = DisableOpenSafeSafari(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.dc = "/usr/bin/defaults" self.path = "com.apple.Safari" self.key = "AutoOpenSafeDownloads" def tearDown(self): pass def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): ''' This makes sure the intial report fails by executing the following commands: defaults write com.apple.Safari AutoOpenSafeDownloads -bool yes @param self: essential if you override this definition @return: boolean - If successful True; If failure False @author: dwalker ''' success = False cmd = [self.dc, "write", self.path, self.key, "-bool", "yes"] self.logdispatch.log(LogPriority.DEBUG, str(cmd)) if self.ch.executeCommand(cmd): success = self.checkReportForRule(False, True) return success def checkReportForRule(self, pCompliance, pRuleSuccess): ''' To see what happended run these commands: defaults read com.apple.Safari AutoOpenSafeDownloads @param self: essential if you override this definition @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' success = True self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + \ str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") cmd = [self.dc, "read", self.path, self.key] self.logdispatch.log(LogPriority.DEBUG, str(cmd)) if self.ch.executeCommand(cmd): output = self.ch.getOutputString() return success def checkFixForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = self.checkReportForRule(True, pRuleSuccess) return success def checkUndoForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = self.checkReportForRule(False, pRuleSuccess) return success
class zzzTestRuleDisableGUILogon(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = DisableGUILogon(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.sh = ServiceHelper(self.environ, self.logdispatch) def tearDown(self): self.rule.undo() def runTest(self): result = self.simpleRuleTest() self.assertTrue( result, "DisableGUILogon(105): rule.iscompliant() " + "is 'False' after rule.fix() and rule.report() have " + "run. This is expected behavior, unless the value " + "of self.rule.ci3 has been manually set to '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 # Enable CIs self.rule.ci1.updatecurrvalue(True) self.rule.ci2.updatecurrvalue(True) # CI 3 is REMOVEX, which will remove X Windows entirely. STONIX unit # tests should generally only be run in virtual environments anyway, # but due to the severity of the changes caused by this rule, it is # disabled by default. To enable, uncomment the line below. #self.rule.ci3.updatecurrvalue(True) # Ensure GUI logon is enabled self.myos = self.environ.getostype().lower() self.logdispatch.log(LogPriority.DEBUG, self.myos) if os.path.exists("/bin/systemctl"): cmd = ["systemctl", "set-default", "graphical.target"] if not self.ch.executeCommand(cmd): success = False elif re.search("debian", self.myos): if not self.sh.enableservice("gdm3"): if not self.sh.enableservice("gdm"): if not self.sh.enableservice("kdm"): if not self.sh.enableservice("xdm"): if not self.sh.enableservice("lightdm"): success = False elif re.search("ubuntu", self.myos): ldmover = "/etc/init/lightdm.override" grub = "/etc/default/grub" if os.path.exists(ldmover): if not os.remove(ldmover): success = False if os.path.exists(grub): tmppath = grub + ".tmp" data = {"GRUB_CMDLINE_LINUX_DEFAULT": '"quiet splash"'} editor = KVEditorStonix(self.statechglogger, self.logdispatch, "conf", grub, tmppath, data, "present", "closedeq") editor.report() if editor.fixables: if editor.fix(): if not editor.commit(): success = False else: success = False else: inittab = "/etc/inittab" if not os.path.exists(inittab): self.logdispatch.log( LogPriority.ERROR, inittab + " not found, init system unknown") 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 zzzTestRuleInstallCasperSuite(RuleTest): def setUp(self): """ Perform this task before running any of the tests in this class @author: Roy Nielsen """ RuleTest.setUp(self) self.rule = InstallCasperSuite(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.pkgr = MacPkgr(self.environ, self.logdispatch) self.pkgUrl = self.rule.reporoot + self.rule.package message = "Reporoot: " + str(self.rule.reporoot) self.logdispatch.log(LogPriority.DEBUG, message) self.connection = Connectivity(self.logdispatch) ########################################################################### def tearDown(self): pass ########################################################################### def test_defaultOsInstall(self): """ Test as if testing on a default OS install. May result initial report pass, which would not run Fix mode. @author: Roy Nielsen """ ##### # Ensure the system is set as the default install would be set for this # OS self.removeJamfFramework() ##### # Run simpleRuleTest self.simpleRuleTest() ##### # Validate successful final state self.checkForBadInstallation() ########################################################################### def test_wrongSystemSettings(self): """ Initial state for this test is set up to fail initial report run, forcing a fix run. @author: Roy Nielsen """ ##### # Put the system in a known bad state, then run the simpleRuleTest self.removeJamfFramework() ##### # Run simpleRuleTest self.simpleRuleTest() ##### # Validate successful final state self.checkForBadInstallation() ########################################################################### def test_correctSystemSettigns(self): """ Only report should run. @author: Roy Nielsen """ ##### # Put the system in a known good state, then run the simpleRuleTest ##### # If there is a network connection, install, otherwise just log hasconnection = self.connection.isPageAvailable(self.pkgUrl) if hasconnection: msg = "Connected to " + str(self.rule.package) self.logdispatch.log(LogPriority.DEBUG, msg) ##### # Install the package if self.pkgr.installPackage(self.rule.package): self.rulesuccess = True self.rule.touch_imaged() ##### # Run simpleRuleTest self.simpleRuleTest() ##### # Validate successful final state self.checkForSuccessfullInstallation() ########################################################################### def test_resultAppend(self): """ Test the unique rule method "resultAppend". @author: Roy Nielsen """ ##### # First test: # test the string case # self.detailedresults = string # passing in string self.rule.detailedresults = "Snow season looks good this year..." string_to_append = "The End" self.rule.resultAppend("The End") self.logdispatch.log(LogPriority.DEBUG, "results: " + str(self.rule.detailedresults)) self.assertTrue( re.search("%s" % string_to_append, self.rule.detailedresults)) ##### # second test: # test the first list case # self.detailedresults = list # passing in string self.rule.detailedresults = ["Snow season looks good this year..."] string_to_append = "The End" ##### ##### # Note here - we're not testing right, but the code passes test. # assertRasis isn't the right assert to be using self.assertRaises(TypeError, self.rule.resultAppend, string_to_append) ##### # Third test: # test the second list case # self.detailedresults = list # passing in list self.rule.detailedresults = ["Snow season looks good this year..."] list_to_append = ["The End"] ##### ##### # Note here - we're not testing right, but the code passes test. # assertRasis isn't the right assert to be using self.assertRaises(TypeError, self.rule.resultAppend, list_to_append) ##### # fourth test: # test the first "else" case # self.detailedresults = string # passing in boolean self.rule.detailedresults = "Snow season looks good this year..." ##### ##### # Note - assertRaises is being correctly used here self.assertRaises(TypeError, self.rule.resultAppend, False) ##### # fifth test: # test the second "else" case # self.detailedresults = list # passing in False self.rule.detailedresults = ["Snow season looks good this year..."] ##### ##### # Note - assertRaises is being correctly used here self.assertRaises(TypeError, self.rule.resultAppend, False) ##### # sixth test: # test the first "else" case # self.detailedresults = string # passing in None self.rule.detailedresults = "Snow season looks good this year..." ##### ##### # Note - assertRaises is being correctly used here self.assertRaises(TypeError, self.rule.resultAppend, None) ##### # seventh test: # test the second "else" case # self.detailedresults = list # passing in None self.rule.detailedresults = ["Snow season looks good this year..."] ##### ##### # Note - assertRaises is being correctly used here self.assertRaises(TypeError, self.rule.resultAppend, None) ##### ##### # Note, we are not testing the passing in of every python type... # Be careful when choosing a representative selection of tests, # as critical tests might be missed. # # In this case, if another valid case is found, a test can be added # that will test that specific case, or class of cases. # # Testing is an iterative process. # ########################################################################### def test_touch_imaged(self): """ Test the unique rule method "touch_imaged". The touched_imaged method is not dependent of any other methods, so it can be tested atomically. @author: Roy Nielsen """ sig1 = "/etc/dds.txt" sig2 = "/var/log/dds.log" ##### # Check for the existence of the first signature file, remove it if it # exists if os.path.exists(sig1): os.unlink(sig1) foundSig1 = True else: foundSig1 = False ##### # Check for the existence of the second signature file, remove it if it # exists if os.path.exists(sig2): os.unlink(sig2) foundSig2 = True else: foundSig2 = False ##### # Call the method self.rule.touch_imaged() ##### # Check for the first file system signature success_a = os.path.isfile("/etc/dds.txt") self.logdispatch.log(LogPriority.DEBUG, "Found first signature file...") self.assertTrue(success_a) ##### # Check for the Second file system signature success_b = os.path.isfile("/var/log/dds.log") self.logdispatch.log(LogPriority.DEBUG, "Found second signature file..") self.assertTrue(success_b) self.assertTrue(success_a and success_b) ##### # If the files didn't exist at the beginning of the test, remove them. if not foundSig1: os.unlink(sig1) if not foundSig2: os.unlink(sig2) ########################################################################### def checkForSuccessfullInstallation(self): """ Check for successfull test run. Specifically what needs to have happened after a successfull run. IE: must satisfy ALL conditions. @author: Roy Nielsen """ ##### # Check for existence of jamf binary success = os.path.isfile("/usr/local/bin/jamf") self.logdispatch.log(LogPriority.DEBUG, "Found the jamf binary..") self.assertTrue(success) ##### # Check for the existence of the LANL Self Service.app success = os.path.isdir("/Applications/LANL Self Service.app") self.logdispatch.log( LogPriority.DEBUG, "Found result: " + str(success) + " Lanl Self Service.app") self.assertTrue(success) ##### # Check for the first file system signature success = os.path.isfile("/etc/dds.txt") self.logdispatch.log(LogPriority.DEBUG, "Found first sig file...") self.assertTrue(success) ##### # Check for the Second file system signature success = os.path.isfile("/var/log/dds.log") self.logdispatch.log(LogPriority.DEBUG, "Found second sig file...") self.assertTrue(success) ##### # Check to make sure the "jamf recon" command works cmd = ["/usr/local/bin/jamf", "recon"] self.ch.executeCommand(cmd) return_code = self.ch.getReturnCode() self.logdispatch.log( LogPriority.DEBUG, "Return code from jamf " + " recon command: " + str(return_code)) self.assertEqual(str(0), str(return_code)) ########################################################################### def checkForBadInstallation(self): """ Check for UNsuccessfull test run. IE: must fail any of the following conditions. Needs fuzzing applied, or variation on inputs to prove the variation works as expected. @Note: Running of the "/usr/local/bin/jamf recon" command is not executed in this test, as that functionality has already been tested. The other variables need to be "fuzzed". IE, run every combination of the variables tested in this test. @author: Roy Nielsen """ ##### # Check if any of the following are false. At least one must be false. success_a = os.path.isfile("/usr/local/bin/jamf") success_b = os.path.isdir("/Applications/LANL Self Service.app") success_c = os.path.isfile("/etc/dds.txt") success_d = os.path.isfile("/var/log/dds.log") ##### # If any of these success parameters are false, the test fails self.assertTrue( success_a and success_b and success_c and success_d, "Could not find all files and directories " + "associated with a successful Casper installation") ##### # Future testing needs to perform "fuzzing" - automated or auto # generated input testing # -- # for every combination of inputs assert the correct outputs # # - at least one case is missing in this method - making sure to also # test for the existence of the Jamf plist. # ########################################################################### 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 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) + ".") if pRuleSuccess: success = True else: success = False 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) + ".") if pRuleSuccess: success = True else: success = False return success ########################################################################### def removeJamfFramework(self): """ Remove the jamf framework for setting initial conditions.. @NOTE: There are many ways that a jamf install can be broken, This tests a clean uninstall. Partial or broken installs are not covered in this test, however it may be a good idea to test for this in the future. @author: Roy Nielsen """ success = False jamf_path = "/usr/local/bin/jamf" if os.path.exists(jamf_path): cmd = [jamf_path, "removeFramework"] self.ch.executeCommand(cmd) output = self.ch.getOutputString().split("\n") self.logdispatch.log(LogPriority.DEBUG, output) if self.ch.getReturnCode() == 0: success = True else: 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 zzzTestRuleConfigureLoginWindow(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = ConfigureLoginWindow(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.dc = "/usr/bin/defaults" def tearDown(self): pass def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): ''' This makes sure the intial report fails by executing the following commands: defaults -currentHost write /Library/Preferences/com.apple.loginwindow SHOWFULLNAME -bool yes defaults -currentHost delete /Library/Preferences/com.apple.loginwindow DisableConsoleAccess @param self: essential if you override this definition @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' success = True if success: command = [ self.dc, "-currentHost", "write", "/Library/Preferences/com.apple.loginwindow", "SHOWFULLNAME", "-bool", "yes" ] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [ self.dc, "-currentHost", "delete", "/Library/Preferences/com.apple.loginwindow", "DisableConsoleAccess" ] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: success = self.checkReportForRule(False, True) return success def checkReportForRule(self, pCompliance, pRuleSuccess): ''' To see what happended run these commans: defaults -currentHost read /Library/Preferences/com.apple.loginwindow SHOWFULLNAME @param self: essential if you override this definition @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 if success: command = [ self.dc, "-currentHost", "read", "/Library/Preferences/com.apple.loginwindow", "SHOWFULLNAME" ] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [ self.dc, "-currentHost", "read", "/Library/Preferences/com.apple.loginwindow", "DisableConsoleAccess" ] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) return success def checkFixForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = self.checkReportForRule(True, pRuleSuccess) return success def checkUndoForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = self.checkReportForRule(False, pRuleSuccess) return success
class zzzTestRuleDisableOpenSafeSafari(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = DisableOpenSafeSafari(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.dc = "/usr/bin/defaults" self.path = "com.apple.Safari" self.key = "AutoOpenSafeDownloads" def tearDown(self): pass def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): '''This makes sure the intial report fails by executing the following commands: defaults write com.apple.Safari AutoOpenSafeDownloads -bool yes :param self: essential if you override this definition :returns: boolean - If successful True; If failure False @author: dwalker ''' success = False cmd = [self.dc, "write", self.path, self.key, "-bool", "yes"] self.logdispatch.log(LogPriority.DEBUG, str(cmd)) if self.ch.executeCommand(cmd): success = self.checkReportForRule(False, True) return success def checkReportForRule(self, pCompliance, pRuleSuccess): '''To see what happended run these commands: defaults read com.apple.Safari AutoOpenSafeDownloads :param self: essential if you override this definition :param pCompliance: :param pRuleSuccess: :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' success = True self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + \ str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") cmd = [self.dc, "read", self.path, self.key] self.logdispatch.log(LogPriority.DEBUG, str(cmd)) if self.ch.executeCommand(cmd): output = self.ch.getOutputString() return success def checkFixForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = self.checkReportForRule(True, pRuleSuccess) return success def checkUndoForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = self.checkReportForRule(False, pRuleSuccess) return success
class zzzTestRuleDisableCloudServices(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = DisableCloudServices(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(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 :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' success = True if self.environ.getosfamily() == "darwin": command = [ "/usr/bin/defaults", "-currentHost", "write", "NSGlobalDomain", "NSDocumentSaveNewDocumentsToCloud", "-bool", "yes" ] success = self.ch.executeCommand(command) else: ph = Pkghelper(self.logdispatch, self.environ) success = ph.install("unity-lens-shopping") 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 zzzTestRuleNoCachedFDEKeys(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = NoCachedFDEKeys(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(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: ekkehard j. koch ''' success = True cmd = "/usr/bin/pmset -a destroyfvkeyonstandby 0" if not self.ch.executeCommand(cmd): 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 zzzTestDisableAFPFileSharing(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = DisableAFPFileSharing(self.config, self.environ, self.logdispatch, self.statechglogger) self.cmdhelper = CommandHelper(self.logdispatch) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber 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: Breen Malmberg ''' success = True try: afpfile = '/System/Library/LaunchDaemons/com.apple.AppleFileSharing.plist' cmd = 'defaults write ' + afpfile + ' Disabled -bool False' self.cmdhelper.executeCommand(cmd) errout = self.cmdhelper.getErrorString() if errout: success = False except Exception: raise 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 zzzTestRuleDisableIRReceiver(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = DisableIRReceiver(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.dc = "/usr/bin/defaults" def tearDown(self): pass def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): ''' This makes sure the intial report fails by executing the following commands: defaults -currentHost write /Library/Preferences/com.apple.driver.AppleIRController.plist -bool yes @param self: essential if you override this definition @return: boolean - If successful True; If failure False @author: ekkehard j. koch ''' success = True if success: command = [self.dc, "-currentHost", "write", "/Library/Preferences/com.apple.driver.AppleIRController.plist", "DeviceEnabled", "-bool", "yes"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: success = self.checkReportForRule(False, True) return success def checkReportForRule(self, pCompliance, pRuleSuccess): ''' To see what happended run these commans: defaults -currentHost read /Library/Preferences/com.apple.driver.AppleIRController.plist @param self: essential if you override this definition @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 if success: command = [self.dc, "-currentHost", "read", "/Library/Preferences/com.apple.driver.AppleIRController.plist", "DeviceEnabled"] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) return success def checkFixForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = self.checkReportForRule(True, pRuleSuccess) return success def checkUndoForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = self.checkReportForRule(False, pRuleSuccess) return success
class zzzTestRuleDisableCloudServices(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = DisableCloudServices(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(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: ekkehard j. koch ''' success = True if self.environ.getosfamily() == "darwin": command = ["/usr/bin/defaults", "-currentHost", "write", "NSGlobalDomain", "NSDocumentSaveNewDocumentsToCloud", "-bool", "yes"] success = self.ch.executeCommand(command) else: ph = Pkghelper(self.logdispatch, self.environ) success = ph.install("unity-lens-shopping") 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 zzzTestRuleSetSSCorners(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = SetSSCorners(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(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: Breen Malmberg ''' success = True self.cmdhelper = CommandHelper(self.logdispatch) optdict = {"wvous-tr-corner": 6} cmd = 'defaults write ' + '\"' + self.environ.geteuidhome() + '/Library/Preferences/com.apple.dock.plist\" ' for item in optdict: self.cmdhelper.executeCommand(cmd + item + ' -int ' + str(optdict[item])) errout = self.cmdhelper.getErrorString() if errout: 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: 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 @return: 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 @return: boolean - If successful True; If failure False @author: Breen Malmberg ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = True return success
class zzzTestRuleNoCoreDumps(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = NoCoreDumps(self.config, self.environ, self.logdispatch, self.statechglogger) self.logger = self.logdispatch self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.checkUndo = True self.ch = CommandHelper(self.logger) 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.getosfamily() == "linux": if not self.setLinuxConditions(): success = False elif self.environ.getostype() == "mac": if not self.setMacConditions(): success = False return success def setMacConditions(self): success = True self.ch.executeCommand("/usr/bin/launchctl limit core") retcode = self.ch.getReturnCode() if retcode != 0: self.detailedresults += "\nFailed to run launchctl command to get current value of core dumps configuration" errmsg = self.ch.getErrorString() self.logger.log(LogPriority.DEBUG, errmsg) else: output = self.ch.getOutputString() if output: if not re.search("1", output): self.ch.executeCommand("/usr/bin/launchctl limit core 1 1") def setLinuxConditions(self): success = True path1 = "/etc/security/limits.conf" if os.path.exists(path1): lookfor1 = "(^\*)\s+hard\s+core\s+0?" contents = readFile(path1, self.logger) if contents: tempstring = "" for line in contents: if not re.search(lookfor1, line.strip()): tempstring += line if not writeFile(path1, tempstring, self.logger): debug = "unable to write incorrect contents to " + path1 + "\n" self.logger.log(LogPriority.DEBUG, debug) success = False if checkPerms(path1, [0, 0, 0o644], self.logger): if not setPerms(path1, [0, 0, 0o777], self.logger): debug = "Unable to set incorrect permissions on " + path1 + "\n" self.logger.log(LogPriority.DEBUG, debug) success = False else: debug = "successfully set incorrect permissions on " + path1 + "\n" self.logger.log(LogPriority.DEBUG, debug) self.ch.executeCommand("/sbin/sysctl fs.suid_dumpable") retcode = self.ch.getReturnCode() if retcode != 0: self.detailedresults += "Failed to get value of core dumps configuration with sysctl command\n" errmsg = self.ch.getErrorString() self.logger.log(LogPriority.DEBUG, errmsg) success = False else: output = self.ch.getOutputString() if output.strip() != "fs.suid_dumpable = 1": if not self.ch.executeCommand("/sbin/sysctl -w fs.suid_dumpable=1"): debug = "Unable to set incorrect value for fs.suid_dumpable" self.logger.log(LogPriority.DEBUG, debug) success = False elif not self.ch.executeCommand("/sbin/sysctl -p"): debug = "Unable to set incorrect value for fs.suid_dumpable" self.logger.log(LogPriority.DEBUG, debug) 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