Exemplo n.º 1
0
 def setConditionsForRule(self):
     '''
     Configure system for the unit test
     @param self: essential if you override this definition
     @return: boolean - If successful True; If failure False
     @author: ekkehard j. koch
     '''
     success = True
     if self.environ.getosfamily() == "darwin":
         command = [
             "/usr/bin/defaults", "-currentHost", "write", "NSGlobalDomain",
             "NSDocumentSaveNewDocumentsToCloud", "-bool", "yes"
         ]
         success = self.ch.executeCommand(command)
     else:
         ph = Pkghelper(self.logdispatch, self.environ)
         success = ph.install("unity-lens-shopping")
     return success
    def 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
        ph = Pkghelper(self.logdispatch, self.environ)
        game = "gnuchess"
        if ph.checkAvailable(game):
            success = ph.install(game)
            if not success:
                error = "Could not install gnuchess. Please check that the " + \
                    "package manager cache is updated and that this PC is " + \
                    "online, and then attempt to run unit test again."
                self.logdispatch.log(LogPriority.ERROR, error)

        return success
    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
        ph = Pkghelper(self.logdispatch, self.environ)
        game = "gnuchess"
        if ph.checkAvailable(game):
            success = ph.install(game)
            if not success:
                error = (
                    "Could not install gnuchess. Please check that the "
                    + "package manager cache is updated and that this PC is "
                    + "online, and then attempt to run unit test again."
                )
                self.logdispatch.log(LogPriority.ERROR, error)

        return success
 def setConditionsForRule(self):
     '''
     Configure system for the unit test
     @param self: essential if you override this definition
     @return: boolean - If successful True; If failure False
     @author: ekkehard j. koch
     '''
     success = True
     if self.environ.getosfamily() == "darwin":
         command = ["/usr/bin/defaults",
                    "-currentHost",
                    "write",
                    "NSGlobalDomain",
                    "NSDocumentSaveNewDocumentsToCloud",
                    "-bool",
                    "yes"]
         success = self.ch.executeCommand(command)
     else:
         ph = Pkghelper(self.logdispatch, self.environ)
         success = ph.install("unity-lens-shopping")
     return success
Exemplo n.º 5
0
    def setConditionsForRule(self):
        '''Configure system for the unit test

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

        '''
        success = False
        ph = Pkghelper(self.logdispatch, self.environ)
        gamelist = ['bovo', 'gnuchess']
        for game in gamelist:
            if ph.checkAvailable(game):
                if ph.install(game):
                    success = True
        if not success:
            error = "Could not install any games for presetup in unit test. " + \
                    "Please check that the package manager cache is updated " + \
                    "and that this PC is online, and then attempt to run " + \
                    "unit test again."
            self.logdispatch.log(LogPriority.ERROR, error)

        return success
Exemplo n.º 6
0
 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
