package main // seal: rc-crypt.js's formats, byte for byte (storage's seal/v1/rc-crypt.js is the spec), for the // zoo's robot. A person's browser does all of this in rc-crypt.js; the self-checks of exhibits 26 and // 27 play that browser (and, to show what is refused, the server), so they need the same bytes. // // P-256 (public halves as the 65-byte uncompressed point, base64), AES-256-GCM as ciphertext || // 16-byte tag (WebCrypto's layout), HKDF-SHA256, all from core:crypto. import "core:crypto/aead" import "core:crypto/ecdh" import "core:crypto/hkdf" import "core:crypto/hmac" import "core:encoding/base64" import "core:encoding/json" import "core:fmt" import "core:strings" Seal_Error :: string // "" = fine s_unb64 :: proc(s: string) -> []u8 { b, err := base64.decode(s) if err != nil do return nil return b } s_hkdf :: proc(ikm, salt: []u8, info: string) -> []u8 { out := make([]u8, 32) hkdf.extract_and_expand(.SHA256, salt, ikm, transmute([]u8)info, out) return out } s_hmac :: proc(key, msg: []u8) -> []u8 { out := make([]u8, 32) hmac.sum(.SHA256, out, msg, key) return out } s_seal :: proc(key, iv, pt: []u8, aad: []u8 = nil) -> []u8 { out := make([]u8, len(pt) + 16) aead.seal_oneshot(.AES_GCM_256, out[:len(pt)], out[len(pt):], key, iv, aad, pt) return out } s_open :: proc(key, iv, ct: []u8, aad: []u8 = nil) -> ([]u8, bool) { if len(ct) < 16 || len(key) != 32 || len(iv) != 12 do return nil, false out := make([]u8, len(ct) - 16) ok := aead.open_oneshot(.AES_GCM_256, out, key, iv, aad, ct[:len(ct) - 16], ct[len(ct) - 16:]) return out, ok } eq_bytes :: proc(a, b: []u8) -> bool { if len(a) != len(b) do return false x: u8 = 0 for i in 0 ..< len(a) do x |= a[i] ~ b[i] return x == 0 } // ---- P-256 ---- Ec :: struct { d: []u8, // the private scalar pub: []u8, // 65 bytes } ec_new :: proc() -> Ec { k: ecdh.Private_Key if !ecdh.private_key_generate(&k, .SECP256R1) do panic("no P-256 key") return ec_of(&k) } @(private = "file") ec_of :: proc(k: ^ecdh.Private_Key) -> Ec { d := make([]u8, 32) ecdh.private_key_bytes(k, d) pub := make([]u8, 65) ecdh.private_key_public_bytes(k, pub) return {d, pub} } ec_from_d :: proc(d: []u8) -> (Ec, bool) { k: ecdh.Private_Key if len(d) != 32 || !ecdh.private_key_set_bytes(&k, .SECP256R1, d) do return {}, false return ec_of(&k), true } ec_load :: proc(pem: string) -> (Ec, bool) { d, ok := pem_scalar(pem) if !ok do return {}, false return ec_from_d(d) } ec_dh :: proc(priv: Ec, pub_raw: []u8) -> ([]u8, bool) { k: ecdh.Private_Key p: ecdh.Public_Key if len(pub_raw) != 65 || pub_raw[0] != 4 do return nil, false if !ecdh.private_key_set_bytes(&k, .SECP256R1, priv.d) || !ecdh.public_key_set_bytes(&p, .SECP256R1, pub_raw) do return nil, false z := make([]u8, 32) if !ecdh.ecdh(&k, &p, z) do return nil, false return z, true } // ---- master keys ---- mk_id :: proc(k: []u8) -> string {return hex(sha256(join(bytes_of("rc-storage mk-id v1"), k)))[:32]} mk_proof :: proc(k: []u8) -> string {return b64(s_hmac(k, bytes_of("rc-storage proof v1")))} unhex :: proc(s: string) -> []u8 { out := make([]u8, len(s) / 2) v :: proc(c: u8) -> u8 {return c - '0' if c <= '9' else (c | 0x20) - 'a' + 10} for i in 0 ..< len(out) do out[i] = v(s[2 * i]) << 4 | v(s[2 * i + 1]) return out } // DEVICE WRAP Wrap :: struct { eph: string `json:"eph"`, iv: string `json:"iv"`, ct: string `json:"ct"`, } wrap_for_device :: proc(pub_b64: string, k: []u8) -> (Wrap, bool) { dpub := s_unb64(pub_b64) eph := ec_new() z, ok := ec_dh(eph, dpub) if !ok do return {}, false key := s_hkdf(z, join(eph.pub, dpub), "rc-storage device-wrap v1") iv := random_bytes(12) return {b64(eph.pub), b64(iv), b64(s_seal(key, iv, k))}, true } unwrap_for_device :: proc(priv: Ec, pub_b64: string, w: Wrap) -> ([]u8, bool) { eph := s_unb64(w.eph) z, ok := ec_dh(priv, eph) if !ok do return nil, false key := s_hkdf(z, join(eph, s_unb64(pub_b64)), "rc-storage device-wrap v1") return s_open(key, s_unb64(w.iv), s_unb64(w.ct)) } // RECOVERY (Crockford base32, 20 bytes as 32 characters) B32 := "0123456789ABCDEFGHJKMNPQRSTVWXYZ" b32norm :: proc(s: string) -> string { b := strings.builder_make() for ch in transmute([]u8)strings.to_upper(s) { switch ch { case ' ', '\t', '\n', '\r', '-': case 'I', 'L': strings.write_byte(&b, '1') case 'O': strings.write_byte(&b, '0') case: strings.write_byte(&b, ch) } } return strings.to_string(b) } b32dec :: proc(s: string, n: int) -> ([]u8, bool) { t := b32norm(s) if len(t) != (n * 8 + 4) / 5 do return nil, false out := make([dynamic]u8) bits, val: u32 = 0, 0 for ch in transmute([]u8)t { i := strings.index_byte(B32, ch) if i < 0 do return nil, false val = ((val << 5) | u32(i)) & 0xffff bits += 5 if bits >= 8 {append(&out, u8((val >> (bits - 8)) & 255)); bits -= 8} } return out[:n], true } Recovery :: struct { salt: string `json:"salt"`, iv: string `json:"iv"`, ct: string `json:"ct"`, created: i64 `json:"created"`, } recovery_unwrap :: proc(phrase: string, rec: Recovery) -> ([]u8, string) { b, ok := b32dec(phrase, 20) if !ok do return nil, "a recovery key is 32 letters and digits" k, ok2 := s_open(s_hkdf(b, s_unb64(rec.salt), "rc-storage recovery v1"), s_unb64(rec.iv), s_unb64(rec.ct)) if !ok2 do return nil, "the recovery key does not open it" return k, "" } // DEVICE APPROVAL new_code :: proc() -> string { r := random_bytes(12) b := strings.builder_make() for x, i in r { if i > 0 && i % 4 == 0 do strings.write_byte(&b, '-') strings.write_byte(&b, B32[x & 31]) } return strings.to_string(b) } approval_key :: proc(code: string) -> []u8 {return s_hkdf(bytes_of(b32norm(code)), nil, "rc-storage approve v1")} req_msg :: proc(id, pub: string) -> []u8 {return join(bytes_of("req\x00"), bytes_of(id), {0}, s_unb64(pub))} ok_msg :: proc(id, pub: string, w: Wrap, mkid: string) -> []u8 { return join(bytes_of("ok\x00"), bytes_of(id), {0}, s_unb64(pub), s_unb64(w.eph), s_unb64(w.iv), s_unb64(w.ct), unhex(mkid)) } request_tag :: proc(code, id, pub: string) -> string {return b64(s_hmac(approval_key(code), req_msg(id, pub)))} check_request :: proc(code: string, q: json.Value) -> bool { return const_eq(request_tag(code, jstr(q, "id"), jstr(q, "pub")), jstr(q, "tag")) } approval_tag :: proc(code, id, pub: string, w: Wrap, mkid: string) -> string {return b64(s_hmac(approval_key(code), ok_msg(id, pub, w, mkid)))} // THE ROOT Root_Entry :: struct { id: string `json:"id"`, pub: string `json:"pub,omitempty"`, // a root wrap key (storage's keyring) eph: string `json:"eph,omitempty"`, // a wrap for the root (an app's keyring) iv: string `json:"iv"`, ct: string `json:"ct"`, } root_id :: proc(pub_b64: string) -> string {return hex(sha256(join(bytes_of("rc-root id v1"), s_unb64(pub_b64))))[:32]} rwk_aad :: proc(root: []u8, pub_b64: string) -> []u8 {return join(bytes_of("rc-root rwk v1\x00"), unhex(mk_id(root)), s_unb64(pub_b64))} open_root_wrap_key :: proc(root: []u8, e: Root_Entry) -> (Ec, string) { if e.id != root_id(e.pub) do return {}, "root key id mismatch" d, ok := s_open(s_hkdf(root, nil, "rc-root rwk-wrap v1"), s_unb64(e.iv), s_unb64(e.ct), rwk_aad(root, e.pub)) if !ok do return {}, "the root key does not open" k, kok := ec_from_d(d) if !kok || !eq_bytes(k.pub, s_unb64(e.pub)) do return {}, "root key does not match its public half" return k, "" } app_aad :: proc(app, mkid: string) -> []u8 {return join(bytes_of("rc-root app v1\x00"), bytes_of(app), {0}, unhex(mkid))} unwrap_from_root :: proc(rwk: Ec, root_pub_b64, app, mkid: string, w: Root_Entry) -> ([]u8, string) { eph := s_unb64(w.eph) z, ok := ec_dh(rwk, eph) if !ok do return nil, "ECDH failed" mk, ok2 := s_open(s_hkdf(z, join(eph, s_unb64(root_pub_b64)), "rc-root app-wrap v1"), s_unb64(w.iv), s_unb64(w.ct), app_aad(app, mkid)) if !ok2 do return nil, "the app's key does not open under the root" if mk_id(mk) != mkid do return nil, "app key id mismatch" return mk, "" } // KEYRING v2: as storage holds it, field for field. Kr_Device :: struct { id: string `json:"id"`, name: string `json:"name"`, pub: string `json:"pub"`, wrap: Wrap `json:"wrap"`, ok: string `json:"ok,omitempty"`, created: i64 `json:"created"`, via: string `json:"via"`, } Kr_Older :: struct { mk_id: string `json:"mk_id"`, iv: string `json:"iv"`, ct: string `json:"ct"`, } Keyring :: struct { v: int `json:"v"`, mk_id: string `json:"mk_id"`, epoch: i64 `json:"epoch"`, root: Root_Entry `json:"root"`, recovery: ^Recovery `json:"recovery,omitempty"`, // storage's own keyring only devices: []Kr_Device `json:"devices"`, older: []Kr_Older `json:"older"`, mac: string `json:"mac"`, } keyring_msg :: proc(kr: Keyring, user, app: string) -> []u8 { b := strings.builder_make() r := kr.root fmt.sbprintf(&b, "rc-keyring v2\nuser %s\napp %s\nmk %s\nepoch %d\nroot %s %s %s %s\n", user, app, kr.mk_id, kr.epoch, r.id, r.pub if r.pub != "" else r.eph, r.iv, r.ct) if app == "-" && kr.recovery != nil {c := kr.recovery^; fmt.sbprintf(&b, "recovery %s %s %s %d\n", c.salt, c.iv, c.ct, c.created)} for d in kr.devices do fmt.sbprintf(&b, "device %s %s %s %s %s %s %s %d %s\n", d.id, d.pub, d.wrap.eph, d.wrap.iv, d.wrap.ct, d.ok if d.ok != "" else "-", d.via, d.created, b64(bytes_of(d.name))) for o in kr.older do fmt.sbprintf(&b, "older %s %s %s\n", o.mk_id, o.iv, o.ct) return transmute([]u8)strings.to_string(b) } keyring_mac :: proc(k: []u8, kr: Keyring, user, app: string) -> string { return b64(s_hmac(s_hkdf(k, nil, "rc-keyring mac v1"), keyring_msg(kr, user, app))) } check_keyring :: proc(k: []u8, kr: Keyring, user, app: string) -> bool { return kr.mac != "" && const_eq(keyring_mac(k, kr, user, app), kr.mac) } open_older :: proc(k: []u8, e: Kr_Older) -> bool { old, ok := s_open(s_hkdf(k, nil, "rc-keyring older v1"), s_unb64(e.iv), s_unb64(e.ct), join(bytes_of("rc-keyring older v1\x00"), unhex(e.mk_id))) return ok && mk_id(old) == e.mk_id } // A device the robot plays: its key, and what it remembers of the keyring. Dev :: struct { id: string, priv: Ec, pub: string, pin: string, // the mk_id it trusts, or "" epoch: i64, code: string, // a pending approval code, or "" } // A device's view (rc-seal.js's trust()): the key its entry opens, or why it is refused. trust_keyring :: proc(kr: Keyring, dev: Dev, user, app: string) -> ([]u8, string) { if kr.v != 2 do return nil, "not a v2 keyring" mine: ^Kr_Device for &d in kr.devices do if d.id == dev.id do mine = &d if mine == nil do return nil, "this device is not in the keyring" if mine.pub != dev.pub do return nil, "this device's entry carries another key" k, ok := unwrap_for_device(dev.priv, dev.pub, mine.wrap) if !ok do return nil, "this device's entry does not open" if mk_id(k) != kr.mk_id do return nil, "this device's entry is not the keyring's key" if dev.pin == kr.mk_id { } else if dev.pin != "" { held := false for o in kr.older do if o.mk_id == dev.pin && open_older(k, o) do held = true if !held do return nil, "the keyring's key changed, and the new one does not hold the old" } else if dev.code == "" || mine.ok == "" || !const_eq(approval_tag(dev.code, dev.id, dev.pub, mine.wrap, kr.mk_id), mine.ok) { return nil, "this device's entry was not vouched for under its code" } if !check_keyring(k, kr, user, app) do return nil, "the keyring was changed by someone without its key" if dev.epoch > kr.epoch do return nil, "the keyring is older than one this device has seen" return k, "" } // ENVELOPE (not FRAGMENTED MEDIA: the zoo seals words) ENV_TYPE :: "application/x-rc-encrypted" envelope_seal :: proc(mk, pt: []u8, name, type: string, log2 := 12) -> []u8 { cs := 1 << uint(log2) size := len(pt) n := max(1, (size + cs - 1) / cs) fk := random_bytes(32) P := random_bytes(8) fk_iv := random_bytes(12) meta := fmt.tprintf(`{{"name":%s,"type":%s,"mtime":%d}}`, jq(name), jq(type), now_ms()) meta_ct := s_seal(fk, join(P, {0xff, 0xff, 0xff, 0xff}), bytes_of(meta), bytes_of("rc-meta")) size8 := make([]u8, 8) for i in 0 ..< 8 do size8[i] = u8(u64(size) >> uint(56 - 8 * i)) head := join(bytes_of("RCE1"), {u8(log2), 0, 0, 0}, size8, unhex(mk_id(mk)), P, fk_iv, s_seal(mk, fk_iv, fk), be32(u32(len(meta_ct))), meta_ct) hh := sha256(head) out := make([dynamic]u8) append(&out, ..head) for i in 0 ..< n { last: u8 = 1 if i == n - 1 else 0 append(&out, ..s_seal(fk, join(P, be32(u32(i))), pt[i * cs:min(size, (i + 1) * cs)], join(hh, {last}))) } return out[:] } // The words and the meta, with the key `key_for` gives for the envelope's mk_id. Refuses what // rc-crypt.js refuses. envelope_open :: proc(key_for: proc(mkid: string, arg: rawptr) -> []u8, arg: rawptr, env_: []u8) -> (pt: []u8, err: string) { e := env_ if len(e) < 104 || string(e[:4]) != "RCE1" do return nil, "not an encrypted file" log2 := int(e[4]) if log2 < 12 || log2 > 24 || e[5] != 0 || e[6] != 0 || e[7] != 0 do return nil, "bad header" size := 0 for i in 0 ..< 8 do size = size << 8 | int(e[8 + i]) mkid := hex(e[16:32]) k := key_for(mkid, arg) if k == nil || mk_id(k) != mkid do return nil, "sealed with a different key" meta_len := int(e[100]) << 24 | int(e[101]) << 16 | int(e[102]) << 8 | int(e[103]) if meta_len > 65536 || 104 + meta_len > len(e) do return nil, "bad header" hl := 104 + meta_len P := e[32:40] fk, ok := s_open(k, e[40:52], e[52:100]) if !ok do return nil, "the file key does not open" if _, mok := s_open(fk, join(P, {0xff, 0xff, 0xff, 0xff}), e[104:hl], bytes_of("rc-meta")); !mok do return nil, "the meta does not open" hh := sha256(e[:hl]) cs := 1 << uint(log2) n := max(1, (size + cs - 1) / cs) out := make([dynamic]u8) at := hl for i in 0 ..< n { l := min(cs, size - i * cs) + 16 if at + l > len(e) do return nil, "truncated" last: u8 = 1 if i == n - 1 else 0 chunk, cok := s_open(fk, join(P, be32(u32(i))), e[at:at + l], join(hh, {last})) if !cok do return nil, "a chunk does not open" append(&out, ..chunk) at += l } if at != len(e) do return nil, "trailing bytes" return out[:], "" } // ---- making a keyring (once per environment, robotseal.odin) ---- b32enc :: proc(bytes: []u8) -> string { out := strings.builder_make() bits, val: u32 = 0, 0 for c in bytes { val = ((val << 8) | u32(c)) & 0xffff bits += 8 for bits >= 5 {strings.write_byte(&out, B32[(val >> (bits - 5)) & 31]); bits -= 5} } if bits > 0 do strings.write_byte(&out, B32[(val << (5 - bits)) & 31]) return strings.to_string(out) } new_recovery_key :: proc() -> ([]u8, string) { b := random_bytes(20) s := b32enc(b) parts := make([dynamic]string) for i := 0; i < len(s); i += 4 do append(&parts, s[i:min(i + 4, len(s))]) return b, strings.join(parts[:], "-") } recovery_wrap :: proc(bytes, k: []u8) -> Recovery { salt, iv := random_bytes(16), random_bytes(12) return {b64(salt), b64(iv), b64(s_seal(s_hkdf(bytes, salt, "rc-storage recovery v1"), iv, k)), now()} } new_root_wrap_key :: proc(root: []u8) -> Root_Entry { k := ec_new() pub := b64(k.pub) iv := random_bytes(12) return {id = root_id(pub), pub = pub, iv = b64(iv), ct = b64(s_seal(s_hkdf(root, nil, "rc-root rwk-wrap v1"), iv, k.d, rwk_aad(root, pub)))} } wrap_for_root :: proc(root_id_, root_pub, app: string, app_mk: []u8) -> Root_Entry { rpub := s_unb64(root_pub) eph := ec_new() z, _ := ec_dh(eph, rpub) iv := random_bytes(12) return {id = root_id_, eph = b64(eph.pub), iv = b64(iv), ct = b64(s_seal(s_hkdf(z, join(eph.pub, rpub), "rc-root app-wrap v1"), iv, app_mk, app_aad(app, mk_id(app_mk))))} }