예제 #1
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() == "solaris":
            path = "/etc/ssh/sshd_config"
            if os.path.exists(path):
                contents = readFile(path, self.logdispatch)
                string = ""
                for line in contents:
                    if re.match("^permitrootlogin", line.strip()):
                        continue
                    else:
                        string += line
                writeFile(path, string, self.logdispatch)
                os.chmod(path, 511)
        else:
            path = "/etc/securetty"
            if os.path.exists("/etc/securetty"):
                string = "this is purposely bad data for testing\n"
                writeFile(path, string, self.logdispatch)
                os.chmod(path, 511)
        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
        groupname = "%wheel"

        if self.environ.getostype() == "Mac OS X":
            self.path = "/private/etc/sudoers"
            groupname = "%admin"
        elif self.environ.getosfamily() == "linux":
            self.path = "/etc/sudoers"
        elif self.environ.getosfamily() == "freebsd":
            self.path = "/usr/local/etc/sudoers"

        contents = readFile(self.path, self.logdispatch)
        tempstring = ""

        for line in contents:
            if re.search("^" + groupname, line):
                continue
            else:
                tempstring += line

        writeFile(self.path + ".tmp", tempstring, self.logdispatch)
        os.rename(self.path + ".tmp", self.path)

        if checkPerms(self.path, [0, 0, 288], self.logdispatch):
            os.chmod(self.path, 256)

        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

        self.rule.ci1.updatecurrvalue(True)
        self.rule.ci2.updatecurrvalue("*****@*****.**")

        aliasfile = "/etc/aliases"
        if os.path.exists(aliasfile):
            contents = readFile(aliasfile, self.logdispatch)
            tempstring = ""
            for line in contents:
                if re.search("^root:", line):
                    continue
                else:
                    tempstring += line

            tmpfile = "/etc/aliases.tmp"
            writeFile(tmpfile, tempstring, self.logdispatch)
            os.rename(tmpfile, aliasfile)
            # set incorrect permissions
            os.chown(aliasfile, 8, 8)
            os.chmod(aliasfile, 0500)
        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() == "solaris":
         path = "/etc/ssh/sshd_config"
         if os.path.exists(path):
             contents = readFile(path, self.logdispatch)
             string = ""
             for line in contents:
                 if re.match("^permitrootlogin", line.strip()):
                     continue
                 else:
                     string += line
             writeFile(path, string, self.logdispatch)
             os.chmod(path, 511)
     else:
         path = "/etc/securetty"
         if os.path.exists("/etc/securetty"):
             string = "this is purposely bad data for testing\n"
             writeFile(path, string, self.logdispatch)
             os.chmod(path, 511)
     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

        self.rule.ci1.updatecurrvalue(True)
        self.rule.ci2.updatecurrvalue("*****@*****.**")

        aliasfile = "/etc/aliases"
        if os.path.exists(aliasfile):
            contents = readFile(aliasfile, self.logdispatch)
            tempstring = ""
            for line in contents:
                if re.search("^root:", line):
                    continue
                else:
                    tempstring += line

            tmpfile = "/etc/aliases.tmp"
            writeFile(tmpfile, tempstring, self.logdispatch)
            os.rename(tmpfile, aliasfile)
            # set incorrect permissions
            os.chown(aliasfile, 8, 8)
            os.chmod(aliasfile, 0500)
        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
        groupname = "%wheel"

        if self.environ.getostype() == "Mac OS X":
            self.path = "/private/etc/sudoers"
            groupname = "%admin"
        elif self.environ.getosfamily() == "linux":
            self.path = "/etc/sudoers"
        elif self.environ.getosfamily() == "freebsd":
            self.path = "/usr/local/etc/sudoers"

        contents = readFile(self.path, self.logdispatch)
        tempstring = ""

        for line in contents:
            if re.search("^" + groupname, line):
                continue
            else:
                tempstring += line

        writeFile(self.path + ".tmp", tempstring, self.logdispatch)
        os.rename(self.path + ".tmp", self.path)

        if checkPerms(self.path, [0, 0, 288], self.logdispatch):
            os.chmod(self.path, 256)

        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: dwalker
        '''
        success = True
        if self.ph.check("squid"):
            if self.ph.manager == "apt-get":
                self.squidfile = "/etc/squid3/squid.conf"
            else:
                self.squidfile = "/etc/squid/squid.conf"
            self.backup = self.squidfile + ".original"
            self.data1 = {"ftp_passive": "on",
                          "ftp_sanitycheck": "on",
                          "check_hostnames": "on",
                          "request_header_max_size": "20 KB",
                          "reply_header_max_size": "20 KB",
                          "cache_effective_user": "******",
                          "cache_effective_group": "squid",
                          "ignore_unknown_nameservers": "on",
                          "allow_underscore": "off",
                          "httpd_suppress_version_string": "on",
                          "forwarded_for": "off",
                          "log_mime_hdrs": "on",
                          "http_access": "deny to_localhost"}

            #make sure these aren't in the file
            self.denied = ["acl Safe_ports port 70",
                           "acl Safe_ports port 210",
                           "acl Safe_ports port 280",
                           "acl Safe_ports port 488",
                           "acl Safe_ports port 591",
                           "acl Safe_ports port 777"]
            if os.path.exists(self.squidfile):
                if checkPerms(self.squidfile, [0, 0, 420], self.logdispatch):
                    if not setPerms(self.squidfile, [0, 0, 416], self.logdispatch):
                        success = False
                copyfile(self.squidfile, self.backup)
                tempstring = ""
                contents = readFile(self.squidfile, self.logdispatch)
                if contents:
                    for line in contents:
                        if re.search("^ftp_passive", line.strip()):
                            '''Delete this line'''
                            continue
                        else:
                            tempstring += line
                '''insert line with incorrect value'''
                tempstring += "request_header_max_size 64 KB\n"
                '''insert line with no value'''
                tempstring += "ignore_unknown_nameservers\n"
                '''insert these two lines we don't want in there'''
                tempstring += "acl Safe_ports port 70\nacl Safe_ports port 210\n"
                if not writeFile(self.squidfile, tempstring, self.logdispatch):
                    success = False
        return success
