class zzzTestFrameworkServiceHelper(unittest.TestCase):

    def setUp(self):
        self.enviro = Environment()
        self.enviro.setdebugmode(False)
        self.logger = LogDispatcher(self.enviro)
        self.mysh = ServiceHelper(self.enviro, self.logger)
        self.myservice = 'crond'
        self.myservicename = ""
        if self.enviro.getosfamily() == 'darwin':
            self.myservice = "/System/Library/PrivateFrameworks/CalendarAgent.framework/Executables/CalendarAgent"
            self.myservicename = "com.apple.CalendarAgent"
        elif self.enviro.getosfamily() == 'solaris':
            self.myservice = 'svc:/system/cron:default'
        elif self.enviro.getosfamily() == 'freebsd':
            self.myservice = 'cron'
        elif os.path.exists('/usr/lib/systemd/system/cron.service'):
            self.myservice = 'cron.service'
        elif os.path.exists('/usr/lib/systemd/system/crond.service'):
            self.myservice = 'crond.service'
        elif os.path.exists('/etc/init.d/vixie-cron'):
            self.myservice = 'vixie-cron'
        elif os.path.exists('/etc/init.d/cron'):
            self.myservice = 'cron'

    def tearDown(self):
        pass

    def testListServices(self):
        svcslist = self.mysh.listservices()
        self.assertTrue(len(svcslist) > 0)

    def testDisableEnable(self):
        self.mysh.disableservice(self.myservice)
        auditresult = self.mysh.auditservice(self.myservice,
                                             self.myservicename)
        self.assertFalse(auditresult,
                         "Service not disabled or return from audit not valid")
        time.sleep(3)
        self.assertFalse(self.mysh.isrunning(self.myservice,
                                             self.myservicename),
                         "Service is still running or return from isrunning not valid")
        self.mysh.enableservice(self.myservice)
        self.assertTrue(self.mysh.auditservice(self.myservice,
                                               self.myservicename),
                        "Service not enabled or return from audit not valid")
        time.sleep(3)
        self.assertTrue(self.mysh.isrunning(self.myservice,
                                            self.myservicename),
                        "Service is not running or return from isrunning not valid")

    def testReloadService(self):
        self.assertTrue(self.mysh.reloadservice(self.myservice,
                                                self.myservicename),
                        'Service reload returned false')
Пример #2
0
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 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 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 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