| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
use crate::cbor::{self, Value}; |
| 8 |
use crate::hash::{hash_object, KeyId, ObjectRef, ObjectType}; |
| 9 |
use crate::objects::{ |
| 10 |
array, bytes, check_version, field, oref, text, uint, ObjectError, FORMAT_VERSION, |
| 11 |
}; |
| 12 |
use ed25519_dalek::ed25519::signature::Signer as _; |
| 13 |
use ed25519_dalek::{ |
| 14 |
Signature as EdSignature, SigningKey as EdSigningKey, VerifyingKey as EdVerifyingKey, |
| 15 |
}; |
| 16 |
use ml_dsa::{ |
| 17 |
EncodedSignature, EncodedVerifyingKey, MlDsa65, Seed, Signature as MlSignature, |
| 18 |
SigningKey as MlSigningKey, VerifyingKey as MlVerifyingKey, |
| 19 |
}; |
| 20 |
use rand::RngCore; |
| 21 |
|
| 22 |
pub const ED25519_PK_LEN: usize = 32; |
| 23 |
pub const MLDSA65_PK_LEN: usize = 1952; |
| 24 |
pub const ED25519_SIG_LEN: usize = 64; |
| 25 |
pub const MLDSA65_SIG_LEN: usize = 3309; |
| 26 |
|
| 27 |
pub const ALG_COMPOSITE: u64 = 1; |
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 34 |
pub struct Scope(u8); |
| 35 |
|
| 36 |
impl Scope { |
| 37 |
pub const NONE: Scope = Scope(0); |
| 38 |
pub const CHANGES: Scope = Scope(1); |
| 39 |
pub const REFS: Scope = Scope(2); |
| 40 |
pub const SEAL: Scope = Scope(4); |
| 41 |
|
| 42 |
pub const ALL: Scope = Scope(7); |
| 43 |
const NAMES: [(Scope, &'static str); 3] = [ |
| 44 |
(Scope::CHANGES, "changes"), |
| 45 |
(Scope::REFS, "refs"), |
| 46 |
(Scope::SEAL, "seal"), |
| 47 |
]; |
| 48 |
|
| 49 |
pub fn has(self, other: Scope) -> bool { |
| 50 |
self.0 & other.0 == other.0 |
| 51 |
} |
| 52 |
pub fn is_empty(self) -> bool { |
| 53 |
self.0 == 0 |
| 54 |
} |
| 55 |
|
| 56 |
pub fn names(self) -> Vec<&'static str> { |
| 57 |
Self::NAMES |
| 58 |
.iter() |
| 59 |
.filter(|(s, _)| self.has(*s)) |
| 60 |
.map(|(_, n)| *n) |
| 61 |
.collect() |
| 62 |
} |
| 63 |
fn named(name: &str) -> Option<Scope> { |
| 64 |
Self::NAMES |
| 65 |
.iter() |
| 66 |
.find(|(_, n)| *n == name) |
| 67 |
.map(|(s, _)| *s) |
| 68 |
} |
| 69 |
|
| 70 |
pub fn parse(s: &str) -> Result<Scope, String> { |
| 71 |
let mut out = Scope::NONE; |
| 72 |
for part in s.split(',').map(str::trim).filter(|p| !p.is_empty()) { |
| 73 |
if part == "all" { |
| 74 |
return Ok(Scope::ALL); |
| 75 |
} |
| 76 |
match Self::named(part) { |
| 77 |
Some(sc) => out = out | sc, |
| 78 |
None => return Err(format!("unknown scope {part:?}: use changes, refs or seal")), |
| 79 |
} |
| 80 |
} |
| 81 |
if out.is_empty() { |
| 82 |
return Err("a delegate needs at least one scope: changes, refs or seal".into()); |
| 83 |
} |
| 84 |
Ok(out) |
| 85 |
} |
| 86 |
} |
| 87 |
|
| 88 |
impl std::ops::BitOr for Scope { |
| 89 |
type Output = Scope; |
| 90 |
fn bitor(self, rhs: Scope) -> Scope { |
| 91 |
Scope(self.0 | rhs.0) |
| 92 |
} |
| 93 |
} |
| 94 |
|
| 95 |
impl std::fmt::Display for Scope { |
| 96 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 97 |
f.write_str(&self.names().join(",")) |
| 98 |
} |
| 99 |
} |
| 100 |
|
| 101 |
impl std::fmt::Debug for Scope { |
| 102 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 103 |
write!(f, "Scope({self})") |
| 104 |
} |
| 105 |
} |
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
#[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 110 |
pub struct Delegate { |
| 111 |
pub key: KeyId, |
| 112 |
pub scope: Scope, |
| 113 |
pub expires: Option<u64>, |
| 114 |
} |
| 115 |
|
| 116 |
impl Delegate { |
| 117 |
|
| 118 |
pub fn full(key: KeyId) -> Delegate { |
| 119 |
Delegate { |
| 120 |
key, |
| 121 |
scope: Scope::ALL, |
| 122 |
expires: None, |
| 123 |
} |
| 124 |
} |
| 125 |
|
| 126 |
pub fn allows(&self, scope: Scope, at_ms: u64) -> bool { |
| 127 |
self.scope.has(scope) && !self.expires.is_some_and(|e| at_ms > e) |
| 128 |
} |
| 129 |
fn to_value(self) -> Value { |
| 130 |
Value::map([ |
| 131 |
(0, Value::Bytes(self.key.0.to_vec())), |
| 132 |
( |
| 133 |
1, |
| 134 |
Value::Array( |
| 135 |
self.scope |
| 136 |
.names() |
| 137 |
.into_iter() |
| 138 |
.map(|n| Value::Text(n.to_string())) |
| 139 |
.collect(), |
| 140 |
), |
| 141 |
), |
| 142 |
(2, self.expires.map(Value::Uint).unwrap_or(Value::Null)), |
| 143 |
]) |
| 144 |
} |
| 145 |
|
| 146 |
|
| 147 |
fn from_value(v: &Value) -> Result<Delegate, ObjectError> { |
| 148 |
if let Value::Bytes(_) = v { |
| 149 |
return Ok(Delegate::full(oref(v, "delegate")?)); |
| 150 |
} |
| 151 |
let m = v |
| 152 |
.as_map() |
| 153 |
.ok_or_else(|| ObjectError::Schema("delegate: expected map".into()))?; |
| 154 |
let key = oref(field(m, 0, "delegate key")?, "delegate key")?; |
| 155 |
let mut scope = Scope::NONE; |
| 156 |
for n in array(field(m, 1, "delegate scope")?, "delegate scope")? { |
| 157 |
let n = text(n, "delegate scope")?; |
| 158 |
scope = scope |
| 159 |
| Scope::named(n) |
| 160 |
.ok_or_else(|| ObjectError::Schema(format!("delegate: unknown scope {n:?}")))?; |
| 161 |
} |
| 162 |
let expires = match field(m, 2, "delegate expires")? { |
| 163 |
v if v.is_null() => None, |
| 164 |
v => Some(uint(v, "delegate expires")?), |
| 165 |
}; |
| 166 |
Ok(Delegate { |
| 167 |
key, |
| 168 |
scope, |
| 169 |
expires, |
| 170 |
}) |
| 171 |
} |
| 172 |
} |
| 173 |
|
| 174 |
#[derive(Clone, Debug, PartialEq, Eq)] |
| 175 |
pub struct Identity { |
| 176 |
pub ed25519_pk: [u8; ED25519_PK_LEN], |
| 177 |
pub mldsa65_pk: Vec<u8>, |
| 178 |
pub name: String, |
| 179 |
pub email: String, |
| 180 |
pub created: u64, |
| 181 |
pub expires: Option<u64>, |
| 182 |
pub previous: Option<KeyId>, |
| 183 |
pub delegates: Vec<Delegate>, |
| 184 |
} |
| 185 |
|
| 186 |
|
| 187 |
fn tidy(mut delegates: Vec<Delegate>) -> Vec<Delegate> { |
| 188 |
delegates.sort_by_key(|d| d.key); |
| 189 |
delegates.dedup_by(|a, b| a.key == b.key); |
| 190 |
delegates |
| 191 |
} |
| 192 |
|
| 193 |
impl Identity { |
| 194 |
|
| 195 |
pub fn delegate(&self, key: &KeyId) -> Option<&Delegate> { |
| 196 |
self.delegates.iter().find(|d| d.key == *key) |
| 197 |
} |
| 198 |
|
| 199 |
pub fn delegates_to(&self, key: &KeyId, scope: Scope, at_ms: u64) -> bool { |
| 200 |
self.delegate(key).is_some_and(|d| d.allows(scope, at_ms)) |
| 201 |
} |
| 202 |
pub fn to_value(&self) -> Value { |
| 203 |
Value::map([ |
| 204 |
(0, Value::Uint(FORMAT_VERSION)), |
| 205 |
(1, Value::Bytes(self.ed25519_pk.to_vec())), |
| 206 |
(2, Value::Bytes(self.mldsa65_pk.clone())), |
| 207 |
(3, Value::Text(self.name.clone())), |
| 208 |
(4, Value::Text(self.email.clone())), |
| 209 |
(5, Value::Uint(self.created)), |
| 210 |
(6, self.expires.map(Value::Uint).unwrap_or(Value::Null)), |
| 211 |
( |
| 212 |
7, |
| 213 |
self.previous |
| 214 |
.map(|p| Value::Bytes(p.0.to_vec())) |
| 215 |
.unwrap_or(Value::Null), |
| 216 |
), |
| 217 |
( |
| 218 |
8, |
| 219 |
Value::Array(self.delegates.iter().map(|d| d.to_value()).collect()), |
| 220 |
), |
| 221 |
]) |
| 222 |
} |
| 223 |
pub fn encode(&self) -> Vec<u8> { |
| 224 |
cbor::encode(&self.to_value()) |
| 225 |
} |
| 226 |
pub fn hash(&self) -> KeyId { |
| 227 |
hash_object(ObjectType::Identity, &self.encode()) |
| 228 |
} |
| 229 |
pub fn decode(b: &[u8]) -> Result<Identity, ObjectError> { |
| 230 |
let v = cbor::decode(b)?; |
| 231 |
let m = v |
| 232 |
.as_map() |
| 233 |
.ok_or_else(|| ObjectError::Schema("identity: expected map".into()))?; |
| 234 |
check_version(m)?; |
| 235 |
let ed = bytes(field(m, 1, "ed25519_pk")?, "ed25519_pk")?; |
| 236 |
let ml = bytes(field(m, 2, "mldsa65_pk")?, "mldsa65_pk")?; |
| 237 |
if ed.len() != ED25519_PK_LEN || ml.len() != MLDSA65_PK_LEN { |
| 238 |
return Err(ObjectError::Schema( |
| 239 |
"identity: wrong public key length".into(), |
| 240 |
)); |
| 241 |
} |
| 242 |
let opt_u = |v: &Value| -> Result<Option<u64>, ObjectError> { |
| 243 |
if v.is_null() { |
| 244 |
Ok(None) |
| 245 |
} else { |
| 246 |
uint(v, "expires").map(Some) |
| 247 |
} |
| 248 |
}; |
| 249 |
let opt_r = |v: &Value| -> Result<Option<KeyId>, ObjectError> { |
| 250 |
if v.is_null() { |
| 251 |
Ok(None) |
| 252 |
} else { |
| 253 |
oref(v, "previous").map(Some) |
| 254 |
} |
| 255 |
}; |
| 256 |
let delegates = tidy( |
| 257 |
array(field(m, 8, "delegates")?, "delegates")? |
| 258 |
.iter() |
| 259 |
.map(Delegate::from_value) |
| 260 |
.collect::<Result<Vec<_>, _>>()?, |
| 261 |
); |
| 262 |
Ok(Identity { |
| 263 |
ed25519_pk: ed.try_into().unwrap(), |
| 264 |
mldsa65_pk: ml.to_vec(), |
| 265 |
name: text(field(m, 3, "name")?, "name")?.to_owned(), |
| 266 |
email: text(field(m, 4, "email")?, "email")?.to_owned(), |
| 267 |
created: uint(field(m, 5, "created")?, "created")?, |
| 268 |
expires: opt_u(field(m, 6, "expires")?)?, |
| 269 |
previous: opt_r(field(m, 7, "previous")?)?, |
| 270 |
delegates, |
| 271 |
}) |
| 272 |
} |
| 273 |
|
| 274 |
|
| 275 |
pub fn is_expired_at(&self, now_ms: u64) -> bool { |
| 276 |
self.expires.is_some_and(|e| now_ms > e) |
| 277 |
} |
| 278 |
|
| 279 |
|
| 280 |
|
| 281 |
pub fn successor( |
| 282 |
&self, |
| 283 |
delegates: Vec<Delegate>, |
| 284 |
expires: Option<u64>, |
| 285 |
created: u64, |
| 286 |
) -> Identity { |
| 287 |
Identity { |
| 288 |
previous: Some(self.hash()), |
| 289 |
delegates: tidy(delegates), |
| 290 |
expires, |
| 291 |
created, |
| 292 |
..self.clone() |
| 293 |
} |
| 294 |
} |
| 295 |
|
| 296 |
|
| 297 |
pub fn verify_ed25519(&self, msg: &[u8], sig: &[u8]) -> Result<(), VerifyError> { |
| 298 |
let sig = EdSignature::from_slice(sig).map_err(|_| VerifyError::Ed25519)?; |
| 299 |
self.ed_key()? |
| 300 |
.verify_strict(msg, &sig) |
| 301 |
.map_err(|_| VerifyError::Ed25519) |
| 302 |
} |
| 303 |
|
| 304 |
fn ed_key(&self) -> Result<EdVerifyingKey, VerifyError> { |
| 305 |
EdVerifyingKey::from_bytes(&self.ed25519_pk).map_err(|_| VerifyError::BadKey) |
| 306 |
} |
| 307 |
fn ml_key(&self) -> Result<MlVerifyingKey<MlDsa65>, VerifyError> { |
| 308 |
let enc = EncodedVerifyingKey::<MlDsa65>::try_from(self.mldsa65_pk.as_slice()) |
| 309 |
.map_err(|_| VerifyError::BadKey)?; |
| 310 |
Ok(MlVerifyingKey::decode(&enc)) |
| 311 |
} |
| 312 |
} |
| 313 |
|
| 314 |
#[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 315 |
pub enum Domain { |
| 316 |
Change, |
| 317 |
Attest, |
| 318 |
Policy, |
| 319 |
|
| 320 |
|
| 321 |
Challenge, |
| 322 |
} |
| 323 |
|
| 324 |
impl Domain { |
| 325 |
pub fn name(self) -> &'static str { |
| 326 |
match self { |
| 327 |
Domain::Change => "change", |
| 328 |
Domain::Attest => "attest", |
| 329 |
Domain::Policy => "policy", |
| 330 |
Domain::Challenge => "challenge", |
| 331 |
} |
| 332 |
} |
| 333 |
} |
| 334 |
|
| 335 |
|
| 336 |
pub fn signing_message(domain: Domain, key: &KeyId, target: &ObjectRef) -> Vec<u8> { |
| 337 |
let mut m = Vec::with_capacity(80); |
| 338 |
m.extend_from_slice(b"oxy1 sig "); |
| 339 |
m.extend_from_slice(domain.name().as_bytes()); |
| 340 |
m.push(0); |
| 341 |
m.extend_from_slice(&key.0); |
| 342 |
m.extend_from_slice(&target.0); |
| 343 |
m |
| 344 |
} |
| 345 |
|
| 346 |
#[derive(Clone, PartialEq, Eq)] |
| 347 |
pub struct Signature { |
| 348 |
pub key: KeyId, |
| 349 |
pub ed: [u8; ED25519_SIG_LEN], |
| 350 |
pub ml: Vec<u8>, |
| 351 |
} |
| 352 |
|
| 353 |
impl std::fmt::Debug for Signature { |
| 354 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 355 |
write!(f, "Signature(key {:?})", self.key) |
| 356 |
} |
| 357 |
} |
| 358 |
|
| 359 |
impl Signature { |
| 360 |
pub fn to_value(&self) -> Value { |
| 361 |
Value::map([ |
| 362 |
(0, Value::Bytes(self.key.0.to_vec())), |
| 363 |
(1, Value::Uint(ALG_COMPOSITE)), |
| 364 |
(2, Value::Bytes(self.ed.to_vec())), |
| 365 |
(3, Value::Bytes(self.ml.clone())), |
| 366 |
]) |
| 367 |
} |
| 368 |
pub fn from_value(v: &Value) -> Result<Signature, ObjectError> { |
| 369 |
let m = v |
| 370 |
.as_map() |
| 371 |
.ok_or_else(|| ObjectError::Schema("signature: expected map".into()))?; |
| 372 |
let alg = uint(field(m, 1, "alg")?, "alg")?; |
| 373 |
if alg != ALG_COMPOSITE { |
| 374 |
return Err(ObjectError::Schema(format!( |
| 375 |
"unknown signature algorithm {alg}" |
| 376 |
))); |
| 377 |
} |
| 378 |
let ed = bytes(field(m, 2, "ed")?, "ed")?; |
| 379 |
let ml = bytes(field(m, 3, "ml")?, "ml")?; |
| 380 |
if ed.len() != ED25519_SIG_LEN || ml.len() != MLDSA65_SIG_LEN { |
| 381 |
return Err(ObjectError::Schema("signature: wrong length".into())); |
| 382 |
} |
| 383 |
Ok(Signature { |
| 384 |
key: oref(field(m, 0, "key")?, "key")?, |
| 385 |
ed: ed.try_into().unwrap(), |
| 386 |
ml: ml.to_vec(), |
| 387 |
}) |
| 388 |
} |
| 389 |
pub fn encode_list(sigs: &[Signature]) -> Vec<u8> { |
| 390 |
cbor::encode(&Value::Array(sigs.iter().map(|s| s.to_value()).collect())) |
| 391 |
} |
| 392 |
pub fn decode_list(b: &[u8]) -> Result<Vec<Signature>, ObjectError> { |
| 393 |
let v = cbor::decode(b)?; |
| 394 |
array(&v, "signatures")? |
| 395 |
.iter() |
| 396 |
.map(Signature::from_value) |
| 397 |
.collect() |
| 398 |
} |
| 399 |
} |
| 400 |
|
| 401 |
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] |
| 402 |
pub enum VerifyError { |
| 403 |
#[error("signature names a different key than the identity")] |
| 404 |
KeyMismatch, |
| 405 |
#[error("identity holds a malformed public key")] |
| 406 |
BadKey, |
| 407 |
#[error("Ed25519 signature invalid")] |
| 408 |
Ed25519, |
| 409 |
#[error("ML-DSA-65 signature invalid")] |
| 410 |
MlDsa, |
| 411 |
#[error("a challenge is at least 16 bytes")] |
| 412 |
ShortChallenge, |
| 413 |
} |
| 414 |
|
| 415 |
|
| 416 |
pub fn verify( |
| 417 |
identity: &Identity, |
| 418 |
sig: &Signature, |
| 419 |
domain: Domain, |
| 420 |
target: &ObjectRef, |
| 421 |
) -> Result<(), VerifyError> { |
| 422 |
let key = identity.hash(); |
| 423 |
if sig.key != key { |
| 424 |
return Err(VerifyError::KeyMismatch); |
| 425 |
} |
| 426 |
let msg = signing_message(domain, &key, target); |
| 427 |
let ed_sig = EdSignature::from_bytes(&sig.ed); |
| 428 |
identity |
| 429 |
.ed_key()? |
| 430 |
.verify_strict(&msg, &ed_sig) |
| 431 |
.map_err(|_| VerifyError::Ed25519)?; |
| 432 |
let enc = |
| 433 |
EncodedSignature::<MlDsa65>::try_from(sig.ml.as_slice()).map_err(|_| VerifyError::MlDsa)?; |
| 434 |
let ml_sig = MlSignature::<MlDsa65>::decode(&enc).ok_or(VerifyError::MlDsa)?; |
| 435 |
if !identity.ml_key()?.verify_with_context(&msg, b"", &ml_sig) { |
| 436 |
return Err(VerifyError::MlDsa); |
| 437 |
} |
| 438 |
Ok(()) |
| 439 |
} |
| 440 |
|
| 441 |
|
| 442 |
#[derive(Clone)] |
| 443 |
pub struct SecretKey { |
| 444 |
pub ed_seed: [u8; 32], |
| 445 |
pub ml_seed: [u8; 32], |
| 446 |
} |
| 447 |
|
| 448 |
impl std::fmt::Debug for SecretKey { |
| 449 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 450 |
f.write_str("SecretKey(..)") |
| 451 |
} |
| 452 |
} |
| 453 |
|
| 454 |
impl SecretKey { |
| 455 |
pub fn generate() -> SecretKey { |
| 456 |
let mut ed_seed = [0u8; 32]; |
| 457 |
let mut ml_seed = [0u8; 32]; |
| 458 |
rand::rngs::OsRng.fill_bytes(&mut ed_seed); |
| 459 |
rand::rngs::OsRng.fill_bytes(&mut ml_seed); |
| 460 |
SecretKey { ed_seed, ml_seed } |
| 461 |
} |
| 462 |
|
| 463 |
fn ed(&self) -> EdSigningKey { |
| 464 |
EdSigningKey::from_bytes(&self.ed_seed) |
| 465 |
} |
| 466 |
fn ml(&self) -> MlSigningKey<MlDsa65> { |
| 467 |
MlSigningKey::from_seed(&Seed::from(self.ml_seed)) |
| 468 |
} |
| 469 |
|
| 470 |
|
| 471 |
pub fn identity(&self, name: &str, email: &str, created: u64) -> Identity { |
| 472 |
Identity { |
| 473 |
ed25519_pk: self.ed().verifying_key().to_bytes(), |
| 474 |
mldsa65_pk: self |
| 475 |
.ml() |
| 476 |
.expanded_key() |
| 477 |
.verifying_key() |
| 478 |
.encode() |
| 479 |
.as_slice() |
| 480 |
.to_vec(), |
| 481 |
name: name.into(), |
| 482 |
email: email.into(), |
| 483 |
created, |
| 484 |
expires: None, |
| 485 |
previous: None, |
| 486 |
delegates: vec![], |
| 487 |
} |
| 488 |
} |
| 489 |
|
| 490 |
|
| 491 |
|
| 492 |
|
| 493 |
pub fn sign_ed25519(&self, msg: &[u8]) -> [u8; 64] { |
| 494 |
self.ed().sign(msg).to_bytes() |
| 495 |
} |
| 496 |
|
| 497 |
pub fn sign(&self, domain: Domain, key: &KeyId, target: &ObjectRef) -> Signature { |
| 498 |
let msg = signing_message(domain, key, target); |
| 499 |
let ed = self.ed().sign(&msg).to_bytes(); |
| 500 |
let ml = self |
| 501 |
.ml() |
| 502 |
.expanded_key() |
| 503 |
.sign_deterministic(&msg, b"") |
| 504 |
.expect("empty context is valid") |
| 505 |
.encode() |
| 506 |
.as_slice() |
| 507 |
.to_vec(); |
| 508 |
Signature { key: *key, ed, ml } |
| 509 |
} |
| 510 |
|
| 511 |
pub fn encode(&self, key: &KeyId) -> Vec<u8> { |
| 512 |
cbor::encode(&Value::map([ |
| 513 |
(0, Value::Uint(FORMAT_VERSION)), |
| 514 |
(1, Value::Bytes(key.0.to_vec())), |
| 515 |
(2, Value::Bytes(self.ed_seed.to_vec())), |
| 516 |
(3, Value::Bytes(self.ml_seed.to_vec())), |
| 517 |
])) |
| 518 |
} |
| 519 |
|
| 520 |
pub fn decode(b: &[u8]) -> Result<(KeyId, SecretKey), ObjectError> { |
| 521 |
let v = cbor::decode(b)?; |
| 522 |
let m = v |
| 523 |
.as_map() |
| 524 |
.ok_or_else(|| ObjectError::Schema("secret key: expected map".into()))?; |
| 525 |
check_version(m)?; |
| 526 |
let seed = |k: u64| -> Result<[u8; 32], ObjectError> { |
| 527 |
bytes(field(m, k, "seed")?, "seed")? |
| 528 |
.try_into() |
| 529 |
.map_err(|_| ObjectError::Schema("seed: expected 32 bytes".into())) |
| 530 |
}; |
| 531 |
Ok(( |
| 532 |
oref(field(m, 1, "key")?, "key")?, |
| 533 |
SecretKey { |
| 534 |
ed_seed: seed(2)?, |
| 535 |
ml_seed: seed(3)?, |
| 536 |
}, |
| 537 |
)) |
| 538 |
} |
| 539 |
} |
| 540 |
|
| 541 |
#[cfg(test)] |
| 542 |
mod tests { |
| 543 |
use super::*; |
| 544 |
|
| 545 |
fn fixed_key() -> SecretKey { |
| 546 |
SecretKey { |
| 547 |
ed_seed: [1; 32], |
| 548 |
ml_seed: [2; 32], |
| 549 |
} |
| 550 |
} |
| 551 |
|
| 552 |
#[test] |
| 553 |
fn identity_round_trip_and_sizes() { |
| 554 |
let sk = fixed_key(); |
| 555 |
let id = sk.identity("Ada", "[email protected]", 1_700_000_000_000); |
| 556 |
assert_eq!(id.mldsa65_pk.len(), MLDSA65_PK_LEN); |
| 557 |
let d = Identity::decode(&id.encode()).unwrap(); |
| 558 |
assert_eq!(d, id); |
| 559 |
assert_eq!(d.hash(), id.hash()); |
| 560 |
|
| 561 |
assert_eq!( |
| 562 |
fixed_key() |
| 563 |
.identity("Ada", "[email protected]", 1_700_000_000_000) |
| 564 |
.hash(), |
| 565 |
id.hash() |
| 566 |
); |
| 567 |
let mut other = id.clone(); |
| 568 |
other.delegates.push(Delegate::full(ObjectRef([9; 32]))); |
| 569 |
assert_ne!(other.hash(), id.hash()); |
| 570 |
} |
| 571 |
|
| 572 |
#[test] |
| 573 |
fn delegates_carry_scope_and_expiry_and_bare_keys_mean_every_scope() { |
| 574 |
let sk = fixed_key(); |
| 575 |
let mut id = sk.identity("Ada", "[email protected]", 1_700_000_000_000); |
| 576 |
let agent = ObjectRef([7; 32]); |
| 577 |
let host = ObjectRef([3; 32]); |
| 578 |
id.delegates = vec![ |
| 579 |
Delegate { |
| 580 |
key: agent, |
| 581 |
scope: Scope::CHANGES, |
| 582 |
expires: Some(2_000), |
| 583 |
}, |
| 584 |
Delegate { |
| 585 |
key: host, |
| 586 |
scope: Scope::CHANGES | Scope::REFS, |
| 587 |
expires: None, |
| 588 |
}, |
| 589 |
]; |
| 590 |
let d = Identity::decode(&id.encode()).unwrap(); |
| 591 |
assert_eq!(d.delegates.len(), 2); |
| 592 |
assert!(d.delegates_to(&agent, Scope::CHANGES, 1_000)); |
| 593 |
assert!(!d.delegates_to(&agent, Scope::CHANGES, 2_001), "expired"); |
| 594 |
assert!(!d.delegates_to(&agent, Scope::REFS, 1_000)); |
| 595 |
assert!(!d.delegates_to(&agent, Scope::SEAL, 1_000)); |
| 596 |
assert!(d.delegates_to(&host, Scope::REFS, u64::MAX)); |
| 597 |
assert!(!d.delegates_to(&host, Scope::SEAL, 0)); |
| 598 |
assert!(!d.delegates_to(&ObjectRef([1; 32]), Scope::CHANGES, 0)); |
| 599 |
assert_eq!( |
| 600 |
Scope::parse("changes, refs").unwrap(), |
| 601 |
Scope::CHANGES | Scope::REFS |
| 602 |
); |
| 603 |
assert_eq!(Scope::parse("all").unwrap(), Scope::ALL); |
| 604 |
assert_eq!((Scope::CHANGES | Scope::SEAL).to_string(), "changes,seal"); |
| 605 |
assert!(Scope::parse("push").is_err() && Scope::parse("").is_err()); |
| 606 |
|
| 607 |
let mut v = id.to_value(); |
| 608 |
if let Value::Map(m) = &mut v { |
| 609 |
m.insert(8, Value::Array(vec![Value::Bytes(host.0.to_vec())])); |
| 610 |
} |
| 611 |
let old = Identity::decode(&cbor::encode(&v)).unwrap(); |
| 612 |
assert_eq!(old.delegates, vec![Delegate::full(host)]); |
| 613 |
assert!(old.delegates_to(&host, Scope::ALL, u64::MAX)); |
| 614 |
} |
| 615 |
|
| 616 |
#[test] |
| 617 |
fn sign_and_verify() { |
| 618 |
let sk = fixed_key(); |
| 619 |
let id = sk.identity("Ada", "[email protected]", 1); |
| 620 |
let key = id.hash(); |
| 621 |
let target = ObjectRef([7; 32]); |
| 622 |
let sig = sk.sign(Domain::Change, &key, &target); |
| 623 |
assert_eq!(sig.ml.len(), MLDSA65_SIG_LEN); |
| 624 |
assert_eq!(verify(&id, &sig, Domain::Change, &target), Ok(())); |
| 625 |
|
| 626 |
assert_eq!( |
| 627 |
verify(&id, &sig, Domain::Change, &ObjectRef([8; 32])), |
| 628 |
Err(VerifyError::Ed25519) |
| 629 |
); |
| 630 |
assert_eq!( |
| 631 |
verify(&id, &sig, Domain::Attest, &target), |
| 632 |
Err(VerifyError::Ed25519) |
| 633 |
); |
| 634 |
|
| 635 |
assert_eq!(sk.sign(Domain::Change, &key, &target), sig); |
| 636 |
|
| 637 |
let l = |
| 638 |
Signature::decode_list(&Signature::encode_list(std::slice::from_ref(&sig))).unwrap(); |
| 639 |
assert_eq!(l, vec![sig]); |
| 640 |
} |
| 641 |
|
| 642 |
#[test] |
| 643 |
fn stripping_or_forging_either_half_fails() { |
| 644 |
let sk = fixed_key(); |
| 645 |
let id = sk.identity("Ada", "a@b", 1); |
| 646 |
let key = id.hash(); |
| 647 |
let target = ObjectRef([7; 32]); |
| 648 |
let good = sk.sign(Domain::Change, &key, &target); |
| 649 |
|
| 650 |
let mut no_ml = good.clone(); |
| 651 |
no_ml.ml = vec![0; MLDSA65_SIG_LEN]; |
| 652 |
assert_eq!( |
| 653 |
verify(&id, &no_ml, Domain::Change, &target), |
| 654 |
Err(VerifyError::MlDsa) |
| 655 |
); |
| 656 |
|
| 657 |
let mut bad_ed = good.clone(); |
| 658 |
bad_ed.ed[10] ^= 1; |
| 659 |
assert_eq!( |
| 660 |
verify(&id, &bad_ed, Domain::Change, &target), |
| 661 |
Err(VerifyError::Ed25519) |
| 662 |
); |
| 663 |
|
| 664 |
|
| 665 |
let other = SecretKey { |
| 666 |
ed_seed: [3; 32], |
| 667 |
ml_seed: [4; 32], |
| 668 |
}; |
| 669 |
let other_id = other.identity("Bob", "b@b", 1); |
| 670 |
let theirs = other.sign(Domain::Change, &other_id.hash(), &target); |
| 671 |
assert_eq!( |
| 672 |
verify(&id, &theirs, Domain::Change, &target), |
| 673 |
Err(VerifyError::KeyMismatch) |
| 674 |
); |
| 675 |
let mut relabelled = theirs.clone(); |
| 676 |
relabelled.key = key; |
| 677 |
assert_eq!( |
| 678 |
verify(&id, &relabelled, Domain::Change, &target), |
| 679 |
Err(VerifyError::Ed25519) |
| 680 |
); |
| 681 |
|
| 682 |
|
| 683 |
let mut short = good.to_value(); |
| 684 |
if let Value::Map(m) = &mut short { |
| 685 |
m.insert(3, Value::Bytes(vec![0; 10])); |
| 686 |
} |
| 687 |
assert!(Signature::from_value(&short).is_err()); |
| 688 |
} |
| 689 |
|
| 690 |
#[test] |
| 691 |
fn secret_key_round_trip() { |
| 692 |
let sk = fixed_key(); |
| 693 |
let key = sk.identity("x", "y", 0).hash(); |
| 694 |
let (k, d) = SecretKey::decode(&sk.encode(&key)).unwrap(); |
| 695 |
assert_eq!(k, key); |
| 696 |
assert_eq!(d.ed_seed, sk.ed_seed); |
| 697 |
assert_eq!(d.ml_seed, sk.ml_seed); |
| 698 |
assert_ne!(SecretKey::generate().ed_seed, SecretKey::generate().ed_seed); |
| 699 |
} |
| 700 |
} |
| 701 |
|
| 702 |
|
| 703 |
|
| 704 |
pub fn challenge_target(challenge: &[u8]) -> ObjectRef { |
| 705 |
let mut h = blake3::Hasher::new(); |
| 706 |
h.update(b"oxy1 challenge "); |
| 707 |
h.update(challenge); |
| 708 |
ObjectRef(*h.finalize().as_bytes()) |
| 709 |
} |
| 710 |
|
| 711 |
impl SecretKey { |
| 712 |
|
| 713 |
pub fn sign_challenge(&self, key: &KeyId, challenge: &[u8]) -> Result<Signature, VerifyError> { |
| 714 |
if challenge.len() < 16 { |
| 715 |
return Err(VerifyError::ShortChallenge); |
| 716 |
} |
| 717 |
Ok(self.sign(Domain::Challenge, key, &challenge_target(challenge))) |
| 718 |
} |
| 719 |
} |
| 720 |
|
| 721 |
|
| 722 |
pub fn verify_challenge( |
| 723 |
identity: &Identity, |
| 724 |
sig: &Signature, |
| 725 |
challenge: &[u8], |
| 726 |
) -> Result<(), VerifyError> { |
| 727 |
if challenge.len() < 16 { |
| 728 |
return Err(VerifyError::ShortChallenge); |
| 729 |
} |
| 730 |
if sig.key != identity.hash() { |
| 731 |
return Err(VerifyError::KeyMismatch); |
| 732 |
} |
| 733 |
verify( |
| 734 |
identity, |
| 735 |
sig, |
| 736 |
Domain::Challenge, |
| 737 |
&challenge_target(challenge), |
| 738 |
) |
| 739 |
} |
| 740 |
|
| 741 |
#[cfg(test)] |
| 742 |
mod challenge_tests { |
| 743 |
use super::*; |
| 744 |
|
| 745 |
#[test] |
| 746 |
fn a_challenge_signature_binds_key_and_bytes() { |
| 747 |
let sk = SecretKey::generate(); |
| 748 |
let id = sk.identity("A", "a@example", 1); |
| 749 |
let key = id.hash(); |
| 750 |
let challenge = [7u8; 32]; |
| 751 |
let sig = sk.sign_challenge(&key, &challenge).unwrap(); |
| 752 |
assert!(verify_challenge(&id, &sig, &challenge).is_ok()); |
| 753 |
assert!( |
| 754 |
verify_challenge(&id, &sig, &[8u8; 32]).is_err(), |
| 755 |
"other bytes" |
| 756 |
); |
| 757 |
let other = SecretKey::generate().identity("B", "b@example", 1); |
| 758 |
assert!( |
| 759 |
verify_challenge(&other, &sig, &challenge).is_err(), |
| 760 |
"other identity" |
| 761 |
); |
| 762 |
assert!(sk.sign_challenge(&key, b"short").is_err()); |
| 763 |
|
| 764 |
assert_ne!(challenge_target(&challenge), ObjectRef(challenge)); |
| 765 |
} |
| 766 |
} |