#!/usr/bin/python
# Copyright 2011 Dominik George & Felix Falk. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are
# permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of
# conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice, this list
# of conditions and the following disclaimer in the documentation and/or other materials
# provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and documentation are those of the
# authors and should not be interpreted as representing official policies, either expressed
# or implied, of the copyright holders.
from glob import glob
from email.parser import Parser
from shutil import move
from time import time
import re
import socket
import os
import sys
import user
print "Starting abuse complaint script."
# Configuration
workdir = user.home + "/abuse"
maildir = user.home + "/mails/.Fail2Ban.Incoming/cur"
donedir = user.home + "/mails/.Fail2Ban.Reported/cur"
nonedir = user.home + "/mails/.Fail2Ban.Non-Reports/cur"
parsedir = user.home + "/mails/.Fail2Ban.Non-Parsable/cur"
olddir = user.home + "/mails/.Fail2Ban.Archived/cur"
outdir = user.home + "/mails/.Fail2Ban.Abuse-Out/cur"
rrdfile = workdir + "/abuse.rrd"
statsdir = workdir + "/stats"
mailfrom = '"Bashinators Abuse Central" <abuse-from@bashinators.de>'
replyto = '"Bashinators Abuse Central" <abuse-reply@bashinators.de>'
mailcc = '"Bashinators Abuse Central" <abuse-out@bashinators.de>'
maxcount = 3
maxage = 7
loglines = 25
parse = Parser()
# Retrieve mail files in incoming queue
mailfiles = glob(maildir + "/*")
attempts = {}
abusetos = {}
hosts = {}
ips = {}
files = {}
msgids = {}
print "Found " + str(len(mailfiles)) + " mail files."
for mailfile in mailfiles:
stat = os.stat(mailfile)
mtime = stat.st_mtime
# Archive if older than maxage days
if mtime + (maxage * 24 * 3600) < time():
print "Archiving " + mailfile + "."
move(mailfile, olddir)
continue
# Parse message
mailfd = open(mailfile, "r")
mail = parse.parse(mailfd)
mailfd.close()
# Guess reporting host from message id
msgid = mail['Message-Id'].strip('<>')
match = re.search('@(.*)', msgid)
host = match.group(1)
# Check subject for valid report
subject = mail['Subject']
match = re.search('\[Fail2Ban\].*?banned', subject)
# Remove if no report
if not match:
move(mailfile, nonedir)
continue
msg = mail.as_string()
# Extract relevant information
match = re.search('The IP (.*) has just been banned.*against (.*?)\..*?(Here are more.*?)(Lines containing.*?)Regards,', msg, re.I | re.S)
# Remove if no report
if not match:
move(mailfile, parsedir)
continue
malip = match.group(1)
malsrv = match.group(2)
malwhois = match.group(3)
mallog = match.group(4)
# Find abuse complaint contact information
match = re.search('^.*?abuse.*?([-a-z0-9._]+@[-a-z0-9._]+).*$', malwhois, re.I | re.M)
try:
abuseto = match.group(1)
except:
match = re.search('^.*?mail.*?([-a-z0-9._]+@[-a-z0-9._]+).*$', malwhois, re.I | re.M)
try:
abuseto = match.group(1)
except:
matches = re.findall('[-a-z0-9._]+@[-a-z0-9._]+', malwhois, re.I | re.S)
abuseto = matches
if len(abuseto) == 0:
print "No abuse contact found in " + msgid + "!"
move(mailfile, parsedir)
continue
print("Attempt from " + malip + " against " + malsrv + " on " + host + ".")
# Update data structures
if not malip in attempts:
attempts[malip] = []
attempts[malip].append((host, malsrv, malwhois, mallog))
if not malip in files:
files[malip] = []
files[malip].append(mailfile)
if not malip in msgids:
msgids[malip] = []
msgids[malip].append(msgid)
if not malip in abusetos:
abusetos[malip] = []
if type(abuseto).__name__ == 'list':
abusetos[malip] += abuseto
else:
if not abuseto in abusetos[malip]:
abusetos[malip].append(abuseto)
if not malip in hosts:
hosts[malip] = []
if not (host, malsrv) in hosts[malip]:
hosts[malip].append((host, malsrv))
# Resolve reporting hostnames
for ip in hosts:
for (host, srv) in hosts[ip]:
if host not in ips:
try:
ips[host] = socket.gethostbyname(host)
except:
ips[host] = ''
# Check for complaint qualifications
for ip in attempts:
count = len(attempts[ip])
if count < maxcount:
continue
print("Attacker " + ip + " with " + str(count) + " reports qualifies for complaint.")
services = ""
# Generate host/service listing
for (host, srv) in hosts[ip]:
services = services + " " + srv + " on " + host + " (" + ips[host] + ")\n"
# Create mail
p = os.popen("/usr/sbin/sendmail -t", "w")
# p = sys.stdout
p.write("From: " + mailfrom + "\n")
p.write("To: " + ', '.join(abusetos[ip]) + "\n")
p.write("Bcc: " + mailcc + "\n")
p.write("Reply-To: " + replyto + "\n")
p.write("Subject: Network Abuse Complaint about " + ip + "\n")
p.write("\n")
p.write('''To whom it may concern,
the host with address ''' + ip + ''', which according to public whois information is
part of a network for which you are listed as abuse contact, has been reported by one
or more of our systems for attacking one or more services running on them.
The specific services and hosts are:
''' + services + '''
The whois record listing you as abuse contact is:
''' + attempts[ip][0][2] + '''
Here is an excerpt from the logs that triggered the report:
''' + "\n".join(attempts[ip][0][3].split("\n")[0:loglines]) + '''
We will supply you with more logs should that be necessary. Please reply to this
email for further assistance in tracking down the misbehaving system. If you do,
it may help if you include the following list of message ids that triggered the alert
(you can also search for those on the website mentioned below if you are interested):
''' + "\n ".join(msgids[ip]) + '''
We trust that you act upon this report according to your Acceptable Usage Policy
or any other documents that appear appropriate.
With kind regards,
Dominik George / Felix Falk
Bashinators Abuse Central
More information: http://www.bashinators.de/abuse/''')
p.close()
# Remove all reports used for complaint
for file in files[ip]:
move(file, donedir)
print("Reported " + ip + " to " + ', '.join(abusetos[ip]) + ".")
# Get counters
cnt_incoming = len(glob(maildir + '/*'))
cnt_reported = len(glob(donedir + '/*'))
cnt_archived = len(glob(olddir + '/*'))
cnt_complain = len(glob(outdir + '/*'))
cnt_sum = cnt_incoming + cnt_reported + cnt_archived
# Update RRD database
os.system("rrdtool update " + rrdfile + " N:" + str(cnt_incoming) + ":" + str(cnt_reported) + ":" + str(cnt_archived) + ":" + str(cnt_sum) + ":" + str(cnt_complain))
# Write stats values
fd = open(statsdir + "/incoming", "w")
fd.write(str(cnt_incoming))
fd.close()
fd = open(statsdir + "/reported", "w")
fd.write(str(cnt_reported))
fd.close()
fd = open(statsdir + "/archived", "w")
fd.write(str(cnt_archived))
fd.close()
fd = open(statsdir + "/complaints", "w")
fd.write(str(cnt_complain))
fd.close()
fd = open(statsdir + "/sum", "w")
fd.write(str(cnt_sum))
fd.close()
os.chdir(workdir)
os.system("./genimg.sh")
print "Finished."
|
Bashinators Abuse Central Main info page |
Copyright © 2011 Dominik George / Felix Falk Published under the Creative Commons SA-BY 3.0 License. |