Các giao thức cốt lõiCore Protocols
Thuộc bộ kiến thức Network Engineer Roadmap.
Tổng quan
Một protocol (giao thức) là tập hợp các quy tắc được thống nhất, cho phép hai hoặc nhiều bên trao đổi thông tin một cách đáng tin cậy. Nó định nghĩa syntax (định dạng thông điệp — các bit, field, dấu phân cách), semantics (ý nghĩa của mỗi thông điệp và hành động nó kích hoạt), và timing (thứ tự thông điệp và cách các bên phản ứng với mất mát, độ trễ, lỗi). Không có protocol, hai máy từ hai hãng khác nhau thậm chí không thể thống nhất một thông điệp kết thúc ở đâu.
Phần lớn các protocol mà một network engineer làm việc hằng ngày là application-layer protocol: DNS, DHCP, HTTP, TLS, SSH, SMTP, NTP, SNMP, v.v. Chúng không nói chuyện trực tiếp với đường truyền vật lý. Thay vào đó chúng chạy phía trên một transport protocol — gần như luôn là TCP hoặc UDP (xem ./03-network-models-and-layers.md để hiểu đầy đủ mô hình phân lớp). Transport layer, đến lượt nó, chạy trên IP (xem ./05-ip-addressing-and-subnetting.md).
Lựa chọn transport quyết định hành vi của application protocol:
| Thuộc tính | TCP | UDP |
|---|---|---|
| Kết nối | Connection-oriented (3-way handshake) | Connectionless |
| Độ tin cậy | Đảm bảo, đúng thứ tự, gửi lại dữ liệu mất | Best-effort, không gửi lại |
| Overhead | Cao hơn (state, ACK, sequence number) | Tối thiểu |
| Flow/congestion control | Có | Không (ứng dụng tự xử lý) |
| Người dùng điển hình | HTTP, TLS, SSH, SMTP, FTP | DNS (query), DHCP, NTP, SNMP, QUIC (trên UDP) |
Nguyên tắc chung: dùng TCP khi mọi byte phải đến đúng thứ tự (trang web, truyền file, phiên shell); dùng UDP khi tốc độ và overhead thấp quan trọng hơn việc giao đủ hoàn hảo, hoặc khi ứng dụng tự cài đặt cơ chế tin cậy (DNS, media real-time, QUIC).
Phần còn lại của ghi chú này đi qua từng protocol cốt lõi: nó giải quyết vấn đề gì, hoạt động trên đường truyền ra sao, dùng port nào, và các lệnh CLI để kiểm tra, troubleshoot.
Kiến thức nền tảng
Application protocol phân lớp trên TCP/UDP
Hãy hình dung một request tải https://example.com như một chồng protocol phối hợp với nhau:
- DHCP đã cấp cho host của bạn một IP address, gateway và DNS server khi nó gia nhập mạng.
- DNS biến
example.comthành một IP address (qua UDP/53, hoặc TCP với câu trả lời lớn). - TCP mở một kết nối tin cậy tới IP đó ở port 443 (hoặc QUIC trên UDP/443 cho HTTP/3).
- TLS thương lượng mã hóa phía trên TCP để phiên trao đổi được riêng tư và xác thực.
- HTTP mang request thực sự (
GET /) và response bên trong tunnel TLS.
Mỗi lớp độc lập: HTTP không quan tâm có TLS hay không, và TLS không quan tâm nó mang dữ liệu ứng dụng loại gì. Chính sự tách biệt này cho phép cùng một thư viện TLS bảo vệ được cả HTTP, SMTP lẫn IMAP.
Port và socket
Một port ở transport layer (0–65535) xác định packet thuộc về ứng dụng nào trên host. Một socket là tổ hợp (IP address, port, protocol). Well-known port (0–1023) dành cho các dịch vụ chuẩn (53 DNS, 80 HTTP, 443 HTTPS, 22 SSH). Registered và ephemeral port (1024–65535) dùng cho client và dịch vụ tùy chỉnh. Khi bạn gõ curl https://example.com, OS chọn một source port ephemeral ngẫu nhiên và kết nối tới destination port 443.
Khái niệm chính
DHCP — Dynamic Host Configuration Protocol
DHCP tự động phát cấu hình IP cho các host để không ai phải cấu hình địa chỉ thủ công. Nó chạy trên UDP, client ở port 68 và server ở port 67. Một client mới và một server chưa từng “nói chuyện” hoàn tất phiên trao đổi DORA:
| Bước | Thông điệp | Hướng | Mục đích |
|---|---|---|---|
| D | DHCPDISCOVER | Client → broadcast | ”Có DHCP server nào ngoài kia không?” |
| O | DHCPOFFER | Server → client | ”Đây là một địa chỉ bạn có thể dùng.” |
| R | DHCPREQUEST | Client → broadcast | ”Tôi nhận offer đó.” (broadcast để các server khác rút offer của họ) |
| A | DHCPACK | Server → client | ”Xác nhận, lease là của bạn.” |
Các ý chính:
- Lease — một địa chỉ được cấp trong một khoảng lease time hữu hạn. Client cố renew ở mốc 50% lease (T1, unicast tới server) và rebind ở mốc 87.5% (T2, broadcast tới bất kỳ server nào) nếu server ban đầu đã biến mất.
- Option — bản tin ACK mang nhiều hơn một địa chỉ: subnet mask (option 1), default gateway/router (option 3), DNS server (option 6), domain name (option 15), NTP server (option 42), lease time (option 51) và nhiều nữa.
- DHCP relay (relay agent /
ip helper-address) — DHCP dựa vào broadcast, mà router thì không chuyển tiếp broadcast. Khi server nằm ở subnet khác, một relay agent trên router của client bắt broadcast và unicast nó tới server, chèn thông tin subnet của client (giaddr) để server biết dùng pool nào. - DHCPv6 tồn tại cho IPv6, dù IPv6 còn hỗ trợ stateless address autoconfiguration (SLAAC).
Kiểm tra lease trên Linux bằng ip addr và xem /var/lib/dhcp/dhclient.leases; trên macOS ipconfig getpacket en0 in ra toàn bộ DHCP reply gồm tất cả option.
DNS — Domain Name System
DNS là cơ sở dữ liệu phân tán ánh xạ tên thân thiện với con người (example.com) sang dữ liệu máy (IP address và hơn thế). Nó chạy chủ yếu trên UDP/53 cho query nhỏ và chuyển sang TCP/53 cho response lớn (trên 512 byte khi không có EDNS) và zone transfer.
Luồng resolution (recursive lookup cho www.example.com):
- Stub resolver — OS của client hỏi recursive resolver đã cấu hình (DNS server nhận từ DHCP, ví dụ
8.8.8.8). - Recursive resolver — nếu chưa có trong cache, nó bắt đầu từ trên xuống. Nó hỏi một root server (“
.comở đâu?”). - Root — trả về name server của TLD
.com. - TLD server — trả về name server authoritative của
example.com. - Authoritative server — trả về record A/AAAA thực sự cho
www.example.com. - Resolver cache câu trả lời (tôn trọng TTL) và trả về cho stub.
Stub chỉ thực hiện một query và nhận câu trả lời cuối cùng; recursive resolver mới là bên đi bộ qua toàn bộ hệ thống phân cấp.
Các record type phổ biến:
| Type | Mục đích | Ví dụ giá trị |
|---|---|---|
A | Tên → IPv4 address | 93.184.216.34 |
AAAA | Tên → IPv6 address | 2606:2800:220:1:248:1893:25c8:1946 |
CNAME | Alias → tên chính danh | www → example.com. |
MX | Mail exchanger (kèm priority) | 10 mail.example.com. |
TXT | Text tùy ý (SPF, DKIM, xác minh) | "v=spf1 include:_spf.google.com ~all" |
NS | Ủy quyền một zone cho name server | ns1.example.com. |
SOA | Start of authority — metadata của zone, serial, timer | serial, refresh, retry, expire, minimum |
SRV | Vị trí dịch vụ (host + port) | _sip._tcp → 0 5 5060 sipserver.example.com. |
PTR | Reverse lookup: IP → tên | 34.216.184.93.in-addr.arpa → example.com. |
CAA | CA nào được phép cấp cert cho domain | 0 issue "letsencrypt.org" |
TTL (Time To Live) — mỗi record mang một TTL tính bằng giây, cho resolver biết cache bao lâu. TTL thấp (ví dụ 300s) giúp thay đổi lan truyền nhanh nhưng tăng tải query; TTL cao (ví dụ 86400s) giảm tải nhưng làm chậm failover.
Encrypted DNS — DNS cổ điển là plaintext, nên bên quan sát trên đường truyền có thể thấy và can thiệp lookup. Hai nâng cấp khắc phục điều này:
- DoT (DNS over TLS) — DNS bọc trong TLS trên TCP/853.
- DoH (DNS over HTTPS) — DNS gửi dưới dạng request HTTPS trên TCP/443, không phân biệt được với traffic web thông thường.
Ví dụ dig:
# Tra A record cơ bản
dig example.com A +short
# 93.184.216.34
# Câu trả lời đầy đủ kèm query time, flag và TTL
dig example.com
# Query một resolver cụ thể
dig @1.1.1.1 example.com
# Mail record
dig example.com MX +short
# Trace toàn bộ chuỗi ủy quyền từ root xuống (hiện từng chặng)
dig +trace example.com
# Reverse lookup (PTR)
dig -x 93.184.216.34
# Xem TTL và SOA
dig example.com SOA
# Tương đương nslookup để kiểm tra nhanh
nslookup example.com 8.8.8.8
HTTP & HTTPS — HyperText Transfer Protocol
HTTP là protocol request/response của web. Client gửi một request (method, path, header, body tùy chọn) và server trả về một response (status line, header, body). HTTP thường dùng TCP/80; HTTPS là HTTP bên trong tunnel TLS trên TCP/443.
Method:
| Method | Ý nghĩa | Safe? | Idempotent? |
|---|---|---|---|
GET | Lấy một resource | Có | Có |
HEAD | Như GET nhưng chỉ header | Có | Có |
POST | Gửi dữ liệu / tạo mới | Không | Không |
PUT | Thay thế một resource | Không | Có |
PATCH | Cập nhật một phần | Không | Không |
DELETE | Xóa một resource | Không | Có |
OPTIONS | Hỏi method nào được phép (CORS preflight) | Có | Có |
Nhóm status code:
| Nhóm | Ý nghĩa | Ví dụ |
|---|---|---|
1xx | Informational | 101 Switching Protocols |
2xx | Success | 200 OK, 201 Created, 204 No Content |
3xx | Redirection | 301 Moved Permanently, 302 Found, 304 Not Modified |
4xx | Lỗi client | 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 429 Too Many Requests |
5xx | Lỗi server | 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout |
Header quan trọng: Host (site nào trên IP dùng chung), Content-Type, Content-Length, Authorization, Cookie/Set-Cookie, Cache-Control, User-Agent, Accept, Location (cho redirect).
Các phiên bản protocol:
| Phiên bản | Transport | Đặc trưng chính |
|---|---|---|
| HTTP/1.1 | TCP | Mỗi kết nối xử lý một request tại một thời điểm; persistent connection và pipelining (ít dùng); dạng text; head-of-line blocking |
| HTTP/2 | TCP + TLS | Binary framing, multiplex nhiều stream trên một kết nối, nén header (HPACK), server push. Vẫn dính head-of-line blocking ở tầng TCP |
| HTTP/3 | QUIC trên UDP/443 | Multiplex không bị TCP head-of-line blocking (stream độc lập), tích hợp sẵn TLS 1.3, thiết lập kết nối nhanh hơn (0-RTT), connection migration khi IP đổi |
HTTP/2 chi tiết
HTTP/2 (RFC 9113, ban đầu là RFC 7540, phát triển từ SPDY của Google) giữ nguyên ngữ nghĩa của HTTP — vẫn cùng bộ method, status code và header — nhưng thay đổi hoàn toàn cách dữ liệu được truyền trên đường dây:
- Binary framing layer. Thay vì các message dạng text, phân tách theo dòng như HTTP/1.1, HTTP/2 chia mỗi message thành các frame nhị phân (HEADERS, DATA, SETTINGS…). Frame dễ parse chính xác và là đơn vị mà cơ chế multiplexing hoạt động trên đó.
- Multiplexing trên một kết nối. Nhiều stream (mỗi stream là một cặp request/response độc lập) được đan xen trên một kết nối TCP duy nhất, mỗi stream có một stream ID. Điều này loại bỏ nhu cầu mở 6+ kết nối song song mỗi origin như HTTP/1.1, và xóa bỏ head-of-line blocking ở tầng ứng dụng (một response chậm không còn chặn các response khác trong tầng HTTP).
- Nén header (HPACK, RFC 7541). Header request/response lặp lại rất nhiều (cùng
User-Agent,Cookie… trên mọi request). HPACK nén chúng bằng một dynamic table dùng chung cộng với mã hóa Huffman, giảm mạnh overhead. HPACK được thiết kế để chống lại tấn công CRIME vốn phá được kiểu nén ngây thơ ở tầng TLS. - Ưu tiên stream & flow control. Client có thể khai báo cây phụ thuộc/trọng số để server gửi các resource quan trọng (CSS, phần trên màn hình) trước; flow control theo từng stream và theo kết nối tránh việc bên gửi nhanh làm ngợp bên nhận chậm.
- Server push (thực tế đã bị loại bỏ). Server có thể chủ động gửi trước resource mà client chưa yêu cầu. Nó hiếm khi hữu ích và thường gây lãng phí, nên hầu hết trình duyệt và server đã tắt/gỡ bỏ — hãy dùng
103 Early Hintsvàpreloadthay thế.
Điểm hạn chế — TCP head-of-line blocking. HTTP/2 xóa HoL blocking bên trong tầng HTTP, nhưng mọi stream vẫn đi chung một kết nối TCP. TCP đảm bảo giao byte stream đúng thứ tự, nên nếu chỉ một packet bị mất, TCP sẽ giữ lại dữ liệu của tất cả các stream cho tới khi packet đó được truyền lại — kể cả những stream không thiếu byte nào. Trên đường truyền hay mất gói (mobile, Wi-Fi nghẽn) điều này khiến HTTP/2 nhanh không hơn, thậm chí chậm hơn, so với nhiều kết nối HTTP/1.1. Đây chính là vấn đề mà QUIC/HTTP/3 được sinh ra để giải quyết.
QUIC & HTTP/3 chi tiết
QUIC (RFC 9000) là một transport protocol mới, đa dụng, xây trên nền UDP, còn HTTP/3 (RFC 9114) là HTTP ánh xạ lên QUIC. QUIC do Google tiên phong và được IETF chuẩn hóa; chạy trên UDP là lựa chọn thực dụng — TCP và UDP gần như là hai transport duy nhất mà các middlebox (firewall, NAT) chắc chắn cho đi qua, và việc nâng cấp bản thân TCP gần như bất khả thi vì quá nhiều logic đã nằm trong kernel hệ điều hành và phần cứng mạng. QUIC nằm trong user space nên có thể tiến hóa nhanh.
Vì sao QUIC quan trọng:
- Không còn head-of-line blocking ở tầng transport. QUIC hiện thực stream ngay trong transport. Mỗi stream được giao độc lập, nên một packet bị mất chỉ làm nghẽn (các) stream chứa byte của nó — các stream khác vẫn chảy bình thường. Điều này cuối cùng mới hiện thực đúng cái multiplexing mà HTTP/2 hứa hẹn, kể cả trên mạng hay mất gói.
- Mã hóa tích hợp sẵn (TLS 1.3). QUIC tích hợp TLS 1.3 trực tiếp thay vì xếp TLS lên trên một transport riêng. Không có QUIC không mã hóa — ngay cả transport header phần lớn cũng được mã hóa/xác thực, đồng thời giảm hiện tượng ossification do middlebox.
- Thiết lập kết nối nhanh hơn. Một phiên HTTPS cổ điển cần TCP handshake (1 RTT) rồi TLS handshake (1 RTT). QUIC gộp thiết lập transport và mã hóa vào 1 RTT duy nhất, và hỗ trợ 0-RTT khi client quay lại có thể gửi dữ liệu request ngay trong packet đầu tiên (kèm lưu ý an toàn replay của 0-RTT — chỉ dùng cho request idempotent).
- Connection migration. Một kết nối QUIC được định danh bằng Connection ID, không phải bộ 4-tuple IP/port. Khi điện thoại chuyển từ Wi-Fi sang mạng di động (IP đổi), kết nối vẫn sống thay vì đứt — lợi thế lớn cho mobile.
- Loss recovery & congestion control hiện đại. QUIC dùng packet number tăng đơn điệu (không còn mập mờ retransmission như TCP), ACK range tường minh, và congestion control cắm-thay được (CUBIC, BBR…).
Đánh đổi & lưu ý vận hành. QUIC tốn CPU hơn TCP (mã hóa từng packet, xử lý ở user space) và vì là UDP nên một số mạng hạn chế sẽ throttle hoặc chặn UDP/443 — khi đó client fallback về HTTP/2 trên TCP. HTTP/3 được quảng bá qua header Alt-Svc (hoặc bản ghi DNS HTTPS/SVCB), nên lần truy cập đầu thường qua HTTP/2 rồi các kết nối sau mới nâng lên HTTP/3.
| Thuộc tính | HTTP/1.1 | HTTP/2 | HTTP/3 |
|---|---|---|---|
| Transport | TCP | TCP | QUIC (UDP) |
| Định dạng wire | Text | Binary frame | Binary frame |
| Multiplexing | Không (nhiều conn song song) | Có (một conn) | Có (một conn) |
| Head-of-line blocking | App + TCP | Chỉ TCP | Không |
| Nén header | Không (chỉ nén body qua gzip) | HPACK | QPACK |
| Mã hóa | Tùy chọn (qua TLS) | Gần như bắt buộc | Tích hợp sẵn (TLS 1.3) |
| Số RTT handshake (kèm TLS) | 2–3 | 2–3 | 1 (0 khi resume) |
| Connection migration | Không | Không | Có (Connection ID) |
Vòng đời request với curl -v https://example.com:
- DNS resolve
example.com. - TCP handshake tới port 443 (hoặc QUIC cho HTTP/3).
- TLS handshake thương lượng mã hóa và xác thực certificate.
- HTTP request được gửi bên trong tunnel TLS.
- Server trả về status, header và body.
- Kết nối được giữ để tái sử dụng hoặc đóng.
# Request chi tiết: hiện DNS, TCP, TLS handshake, header request và response
curl -v https://example.com
# Chỉ header của response
curl -I https://example.com
# Ép một phiên bản HTTP cụ thể
curl --http2 -I https://example.com
curl --http3 -I https://cloudflare.com
# Đi theo redirect và đo thời gian từng pha
curl -L -o /dev/null -s -w "dns:%{time_namelookup} connect:%{time_connect} tls:%{time_appconnect} total:%{time_total}\n" https://example.com
SSL/TLS — Transport Layer Security
TLS (kế thừa hiện đại của SSL, vốn đã bị loại bỏ hoàn toàn) bảo mật một kết nối transport. Nó cung cấp ba đảm bảo:
- Confidentiality (bảo mật) — traffic được mã hóa; bên quan sát trên đường truyền không đọc được.
- Integrity (toàn vẹn) — phát hiện được sự sửa đổi nhờ authenticated encryption (AEAD).
- Authentication (xác thực) — client xác minh danh tính server qua certificate (và tùy chọn server xác minh client, mutual TLS).
TLS handshake (TLS 1.2, đơn giản hóa):
- ClientHello — client gửi các phiên bản TLS hỗ trợ, cipher suite và một số random.
- ServerHello — server chọn phiên bản và cipher, gửi số random và certificate của nó.
- Client xác thực chuỗi certificate, rồi hai bên thực hiện key exchange (ECDHE) để suy ra một session key chung.
- Bản tin Finished xác nhận cả hai bên suy ra cùng key; dữ liệu ứng dụng mã hóa bắt đầu chạy.
Điều này tốn hai round trip trước khi dữ liệu có thể chạy.
TLS 1.3 rút gọn xuống còn một round trip (1-RTT), và hỗ trợ resumption 0-RTT cho lần truy cập lặp lại. Nó loại bỏ toàn bộ các tùy chọn cũ, yếu: chỉ còn key exchange có forward secrecy (ephemeral) và cipher AEAD, bỏ RSA key transport và static Diffie-Hellman, và danh sách cipher suite nhỏ và an toàn hơn nhiều.
| TLS 1.2 | TLS 1.3 | |
|---|---|---|
| Round trip handshake | 2-RTT | 1-RTT (resumption 0-RTT) |
| Cipher suite | Nhiều, một số yếu | Ít, toàn bộ AEAD + forward secrecy |
| Key exchange | RSA hoặc (EC)DHE | Chỉ (EC)DHE |
| Trạng thái | Chấp nhận được | Ưu tiên |
Certificate và chain of trust: server trình một X.509 certificate gắn tên domain của nó với một public key, được ký bởi một Certificate Authority (CA). Thiết bị của bạn tin một tập root CA được OS/browser cài sẵn. Certificate leaf của server thường được ký bởi một CA intermediate, mà intermediate lại được ký bởi một root. Client đi qua chuỗi này từ leaf → intermediate → trusted root; nếu nó kết thúc tại một root đáng tin và không cái nào hết hạn hay bị thu hồi, certificate là hợp lệ.
# Kiểm tra certificate của server và toàn bộ chuỗi
openssl s_client -connect example.com:443 -servername example.com </dev/null
# Hiện protocol và cipher đã thương lượng
openssl s_client -connect example.com:443 -servername example.com </dev/null 2>/dev/null | grep -E "Protocol|Cipher"
# Đọc subject, issuer và ngày hiệu lực của certificate
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null | openssl x509 -noout -subject -issuer -dates
# curl hiện chi tiết TLS ở chế độ verbose
curl -v https://example.com 2>&1 | grep -E "SSL|TLS|subject|issuer"
SSH — Secure Shell
SSH là chuẩn cho quản trị từ xa an toàn, thay thế telnet, rlogin, rsh vốn plaintext. Nó chạy trên TCP/22 và cho bạn một kênh mã hóa, xác thực để truy cập shell, truyền file và tunneling.
Xác thực:
- Password — đơn giản nhưng dễ bị phishing và brute-force.
- Public-key — phương pháp ưu tiên. Bạn tạo một cặp key; public key đưa vào
~/.ssh/authorized_keyscủa server, private key ở lại trên client. Server thách thức bạn chứng minh bạn nắm private key mà không bao giờ truyền nó đi.
Host key — ở lần kết nối đầu, server trình host key của nó; bạn xác minh và cache fingerprint vào ~/.ssh/known_hosts để các kết nối sau phát hiện man-in-the-middle (đó là cảnh báo “REMOTE HOST IDENTIFICATION HAS CHANGED”).
Tunneling / port forwarding — SSH có thể bọc traffic khác bên trong kênh mã hóa của nó:
- Local forward (
-L) — đưa một dịch vụ từ xa ra máy local của bạn. - Remote forward (
-R) — đưa một dịch vụ local ra máy từ xa. - Dynamic forward (
-D) — biến SSH thành một SOCKS proxy.
# Tạo cặp key hiện đại
ssh-keygen -t ed25519 -C "you@example.com"
# Copy public key lên server
ssh-copy-id user@server.example.com
# Kết nối (verbose để debug vấn đề auth)
ssh -v user@server.example.com
# Local forward: truy cập DB từ xa (127.0.0.1:5432 trên server) qua localhost:5432
ssh -L 5432:localhost:5432 user@server.example.com
# SOCKS proxy động ở port 1080
ssh -D 1080 user@server.example.com
# Chạy một lệnh đơn từ xa
ssh user@server.example.com "uptime"
FTP vs SFTP vs FTPS — truyền file
| FTP | FTPS | SFTP | |
|---|---|---|---|
| Dựa trên | FTP gốc | FTP + TLS | SSH subsystem |
| Mã hóa | Không (plaintext) | TLS (explicit hoặc implicit) | SSH (luôn mã hóa) |
| Port | 21 (control) + 20/động (data) | 21 / 990 + dải data | 22 (một kết nối) |
| Thân thiện firewall | Không (kênh data riêng, rắc rối active/passive) | Không (vấn đề kênh tương tự) | Có (một port) |
| Auth | Password | Password + cert | SSH key hoặc password |
FTP thuần không được khuyến nghị vì nó gửi credential và dữ liệu dạng cleartext, và thiết kế hai kênh (control + data) là cơn ác mộng khi đi qua firewall và NAT (active vs passive mode). Hãy ưu tiên SFTP — nó hoàn toàn không phải “FTP over SSL” mà là một protocol riêng biệt chạy như một subsystem của SSH, nên tái sử dụng cơ chế xác thực, mã hóa và sự đơn giản một-port của SSH. Chỉ dùng FTPS khi bạn buộc phải tương thích với các FTP server cũ có hỗ trợ TLS.
# Phiên SFTP tương tác (dùng auth SSH trên port 22)
sftp user@server.example.com
# Không tương tác: lấy một file
sftp user@server.example.com:/remote/path/file.tar.gz .
# scp là "người anh em" copy đơn giản, cũng qua SSH
scp localfile.txt user@server.example.com:/remote/dir/
SMTP / IMAP / POP3 — email
Email dùng các protocol khác nhau cho gửi và lấy thư:
| Protocol | Vai trò | Port |
|---|---|---|
| SMTP | Gửi thư (client→server, relay server→server) | 25 (server-to-server), 587 (submission với STARTTLS), 465 (submission TLS ngầm) |
| IMAP | Lấy thư, giữ trên server, đồng bộ nhiều thiết bị | 143 (STARTTLS), 993 (TLS ngầm) |
| POP3 | Lấy thư, thường tải-về-rồi-xóa | 110 (STARTTLS), 995 (TLS ngầm) |
Luồng thư: mail client của bạn submit một message tới SMTP server của nhà cung cấp ở port 587 (submission có xác thực). Server đó tra MX record của domain người nhận trong DNS và relay message qua SMTP/25 tới mail server người nhận. Người nhận sau đó lấy thư bằng IMAP (hiện đại, giữ thư trên server và đồng bộ) hoặc POP3 (cũ hơn, tải về rồi xóa).
Chống giả mạo (xem ./11-network-security.md): vì SMTP không có xác thực người gửi tích hợp, ba cơ chế dựa trên DNS chống giả mạo:
- SPF — một TXT record liệt kê server nào được phép gửi thư cho domain.
- DKIM — server gửi ký message bằng private key; public key được công bố trong DNS.
- DMARC — một chính sách (TXT record) chỉ cho bên nhận biết làm gì khi SPF/DKIM thất bại, kèm báo cáo.
# Tìm nơi thư của một domain được gửi tới
dig gmail.com MX +short
# Kiểm tra chính sách SPF và DMARC của một domain
dig example.com TXT +short
dig _dmarc.example.com TXT +short
NTP và SNTP — đồng bộ thời gian
NTP (Network Time Protocol) giữ đồng hồ trên toàn mạng chính xác tới mức mili-giây. Nó chạy trên UDP/123. Nguồn thời gian được tổ chức thành các stratum:
- Stratum 0 — đồng hồ tham chiếu (GPS, đồng hồ nguyên tử). Không nằm trực tiếp trên mạng.
- Stratum 1 — server gắn trực tiếp với nguồn stratum-0.
- Stratum 2, 3, … — server đồng bộ từ stratum phía trên. Số càng cao = càng xa nguồn.
NTP dùng các trao đổi có timestamp để ước lượng cả offset lẫn round-trip delay, rồi từ từ hiệu chỉnh đồng hồ local (slewing) thay vì nhảy giật, để tránh thời gian bị lùi.
SNTP (Simple NTP) là một tập con nhẹ của cùng protocol và định dạng wire, dùng cho thiết bị chỉ cần đồng bộ đơn giản một lần mà không cần lọc thống kê và hiệu chỉnh đầy đủ như NTP daemon làm.
Vì sao thời gian chính xác lại quan trọng:
- TLS certificate có cửa sổ hiệu lực; đồng hồ sai làm cert hợp lệ trông như hết hạn hoặc chưa có hiệu lực, làm hỏng HTTPS.
- Log và monitoring trên nhiều host trở nên vô dụng nếu timestamp không khớp khi correlate một sự cố.
- Kerberos và nhiều hệ auth từ chối request có timestamp lệch quá xa (chống replay).
- Mã TOTP / 2FA dựa trên thời gian.
# Kiểm tra trạng thái đồng bộ (chrony)
chronyc tracking
chronyc sources -v
# Kiểm tra trạng thái đồng bộ (systemd-timesyncd)
timedatectl status
# Query trực tiếp một NTP server
ntpdate -q pool.ntp.org
SNMP — Simple Network Management Protocol
SNMP là cách bạn giám sát và (tùy chọn) cấu hình thiết bị mạng — router, switch, firewall, máy in, UPS. Nó chạy trên UDP/161 (query tới agent) và UDP/162 (trap gửi về manager). Các thành phần cốt lõi:
- Manager — hệ giám sát (NMS) poll thiết bị và nhận trap.
- Agent — phần mềm trên thiết bị được quản lý, phơi bày dữ liệu và gửi trap (cảnh báo bất đồng bộ).
- MIB (Management Information Base) — schema mô tả dữ liệu sẵn có.
- OID (Object Identifier) — một đường dẫn số dạng chấm (ví dụ
1.3.6.1.2.1.1.3.0= system uptime) định vị một giá trị trong cây MIB.
Phiên bản quan trọng về mặt bảo mật:
| Phiên bản | Auth | Mã hóa | Ghi chú |
|---|---|---|---|
| v1 | Community string (plaintext) | Không | Cũ, nên tránh |
| v2c | Community string (plaintext) | Không | Phổ biến nhưng không an toàn — community string đi cleartext |
| v3 | Theo user, có auth (HMAC) | Có (privacy/priv) | Nên dùng — hỗ trợ xác thực và mã hóa |
Ưu tiên SNMPv3 ở bất cứ đâu có thể. Đây chỉ là tổng quan ngắn; quy trình monitoring, polling vs streaming telemetry, và dashboard được trình bày trong ./14-monitoring-and-observability.md.
# Walk MIB system của một thiết bị bằng SNMPv2c (community "public")
snmpwalk -v2c -c public 192.0.2.1 system
# Lấy một OID đơn (sysUpTime)
snmpget -v2c -c public 192.0.2.1 1.3.6.1.2.1.1.3.0
# SNMPv3 với auth + privacy
snmpwalk -v3 -l authPriv -u monitor -a SHA -A "authpass" -x AES -X "privpass" 192.0.2.1 system
API cho networking
Thiết bị mạng hiện đại ngày càng được quản lý theo hướng lập trình thay vì gõ CLI thủ công. Đây là nền tảng của network automation (xem ./17-network-automation.md). Các interface chính:
| API | Transport / encoding | Mục đích |
|---|---|---|
| REST | HTTP(S) + JSON | API thiết bị/controller đa dụng (ví dụ cloud, controller SD-WAN, DNAC) |
| RESTCONF | HTTP(S) + JSON/XML, mô hình YANG | Truy cập kiểu REST tới config/state theo YANG của thiết bị |
| NETCONF | SSH (TCP/830) + XML, mô hình YANG | Cấu hình transactional với datastore candidate/running, commit/rollback |
| gNMI | gRPC trên HTTP/2, protobuf | Config + streaming telemetry tần suất cao, trung lập nhà cung cấp (OpenConfig) |
Vì sao API quan trọng: gõ lệnh vào CLI không mở rộng được lên hàng trăm thiết bị và dễ lỗi. API cho bạn dữ liệu có cấu trúc (JSON/XML thay vì “cào” text từ màn hình), thay đổi transactional (commit/rollback của NETCONF), và mô hình máy đọc được (YANG) để các công cụ như Ansible, Terraform và script Python cấu hình cả đội thiết bị nhất quán và an toàn. gNMI còn cho phép streaming telemetry — thiết bị đẩy metric liên tục thay vì bị poll, mở rộng tốt hơn nhiều so với SNMP với đội thiết bị lớn. Xem ./17-network-automation.md để biết công cụ và quy trình.
# RESTCONF: đọc config interface dạng JSON
curl -k -u admin:admin \
-H "Accept: application/yang-data+json" \
https://192.0.2.1/restconf/data/ietf-interfaces:interfaces
# NETCONF chạy qua SSH ở port 830
ssh admin@192.0.2.1 -p 830 -s netconf
Tóm tắt: protocol → transport → default port
| Protocol | Transport | Port mặc định | Mục đích |
|---|---|---|---|
| DHCP | UDP | 67 (server), 68 (client) | Tự động cấu hình IP |
| DNS | UDP/TCP | 53 | Phân giải tên |
| DoT | TCP | 853 | DNS over TLS |
| DoH | TCP | 443 | DNS over HTTPS |
| HTTP | TCP | 80 | Web |
| HTTPS | TCP (QUIC cho HTTP/3) | 443 | Web qua TLS |
| SSH / SFTP | TCP | 22 | Shell an toàn & truyền file |
| FTP | TCP | 21 (control), 20 (data) | Truyền file kiểu cũ |
| FTPS | TCP | 990 / 21 + dải data | FTP qua TLS |
| SMTP | TCP | 25, 587, 465 | Gửi email |
| IMAP | TCP | 143, 993 | Lấy email (đồng bộ) |
| POP3 | TCP | 110, 995 | Lấy email (tải về) |
| NTP | UDP | 123 | Đồng bộ thời gian |
| SNMP | UDP | 161 (query), 162 (trap) | Giám sát thiết bị |
| NETCONF | TCP (SSH) | 830 | API cấu hình mạng |
| RESTCONF | TCP (HTTPS) | 443 | API cấu hình mạng |
Best Practices
- Mã hóa mọi thứ. Ưu tiên biến thể an toàn của mọi protocol: HTTPS thay HTTP, SFTP/FTPS thay FTP, SNMPv3 thay v2c, DoT/DoH thay DNS plaintext, và SMTP/IMAP bật TLS. Protocol plaintext làm rò rỉ credential và dữ liệu cho bất kỳ ai trên đường truyền.
- Tắt các phiên bản yếu. Vô hiệu hóa SSLv3, TLS 1.0/1.1, SSH v1 và SNMPv1/v2c bất cứ khi nào có thể. Chuẩn hóa về TLS 1.2+ (lý tưởng là 1.3) và SNMPv3.
- Dùng key-based auth, không dùng password cho SSH và SFTP. Tắt password login và root login trên server, bảo vệ private key bằng passphrase.
- Đặt TTL DNS hợp lý. Hạ TTL trước một migration có kế hoạch để thay đổi lan truyền nhanh; nâng lại sau đó để giảm tải query. Luôn giữ ít nhất hai NS record trên hạ tầng tách biệt.
- Giữ đồng hồ được đồng bộ. Chạy NTP/chrony trên mọi host và thiết bị mạng. Lệch đồng hồ âm thầm làm hỏng xác thực TLS, correlate log, và Kerberos/2FA.
- Hiểu transport của bạn. Biết một protocol là TCP hay UDP trước khi troubleshoot — dịch vụ UDP (DNS, DHCP, NTP, SNMP) fail khác với TCP, và rule firewall phải khớp.
- Hardening DHCP. Dùng DHCP snooping trên switch để chặn DHCP server giả mạo, và relay agent (
ip helper-address) để giao qua các subnet. - Bảo vệ email bằng SPF, DKIM và DMARC. Cả ba đều là DNS record; thiếu bất kỳ cái nào cũng cho kẻ tấn công giả mạo domain của bạn.
- Ưu tiên API hơn cào màn hình. Với automation, dùng interface có cấu trúc NETCONF/RESTCONF/gNMI thay vì parse output CLI — chúng transactional và máy đọc được.
- Xác thực certificate đúng cách. Không bao giờ tắt xác minh certificate (
curl -k,verify=False) ở production; hãy sửa chain of trust. Giám sát ngày hết hạn của certificate.
Tài liệu tham khảo
- RFC 2131 — Dynamic Host Configuration Protocol (DHCP)
- RFC 1034 / 1035 — Domain Names (khái niệm và đặc tả DNS)
- RFC 9110 — HTTP Semantics
- RFC 9113 — HTTP/2
- RFC 9000 — QUIC: A UDP-Based Multiplexed and Secure Transport
- RFC 9114 — HTTP/3
- RFC 8446 — The Transport Layer Security (TLS) Protocol Version 1.3
- RFC 4251 — The Secure Shell (SSH) Protocol Architecture
- MDN Web Docs — HTTP
- Cloudflare Learning — What is DNS?
- Cloudflare Learning — What is SSL/TLS?
Part of the Network Engineer Roadmap knowledge base.
Overview
A protocol is an agreed-upon set of rules that lets two or more parties exchange information reliably. It defines the syntax (how messages are formatted — the bits, fields, and delimiters), the semantics (what each message means and what actions it triggers), and the timing (the order of messages and how parties react to loss, delay, or errors). Without protocols, two machines from different vendors could not agree on so much as where a message ends.
Most of the protocols a network engineer works with day to day are application-layer protocols: DNS, DHCP, HTTP, TLS, SSH, SMTP, NTP, SNMP, and so on. These do not talk to the wire directly. Instead they ride on top of a transport protocol — almost always TCP or UDP (see ./03-network-models-and-layers.md for the full layering model). The transport layer, in turn, rides on IP (see ./05-ip-addressing-and-subnetting.md).
The choice of transport shapes the application protocol’s behaviour:
| Property | TCP | UDP |
|---|---|---|
| Connection | Connection-oriented (3-way handshake) | Connectionless |
| Reliability | Guaranteed, ordered, retransmits lost data | Best-effort, no retransmission |
| Overhead | Higher (state, ACKs, sequence numbers) | Minimal |
| Flow/congestion control | Yes | No (app must handle it) |
| Typical users | HTTP, TLS, SSH, SMTP, FTP | DNS (queries), DHCP, NTP, SNMP, QUIC (over UDP) |
The rule of thumb: use TCP when every byte must arrive in order (web pages, file transfers, shell sessions); use UDP when speed and low overhead beat perfect delivery, or when the application implements its own reliability (DNS, real-time media, QUIC).
The rest of this note walks through each core protocol: what problem it solves, how it works on the wire, the ports it uses, and the CLI commands you use to inspect and troubleshoot it.
Fundamentals
Layered application protocols over TCP/UDP
Think of a request to load https://example.com as a stack of protocols working together:
- DHCP already gave your host an IP address, gateway, and DNS server when it joined the network.
- DNS turns
example.cominto an IP address (over UDP/53, or TCP for large answers). - TCP opens a reliable connection to that IP on port 443 (or QUIC over UDP/443 for HTTP/3).
- TLS negotiates encryption on top of TCP so the exchange is private and authenticated.
- HTTP carries the actual request (
GET /) and response inside the TLS tunnel.
Every layer is independent: HTTP does not care whether TLS is present, and TLS does not care what application data it carries. This separation is what lets the same TLS library secure HTTP, SMTP, and IMAP alike.
Ports and sockets
A transport-layer port (0–65535) identifies which application on a host a packet belongs to. A socket is the combination (IP address, port, protocol). Well-known ports (0–1023) are reserved for standard services (53 DNS, 80 HTTP, 443 HTTPS, 22 SSH). Registered and ephemeral ports (1024–65535) are used by clients and custom services. When you type curl https://example.com, your OS picks a random ephemeral source port and connects to destination port 443.
Key Concepts
DHCP — Dynamic Host Configuration Protocol
DHCP automatically hands out IP configuration to hosts so nobody has to configure addresses by hand. It runs over UDP, with the client on port 68 and the server on port 67. A new client and a server that have never spoken before complete the DORA exchange:
| Step | Message | Direction | Purpose |
|---|---|---|---|
| D | DHCPDISCOVER | Client → broadcast | ”Is there a DHCP server out there?” |
| O | DHCPOFFER | Server → client | ”Here is an address you may use.” |
| R | DHCPREQUEST | Client → broadcast | ”I’ll take that offer.” (broadcast so other servers withdraw theirs) |
| A | DHCPACK | Server → client | ”Confirmed, the lease is yours.” |
Key ideas:
- Lease — an address is granted for a finite lease time. The client tries to renew at 50% of the lease (T1, unicast to the server) and rebind at 87.5% (T2, broadcast to any server) if the original server is gone.
- Options — the ACK carries more than an address: subnet mask (option 1), default gateway/router (option 3), DNS servers (option 6), domain name (option 15), NTP servers (option 42), lease time (option 51), and many more.
- DHCP relay (relay agent /
ip helper-address) — DHCP relies on broadcasts, which routers do not forward. When the server sits on a different subnet, a relay agent on the client’s router captures the broadcast and unicasts it to the server, inserting the client’s subnet (giaddr) so the server knows which pool to use. - DHCPv6 exists for IPv6, though IPv6 also supports stateless address autoconfiguration (SLAAC).
Inspect a lease on Linux with ip addr and check /var/lib/dhcp/dhclient.leases; on macOS ipconfig getpacket en0 dumps the full DHCP reply including all options.
DNS — Domain Name System
DNS is the distributed database that maps human-friendly names (example.com) to machine data (IP addresses and more). It runs primarily over UDP/53 for small queries and falls back to TCP/53 for large responses (over 512 bytes without EDNS) and zone transfers.
Resolution flow (recursive lookup for www.example.com):
- Stub resolver — the client OS asks its configured recursive resolver (the DNS server it got from DHCP, e.g.
8.8.8.8). - Recursive resolver — if not cached, it starts at the top. It asks a root server (“where is
.com?”). - Root — replies with the TLD name servers for
.com. - TLD server — replies with the authoritative name servers for
example.com. - Authoritative server — returns the actual A/AAAA record for
www.example.com. - The resolver caches the answer (honouring its TTL) and returns it to the stub.
The stub does one query and gets a final answer; the recursive resolver does the legwork of walking the hierarchy.
Common record types:
| Type | Purpose | Example value |
|---|---|---|
A | Name → IPv4 address | 93.184.216.34 |
AAAA | Name → IPv6 address | 2606:2800:220:1:248:1893:25c8:1946 |
CNAME | Alias → canonical name | www → example.com. |
MX | Mail exchanger (with priority) | 10 mail.example.com. |
TXT | Arbitrary text (SPF, DKIM, verification) | "v=spf1 include:_spf.google.com ~all" |
NS | Delegates a zone to name servers | ns1.example.com. |
SOA | Start of authority — zone metadata, serial, timers | serial, refresh, retry, expire, minimum |
SRV | Service location (host + port) | _sip._tcp → 0 5 5060 sipserver.example.com. |
PTR | Reverse lookup: IP → name | 34.216.184.93.in-addr.arpa → example.com. |
CAA | Which CAs may issue certs for the domain | 0 issue "letsencrypt.org" |
TTL (Time To Live) — every record carries a TTL in seconds telling resolvers how long to cache it. Low TTLs (e.g. 300s) make changes propagate fast but increase query load; high TTLs (e.g. 86400s) cut load but slow down failovers.
Encrypted DNS — classic DNS is plaintext, so on-path observers can see and tamper with lookups. Two upgrades fix this:
- DoT (DNS over TLS) — DNS wrapped in TLS on TCP/853.
- DoH (DNS over HTTPS) — DNS sent as HTTPS requests on TCP/443, indistinguishable from normal web traffic.
dig examples:
# Basic A record lookup
dig example.com A +short
# 93.184.216.34
# Full answer with query time, flags, and TTL
dig example.com
# Query a specific resolver
dig @1.1.1.1 example.com
# Mail records
dig example.com MX +short
# Trace the full delegation from the root down (shows each hop)
dig +trace example.com
# Reverse lookup (PTR)
dig -x 93.184.216.34
# See the TTL and SOA
dig example.com SOA
# nslookup equivalent for a quick check
nslookup example.com 8.8.8.8
HTTP & HTTPS — HyperText Transfer Protocol
HTTP is the request/response protocol of the web. A client sends a request (method, path, headers, optional body) and the server returns a response (status line, headers, body). Plain HTTP uses TCP/80; HTTPS is HTTP inside a TLS tunnel on TCP/443.
Methods:
| Method | Meaning | Safe? | Idempotent? |
|---|---|---|---|
GET | Retrieve a resource | Yes | Yes |
HEAD | Like GET but headers only | Yes | Yes |
POST | Submit data / create | No | No |
PUT | Replace a resource | No | Yes |
PATCH | Partially update | No | No |
DELETE | Remove a resource | No | Yes |
OPTIONS | Ask what methods are allowed (CORS preflight) | Yes | Yes |
Status code classes:
| Class | Meaning | Examples |
|---|---|---|
1xx | Informational | 101 Switching Protocols |
2xx | Success | 200 OK, 201 Created, 204 No Content |
3xx | Redirection | 301 Moved Permanently, 302 Found, 304 Not Modified |
4xx | Client error | 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 429 Too Many Requests |
5xx | Server error | 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout |
Important headers: Host (which site on a shared IP), Content-Type, Content-Length, Authorization, Cookie/Set-Cookie, Cache-Control, User-Agent, Accept, Location (for redirects).
Protocol versions:
| Version | Transport | Key traits |
|---|---|---|
| HTTP/1.1 | TCP | One request at a time per connection; persistent connections and pipelining (rarely used); text-based; head-of-line blocking |
| HTTP/2 | TCP + TLS | Binary framing, multiplexed streams over one connection, header compression (HPACK), server push. Still suffers TCP-level head-of-line blocking |
| HTTP/3 | QUIC over UDP/443 | Multiplexing without TCP head-of-line blocking (streams are independent), built-in TLS 1.3, faster connection setup (0-RTT), connection migration across IP changes |
HTTP/2 in depth
HTTP/2 (RFC 9113, originally RFC 7540, derived from Google’s SPDY) keeps HTTP’s semantics — the same methods, status codes, and headers — but completely changes how bytes go on the wire:
- Binary framing layer. Instead of the plaintext, line-delimited messages of HTTP/1.1, HTTP/2 splits every message into binary frames (HEADERS, DATA, SETTINGS, etc.). Frames are easier to parse unambiguously and are the unit that multiplexing operates on.
- Multiplexing over one connection. Many streams (each an independent request/response) are interleaved over a single TCP connection, each identified by a stream ID. This kills the HTTP/1.1 need to open 6+ parallel connections per origin and eliminates application-level head-of-line blocking (a slow response no longer blocks others in the HTTP layer).
- Header compression (HPACK, RFC 7541). Request/response headers are highly repetitive (same
User-Agent,Cookie, etc. on every request). HPACK compresses them with a shared dynamic table plus Huffman coding, cutting overhead dramatically. HPACK was designed to resist the CRIME attack that broke naive TLS-layer compression. - Stream prioritization & flow control. Clients can express a dependency/weight tree so the server sends critical resources (CSS, above-the-fold) first; per-stream and per-connection flow control prevent a fast sender from overwhelming a slow receiver.
- Server push (deprecated in practice). The server could pre-emptively send resources the client hadn’t requested yet. It rarely helped and was often wasteful, so most browsers and servers have disabled/removed it — prefer
103 Early Hintsandpreloadinstead.
The catch — TCP head-of-line blocking. HTTP/2 removes HoL blocking inside the HTTP layer, but all streams still ride one TCP connection. TCP guarantees in-order delivery of the byte stream, so if a single packet is lost, TCP holds back every stream’s data until that packet is retransmitted — even streams that had no missing bytes. On lossy links (mobile, congested Wi-Fi) this can make HTTP/2 no faster, or slower, than multiple HTTP/1.1 connections. This is exactly the problem QUIC/HTTP/3 was built to fix.
QUIC & HTTP/3 in depth
QUIC (RFC 9000) is a new, general-purpose transport protocol built on top of UDP, and HTTP/3 (RFC 9114) is HTTP mapped onto QUIC. QUIC was pioneered by Google and standardized by the IETF; running over UDP was a pragmatic choice — TCP and UDP are effectively the only transports that middleboxes (firewalls, NAT) reliably pass, and evolving TCP itself is nearly impossible because so much logic is baked into OS kernels and network hardware. QUIC lives in user space, so it can iterate quickly.
Why QUIC matters:
- No transport-level head-of-line blocking. QUIC implements streams inside the transport. Each stream is delivered independently, so a lost packet only stalls the stream(s) whose bytes it carried — other streams keep flowing. This finally delivers the multiplexing HTTP/2 promised, even on lossy networks.
- Encryption is built in (TLS 1.3). QUIC integrates TLS 1.3 directly rather than layering TLS over a separate transport. There is no unencrypted QUIC — the transport headers themselves are largely encrypted/authenticated, which also reduces middlebox ossification.
- Faster connection establishment. A classic HTTPS start is TCP handshake (1 RTT) then TLS handshake (1 RTT). QUIC merges transport and cryptographic setup into a single 1-RTT handshake, and supports 0-RTT resumption where a returning client can send request data in the very first packet (with the well-known 0-RTT replay-safety caveat — only for idempotent requests).
- Connection migration. A QUIC connection is identified by a Connection ID, not the 4-tuple of IPs/ports. When your phone switches from Wi-Fi to cellular (its IP changes), the connection survives instead of breaking — a big win for mobile.
- Modern loss recovery & congestion control. QUIC uses monotonically increasing packet numbers (no TCP retransmission ambiguity), explicit ACK ranges, and pluggable congestion control (e.g. CUBIC, BBR).
Trade-offs & operational notes. QUIC is more CPU-intensive than TCP (encryption per packet, user-space processing) and, because it is UDP, some restrictive networks throttle or block UDP/443 — clients then fall back to HTTP/2 over TCP. HTTP/3 is advertised via the Alt-Svc header (or HTTPS/SVCB DNS records), so the first visit typically happens over HTTP/2 and subsequent connections upgrade to HTTP/3.
| Property | HTTP/1.1 | HTTP/2 | HTTP/3 |
|---|---|---|---|
| Transport | TCP | TCP | QUIC (UDP) |
| Wire format | Text | Binary frames | Binary frames |
| Multiplexing | No (parallel conns) | Yes (one conn) | Yes (one conn) |
| Head-of-line blocking | App + TCP | TCP only | None |
| Header compression | None (gzip body only) | HPACK | QPACK |
| Encryption | Optional (via TLS) | Effectively required | Built-in (TLS 1.3) |
| Handshake RTTs (with TLS) | 2–3 | 2–3 | 1 (0 on resume) |
| Connection migration | No | No | Yes (Connection ID) |
Request lifecycle for curl -v https://example.com:
- DNS resolves
example.com. - TCP handshake to port 443 (or QUIC for HTTP/3).
- TLS handshake negotiates encryption and validates the certificate.
- HTTP request is sent inside the TLS tunnel.
- Server responds with status, headers, and body.
- Connection is kept alive for reuse or closed.
# Verbose request: shows DNS, TCP, TLS handshake, request and response headers
curl -v https://example.com
# Response headers only
curl -I https://example.com
# Force a specific HTTP version
curl --http2 -I https://example.com
curl --http3 -I https://cloudflare.com
# Follow redirects and time the phases
curl -L -o /dev/null -s -w "dns:%{time_namelookup} connect:%{time_connect} tls:%{time_appconnect} total:%{time_total}\n" https://example.com
SSL/TLS — Transport Layer Security
TLS (the modern successor to SSL, which is fully deprecated) secures a transport connection. It provides three guarantees:
- Confidentiality — traffic is encrypted; on-path observers cannot read it.
- Integrity — tampering is detected via authenticated encryption (AEAD).
- Authentication — the client verifies the server’s identity via its certificate (and optionally the server verifies the client, mutual TLS).
The TLS handshake (TLS 1.2, simplified):
- ClientHello — client sends supported TLS versions, cipher suites, and a random.
- ServerHello — server picks a version and cipher, sends its random and its certificate.
- Client validates the certificate chain, then both sides perform a key exchange (ECDHE) to derive a shared session key.
- Finished messages confirm both sides derived the same keys; encrypted application data flows.
This costs two round trips before data can flow.
TLS 1.3 streamlines this to one round trip (1-RTT), and supports 0-RTT resumption for repeat visits. It removes all the old, weak options: only forward-secret (ephemeral) key exchange and AEAD ciphers remain, RSA key transport and static Diffie-Hellman are gone, and the whole cipher-suite list is much smaller and safer.
| TLS 1.2 | TLS 1.3 | |
|---|---|---|
| Handshake round trips | 2-RTT | 1-RTT (0-RTT resumption) |
| Cipher suites | Many, some weak | Small, all AEAD + forward secrecy |
| Key exchange | RSA or (EC)DHE | (EC)DHE only |
| Status | Acceptable | Preferred |
Certificates and the chain of trust: a server presents an X.509 certificate binding its domain name to a public key, signed by a Certificate Authority (CA). Your device trusts a set of root CAs shipped by the OS/browser. The server’s leaf certificate is usually signed by an intermediate CA, which is signed by a root. The client walks this chain from leaf → intermediate → trusted root; if it terminates in a trusted root and none are expired or revoked, the certificate is valid.
# Inspect a server's certificate and the full chain
openssl s_client -connect example.com:443 -servername example.com </dev/null
# Show the negotiated protocol and cipher
openssl s_client -connect example.com:443 -servername example.com </dev/null 2>/dev/null | grep -E "Protocol|Cipher"
# Read a certificate's subject, issuer, and validity dates
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null | openssl x509 -noout -subject -issuer -dates
# curl shows TLS details in verbose mode
curl -v https://example.com 2>&1 | grep -E "SSL|TLS|subject|issuer"
SSH — Secure Shell
SSH is the standard for secure remote administration, replacing the plaintext telnet, rlogin, and rsh. It runs over TCP/22 and gives you an encrypted, authenticated channel for shell access, file transfer, and tunnelling.
Authentication:
- Password — simple but phishable and brute-forceable.
- Public-key — the preferred method. You generate a key pair; the public key goes into the server’s
~/.ssh/authorized_keys, the private key stays on your client. The server challenges you to prove you hold the private key without ever transmitting it.
Host keys — on first connect the server presents its host key; you verify and cache its fingerprint in ~/.ssh/known_hosts so future connections detect man-in-the-middle attempts (that’s the “REMOTE HOST IDENTIFICATION HAS CHANGED” warning).
Tunnelling / port forwarding — SSH can wrap other traffic inside its encrypted channel:
- Local forward (
-L) — expose a remote service on your local machine. - Remote forward (
-R) — expose a local service on the remote machine. - Dynamic forward (
-D) — turn SSH into a SOCKS proxy.
# Generate a modern key pair
ssh-keygen -t ed25519 -C "you@example.com"
# Copy your public key to a server
ssh-copy-id user@server.example.com
# Connect (verbose to debug auth issues)
ssh -v user@server.example.com
# Local forward: reach the remote DB (127.0.0.1:5432 on server) via localhost:5432
ssh -L 5432:localhost:5432 user@server.example.com
# Dynamic SOCKS proxy on port 1080
ssh -D 1080 user@server.example.com
# Run a single command remotely
ssh user@server.example.com "uptime"
FTP vs SFTP vs FTPS — file transfer
| FTP | FTPS | SFTP | |
|---|---|---|---|
| Based on | Original FTP | FTP + TLS | SSH subsystem |
| Encryption | None (plaintext) | TLS (explicit or implicit) | SSH (always encrypted) |
| Ports | 21 (control) + 20/dynamic (data) | 21 / 990 + data range | 22 (single connection) |
| Firewall-friendly | No (separate data channel, active/passive complications) | No (same channel issues) | Yes (one port) |
| Auth | Password | Password + certs | SSH keys or password |
Plain FTP is discouraged because it sends credentials and data in cleartext, and its dual-channel (control + data) design is a nightmare through firewalls and NAT (active vs passive mode). Prefer SFTP — it is not “FTP over SSL” at all but a distinct protocol running as a subsystem of SSH, so it reuses SSH’s authentication, encryption, and single-port simplicity. Use FTPS only when you must interoperate with legacy FTP servers that support TLS.
# SFTP interactive session (uses SSH auth on port 22)
sftp user@server.example.com
# Non-interactive: fetch a file
sftp user@server.example.com:/remote/path/file.tar.gz .
# scp is the simple copy cousin, also over SSH
scp localfile.txt user@server.example.com:/remote/dir/
SMTP / IMAP / POP3 — email
Email uses different protocols for sending and retrieving:
| Protocol | Role | Ports |
|---|---|---|
| SMTP | Send mail (client→server, server→server relay) | 25 (server-to-server), 587 (submission with STARTTLS), 465 (implicit TLS submission) |
| IMAP | Retrieve mail, keep it on the server, sync across devices | 143 (STARTTLS), 993 (implicit TLS) |
| POP3 | Retrieve mail, typically download-and-delete | 110 (STARTTLS), 995 (implicit TLS) |
Mail flow: your mail client submits a message to your provider’s SMTP server on port 587 (authenticated submission). That server looks up the recipient domain’s MX record in DNS and relays the message over SMTP/25 to the recipient’s mail server. The recipient later fetches it with IMAP (modern, keeps mail server-side and synced) or POP3 (older, download-then-delete).
Anti-spoofing (see ./11-network-security.md): because SMTP has no built-in sender authentication, three DNS-based mechanisms fight forgery:
- SPF — a TXT record listing which servers may send mail for the domain.
- DKIM — the sending server signs messages with a private key; the public key is published in DNS.
- DMARC — a policy (TXT record) telling receivers what to do when SPF/DKIM fail, plus reporting.
# Find where mail for a domain is delivered
dig gmail.com MX +short
# Check a domain's SPF and DMARC policies
dig example.com TXT +short
dig _dmarc.example.com TXT +short
NTP and SNTP — time synchronization
NTP (Network Time Protocol) keeps clocks across a network accurate to milliseconds. It runs over UDP/123. Time sources are organized into strata:
- Stratum 0 — reference clocks (GPS, atomic clocks). Not on the network directly.
- Stratum 1 — servers directly attached to a stratum-0 source.
- Stratum 2, 3, … — servers that sync from the stratum above them. Higher number = further from the source.
NTP uses timestamped exchanges to estimate both the offset and the round-trip delay, then gradually disciplines the local clock (slewing) rather than jumping it, to avoid time going backwards.
SNTP (Simple NTP) is a lightweight subset of the same protocol and wire format, used by devices that just need a simple one-shot sync without the full statistical filtering and disciplining that NTP daemons do.
Why accurate time matters:
- TLS certificates have validity windows; a wrong clock makes valid certs look expired or not-yet-valid, breaking HTTPS.
- Logs and monitoring across many hosts are useless if timestamps do not line up when correlating an incident.
- Kerberos and many auth systems reject requests whose timestamps drift too far (replay protection).
- TOTP / 2FA codes are time-based.
# Check sync status (chrony)
chronyc tracking
chronyc sources -v
# Check sync status (systemd-timesyncd)
timedatectl status
# Query an NTP server directly
ntpdate -q pool.ntp.org
SNMP — Simple Network Management Protocol
SNMP is how you monitor and (optionally) configure network devices — routers, switches, firewalls, printers, UPS units. It runs over UDP/161 (queries to agents) and UDP/162 (traps sent to the manager). Core pieces:
- Manager — the monitoring system (NMS) that polls devices and receives traps.
- Agent — software on the managed device that exposes data and sends traps (asynchronous alerts).
- MIB (Management Information Base) — the schema describing available data.
- OID (Object Identifier) — a dotted numeric path (e.g.
1.3.6.1.2.1.1.3.0= system uptime) addressing one value in the MIB tree.
Versions matter for security:
| Version | Auth | Encryption | Notes |
|---|---|---|---|
| v1 | Community string (plaintext) | None | Legacy, avoid |
| v2c | Community string (plaintext) | None | Common but insecure — community string travels in the clear |
| v3 | User-based, with auth (HMAC) | Yes (privacy/priv) | Use this — supports authentication and encryption |
Prefer SNMPv3 wherever possible. This is a brief overview; monitoring workflows, polling vs streaming telemetry, and dashboards are covered in ./14-monitoring-and-observability.md.
# Walk a device's system MIB with SNMPv2c (community "public")
snmpwalk -v2c -c public 192.0.2.1 system
# Get a single OID (sysUpTime)
snmpget -v2c -c public 192.0.2.1 1.3.6.1.2.1.1.3.0
# SNMPv3 with auth + privacy
snmpwalk -v3 -l authPriv -u monitor -a SHA -A "authpass" -x AES -X "privpass" 192.0.2.1 system
APIs for networking
Modern network gear is increasingly managed programmatically instead of by hand-typed CLI. This is the foundation of network automation (see ./17-network-automation.md). The main interfaces:
| API | Transport / encoding | Purpose |
|---|---|---|
| REST | HTTP(S) + JSON | General-purpose device/controller APIs (e.g. cloud, SD-WAN controllers, DNAC) |
| RESTCONF | HTTP(S) + JSON/XML, YANG-modeled | REST-style access to a device’s YANG configuration/state |
| NETCONF | SSH (TCP/830) + XML, YANG-modeled | Transactional config with candidate/running datastores, commit/rollback |
| gNMI | gRPC over HTTP/2, protobuf | Config + high-frequency streaming telemetry, vendor-neutral (OpenConfig) |
Why APIs matter: typing commands into a CLI does not scale to hundreds of devices and is error-prone. APIs give you structured data (JSON/XML instead of screen-scraped text), transactional changes (NETCONF’s commit/rollback), and machine-readable models (YANG) so tools like Ansible, Terraform, and Python scripts can configure fleets consistently and safely. gNMI additionally enables streaming telemetry — devices push metrics continuously instead of being polled, which is far more scalable than SNMP for large fleets. See ./17-network-automation.md for tooling and workflows.
# RESTCONF: read interface config as JSON
curl -k -u admin:admin \
-H "Accept: application/yang-data+json" \
https://192.0.2.1/restconf/data/ietf-interfaces:interfaces
# NETCONF happens over SSH on port 830
ssh admin@192.0.2.1 -p 830 -s netconf
Summary: protocol → transport → default port
| Protocol | Transport | Default port(s) | Purpose |
|---|---|---|---|
| DHCP | UDP | 67 (server), 68 (client) | Automatic IP configuration |
| DNS | UDP/TCP | 53 | Name resolution |
| DoT | TCP | 853 | DNS over TLS |
| DoH | TCP | 443 | DNS over HTTPS |
| HTTP | TCP | 80 | Web |
| HTTPS | TCP (QUIC for HTTP/3) | 443 | Web over TLS |
| SSH / SFTP | TCP | 22 | Secure shell & file transfer |
| FTP | TCP | 21 (control), 20 (data) | Legacy file transfer |
| FTPS | TCP | 990 / 21 + data range | FTP over TLS |
| SMTP | TCP | 25, 587, 465 | Sending email |
| IMAP | TCP | 143, 993 | Retrieving email (sync) |
| POP3 | TCP | 110, 995 | Retrieving email (download) |
| NTP | UDP | 123 | Time synchronization |
| SNMP | UDP | 161 (query), 162 (trap) | Device monitoring |
| NETCONF | TCP (SSH) | 830 | Network config API |
| RESTCONF | TCP (HTTPS) | 443 | Network config API |
Best Practices
- Encrypt everything. Prefer the secure variant of every protocol: HTTPS over HTTP, SFTP/FTPS over FTP, SNMPv3 over v2c, DoT/DoH over plaintext DNS, and TLS-enabled SMTP/IMAP. Plaintext protocols leak credentials and data to anyone on the path.
- Disable weak versions. Turn off SSLv3, TLS 1.0/1.1, SSH v1, and SNMPv1/v2c wherever you can. Standardize on TLS 1.2+ (ideally 1.3) and SNMPv3.
- Use key-based auth, not passwords, for SSH and SFTP. Disable password and root login on servers, and protect private keys with passphrases.
- Set sensible DNS TTLs. Lower TTLs before a planned migration so changes propagate quickly; raise them afterward to reduce query load. Always keep at least two NS records on separate infrastructure.
- Keep clocks synced. Run NTP/chrony on every host and network device. Clock drift silently breaks TLS validation, log correlation, and Kerberos/2FA.
- Understand your transport. Know whether a protocol is TCP or UDP before troubleshooting — a UDP service (DNS, DHCP, NTP, SNMP) fails differently from a TCP one, and firewall rules must match.
- Harden DHCP. Use DHCP snooping on switches to block rogue DHCP servers, and relay agents (
ip helper-address) for cross-subnet delivery. - Protect email with SPF, DKIM, and DMARC. All three are DNS records; missing any of them lets attackers spoof your domain.
- Prefer APIs over screen-scraping. For automation, use NETCONF/RESTCONF/gNMI structured interfaces rather than parsing CLI output — they are transactional and machine-readable.
- Validate certificates properly. Never disable certificate verification (
curl -k,verify=False) in production; fix the trust chain instead. Monitor certificate expiry.
References
- RFC 2131 — Dynamic Host Configuration Protocol (DHCP)
- RFC 1034 / 1035 — Domain Names (DNS concepts and specification)
- RFC 9110 — HTTP Semantics
- RFC 9113 — HTTP/2
- RFC 9000 — QUIC: A UDP-Based Multiplexed and Secure Transport
- RFC 9114 — HTTP/3
- RFC 8446 — The Transport Layer Security (TLS) Protocol Version 1.3
- RFC 4251 — The Secure Shell (SSH) Protocol Architecture
- MDN Web Docs — HTTP
- Cloudflare Learning — What is DNS?
- Cloudflare Learning — What is SSL/TLS?