def setUp(self):
        '''initialize and set class variables and objects'''

        self.environ = Environment()
        self.environ.setdebugmode(True)
        self.logger = LogDispatcher(self.environ)
        self.mysh = ServiceHelper(self.environ, self.logger)

        # set service name
        self.myservice = 'crond'
        self.myservicename = ""
        if self.environ.getosfamily() == 'darwin':
            self.myservice = "/Library/LaunchDaemons/gov.lanl.stonix.report.plist"
            self.myservicename = "gov.lanl.stonix.report"
        elif self.environ.getosfamily() == 'solaris':
            self.myservice = 'svc:/system/cron:default'
        elif self.environ.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'

        if self.environ.getosfamily() == "darwin":
            self.service = self.myservice, self.myservicename
        else:
            self.service = [self.myservice]

        # store system initial state
        self.orig_enabled = self.mysh.auditService(*self.service)
Ejemplo n.º 2
0
    def setUp(self):
        RuleTest.setUp(self)
        self.rule = ConfigureLinuxFirewall(self.config, self.environ,
                                           self.logdispatch,
                                           self.statechglogger)
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.logger = self.logdispatch
        self.ch = CommandHelper(self.logger)
        self.servicehelper = ServiceHelper(self.environ, self.logger)
        self.checkUndo = True
        self.isfirewalld = False
        self.isufw = False
        if os.path.exists('/bin/firewall-cmd'):
            self.isfirewalld = True
        if os.path.exists('/usr/sbin/ufw'):
            self.isufw = True

        # mostly pertains to RHEL6, Centos6
        self.iptables = "/usr/sbin/iptables"
        if not os.path.exists(self.iptables):
            self.iptables = '/sbin/iptables'
        self.ip6tables = "/usr/sbin/ip6tables"
        if not os.path.exists(self.ip6tables):
            self.ip6tables = '/sbin/ip6tables'
        if os.path.exists("/usr/sbin/iptables-restore"):
            self.iprestore = "/usr/sbin/iptables-restore"
        elif os.path.exists("/sbin/iptables-restore"):
            self.iprestore = "/sbin/iptables-restore"

        if os.path.exists("/usr/sbin/ip6tables-restore"):
            self.ip6restore = "/usr/sbin/ip6tables-restore"
        elif os.path.exists("/sbin/ip6tables-restore"):
            self.ip6restore = "/sbin/ip6tables-restore"
        self.scriptType = ""
Ejemplo n.º 3
0
 def setUp(self):
     RuleTest.setUp(self)
     self.rule = DisableGUILogon(self.config, self.environ,
                                 self.logdispatch, self.statechglogger)
     self.rulename = self.rule.rulename
     self.rulenumber = self.rule.rulenumber
     self.ch = CommandHelper(self.logdispatch)
     self.sh = ServiceHelper(self.environ, self.logdispatch)
 def setUp(self):
     RuleTest.setUp(self)
     self.rule = 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)
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')
Ejemplo n.º 6
0
 def setUp(self):
     RuleTest.setUp(self)
     self.rule = SecureMDNS(self.config, self.environ, self.logdispatch,
                            self.statechglogger)
     self.rulename = self.rule.rulename
     self.rulenumber = self.rule.rulenumber
     self.ch = CommandHelper(self.logdispatch)
     self.dc = "/usr/bin/defaults"
     self.lc = "/bin/launchctl"
     self.plb = "/usr/libexec/PlistBuddy"
     self.sh = ServiceHelper(self.environ, self.logdispatch)
Ejemplo n.º 7
0
 def setUp(self):
     RuleTest.setUp(self)
     self.rule = SecureMDNS(self.config, self.environ, self.logdispatch,
                            self.statechglogger)
     self.rulename = self.rule.rulename
     self.rulenumber = self.rule.rulenumber
     self.ch = CommandHelper(self.logdispatch)
     self.plb = "/usr/libexec/PlistBuddy"
     self.sh = ServiceHelper(self.environ, self.logdispatch)
     self.service = ""
     self.serviceTarget = ""
 def setUp(self):
     RuleTest.setUp(self)
     self.rule = DisableGUILogon(self.config, self.environ,
                                 self.logdispatch, self.statechglogger)
     self.rulename = self.rule.rulename
     self.rulenumber = self.rule.rulenumber
     self.ch = CommandHelper(self.logdispatch)
     self.sh = ServiceHelper(self.environ, self.logdispatch)
 def setUp(self):
     RuleTest.setUp(self)
     self.rule = 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)
Ejemplo n.º 10
0
 def setUp(self):
     RuleTest.setUp(self)
     self.rule = SecureMDNS(self.config,
                            self.environ,
                            self.logdispatch,
                            self.statechglogger)
     self.rulename = self.rule.rulename
     self.rulenumber = self.rule.rulenumber
     self.ch = CommandHelper(self.logdispatch)
     self.dc = "/usr/bin/defaults"
     self.lc = "/bin/launchctl"
     self.plb = "/usr/libexec/PlistBuddy"
     self.sh = ServiceHelper(self.environ, self.logdispatch)
