def fixLockdownX(self): success = True if self.sh.disableService("xfs", _="_"): self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "servicehelper", "servicename": "xfs", "startstate": "enabled", "endstate": "disabled"} self.statechglogger.recordchgevent(myid, event) else: success = False self.detailedresults += "STONIX was unable to disable the " + \ "xfs service\n" if not self.xservSecure: serverrcString = "exec X :0 -nolisten tcp $@" if not os.path.exists(self.serverrc): createFile(self.serverrc, self.logger) self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "creation", "filepath": self.serverrc} self.statechglogger.recordchgevent(myid, event) writeFile(self.serverrc, serverrcString, self.logger) else: open(self.serverrc, "a").write(serverrcString) return success
def fixFreebsd(self): if not checkPerms(self.path, [0, 0, 0o644], self.logger): self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) if not setPerms(self.path, [0, 0, 0o644], self.logger, self.statechglogger, myid): return False if self.networkTuning1.getcurrvalue() or \ self.networkTuning2.getcurrvalue(): if self.editor.fixables: self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) self.editor.setEventID(myid) if not self.editor.fix(): return False elif not self.editor.commit(): return False os.chown(self.path, 0, 0) os.chmod(self.path, 0o644) resetsecon(self.path) cmd = ["/usr/sbin/service", "sysctl", "restart"] self.ch.executeCommand(cmd) if self.ch.getReturnCode() != 0: self.detailedresults = "Unable to restart sysctl\n" self.logger.log(LogPriority.DEBUG, self.detailedresults) return False else: return True else: return True
def fixsolaris(self): '''because solaris has to be different @author bemalmbe ''' if not checkPerms(self.editor.getPath(), [0, 3, 420], self.logger): self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) if not setPerms(self.editor.getPath(), [0, 3, 420], self.logger, self.statechglogger, myid): self.rulesuccess = False if self.editor.fixables or self.editor.removeables: self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) self.editor.setEventID(myid) if not self.editor.fix(): self.detailedresults += "Unable to run fix for kveditor\n" self.rulesuccess = False return False elif not self.editor.commit(): self.detailedresults += "Unable to run commit for kveditor\n" self.rulesuccess = False return False return True
def setaccountlockout(self, regex): """ configure the account lockout time in pam :param regex: string; regular expression :return: success :rtype: bool """ success = True pamfiles = [] if self.ph.manager in ("yum", "dnf"): pamfiles.append(self.pamauthfile) pamfiles.append(self.pampassfile) writecontents = self.auth + "\n" + self.acct + "\n" + \ self.password + "\n" + self.session else: pamfiles.append(self.pamauthfile) writecontents = self.auth for pamfile in pamfiles: if not os.path.exists(pamfile): self.detailedresults += pamfile + " doesn't exist.\n" + \ "Stonix will not attempt to create this file " + \ "and the fix for the this rule will not continue\n" return False # """Check permissions on pam file(s)""" for pamfile in pamfiles: if not checkPerms(pamfile, [0, 0, 0o644], self.logger): self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) if not setPerms(pamfile, [0, 0, 0o644], self.logger, self.statechglogger, myid): success = False self.detailedresults += "Unable to set " + \ "correct permissions on " + pamfile + "\n" contents = readFile(pamfile, self.logger) found = False for line in contents: if re.search(regex, line.strip()): found = True if not found: tmpfile = pamfile + ".stonixtmp" if writeFile(tmpfile, writecontents, self.logger): self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {'eventtype': 'conf', 'filepath': pamfile} self.statechglogger.recordchgevent(myid, event) self.statechglogger.recordfilechange(pamfile, tmpfile, myid) os.rename(tmpfile, pamfile) os.chown(pamfile, 0, 0) os.chmod(pamfile, 0o644) resetsecon(pamfile) else: self.detailedresults += "Unable to write to " + pamfile + "\n" success = False return success
def correctFile(self, kfile, user): '''separate method to find the correct contents of each file passed in as a parameter. @author: dwalker :param filehandle: string :param kfile: :param user: :returns: bool ''' created = False success = True self.editor = "" debug = "" if not os.path.exists(kfile): if not createFile(kfile, self.logger): self.detailedresults += "Unable to create " + kfile + \ " file for the user\n" self.logger.log(LogPriority.DEBUG, self.detailedresults) return False created = True if self.environ.geteuid() == 0: self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "creation", "filepath": kfile} self.statechglogger.recordchgevent(myid, event) if not self.searchFile(kfile): if self.editor.fixables: if self.environ.geteuid() == 0 and not created: self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) self.editor.setEventID(myid) if not self.editor.fix(): debug = "Kveditor fix is failing for file " + \ kfile + "\n" self.logger.log(LogPriority.DEBUG, debug) self.detailedresults += "Unable to correct contents for " + \ kfile + "\n" return False elif not self.editor.commit(): debug = "Kveditor commit is failing for file " + \ kfile + "\n" self.logger.log(LogPriority.DEBUG, debug) self.detailedresults += "Unable to correct contents for " + \ kfile + "\n" return False uid = getpwnam(user)[2] gid = getpwnam(user)[3] os.chmod(kfile, 0o600) os.chown(kfile, uid, gid) resetsecon(kfile) return success
def fix(self): try: if not self.ci.getcurrvalue(): return results = "" success = True # Clear out event history so only the latest fix is recorded self.iditerator = 0 eventlist = self.statechglogger.findrulechanges(self.rulenumber) for event in eventlist: self.statechglogger.deleteentry(event) if os.path.exists(self.path): if not checkPerms(self.path, [0, 0, 0o644], self.logger): self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) if not setPerms(self.path, [0, 0, 0o644], self.logger, self.statechglogger, myid): success = False results += "Could not set permissions on " + \ self.path + "\n" if self.editor.fixables or self.editor.removeables: self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) self.editor.setEventID(myid) if not self.editor.fix(): debug = "kveditor fix did not run successfully\n" self.logger.log(LogPriority.DEBUG, debug) success = False elif not self.editor.commit(): debug = "kveditor commit did not run successfully\n" self.logger.log(LogPriority.DEBUG, debug) success = False os.chown(self.path, 0, 0) os.chmod(self.path, 0o644) resetsecon(self.path) else: success = False results += "Could not find path to sshd_config\n" self.detailedresults = results self.rulesuccess = success except (KeyboardInterrupt, SystemExit): # User initiated exit raise except Exception: self.rulesuccess = False success = False self.detailedresults += "\n" + traceback.format_exc() self.logdispatch.log(LogPriority.ERROR, self.detailedresults) self.formatDetailedResults("fix", success, self.detailedresults) self.logdispatch.log(LogPriority.INFO, self.detailedresults) return self.rulesuccess
def afterfix(self): '''restart the service after fix :returns: afterfixsuccessful :rtype: bool @author: ekkehard j. koch @change: Breen Malmberg - 12/20/2016 - added doc string; var init before try @change: ekkehard - 2017/10/04 - temporary launchctl fix ''' afterfixsuccessful = True try: # TODO: This code needs to be fixed after implementation [artf39626]: ServiceHelper Enhancement # FIXME: SystemHelper version 2 [artf39626]: ServiceHelper Enhancement # service = "/System/Library/LaunchDaemons/com.apple.blued.plist" servicename = "system/com.apple.blued" # if afterfixsuccessful: # afterfixsuccessful = self.sh.auditservice(service, servicename) # if afterfixsuccessful: # afterfixsuccessful = self.sh.disableservice(service, servicename) # if afterfixsuccessful: # afterfixsuccessful = self.sh.enableservice(service, servicename) if afterfixsuccessful: command = ["/bin/launchctl", "stop", servicename] afterfixsuccessful = self.ch.executeCommand(command) if afterfixsuccessful: command = ["/bin/launchctl", "disable", servicename] afterfixsuccessful = self.ch.executeCommand(command) if afterfixsuccessful: self.iditerator = +1 myID = iterate(self.iditerator, self.rulenumber) command = ["/bin/launchctl", "enable", servicename] event = {"eventtype": "comm", "command": command} self.statechglogger.recordchgevent(myID, event) self.iditerator = +1 myID = iterate(self.iditerator, self.rulenumber) command = ["/bin/launchctl", "start", servicename] event = {"eventtype": "comm", "command": command} self.statechglogger.recordchgevent(myID, event) except (KeyboardInterrupt, SystemExit): raise except Exception as err: self.rulesuccess = False afterfixsuccessful = False messagestring = str(err) + " - " + str(traceback.format_exc()) self.resultAppend(messagestring) self.logdispatch.log(LogPriority.ERROR, self.detailedresults) return afterfixsuccessful
def setpwquality(self): """ :return: """ success = True created = False pwqfile = "/etc/security/pwquality.conf" if not os.path.exists(pwqfile): createFile(pwqfile, self.logger) self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {'eventtype': 'creation', 'filepath': pwqfile} self.statechglogger.recordchgevent(myid, event) created = True tmpfile = pwqfile + ".stonixtmp" if self.environ.getsystemfismacat() == "high": data = {"difok": "7", "minlen": "14", "dcredit": "0", "ucredit": "0", "lcredit": "0", "ocredit": "0", "maxrepeat": "3", "minclass": "4"} else: data = {"difok": "7", "minlen": "8", "dcredit": "0", "ucredit": "0", "lcredit": "0", "ocredit": "0", "maxrepeat": "3", "minclass": "3"} self.pwqeditor = KVEditorStonix(self.statechglogger, self.logger, "conf", pwqfile, tmpfile, data, "present", "openeq") self.pwqeditor.report() if self.pwqeditor.fixables: if self.pwqeditor.fix(): if not created: self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) self.pwqeditor.setEventID(myid) if not self.pwqeditor.commit(): success = False self.detailedresults += "Unable to correct " + pwqfile + "\n" else: success = False self.detailedresults += "Unable to correct " + pwqfile + "\n" return success
def fix(self): """ set the value of schema thumbnailers disable-all to true and create the thumbnailers lock file if it doesn't exist :return: self.rulesuccess :rtype: bool """ self.rulesuccess = True self.detailedresults = "" self.iditerator = 0 try: if self.ci.getcurrvalue(): # This portion of the code is run in user context if self.environ.geteuid() != 0: if not self.setValue(): self.rulesuccess = False else: self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "commandstring", "command": re.sub("true", "false", self.setcmd)} self.statechglogger.recordchgevent(myid, event) # This portion of the code has to be run in root context else: if not self.setLockFile(): self.rulesuccess = False if os.path.exists(self.dconf): self.ch.executeCommand(self.updatecmd) if self.ch.getReturnCode() == 0: self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "commandstring", "command": self.updatecmd} self.statechglogger.recordchgevent(myid, event) else: self.logger.log(LogPriority.DEBUG, "CI not enabled. Fix was not performed.") except (KeyboardInterrupt, SystemExit): raise except Exception: self.rulesuccess = False self.detailedresults += "\n" + traceback.format_exc() self.logger.log(LogPriority.ERROR, self.detailedresults) self.formatDetailedResults("fix", self.rulesuccess, self.detailedresults) self.logger.log(LogPriority.INFO, self.detailedresults) return self.rulesuccess
def fixSelinux(self): """ :return: """ success = True self.iditerator = 0 activate_utility = "/usr/sbin/selinux-activate" # install selinux package if it is not installed if not self.ph.check(self.mac_package): if not self.ph.install(self.mac_package): success = False self.detailedresults += "\nFailed to install selinux package" else: # if we just installed selinux, then we need to discover the correct conf path self.set_selinux_conf_path() self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype":"pkghelper", "pkgname":self.mac_package} self.statechglogger.recordchgevent(myid, event) if os.path.exists(activate_utility): self.ch.executeCommand(activate_utility) output = self.ch.getOutputString() if re.search("need to reboot", output, re.I): self.detailedresults += "\nSElinux has been configured, but you will need to reboot before selinux can become active. This rule will not report compliant until this is done." # set enforcement mode for selinux self.ch.executeCommand("/usr/sbin/setenforce " + self.mode) retcode = self.ch.getReturnCode() if retcode != 0: success = False self.detailedresults += "\nFailed to set selinux mode to: " + self.mode self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) self.selinux_config_editor.setEventID(myid) # configure the selinux config file for persistence through reboot if not self.selinux_config_editor.fix(): success = False self.detailedresults += "\nFailed to fix " + self.selinux_config_file elif not self.selinux_config_editor.commit(): success = False self.detailedresults += "\nFailed to fix " + self.selinux_config_file return success
def fixShadow(self): success = True if not os.path.exists(self.shadowfile): self.detailedresults += self.shadowfile + "does not exist. \ Will not perform fix on shadow file\n" return False if self.fixusers: contents = readFile(self.shadowfile, self.logger) if self.ph.manager == "apt-get": perms = [0, 42, 0o640] else: perms = [0, 0, 0o400] if not checkPerms(self.shadowfile, perms, self.logger) and \ not checkPerms(self.shadowfile, [0, 0, 0], self.logger): self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) setPerms(self.shadowfile, perms, self.logger, self.statechglogger, myid) tmpdate = strftime("%Y%m%d") tmpdate = list(tmpdate) date = tmpdate[0] + tmpdate[1] + tmpdate[2] + tmpdate[3] + "-" + \ tmpdate[4] + tmpdate[5] + "-" + tmpdate[6] + tmpdate[7] for user in self.fixusers: cmd = ["chage", "-d", date, "-m", "1", "-M", "180", "-W", "28", "-I", "35", user] self.ch.executeCommand(cmd) # We have to do some gymnastics here, because chage writes directly # to /etc/shadow, but statechglogger expects the new contents to # be in a temp file. newContents = readFile(self.shadowfile, self.logger) shadowTmp = "/tmp/shadow.stonixtmp" createFile(shadowTmp, self.logger) writeFile(shadowTmp, "".join(newContents) + "\n", self.logger) writeFile(self.shadowfile, "".join(contents) + "\n", self.logger) self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {'eventtype': 'conf', 'filepath': self.shadowfile} self.statechglogger.recordchgevent(myid, event) self.statechglogger.recordfilechange(self.shadowfile, shadowTmp, myid) shutil.move(shadowTmp, self.shadowfile) os.chmod(self.shadowfile, perms[2]) os.chown(self.shadowfile, perms[0], perms[1]) resetsecon(self.shadowfile) return success
def secure_remote_ae(self): ''' ''' retval = True desired_remote_ae_users = self.getUUIDs( self.secureremoteevents.getcurrvalue()) securecmd = "/usr/bin/dscl . create /Groups/com.apple.access_remote_ae GroupMembers " + " ".join( desired_remote_ae_users) original_remote_ae_users = self.getRemoteAEUsers() if original_remote_ae_users: undocmd = "/usr/bin/dscl . create /Groups/com.apple.access_remote_ae GroupMembers " + " ".join( original_remote_ae_users) else: undocmd = "/usr/bin/dscl . delete /Groups/com.apple.access_remote_ae GroupMembers" self.cmhelper.executeCommand(securecmd) retcode = self.cmhelper.getReturnCode() if retcode == 0: self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "commandstring", "command": undocmd} self.statechglogger.recordchgevent(myid, event) else: retval = False self.detailedresults += "\nFailed to properly configure the desired remote apple events users" # we assume the user wants to use the service if they configure the user list for it # and turn off the disable events CI if not self.disableremoteevents.getcurrvalue(): undo_enable_remote_ae_cmd = "/usr/sbin/systemsetup setremoteappleevents off" enable_remote_ae_cmd = "/usr/sbin/systemsetup setremoteappleevents on" self.cmhelper.executeCommand(enable_remote_ae_cmd) retcode = self.cmhelper.getReturnCode() if retcode != 0: retval = False self.detailedresults += "\nFailed to enable remote apple events service" else: self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = { "eventtype": "commandstring", "command": undo_enable_remote_ae_cmd } self.statechglogger.recordchgevent(myid, event) return retval
def fixcommon(self): '''run fix functionlity which is common to all platforms :returns: success :rtype: boolean @author: Breen Malmberg ''' success = True if self.commoneditor.fixables: self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) self.commoneditor.setEventID(myid) if not self.commoneditor.fix(): debug = self.sshdfile + " editor fix is returning false\n" self.logger.log(LogPriority.DEBUG, debug) success = False elif not self.commoneditor.commit(): debug = self.sshdfile + " editor commit is returning false\n" self.logger.log(LogPriority.DEBUG, debug) success = False if not success: self.detailedresults += "Unable to correct contents of " + \ self.sshdfile + "\n" return success
def fix(self): try: if not self.ci.getcurrvalue(): return if os.path.exists(self.profile): success = True self.detailedresults = "" self.iditerator = 0 eventlist = self.statechglogger.findrulechanges( self.rulenumber) for event in eventlist: self.statechglogger.deleteentry(event) cmd = ["/usr/bin/profiles", "-I", "-F", self.profile] if not self.ch.executeCommand(cmd): success = False else: self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) cmd = ["/usr/bin/profiles", "-R", "-p", self.identifier] event = {"eventtype": "comm", "command": cmd} self.statechglogger.recordchgevent(myid, event) else: success = False self.rulesuccess = success except (KeyboardInterrupt, SystemExit): raise except Exception: self.rulesuccess = False self.detailedresults += "\n" + 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
def fixUbuntu(self): '''if debian, disable unity-lens-shopping and unity-webapps-common cloud service packages, if they are installed ''' # defaults self.iditerator = 0 try: for package in self.debianpkglist: if self.ph.check(package): self.ph.remove(package) cmd = self.ph.getInstall() + package event = {'eventtype': 'commandstring', 'command': cmd} self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) self.statechglogger.recordchgevent(myid, event) except (KeyboardInterrupt, SystemExit): raise except Exception as err: self.rulesuccess = False self.detailedresults += "\n" + str(err) + 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
def setLockFile(self): """ create the lock file for disable thumbnailers (if running in root context) :return: success - True if file is created; False if not :rtype: bool """ success = True if not os.path.isdir("/etc/dconf/db/local.d/locks"): try: os.makedirs("/etc/dconf/db/local.d/locks", 0o755) except Exception: pass try: if not self.lock_editor.fix(): self.detailedresults += "\nFailed to lock thumbnailers setting" success = False elif not self.lock_editor.commit(): self.detailedresults += "\nFailed to lock thumbnailers setting" success = False except Exception: success = False if success: self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "conf", "filepath": self.lockfile} self.statechglogger.recordchgevent(myid, event) return success
def fix_aide_installed(self): """ :return: success :rtype: bool """ success = True self.logger.log(LogPriority.DEBUG, "Installing aide package") if not self.ph.install(self.aide_package): success = False self.logger.log(LogPriority.DEBUG, "Failed to install aide package") if not self.ph.checkAvailable(self.aide_package): self.logger.log(LogPriority.DEBUG, "aide package not available on this system") else: self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = { "eventtype": "pkghelper", "pkgname": self.aide_package, "startstate": "removed", "endstate": "installed" } self.statechglogger.recordchgevent(myid, event) self.set_aide_paths() self.set_aide_cron_job() self.report_aide_conf() self.report_aide_cronjob() return success
def fix_aide_cronjob(self): """ :return: success :rtype: bool """ success = True self.logger.log(LogPriority.DEBUG, "Creating aide cron job") try: f = open(self.aide_cron_file, "w") f.write(self.aide_cron_job) f.close() self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "creation", "filepath": self.aide_cron_file} self.statechglogger.recordchgevent(myid, event) except: success = False self.logger.log(LogPriority.DEBUG, "Failed to create aide cron job") return success
def fixLogDef(self, specs): success = True debug = "" if not os.path.exists(self.logdeffile): if createFile(self.logdeffile, self.logger): self.logindefcreate = True setPerms(self.logdeffile, [0, 0, 0o644], self.logger) tmpfile = self.logdeffile + ".tmp" self.editor1 = KVEditorStonix(self.statechglogger, self.logger, "conf", self.logdeffile, tmpfile, specs, "present", "space") else: self.detailedresults += "Was not able to create " + \ self.logdeffile + " file\n" success = False if self.logindefcreate: self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "creation", "filepath": self.logdeffile} self.statechglogger.recordchgevent(myid, event) elif not checkPerms(self.logdeffile, [0, 0, 0o644], self.logger): self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) if not setPerms(self.logdeffile, [0, 0, 0o644], self.logger, self.statechglogger, myid): debug += "permissions not correct on: " + \ self.logdeffile + "\n" success = False if self.editor1.fixables or self.editor1.removeables: if not self.logindefcreate: self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) self.editor1.setEventID(myid) if not self.editor1.fix(): debug += "fixLogDef editor.fix did not complete successfully\n" success = False elif not self.editor1.commit(): debug += "fixLogDef editor.commit did not complete successfully\n" success = False os.chown(self.logdeffile, 0, 0) os.chmod(self.logdeffile, 0o644) resetsecon(self.logdeffile) if debug: self.logger.log(LogPriority.DEBUG, debug) return success
def fix(self): try: if not self.ci.getcurrvalue(): return success = True self.detailedresults = "" #clear out event history so only the latest fix is recorded self.iditerator = 0 eventlist = self.statechglogger.findrulechanges(self.rulenumber) for event in eventlist: self.statechglogger.deleteentry(event) cmd = ["/bin/launchctl", "disable", "system/com.apple.ftpd"] self.ch.executeCommand(cmd) cmd = ["/bin/launchctl", "unload", "/System/Library/LaunchDaemons/ftp.plist"] if not self.ch.executeCommand(cmd): success = False else: self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) cmd = ["/bin/launchctl", "enable", "system/com.apple.ftpd"] event = {"eventtype": "comm", "command": cmd} self.statechglogger.recordchgevent(myid, event) self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) cmd = ["/bin/launchctl", "load", "-w", "/System/Library/LaunchDaemons/ftp.plist"] event = {"eventtype": "comm", "command": cmd} self.statechglogger.recordchgevent(myid, event) self.rulesuccess = success 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("fix", success, self.detailedresults) self.logdispatch.log(LogPriority.INFO, self.detailedresults) return self.rulesuccess
def appendLine(self, appendValue, targetFile, ownership, perms): '''private method for appending a line (appendValue) to a file (targetFile) :param appendValue: str string to append to the targetFile :param targetFile: str name of the file to append appendValue to :param ownership: list 2-element list containing: [uid, gid] :param perms: int 4-digit integer representing the octal format of file permissions @author: bemalmbe ''' # defaults tempfile = targetFile + '.stonixtmp' self.detailedresults = '' try: if not isinstance(ownership, list): self.detailedresults += '\nownership argument for appendLine must be of type: list' if len(ownership) != 2: self.detailedresults += '\nownership argument for appendLine must be size 2' if not isinstance(perms, int): self.detailedresults += '\nperms argument for appendLine must be an integer' if len(str(perms)) != 4: self.detailedresults += '\nperms argument for appendLine must be in octal format (4 digits)' if self.detailedresults != '': self.logger.log(LogPriority.DEBUG, self.detailedresults) f = open(targetFile, 'r') contentlines = f.readlines() f.close() contentlines.append('\n# This line added by STONIX') contentlines.append(appendValue) tf = open(tempfile, 'w') tf.writelines(contentlines) tf.close() event = {'eventtype': 'conf', 'filepath': targetFile} self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) self.statechglogger.recordchgevent(myid, event) self.statechglogger.recordfilechange(targetFile, tempfile, myid) os.rename(tempfile, targetFile) os.chmod(targetFile, perms) os.chown(targetFile, ownership[0], ownership[1]) except (KeyboardInterrupt, SystemExit): raise except Exception: self.detailedresults += traceback.format_exc() self.logger.log(LogPriority.ERROR, self.detailedresults)
def fix(self): """The fix method will apply the required settings to the system. self.rulesuccess will be updated if the rule does not succeed. :return: self.rulesuccess - boolean; True if fix succeeds, False if not """ self.detailedresults = "" self.rulesuccess = True path = "/etc/passwd" tmppath = path + ".stonixtmp" self.iditerator = 0 newcontentlines = [] try: if not self.ci.getcurrvalue(): return self.rulesuccess f = open(path, "r") contentlines = f.readlines() f.close() for line in contentlines: sline = line.split(":") if sline[0] in self.corrections_needed: sline[6] = "/sbin/nologin\n" line = ":".join(sline) newcontentlines.append(line) tf = open(tmppath, "w") tf.writelines(newcontentlines) self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {'eventtype': 'conf', 'filepath': path} self.statechglogger.recordchgevent(myid, event) self.statechglogger.recordfilechange(path, tmppath, myid) os.rename(tmppath, path) os.chown(path, 0, 0) os.chmod(path, 420) resetsecon(path) except (KeyboardInterrupt, SystemExit): raise except Exception: self.rulesuccess = False self.detailedresults = traceback.format_exc() self.logger.log(LogPriority.ERROR, self.detailedresults) self.formatDetailedResults("fix", self.rulesuccess, self.detailedresults) self.logdispatch.log(LogPriority.INFO, self.detailedresults) return self.rulesuccess
def fix(self): '''Remove any data-collection and reporting utilities from the system report success status as True if all are removed report success status as False if any remain :returns: self.rulesuccess :rtype: bool @author: Breen Malmberg ''' self.detailedresults = "" self.rulesuccess = True self.iditerator = 0 try: if self.enabledCI.getcurrvalue(): eventlist = self.statechglogger.findrulechanges( self.rulenumber) for event in eventlist: self.statechglogger.deleteentry(event) for pkg in self.removepkgs: if not self.ph.remove(pkg): self.detailedresults += "\nUnable to remove package: " + str( pkg) self.rulesuccess = False else: self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) comm = self.ph.getRemove() + pkg event = {"eventtype": "commandstring", "command": comm} self.statechglogger.recordchgevent(myid, event) self.logger.log(LogPriority.DEBUG, "Removing package: " + str(pkg)) else: self.logger.log(LogPriority.DEBUG, "Rule was NOT enabled. Nothing was done.") except (KeyboardInterrupt, SystemExit): raise except Exception: self.rulesuccess = False self.detailedresults += "\n" + 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
def fix(self): '''set the sudo timeout to a pre-defined appropriate value @author Breen Malmberg ''' self.detailedresults = "" self.rulesuccess = True self.iditerator = 0 changed = False tempfile = self.sudofile + ".stonixtmp" self.fixsudotimeout = "Defaults timestamp_timeout=" + self.timeouttime + "\n" try: if self.ci.getcurrvalue(): f = open(self.sudofile, 'r') contents = f.readlines() f.close() for line in contents: if re.search("^Defaults\s+env_reset", line): contents.insert((contents.index(line) + 1), self.fixsudotimeout) changed = True if changed: tf = open(tempfile, 'w') tf.writelines(contents) tf.close() self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "conf", "filepath": self.sudofile} self.statechglogger.recordchgevent(myid, event) self.statechglogger.recordfilechange(self.sudofile, tempfile, myid) os.rename(tempfile, self.sudofile) os.chown(self.sudofile, 0, 0) os.chmod(self.sudofile, 0o440) resetsecon(self.sudofile) self.logger.log(LogPriority.DEBUG, "Added the configuration setting to " + str(self.sudofile)) else: self.detailedresults += "\nRule was not enabled. Nothing was done." self.logger.log(LogPriority.DEBUG, "Rule was not enabled. Nothing was done.") except (KeyboardInterrupt, SystemExit): raise except Exception: self.rulesuccess = False self.detailedresults += "\n" + 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
def fix(self): '''Perform operations to disable web sharing :returns: self.rulesuccess :rtype: bool @author: Breen Malmberg ''' # defaults self.detailedresults = '' self.rulesuccess = True self.id = 0 try: if self.disableWebSharing.getcurrvalue(): #if not self.cmhelper.executeCommand('defaults write /System/Library/LaunchDaemons/org.apache.httpd Disabled -bool true'): # self.rulesuccess = False if not self.svchelper.disableService( self.maclongname, servicename=self.macshortname): self.rulesuccess = False self.logger.log( LogPriority.DEBUG, "Failed to disable service: " + str(self.maclongname)) else: self.id += 1 myid = iterate(self.id, self.rulenumber) event = { 'eventtype': 'commandstring', 'command': 'defaults delete /System/Library/LaunchDaemons/org.apache.httpd Disabled' } self.statechglogger.recordchgevent(myid, event) else: self.detailedresults += '\nRule was not enabled, so nothing was done.' except (KeyboardInterrupt, SystemExit): raise except Exception as err: self.rulesuccess = False self.detailedresults += "\n" + \ str(err) + " - " + str(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
def setlogindefs(self): """ configure login.defs options :return: success :rtype: bool """ success = True if not checkPerms(self.logindefs, [0, 0, 0o644], self.logger): self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) if not setPerms(self.logindefs, [0, 0, 0o644], self.logger, self.statechglogger, myid): self.detailedresults += "Unable to set permissions on " + self.logindefs + " file\n" success = False if self.editor2: if self.editor2.fixables: self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) self.editor2.setEventID(myid) if self.editor2.fix(): if self.editor2.commit(): debug = "/etc/login.defs file has been corrected\n" self.logger.log(LogPriority.DEBUG, debug) os.chown(self.logindefs, 0, 0) os.chmod(self.logindefs, 0o644) resetsecon(self.logindefs) else: debug = "Unable to correct the contents of /etc/login.defs\n" self.detailedresults += "Unable to correct the contents of /etc/login.defs\n" self.logger.log(LogPriority.DEBUG, debug) success = False else: self.detailedresults += "Unable to correct the contents of /etc/login.defs\n" debug = "Unable to correct the contents of /etc/login.defs\n" self.logger.log(LogPriority.DEBUG, debug) success = False return success
def fix(self): '''run kextunload on the AppleCameraInterface driver to unload it and disable the iSight camera. return True if the command succeeds. return False if the command fails. :returns: success :rtype: bool @author: Breen Malmberg @change: dwalker - ??? - ??? @change: Breen Malmberg - 1/19/2017 - minor doc string edit; minor refactor @change: dwalker 10/3/2017 updated to check for a profile value ''' try: success = True self.detailedresults = "" # only run the fix actions if the CI has been enabled if not self.ci.getcurrvalue(): self.detailedresults += "Configuration item was not enabled\n" self.rulesuccess = False self.formatDetailedResults("report", self.rulesuccess, self.detailedresults) self.logdispatch.log(LogPriority.INFO, self.detailedresults) return self.rulesuccess self.iditerator = 0 eventlist = self.statechglogger.findrulechanges(self.rulenumber) for event in eventlist: self.statechglogger.deleteentry(event) if not self.cameditor.report(): if self.cameditor.fix(): self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) self.cameditor.setEventID(myid) if not self.cameditor.commit(): success = False self.detailedresults += "Unable to install profile\n" self.logdispatch.log(LogPriority.DEBUG, "Kveditor commit failed") else: success = False self.detailedresults += "Unable to install profile\n" self.logdispatch.log(LogPriority.DEBUG, "Kveditor fix failed") else: self.detailedresults += "Camera disablement profile was already installed.\n" self.rulesuccess = success 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("fix", success, self.detailedresults) self.logdispatch.log(LogPriority.INFO, self.detailedresults) return self.rulesuccess
def fix(self): try: if not self.ci.getcurrvalue(): return success = True self.detailedresults = "" self.iditerator = 0 eventlist = self.statechglogger.findrulechanges(self.rulenumber) for event in eventlist: self.statechglogger.deleteentry(event) if os.path.exists(self.path): sttyText = readFile(self.path, self.logger) newSttyText = [] for line in sttyText: # Check for both serial connections and the old style of # virtual connections if re.search(self.serialRE, line) or \ re.search(r"^vc/\d", line): line = "#" + line newSttyText.append(line) newSttyString = "".join(newSttyText) tmpfile = self.path + ".tmp" if writeFile(tmpfile, newSttyString, self.logger): self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "conf", "filepath": self.path} self.statechglogger.recordchgevent(myid, event) self.statechglogger.recordfilechange( self.path, tmpfile, myid) os.rename(tmpfile, self.path) perms = self.perms setPerms(self.path, perms, self.logger, self.statechglogger, myid) resetsecon(self.path) else: success = False self.detailedresults += "Problem writing new " + \ "contents to temporary file" self.rulesuccess = success 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("fix", self.rulesuccess, self.detailedresults) self.logdispatch.log(LogPriority.INFO, self.detailedresults) return self.rulesuccess
def fix(self): try: if not self.ci.getcurrvalue(): return success = True debug = "" self.iditerator = 0 eventlist = self.statechglogger.findrulechanges(self.rulenumber) for event in eventlist: self.statechglogger.deleteentry(event) for game in self.gamesfound: # pkgName = self.ph.getPackageFromFile(game) # if pkgName is not None and str(pkgName) is not "": if self.ph.remove(game): self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = { "eventtype": "pkghelper", "pkgname": game, "startstate": "installed", "endstate": "removed" } self.statechglogger.recordchgevent(myid, event) else: success = False self.detailedresults += "Unable to remove " + game + "\n" for game in self.gamedirsfound: #did not put state change event recording here due to python #not sending valid return code back for success or failure #with os.remove command therefore not knowing if successful #to record event if os.path.exists(game): os.remove(game) if os.path.exists("/usr/games/"): if not self.__cleandir("/usr/games/"): success = False self.detailedresults += "Unable to remove all games from /usr/games\n" self.rulesuccess = success 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("fix", self.rulesuccess, self.detailedresults) self.logdispatch.log(LogPriority.INFO, self.detailedresults) return self.rulesuccess
def fix(self): '''The fix method will apply the required settings to the system. self.rulesuccess will be updated if the rule does not succeed. Attempt to install Vlock, record success or failure in event logger. :returns: self.rulesuccess :rtype: bool @author: Derek T Walker ''' try: self.detailedresults = "" self.rulesuccess = True self.iditerator = 0 if not self.ci.getcurrvalue(): 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) undocmd = self.ph.getRemove() if not self.ph.install(self.pkg): self.rulesuccess = False self.detailedresults += "\nFailed to install vlock package" else: undocmd += self.pkg self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "comm", "command": undocmd} self.statechglogger.recordchgevent(myid, event) self.detailedresults += "\nvlock Package was installed successfully" except (KeyboardInterrupt, SystemExit): raise except Exception: self.rulesuccess = False self.detailedresults += "\n" + 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