Skip to main content

umbera_core/
amf.rs

1//! AMF — Asymmetric Message Franking (verifiable abuse reporting), server-blind.
2//!
3//! Faithful implementation of the AMF design of Tyagi, Grubbs, Len, Miers, Ristenpart
4//! ("Asymmetric Message Franking: Content Moderation for Metadata-Private E2E Encryption",
5//! CRYPTO 2019): a **designated-verifier signature with a judge**, realized as a non-interactive
6//! (Fiat–Shamir) **CDS OR-proof** over a prime-order group (Ristretto255) plus a judge-openable
7//! ElGamal tag. NO server signing → the server stays blind; sender binding comes from the sender's
8//! own key, deniability from receiver-forgeability, accountability from the judge key.
9//!
10//! ⚠️ SECURITY-CRITICAL. This realizes the AMF *construction shape* (Σ-protocol OR + judge tag);
11//! the algebraic relations are documented inline. REVIEW against the published paper before
12//! production use to guarantee bit-exact security equivalence.
13//!
14//! Group `G = Ristretto255`, basepoint `B`, prime order `ℓ`. Keys `(x, P = x·B)`.
15//! Parties: Sender `(a, PkS)`, Receiver `(r, PkR)`, Judge `(j, PkJ)`.
16//!
17//! ## Frank(a, PkR, PkJ, m) → σ
18//! Judge tag (ElGamal under PkJ, encrypting the *real signer's* public key as the "branch label"):
19//!   `T1 = k·B`,  `T2 = k·PkJ + PkS`   (so `Judge: T2 − j·T1 = PkS`).
20//! OR-proof (CDS) of the statement, Fiat–Shamir-bound to `m`:
21//!   `{ ∃(a,k): PkS=a·B ∧ T1=k·B ∧ T2=a·B+k·PkJ }`   (sender branch — the REAL one)
22//!   `OR  { ∃(r,k'): PkR=r·B ∧ T1=k'·B ∧ T2=r·B+k'·PkJ }` (receiver branch — simulated).
23//!
24//! ## Verify (receiver): only checks the OR-proof. A sender-σ AND a receiver-forge both pass →
25//! non-transferable → **deniability**. The receiver, knowing they didn't forge it, is convinced.
26//! ## Judge: checks the OR-proof AND decrypts `M = T2 − j·T1`; accepts the accusation iff `M == PkS`
27//! → a receiver forgery (which encrypts PkR) is rejected → can't frame the sender → **sender binding**.
28
29use curve25519_dalek::constants::RISTRETTO_BASEPOINT_POINT as B;
30use curve25519_dalek::ristretto::{CompressedRistretto, RistrettoPoint};
31use curve25519_dalek::scalar::Scalar;
32use hmac::{Hmac, Mac};
33use sha2::{Digest, Sha256, Sha512};
34
35type R<T> = Result<T, AmfError>;
36
37#[derive(Debug, thiserror::Error, uniffi::Error)]
38pub enum AmfError {
39    #[error("amf crypto error: {0}")]
40    Crypto(String),
41}
42fn err<T>(m: &str) -> R<T> {
43    Err(AmfError::Crypto(m.to_string()))
44}
45
46#[derive(uniffi::Record)]
47pub struct AmfKeyPair {
48    pub secret: Vec<u8>,
49    pub public: Vec<u8>,
50}
51
52// ── helpers ──────────────────────────────────────────────────────────────────
53fn rand_scalar() -> Scalar {
54    let mut b = [0u8; 64];
55    getrandom::fill(&mut b).expect("OS RNG");
56    Scalar::from_bytes_mod_order_wide(&b)
57}
58fn pt_bytes(p: &RistrettoPoint) -> [u8; 32] {
59    p.compress().to_bytes()
60}
61fn pt_from(b: &[u8]) -> R<RistrettoPoint> {
62    if b.len() != 32 {
63        return err("point must be 32 bytes");
64    }
65    CompressedRistretto::from_slice(b)
66        .map_err(|_| AmfError::Crypto("bad compressed point".into()))?
67        .decompress()
68        .ok_or_else(|| AmfError::Crypto("point not on curve".into()))
69}
70fn sc_from(b: &[u8]) -> R<Scalar> {
71    let arr: [u8; 32] = b.try_into().map_err(|_| AmfError::Crypto("scalar must be 32 bytes".into()))?;
72    Option::<Scalar>::from(Scalar::from_canonical_bytes(arr))
73        .ok_or_else(|| AmfError::Crypto("non-canonical scalar".into()))
74}
75
76/// Fiat–Shamir challenge over the full transcript (domain-separated, binds the message).
77fn challenge(msg: &[u8], pts: &[&RistrettoPoint]) -> Scalar {
78    let mut h = Sha512::new();
79    h.update(b"TYPEX-AMF-v1/challenge");
80    h.update((msg.len() as u64).to_le_bytes());
81    h.update(msg);
82    for p in pts {
83        h.update(p.compress().as_bytes());
84    }
85    let d = h.finalize();
86    let mut wide = [0u8; 64];
87    wide.copy_from_slice(&d);
88    Scalar::from_bytes_mod_order_wide(&wide)
89}
90
91// One CDS branch's three Schnorr commitments for relations (P = w1·B, T1 = w2·B, T2 = w1·B + w2·PkJ),
92// recomputed from a (challenge, responses) pair: A = z·Gen − c·Stmt.
93struct Branch {
94    a1: RistrettoPoint, // for P
95    a2: RistrettoPoint, // for T1
96    a3: RistrettoPoint, // for T2
97}
98fn recompute_branch(
99    p: &RistrettoPoint,
100    t1: &RistrettoPoint,
101    t2: &RistrettoPoint,
102    pk_j: &RistrettoPoint,
103    c: &Scalar,
104    z1: &Scalar,
105    z2: &Scalar,
106) -> Branch {
107    Branch {
108        a1: z1 * B - c * p,
109        a2: z2 * B - c * t1,
110        a3: (z1 * B + z2 * pk_j) - c * t2,
111    }
112}
113
114// ── public API (uniffi) ───────────────────────────────────────────────────────
115
116/// Per-message binding commitment: HMAC-SHA256(frankKey, plaintext). Selective disclosure — the
117/// frankKey is fresh per message, so revealing one message's key/commitment reveals nothing else.
118#[uniffi::export]
119pub fn amf_commit(frank_key: Vec<u8>, msg: Vec<u8>) -> R<Vec<u8>> {
120    let mut mac = <Hmac<Sha256> as hmac::KeyInit>::new_from_slice(&frank_key)
121        .map_err(|_| AmfError::Crypto("bad hmac key".into()))?;
122    mac.update(&msg);
123    Ok(mac.finalize().into_bytes().to_vec())
124}
125
126/// New AMF identity keypair (Ristretto). Private stays on-device; public is shared E2E.
127#[uniffi::export]
128pub fn amf_keygen() -> AmfKeyPair {
129    let x = rand_scalar();
130    AmfKeyPair {
131        secret: x.to_bytes().to_vec(),
132        public: pt_bytes(&(x * B)).to_vec(),
133    }
134}
135
136/// Public key for a secret (helper for tests / key derivation).
137#[uniffi::export]
138pub fn amf_public_of(secret: Vec<u8>) -> R<Vec<u8>> {
139    let x = sc_from(&secret)?;
140    Ok(pt_bytes(&(x * B)).to_vec())
141}
142
143/// Deterministic keypair from a seed (e.g. the group's MLS-exported secret). Used for the GROUP
144/// "receiver" designated-verifier key so franking is ONE signature per message (group AMF, not
145/// pairwise) and reveals no member identity. Scalar = reduce(SHA512(domain || seed)).
146#[uniffi::export]
147pub fn amf_keypair_from_seed(seed: Vec<u8>) -> AmfKeyPair {
148    let mut h = Sha512::new();
149    h.update(b"TYPEX-AMF-v1/seed");
150    h.update(&seed);
151    let d = h.finalize();
152    let mut wide = [0u8; 64];
153    wide.copy_from_slice(&d);
154    let x = Scalar::from_bytes_mod_order_wide(&wide);
155    AmfKeyPair {
156        secret: x.to_bytes().to_vec(),
157        public: pt_bytes(&(x * B)).to_vec(),
158    }
159}
160
161// Internal signer used by both frank (sender-real) and forge (receiver-real). `real_sender`
162// selects which branch is the honest one; `label` is the point encrypted in the judge tag.
163fn sign_internal(
164    sk_real: &Scalar,
165    pk_real: &RistrettoPoint,
166    pk_sim: &RistrettoPoint,
167    pk_j: &RistrettoPoint,
168    label: &RistrettoPoint, // PkS for a real sender; PkR for a receiver forge
169    msg: &[u8],
170    sender_is_real: bool,
171) -> Vec<u8> {
172    // ElGamal judge tag encrypting `label` under PkJ.
173    let k = rand_scalar();
174    let t1 = k * B;
175    let t2 = k * pk_j + label;
176
177    // Honest branch nonces.
178    let rho1 = rand_scalar();
179    let rho2 = rand_scalar();
180    let a1 = rho1 * B;
181    let a2 = rho2 * B;
182    let a3 = rho1 * B + rho2 * pk_j;
183
184    // Simulated branch: random challenge + responses → back-compute its commitments.
185    let c_sim = rand_scalar();
186    let z_sim_1 = rand_scalar();
187    let z_sim_2 = rand_scalar();
188    let sim = recompute_branch(pk_sim, &t1, &t2, pk_j, &c_sim, &z_sim_1, &z_sim_2);
189
190    // Transcript order is ALWAYS (sender-branch commitments, receiver-branch commitments) so
191    // verify/judge can recompute identically regardless of which side is real.
192    let (sa1, sa2, sa3, ra1, ra2, ra3) = if sender_is_real {
193        (&a1, &a2, &a3, &sim.a1, &sim.a2, &sim.a3)
194    } else {
195        (&sim.a1, &sim.a2, &sim.a3, &a1, &a2, &a3)
196    };
197    // PkS, PkR for the transcript (real/sim mapped to sender/receiver slots).
198    let (pk_s_t, pk_r_t) = if sender_is_real { (pk_real, pk_sim) } else { (pk_sim, pk_real) };
199
200    let c = challenge(
201        msg,
202        &[pk_s_t, pk_r_t, pk_j, &t1, &t2, sa1, sa2, sa3, ra1, ra2, ra3],
203    );
204    let c_real = c - c_sim;
205    let z_real_1 = rho1 + c_real * sk_real;
206    let z_real_2 = rho2 + c_real * k;
207
208    // Serialize as (T1, T2, c_s, c_r, z_s1, z_s2, z_r1, z_r2) — sender slot first.
209    let (c_s, c_r, z_s1, z_s2, z_r1, z_r2) = if sender_is_real {
210        (c_real, c_sim, z_real_1, z_real_2, z_sim_1, z_sim_2)
211    } else {
212        (c_sim, c_real, z_sim_1, z_sim_2, z_real_1, z_real_2)
213    };
214    let mut out = Vec::with_capacity(256);
215    for b in [
216        pt_bytes(&t1),
217        pt_bytes(&t2),
218        c_s.to_bytes(),
219        c_r.to_bytes(),
220        z_s1.to_bytes(),
221        z_s2.to_bytes(),
222        z_r1.to_bytes(),
223        z_r2.to_bytes(),
224    ] {
225        out.extend_from_slice(&b);
226    }
227    out
228}
229
230/// Sender franks a message: produces an AMF signature binding (sender authored exactly `msg`),
231/// verifiable by the receiver, openable by the judge, deniable to everyone else.
232#[uniffi::export]
233pub fn amf_frank(sk_s: Vec<u8>, pk_r: Vec<u8>, pk_j: Vec<u8>, msg: Vec<u8>) -> R<Vec<u8>> {
234    let a = sc_from(&sk_s)?;
235    let pk_s = a * B;
236    let pk_r = pt_from(&pk_r)?;
237    let pk_j = pt_from(&pk_j)?;
238    Ok(sign_internal(&a, &pk_s, &pk_r, &pk_j, &pk_s, &msg, true))
239}
240
241struct Sig {
242    t1: RistrettoPoint,
243    t2: RistrettoPoint,
244    c_s: Scalar,
245    c_r: Scalar,
246    z_s1: Scalar,
247    z_s2: Scalar,
248    z_r1: Scalar,
249    z_r2: Scalar,
250}
251fn parse_sig(sig: &[u8]) -> R<Sig> {
252    if sig.len() != 256 {
253        return err("signature must be 256 bytes");
254    }
255    Ok(Sig {
256        t1: pt_from(&sig[0..32])?,
257        t2: pt_from(&sig[32..64])?,
258        c_s: sc_from(&sig[64..96])?,
259        c_r: sc_from(&sig[96..128])?,
260        z_s1: sc_from(&sig[128..160])?,
261        z_s2: sc_from(&sig[160..192])?,
262        z_r1: sc_from(&sig[192..224])?,
263        z_r2: sc_from(&sig[224..256])?,
264    })
265}
266
267fn check_or_proof(pk_s: &RistrettoPoint, pk_r: &RistrettoPoint, pk_j: &RistrettoPoint, msg: &[u8], s: &Sig) -> bool {
268    let sb = recompute_branch(pk_s, &s.t1, &s.t2, pk_j, &s.c_s, &s.z_s1, &s.z_s2);
269    let rb = recompute_branch(pk_r, &s.t1, &s.t2, pk_j, &s.c_r, &s.z_r1, &s.z_r2);
270    let c = challenge(
271        msg,
272        &[pk_s, pk_r, pk_j, &s.t1, &s.t2, &sb.a1, &sb.a2, &sb.a3, &rb.a1, &rb.a2, &rb.a3],
273    );
274    (s.c_s + s.c_r) == c
275}
276
277/// Receiver-side verification: the OR-proof is valid. (Deniable: a receiver forgery also passes.)
278#[uniffi::export]
279pub fn amf_verify(pk_s: Vec<u8>, pk_r: Vec<u8>, pk_j: Vec<u8>, msg: Vec<u8>, sig: Vec<u8>) -> R<bool> {
280    let pk_s = pt_from(&pk_s)?;
281    let pk_r = pt_from(&pk_r)?;
282    let pk_j = pt_from(&pk_j)?;
283    let s = parse_sig(&sig)?;
284    Ok(check_or_proof(&pk_s, &pk_r, &pk_j, &msg, &s))
285}
286
287/// Judge-side adjudication: OR-proof valid AND the judge tag decrypts to PkS (the accused sender).
288/// A receiver forgery encrypts PkR → judge returns false → the sender can't be framed.
289#[uniffi::export]
290pub fn amf_judge(pk_s: Vec<u8>, pk_r: Vec<u8>, sk_j: Vec<u8>, msg: Vec<u8>, sig: Vec<u8>) -> R<bool> {
291    let pk_s = pt_from(&pk_s)?;
292    let pk_r = pt_from(&pk_r)?;
293    let j = sc_from(&sk_j)?;
294    let pk_j = j * B;
295    let s = parse_sig(&sig)?;
296    if !check_or_proof(&pk_s, &pk_r, &pk_j, &msg, &s) {
297        return Ok(false);
298    }
299    let label = s.t2 - j * s.t1; // ElGamal decrypt
300    Ok(label == pk_s)
301}
302
303/// Receiver forgery (knows `sk_r`) — used to PROVE deniability in tests: it produces a signature
304/// that `amf_verify` accepts but `amf_judge` rejects (the tag encrypts PkR, not PkS). The existence
305/// of this forgery is exactly why a verifying signature is non-transferable to a third party.
306#[uniffi::export]
307pub fn amf_forge(pk_s: Vec<u8>, sk_r: Vec<u8>, pk_j: Vec<u8>, msg: Vec<u8>) -> R<Vec<u8>> {
308    let r = sc_from(&sk_r)?;
309    let pk_r = r * B;
310    let pk_s = pt_from(&pk_s)?;
311    let pk_j = pt_from(&pk_j)?;
312    Ok(sign_internal(&r, &pk_r, &pk_s, &pk_j, &pk_r, &msg, false))
313}
314
315#[cfg(test)]
316mod tests {
317    use super::*;
318
319    #[test]
320    fn frank_verify_judge_roundtrip() {
321        let s = amf_keygen();
322        let r = amf_keygen();
323        let j = amf_keygen();
324        let msg = b"hello group".to_vec();
325        let sig = amf_frank(s.secret.clone(), r.public.clone(), j.public.clone(), msg.clone()).unwrap();
326        // P2: receiver verifies + judge confirms the sender.
327        assert!(amf_verify(s.public.clone(), r.public.clone(), j.public.clone(), msg.clone(), sig.clone()).unwrap());
328        assert!(amf_judge(s.public.clone(), r.public.clone(), j.secret.clone(), msg.clone(), sig.clone()).unwrap());
329    }
330
331    #[test]
332    fn tamper_fails() {
333        let s = amf_keygen();
334        let r = amf_keygen();
335        let j = amf_keygen();
336        let sig = amf_frank(s.secret.clone(), r.public.clone(), j.public.clone(), b"a".to_vec()).unwrap();
337        // Different message → verification fails.
338        assert!(!amf_verify(s.public.clone(), r.public.clone(), j.public.clone(), b"b".to_vec(), sig).unwrap());
339    }
340
341    #[test]
342    fn deniability_and_sender_binding() {
343        // P5: the receiver can FORGE a verify-valid signature → non-transferable.
344        // P2: but the judge rejects the forgery (it isn't really from the sender).
345        let s = amf_keygen();
346        let r = amf_keygen();
347        let j = amf_keygen();
348        let msg = b"deniable".to_vec();
349        let forged = amf_forge(s.public.clone(), r.secret.clone(), j.public.clone(), msg.clone()).unwrap();
350        assert!(amf_verify(s.public.clone(), r.public.clone(), j.public.clone(), msg.clone(), forged.clone()).unwrap(),
351                "forgery must verify (deniability)");
352        assert!(!amf_judge(s.public.clone(), r.public.clone(), j.secret.clone(), msg.clone(), forged).unwrap(),
353                "judge must REJECT the receiver forgery (sender binding)");
354    }
355
356    #[test]
357    fn commit_binds() {
358        let k = vec![7u8; 32];
359        let c1 = amf_commit(k.clone(), b"x".to_vec()).unwrap();
360        let c2 = amf_commit(k.clone(), b"y".to_vec()).unwrap();
361        let c1b = amf_commit(k, b"x".to_vec()).unwrap();
362        assert_eq!(c1, c1b);
363        assert_ne!(c1, c2);
364    }
365}