rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
if node.has_key(key) and value == node[key]: del propvalues[key]
if node.has_key(propname) and value == node[propname]: del propvalues[propname]
def set(self, nodeid, **propvalues): """Modify a property on an existing node of this class. 'nodeid' must be the id of an existing node of this class or an IndexError is raised.
link_class = self.properties[key].classname
link_class = self.properties[propname].classname
def set(self, nodeid, **propvalues): """Modify a property on an existing node of this class. 'nodeid' must be the id of an existing node of this class or an IndexError is raised.
key, value, self.properties[key].classname)
propname, value, self.properties[propname].classname)
def set(self, nodeid, **propvalues): """Modify a property on an existing node of this class. 'nodeid' must be the id of an existing node of this class or an IndexError is raised.
if self.do_journal and self.properties[key].do_journal:
if self.do_journal and self.properties[propname].do_journal:
def set(self, nodeid, **propvalues): """Modify a property on an existing node of this class. 'nodeid' must be the id of an existing node of this class or an IndexError is raised.
if node[key] is not None: self.db.addjournal(link_class, node[key], 'unlink', (self.classname, nodeid, key))
if node[propname] is not None: self.db.addjournal(link_class, node[propname], 'unlink', (self.classname, nodeid, propname))
def set(self, nodeid, **propvalues): """Modify a property on an existing node of this class. 'nodeid' must be the id of an existing node of this class or an IndexError is raised.
(self.classname, nodeid, key))
(self.classname, nodeid, propname))
def set(self, nodeid, **propvalues): """Modify a property on an existing node of this class. 'nodeid' must be the id of an existing node of this class or an IndexError is raised.
raise TypeError, 'new property "%s" not a list of ids'%key link_class = self.properties[key].classname
raise TypeError, 'new property "%s" not a list of'\ ' ids'%propname link_class = self.properties[propname].classname
def set(self, nodeid, **propvalues): """Modify a property on an existing node of this class. 'nodeid' must be the id of an existing node of this class or an IndexError is raised.
'must be a string'%key
'must be a string'%propname
def set(self, nodeid, **propvalues): """Modify a property on an existing node of this class. 'nodeid' must be the id of an existing node of this class or an IndexError is raised.
key, entry, self.properties[key].classname)
propname, entry, self.properties[propname].classname)
def set(self, nodeid, **propvalues): """Modify a property on an existing node of this class. 'nodeid' must be the id of an existing node of this class or an IndexError is raised.
propvalues[key] = value
propvalues[propname] = value add = [] remove = []
def set(self, nodeid, **propvalues): """Modify a property on an existing node of this class. 'nodeid' must be the id of an existing node of this class or an IndexError is raised.
if node.has_key(key): l = node[key]
if node.has_key(propname): l = node[propname]
def set(self, nodeid, **propvalues): """Modify a property on an existing node of this class. 'nodeid' must be the id of an existing node of this class or an IndexError is raised.
raise TypeError, 'new property "%s" not a string'%key
raise TypeError, 'new property "%s" not a string'%propname
def set(self, nodeid, **propvalues): """Modify a property on an existing node of this class. 'nodeid' must be the id of an existing node of this class or an IndexError is raised.
raise TypeError, 'new property "%s" not a Password'% key propvalues[key] = value
raise TypeError, 'new property "%s" not a Password'%propname propvalues[propname] = value
def set(self, nodeid, **propvalues): """Modify a property on an existing node of this class. 'nodeid' must be the id of an existing node of this class or an IndexError is raised.
raise TypeError, 'new property "%s" not a Date'% key propvalues[key] = value
raise TypeError, 'new property "%s" not a Date'% propname propvalues[propname] = value
def set(self, nodeid, **propvalues): """Modify a property on an existing node of this class. 'nodeid' must be the id of an existing node of this class or an IndexError is raised.
raise TypeError, 'new property "%s" not an Interval'% key propvalues[key] = value node[key] = value
raise TypeError, 'new property "%s" not an '\ 'Interval'%propname propvalues[propname] = value node[propname] = value
def set(self, nodeid, **propvalues): """Modify a property on an existing node of this class. 'nodeid' must be the id of an existing node of this class or an IndexError is raised.
1. figure out who we are, defaulting to the "anonymous" user
1. look for charset and language preferences, set up user locale see determine_charset, determine_language 2. figure out who we are, defaulting to the "anonymous" user
def inner_main(self): '''Process a request.
2. figure out what the request is for - the context
3. figure out what the request is for - the context
def inner_main(self): '''Process a request.
3. handle any requested action (item edit, search, ...)
4. handle any requested action (item edit, search, ...)
def inner_main(self): '''Process a request.
4. render a template, resulting in HTML output
5. render a template, resulting in HTML output
def inner_main(self): '''Process a request.
''' Open the database and set the current user.
"""Open the database and set the current user.
def opendb(self, username): ''' Open the database and set the current user.
'''
"""
def opendb(self, username): ''' Open the database and set the current user.
'value "%(value)s" not a designator') % locals()
'value "%(entry)s" not a designator') % locals()
propdef = all_propdef[cn]
path = os.path.join(os.getcwd(), self.dir, 'nodes.%s'%classname) db_type = whichdb.whichdb(path) if not db_type: db_type = whichdb.whichdb(path+'.db') db_type = whichdb.whichdb(path) if not db_type and os.path.exists(path) or os.path.exists(path+'.db'): raise hyperdb.DatabaseError, \ "Couldn't identify the database type"
db_type = '' path = os.path.join(os.getcwd(), self.dir, name) if os.path.exists(path): db_type = whichdb.whichdb(path) if not db_type: raise hyperdb.DatabaseError, "Couldn't identify database type" elif os.path.exists(path+'.db'): db_type = 'dbm'
def getclassdb(self, classname, mode='r'): ''' grab a connection to the class db that will be used for multiple actions ''' # determine which DB wrote the class file path = os.path.join(os.getcwd(), self.dir, 'nodes.%s'%classname) db_type = whichdb.whichdb(path) if not db_type: # dbm appends ".db" db_type = whichdb.whichdb(path+'.db') db_type = whichdb.whichdb(path)
except:
except ImportError:
def getclassdb(self, classname, mode='r'): ''' grab a connection to the class db that will be used for multiple actions ''' # determine which DB wrote the class file path = os.path.join(os.getcwd(), self.dir, 'nodes.%s'%classname) db_type = whichdb.whichdb(path) if not db_type: # dbm appends ".db" db_type = whichdb.whichdb(path+'.db') db_type = whichdb.whichdb(path)
db = anydbm.open(os.path.join(self.dir, 'journals.%s'%classname), 'r') except anydbm.open, error: if error.args[0] != 2: raise
db = self._opendb('journals.%s'%classname, 'r') except anydbm.error, error: if str(error) == "need 'c' or 'n' flag to open new db": return [] elif error.args[0] != 2: raise
def getjournal(self, classname, nodeid): ''' get the journal for id ''' # attempt to open the journal - in some rare cases, the journal may # not exist try: db = anydbm.open(os.path.join(self.dir, 'journals.%s'%classname), 'r') except anydbm.open, error: if error.args[0] != 2: raise return [] journal = marshal.loads(db[nodeid]) res = [] for entry in journal: (nodeid, date_stamp, self.journaltag, action, params) = entry date_obj = date.Date(date_stamp) res.append((nodeid, date_obj, self.journaltag, action, params)) return res
pass
delimiter = ':'
def writerows(self, rows): for fields in rows: print >>self.fileobj, self.p.join(fields)
body.write('\n'.join(error))
body.write(quopri.encodestring ('\n'.join(error)))
def bounce_message(self, bounced_message, to, error, subject='Failed issue tracker submission'): """Bounce a message, attaching the failed submission.
r'\s*(P<quote>")?(\[(?P<classname>[^\d\s]+)(?P<nodeid>\d+)?\])?'
r'\s*(?P<quote>")?(\[(?P<classname>[^\d\s]+)(?P<nodeid>\d+)?\])?'
def getPart(self): ''' Get a single part of a multipart message and return it as a new Message instance. ''' boundary = self.getparam('boundary') mid, end = '--'+boundary, '--'+boundary+'--' s = cStringIO.StringIO() while 1: line = self.fp.readline() if not line: break if line.strip() in (mid, end): break s.write(line) if not s.getvalue().strip(): return None s.seek(0) return Message(s)
if is_sqlite3:
if sqlite_version in (2,3):
def db_nuke(config): shutil.rmtree(config.DATABASE)
if is_sqlite3: conn = sqlite.connect(db, 30) conn.row_factory = sqlite.Row else:
if sqlite_version == 1:
def sql_open_connection(self): '''Open a standard, non-autocommitting connection.
if is_sqlite3:
if sqlite_version in (2,3):
def update_class(self, spec, old_spec, force=0, adding_v2=0): ''' Determine the differences between the current spec and the database version of the spec, and update where necessary.
elif is_sqlite3:
elif sqlite_version in (2,3):
def update_class(self, spec, old_spec, force=0, adding_v2=0): ''' Determine the differences between the current spec and the database version of the spec, and update where necessary.
elif (not is_sqlite3 and entry.has_key(name)):
elif (sqlite_version == 1 and entry.has_key(name)):
def update_class(self, spec, old_spec, force=0, adding_v2=0): ''' Determine the differences between the current spec and the database version of the spec, and update where necessary.
if is_sqlite3:
if sqlite_version in (2,3):
def create_class(self, spec): rdbms_common.Database.create_class(self, spec) sql = 'insert into ids (name, num) values (%s, %s)'%(self.arg, self.arg) vals = (spec.classname, 1) self.sql(sql, vals)
Try:
try:
def handle_message(self, message): ''' message - a Message instance
def setrruleset(self, rruleset): - dtstart = self.dtstart.value
+ @classmethod + def duplicate(clz, copyit): + newcopy = clz() + newcopy.copy(copyit) + return newcopy + + def copy(self, copyit): + super(Component, self).copy(copyit)
def setrruleset(self, rruleset):
+ + try: + dtstart = self.dtstart.value + except AttributeError, KeyError: + if self.name == "VTODO": + dtstart = self.due.value + else: + raise + isDate = datetime.date == type(dtstart) if isDate: dtstart = datetime.datetime(dtstart.year,dtstart.month, dtstart.day) @@ -575,6 +593,8 @@ if obj.value.tzinfo is None: obj.params['X-VOBJ-FLOATINGTIME-ALLOWED'] = ['TRUE'] if obj.params.get('TZID'): + + obj.params['X-VOBJ-ORIGINAL-TZID'] = obj.params['TZID'] del obj.params['TZID'] return obj @@ -587,6 +607,10 @@ obj.value = dateTimeToString(obj.value, cls.forceUTC) if not cls.forceUTC and tzid is not None: obj.tzid_param = tzid + if obj.params.get('X-VOBJ-ORIGINAL-TZID'): + if not hasattr(obj, 'tzid_param'): + obj.tzid_param = obj.params['X-VOBJ-ORIGINAL-TZID'] + del obj.params['X-VOBJ-ORIGINAL-TZID'] return obj @@ -607,7 +631,10 @@ obj.value=str(obj.value) obj.value=parseDtstart(obj) if getattr(obj, 'value_param', 'DATE-TIME').upper() == 'DATE-TIME': - if hasattr(obj, 'tzid_param'): del obj.tzid_param + if hasattr(obj, 'tzid_param'): + + obj.params['X-VOBJ-ORIGINAL-TZID'] = obj.tzid_param + del obj.tzid_param return obj @staticmethod
+ + self.contents = {} + for key, lvalue in copyit.contents.items(): + newvalue = [] + for value in lvalue: + newitem = value.duplicate(value) + newvalue.append(newitem) + self.contents[key] = newvalue + + self.name = copyit.name + self.useBegin = copyit.useBegin + def setProfile(self, name): """Assign a PROFILE to this unnamed component.
def setrruleset(self, rruleset):
def get_flags_debug(self): @@ -216,7 +216,7 @@ - for fc_exe in map(find_executable,['gfortran','f95']): + for fc_exe in map(find_executable,['gfortran-dp-4.0','f95']): if os.path.isfile(fc_exe): break executables = {
if os.path.join(sys.prefix, 'lib') not in default_lib_dirs:
def get_flags_debug(self):
logStats = os.stat(self.logPath)
self.logStats = os.stat(self.logPath)
def isModified(self): """ Checks if the log file has been modified using os.stat(). """ try: logStats = os.stat(self.logPath) except OSError: self.logSys.error("Unable to get stat on "+self.logPath) sys.exit(-1) if self.lastModTime == logStats.st_mtime: return False else: self.logSys.debug(self.logPath+" has been modified") self.lastModTime = logStats.st_mtime return True
if self.lastModTime == logStats.st_mtime:
if self.lastModTime == self.logStats.st_mtime:
def isModified(self): """ Checks if the log file has been modified using os.stat(). """ try: logStats = os.stat(self.logPath) except OSError: self.logSys.error("Unable to get stat on "+self.logPath) sys.exit(-1) if self.lastModTime == logStats.st_mtime: return False else: self.logSys.debug(self.logPath+" has been modified") self.lastModTime = logStats.st_mtime return True
self.lastModTime = logStats.st_mtime
self.lastModTime = self.logStats.st_mtime
def isModified(self): """ Checks if the log file has been modified using os.stat(). """ try: logStats = os.stat(self.logPath) except OSError: self.logSys.error("Unable to get stat on "+self.logPath) sys.exit(-1) if self.lastModTime == logStats.st_mtime: return False else: self.logSys.debug(self.logPath+" has been modified") self.lastModTime = logStats.st_mtime return True
self.logSys.debug("Setting file position to " + `self.lastPos`) logFile.seek(self.lastPos)
self.setFilePos(logFile)
def getFailures(self): """ Gets all the failure in the log file which are newer than time.time()-self.findTime. Returns a dict with the IP, the number of failure and the latest failure time. """ ipList = dict() logFile = self.openLogFile() self.logSys.debug("Setting file position to " + `self.lastPos`) logFile.seek(self.lastPos) for line in logFile.readlines(): failList = self.findFailure(line) for element in failList: ip = element[0] unixTime = element[1] if unixTime < time.time()-self.findTime: break if self.inIgnoreIPList(ip): self.logSys.debug("Ignore "+ip) continue self.logSys.debug("Found "+ip) if ipList.has_key(ip): ipList[ip] = (ipList[ip][0]+1, unixTime) else: ipList[ip] = (1, unixTime) self.lastPos = logFile.tell() logFile.close() return ipList
Thanks to Kvin Drapel.
Thanks to Kevin Drapel.
def dnsToIp(dns): """ Convert a DNS into an IP address using the Python socket module. Thanks to Kvin Drapel. """ try: return socket.gethostbyname_ex(dns)[2] except socket.gaierror: return list()
else:
if not ipList:
def textToIp(text): """ Return the IP of DNS found in a given text. """ ipList = list() # Search for plain IP plainIP = searchIP(text) for element in plainIP: ipList.append(element) else: # Try to get IP from possible DNS dnsList = textToDns(text) for element in dnsList: dns = dnsToIp(element) for e in dns: ipList.append(e) return ipList
print socket.gethostbyname_ex("www.google")[2]
print socket.gethostbyname_ex("195.122.223.30")[2]
def textToIp(text): """ Return the IP of DNS found in a given text. """ ipList = list() # Search for plain IP plainIP = searchIP(text) for element in plainIP: ipList.append(element) else: # Try to get IP from possible DNS dnsList = textToDns(text) for element in dnsList: dns = dnsToIp(element) for e in dns: ipList.append(e) return ipList
self.server.start()
self.server.start(False)
def setUp(self): """Call before every test case.""" self.server = Server() self.server.setLogLevel(0) self.server.start()
stream.append(["set", self.__name, "addignoreip", self.__opts[opt]])
for ip in self.__opts[opt].split(): stream.append(["set", self.__name, "addignoreip", ip])
def convert(self): stream = [] for opt in self.__opts: if opt == "logpath": for path in self.__opts[opt].split("\n"): pathList = glob.glob(path) if len(pathList) == 0: logSys.error("No file found for " + path) for p in pathList: stream.append(["set", self.__name, "addlogpath", p]) elif opt == "backend": backend = self.__opts[opt] elif opt == "maxretry": stream.append(["set", self.__name, "maxretry", self.__opts[opt]]) elif opt == "ignoreip": stream.append(["set", self.__name, "addignoreip", self.__opts[opt]]) elif opt == "maxtime": stream.append(["set", self.__name, "maxtime", self.__opts[opt]]) elif opt == "bantime": stream.append(["set", self.__name, "bantime", self.__opts[opt]]) stream.extend(self.__filter.convert()) for action in self.__actions: stream.extend(action.convert()) stream.insert(0, ["add", self.__name, backend]) return stream
self.__socket.join()
while self.__socket.isAlive(): self.__socket.join(1)
def start(self, sock, force = False): logSys.info("Starting Fail2ban") # First set the mask to only allow access to owner os.umask(0077) if self.__daemon: ret = self.__createDaemon() if ret: logSys.info("Daemon started") else: logSys.error("Could not create daemon") raise ServerInitializationError("Could not create daemon") # Start the communication logSys.debug("Starting communication") try: self.__socket.initialize(sock, force) self.__socket.start() self.__socket.join() except SSocketErrorException: logSys.error("Could not start server") logSys.info("Exiting Fail2ban")
logSys.warn("[%s] Ban %s" % (self.jail.getName(), aInfo["ip"])) for action in self.__actions: action.execActionBan(aInfo) self.__banManager.addBanTicket(bTicket) return True
aInfo["time"] = bTicket.getTime() if self.__banManager.addBanTicket(bTicket): logSys.warn("[%s] Ban %s" % (self.jail.getName(), aInfo["ip"])) for action in self.__actions: action.execActionBan(aInfo) return True else: logSys.warn("[%s] %s already banned" % (self.jail.getName(), aInfo["ip"]))
def __checkBan(self): ticket = self.jail.getFailTicket() if ticket != False: aInfo = dict() bTicket = BanManager.createBanTicket(ticket) aInfo["ip"] = bTicket.getIP() aInfo["failures"] = bTicket.getAttempt() logSys.warn("[%s] Ban %s" % (self.jail.getName(), aInfo["ip"])) for action in self.__actions: action.execActionBan(aInfo) self.__banManager.addBanTicket(bTicket) return True return False
aInfo = dict() aInfo["ip"] = ticket.getIP() logSys.warn("[%s] Unban %s" % (self.jail.getName(), aInfo["ip"])) for action in self.__actions: action.execActionUnban(aInfo)
self.__unBan(ticket)
def __checkUnBan(self): for ticket in self.__banManager.unBanList(MyTime.time()): aInfo = dict() aInfo["ip"] = ticket.getIP() logSys.warn("[%s] Unban %s" % (self.jail.getName(), aInfo["ip"])) for action in self.__actions: action.execActionUnban(aInfo)
aInfo = dict() aInfo["ip"] = ticket.getIP() logSys.warn("[%s] Unban %s" % (self.jail.getName(), aInfo["ip"])) for action in self.__actions: action.execActionUnban(aInfo)
self.__unBan(ticket) def __unBan(self, ticket): aInfo = dict() aInfo["ip"] = ticket.getIP() aInfo["failures"] = ticket.getAttempt() aInfo["time"] = ticket.getTime() logSys.warn("[%s] Unban %s" % (self.jail.getName(), aInfo["ip"])) for action in self.__actions: action.execActionUnban(aInfo)
def __flushBan(self): logSys.debug("Flush ban list") for ticket in self.__banManager.flushBanList(): aInfo = dict() aInfo["ip"] = ticket.getIP() logSys.warn("[%s] Unban %s" % (self.jail.getName(), aInfo["ip"])) for action in self.__actions: action.execActionUnban(aInfo)
def __init__(self, banTime, verbose = False):
def __init__(self, banTime, logSys):
def __init__(self, banTime, verbose = False): self.banTime = banTime self.verbose = verbose
self.verbose = verbose
self.logSys = logSys
def __init__(self, banTime, verbose = False): self.banTime = banTime self.verbose = verbose
def addBanIP(self, ip):
def addBanIP(self, ip, debug):
def addBanIP(self, ip): if not self.inBanList(ip): self.banList[ip] = time.time() self.executeCmd(self.banIP(ip)) else: if self.verbose: print ip, "already in ban list"
self.executeCmd(self.banIP(ip))
self.executeCmd(self.banIP(ip), debug)
def addBanIP(self, ip): if not self.inBanList(ip): self.banList[ip] = time.time() self.executeCmd(self.banIP(ip)) else: if self.verbose: print ip, "already in ban list"
if self.verbose: print ip, "already in ban list"
self.logSys.info(ip+" already in ban list")
def addBanIP(self, ip): if not self.inBanList(ip): self.banList[ip] = time.time() self.executeCmd(self.banIP(ip)) else: if self.verbose: print ip, "already in ban list"
def delBanIP(self, ip):
def delBanIP(self, ip, debug):
def delBanIP(self, ip): if self.inBanList(ip): del self.banList[ip] self.executeCmd(self.unBanIP(ip)) else: if self.verbose: print ip, "not in ban list"
self.executeCmd(self.unBanIP(ip))
self.executeCmd(self.unBanIP(ip), debug)
def delBanIP(self, ip): if self.inBanList(ip): del self.banList[ip] self.executeCmd(self.unBanIP(ip)) else: if self.verbose: print ip, "not in ban list"
if self.verbose: print ip, "not in ban list"
self.logSys.info(ip+" not in ban list")
def delBanIP(self, ip): if self.inBanList(ip): del self.banList[ip] self.executeCmd(self.unBanIP(ip)) else: if self.verbose: print ip, "not in ban list"
def checkForUnBan(self):
def checkForUnBan(self, debug):
def checkForUnBan(self): """ Check for user to remove from ban list. """ banListTemp = self.banList.copy() iterBanList = banListTemp.iteritems() for i in range(len(self.banList)): element = iterBanList.next() ip = element[0] btime = element[1] if btime < time.time()-self.banTime: self.delBanIP(ip) if self.verbose: print '`->', time.time()
self.delBanIP(ip) if self.verbose: print '`->', time.time()
self.delBanIP(ip, debug)
def checkForUnBan(self): """ Check for user to remove from ban list. """ banListTemp = self.banList.copy() iterBanList = banListTemp.iteritems() for i in range(len(self.banList)): element = iterBanList.next() ip = element[0] btime = element[1] if btime < time.time()-self.banTime: self.delBanIP(ip) if self.verbose: print '`->', time.time()
def flushBanList(self):
def flushBanList(self, debug):
def flushBanList(self): iterBanList = self.banList.iteritems() for i in range(len(self.banList)): element = iterBanList.next() ip = element[0] self.delBanIP(ip)
self.delBanIP(ip)
self.delBanIP(ip, debug)
def flushBanList(self): iterBanList = self.banList.iteritems() for i in range(len(self.banList)): element = iterBanList.next() ip = element[0] self.delBanIP(ip)
def executeCmd(self, cmd): if self.verbose: print cmd return
def executeCmd(self, cmd, debug): self.logSys.debug(cmd) if not debug: return os.system(cmd) else: return None
def executeCmd(self, cmd): if self.verbose: print cmd return #os.system(cmd)
fileHandler = open(lockfile, mode='w') pid = os.getpid() fileHandler.write(`pid`+'\n') fileHandler.close() logSys.debug("Created PID lock ("+`pid`+") in "+lockfile)
def checkForPID(lockfile): """ Checks for running Fail2Ban. Returns the current PID if Fail2Ban is running or False if no instance found. """ try: fileHandler = open(lockfile) pid = fileHandler.readline() return pid except IOError: fileHandler = open(lockfile, mode='w') pid = os.getpid() fileHandler.write(`pid`+'\n') fileHandler.close() logSys.debug("Created PID lock ("+`pid`+") in "+lockfile) return False
return None
return []
def textToDns(text): """ Search for possible DNS in an arbitrary text. """ match = re.findall("\w*\.\w*\.\w*", text) if match: return match else: return None
return None
return []
def searchIP(text): """ Search if an IP address if directly available and return it. """ match = re.findall("(?:\d{1,3}\.){3}\d{1,3}", text) if match: return match else: return None
if plainIP: for element in plainIP: ipList.append(element)
for element in plainIP: ipList.append(element)
def textToIp(text): """ Return the IP of DNS found in a given text. """ ipList = list() # Search for plain IP plainIP = searchIP(text) if plainIP: for element in plainIP: ipList.append(element) else: # Try to get IP from possible DNS dnsList = textToDns(text) for element in dnsList: dns = dnsToIp(element) for e in dns: ipList.append(e) return ipList
match = re.findall("\w*\.\w*\.\w*", text)
match = re.findall("\S*\.\w*\.\w*", text)
def textToDns(text): """ Search for possible DNS in an arbitrary text. """ match = re.findall("\w*\.\w*\.\w*", text) if match: return match else: return []
def read(self, filename):
def read(self, FILENAME):
def read(self, filename): global basedir basename = basedir + filename logSys.debug("Reading " + basename) bConf = basename + ".conf" bLocal = basename + ".local" if os.path.exists(bConf) or os.path.exists(bLocal): SafeConfigParser.read(self, [bConf, bLocal]) return True else: logSys.error(bConf + " and " + bLocal + " do not exist") return False
self.logSys.debug("Log rotation detected")
self.logSys.debug("Log rotation detected for " + self.logPath)
def setFilePos(self, file): """ Sets the file position. We must take care of log file rotation and reset the position to 0 in that case. Use the log message timestamp in order to detect this. """ line = file.readline() if self.lastDate < self.getTime(line): self.logSys.debug("Date " + `self.lastDate` + " is " + "smaller than " + `self.getTime(line)`) self.logSys.debug("Log rotation detected") self.lastPos = 0 self.logSys.debug("Setting file position to " + `self.lastPos`) file.seek(self.lastPos)
self.logSys.debug("Setting file position to " + `self.lastPos`)
self.logSys.debug("Setting file position to " + `self.lastPos` + " for " + self.logPath)
def setFilePos(self, file): """ Sets the file position. We must take care of log file rotation and reset the position to 0 in that case. Use the log message timestamp in order to detect this. """ line = file.readline() if self.lastDate < self.getTime(line): self.logSys.debug("Date " + `self.lastDate` + " is " + "smaller than " + `self.getTime(line)`) self.logSys.debug("Log rotation detected") self.lastPos = 0 self.logSys.debug("Setting file position to " + `self.lastPos`) file.seek(self.lastPos)
iterBanList = self.banList.iteritems()
banListTemp = self.banList.copy() iterBanList = banListTemp.iteritems()
def flushBanList(self, debug): """ Flushes the ban list and of course the firewall rules. Called when fail2ban exits. """ iterBanList = self.banList.iteritems() for i in range(len(self.banList)): element = iterBanList.next() ip = element[0] self.delBanIP(ip, debug)
logSys.warn("[%s] Ban %s" % self.jail.getName(), aInfo["ip"])
logSys.warn("[%s] Ban %s" % (self.jail.getName(), aInfo["ip"]))
def __checkBan(self): ticket = self.jail.getFailTicket() if ticket != False: aInfo = dict() bTicket = BanManager.createBanTicket(ticket) aInfo["ip"] = bTicket.getIP() aInfo["failures"] = bTicket.getAttempt() logSys.warn("[%s] Ban %s" % self.jail.getName(), aInfo["ip"]) for action in self.__actions: action.execActionBan(aInfo) self.__banManager.addBanTicket(bTicket) return True return False
logSys.warn("[%s] Unban %s" % self.jail.getName(), aInfo["ip"])
logSys.warn("[%s] Unban %s" % (self.jail.getName(), aInfo["ip"]))
def __checkUnBan(self): for ticket in self.__banManager.unBanList(time.time()): aInfo = dict() aInfo["ip"] = ticket.getIP() logSys.warn("[%s] Unban %s" % self.jail.getName(), aInfo["ip"]) for action in self.__actions: action.execActionUnban(aInfo)
logSys.warn("[%s] Unban %s" % self.jail.getName(), aInfo["ip"])
logSys.warn("[%s] Unban %s" % (self.jail.getName(), aInfo["ip"]))
def __flushBan(self): logSys.debug("Flush ban list") for ticket in self.__banManager.flushBanList(): aInfo = dict() aInfo["ip"] = ticket.getIP() logSys.warn("[%s] Unban %s" % self.jail.getName(), aInfo["ip"]) for action in self.__actions: action.execActionUnban(aInfo)
print lastDate print lineDate
def __setFilePos(self): line = self.__crtHandler.readline() lastDate = self.__lastDate[self.__crtFilename] lineDate = self.dateDetector.getUnixTime(line) print lastDate print lineDate if lastDate < lineDate: logSys.debug("Date " + `lastDate` + " is smaller than " + `lineDate`) logSys.debug("Log rotation detected for " + self.__crtFilename) self.__lastPos[self.__crtFilename] = 0 lastPos = self.__lastPos[self.__crtFilename] logSys.debug("Setting file position to " + `lastPos` + " for " + self.__crtFilename) self.__crtHandler.seek(lastPos)
print "fail2ban [-h][-v][-b]"
print "fail2ban [-h][-v][-b][-d][-f <pwdfail file>][-l <log file>]"
def usage(): print "fail2ban [-h][-v][-b]" sys.exit(0)
os.chdir("/")
def createDaemon(): """Detach a process from the controlling terminal and run it in the background as a daemon. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 """ try: # Fork a child process so the parent can exit. This will return control # to the command line or shell. This is required so that the new process # is guaranteed not to be a process group leader. We have this guarantee # because the process GID of the parent is inherited by the child, but # the child gets a new PID, making it impossible for its PID to equal its # PGID. pid = os.fork() except OSError, e: return((e.errno, e.strerror)) # ERROR (return a tuple) if (pid == 0): # The first child. # Next we call os.setsid() to become the session leader of this new # session. The process also becomes the process group leader of the # new process group. Since a controlling terminal is associated with a # session, and this new session has not yet acquired a controlling # terminal our process now has no controlling terminal. This shouldn't # fail, since we're guaranteed that the child is not a process group # leader. os.setsid() # When the first child terminates, all processes in the second child # are sent a SIGHUP, so it's ignored. signal.signal(signal.SIGHUP, signal.SIG_IGN) try: # Fork a second child to prevent zombies. Since the first child is # a session leader without a controlling terminal, it's possible for # it to acquire one by opening a terminal in the future. This second # fork guarantees that the child is no longer a session leader, thus # preventing the daemon from ever acquiring a controlling terminal. pid = os.fork() # Fork a second child. except OSError, e: return((e.errno, e.strerror)) # ERROR (return a tuple) if (pid == 0): # The second child. # Ensure that the daemon doesn't keep any directory in use. Failure # to do this could make a filesystem unmountable. #os.chdir("/") # Give the child complete control over permissions. os.umask(0) else: os._exit(0) # Exit parent (the first child) of the second child. else: os._exit(0) # Exit parent of the first child. # Close all open files. Try the system configuration variable, SC_OPEN_MAX, # for the maximum number of open files to close. If it doesn't exist, use # the default value (configurable). try: maxfd = os.sysconf("SC_OPEN_MAX") except (AttributeError, ValueError): maxfd = 256 # default maximum for fd in range(0, maxfd): try: os.close(fd) except OSError: # ERROR (ignore) pass # Redirect the standard file descriptors to /dev/null. os.open("/dev/null", os.O_RDONLY) # standard input (0) #os.open("/dev/null", os.O_RDWR) # standard output (1) os.open("/tmp/fail2ban.log", os.O_CREAT|os.O_APPEND|os.O_RDWR) # standard output (1) #os.open("/dev/null", os.O_RDWR) # standard error (2) os.open("/tmp/fail2ban.log", os.O_CREAT|os.O_APPEND|os.O_RDWR) # standard error (2) return(0)
os.open("/tmp/fail2ban.log", os.O_CREAT|os.O_APPEND|os.O_RDWR) os.open("/tmp/fail2ban.log", os.O_CREAT|os.O_APPEND|os.O_RDWR)
os.open("/dev/null", os.O_RDWR) os.open("/dev/null", os.O_RDWR)
def createDaemon(): """Detach a process from the controlling terminal and run it in the background as a daemon. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 """ try: # Fork a child process so the parent can exit. This will return control # to the command line or shell. This is required so that the new process # is guaranteed not to be a process group leader. We have this guarantee # because the process GID of the parent is inherited by the child, but # the child gets a new PID, making it impossible for its PID to equal its # PGID. pid = os.fork() except OSError, e: return((e.errno, e.strerror)) # ERROR (return a tuple) if (pid == 0): # The first child. # Next we call os.setsid() to become the session leader of this new # session. The process also becomes the process group leader of the # new process group. Since a controlling terminal is associated with a # session, and this new session has not yet acquired a controlling # terminal our process now has no controlling terminal. This shouldn't # fail, since we're guaranteed that the child is not a process group # leader. os.setsid() # When the first child terminates, all processes in the second child # are sent a SIGHUP, so it's ignored. signal.signal(signal.SIGHUP, signal.SIG_IGN) try: # Fork a second child to prevent zombies. Since the first child is # a session leader without a controlling terminal, it's possible for # it to acquire one by opening a terminal in the future. This second # fork guarantees that the child is no longer a session leader, thus # preventing the daemon from ever acquiring a controlling terminal. pid = os.fork() # Fork a second child. except OSError, e: return((e.errno, e.strerror)) # ERROR (return a tuple) if (pid == 0): # The second child. # Ensure that the daemon doesn't keep any directory in use. Failure # to do this could make a filesystem unmountable. #os.chdir("/") # Give the child complete control over permissions. os.umask(0) else: os._exit(0) # Exit parent (the first child) of the second child. else: os._exit(0) # Exit parent of the first child. # Close all open files. Try the system configuration variable, SC_OPEN_MAX, # for the maximum number of open files to close. If it doesn't exist, use # the default value (configurable). try: maxfd = os.sysconf("SC_OPEN_MAX") except (AttributeError, ValueError): maxfd = 256 # default maximum for fd in range(0, maxfd): try: os.close(fd) except OSError: # ERROR (ignore) pass # Redirect the standard file descriptors to /dev/null. os.open("/dev/null", os.O_RDONLY) # standard input (0) #os.open("/dev/null", os.O_RDWR) # standard output (1) os.open("/tmp/fail2ban.log", os.O_CREAT|os.O_APPEND|os.O_RDWR) # standard output (1) #os.open("/dev/null", os.O_RDWR) # standard error (2) os.open("/tmp/fail2ban.log", os.O_CREAT|os.O_APPEND|os.O_RDWR) # standard error (2) return(0)
optList, args = getopt.getopt(sys.argv[1:], 'hvb')
optList, args = getopt.getopt(sys.argv[1:], 'hvbdf:l:')
def createDaemon(): """Detach a process from the controlling terminal and run it in the background as a daemon. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 """ try: # Fork a child process so the parent can exit. This will return control # to the command line or shell. This is required so that the new process # is guaranteed not to be a process group leader. We have this guarantee # because the process GID of the parent is inherited by the child, but # the child gets a new PID, making it impossible for its PID to equal its # PGID. pid = os.fork() except OSError, e: return((e.errno, e.strerror)) # ERROR (return a tuple) if (pid == 0): # The first child. # Next we call os.setsid() to become the session leader of this new # session. The process also becomes the process group leader of the # new process group. Since a controlling terminal is associated with a # session, and this new session has not yet acquired a controlling # terminal our process now has no controlling terminal. This shouldn't # fail, since we're guaranteed that the child is not a process group # leader. os.setsid() # When the first child terminates, all processes in the second child # are sent a SIGHUP, so it's ignored. signal.signal(signal.SIGHUP, signal.SIG_IGN) try: # Fork a second child to prevent zombies. Since the first child is # a session leader without a controlling terminal, it's possible for # it to acquire one by opening a terminal in the future. This second # fork guarantees that the child is no longer a session leader, thus # preventing the daemon from ever acquiring a controlling terminal. pid = os.fork() # Fork a second child. except OSError, e: return((e.errno, e.strerror)) # ERROR (return a tuple) if (pid == 0): # The second child. # Ensure that the daemon doesn't keep any directory in use. Failure # to do this could make a filesystem unmountable. #os.chdir("/") # Give the child complete control over permissions. os.umask(0) else: os._exit(0) # Exit parent (the first child) of the second child. else: os._exit(0) # Exit parent of the first child. # Close all open files. Try the system configuration variable, SC_OPEN_MAX, # for the maximum number of open files to close. If it doesn't exist, use # the default value (configurable). try: maxfd = os.sysconf("SC_OPEN_MAX") except (AttributeError, ValueError): maxfd = 256 # default maximum for fd in range(0, maxfd): try: os.close(fd) except OSError: # ERROR (ignore) pass # Redirect the standard file descriptors to /dev/null. os.open("/dev/null", os.O_RDONLY) # standard input (0) #os.open("/dev/null", os.O_RDWR) # standard output (1) os.open("/tmp/fail2ban.log", os.O_CREAT|os.O_APPEND|os.O_RDWR) # standard output (1) #os.open("/dev/null", os.O_RDWR) # standard error (2) os.open("/tmp/fail2ban.log", os.O_CREAT|os.O_APPEND|os.O_RDWR) # standard error (2) return(0)
verbose = False
debug = False logFilePath = "/var/log/pwdfail/current"
def createDaemon(): """Detach a process from the controlling terminal and run it in the background as a daemon. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 """ try: # Fork a child process so the parent can exit. This will return control # to the command line or shell. This is required so that the new process # is guaranteed not to be a process group leader. We have this guarantee # because the process GID of the parent is inherited by the child, but # the child gets a new PID, making it impossible for its PID to equal its # PGID. pid = os.fork() except OSError, e: return((e.errno, e.strerror)) # ERROR (return a tuple) if (pid == 0): # The first child. # Next we call os.setsid() to become the session leader of this new # session. The process also becomes the process group leader of the # new process group. Since a controlling terminal is associated with a # session, and this new session has not yet acquired a controlling # terminal our process now has no controlling terminal. This shouldn't # fail, since we're guaranteed that the child is not a process group # leader. os.setsid() # When the first child terminates, all processes in the second child # are sent a SIGHUP, so it's ignored. signal.signal(signal.SIGHUP, signal.SIG_IGN) try: # Fork a second child to prevent zombies. Since the first child is # a session leader without a controlling terminal, it's possible for # it to acquire one by opening a terminal in the future. This second # fork guarantees that the child is no longer a session leader, thus # preventing the daemon from ever acquiring a controlling terminal. pid = os.fork() # Fork a second child. except OSError, e: return((e.errno, e.strerror)) # ERROR (return a tuple) if (pid == 0): # The second child. # Ensure that the daemon doesn't keep any directory in use. Failure # to do this could make a filesystem unmountable. #os.chdir("/") # Give the child complete control over permissions. os.umask(0) else: os._exit(0) # Exit parent (the first child) of the second child. else: os._exit(0) # Exit parent of the first child. # Close all open files. Try the system configuration variable, SC_OPEN_MAX, # for the maximum number of open files to close. If it doesn't exist, use # the default value (configurable). try: maxfd = os.sysconf("SC_OPEN_MAX") except (AttributeError, ValueError): maxfd = 256 # default maximum for fd in range(0, maxfd): try: os.close(fd) except OSError: # ERROR (ignore) pass # Redirect the standard file descriptors to /dev/null. os.open("/dev/null", os.O_RDONLY) # standard input (0) #os.open("/dev/null", os.O_RDWR) # standard output (1) os.open("/tmp/fail2ban.log", os.O_CREAT|os.O_APPEND|os.O_RDWR) # standard output (1) #os.open("/dev/null", os.O_RDWR) # standard error (2) os.open("/tmp/fail2ban.log", os.O_CREAT|os.O_APPEND|os.O_RDWR) # standard error (2) return(0)
verbose = True
logSys.set_loglevel(log4py.LOGLEVEL_VERBOSE)
def createDaemon(): """Detach a process from the controlling terminal and run it in the background as a daemon. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 """ try: # Fork a child process so the parent can exit. This will return control # to the command line or shell. This is required so that the new process # is guaranteed not to be a process group leader. We have this guarantee # because the process GID of the parent is inherited by the child, but # the child gets a new PID, making it impossible for its PID to equal its # PGID. pid = os.fork() except OSError, e: return((e.errno, e.strerror)) # ERROR (return a tuple) if (pid == 0): # The first child. # Next we call os.setsid() to become the session leader of this new # session. The process also becomes the process group leader of the # new process group. Since a controlling terminal is associated with a # session, and this new session has not yet acquired a controlling # terminal our process now has no controlling terminal. This shouldn't # fail, since we're guaranteed that the child is not a process group # leader. os.setsid() # When the first child terminates, all processes in the second child # are sent a SIGHUP, so it's ignored. signal.signal(signal.SIGHUP, signal.SIG_IGN) try: # Fork a second child to prevent zombies. Since the first child is # a session leader without a controlling terminal, it's possible for # it to acquire one by opening a terminal in the future. This second # fork guarantees that the child is no longer a session leader, thus # preventing the daemon from ever acquiring a controlling terminal. pid = os.fork() # Fork a second child. except OSError, e: return((e.errno, e.strerror)) # ERROR (return a tuple) if (pid == 0): # The second child. # Ensure that the daemon doesn't keep any directory in use. Failure # to do this could make a filesystem unmountable. #os.chdir("/") # Give the child complete control over permissions. os.umask(0) else: os._exit(0) # Exit parent (the first child) of the second child. else: os._exit(0) # Exit parent of the first child. # Close all open files. Try the system configuration variable, SC_OPEN_MAX, # for the maximum number of open files to close. If it doesn't exist, use # the default value (configurable). try: maxfd = os.sysconf("SC_OPEN_MAX") except (AttributeError, ValueError): maxfd = 256 # default maximum for fd in range(0, maxfd): try: os.close(fd) except OSError: # ERROR (ignore) pass # Redirect the standard file descriptors to /dev/null. os.open("/dev/null", os.O_RDONLY) # standard input (0) #os.open("/dev/null", os.O_RDWR) # standard output (1) os.open("/tmp/fail2ban.log", os.O_CREAT|os.O_APPEND|os.O_RDWR) # standard output (1) #os.open("/dev/null", os.O_RDWR) # standard error (2) os.open("/tmp/fail2ban.log", os.O_CREAT|os.O_APPEND|os.O_RDWR) # standard error (2) return(0)
print "Unable to start daemon"
logSys.error("Unable to start daemon")
def createDaemon(): """Detach a process from the controlling terminal and run it in the background as a daemon. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 """ try: # Fork a child process so the parent can exit. This will return control # to the command line or shell. This is required so that the new process # is guaranteed not to be a process group leader. We have this guarantee # because the process GID of the parent is inherited by the child, but # the child gets a new PID, making it impossible for its PID to equal its # PGID. pid = os.fork() except OSError, e: return((e.errno, e.strerror)) # ERROR (return a tuple) if (pid == 0): # The first child. # Next we call os.setsid() to become the session leader of this new # session. The process also becomes the process group leader of the # new process group. Since a controlling terminal is associated with a # session, and this new session has not yet acquired a controlling # terminal our process now has no controlling terminal. This shouldn't # fail, since we're guaranteed that the child is not a process group # leader. os.setsid() # When the first child terminates, all processes in the second child # are sent a SIGHUP, so it's ignored. signal.signal(signal.SIGHUP, signal.SIG_IGN) try: # Fork a second child to prevent zombies. Since the first child is # a session leader without a controlling terminal, it's possible for # it to acquire one by opening a terminal in the future. This second # fork guarantees that the child is no longer a session leader, thus # preventing the daemon from ever acquiring a controlling terminal. pid = os.fork() # Fork a second child. except OSError, e: return((e.errno, e.strerror)) # ERROR (return a tuple) if (pid == 0): # The second child. # Ensure that the daemon doesn't keep any directory in use. Failure # to do this could make a filesystem unmountable. #os.chdir("/") # Give the child complete control over permissions. os.umask(0) else: os._exit(0) # Exit parent (the first child) of the second child. else: os._exit(0) # Exit parent of the first child. # Close all open files. Try the system configuration variable, SC_OPEN_MAX, # for the maximum number of open files to close. If it doesn't exist, use # the default value (configurable). try: maxfd = os.sysconf("SC_OPEN_MAX") except (AttributeError, ValueError): maxfd = 256 # default maximum for fd in range(0, maxfd): try: os.close(fd) except OSError: # ERROR (ignore) pass # Redirect the standard file descriptors to /dev/null. os.open("/dev/null", os.O_RDONLY) # standard input (0) #os.open("/dev/null", os.O_RDWR) # standard output (1) os.open("/tmp/fail2ban.log", os.O_CREAT|os.O_APPEND|os.O_RDWR) # standard output (1) #os.open("/dev/null", os.O_RDWR) # standard error (2) os.open("/tmp/fail2ban.log", os.O_CREAT|os.O_APPEND|os.O_RDWR) # standard error (2) return(0)
print "You must be root."
logSys.error("You must be root") if not debug: sys.exit(-1)
def createDaemon(): """Detach a process from the controlling terminal and run it in the background as a daemon. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 """ try: # Fork a child process so the parent can exit. This will return control # to the command line or shell. This is required so that the new process # is guaranteed not to be a process group leader. We have this guarantee # because the process GID of the parent is inherited by the child, but # the child gets a new PID, making it impossible for its PID to equal its # PGID. pid = os.fork() except OSError, e: return((e.errno, e.strerror)) # ERROR (return a tuple) if (pid == 0): # The first child. # Next we call os.setsid() to become the session leader of this new # session. The process also becomes the process group leader of the # new process group. Since a controlling terminal is associated with a # session, and this new session has not yet acquired a controlling # terminal our process now has no controlling terminal. This shouldn't # fail, since we're guaranteed that the child is not a process group # leader. os.setsid() # When the first child terminates, all processes in the second child # are sent a SIGHUP, so it's ignored. signal.signal(signal.SIGHUP, signal.SIG_IGN) try: # Fork a second child to prevent zombies. Since the first child is # a session leader without a controlling terminal, it's possible for # it to acquire one by opening a terminal in the future. This second # fork guarantees that the child is no longer a session leader, thus # preventing the daemon from ever acquiring a controlling terminal. pid = os.fork() # Fork a second child. except OSError, e: return((e.errno, e.strerror)) # ERROR (return a tuple) if (pid == 0): # The second child. # Ensure that the daemon doesn't keep any directory in use. Failure # to do this could make a filesystem unmountable. #os.chdir("/") # Give the child complete control over permissions. os.umask(0) else: os._exit(0) # Exit parent (the first child) of the second child. else: os._exit(0) # Exit parent of the first child. # Close all open files. Try the system configuration variable, SC_OPEN_MAX, # for the maximum number of open files to close. If it doesn't exist, use # the default value (configurable). try: maxfd = os.sysconf("SC_OPEN_MAX") except (AttributeError, ValueError): maxfd = 256 # default maximum for fd in range(0, maxfd): try: os.close(fd) except OSError: # ERROR (ignore) pass # Redirect the standard file descriptors to /dev/null. os.open("/dev/null", os.O_RDONLY) # standard input (0) #os.open("/dev/null", os.O_RDWR) # standard output (1) os.open("/tmp/fail2ban.log", os.O_CREAT|os.O_APPEND|os.O_RDWR) # standard output (1) #os.open("/dev/null", os.O_RDWR) # standard error (2) os.open("/tmp/fail2ban.log", os.O_CREAT|os.O_APPEND|os.O_RDWR) # standard error (2) return(0)
fireWall = Iptables(600, verbose = verbose) logFile = Metalog("./log-test/test", 600, verbose = verbose)
fireWall = Iptables(600, logSys) logFile = Metalog(logFilePath, logSys, 600)
def createDaemon(): """Detach a process from the controlling terminal and run it in the background as a daemon. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 """ try: # Fork a child process so the parent can exit. This will return control # to the command line or shell. This is required so that the new process # is guaranteed not to be a process group leader. We have this guarantee # because the process GID of the parent is inherited by the child, but # the child gets a new PID, making it impossible for its PID to equal its # PGID. pid = os.fork() except OSError, e: return((e.errno, e.strerror)) # ERROR (return a tuple) if (pid == 0): # The first child. # Next we call os.setsid() to become the session leader of this new # session. The process also becomes the process group leader of the # new process group. Since a controlling terminal is associated with a # session, and this new session has not yet acquired a controlling # terminal our process now has no controlling terminal. This shouldn't # fail, since we're guaranteed that the child is not a process group # leader. os.setsid() # When the first child terminates, all processes in the second child # are sent a SIGHUP, so it's ignored. signal.signal(signal.SIGHUP, signal.SIG_IGN) try: # Fork a second child to prevent zombies. Since the first child is # a session leader without a controlling terminal, it's possible for # it to acquire one by opening a terminal in the future. This second # fork guarantees that the child is no longer a session leader, thus # preventing the daemon from ever acquiring a controlling terminal. pid = os.fork() # Fork a second child. except OSError, e: return((e.errno, e.strerror)) # ERROR (return a tuple) if (pid == 0): # The second child. # Ensure that the daemon doesn't keep any directory in use. Failure # to do this could make a filesystem unmountable. #os.chdir("/") # Give the child complete control over permissions. os.umask(0) else: os._exit(0) # Exit parent (the first child) of the second child. else: os._exit(0) # Exit parent of the first child. # Close all open files. Try the system configuration variable, SC_OPEN_MAX, # for the maximum number of open files to close. If it doesn't exist, use # the default value (configurable). try: maxfd = os.sysconf("SC_OPEN_MAX") except (AttributeError, ValueError): maxfd = 256 # default maximum for fd in range(0, maxfd): try: os.close(fd) except OSError: # ERROR (ignore) pass # Redirect the standard file descriptors to /dev/null. os.open("/dev/null", os.O_RDONLY) # standard input (0) #os.open("/dev/null", os.O_RDWR) # standard output (1) os.open("/tmp/fail2ban.log", os.O_CREAT|os.O_APPEND|os.O_RDWR) # standard output (1) #os.open("/dev/null", os.O_RDWR) # standard error (2) os.open("/tmp/fail2ban.log", os.O_CREAT|os.O_APPEND|os.O_RDWR) # standard error (2) return(0)
fireWall.checkForUnBan()
fireWall.checkForUnBan(debug)
def createDaemon(): """Detach a process from the controlling terminal and run it in the background as a daemon. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 """ try: # Fork a child process so the parent can exit. This will return control # to the command line or shell. This is required so that the new process # is guaranteed not to be a process group leader. We have this guarantee # because the process GID of the parent is inherited by the child, but # the child gets a new PID, making it impossible for its PID to equal its # PGID. pid = os.fork() except OSError, e: return((e.errno, e.strerror)) # ERROR (return a tuple) if (pid == 0): # The first child. # Next we call os.setsid() to become the session leader of this new # session. The process also becomes the process group leader of the # new process group. Since a controlling terminal is associated with a # session, and this new session has not yet acquired a controlling # terminal our process now has no controlling terminal. This shouldn't # fail, since we're guaranteed that the child is not a process group # leader. os.setsid() # When the first child terminates, all processes in the second child # are sent a SIGHUP, so it's ignored. signal.signal(signal.SIGHUP, signal.SIG_IGN) try: # Fork a second child to prevent zombies. Since the first child is # a session leader without a controlling terminal, it's possible for # it to acquire one by opening a terminal in the future. This second # fork guarantees that the child is no longer a session leader, thus # preventing the daemon from ever acquiring a controlling terminal. pid = os.fork() # Fork a second child. except OSError, e: return((e.errno, e.strerror)) # ERROR (return a tuple) if (pid == 0): # The second child. # Ensure that the daemon doesn't keep any directory in use. Failure # to do this could make a filesystem unmountable. #os.chdir("/") # Give the child complete control over permissions. os.umask(0) else: os._exit(0) # Exit parent (the first child) of the second child. else: os._exit(0) # Exit parent of the first child. # Close all open files. Try the system configuration variable, SC_OPEN_MAX, # for the maximum number of open files to close. If it doesn't exist, use # the default value (configurable). try: maxfd = os.sysconf("SC_OPEN_MAX") except (AttributeError, ValueError): maxfd = 256 # default maximum for fd in range(0, maxfd): try: os.close(fd) except OSError: # ERROR (ignore) pass # Redirect the standard file descriptors to /dev/null. os.open("/dev/null", os.O_RDONLY) # standard input (0) #os.open("/dev/null", os.O_RDWR) # standard output (1) os.open("/tmp/fail2ban.log", os.O_CREAT|os.O_APPEND|os.O_RDWR) # standard output (1) #os.open("/dev/null", os.O_RDWR) # standard error (2) os.open("/tmp/fail2ban.log", os.O_CREAT|os.O_APPEND|os.O_RDWR) # standard error (2) return(0)
fireWall.addBanIP(element[0])
fireWall.addBanIP(element[0], debug)
def createDaemon(): """Detach a process from the controlling terminal and run it in the background as a daemon. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 """ try: # Fork a child process so the parent can exit. This will return control # to the command line or shell. This is required so that the new process # is guaranteed not to be a process group leader. We have this guarantee # because the process GID of the parent is inherited by the child, but # the child gets a new PID, making it impossible for its PID to equal its # PGID. pid = os.fork() except OSError, e: return((e.errno, e.strerror)) # ERROR (return a tuple) if (pid == 0): # The first child. # Next we call os.setsid() to become the session leader of this new # session. The process also becomes the process group leader of the # new process group. Since a controlling terminal is associated with a # session, and this new session has not yet acquired a controlling # terminal our process now has no controlling terminal. This shouldn't # fail, since we're guaranteed that the child is not a process group # leader. os.setsid() # When the first child terminates, all processes in the second child # are sent a SIGHUP, so it's ignored. signal.signal(signal.SIGHUP, signal.SIG_IGN) try: # Fork a second child to prevent zombies. Since the first child is # a session leader without a controlling terminal, it's possible for # it to acquire one by opening a terminal in the future. This second # fork guarantees that the child is no longer a session leader, thus # preventing the daemon from ever acquiring a controlling terminal. pid = os.fork() # Fork a second child. except OSError, e: return((e.errno, e.strerror)) # ERROR (return a tuple) if (pid == 0): # The second child. # Ensure that the daemon doesn't keep any directory in use. Failure # to do this could make a filesystem unmountable. #os.chdir("/") # Give the child complete control over permissions. os.umask(0) else: os._exit(0) # Exit parent (the first child) of the second child. else: os._exit(0) # Exit parent of the first child. # Close all open files. Try the system configuration variable, SC_OPEN_MAX, # for the maximum number of open files to close. If it doesn't exist, use # the default value (configurable). try: maxfd = os.sysconf("SC_OPEN_MAX") except (AttributeError, ValueError): maxfd = 256 # default maximum for fd in range(0, maxfd): try: os.close(fd) except OSError: # ERROR (ignore) pass # Redirect the standard file descriptors to /dev/null. os.open("/dev/null", os.O_RDONLY) # standard input (0) #os.open("/dev/null", os.O_RDWR) # standard output (1) os.open("/tmp/fail2ban.log", os.O_CREAT|os.O_APPEND|os.O_RDWR) # standard output (1) #os.open("/dev/null", os.O_RDWR) # standard error (2) os.open("/tmp/fail2ban.log", os.O_CREAT|os.O_APPEND|os.O_RDWR) # standard error (2) return(0)
print 'Restoring iptables...' fireWall.flushBanList() print 'Exiting...'
logSys.info("Restoring iptables...") fireWall.flushBanList(debug) logSys.info("Exiting...")
def createDaemon(): """Detach a process from the controlling terminal and run it in the background as a daemon. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 """ try: # Fork a child process so the parent can exit. This will return control # to the command line or shell. This is required so that the new process # is guaranteed not to be a process group leader. We have this guarantee # because the process GID of the parent is inherited by the child, but # the child gets a new PID, making it impossible for its PID to equal its # PGID. pid = os.fork() except OSError, e: return((e.errno, e.strerror)) # ERROR (return a tuple) if (pid == 0): # The first child. # Next we call os.setsid() to become the session leader of this new # session. The process also becomes the process group leader of the # new process group. Since a controlling terminal is associated with a # session, and this new session has not yet acquired a controlling # terminal our process now has no controlling terminal. This shouldn't # fail, since we're guaranteed that the child is not a process group # leader. os.setsid() # When the first child terminates, all processes in the second child # are sent a SIGHUP, so it's ignored. signal.signal(signal.SIGHUP, signal.SIG_IGN) try: # Fork a second child to prevent zombies. Since the first child is # a session leader without a controlling terminal, it's possible for # it to acquire one by opening a terminal in the future. This second # fork guarantees that the child is no longer a session leader, thus # preventing the daemon from ever acquiring a controlling terminal. pid = os.fork() # Fork a second child. except OSError, e: return((e.errno, e.strerror)) # ERROR (return a tuple) if (pid == 0): # The second child. # Ensure that the daemon doesn't keep any directory in use. Failure # to do this could make a filesystem unmountable. #os.chdir("/") # Give the child complete control over permissions. os.umask(0) else: os._exit(0) # Exit parent (the first child) of the second child. else: os._exit(0) # Exit parent of the first child. # Close all open files. Try the system configuration variable, SC_OPEN_MAX, # for the maximum number of open files to close. If it doesn't exist, use # the default value (configurable). try: maxfd = os.sysconf("SC_OPEN_MAX") except (AttributeError, ValueError): maxfd = 256 # default maximum for fd in range(0, maxfd): try: os.close(fd) except OSError: # ERROR (ignore) pass # Redirect the standard file descriptors to /dev/null. os.open("/dev/null", os.O_RDONLY) # standard input (0) #os.open("/dev/null", os.O_RDWR) # standard output (1) os.open("/tmp/fail2ban.log", os.O_CREAT|os.O_APPEND|os.O_RDWR) # standard output (1) #os.open("/dev/null", os.O_RDWR) # standard error (2) os.open("/tmp/fail2ban.log", os.O_CREAT|os.O_APPEND|os.O_RDWR) # standard error (2) return(0)
print " -d start in debug mode"
def dispUsage(): """ Prints Fail2Ban command line options and exits """ print "Usage: "+sys.argv[0]+" [OPTIONS]" print print "Fail2Ban v"+version+" reads log file that contains password failure report" print "and bans the corresponding IP addresses using firewall rules." print print " -b start in background" print " -d start in debug mode" print " -c <FILE> read configuration file FILE" print " -p <FILE> create PID lock in FILE" print " -h display this help message" print " -i <IP(s)> IP(s) to ignore" print " -k kill a currently running instance" print " -r <VALUE> allow a max of VALUE password failure [maxfailures]" print " -t <TIME> ban IP for TIME seconds [bantime]" print " -f <TIME> lifetime in seconds of failed entry [findtime]" print " -v verbose. Use twice for greater effect" print " -V print software version" print print "Report bugs to <[email protected]>" sys.exit(0)
self.ssock.setblocking(True)
self.ssock.settimeout(1)
def initialize(self, force = False): # Remove socket if os.path.exists(SSocket.SOCKET_FILE): logSys.error("Fail2ban seems to be already running") if force: logSys.warn("Forcing execution of the server") os.remove(SSocket.SOCKET_FILE) else: raise SSocketErrorException("Server already running") # Create an INET, STREAMing socket #self.ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.ssock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) #self.ssock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #self.ssock.setblocking(False) self.ssock.setblocking(True) # Bind the socket to a public host and a well-known port #self.ssock.bind(("localhost", 2222)) self.ssock.bind(SSocket.SOCKET_FILE) # Become a server socket self.ssock.listen(5)
(csock, address) = self.ssock.accept() thread = SocketWorker(csock, self.transmit) thread.start()
try: (csock, address) = self.ssock.accept() thread = SocketWorker(csock, self.transmit) thread.start() except socket.timeout: pass
def run(self): self.isRunning = True while self.isRunning: # TODO Fix shutdown. A new request is required because accept() # is blocking. (csock, address) = self.ssock.accept() thread = SocketWorker(csock, self.transmit) thread.start() self.ssock.close() # Remove socket if os.path.exists(SSocket.SOCKET_FILE): logSys.debug("Removed socket file " + SSocket.SOCKET_FILE) os.remove(SSocket.SOCKET_FILE) logSys.debug("Socket shutdown") return True
print DNSUtils.ipCRE
def searchIP(text): """ Search if an IP address if directly available and return it. """ print DNSUtils.ipCRE match = DNSUtils.ipCRE.match(text) if match: return match else: return None
if isValidIP(element): ipList.append(element)
plainIPStr = plainIP.group(0) if DNSUtils.isValidIP(plainIPStr): ipList.append(plainIPStr)
def textToIp(text): """ Return the IP of DNS found in a given text. """ ipList = list() # Search for plain IP plainIP = DNSUtils.searchIP(text) if not plainIP == None: if isValidIP(element): ipList.append(element) if not ipList: # Try to get IP from possible DNS dnsList = DNSUtils.textToDns(text) if not dnsList == None: dns = DNSUtils.dnsToIp(element) for e in dns: ipList.append(e) return ipList
dnsList = DNSUtils.textToDns(text) if not dnsList == None: dns = DNSUtils.dnsToIp(element) for e in dns:
dns = DNSUtils.textToDns(text) if not dns == None: ip = DNSUtils.dnsToIp(dns.group(0)) for e in ip:
def textToIp(text): """ Return the IP of DNS found in a given text. """ ipList = list() # Search for plain IP plainIP = DNSUtils.searchIP(text) if not plainIP == None: if isValidIP(element): ipList.append(element) if not ipList: # Try to get IP from possible DNS dnsList = DNSUtils.textToDns(text) if not dnsList == None: dns = DNSUtils.dnsToIp(element) for e in dns: ipList.append(e) return ipList
match = re.findall("\S*\.\w*\.\w*", text)
match = re.findall("(?:(?:\w|-)+\.){2,}\w+", text)
def textToDns(text): """ Search for possible DNS in an arbitrary text. """ match = re.findall("\S*\.\w*\.\w*", text) if match: return match else: return []
if element[1][0] >= retryAllowed:
if element[1][0] >= conf["maxretry"]:
def createDaemon(): """Detach a process from the controlling terminal and run it in the background as a daemon. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 """ try: # Fork a child process so the parent can exit. This will return control # to the command line or shell. This is required so that the new process # is guaranteed not to be a process group leader. We have this guarantee # because the process GID of the parent is inherited by the child, but # the child gets a new PID, making it impossible for its PID to equal its # PGID. pid = os.fork() except OSError, e: return((e.errno, e.strerror)) # ERROR (return a tuple) if (pid == 0): # The first child. # Next we call os.setsid() to become the session leader of this new # session. The process also becomes the process group leader of the # new process group. Since a controlling terminal is associated with a # session, and this new session has not yet acquired a controlling # terminal our process now has no controlling terminal. This shouldn't # fail, since we're guaranteed that the child is not a process group # leader. os.setsid() # When the first child terminates, all processes in the second child # are sent a SIGHUP, so it's ignored. signal.signal(signal.SIGHUP, signal.SIG_IGN) try: # Fork a second child to prevent zombies. Since the first child is # a session leader without a controlling terminal, it's possible for # it to acquire one by opening a terminal in the future. This second # fork guarantees that the child is no longer a session leader, thus # preventing the daemon from ever acquiring a controlling terminal. pid = os.fork() # Fork a second child. except OSError, e: return((e.errno, e.strerror)) # ERROR (return a tuple) if (pid == 0): # The second child. # Ensure that the daemon doesn't keep any directory in use. Failure # to do this could make a filesystem unmountable. os.chdir("/") # Give the child complete control over permissions. os.umask(0) else: os._exit(0) # Exit parent (the first child) of the second child. else: os._exit(0) # Exit parent of the first child. # Close all open files. Try the system configuration variable, SC_OPEN_MAX, # for the maximum number of open files to close. If it doesn't exist, use # the default value (configurable). try: maxfd = os.sysconf("SC_OPEN_MAX") except (AttributeError, ValueError): maxfd = 256 # default maximum for fd in range(0, maxfd): try: os.close(fd) except OSError: # ERROR (ignore) pass # Redirect the standard file descriptors to /dev/null. os.open("/dev/null", os.O_RDONLY) # standard input (0) os.open("/dev/null", os.O_RDWR) # standard output (1) os.open("/dev/null", os.O_RDWR) # standard error (2) return(0)
return os.kill(pid, 2)
try: return os.kill(pid, 2) except OSError: logSys.error("Can not kill process " + `pid` + ". Please check that " + "Fail2Ban is not running and remove the file " + "'/tmp/fail2ban.pid'")
def killPID(pid): """ Kills the process with the given PID using the INT signal (same effect as <ctrl>+<c>). """ return os.kill(pid, 2)
_checkLoadAttr(self, 'schema')
self._checkLoadAttr('schema')
def beforeChange_schema(self): """Load the values of fields from according to fields_map if present. Each key in fields_map is a field in the old schema and each value is a field in the new schema. If fields_map isn't a mapping, each filed in the old schema will be migrated into the new schema. Obeys field modes for readable and writable fields. These values are then passed in as field kwargs into the constructor in the createNew method.""" _checkLoadAttr(self, 'schema')
self.old._v_is_cp = is_cp
self.new._v_is_cp = is_cp
def migrate_references(self): """Migrate references annotation.""" # Restor the references annotation if hasattr(self, REFERENCE_ANNOTATION): at_references = getattr(self, REFERENCE_ANNOTATION) setattr(self.new, REFERENCE_ANNOTATION, at_references) # Run the reference manage_afterAdd to transition all copied # references is_cp = getattr(self.old, '_v_is_cp', _marker) self.new._v_is_cp = 0 Referenceable.manage_afterAdd(self.new, self.new, self.new.getParentNode()) if is_cp is not _marker: self.old._v_is_cp = is_cp else: del self.old._v_is_cp