Part II — Hands-on networking · Chapter 4

The virtual network lab: namespaces, bridges and OvS

~45 min read5 interactive widgets4 plates

In this chapter

  1. Why build a virtual network at all
  2. The building blocks: namespaces, veth, bridges, switches
  3. Exercises 1 to 3: two hosts, three ways to connect them
  4. One switch, one LAN, then two LANs
  5. Adding a router: inter-LAN routing
  6. ARP, ip neigh and ARP poisoning
  7. NAT and MASQUERADE
  8. Forwarding tables and the two paths
  9. Virtual LANs and IEEE 802.1Q
  10. Tunnels: GRE and VXLAN
  11. Check your understanding

1. Why build a virtual network at all

The virtual network infrastructure of chapter 2 was described from the outside; here it is built from the inside, by hand, on a single Linux machine. The motivation stated in the lab is the same one that justified emulation in general: computer networks are complex — several devices, several interfaces, several protocols running, and physical interconnections that originate complex topologies — and you cannot experiment on a live one.

The physical picture the lab starts from is worth keeping in mind, because the whole exercise is to reproduce it on one host:

The mapping from physical roles to Linux constructs is the plan for the whole chapter:

RoleVirtual construct
HostLinux network namespace — a separate protocol stack with its own IP addresses, routing tables and forwarding strategies
SwitchLinux bridge (unmanaged) or Open vSwitch (more advanced)
Cableveth pair — a virtual Ethernet link with a plug at each end
Router / application gatewayA namespace (or container / VM) that segregates processes and forwards between stacks

Why namespaces first? Because network namespaces are the foundation of network isolation in Linux: they isolate network devices, isolate the IPv4 and IPv6 stacks, isolate routing tables and firewall rules, and isolate sockets and port spaces. They are the basic building block behind many virtual networking systems — including the Docker bridge driver from chapter 2 and the Kathará containers of chapter 11.

2. The building blocks: namespaces, veth, bridges, switches

The lab uses the modern ip suite throughout. The commands below are the complete vocabulary you need to build any topology in this chapter; the annotated view groups them by the object they act on.

Managing namespaces

ip netns add NAMESPACE       # create a namespace
ip netns del NAMESPACE       # delete a namespace
ip netns list                # list existing namespaces
ip netns exec NAMESPACE CMD  # run CMD inside NAMESPACE
ip netns monitor             # report namespace events

Creating links and connecting them

# a virtual Ethernet cable with two plugs
ip link add NAME1 type veth peer name NAME2

# a plug can be given a fixed MAC address
ip link add veth0 address "00:00:00:11:11:11" type veth peer name eth-H11

# a Linux bridge: an unmanaged Ethernet LAN switch
ip link add NAME type bridge

# plug one end of a veth into a namespace, the other into a bridge
ip link set NAME netns NAMESPACE     # attach the plug to a namespace
ip link set NAME master BRIDGE       # attach the plug to a bridge

Open vSwitch

ovs-vsctl show                  # list the active switches
ovs-vsctl add-br SW             # create a new switch
ovs-vsctl add-port N_SW N_VETH  # connect a veth end to a switch

Open vSwitch is described as a more recent implementation with more advanced features than the Linux bridge. That difference is not cosmetic: the Linux bridge is a plain unmanaged switch, while OvS is OpenFlow-enabled and is exactly the kind of programmable virtual switch a controller can drive — the reason chapter 3's controller had something to talk to, and the reason the VLAN and tunnelling exercises later in this chapter reach for ovs-vsctl.

Editor's note

There are also the older bridge command (manage the forwarding database with bridge fdb, set link properties with bridge link) and the deprecated arp command. The lab is explicit that arp is deprecated and that the current tool is ip neigh — a small but exam-relevant modernisation.

3. Exercises 1 to 3: two hosts, three ways to connect them

