Пример #1
0
    def apply(self, optionDict=None):
        """Create and replace the audit rules configuration."""

        action_record = []
        result, reason = self.scan(optionDict)
        if result == 'Pass':
            return 0, action_record

        option = xml.sax.saxutils.unescape(optionDict['auditRules'])
        if option[-1] != '\n':
            option = option + '\n'

        if os.path.exists(self.__target_file):
            # Protect file
            tcs_utils.protect_file(self.__target_file)

            try:
                out_obj = open(self.__target_file + '.new', 'w')
            except IOError, err:
                msg = "Unable to create temporary file (%s)." % str(err)
                self.logger.error(self.module_name, 'Apply Error: ' + msg)
                raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))

            out_obj.write(option)
            out_obj.close()

            action_record.append(
                tcs_utils.generate_diff_record(self.__target_file + '.new',
                                               self.__target_file))

            try:
                shutil.copymode(self.__target_file,
                                self.__target_file + '.new')
                shutil.copy2(self.__target_file + '.new', self.__target_file)
                sb_utils.SELinux.restoreSecurityContext(self.__target_file)

                os.unlink(self.__target_file + '.new')

            except (IOError, OSError), err:
                msg = "Unable to replace %s with new version: %s" % (
                    self.__target_file, err)
                self.logger.error(self.module_name, 'Apply Error: ' + msg)
                raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))
Пример #2
0
            self.logger.error(self.module_name, 'Apply Error: ' + msg)
            raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))

        for line_nr, line in enumerate(in_obj.xreadlines()):
            if line.strip().split("=")[0] == 'SYSLOGD_OPTIONS' and \
             '-r' in line.strip().split("=")[1]:
                out_obj.write(line.replace('-r', ''))
                msg = "Removing '-r' from SYSLOGD_OPTIONS at line %d" % line_nr
                self.logger.notice(self.module_name, 'Apply Performed: ' + msg)
            else:
                out_obj.write(line)

        in_obj.close()
        out_obj.close()

        action_record = tcs_utils.generate_diff_record(
            self.__target_file + '.new', self.__target_file)

        try:
            shutil.copymode(self.__target_file, self.__target_file + '.new')
            shutil.copy2(self.__target_file + '.new', self.__target_file)
            sb_utils.SELinux.restoreSecurityContext(self.__target_file)
            os.unlink(self.__target_file + '.new')
        except OSError:
            msg = "Unable to replace %s with new version" % self.__target_file
            self.logger.error(self.module_name, 'Apply Error: ' + msg)
            raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))

        msg = 'Remote rsyslog disabled.'
        self.logger.notice(self.module_name, 'Apply Performed: ' + msg)
        return 1, action_record
Пример #3
0
            shutil.copymode(self.__target_file3, self.__target_file3 + '.new')
        except (OSError, IOError), err:
            msg = "Unable to create temporary %s.new file" % self.__target_file3
            self.logger.error(self.module_name, 'Apply Error: ' + msg)
            raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))

        msg = "Removing any lines beginning with '+' from %s" % self.__target_file3
        self.logger.info(self.module_name, msg)
        for line in in_obj:
            if not line.startswith('+'):
                out_obj.write(line)

        in_obj.close()
        out_obj.close()

        action_record = tcs_utils.generate_diff_record(
            self.__target_file1 + '.new', self.__target_file1)

        action_record += '\n'
        action_record += tcs_utils.generate_diff_record(
            self.__target_file2 + '.new', self.__target_file2)

        action_record += '\n'
        action_record += tcs_utils.generate_diff_record(
            self.__target_file3 + '.new', self.__target_file3)

        try:
            shutil.copymode(self.__target_file1, self.__target_file1 + '.new')
            shutil.copy2(self.__target_file1 + '.new', self.__target_file1)
            sb_utils.SELinux.restoreSecurityContext(self.__target_file1)
            os.unlink(self.__target_file1 + '.new')
        except (IOError, OSError):
Пример #4
0
            # diff record to be used to restore it during an undo
            tcs_utils.protect_file(self.__target_file)

            newfile = self.__target_file + '.new'
            oldfile = self.__target_file

            try:
                out_obj = open(newfile, 'w')
                out_obj.write(new_lines)
                out_obj.close()
            except IOError, err:
                msg = "Unable to create temporary file: %s" % str(err)
                self.logger.error(self.module_name, 'Apply Error: ' + msg)
                raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))

            action_record = tcs_utils.generate_diff_record(newfile, oldfile)

            try:
                shutil.copymode(oldfile, newfile)
                shutil.copy2(newfile, oldfile)
                sb_utils.SELinux.restoreSecurityContext(newfile)
                os.unlink(newfile)
            except (OSError, IOError), err:
                msg = "Unable to replace %s with new version: %s" % (newfile,
                                                                     str(err))
                self.logger.error(self.module_name, 'Apply Error: ' + msg)
                raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))

        msg = '%s configuration file created' % self.__target_file
        self.logger.notice(self.module_name, 'Apply Performed: ' + msg)
        return 1, action_record
