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::client::plaintext::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;
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        Plaintext {
104            sender_fetch_key: self.fetch_key.pk,
105            sender_reply_pubkey_hybrid: self.message_keys.metadata_kp.public_key().clone(),
106            msg: message,
107        }
108    }
109
110    fn keybundles(&self) -> Vec<&MessageKeyBundle> {
111        alloc::vec![&self.message_keys]
112    }
113}
114
115impl Source {
116    /// Create a new source with a randomly generated 12-word BIP39 mnemonic.
117    #[cfg_attr(hax, hax_lib::opaque)]
118    pub fn new<R: RngCore + CryptoRng>(mut rng: R) -> Self {
119        let mut entropy = [0u8; 16];
120        rng.fill_bytes(&mut entropy);
121        let mnemonic = Mnemonic::from_entropy(&entropy).expect("16 bytes is valid BIP39 entropy");
122        Self::from_master_key(&entropy, mnemonic.to_string())
123    }
124
125    /// Returns the source's passphrase as a 12-word BIP39 mnemonic.
126    ///
127    /// # Security
128    ///
129    /// The passphrase is the root secret from which all source keys are
130    /// derived. It MUST be stored and transmitted only over secure channels.
131    #[cfg_attr(hax, hax_lib::opaque)]
132    pub fn passphrase(&self) -> &str {
133        &self.passphrase
134    }
135
136    /// Reconstruct source keys from a 12-word BIP39 mnemonic (step 4).
137    ///
138    /// # Errors
139    ///
140    /// Returns an error if `passphrase` is not a valid 12-word BIP39 mnemonic,
141    /// i.e. it contains an unknown word, has the wrong length, or fails the
142    /// checksum.
143    #[cfg_attr(hax, hax_lib::opaque)]
144    pub fn from_passphrase(passphrase: &str) -> Result<Self, Error> {
145        let mnemonic = Mnemonic::parse_in(Language::English, passphrase)
146            .map_err(|e| anyhow::anyhow!("invalid BIP39 mnemonic: {e}"))?;
147
148        let (entropy, len) = mnemonic.to_entropy_array();
149        if len != 16 {
150            return Err(anyhow::anyhow!(
151                "source passphrase must be a 12-word BIP39 mnemonic (128-bit entropy)"
152            ));
153        }
154        let mut mk = [0u8; 16];
155        mk.copy_from_slice(&entropy[..16]);
156
157        Ok(Self::from_master_key(&mk, mnemonic.to_string()))
158    }
159
160    /// Derive a source's long-term keys from the master key `mk` (the 16-byte
161    /// BIP39 entropy), then assemble the [`Source`] tagged with the originating
162    /// `passphrase` mnemonic.
163    ///
164    /// Each private key is derived from `mk` with a domain-separated KDF.
165    #[cfg_attr(hax, hax_lib::opaque)]
166    fn from_master_key(mk: &[u8; 16], passphrase: String) -> Self {
167        // we need a 64 byte string for the ristretto255 scalar (see RFC 9496 section 4.4).
168        let mut fetch_seed = [0u8; DHPrivateKey::SEED_LEN];
169        hkdf::sha256(&mut fetch_seed, SOURCE_KDF_SALT, mk, b"sourcefetchkey")
170            .expect("HKDF fetch key derivation failed");
171
172        // sk_S^APKE is a hybrid key requiring two sub-derivations:
173        // the DH-AKEM and ML-KEM components are each derived with their own
174        // label under the "sourceAPKEkey" namespace.
175        let mut dh_seed = [0u8; DhAkemPrivateKey::SEED_LEN];
176        hkdf::sha256(&mut dh_seed, SOURCE_KDF_SALT, mk, b"sourceAPKEkey-dh")
177            .expect("HKDF APKE DH key derivation failed");
178
179        let mut mlkem_seed = [0u8; MLKEM768PrivateKey::SEED_LEN];
180        hkdf::sha256(&mut mlkem_seed, SOURCE_KDF_SALT, mk, b"sourceAPKEkey-mlkem")
181            .expect("HKDF APKE ML-KEM key derivation failed");
182
183        let mut pke_seed = [0u8; XWingPrivateKey::SEED_LEN];
184        hkdf::sha256(&mut pke_seed, SOURCE_KDF_SALT, mk, b"sourcePKEkey")
185            .expect("HKDF PKE key derivation failed");
186
187        // Create key pairs
188        let (fetch_sk, fetch_pk): (DHPrivateKey, DHPublicKey) = deterministic_dh_keygen(fetch_seed);
189
190        let message_kp =
191            kgen_deterministic_message(dh_seed, mlkem_seed).expect("Need SD-APKE keygen");
192
193        let metadata_kp = kgen_deterministic_metadata(pke_seed).expect("Need X-Wing keygen");
194
195        let session = SessionStorage {
196            fpf_key: None,
197            nr_key: None,
198            fpf_signature: None,
199        };
200
201        Self {
202            fetch_key: KeyPair {
203                sk: fetch_sk,
204                pk: fetch_pk,
205            },
206            message_keys: MessageKeyBundle::new(message_kp, metadata_kp),
207            passphrase,
208            session,
209        }
210    }
211
212    /// Returns the public key material for this source.
213    pub fn public(&self) -> SourcePublicView {
214        SourcePublicView {
215            fetch_pk: self.fetch_key.pk,
216            message_pks: self.message_keys.public(),
217        }
218    }
219}
220
221impl SourcePublicView {
222    /// Reconstruct a source's public view from the reply keys recovered when
223    /// decrypting their submission.
224    pub fn from_reply_keys(
225        fetch_pk: DHPublicKey,
226        apke: MessagePublicKey,
227        metadata_pk: MetadataPublicKey,
228    ) -> Self {
229        SourcePublicView {
230            fetch_pk,
231            message_pks: KeyBundlePublic {
232                apke_pk: apke,
233                metadata_pk,
234            },
235        }
236    }
237}
238
239#[cfg(test)]
240mod tests {
241    use super::*;
242    use proptest::prelude::*;
243    use rand_chacha::ChaCha20Rng;
244    use rand_core::{Rng, SeedableRng};
245
246    /// Canonical BIP39 test vector: 16 zero bytes of entropy.
247    const TEST_MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
248
249    #[test]
250    fn test_initialize_with_passphrase() {
251        let source1 = Source::from_passphrase(TEST_MNEMONIC).expect("valid mnemonic");
252        let source2 = Source::from_passphrase(TEST_MNEMONIC).expect("valid mnemonic");
253
254        assert_eq!(
255            source1.passphrase, source2.passphrase,
256            "Expected identical passphrase"
257        );
258
259        // SD-APKE keys (pk^APKE = (pk1, pk2))
260        assert_eq!(
261            source1.message_keys.apke.public_key().as_bytes(),
262            source2.message_keys.apke.public_key().as_bytes(),
263            "SD-APKE public key should be identical"
264        );
265
266        // Metadata keys
267        assert_eq!(
268            source1.message_keys.metadata_kp.public_key().as_bytes(),
269            source2.message_keys.metadata_kp.public_key().as_bytes(),
270            "XWING Encaps Key should be identical"
271        );
272        assert_eq!(
273            source1.message_keys.metadata_kp.private_key().as_bytes(),
274            source2.message_keys.metadata_kp.private_key().as_bytes(),
275            "XWING Decaps Key should be identical"
276        );
277        assert_ne!(
278            source1.message_keys.metadata_kp.private_key().as_bytes(),
279            &[0u8; XWingPrivateKey::LEN]
280        );
281    }
282
283    proptest! {
284        #[test]
285        fn test_new_source_roundtrips_through_passphrase(seed in any::<u64>()) {
286            let source = Source::new(ChaCha20Rng::seed_from_u64(seed));
287
288            let restored = Source::from_passphrase(source.passphrase())
289                .expect("generated mnemonic is valid");
290
291            prop_assert_eq!(source.passphrase(), restored.passphrase());
292            prop_assert_eq!(
293                source.message_keys.apke.public_key().as_bytes(),
294                restored.message_keys.apke.public_key().as_bytes(),
295            );
296        }
297    }
298
299    #[test]
300    fn test_invalid_mnemonic_is_rejected() {
301        let bad_checksum = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon";
302        assert!(Source::from_passphrase(bad_checksum).is_err());
303
304        assert!(Source::from_passphrase("hello world").is_err());
305    }
306}