The first three exercises are the same goal — a point-to-point IP network between two namespaces on 172.0.0.0/30 — solved with three different Layer 2 fabrics. Doing the same thing three ways is the point: it isolates what the fabric does from what the hosts do.

ExerciseFabric between Host1 and Host2What it teaches
1A direct veth pair (veth1 ↔ veth2)The cable itself; no switching at all
2A Linux bridge SW1 in betweenSoftware Layer 2 switching, unmanaged
3An Open vSwitch SW1 in betweenThe programmable switch, same wiring

Three checks are required after each: names must be unique within each namespace, the ARP tables must be inspected, and connectivity must be verified. The reference topology for exercise 2/3 is one namespace on each side, a veth from each into the switch:

Host1 and Host2 namespaces each connected by a veth into a central switch SW1 on the 172.0.0.0/30 network Host1 Host2 172.0.0.1/30 172.0.0.2/30 SW1 bridge or OvS veth1 veth2 Exercise 1 removes SW1 and joins veth1 directly to veth2 — the same hosts, no switch.
Plate 4.1 — The base topology of Lab 1. Only the box in the middle changes across exercises 1 to 3.

A concrete, complete version of exercise 3 (Open vSwitch) reads as follows. Every line maps to one of the building blocks above:

# 1. create the two host namespaces
ip netns add Host1
ip netns add Host2

# 2. create two veth cables and hand one plug of each to a host
ip link add veth1 type veth peer name sw-p1
ip link add veth2 type veth peer name sw-p2
ip link set veth1 netns Host1
ip link set veth2 netns Host2

# 3. create the switch and plug the other ends into it
ovs-vsctl add-br SW1
ovs-vsctl add-port SW1 sw-p1
ovs-vsctl add-port SW1 sw-p2
ip link set sw-p1 up
ip link set sw-p2 up

# 4. address the hosts on 172.0.0.0/30 and bring the plugs up
ip netns exec Host1 ip addr add 172.0.0.1/30 dev veth1
ip netns exec Host1 ip link set veth1 up
ip netns exec Host2 ip addr add 172.0.0.2/30 dev veth2
ip netns exec Host2 ip link set veth2 up

# 5. check
ip netns exec Host1 ping -c1 172.0.0.2
ip netns exec Host1 ip neigh          # the arp table, the modern way

4. One switch, one LAN, then two LANs

Exercise 4 scales the switch out: one SW1 with four hosts, all on a single 10.0.1.0/24 network — one switch corresponds to one LAN, a single broadcast domain. Connectivity is tested across all four.

Exercise 5 makes the pivotal change with almost no new equipment: the same four hosts, the same single switch, but the addresses are split into two IP networks, 10.0.1.0/24 and 10.0.2.0/24. Reachability is tested — and the lesson is delivered by what fails. Two hosts on the same switch but on different IP networks cannot reach each other, because a switch does not route between IP networks; it only forwards within one broadcast domain.

Key idea

Exercise 5 separates two ideas that beginners fuse: Layer 2 reachability (are we on the same switch?) and Layer 3 reachability (are we in the same IP network?). Being on the same switch is necessary but not sufficient; crossing IP networks needs a router, which is exactly what exercise 6 adds.

5. Adding a router: inter-LAN routing

Exercise 6 adds a router R1 with one leg in each network — 10.0.1.254 on the first, 10.0.2.254 on the second — so the two IP networks can finally talk. A namespace becomes a router the moment it is allowed to forward between its interfaces (IP forwarding enabled) and the hosts point their default route at it.

Lab session 2 refines this into a routed topology with two switches, one per LAN, both connected to R1, and then chains more routers (R1, R2, R3, R4) across intermediate /30 networks. The single most important sentence of the whole routing lab is stated as the "main message to remember":

For the exam

For the network to work properly, all the network prefixes must appear in the forwarding tables of all the gateways/routers. A prefix may appear on its own, or be summarised into a more general prefix, or be covered by the default route — but it must be reachable from every router that has to forward towards it. A missing prefix in a single router breaks the path.