Exemplo n.º 7
0
class zzzTestRuleSecureMTA(RuleTest):
    def setUp(self):
        RuleTest.setUp(self)
        self.rule = SecureMTA(self.config, self.environ, self.logdispatch,
                              self.statechglogger)
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.ch = CommandHelper(self.logdispatch)
        if self.environ.operatingsystem == "Mac OS X":
            self.isMac = True
        else:
            self.isMac = False
        if not self.isMac:
            self.ph = Pkghelper(self.logdispatch, self.environ)
            self.origState = [False, False, False, False]

            self.smPath = "/etc/mail/sendmail.cf"
            self.smTmp = "/tmp/" + os.path.split(self.smPath)[1] + ".utmp"
            self.pfPathlist = [
                '/etc/postfix/main.cf', '/private/etc/postfix/main.cf',
                '/usr/lib/postfix/main.cf'
            ]
            self.pfPath = ""
            for path in self.pfPathlist:
                if os.path.exists(path):
                    self.pfPath = path
            if self.pfPath == "":
                self.pfPath = "/etc/postfix/main.cf"
            self.pfTmp = "/tmp/" + os.path.split(self.pfPath)[1] + ".utmp"

    def tearDown(self):
        if os.path.exists(self.smTmp):
            os.rename(self.smTmp, self.smPath)
        if os.path.exists(self.pfTmp):
            os.rename(self.pfTmp, self.pfPath)

    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
        # origState variables are not currently used
        if not self.isMac:
            if self.ph.check("sendmail"):
                self.origState[0] = True
            if self.ph.check("postfix"):
                self.origState[1] = True
            if os.path.exists(self.smPath):
                self.origState[2] = True
                os.rename(self.smPath, self.smTmp)
            if os.path.exists(self.pfPath):
                self.origState[3] = True
                os.rename(self.pfPath, self.pfTmp)
        return success

    def testFalseFalseFalseFalse(self):
        if not self.isMac:
            if self.ph.check("sendmail"):
                self.ph.remove("sendmail")
            if self.ph.check("postfix"):
                self.ph.remove("postfix")
            if os.path.exists(self.smPath):
                os.remove(self.smPath)
            if os.path.exists(self.pfPath):
                os.remove(self.pfPath)
            self.simpleRuleTest()

    def testTrueFalseFalseFalse(self):
        if not self.isMac:
            if not self.ph.check("sendmail"):
                self.ph.install("sendmail")
            if self.ph.check("postfix"):
                self.ph.remove("postfix")
            if os.path.exists(self.smPath):
                os.remove(self.smPath)
            if os.path.exists(self.pfPath):
                os.remove(self.pfPath)
            self.simpleRuleTest()

    def testTrueTrueFalseFalse(self):
        if not self.isMac:
            if not self.ph.check("sendmail"):
                self.ph.install("sendmail")
            if not self.ph.check("postfix"):
                self.ph.install("postfix")
            if os.path.exists(self.smPath):
                os.remove(self.smPath)
            if os.path.exists(self.pfPath):
                os.remove(self.pfPath)
            self.simpleRuleTest()

    def testTrueTrueTrueFalse(self):
        if not self.isMac:
            if not self.ph.check("sendmail"):
                self.ph.install("sendmail")
            if not self.ph.check("postfix"):
                self.ph.install("postfix")
            if not os.path.exists(self.smPath):
                open(self.smPath, "w")
            if os.path.exists(self.pfPath):
                os.remove(self.pfPath)
            self.simpleRuleTest()

    def testTrueTrueTrueTrue(self):
        if not self.isMac:
            if not self.ph.check("sendmail"):
                self.ph.install("sendmail")
            if not self.ph.check("postfix"):
                self.ph.install("postfix")
            if not os.path.exists(self.smPath):
                open(self.smPath, "w")
            if not os.path.exists(self.pfPath):
                open(self.pfPath, "w")
            self.simpleRuleTest()

    def testTrueFalseTrueFalse(self):
        if not self.isMac:
            if not self.ph.check("sendmail"):
                self.ph.install("sendmail")
            if self.ph.check("postfix"):
                self.ph.remove("postfix")
            if not os.path.exists(self.smPath):
                open(self.smPath, "w")
            if os.path.exists(self.pfPath):
                os.remove(self.pfPath)
            self.simpleRuleTest()

    def testFalseTrueFalseFalse(self):
        if not self.isMac:
            if self.ph.check("sendmail"):
                self.ph.remove("sendmail")
            if not self.ph.check("postfix"):
                self.ph.install("postfix")
            if os.path.exists(self.smPath):
                os.remove(self.smPath)
            if os.path.exists(self.pfPath):
                os.remove(self.pfPath)
            self.simpleRuleTest()

    def testFalseTrueFalseTrue(self):
        if not self.isMac:
            if self.ph.check("sendmail"):
                self.ph.remove("sendmail")
            if not self.ph.check("postfix"):
                self.ph.install("postfix")
            if os.path.exists(self.smPath):
                os.remove(self.smPath)
            if not os.path.exists(self.pfPath):
                open(self.pfPath, "w")
            self.simpleRuleTest()

    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
