"Fossies" - the Fresh Open Source Software Archive  

Source code changes of the file "fail2ban/server/actions.py" between
fail2ban-0.10.5.tar.gz and fail2ban-0.11.1.tar.gz

About:

actions.py  (fail2ban-0.10.5):actions.py  (fail2ban-0.11.1)
skipping to change at line 42 skipping to change at line 42
try: try:
from collections import OrderedDict from collections import OrderedDict
except ImportError: except ImportError:
OrderedDict = dict OrderedDict = dict
from .banmanager import BanManager, BanTicket from .banmanager import BanManager, BanTicket
from .ipdns import IPAddr from .ipdns import IPAddr
from .jailthread import JailThread from .jailthread import JailThread
from .action import ActionBase, CommandAction, CallingMap from .action import ActionBase, CommandAction, CallingMap
from .mytime import MyTime from .mytime import MyTime
from .observer import Observers
from .utils import Utils from .utils import Utils
from ..helpers import getLogger from ..helpers import getLogger
# Gets the instance of the logger. # Gets the instance of the logger.
logSys = getLogger(__name__) logSys = getLogger(__name__)
class Actions(JailThread, Mapping): class Actions(JailThread, Mapping):
"""Handles jail actions. """Handles jail actions.
This class handles the actions of the jail. Creation, deletion or to This class handles the actions of the jail. Creation, deletion or to
skipping to change at line 211 skipping to change at line 212
logSys.info(" banTime: %s" % value) logSys.info(" banTime: %s" % value)
## ##
# Get the ban time. # Get the ban time.
# #
# @return the time # @return the time
def getBanTime(self): def getBanTime(self):
return self.__banManager.getBanTime() return self.__banManager.getBanTime()
def getBanList(self, withTime=False):
"""Returns the list of banned IP addresses.
Returns
-------
list
The list of banned IP addresses.
"""
return self.__banManager.getBanList(ordered=True, withTime=withTi
me)
def addBannedIP(self, ip): def addBannedIP(self, ip):
"""Ban an IP or list of IPs.""" """Ban an IP or list of IPs."""
unixTime = MyTime.time() unixTime = MyTime.time()
if isinstance(ip, list): if isinstance(ip, list):
# Multiple IPs: # Multiple IPs:
tickets = (BanTicket(ip, unixTime) for ip in ip) tickets = (BanTicket(ip, unixTime) for ip in ip)
else: else:
# Single IP: # Single IP:
tickets = (BanTicket(ip, unixTime),) tickets = (BanTicket(ip, unixTime),)
skipping to change at line 343 skipping to change at line 354
CM_REPR_ITEMS = ("fid", "raw-ticket") CM_REPR_ITEMS = ("fid", "raw-ticket")
AI_DICT = { AI_DICT = {
"ip": lambda self: self.__ticke t.getIP(), "ip": lambda self: self.__ticke t.getIP(),
"family": lambda self: self['ip'].familyStr, "family": lambda self: self['ip'].familyStr,
"ip-rev": lambda self: self['ip'].getPTR('' ), "ip-rev": lambda self: self['ip'].getPTR('' ),
"ip-host": lambda self: self['ip'].getHost(), "ip-host": lambda self: self['ip'].getHost(),
"fid": lambda self: self.__ticket.getID( ), "fid": lambda self: self.__ticket.getID( ),
"failures": lambda self: self.__ticket.getAttempt(), "failures": lambda self: self.__ticket.getAttempt(),
"time": lambda self: self.__ticket.getTim e(), "time": lambda self: self.__ticket.getTim e(),
"bantime": lambda self: self._getBanTime(),
"bancount": lambda self: self.__ticket.getBanCount(),
"matches": lambda self: "\n".join(self.__ticket.getM atches()), "matches": lambda self: "\n".join(self.__ticket.getM atches()),
# to bypass actions, that should not be executed for rest ored tickets # to bypass actions, that should not be executed for rest ored tickets
"restored": lambda self: (1 if self.__ticket.restored else 0), "restored": lambda self: (1 if self.__ticket.restored else 0),
# extra-interpolation - all match-tags (captured from the filter): # extra-interpolation - all match-tags (captured from the filter):
"F-*": lambda self, tag=None: self.__tic ket.getData(tag), "F-*": lambda self, tag=None: self.__tic ket.getData(tag),
# merged info: # merged info:
"ipmatches": lambda self: "\n".join(se lf._mi4ip(True).getMatches()), "ipmatches": lambda self: "\n".join(se lf._mi4ip(True).getMatches()),
"ipjailmatches": lambda self: "\n".join(self._mi4i p().getMatches()), "ipjailmatches": lambda self: "\n".join(self._mi4i p().getMatches()),
"ipfailures": lambda self: self._mi4ip( True).getAttempt(), "ipfailures": lambda self: self._mi4ip( True).getAttempt(),
"ipjailfailures": lambda self: self._mi4ip().getAtt empt(), "ipjailfailures": lambda self: self._mi4ip().getAtt empt(),
skipping to change at line 369 skipping to change at line 382
def __init__(self, ticket, jail=None, immutable=True, data=AI_DIC T): def __init__(self, ticket, jail=None, immutable=True, data=AI_DIC T):
self.__ticket = ticket self.__ticket = ticket
self.__jail = jail self.__jail = jail
self.storage = dict() self.storage = dict()
self.immutable = immutable self.immutable = immutable
self.data = data self.data = data
def copy(self): # pragma: no cover def copy(self): # pragma: no cover
return self.__class__(self.__ticket, self.__jail, self.im mutable, self.data.copy()) return self.__class__(self.__ticket, self.__jail, self.im mutable, self.data.copy())
def _getBanTime(self):
btime = self.__ticket.getBanTime()
if btime is None: btime = self.__jail.actions.getBanTime(
)
return int(btime)
def _mi4ip(self, overalljails=False): def _mi4ip(self, overalljails=False):
"""Gets bans merged once, a helper for lambda(s), prevent s stop of executing action by any exception inside. """Gets bans merged once, a helper for lambda(s), prevent s stop of executing action by any exception inside.
This function never returns None for ainfo lambdas - alwa ys a ticket (merged or single one) This function never returns None for ainfo lambdas - alwa ys a ticket (merged or single one)
and prevents any errors through merging (to guarantee ban actions will be executed). and prevents any errors through merging (to guarantee ban actions will be executed).
[TODO] move merging to observer - here we could wait for merge and read already merged info from a database [TODO] move merging to observer - here we could wait for merge and read already merged info from a database
Parameters Parameters
---------- ----------
overalljails : bool overalljails : bool
skipping to change at line 441 skipping to change at line 459
Returns Returns
------- -------
bool bool
True if an IP address get banned. True if an IP address get banned.
""" """
cnt = 0 cnt = 0
if not tickets: if not tickets:
tickets = self.__getFailTickets(self.banPrecedence) tickets = self.__getFailTickets(self.banPrecedence)
rebanacts = None rebanacts = None
for ticket in tickets: for ticket in tickets:
bTicket = BanManager.createBanTicket(ticket)
bTicket = BanTicket.wrap(ticket)
btime = ticket.getBanTime(self.__banManager.getBanTime())
ip = bTicket.getIP() ip = bTicket.getIP()
aInfo = self.__getActionInfo(bTicket) aInfo = self.__getActionInfo(bTicket)
reason = {} reason = {}
if self.__banManager.addBanTicket(bTicket, reason=reason) : if self.__banManager.addBanTicket(bTicket, reason=reason) :
cnt += 1 cnt += 1
# report ticket to observer, to check time should
be increased and hereafter observer writes ban to database (asynchronous)
if Observers.Main is not None and not bTicket.res
tored:
Observers.Main.add('banFound', bTicket, s
elf._jail, btime)
logSys.notice("[%s] %sBan %s", self._jail.name, ( '' if not bTicket.restored else 'Restore '), ip) logSys.notice("[%s] %sBan %s", self._jail.name, ( '' if not bTicket.restored else 'Restore '), ip)
# do actions :
for name, action in self._actions.iteritems(): for name, action in self._actions.iteritems():
try: try:
if ticket.restored and getattr(ac tion, 'norestored', False): if ticket.restored and getattr(ac tion, 'norestored', False):
continue continue
if not aInfo.immutable: aInfo.res et() if not aInfo.immutable: aInfo.res et()
action.ban(aInfo) action.ban(aInfo)
except Exception as e: except Exception as e:
logSys.error( logSys.error(
"Failed to execute ban ja il '%s' action '%s' " "Failed to execute ban ja il '%s' action '%s' "
"info '%r': %s", "info '%r': %s",
self._jail.name, name, aI nfo, e, self._jail.name, name, aI nfo, e,
exc_info=logSys.getEffect iveLevel()<=logging.DEBUG) exc_info=logSys.getEffect iveLevel()<=logging.DEBUG)
# after all actions are processed set banned flag : # after all actions are processed set banned flag :
bTicket.banned = True bTicket.banned = True
if self.banEpoch: # be sure tickets always have t he same ban epoch (default 0): if self.banEpoch: # be sure tickets always have t he same ban epoch (default 0):
bTicket.banEpoch = self.banEpoch bTicket.banEpoch = self.banEpoch
else: else:
bTicket = reason['ticket'] if reason.get('expired', 0):
logSys.info('[%s] Ignore %s, expired bant
ime', self._jail.name, ip)
continue
bTicket = reason.get('ticket', bTicket)
# if already banned (otherwise still process some action) # if already banned (otherwise still process some action)
if bTicket.banned: if bTicket.banned:
# compare time of failure occurrence with time ticket was really banned: # compare time of failure occurrence with time ticket was really banned:
diftm = ticket.getTime() - bTicket.getTim e() diftm = ticket.getTime() - bTicket.getTim e()
# log already banned with following level : # log already banned with following level :
# DEBUG - before 3 seconds - certain interval for it, because of possible latency by recognizing in backends, etc. # DEBUG - before 3 seconds - certain interval for it, because of possible latency by recognizing in backends, etc.
# NOTICE - before 60 seconds - may sti ll occur if action is slow, or very high load in backend, # NOTICE - before 60 seconds - may sti ll occur if action is slow, or very high load in backend,
# WARNING - after 60 seconds - very lon g time, something may be wrong # WARNING - after 60 seconds - very lon g time, something may be wrong
ll = logging.DEBUG if diftm < 3 \ ll = logging.DEBUG if diftm < 3 \
else logging.NOTICE if diftm < 60 \ else logging.NOTICE if diftm < 60 \
skipping to change at line 532 skipping to change at line 559
"info '%r': %s", "info '%r': %s",
self._jail.name, name, aInfo, e, self._jail.name, name, aInfo, e,
exc_info=logSys.getEffectiveLevel()<=logg ing.DEBUG) exc_info=logSys.getEffectiveLevel()<=logg ing.DEBUG)
return 0 return 0
# after all actions are processed set banned flag: # after all actions are processed set banned flag:
ticket.banned = True ticket.banned = True
if self.banEpoch: # be sure tickets always have the same ban epoc h (default 0): if self.banEpoch: # be sure tickets always have the same ban epoc h (default 0):
ticket.banEpoch = self.banEpoch ticket.banEpoch = self.banEpoch
return 1 return 1
def _prolongBan(self, ticket):
# prevent to prolong ticket that was removed in-between,
# if it in ban list - ban time already prolonged (and it stays th
ere):
if not self.__banManager._inBanList(ticket): return
# do actions :
aInfo = None
for name, action in self._actions.iteritems():
try:
if ticket.restored and getattr(action, 'norestore
d', False):
continue
if not action._prolongable:
continue
if aInfo is None:
aInfo = self.__getActionInfo(ticket)
if not aInfo.immutable: aInfo.reset()
action.prolong(aInfo)
except Exception as e:
logSys.error(
"Failed to execute ban jail '%s' action '
%s' "
"info '%r': %s",
self._jail.name, name, aInfo, e,
exc_info=logSys.getEffectiveLevel()<=logg
ing.DEBUG)
def __checkUnBan(self, maxCount=None): def __checkUnBan(self, maxCount=None):
"""Check for IP address to unban. """Check for IP address to unban.
Unban IP addresses which are outdated. Unban IP addresses which are outdated.
""" """
lst = self.__banManager.unBanList(MyTime.time(), maxCount) lst = self.__banManager.unBanList(MyTime.time(), maxCount)
for ticket in lst: for ticket in lst:
self.__unBan(ticket) self.__unBan(ticket)
cnt = len(lst) cnt = len(lst)
if cnt: if cnt:
 End of changes. 9 change blocks. 
2 lines changed or deleted 62 lines changed or added

Home  |  About  |  Features  |  All  |  Newest  |  Dox  |  Diffs  |  RSS Feeds  |  Screenshots  |  Comments  |  Imprint  |  Privacy  |  HTTP(S)