> ⚠️ Authorization Notice: Cryptographic testing and analysis techniques in this chapter must be performed only against systems you own or have explicit written authorization to test. Intercepting or decrypting communications without authorization...
Learning Objectives
- Understand the fundamental cryptographic primitives used to protect data
- Explain how TLS/SSL establishes secure connections and where it can fail
- Analyze historical protocol attacks including POODLE, BEAST, DROWN, and ROBOT
- Identify certificate and PKI weaknesses exploitable in penetration tests
- Recognize common cryptographic implementation flaws
- Apply practical techniques for attacking weak encryption in authorized engagements
- Evaluate post-quantum cryptography and its implications for security testing
In This Chapter
- Introduction
- 28.1 Cryptographic Primitives: Hashing, Symmetric, Asymmetric
- 28.2 TLS/SSL: How It Works and How It Breaks
- 28.3 Historical Protocol Attacks (POODLE, BEAST, DROWN, ROBOT)
- 28.4 Certificate Attacks and PKI Weaknesses
- 28.5 Cryptographic Implementation Flaws
- 28.6 Attacking Encryption in Practice
- 28.7 Modern Cryptography and Post-Quantum Considerations
- 28.8 Chapter Summary
- Review Questions
- Further Reading Preview
Chapter 28: Cryptography for Hackers
⚠️ Authorization Notice: Cryptographic testing and analysis techniques in this chapter must be performed only against systems you own or have explicit written authorization to test. Intercepting or decrypting communications without authorization violates federal wiretapping laws (18 U.S.C. Section 2511) in addition to computer fraud statutes. Always operate within your Rules of Engagement.
Introduction
In Chapter 27, we learned how to evade detection systems. Many of those techniques -- encrypted C2 channels, TLS-based tunneling, HTTPS beacons -- rely on cryptography to protect our communications from inspection. But what happens when the cryptography itself is the target?
Cryptography is the mathematical foundation upon which digital security is built. Every time you log into a website, make a payment, send an encrypted message, or connect to a VPN, cryptographic algorithms protect the confidentiality, integrity, and authenticity of your data. When cryptography works correctly, it is virtually unbreakable. When it is implemented poorly, misconfigured, or based on outdated standards, it becomes the weakest link in the security chain.
As penetration testers, we do not typically try to break the underlying mathematics of modern cryptographic algorithms -- that is the domain of academic cryptographers with decades of expertise and enormous computational resources. Instead, we look for how cryptography is used incorrectly: weak cipher suites, outdated protocols, improper key management, flawed implementations, and configuration errors. These practical weaknesses are far more common than mathematical ones, and they are devastating when exploited.
Consider the MedSecure engagement. Their patient portal uses HTTPS, which sounds secure. But what version of TLS is it running? What cipher suites does it support? Does it still allow TLS 1.0 for backward compatibility with legacy medical devices? Is the certificate properly configured? Are the session cookies truly protected? How are passwords hashed in the database? Is the JWT implementation secure? Are API keys properly managed? These are the questions a penetration tester must answer.
The healthcare sector is particularly exposed to cryptographic vulnerabilities. Legacy medical devices often run outdated software with deprecated protocols. HIPAA requires encryption of electronic protected health information (ePHI) in transit and at rest, but does not specify minimum algorithm standards, leading to wide variation in implementation quality. And healthcare data has a uniquely long useful life -- a patient's medical record remains sensitive indefinitely, making the "harvest now, decrypt later" quantum threat particularly relevant.
In this chapter, we will build a practical understanding of cryptography from the hacker's perspective. We start with the fundamental primitives, understand how they combine to form protocols like TLS, examine how those protocols have been broken historically, and develop the skills to identify and exploit cryptographic weaknesses in real-world systems.
💡 Key Insight: You do not need a PhD in mathematics to exploit cryptographic weaknesses. Most real-world crypto attacks target implementation flaws, configuration errors, and protocol design mistakes -- not the underlying math. Understanding the concepts in this chapter will equip you to find these weaknesses during penetration tests.
28.1 Cryptographic Primitives: Hashing, Symmetric, Asymmetric
Hash Functions
A cryptographic hash function takes input of any size and produces a fixed-size output (the hash or digest) with the following properties:
- Deterministic: The same input always produces the same output
- One-way: Given a hash, it is computationally infeasible to find the input
- Collision-resistant: It is computationally infeasible to find two inputs that produce the same hash
- Avalanche effect: A small change in input produces a dramatically different hash
Common Hash Algorithms:
| Algorithm | Output Size | Status | Notes |
|---|---|---|---|
| MD5 | 128 bits | Broken | Collision attacks demonstrated in 2004 |
| SHA-1 | 160 bits | Deprecated | First practical collision in 2017 (SHAttered) |
| SHA-256 | 256 bits | Current standard | Part of SHA-2 family |
| SHA-384/512 | 384/512 bits | Current standard | Part of SHA-2 family |
| SHA-3 (Keccak) | Variable | Current standard | Different internal structure from SHA-2 |
| BLAKE2/BLAKE3 | Variable | Current standard | Very fast, used in modern applications |
| bcrypt | 184 bits | Current for passwords | Includes salt and cost factor |
| Argon2 | Variable | Current for passwords | Winner of Password Hashing Competition |
Hashing in Security: Hash functions appear everywhere in security: - Password storage: Passwords are hashed (ideally with bcrypt/Argon2) and the hash is stored instead of the plaintext - File integrity: Hash digests verify that files have not been tampered with - Digital signatures: The hash of a message is signed, not the message itself - Certificate fingerprints: Certificate identity is verified by comparing hash fingerprints - HMAC: Hash-based Message Authentication Code provides both integrity and authentication
Attacking Hashes: As penetration testers, we commonly encounter password hashes that we need to crack (covered in depth in Chapter 15). We also look for systems that still use MD5 or SHA-1 for security-critical functions, as these can be exploited through collision attacks.
A collision attack against MD5 allows an attacker to create two different files with the same MD5 hash. This was famously exploited in the Flame malware (2012), which used an MD5 collision to forge a Microsoft code-signing certificate.
Symmetric Encryption
Symmetric encryption uses the same key for both encryption and decryption. It is fast and efficient, making it suitable for encrypting large amounts of data.
Block Ciphers encrypt data in fixed-size blocks:
- AES (Advanced Encryption Standard): The current standard, supporting 128, 192, and 256-bit keys. AES with a proper mode of operation is considered unbreakable with current technology.
- DES (Data Encryption Standard): 56-bit key, broken. Can be brute-forced in hours.
- 3DES (Triple DES): Applies DES three times with two or three keys. Slow and effectively deprecated.
- Blowfish/Twofish: Variable key length, used in some legacy systems.
Block Cipher Modes of Operation are critical to security:
-
ECB (Electronic Codebook): Each block is encrypted independently. Identical plaintext blocks produce identical ciphertext blocks, leaking patterns. Never use ECB for data encryption (see Case Study 2 for a devastating example).
-
CBC (Cipher Block Chaining): Each block is XOR'd with the previous ciphertext block before encryption. Requires an initialization vector (IV). Secure when implemented correctly, but vulnerable to padding oracle attacks (more in Section 28.5).
-
CTR (Counter): Turns a block cipher into a stream cipher using a counter. Parallelizable and efficient. Used in many modern applications.
-
GCM (Galois/Counter Mode): CTR mode with built-in authentication. Provides both confidentiality and integrity. The preferred mode for modern applications (used in TLS 1.3).
⚠️ Critical Understanding: The choice of mode is often more important than the choice of cipher. AES-256 in ECB mode is less secure than AES-128 in GCM mode, because ECB leaks patterns regardless of key strength.
Stream Ciphers encrypt data one byte at a time:
- RC4: Once widely used in SSL/TLS and WEP. Multiple biases discovered, now considered broken for security use.
- ChaCha20: Modern stream cipher, used in TLS 1.3 as an alternative to AES-GCM. Preferred on devices without AES hardware acceleration.
Asymmetric Encryption
Asymmetric (public-key) encryption uses a mathematically related key pair: a public key (shared freely) and a private key (kept secret). Data encrypted with the public key can only be decrypted with the private key, and vice versa.
RSA: Based on the difficulty of factoring large numbers. Key sizes of 2048 bits or larger are currently considered secure. RSA is used for key exchange, digital signatures, and encryption. However, it is slow compared to symmetric encryption, so it is typically used to encrypt a symmetric key, which then encrypts the actual data (hybrid encryption).
Elliptic Curve Cryptography (ECC): Based on the difficulty of the elliptic curve discrete logarithm problem. Provides equivalent security to RSA with much smaller key sizes (256-bit ECC is roughly equivalent to 3072-bit RSA). Used extensively in modern TLS, SSH, and cryptocurrencies.
Diffie-Hellman Key Exchange: Not an encryption algorithm per se, but a method for two parties to establish a shared secret over an insecure channel. Used in TLS to establish session keys. The ephemeral variant (DHE/ECDHE) provides perfect forward secrecy -- even if the server's long-term private key is later compromised, past sessions cannot be decrypted.
💡 Key Insight for Pentesters: Always check whether a server supports perfect forward secrecy (PFS). Without PFS (e.g., using static RSA key exchange), an attacker who records encrypted traffic and later obtains the server's private key can decrypt all historical traffic. With PFS (using ECDHE), each session uses a unique key that is discarded, making retrospective decryption impossible.
Digital Signatures
Digital signatures combine hashing and asymmetric encryption to provide authentication, integrity, and non-repudiation. The signer hashes the message and encrypts the hash with their private key. Anyone can verify the signature by decrypting it with the signer's public key and comparing the resulting hash with a fresh hash of the message.
Common signature algorithms: - RSA-PSS: RSA-based signature with probabilistic padding (replacing the older PKCS#1 v1.5) - ECDSA: Elliptic curve-based signatures - EdDSA (Ed25519): Modern, deterministic signature scheme. Fast, resistant to side-channel attacks
MedSecure Scenario: Cryptographic Inventory
Before attacking MedSecure's cryptography, we need to inventory their cryptographic usage:
- Patient portal: HTTPS (what TLS version? What cipher suites?)
- Database: Encrypted at rest (what algorithm? What mode? How are keys managed?)
- Internal communications: VPN between offices (what protocol? IPsec or SSL VPN?)
- Password storage: How are passwords hashed? (bcrypt? MD5? plaintext?)
- API authentication: JWT tokens (what signing algorithm? Where is the key?)
- Medical device communications: HL7/FHIR over what transport? Encrypted?
Each of these represents a potential attack surface if the cryptographic implementation is weak.
28.2 TLS/SSL: How It Works and How It Breaks
A Brief History
The evolution of transport encryption tells a story of continuous improvement driven by continuous attacks:
- SSL 2.0 (1995): First widely deployed version. Multiple severe vulnerabilities. Deprecated.
- SSL 3.0 (1996): Significant improvements, but still fundamentally flawed. Vulnerable to POODLE. Deprecated.
- TLS 1.0 (1999): Rebranded SSL with incremental improvements. Vulnerable to BEAST. Deprecated by PCI DSS in 2018.
- TLS 1.1 (2006): Fixed BEAST vulnerability, but introduced no significant improvements. Deprecated.
- TLS 1.2 (2008): Major improvement. Added AEAD ciphers (GCM), support for SHA-256, and negotiation of hash/signature algorithms. Currently the most widely deployed version.
- TLS 1.3 (2018): Complete redesign. Removed insecure algorithms, simplified handshake (one round-trip), mandatory PFS, mandatory AEAD encryption. The current gold standard.
⚠️ Terminology Note: Although SSL has been deprecated since 2015, many people (and tools) still use "SSL" when they mean "TLS." In this chapter, we use the correct protocol name. When we say "SSL," we specifically mean the deprecated SSL 2.0/3.0 protocols.
The TLS 1.2 Handshake
Understanding the handshake is essential for understanding attacks against it:
-
ClientHello: The client sends supported TLS versions, cipher suites, compression methods, and extensions (including SNI -- the hostname the client wants to connect to).
-
ServerHello: The server selects a TLS version and cipher suite from the client's list, sends its choice along with a random value.
-
Certificate: The server sends its X.509 certificate (and any intermediate certificates) to the client.
-
ServerKeyExchange (if using DHE/ECDHE): The server sends its Diffie-Hellman parameters, signed with its private key.
-
ServerHelloDone: The server signals it is done with its initial messages.
-
ClientKeyExchange: The client sends its part of the key exchange (e.g., its DH public value, or the pre-master secret encrypted with the server's public key for RSA key exchange).
-
ChangeCipherSpec: Both sides signal they are switching to encrypted communication.
-
Finished: Both sides send a hash of all handshake messages, encrypted with the negotiated keys. This verifies that the handshake was not tampered with.
After the handshake, both sides have derived the same session keys and can communicate securely. The entire handshake takes two round-trips (2-RTT).
The TLS 1.3 Handshake
TLS 1.3 simplifies this dramatically:
-
ClientHello: The client sends supported versions, cipher suites, key shares (optimistically sending DH public values for likely-to-be-selected groups), and extensions.
-
ServerHello + EncryptedExtensions + Certificate + CertificateVerify + Finished: The server responds with everything in a single flight, including its key share, certificate, and finished message. From this point, the server's messages are encrypted.
-
Client Finished: The client verifies the server's certificate and sends its finished message.
The handshake completes in one round-trip (1-RTT). TLS 1.3 even supports 0-RTT resumption for previously connected clients, though this introduces replay risks.
Key Improvements in TLS 1.3: - Removed RSA key exchange (mandatory PFS via ECDHE or DHE) - Removed CBC mode ciphers (mandatory AEAD -- GCM or ChaCha20-Poly1305) - Removed MD5 and SHA-1 - Removed compression (prevents CRIME attack) - Removed renegotiation (prevents triple handshake attack) - Encrypted most of the handshake (certificate is no longer visible to passive observers)
Cipher Suite Notation
A TLS 1.2 cipher suite string like TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 tells you:
- ECDHE: Key exchange method (Elliptic Curve Diffie-Hellman Ephemeral)
- RSA: Authentication method (certificate signed with RSA)
- AES_256_GCM: Encryption algorithm and mode (AES-256 in Galois/Counter Mode)
- SHA384: PRF hash function
TLS 1.3 simplifies this: TLS_AES_256_GCM_SHA384 (key exchange is always ECDHE/DHE, authentication is defined by the certificate).
Key Derivation in TLS
Understanding how session keys are derived is important for pentesters because it explains why some attacks work and others do not.
In TLS 1.2, the key derivation process works as follows: 1. Client and server exchange random values (Client Random and Server Random) 2. Key exchange produces a Pre-Master Secret (PMS) - RSA: Client generates PMS, encrypts with server's public key - ECDHE: Both sides contribute DH shares, compute shared secret 3. PMS + Client Random + Server Random are combined via the Pseudo-Random Function (PRF) to derive the Master Secret 4. Master Secret is expanded into the actual encryption keys, MAC keys, and IVs
The critical difference between RSA and ECDHE key exchange: - RSA: The PMS is encrypted with the server's public key. Anyone with the private key can recover the PMS and derive all session keys. This means recorded traffic can be decrypted later if the private key is obtained. - ECDHE: Each side generates an ephemeral DH key pair. The shared secret is computed from these ephemeral keys, which are discarded after the handshake. Even with the server's long-term private key, an attacker cannot recover the ephemeral keys and therefore cannot decrypt the session.
This is why Perfect Forward Secrecy (PFS) matters so much, and why TLS 1.3 mandated it by removing RSA key exchange entirely.
Downgrade Protection in TLS
TLS includes specific mechanisms to prevent protocol downgrade attacks:
Version Negotiation: In TLS 1.2, the client sends the highest version it supports in the ClientHello. The server selects the highest version both support. An attacker modifying the ClientHello to show a lower version is detected by the Finished message, which contains a hash of all handshake messages (including the original ClientHello).
TLS_FALLBACK_SCSV (RFC 7507): When a client retries a connection with a lower protocol version (due to a connection failure), it includes the TLS_FALLBACK_SCSV cipher suite value in its ClientHello. If the server supports a higher version than what is being negotiated, it recognizes the SCSV and rejects the connection, preventing forced downgrades.
TLS 1.3 Downgrade Sentinel: TLS 1.3 includes additional protection: if the server supports TLS 1.3 but is negotiating TLS 1.2 or below, it embeds a specific sentinel value in the ServerHello random field. A TLS 1.3-capable client that sees this sentinel knows a downgrade attack is occurring and aborts the connection.
These mechanisms are important context for understanding historical attacks like POODLE, which relied on protocol downgrade.
What to Test: TLS Configuration Assessment
During a penetration test, assessing TLS configuration is one of the first and most important steps:
# Using testssl.sh (comprehensive)
testssl.sh https://portal.medsecure.example.com
# Using sslyze (Python-based)
sslyze --regular portal.medsecure.example.com
# Using Nmap
nmap --script ssl-enum-ciphers -p 443 portal.medsecure.example.com
# Using openssl s_client (manual)
openssl s_client -connect portal.medsecure.example.com:443 -tls1
openssl s_client -connect portal.medsecure.example.com:443 -tls1_1
openssl s_client -connect portal.medsecure.example.com:443 -tls1_2
Key findings to look for: - Support for SSL 3.0, TLS 1.0, or TLS 1.1 (deprecated protocols) - Support for RC4, DES, 3DES, or NULL cipher suites - Absence of AEAD ciphers (GCM, ChaCha20-Poly1305) - Missing perfect forward secrecy (static RSA key exchange) - Weak DH parameters (< 2048 bits) -- vulnerable to Logjam - Certificate issues (expired, wrong hostname, weak signature, self-signed) - Missing HSTS (HTTP Strict Transport Security) header - Missing certificate pinning (for mobile applications)
🔵 Blue Team Perspective: Run testssl.sh against your own infrastructure on a regular basis. Automate this with a CI/CD pipeline that fails if deprecated protocols or weak ciphers are detected. Mozilla's SSL Configuration Generator (ssl-config.mozilla.org) provides recommended configurations for popular web servers.
28.3 Historical Protocol Attacks (POODLE, BEAST, DROWN, ROBOT)
BEAST (Browser Exploit Against SSL/TLS) -- 2011
The Vulnerability: BEAST exploited a weakness in TLS 1.0's implementation of CBC mode. In TLS 1.0, the initialization vector (IV) for each record is the last ciphertext block of the previous record, making it predictable. An attacker who can inject chosen plaintext (e.g., via JavaScript in the victim's browser) and observe the ciphertext can use a block-wise adaptive chosen-plaintext attack to decrypt one byte of a target block at a time.
Attack Requirements: Same-origin policy bypass (to inject JavaScript), ability to observe encrypted traffic (man-in-the-middle position).
Impact: An attacker could decrypt HTTPS cookies, session tokens, or other sensitive data byte by byte.
Mitigation: TLS 1.1 fixed this by using explicit, random IVs. Server-side mitigations included using RC4 (ironically, this became the recommended fix until RC4 was itself broken) or implementing the 1/n-1 record splitting workaround. The real fix: upgrade to TLS 1.2+.
Current Status: TLS 1.0 is deprecated. BEAST is primarily a historical concern, but legacy systems (especially medical devices and industrial control systems) may still be vulnerable.
POODLE (Padding Oracle On Downgraded Legacy Encryption) -- 2014
The Vulnerability: POODLE attacked SSL 3.0's CBC mode padding. SSL 3.0 uses non-deterministic padding and does not include the padding in the MAC (Message Authentication Code). An attacker in a man-in-the-middle position can modify the padding of a CBC-encrypted block and observe whether the server accepts or rejects it. By systematically modifying padding bytes, the attacker can decrypt one byte per 256 requests on average.
The Downgrade Component: Even if a server supports TLS 1.2, POODLE exploits the protocol negotiation fallback. An attacker intercepts the connection and interferes with the TLS handshake, causing the client to fall back to SSL 3.0 (which many browsers and servers still supported).
Impact: Decryption of HTTPS session cookies, typically requiring about 256 requests per byte.
Mitigation: Disable SSL 3.0 entirely. Implement TLS_FALLBACK_SCSV (a signal that prevents protocol downgrade attacks). Modern browsers have removed SSL 3.0 support.
POODLE variant for TLS (December 2014): Some TLS implementations (notably F5 BIG-IP, A10 Networks) incorrectly checked CBC padding in TLS 1.0-1.2, making them vulnerable to a POODLE-like attack even without SSL 3.0.
DROWN (Decrypting RSA with Obsolete and Weakened eNcryption) -- 2016
The Vulnerability: DROWN exploited the fact that many servers supported SSL 2.0 (even if it was disabled on the HTTPS port) because the same RSA private key was used across multiple services. An attacker could exploit SSL 2.0's weak export-grade cryptography to recover the server's RSA session keys, then use those keys to decrypt TLS connections that used RSA key exchange.
Attack Requirements: The target server (or any server sharing the same RSA private key) must support SSL 2.0. The attacker must observe a TLS connection that uses RSA key exchange (without PFS).
Impact: Decryption of recorded TLS sessions. At disclosure, approximately 33% of all HTTPS servers were vulnerable.
Mitigation: Disable SSL 2.0 on all services. Ensure RSA private keys are not shared across servers with different security configurations. Use PFS (ECDHE) to protect against retrospective decryption.
💡 Key Insight: DROWN demonstrates a critical principle: a chain is only as strong as its weakest link. A perfectly configured TLS 1.2 server is vulnerable if it shares its private key with a server that supports SSL 2.0. During penetration tests, always check for related services that might share certificates.
ROBOT (Return Of Bleichenbacher's Oracle Threat) -- 2017
The Vulnerability: ROBOT revived a 1998 attack by Daniel Bleichenbacher against RSA PKCS#1 v1.5 encryption. When a TLS server receives a ClientKeyExchange message with RSA encryption, it must decrypt the pre-master secret. If the decrypted padding is invalid, the server should respond identically to a valid padding (to prevent the oracle). However, many implementations responded differently (different timing, different error messages, different alert codes), creating a padding oracle.
Impact: An attacker could sign arbitrary messages with the server's private key or decrypt recorded TLS sessions that used RSA key exchange. Major vendors affected included F5 BIG-IP, Citrix, Cisco ACE, Erlang, Bouncy Castle, and WolfSSL.
Mitigation: Use ECDHE key exchange (PFS) instead of RSA key exchange. Patch vulnerable implementations. TLS 1.3 removed RSA key exchange entirely, eliminating this class of attack.
CRIME and BREACH -- Compression-Based Attacks
CRIME (2012): Exploited TLS-level compression. An attacker who can inject chosen plaintext and observe the compressed, encrypted output can infer the content of secrets (like session cookies) by observing changes in compressed size. Mitigation: disable TLS compression (now default).
BREACH (2013): Applied the same concept to HTTP-level compression (gzip). Since HTTP compression is essential for performance, BREACH is harder to mitigate. Defenses include: randomizing secrets per-request, separating secrets from user-controlled content, and disabling compression for responses containing secrets.
Heartbleed (CVE-2014-0160) -- Not a Protocol Attack
Heartbleed was not a protocol vulnerability but an implementation bug in OpenSSL's handling of the TLS Heartbeat extension. The Heartbeat extension allows TLS endpoints to send a "keep-alive" message containing a payload and a length field indicating the payload size. The server should echo back the payload with the specified length.
The bug was simple: OpenSSL trusted the client-supplied length field without verifying it against the actual payload size. An attacker could send a heartbeat request with a tiny payload (say, 1 byte) but claim a length of 65,535 bytes. OpenSSL would read 65,535 bytes from its process memory -- starting from the heartbeat payload's location -- and send them back. This 65,535-byte response contained whatever happened to be in adjacent memory: private keys, session tokens, usernames, passwords, and other sensitive data.
Why Heartbleed Was So Devastating: 1. Silent exploitation: No authentication required, no log entries generated. Exploitation was completely invisible to the server operator. 2. Widespread impact: OpenSSL was (and is) the most widely used TLS library. An estimated 17% of all HTTPS servers were vulnerable at disclosure. 3. Private key exposure: Server private keys could be extracted, enabling retrospective decryption of recorded traffic (for connections without PFS) and real-time MITM attacks. 4. Difficult remediation: Simply patching was not enough. Affected organizations had to revoke and reissue certificates, rotate all credentials that may have been exposed, and assess whether they had been exploited (impossible to determine definitively since exploitation left no trace).
Heartbleed demonstrated that implementation bugs can be far more devastating than protocol weaknesses. A single missing bounds check in a widely-deployed library compromised the security of millions of systems worldwide. For penetration testers, Heartbleed remains a reminder to test for implementation-specific vulnerabilities, not just protocol-level issues.
🧪 Try It in Your Lab: Set up a deliberately vulnerable OpenSSL version on a test server and use the Nmap heartbleed script (
nmap --script ssl-heartbleed -p 443 target) to detect it. Then use a Heartbleed exploitation tool to observe what data is leaked from server memory. This exercise dramatically illustrates the impact of implementation bugs.
Testing for Protocol Vulnerabilities
During a penetration test, check for these vulnerabilities:
# Test for POODLE (SSL 3.0)
openssl s_client -connect target:443 -ssl3
# Test for DROWN (SSL 2.0 on any related server)
openssl s_client -connect target:443 -ssl2
# Test for ROBOT
python3 robot-detect.py target:443
# Comprehensive testing with testssl.sh
testssl.sh --vulnerable target:443
# Nmap vuln scripts
nmap --script ssl-poodle,ssl-heartbleed,ssl-dh-params -p 443 target
🔵 Blue Team Perspective: Maintain a cryptographic inventory of all TLS configurations across your organization. Legacy systems, load balancers, and non-web services (SMTP, IMAP, LDAP) are often overlooked. Automated scanning with testssl.sh or sslyze should be part of your regular vulnerability management program.
28.4 Certificate Attacks and PKI Weaknesses
How PKI Works
Public Key Infrastructure (PKI) is the trust framework that makes TLS work. When your browser connects to a website over HTTPS, it needs to verify that the server's public key actually belongs to the claimed domain. PKI accomplishes this through a hierarchy of trust:
- Certificate Authorities (CAs) are trusted third parties whose root certificates are pre-installed in browsers and operating systems.
- Intermediate CAs are signed by root CAs and sign end-entity certificates.
- End-entity certificates are issued to website operators after domain validation (DV), organization validation (OV), or extended validation (EV).
- Certificate chain: Browser validates the chain from end-entity to intermediate to root.
Certificate Attack Vectors
Expired Certificates: An expired certificate may indicate poor certificate management, and in some environments, applications are configured to ignore certificate expiration. Test whether the application properly rejects expired certificates.
Self-Signed Certificates: Common in internal applications, development environments, and some medical devices. If users or applications are trained to ignore certificate warnings, man-in-the-middle (MITM) attacks become trivial.
Hostname Mismatch: A certificate issued for www.medsecure.example.com should not be trusted for portal.medsecure.example.com unless it includes that hostname as a Subject Alternative Name (SAN). Check for wildcard certificates (*.medsecure.example.com) and their scope.
Weak Signature Algorithms: Certificates signed with MD5 or SHA-1 are vulnerable to collision attacks. The Flame malware exploited an MD5 collision to forge a Microsoft Windows Update certificate. Google's SHAttered attack (2017) demonstrated a practical SHA-1 collision.
Certificate Transparency (CT) Logs: CT logs publicly record all certificates issued by participating CAs. This is a defensive mechanism (allowing domain owners to detect unauthorized certificates), but pentesters can use CT logs for reconnaissance -- discovering subdomains that the organization might not have intended to make public.
# Search CT logs for certificates
curl -s "https://crt.sh/?q=medsecure.example.com&output=json" | jq '.[] | .name_value' | sort -u
Man-in-the-Middle with Rogue Certificates
In an authorized engagement, you may need to demonstrate MITM attacks to show the risk of improper certificate validation. This is common in:
-
Mobile app testing: Many mobile apps fail to implement certificate pinning or implement it incorrectly. Using tools like Burp Suite with a custom CA certificate installed on the device, you can intercept HTTPS traffic.
-
Thick client testing: Desktop applications may use their own TLS implementation that does not properly validate certificates.
-
Internal network testing: If you can ARP spoof or DNS poison within the internal network, you can redirect HTTPS connections to your proxy with a self-signed certificate. If users click through certificate warnings, the attack succeeds.
Tools for certificate-based MITM: - mitmproxy: Python-based proxy with a powerful scripting API - Burp Suite: Industry-standard web proxy with TLS interception - bettercap: Network attack framework with MITM capabilities - evilginx2: Reverse proxy for phishing with real-time MITM (for authorized testing only)
Certificate Pinning and Bypass
Certificate pinning restricts which certificates an application trusts for a specific domain. Instead of trusting any certificate signed by a trusted CA, the application only trusts a specific certificate or public key.
Types of pinning: - Public Key Pinning: Pins the public key hash (most resilient) - Certificate Pinning: Pins the specific certificate (breaks on certificate rotation) - CA Pinning: Pins the issuing CA (less granular)
Bypassing pinning (for authorized mobile app testing):
- Frida + objection: Dynamic instrumentation to hook and disable certificate validation at runtime
objection --gadget com.medsecure.app explore
com.medsecure.app > android sslpinning disable
- Magisk + TrustMeAlready: Install a Magisk module that patches certificate validation system-wide
- Apktool + modification: Decompile the APK, modify the network security configuration, recompile and sign
⚠️ Important: Certificate pinning bypass should only be performed on applications you have authorization to test. This technique is essential for mobile app penetration testing but constitutes unauthorized interception if performed on third-party applications.
ShopStack Scenario: Certificate Issues
During the ShopStack engagement, we discover several certificate-related findings:
- The
admin.shopstack.example.comsubdomain uses a self-signed certificate. The admin team has been trained to click through browser warnings, making MITM attacks trivial. - The ShopStack mobile app does not implement certificate pinning. We install Burp's CA certificate on a test device and intercept all API traffic, revealing API keys and session tokens.
- The main
shopstack.example.comcertificate uses a 1024-bit RSA key (too small by modern standards) and is signed with SHA-1. - CT log enumeration reveals a staging subdomain (
staging.shopstack.example.com) running an older, vulnerable version of the application.
28.5 Cryptographic Implementation Flaws
The Padding Oracle Attack
The padding oracle attack, first described by Serge Vaudenay in 2002, is one of the most elegant and practical cryptographic attacks. It exploits improper handling of padding errors in CBC mode encryption.
How CBC Padding Works: When data does not fill a complete block, padding bytes are added. PKCS#7 padding uses the padding length as the padding value: if 3 bytes of padding are needed, the padding is 03 03 03. The receiver decrypts the block, checks the padding, and strips it.
The Oracle: If the server responds differently to valid versus invalid padding (different error message, different response time, different HTTP status code), it leaks information. An attacker can modify ciphertext bytes and observe the server's response to determine whether the decrypted padding is valid.
The Attack: By systematically modifying the second-to-last ciphertext block, the attacker can determine the intermediate decryption value of the last block. Combined with the original ciphertext, this reveals the plaintext. The attack requires at most 256 * block_size requests per block.
Real-World Impact: - ASP.NET Padding Oracle (2010): Microsoft's ASP.NET framework was vulnerable to a padding oracle attack through its ViewState and Forms Authentication cookies. This allowed complete decryption and forgery of authentication cookies, leading to full application compromise. Microsoft issued an emergency out-of-band patch. - Lucky Thirteen (2013): A timing-based padding oracle against TLS CBC mode. The TLS specification attempted to prevent padding oracles by processing records in constant time regardless of padding validity, but implementations leaked timing information through differences in MAC verification processing.
Detection and Prevention: - Use AEAD ciphers (GCM, ChaCha20-Poly1305) instead of CBC mode - If CBC must be used, implement constant-time padding verification - Use the Encrypt-then-MAC extension - Test for padding oracles with tools like PadBuster and Burp Suite's Active Scan
ECB Mode Vulnerabilities
Electronic Codebook (ECB) mode encrypts each block independently with the same key. This means identical plaintext blocks produce identical ciphertext blocks, revealing patterns in the data.
The classic demonstration uses image encryption: encrypting a bitmap image in ECB mode preserves the image's visual patterns because areas of the same color produce the same ciphertext. The "ECB Penguin" (a Linux Tux logo encrypted in ECB mode) is a famous illustration -- the penguin is clearly recognizable in the ciphertext.
This is not just a theoretical concern. See Case Study 2 for how Adobe's use of ECB mode in their password database exposed patterns in 153 million user accounts.
Initialization Vector (IV) Misuse
Many encryption modes require a unique, unpredictable initialization vector for each encryption operation. Common IV mistakes:
- Static IV: Using the same IV for every encryption. In CBC mode, this means identical first blocks of plaintext produce identical first blocks of ciphertext.
- Sequential IV: Using a counter as the IV. In CBC mode, this enables the BEAST attack (predictable IVs).
- IV reuse in CTR/GCM: Catastrophic. If two messages are encrypted with the same key and nonce (IV) in CTR or GCM mode, XOR'ing the two ciphertexts produces the XOR of the two plaintexts, from which both can often be recovered.
⚠️ Critical: AES-GCM nonce reuse allows both decryption of plaintext AND forgery of the authentication tag. This completely destroys both confidentiality and integrity. During testing, check for nonce reuse in any application using GCM mode.
Random Number Generation Failures
Cryptography depends on unpredictable random numbers. Failures in random number generation have caused catastrophic security breaks:
-
Debian OpenSSL Bug (2008): A Debian maintainer commented out two lines of code that seeded OpenSSL's random number generator, reducing the entropy to approximately 15 bits (32,767 possible keys). Every SSL certificate, SSH key, and other cryptographic key generated on Debian, Ubuntu, or derivatives during the two years this bug existed was predictable.
-
Android SecureRandom Bug (2013): Android's
SecureRandomclass had insufficient entropy on some devices, leading to predictable random values. This resulted in the theft of Bitcoin from Android wallets because ECDSA signatures with predictable random values leak the private key. -
RSA Key Generation with Low Entropy: Embedded devices (routers, IoT devices) sometimes generate RSA keys during first boot with insufficient entropy. Researchers have factored millions of RSA keys by finding pairs that share a prime factor -- a consequence of low-entropy random number generation.
Timing Side-Channel Attacks
Timing attacks exploit the fact that different code paths take different amounts of time. In cryptography, this can leak sensitive information:
String Comparison Timing: Comparing two strings byte-by-byte returns as soon as a mismatch is found. An attacker who can measure response times can determine how many leading bytes of a secret match their guess. By iterating through possible values for each byte position, the entire secret can be recovered one byte at a time.
This is why cryptographic comparisons must use constant-time functions:
# INSECURE: Early exit on mismatch
if user_mac == computed_mac: # This leaks timing information
return True
# SECURE: Constant-time comparison
import hmac
if hmac.compare_digest(user_mac, computed_mac): # Always compares all bytes
return True
RSA Timing Attacks: The time taken to perform RSA private key operations can vary based on the key material. Implementations must use blinding (multiplying the input by a random value before decryption) to prevent timing-based key recovery.
Cache Timing Attacks: AES implementations that use lookup tables can leak key information through CPU cache timing. The attacker monitors which cache lines are accessed during encryption, revealing which table entries were used, which in turn reveals key bytes. Constant-time AES implementations (using bitslicing or hardware AES-NI instructions) mitigate this.
During penetration testing, you may not directly exploit timing attacks, but you should be aware of them when reviewing cryptographic implementations. Any application that performs its own cryptographic comparisons or key operations (rather than using a vetted library) is at risk.
Hardcoded Keys and Key Management Failures
The most common cryptographic "attack" in penetration testing is simply finding the key:
- Hardcoded in source code: Encryption keys embedded in application code, configuration files, or mobile app binaries
- Default keys: Devices or applications shipped with default encryption keys that are never changed
- Keys in environment variables: Better than hardcoded, but still accessible to anyone with shell access
- Keys in version control: API keys, certificates, and encryption keys committed to Git repositories
- Weak key derivation: Using MD5(password) as an encryption key instead of a proper KDF (Key Derivation Function) like PBKDF2, scrypt, or Argon2
# Search for potential hardcoded keys in source code
grep -rn "password\|secret\|key\|apikey\|api_key\|token" --include="*.py" --include="*.js" --include="*.java" /path/to/source/
# Search for private keys in common locations
find / -name "*.pem" -o -name "*.key" -o -name "*.pfx" -o -name "*.p12" 2>/dev/null
# Check Git history for accidentally committed secrets
git log --all --full-history -- "*.key" "*.pem" ".env" "config*.json"
🔵 Blue Team Perspective: Implement automated secret scanning in your CI/CD pipeline using tools like GitLeaks, TruffleHog, or GitHub's built-in secret scanning. Use a secrets management solution (HashiCorp Vault, AWS Secrets Manager, Azure Key Vault) for runtime key access. Rotate keys regularly and monitor for unauthorized access.
28.6 Attacking Encryption in Practice
TLS Stripping (SSLStrip)
TLS stripping attacks exploit the transition from HTTP to HTTPS. When a user types medsecure.com (without https://), the browser first connects via HTTP, and the server redirects to HTTPS. An attacker in a MITM position can intercept this initial HTTP connection and proxy the connection, maintaining HTTP with the victim while communicating with the server via HTTPS.
The attack flow:
1. Attacker ARP spoofs to become the default gateway
2. Victim requests http://medsecure.com
3. Attacker intercepts and forwards to https://medsecure.com
4. Server responds with HTTPS content
5. Attacker strips HTTPS, sends HTTP content to victim
6. Victim sees an unencrypted connection but the page looks normal
Tools: sslstrip, bettercap, mitmproxy
Mitigation: HTTP Strict Transport Security (HSTS) header instructs the browser to always use HTTPS for the domain. HSTS preloading goes further by hardcoding the domain in the browser's preload list, preventing even the first HTTP request.
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
Downgrade Attacks
Downgrade attacks force a connection to use a weaker protocol version or cipher suite than both client and server support. The attacker, positioned as a man-in-the-middle, modifies the ClientHello to remove modern cipher suites or injects errors (TCP RSTs, handshake failures) that cause the client to fall back to weaker protocols.
The downgrade attack pattern has appeared repeatedly in TLS history:
- POODLE (2014): Forced downgrade from TLS 1.x to SSL 3.0, then exploited CBC padding
- FREAK (2015): Forced downgrade to 512-bit RSA export cipher suites, which could be factored in hours
- Logjam (2015): Forced downgrade to 512-bit DH export parameters, enabling computation of the discrete logarithm
- DROWN (2016): Cross-protocol attack using SSL 2.0 to break TLS connections
These attacks share a common theme: a weakness in an obsolete protocol or cipher suite becomes exploitable when an attacker can force its use. The lesson is clear -- disabling deprecated protocols and cipher suites is not just a compliance checkbox, it is a critical security measure.
TLS Fallback SCSV (RFC 7507) mitigates protocol downgrade by having the client signal when it is retrying with a lower protocol version. The server rejects the connection if it supports a higher version.
TLS 1.3 includes additional downgrade protection by embedding a sentinel value in the ServerHello random field when the server supports TLS 1.3 but is negotiating a lower version. A TLS 1.3-capable client that observes this sentinel knows a downgrade is occurring and aborts the connection, even if the sentinel appears in a seemingly valid TLS 1.2 handshake.
During penetration testing, always check whether a server can be downgraded. Even if the server supports TLS 1.3, the presence of TLS 1.0 or SSL 3.0 support creates a downgrade path that a MITM attacker could exploit.
Attacking Password Hashing
While covered in detail in Chapter 15, it is worth revisiting password hashing from a cryptographic perspective:
Unsalted Hashes: Without a salt (random value prepended to the password before hashing), identical passwords produce identical hashes. This enables rainbow table attacks -- precomputed hash-to-plaintext lookup tables.
Fast Hashes for Passwords: Using SHA-256 or MD5 for password hashing is insecure because these algorithms are designed to be fast. A modern GPU can compute billions of SHA-256 hashes per second. Password-specific hash functions (bcrypt, scrypt, Argon2) are deliberately slow, requiring significant computation and memory for each hash.
Practical Testing:
# Identify hash type
hashid '$2b$12$LJ3m4ys32...'
# Result: bcrypt
# Crack with hashcat
hashcat -m 3200 hashes.txt wordlist.txt # bcrypt mode
# Crack with John the Ripper
john --format=bcrypt hashes.txt --wordlist=wordlist.txt
Attacking JWT (JSON Web Tokens)
JWTs are widely used for API authentication and often contain cryptographic vulnerabilities:
None Algorithm Attack: Some JWT libraries accept "alg": "none", meaning the token is not signed at all. An attacker can modify the token payload, set the algorithm to "none," remove the signature, and the server accepts it.
Algorithm Confusion (Key Confusion): If a server uses RSA to sign JWTs (asymmetric), but the library also accepts HMAC (symmetric), an attacker can change the algorithm from RS256 to HS256 and sign the token using the server's public key (which is public!) as the HMAC secret.
Weak Signing Keys: Short or predictable HMAC secrets can be brute-forced:
# Brute-force JWT HMAC secret
hashcat -a 0 -m 16500 jwt.txt wordlist.txt
JKU/X5U Injection: If the JWT header includes a jku (JWK Set URL) or x5u (X.509 URL) field, and the server fetches the key from this URL without proper validation, the attacker can point it to their own key server.
🧪 Try It in Your Lab: Deploy the JWT-related challenges from OWASP WebGoat or PortSwigger Web Security Academy. Practice the none algorithm attack, algorithm confusion, and weak key brute-forcing in a safe environment.
Attacking Encrypted Databases and Files
During post-exploitation, you may encounter encrypted databases, files, or disk volumes. The approach is rarely to break the encryption directly -- instead, we target key management weaknesses:
SQLite/SQLCipher: Some SQLite databases use SQLCipher for encryption. The encryption is strong (AES-256-CBC), but the key must be stored or derived somewhere. Common locations: - Hardcoded in the application source code - Stored in a configuration file - Derived from a user password (potentially crackable) - Stored in the operating system keychain (accessible with admin privileges) - Present in process memory during application runtime
BitLocker: Windows full-disk encryption using AES-128 or AES-256. Attack vectors include:
- Recovery key stored in Active Directory (accessible to domain admins)
- Recovery key printed and stored physically (social engineering target)
- TPM-only mode without PIN (vulnerable to cold boot attacks, DMA attacks, or sniffing the TPM bus)
- Memory analysis if the system is running (keys are in memory)
- manage-bde command reveals protection status and key protectors
FileVault 2: macOS full-disk encryption. Keys may be escrowed in: - Apple's iCloud recovery - MDM solution (institutional recovery keys) - Enterprise key escrow services
KeePass/LastPass databases: Password manager databases encrypted with a master password. If you can extract the database file:
# Extract hash from KeePass database for cracking
keepass2john database.kdbx > keepass_hash.txt
# Crack with hashcat or John
hashcat -m 13400 keepass_hash.txt wordlist.txt
john keepass_hash.txt --wordlist=wordlist.txt
Application-Level Encryption: Many applications implement their own encryption for data at rest. Common weaknesses include: - Key derived from a predictable value (timestamp, user ID, sequential number) - Key stored alongside the encrypted data (defeating the purpose of encryption) - Encryption used without authentication (no HMAC or AEAD), allowing ciphertext manipulation - Weak key derivation (single SHA-256 iteration instead of PBKDF2/Argon2)
MedSecure Scenario: Cryptographic Assessment Findings
During the MedSecure engagement, our cryptographic assessment reveals several concerning findings:
-
Patient Portal TLS: Supports TLS 1.0 for compatibility with legacy HL7 interfaces. Uses CBC cipher suites without PFS. Certificate is SHA-256 signed but expiring in 16 days.
-
Internal API: Uses JWT with HS256 (symmetric key). The JWT secret is a dictionary word ("medsecure") that we crack with hashcat in 3 seconds. We forge admin tokens and access patient records.
-
Database at Rest: Patient database uses column-level encryption with AES-256-CBC. However, the encryption key is stored in the same database in a "config" table, protected only by application-level access controls.
-
Password Storage: Legacy accounts use MD5 without salt (from a 2015 migration). Newer accounts use bcrypt with cost factor 10. We recommend migrating all accounts to Argon2id.
-
Medical Device Communication: HL7v2 messages between the patient portal and the lab system are transmitted over an unencrypted TCP connection on the internal network. These messages contain patient names, dates of birth, and test results.
Each finding is documented with risk rating, evidence, and specific remediation steps.
28.7 Modern Cryptography and Post-Quantum Considerations
The Quantum Threat
Quantum computers exploit quantum mechanical phenomena (superposition and entanglement) to perform certain computations exponentially faster than classical computers. Two quantum algorithms pose existential threats to current cryptography:
Shor's Algorithm can factor large numbers and compute discrete logarithms in polynomial time. This breaks: - RSA (based on factoring) - Diffie-Hellman (based on discrete logarithms) - ECC (based on elliptic curve discrete logarithms) - DSA, ECDSA (signature schemes based on these problems)
Grover's Algorithm provides a quadratic speedup for searching. For symmetric encryption, this means: - AES-128 provides only 64-bit security against quantum attacks - AES-256 provides 128-bit security against quantum attacks (still secure) - Hash function collision resistance is reduced by a square root factor
The "Harvest Now, Decrypt Later" Threat
Even though large-scale quantum computers do not yet exist (as of 2026, the largest quantum computers have roughly 1,000-1,500 qubits, while breaking RSA-2048 is estimated to require millions of logical qubits), the threat is real today because of "harvest now, decrypt later" (HNDL) attacks:
- A nation-state adversary records encrypted traffic today
- They store this encrypted data until quantum computers are available
- They use quantum computers to decrypt the historical traffic
For data that must remain confidential for decades (government secrets, healthcare records, trade secrets), this means post-quantum cryptography is needed now.
NIST Post-Quantum Standards
In 2024, NIST finalized the first post-quantum cryptographic standards:
- ML-KEM (CRYSTALS-Kyber): Lattice-based key encapsulation mechanism (KEM). Selected as the primary standard for key exchange. Already being integrated into TLS implementations.
- ML-DSA (CRYSTALS-Dilithium): Lattice-based digital signature scheme. Selected as the primary standard for digital signatures.
- SLH-DSA (SPHINCS+): Hash-based digital signature scheme. Provides a backup based on different mathematical assumptions.
- FN-DSA (FALCON): Lattice-based signature scheme with compact signatures. Standardized in 2025.
Hybrid Approaches
The current recommendation is to use hybrid key exchange, combining a classical algorithm (like ECDHE) with a post-quantum algorithm (like ML-KEM). This ensures that: - If the post-quantum algorithm turns out to be broken, the classical algorithm still provides security - If a quantum computer breaks the classical algorithm, the post-quantum algorithm provides security
Google Chrome and other browsers have begun deploying hybrid key exchange (X25519 + ML-KEM-768) in TLS connections. This is visible in Wireshark as significantly larger ClientHello messages (approximately 1,200 bytes for the ML-KEM key share alone, compared to 32 bytes for X25519).
The hybrid approach also applies to digital signatures in certificates, though the transition is more complex due to certificate chain size constraints. A certificate chain with ML-DSA signatures can be several kilobytes larger than an equivalent ECDSA chain, potentially causing issues with systems that have fixed buffer sizes for certificate processing.
Cryptographic Agility: Organizations should design their systems with cryptographic agility -- the ability to swap cryptographic algorithms without major architectural changes. This means: - Abstracting cryptographic operations behind well-defined interfaces - Storing algorithm identifiers alongside encrypted data - Supporting multiple algorithms simultaneously during transition periods - Testing new algorithms in parallel before fully migrating
Cryptographic agility is not just a post-quantum concern. History shows that algorithms are regularly deprecated (MD5, SHA-1, DES, RC4). Organizations that build agility into their architectures today will adapt more quickly to future transitions.
🔵 Blue Team Perspective: Begin your post-quantum preparation now: 1. Conduct a cryptographic inventory of all systems and their algorithms 2. Identify data with long-term confidentiality requirements (> 10 years) 3. Enable hybrid key exchange in TLS where available (modern browsers and servers already support it) 4. Test your infrastructure for compatibility with larger key sizes and certificates 5. Develop a cryptographic migration plan with timeline and priorities
The Quantum Timeline
A common question is "when will quantum computers break RSA?" The honest answer is that no one knows for certain. As of early 2026, the largest quantum computers have approximately 1,000-1,500 physical qubits. Breaking RSA-2048 is estimated to require millions of logical qubits (with error correction), which requires tens of millions to billions of physical qubits depending on error rates.
Current expert estimates for cryptographically relevant quantum computers (CRQCs):
| Estimate Source | Timeline |
|---|---|
| Optimistic (some quantum computing companies) | 2030-2035 |
| Moderate (NIST, academic consensus) | 2035-2045 |
| Conservative (some cryptographers) | 2045+ or never |
Regardless of the timeline, the "harvest now, decrypt later" threat means that data encrypted today may be at risk. For organizations handling classified information, healthcare records with long retention requirements, or trade secrets with multi-decade value, post-quantum migration is a present-day priority.
Implications for Penetration Testing
Post-quantum cryptography introduces new testing considerations:
- Check for PQC readiness: Does the target organization have a cryptographic inventory and a migration plan?
- Hybrid implementations: Test for correct implementation of hybrid key exchange
- Performance impact: PQC algorithms have larger key sizes and different performance characteristics. ML-KEM-768 public keys are 1,184 bytes (vs. 32 bytes for X25519).
- Certificate size: PQC certificates are larger, potentially causing issues with legacy systems that have buffer size limits
- New implementation bugs: PQC implementations are newer and less battle-tested, potentially containing novel vulnerabilities
Other Modern Cryptographic Developments
Zero-Knowledge Proofs (ZKPs): Allow one party to prove they know a value without revealing the value itself. Used in privacy-preserving authentication and blockchain systems. Pentesters should understand ZKPs when testing systems that claim zero-knowledge properties.
Homomorphic Encryption: Allows computation on encrypted data without decryption. Still largely theoretical for general computation, but practical for specific use cases like encrypted database queries. The security of the homomorphic encryption scheme itself is a testing target.
Multi-Party Computation (MPC): Allows multiple parties to jointly compute a function without revealing their individual inputs. Used in privacy-preserving data analysis and distributed key management.
💡 Key Insight: As a penetration tester in the 2020s and beyond, staying current with cryptographic developments is essential. The transition to post-quantum cryptography is the largest cryptographic migration in the history of the internet, and it will create new attack surfaces and implementation bugs for years to come.
28.8 Chapter Summary
Key Concepts
This chapter provided a comprehensive overview of cryptography from the penetration tester's perspective:
Cryptographic primitives form the building blocks. Hash functions provide integrity, symmetric encryption provides confidentiality, asymmetric encryption enables key exchange and digital signatures. Understanding these primitives is essential for identifying weaknesses.
TLS/SSL has evolved through continuous attack. From SSL 2.0 to TLS 1.3, each protocol version addressed weaknesses found in its predecessors. TLS 1.3 represents a major improvement, removing insecure algorithms and simplifying the handshake. Testing TLS configuration is a core penetration testing skill.
Historical protocol attacks teach fundamental lessons. BEAST, POODLE, DROWN, ROBOT, Heartbleed, and other attacks demonstrate recurring themes: padding oracles, downgrade attacks, cross-protocol weaknesses, and implementation bugs. These patterns continue to appear in new contexts.
PKI and certificate management are common weak points. Self-signed certificates, expired certificates, missing certificate pinning, and weak signature algorithms create exploitable weaknesses. Certificate Transparency provides both defensive monitoring and offensive reconnaissance.
Implementation flaws are more common than mathematical breaks. Padding oracles, ECB mode usage, IV reuse, weak random number generation, and hardcoded keys are practical vulnerabilities found in real applications. These do not require breaking the underlying mathematics.
Practical attacks target the ecosystem, not the algorithm. TLS stripping, downgrade attacks, JWT manipulation, and hash cracking exploit the way cryptography is used, not the algorithms themselves. The gap between cryptographic theory and its practical application is where most vulnerabilities live.
Post-quantum cryptography is an emerging concern. The "harvest now, decrypt later" threat makes post-quantum migration urgent even before practical quantum computers exist. NIST has standardized ML-KEM, ML-DSA, SLH-DSA, and FN-DSA. Hybrid approaches combining classical and post-quantum algorithms are being deployed today.
The Practical Takeaway
As a penetration tester, your cryptographic testing checklist should include: 1. TLS version and cipher suite assessment 2. Certificate validation and chain analysis 3. Key management and storage practices 4. Password hashing algorithm identification 5. JWT implementation review 6. Cryptographic protocol compliance 7. Random number generation quality 8. Post-quantum readiness assessment
You do not need to be a mathematician to find cryptographic vulnerabilities. You need to understand the principles, know the common mistakes, and have the tools to test for them.
What's Next
With evasion techniques (Chapter 27) and cryptographic analysis (Chapter 28) now in your toolkit, you have completed Part 5: Post-Exploitation and Advanced Techniques. In Part 6, we move to specialized domains -- starting with cloud security in Chapter 29, where the cryptographic concepts from this chapter will be essential for understanding cloud key management, encrypted storage, and TLS in cloud-native environments.
Review Questions
-
Explain the difference between symmetric and asymmetric encryption. Why do most systems use both (hybrid encryption)?
-
Why is ECB mode insecure for encrypting structured data? Describe a real-world scenario where ECB mode caused a security breach.
-
Walk through the TLS 1.2 handshake step by step. How does TLS 1.3 improve upon it?
-
Explain the POODLE attack. What protocol weakness did it exploit, and how was the downgrade component essential to the attack?
-
What is perfect forward secrecy, and why is it important? Which key exchange mechanisms provide PFS?
-
Describe a padding oracle attack. What conditions must exist for the attack to work, and what can it achieve?
-
How does certificate pinning work, and why is bypass testing important for mobile application security assessments?
-
Explain the "none algorithm" attack against JWT. What implementation mistake makes this attack possible?
-
What is the "harvest now, decrypt later" threat, and why does it make post-quantum cryptography urgent even before practical quantum computers exist?
-
You discover that MedSecure's patient portal supports TLS 1.0, uses RSA key exchange without PFS, and has a certificate signed with SHA-1. Describe the specific risks each of these findings represents and recommend mitigations.
Further Reading Preview
For additional resources on cryptography for penetration testers, see this chapter's further-reading.md, which includes references to foundational cryptography texts, TLS assessment tools, historical attack research papers, and post-quantum cryptography standards.