예제 #1
0
class zzzTestRuleDisableIPV6(RuleTest):
    def setUp(self):
        RuleTest.setUp(self)
        self.rule = DisableIPV6(self.config, self.environ, self.logdispatch,
                                self.statechglogger)
        self.logger = self.logdispatch
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.ch = CommandHelper(self.logdispatch)
        self.checkUndo = True

    def tearDown(self):
        pass

    def runTest(self):
        self.simpleRuleTest()

    def setConditionsForRule(self):
        '''Configure system for the unit test

        :param self: essential if you override this definition
        :returns: boolean - If successful True; If failure False
        @author: ekkehard j. koch

        '''
        success = True
        if self.environ.getosfamily() == "linux":
            success = self.setLinuxConditions()
        elif self.environ.getosfamily() == "darwin":
            success = self.setMacConditions()
        return success

    def setLinuxConditions(self):
        success = True
        self.ph = Pkghelper(self.logger, self.environ)
        if not self.messupNetconfigFile():
            success = False
        if not self.messupSysctl():
            success = False
        if not self.messupModprobeFiles():
            success = False
        if not self.messupInterfaceFile():
            success = False
        if self.ph.manager == "apt-get":
            if not self.messupSSHDFile():
                success = False
        return success

    def setMacConditions(self):
        success = True
        debug = ""
        networksetup = "/usr/sbin/networksetup"
        listnetworkservices = networksetup + " -listallnetworkservices"
        ipv6status = "^IPv6:\s+On"
        getinfo = networksetup + " -getinfo"
        self.ch.executeCommand(listnetworkservices)
        retcode = self.ch.getReturnCode()
        if retcode != 0:
            success = False
            debug = "Failed to get list of network services"
            self.logger.log(LogPriority.DEBUG, debug)
        else:
            networkservices = self.ch.getOutput()
            for ns in networkservices:
                # ignore non-network service output lines
                if re.search("denotes that", ns, re.IGNORECASE):
                    continue
                else:
                    self.ch.executeCommand(networksetup + ' -setv6automatic ' +
                                           '"' + ns + '"')
                    retcode = self.ch.getReturnCode()
                    if retcode != 0:
                        success = False
                        debug = "Failed to get information for network service: " + ns
                        self.logger.log(LogPriority.DEBUG, debug)
        return success

    def messupNetconfigFile(self):
        success = True
        # stig portion, check netconfig file for correct contents
        if self.ph.manager == "apt-get":
            nfspkg = "nfs-common"
        else:
            nfspkg = "nfs-utils.x86_64"
        if self.ph.check(nfspkg):
            if not self.ph.remove(nfspkg):
                success = False
                debug = "Unable to remove nfs package for preconditions"
                self.logger.log(LogPriority.DEBUG, debug)
        if os.path.exists("/etc/netconfig"):
            item1 = "udp6 tpi_clts v inet6 udp - -"
            item2 = "tcp6 tpi_cots_ord v inet6 tcp - -"
            item1found, item2found, fixFile = False, False, False
            writestring = ""
            contents = readFile("/etc/netconfig", self.logger)
            for line in contents:
                writestring += line
                line = re.sub("\s+", " ", line.strip())
                if re.search(item1, line):
                    item1found = True
                if re.search(item2, line):
                    item2found = True
            if not item1found:
                writestring += item1
                fixFile = True
            if not item2found:
                writestring += item2
                fixFile = True
            if fixFile:
                if not writeFile("/etc/netconfig", writestring, self.logger):
                    success = False
                    debug = "Unable tomess up /etc/netconfig file for preconditions"
                    self.logger.log(LogPriority.DEBUG, debug)
        return success

    def messupSysctl(self):
        success = True
        sysctlcmd = ""
        sysctl = "/etc/sysctl.conf"
        directives = [
            "net.ipv6.conf.all.disable_ipv6=0",
            "net.ipv6.conf.default.disable_ipv6=0"
        ]
        filedirectives = {
            "net.ipv6.conf.all.disable_ipv6": "0",
            "net.ipv6.conf.default.disable_ipv6": "0"
        }
        tmpfile = sysctl + ".tmp"

        if os.path.exists(sysctl):
            editor = KVEditorStonix(self.statechglogger, self.logger, "conf",
                                    sysctl, tmpfile, filedirectives, "present",
                                    "openeq")
            if not editor.report():
                if not editor.fix():
                    success = False
                    debug = "Unable to mess up " + sysctl + " file for preconditions"
                    self.logger.log(LogPriority.DEBUG, debug)
                elif not editor.commit():
                    success = False
                    debug = "Unable to mess up " + sysctl + " file for preconditions"
                    self.logger.log(LogPriority.DEBUG, debug)
        sysctllocs = ["/sbin/sysctl", "/usr/sbin/sysctl"]
        for loc in sysctllocs:
            if os.path.exists(loc):
                sysctlcmd = loc

        if sysctlcmd:
            for d in directives:
                setbadopt = sysctlcmd + " -w " + d
                self.ch.executeCommand(setbadopt)
                retcode = self.ch.getReturnCode()
                if retcode != 0:
                    success = False
                    debug = "Failed to write configuration change: " + d + "\n"
                    self.logger.log(LogPriority.DEBUG, debug)
        else:
            debug = "sysctl command not found on system\n"
            self.logger.log(LogPriority.DEBUG, debug)
            success = False
        return success

    def messupModprobeFiles(self):
        success = True
        modprobes = {
            "options": "ipv6 disable=1",
            "install": "ipv6 /bin/true",
            "helloworld": ""
        }
        if os.path.exists("/etc/modprobe.d/"):
            modprobefiles = glob.glob("/etc/modprobe.d/*")
            for modfile in modprobefiles:
                tmpfile = modfile + ".tmp"
                editor = KVEditorStonix(self.statechglogger, self.logger,
                                        "conf", modfile, tmpfile, modprobes,
                                        "notpresent", "space")
                if not editor.report():
                    if not editor.fix():
                        success = False
                        debug = "Unable to mess up " + modfile + " file for preconditions"
                        self.logger.log(LogPriority.DEBUG, debug)
                    elif not editor.commit():
                        success = False
                        debug = "Unable to mess up " + modfile + " file for preconditions"
                        self.logger.log(LogPriority.DEBUG, debug)
        return success

    def messupInterfaceFile(self):
        success = True
        interface = {"IPV6INIT": '"yes"', "NETWORKING_IPV6": '"yes"'}
        # Check for existence of interface and network files to be configured
        if self.ph.manager == "yum":
            ifacefile = "/etc/sysconfig/network-scripts/"
            if not os.path.exists(ifacefile):
                ifacefile = ""
            netwrkfile = "/etc/sysconfig/network"
            if not os.path.exists(netwrkfile):
                netwrkfile = ""
        elif self.ph.manager == "zypper":
            ifacefile = "/etc/sysconfig/network/"
            if not os.path.exists(ifacefile):
                ifacefile = ""
        if ifacefile:
            dirs = glob.glob(ifacefile + "*")
            for loc in dirs:
                contents = []
                if re.search('^' + ifacefile + 'ifcfg', loc):
                    tmpfile = loc + ".tmp"
                    editor = KVEditorStonix(self.statechglogger, self.logger,
                                            "conf", loc, tmpfile, interface,
                                            "present", "closedeq")
                    if not editor.report():
                        if not editor.fix():
                            success = False
                            debug = "Unable to mess up " + loc + " file for preconditions"
                            self.logger.log(LogPriority.DEBUG, debug)
                        elif not editor.commit():
                            success = False
                            debug = "Unable to mess up " + loc + " file for preconditions"
                            self.logger.log(LogPriority.DEBUG, debug)
        return success

    def messupSSHDFile(self):
        success = True
        sshfile = "/etc/ssh/sshd_config"
        if os.path.exists(sshfile):
            tmpfile = sshfile + ".tmp"
            data = {"AddressFamily": "inet"}
            editor = KVEditorStonix(self.statechglogger, self.logger, "conf",
                                    sshfile, tmpfile, data, "notpresent",
                                    "space")
            if not editor.report():
                if not editor.fix():
                    success = False
                    debug = "Unable to mess up " + sshfile + " file for preconditions"
                    self.logger.log(LogPriority.DEBUG, debug)
                elif not editor.commit():
                    success = False
                    debug = "Unable to mess up " + sshfile + " file for preconditions"
                    self.logger.log(LogPriority.DEBUG, debug)
        return success

    def checkReportForRule(self, pCompliance, pRuleSuccess):
        '''check on whether report was correct

        :param self: essential if you override this definition
        :param pCompliance: the self.iscompliant value of rule
        :param pRuleSuccess: did report run successfully
        :returns: boolean - If successful True; If failure False
        @author: ekkehard j. koch

        '''
        self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + \
                             str(pCompliance) + ".")
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \
                             str(pRuleSuccess) + ".")
        success = True
        return success

    def checkFixForRule(self, pRuleSuccess):
        '''check on whether fix was correct

        :param self: essential if you override this definition
        :param pRuleSuccess: did report run successfully
        :returns: boolean - If successful True; If failure False
        @author: ekkehard j. koch

        '''
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \
                             str(pRuleSuccess) + ".")
        success = True
        return success

    def checkUndoForRule(self, pRuleSuccess):
        '''check on whether undo was correct

        :param self: essential if you override this definition
        :param pRuleSuccess: did report run successfully
        :returns: boolean - If successful True; If failure False
        @author: ekkehard j. koch

        '''
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \
                             str(pRuleSuccess) + ".")
        success = True
        return success
