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 04 · 45 minutes

Route between VLANs and read a tag

After this lesson you can
  • Choose a route by the longest prefix
  • Read an 802.1Q tag and tell an access port from a trunk port
  • Describe routing between VLANs and why a router must filter it
Lab files of this lesson (20)

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

A small office has one switch and one router. The owner wants the guest Wi-Fi and the finance computers on separate networks and asks: "Can a guest reach finance?" You write the decisions of the router and of a switch with VLANs yourself, to see where a guest frame stops.

Recall

What does a switch do with a frame whose destination address is not in its table?

It floods the frame: a copy goes out of every other port (lesson 3).

What is the default route for?

It matches every address, is used last, and sends the packet to the gateway.

The idea

A router connects networks. It picks the entry of its routing table with the longest prefix that matches the destination address, and the entry names the next hop: the next router, or nothing if the network is directly connected. The frame that leaves has a new MAC header for the next hop, the same IP addresses and a TTL lowered by one. A host does the same: its default gateway is the next hop for every outside address (lesson 2).

A VLAN (virtual LAN) splits one switch into several separate networks. Standard 802.1Q adds a tag of four bytes after the source address: the marker 0x8100, 3 bits of priority, 1 bit "drop eligible", and a 12-bit VLAN ID (1 to 4094). Two port types matter:

PortCarriesFrames on the wire
AccessOne VLAN, for one deviceUntagged. The switch adds the tag inside, and removes it on the way out.
TrunkMany VLANs, between switches or to a routerTagged, with the VLAN ID. One VLAN, the native VLAN, can be untagged.

Each VLAN is its own broadcast domain and needs its own address block. Traffic between two VLANs goes through a router (inter-VLAN routing), which can also filter it.

A packet from VLAN 10 to VLAN 20
VLAN 10Switch and routerVLAN 20PC in VLAN 10SwitchRouterServer in VLAN 201234VLAN 10Switch and routerVLAN 20PC in VLAN 10SwitchRouterServer in VLAN 201234
  1. PC in VLAN 10 → Switch: untagged frame to the gateway MAC
  2. Switch → Router: same frame, tag 10, on the trunk
  3. Router → Switch: route lookup, new frame with tag 20
  4. Switch → Server in VLAN 20: untagged, the tag is removed

Worked example

1. Choose a route like a router

The file routes.txt is a routing table: a network, the next hop (- means directly connected) and the interface. route.py finds every entry that contains the address and takes the one with the longest prefix. max returns the largest item of a list. With key=, it compares the items by a value that you give. lambda r: r[0].prefixlen is a one-line function: for an entry r, it gives the prefix length of its network. The frame goes to the next hop, so ARP must find its address.

cd ~/krlab/networking
cat > routes.txt <<'EOT'
10.20.0.0/22 - eth0
10.30.0.0/16 10.20.0.1 eth0
10.30.5.0/24 10.20.0.2 eth0
0.0.0.0/0 10.20.0.254 eth0
EOT

route.py

import ipaddress
import sys

routes = []
for line in open(sys.argv[1]):
    network, via, dev = line.split()
    routes.append((ipaddress.ip_network(network), via, dev))

for text in sys.argv[2:]:
    address = ipaddress.ip_address(text)
    matches = [r for r in routes if address in r[0]]
    if not matches:
        print(f"{text:<12} no route: network unreachable")
        continue
    network, via, dev = max(matches, key=lambda r: r[0].prefixlen)  # the longest prefix wins
    arp_for = text if via == "-" else via  # the frame goes to this address, found by ARP
    print(f"{text:<12} matches {len(matches)}  use {str(network):<13} dev {dev}  ARP for {arp_for}")
python3 route.py routes.txt 10.20.1.5 10.30.5.9 10.30.9.9 8.8.8.8
10.20.1.5    matches 2  use 10.20.0.0/22  dev eth0  ARP for 10.20.1.5
10.30.5.9    matches 3  use 10.30.5.0/24  dev eth0  ARP for 10.20.0.2
10.30.9.9    matches 2  use 10.30.0.0/16  dev eth0  ARP for 10.20.0.1
8.8.8.8      matches 1  use 0.0.0.0/0     dev eth0  ARP for 10.20.0.254

