Add IP blacklist support

This commit is contained in:
Juhani Haverinen 2016-07-24 20:36:43 +03:00
parent 42d7b2d61d
commit 0d092f83c3
1 changed files with 42 additions and 3 deletions

View File

@ -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()