2014-02-09 12:23:14 +00:00
|
|
|
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: t -*-
|
|
|
|
# vi: set ft=python sts=4 ts=4 sw=4 noet :
|
|
|
|
|
|
|
|
# This file is part of Fail2Ban.
|
|
|
|
#
|
|
|
|
# Fail2Ban is free software; you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation; either version 2 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# Fail2Ban is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with Fail2Ban; if not, write to the Free Software
|
|
|
|
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
|
|
|
|
2014-03-12 21:54:15 +00:00
|
|
|
import sys
|
2018-07-05 14:27:36 +00:00
|
|
|
if sys.version_info < (2, 7): # pragma: no cover
|
2014-03-12 21:54:15 +00:00
|
|
|
raise ImportError("badips.py action requires Python >= 2.7")
|
2014-02-09 12:23:14 +00:00
|
|
|
import json
|
|
|
|
import threading
|
2014-02-14 17:10:34 +00:00
|
|
|
import logging
|
2018-07-05 14:27:36 +00:00
|
|
|
if sys.version_info >= (3, ): # pragma: 2.x no cover
|
2014-02-09 12:23:14 +00:00
|
|
|
from urllib.request import Request, urlopen
|
|
|
|
from urllib.parse import urlencode
|
|
|
|
from urllib.error import HTTPError
|
2018-07-05 14:27:36 +00:00
|
|
|
else: # pragma: 3.x no cover
|
2014-02-09 12:23:14 +00:00
|
|
|
from urllib2 import Request, urlopen, HTTPError
|
|
|
|
from urllib import urlencode
|
|
|
|
|
|
|
|
from fail2ban.server.actions import ActionBase
|
2018-10-02 10:32:15 +00:00
|
|
|
from fail2ban.helpers import str2LogLevel
|
|
|
|
|
2014-02-09 12:23:14 +00:00
|
|
|
|
2015-07-04 17:47:40 +00:00
|
|
|
|
2016-09-30 09:28:21 +00:00
|
|
|
class BadIPsAction(ActionBase): # pragma: no cover - may be unavailable
|
2014-04-23 14:04:17 +00:00
|
|
|
"""Fail2Ban action which reports bans to badips.com, and also
|
2014-02-09 12:23:14 +00:00
|
|
|
blacklist bad IPs listed on badips.com by using another action's
|
|
|
|
ban method.
|
2014-03-13 19:58:32 +00:00
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
jail : Jail
|
|
|
|
The jail which the action belongs to.
|
|
|
|
name : str
|
|
|
|
Name assigned to the action.
|
|
|
|
category : str
|
|
|
|
Valid badips.com category for reporting failures.
|
|
|
|
score : int, optional
|
2014-03-13 22:05:50 +00:00
|
|
|
Minimum score for bad IPs. Default 3.
|
2014-03-13 19:58:32 +00:00
|
|
|
age : str, optional
|
|
|
|
Age of last report for bad IPs, per badips.com syntax.
|
|
|
|
Default "24h" (24 hours)
|
2014-04-23 14:04:17 +00:00
|
|
|
key : str, optional
|
2014-03-13 22:45:10 +00:00
|
|
|
Key issued by badips.com to report bans, for later retrieval
|
|
|
|
of personalised content.
|
2014-03-13 19:58:32 +00:00
|
|
|
banaction : str, optional
|
|
|
|
Name of banaction to use for blacklisting bad IPs. If `None`,
|
|
|
|
no blacklist of IPs will take place.
|
|
|
|
Default `None`.
|
|
|
|
bancategory : str, optional
|
|
|
|
Name of category to use for blacklisting, which can differ
|
|
|
|
from category used for reporting. e.g. may want to report
|
|
|
|
"postfix", but want to use whole "mail" category for blacklist.
|
|
|
|
Default `category`.
|
2014-04-23 14:04:17 +00:00
|
|
|
bankey : str, optional
|
2014-03-13 22:45:10 +00:00
|
|
|
Key issued by badips.com to blacklist IPs reported with the
|
|
|
|
associated key.
|
2014-03-13 19:58:32 +00:00
|
|
|
updateperiod : int, optional
|
|
|
|
Time in seconds between updating bad IPs blacklist.
|
|
|
|
Default 900 (15 minutes)
|
2018-10-02 10:32:15 +00:00
|
|
|
loglevel : int/str, optional
|
|
|
|
Log level of the message when an IP is (un)banned.
|
|
|
|
Default `DEBUG`.
|
2015-12-31 01:30:25 +00:00
|
|
|
agent : str, optional
|
|
|
|
User agent transmitted to server.
|
|
|
|
Default `Fail2Ban/ver.`
|
2014-03-13 19:58:32 +00:00
|
|
|
|
|
|
|
Raises
|
|
|
|
------
|
|
|
|
ValueError
|
|
|
|
If invalid `category`, `score`, `banaction` or `updateperiod`.
|
2014-02-09 12:23:14 +00:00
|
|
|
"""
|
2014-03-13 19:58:32 +00:00
|
|
|
|
2016-06-10 11:15:46 +00:00
|
|
|
TIMEOUT = 10
|
2018-02-26 08:58:37 +00:00
|
|
|
_badips = "https://www.badips.com"
|
2015-12-31 01:30:25 +00:00
|
|
|
def _Request(self, url, **argv):
|
|
|
|
return Request(url, headers={'User-Agent': self.agent}, **argv)
|
2014-02-09 12:23:14 +00:00
|
|
|
|
2014-03-13 22:45:10 +00:00
|
|
|
def __init__(self, jail, name, category, score=3, age="24h", key=None,
|
2018-10-02 10:32:15 +00:00
|
|
|
banaction=None, bancategory=None, bankey=None, updateperiod=900, loglevel='DEBUG', agent="Fail2Ban",
|
2016-06-10 11:15:46 +00:00
|
|
|
timeout=TIMEOUT):
|
2014-02-09 12:23:14 +00:00
|
|
|
super(BadIPsAction, self).__init__(jail, name)
|
|
|
|
|
2016-06-10 11:15:46 +00:00
|
|
|
self.timeout = timeout
|
2016-01-04 08:30:32 +00:00
|
|
|
self.agent = agent
|
2014-02-09 12:23:14 +00:00
|
|
|
self.category = category
|
|
|
|
self.score = score
|
|
|
|
self.age = age
|
2014-03-13 22:45:10 +00:00
|
|
|
self.key = key
|
2014-02-09 12:23:14 +00:00
|
|
|
self.banaction = banaction
|
2014-02-14 17:45:08 +00:00
|
|
|
self.bancategory = bancategory or category
|
2014-03-13 22:45:10 +00:00
|
|
|
self.bankey = bankey
|
2018-10-02 10:38:29 +00:00
|
|
|
self.loglevel = str2LogLevel(loglevel)
|
2014-02-09 12:23:14 +00:00
|
|
|
self.updateperiod = updateperiod
|
|
|
|
|
|
|
|
self._bannedips = set()
|
|
|
|
# Used later for threading.Timer for updating badips
|
|
|
|
self._timer = None
|
|
|
|
|
2016-09-30 09:28:21 +00:00
|
|
|
@staticmethod
|
|
|
|
def isAvailable(timeout=1):
|
|
|
|
try:
|
|
|
|
response = urlopen(Request("/".join([BadIPsAction._badips]),
|
|
|
|
headers={'User-Agent': "Fail2Ban"}), timeout=timeout)
|
|
|
|
return True, ''
|
|
|
|
except Exception as e: # pragma: no cover
|
|
|
|
return False, e
|
|
|
|
|
2018-04-05 09:26:43 +00:00
|
|
|
def logError(self, response, what=''): # pragma: no cover - sporadical (502: Bad Gateway, etc)
|
|
|
|
messages = {}
|
|
|
|
try:
|
|
|
|
messages = json.loads(response.read().decode('utf-8'))
|
|
|
|
except:
|
|
|
|
pass
|
|
|
|
self._logSys.error(
|
|
|
|
"%s. badips.com response: '%s'", what,
|
|
|
|
messages.get('err', 'Unknown'))
|
2016-09-30 09:28:21 +00:00
|
|
|
|
2014-03-16 14:18:19 +00:00
|
|
|
def getCategories(self, incParents=False):
|
2014-02-09 12:23:14 +00:00
|
|
|
"""Get badips.com categories.
|
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
|
|
|
set
|
|
|
|
Set of categories.
|
|
|
|
|
|
|
|
Raises
|
|
|
|
------
|
|
|
|
HTTPError
|
|
|
|
Any issues with badips.com request.
|
2015-02-13 13:51:10 +00:00
|
|
|
ValueError
|
|
|
|
If badips.com response didn't contain necessary information
|
2014-02-09 12:23:14 +00:00
|
|
|
"""
|
|
|
|
try:
|
|
|
|
response = urlopen(
|
2016-06-10 11:15:46 +00:00
|
|
|
self._Request("/".join([self._badips, "get", "categories"])), timeout=self.timeout)
|
2018-04-05 09:26:43 +00:00
|
|
|
except HTTPError as response: # pragma: no cover
|
|
|
|
self.logError(response, "Failed to fetch categories")
|
2014-02-09 12:23:14 +00:00
|
|
|
raise
|
|
|
|
else:
|
2015-02-13 13:51:10 +00:00
|
|
|
response_json = json.loads(response.read().decode('utf-8'))
|
|
|
|
if not 'categories' in response_json:
|
|
|
|
err = "badips.com response lacked categories specification. Response was: %s" \
|
|
|
|
% (response_json,)
|
|
|
|
self._logSys.error(err)
|
|
|
|
raise ValueError(err)
|
|
|
|
categories = response_json['categories']
|
2014-02-09 12:23:14 +00:00
|
|
|
categories_names = set(
|
|
|
|
value['Name'] for value in categories)
|
2014-02-14 17:45:08 +00:00
|
|
|
if incParents:
|
|
|
|
categories_names.update(set(
|
|
|
|
value['Parent'] for value in categories
|
|
|
|
if "Parent" in value))
|
2014-02-09 12:23:14 +00:00
|
|
|
return categories_names
|
|
|
|
|
2014-03-16 14:18:19 +00:00
|
|
|
def getList(self, category, score, age, key=None):
|
2014-02-09 12:23:14 +00:00
|
|
|
"""Get badips.com list of bad IPs.
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
category : str
|
|
|
|
Valid badips.com category.
|
|
|
|
score : int
|
|
|
|
Minimum score for bad IPs.
|
|
|
|
age : str
|
|
|
|
Age of last report for bad IPs, per badips.com syntax.
|
2014-03-13 22:45:10 +00:00
|
|
|
key : str, optional
|
|
|
|
Key issued by badips.com to fetch IPs reported with the
|
|
|
|
associated key.
|
2014-02-09 12:23:14 +00:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
|
|
|
set
|
|
|
|
Set of bad IPs.
|
|
|
|
|
|
|
|
Raises
|
|
|
|
------
|
|
|
|
HTTPError
|
|
|
|
Any issues with badips.com request.
|
|
|
|
"""
|
|
|
|
try:
|
2014-03-13 22:45:10 +00:00
|
|
|
url = "?".join([
|
2014-03-16 14:18:19 +00:00
|
|
|
"/".join([self._badips, "get", "list", category, str(score)]),
|
2014-03-13 22:45:10 +00:00
|
|
|
urlencode({'age': age})])
|
|
|
|
if key:
|
2014-06-07 19:51:53 +00:00
|
|
|
url = "&".join([url, urlencode({'key': key})])
|
2018-02-26 17:16:20 +00:00
|
|
|
self._logSys.debug('badips.com: get list, url: %r', url)
|
2016-06-10 11:15:46 +00:00
|
|
|
response = urlopen(self._Request(url), timeout=self.timeout)
|
2018-04-05 09:26:43 +00:00
|
|
|
except HTTPError as response: # pragma: no cover
|
|
|
|
self.logError(response, "Failed to fetch bad IP list")
|
2014-02-09 12:23:14 +00:00
|
|
|
raise
|
|
|
|
else:
|
|
|
|
return set(response.read().decode('utf-8').split())
|
|
|
|
|
|
|
|
@property
|
|
|
|
def category(self):
|
2014-02-14 17:45:08 +00:00
|
|
|
"""badips.com category for reporting IPs.
|
2014-02-09 12:23:14 +00:00
|
|
|
"""
|
|
|
|
return self._category
|
|
|
|
|
|
|
|
@category.setter
|
|
|
|
def category(self, category):
|
|
|
|
if category not in self.getCategories():
|
|
|
|
self._logSys.error("Category name '%s' not valid. "
|
|
|
|
"see badips.com for list of valid categories",
|
|
|
|
category)
|
|
|
|
raise ValueError("Invalid category: %s" % category)
|
|
|
|
self._category = category
|
|
|
|
|
2014-02-14 17:45:08 +00:00
|
|
|
@property
|
|
|
|
def bancategory(self):
|
|
|
|
"""badips.com bancategory for fetching IPs.
|
|
|
|
"""
|
|
|
|
return self._bancategory
|
|
|
|
|
|
|
|
@bancategory.setter
|
|
|
|
def bancategory(self, bancategory):
|
2018-02-27 09:12:22 +00:00
|
|
|
if bancategory != "any" and bancategory not in self.getCategories(incParents=True):
|
2014-02-14 17:45:08 +00:00
|
|
|
self._logSys.error("Category name '%s' not valid. "
|
|
|
|
"see badips.com for list of valid categories",
|
|
|
|
bancategory)
|
|
|
|
raise ValueError("Invalid bancategory: %s" % bancategory)
|
|
|
|
self._bancategory = bancategory
|
|
|
|
|
2014-02-09 12:23:14 +00:00
|
|
|
@property
|
|
|
|
def score(self):
|
|
|
|
"""badips.com minimum score for fetching IPs.
|
|
|
|
"""
|
|
|
|
return self._score
|
|
|
|
|
|
|
|
@score.setter
|
|
|
|
def score(self, score):
|
|
|
|
score = int(score)
|
|
|
|
if 0 <= score <= 5:
|
|
|
|
self._score = score
|
|
|
|
else:
|
|
|
|
raise ValueError("Score must be 0-5")
|
|
|
|
|
|
|
|
@property
|
|
|
|
def banaction(self):
|
|
|
|
"""Jail action to use for banning/unbanning.
|
|
|
|
"""
|
|
|
|
return self._banaction
|
|
|
|
|
|
|
|
@banaction.setter
|
|
|
|
def banaction(self, banaction):
|
|
|
|
if banaction is not None and banaction not in self._jail.actions:
|
|
|
|
self._logSys.error("Action name '%s' not in jail '%s'",
|
2014-03-13 20:01:15 +00:00
|
|
|
banaction, self._jail.name)
|
2014-02-09 12:23:14 +00:00
|
|
|
raise ValueError("Invalid banaction")
|
|
|
|
self._banaction = banaction
|
|
|
|
|
|
|
|
@property
|
|
|
|
def updateperiod(self):
|
|
|
|
"""Period in seconds between banned bad IPs will be updated.
|
|
|
|
"""
|
|
|
|
return self._updateperiod
|
|
|
|
|
|
|
|
@updateperiod.setter
|
|
|
|
def updateperiod(self, updateperiod):
|
|
|
|
updateperiod = int(updateperiod)
|
|
|
|
if updateperiod > 0:
|
|
|
|
self._updateperiod = updateperiod
|
|
|
|
else:
|
|
|
|
raise ValueError("Update period must be integer greater than 0")
|
|
|
|
|
|
|
|
def _banIPs(self, ips):
|
|
|
|
for ip in ips:
|
2014-02-14 17:10:34 +00:00
|
|
|
try:
|
|
|
|
self._jail.actions[self.banaction].ban({
|
|
|
|
'ip': ip,
|
|
|
|
'failures': 0,
|
|
|
|
'matches': "",
|
|
|
|
'ipmatches': "",
|
|
|
|
'ipjailmatches': "",
|
|
|
|
})
|
|
|
|
except Exception as e:
|
|
|
|
self._logSys.error(
|
|
|
|
"Error banning IP %s for jail '%s' with action '%s': %s",
|
2014-03-13 20:01:15 +00:00
|
|
|
ip, self._jail.name, self.banaction, e,
|
2014-04-12 10:21:52 +00:00
|
|
|
exc_info=self._logSys.getEffectiveLevel()<=logging.DEBUG)
|
2014-02-14 17:10:34 +00:00
|
|
|
else:
|
|
|
|
self._bannedips.add(ip)
|
2018-10-02 10:32:15 +00:00
|
|
|
self._logSys.log(self.loglevel,
|
|
|
|
"Banned IP %s for jail '%s' with action '%s'",
|
|
|
|
ip, self._jail.name, self.banaction)
|
2014-02-09 12:23:14 +00:00
|
|
|
|
|
|
|
def _unbanIPs(self, ips):
|
|
|
|
for ip in ips:
|
2014-02-14 17:10:34 +00:00
|
|
|
try:
|
|
|
|
self._jail.actions[self.banaction].unban({
|
|
|
|
'ip': ip,
|
|
|
|
'failures': 0,
|
|
|
|
'matches': "",
|
|
|
|
'ipmatches': "",
|
|
|
|
'ipjailmatches': "",
|
|
|
|
})
|
|
|
|
except Exception as e:
|
2018-08-19 20:35:09 +00:00
|
|
|
self._logSys.error(
|
2014-02-14 17:10:34 +00:00
|
|
|
"Error unbanning IP %s for jail '%s' with action '%s': %s",
|
2014-03-13 20:01:15 +00:00
|
|
|
ip, self._jail.name, self.banaction, e,
|
2014-04-12 10:21:52 +00:00
|
|
|
exc_info=self._logSys.getEffectiveLevel()<=logging.DEBUG)
|
2014-02-14 17:10:34 +00:00
|
|
|
else:
|
2018-10-02 10:32:15 +00:00
|
|
|
self._logSys.log(self.loglevel,
|
|
|
|
"Unbanned IP %s for jail '%s' with action '%s'",
|
|
|
|
ip, self._jail.name, self.banaction)
|
2014-02-14 17:10:34 +00:00
|
|
|
finally:
|
|
|
|
self._bannedips.remove(ip)
|
2014-02-09 12:23:14 +00:00
|
|
|
|
|
|
|
def start(self):
|
|
|
|
"""If `banaction` set, blacklists bad IPs.
|
|
|
|
"""
|
|
|
|
if self.banaction is not None:
|
2014-02-14 17:10:34 +00:00
|
|
|
self.update()
|
2014-02-09 12:23:14 +00:00
|
|
|
|
|
|
|
def update(self):
|
|
|
|
"""If `banaction` set, updates blacklisted IPs.
|
|
|
|
|
|
|
|
Queries badips.com for list of bad IPs, removing IPs from the
|
|
|
|
blacklist if no longer present, and adds new bad IPs to the
|
|
|
|
blacklist.
|
|
|
|
"""
|
|
|
|
if self.banaction is not None:
|
|
|
|
if self._timer:
|
|
|
|
self._timer.cancel()
|
|
|
|
self._timer = None
|
|
|
|
|
2014-02-14 17:10:34 +00:00
|
|
|
try:
|
2014-03-13 22:45:10 +00:00
|
|
|
ips = self.getList(
|
|
|
|
self.bancategory, self.score, self.age, self.bankey)
|
2014-02-14 17:10:34 +00:00
|
|
|
# Remove old IPs no longer listed
|
2018-09-08 07:28:42 +00:00
|
|
|
s = self._bannedips - ips
|
|
|
|
m = len(s)
|
|
|
|
self._unbanIPs(s)
|
2014-02-14 17:10:34 +00:00
|
|
|
# Add new IPs which are now listed
|
2018-09-08 07:28:42 +00:00
|
|
|
s = ips - self._bannedips
|
|
|
|
p = len(s)
|
|
|
|
self._banIPs(s)
|
2018-10-02 10:38:29 +00:00
|
|
|
self._logSys.log(self.loglevel,
|
2018-09-08 07:28:42 +00:00
|
|
|
"Updated IPs for jail '%s' (-%d/+%d). Update again in %i seconds",
|
|
|
|
self._jail.name, m, p, self.updateperiod)
|
2014-02-14 17:10:34 +00:00
|
|
|
finally:
|
|
|
|
self._timer = threading.Timer(self.updateperiod, self.update)
|
|
|
|
self._timer.start()
|
2014-02-09 12:23:14 +00:00
|
|
|
|
|
|
|
def stop(self):
|
|
|
|
"""If `banaction` set, clears blacklisted IPs.
|
|
|
|
"""
|
|
|
|
if self.banaction is not None:
|
|
|
|
if self._timer:
|
|
|
|
self._timer.cancel()
|
|
|
|
self._timer = None
|
|
|
|
self._unbanIPs(self._bannedips.copy())
|
|
|
|
|
|
|
|
def ban(self, aInfo):
|
|
|
|
"""Reports banned IP to badips.com.
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
aInfo : dict
|
|
|
|
Dictionary which includes information in relation to
|
|
|
|
the ban.
|
|
|
|
|
|
|
|
Raises
|
|
|
|
------
|
|
|
|
HTTPError
|
|
|
|
Any issues with badips.com request.
|
|
|
|
"""
|
|
|
|
try:
|
2018-02-26 14:55:21 +00:00
|
|
|
url = "/".join([self._badips, "add", self.category, str(aInfo['ip'])])
|
2014-03-13 22:45:10 +00:00
|
|
|
if self.key:
|
2014-06-07 19:51:53 +00:00
|
|
|
url = "?".join([url, urlencode({'key': self.key})])
|
2018-02-26 17:16:20 +00:00
|
|
|
self._logSys.debug('badips.com: ban, url: %r', url)
|
2016-06-10 11:15:46 +00:00
|
|
|
response = urlopen(self._Request(url), timeout=self.timeout)
|
2018-04-05 09:26:43 +00:00
|
|
|
except HTTPError as response: # pragma: no cover
|
|
|
|
self.logError(response, "Failed to ban")
|
2014-02-09 12:23:14 +00:00
|
|
|
raise
|
|
|
|
else:
|
|
|
|
messages = json.loads(response.read().decode('utf-8'))
|
2018-04-05 09:26:43 +00:00
|
|
|
self._logSys.debug(
|
2014-02-09 12:23:14 +00:00
|
|
|
"Response from badips.com report: '%s'",
|
|
|
|
messages['suc'])
|
|
|
|
|
|
|
|
Action = BadIPsAction
|