Tech Guides

NETOPS//FUNDAMENTALS

Network Operations & Infrastructure Reference v2.0

TCP/IP STACK ONLINE
DNS RESOLUTION ACTIVE
FIREWALL MONITORING
INTRUSION DETECTION
v2.0
NETOPS REFERENCE
RFC COMPLIANT
01

Quick Reference

Essential networking commands organized by task. Copy, paste, diagnose.

Connectivity Testing

ping -c 4 192.168.1.1
Test reachability (4 packets)
ping -c 4 -s 1472 -M do host
Test MTU (don't fragment)
traceroute example.com
Trace route to destination
mtr example.com
Continuous trace + ping combined

DNS Lookup

dig example.com
DNS query (A record)
dig +short example.com AAAA
Quick IPv6 lookup
dig @8.8.8.8 example.com
Query specific server
nslookup example.com
Simple DNS lookup

Port & Service Discovery

ss -tlnp
Show listening TCP ports
ss -ulnp
Show listening UDP ports
nmap -sS -p 1-1000 host
SYN scan ports 1-1000
nmap -sV host
Service version detection

Interface & Routing

ip addr show
Show all interfaces
ip route show
Show routing table
ip link set eth0 up/down
Enable/disable interface
ip neigh show
Show ARP/neighbor table

Traffic Capture

tcpdump -i eth0 -n
Capture on interface
tcpdump -i eth0 port 80
Capture HTTP traffic
tcpdump -i eth0 -w capture.pcap
Save to file
curl -I -w "time_total: %{time_total}\n" URL
HTTP timing

Configuration Files

cat /etc/resolv.conf
DNS config
cat /etc/hosts
Local hostname resolution
sysctl net.ipv4.ip_forward
Check IP forwarding
iptables -L -n -v
List firewall rules
02

The Network Stack

The OSI 7-layer model and TCP/IP 4-layer model provide the conceptual frameworks for understanding how data moves across networks.

OSI Reference Model

The Open Systems Interconnection model defines seven abstraction layers for network communication. Each layer serves the layer above it and is served by the layer below it.

Layer Name PDU Protocols Devices
7 Application Data HTTP, FTP, SMTP, DNS, SNMP Proxy, WAF
6 Presentation Data SSL/TLS, JPEG, ASCII
5 Session Data NetBIOS, RPC, SMB
4 Transport Segment / Datagram TCP, UDP Load Balancer
3 Network Packet IP, ICMP, OSPF, BGP Router
2 Data Link Frame Ethernet, Wi-Fi, ARP Switch
1 Physical Bits Cables, Radio, Fiber Hub, NIC

TCP/IP Model

The practical protocol suite that powers the internet. Maps roughly to the OSI model but consolidates the upper layers.

Layer OSI Equivalent Key Protocols
Application Layers 5-7 HTTP, DNS, SMTP, SNMP, SSH
Transport Layer 4 TCP, UDP
Internet Layer 3 IP, ICMP, ARP
Network Access Layers 1-2 Ethernet, Wi-Fi, PPP

Data Encapsulation

As data moves down the stack, each layer wraps it with its own header (and sometimes trailer). This process is called encapsulation. On the receiving end, each layer strips its header in reverse order (de-encapsulation).

Application
DATA
Transport
TCP HDR DATA
Network
IP HDR TCP HDR DATA
Data Link
MAC HDR IP HDR TCP HDR DATA FCS
Physical
BITS ON THE WIRE
// Conceptual vs. Practical

The OSI model is the conceptual framework for learning and troubleshooting. TCP/IP is the practical protocol suite that runs the internet. When debugging, think in layers: start at Layer 1 (is the cable plugged in?) and work your way up.

03

IP Addressing & Subnetting

Understanding IP address structure, subnet masks, CIDR notation, and how to carve address space into usable networks.

IPv4 Address Structure

IPv4 addresses are 32-bit numbers expressed in dotted-decimal notation. The subnet mask divides the address into a network portion and a host portion.

Format
32-bit / 4 octets
Notation
192.168.1.1
Total Addresses
4,294,967,296
# Example breakdown:  192.168.1.0/24
#
# IP Address:       192.168.1.0
# Subnet Mask:      255.255.255.0
# Network:          192.168.1.0     (first 24 bits)
# Broadcast:        192.168.1.255   (last address)
# Usable Range:     192.168.1.1  -  192.168.1.254
# Total Addresses:  256
# Usable Hosts:     254

Private Address Ranges (RFC 1918)

Reserved for internal use. Not routable on the public internet. Use NAT (Network Address Translation) to reach external networks.

Range CIDR Addresses Typical Use
10.0.0.0 – 10.255.255.255 10.0.0.0/8 16,777,216 Enterprise
172.16.0.0 – 172.31.255.255 172.16.0.0/12 1,048,576 Mid-size
192.168.0.0 – 192.168.255.255 192.168.0.0/16 65,536 Home / Small Office

Special Addresses

  • 127.0.0.0/8Loopback. Traffic never leaves the host. 127.0.0.1 is localhost.
  • 169.254.0.0/16APIPA (link-local). Auto-assigned when DHCP fails.
  • 0.0.0.0/0Default route. Matches all destinations (gateway of last resort).
  • 255.255.255.255Limited broadcast. Sent to all hosts on the local network segment.

CIDR Reference Table

Classless Inter-Domain Routing replaced the old Class A/B/C system. The /prefix number indicates how many bits define the network portion.

CIDR Subnet Mask Addresses Usable Hosts Common Use
/8 255.0.0.0 16,777,216 16,777,214 Large enterprise
/16 255.255.0.0 65,536 65,534 Campus
/24 255.255.255.0 256 254 Standard LAN
/25 255.255.255.128 128 126 Half subnet
/26 255.255.255.192 64 62 Department
/27 255.255.255.224 32 30 Small group
/28 255.255.255.240 16 14 Server VLAN
/30 255.255.255.252 4 2 Point-to-point
/32 255.255.255.255 1 1 Host route
// Remember

Usable hosts = total addresses - 2 (one for network address, one for broadcast). Exception: /31 point-to-point links (RFC 3021) use both addresses, and /32 is a single host.

IPv6 Overview

IPv6 uses 128-bit addresses written as 8 groups of 4 hexadecimal digits, separated by colons. It provides a vastly larger address space than IPv4.

Address Size
128-bit
Notation
2001:0db8::1
Global Adoption
~47% (2026)
  • Standard subnet: /64 — 64 bits for network, 64 bits for host interface ID
  • Link-local: fe80::/10 — Auto-configured on every interface, non-routable
  • Loopback: ::1 — Equivalent to IPv4's 127.0.0.1
  • Unspecified: :: — Equivalent to IPv4's 0.0.0.0
  • Global unicast: 2000::/3 — Publicly routable addresses
  • Unique local: fc00::/7 — Equivalent to RFC 1918 private ranges
# IPv6 address shortening rules:
#
# Full:        2001:0db8:0000:0000:0000:0000:0000:0001
# Drop zeros:  2001:db8:0:0:0:0:0:1
# Collapse:    2001:db8::1
#
# Rules:
# 1. Remove leading zeros in each group
# 2. Replace ONE consecutive run of all-zero groups with ::
# 3. :: can only appear ONCE in an address

Subnet Calculation Example

Given 10.0.0.0/24, subnet into /26 blocks. A /24 has 256 addresses; each /26 has 64 addresses, so we get 4 subnets.

Subnet Network Usable Range Broadcast Hosts
1 10.0.0.0/26 .1 – .62 10.0.0.63 62
2 10.0.0.64/26 .65 – .126 10.0.0.127 62
3 10.0.0.128/26 .129 – .190 10.0.0.191 62
4 10.0.0.192/26 .193 – .254 10.0.0.255 62
# Quick subnet math:
#
# /26 = 32 - 26 = 6 host bits
# 2^6 = 64 addresses per subnet
# 64 - 2 = 62 usable hosts per subnet
# 256 / 64 = 4 subnets from a /24
#
# Block size = 256 - subnet_mask_octet
# For /26:  subnet mask = 255.255.255.192
#           block size  = 256 - 192 = 64
# Subnets start at:  .0, .64, .128, .192
// Quick Subnet Formula

Number of subnets = 2^(new_bits). Number of hosts per subnet = 2^(host_bits) - 2. When splitting a /24 into /26s, you borrow 2 bits (26-24=2), giving 2^2 = 4 subnets, each with 2^6 - 2 = 62 hosts.

04

DNS Resolution

How domain names are translated into IP addresses through a hierarchical, distributed naming system that underpins virtually all internet communication.

DNS Hierarchy

The Domain Name System operates as a hierarchical, distributed database with four key server types, each responsible for a different level of the resolution chain.

Root Servers
13 Named Authorities (A–M)
TLD Servers
.com .net .org + Country Codes
Authoritative NS
Store Actual DNS Records
Recursive Resolvers
ISP / 8.8.8.8 / 1.1.1.1
  • Root Servers — 13 named authorities (A through M) operated by organizations worldwide. They maintain knowledge of TLD nameservers and are the starting point for resolving any domain.
  • TLD Servers — Handle top-level domains like .com, .net, .org, and country codes (.uk, .de, .jp). They know which authoritative nameservers handle each registered domain.
  • Authoritative Nameservers — The final authority for a domain. They store the actual DNS records (A, AAAA, MX, CNAME, etc.) and return definitive answers.
  • Recursive Resolvers — The first stop for your DNS query. Your ISP, Google (8.8.8.8), or Cloudflare (1.1.1.1) operate these. They cache results to speed up subsequent lookups.

Resolution Chain

When you type a URL into your browser, a multi-step resolution process unfolds to translate the domain name into a routable IP address.

Step 1
Browser checks local cache
Step 2
OS checks /etc/hosts, then system DNS cache
Step 3
Query sent to recursive resolver
Step 4
Resolver checks its own cache
Step 5
Query root server Get TLD referral
Step 6
Query TLD server Get authoritative NS
Step 7
Query authoritative NS Get IP address
Step 8
IP returned to client, cached per TTL

DNS Record Types

Type Purpose Example
A Domain → IPv4 example.com → 192.0.2.1
AAAA Domain → IPv6 example.com → 2001:db8::1
CNAME Alias www → example.com
MX Mail server Priority 10 mail.example.com
TXT Arbitrary text SPF, DKIM verification
NS Nameserver ns1.example.com
SOA Zone authority Serial, refresh, retry, expire
PTR Reverse lookup IP → domain
SRV Service locator _sip._tcp.example.com

DNS Commands

# Basic lookups
dig example.com                    # A record query
dig example.com MX                 # Mail server lookup
dig +short example.com AAAA        # Quick IPv6 lookup
dig @8.8.8.8 example.com          # Query specific server
dig +trace example.com             # Full resolution trace

# nslookup
nslookup example.com               # Basic lookup
nslookup -type=MX example.com     # MX records
nslookup example.com 8.8.8.8      # Use specific server

# Reverse DNS
dig -x 192.0.2.1                   # Reverse lookup
host 192.0.2.1                     # Simple reverse

# Cache management
# Linux: systemd-resolve --flush-caches
# macOS: sudo dscacheutil -flushcache
# Windows: ipconfig /flushdns

DNSSEC

DNSSEC (DNS Security Extensions) adds cryptographic signing to DNS data to prevent spoofing and cache poisoning attacks. It works by establishing a chain of trust from the root zone down to individual records.

  • DNSKEY — Public key used to verify signatures
  • RRSIG — Signature over a set of DNS records
  • DS — Delegation Signer, links parent and child zones
  • NSEC / NSEC3 — Authenticated denial of existence
// DNSSEC Limitation

DNSSEC provides authentication and integrity but does NOT provide confidentiality. DNS queries and responses are still transmitted in plaintext. For encrypted DNS, use DNS-over-HTTPS (DoH) or DNS-over-TLS (DoT).

Common DNS Gotchas

// CNAME at Apex

CNAME records cannot be used on apex (root) domains per RFC 1034. Use ALIAS or ANAME records instead, which are provider-specific extensions that solve this limitation.

// MX Target Restriction

MX records must point to an A or AAAA record, never to a CNAME. Pointing MX to a CNAME violates RFC 2181 and will cause mail delivery failures with strict resolvers.

// TTL & Propagation

TTL (Time to Live) directly affects how long records are cached. Before making DNS changes, lower the TTL well in advance (e.g., to 300 seconds) so the old record expires quickly from caches worldwide.

// Case Insensitivity

DNS is case-insensitive per RFC 4343. Example.COM and example.com resolve identically. However, case is preserved in records for display purposes.

05

Core Protocols

The fundamental transport and application-layer protocols that form the backbone of modern networking — from TCP reliability to HTTP communication.

TCP vs UDP

Feature TCP UDP
Connection Connection-oriented (3-way handshake) Connectionless
Reliability Guaranteed delivery, ACKs Best-effort, no guarantees
Ordering In-order delivery (sequence numbers) No ordering
Speed Slower (reliability overhead) Faster (minimal overhead)
Flow Control Sliding window None
Header Size 20–60 bytes 8 bytes
Use Cases HTTP, FTP, SSH, SMTP DNS, VoIP, streaming, gaming

TCP Three-Way Handshake

TCP establishes a reliable connection using a three-way handshake before any data is transmitted. Each side exchanges sequence numbers to synchronize.

Client                    Server
  |  1. SYN (seq=x)         |
  |------------------------->|
  |  2. SYN-ACK (seq=y,      |
  |     ack=x+1)             |
  |<-------------------------|
  |  3. ACK (ack=y+1)        |
  |------------------------->|
  |  Connection Established   |

Connection teardown uses a 4-way process: the initiator sends FIN, receiver sends ACK, then receiver sends its own FIN, and initiator sends final ACK. This allows each side to finish transmitting independently.

Client                    Server
  |  1. FIN                  |
  |------------------------->|
  |  2. ACK                  |
  |<-------------------------|
  |  3. FIN                  |
  |<-------------------------|
  |  4. ACK                  |
  |------------------------->|
  |  Connection Closed        |

DHCP (DORA Process)

Dynamic Host Configuration Protocol automatically assigns IP addresses and network parameters using a four-step broadcast process known as DORA.

D — Discover
Client broadcasts 0.0.0.0 → 255.255.255.255 (UDP 67/68)
O — Offer
Server responds with IP, mask, gateway, DNS, lease time
R — Request
Client accepts offer (broadcast, identifies chosen server)
A — Acknowledge
Server confirms, client configures interface
Server Port
UDP 67
Client Port
UDP 68
Lease Renewal
T1 = 50% of Lease

HTTP / HTTPS

The Hypertext Transfer Protocol is the foundation of web communication. HTTPS adds TLS encryption for secure data transfer.

HTTP Methods:

Method Purpose Idempotent Safe
GET Retrieve Yes Yes
POST Create No No
PUT Replace Yes No
PATCH Partial update No No
DELETE Remove Yes No
HEAD Headers only Yes Yes

Status Codes:

Range Category Key Codes
1xx Informational 100 Continue
2xx Success 200 OK, 201 Created, 204 No Content
3xx Redirect 301 Permanent, 302 Found, 304 Not Modified
4xx Client Error 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found
5xx Server Error 500 Internal, 502 Bad Gateway, 503 Unavailable

TLS Handshake (simplified): Client Hello → Server Hello + certificate → Verify certificate chain → Session key exchange (ECDHE) → Encrypted communication begins.

HTTP Port
TCP 80
HTTPS Port
TCP 443

SMTP & Email Flow

Email traverses multiple protocols and servers from sender to recipient. The journey involves submission, relay, delivery, and retrieval stages.

MUA
Mail User Agent (your email client)
MSA :587
Mail Submission Agent (authenticated relay)
MTA :25
Mail Transfer Agent → MTA (server-to-server relay)
MDA
Mail Delivery Agent (stores in mailbox)
Recipient
IMAP :993 / POP3 :995 (retrieval)
// Email Authentication

SPF (Sender Policy Framework) defines which IPs can send for a domain. DKIM (DomainKeys Identified Mail) adds cryptographic signatures to verify message integrity. DMARC ties SPF and DKIM together with a policy for handling failures. All three are essential for deliverability and preventing spoofing.

SNMP

Simple Network Management Protocol enables monitoring and management of network devices. Agents on devices expose metrics via a Management Information Base (MIB).

Version Security Notes
v1 Community strings (plaintext) Legacy, avoid
v2c Community strings (plaintext) 64-bit counters, bulk operations
v3 Authentication + encryption Recommended for all environments
Agent Port
UDP 161
Trap Port
UDP 162
// Security Advisory

Always use SNMPv3 in production. SNMPv1 and v2c transmit community strings in plaintext, making them trivially interceptable. Default community strings like "public" and "private" are the first thing attackers check.

NTP

Network Time Protocol synchronizes clocks across networked systems using a stratum hierarchy. Accurate time is critical for logging, authentication (Kerberos), TLS certificates, and distributed systems.

Stratum Source Accuracy
0 Atomic / GPS clock Microseconds
1 Direct connection to stratum 0 Microseconds
2 Synced to stratum 1 Milliseconds
3–15 Each level synced to previous Increasing drift
16 Unsynchronized N/A
Port
UDP 123
Common Servers
pool.ntp.org
Alternatives
time.google.com / time.nist.gov
06

Routing & Switching

How packets find their way across networks through routing tables, dynamic protocols, VLANs, and Layer 2/3 forwarding decisions.

Routing Tables

Every host and router maintains a routing table that determines where to forward packets. The ip route command displays the current routing decisions.

$ ip route show
default via 192.168.1.1 dev eth0 proto dhcp metric 100
10.0.0.0/8 via 10.1.1.1 dev tun0
172.16.0.0/16 dev docker0 proto kernel scope link src 172.16.0.1
192.168.1.0/24 dev eth0 proto kernel scope link src 192.168.1.100
  • default via 192.168.1.1Default route. Gateway of last resort for all unknown destinations.
  • 10.0.0.0/8 via 10.1.1.1Static route. Traffic to 10.x.x.x goes through the VPN tunnel gateway.
  • 172.16.0.0/16 dev docker0Kernel route. Directly connected via Docker bridge interface.
  • 192.168.1.0/24 dev eth0Connected route. Local network directly attached to eth0.

Route codes (common in Cisco/routing daemon output):

C
Connected (directly attached)
S
Static (manually configured)
O
OSPF learned
B
BGP learned
D
EIGRP learned

Static vs Dynamic Routing

Aspect Static Dynamic
Config Manual Auto via protocol
Updates Manual when topology changes Automatic adaptation
Resources Low (no protocol overhead) CPU + bandwidth for updates
Security More secure (no advertisements) Protocol exchanges visible
Failover No automatic rerouting Automatic alternate paths
Best For Small / stub networks Large enterprise networks

OSPF vs BGP

Feature OSPF (IGP) BGP (EGP)
Scope Within an Autonomous System Between Autonomous Systems
Algorithm Link-state (Dijkstra) Path vector + policy
Convergence Fast (seconds) Slower (policy evaluation)
Scale ~500 routers/area Internet scale
Use Case Corporate LAN / Data Center Internet edge, WAN peering
// Best Practice

Use OSPF for internal routing within your network. Deploy BGP at the edge where you peer with ISPs or other autonomous systems. Many enterprise networks run both: OSPF internally, BGP externally.

VLANs (802.1Q)

Virtual LANs logically segment a physical network into separate broadcast domains. IEEE 802.1Q defines the standard by adding a 4-byte tag to Ethernet frames containing a TPID (Tag Protocol Identifier) and TCI (Tag Control Information) with a VLAN ID ranging from 0–4094.

Access Port
Belongs to a single VLAN. Frames are untagged. Used for end devices (PCs, printers, phones).
Trunk Port
Carries multiple VLANs. Frames are tagged with 802.1Q headers. Used between switches and routers.
  • Logical segmentation — Group users by function regardless of physical location
  • Reduced broadcast domains — Broadcasts stay within the VLAN, reducing network noise
  • Security isolation — Traffic between VLANs must pass through a router or L3 switch with ACLs

ARP

Address Resolution Protocol maps IP addresses to MAC addresses on a local network segment. It operates at Layer 2 and is essential for Ethernet communication.

Step 1
Host needs MAC for destination IP
Step 2
Broadcasts ARP request: "Who has 192.168.1.1?"
Step 3
Target replies with its MAC address (unicast)
Step 4
Requester caches in ARP table (5–20 min TTL)
ip neigh show                  # Show ARP table (modern)
arp -a                          # Show ARP table (legacy)
arping -I eth0 192.168.1.1    # ARP ping specific host
ip neigh flush dev eth0         # Clear ARP cache
// Gratuitous ARP

A gratuitous ARP is an unsolicited ARP reply broadcast by a host to announce its IP-to-MAC mapping. Used during failover (VRRP/HSRP), IP address changes, and NIC replacements to update other hosts' ARP caches immediately.

L2 vs L3 Switches

Feature Layer 2 Layer 3
Forwarding MAC-based IP-based (routing)
Inter-VLAN Cannot route between VLANs Routes natively (SVI interfaces)
Protocols STP, VLANs OSPF, BGP, static routes
Use Case Access layer Distribution / core layer

Spanning Tree (STP)

Spanning Tree Protocol (IEEE 802.1D) prevents Layer 2 loops in networks with redundant paths. Without STP, broadcast storms would overwhelm the network.

STP elects a root bridge (lowest Bridge ID) and assigns port roles:

  • Root Port — Best path toward the root bridge (one per non-root switch)
  • Designated Port — Best path away from root on each segment (forwarding)
  • Blocked Port — Redundant path, disabled to prevent loops

Port states (classic STP): Blocking → Listening → Learning → Forwarding. Total convergence time: 30–50 seconds.

// Modern Alternative: RSTP

Rapid Spanning Tree Protocol (IEEE 802.1w) converges in 1–2 seconds instead of STP's 30–50 seconds. It introduces new port roles (Alternate, Backup) and port states (Discarding, Learning, Forwarding). RSTP is backward-compatible with STP and should be used in all modern deployments.

07

Firewalls & Security

Network security fundamentals — from packet filtering and stateful inspection to NAT traversal and zero trust architectures.

Stateful vs Stateless Firewalls

Aspect Stateless Stateful
Inspection Individual packets Connection state tracking
Memory No session state Maintains connection tables
Decision Headers only (IP, port, protocol) Context + state (NEW, ESTABLISHED, RELATED, INVALID)
Performance Faster (less processing) Slightly slower
Security Lower (no context) Higher (session awareness)
Example Traditional ACLs iptables/nftables with conntrack
// Connection States

Stateful firewalls track connections in four states: NEW (first packet), ESTABLISHED (ongoing), RELATED (associated, e.g. FTP data), INVALID (malformed).

Access Control Lists (ACLs)

Ordered permit/deny rules, applied to interfaces. Sequential evaluation, first match wins, implicit deny-all at end.

iptables

Chain Purpose Traffic
INPUT Destined for local system Incoming
OUTPUT Generated by local system Outgoing
FORWARD Routed through system Transit
PREROUTING Before routing decision DNAT
POSTROUTING After routing decision SNAT

Targets: ACCEPT, DROP, REJECT, LOG, MASQUERADE, DNAT, SNAT

# Allow established connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Allow SSH from specific subnet
iptables -A INPUT -p tcp --dport 22 -s 10.0.0.0/8 -j ACCEPT

# Allow HTTP/HTTPS
iptables -A INPUT -p tcp -m multiport --dports 80,443 -j ACCEPT

# Drop all other incoming
iptables -A INPUT -j DROP

# List rules with line numbers
iptables -L -n -v --line-numbers

# Save and restore
iptables-save > /etc/iptables/rules.v4
iptables-restore < /etc/iptables/rules.v4

nftables (Modern Replacement)

// nftables Adoption

nftables is the default in Debian, Fedora, Ubuntu, RHEL 8+. iptables is in legacy mode. Kubernetes 1.33+ uses nftables.

Key improvements: unified IPv4/IPv6/ARP, cleaner syntax, incremental updates, better performance.

# Create table and chain
nft add table inet filter
nft add chain inet filter input { type filter hook input priority 0 \; policy drop \; }

# Allow established
nft add rule inet filter input ct state established,related accept

# Allow SSH and HTTP
nft add rule inet filter input tcp dport { 22, 80, 443 } accept

# Allow ICMP
nft add rule inet filter input icmp type echo-request accept

# List rules
nft list ruleset

# Compare: iptables vs nftables
# iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# nft add rule inet filter input tcp dport 22 accept

NAT/PAT

Type Direction Use Case How It Works
SNAT Outbound Private → Public IP Rewrites source IP
DNAT Inbound Port forwarding Rewrites destination IP
MASQUERADE Outbound Dynamic public IP (DHCP) SNAT with auto IP
PAT Both Many-to-one using ports Maps internal hosts to ports
# SNAT: Static source translation
iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j SNAT --to-source 203.0.113.10

# MASQUERADE: Dynamic SNAT
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

# DNAT: Port forwarding (public:443 → internal:8443)
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 443 -j DNAT --to-destination 192.168.1.10:8443

# Enable IP forwarding
sysctl -w net.ipv4.ip_forward=1
echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf

Zero Trust Networking

Core principles:

  • Never Trust, Always Verify — Authenticate every user, device, application
  • Least Privilege Access — Minimum permissions for minimum time
  • Assume Breach — Design for detection, isolation, containment

Key implementation:

  • Replace VPN with identity-aware proxies
  • Micro-segmentation (VLANs, software-defined)
  • MFA for all access
  • Continuous monitoring (EDR/XDR)
  • Service mesh for workload-to-workload auth
// Zero Trust Misconception

Zero trust is NOT removing your firewall. It means no implicit trust zones — verify identity at every access point.

08

VPNs & Tunneling

Virtual private networks and tunneling protocols — from site-to-site IPSec to modern WireGuard and SSH port forwarding.

VPN Protocol Comparison

Protocol Speed Security Complexity Best For
WireGuard Excellent Strong Low Default choice 2026
OpenVPN Good Strong High Compliance, legacy
IPSec Good Strong High Site-to-site
IKEv2/IPSec Excellent Strong Medium Mobile users
SSH Tunnels Good Strong Low Ad-hoc admin access
// Deprecated Protocol

NEVER use PPTP — known security vulnerabilities. Deprecated by Microsoft.

IPSec

IKE Phases:

  • Phase 1 — Negotiate encryption, auth, hashing, DH group → creates ISAKMP SA (control channel)
  • Phase 2 — Negotiate IPSec params (ESP/AH) → creates IPSec SA (data tunnel)

Protocols:

Protocol Encryption Auth Integrity Use
ESP Yes Yes Yes Standard (confidentiality + auth)
AH No Yes Yes Legacy (auth only, rarely used)

Modes:

Mode IP Header Use Case
Transport Original preserved Host-to-host
Tunnel New header added Site-to-site (most common)

WireGuard

Key advantages: ~4,000 lines of code (vs OpenVPN ~100,000+), 60% faster in real tests, kernel-level, modern crypto (ChaCha20, Curve25519), seamless roaming.

# Server (/etc/wireguard/wg0.conf)
[Interface]
PrivateKey = <server-private-key>
Address = 10.0.0.1/24
ListenPort = 51820

[Peer]
PublicKey = <client-public-key>
AllowedIPs = 10.0.0.2/32

# Client
[Interface]
PrivateKey = <client-private-key>
Address = 10.0.0.2/24
DNS = 1.1.1.1

[Peer]
PublicKey = <server-public-key>
Endpoint = vpn.example.com:51820
AllowedIPs = 0.0.0.0/0
PersistentKeepalive = 25
# Start/stop
wg-quick up wg0
wg-quick down wg0

# Status
wg show
wg show wg0

# Generate keys
wg genkey | tee privatekey | wg pubkey > publickey

OpenVPN

Still relevant for: compliance requirements, TCP mode (WireGuard UDP only), restrictive firewalls (can run on TCP 443), existing PKI infrastructure.

port 1194
proto udp
dev tun
ca ca.crt
cert server.crt
key server.key
dh dh2048.pem
server 10.8.0.0 255.255.255.0
push "redirect-gateway def1"
push "dhcp-option DNS 8.8.8.8"

SSH Tunneling

Flag Type Direction Use Case
-L Local Forward Local → Remote Access remote service locally
-R Remote Forward Remote → Local Expose local service remotely
-D Dynamic (SOCKS) SOCKS proxy Browser/app proxying
# Local: Access remote DB from localhost:3306
ssh -L 3306:db-server:3306 user@jump-host

# Remote: Share local web server on remote:8080
ssh -R 8080:localhost:80 user@public-server

# Dynamic SOCKS proxy on localhost:1080
ssh -D 1080 user@proxy-server

# Background tunnel (no shell)
ssh -fN -L 8080:internal:80 user@gateway

When to Use Which

  • Remote workers — WireGuard (primary), IKEv2 (mobile fallback)
  • Site-to-site — IPSec tunnel mode
  • Developers/admins — SSH tunneling for ad-hoc access
  • Compliance-heavy — OpenVPN with full PKI
  • Routing over WAN — GRE + IPSec (multicast support)
09

Load Balancing & High Availability

Distributing traffic across servers, health checking, session persistence, and ensuring uptime through redundancy patterns.

L4 vs L7 Load Balancing

Feature Layer 4 (Transport) Layer 7 (Application)
Decisions IP + port URL, headers, cookies, content
Speed Faster (no content inspection) Slower (deep inspection)
SSL Pass-through or terminate Always terminate + re-encrypt
Routing All traffic for connection to same backend Request-level routing
Use Case TCP/UDP services, databases HTTP APIs, microservices
Examples HAProxy (TCP mode), LVS Nginx, HAProxy (HTTP mode), Envoy

Algorithms

Algorithm How It Works Best For
Round Robin Sequential rotation Equal-capacity servers
Weighted Round Robin Proportional by weight Mixed-capacity servers
Least Connections Route to fewest active Variable request duration
IP Hash Hash source IP → consistent backend Session persistence
Least Response Time Route to fastest responder Latency-sensitive apps
Random Random selection Large server pools

Health Checks

Types: TCP connect, HTTP GET (check status code), custom scripts. Key parameters: interval, timeout, threshold (unhealthy after N failures), recovery threshold.

backend web_servers
    option httpchk GET /health
    http-check expect status 200
    server web1 192.168.1.10:8080 check inter 5s fall 3 rise 2
    server web2 192.168.1.11:8080 check inter 5s fall 3 rise 2
    server web3 192.168.1.12:8080 check inter 5s fall 3 rise 2 backup

Session Persistence

Methods:

  • Source IP — Hash client IP → same backend (breaks behind NAT)
  • Cookie-based — LB inserts/reads cookie with backend ID
  • URL parameter — Session ID in URL
  • SSL Session ID — TLS session → same backend
// Stateless Architecture

Stateless architectures (shared session stores like Redis) eliminate the need for sticky sessions.

DNS Load Balancing

How it works: Multiple A records for same domain, DNS rotates responses. Pros: Simple, no special infrastructure. Cons: No health checks, TTL caching delays failover, no session persistence.

High Availability Patterns

  • Active-Passive — Standby takes over on failure (VRRP/keepalived)
  • Active-Active — All nodes serve traffic simultaneously
  • Floating/Virtual IP — VIP moves between nodes via VRRP

VRRP/keepalived example:

# /etc/keepalived/keepalived.conf
vrrp_instance VI_1 {
    state MASTER
    interface eth0
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass secret123
    }
    virtual_ipaddress {
        192.168.1.100/24
    }
}
10

