Linux’s Hour 8: Advanced Networking and TLS / PKI
- Draw the Linux packet receive/transmit path: NIC → driver (NAPI) →
sk_buff→ tc → netfilter hooks → routing decision → socket, and state which layer tcpdump, nftables, andip routeoperate at. - Use only the
ipcommand to build a topology with two network namespaces + veth + Linux bridge + NAT, and understand its correspondence to Docker’s default bridge and Kubernetes CNI. - Use
ip ruleand multiple routing tables to resolve “return traffic taking the wrong interface” on multihomed hosts, write SNAT / MASQUERADE / DNAT rules with nftables, and observe NAT mappings withconntrack. - Explain SYN queues and accept queues,
somaxconn, TIME_WAIT and local port exhaustion, keepalive, and BBR, and collect evidence withss -tiandnstat. - Clearly explain the differences between TLS 1.3 and 1.2 handshakes, how certificate chains are verified level by level, the roles of SNI and ALPN, and the status of certificate revocation after 2025 (OCSP phased out and CRL returning).
- Use openssl to build a two-tier private CA (root + intermediate), issue server and client certificates with SANs, revoke certificates and publish a CRL, and add the root certificate to the Ubuntu / RHEL trust stores.
- Use ACME (certbot and other tools) for HTTP-01 / DNS-01 automatic renewal, design renewal and expiration monitoring according to the CA/B Forum’s 200 → 100 → 47-day validity-period schedule, and use nginx for mTLS.
- Use
openssl s_client,curl -v, andtracepathto quickly locate incomplete chains, hostname mismatches, expiration, clock skew, missing SNI, and MTU issues.
1-Hour Time Allocation
| # | Time | Module | Core Content | Animation / Interaction | Lab (linuxlab VM) |
|---|---|---|---|---|---|
| 0 | Before class | Preparation: Network Namespace Lab Topology and openssl | Install the tools, generate ~/linuxlab/net8/topo.sh (the red / blue namespaces + br-lab + NAT), and check openssl and firewall forwarding policies | Environment self-check | topo.sh up smoke test |
| 1 | 00–06 | Linux Network Stack Overview | NIC, DMA rings, interrupts and NAPI, sk_buff, GRO/GSO, the five tc/netfilter hooks, routing decisions, and socket buffers | Core animation: the receive / transmit / forwarding path of a packet | ethtool、ip -s link、/proc/net/softnet_stat、nft monitor trace |
| 2 | 06–13 | bridge, veth, VLAN, and Network Namespaces | veth pairs, Linux bridge and FDB, VLAN subinterfaces and VLAN-aware bridge, ip netns, and their correspondence to Docker / K8s networking | Core animation: packet paths from red → blue and from red → the Internet (via NAT) | Build the topology manually and observe ARP and FDB learning |
| 3 | 13–21 | Policy Routing, Multihoming, and NAT | ip rule, multiple routing tables, multi-NIC return paths, rp_filter, ip_forward, SNAT / MASQUERADE / DNAT, conntrack | Routing Decision Simulator (Rules → Tables → Routes) | Reproduce and fix “the return path uses the wrong interface,” and implement port forwarding |
| 4 | 21–28 | TCP Queues, TIME_WAIT, and Keepalive | Three-way handshake, SYN / accept queues, somaxconn, syncookies, TIME_WAIT and port exhaustion, keepalive, congestion control and BBR, ss -ti | Listen Queue Simulator | Cause accept queue overflow and switch to BBR |
| 5 | 28–35 | TLS Fundamentals: Handshake, Certificate Chains, and SNI | TLS 1.3 / 1.2 handshakes, key exchange (including X25519MLKEM768), certificate chains and trust stores, SNI, ALPN, current revocation status | Core Animation: TLS 1.3 Handshake + Step-by-Step Certificate Chain Verification | Dissect a real website with openssl s_client |
| 6 | 35–42 | PKI in Practice: An OpenSSL Private CA | Root CA / intermediate CA, extensions (basicConstraints, keyUsage, EKU, SAN, CDP), the openssl ca database, revocation and CRLs, trust stores | PKI Builder (Issuing / Revoking / Verifying) | Build a two-tier CA and issue server and client certificates for myapp |
| 7 | 42–50 | ACME, Rotation, and mTLS | ACME workflows, HTTP-01 / DNS-01 / TLS-ALPN-01, certbot and other clients, ARI, shortened validity-period timelines, rotation and expiration monitoring, nginx mTLS | Certificate Validity and Renewal Strategy Simulator | Enable mTLS for myapp in nginx + configure an expiration-check timer |
| 8 | 50–60 | Network and TLS Troubleshooting and Self-Assessment | openssl s_client troubleshooting patterns, expired certificates / incomplete chains / hostname mismatches / clock skew / SNI / MTU, curl -v | TLS Fault Locator + Interactive Troubleshooting Tree | Fault injection: diagnose 5 TLS faults one by one |
| — | After the Lesson | Cheat Sheet · Comprehensive Lab | End-to-end exercise: “Put myapp behind an internal HTTPS + mTLS gateway” | Course Completion Quiz (12 Questions) | Comprehensive Lab |
Knowledge Coverage Matrix
| Target Skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key Commands | Labs |
|---|---|---|---|---|---|---|---|---|---|---|
| Network stack layering and observation points | ✓ | ✓ | ✓ | ✓ | · | · | · | ✓ | ethtool -S、ip -s link、nft monitor trace | M1 |
| Virtual networking (netns / veth / bridge / VLAN) | · | ✓ | ✓ | ✓ | · | · | ✓ | ✓ | ip netns、ip link add type veth、bridge fdb | topo.sh |
| Policy routing and NAT | ✓ | ✓ | ✓ | · | · | · | · | ✓ | ip rule、ip route get、nft、conntrack -L | Return-path repair, port forwarding |
| TCP connection management and tuning | ✓ | · | · | ✓ | · | · | · | ✓ | ss -ltn、ss -ti、nstat、sysctl net.ipv4.tcp_* | Queue overflow, BBR |
| TLS handshakes, SNI, ALPN | · | · | · | · | ✓ | · | ✓ | ✓ | openssl s_client -servername -alpn、curl -v | Dissecting a real website |
| Certificate chains, trust stores, revocation | · | · | · | · | ✓ | ✓ | ✓ | ✓ | openssl verify、update-ca-certificates、update-ca-trust | Private CA |
| Private CA issuance and CRLs | · | · | · | · | · | ✓ | ✓ | ✓ | openssl req、openssl ca -gencrl | Two-tier CA |
| ACME automation, rotation, expiration monitoring | · | · | · | · | ✓ | · | ✓ | ✓ | certbot renew、openssl x509 -checkend | certcheck timer |
| mTLS | · | · | · | · | ✓ | ✓ | ✓ | ✓ | ssl_verify_client、curl --cert --key | nginx mTLS |
Topics Not Covered in This Lesson (and Where to Learn Them)
| Topic | Why It Is Not Covered in This Lesson | Where to Learn It |
|---|---|---|
ip/ss fundamentals, netplan, systemd-resolved | Covered in Lesson 2 | Lesson 2 M5 |
| Basic troubleshooting of tcpdump filters, retransmissions / full conntrack tables / DNS timeouts | Covered in Lesson 7; this lesson only provides links | Lesson 7 M5 |
| nftables filtering rules, firewalld, ufw | Covered in Lesson 6; this lesson covers only NAT and forwarding | Lesson 6 M3 |
| Overall principles of namespaces / cgroups | Covered in Lesson 6; this lesson focuses only on network namespaces in depth | Lesson 6 M7 |
| Docker network drivers, Kubernetes CNI, Service, Ingress / Gateway API, cert-manager | Part of the container platform | Docker in 8 Hours, Kubernetes in 8 + 1 Hours |
| Certificate expiration alert dashboard (blackbox_exporter) | Part of the monitoring system | Prometheus & Grafana in 8 + 1 Hours |
| WireGuard / IPsec VPN, BGP, eBPF/XDP data-plane programming, HSM and enterprise CA software (EJBCA, step-ca, Vault PKI) | Requires a separate course | Official documentation for each project; the openssl concepts in this course can be directly transferred |
How to Use This Courseware
Principles · Diagrams · Animation · Commands · Labs · Production Cases · Troubleshooting · Quiz · Voice · Video. Recommended sequence: principles → animation → perform the lab on linuxlab → troubleshooting.
A quiz score of ≥ 70% or clicking “Mark This Module Complete” counts toward progress. Progress is saved in this browser (if local storage is disabled, it will be cleared after a refresh).
The “Voice” page uses the browser’s built-in Web Speech API (zh-CN) to read the lecture script aloud; when no Chinese voice package is available, the lecture script can be read directly or provided to a TTS tool.
3.5.5-1ubuntu3.7, nftables 1.1.6-1, nginx 1.28.3, certbot 4.0.0-4 (universe), and iproute2 6.19. Latest upstream versions: OpenSSL 4.1.0 (2026-10-23); OpenSSL 3.5 is an LTS release (supported until 2030-04); certbot 5.10.0 (2026-11-10, available through the snap channel). Certificate validity periods are governed by the CA/B Forum Baseline Requirements 2.3.1: maximum 200 days from 2026-03-15, 100 days from 2027-03-15, and 47 days from 2029-03-15. The RHEL-family comparison machine rhellab (Rocky / AlmaLinux 10) appears only in the trust store and firewalld sections. Any output not executed on a real machine is labeled “Example”.Module 0 · Preparation: Network Namespace Lab Topology and openssl (Complete Before the Course)
- Lab machine created in Lesson 1: hostname
linuxlab, userlabadmin(with sudo privileges), working directory~/linuxlab. Recommended: 2 vCPUs / 4 GiB / 20 GiB (multipass launch --name linuxlab --cpus 2 --memory 4G --disk 20G). - myapp deployed in Lesson 2:
myapp.service, port 5000,/healthz, configuration at/etc/myapp/myapp.env. M7 will add an nginx TLS gateway in front of it. - Transition from Lesson 7: the
~/linuxlab/faults/fault-injection toolkit is not needed; if any artifacts remain, runsudo ~/linuxlab/faults/reset.shfirst. - Transition from Lesson 6: if UFW is enabled, its default forward policy is DROP, which blocks namespaces from accessing the internet (see Step 3).
- WSL2 users: WSL2 can create network namespaces, but NAT, bridging, and kernel modules (such as
tcp_bbr) behave differently than in a real virtual machine; use Multipass / Hyper-V / VirtualBox.
Step 1: Install the tools
sudo apt update sudo apt install -y iproute2 nftables conntrack tcpdump ethtool openssl ca-certificates \ curl bind9-dnsutils nginx python3 openssl version; nft --version; ip -V systemctl is-active myapp
OpenSSL 3.5.5 <发布日期> (Library: OpenSSL 3.5.5 <发布日期>) nftables v1.1.6 (<版本代号>) ip utility, iproute2-6.19.0, libbpf 1.6.x active
The release date and codename following the version number may vary. After installation, nginx starts automatically and listens on port 80; it will be configured in M7. If it is not needed yet, you can run sudo systemctl disable --now nginx.
Step 2: Generate the topology script ~/linuxlab/net8/topo.sh
Topology: Create a Linux bridge br-lab on the host (linuxlab) (10.200.0.1/24, acting as a switch + default gateway). Two network namespaces, red (10.200.0.10) and blue (10.200.0.20), each connect to br-lab via a pair of veth interfaces. Enable forwarding on the host, and use the nftables table ip lab8 to MASQUERADE 10.200.0.0/24 to the uplink interface. The multi subcommand adds a second subnet and a multi-NIC namespace for Module 3.
mkdir -p ~/linuxlab/net8 && cd ~/linuxlab/net8
cat > topo.sh <<'EOF'
#!/usr/bin/env bash
# Linux 第 8 课实验拓扑:只能在 linuxlab 上运行
set -euo pipefail
[ "$(hostname)" = "linuxlab" ] || { echo "拒绝执行:只允许在 linuxlab 上运行" >&2; exit 1; }
[ "$(id -u)" -eq 0 ] || { echo "请用 sudo 运行:sudo $0 $*" >&2; exit 1; }
UPLINK="$(ip route show default | awk '{print $5; exit}')"
SAVE=/run/lab8.ipfwd
mkns() { # mkns 名字 网桥 地址/掩码 网关 [命名空间内的网卡名]
local ns=$1 br=$2 addr=$3 gw=$4 dev=${5:-eth0}
ip netns list | grep -qw "$ns" || ip netns add "$ns"
ip link add "v-$ns-$dev" type veth peer name "$dev" netns "$ns"
ip link set "v-$ns-$dev" master "$br" up
ip -n "$ns" addr add "$addr" dev "$dev"
ip -n "$ns" link set lo up
ip -n "$ns" link set "$dev" up
[ -n "$gw" ] && ip -n "$ns" route add default via "$gw" dev "$dev"
return 0
}
up() {
[ -f "$SAVE" ] || sysctl -n net.ipv4.ip_forward > "$SAVE"
ip link add br-lab type bridge
ip addr add 10.200.0.1/24 dev br-lab
ip link set br-lab up
mkns red br-lab 10.200.0.10/24 10.200.0.1
mkns blue br-lab 10.200.0.20/24 10.200.0.1
sysctl -qw net.ipv4.ip_forward=1
nft -f - <<NFT
table ip lab8 {
chain postrouting {
type nat hook postrouting priority srcnat; policy accept;
ip saddr 10.200.0.0/16 oifname "$UPLINK" counter masquerade
}
}
NFT
echo "拓扑已创建:br-lab 10.200.0.1,red 10.200.0.10,blue 10.200.0.20,出口 $UPLINK"
}
multi() { # 模块 3:第二个网段 br-lab2 + 双网卡命名空间 green + 独立网段的 client
ip link add br-lab2 type bridge
ip addr add 10.201.0.1/24 dev br-lab2
ip link set br-lab2 up
mkns green br-lab 10.200.0.30/24 10.200.0.1 eth0
mkns green br-lab2 10.201.0.30/24 "" eth1
ip netns add client
ip link add v-client type veth peer name eth0 netns client
ip addr add 10.202.0.1/24 dev v-client; ip link set v-client up
ip -n client addr add 10.202.0.50/24 dev eth0
ip -n client link set lo up; ip -n client link set eth0 up
ip -n client route add default via 10.202.0.1
echo "multi 已创建:green eth0=10.200.0.30 eth1=10.201.0.30,client=10.202.0.50"
}
down() {
for ns in red blue green client; do ip netns del "$ns" 2>/dev/null || true; done
for l in br-lab br-lab2 v-client; do ip link del "$l" 2>/dev/null || true; done
nft delete table ip lab8 2>/dev/null || true
if [ -f "$SAVE" ]; then sysctl -qw net.ipv4.ip_forward="$(cat "$SAVE")"; rm -f "$SAVE"; fi
echo "拓扑已清理"
}
status() {
ip -br link show type bridge; ip netns list
for ns in $(ip netns list | awk '{print $1}'); do echo "== $ns"; ip -n "$ns" -br addr; done
nft list table ip lab8 2>/dev/null | grep -E 'masquerade|dnat|snat|drop' || true
}
case "${1:-}" in up) up ;; multi) multi ;; down) down ;; status) status ;;
*) echo "用法:sudo $0 {up|multi|down|status}"; exit 2 ;; esac
EOF
chmod +x topo.sh
sudo ./topo.sh up
sudo ./topo.sh status
拓扑已创建:br-lab 10.200.0.1,red 10.200.0.10,blue 10.200.0.20,出口 ens3
br-lab UP 0a:58:3c:1e:2f:44 <BROADCAST,MULTICAST,UP,LOWER_UP>
blue (id: 1)
red (id: 0)
== blue
lo UNKNOWN 127.0.0.1/8 ::1/128
eth0@if7 UP 10.200.0.20/24 fe80::5c1e:9aff:fe21:3b10/64
== red
lo UNKNOWN 127.0.0.1/8 ::1/128
eth0@if5 UP 10.200.0.10/24 fe80::d4a2:11ff:fe8b:7c01/64
ip saddr 10.200.0.0/16 oifname "ens3" counter packets 0 bytes 0 masquerade
Namespaces and veth interfaces do not persist across reboots (they exist in memory); after reboot, run sudo ./topo.sh up again. In eth0@if7, if7 is the ifindex of the peer veth on the host. The uplink interface name (ens3, enp0s1, eth0) varies by platform.
Step 3: Confirm that forwarding is not blocked by the firewall
sudo ip netns exec red ping -c 2 10.200.0.20 # 同网段:经 bridge 二层转发 sudo ip netns exec red ping -c 2 1.1.1.1 # 出网:经宿主机路由 + NAT sudo ufw status 2>/dev/null | head -1 sudo nft list ruleset | grep -E 'hook forward'
DEFAULT_FORWARD_POLICY="DROP"; run sudo ufw route allow in on br-lab out on <uplink interface> (return traffic is allowed by UFW's conntrack rules). ② On machines with Docker installed, the iptables FORWARD chain policy is often DROP, and br_netfilter causes bridged traffic to pass through iptables as well. A drop in the forward chain of any nftables table will drop packets; adding accept to the lab8 table cannot “override” other tables. Cloud hosts also need their cloud-side source/destination checks checked (this lesson only forwards traffic in a local virtual machine; it does not cover that).Step 4: Prepare the PKI and log directories
mkdir -p ~/linuxlab/pki ~/linuxlab/net8/captures echo "10.200.0.20 myapp.lab.internal" | sudo tee -a /etc/hosts openssl list -kem-algorithms | head -5 # 3.5 起内置 ML-KEM openssl ciphers -s -tls1_3
{ 1.2.840.113549.1.1.1, 2.5.8.1.1, RSA } @ default
ML-KEM-512 @ default
ML-KEM-768 @ default
ML-KEM-1024 @ default
X25519MLKEM768 @ default
TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256
myapp.lab.internal resolves to blue's address (the M6 server certificate uses this name). .internal is a top-level domain reserved by ICANN for private network use and will not conflict with public domain names. The list format may vary.
Module 1 · An Overview of the Linux Network Stack: From NIC to Socket
- State the packet receive path in order: NIC DMA → interrupts + NAPI polling →
sk_buff→ GRO → tc ingress → netfilter PREROUTING → routing decision → INPUT / FORWARD → socket. - State where each of netfilter’s five hooks (PREROUTING, INPUT, FORWARD, OUTPUT, POSTROUTING) is located, and why DNAT and SNAT are placed on the first and last hooks, respectively.
- Know the respective observation / intervention points of tcpdump, XDP, tc, nftables, and the routing table, and be able to use
ethtool -S,ip -s link,/proc/net/softnet_stat, andnft monitor traceto locate “which layer dropped the packet.”
ip addr / ip route from Lesson 2, M5, and the tcpdump capture points in Lesson 7, M5. Importance:★★★★★ (all subsequent modules are located on this map)What: The Packet’s Journey Through the Kernel
- NIC and driver: The NIC writes received frames to the receive ring (RX ring) in memory via DMA, then triggers a hard interrupt. The driver does only the minimum in the interrupt handler—disables interrupts for that queue and schedules NAPI polling; actual packet reception is completed in batches in the softirq (
NET_RX), avoiding “one interrupt per packet.” Multi-queue NICs use RSS to distribute different flows across different CPUs. sk_buff(skb): The driver allocates astruct sk_bufffor each packet. It is the “packet descriptor” passed through the network stack: it points to the data buffer (head / data / tail / endpointers), records the header offsets for each layer, the associated device, timestamp, mark, conntrack pointer, and so on. When processing headers at each layer, the stack moves pointers instead of copying data; tcpdump receives a clone of the skb.- XDP and GRO: The XDP program (eBPF) runs in the driver before skb allocation and can directly drop or redirect packets. It is commonly used for DDoS protection and load balancing; GRO combines multiple small packets from the same flow into a large packet before passing it upward, reducing per-packet overhead (in the transmit direction, the corresponding mechanisms are GSO / TSO: the protocol stack passes down a large packet, which is finally segmented by the NIC or driver).
- tc ingress and capture points: AF_PACKET (tcpdump) obtains a copy here; the tc (traffic control) ingress can perform classification, rate limiting, and eBPF operations.
- netfilter hooks: There are five hooks at the IP layer. nftables / iptables rules and conntrack (connection tracking) are attached to them: PREROUTING (just after entering the IP layer, where conntrack creates an entry and DNAT is performed) → routing decision → packets destined for the local host go through INPUT, while packets that need forwarding go through FORWARD → before leaving, packets go through POSTROUTING (SNAT / MASQUERADE). Packets sent by the local host first go through OUTPUT.
- Routing decision: First, the policy rules (
ip rule) are consulted to determine which routing table to use; then the longest-prefix match is performed in that table to obtain the output interface, next hop, and source address (explained in detail in Module 3). - Transport layer and sockets: TCP/UDP finds the socket based on the four-tuple, and the data enters the receive buffer, waking processes blocked on
recv()/epoll. Listening sockets also have a SYN queue and an accept queue (Module 4). - Sending direction:
send()→ socket send buffer → TCP segmentation (or a GSO large packet) → IP routing → OUTPUT → POSTROUTING → qdisc (queueing disciplines, such asfq_codelandfq) → packet capture point → driver TX ring → network card.
Why: Why Operations Engineers Need to Understand This Diagram
“The packet was dropped” can happen at any point: the NIC ring is full (rx_missed_errors), soft interrupt processing cannot keep up (dropped / time_squeeze in softnet), the firewall issues a DROP, no route matches (Network is unreachable), reverse-path filtering (rp_filter), the conntrack table is full, the socket buffer is full, or the accept queue overflows. Different points have different counters—only by knowing how far the packet got can you know which counter to check.
How: Observation Tools for Each Point
| Point | Typical Problems | What to Check |
|---|---|---|
| NIC / driver | Ring full, CRC errors, link negotiation | ethtool -S IF (rx_missed, rx_crc_errors), ethtool -g IF (ring size), ip -s -s link |
| Soft interrupts / NAPI | One CPU fully utilized, packet backlog | /proc/net/softnet_stat (one CPU per line; column 2 is dropped, column 3 is time_squeeze, in hexadecimal), %soft in mpstat -P ALL |
| tc / qdisc | Rate limiting, netem, queue drops | tc -s qdisc show dev IF |
| netfilter | Rule DROP, NAT errors, conntrack full | nft list ruleset (with counter), nft monitor trace, conntrack -S |
| Routing | Wrong egress, no route, rp_filter drops | ip route get, ip rule, nstat -az IPReversePathFilter (the counter name depends on the actual system) |
| Socket | Receive buffer full, accept queue overflow | ss -tmi(skmem)、nstat -az TcpExtListenOverflows |
| Full path | “Where exactly was it dropped?” | perf trace / bpftrace tracing the packet-drop reasons for kfree_skb (the skb:kfree_skb tracepoint includes a reason field; see Lesson 7 M7) |
When: Decision Process
- First determine the direction (receive / send / forward) and protocol, then use
ip route get <destination> from <source> iif <incoming interface>to predict how the kernel will route it. - Capture packets once at the ingress and once at the egress (see Lesson 7 for tcpdump capture locations) to determine whether the packet “came in and whether it went out.”
- It came in but did not go out → the intermediate netfilter / routing / rp_filter; use
nft monitor traceto see the rules match one by one. - If even the NIC counters are increasing → the driver or hardware layer (ring size, interrupt affinity, RSS).
Comparison: Several Mechanisms “Attached to the Data Path”
| XDP | tc(cls_bpf / qdisc) | netfilter(nftables) | Socket filtering / eBPF cgroup | |
|---|---|---|---|---|
| Position | Inside the driver, before skb allocation | ingress / egress, with skb | Five hooks at the IP layer (as well as the bridge, arp, and netdev families) | Socket- or cgroup-level |
| Can it see conntrack? | No | No (helper functions are available to query it) | Yes | No |
| Typical uses | DDoS dropping, L4 load balancing | Rate limiting, traffic shaping, Cilium data plane | Firewalls, NAT | Control container ingress and egress traffic by cgroup |
iptables is mostly iptables-nft, and the rules are likewise written to nf_tables. ③ “High softirq usage means there is not enough CPU”—often, all interrupts are landing on a single CPU; check RSS / RPS and irqbalance. ④ “Routing only looks at the destination address”—policy routing can select a table based on the source address, input interface, or fwmark.Figure 1-1: Receive, transmit, and forwarding paths and the five netfilter hooks
Figure 1-2: The pointer model of sk_buff
The receive / transmit / forwarding path of a packet
Select a scenario and click “Play.” The dot moves along the kernel path, and the section below shows what happens at each station and which commands you can use to observe it there (the output is an example). All three scenarios can be reproduced in this lesson’s red / blue topology.
Core commands and parameters
| Command | Function | Description |
|---|---|---|
ip -s -s link show dev IF | Interface receive/transmit statistics | Two -s options show error details (crc, missed, fifo) |
ethtool -S IF / -g / -k / -l | Driver counters / ring size / offload features / queue count | Counter names are determined by the driver; virtual NICs (virtio, veth) have few counters |
cat /proc/net/softnet_stat | Per-CPU softirq receive statistics | Hexadecimal; the 2nd column is drops (backlog full), and the 3rd column is time_squeeze (budget exhausted) |
cat /proc/interrupts | grep IF | Which CPUs the interrupts are distributed across | Used together with /proc/irq/N/smp_affinity_list |
sysctl net.core.netdev_budget net.core.netdev_max_backlog | NAPI budget and backlog queue | Can be increased appropriately when time_squeeze continues to grow |
ip route get 1.1.1.1 from 10.200.0.10 iif br-lab | Simulate a routing decision | When iif is specified, it is evaluated as “forwarding” and is affected by ip_forward and rp_filter |
nft monitor trace | Display in real time the rules matched by each marked packet | First, packets must be marked with a meta nftrace set 1 rule |
tc -s qdisc show dev IF | Egress queuing discipline and drops | Ubuntu defaults to fq_codel (determined by net.core.default_qdisc; verify against the actual configuration) |
IF=$(ip route show default | awk '{print $5; exit}')
ip -s -s link show dev "$IF" | sed -n '1,12p'
ethtool -i "$IF" | head -3; ethtool -l "$IF" 2>/dev/null | tail -5
awk '{print "cpu"NR-1, "processed=0x"$1, "dropped=0x"$2, "squeezed=0x"$3}' /proc/net/softnet_stat
2: ens3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP mode DEFAULT group default qlen 1000
link/ether 52:54:00:9a:1c:07 brd ff:ff:ff:ff:ff:ff
RX: bytes packets errors dropped missed mcast
48211934 41237 0 0 0 0
RX errors: length crc frame fifo overrun
0 0 0 0 0
TX: bytes packets errors dropped carrier collsns
3120875 21876 0 0 0 0
driver: virtio_net
version: 1.0.0
cpu0 processed=0x0000a1f3 dropped=0x00000000 squeezed=0x00000000
cpu1 processed=0x00009c22 dropped=0x00000000 squeezed=0x00000002
Use nft trace to see which rules a packet passes through
sudo nft add table inet tracedemo
sudo nft add chain inet tracedemo pre '{ type filter hook prerouting priority -350; }'
sudo nft add rule inet tracedemo pre ip saddr 10.200.0.10 icmp type echo-request meta nftrace set 1
sudo timeout 10 nft monitor trace &
sudo ip netns exec red ping -c 1 1.1.1.1
sleep 1; sudo nft delete table inet tracedemo
trace id 3c1a7e02 inet tracedemo pre packet: iif "br-lab" ip saddr 10.200.0.10 ip daddr 1.1.1.1 ... icmp type echo-request trace id 3c1a7e02 inet tracedemo pre rule ip saddr 10.200.0.10 icmp type echo-request meta nftrace set 1 (verdict continue) trace id 3c1a7e02 ip lab8 postrouting packet: iif "br-lab" oif "ens3" ip saddr 10.200.0.10 ip daddr 1.1.1.1 ... trace id 3c1a7e02 ip lab8 postrouting rule ip saddr 10.200.0.0/16 oifname "ens3" counter packets 1 bytes 84 masquerade (verdict accept)
Priority -350 causes the marking rule to run before conntrack (-200). The trace shows the packet sequentially passing through PREROUTING, being routed to ens3, and reaching POSTROUTING where it is MASQUERADEd—exactly the forwarding path shown in Figure 1-1.
Lab 1: Verify the three paths in the topology (approximately 6 minutes)
ip route get 10.200.0.20 # 宿主机 → blue(本机发出) ip route get 1.1.1.1 from 10.200.0.10 iif br-lab # red → 互联网(转发) sudo ip netns exec blue ip route get 10.200.0.10 # blue → red(命名空间内)
10.200.0.20 dev br-lab src 10.200.0.1 uid 1000
cache
1.1.1.1 from 10.200.0.10 via 192.168.64.1 dev ens3
cache iif br-lab
10.200.0.10 dev eth0 src 10.200.0.20 uid 0
cacheIF=$(ip route show default | awk '{print $5; exit}')
sudo tcpdump -i br-lab -nn -c 2 icmp &
sudo tcpdump -i "$IF" -nn -c 2 icmp &
sleep 1; sudo ip netns exec red ping -c 1 1.1.1.1; wait
10:02:11.120 IP 10.200.0.10 > 1.1.1.1: ICMP echo request, id 4121, seq 1, length 64 10:02:11.121 IP 192.168.64.5 > 1.1.1.1: ICMP echo request, id 4121, seq 1, length 64 10:02:11.135 IP 1.1.1.1 > 192.168.64.5: ICMP echo reply, id 4121, seq 1, length 64 10:02:11.135 IP 1.1.1.1 > 10.200.0.10: ICMP echo reply, id 4121, seq 1, length 64
On br-lab, you see the private address; on the uplink interface, you see the host address—MASQUERADE occurs in POSTROUTING, and conntrack automatically performs the reverse translation on the return path.
sudo sysctl -w net.ipv4.ip_forward=0 sudo ip netns exec red ping -c 1 -W 2 1.1.1.1; echo "exit=$?" nstat -az IpOutNoRoutes IpInAddrErrors IpForwDatagrams sudo sysctl -w net.ipv4.ip_forward=1
From 10.200.0.1 icmp_seq=1 Destination Host Unreachable 1 packets transmitted, 0 received, +1 errors, 100% packet loss, time 0ms exit=1 IpOutNoRoutes 0 0.0 IpInAddrErrors 7 0.0 IpForwDatagrams 1834 0.0
After forwarding is disabled, packets whose destination is not the local host are discarded at the routing decision point (counted under IpInAddrErrors, with an ICMP host-unreachable message sent back; counter attribution depends on the actual kernel); tcpdump can still see the requests on br-lab.
grep -E 'NET_RX|NET_TX' /proc/softirqs sudo ip netns exec red ping -f -c 20000 10.200.0.20 >/dev/null grep -E 'NET_RX|NET_TX' /proc/softirqs
Only root can initiate a flood ping. The CPU whose NET_RX count increases is the CPU processing these packets. The veth “receive packet” path likewise uses the NAPI soft-interrupt path.
tracedemo table, run sudo nft delete table inet tracedemo.Case 1: Packet loss during peak periods, while CPU usage is only 40%
Problem: An 8-core gateway drops packets during traffic peaks, while overall CPU usage is only 40%. Procedure: mpstat -P ALL 1 shows that CPU0’s %soft is close to 100%, while the other cores are idle; the first line of /proc/net/softnet_stat shows time_squeeze continuing to increase; ethtool -l shows that the network interface has only one queue enabled. Configuration: Enable multi-queue RSS with ethtool -L IF combined 8, and confirm that irqbalance is running; for virtual network interfaces that cannot use multiple queues, RPS can be used (/sys/class/net/IF/queues/rx-0/rps_cpus). Limitation: The number of queues is limited by the network interface and virtualization platform (for cloud instances, the number of queues is usually tied to the instance type).
Case 2: Firewall rules “look right,” but packets are dropped
Problem: A newly added nftables accept rule does not take effect. Procedure: nft monitor trace shows the packet being dropped in the forward chain of another table (created by some proxy software). Conclusion: Multiple base chains on the same hook are all executed in priority order, and a drop in any of them is final; accept only ends the current chain. Improvement: Unify the source of the rules, or allow the traffic in the table where the conflict occurs.
Case 3: Packet capture shows the request, but the application log does not
Problem: tcpdump on the server shows the client’s SYN, but the server has no connection records. Procedure: tcpdump captures packets before netfilter; the counters in the input chain in nft list ruleset show that an old rule dropped the packet. Lesson: “Capturing a packet” only proves that it reached the network interface, not that it reached the socket.
Common Errors and Solutions
connect: Network is unreachable
Cause: Route lookup failure: no route (including a default route) matches the destination address, so the kernel immediately returns ENETUNREACH and the packet never leaves the local machine.
ip route get <目的地址> ip route show table all | grep -E '^default|unreachable' ip rule
Fix: Add a default route or a specific route (persist it with netplan); check whether policy routing is directing traffic to an empty table.
RTNETLINK answers: File exists
Cause: The entry to be added by ip addr add / ip route add already exists (for example, because topo.sh up was run more than once).
ip -br addr; ip route; sudo ./topo.sh status
Fix: Use ip route replace instead of add to make the operation idempotent; or run sudo ./topo.sh down before up.
The second column (dropped) in /proc/net/softnet_stat keeps increasing
Cause: The per-CPU backlog queue (net.core.netdev_max_backlog) is full. This commonly occurs on paths that require queueing, such as RPS or veth, under high packet-per-second (pps) loads.
sysctl net.core.netdev_max_backlog net.core.netdev_budget mpstat -P ALL 1 3 | grep -E 'CPU|all| 0 '
Fix: Increase netdev_max_backlog moderately and distribute the load across multiple cores (RSS / RPS); first confirm that this counter is actually increasing—do not adjust it blindly.
Error: Could not process rule: No such file or directory
Cause: The table or chain referenced by the nft command does not exist (for example, the table or chain was not created before nft add rule inet tracedemo pre ...), or the family is incorrect (ip and inet are different table types).
sudo nft list tables sudo nft list table ip lab8
Fix: Create the table and chain first; note that table ip lab8 and table inet lab8 are two different tables.
1. Without sending any packets, determine which interface and next hop a packet arriving from red (10.200.0.10) via br-lab and destined for 8.8.8.8 would be forwarded through.
ip route get 8.8.8.8 from 10.200.0.10 iif br-lab
2. Display each CPU’s softnet drop count and time_squeeze count in decimal.
awk '{printf "cpu%d dropped=%d squeeze=%d\n", NR-1, strtonum("0x"$2), strtonum("0x"$3)}' /proc/net/softnet_statstrtonum is a gawk extension; when Ubuntu’s default awk is mawk, use gawk or printf '%d\n' 0x... instead.
A Linux gateway performing NAT occasionally fails when an internal client accesses the external network. tcpdump on the gateway sees the SYN on the internal interface but not on the external interface. In network stack order, which points would you check in sequence?
The packet entered through the internal interface but did not leave through the external interface, so the problem is somewhere between the two: ① PREROUTING (whether DNAT / marking rules are causing unintended matches, and whether conntrack is full: conntrack -S, dmesg | grep conntrack); ② routing decision (ip route get destination from client iif internal-interface, policy routing, rp_filter); ③ FORWARD (ip_forward, drop counters for the forward chains in each table, nft monitor trace); ④ POSTROUTING (MASQUERADE port allocation failures are counted under insert_failed / drop in conntrack -S); ⑤ qdisc (tc -s qdisc). The capture point on the external interface is after qdisc, so packets dropped by qdisc will also appear as “not seen.”
Verified Instructional Videos
A video specifically explaining NAPI, sk_buff, and the netfilter hook path: No verified video found; refer to the kernel documentation and the storyboard below.
Official Documentation
- Scaling in the Linux Networking Stack(RSS / RPS / RFS / XPS)
- NAPI(kernel.org) · struct sk_buff(kernel.org)
- Netfilter hooks(nftables wiki) · Ruleset debug / tracing
- ip-route(8) · ethtool(8)
Video Storyboard Script (approximately 90 seconds)
This courseware cannot directly generate video/MP3 files; a storyboard and narration script have been provided.
Visual: The network card uses DMA to write frames into a ring buffer; an interrupt flashes briefly; NAPI polling retrieves more than a dozen packets at once, wrapping each in an sk_buff shell.
Voice-over: The first stop for a packet entering Linux is not the firewall, but the network card, driver, and soft interrupt.
Visual: The skb passes through PREROUTING, the routing junction (branching into INPUT and FORWARD), and POSTROUTING in sequence; DNAT and SNAT are marked at the junctions.
Voice-over: Five netfilter hooks plus one routing decision determine whether the packet is delivered to the local machine or forwarded, and whether its address needs to be rewritten.
Visual: The corresponding counters appear beside each stop: ethtool, softnet_stat, nft counter, nstat, and ss.
Voice-over: Each stop has its own counters. Once you know which stop the packet reached, you know which number to check.
Module 2 · Virtual Networking: bridge, veth, VLAN, and Network Namespaces
- Explain what network namespaces isolate (interfaces, addresses, routing tables, netfilter rules, sockets,
/proc/sys/net), and useip netns,ip -n, andnsenterto enter and inspect them. - Understand veth pairs (“the two ends of one network cable”) and the Linux bridge (a Layer 2 switch that learns MAC addresses, with an FDB table), and be able to read
bridge fdbandip neigh. - Be able to configure VLAN subinterfaces (
type vlan id N) and VLAN-aware bridges (vlan_filtering 1,bridge vlan). - Map this lesson’s topology to the Docker default bridge (docker0) and Kubernetes CNI, and find the veth corresponding to a given container on the host.
What: Four Building Blocks
| Building block | What it is | Real-world analogy | Creation command |
|---|---|---|---|
| Network namespace netns | An independent copy of a network stack: its own interfaces, addresses, routing table, neighbor table, netfilter rules, sockets, and net.* sysctls | An independent host | ip netns add red |
| veth pair | A pair of virtual Ethernet interfaces: a frame sent from one end is immediately received at the other; the two ends can be placed in different namespaces | A network cable | ip link add A type veth peer name B netns red |
| Linux bridge | A Layer 2 switch in the kernel: it learns source MAC addresses from each port and writes them to the FDB (forwarding database), forwards according to the destination MAC address, and floods frames when the destination is unknown; the bridge device itself can also be assigned an IP address, becoming the host’s interface on that subnet | A switch (plus one port connected to the host) | ip link add br-lab type bridge |
| VLAN | An 802.1Q tag (12-bit VID, 1–4094) divides one Layer 2 network into multiple broadcast domains | VLAN segmentation on a switch | ip link add link eth0 name eth0.100 type vlan id 100 |
Why: Container networking is a combination of these building blocks
- Docker default bridge network: the
docker0bridge on the host (default 172.17.0.1/16); each container has one netns, with one end of a veth pair calledeth0inside the container and the other end attached to docker0 asveth<random>; outbound access uses MASQUERADE, and port publishing uses DNAT (Module 3). See the networking section of the Docker course for details. - Kubernetes: each Pod has one netns (held by the pause/sandbox container), and the CNI plugin connects it to the network: the
bridgeplugin is almost identical to this lesson’s topology (the bridge is commonly calledcni0); Calico and others use “veth + routing” instead of a bridge; Cilium forwards traffic directly on the veth using eBPF. See the Kubernetes course for details. - Virtual machines: a KVM virtual machine’s tap device is likewise connected to a Linux bridge.
How: Ways to enter a namespace
| Method | Use case | Example |
|---|---|---|
ip netns exec NAME CMD | A named namespace (mounted at /run/netns/NAME); an independent /sys is also mounted for the namespace, and configuration files under /etc/netns/NAME/ (such as resolv.conf) are used | sudo ip netns exec red ss -ltn |
ip -n NAME ... | A shorthand for executing only an ip subcommand | ip -n red route |
nsenter -t PID -n CMD | Enter the network namespace of a process (such as a container’s main process); a container’s netns is usually not located under /run/netns | sudo nsenter -t $(docker inspect -f '{{.State.Pid}}' web) -n ip addr |
lsns -t net | List all network namespaces in the system and the processes holding them | sudo lsns -t net |
When: Bridging, routing, or macvlan?
| Option | Principle | Advantages | Costs |
|---|---|---|---|
| bridge + veth | This lesson’s topology | Simple and universal; provides Layer 2 connectivity between namespaces | Outbound access requires NAT or additional routing; passing through the bridge and netfilter incurs some overhead |
| Purely routed veth (no bridge) | Configure a /32 route on the host side of each veth | No broadcast domain, making policy configuration easier | Requires a routing protocol or controller to distribute routes |
| macvlan / ipvlan | Derive subinterfaces on the physical NIC and assign them addresses directly from the upstream subnet | Good performance; containers appear on the physical network as independent hosts | By default, the host cannot communicate with its own macvlan subinterfaces; the upstream switch may limit the number of MAC addresses |
lo interface in the DOWN state; you must connect it manually. ② “Both ends of a veth must be assigned an IP address” — The end connected to a bridge is a switch port and does not need an IP address. ③ “A bridge is a Layer 3 device” — A bridge performs Layer 2 forwarding; an IP address assigned to a bridge belongs to the host, and forwarding across subnets relies on the host's routing. ④ “Interfaces must be deleted before deleting a namespace” — When a namespace is deleted, the veth end inside it is destroyed, and the other end disappears accordingly.Figure 2-1: Correspondence Between This Lesson's Topology and Docker's Default Network
VLAN-aware bridge
Packet paths between two network namespaces and out to the network through NAT
Play after selecting a scenario: observe how ARP broadcasts are flooded by the bridge, how the FDB learns MAC addresses, how packets are routed and MASQUERADEd on the host, and how conntrack restores them on the return path. The table on the right displays real-time changes to the FDB and conntrack (sample data).
Core Commands and Parameters
| Command | Function | Description |
|---|---|---|
ip netns add|del|list | Manage named namespaces | Located at /run/netns/; disappears after a reboot |
ip -n red -br addr / ip -n red route | Execute ip subcommands within a namespace | Equivalent to ip netns exec red ip ... |
ip link add v-a type veth peer name eth0 netns red | Create a veth pair and move one end into a namespace | Interface names are limited to 15 characters |
ip link set v-a master br-lab up | Connect an interface to a bridge | nomaster removes it |
bridge link / bridge fdb show br br-lab | Bridge port status / MAC forwarding table | FDB entries with master br-lab are learned; permanent indicates local entries |
ip neigh | Neighbor (ARP) table | States REACHABLE / STALE / FAILED |
ip -d link show dev X | Display device-type details | Parameters for veth, bridge, and VLAN are shown here |
ethtool -S v-red-eth0 | veth statistics, including peer_ifindex | Used to find which namespace contains the peer |
bridge vlan show / bridge vlan add dev X vid N pvid untagged | Port VLAN table for a VLAN-aware bridge | First run ip link set br type bridge vlan_filtering 1 |
lsns -t net / nsenter -t PID -n | Find and enter the network namespace of any process | Commonly used for container troubleshooting |
bridge link show master br-lab bridge fdb show br br-lab | grep -v permanent ip neigh show dev br-lab sudo ip netns exec red ip neigh
5: v-red-eth0@if2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 master br-lab state forwarding priority 32 cost 2 7: v-blue-eth0@if2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 master br-lab state forwarding priority 32 cost 2 d6:a2:11:8b:7c:01 dev v-red-eth0 master br-lab 5e:1e:9a:21:3b:10 dev v-blue-eth0 master br-lab 10.200.0.10 lladdr d6:a2:11:8b:7c:01 REACHABLE 10.200.0.20 dev eth0 lladdr 5e:1e:9a:21:3b:10 REACHABLE 10.200.0.1 dev eth0 lladdr 0a:58:3c:1e:2f:44 STALE
Find the Host veth Corresponding to a Docker Container (When Docker Is Present)
PID=$(docker inspect -f '{{.State.Pid}}' <容器名>)
IDX=$(sudo nsenter -t "$PID" -n cat /sys/class/net/eth0/iflink) # 对端在宿主机上的 ifindex
ip -o link | awk -F': ' -v i="$IDX" '$1==i {print $2}'
iflink is the ifindex of the veth peer; on the host, the interface with the same ifindex is its “other end.”
Lab 2: Examine the Topology in Detail, Then Add VLAN Isolation (Approximately 7 Minutes)
sudo ip netns add scratch sudo ip -n scratch link sudo ip netns exec scratch ping -c1 127.0.0.1; sudo ip -n scratch link set lo up sudo ip netns exec scratch ping -c1 -W1 127.0.0.1 sudo ip netns exec scratch sysctl net.ipv4.ip_forward sudo ip netns del scratch
1: lo: <LOOPBACK> mtu 65536 qdisc noop state DOWN mode DEFAULT group default qlen 1000 ping: connect: Network is unreachable 1 packets transmitted, 1 received, 0% packet loss, time 0ms net.ipv4.ip_forward = 0
The new namespace contains only a DOWN lo; even loopback is unreachable. Its sysctl is also an independent copy (ip_forward is 0 in the new namespace and is unrelated to the host).
sudo ip -n red neigh flush all; sudo ip -n blue neigh flush all sudo bridge fdb show br br-lab | grep -v permanent # 可能还有旧条目(默认 300 秒老化) sudo ip netns exec blue tcpdump -i eth0 -nn -e -c 4 arp or icmp & sleep 1; sudo ip netns exec red ping -c1 10.200.0.20; wait bridge fdb show br br-lab | grep -v permanent
d6:a2:11:8b:7c:01 > ff:ff:ff:ff:ff:ff, ethertype ARP (0x0806), length 42: Request who-has 10.200.0.20 tell 10.200.0.10, length 28 5e:1e:9a:21:3b:10 > d6:a2:11:8b:7c:01, ethertype ARP (0x0806), length 42: Reply 10.200.0.20 is-at 5e:1e:9a:21:3b:10, length 28 d6:a2:11:8b:7c:01 > 5e:1e:9a:21:3b:10, ethertype IPv4 (0x0800), length 98: 10.200.0.10 > 10.200.0.20: ICMP echo request ... 5e:1e:9a:21:3b:10 > d6:a2:11:8b:7c:01, ethertype IPv4 (0x0800), length 98: 10.200.0.20 > 10.200.0.10: ICMP echo reply ... d6:a2:11:8b:7c:01 dev v-red-eth0 master br-lab 5e:1e:9a:21:3b:10 dev v-blue-eth0 master br-lab
sudo ip link set br-lab type bridge vlan_filtering 1 sudo bridge vlan del dev v-red-eth0 vid 1 sudo bridge vlan add dev v-red-eth0 vid 100 pvid untagged bridge vlan show sudo ip netns exec red ping -c1 -W1 10.200.0.20; echo "red→blue exit=$?" sudo ip netns exec red ping -c1 -W1 10.200.0.1; echo "red→gw exit=$?"
port vlan-id br-lab 1 PVID Egress Untagged v-red-eth0 100 PVID Egress Untagged v-blue-eth0 1 PVID Egress Untagged red→blue exit=1 red→gw exit=1
After entering the bridge, red's frames are tagged with VID 100, while blue and the bridge itself (the host interface) are both on VID 1, so red is isolated in its own broadcast domain. To allow VLAN 100 to access the network, add vid 100 to the bridge's self port and create a br-lab.100 subinterface as the gateway for that VLAN.
sudo bridge vlan add dev v-blue-eth0 vid 100 # tagged sudo ip -n blue link add link eth0 name eth0.100 type vlan id 100 sudo ip -n blue addr add 10.210.0.20/24 dev eth0.100; sudo ip -n blue link set eth0.100 up sudo ip -n red addr add 10.210.0.10/24 dev eth0 sudo ip netns exec red ping -c1 10.210.0.20 sudo ip -n blue -d link show eth0.100 | grep -o 'vlan protocol 802.1Q id 100'
sudo ip link set br-lab type bridge vlan_filtering 0 sudo ./topo.sh down && sudo ./topo.sh up # 最干净的恢复方式(在 ~/linuxlab/net8 下执行)
Case 1: Containers cannot access services on the host in a macvlan network
Problem: To allow containers to obtain office network addresses directly, the team switched to a macvlan network, but the host and these containers could no longer ping each other. Approach: This is known behavior of macvlan—traffic between the parent interface and its macvlan subinterfaces does not pass through the external switch and does not “loop back” within the kernel. Configuration: Create another macvlan subinterface (such as mac0) on the host and add a route for the container subnet; or switch to a bridge network with routing. Limitation: Port security on the upstream switch (the number of MAC addresses per port) may limit the number of macvlan containers.
Case 2: Network problems inside a Pod—how to capture packets on the node
Problem: A Pod occasionally times out when connecting, and its image does not include tcpdump. Approach: Use crictl inspect on the node to obtain the container PID, then use nsenter -t PID -n tcpdump -i eth0 to capture packets in the Pod's network namespace using the host's tcpdump binary; alternatively, use the iflink method from the previous page to find the host-side veth and capture packets there. Limitation: Node root privileges are required; on managed Kubernetes, you can use kubectl debug node/... to start a privileged debug Pod.
Case 3: ARP flapping with many containers on the same bridge
Problem: Hundreds of containers are running on one host, and “neighbor table overflow” occurs intermittently. Approach: dmesg shows neighbour: arp_cache: neighbor table overflow!; ip neigh | wc -l is close to net.ipv4.neigh.default.gc_thresh3 (1024 by default). Configuration: Increase gc_thresh1/2/3 according to the scale. Limitation: An excessively large neighbor table also increases memory usage and GC overhead; routing-based CNIs are more suitable for large-scale scenarios.
Common Errors and Solutions
Cannot open network namespace "red": No such file or directory
Cause: The namespace does not exist (due to a typo or because /run/netns was cleared after a reboot).
ip netns list; ls -l /run/netns/
Fix: Run sudo ./topo.sh up again. For persistence, use a systemd unit or manage it with netplan / systemd-networkd instead of manual commands.
RTNETLINK answers: Operation not permitted
Cause: CAP_NET_ADMIN is unavailable (sudo was omitted), or the operation is being performed in a restricted container or a non-privileged user namespace.
id -u; capsh --print 2>/dev/null | grep -i net_admin
Fix: Use sudo; in a container, --cap-add NET_ADMIN is required (use with caution).
Error: argument "v-green-eth0-long" is wrong: "name" not a valid ifname
Cause: Linux interface names are limited to 15 characters (IFNAMSIZ is 16, including the terminating 0).
Fix: Shorten the name (for example, v-grn0); Docker uses veth plus 7 random hexadecimal digits specifically to avoid exceeding the limit.
Symptom: red can ping the gateway 10.200.0.1 but cannot ping blue
Cause: Communication within the same subnet only passes through Layer 2 forwarding on the bridge. Common causes: blue's veth does not have master br-lab or is DOWN; vlan_filtering is enabled but the VLANs do not match; the host has loaded br_netfilter and the iptables / nft forward policy is DROP (common on Docker hosts).
bridge link show master br-lab bridge vlan show lsmod | grep br_netfilter; sysctl net.bridge.bridge-nf-call-iptables 2>/dev/null
Fix: Correct the port and VLAN; if using br_netfilter, allow traffic within the bridge or disable bridge-nf-call-iptables when it is not needed (do not disable it on Kubernetes nodes).
1. Create a namespace named green, connect it to br-lab using veth, assign it the address 10.200.0.30/24, and set the default gateway to 10.200.0.1.
sudo ip netns add green sudo ip link add v-green type veth peer name eth0 netns green sudo ip link set v-green master br-lab up sudo ip -n green addr add 10.200.0.30/24 dev eth0 sudo ip -n green link set lo up; sudo ip -n green link set eth0 up sudo ip -n green route add default via 10.200.0.1
2. List all network namespaces on the system and the processes that hold them, then check the listening ports in the network namespace of the process with PID 4242.
sudo lsns -t net sudo nsenter -t 4242 -n ss -ltnp
You need to provide Layer 2 isolation for the test environments of three teams on a Linux host. All three environments must be able to access the network through the same uplink, and the upstream switch provides only one trunk port. How would you design this?
Use a VLAN-aware bridge: configure the physical uplink as a trunk port (carrying tagged VID 10/20/30), and set each environment’s namespace or VM port to the corresponding VID as a pvid and untagged; if the gateway is on the upstream router, Linux only handles Layer 2; if the host acts as the gateway, create subinterfaces such as br0.10 on the bridge for each VID and configure gateway addresses, enable forwarding, and use nftables to restrict inter-VLAN access in the forward chain and perform MASQUERADE in postrouting. This is easier to maintain than “one bridge per VLAN + multiple eth0.N interfaces.”
Verified Educational Videos
Official Documentation
- ip-netns(8) · veth(4) · network_namespaces(7)
- bridge(8) · Ethernet Bridging(kernel.org)
- Docker: Bridge network driver · CNI bridge plugin
Video Storyboard (Approx. 90 Seconds)
This course material cannot generate video/MP3 directly; a storyboard and narration script are provided.
Visual: Two transparent little rooms, red and blue, “grow” inside a host machine, each with an empty network stack.
Narration: A network namespace is like putting several little machines inside one computer. They cannot see one another.
Visual: One veth cable runs from red to the bridge in the middle, and another runs from blue; ARP broadcasts flood across the bridge as entries fill the FDB table one by one.
Narration: A veth is a cable, and a bridge is a switch. The first communication uses a broadcast to find the other side; afterward, the switch remembers which port each device is on.
Visual: Label transformation: br-lab becomes docker0, and red becomes a container icon; a MASQUERADE stamp is applied to the packet at the exit.
Voice-over: This is the whole secret behind Docker’s default network: namespaces, veth, a bridge, plus one NAT rule.
Module 3 · Advanced Routing: Policy Routing, Multiple Network Interfaces, and NAT
- Understand the three default
ip rulerules (local / main / default), add rules that select tables by source address, incoming interface, or fwmark, and write routes in custom routing tables. - Reproduce and fix the “return traffic takes the wrong interface” problem on multi-homed hosts, and understand the role of rp_filter (strict / loose) and cloud-platform anti-spoofing checks.
- Use nftables to write SNAT, MASQUERADE, and DNAT (port forwarding) rules; understand why NAT is evaluated only for the first packet of a connection, and how to use
conntrackto view and delete mappings. - Use netplan to persist policy routing.
What: Routing decisions take two steps
- Policy rules (RPDB):
ip rulematches rules one by one in ascending priority order (selection criteria includefromsource prefix,todestination prefix,iif/oif,fwmark,ipproto,dport,uidrange, and so on). After a match, it looks up the routing table specified by the rule; if that table has no matching route, it continues to the next rule. - Routing table lookup: Within the table, the longest-prefix match is performed to obtain the outgoing interface, next hop (via), and preferred source address (src).
0: from all lookup local # 本机地址与广播(内核自动维护) 32766: from all lookup main # 平时 ip route 看到的就是 main 表 32767: from all lookup default # 通常为空
The mapping between table names and numbers is defined in /etc/iproute2/rt_tables (newer versions of iproute2 also read /usr/share/iproute2/rt_tables and rt_tables.d/); using a number directly (such as table 201) also works.
Why: The return-traffic problem with multiple network interfaces
A host has two network interfaces: eth0 (10.200.0.30, with the default gateway on this interface) and eth1 (10.201.0.30). When a remote client accesses the address on eth1, the request arrives through eth1, but the destination address of the reply is in the remote network, and the main table has only one default route pointing to eth0—the reply is sent through eth0, yet its source address is 10.201.0.30. As a result, the upstream router / firewall sees a packet whose “source address does not belong on this interface” and drops it (anti-spoofing and stateful firewalls see only half of the connection), causing the client to time out. The same applies in the cloud: after Azure and AWS add a second network interface to a VM, both require policy routing to be configured within the system (see Lesson 3 and Lesson 4).
Fix: Create a routing table for each network interface, add the directly connected route and default gateway for that interface, and then add the rule from <that interface's address> lookup <that table>. The source address of the reply is the address that was accessed, so it automatically uses the corresponding table.
rp_filter: Reverse-path filtering
| Value | Meaning | Effect |
|---|---|---|
| 0 | No checking | Accept any source address |
| 1 (strict) | The best route to the source address must go out through the interface on which the packet was received | Packets with asymmetric routes are dropped and counted in IPReversePathFilter |
| 2 (loose) | The source address only needs to be reachable through any interface | Only clearly spoofed source addresses are blocked |
The effective value is the larger value of conf.all.rp_filter and conf.<interface>.rp_filter. Ubuntu sets it to 2 by default through /etc/sysctl.d/10-network-security.conf (loose; actual settings prevail). nftables can also use fib saddr . iif oif missing drop to implement strict reverse path checking.
How:NAT and conntrack
| Type | Hook | Rewrite | Typical use | nftables syntax |
|---|---|---|---|---|
| SNAT | POSTROUTING | Source address (and port) | Fixed public IP on the outbound interface | oifname "eth0" snat to 203.0.113.10 |
| MASQUERADE | POSTROUTING | Source address = current address of the output interface | Dynamic outbound address (DHCP, dial-up), container egress | oifname "eth0" masquerade |
| DNAT | PREROUTING (traffic generated by the local machine uses OUTPUT) | Destination address (and port) | Port forwarding, publishing services | tcp dport 8080 dnat to 10.200.0.20:80 |
| REDIRECT | PREROUTING / OUTPUT | Destination = local machine | Transparent proxy | tcp dport 80 redirect to :3128 |
- conntrack is NAT’s ledger: each connection has one record containing two sets of four-tuples: the “original direction” and the “reply direction.” NAT rules are evaluated only for the first packet (NEW) of a connection, and the result is written to conntrack; subsequent packets (including reply packets) are rewritten directly according to the record, without checking the nat chain again.
- Therefore: modifying NAT rules does not take effect for established connections; you need to use
conntrack -Dto delete the old records (or wait for them to time out). - NAT depends on
ip_forward=1(in forwarding scenarios) and the forward chain allowing the traffic; return traffic can be allowed withct state established,related accept. - MASQUERADE clears related conntrack entries when the interface address changes or the interface goes down; for a fixed IP, SNAT is more explicit.
When:Which solution to choose
| Requirement | Solution |
|---|---|
| Separate return paths for multiple network interfaces | One table per network interface + from address rule |
| Some applications use a VPN / a specific outbound interface | Mark with nftables using meta mark, or use ip rule uidrange + a separate routing table |
| Internal network access to the Internet | SNAT / MASQUERADE |
| External access to internal services | DNAT (or a reverse proxy, which makes TLS and logging easier) |
Figure 3-1: Multiple-network-interface return-path issue and policy-routing fix
Figure 3-2: DNAT port forwarding and the two directions of conntrack
Routing Decision Simulator: Rules → Tables → Routes
Select a packet and click “Find.” The simulator compares ip rule entries one by one in priority order. After a match, it performs longest-prefix matching in the corresponding routing table; if there is no match in the table, it continues to the next rule. You can switch “Whether the table 201 rule has been added” to compare the return path before and after the fix.
Core Commands and Parameters
| Command | Function | Description |
|---|---|---|
ip rule [list] | View policy rules | ip -6 rule is a separate rule set for IPv6 |
ip rule add from 10.201.0.30 table 201 priority 1000 | Select a table by source address | You can also use iif, fwmark 0x1, uidrange 1001-1001, ipproto tcp dport 443 |
ip route add default via 10.201.0.1 dev eth1 table 201 | Add a route to a custom table | Use ip route show table 201 to view it; use table all to view all |
ip route get 10.202.0.50 from 10.201.0.30 | Verify the decision | Add mark 0x1 and iif to simulate more conditions |
sysctl net.ipv4.conf.all.rp_filter | Reverse path filtering | Each interface has its own value |
nft add rule ip lab8 prerouting tcp dport 8080 dnat to 10.200.0.20:80 | Port forwarding | The chain requires type nat hook prerouting priority dstnat |
sudo conntrack -L [-p tcp --dport 8080] | List connection tracking entries | -E real-time events; -D delete; -C count; -S statistics |
Persistent policy routing with netplan (configuration for a real host)
# /etc/netplan/60-eth1.yaml
network:
version: 2
ethernets:
eth1:
addresses: [10.201.0.30/24]
routes:
- to: 10.201.0.0/24
scope: link
table: 201
- to: default
via: 10.201.0.1
table: 201
routing-policy:
- from: 10.201.0.30
table: 201
priority: 1000
sudo chmod 600 /etc/netplan/60-eth1.yaml sudo netplan try # 120 秒内不确认会自动回滚,远程操作必备 ip rule; ip route show table 201
Complete nftables NAT example
table ip lab8 {
chain prerouting {
type nat hook prerouting priority dstnat; policy accept;
iifname "v-client" tcp dport 8080 counter dnat to 10.200.0.20:80
}
chain postrouting {
type nat hook postrouting priority srcnat; policy accept;
ip saddr 10.200.0.0/16 oifname "ens3" counter masquerade
# 固定公网地址时:ip saddr 10.200.0.0/16 oifname "ens3" snat to 203.0.113.10
}
}
Lab 3: Reproduce “return traffic takes the wrong interface,” fix it with policy routing, then set up port forwarding (about 8 minutes)
~/linuxlab/net8):
sudo ./topo.sh multi
sudo nft add chain ip lab8 antispoof '{ type filter hook prerouting priority -150; policy accept; }'
sudo nft add rule ip lab8 antispoof iifname "br-lab" ip saddr != 10.200.0.0/24 counter drop
sudo ./topo.sh status
This rule simulates “the upstream device accepts source addresses only from this subnet”—this is the effect of anti-spoofing on cloud platforms and uRPF on enterprise firewalls.
sudo ip netns exec client ping -c2 -W1 10.200.0.30 # 访问 eth0 地址 sudo ip netns exec client ping -c2 -W1 10.201.0.30 # 访问 eth1 地址 sudo ip -n green route get 10.202.0.50 from 10.201.0.30 sudo nft list chain ip lab8 antispoof | grep counter
2 packets transmitted, 2 received, 0% packet loss
2 packets transmitted, 0 received, 100% packet loss
10.202.0.50 from 10.201.0.30 via 10.200.0.1 dev eth0 uid 0
iifname "br-lab" ip saddr != 10.200.0.0/24 counter packets 2 bytes 168 drop
route get makes the problem immediately clear: the source address is from eth1, but the outgoing interface is eth0. The counter proves that the reply packets are being dropped upstream.
sudo ip -n green route add 10.201.0.0/24 dev eth1 src 10.201.0.30 table 201 sudo ip -n green route add default via 10.201.0.1 dev eth1 table 201 sudo ip -n green rule add from 10.201.0.30 table 201 priority 1000 sudo ip -n green rule sudo ip -n green route get 10.202.0.50 from 10.201.0.30 sudo ip netns exec client ping -c2 -W1 10.201.0.30
0: from all lookup local 1000: from 10.201.0.30 lookup 201 32766: from all lookup main 32767: from all lookup default 10.202.0.50 from 10.201.0.30 via 10.201.0.1 dev eth1 table 201 uid 0 2 packets transmitted, 2 received, 0% packet loss
sudo ip netns exec blue python3 -m http.server 80 --bind 10.200.0.20 >/dev/null 2>&1 &
sudo nft add chain ip lab8 prerouting '{ type nat hook prerouting priority dstnat; policy accept; }'
sudo nft add rule ip lab8 prerouting iifname "v-client" tcp dport 8080 counter dnat to 10.200.0.20:80
sudo ip netns exec client curl -sS -o /dev/null -w '%{http_code}\n' http://10.202.0.1:8080/
sudo conntrack -L -p tcp --orig-port-dst 8080 2>/dev/null
200 tcp 6 118 TIME_WAIT src=10.202.0.50 dst=10.202.0.1 sport=40112 dport=8080 src=10.200.0.20 dst=10.202.0.50 sport=80 dport=40112 [ASSURED] mark=0 use=1 conntrack v1.4.9 (conntrack-tools): 1 flow entries have been shown.
The second address pair is the “expected reply direction”: blue replies to 10.202.0.50, and the host then changes the source back to 10.202.0.1:8080 according to this entry.
sudo ip netns exec client bash -c 'exec 3<>/dev/tcp/10.202.0.1/8080; sleep 30' & sleep 1 sudo nft flush chain ip lab8 prerouting # 删除 DNAT 规则 sudo conntrack -L -p tcp --orig-port-dst 8080 2>/dev/null | grep ESTABLISHED # 旧连接映射仍在 sudo conntrack -D -p tcp --orig-port-dst 8080 # 强制删除映射
sudo ip netns pids blue | xargs -r sudo kill sudo ./topo.sh down && sudo ./topo.sh up
Case 1: A cloud VM gets a second network interface, and services on the new interface cannot be reached
Problem: A second network interface (on another subnet) was added to the VM for management traffic. Accessing that address from the management network times out. Approach: ip route get <management client IP> from <second interface IP> shows traffic going via eth0; packet capture confirms that requests arrive via eth1 and replies leave via eth0. Configuration: Configure routing-policy and a table for eth1 in netplan. Limitation: Some cloud images’ cloud-init or network agents automatically generate policy routes for attached interfaces (behavior varies by image and platform; refer to the platform documentation). Check existing rules before configuring manually to avoid duplicates.
Case 2: After changing the port-forwarding destination, some users still access the old backend
Issue: After changing the DNAT target from the old server to the new server, long-lived clients (WebSocket) remain connected to the old backend. Action: Old mappings still exist in conntrack -L. Configuration: Delete by destination address: conntrack -D --reply-src <旧后端>. Lesson: The NAT change plan must include conntrack handling, or use a reverse proxy / load balancer that supports graceful switching.
Case 3: All internal hosts appear to use the same source IP for outbound traffic and are rate-limited by the peer
Issue: Hundreds of internal hosts access the Internet through a Linux gateway using MASQUERADE. The peer API rate-limits by source IP, resulting in frequent 429 responses. In addition, conntrack -S on the gateway shows that insert_failed is increasing. Action: Concurrent connections to the same destination IP:port are limited by the number of source ports (approximately 28,000 ephemeral ports × the number of egress IPs). Configuration: SNAT to multiple egress addresses (snat to 203.0.113.10-203.0.113.13), or route different services through different egress paths; negotiate a whitelist with the peer. Limitation: The number and cost of egress IPs.
Common Errors and Solutions
Error: Nexthop has invalid gateway.
Cause: When adding a via gateway in a custom table, the kernel cannot find a directly connected route to the gateway (the gateway is not in the subnet of any interface, or the interface is not UP).
ip -br addr; ip route show table all | grep 10.201.0
Fix: First verify the interface address and status; if necessary, add onlink (explicitly telling the kernel that the gateway is on that link), or first add a directly connected subnet route to the table.
Symptom: After a policy routing rule has been added, ip route get still uses the main table
Cause: The rule priority is greater than 32766 (placing it after main); from specifies a subnet, but the packet's source address is not within it; or the target table is empty, causing matching to continue with subsequent rules after a “miss.”
ip rule ip route show table 201 ip route get <目的> from <源>
Fix: Set the rule priority to less than 32766; ensure that the table contains a route.
Error: Could not process rule: No such file or directory (when adding a dnat rule)
Cause: The target chain does not exist, or the chain is not of type nat (writing dnat in a type filter chain will produce an error such as “Operation not supported”; the exact wording depends on the actual situation).
sudo nft list table ip lab8
Fix: Create a chain with type nat hook prerouting priority dstnat before adding the rule.
Symptom: Local curl 127.0.0.1:8080 does not pass through port forwarding
Cause: Packets sent by the local host do not pass through PREROUTING, but through OUTPUT; moreover, DNAT of packets destined for 127.0.0.0/8 to an external address also requires net.ipv4.conf.all.route_localnet=1.
Fix: Add the same dnat rule in a type nat hook output chain, and test using the host's non-loopback address; or simply use a reverse proxy (nginx).
1. Route all traffic for user ID 1001 through routing table 300 (for example, through a VPN egress), and verify.
sudo ip rule add uidrange 1001-1001 table 300 priority 900 sudo ip route add default via 10.8.0.1 dev wg0 table 300 ip route get 1.1.1.1 uid 1001
2. View all connections that have undergone DNAT (entries whose reply-direction source address differs from the original destination address).
sudo conntrack -L --dst-nat
A Linux server is simultaneously connected to the production network (eth0, the default gateway) and the backup network (eth1, 10.50.0.0/16, gateway 10.50.0.1). The backup server 10.60.1.5 is located on another subnet and can only be reached through the backup network gateway. Design the routing and explain why “adding a static route to 10.60.0.0/16” alone is not sufficient, as well as the applicable scenarios for each approach.
If the server only actively accesses the backup server, adding the static route 10.60.0.0/16 via 10.50.0.1 dev eth1 is sufficient—this is the simplest solution. However, if the backup server or hosts on other subnets need to actively access the address on eth1, the reply packets need to return through eth1, and there may be many remote subnets that cannot be enumerated one by one. In this case, a table should be created for eth1 (a directly connected route + default via 10.50.0.1), along with a from <eth1 address> table N rule. Both approaches can coexist: the static route handles path selection for active access, while policy routing handles the return path for inbound access.
Verified Educational Video
No verified video was found specifically on policy routing (ip rule / multiple routing tables), conntrack, and nftables NAT. Refer to the official documentation and storyboard below.
Official Documentation
- ip-rule(8) · ip-route(8)
- Performing NAT(nftables wiki) · nft(8)
- conntrack(8) · ip-sysctl:rp_filter、ip_forward
- Netplan YAML: routes and routing-policy
Video Storyboard Script (approximately 90 seconds)
This courseware cannot directly generate video/MP3 files; a storyboard and narration script are provided.
Visual: A dual-NIC server; a request enters through the door on the right, but the reply exits through the door on the left and is stopped at the entrance by a security guard (anti-spoofing).
Narration: The most common pitfall with multiple NICs: routing only looks at the destination and does not care which door the request entered through.
Visual: The ip rule list looks like a row of signposts. The reply, carrying its own source address, finds the signpost “from 10.201.0.30 → table 201” and enters through the door on the right.
Narration: Policy routing lets the source address determine which table to look up. One table per NIC makes the return path symmetric naturally.
Visual: DNAT rewrites the destination address at the entrance, and conntrack records a line in its ledger; when the reply passes through, it is rewritten back according to the ledger.
Narration: NAT makes its decision only on the first packet; after that, everything follows conntrack. When changing the rules, do not forget to clear the ledger.
Module 4 · TCP Tuning and Connection Issues: Queues, TIME_WAIT, and Keepalive
- Draw the three-way handshake and the server-side SYN queue (half-open connections) and accept queue (fully established connections); state what
backlog,net.core.somaxconn,tcp_max_syn_backlog, andtcp_syncookieseach control; and usess -ltnandnstatto prove overflow. - State which side enters TIME_WAIT, why it exists, how long it lasts, and the actual conditions for “port exhaustion” and the correct countermeasures (prioritize connection reuse, with
tcp_tw_reuseas a secondary option). - Understand the three TCP keepalive parameters and their relationship to cloud load balancer / NAT idle timeouts.
- Read the rtt, cwnd, retrans, delivery_rate, and other fields in
ss -ti; understand the differences between CUBIC and BBR and how to switch between them safely.
What: The Two Queues of a Listening Socket
- The client sends a SYN. The server creates a lightweight “request socket” for it, places it in the SYN queue, and sends back a SYN-ACK.
- The client sends back an ACK, and the handshake is complete. The server moves the connection from the SYN queue to the accept queue.
- The application does not take the connection until it calls
accept(). If the application is too busy (all workers are occupied or the event loop is blocked), the accept queue will build up.
| Parameter / Counter | Meaning | Default (Linux 7.0; verify against the actual system) |
|---|---|---|
listen(fd, backlog) | Length of the accept queue requested by the application | Determined by the application (gunicorn --backlog defaults to 2048; nginx listen ... backlog= defaults to 511 on Linux) |
net.core.somaxconn | Accept queue limit: actual value = min(backlog, somaxconn) | 4096 (since kernel 5.4) |
net.ipv4.tcp_max_syn_backlog | SYN queue-related limit | Calculated based on memory; commonly 128–4096 or higher |
net.ipv4.tcp_syncookies | Use SYN cookies when the SYN queue is full, without occupying queue space | 1 (enabled only when the queue is full) |
TcpExtListenOverflows / TcpExtListenDrops | Drops caused by a full accept queue / drops across all listening sockets | Should be 0 or very low |
What happens when the accept queue is full: New SYNs are dropped; for connections that have already received a SYN-ACK, the client's final ACK is dropped (when tcp_abort_on_overflow=0), so the client believes the connection is established while the server subsequently retransmits the SYN-ACK. The user sees an occasional 1-second or 3-second connection stall (the backoff intervals for SYN retransmissions), rather than an error.
TIME_WAIT and Port Exhaustion
- Whichever side closes first enters TIME_WAIT (the active closer). In Linux, it lasts exactly 60 seconds (
TCP_TIMEWAIT_LEN, which cannot be modified through sysctl;tcp_fin_timeoutcontrols FIN_WAIT_2). - Purpose: to ensure that the final ACK can still be retransmitted if it is lost, and to prevent delayed packets from an old connection from entering a new connection using the same four-tuple.
- Actual condition for port exhaustion: Connections from a client to the same destination IP:port require different local ports; the local port range is
net.ipv4.ip_local_port_range, defaulting to32768 60999(approximately 28,000 ports), and four-tuples in TIME_WAIT cannot be reused temporarily. High-concurrency short-lived connections to the same backend (for example, an HTTP client without connection pooling or connections through the same NAT egress) can exhaust the ports and produceCannot assign requested address(EADDRNOTAVAIL). - Order of countermeasures: ① Reuse connections (HTTP keep-alive, connection pooling); ② have the server perform the active close; ③ add destination addresses / ports or egress IP addresses; ④ expand
ip_local_port_range; ⑤net.ipv4.tcp_tw_reuse=1(affects only outbound-initiated connections and depends on TCP timestamps; the default value 2 means it is enabled only for loopback).tcp_tw_recyclewas removed in kernel 4.12; do not look for it.
keepalive
TCP keepalive is disabled by default; the application needs to set SO_KEEPALIVE. Once enabled, probing starts after tcp_keepalive_time seconds of idle time (7200 seconds by default), then occurs once every tcp_keepalive_intvl seconds (75 seconds); the connection is disconnected after tcp_keepalive_probes (9) consecutive probes receive no response. Two hours is far longer than the idle timeouts of cloud load balancers / NAT gateways (for example, 4 minutes by default for Azure Load Balancer and 350 seconds for AWS NLB; refer to the platform documentation), so intermediate devices may silently discard the idle connection mapping, and the next send is when the dead connection is discovered (RST or timeout). Long-lived connection applications should set options such as TCP_KEEPIDLE at the socket level (or use application-layer heartbeats), with an interval shorter than the shortest idle timeout along the path.
Congestion Control and BBR
| CUBIC (Linux default) | BBR | |
|---|---|---|
| Signal | Packet loss (reduce the window after packet loss) | Measure bottleneck bandwidth and minimum RTT, and model the sending rate |
| Suitable for | General-purpose use; fair with other flows | High-bandwidth, long-distance links with random packet loss (intercontinental, wireless) |
| Note | Deep buffers cause queuing latency (bufferbloat) | Fairness is disputed when running alongside CUBIC flows; tcp_bbr in mainline kernels is BBR v1 (whether v3 has been merged depends on the actual kernel); since kernel 4.13, fq qdisc is no longer strictly required, but pairing it with fq is still recommended |
Congestion control affects only the sender: to accelerate downloads, switch it on the server. net.ipv4.tcp_congestion_control takes effect per network namespace, and applications can also make an individual selection using the TCP_CONGESTION socket option.
When: Decision Flow
- Connections occasionally stall for 1 / 3 seconds → check whether
nstat -az TcpExtListenOverflowsis increasing and whether Recv-Q inss -ltnis close to Send-Q → scale out application workers first, then adjust backlog / somaxconn. Cannot assign requested address→ usess -sto check the number of TIME-WAIT sockets, andss -tan state time-wait '( dport = :<后端端口> )' | wc -l→ connection pooling.- The first request fails after a long-lived connection has been idle → intermediate-device idle timeout → keepalive / heartbeat.
- Low throughput and high RTT → use
ss -tito check cwnd, rwnd_limited, sndbuf_limited, and retrans, then consider buffer settings (tcp_rmem/tcp_wmemautotuning) and BBR.
Figure 4-1: Handshake, Two Queues, and Overflow Points
Figure 4-2: The Parts of the TCP State Machine Most Relevant to Operations
Listening Queue Simulator
Adjust backlog and somaxconn, then send a burst of connections and have the application accept them. Observe changes in the SYN queue, accept queue, and ListenOverflows counter, as well as what the client observes. The values use a simplified teaching model (the real kernel determines overflow only when the queue length is “greater than” the limit, so Recv-Q may display the limit + 1).
Core Commands and Parameters
| Command | Function | Description |
|---|---|---|
ss -ltn 'sport = :5000' | Current length and limit of the listen queue | Recv-Q / Send-Q |
ss -s | Summary by state (including timewait) | Quickly determine the order of magnitude |
ss -tan state time-wait | wc -l | Number of TIME_WAIT connections | Can add the filter '( dport = :6379 )' |
ss -tni dst 10.200.0.20 | TCP information from the kernel for connections | cubic/bbr、rtt、cwnd、retrans、delivery_rate、*_limited |
ss -tmi | Socket memory (skmem) | r receive queue, rb receive buffer limit, d drops |
nstat -az TcpExtListenOverflows TcpExtListenDrops TcpExtTCPTimeWaitOverflow | Queue and TIME_WAIT counters | Display increments without -a |
sysctl net.core.somaxconn net.ipv4.tcp_max_syn_backlog net.ipv4.ip_local_port_range net.ipv4.tcp_tw_reuse | View key parameters | Persistently write to /etc/sysctl.d/90-tcp.conf |
sysctl net.ipv4.tcp_available_congestion_control | Loaded congestion control algorithms | bbr appears after modprobe tcp_bbr |
sysctl net.core.somaxconn net.ipv4.tcp_max_syn_backlog net.ipv4.tcp_syncookies \ net.ipv4.ip_local_port_range net.ipv4.tcp_tw_reuse net.ipv4.tcp_fin_timeout \ net.ipv4.tcp_keepalive_time net.ipv4.tcp_keepalive_intvl net.ipv4.tcp_keepalive_probes \ net.ipv4.tcp_congestion_control net.core.default_qdisc ss -ltn 'sport = :5000'
net.core.somaxconn = 4096 net.ipv4.tcp_max_syn_backlog = 512 net.ipv4.tcp_syncookies = 1 net.ipv4.ip_local_port_range = 32768 60999 net.ipv4.tcp_tw_reuse = 2 net.ipv4.tcp_fin_timeout = 60 net.ipv4.tcp_keepalive_time = 7200 net.ipv4.tcp_keepalive_intvl = 75 net.ipv4.tcp_keepalive_probes = 9 net.ipv4.tcp_congestion_control = cubic net.core.default_qdisc = fq_codel State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 2048 0.0.0.0:5000 0.0.0.0:*
Understanding ss -ti
ESTAB 0 0 10.200.0.10:52144 10.200.0.20:8000 cubic wscale:7,7 rto:204 rtt:0.061/0.019 ato:40 mss:1448 pmtu:1500 rcvmss:536 advmss:1448 cwnd:10 bytes_sent:154 bytes_acked:155 bytes_received:2215 segs_out:6 segs_in:5 send 1.9Gbps lastsnd:12 lastrcv:12 lastack:12 pacing_rate 3.8Gbps delivery_rate 268Mbps app_limited rcv_space:14480 rcv_ssthresh:64088 minrtt:0.045 retrans:0/0
| Field | Meaning |
|---|---|
rtt:average/variance, minrtt | Smoothed RTT (milliseconds) and the minimum RTT observed |
rto | Current retransmission timeout (milliseconds), approximately 200 minimum |
cwnd、ssthresh | Congestion window (in MSS units) and slow-start threshold |
retrans:current/total | Number of retransmissions; continuous growth indicates packet loss |
app_limited / rwnd_limited / sndbuf_limited | Sending is limited by the application / the peer's receive window / the local send buffer |
Experiment 4: Accept Queue Overflow, TIME_WAIT Port Exhaustion, and BBR (approximately 7 minutes)
sudo ip netns exec blue python3 -c '
import socket, time
s = socket.socket(); s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("10.200.0.20", 9000)); s.listen(4); time.sleep(300)' &
sleep 1
for i in $(seq 12); do sudo ip netns exec red timeout 20 bash -c 'exec 3<>/dev/tcp/10.200.0.20/9000; sleep 15' 2>/dev/null & done
sleep 3
sudo ip netns exec blue ss -ltn 'sport = :9000'
sudo ip netns exec blue nstat -az TcpExtListenOverflows TcpExtListenDrops
sudo ip netns exec red ss -tan '( dport = :9000 )' | awk 'NR>1{print $1}' | sort | uniq -c
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 5 4 10.200.0.20:9000 0.0.0.0:*
TcpExtListenOverflows 14 0.0
TcpExtListenDrops 14 0.0
5 ESTAB
7 SYN-SENT
Recv-Q 5 > Send-Q 4: the queue is full (the criterion is “greater than” the limit, so it can hold 1 additional item). The other 7 clients remain in SYN-SENT, and the kernel retransmits SYNs at intervals of 1s, 2s, 4s, … The counters are tracked separately in the blue namespace.
sudo ip netns pids blue | xargs -r sudo kill
sudo ip netns exec blue python3 -m http.server 8000 --bind 10.200.0.20 --protocol HTTP/1.1 >/dev/null 2>&1 &
sudo ip netns exec red sysctl -w net.ipv4.ip_local_port_range="40000 40009"
sudo ip netns exec red sysctl net.ipv4.tcp_tw_reuse
for i in $(seq 12); do sudo ip netns exec red curl -sS -o /dev/null -w "%{http_code} " http://10.200.0.20:8000/; done; echo
sudo ip netns exec red ss -tan state time-wait | tail -n +2 | wc -l
net.ipv4.tcp_tw_reuse = 2 200 200 200 200 200 200 200 200 200 200 curl: (7) Failed to connect to 10.200.0.20 port 8000 after 0 ms: Could not connect to server 000 curl: (7) Failed to connect to 10.200.0.20 port 8000 after 0 ms: Could not connect to server 000 10
The HTTP/1.1 server keeps the connection open, and curl actively closes it when it exits—TIME_WAIT is placed on the client, red. All 10 ports are in TIME_WAIT, and the 11th connect() receives EADDRNOTAVAIL (strace -e connect shows “Cannot assign requested address”). The --protocol option requires Python 3.11+.
sudo ip netns exec red sysctl -w net.ipv4.tcp_tw_reuse=1
for i in $(seq 12); do sudo ip netns exec red curl -sS -o /dev/null -w "%{http_code} " http://10.200.0.20:8000/; done; echo
200 200 200 200 200 200 200 200 200 200 200 200
TIME_WAIT entries are safely reused under timestamp protection (reuse requires at least 1 second to have elapsed since the previous connection). In real systems, connection reuse remains the first choice: for example, myapp should access Redis through a connection pool rather than creating a new connection for each request.
sudo modprobe tcp_bbr sysctl net.ipv4.tcp_available_congestion_control sudo ip netns exec blue sysctl -w net.ipv4.tcp_congestion_control=bbr head -c 50M /dev/zero > /tmp/blob && sudo mv /tmp/blob /root/blob # 准备一个测试文件 sudo ip netns exec blue bash -c 'cd /root && python3 -m http.server 8001 --bind 10.200.0.20' >/dev/null 2>&1 & sleep 1; sudo ip netns exec red curl -s -o /dev/null http://10.200.0.20:8001/blob & sleep 0.3; sudo ip netns exec blue ss -tni '( sport = :8001 )' | grep -o -E 'bbr|cubic|delivery_rate [^ ]+' | head -3
net.ipv4.tcp_available_congestion_control = reno cubic bbr bbr delivery_rate 6.2Gbps
There is no real bottleneck on the veth, so the difference between CUBIC and BBR is not obvious; you can use tc qdisc add dev v-blue-eth0 root netem delay 50ms loss 1% to simulate a long-distance lossy link for comparison (netem was introduced in Lesson 7, M5). Before switching in production, evaluate it with real traffic in a canary environment.
sudo ip netns pids blue | xargs -r sudo kill; sudo ip netns pids red | xargs -r sudo kill sudo rm -f /root/blob cd ~/linuxlab/net8 && sudo ./topo.sh down && sudo ./topo.sh up # 命名空间内的 sysctl 随之复位
Case 1: 1-second and 3-second “steps” in P99 after a release
Problem: The new version reduced the number of gunicorn workers from 8 to 4, and discrete P99 spikes of 1.0s and 3.0s appeared during peak hours. Approach: nstat -az TcpExtListenOverflows increased by hundreds every minute; the Recv-Q in ss -ltn was often at its limit. The discrete whole-second delays are exactly the SYN retransmission backoff. Configuration: Restore the number of workers and assess capacity; use backlog only as a buffer. Lesson: Queue overflows do not appear in application logs, so collect the ListenOverflows metric (included by default in node_exporter’s netstat collector; see the Prometheus course).
Case 2: Batch job reports Cannot assign requested address
Problem: A data synchronization job initiates thousands of short-lived connections per second to the same API gateway, and starts failing heavily after running for more than ten minutes. Approach: ss -tan state time-wait '( dport = :443 )' | wc -l returned about 28,000, exactly the size of the port range. Configuration: Switch to an HTTP client with connection pooling (requests.Session / HTTP keep-alive); the failures disappeared and TIME_WAIT fell to dozens. Limitation: When egressing through NAT, the NAT gateway’s own ports can also be exhausted (see Module 3, Case 3).
Case 3: Database connection “drops after being idle for a while”
Problem: An application accesses a database through a cloud load balancer. After being idle overnight, the first query returns Connection reset by peer. Approach: The load balancer’s idle timeout is 4 minutes, while the system keepalive is 7200 seconds; the connection mapping has long since been deleted. Configuration: Enable keepalive in the database driver and set keepalives_idle=60 (or have the connection pool periodically validate connections), or increase the load balancer’s idle timeout. Limitation: Changing the global tcp_keepalive_time only affects sockets with SO_KEEPALIVE enabled.
Common Errors and Solutions
TCP: request_sock_TCP: Possible SYN flooding on port 0.0.0.0:5000. Sending cookies.
Cause: The SYN queue is full, so the kernel starts using SYN cookies. This may be a real attack, or the full accept queue caused by slow accept processing may also lead to a buildup of half-open connections.
ss -ltn 'sport = :5000'; nstat -az TcpExtListenOverflows TcpExtSyncookiesSent ss -tan state syn-recv | wc -l
Fix: Distinguish an attack (many different sources, extremely high SYN-RECV counts) from insufficient capacity (Recv-Q at its limit); for the latter, scale up the application and, if necessary, increase backlog / somaxconn. See Lesson 7, M5.
connect: Cannot assign requested address
Cause: EADDRNOTAVAIL: Local port exhaustion (all four-tuples to the same destination are occupied or in TIME_WAIT), or a source address that does not exist on the local machine was bound.
ss -s; ss -tan state time-wait | awk '{print $4}' | sort | uniq -c | sort -nr | head
sysctl net.ipv4.ip_local_port_range net.ipv4.tcp_tw_reuse
Fix: Reuse connections; expand the port range; if necessary, set tcp_tw_reuse=1; check whether the application bound to an incorrect source IP.
Symptom: Thousands of CLOSE_WAIT connections on the server that never go away
Cause: The peer has closed the connection, but the local application has not called close()—a socket / file descriptor leak that may eventually trigger Too many open files.
ss -tanp state close-wait | awk '{print $NF}' | sort | uniq -c | sort -nr | head
ls /proc/<PID>/fd | wc -l; grep 'open files' /proc/<PID>/limits
Fix: Fix the application code (ensure connections are closed even on exception paths, and set timeouts for HTTP clients); restarting only provides temporary relief.
sysctl: setting key "net.ipv4.tcp_congestion_control": No such file or directory
Cause: An algorithm name that has not been loaded was written (for example, if the bbr module is not loaded, the kernel returns ENOENT; the wording of the sysctl message depends on the actual case).
sysctl net.ipv4.tcp_available_congestion_control sudo modprobe tcp_bbr; echo tcp_bbr | sudo tee /etc/modules-load.d/bbr.conf
Fix: Load the module first and make it persistent (/etc/modules-load.d/), then configure /etc/sysctl.d/.
1. Count the distribution by state of all current connections to Redis (6379).
ss -tan '( dport = :6379 )' | awk 'NR>1{print $1}' | sort | uniq -c2. Persistence: load BBR, use fq as the default qdisc, and set the congestion control to bbr.
echo tcp_bbr | sudo tee /etc/modules-load.d/bbr.conf printf 'net.core.default_qdisc = fq\nnet.ipv4.tcp_congestion_control = bbr\n' | sudo tee /etc/sysctl.d/90-bbr.conf sudo modprobe tcp_bbr && sudo sysctl --system | tail -3
An Nginx reverse proxy forwards requests to five backend ports on the same host. During peak periods, the Nginx error log shows “connect() to 127.0.0.1:8081 failed (99: Cannot assign requested address)”. Analyze the cause and provide at least three solutions, ranked by priority.
Error code 99 is EADDRNOTAVAIL: Nginx uses short-lived connections to each backend, and as the active closer, Nginx accumulates a large number of TIME_WAIT sockets, exhausting the local ports for the destination 127.0.0.1:8081. Priority: ① Enable a keepalive connection pool in the upstream (and set proxy_http_version 1.1 and clear the Connection header) to fundamentally reduce the creation of new connections; ② add backend listening addresses or use Unix sockets; ③ increase ip_local_port_range; ④ tcp_tw_reuse (the default value 2 is already enabled for loopback, so in this case it more strongly indicates that the connection rate exceeds the reuse rate). Do not use the removed tcp_tw_recycle.
Verified Instructional Videos
Topic video on SYN/accept queues, TIME_WAIT, and BBR: No verified video found; refer to the kernel documentation and the storyboard below.
Official Documentation
- ip-sysctl (kernel.org): tcp_* and ip_local_port_range
- listen(2) · tcp(7) · ss(8)
- BBR: Congestion-Based Congestion Control(Google Research)
Video Storyboard Script (approximately 90 seconds)
This courseware cannot directly generate video/MP3 files; a storyboard and narration script are provided.
Visual: Two lines of people waiting outside a restaurant: one line has just taken a number (the SYN queue), while the other is seated and waiting to order (the accept queue); the waiter (the application) is overwhelmed, the second line is full, and the customers at the entrance are left waiting, knocking on the door again after 1 second, then 3 seconds.
Voice-over: When the accept queue is full, no error is reported; it simply makes the client inexplicably wait a few extra seconds.
Visual: Client-side port numbers are like parking spaces; every closed connection must remain in its space for 60 seconds (TIME_WAIT), and the spaces quickly fill up.
Voice-over: The root cause of port exhaustion is too many short-lived connections. A connection pool is more effective than any kernel parameter.
Visual: Two curves: CUBIC is cut in half when it encounters packet loss, while BBR smoothly tracks the bottleneck bandwidth.
Voice-over: Congestion control takes effect only on the sender side. Measure first, then roll out the change gradually on the server.
Module 5 · TLS Principles: Handshake, Certificate Chain, and SNI
- Describe the complete TLS 1.3 handshake (1-RTT) in message order, and state the key differences from TLS 1.2 (2-RTT): only (EC)DHE remains for key exchange, certificates are encrypted, and cipher suites are simplified.
- Explain certificate chain validation: leaf certificate → intermediate CA → root in the trust store, with each level checked for signature, validity period, usage (basicConstraints / keyUsage / EKU), and hostname (SAN).
- Manage the system trust store on Ubuntu (
update-ca-certificates) and RHEL-family systems (update-ca-trust), and know that runtimes such as Python / Java / Node.js may use their own trust stores. - State the roles of SNI and ALPN, and the status of certificate revocation after 2025: OCSP is being phased out, CRLs are returning, and certificates have short validity periods.
What: TLS 1.3 Handshake (1-RTT)
- ClientHello (plaintext): supported versions (including TLS 1.3 in the
supported_versionsextension), cipher suites, key_share (the client’s precomputed key-exchange public key; OpenSSL 3.5 sends the post-quantum hybrid groupX25519MLKEM768andX25519by default), SNI (the hostname to access), ALPN (the desired application protocol, such ash2orhttp/1.1), and signature algorithms. - ServerHello (plaintext): the selected version and cipher suite, and the server’s key_share. At this point, both sides independently calculate the shared secret; all subsequent handshake messages are encrypted.
- {EncryptedExtensions}: ALPN result and other information; {Certificate}: certificate chain; {CertificateVerify}: the server signs the handshake transcript with its private key to prove that it possesses the private key corresponding to the certificate; {Finished}: a MAC over the entire handshake. If a client certificate is required, the server also sends {CertificateRequest} (mTLS, Module 7).
- The client validates the certificate chain and signature, sends {Finished}, and can then send application data.
| TLS 1.2 | TLS 1.3 | |
|---|---|---|
| Handshake round trips | 2-RTT | 1-RTT (session resumption can use 0-RTT, with a replay risk) |
| Key exchange | RSA key transport or (EC)DHE | Only (EC)DHE (and hybrid PQC); forward secrecy is inherent |
| Certificates | Transmitted in plaintext | Transmitted encrypted |
| Cipher suites | Many combinations (e.g., ECDHE-RSA-AES128-GCM-SHA256) | 5, describing only AEAD + hash (e.g., TLS_AES_128_GCM_SHA256) |
| Removed | — | RSA key transport, CBC, RC4, SHA-1 signatures, compression, renegotiation |
Certificate Chain Validation
The server sends “leaf certificate + intermediate certificates” (it does not need to and should not send the root certificate); the client uses a root in its trust store to complete the chain, then checks each level:
- Signature: Each certificate’s signature can be verified using the public key of the certificate above it.
- Validity period: The current time falls between notBefore and notAfter (depends on the local clock—a clock skew can cause a certificate to appear “not yet valid” or “expired”).
- CA constraints: The parent certificate must have
basicConstraints: CA:TRUE,keyUsagecontainingkeyCertSign, and satisfypathlen. - Usage: The leaf certificate’s EKU must include
serverAuth(client certificates includeclientAuth). - Hostname: The name being accessed must match a DNS or IP entry in the SAN (Subject Alternative Name); modern clients no longer check the CN. The wildcard
*.example.commatches only one level. - Revocation (optional, depending on the client): CRL or OCSP.
Trust Stores
| Ubuntu / Debian | RHEL / Rocky / Alma | |
|---|---|---|
| Add a private root | Place in /usr/local/share/ca-certificates/NAME.crt (PEM; the extension must be .crt) | Place in /etc/pki/ca-trust/source/anchors/ |
| Update command | sudo update-ca-certificates | sudo update-ca-trust (equivalent to update-ca-trust extract) |
| Generated bundle file | /etc/ssl/certs/ca-certificates.crt | /etc/pki/tls/certs/ca-bundle.crt (points to /etc/pki/ca-trust/extracted/) |
| Users | Programs that link to the system TLS library, such as OpenSSL, curl, wget, apt / dnf, and others. Exception: Python requests uses the bundle included with certifi by default (can be configured with REQUESTS_CA_BUNDLE); Java uses its own cacerts (keytool); Node.js uses its built-in roots by default (can use NODE_EXTRA_CA_CERTS or, in newer versions, --use-system-ca); Firefox uses NSS. | |
SNI and ALPN
- SNI: When multiple HTTPS sites are hosted on one IP address, the server selects a certificate based on the hostname in the ClientHello. If SNI is not sent (for example, when
openssl s_clientconnects to an IP address or when using an older client), the default certificate is returned, resulting in a “hostname mismatch” or handshake failure. SNI is sent in plaintext; ECH (Encrypted ClientHello) is used to encrypt it, while standardization and deployment progress remain subject to actual developments. - ALPN: Negotiates the application-layer protocol during the handshake (
h2,http/1.1; HTTP/3 is negotiated separately over QUIC). gRPC depends on h2; failure of ALPN negotiation causes the connection to be rejected.
Current state of revocation (2026)
- Let's Encrypt has discontinued OCSP: As of 2025-05-07, new certificates no longer include an OCSP URL; on 2025-08-06, the OCSP service was shut down, and revocation information is published only through CRL (for privacy reasons—OCSP exposes which sites users have accessed—and due to operational costs). CA/B Forum rules also now allow public CAs to provide CRL only.
- Browsers aggregate revocation data themselves: Chrome uses CRLSets, and Firefox uses CRLite; they generally do not query OCSP online.
- Therefore, OCSP stapling is meaningless for certificates without an OCSP URL (nginx will issue a warning and ignore it); the actual trend is to shorten certificate validity periods, allowing stolen certificates to expire naturally soon (Module 7).
- Private PKIs still need their own revocation mechanism: CRL (Module 6) or certificates with extremely short validity periods.
Figure 5-1: TLS 1.3 and TLS 1.2 Handshake Comparison
Figure 5-2: Step-by-Step Certificate Chain Validation
TLS 1.3 Handshake + Step-by-Step Certificate Chain Validation
Click “Next” to send handshake messages one by one; after entering the certificate validation phase, validation proceeds upward from the leaf certificate level by level until it reaches the root in the trust store. You can select a “faulty certificate” to see at which level and for what reason validation fails (output is an example, with the format based on OpenSSL 3.5).
Core Commands and Parameters
| Command | Function | Description |
|---|---|---|
openssl s_client -connect HOST:443 -servername HOST -brief </dev/null | Handshake summary: version, cipher suite, group, verification result | </dev/null makes it exit immediately after the handshake |
... -showcerts | Prints the entire chain sent by the server (PEM) | Counts the number of BEGIN CERTIFICATE occurrences |
... -tls1_2 / -tls1_3 | Forces the protocol version | Test server support scope |
... -alpn h2,http/1.1 | Test ALPN | Output ALPN protocol: h2 |
... -groups X25519MLKEM768 | Specify the key exchange group | Test post-quantum hybrid group support |
openssl x509 -in c.pem -noout -subject -issuer -dates -ext subjectAltName,extendedKeyUsage | View key certificate fields | Use -text to view all |
openssl verify -CAfile root.pem -untrusted int.pem leaf.pem | Verify the chain offline | -verify_hostname、-purpose sslserver |
curl -v https://HOST/ / curl -w '%{time_appconnect}' | View the TLS process / handshake duration | --cacert、--resolve、--tlsv1.3 |
sudo update-ca-certificates / sudo update-ca-trust | Update the system trust store | Ubuntu / RHEL-based systems |
openssl s_client -connect ubuntu.com:443 -servername ubuntu.com -brief </dev/null 2>&1 | head -12
CONNECTION ESTABLISHED Protocol version: TLSv1.3 Ciphersuite: TLS_AES_256_GCM_SHA384 Peer certificate: CN=ubuntu.com Hash used: SHA256 Signature type: ECDSA Verification: OK Negotiated TLS1.3 group: X25519MLKEM768 DONE
openssl s_client -connect ubuntu.com:443 -servername ubuntu.com -showcerts </dev/null 2>/dev/null \
| awk '/^ *[0-9] s:/{print} /^ *i:/{print}'
0 s:CN=ubuntu.com i:C=US, O=Let's Encrypt, CN=E8 1 s:C=US, O=Let's Encrypt, CN=E8 i:C=US, O=Internet Security Research Group, CN=ISRG Root X1
Depth 0 is the leaf, and depth 1 is the intermediate certificate; the root (ISRG Root X1) is not sent and is provided by the client trust store. Intermediate certificate names (E7/E8, etc.) change as the CA rotates.
Lab 5: Dissecting a Real Site and Trust Store (about 7 minutes)
for v in -tls1_2 -tls1_3; do echo "== $v"; openssl s_client -connect ubuntu.com:443 -servername ubuntu.com $v -brief </dev/null 2>&1 | grep -E 'Protocol|Ciphersuite|group|Verification'; done
curl -sS -o /dev/null -w 'tcp=%{time_connect} tls=%{time_appconnect} ttfb=%{time_starttransfer}\n' https://ubuntu.com
time_appconnect - time_connect is approximately the handshake time: TLS 1.3 takes approximately 1 RTT.
cd ~/linuxlab/pki openssl s_client -connect ubuntu.com:443 -servername ubuntu.com </dev/null 2>/dev/null | openssl x509 > ubuntu-leaf.pem openssl x509 -in ubuntu-leaf.pem -noout -subject -issuer -dates -ext subjectAltName,extendedKeyUsage,crlDistributionPoints,authorityInfoAccess
subject=CN=ubuntu.com
issuer=C=US, O=Let's Encrypt, CN=E8
notBefore=Oct 20 08:11:02 2026 GMT
notAfter=Jan 18 08:11:01 2027 GMT
X509v3 Subject Alternative Name:
DNS:ubuntu.com, DNS:www.ubuntu.com
X509v3 Extended Key Usage:
TLS Web Server Authentication
X509v3 CRL Distribution Points:
Full Name:
URI:http://e8.c.lencr.org/43.crl
Authority Information Access:
CA Issuers - URI:http://e8.i.lencr.org/
Note: AIA contains only “CA Issuers” and does not contain “OCSP - URI”; EKU contains only server authentication (Let's Encrypt removed clientAuth in 2026; see Module 7). The CA used by a specific site should be determined in practice.
IP=$(getent ahostsv4 ubuntu.com | awk 'NR==1{print $1}')
openssl s_client -connect "$IP:443" -noservername </dev/null 2>&1 | grep -E 'subject=|Verify return|alert' | head -3
openssl s_client -connect "$IP:443" -servername ubuntu.com </dev/null 2>&1 | grep -E 'subject=' | head -1
Without SNI, the server may return a default certificate, return a handshake failure alert, or work normally—depending on the server / CDN configuration. Use -servername to reliably obtain the correct certificate.
ls /etc/ssl/certs | wc -l grep -c 'BEGIN CERTIFICATE' /etc/ssl/certs/ca-certificates.crt openssl x509 -in /etc/ssl/certs/ISRG_Root_X1.pem -noout -subject -enddate python3 -c "import ssl; print(ssl.get_default_verify_paths())"
subject=C=US, O=Internet Security Research Group, CN=ISRG Root X1 notAfter=Jun 4 11:04:38 2035 GMT DefaultVerifyPaths(cafile=None, capath='/usr/lib/ssl/certs', openssl_cafile_env='SSL_CERT_FILE', openssl_cafile='/usr/lib/ssl/cert.pem', openssl_capath_env='SSL_CERT_DIR', openssl_capath='/usr/lib/ssl/certs')
Python's standard-library ssl uses the system OpenSSL paths (on Ubuntu, /usr/lib/ssl/certs points to /etc/ssl/certs); third-party library requests, by default, uses certifi. Module 6 will add the private root here.
rm -f ~/linuxlab/pki/ubuntu-leaf.pem.Case 1: Browser works, but API clients report unable to get local issuer certificate
Problem: After certificate renewal, web access works normally, but all callers written in Java and Go fail. Procedure: openssl s_client -showcerts shows only 1 certificate (depth 0); the intermediate certificate is missing. The browser completes the chain using its cache or by downloading it via AIA, but other clients do not. Fix: Configure the server to use the full chain (leaf + intermediate). Prevention: Verify with curl / openssl in monitoring, not with a browser.
Case 2: Internal service calls fail, but curl succeeds
Problem: Operations added the private root to the system trust store. curl can access internal HTTPS, but the Python service still reports CERTIFICATE_VERIFY_FAILED. Procedure: The service uses requests, which by default reads certifi's bundle. Fix: Set Environment=REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt in the systemd unit, or use a solution such as truststore to make Python read the system trust store. Lesson: The change checklist for “adding a root” must cover all runtimes.
Case 3: gRPC service cannot connect after load balancing
Problem: The gRPC client reports “protocol error”. Procedure: openssl s_client -alpn h2 shows No ALPN negotiated—HTTP/2 is not enabled on the load balancer terminating TLS. Fix: Enable h2 / gRPC support on the load balancer.
Common Errors and Solutions
verify error:num=20:unable to get local issuer certificate
Cause: Issuer not found: the server did not send the intermediate certificate, or the root is not in the client's trust store (private CA).
openssl s_client -connect HOST:443 -servername HOST -showcerts </dev/null 2>/dev/null | grep -E '^ *[0-9] s:|^ *i:'
Fix: Configure the server to use the full chain; for a private CA, add the root to the client's trust store or specify it with -CAfile / --cacert.
curl: (60) SSL certificate problem: unable to get local issuer certificate
Cause: Same as above; curl's wording. -k (--insecure) only masks the problem.
curl -v https://HOST/ 2>&1 | grep -E 'CAfile|issuer|subject' curl --cacert ~/linuxlab/pki/root/certs/root.crt https://HOST/
SSL: no alternative certificate subject name matches target host name 'x.x.x.x'
Cause: Accessing the service by IP or alias when that IP / name is not in the certificate's SAN (curl's error; in OpenSSL, hostname mismatch, num=62).
openssl x509 -in leaf.pem -noout -ext subjectAltName curl --resolve HOST:443:IP https://HOST/ # 用正确的名字连接指定 IP
error:0A00010B:SSL routines::wrong version number
Cause: Initiating a TLS handshake on a port for a plaintext protocol (not TLS), such as https://host:80, or the backend only supports HTTP.
curl -v http://HOST:PORT/ ; openssl s_client -connect HOST:PORT </dev/null 2>&1 | head -3
Fix: Confirm the port's protocol; when reverse-proxying to the backend, pay attention to proxy_pass http:// versus https://.
1. Check how many days remain before the certificate for example.com expires (output only notAfter).
openssl s_client -connect example.com:443 -servername example.com </dev/null 2>/dev/null | openssl x509 -noout -enddate
2. Test whether a server supports TLS 1.3 + h2, and output only the protocol version and ALPN result.
openssl s_client -connect HOST:443 -servername HOST -tls1_3 -alpn h2 </dev/null 2>&1 | grep -E '^New,|Protocol *:|ALPN'
The team wants to enable OCSP stapling on all services in the internal network to “strengthen revocation checking.” The certificates come from Let's Encrypt and the company's private CA. What is your opinion?
Since 2025, Let's Encrypt certificates have not included an OCSP URL, and the service has been shut down, so stapling is not applicable (nginx will only issue a warning and ignore it). It is likewise ineffective for a private CA if no OCSP responder has been deployed. More effective approaches are to rely on short validity periods + automatic renewal for public certificates; for private PKI, publish a CRL and configure the services that require revocation checking (such as mTLS gateways) to use the CRL, or simply use certificates with validity periods of only a few days; at the same time, establish an emergency procedure for private-key compromise (revocation + reissuance + rotation).
Verified Educational Videos
Official Documentation
- RFC 8446: TLS 1.3 · RFC 5280: X.509 Certificates and CRLs
- openssl-s_client(1) · openssl-verify(1)
- Let's Encrypt:OCSP Service Has Reached End of Life
- update-ca-certificates(8) · RHEL:Using shared system certificates
Video Storyboard Script (approximately 90 seconds)
This courseware cannot directly generate video/MP3 files; a storyboard and narration script have been provided.
Visual: The client sends a ClientHello labeled with SNI, ALPN, and a “half key” (key_share); the server sends back the other half, and the two halves combine to form the session key. All subsequent envelopes are locked.
Narration: TLS 1.3 completes the key exchange in the first round trip, and even the certificate is inside an encrypted envelope.
Visual: The certificate chain resembles a three-level staircase: leaf, intermediate, and root; the verifier climbs from bottom to top, checking the signature, dates, and intended usage at each level, and finally comparing the last level with the root in the trust store.
Narration: The server must send the leaf and intermediate certificates; the client already has the root certificate. Omitting the intermediate certificate is the most common production failure.
Visual: The OCSP phone line is cut, while the calendar beside it shortens certificate lifetimes from one year to several dozen days.
Voice-over: Revocation is becoming increasingly unreliable, and the industry's answer is to shorten certificate lifetimes and automate everything.
Module 6 · PKI in Practice: Building a Private CA, Issuing and Revoking Certificates with openssl
- Explain why a two-tier “root CA + intermediate CA” structure is used, as well as the significance of keeping the root private key offline and setting
pathlen:0on the intermediate CA. - Write an
openssl.cnfcontaining the CA database (index.txt,serial,crlnumber), policies, and extension sections for each type of certificate (v3_root,v3_int,server_cert,client_cert). - Issue a server certificate with SAN and a client certificate with clientAuth, revoke certificates and generate a CRL, and verify it with
openssl verify -crl_check. - Add the private root to the Ubuntu and RHEL system trust stores, and verify that curl can directly trust internal services.
What: Components of a Private PKI
| Component | Function | Files in This Lesson |
|---|---|---|
| Root CA | Trust anchor, self-signed; long validity period (10–20 years); the private key should be kept offline (HSM, offline machine, encrypted media) | root/private/root.key、root/certs/root.crt |
| Intermediate (issuing) CA | Issued by the root and used for routine issuance of end-entity certificates; if compromised, only the intermediate CA needs to be revoked and rebuilt by the root, without replacing the trust anchors on all clients | int/private/int.key、int/certs/int.crt |
| CA database | index.txt (one line for each issued certificate: V valid / R revoked / E expired), serial (next serial number), crlnumber | int/index.txt, etc. |
| CRL | Revocation list, signed by the CA, with a validity period (nextUpdate); it must be regenerated and published regularly | int/crl/int.crl |
| End-entity certificates | Server certificates (serverAuth + SAN), client certificates (clientAuth) | myapp.crt、alice.crt |
Key Extensions (Determine What a Certificate “Can Do”)
| Extension | Root / Intermediate CA | Server Certificate | Client Certificate |
|---|---|---|---|
| basicConstraints | critical, CA:true (add pathlen:0 to the intermediate: it cannot sign another CA) | critical, CA:false | |
| keyUsage | critical, keyCertSign, cRLSign | critical, digitalSignature (for an RSA certificate used for TLS 1.2 RSA key transport, keyEncipherment is also required) | |
| extendedKeyUsage | Usually not set | serverAuth | clientAuth |
| subjectAltName | — | DNS:myapp.lab.internal, IP:10.200.0.20 | Optional (such as email: or URI:spiffe://…) |
| crlDistributionPoints | CRL pointing to the root in the intermediate CA certificate | CRL URL pointing to the intermediate CA | |
| SKID / AKID | Key identifiers: help clients find the correct issuer among multiple CA certificates with the same name (especially important during CA rotation) | ||
Why: Why Not Use Self-Signed Certificates Directly
- There is one self-signed certificate per server, and clients must trust each one individually; expiration and replacement require changes on all clients.
- A private CA requires distributing the root certificate only once; server certificates can be rotated automatically on a short-term basis; certificates can be revoked; and client certificates can be issued to implement mTLS.
How: Several openssl Subcommands
| Subcommand | Purpose |
|---|---|
openssl genpkey | Generate a private key (RSA, EC P-256/P-384, Ed25519; OpenSSL 3.5 also supports ML-DSA, but browsers and most TLS clients do not yet accept post-quantum certificates) |
openssl req | Generate a CSR; -x509 directly generates a self-signed certificate (for use as a root) |
openssl ca | Issue certificates according to openssl.cnf, maintain the database, revoke certificates, and generate CRLs—suitable for teaching and small-scale use |
openssl x509 -req | Quick issuance without maintaining a database (cannot be managed with ca -revoke) |
openssl verify / openssl crl | Validate the chain offline and view the CRL |
When: Build an OpenSSL CA or use a product
OpenSSL CA is suitable for learning, laboratories, and a small number of long-lived certificates. When there are many certificates, and automated issuance (ACME, Kubernetes), auditing, and HSM support are required, use a dedicated product: step-ca (supports ACME), HashiCorp Vault PKI, EJBCA, a cloud provider's managed private CA, or cert-manager in Kubernetes. The concepts are exactly the same: root / intermediate, extensions, revocation, and rotation.
copy_extensions = copy is convenient, so it can be enabled freely”—it copies the extensions in the CSR into the certificate; if basicConstraints is not explicitly set in the CA section, a malicious CSR may obtain CA privileges; basicConstraints / keyUsage / EKU must be fixed in the issuance section. ③ “Generating the CRL once is enough”—a CRL has a nextUpdate; after it expires, strict validators will reject all certificates. ④ “The longer the certificate validity period, the less trouble”—the longer it is, the longer the impact of a compromise will last, and the less familiar the rotation process will become.Figure 6-1: Two-tier PKI and the certificates issued in this lesson
Figure 6-2: Issuance process (CSR mode)
PKI Builder: Issuance, Revocation, and Validation
Click the buttons in order to build the PKI. The right side displays the contents of int/index.txt and the CRL in real time; “Validate” simulates the step-by-step checks performed by openssl verify -crl_check. Buttons will explain the reason when prerequisites are not met.
openssl.cnf (stored at ~/linuxlab/pki/openssl.cnf)
[ ca ] default_ca = CA_int [ CA_root ] dir = ./root database = $dir/index.txt new_certs_dir = $dir/newcerts certificate = $dir/certs/root.crt private_key = $dir/private/root.key serial = $dir/serial crlnumber = $dir/crlnumber default_md = sha384 default_days = 1825 default_crl_days = 180 policy = policy_loose copy_extensions = none unique_subject = no [ CA_int ] dir = ./int database = $dir/index.txt new_certs_dir = $dir/newcerts certificate = $dir/certs/int.crt private_key = $dir/private/int.key serial = $dir/serial crlnumber = $dir/crlnumber default_md = sha256 default_days = 90 default_crl_days = 7 policy = policy_loose copy_extensions = copy # 只为复制 CSR 中的 SAN;关键扩展在下方各段强制设定 unique_subject = no [ policy_loose ] commonName = supplied organizationName = optional [ req ] distinguished_name = req_dn prompt = no [ req_dn ] CN = placeholder [ v3_root ] basicConstraints = critical, CA:true keyUsage = critical, keyCertSign, cRLSign subjectKeyIdentifier = hash [ v3_int ] basicConstraints = critical, CA:true, pathlen:0 keyUsage = critical, keyCertSign, cRLSign subjectKeyIdentifier = hash authorityKeyIdentifier = keyid:always crlDistributionPoints = URI:http://10.200.0.1:8000/root.crl [ server_cert ] basicConstraints = critical, CA:false keyUsage = critical, digitalSignature extendedKeyUsage = serverAuth subjectKeyIdentifier = hash authorityKeyIdentifier = keyid crlDistributionPoints = URI:http://10.200.0.1:8000/int.crl [ client_cert ] basicConstraints = critical, CA:false keyUsage = critical, digitalSignature extendedKeyUsage = clientAuth subjectKeyIdentifier = hash authorityKeyIdentifier = keyid crlDistributionPoints = URI:http://10.200.0.1:8000/int.crl
Quick Reference for Common Commands
| Command | Function |
|---|---|
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out k.key | Generate an EC private key (RSA: -algorithm RSA -pkeyopt rsa_keygen_bits:3072) |
openssl req -new -key k.key -subj "/CN=x" -addext "subjectAltName=DNS:x,IP:10.0.0.1" -out x.csr | Generate a CSR with SAN |
openssl req -in x.csr -noout -text -verify | Check the CSR contents and signature |
openssl ca -config openssl.cnf -name CA_int -extensions server_cert -in x.csr -out x.crt -batch -notext | Issue |
openssl ca -config openssl.cnf -name CA_int -revoke x.crt -crl_reason keyCompromise | Revoke (write to index.txt) |
openssl ca -config openssl.cnf -name CA_int -gencrl -out int/crl/int.crl | Generate a CRL |
openssl crl -in int/crl/int.crl -noout -text | View the CRL |
openssl x509 -noout -pubkey / openssl pkey -pubout | Verify that the certificate and private key match (compare the public keys output by both; applicable to both RSA and EC) |
Lab 6: Two-tier CA → Server Certificate → Client Certificate → Revocation (approximately 7 minutes)
genpkey -aes256), with backups and access approval.~/linuxlab/pki/):
cd ~/linuxlab/pki
mkdir -p root/{certs,crl,newcerts,private} int/{certs,crl,newcerts,private}
chmod 700 root/private int/private
touch root/index.txt int/index.txt
echo 1000 > root/serial; echo 1000 > int/serial
echo 1000 > root/crlnumber; echo 1000 > int/crlnumberopenssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-384 -out root/private/root.key openssl req -config openssl.cnf -new -x509 -key root/private/root.key -days 3650 -sha384 \ -subj "/O=Linux Lab/CN=Linux Lab Root CA" -extensions v3_root -out root/certs/root.crt openssl x509 -in root/certs/root.crt -noout -subject -issuer -ext basicConstraints,keyUsage
subject=O=Linux Lab, CN=Linux Lab Root CA
issuer=O=Linux Lab, CN=Linux Lab Root CA
X509v3 Basic Constraints: critical
CA:TRUE
X509v3 Key Usage: critical
Certificate Sign, CRL Signopenssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out int/private/int.key openssl req -config openssl.cnf -new -key int/private/int.key \ -subj "/O=Linux Lab/CN=Linux Lab Issuing CA 1" -out int/int.csr openssl ca -config openssl.cnf -name CA_root -batch -notext -extensions v3_int -days 1825 \ -in int/int.csr -out int/certs/int.crt cat int/certs/int.crt root/certs/root.crt > int/certs/ca-chain.crt openssl verify -CAfile root/certs/root.crt int/certs/int.crt
Using configuration from openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
Serial Number: 4096 (0x1000)
...
Data Base Updated
int/certs/int.crt: OKopenssl req -new -newkey ec -pkeyopt ec_paramgen_curve:P-256 -noenc -keyout myapp.key \ -subj "/CN=myapp.lab.internal" \ -addext "subjectAltName=DNS:myapp.lab.internal,IP:10.200.0.20" -out myapp.csr openssl ca -config openssl.cnf -name CA_int -batch -notext -extensions server_cert \ -in myapp.csr -out myapp.crt cat myapp.crt int/certs/int.crt > myapp-fullchain.crt openssl x509 -in myapp.crt -noout -subject -issuer -enddate -ext subjectAltName,extendedKeyUsage openssl verify -CAfile root/certs/root.crt -untrusted int/certs/int.crt \ -purpose sslserver -verify_hostname myapp.lab.internal myapp.crt
subject=CN=myapp.lab.internal
issuer=O=Linux Lab, CN=Linux Lab Issuing CA 1
notAfter=Feb 16 09:30:12 2027 GMT
X509v3 Subject Alternative Name:
DNS:myapp.lab.internal, IP Address:10.200.0.20
X509v3 Extended Key Usage:
TLS Web Server Authentication
myapp.crt: OKfor u in alice bob; do openssl req -new -newkey ec -pkeyopt ec_paramgen_curve:P-256 -noenc -keyout $u.key -subj "/CN=$u" -out $u.csr openssl ca -config openssl.cnf -name CA_int -batch -notext -extensions client_cert -days 30 -in $u.csr -out $u.crt done cat int/index.txt
V 270216093012Z 1000 unknown /CN=myapp.lab.internal V 261218093120Z 1001 unknown /CN=alice V 261218093121Z 1002 unknown /CN=bob
openssl ca -config openssl.cnf -name CA_int -revoke bob.crt -crl_reason keyCompromise openssl ca -config openssl.cnf -name CA_int -gencrl -out int/crl/int.crl openssl ca -config openssl.cnf -name CA_root -gencrl -out root/crl/root.crl openssl crl -in int/crl/int.crl -noout -text | grep -E 'Next Update|Serial Number|Revocation Date|Key Compromise' openssl verify -crl_check -CAfile root/certs/root.crt -untrusted int/certs/int.crt -CRLfile int/crl/int.crl alice.crt bob.crt
Next Update: Nov 25 09:35:40 2026 GMT
Serial Number: 1002
Revocation Date: Nov 18 09:35:31 2026 GMT
Key Compromise
alice.crt: OK
CN=bob
error 23 at 0 depth lookup: certificate revoked
error bob.crt: verification failedsudo cp root/certs/root.crt /usr/local/share/ca-certificates/linuxlab-root-ca.crt
sudo update-ca-certificates
sudo ip netns exec blue openssl s_server -accept 443 -cert myapp.crt -key myapp.key \
-cert_chain int/certs/int.crt -www -quiet &
sleep 1; curl -sS https://myapp.lab.internal/ | head -3
curl -sS https://10.200.0.20/ -o /dev/null -w '%{http_code}\n'
sudo ip netns pids blue | xargs -r sudo kill
Updating certificates in /etc/ssl/certs... 1 added, 0 removed; done. Running hooks in /etc/ca-certificates/update.d... done. <HTML><BODY BGCOLOR="#ffffff"> <pre> s_server -accept 443 -cert myapp.crt ... 200
Access by IP also succeeds because the SAN contains IP:10.200.0.20. Equivalent operation on RHEL-based systems (rhellab): sudo cp root.crt /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust.
Case 1: Intermediate CA expires, causing simultaneous errors across all internal company services
Problem: The intermediate CA created five years ago expires, causing all server certificates it issued that are still within their validity periods to become invalid at the same time. Approach: An expired certificate at any level of the chain causes verification to fail. Remediation: Create a new intermediate CA one year in advance (signed by the same root), have new certificates issued by the new intermediate CA, and allow the old certificates to be naturally rotated out. Prevention: Monitor the expiration date of every certificate in the chain, not just the leaf certificate.
Case 2: The Internal CA Issued a “Server Certificate” That Could Be Used as a CA
Issue: An audit found that a server certificate had CA:TRUE. Action: The certificate was issued with copy_extensions = copyall, allowing the basicConstraints in the CSR to override the CA settings. Remediation: Revoke the certificate and publish a CRL; change the configuration to copy and explicitly set the critical extensions in the signing section; add pathlen:0 to the intermediate CA as a fallback (even if it issues a CA certificate, that certificate cannot issue any further valid certificates).
Case 3: An Expired CRL Prevented All VPN Users from Logging In
Issue: One morning, all VPN users failed to log in. Action: The VPN gateway strictly validated the CRL, but the CRL's nextUpdate had passed (the host running the scheduled CRL-generation task had been decommissioned). Remediation: Regenerate and publish the CRL; implement CRL generation as a highly available scheduled task, and monitor the CRL's nextUpdate.
Common Errors and Solutions
failed to update database TXT_DB error number 2
Cause: When unique_subject = yes (the default), if a valid certificate already exists for the same subject, openssl ca rejects duplicate issuance (common during renewal).
grep '/CN=myapp.lab.internal' int/index.txt; cat int/index.txt.attr 2>/dev/null
Remediation: Set unique_subject = no in the CA section (index.txt.attr also records this value), or revoke the old certificate first.
The commonName field needed to be supplied and was missing
Cause: The policy section requires commonName = supplied, but the CSR has no CN (CSRs containing only a SAN are common).
Remediation: Add a CN to the CSR, or change the policy to optional (the SAN is the basis for hostname matching).
error 24 at 1 depth lookup: invalid CA certificate
Cause: One level of the chain lacks CA:TRUE or the keyUsage is missing keyCertSign (for example, a server certificate was mistakenly used as an intermediate certificate, or -extensions v3_int was omitted when signing the intermediate CA).
openssl x509 -in int/certs/int.crt -noout -ext basicConstraints,keyUsage
Remediation: Reissue the intermediate CA using the correct extensions section.
error 3 at 0 depth lookup: unable to get certificate CRL
Cause: CRL checking is enabled, but the CRL for the corresponding issuer has not been provided; -crl_check_all or certain services (such as nginx's ssl_crl) require every level in the chain to have a CRL.
openssl verify -crl_check_all -CAfile root/certs/root.crt -untrusted int/certs/int.crt \ -CRLfile int/crl/int.crl -CRLfile root/crl/root.crl alice.crt
Remediation: Provide CRLs for both the root and intermediate CAs (this is why root.crl was also generated in the lab).
X509_check_private_key:key values mismatch
Cause: The certificate and private key do not match (the wrong files were used during deployment). In nginx, this appears as a startup failure.
diff <(openssl x509 -in myapp.crt -noout -pubkey) <(openssl pkey -in myapp.key -pubout) && echo match
1. Generate an RSA 3072 private key and CSR for api.lab.internal (with api.lab.internal and api in the SAN), and inspect the CSR contents.
openssl req -new -newkey rsa:3072 -noenc -keyout api.key -subj "/CN=api.lab.internal" \ -addext "subjectAltName=DNS:api.lab.internal,DNS:api" -out api.csr openssl req -in api.csr -noout -text -verify | grep -E 'verify|Subject:|DNS:'
2. List the serial numbers and subjects of all revoked certificates in int/index.txt.
awk -F'\t' '$1=="R"{print $4, $6}' ~/linuxlab/pki/int/index.txtThe company needs to provide TLS certificates for 300 internal services and client certificates for 2,000 devices. Give recommendations for the PKI hierarchy, certificate validity periods, issuance and revocation methods, and explain whether openssl ca is suitable.
Hierarchy: an offline root (HSM or offline machine, 10–20 years) → at least two intermediate CAs (one for servers / one for device clients, separated to facilitate independent revocation and different policies), with pathlen:0 and EKU constraints set on the intermediate CAs. Validity periods: automatically rotate server certificates every 30–90 days; device certificate validity should be determined by the enrollment process, with ≤1 year recommended and automatic renewal supported. Issuance: use a CA product that supports ACME / SCEP / EST or APIs (step-ca, Vault PKI, a cloud-hosted private CA, or cert-manager in Kubernetes); openssl ca lacks concurrency, auditing, and automation interfaces, and is suitable only for labs or a very small number of certificates. Revocation: publish CRLs (with highly available HTTP distribution and nextUpdate monitoring); server certificates should rely on short validity periods; device certificates require a revocation process and CRL checking on the mTLS gateway.
Verified Instructional Video
Official Documentation
- openssl-ca(1) · openssl-req(1) · x509v3_config(5)
- RFC 5280: Certificate Path Validation and CRLs
- OpenSSL Versions and Support Lifecycle
Video Storyboard (approximately 90 seconds)
This courseware cannot generate video/MP3 directly; a storyboard and narration script are provided.
Visual: The root CA in the safe comes out only once, stamps the intermediate CA, and is immediately locked away again.
Narration: The less often the root private key is used, the safer it is; routine issuance is delegated to the intermediate CA.
Visual: The CSR form says “I want SANs; I want to be a CA”; the CA crosses out “be a CA” in red and stamps it with a serverAuth seal.
Narration: A CSR is only a request; what ultimately appears in the certificate is determined by the CA’s configuration.
Visual: The line for bob in index.txt changes from V to R, the CRL bulletin board is updated, and the validator rejects bob after reading the bulletin.
Narration: Revocation must be recorded in the database, and the CRL must also be published and continuously refreshed before it expires.
Module 7 · Certificate Operations: ACME Automatic Renewal, Rotation, and mTLS
- Explain the ACME workflow (account → order → authorization → challenge → CSR submission → certificate download) and the applicable scenarios for HTTP-01, DNS-01, and TLS-ALPN-01 (wildcards can only use DNS-01).
- Remember the CA/B Forum validity-period schedule (200 days from 2026-03-15, 100 days from 2027-03-15, and 47 days from 2029-03-15) and Let’s Encrypt’s 90 → 64 → 45-day plan, and use them to design a renewal strategy (proportional renewal + ARI).
- Use certbot’s deploy hook to automatically reload services; use standalone scripts/monitoring to check the number of days remaining on certificates, without relying on notification emails from the CA (Let’s Encrypt stopped sending them on 2025-06-04).
- Configure mTLS for myapp with nginx: have the server verify client certificates, check the CRL, and pass the client identity to the application; know that public CAs no longer issue certificates containing clientAuth.
What: The ACME Protocol
- Account: The client generates an account key and registers it with the CA (Let's Encrypt no longer stores contact email addresses).
- Order: Request a set of identifiers (domain names; some CAs and profiles also support IP addresses). You can select a profile, such as Let's Encrypt's
classic,tlsserver, orshortlived(approximately 6 days). - Authorization and challenges: Prove that you control these identifiers:
Challenge Proof method Applicable to Notes HTTP-01 Place a response at http://domain/.well-known/acme-challenge/<token>A single server or a small number of servers accessible from the public internet on port 80 Port 80 must be reachable; wildcards are not supported; when using multiple load-balanced servers, every node must be able to respond DNS-01 Write a TXT record at _acme-challenge.domainWildcards, internal hosts, and situations where port 80 cannot be opened Requires DNS API credentials—use the least privilege possible (allow changes to TXT records only); be aware of DNS propagation delays TLS-ALPN-01 Return a special certificate on port 443 using ALPN acme-tls/1Scenarios where only port 443 is open (built-in support in Caddy, Traefik, and others) certbot does not support this method natively - Submit the CSR and download the certificate: After the order is finalized, obtain the certificate and the intermediate certificate (fullchain).
- Renewal: Repeat the process above. Authorizations can be reused for a period of time (currently 30 days for Let's Encrypt, reduced to 10 days in 2027 and 7 hours in 2028). ARI (RFC 9773) allows the CA to tell the client the recommended renewal window, and also makes it easier for the CA to notify clients to renew early in the event of large-scale revocation.
Why: Why validity periods are getting shorter
| Effective date | CA/B Forum: Maximum validity period for public TLS certificates | Validity period for reusing domain validation data |
|---|---|---|
| Before 2026-03-15 | 398 days | 398 days |
| 2026-03-15 (effective) | 200 days | 200 days |
| 2027-03-15 | 100 days | 100 days |
| 2029-03-15 | 47 days | 10 days |
| Date | Let's Encrypt plan |
|---|---|
| 2026-05-13 | Change the tlsserver profile (optional) to 45-day certificates |
| 2027-02-10 | Change the default classic profile to 64 days, with a 10-day authorization reuse period |
| 2028-02-16 | Change classic to 45 days, with a 7-hour authorization reuse period |
Reason: The revocation mechanism is unreliable (Module 5); short validity periods limit the time during which a compromised private key or misissuance can have an impact, and also force everyone to automate. Let's Encrypt explicitly states that the fixed practice of “renewing once every 60 days” is no longer applicable; clients that do not support ARI should renew at approximately 2/3 of the validity period.
How: Choosing an ACME client
| Client | Features |
|---|---|
| certbot | Maintained by EFF, Python. The Ubuntu 26.04 package is 4.0.0 (supports profiles but not ARI); upstream 5.10.0 (2026-11-10) supports ARI (since 4.1.0) and --ip-address (since 5.3.0), and can be obtained via snap. The apt version includes certbot.timer; the snap version uses snap.certbot.renew.timer. |
| acme.sh / lego | Single-file Shell / single-binary Go, with many DNS provider plugins; suitable for containers and embedded systems |
| Caddy / Traefik | ACME is built into the web server / reverse proxy, with automatic issuance and renewal |
| cert-manager | The standard solution in Kubernetes (Issuer / Certificate CRD); see the Kubernetes course |
Rotation
- Certificate rotation: After writing the new certificate, run
nginx -t && systemctl reload nginx(graceful reload; existing connections are not interrupted). Many services read certificates only at startup—you must use a deploy hook or an inotify trigger to reload them; otherwise, renewal may succeed while the service continues using the old certificate. - Private key rotation: Generate a new private key with each renewal (this is certbot’s default); set the private key file permissions to 600, with the service account or root as the owner.
- CA rotation: First distribute the new root / intermediate certificates to all client trust stores (keep the old and new certificates side by side), then switch to issuing with the new CA, and finally remove the old root. Reversing this order causes an incident.
- Independent monitoring: Probe the number of days remaining on the “certificate currently being served” from outside (
probe_ssl_earliest_cert_expiryin blackbox_exporter; see the Prometheus course), rather than just checking the file on disk.
mTLS (mutual TLS)
During the handshake, the server sends a CertificateRequest (including a list of acceptable CAs), and the client completes CertificateVerify using its own certificate and private key. The server validates the client certificate using the same rules as those used to validate a server certificate on the client side (chain, validity period, clientAuth EKU, optional CRL). Use cases: service-to-service authentication (zero trust, service meshes), API partner access, and device access.
Public CAs are no longer suitable for client certificates: The Chrome Root Program requires public TLS hierarchies to be used only for server authentication. Since 2026-02-11, Let's Encrypt certificates no longer include the clientAuth EKU by default; the temporary tlsclient profile was discontinued on 2026-07-08. mTLS client certificates should come from a private CA (Module 6).
When: Quick selection guide
| Scenario | Recommendation |
|---|---|
| Public-facing websites / APIs | Public CA + ACME (HTTP-01 or DNS-01) + deploy hook + external monitoring |
| Internal services that cannot be validated publicly | DNS-01 (if using a publicly resolvable domain) or a private CA (a private CA that supports ACME, such as step-ca) |
| Service-to-service identity authentication | Private CA + mTLS; for large-scale deployments, use a service mesh or SPIFFE to automatically issue short-lived certificates |
Figure 7-1: ACME HTTP-01 and DNS-01
Figure 7-2: Additional messages in the mTLS handshake
Certificate Validity Period and Renewal Strategy Simulator
Select a certificate validity period and renewal strategy. The simulator plots each certificate’s validity interval on a one-year timeline: green indicates validity, and red indicates gaps during which the certificate has expired. “Number of consecutive days renewal fails” simulates situations such as a DNS API outage, showing how much margin each strategy leaves.
Common certbot Commands (Public-Facing Hosts)
| Command | Purpose |
|---|---|
sudo certbot certonly --webroot -w /var/www/html -d app.example.com | HTTP-01 (webroot method); obtains the certificate only and does not modify the web configuration |
sudo certbot --nginx -d app.example.com | Automatically modifies the nginx configuration (requires python3-certbot-nginx or the snap version) |
sudo certbot certonly --dns-<provider> --dns-<provider>-credentials /root/.secrets/dns.ini -d '*.example.com' | DNS-01 wildcard (requires the corresponding DNS plugin to be installed; credentials file permissions must be 600) |
--staging(--test-cert) | Use the staging environment to avoid triggering rate limits in the production environment |
--preferred-profile tlsserver / --required-profile | Select an ACME configuration file (certbot 4.0+) |
--deploy-hook "systemctl reload nginx" | Run after each successful issuance; can also be placed in /etc/letsencrypt/renewal-hooks/deploy/ |
sudo certbot renew --dry-run | Simulate renewal (for the staging environment) |
sudo certbot certificates | List certificates and expiration dates |
systemctl list-timers | grep -i certbot | Confirm that the renewal timer exists and will run |
/etc/letsencrypt/live/app.example.com/ ├── cert.pem # 叶子证书 ├── chain.pem # 中间证书 ├── fullchain.pem # 叶子 + 中间 —— nginx 的 ssl_certificate 用它 └── privkey.pem # 私钥 —— ssl_certificate_key (live/ 下是指向 archive/ 中带编号文件的符号链接;续期后链接自动更新)
Key nginx TLS / mTLS Directives
| Directive | Purpose |
|---|---|
ssl_certificate / ssl_certificate_key | Server certificate (fullchain) and private key |
ssl_protocols TLSv1.2 TLSv1.3; | Allowed protocol versions |
ssl_client_certificate | CA used to verify client certificates (and announced in CertificateRequest) |
ssl_verify_client on | optional | Require / optional client certificate |
ssl_verify_depth 2; | Maximum client certificate chain depth |
ssl_crl | CRL file (PEM; multiple files can be concatenated; must cover every CA in the chain) |
$ssl_client_verify、$ssl_client_s_dn、$ssl_client_serial | Verification result and client identity, which can be passed to the backend or written to logs |
One-Line Command for Expiration Checks
openssl x509 -in /etc/nginx/pki/myapp-fullchain.crt -noout -checkend $((21*86400)) && echo "≥21 天" || echo "21 天内过期!"
Lab 7: Enable mTLS for myapp in nginx + Expiration Monitoring + Rotation Exercise (about 8 minutes)
cd ~/linuxlab/pki sudo install -d -m 750 /etc/nginx/pki sudo install -m 600 myapp.key /etc/nginx/pki/ sudo install -m 644 myapp-fullchain.crt int/certs/ca-chain.crt /etc/nginx/pki/ cat int/crl/int.crl root/crl/root.crl | sudo tee /etc/nginx/pki/crl.pem >/dev/null
sudo tee /etc/nginx/sites-available/myapp-mtls >/dev/null <<'EOF'
server {
listen 8443 ssl;
server_name myapp.lab.internal;
ssl_certificate /etc/nginx/pki/myapp-fullchain.crt;
ssl_certificate_key /etc/nginx/pki/myapp.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_client_certificate /etc/nginx/pki/ca-chain.crt;
ssl_verify_client on;
ssl_verify_depth 2;
ssl_crl /etc/nginx/pki/crl.pem;
location / {
proxy_pass http://127.0.0.1:5000;
proxy_set_header X-Client-DN $ssl_client_s_dn;
proxy_set_header X-Client-Verify $ssl_client_verify;
}
}
EOF
sudo ln -sf /etc/nginx/sites-available/myapp-mtls /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
myapp.lab.internal points to blue in /etc/hosts, so use --resolve to point it to the local machine):
R="--resolve myapp.lab.internal:8443:127.0.0.1" U=https://myapp.lab.internal:8443/healthz curl -sS $R $U | grep -o '<title>.*</title>' # 无证书 curl -sS $R --cert ~/linuxlab/pki/alice.crt --key ~/linuxlab/pki/alice.key $U; echo # alice curl -sS $R --cert ~/linuxlab/pki/bob.crt --key ~/linuxlab/pki/bob.key $U | grep -o '<title>.*</title>' sudo tail -n 2 /var/log/nginx/error.log
<title>400 No required SSL certificate was sent</title>
{"status": "ok"}
<title>400 The SSL certificate error</title>
... [info] ... client SSL certificate verify error: (23:certificate revoked) while reading client request headers, client: 127.0.0.1, server: myapp.lab.internal ...
The server certificate is validated by the private root in the system trust store (added in Module 6), so curl does not need --cacert. The log level for verification failures is info; if you cannot see them, temporarily set the error_log level to info. You can also test from the red namespace: sudo ip netns exec red curl --resolve myapp.lab.internal:8443:10.200.0.1 ... (if UFW is enabled, allow 8443).
cat > ~/linuxlab/net8/certcheck.sh <<'EOF'
#!/usr/bin/env bash
# 用法:certcheck.sh 阈值天数 目标... 目标:证书文件,或 地址:端口[/SNI]
set -uo pipefail
DAYS=${1:-21}; shift; rc=0
for t in "$@"; do
if [ -f "$t" ]; then pem=$(openssl x509 -in "$t" 2>/dev/null)
else addr=${t%%/*}; sni=${t#*/}; [ "$sni" = "$t" ] && sni=${addr%:*}
pem=$(openssl s_client -connect "$addr" -servername "$sni" </dev/null 2>/dev/null | openssl x509 2>/dev/null); fi
if [ -z "${pem:-}" ]; then echo "UNKNOWN $t 取不到证书"; rc=2; continue; fi
end=$(openssl x509 -noout -enddate <<<"$pem" | cut -d= -f2)
left=$(( ( $(date -d "$end" +%s) - $(date +%s) ) / 86400 ))
if openssl x509 -noout -checkend $((DAYS*86400)) <<<"$pem" >/dev/null; then echo "OK $t 剩余 ${left} 天"
else echo "WARN $t 剩余 ${left} 天(阈值 ${DAYS} 天)"; rc=1; fi
done
exit $rc
EOF
chmod +x ~/linuxlab/net8/certcheck.sh
~/linuxlab/net8/certcheck.sh 21 /etc/nginx/pki/myapp-fullchain.crt 127.0.0.1:8443/myapp.lab.internal ~/linuxlab/pki/alice.crt
~/linuxlab/net8/certcheck.sh 45 ~/linuxlab/pki/alice.crt; echo "exit=$?"
OK /etc/nginx/pki/myapp-fullchain.crt 剩余 89 天 OK 127.0.0.1:8443/myapp.lab.internal 剩余 89 天 OK /home/labadmin/linuxlab/pki/alice.crt 剩余 29 天 WARN /home/labadmin/linuxlab/pki/alice.crt 剩余 29 天(阈值 45 天) exit=1
sudo tee /etc/systemd/system/certcheck.service >/dev/null <<EOF [Unit] Description=Check TLS certificate expiry [Service] Type=oneshot ExecStart=$HOME/linuxlab/net8/certcheck.sh 21 /etc/nginx/pki/myapp-fullchain.crt 127.0.0.1:8443/myapp.lab.internal EOF sudo tee /etc/systemd/system/certcheck.timer >/dev/null <<'EOF' [Unit] Description=Daily TLS certificate expiry check [Timer] OnCalendar=daily RandomizedDelaySec=1h Persistent=true [Install] WantedBy=timers.target EOF sudo systemctl daemon-reload && sudo systemctl enable --now certcheck.timer sudo systemctl start certcheck.service; journalctl -u certcheck -n 3 --no-pager
When the script exits with a non-zero status, the unit enters the failed state. It can be integrated with the OnFailure= notification from Lesson 2, or used to trigger alerts through node_exporter’s systemd collector.
cd ~/linuxlab/pki openssl req -new -newkey ec -pkeyopt ec_paramgen_curve:P-256 -noenc -keyout myapp-new.key \ -subj "/CN=myapp.lab.internal" -addext "subjectAltName=DNS:myapp.lab.internal,IP:10.200.0.20" -out myapp-new.csr openssl ca -config openssl.cnf -name CA_int -batch -notext -extensions server_cert -in myapp-new.csr -out myapp-new.crt cat myapp-new.crt int/certs/int.crt > myapp-new-fullchain.crt sudo install -m 600 myapp-new.key /etc/nginx/pki/myapp.key sudo install -m 644 myapp-new-fullchain.crt /etc/nginx/pki/myapp-fullchain.crt sudo nginx -t && sudo systemctl reload nginx openssl s_client -connect 127.0.0.1:8443 -servername myapp.lab.internal </dev/null 2>/dev/null | openssl x509 -noout -serial
serial=1003
The serial number changes from 1000 to 1003, proving that the live service is now using the new certificate. Install the private key and certificate first, then reload once; if nginx -t fails (for example, because the private key and certificate do not match), the old configuration continues serving.
sudo snap install --classic certbot # 上游最新版;或 sudo apt install certbot(26.04 为 4.0.0) sudo certbot certonly --staging --webroot -w /var/www/html -d <你的域名> \ --deploy-hook "systemctl reload nginx" sudo certbot renew --dry-run systemctl list-timers | grep -i certbot
These commands were not run in an actual public environment for this course material; the webroot path and snap availability depend on your environment. Lab machines are usually behind NAT, so the CA cannot access them over HTTP-01—that is why internal hosts need to use DNS-01 or a private CA.
Case 1: Renewal succeeds, but the website still serves an expired certificate
Problem: Monitoring alerts that the certificate has expired, but certbot certificates shows that it has 60 days remaining. Diagnosis: openssl s_client shows that the live serial number is old—the service (a Java application with built-in TLS) reads the certificate only at startup and was not restarted after renewal. Fix: Add a deploy hook to restart or reload the service; change monitoring to probe the live certificate.
Case 2: Risks of leaked DNS-01 credentials
Problem: To issue wildcard certificates, full-access API keys for the DNS provider were stored on every web server. Risk: If any one server is compromised, an attacker can modify DNS for the entire domain. Improvement: Issue and distribute certificates from a single controlled host; restrict the API token to modifying _acme-challenge TXT records; or use a CNAME to delegate _acme-challenge to a dedicated validation zone.
Case 3: A partner's mTLS suddenly fails
Problem: In early 2026, a partner used a Let's Encrypt certificate as a client certificate to connect to our mTLS gateway, and was rejected after renewal. Diagnosis: openssl x509 -ext extendedKeyUsage shows that the new certificate has only serverAuth. Fix: Issue the partner a private CA client certificate (or use another authentication method), and configure the gateway to trust only the private CA.
Common errors and solutions
Certbot failed to authenticate some domains (authenticator: webroot). ... Type: unauthorized ... 404
Cause: The CA gets a 404 when accessing http://domain/.well-known/acme-challenge/…: the webroot path does not match nginx's actual document root, port 80 redirects elsewhere, or DNS points to another server (the error format depends on the certbot version).
echo test | sudo tee /var/www/html/.well-known/acme-challenge/t curl -i http://<域名>/.well-known/acme-challenge/t dig +short A <域名>; dig +short AAAA <域名>
Fix: Configure a separate location ^~ /.well-known/acme-challenge/ for this path; note that an AAAA record pointing to an incorrect IPv6 address can also cause failure.
too many certificates (5) already issued for this exact set of identifiers in the last 168h0m0s
Cause: The rate limit for the Let's Encrypt production environment has been triggered (repeated issuance for the same set of names; specific limits and error wording are subject to the Let's Encrypt documentation).
Fix: Use --staging during debugging; wait for the rate-limit window; investigate what is repeatedly issuing certificates (for example, a container requesting a new certificate every time it starts).
400 No required SSL certificate was sent
Cause: nginx requires a client certificate, but the client did not send one: no certificate was configured; or the client certificate was not issued by a CA advertised by the server in the CertificateRequest, so the client (such as a browser) chose not to send it.
openssl s_client -connect HOST:8443 -servername HOST </dev/null 2>/dev/null | sed -n '/Acceptable client certificate CA names/,/^Requested/p'
client SSL certificate verify error: (3:unable to get certificate CRL)
Cause: nginx's ssl_crl requires every CA in the chain to have a CRL, but only the intermediate CA's CRL was provided.
Fix: Concatenate the root and intermediate CA CRLs into the same file; refresh it regularly (reports (12:CRL has expired) when the CRL expires).
nginx: [emerg] cannot load certificate key "/etc/nginx/pki/myapp.key": ... Permission denied
Cause: Private-key permissions or AppArmor / SELinux restrictions (the nginx master process reads the certificate as root; if it is read by a non-root service, the correct group ownership is required).
sudo ls -l /etc/nginx/pki/; sudo journalctl -k -g apparmor -n 5
1. Use curl to call the mTLS service as alice, and output only the HTTP status code and TLS handshake duration.
curl -sS -o /dev/null --resolve myapp.lab.internal:8443:127.0.0.1 \
--cert ~/linuxlab/pki/alice.crt --key ~/linuxlab/pki/alice.key \
-w '%{http_code} tls=%{time_appconnect}\n' https://myapp.lab.internal:8443/healthz2. Add a global deploy hook for certbot so that after each renewal it checks the nginx configuration before reloading it.
sudo tee /etc/letsencrypt/renewal-hooks/deploy/10-reload-nginx.sh >/dev/null <<'EOF' #!/bin/sh nginx -t && systemctl reload nginx EOF sudo chmod +x /etc/letsencrypt/renewal-hooks/deploy/10-reload-nginx.sh
You are responsible for 40 public-facing domain names distributed across nginx, two Java applications, and a cloud load balancer; starting in 2027, Let's Encrypt's default certificate lifetime will become 64 days, and in 2028, 45 days. Provide a migration plan.
① Inventory: For each domain name, record the certificate source, issuance method, deployment location, and whether a restart is required for loading. ② Standardize automation: Use certbot / lego + deploy hooks for nginx; modify the Java applications to terminate TLS at a front-end reverse proxy, or support hot reloading; change the cloud load balancer to use platform-managed certificates or upload them automatically through an API. ③ Renewal strategy: Enable ARI for clients that support it (certbot ≥ 4.1); otherwise renew at 2/3 of the validity period, and delete all fixed “every 60 days” cron jobs. ④ Validation method: Centralize issuance using DNS-01 where possible, with API tokens having the minimum required privileges. ⑤ Monitoring: Externally probe probe_ssl_earliest_cert_expiry for all endpoints, with thresholds set as a proportion of the validity period (for example, alert when less than < 1/4 remains). ⑥ Drills: In the test environment, use the tlsserver (45-day) configuration to expose problems in advance.
Verified Educational Videos
Video focused on the ACME protocol, certbot automatic renewal, and nginx mTLS: No verified video found; refer to the official documentation and the storyboard below.
Official Documentation
- Let's Encrypt:Challenge Types · Profiles · Decreasing Certificate Lifetimes to 45 Days
- Let's Encrypt:Ending TLS Client Authentication Certificate Support
- CA/B Forum Baseline Requirements(2.3.1)
- RFC 8555:ACME · RFC 9773:ARI
- Certbot User Guide · ngx_http_ssl_module
Video Storyboard Script (approximately 90 seconds)
This courseware cannot directly generate video/MP3 files; a storyboard and narration script have been provided.
Visual: On a calendar, the color bar representing certificate lifetimes shrinks from one year to 200 days, then 100 days, and finally 47 days; beside it, a person holds a sticky note saying “Remember to renew,” which is blown away by the wind.
Voice-over: Certificate lifetimes are becoming shorter and shorter; relying on people to remember renewals is no longer possible.
Visual: An ACME client and a CA converse: place an order, present a token, the CA checks it, submit a CSR, receive the certificate, and finally the deploy hook presses nginx's reload button.
Voice-over: Automatic renewal must be automated together with deployment, and external monitoring must be used to confirm that the production certificate has actually been updated.
Visual: At the mTLS gateway entrance, alice presents an identity badge issued by the private CA and is allowed through, while bob’s badge is blocked because it is on the CRL blacklist.
Voice-over: For service-to-service authentication, use client certificates issued by a private CA, together with a CRL or short validity periods, so identities can be verified and revoked.
Module 8 · Network and TLS Troubleshooting and Self-Assessment
openssl s_client -connect -servername -showcerts; then troubleshoot section by section in the order “name → connection → handshake → chain → name matching → time → application”- Use a fixed troubleshooting sequence to locate HTTPS failures, and map curl / OpenSSL errors to root causes (incomplete chain, expired, not yet valid / clock skew, hostname mismatch, self-signed, protocol mismatch, SNI, MTU).
- Become proficient with
openssl s_clientoptions-servername,-showcerts,-verify_return_error,-verify_hostname,-CAfile,-cert/-key, as well ascurl -vand--resolve. - Inject 8 types of faults into the topology and diagnose them independently using the interactive troubleshooting tree.
What: The Seven Stages of an HTTPS Request
| # | Stage | Typical Error / Symptom | First Command |
|---|---|---|---|
| 1 | Name resolution | curl: (6) Could not resolve host | getent hosts NAME、resolvectl query |
| 2 | TCP connection | (7) Couldn't connect (refused), (28) timed out | ss -ltn、nc -vz HOST 443、tcpdump |
| 3 | TLS negotiation | wrong version number, handshake failure, unsupported protocol, handshake hangs | openssl s_client -tls1_2/-tls1_3、-servername |
| 4 | Certificate chain | unable to get local issuer certificate(20)、self-signed certificate(18)、self-signed certificate in certificate chain(19) | s_client -showcerts |
| 5 | Hostname | hostname mismatch(62)、curl no alternative certificate subject name matches | openssl x509 -ext subjectAltName |
| 6 | Time | certificate has expired(10)、certificate is not yet valid(9) | openssl x509 -dates、timedatectl |
| 7 | Client certificate / application | nginx 400 No required SSL certificate was sent、alert certificate required、alert unknown ca | s_client -cert -key, server error.log |
Why: Why “It Works in the Browser” Does Not Mean There Is No Problem
- Browsers cache intermediate certificates, complete the chain through AIA, and have their own trust stores; curl, Java, Go, and Python do not necessarily do this.
- Browsers always send SNI; scripts that access an IP address, or older clients, may not.
- There may be multiple nodes behind the load balancer, and only one node may have an incorrectly configured certificate—try several times, or use
--resolveseparately with each node IP.
How: The s_client Troubleshooting Pattern
H=myapp.lab.internal; P=443 openssl s_client -connect $H:$P -servername $H -showcerts -verify_return_error -verify_hostname $H </dev/null 2>&1 \ | grep -E '^ *[0-9] s:|^ *i:|v:NotBefore|Verify return code|verify error|Protocol|Cipher|alert|errno'
-servername: Send SNI (OpenSSL 3 sends it by default when the host name is used with-connect, but writing it explicitly is more reliable; when connecting to an IP, it must be specified).0 s:/i:and1 s:/i:in-showcertsdisplay the chain actually sent by the server and the validity period of each certificate (v:NotBefore/NotAfter).-verify_return_error: Abort the handshake when verification fails (by default, s_client only prints the error and continues).- Only
Verify return code: 0 (ok)indicates success; for other numbers, refer to the error codes foropenssl verify.
When: Special Cases
- Clock skew: Newly issued certificates report “not yet valid,” or all certificates suddenly show as “expired” →
timedatectl,chronyc tracking(see Lesson 2, M7 for time synchronization). This is especially common after a virtual machine is restored from a snapshot. - MTU: TCP connects and small HTTP requests work normally, but the TLS handshake hangs—the server’s certificate chain usually exceeds one MSS, so large packets are silently dropped along the path (the MTU black hole in Lesson 7, M5).
- Intermediate devices: A TLS inspection proxy will replace the certificate (the issuer becomes the company proxy CA); the issuer is immediately visible in
s_client.
curl -k works, the certificate must be fine”—-k skips all verification. ② “If s_client displays CONNECTED, the handshake succeeded”—CONNECTED only means that the TCP connection has been established. ③ “An expired certificate must mean the certificate is the problem”—the client clock may also be wrong. ④ “A handshake timeout is a server performance problem”—rule out MTU and the firewall first.Figure 8-1: Error → Stage → Command
TLS Troubleshooter
Select a failure and play it: the request moves through seven stages, stopping at the point of failure and displaying an error message in a realistic format, diagnostic commands, and a fix (output is an example). All of these failures can be reproduced in the blue namespace using tlsfault.sh from the “Lab” in this module.
Quick Reference: Troubleshooting Commands
| Purpose | Command |
|---|---|
| View everything at once | openssl s_client -connect H:443 -servername H -showcerts -verify_return_error </dev/null |
| Specify the trusted CA | ... -CAfile ~/linuxlab/pki/root/certs/root.crt;curl:--cacert |
| Check the hostname | ... -verify_hostname H;openssl x509 -checkhost H -noout -in c.pem |
| Include a client certificate | ... -cert alice.crt -key alice.key;curl:--cert --key |
| Bypass DNS and specify an IP | curl --resolve H:443:IP https://H/;s_client:-connect IP:443 -servername H |
| Detailed process | curl -v (look for SSL connection using, Server certificate, and ALPN) |
| STARTTLS service | openssl s_client -connect mail:587 -starttls smtp (also supports imap, postgres, ldap, and others) |
| Local time | timedatectl、chronyc tracking |
| MTU | ping -M do -s 1472 H、tracepath -n H、ip link show |
curl -v https://myapp.lab.internal/ 2>&1 | grep -E '^\* (Connected|SSL connection|ALPN|Server certificate| subject| expire| issuer| SSL certificate verify)'
* Connected to myapp.lab.internal (10.200.0.20) port 443 * SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384 / X25519MLKEM768 / id-ecPublicKey * ALPN: server did not agree on a protocol. Uses default. * Server certificate: * subject: CN=myapp.lab.internal * expire date: Feb 16 09:30:12 2027 GMT * issuer: O=Linux Lab; CN=Linux Lab Issuing CA 1 * SSL certificate verify ok.
The format of curl’s -v output varies by version; use the actual output as the reference.
Lab 8: TLS Fault Injection and Diagnostics (approximately 10 minutes)
gen runs as a regular user; start/stop require sudo):
cat > ~/linuxlab/net8/tlsfault.sh <<'EOF'
#!/usr/bin/env bash
# TLS 故障注入:服务端运行在 blue 命名空间 10.200.0.20:443
set -euo pipefail
PKI=${PKI:-/home/${SUDO_USER:-$USER}/linuxlab/pki}; F=$PKI/faults
gen() { # 生成故障证书(普通用户运行)
cd "$PKI"; mkdir -p faults
mk() { openssl req -new -newkey ec -pkeyopt ec_paramgen_curve:P-256 -noenc -keyout faults/$1.key \
-subj "/CN=$2" -addext "subjectAltName=DNS:$2" -out faults/$1.csr 2>/dev/null; }
sign() { openssl ca -config openssl.cnf -name CA_int -batch -notext -extensions server_cert "$@" 2>/dev/null; }
mk expired myapp.lab.internal; sign -startdate 20250101000000Z -enddate 20250401000000Z -in faults/expired.csr -out faults/expired.crt
mk future myapp.lab.internal; sign -startdate 20270601000000Z -enddate 20270901000000Z -in faults/future.csr -out faults/future.crt
mk wrongname other.lab.internal; sign -in faults/wrongname.csr -out faults/wrongname.crt
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -noenc -days 30 -keyout faults/self.key \
-subj "/CN=myapp.lab.internal" -addext "subjectAltName=DNS:myapp.lab.internal" -out faults/self.crt 2>/dev/null
echo "已生成:$(ls faults/*.crt | xargs -n1 basename | tr '\n' ' ')"
}
stop() { ip netns pids blue | xargs -r kill 2>/dev/null || true; ip link set v-blue-eth0 mtu 1500; }
srv() { ip netns exec blue openssl s_server -accept 443 -www -quiet "$@" >/dev/null 2>&1 & }
start() {
stop; C="-cert_chain $PKI/int/certs/int.crt"
case "$1" in
ok) srv -cert $PKI/myapp.crt -key $PKI/myapp.key $C ;;
nochain) srv -cert $PKI/myapp.crt -key $PKI/myapp.key ;;
expired|future|wrongname) srv -cert $F/$1.crt -key $F/$1.key $C ;;
selfsigned) srv -cert $F/self.crt -key $F/self.key ;;
plain) ip netns exec blue python3 -m http.server 443 --bind 10.200.0.20 >/dev/null 2>&1 & ;;
mtu) srv -cert $PKI/myapp.crt -key $PKI/myapp.key $C; ip link set v-blue-eth0 mtu 1400 ;;
*) echo "故障:ok nochain expired future wrongname selfsigned plain mtu"; exit 2 ;;
esac
sleep 1; echo "已启动:$1(停止:sudo $0 stop)"
}
case "${1:-}" in gen) gen ;; start) [ "$(id -u)" -eq 0 ] || { echo "需要 sudo"; exit 1; }; start "${2:-}" ;;
stop) stop ;; *) echo "用法:$0 gen | sudo $0 start <故障> | sudo $0 stop"; exit 2 ;; esac
EOF
chmod +x ~/linuxlab/net8/tlsfault.sh
~/linuxlab/net8/tlsfault.sh gen
gen adds 3 records to the CA database in module 6 (the expired and future-dated certificates are also recorded; this is normal). The mtu fault sets the MTU of the blue port on the bridge to 1400: frames larger than 1400 are silently dropped at layer 2, and no ICMP is generated.
T=~/linuxlab/net8/tlsfault.sh
for f in nochain expired future wrongname selfsigned plain mtu; do
sudo $T start $f >/dev/null
echo "===== $f"
sudo ip netns exec red curl -sS --max-time 5 -o /dev/null https://myapp.lab.internal/ 2>&1 | head -1
sudo ip netns exec red timeout 6 openssl s_client -connect myapp.lab.internal:443 -servername myapp.lab.internal \
-verify_hostname myapp.lab.internal </dev/null 2>&1 | grep -m2 -E 'verify error|wrong version|errno|Verify return' || echo "(s_client 无输出:握手挂起)"
done
sudo $T stop
===== nochain curl: (60) SSL certificate problem: unable to get local issuer certificate verify error:num=20:unable to get local issuer certificate ===== expired curl: (60) SSL certificate problem: certificate has expired verify error:num=10:certificate has expired ===== future curl: (60) SSL certificate problem: certificate is not yet valid verify error:num=9:certificate is not yet valid ===== wrongname curl: (60) SSL: no alternative certificate subject name matches target host name 'myapp.lab.internal' verify error:num=62:hostname mismatch ===== selfsigned curl: (60) SSL certificate problem: self-signed certificate verify error:num=18:self-signed certificate ===== plain curl: (35) OpenSSL/3.5.5: error:0A00010B:SSL routines::wrong version number 40D7...:error:0A00010B:SSL routines:ssl3_get_record:wrong version number:... ===== mtu curl: (28) SSL connection timeout (s_client 无输出:握手挂起)
sudo ~/linuxlab/net8/tlsfault.sh start mtu sudo ip netns exec red ping -c1 -W1 -M do -s 1372 10.200.0.20 && echo "1400 字节 OK" sudo ip netns exec red ping -c1 -W1 -M do -s 1472 10.200.0.20 || echo "1500 字节失败" ip -d link show v-blue-eth0 | grep -o 'mtu [0-9]*' sudo ~/linuxlab/net8/tlsfault.sh stop
The client is placed in red: both red and blue have an MTU of 1500, and the MSS negotiated by both sides is 1460, but the bridge port in the middle has an MTU of only 1400—this is precisely the “path MTU smaller than the endpoint MTU with no ICMP” black hole. (The behavior is different when testing from the host: the bridge device automatically lowers its own MTU to the minimum port value of 1400, so the host advertises a smaller MSS and can communicate instead.) Why does the TCP handshake succeed while TLS hangs? The SYN is small; the ServerHello + certificate chain sent by the server exceeds 1400 bytes, is dropped, and is repeatedly retransmitted. Fix: standardize the MTU, or perform MSS clamping at the routing egress (Lesson 7, M5, Case 3).
| Fault | Root Cause | Remediation |
|---|---|---|
| nochain | Only the leaf certificate was sent | Configure the full chain (-cert_chain / nginx's fullchain.pem) |
| expired | Certificate expired | Renew and reload; establish monitoring (M7) |
| future | notBefore is in the future (or the client clock is slow) | Check timedatectl; reissue |
| wrongname | SAN does not include the access name | Reissue a certificate containing the correct SAN |
| selfsigned | Not issued by a trusted CA | Use a private CA to issue it; or explicitly add the certificate to the client's trust store (not recommended) |
| plain | Plaintext HTTP is running on the port | Correct the port / protocol |
| mtu | Path MTU mismatch; large packets are silently dropped | Standardize the MTU / MSS clamping |
sudo ~/linuxlab/net8/tlsfault.sh stop (the fault certificates are retained in ~/linuxlab/pki/faults/ and will be deleted together after the comprehensive lab).Case 1: Only Some Users Report Certificate Errors
Problem: Approximately 1/4 of requests report certificate errors. Approach: Run curl --resolve H:443:Node IP separately against the 4 nodes behind the load balancer; one of them failed to install the intermediate certificate during rotation. Improvement: Change certificate deployment to unified distribution through configuration management (Ansible course), and probe each node.
Case 2: All HTTPS Calls Fail on a Virtual Machine Restored from a Snapshot
Problem: apt and curl both report certificate is not yet valid. Approach: timedatectl showed that the system time was stuck at the snapshot time (three months earlier), and NTP had not synchronized because of the firewall. Remediation: Allow NTP and run chronyc makestep. Lesson: A certificate error is not necessarily a certificate problem.
Case 3: VPN Users' Access to Internal HTTPS Keeps Spinning
Problem: VPN users can ping the internal site normally, but the webpage keeps loading. Approach: curl -v stopped after TLSv1.3 (OUT), TLS handshake, Client hello; ping -M do -s 1372 worked, while -s 1472 did not. Remediation: Configure MSS clamping on the VPN gateway for the tunnel interface.
Interactive Troubleshooting Tree: HTTPS / mTLS Access Failure
Starting from the observed symptoms, answer the questions step by step; the troubleshooting tree provides diagnoses and commands.
Additional Note: Easily Misread Error Messages
verify error:num=19:self-signed certificate in certificate chain
Cause: An untrusted self-signed root appeared in the chain (the server sent the private root along with the rest, but the client does not trust that root; or the TLS inspection proxy's root is not installed).
openssl s_client -connect H:443 -servername H -showcerts </dev/null 2>/dev/null | grep -E '^ *[0-9] s:|^ *i:'
Remediation: Add that root to the client's trust store (confirm that it is indeed a CA you trust).
tlsv1 alert unknown ca / SSL alert number 48
Cause: This is an alert sent by the peer: in mTLS, the server does not trust the issuer of your client certificate, or the client does not trust the server certificate (depending on which side printed it).
Remediation: Verify the CA in ssl_client_certificate against the issuer of the client certificate.
tlsv13 alert certificate required / SSL alert number 116
Cause: The TLS 1.3 server requires a client certificate, but the client did not provide one (behavior varies by server implementation: nginx completes the handshake and returns HTTP 400).
Remediation: Provide --cert/--key; confirm that the client certificate's EKU contains clientAuth.
sslv3 alert handshake failure (without SNI)
Cause: The server (or CDN) provides certificates only for known SNI values and has no default certificate; it is also possible that the two sides have no protocol version / cipher suite in common.
openssl s_client -connect IP:443 -servername H -brief </dev/null openssl s_client -connect H:443 -tls1_2 -brief </dev/null
1. For the three nodes behind the load balancer (10.0.0.11–13), check the expiration date and serial number of the www.example.com certificate on each node.
for ip in 10.0.0.11 10.0.0.12 10.0.0.13; do
printf '%s ' "$ip"; openssl s_client -connect $ip:443 -servername www.example.com </dev/null 2>/dev/null \
| openssl x509 -noout -enddate -serial | tr '\n' ' '; echo
done2. Check the subject and issuer of the certificate on a PostgreSQL server (5432, STARTTLS).
openssl s_client -connect db.lab.internal:5432 -starttls postgres </dev/null 2>/dev/null | openssl x509 -noout -subject -issuer
On Monday morning, monitoring shows that all internal API calls are failing with certificate has expired, but Operations confirms that the leaf certificate will not expire for another 60 days. List three areas you would check and the commands you would use.
① Other certificates in the chain: use s_client -showcerts to view each certificate’s v:NotAfter—the intermediate CA or an old cross-signed root may have expired (for example, an old cross-signed chain). ② Client clock: use timedatectl and chronyc tracking; a clock that is fast can make a certificate appear to have “expired early.” ③ It is not the same certificate: some load-balancer nodes, the default SNI certificate, or a TLS inspection proxy may be presenting an expired certificate—use --resolve to check each node individually and check the issuer. Also confirm whether the client’s trust store contains only the expired old root (which requires updating ca-certificates).
Verified Instructional Video
For the featured video “Hands-On Troubleshooting with openssl s_client”: no verified video found. Use the official documentation and the storyboard below as the reference.
Official Documentation
- openssl-s_client(1) · openssl-verification-options(1) (error codes and verification options)
- libcurl error codes · curl: SSL certificate verification
- RFC 8446 Section 6: Alert Protocol
Video Storyboard Script (approximately 90 seconds)
This courseware cannot directly generate video/MP3 files; a storyboard and narration script are provided.
Visual: An HTTPS request passes through seven gates: DNS, TCP, negotiation, chain, name, time, and application, with each gate displaying its characteristic error sign.
Voice-over: First determine which gate it is stuck at, then apply the appropriate remedy.
Visual: The s_client output in the terminal is highlighted: certificate 0 and certificate 1, each certificate’s validity period, and the final Verify return code.
Voice-over: A single s_client command shows which certificates the server sent and which one has a problem.
Visual: The TLS handshake stalls, and a large packet is blocked at a narrow gate (MTU 1400); a smaller packet passes through successfully.
Narration: A stalled handshake isn’t necessarily TLS’s fault. Large packets being silently dropped along the path can also cause HTTPS to spin.
Command Quick Reference
ip netns add red; ip netns list; ip netns del red ip link add v-red type veth peer name eth0 netns red ip link add br0 type bridge; ip link set v-red master br0 up ip -n red addr add 10.200.0.10/24 dev eth0 ip -n red link set eth0 up; ip -n red route add default via 10.200.0.1 ip netns exec red ss -ltn # 在命名空间里执行任意命令 nsenter -t PID -n ip addr # 进入进程(容器)的网络命名空间 bridge fdb show br br0; bridge vlan show ip link add link eth0 name eth0.100 type vlan id 100
ip route get 1.1.1.1 from 10.200.0.10 iif br-lab ip rule add from 10.201.0.30 table 201 priority 1000 ip route add default via 10.201.0.1 dev eth1 table 201 ip route show table all | grep table sysctl -w net.ipv4.ip_forward=1 nft add rule ip nat postrouting oifname "eth0" masquerade nft add rule ip nat prerouting tcp dport 8080 dnat to 10.200.0.20:80 conntrack -L --dst-nat; conntrack -D -p tcp --orig-port-dst 8080 nft monitor trace # 配合 meta nftrace set 1
ip -s -s link; ethtool -S IF; ethtool -g IF; ethtool -l IF cat /proc/net/softnet_stat # 第 2 列丢弃,第 3 列 squeeze ss -ltn 'sport = :5000' # LISTEN:Recv-Q 当前 / Send-Q 上限 ss -tni dst 10.200.0.20 # rtt cwnd retrans bbr/cubic ss -s; ss -tan state time-wait | wc -l nstat -az TcpExtListenOverflows TcpExtListenDrops sysctl net.core.somaxconn net.ipv4.ip_local_port_range net.ipv4.tcp_tw_reuse modprobe tcp_bbr; sysctl -w net.ipv4.tcp_congestion_control=bbr
openssl s_client -connect H:443 -servername H -brief </dev/null
openssl s_client -connect H:443 -servername H -showcerts -verify_return_error </dev/null
openssl s_client -connect H:443 -tls1_3 -alpn h2 </dev/null
openssl x509 -in c.pem -noout -subject -issuer -dates -ext subjectAltName
openssl x509 -in c.pem -noout -checkend $((21*86400))
openssl verify -CAfile root.crt -untrusted int.crt -verify_hostname H leaf.crt
curl -v --resolve H:443:IP https://H/
curl -w 'tls=%{time_appconnect}\n' -o /dev/null -s https://H/openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out k.key openssl req -new -key k.key -subj "/CN=h" -addext "subjectAltName=DNS:h,IP:10.0.0.1" -out h.csr openssl ca -config openssl.cnf -name CA_int -extensions server_cert -batch -notext -in h.csr -out h.crt openssl ca -config openssl.cnf -name CA_int -revoke h.crt -crl_reason keyCompromise openssl ca -config openssl.cnf -name CA_int -gencrl -out int.crl openssl crl -in int.crl -noout -text diff <(openssl x509 -in h.crt -noout -pubkey) <(openssl pkey -in k.key -pubout)
# Ubuntu cp root.crt /usr/local/share/ca-certificates/my-root.crt && update-ca-certificates # RHEL / Rocky / Alma cp root.crt /etc/pki/ca-trust/source/anchors/ && update-ca-trust certbot certonly --staging --webroot -w /var/www/html -d H --deploy-hook "systemctl reload nginx" certbot renew --dry-run; certbot certificates nginx -t && systemctl reload nginx # mTLS:ssl_client_certificate ca-chain.crt; ssl_verify_client on; ssl_crl crl.pem;
Key Figures
| Item | Value (verified on 2026-11-18) |
|---|---|
| Maximum validity period for public TLS certificates (CA/B BR 2.3.1) | 200 days (from 2026-03-15) → 100 days (2027-03-15) → 47 days (2029-03-15) |
| Let's Encrypt default certificates | 90 days → 64 days (2027-02-10) → 45 days (2028-02-16); shortlived approximately 6 days |
| Let's Encrypt discontinuation of OCSP / reminder emails / clientAuth | OCSP service shut down on 2025-08-06; reminder emails discontinued on 2025-06-04; clientAuth EKU removed by default from 2026-02-11 (tlsclient configuration file discontinued on 2026-07-08) |
| TCP defaults (Linux 7.0) | somaxconn 4096; port range 32768–60999; TIME_WAIT 60 seconds; keepalive 7200/75/9; tcp_tw_reuse=2; congestion control cubic |
| OpenSSL | Ubuntu 26.04: 3.5.5 (3.5 is LTS, through 2030-04); latest upstream 4.1.0 (2026-10-23) |
Comprehensive Lab + Final Exam
gw.lab.internal (host 10.200.0.1:9443). You need to: issue a gateway certificate and a client certificate, configure the gateway, verify access control, handle a certificate compromise (revocation), complete a certificate rotation without interruption, and diagnose a network failure “conveniently” caused by an operations colleague.cd ~/linuxlab/net8 && sudo ./topo.sh status | head -3 ls ~/linuxlab/pki/root/certs/root.crt ~/linuxlab/pki/int/certs/int.crt echo "10.200.0.1 gw.lab.internal" | sudo tee -a /etc/hosts
cd ~/linuxlab/pki openssl req -new -newkey ec -pkeyopt ec_paramgen_curve:P-256 -noenc -keyout gw.key -subj "/CN=gw.lab.internal" \ -addext "subjectAltName=DNS:gw.lab.internal,IP:10.200.0.1" -out gw.csr openssl ca -config openssl.cnf -name CA_int -batch -notext -extensions server_cert -in gw.csr -out gw.crt cat gw.crt int/certs/int.crt > gw-fullchain.crt openssl req -new -newkey ec -pkeyopt ec_paramgen_curve:P-256 -noenc -keyout orders.key -subj "/CN=orders" -out orders.csr openssl ca -config openssl.cnf -name CA_int -batch -notext -extensions client_cert -days 30 -in orders.csr -out orders.crt
/etc/nginx/sites-available/gw-mtls: listen 10.200.0.1:9443 ssl;, server_name gw.lab.internal;, and change the certificates to gw-fullchain.crt / gw.key (install them in /etc/nginx/pki/). Keep the other mTLS directives unchanged, and additionally record $ssl_client_s_dn in access_log:
log_format mtls '$remote_addr "$ssl_client_s_dn" $ssl_client_verify "$request" $status';
# 放在 http{} 级别(例如 /etc/nginx/conf.d/mtls-log.conf),然后在 server{} 中:
access_log /var/log/nginx/gw-access.log mtls;
sudo nginx -t && sudo systemctl reload nginx sudo ss -ltnp 'sport = :9443'
P=~/linuxlab/pki; U=https://gw.lab.internal:9443/healthz
sudo ip netns exec red curl -sS -o /dev/null -w '%{http_code}\n' $U # 期望 400
sudo ip netns exec red curl -sS --cert $P/orders.crt --key $P/orders.key $U; echo # 期望 200
sudo ip netns exec red curl -sS -o /dev/null -w '%{http_code}\n' --cert $P/bob.crt --key $P/bob.key $U # 期望 400(已吊销)
sudo tail -n 3 /var/log/nginx/gw-access.logcd ~/linuxlab/pki openssl ca -config openssl.cnf -name CA_int -revoke orders.crt -crl_reason keyCompromise openssl ca -config openssl.cnf -name CA_int -gencrl -out int/crl/int.crl cat int/crl/int.crl root/crl/root.crl | sudo tee /etc/nginx/pki/crl.pem >/dev/null sudo systemctl reload nginx # 重新为 orders 生成新私钥与证书(文件名 orders2),再从 red 验证旧证书 400、新证书 200
Consider: What happens if root.crl has already expired? (Hint: the CRL has expired troubleshooting page in Module 7)
nginx -t, and reload; before and after the rotation, run openssl s_client ... | openssl x509 -noout -serial once each, while also running a loop in red that makes one request every 0.2 seconds, confirming that there are no failed requests during the rotation.
sudo ip netns exec red bash -c 'for i in $(seq 100); do curl -s -o /dev/null -w "%{http_code} " --cert '"$P"'/orders2.crt --key '"$P"'/orders2.key https://gw.lab.internal:9443/healthz; sleep 0.2; done; echo' &sudo ip link set v-red-eth0 mtu 1280
Symptom: when orders calls the gateway, it “spins indefinitely,” while ping works normally. Diagnose it using the methods from Module 8: Where does curl -v stop? What is the critical size for ping -M do? After fixing it, recheck with certcheck and curl.
sudo ip link set v-red-eth0 mtu 1500
~/linuxlab/net8/certcheck.sh 21 127.0.0.1:8443/myapp.lab.internal 10.200.0.1:9443/gw.lab.internal
# —— 完全清理(课程结束后执行;第 9 课不依赖这些资源)——
sudo rm -f /etc/nginx/sites-enabled/{myapp-mtls,gw-mtls} /etc/nginx/sites-available/{myapp-mtls,gw-mtls} /etc/nginx/conf.d/mtls-log.conf
sudo rm -rf /etc/nginx/pki && sudo nginx -t && sudo systemctl reload nginx
sudo systemctl disable --now certcheck.timer; sudo rm -f /etc/systemd/system/certcheck.{service,timer}; sudo systemctl daemon-reload
sudo rm -f /usr/local/share/ca-certificates/linuxlab-root-ca.crt && sudo update-ca-certificates --fresh
sudo sed -i '/lab\.internal/d' /etc/hosts
sudo ~/linuxlab/net8/tlsfault.sh stop 2>/dev/null; sudo ~/linuxlab/net8/topo.sh down
rm -rf ~/linuxlab/pki # 如需保留私有 CA 供以后练习,请跳过这一行Open-Ended Self-Test (6 Questions)
1. In one sentence each, explain the roles of veth, bridge, network namespaces, and MASQUERADE in Docker's default network.
A network namespace gives each container an independent network stack; veth is the network cable that connects the container (one end is called eth0 inside the container); the bridge (docker0) is the switch that connects all containers and serves as their gateway; MASQUERADE changes the container's private source address to the host address at the exit, and conntrack restores it on the return path.
2. Why is DNAT in PREROUTING and SNAT in POSTROUTING? What happens if DNAT is placed after routing?
DNAT changes the destination address and must be completed before the routing decision so that the kernel can route according to the new destination (for example, forwarding the packet to the backend instead of delivering it to the local machine). SNAT changes the source address and needs to be performed after the output interface has been determined so that the correct outgoing address can be selected. If the destination address is changed after routing, the packet has already been routed according to the old destination and will be sent to the wrong place.
3. The server's ss -ltn shows Recv-Q 129 and Send-Q 128. What does this indicate? What should you do next?
The accept queue is full (the limit is 128; the kernel considers it an overflow only when the length exceeds the limit, so 129 may be displayed). The SYN or final ACK of new connections will be dropped, causing clients to experience retransmission delays of 1 s / 3 s. Next: use nstat -az TcpExtListenOverflows to confirm that the count is increasing, and check whether the application is stuck or lacks workers; backlog 128 may be the application's default value (nginx or certain frameworks). The backlog can be increased, but the default somaxconn of 4096 is not the bottleneck.
4. What role does the certificate play in the TLS 1.3 handshake? If the server's private key is compromised, can previously recorded traffic be decrypted?
The certificate and CertificateVerify are used only to prove the server's identity; the session key comes from the (EC)DHE ephemeral key exchange. Because the ephemeral private key is discarded after use, TLS 1.3 provides forward secrecy: compromising the private key does not allow previously recorded traffic to be decrypted (but an attacker can impersonate the server, so the certificate must be revoked and replaced). In TLS 1.2, forward secrecy is not provided when RSA key transport is used.
5. Your private CA's intermediate certificate will expire in 6 months. Write out the rotation steps.
① Use the root CA to issue a new intermediate CA (with a new key and either the same name but a different SKID, or rename it to Issuing CA 2); ② add the new intermediate certificate to the fullchain configuration templates on all servers and to the mTLS gateway's ssl_client_certificate (keep the old and new certificates in place concurrently), and publish the new intermediate CA's CRL; ③ switch issuance: issue all new certificates from the new intermediate CA; ④ wait until all certificates issued by the old intermediate naturally expire or have been rotated early; ⑤ remove the old intermediate from the trust configuration and stop publishing its CRL (or publish a final CRL). Monitor the expiration time of every level in the chain throughout the process.
6. Why is the validity period of public CA certificates getting shorter? What does this mean for operations teams?
Revocation mechanisms (OCSP and CRL) are unreliable in practice and raise privacy concerns. Shorter validity periods can limit the time window for the impact of private-key compromise and misissuance, while driving comprehensive automation and cryptographic agility. This means that all certificates must be requested, deployed, and reloaded automatically; use ARI or renew at 2/3 of the validity period; establish independent expiration monitoring; eliminate systems that “require certificates to be uploaded manually”; and ensure DNS-01 credentials have least privilege.
Sources and Version Notes
Sources and Verification Conclusions
| Topic | Verification Conclusion | Sources (accessed 2026-11-18) |
|---|---|---|
| Ubuntu 26.04 packages | openssl 3.5.5-1ubuntu3.7, nftables 1.1.6-1, nginx 1.28.3-2ubuntu1.12, certbot 4.0.0-4 (universe); iproute2 6.19, conntrack 1.4.9, and kernel 7.0 retain the verification results from Lesson 7 | packages.ubuntu.com/resolute |
| OpenSSL versions | 4.1.0 (2026-10-23, supported until 2027-11-23), 4.0.3 (2026-09-29), 3.5.9 LTS (supported until 2030-04-08) | openssl-library.org/source |
| Default TLS groups in OpenSSL 3.5 | The default keyshare is X25519MLKEM768 and X25519, with hybrid PQC groups preferred; the default encryption algorithm for req and others has changed to aes-256-cbc | OpenSSL 3.5 NEWS |
| Certificate validity period schedule | BR 2.3.1 (2026-10-04): 200 days from 2026-03-15, 100 days from 2027-03-15, and 47 days from 2029-03-15; the domain validation reuse period is reduced from 200 to 100 to 10 days | CA/B Forum Baseline Requirements |
| Let's Encrypt 45-day plan | 2026-05-13: tlsserver, 45 days; 2027-02-10: classic, 64 days, authorization reuse, 10 days; 2028-02-16: classic, 45 days, reuse, 7 hours; without ARI, renew at approximately 2/3 of the validity period | letsencrypt.org |
| Let's Encrypt OCSP | Certificates have not included an OCSP URL since 2025-05-07; the OCSP service was shut down on 2025-08-06, leaving only CRL | OCSP Service Has Reached End of Life |
| Let's Encrypt clientAuth | On 2026-02-11, the default configuration file removed the clientAuth EKU; the tlsclient configuration file was extended and then disabled on 2026-07-08; based on the Chrome Root Program's June 2026 split requirement | Ending TLS Client Authentication Certificate Support |
| Let's Encrypt reminder emails | Expiration reminder emails were discontinued on 2025-06-04 | Expiration Notification Service Has Ended |
| certbot | Upstream 5.10.0 (2026-11-10); ARI support 4.1.0 (2025-06-10); --preferred-profile / --required-profile 4.0.0; --ip-address 5.3.0 | certbot CHANGELOG |
| ACME / ARI | RFC 8555; ARI is RFC 9773 (2025-06) | RFC 9773 |
| TLS、X.509 | TLS 1.3 message sequence and 5 cipher suites; certificate path validation and CRL | RFC 8446;RFC 5280 |
| Kernel network parameters | Semantics and default values of somaxconn, tcp_tw_reuse, ip_local_port_range, keepalive, and rp_filter | ip-sysctl;scaling |
| iproute2 / nftables / conntrack | ip-netns, ip-rule, bridge, nft NAT, and conntrack options | man7.org;nftables wiki |
Video verification notes
All videos were verified for their titles and channels through YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json) on 2026-11-18:
| Video ID | Title | Channel | Used for |
|---|---|---|---|
| fhBHvsi0Ql0 | LISA19 - Linux Systems Performance | USENIX | M1、M4 |
| _WgUwUf1d34 | Introduction to Linux Network Namespaces | David Mahler | M2 |
| 6v_BDHIgOY8 | Container Networking From Scratch - Kristen Jacobs, Oracle | CNCF [Cloud Native Computing Foundation] | M2、M3 |
| 0TLDTodL7Lc | Transport Layer Security (TLS) - Computerphile | Computerphile | M5 |
| j9QmMEWmcfo | SSL, TLS, HTTPS Explained | ByteByteGo | M5 |
| cuR05y_2Gxc | Breaking Down the TLS Handshake | F5 DevCentral Community | M5、M8 |
| sEkw8ZcxtFk | SSL/TLS handshake Protocol | Sunny Classroom | M5 |
| T4Df5_cojAs | How does HTTPS work? What's a CA? What's a self-signed Certificate? | kubucation | M6 |
| qXLD2UHq2vk | Intro to Digital Certificates | Dave Crabbe | M6 |
| GSIDS_lvRv4 | Public Key Cryptography - Computerphile | Computerphile | M6 |
| 4nGrOpo0Cuc | SSL TLS HTTPS process explained in 7 minutes | Johannes Bickel | M7 |
No verified topical videos were found for NAPI / sk_buff, policy routing, TCP queues and BBR, ACME and certbot, mTLS, s_client troubleshooting, or related topics. Storyboard scripts have been provided in the corresponding “Videos” tabs. Videos from small third-party channels are supplementary only; this lesson and the official documentation take precedence.
Voice-over notes
The “Voice” tab uses the browser's built-in Web Speech API (speechSynthesis, zh-CN voice) to read the lesson script aloud in real time; English terms are read using an en-US voice. This courseware cannot embed or generate MP3 files; when audio is needed, the script can be provided to any TTS tool.
Known limitations
- The commands in this lesson were not executed individually on a physical Ubuntu 26.04 system; all output is illustrative. MAC addresses, interface numbers, serial numbers, dates, counter values, and network interface names (ens3 / enp0s1 / eth0) depend on the actual environment.
- The original error messages from curl, OpenSSL, nginx, certbot, and resolvectl come from upstream documentation and common versions and were not verified verbatim on 26.04 (the text indicates that actual results may vary); the output format of
-vin curl 8.x varies by version. - Ubuntu's default
rp_filter=2, the specific value oftcp_max_syn_backlog,default_qdiscbeing fq_codel, and the name of the nstat counter that records packet drops after disablingip_forwardwere not verified on a physical 26.04 system. ssl_crlin nginx requires a CRL for every CA in the certificate chain. The log level for client certificate verification failures isinfo. These points are based on nginx source code behavior and common experience; they have not been tested on version 1.28.3.- Idle timeouts for cloud load balancers (4 minutes for Azure LB, 350 seconds for AWS NLB) are common platform defaults; refer to the platform documentation. The progress of ECH standardization and deployment, and the BBR version in the mainline kernel, have not been individually verified.
- The optional ACME exercise requires a public domain name; no certificate was actually requested for this course material. Refer to the official documentation for Let's Encrypt rate-limit values and error messages.
- WSL2 networking namespace, bridging, and kernel module behavior differ from those of virtual machines. Please use Multipass / Hyper-V / VirtualBox.