class zzzTestDisableAFPFileSharing(RuleTest):

    def setUp(self):

        RuleTest.setUp(self)
        self.rule = DisableAFPFileSharing(self.config,
                                self.environ,
                                self.logdispatch,
                                self.statechglogger)
        self.cmdhelper = CommandHelper(self.logdispatch)
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber

    def tearDown(self):
        pass

    def runTest(self):
        self.simpleRuleTest()

    def setConditionsForRule(self):
        '''
        Configure system for the unit test
        @param self: essential if you override this definition
        @return: boolean - If successful True; If failure False
        @author: Breen Malmberg
        '''

        success = True

        try:

            cmd = '/bin/launchctl enable system/com.apple.AppleFileServer'

            self.cmdhelper.executeCommand(cmd)
            retcode = self.cmdhelper.getReturnCode()
            if retcode != 0:
                errstr = self.cmdhelper.getErrorString()
                self.logdispatch.log(LogPriority.DEBUG, errstr)
                success = False

        except Exception:
            raise
        return success

    def checkReportForRule(self, pCompliance, pRuleSuccess):
        '''
        check on whether report was correct
        @param self: essential if you override this definition
        @param pCompliance: the self.iscompliant value of rule
        @param pRuleSuccess: did report run successfully
        @return: boolean - If successful True; If failure False
        @author: ekkehard j. koch
        '''
        self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + \
                             str(pCompliance) + ".")
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \
                             str(pRuleSuccess) + ".")
        success = True
        return success

    def checkFixForRule(self, pRuleSuccess):
        '''
        check on whether fix was correct
        @param self: essential if you override this definition
        @param pRuleSuccess: did report run successfully
        @return: boolean - If successful True; If failure False
        @author: ekkehard j. koch
        '''
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \
                             str(pRuleSuccess) + ".")
        success = True
        return success

    def checkUndoForRule(self, pRuleSuccess):
        '''
        check on whether undo was correct
        @param self: essential if you override this definition
        @param pRuleSuccess: did report run successfully
        @return: boolean - If successful True; If failure False
        @author: ekkehard j. koch
        '''
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \
                             str(pRuleSuccess) + ".")
        success = True
        return success