Пример #5
0
        made_change = False
        for line in lines:
            if auth.search(line) and not made_change:
                # Insert the new line
                out_obj.write(new_line)
                made_change = True
            else:
                out_obj.write(line)

        if made_change == False:
            out_obj.write('\n# Added by OS Lockdown\n')
            out_obj.write(new_line)

        out_obj.close()
        action_record = tcs_utils.generate_diff_record(
            '/tmp/.default_login.new', '/etc/default/login')

        try:
            shutil.copymode('/etc/default/login', '/tmp/.default_login.new')
            shutil.copy2('/tmp/.default_login.new', '/etc/default/login')
            os.unlink('/tmp/.default_login.new')
        except OSError:
            msg = "Unable to replace /etc/default/login with new version."
            self.logger.error(self.module_name, 'Apply Error: ' + msg)
            raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))

        msg = 'RETRIES=3 set in /etc/default/login'
        self.logger.notice(self.module_name, 'Apply Performed: ' + msg)

        #
        # /etc/security/policy.conf needs LOCK_AFTER_RETRIES=YES
Пример #6
0
                                break

                    except IndexError:
                        msg = "Apply Error: %s: malformed line %d" % \
                                            (self.__target_file, line_count)
                        self.logger.error(self.module_name,  msg)

                    break

            outfile.write(line + '\n') 


        infile.close()
        outfile.close()
  
        action_record = tcs_utils.generate_diff_record(self.__tmp_file, 
                                                       self.__target_file)

        try:
            shutil.copymode(self.__target_file, self.__tmp_file)
            shutil.copy2(self.__tmp_file, self.__target_file)
            os.unlink(self.__tmp_file)
        except OSError:
            msg = "Unable to replace %s with new version." % self.__target_file
            self.logger.info(self.module_name, 'Apply Error: ' + msg)
            raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))

        return 1, action_record

    ##########################################################################            
    def undo(self, change_record=None):
        """Undo previous change application."""
Пример #7
0
                                already_done[section][opt] = True
                                newline = opt + '=' + subkey[opt] + '\n'
                                msg = 'Apply Performed: Set ' + opt + ' = ' + subkey[
                                    opt]
                                self.logger.info(self.module_name, msg)

                            else:
                                if already_done[section][opt] == True:
                                    continue
                                already_done[section][opt] = True

                out_obj.write(newline)

            out_obj.close()

            change_record = tcs_utils.generate_diff_record(
                newfile, self.__gdm_file)

            # Switch old file with new one while preserving permissions
            try:
                shutil.copymode(self.__gdm_file, newfile)
                shutil.copy2(newfile, self.__gdm_file)
                os.unlink(newfile)
            except OSError, err:
                msg = "Unable to replace %s with new version: %s" % \
                      (self.__gdm_file, err)
                self.logger.error(self.module_name, 'Apply Error: ' + msg)
                raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))

        #
        # X11-Server - tcp_listen property should be set to false.
        #
Пример #8
0
                        orig_line = regex3a.sub('=', orig_line)

                        orig_line = regex4.sub('\"', orig_line)

                        orig_line = regex5.sub('=\"', orig_line)

                        msg = "Removed . and :: from PATH in %s" \
                                     % rc_script
                        self.logger.notice(self.module_name, 
                                     'Apply Performed: ' + msg)

                out_obj.write(orig_line) 
            in_obj.close()
            out_obj.close()
            change_record += tcs_utils.generate_diff_record(tmpfile, rc_script)

            try:
                shutil.copymode(rc_script, tmpfile)
                shutil.copy2(tmpfile, rc_script)
                sb_utils.SELinux.restoreSecurityContext(rc_script)
                os.unlink(tmpfile)
            except (OSError, IOError), err:
                msg = "Unable to replace %s with new version" % (rc_script, err)
                self.logger.error(self.module_name, 'Apply Error: ' + msg)

        if change_record == "":
            return 0, ""
        else:
            return 1, change_record