Troubleshooting Toolkit

Comprehensive diagnostic reference — from systematic methodology to packet-level analysis with ping, traceroute, tcpdump, nmap, Wireshark, and more.

Troubleshooting Methodology

Decision flow for network issues — work from the bottom of the stack upward:

  • 1. Identify the problem — What exactly isn't working? (connectivity, DNS, specific service, slow performance)
  • 2. Check local configip addr, ip route, /etc/resolv.conf
  • 3. Test connectivityping localhostping gatewayping external IPping domain
  • 4. Check DNSdig example.com, nslookup
  • 5. Check ports/servicesss -tlnp, nmap
  • 6. Trace the pathtraceroute, mtr
  • 7. Capture traffictcpdump, Wireshark
// Bottom-Up Rule

Always start at the bottom of the stack and work up. If ping to the gateway fails, don't bother checking DNS.

ping

# Basic connectivity test
ping -c 4 192.168.1.1              # Send 4 packets
ping -c 4 8.8.8.8                   # Test internet
ping -c 4 example.com               # Test DNS + connectivity

# Advanced options
ping -i 0.2 host                    # 200ms interval (fast ping)
ping -s 1472 -M do host             # MTU test (don't fragment)
ping -t 5 host                      # Set TTL
ping -W 2 host                      # 2-second timeout
ping -f host                        # Flood ping (careful!)

