TExcelTAD
Home › Ethical Hacking & Penetration Testing Methodology › Scope as Data: CIDR Checks in Python

Scope as Data: CIDR Checks in Python

Clients send scope in every format: a spreadsheet of addresses, a paragraph in an e-mail ("our DMZ and the office range"), a screenshot of a firewall rule. Testers who paste that into a scanner by hand eventually scan someone else. The professional habit is to turn the scope into data once, check it for mistakes, generate every target list from it, and check every result (a host name that resolves, an address found in a page) against it again. The scope checker of Security Foundations decided single requests. This lesson goes one step earlier and one step later: cleaning a client's scope list, expanding it into target lists with the exclusions removed, and screening discovered names.

CIDR in one paragraph

A CIDR block such as 10.10.0.0/24 is a network address and a prefix length: the first 24 bits are fixed, the last 8 vary, so the block holds 2^(32-24) = 256 addresses. /29 holds 8, /32 is one host. Python's ipaddress module does all of this exactly, for IPv4 and IPv6, including the operations a tester needs: membership (ip in net), overlap (a.overlaps(b)), subtraction (net.address_exclude(sub)) and merging (collapse_addresses). The subnetting lesson has the bit-level detail and a lab.

Step 1: clean the client's list

The list below is what a client might send. It has the usual mistakes: a block written with host bits set, a duplicate inside a larger block, a public address that may belong to someone else, and an IPv6 range.

python · try it yourself
import ipaddress

client_list = """
10.10.0.0/24
10.10.0.64/26
10.10.0.130/25
198.51.100.7
10.10.2.0/23
fd00:10:10::/64
"""
DOC = ipaddress.ip_network("198.51.100.0/24")   # documentation range, stands in for public space here

nets, notes = [], []
for line in client_list.split():
    try:
        net = ipaddress.ip_network(line)
    except ValueError:
        net = ipaddress.ip_network(line, strict=False)
        notes.append(f"{line}: host bits set, read as {net}; confirm with the client")
    if net.version == 4 and (net.subnet_of(DOC) or not net.is_private):
        notes.append(f"{line}: public address space; whose is it? check ownership (WHOIS/RIR) before testing")
    nets.append(net)
for a in nets:
    for b in nets:
        if a != b and a.version == b.version and a.subnet_of(b):
            notes.append(f"{a} is already inside {b}")
v4 = list(ipaddress.collapse_addresses(n for n in nets if n.version == 4))
v6 = [n for n in nets if n.version == 6]
for n in notes:
    print("NOTE", n)
