diff --git a/bjo.lock b/bjo.lock index 2f2d759..07dfb5d 100644 --- a/bjo.lock +++ b/bjo.lock @@ -1,5 +1,5 @@ (lock (locked - (package (name (bjosodium)) (version "0.1.0") + (package (name (bjosodium)) (version "0.2.0") (source (git (url "https://rikspucko.koketteriet.se/bjoli/bjosodium"))) - (commit "911f4bcc4676ca6393f8eb43286fdddd69cf6b5665aca0770ceaf869fb73767b")))) + (commit "2be75d9b22691b44d571ef4fa8516390ca9a47a4d64a3d92b39d6f9878627b13")))) diff --git a/manifest.bjodat b/manifest.bjodat index 142b2bb..eb51818 100644 --- a/manifest.bjodat +++ b/manifest.bjodat @@ -1,12 +1,12 @@ (package (name (bjomarks)) - (version "0.1.0") + (version "0.2.1") (description "Bookmarks in an encrypted store: one file for each device, in any folder that a file syncer or WebDAV shares.") (license "MPL-2.0") (depends (package (name (bjosodium)) - (version (version-at-least "0.1.0")) + (version (version-at-least "0.2.0")) (source (git (url "https://rikspucko.koketteriet.se/bjoli/bjosodium"))))) ;; A library: there is no src/main.bjo. diff --git a/src/bookmark.bjo b/src/bookmark.bjo index 06f9867..19e6044 100644 --- a/src/bookmark.bjo +++ b/src/bookmark.bjo @@ -169,7 +169,7 @@ (when (>= i 0) (set! out i (get hex-digits (cast int (bitwise-and rest 15L)))) (go (- i 1) (shift-right rest 4)))) - (bytes->string out)) + (bytes->string/lossy out)) ;; The value of the lower-case hex digits of `bytes` from `start` to `end`. ;; `None` for any other byte. diff --git a/src/keys.bjo b/src/keys.bjo index 930e19b..a5da256 100644 --- a/src/keys.bjo +++ b/src/keys.bjo @@ -5,8 +5,8 @@ ;; bjomarks/src/keys.bjo — the module (bjomarks keys): `keys.bin`, the file ;; that holds the key of a vault, encrypted with keys made from passwords. ;; -;; - A vault has one data key (DEK): 32 random bytes that encrypt every -;; device's file. +;; - A vault has one data key (DEK): a random key of 32 bytes that encrypts +;; every device's file. ;; - `keys.bin` holds the DEK wrapped (encrypted) in one or more slots. A ;; password slot wraps it with a key (KEK) that Argon2id makes from the ;; password and the slot's salt and cost. @@ -65,6 +65,7 @@ (import (std prelude)) (import (std uuid)) (import (bjosodium core)) +(import (bjosodium raw)) (import (bjomarks binary)) (: string) @@ -83,8 +84,8 @@ ;; each with its key id, the latest first. (type (: Unlocked (Record (: vault-id Uuid) (: key-id int) - (: dek (Array byte)) - (: earlier (Vec (Tuple int (Array byte))))))) + (: dek AeadKey) + (: earlier (Vec (Tuple int AeadKey)))))) ;; The key ids of a keys file, which it shows without a password: the ;; current one, and the earlier ones, the latest first. @@ -131,14 +132,33 @@ (: int) (def max-earlier-keys 200) +;; The Argon2id cost of `cost`. Raises `ArgumentException` when it is out of +;; libsodium's range. +(: (-> KeyCost Argon2idCost)) +(defun (argon2id-cost cost) (make-argon2id-cost (.iterations cost) (.memory-kib cost))) + +;; `key`, encrypted with `kek` and `nonce`. The copy of its bytes is wiped. +(: (-> AeadKey AeadNonce AeadKey (Array byte) (Array byte))) +(defun (wrap-key kek nonce key aad) + (def plain (aead-key->bytes key)) + (try (aead-encrypt kek nonce plain #:aad aad) #:finally (wipe! plain))) + +;; The key of the decrypted bytes `plain`, which are `dek-length` long. The +;; bytes are wiped. +(: (-> (Array byte) AeadKey)) +(defun (take-key plain) + (def key (bytes->aead-key plain)) + (wipe! plain) + key) + (: (-> Cipher int)) (defun (slot-length cipher) #fl(+ slot-head-length (cipher-nonce-length cipher) dek-length (cipher-tag-length cipher))) ;; The DEK, wrapped for `password` in a new slot, as the whole of a keys ;; file with that one password slot, and a slot for each of the `#:earlier` ;; keys, wrapped with the DEK. -(: (-> Uuid int (Array byte) string (#:cost KeyCost) (#:cipher Cipher) - (#:earlier (Vec (Tuple int (Array byte)))) +(: (-> Uuid int AeadKey string (#:cost KeyCost) (#:cipher Cipher) + (#:earlier (Vec (Tuple int AeadKey))) (Array byte))) (defun (wrap-keys vault-id key-id dek password #:cost default-key-cost #:cipher (preferred-cipher) #:earlier []) @@ -159,10 +179,10 @@ (put-u32! file (+ at 10) (.memory-kib cost)) (put-bytes! file (+ at 14) salt) (put-u8! file (+ at 30) (cipher->code cipher)) - (put-bytes! file (+ at slot-head-length) nonce) + (put-bytes! file (+ at slot-head-length) (aead-nonce->bytes nonce)) (def aad (bytes-concat (get-bytes file 0 22) (get-bytes file at slot-head-length))) - (def kek (argon2id-derive-key password salt #:iterations (.iterations cost) #:memory-kib (.memory-kib cost))) - (def wrapped (try (aead-encrypt cipher kek nonce dek #:aad aad) #:finally (wipe! kek))) + (def kek (argon2id-derive-key password salt (argon2id-cost cost))) + (def wrapped (try (wrap-key kek nonce dek aad) #:finally (wipe-aead-key! kek))) (put-bytes! file (+ at slot-head-length nonce-length) wrapped) (loop (:for (Tuple i old) (enumerate kept)) (:do (def (Tuple old-id old-dek) old) @@ -173,10 +193,10 @@ (put-u8! file (+ there 5) 0) (put-u32! file (+ there 6) key-id) (put-u8! file (+ there 30) (cipher->code cipher)) - (put-bytes! file (+ there slot-head-length) old-nonce) + (put-bytes! file (+ there slot-head-length) (aead-nonce->bytes old-nonce)) (def old-aad (bytes-concat (get-bytes file 0 22) (get-bytes file there slot-head-length))) (put-bytes! file (+ there slot-head-length nonce-length) - (aead-encrypt cipher dek old-nonce old-dek #:aad old-aad)))) + (wrap-key dek old-nonce old-dek old-aad)))) file) ;; A new vault: a new vault id and a new DEK, with key id 1, and its keys @@ -184,7 +204,7 @@ (: (-> string (#:cost KeyCost) (#:cipher Cipher) (Tuple (Array byte) Unlocked))) (defun (make-keys password #:cost default-key-cost #:cipher (preferred-cipher)) (def vault-id (uuid-v4)) - (def dek (make-aead-key XChaCha20Poly1305)) + (def dek (make-aead-key)) (Tuple (wrap-keys vault-id 1 dek password #:cost cost #:cipher cipher) (Unlocked (vault-id vault-id) (key-id 1) (dek dek) (earlier [])))) @@ -192,7 +212,7 @@ ;; a new key at once do not give theirs the same id. (: (-> (Vec int) int)) (defun (new-key-id known) - (def id (get-u32 (make-aead-key XChaCha20Poly1305) 0)) + (def id (get-u32 (random-bytes 4) 0)) (if (or (<= id 1) (vec-contains? known id)) (new-key-id known) id)) ;; A new DEK for the vault of `u`, for a new password: its keys file, and @@ -202,7 +222,7 @@ (defun (new-keys u password #:cost default-key-cost #:cipher (preferred-cipher)) (def earlier (vec-append [(Tuple (.key-id u) (.dek u))] (.earlier u))) (def key-id (new-key-id (vec-map fst earlier))) - (def dek (make-aead-key XChaCha20Poly1305)) + (def dek (make-aead-key)) (def kept (vec-take earlier max-earlier-keys)) (Tuple (wrap-keys (.vault-id u) key-id dek password #:cost cost #:cipher cipher #:earlier kept) (Unlocked (vault-id (.vault-id u)) (key-id key-id) (dek dek) (earlier kept)))) @@ -229,7 +249,7 @@ (: salt (Array byte)) (: cipher Cipher) (: aad (Array byte)) - (: nonce (Array byte)) + (: nonce AeadNonce) (: wrapped (Array byte))))) ;; The slot at `at`, and where the next one starts, or why it is not a slot. @@ -251,7 +271,7 @@ (salt (get-bytes file (+ at 14) 16)) (cipher cipher) (aad (bytes-concat (get-bytes file 0 22) (get-bytes file at slot-head-length))) - (nonce (get-bytes file (+ at slot-head-length) nonce-length)) + (nonce (bytes->aead-nonce cipher (get-bytes file (+ at slot-head-length) nonce-length))) (wrapped (get-bytes file (+ at slot-head-length nonce-length) (+ dek-length (cipher-tag-length cipher))))) (+ at length)))))) @@ -275,13 +295,13 @@ (Err (BadKeys (str "a slot asks for " (int->string (.memory-kib cost)) " KiB")))) (else (Ok cost)))) -;; The DEK of a password slot, or `None` when the password does not open it. +;; The bytes of the DEK of a password slot, or `None` when the password does +;; not open it. (: (-> Slot string KeyCost (Option (Array byte)))) (defun (open-slot slot password cost) - (def kek (argon2id-derive-key password (.salt slot) #:iterations (.iterations cost) - #:memory-kib (.memory-kib cost))) - (try (aead-decrypt (.cipher slot) kek (.nonce slot) (.wrapped slot) #:aad (.aad slot)) - #:finally (wipe! kek))) + (def kek (argon2id-derive-key password (.salt slot) (argon2id-cost cost))) + (try (aead-decrypt kek (.nonce slot) (.wrapped slot) #:aad (.aad slot)) + #:finally (wipe-aead-key! kek))) ;; The vault id, the key id and the DEK, from the first password slot that ;; `password` opens. @@ -295,16 +315,16 @@ (def (Ok slots) (read-slots file count) :propagate) (def passwords (vec-filter (fun (s) (and (= (.kind s) 1) (= (.kdf s) 1))) slots)) ;; The earlier keys that the DEK `key-id` wraps, or why one does not open. - (: (-> int (Array byte) (Result KeysError (Vec (Tuple int (Array byte)))))) + (: (-> int AeadKey (Result KeysError (Vec (Tuple int AeadKey))))) (defun (earlier-of key-id dek) (let go ((i 0) (out [])) (if (= i (vec-length slots)) (Ok out) (let ((s (vec-ref slots i))) (if (and (= (.kind s) 2) (= (get-u32 (.aad s) 28) key-id)) - (match (aead-decrypt (.cipher s) dek (.nonce s) (.wrapped s) #:aad (.aad s)) + (match (aead-decrypt dek (.nonce s) (.wrapped s) #:aad (.aad s)) ((Some old) #:when (= (array-length old) dek-length) - (go (+ i 1) (vec-add out (Tuple (.slot-key-id s) old)))) + (go (+ i 1) (vec-add out (Tuple (.slot-key-id s) (take-key old))))) (_ (Err (BadKeys (str "the earlier key " (int->string (.slot-key-id s)) " does not open"))))) (go (+ i 1) out)))))) (cond @@ -320,12 +340,13 @@ ((Err why) (Err why)) ((Ok cost) (match (open-slot slot password cost) - ((Some dek) - (if (= (array-length dek) dek-length) - (match (earlier-of (.slot-key-id slot) dek) - ((Ok earlier) - (Ok (Unlocked (vault-id vault-id) (key-id (.slot-key-id slot)) (dek dek) (earlier earlier)))) - ((Err why) (Err why))) + ((Some plain) + (if (= (array-length plain) dek-length) + (let ((dek (take-key plain))) + (match (earlier-of (.slot-key-id slot) dek) + ((Ok earlier) + (Ok (Unlocked (vault-id vault-id) (key-id (.slot-key-id slot)) (dek dek) (earlier earlier)))) + ((Err why) (Err why)))) (Err (BadKeys "the key in a slot has the wrong length")))) (None (go (+ i 1)))))))))))) diff --git a/src/store.bjo b/src/store.bjo index 43a5781..a106b17 100644 --- a/src/store.bjo +++ b/src/store.bjo @@ -72,6 +72,7 @@ (import (std uuid)) (import (text json)) (import (bjosodium core)) +(import (bjosodium raw)) (import (bjomarks binary)) (import (bjomarks bookmark)) (import (bjomarks keys)) @@ -268,11 +269,12 @@ (else (Err (str "unknown compression " (int->string compression)))))))) ;; A device file with a new random nonce. -(: (-> FileHead (Array byte) DeviceDoc (Array byte))) +(: (-> FileHead AeadKey DeviceDoc (Array byte))) (defun (encode-device-file head dek doc) (def cipher (.head-cipher head)) (def nonce (make-aead-nonce cipher)) - (def header (: (make-array (+ head-length (array-length nonce))) (Array byte))) + (def nonce-bytes (aead-nonce->bytes nonce)) + (def header (: (make-array (+ head-length (array-length nonce-bytes))) (Array byte))) (put-bytes! header 0 device-magic) (put-u16! header 4 device-format) (put-bytes! header 6 (uuid->bytes (.head-vault head))) @@ -280,14 +282,14 @@ (put-u64! header 38 (.head-revision head)) (put-u32! header 46 (.head-key-id head)) (put-u8! header 50 (cipher->code cipher)) - (put-bytes! header head-length nonce) + (put-bytes! header head-length nonce-bytes) (def contents (pack (string->bytes (device-doc->string doc)))) - (def sealed (aead-encrypt cipher dek nonce contents #:aad header)) + (def sealed (aead-encrypt dek nonce contents #:aad header)) (wipe! contents) (bytes-concat header sealed)) ;; The DEK of the key id `id`, of those `known`. -(: (-> (Vec (Tuple int (Array byte))) int (Option (Array byte)))) +(: (-> (Vec (Tuple int AeadKey)) int (Option AeadKey))) (defun (key-of known id) (let go ((i 0)) (cond ((= i (vec-length known)) None) @@ -298,7 +300,7 @@ ;; - The file must be of the vault `vault-id`, and encrypted with one of the ;; DEKs `known`, each with its key id. ;; - The document must name the device that the header names. -(: (-> (Array byte) Uuid (Vec (Tuple int (Array byte))) (Result string (Tuple FileHead DeviceDoc)))) +(: (-> (Array byte) Uuid (Vec (Tuple int AeadKey)) (Result string (Tuple FileHead DeviceDoc)))) (defun (decode-device-file file vault-id known) (def n (array-length file)) (def version (if (>= n 6) (get-u16 file 4) 0)) @@ -322,12 +324,13 @@ (:def nonce-length (cipher-nonce-length cipher)) ((< n (+ head-length nonce-length (cipher-tag-length cipher))) (Err "too short for a device file")) (:def header (get-bytes file 0 (+ head-length nonce-length))) - (:def nonce (get-bytes file head-length nonce-length)) + (:def nonce (bytes->aead-nonce cipher (get-bytes file head-length nonce-length))) (:def sealed (get-bytes file (+ head-length nonce-length) (- n (+ head-length nonce-length)))) - (:def (Some contents) (aead-decrypt cipher dek nonce sealed #:aad header) + (:def (Some contents) (aead-decrypt dek nonce sealed #:aad header) :leave-with (Err "it does not decrypt: it was changed, or it was encrypted with another key")) (:def (Ok json) (unpack contents) :propagate) - (:def (Ok doc) (parse-device-doc (bytes->string json)) :propagate) + (:def (Ok text) (bytes->string json) :leave-with (Err "the document in it is not UTF-8")) + (:def (Ok doc) (parse-device-doc text) :propagate) ((not (= (.device doc) device)) (Err (str "the header names the device " (uuid->string device) ", and the document names " (uuid->string (.device doc))))) @@ -415,8 +418,8 @@ (: id Uuid) (: device Uuid) (: key-id int) - (: dek (Array byte)) - (: known (Vec (Tuple int (Array byte)))) + (: dek AeadKey) + (: known (Vec (Tuple int AeadKey))) (: cipher Cipher) (: entries (Map string Entry)) (: seen (Map string long)) @@ -449,7 +452,7 @@ ((BadKeys why) (BadFile (str keys-file-name ": " why))))) ;; The keys that `u` gives: the current one first, then the earlier ones. -(: (-> Unlocked (Vec (Tuple int (Array byte))))) +(: (-> Unlocked (Vec (Tuple int AeadKey)))) (defun (keys-of u) (vec-append [(Tuple (.key-id u) (.dek u))] (.earlier u))) (: (-> Storage Unlocked string Uuid Vault)) @@ -574,7 +577,7 @@ (None (Err e)))))))) ;; `u` with the keys of `more` that it does not have, as earlier keys. -(: (-> Unlocked (Vec (Tuple int (Array byte))) Unlocked)) +(: (-> Unlocked (Vec (Tuple int AeadKey)) Unlocked)) (defun (with-keys u more) (def ids (vec-map fst (keys-of u))) (record-set u (earlier (vec-append (.earlier u) (vec-filter (fun (k) (not (vec-contains? ids (fst k)))) more))))) @@ -699,7 +702,7 @@ ;; Sets the DEKs to zeros. Do not use the vault after this. (: (-> Vault void)) (defun (vault-close v) - (loop (:for k (.known v)) (:do (wipe! (snd k))))) + (loop (:for k (.known v)) (:do (wipe-aead-key! (snd k))))) ;; --------------------------------------------------------------------------- ;; Changes diff --git a/src/title.bjo b/src/title.bjo index e504ada..9d80d98 100644 --- a/src/title.bjo +++ b/src/title.bjo @@ -87,7 +87,7 @@ (let go ((i start)) (if (and (< i end) (name-byte? (cast int (array-ref bytes i)))) (go (+ i 1)) - (bytes->string (ro-span->array (array->ro-span bytes #:from start #:to i)))))) + (bytes->string/lossy (ro-span->array (array->ro-span bytes #:from start #:to i)))))) ;; The charset that a `Content-Type` value names, if it names one. (: (-> string (Option string))) @@ -118,9 +118,9 @@ (def encoding (match charset ((Some name) (match (encoding-named name) ((Some e) e) (None utf-8))) (None utf-8))) - (match (try (bytes->string slice #:encoding encoding) #:catch (System.Exception)) + (match (bytes->string slice #:encoding encoding) ((Ok text) text) - ((Err _) (bytes->string slice #:encoding windows-1252)))) + ((Err _) (bytes->string/lossy slice #:encoding windows-1252)))) ;; The title of the page in the first `n` bytes of `bytes`, as ;; `clean-title` makes it. `None` when there is no whole `` element, diff --git a/tests/keys.bjo b/tests/keys.bjo index 9d28e6b..3c41040 100644 --- a/tests/keys.bjo +++ b/tests/keys.bjo @@ -28,6 +28,9 @@ (: (-> (Array byte) (Array byte))) (defun (copy-of a) (get-bytes a 0 (array-length a))) +(: (-> AeadKey AeadKey bool)) +(defun (same-key? a b) (bytes=? (aead-key->bytes a) (aead-key->bytes b))) + ;; A copy of `a` with bit 0 of byte `at` changed. (: (-> (Array byte) int (Array byte))) (defun (flipped a at) @@ -52,8 +55,8 @@ (def (Ok opened) (unlock-keys file "hunter2") :leave-with (check-fail "it did not open")) (check (= (.vault-id opened) (.vault-id made))) (check (= (.key-id opened) 1)) - (check (bytes=? (.dek opened) (.dek made))) - (check (= (array-length (.dek made)) 32)) + (check (same-key? (.dek opened) (.dek made))) + (check (= (array-length (aead-key->bytes (.dek made))) 32)) (check (= (keys-vault-id file) (Ok (.vault-id made))))) (deftest "each cipher wraps the key" @@ -75,14 +78,14 @@ (def (Tuple _f1 a) (make-keys "pw" #:cost cheap)) (def (Tuple _f2 b) (make-keys "pw" #:cost cheap)) (check (not (= (.vault-id a) (.vault-id b)))) - (check (not (bytes=? (.dek a) (.dek b))))) + (check (not (same-key? (.dek a) (.dek b))))) (deftest "a new password keeps the vault and its key" (def (Tuple old made) (make-keys "old password" #:cost cheap)) (def new (wrap-keys (.vault-id made) (.key-id made) (.dek made) "new password" #:cost cheap)) (check (= (outcome (unlock-keys new "old password")) "WrongPassword")) (def (Ok opened) (unlock-keys new "new password") :leave-with (check-fail "it did not open")) - (check (bytes=? (.dek opened) (.dek made))) + (check (same-key? (.dek opened) (.dek made))) (check (= (.vault-id opened) (.vault-id made))) (check (= (outcome (unlock-keys old "old password")) "Ok"))) @@ -135,13 +138,13 @@ (def (Tuple new rotated) (new-keys made "new password" #:cost cheap)) (check (= (.vault-id rotated) (.vault-id made))) (check (not (= (.key-id rotated) (.key-id made)))) - (check (not (bytes=? (.dek rotated) (.dek made)))) + (check (not (same-key? (.dek rotated) (.dek made)))) ;; The new file opens with the new password, and gives the earlier key. (def (Ok opened) (unlock-keys new "new password") :leave-with (check-fail "it did not open")) (check (= (.key-id opened) (.key-id rotated))) - (check (bytes=? (.dek opened) (.dek rotated))) + (check (same-key? (.dek opened) (.dek rotated))) (check (= (vec-map fst (.earlier opened)) [1])) - (check (bytes=? (snd (vec-ref (.earlier opened) 0)) (.dek made))) + (check (same-key? (snd (vec-ref (.earlier opened) 0)) (.dek made))) (check (= (outcome (unlock-keys new "old password")) "WrongPassword")) ;; The old file and the old password give the old key only. (def (Ok was) (unlock-keys old "old password") :leave-with (check-fail "the old file did not open")) diff --git a/tests/store.bjo b/tests/store.bjo index 7bc26ec..8006b29 100644 --- a/tests/store.bjo +++ b/tests/store.bjo @@ -543,7 +543,7 @@ (def a0 (vault-save (fst (add-bookmark (create f (.one f)) "https://example.org/a" [])))) (def mine (own-keys f (.one f))) ;; The same vault id, another key, and another password. - (set-shared-keys! f (wrap-keys (vault-id a0) 7 (make-aead-key XChaCha20Poly1305) "not yours" #:cost cheap)) + (set-shared-keys! f (wrap-keys (vault-id a0) 7 (make-aead-key) "not yours" #:cost cheap)) (def (Tuple a1 report) (sync (opened (reopen f (.one f) "hunter2")))) (check (told? report "holds none of this device's keys")) (check (= (urls a1) ["https://example.org/a"])) diff --git a/tests/title.bjo b/tests/title.bjo index c3bc515..d709d24 100644 --- a/tests/title.bjo +++ b/tests/title.bjo @@ -134,7 +134,7 @@ (if (string-contains? seen "\r\n\r\n") (path-of seen) (match (read-some in) - ((Some bs) (go (str seen (bytes->string bs)))) + ((Some bs) (go (str seen (bytes->string/lossy bs)))) (None (path-of seen)))))) ;; Waits `ms`, or less when the server stops. diff --git a/tests/wayback.bjo b/tests/wayback.bjo index 050086a..b404622 100644 --- a/tests/wayback.bjo +++ b/tests/wayback.bjo @@ -63,7 +63,7 @@ (if (string-contains? seen "\r\n\r\n") (match (string-split-once seen "\r\n") ((Some (Tuple l _)) l) (None seen)) (match (read-some in) - ((Some bs) (go (str seen (bytes->string bs)))) + ((Some bs) (go (str seen (bytes->string/lossy bs)))) (None seen))))) ;; One connection: one request, one answer. The wait ends early when the