# Interpret results
# 64 bytes from 8.8.8.8: icmp_seq=1 ttl=118 time=12.3 ms
# time = round-trip latency
# ttl  = hops remaining (start 64 or 128)
# packet loss = reliability indicator

traceroute & mtr

# traceroute (uses UDP by default on Linux, ICMP on Windows)
traceroute example.com               # Standard trace
traceroute -I example.com            # Use ICMP instead of UDP
traceroute -T -p 443 example.com    # TCP trace on port 443
traceroute -n example.com            # Skip DNS resolution

# mtr (combines ping + traceroute, continuous monitoring)
mtr example.com                      # Interactive mode
mtr -r -c 100 example.com           # Report mode, 100 cycles
mtr -n example.com                   # No DNS resolution
mtr --tcp -P 443 example.com        # TCP mode on port 443

Reading mtr output: Key columns are Host, Loss%, Snt (sent), Last, Avg, Best, Wrst (worst), and StDev. High loss at one hop but not subsequent hops indicates ICMP rate limiting (normal). High loss from one hop onward indicates a real problem at that hop.

tcpdump

# Basic capture
tcpdump -i eth0                      # Capture all on interface
tcpdump -i any                       # Capture on all interfaces
tcpdump -i eth0 -n                   # Don't resolve hostnames
tcpdump -i eth0 -c 100              # Capture 100 packets

