Example #1
0
    def updated(self):
        '''This method checks to see if the system is fully patched or if there
        are updates that need to be done. Returns True if the system
        is patched or the check doesn't apply. If there are updates that need
        to be applied then it returns False.


        :returns: updated

        :rtype: bool
@author: dkennel
@change: Breen Malmberg - 4/26/2017 - added method call checkUpdate()
        added code to use package helper instead of dynamically looking
        up the package manager and command to use

        '''

        updated = False
        osEnvBkup = os.environ
        if PROXY is not None:
            os.environ["http_proxy"] = PROXY
            os.environ["https_proxy"] = PROXY
        self.ph = Pkghelper(self.logger, self.environ)

        try:

            if not self.ph.checkUpdate():
                updated = True

        except Exception:
            raise
        os.environ = osEnvBkup
        return updated
Example #2
0
    def __init__(self, config, enviro, logger, statechglogger):
        Rule.__init__(self, config, enviro, logger, statechglogger)
        self.logger = logger
        self.rulenumber = 244
        self.rulename = "RemoveSUIDGames"
        self.formatDetailedResults("initialize")
        self.mandatory = True
        self.sethelptext()
        self.applicable = {'type': 'white', 'family': 'linux'}

        # Configuration item instantiation
        datatype = "bool"
        key = "REMOVESUIDGAMES"
        instructions = "To disable this rule, set the value of " + \
                       "REMOVESUIDGAMES to false."
        default = True
        self.ci = self.initCi(datatype, key, instructions, default)

        self.guidance = ["LANL 15.7"]
        self.iditerator = 0
        self.ph = Pkghelper(self.logger, self.environ)

        self.gamelist = [
            'atlantik', 'bomber', 'bovo', 'gnuchess', 'kapman', 'kasteroids',
            'katomic', 'kbackgammon', 'kbattleship', 'kblackbox', 'kblocks',
            'kbounce', 'kbreakout', 'kdiamond', 'kenolaba', 'kfouleggs',
            'kfourinline', 'kgoldrunner', 'killbots', 'kiriki', 'kjumpingcube',
            'klickety', 'klines', 'kmahjongg', 'kmines', 'knetwalk', 'kolf',
            'kollision', 'konquest', 'kpat', 'kpoker', 'kreversi', 'ksame',
            'kshisen', 'ksirk', 'ksirkskineditor', 'ksirtet', 'ksmiletris',
            'ksnake', 'kspaceduel', 'ksquares', 'ksudoku', 'ktron',
            'ktuberling', 'kubrick', 'kwin4', 'kwin4proc', 'lskat',
            'lskatproc', 'gnome-games', 'kdegames', 'gnome-taquin'
        ]
Example #3
0
    def localize(self):
        """
        set paths based on what versions of which utilities exist on the system

        :return: void
        """

        self.gsettings = "/usr/bin/gsettings"
        self.gconf = "/usr/bin/gconftool-2"
        self.dconf = "/usr/bin/dconf"
        self.getcmd = ""
        self.setcmd = ""
        self.updatecmd = ""
        packages = ["gnome", "gdm", "gdm3", "gnome3"]
        self.lockfile = "/etc/dconf/db/local.d/locks/stonix-thumbnailers"
        self.lockthumbnails = {"/org/gnome/desktop/thumbnailers/disable-all":""}

        if os.path.exists(self.gsettings):
            self.getcmd = self.gsettings + " get org.gnome.desktop.thumbnailers disable-all"
            self.setcmd = self.gsettings + " set org.gnome.desktop.thummailerss disable-all true"
        elif os.path.exists(self.gconf):
            self.getcmd = self.gconf + " --get /schemas/org/gnome/desktop/thumbnailers/disable_all"
            self.setcmd = self.gconf + " --type bool --set /schemass/org/gnome/desktop/thumbnailers/disable_all true"
        if os.path.exists(self.dconf):
            self.updatecmd = self.dconf + " update"

        self.ch = CommandHelper(self.logger)
        self.ph = Pkghelper(self.logger, self.environ)
        self.gnome_installed = False
        if self.environ.getosname() != "Mac OS":
            if [self.ph.check(p) for p in packages]:
                self.gnome_installed = True
Example #4
0
    def report(self):
        """

        :return: self.compliant
        :rtype: bool
        """

        try:
            self.detailedresults = ""
            compliant = True

            self.ph = Pkghelper(self.logger, self.environ)
            if self.ph.manager == "apt-get":
                pkg = "tftpd-hpa"
                if self.ph.check(pkg):
                    self.tftpFile = "/etc/default/tftpd-hpa"
                    if os.path.exists(self.tftpFile):
                        compliant = self.reportDebianSys()
            else:
                pkg = "tftp-server"
                if self.ph.check(pkg):
                    self.tftpFile = "/etc/xinetd.d/tftp"
                    if os.path.exists(self.tftpFile):
                        compliant = self.reportOtherSys()
            self.compliant = compliant
        except (KeyboardInterrupt, SystemExit):
            raise
        except Exception:
            self.compliant = False
            self.detailedresults += "\n" + traceback.format_exc()
            self.logdispatch.log(LogPriority.ERROR, self.detailedresults)
        self.formatDetailedResults("report", self.compliant,
                                   self.detailedresults)
        self.logdispatch.log(LogPriority.INFO, self.detailedresults)
        return self.compliant