The address 10.30.5.9 matches three entries, and the /24 wins. The default route matches every address, so it is the last choice. Without it, an unknown address is "network unreachable".

2. Read an 802.1Q frame

tagged.hex is a recorded frame from a trunk port. vlan.py reads the 14 bytes of the header, and when the type is 0x8100 it reads the next two bytes (a014): & 0x0FFF keeps the 12 low bits (the VLAN ID) and >> 13 keeps the top 3 bits (the priority).

cat > tagged.hex <<'EOT'
02000000000202000000000a8100a014080045000020000140004001209b0a1401070a1e0509080019270007000170696e67
EOT

vlan.py

import struct
import sys

from inet import mac_text

frame = bytes.fromhex(open(sys.argv[1]).read())
dst, src, kind = struct.unpack("!6s6sH", frame[:14])
print(f"dst {mac_text(dst)}  src {mac_text(src)}")
if kind != 0x8100:
    print(f"untagged frame, type 0x{kind:04x}")
else:
    tci, inner = struct.unpack("!HH", frame[14:18])
    print(f"tagged: VLAN {tci & 0x0FFF}  priority {tci >> 13}  drop-eligible {tci >> 12 & 1}  inner type 0x{inner:04x}")
python3 vlan.py tagged.hex
dst 02:00:00:00:00:02  src 02:00:00:00:00:0a
tagged: VLAN 20  priority 5  drop-eligible 0  inner type 0x0800
The first 18 bytes of tagged.hex
02:00:00:00:00:02destination MAC02:00:00:00:00:0asource MAC8100tag marker (802.1Q)a014priority 5, VLAN 200800type inside the tag: IPv402:00:00:00:00:02destination MAC02:00:00:00:00:0asource MAC8100tag marker (802.1Q)a014priority 5, VLAN 200800type inside the tag: IPv4

3. Put VLAN 10 on the virtual cable

This step uses vlanlab.sh from lesson 3 and needs no root: unshare -Urn gives you a private network. If it fails, see "If it fails" in the set-up, or skip this step. ip link add link v0 name v0.10 type vlan id 10 makes a sub-interface of v0 that adds the tag of VLAN 10 to every frame that leaves and removes it from every frame that arrives. tag.sh does this at both ends, gives them a new network, and captures again (vlan and arp keeps tagged ARP frames).

tag.sh

ip link add link v0 name v0.10 type vlan id 10
ip addr add 10.10.0.1/24 dev v0.10; ip link set v0.10 up
nsenter -t $OTHER -n sh -c 'ip link add link v1 name v1.10 type vlan id 10;
  ip addr add 10.10.0.2/24 dev v1.10; ip link set v1.10 up'
tcpdump -Z root -t -e -nn -i v0 -c 2 'vlan and arp' > tagged.txt 2>/dev/null &
DUMP=$!
sleep 1
ping -c 1 -W 2 10.10.0.2 > /dev/null
wait $DUMP
cat tagged.txt
unshare -Urn sh vlanlab.sh tag.sh
02:00:00:00:10:01 > ff:ff:ff:ff:ff:ff, ethertype 802.1Q (0x8100), length 46: vlan 10, p 0, ethertype ARP (0x0806), Request who-has 10.10.0.2 tell 10.10.0.1, length 28
02:00:00:00:10:02 > 02:00:00:00:10:01, ethertype 802.1Q (0x8100), length 46: vlan 10, p 0, ethertype ARP (0x0806), Reply 10.10.0.2 is-at 02:00:00:00:10:02, length 28

The frames are 4 bytes longer (46, not 42) and carry vlan 10, the tag that vlan.py read in step 2.

Your turn

The office switch has five ports: 1 and 2 are access ports of VLAN 10 (finance), 3 and 4 are access ports of VLAN 20 (guest), and 5 is a trunk to the router for both. Save the data.

