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 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!")
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)
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!")
def setUp(self): ''' ''' self.enviro = Environment() self.enviro.setdebugmode(True) self.logger = LogDispatcher(self.enviro) self.commandhelper = CommandHelper(self.logger)
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 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 setUp(self): RuleTest.setUp(self) self.rule = DisableGuestAccess(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 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 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)
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 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 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 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 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 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 setUp(self): RuleTest.setUp(self) self.rule = SetNTP(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.ss = "/usr/sbin/systemsetup"
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 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 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 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 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 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 setUp(self): RuleTest.setUp(self) self.rule = STIGConfigureApplicationRestrictionsPolicy(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.Application_Restrictions.alacarte" self.rule.profile = "/Users/vagrant/stonix/src/stonix_resources/files/" + \ "U_Apple_OS_X_10-11_V1R1_STIG_Application_Restrictions_Policy.mobileconfig"
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 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 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 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 setUp(self): RuleTest.setUp(self) self.rule = STIGConfigureBluetoothPolicy(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 = '\"Bluetooth Policy\"' if search("10\.11\.*", self.environ.getosver()): self.rule.profile = "/Users/vagrant/stonix/src/stonix_resources/files/" + \ "U_Apple_OS_X_10-11_V1R1_STIG_Bluetooth_Policy.mobileconfig" else: self.rule.profile = "/Users/vagrant/stonix/src/stonix_resources/files/" + \ "U_Apple_macOS_10-12_V1R1_STIG_Bluetooth_Policy.mobileconfig"
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
def setUp(self): self.enviro = Environment() self.enviro.setdebugmode(True) self.logger = LogDispatcher(self.enviro) self.commandhelper = CommandHelper(self.logger)
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 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 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 zzzTestRuleConfigureDiagnosticReporting(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = ConfigureDiagnosticReporting(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 initial report fails :param self: essential if you override this definition :returns: boolean - If successful True; If failure False @author: Eric Ball ''' success = True if success: command = [ self.dc, "write", "/Library/Application Support/" + "CrashReporter/DiagnosticMessagesHistory.plist", "AutoSubmit", "-bool", "yes" ] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: version = self.environ.getosver() versionsplit = version.split(".") if len(versionsplit) >= 2: minorversion = int(versionsplit[1]) else: minorversion = 0 if minorversion >= 10: command = [ self.dc, "write", "/Library/Application Support/" + "CrashReporter/DiagnosticMessagesHistory.plist", "ThirdPartyDataSubmit", "-bool", "yes" ] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) 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 zzzTestRuleDisableMediaAutomaticActions(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = DisableMediaAutomaticActions(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.digihub com.apple.digihub.blank.cd.appeared defaults -currentHost delete /Library/Preferences/com.apple.digihub com.apple.digihub.blank.dvd.appeared defaults -currentHost delete /Library/Preferences/com.apple.digihub com.apple.digihub.cd.picture.appeared defaults -currentHost delete /Library/Preferences/com.apple.digihub com.apple.digihub.dvd.video.appeared :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.digihub", "com.apple.digihub.blank.cd.appeared" ] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [ self.dc, "-currentHost", "delete", "/Library/Preferences/com.apple.digihub", "com.apple.digihub.blank.dvd.appeared" ] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [ self.dc, "-currentHost", "delete", "/Library/Preferences/com.apple.digihub", "com.apple.digihub.cd.picture.appeared" ] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [ self.dc, "-currentHost", "delete", "/Library/Preferences/com.apple.digihub", "com.apple.digihub.dvd.video.appeared" ] 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 commands: defaults -currentHost read /Library/Preferences/com.apple.digihub com.apple.digihub.blank.cd.appeared defaults -currentHost read /Library/Preferences/com.apple.digihub com.apple.digihub.blank.dvd.appeared defaults -currentHost read /Library/Preferences/com.apple.digihub com.apple.digihub.cd.picture.appeared defaults -currentHost read /Library/Preferences/com.apple.digihub com.apple.digihub.dvd.video.appeared :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/com.apple.digihub", "com.apple.digihub.blank.cd.appeared" ] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [ self.dc, "-currentHost", "read", "/Library/Preferences/com.apple.digihub", "com.apple.digihub.blank.dvd.appeared" ] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [ self.dc, "-currentHost", "read", "/Library/Preferences/com.apple.digihub", "com.apple.digihub.cd.picture.appeared" ] self.logdispatch.log(LogPriority.DEBUG, str(command)) success = self.ch.executeCommand(command) if success: command = [ self.dc, "-currentHost", "read", "/Library/Preferences/com.apple.digihub", "com.apple.digihub.dvd.video.appeared" ] 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 zzzTestFrameworkmacbuild(unittest.TestCase): def setUp(self): self.enviro = Environment() self.enviro.setdebugmode(True) self.logger = LogDispatcher(self.enviro) self.ch = CommandHelper(self.logger) self.changedDir = False # stonixtest must currently be run from the stonixroot directory, so # that is the best bet for the cwd if os.path.exists("src/Macbuild"): os.chdir("src/Macbuild") self.changedDir = True # Cannot guarantee that test will end in self.myDir = os.getcwd() # this dir, so we record it first self.mb = build.SoftwareBuilder(options=optparse.Values({ "compileGui": True, "version": "0.dev-UT", "clean": False, "test": True })) def tearDown(self): if self.changedDir: os.chdir(self.myDir) self.ch.executeCommand(["./build.py", "-c"]) os.chdir("../..") def testSetupAndDetachRamdisk(self): path = "/tmp/mount_ramdisk_for_ut" if os.path.exists(path): rmtree(path) os.mkdir(path) device = self.mb.setupRamdisk(512, path) self.assertRegex(device, "/dev/disk\d+", "Unexpected return from setupRamdisk") self.assertTrue(self.mb.detachRamdisk(device), "Did not successfully detach ramdisk") def testExitMethod(self): ramdiskPath = "/tmp/mount_ramdisk_for_ut" luggagePath = "/tmp/luggage_ramdisk_for_ut" ramdisk = self.mb.setupRamdisk(1024, ramdiskPath) luggage = self.mb.setupRamdisk(1024, luggagePath) self.assertRaises(SystemExit, self.mb.exit, ramdisk, luggage, 999) def testCompileStonix4MacAppUiFilesMethod(self): self.mb.compileStonix4MacAppUiFiles("./stonix4mac") try: adminCred = open("stonix4mac/admin_credentials_ui.py", "r").read() stonixWrapper = open("stonix4mac/stonix_wrapper_ui.py", "r").read() generalWarning = open("stonix4mac/general_warning_ui.py", "r").read() except OSError: self.assertTrue(False, "One or more UI files could not be found") else: self.assertTrue(adminCred, "admin_credentials_ui.py file is empty") self.assertTrue(stonixWrapper, "stonix_wrapper_ui.py file is empty") self.assertTrue(generalWarning, "general_warning_ui.py file is empty") self.assertRaises(OSError, self.mb.compileStonix4MacAppUiFiles, "thisdirdoesnotexist") def testSetProgramArgumentsVersionMethod(self): path = "../stonix_resources/localize.py" self.mb.setProgramArgumentsVersion(path) version = self.mb.APPVERSION localizeContents = open(path, "r").read() self.assertTrue(re.search(version, localizeContents), "Could not find correct version in localize.py") self.assertRaises(IOError, self.mb.setProgramArgumentsVersion, "badpath.py") def testPrepStonixBuildMethod(self): self.mb.prepStonixBuild(".") stonixDirList = os.listdir("stonix") self.assertTrue(stonixDirList, "No files found in stonix directory") self.assertRaises(OSError, self.mb.prepStonixBuild, "thisdirisfake") def testDriverAndBuildMethods(self): # Due to issues with dependencies, several methods cannot be easily # tested as units. Therefore, the "driver" method is run, and artifacts # from each method are checked. self.mb.driver() # Check compileApp artifacts try: stonixSpec = open("stonix/stonix.spec", "r").read() stonix4macSpec = open("stonix4mac/stonix4mac.spec", "r").read() except IOError: self.assertTrue(False, "One or more spec files not found") else: self.assertTrue(stonixSpec, "stonix.spec file is empty") self.assertTrue(stonix4macSpec, "stonix4mac.spec file is empty") # Check buildStonix4MacAppResources artifacts self.assertTrue( os.path.exists("stonix4mac/dist/stonix4mac.app/" + "Contents/Resources/stonix.conf"), "Could not find stonix.conf file in package") self.assertTrue( os.path.exists("stonix4mac/dist/stonix4mac.app/" + "Contents/Resources/stonix.app"), "Could not find stonix.app in stonix4mac.app Resources") # Check buildStonix4MacAppPkg artifacts self.assertTrue(os.path.exists("dmgs/stonix4mac-0.dev-UT.pkg"), "Could not find stonix4mac pkg file")
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 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 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 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 :param userName: :param password: ''' 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 :param directory: (Default value = ".") :param action: (Default value = "") :param object: (Default value = "") :param property: (Default value = "") :param value: (Default value = "") ''' 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 :param directory: (Default value = "") :param action: (Default value = "") :param dirobj: (Default value = "") :param property: (Default value = "") ''' success = False reterr = "" retval = "" ##### # FIRST VALIDATE INPUT!! if isinstance(directory, str) and re.match("^[/\.][A-Za-z0-9/]*", directory): success = True else: success = False if isinstance(action, str) and re.match("^[-]*[a-z]+", action) and success: success = True else: success = False if isinstance(dirobj, str) and re.match("^[A-Za-z0=9/]+", dirobj) and success: success = True else: success = False if isinstance(property, str) 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 :param uid: ''' 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 :param userName: (Default value = "") ''' success = False reterr = "" if isinstance(userName, str)\ 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 :param user: (Default value = "") :param shell: (Default value = "") ''' 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 :param user: (Default value = "") :param comment: (Default value = "") ''' 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 :param user: (Default value = "") :param uid: (Default value = "") ''' 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 :param user: (Default value = "") :param priGid: (Default value = "") ''' 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 :param user: (Default value = "") :param userHome: (Default value = "") ''' 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 :param user: (Default value = "") ''' 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 :param user: (Default value = "") :param group: (Default value = "") ''' 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=""): ''' :param user: (Default value = "") :param group: (Default value = "") ''' 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 :param user: (Default value = "") :param password: (Default value = "") ''' success = False if self.isSaneUserName(user) and isinstance(password, str): 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 :param user: (Default value = "") :param password: (Default value = "") ''' pass """ self.sec = "/usr/bin/security" success = False keychainpath = "" if self.isSaneUserName(user) and isinstance(password, str): 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 :param user: (Default value = "") ''' 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 :param user: (Default value = "") ''' 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 as 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 #---------------------------------------------------------------------- def validateUser(self, userName=False, userShell=False, userComment=False, userUid=False, userPriGid=False, userHomeDir=False): '''Future functionality... validate that the passed in parameters to the class instanciation match. @author: :param userName: (Default value = False) :param userShell: (Default value = False) :param userComment: (Default value = False) :param userUid: (Default value = False) :param userPriGid: (Default value = False) :param userHomeDir: (Default value = False) ''' sane = False ##### # Look up all user attributes and check that they are accurate. # Only check the "SANE" parameters passed in. if self.isSaneUserName(userName): self.userName = userName sane = True else: raise BadUserInfoError("Need a valid user name...") if self.isSaneUserShell(userShell) and sane: self.userShell = userShell elif not userShell: pass else: sane = False if self.isSaneUserComment(userComment) and sane: self.userComment = userComment elif not userComment: pass else: sane = False if self.isSaneUserUid(str(userUid)) and sane: self.userUid = self.userUid elif not userUid: pass else: sane = False if self.isSaneUserPriGid(str(userPriGid)) and sane: self.userUid = userUid elif not userPriGid: pass else: sane = False if self.isSaneUserHomeDir(userHomeDir) and sane: self.userHomeDir = userHomeDir elif not userHomeDir: pass else: sane = False return sane #---------------------------------------------------------------------- def getUser(self, userName=""): ''' :param userName: (Default value = "") ''' userInfo = False if self.isSaneUserName(userName): output = self.getDscl(".", "read", "/Users/" + str(userName), "RecordName") try: userInfo = output.split()[1] except (KeyError, IndexError) as err: self.logger.log(lp.INFO, "Error attempting to find user" + \ str(userName) + " in the " + \ "directory service.") else: raise BadUserInfoError("Need a valid user name...") return userInfo #---------------------------------------------------------------------- def getUserShell(self, userName=""): ''' :param userName: (Default value = "") ''' userShell = False if self.isSaneUserName(userName): output = self.getDscl(".", "read", "/Users/" + str(userName), "UserShell") try: userShell = output.split()[1] except (KeyError, IndexError) as err: self.logger.log(lp.INFO, "Error attempting to find user" + \ str(userName) + " in the " + \ "directory service.") else: raise BadUserInfoError("Need a valid user name...") return userShell #---------------------------------------------------------------------- def getUserComment(self, userName=""): ''' :param userName: (Default value = "") ''' userComment = False if self.isSaneUserName(userName): ##### # Need to process the output to get the right information due to a # spurrious "\n" in the output output = self.getDscl(".", "read", "/Users/" + str(userName), "RealName") try: userComment = output[1] except (KeyError, IndexError) as err: self.logger.log(lp.INFO, "Error attempting to find user" + \ str(userName) + " in the " + \ "directory service.") else: raise BadUserInfoError("Need a valid user name...") return userComment #---------------------------------------------------------------------- def getUserUid(self, userName=""): ''' :param userName: (Default value = "") ''' userUid = False if self.isSaneUserName(userName): output = self.getDscl(".", "read", "/Users/" + str(userName), "UniqueID") ##### # Process to get out the right information.... try: userUid = output.split()[1] except (KeyError, IndexError) as err: self.logger.log(lp.INFO, "Error attempting to find user" + \ str(userName) + " in the " + \ "directory service.") else: raise BadUserInfoError("Need a valid user name...") return userUid #---------------------------------------------------------------------- def getUserPriGid(self, userName=""): ''' :param userName: (Default value = "") ''' userPriGid = False if self.isSaneUserName(userName): output = self.getDscl(".", "read", "/Users/" + str(userName), "PrimaryGroupID") ##### # Process to get out the right information.... try: userPriGid = output.split()[1] except (KeyError, IndexError) as err: self.logger.log(lp.INFO, "Error attempting to find user" + \ str(userName) + " in the " + \ "directory service.") else: raise BadUserInfoError("Need a valid user name...") return userPriGid #---------------------------------------------------------------------- def getUserHomeDir(self, userName=""): ''' :param userName: (Default value = "") ''' userHomeDir = False if self.isSaneUserName(userName): output = self.getDscl(".", "read", "/Users/" + str(userName), "NFSHomeDirectory") ##### # Process to get out the right information.... try: userHomeDir = output.split()[1] except (KeyError, IndexError) as err: self.logger.log(lp.INFO, "Error attempting to find user" + \ str(userName) + " in the " + \ "directory service.") else: raise BadUserInfoError("Need a valid user name...") return userHomeDir #---------------------------------------------------------------------- def isUserInstalled(self, user=""): '''Check if the user "user" is installed @author Roy Nielsen :param user: (Default value = "") ''' success = False if self.isSaneUserName(user): cmd = [self.dscl, ".", "-read", "/Users/" + str(user)] self.runWith.setCommand(cmd) self.runWith.communicate() retval, reterr, retcode = self.runWith.getNlogReturns() if not reterr: success = True return success #---------------------------------------------------------------------- def isUserInGroup(self, userName="", groupName=""): '''Check if this user is in this group @author: Roy Nielsen :param userName: (Default value = "") :param groupName: (Default value = "") ''' success = False if self.isSaneUserName(userName) and self.isSaneGroupName(groupName): output = self.getDscl(".", "read", "/Groups/" + groupName, "users") users = output.split()[:-1] if userName in users: success = True return success #---------------------------------------------------------------------- def fixUserHome(self, userName=""): '''Get the user information from the local directory and fix the user ownership and group of the user's home directory to reflect what is in the local directory service. @author: Roy Nielsen :param userName: (Default value = "") ''' success = False if self.isSaneUserName(userName): ##### # Acquire the user data based on the username first. try: userUid = self.getUserUid(userName) userPriGid = self.getUserPriGid(userName) userHomeDir = self.getUserHomeDir(userName) except BadUserInfoError as err: self.logger.log(lp.INFO, "Exception trying to find: \"" + \ str(userName) + "\" user information") self.logger.log(lp.INFO, "err: " + str(err)) else: success = True if success: try: for root, dirs, files in os.walk(userHomeDir): for d in dirs: os.chown(os.path.join(root, d), userUid, userPriGid) for f in files: os.chown(os.path.join(root, d, f), userUid, userPriGid) except: success = False self.logger.log(lp.INFO, "Exception attempting to chown...") raise err else: 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.logger = self.logdispatch 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 :returns: 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) else: success1 = self.setkde() if self.effectiveUserID == 0: success2 = self.setgnome() else: success2 = True if success1 and success2: success = True else: success = False return success def setkde(self): '''Method to setup kde desktop to not be compliant @author: dwalker :returns: bool ''' self.kdeprops = {"ScreenSaver": {"Enabled": "true", "Lock": "true", "LockGrace": "60000", "Timeout": "840"}} self.kderuin = [] debug = "Inside setkde method" success = True bindir = glob("/usr/bin/kde*") kdefound = False for kdefile in bindir: if re.search("^/usr/bin/kde\d$", str(kdefile)): kdefound = True if kdefound and self.environ.geteuid() == 0: contents = readFile("/etc/passwd", self.logger) if not contents: debug += "You have some serious issues, /etc/passwd is blank\n" self.logger.log(LogPriority.ERROR, debug) return False for line in contents: temp = line.split(":") try: if int(temp[2]) >= 500: if temp[5] and re.search('/', temp[5]): homebase = temp[5] if not re.search("^/home/", homebase): continue kfile = homebase + "/.kde/share/config/kscreensaverrc" if os.path.exists(kfile): uid = getpwnam(temp[0])[2] gid = getpwnam(temp[0])[3] if checkPerms(kfile, [uid, gid, 0o600], self.logger): if not setPerms(kfile, [0, 0, 0o644], self.logger): success = False debug += "Unable to set incorrect perms " + \ "on " + kfile + " for testing\n" if not self.wreckFile(kfile): debug += "Was not able to mess " + \ "up file for testing\n" success = False else: debug += "placeholder 6 in /etc/passwd is not a \ directory, invalid form of /etc/passwd" self.logger.log(LogPriority.ERROR, debug) return False except IndexError: success = False debug += traceback.format_exc() + "\n" debug += "Index out of range\n" self.logger.log(LogPriority.ERROR, debug) break except Exception: break elif kdefound: who = "/usr/bin/whoami" message = Popen(who, stdout=PIPE, shell=False) info = message.stdout.read().strip() contents = readFile('/etc/passwd', self.logger) if not contents: debug += "You have some serious issues, /etc/passwd is blank\n" self.logger.log(LogPriority.ERROR, debug) return False compliant = True for line in contents: temp = line.split(':') try: if temp[0] == info: if temp[5] and re.search('/', temp[5]): homebase = temp[5] if not re.search("^/home/", homebase): continue kfile = homebase + "/.kde/share/config/kscreensaverrc" if os.path.exists(kfile): uid = getpwnam(temp[0])[2] gid = getpwnam(temp[0])[3] if checkPerms(kfile, [uid, gid, 0o600], self.logger): if not setPerms(kfile, [0, 0, 0o644], self.logger): success = False debug += "Unable to set incorrect perms " + \ "on " + kfile + " for testing\n" if not self.wreckFile(kfile): debug += "Was not able to mess " + \ "up file for testing\n" success = False else: debug += "placeholder 6 in /etc/passwd is not a \ directory, invalid form of /etc/passwd" self.logger.log(LogPriority.ERROR, debug) return False break except IndexError: success = False debug += traceback.format_exc() + "\n" debug += "Index out of range\n" self.logger.log(LogPriority.ERROR, debug) self.detailedresults += "Unexpected formatting in " + \ "/etc/passwd" break except Exception: debug += traceback.format_exc() + "\n" self.logger.log(LogPriority.ERROR, debug) break return success def setgnome(self): '''Method to setup gnome desktop to not be compliant @author: dwalker :returns: bool ''' success = True debug = "Inside setgnome method\n" gconf = "/usr/bin/gconftool-2" gsettings = "/usr/bin/gsettings" dconfsettingslock = "/etc/dconf/db/local.d/locks/stonix-settings.conf" dconflockdata = ["/org/gnome/desktop/session/idle-delay", "/org/gnome/desktop/screensaver/idle-activation-enabled", "/org/gnome/desktop/screensaver/lock-enabled", "/org/gnome/desktop/screensaver/lock-delay", "/org/gnome/desktop/screensaver/picture-uri"] dconfsettings = "/etc/dconf/db/local.d/local.key" dconfdata = {"org/gnome/desktop/screensaver": { "idle-activation-enabled": "true", "lock-enabled": "true", "lock-delay": "0", "picture-opacity": "100", "picture-uri": "\'\'"}, "org/gnome/desktop/session": { "idle-delay": "uint32 900"}} dconfuserprofile = "/etc/dconf/profile/user" userprofilecontent = "user-db:user\n" + \ "system-db:local" if os.path.exists(gconf): setcmds1 = ["/apps/gnome-screensaver/idle_activation_enabled false", "/apps/gnome-screensaver/lock_enabled false"] setcmds2 = "/desktop/gnome/session/idle_delay 5" for cmd in setcmds1: cmd2 = gconf + " --type bool --set " + cmd if not self.ch.executeCommand(cmd2): success = False debug += "Issues setting " + cmd2 + "\n" cmd2 = gconf + " --type int --set " + setcmds2 if not self.ch.executeCommand(cmd2): success = False debug += "Issues setting " + cmd2 + "\n" if os.path.exists(gsettings): # delete lock file so that if os.path.exists(dconfsettingslock): os.remove(dconfsettingslock) cmd = "/usr/bin/dconf update" self.ch.executeCommand(cmd) setcmds = [" set org.gnome.desktop.screensaver " + "idle-activation-enabled false", " set org.gnome.desktop.screensaver lock-enabled false", " set org.gnome.desktop.screensaver lock-delay 10", " set org.gnome.desktop.screensaver picture-opacity 50", " set org.gnome.desktop.session idle-delay 20"] for cmd in setcmds: cmd2 = gsettings + cmd if not self.ch.executeCommand(cmd2): success = False debug += "Issues setting " + cmd2 + "\n" #write correct contents to dconf lock file if os.path.exists(dconfsettings): self.kveditor = KVEditorStonix(self.statechglogger, self.logger, "tagconf", dconfsettings, dconfsettings + ".tmp", dconfdata, "notpresent", "closedeq") if not self.kveditor.report(): if not self.kveditor.fix(): success = False debug += "Unable to set incorrect contents " + \ "for " + dconfsettings + "\n" elif not self.kveditor.commit(): success = False debug += "Unable to set incorrect contents " + \ "for " + dconfsettings + "\n" # self.logger.log(LogPriority.ERROR, debug) return success def wreckFile(self, filehandle): '''Method to ensure correct contents are NOT in file for testing @author: dwalker :param filehandle: string :returns: bool ''' self.editor = "" kvt = "tagconf" intent = "notpresent" tpath = filehandle + ".tmp" conftype = "closedeq" self.editor = KVEditorStonix(self.statechglogger, self.logger, kvt, filehandle, tpath, self.kdeprops, intent, conftype) if not self.editor.report(): if self.editor.fix(): if self.editor.commit(): return True else: return False else: return False else: return 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 :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 zzzTestRuleRestrictAccessToKernelMessageBuffer(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = RestrictAccessToKernelMessageBuffer( 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 self.ch.executeCommand("sysctl -w kernel.dmesg_restrict=0") return success def test_initobjs(self): '''test initobjs method of RestrictAccessToKernelMessageBuffer''' self.rule.initobjs() self.assertFalse( self.rule.ch == None, "initobjs method should successfully initialize the command helper object self.ch within the rule." ) def test_localize(self): '''test localize method of RestrictAccessToKernelMessageBuffer''' self.rule.localize() self.assertFalse( self.rule.fixcommand == "", "localize should set the fixcommand variable to the correct command string." ) self.assertFalse( self.rule.fixcommand == None, "localize should set the fixcommand variable to the correct command string." ) self.assertFalse( self.rule.reportcommand == "", "localize should set the reportcommand variable to the correct command string." ) self.assertFalse( self.rule.reportcommand == None, "localize should set the reportcommand variable to the correct command string." ) def test_reportFalse(self): '''test report return value in case of non compliant state''' self.ch.executeCommand("sysctl -w kernel.dmesg_restrict=0") self.assertFalse( self.rule.report(), "when the kernel.dmesg_restrict option is set to 0, report should always return False" ) def test_reportTrue(self): '''test report return value in case of compliant state''' self.ch.executeCommand("sysctl -w kernel.dmesg_restrict=1") self.assertTrue( self.rule.report(), "when the kernel.dmesg_restrict option is set to 1, report should always return 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 :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + \ str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = True return success def checkFixForRule(self, pRuleSuccess): '''check on whether fix was correct :param self: essential if you override this definition :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = True return success def checkUndoForRule(self, pRuleSuccess): '''check on whether undo was correct :param self: essential if you override this definition :param pRuleSuccess: did report run successfully :returns: boolean - If successful True; If failure False @author: ekkehard j. koch ''' self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") success = True return success
class zzzTestRuleAuditFirefoxUsage(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = AuditFirefoxUsage(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rulenumber = self.rule.rulenumber self.ch = CommandHelper(self.logdispatch) self.ph = Pkghelper(self.logdispatch, self.environ) self.initMozDir = False self.moveMozDir = False self.mozPath = "/root/.mozilla/firefox" self.profilePath = "/root/.mozilla/firefox/profiles.ini" def tearDown(self): mozPath = self.mozPath if self.initMozDir and os.path.exists(mozPath): shutil.rmtree(mozPath) elif self.moveMozDir: if os.path.exists(mozPath): shutil.rmtree(mozPath) if os.path.exists(mozPath + ".stonixtmp"): os.rename(mozPath + ".stonixtmp", mozPath) def runTest(self): profilePath = self.profilePath if self.ph.check("firefox"): self.browser = "/usr/bin/firefox" self.setConditionsForRule() # setConditionsForRule will not work on a remote terminal. If the # path doesn't exist, we will skip the test. if os.path.exists(profilePath): self.assertFalse( self.rule.report(), "Report was not false " + "after test conditions were set") else: self.logdispatch.log( LogPriority.DEBUG, "Firefox directory was not created. " + "Skipping test.") elif self.ph.check("iceweasel"): self.browser = "/usr/bin/iceweasel" self.setConditionsForRule() # setConditionsForRule will not work on a remote terminal. If the # path doesn't exist, we will skip the test. if os.path.exists(profilePath): self.assertFalse( self.rule.report(), "Report was not false " + "after test conditions were set") else: self.logdispatch.log( LogPriority.DEBUG, "Firefox directory was not created. " + "Skipping test.") else: debug = "Firefox not installed. Unit test will not make " + \ "any changes." self.logdispatch.log(LogPriority.DEBUG, debug) return True def setConditionsForRule(self): '''Configure system for the unit test :param self: essential if you override this definition :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 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 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) 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 = ["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 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 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 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 zzzTestRuleConfigurePasswordProfile(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = ConfigurePasswordProfile(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): success = True cmd = ["/usr/bin/profiles", "-L"] 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 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 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 zzzTestRuleDisableThumbnailers(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = DisableThumbnailers(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 self.gconf = "/usr/bin/gconftool-2" cmd = self.gconf + " --direct --config-source " + \ "xml:readwrite:/etc/gconf/gconf.xml.mandatory " + \ "--type bool --set " + \ "/desktop/gnome/thumbnailers/disable_all false" 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 zzzTestRuleSTIGConfigureRestrictionsPolicy(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = STIGConfigureRestrictionsPolicy(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.Restrictions.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_Restrictions_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_Restrictions_Policy.mobileconfig" else: self.rule.profile = "/Users/vagrant/stonix/src/stonix_resources/files/" + \ "U_Apple_macOS_10-12_V1R1_STIG_Restrictions_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\.Restrictions\.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 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 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.identifier = "041AD784-F0E2-40F5-9433-08ED6B105DDA" self.rule.camprofile = "/Users/vagrant/stonix/src/stonix_resources/" + \ "files/stonix4macCameraDisablement.mobileconfig" self.rule.ci.updatecurrvalue(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 @change: Breen Malmberg - 06102015 - changed this method to reflect the new functionality of DisableCamera.py ''' 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(escape(self.identifier), 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 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 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 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