Commit 7fdbc11974
Unsigned
Layout: unified · split
App/Sources/AppAttest.swift added +52
| @@ -0,0 +1,52 @@ | |||
| 1 | import CryptoKit | ||
| 2 | import DeviceCheck | ||
| 3 | import Foundation | ||
| 4 | |||
| 5 | /// App Attest for device registration: a key attested once with the backend, then an assertion over each | ||
| 6 | /// registration body. Nil where App Attest is unsupported (the Simulator) or fails; the backend accepts unsigned | ||
| 7 | /// registrations unless it is set to require them. | ||
| 8 | @MainActor | ||
| 9 | enum AppAttest { | ||
| 10 | private static let keyIDKey = "appAttestKeyID" | ||
| 11 | |||
| 12 | /// Adds a fresh challenge to `body`, then returns the serialized body and the assertion headers for it. | ||
| 13 | static func sign(_ body: [String: Any], base: URL) async -> (Data, [String: String])? { | ||
| 14 | let service = DCAppAttestService.shared | ||
| 15 | guard service.isSupported, let keyID = await attestedKey(base: base), let challenge = await challenge(base: base) else { return nil } | ||
| 16 | var body = body | ||
| 17 | body["challenge"] = challenge | ||
| 18 | guard let data = try? JSONSerialization.data(withJSONObject: body) else { return nil } | ||
| 19 | do { | ||
| 20 | let assertion = try await service.generateAssertion(keyID, clientDataHash: Data(SHA256.hash(data: data))) | ||
| 21 | return (data, ["x-app-attest-key": keyID, "x-app-attest-assertion": assertion.base64EncodedString()]) | ||
| 22 | } catch let error as DCError where error.code == .invalidKey { | ||
| 23 | UserDefaults.standard.removeObject(forKey: keyIDKey) | ||
| 24 | return nil | ||
| 25 | } catch { | ||
| 26 | return nil | ||
| 27 | } | ||
| 28 | } | ||
| 29 | |||
| 30 | /// The stored key, or a new one attested with the backend. | ||
| 31 | private static func attestedKey(base: URL) async -> String? { | ||
| 32 | if let id = UserDefaults.standard.string(forKey: keyIDKey) { return id } | ||
| 33 | let service = DCAppAttestService.shared | ||
| 34 | guard let id = try? await service.generateKey(), let challenge = await challenge(base: base), let bytes = Data(base64Encoded: challenge), | ||
| 35 | let attestation = try? await service.attestKey(id, clientDataHash: Data(SHA256.hash(data: bytes))) else { return nil } | ||
| 36 | var req = URLRequest(url: base.appending(path: "v1/attest")) | ||
| 37 | req.httpMethod = "POST" | ||
| 38 | req.setValue("application/json", forHTTPHeaderField: "content-type") | ||
| 39 | req.httpBody = try? JSONSerialization.data(withJSONObject: ["keyId": id, "attestation": attestation.base64EncodedString(), "challenge": challenge]) | ||
| 40 | guard let (_, response) = try? await URLSession.shared.data(for: req), (response as? HTTPURLResponse)?.statusCode == 200 else { return nil } | ||
| 41 | UserDefaults.standard.set(id, forKey: keyIDKey) | ||
| 42 | return id | ||
| 43 | } | ||
| 44 | |||
| 45 | private static func challenge(base: URL) async -> String? { | ||
| 46 | var req = URLRequest(url: base.appending(path: "v1/challenge")) | ||
| 47 | req.httpMethod = "POST" | ||
| 48 | guard let (data, _) = try? await URLSession.shared.data(for: req), | ||
| 49 | let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil } | ||
| 50 | return json["challenge"] as? String | ||
| 51 | } | ||
| 52 | } | ||
App/Sources/AuroraAlerts.swift +6 −1
| @@ -82,7 +82,12 @@ final class AuroraAlerts { | |||
| 82 | var req = URLRequest(url: apiBase.appending(path: "v1/devices")) | 82 | var req = URLRequest(url: apiBase.appending(path: "v1/devices")) |
| 83 | req.httpMethod = "POST" | 83 | req.httpMethod = "POST" |
| 84 | req.setValue("application/json", forHTTPHeaderField: "content-type") | 84 | req.setValue("application/json", forHTTPHeaderField: "content-type") |
| 85 | req.httpBody = try? JSONSerialization.data(withJSONObject: body) | 85 | if let (data, headers) = await AppAttest.sign(body, base: apiBase) { |
| 86 | req.httpBody = data | ||
| 87 | for (k, v) in headers { req.setValue(v, forHTTPHeaderField: k) } | ||
| 88 | } else { | ||
| 89 | req.httpBody = try? JSONSerialization.data(withJSONObject: body) | ||
| 90 | } | ||
| 86 | let ok = await send(req) | 91 | let ok = await send(req) |
| 87 | status = ok ? nil : "Couldn't reach the Moonrise server. Alerts will register next time." | 92 | status = ok ? nil : "Couldn't reach the Moonrise server. Alerts will register next time." |
| 88 | } else { | 93 | } else { |
PLAN.org +6 −1
| @@ -595,7 +595,12 @@ Worker; DSN Now freshness; NASA/ESA image licences; 26 LoC plates bundled. | |||
| 595 | user program files cover them meanwhile. | 595 | user program files cover them meanwhile. |
| 596 | 596 | ||
| 597 | ** v5.7: backend | 597 | ** v5.7: backend |
| 598 | - App Attest verification on device registration. | 598 | - App Attest verification on device registration. Done: =/v1/challenge=, |
| 599 | =/v1/attest= (chain to Apple's root, nonce, key ID, app ID, AAGUID) and | ||
| 600 | an assertion over each =/v1/devices= body with a one-time challenge and a | ||
| 601 | rising counter. Bad assertions are refused; unsigned registrations are | ||
| 602 | accepted until =APP_ATTEST=require= is set, after builds without it age | ||
| 603 | out. Keys are stored apart from devices. | ||
| 599 | 604 | ||
| 600 | ** on hold | 605 | ** on hold |
| 601 | - Smart-telescope pointing (Seestar and similar): until there is a | 606 | - Smart-telescope pointing (Seestar and similar): until there is a |
server/migrations/0008_app_attest.sql added +14
| @@ -0,0 +1,14 @@ | |||
| 1 | -- App Attest: one-time challenges, and keys attested by the app (not linked to devices or push tokens). | ||
| 2 | CREATE TABLE attest_challenges ( | ||
| 3 | challenge TEXT PRIMARY KEY, | ||
| 4 | expires_at TEXT NOT NULL | ||
| 5 | ); | ||
| 6 | |||
| 7 | CREATE TABLE app_keys ( | ||
| 8 | key_id TEXT PRIMARY KEY, | ||
| 9 | spki TEXT NOT NULL, | ||
| 10 | environment TEXT NOT NULL, | ||
| 11 | counter INTEGER NOT NULL, | ||
| 12 | created_at TEXT NOT NULL, | ||
| 13 | last_used TEXT NOT NULL | ||
| 14 | ); | ||
server/scripts/attest-fixture.ts added +59
| @@ -0,0 +1,59 @@ | |||
| 1 | // Writes test/fixtures/attest.json: an App Attest attestation built like Apple's (P-384 root and intermediate, P-256 | ||
| 2 | // leaf with the nonce extension) under a throwaway root, for test/appattest.test.ts. Needs openssl. | ||
| 3 | // node scripts/attest-fixture.ts | ||
| 4 | import { execFileSync } from "node:child_process"; | ||
| 5 | import { createHash, createPublicKey, randomBytes } from "node:crypto"; | ||
| 6 | import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; | ||
| 7 | import { tmpdir } from "node:os"; | ||
| 8 | import { join } from "node:path"; | ||
| 9 | |||
| 10 | const APP_ID = "ZCNAX3VL9D.sh.krz.moonrise"; | ||
| 11 | const dir = mkdtempSync(join(tmpdir(), "attest-")); | ||
| 12 | const f = (n: string) => join(dir, n); | ||
| 13 | const ssl = (...args: string[]) => execFileSync("openssl", args, { cwd: dir, stdio: ["ignore", "pipe", "inherit"] }); | ||
| 14 | const sha = (...b: Buffer[]) => createHash("sha256").update(Buffer.concat(b)).digest(); | ||
| 15 | |||
| 16 | ssl("ecparam", "-name", "secp384r1", "-genkey", "-noout", "-out", "root.key"); | ||
| 17 | ssl("req", "-x509", "-new", "-key", "root.key", "-subj", "/CN=Test Root", "-days", "36500", "-sha384", "-addext", "basicConstraints=critical,CA:true", "-out", "root.pem"); | ||
| 18 | ssl("ecparam", "-name", "secp384r1", "-genkey", "-noout", "-out", "ca.key"); | ||
| 19 | ssl("req", "-new", "-key", "ca.key", "-subj", "/CN=Test CA", "-out", "ca.csr"); | ||
| 20 | writeFileSync(f("ca.ext"), "basicConstraints=critical,CA:true\n"); | ||
| 21 | ssl("x509", "-req", "-in", "ca.csr", "-CA", "root.pem", "-CAkey", "root.key", "-CAcreateserial", "-days", "36500", "-sha384", "-extfile", "ca.ext", "-out", "ca.pem"); | ||
| 22 | |||
| 23 | ssl("ecparam", "-name", "prime256v1", "-genkey", "-noout", "-out", "leaf.key"); | ||
| 24 | ssl("pkcs8", "-topk8", "-nocrypt", "-in", "leaf.key", "-out", "leaf.p8"); | ||
| 25 | const jwk = createPublicKey(readFileSync(f("leaf.key"))).export({ format: "jwk" }); | ||
| 26 | const point = Buffer.concat([Buffer.from([4]), Buffer.from(jwk.x!, "base64url"), Buffer.from(jwk.y!, "base64url")]); | ||
| 27 | const keyId = sha(point); | ||
| 28 | |||
| 29 | const counter = Buffer.alloc(4); | ||
| 30 | const len = Buffer.alloc(2); | ||
| 31 | len.writeUInt16BE(32); | ||
| 32 | const authData = Buffer.concat([sha(Buffer.from(APP_ID)), Buffer.from([0x40]), counter, Buffer.from("appattestdevelop"), len, keyId]); | ||
| 33 | const challenge = randomBytes(32); | ||
| 34 | const nonce = sha(authData, sha(challenge)); | ||
| 35 | |||
| 36 | ssl("req", "-new", "-key", "leaf.key", "-subj", "/CN=Test Leaf", "-out", "leaf.csr"); | ||
| 37 | writeFileSync(f("leaf.ext"), `1.2.840.113635.100.8.2=DER:3024a1220420${nonce.toString("hex")}\n`); | ||
| 38 | ssl("x509", "-req", "-in", "leaf.csr", "-CA", "ca.pem", "-CAkey", "ca.key", "-CAcreateserial", "-days", "36500", "-sha256", "-extfile", "leaf.ext", "-out", "leaf.pem"); | ||
| 39 | const der = (n: string) => ssl("x509", "-in", n, "-outform", "DER"); | ||
| 40 | |||
| 41 | // CBOR: {"fmt": "apple-appattest", "attStmt": {"x5c": [leaf, ca], "receipt": h''}, "authData": authData} | ||
| 42 | const head = (major: number, n: number) => n < 24 ? Buffer.from([major << 5 | n]) : n < 256 ? Buffer.from([major << 5 | 24, n]) : Buffer.from([major << 5 | 25, n >> 8, n & 255]); | ||
| 43 | const bytes = (b: Buffer) => Buffer.concat([head(2, b.length), b]); | ||
| 44 | const text = (s: string) => Buffer.concat([head(3, Buffer.byteLength(s)), Buffer.from(s)]); | ||
| 45 | const attestation = Buffer.concat([ | ||
| 46 | head(5, 3), | ||
| 47 | text("fmt"), text("apple-appattest"), | ||
| 48 | text("attStmt"), head(5, 2), text("x5c"), head(4, 2), bytes(der("leaf.pem")), bytes(der("ca.pem")), text("receipt"), bytes(Buffer.alloc(0)), | ||
| 49 | text("authData"), bytes(authData), | ||
| 50 | ]); | ||
| 51 | |||
| 52 | writeFileSync(new URL("../test/fixtures/attest.json", import.meta.url), JSON.stringify({ | ||
| 53 | appId: APP_ID, | ||
| 54 | root: readFileSync(f("root.pem"), "utf8"), | ||
| 55 | attestation: attestation.toString("base64"), | ||
| 56 | keyId: keyId.toString("base64"), | ||
| 57 | challenge: challenge.toString("base64"), | ||
| 58 | leafKey: readFileSync(f("leaf.p8"), "utf8"), | ||
| 59 | }, null, 2) + "\n"); | ||
server/src/appattest.ts added +249
| @@ -0,0 +1,249 @@ | |||
| 1 | // App Attest (developer.apple.com, "Validating apps that connect to your server"): attestation of a new key, then an | ||
| 2 | // assertion with each device registration. WebCrypto only; minimal CBOR and DER readers for the shapes Apple sends. | ||
| 3 | |||
| 4 | /** Apple App Attestation Root CA, from https://www.apple.com/certificateauthority/Apple_App_Attestation_Root_CA.pem. */ | ||
| 5 | export const APPLE_ROOT = `-----BEGIN CERTIFICATE----- | ||
| 6 | MIICITCCAaegAwIBAgIQC/O+DvHN0uD7jG5yH2IXmDAKBggqhkjOPQQDAzBSMSYw | ||
| 7 | JAYDVQQDDB1BcHBsZSBBcHAgQXR0ZXN0YXRpb24gUm9vdCBDQTETMBEGA1UECgwK | ||
| 8 | QXBwbGUgSW5jLjETMBEGA1UECAwKQ2FsaWZvcm5pYTAeFw0yMDAzMTgxODMyNTNa | ||
| 9 | Fw00NTAzMTUwMDAwMDBaMFIxJjAkBgNVBAMMHUFwcGxlIEFwcCBBdHRlc3RhdGlv | ||
| 10 | biBSb290IENBMRMwEQYDVQQKDApBcHBsZSBJbmMuMRMwEQYDVQQIDApDYWxpZm9y | ||
| 11 | bmlhMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAERTHhmLW07ATaFQIEVwTtT4dyctdh | ||
| 12 | NbJhFs/Ii2FdCgAHGbpphY3+d8qjuDngIN3WVhQUBHAoMeQ/cLiP1sOUtgjqK9au | ||
| 13 | Yen1mMEvRq9Sk3Jm5X8U62H+xTD3FE9TgS41o0IwQDAPBgNVHRMBAf8EBTADAQH/ | ||
| 14 | MB0GA1UdDgQWBBSskRBTM72+aEH/pwyp5frq5eWKoTAOBgNVHQ8BAf8EBAMCAQYw | ||
| 15 | CgYIKoZIzj0EAwMDaAAwZQIwQgFGnByvsiVbpTKwSga0kP0e8EeDS4+sQmTvb7vn | ||
| 16 | 53O5+FRXgeLhpJ06ysC5PrOyAjEAp5U4xDgEgllF7En3VcE3iexZZtKeYnpqtijV | ||
| 17 | oyFraWVIyd/dganmrduC1bmTBGwD | ||
| 18 | -----END CERTIFICATE-----`; | ||
| 19 | |||
| 20 | const NONCE_OID = "1.2.840.113635.100.8.2"; | ||
| 21 | const AAGUID_PRODUCTION = "appattest\0\0\0\0\0\0\0"; | ||
| 22 | const AAGUID_DEVELOPMENT = "appattestdevelop"; | ||
| 23 | |||
| 24 | export class AttestError extends Error {} | ||
| 25 | |||
| 26 | const fail = (m: string): never => { | ||
| 27 | throw new AttestError(m); | ||
| 28 | }; | ||
| 29 | |||
| 30 | const encoder = new TextEncoder(); | ||
| 31 | const sha256 = async (...parts: Uint8Array[]) => new Uint8Array(await crypto.subtle.digest("SHA-256", concat(...parts))); | ||
| 32 | |||
| 33 | export function concat(...parts: Uint8Array[]): Uint8Array { | ||
| 34 | const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); | ||
| 35 | let i = 0; | ||
| 36 | for (const p of parts) { | ||
| 37 | out.set(p, i); | ||
| 38 | i += p.length; | ||
| 39 | } | ||
| 40 | return out; | ||
| 41 | } | ||
| 42 | |||
| 43 | const equal = (a: Uint8Array, b: Uint8Array) => a.length === b.length && a.every((x, i) => x === b[i]); | ||
| 44 | export const fromBase64 = (s: string) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0)); | ||
| 45 | export const toBase64 = (b: Uint8Array) => btoa(String.fromCharCode(...b)); | ||
| 46 | |||
| 47 | // MARK: CBOR (major types 0–5 with definite lengths, which is all App Attest uses) | ||
| 48 | |||
| 49 | export function cbor(bytes: Uint8Array): unknown { | ||
| 50 | let i = 0; | ||
| 51 | const length = (info: number): number => { | ||
| 52 | if (info < 24) return info; | ||
| 53 | const n = info === 24 ? 1 : info === 25 ? 2 : info === 26 ? 4 : fail("cbor length"); | ||
| 54 | let v = 0; | ||
| 55 | for (let k = 0; k < n; k++) v = v * 256 + bytes[i++]; | ||
| 56 | return v; | ||
| 57 | }; | ||
| 58 | const item = (): unknown => { | ||
| 59 | if (i >= bytes.length) fail("cbor truncated"); | ||
| 60 | const head = bytes[i++], major = head >> 5, n = length(head & 31); | ||
| 61 | switch (major) { | ||
| 62 | case 0: return n; | ||
| 63 | case 1: return -1 - n; | ||
| 64 | case 2: { const v = bytes.slice(i, i + n); i += n; return v; } | ||
| 65 | case 3: { const v = new TextDecoder().decode(bytes.slice(i, i + n)); i += n; return v; } | ||
| 66 | case 4: return Array.from({ length: n }, item); | ||
| 67 | case 5: { const m = new Map<unknown, unknown>(); for (let k = 0; k < n; k++) m.set(item(), item()); return m; } | ||
| 68 | default: return fail("cbor type"); | ||
| 69 | } | ||
| 70 | }; | ||
| 71 | return item(); | ||
| 72 | } | ||
| 73 | |||
| 74 | // MARK: DER | ||
| 75 | |||
| 76 | interface Der { tag: number; start: number; header: number; length: number; bytes: Uint8Array } | ||
| 77 | |||
| 78 | function der(bytes: Uint8Array, at = 0): Der { | ||
| 79 | const tag = bytes[at]; | ||
| 80 | let length = bytes[at + 1], header = 2; | ||
| 81 | if (length & 0x80) { | ||
| 82 | const n = length & 0x7f; | ||
| 83 | length = 0; | ||
| 84 | for (let k = 0; k < n; k++) length = length * 256 + bytes[at + 2 + k]; | ||
| 85 | header += n; | ||
| 86 | } | ||
| 87 | if (at + header + length > bytes.length) fail("der truncated"); | ||
| 88 | return { tag, start: at, header, length, bytes }; | ||
| 89 | } | ||
| 90 | |||
| 91 | const content = (d: Der) => d.bytes.slice(d.start + d.header, d.start + d.header + d.length); | ||
| 92 | const whole = (d: Der) => d.bytes.slice(d.start, d.start + d.header + d.length); | ||
| 93 | |||
| 94 | function children(d: Der): Der[] { | ||
| 95 | const out: Der[] = []; | ||
| 96 | let at = d.start + d.header; | ||
| 97 | while (at < d.start + d.header + d.length) { | ||
| 98 | const c = der(d.bytes, at); | ||
| 99 | out.push(c); | ||
| 100 | at = c.start + c.header + c.length; | ||
| 101 | } | ||
| 102 | return out; | ||
| 103 | } | ||
| 104 | |||
| 105 | function oid(b: Uint8Array): string { | ||
| 106 | const parts = [Math.floor(b[0] / 40), b[0] % 40]; | ||
| 107 | let v = 0; | ||
| 108 | for (const x of b.slice(1)) { | ||
| 109 | v = v * 128 + (x & 0x7f); | ||
| 110 | if (!(x & 0x80)) { parts.push(v); v = 0; } | ||
| 111 | } | ||
| 112 | return parts.join("."); | ||
| 113 | } | ||
| 114 | |||
| 115 | function time(d: Der): number { | ||
| 116 | const s = new TextDecoder().decode(content(d)); | ||
| 117 | const full = d.tag === 0x17 ? (Number(s.slice(0, 2)) < 50 ? "20" : "19") + s : s; // UTCTime or GeneralizedTime | ||
| 118 | return Date.UTC(+full.slice(0, 4), +full.slice(4, 6) - 1, +full.slice(6, 8), +full.slice(8, 10), +full.slice(10, 12), +full.slice(12, 14)); | ||
| 119 | } | ||
| 120 | |||
| 121 | interface Certificate { | ||
| 122 | tbs: Uint8Array; | ||
| 123 | signatureHash: "SHA-256" | "SHA-384"; | ||
| 124 | signature: Uint8Array; | ||
| 125 | spki: Uint8Array; | ||
| 126 | curve: "P-256" | "P-384"; | ||
| 127 | /** EC point, uncompressed. */ | ||
| 128 | point: Uint8Array; | ||
| 129 | notBefore: number; | ||
| 130 | notAfter: number; | ||
| 131 | extensions: Map<string, Uint8Array>; | ||
| 132 | } | ||
| 133 | |||
| 134 | const CURVES: Record<string, "P-256" | "P-384"> = { "1.2.840.10045.3.1.7": "P-256", "1.3.132.0.34": "P-384" }; | ||
| 135 | const HASHES: Record<string, "SHA-256" | "SHA-384"> = { "1.2.840.10045.4.3.2": "SHA-256", "1.2.840.10045.4.3.3": "SHA-384" }; | ||
| 136 | |||
| 137 | export function certificate(bytes: Uint8Array): Certificate { | ||
| 138 | const [tbs, alg, sig] = children(der(bytes)); | ||
| 139 | const fields = children(tbs); | ||
| 140 | const f = fields[0].tag === 0xa0 ? fields.slice(1) : fields; // skip [0] version | ||
| 141 | const [, , , validity, , spki] = f; | ||
| 142 | const [notBefore, notAfter] = children(validity).map(time); | ||
| 143 | const [spkiAlg, key] = children(spki); | ||
| 144 | const curve = CURVES[oid(content(children(spkiAlg)[1]))] ?? fail("curve"); | ||
| 145 | const extensions = new Map<string, Uint8Array>(); | ||
| 146 | const ext = f.find((x) => x.tag === 0xa3); | ||
| 147 | if (ext) { | ||
| 148 | for (const e of children(children(ext)[0])) { | ||
| 149 | const parts = children(e); | ||
| 150 | extensions.set(oid(content(parts[0])), content(parts[parts.length - 1])); | ||
| 151 | } | ||
| 152 | } | ||
| 153 | return { | ||
| 154 | tbs: whole(tbs), | ||
| 155 | signatureHash: HASHES[oid(content(children(alg)[0]))] ?? fail("signature algorithm"), | ||
| 156 | signature: content(sig).slice(1), // drop the BIT STRING's unused-bits byte | ||
| 157 | spki: whole(spki), | ||
| 158 | curve, | ||
| 159 | point: content(key).slice(1), | ||
| 160 | notBefore, | ||
| 161 | notAfter, | ||
| 162 | extensions, | ||
| 163 | }; | ||
| 164 | } | ||
| 165 | |||
| 166 | const pem = (s: string) => fromBase64(s.replace(/-----[^-]+-----/g, "").replace(/\s+/g, "")); | ||
| 167 | |||
| 168 | /** DER ECDSA-Sig-Value to the r||s WebCrypto expects. */ | ||
| 169 | export function rawSignature(sig: Uint8Array, size: number): Uint8Array { | ||
| 170 | const [r, s] = children(der(sig)).map(content); | ||
| 171 | const fit = (x: Uint8Array) => { | ||
| 172 | const t = x.slice(Math.max(0, x.length - size)); | ||
| 173 | return concat(new Uint8Array(size - t.length), t); | ||
| 174 | }; | ||
| 175 | return concat(fit(r), fit(s)); | ||
| 176 | } | ||
| 177 | |||
| 178 | async function verifies(issuer: { spki: Uint8Array; curve: "P-256" | "P-384" }, hash: "SHA-256" | "SHA-384", signature: Uint8Array, data: Uint8Array): Promise<boolean> { | ||
| 179 | const key = await crypto.subtle.importKey("spki", issuer.spki, { name: "ECDSA", namedCurve: issuer.curve }, false, ["verify"]); | ||
| 180 | return crypto.subtle.verify({ name: "ECDSA", hash }, key, rawSignature(signature, issuer.curve === "P-256" ? 32 : 48), data); | ||
| 181 | } | ||
| 182 | |||
| 183 | // MARK: attestation and assertion | ||
| 184 | |||
| 185 | interface AuthData { rpIdHash: Uint8Array; counter: number; aaguid: string; credentialId: Uint8Array } | ||
| 186 | |||
| 187 | function authData(b: Uint8Array, attested: boolean): AuthData { | ||
| 188 | if (b.length < 37) fail("authData"); | ||
| 189 | const counter = new DataView(b.buffer, b.byteOffset + 33, 4).getUint32(0); | ||
| 190 | if (!attested) return { rpIdHash: b.slice(0, 32), counter, aaguid: "", credentialId: new Uint8Array() }; | ||
| 191 | if (b.length < 55) fail("authData"); | ||
| 192 | const n = new DataView(b.buffer, b.byteOffset + 53, 2).getUint16(0); | ||
| 193 | return { rpIdHash: b.slice(0, 32), counter, aaguid: new TextDecoder().decode(b.slice(37, 53)), credentialId: b.slice(55, 55 + n) }; | ||
| 194 | } | ||
| 195 | |||
| 196 | export interface AttestedKey { | ||
| 197 | /** SubjectPublicKeyInfo of the key, for assertions. */ | ||
| 198 | spki: Uint8Array; | ||
| 199 | environment: "sandbox" | "production"; | ||
| 200 | } | ||
| 201 | |||
| 202 | /** | ||
| 203 | * Checks an attestation object for `keyId` (base64), made with clientDataHash = SHA-256(`challenge`). `appId` is | ||
| 204 | * "TEAMID.bundle.id". `root` is Apple's root in production; tests pass their own. | ||
| 205 | */ | ||
| 206 | export async function verifyAttestation(a: { attestation: Uint8Array; keyId: string; challenge: Uint8Array; appId: string; now: Date; root?: string }): Promise<AttestedKey> { | ||
| 207 | const obj = cbor(a.attestation) as Map<string, unknown>; | ||
| 208 | if (!(obj instanceof Map) || obj.get("fmt") !== "apple-appattest") fail("format"); | ||
| 209 | const stmt = obj.get("attStmt") as Map<string, unknown>; | ||
| 210 | const x5c = stmt?.get("x5c") as Uint8Array[]; | ||
| 211 | const raw = obj.get("authData") as Uint8Array; | ||
| 212 | if (!Array.isArray(x5c) || x5c.length < 2 || !(raw instanceof Uint8Array)) fail("structure"); | ||
| 213 | |||
| 214 | const [leaf, intermediate] = x5c.map(certificate); | ||
| 215 | const root = certificate(pem(a.root ?? APPLE_ROOT)); | ||
| 216 | const t = a.now.getTime(); | ||
| 217 | for (const c of [leaf, intermediate]) if (t < c.notBefore || t > c.notAfter) fail("certificate dates"); | ||
| 218 | if (!(await verifies(root, intermediate.signatureHash, intermediate.signature, intermediate.tbs))) fail("intermediate signature"); | ||
| 219 | if (!(await verifies(intermediate, leaf.signatureHash, leaf.signature, leaf.tbs))) fail("leaf signature"); | ||
| 220 | |||
| 221 | const nonce = await sha256(raw, await sha256(a.challenge)); | ||
| 222 | const ext = leaf.extensions.get(NONCE_OID) ?? fail("nonce extension"); | ||
| 223 | // SEQUENCE { [1] { OCTET STRING nonce } } | ||
| 224 | const inner = content(children(children(der(ext))[0])[0]); | ||
| 225 | if (!equal(inner, nonce)) fail("nonce"); | ||
| 226 | |||
| 227 | const keyId = fromBase64(a.keyId); | ||
| 228 | if (!equal(await sha256(leaf.point), keyId)) fail("key id"); | ||
| 229 | const auth = authData(raw, true); | ||
| 230 | if (!equal(auth.rpIdHash, await sha256(encoder.encode(a.appId)))) fail("app id"); | ||
| 231 | if (auth.counter !== 0) fail("counter"); | ||
| 232 | if (auth.aaguid !== AAGUID_PRODUCTION && auth.aaguid !== AAGUID_DEVELOPMENT) fail("aaguid"); | ||
| 233 | if (!equal(auth.credentialId, keyId)) fail("credential id"); | ||
| 234 | return { spki: leaf.spki, environment: auth.aaguid === AAGUID_DEVELOPMENT ? "sandbox" : "production" }; | ||
| 235 | } | ||
| 236 | |||
| 237 | /** Checks an assertion over `clientData` with an attested key; returns its counter, which must exceed `lastCounter`. */ | ||
| 238 | export async function verifyAssertion(a: { assertion: Uint8Array; clientData: Uint8Array; spki: Uint8Array; appId: string; lastCounter: number }): Promise<number> { | ||
| 239 | const obj = cbor(a.assertion) as Map<string, unknown>; | ||
| 240 | const signature = obj instanceof Map ? obj.get("signature") : undefined; | ||
| 241 | const raw = obj instanceof Map ? obj.get("authenticatorData") : undefined; | ||
| 242 | if (!(signature instanceof Uint8Array) || !(raw instanceof Uint8Array)) fail("structure"); | ||
| 243 | const nonce = await sha256(raw as Uint8Array, await sha256(a.clientData)); | ||
| 244 | if (!(await verifies({ spki: a.spki, curve: "P-256" }, "SHA-256", signature as Uint8Array, nonce))) fail("signature"); | ||
| 245 | const auth = authData(raw as Uint8Array, false); | ||
| 246 | if (!equal(auth.rpIdHash, await sha256(encoder.encode(a.appId)))) fail("app id"); | ||
| 247 | if (auth.counter <= a.lastCounter) fail("counter"); | ||
| 248 | return auth.counter; | ||
| 249 | } | ||
server/src/index.ts +75 −1
| @@ -1,4 +1,5 @@ | |||
| 1 | import { activityPush, focusEvery, focusPick, focusPollDue, inFocus, needsChannel, sinceNet, type ActivityState } from "./activity"; | 1 | import { activityPush, focusEvery, focusPick, focusPollDue, inFocus, needsChannel, sinceNet, type ActivityState } from "./activity"; |
| 2 | import { AttestError, fromBase64, toBase64, verifyAssertion, verifyAttestation, type AttestedKey } from "./appattest"; | ||
| 2 | import { broadcast, createChannel, deleteChannel, retryable, send, sendAll, type ApnsConfig } from "./apns"; | 3 | import { broadcast, createChannel, deleteChannel, retryable, send, sendAll, type ApnsConfig } from "./apns"; |
| 3 | import { actionableKp, alertBands, eventKey, isNight } from "./aurora"; | 4 | import { actionableKp, alertBands, eventKey, isNight } from "./aurora"; |
| 4 | import { compose, fetchGroups, fetchSupGP, fitsLaunch, retryDue, retryTick, supgpFile, supgpLaunches, type LaunchElements, type LaunchRef, type Row } from "./celestrak"; | 5 | import { compose, fetchGroups, fetchSupGP, fitsLaunch, retryDue, retryTick, supgpFile, supgpLaunches, type LaunchElements, type LaunchRef, type Row } from "./celestrak"; |
| @@ -21,6 +22,8 @@ interface Env { | |||
| 21 | LL2_API_KEY?: string; | 22 | LL2_API_KEY?: string; |
| 22 | /** "1": the Worker creates and deletes launch channels itself. Otherwise scripts/channels.ts fills the pool. */ | 23 | /** "1": the Worker creates and deletes launch channels itself. Otherwise scripts/channels.ts fills the pool. */ |
| 23 | APNS_MANAGE_CHANNELS?: string; | 24 | APNS_MANAGE_CHANNELS?: string; |
| 25 | /** "require": device registrations without an App Attest assertion are refused. Otherwise only bad ones are. */ | ||
| 26 | APP_ATTEST?: string; | ||
| 24 | } | 27 | } |
| 25 | 28 | ||
| 26 | interface DeviceRequest { | 29 | interface DeviceRequest { |
| @@ -30,8 +33,13 @@ interface DeviceRequest { | |||
| 30 | utcOffsetMinutes: number; | 33 | utcOffsetMinutes: number; |
| 31 | aurora?: boolean; | 34 | aurora?: boolean; |
| 32 | news?: boolean; | 35 | news?: boolean; |
| 36 | /** From POST /v1/challenge; required with an App Attest assertion. */ | ||
| 37 | challenge?: string; | ||
| 33 | } | 38 | } |
| 34 | 39 | ||
| 40 | /** Challenges are good for 5 minutes and used once. */ | ||
| 41 | const CHALLENGE_MS = 5 * 60_000; | ||
| 42 | |||
| 35 | const NEWS_CRON = "*/10 * * * *"; | 43 | const NEWS_CRON = "*/10 * * * *"; |
| 36 | const SATELLITE_CRON = "7 */2 * * *"; | 44 | const SATELLITE_CRON = "7 */2 * * *"; |
| 37 | const FOCUS_CRON = "*/2 * * * *"; | 45 | const FOCUS_CRON = "*/2 * * * *"; |
| @@ -154,9 +162,25 @@ export default { | |||
| 154 | // The policy lives on krz.sh; older builds link here. | 162 | // The policy lives on krz.sh; older builds link here. |
| 155 | if (request.method === "GET" && url.pathname === "/privacy") return Response.redirect(PRIVACY_URL, 301); | 163 | if (request.method === "GET" && url.pathname === "/privacy") return Response.redirect(PRIVACY_URL, 301); |
| 156 | 164 | ||
| 165 | if (request.method === "POST" && url.pathname === "/v1/challenge") { | ||
| 166 | const challenge = toBase64(crypto.getRandomValues(new Uint8Array(32))); | ||
| 167 | await env.DB.prepare("INSERT INTO attest_challenges (challenge, expires_at) VALUES (?1, ?2)").bind(challenge, new Date(now.getTime() + CHALLENGE_MS).toISOString()).run(); | ||
| 168 | return json({ challenge }); | ||
| 169 | } | ||
| 170 | |||
| 171 | if (request.method === "POST" && url.pathname === "/v1/attest") return attest(request, env, now); | ||
| 172 | |||
| 157 | if (request.method === "POST" && url.pathname === "/v1/devices") { | 173 | if (request.method === "POST" && url.pathname === "/v1/devices") { |
| 158 | const d = (await request.json().catch(() => ({}))) as Partial<DeviceRequest>; | 174 | const body = new Uint8Array(await request.arrayBuffer()); |
| 175 | let d: Partial<DeviceRequest>; | ||
| 176 | try { | ||
| 177 | d = JSON.parse(new TextDecoder().decode(body)); | ||
| 178 | } catch { | ||
| 179 | d = {}; | ||
| 180 | } | ||
| 159 | if (!validDevice(d)) return json({ error: "invalid device" }, 400); | 181 | if (!validDevice(d)) return json({ error: "invalid device" }, 400); |
| 182 | const refused = await checkAssertion(env, request, body, d.challenge, now); | ||
| 183 | if (refused) return refused; | ||
| 160 | await env.DB.prepare( | 184 | await env.DB.prepare( |
| 161 | `INSERT INTO devices (token, environment, band, utc_offset_minutes, aurora, news, last_seen) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) | 185 | `INSERT INTO devices (token, environment, band, utc_offset_minutes, aurora, news, last_seen) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) |
| 162 | ON CONFLICT (token) DO UPDATE SET environment = ?2, band = ?3, utc_offset_minutes = ?4, aurora = ?5, news = ?6, last_seen = ?7`, | 186 | ON CONFLICT (token) DO UPDATE SET environment = ?2, band = ?3, utc_offset_minutes = ?4, aurora = ?5, news = ?6, last_seen = ?7`, |
| @@ -187,6 +211,54 @@ export default { | |||
| 187 | }, | 211 | }, |
| 188 | } satisfies ExportedHandler<Env>; | 212 | } satisfies ExportedHandler<Env>; |
| 189 | 213 | ||
| 214 | const appId = (env: Env) => `${env.APNS_TEAM_ID}.${env.APNS_TOPIC}`; | ||
| 215 | |||
| 216 | /** Deletes a challenge and says whether it was there and unexpired. */ | ||
| 217 | async function useChallenge(env: Env, challenge: string | undefined, now: Date): Promise<boolean> { | ||
| 218 | if (typeof challenge !== "string") return false; | ||
| 219 | const row = await env.DB.prepare("DELETE FROM attest_challenges WHERE challenge = ?1 RETURNING expires_at").bind(challenge).first<{ expires_at: string }>(); | ||
| 220 | return !!row && row.expires_at > now.toISOString(); | ||
| 221 | } | ||
| 222 | |||
| 223 | /** POST /v1/attest {keyId, attestation, challenge}: stores a key Apple attests belongs to this app. */ | ||
| 224 | async function attest(request: Request, env: Env, now: Date): Promise<Response> { | ||
| 225 | const a = (await request.json().catch(() => ({}))) as { keyId?: unknown; attestation?: unknown; challenge?: string }; | ||
| 226 | if (typeof a.keyId !== "string" || typeof a.attestation !== "string" || a.attestation.length > 20_000) return json({ error: "invalid attestation" }, 400); | ||
| 227 | if (!(await useChallenge(env, a.challenge, now))) return json({ error: "unknown or expired challenge" }, 401); | ||
| 228 | let key: AttestedKey; | ||
| 229 | try { | ||
| 230 | key = await verifyAttestation({ attestation: fromBase64(a.attestation), keyId: a.keyId, challenge: fromBase64(a.challenge!), appId: appId(env), now }); | ||
| 231 | } catch (e) { | ||
| 232 | // Malformed input surfaces as DOMException (base64, WebCrypto) or RangeError (truncated data) as well as AttestError. | ||
| 233 | return json({ error: `attestation: ${e instanceof AttestError ? e.message : "malformed"}` }, 401); | ||
| 234 | } | ||
| 235 | await env.DB.prepare("INSERT OR IGNORE INTO app_keys (key_id, spki, environment, counter, created_at, last_used) VALUES (?1, ?2, ?3, 0, ?4, ?4)") | ||
| 236 | .bind(a.keyId, toBase64(key.spki), key.environment, now.toISOString()).run(); | ||
| 237 | return json({ ok: true }); | ||
| 238 | } | ||
| 239 | |||
| 240 | /** | ||
| 241 | * A refusal, or null to go ahead: the request's App Attest assertion (header x-app-attest-assertion, by key | ||
| 242 | * x-app-attest-key) must sign the exact body, which carries a fresh challenge. Without one, refused only when | ||
| 243 | * APP_ATTEST is "require". | ||
| 244 | */ | ||
| 245 | async function checkAssertion(env: Env, request: Request, body: Uint8Array, challenge: string | undefined, now: Date): Promise<Response | null> { | ||
| 246 | const keyId = request.headers.get("x-app-attest-key"), assertion = request.headers.get("x-app-attest-assertion"); | ||
| 247 | if (!keyId || !assertion) return env.APP_ATTEST === "require" ? json({ error: "app attest required" }, 401) : null; | ||
| 248 | const key = await env.DB.prepare("SELECT spki, counter FROM app_keys WHERE key_id = ?1").bind(keyId).first<{ spki: string; counter: number }>(); | ||
| 249 | if (!key) return json({ error: "unknown key" }, 401); | ||
| 250 | if (!(await useChallenge(env, challenge, now))) return json({ error: "unknown or expired challenge" }, 401); | ||
| 251 | let counter: number; | ||
| 252 | try { | ||
| 253 | counter = await verifyAssertion({ assertion: fromBase64(assertion), clientData: body, spki: fromBase64(key.spki), appId: appId(env), lastCounter: key.counter }); | ||
| 254 | } catch (e) { | ||
| 255 | return json({ error: `assertion: ${e instanceof AttestError ? e.message : "malformed"}` }, 401); | ||
| 256 | } | ||
| 257 | // The counter only rises, so a replayed or concurrent assertion with the same counter loses here. | ||
| 258 | const updated = await env.DB.prepare("UPDATE app_keys SET counter = ?2, last_used = ?3 WHERE key_id = ?1 AND counter < ?2").bind(keyId, counter, now.toISOString()).run(); | ||
| 259 | return updated.meta.changes ? null : json({ error: "assertion: counter" }, 401); | ||
| 260 | } | ||
| 261 | |||
| 190 | /** One test push to a registered device, at most once per 10 minutes per device. */ | 262 | /** One test push to a registered device, at most once per 10 minutes per device. */ |
| 191 | async function sendTest(env: Env, token: string, now: Date): Promise<Response> { | 263 | async function sendTest(env: Env, token: string, now: Date): Promise<Response> { |
| 192 | const device = await env.DB.prepare("SELECT environment FROM devices WHERE token = ?1").bind(token).first<{ environment: string }>(); | 264 | const device = await env.DB.prepare("SELECT environment FROM devices WHERE token = ?1").bind(token).first<{ environment: string }>(); |
| @@ -674,6 +746,8 @@ async function sendAlerts(env: Env, kind: string, recipients: Recipient[], now: | |||
| 674 | /** Daily: alert keys older than 3 days (the longest is a local day) and devices not registered in DEVICE_RETENTION_MS. */ | 746 | /** Daily: alert keys older than 3 days (the longest is a local day) and devices not registered in DEVICE_RETENTION_MS. */ |
| 675 | async function prune(env: Env, now: Date): Promise<void> { | 747 | async function prune(env: Env, now: Date): Promise<void> { |
| 676 | await env.DB.batch([ | 748 | await env.DB.batch([ |
| 749 | env.DB.prepare("DELETE FROM attest_challenges WHERE expires_at < ?1").bind(now.toISOString()), | ||
| 750 | env.DB.prepare("DELETE FROM app_keys WHERE last_used < ?1").bind(new Date(now.getTime() - DEVICE_RETENTION_MS).toISOString()), | ||
| 677 | env.DB.prepare("DELETE FROM alerts_sent WHERE sent_at < ?1").bind(new Date(now.getTime() - 3 * 86400_000).toISOString()), | 751 | env.DB.prepare("DELETE FROM alerts_sent WHERE sent_at < ?1").bind(new Date(now.getTime() - 3 * 86400_000).toISOString()), |
| 678 | env.DB.prepare("DELETE FROM devices WHERE last_seen < ?1").bind(new Date(now.getTime() - DEVICE_RETENTION_MS).toISOString()), | 752 | env.DB.prepare("DELETE FROM devices WHERE last_seen < ?1").bind(new Date(now.getTime() - DEVICE_RETENTION_MS).toISOString()), |
| 679 | ]); | 753 | ]); |
server/test/appattest.test.ts added +52
| @@ -0,0 +1,52 @@ | |||
| 1 | import assert from "node:assert/strict"; | ||
| 2 | import { createHash, createPrivateKey, sign } from "node:crypto"; | ||
| 3 | import { readFileSync } from "node:fs"; | ||
| 4 | import { test } from "node:test"; | ||
| 5 | import { AttestError, cbor, fromBase64, verifyAssertion, verifyAttestation } from "../src/appattest.ts"; | ||
| 6 | |||
| 7 | const fx = JSON.parse(readFileSync(new URL("./fixtures/attest.json", import.meta.url), "utf8")); | ||
| 8 | const now = new Date("2027-01-01T00:00:00Z"); | ||
| 9 | const base = { attestation: fromBase64(fx.attestation), keyId: fx.keyId, challenge: fromBase64(fx.challenge), appId: fx.appId, now, root: fx.root }; | ||
| 10 | const sha = (...b: Buffer[]) => createHash("sha256").update(Buffer.concat(b)).digest(); | ||
| 11 | |||
| 12 | /** CBOR {"signature": sig, "authenticatorData": authData}, signed with the fixture's leaf key. */ | ||
| 13 | function assertion(clientData: string, counter: number, appId = fx.appId): Uint8Array { | ||
| 14 | const c = Buffer.alloc(4); | ||
| 15 | c.writeUInt32BE(counter); | ||
| 16 | const authData = Buffer.concat([sha(Buffer.from(appId)), Buffer.from([0x40]), c]); | ||
| 17 | const signature = sign("sha256", sha(authData, sha(Buffer.from(clientData))), createPrivateKey(fx.leafKey)); | ||
| 18 | const text = (s: string) => Buffer.concat([Buffer.from([0x60 | s.length]), Buffer.from(s)]); | ||
| 19 | const bytes = (b: Buffer) => Buffer.concat([Buffer.from([0x58, b.length]), b]); | ||
| 20 | return Buffer.concat([Buffer.from([0xa2]), text("signature"), bytes(signature), text("authenticatorData"), bytes(authData)]); | ||
| 21 | } | ||
| 22 | |||
| 23 | test("CBOR maps, arrays, byte and text strings decode", () => { | ||
| 24 | const m = cbor(Uint8Array.from([0xa2, 0x61, 0x61, 0x82, 0x01, 0x20, 0x61, 0x62, 0x42, 0xca, 0xfe])) as Map<string, unknown>; | ||
| 25 | assert.deepEqual(m.get("a"), [1, -1]); | ||
| 26 | assert.deepEqual(m.get("b"), Uint8Array.from([0xca, 0xfe])); | ||
| 27 | }); | ||
| 28 | |||
| 29 | test("an attestation under its root verifies as a development key", async () => { | ||
| 30 | const k = await verifyAttestation(base); | ||
| 31 | assert.equal(k.environment, "sandbox"); | ||
| 32 | assert.ok(k.spki.length > 60); | ||
| 33 | }); | ||
| 34 | |||
| 35 | test("attestations fail on another challenge, app, key, root or date", async () => { | ||
| 36 | const rejects = (over: Partial<typeof base>, message: string) => | ||
| 37 | assert.rejects(verifyAttestation({ ...base, ...over }), (e) => e instanceof AttestError && e.message === message); | ||
| 38 | await rejects({ challenge: new Uint8Array(32) }, "nonce"); | ||
| 39 | await rejects({ appId: "ZCNAX3VL9D.sh.krz.other" }, "app id"); | ||
| 40 | await rejects({ keyId: btoa("x".repeat(32)) }, "key id"); | ||
| 41 | await rejects({ root: undefined }, "intermediate signature"); | ||
| 42 | await rejects({ now: new Date("2200-01-01T00:00:00Z") }, "certificate dates"); | ||
| 43 | }); | ||
| 44 | |||
| 45 | test("assertions verify over the request body and need a rising counter", async () => { | ||
| 46 | const { spki } = await verifyAttestation(base); | ||
| 47 | const body = '{"token":"ab","challenge":"x"}'; | ||
| 48 | assert.equal(await verifyAssertion({ assertion: assertion(body, 3), clientData: new TextEncoder().encode(body), spki, appId: fx.appId, lastCounter: 2 }), 3); | ||
| 49 | await assert.rejects(verifyAssertion({ assertion: assertion(body, 2), clientData: new TextEncoder().encode(body), spki, appId: fx.appId, lastCounter: 2 }), /counter/); | ||
| 50 | await assert.rejects(verifyAssertion({ assertion: assertion(body, 3), clientData: new TextEncoder().encode(body + " "), spki, appId: fx.appId, lastCounter: 0 }), /signature/); | ||
| 51 | await assert.rejects(verifyAssertion({ assertion: assertion(body, 3, "X.y"), clientData: new TextEncoder().encode(body), spki, appId: fx.appId, lastCounter: 0 }), /app id/); | ||
| 52 | }); | ||
server/test/fixtures/attest.json added +8
| @@ -0,0 +1,8 @@ | |||
| 1 | { | ||
| 2 | "appId": "ZCNAX3VL9D.sh.krz.moonrise", | ||
| 3 | "root": "-----BEGIN CERTIFICATE-----\nMIIBmzCCASGgAwIBAgIUKujcoE1Py11nkte5SDrjDjH25M8wCgYIKoZIzj0EAwMw\nFDESMBAGA1UEAwwJVGVzdCBSb290MCAXDTI2MTAyMjA0NDI1NloYDzIxMjYwOTI4\nMDQ0MjU2WjAUMRIwEAYDVQQDDAlUZXN0IFJvb3QwdjAQBgcqhkjOPQIBBgUrgQQA\nIgNiAAQ2HVZCigTg7eGL/2XHVeX9xz9NGY3p1KV9k5uY6SzaIurSENh063xPtSeK\nMH5famUVvQOeEfrwNN4KGaoPv9nwiFYfxB9WbFLrxojjypLXTYytklhYSeAgSZZO\n5mcsL/ujMjAwMB0GA1UdDgQWBBSHEcXnFLnkAKM8mVg47r65lZ0jADAPBgNVHRMB\nAf8EBTADAQH/MAoGCCqGSM49BAMDA2gAMGUCMCFBJiCiuUXLrAgloT0Q2S5tQZSd\ngWl3RzFy/lJJdBA6G7s0LgiSBhUgagDJRRE1WwIxAIvkee70XpFmT3wzJEgAGWbn\nNVHxSfDg+NcPDG+sEpMeECP4maSPRVwvXJULyqNKxw==\n-----END CERTIFICATE-----\n", | ||
| 4 | "attestation": "o2NmbXRvYXBwbGUtYXBwYXR0ZXN0Z2F0dFN0bXSiY3g1Y4JZAYQwggGAMIIBB6ADAgECAhQsvTruZFOGSvmQU3zAr1+SF7uIDjAKBggqhkjOPQQDAjASMRAwDgYDVQQDDAdUZXN0IENBMCAXDTI2MTAyMjA0NDI1NloYDzIxMjYwOTI4MDQ0MjU2WjAUMRIwEAYDVQQDDAlUZXN0IExlYWYwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAT+rJ8y1LeMewZnbUPOxL3d5GktygEpFE+Vu7T5WayEWskdOtiUjXDlO9uV6wLGhrU3u2vXeydkhDcbs/kNhJJAozcwNTAzBgkqhkiG92NkCAIEJjAkoSIEII6LFzd0dSyfPLFBsfoINCFt5j6tQBwV/2sHA85NcY0rMAoGCCqGSM49BAMCA2cAMGQCMBwJJ5r62RcEybVhSjU1FzuUG4vauNpv//QF9gBVomiHy1ZS023tW1GKxNiHqXXyBQIwPxhxWIsnkBGTFgWVKy5Wlsb/QS62Qqh0LNXzPGQOTPSZAV5nQxvCVaDFeFjR+KmoWQF/MIIBezCCAQCgAwIBAgIUbq1eEBYC+yuaPh8q2CLTFV43PQswCgYIKoZIzj0EAwMwFDESMBAGA1UEAwwJVGVzdCBSb290MCAXDTI2MTAyMjA0NDI1NloYDzIxMjYwOTI4MDQ0MjU2WjASMRAwDgYDVQQDDAdUZXN0IENBMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAENU+CwN2qCWqXYEwLN1FO54M6pxK/iXhnv1A487QAt7tIR1Z0UP/7GkgHa4mCZNH7KQYrgZpFT5iUSwUXMlwNhmGtmg7Hn1xN/GzMQeuMn2b7rabr+vu/X4Q3PBhtTQ7qoxMwETAPBgNVHRMBAf8EBTADAQH/MAoGCCqGSM49BAMDA2kAMGYCMQDB551PUq36M1nFXxNCowTo8dnqxKw+m44vm6SZ4iBxewoI+6o6rdtTgfIjgFXvqm8CMQC3KWPQWPRWPs+hjeV45C3Ftxwhgim2LXQvD3tJ1Snm9taVVkf4RtVlbMnvL7PAxSZncmVjZWlwdEBoYXV0aERhdGFYV6oeXReSzoB0YHZlif4Puofq5FOjU1BGCdu+JYjzUtVmQAAAAABhcHBhdHRlc3RkZXZlbG9wACDlk56Z59/eH3EQfZ2gS/EiTXsNLHhyOtsL77fh/jAEFg==", | ||
| 5 | "keyId": "5ZOemeff3h9xEH2doEvxIk17DSx4cjrbC++34f4wBBY=", | ||
| 6 | "challenge": "fcixFPpKpM7UCUEeRpCR0RRb1Fwz17ixh1JRdTlGiac=", | ||
| 7 | "leafKey": "-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg+Pf/ZCbrgnfDEpST\nuwg/Cs3/LlBjZogYgyCA87WEVPihRANCAAT+rJ8y1LeMewZnbUPOxL3d5GktygEp\nFE+Vu7T5WayEWskdOtiUjXDlO9uV6wLGhrU3u2vXeydkhDcbs/kNhJJA\n-----END PRIVATE KEY-----\n" | ||
| 8 | } | ||
server/test/worker.test.ts +46
| @@ -2,6 +2,7 @@ import assert from "node:assert/strict"; | |||
| 2 | import { readdirSync, readFileSync } from "node:fs"; | 2 | import { readdirSync, readFileSync } from "node:fs"; |
| 3 | import { registerHooks } from "node:module"; | 3 | import { registerHooks } from "node:module"; |
| 4 | import { DatabaseSync, type SQLInputValue } from "node:sqlite"; | 4 | import { DatabaseSync, type SQLInputValue } from "node:sqlite"; |
| 5 | import { createHash, createPrivateKey, sign } from "node:crypto"; | ||
| 5 | import { afterEach, mock, test } from "node:test"; | 6 | import { afterEach, mock, test } from "node:test"; |
| 6 | 7 | ||
| 7 | // src/index.ts imports without extensions, which wrangler's bundler resolves. | 8 | // src/index.ts imports without extensions, which wrangler's bundler resolves. |
| @@ -16,6 +17,7 @@ registerHooks({ | |||
| 16 | }, | 17 | }, |
| 17 | }); | 18 | }); |
| 18 | const { default: worker, PUSH_SLICE } = await import("../src/index.ts"); | 19 | const { default: worker, PUSH_SLICE } = await import("../src/index.ts"); |
| 20 | const { fromBase64, toBase64, verifyAttestation } = await import("../src/appattest.ts"); | ||
| 19 | 21 | ||
| 20 | const FIVE = "*/5 * * * *"; | 22 | const FIVE = "*/5 * * * *"; |
| 21 | const TWO = "*/2 * * * *"; | 23 | const TWO = "*/2 * * * *"; |
| @@ -546,3 +548,47 @@ test("a storm opens a channel pair, updates it, and ends it after 3 calm hours; | |||
| 546 | assert.deepEqual(managed, ["POST", "POST", "DELETE", "DELETE"]); | 548 | assert.deepEqual(managed, ["POST", "POST", "DELETE", "DELETE"]); |
| 547 | assert.equal(count(db, "SELECT COUNT(*) AS n FROM storm_channels"), 0); | 549 | assert.equal(count(db, "SELECT COUNT(*) AS n FROM storm_channels"), 0); |
| 548 | }); | 550 | }); |
| 551 | |||
| 552 | test("device registration checks an App Attest assertion over the body, with a one-time challenge", async () => { | ||
| 553 | const fx = JSON.parse(readFileSync(new URL("./fixtures/attest.json", import.meta.url), "utf8")); | ||
| 554 | const { db, env } = await setup({ APNS_TEAM_ID: "ZCNAX3VL9D" }); | ||
| 555 | const post = (path: string, body: string, headers: Record<string, string> = {}) => | ||
| 556 | worker.fetch(new Request(`https://moonrise.krz.sh${path}`, { method: "POST", body, headers }), env as never); | ||
| 557 | const challenge = async () => ((await (await post("/v1/challenge", "")).json()) as { challenge: string }).challenge; | ||
| 558 | |||
| 559 | // The fixture's chain is not Apple's, so the endpoint refuses it, and the challenge is spent either way. | ||
| 560 | const c0 = await challenge(); | ||
| 561 | const refused = await post("/v1/attest", JSON.stringify({ keyId: fx.keyId, attestation: fx.attestation, challenge: c0 })); | ||
| 562 | assert.equal(refused.status, 401); | ||
| 563 | assert.deepEqual(await refused.json(), { error: "attestation: intermediate signature" }); | ||
| 564 | assert.equal(count(db, "SELECT COUNT(*) AS n FROM attest_challenges"), 0); | ||
| 565 | assert.equal((await post("/v1/attest", JSON.stringify({ keyId: fx.keyId, attestation: "x", challenge: "nope" }))).status, 401); | ||
| 566 | |||
| 567 | const { spki } = await verifyAttestation({ attestation: fromBase64(fx.attestation), keyId: fx.keyId, challenge: fromBase64(fx.challenge), appId: fx.appId, now: new Date("2027-01-01T00:00:00Z"), root: fx.root }); | ||
| 568 | db.prepare("INSERT INTO app_keys (key_id, spki, environment, counter, created_at, last_used) VALUES (?, ?, 'sandbox', 0, 'x', 'x')").run(fx.keyId, toBase64(spki)); | ||
| 569 | const sha = (...b: Buffer[]) => createHash("sha256").update(Buffer.concat(b)).digest(); | ||
| 570 | const assertion = (body: string, counter: number) => { | ||
| 571 | const c = Buffer.alloc(4); | ||
| 572 | c.writeUInt32BE(counter); | ||
| 573 | const authData = Buffer.concat([sha(Buffer.from(fx.appId)), Buffer.from([0x40]), c]); | ||
| 574 | const sig = sign("sha256", sha(authData, sha(Buffer.from(body))), createPrivateKey(fx.leafKey)); | ||
| 575 | const text = (s: string) => Buffer.concat([Buffer.from([0x60 | s.length]), Buffer.from(s)]); | ||
| 576 | const bytes = (b: Buffer) => Buffer.concat([Buffer.from([0x58, b.length]), b]); | ||
| 577 | return Buffer.concat([Buffer.from([0xa2]), text("signature"), bytes(sig), text("authenticatorData"), bytes(authData)]).toString("base64"); | ||
| 578 | }; | ||
| 579 | const device = (c: string) => JSON.stringify({ token: token(7), environment: "sandbox", band: 45, utcOffsetMinutes: 0, aurora: true, challenge: c }); | ||
| 580 | |||
| 581 | const body = device(await challenge()); | ||
| 582 | const headers = { "x-app-attest-key": fx.keyId, "x-app-attest-assertion": assertion(body, 1) }; | ||
| 583 | assert.equal((await post("/v1/devices", body, headers)).status, 200); | ||
| 584 | assert.equal(count(db, "SELECT counter AS n FROM app_keys"), 1); | ||
| 585 | assert.equal(count(db, "SELECT COUNT(*) AS n FROM devices"), 1); | ||
| 586 | assert.equal((await post("/v1/devices", body, headers)).status, 401, "replay: challenge spent"); | ||
| 587 | const tampered = device(await challenge()); | ||
| 588 | assert.equal((await post("/v1/devices", tampered.replace('"band":45', '"band":50'), { ...headers, "x-app-attest-assertion": assertion(tampered, 2) })).status, 401); | ||
| 589 | |||
| 590 | const plain = JSON.stringify({ token: token(8), environment: "sandbox", band: 45, utcOffsetMinutes: 0 }); | ||
| 591 | assert.equal((await post("/v1/devices", plain)).status, 200, "unattested accepted by default"); | ||
| 592 | const { env: strict } = await setup({ APNS_TEAM_ID: "ZCNAX3VL9D", APP_ATTEST: "require" }); | ||
| 593 | assert.equal((await worker.fetch(new Request("https://moonrise.krz.sh/v1/devices", { method: "POST", body: plain }), strict as never)).status, 401); | ||
| 594 | }); | ||