Manual routes are added with a single command, repeated on every router that needs to know about a remote network:

ip route add <network> via <gateway address>

# e.g. on R1, teach it how to reach the far LAN through R2
ip netns exec R1 ip route add 10.0.2.0/24 via 192.168.0.5

Use the reachability walker below to feel the "every router must know every prefix" rule directly: remove one route and watch a path go dark.

6. ARP, ip neigh and ARP poisoning

The lab makes the deprecation explicit: the arp command is deprecated, and the current tool to manage the ARP table is ip neigh. It shows a table with the IP address, the interface the information was received on, the corresponding MAC address, and a state. The states are worth knowing because they explain the timing behaviour of a LAN:

StateMeaning
REACHABLENeighbour recently confirmed reachable; timer running (usually about 30 seconds in Linux).
STALEEntry is old, no recent confirmation, still usable but needs verification soon.
DELAYSystem waiting briefly before probing; gives upper-layer protocols a chance to confirm reachability.
PROBEActively sending ARP requests, trying to confirm the neighbour is alive.
INCOMPLETEARP request sent, no reply yet, MAC address unknown.
FAILEDNo response after multiple probes; entry considered unreachable.

ARP poisoning

The security exercise turns this machinery into an attack, in the classic three phases. An attacker A (played in the lab by host H12) is connected to the LAN and:

  1. Reconnaissance — gather useful information, in this case which IP hosts are active: arp-scan 10.0.1.0/24.
  2. Scanning — capture traffic with Wireshark to understand which host is the network gateway.
  3. Execution — launch the ARP poisoning to become Man In The Middle: arpspoof -i veth0 -t 10.0.0.11 -r 10.0.0.254.

The study steps use Wireshark on the gateway interface, print the ARP cache in H11 and R1, and run traceroute from H11 to H21 to see the detour. The attack is then made stealthy:

# stop the kernel from advertising a shorter path back
sysctl -w net.ipv4.conf.veth0.send_redirects=0
sysctl -w net.ipv4.conf.all.send_redirects=0

# hide the extra hop from traceroute
iptables -A OUTPUT -o veth0 -p icmp --icmp-type time-exceeded -j DROP
Careful

The two stealth measures are not decorative. Disabling ICMP redirects stops the router from telling H11 "you can reach the gateway directly, skip me", which would undo the poisoning; dropping time-exceeded replies stops traceroute from revealing the attacker as an extra hop. Both attack the diagnostic feedback the network normally gives you — which is exactly why a network IDS (chapter 14) watches for anomalies rather than trusting the endpoints.

7. NAT and MASQUERADE

Exercise 6 is then reworked so that the far side is a private network 192.168.0.0/24, and NAT is applied in R1. The lab uses iptables in the nat table:

# translate everything leaving R1, taking the source from the output interface
iptables -t nat -A POSTROUTING -j MASQUERADE

# reset the nat table and apply NAT one way only, on a specific interface
iptables -t nat -F
iptables -t nat -A POSTROUTING -o veth2 -j MASQUERADE

The verification method is instructive: open Wireshark in R1, ping from H11 to H21 analysing veth1 first and veth2 second, then ping the other way analysing veth2 first and veth1 second. Watching the same ping on the two legs of the router is how you actually see the address being rewritten.

MASQUERADE is a special case of source NAT: as the firewall deck (chapter 14) states, it works like SNAT but automatically assigns the packet the address of the output interface — which is why it is the natural choice for a gateway whose external address may change. The connection tracking that makes this work — first packet rewritten by the nat table, the rest handled automatically by conntrack, replies restored to the original address — is developed fully in chapter 14.

8. Forwarding tables and the two paths

The routing lab ends on a subtle and genuinely important point about the difference between a connection and its two directions. The observations from exercise 9 (the four-router topology) are:

The answer the question is fishing for is that each router independently decides the next hop for a packet based on its own forwarding table and the packet's destination. Nobody decides a whole path; a path is what emerges from a sequence of independent local decisions. That is why a forward path and a return path can legitimately differ (asymmetric routing), and why a single wrong or missing entry anywhere along either direction is enough to break connectivity even though every other router is configured perfectly.

Key idea

A path is not an object anyone owns; it is the trace left by many routers each answering the same tiny question — "given this destination, what is my next hop?" — from its own table. This is the local-decision principle that P4's match-action tables (chapter 6) make explicit and programmable.

9. Virtual LANs and IEEE 802.1Q

Lab session 3 attacks the broadcast-domain problem from section 4. In general one switch corresponds to one LAN: broadcast messages go to all ports regardless of IP configuration, a single broadcast domain. For security and efficiency reasons it is better to separate the broadcast domains of different IP networks, and the switch must be configured accordingly. That is a Virtual LAN.

VLAN classificationHow membership is decided
Static (port-based)Each switch port belongs to one or more VLANs; a host belongs to a VLAN based on the port it is connected to. To move a host, reconfigure the switch port.
DynamicA host belongs to a VLAN based on its MAC or IP address, regardless of the port. To move a host, change the address-to-VLAN configuration.

The problem with extended LANs

The interesting case is an extended LAN with multiple switches: how can we say to which VLAN an Ethernet frame belongs when it crosses the inter-switch interface? The answer is IEEE 802.1Q, which allows an Ethernet frame to specify its VLAN by adding a tag to the Ethernet header. Both ends of the cable must support 802.1Q, and the tag is also used to create virtual sub-interfaces on hosts and routers.

The four-byte IEEE 802.1Q tag: 16-bit Tag Protocol Identifier, 3-bit priority, 1-bit CFI, and 12-bit VLAN identifier TPID — 16 bit usually 0x8100 Priority 3 bit CFI 1 bit VID — VLAN identifier, 12 bit VLAN number, 0 to 4095 Four bytes inserted into the Ethernet header. 12 bits of VID is why there are at most 4096 VLANs — and why VXLAN's 24-bit VNI (16M segments) exists.
Plate 4.2 — The 802.1Q tag. The 12-bit VID caps VLANs at 4096, a limit that directly motivates the tunnelling of section 10.

Port modes and the commands

Access modeTrunk mode
Port belongs to a single VLAN; 802.1Q tagging not required; typical for ports connected to simple hosts. Port belongs to multiple VLANs; 802.1Q tagging required to tell which VLAN a frame belongs to; can carry one untagged "native" VLAN and several tagged VLANs at once; typical for ports connected to switches and routers.
# Open vSwitch: an access port on one VLAN
ovs-vsctl set port <interface> tag=<VLAN ID>

# a trunk port carrying several VLANs
ovs-vsctl set port <interface> trunks=ID1,ID2,ID3

# reset
ovs-vsctl clear port <interface> tag trunks vlan_mode

# on a namespace: a tagged sub-interface (router-on-a-stick)
ip link add link <interface> name <sub-interface> type vlan id <VLAN ID>
ip link del <sub-interface>

The last command is the mechanism behind the gateway with a single interface design: a router R1 with one physical leg carries both 10.0.1.254 and 10.0.2.254 as tagged sub-interfaces, and routes between the two VLANs over that one wire.

10. Tunnels: GRE and VXLAN

Lab session 4 starts from a concrete problem. Routing between R1 and R2 requires exchanging routing information across a wide area network — but what if the infrastructure is private and must not be disclosed to the public network? The solution: create a virtual direct connection between R1 and R2 over which the private routing information is exchanged. That virtual wire is a tunnel.

GRE