print("merged IPv4 scope:", ", ".join(map(str, v4)))
print("IPv6 scope:", ", ".join(map(str, v6)), "(", v6[0].num_addresses, "addresses: enumerate, don't sweep )")
NOTE 10.10.0.130/25: host bits set, read as 10.10.0.128/25; confirm with the client
NOTE 198.51.100.7: public address space; whose is it? check ownership (WHOIS/RIR) before testing
NOTE 10.10.0.64/26 is already inside 10.10.0.0/24
NOTE 10.10.0.128/25 is already inside 10.10.0.0/24
merged IPv4 scope: 10.10.0.0/24, 10.10.2.0/23, 198.51.100.7/32
IPv6 scope: fd00:10:10::/64 ( 18446744073709551616 addresses: enumerate, don't sweep )

The client's 10.10.0.130/25 really means the upper half of the /24 (.128 to .255), which the /24 already covers. Maybe the client meant a single host 10.10.0.130, a very different scope. Ask. The documentation address 198.51.100.7 stands in for a public address here; a real public address always needs an ownership check, because hosting providers reassign them. An IPv6 /64 has 2^64 addresses and can't be swept; IPv6 targets come from DNS, the client's inventory and neighbour tables, never from enumeration.

Step 2: expand into target lists

Scanners accept exclusions (nmap --exclude, --excludefile), but a target list with the exclusions already removed is easier to review and to log. address_exclude splits a block around a hole.

python · try it yourself
import ipaddress

scope = [ipaddress.ip_network("10.10.0.0/24"), ipaddress.ip_network("10.10.2.0/23")]
excluded = [ipaddress.ip_network(x) for x in ["10.10.0.1/32", "10.10.0.200/29", "10.10.2.0/28"]]

def subtract(nets, holes):
    result = list(nets)
    for hole in holes:
        nxt = []
        for net in result:
            if hole.subnet_of(net):
                nxt.extend(net.address_exclude(hole))
            elif not net.subnet_of(hole):
                nxt.append(net)
        result = nxt
    return sorted(ipaddress.collapse_addresses(result))

targets = subtract(scope, excluded)
print(len(targets), "blocks:", " ".join(map(str, targets)))
total = sum(n.num_addresses for n in targets)
print("addresses to scan:", total, "of", sum(n.num_addresses for n in scope))
for probe in ["10.10.0.1", "10.10.0.199", "10.10.0.204", "10.10.0.208", "10.10.2.15", "10.10.2.16", "10.10.3.255"]:
    ip = ipaddress.ip_address(probe)
    print(f"{probe:<12} {'scan' if any(ip in n for n in targets) else 'skip'}")
16 blocks: 10.10.0.0/32 10.10.0.2/31 10.10.0.4/30 10.10.0.8/29 10.10.0.16/28 10.10.0.32/27 10.10.0.64/26 10.10.0.128/26 10.10.0.192/29 10.10.0.208/28 10.10.0.224/27 10.10.2.16/28 10.10.2.32/27 10.10.2.64/26 10.10.2.128/25 10.10.3.0/24
addresses to scan: 743 of 768
10.10.0.1    skip
10.10.0.199  scan
10.10.0.204  skip
10.10.0.208  scan
10.10.2.15   skip
10.10.2.16   scan
10.10.3.255  scan

The exclusions cut 1 + 8 + 16 = 25 addresses out of 768, and the result is sixteen CIDR blocks (743 addresses) that a scanner can take with -iL and a reviewer can check. Edge addresses are where mistakes hide, so the probes test both sides of every hole: .199 and .208 are in, .200 to .207 are out.

Step 3: screen what you discover

Recon produces names and addresses the client never listed: a subdomain in a certificate, an address in a JavaScript file, a mail server in an MX record. Each one is screened before anything is sent to it.

python · try it yourself
import ipaddress

scope = [ipaddress.ip_network(n) for n in ["10.10.0.0/24", "10.10.2.0/23"]]
excluded = [ipaddress.ip_network(n) for n in ["10.10.0.1/32", "10.10.0.200/29", "10.10.2.0/28"]]

def in_scope(addr):
    ip = ipaddress.ip_address(addr)
    return any(ip in n for n in scope) and not any(ip in n for n in excluded)

discovered = {   # name -> addresses it resolved to during recon (lab data)
    "www.lab.test": ["10.10.0.10"],
    "intranet.lab.test": ["10.10.0.10"],
    "mail.lab.test": ["10.10.0.25"],
    "vpn.lab.test": ["10.10.0.1"],
    "backup.lab.test": ["10.10.0.203"],
    "status.lab.test": ["203.0.113.80"],
    "shop.lab.test": ["10.10.0.30", "203.0.113.50"],
}
for name, addrs in discovered.items():
    verdicts = ["in" if in_scope(a) else "OUT" for a in addrs]
    if all(v == "in" for v in verdicts):
        action = "test"
    elif any(v == "in" for v in verdicts):
        action = "ASK: only some addresses are in scope (load balancer or CDN?)"
    else:
        action = "do not touch; list as observed, out of scope"
    print(f"{name:<18} {', '.join(f'{a} {v}' for a, v in zip(addrs, verdicts)):<36} {action}")
www.lab.test       10.10.0.10 in                        test
intranet.lab.test  10.10.0.10 in                        test
mail.lab.test      10.10.0.25 in                        test
vpn.lab.test       10.10.0.1 OUT                        do not touch; list as observed, out of scope
backup.lab.test    10.10.0.203 OUT                      do not touch; list as observed, out of scope
status.lab.test    203.0.113.80 OUT                     do not touch; list as observed, out of scope
shop.lab.test      10.10.0.30 in, 203.0.113.50 OUT      ASK: only some addresses are in scope (load balancer or CDN?)

vpn.lab.test and backup.lab.test sit on excluded addresses, and status.lab.test is hosted elsewhere (a status-page service, perhaps): all three go into the report as observed, not tested, which is itself useful to the client. shop.lab.test is the interesting case. One of its addresses is in scope and one isn't, so a request to the name may land on either. Testing it needs a decision from the client, and probably the third party.

How scope mistakes are detected

  • Reviewing the generated target list (not the raw client list) at kick-off, with the edge probes printed.
  • Checking every scanner's actual target list in its output file (nmap -oX records the command line and every host) against the scope before the report.
  • The client's network team, if announced, sees scans from the declared source address and can compare the destinations.

How they are prevented

One scope file in the engagement repository, versioned and signed; target lists only ever generated from it; tools invoked through a wrapper that checks targets (as in the introduction); discovered assets screened by the function above before any request; any change a new signed version.

Pitfalls

  • strict=False without asking. It silently turns 10.10.0.130/25 into 10.10.0.128/25. Use it to read the client's intent, then confirm.
  • IPv6 forgotten. A host excluded by its IPv4 address may still answer on IPv6. Exclusions must list both.
  • DNS changes during the test. Names are re-resolved and re-screened each day; a cloud load balancer's addresses move.
  • Wildcards in names. *.lab.test matches x.y.lab.test in some tools and not in others. Write the rule in the RoE.

Practice

  1. Add 10.10.1.0/24 to the client list in step 1. What does collapse_addresses now return, and why is that worth a question to the client?
  2. Change subtract so that it also accepts holes that are larger than a scope block (an exclusion of 10.10.0.0/23 against the block 10.10.0.0/24). Does the current code already handle it?
Answers
  1. With 10.10.0.0/24, 10.10.1.0/24 and 10.10.2.0/23, the private ranges merge into one block, 10.10.0.0/22 (and 198.51.100.7/32 stays on its own). That is correct arithmetic, but the client listed three separate ranges, and the merged form hides that 10.10.1.0/24 was a late addition. Ask whether it really belongs, and keep the original list in the record.
  2. Yes: a block that is a subnet of the hole is dropped by the elif not net.subnet_of(hole) branch. Overlaps where neither contains the other can't happen with CIDR blocks: two blocks are either disjoint or one contains the other.

Test yourself

How many addresses does 10.10.0.200/29 contain, and which?

  1. 29: .200 to .228
  2. 8: .200 to .207
  3. 16: .200 to .215
  4. 1: .200

A client writes 10.10.0.130/25. What does it denote, and what should you do?

  1. The single host .130; test it
  2. The block .128 to .255 (host bits set); confirm the intent with the client
  3. An error; ignore the line
  4. The whole /24

shop.lab.test resolves to one in-scope and one out-of-scope address. What do you do?

  1. Test it, the name is in scope
  2. Ask the client: requests may land on a third party's system
  3. Test only on Sundays
  4. Ignore DNS and test by name

Why is an IPv6 /64 never swept address by address?

  1. IPv6 forbids scanning
  2. It has 2^64 addresses; targets come from DNS, inventories and neighbour tables
  3. Nmap doesn't support IPv6
  4. All IPv6 addresses are public