Exemplo n.º 8
0
class zzzTestRuleForceIdleLogout(RuleTest):
    def setUp(self):
        RuleTest.setUp(self)
        self.rule = ForceIdleLogout(self.config, self.environ,
                                    self.logdispatch, self.statechglogger)
        self.logger = self.logdispatch
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.rule.filci.updatecurrvalue(True)
        self.checkUndo = True
        self.cmdhelper = CommandHelper(self.logger)
        self.ph = Pkghelper(self.logger, self.environ)
        self.gnomesettingpath = "/etc/dconf/db/local.d/00-autologout"
        self.gnomelockpath = "/etc/dconf/db/local.d/locks/autologout"
        self.undotimeout = ""
        self.undoforcelogout = ""
        self.kdesddm = False
        myos = self.environ.getostype().lower()
        if re.search("red hat", myos) or re.search("centos", myos):
            self.gconf = "GConf2"
        else:
            self.gconf = "gconf2"
        self.timeoutci = self.rule.timeoutci.getcurrvalue()

    def tearDown(self):
        pass

    def runTest(self):
        self.simpleRuleTest()

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

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

        '''
        success = True
        if self.environ.osfamily == 'linux':
            try:
                self.seconds = self.timeoutci * 60
            except (TypeError):
                debug = "FORCEIDLELOGOUTTIMEOUT value is not " + \
                                        "valid!\n"
                self.logger.log(LogPriority.DEBUG, debug)
                return False
            self.kdesddm = self.ph.check("sddm")
            self.gnomesettingpath = "/etc/dconf/db/local.d/00-autologout"
            desktopmgr = False
            desktopmgrs = [
                "gdm", "gdm3", "kdm", "kde-workspace", "sddm",
                "patterns-kde-kde_yast"
            ]
            if self.ph.check("gdm") or self.ph.check("gdm3"):
                desktopmgr = True
            if self.ph.check("kdm") or self.ph.check("kde-workspace")or \
                    self.ph.check("sddm") or self.ph.check("patterns-kde-kde_yast"):
                desktopmgr = True
            if not desktopmgr:
                for mgr in desktopmgrs:
                    if self.ph.checkAvailable(mgr):
                        if self.ph.install(mgr):
                            desktopmgr = True
                if not desktopmgr:
                    success = False
                    debug = "Unable to install a desktop manager for testing\n"
                    self.logger.log(LogPriority.DEBUG, debug)
            success = self.setgnome()
            success = self.setkde()
        elif self.environ.getosfamily() == 'darwin':
            if not self.setosx():
                success = False
        return success

    def setgnome(self):
        '''
        @author: dwalker
        @return: bool - success
        '''
        debug = ""
        if self.environ.geteuid() != 0:
            debug = "Unable to set gnome conditions in unit " + \
                "test because user is not root."

        success = True
        if os.path.exists('/etc/dconf/db/local.d'):
            if os.path.exists(self.gnomesettingpath):
                if not os.remove(self.gnomesettingpath):
                    success = False
                    debug = "Unable to remove " + self.gnomesettingpath + \
                        " for unit test preconditions\n"
                    self.logger.log(LogPriority.DEBUG, debug)
        if self.ph.check(self.gconf):
            get = "/usr/bin/gconftool-2 --direct --config-source " + \
                "xml:readwrite:/etc/gconf/gconf.xml.mandatory --get "
            set = "/usr/bin/gconftool-2 --direct --config-source " + \
                "xml:readwrite:/etc/gconf/gconf.xml.mandatory --set "
            unset = "/usr/bin/gconftool-2 --direct --config-source " + \
                "xml/readwrite:/etc/gconf/gconf.xml.mandatory --unset "
            idletimecmd = get + "/desktop/gnome/session/max_idle_time"
            if self.cmdhelper.executeCommand(idletimecmd):
                output = self.cmdhelper.getOutput()
                if output:
                    try:
                        if int(output[0].strip()) == self.seconds:
                            timeout = int(self.seconds) + 5
                            idletimecmd = set + "--type integer /desktop/gnome/session/max_idle_time " + \
                                str(timeout)
                            if not self.cmdhelper.executeCommand(idletimecmd):
                                success = False
                                debug = "Unable to set incorrect timeout value for " + \
                                    "unit test preconditions\n"
                                self.logger.log(LogPriority.DEBUG, debug)
                    except (IndexError):
                        debug = "No output to display timeout value\n"
                        self.logger.log(LogPriority.DEBUG, debug)
            else:
                success = False
                debug = "Unable to obtain the timeout value\n"
                self.logger.log(LogPriority.DEBUG, debug)
            idleactcmd = get + "/desktop/gnome/session/max_idle_action"
            if self.cmdhelper.executeCommand(idleactcmd):
                output = self.cmdhelper.getOutput()
                if output:
                    if re.search("forced-logout", output[0]):
                        idleact = unset + "/desktop/gnome/session/max_idle_action"
                        if not self.cmdhelper.executeCommand(idleact):
                            success = False
                            debug = "Unable to unset max_idle_action for " + \
                                "unit test preconditions\n"
                            self.logger.log(LogPriority.DEBUG, debug)

        return success

    def setkde(self):
        '''
        @author: dwalker
        @return: bool - success
        '''
        success = True
        debug = ""
        if self.kdesddm:
            self.kdecheck = ".config/kdeglobals"
            self.rcpath = ".config/kscreenlockerrc"
            self.kdeprops = {"ScreenSaver": {"Timeout": str(self.seconds)}}
        else:
            self.kdecheck = ".kde"
            self.rcpath = ".kde/share/config/kscreensaverrc"
            self.kdeprops = {
                "ScreenSaver": {
                    "AutoLogout": "true",
                    "AutoLogoutTimeout": str(self.seconds)
                }
            }
        contents = readFile("/etc/passwd", self.logger)
        for line in contents:
            username = ""
            homepath = ""
            temp = line.split(":")
            try:
                username = temp[0]
                homepath = temp[5]
            except (IndexError):
                continue
            kdeparent = os.path.join(homepath, self.kdecheck)
            kdefile = os.path.join(homepath, self.rcpath)
            if not os.path.exists(kdeparent):
                continue
            elif os.path.exists(kdefile):
                if self.searchFile(kdefile):
                    if not self.messFile(kdefile):
                        success = False
                        debug = "Unable to set incorrect values for kde " + \
                                "for user " + username + " in " + \
                                "unit test preconditions\n"
                        self.logger.log(LogPriority.DEBUG, debug)
        return success

    def searchFile(self, filehandle):
        '''temporary method to separate the code to find directives from the
        rest of the code.  Will put back all in one method eventually
        @author: dwalker
        @return: bool
        @param filehandle: string
        '''
        self.editor = ""
        kvt = "tagconf"
        intent = "present"
        tpath = filehandle + ".tmp"
        conftype = "closedeq"
        self.editor = KVEditorStonix(self.statechglogger, self.logger, kvt,
                                     filehandle, tpath, self.kdeprops, intent,
                                     conftype)
        if not self.editor.report():
            return False
        else:
            return True

    def messFile(self, filehandle):
        success = True
        self.editor = ""
        garbagevalue = ""
        while True:
            garbagevalue = randint(0, 200)
            if garbagevalue != self.timeoutci:
                break
        kvt = "tagconf"
        intent = "present"
        tpath = filehandle + ".tmp"
        conftype = "closedeq"
        if self.kdesddm:
            self.kdecheck = ".config/kdeglobals"
            self.rcpath = ".config/kscreenlockerrc"
            self.kdeprops = {"ScreenSaver": {"Timeout": str(garbagevalue)}}
        else:
            self.kdecheck = ".kde"
            self.rcpath = ".kde/share/config/kscreensaverrc"
            self.kdeprops = {
                "ScreenSaver": {
                    "AutoLogout": "true",
                    "AutoLogoutTimeout": str(garbagevalue)
                }
            }
        self.editor = KVEditorStonix(self.statechglogger, self.logger, kvt,
                                     filehandle, tpath, self.kdeprops, intent,
                                     conftype)
        self.editor.report()
        if not self.editor.fix():
            success = False
        elif not self.editor.commit():
            success = False
        return success

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

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

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

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

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

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

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

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

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

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

    def runTest(self):
        self.simpleRuleTest()

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

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

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

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

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

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

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

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

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

    def setUp(self):
        RuleTest.setUp(self)
        self.rule = DisablePrelinking(self.config,
                                      self.environ,
                                      self.logdispatch,
                                      self.statechglogger)
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.ch = CommandHelper(self.logdispatch)
        self.ph = Pkghelper(self.logdispatch, self.environ)
        self.prelinkInstalled = False

    def tearDown(self):
        if not self.prelinkInstalled:
            self.ph.remove("prelink")

    def runTest(self):
        self.simpleRuleTest()

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

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

        '''
        success = True
        if self.ph.check("prelink"):
            self.prelinkInstalled = True
        elif self.ph.checkAvailable("prelink"):
            self.ph.install("prelink")
        else:
            return True
        path = "/usr/sbin/prelink"
        cmd = [path, "/bin/ls"]
        if os.path.exists(path):
            self.ch.executeCommand(cmd)

        if re.search("debian|ubuntu", self.environ.getostype().lower()):
            path = "/etc/default/prelink"
        else:
            path = "/etc/sysconfig/prelink"
        if os.path.exists(path):
            tmppath = path + ".tmp"
            data = {"PRELINKING": "yes"}
            self.editor = KVEditorStonix(self.statechglogger, self.logdispatch,
                                         "conf", path, tmppath,
                                         data, "present", "closedeq")
            if not self.editor.report():
                if self.editor.fix():
                    if not self.editor.commit():
                        success = False
                        self.logdispatch.log(LogPriority.ERROR,
                                             "KVEditor failed to commit.")
                else:
                    success = False
                    self.logdispatch.log(LogPriority.ERROR,
                                         "KVEditor failed to fix.")
        else:
            writeFile(path, "PRELINKING=yes", self.logdispatch)

        return success

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

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

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

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

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

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

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

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

        '''
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " +
                             str(pRuleSuccess) + ".")
        success = True
        return success
Exemplo n.º 11
0
class zzzTestRuleSecureMTA(RuleTest):

    def setUp(self):
        RuleTest.setUp(self)
        self.rule = SecureMTA(self.config,
                              self.environ,
                              self.logdispatch,
                              self.statechglogger)
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.ch = CommandHelper(self.logdispatch)
        if self.environ.operatingsystem == "Mac OS X":
            self.isMac = True
        else:
            self.isMac = False
        if not self.isMac:
            self.ph = Pkghelper(self.logdispatch, self.environ)
            self.origState = [False, False, False, False]

            self.smPath = "/etc/mail/sendmail.cf"
            self.smTmp = "/tmp/" + os.path.split(self.smPath)[1] + ".utmp"
            self.pfPathlist = ['/etc/postfix/main.cf',
                               '/private/etc/postfix/main.cf',
                               '/usr/lib/postfix/main.cf']
            self.pfPath = ""
            for path in self.pfPathlist:
                if os.path.exists(path):
                    self.pfPath = path
            if self.pfPath == "":
                self.pfPath = "/etc/postfix/main.cf"
            self.pfTmp = "/tmp/" + os.path.split(self.pfPath)[1] + ".utmp"

    def tearDown(self):
        if not self.isMac:
            if self.origState[0] is True and not self.ph.check("sendmail"):
                self.ph.install("sendmail")
            elif self.origState[0] is False and self.ph.check("sendmail"):
                self.ph.remove("sendmail")

            if self.origState[1] is True and not self.ph.check("postfix"):
                self.ph.install("postfix")
            elif self.origState[1] is False and self.ph.check("postfix"):
                self.ph.remove("postfix")

            if self.origState[2] is True and os.path.exists(self.smTmp):
                smDir = os.path.split(self.smPath)[0]
                if not os.path.exists(smDir):
                    os.makedirs(smDir)
                os.rename(self.smTmp, self.smPath)
            elif self.origState[2] is False and os.path.exists(self.smPath):
                os.remove(self.smPath)

            if self.origState[3] is True and os.path.exists(self.pfTmp):
                pfDir = os.path.split(self.pfPath)[0]
                if not os.path.exists(pfDir):
                    os.makedirs(pfDir)
                os.rename(self.pfTmp, self.pfPath)
            elif self.origState[3] is False and os.path.exists(self.pfPath):
                os.remove(self.pfPath)

    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 not self.isMac:
            if self.ph.check("sendmail"):
                self.origState[0] = True
            if self.ph.check("postfix"):
                self.origState[1] = True
            if os.path.exists(self.smPath):
                self.origState[2] = True
                os.rename(self.smPath, self.smTmp)
            if os.path.exists(self.pfPath):
                self.origState[3] = True
                os.rename(self.pfPath, self.pfTmp)
        return success

    def testFalseFalseFalseFalse(self):
        if not self.isMac:
            if self.ph.check("sendmail"):
                self.ph.remove("sendmail")
            if self.ph.check("postfix"):
                self.ph.remove("postfix")
            if os.path.exists(self.smPath):
                os.remove(self.smPath)
            if os.path.exists(self.pfPath):
                os.remove(self.pfPath)
            self.simpleRuleTest()

    def testTrueFalseFalseFalse(self):
        if not self.isMac:
            if not self.ph.check("sendmail"):
                self.ph.install("sendmail")
            if self.ph.check("postfix"):
                self.ph.remove("postfix")
            if os.path.exists(self.smPath):
                os.remove(self.smPath)
            if os.path.exists(self.pfPath):
                os.remove(self.pfPath)
            self.simpleRuleTest()

    def testTrueTrueFalseFalse(self):
        if not self.isMac:
            if not self.ph.check("sendmail"):
                self.ph.install("sendmail")
            if not self.ph.check("postfix"):
                self.ph.install("postfix")
            if os.path.exists(self.smPath):
                os.remove(self.smPath)
            if os.path.exists(self.pfPath):
                os.remove(self.pfPath)
            self.simpleRuleTest()

    def testTrueTrueTrueFalse(self):
        if not self.isMac:
            if not self.ph.check("sendmail"):
                self.ph.install("sendmail")
            if not self.ph.check("postfix"):
                self.ph.install("postfix")
            if not os.path.exists(self.smPath):
                open(self.smPath, "w")
            if os.path.exists(self.pfPath):
                os.remove(self.pfPath)
            self.simpleRuleTest()

    def testTrueTrueTrueTrue(self):
        if not self.isMac:
            if not self.ph.check("sendmail"):
                self.ph.install("sendmail")
            if not self.ph.check("postfix"):
                self.ph.install("postfix")
            if not os.path.exists(self.smPath):
                open(self.smPath, "w")
            if not os.path.exists(self.pfPath):
                open(self.pfPath, "w")
            self.simpleRuleTest()

    def testTrueFalseTrueFalse(self):
        if not self.isMac:
            if not self.ph.check("sendmail"):
                self.ph.install("sendmail")
            if self.ph.check("postfix"):
                self.ph.remove("postfix")
            if not os.path.exists(self.smPath):
                open(self.smPath, "w")
            if os.path.exists(self.pfPath):
                os.remove(self.pfPath)
            self.simpleRuleTest()

    def testFalseTrueFalseFalse(self):
        if not self.isMac:
            if self.ph.check("sendmail"):
                self.ph.remove("sendmail")
            if not self.ph.check("postfix"):
                self.ph.install("postfix")
            if os.path.exists(self.smPath):
                os.remove(self.smPath)
            if os.path.exists(self.pfPath):
                os.remove(self.pfPath)
            self.simpleRuleTest()

    def testFalseTrueFalseTrue(self):
        if not self.isMac:
            if self.ph.check("sendmail"):
                self.ph.remove("sendmail")
            if not self.ph.check("postfix"):
                self.ph.install("postfix")
            if os.path.exists(self.smPath):
                os.remove(self.smPath)
            if not os.path.exists(self.pfPath):
                open(self.pfPath, "w")
            self.simpleRuleTest()

    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
Exemplo n.º 12
0
class zzzTestRuleRemoveSoftware(RuleTest):
    def setUp(self):
        RuleTest.setUp(self)
        self.rule = RemoveSoftware(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.checkUndo = True

    def tearDown(self):
        for pkg in self.installed:
            self.ph.install(pkg)

    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: dwalker

        '''
        success = True
        self.rule.ci.updatecurrvalue(True)
        self.installed = []
        default = [
            "squid", "telnet-server", "rsh-server", "rsh", "rsh-client",
            "talk", "talk-server", "talkd", "tftp-server", "tftp", "tftpd"
        ]
        for pkg in default:
            if not self.ph.check(pkg) and self.ph.checkAvailable(pkg):
                self.ph.install(pkg)
            elif self.ph.check(pkg) and self.ph.checkAvailable(pkg):
                self.installed.append(pkg)
        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: dwalker

        '''
        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: dwalker

        '''
        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: dwalker

        '''
        self.logdispatch.log(LogPriority.DEBUG,
                             "pRuleSuccess = " + str(pRuleSuccess) + ".")
        success = True
        return success
Exemplo n.º 13
0
class zzzTestRuleDisableUbuntuDataCollection(RuleTest):
    def setUp(self):
        '''


        :returns: None
        @author: ekkehard j. koch, Breen Malmberg

        '''

        RuleTest.setUp(self)
        self.rule = DisableUbuntuDataCollection(self.config, self.environ,
                                                self.logdispatch,
                                                self.statechglogger)
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.ph = Pkghelper(self.logdispatch, self.environ)
        self.datacollectionpkgs = [
            "popularity-contest", "apport", "ubuntu-report"
        ]
        self.teardownpkgs = []

    def tearDown(self):
        '''


        :returns: None

        '''

        for pkg in self.teardownpkgs:
            self.ph.remove(pkg)
            self.teardownpkgs.remove(pkg)

    def runTest(self):
        '''


        :returns: None

        '''

        self.simpleRuleTest()

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


        :returns: success

        :rtype: bool
@author: ekkehard j. koch, Breen Malmberg

        '''

        success = True
        self.rule.enabledCI.updatecurrvalue(True)

        for pkg in self.datacollectionpkgs:
            if not self.ph.check(pkg):
                self.ph.install(pkg)
                self.teardownpkgs.append(pkg)
        return success

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

        :param pCompliance: the self.iscompliant value of rule
        :param pRuleSuccess: did report run successfully
        :returns: success
        :rtype: bool
