| 1983686f Andy McCall ↶ |
1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
use crate::cbor::{self, Value}; |
| 8 |
use crate::hash::{hash_object, KeyId, ObjectRef, ObjectType}; |
| 75167672 Andy McCall |
9 |
use crate::objects::{ |
| 10 |
array, bytes, check_version, field, oref, text, uint, ObjectError, FORMAT_VERSION, |
| 11 |
}; |
| 1983686f Andy McCall ↶ |
12 |
use ed25519_dalek::ed25519::signature::Signer as _; |
| 75167672 Andy McCall |
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 |
}; |
| 1983686f Andy McCall ↶ |
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 |
|
| 7ba155f2 Andy McCall ↶ |
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 |
} |
| 02e69188 Andy McCall ↶ |
63 |
pub(crate) fn named(name: &str) -> Option<Scope> { |
| 7ba155f2 Andy McCall ↶ |
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 |
|
| 1983686f Andy McCall ↶ |
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>, |
| 7ba155f2 Andy McCall ↶ |
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 |
| 1983686f Andy McCall ↶ |
191 |
} |
| 192 |
|
| 193 |
impl Identity { |
| 7ba155f2 Andy McCall ↶ |
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 |
} |
| 1983686f Andy McCall ↶ |
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)), |
| 75167672 Andy McCall |
211 |
( |
| 212 |
7, |
| 213 |
self.previous |
| 214 |
.map(|p| Value::Bytes(p.0.to_vec())) |
| 215 |
.unwrap_or(Value::Null), |
| 216 |
), |
| 217 |
( |
| 218 |
8, |
| 7ba155f2 Andy McCall ↶ |
219 |
Value::Array(self.delegates.iter().map(|d| d.to_value()).collect()), |
| 75167672 Andy McCall |
220 |
), |
| 1983686f Andy McCall ↶ |
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)?; |
| 75167672 Andy McCall |
231 |
let m = v |
| 232 |
.as_map() |
| 233 |
.ok_or_else(|| ObjectError::Schema("identity: expected map".into()))?; |
| 1983686f Andy McCall ↶ |
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 { |
| 75167672 Andy McCall |
238 |
return Err(ObjectError::Schema( |
| 239 |
"identity: wrong public key length".into(), |
| 240 |
)); |
| 1983686f Andy McCall ↶ |
241 |
} |
| 75167672 Andy McCall |
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 |
}; |
| 7ba155f2 Andy McCall ↶ |
256 |
let delegates = tidy( |
| 257 |
array(field(m, 8, "delegates")?, "delegates")? |
| 258 |
.iter() |
| 259 |
.map(Delegate::from_value) |
| 260 |
.collect::<Result<Vec<_>, _>>()?, |
| 261 |
); |
| 1983686f Andy McCall ↶ |
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 |
|
| 28fc23d7 Andy McCall ↶ |
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 |
|
| 7ba155f2 Andy McCall ↶ |
281 |
pub fn successor( |
| 282 |
&self, |
| 283 |
delegates: Vec<Delegate>, |
| 284 |
expires: Option<u64>, |
| 285 |
created: u64, |
| 286 |
) -> Identity { |
| 75167672 Andy McCall |
287 |
Identity { |
| 288 |
previous: Some(self.hash()), |
| 7ba155f2 Andy McCall ↶ |
289 |
delegates: tidy(delegates), |
| 75167672 Andy McCall |
290 |
expires, |
| 291 |
created, |
| 292 |
..self.clone() |
| 293 |
} |
| 28fc23d7 Andy McCall ↶ |
294 |
} |
| 295 |
|
| a39754d0 Andy McCall ↶ |
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 |
|
| 1983686f Andy McCall ↶ |
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> { |
| 75167672 Andy McCall |
308 |
let enc = EncodedVerifyingKey::<MlDsa65>::try_from(self.mldsa65_pk.as_slice()) |
| 309 |
.map_err(|_| VerifyError::BadKey)?; |
| 1983686f Andy McCall ↶ |
310 |
Ok(MlVerifyingKey::decode(&enc)) |
| 311 |
} |
| 312 |
} |
| 313 |
|
| 314 |
#[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 315 |
pub enum Domain { |
| 316 |
Change, |
| 317 |
Attest, |
| 83e0677b Andy McCall ↶ |
318 |
Policy, |
| 7aa2dc93 Andy McCall ↶ |
319 |
|
| 320 |
|
| 321 |
Challenge, |
| 02e69188 Andy McCall ↶ |
322 |
|
| 323 |
Certificate, |
| a2387d54 Andy McCall ↶ |
324 |
|
| 325 |
Grant, |
| e5f8eb2a Andy McCall ↶ |
326 |
|
| 327 |
Checkpoint, |
| 1983686f Andy McCall ↶ |
328 |
} |
| 329 |
|
| 330 |
impl Domain { |
| 331 |
pub fn name(self) -> &'static str { |
| 332 |
match self { |
| 333 |
Domain::Change => "change", |
| 334 |
Domain::Attest => "attest", |
| 83e0677b Andy McCall ↶ |
335 |
Domain::Policy => "policy", |
| 7aa2dc93 Andy McCall ↶ |
336 |
Domain::Challenge => "challenge", |
| 02e69188 Andy McCall ↶ |
337 |
Domain::Certificate => "certificate", |
| a2387d54 Andy McCall ↶ |
338 |
Domain::Grant => "grant", |
| e5f8eb2a Andy McCall ↶ |
339 |
Domain::Checkpoint => "checkpoint", |
| 1983686f Andy McCall ↶ |
340 |
} |
| 341 |
} |
| 342 |
} |
| 343 |
|
| 344 |
|
| 345 |
pub fn signing_message(domain: Domain, key: &KeyId, target: &ObjectRef) -> Vec<u8> { |
| 346 |
let mut m = Vec::with_capacity(80); |
| 347 |
m.extend_from_slice(b"oxy1 sig "); |
| 348 |
m.extend_from_slice(domain.name().as_bytes()); |
| 349 |
m.push(0); |
| 350 |
m.extend_from_slice(&key.0); |
| 351 |
m.extend_from_slice(&target.0); |
| 352 |
m |
| 353 |
} |
| 354 |
|
| 355 |
#[derive(Clone, PartialEq, Eq)] |
| 356 |
pub struct Signature { |
| 357 |
pub key: KeyId, |
| 358 |
pub ed: [u8; ED25519_SIG_LEN], |
| 359 |
pub ml: Vec<u8>, |
| 360 |
} |
| 361 |
|
| 362 |
impl std::fmt::Debug for Signature { |
| 363 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 364 |
write!(f, "Signature(key {:?})", self.key) |
| 365 |
} |
| 366 |
} |
| 367 |
|
| 368 |
impl Signature { |
| 369 |
pub fn to_value(&self) -> Value { |
| 370 |
Value::map([ |
| 371 |
(0, Value::Bytes(self.key.0.to_vec())), |
| 372 |
(1, Value::Uint(ALG_COMPOSITE)), |
| 373 |
(2, Value::Bytes(self.ed.to_vec())), |
| 374 |
(3, Value::Bytes(self.ml.clone())), |
| 375 |
]) |
| 376 |
} |
| 377 |
pub fn from_value(v: &Value) -> Result<Signature, ObjectError> { |
| 75167672 Andy McCall |
378 |
let m = v |
| 379 |
.as_map() |
| 380 |
.ok_or_else(|| ObjectError::Schema("signature: expected map".into()))?; |
| 1983686f Andy McCall ↶ |
381 |
let alg = uint(field(m, 1, "alg")?, "alg")?; |
| 382 |
if alg != ALG_COMPOSITE { |
| 75167672 Andy McCall |
383 |
return Err(ObjectError::Schema(format!( |
| 384 |
"unknown signature algorithm {alg}" |
| 385 |
))); |
| 1983686f Andy McCall ↶ |
386 |
} |
| 387 |
let ed = bytes(field(m, 2, "ed")?, "ed")?; |
| 388 |
let ml = bytes(field(m, 3, "ml")?, "ml")?; |
| 389 |
if ed.len() != ED25519_SIG_LEN || ml.len() != MLDSA65_SIG_LEN { |
| 390 |
return Err(ObjectError::Schema("signature: wrong length".into())); |
| 391 |
} |
| 75167672 Andy McCall |
392 |
Ok(Signature { |
| 393 |
key: oref(field(m, 0, "key")?, "key")?, |
| 394 |
ed: ed.try_into().unwrap(), |
| 395 |
ml: ml.to_vec(), |
| 396 |
}) |
| 1983686f Andy McCall ↶ |
397 |
} |
| 398 |
pub fn encode_list(sigs: &[Signature]) -> Vec<u8> { |
| 399 |
cbor::encode(&Value::Array(sigs.iter().map(|s| s.to_value()).collect())) |
| 400 |
} |
| 401 |
pub fn decode_list(b: &[u8]) -> Result<Vec<Signature>, ObjectError> { |
| 402 |
let v = cbor::decode(b)?; |
| 75167672 Andy McCall |
403 |
array(&v, "signatures")? |
| 404 |
.iter() |
| 405 |
.map(Signature::from_value) |
| 406 |
.collect() |
| 1983686f Andy McCall ↶ |
407 |
} |
| 408 |
} |
| 409 |
|
| 410 |
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] |
| 411 |
pub enum VerifyError { |
| 412 |
#[error("signature names a different key than the identity")] |
| 413 |
KeyMismatch, |
| 414 |
#[error("identity holds a malformed public key")] |
| 415 |
BadKey, |
| 416 |
#[error("Ed25519 signature invalid")] |
| 417 |
Ed25519, |
| 418 |
#[error("ML-DSA-65 signature invalid")] |
| 419 |
MlDsa, |
| 7aa2dc93 Andy McCall ↶ |
420 |
#[error("a challenge is at least 16 bytes")] |
| 421 |
ShortChallenge, |
| 1983686f Andy McCall ↶ |
422 |
} |
| 423 |
|
| 424 |
|
| 75167672 Andy McCall |
425 |
pub fn verify( |
| 426 |
identity: &Identity, |
| 427 |
sig: &Signature, |
| 428 |
domain: Domain, |
| 429 |
target: &ObjectRef, |
| 430 |
) -> Result<(), VerifyError> { |
| 1983686f Andy McCall ↶ |
431 |
let key = identity.hash(); |
| 432 |
if sig.key != key { |
| 433 |
return Err(VerifyError::KeyMismatch); |
| 434 |
} |
| 435 |
let msg = signing_message(domain, &key, target); |
| 436 |
let ed_sig = EdSignature::from_bytes(&sig.ed); |
| 75167672 Andy McCall |
437 |
identity |
| 438 |
.ed_key()? |
| 439 |
.verify_strict(&msg, &ed_sig) |
| 440 |
.map_err(|_| VerifyError::Ed25519)?; |
| 441 |
let enc = |
| 442 |
EncodedSignature::<MlDsa65>::try_from(sig.ml.as_slice()).map_err(|_| VerifyError::MlDsa)?; |
| 1983686f Andy McCall ↶ |
443 |
let ml_sig = MlSignature::<MlDsa65>::decode(&enc).ok_or(VerifyError::MlDsa)?; |
| 444 |
if !identity.ml_key()?.verify_with_context(&msg, b"", &ml_sig) { |
| 445 |
return Err(VerifyError::MlDsa); |
| 446 |
} |
| 447 |
Ok(()) |
| 448 |
} |
| 449 |
|
| 450 |
|
| 451 |
#[derive(Clone)] |
| 452 |
pub struct SecretKey { |
| 453 |
pub ed_seed: [u8; 32], |
| 454 |
pub ml_seed: [u8; 32], |
| 455 |
} |
| 456 |
|
| 457 |
impl std::fmt::Debug for SecretKey { |
| 458 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 459 |
f.write_str("SecretKey(..)") |
| 460 |
} |
| 461 |
} |
| 462 |
|
| 463 |
impl SecretKey { |
| 464 |
pub fn generate() -> SecretKey { |
| 465 |
let mut ed_seed = [0u8; 32]; |
| 466 |
let mut ml_seed = [0u8; 32]; |
| 467 |
rand::rngs::OsRng.fill_bytes(&mut ed_seed); |
| 468 |
rand::rngs::OsRng.fill_bytes(&mut ml_seed); |
| 469 |
SecretKey { ed_seed, ml_seed } |
| 470 |
} |
| 471 |
|
| 472 |
fn ed(&self) -> EdSigningKey { |
| 473 |
EdSigningKey::from_bytes(&self.ed_seed) |
| 474 |
} |
| 475 |
fn ml(&self) -> MlSigningKey<MlDsa65> { |
| 476 |
MlSigningKey::from_seed(&Seed::from(self.ml_seed)) |
| 477 |
} |
| 478 |
|
| 479 |
|
| 480 |
pub fn identity(&self, name: &str, email: &str, created: u64) -> Identity { |
| 481 |
Identity { |
| 482 |
ed25519_pk: self.ed().verifying_key().to_bytes(), |
| 75167672 Andy McCall |
483 |
mldsa65_pk: self |
| 484 |
.ml() |
| 485 |
.expanded_key() |
| 486 |
.verifying_key() |
| 487 |
.encode() |
| 488 |
.as_slice() |
| 489 |
.to_vec(), |
| 1983686f Andy McCall ↶ |
490 |
name: name.into(), |
| 491 |
email: email.into(), |
| 492 |
created, |
| 493 |
expires: None, |
| 494 |
previous: None, |
| 495 |
delegates: vec![], |
| 496 |
} |
| a39754d0 Andy McCall ↶ |
497 |
} |
| 498 |
|
| 499 |
|
| 500 |
|
| 501 |
|
| 502 |
pub fn sign_ed25519(&self, msg: &[u8]) -> [u8; 64] { |
| 503 |
self.ed().sign(msg).to_bytes() |
| 1983686f Andy McCall ↶ |
504 |
} |
| 505 |
|
| 506 |
pub fn sign(&self, domain: Domain, key: &KeyId, target: &ObjectRef) -> Signature { |
| 507 |
let msg = signing_message(domain, key, target); |
| 508 |
let ed = self.ed().sign(&msg).to_bytes(); |
| 75167672 Andy McCall |
509 |
let ml = self |
| 510 |
.ml() |
| 511 |
.expanded_key() |
| 512 |
.sign_deterministic(&msg, b"") |
| 513 |
.expect("empty context is valid") |
| 514 |
.encode() |
| 515 |
.as_slice() |
| 516 |
.to_vec(); |
| 1983686f Andy McCall ↶ |
517 |
Signature { key: *key, ed, ml } |
| 518 |
} |
| 519 |
|
| 520 |
pub fn encode(&self, key: &KeyId) -> Vec<u8> { |
| 521 |
cbor::encode(&Value::map([ |
| 522 |
(0, Value::Uint(FORMAT_VERSION)), |
| 523 |
(1, Value::Bytes(key.0.to_vec())), |
| 524 |
(2, Value::Bytes(self.ed_seed.to_vec())), |
| 525 |
(3, Value::Bytes(self.ml_seed.to_vec())), |
| 526 |
])) |
| 527 |
} |
| 528 |
|
| 529 |
pub fn decode(b: &[u8]) -> Result<(KeyId, SecretKey), ObjectError> { |
| 530 |
let v = cbor::decode(b)?; |
| 75167672 Andy McCall |
531 |
let m = v |
| 532 |
.as_map() |
| 533 |
.ok_or_else(|| ObjectError::Schema("secret key: expected map".into()))?; |
| 1983686f Andy McCall ↶ |
534 |
check_version(m)?; |
| 535 |
let seed = |k: u64| -> Result<[u8; 32], ObjectError> { |
| 75167672 Andy McCall |
536 |
bytes(field(m, k, "seed")?, "seed")? |
| 537 |
.try_into() |
| 538 |
.map_err(|_| ObjectError::Schema("seed: expected 32 bytes".into())) |
| 1983686f Andy McCall ↶ |
539 |
}; |
| 75167672 Andy McCall |
540 |
Ok(( |
| 541 |
oref(field(m, 1, "key")?, "key")?, |
| 542 |
SecretKey { |
| 543 |
ed_seed: seed(2)?, |
| 544 |
ml_seed: seed(3)?, |
| 545 |
}, |
| 546 |
)) |
| 1983686f Andy McCall ↶ |
547 |
} |
| 548 |
} |
| 549 |
|
| 550 |
#[cfg(test)] |
| 551 |
mod tests { |
| 552 |
use super::*; |
| 553 |
|
| 554 |
fn fixed_key() -> SecretKey { |
| 75167672 Andy McCall |
555 |
SecretKey { |
| 556 |
ed_seed: [1; 32], |
| 557 |
ml_seed: [2; 32], |
| 558 |
} |
| 1983686f Andy McCall ↶ |
559 |
} |
| 560 |
|
| 561 |
#[test] |
| 562 |
fn identity_round_trip_and_sizes() { |
| 563 |
let sk = fixed_key(); |
| 564 |
let id = sk.identity("Ada", "[email protected]", 1_700_000_000_000); |
| 565 |
assert_eq!(id.mldsa65_pk.len(), MLDSA65_PK_LEN); |
| 566 |
let d = Identity::decode(&id.encode()).unwrap(); |
| 567 |
assert_eq!(d, id); |
| 568 |
assert_eq!(d.hash(), id.hash()); |
| 569 |
|
| 75167672 Andy McCall |
570 |
assert_eq!( |
| 571 |
fixed_key() |
| 572 |
.identity("Ada", "[email protected]", 1_700_000_000_000) |
| 573 |
.hash(), |
| 574 |
id.hash() |
| 575 |
); |
| 1983686f Andy McCall ↶ |
576 |
let mut other = id.clone(); |
| 7ba155f2 Andy McCall ↶ |
577 |
other.delegates.push(Delegate::full(ObjectRef([9; 32]))); |
| 1983686f Andy McCall ↶ |
578 |
assert_ne!(other.hash(), id.hash()); |
| 7ba155f2 Andy McCall ↶ |
579 |
} |
| 580 |
|
| 581 |
#[test] |
| 582 |
fn delegates_carry_scope_and_expiry_and_bare_keys_mean_every_scope() { |
| 583 |
let sk = fixed_key(); |
| 584 |
let mut id = sk.identity("Ada", "[email protected]", 1_700_000_000_000); |
| 585 |
let agent = ObjectRef([7; 32]); |
| 586 |
let host = ObjectRef([3; 32]); |
| 587 |
id.delegates = vec![ |
| 588 |
Delegate { |
| 589 |
key: agent, |
| 590 |
scope: Scope::CHANGES, |
| 591 |
expires: Some(2_000), |
| 592 |
}, |
| 593 |
Delegate { |
| 594 |
key: host, |
| 595 |
scope: Scope::CHANGES | Scope::REFS, |
| 596 |
expires: None, |
| 597 |
}, |
| 598 |
]; |
| 599 |
let d = Identity::decode(&id.encode()).unwrap(); |
| 600 |
assert_eq!(d.delegates.len(), 2); |
| 601 |
assert!(d.delegates_to(&agent, Scope::CHANGES, 1_000)); |
| 602 |
assert!(!d.delegates_to(&agent, Scope::CHANGES, 2_001), "expired"); |
| 603 |
assert!(!d.delegates_to(&agent, Scope::REFS, 1_000)); |
| 604 |
assert!(!d.delegates_to(&agent, Scope::SEAL, 1_000)); |
| 605 |
assert!(d.delegates_to(&host, Scope::REFS, u64::MAX)); |
| 606 |
assert!(!d.delegates_to(&host, Scope::SEAL, 0)); |
| 607 |
assert!(!d.delegates_to(&ObjectRef([1; 32]), Scope::CHANGES, 0)); |
| 608 |
assert_eq!( |
| 609 |
Scope::parse("changes, refs").unwrap(), |
| 610 |
Scope::CHANGES | Scope::REFS |
| 611 |
); |
| 612 |
assert_eq!(Scope::parse("all").unwrap(), Scope::ALL); |
| 613 |
assert_eq!((Scope::CHANGES | Scope::SEAL).to_string(), "changes,seal"); |
| 614 |
assert!(Scope::parse("push").is_err() && Scope::parse("").is_err()); |
| 615 |
|
| 616 |
let mut v = id.to_value(); |
| 617 |
if let Value::Map(m) = &mut v { |
| 618 |
m.insert(8, Value::Array(vec![Value::Bytes(host.0.to_vec())])); |
| 619 |
} |
| 620 |
let old = Identity::decode(&cbor::encode(&v)).unwrap(); |
| 621 |
assert_eq!(old.delegates, vec![Delegate::full(host)]); |
| 622 |
assert!(old.delegates_to(&host, Scope::ALL, u64::MAX)); |
| 1983686f Andy McCall ↶ |
623 |
} |
| 624 |
|
| 625 |
#[test] |
| 626 |
fn sign_and_verify() { |
| 627 |
let sk = fixed_key(); |
| 628 |
let id = sk.identity("Ada", "[email protected]", 1); |
| 629 |
let key = id.hash(); |
| 630 |
let target = ObjectRef([7; 32]); |
| 631 |
let sig = sk.sign(Domain::Change, &key, &target); |
| 632 |
assert_eq!(sig.ml.len(), MLDSA65_SIG_LEN); |
| 633 |
assert_eq!(verify(&id, &sig, Domain::Change, &target), Ok(())); |
| 634 |
|
| 75167672 Andy McCall |
635 |
assert_eq!( |
| 636 |
verify(&id, &sig, Domain::Change, &ObjectRef([8; 32])), |
| 637 |
Err(VerifyError::Ed25519) |
| 638 |
); |
| 639 |
assert_eq!( |
| 640 |
verify(&id, &sig, Domain::Attest, &target), |
| 641 |
Err(VerifyError::Ed25519) |
| 642 |
); |
| 1983686f Andy McCall ↶ |
643 |
|
| 644 |
assert_eq!(sk.sign(Domain::Change, &key, &target), sig); |
| 645 |
|
| 75167672 Andy McCall |
646 |
let l = |
| 647 |
Signature::decode_list(&Signature::encode_list(std::slice::from_ref(&sig))).unwrap(); |
| 1983686f Andy McCall ↶ |
648 |
assert_eq!(l, vec![sig]); |
| 649 |
} |
| 650 |
|
| 651 |
#[test] |
| 652 |
fn stripping_or_forging_either_half_fails() { |
| 653 |
let sk = fixed_key(); |
| 654 |
let id = sk.identity("Ada", "a@b", 1); |
| 655 |
let key = id.hash(); |
| 656 |
let target = ObjectRef([7; 32]); |
| 657 |
let good = sk.sign(Domain::Change, &key, &target); |
| 658 |
|
| 659 |
let mut no_ml = good.clone(); |
| 660 |
no_ml.ml = vec![0; MLDSA65_SIG_LEN]; |
| 75167672 Andy McCall |
661 |
assert_eq!( |
| 662 |
verify(&id, &no_ml, Domain::Change, &target), |
| 663 |
Err(VerifyError::MlDsa) |
| 664 |
); |
| 1983686f Andy McCall ↶ |
665 |
|
| 666 |
let mut bad_ed = good.clone(); |
| 667 |
bad_ed.ed[10] ^= 1; |
| 75167672 Andy McCall |
668 |
assert_eq!( |
| 669 |
verify(&id, &bad_ed, Domain::Change, &target), |
| 670 |
Err(VerifyError::Ed25519) |
| 671 |
); |
| 1983686f Andy McCall ↶ |
672 |
|
| 673 |
|
| 75167672 Andy McCall |
674 |
let other = SecretKey { |
| 675 |
ed_seed: [3; 32], |
| 676 |
ml_seed: [4; 32], |
| 677 |
}; |
| 1983686f Andy McCall ↶ |
678 |
let other_id = other.identity("Bob", "b@b", 1); |
| 679 |
let theirs = other.sign(Domain::Change, &other_id.hash(), &target); |
| 75167672 Andy McCall |
680 |
assert_eq!( |
| 681 |
verify(&id, &theirs, Domain::Change, &target), |
| 682 |
Err(VerifyError::KeyMismatch) |
| 683 |
); |
| 1983686f Andy McCall ↶ |
684 |
let mut relabelled = theirs.clone(); |
| 685 |
relabelled.key = key; |
| 75167672 Andy McCall |
686 |
assert_eq!( |
| 687 |
verify(&id, &relabelled, Domain::Change, &target), |
| 688 |
Err(VerifyError::Ed25519) |
| 689 |
); |
| 1983686f Andy McCall ↶ |
690 |
|
| 691 |
|
| 692 |
let mut short = good.to_value(); |
| 693 |
if let Value::Map(m) = &mut short { |
| 694 |
m.insert(3, Value::Bytes(vec![0; 10])); |
| 695 |
} |
| 696 |
assert!(Signature::from_value(&short).is_err()); |
| 697 |
} |
| 698 |
|
| 699 |
#[test] |
| 700 |
fn secret_key_round_trip() { |
| 701 |
let sk = fixed_key(); |
| 702 |
let key = sk.identity("x", "y", 0).hash(); |
| 703 |
let (k, d) = SecretKey::decode(&sk.encode(&key)).unwrap(); |
| 704 |
assert_eq!(k, key); |
| 705 |
assert_eq!(d.ed_seed, sk.ed_seed); |
| 706 |
assert_eq!(d.ml_seed, sk.ml_seed); |
| 707 |
assert_ne!(SecretKey::generate().ed_seed, SecretKey::generate().ed_seed); |
| 708 |
} |
| 709 |
} |
| 7aa2dc93 Andy McCall ↶ |
710 |
|
| 711 |
|
| 712 |
|
| 713 |
pub fn challenge_target(challenge: &[u8]) -> ObjectRef { |
| 714 |
let mut h = blake3::Hasher::new(); |
| 715 |
h.update(b"oxy1 challenge "); |
| 716 |
h.update(challenge); |
| 717 |
ObjectRef(*h.finalize().as_bytes()) |
| 718 |
} |
| 719 |
|
| 720 |
impl SecretKey { |
| 721 |
|
| 722 |
pub fn sign_challenge(&self, key: &KeyId, challenge: &[u8]) -> Result<Signature, VerifyError> { |
| 723 |
if challenge.len() < 16 { |
| 724 |
return Err(VerifyError::ShortChallenge); |
| 725 |
} |
| 726 |
Ok(self.sign(Domain::Challenge, key, &challenge_target(challenge))) |
| 727 |
} |
| 728 |
} |
| 729 |
|
| 730 |
|
| 119bbf50 Andy McCall ↶ |
731 |
pub fn verify_challenge( |
| 732 |
identity: &Identity, |
| 733 |
sig: &Signature, |
| 734 |
challenge: &[u8], |
| 735 |
) -> Result<(), VerifyError> { |
| 7aa2dc93 Andy McCall ↶ |
736 |
if challenge.len() < 16 { |
| 737 |
return Err(VerifyError::ShortChallenge); |
| 738 |
} |
| 739 |
if sig.key != identity.hash() { |
| 740 |
return Err(VerifyError::KeyMismatch); |
| 741 |
} |
| 119bbf50 Andy McCall ↶ |
742 |
verify( |
| 743 |
identity, |
| 744 |
sig, |
| 745 |
Domain::Challenge, |
| 746 |
&challenge_target(challenge), |
| 747 |
) |
| 7aa2dc93 Andy McCall ↶ |
748 |
} |
| 749 |
|
| 750 |
#[cfg(test)] |
| 751 |
mod challenge_tests { |
| 752 |
use super::*; |
| 753 |
|
| 754 |
#[test] |
| 755 |
fn a_challenge_signature_binds_key_and_bytes() { |
| 756 |
let sk = SecretKey::generate(); |
| 757 |
let id = sk.identity("A", "a@example", 1); |
| 758 |
let key = id.hash(); |
| 759 |
let challenge = [7u8; 32]; |
| 760 |
let sig = sk.sign_challenge(&key, &challenge).unwrap(); |
| 761 |
assert!(verify_challenge(&id, &sig, &challenge).is_ok()); |
| 119bbf50 Andy McCall ↶ |
762 |
assert!( |
| 763 |
verify_challenge(&id, &sig, &[8u8; 32]).is_err(), |
| 764 |
"other bytes" |
| 765 |
); |
| 7aa2dc93 Andy McCall ↶ |
766 |
let other = SecretKey::generate().identity("B", "b@example", 1); |
| 119bbf50 Andy McCall ↶ |
767 |
assert!( |
| 768 |
verify_challenge(&other, &sig, &challenge).is_err(), |
| 769 |
"other identity" |
| 770 |
); |
| 7aa2dc93 Andy McCall ↶ |
771 |
assert!(sk.sign_challenge(&key, b"short").is_err()); |
| 772 |
|
| 773 |
assert_ne!(challenge_target(&challenge), ObjectRef(challenge)); |
| 774 |
} |
| 775 |
} |