Ejemplo n.º 11
0
 def setUp(self):
     RuleTest.setUp(self)
     self.rule = SecureMDNS(self.config,
                            self.environ,
                            self.logdispatch,
                            self.statechglogger)
     self.rulename = self.rule.rulename
     self.rulenumber = self.rule.rulenumber
     self.ch = CommandHelper(self.logdispatch)
     self.plb = "/usr/libexec/PlistBuddy"
     self.sh = ServiceHelper(self.environ, self.logdispatch)
     self.service = ""
     self.serviceTarget=""
 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 setUp(self):
        """
        initialize and set class variables and objects

        """

        self.environ = Environment()
        self.environ.setdebugmode(True)
        self.logger = LogDispatcher(self.environ)
        self.mysh = ServiceHelper(self.environ, self.logger)

        # set service name
        self.myservice = 'crond'
        self.myservicename = ""
        if self.environ.getosfamily() == 'darwin':
            self.myservice = "/Library/LaunchDaemons/gov.lanl.stonix.report.plist"
            self.myservicename = "gov.lanl.stonix.report"
        elif self.environ.getosfamily() == 'solaris':
            self.myservice = 'svc:/system/cron:default'
        elif self.environ.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'

        if self.environ.getosfamily() == "darwin":
            self.service = self.myservice, self.myservicename
        else:
            self.service = [self.myservice]

        # store system initial state
        self.orig_enabled = self.mysh.auditService(*self.service)
    def setUp(self):
        RuleTest.setUp(self)
        self.rule = ConfigureLinuxFirewall(self.config,
                                           self.environ,
                                           self.logdispatch,
                                           self.statechglogger)
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.logger = self.logdispatch
        self.ch = CommandHelper(self.logger)
        self.servicehelper = ServiceHelper(self.environ, self.logger)
        self.checkUndo = True
        self.isfirewalld = False
        self.isufw = False
        if os.path.exists('/bin/firewall-cmd'):
            self.isfirewalld = True
        if os.path.exists('/usr/sbin/ufw'):
            self.isufw = True

        # mostly pertains to RHEL6, Centos6
        self.iptables = "/usr/sbin/iptables"
        if not os.path.exists(self.iptables):
            self.iptables = '/sbin/iptables'
        self.ip6tables = "/usr/sbin/ip6tables"
        if not os.path.exists(self.ip6tables):
            self.ip6tables = '/sbin/ip6tables'
        if os.path.exists("/usr/sbin/iptables-restore"):
            self.iprestore = "/usr/sbin/iptables-restore"
        elif os.path.exists("/sbin/iptables-restore"):
            self.iprestore = "/sbin/iptables-restore"

        if os.path.exists("/usr/sbin/ip6tables-restore"):
            self.ip6restore = "/usr/sbin/ip6tables-restore"
        elif os.path.exists("/sbin/ip6tables-restore"):
            self.ip6restore = "/sbin/ip6tables-restore"
        self.scriptType = ""
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
Ejemplo n.º 17
0
class zzzTestRuleConfigureLinuxFirewall(RuleTest):
    def setUp(self):
        RuleTest.setUp(self)
        self.rule = ConfigureLinuxFirewall(self.config, self.environ,
                                           self.logdispatch,
                                           self.statechglogger)
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.logger = self.logdispatch
        self.ch = CommandHelper(self.logger)
        self.servicehelper = ServiceHelper(self.environ, self.logger)
        self.checkUndo = True
        self.isfirewalld = False
        self.isufw = False
        if os.path.exists('/bin/firewall-cmd'):
            self.isfirewalld = True
        if os.path.exists('/usr/sbin/ufw'):
            self.isufw = True

        # mostly pertains to RHEL6, Centos6
        self.iptables = "/usr/sbin/iptables"
        if not os.path.exists(self.iptables):
            self.iptables = '/sbin/iptables'
        self.ip6tables = "/usr/sbin/ip6tables"
        if not os.path.exists(self.ip6tables):
            self.ip6tables = '/sbin/ip6tables'
        if os.path.exists("/usr/sbin/iptables-restore"):
            self.iprestore = "/usr/sbin/iptables-restore"
        elif os.path.exists("/sbin/iptables-restore"):
            self.iprestore = "/sbin/iptables-restore"

        if os.path.exists("/usr/sbin/ip6tables-restore"):
            self.ip6restore = "/usr/sbin/ip6tables-restore"
        elif os.path.exists("/sbin/ip6tables-restore"):
            self.ip6restore = "/sbin/ip6tables-restore"
        self.scriptType = ""

    def tearDown(self):
        pass

    def runTest(self):
        self.simpleRuleTest()

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

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

        '''
        success = True
        self.detailedresults = ""
        self.iptScriptPath = ""
        scriptExists = ""
        debug = ""
        if self.isfirewalld:
            if self.servicehelper.auditService('firewalld.service'):
                if not self.servicehelper.disableService('firewalld.service'):
                    success = False
        if self.isufw:
            cmdufw = '/usr/sbin/ufw status'
            if not self.ch.executeCommand(cmdufw):
                debug = "Unable to run ufw status command in unit test\n"
                self.logger.log(LogPriority.DEBUG, debug)
                success = False
            else:
                outputufw = self.ch.getOutputString()
                if re.search('Status: active', outputufw):
                    ufwcmd = '/usr/sbin/ufw --force disable'
                    if not self.ch.executeCommand(ufwcmd):
                        debug = "Unable to disable firewall for unit test\n"
                        self.logger.log(LogPriority.DEBUG, debug)
                        success = False
                    else:
                        cmdufw = "/usr/sbin/ufw status verbose"
                        if not self.ch.executeCommand(cmdufw):
                            debug = "Unable to get verbose status for unit test\n"
                            self.logger.log(LogPriority.DEBUG, debug)
                            success = False
                        else:
                            outputfw = self.cmdhelper.getOutputString()
                            if re.search("Default\:\ deny\ \(incoming\)",
                                         outputfw):
                                ufwcmd = "/usr/sbin/ufw default allow incoming"
                                if not self.ch.executeCommand(ufwcmd):
                                    debug = "Unable to set allow status for unit test\n"
                                    self.logger.log(LogPriority.DEBUG, debug)
                                    success = False
        elif os.path.exists('/usr/bin/system-config-firewall') or \
            os.path.exists('/usr/bin/system-config-firewall-tui'):
            print("system-config-firewall commands exist\n")
            fwpath = '/etc/sysconfig/system-config-firewall'
            iptpath = '/etc/sysconfig/iptables'
            ip6tpath = '/etc/sysconfig/ip6tables'
            if os.path.exists(fwpath):
                os.remove(fwpath)
            if os.path.exists(iptpath):
                os.remove(iptpath)
            if os.path.exists(ip6tpath):
                os.remove(ip6tpath)
            if not self.servicehelper.disableService('iptables'):
                print("unable to disable iptables\n")
                success = False
                debug = "Could not disable iptables in unit test\n"
                self.logger.log(LogPriority.DEBUG, debug)
            if not self.servicehelper.disableService('ip6tables'):
                print("unable to disable ip6tables\n")
                success = False
                debug = "Could not disable ip6tables in unit test\n"
                self.logger.log(LogPriority.DEBUG, debug)
            cmd = "/sbin/service iptables stop"
            if not self.ch.executeCommand(cmd):
                success = False
                debug = "Unable to stop iptables in unit test\n"
                print("unable to stop iptables in unit test\n")
                self.logger.log(LogPriority.DEBUG, debug)
            cmd = "/sbin/service ip6tables stop"
            if not self.ch.executeCommand(cmd):
                success = False
                debug = "Unable to stop ip6tables in unit test\n"
                print("unable to stop iop6tables in unit test\n")
                self.logger.log(LogPriority.DEBUG, debug)
        elif os.path.exists(self.iprestore) and \
                os.path.exists(self.ip6restore):
            if os.path.exists(self.iptScriptPath):
                if not os.remove(self.iptScriptPath):
                    debug = "Unable to remove " + self.iptScriptPath + " for setConditionsForRule\n"
                    self.logger.log(LogPriority.DEBUG, debug)
                    success = False
        return success

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

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

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

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

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

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

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

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

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

    def getScriptValues(self, scriptname):
        if scriptname == "iptscript":
            iptScript = '''fw_custom_after_chain_creation() {
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
-A INPUT -p ipv6-icmp -j ACCEPT
-A INPUT -m state --state NEW -m udp -p udp --dport 546 -d fe80::/64 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp6-adm-prohibited
-A FORWARD -j REJECT --reject-with icmp6-adm-prohibited
    true
}