예제 #3
0
class zzzTestRuleInstallCasperSuite(RuleTest):
    def setUp(self):
        """
        Perform this task before running any of the tests in this class

        @author: Roy Nielsen
        """
        RuleTest.setUp(self)
        self.rule = InstallCasperSuite(self.config, self.environ,
                                       self.logdispatch, self.statechglogger)
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.ch = CommandHelper(self.logdispatch)
        self.pkgr = MacPkgr(self.environ, self.logdispatch)
        self.pkgUrl = self.rule.reporoot + self.rule.package
        message = "Reporoot: " + str(self.rule.reporoot)
        self.logdispatch.log(LogPriority.DEBUG, message)
        self.connection = Connectivity(self.logdispatch)

    ###########################################################################

    def tearDown(self):
        pass

    ###########################################################################

    def test_defaultOsInstall(self):
        """
        Test as if testing on a default OS install.  May result initial report
        pass, which would not run Fix mode.

        @author: Roy Nielsen
        """
        #####
        # Ensure the system is set as the default install would be set for this
        # OS
        self.removeJamfFramework()

        #####
        # Run simpleRuleTest
        self.simpleRuleTest()

        #####
        # Validate successful final state
        self.checkForBadInstallation()

    ###########################################################################

    def test_wrongSystemSettings(self):
        """
        Initial state for this test is set up to fail initial report run,
        forcing a fix run.

        @author: Roy Nielsen
        """
        #####
        # Put the system in a known bad state, then run the simpleRuleTest
        self.removeJamfFramework()

        #####
        # Run simpleRuleTest
        self.simpleRuleTest()

        #####
        # Validate successful final state
        self.checkForBadInstallation()

    ###########################################################################

    def test_correctSystemSettigns(self):
        """
        Only report should run.

        @author: Roy Nielsen
        """
        #####
        # Put the system in a known good state, then run the simpleRuleTest

        #####
        # If there is a network connection, install, otherwise just log
        hasconnection = self.connection.isPageAvailable(self.pkgUrl)
        if hasconnection:
            msg = "Connected to " + str(self.rule.package)
            self.logdispatch.log(LogPriority.DEBUG, msg)
            #####
            # Install the package
            if self.pkgr.installPackage(self.rule.package):
                self.rulesuccess = True
                self.rule.touch_imaged()

        #####
        # Run simpleRuleTest
        self.simpleRuleTest()

        #####
        # Validate successful final state
        self.checkForSuccessfullInstallation()

    ###########################################################################

    def test_resultAppend(self):
        """
        Test the unique rule method "resultAppend".

        @author: Roy Nielsen
        """
        #####
        # First test:
        # test the string case
        # self.detailedresults = string
        # passing in string
        self.rule.detailedresults = "Snow season looks good this year..."
        string_to_append = "The End"
        self.rule.resultAppend("The End")
        self.logdispatch.log(LogPriority.DEBUG,
                             "results: " + str(self.rule.detailedresults))
        self.assertTrue(
            re.search("%s" % string_to_append, self.rule.detailedresults))

        #####
        # second test:
        # test the first list case
        # self.detailedresults = list
        # passing in string
        self.rule.detailedresults = ["Snow season looks good this year..."]
        string_to_append = "The End"

        #####
        #####
        # Note here - we're not testing right, but the code passes test.
        # assertRasis isn't the right assert to be using
        self.assertRaises(TypeError, self.rule.resultAppend, string_to_append)

        #####
        # Third test:
        # test the second list case
        # self.detailedresults = list
        # passing in list
        self.rule.detailedresults = ["Snow season looks good this year..."]
        list_to_append = ["The End"]

        #####
        #####
        # Note here - we're not testing right, but the code passes test.
        # assertRasis isn't the right assert to be using
        self.assertRaises(TypeError, self.rule.resultAppend, list_to_append)

        #####
        # fourth test:
        # test the first "else" case
        # self.detailedresults = string
        # passing in boolean
        self.rule.detailedresults = "Snow season looks good this year..."

        #####
        #####
        # Note - assertRaises is being correctly used here
        self.assertRaises(TypeError, self.rule.resultAppend, False)

        #####
        # fifth test:
        # test the second "else" case
        # self.detailedresults = list
        # passing in False
        self.rule.detailedresults = ["Snow season looks good this year..."]

        #####
        #####
        # Note - assertRaises is being correctly used here
        self.assertRaises(TypeError, self.rule.resultAppend, False)

        #####
        # sixth test:
        # test the first "else" case
        # self.detailedresults = string
        # passing in None
        self.rule.detailedresults = "Snow season looks good this year..."

        #####
        #####
        # Note - assertRaises is being correctly used here
        self.assertRaises(TypeError, self.rule.resultAppend, None)

        #####
        # seventh test:
        # test the second "else" case
        # self.detailedresults = list
        # passing in None
        self.rule.detailedresults = ["Snow season looks good this year..."]

        #####
        #####
        # Note - assertRaises is being correctly used here
        self.assertRaises(TypeError, self.rule.resultAppend, None)

        #####
        #####
        # Note, we are not testing the passing in of every python type...
        # Be careful when choosing a representative selection of tests,
        # as critical tests might be missed.
        #
        # In this case, if another valid case is found, a test can be added
        # that will test that specific case, or class of cases.
        #
        # Testing is an iterative process.
        #

    ###########################################################################

    def test_touch_imaged(self):
        """
        Test the unique rule method "touch_imaged".

        The touched_imaged method is not dependent of any other methods, so it
        can be tested atomically.

        @author: Roy Nielsen
        """
        sig1 = "/etc/dds.txt"
        sig2 = "/var/log/dds.log"

        #####
        # Check for the existence of the first signature file, remove it if it
        # exists
        if os.path.exists(sig1):

            os.unlink(sig1)

            foundSig1 = True
        else:
            foundSig1 = False

        #####
        # Check for the existence of the second signature file, remove it if it
        # exists
        if os.path.exists(sig2):
            os.unlink(sig2)
            foundSig2 = True
        else:
            foundSig2 = False

        #####
        # Call the method
        self.rule.touch_imaged()

        #####
        # Check for the first file system signature
        success_a = os.path.isfile("/etc/dds.txt")
        self.logdispatch.log(LogPriority.DEBUG,
                             "Found first signature file...")
        self.assertTrue(success_a)

        #####
        # Check for the Second file system signature
        success_b = os.path.isfile("/var/log/dds.log")
        self.logdispatch.log(LogPriority.DEBUG,
                             "Found second signature file..")
        self.assertTrue(success_b)

        self.assertTrue(success_a and success_b)

        #####
        # If the files didn't exist at the beginning of the test, remove them.
        if not foundSig1:
            os.unlink(sig1)
        if not foundSig2:
            os.unlink(sig2)

    ###########################################################################

    def checkForSuccessfullInstallation(self):
        """
        Check for successfull test run.  Specifically what needs to have
        happened after a successfull run.  IE: must satisfy ALL conditions.

        @author: Roy Nielsen
        """
        #####
        # Check for existence of jamf binary
        success = os.path.isfile("/usr/local/bin/jamf")
        self.logdispatch.log(LogPriority.DEBUG, "Found the jamf binary..")
        self.assertTrue(success)

        #####
        # Check for the existence of the LANL Self Service.app
        success = os.path.isdir("/Applications/LANL Self Service.app")
        self.logdispatch.log(
            LogPriority.DEBUG,
            "Found result: " + str(success) + " Lanl Self Service.app")
        self.assertTrue(success)

        #####
        # Check for the first file system signature
        success = os.path.isfile("/etc/dds.txt")
        self.logdispatch.log(LogPriority.DEBUG, "Found first sig file...")
        self.assertTrue(success)

        #####
        # Check for the Second file system signature
        success = os.path.isfile("/var/log/dds.log")
        self.logdispatch.log(LogPriority.DEBUG, "Found second sig file...")
        self.assertTrue(success)

        #####
        # Check to make sure the "jamf recon" command works
        cmd = ["/usr/local/bin/jamf", "recon"]
        self.ch.executeCommand(cmd)
        return_code = self.ch.getReturnCode()
        self.logdispatch.log(
            LogPriority.DEBUG,
            "Return code from jamf " + " recon command: " + str(return_code))
        self.assertEqual(str(0), str(return_code))

    ###########################################################################

    def checkForBadInstallation(self):
        """
        Check for UNsuccessfull test run.  IE: must fail any of the following
        conditions.  Needs fuzzing applied, or variation on inputs to prove
        the variation works as expected.

        @Note: Running of the "/usr/local/bin/jamf recon" command is not
               executed in this test, as that functionality has already been
               tested.  The other variables need to be "fuzzed". IE, run
               every combination of the variables tested in this test.

        @author: Roy Nielsen
        """

        #####
        # Check if any of the following are false.  At least one must be false.
        success_a = os.path.isfile("/usr/local/bin/jamf")
        success_b = os.path.isdir("/Applications/LANL Self Service.app")
        success_c = os.path.isfile("/etc/dds.txt")
        success_d = os.path.isfile("/var/log/dds.log")

        #####
        # If any of these success parameters are false, the test fails
        self.assertTrue(
            success_a and success_b and success_c and success_d,
            "Could not find all files and directories " +
            "associated with a successful Casper installation")

        #####
        # Future testing needs to perform "fuzzing" - automated or auto
        # generated input testing
        # --
        # for every combination of inputs assert the correct outputs
        #
        # - at least one case is missing in this method - making sure to also
        #   test for the existence of the Jamf plist.
        #

    ###########################################################################

    def setConditionsForRule(self):
        '''Configure system for the unit test

        :param self: essential if you override this definition
        :returns: boolean - If successful True; If failure False
        @author: ekkehard j. koch

        '''
        success = True
        return success

    ###########################################################################

    def checkReportForRule(self, pCompliance, pRuleSuccess):
        '''check on whether report was correct

        :param self: essential if you override this definition
        :param pCompliance: the self.iscompliant value of rule
        :param pRuleSuccess: did report run successfully
        :returns: boolean - If successful True; If failure False
        @author: ekkehard j. koch

        '''
        self.logdispatch.log(LogPriority.DEBUG,
                             "pCompliance = " + str(pCompliance) + ".")
        self.logdispatch.log(LogPriority.DEBUG,
                             "pRuleSuccess = " + str(pRuleSuccess) + ".")

        success = True
        return success

    ###########################################################################

    def checkFixForRule(self, pRuleSuccess):
        '''check on whether fix was correct

        :param self: essential if you override this definition
        :param pRuleSuccess: did report run successfully
        :returns: boolean - If successful True; If failure False
        @author: ekkehard j. koch

        '''
        self.logdispatch.log(LogPriority.DEBUG,
                             "pRuleSuccess = " + str(pRuleSuccess) + ".")

        if pRuleSuccess:
            success = True
        else:
            success = False

        return success

    ###########################################################################

    def checkUndoForRule(self, pRuleSuccess):
        '''check on whether undo was correct

        :param self: essential if you override this definition
        :param pRuleSuccess: did report run successfully
        :returns: boolean - If successful True; If failure False
        @author: ekkehard j. koch

        '''
        self.logdispatch.log(LogPriority.DEBUG,
                             "pRuleSuccess = " + str(pRuleSuccess) + ".")

        if pRuleSuccess:
            success = True
        else:
            success = False

        return success

    ###########################################################################

    def removeJamfFramework(self):
        """
        Remove the jamf framework for setting initial conditions..

        @NOTE: There are many ways that a jamf install can be broken,
               This tests a clean uninstall.  Partial or broken installs
               are not covered in this test, however it may be a good idea
               to test for this in the future.

        @author: Roy Nielsen
        """
        success = False
        jamf_path = "/usr/local/bin/jamf"
        if os.path.exists(jamf_path):
            cmd = [jamf_path, "removeFramework"]

            self.ch.executeCommand(cmd)

            output = self.ch.getOutputString().split("\n")
            self.logdispatch.log(LogPriority.DEBUG, output)

            if self.ch.getReturnCode() == 0:
                success = True
        else:
            success = True
        return success