@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 pRuleSuccess: did report run successfully
        :returns: success
        :rtype: bool
@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 pRuleSuccess: did report run successfully
        :returns: success
        :rtype: bool
@author: ekkehard j. koch

        '''

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

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

    def runTest(self):
        self.simpleRuleTest()

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

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

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

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


        :returns: boolean

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

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


        :returns: boolean

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

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

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

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

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

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

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

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

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

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

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

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

        '''
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \
                             str(pRuleSuccess) + ".")
        success = True
        return success
Exemplo n.º 15
0
class zzzTestRuleRemoveSoftware(RuleTest):

    def setUp(self):
        RuleTest.setUp(self)
        self.rule = RemoveSoftware(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.checkUndo = True

    def tearDown(self):
        for pkg in self.installed:
            self.ph.install(pkg)

    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: dwalker
        '''
        success = True
        self.rule.ci.updatecurrvalue(True)
        self.installed = []
        default = ["squid",
                   "telnet-server",
                   "rsh-server",
                   "rsh",
                   "rsh-client",
                   "talk",
                   "talk-server",
                   "talkd",
                   "tftp-server",
                   "tftp",
                   "tftpd"]
        for pkg in default:
            if not self.ph.check(pkg) and self.ph.checkAvailable(pkg):
                self.ph.install(pkg)
            elif self.ph.check(pkg) and self.ph.checkAvailable(pkg):
                self.installed.append(pkg)
        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: dwalker
        '''
        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: dwalker
        '''
        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: dwalker
        '''
        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " +
                             str(pRuleSuccess) + ".")
        success = True
        return success
