Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions dm/host/hle_ssl_apple.m
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,7 @@ static uint32_t prepare(DmTlsConnection *c) {
c.handshaking = YES; uint32_t result = status_result(c, s);
trace(c, DM_TLS_PREPARE, result, s, v); return result;
}
static BOOL verify_peer(DmTlsConnection *c) {
static BOOL verify_peer(DmTlsConnection *c, unsigned *reason) {
SecTrustRef trust = NULL; if (SSLCopyPeerTrust(c->tls, &trust) || !trust) return NO;
if (c.policyPinned) {
SecCertificateRef leaf = SecTrustGetCertificateAtIndex(trust, 0);
Expand All @@ -464,6 +464,7 @@ static BOOL verify_peer(DmTlsConnection *c) {
CFErrorRef failure = NULL;
dm_guest_host_wait_begin();
BOOL valid = !result && SecTrustEvaluateWithError(trust, &failure);
if (!valid) *reason = DM_TLS_VERIFY_PLATFORM_TRUST;
if (valid) {
CFIndex count = SecTrustGetCertificateCount(trust);
NSMutableArray<NSData *> *data = [NSMutableArray new];
Expand All @@ -477,6 +478,7 @@ static BOOL verify_peer(DmTlsConnection *c) {
}
if (valid) valid = dm_nextendo_x509_verify(c.peerName.UTF8String, c.policyAnchor.bytes,
c.policyAnchor.length, chain, sizes, (size_t)count);
if (!valid) *reason = DM_TLS_VERIFY_STRICT_X509;
}
dm_guest_host_wait_end();
if (failure) CFRelease(failure); CFRelease(trust); return valid;
Expand All @@ -503,14 +505,16 @@ static uint32_t handshake_locked(DmTlsConnection *c) {
if (atomic_load(&c->closed)) return error(c, DM_SSL_BAD_SOCKET);
c->wanted = POLLIN; OSStatus status = SSLHandshake(c->tls);
if (status == errSSLServerAuthCompleted) {
BOOL valid = verify_peer(c); trace(c, DM_TLS_VERIFY, valid ? 0 : DM_SSL_FAIL, status, 0);
unsigned reason = 0;
BOOL valid = verify_peer(c, &reason); trace(c, DM_TLS_VERIFY, valid ? 0 : DM_SSL_FAIL, status, reason);
if (!valid) { c.rejected = YES; c.verifyError = DM_SSL_FAIL; SSLSetError(c->tls, errSSLXCertChainInvalid); return error(c, DM_SSL_FAIL); }
c.verified = YES;
continue;
}
if (!status) {
if (!c.verified) {
BOOL valid = verify_peer(c); trace(c, DM_TLS_VERIFY, valid ? 0 : DM_SSL_FAIL, status, 0);
unsigned reason = 0;
BOOL valid = verify_peer(c, &reason); trace(c, DM_TLS_VERIFY, valid ? 0 : DM_SSL_FAIL, status, reason);
if (!valid) { c.rejected = YES; c.verifyError = DM_SSL_FAIL; SSLSetError(c->tls, errSSLXCertChainInvalid); return error(c, DM_SSL_FAIL); }
}
c.verified = YES; c.established = YES; trace(c, DM_TLS_HANDSHAKE, 0, 0, 0); return error(c, 0);
Expand Down
11 changes: 9 additions & 2 deletions dm/host/ssl_trace.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ typedef enum {
DM_TLS_READ, DM_TLS_WRITE
} dm_tls_stage;

enum { DM_TLS_VERIFY_PLATFORM_TRUST = 1, DM_TLS_VERIFY_STRICT_X509 };

static inline void dm_tls_trace(dm_tls_stage stage, uint64_t session, uint32_t result,
int32_t native, uint64_t detail, unsigned flags) {
int saved = errno;
Expand All @@ -22,9 +24,14 @@ static inline void dm_tls_trace(dm_tls_stage stage, uint64_t session, uint32_t r
unsigned used = atomic_load(&events);
while (used < 128) {
if (atomic_compare_exchange_weak(&events, &used, used + 1)) {
const char *reason = "";
if (stage == DM_TLS_VERIFY && result) {
if (detail == DM_TLS_VERIFY_PLATFORM_TRUST) reason = " verify=platform-trust";
else if (detail == DM_TLS_VERIFY_STRICT_X509) reason = " verify=strict-x509";
}
fprintf(stderr, "[ssl-trace] stage=%u session=%" PRIu64 " result=0x%08" PRIx32
" native=%" PRId32 " detail=%" PRIu64 " flags=0x%02x\n",
(unsigned)stage, session, result, native, detail, flags);
" native=%" PRId32 " detail=%" PRIu64 " flags=0x%02x%s\n",
(unsigned)stage, session, result, native, detail, flags, reason);
break;
}
}
Expand Down
10 changes: 5 additions & 5 deletions dm/host/tests/t_nextendo_routes.c
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ static void resolve_checks(int ready) {
hint.flags = 4; CHECK(dm_net_getaddrinfo("api.console.invalid", "443", &hint, &output) == 8 && !output, "AI_NUMERICHOST does not turn a mapped DNS name into a numeric caller input");
hint.flags = 1; CHECK(dm_net_getaddrinfo(NULL, "0", &hint, &output) == 0 && output, "passive null-host binding never requires a DNS service route"); if (output) dm_net_freeaddrinfo(output);
}
static void tls_checks(int ready, unsigned port, bool reject_pin) {
static void tls_checks(int ready, unsigned port, bool reject_peer) {
char context[32] = {0}, connection[32] = {0}; CHECK(dm_ssl_context_create(context, 32) == 0 && dm_ssl_connection_create(connection, context) == 0, "actual native TLS registry prepared");
CHECK(dm_ssl_set_hostname(connection, "never-configured.nintendo.net", 29) != 0, "unknown SNI cannot bypass fail-closed DNS through a literal socket");
CHECK(dm_ssl_set_hostname(connection, "127.0.0.9", 9) != 0, "an unconfigured numeric address does not authorize TLS SNI");
Expand All @@ -54,12 +54,12 @@ static void tls_checks(int ready, unsigned port, bool reject_pin) {
CHECK(dm_net_getaddrinfo("api.console.invalid", service, &hint, &answer) == 0 && answer, "actual TLS socket obtains the routed resolver address");
int fd = dm_net_socket(2, 1, 6); dm_net_addrinfo *info = answer;
CHECK(info && fd >= 0 && dm_net_connect(fd, info->addr, info->addrlen) == 0 && dm_ssl_set_socket(connection, fd) == 0, "guest TCP descriptor is connected and borrowed safely"); if (answer) dm_net_freeaddrinfo(answer);
if (reject_pin) {
CHECK(dm_ssl_handshake(connection) != 0, "a different enrolled certificate rejects the actual TLS peer");
if (reject_peer) {
CHECK(dm_ssl_handshake(connection) != 0, "a different CA or enrolled certificate rejects the actual TLS peer");
int sent = 99; uint32_t verification = 0;
CHECK(dm_ssl_last_error(connection, &verification, true) == 0 && verification &&
dm_ssl_write(connection, "PING", &sent, 4) != 0 && sent == 0,
"failed pin verification retains its error and sends no application data");
"failed verification retains its error and sends no application data");
dm_ssl_connection_destroy(connection); dm_ssl_context_destroy(context); return;
}
CHECK(dm_ssl_handshake(connection) == 0, "mapped SNI and only its scoped DER CA complete a real TLS handshake");
Expand Down Expand Up @@ -117,7 +117,7 @@ int main(int argc, char **argv) {
CHECK(dm_bcat_online_enabled() == (status == 0), "BCAT capability requires an opted-in, fully published profile");
resolve_checks(status == 0);
setenv("DM_NETWORK", "auto", 1); resolve_checks(status == 0);
tls_checks(status == 0, argc >= 4 ? (unsigned)strtoul(argv[3],NULL,10) : 0, argc == 5 && !strcmp(argv[4], "reject-pin"));
tls_checks(status == 0, argc >= 4 ? (unsigned)strtoul(argv[3],NULL,10) : 0, argc == 5 && !strcmp(argv[4], "reject-peer"));
if (argc == 5 && !strcmp(argv[4], "v2")) v2_checks();
if (argc == 5 && !strcmp(argv[4], "handoff")) handoff_checks((unsigned)strtoul(argv[3], NULL, 10));
unsetenv("DM_NEXTENDO_ROUTES"); setenv("DM_NETWORK", "auto", 1);
Expand Down
16 changes: 15 additions & 1 deletion dm/host/tests/test_nextendo_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@ def serve(listener=listener, tls=tls):
(root/'pin-endpoint.cnf').write_text('basicConstraints=critical,CA:TRUE\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid\n')
command(['openssl','x509','-req','-in','server.csr','-signkey','server.key','-days','1','-extfile','pin-endpoint.cnf','-out','pin.pem'], folder)
command(['openssl','x509','-in','pin.pem','-outform','der','-out','pin.der'], folder)
untrusted = root / 'untrusted-ca.tsv'
untrusted.write_text(text.replace('ca.der', 'pin.der').replace(digest, hashlib.sha256((root/'pin.der').read_bytes()).hexdigest()))
untrusted.chmod(0o600)
command(['openssl','x509','-req','-in','server.csr','-signkey','server.key','-days','1','-set_serial','1234567','-out','other-pin.pem'], folder)
command(['openssl','x509','-in','other-pin.pem','-outform','der','-out','other-pin.der'], folder)
pin_tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
Expand All @@ -142,6 +145,17 @@ def serve(listener=listener, tls=tls):
(root/certificate).chmod(0o600); pin_configs.append((path,reject,name == 'pin-handoff'))
total = 0
try:
verify_env = {**os.environ, "DM_SSL_TRACE": "1"}
for path, label in [(config, 'strict-x509'), (untrusted, 'platform-trust')]:
args = [str(executable), str(path), '0', str(listener.getsockname()[1])]
if path == untrusted: args.append('reject-peer')
result = subprocess.run(args, env=verify_env, text=True, capture_output=True, timeout=15, check=True)
failed = [line for line in result.stderr.splitlines() if line.startswith('[ssl-trace] stage=5 ') and 'result=0x00000000' not in line]
if len(failed) != 1 or not re.fullmatch(
r'\[ssl-trace\] stage=5 session=\d+ result=0x[0-9a-f]{8} native=-?\d+ detail=\d+ flags=0x[0-9a-f]{2} verify=' + label, failed[0]
):
raise AssertionError(f"expected only the {label} verification failure label, got {failed}")
print("TLS verify trace: distinct fixed labels for platform trust and strict X.509")
for path, status in cases:
args = [str(executable), path, str(status)]
if path in (str(config), str(v2)):
Expand All @@ -155,7 +169,7 @@ def serve(listener=listener, tls=tls):
raise AssertionError(result.stdout)
total += int(match[1])
for path,reject,handoff in pin_configs:
result=subprocess.run([str(executable),str(path),'0',str(pin_listener.getsockname()[1]),'reject-pin' if reject else 'handoff' if handoff else 'v2'],text=True,capture_output=True,timeout=15)
result=subprocess.run([str(executable),str(path),'0',str(pin_listener.getsockname()[1]),'reject-peer' if reject else 'handoff' if handoff else 'v2'],text=True,capture_output=True,timeout=15)
if result.returncode: raise AssertionError(f'enrolled leaf {path.name}: {result.stdout}\n{result.stderr}')
match = re.search(r'routes: (\d+) checks, 0 failures',result.stdout)
if match is None: raise AssertionError(result.stdout)
Expand Down
1 change: 1 addition & 0 deletions docs/agents/symptoms.md
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
## Optional online-service backend

- an enabled native socket connects, but the SDK's TLS context is still an unavailable-service cut. → [Native client TLS](../reference/online-services.md#native-client-tls)
- `DM_SSL_TRACE=1` reports the same verify failure for a rejected chain and for a chain that passes platform trust but fails strict X.509. → [A scoped CA failure does not say which TLS check rejected it](../reference/online-services.md#a-scoped-ca-failure-does-not-say-which-tls-check-rejected-it)
- a service template reaches native DNS unchanged, or an IP handoff loses the logical TLS service identity. → [Explicit routing and NSD](../reference/online-services.md#explicit-routing-and-nsd)
- a service transport works but the SDK has no usable account identity/token or friends snapshot. → [Account and social providers](../reference/online-services.md#account-and-social-providers)

Expand Down
2 changes: 1 addition & 1 deletion docs/env_switches.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ DM_SPIN switch `0` makes the rewriter's spin gate return at once, so guest poll
DM_SPIN_LIST diagnostic `=1` makes `patch_nso.py` print every guest poll loop it found and sends through a spin gate
DM_SPIN_POLL switch `=<µs>`: how long a spin-gate wait polls before it sleeps with the yield back-off (default 2000; `0` yields on every pass)
DM_SPLIT_REGISTERED_MAP path Registered `shader_map.tsv` used by the splitter to keep a known source label when the same shader is found in several places
DM_SSL_TRACE diagnostic 1 logs at most 128 numeric TLS state events; no hosts, pointers, credentials or stream data.
DM_SSL_TRACE diagnostic 1 logs at most 128 TLS state events with numeric fields and fixed verify failure labels; no hosts, pointers, certificates, credentials or stream data.
DM_SVC diagnostic `=1` logs memory SVCs (`SetHeapSize`, `MapMemory`, `Map`/`UnmapPhysicalMemory`) with their addresses and sizes
DM_SW2 player `=1` turns on Switch 2 controllers over Bluetooth LE (Joy-Con 2, Pro Controller 2): the settings window's Switch 2 controllers. Off, no Bluetooth client is created and macOS asks nothing. The host also stays off when the app's Info.plist has no NSBluetoothAlwaysUsageDescription, without which macOS ends the process at the first Bluetooth scan
DM_SW2_GYRO_DPS diagnostic `=<degrees per second per count>` is the Switch 2 controllers' gyro scale (default 0.0607, measured on a left and a right Joy-Con 2; the Switch family's nominal 0.070 turned a 90 degree tilt into 104)
Expand Down
9 changes: 8 additions & 1 deletion docs/reference/online-services.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@ This backend is independent of a game library or authorization interface. I extr
- **Build:** `dm/tools/apple_crypto.py` pins OpenSSL source by SHA-256 and builds static libcrypto for the selected Apple SDK. The DM_OPENSSL_ROOT build variable may point to an already prepared target-compatible prefix. The iOS source/flags generator propagates the static archive to both real and smoke links; a Mac archive is not an iPhone dependency. The [OpenSSL license and provenance](../../dm/third_party/notices/OpenSSL/PROVENANCE.md) must accompany redistributed linked applications. No OpenSSL binary is committed.
- **Check:** I exercised real loopback TLS through the guest's registered C/C++ gates using ephemeral test certificates: SNI/hostname failures, nonblocking progression, data, polling, certificate buffers, descriptor generation/close ownership, context IDs, ALPN and lifecycle. The private verifier separately rejects malformed DER, wrong purposes/names/anchors, weak/invalid signatures, expired/future leaves and an unpaired/rotated enrolled certificate. No user account or public game server is involved in these fixtures.

### A scoped CA failure does not say which TLS check rejected it

- **Symptom:** `DM_SSL_TRACE=1` reports the same verify failure for a rejected chain and for a chain that passes platform trust but fails strict X.509.
- **Cause:** the verify trace kept only the combined outcome.
- **Fix:** append `verify=platform-trust` or `verify=strict-x509` to the existing failure event for this path. Neither label carries peer data or changes the verification result.
- **Found on:** loopback TLS with an untrusted CA and with a trusted chain for the wrong name.

### Explicit routing and NSD

- **Symptom:** a service template reaches native DNS unchanged, or an IP handoff loses the logical TLS service identity.
Expand Down Expand Up @@ -44,6 +51,6 @@ make -C dm/host/tests GAME=010015100B514000 nextendo-routes nextendo-routes-sani
make -C dm/host/tests GAME=010015100B514000 nextendo-account nextendo-account-sanitize nextendo-api nextendo-api-sanitize nextendo-social nextendo-social-sanitize
```

`DM_SSL_TRACE=1` enables at most 128 numeric state events and preserves errno; it never prints names, addresses, pointers, certificates, credentials or stream contents. `DM_SYSTEM_DATA_DIR` can point at the player's private original system resources for the certificate store (`0100000000000800/files/ssl_TrustedCerts.bdf`); without it the host reads the CertStore archive's file from `DM_SYSTEM_DIR`'s `sysdata/0100000000000800/` (the iOS app's `Documents/system`). None is distributed here. With no store file in either place, a stand-in CA set with `dm_ssl_set_builtin_fallback` answers the built-in requests under each ID asked for: in Nextendo mode, the service profile's CA (`hle_nextendo_routes.c`), so the sign-in is all a game's own TLS needs. A store that is there but rejected still fails. The first outcome of each kind is logged (`ssl: certificate store: ...`, which place and how many certificates, or why none), and every built-in certificate request once (`ssl: built-in certificates ...`, IDs and result only).
`DM_SSL_TRACE=1` enables at most 128 state events with numeric fields and fixed verify failure labels, and preserves errno. It never prints names, addresses, pointers, certificates, credentials or stream contents. `DM_SYSTEM_DATA_DIR` can point at the player's private original system resources for the certificate store (`0100000000000800/files/ssl_TrustedCerts.bdf`); without it the host reads the CertStore archive's file from `DM_SYSTEM_DIR`'s `sysdata/0100000000000800/` (the iOS app's `Documents/system`). None is distributed here. With no store file in either place, a stand-in CA set with `dm_ssl_set_builtin_fallback` answers the built-in requests under each ID asked for: in Nextendo mode, the service profile's CA (`hle_nextendo_routes.c`), so the sign-in is all a game's own TLS needs. A store that is there but rejected still fails. The first outcome of each kind is logged (`ssl: certificate store: ...`, which place and how many certificates, or why none), and every built-in certificate request once (`ssl: built-in certificates ...`, IDs and result only).

In my originating fork I validated the Mario Kart 8 Deluxe 4.0.1 online connection path on Mac (not a completed Nextendo race), a Smash 13.0.5 arena on Mac, and Splatoon 2 EUR 5.5.2 reaching its lobby and Territorial queue. Those configurations used separately reviewed service trust policies; no observed leaf is part of this contribution. I did not complete a Splatoon match. These historical tests do not qualify every game, iOS online, a new upstream shader chain or this rebased extraction. I have not repeated the five-game graphical regression on this backend-only branch; the no-GUI fixtures, HLE registry and Apple compile checks are separate evidence.