The Hacker's Field Manual: Network Security & Applied Cryptography
Welcome to the definitive field guide. This manual synthesizes the critical foundations of Applied Cryptography and Network Security. Whether you are auditing architectures, dissecting packets, or breaking legacy ciphers, this knowledge is your weapon.
Part 1: Applied Cryptography
Cryptography is the art and science of secure communication in the presence of adversarial third parties.
1.1 The Fundamentals
Every cryptographic schema consists of two primary algorithms:
- Encryption Algorithm: Transforms plaintext into ciphertext.
- Decryption Algorithm: Restores ciphertext back to plaintext.
Cryptosystems generally fall into two categories based on key distribution:
- Symmetric Cryptography: A single key is shared between parties and used for both encryption and decryption.
- Asymmetric Cryptography: Uses a key pair—a public key for encryption and a private key for decryption.
[!NOTE] Power Analysis (Side-Channel Attack) When a chip encrypts data, its power consumption fluctuates based on the operations performed. Attackers can analyze these power spikes to deduce the underlying algorithm and potentially extract keys. Modern algorithms incorporate mitigations for this.
1.2 Classic Ciphers and Their Weaknesses
Early encryption relied heavily on substitution and transposition.
- Caesar Cipher: Shifts each letter by a fixed key. Weakness: Trivial to brute-force (only 25 possibilities).
- Shift / Monoalphabetic Ciphers: Arbitrary substitution maps. Weakness: Vulnerable to frequency analysis since identical plaintext characters map to identical ciphertext characters.
- Vigenère Cipher: A polyalphabetic substitution using a repeated keyword and a matrix (tabula recta). Weakness: If the key length is deduced, it can be broken via frequency analysis. (Historically, Enigma suffered from operators reusing keys like "QWE" or predictable structures like daily weather reports).
- Transposition / Permutation: Scrambles the order of letters (e.g., Rail Fence technique or columnar transpositions).
1.3 XOR and The One-Time Pad
The XOR (Exclusive OR) operation is the backbone of digital cryptography.
0 ⊕ 0 = 0 | 1 ⊕ 1 = 0
0 ⊕ 1 = 1 | 1 ⊕ 0 = 1
In an XOR Cipher, the plaintext and a key (pad) of equal length are XORed bit-by-bit. If the pad is completely random and used exactly once, this forms a One-Time Pad, which is mathematically unbreakable. Danger: Reusing the pad (Many-Time Pad) destroys security, allowing attackers to deduce the key through ciphertext correlations.
1.4 Modern Symmetric Ciphers
Modern ciphers operate either on blocks of data or continuous streams.
Block Ciphers
Block ciphers encrypt data in fixed-size chunks. They typically use an iterative architecture:
- Key Scheduler: Derives multiple subkeys from the master key.
- Round Function: Applies substitutions and permutations iteratively using the subkeys.
- DES (Data Encryption Standard): 56-bit key (plus parity), 16 rounds. Status: Deprecated (brute-forceable).
- 3DES: Applies DES three times (Encrypt with K1, Decrypt with K2, Encrypt with K3) to achieve a 168-bit effective key length.
- AES (Advanced Encryption Standard): The modern standard. Uses 128, 192, or 256-bit keys over 10, 12, or 14 rounds respectively.
Stream Ciphers & Modes of Operation
Stream ciphers encrypt bits individually. However, block ciphers can be turned into stream ciphers using specific modes of operation.
- ECB (Electronic Codebook) Mode: Each block is encrypted independently with the same key.
- Weakness: Identical plaintext blocks produce identical ciphertext blocks, preserving the global structure of the data (famously illustrated by the ECB Penguin image).
- Padding Oracle Attack: Block ciphers require padding (adding dummy bytes) if the plaintext doesn't perfectly align with the block size. If a system reveals whether the padding is valid upon decryption, an attacker can brute-force the plaintext one byte at a time.
1.5 The Key Exchange Problem
How do parties securely agree on a symmetric key over an insecure channel?
- Trusted Third Party (TTP): A central server securely communicates with each user and distributes session keys. Drawbacks: Single point of failure, fully centralized.
- Merkle Puzzles: Alice sends Bob a large number of "puzzles." Bob solves one to extract a key identifier and a session key. Drawback: An eavesdropper can solve all puzzles in $O(N)$ time.
Diffie-Hellman Key Exchange
A revolutionary protocol allowing two parties to establish a shared secret over an insecure channel.
- Alice and Bob agree on a large prime $p$ and a base generator $g$.
- Alice picks a secret $a$ and sends $A = g^a \pmod p$.
- Bob picks a secret $b$ and sends $B = g^b \pmod p$.
- Both compute the shared secret: $S = B^a \pmod p = A^b \pmod p = g^{ab} \pmod p$.
[!WARNING] Diffie-Hellman does not authenticate the parties. It is heavily vulnerable to Man-in-the-Middle (MitM) attacks. An attacker can intercept the exchanges, negotiate separate keys with Alice and Bob, and relay decrypted/re-encrypted traffic seamlessly.
1.6 Asymmetric Cryptography: RSA
RSA solves the key distribution problem using a mathematical trapdoor (prime factorization).
Key Generation:
- Choose two large primes, $p$ and $q$.
- Compute $n = p \times q$.
- Compute Euler's totient: $\phi(n) = (p-1) \times (q-1)$.
- Choose public exponent $e$ such that $1 < e < \phi(n)$ and $e$ is coprime to $\phi(n)$.
- Compute private exponent $d$ such that $(e \times d) \pmod{\phi(n)} = 1$.
Encryption & Decryption:
- Encrypt: $C = M^e \pmod n$
- Decrypt: $M = C^d \pmod n$
Optimization Note: Decryption (exponentiating with $d$) is computationally heavy. The Chinese Remainder Theorem (CRT) is often used to dramatically speed up RSA decryption.
1.7 Practical Attack: Meet in the Middle
Why don't we use 2DES (encrypting twice with two different 56-bit keys)? Because of the Meet-in-the-Middle attack. An attacker encrypts the known plaintext with all possible $K_1$ and decrypts the ciphertext with all possible $K_2$. Where the intermediate values match, the keys are found.
# A stylized snippet demonstrating a Meet-in-the-Middle on a custom Double-Cipher
dizionario = {}
# Step 1: Encrypt plaintext with all possible k1 and store in dictionary
for a in string.ascii_lowercase:
for b in string.ascii_lowercase:
for c in string.ascii_lowercase:
for d in string.ascii_lowercase:
k1 = a+b+c+d
c1 = encrypt(messaggio, k1)
dizionario[c1] = k1
# Step 2: Decrypt ciphertext with all possible k2 and check for collision
for a in string.ascii_lowercase:
for b in string.ascii_lowercase:
for c in string.ascii_lowercase:
for d in string.ascii_lowercase:
k2 = a+b+c+d
c2 = decrypt(messaggioCriptato, k2)
# Collision found! We have our keys.
if c2 in dizionario:
flag = dizionario[c2] + k2
print("CCIT{" + "{}".format(flag) + "}")
sys.exit(0)
Part 2: Network Security
To attack or defend a network, one must intimately understand its layers, protocols, and routing behaviors.
2.1 The Models: OSI vs TCP/IP
- ISO/OSI (7 Layers): Theoretical framework (Application, Presentation, Session, Transport, Network, Data Link, Physical).
- TCP/IP (4 Layers): The practical standard of the Internet (Application, Transport, Internet, Network Access).
Data Encapsulation: As data moves down the stack, each layer adds its own header (or footer), creating a Protocol Data Unit (PDU).
2.2 Layer 2: Data Link & Ethernet
- Ethernet encapsulates data into frames.
- Routing at this level relies on MAC (Media Access Control) addresses (48-bit hardware addresses).
- Switches & Bridges: Devices that route traffic based on MAC addresses. They build a MAC Address Table by learning which MAC is on which port.
- Flooding: If a switch doesn't know the destination MAC, it floods the frame to all ports (except the origin).
- Broadcast Domain: All nodes reachable at Layer 2 without crossing a Layer 3 boundary.
2.3 Layer 3: Network & IP Routing
The Internet Protocol (IP) handles global packet routing.
- IPv4: 32-bit addresses divided into four octets. (e.g., 192.168.1.10)
- Subnetting (Netmask): Splits an IP into a Network component and an Host component.
- e.g.,
/24means 24 bits for the network, leaving 8 bits (256 addresses) for hosts. - The first address is the Network Address, the last is the Broadcast Address.
- e.g.,
- Private IPs: Non-routable on the public internet (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16).
Address Resolution Protocol (ARP): Maps Layer 3 IPs to Layer 2 MACs. If a device needs to talk to an IP on the local subnet, it broadcasts an ARP Request: "Who has this IP? Tell my MAC."
Routing: Routers use a Routing Table to determine the next hop. Routes can be directly connected, statically assigned, or defined by a default gateway.
2.4 NAT & Port Forwarding
To bridge private networks with the public internet:
- Source NAT (Masquerade): Rewrites the source IP of outgoing packets to the router's public IP. Multiple private hosts share one public IP.
- Destination NAT (Port Forwarding): Rewrites the destination IP of incoming packets, mapping an external port to an internal server's private IP.
2.5 Layer 4: Transport (TCP vs UDP)
- TCP (Transmission Control Protocol): Connection-oriented. Uses a Three-Way Handshake (SYN, SYN-ACK, ACK) to establish a reliable session. Handles retransmission and sequencing.
- UDP (User Datagram Protocol): Connectionless. Fast but unreliable. Best for streaming or VoIP.
- Ports: 16-bit identifiers mapping traffic to specific processes.
- Well-known: 0–1023 (Requires root)
- Registered: 1024–49151
- Ephemeral: 49152–65535
2.6 Application Layer: DNS & HTTP
- DNS (Domain Name System): Resolves hostnames to IP addresses. Uses UDP/TCP port 53. Resolvers recursively query Root, TLD, and Authoritative servers to find records.
- HTTP/HTTPS: The backbone of the web. Relies on Request/Response cycles. Data is identified via URLs and transferred in plaintext (unless encapsulated in TLS for HTTPS).
2.7 Virtualization & Containerization
Modern networks are heavily virtualized.
| Feature | Virtual Machines (VMs) | Containers (Docker) |
|---|---|---|
| Architecture | Hardware virtualization (Hypervisor) | OS virtualization (Shared Kernel) |
| OS Footprint | Full guest OS per VM | Shares host OS |
| Isolation | High (Complete abstraction) | Relaxed (Process/namespace level) |
| Resource Usage | Heavy (CPU, RAM, Disk) | Lightweight and scalable |
- Docker Networking: By default, containers use a
bridgenetwork (isolated Layer 3). To expose services, ports must be explicitly published (-p host_port:container_port).
2.8 Attack Surface & Perimeters
A security perimeter divides internal assets (high trust) from the external world (zero trust).
- DMZ (Demilitarized Zone): A subnetwork exposing external-facing services while isolating the internal network.
- Firewalls: Passive perimeter defenses that filter traffic based on ACLs (Access Control Lists).
Network Sniffing & Interception
To analyze (or steal) traffic, attackers use sniffers (e.g., tcpdump, Wireshark).
- The Switch Problem: Switches isolate traffic. A sniffer on port A won't see traffic between port B and C.
- Solutions for Sniffing:
- Port Mirroring / SPAN: Configuring the switch to duplicate traffic to the sniffer's port.
- Network TAP (Traffic Access Point): A hardware device physically inserted inline to passively copy all traffic.
- ARP Poisoning (Spoofing): An active attack. The attacker sends forged ARP Replies to the target and the gateway, claiming to have the MAC address of the other. The traffic is thereby routed through the attacker (MitM).
- Example tools:
arpspoof - Requirement: IP forwarding must be enabled on the attacker machine (
echo 1 > /proc/sys/net/ipv4/ip_forward) so traffic isn't dropped.
- Example tools:
Stay sharp. Trust nothing. Verify everything.