Пример #9
0
                    if int(parval) != int(option):
                        out_obj.write('%s: %d\n' % (param, int(option)))
                        continue

                out_obj.write(orig_line)
                    
            if found_it1 == False:
                out_obj.write('dtsession*saverTimeout: %d\n' % int(option))

            if found_it2 == False:
                out_obj.write('dtsession*lockTimeout: %d\n' % int(option))

            in_obj.close()
            out_obj.close()

            action_record.append(tcs_utils.generate_diff_record(conf_file + '.new',
                                                           conf_file) + '\n')

            try:
                shutil.copymode(conf_file, conf_file+ '.new')
                shutil.copy2(conf_file + '.new', conf_file)
                os.unlink(conf_file + '.new')
            except OSError:
                msg = "Unable to replace %s with new version." % conf_file
                self.logger.error(self.module_name, 'Apply Error: ' + msg)
                failure_flag = True


        if failure_flag == True:
            msg = 'Unable to set CDE screen saver options'
            self.logger.error(self.module_name, 'Apply Failed: ' + msg)
            return 0, ''
Пример #10
0
        made_changes = False
        for line in infile.readlines():
            if pattern.search(line.strip()):
                found_it = True
            outfile.write(line)
            

        if found_it == False:
            made_changes = True
            outfile.write('mount * hsfs udfs ufs -o nosuid\n')

        infile.close()
        outfile.close()

        if made_changes == True:
            action_record.append(tcs_utils.generate_diff_record(\
                              '/etc/rmmount.conf.new', '/etc/rmmount.conf'))
            action_record.append('\n')

            try:
                shutil.copy2('/etc/rmmount.conf.new', '/etc/rmmount.conf')
                os.unlink('/etc/rmmount.conf.new')
            except OSError, err:
                msg = 'Unable to update /etc/rmmount.conf: %s' % err
                self.logger.info(self.module_name, 'Apply Error: ' + msg)
                raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))
                
            msg = "Updated /etc/rmmount.conf"
            self.logger.info(self.module_name, 'Apply Performed: ' + msg)
        else:
            try:
                os.unlink('/etc/rmmount.conf.new')
Пример #11
0
                out_obj.write(orig_line)

            if found_it1 == False:
                out_obj.write('*lock: true\n')

            if found_it2 == False:
                out_obj.write('*lockTimeout: 0:00:00\n')

            if found_it3 == False:
                out_obj.write('*timeout: 0:%02d:00\n' % int(option))

            in_obj.close()
            out_obj.close()

            action_record.append(
                tcs_utils.generate_diff_record(conf_file + '.new', conf_file) +
                '\n')

            try:
                shutil.copymode(conf_file, conf_file + '.new')
                shutil.copy2(conf_file + '.new', conf_file)
                os.unlink(conf_file + '.new')
            except OSError:
                msg = "Unable to replace %s with new version." % conf_file
                self.logger.error(self.module_name, 'Apply Error: ' + msg)
                failure_flag = True

        if failure_flag == True:
            msg = 'Unable to set CDE screen saver options'
            self.logger.error(self.module_name, 'Apply Failed: ' + msg)
            return 0, ''
Пример #12
0
    # file
    ##########################################################################
    def generate_patch_entry(self, filename, newlines):

        try:
            tmpfile = open(self.__tmp_file, 'w')

        except IOError, err:
            msg = "Unable to create scratch file %s holding changes for %s: %s" % (
                self.__tmp_file, filename, err)
            self.logger.error(self.module_name, 'Apply Failed: ' + msg)
            raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))
        tmpfile.writelines(newlines)
        tmpfile.close()

        change_record = tcs_utils.generate_diff_record(self.__tmp_file,
                                                       filename)

        try:
            shutil.copymode(filename, self.__tmp_file)
            shutil.copy2(self.__tmp_file, filename)
            sb_utils.SELinux.restoreSecurityContext(filename)
            os.unlink(self.__tmp_file)
        except (IOError), err:
            msg = 'Apply Error: ' + str(err)
            self.logger.error(self.module_name, msg)
            raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))
        return change_record

    ##########################################################################
    def apply(self, option=None):
Пример #13
0
                            self.logger.notice(self.module_name, "Apply Performed: " + msg)
                            messages['messages'].append(msg)

                        if key_count[key] > 1:
                            line = 'discard'

                if line != 'discard':
                    out_obj.write(line+'\n')
                
            for key in self.__opts.keys():
                if key_count[key] == 0:
                    line = 'user_pref("' + key + '", ' + self.__opts[key] + ');'
                    out_obj.write(line+'\n')

            out_obj.close()
            change_record = tcs_utils.generate_diff_record(pref_file + '.new', 
                pref_file) + '\n'

            action_record += change_record
            try:
                shutil.copymode(pref_file, pref_file + '.new')
                shutil.copy2(pref_file + '.new', pref_file)
                sb_utils.SELinux.restoreSecurityContext(pref_file)
                os.unlink(pref_file + '.new')
            except (OSError, IOError), err:
                msg = "Unable to replace %s with new version: %s" % (pref_file, err)
                self.logger.error(self.module_name, 'Apply Error: ' + msg)
                raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))

            msg = pref_file + ' updated' 
            self.logger.notice(self.module_name, 'Apply Performed: ' + msg)