fw_custom_before_port_handling() {
    true
}

fw_custom_before_masq() {
    true
}

fw_custom_before_denyall() {
    true
}

fw_custom_after_finished() {
    true
}
'''
            return iptScript
        elif scriptname == "iptables":
            iptables = '''*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT
'''
            return iptables
        elif scriptname == "ip6tables":
            ip6tables = '''*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p ipv6-icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m udp -p udp --dport 546 -d fe80::/64 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp6-adm-prohibited
-A FORWARD -j REJECT --reject-with icmp6-adm-prohibited
COMMIT
'''
            return ip6tables
        elif scriptname == "systemconfigurefirewall":
            systemconfigfirewall = '''# Configuration file for system-config-firewall

--enabled
--service=ssh
'''
            return systemconfigfirewall
        elif scriptname == "sysconfigiptables":
            sysconfigiptables = '''# Firewall configuration written by system-config-firewall
# Manual customization of this file is not recommended.
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT
'''
            return sysconfigiptables
        elif scriptname == "sysconfigip6tables":
            sysconfigip6tables = '''# Firewall configuration written by system-config-firewall
# Manual customization of this file is not recommended.
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p ipv6-icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m udp -p udp --dport 546 -d fe80::/64 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp6-adm-prohibited
-A FORWARD -j REJECT --reject-with icmp6-adm-prohibited
COMMIT
'''
            return sysconfigip6tables
Ejemplo n.º 18
0
class zzzTestRuleSecureMDNS(RuleTest):

    def setUp(self):
        RuleTest.setUp(self)
        self.rule = SecureMDNS(self.config,
                               self.environ,
                               self.logdispatch,
                               self.statechglogger)
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.ch = CommandHelper(self.logdispatch)
        self.dc = "/usr/bin/defaults"
        self.lc = "/bin/launchctl"
        self.plb = "/usr/libexec/PlistBuddy"
        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: ekkehard j. koch
        '''
        success = True
        if self.environ.getosfamily() == "darwin":
            success = False
            osxversion = str(self.environ.getosver())
            if osxversion.startswith("10.10.0") or osxversion.startswith("10.10.1") or osxversion.startswith("10.10.2") or osxversion.startswith("10.10.3"):
                self.service = "/System/Library/LaunchDaemons/com.apple.discoveryd.plist"
                self.servicename = "com.apple.networking.discoveryd"
                self.parameter = "--no-multicast"
                self.pbd =  self.plb + ' -c "Delete :ProgramArguments: string '  + self.parameter + '" ' +  self.service
                success = True
            else:
                self.service = "/System/Library/LaunchDaemons/com.apple.mDNSResponder.plist"
                if osxversion.startswith("10.10"):
                    self.servicename = "com.apple.mDNSResponder.reloaded"
                    self.parameter = "-NoMulticastAdvertisements"
                else:
                    self.servicename = "com.apple.mDNSResponder"
                    self.parameter = "-NoMulticastAdvertisements"
                self.pbd =  self.plb + ' -c "Delete :ProgramArguments: string ' + self.parameter + '" ' +  self.service
                success = True
