Skip to main content

securedrop_protocol_minimal/
ciphertext.rs

1use crate::message::MessageCiphertext;
2use crate::metadata::MetadataCiphertext;
3use crate::primitives::provider::constants::LEN_KMID;
4use crate::primitives::ristretto255::{DH_PUBLIC_KEY_LEN, DHPublicKey};
5use crate::primitives::xwing::XWING_PUBLIC_KEY_LEN;
6use alloc::vec::Vec;
7use anyhow::Error;
8#[cfg(not(hax))]
9use serde::{Deserialize, Serialize};
10
11/// Hex string serde for fixed length byte arrays
12#[cfg(not(hax))]
13mod hex_array {
14    use alloc::string::String;
15    use serde::de::Error as _;
16    use serde::{Deserialize, Deserializer, Serializer};
17
18    pub fn serialize<const N: usize, S: Serializer>(
19        bytes: &[u8; N],
20        ser: S,
21    ) -> Result<S::Ok, S::Error> {
22        ser.serialize_str(&hex::encode(bytes))
23    }
24
25    pub fn deserialize<'de, const N: usize, D: Deserializer<'de>>(
26        de: D,
27    ) -> Result<[u8; N], D::Error> {
28        let s = String::deserialize(de)?;
29        let mut out = [0u8; N];
30        hex::decode_to_slice(s.trim(), &mut out).map_err(D::Error::custom)?;
31        Ok(out)
32    }
33}
34
35/// The full submission `(C_S, X, Z)` sent from sender to server in step 6.
36///
37/// - `C_S = (ct^APKE, ct^PKE)`: the two ciphertexts
38/// - `X = g^x`: ephemeral DH public key (hint)
39/// - `Z = (pk_R^fetch)^x`: DH share for fetching (hint)
40///
41/// The server stores `(id, C_S, X, Z)` per message.
42#[derive(Debug, Clone)]
43#[cfg_attr(not(hax), derive(Serialize, Deserialize))]
44pub struct Envelope {
45    /// `ct^APKE`: SD-APKE ciphertext `((c1, cp), c2)` - the encrypted message
46    pub(crate) ct_apke: MessageCiphertext,
47
48    /// `ct^PKE`: SD-PKE ciphertext `(c, c')` - the encrypted sender APKE public key
49    pub(crate) ct_pke: MetadataCiphertext,
50
51    /// `X = g^x`: ephemeral DH public key for the hint
52    pub(crate) mgdh_pubkey: DHPublicKey,
53
54    /// `Z = (pk_R^fetch)^x`: DH share for fetching
55    pub(crate) mgdh: DHPublicKey,
56}
57
58impl Envelope {
59    // Used for benchmarks - see wasm_bindgen
60    pub fn size_hint(&self) -> usize {
61        self.ct_apke.len() + self.ct_pke.len()
62    }
63
64    pub fn cmessage_len(&self) -> usize {
65        self.ct_apke.len()
66    }
67
68    // SD-PKE ciphertext byte length: encapsulation c + AEAD ciphertext c'
69    pub fn cmetadata_len(&self) -> usize {
70        self.ct_pke.len()
71    }
72}
73
74#[derive(Debug, Clone)]
75/// Toy pt structure - TODO: provide params in correct order
76pub struct Plaintext {
77    /// Metadata key: $pk_S^{PKE}$ in the spec
78    pub sender_reply_pubkey_hybrid: [u8; XWING_PUBLIC_KEY_LEN],
79    /// Fetching key: $pk_S^{fetch}$ in the spec
80    pub sender_fetch_key: DHPublicKey,
81    /// Message
82    pub msg: Vec<u8>,
83}
84
85impl Plaintext {
86    pub fn to_bytes(&self) -> alloc::vec::Vec<u8> {
87        // TODO: Deviates from spec
88        let mut buf = Vec::new();
89
90        buf.extend_from_slice(&self.sender_reply_pubkey_hybrid);
91        buf.extend_from_slice(&self.sender_fetch_key.into_bytes());
92        buf.extend_from_slice(&self.msg);
93
94        buf
95    }
96
97    pub fn len(&self) -> usize {
98        XWING_PUBLIC_KEY_LEN + DH_PUBLIC_KEY_LEN + self.msg.len()
99    }
100
101    // Toy parsing only
102    pub fn from_bytes(pt_bytes: &[u8]) -> Result<Self, Error> {
103        let mut offset = 0;
104
105        let mut sender_reply_pubkey_hybrid = [0u8; XWING_PUBLIC_KEY_LEN];
106        sender_reply_pubkey_hybrid
107            .copy_from_slice(&pt_bytes[offset..offset + XWING_PUBLIC_KEY_LEN]);
108        offset += XWING_PUBLIC_KEY_LEN;
109
110        let mut fetch_key_bytes = [0u8; DH_PUBLIC_KEY_LEN];
111        fetch_key_bytes.copy_from_slice(&pt_bytes[offset..offset + DH_PUBLIC_KEY_LEN]);
112
113        let sender_fetch_key = DHPublicKey::decode(fetch_key_bytes)?;
114        offset += DH_PUBLIC_KEY_LEN;
115
116        let msg = pt_bytes[offset..].to_vec();
117
118        Ok(Plaintext {
119            sender_reply_pubkey_hybrid,
120            sender_fetch_key,
121            msg,
122        })
123    }
124}
125
126#[derive(Clone, Debug)]
127#[cfg_attr(not(hax), derive(Serialize, Deserialize))]
128pub struct FetchResponse {
129    #[cfg_attr(not(hax), serde(with = "hex_array"))]
130    pub(crate) enc_id: [u8; LEN_KMID], // aka kmid
131    // `Q_k`, the per-request clue
132    pub(crate) pmgdh: DHPublicKey,
133}
134
135impl FetchResponse {
136    pub fn new(enc_id: [u8; LEN_KMID], pmgdh: DHPublicKey) -> Self {
137        Self { enc_id, pmgdh }
138    }
139}
140
141#[cfg(test)]
142mod tests {
143    use super::*;
144    use crate::metadata::LEN_METADATA_CIPHERTEXT;
145    use crate::primitives::dh_akem::DH_AKEM_ENCAPS_SECRET_LEN;
146    use crate::primitives::mlkem::LEN_MLKEM_SHAREDSECRET_ENCAPS;
147    use crate::primitives::ristretto255::random_dh_public_key;
148    use crate::primitives::xwing::LEN_XWING_SHAREDSECRET_ENCAPS;
149    use proptest::prelude::*;
150    use rand_chacha::ChaCha20Rng;
151    use rand_core::SeedableRng;
152
153    fn message_ct(c1: Vec<u8>, cp: Vec<u8>, c2: Vec<u8>) -> MessageCiphertext {
154        MessageCiphertext {
155            c1: c1.try_into().expect("c1 length"),
156            cp,
157            c2: c2.try_into().expect("c2 length"),
158        }
159    }
160
161    proptest! {
162        #[test]
163        fn test_message_ciphertext_byte_roundtrip(
164            c1 in prop::collection::vec(any::<u8>(), DH_AKEM_ENCAPS_SECRET_LEN),
165            cp in prop::collection::vec(any::<u8>(), 0..128),
166            c2 in prop::collection::vec(any::<u8>(), LEN_MLKEM_SHAREDSECRET_ENCAPS),
167        ) {
168            let ct = message_ct(c1, cp, c2);
169            let restored = MessageCiphertext::from_bytes(&ct.as_bytes()).expect("valid bytes");
170            prop_assert_eq!(ct.as_bytes(), restored.as_bytes());
171        }
172
173        #[test]
174        fn test_metadata_ciphertext_byte_roundtrip(
175            c in prop::collection::vec(any::<u8>(), LEN_XWING_SHAREDSECRET_ENCAPS),
176            cp in prop::collection::vec(any::<u8>(), LEN_METADATA_CIPHERTEXT)
177            .prop_map(|v| v.try_into().unwrap()),
178        ) {
179            let ct = MetadataCiphertext { c: c.try_into().expect("c length"), cp };
180            let restored = MetadataCiphertext::from_bytes(&ct.as_bytes()).expect("valid bytes");
181            prop_assert_eq!(ct.as_bytes(), restored.as_bytes());
182        }
183
184        #[test]
185        fn test_envelope_serde_roundtrip(
186            c1 in prop::collection::vec(any::<u8>(), DH_AKEM_ENCAPS_SECRET_LEN),
187            cp_a in prop::collection::vec(any::<u8>(), 0..128),
188            c2 in prop::collection::vec(any::<u8>(), LEN_MLKEM_SHAREDSECRET_ENCAPS),
189            c in prop::collection::vec(any::<u8>(), LEN_XWING_SHAREDSECRET_ENCAPS),
190            cp_b in prop::collection::vec(any::<u8>(), LEN_METADATA_CIPHERTEXT)
191            .prop_map(|v| v.try_into().unwrap()),
192            rng_seed: u64,
193        ) {
194            // X and Z must be valid ristretto255 encodings
195            let mut rng = ChaCha20Rng::seed_from_u64(rng_seed);
196            let mgdh_pubkey = random_dh_public_key(&mut rng);
197            let mgdh = random_dh_public_key(&mut rng);
198
199            let env = Envelope {
200                ct_apke: message_ct(c1, cp_a, c2),
201                ct_pke: MetadataCiphertext { c: c.try_into().expect("c length"), cp: cp_b },
202                mgdh_pubkey,
203                mgdh,
204            };
205            let json = serde_json::to_string(&env).expect("serialize");
206            let restored: Envelope = serde_json::from_str(&json).expect("deserialize");
207            prop_assert_eq!(env.ct_apke.as_bytes(), restored.ct_apke.as_bytes());
208            prop_assert_eq!(env.ct_pke.as_bytes(), restored.ct_pke.as_bytes());
209            prop_assert_eq!(env.mgdh_pubkey.into_bytes(), restored.mgdh_pubkey.into_bytes());
210            prop_assert_eq!(env.mgdh.into_bytes(), restored.mgdh.into_bytes());
211        }
212
213        #[test]
214        fn test_fetch_challenge_response_serde_roundtrip(
215            enc_ids in prop::collection::vec(
216                prop::collection::vec(any::<u8>(), LEN_KMID), 0..6),
217            rng_seed: u64,
218        ) {
219            // pmgdh is a ristretto255 group element
220            let mut rng = ChaCha20Rng::seed_from_u64(rng_seed);
221            let messages: Vec<FetchResponse> = enc_ids
222                .iter()
223                .map(|enc_id| FetchResponse {
224                    enc_id: enc_id.clone().try_into().expect("enc_id length"),
225                    pmgdh: random_dh_public_key(&mut rng),
226                })
227                .collect();
228            let n = messages.len();
229            let resp = crate::wire::core::MessageChallengeFetchResponse { count: n, messages };
230
231            let json = serde_json::to_string(&resp).expect("serialize");
232            let restored: crate::wire::core::MessageChallengeFetchResponse =
233                serde_json::from_str(&json).expect("deserialize");
234
235            prop_assert_eq!(restored.count, resp.count);
236            prop_assert_eq!(restored.messages.len(), resp.messages.len());
237            for (a, b) in resp.messages.iter().zip(restored.messages.iter()) {
238                prop_assert_eq!(a.enc_id, b.enc_id);
239                prop_assert_eq!(a.pmgdh.into_bytes(), b.pmgdh.into_bytes());
240            }
241        }
242    }
243}