Example #5
0
    def reportUbuntu(self):
        '''if debian, check for unity-lens-shopping and unity-webapps-common
        cloud service packages


        '''

        # defaults
        self.compliant = True
        self.detailedresults = ""

        try:

            self.ph = Pkghelper(self.logdispatch, self.environ)

            for package in self.debianpkglist:
                if self.ph.check(package):
                    self.compliant = False

        except (KeyboardInterrupt, SystemExit):
            raise
        except Exception as err:
            self.rulesuccess = False
            self.detailedresults = self.detailedresults + "\n" + str(err) + \
                " - " + str(traceback.format_exc())
            self.logdispatch.log(LogPriority.ERROR, self.detailedresults)
        self.formatDetailedResults("report", self.compliant,
                                   self.detailedresults)
        self.logdispatch.log(LogPriority.INFO, self.detailedresults)
        return self.compliant
Example #6
0
    def __init__(self, config, environ, logger, statechglogger):
        """
        Constructor
        """
        Rule.__init__(self, config, environ, logger, statechglogger)
        self.logger = logger
        self.rulenumber = 9
        self.rulename = 'SystemAccounting'
        self.formatDetailedResults("initialize")
        self.mandatory = False
        self.rootrequired = True
        self.sethelptext()
        self.guidance = ['CIS 2.4', 'cce-3992-5']
        self.applicable = {
            'type': 'white',
            'family': 'linux',
            'os': {
                'Mac OS X': ['10.15', 'r', '10.15.10']
            }
        }

        # set up configuration item for this rule
        datatype = 'bool'
        key = 'SYSTEMACCOUNTING'
        instructions = "This is an optional rule and is disabled by default, due to the significant load it can place on the system when enabled. To enable system accounting, set the value of SYSTEMACCOUNTING to True."
        default = False
        self.ci = self.initCi(datatype, key, instructions, default)

        self.ostype = self.environ.getostype()
        self.ph = Pkghelper(self.logger, self.environ)
        self.ch = CommandHelper(self.logger)
        self._set_paths()
Example #7
0
    def init_objs(self):
        """

        """

        self.ph = Pkghelper(self.logger, self.environ)
        self.ch = CommandHelper(self.logger)
    def __init__(self, config, environ, logger, statechglogger):
        """

        @param config:
        @param environ:
        @param logger:
        @param statechglogger:
        """

        Rule.__init__(self, config, environ, logger, statechglogger)
        self.logger = logger
        self.rulenumber = 97
        self.rulename = "ConfigureProcessAccounting"
        self.formatDetailedResults("initialize")
        self.mandatory = True
        self.sethelptext()
        self.guidance = ["CCE-RHEL7-CCE-TBD 3.2.15"]
        self.applicable = {"type": "white", "family": ["linux"]}

        # Configuration item instantiation
        datatype = "bool"
        key = "CONFIGUREPROCESSACCOUNTING"
        instructions = "To disable this rule, set the value of " + \
                       "CONFIGUREPROCESSACCOUNTING to False."
        default = True
        self.ci = self.initCi(datatype, key, instructions, default)

        self.ph = Pkghelper(self.logger, self.environ)
        self.sh = ServiceHelper(self.environ, self.logger)
Example #9
0
 def __init__(self, config, environ, logger, statechglogger):
     Rule.__init__(self, config, environ, logger, statechglogger)
     self.logger = logger
     self.rootrequired = True
     self.rulenumber = 127
     self.rulename = 'SSHTimeout'
     self.formatDetailedResults("initialize")
     self.mandatory = True
     self.sethelptext()
     self.boolCi = self.initCi(
         "bool", "SSHTIMEOUTON",
         "To disable this rule set the value " + "of SSHTIMEOUTON to False",
         True)
     self.intCi = self.initCi(
         "int", "SSHTIMEOUT", "Set your preferred timeout value here, " +
         "in seconds. Default is 900 (15 minutes).", 900)
     self.guidance = ['NSA 3.5.2.3']
     self.iditerator = 0
     self.editor = ""
     self.applicable = {
         'type': 'white',
         'family': ['linux', 'solaris', 'freebsd'],
         'os': {
             'Mac OS X': ['10.15', 'r', '10.15.10']
         }
     }
     self.ph = Pkghelper(self.logger, self.environ)
Example #10
0
    def report(self):
        """
        report whether any of the packages listed in the self.pkgci ci are installed
        return False if any are installed
        return True if none of them are installed

        :returns: self.compliant
        :rtype: bool
        """

        self.detailedresults = ""
        self.compliant = True
        self.ph = Pkghelper(self.logger, self.environ)
        packages = self.pkgci.getcurrvalue()
        self.remove_packages = []

        try:

            if packages:
                for pkg in packages:
                    if self.ph.check(pkg):
                        self.remove_packages.append(pkg)
                        self.detailedresults += pkg + " is installed\n"
                        self.compliant = False

        except Exception:
            self.compliant = False
            self.detailedresults += traceback.format_exc()
            self.logdispatch.log(LogPriority.ERROR, self.detailedresults)
        self.formatDetailedResults("report", self.compliant,
                                   self.detailedresults)
        self.logdispatch.log(LogPriority.INFO, self.detailedresults)

        return self.compliant
Example #11
0
    def initobjs(self):
        '''initialize objects needed/used by other methods within this class


        :returns: void
        @author: Breen Malmberg

        '''

        try:

            # if you add class variables here, be sure to also add
            # checks for them, in the checkinitobjs() method
            self.pkgh = Pkghelper(self.logger, self.environ)
            self.svch = ServiceHelper(self.environ, self.logger)
            self.cmdh = CommandHelper(self.logger)
            self.debian = False
            self.suse = False
            self.redhat = False
            self.pkgdict = {}
            self.confpathdict = {}
            self.servicename = ''
            self.osdetected = False

        except Exception:
            raise
