Skip to main content

securedrop_protocol_minimal/
source.rs

1use crate::VerifyingKey;
2use crate::api::Client;
3use crate::message::{MessagePublicKey, deterministic_keygen as kgen_deterministic_message};
4use crate::metadata::{MetadataPublicKey, deterministic_keygen as kgen_deterministic_metadata};
5use crate::primitives::ristretto255::{DHPrivateKey, DHPublicKey, deterministic_dh_keygen};
6use alloc::string::{String, ToString};
7use alloc::vec::Vec;
8use anyhow::Error;
9use bip39::{Language, Mnemonic};
10use rand_core::{CryptoRng, RngCore};
11
12use crate::ciphertext::Plaintext;
13use crate::keys::*;
14use crate::primitives::dh_akem::DhAkemPrivateKey;
15use crate::primitives::mlkem::MLKEM768PrivateKey;
16use crate::primitives::provider::hkdf;
17use crate::primitives::xwing::{XWingPrivateKey, XWingPublicKey};
18use crate::traits::{UserPublic, UserSecret};
19
20// do not re-export!
21use crate::sealed;
22
23#[cfg(not(hax))]
24impl sealed::Sealed for Source {}
25
26/// Fixed, public, application-specific salt for source key derivation.
27const SOURCE_KDF_SALT: &[u8] = b"securedrop-source-v1";
28
29/// A source and their long-term key material (step 4).
30///
31/// A source's keys are fully determined by their passphrase, a 12-word BIP39
32/// mnemonic. The mnemonic's 16-byte entropy is used directly as the master key
33/// `mk`, from which the fetch key, APKE key, and PKE key are derived with a
34/// domain-separated KDF. Returning sources reconstruct the same keys by calling
35/// [`Source::from_passphrase`] with the same mnemonic.
36pub struct Source {
37    fetch_key: DhFetchKeyPair,
38    message_keys: MessageKeyBundle,
39    passphrase: String,
40    session: SessionStorage,
41}
42
43// hax struggles with the debug format function signature, but it is
44// debug only, so we can exclude it from extraction
45#[cfg_attr(hax, hax_lib::exclude)]
46impl core::fmt::Debug for Source {
47    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
48        // Using non-exhaustive to avoid leaking source keys.
49        f.debug_struct("Source").finish_non_exhaustive()
50    }
51}
52
53/// The public key material of a source, used by journalists to send replies.
54#[derive(Debug, Clone)]
55pub struct SourcePublicView {
56    fetch_pk: DHPublicKey,
57    message_pks: KeyBundlePublic,
58}
59
60impl UserPublic for SourcePublicView {
61    fn fetch_pk(&self) -> &DHPublicKey {
62        &self.fetch_pk
63    }
64
65    fn message_auth_pk(&self) -> &MessagePublicKey {
66        &self.message_pks.apke_pk
67    }
68
69    fn message_metadata_pk(&self) -> &MetadataPublicKey {
70        &self.message_pks.metadata_pk
71    }
72
73    fn message_enc_pk(&self) -> &MessagePublicKey {
74        &self.message_pks.apke_pk
75    }
76}
77
78impl Client for Source {
79    fn newsroom_verifying_key(&self) -> Option<&VerifyingKey> {
80        self.session.nr_key.as_ref()
81    }
82
83    fn set_newsroom_verifying_key(&mut self, key: VerifyingKey) {
84        self.session.nr_key = Some(key);
85    }
86}
87
88/// Private, common to all users, implemented for sources
89impl UserSecret for Source {
90    fn num_bundles(&self) -> usize {
91        1
92    }
93
94    fn fetch_keypair(&self) -> (&DHPrivateKey, &DHPublicKey) {
95        (&self.fetch_key.sk, &self.fetch_key.pk)
96    }
97
98    fn message_auth_keypair(&self) -> &crate::message::MessageKeyPair {
99        &self.message_keys.apke
100    }
101
102    fn build_message(&self, message: Vec<u8>) -> Plaintext {
103        let mut reply_key_pq_hybrid = [0u8; XWingPublicKey::LEN];
104        reply_key_pq_hybrid.copy_from_slice(self.message_keys.metadata_kp.public_key().as_bytes());
105
106        Plaintext {
107            sender_fetch_key: self.fetch_key.pk,
108            sender_reply_pubkey_hybrid: reply_key_pq_hybrid,
109            msg: message,
110        }
111    }
112
113    fn keybundles(&self) -> Vec<&MessageKeyBundle> {
114        alloc::vec![&self.message_keys]
115    }
116}
117
118impl Source {
119    /// Create a new source with a randomly generated 12-word BIP39 mnemonic.
120    #[cfg_attr(hax, hax_lib::opaque)]
121    pub fn new<R: RngCore + CryptoRng>(mut rng: R) -> Self {
122        let mut entropy = [0u8; 16];
123        rng.fill_bytes(&mut entropy);
124        let mnemonic = Mnemonic::from_entropy(&entropy).expect("16 bytes is valid BIP39 entropy");
125        Self::from_master_key(&entropy, mnemonic.to_string())
126    }
127
128    /// Returns the source's passphrase as a 12-word BIP39 mnemonic.
129    ///
130    /// # Security
131    ///
132    /// The passphrase is the root secret from which all source keys are
133    /// derived. It MUST be stored and transmitted only over secure channels.
134    #[cfg_attr(hax, hax_lib::opaque)]
135    pub fn passphrase(&self) -> &str {
136        &self.passphrase
137    }
138
139    /// Reconstruct source keys from a 12-word BIP39 mnemonic (step 4).
140    ///
141    /// # Errors
142    ///
143    /// Returns an error if `passphrase` is not a valid 12-word BIP39 mnemonic,
144    /// i.e. it contains an unknown word, has the wrong length, or fails the
145    /// checksum.
146    #[cfg_attr(hax, hax_lib::opaque)]
147    pub fn from_passphrase(passphrase: &str) -> Result<Self, Error> {
148        let mnemonic = Mnemonic::parse_in(Language::English, passphrase)
149            .map_err(|e| anyhow::anyhow!("invalid BIP39 mnemonic: {e}"))?;
150
151        let (entropy, len) = mnemonic.to_entropy_array();
152        if len != 16 {
153            return Err(anyhow::anyhow!(
154                "source passphrase must be a 12-word BIP39 mnemonic (128-bit entropy)"
155            ));
156        }
157        let mut mk = [0u8; 16];
158        mk.copy_from_slice(&entropy[..16]);
159
160        Ok(Self::from_master_key(&mk, mnemonic.to_string()))
161    }
162
163    /// Derive a source's long-term keys from the master key `mk` (the 16-byte
164    /// BIP39 entropy), then assemble the [`Source`] tagged with the originating
165    /// `passphrase` mnemonic.
166    ///
167    /// Each private key is derived from `mk` with a domain-separated KDF.
168    #[cfg_attr(hax, hax_lib::opaque)]
169    fn from_master_key(mk: &[u8; 16], passphrase: String) -> Self {
170        // we need a 64 byte string for the ristretto255 scalar (see RFC 9496 section 4.4).
171        let mut fetch_seed = [0u8; DHPrivateKey::SEED_LEN];
172        hkdf::sha256(&mut fetch_seed, SOURCE_KDF_SALT, mk, b"sourcefetchkey")
173            .expect("HKDF fetch key derivation failed");
174
175        // sk_S^APKE is a hybrid key requiring two sub-derivations:
176        // the DH-AKEM and ML-KEM components are each derived with their own
177        // label under the "sourceAPKEkey" namespace.
178        let mut dh_seed = [0u8; DhAkemPrivateKey::SEED_LEN];
179        hkdf::sha256(&mut dh_seed, SOURCE_KDF_SALT, mk, b"sourceAPKEkey-dh")
180            .expect("HKDF APKE DH key derivation failed");
181
182        let mut mlkem_seed = [0u8; MLKEM768PrivateKey::SEED_LEN];
183        hkdf::sha256(&mut mlkem_seed, SOURCE_KDF_SALT, mk, b"sourceAPKEkey-mlkem")
184            .expect("HKDF APKE ML-KEM key derivation failed");
185
186        let mut pke_seed = [0u8; XWingPrivateKey::SEED_LEN];
187        hkdf::sha256(&mut pke_seed, SOURCE_KDF_SALT, mk, b"sourcePKEkey")
188            .expect("HKDF PKE key derivation failed");
189
190        // Create key pairs
191        let (fetch_sk, fetch_pk): (DHPrivateKey, DHPublicKey) = deterministic_dh_keygen(fetch_seed);
192
193        let message_kp =
194            kgen_deterministic_message(dh_seed, mlkem_seed).expect("Need SD-APKE keygen");
195
196        let metadata_kp = kgen_deterministic_metadata(pke_seed).expect("Need X-Wing keygen");
197
198        let session = SessionStorage {
199            fpf_key: None,
200            nr_key: None,
201            fpf_signature: None,
202        };
203
204        Self {
205            fetch_key: KeyPair {
206                sk: fetch_sk,
207                pk: fetch_pk,
208            },
209            message_keys: MessageKeyBundle::new(message_kp, metadata_kp),
210            passphrase,
211            session,
212        }
213    }
214
215    /// Returns the public key material for this source.
216    pub fn public(&self) -> SourcePublicView {
217        SourcePublicView {
218            fetch_pk: self.fetch_key.pk,
219            message_pks: self.message_keys.public(),
220        }
221    }
222}
223
224impl SourcePublicView {
225    /// Reconstruct a source's public view from the reply keys recovered when
226    /// decrypting their submission.
227    pub fn from_reply_keys(
228        fetch_pk: DHPublicKey,
229        apke: MessagePublicKey,
230        metadata_pk: MetadataPublicKey,
231    ) -> Self {
232        SourcePublicView {
233            fetch_pk,
234            message_pks: KeyBundlePublic {
235                apke_pk: apke,
236                metadata_pk,
237            },
238        }
239    }
240}
241
242#[cfg(test)]
243mod tests {
244    use super::*;
245    use proptest::prelude::*;
246    use rand_chacha::ChaCha20Rng;
247    use rand_core::{Rng, SeedableRng};
248
249    /// Canonical BIP39 test vector: 16 zero bytes of entropy.
250    const TEST_MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
251
252    #[test]
253    fn test_initialize_with_passphrase() {
254        let source1 = Source::from_passphrase(TEST_MNEMONIC).expect("valid mnemonic");
255        let source2 = Source::from_passphrase(TEST_MNEMONIC).expect("valid mnemonic");
256
257        assert_eq!(
258            source1.passphrase, source2.passphrase,
259            "Expected identical passphrase"
260        );
261
262        // SD-APKE keys (pk^APKE = (pk1, pk2))
263        assert_eq!(
264            source1.message_keys.apke.public_key().as_bytes(),
265            source2.message_keys.apke.public_key().as_bytes(),
266            "SD-APKE public key should be identical"
267        );
268
269        // Metadata keys
270        assert_eq!(
271            source1.message_keys.metadata_kp.public_key().as_bytes(),
272            source2.message_keys.metadata_kp.public_key().as_bytes(),
273            "XWING Encaps Key should be identical"
274        );
275        assert_eq!(
276            source1.message_keys.metadata_kp.private_key().as_bytes(),
277            source2.message_keys.metadata_kp.private_key().as_bytes(),
278            "XWING Decaps Key should be identical"
279        );
280        assert_ne!(
281            source1.message_keys.metadata_kp.private_key().as_bytes(),
282            &[0u8; XWingPrivateKey::LEN]
283        );
284    }
285
286    proptest! {
287        #[test]
288        fn test_new_source_roundtrips_through_passphrase(seed in any::<u64>()) {
289            let source = Source::new(ChaCha20Rng::seed_from_u64(seed));
290
291            let restored = Source::from_passphrase(source.passphrase())
292                .expect("generated mnemonic is valid");
293
294            prop_assert_eq!(source.passphrase(), restored.passphrase());
295            prop_assert_eq!(
296                source.message_keys.apke.public_key().as_bytes(),
297                restored.message_keys.apke.public_key().as_bytes(),
298            );
299        }
300    }
301
302    #[test]
303    fn test_invalid_mnemonic_is_rejected() {
304        let bad_checksum = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon";
305        assert!(Source::from_passphrase(bad_checksum).is_err());
306
307        assert!(Source::from_passphrase("hello world").is_err());
308    }
309}