def undo(self, change_record=None): """Reverse settings in /etc/php.ini""" retval = True # convert back from string to dictionary change_record = tcs_utils.string_to_dictionary(change_record) messages = {'messages': []} gdm_prelogin_status = "N/A" kdm_prelogin_status = "N/A" if change_record.has_key('gdm'): if self.uses_simple_greeter(): gdm_prelogin_status, gdm_prelogin_changes, gdm_prelogin_messages = self.gdm_banner_simple_greeter( "undo", change_record['gdm']) else: gdm_prelogin_status, gdm_prelogin_changes, gdm_prelogin_messages = self.gdm_banner( "undo", change_record['gdm']) messages.update(gdm_prelogin_messages) if change_record.has_key('kdm'): kdm_prelogin_status, kdm_prelogin_changes, kdm_prelogin_messages = self.kdm_banner( "undo", change_record['kdm']) messages.update(kdm_prelogin_messages) if gdm_prelogin_status == 'Fail' or kdm_prelogin_status == 'Fail': retval = False return retval, '', {'messages': []}
def undo(change_record=None): retval = False # catch the case were we get a straight text string.... if type(change_record) != type({}): change_record = tcs_utils.string_to_dictionary(change_record) allChanges = {} options = {'checkOnly': False, 'exactDACs': True} # we *do* need to split these out now, as each file may have an individual set of changes.... for fileName, changesToUndo in change_record.items(): changes = sb_utils.file.fileperms.search_and_change_file_attributes( fileName, changesToUndo, options) allChanges.update(changes) if allChanges: msg = "Undo Performed" retval = True else: msg = "No changes were reverted" retval = False return retval, msg
def undo(self, change_record=None): retval = False msg = "" messages = {} messages['messages'] = [] if not change_record : msg = 'Unable to undo without valid change record' self.logger.error(self.module_name, 'Undo Error: ' + msg) return False, msg, {'messages': ["Error: %s" % msg]} changeDict = tcs_utils.string_to_dictionary(change_record) self._grubHandler = sb_utils.os.grub.GrubHandler() try: messages['messages'].extend(self._grubHandler.readGrub()) for section in changeDict['sectionNames']: self._grubHandler.restoreSectionLines(changeDict['sections'][section]) msg = "Alternate boot definition lines restored" self.logger.notice(self.module_name, 'Undo Performed: ' + msg) # writeGrub raises an exception on error self._grubHandler.writeGrub() retval = True except tcs_utils.OSNotApplicable,err: msg = "%s" % str(err) self.logger.info(self.module_name, msg) messages['messages'].append(msg)
def undo(self, change_record=None): change_record = tcs_utils.string_to_dictionary(change_record) msg = "Reverting settings in %s" % (self.__target_file) self.logger.info(self.module_name, msg) for xparam, xvalue in change_record.iteritems(): results = '' if xvalue == '': results = sb_utils.os.config.unsetparam( \ configfile=self.__target_file, param=xparam, delim='=') else: results = sb_utils.os.config.setparam( \ configfile=self.__target_file, \ param=xparam, value=xvalue, delim='=') if results == False: msg = "Unable to set %s in %s" % (xparam, self.__target_file) self.logger.error(self.module_name, 'Undo Error: ' + msg) raise tcs_utils.ActionError('%s %s' % (self.module_name, msg)) else: if xvalue == '': msg = "'%s' removed from %s" % (xparam, self.__target_file) else: msg = "'%s' set to '%s' in %s" % (xparam, xvalue, self.__target_file) self.logger.notice(self.module_name, "Undo Performed: " + msg) return 1
def undo(self, change_record=None): """Undo the previous action.""" allChanges = {} allMessages = [] retval = False # and oldstyle change record is only going to say 'on' or 'off' if change_record in ['off', 'on']: requiredChanges = {'state': change_record} if os.path.isfile(self.__target_file): requiredChanges.update({'content': ['DAEMON=yes', 'QUEUE=1h']}) allChanges = {self.__target_file: requiredChanges} else: allChanges = tcs_utils.string_to_dictionary(change_record) changes = {} messages = [] changes, messages = self.processDesiredChanges('undo', allChanges) allChanges.update(changes) allMessages.extend(messages) if allChanges: retval = True else: retval = False return retval, '', {'messages': messages}
def scanFiles(self, optionDict, action): changes = {} messages = [] # We need to operate one file at a time here... so we'll rebuild our dictiony of stuff to do as we go... for fileName in sb_utils.file.fileperms.splitStringIntoFiles( optionDict['fileList']): options = {} thisOptDict = {'fileList': fileName} if optionDict['dacs']: thisOptDict['dacs'] = optionDict['dacs'] if optionDict['allowedUnames']: thisOptDict['allowedUnames'] = optionDict['allowedUnames'] if fileName.endswith('aliases.db'): if optionDict['allowedGnamesAliasesDB']: thisOptDict['allowedGnames'] = optionDict[ 'allowedGnamesAliasesDB'] elif optionDict['allowedGnames']: thisOptDict['allowedGnames'] = optionDict['allowedGnames'] if action == "scan": r1, r2 = GenericPerms.scan(optionDict=thisOptDict) if r2: changes['changes'] = 'yes' else: r1, r2 = GenericPerms.apply(optionDict=thisOptDict) if r2 != '{}': changes.update(tcs_utils.string_to_dictionary(r2)) if changes: messages.append("%s has incorrect perms/ownership" % fileName) return changes, messages
def undo(self, option=None): messages = [] # old style change record - we know what *might* have been applied, so construct an undo record # old generic used a patch set, old redhat6 used simply 'added', suse used 'applied', so if option in ['added', 'applied'] or ( type(option)==type("") and option.startswith ("--- /etc")): # generate an default 'undo' set for any possible change we could have made change_set = self.generate_changes(is_undo=True) else: change_set = tcs_utils.string_to_dictionary(option) all_messages, changes = self.process_change_set(change_set, "undo") for level, text in all_messages: if level in ['ok']: self.logger.notice(self.module_name, text) messages.append(text) elif level in [ 'problem', 'fix']: self.logger.info(self.module_name, text) messages.append(text) elif level in ['error' ]: self.logger.error(self.module_name, text) messages.append(text) if changes == {}: retval = False changes = "" else: retval = True return retval, str(changes), {'messages':messages}
def undo_TBD(self, change_record=None): """Undo the previous action.""" messages = [] if change_record == 'none': #Ok, we need to create our remove data from whole cloth... change_set = {} ctm = [] ctm.append( {'search': 'remove usb-storage /sbin/modprobe -r usb-storage'}) change_set[self.__target_file] = ctm else: change_set = tcs_utils.string_to_dictionary(change_record) all_messages, changes = self.process_change_set(change_set, "undo") for level, text in all_messages: if level in ['ok']: self.logger.notice(self.module_name, text) messages.append(text) elif level in ['problem', 'fix']: self.logger.info(self.module_name, text) messages.append(text) elif level in ['error']: self.logger.error(self.module_name, text) messages.append(text) if changes == {}: retval = False changes = "" else: retval = True return retval, str(changes), {'messages': messages}
def undo(self, change_record): """Undo the previous action.""" if change_record[0:11].strip().startswith('['): # new style... change_record = tcs_utils.string_to_dictionary(change_record)[0] if change_record == []: change_record = None if not change_record: msg = "No previous value provided for %s; "\ "removing entry from %s" % (self.__param, self.__target_file) self.logger.info(self.module_name, 'Undo: ' + msg) results = sb_utils.os.config.unsetparam( param=self.__param, configfile=self.__target_file) else: results = sb_utils.os.config.setparam( param=self.__param, delim='=', value=change_record, configfile=self.__target_file) if results == False: msg = "Unable to restore %s in %s" % (self.__param, self.__target_file) self.logger.error(self.module_name, 'Undo Failed: ' + msg) return 0 msg = "Restored %s in %s" % (self.__param, self.__target_file) self.logger.notice(self.module_name, 'Undo Performed: ' + msg) return 1
def change_bulk_file_attributes(bulkchanges, options={'checkOnly':False, 'exactDACs': True}): revert = {} changeFileAttributes = ChangeFileAttributes(options) if type(bulkchanges) == type("string"): bulkchanges = tcs_utils.string_to_dictionary(bulkchanges) if type(bulkchanges) != type ({}): raise SyntaxError("%s - expected a string or dictionary as argument, got %s" % ("change_bulk_file_attributes", str(type(bulkchanges)))) for thisfile in bulkchanges: revert.update(changeFileAttributes.makeChanges(thisfile, bulkchanges[thisfile])) return revert
def undo(self, change_record=None): if not change_record.startswith('{'): msg = "Found oldstyle (pre4.1.1) change record - unable to perform undo due to potential conflicts with other modules" self.logger.error(self.module_name, 'Undo Error: ' + msg) raise tcs_utils.ActionError('%s %s' % (self.module_name, msg)) usersToUnlock = tcs_utils.string_to_dictionary(change_record) for userName in usersToUnlock['LockedUsers']: sb_utils.acctmgt.users.unlock(userName, doSysAccounts=True) return 1
def undo(self, change_record=None): results = False reason = "" messages = [] change_record = tcs_utils.string_to_dictionary(change_record) # Ugly, but iterate over *each* change so we could read/write each repo multiple times potentially for repoName, fileChanges in change_record.items(): for change in fileChanges: messages, undoChanges = self.checkRepoFile(repoName, 'undo', change[1], change[2], change[0]) if undoChanges: results = True return results, reason, {'messages':messages}
def undo(self, change_record=None): retval = True messages = {'messages': []} banner_status = True banner_changes = None banner_messages = {} script_status = True script_changes = None script_messages = {} conf_status = True conf_changes = None conf_messages = {} dt_status = True dt_changes = None dt_messages = {} # convert back from string to dictionary change_record = tcs_utils.string_to_dictionary(change_record) if change_record.has_key('banner'): banner_text = change_record['banner'] banner_status, banner_changes, banner_messages = self.set_banner_text( "Undo", self.banner_filename, banner_text) messages.update(banner_messages) if change_record.has_key('dt'): script_text = change_record['dt'] dt_status, dt_changes, dt_messages = self.set_script_text( "Undo", "Dtlogin", self.dt_script_filename, script_text) messages.update(banner_messages) if change_record.has_key('script'): script_text = change_record['script'] script_status, script_changes, script_messages = self.set_script_text( "Undo", "GDK/KDM", self.script_file, script_text) messages.update(script_messages) if change_record.has_key('conf'): invocation = change_record['conf'] conf_status, conf_changes, conf_messages = self.set_conf_settings( "Undo", self.script_conf_file, invocation) messages.update(conf_messages) if banner_status == False or script_status == False or conf_status == False or dt_status == False: retval = False return retval, '', {'messages': []}
def undo(self, change_record=None): messages = {} messages['messages'] = [] change_record = tcs_utils.string_to_dictionary(change_record) # we're counting on the fact that each line to remove should appear once at most allMessages = [] for fileName, changes in change_record.items(): allMessages.extend(self.undoFile(fileName, changes)) return True,'',{'messages':allMessages}
def undo(self, change_record): """ Re-enable the ctrl-alt-del key combination.""" messages = {'messages':[]} if change_record == 'added' : # oldstyle change record change_record = {'targetfile' : 'added'} else: try: change_record = tcs_utils.string_to_dictionary (change_record) except Exception, err: msg = "Unable to process change_record to perform undo: %s" % str(err) self.logger.error(self.module_name, 'Undo Error: '+ msg) raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))
def undo(self, change_record=None): """Undo the previous action.""" change_record = tcs_utils.string_to_dictionary(change_record) for configfile in change_record.keys(): param, val = change_record[configfile] if val: sb_utils.os.config.setparam(configfile=configfile, delim=' ', param=param, value=val) else: sb_utils.os.config.unsetparam(configfile=configfile, delim=' ', param=param) return True, '', {}
def undo(self, change_record=None): if not change_record or change_record == '': msg = "Unable to perform undo operation without change record." self.logger.error(self.module_name, 'Undo Error: ' + msg) raise tcs_utils.ActionError('%s %s' % (self.module_name, msg)) messages = {} messages['messages'] = [] changes_to_make = tcs_utils.string_to_dictionary(change_record) try: lines = open(self.__target_file).readlines() except Exception, err: msg = "Unable to process file %s: %s" % (self.__target_file, str(err)) raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))
def undo(self, change_record=None): if not change_record: msg = "Skipping Undo: No change record in state file." self.logger.notice(self.module_name, msg) return 1 # Old style change record was simply the permissions to restore, so if we only get a number as the change_record # treat it as such (with DECIMAL perms) and create the newstyle change record if not change_record[0:200].strip().startswith('{'): newperms = int(change_record, 10) change_record = {} change_record[self.__target_file] = {'dacs': newperms} else: change_record = tcs_utils.string_to_dictionary(change_record) return GenericPerms.undo(change_record=change_record)
def undo(self, change_record=None): change_record = tcs_utils.string_to_dictionary(change_record) messages = [] for key, val in change_record.iteritems(): oldParam = sb_utils.os.config.setparam(configfile=self.__config, delim='=', param=key, value=val) if change_record: # Set trigger file for /.autorelabel trigger file try: open("/.autorelabel", 'w+') except Exception, err: msg = "Unable to create/open trigger file '/.autorelabel' : %s" % str( err) messages.append(msg) self.logger.error(self.module_name, msg)
def undo(self, change_record=None): messages = {'messages': []} # if we have a newstyle change record (a dictionary) we can take the value of the 'oldline' key and then # use it as the change record itself, since we no longer allow for an 'empty' change record to be in the state file if change_record[0:100].strip().startswith('{'): change_record = tcs_utils.string_to_dictionary(change_record) change_record = change_record['oldline'] try: shutil.copy2('/etc/xinetd.d/tftp', '/tmp/.tftp.new') sb_utils.SELinux.restoreSecurityContext('/etc/xinetd.d/tftp') out_obj = open('/etc/xinetd.d/tftp', 'w') in_obj = open('/tmp/.tftp.new', 'r') except (OSError, IOError), err: msg = "Unable to create temp file: %s" % err self.logger.error(self.module_name, 'Undo Error: ' + msg) raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))
def undo(self, change_record=None): retval = True if not change_record or change_record == '': msg = "Unable to perform undo operation without change record." self.logger.error(self.module_name, 'Undo Error: ' + msg) raise tcs_utils.ActionError('%s %s' % (self.module_name, msg)) messages = {} messages['messages'] = [] changes_to_make = tcs_utils.string_to_dictionary(change_record) if changes_to_make == ['newfile']: fix_count = len(changes_to_make) os.unlink(self.__target_file) msg = "Removed %s file" % self.__target_file else: try: lines = open(self.__target_file).readlines() except Exception, err: msg = "Unable to process file %s: %s" % (self.__target_file, str(err)) raise tcs_utils.ActionError('%s %s' % (self.module_name, msg)) results, change_record, lines = self.process_file( lines, changes_to_make, True) fix_count = 0 for msg in results: if msg[0] in ['fix']: fix_count = fix_count + 1 self.logger.notice(self.module_name, msg[1]) messages['messages'].append(msg[1]) if fix_count != len(changes_to_make): retval = False msg = "Unable to revert all changes to %s, no changes will be made" % self.__target_file raise tcs_utils.ActionError('%s %s' % (self.module_name, msg)) else: retval = True open(self.__target_file, "w").writelines(lines)
def restoreSysAcct(change_record=None): logger = TCSLogger.TCSLogger.getInstance() if type(change_record) == type({}): # print change_record.keys() accountData = change_record else: msg = "Converting string to dictionary..." logger.log_info('sb_utils.acctmgt.acctfiles.restoreSysAcct', msg) try: accountData = tcs_utils.string_to_dictionary(change_record) except SyntaxError: accountData = _change_old_restore_to_new_restore(change_record) try: accountInfo = accountData['acctinfo'] filelist = accountData['filelist'] except KeyError, err: msg = "Unable to process restore dictionary: %s" % (err) logger.log_err('sb_utils.acctmgt.acctfiles.restoreSysAcct', msg) return False
def undo(self, change_record=None): """Disable account locking after 3 unsuccessful login attempts.""" # we're not calling scan directly self._init_fields() if not change_record: msg = "Unable to perform undo operation without change record." self.logger.error(self.module_name, 'Undo Error: ' + msg) raise tcs_utils.ActionError('%s %s' % (self.module_name, msg)) changes = {} if change_record != 'added': try: changes = tcs_utils.string_to_dictionary(change_record) try: changes = changes['files'] except KeyError: changes = {'/etc/pam.d/system-auth': changes} except Exception, err: msg = "Unable to process change_record to perform undo.\n%s" % err self.logger.error(self.module_name, 'Undo Error: ' + msg) raise tcs_utils.ActionError('%s %s' % (self.module_name, msg))
def undo(self, change_record=None): """Undo the previous action.""" retval = False change_record = tcs_utils.string_to_dictionary(change_record) allChanges = {} allMessages = [] for fileName, changesToUndo in change_record.items(): changes, messages = self.checkFile('undo', fileName, changesToUndo) allChanges.update(changes) allMessages.extend(messages) if allChanges: msg = "Undo Performed" self.logger.notice(self.module_name, 'Undo Performed: ' + msg) retval = True else: msg = "No changes were reverted" self.logger.error(self.module_name, 'Undo Performed: ' + msg) retval = False return retval, msg, {'messages': allMessages}
def undo(self, change_record=None): retval = False msg = "" messages = {} messages['messages'] = [] if not change_record: msg = 'Unable to undo without valid change record' self.logger.error(self.module_name, 'Undo Error: ' + msg) return False, msg, {'messages': ["Error: %s" % msg]} changeDict = tcs_utils.string_to_dictionary(change_record) self._grubHandler = sb_utils.os.grub.GrubHandler() try: self._grubHandler.readGrub() numDefs = self._grubHandler.numBootDefs() if numDefs > 1: msg = "%s : found %d boot definitions, expected only a single definition" % ( self.module_name, numDefs) messages['messages'].append(msg) self.logger.warning(self.module_name, msg) for section in changeDict.keys(): for tag, data in changeDict[section].items(): rec, msgs = self._grubHandler.addToLines( section, tag, data) messages['messages'].extend(msgs) msg = "Kernel boot lines restored" self.logger.notice(self.module_name, 'Undo Performed: ' + msg) # writeGrub raises an exception on error self._grubHandler.writeGrub() retval = True except tcs_utils.OSNotApplicable, err: msg = "%s" % str(err) self.logger.info(self.module_name, msg) messages['messages'].append(msg)
# note - oldstyle changes records were patches, so try to split out any patches *first*. Anything after that we need to process as a stringified dictionary patches, changeString = tcs_utils.split_patches(change_record) if patches: # Ok, found at least one patch, pass the whole change record through to the legacy patch apply stuff, it will quietly drop anything at the end try: tcs_utils.apply_patch(change_record) except tcs_utils.ActionError, err: msg = "Unable to undo previous changes (%s)." % err self.logger.error(self.module_name+'.undoCfg', 'Undo Error: ' + msg) raise tcs_utils.ActionError('%s %s' % (self.module_name+'.undoCfg', msg)) # anything else/left should be convert into a dictionary and procesed if changeString: changeDict = tcs_utils.string_to_dictionary(changeString) for section, param, value in changeDict: junk = self.setparam(configfile=self.configfile, param = param, value = value, hostSection=section) self.logger.notice(self.module_name+'.undoCfg', 'Undo Performed ') return True,'',{} def _splitRestrictions(self, restrictions, prefix="", suffix=""): allowedOptions = [] deniedOptions = [] allowedPattern = "" deniedPattern = "" if restrictions: for opt in restrictions: if opt.startswith("!"):
# oldstyle change record is a simple patchset, and we have no history on the original permissions, so # don't alter them, but we do need to revert the patch the oldway. if not change_record.startswith('{'): msg = "Detected oldstyle change record" self.logger.info(self.module_name, msg) try: tcs_utils.apply_patch(change_record) allChanges = "{}" except tcs_utils.ActionError, err: msg = "Unable to undo previous changes (%s)." % err self.logger.error(self.module_name, 'Undo Error: ' + msg) raise tcs_utils.ActionError('%s %s' % (self.module_name, msg)) else: change_record = tcs_utils.string_to_dictionary(change_record) for fileName, changesToUndo in change_record.items(): changes, messages = self.checkSecuretty( 'undo', fileName, changesToUndo) allChanges.update(changes) allMessages.extend(messages) if allChanges: msg = "Undo Performed" self.logger.notice(self.module_name, 'Undo Performed: ' + msg) retval = True else: msg = "No changes were reverted" self.logger.error(self.module_name, 'Undo Performed: ' + msg) retval = False