Example #12
0
    def initobjs(self):
        '''initialize helper objects
        @author: Breen Malmberg


        '''

        self.ch = CommandHelper(self.logger)
        self.pkg = Pkghelper(self.logger, self.environ)
Example #13
0
    def __init__(self, config, environ, logger, statechglogger):
        Rule.__init__(self, config, environ, logger, statechglogger)
        self.logger = logger
        self.rulenumber = 105
        self.rulename = "DisableGUILogon"
        self.formatDetailedResults("initialize")
        self.mandatory = False
        self.applicable = {'type': 'white',
                           'family': ['linux']}

        # Configuration item instantiation
        datatype = "bool"
        key = "DISABLEX"
        instructions = "To enable this item, set the value of DISABLEX " + \
            "to True. When enabled, this rule will disable the automatic " + \
            "GUI login, and the system will instead boot to the console " + \
            "(runlevel 3). This will not remove any GUI components, and the " + \
            "GUI can still be started using the \"startx\" command."
        default = False
        self.ci1 = self.initCi(datatype, key, instructions, default)

        datatype = "bool"
        key = "LOCKDOWNX"
        instructions = "To enable this item, set the value of LOCKDOWNX " + \
            "to True. When enabled, this item will help secure X Windows by " + \
            "disabling the X Font Server (xfs) service and disabling X " + \
            "Window System Listening. This item should be enabled if X " + \
            "Windows is disabled but will be occasionally started via " + \
            "startx, unless there is a mission-critical need for xfs or " + \
            "a remote display."
        default = False
        self.ci2 = self.initCi(datatype, key, instructions, default)

        datatype = "bool"
        key = "REMOVEX"
        instructions = "To enable this item, set the value of REMOVEX " + \
            "to True. When enabled, this item will COMPLETELY remove X " + \
            "Windows from the system, and on most platforms will disable " + \
            "any currently running display manager. It is therefore " + \
            "recommended that this rule be run from a console session " + \
            "rather than from the GUI.\nREMOVEX cannot be undone."
        default = False
        self.ci3 = self.initCi(datatype, key, instructions, default)

        self.guidance = ["NSA 3.6.1.1", "NSA 3.6.1.2", "NSA 3.6.1.3",
                         "CCE 4462-8", "CCE 4422-2", "CCE 4448-7",
                         "CCE 4074-1"]
        self.iditerator = 0
        self.ph = Pkghelper(self.logger, self.environ)
        self.ch = CommandHelper(self.logger)
        self.sh = ServiceHelper(self.environ, self.logger)
        self.myos = self.environ.getostype().lower()
        self.sethelptext()
Example #14
0
    def report(self):
        """determine whether the fix() method of this rule has run successfully
        yet or not

        :return: self.compliant
        :rtype: bool
        """

        self.detailedresults = ""

        # UPDATE THIS SECTION IF THE CONSTANTS BEING USED IN THIS CLASS CHANGE
        self.constlist = [NTPSERVERSEXTERNAL, NTPSERVERSINTERNAL]
        if not any(self.constlist):
            self.compliant = False
            self.detailedresults += "\nThis rule requires that at least one of the following constants, in localize.py, be defined and not None: NTPSERVERSEXTERNAL, NTPSERVERSINTERNAL"
            self.formatDetailedResults("report", self.compliant,
                                       self.detailedresults)
            return self.compliant

        self.ph = Pkghelper(self.logger, self.environ)
        self.ch = CommandHelper(self.logger)

        if self._test_connection(NTPSERVERSINTERNAL):
            self.time_servers = NTPSERVERSINTERNAL
        else:
            self.time_servers = NTPSERVERSEXTERNAL

        self.compliant = True

        try:

            if self.environ.getosfamily() == "darwin":
                self.ss = "/usr/sbin/systemsetup"
                if not self._report_darwin():
                    self.compliant = False
            else:
                if not self._report_linux():
                    self.compliant = False

        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.compliant = False
            self.detailedresults += "\n" + traceback.format_exc()
            self.logdispatch.log(LogPriority.ERROR, self.detailedresults)
        self.formatDetailedResults("report", self.compliant,
                                   self.detailedresults)
        self.logdispatch.log(LogPriority.INFO, self.detailedresults)

        return self.compliant
Example #15
0
    def report(self):
        '''Determine which report method(s) to run and run them


        :returns: bool
        @author bemalmbe

        '''

        # defaults
        self.detailedresults = ""

        try:

            if self.environ.getostype() == 'Mac OS X':
                self.compliant = self.reportmac()
                self.formatDetailedResults("report", self.compliant,
                                           self.detailedresults)
                self.logdispatch.log(LogPriority.INFO, self.detailedresults)
                return self.compliant
            compliant = True
            self.svchelper = ServiceHelper(self.environ, self.logger)
            self.pkghelper = Pkghelper(self.logger, self.environ)

            if self.disablesnmp.getcurrvalue():
                if not self.reportDisableSNMP():
                    compliant = False

            if self.configuresnmp.getcurrvalue():
                if not self.reportConfigureSNMP():
                    compliant = False

            self.compliant = compliant

        except AttributeError:
            self.detailedresults = traceback.format_exc()
            self.logger.log(LogPriority.DEBUG, self.detailedresults)
        except (KeyboardInterrupt, SystemExit):
            raise
        except Exception as err:
            self.rulesuccess = False
            self.detailedresults = self.detailedresults + "\n" + str(err) + \
                " - " + str(traceback.format_exc())
            self.logdispatch.log(LogPriority.ERROR, self.detailedresults)
        self.formatDetailedResults("report", self.compliant,
                                   self.detailedresults)
        self.logdispatch.log(LogPriority.INFO, self.detailedresults)
        return self.compliant
