From 0d092f83c368c5985aadc9dfcd69c0fddac6d6af Mon Sep 17 00:00:00 2001 From: Juhani Haverinen Date: Sun, 24 Jul 2016 20:36:43 +0300 Subject: [PATCH] Add IP blacklist support --- gophersrv.py | 45 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/gophersrv.py b/gophersrv.py index 4dfd5a2..f02d2d3 100644 --- a/gophersrv.py +++ b/gophersrv.py @@ -34,8 +34,9 @@ import subprocess import threading # Config -port = 7070 -gopherroot = os.environ['HOME']+'/gopher' +port = 7070 +gopherroot = os.environ['HOME']+'/gopher' +blacklistfile = os.environ['HOME']+'/gopher_blacklist' # Set up socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) @@ -269,6 +270,44 @@ class Serve(threading.Thread): except socket.error: self.conn.close() +def toint(addr): + a1, a2, a3, a4 = [int(i) for i in addr.split('.')] + return a1<<24 | a2<<16 | a3<<8 | a4 + +try: + f = open(blacklistfile, 'r') +except IOError: + blacklist = [] +else: + blacklist = [] + for line in f: + if len(line) > 0 and line[-1] == '\n': + line = line[:-1] + + line = line.split('/') + if len(line) == 1: + addr = toint(line[0]) + upto = 32 + elif len(line) == 2: + addr = toint(line[0]) + upto = int(line[1]) + else: + assert(not 'Invalid line format') + + blacklist.append((addr, upto)) + + f.close() + +def matchaddr(addr, blacklist_entry): + blacklist_addr, upto = blacklist_entry + shift = 32 - upto + return addr >> shift == blacklist_addr >> shift + while True: conn, addr = sock.accept() - Serve(conn).start() + ip, port = addr + if not any(map(lambda x: matchaddr(toint(ip), x), blacklist)): + print ip, blacklist#debg + Serve(conn).start() + else: + conn.close()