class zzzTestRuleDisableUbuntuDataCollection(RuleTest):

    def setUp(self):
        '''

        @return: None
        @author: ekkehard j. koch, Breen Malmberg
        '''

        RuleTest.setUp(self)
        self.rule = DisableUbuntuDataCollection(self.config, self.environ, self.logdispatch, self.statechglogger)
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.ph = Pkghelper(self.logdispatch, self.environ)
        self.datacollectionpkgs = ["popularity-contest", "apport", "ubuntu-report"]
        self.teardownpkgs = []

    def tearDown(self):
        '''

        @return: None
        '''

        for pkg in self.teardownpkgs:
            self.ph.remove(pkg)
            self.teardownpkgs.remove(pkg)

    def runTest(self):
        '''

        @return: None
        '''

        self.simpleRuleTest()

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

        @return: success
        @rtype: bool
        @author: ekkehard j. koch, Breen Malmberg
        '''

        success = True
        self.rule.enabledCI.updatecurrvalue(True)

        for pkg in self.datacollectionpkgs:
            if not self.ph.check(pkg):
                self.ph.install(pkg)
                self.teardownpkgs.append(pkg)
        return success

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

        @param pCompliance: the self.iscompliant value of rule
        @param pRuleSuccess: did report run successfully
        @return: success
        @rtype: bool
        @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 pRuleSuccess: did report run successfully
        @return: success
        @rtype: bool
        @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 pRuleSuccess: did report run successfully
        @return: success
        @rtype: bool
        @author: ekkehard j. koch
        '''

        self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".")
        success = True
        return success
