|
1 | | -"""Only exports is_private_ip function""" |
2 | | - |
3 | | -import ipaddress |
| 1 | +from aikido_zen.helpers.ip_matcher import IPMatcher |
| 2 | +from aikido_zen.helpers.ip_matcher.map_ipv4_to_ipv6 import map_ipv4_to_ipv6 |
4 | 3 |
|
5 | 4 | # Define private IP ranges |
6 | 5 | PRIVATE_IP_RANGES = [ |
|
35 | 34 | "3fff::/20", # Documentation prefix (RFC 9637) |
36 | 35 | ] |
37 | 36 |
|
38 | | -# Create a set to hold private IP networks |
39 | | -private_ip_networks = set() |
| 37 | +private_ip_list = IPMatcher() |
40 | 38 |
|
41 | | -# Add private IPv4 ranges to the set |
42 | 39 | for ip_range in PRIVATE_IP_RANGES: |
43 | | - private_ip_networks.add(ipaddress.ip_network(ip_range)) |
44 | | - |
45 | | -# Add private IPv6 ranges to the set |
| 40 | + private_ip_list.add(ip_range) |
| 41 | + private_ip_list.add(map_ipv4_to_ipv6(ip_range)) |
46 | 42 | for ip_range in PRIVATE_IPV6_RANGES: |
47 | | - private_ip_networks.add(ipaddress.ip_network(ip_range)) |
48 | | - |
49 | | - |
50 | | -def normalize_ip(ip): |
51 | | - """Normalize the IP address by removing leading zeros.""" |
52 | | - if not ":" in ip: |
53 | | - # Normalize IPv4 ip's |
54 | | - parts = ip.split(".") |
55 | | - normalized_parts = [ |
56 | | - str(int(part)) for part in parts |
57 | | - ] # Convert to int and back to str to remove leading zeros |
58 | | - return ".".join(normalized_parts) |
59 | | - return ip |
| 43 | + private_ip_list.add(ip_range) |
60 | 44 |
|
61 | 45 |
|
62 | 46 | def is_private_ip(ip): |
63 | 47 | """Returns true if the ip entered is private""" |
64 | | - try: |
65 | | - normalized_ip = normalize_ip(ip) |
66 | | - ip_obj = ipaddress.ip_address(normalized_ip) |
67 | | - if isinstance(ip_obj, ipaddress.IPv6Address) and ip_obj.ipv4_mapped: |
68 | | - # If it's an IPv4-mapped IPv6 addresses, check if the IPv4 address is in any of the private networks |
69 | | - return any(ip_obj.ipv4_mapped in network for network in private_ip_networks) |
70 | | - |
71 | | - # Check if the IP address is in any of the private networks |
72 | | - return any(ip_obj in network for network in private_ip_networks) |
73 | | - except ValueError: |
74 | | - return False # Return False if the IP address is invalid |
| 48 | + return private_ip_list.has(ip) |
0 commit comments