# This needs to be fixed
#            if success:
#                command = self.pbd
#                success = self.ch.executeCommand(command)
            if success:
                success = self.sh.reloadservice(self.service, self.servicename)
        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 zzzTestFrameworkServiceHelper(unittest.TestCase):
    """
    Class docs
    """

    def setUp(self):
        """
        initialize and set class variables and objects

        """

        self.environ = Environment()
        self.environ.setdebugmode(True)
        self.logger = LogDispatcher(self.environ)
        self.mysh = ServiceHelper(self.environ, self.logger)

        # set service name
        self.myservice = 'crond'
        self.myservicename = ""
        if self.environ.getosfamily() == 'darwin':
            self.myservice = "/Library/LaunchDaemons/gov.lanl.stonix.report.plist"
            self.myservicename = "gov.lanl.stonix.report"
        elif self.environ.getosfamily() == 'solaris':
            self.myservice = 'svc:/system/cron:default'
        elif self.environ.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'

        if self.environ.getosfamily() == "darwin":
            self.service = self.myservice, self.myservicename
        else:
            self.service = [self.myservice]

        # store system initial state
        self.orig_enabled = self.mysh.auditService(*self.service)

    def tearDown(self):
        """
        restore system initial state

        """

        if self.orig_enabled:
            self.mysh.enableService(*self.service)
        else:
            self.mysh.disableService(*self.service)

    def testListServices(self):
        """
        test listing of services

        """

        services = self.mysh.listServices()

        self.assertGreater(len(services), 0)
        self.assertIsInstance(services, list)

    def testDisable(self):
        """
        test disabling a service from initial state:
        enabled

        """

        # make sure service is started, so stopping it will be a valid test of the function
        if not self.mysh.auditService(*self.service):
            self.mysh.enableService(*self.service)

        disabled = self.mysh.disableService(*self.service)
        self.assertTrue(disabled)

    def testEnable(self):
        """
        test enabling a service from initial state:
        disabled

        """

        # make sure service is stopped, so starting it will be a valid test of the function
        if self.mysh.auditService(*self.service):
            self.mysh.disableService(*self.service)

        enabled = self.mysh.enableService(*self.service)
        self.assertTrue(enabled)

    def testReloadService(self):
        """
        test reloading a service from both initial states:
        enabled
        disabled

        """

        self.mysh.disableService(*self.service)
        reloaded1 = self.mysh.reloadService(*self.service)
        self.assertTrue(reloaded1)

        self.mysh.enableService(*self.service)
        reloaded2 = self.mysh.reloadService(*self.service)
        self.assertTrue(reloaded2)

    def testIsRunning(self):
        """
        test status checking to see if a service
        is running
        (start and stop not implemented in all helpers)

        """

        if self.mysh.startService(*self.service):
            self.assertTrue(self.mysh.isRunning(*self.service))

        if self.mysh.stopService(*self.service):
            self.assertFalse(self.mysh.isRunning(*self.service))
