feat(captive): Build captive portal + fake activation server

Captive portal HTTP server mimicking Apple's activation endpoints
(albert.apple.com, humb.apple.com). Handles captive detection,
profile serving, drmHandshake, deviceActivation, and VU#346053
baa endpoint. Includes cert generation, profile builder, DNS
config generator, and local test script.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
tr4m0ryp 2026-04-05 21:52:10 +02:00
parent c5d65e823c
commit cfb8157064
6 changed files with 997 additions and 0 deletions

View file

@ -0,0 +1,210 @@
#!/usr/bin/env python3
"""
Activation protocol response builders.
Constructs plist responses that mimic Apple's activation servers:
- albert.apple.com /deviceservices/drmHandshake
- albert.apple.com /deviceservices/deviceActivation
- humb.apple.com /humbug/baa
All certificate/key data uses placeholder values marked with TODO.
The plist structure is derived from binary analysis of MobileActivation.
"""
import plistlib
import uuid
import time
from datetime import datetime, timezone
# ---------------------------------------------------------------------------
# Constants derived from MobileActivation binary analysis
# ---------------------------------------------------------------------------
ACTIVATION_USER_AGENT = "iOS Device Activator (MobileActivation-592.103.2)"
HOST_IDENTIFIER = "thephonedoesntcarewhatisendhereitseems"
# TODO: Replace these with real extracted/generated values.
PLACEHOLDER_CERT = (
b"-----BEGIN CERTIFICATE-----\n"
b"PLACEHOLDER_DEVICE_CERTIFICATE_DATA\n"
b"TODO: Replace with actual device certificate\n"
b"-----END CERTIFICATE-----\n"
)
PLACEHOLDER_KEY_DATA = (
b"PLACEHOLDER_FAIRPLAY_KEY_DATA_"
b"TODO_REPLACE_WITH_ACTUAL_FP_KEYS"
)
PLACEHOLDER_FDR_BLOB = (
b"PLACEHOLDER_FDR_BLOB_DATA_"
b"TODO_REPLACE_WITH_EXTRACTED_FDR"
)
PLACEHOLDER_SERVER_KP = (
b"PLACEHOLDER_SERVER_KP_DATA_"
b"TODO_REPLACE_WITH_SERVER_KEYPAIR"
)
PLACEHOLDER_ACCOUNT_TOKEN = (
b"PLACEHOLDER_ACCOUNT_TOKEN_"
b"TODO_REPLACE_WITH_VALID_TOKEN"
)
# ---------------------------------------------------------------------------
# drmHandshake response
# ---------------------------------------------------------------------------
def build_handshake_response():
"""
Build a drmHandshake response plist.
This is the first message in the activation handshake. The device
sends its FairPlay identity; the server replies with keying material
that the device uses to build the full activation request.
Returns:
bytes: Binary plist data.
"""
response = {
"HandshakeResponseMessage": {
# Server key-pair material for the DRM session
# TODO: These must match the FairPlay protocol expectations
"serverKP": PLACEHOLDER_SERVER_KP,
# Factory Data Reset blob -- device uses this to prove identity
"FDRBlob": PLACEHOLDER_FDR_BLOB,
# Software Update info block
"SUInfo": {
"SUDocumentID": str(uuid.uuid4()),
"SUAllowedIn": True,
"SUVersion": "1.0",
},
# Session identifier
"sessionID": str(uuid.uuid4()),
# Timestamp
"timestamp": int(time.time()),
},
"Status": "SUCCESS",
"ProtocolVersion": "2",
}
return plistlib.dumps(response, fmt=plistlib.FMT_XML)
# ---------------------------------------------------------------------------
# deviceActivation response
# ---------------------------------------------------------------------------
def build_activation_record(device_info):
"""
Build a factory activation record plist.
Mimics the response from createFActivationInfo / deviceActivation.
The device validates this record to determine activation state.
Args:
device_info: Raw activation-info payload from the device (for logging).
Returns:
bytes: Binary plist data containing the activation record.
"""
# Unique identifiers for this activation
activation_id = str(uuid.uuid4())
now_iso = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
activation_record = {
# Account binding token
# TODO: Must be a valid token that passes MobileActivation validation
"AccountToken": PLACEHOLDER_ACCOUNT_TOKEN,
# Device certificate chain
# TODO: Must match device's FairPlay identity
"DeviceCertificate": PLACEHOLDER_CERT,
# FairPlay key data for DRM binding
# TODO: Derive from handshake session
"FairPlayKeyData": PLACEHOLDER_KEY_DATA,
# Activation state
"ActivationState": "Activated",
"ActivationStateDescription": "Factory Activated",
# Record metadata
"ActivationRecordID": activation_id,
"ActivationTimestamp": now_iso,
# Brick state flag -- False means the device should boot normally
"BrickState": False,
# Push registration (for APNs)
"PushToken": b"PLACEHOLDER_PUSH_TOKEN_TODO",
# Provisioning info
"UniqueDeviceID": HOST_IDENTIFIER,
}
# Wrap in the expected outer structure
response = {
"ActivationRecord": activation_record,
"Status": "SUCCESS",
"ProtocolVersion": "2",
"AccountTokenCertificate": PLACEHOLDER_CERT,
"DeviceActivation": {
"activation-record": plistlib.dumps(
activation_record, fmt=plistlib.FMT_XML
),
},
}
return plistlib.dumps(response, fmt=plistlib.FMT_XML)
# ---------------------------------------------------------------------------
# humbug/baa response (VU#346053)
# ---------------------------------------------------------------------------
def build_baa_response():
"""
Build a humb.apple.com/humbug/baa provisioning response.
VU#346053: The baa (Brick Activation Avoidance) endpoint handles
device provisioning. A crafted response here can influence the
device's activation state machine.
Returns:
bytes: Binary plist data.
"""
response = {
"ProtocolVersion": "2",
"Status": "SUCCESS",
# Provisioning response body
"ProvisioningResponse": {
# TODO: The real response includes signed provisioning data
"ProvisioningCertificateChain": PLACEHOLDER_CERT,
"ProvisioningData": (
b"PLACEHOLDER_PROVISIONING_DATA_"
b"TODO_REPLACE_WITH_CRAFTED_PAYLOAD"
),
# Nonce echo -- the device checks this matches its request
"Nonce": b"PLACEHOLDER_NONCE_TODO",
# Timestamp for replay protection
"Timestamp": int(time.time()),
# Session binding
"SessionID": str(uuid.uuid4()),
},
# BAA-specific flags
"BAAResponse": {
"AllowActivation": True,
"BrickState": False,
"GracePeriod": 0,
"Message": "Device provisioning successful",
},
}
return plistlib.dumps(response, fmt=plistlib.FMT_XML)