Example #16
0
    def __init__(self, config, environ, logger, statechglogger):
        '''

        @param config:
        @param environ:
        @param logger:
        @param statechglogger:
        '''
        Rule.__init__(self, config, environ, logger, statechglogger)

        self.logger = logger
        self.rulenumber = 29
        self.rulename = 'DisableRemoveableStorage'
        self.mandatory = False
        self.formatDetailedResults("initialize")
        self.guidance = ['NSA 2.2.2.2, CIS, NSA(2.2.2.2), cce-4006-3,4173-1']
        self.applicable = {
            'type': 'white',
            'family': ['linux', 'solaris', 'freebsd'],
            'os': {
                'Mac OS X': ['10.15', 'r', '10.15.10']
            },
            'fisma': 'high'
        }

        # configuration item instantiation
        datatype = "bool"
        key = "DISABLEREMOVEABLESTORAGE"
        instructions = "To disable removeable storage devices on this system, set the value of DISABLEREMOVEABLESTORAGE to True"
        default = False
        self.storageci = self.initCi(datatype, key, instructions, default)

        #global variables
        self.grubfiles = [
            "/boot/grub2/grub.cfg", "/boot/grub/grub.cfg",
            "/boot/grub/grub.conf"
        ]
        self.pcmcialist = ['pcmcia-cs', 'kernel-pcmcia-cs', 'pcmciautils']
        self.pkgremovedlist = []
        self.iditerator = 0
        self.created = False
        self.daemonpath = os.path.abspath(
            os.path.join(os.path.dirname(
                sys.argv[0]))) + "/stonix_resources/disablestorage.py"
        self.sethelptext()
        self.grubperms = ""
        self.ph = Pkghelper(self.logger, self.environ)
        self.ch = CommandHelper(self.logger)
Example #17
0
    def initObjs(self):
        '''initialize all required class objects


        :returns: void
        @author: Breen Malmberg

        '''

        if self.linux:
            self.ph = Pkghelper(self.logger, self.environ)
        if self.darwin:
            pass
        self.sh = ServiceHelper(self.environ, self.logger)
        self.serviceTarget = ""
        self.ch = CommandHelper(self.logger)
    def report(self):
        '''The report method examines the current configuration and determines
        whether or not it is correct. If the config is correct then the
        self.compliant, self.detailedresults and self.currstate properties are
        updated to reflect the system status. self.rulesuccess will be updated
        if the rule does not succeed.
        Perform a check to see if PROMPT has been set to 'no' or not


        :returns: bool
        @author bemalmbe
        @change: dwalker

        '''
        try:
            self.detailedresults = ""
            compliant = True
            self.perms = [0, 0, 420]
            self.helper = Pkghelper(self.logger, self.environ)
            if self.helper.manager == "portage":
                self.filepath = "/etc/conf.d/rc"
                keyval = {"RC_INTERACTIVE": "no"}
            elif self.helper.manager == "zypper":
                self.filepath = "/etc/sysconfig/boot"
                keyval = {"PROMPT_FOR_CONFIRM": "no"}
            elif self.helper.manager == "apt-get":
                self.filepath = "/etc/default/grub"
                keyval = {"GRUB_DISABLE_RECOVERY": '"true"'}
                self.restart = "/usr/sbin/update-grub"
            elif self.helper.manager == "yum" or self.helper.manager == "dnf":
                self.filepath = "/etc/sysconfig/init"
                keyval = {"PROMPT": "no"}
            tmpPath = self.filepath + ".tmp"
            if not os.path.exists(self.filepath):
                if createFile(self.filepath, self.logger):
                    self.created = True
            if not checkPerms(self.filepath, self.perms, self.logger):
                compliant = False
                self.detailedresults += "Permissions are not correct on " + \
                    self.filepath + "\n"
            self.editor = KVEditorStonix(self.statechglogger, self.logger,
                                         "conf", self.filepath, tmpPath,
                                         keyval, "present", "closedeq")
            if os.path.exists(self.filepath):
                if not self.editor.report():
                    self.detailedresults += "Configuration for " + \
                        self.filepath + " is incorrect via kveditor report\n"
                    compliant = False
            self.compliant = compliant

        except (KeyboardInterrupt, SystemExit):
            raise
        except Exception:
            self.rulesuccess = False
            self.detailedresults += "\n" + traceback.format_exc()
            self.logdispatch.log(LogPriority.ERROR, self.detailedresults)
        self.formatDetailedResults("report", self.compliant,
                                   self.detailedresults)
        self.logdispatch.log(LogPriority.INFO, self.detailedresults)
        return self.compliant
Example #19
0
    def report(self):
        try:
            self.detailedresults = ""
            self.ch = CommandHelper(self.logger)
            self.lockedpwds = '^\*LK\*|^!|^\*|^x$'
            if self.environ.getosfamily() == "linux":
                self.ph = Pkghelper(self.logger, self.environ)
                self.specs = {"PASS_MAX_DAYS": "180",
                              "PASS_MIN_DAYS": "1",
                              "PASS_MIN_LEN": "8",
                              "PASS_WARN_AGE": "28"}
                if self.ph.manager in ("apt-get", "zypper"):
                    # apt-get systems do not set min length in the same file
                    # as other systems(login.defs)
                    del self.specs["PASS_MIN_LEN"]

                self.shadowfile = "/etc/shadow"
                self.logdeffile = "/etc/login.defs"
                self.useraddfile = "/etc/default/useradd"
                self.libuserfile = "/etc/libuser.conf"
                self.compliant = self.reportLinux()
            elif self.environ.getosfamily() == "solaris":
                self.specs = {"PASSLENGTH": "8",
                              "MINWEEKS": "1",
                              "MAXWEEKS": "26",
                              "WARNWEEKS": "4"}
                self.shadowfile = "/etc/shadow"
                self.logdeffile = "/etc/default/passwd"
                self.compliant = self.reportSolaris()
            elif self.environ.getosfamily() == "freebsd":
                self.specs = {"warnpassword": "******",
                              "minpasswordlen": "8",
                              "passwordtime": "180d"}
                self.shadowfile = "/etc/master.passwd"
                self.loginfile = "/etc/login.conf"
                self.compliant = self.reportFreebsd()
        except (KeyboardInterrupt, SystemExit):
            # User initiated exit
            raise
        except Exception:
            self.rulesuccess = False
            self.detailedresults += "\n" + traceback.format_exc()
            self.logdispatch.log(LogPriority.ERROR, self.detailedresults)
        self.formatDetailedResults("report", self.compliant,
                                   self.detailedresults)
        self.logdispatch.log(LogPriority.INFO, self.detailedresults)
        return self.compliant