예제 #8
0
    def setLinuxConditions(self):
        success = True
        path1 = "/etc/security/limits.conf"
        if os.path.exists(path1):
            lookfor1 = "(^\*)\s+hard\s+core\s+0?"
            contents = readFile(path1, self.logger)
            if contents:
                tempstring = ""
                for line in contents:
                    if not re.search(lookfor1, line.strip()):
                        tempstring += line
                if not writeFile(path1, tempstring, self.logger):
                    debug = "unable to write incorrect contents to " + path1 + "\n"
                    self.logger.log(LogPriority.DEBUG, debug)
                    success = False
            if checkPerms(path1, [0, 0, 0o644], self.logger):
                if not setPerms(path1, [0, 0, 0o777], self.logger):
                    debug = "Unable to set incorrect permissions on " + path1 + "\n"
                    self.logger.log(LogPriority.DEBUG, debug)
                    success = False
                else:
                    debug = "successfully set incorrect permissions on " + path1 + "\n"
                    self.logger.log(LogPriority.DEBUG, debug)

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

        if retcode != 0:
            self.detailedresults += "Failed to get value of core dumps configuration with sysctl command\n"
            errmsg = self.ch.getErrorString()
            self.logger.log(LogPriority.DEBUG, errmsg)
            success = False
        else:
            output = self.ch.getOutputString()
            if output.strip() != "fs.suid_dumpable = 1":
                if not self.ch.executeCommand("/sbin/sysctl -w fs.suid_dumpable=1"):
                    debug = "Unable to set incorrect value for fs.suid_dumpable"
                    self.logger.log(LogPriority.DEBUG, debug)
                    success = False
                elif not self.ch.executeCommand("/sbin/sysctl -p"):
                    debug = "Unable to set incorrect value for fs.suid_dumpable"
                    self.logger.log(LogPriority.DEBUG, debug)
                    success = False
        
        return success
예제 #9
0
 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
예제 #10
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
     path = "/etc/default/keyserv"
     if os.path.exists(path):
         contents = readFile(path, self.logdispatch)
         tempstring = ""
         for line in contents:
             if re.match("^ENABLE_NOBODY_KEYS", line.strip()):
                 continue
             else:
                 tempstring += line
         tempstring += "ENABLE_NOBODY_KEYS=YES"
         writeFile(path, tempstring, self.logdispatch)
     return success
