fix: AppContext::new is a const fn over a &'static label (QA S-09)
A label is one fixed string per purpose; taking any runtime bytes let a consumer derive it from a peer name, a file name or a message field, and two purposes could then collide. AppContext::new now takes &'static [u8] and is a const fn, so contexts are built as consts and a bad label fails the consumer's build; there is no runtime constructor (the simplest API: one constructor, no escape hatch until a need appears). Tests: a const OK and a const EMPTY context; sig_hygiene refuses a consumer that passes a runtime Vec (E0597/E0716); the one test that needs runtime labels (flipping label bytes) leaks them on purpose. The random labels in sig_malformed and fuzz mode 5's AppContext part are dropped (the raw-ctx part of mode 5 stays). A doctest shows the const pattern, and docs/02_signatures.md says so.
This commit is contained in:
@@ -147,7 +147,11 @@ Where the code differs from, or adds to, the design above (the code wins):
|
||||
canonical one, as well as small-order points (`Error::InvalidVerifyingKey`). Invisible to honest
|
||||
keys and to the RFC's vectors.
|
||||
- **App labels are 1 to 231 bytes** (`MAX_APP_LABEL_LEN` = 255 minus the 24-byte prefix); an empty
|
||||
label is `TooShort`, a longer one `TooLong`.
|
||||
label is `TooShort`, a longer one `TooLong`. **And `&'static`** (QA S-09): `AppContext::new` is a
|
||||
`const fn` taking `&'static [u8]`, so a label is written in the source, not derived from a peer
|
||||
name, file name or message field at run time (a consumer would have to leak memory on purpose to
|
||||
get around it). A consumer builds its contexts as `const`s, which also moves the length check to
|
||||
its compile time. There is no runtime constructor.
|
||||
- **Key bindings** are hashed field by field (no allocation); the window is inclusive at both ends;
|
||||
`verify_binding` checks, in this order, the window's shape and the id length
|
||||
(`InvalidValidity`, `TooLong`), the signature (`InvalidSignature`), then `now`
|
||||
|
||||
@@ -96,10 +96,8 @@ fuzz_target!(|input: &[u8]| {
|
||||
}
|
||||
}
|
||||
5 => {
|
||||
// Any label, and any raw ctx (0..=255 bytes, or a typed error for longer).
|
||||
if let Ok(c) = AppContext::new(data) {
|
||||
assert!(vk.verify(MSG, &c, &f.sig).is_err() || c == f.ctx);
|
||||
}
|
||||
// Any raw ctx (0..=255 bytes, or a typed error for longer). `AppContext` labels are
|
||||
// `&'static` and fixed at compile time, so there is no runtime label to fuzz.
|
||||
let raw = xor_into(f.ctx.as_bytes(), data);
|
||||
match sign::verify_composite_raw(vk, MSG, &raw, &f.sig) {
|
||||
Ok(()) => assert_eq!(raw, f.ctx.as_bytes()),
|
||||
|
||||
+26
-4
@@ -85,6 +85,19 @@ const _: () = assert!(SIGNATURE_LEN == ML_DSA_SIGNATURE_LEN + ed25519_dalek::SIG
|
||||
/// An application context: [`APP_CONTEXT_PREFIX`] followed by the caller's label, 25 to 255 bytes
|
||||
/// in all. It can only be built with that prefix, so a caller cannot pass an empty context, the
|
||||
/// key-binding context or a foreign one by accident.
|
||||
///
|
||||
/// The label is `&'static` (QA S-09): one fixed label per purpose, written in the source, never
|
||||
/// derived from a peer name, a file name or a message field (two purposes whose labels came from
|
||||
/// data could collide). Build it once, at compile time:
|
||||
///
|
||||
/// ```
|
||||
/// use arcanum::sign::AppContext;
|
||||
/// const PLANS: AppContext = match AppContext::new(b"plans") {
|
||||
/// Ok(ctx) => ctx,
|
||||
/// Err(_) => panic!("label is 1 to 231 bytes"),
|
||||
/// };
|
||||
/// assert_eq!(PLANS.as_bytes(), b"domi/arcanum/v2/sig/app/plans");
|
||||
/// ```
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct AppContext {
|
||||
bytes: [u8; MAX_CONTEXT_LEN],
|
||||
@@ -92,12 +105,13 @@ pub struct AppContext {
|
||||
}
|
||||
|
||||
impl AppContext {
|
||||
/// `domi/arcanum/v2/sig/app/` + `label`. Use one fixed label per purpose (Day 3: `plans`).
|
||||
/// `domi/arcanum/v2/sig/app/` + `label`, for a fixed, compile-time label (Day 3: `plans`).
|
||||
/// A `const fn`, so a `const` context is checked when the consumer compiles.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::TooShort`] for an empty label; [`Error::TooLong`] for one over
|
||||
/// [`MAX_APP_LABEL_LEN`] (231) bytes.
|
||||
pub fn new(label: &[u8]) -> Result<Self, Error> {
|
||||
pub const fn new(label: &'static [u8]) -> Result<Self, Error> {
|
||||
if label.is_empty() {
|
||||
return Err(Error::TooShort { input: Input::Context, minimum: 1, actual: 0 });
|
||||
}
|
||||
@@ -106,8 +120,16 @@ impl AppContext {
|
||||
}
|
||||
let mut bytes = [0u8; MAX_CONTEXT_LEN];
|
||||
let p = APP_CONTEXT_PREFIX.len();
|
||||
bytes[..p].copy_from_slice(APP_CONTEXT_PREFIX);
|
||||
bytes[p..p + label.len()].copy_from_slice(label);
|
||||
let mut i = 0;
|
||||
while i < p {
|
||||
bytes[i] = APP_CONTEXT_PREFIX[i];
|
||||
i += 1;
|
||||
}
|
||||
let mut j = 0;
|
||||
while j < label.len() {
|
||||
bytes[p + j] = label[j];
|
||||
j += 1;
|
||||
}
|
||||
Ok(Self { bytes, len: p + label.len() })
|
||||
}
|
||||
|
||||
|
||||
@@ -43,12 +43,14 @@ fn flipping_any_byte_of_the_message_fails() {
|
||||
fn flipping_any_byte_of_the_context_fails() {
|
||||
let (sk, c, sig) = setup(51);
|
||||
let vk = sk.verifying_key();
|
||||
// Through the release API: every byte of the caller's label.
|
||||
// Through the release API: every byte of the caller's label. Labels are `&'static` (QA S-09);
|
||||
// a test may leak a few to build them at run time, which a consumer must not do.
|
||||
let label = b"every-byte";
|
||||
for i in 0..label.len() {
|
||||
let mut l = label.to_vec();
|
||||
l[i] ^= 0x01;
|
||||
assert_eq!(vk.verify(MSG, &AppContext::new(&l).unwrap(), &sig), Err(Error::InvalidSignature), "label byte {i}");
|
||||
let l: &'static [u8] = Box::leak(l.into_boxed_slice());
|
||||
assert_eq!(vk.verify(MSG, &AppContext::new(l).unwrap(), &sig), Err(Error::InvalidSignature), "label byte {i}");
|
||||
}
|
||||
// Through the raw interface: every byte of the whole ctx, Arcanum's prefix included.
|
||||
let full = c.as_bytes().to_vec();
|
||||
@@ -148,7 +150,7 @@ fn a_key_binding_never_verifies_as_an_app_message_and_back() {
|
||||
assert_eq!(sign::verify_composite_raw(vk, &msg, KEM_KEY_CONTEXT, &binding), Ok(()), "documented encoding");
|
||||
|
||||
// As an application message, under any application label: refused.
|
||||
for label in [&b"kem-key"[..], b"", b"domi/arcanum/v2/sig/kem-key", b"x"] {
|
||||
for label in [b"kem-key".as_slice(), b"", b"domi/arcanum/v2/sig/kem-key", b"x"] {
|
||||
if let Ok(c) = AppContext::new(label) {
|
||||
assert_eq!(vk.verify(&msg, &c, &binding), Err(Error::InvalidSignature), "label {label:?}");
|
||||
}
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ use sha2::{Digest, Sha512};
|
||||
const ML: usize = 3309; // the ML-DSA-65 half comes first
|
||||
const ML_PK: usize = 1952;
|
||||
|
||||
fn ctx(label: &[u8]) -> AppContext {
|
||||
fn ctx(label: &'static [u8]) -> AppContext {
|
||||
AppContext::new(label).unwrap()
|
||||
}
|
||||
|
||||
|
||||
@@ -157,7 +157,7 @@ fn the_raw_interface_is_not_reachable_without_hazmat() {
|
||||
/// `Deref`/`AsRef` to the component keys, and an `AppContext` only from the Arcanum prefix.
|
||||
#[test]
|
||||
fn ml_dsa_internals_are_not_reachable() {
|
||||
let calls: [(&str, &str, &[&str]); 8] = [
|
||||
let calls: [(&str, &str, &[&str]); 9] = [
|
||||
("re-export of ml_dsa", "use arcanum::ml_dsa;", &["E0432"]),
|
||||
("re-export in sign", "use arcanum::sign::ml_dsa;", &["E0432"]),
|
||||
("sign_internal through the key", "let _ = key().sign_internal(&[b\"m\"], &Default::default());", &["E0599"]),
|
||||
@@ -170,6 +170,11 @@ fn ml_dsa_internals_are_not_reachable() {
|
||||
("a component key field", "let k = key(); let _ = &k.ml;", &["E0609", "E0616"]),
|
||||
("a foreign or empty context", "let _ = arcanum::sign::AppContext::from_raw(b\"\");", &["E0599"]),
|
||||
("cloning a signing key", "let k = key(); let _ = k.clone();", &["E0599"]),
|
||||
(
|
||||
"a label built at run time (QA S-09)",
|
||||
"let l = std::env::args().next().unwrap().into_bytes(); let _ = arcanum::sign::AppContext::new(&l);",
|
||||
&["E0597", "E0716"],
|
||||
),
|
||||
];
|
||||
for (what, body, needles) in calls {
|
||||
assert_refused(what, body, needles);
|
||||
|
||||
@@ -101,6 +101,11 @@ fn contexts_of_the_wrong_length_are_typed_errors() {
|
||||
Error::TooLong { input: Input::Context, maximum: MAX_APP_LABEL_LEN, actual: MAX_APP_LABEL_LEN + 1 }
|
||||
);
|
||||
assert_eq!(AppContext::new(b"").unwrap_err(), Error::TooShort { input: Input::Context, minimum: 1, actual: 0 });
|
||||
// QA S-09: the constructor is a `const fn`, so a bad label can fail the consumer's build.
|
||||
const OK: Result<AppContext, Error> = AppContext::new(b"const");
|
||||
const EMPTY: Result<AppContext, Error> = AppContext::new(b"");
|
||||
assert_eq!(OK.unwrap().as_bytes(), b"domi/arcanum/v2/sig/app/const");
|
||||
assert!(EMPTY.is_err());
|
||||
|
||||
// The raw RFC interface: 255 bytes is the most, 256 is a typed error (sign and verify).
|
||||
let sig = sign::sign_composite_raw(&sk, b"m", &[1; 255], &mut rng(64)).unwrap();
|
||||
@@ -149,8 +154,6 @@ fn random_bytes_never_panic() {
|
||||
let sig = k.sign(&buf, &c, &mut r).unwrap();
|
||||
assert_eq!(k.verifying_key().verify(&buf, &c, &sig), Ok(()));
|
||||
}
|
||||
// Random labels: typed errors or a context, never a panic.
|
||||
let _ = AppContext::new(&buf[..len.min(300)]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user