Skip to content

Commit ca9d99e

Browse files
committed
enhance resolver_external checks
1 parent 6795df6 commit ca9d99e

File tree

1 file changed

+17
-26
lines changed

1 file changed

+17
-26
lines changed

gixy/directives/directive.py

Lines changed: 17 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from gixy.core.variable import Variable
44
from gixy.core.regexp import Regexp
55

6+
import ipaddress
67

78
def get_overrides():
89
"""Get a list of all directives that override the default behavior"""
@@ -235,36 +236,23 @@ def is_local_ipv6(ip):
235236
IP may include a port number, e.g. `[::1]:80`
236237
If port is not specified, IP can be specified without brackets, e.g. ::1
237238
"""
238-
# Remove brackets if present
239239
if ip.startswith("[") and "]" in ip:
240240
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
252246

253247

254248
def is_local_ipv4(addr):
255249
"""Check if an IPv4 address is a local address"""
256250
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
268256

269257

270258
class ResolverDirective(Directive):
@@ -286,13 +274,16 @@ def __init__(self, name, args):
286274
def get_external_nameservers(self):
287275
"""Get a list of external nameservers used by the resolver directive"""
288276
external_nameservers = []
277+
local_suffixes = (
278+
".intranet", ".internal", ".private", ".corp", ".home",
279+
".lan", ".local", ".localhost"
280+
)
289281
for addr in self.addresses:
290-
# Check for IPv4 addresses
282+
if any(addr.endswith(suffix) for suffix in local_suffixes):
283+
continue
291284
if "." in addr and is_local_ipv4(addr):
292285
continue
293-
# Check for IPv6 addresses
294286
if ":" in addr and is_local_ipv6(addr):
295287
continue
296-
297288
external_nameservers.append(addr)
298289
return external_nameservers

0 commit comments

Comments
 (0)