class 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 zzzTestRuleDisableInactiveAccounts(RuleTest):

    def setUp(self):
        RuleTest.setUp(self)
        self.rule = DisableInactiveAccounts(self.config,
                                    self.environ,
                                    self.logdispatch,
                                    self.statechglogger)
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.ch = CommandHelper(self.logdispatch)

    def tearDown(self):
        pass

    def runTest(self):
        self.setConditionsForRule()
        self.simpleRuleTest()

    def setConditionsForRule(self):
        '''
        Configure system for the unit test
        @param self: essential if you override this definition
        @return: boolean - If successful True; If failure False
        @author: Breen Malmberg
        '''
        success = True
        return success

    def test_dscl_path(self):
        '''
        test for valid location of dscl command path
        @author: Breen Malmberg
        '''

        found = False
        if os.path.exists('/usr/bin/dscl'):
            found = True
        self.assertTrue(found, True)

    def test_get_users(self):
        '''
        test the command to get the list of users
        @author: Breen Malmberg
        '''

        self.ch.executeCommand('/usr/bin/dscl . -ls /Users')
        rc = self.ch.getReturnCode()
        # rc should always be 0 after this command is run (means it ran successfully)
        # however 0 is interpreted as false by python, so.. assertFalse
        self.assertFalse(rc, "The return code for getting the list of users should always be 0 (success)")

    def test_pwpolicy_path(self):
        '''
        test for valid location of pwpolicy command path
        @author: Breen Malmberg
        '''

        found = False
        if os.path.exists('/usr/bin/pwpolicy'):
            found = True
        self.assertTrue(found, True)

    def test_initobjs(self):
        '''
        test whether the private method initobjs works
        @author: Breen Malmberg
        '''

        self.rule.initobjs()
        self.assertTrue(self.rule.cmdhelper, "CommandHelper object should always initialize after initobjs() is run")

    def checkReportForRule(self, pCompliance, pRuleSuccess):
        '''
        check on whether report was correct
        @param self: essential if you override this definition
        @param pCompliance: the self.iscompliant value of rule
        @param pRuleSuccess: did report run successfully
        @return: boolean - If successful True; If failure False
        @author: Breen Malmberg
        '''
        self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + \
                             str(pCompliance) + ".")
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \
                             str(pRuleSuccess) + ".")
        success = True
        return success

    def checkFixForRule(self, pRuleSuccess):
        '''
        check on whether fix was correct
        @param self: essential if you override this definition
        @param pRuleSuccess: did report run successfully
        @return: boolean - If successful True; If failure False
        @author: Breen Malmberg
        '''
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \
                             str(pRuleSuccess) + ".")
        success = True
        return success

    def checkUndoForRule(self, pRuleSuccess):
        '''
        check on whether undo was correct
        @param self: essential if you override this definition
        @param pRuleSuccess: did report run successfully
        @return: boolean - If successful True; If failure False
        @author: Breen Malmberg
        '''
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \
                             str(pRuleSuccess) + ".")
        success = True
        return success
class zzzTestRuleDisableRemoveableStorage(RuleTest):

    def setUp(self):
        RuleTest.setUp(self)
        self.rule = DisableRemoveableStorage(self.config,
                                             self.environ,
                                             self.logdispatch,
                                             self.statechglogger)
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.ch = CommandHelper(self.logdispatch)
        self.rule.storageci.updatecurrvalue(True)
        self.logger = self.logdispatch
        self.ignoreresults = True
    def tearDown(self):
        pass

    def runTest(self):
        self.simpleRuleTest()

    def setConditionsForRule(self):
        '''
        Configure system for the unit test
        @param self: essential if you override this definition
        @return: boolean - If successful True; If failure False
        @author: ekkehard j. koch
        '''
        success = True
        if self.environ.getostype() == "Mac OS X":
            success = self.setConditionsForMac()
        else:
            success = self.setConditionsForLinux()
        return success

    def setConditionsForMac(self):
        '''
        Method to configure mac non compliant for unit test
        @author: dwalker
        @return: boolean
        '''
        success = True
        daemonpath = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]))) + "/src/stonix_resources/disablestorage"
        plistpath = "/Library/LaunchDaemons/gov.lanl.stonix.disablestorage.plist"
        self.rule.daemonpath = daemonpath
        if re.search("^10.11", self.environ.getosver()):
            usb = "IOUSBMassStorageDriver"
        else:
            usb = "IOUSBMassStorageClass"
        kernelmods = [usb,
                      "IOFireWireFamily",
                      "AppleThunderboltUTDM",
                      "AppleSDXC"]
        check = "/usr/sbin/kextstat"
        load = "/sbin/kextload"
        '''Remove plist file for launch job if exists'''
        if os.path.exists(plistpath):
            os.remove(plistpath)
        '''Remove daemon file if exists'''
        if os.path.exists(daemonpath):
            os.remove(daemonpath)
        for kmod in kernelmods:
            cmd = check + "| grep " + kmod
            self.ch.executeCommand(cmd)
            if self.ch.getReturnCode() != 0:
                '''kernel mod is not loaded, load to make non-compliant'''
                cmd = load + " /System/Library/Extensions/" + kmod + ".kext"
                if not self.ch.executeCommand(cmd):
                    debug = "Unable to load kernel module " + kmod + " for unit test\n"
                    self.logdispatch.log(LogPriority.DEBUG, debug)
                    success = False
        return success

    def setConditionsForLinux(self):
        '''
        Method to configure mac non compliant for unit test
        @author: dwalker
        @return: boolean
        '''
        success = True
        self.ph = Pkghelper(self.logger, self.environ)
        # check compliance of grub file(s) if files exist
        if re.search("Red Hat", self.environ.getostype()) and \
                re.search("^6", self.environ.getosver()):
            self.grubperms = [0, 0, 0o600]
        elif self.ph.manager is "apt-get":
            self.grubperms = [0, 0, 0o400]
        else:
            self.grubperms = [0, 0, 0o644]
        grubfiles = ["/boot/grub2/grub.cfg",
                     "/boot/grub/grub.cfg"
                     "/boot/grub/grub.conf"]
        for grub in grubfiles:
            if os.path.exists(grub):
                if self.grubperms:
                    if checkPerms(grub, self.grubperms, self.logger):
                        if not setPerms(grub, [0, 0, 0o777], self.logger):
                            success = False
                contents = readFile(grub, self.logger)
                if contents:
                    for line in contents:
                        if re.search("^kernel", line.strip()) or re.search("^linux", line.strip()) \
                                or re.search("^linux16", line.strip()):
                            if re.search("\s+nousb\s*", line):
                                if not re.sub("nousb", "", line):
                                    success = False
                            if re.search("\s+usbcore\.authorized_default=0\s*", line):
                                if not re.sub("usbcore\.authorized_default=0", "", line):
                                    success = False

        pcmcialist = ['pcmcia-cs', 'kernel-pcmcia-cs', 'pcmciautils']
        # check for existence of certain usb packages, non-compliant
        # if any exist
        for item in pcmcialist:
            if not self.ph.check(item):
                self.ph.install(item)

        removeables = []
        found1 = True
        blacklist = {"blacklist usb_storage": False,
                     "install usbcore /bin/true": False,
                     "install usb-storage /bin/true": False,
                     "blacklist uas": False,
                     "blacklist firewire-ohci": False,
                     "blacklist firewire-sbp2": False}
        if os.path.exists("/etc/modprobe.d"):
            dirs = glob.glob("/etc/modprobe.d/*")
            for directory in dirs:
                if os.path.isdir(directory):
                    continue
                tempstring = ""
                contents = readFile(directory, self.logger)
                for line in contents:
                    if line.strip() in blacklist:
                        continue
                    else:
                        tempstring += line
                if not writeFile(directory, tempstring, self.logger):
                    success = False
        if os.path.exists("/etc/modprobe.conf"):
            contents = readFile("/etc/modprobe.conf", self.logger)
            tempstring = ""
            for line in contents:
                if line.strip() in blacklist:
                    continue
                else:
                    tempstring += line
            if not writeFile("/etc/modprobe.conf", tempstring, self.logger):
                success = False

        udevfile = "/etc/udev/rules.d/10-local.rules"
        if os.path.exists(udevfile):
            if checkPerms(udevfile, [0, 0, 0o644], self.logger):
                if not setPerms(udevfile, [0 ,0, 0o777], self.logger):
                    success = False
            contents = readFile(udevfile, self.logger)
            tempstring = ""
            for line in contents:
                if re.search("ACTION\=\=\"add\"\, SUBSYSTEMS\=\=\"usb\"\, RUN\+\=\"/bin/sh \-c \'for host in /sys/bus/usb/devices/usb\*\; do echo 0 \> \$host/authorized\_default\; done\'\"",
                        line.strip()):
                    continue
                else:
                    tempstring += line
            if not writeFile(udevfile, tempstring, self.logger):
                success = False
        return success

    def checkReportForRule(self, pCompliance, pRuleSuccess):
        '''
        check on whether report was correct
        @param self: essential if you override this definition
        @param pCompliance: the self.iscompliant value of rule
        @param pRuleSuccess: did report run successfully
        @return: boolean - If successful True; If failure False
        @author: ekkehard j. koch
        '''
        self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + \
                             str(pCompliance) + ".")
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \
                             str(pRuleSuccess) + ".")
        success = True
        return success

    def checkFixForRule(self, pRuleSuccess):
        '''
        check on whether fix was correct
        @param self: essential if you override this definition
        @param pRuleSuccess: did report run successfully
        @return: boolean - If successful True; If failure False
        @author: ekkehard j. koch
        '''
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \
                             str(pRuleSuccess) + ".")
        success = True
        return success

    def checkUndoForRule(self, pRuleSuccess):
        '''
        check on whether undo was correct
        @param self: essential if you override this definition
        @param pRuleSuccess: did report run successfully
        @return: boolean - If successful True; If failure False
        @author: ekkehard j. koch
        '''
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \
                             str(pRuleSuccess) + ".")
        success = True
        return success
