Improved IP address handling (includes IPv6)

This commit is contained in:
JonnyWong16 2017-02-05 18:55:10 -08:00
commit ca472ff597
14 changed files with 178 additions and 220 deletions

View file

@ -502,28 +502,32 @@ def sanitize(string):
else:
return ''
def is_ip_public(host):
ip_address = get_ip(host)
ip = IP(ip_address)
if ip.iptype() == 'PUBLIC':
def is_public_ip(host):
ip = is_valid_ip(get_ip(host))
if ip and ip.iptype() == 'PUBLIC':
return True
return False
def get_ip(host):
ip_address = ''
try:
socket.inet_aton(host)
ip_address = host
except socket.error:
if is_valid_ip(host):
return host
else:
try:
ip_address = socket.gethostbyname(host)
ip_address = socket.getaddrinfo(host, None)[0][4][0]
logger.debug(u"IP Checker :: Resolved %s to %s." % (host, ip_address))
except:
logger.error(u"IP Checker :: Bad IP or hostname provided.")
return ip_address
def is_valid_ip(address):
try:
return IP(address)
except TypeError:
return False
except ValueError:
return False
def install_geoip_db():
maxmind_url = 'http://geolite.maxmind.com/download/geoip/database/'
geolite2_gz = 'GeoLite2-City.mmdb.gz'

View file

@ -92,14 +92,14 @@ class PublicIPFilter(logging.Filter):
# Currently only checking for ipv4 addresses
ipv4 = re.findall(r'[0-9]+(?:\.[0-9]+){3}(?!\d*-[a-z0-9]{6})', record.msg)
for ip in ipv4:
if helpers.is_ip_public(ip):
if helpers.is_public_ip(ip):
record.msg = record.msg.replace(ip, ip.partition('.')[0] + '.***.***.***')
args = []
for arg in record.args:
ipv4 = re.findall(r'[0-9]+(?:\.[0-9]+){3}(?!\d*-[a-z0-9]{6})', arg) if isinstance(arg, basestring) else []
for ip in ipv4:
if helpers.is_ip_public(ip):
if helpers.is_public_ip(ip):
arg = arg.replace(ip, ip.partition('.')[0] + '.***.***.***')
args.append(arg)
record.args = tuple(args)

View file

@ -1719,11 +1719,7 @@ class WebInterface(object):
@cherrypy.expose
@requireAuth()
def get_ip_address_details(self, ip_address=None, **kwargs):
import socket
try:
socket.inet_aton(ip_address)
except socket.error:
if not helpers.is_valid_ip(ip_address):
ip_address = None
return serve_template(templatename="ip_address_modal.html", title="IP Address Details", data=ip_address)