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::provider::hkdf;
15use crate::primitives::ristretto255::DH_SEED_LEN;
16use crate::primitives::xwing::XWING_PUBLIC_KEY_LEN;
17use crate::traits::{UserPublic, UserSecret};
18
19// do not re-export!
20use crate::sealed;
21
22#[cfg(not(hax))]
23impl sealed::Sealed for Source {}
24
25/// Fixed, public, application-specific salt for source key derivation.
26const SOURCE_KDF_SALT: &[u8] = b"securedrop-source-v1";
27
28/// A source and their long-term key material (step 4).
29///
30/// A source's keys are fully determined by their passphrase, a 12-word BIP39
31/// mnemonic. The mnemonic's 16-byte entropy is used directly as the master key
32/// `mk`, from which the fetch key, APKE key, and PKE key are derived with a
33/// domain-separated KDF. Returning sources reconstruct the same keys by calling
34/// [`Source::from_passphrase`] with the same mnemonic.
35pub struct Source {
36    fetch_key: DhFetchKeyPair,
37    message_keys: MessageKeyBundle,
38    passphrase: String,
39    session: SessionStorage,
40}
41
42// hax struggles with the debug format function signature, but it is
43// debug only, so we can exclude it from extraction
44#[cfg_attr(hax, hax_lib::exclude)]
45impl core::fmt::Debug for Source {
46    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
47        // Using non-exhaustive to avoid leaking source keys.
48        f.debug_struct("Source").finish_non_exhaustive()
49    }
50}
51
52/// The public key material of a source, used by journalists to send replies.
53#[derive(Debug, Clone)]
54pub struct SourcePublicView {
55    fetch_pk: DHPublicKey,
56    apke_pk: MessagePublicKey,
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.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; XWING_PUBLIC_KEY_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; DH_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; 32];
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; 64];
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; 32];
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            apke_pk: self.message_keys.apke.public_key().clone(),
220            message_pks: self.message_keys.public(),
221        }
222    }
223}
224
225impl SourcePublicView {
226    /// Reconstruct a source's public view from the reply keys recovered when
227    /// decrypting their submission.
228    pub fn from_reply_keys(
229        fetch_pk: DHPublicKey,
230        apke: MessagePublicKey,
231        metadata_pk: MetadataPublicKey,
232    ) -> Self {
233        SourcePublicView {
234            fetch_pk,
235            apke_pk: apke.clone(),
236            message_pks: KeyBundlePublic {
237                apke_pk: apke,
238                metadata_pk,
239            },
240        }
241    }
242}
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247    use crate::primitives::xwing::XWING_PRIVATE_KEY_LEN;
248    use proptest::prelude::*;
249    use rand_chacha::ChaCha20Rng;
250    use rand_core::{Rng, SeedableRng};
251
252    /// Canonical BIP39 test vector: 16 zero bytes of entropy.
253    const TEST_MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
254
255    #[test]
256    fn test_initialize_with_passphrase() {
257        let source1 = Source::from_passphrase(TEST_MNEMONIC).expect("valid mnemonic");
258        let source2 = Source::from_passphrase(TEST_MNEMONIC).expect("valid mnemonic");
259
260        assert_eq!(
261            source1.passphrase, source2.passphrase,
262            "Expected identical passphrase"
263        );
264
265        // SD-APKE keys (pk^APKE = (pk1, pk2))
266        assert_eq!(
267            source1.message_keys.apke.public_key().as_bytes(),
268            source2.message_keys.apke.public_key().as_bytes(),
269            "SD-APKE public key should be identical"
270        );
271
272        // Metadata keys
273        assert_eq!(
274            source1.message_keys.metadata_kp.public_key().as_bytes(),
275            source2.message_keys.metadata_kp.public_key().as_bytes(),
276            "XWING Encaps Key should be identical"
277        );
278        assert_eq!(
279            source1.message_keys.metadata_kp.private_key().as_bytes(),
280            source2.message_keys.metadata_kp.private_key().as_bytes(),
281            "XWING Decaps Key should be identical"
282        );
283        assert_ne!(
284            source1.message_keys.metadata_kp.private_key().as_bytes(),
285            &[0u8; XWING_PRIVATE_KEY_LEN]
286        );
287    }
288
289    proptest! {
290        #[test]
291        fn test_new_source_roundtrips_through_passphrase(seed in any::<u64>()) {
292            let source = Source::new(ChaCha20Rng::seed_from_u64(seed));
293
294            let restored = Source::from_passphrase(source.passphrase())
295                .expect("generated mnemonic is valid");
296
297            prop_assert_eq!(source.passphrase(), restored.passphrase());
298            prop_assert_eq!(
299                source.message_keys.apke.public_key().as_bytes(),
300                restored.message_keys.apke.public_key().as_bytes(),
301            );
302        }
303    }
304
305    #[test]
306    fn test_invalid_mnemonic_is_rejected() {
307        let bad_checksum = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon";
308        assert!(Source::from_passphrase(bad_checksum).is_err());
309
310        assert!(Source::from_passphrase("hello world").is_err());
311    }
312}