예제 #7
0
class zzzTestRuleNoCoreDumps(RuleTest):

    def setUp(self):
        RuleTest.setUp(self)
        self.rule = NoCoreDumps(self.config,
                                self.environ,
                                self.logdispatch,
                                self.statechglogger)
        self.logger = self.logdispatch
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.checkUndo = True
        self.ch = CommandHelper(self.logger)
    def tearDown(self):
        pass

    def runTest(self):
        self.simpleRuleTest()

    def setConditionsForRule(self):
        """
        Configure system for the unit test
        @param self: essential if you override this definition
        @return: boolean - If successful True; If failure False
        @author: Ekkehard J. Koch
        """
        success = True
        if self.environ.getosfamily() == "linux":
            if not self.setLinuxConditions():
                success = False
        elif self.environ.getostype() == "mac":
            if not self.setMacConditions():
                success = False
        return success

    def setMacConditions(self):
        success = True
        self.ch.executeCommand("/usr/bin/launchctl limit core")
        retcode = self.ch.getReturnCode()
        if retcode != 0:
            self.detailedresults += "\nFailed to run launchctl command to get current value of core dumps configuration"
            errmsg = self.ch.getErrorString()
            self.logger.log(LogPriority.DEBUG, errmsg)
        else:
            output = self.ch.getOutputString()
            if output:
                if not re.search("1", output):
                    self.ch.executeCommand("/usr/bin/launchctl limit core 1 1")

    def setLinuxConditions(self):
        success = True
        path1 = "/etc/security/limits.conf"
        if os.path.exists(path1):
            lookfor1 = "(^\*)\s+hard\s+core\s+0?"
            contents = readFile(path1, self.logger)
            if contents:
                tempstring = ""
                for line in contents:
                    if not re.search(lookfor1, line.strip()):
                        tempstring += line
                if not writeFile(path1, tempstring, self.logger):
                    debug = "unable to write incorrect contents to " + path1 + "\n"
                    self.logger.log(LogPriority.DEBUG, debug)
                    success = False
            if checkPerms(path1, [0, 0, 0o644], self.logger):
                if not setPerms(path1, [0, 0, 0o777], self.logger):
                    debug = "Unable to set incorrect permissions on " + path1 + "\n"
                    self.logger.log(LogPriority.DEBUG, debug)
                    success = False
                else:
                    debug = "successfully set incorrect permissions on " + path1 + "\n"
                    self.logger.log(LogPriority.DEBUG, debug)

        self.ch.executeCommand("/sbin/sysctl fs.suid_dumpable")
        retcode = self.ch.getReturnCode()

        if retcode != 0:
            self.detailedresults += "Failed to get value of core dumps configuration with sysctl command\n"
            errmsg = self.ch.getErrorString()
            self.logger.log(LogPriority.DEBUG, errmsg)
            success = False
        else:
            output = self.ch.getOutputString()
            if output.strip() != "fs.suid_dumpable = 1":
                if not self.ch.executeCommand("/sbin/sysctl -w fs.suid_dumpable=1"):
                    debug = "Unable to set incorrect value for fs.suid_dumpable"
                    self.logger.log(LogPriority.DEBUG, debug)
                    success = False
                elif not self.ch.executeCommand("/sbin/sysctl -p"):
                    debug = "Unable to set incorrect value for fs.suid_dumpable"
                    self.logger.log(LogPriority.DEBUG, debug)
                    success = False
        
        return success

    def checkReportForRule(self, pCompliance, pRuleSuccess):
        """
        check on whether report was correct
        @param self: essential if you override this definition
        @param pCompliance: the self.iscompliant value of rule
        @param pRuleSuccess: did report run successfully
        @return: boolean - If successful True; If failure False
        @author: Ekkehard J. Koch
        """
        self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + \
                             str(pCompliance) + ".")
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \
                             str(pRuleSuccess) + ".")
        success = True
        return success

    def checkFixForRule(self, pRuleSuccess):
        """
        check on whether fix was correct
        @param self: essential if you override this definition
        @param pRuleSuccess: did report run successfully
        @return: boolean - If successful True; If failure False
        @author: Ekkehard J. Koch
        """
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \
                             str(pRuleSuccess) + ".")
        success = True
        return success

    def checkUndoForRule(self, pRuleSuccess):
        """
        check on whether undo was correct
        @param self: essential if you override this definition
        @param pRuleSuccess: did report run successfully
        @return: boolean - If successful True; If failure False
        @author: Ekkehard J. Koch
        """
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \
                             str(pRuleSuccess) + ".")
        success = True
        return success
class zzzTestRuleEnableKernelAuditing(RuleTest):

    def setUp(self):
        RuleTest.setUp(self)
        self.rule = EnableKernelAuditing(self.config,
                                    self.environ,
                                    self.logdispatch,
                                    self.statechglogger)
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.ch = CommandHelper(self.logdispatch)

    def tearDown(self):
        # restore backups of original files, made before testing
#         if self.environ.getosfamily() == 'darwin':
#             auditcontrolbak = '/etc/security/audit_control.stonixbak'
#             audituserbak = '/etc/security/audit_user.stonixbak'
#             if os.path.exists(auditcontrolbak):
#                 os.rename(auditcontrolbak, '/etc/security/audit_control')
#             if os.path.exists(audituserbak):
#                 os.rename(audituserbak, '/etc/security/audit_user')
#         else:
#             auditdbaks =['/etc/audit/auditd.conf.stonixbak', '/etc/auditd.conf.stonixbak'] 
#             auditrulesbaks = ['/etc/audit/audit.rules.stonixbak', '/etc/audit/rules.d/audit.rules.stonixbak']
#             for bak in auditdbaks:
#                 if os.path.exists(bak):
#                     os.rename(bak, bak[:-10])
#             for bak in auditrulesbaks:
#                 if os.path.exists(bak):
#                     os.rename(bak, bak[:-10])
        pass

    def runTest(self):
        self.simpleRuleTest()

    def setConditionsForRule(self):
        '''
        Configure system for the unit test
        @param self: essential if you override this definition
        @return: boolean - If successful True; If failure False
        @author: ekkehard j. koch
        '''

        success = True