View file

@ -0,0 +1,134 @@
#!/usr/bin/env python3
"""
DNS configuration generator for captive portal.
Generates a dnsmasq.conf that redirects Apple activation and captive
portal domains to the local server. Also configures DHCP so connected
devices use this server as their gateway and DNS resolver.
Usage:
python3 dns_config.py [server_ip] [output_file]
Defaults:
server_ip = 192.168.1.1
output_file = stdout
"""
import os
import sys
from datetime import datetime
# ---------------------------------------------------------------------------
# Domains that must resolve to our server
# ---------------------------------------------------------------------------
REDIRECT_DOMAINS = [
# Captive portal detection
"captive.apple.com",
"www.apple.com",
"www.appleiphonecell.com",
"www.itools.info",
"www.ibook.info",
"www.airport.us",
"www.thinkdifferent.us",
# Activation servers
"albert.apple.com",
"humb.apple.com",
# Software / catalog / provisioning
"gs.apple.com",
"mesu.apple.com",
"osrecovery.apple.com",
"isu.apple.com",
# Identity services (optional, for deeper interception)
"identity.ess.apple.com",
"setup.icloud.com",
]
def generate_dnsmasq_conf(
server_ip="192.168.1.1",
dhcp_start=None,
dhcp_end=None,
log_path=None,
):
"""
Generate dnsmasq configuration text.
Args:
server_ip: IP address of this server on the test network.
dhcp_start: First address in DHCP pool (default: server_ip range .100).
dhcp_end: Last address in DHCP pool (default: server_ip range .200).
log_path: Path for DNS query log (default: alongside this script).
Returns:
str: Complete dnsmasq.conf content.
"""
# Derive DHCP range from server IP if not specified
prefix = ".".join(server_ip.split(".")[:3])
if dhcp_start is None:
dhcp_start = f"{prefix}.100"
if dhcp_end is None:
dhcp_end = f"{prefix}.200"
if log_path is None:
log_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "dns.log"
)
lines = []
lines.append(f"# dnsmasq configuration for captive portal")
lines.append(f"# Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
lines.append(f"# Server IP: {server_ip}")
lines.append("")
# -- DNS redirection --------------------------------------------------
lines.append("# ---- Domain redirection ----")
lines.append("# Redirect Apple activation + captive portal domains")
for domain in REDIRECT_DOMAINS:
lines.append(f"address=/{domain}/{server_ip}")
lines.append("")
# -- DHCP configuration -----------------------------------------------
lines.append("# ---- DHCP ----")
lines.append(f"dhcp-range={dhcp_start},{dhcp_end},12h")
lines.append(f"dhcp-option=3,{server_ip} # Default gateway")
lines.append(f"dhcp-option=6,{server_ip} # DNS server")
lines.append("")
# -- General settings -------------------------------------------------
lines.append("# ---- General ----")
lines.append("no-resolv")
lines.append("no-hosts")
lines.append(f"listen-address={server_ip},127.0.0.1")
lines.append("bind-interfaces")
lines.append("")
# -- Logging ----------------------------------------------------------
lines.append("# ---- Logging ----")
lines.append("log-queries")
lines.append(f"log-facility={log_path}")
lines.append("")
return "\n".join(lines) + "\n"
# ---------------------------------------------------------------------------
# CLI entry point
# ---------------------------------------------------------------------------
def main():
server_ip = sys.argv[1] if len(sys.argv) > 1 else "192.168.1.1"
output_file = sys.argv[2] if len(sys.argv) > 2 else None
conf = generate_dnsmasq_conf(server_ip=server_ip)
if output_file:
with open(output_file, "w") as f:
f.write(conf)
print(f"Written to {output_file}")
else:
print(conf)
if __name__ == "__main__":
main()

262
captive_portal/server/portal.py Executable file
View file

@ -0,0 +1,262 @@
#!/usr/bin/env python3
"""
Captive portal HTTP server for iOS activation research.
Simulates Apple's captive portal detection and activation endpoints:
- captive.apple.com/hotspot-detect.html
- albert.apple.com/deviceservices/*
- humb.apple.com/humbug/baa
All requests are logged for analysis.
"""
import os
import sys
import json
import time
import logging
from datetime import datetime
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import parse_qs, unquote_plus
# ---------------------------------------------------------------------------
# Paths
# ---------------------------------------------------------------------------
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_DIR = os.path.dirname(SCRIPT_DIR)
PAYLOADS_DIR = os.path.join(PROJECT_DIR, "payloads")
ACCESS_LOG = os.path.join(SCRIPT_DIR, "access.log")
REQUESTS_DIR = os.path.join(SCRIPT_DIR, "requests")
os.makedirs(REQUESTS_DIR, exist_ok=True)
# ---------------------------------------------------------------------------
# Logging
# ---------------------------------------------------------------------------
file_handler = logging.FileHandler(ACCESS_LOG)
file_handler.setFormatter(logging.Formatter(
"%(asctime)s | %(message)s", datefmt="%Y-%m-%d %H:%M:%S"
))
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(logging.Formatter(
"\033[36m%(asctime)s\033[0m | %(message)s", datefmt="%H:%M:%S"
))
logger = logging.getLogger("portal")
logger.setLevel(logging.DEBUG)
logger.addHandler(file_handler)
logger.addHandler(stream_handler)
# ---------------------------------------------------------------------------
# Lazy import of response builders
# ---------------------------------------------------------------------------
sys.path.insert(0, SCRIPT_DIR)
from activation_responses import (
build_handshake_response,
build_activation_record,
build_baa_response,
)
# ---------------------------------------------------------------------------
# HTML templates
# ---------------------------------------------------------------------------
STATUS_PAGE = """\
<!DOCTYPE html>
<html><head><title>Portal Status</title>
<style>
body{font-family:Helvetica,Arial,sans-serif;background:#111;color:#eee;
display:flex;align-items:center;justify-content:center;height:100vh;margin:0}
.box{text-align:center;border:1px solid #333;padding:2em 3em;border-radius:8px}
h1{margin:0 0 .5em}
p{color:#888}
</style></head>
<body><div class="box">
<h1>Captive Portal Server</h1>
<p>Running -- all endpoints operational.</p>
<p style="font-size:.8em;color:#555">Started: %(started)s</p>
</div></body></html>
"""
CAPTIVE_PAGE = """\
<!DOCTYPE html>
<html><head><title>Network Authentication</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
body{font-family:-apple-system,Helvetica,Arial,sans-serif;background:#f5f5f7;
color:#1d1d1f;margin:0;padding:2em;text-align:center}
.card{background:#fff;border-radius:12px;padding:2em;max-width:400px;
margin:3em auto;box-shadow:0 2px 12px rgba(0,0,0,.08)}
h1{font-size:1.3em;margin-bottom:.5em}
p{color:#666;line-height:1.5}
a.btn{display:inline-block;margin-top:1.5em;padding:.8em 2em;
background:#0071e3;color:#fff;border-radius:8px;text-decoration:none;
font-weight:600}
a.btn:hover{background:#005bb5}
.note{font-size:.75em;color:#999;margin-top:1.5em}
</style></head>
<body>
<div class="card">
<h1>Network Configuration Required</h1>
<p>This network requires authentication. Install the network profile
to continue.</p>
<a class="btn" href="/profile.mobileconfig">Install Profile</a>
<p class="note">The profile configures your device for secure access
to this network.</p>
</div>
</body></html>
"""
SERVER_START_TIME = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# ---------------------------------------------------------------------------
# Request body logger
# ---------------------------------------------------------------------------
_request_counter = 0
def _save_request_body(method, path, body):
"""Persist request body to individual file for later analysis."""
global _request_counter
_request_counter += 1
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
safe_path = path.strip("/").replace("/", "_") or "root"
fname = f"{ts}_{_request_counter}_{method}_{safe_path}.bin"
fpath = os.path.join(REQUESTS_DIR, fname)
with open(fpath, "wb") as f:
f.write(body)
return fpath
# ---------------------------------------------------------------------------
# Handler
# ---------------------------------------------------------------------------
class PortalHandler(BaseHTTPRequestHandler):
"""Routes requests to the appropriate handler."""
# Silence default stderr logging (we handle it ourselves)
def log_message(self, fmt, *args):
logger.info("%s %s %s", self.address_string(), self.command, self.path)
# -- Helpers ----------------------------------------------------------
def _send(self, code, content_type, body):
if isinstance(body, str):
body = body.encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def _read_body(self):
length = int(self.headers.get("Content-Length", 0))
return self.rfile.read(length) if length else b""
# -- GET routes -------------------------------------------------------
def do_GET(self):
path = self.path.split("?")[0]
if path == "/":
self._handle_status()
elif path == "/hotspot-detect.html":
self._handle_hotspot()
elif path == "/captive-portal":
self._handle_captive()
elif path == "/profile.mobileconfig":
self._handle_profile()
else:
self._send(404, "text/plain", "Not Found")
def _handle_status(self):
html = STATUS_PAGE % {"started": SERVER_START_TIME}
self._send(200, "text/html", html)
def _handle_hotspot(self):
# Apple expects the literal string "<HTML><HEAD><TITLE>Success</TITLE>"
# to dismiss the WebSheet. Returning anything else keeps it open.
logger.info(" >> Captive detection hit -- returning portal page")
self._send(200, "text/html", CAPTIVE_PAGE)
def _handle_captive(self):
self._send(200, "text/html", CAPTIVE_PAGE)
def _handle_profile(self):
profile_path = os.path.join(PAYLOADS_DIR, "network.mobileconfig")
if not os.path.isfile(profile_path):
logger.warning(" >> Profile not found at %s", profile_path)
self._send(404, "text/plain",
"Profile not built yet. Run payloads/build_profile.py first.")
return
with open(profile_path, "rb") as f:
data = f.read()
logger.info(" >> Serving profile (%d bytes)", len(data))
self._send(200, "application/x-apple-aspen-config", data)
# -- POST routes ------------------------------------------------------
def do_POST(self):
path = self.path.split("?")[0]
body = self._read_body()
saved = _save_request_body("POST", path, body)
logger.info(" >> POST body saved to %s (%d bytes)", saved, len(body))
if path == "/deviceservices/drmHandshake":
self._handle_handshake(body)
elif path == "/deviceservices/deviceActivation":
self._handle_activation(body)
elif path == "/humbug/baa":
self._handle_baa(body)
else:
self._send(404, "text/plain", "Not Found")
def _handle_handshake(self, body):
logger.info(" >> drmHandshake request received")
resp = build_handshake_response()
self._send(200, "application/x-apple-plist", resp)
def _handle_activation(self, body):
logger.info(" >> deviceActivation request received")
# Parse URL-encoded body to extract activation-info
try:
params = parse_qs(body.decode("utf-8", errors="replace"))
device_info = params.get("activation-info", [b""])[0]
except Exception:
device_info = body
resp = build_activation_record(device_info)
self._send(200, "application/x-apple-plist", resp)
def _handle_baa(self, body):
logger.info(" >> humbug/baa request received (VU#346053 target)")
resp = build_baa_response()
self._send(200, "application/x-apple-plist", resp)
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
def main():
host = "0.0.0.0"
port = int(os.environ.get("PORTAL_PORT", 80))
print("\033[1;32m" + "=" * 56)
print(" Captive Portal Server")
print("=" * 56 + "\033[0m")
print(f" Listening on {host}:{port}")
print(f" Access log: {ACCESS_LOG}")
print(f" Request log: {REQUESTS_DIR}/")
print()
try:
server = HTTPServer((host, port), PortalHandler)
server.serve_forever()
except PermissionError:
print("\033[1;31mError: Port 80 requires root. Run with sudo.\033[0m")
sys.exit(1)
except KeyboardInterrupt:
print("\n\033[33mShutting down.\033[0m")
server.server_close()
if __name__ == "__main__":
main()