;; This Source Code Form is subject to the terms of the Mozilla Public ;; License, v. 2.0. If a copy of the MPL was not distributed with this ;; file, You can obtain one at http://mozilla.org/MPL/2.0/. ;; bjosodium/src/impl.bjo — the module (bjosodium impl): the implementation ;; of (bjosodium core) and (bjosodium raw). Import those, not this module. ;; ;; - Keys and nonces are opaque types, `AeadKey` and `AeadNonce`, so that one ;; cannot be given where the other is wanted. Data, associated data and ;; salts are (Array byte). ;; - A password is a string. It is normalized to Unicode NFC, then used as ;; its UTF-8 bytes. ;; - Encryption is AEAD: decryption returns `None` when the tag does not ;; verify. Then the key, the nonce, the associated data or the bytes are ;; not the ones that were used to encrypt. ;; - A wrong length of a key, a nonce or a salt, and a cost out of range, ;; raise `ArgumentException`. These are errors in the program, not in the ;; data. ;; - The Argon2id functions take a core for tens to hundreds of milliseconds. ;; In a bjoroutine they run on a thread of their own, so the fiber pool is ;; not blocked. (export ;; Ciphers. Transparent: Aegis256, XChaCha20Poly1305. Cipher cipher-nonce-length cipher-tag-length aegis256-accelerated? preferred-cipher ;; Keys AeadKey aead-key-length make-aead-key bytes->aead-key aead-key->bytes wipe-aead-key! ;; Sealing: a random nonce in front of the result aead-seal aead-unseal ;; Nonces and encryption with them, for (bjosodium raw) AeadNonce make-aead-nonce bytes->aead-nonce aead-nonce->bytes aead-nonce-cipher aead-encrypt aead-decrypt ;; Argon2id Argon2idCost make-argon2id-cost argon2id-cost-iterations argon2id-cost-memory-kib argon2id-interactive argon2id-moderate argon2id-sensitive argon2id-derive-key argon2id-hash argon2id-verify argon2id-needs-rehash? make-argon2id-salt argon2id-salt-length ;; Random bytes and memory random-bytes wipe!) (import (std prelude)) (import (only (std unicode normalize) string-nfc)) (type (: Cipher (Union Aegis256 XChaCha20Poly1305))) (import/class (ArgumentException (: System.ArgumentException (-> string ArgumentException))) (Algorithm (: LibSodium.PasswordHashArgonAlgorithm))) ;; LibSodium.Net's AEAD methods take the output, the input, the key, the tag, ;; the associated data and the nonce, in that order. A tag span makes the ;; call detached: the tag goes into that span. Each method returns the part ;; of the output it wrote, which this module does not need. ;; ;; An empty span for the tag or the nonce is not the same as no argument, so ;; every call gives all six. (import/extern (clr-aegis-encrypt (: LibSodium.Aegis256.Encrypt (-> (Span byte) (RoSpan byte) (RoSpan byte) (Span byte) (RoSpan byte) (RoSpan byte) (Span byte)))) ;; Raises `LibSodiumException` when the tag does not verify. (clr-aegis-decrypt (: LibSodium.Aegis256.Decrypt (-> (Span byte) (RoSpan byte) (RoSpan byte) (RoSpan byte) (RoSpan byte) (RoSpan byte) (Span byte)))) (clr-xchacha-encrypt (: LibSodium.XChaCha20Poly1305.Encrypt (-> (Span byte) (RoSpan byte) (RoSpan byte) (Span byte) (RoSpan byte) (RoSpan byte) (Span byte)))) ;; Raises `LibSodiumException` when the tag does not verify. (clr-xchacha-decrypt (: LibSodium.XChaCha20Poly1305.Decrypt (-> (Span byte) (RoSpan byte) (RoSpan byte) (RoSpan byte) (RoSpan byte) (RoSpan byte) (Span byte)))) ;; libsodium's randombytes_buf: the system's random source. (clr-random-fill (: LibSodium.RandomGenerator.Fill (-> (Span byte) void))) ;; sodium_memzero. (clr-mem-zero (: LibSodium.SecureMemory.MemZero (-> (Array byte) void))) ;; The key, the password, the salt, the iterations, the memory in bytes, ;; and the algorithm. (clr-argon2-derive (: LibSodium.CryptoPasswordHashArgon.DeriveKey (-> (Span byte) (RoSpan byte) (RoSpan byte) int int Algorithm void))) ;; The password, the iterations and the memory in bytes. Argon2id, with a ;; random salt. (clr-argon2-hash (: LibSodium.CryptoPasswordHashArgon.HashPassword (-> (RoSpan byte) int int string))) (clr-argon2-verify (: LibSodium.CryptoPasswordHashArgon.VerifyPassword (-> string (RoSpan byte) bool))) (clr-arm-aes? (: System.Runtime.Intrinsics.Arm.Aes.IsSupported #:get)) (clr-x86-aes? (: System.Runtime.Intrinsics.X86.Aes.IsSupported #:get)) (clr-x86-avx? (: System.Runtime.Intrinsics.X86.Avx.IsSupported #:get))) (: (-> string %a)) (defun (refuse message) (raise (cast Exception (ArgumentException. message)))) (: (-> (Array byte) (Array byte))) (defun (copy-of bytes) (ro-span->array (array->ro-span bytes))) ;; --------------------------------------------------------------------------- ;; Ciphers ;; --------------------------------------------------------------------------- ;; In bytes. (: (-> Cipher int)) (defun (cipher-nonce-length cipher) (match cipher (Aegis256 32) (XChaCha20Poly1305 24))) ;; In bytes. The ciphertext is this much longer than the plaintext. (: (-> Cipher int)) (defun (cipher-tag-length cipher) (match cipher (Aegis256 32) (XChaCha20Poly1305 16))) ;; libsodium uses AES instructions for AEGIS-256 when the CPU has them: the ;; ARMv8 AES instructions on 64-bit ARM, or AES-NI and AVX on x86. Without ;; them it uses AES in software, which is slower than XChaCha20-Poly1305. ;; This is the same test, as .NET reports the CPU. (: (-> bool)) (defun (aegis256-accelerated?) (or clr-arm-aes? (and clr-x86-aes? clr-x86-avx?))) ;; Aegis256 when `aegis256-accelerated?`, else XChaCha20Poly1305. Both are ;; safe; this is the faster one on this CPU. (: (-> Cipher)) (defun (preferred-cipher) (if (aegis256-accelerated?) Aegis256 XChaCha20Poly1305)) (: (-> Cipher string)) (defun (cipher-label cipher) (match cipher (Aegis256 "AEGIS-256") (XChaCha20Poly1305 "XChaCha20-Poly1305"))) ;; --------------------------------------------------------------------------- ;; Random bytes and memory ;; --------------------------------------------------------------------------- ;; `n` bytes from the system's random source. (: (-> int (Array byte))) (defun (random-bytes n) (when (< n 0) (refuse (str "The number of random bytes must be at least 0, not " (int->string n) "."))) (def bytes (: (make-array n) (Array byte))) (clr-random-fill (array->span bytes)) bytes) ;; Sets every byte of `bytes` to 0, with sodium_memzero, which the compiler ;; does not remove. The garbage collector can have moved the array before, ;; and it does not clear the old copy, so this makes copies fewer but does ;; not remove all of them. (: (-> (Array byte) void)) (defun (wipe! bytes) (clr-mem-zero bytes)) ;; --------------------------------------------------------------------------- ;; Keys ;; --------------------------------------------------------------------------- ;; A key of either cipher: 32 bytes. Opaque, and printed as #, so ;; that its bytes do not get into a log. (type (: AeadKey #:opaque (Record (: key-bytes (Array byte))))) ;; In bytes, for both ciphers. (: int) (def aead-key-length 32) ;; A new random key, from the system's random source. (: (-> AeadKey)) (defun (make-aead-key) (AeadKey (key-bytes (random-bytes aead-key-length)))) ;; A key from a copy of `bytes`, as `aead-key->bytes` gave them. Raises ;; `ArgumentException` when `bytes` is not `aead-key-length` bytes. (: (-> (Array byte) AeadKey)) (defun (bytes->aead-key bytes) (def n (array-length bytes)) (when (not (= n aead-key-length)) (refuse (str "A key must be " (int->string aead-key-length) " bytes, not " (int->string n) "."))) (AeadKey (key-bytes (copy-of bytes)))) ;; A copy of the bytes of `key`, to encrypt it with another key or to store ;; it. Wipe the copy with `wipe!` when it is no longer needed. (: (-> AeadKey (Array byte))) (defun (aead-key->bytes key) (copy-of (record-ref key key-bytes))) ;; Sets the bytes of `key` to 0. The key must not be used after this: it ;; would encrypt with a key of zeros. (: (-> AeadKey void)) (defun (wipe-aead-key! key) (wipe! (record-ref key key-bytes))) ;; --------------------------------------------------------------------------- ;; Nonces ;; --------------------------------------------------------------------------- ;; A nonce of one cipher. Opaque. It knows its cipher, so `aead-encrypt` ;; and `aead-decrypt` take no cipher. (type (: AeadNonce #:opaque (Record (: nonce-cipher Cipher) (: nonce-bytes (Array byte))))) ;; A new random nonce for `cipher`, from the system's random source. (: (-> Cipher AeadNonce)) (defun (make-aead-nonce cipher) (AeadNonce (nonce-cipher cipher) (nonce-bytes (random-bytes (cipher-nonce-length cipher))))) ;; A nonce of `cipher` from a copy of `bytes`, as `aead-nonce->bytes` gave ;; them. Raises `ArgumentException` when `bytes` is not the cipher's nonce ;; length. (: (-> Cipher (Array byte) AeadNonce)) (defun (bytes->aead-nonce cipher bytes) (def n (array-length bytes)) (def wanted (cipher-nonce-length cipher)) (when (not (= n wanted)) (refuse (str "The nonce of " (cipher-label cipher) " must be " (int->string wanted) " bytes, not " (int->string n) "."))) (AeadNonce (nonce-cipher cipher) (nonce-bytes (copy-of bytes)))) ;; A copy of the bytes of `nonce`, to store beside the ciphertext. (: (-> AeadNonce (Array byte))) (defun (aead-nonce->bytes nonce) (copy-of (record-ref nonce nonce-bytes))) (: (-> AeadNonce Cipher)) (defun (aead-nonce-cipher nonce) (record-ref nonce nonce-cipher)) ;; --------------------------------------------------------------------------- ;; Encryption ;; --------------------------------------------------------------------------- (: (Array byte)) (def no-aad (make-array 0)) ;; Writes the ciphertext of `plaintext` into `out`, then the tag. `out` is ;; exactly as long as the two. (: (-> Cipher (RoSpan byte) (RoSpan byte) (RoSpan byte) (RoSpan byte) (Span byte) void)) (defun (encrypt-into! cipher key nonce aad plaintext out) (def n (ro-span-length plaintext)) (def text (span-slice out #:to n)) (def tag (span-slice out #:from n)) (ignore (match cipher (Aegis256 (span-length (clr-aegis-encrypt text plaintext key tag aad nonce))) (XChaCha20Poly1305 (span-length (clr-xchacha-encrypt text plaintext key tag aad nonce)))))) ;; The plaintext of the bytes of `box` from `from`: the ciphertext, then the ;; tag. The caller checks that the tag fits. ;; Raises `LibSodiumException` when the tag does not verify. (: (-> Cipher (RoSpan byte) (RoSpan byte) (Array byte) (Array byte) int (Array byte))) (defun (decrypt-now cipher key nonce aad box from) (def n (- (array-length box) from (cipher-tag-length cipher))) (def out (: (make-array n) (Array byte))) (def text (array->ro-span box #:from from #:to (+ from n))) (def tag (array->ro-span box #:from (+ from n))) (def a (array->ro-span aad)) (ignore (match cipher (Aegis256 (span-length (clr-aegis-decrypt (array->span out) text key tag a nonce))) (XChaCha20Poly1305 (span-length (clr-xchacha-decrypt (array->span out) text key tag a nonce))))) out) ;; `decrypt-now`, with `None` when the tag does not verify. (: (-> Cipher (RoSpan byte) (RoSpan byte) (Array byte) (Array byte) int (Option (Array byte)))) (defun (decrypt-checked cipher key nonce aad box from) (match (try (decrypt-now cipher key nonce aad box from) #:catch (LibSodium.LibSodiumException)) ((Ok plaintext) (Some plaintext)) ((Err _) None))) (: (-> AeadKey (RoSpan byte))) (defun (key-span key) (array->ro-span (record-ref key key-bytes))) ;; The ciphertext and then the tag: `cipher-tag-length` bytes longer than ;; `plaintext`. The nonce is not in the result; store it beside it. Never ;; encrypt two messages with the same key and nonce. (: (-> AeadKey AeadNonce (Array byte) (#:aad (Array byte)) (Array byte))) (defun (aead-encrypt key nonce plaintext #:aad no-aad) (def cipher (record-ref nonce nonce-cipher)) (def out (: (make-array (+ (array-length plaintext) (cipher-tag-length cipher))) (Array byte))) (encrypt-into! cipher (key-span key) (array->ro-span (record-ref nonce nonce-bytes)) (array->ro-span aad) (array->ro-span plaintext) (array->span out)) out) ;; The plaintext of a result of `aead-encrypt`. `None` when the tag does not ;; verify, and when `ciphertext` is shorter than a tag. (: (-> AeadKey AeadNonce (Array byte) (#:aad (Array byte)) (Option (Array byte)))) (defun (aead-decrypt key nonce ciphertext #:aad no-aad) (def cipher (record-ref nonce nonce-cipher)) (if (< (array-length ciphertext) (cipher-tag-length cipher)) None (decrypt-checked cipher (key-span key) (array->ro-span (record-ref nonce nonce-bytes)) aad ciphertext 0))) ;; A new random nonce, the ciphertext, and the tag, in one array: ;; `cipher-nonce-length` and `cipher-tag-length` bytes longer than ;; `plaintext`. The cipher is not in the result: store it beside it, or use ;; one cipher everywhere. (: (-> Cipher AeadKey (Array byte) (#:aad (Array byte)) (Array byte))) (defun (aead-seal cipher key plaintext #:aad no-aad) (def nonce-length (cipher-nonce-length cipher)) (def out (: (make-array (+ nonce-length (array-length plaintext) (cipher-tag-length cipher))) (Array byte))) (clr-random-fill (array->span out #:to nonce-length)) (encrypt-into! cipher (key-span key) (array->ro-span out #:to nonce-length) (array->ro-span aad) (array->ro-span plaintext) (array->span out #:from nonce-length)) out) ;; The plaintext of a result of `aead-seal` with the same cipher. `None` when ;; the tag does not verify, and when `sealed` is shorter than a nonce and a ;; tag. (: (-> Cipher AeadKey (Array byte) (#:aad (Array byte)) (Option (Array byte)))) (defun (aead-unseal cipher key sealed #:aad no-aad) (def nonce-length (cipher-nonce-length cipher)) (if (< (array-length sealed) (+ nonce-length (cipher-tag-length cipher))) None (decrypt-checked cipher (key-span key) (array->ro-span sealed #:to nonce-length) aad sealed nonce-length))) ;; --------------------------------------------------------------------------- ;; Argon2id ;; --------------------------------------------------------------------------- ;; ;; libsodium's Argon2id is version 1.3 with one lane (p=1). The cost is the ;; number of iterations (t) and the memory in KiB (m). ;; In bytes: crypto_pwhash_SALTBYTES. (: int) (def argon2id-salt-length 16) ;; A new random salt for `argon2id-derive-key`, from the system's random ;; source. A salt need not be secret: store it with the data. (: (-> (Array byte))) (defun (make-argon2id-salt) (random-bytes argon2id-salt-length)) ;; crypto_pwhash_MEMLIMIT_MIN is 8 KiB. LibSodium.Net takes the memory in ;; bytes as an int, so the most it can give is just under 2 GiB. (: int) (def min-memory-kib 8) (: int) (def max-memory-kib 2097151) ;; A cost of Argon2id: the iterations and the memory in KiB. Opaque, so that ;; each one was checked by `make-argon2id-cost`. (type (: Argon2idCost #:opaque (Record (: cost-iterations int) (: cost-memory-kib int)))) ;; Raises `ArgumentException` when `iterations` is less than 1, or ;; `memory-kib` is not from 8 to 2097151. (: (-> int int Argon2idCost)) (defun (make-argon2id-cost iterations memory-kib) (when (< iterations 1) (refuse (str "The iteration count must be at least 1, not " (int->string iterations) "."))) (when (or (< memory-kib min-memory-kib) (> memory-kib max-memory-kib)) (refuse (str "The memory must be from " (int->string min-memory-kib) " to " (int->string max-memory-kib) " KiB, not " (int->string memory-kib) "."))) (Argon2idCost (cost-iterations iterations) (cost-memory-kib memory-kib))) (: (-> Argon2idCost int)) (defun (argon2id-cost-iterations cost) (record-ref cost cost-iterations)) (: (-> Argon2idCost int)) (defun (argon2id-cost-memory-kib cost) (record-ref cost cost-memory-kib)) ;; libsodium's OPSLIMIT_INTERACTIVE and MEMLIMIT_INTERACTIVE: 2 iterations ;; over 64 MiB. (: Argon2idCost) (def argon2id-interactive (make-argon2id-cost 2 65536)) ;; libsodium's MODERATE: 3 iterations over 256 MiB. (: Argon2idCost) (def argon2id-moderate (make-argon2id-cost 3 262144)) ;; libsodium's SENSITIVE: 4 iterations over 1 GiB. (: Argon2idCost) (def argon2id-sensitive (make-argon2id-cost 4 1048576)) ;; The UTF-8 bytes of `password` in Unicode NFC. The same password typed on ;; two devices can come as different code points: "é" as one, or as "e" and ;; a combining accent. NFC makes them the same bytes. (std unicode normalize) ;; has its own tables, so every platform gives the same bytes; .NET's ;; String.Normalize would follow the ICU of each platform. (: (-> string (Array byte))) (defun (password-bytes password) (string->bytes (string-nfc password))) ;; The value of a thread's result, or its exception raised again. (: (-> (Result Exception %a) %a)) (defun (unwrap-thread r) (match r ((Ok v) v) ((Err e) (raise e)))) (: (-> string (Array byte) Argon2idCost AeadKey)) (defun (derive-now password salt cost) (when (not (= (array-length salt) argon2id-salt-length)) (refuse (str "The salt must be " (int->string argon2id-salt-length) " bytes, not " (int->string (array-length salt)) "."))) (def key (: (make-array aead-key-length) (Array byte))) (def secret (password-bytes password)) (try (clr-argon2-derive (array->span key) (array->ro-span secret) (array->ro-span salt) (argon2id-cost-iterations cost) (* (argon2id-cost-memory-kib cost) 1024) Algorithm.Argon2id13) #:finally (clr-mem-zero secret)) (AeadKey (key-bytes key))) (: (-> string Argon2idCost string)) (defun (hash-now password cost) (def secret (password-bytes password)) (try (clr-argon2-hash (array->ro-span secret) (argon2id-cost-iterations cost) (* (argon2id-cost-memory-kib cost) 1024)) #:finally (clr-mem-zero secret))) ;; What a stored hash says about its cost. (type (: StoredCost (Record (: stored-memory-kib int) (: stored-iterations int) (: stored-lanes int)))) ;; ASCII digits, as an int. `None` for an empty string, for any other ;; character, and for a number too big for an int. (: (-> string (Option int))) (defun (decimal text) (def bytes (string->bytes text)) (def n (array-length bytes)) (let go ((i 0) (v 0L)) (cond ((= i n) (if (> n 0) (Some (cast int v)) None)) (else (def b (cast int (array-ref bytes i))) (def next (+ (* v 10L) (cast long (- b 48)))) (if (and (>= b 48) (<= b 57) (<= next 2147483647L)) (go (+ i 1) next) None))))) ;; The number after `prefix` in `field`, as `m=65536`. (: (-> string string (Option int))) (defun (field-value field prefix) (if (string-starts-with? field prefix) (decimal (string-drop field (string-length prefix))) None)) ;; Raises `ArgumentException` when `stored` is not ;; `$argon2id$v=19$m=,t=,p=$$`. The salt and the hash ;; must not be empty. Their base64 is checked by libsodium. (: (-> string StoredCost)) (defun (parse-stored stored) (def fail "Not an Argon2id hash: expected $argon2id$v=19$m=,t=,p=$$.") (def parts (string-split stored "$")) ;; The leading `$` makes the first part empty. (if (not (and (= (vec-length parts) 6) (= (vec-ref parts 0) "") (= (vec-ref parts 1) "argon2id") (= (vec-ref parts 2) "v=19") (> (string-length (vec-ref parts 4)) 0) (> (string-length (vec-ref parts 5)) 0))) (refuse fail) (let ((fields (string-split (vec-ref parts 3) ","))) (if (not (= (vec-length fields) 3)) (refuse fail) (match (Tuple (field-value (vec-ref fields 0) "m=") (field-value (vec-ref fields 1) "t=") (field-value (vec-ref fields 2) "p=")) ((Tuple (Some m) (Some t) (Some p)) (StoredCost (stored-memory-kib m) (stored-iterations t) (stored-lanes p))) (_ (refuse fail))))))) (: (-> string string bool)) (defun (verify-now password stored) (ignore (parse-stored stored)) (def secret (password-bytes password)) (try (clr-argon2-verify stored (array->ro-span secret)) #:finally (clr-mem-zero secret))) ;; A key from `password` and `salt`: the same password, salt and cost give ;; the same key. Store the salt and the cost with the data, to derive the ;; key again. ;; Raises `ArgumentException` when the salt is not `argon2id-salt-length` ;; bytes. (: (-> string (Array byte) Argon2idCost AeadKey)) (defbjouble (argon2id-derive-key password salt cost) (#:sync (derive-now password salt cost)) (#:bjo (unwrap-thread (sync (spawn/thread #(derive-now password salt cost)))))) ;; A PHC string to store: `$argon2id$v=19$m=65536,t=2,p=1$$`, ;; with a random salt of 16 bytes and a hash of 32. The cost is in the ;; string. (: (-> string Argon2idCost string)) (defbjouble (argon2id-hash password cost) (#:sync (hash-now password cost)) (#:bjo (unwrap-thread (sync (spawn/thread #(hash-now password cost)))))) ;; True when `password` gives `stored`. The cost comes from `stored`. ;; Raises `ArgumentException` when `stored` is not an Argon2id PHC string. ;; This is an error in the stored data, not a wrong password. (: (-> string string bool)) (defbjouble (argon2id-verify password stored) (#:sync (verify-now password stored)) (#:bjo (unwrap-thread (sync (spawn/thread #(verify-now password stored)))))) ;; True when `stored` was made with fewer iterations or less memory than ;; `cost`. Check this after a correct `argon2id-verify`, and store a new hash ;; of the password if it is true. Raises `ArgumentException` when `stored` is ;; not an Argon2id PHC string. (: (-> string Argon2idCost bool)) (defun (argon2id-needs-rehash? stored cost) (def found (parse-stored stored)) (or (< (record-ref found stored-iterations) (argon2id-cost-iterations cost)) (< (record-ref found stored-memory-kib) (argon2id-cost-memory-kib cost))))