Zoo

← back to the zoo

27. A new device needs an old one

A device that never opened your sealed files gets in only with a code typed on one that has, or with your recovery key.

rc-seal.js: seal.request() shows a code, seal.approve(code) on a device that has the key lets the new one in, seal.useStorage() lets storage's window do it with your recovery key; every keyring is checked under the key it guards.

This is the code serving the zoo right now: the bytes this very program was built from (each file is embedded when the zoo is compiled), at commit 55c71513c5 (live). The zoo's own self-check fetches this page and compares it byte for byte with the file it runs.

e27_new_device.odin sha256 170e6a8eb4ed · raw

1package main
2
3// Exhibit 27. A browser that never opened your sealed postcard gets in only two ways: a code it shows,
4// typed on a device that already can (both ends check an HMAC keyed by the code, so the server can
5// neither swap the new device's key nor hand it a key of its own), or your recovery key (in storage's
6// window, so the root never reaches this page). rc-seal.js does both; the card uses exhibit 26's
7// instance. The self-check plays three of the robot's browsers, and the server twice.
8
9import "core:encoding/json"
10import "core:fmt"
11import "core:strings"
12import "ratcloud:rc"
13
14e27 :: proc() -> Exhibit {
15	return {
16		n = 27, wing = "Sealed",
17		title = "A new device needs an old one",
18		promise = "A device that never opened your sealed files gets in only with a code typed on one that has, or with your recovery key.",
19		block = "rc-seal.js: seal.request() shows a code, seal.approve(code) on a device that has the key lets the new one in, seal.useStorage() lets storage's window do it with your recovery key; every keyring is checked under the key it guards.",
20		src = {"e27_new_device.odin", #load("e27_new_device.odin", string)},
21		files = srcs({"robotseal.odin", #load("robotseal.odin", string)}, {"seal.odin", #load("seal.odin", string)}),
22		script = {"web/e27.js", #load("web/e27.js", string)},
23		show = proc(me: ^rc.User) -> string {
24			if me == nil do return signin_line(", seal a postcard (26), then open this page in a private window.")
25			return `<div id="seal27"><p class="muted">Loading…</p></div>`
26		},
27		check = proc() -> Check {
28			s, err := robot_sealing()
29			if err != "" do return fail(err)
30			kA, kr, kerr := robot_zoo_key(&s)
31			if kerr != "" do return fail(kerr)
32			words := postcard_words()
33			if _, _, perr := robot_seal_postcard(kA, words); perr != "" do return fail(perr)
34			steps := make([dynamic]string)
35			// B: a browser that never opened it. It shows a code and asks.
36			bk := ec_new()
37			B := Dev{id = b64u(random_bytes(18)), priv = bk, pub = b64(bk.pub), code = new_code()}
38			defer {
39				// B leaves again, so the robot's keyring does not grow every five minutes.
40				if k2, kr2, e2 := robot_zoo_key(&s); e2 == "" {
41					keep := make([dynamic]Kr_Device)
42					for d in kr2.devices do if d.id != B.id do append(&keep, d)
43					if len(keep) != len(kr2.devices) do robot_zoo_write(&s, k2, kr2, keep[:])
44				}
45				robot_zoo_storage("keyring", fmt.tprintf(`{{"op":"decline","id":%s}}`, jq(B.id)))
46			}
47			if _, e := robot_zoo_storage("keyring", fmt.tprintf(`{{"op":"request","id":%s,"name":"Robot's new device","pub":%s,"tag":%s}}`, jq(B.id), jq(B.pub), jq(request_tag(B.code, B.id, B.pub)))); e != "" do return fail(e)
48			if _, terr := trust_keyring(kr, B, s.user, "zoo"); terr == "" do return fail("a device that was never let in opened the keyring")
49			_, held, herr := robot_postcard_bytes()
50			if herr != "" do return fail(herr)
51			none :: proc(id: string, arg: rawptr) -> []u8 {return nil}
52			if _, e := envelope_open(none, nil, held); e == "" do return fail("the postcard opened with no key")
53			append(&steps, "locked, showing a code")
54			// A, the robot's first device, is told a wrong code: no waiting device matches it.
55			g, gerr := robot_zoo_storage("keyring", `{"op":"get","fresh":true}`)
56			if gerr != "" do return fail(gerr)
57			reqs := jarr(g, "requests")
58			q_i := -1
59			for q, i in reqs do if jstr(q, "id") == B.id do q_i = i
60			if q_i < 0 do return fail("storage does not show the new device's request")
61			wrong := new_code()
62			for q in reqs do if check_request(wrong, q) do return fail("a wrong code matched a waiting device")
63			append(&steps, "a wrong code refused")
64			q := reqs[q_i]
65			// The server swaps the waiting device's public key for one of its own (the check plays the server).
66			swapped := parse(to_json(q))
67			if o, ok := swapped.(json.Object); ok do o["pub"] = json.String(b64(ec_new().pub))
68			if check_request(B.code, swapped) do return fail("a key the server swapped into the request was accepted")
69			append(&steps, "a key the server swapped into the request refused")
70			// The right code: A wraps the zoo's key for B and vouches for it under the code.
71			if !check_request(B.code, q) do return fail("the right code did not match the request")
72			w, _ := wrap_for_device(jstr(q, "pub"), kA)
73			devs := make([dynamic]Kr_Device)
74			append(&devs, ..kr.devices)
75			append(&devs, Kr_Device{id = jstr(q, "id"), name = jstr(q, "name"), pub = jstr(q, "pub"), wrap = w, ok = approval_tag(B.code, jstr(q, "id"), jstr(q, "pub"), w, kr.mk_id), created = now(), via = "approved"})
76			kr2, werr := robot_zoo_write(&s, kA, kr, devs[:])
77			if werr != "" do return fail(werr)
78			// The server hands B a wrap of a key of its own instead (keeping A's tag): refused.
79			fake := kr2
80			fake.devices = make([]Kr_Device, len(kr2.devices))
81			copy(fake.devices, kr2.devices)
82			for &d in fake.devices do if d.id == B.id {d.wrap, _ = wrap_for_device(B.pub, random_bytes(32))}
83			if _, e := trust_keyring(fake, B, s.user, "zoo"); e == "" do return fail("a wrap of a key the server chose was accepted")
84			append(&steps, "a key the server swapped in for the new device refused")
85			g2, g2err := robot_zoo_storage("keyring", `{"op":"get","fresh":true}`)
86			if g2err != "" do return fail(g2err)
87			kr3, _ := keyring_of(jget(g2, "keyring"))
88			kB, berr := trust_keyring(kr3, B, s.user, "zoo")
89			if berr != "" do return fail(cat("the new device, let in with the right code, is refused: ", berr))
90			_, held2, h2err := robot_postcard_bytes()
91			if h2err != "" do return fail(h2err)
92			Keys :: struct {
93				id: string,
94				k:  []u8,
95			}
96			key_for :: proc(id: string, arg: rawptr) -> []u8 {x := (^Keys)(arg); return x.k if id == x.id else nil}
97			kb := Keys{kr3.mk_id, kB}
98			if back, e := envelope_open(key_for, &kb, held2); e != "" || string(back) != words do return fail("the new device opened other words")
99			append(&steps, "with the right code, the new device opens the postcard")
100			// C: nothing but the recovery key. In a browser this happens in storage's window.
101			rj, rerr := robot_storage_seal(`{"op":"get","fresh":true}`)
102			if rerr != "" do return fail(rerr)
103			root, rok := keyring_of(jget(rj, "keyring"))
104			if !rok || root.recovery == nil {
105				keys := make([dynamic]string)
106				if o, isobj := jget(rj, "keyring").(json.Object); isobj do for k in o do append(&keys, k)
107				return fail(cat("storage's keyring for the robot has no recovery entry (it has: ", strings.join(keys[:], ", "), "; it parsed: ", "yes" if rok else g_keyring_err, ")"))
108			}
109			R, uerr := recovery_unwrap(s.phrase, root.recovery^)
110			if uerr != "" do return fail(uerr)
111			if mk_id(R) != root.mk_id || !check_keyring(R, root, s.user, "-") do return fail("the recovery key does not open a keyring that checks out")
112			rwk, oerr := open_root_wrap_key(R, root.root)
113			if oerr != "" do return fail(oerr)
114			M, merr := unwrap_from_root(rwk, root.root.pub, "zoo", kr3.mk_id, kr3.root)
115			if merr != "" do return fail(merr)
116			if !check_keyring(M, kr3, s.user, "zoo") do return fail("the zoo's keyring does not check out under the key the recovery key opened")
117			km := Keys{kr3.mk_id, M}
118			if back, e := envelope_open(key_for, &km, held2); e != "" || string(back) != words do return fail("the recovery key opened other words")
119			append(&steps, "the recovery key opens it too")
120			return pass(cat("a new device of the robot's: ", strings.join(steps[:], "; ")), struct {
121					steps: []string `json:"steps"`,
122				}{steps[:]})
123		},
124	}
125}

robotseal.odin sha256 d4dab5c5e496 · raw

1package main
2
3// The robot's sealing, for the self-checks of exhibits 26 and 27. The robot plays a person's browsers
4// the way rc-crypt.js and rc-seal.js do in a real one (seal.odin has the same bytes): at storage
5// (/api/seal, with its storage sign-in), and at the zoo, whose server forwards to storage like any
6// app's (/api/26/storage). It holds what a person holds: each device's private key and the recovery
7// key, in robot-seal.json (the zoo's own data, like the robot's passkey), never a key that opens a
8// file; those are unwrapped again at every check.
9
10import "core:encoding/json"
11import "core:fmt"
12import "core:strings"
13import "ratcloud:rc"
14
15Rdev :: struct {
16	id:    string `json:"id"`,
17	pem:   string `json:"pem"`,
18	pub:   string `json:"pub"`,
19	pin:   string `json:"pin"`,
20	epoch: i64 `json:"epoch"`,
21}
22Rseal :: struct {
23	user:        string `json:"user"`,
24	storage_dev: Rdev `json:"storage_dev"`,
25	zoo_dev:     Rdev `json:"zoo_dev"`,
26	phrase:      string `json:"phrase"`,
27	made:        i64 `json:"made"`,
28}
29
30RSEAL_FILE :: "robot-seal.json"
31POSTCARD :: "sealed/postcard.rce"
32
33rseal_save :: proc(s: Rseal) -> string {
34	if rc.write_file(RSEAL_FILE, transmute([]u8)to_json(s)) != 0 do return "could not save the robot's sealing state"
35	return ""
36}
37
38robot_at_storage :: proc() -> (^Browser, string) {return robot_at("storage")}
39
40// Storage's own page API, as the robot's browser at storage.
41robot_storage_seal :: proc(in_json: string) -> (json.Value, string) {
42	b, err := robot_at_storage()
43	if err != "" do return nil, err
44	r := post(b, cat(rc.app_url("storage"), "/api/seal"), in_json)
45	if r.status != 200 do return nil, fmt.tprintf("storage's /api/seal answered %d: %s", r.status, jstr(r.j, "error") if r.j != nil else clip(r.body, 120))
46	return r.j, ""
47}
48// The zoo's own route to storage, as the zoo's page calls it.
49robot_zoo_storage :: proc(op, body: string) -> (json.Value, string) {
50	b, err := robot_at()
51	if err != "" do return nil, err
52	r := post(b, self_url("/api/26/storage"), fmt.tprintf(`{{"op":%s,"body":%s}}`, jq(op), body))
53	if r.status != 200 do return nil, fmt.tprintf("the zoo's /api/26/storage (%s) answered %d: %s", op, r.status, jstr(r.j, "error") if r.j != nil else clip(r.body, 120))
54	return r.j, ""
55}
56
57rdev :: proc(d: Rdev) -> (Dev, bool) {
58	k, ok := ec_load(d.pem)
59	return {id = d.id, priv = k, pub = d.pub, pin = d.pin, epoch = d.epoch}, ok
60}
61new_rdev :: proc() -> Rdev {
62	k := ec_new()
63	return {id = b64u(random_bytes(18)), pem = pem_of(k.d, k.pub), pub = b64(k.pub)}
64}
65rdev_entry :: proc(d: Rdev, k: []u8, via, name: string) -> Kr_Device {
66	w, _ := wrap_for_device(d.pub, k)
67	return {id = d.id, name = name, pub = d.pub, wrap = w, created = now(), via = via}
68}
69
70g_keyring_err: string
71keyring_of :: proc(v: json.Value) -> (kr: Keyring, ok: bool) {
72	if v == nil do return {}, false
73	if _, null := v.(json.Null); null do return {}, false
74	// core:encoding/json does not unmarshal into a pointer: the recovery entry goes in by hand
75	o, isobj := v.(json.Object)
76	if !isobj do return {}, false
77	rec := o["recovery"]
78	delete_key(&o, "recovery")
79	err := json.unmarshal_string(to_json(o), &kr)
80	o["recovery"] = rec
81	if jhas(rec) {
82		r := new(Recovery)
83		if json.unmarshal_string(to_json(rec), r) == nil do kr.recovery = r
84	}
85	if err != nil do g_keyring_err = fmt.tprintf("%v", err)
86	return kr, err == nil
87}
88
89// The robot's devices, set up once per environment: a storage device holding its root (and the
90// recovery key), and a zoo device holding the zoo's key for it.
91robot_sealing :: proc() -> (Rseal, string) {
92	uid := itoa(robot_user().id)
93	s: Rseal
94	if b, err := rc.read_file(RSEAL_FILE); err == 0 && json.unmarshal(b, &s) == nil && s.user == uid && uid != "0" do return s, ""
95	if _, err := robot_at_storage(); err != "" do return {}, err
96	uid = itoa(robot_user().id)
97	have, err := robot_storage_seal(`{"op":"get","fresh":true}`)
98	if err != "" do return {}, err
99	if jhas(have, "keyring") do return {}, "the robot has a keyring at storage but not its devices (robot-seal.json was lost): its sealed postcard cannot be opened"
100	root := random_bytes(32)
101	rb, phrase := new_recovery_key()
102	sd := new_rdev()
103	e := new_root_wrap_key(root)
104	rec := recovery_wrap(rb, root)
105	kr := Keyring{v = 2, mk_id = mk_id(root), epoch = 1, root = e, recovery = &rec, devices = {rdev_entry(sd, root, "created", "Zoo robot")}, older = {}}
106	kr.mac = keyring_mac(root, kr, uid, "-")
107	if _, err2 := robot_storage_seal(fmt.tprintf(`{{"op":"put","keyring":%s,"newproof":%s}}`, to_json(kr), jq(mk_proof(root)))); err2 != "" do return {}, err2
108	sd.pin, sd.epoch = kr.mk_id, 1
109	// The zoo's key, wrapped to the root's public half: the robot holds the root here, so it opens the
110	// entry and the public half it wraps to is the root's own (in a browser: storage's window).
111	if _, rerr := open_root_wrap_key(root, e); rerr != "" do return {}, rerr
112	app := random_bytes(32)
113	zd := new_rdev()
114	akr := Keyring{v = 2, mk_id = mk_id(app), epoch = 1, root = wrap_for_root(e.id, e.pub, "zoo", app), devices = {rdev_entry(zd, app, "created", "Zoo robot")}, older = {}}
115	akr.mac = keyring_mac(app, akr, uid, "zoo")
116	if _, err3 := robot_zoo_storage("keyring", fmt.tprintf(`{{"op":"put","keyring":%s,"newproof":%s}}`, to_json(akr), jq(mk_proof(app)))); err3 != "" do return {}, err3
117	zd.pin, zd.epoch = akr.mk_id, 1
118	s = {user = uid, storage_dev = sd, zoo_dev = zd, phrase = phrase, made = now()}
119	return s, rseal_save(s)
120}
121
122// The zoo's key for the robot, as its zoo device opens it (rc-seal.js's trust()).
123robot_zoo_key :: proc(s: ^Rseal) -> ([]u8, Keyring, string) {
124	j, err := robot_zoo_storage("keyring", `{"op":"get","fresh":true}`)
125	if err != "" do return nil, {}, err
126	kr, ok := keyring_of(jget(j, "keyring"))
127	if !ok do return nil, {}, "the zoo has no keyring for the robot at storage"
128	dev, dok := rdev(s.zoo_dev)
129	if !dok do return nil, {}, "the robot's zoo device key does not load"
130	k, terr := trust_keyring(kr, dev, s.user, "zoo")
131	if terr != "" do return nil, {}, terr
132	s.zoo_dev.pin, s.zoo_dev.epoch = kr.mk_id, kr.epoch
133	if e := rseal_save(s^); e != "" do return nil, {}, e
134	return k, kr, ""
135}
136
137// A keyring the robot changes: one more epoch, its MAC, the proof of the key it holds.
138robot_zoo_write :: proc(s: ^Rseal, k: []u8, kr: Keyring, devices: []Kr_Device) -> (Keyring, string) {
139	next := kr
140	next.epoch = kr.epoch + 1
141	next.devices = devices
142	if next.older == nil do next.older = make([]Kr_Older, 0)
143	next.mac = ""
144	next.mac = keyring_mac(k, next, s.user, "zoo")
145	j, err := robot_zoo_storage("keyring", fmt.tprintf(`{{"op":"put","keyring":%s,"proof":%s}}`, to_json(next), jq(mk_proof(k))))
146	if err != "" do return {}, err
147	out, ok := keyring_of(jget(j, "keyring"))
148	if !ok do return {}, "storage did not hand the keyring back"
149	s.zoo_dev.epoch = out.epoch
150	return out, rseal_save(s^)
151}
152
153// Seal words under the zoo's key and save them as the robot's postcard, through the public paths:
154// begin, the bytes straight to B2, commit. The file and the envelope's bytes.
155robot_seal_postcard :: proc(k: []u8, words: string) -> (json.Value, []u8, string) {
156	env_ := envelope_seal(k, bytes_of(words), "postcard.txt", "text/plain")
157	j, err := robot_zoo_storage("begin", fmt.tprintf(`{{"files":[{{"path":%s,"size":%d,"type":%s}}]}}`, jq(POSTCARD), len(env_), jq(ENV_TYPE)))
158	if err != "" do return nil, nil, err
159	f := jarr(j, "files")
160	if len(f) == 0 || jstr(f[0], "url") == "" do return nil, nil, cat("storage would not begin the postcard: ", to_json(j))
161	put := put_many({{jstr(f[0], "url"), jstr(f[0], "type"), env_}})[0]
162	if put != 200 do return nil, nil, fmt.tprintf("B2 answered the PUT with %d", put)
163	c, cerr := robot_zoo_storage("commit", fmt.tprintf(`{{"ids":[%d]}}`, jint(f[0], "id")))
164	if cerr != "" do return nil, nil, cerr
165	cf := jarr(c, "files")
166	if len(cf) == 0 || !jhas(cf[0], "file") do return nil, nil, cat("storage would not commit the postcard: ", to_json(c))
167	return jget(cf[0], "file"), env_, ""
168}
169
170// The robot's postcard as the bucket holds it (a presigned GET, like a browser's).
171robot_postcard_bytes :: proc() -> (json.Value, []u8, string) {
172	j, err := robot_zoo_storage("urls", fmt.tprintf(`{{"paths":[%s]}}`, jq(POSTCARD)))
173	if err != "" do return nil, nil, err
174	f := jarr(j, "files")
175	if len(f) == 0 || jstr(f[0], "url") == "" do return nil, nil, cat("storage has no postcard for the robot: ", to_json(j))
176	g := get_many({jstr(f[0], "url")})[0]
177	if g.status != 200 do return nil, nil, fmt.tprintf("the bucket answered %d", g.status)
178	return f[0], g.body, ""
179}
180
181POSTCARD_WORDS := [?]string{"otter", "lantern", "harbour", "juniper", "comet", "pebble", "meadow", "falcon", "teacup", "glacier", "cinnamon", "lighthouse"}
182postcard_words :: proc() -> string {
183	return fmt.tprintf("Sealed at %s UTC by the zoo's robot. Today's word: %s-%s.", hm(now()), POSTCARD_WORDS[random_int(0, len(POSTCARD_WORDS) - 1)], random_hex(3))
184}
185
186_ :: strings

seal.odin sha256 e6ef86895cb2 · raw

1package main
2
3// seal: rc-crypt.js's formats, byte for byte (storage's seal/v1/rc-crypt.js is the spec), for the
4// zoo's robot. A person's browser does all of this in rc-crypt.js; the self-checks of exhibits 26 and
5// 27 play that browser (and, to show what is refused, the server), so they need the same bytes.
6//
7// P-256 (public halves as the 65-byte uncompressed point, base64), AES-256-GCM as ciphertext ||
8// 16-byte tag (WebCrypto's layout), HKDF-SHA256, all from core:crypto.
9
10import "core:crypto/aead"
11import "core:crypto/ecdh"
12import "core:crypto/hkdf"
13import "core:crypto/hmac"
14import "core:encoding/base64"
15import "core:encoding/json"
16import "core:fmt"
17import "core:strings"
18
19Seal_Error :: string // "" = fine
20
21s_unb64 :: proc(s: string) -> []u8 {
22	b, err := base64.decode(s)
23	if err != nil do return nil
24	return b
25}
26
27s_hkdf :: proc(ikm, salt: []u8, info: string) -> []u8 {
28	out := make([]u8, 32)
29	hkdf.extract_and_expand(.SHA256, salt, ikm, transmute([]u8)info, out)
30	return out
31}
32s_hmac :: proc(key, msg: []u8) -> []u8 {
33	out := make([]u8, 32)
34	hmac.sum(.SHA256, out, msg, key)
35	return out
36}
37s_seal :: proc(key, iv, pt: []u8, aad: []u8 = nil) -> []u8 {
38	out := make([]u8, len(pt) + 16)
39	aead.seal_oneshot(.AES_GCM_256, out[:len(pt)], out[len(pt):], key, iv, aad, pt)
40	return out
41}
42s_open :: proc(key, iv, ct: []u8, aad: []u8 = nil) -> ([]u8, bool) {
43	if len(ct) < 16 || len(key) != 32 || len(iv) != 12 do return nil, false
44	out := make([]u8, len(ct) - 16)
45	ok := aead.open_oneshot(.AES_GCM_256, out, key, iv, aad, ct[:len(ct) - 16], ct[len(ct) - 16:])
46	return out, ok
47}
48eq_bytes :: proc(a, b: []u8) -> bool {
49	if len(a) != len(b) do return false
50	x: u8 = 0
51	for i in 0 ..< len(a) do x |= a[i] ~ b[i]
52	return x == 0
53}
54
55// ---- P-256 ----
56
57Ec :: struct {
58	d:   []u8, // the private scalar
59	pub: []u8, // 65 bytes
60}
61
62ec_new :: proc() -> Ec {
63	k: ecdh.Private_Key
64	if !ecdh.private_key_generate(&k, .SECP256R1) do panic("no P-256 key")
65	return ec_of(&k)
66}
67@(private = "file")
68ec_of :: proc(k: ^ecdh.Private_Key) -> Ec {
69	d := make([]u8, 32)
70	ecdh.private_key_bytes(k, d)
71	pub := make([]u8, 65)
72	ecdh.private_key_public_bytes(k, pub)
73	return {d, pub}
74}
75ec_from_d :: proc(d: []u8) -> (Ec, bool) {
76	k: ecdh.Private_Key
77	if len(d) != 32 || !ecdh.private_key_set_bytes(&k, .SECP256R1, d) do return {}, false
78	return ec_of(&k), true
79}
80ec_load :: proc(pem: string) -> (Ec, bool) {
81	d, ok := pem_scalar(pem)
82	if !ok do return {}, false
83	return ec_from_d(d)
84}
85ec_dh :: proc(priv: Ec, pub_raw: []u8) -> ([]u8, bool) {
86	k: ecdh.Private_Key
87	p: ecdh.Public_Key
88	if len(pub_raw) != 65 || pub_raw[0] != 4 do return nil, false
89	if !ecdh.private_key_set_bytes(&k, .SECP256R1, priv.d) || !ecdh.public_key_set_bytes(&p, .SECP256R1, pub_raw) do return nil, false
90	z := make([]u8, 32)
91	if !ecdh.ecdh(&k, &p, z) do return nil, false
92	return z, true
93}
94
95// ---- master keys ----
96
97mk_id :: proc(k: []u8) -> string {return hex(sha256(join(bytes_of("rc-storage mk-id v1"), k)))[:32]}
98mk_proof :: proc(k: []u8) -> string {return b64(s_hmac(k, bytes_of("rc-storage proof v1")))}
99unhex :: proc(s: string) -> []u8 {
100	out := make([]u8, len(s) / 2)
101	v :: proc(c: u8) -> u8 {return c - '0' if c <= '9' else (c | 0x20) - 'a' + 10}
102	for i in 0 ..< len(out) do out[i] = v(s[2 * i]) << 4 | v(s[2 * i + 1])
103	return out
104}
105
106// DEVICE WRAP
107Wrap :: struct {
108	eph: string `json:"eph"`,
109	iv:  string `json:"iv"`,
110	ct:  string `json:"ct"`,
111}
112
113wrap_for_device :: proc(pub_b64: string, k: []u8) -> (Wrap, bool) {
114	dpub := s_unb64(pub_b64)
115	eph := ec_new()
116	z, ok := ec_dh(eph, dpub)
117	if !ok do return {}, false
118	key := s_hkdf(z, join(eph.pub, dpub), "rc-storage device-wrap v1")
119	iv := random_bytes(12)
120	return {b64(eph.pub), b64(iv), b64(s_seal(key, iv, k))}, true
121}
122unwrap_for_device :: proc(priv: Ec, pub_b64: string, w: Wrap) -> ([]u8, bool) {
123	eph := s_unb64(w.eph)
124	z, ok := ec_dh(priv, eph)
125	if !ok do return nil, false
126	key := s_hkdf(z, join(eph, s_unb64(pub_b64)), "rc-storage device-wrap v1")
127	return s_open(key, s_unb64(w.iv), s_unb64(w.ct))
128}
129
130// RECOVERY (Crockford base32, 20 bytes as 32 characters)
131B32 := "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
132b32norm :: proc(s: string) -> string {
133	b := strings.builder_make()
134	for ch in transmute([]u8)strings.to_upper(s) {
135		switch ch {
136		case ' ', '\t', '\n', '\r', '-':
137		case 'I', 'L': strings.write_byte(&b, '1')
138		case 'O': strings.write_byte(&b, '0')
139		case: strings.write_byte(&b, ch)
140		}
141	}
142	return strings.to_string(b)
143}
144b32dec :: proc(s: string, n: int) -> ([]u8, bool) {
145	t := b32norm(s)
146	if len(t) != (n * 8 + 4) / 5 do return nil, false
147	out := make([dynamic]u8)
148	bits, val: u32 = 0, 0
149	for ch in transmute([]u8)t {
150		i := strings.index_byte(B32, ch)
151		if i < 0 do return nil, false
152		val = ((val << 5) | u32(i)) & 0xffff
153		bits += 5
154		if bits >= 8 {append(&out, u8((val >> (bits - 8)) & 255)); bits -= 8}
155	}
156	return out[:n], true
157}
158
159Recovery :: struct {
160	salt:    string `json:"salt"`,
161	iv:      string `json:"iv"`,
162	ct:      string `json:"ct"`,
163	created: i64 `json:"created"`,
164}
165
166recovery_unwrap :: proc(phrase: string, rec: Recovery) -> ([]u8, string) {
167	b, ok := b32dec(phrase, 20)
168	if !ok do return nil, "a recovery key is 32 letters and digits"
169	k, ok2 := s_open(s_hkdf(b, s_unb64(rec.salt), "rc-storage recovery v1"), s_unb64(rec.iv), s_unb64(rec.ct))
170	if !ok2 do return nil, "the recovery key does not open it"
171	return k, ""
172}
173
174// DEVICE APPROVAL
175new_code :: proc() -> string {
176	r := random_bytes(12)
177	b := strings.builder_make()
178	for x, i in r {
179		if i > 0 && i % 4 == 0 do strings.write_byte(&b, '-')
180		strings.write_byte(&b, B32[x & 31])
181	}
182	return strings.to_string(b)
183}
184approval_key :: proc(code: string) -> []u8 {return s_hkdf(bytes_of(b32norm(code)), nil, "rc-storage approve v1")}
185req_msg :: proc(id, pub: string) -> []u8 {return join(bytes_of("req\x00"), bytes_of(id), {0}, s_unb64(pub))}
186ok_msg :: proc(id, pub: string, w: Wrap, mkid: string) -> []u8 {
187	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))
188}
189request_tag :: proc(code, id, pub: string) -> string {return b64(s_hmac(approval_key(code), req_msg(id, pub)))}
190check_request :: proc(code: string, q: json.Value) -> bool {
191	return const_eq(request_tag(code, jstr(q, "id"), jstr(q, "pub")), jstr(q, "tag"))
192}
193approval_tag :: proc(code, id, pub: string, w: Wrap, mkid: string) -> string {return b64(s_hmac(approval_key(code), ok_msg(id, pub, w, mkid)))}
194
195// THE ROOT
196Root_Entry :: struct {
197	id:  string `json:"id"`,
198	pub: string `json:"pub,omitempty"`, // a root wrap key (storage's keyring)
199	eph: string `json:"eph,omitempty"`, // a wrap for the root (an app's keyring)
200	iv:  string `json:"iv"`,
201	ct:  string `json:"ct"`,
202}
203
204root_id :: proc(pub_b64: string) -> string {return hex(sha256(join(bytes_of("rc-root id v1"), s_unb64(pub_b64))))[:32]}
205rwk_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))}
206open_root_wrap_key :: proc(root: []u8, e: Root_Entry) -> (Ec, string) {
207	if e.id != root_id(e.pub) do return {}, "root key id mismatch"
208	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))
209	if !ok do return {}, "the root key does not open"
210	k, kok := ec_from_d(d)
211	if !kok || !eq_bytes(k.pub, s_unb64(e.pub)) do return {}, "root key does not match its public half"
212	return k, ""
213}
214app_aad :: proc(app, mkid: string) -> []u8 {return join(bytes_of("rc-root app v1\x00"), bytes_of(app), {0}, unhex(mkid))}
215unwrap_from_root :: proc(rwk: Ec, root_pub_b64, app, mkid: string, w: Root_Entry) -> ([]u8, string) {
216	eph := s_unb64(w.eph)
217	z, ok := ec_dh(rwk, eph)
218	if !ok do return nil, "ECDH failed"
219	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))
220	if !ok2 do return nil, "the app's key does not open under the root"
221	if mk_id(mk) != mkid do return nil, "app key id mismatch"
222	return mk, ""
223}
224
225// KEYRING v2: as storage holds it, field for field.
226Kr_Device :: struct {
227	id:      string `json:"id"`,
228	name:    string `json:"name"`,
229	pub:     string `json:"pub"`,
230	wrap:    Wrap `json:"wrap"`,
231	ok:      string `json:"ok,omitempty"`,
232	created: i64 `json:"created"`,
233	via:     string `json:"via"`,
234}
235Kr_Older :: struct {
236	mk_id: string `json:"mk_id"`,
237	iv:    string `json:"iv"`,
238	ct:    string `json:"ct"`,
239}
240Keyring :: struct {
241	v:        int `json:"v"`,
242	mk_id:    string `json:"mk_id"`,
243	epoch:    i64 `json:"epoch"`,
244	root:     Root_Entry `json:"root"`,
245	recovery: ^Recovery `json:"recovery,omitempty"`, // storage's own keyring only
246	devices:  []Kr_Device `json:"devices"`,
247	older:    []Kr_Older `json:"older"`,
248	mac:      string `json:"mac"`,
249}
250
251keyring_msg :: proc(kr: Keyring, user, app: string) -> []u8 {
252	b := strings.builder_make()
253	r := kr.root
254	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)
255	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)}
256	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)))
257	for o in kr.older do fmt.sbprintf(&b, "older %s %s %s\n", o.mk_id, o.iv, o.ct)
258	return transmute([]u8)strings.to_string(b)
259}
260keyring_mac :: proc(k: []u8, kr: Keyring, user, app: string) -> string {
261	return b64(s_hmac(s_hkdf(k, nil, "rc-keyring mac v1"), keyring_msg(kr, user, app)))
262}
263check_keyring :: proc(k: []u8, kr: Keyring, user, app: string) -> bool {
264	return kr.mac != "" && const_eq(keyring_mac(k, kr, user, app), kr.mac)
265}
266open_older :: proc(k: []u8, e: Kr_Older) -> bool {
267	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)))
268	return ok && mk_id(old) == e.mk_id
269}
270
271// A device the robot plays: its key, and what it remembers of the keyring.
272Dev :: struct {
273	id:    string,
274	priv:  Ec,
275	pub:   string,
276	pin:   string, // the mk_id it trusts, or ""
277	epoch: i64,
278	code:  string, // a pending approval code, or ""
279}
280
281// A device's view (rc-seal.js's trust()): the key its entry opens, or why it is refused.
282trust_keyring :: proc(kr: Keyring, dev: Dev, user, app: string) -> ([]u8, string) {
283	if kr.v != 2 do return nil, "not a v2 keyring"
284	mine: ^Kr_Device
285	for &d in kr.devices do if d.id == dev.id do mine = &d
286	if mine == nil do return nil, "this device is not in the keyring"
287	if mine.pub != dev.pub do return nil, "this device's entry carries another key"
288	k, ok := unwrap_for_device(dev.priv, dev.pub, mine.wrap)
289	if !ok do return nil, "this device's entry does not open"
290	if mk_id(k) != kr.mk_id do return nil, "this device's entry is not the keyring's key"
291	if dev.pin == kr.mk_id {
292	} else if dev.pin != "" {
293		held := false
294		for o in kr.older do if o.mk_id == dev.pin && open_older(k, o) do held = true
295		if !held do return nil, "the keyring's key changed, and the new one does not hold the old"
296	} else if dev.code == "" || mine.ok == "" || !const_eq(approval_tag(dev.code, dev.id, dev.pub, mine.wrap, kr.mk_id), mine.ok) {
297		return nil, "this device's entry was not vouched for under its code"
298	}
299	if !check_keyring(k, kr, user, app) do return nil, "the keyring was changed by someone without its key"
300	if dev.epoch > kr.epoch do return nil, "the keyring is older than one this device has seen"
301	return k, ""
302}
303
304// ENVELOPE (not FRAGMENTED MEDIA: the zoo seals words)
305ENV_TYPE :: "application/x-rc-encrypted"
306
307envelope_seal :: proc(mk, pt: []u8, name, type: string, log2 := 12) -> []u8 {
308	cs := 1 << uint(log2)
309	size := len(pt)
310	n := max(1, (size + cs - 1) / cs)
311	fk := random_bytes(32)
312	P := random_bytes(8)
313	fk_iv := random_bytes(12)
314	meta := fmt.tprintf(`{{"name":%s,"type":%s,"mtime":%d}}`, jq(name), jq(type), now_ms())
315	meta_ct := s_seal(fk, join(P, {0xff, 0xff, 0xff, 0xff}), bytes_of(meta), bytes_of("rc-meta"))
316	size8 := make([]u8, 8)
317	for i in 0 ..< 8 do size8[i] = u8(u64(size) >> uint(56 - 8 * i))
318	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)
319	hh := sha256(head)
320	out := make([dynamic]u8)
321	append(&out, ..head)
322	for i in 0 ..< n {
323		last: u8 = 1 if i == n - 1 else 0
324		append(&out, ..s_seal(fk, join(P, be32(u32(i))), pt[i * cs:min(size, (i + 1) * cs)], join(hh, {last})))
325	}
326	return out[:]
327}
328
329// The words and the meta, with the key `key_for` gives for the envelope's mk_id. Refuses what
330// rc-crypt.js refuses.
331envelope_open :: proc(key_for: proc(mkid: string, arg: rawptr) -> []u8, arg: rawptr, env_: []u8) -> (pt: []u8, err: string) {
332	e := env_
333	if len(e) < 104 || string(e[:4]) != "RCE1" do return nil, "not an encrypted file"
334	log2 := int(e[4])
335	if log2 < 12 || log2 > 24 || e[5] != 0 || e[6] != 0 || e[7] != 0 do return nil, "bad header"
336	size := 0
337	for i in 0 ..< 8 do size = size << 8 | int(e[8 + i])
338	mkid := hex(e[16:32])
339	k := key_for(mkid, arg)
340	if k == nil || mk_id(k) != mkid do return nil, "sealed with a different key"
341	meta_len := int(e[100]) << 24 | int(e[101]) << 16 | int(e[102]) << 8 | int(e[103])
342	if meta_len > 65536 || 104 + meta_len > len(e) do return nil, "bad header"
343	hl := 104 + meta_len
344	P := e[32:40]
345	fk, ok := s_open(k, e[40:52], e[52:100])
346	if !ok do return nil, "the file key does not open"
347	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"
348	hh := sha256(e[:hl])
349	cs := 1 << uint(log2)
350	n := max(1, (size + cs - 1) / cs)
351	out := make([dynamic]u8)
352	at := hl
353	for i in 0 ..< n {
354		l := min(cs, size - i * cs) + 16
355		if at + l > len(e) do return nil, "truncated"
356		last: u8 = 1 if i == n - 1 else 0
357		chunk, cok := s_open(fk, join(P, be32(u32(i))), e[at:at + l], join(hh, {last}))
358		if !cok do return nil, "a chunk does not open"
359		append(&out, ..chunk)
360		at += l
361	}
362	if at != len(e) do return nil, "trailing bytes"
363	return out[:], ""
364}
365
366// ---- making a keyring (once per environment, robotseal.odin) ----
367
368b32enc :: proc(bytes: []u8) -> string {
369	out := strings.builder_make()
370	bits, val: u32 = 0, 0
371	for c in bytes {
372		val = ((val << 8) | u32(c)) & 0xffff
373		bits += 8
374		for bits >= 5 {strings.write_byte(&out, B32[(val >> (bits - 5)) & 31]); bits -= 5}
375	}
376	if bits > 0 do strings.write_byte(&out, B32[(val << (5 - bits)) & 31])
377	return strings.to_string(out)
378}
379new_recovery_key :: proc() -> ([]u8, string) {
380	b := random_bytes(20)
381	s := b32enc(b)
382	parts := make([dynamic]string)
383	for i := 0; i < len(s); i += 4 do append(&parts, s[i:min(i + 4, len(s))])
384	return b, strings.join(parts[:], "-")
385}
386recovery_wrap :: proc(bytes, k: []u8) -> Recovery {
387	salt, iv := random_bytes(16), random_bytes(12)
388	return {b64(salt), b64(iv), b64(s_seal(s_hkdf(bytes, salt, "rc-storage recovery v1"), iv, k)), now()}
389}
390new_root_wrap_key :: proc(root: []u8) -> Root_Entry {
391	k := ec_new()
392	pub := b64(k.pub)
393	iv := random_bytes(12)
394	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)))}
395}
396wrap_for_root :: proc(root_id_, root_pub, app: string, app_mk: []u8) -> Root_Entry {
397	rpub := s_unb64(root_pub)
398	eph := ec_new()
399	z, _ := ec_dh(eph, rpub)
400	iv := random_bytes(12)
401	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))))}
402}