Ejemplo n.º 20
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
Ejemplo n.º 21
0
class zzzTestFrameworkServiceHelper(unittest.TestCase):
    '''Class docs'''

    def setUp(self):
        '''initialize and set class variables and objects'''

        self.environ = Environment()
        self.environ.setdebugmode(True)
        self.logger = LogDispatcher(self.environ)
        self.mysh = ServiceHelper(self.environ, self.logger)

        # set service name
        self.myservice = 'crond'
        self.myservicename = ""
        if self.environ.getosfamily() == 'darwin':
            self.myservice = "/Library/LaunchDaemons/gov.lanl.stonix.report.plist"
            self.myservicename = "gov.lanl.stonix.report"
        elif self.environ.getosfamily() == 'solaris':
            self.myservice = 'svc:/system/cron:default'
        elif self.environ.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'

        if self.environ.getosfamily() == "darwin":
            self.service = self.myservice, self.myservicename
        else:
            self.service = [self.myservice]

        # store system initial state
        self.orig_enabled = self.mysh.auditService(*self.service)

    def tearDown(self):
        '''restore system initial state'''

        if self.orig_enabled:
            self.mysh.enableService(*self.service)
        else:
            self.mysh.disableService(*self.service)

    def testListServices(self):
        '''test listing of services'''

        services = self.mysh.listServices()

        self.assertGreater(len(services), 0)
        self.assertIsInstance(services, list)

    def testDisable(self):
        '''test disabling a service from initial state:
        enabled


        '''

        # make sure service is started, so stopping it will be a valid test of the function
        if not self.mysh.auditService(*self.service):
            self.mysh.enableService(*self.service)

        disabled = self.mysh.disableService(*self.service)
        self.assertTrue(disabled)

    def testEnable(self):
        '''test enabling a service from initial state:
        disabled


        '''

        # make sure service is stopped, so starting it will be a valid test of the function
        if self.mysh.auditService(*self.service):
            self.mysh.disableService(*self.service)

        enabled = self.mysh.enableService(*self.service)
        self.assertTrue(enabled)

    def testReloadService(self):
        '''test reloading a service from both initial states:
        enabled
        disabled


        '''

        self.mysh.disableService(*self.service)
        reloaded1 = self.mysh.reloadService(*self.service)
        self.assertTrue(reloaded1)

        self.mysh.enableService(*self.service)
        reloaded2 = self.mysh.reloadService(*self.service)
        self.assertTrue(reloaded2)

    def testIsRunning(self):
        '''test status checking to see if a service
        is running
        (start and stop not implemented in all helpers)


        '''

        if self.mysh.startService(*self.service):
            self.assertTrue(self.mysh.isRunning(*self.service))

        if self.mysh.stopService(*self.service):
            self.assertFalse(self.mysh.isRunning(*self.service))