cat > ports.txt <<'EOT'
1 access 10
2 access 10
3 access 20
4 access 20
5 trunk 10,20
EOT
cat > frames2.txt <<'EOT'
1 - 02:00:00:00:00:0a 02:00:00:00:00:0b
2 - 02:00:00:00:00:0b 02:00:00:00:00:0a
3 - 02:00:00:00:00:0c ff:ff:ff:ff:ff:ff
5 20 02:00:00:00:00:0e 02:00:00:00:00:0c
5 10 02:00:00:00:00:0e 02:00:00:00:00:0a
5 30 02:00:00:00:00:0f 02:00:00:00:00:0a
4 - 02:00:00:00:00:0d 02:00:00:00:00:0b
3 - 02:00:00:00:00:0c 02:00:00:00:00:0e
EOT
cat > routes2.txt <<'EOT'
10.10.0.0/24 - eth0.10
10.20.0.0/24 - eth0.20
10.10.8.0/24 10.10.0.2 eth0.10
0.0.0.0/0 203.0.113.1 eth1
EOT

A line of frames2.txt has the port, the VLAN tag (- if untagged) and the two MACs. Copy switch.py and make it know the VLANs. An access port puts its frames in its own VLAN. A trunk port takes the VLAN from the tag. Keep one MAC table for each VLAN, flood only inside the VLAN, and drop a frame whose VLAN is not allowed on its port. Look at the frame from port 4 to 0b: does it reach finance? Then run route.py on routes2.txt, the table of the office router, for 10.10.0.9, 10.10.8.5 and 8.8.8.8. The router has one cable to the switch: eth0.10 is the tag for finance and eth0.20 the tag for guest. Answer from your own output.

Answer the owner in two sentences: can a guest frame reach finance on this switch? The router has a direct route to finance, so what must it do with guest packets?

A model VLAN switch

{int(v) for v in vlans.split(",")} builds a set: a collection with no order and no repeats, here the allowed VLAN numbers of a port. setdefault(vlan, {}) returns the table of that VLAN, and makes an empty one the first time. min(allowed) is the one VLAN of an access port.

import sys

ports = {}  # port -> (kind, allowed VLANs)
for line in open(sys.argv[1]):
    port, kind, vlans = line.split()
    ports[int(port)] = (kind, {int(v) for v in vlans.split(",")})

tables = {}  # VLAN -> {MAC: port}
for line in open(sys.argv[2]):
    port, tag, src, dst = line.split()
    port = int(port)
    kind, allowed = ports[port]
    vlan = int(tag) if kind == "trunk" else min(allowed)
    if vlan not in allowed:
        print(f"port {port}: VLAN {vlan} not allowed, drop")
        continue
    table = tables.setdefault(vlan, {})
    table[src] = port
    if dst in table:
        action, out = "forward", [table[dst]]
    else:
        action, out = "flood", [p for p in ports if vlan in ports[p][1] and p != port]
    print(f"VLAN {vlan}  {src[-2:]} -> {dst[-2:]}  {action:<8} out {out}")
print(tables[20])

Three lines of its output say flood, and they send 2 + 2 + 2 = 6 copies. The frame from port 4 to 0b floods only to ports 3 and 5 (VLAN 20), so finance never sees it. The router must drop the guest packets that it would route to finance (lesson 12 shows a rule that drops).

Check yourself

Two computers have the addresses 10.1.1.5/24 and 10.1.1.6/24, but they are in different VLANs on one switch. Can they talk?

No. Each VLAN is a separate broadcast domain, so the ARP request of one never reaches the other. They need a router.

A host sends a packet to a server on another network. Which MAC address and which IP address are in the destination fields of the frame?

The MAC address is the default gateway's, found with ARP. The IP address is the server's.

What is the difference between an access port and a trunk port?

An access port belongs to one VLAN and sends untagged frames. A trunk port carries many VLANs and tags each frame.

Field notes

  • A VLAN separates broadcast domains. It is not a firewall. Put the filter rules between VLANs on the router (lesson 12 shows a rule on a router), and test them from a machine in the VLAN.
  • Two classic VLAN attacks are double tagging (the first switch removes the outer tag, the second reads the inner one) and a user port that negotiates a trunk. Turn off automatic trunking on user ports, keep users out of the native VLAN, and shut unused ports.
  • Test the rules between VLANs from a host inside each VLAN, in both directions. A rule list shows the intent, not what the router does.