# Filters
tcpdump -i eth0 host 192.168.1.100  # Specific host
tcpdump -i eth0 port 80              # Specific port
tcpdump -i eth0 src 10.0.0.1        # Source IP only
tcpdump -i eth0 dst port 443        # Destination port
tcpdump -i eth0 'tcp[tcpflags] & tcp-syn != 0'  # SYN packets

# Save and read
tcpdump -i eth0 -w capture.pcap      # Write to file
tcpdump -r capture.pcap              # Read from file
tcpdump -r capture.pcap -A           # Read with ASCII output

# Combine filters
tcpdump -i eth0 'host 10.0.0.1 and port 443'
tcpdump -i eth0 'src net 192.168.1.0/24 and dst port 80'

ss (Socket Statistics)

# Show listening sockets
ss -tlnp                              # TCP listening, numeric, process
ss -ulnp                              # UDP listening
ss -tlnp | grep :80                  # Find what's on port 80

# Show all connections
ss -tan                               # All TCP, numeric
ss -tan state established             # Only established
ss -tan state time-wait              # Only TIME_WAIT

# Show socket statistics
ss -s                                 # Summary statistics

# Filter by port or address
ss -tn dst :443                      # Connections to port 443
ss -tn src 192.168.1.100             # Connections from IP
ss -tn 'dport == :80 or dport == :443'  # Multiple ports
// ss vs netstat