Ejemplo n.º 22
0
class zzzTestRuleSecureMDNS(RuleTest):
    def setUp(self):
        RuleTest.setUp(self)
        self.rule = SecureMDNS(self.config, self.environ, self.logdispatch,
                               self.statechglogger)
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.ch = CommandHelper(self.logdispatch)
        self.dc = "/usr/bin/defaults"
        self.lc = "/bin/launchctl"
        self.plb = "/usr/libexec/PlistBuddy"
        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: ekkehard j. koch
        '''
        success = True
        if self.environ.getosfamily() == "darwin":
            success = False
            osxversion = str(self.environ.getosver())
            if osxversion.startswith("10.10.0") or osxversion.startswith(
                    "10.10.1") or osxversion.startswith(
                        "10.10.2") or osxversion.startswith("10.10.3"):
                self.service = "/System/Library/LaunchDaemons/com.apple.discoveryd.plist"
                self.servicename = "com.apple.networking.discoveryd"
                self.parameter = "--no-multicast"
                self.pbd = self.plb + ' -c "Delete :ProgramArguments: string ' + self.parameter + '" ' + self.service
                success = True
            else:
                self.service = "/System/Library/LaunchDaemons/com.apple.mDNSResponder.plist"
                if osxversion.startswith("10.10"):
                    self.servicename = "com.apple.mDNSResponder.reloaded"
                    self.parameter = "-NoMulticastAdvertisements"
                else:
                    self.servicename = "com.apple.mDNSResponder"
                    self.parameter = "-NoMulticastAdvertisements"
                self.pbd = self.plb + ' -c "Delete :ProgramArguments: string ' + self.parameter + '" ' + self.service
                success = True


# This needs to be fixed
#            if success:
#                command = self.pbd
#                success = self.ch.executeCommand(command)
            if success:
                success = self.sh.reloadservice(self.service, self.servicename)
        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
Ejemplo n.º 23
0
class zzzTestRuleSecureMDNS(RuleTest):

    def setUp(self):
        RuleTest.setUp(self)
        self.rule = SecureMDNS(self.config,
                               self.environ,
                               self.logdispatch,
                               self.statechglogger)
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.ch = CommandHelper(self.logdispatch)
        self.plb = "/usr/libexec/PlistBuddy"
        self.sh = ServiceHelper(self.environ, self.logdispatch)
        self.service = ""
        self.serviceTarget=""

    def tearDown(self):
        if os.path.exists(self.service + ".stonixtmp"):
            os.rename(self.service + ".stonixtmp", self.service)

    def runTest(self):
        self.simpleRuleTest()

    def setConditionsForRule(self):
        '''
        Configure system for the unit test
        @param self: essential if you override this definition
        @return: boolean - If successful True; If failure False
        @author: ekkehard j. koch
        '''
        success = True
        if self.environ.getosfamily() == "darwin":
            success = False
            osxversion = str(self.environ.getosver())
            if osxversion.startswith("10.10.0") or \
               osxversion.startswith("10.10.1") or \
               osxversion.startswith("10.10.2") or \
               osxversion.startswith("10.10.3"):
                debug = "Using discoveryd LaunchDaemon"
                self.logdispatch.log(LogPriority.DEBUG, debug)
                service = \
                    "/System/Library/LaunchDaemons/com.apple.discoveryd.plist"
                servicename = "com.apple.networking.discoveryd"
                parameter = "--no-multicast"
                plistText = readFile(service, self.logdispatch)
                newPlistText = re.sub("<string>" + parameter + "</string>",
                                      "", "".join(plistText))
                success = True
            else:
                debug = "Using mDNSResponder LaunchDaemon"
                self.logdispatch.log(LogPriority.DEBUG, debug)
                service = "/System/Library/LaunchDaemons/" + \
                    "com.apple.mDNSResponder.plist"
                if osxversion.startswith("10.10"):
                    servicename = "com.apple.mDNSResponder.reloaded"
                    parameter = "-NoMulticastAdvertisements"
                else:
                    servicename = "com.apple.mDNSResponder"
                    parameter = "-NoMulticastAdvertisements"
                plistText = readFile(service, self.logdispatch)
                newPlistText = re.sub("<string>" + parameter + "</string>",
                                      "", "".join(plistText))
                success = True
            self.service = service
            if success and self.sh.auditService(service, serviceTarget=servicename):
                success = writeFile(service + ".stonixtmp", "".join(plistText),
                                    self.logdispatch)
                success = writeFile(service, newPlistText, self.logdispatch)
            if success and self.sh.auditService(service, serviceTarget=servicename):
                success = self.sh.reloadService(service, serviceTarget=servicename)
        else:
            ph = Pkghelper(self.logdispatch, self.environ)
            package = "avahi-daemon"
            service = "avahi-daemon"
            if (ph.determineMgr() == "yum" or ph.determineMgr() == "dnf"):
                package = "avahi"
                path = "/etc/sysconfig/network"
                if os.path.exists(path):
                    tmppath = path + ".tmp"
                    data = {"NOZEROCONF": "yes"}
                    editor = KVEditorStonix(self.statechglogger,
                                            self.logdispatch, "conf",
                                            path, tmppath, data,
                                            "notpresent", "closedeq")
                    if not editor.report():
                        if editor.fix():
                            if not editor.commit():
                                success = False
                        else:
                            success = False
            elif ph.determineMgr() == "zypper":
                package = "avahi"
            if not ph.check(package) and ph.checkAvailable(package):
                success = ph.install(package)
            if success and not self.sh.auditService(service, serviceTarget=self.serviceTarget):
                self.sh.enableService(service, serviceTarget=self.serviceTarget)
        return success

    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 zzzTestRuleConfigureLinuxFirewall(RuleTest):

    def setUp(self):
        RuleTest.setUp(self)
        self.rule = ConfigureLinuxFirewall(self.config,
                                           self.environ,
                                           self.logdispatch,
                                           self.statechglogger)
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.logger = self.logdispatch
        self.ch = CommandHelper(self.logger)
        self.servicehelper = ServiceHelper(self.environ, self.logger)
        self.checkUndo = True
        self.isfirewalld = False
        self.isufw = False
        if os.path.exists('/bin/firewall-cmd'):
            self.isfirewalld = True
        if os.path.exists('/usr/sbin/ufw'):
            self.isufw = True

        # mostly pertains to RHEL6, Centos6
        self.iptables = "/usr/sbin/iptables"
        if not os.path.exists(self.iptables):
            self.iptables = '/sbin/iptables'
        self.ip6tables = "/usr/sbin/ip6tables"
        if not os.path.exists(self.ip6tables):
            self.ip6tables = '/sbin/ip6tables'
        if os.path.exists("/usr/sbin/iptables-restore"):
            self.iprestore = "/usr/sbin/iptables-restore"
        elif os.path.exists("/sbin/iptables-restore"):
            self.iprestore = "/sbin/iptables-restore"

        if os.path.exists("/usr/sbin/ip6tables-restore"):
            self.ip6restore = "/usr/sbin/ip6tables-restore"
        elif os.path.exists("/sbin/ip6tables-restore"):
            self.ip6restore = "/sbin/ip6tables-restore"
        self.scriptType = ""

    def tearDown(self):
        pass

    def runTest(self):
        self.simpleRuleTest()

    def setConditionsForRule(self):
        '''
        Configure system for the unit test
        @param self: essential if you override this definition
        @return: boolean - If successful True; If failure False
        @author: ekkehard j. koch
        '''
        success = True
        self.detailedresults = ""
        self.iptScriptPath = ""
        scriptExists = ""
        debug = ""
        if self.isfirewalld:
            if self.servicehelper.auditService('firewalld.service'):
                if not self.servicehelper.disableService('firewalld.service'):
                    success = False
        if self.isufw:
            cmdufw = '/usr/sbin/ufw status'
            if not self.ch.executeCommand(cmdufw):
                debug = "Unable to run ufw status command in unit test\n"
                self.logger.log(LogPriority.DEBUG, debug)
                success = False
            else:
                outputufw = self.ch.getOutputString()
                if re.search('Status: active', outputufw):
                    ufwcmd = '/usr/sbin/ufw --force disable'
                    if not self.ch.executeCommand(ufwcmd):
                        debug = "Unable to disable firewall for unit test\n"
                        self.logger.log(LogPriority.DEBUG, debug)
                        success = False
                    else:
                        cmdufw = "/usr/sbin/ufw status verbose"
                        if not self.ch.executeCommand(cmdufw):
                            debug = "Unable to get verbose status for unit test\n"
                            self.logger.log(LogPriority.DEBUG, debug)
                            success = False
                        else:
                            outputfw = self.cmdhelper.getOutputString()
                            if re.search("Default\:\ deny\ \(incoming\)", outputfw):
                                ufwcmd = "/usr/sbin/ufw default allow incoming"
                                if not self.ch.executeCommand(ufwcmd):
                                    debug = "Unable to set allow status for unit test\n"
                                    self.logger.log(LogPriority.DEBUG, debug)
                                    success = False
        elif os.path.exists('/usr/bin/system-config-firewall') or \
            os.path.exists('/usr/bin/system-config-firewall-tui'):
            print "system-config-firewall commands exist\n"
            fwpath = '/etc/sysconfig/system-config-firewall'
            iptpath = '/etc/sysconfig/iptables'
            ip6tpath = '/etc/sysconfig/ip6tables'
            if os.path.exists(fwpath):
                os.remove(fwpath)
            if os.path.exists(iptpath):
                os.remove(iptpath)
            if os.path.exists(ip6tpath):
                os.remove(ip6tpath)
            if not self.servicehelper.disableService('iptables'):
                print "unable to disable iptables\n"
                success = False
                debug = "Could not disable iptables in unit test\n"
                self.logger.log(LogPriority.DEBUG, debug)
            if not self.servicehelper.disableService('ip6tables'):
                print "unable to disable ip6tables\n"
                success = False
                debug = "Could not disable ip6tables in unit test\n"
                self.logger.log(LogPriority.DEBUG, debug)
            cmd = "/sbin/service iptables stop"
            if not self.ch.executeCommand(cmd):
                success = False
                debug = "Unable to stop iptables in unit test\n"
                print "unable to stop iptables in unit test\n"
                self.logger.log(LogPriority.DEBUG, debug)
            cmd = "/sbin/service ip6tables stop"
            if not self.ch.executeCommand(cmd):
                success = False
                debug = "Unable to stop ip6tables in unit test\n"
                print "unable to stop iop6tables in unit test\n"
                self.logger.log(LogPriority.DEBUG, debug)
        elif os.path.exists(self.iprestore) and \
                os.path.exists(self.ip6restore):
            if os.path.exists(self.iptScriptPath):
                if not os.remove(self.iptScriptPath):
                    debug = "Unable to remove " + self.iptScriptPath + " for setConditionsForRule\n"
                    self.logger.log(LogPriority.DEBUG, debug)
                    success = False
        return success

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

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

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

    def getScriptValues(self, scriptname):
        if scriptname == "iptscript":
            iptScript = '''fw_custom_after_chain_creation() {
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
-A INPUT -p ipv6-icmp -j ACCEPT
-A INPUT -m state --state NEW -m udp -p udp --dport 546 -d fe80::/64 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp6-adm-prohibited
-A FORWARD -j REJECT --reject-with icmp6-adm-prohibited
    true
}