web/e27.js sha256 52a3e373919f · raw

1(async () => {
2  const box = document.getElementById("seal27");
3  if (!box) return;
4  for (let i = 0; i < 100 && !window.zooSeal; i++) await new Promise((r) => setTimeout(r, 100));
5  const seal = window.zooSeal;
6  if (!seal) { box.innerHTML = '<p class="muted">Card 26 did not start (see there).</p>'; return; }
7  let stop = null;
8  async function render(flash) {
9    if (stop) { stop(); stop = null; }
10    for (let i = 0; i < 100 && seal.status === "loading"; i++) await new Promise((r) => setTimeout(r, 100));
11    const st = seal.status;
12    if (st === "nostorage" || st === "none" || st === "unsupported") { box.innerHTML = '<p class="muted">Seal a postcard first (26).</p>'; return; }
13    if (st === "locked") {
14      let code = "…";
15      try { code = await seal.request(); } catch (e) { code = ""; }
16      box.innerHTML = '<p>This browser has never opened your postcard. On a device that has, type this code in card 27:</p>'
17        + '<p class="code" id="seal-code">' + zoo.esc(code) + '</p><p class="muted small">It works for 15 minutes. Waiting…</p>'
18        + '<p><button id="seal-recover">Use your recovery key</button> <span class="out" id="seal-rout"></span></p>'
19        + '<p class="muted small">Storage opens in a small window; your recovery key is typed there, never here.</p>';
20      document.getElementById("seal-recover").onclick = async (ev) => {
21        ev.target.disabled = true; document.getElementById("seal-rout").textContent = "in storage's window…";
22        try { await seal.useStorage(); window.zooSealRender && window.zooSealRender("Let in with your recovery key, in storage's window."); render(); }
23        catch (e) { ev.target.disabled = false; document.getElementById("seal-rout").textContent = e.message; }
24      };
25      stop = seal.poll((s) => { if (s === "ready") { window.zooSealRender && window.zooSealRender("Let in by a device that had the key."); render(); } });
26      return;
27    }
28    const devs = seal.devices.map((d) => '<li><span>' + zoo.esc(d.name) + (d.mine ? ' <span class="tag ok">this browser</span>' : '') + ' <small class="muted">' + zoo.esc(d.via) + '</small></span></li>').join("");
29    box.innerHTML = (flash ? '<p class="tag ok">' + zoo.esc(flash) + '</p>' : '')
30      + '<p>Open this page in a private window (or on another device), sign in, and type the code it shows here:</p>'
31      + '<form id="seal-approve" class="row"><input id="seal-code-in" placeholder="XXXX-XXXX-XXXX" autocomplete="off" spellcheck="false" required><button class="primary">Let it in</button></form><p class="out" id="seal-aout"></p>'
32      + '<p class="muted small">Your devices that open the zoo\'s postcards:</p><ul class="list">' + devs + '</ul>';
33    document.getElementById("seal-approve").onsubmit = async (ev) => {
34      ev.preventDefault();
35      const out = document.getElementById("seal-aout");
36      out.textContent = "checking the code…";
37      try { const n = await seal.approve(document.getElementById("seal-code-in").value); render("Let in: " + n + "."); }
38      catch (e) { out.textContent = e.message; }
39    };
40  }
41  render();
42})();