ss replaces the legacy netstat command. Use ss on modern systems — it's faster and more feature-rich.

nmap

# Host discovery
nmap -sn 192.168.1.0/24             # Ping sweep (no port scan)

# Port scanning
nmap -sS host                        # SYN scan (stealth, default)
nmap -sT host                        # TCP connect scan
nmap -sU host                        # UDP scan (slow)
nmap -p 1-1000 host                  # Specific port range
nmap -p 22,80,443 host              # Specific ports
nmap -p- host                        # All 65535 ports

# Service/version detection
nmap -sV host                        # Service versions
nmap -sV --version-intensity 5 host  # Aggressive detection
nmap -O host                         # OS detection
nmap -A host                         # Aggressive (OS + version + scripts + traceroute)

# Output formats
nmap -oN scan.txt host              # Normal output
nmap -oX scan.xml host              # XML output
nmap -oG scan.grep host             # Grepable output
// Authorization Required

Only scan networks you own or have explicit authorization to test. Unauthorized scanning may violate laws.

Wireshark Filters

Common display filters:

# Protocol filters
tcp                                   # All TCP traffic
udp                                   # All UDP traffic
dns                                   # DNS queries/responses
http                                  # HTTP traffic
tls                                   # TLS/SSL traffic

# Address filters
ip.addr == 192.168.1.100             # Source or destination
ip.src == 10.0.0.1                   # Source only
ip.dst == 10.0.0.1                   # Destination only