fw_custom_before_port_handling() {
    true
}

fw_custom_before_masq() {
    true
}

fw_custom_before_denyall() {
    true
}

fw_custom_after_finished() {
    true
}
'''
            return iptScript
        elif scriptname == "iptables":
            iptables = '''*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT
'''
            return iptables
        elif scriptname == "ip6tables":
            ip6tables = '''*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p ipv6-icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m udp -p udp --dport 546 -d fe80::/64 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp6-adm-prohibited
-A FORWARD -j REJECT --reject-with icmp6-adm-prohibited
COMMIT
'''
            return ip6tables
        elif scriptname == "systemconfigurefirewall":
            systemconfigfirewall = '''# Configuration file for system-config-firewall

--enabled
--service=ssh
'''
            return systemconfigfirewall
        elif scriptname == "sysconfigiptables":
            sysconfigiptables = '''# Firewall configuration written by system-config-firewall
# Manual customization of this file is not recommended.
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT
'''
            return sysconfigiptables
        elif scriptname == "sysconfigip6tables":
            sysconfigip6tables = '''# Firewall configuration written by system-config-firewall
# Manual customization of this file is not recommended.
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p ipv6-icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m udp -p udp --dport 546 -d fe80::/64 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp6-adm-prohibited
-A FORWARD -j REJECT --reject-with icmp6-adm-prohibited
COMMIT
'''
            return sysconfigip6tables
class 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
Ejemplo n.º 26
0
class zzzTestRuleSecureMDNS(RuleTest):
    def setUp(self):
        RuleTest.setUp(self)
        self.rule = SecureMDNS(self.config, self.environ, self.logdispatch,
                               self.statechglogger)
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.ch = CommandHelper(self.logdispatch)
        self.plb = "/usr/libexec/PlistBuddy"
        self.sh = ServiceHelper(self.environ, self.logdispatch)
        self.service = ""
        self.serviceTarget = ""

    def tearDown(self):
        if os.path.exists(self.service + ".stonixtmp"):
            os.rename(self.service + ".stonixtmp", self.service)

    def runTest(self):
        self.simpleRuleTest()

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

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

        '''
        success = True
        if self.environ.getosfamily() == "darwin":
            success = False
            osxversion = str(self.environ.getosver())
            if osxversion.startswith("10.10.0") or \
               osxversion.startswith("10.10.1") or \
               osxversion.startswith("10.10.2") or \
               osxversion.startswith("10.10.3"):
                debug = "Using discoveryd LaunchDaemon"
                self.logdispatch.log(LogPriority.DEBUG, debug)
                service = \
                    "/System/Library/LaunchDaemons/com.apple.discoveryd.plist"
                servicename = "com.apple.networking.discoveryd"
                parameter = "--no-multicast"
                plistText = readFile(service, self.logdispatch)
                newPlistText = re.sub("<string>" + parameter + "</string>", "",
                                      "".join(plistText))
                success = True
            else:
                debug = "Using mDNSResponder LaunchDaemon"
                self.logdispatch.log(LogPriority.DEBUG, debug)
                service = "/System/Library/LaunchDaemons/" + \
                    "com.apple.mDNSResponder.plist"
                if osxversion.startswith("10.10"):
                    servicename = "com.apple.mDNSResponder.reloaded"
                    parameter = "-NoMulticastAdvertisements"
                else:
                    servicename = "com.apple.mDNSResponder"
                    parameter = "-NoMulticastAdvertisements"
                plistText = readFile(service, self.logdispatch)
                newPlistText = re.sub("<string>" + parameter + "</string>", "",
                                      "".join(plistText))
                success = True
            self.service = service
            if success and self.sh.auditService(service,
                                                serviceTarget=servicename):
                success = writeFile(service + ".stonixtmp", "".join(plistText),
                                    self.logdispatch)
                success = writeFile(service, newPlistText, self.logdispatch)
            if success and self.sh.auditService(service,
                                                serviceTarget=servicename):
                success = self.sh.reloadService(service,
                                                serviceTarget=servicename)
        else:
            ph = Pkghelper(self.logdispatch, self.environ)
            package = "avahi-daemon"
            service = "avahi-daemon"
            if (ph.determineMgr() == "yum" or ph.determineMgr() == "dnf"):
                package = "avahi"
                path = "/etc/sysconfig/network"
                if os.path.exists(path):
                    tmppath = path + ".tmp"
                    data = {"NOZEROCONF": "yes"}
                    editor = KVEditorStonix(self.statechglogger,
                                            self.logdispatch, "conf", path,
                                            tmppath, data, "notpresent",
                                            "closedeq")
                    if not editor.report():
                        if editor.fix():
                            if not editor.commit():
                                success = False
                        else:
                            success = False
            elif ph.determineMgr() == "zypper":
                package = "avahi"
            if not ph.check(package) and ph.checkAvailable(package):
                success = ph.install(package)
            if success and not self.sh.auditService(
                    service, serviceTarget=self.serviceTarget):
                self.sh.enableService(service,
                                      serviceTarget=self.serviceTarget)
        return success

    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