# 
#         # make backups of any original files, before testing
#         if self.environ.getosfamily() == 'darwin':
#             if os.path.exists('/etc/security/audit_control'):
#                 os.rename('/etc/security/audit_control', '/etc/security/audit_control.stonixbak')
#             if os.path.exists('/etc/security/audit_user'):
#                 os.rename('/etc/security/audit_user', '/etc/security/audit_user.stonixbak')
#         else:
#             auditdpaths = ['/etc/audit/auditd.conf', '/etc/auditd.conf']
#             for path in auditdpaths:
#                 if os.path.exists(path):
#                     os.rename(path, path + '.stonixbak')
#             if os.path.exists('/etc/audisp/audispd.conf'):
#                 os.rename('/etc/audisp/audispd.conf', '/etc/audisp/audispd.conf.stonixbak')
#             auditruleslocs = ['/etc/audit/audit.rules', '/etc/audit/rules.d/audit.rules']
#             for loc in auditruleslocs:
#                 if os.path.exists(loc):
#                     os.rename(loc, loc + '.stonixbak')
        return success

    def test_freqci_in_range(self):
        '''
        test if the frequency ci value is within range

        @author: Breen Malmberg
        '''

        allowable_freq_range = range(1,100)
        self.assertTrue(self.rule.freqci.getcurrvalue() in allowable_freq_range)

    def test_flushtype_valid(self):
        '''
        test if the flush type ci value is a valid flush type

        @author: Breen Malmberg
        '''

        allowable_flush_types = ['data', 'incremental', 'sync']
        self.assertTrue(self.rule.flushtypeci.getcurrvalue() in allowable_flush_types)

    def test_get_system_arch(self):
        '''
        test the command to get the system arch
        @author: Breen Malmberg
        '''

        found = False

        self.ch.executeCommand('/usr/bin/uname -m')
        self.assertEqual(0, self.ch.getReturnCode())
        outputlines = self.ch.getOutput()
        self.assertFalse(outputlines == '')
        for line in outputlines:
            if re.search('^x86\_64', line):
                found = True
        for line in outputlines:
            if re.search('^x86', line):
                found = True
        self.assertEqual(found, True)

    def test_get_suid_files(self):
        '''
        test the command to find suid files
        @author: Breen Malmberg
        '''

        self.ch.executeCommand('/usr/bin/find / -xdev -type f -perm -4000 -o -type f -perm -2000')
        self.assertEqual(0, self.ch.getReturnCode())

    def test_release_file_exists(self):
        '''
        does at least one of the release file paths that the code relies on exist?
        linux-only
        @author: Breen Malmberg
        '''

        if self.environ.getosfamily() == 'darwin':
            return True

        found = False

        releasefilelocs = ['/etc/os-release', '/etc/redhat-release']
        for loc in releasefilelocs:
            if os.path.exists(loc):
                found = True
        self.assertEqual(found, True)

    def test_grub_cfg_file_exists(self):
        '''
        does at least one of the grub config file paths that the code relies on exist?
        linux-only
        @author: Breen Malmberg
        '''

        if self.environ.getosfamily() == 'darwin':
            return True

        found = False

        grubcfglocs = ['/boot/grub/grub.conf', '/etc/default/grub']
        for loc in grubcfglocs:
            if os.path.exists(loc):
                found = True
        self.assertEqual(found, True)

    def checkReportForRule(self, pCompliance, pRuleSuccess):
        '''
        check on whether report was correct
        @param self: essential if you override this definition
        @param pCompliance: the self.iscompliant value of rule
        @param pRuleSuccess: did report run successfully
        @return: boolean - If successful True; If failure False
        @author: ekkehard j. koch
        '''
        self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + \
                             str(pCompliance) + ".")
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \
                             str(pRuleSuccess) + ".")
        success = True
        return success

    def checkFixForRule(self, pRuleSuccess):
        '''
        check on whether fix was correct
        @param self: essential if you override this definition
        @param pRuleSuccess: did report run successfully
        @return: boolean - If successful True; If failure False
        @author: ekkehard j. koch
        '''
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \
                             str(pRuleSuccess) + ".")
        success = True
        return success

    def checkUndoForRule(self, pRuleSuccess):
        '''
        check on whether undo was correct
        @param self: essential if you override this definition
        @param pRuleSuccess: did report run successfully
        @return: boolean - If successful True; If failure False
        @author: ekkehard j. koch
        '''
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \
                             str(pRuleSuccess) + ".")
        success = True
        return success
class zzzTestRuleDisableInactiveAccounts(RuleTest):

    def setUp(self):
        RuleTest.setUp(self)
        self.rule = DisableInactiveAccounts(self.config,
                                    self.environ,
                                    self.logdispatch,
                                    self.statechglogger)
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.ch = CommandHelper(self.logdispatch)

    def tearDown(self):
        pass

    def runTest(self):
        self.setConditionsForRule()
        self.simpleRuleTest()

    def setConditionsForRule(self):
        '''Configure system for the unit test

        :param self: essential if you override this definition
        :returns: boolean - If successful True; If failure False
        @author: Breen Malmberg

        '''
        success = True
        return success

    def test_dscl_path(self):
        '''test for valid location of dscl command path
        @author: Breen Malmberg


        '''

        found = False
        if os.path.exists('/usr/bin/dscl'):
            found = True
        self.assertTrue(found, True)

    def test_get_users(self):
        '''test the command to get the list of users
        @author: Breen Malmberg


        '''

        self.ch.executeCommand('/usr/bin/dscl . -ls /Users')
        rc = self.ch.getReturnCode()
        # rc should always be 0 after this command is run (means it ran successfully)
        # however 0 is interpreted as false by python, so.. assertFalse
        self.assertFalse(rc, "The return code for getting the list of users should always be 0 (success)")

    def test_pwpolicy_path(self):
        '''test for valid location of pwpolicy command path
        @author: Breen Malmberg


        '''

        found = False
        if os.path.exists('/usr/bin/pwpolicy'):
            found = True
        self.assertTrue(found, True)

    def test_initobjs(self):
        '''test whether the private method initobjs works
        @author: Breen Malmberg


        '''

        self.rule.initobjs()
        self.assertTrue(self.rule.cmdhelper, "CommandHelper object should always initialize after initobjs() is run")

    def checkReportForRule(self, pCompliance, pRuleSuccess):
        '''check on whether report was correct

        :param self: essential if you override this definition
        :param pCompliance: the self.iscompliant value of rule
        :param pRuleSuccess: did report run successfully
        :returns: boolean - If successful True; If failure False
        @author: Breen Malmberg

        '''
        self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + \
                             str(pCompliance) + ".")
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \
                             str(pRuleSuccess) + ".")
        success = True
        return success

    def checkFixForRule(self, pRuleSuccess):
        '''check on whether fix was correct

        :param self: essential if you override this definition
        :param pRuleSuccess: did report run successfully
        :returns: boolean - If successful True; If failure False
        @author: Breen Malmberg

        '''
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \
                             str(pRuleSuccess) + ".")
        success = True
        return success

    def checkUndoForRule(self, pRuleSuccess):
        '''check on whether undo was correct

        :param self: essential if you override this definition
        :param pRuleSuccess: did report run successfully
        :returns: boolean - If successful True; If failure False
        @author: Breen Malmberg

        '''
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \
                             str(pRuleSuccess) + ".")
        success = True
        return success