Example #20
0
    def initobjs(self):
        ''' '''

        try:

            self.ph = Pkghelper(self.logger, self.environ)
            self.ch = CommandHelper(self.logger)
            self.linux = False
            self.mac = False
            self.gnome2 = False
            self.gnome3 = False
            self.kde = False
            self.lightdm = False
            self.badline = False

        except Exception:
            raise
Example #21
0
 def report(self):
     try:
         self.detailedresults = ""
         self.ph = Pkghelper(self.logger, self.environ)
         self.data1 = {
             "ddns-update-style": "none;",
             "deny": ["declines;", "bootp;"]
         }
         self.data2 = [
             "domain-name", "domain-name-servers", "nis-domain",
             "nis-servers", "ntp-servers", "routers", "time-offset"
         ]
         if self.ph.manager == "zypper":
             self.path = "/etc/dhcpd.conf"
         elif self.ph.manager == "yum" or self.ph.manager == "dnf":
             self.path = "/etc/dhcp/dhcpd.conf"
         elif self.ph.manager == "apt-get":
             self.path = "/etc/dhcp/dhcpd.conf"
         self.tmppath = self.path + ".tmp"
         compliant = True
         if os.path.exists(self.path):
             if not checkPerms(self.path, [0, 0, 0o644], self.logger):
                 self.detailedresults += "The permissions on " + \
                     self.path + " are incorrect\n"
                 compliant = False
             self.editor = KVEditorStonix(self.statechglogger, self.logger,
                                          "conf", self.path, self.tmppath,
                                          self.data1, "present", "space")
             if not self.editor.report():
                 self.detailedresults += self.path + " doesn't contain " + \
                     "the correct contents\n"
                 compliant = False
             contents = readFile(self.path, self.logger)
             for line in contents:
                 if re.match('^#', line) or re.match(r'^\s*$', line):
                     continue
                 if re.search("^option", line):
                     linesplit = line.split()
                     if len(linesplit) >= 2:
                         for item in self.data2:
                             if re.search(item, linesplit[1]):
                                 compliant = False
                                 self.detailedresults += "Unwanted " + \
                                     "option found in " + self.path + \
                                     ": " + line
         self.compliant = compliant
     except (KeyboardInterrupt, SystemExit):
         raise
     except Exception:
         self.rulesuccess = False
         self.detailedresults += "\n" + traceback.format_exc()
         self.logdispatch.log(LogPriority.ERROR, self.detailedresults)
     self.formatDetailedResults("report", self.compliant,
                                self.detailedresults)
     self.logdispatch.log(LogPriority.INFO, self.detailedresults)
     return self.compliant
Example #22
0
    def __init__(self, config, environ, logger, statechglogger):
        """
        private method to initialize the module

        :param config: configuration object instance
        :param environ: environment object instance
        :param logger: logdispatcher object instance
        :param statechglogger: statechglogger object instance
        """

        Rule.__init__(self, config, environ, logger, statechglogger)
        self.logger = logger
        self.rulenumber = 84
        self.rulename = "AuditFirefoxUsage"
        self.mandatory = True
        self.rootrequired = True
        self.sethelptext()
        self.formatDetailedResults("initialize")
        self.guidance = []
        self.applicable = {'type': 'white', 'family': ['linux']}
        # Configuration item instantiation
        datatype = 'list'
        key = 'APPROVEDDOMAINS'
        instructions = """This is a list of domains which the root user is \
approved to browse."""
        default = LOCALDOMAINS
        if default == None:
            default = ["localhost"]
        elif not default:
            default = ["localhost"]
        self.approvedDomainsCi = self.initCi(datatype, key, instructions,
                                             default)

        datatype = 'bool'
        key = 'DISABLEPROXY'
        instructions = """To disable Firefox's proxy settings, ensuring that \
browsing is limited to local domains in a proxied environment, set \
DISABLEPROXY to True."""
        default = True
        self.ci = self.initCi(datatype, key, instructions, default)

        self.ph = Pkghelper(self.logger, self.environ)
        self.auditonly = True
Example #23
0
 def report(self):
     try:
         self.detailedresults = ""
         if self.environ.getosfamily() == "linux":
             self.ph = Pkghelper(self.logger, self.environ)
             self.compliant = self.reportLinux()
         elif self.environ.getosfamily() == "freebsd":
             self.compliant = self.reportFree()
         elif self.environ.getostype() == "Mac OS X":
             self.compliant = self.reportMac()
     except (KeyboardInterrupt, SystemExit):
         raise
     except Exception:
         self.rulesuccess = False
         self.detailedresults += "\n" + traceback.format_exc()
         self.logdispatch.log(LogPriority.ERROR, self.detailedresults)
     self.formatDetailedResults("report", self.compliant,
                                self.detailedresults)
     self.logdispatch.log(LogPriority.INFO, self.detailedresults)
     return self.compliant