예제 #11
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: Eric Ball
     '''
     success = True
     # This is tested as working on both platforms
     sudoers = "/etc/sudoers"
     self.rule.ci.updatecurrvalue(True)
     self.rule.iditerator = 0
     myid = iterate(self.rule.iditerator, self.rule.rulenumber)
     setPerms(sudoers, [99, 99, 0770], self.logdispatch,
              self.statechglogger, myid)
     contents = readFile(sudoers, self.logdispatch)
     for line in contents:
         if re.search("^Defaults\s+timestamp_timeout", line.strip()):
             contents.remove(line)
             break
     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
     # This is tested as working on both platforms
     sudoers = "/etc/sudoers"
     self.rule.ci.updatecurrvalue(True)
     self.rule.iditerator = 0
     myid = iterate(self.rule.iditerator, self.rule.rulenumber)
     setPerms(sudoers, [99, 99, 0770], self.logdispatch,
              self.statechglogger, myid)
     contents = readFile(sudoers, self.logdispatch)
     for line in contents:
         if re.search("^Defaults\s+timestamp_timeout", line.strip()):
             contents.remove(line)
             break
     return success
예제 #13
0
 def messupNetconfigFile(self):
     success = True
     # stig portion, check netconfig file for correct contents
     if self.ph.manager == "apt-get":
         nfspkg = "nfs-common"
     else:
         nfspkg = "nfs-utils.x86_64"
     if self.ph.check(nfspkg):
         if not self.ph.remove(nfspkg):
             success = False
             debug = "Unable to remove nfs package for preconditions"
             self.logger.log(LogPriority.DEBUG, debug)
     if os.path.exists("/etc/netconfig"):
         item1 = "udp6 tpi_clts v inet6 udp - -"
         item2 = "tcp6 tpi_cots_ord v inet6 tcp - -"
         item1found, item2found, fixFile = False, False, False
         writestring = ""
         contents = readFile("/etc/netconfig", self.logger)
         for line in contents:
             writestring += line
             line = re.sub("\s+", " ", line.strip())
             if re.search(item1, line):
                 item1found = True
             if re.search(item2, line):
                 item2found = True
         if not item1found:
             writestring += item1
             fixFile = True
         if not item2found:
             writestring += item2
             fixFile = True
         if fixFile:
             if not writeFile("/etc/netconfig", writestring, self.logger):
                 success = False
                 debug = "Unable tomess up /etc/netconfig file for preconditions"
                 self.logger.log(LogPriority.DEBUG, debug)
     return success
예제 #14
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: Derek Walker

        """

        success = True
        if self.ph.manager == "apt-get":
            self.tftpfile = "/etc/default/tftpd-hpa"
            tmpfile = self.tftpfile + ".tmp"
            if os.path.exists(self.tftpfile):
                contents = readFile(self.tftpfile, self.logger)
                tempstring = ""
                for line in contents:
                    """Take TFTP_OPTIONS line out of file"""
                    if re.search("TFTP_OPTIONS", line.strip()):
                        continue
                    elif re.search("TFTP_DIRECTORY", line.strip()):
                        tempstring += 'TFTP_DIRECTORY="/var/lib/tftpbad"'
                        continue
                    else:
                        tempstring += line
                if not writeFile(tmpfile, tempstring, self.logger):
                    success = False
                else:
                    os.rename(tmpfile, self.tftpfile)
                    os.chown(self.tftpfile, 0, 0)
                    os.chmod(self.tftpfile, 400)
        else:
            #if server_args line found, remove to make non-compliant
            self.tftpfile = "/etc/xinetd.d/tftp"
            tftpoptions, contents2 = [], []
            if os.path.exists(self.tftpfile):
                i = 0
                contents = readFile(self.tftpfile, self.logger)
                if checkPerms(self.tftpfile, [0, 0, 420], self.logger):
                    setPerms(self.tftpfile, [0, 0, 400], self.logger)
                try:
                    for line in contents:
                        if re.search("service tftp", line.strip()):
                            contents2 = contents[i + 1:]
                        else:
                            i += 1
                except IndexError:
                    pass
                if contents2:
                    if contents2[0].strip() == "{":
                        del (contents2[0])
                    if contents2:
                        i = 0
                        while i <= len(contents2) and contents2[i].strip(
                        ) != "}" and contents2[i].strip() != "{":
                            tftpoptions.append(contents2[i])
                            i += 1
                        if tftpoptions:
                            for line in tftpoptions:
                                if re.search("server_args", line):
                                    contents.remove(line)
        return success
예제 #15
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
    def setkde(self):
        '''Method to setup kde desktop to not be compliant
        @author: dwalker
        @return: bool
        '''
        self.kdeprops = {"ScreenSaver": {"Enabled": "true",
                                             "Lock": "true",
                                             "LockGrace": "60000",
                                             "Timeout": "840"}}
        self.kderuin = []
        debug = "Inside setkde method"
        success = True
        bindir = glob("/usr/bin/kde*")
        kdefound = False
        for kdefile in bindir:
            if re.search("^/usr/bin/kde\d$", str(kdefile)):
                kdefound = True
        if kdefound and self.environ.geteuid() == 0:
            contents = readFile("/etc/passwd", self.logger)
            if not contents:
                debug += "You have some serious issues, /etc/passwd is blank\n"
                self.logger.log(LogPriority.ERROR, debug)
                return False
            for line in contents:
                temp = line.split(":")
                try:
                    if int(temp[2]) >= 500:
                        if temp[5] and re.search('/', temp[5]):
                            homebase = temp[5]
                            if not re.search("^/home/", homebase):
                                continue
                            kfile = homebase + "/.kde/share/config/kscreensaverrc"
                            if os.path.exists(kfile):
                                uid = getpwnam(temp[0])[2]
                                gid = getpwnam(temp[0])[3]
                                if checkPerms(kfile, [uid, gid, 0o600],
                                                  self.logger):
                                    if not setPerms(kfile, [0, 0, 0o644],
                                                    self.logger):
                                        success = False
                                        debug += "Unable to set incorrect perms " + \
                                            "on " + kfile + " for testing\n"
                                if not self.wreckFile(kfile):
                                    debug += "Was not able to mess " + \
                                        "up file for testing\n"
                                    success = False
                        else:
                            debug += "placeholder 6 in /etc/passwd is not a \
directory, invalid form of /etc/passwd"
                            self.logger.log(LogPriority.ERROR, debug)
                            return False
                except IndexError:
                    success = False
                    debug += traceback.format_exc() + "\n"
                    debug += "Index out of range\n"
                    self.logger.log(LogPriority.ERROR, debug)
                    break
                except Exception:
                    break
        elif kdefound:
            who = "/usr/bin/whoami"
            message = Popen(who, stdout=PIPE, shell=False)
            info = message.stdout.read().strip()
            contents = readFile('/etc/passwd', self.logger)
            if not contents:
                debug += "You have some serious issues, /etc/passwd is blank\n"
                self.logger.log(LogPriority.ERROR, debug)
                return False
            compliant = True
            for line in contents:
                temp = line.split(':')
                try:
                    if temp[0] == info:
                        if temp[5] and re.search('/', temp[5]):
                            homebase = temp[5]
                            if not re.search("^/home/", homebase):
                                continue
                            kfile = homebase + "/.kde/share/config/kscreensaverrc"
                            if os.path.exists(kfile):
                                uid = getpwnam(temp[0])[2]
                                gid = getpwnam(temp[0])[3]
                                if checkPerms(kfile, [uid, gid, 0o600],
                                                  self.logger):
                                    if not setPerms(kfile, [0, 0, 0o644],
                                                    self.logger):
                                        success = False
                                        debug += "Unable to set incorrect perms " + \
                                            "on " + kfile + " for testing\n"
                                if not self.wreckFile(kfile):
                                    debug += "Was not able to mess " + \
                                        "up file for testing\n"
                                    success = False
                        else:
                            debug += "placeholder 6 in /etc/passwd is not a \
directory, invalid form of /etc/passwd"
                            self.logger.log(LogPriority.ERROR, debug)
                            return False
                        break
                except IndexError:
                    success = False
                    debug += traceback.format_exc() + "\n"
                    debug += "Index out of range\n"
                    self.logger.log(LogPriority.ERROR, debug)
                    self.detailedresults += "Unexpected formatting in " + \
                        "/etc/passwd"
                    break
                except Exception:
                    debug += traceback.format_exc() + "\n"
                    self.logger.log(LogPriority.ERROR, debug)
                    break
        return success
    def 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 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
     if not self.environ.getostype() == "Mac OS X":
         self.ph = Pkghelper(self.logger, self.environ)
         if self.ph.manager == "apt-get":
             self.tftpfile = "/etc/default/tftpd-hpa"
             tmpfile = self.tftpfile + ".tmp"
             if os.path.exists(self.tftpfile):
                 contents = readFile(self.tftpfile, self.logger)
                 tempstring = ""
                 for line in contents:
                     '''Take TFTP_OPTIONS line out of file'''
                     if re.search("TFTP_OPTIONS", line.strip()):
                         continue
                     elif re.search("TFTP_DIRECTORY", line.strip()):
                         tempstring += 'TFTP_DIRECTORY="/var/lib/tftpbad"'
                         continue
                     else:
                         tempstring += line
                 if not writeFile(tmpfile, tempstring, self.logger):
                     success = False
                 else:
                     os.rename(tmpfile, self.tftpfile)
                     os.chown(self.tftpfile, 0, 0)
                     os.chmod(self.tftpfile, 400)
         else:
             #if server_args line found, remove to make non-compliant
             self.tftpfile = "/etc/xinetd.d/tftp"
             tftpoptions, contents2 = [], []
             if os.path.exists(self.tftpfile):
                 i = 0
                 contents = readFile(self.tftpfile, self.logger)
                 if checkPerms(self.tftpfile, [0, 0, 420], self.logger):
                     setPerms(self.tftpfile, [0, 0, 400], self.logger)  
                 try:
                     for line in contents:
                         if re.search("service tftp", line.strip()):
                             contents2 = contents[i+1:]
                         else:
                             i += 1
                 except IndexError:
                     pass
                 if contents2:
                     if contents2[0].strip() == "{":
                         del(contents2[0])
                     if contents2:
                         i = 0
                         while i <= len(contents2) and contents2[i].strip() != "}" and contents2[i].strip() != "{":
                             tftpoptions.append(contents2[i])
                             i += 1
                         if tftpoptions:
                             for line in tftpoptions:
                                 if re.search("server_args", line):
                                     contents.remove(line)
     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 setgnome(self):
     '''Method to setup gnome desktop to not be compliant
     @author: dwalker
     @return: bool
     '''
     success = True
     debug = "Inside setgnome method\n"
     gconf = "/usr/bin/gconftool-2"
     gsettings = "/usr/bin/gsettings"
     dconfsettingslock = "/etc/dconf/db/local.d/locks/stonix-settings.conf"
     dconflockdata = ["/org/gnome/desktop/session/idle-delay",
                        "/org/gnome/desktop/session/idle-activation-enabled",
                        "/org/gnome/desktop/screensaver/lock-enabled",
                        "/org/gnome/desktop/screensaver/lock-delay",
                        "/org/gnome/desktop/screensaver/picture-uri"]
     dconfsettings = "/etc/dconf/db/local.d/local.key"
     dconfdata = {"org/gnome/desktop/screensaver": {
                                                 "idle-activation-enabled": "true",
                                                 "lock-enabled": "true",
                                                 "lock-delay": "0",
                                                 "picture-opacity": "100",
                                                 "picture-uri": "\'\'"},
                                   "org/gnome/desktop/session": {
                                                 "idle-delay": "uint32 900"}}
     dconfuserprofile = "/etc/dconf/profile/user"
     userprofilecontent = "user-db:user\n" + \
                                       "system-db:local"
     if os.path.exists(gconf):
         setcmds1 = ["/apps/gnome-screensaver/idle_activation_enabled false",
                    "/apps/gnome-screensaver/lock_enabled false"]
         setcmds2 = "/desktop/gnome/session/idle_delay 5"
         for cmd in setcmds1:
             cmd2 = gconf + " --type bool --set " + cmd
             if not self.ch.executeCommand(cmd2):
                 success = False
                 debug += "Issues setting " + cmd2 + "\n"
         cmd2 = gconf + " --type int --set " + setcmds2
         if not self.ch.executeCommand(cmd2):
             success = False
             debug += "Issues setting " + cmd2 + "\n"
     if os.path.exists(gsettings):
         setcmds = [" set org.gnome.desktop.screensaver " +
                    "idle-activation-enabled false",
                    " set org.gnome.desktop.screensaver lock-enabled false",
                    " set org.gnome.desktop.screensaver lock-delay 10",
                    " set org.gnome.desktop.screensaver picture-opacity 50",
                    " set org.gnome.desktop.session idle-delay 20"]
         for cmd in setcmds:
             cmd2 = gsettings + cmd
             if not self.ch.executeCommand(cmd2):
                 success = False
                 debug += "Issues setting " + cmd2 + "\n"
     if self.environ.geteuid() == 0:
         #write correct contents to dconf lock file
         if os.path.exists(dconfsettingslock):
             tempstring = ""
             tmpfile = dconfsettingslock + ".tmp"
             contents = readFile(dconfsettingslock, self.logger)
             for line in contents:
                 if line.strip() in dconflockdata:
                     continue
                 else:
                     tempstring += line
             if not writeFile(tmpfile, tempstring, self.logger):
                 success = False
                 debug += "Unable to write contents to " + \
                     "stonix-settings file\n"
             else:
                 os.rename(tmpfile, dconfsettingslock)
                 os.chown(dconfsettingslock, 0, 0)
                 os.chmod(dconfsettingslock, 493)
                 resetsecon(dconfsettingslock)
         #write correct contents to dconf lock file
         if os.path.exists(dconfsettings):
             self.kveditor = KVEditorStonix(self.statechglogger,
                                            self.logger,
                                            "tagconf",
                                            dconfsettings,
                                            dconfsettings + ".tmp",
                                            dconfdata, "notpresent",
                                            "closedeq")
             if not self.kveditor.report():
                 success = False
                 debug += "Unable to set incorrect contents " + \
                     "for " + dconfsettings + "\n"
             elif not self.kveditor.fix():
                 success = False
                 debug += "Unable to set incorrect contents " + \
                     "for " + dconfsettings + "\n"
             elif not self.kveditor.commit():
                 success = False
                 debug += "Unable to set incorrect contents " + \
                     "for " + dconfsettings + "\n"
         
         if os.path.exists(dconfuserprofile):
             fixing = False
             contents = readFile(dconfuserprofile, self.logger)
             contentstring = ""
             for line in contents:
                 contentstring += line
                 if re.search(userprofilecontent, contentstring):
                    fixing = True
             if fixing:
                 contentstring = ""
                 tempfile = dconfuserprofile + ".tmp"
                 if not writeFile(tempfile, contentstring, self.logger):
                     success = False
                     debug += "Unable to set incorrect contents " + \
                     "for " + dconfuserprofile + "\n"
                 else:
                     os.rename(tempfile, dconfuserprofile)
                     os.chown(dconfuserprofile, 0, 0)
                     os.chmod(dconfuserprofile, 493)
                     resetsecon(dconfuserprofile)
     self.logger.log(LogPriority.ERROR, debug)
     return success
예제 #21
0
    def setLinuxConditions(self):
        success = True
        debug = ""
        path1 = "/etc/security/limits.conf"
        if os.path.exists(path1):
            lookfor1 = "(^\*)\s+hard\s+core\s+0?"
            contents = readFile(path1, self.logger)
            if contents:
                tempstring = ""
                for line in contents:
                    if not re.search(lookfor1, line.strip()):
                        tempstring += line
                if not writeFile(path1, tempstring, self.logger):
                    debug = "unable to write incorrect contents to " + path1
                    self.logger.log(LogPriority.DEBUG, debug)
                    success = False
            if not checkPerms(path1, [0, 0, 0o777], self.logger):
                if not setPerms(path1, [0, 0, 0o777], self.logger):
                    debug = "Unable to set incorrect permissions on " + path1
                    self.logger.log(LogPriority.DEBUG, debug)
                    success = False
                else:
                    debug = "successfully set incorrect permissions on " + path1
                    self.logger.log(LogPriority.DEBUG, debug)

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

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

        return success
예제 #22
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
예제 #23
0
    def setkde(self):
        '''Method to setup kde desktop to not be compliant
        @author: dwalker


        :returns: bool

        '''
        self.kdeprops = {"ScreenSaver": {"Enabled": "true",
                                             "Lock": "true",
                                             "LockGrace": "60000",
                                             "Timeout": "840"}}
        self.kderuin = []
        debug = "Inside setkde method"
        success = True
        bindir = glob("/usr/bin/kde*")
        kdefound = False
        for kdefile in bindir:
            if re.search("^/usr/bin/kde\d$", str(kdefile)):
                kdefound = True
        if kdefound and self.environ.geteuid() == 0:
            contents = readFile("/etc/passwd", self.logger)
            if not contents:
                debug += "You have some serious issues, /etc/passwd is blank\n"
                self.logger.log(LogPriority.ERROR, debug)
                return False
            for line in contents:
                temp = line.split(":")
                try:
                    if int(temp[2]) >= 500:
                        if temp[5] and re.search('/', temp[5]):
                            homebase = temp[5]
                            if not re.search("^/home/", homebase):
                                continue
                            kfile = homebase + "/.kde/share/config/kscreensaverrc"
                            if os.path.exists(kfile):
                                uid = getpwnam(temp[0])[2]
                                gid = getpwnam(temp[0])[3]
                                if checkPerms(kfile, [uid, gid, 0o600],
                                                  self.logger):
                                    if not setPerms(kfile, [0, 0, 0o644],
                                                    self.logger):
                                        success = False
                                        debug += "Unable to set incorrect perms " + \
                                            "on " + kfile + " for testing\n"
                                if not self.wreckFile(kfile):
                                    debug += "Was not able to mess " + \
                                        "up file for testing\n"
                                    success = False
                        else:
                            debug += "placeholder 6 in /etc/passwd is not a \
directory, invalid form of /etc/passwd"
                            self.logger.log(LogPriority.ERROR, debug)
                            return False
                except IndexError:
                    success = False
                    debug += traceback.format_exc() + "\n"
                    debug += "Index out of range\n"
                    self.logger.log(LogPriority.ERROR, debug)
                    break
                except Exception:
                    break
        elif kdefound:
            who = "/usr/bin/whoami"
            message = Popen(who, stdout=PIPE, shell=False)
            info = message.stdout.read().strip()
            contents = readFile('/etc/passwd', self.logger)
            if not contents:
                debug += "You have some serious issues, /etc/passwd is blank\n"
                self.logger.log(LogPriority.ERROR, debug)
                return False
            compliant = True
            for line in contents:
                temp = line.split(':')
                try:
                    if temp[0] == info:
                        if temp[5] and re.search('/', temp[5]):
                            homebase = temp[5]
                            if not re.search("^/home/", homebase):
                                continue
                            kfile = homebase + "/.kde/share/config/kscreensaverrc"
                            if os.path.exists(kfile):
                                uid = getpwnam(temp[0])[2]
                                gid = getpwnam(temp[0])[3]
                                if checkPerms(kfile, [uid, gid, 0o600],
                                                  self.logger):
                                    if not setPerms(kfile, [0, 0, 0o644],
                                                    self.logger):
                                        success = False
                                        debug += "Unable to set incorrect perms " + \
                                            "on " + kfile + " for testing\n"
                                if not self.wreckFile(kfile):
                                    debug += "Was not able to mess " + \
                                        "up file for testing\n"
                                    success = False
                        else:
                            debug += "placeholder 6 in /etc/passwd is not a \
directory, invalid form of /etc/passwd"
                            self.logger.log(LogPriority.ERROR, debug)
                            return False
                        break
                except IndexError:
                    success = False
                    debug += traceback.format_exc() + "\n"
                    debug += "Index out of range\n"
                    self.logger.log(LogPriority.ERROR, debug)
                    self.detailedresults += "Unexpected formatting in " + \
                        "/etc/passwd"
                    break
                except Exception:
                    debug += traceback.format_exc() + "\n"
                    self.logger.log(LogPriority.ERROR, debug)
                    break
        return success