Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6e4da02351 | |||
| e365f21d54 | |||
| df7c149b25 | |||
| 7a7a628fa5 |
@@ -11,11 +11,13 @@ crates/custos-gen memorable password, nickname, random, PIN, strict-site, se
|
|||||||
crates/custos-keys key pairs (Ed25519, ECDSA P-256, RSA) as OpenSSH and PKCS#8 PEM
|
crates/custos-keys key pairs (Ed25519, ECDSA P-256, RSA) as OpenSSH and PKCS#8 PEM
|
||||||
crates/custos-totp TOTP / HOTP (RFC 6238 / 4226 vectors are tests), otpauth:// parsing
|
crates/custos-totp TOTP / HOTP (RFC 6238 / 4226 vectors are tests), otpauth:// parsing
|
||||||
crates/custos-qr QR payload strings (Wi-Fi escaping); rendering is the app's job
|
crates/custos-qr QR payload strings (Wi-Fi escaping); rendering is the app's job
|
||||||
|
crates/custos-seal sealed boxes (X25519 + XChaCha20-Poly1305) for factor material through a mailbox; at-rest sealing
|
||||||
crates/custos-share private share links: XChaCha20-Poly1305 blob, key in the URL fragment, optional password
|
crates/custos-share private share links: XChaCha20-Poly1305 blob, key in the URL fragment, optional password
|
||||||
crates/custos-wasm the browser build (web vault + share page): JSON `call` ABI, no wasm-bindgen; js/custos.mjs
|
crates/custos-wasm the browser build (web vault + share page): JSON `call` ABI, no wasm-bindgen; js/custos.mjs
|
||||||
docs/FORMAT.md the vault file format, version 1 (versioned; change it before the code)
|
docs/FORMAT.md the vault file format, version 1 (versioned; change it before the code)
|
||||||
docs/FACTORS.md version 2: any two factors open the vault; the machine store
|
docs/FACTORS.md version 2: any two factors open the vault; the machine store
|
||||||
docs/KEYS.md secret keys, API keys and key pairs
|
docs/KEYS.md secret keys, API keys and key pairs
|
||||||
|
docs/SEAL.md sealed boxes and the match code
|
||||||
docs/SHARE.md the share blob and link format (versioned like FORMAT.md)
|
docs/SHARE.md the share blob and link format (versioned like FORMAT.md)
|
||||||
docs/THREAT_MODEL.md what is and is not protected
|
docs/THREAT_MODEL.md what is and is not protected
|
||||||
```
|
```
|
||||||
@@ -38,7 +40,7 @@ On the dev machine set `CARGO_HOME=F:\C-Drive-Migration\future-caches\cargo` (C:
|
|||||||
- No binaries in git.
|
- No binaries in git.
|
||||||
- **No custom crypto.** Only RustCrypto / rust-random crates (`argon2`, `chacha20poly1305`, `hkdf`, `zeroize`,
|
- **No custom crypto.** Only RustCrypto / rust-random crates (`argon2`, `chacha20poly1305`, `hkdf`, `zeroize`,
|
||||||
`rand` with `SysRng`; for key pairs `ssh-key`, `p256`, `rsa` and `ed25519-dalek`, RustCrypto's Ed25519
|
`rand` with `SysRng`; for key pairs `ssh-key`, `p256`, `rsa` and `ed25519-dalek`, RustCrypto's Ed25519
|
||||||
backend). Randomness from the OS CSPRNG only.
|
backend; `x25519-dalek` for sealed boxes). Randomness from the OS CSPRNG only.
|
||||||
- **Secrets never in logs, panics, error messages, `Debug`/`Display` output or test snapshots.**
|
- **Secrets never in logs, panics, error messages, `Debug`/`Display` output or test snapshots.**
|
||||||
Secret-holding types print `[redacted]`; there is a test for each one.
|
Secret-holding types print `[redacted]`; there is a test for each one.
|
||||||
- Tests here are mandatory (it is public and holds the crypto). A format change updates `docs/FORMAT.md`
|
- Tests here are mandatory (it is public and holds the crypto). A format change updates `docs/FORMAT.md`
|
||||||
|
|||||||
Generated
+33
-7
@@ -243,7 +243,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-gen"
|
name = "custos-gen"
|
||||||
version = "0.4.0"
|
version = "0.6.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"custos-vault",
|
"custos-vault",
|
||||||
"data-encoding",
|
"data-encoding",
|
||||||
@@ -255,7 +255,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-keys"
|
name = "custos-keys"
|
||||||
version = "0.4.0"
|
version = "0.6.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"custos-vault",
|
"custos-vault",
|
||||||
"ed25519-dalek",
|
"ed25519-dalek",
|
||||||
@@ -268,11 +268,24 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-qr"
|
name = "custos-qr"
|
||||||
version = "0.4.0"
|
version = "0.6.0"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "custos-seal"
|
||||||
|
version = "0.6.0"
|
||||||
|
dependencies = [
|
||||||
|
"chacha20poly1305",
|
||||||
|
"hkdf",
|
||||||
|
"rand 0.10.3",
|
||||||
|
"sha2 0.11.1",
|
||||||
|
"thiserror",
|
||||||
|
"x25519-dalek",
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-share"
|
name = "custos-share"
|
||||||
version = "0.4.0"
|
version = "0.6.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"argon2",
|
"argon2",
|
||||||
"chacha20poly1305",
|
"chacha20poly1305",
|
||||||
@@ -289,7 +302,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-totp"
|
name = "custos-totp"
|
||||||
version = "0.4.0"
|
version = "0.6.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"custos-vault",
|
"custos-vault",
|
||||||
"data-encoding",
|
"data-encoding",
|
||||||
@@ -302,7 +315,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-vault"
|
name = "custos-vault"
|
||||||
version = "0.4.0"
|
version = "0.6.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"argon2",
|
"argon2",
|
||||||
"chacha20poly1305",
|
"chacha20poly1305",
|
||||||
@@ -318,9 +331,10 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-wasm"
|
name = "custos-wasm"
|
||||||
version = "0.4.0"
|
version = "0.6.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"custos-qr",
|
"custos-qr",
|
||||||
|
"custos-seal",
|
||||||
"custos-share",
|
"custos-share",
|
||||||
"custos-totp",
|
"custos-totp",
|
||||||
"custos-vault",
|
"custos-vault",
|
||||||
@@ -1228,6 +1242,18 @@ dependencies = [
|
|||||||
"windows-link",
|
"windows-link",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "x25519-dalek"
|
||||||
|
version = "2.0.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277"
|
||||||
|
dependencies = [
|
||||||
|
"curve25519-dalek",
|
||||||
|
"rand_core 0.6.4",
|
||||||
|
"serde",
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "zerocopy"
|
name = "zerocopy"
|
||||||
version = "0.8.63"
|
version = "0.8.63"
|
||||||
|
|||||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
|||||||
members = ["crates/*"]
|
members = ["crates/*"]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.4.0"
|
version = "0.6.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
license = "MPL-2.0"
|
license = "MPL-2.0"
|
||||||
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
|
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
|
||||||
|
|||||||
+104
-23
@@ -14,6 +14,10 @@ pub enum KeyError {
|
|||||||
Encode,
|
Encode,
|
||||||
#[error("not a valid key of this algorithm")]
|
#[error("not a valid key of this algorithm")]
|
||||||
Invalid,
|
Invalid,
|
||||||
|
#[error("the key is protected with a passphrase; remove it or import the key in the Custos app")]
|
||||||
|
Encrypted,
|
||||||
|
#[error("not a private key Custos can import (Ed25519, ECDSA P-256 or RSA 2048-4096 bits)")]
|
||||||
|
Unsupported,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
@@ -64,35 +68,112 @@ fn enc<T, E>(r: Result<T, E>) -> Result<T, KeyError> {
|
|||||||
|
|
||||||
/// A new key pair. RSA takes a few seconds (prime generation).
|
/// A new key pair. RSA takes a few seconds (prime generation).
|
||||||
pub fn generate(alg: Algorithm, comment: &str) -> Result<KeyPair, KeyError> {
|
pub fn generate(alg: Algorithm, comment: &str) -> Result<KeyPair, KeyError> {
|
||||||
let (data, private_pem, public_pem) = match alg {
|
match alg {
|
||||||
Algorithm::Ed25519 => {
|
Algorithm::Ed25519 => from_ed25519(ed25519_dalek::SigningKey::generate(&mut OsRng), comment),
|
||||||
use ed25519_dalek::pkcs8::{EncodePrivateKey, EncodePublicKey};
|
Algorithm::EcdsaP256 => from_p256(p256::SecretKey::random(&mut OsRng), comment),
|
||||||
let sk = ed25519_dalek::SigningKey::generate(&mut OsRng);
|
|
||||||
let private_pem = enc(sk.to_pkcs8_pem(LineEnding::LF))?.to_string();
|
|
||||||
let public_pem = enc(sk.verifying_key().to_public_key_pem(LineEnding::LF))?;
|
|
||||||
(KeypairData::Ed25519(Ed25519Keypair::from(&sk)), private_pem, public_pem)
|
|
||||||
}
|
|
||||||
Algorithm::EcdsaP256 => {
|
|
||||||
use p256::pkcs8::{EncodePrivateKey, EncodePublicKey};
|
|
||||||
let sk = p256::SecretKey::random(&mut OsRng);
|
|
||||||
let private_pem = enc(sk.to_pkcs8_pem(LineEnding::LF))?.to_string();
|
|
||||||
let public_pem = enc(sk.public_key().to_public_key_pem(LineEnding::LF))?;
|
|
||||||
let public = sk.public_key();
|
|
||||||
(KeypairData::Ecdsa(EcdsaKeypair::NistP256 { private: sk.into(), public: public.into() }), private_pem, public_pem)
|
|
||||||
}
|
|
||||||
Algorithm::Rsa3072 | Algorithm::Rsa4096 => {
|
Algorithm::Rsa3072 | Algorithm::Rsa4096 => {
|
||||||
use rsa::pkcs8::{EncodePrivateKey, EncodePublicKey};
|
|
||||||
let bits = if alg == Algorithm::Rsa3072 { 3072 } else { 4096 };
|
let bits = if alg == Algorithm::Rsa3072 { 3072 } else { 4096 };
|
||||||
let sk = enc(rsa::RsaPrivateKey::new(&mut OsRng, bits))?;
|
from_rsa(enc(rsa::RsaPrivateKey::new(&mut OsRng, bits))?, comment)
|
||||||
let private_pem = enc(sk.to_pkcs8_pem(LineEnding::LF))?.to_string();
|
|
||||||
let public_pem = enc(sk.to_public_key().to_public_key_pem(LineEnding::LF))?;
|
|
||||||
(KeypairData::Rsa(enc(RsaKeypair::try_from(sk))?), private_pem, public_pem)
|
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An existing private key as a key pair (docs/KEYS.md, "Importing"): an OpenSSH private key, PKCS#8
|
||||||
|
/// (`BEGIN PRIVATE KEY`), PKCS#1 (`BEGIN RSA PRIVATE KEY`) or SEC1 (`BEGIN EC PRIVATE KEY`), unencrypted.
|
||||||
|
/// The public parts and the fingerprint are derived from the private key, never taken from the input.
|
||||||
|
/// An OpenSSH key keeps its own comment unless it has none.
|
||||||
|
pub fn import(text: &str, comment: &str) -> Result<KeyPair, KeyError> {
|
||||||
|
// Pasted or read from a Windows file: CRLF line ends.
|
||||||
|
let text = text.replace("
|
||||||
|
", "
|
||||||
|
");
|
||||||
|
let text = text.trim();
|
||||||
|
let has = |label: &str| text.contains(&format!("-----BEGIN {label}-----"));
|
||||||
|
if has("ENCRYPTED PRIVATE KEY") || text.contains("Proc-Type: 4,ENCRYPTED") {
|
||||||
|
return Err(KeyError::Encrypted);
|
||||||
|
}
|
||||||
|
if has("OPENSSH PRIVATE KEY") {
|
||||||
|
let key = PrivateKey::from_openssh(text).map_err(|_| KeyError::Invalid)?;
|
||||||
|
if key.is_encrypted() {
|
||||||
|
return Err(KeyError::Encrypted);
|
||||||
|
}
|
||||||
|
let comment = if key.comment().is_empty() { comment.to_owned() } else { key.comment().to_owned() };
|
||||||
|
return match key.key_data() {
|
||||||
|
KeypairData::Ed25519(k) => from_ed25519(ed25519_dalek::SigningKey::from_bytes(&k.private.to_bytes()), &comment),
|
||||||
|
KeypairData::Ecdsa(EcdsaKeypair::NistP256 { private, .. }) => {
|
||||||
|
from_p256(p256::SecretKey::from_slice(private.as_slice()).map_err(|_| KeyError::Invalid)?, &comment)
|
||||||
|
}
|
||||||
|
KeypairData::Rsa(k) => from_rsa(rsa_from_openssh(k)?, &comment),
|
||||||
|
KeypairData::Encrypted(_) => Err(KeyError::Encrypted),
|
||||||
|
_ => Err(KeyError::Unsupported),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if has("PRIVATE KEY") {
|
||||||
|
use ed25519_dalek::pkcs8::DecodePrivateKey;
|
||||||
|
if let Ok(sk) = ed25519_dalek::SigningKey::from_pkcs8_pem(text) {
|
||||||
|
return from_ed25519(sk, comment);
|
||||||
|
}
|
||||||
|
if let Ok(sk) = p256::SecretKey::from_pkcs8_pem(text) {
|
||||||
|
return from_p256(sk, comment);
|
||||||
|
}
|
||||||
|
if let Ok(sk) = rsa::RsaPrivateKey::from_pkcs8_pem(text) {
|
||||||
|
return from_rsa(sk, comment);
|
||||||
|
}
|
||||||
|
return Err(KeyError::Unsupported);
|
||||||
|
}
|
||||||
|
if has("RSA PRIVATE KEY") {
|
||||||
|
use rsa::pkcs1::DecodeRsaPrivateKey;
|
||||||
|
return from_rsa(rsa::RsaPrivateKey::from_pkcs1_pem(text).map_err(|_| KeyError::Invalid)?, comment);
|
||||||
|
}
|
||||||
|
if has("EC PRIVATE KEY") {
|
||||||
|
return from_p256(p256::SecretKey::from_sec1_pem(text).map_err(|_| KeyError::Unsupported)?, comment);
|
||||||
|
}
|
||||||
|
Err(KeyError::Unsupported)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// ssh-key 0.6.7's own `TryFrom<&RsaKeypair>` passes `p` twice instead of `p` and `q`, so the key is
|
||||||
|
/// rebuilt from its components here.
|
||||||
|
fn rsa_from_openssh(k: &RsaKeypair) -> Result<rsa::RsaPrivateKey, KeyError> {
|
||||||
|
let n = |m: &ssh_key::Mpint| rsa::BigUint::try_from(m).map_err(|_| KeyError::Invalid);
|
||||||
|
let sk = rsa::RsaPrivateKey::from_components(n(&k.public.n)?, n(&k.public.e)?, n(&k.private.d)?, vec![n(&k.private.p)?, n(&k.private.q)?])
|
||||||
|
.map_err(|_| KeyError::Invalid)?;
|
||||||
|
sk.validate().map_err(|_| KeyError::Invalid)?;
|
||||||
|
Ok(sk)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_ed25519(sk: ed25519_dalek::SigningKey, comment: &str) -> Result<KeyPair, KeyError> {
|
||||||
|
use ed25519_dalek::pkcs8::{EncodePrivateKey, EncodePublicKey};
|
||||||
|
let private_pem = enc(sk.to_pkcs8_pem(LineEnding::LF))?.to_string();
|
||||||
|
let public_pem = enc(sk.verifying_key().to_public_key_pem(LineEnding::LF))?;
|
||||||
|
assemble("ed25519", KeypairData::Ed25519(Ed25519Keypair::from(&sk)), private_pem, public_pem, comment)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_p256(sk: p256::SecretKey, comment: &str) -> Result<KeyPair, KeyError> {
|
||||||
|
use p256::pkcs8::{EncodePrivateKey, EncodePublicKey};
|
||||||
|
let private_pem = enc(sk.to_pkcs8_pem(LineEnding::LF))?.to_string();
|
||||||
|
let public_pem = enc(sk.public_key().to_public_key_pem(LineEnding::LF))?;
|
||||||
|
let public = sk.public_key();
|
||||||
|
let data = KeypairData::Ecdsa(EcdsaKeypair::NistP256 { private: sk.into(), public: public.into() });
|
||||||
|
assemble("ecdsa-p256", data, private_pem, public_pem, comment)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_rsa(sk: rsa::RsaPrivateKey, comment: &str) -> Result<KeyPair, KeyError> {
|
||||||
|
use rsa::pkcs8::{EncodePrivateKey, EncodePublicKey};
|
||||||
|
use rsa::traits::PublicKeyParts;
|
||||||
|
let bits = sk.size() * 8;
|
||||||
|
if !(2048..=4096).contains(&bits) {
|
||||||
|
return Err(KeyError::Unsupported);
|
||||||
|
}
|
||||||
|
let private_pem = enc(sk.to_pkcs8_pem(LineEnding::LF))?.to_string();
|
||||||
|
let public_pem = enc(sk.to_public_key().to_public_key_pem(LineEnding::LF))?;
|
||||||
|
assemble(&format!("rsa-{bits}"), KeypairData::Rsa(enc(RsaKeypair::try_from(sk))?), private_pem, public_pem, comment)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assemble(algorithm: &str, data: KeypairData, private_pem: String, public_pem: String, comment: &str) -> Result<KeyPair, KeyError> {
|
||||||
let private = enc(PrivateKey::new(data, comment))?;
|
let private = enc(PrivateKey::new(data, comment))?;
|
||||||
let public = private.public_key();
|
let public = private.public_key();
|
||||||
Ok(KeyPair {
|
Ok(KeyPair {
|
||||||
algorithm: alg.name().into(),
|
algorithm: algorithm.into(),
|
||||||
public_openssh: enc(public.to_openssh())?,
|
public_openssh: enc(public.to_openssh())?,
|
||||||
public_pem,
|
public_pem,
|
||||||
private_pem: SecretString::new(private_pem),
|
private_pem: SecretString::new(private_pem),
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
-----BEGIN OPENSSH PRIVATE KEY-----
|
||||||
|
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
|
||||||
|
QyNTUxOQAAACDt2TW39UZy8qwtg1TjmyyP6tQyICmROg6Ed8wT8LfNMAAAAJDgLH6c4Cx+
|
||||||
|
nAAAAAtzc2gtZWQyNTUxOQAAACDt2TW39UZy8qwtg1TjmyyP6tQyICmROg6Ed8wT8LfNMA
|
||||||
|
AAAEBnrsV5Mk4SOUMLEChNqaRAd2+aSJlQup0lVfIDpgs0ZO3ZNbf1RnLyrC2DVOObLI/q
|
||||||
|
1DIgKZE6DoR3zBPwt80wAAAADGZpeHR1cmVAdGVzdAE=
|
||||||
|
-----END OPENSSH PRIVATE KEY-----
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
-----BEGIN OPENSSH PRIVATE KEY-----
|
||||||
|
b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABD6DWv11a
|
||||||
|
60wSTEmglCO465AAAAGAAAAAEAAAAzAAAAC3NzaC1lZDI1NTE5AAAAILvNKbmysLcBtsSO
|
||||||
|
rLTfznA6I1TNJa6UryfZvKCK8m8SAAAAkFMVbzEv6H/wWf5oYKy2l9wRAZzrvy2mqkyLRm
|
||||||
|
DyIuKemJsVxFao1sL84IpcMC809PUX4qHLT5qFb/wOcv3fJKsFluHJS3c26CAqe6pbgP6W
|
||||||
|
pXPKKKedbzrcRxfgVORw36fBNJdMQbFAUsYq2ytId0vHb8JYHCzjO3vSYPAaG+kfwrfRxn
|
||||||
|
7wvt5tz4/9N14Wag==
|
||||||
|
-----END OPENSSH PRIVATE KEY-----
|
||||||
@@ -48,3 +48,64 @@ fn algorithm_names_parse() {
|
|||||||
}
|
}
|
||||||
assert_eq!(Algorithm::from_name("dsa"), None);
|
assert_eq!(Algorithm::from_name("dsa"), None);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- importing (docs/KEYS.md, "Importing") ----
|
||||||
|
|
||||||
|
/// A throwaway key made by `ssh-keygen -t ed25519 -C fixture@test` for these tests only.
|
||||||
|
const SSH_KEYGEN_ED25519: &str = include_str!("fixtures/ssh-keygen-ed25519");
|
||||||
|
/// The same kind of key with the passphrase `fixture-pass`.
|
||||||
|
const SSH_KEYGEN_ENCRYPTED: &str = include_str!("fixtures/ssh-keygen-ed25519-passphrase");
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_ssh_keygen_key_imports_with_its_own_fingerprint_and_comment() {
|
||||||
|
let k = custos_keys::import(SSH_KEYGEN_ED25519, "fallback").unwrap();
|
||||||
|
assert_eq!(k.algorithm, "ed25519");
|
||||||
|
// What `ssh-keygen -l -f` printed for the fixture.
|
||||||
|
assert_eq!(k.fingerprint, "SHA256:IGwHpAF8aVpXvaBckNayqTMlHUvRgN9+w1uS7iyLPGE");
|
||||||
|
assert!(k.public_openssh.ends_with(" fixture@test"));
|
||||||
|
assert!(custos_keys::pem_matches(Algorithm::Ed25519, k.private_pem.expose(), &k.public_pem).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_private_key_format_imports_to_the_same_key() {
|
||||||
|
use p256::pkcs8::DecodePrivateKey as _;
|
||||||
|
use rsa::pkcs1::EncodeRsaPrivateKey;
|
||||||
|
for alg in [Algorithm::Ed25519, Algorithm::EcdsaP256, Algorithm::Rsa3072] {
|
||||||
|
let k = generate(alg, "deploy").unwrap();
|
||||||
|
let mut inputs = vec![k.private_openssh.expose().to_owned(), k.private_pem.expose().to_owned()];
|
||||||
|
match alg {
|
||||||
|
Algorithm::EcdsaP256 => {
|
||||||
|
let sk = p256::SecretKey::from_pkcs8_pem(k.private_pem.expose()).unwrap();
|
||||||
|
inputs.push(sk.to_sec1_pem(p256::pkcs8::LineEnding::LF).unwrap().to_string());
|
||||||
|
}
|
||||||
|
Algorithm::Rsa3072 => {
|
||||||
|
let sk = rsa::RsaPrivateKey::from_pkcs8_pem(k.private_pem.expose()).unwrap();
|
||||||
|
inputs.push(sk.to_pkcs1_pem(rsa::pkcs8::LineEnding::LF).unwrap().to_string());
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
for text in inputs {
|
||||||
|
// Surrounding whitespace (a paste, a file with CRLF line ends) does not matter.
|
||||||
|
let pasted = format!("\r\n {}\r\n", text.replace('\n', "\r\n"));
|
||||||
|
let i = custos_keys::import(&pasted, "deploy").unwrap_or_else(|e| panic!("{alg:?} {}: {e:?}", text.lines().next().unwrap()));
|
||||||
|
assert_eq!((i.algorithm.as_str(), i.fingerprint.as_str()), (alg.name(), k.fingerprint.as_str()), "{alg:?}");
|
||||||
|
assert_eq!(i.public_pem, k.public_pem);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn protected_and_unknown_keys_are_refused() {
|
||||||
|
use custos_keys::KeyError;
|
||||||
|
assert!(matches!(custos_keys::import(SSH_KEYGEN_ENCRYPTED, "x"), Err(KeyError::Encrypted)));
|
||||||
|
let pkcs8_encrypted = "-----BEGIN ENCRYPTED PRIVATE KEY-----\nMIIB\n-----END ENCRYPTED PRIVATE KEY-----";
|
||||||
|
assert!(matches!(custos_keys::import(pkcs8_encrypted, "x"), Err(KeyError::Encrypted)));
|
||||||
|
let pkcs1_encrypted = "-----BEGIN RSA PRIVATE KEY-----\nProc-Type: 4,ENCRYPTED\nDEK-Info: AES-128-CBC,00\n\nAAAA\n-----END RSA PRIVATE KEY-----";
|
||||||
|
assert!(matches!(custos_keys::import(pkcs1_encrypted, "x"), Err(KeyError::Encrypted)));
|
||||||
|
// A public key, a password, garbage: nothing to import, and the error never repeats the input.
|
||||||
|
let public = generate(Algorithm::Ed25519, "p").unwrap().public_openssh;
|
||||||
|
for text in [public.as_str(), "hunter2-not-a-key", "-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----"] {
|
||||||
|
let e = custos_keys::import(text, "x").unwrap_err();
|
||||||
|
assert!(!e.to_string().contains("hunter2") && !e.to_string().contains("AAAA"), "{e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
[package]
|
||||||
|
name = "custos-seal"
|
||||||
|
description = "Custos sealed boxes: a secret encrypted to one device's X25519 key, and at-rest sealing for the factor service (docs/SEAL.md)"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
x25519-dalek = { version = "2", features = ["static_secrets", "zeroize"] }
|
||||||
|
chacha20poly1305.workspace = true
|
||||||
|
hkdf.workspace = true
|
||||||
|
sha2.workspace = true
|
||||||
|
rand.workspace = true
|
||||||
|
zeroize.workspace = true
|
||||||
|
thiserror.workspace = true
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
//! Sealed boxes (docs/SEAL.md). A device that wants a secret makes a one-time X25519 key pair and sends
|
||||||
|
//! only its public key; whoever releases the secret seals it to that key, so the mailbox in between (the
|
||||||
|
//! factor service on the home server) carries ciphertext it cannot open. Also the factor service's
|
||||||
|
//! at-rest sealing of the TOTP shares it keeps.
|
||||||
|
//!
|
||||||
|
//! ```text
|
||||||
|
//! sealed = "CSL1" ‖ ephemeral public (32) ‖ nonce (24) ‖ XChaCha20-Poly1305(key, nonce, plaintext, aad)
|
||||||
|
//! key = HKDF-SHA256(X25519(ephemeral, recipient), salt = ephemeral pub ‖ recipient pub,
|
||||||
|
//! info = "custos seal v1" ‖ context)
|
||||||
|
//! aad = "CSL1" ‖ ephemeral public ‖ context
|
||||||
|
//!
|
||||||
|
//! at rest = "CSR1" ‖ nonce (24) ‖ XChaCha20-Poly1305(HKDF(key, "", "custos rest v1" ‖ context), nonce,
|
||||||
|
//! plaintext, "CSR1" ‖ context)
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! `context` binds a box to its purpose (e.g. `approval:<factor id>:<request id>`): a box sealed for one
|
||||||
|
//! request does not open as another.
|
||||||
|
|
||||||
|
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
|
||||||
|
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
|
||||||
|
use rand::Rng;
|
||||||
|
use rand::rand_core::UnwrapErr;
|
||||||
|
use rand::rngs::SysRng;
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
use x25519_dalek::{PublicKey, StaticSecret};
|
||||||
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
|
const MAGIC: &[u8; 4] = b"CSL1";
|
||||||
|
const REST: &[u8; 4] = b"CSR1";
|
||||||
|
const NONCE: usize = 24;
|
||||||
|
const TAG: usize = 16;
|
||||||
|
/// The largest plaintext a box carries (a key pair's private key fits many times over).
|
||||||
|
pub const MAX_PLAINTEXT: usize = 32 * 1024;
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum SealError {
|
||||||
|
#[error("not a sealed box, or it was changed")]
|
||||||
|
Malformed,
|
||||||
|
#[error("this box was not sealed for this key and purpose")]
|
||||||
|
Rejected,
|
||||||
|
#[error("not a valid public key")]
|
||||||
|
BadKey,
|
||||||
|
#[error("the secret is too large to seal")]
|
||||||
|
TooLarge,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn random<const N: usize>() -> Zeroizing<[u8; N]> {
|
||||||
|
let mut b = Zeroizing::new([0u8; N]);
|
||||||
|
UnwrapErr(SysRng).fill_bytes(b.as_mut());
|
||||||
|
b
|
||||||
|
}
|
||||||
|
|
||||||
|
fn derive(ikm: &[u8], salt: &[u8], info: &[&[u8]]) -> Zeroizing<[u8; 32]> {
|
||||||
|
let mut k = Zeroizing::new([0u8; 32]);
|
||||||
|
hkdf::Hkdf::<Sha256>::new(Some(salt), ikm).expand(&info.concat(), k.as_mut()).expect("32 bytes is a valid HKDF length");
|
||||||
|
k
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cipher(key: &[u8; 32]) -> XChaCha20Poly1305 {
|
||||||
|
XChaCha20Poly1305::new_from_slice(key).expect("32-byte key")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn xnonce(n: &[u8]) -> XNonce {
|
||||||
|
XNonce::try_from(n).expect("24-byte nonce")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The one-time key pair of a device waiting for a secret. Its secret half never leaves memory and is
|
||||||
|
/// wiped on drop.
|
||||||
|
pub struct Recipient {
|
||||||
|
secret: StaticSecret,
|
||||||
|
public: [u8; 32],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Recipient {
|
||||||
|
pub fn generate() -> Recipient {
|
||||||
|
let secret = StaticSecret::from(*random::<32>());
|
||||||
|
let public = PublicKey::from(&secret).to_bytes();
|
||||||
|
Recipient { secret, public }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the device sends: 32 bytes.
|
||||||
|
pub fn public(&self) -> [u8; 32] {
|
||||||
|
self.public
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The six digits both screens show, so the person approving sees it is this request.
|
||||||
|
pub fn match_code(&self) -> String {
|
||||||
|
match_code(&self.public)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opens a box sealed to this key for `context`.
|
||||||
|
pub fn open(&self, sealed: &[u8], context: &[u8]) -> Result<Zeroizing<Vec<u8>>, SealError> {
|
||||||
|
if sealed.len() < 4 + 32 + NONCE + TAG || &sealed[..4] != MAGIC {
|
||||||
|
return Err(SealError::Malformed);
|
||||||
|
}
|
||||||
|
let eph: [u8; 32] = sealed[4..36].try_into().expect("32 bytes");
|
||||||
|
let shared = self.secret.diffie_hellman(&PublicKey::from(eph));
|
||||||
|
if !shared.was_contributory() {
|
||||||
|
return Err(SealError::Rejected);
|
||||||
|
}
|
||||||
|
let key = derive(shared.as_bytes(), &[eph.as_slice(), &self.public].concat(), &[b"custos seal v1", context]);
|
||||||
|
let aad = [MAGIC.as_slice(), &eph, context].concat();
|
||||||
|
cipher(&key)
|
||||||
|
.decrypt(&xnonce(&sealed[36..36 + NONCE]), Payload { msg: &sealed[36 + NONCE..], aad: &aad })
|
||||||
|
.map(Zeroizing::new)
|
||||||
|
.map_err(|_| SealError::Rejected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for Recipient {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
write!(f, "Recipient {{ match_code: {} }}", self.match_code())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Seals `plaintext` to a recipient's public key for `context`. Only that recipient opens it.
|
||||||
|
pub fn seal(recipient: &[u8], context: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, SealError> {
|
||||||
|
let recipient: [u8; 32] = recipient.try_into().map_err(|_| SealError::BadKey)?;
|
||||||
|
if plaintext.len() > MAX_PLAINTEXT {
|
||||||
|
return Err(SealError::TooLarge);
|
||||||
|
}
|
||||||
|
let eph = StaticSecret::from(*random::<32>());
|
||||||
|
let eph_pub = PublicKey::from(&eph).to_bytes();
|
||||||
|
let shared = eph.diffie_hellman(&PublicKey::from(recipient));
|
||||||
|
// A low-order "public key" would give a shared secret anyone knows.
|
||||||
|
if !shared.was_contributory() {
|
||||||
|
return Err(SealError::BadKey);
|
||||||
|
}
|
||||||
|
let key = derive(shared.as_bytes(), &[eph_pub.as_slice(), &recipient].concat(), &[b"custos seal v1", context]);
|
||||||
|
let nonce = random::<NONCE>();
|
||||||
|
let aad = [MAGIC.as_slice(), &eph_pub, context].concat();
|
||||||
|
let ct = cipher(&key)
|
||||||
|
.encrypt(&xnonce(nonce.as_ref()), Payload { msg: plaintext, aad: &aad })
|
||||||
|
.expect("encryption cannot fail for in-memory buffers");
|
||||||
|
Ok([MAGIC.as_slice(), &eph_pub, nonce.as_ref(), &ct].concat())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Six digits from a public key: what the requesting screen and the approving screen both show.
|
||||||
|
pub fn match_code(public: &[u8]) -> String {
|
||||||
|
let h = Sha256::new().chain_update(b"custos match v1").chain_update(public).finalize();
|
||||||
|
let n = u32::from_be_bytes([h[0], h[1], h[2], h[3]]) % 1_000_000;
|
||||||
|
format!("{n:06}")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The match code of the one-time key a box was sealed with. When the receiver must know who sealed a
|
||||||
|
/// box (pairing a phone), the sealing screen shows this code and the receiving screen checks it.
|
||||||
|
pub fn sender_code(sealed: &[u8]) -> Result<String, SealError> {
|
||||||
|
if sealed.len() < 4 + 32 + NONCE + TAG || &sealed[..4] != MAGIC {
|
||||||
|
return Err(SealError::Malformed);
|
||||||
|
}
|
||||||
|
Ok(match_code(&sealed[4..36]))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Seals data the factor service keeps on disk, with its own key (from a systemd credential).
|
||||||
|
pub fn seal_at_rest(key: &[u8; 32], context: &[u8], plaintext: &[u8]) -> Vec<u8> {
|
||||||
|
let k = derive(key, b"", &[b"custos rest v1", context]);
|
||||||
|
let nonce = random::<NONCE>();
|
||||||
|
let aad = [REST.as_slice(), context].concat();
|
||||||
|
let ct = cipher(&k)
|
||||||
|
.encrypt(&xnonce(nonce.as_ref()), Payload { msg: plaintext, aad: &aad })
|
||||||
|
.expect("encryption cannot fail for in-memory buffers");
|
||||||
|
[REST.as_slice(), nonce.as_ref(), &ct].concat()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn open_at_rest(key: &[u8; 32], context: &[u8], sealed: &[u8]) -> Result<Zeroizing<Vec<u8>>, SealError> {
|
||||||
|
if sealed.len() < 4 + NONCE + TAG || &sealed[..4] != REST {
|
||||||
|
return Err(SealError::Malformed);
|
||||||
|
}
|
||||||
|
let k = derive(key, b"", &[b"custos rest v1", context]);
|
||||||
|
let aad = [REST.as_slice(), context].concat();
|
||||||
|
cipher(&k)
|
||||||
|
.decrypt(&xnonce(&sealed[4..4 + NONCE]), Payload { msg: &sealed[4 + NONCE..], aad: &aad })
|
||||||
|
.map(Zeroizing::new)
|
||||||
|
.map_err(|_| SealError::Rejected)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 32 random bytes from the OS (factor material, tokens).
|
||||||
|
pub fn random_bytes() -> Zeroizing<[u8; 32]> {
|
||||||
|
random()
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
//! Mandatory tests for sealed boxes (docs/SEAL.md).
|
||||||
|
|
||||||
|
use custos_seal::{Recipient, SealError, match_code, open_at_rest, seal, seal_at_rest, sender_code};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_the_recipient_opens_and_only_for_its_purpose() {
|
||||||
|
let r = Recipient::generate();
|
||||||
|
let other = Recipient::generate();
|
||||||
|
let b = seal(&r.public(), b"approval:f1:r1", b"factor material").unwrap();
|
||||||
|
assert_eq!(r.open(&b, b"approval:f1:r1").unwrap().as_slice(), b"factor material");
|
||||||
|
assert_eq!(other.open(&b, b"approval:f1:r1"), Err(SealError::Rejected));
|
||||||
|
// The same box for another request or factor does not open.
|
||||||
|
assert_eq!(r.open(&b, b"approval:f1:r2"), Err(SealError::Rejected));
|
||||||
|
// Two seals of the same secret differ (fresh ephemeral key and nonce).
|
||||||
|
assert_ne!(b, seal(&r.public(), b"approval:f1:r1", b"factor material").unwrap());
|
||||||
|
assert!(!b.windows(15).any(|w| w == b"factor material"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_changed_byte_is_refused() {
|
||||||
|
let r = Recipient::generate();
|
||||||
|
let b = seal(&r.public(), b"c", b"secret").unwrap();
|
||||||
|
for i in 0..b.len() {
|
||||||
|
let mut bad = b.clone();
|
||||||
|
bad[i] ^= 1;
|
||||||
|
assert!(r.open(&bad, b"c").is_err(), "byte {i}");
|
||||||
|
}
|
||||||
|
assert_eq!(r.open(&b[..b.len() - 1], b"c"), Err(SealError::Rejected));
|
||||||
|
assert_eq!(r.open(&b[..20], b"c"), Err(SealError::Malformed));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bad_public_keys_are_refused() {
|
||||||
|
assert_eq!(seal(&[1u8; 31], b"c", b"s"), Err(SealError::BadKey));
|
||||||
|
// The all-zero point (low order) would give a shared secret everyone knows.
|
||||||
|
assert_eq!(seal(&[0u8; 32], b"c", b"s"), Err(SealError::BadKey));
|
||||||
|
assert_eq!(seal(&Recipient::generate().public(), b"c", &vec![0u8; 40_000]), Err(SealError::TooLarge));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_match_code_is_six_digits_and_follows_the_key() {
|
||||||
|
let r = Recipient::generate();
|
||||||
|
assert_eq!(r.match_code(), match_code(&r.public()));
|
||||||
|
assert_eq!(r.match_code().len(), 6);
|
||||||
|
assert!(r.match_code().bytes().all(|b| b.is_ascii_digit()));
|
||||||
|
// A known vector, so every implementation (the web app's wasm too) shows the same digits.
|
||||||
|
assert_eq!(match_code(&[7u8; 32]), KNOWN_MATCH_CODE);
|
||||||
|
let codes: std::collections::HashSet<String> = (0..50).map(|_| Recipient::generate().match_code()).collect();
|
||||||
|
assert!(codes.len() > 45);
|
||||||
|
assert!(!format!("{r:?}").contains(&format!("{:?}", r.public())));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// SHA-256("custos match v1" ‖ 0x07 × 32), first four bytes big-endian, mod 1 000 000.
|
||||||
|
const KNOWN_MATCH_CODE: &str = "684361";
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_sender_code_differs_per_box_and_needs_a_box() {
|
||||||
|
let r = Recipient::generate();
|
||||||
|
let a = seal(&r.public(), b"pair:1", b"x").unwrap();
|
||||||
|
let b = seal(&r.public(), b"pair:1", b"x").unwrap();
|
||||||
|
assert_eq!(sender_code(&a).unwrap(), match_code(&a[4..36]));
|
||||||
|
assert_ne!(a[4..36], b[4..36], "a fresh one-time key per box");
|
||||||
|
assert_eq!(sender_code(&a[..40]), Err(SealError::Malformed));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn at_rest_seals_open_with_the_same_key_and_context_only() {
|
||||||
|
let key = [9u8; 32];
|
||||||
|
let b = seal_at_rest(&key, b"totp:f1", b"share");
|
||||||
|
assert_eq!(open_at_rest(&key, b"totp:f1", &b).unwrap().as_slice(), b"share");
|
||||||
|
assert_eq!(open_at_rest(&[8u8; 32], b"totp:f1", &b), Err(SealError::Rejected));
|
||||||
|
assert_eq!(open_at_rest(&key, b"totp:f2", &b), Err(SealError::Rejected));
|
||||||
|
assert_eq!(open_at_rest(&key, b"totp:f1", b"CSR1"), Err(SealError::Malformed));
|
||||||
|
}
|
||||||
@@ -57,6 +57,8 @@ pub enum Error {
|
|||||||
NeedTwoFactors,
|
NeedTwoFactors,
|
||||||
#[error("this factor does not open the vault")]
|
#[error("this factor does not open the vault")]
|
||||||
FactorRejected,
|
FactorRejected,
|
||||||
|
#[error("these two factors are kept on the same device; use one of them with another factor")]
|
||||||
|
SameDevice,
|
||||||
#[error("a vault has at most 8 factors and one master password")]
|
#[error("a vault has at most 8 factors and one master password")]
|
||||||
TooManyFactors,
|
TooManyFactors,
|
||||||
#[error("{0}")]
|
#[error("{0}")]
|
||||||
@@ -448,7 +450,8 @@ impl Vault {
|
|||||||
return Err(Error::NeedTwoFactors);
|
return Err(Error::NeedTwoFactors);
|
||||||
}
|
}
|
||||||
let (x, y) = if fa.id < fb.id { (fa.id, fb.id) } else { (fb.id, fa.id) };
|
let (x, y) = if fa.id < fb.id { (fa.id, fb.id) } else { (fb.id, fa.id) };
|
||||||
let slot = header.pair_slots().into_iter().find(|p| p.a == x && p.b == y).ok_or(Error::Corrupted)?;
|
// Both factors opened, so a missing pair is one added apart from the other (one device).
|
||||||
|
let slot = header.pair_slots().into_iter().find(|p| p.a == x && p.b == y).ok_or(Error::SameDevice)?;
|
||||||
let k = crypto::open(&pair_kek(&fa, &fb), &slot.nonce, &slot.wrapped, &slot.aad()).ok_or(Error::Corrupted)?;
|
let k = crypto::open(&pair_kek(&fa, &fb), &slot.nonce, &slot.wrapped, &slot.aad()).ok_or(Error::Corrupted)?;
|
||||||
Vault::open_body(bytes, header, body_at, key32(k)?)
|
Vault::open_body(bytes, header, body_at, key32(k)?)
|
||||||
}
|
}
|
||||||
@@ -479,6 +482,16 @@ impl Vault {
|
|||||||
Ok(header.factor_slots().iter().filter_map(|s| FactorKind::from_code(s.kind)).collect())
|
Ok(header.factor_slots().iter().filter_map(|s| FactorKind::from_code(s.kind)).collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The factors a vault file has, from its header (no key needed): id (32 hex digits) and type. The app
|
||||||
|
/// asks the TOTP service and paired devices for a factor by this id.
|
||||||
|
pub fn factor_ids(bytes: &[u8]) -> Result<Vec<(String, FactorKind)>, Error> {
|
||||||
|
let (header, _) = Header::parse(bytes)?;
|
||||||
|
if header.version == VERSION {
|
||||||
|
return Ok(Vec::new());
|
||||||
|
}
|
||||||
|
Ok(header.factor_slots().iter().filter_map(|s| Some((hex(&s.id), FactorKind::from_code(s.kind)?))).collect())
|
||||||
|
}
|
||||||
|
|
||||||
pub fn is_machine_store(bytes: &[u8]) -> Result<bool, Error> {
|
pub fn is_machine_store(bytes: &[u8]) -> Result<bool, Error> {
|
||||||
Ok(Header::parse(bytes)?.0.is_machine_store())
|
Ok(Header::parse(bytes)?.0.is_machine_store())
|
||||||
}
|
}
|
||||||
@@ -584,6 +597,17 @@ impl Vault {
|
|||||||
/// Adds a factor to a version-2 vault: only the new factor's material is needed (docs/FACTORS.md).
|
/// Adds a factor to a version-2 vault: only the new factor's material is needed (docs/FACTORS.md).
|
||||||
/// Returns its id. A second master password is refused; use [`Vault::change_password`].
|
/// Returns its id. A second master password is refused; use [`Vault::change_password`].
|
||||||
pub fn add_factor(&mut self, u: Unlock, label: &str) -> Result<String, Error> {
|
pub fn add_factor(&mut self, u: Unlock, label: &str) -> Result<String, Error> {
|
||||||
|
self.add_factor_apart(u, label, &[])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds a factor that never pairs with the factors `apart` (ids of factors kept on the same device, such
|
||||||
|
/// as a phone's passkey and its approval key): together they open nothing, so one device is never two
|
||||||
|
/// factors. Returns its id.
|
||||||
|
pub fn add_factor_apart(&mut self, u: Unlock, label: &str, apart: &[&str]) -> Result<String, Error> {
|
||||||
|
let apart: Vec<[u8; ID_LEN]> = apart.iter().map(|a| unhex(a).ok_or(Error::FactorRejected)).collect::<Result<_, _>>()?;
|
||||||
|
if apart.iter().any(|a| !self.factors.iter().any(|f| f.id == *a)) {
|
||||||
|
return Err(Error::FactorRejected);
|
||||||
|
}
|
||||||
if self.version != VERSION_2 {
|
if self.version != VERSION_2 {
|
||||||
return Err(Error::NeedTwoFactors);
|
return Err(Error::NeedTwoFactors);
|
||||||
}
|
}
|
||||||
@@ -601,7 +625,7 @@ impl Vault {
|
|||||||
let rec = FactorRec { id, kind: u.kind(), label: label.into(), created: now_ms(), key: crypto::random_key() };
|
let rec = FactorRec { id, kind: u.kind(), label: label.into(), created: now_ms(), key: crypto::random_key() };
|
||||||
let slot = factor_slot(id, &rec.key, &u, self.kdf_new)?;
|
let slot = factor_slot(id, &rec.key, &u, self.kdf_new)?;
|
||||||
self.slots.push(slot.raw());
|
self.slots.push(slot.raw());
|
||||||
for other in &self.factors {
|
for other in self.factors.iter().filter(|f| !apart.contains(&f.id)) {
|
||||||
self.slots.push(pair_slot(&self.key, &rec, other).raw());
|
self.slots.push(pair_slot(&self.key, &rec, other).raw());
|
||||||
}
|
}
|
||||||
self.factors.push(rec);
|
self.factors.push(rec);
|
||||||
|
|||||||
@@ -132,6 +132,11 @@ fn a_v1_vault_upgrades_and_its_password_alone_stops_working() {
|
|||||||
let new = v.to_bytes().unwrap();
|
let new = v.to_bytes().unwrap();
|
||||||
assert_eq!(Vault::version_of(&new).unwrap(), 2);
|
assert_eq!(Vault::version_of(&new).unwrap(), 2);
|
||||||
assert_eq!(Vault::factor_kinds(&new).unwrap(), [FactorKind::Password, FactorKind::Device]);
|
assert_eq!(Vault::factor_kinds(&new).unwrap(), [FactorKind::Password, FactorKind::Device]);
|
||||||
|
// The header names each factor by the id the unlocked vault lists; a v1 file has none.
|
||||||
|
let ids = Vault::factor_ids(&new).unwrap();
|
||||||
|
let listed: Vec<(String, FactorKind)> = v.factors().into_iter().map(|f| (f.id, f.kind)).collect();
|
||||||
|
assert_eq!(ids, listed);
|
||||||
|
assert!(Vault::factor_ids(&old).unwrap().is_empty());
|
||||||
assert!(matches!(Vault::open(&new, &p), Err(Error::NeedTwoFactors)));
|
assert!(matches!(Vault::open(&new, &p), Err(Error::NeedTwoFactors)));
|
||||||
let back = open(&new, Unlock::Password(&p), Unlock::Material(FactorKind::Device, &DEVICE)).unwrap();
|
let back = open(&new, Unlock::Password(&p), Unlock::Material(FactorKind::Device, &DEVICE)).unwrap();
|
||||||
assert_eq!(back.items().len(), 1);
|
assert_eq!(back.items().len(), 1);
|
||||||
@@ -206,3 +211,31 @@ fn the_key_pair_item_type_round_trips() {
|
|||||||
let item = back.items().iter().find(|i| i.kind == ItemType::KeyPair).unwrap();
|
let item = back.items().iter().find(|i| i.kind == ItemType::KeyPair).unwrap();
|
||||||
assert!(item.fields.iter().any(|f| f.name == "private-key" && f.secret));
|
assert!(item.fields.iter().any(|f| f.name == "private-key" && f.secret));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn factors_on_one_device_never_open_together() {
|
||||||
|
let mut v = two_factor_vault();
|
||||||
|
let passkey = v.add_factor(Unlock::Material(FactorKind::Passkey, &PHONE), "Phone passkey").unwrap();
|
||||||
|
let approval = [12u8; 32];
|
||||||
|
v.add_factor_apart(Unlock::Material(FactorKind::Approval, &approval), "Phone", &[&passkey]).unwrap();
|
||||||
|
let bytes = v.to_bytes().unwrap();
|
||||||
|
let phone = Unlock::Material(FactorKind::Passkey, &PHONE);
|
||||||
|
let phone_approval = Unlock::Material(FactorKind::Approval, &approval);
|
||||||
|
assert!(matches!(open(&bytes, phone, phone_approval), Err(Error::SameDevice)));
|
||||||
|
assert!(matches!(open(&bytes, phone_approval, phone), Err(Error::SameDevice)));
|
||||||
|
// Each still pairs with everything else.
|
||||||
|
let p = pw("Orbit7-Fable3");
|
||||||
|
assert!(open(&bytes, Unlock::Password(&p), phone).is_ok());
|
||||||
|
assert!(open(&bytes, Unlock::Password(&p), phone_approval).is_ok());
|
||||||
|
assert!(open(&bytes, Unlock::Material(FactorKind::Device, &DEVICE), phone_approval).is_ok());
|
||||||
|
// A factor added later pairs with both.
|
||||||
|
let mut v = open(&bytes, Unlock::Password(&p), phone).unwrap();
|
||||||
|
v.add_factor(Unlock::Material(FactorKind::Totp, &TOTP), "TOTP backup").unwrap();
|
||||||
|
let bytes = v.to_bytes().unwrap();
|
||||||
|
assert!(open(&bytes, Unlock::Material(FactorKind::Totp, &TOTP), phone_approval).is_ok());
|
||||||
|
// Only existing factors can be named.
|
||||||
|
assert!(matches!(
|
||||||
|
v.add_factor_apart(Unlock::Material(FactorKind::Device, &[13; 32]), "x", &["00112233445566778899aabbccddeeff"]),
|
||||||
|
Err(Error::FactorRejected)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ custos-vault = { path = "../custos-vault" }
|
|||||||
custos-share = { path = "../custos-share" }
|
custos-share = { path = "../custos-share" }
|
||||||
custos-totp = { path = "../custos-totp" }
|
custos-totp = { path = "../custos-totp" }
|
||||||
custos-qr = { path = "../custos-qr" }
|
custos-qr = { path = "../custos-qr" }
|
||||||
|
custos-seal = { path = "../custos-seal" }
|
||||||
serde.workspace = true
|
serde.workspace = true
|
||||||
serde_json.workspace = true
|
serde_json.workspace = true
|
||||||
data-encoding.workspace = true
|
data-encoding.workspace = true
|
||||||
|
|||||||
@@ -16,9 +16,15 @@
|
|||||||
//! Requests are `{"op": …, …}`; responses `{"ok": true, …}` or `{"ok": false, "error": "<message>"}`.
|
//! Requests are `{"op": …, …}`; responses `{"ok": true, …}` or `{"ok": false, "error": "<message>"}`.
|
||||||
//! See [`handle`] for the operations. One vault at a time is held here while unlocked; `lock` drops it
|
//! See [`handle`] for the operations. One vault at a time is held here while unlocked; `lock` drops it
|
||||||
//! (and with it the key, wiped).
|
//! (and with it the key, wiped).
|
||||||
|
//!
|
||||||
|
//! Two factors (docs/FACTORS.md, docs/SEAL.md): the page asks for a one-time key (`recipient`), sends its
|
||||||
|
//! public half to the factor service, and passes the sealed answer back in `open_with`. The key's secret
|
||||||
|
//! half never leaves this module. A paired phone keeps its approval material wrapped with its passkey's
|
||||||
|
//! PRF output (`phone_enrol`, `phone_approve`); unwrapped, it exists only inside one call.
|
||||||
|
|
||||||
|
use custos_seal::Recipient;
|
||||||
use custos_share::{Payload, ShareError};
|
use custos_share::{Payload, ShareError};
|
||||||
use custos_vault::{Item, ItemType, SecretString, Vault};
|
use custos_vault::{FactorKind, Item, ItemType, SecretString, Unlock, Vault};
|
||||||
use data_encoding::BASE64;
|
use data_encoding::BASE64;
|
||||||
use qrcode::render::svg;
|
use qrcode::render::svg;
|
||||||
use qrcode::{EcLevel, QrCode};
|
use qrcode::{EcLevel, QrCode};
|
||||||
@@ -29,6 +35,24 @@ use zeroize::Zeroizing;
|
|||||||
|
|
||||||
thread_local! {
|
thread_local! {
|
||||||
static VAULT: RefCell<Option<Vault>> = const { RefCell::new(None) };
|
static VAULT: RefCell<Option<Vault>> = const { RefCell::new(None) };
|
||||||
|
/// One-time keys waiting for a sealed answer, by their public key (base64). Each is used once.
|
||||||
|
static RECIPIENTS: RefCell<Vec<(String, Recipient)>> = const { RefCell::new(Vec::new()) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// At most this many one-time keys wait at once; the oldest goes first.
|
||||||
|
const MAX_RECIPIENTS: usize = 8;
|
||||||
|
/// The at-rest context of a phone's approval material, wrapped with its passkey's PRF output.
|
||||||
|
const PHONE_APPROVAL: &[u8] = b"custos phone approval v1";
|
||||||
|
|
||||||
|
/// One factor given to `open_with`.
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(tag = "kind", rename_all = "snake_case", rename_all_fields = "camelCase")]
|
||||||
|
enum FactorIn {
|
||||||
|
Password { password: SecretString },
|
||||||
|
/// A factor service's or a device's answer, sealed to a key from `recipient` (`pub`) for `context`.
|
||||||
|
Sealed { factor: FactorKind, r#pub: String, sealed: String, context: String },
|
||||||
|
/// Material the page holds itself: a passkey's PRF output (base64).
|
||||||
|
Material { factor: FactorKind, material: SecretString },
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
@@ -67,6 +91,38 @@ enum Request {
|
|||||||
fragment: String,
|
fragment: String,
|
||||||
password: Option<SecretString>,
|
password: Option<SecretString>,
|
||||||
},
|
},
|
||||||
|
/// The format version and the factors (id, type) of a vault, from its header alone.
|
||||||
|
Factors {
|
||||||
|
vault: String,
|
||||||
|
},
|
||||||
|
/// A new one-time key: `{pub, match}`.
|
||||||
|
Recipient,
|
||||||
|
/// The match code of a public key (base64), for example a requesting device's.
|
||||||
|
MatchCode {
|
||||||
|
r#pub: String,
|
||||||
|
},
|
||||||
|
/// Opens a version-2 vault with two different factors.
|
||||||
|
OpenWith {
|
||||||
|
vault: String,
|
||||||
|
factors: Vec<FactorIn>,
|
||||||
|
},
|
||||||
|
/// Pairs this phone with a PC that waits with the one-time key `pub`: makes the phone's approval
|
||||||
|
/// material and seals it with the passkey's PRF output (`prf`, base64) to the PC for `context`.
|
||||||
|
/// Returns the box, its sender code, and the material wrapped with the PRF output (`wrapped`).
|
||||||
|
PhoneEnrol {
|
||||||
|
r#pub: String,
|
||||||
|
context: String,
|
||||||
|
label: String,
|
||||||
|
prf: SecretString,
|
||||||
|
},
|
||||||
|
/// Approves a request: unwraps this phone's approval material with the PRF output and seals it to
|
||||||
|
/// the requester's key for `context` (`approval:<factor>:<request id>`).
|
||||||
|
PhoneApprove {
|
||||||
|
wrapped: String,
|
||||||
|
prf: SecretString,
|
||||||
|
r#pub: String,
|
||||||
|
context: String,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
fn err(msg: impl ToString) -> Value {
|
fn err(msg: impl ToString) -> Value {
|
||||||
@@ -178,6 +234,48 @@ fn payload_json(p: &Payload) -> Value {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn b64(s: &str) -> Option<Zeroizing<Vec<u8>>> {
|
||||||
|
BASE64.decode(s.as_bytes()).ok().map(Zeroizing::new)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn key32(s: &SecretString) -> Option<Zeroizing<[u8; 32]>> {
|
||||||
|
let v = b64(s.expose())?;
|
||||||
|
let a: [u8; 32] = v.as_slice().try_into().ok()?;
|
||||||
|
Some(Zeroizing::new(a))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn take_recipient(public: &str) -> Option<Recipient> {
|
||||||
|
RECIPIENTS.with_borrow_mut(|r| r.iter().position(|(p, _)| p == public).map(|i| r.remove(i).1))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The material for one factor; a password stays a password.
|
||||||
|
enum Given {
|
||||||
|
Password(SecretString),
|
||||||
|
Material(FactorKind, Zeroizing<Vec<u8>>),
|
||||||
|
}
|
||||||
|
|
||||||
|
fn given(f: FactorIn) -> Result<Given, String> {
|
||||||
|
match f {
|
||||||
|
FactorIn::Password { password } => Ok(Given::Password(password)),
|
||||||
|
FactorIn::Material { factor, material } => {
|
||||||
|
Ok(Given::Material(factor, b64(material.expose()).ok_or("A malformed factor.")?))
|
||||||
|
}
|
||||||
|
FactorIn::Sealed { factor, r#pub, sealed, context } => {
|
||||||
|
let me = take_recipient(&r#pub).ok_or("That request expired. Ask again.")?;
|
||||||
|
let sealed = b64(&sealed).ok_or("A malformed answer.")?;
|
||||||
|
let m = me.open(&sealed, context.as_bytes()).map_err(|e| e.to_string())?;
|
||||||
|
Ok(Given::Material(factor, m))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unlock(g: &Given) -> Unlock<'_> {
|
||||||
|
match g {
|
||||||
|
Given::Password(p) => Unlock::Password(p),
|
||||||
|
Given::Material(k, m) => Unlock::Material(*k, m),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn share_error(e: ShareError) -> Value {
|
fn share_error(e: ShareError) -> Value {
|
||||||
json!({ "ok": false, "error": e.to_string(), "code": format!("{e:?}") })
|
json!({ "ok": false, "error": e.to_string(), "code": format!("{e:?}") })
|
||||||
}
|
}
|
||||||
@@ -254,6 +352,81 @@ pub fn handle(request: &[u8]) -> Value {
|
|||||||
Err(e) => share_error(e),
|
Err(e) => share_error(e),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Request::Factors { vault } => {
|
||||||
|
let Some(bytes) = b64(&vault) else { return err("The vault file is damaged.") };
|
||||||
|
match (Vault::version_of(&bytes), Vault::factor_ids(&bytes)) {
|
||||||
|
(Ok(version), Ok(ids)) => json!({
|
||||||
|
"ok": true,
|
||||||
|
"version": version,
|
||||||
|
"factors": ids.iter().map(|(id, kind)| json!({ "id": id, "kind": kind })).collect::<Vec<_>>(),
|
||||||
|
}),
|
||||||
|
(Err(e), _) | (_, Err(e)) => err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Request::Recipient => {
|
||||||
|
let me = Recipient::generate();
|
||||||
|
let public = BASE64.encode(&me.public());
|
||||||
|
let code = me.match_code();
|
||||||
|
RECIPIENTS.with_borrow_mut(|r| {
|
||||||
|
if r.len() >= MAX_RECIPIENTS {
|
||||||
|
r.remove(0);
|
||||||
|
}
|
||||||
|
r.push((public.clone(), me));
|
||||||
|
});
|
||||||
|
json!({ "ok": true, "pub": public, "match": code })
|
||||||
|
}
|
||||||
|
Request::MatchCode { r#pub } => match b64(&r#pub) {
|
||||||
|
Some(p) if p.len() == 32 => json!({ "ok": true, "match": custos_seal::match_code(&p) }),
|
||||||
|
_ => err("Not a valid public key."),
|
||||||
|
},
|
||||||
|
Request::OpenWith { vault, factors } => {
|
||||||
|
let Some(bytes) = b64(&vault) else { return err("The vault file is damaged.") };
|
||||||
|
let mut factors = factors.into_iter();
|
||||||
|
let (Some(a), Some(b), None) = (factors.next(), factors.next(), factors.next()) else {
|
||||||
|
return err("Choose two different factors.");
|
||||||
|
};
|
||||||
|
let (a, b) = match (given(a), given(b)) {
|
||||||
|
(Ok(a), Ok(b)) => (a, b),
|
||||||
|
(Err(e), _) | (_, Err(e)) => return err(e),
|
||||||
|
};
|
||||||
|
match Vault::open_with(&bytes, unlock(&a), unlock(&b)) {
|
||||||
|
Ok(v) => {
|
||||||
|
let out = items(&v);
|
||||||
|
VAULT.set(Some(v));
|
||||||
|
out
|
||||||
|
}
|
||||||
|
Err(e) => err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Request::PhoneEnrol { r#pub, context, label, prf } => {
|
||||||
|
let (Some(public), Some(prf_key)) = (b64(&r#pub), key32(&prf)) else { return err("A malformed request.") };
|
||||||
|
let material = custos_seal::random_bytes();
|
||||||
|
let plain = Zeroizing::new(
|
||||||
|
json!({ "label": label, "passkey": prf.expose(), "approval": BASE64.encode(material.as_ref()) })
|
||||||
|
.to_string(),
|
||||||
|
);
|
||||||
|
match custos_seal::seal(&public, context.as_bytes(), plain.as_bytes()) {
|
||||||
|
Ok(sealed) => json!({
|
||||||
|
"ok": true,
|
||||||
|
"code": custos_seal::sender_code(&sealed).unwrap_or_default(),
|
||||||
|
"sealed": BASE64.encode(&sealed),
|
||||||
|
"wrapped": BASE64.encode(&custos_seal::seal_at_rest(&prf_key, PHONE_APPROVAL, material.as_ref())),
|
||||||
|
}),
|
||||||
|
Err(e) => err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Request::PhoneApprove { wrapped, prf, r#pub, context } => {
|
||||||
|
let (Some(wrapped), Some(prf_key), Some(public)) = (b64(&wrapped), key32(&prf), b64(&r#pub)) else {
|
||||||
|
return err("A malformed request.");
|
||||||
|
};
|
||||||
|
let Ok(material) = custos_seal::open_at_rest(&prf_key, PHONE_APPROVAL, &wrapped) else {
|
||||||
|
return err("This passkey does not belong to this phone's pairing.");
|
||||||
|
};
|
||||||
|
match custos_seal::seal(&public, context.as_bytes(), &material) {
|
||||||
|
Ok(sealed) => json!({ "ok": true, "sealed": BASE64.encode(&sealed) }),
|
||||||
|
Err(e) => err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
//! Two factors in the browser: opening a version-2 vault with a sealed answer or a passkey's PRF output,
|
||||||
|
//! and a phone's pairing and approvals (docs/FACTORS.md, docs/SEAL.md).
|
||||||
|
|
||||||
|
use custos_seal::Recipient;
|
||||||
|
use custos_vault::{FactorKind, Item, ItemType, KdfParams, SecretString, Unlock, Vault};
|
||||||
|
use data_encoding::BASE64;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
|
||||||
|
const PASSWORD: &str = "Test4-Vault7-Only2";
|
||||||
|
const SECRET: &str = "s3cret-Ž!";
|
||||||
|
|
||||||
|
fn call(v: Value) -> Value {
|
||||||
|
custos_wasm::handle(v.to_string().as_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A version-2 vault: the master password and a TOTP factor with `totp` as its material.
|
||||||
|
fn vault(totp: &[u8]) -> Vault {
|
||||||
|
let pw = SecretString::from(PASSWORD);
|
||||||
|
let mut v = Vault::create_with(Unlock::Password(&pw), "Master password", Unlock::Material(FactorKind::Totp, totp), "TOTP", FAST)
|
||||||
|
.unwrap();
|
||||||
|
let mut login = Item::new(ItemType::WebLogin, "GitHub", 0);
|
||||||
|
login.set("password", SECRET, 0);
|
||||||
|
v.add(login);
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
fn b64(v: &Vault) -> String {
|
||||||
|
BASE64.encode(&v.to_bytes().unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn factors_from_the_header() {
|
||||||
|
let v = vault(&[3; 32]);
|
||||||
|
let r = call(json!({ "op": "factors", "vault": b64(&v) }));
|
||||||
|
assert_eq!(r["version"], 2, "{r}");
|
||||||
|
let kinds: Vec<&str> = r["factors"].as_array().unwrap().iter().map(|f| f["kind"].as_str().unwrap()).collect();
|
||||||
|
assert_eq!(kinds, ["password", "totp"]);
|
||||||
|
let totp = v.factors().into_iter().find(|f| f.kind == FactorKind::Totp).unwrap();
|
||||||
|
assert_eq!(r["factors"][1]["id"], totp.id.as_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn open_with_password_and_a_sealed_totp_release() {
|
||||||
|
let material = [3u8; 32];
|
||||||
|
let v = vault(&material);
|
||||||
|
let file = b64(&v);
|
||||||
|
let totp = v.factors().into_iter().find(|f| f.kind == FactorKind::Totp).unwrap().id;
|
||||||
|
let context = format!("totp:{totp}");
|
||||||
|
|
||||||
|
let me = call(json!({ "op": "recipient" }));
|
||||||
|
let public = BASE64.decode(me["pub"].as_str().unwrap().as_bytes()).unwrap();
|
||||||
|
assert_eq!(me["match"], custos_seal::match_code(&public));
|
||||||
|
// What the factor service sends back after a valid code.
|
||||||
|
let sealed = BASE64.encode(&custos_seal::seal(&public, context.as_bytes(), &material).unwrap());
|
||||||
|
let sealed_in = |ctx: &str| json!({ "kind": "sealed", "factor": "totp", "pub": me["pub"], "sealed": sealed, "context": ctx });
|
||||||
|
let password = json!({ "kind": "password", "password": PASSWORD });
|
||||||
|
|
||||||
|
// Only the right context opens it.
|
||||||
|
let wrong = call(json!({ "op": "open_with", "vault": file, "factors": [password, sealed_in("totp:other")] }));
|
||||||
|
assert_eq!(wrong["ok"], false);
|
||||||
|
// The key is used once, even when the answer was refused.
|
||||||
|
let again = call(json!({ "op": "open_with", "vault": file, "factors": [password, sealed_in(&context)] }));
|
||||||
|
assert_eq!(again["error"], "That request expired. Ask again.");
|
||||||
|
|
||||||
|
let me = call(json!({ "op": "recipient" }));
|
||||||
|
let public = BASE64.decode(me["pub"].as_str().unwrap().as_bytes()).unwrap();
|
||||||
|
let sealed = BASE64.encode(&custos_seal::seal(&public, context.as_bytes(), &material).unwrap());
|
||||||
|
let ok = call(json!({ "op": "open_with", "vault": file, "factors": [
|
||||||
|
{ "kind": "sealed", "factor": "totp", "pub": me["pub"], "sealed": sealed, "context": context },
|
||||||
|
password,
|
||||||
|
]}));
|
||||||
|
assert_eq!(ok["ok"], true, "{ok}");
|
||||||
|
assert_eq!(ok["items"].as_array().unwrap().len(), 1);
|
||||||
|
assert!(!ok.to_string().contains(SECRET));
|
||||||
|
call(json!({ "op": "lock" }));
|
||||||
|
|
||||||
|
// One factor, or the same one twice, never opens it.
|
||||||
|
for factors in [json!([password]), json!([password, password])] {
|
||||||
|
let r = call(json!({ "op": "open_with", "vault": file, "factors": factors }));
|
||||||
|
assert_eq!(r["ok"], false, "{r}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_phone_pairs_then_opens_and_approves() {
|
||||||
|
let mut v = vault(&[3; 32]);
|
||||||
|
let prf = [9u8; 32];
|
||||||
|
let prf64 = BASE64.encode(&prf);
|
||||||
|
|
||||||
|
// The PC waits with a one-time key; the phone seals its pairing to it.
|
||||||
|
let pc = Recipient::generate();
|
||||||
|
let context = "pair:abc";
|
||||||
|
let r = call(json!({ "op": "phone_enrol", "pub": BASE64.encode(&pc.public()), "context": context, "label": "Phone", "prf": prf64 }));
|
||||||
|
assert_eq!(r["ok"], true, "{r}");
|
||||||
|
let sealed = BASE64.decode(r["sealed"].as_str().unwrap().as_bytes()).unwrap();
|
||||||
|
assert_eq!(r["code"], custos_seal::sender_code(&sealed).unwrap(), "the PC checks the code the phone shows");
|
||||||
|
assert!(pc.open(&sealed, b"pair:other").is_err());
|
||||||
|
let plain: Value = serde_json::from_slice(&pc.open(&sealed, context.as_bytes()).unwrap()).unwrap();
|
||||||
|
assert_eq!((plain["label"].as_str(), plain["passkey"].as_str()), (Some("Phone"), Some(prf64.as_str())));
|
||||||
|
let approval = BASE64.decode(plain["approval"].as_str().unwrap().as_bytes()).unwrap();
|
||||||
|
assert_eq!(approval.len(), 32);
|
||||||
|
let wrapped = r["wrapped"].as_str().unwrap();
|
||||||
|
assert!(!r.to_string().contains(plain["approval"].as_str().unwrap()), "the material leaves only sealed or wrapped");
|
||||||
|
|
||||||
|
// The PC adds both factors.
|
||||||
|
let passkey_id = v.add_factor(Unlock::Material(FactorKind::Passkey, &prf), "Phone passkey").unwrap();
|
||||||
|
let approval_id = v.add_factor_apart(Unlock::Material(FactorKind::Approval, &approval), "Phone", &[&passkey_id]).unwrap();
|
||||||
|
let file = b64(&v);
|
||||||
|
|
||||||
|
// The phone opens it with its passkey and the master password.
|
||||||
|
let r = call(json!({ "op": "open_with", "vault": file, "factors": [
|
||||||
|
{ "kind": "material", "factor": "passkey", "material": prf64 },
|
||||||
|
{ "kind": "password", "password": PASSWORD },
|
||||||
|
]}));
|
||||||
|
assert_eq!(r["ok"], true, "{r}");
|
||||||
|
call(json!({ "op": "lock" }));
|
||||||
|
// Its two factors never open it together.
|
||||||
|
let me = call(json!({ "op": "recipient" }));
|
||||||
|
let public = BASE64.decode(me["pub"].as_str().unwrap().as_bytes()).unwrap();
|
||||||
|
let sealed = BASE64.encode(&custos_seal::seal(&public, b"approval:x:y", &approval).unwrap());
|
||||||
|
let r = call(json!({ "op": "open_with", "vault": file, "factors": [
|
||||||
|
{ "kind": "material", "factor": "passkey", "material": prf64 },
|
||||||
|
{ "kind": "sealed", "factor": "approval", "pub": me["pub"], "sealed": sealed, "context": "approval:x:y" },
|
||||||
|
]}));
|
||||||
|
assert_eq!(r["error"], "these two factors are kept on the same device; use one of them with another factor");
|
||||||
|
|
||||||
|
// The PC asks the phone; the phone approves with its passkey.
|
||||||
|
let requester = Recipient::generate();
|
||||||
|
let req_pub = BASE64.encode(&requester.public());
|
||||||
|
assert_eq!(call(json!({ "op": "match_code", "pub": req_pub }))["match"], requester.match_code());
|
||||||
|
let ctx = format!("approval:{approval_id}:r1");
|
||||||
|
let wrong_key = call(json!({ "op": "phone_approve", "wrapped": wrapped, "prf": BASE64.encode(&[8u8; 32]), "pub": req_pub, "context": ctx }));
|
||||||
|
assert_eq!(wrong_key["ok"], false);
|
||||||
|
let r = call(json!({ "op": "phone_approve", "wrapped": wrapped, "prf": prf64, "pub": req_pub, "context": ctx }));
|
||||||
|
let sealed = BASE64.decode(r["sealed"].as_str().unwrap().as_bytes()).unwrap();
|
||||||
|
let m = requester.open(&sealed, ctx.as_bytes()).unwrap();
|
||||||
|
let pw = SecretString::from(PASSWORD);
|
||||||
|
assert!(Vault::open_with(&v.to_bytes().unwrap(), Unlock::Password(&pw), Unlock::Material(FactorKind::Approval, &m)).is_ok());
|
||||||
|
}
|
||||||
@@ -89,6 +89,35 @@ slot, then the body.
|
|||||||
| Both unwrap, but their pair slot is missing or fails | `Corrupted` |
|
| Both unwrap, but their pair slot is missing or fails | `Corrupted` |
|
||||||
| A machine store: its one device factor unwraps, then the single slot | — |
|
| A machine store: its one device factor unwraps, then the single slot | — |
|
||||||
|
|
||||||
|
## Which factors a file has
|
||||||
|
|
||||||
|
`Vault::factor_ids(bytes)` reads the header alone and returns each factor's id and type. No key is needed,
|
||||||
|
because ids and types are not secret. The app uses them to ask the TOTP service or a paired device for a
|
||||||
|
factor. Those services pass material through a mailbox they cannot read; see `docs/SEAL.md`.
|
||||||
|
|
||||||
|
## In the browser and on a phone
|
||||||
|
|
||||||
|
`custos-wasm` opens a version-2 vault with any two factors (`open_with`). A factor that comes from the
|
||||||
|
factor service or from another device arrives as a box sealed to a one-time key the module made
|
||||||
|
(`recipient`); the key's secret half never leaves WebAssembly memory and is used once.
|
||||||
|
|
||||||
|
**Pairing a phone** gives the vault two factors at once, both added by the PC (which writes the file):
|
||||||
|
1. The PC waits with a one-time key and shows its match code; the phone shows the same code.
|
||||||
|
2. On the phone, a passkey is created and evaluated with the WebAuthn PRF extension
|
||||||
|
(salt `SHA-256("custos passkey v1")`). Its 32-byte output is the **passkey** factor's material.
|
||||||
|
3. `phone_enrol` makes 32 random bytes, the phone's **approval** material, and seals both to the PC
|
||||||
|
(context `pair:<pairing id>`). The phone keeps the approval material only wrapped with the PRF output
|
||||||
|
(at-rest sealing, context `custos phone approval v1`), so stolen browser storage is not a factor.
|
||||||
|
4. The phone shows the box's sender code (`docs/SEAL.md`); the PC adds the factors only after you confirm it
|
||||||
|
shows the same code. It adds the approval factor **apart** from the passkey (`add_factor_apart`).
|
||||||
|
|
||||||
|
**Factors on one device never pair.** `add_factor_apart` writes no pair slot between the new factor and the
|
||||||
|
ones named, so those two open nothing together (`Error::SameDevice`) while each still pairs with every other
|
||||||
|
factor. A phone's passkey and its approval key, or a PC's device key and its approval key, are added apart.
|
||||||
|
|
||||||
|
`phone_approve` unwraps the approval material with a fresh PRF output (Face ID, Touch ID) and seals it to a
|
||||||
|
requesting device, for `approval:<factor id>:<request id>`. The material exists unwrapped only inside that call.
|
||||||
|
|
||||||
## Body
|
## Body
|
||||||
|
|
||||||
`"format": 2`, and a `factors` list next to `items`:
|
`"format": 2`, and a `factors` list next to `items`:
|
||||||
|
|||||||
@@ -36,3 +36,26 @@ Each gives:
|
|||||||
- `fingerprint`: `SHA256:…`, exactly as `ssh-keygen -l` prints it.
|
- `fingerprint`: `SHA256:…`, exactly as `ssh-keygen -l` prints it.
|
||||||
|
|
||||||
The crates are RustCrypto's: `ssh-key`, `ed25519-dalek` (its Ed25519 backend), `p256`, `rsa`.
|
The crates are RustCrypto's: `ssh-key`, `ed25519-dalek` (its Ed25519 backend), `p256`, `rsa`.
|
||||||
|
|
||||||
|
## Importing (`custos_keys::import`)
|
||||||
|
|
||||||
|
An existing private key becomes the same kind of item. Accepted formats:
|
||||||
|
|
||||||
|
| Input | Header | Algorithms |
|
||||||
|
|:--|:--|:--|
|
||||||
|
| OpenSSH private key | `BEGIN OPENSSH PRIVATE KEY` | Ed25519, ECDSA P-256, RSA |
|
||||||
|
| PKCS#8 | `BEGIN PRIVATE KEY` | Ed25519, ECDSA P-256, RSA |
|
||||||
|
| PKCS#1 | `BEGIN RSA PRIVATE KEY` | RSA |
|
||||||
|
| SEC1 | `BEGIN EC PRIVATE KEY` | ECDSA P-256 |
|
||||||
|
|
||||||
|
- **The public line, the PEMs and the fingerprint are derived from the private key**, never copied from the
|
||||||
|
input. A pasted public key therefore cannot disagree with its private key.
|
||||||
|
- **RSA:** 2048 to 4096 bits. An imported 2048-bit key is named `rsa-2048`; Custos never generates one.
|
||||||
|
- **A passphrase-protected key is refused** (`Encrypted`): OpenSSH with a cipher, `ENCRYPTED PRIVATE KEY`,
|
||||||
|
or PKCS#1 with `Proc-Type: 4,ENCRYPTED`. Remove the passphrase first (`ssh-keygen -p`); the vault is the
|
||||||
|
key's encryption.
|
||||||
|
- **Comment:** an OpenSSH key keeps its own comment; the other formats take the item's name.
|
||||||
|
- **Line ends:** CRLF and surrounding whitespace are accepted, as in a paste or a Windows file.
|
||||||
|
- **Errors never repeat the input.**
|
||||||
|
- **ssh-key 0.6.7 conversion bug:** its `TryFrom<&RsaKeypair> for rsa::RsaPrivateKey` uses `p` twice. Custos
|
||||||
|
rebuilds the key from `n, e, d, p, q` and validates it instead.
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
# Sealed boxes (`custos-seal`)
|
||||||
|
|
||||||
|
The two-factor services (`docs/FACTORS.md`, types 3 and 4) pass factor material through a mailbox on the
|
||||||
|
home server. The mailbox must never be able to read it. So the device that wants a secret makes a
|
||||||
|
**one-time X25519 key pair**, sends only the public half, and whoever releases the secret seals it to that
|
||||||
|
key. The same box carries a secret from the user's PC to a Claude Code cloud session.
|
||||||
|
|
||||||
|
## The box, version 1
|
||||||
|
|
||||||
|
```
|
||||||
|
sealed = "CSL1" ‖ E (32) ‖ nonce (24) ‖ XChaCha20-Poly1305(K, nonce, plaintext, aad)
|
||||||
|
|
||||||
|
E the sender's ephemeral X25519 public key (a fresh one per box)
|
||||||
|
R the recipient's one-time public key
|
||||||
|
K HKDF-SHA256(ikm = X25519(e, R), salt = E ‖ R, info = "custos seal v1" ‖ context)
|
||||||
|
aad "CSL1" ‖ E ‖ context
|
||||||
|
```
|
||||||
|
|
||||||
|
- **`context`** names the purpose, for example `approval:<factor id>:<request id>` or `cloud:<request id>`.
|
||||||
|
A box opens only with the context it was sealed for, so a box for one request does not work as another.
|
||||||
|
- **A low-order public key is refused** on both sides: the shared secret must be contributory.
|
||||||
|
- **Plaintext limit:** 32 KiB.
|
||||||
|
- **The recipient's secret half** lives only in memory, as `x25519_dalek::StaticSecret` with `zeroize`,
|
||||||
|
and is wiped on drop. Nothing writes it to disk.
|
||||||
|
|
||||||
|
## The match code
|
||||||
|
|
||||||
|
Six digits that the requesting screen and the approving screen both show:
|
||||||
|
|
||||||
|
```
|
||||||
|
match = u32_be(SHA-256("custos match v1" ‖ R)[0..4]) mod 1 000 000, zero-padded to 6 digits
|
||||||
|
```
|
||||||
|
|
||||||
|
If they differ, someone else's request is waiting: deny it. The code is not a secret. It only ties the
|
||||||
|
approval to the key the box is sealed for.
|
||||||
|
|
||||||
|
Test vector: R = `07` × 32 → `684361`.
|
||||||
|
|
||||||
|
### The sender code
|
||||||
|
|
||||||
|
The match code of a box's ephemeral key E (`sender_code`). When the receiver must know who sealed a box,
|
||||||
|
as when a PC adds a phone's factors, the sealing screen shows this code and the receiving screen asks the
|
||||||
|
person to confirm it. E is fresh for every box, so each box has its own code.
|
||||||
|
|
||||||
|
## At rest
|
||||||
|
|
||||||
|
The factor service keeps each TOTP share sealed with its own key, which comes from a systemd credential
|
||||||
|
that is not in its state directory:
|
||||||
|
|
||||||
|
```
|
||||||
|
at rest = "CSR1" ‖ nonce (24) ‖ XChaCha20-Poly1305(HKDF-SHA256(key, salt = "", info = "custos rest v1" ‖ context),
|
||||||
|
nonce, plaintext, "CSR1" ‖ context)
|
||||||
|
```
|
||||||
|
|
||||||
|
What this protects: a leaked copy of `/var/lib/custos-factors` without the credential gives nothing.
|
||||||
|
What it does not protect: anyone who controls the running server. That is one factor, which is why a
|
||||||
|
factor is never enough alone.
|
||||||
|
|
||||||
|
## Crates
|
||||||
|
|
||||||
|
`x25519-dalek` 2 (dalek-cryptography, the X25519 sibling of the `ed25519-dalek` used for key pairs),
|
||||||
|
`chacha20poly1305`, `hkdf`, `sha2`, and `rand`'s `SysRng`.
|
||||||
@@ -58,6 +58,16 @@ just as plainly, what it does not.
|
|||||||
revealed or copied value passes through JavaScript strings, which cannot be wiped. Lock (or close the tab)
|
revealed or copied value passes through JavaScript strings, which cannot be wiped. Lock (or close the tab)
|
||||||
when done.
|
when done.
|
||||||
|
|
||||||
|
- **The factor service holds one factor.** It releases the TOTP factor after a valid code, so whoever
|
||||||
|
controls the home server has that factor. It is one factor, never enough alone. Approval material and
|
||||||
|
cloud secrets pass through it only as sealed boxes (`docs/SEAL.md`), which it cannot open.
|
||||||
|
- **A paired phone's browser storage** holds its approval material wrapped with the passkey's PRF output,
|
||||||
|
which the authenticator gives only after Face ID or Touch ID. The passkey and the approval key are added
|
||||||
|
apart (docs/FACTORS.md), so the phone alone is one device and opens nothing: it still needs the master
|
||||||
|
password, the TOTP code or a PC.
|
||||||
|
- **An approval is only as careful as the person approving.** Compare the six-digit match code on both
|
||||||
|
screens; a request you did not start is someone else's.
|
||||||
|
|
||||||
## Design rules that follow from this
|
## Design rules that follow from this
|
||||||
|
|
||||||
- No custom cryptography: Argon2id (`argon2`), XChaCha20-Poly1305 (`chacha20poly1305`), the OS CSPRNG
|
- No custom cryptography: Argon2id (`argon2`), XChaCha20-Poly1305 (`chacha20poly1305`), the OS CSPRNG
|
||||||
|
|||||||
Reference in New Issue
Block a user