Пример #14
0
class SetMesgN:
    """
    SetMesgN module restricts write access to a terminal to only the owner
    """

    ##########################################################################
    def __init__(self):

        self.module_name = "SetMesgN"
        self.regex = re.compile(r'^(\s*[^#]?mesg\s+-?)([nNyY])')

        self.logger = TCSLogger.TCSLogger.getInstance()

    ##########################################################################
    def validate_input(self, option):
        if option and option != 'None':
            return 1
        return 0

    ##########################################################################
    def _change_one_file(self, action, fileName):

        # generate exclusion list *early* to avoid cluttering log
        sb_utils.file.exclusion.exlist()

        # Protect file
        tcs_utils.protect_file(fileName)

        action_record = ""
        madeChange = False
        mesg_found = False
        actionName = action[0].upper() + action[1:]

        msg = "%s: Examining '%s' " % (actionName, fileName)
        self.logger.debug(self.module_name, msg)
        lines = []
        try:
            lines = open(fileName, 'r').readlines()
        except Exception, err:
            msg = "Unable to open file %s (%s)." % (fileName, str(err))
            self.logger.error(self.module_name,
                              '%s Error: %s' % (actionName, msg))

        numLines = len(lines)
        for lr in range(numLines):
            match = self.regex.search(lines[lr])
            if match:
                #                print >>sys.stderr,"Found match at line %s:%d" % (fileName,lr)
                mesg_found = True
                newline = self.regex.sub(r'\1n', lines[lr])
                mesg_found = True
                if newline != lines[lr]:
                    msg = " found '%s' instead of '%s' at line %d of '%s'" % (
                        lines[lr].strip(), newline.strip(), lr + 1, fileName)
                    self.logger.notice(self.module_name,
                                       "Scan Failure: %s" % msg)
                    madeChange = True
                    lines[lr] = newline
                else:
                    msg = "%s: found '%s' at line %d of '%s'" % (
                        actionName, lines[lr].strip(), lr + 1, fileName)
                    self.logger.debug(self.module_name, msg)

#        self.logger.info(self.module_name, 'Read %d lines from %s, mesg_found = %s' % (len(lines), fileName, mesg_found))
        if mesg_found != True:
            if numLines > 0 and not lines[-1].endswith("\n"):
                lines.append("\n")
            lines.append("mesg n\n")
            madeChange = True
            msg = "Error: Did not find any 'mesg' commands in '%s'" % (
                fileName)
            self.logger.notice(self.module_name, 'Scan Error: %s' % (msg))
            if action == 'apply':
                msg = "Added 'mesg n' to '%s'" % (fileName)
                self.logger.notice(self.module_name, 'Apply: %s' % (msg))

        if madeChange:
            if action == 'apply':
                try:
                    out_obj = open(fileName + '.new', 'w').writelines(lines)
                except Exception, err:
                    msg = "Unable to create/write to temporary file (%s)." % str(
                        err)
                    self.logger.error(self.module_name, 'Apply Error: ' + msg)
                    raise tcs_utils.ActionError('%s %s' %
                                                (self.module_name, msg))

                action_record = tcs_utils.generate_diff_record(
                    fileName + '.new', fileName)

                try:
                    shutil.copymode(fileName, fileName + '.new')
                    shutil.copy2(fileName + '.new', fileName)
                    sb_utils.SELinux.restoreSecurityContext(fileName)
                    os.unlink(fileName + '.new')
                except OSError:
                    msg = "Unable to replace %s with new version." % fileName
                    self.logger.error(self.module_name, 'Apply Error: ' + msg)
                    raise tcs_utils.ActionError('%s %s' %
                                                (self.module_name, msg))
            else:
                action_record = "Changed"
Пример #15
0
            for line in in_obj:
                linelist = line.split()
                try:
                    if search_pattern.search(linelist[2]):
                        continue
                    if search_pattern.search(linelist[3]):
                        continue
                except IndexError:
                    pass

                out_obj.write(line)

            in_obj.close()
            out_obj.close()

            action_record += tcs_utils.generate_diff_record(
                pamfile + '.new', pamfile)

            try:
                shutil.copymode(pamfile, pamfile + '.new')
                shutil.copy2(pamfile + '.new', pamfile)
                sb_utils.SELinux.restoreSecurityContext(pamfile)
                os.unlink(pamfile + '.new')
            except (IOError, OSError):
                msg = "Unable to replace %s with new version" % pamfile
                self.logger.error(self.module_name, 'Apply Error: ' + msg)
                raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))

        msg = 'Disabled rhosts support.'
        self.logger.notice(self.module_name, 'Apply Performed: ' + msg)
        return 1, action_record