class zzzTestRuleDisableRemoveableStorage(RuleTest):

    def setUp(self):
        RuleTest.setUp(self)
        self.rule = DisableRemoveableStorage(self.config,
                                             self.environ,
                                             self.logdispatch,
                                             self.statechglogger)
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.ch = CommandHelper(self.logdispatch)
        self.rule.storageci.updatecurrvalue(True)
        self.logger = self.logdispatch
        self.ignoreresults = True
    def tearDown(self):
        pass

    def runTest(self):
        self.simpleRuleTest()

    def setConditionsForRule(self):
        '''Configure system for the unit test

        :param self: essential if you override this definition
        :returns: boolean - If successful True; If failure False
        @author: ekkehard j. koch

        '''
        success = True
        if self.environ.getostype() == "Mac OS X":
            success = self.setConditionsForMac()
        else:
            success = self.setConditionsForLinux()
        return success

    def setConditionsForMac(self):
        '''Method to configure mac non compliant for unit test
        @author: dwalker


        :returns: boolean

        '''
        success = True
        daemonpath = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]))) + "/src/stonix_resources/disablestorage.py"
        plistpath = "/Library/LaunchDaemons/gov.lanl.stonix.disablestorage.plist"
        self.rule.daemonpath = daemonpath
        if re.search("^10.11", self.environ.getosver()):
            usb = "IOUSBMassStorageDriver"
        else:
            usb = "IOUSBMassStorageClass"
        kernelmods = [usb,
                      "IOFireWireFamily",
                      "AppleThunderboltUTDM",
                      "AppleSDXC"]
        check = "/usr/sbin/kextstat"
        load = "/sbin/kextload"
        '''Remove plist file for launch job if exists'''
        if os.path.exists(plistpath):
            os.remove(plistpath)
        '''Remove daemon file if exists'''
        if os.path.exists(daemonpath):
            os.remove(daemonpath)
        for kmod in kernelmods:
            cmd = check + "| grep " + kmod
            self.ch.executeCommand(cmd)
            if self.ch.getReturnCode() != 0:
                '''kernel mod is not loaded, load to make non-compliant'''
                cmd = load + " /System/Library/Extensions/" + kmod + ".kext"
                if not self.ch.executeCommand(cmd):
                    debug = "Unable to load kernel module " + kmod + " for unit test\n"
                    self.logdispatch.log(LogPriority.DEBUG, debug)
                    success = False
        return success

    def setConditionsForLinux(self):
        '''Method to configure mac non compliant for unit test
        @author: dwalker


        :returns: boolean

        '''
        success = True
        self.ph = Pkghelper(self.logger, self.environ)
        # check compliance of grub file(s) if files exist
        if re.search("Red Hat", self.environ.getostype()) and \
                re.search("^6", self.environ.getosver()):
            self.grubperms = [0, 0, 0o600]
        elif self.ph.manager is "apt-get":
            self.grubperms = [0, 0, 0o400]
        else:
            self.grubperms = [0, 0, 0o644]
        grubfiles = ["/boot/grub2/grub.cfg",
                     "/boot/grub/grub.cfg"
                     "/boot/grub/grub.conf"]
        for grub in grubfiles:
            if os.path.exists(grub):
                if self.grubperms:
                    if checkPerms(grub, self.grubperms, self.logger):
                        if not setPerms(grub, [0, 0, 0o777], self.logger):
                            success = False
                contents = readFile(grub, self.logger)
                if contents:
                    for line in contents:
                        if re.search("^kernel", line.strip()) or re.search("^linux", line.strip()) \
                                or re.search("^linux16", line.strip()):
                            if re.search("\s+nousb\s*", line):
                                if not re.sub("nousb", "", line):
                                    success = False
                            if re.search("\s+usbcore\.authorized_default=0\s*", line):
                                if not re.sub("usbcore\.authorized_default=0", "", line):
                                    success = False

        pcmcialist = ['pcmcia-cs', 'kernel-pcmcia-cs', 'pcmciautils']
        # check for existence of certain usb packages, non-compliant
        # if any exist
        for item in pcmcialist:
            if not self.ph.check(item):
                self.ph.install(item)

        removeables = []
        found1 = True
        blacklist = {"blacklist usb_storage": False,
                     "install usbcore /bin/true": False,
                     "install usb-storage /bin/true": False,
                     "blacklist uas": False,
                     "blacklist firewire-ohci": False,
                     "blacklist firewire-sbp2": False}
        if os.path.exists("/etc/modprobe.d"):
            dirs = glob.glob("/etc/modprobe.d/*")
            for directory in dirs:
                if os.path.isdir(directory):
                    continue
                tempstring = ""
                contents = readFile(directory, self.logger)
                for line in contents:
                    if line.strip() in blacklist:
                        continue
                    else:
                        tempstring += line
                if not writeFile(directory, tempstring, self.logger):
                    success = False
        if os.path.exists("/etc/modprobe.conf"):
            contents = readFile("/etc/modprobe.conf", self.logger)
            tempstring = ""
            for line in contents:
                if line.strip() in blacklist:
                    continue
                else:
                    tempstring += line
            if not writeFile("/etc/modprobe.conf", tempstring, self.logger):
                success = False

        udevfile = "/etc/udev/rules.d/10-local.rules"
        if os.path.exists(udevfile):
            if checkPerms(udevfile, [0, 0, 0o644], self.logger):
                if not setPerms(udevfile, [0 ,0, 0o777], self.logger):
                    success = False
            contents = readFile(udevfile, self.logger)
            tempstring = ""
            for line in contents:
                if re.search("ACTION\=\=\"add\"\, SUBSYSTEMS\=\=\"usb\"\, RUN\+\=\"/bin/sh \-c \'for host in /sys/bus/usb/devices/usb\*\; do echo 0 \> \$host/authorized\_default\; done\'\"",
                        line.strip()):
                    continue
                else:
                    tempstring += line
            if not writeFile(udevfile, tempstring, self.logger):
                success = False
        return success

    def checkReportForRule(self, pCompliance, pRuleSuccess):
        '''check on whether report was correct

        :param self: essential if you override this definition
        :param pCompliance: the self.iscompliant value of rule
        :param pRuleSuccess: did report run successfully
        :returns: boolean - If successful True; If failure False
        @author: ekkehard j. koch

        '''
        self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + \
                             str(pCompliance) + ".")
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \
                             str(pRuleSuccess) + ".")
        success = True
        return success

    def checkFixForRule(self, pRuleSuccess):
        '''check on whether fix was correct

        :param self: essential if you override this definition
        :param pRuleSuccess: did report run successfully
        :returns: boolean - If successful True; If failure False
        @author: ekkehard j. koch

        '''
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \
                             str(pRuleSuccess) + ".")
        success = True
        return success

    def checkUndoForRule(self, pRuleSuccess):
        '''check on whether undo was correct

        :param self: essential if you override this definition
        :param pRuleSuccess: did report run successfully
        :returns: boolean - If successful True; If failure False
        @author: ekkehard j. koch

        '''
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \
                             str(pRuleSuccess) + ".")
        success = True
        return success
