3
3
from gixy .core .variable import Variable
4
4
from gixy .core .regexp import Regexp
5
5
6
+ import ipaddress
6
7
7
8
def get_overrides ():
8
9
"""Get a list of all directives that override the default behavior"""
@@ -235,36 +236,23 @@ def is_local_ipv6(ip):
235
236
IP may include a port number, e.g. `[::1]:80`
236
237
If port is not specified, IP can be specified without brackets, e.g. ::1
237
238
"""
238
- # Remove brackets if present
239
239
if ip .startswith ("[" ) and "]" in ip :
240
240
ip = ip .split ("]" )[0 ][1 :]
241
-
242
- # Exclude loopback address ([::1])
243
- if ip == "::1" :
244
- return True
245
- # Exclude link-local addresses (fe80::/10)
246
- if ip .startswith ("fe80:" ):
247
- return True
248
- # Exclude unique local addresses (fc00::/7)
249
- if ip .startswith ("fc" ) or ip .startswith ("fd" ):
250
- return True
251
- return False
241
+ try :
242
+ ip_obj = ipaddress .IPv6Address (ip )
243
+ return ip_obj .is_loopback or ip_obj .is_link_local or ip_obj .is_private
244
+ except ValueError :
245
+ return False
252
246
253
247
254
248
def is_local_ipv4 (addr ):
255
249
"""Check if an IPv4 address is a local address"""
256
250
ip = addr .rsplit (":" , 1 )[0 ]
257
- # Exclude loopback addresses (127.0.0.0/8)
258
- if ip .startswith ("127." ):
259
- return True
260
- # Exclude private addresses (10.x.x.x, 172.16.x.x - 172.31.x.x, 192.168.x.x)
261
- if ip .startswith ("10." ) or ip .startswith ("192.168." ):
262
- return True
263
- if ip .startswith ("172." ):
264
- second_octet = int (ip .split ("." )[1 ])
265
- if 16 <= second_octet <= 31 :
266
- return True
267
- return False
251
+ try :
252
+ ip_obj = ipaddress .IPv4Address (ip )
253
+ return ip_obj .is_loopback or ip_obj .is_private
254
+ except ValueError :
255
+ return False
268
256
269
257
270
258
class ResolverDirective (Directive ):
@@ -286,13 +274,16 @@ def __init__(self, name, args):
286
274
def get_external_nameservers (self ):
287
275
"""Get a list of external nameservers used by the resolver directive"""
288
276
external_nameservers = []
277
+ local_suffixes = (
278
+ ".intranet" , ".internal" , ".private" , ".corp" , ".home" ,
279
+ ".lan" , ".local" , ".localhost"
280
+ )
289
281
for addr in self .addresses :
290
- # Check for IPv4 addresses
282
+ if any (addr .endswith (suffix ) for suffix in local_suffixes ):
283
+ continue
291
284
if "." in addr and is_local_ipv4 (addr ):
292
285
continue
293
- # Check for IPv6 addresses
294
286
if ":" in addr and is_local_ipv6 (addr ):
295
287
continue
296
-
297
288
external_nameservers .append (addr )
298
289
return external_nameservers
0 commit comments