1
//! Key rotation tasks of the relay.
2

            
3
mod keys;
4
mod views;
5

            
6
use anyhow::{Context, anyhow};
7
use base64ct::{Base64Unpadded, Encoding};
8
use futures::{FutureExt as _, StreamExt as _, channel::mpsc};
9
use std::{
10
    sync::Arc,
11
    time::{Duration, SystemTime},
12
};
13
use tracing::trace;
14

            
15
use tor_async_utils::{mpsc_channel_no_memquota, oneshot};
16
use tor_chanmgr::ChanMgr;
17
use tor_error::warn_report;
18
use tor_keymgr::KeyMgr;
19
use tor_llcrypto::pk::ed25519::Ed25519Identity;
20
use tor_netdir::{DirEvent, NetDirProvider};
21
use tor_netdoc::doc::routerdesc::{NtorOnionKeyCrossCert, NtorOnionKeyCrossCertConstructor};
22
use tor_netdoc::types::{Ed25519NtorCrossCert, NumericBoolean};
23
use tor_proto::RelayChannelAuthMaterial;
24
use tor_proto::relay::CreateRequestHandler;
25
use tor_relay_crypto::{
26
    RelaySigningKeyCert,
27
    pk::{
28
        RelayIdentityKeypair, RelayIdentityRsaKeypair, RelayNtorKeys, RelayNtorPublicKey,
29
        RelaySigningKeypair,
30
    },
31
};
32
use tor_rtcompat::{Runtime, SleepProviderExt};
33

            
34
use crate::{
35
    keys::{RelayIdentityKeypairSpecifier, RelayIdentityRsaKeypairSpecifier},
36
    tasks::{
37
        crypto::views::FullKeyView,
38
        descriptor::{DescriptorCommand, DescriptorCommandSender},
39
    },
40
};
41

            
42
/// Buffer time before key expiry to trigger rotation. This ensures we rotate slightly before the
43
/// key actually expires rather than right at or after expiry.
44
///
45
/// C-tor uses 3 hours for the link/auth key and 1 day for the signing key. Let's use 3 hours here,
46
/// it should be plenty to make it happen even if hiccups happen.
47
const KEY_ROTATION_EXPIRE_BUFFER: Duration = Duration::from_secs(3 * 60 * 60);
48

            
49
/// Lifetime of the ntor onion key cross-certificate (`ntor-onion-key-crosscert`).
50
///
51
/// Taken from C-tor.
52
// TODO(relay): Tie this to the ntor key rotation schedule so the certificate
53
// expires at the same time as the key.
54
const NTOR_CROSSCERT_LIFETIME: Duration = Duration::from_secs(30 * 24 * 60 * 60);
55

            
56
/// A command sent handled by the [`Reactor`] over a command channel.
57
#[derive(Debug)]
58
#[non_exhaustive]
59
pub(crate) enum CryptoCommand {
60
    /// Request a consistent snapshot of the material needed to encode and sign a router descriptor.
61
    GetRouterDescKeyMaterial {
62
        /// Reply channel for the key material or error.
63
        tx: oneshot::Sender<anyhow::Result<RouterDescKeyMaterial>>,
64
    },
65
}
66

            
67
/// Key material needed to build, encode, and sign a
68
/// [`tor_netdoc::doc::routerdesc::RouterDesc`].
69
///
70
/// Collected in one crypto command so key rotation cannot race with the lookups.
71
///
72
/// The ntor cross-certificate is signed in the crypto task so no Ntor private keys are
73
/// sent in this struct.
74
//
75
// TODO(relay): Wrap the private keypairs in `Arc` so they are never copied.
76
pub(crate) struct RouterDescKeyMaterial {
77
    /// Public Ed25519 identity.
78
    pub(crate) ed_identity: Ed25519Identity,
79
    /// Signing key cert.
80
    pub(crate) ed_signing_cert: RelaySigningKeyCert,
81
    /// Ntor cross-certificate and the sign bit.
82
    pub(crate) ntor_crosscert: NtorOnionKeyCrossCert,
83
    /// Latest ntor public onion key.
84
    pub(crate) ntor_key: RelayNtorPublicKey,
85
    /// Relay Ed25519 signing keypair.
86
    pub(crate) relay_sign_kp: RelaySigningKeypair,
87
    /// RSA identity keypair.
88
    ///
89
    /// The identity private key is required to sign the router descriptor.
90
    /// Offline RSA identity keys are not supported.
91
    pub(crate) rsa_identity_kp: RelayIdentityRsaKeypair,
92
}
93

            
94
/// The sending side of the [`DescriptorCommand`] channel.
95
pub(crate) type CryptoCommandSender = mpsc::Sender<CryptoCommand>;
96
/// The receiving side of the [`DescriptorCommand`] channel.
97
pub(crate) type CryptoCommandReceiver = mpsc::Receiver<CryptoCommand>;
98

            
99
/// Returns a new [`CryptoCommand`] channel.
100
///
101
/// This is a bounded to limit key request spamming (in case of a bug).
102
pub(crate) fn new_command_channel() -> (CryptoCommandSender, CryptoCommandReceiver) {
103
    mpsc_channel_no_memquota(128)
104
}
105

            
106
/// Key rotation parameters derived from the consensus.
107
#[derive(Copy, Clone, Debug)]
108
struct KeyRotationParams {
109
    /// How long a newly generated ntor key is valid.
110
    ntor_lifetime: Duration,
111
    /// How long after expiry the ntor key is still accepted for incoming circuits.
112
    ntor_grace_period: Duration,
113
}
114

            
115
impl From<&tor_netdir::params::NetParameters> for KeyRotationParams {
116
30
    fn from(params: &tor_netdir::params::NetParameters) -> Self {
117
30
        let rotation_days = params.onion_key_rotation_days.get() as u64;
118
        // Grace period is clamped to [1, rotation_days] per the spec.
119
30
        let grace_days = (params.onion_key_grace_period_days.get() as u64).min(rotation_days);
120
30
        Self {
121
30
            ntor_lifetime: Duration::from_secs(rotation_days * 24 * 60 * 60),
122
30
            ntor_grace_period: Duration::from_secs(grace_days * 24 * 60 * 60),
123
30
        }
124
30
    }
125
}
126

            
127
/// Key material generated/loaded at init.
128
///
129
/// This is specific to be at the relay startup and only returned by `try_generate_keys()` that is
130
/// only called before the relay starts.
131
pub(crate) struct InitKeyMaterial {
132
    /// Channel authentication key material.
133
    pub(crate) chan_auth_keys: RelayChannelAuthMaterial,
134
    /// Ntor keys.
135
    pub(crate) ntor_keys: RelayNtorKeys,
136
}
137

            
138
/// Attempt to initialize the key material needed for a relay to function. This function will
139
/// generate any missing keys or load them from the given [`KeyMgr`]. The keys are:
140
///
141
/// * Identity Ed25519 keypair.
142
/// * Identity RSA.
143
/// * Relay signing keypair.
144
/// * Relay link signing keypair.
145
/// * Relay ntor keypair.
146
///
147
/// This function is only called when our relay initializes in order to attempt to generate any
148
/// missing keys or/and rotate expired keys.
149
///
150
/// Returned the initialization key material.
151
2
pub(crate) fn init_keys<R: Runtime>(
152
2
    runtime: &R,
153
2
    keymgr: &KeyMgr,
154
2
) -> anyhow::Result<InitKeyMaterial> {
155
2
    let now = runtime.wallclock();
156

            
157
    // Attempt to generate our identity keys (ed and RSA). Those keys DO NOT rotate. It won't be
158
    // replaced if they already exists.
159
2
    keys::generate_key::<RelayIdentityKeypair>(keymgr, &RelayIdentityKeypairSpecifier::new())?;
160
2
    keys::generate_key::<RelayIdentityRsaKeypair>(
161
2
        keymgr,
162
2
        &RelayIdentityRsaKeypairSpecifier::new(),
163
2
    )?;
164

            
165
    // Attempt to rotate the keys. Any missing keys (and cert) will be generated. At bootstrap
166
    // there is no consensus yet, so we have to use the default parameters.
167
2
    let _ = keys::try_rotate_keys(
168
2
        now,
169
2
        keymgr,
170
2
        KeyRotationParams::from(&tor_netdir::params::NetParameters::default()),
171
2
    )?;
172

            
173
    // Throwaway full key view only for this purpose.
174
2
    let key_view = FullKeyView::new(keymgr)?;
175

            
176
    Ok(InitKeyMaterial {
177
2
        chan_auth_keys: keys::build_proto_relay_auth_material(now, &key_view)?,
178
2
        ntor_keys: key_view.ks_ntor_keys()?,
179
    })
180
2
}
181

            
182
/// Reactor object handling the rotation of relay crypto keys.
183
pub(crate) struct Reactor<R: Runtime> {
184
    /// Underlying runtime for a time provider.
185
    runtime: R,
186
    /// Reference to the arti-relay channel manager [`ChanMgr`]
187
    chanmgr: Arc<ChanMgr<R>>,
188
    /// Reference to the create request handler so we can update it.
189
    create_request_handler: Arc<CreateRequestHandler>,
190
    /// Full key view.
191
    view: FullKeyView<KeyMgr>,
192
    /// Net directory provider used to watch for consensus changes.
193
    netdir: Arc<dyn NetDirProvider>,
194
    /// Descriptor task TX channel.
195
    desc_tx: DescriptorCommandSender,
196
    /// Our crypto command RX channel.
197
    our_rx: CryptoCommandReceiver,
198
}
199

            
200
impl<R: Runtime> Reactor<R> {
201
    /// Constructor.
202
    pub(crate) fn new(
203
        runtime: R,
204
        chanmgr: Arc<ChanMgr<R>>,
205
        create_request_handler: Arc<CreateRequestHandler>,
206
        keymgr: KeyMgr,
207
        netdir: Arc<dyn NetDirProvider>,
208
        desc_tx: DescriptorCommandSender,
209
        our_rx: CryptoCommandReceiver,
210
    ) -> anyhow::Result<Self> {
211
        Ok(Self {
212
            runtime,
213
            chanmgr,
214
            create_request_handler,
215
            view: FullKeyView::new(keymgr)?,
216
            netdir,
217
            desc_tx,
218
            our_rx,
219
        })
220
    }
221

            
222
    /// Log the relay's identities and public ntor key.
223
    fn log_public_keys(&self) -> anyhow::Result<()> {
224
        let rsa_id = self.view.ks_relayid_rsa()?.to_rsa_identity();
225
        let ed_id = self.view.ks_relayid_ed()?.to_ed25519_id();
226

            
227
        let ntor_keys = self.view.ks_ntor_keys()?;
228
        // Base64-encode the public ntor key.
229
        let ntor = Base64Unpadded::encode_string(ntor_keys.latest().public().inner().as_bytes());
230

            
231
        // Log the relay's identities.
232
        // TODO: We should also log this after a key rotation:
233
        // https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/3773#note_3367789
234
        // TODO: This is useful at info level while we're developing,
235
        // but the level should probably be lowered in the future.
236
        tracing::info!("RSA identity: {rsa_id}");
237
        tracing::info!("Ed25519 identity: {ed_id}");
238
        tracing::info!("Ntor public key: {ntor}");
239

            
240
        Ok(())
241
    }
242

            
243
    /// Handle a [`CryptoCommand`] received by the reactor.
244
    fn handle_command(&mut self, cmd: CryptoCommand) -> anyhow::Result<()> {
245
        match cmd {
246
            CryptoCommand::GetRouterDescKeyMaterial { tx } => {
247
                let material = self.router_desc_key_material();
248
                tx.send(material)
249
                    .map_err(|_| anyhow!("GetRouterDescKeyMaterial reply tx failed"))?;
250
            }
251
        }
252

            
253
        Ok(())
254
    }
255

            
256
    /// Collect the latest key material needed for router descriptor encoding and
257
    /// signature.
258
    ///
259
    /// This is called upong receiving a [`CryptoCommand::GetRouterDescKeyMaterial`] from
260
    /// the descriptor task.
261
    fn router_desc_key_material(&self) -> anyhow::Result<RouterDescKeyMaterial> {
262
        let ed_identity = self.view.ks_relayid_ed()?.to_ed25519_id();
263
        let ntor_keys = self.view.ks_ntor_keys()?;
264
        let ntor_keypair = ntor_keys.latest();
265
        let (ntor_ed_kp, ntor_signbit) =
266
            tor_llcrypto::pk::keymanip::convert_curve25519_to_ed25519_private(
267
                ntor_keypair.secret(),
268
            )
269
            .ok_or_else(|| anyhow!("Failed to convert ed25519 key from ntor key"))?;
270
        let ntor_crosscert = Ed25519NtorCrossCert::new_signed(
271
            &ntor_ed_kp,
272
            ed_identity,
273
            self.runtime.wallclock() + NTOR_CROSSCERT_LIFETIME,
274
        )
275
        .context("Failed to build ntor crosscert")?;
276

            
277
        Ok(RouterDescKeyMaterial {
278
            ed_identity,
279
            relay_sign_kp: self.view.ks_relaysign_ed()?,
280
            ed_signing_cert: self.view.cert_relaysign_ed()?,
281
            rsa_identity_kp: self.view.ks_relayid_rsa()?,
282
            ntor_key: ntor_keypair.public(),
283
            ntor_crosscert: NtorOnionKeyCrossCertConstructor {
284
                bit: NumericBoolean(ntor_signbit != 0),
285
                cert: ntor_crosscert,
286
            }
287
            .construct(),
288
        })
289
    }
290

            
291
    /// Launch the reactor, and run until an error is encountered.
292
    pub(crate) async fn run(mut self) -> anyhow::Result<void::Void> {
293
        trace!("Starting crypto reactor task");
294

            
295
        // Subscribe before the first run_once() so we don't miss any events that arrive
296
        // between startup and entering the select loop.
297
        let mut consensus_events = self
298
            .netdir
299
            .events()
300
            .filter(|ev| std::future::ready(matches!(ev, DirEvent::NewConsensus)));
301

            
302
        // TODO: This is mostly useful for debugging.
303
        // We might want to remove this in the future, or move this somewhere else.
304
        self.log_public_keys()
305
            .context("Failed to log public keys")?;
306

            
307
        loop {
308
            let next_wake = self.run_once()?;
309
            futures::select! {
310
                // Sleep until next wake up.
311
                _ = self.runtime.sleep_until_wallclock(next_wake).fuse() => {}
312
                // New consensus arrived, might be new parameters. Run the loop, it will pickup the
313
                // latest.
314
                ev = consensus_events.next().fuse() => {
315
                    ev.context("NetDir event stream ended unexpectedly")?;
316
                }
317
                // Crypto command channel.
318
                cmd = self.our_rx.next().fuse() => {
319
                    let cmd = cmd.context("Crypto command channel closed")?;
320
                    if let Err(e) = self.handle_command(cmd) {
321
                        warn_report!(e, "Crypto task command failure");
322
                    }
323
                }
324
            }
325
        }
326
    }
327

            
328
    /// Helper: run once to handle a single rotation tick.
329
    fn run_once(&mut self) -> anyhow::Result<SystemTime> {
330
        let now = self.runtime.wallclock();
331
        // Attempt a rotation of all keys.
332
        let (changed, next_expiry) = self.try_rotate_keys(now)?;
333

            
334
        if changed.link_ed || changed.relaysign_ed {
335
            let auth_material = keys::build_proto_relay_auth_material(now, &self.view)?;
336
            self.chanmgr
337
                .set_relay_auth_material(Arc::new(auth_material))
338
                .context("Failed to set relay auth material on ChanMgr")?;
339
        }
340

            
341
        if changed.ntor_latest || changed.ntor_previous {
342
            let ntor_keys = self.view.ks_ntor_keys()?;
343
            self.create_request_handler.update_ntor_keys(ntor_keys);
344
        }
345

            
346
        // Notify the descriptor task that its keys have changed.
347
        if changed.relay_desc_keys_changed() {
348
            self.desc_tx
349
                .try_send(DescriptorCommand::Publish)
350
                .context("Desc task channel try_send failed")?;
351
            // Note, we can never wait for the publish to finish here because the
352
            // descriptor task upon receiving the command will send us commands to get
353
            // the keys it needs. Waiting here would lead to a deadlock.
354
        }
355

            
356
        // Sleep until the earliest key expiry minus buffer so we rotate before it expires.
357
        // If the subtraction would underflow, wake up immediately to rotate the expired key.
358
        Ok(next_expiry
359
            .checked_sub(KEY_ROTATION_EXPIRE_BUFFER)
360
            .unwrap_or(now))
361
    }
362

            
363
    /// Attempt to rotate all keys except identity keys.
364
    ///
365
    /// Holds the write lock for the entire rotate + reconcile to prevent the race where another
366
    /// task reads a key between the keymgr update and the cache update.
367
    ///
368
    /// Returns which key types changed and the earliest expiry time across all keys.
369
    fn try_rotate_keys(
370
        &mut self,
371
        now: SystemTime,
372
    ) -> anyhow::Result<(views::ValidUntilChanged, SystemTime)> {
373
        let rotation_params = KeyRotationParams::from(self.netdir.params().as_ref().as_ref());
374
        let next_expiry = keys::try_rotate_keys(now, self.view.keymgr(), rotation_params)?;
375
        let changed = self.view.recompute_valid_until()?;
376
        Ok((changed, next_expiry))
377
    }
378
}
379

            
380
#[cfg(test)]
381
mod test {
382
    // @@ begin test lint list maintained by maint/add_warning @@
383
    #![allow(clippy::bool_assert_comparison)]
384
    #![allow(clippy::clone_on_copy)]
385
    #![allow(clippy::dbg_macro)]
386
    #![allow(clippy::mixed_attributes_style)]
387
    #![allow(clippy::print_stderr)]
388
    #![allow(clippy::print_stdout)]
389
    #![allow(clippy::single_char_pattern)]
390
    #![allow(clippy::unwrap_used)]
391
    #![allow(clippy::unchecked_time_subtraction)]
392
    #![allow(clippy::useless_vec)]
393
    #![allow(clippy::needless_pass_by_value)]
394
    #![allow(clippy::string_slice)] // See arti#2571
395
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
396

            
397
    use super::*;
398

            
399
    use tor_keymgr::{ArtiEphemeralKeystore, KeyMgrBuilder};
400
    use tor_rtmock::MockRuntime;
401

            
402
    /// Initialize test basics that is runtime and a KeyMgr.
403
    pub(super) fn new_keymgr() -> KeyMgr {
404
        let store = Box::new(ArtiEphemeralKeystore::new("test".to_string()));
405
        KeyMgrBuilder::default()
406
            .primary_store(store)
407
            .build()
408
            .unwrap()
409
    }
410

            
411
    /// Test the actual bootstrap function, `try_generate_keys()` which is in charge of
412
    /// initializing the auth material.
413
    #[test]
414
    fn test_bootstrap() {
415
        MockRuntime::test_with_various(|runtime| async move {
416
            let _auth_material = match init_keys(&runtime, &new_keymgr()) {
417
                Ok(a) => a,
418
                Err(e) => {
419
                    panic!("Unable to bootstrap keys and generate RelayChannelAuthMaterial: {e}");
420
                }
421
            };
422
        });
423
    }
424
}