예제 #11
0
class zzzTestRuleNoCoreDumps(RuleTest):
    def setUp(self):
        RuleTest.setUp(self)
        self.rule = NoCoreDumps(self.config, self.environ, self.logdispatch,
                                self.statechglogger)
        self.logger = self.logdispatch
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.checkUndo = True
        self.ch = CommandHelper(self.logger)

    def tearDown(self):
        pass

    def runTest(self):
        self.simpleRuleTest()

    def setConditionsForRule(self):
        '''Configure system for the unit test

        :param self: essential if you override this definition
        :returns: boolean - If successful True; If failure False
        @author: Ekkehard J. Koch

        '''
        success = True
        if self.environ.getosfamily() == "linux":
            if not self.setLinuxConditions():
                success = False
        elif self.environ.getostype() == "mac":
            if not self.setMacConditions():
                success = False
        return success

    def setMacConditions(self):
        success = True
        self.ch.executeCommand("/usr/bin/launchctl limit core")
        retcode = self.ch.getReturnCode()
        if retcode != 0:
            debug = "Failed to run launchctl command to get current value of core dumps configuration\n"
            debug += self.ch.getErrorString()
            self.logger.log(LogPriority.DEBUG, debug)
        else:
            output = self.ch.getOutputString()
            if output:
                if not re.search("1", output):
                    self.ch.executeCommand("/usr/bin/launchctl limit core 1 1")

    def setLinuxConditions(self):
        success = True
        debug = ""
        path1 = "/etc/security/limits.conf"
        if os.path.exists(path1):
            lookfor1 = "(^\*)\s+hard\s+core\s+0?"
            contents = readFile(path1, self.logger)
            if contents:
                tempstring = ""
                for line in contents:
                    if not re.search(lookfor1, line.strip()):
                        tempstring += line
                if not writeFile(path1, tempstring, self.logger):
                    debug = "unable to write incorrect contents to " + path1
                    self.logger.log(LogPriority.DEBUG, debug)
                    success = False
            if not checkPerms(path1, [0, 0, 0o777], self.logger):
                if not setPerms(path1, [0, 0, 0o777], self.logger):
                    debug = "Unable to set incorrect permissions on " + path1
                    self.logger.log(LogPriority.DEBUG, debug)
                    success = False
                else:
                    debug = "successfully set incorrect permissions on " + path1
                    self.logger.log(LogPriority.DEBUG, debug)

        sysctl = "/etc/sysctl.conf"
        tmpfile = sysctl + ".tmp"
        editor = KVEditorStonix(self.statechglogger, self.logger, "conf",
                                sysctl, tmpfile, {"fs.suid_dumpable": "1"},
                                "present", "openeq")
        if not checkPerms(sysctl, [0, 0, 0o777], self.logger):
            if not setPerms(sysctl, [0, 0, 0o777], self.logger):
                debug = "Unable to set incorrect permissions on " + path1
                self.logger.log(LogPriority.DEBUG, debug)
                success = False
            else:
                debug = "successfully set incorrect permissions on " + path1
                self.logger.log(LogPriority.DEBUG, debug)
        if not editor.report():
            if not editor.fix():
                success = False
                debug = "Unable to set conditions for /etc/sysctl.conf file"
                self.logger.log(LogPriority.DEBUG, debug)
            elif not editor.commit():
                success = False
                debug = "Unable to set conditions for /etc/sysctl.conf file"
                self.logger.log(LogPriority.DEBUG, debug)

        self.ch.executeCommand("/sbin/sysctl fs.suid_dumpable")
        retcode = self.ch.getReturnCode()
        if retcode != 0:
            debug = "Failed to get value of core dumps configuration with sysctl command"
            debug += self.ch.getErrorString()
            self.logger.log(LogPriority.DEBUG, debug)
            success = False
        else:
            output = self.ch.getOutputString()
            if output.strip() != "fs.suid_dumpable = 1":
                if not self.ch.executeCommand(
                        "/sbin/sysctl -w fs.suid_dumpable=1"):
                    debug = "Unable to set incorrect value for fs.suid_dumpable"
                    self.logger.log(LogPriority.DEBUG, debug)
                    success = False
                elif not self.ch.executeCommand("/sbin/sysctl -q -e -p"):
                    debug = "Unable to set incorrect value for fs.suid_dumpable"
                    self.logger.log(LogPriority.DEBUG, debug)
                    success = False

        return success

    def checkReportForRule(self, pCompliance, pRuleSuccess):
        '''check on whether report was correct

        :param self: essential if you override this definition
        :param pCompliance: the self.iscompliant value of rule
        :param pRuleSuccess: did report run successfully
        :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 zzzTestRuleEnableKernelAuditing(RuleTest):
    def setUp(self):
        RuleTest.setUp(self)
        self.rule = EnableKernelAuditing(self.config, self.environ,
                                         self.logdispatch, self.statechglogger)
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.ch = CommandHelper(self.logdispatch)

    def tearDown(self):
        # restore backups of original files, made before testing
        #         if self.environ.getosfamily() == 'darwin':
        #             auditcontrolbak = '/etc/security/audit_control.stonixbak'
        #             audituserbak = '/etc/security/audit_user.stonixbak'
        #             if os.path.exists(auditcontrolbak):
        #                 os.rename(auditcontrolbak, '/etc/security/audit_control')
        #             if os.path.exists(audituserbak):
        #                 os.rename(audituserbak, '/etc/security/audit_user')
        #         else:
        #             auditdbaks =['/etc/audit/auditd.conf.stonixbak', '/etc/auditd.conf.stonixbak']
        #             auditrulesbaks = ['/etc/audit/audit.rules.stonixbak', '/etc/audit/rules.d/audit.rules.stonixbak']
        #             for bak in auditdbaks:
        #                 if os.path.exists(bak):
        #                     os.rename(bak, bak[:-10])
        #             for bak in auditrulesbaks:
        #                 if os.path.exists(bak):
        #                     os.rename(bak, bak[:-10])
        pass

    def runTest(self):
        self.simpleRuleTest()

    def setConditionsForRule(self):
        '''Configure system for the unit test

        :param self: essential if you override this definition
        :returns: boolean - If successful True; If failure False
        @author: ekkehard j. koch

        '''

        success = True
        #
        #         # make backups of any original files, before testing
        #         if self.environ.getosfamily() == 'darwin':
        #             if os.path.exists('/etc/security/audit_control'):
        #                 os.rename('/etc/security/audit_control', '/etc/security/audit_control.stonixbak')
        #             if os.path.exists('/etc/security/audit_user'):
        #                 os.rename('/etc/security/audit_user', '/etc/security/audit_user.stonixbak')
        #         else:
        #             auditdpaths = ['/etc/audit/auditd.conf', '/etc/auditd.conf']
        #             for path in auditdpaths:
        #                 if os.path.exists(path):
        #                     os.rename(path, path + '.stonixbak')
        #             if os.path.exists('/etc/audisp/audispd.conf'):
        #                 os.rename('/etc/audisp/audispd.conf', '/etc/audisp/audispd.conf.stonixbak')
        #             auditruleslocs = ['/etc/audit/audit.rules', '/etc/audit/rules.d/audit.rules']
        #             for loc in auditruleslocs:
        #                 if os.path.exists(loc):
        #                     os.rename(loc, loc + '.stonixbak')
        return success

    def test_freqci_in_range(self):
        '''test if the frequency ci value is within range
        
        @author: Breen Malmberg


        '''

        allowable_freq_range = list(range(1, 100))
        self.assertTrue(
            self.rule.freqci.getcurrvalue() in allowable_freq_range)

    def test_flushtype_valid(self):
        '''test if the flush type ci value is a valid flush type
        
        @author: Breen Malmberg


        '''

        allowable_flush_types = ['data', 'incremental', 'sync']
        self.assertTrue(
            self.rule.flushtypeci.getcurrvalue() in allowable_flush_types)

    def test_get_system_arch(self):
        '''test the command to get the system arch
        @author: Breen Malmberg


        '''

        found = False

        self.ch.executeCommand('/usr/bin/uname -m')
        self.assertEqual(0, self.ch.getReturnCode())
        outputlines = self.ch.getOutput()
        self.assertFalse(outputlines == '')
        for line in outputlines:
            if re.search('^x86\_64', line):
                found = True
        for line in outputlines:
            if re.search('^x86', line):
                found = True
        self.assertEqual(found, True)

    def test_get_suid_files(self):
        '''test the command to find suid files
        @author: Breen Malmberg


        '''

        self.ch.executeCommand(
            '/usr/bin/find / -xdev -type f -perm -4000 -o -type f -perm -2000')
        self.assertEqual(0, self.ch.getReturnCode())

    def test_release_file_exists(self):
        '''does at least one of the release file paths that the code relies on exist?
        linux-only
        @author: Breen Malmberg


        '''

        if self.environ.getosfamily() == 'darwin':
            return True

        found = False

        releasefilelocs = ['/etc/os-release', '/etc/redhat-release']
        for loc in releasefilelocs:
            if os.path.exists(loc):
                found = True
        self.assertEqual(found, True)

    def test_grub_cfg_file_exists(self):
        '''does at least one of the grub config file paths that the code relies on exist?
        linux-only
        @author: Breen Malmberg


        '''

        if self.environ.getosfamily() == 'darwin':
            return True

        found = False

        grubcfglocs = ['/boot/grub/grub.conf', '/etc/default/grub']
        for loc in grubcfglocs:
            if os.path.exists(loc):
                found = True
        self.assertEqual(found, True)

    def checkReportForRule(self, pCompliance, pRuleSuccess):
        '''check on whether report was correct

        :param self: essential if you override this definition
        :param pCompliance: the self.iscompliant value of rule
        :param pRuleSuccess: did report run successfully
        :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