Created
June 17, 2019 16:05
-
-
Save gdvalle/0e539154521ab0917cee72f9b94af6dd to your computer and use it in GitHub Desktop.
List all GCP IPv4 network blocks using the cloud-netblocks TXT records.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
from dns.resolver import Resolver | |
dns_resolver = Resolver() | |
def _parse_netblock_includes(txt): | |
includes = set() | |
ip4_blocks = set() | |
for txt_entry in txt.split(): | |
if txt_entry.startswith("include:"): | |
includes.add(txt_entry.split(":")[1]) | |
elif txt_entry.startswith("ip4:"): | |
ip4_blocks.add(txt_entry.split(":")[1]) | |
return includes, ip4_blocks | |
def list_gcp_network_blocks(): | |
"""Enumerate every IPv4 block GCP uses by querying cloud-netblocks TXT records. | |
""" | |
gcp_ip4_blocks = set() | |
netblocks = ["_cloud-netblocks.googleusercontent.com"] | |
while netblocks: | |
netblock = netblocks.pop(0) | |
for nb_answer in dns_resolver.query(netblock, "TXT"): | |
for txt_record in nb_answer.strings: | |
includes, ip4_blocks = _parse_netblock_includes( | |
txt_record.decode("utf-8") | |
) | |
netblocks.extend(includes) | |
gcp_ip4_blocks.update(ip4_blocks) | |
return gcp_ip4_blocks | |
blocks = list(list_gcp_network_blocks()) | |
print(json.dumps(blocks)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment