Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 06 · 45 minutes

Check what the network of an account lets in

After this lesson you can
  • Explain subnets, route tables, security groups and network ACLs and how they differ
  • Decide with a program which ports the internet can reach, and why
  • Close the open ports with the smallest change and keep the service working
Lab files of this lesson (11)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

The storage is fixed. The next mail is from the hosting bill: a database of Larkfield answers connections from addresses all over the world. Your lead asks: "Which of our machines can the internet reach, on which ports? And what can reach the orders database? I want the reason for each answer, because the network team will say that the firewall is fine." In a cloud the firewall is not one box. It is four kinds of setting, and a port is open only when all of them agree.

Recall

Lesson 5: which two Block Public Access settings act on a public ACL or policy that already exists?

IgnorePublicAcls and RestrictPublicBuckets. The other two only refuse new public ACLs and new public policies.

Lesson 1: who is responsible for the firewall rules of a virtual machine in the cloud?

The customer. The provider protects the hardware and the layer below the machine. The rules that decide who may connect are configuration, and configuration is always yours.

The idea

A VPC (virtual private cloud) is a private network inside your account, with an address range that you choose. You split it into subnets. You know addresses, routes and firewalls from "Networking hands-on", lessons 2 and 11. The cloud adds its own names.

PartWhat it does
Route tableSays where the traffic of a subnet goes. A route to an internet gateway makes the subnet a public subnet. Without that route it is a private subnet.
NAT gatewayLets machines of a private subnet start connections to the internet. Nothing from outside can start a connection through it.
Security groupA firewall around one machine. It has allow rules only, and it is stateful: the answer to an allowed connection may always go back. A rule can name an address range or another security group as the source.
Network ACLA firewall around a subnet. It has allow and deny rules with numbers, read from the lowest number up: the first rule that fits decides. It is stateless: the answer needs a rule of its own in the other direction.

In the files of this lesson and in the AWS API, an inbound rule is an ingress rule and an outbound rule is an egress rule.

A request from the internet reaches a machine only if four things are true: the machine has a public address, its subnet has a route to an internet gateway, the network ACL allows the request and the answer, and a security group allows the request.

Who can reach what at Larkfield
InternetPublic subnetsPrivate subnetsCustomerAttackerweb-1bastion-1legacy-dbapp-1db-112345InternetPublic subnetsPrivate subnetsCustomerAttackerweb-1bastion-1legacy-dbapp-1db-112345
  1. Customer → web-1: port 443, meant to be public
  2. web-1 → app-1: port 8080, allowed by group name
  3. app-1 → db-1: port 5432, allowed by group name
  4. Attacker → bastion-1: port 22 is open to every address
  5. Attacker → legacy-db: port 3306 is open to every address

A security group that names another group as its source ("allow port 5432 from members of sg-app") is the cloud's best network habit: the rule follows the machines and not their addresses.

0.0.0.0/0 means every IPv4 address. In an inbound rule it means "the whole internet". It is right for the web port of a public site and wrong for almost everything else. A bastion is a machine in a public subnet whose only job is to accept SSH from administrators, who go on from there. It needs an open port and SSH keys. AWS Systems Manager Session Manager is the provider's replacement: an agent on the machine opens the connection outwards, so no inbound port, no bastion and no SSH key is needed, and access is decided by IAM.

Two defaults are worth knowing. The default network ACL of a VPC allows everything in both directions. The default security group allows inbound traffic only from its own members, and all outbound traffic.

Same idea, other namesAWSMicrosoft AzureGoogle Cloud
Private networkVPCVirtual network (VNet)VPC network
Stateful firewall rulesSecurity group: allow rules onlyNetwork security group: allow and deny rules with a priority, lower number firstVPC firewall rules: allow and deny rules with a priority
Start state for inbound trafficDenied until a rule allows itThe default rule DenyAllInboundAn implied rule that denies ingress

Worked example

1. Read the network file

account/network.json is a file in our own shape that joins what five API calls return: subnets, route tables, security groups, network ACLs and instances. It also holds a list expected_public: the ports that Larkfield has decided to offer to the world.

python3 -c "
import json
net = json.load(open('account/network.json'))
print('expected:', net['expected_public'])
for s in net['subnets']:
    print(s['id'], s['cidr'], s['route_table'], s['nacl'])
for g in net['security_groups']:
    print(g['id'], [(r['from_port'], r.get('cidr') or r['source_group']) for r in g['ingress']])"
expected: [['web-1', 443], ['web-1', 80]]
subnet-public-a 10.20.1.0/24 rt-public nacl-main
subnet-app-a 10.20.11.0/24 rt-private nacl-main
subnet-db-a 10.20.21.0/24 rt-db nacl-main
subnet-legacy 10.20.31.0/24 rt-public nacl-legacy
sg-web [(443, '0.0.0.0/0'), (80, '0.0.0.0/0')]
sg-bastion [(22, '0.0.0.0/0')]
sg-app [(8080, 'sg-web'), (22, 'sg-bastion')]
sg-db [(5432, 'sg-app'), (5432, '0.0.0.0/0')]
sg-legacy [(3306, '0.0.0.0/0'), (3389, '203.0.113.0/24')]

Two things stand out before any program runs. sg-db has two rules for port 5432: one from the application group, and one from everywhere. And three groups allow a port from 0.0.0.0/0 that is not a web port.

2. Save the checker

reach.py takes every security-group rule that names an address range and asks the four questions in order. The function nacl_allows is the stateless part: it sorts the entries of one direction by number and returns the decision of the first one that fits.

def nacl_allows(nacl, address, port, egress):
    """A network ACL reads its rules from the lowest number up. The first rule that fits decides. No rule: deny."""
    for e in sorted((e for e in nacl["entries"] if e["egress"] == egress), key=lambda e: e["rule_number"]):
        in_range = e["protocol"] == "all" or e["from_port"] <= port <= e["to_port"]
        if in_range and ipaddress.ip_address(address) in ipaddress.ip_network(e["cidr"]):
            return e["action"] == "allow", e["rule_number"]
    return False, "*"

The function exposure calls it twice for each rule: once for the request (inbound, to the port of the service) and once for the answer (outbound, to a high port of the client, because a client connects from a port with a high number). who_can_reach lists the machines and ranges that the security groups of one instance let in on one port. The checker reads TCP rules and IPv4 only, and it does not model a load balancer. Open the block and save the file.

The finished file: reach.py

reach.py

"""reach.py: what can reach what in the network of an account.

    python3 reach.py [FILE]                      ports that the internet can reach (default file: account/network.json)
    python3 reach.py FILE INSTANCE PORT          who can reach one port of one instance
Exit code 1 when a port is open to the internet that is not on the list expected_public of the file.
"""
import ipaddress
import json
import sys

ANY = "0.0.0.0/0"
OUTSIDE = "198.51.100.7"                     # a test address on the internet


def by_id(items):
    return {x["id"]: x for x in items}


def nacl_allows(nacl, address, port, egress):
    """A network ACL reads its rules from the lowest number up. The first rule that fits decides. No rule: deny."""
    for e in sorted((e for e in nacl["entries"] if e["egress"] == egress), key=lambda e: e["rule_number"]):
        in_range = e["protocol"] == "all" or e["from_port"] <= port <= e["to_port"]
        if in_range and ipaddress.ip_address(address) in ipaddress.ip_network(e["cidr"]):
            return e["action"] == "allow", e["rule_number"]
    return False, "*"


def internet_route(net, subnet):
    table = by_id(net["route_tables"])[subnet["route_table"]]
    return any(route["destination"] == ANY and route["target"].startswith("igw-") for route in table["routes"])


def exposure(net):
    """One row for each security-group rule that names an address range, with the reason it is open or closed."""
    groups, subnets, nacls = by_id(net["security_groups"]), by_id(net["subnets"]), by_id(net["nacls"])
    rows = []
    for inst in net["instances"]:
        subnet = subnets[inst["subnet"]]
        nacl = nacls[subnet["nacl"]]
        for gid in inst["security_groups"]:
            for rule in groups[gid]["ingress"]:
                if "cidr" not in rule:
                    continue
                source = OUTSIDE if rule["cidr"] == ANY else str(next(ipaddress.ip_network(rule["cidr"]).hosts()))
                port = rule["from_port"]
                if not inst["public_ip"]:
                    state, why = "closed", "no public address"
                elif not internet_route(net, subnet):
                    state, why = "closed", "no route to an internet gateway"
                else:
                    ok_in, n_in = nacl_allows(nacl, source, port, egress=False)
                    ok_out, n_out = nacl_allows(nacl, source, 50000, egress=True)  # the answer leaves from a high port
                    if not ok_in:
                        state, why = "closed", f"network ACL rule {n_in} denies the request"
                    elif not ok_out:
                        state, why = "closed", f"network ACL rule {n_out} denies the answer"
                    else:
                        state, why = "OPEN", f"{gid} allows it, network ACL rule {n_in} allows it"
                rows.append({"instance": inst["name"], "port": port, "to_port": rule["to_port"], "from": rule["cidr"], "group": gid,
                             "state": state, "why": why})
    return rows


def who_can_reach(net, name, port):
    """The instances and address ranges that the security groups of an instance let in on a port."""
    groups = by_id(net["security_groups"])
    target = next(i for i in net["instances"] if i["name"] == name)
    out = []
    for gid in target["security_groups"]:
        for rule in groups[gid]["ingress"]:
            if not rule["from_port"] <= port <= rule["to_port"]:
                continue
            if "cidr" in rule:
                out.append(f"range {rule['cidr']}")
            else:
                out += [f"instance {i['name']} (member of {rule['source_group']})"
                        for i in net["instances"] if rule["source_group"] in i["security_groups"]]
    return out


def expected(net):
    """The ports that are meant to be public, as (instance, port) pairs."""
    return {(name, port) for name, port in net.get("expected_public", [])}


def findings(net):
    out = []
    for x in exposure(net):
        world = x["from"] == ANY
        if x["state"] == "OPEN" and world and (x["instance"], x["port"]) not in expected(net):
            out.append({"severity": "critical", "code": "OPEN-PORT", "subject": f"instance {x['instance']}",
                        "text": f"port {x['port']} is open to the internet ({x['group']})"})
        elif x["state"] == "closed" and world:
            out.append({"severity": "medium", "code": "WIDE-RULE", "subject": f"instance {x['instance']}",
                        "text": f"{x['group']} allows port {x['port']} from {ANY}; only this stops it: {x['why']}"})
    return out


if __name__ == "__main__":
    with open(sys.argv[1] if len(sys.argv) > 1 else "account/network.json") as src:
        net = json.load(src)
    if len(sys.argv) > 3:
        for line in who_can_reach(net, sys.argv[2], int(sys.argv[3])):
            print(line)
        sys.exit(0)
    rows = exposure(net)
    for x in rows:
        print(f"{x['instance']:10s} {x['port']:5d} from {x['from']:15s} {x['state']:6s} {x['why']}")
    world = [x for x in rows if x["state"] == "OPEN" and x["from"] == ANY]
    surprise = [x for x in world if (x["instance"], x["port"]) not in expected(net)]
    print(f"{len(world)} ports open to the internet, {len(surprise)} not expected")
    sys.exit(1 if surprise else 0)

3. List what the internet can reach

python3 reach.py
echo "exit code $?"
web-1        443 from 0.0.0.0/0       OPEN   sg-web allows it, network ACL rule 100 allows it
web-1         80 from 0.0.0.0/0       OPEN   sg-web allows it, network ACL rule 100 allows it
bastion-1     22 from 0.0.0.0/0       OPEN   sg-bastion allows it, network ACL rule 100 allows it
db-1        5432 from 0.0.0.0/0       closed no public address
legacy-db   3306 from 0.0.0.0/0       OPEN   sg-legacy allows it, network ACL rule 100 allows it
legacy-db   3389 from 203.0.113.0/24  closed network ACL rule 90 denies the request
4 ports open to the internet, 2 not expected
exit code 1

Four ports are open to the internet. Two are the web site. The other two are SSH on the bastion and MySQL on the old database legacy-db, which sits in a public subnet with a public address.

Two lines say closed, and both deserve a second look. db-1 has the rule "5432 from everywhere", and only the missing public address saves it. legacy-db allows remote desktop (3389) from a partner range, and rule 90 of its network ACL denies that port before rule 100 allows everything.

4. Ask who can reach the orders database

With three arguments, the program answers the second question of your lead.

python3 reach.py account/network.json db-1 5432
instance app-1 (member of sg-app)
range 0.0.0.0/0

The first line is the design: the application server, by group name. The second line is the mistake. Today it does nothing from the internet, and it still lets every machine inside the VPC connect to the database, including the bastion that the whole world can try to log in to.

5. See what stateless means

Take the egress rule out of the main network ACL, in memory only, and ask again about the web port.

python3 -c "
import json, reach
net = json.load(open('account/network.json'))
nacl = net['nacls'][0]
print('with the egress rule:   ', [x['state'] for x in reach.exposure(net) if x['instance'] == 'web-1'])
nacl['entries'] = [e for e in nacl['entries'] if not e['egress']]
print('without the egress rule:', [(x['state'], x['why']) for x in reach.exposure(net) if x['instance'] == 'web-1'][0])"
with the egress rule:    ['OPEN', 'OPEN']
without the egress rule: ('closed', 'network ACL rule * denies the answer')

The request still gets in. The answer cannot leave, so the site is down. A security group would not behave like this, because it remembers the connection. This is the usual accident with network ACLs, and the reason to use security groups for most rules and a network ACL for a few broad denies.

Your turn

Copy account/network.json to network-fixed.json and repair it, by hand or with a few lines of Python. Change security groups only.

  • The orders database db-1 must accept port 5432 from the application servers and from nothing else.
  • The old database legacy-db must not accept port 3306 from the internet.
  • The bastion must accept SSH only from the office network 192.0.2.0/24.
  • The web site must keep working.

Then run the checker on your file, and ask it who can reach db-1 on port 5432.

Check yourself

A security group allows port 5432 from 0.0.0.0/0, and the machine is in a private subnet with no public address. Is that a finding?

Yes, a medium one. Nothing from the internet arrives today, but every machine in the VPC can connect, and one later change (a public address, a new route, a move to another subnet) opens the database to the world. Each layer should be right alone, so that one mistake is not enough.

You add a rule to a network ACL that allows inbound port 443. The site still does not answer. What is the likely cause?

The answer cannot leave. A network ACL is stateless, so it needs an outbound rule for the high ports that clients connect from. A security group needs no such rule, because it is stateful.

Why is "allow from the group sg-app" better than "allow from 10.20.11.0/24"?

The range allows every machine that is ever put into that subnet. The group allows the machines that were given that role, wherever they are, and it keeps working when addresses change. It also documents the design: this database serves this application.

Field notes

  • VPC Reachability Analyzer and Network Access Analyzer are the provider's tools for the question of this lesson, with every layer modelled. Use them for the real answer, and a checker like this one in a pipeline.
  • VPC Flow Logs record the connections that were accepted and rejected, per network interface. They are the network's part of the evidence in an incident, and they are off until you switch them on.
  • Remove the bastion when you can. Session Manager needs no inbound port, records who started a session, and can log what was typed.
  • A database belongs in a subnet with no route to an internet gateway and without a public address, with one inbound rule that names the group of its application.
  • The CIS AWS Foundations Benchmark has controls for exactly these findings: no inbound rule from 0.0.0.0/0 to the remote administration ports, and a default security group that allows nothing. Read the current version at the source.