Generic Routing Encapsulation (GRE, RFC 1701) is a tunnelling protocol over IP for generic protocols. It prepends an outer IP header and a GRE header in front of the original packet — allowing, among other things, IP over IP. The GRE header carries a version, a protocol type (which protocol is encapsulated) and options: checksum, key (authentication of the packet source), sequence number (so the destination can reorder), and routing (source routing policy).

# enable GRE, then create the tunnel endpoint in each router
modprobe ip_gre

ip netns exec R1 ip tunnel add GT1 mode gre \
    remote 192.168.0.5 local 192.168.0.1 ttl 63
ip netns exec R1 ip link set GT1 up

# give the tunnel interface an address on both ends
ip netns exec R1 ip addr add 192.168.100.1/30 dev GT1

# route the tenant networks through the tunnel
ip netns exec R1 ip route add 10.0.2.0/24 via 192.168.100.2
ip netns exec R2 ip route add 10.0.1.0/24 via 192.168.100.1

VXLAN

Virtual Extensible LAN (VXLAN) is a highly scalable distributed Layer 2 overlay network for tenant traffic isolation in cloud computing environments. Its defining properties, straight from the slides:

That last figure is the punchline of the whole VLAN-to-VXLAN progression: 802.1Q gives you 12 bits and about 4000 segments; VXLAN gives you 24 bits and 16 million — enough to give every tenant of a large cloud its own isolated Layer 2 segment. The application scenario in the lab is exactly that: one single IP network extended over the global network, VXLAN transporting Ethernet frames — including ARP requests — over an IP network so that hosts on 192.168.1.0/24 behave as if they shared one LAN even though a routed network sits between them.

Two sites each with a virtual bridge and a VTEP, joined by a VXLAN tunnel over an IP network, so that hosts appear to share one Layer 2 segment H1 192.168.1.1 H2 192.168.1.2 br100 VTEP R1 H3 192.168.1.3 H4 192.168.1.4 br100 VTEP R2 VXLAN tunnel — VNI 100 IP Network (UDP dport 4789) The virtual bridges make an L2 broadcast domain; the VTEPs carry its frames across the routed IP network. To the four hosts it is one flat 192.168.1.0/24 LAN.
Plate 4.3 — VXLAN overlay. The virtual bridges create a Layer 2 broadcast domain that the stateless VTEP tunnels stretch over an IP network.
# a VXLAN interface: segment 100, UDP-encapsulated between two VTEPs
ip link add <name> type vxlan id 100 \
    local <local IP> remote <remote IP> nolearning dstport 4789

To make VXLAN carry a broadcast domain, the lab creates a virtual layer-2 broadcast domain using virtual bridges in the routers at the edges of the tunnel, and connects to those bridges every interface whose packets must cross the tunnel. GRE gave a point-to-point virtual wire between two routers; VXLAN gives a whole virtual switch stretched across an IP network.

For the exam

Contrast the two tunnels cleanly. GRE: RFC 1701, encapsulates a packet (IP over IP possible) with an outer IP + GRE header; a point-to-point Layer 3 virtual link, used here to carry private routing information across a public WAN. VXLAN: Layer 2 over UDP (port 4789), stateless VTEP-to-VTEP tunnels, a 24-bit VNI giving 16 million segments; a Layer 2 overlay used to stretch one broadcast domain across an IP network for tenant isolation in the cloud.

Check your understanding

Why are network namespaces studied first, and what do they isolate?

Because they are the foundation of network isolation in Linux and the basic building block behind many virtual networking systems. A network namespace isolates network devices, the IPv4 and IPv6 stacks, routing tables and firewall rules, and sockets and port spaces. Running many namespaces on one machine is running many separate protocol stacks on one machine.

Map each physical network role to its Linux virtual construct.

Host → network namespace; switch → Linux bridge (unmanaged) or Open vSwitch (advanced); cable → veth pair (a virtual Ethernet link with a plug at each end); router or application gateway → a namespace/container/VM that segregates processes and forwards between stacks.