Example #24
0
    def __init__(self, config, environ, logger, statechglogger):
        '''
        Constructor
        '''
        Rule.__init__(self, config, environ, logger, statechglogger)
        self.logger = logger
        self.statechglogger = statechglogger
        self.rulenumber = 7
        self.rulename = 'SoftwarePatching'
        self.formatDetailedResults("initialize")
        self.mandatory = True
        self.sethelptext()
        self.rootrequired = True
        self.environ = environ
        self.applicable = {
            'type': 'black',
            'family': ['darwin', 'solaris', 'suse']
        }

        data = "bool"
        key = "SCHEDULEUPDATE"
        instructions = "To disable creation of a scheduled " + \
                       "update job set the value of this " + \
                       "setting to no or false. Doing so " + \
                       "puts a larger burden for keeping " + \
                       "this system up to date on the system " + \
                       "administrators. This setting doesn't " + \
                       "apply to some systems whose updates " + \
                       "cannot be installed automatically " + \
                       "for various reasons. "
        default = True

        self.ci = self.initCi(data, key, instructions, default)

        self.guidance = [
            'CCE 14813-0', 'CCE 14914-6', 'CCE 4218-4', 'CCE 14440-2'
        ]
        self.caveats = ''
        self.ch = CommandHelper(self.logger)
        self.ph = Pkghelper(self.logger, self.environ)
        self.constlist = [PROXY, UPDATESERVERS]
    def report(self):
        '''Check for the existence of any of a number of data-collection
        and reporting utilities on the system
        report compliance status as not compliant if any exist
        report compliance status as compliant if none exist


        :returns: self.compliant

        :rtype: bool
@author: Breen Malmberg

        '''

        self.detailedresults = ""
        self.ph = Pkghelper(self.logger, self.environ)
        self.compliant = True

        self.pkgslist = ["popularity-contest", "apport", "ubuntu-report"]
        self.removepkgs = []

        try:

            for pkg in self.pkgslist:
                if self.ph.check(pkg):
                    self.compliant = False
                    self.detailedresults += "\nData collection utility: " + str(
                        pkg) + " is still installed"
                    self.removepkgs.append(pkg)

        except (KeyboardInterrupt, SystemExit):
            raise
        except Exception:
            self.compliant = False
            self.detailedresults += "\n" + traceback.format_exc()
            self.logdispatch.log(LogPriority.ERROR, self.detailedresults)
        self.formatDetailedResults("report", self.compliant,
                                   self.detailedresults)
        self.logdispatch.log(LogPriority.INFO, self.detailedresults)

        return self.compliant
Example #26
0
    def report(self):
        """check the gdm/gnome setting for thumbnailers to determine
        if it is off or on. report compliant if it is off,
        non-compliant if it is on.


        :return: self.compliant
        :rtype: bool
        """

        self.compliant = True
        self.ch = CommandHelper(self.logger)
        self.ph = Pkghelper(self.logger, self.environ)
        self.detailedresults = ""

        try:
            self.localize()
            if self.gnome_installed:
                # This portion of the code is relevant to user context
                if self.environ.geteuid() != 0:
                    self.ch.executeCommand(self.getcmd)
                    if not self.ch.findInOutput("true"):
                        self.compliant = False
                        self.detailedresults += "\nGnome thumbnailers are enabled"
                # This portion of the code is relevant to root context
                else:
                    if not self.checkLockFile():
                        self.compliant = False
            else:
                self.logger.log(LogPriority.DEBUG, "Gnome is not installed. Nothing to check.")

        except (KeyboardInterrupt, SystemExit):
            raise
        except Exception:
            self.compliant = False
            self.detailedresults += "\n" + traceback.format_exc()
            self.logger.log(LogPriority.ERROR, self.detailedresults)
        self.formatDetailedResults("report", self.compliant, self.detailedresults)
        self.logger.log(LogPriority.INFO, self.detailedresults)

        return self.compliant
Example #27
0
    def report(self):
        '''Perform a check to see if package is already installed.
        If so, there is  no need to run Fix method


        :returns: self.compliant

        :rtype: bool
@author: Derek T Walker

        '''

        try:

            self.detailedresults = ""
            self.ph = Pkghelper(self.logger, self.environ)
            self.ch = CommandHelper(self.logger)
            self.compliant = True

            self.set_pkg()

            if not self.ph.check(self.pkg):
                self.compliant = False
                self.detailedresults += "\nvlock Package is NOT installed"
            else:
                self.detailedresults += "\nvlock Package is installed"

        except (KeyboardInterrupt, SystemExit):
            raise
        except Exception:
            self.compliant = False
            self.detailedresults += "\n" + traceback.format_exc()
            self.logdispatch.log(LogPriority.ERROR, self.detailedresults)
        self.formatDetailedResults("report", self.compliant,
                                   self.detailedresults)
        self.logdispatch.log(LogPriority.INFO, self.detailedresults)
        return self.compliant
Example #28
0
    def report(self):
        '''checks to see if a plus entry exists, returns True if a plus entry
        exists and False if not


        :returns: bool
        @author: D.Walker

        '''
        try:
            self.detailedresults = ""
            compliant = True
            self.badfiles = []
            self.ph = Pkghelper(self.logger, self.environ)
            if self.environ.getostype() == "Mac OS X":
                filelist = ["/private/etc/master.passwd",
                            "/private/etc/shadow",
                            "/private/etc/passwd",
                            "/private/etc/group",
                            "/private/etc/grp"]
            else:
                filelist = ["/etc/master.passwd",
                            "/etc/shadow",
                            "/etc/passwd",
                            "/etc/group",
                            "/etc/grp"]
            counter = 0
            for fileItem in filelist:
                if os.path.exists(fileItem):
                    contents = readFile(fileItem, self.logger)
                    for line in contents:
                        if re.search("^\+", line.strip()):
                            self.badfiles.append(fileItem)
                            counter += 1
                            compliant = False
            self.detailedresults += "Found " + str(counter) + \
