package main // The zoo's robot: a real account, `zoo-robot`, visible in the directory like anyone, that the // self-check signs in as. Its passkey is a software key kept in robot.json (the zoo's own data; // nothing of root's or account's). It signs in exactly as a person does: a WebAuthn assertion to // account, then the silent upgrade into each app it visits. // // Live and staging each have their own account, so each environment has its own robot. One sign-in // per instance (a request or a job run); robot_done() signs it out again at the end, so robot // sessions never pile up. import "core:crypto/ecdsa" import "core:crypto/hash" import "core:encoding/base64" import "core:encoding/json" import "core:fmt" import "core:strings" import "ratcloud:rc" ROBOT_NAME :: "zoo-robot" Robot_File :: struct { username: string `json:"username"`, id: i64 `json:"id"`, cred: string `json:"cred"`, // the credential id, base64url key: string `json:"key"`, // the private key, PEM count: i64 `json:"count"`, } b64u :: proc(b: []u8) -> string { s := base64.encode(b) out := strings.builder_make() for ch in transmute([]u8)s { switch ch { case '+': strings.write_byte(&out, '-') case '/': strings.write_byte(&out, '_') case '=': case: strings.write_byte(&out, ch) } } return strings.to_string(out) } b64 :: proc(b: []u8) -> string {return base64.encode(b)} unb64 :: proc(s: string) -> ([]u8, bool) { t := strings.builder_make() for ch in transmute([]u8)s { switch ch { case '-': strings.write_byte(&t, '+') case '_': strings.write_byte(&t, '/') case ' ', '\n', '\r', '\t': case: strings.write_byte(&t, ch) } } for strings.builder_len(t) % 4 != 0 do strings.write_byte(&t, '=') b, err := base64.decode(strings.to_string(t)) return b, err == nil } sha256 :: proc(b: []u8) -> []u8 { out := make([]u8, 32) hash.hash_bytes_to_buffer(.SHA256, b, out) return out } sha256s :: proc(s: string) -> []u8 {return sha256(transmute([]u8)s)} bytes_of :: proc(s: string) -> []u8 {return transmute([]u8)s} join :: proc(parts: ..[]u8) -> []u8 { n := 0 for p in parts do n += len(p) out := make([]u8, n) o := 0 for p in parts {copy(out[o:], p); o += len(p)} return out } be32 :: proc(n: u32) -> []u8 {return bs(u8(n >> 24), u8(n >> 16), u8(n >> 8), u8(n))} be16 :: proc(n: u16) -> []u8 {return bs(u8(n >> 8), u8(n))} // A slice of these bytes that outlives the call. bs :: proc(xs: ..u8) -> []u8 { out := make([]u8, len(xs)) copy(out, xs) return out } // ---- P-256 keys as PEM: the 32-byte scalar inside SEC 1 or PKCS #8 ---------------------------------- // The private scalar d of a P-256 key in PEM (SEC 1 "EC PRIVATE KEY" or PKCS #8 "PRIVATE KEY", as // openssl writes them): the OCTET STRING after ECPrivateKey's version 1. pem_scalar :: proc(pem: string) -> ([]u8, bool) { body := strings.builder_make() for line in strings.split_lines(pem) { if strings.has_prefix(line, "-----") do continue strings.write_string(&body, strings.trim_space(line)) } der, ok := unb64(strings.to_string(body)) if !ok do return nil, false for i in 0 ..< len(der) - 37 { if der[i] == 0x02 && der[i + 1] == 0x01 && der[i + 2] == 0x01 && der[i + 3] == 0x04 && der[i + 4] == 0x20 do return der[i + 5:i + 37], true } return nil, false } // SEC 1 PEM of a P-256 key: d and its public point. pem_of :: proc(d, pub: []u8) -> string { der := join({0x30, 0x77, 0x02, 0x01, 0x01, 0x04, 0x20}, d, {0xa0, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0xa1, 0x44, 0x03, 0x42, 0x00}, pub) s := base64.encode(der) b := strings.builder_make() label := cat("EC PRIV", "ATE KEY") // split, so exhibit 14's search for a key's shape does not find this line strings.write_string(&b, cat("-----BEGIN ", label, "-----\n")) for i := 0; i < len(s); i += 64 {strings.write_string(&b, s[i:min(i + 64, len(s))]); strings.write_byte(&b, '\n')} strings.write_string(&b, cat("-----END ", label, "-----\n")) return strings.to_string(b) } // An ES256 signature (DER, as WebAuthn wants) over msg with the key in pem. es256_sign :: proc(pem: string, msg: []u8) -> ([]u8, bool) { d, ok := pem_scalar(pem) if !ok do return nil, false k: ecdsa.Private_Key if !ecdsa.private_key_set_bytes(&k, .SECP256R1, d) do return nil, false return ecdsa.sign_asn1(&k, .SHA256, msg, context.allocator) } // ---- CBOR, just enough for a COSE key and an attestation object ------------------------------------- cbor_head :: proc(major: u8, n: int) -> []u8 { if n < 24 do return bs(major << 5 | u8(n)) if n < 256 do return bs(major << 5 | 24, u8(n)) return bs(major << 5 | 25, u8(n >> 8), u8(n)) } cbor_int :: proc(n: int) -> []u8 {return cbor_head(0, n) if n >= 0 else cbor_head(1, -1 - n)} cbor_bytes :: proc(b: []u8) -> []u8 {return join(cbor_head(2, len(b)), b)} cbor_text :: proc(s: string) -> []u8 {return join(cbor_head(3, len(s)), transmute([]u8)s)} // ---- the robot ----------------------------------------------------------------------------------- ROBOT_FILE :: "robot.json" robot_file :: proc() -> (r: Robot_File, ok: bool) { b, err := rc.read_file(ROBOT_FILE) if err != 0 || len(b) == 0 do return {}, false // unmarshal first: a return's values are read left to right, so `return r, unmarshal(&r)` returns the empty r ok = json.unmarshal(b, &r) == nil && r.key != "" return r, ok } // The robot's passkey and counter, written whole or not at all (the host writes a temp file and // renames it): a half-written file would read as "no robot", the next run would register // zoo-robot-1, and the real robot's name would be stranded. robot_save :: proc(r: Robot_File) { if rc.write_file(ROBOT_FILE, transmute([]u8)to_json(r)) != 0 do panic("could not save the robot's state") } rp_id :: proc() -> string {return domain_host(env().accounts)} domain_host :: proc(url: string) -> string { s := strings.trim_prefix(strings.trim_prefix(url, "https://"), "http://") if i := strings.index_byte(s, '/'); i >= 0 do s = s[:i] return s } account_api :: proc(b: ^Browser, name: string, in_ := "{}") -> (int, json.Value) { r := post(b, cat(env().accounts, "/api/", name), in_) return r.status, r.j } // Make the robot's account (once per environment) and give it a picture. robot_register :: proc(b: ^Browser) -> (Robot_File, string) { k: ecdsa.Private_Key if !ecdsa.private_key_generate(&k, .SECP256R1) do return {}, "could not make a key" d := make([]u8, 32) ecdsa.private_key_bytes(&k, d) pub := make([]u8, 65) ecdsa.private_key_public_bytes(&k, pub) cred := random_bytes(16) // If a previous robot.json was lost, its name is retired for good: take the next free one. code: int o: json.Value for i in 0 ..< 5 { name := ROBOT_NAME if i == 0 else fmt.tprintf("%s-%d", ROBOT_NAME, i) code, o = account_api(b, "register-start", fmt.tprintf(`{{"username":%s}}`, jq(name))) if code == 200 do break } if code != 200 do return {}, cat("account would not register a robot: ", to_json(o)) cose := join(cbor_head(5, 5), cbor_int(1), cbor_int(2), cbor_int(3), cbor_int(-7), cbor_int(-1), cbor_int(1), cbor_int(-2), cbor_bytes(pub[1:33]), cbor_int(-3), cbor_bytes(pub[33:65])) ad := join(sha256s(rp_id()), {0x45}, be32(0), make([]u8, 16), be16(16), cred, cose) att := join(cbor_head(5, 3), cbor_text("fmt"), cbor_text("none"), cbor_text("attStmt"), cbor_head(5, 0), cbor_text("authData"), cbor_bytes(ad)) cdj := fmt.tprintf(`{{"type":"webauthn.create","challenge":%s,"origin":%s,"crossOrigin":false}}`, jq(jstr(o, "challenge")), jq(env().accounts)) code2, j := account_api(b, "register-finish", fmt.tprintf(`{{"clientDataJSON":%s,"attestationObject":%s}}`, jq(b64u(bytes_of(cdj))), jq(b64u(att)))) if code2 != 200 do return {}, cat("robot registration failed: ", to_json(j)) r := Robot_File{username = jstr(j, "user", "username"), id = jint(j, "user", "id"), cred = b64u(cred), key = pem_of(d, pub), count = 0} robot_save(r) account_api(b, "profile", `{"name":"Zoo Robot"}`) account_api(b, "picture", fmt.tprintf(`{{"image":%s}}`, jq(b64(robot_picture())))) return r, "" } g_robot: ^Browser g_robot_at: map[string]bool // A WebAuthn assertion with the robot's passkey over this challenge: the counter goes up first, // under the robot's lock (one counter value per signature). The fields account's *-finish wants. @(private = "file") robot_assert :: proc(challenge: string) -> (string, string) { r, ok := robot_file() if !ok do return "", "the robot's robot.json is gone" // The signature counter must go up every time. Time does, even after a restore from backup. r.count = max(r.count + 1, now()) ad := join(sha256s(rp_id()), {0x05}, be32(u32(r.count))) cdj := fmt.tprintf(`{{"type":"webauthn.get","challenge":%s,"origin":%s}}`, jq(challenge), jq(env().accounts)) sig, sok := es256_sign(r.key, join(ad, sha256s(cdj))) if !sok do return "", "the robot's key did not sign" robot_save(r) return fmt.tprintf(`{{"id":%s,"clientDataJSON":%s,"authenticatorData":%s,"signature":%s}}`, jq(r.cred), jq(b64u(bytes_of(cdj))), jq(b64u(ad)), jq(b64u(sig))), "" } // A browser signed in as the robot at account, or why not. One sign-in per instance. robot :: proc() -> (^Browser, string) { if g_robot != nil do return g_robot, "" lk := lock_open("robot.json.lock") defer lock_close(lk) lock_wait(lk, 30_000) // the job's check and a web check never sign in with one counter value b := new_browser() if _, ok := robot_file(); !ok { if _, err := robot_register(b); err != "" do return nil, err } account_api(b, "signout") // registering signed it in; start clean either way code, o := account_api(b, "login-start") if code != 200 do return nil, fmt.tprintf("account login-start answered %d", code) fin, err := robot_assert(jstr(o, "challenge")) if err != "" do return nil, err code2, j := account_api(b, "login-finish", fin) if code2 != 200 do return nil, fmt.tprintf("the robot could not sign in at account (%d): %s", code2, jstr(j, "error")) g_robot = b g_robot_at = make(map[string]bool) return b, "" } // At the end of the instance: sign the robot out at account, if it signed in. robot_done :: proc() { if g_robot != nil do account_api(g_robot, "signout") g_robot = nil } Robot_User :: struct { id: i64, username: string, } robot_user :: proc() -> Robot_User { r, _ := robot_file() return {r.id, r.username} } // The robot's browser after a page load at app (default: the zoo), so its token is there too. robot_at :: proc(app := "") -> (^Browser, string) { b, err := robot() if err != "" do return nil, err if !g_robot_at[app] { url := self_url() if app == "" else cat(rc.app_url(app), "/") r := visit(b, url) if r.status != 200 do return nil, fmt.tprintf("%s answered the robot with %d", "the zoo" if app == "" else app, r.status) g_robot_at[app] = true } return b, "" } // A passkey approval of exactly this action and params, as the robot (account README, "Approvals"): // the same two calls account's /approve page makes, signed with the robot's software passkey, for // app to file with aud (root). The approval, or why not. robot_approve :: proc(app, action, params_json: string, aud := "root") -> (string, string) { b, err := robot() if err != "" do return "", err lk := lock_open("robot.json.lock") defer lock_close(lk) lock_wait(lk, 30_000) // one counter value per signature, as at sign-in code, o := account_api(b, "approve-start", fmt.tprintf(`{{"app":%s,"aud":%s,"action":%s,"params":%s}}`, jq(app), jq(aud), jq(action), params_json)) if code != 200 || jstr(o, "challenge") == "" do return "", fmt.tprintf("account would not start an approval of %s (%d): %s", action, code, jstr(o, "error")) fin, ferr := robot_assert(jstr(o, "challenge")) if ferr != "" do return "", ferr code2, j := account_api(b, "approve-finish", fin) if code2 != 200 || jstr(j, "approval") == "" do return "", fmt.tprintf("account would not sign the approval of %s (%d): %s", action, code2, jstr(j, "error")) return jstr(j, "approval"), "" } // A little robot face, drawn here so the guestbook has a picture to show. robot_picture :: proc() -> []u8 { im := image_new(128, 128, {{46, 125, 90}, {240, 240, 230}, {30, 30, 30}}) fill_rect(&im, 24, 34, 104, 100, 1) fill_ellipse(&im, 48, 60, 8, 2) fill_ellipse(&im, 80, 60, 8, 2) fill_rect(&im, 46, 82, 82, 88, 2) fill_rect(&im, 61, 18, 67, 34, 1) return png_encode(&im) }