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:
parent
c5d65e823c
commit
cfb8157064
6 changed files with 997 additions and 0 deletions
83
captive_portal/certs/generate_ca.sh
Executable file
83
captive_portal/certs/generate_ca.sh
Executable file
|
|
@ -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"
|
||||
154
captive_portal/payloads/build_profile.py
Executable file
154
captive_portal/payloads/build_profile.py
Executable file
|
|
@ -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()
|
||||
210
captive_portal/server/activation_responses.py
Normal file
210
captive_portal/server/activation_responses.py
Normal 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)
|
||||
134
captive_portal/server/dns_config.py
Executable file
134
captive_portal/server/dns_config.py
Executable 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
262
captive_portal/server/portal.py
Executable 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()
|
||||
154
captive_portal/test_local.sh
Executable file
154
captive_portal/test_local.sh
Executable file
|
|
@ -0,0 +1,154 @@
|
|||
#!/usr/bin/env bash
|
||||
#
|
||||
# test_local.sh -- Test all captive portal endpoints on localhost.
|
||||
#
|
||||
# This script starts the portal server on a non-privileged port (8080),
|
||||
# runs through every endpoint, then cleans up.
|
||||
#
|
||||
# Usage:
|
||||
# chmod +x test_local.sh
|
||||
# ./test_local.sh
|
||||
#
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
SERVER_SCRIPT="$SCRIPT_DIR/server/portal.py"
|
||||
PORT=8080
|
||||
BASE="http://localhost:$PORT"
|
||||
PASS=0
|
||||
FAIL=0
|
||||
|
||||
# -- Helpers --------------------------------------------------------------
|
||||
|
||||
print_header() {
|
||||
echo ""
|
||||
echo "============================================"
|
||||
echo " $1"
|
||||
echo "============================================"
|
||||
}
|
||||
|
||||
check_response() {
|
||||
local label="$1"
|
||||
local expected="$2"
|
||||
local actual="$3"
|
||||
|
||||
if echo "$actual" | grep -q "$expected"; then
|
||||
echo " [PASS] $label"
|
||||
PASS=$((PASS + 1))
|
||||
else
|
||||
echo " [FAIL] $label -- expected '$expected' in response"
|
||||
echo " Response: $(echo "$actual" | head -5)"
|
||||
FAIL=$((FAIL + 1))
|
||||
fi
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
if [ -n "${SERVER_PID:-}" ] && kill -0 "$SERVER_PID" 2>/dev/null; then
|
||||
kill "$SERVER_PID" 2>/dev/null || true
|
||||
wait "$SERVER_PID" 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
# -- Start server on non-privileged port ---------------------------------
|
||||
|
||||
print_header "Starting server on port $PORT"
|
||||
|
||||
# Start server with env var port override (portal.py reads PORTAL_PORT)
|
||||
PORTAL_PORT=$PORT python3 "$SERVER_SCRIPT" &
|
||||
SERVER_PID=$!
|
||||
|
||||
# Wait for server to start
|
||||
sleep 1
|
||||
|
||||
if ! kill -0 "$SERVER_PID" 2>/dev/null; then
|
||||
echo "Error: Server failed to start."
|
||||
exit 1
|
||||
fi
|
||||
echo " Server PID: $SERVER_PID"
|
||||
|
||||
# -- Test GET endpoints ---------------------------------------------------
|
||||
|
||||
print_header "GET / (status page)"
|
||||
RESP=$(curl -s "$BASE/")
|
||||
check_response "Status page returns HTML" "Captive Portal Server" "$RESP"
|
||||
|
||||
print_header "GET /hotspot-detect.html (captive detection)"
|
||||
RESP=$(curl -s "$BASE/hotspot-detect.html")
|
||||
check_response "Does NOT return Success (triggers WebSheet)" "Network Configuration Required" "$RESP"
|
||||
# Verify it does NOT contain the Apple success string
|
||||
if echo "$RESP" | grep -q "<TITLE>Success</TITLE>"; then
|
||||
echo " [FAIL] Response contains Success -- WebSheet would dismiss"
|
||||
FAIL=$((FAIL + 1))
|
||||
else
|
||||
echo " [PASS] No Success title -- WebSheet stays open"
|
||||
PASS=$((PASS + 1))
|
||||
fi
|
||||
|
||||
print_header "GET /captive-portal (portal page)"
|
||||
RESP=$(curl -s "$BASE/captive-portal")
|
||||
check_response "Portal page has profile link" "profile.mobileconfig" "$RESP"
|
||||
|
||||
print_header "GET /profile.mobileconfig"
|
||||
RESP=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/profile.mobileconfig")
|
||||
# Profile may not exist yet (404 is acceptable if not built)
|
||||
if [ "$RESP" = "200" ]; then
|
||||
echo " [PASS] Profile served (200)"
|
||||
PASS=$((PASS + 1))
|
||||
elif [ "$RESP" = "404" ]; then
|
||||
echo " [PASS] Profile not built yet (404 expected before build_profile.py)"
|
||||
PASS=$((PASS + 1))
|
||||
else
|
||||
echo " [FAIL] Unexpected status: $RESP"
|
||||
FAIL=$((FAIL + 1))
|
||||
fi
|
||||
|
||||
# -- Test POST endpoints --------------------------------------------------
|
||||
|
||||
print_header "POST /deviceservices/drmHandshake"
|
||||
RESP=$(curl -s -X POST \
|
||||
-H "Content-Type: application/x-apple-plist" \
|
||||
-H "User-Agent: iOS Device Activator (MobileActivation-592.103.2)" \
|
||||
-d '<?xml version="1.0"?><plist version="1.0"><dict><key>Test</key><true/></dict></plist>' \
|
||||
"$BASE/deviceservices/drmHandshake")
|
||||
check_response "Handshake returns plist" "HandshakeResponseMessage" "$RESP"
|
||||
|
||||
print_header "POST /deviceservices/deviceActivation"
|
||||
RESP=$(curl -s -X POST \
|
||||
-H "Content-Type: application/x-www-form-urlencoded" \
|
||||
-H "User-Agent: iOS Device Activator (MobileActivation-592.103.2)" \
|
||||
-d 'activation-info=test_activation_data' \
|
||||
"$BASE/deviceservices/deviceActivation")
|
||||
check_response "Activation returns record" "ActivationRecord" "$RESP"
|
||||
|
||||
print_header "POST /humbug/baa"
|
||||
RESP=$(curl -s -X POST \
|
||||
-H "Content-Type: application/x-apple-plist" \
|
||||
-H "User-Agent: iOS Device Activator (MobileActivation-592.103.2)" \
|
||||
-d '<?xml version="1.0"?><plist version="1.0"><dict><key>Nonce</key><data>AAAA</data></dict></plist>' \
|
||||
"$BASE/humbug/baa")
|
||||
check_response "BAA returns provisioning response" "ProvisioningResponse" "$RESP"
|
||||
|
||||
# -- Test 404 handling ----------------------------------------------------
|
||||
|
||||
print_header "GET /nonexistent (404)"
|
||||
RESP=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/nonexistent")
|
||||
check_response "Returns 404" "404" "$RESP"
|
||||
|
||||
# -- Summary --------------------------------------------------------------
|
||||
|
||||
print_header "Results"
|
||||
TOTAL=$((PASS + FAIL))
|
||||
echo " Passed: $PASS / $TOTAL"
|
||||
echo " Failed: $FAIL / $TOTAL"
|
||||
|
||||
if [ "$FAIL" -gt 0 ]; then
|
||||
echo ""
|
||||
echo " Some tests failed."
|
||||
exit 1
|
||||
else
|
||||
echo ""
|
||||
echo " All tests passed."
|
||||
exit 0
|
||||
fi
|
||||
Loading…
Add table
Add a link
Reference in a new issue