" plus accounts\n"
            self.compliant = compliant
        except (KeyboardInterrupt, SystemExit):
            # User initiated exit
            raise
        except Exception:
            self.rulesuccess = False
            self.detailedresults += "\n" + traceback.format_exc()
            self.logdispatch.log(LogPriority.ERROR, self.detailedresults)
        self.formatDetailedResults("report", self.compliant,
                                   self.detailedresults)
        self.logdispatch.log(LogPriority.INFO, self.detailedresults)
        return self.compliant
Example #29
0
    def fix_rhel7_boot_fips(self):
        """
        enable fips compliance on redhat 7 systems
        https://access.redhat.com/solutions/137833

        :return: success
        :rtype: bool
        """

        success = True
        self.ph = Pkghelper(self.logdispatch, self.environ)
        grubby = "/usr/sbin/grubby"
        findmnt = "/usr/bin/findmnt"

        try:

            # configure the system to be compatible with luks and fips
            self.configure_luks_compatibility()

            # add fips=1 to kernel boot line (requires sytem restart to take effect)
            self.ch.executeCommand(grubby + " --update-kernel=$(" + grubby +
                                   " --default-kernel) --args=fips=1")
            retcode = self.ch.getReturnCode()
            if retcode != 0:
                success = False
                self.detailedresults += "\nFailed to enable fips compliance in kernel boot line"

            # update boot partition info
            uuid = ""
            self.ch.executeCommand(findmnt + " -no uuid /boot")
            retcode = self.ch.getReturnCode()
            if retcode == 0:
                uuid = self.ch.getOutputString()
            else:
                success = False
                self.detailedresults += "\nFailed to update boot partition info"
            if uuid:
                self.ch.executeCommand(
                    "[[ -n $uuid ]] && " + grubby + " --update-kernel=$(" +
                    grubby + " --default-kernel) --args=boot=UUID=${uuid}")

        except:
            raise

        return success
Example #30
0
class RemoveSoftware(Rule):
    """This class removes any unnecessary software installed on the system"""
    def __init__(self, config, environ, logger, statechglogger):
        """
        Constructor
        """

        Rule.__init__(self, config, environ, logger, statechglogger)
        self.logger = logger
        self.rulenumber = 91
        self.rulename = "RemoveSoftware"
        self.mandatory = True
        self.formatDetailedResults("initialize")
        self.sethelptext()
        self.rootrequired = True
        self.guidance = ["NSA 2.3.5.6"]
        self.applicable = {'type': 'white', 'family': ['linux', 'freebsd']}

        # Configuration item instantiation
        datatype1 = "bool"
        key1 = "REMOVESOFTWARE"
        instructions1 = "To disable this rule set the value of REMOVESOFTWARE TO False."
        default1 = False
        self.ci = self.initCi(datatype1, key1, instructions1, default1)

        datatype2 = "list"
        key2 = "PACKAGES"
        instructions2 = "Enter the package(s) that you wish to remove.  By " + \
            "default we already list packages that we recommend for removal."
        default2 = [
            "squid", "telnet-server", "rsh-server", "rsh", "rsh-client",
            "talk", "talk-server", "talkd", "libpam-ccreds", "pam_ccreds",
            "tftp-server", "tftp", "tftpd", "udhcpd", "dhcpd", "dhcp",
            "dhcp-server", "yast2-dhcp-server", "vsftpd", "httpd", "dovecot",
            "dovecot-imapd", "dovecot-pop3d", "snmpd", "net-snmpd", "net-snmp",
            "ipsec-tools", "irda-utils", "slapd", "openldap-servers",
            "openldap2", "bind9", "bind9.i386", "bind", "dnsutils",
            "bind-utils", "redhat-access-insights", "insights-client"
        ]

        self.pkgci = self.initCi(datatype2, key2, instructions2, default2)

    def report(self):
        """
        report whether any of the packages listed in the self.pkgci ci are installed
        return False if any are installed
        return True if none of them are installed

        :returns: self.compliant
        :rtype: bool
        """

        self.detailedresults = ""
        self.compliant = True
        self.ph = Pkghelper(self.logger, self.environ)
        packages = self.pkgci.getcurrvalue()
        self.remove_packages = []

        try:

            if packages:
                for pkg in packages:
                    if self.ph.check(pkg):
                        self.remove_packages.append(pkg)
                        self.detailedresults += pkg + " is installed\n"
                        self.compliant = False

        except Exception:
            self.compliant = False
            self.detailedresults += traceback.format_exc()
            self.logdispatch.log(LogPriority.ERROR, self.detailedresults)
        self.formatDetailedResults("report", self.compliant,
                                   self.detailedresults)
        self.logdispatch.log(LogPriority.INFO, self.detailedresults)

        return self.compliant

    def fix(self):
        """
        remove all software packages listed in the self.pkgci list

        :returns: self.rulesuccess
        :rtype: bool
        """

        self.rulesuccess = True
        self.detailedresults = ""
        self.iditerator = 0
        enabled = self.ci.getcurrvalue()

        try:

            if not enabled:
                self.formatDetailedResults("fix", self.rulesuccess,
                                           self.detailedresults)
                return self.rulesuccess
            elif not self.remove_packages:
                self.formatDetailedResults("fix", self.rulesuccess,
                                           self.detailedresults)
                return self.rulesuccess

            # Clear out event history so only the latest fix is recorded
            eventlist = self.statechglogger.findrulechanges(self.rulenumber)
            for event in eventlist:
                self.statechglogger.deleteentry(event)

            for pkg in self.remove_packages:
                try:
                    if self.ph.remove(pkg):
                        self.iditerator += 1
                        self.detailedresults += "\nRemoved package: " + str(
                            pkg)
                        myid = iterate(self.iditerator, self.rulenumber)
                        event = {
                            "eventtype": "pkghelper",
                            "pkgname": pkg,
                            "startstate": "installed",
                            "endstate": "removed"
                        }
                        self.statechglogger.recordchgevent(myid, event)
                    else:
                        self.rulesuccess = False
                        self.detailedresults += "\nFailed to remove package: " + str(
                            pkg)
                except Exception:
                    continue

        except (KeyboardInterrupt, SystemExit):
            raise
        except Exception:
            self.rulesuccess = False
            self.detailedresults += traceback.format_exc()
            self.logdispatch.log(LogPriority.ERROR, self.detailedresults)
        self.formatDetailedResults("fix", self.rulesuccess,
                                   self.detailedresults)
        self.logdispatch.log(LogPriority.INFO, self.detailedresults)

        return self.rulesuccess