Exemplo n.º 17
0
class zzzTestRuleSystemAccounting(RuleTest):
    def setUp(self):
        RuleTest.setUp(self)
        self.rule = SystemAccounting(self.config, self.environ,
                                     self.logdispatch, self.statechglogger)
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.ch = CommandHelper(self.logdispatch)
        self.ph = Pkghelper(self.logdispatch, self.environ)
        self.rule.ci.updatecurrvalue(True)

    def tearDown(self):
        pass

    def runTest(self):
        result = self.simpleRuleTest()
        self.assertTrue(
            result, "SystemAccounting(9): rule.iscompliant() is " +
            "'False' after rule.fix() and rule.report() have " +
            "run. This may be due to a proxy error; if the " +
            "proper proxy is not set in localize.py, set it and " +
            "run this test again.")

    def test_default_sysstat_empty(self):
        """
        test correction of /etc/default/sysstat if it has no entry in it

        :return:
        """

        file = "/etc/default/sysstat"
        backup = "/etc/default/sysstat.stonix_test_bak"

        if os.path.isfile(file):
            self._backup_file(file)
            f = open(file, "w")
            f.write("")
            f.close()

            self.rule._set_paths()
            self.assertFalse(self.rule._report_configuration())
            self.rule._fix_configuration()
            self.assertTrue(self.rule._report_configuration())

            self._restore_file(backup)
        else:
            return True

    def test_default_sysstat_comment(self):
        """
        test correction of /etc/default/sysstat if it has the entry commented out

        :return:
        """

        file = "/etc/default/sysstat"
        backup = "/etc/default/sysstat.stonix_test_bak"

        if os.path.isfile(file):
            self._backup_file(file)
            f = open(file, "w")
            f.write('# ENABLED="true"')
            f.close()

            self.rule._set_paths()
            self.assertFalse(self.rule._report_configuration())
            self.rule._fix_configuration()
            self.assertTrue(self.rule._report_configuration())

            self._restore_file(backup)
        else:
            return True

    def test_default_sysstat_wrongvalue(self):
        """
        test correction of /etc/default/sysstat if it has the entry set to the wrong value

        :return:
        """

        file = "/etc/default/sysstat"
        backup = "/etc/default/sysstat.stonix_test_bak"

        if os.path.isfile(file):
            self._backup_file(file)
            f = open(file, "w")
            f.write('ENABLED="false"')
            f.close()

            self.rule._set_paths()
            self.assertFalse(self.rule._report_configuration())
            self.rule._fix_configuration()
            self.assertTrue(self.rule._report_configuration())

            self._restore_file(backup)
        else:
            return True

    def test_default_sysstat_rightvalue(self):
        """
        test correction of /etc/default/sysstat if it has the entry set to the right value

        :return:
        """

        file = "/etc/default/sysstat"
        backup = "/etc/default/sysstat.stonix_test_bak"

        if os.path.isfile(file):
            self._backup_file(file)
            f = open(file, "w")
            f.write('ENABLED="true"')
            f.close()

            self.rule._set_paths()
            self.assertTrue(self.rule._report_configuration())
            self.rule._fix_configuration()
            self.assertTrue(self.rule._report_configuration())

            self._restore_file(backup)
        else:
            return True

    def test_installation_installed(self):
        """
        test installation report/fix if package already installed
        applies to Linux only

        :return:
        """

        if self.rule.ostype == "Mac OS X":
            return True

        package = "sysstat"

        if self.ph.check(package):
            self.rule._set_paths()
            self.assertTrue(self.rule._report_installation())
            self.rule._fix_installation()
            self.assertTrue(self.rule._report_installation())
        else:
            return True

    def test_installation_missing(self):
        """
        test installation report/fix if package not installed
        applies to Linux only

        :return:
        """

        if self.rule.ostype == "Mac OS X":
            return True

        package = "sysstat"

        if not self.ph.check(package):
            self.rule._set_paths()
            self.assertFalse(self.rule._report_installation())
            self.rule._fix_installation()
            self.assertTrue(self.rule._report_installation())
        else:
            return True

    def test_set_paths(self):
        """
        test that all paths and necessary variables for the class are able to be properly
        determined and set once package is installed

        :return:
        """

        package = "sysstat"

        self.ph.install(package)

        self.rule._set_paths()

        self.assertTrue(self.rule.sysstat_package)
        self.assertTrue(self.rule.sysstat_service_file)
        self.assertTrue(self.rule.sa1)
        self.assertTrue(self.rule.sa2)
        self.assertTrue(self.rule.sysstat_service_contents)
        self.assertTrue(self.rule.sysstat_cron_contents)
        self.assertTrue(self.rule.ostype)

        self.ph.remove(package)

    def _restore_file(self, backup):
        """

        :param backup:
        :return:
        """

        if os.path.isfile(backup):
            if re.search("\.stonix_test_bak", backup):
                shutil.copy2(backup, backup.replace(".stonix_test_bak", ""))

    def _backup_file(self, original):
        """

        :param original:
        :return:
        """

        if os.path.isfile(original):
            shutil.copy2(original, original + ".stonix_test_bak")

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

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

        """

        success = True
        self.rule.ci.updatecurrvalue(True)
        return success

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

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

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

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

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

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

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

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

        """
        self.logdispatch.log(LogPriority.DEBUG,
                             "pRuleSuccess = " + str(pRuleSuccess) + ".")
        success = True
        return success