Exercises 1 to 3 connect the same two hosts three ways. What are the three fabrics and why do it three times?

A direct veth pair; a Linux bridge; an Open vSwitch — all on 172.0.0.0/30. Repeating the same goal with three fabrics isolates the fabric's behaviour from the hosts' behaviour, and introduces the difference between an unmanaged bridge and a programmable OvS.

Two hosts are on the same switch but on 10.0.1.0/24 and 10.0.2.0/24. Can they reach each other?

No. A switch forwards within a single broadcast domain but does not route between IP networks. Being on the same switch is Layer 2 reachability; crossing IP networks is Layer 3 reachability and needs a router with a leg in each network (for example R1 at 10.0.1.254 and 10.0.2.254).

What is the "main message to remember" about forwarding tables?

For the network to work properly, all the network prefixes must appear in the forwarding tables of all the gateways/routers. A prefix can appear on its own, be summarised into a more general prefix, or be covered by the default — but every router that must forward towards it needs to know how. One missing entry breaks the path.

Which command replaced arp, and what do the neighbour states mean?

ip neigh replaced the deprecated arp. States: REACHABLE (recently confirmed, ~30 s timer), STALE (old but usable, needs reverification), DELAY (waiting briefly before probing), PROBE (actively sending ARP requests), INCOMPLETE (request sent, no reply, MAC unknown), FAILED (unreachable after multiple probes).

Describe the three phases of the ARP-poisoning exercise and the two stealth measures.

Reconnaissance (arp-scan to find active hosts), scanning (Wireshark to find the gateway), execution (arpspoof to become man-in-the-middle). Stealth: disable ICMP redirects (sysctl ... send_redirects=0) so the router does not advertise a direct path, and drop outgoing ICMP time-exceeded with iptables so traceroute cannot reveal the extra hop.

What is MASQUERADE and why suit it a gateway?

It is a form of source NAT that works like SNAT but automatically assigns the packet the address of the output interface. That makes it ideal for a gateway whose external address may change, since you do not have to hard-code a source address. In the lab, iptables -t nat -A POSTROUTING -j MASQUERADE on R1, verified with Wireshark on R1 watching both legs.

Can the forward and backward paths differ, and who decides them?

Yes — forward and backward paths do not need to be the same. Nobody decides a whole path: each router independently chooses the next hop for a packet from its own forwarding table and the packet's destination. A path is the emergent trace of many independent local decisions, which is why asymmetric routing is legitimate and why one wrong entry anywhere breaks connectivity.

Why are VLANs needed and how does 802.1Q solve the extended-LAN problem?

One switch is one broadcast domain; for security and efficiency it is better to separate the broadcast domains of different IP networks. When a frame crosses an inter-switch link you cannot otherwise tell which VLAN it belongs to. IEEE 802.1Q adds a 4-byte tag to the Ethernet header (TPID usually 0x8100, 3-bit priority, 1-bit CFI, 12-bit VID, 0–4095); both ends must support it. Access ports carry one untagged VLAN, trunk ports carry several tagged VLANs.

Contrast GRE and VXLAN.

GRE (RFC 1701): a tunnelling protocol over IP for generic protocols, prepending an outer IP + GRE header (IP over IP possible); a point-to-point Layer 3 virtual link, used to carry private routing info across a public WAN. VXLAN: a Layer 2 overlay encapsulating Ethernet in UDP (port 4789), stateless VTEP-to-VTEP tunnels, each segment a 24-bit VNI (16 million segments); used to stretch one broadcast domain across an IP network for tenant isolation.

Why is the 24-bit VNI significant compared to the 802.1Q VID?

The 802.1Q VID is 12 bits, capping VLANs at 4096 segments — too few for a large multi-tenant cloud. The VXLAN VNI is 24 bits, giving about 16 million segments, enough to give every tenant its own isolated Layer 2 segment. The jump from 12 to 24 bits is the whole reason VXLAN exists.