Example #31
0
    def undo(self):
        """
        Undo changes made by this rule. Some rules may not be undone.
        self.rulesuccess will be updated if the rule does not succeed.

        @author D. Kennel & D. Walker
        """
        # pass
        if not self.environ.geteuid() == 0:
            self.detailedresults = "Root access required to revert changes."
            self.formatDetailedResults("undo", None, self.detailedresults)
        try:
# This must be implemented later once the parameter option or observable
# pattern for taking control of self.detailedresults refresh is implemented
# see artf30937 : self.detailedresults through application flow for details
            self.detailedresults = ""
            undosuccessful = True
            eventlist = self.statechglogger.findrulechanges(self.rulenumber)
            if not eventlist:
                self.formatDetailedResults("undo", None, self.detailedresults)
                self.logdispatch.log(LogPriority.INFO, self.detailedresults)
                return undosuccessful
            #eventlist.reverse()
            for entry in eventlist:
                try:
                    event = self.statechglogger.getchgevent(entry)
                    if event["eventtype"] == "perm":
                        perms = event["startstate"]
                        os.chmod(event["filepath"], perms[2])
                        os.chown(event["filepath"], perms[0], perms[1])

                    elif event["eventtype"] == "conf":
                        self.statechglogger.revertfilechanges(event["filepath"],
                                                              entry)

                    elif event["eventtype"] == "comm" or \
                         event["eventtype"] == "commandstring":
                        ch = CommandHelper(self.logdispatch)
                        command = event["command"]
                        ch.executeCommand(command)
                        if ch.getReturnCode() != 0:
                            self.detailedresults = "Couldn't run the " + \
                                "command to undo\n"
                            self.logdispatch.log(LogPriority.DEBUG,
                                                 self.detailedresults)

                    elif event["eventtype"] == "creation":
                        try:
                            os.remove(event["filepath"])
                        except OSError as oser:
                            if oser.errno == 21:
                                try:
                                    os.rmdir(event["filepath"])
                                except OSError as oserr:
                                    if oserr.errno == 39:
                                        self.logdispatch.log(LogPriority.DEBUG, "Cannot remove file path: " + str(event["filepath"]) + " because it is a non-empty directory.")
                            elif oser.errno == 2:
                                self.logdispatch.log(LogPriority.DEBUG, "Cannot remove file path: " + str(event["filepath"]) + " because it does not exist.")

                    elif event["eventtype"] == "deletion":
                        self.statechglogger.revertfiledelete(event["filepath"])

                    elif event["eventtype"] == "pkghelper":
                        ph = Pkghelper(self.logdispatch, self.environ)
                        if event["startstate"] == "installed":
                            ph.install(event["pkgname"])
                        elif event["startstate"] == "removed":
                            ph.remove(event["pkgname"])
                        else:
                            self.detailedresults = 'Invalid startstate for ' \
                                + 'eventtype "pkghelper". startstate should ' \
                                + 'either be "installed" or "removed"\n'
                            self.logdispatch.log(LogPriority.ERROR,
                                                 self.detailedresults)

                    elif event["eventtype"] == "servicehelper":
                        sh = ServiceHelper(self.environ, self.logdispatch)
                        if event["startstate"] == "enabled":
                            sh.enableservice(event["servicename"])
                        elif event["startstate"] == "disabled":
                            sh.disableservice(event["servicename"])
                        else:
                            self.detailedresults = 'Invalid startstate for ' \
                                + 'eventtype "servicehelper". startstate ' + \
                                'should either be "enabled" or "disabled"\n'
                            self.logdispatch.log(LogPriority.ERROR,
                                                 self.detailedresults)
                except(IndexError, KeyError):
                    self.detailedresults = "EventID " + entry + " not found"
                    self.logdispatch.log(LogPriority.DEBUG,
                                         self.detailedresults)
        except(KeyboardInterrupt, SystemExit):
            raise
        except Exception:
            undosuccessful = False
            self.detailedresults = traceback.format_exc()
            self.logdispatch.log(LogPriority.ERROR, [self.rulename + ".undo",
                                                     self.detailedresults])
        self.formatDetailedResults("undo", undosuccessful,
                                   self.detailedresults)
        self.logdispatch.log(LogPriority.INFO, self.detailedresults)
        return undosuccessful