Exemplo n.º 18
0
    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
class zzzTestRuleDisablePrelinking(RuleTest):

    def setUp(self):
        RuleTest.setUp(self)
        self.rule = DisablePrelinking(self.config,
                                      self.environ,
                                      self.logdispatch,
                                      self.statechglogger)
        self.rulename = self.rule.rulename
        self.rulenumber = self.rule.rulenumber
        self.ch = CommandHelper(self.logdispatch)
        self.ph = Pkghelper(self.logdispatch, self.environ)
        self.prelinkInstalled = False

    def tearDown(self):
        if not self.prelinkInstalled:
            self.ph.remove("prelink")

    def runTest(self):
        self.simpleRuleTest()

    def setConditionsForRule(self):
        '''
        Configure system for the unit test
        @param self: essential if you override this definition
        @return: boolean - If successful True; If failure False
        @author: ekkehard j. koch
        '''
        success = True
        if self.ph.check("prelink"):
            self.prelinkInstalled = True
        elif self.ph.checkAvailable("prelink"):
            self.ph.install("prelink")
        else:
            return True
        path = "/usr/sbin/prelink"
        cmd = [path, "/bin/ls"]
        if os.path.exists(path):
            self.ch.executeCommand(cmd)

        if re.search("debian|ubuntu", self.environ.getostype().lower()):
            path = "/etc/default/prelink"
        else:
            path = "/etc/sysconfig/prelink"
        if os.path.exists(path):
            tmppath = path + ".tmp"
            data = {"PRELINKING": "yes"}
            self.editor = KVEditorStonix(self.statechglogger, self.logdispatch,
                                         "conf", path, tmppath,
                                         data, "present", "closedeq")
            if not self.editor.report():
                if self.editor.fix():
                    if not self.editor.commit():
                        success = False
                        self.logdispatch.log(LogPriority.ERROR,
                                             "KVEditor failed to commit.")
                else:
                    success = False
                    self.logdispatch.log(LogPriority.ERROR,
                                         "KVEditor failed to fix.")
        else:
            writeFile(path, "PRELINKING=yes", self.logdispatch)

        return success

    def checkReportForRule(self, pCompliance, pRuleSuccess):
        '''
        check on whether report was correct
        @param self: essential if you override this definition
        @param pCompliance: the self.iscompliant value of rule
        @param pRuleSuccess: did report run successfully
        @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