# Port filters
tcp.port == 443                      # Source or destination port
tcp.dport == 80                      # Destination port only
tcp.port in {80,443,8080}           # Multiple ports

# Combined
http && ip.addr == 192.168.1.100    # HTTP from/to specific host
tcp.flags.syn == 1                   # SYN packets only
tcp.analysis.retransmission         # Retransmissions (troubleshooting)
dns.flags.response == 0             # DNS queries only

curl for Network Testing

# Basic HTTP testing
curl -I https://example.com          # Headers only
curl -v https://example.com          # Verbose (full handshake)
curl -o /dev/null -s -w "HTTP %{http_code}\n" URL  # Status code only

# Timing breakdown
curl -o /dev/null -s -w "\
  DNS:        %{time_namelookup}s\n\
  Connect:    %{time_connect}s\n\
  TLS:        %{time_appconnect}s\n\
  TTFB:       %{time_starttransfer}s\n\
  Total:      %{time_total}s\n" https://example.com

# Testing specific features
curl -4 example.com                   # Force IPv4
curl -6 example.com                   # Force IPv6
curl --resolve example.com:443:1.2.3.4 https://example.com  # Override DNS
curl -k https://self-signed.example.com  # Skip TLS verification

ip Command Reference

# Interfaces
ip addr show                         # Show all interfaces
ip addr show dev eth0                # Specific interface
ip link set eth0 up                  # Enable interface
ip link set eth0 down                # Disable interface

# IP addresses
ip addr add 192.168.1.100/24 dev eth0    # Add IP
ip addr del 192.168.1.100/24 dev eth0    # Remove IP

# Routes
ip route show                        # Show routing table
ip route add 10.0.0.0/8 via 192.168.1.1  # Add route
ip route del 10.0.0.0/8              # Delete route
ip route add default via 192.168.1.1  # Set default gateway

# ARP/Neighbors
ip neigh show                        # Show ARP table
ip neigh flush dev eth0              # Clear ARP cache