From 3acb0b854864af6a4eac7e24d46ba662149bce32 Mon Sep 17 00:00:00 2001 From: Cyril Jaquier Date: Tue, 12 Jul 2005 13:10:14 +0000 Subject: [PATCH] - Added CIDR mask support git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@133 a942ae1a-1317-0410-a47c-b1dcaea8d605 --- logreader/logreader.py | 12 +++++++++++- utils/dns.py | 20 +++++++++++++++++++- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/logreader/logreader.py b/logreader/logreader.py index 79f5e7db..eb9169ab 100644 --- a/logreader/logreader.py +++ b/logreader/logreader.py @@ -64,7 +64,17 @@ class LogReader: def inIgnoreIPList(self, ip): """ Checks if IP is in the ignore list. """ - return ip in self.ignoreIpList + for i in self.ignoreIpList: + s = i.split('/', 1) + # IP address without CIDR mask + if len(s) == 1: + s.insert(1, '32') + s[1] = long(s[1]) + a = cidr(s[0], s[1]) + b = cidr(ip, s[1]) + if a == b: + return True + return False def openLogFile(self): """ Opens the log file specified on init. diff --git a/utils/dns.py b/utils/dns.py index ce629d69..729f599d 100644 --- a/utils/dns.py +++ b/utils/dns.py @@ -24,7 +24,7 @@ __date__ = "$Date$" __copyright__ = "Copyright (c) 2004 Cyril Jaquier" __license__ = "GPL" -import os, re, socket +import os, re, socket, struct def dnsToIp(dns): """ Convert a DNS into an IP address using the Python socket module. @@ -71,3 +71,21 @@ def textToIp(text): for e in dns: ipList.append(e) return ipList + +def cidr(i, n): + """ Convert an IP address string with a CIDR mask into a 32-bit + integer. + """ + # 32-bit IPv4 address mask + MASK = 0xFFFFFFFFL + return ~(MASK >> n) & MASK & addr2bin(i) + +def addr2bin(str): + """ Convert a string IPv4 address into an unsigned integer. + """ + return struct.unpack("!L", socket.inet_aton(str))[0] + +def bin2addr(addr): + """ Convert a numeric IPv4 address into string n.n.n.n form. + """ + return socket.inet_ntoa(struct.pack("!L", addr))