CUNP cheat sheet
CUNP · Keep the key ideas within reach.
Unix/Linux System and Network Fundamentals
Every process has a PID; /proc//fd lists open file descriptors, and /proc/net/{tcp,udp,unix} exposes kernel socket tables in text form.
File permission bits: r=4, w=2, x=1 per owner/group/other triad; special bits setuid (4000), setgid (2000), sticky (1000). Directories need x to traverse and r to list names.
Signals: SIGHUP(1) hangup, SIGINT(2) Ctrl-C, SIGKILL(9) uncatchable, SIGTERM(15) default graceful stop, SIGSTOP(19) uncatchable pause. kill -l lists names.
Standard streams: fd 0 stdin, 1 stdout, 2 stderr.
2>&1duplicates stderr onto stdout's current target; order matters (cmd >f 2>&1vscmd 2>&1 >f).Inodes hold metadata (mode, uid, gid, size, timestamps, link count); hard links share an inode, symlinks store a path and can dangle.
df -ireports inode exhaustion.systemd unit types: .service, .socket, .timer, .target, .mount.
systemctl status,journalctl -u <unit> -f, andsystemd-analyze blameare the primary inspection commands.Load average counts runnable plus uninterruptible (D-state) tasks averaged over 1, 5, 15 minutes; compare against CPU count from
nproc, not against 1.0.Unix domain sockets appear as S in
ls -land as type u inss -x; they are local-only and often used by daemons such as dbus and Docker.
Network Architecture, Protocols, and the TCP/IP Stack
TCP header flags: SYN, ACK, FIN, RST, PSH, URG. Connection setup is SYN, SYN-ACK, ACK; teardown is FIN-ACK pairs or RST for abort.
TCP state machine includes LISTEN, SYN_SENT, SYN_RECV, ESTABLISHED, FIN_WAIT1/2, CLOSE_WAIT, LAST_ACK, TIME_WAIT (2*MSL, typically 60s on Linux).
UDP has an 8-byte header (src port, dst port, length, checksum) and no ordering, retransmission, or congestion control; DNS, DHCP, NTP, and QUIC build reliability above it.
IPv4 header is 20 bytes minimum; key fields are TTL, protocol (6=TCP, 17=UDP, 1=ICMP), fragmentation offset, and header checksum. IPv6 uses a fixed 40-byte header with a hop limit and no header checksum.
Private ranges: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16; link-local 169.254.0.0/16 (IPv4) and fe80::/10 (IPv6). Loopback is 127.0.0.0/8 and ::1.
Well-known ports: 22 SSH, 25 SMTP, 53 DNS, 67/68 DHCP, 80 HTTP, 123 NTP, 443 HTTPS, 514 syslog, 3306 MySQL, 5432 PostgreSQL.
ICMP types: 0 echo reply, 3 destination unreachable (with codes such as 3 port unreachable, 4 fragmentation needed), 8 echo request, 11 time exceeded (traceroute mechanism).
MTU vs MSS: MSS = MTU - IP header - TCP header; 1500-byte Ethernet MTU gives 1460-byte IPv4 TCP MSS. Path MTU discovery relies on ICMP type 3 code 4 or IPv6 Packet Too Big.
Unix Network Configuration and Interface Management
Legacy tools:
ifconfig,route -n,netstat -i. Modern replacements:ip addr,ip route,ip link,ss. Both read the same kernel state; iproute2 is the maintained path.ip addr add 192.0.2.10/24 dev eth0adds an address;ip link set eth0 upenables the interface;ip route add default via 192.0.2.1sets the gateway.Persistent config locations vary: Debian/Ubuntu use /etc/network/interfaces or netplan YAML in /etc/netplan; RHEL family uses /etc/sysconfig/network-scripts/ifcfg-* or NetworkManager keyfiles.
ip -s linkshows RX/TX packet, error, and drop counters;ip -s link show eth0narrows it. Rising drops on RX often indicate a full ring buffer or socket backlog.VLAN tagging:
ip link add link eth0 name eth0.100 type vlan id 100. Bonding modes include balance-rr(0), active-backup(1), and 802.3ad LACP(4).ethtool eth0reports link speed, duplex, and driver;ethtool -S eth0dumps NIC statistics;ethtool -k eth0shows offload features such as TSO, GSO, and GRO.resolvectl status(systemd-resolved) or /etc/resolv.conf shows resolver state;ip neighdisplays the ARP/NDP neighbor cache and its REACHABLE/STALE/FAILED states.ip netns add labcreates a network namespace;ip netns exec lab <cmd>runs a command inside it, giving an isolated interface and routing table for testing.
Network Services and Daemon Administration
ss -lntuplists listening TCP and UDP sockets with process names;ss -tan state establishedfilters by TCP state. Requires privilege to see other users' PIDs.A daemon is a background process detached from a controlling terminal; under systemd,
Type=simple,forking, andnotifydescribe how startup completion is signaled.systemctl enable --now <unit>creates the symlink for boot start and starts it immediately;disableremoves the link but does not stop a running instance.Socket activation: a .socket unit holds the port and passes the listening fd to the .service on first connection, allowing the service to start on demand.
journalctl -u nginx --since '1 hour ago' -p errfilters by unit, time, and syslog priority. Priorities run 0 emerg to 7 debug.Configuration test before reload is standard practice:
nginx -t,apachectl configtest,sshd -t,named-checkconf. Reload (SIGHUP) re-reads config without dropping listeners in most daemons.DHCP DORA: Discover, Offer, Request, Ack. Lease timers are renewal (T1, default 50% of lease) and rebinding (T2, default 87.5%).
DNS record types: A, AAAA, CNAME (no other records at the same name), MX (with preference), NS, PTR, TXT, SOA (serial, refresh, retry, expire, minimum TTL).
Routing, Firewalling, and Traffic Control
Longest-prefix match wins in routing; among equal prefixes, the lowest metric (or administrative distance) is preferred.
ip route get 203.0.113.5shows the chosen path.Linux uses policy routing with rules:
ip rule add from 10.0.0.0/24 table 100plusip route add default via 10.0.0.1 table 100. Rules are evaluated by priority number, lowest first.nftables replaced iptables/ip6tables/arptables/ebtables. Base chains attach to hooks (prerouting, input, forward, output, postrouting) with a type (filter, nat, route) and priority.
Netfilter hook order for a locally destined packet: prerouting, input, local process, output, postrouting. Forwarded traffic traverses prerouting, forward, postrouting.
NAT: SNAT/masquerade rewrites source in postrouting; DNAT rewrites destination in prerouting. Conntrack tracks flows;
conntrack -Llists them andnf_conntrack_maxbounds the table.Default policies: DROP inbound with explicit ACCEPT rules, and place an established/related conntrack accept rule early to avoid re-evaluating every packet.
tc qdiscs: pfifo_fast is default, fq_codel is common for bufferbloat control, netem adds delay/loss/jitter for testing, and HTB/tbf shape bandwidth.
tc -s qdisc showprints counters.ip route add blackhole 198.51.100.0/24silently discards;unreachablereturns ICMP unreachable;prohibitreturns administratively prohibited. These are useful for RTBH filtering.
Network Security, Authentication, and Access Control
TLS handshake (1.2): ClientHello, ServerHello plus certificate, key exchange, Finished. TLS 1.3 cuts a round trip and mandates forward-secret key exchange such as ECDHE.
SSH key auth: client proves possession of the private key by signing a session-bound challenge; the server checks ~/.ssh/authorized_keys.
ssh-keygen -t ed25519is the current default choice.SELinux modes are Enforcing, Permissive, Disabled; contexts are user:role:type:level.
getenforce,ls -Z,ausearch -m avc, andrestoreconare core commands. AppArmor uses path-based profiles.PAM stacks: /etc/pam.d/ lists type (auth, account, password, session), control flag (required, requisite, sufficient, optional), and module.
pam_tally2/faillockimplement lockout.File-based access control: umask subtracts from 666 (files) and 777 (directories). A umask of 027 yields files 640 and directories 750.
sudopolicy lives in /etc/sudoers and /etc/sudoers.d; edit withvisudo. Entries areuser host=(runas) command; NOPASSWD removes the password prompt.Certificate validation checks chain to a trusted root, validity dates, hostname/SAN match, and revocation via CRL or OCSP.
openssl s_client -connect host:443 -servername hostinspects a live chain.Defense in depth on a host: least-privilege service accounts, key-only SSH with
PermitRootLogin no, firewall default-deny, and auditd rules on sensitive paths such as /etc/passwd.
Troubleshooting, Monitoring, and Performance Analysis
Layer-by-layer triage:
ip addr(L2/L3 local),ip routeand ping gateway (L3),dig @resolver(DNS),nc -vz host portorss -tn(L4), then application logs.tracerouteuses UDP by default on Linux and ICMP with-I;mtrcombines ping and traceroute in a continuous view. Stars can mean filtering, not necessarily failure.tcpdump -ni eth0 'tcp port 443 and host 203.0.113.5'captures with BPF filters;-w file.pcapwrites for Wireshark.-s 0captures full packets.TIME_WAIT accumulation on a busy server is normal; it indicates the local side closed first. Tune with
tcp_tw_reuseonly after confirming the actual bottleneck.ss -sgives a socket summary;ss -tishows per-connection RTT, cwnd, retransmits, and rto. High retransmits point to loss or congestion, not always to a slow app.Latency vs throughput:
pingmeasures RTT,iperf3measures achievable bandwidth,curl -w '%{time_total}'measures application-visible time. Do not conflate them.vmstat 1,iostat -xz 1,sar -n DEV 1, andpidstat -dseparate CPU, disk, and network pressure.topload above CPU count with high %wa suggests I/O wait.DNS troubleshooting order: /etc/nsswitch.conf hosts line, /etc/resolv.conf nameservers,
dig +tracefor delegation, andgetent hosts nameto test the same path applications use.
Shell Scripting and Network Automation
Strict-mode header:
set -euo pipefailexits on error, unset variable, or failed pipeline component;IFS=$'\n\t'avoids word-splitting surprises.[[ ]]is bash-specific and safer than[ ]: it supports=~regex,&&/||, and no word splitting. Quote variables in[ ]tests.Command substitution
$(cmd)strips trailing newlines;while IFS= read -r line; do ...; done < filepreserves whitespace and backslashes when reading lines.getopts 'h:p:v' optparses short flags withOPTARGandOPTIND; long options need manual case parsing orgetopt --longon GNU systems.Idempotent network automation: check state before changing it, e.g.
ip -o addr show dev eth0 | grep -q '192.0.2.10/24' || ip addr add ....Exit codes: 0 success, 1 general error, 2 misuse of shell builtin, 126 not executable, 127 command not found, 128+N killed by signal N (130 = SIGINT).
trap 'cleanup' EXIT INT TERMguarantees removal of temp files or namespace teardown.mktempcreates safe unique paths instead of predictable /tmp names.Parallelism:
xargs -P 8 -n 1 cmdorGNU parallel; collect results to per-host files to avoid interleaved output. Usetimeout 5 cmdto bound slow network calls.
Unix/Linux System and Network Fundamentals
Every process has a PID; /proc//fd lists open file descriptors, and /proc/net/{tcp,udp,unix} exposes kernel socket tables in text form.
File permission bits: r=4, w=2, x=1 per owner/group/other triad; special bits setuid (4000), setgid (2000), sticky (1000). Directories need x to traverse and r to list names.
Signals: SIGHUP(1) hangup, SIGINT(2) Ctrl-C, SIGKILL(9) uncatchable, SIGTERM(15) default graceful stop, SIGSTOP(19) uncatchable pause. kill -l lists names.
Standard streams: fd 0 stdin, 1 stdout, 2 stderr.
2>&1duplicates stderr onto stdout's current target; order matters (cmd >f 2>&1vscmd 2>&1 >f).Inodes hold metadata (mode, uid, gid, size, timestamps, link count); hard links share an inode, symlinks store a path and can dangle.
df -ireports inode exhaustion.systemd unit types: .service, .socket, .timer, .target, .mount.
systemctl status,journalctl -u <unit> -f, andsystemd-analyze blameare the primary inspection commands.Load average counts runnable plus uninterruptible (D-state) tasks averaged over 1, 5, 15 minutes; compare against CPU count from
nproc, not against 1.0.Unix domain sockets appear as S in
ls -land as type u inss -x; they are local-only and often used by daemons such as dbus and Docker.
Network Architecture, Protocols, and the TCP/IP Stack
TCP header flags: SYN, ACK, FIN, RST, PSH, URG. Connection setup is SYN, SYN-ACK, ACK; teardown is FIN-ACK pairs or RST for abort.
TCP state machine includes LISTEN, SYN_SENT, SYN_RECV, ESTABLISHED, FIN_WAIT1/2, CLOSE_WAIT, LAST_ACK, TIME_WAIT (2*MSL, typically 60s on Linux).
UDP has an 8-byte header (src port, dst port, length, checksum) and no ordering, retransmission, or congestion control; DNS, DHCP, NTP, and QUIC build reliability above it.
IPv4 header is 20 bytes minimum; key fields are TTL, protocol (6=TCP, 17=UDP, 1=ICMP), fragmentation offset, and header checksum. IPv6 uses a fixed 40-byte header with a hop limit and no header checksum.
Private ranges: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16; link-local 169.254.0.0/16 (IPv4) and fe80::/10 (IPv6). Loopback is 127.0.0.0/8 and ::1.
Well-known ports: 22 SSH, 25 SMTP, 53 DNS, 67/68 DHCP, 80 HTTP, 123 NTP, 443 HTTPS, 514 syslog, 3306 MySQL, 5432 PostgreSQL.
ICMP types: 0 echo reply, 3 destination unreachable (with codes such as 3 port unreachable, 4 fragmentation needed), 8 echo request, 11 time exceeded (traceroute mechanism).
MTU vs MSS: MSS = MTU - IP header - TCP header; 1500-byte Ethernet MTU gives 1460-byte IPv4 TCP MSS. Path MTU discovery relies on ICMP type 3 code 4 or IPv6 Packet Too Big.
Unix Network Configuration and Interface Management
Legacy tools:
ifconfig,route -n,netstat -i. Modern replacements:ip addr,ip route,ip link,ss. Both read the same kernel state; iproute2 is the maintained path.ip addr add 192.0.2.10/24 dev eth0adds an address;ip link set eth0 upenables the interface;ip route add default via 192.0.2.1sets the gateway.Persistent config locations vary: Debian/Ubuntu use /etc/network/interfaces or netplan YAML in /etc/netplan; RHEL family uses /etc/sysconfig/network-scripts/ifcfg-* or NetworkManager keyfiles.
ip -s linkshows RX/TX packet, error, and drop counters;ip -s link show eth0narrows it. Rising drops on RX often indicate a full ring buffer or socket backlog.VLAN tagging:
ip link add link eth0 name eth0.100 type vlan id 100. Bonding modes include balance-rr(0), active-backup(1), and 802.3ad LACP(4).ethtool eth0reports link speed, duplex, and driver;ethtool -S eth0dumps NIC statistics;ethtool -k eth0shows offload features such as TSO, GSO, and GRO.resolvectl status(systemd-resolved) or /etc/resolv.conf shows resolver state;ip neighdisplays the ARP/NDP neighbor cache and its REACHABLE/STALE/FAILED states.ip netns add labcreates a network namespace;ip netns exec lab <cmd>runs a command inside it, giving an isolated interface and routing table for testing.
Network Services and Daemon Administration
ss -lntuplists listening TCP and UDP sockets with process names;ss -tan state establishedfilters by TCP state. Requires privilege to see other users' PIDs.A daemon is a background process detached from a controlling terminal; under systemd,
Type=simple,forking, andnotifydescribe how startup completion is signaled.systemctl enable --now <unit>creates the symlink for boot start and starts it immediately;disableremoves the link but does not stop a running instance.Socket activation: a .socket unit holds the port and passes the listening fd to the .service on first connection, allowing the service to start on demand.
journalctl -u nginx --since '1 hour ago' -p errfilters by unit, time, and syslog priority. Priorities run 0 emerg to 7 debug.Configuration test before reload is standard practice:
nginx -t,apachectl configtest,sshd -t,named-checkconf. Reload (SIGHUP) re-reads config without dropping listeners in most daemons.DHCP DORA: Discover, Offer, Request, Ack. Lease timers are renewal (T1, default 50% of lease) and rebinding (T2, default 87.5%).
DNS record types: A, AAAA, CNAME (no other records at the same name), MX (with preference), NS, PTR, TXT, SOA (serial, refresh, retry, expire, minimum TTL).
Routing, Firewalling, and Traffic Control
Longest-prefix match wins in routing; among equal prefixes, the lowest metric (or administrative distance) is preferred.
ip route get 203.0.113.5shows the chosen path.Linux uses policy routing with rules:
ip rule add from 10.0.0.0/24 table 100plusip route add default via 10.0.0.1 table 100. Rules are evaluated by priority number, lowest first.nftables replaced iptables/ip6tables/arptables/ebtables. Base chains attach to hooks (prerouting, input, forward, output, postrouting) with a type (filter, nat, route) and priority.
Netfilter hook order for a locally destined packet: prerouting, input, local process, output, postrouting. Forwarded traffic traverses prerouting, forward, postrouting.
NAT: SNAT/masquerade rewrites source in postrouting; DNAT rewrites destination in prerouting. Conntrack tracks flows;
conntrack -Llists them andnf_conntrack_maxbounds the table.Default policies: DROP inbound with explicit ACCEPT rules, and place an established/related conntrack accept rule early to avoid re-evaluating every packet.
tc qdiscs: pfifo_fast is default, fq_codel is common for bufferbloat control, netem adds delay/loss/jitter for testing, and HTB/tbf shape bandwidth.
tc -s qdisc showprints counters.ip route add blackhole 198.51.100.0/24silently discards;unreachablereturns ICMP unreachable;prohibitreturns administratively prohibited. These are useful for RTBH filtering.
Network Security, Authentication, and Access Control
TLS handshake (1.2): ClientHello, ServerHello plus certificate, key exchange, Finished. TLS 1.3 cuts a round trip and mandates forward-secret key exchange such as ECDHE.
SSH key auth: client proves possession of the private key by signing a session-bound challenge; the server checks ~/.ssh/authorized_keys.
ssh-keygen -t ed25519is the current default choice.SELinux modes are Enforcing, Permissive, Disabled; contexts are user:role:type:level.
getenforce,ls -Z,ausearch -m avc, andrestoreconare core commands. AppArmor uses path-based profiles.PAM stacks: /etc/pam.d/ lists type (auth, account, password, session), control flag (required, requisite, sufficient, optional), and module.
pam_tally2/faillockimplement lockout.File-based access control: umask subtracts from 666 (files) and 777 (directories). A umask of 027 yields files 640 and directories 750.
sudopolicy lives in /etc/sudoers and /etc/sudoers.d; edit withvisudo. Entries areuser host=(runas) command; NOPASSWD removes the password prompt.Certificate validation checks chain to a trusted root, validity dates, hostname/SAN match, and revocation via CRL or OCSP.
openssl s_client -connect host:443 -servername hostinspects a live chain.Defense in depth on a host: least-privilege service accounts, key-only SSH with
PermitRootLogin no, firewall default-deny, and auditd rules on sensitive paths such as /etc/passwd.
Troubleshooting, Monitoring, and Performance Analysis
Layer-by-layer triage:
ip addr(L2/L3 local),ip routeand ping gateway (L3),dig @resolver(DNS),nc -vz host portorss -tn(L4), then application logs.tracerouteuses UDP by default on Linux and ICMP with-I;mtrcombines ping and traceroute in a continuous view. Stars can mean filtering, not necessarily failure.tcpdump -ni eth0 'tcp port 443 and host 203.0.113.5'captures with BPF filters;-w file.pcapwrites for Wireshark.-s 0captures full packets.TIME_WAIT accumulation on a busy server is normal; it indicates the local side closed first. Tune with
tcp_tw_reuseonly after confirming the actual bottleneck.ss -sgives a socket summary;ss -tishows per-connection RTT, cwnd, retransmits, and rto. High retransmits point to loss or congestion, not always to a slow app.Latency vs throughput:
pingmeasures RTT,iperf3measures achievable bandwidth,curl -w '%{time_total}'measures application-visible time. Do not conflate them.vmstat 1,iostat -xz 1,sar -n DEV 1, andpidstat -dseparate CPU, disk, and network pressure.topload above CPU count with high %wa suggests I/O wait.DNS troubleshooting order: /etc/nsswitch.conf hosts line, /etc/resolv.conf nameservers,
dig +tracefor delegation, andgetent hosts nameto test the same path applications use.
Shell Scripting and Network Automation
Strict-mode header:
set -euo pipefailexits on error, unset variable, or failed pipeline component;IFS=$'\n\t'avoids word-splitting surprises.[[ ]]is bash-specific and safer than[ ]: it supports=~regex,&&/||, and no word splitting. Quote variables in[ ]tests.Command substitution
$(cmd)strips trailing newlines;while IFS= read -r line; do ...; done < filepreserves whitespace and backslashes when reading lines.getopts 'h:p:v' optparses short flags withOPTARGandOPTIND; long options need manual case parsing orgetopt --longon GNU systems.Idempotent network automation: check state before changing it, e.g.
ip -o addr show dev eth0 | grep -q '192.0.2.10/24' || ip addr add ....Exit codes: 0 success, 1 general error, 2 misuse of shell builtin, 126 not executable, 127 command not found, 128+N killed by signal N (130 = SIGINT).
trap 'cleanup' EXIT INT TERMguarantees removal of temp files or namespace teardown.mktempcreates safe unique paths instead of predictable /tmp names.Parallelism:
xargs -P 8 -n 1 cmdorGNU parallel; collect results to per-host files to avoid interleaved output. Usetimeout 5 cmdto bound slow network calls.