1
//! Implements the HS ntor key exchange, as used in v3 onion services.
2
//!
3
//! The Ntor protocol of this section is specified in section
4
//! [NTOR-WITH-EXTRA-DATA] of rend-spec-v3.txt.
5
//!
6
//! The main difference between this HS Ntor handshake and the regular Ntor
7
//! handshake in ./ntor.rs is that this one allows each party to encrypt data
8
//! (without forward secrecy) after it sends the first message. This
9
//! opportunistic encryption property is used by clients in the onion service
10
//! protocol to encrypt introduction data in the INTRODUCE1 cell, and by
11
//! services to encrypt data in the RENDEZVOUS1 cell.
12
//!
13
//! # Status
14
//!
15
//! This module is available only when the `hs-common` feature is enabled.  The
16
//! specific handshakes are enabled by `hs-client` and `hs-service`.
17

            
18
// We want to use the exact variable names from the rend-spec-v3.txt proposal.
19
// This means that we allow variables to be named x (privkey) and X (pubkey).
20
// FIXME: this particular allow is rather hazardous since it can stop warnings
21
//        about match statements containing bindings rather than variant names.
22
#![allow(non_snake_case)]
23

            
24
use crate::crypto::handshake::KeyGenerator;
25
use crate::crypto::ll::kdf::{Kdf, ShakeKdf};
26
use crate::util::ct;
27
use crate::{Error, Result};
28
use std::result::Result as StdResult;
29
use tor_bytes::{Reader, SecretBuf, Writer};
30
use tor_hscrypto::{
31
    Subcredential,
32
    ops::{HS_MAC_LEN, hs_mac},
33
    pk::{HsIntroPtSessionIdKey, HsSvcNtorKey},
34
};
35
use tor_llcrypto::pk::{curve25519, ed25519};
36
use tor_llcrypto::util::ct::CtByteArray;
37

            
38
use cipher::{KeyIvInit, StreamCipher};
39

            
40
use subtle::ConstantTimeEq as _;
41
use tor_error::into_internal;
42
use tor_llcrypto::cipher::aes::Aes256Ctr;
43
use zeroize::{Zeroize as _, Zeroizing};
44

            
45
#[cfg(any(test, feature = "hs-service"))]
46
use tor_hscrypto::pk::HsSvcNtorKeypair;
47

            
48
/// The ENC_KEY from the HS Ntor protocol
49
//
50
// TODO (nickm): Any move operations applied to this key could subvert the zeroizing.
51
type EncKey = Zeroizing<[u8; 32]>;
52
/// The MAC_KEY from the HS Ntor protocol
53
type MacKey = [u8; 32];
54
/// A generic 256-bit MAC tag
55
type MacTag = CtByteArray<HS_MAC_LEN>;
56
/// The AUTH_INPUT_MAC from the HS Ntor protocol
57
type AuthInputMac = MacTag;
58

            
59
/// The key generator used by the HS ntor handshake.  Implements the simple key
60
/// expansion protocol specified in section "Key expansion" of rend-spec-v3.txt .
61
pub struct HsNtorHkdfKeyGenerator {
62
    /// Secret data derived from the handshake, used as input to HKDF
63
    seed: SecretBuf,
64
}
65

            
66
impl HsNtorHkdfKeyGenerator {
67
    /// Create a new key generator to expand a given seed
68
5
    pub fn new(seed: SecretBuf) -> Self {
69
5
        HsNtorHkdfKeyGenerator { seed }
70
5
    }
71
}
72

            
73
impl KeyGenerator for HsNtorHkdfKeyGenerator {
74
    /// Expand the seed into a keystream of 'keylen' size
75
5
    fn expand(self, keylen: usize) -> Result<SecretBuf> {
76
5
        ShakeKdf::new().derive(&self.seed[..], keylen)
77
5
    }
78
}
79

            
80
/*********************** Client Side Code ************************************/
81

            
82
/// Information about an onion service that is needed for a client to perform an
83
/// hs_ntor handshake with it.
84
#[derive(Clone)]
85
#[cfg(any(test, feature = "hs-client"))]
86
pub struct HsNtorServiceInfo {
87
    /// Introduction point encryption key (aka `B`, aka `KP_hss_ntor`)
88
    /// (found in the HS descriptor)
89
    B: HsSvcNtorKey,
90

            
91
    /// Introduction point authentication key (aka `AUTH_KEY`, aka `KP_hs_ipt_sid`)
92
    /// (found in the HS descriptor)
93
    ///
94
    /// TODO: This is needed to begin _and end_ the handshake, which makes
95
    /// things a little trickier if someday we want to have several of these
96
    /// handshakes in operation at once, so that we can make
97
    /// multiple introduction attempts simultaneously
98
    /// using the same renedezvous point.
99
    /// That's not something that C Tor supports, though, so neither do we (yet).
100
    auth_key: HsIntroPtSessionIdKey,
101

            
102
    /// Service subcredential
103
    subcredential: Subcredential,
104
}
105

            
106
#[cfg(any(test, feature = "hs-client"))]
107
impl HsNtorServiceInfo {
108
    /// Create a new `HsNtorServiceInfo`
109
4251
    pub fn new(
110
4251
        B: HsSvcNtorKey,
111
4251
        auth_key: HsIntroPtSessionIdKey,
112
4251
        subcredential: Subcredential,
113
4251
    ) -> Self {
114
4251
        HsNtorServiceInfo {
115
4251
            B,
116
4251
            auth_key,
117
4251
            subcredential,
118
4251
        }
119
4251
    }
120
}
121

            
122
/// Client state for an ntor handshake.
123
#[cfg(any(test, feature = "hs-client"))]
124
pub struct HsNtorClientState {
125
    /// Information about the service we are connecting to.
126
    service_info: HsNtorServiceInfo,
127

            
128
    /// The temporary curve25519 secret that we generated for this handshake.
129
    x: curve25519::StaticSecret,
130
    /// The corresponding private key
131
    X: curve25519::PublicKey,
132

            
133
    /// A shared secret constructed from our secret key `x` and the service's
134
    /// public ntor key `B`.  (The service has a separate public ntor key
135
    /// associated with each intro point.)
136
    Bx: curve25519::SharedSecret,
137

            
138
    /// Target length for the generated Introduce1 messages.
139
    intro1_target_len: usize,
140
}
141

            
142
/// Default target length for our generated Introduce1 messages.
143
///
144
/// This value is chosen to be the maximum size of a single-cell message
145
/// after proposal 340 is implemented.  (509 bytes for cell data, minus 16 bytes
146
/// for relay encryption overhead, minus 1 byte for relay command, minus 2 bytes
147
/// for relay message length.)
148
#[cfg(any(test, feature = "hs-client"))]
149
const INTRO1_TARGET_LEN: usize = 490;
150

            
151
#[cfg(any(test, feature = "hs-client"))]
152
impl HsNtorClientState {
153
    /// Construct a new `HsNtorClientState` for connecting to a given onion
154
    /// service described in `service_info`.
155
    ///
156
    /// Once constructed, this `HsNtorClientState` can be used to construct an
157
    /// INTRODUCE1 bodies that can be sent to an introduction point.
158
86
    pub fn new<R>(rng: &mut R, service_info: HsNtorServiceInfo) -> Self
159
86
    where
160
86
        R: rand::Rng + rand::CryptoRng,
161
    {
162
86
        let x = curve25519::StaticSecret::random_from_rng(rng);
163
86
        Self::new_no_keygen(service_info, x)
164
86
    }
165

            
166
    /// Override the default target length for the resulting introduce1 message.
167
    #[cfg(test)]
168
1
    fn set_intro1_target_len(&mut self, len: usize) {
169
1
        self.intro1_target_len = len;
170
1
    }
171

            
172
    /// As `new()`, but do not use an RNG to generate our ephemeral secret key x.
173
4252
    fn new_no_keygen(service_info: HsNtorServiceInfo, x: curve25519::StaticSecret) -> Self {
174
4252
        let X = curve25519::PublicKey::from(&x);
175
4252
        let Bx = x.diffie_hellman(&service_info.B);
176
4252
        Self {
177
4252
            service_info,
178
4252
            x,
179
4252
            X,
180
4252
            Bx,
181
4252
            intro1_target_len: INTRO1_TARGET_LEN,
182
4252
        }
183
4252
    }
184

            
185
    /// Return the data that should be written as the encrypted part of and
186
    /// the data that should be written as the encrypted part of the INTRODUCE1
187
    /// message. The data that is
188
    /// written is:
189
    ///
190
    /// ```text
191
    ///  CLIENT_PK                [PK_PUBKEY_LEN bytes]
192
    ///  ENCRYPTED_DATA           [Padded to length of plaintext]
193
    ///  MAC                      [MAC_LEN bytes]
194
    /// ```
195
4252
    pub fn client_send_intro(&self, intro_header: &[u8], plaintext_body: &[u8]) -> Result<Vec<u8>> {
196
        /// The number of bytes added by this encryption.
197
        const ENC_OVERHEAD: usize = 32 + 32;
198

            
199
4252
        let state = self;
200
4252
        let service = &state.service_info;
201

            
202
        // Compute keys required to finish this part of the handshake
203
4252
        let (enc_key, mac_key) = get_introduce_key_material(
204
4252
            &state.Bx,
205
4252
            &service.auth_key,
206
4252
            &state.X,
207
4252
            &service.B,
208
4252
            &service.subcredential,
209
4252
        )?;
210

            
211
4252
        let padded_body_target_len = self
212
4252
            .intro1_target_len
213
4252
            .saturating_sub(intro_header.len() + ENC_OVERHEAD);
214
4252
        let mut padded_body = plaintext_body.to_vec();
215
4252
        if padded_body.len() < padded_body_target_len {
216
4251
            padded_body.resize(padded_body_target_len, 0);
217
1
        }
218
4252
        debug_assert!(padded_body.len() >= padded_body_target_len);
219

            
220
        let (ciphertext, mac_tag) =
221
4252
            encrypt_and_mac(&padded_body, intro_header, &state.X, &enc_key, mac_key);
222
4252
        padded_body.zeroize();
223

            
224
        // Create the relevant parts of INTRO1
225
4252
        let mut response: Vec<u8> = Vec::new();
226
4252
        response
227
4252
            .write(&state.X)
228
4252
            .and_then(|_| response.write(&ciphertext))
229
4252
            .and_then(|_| response.write(&mac_tag))
230
4252
            .map_err(into_internal!("Can't encode hs-ntor client handshake."))?;
231

            
232
4252
        Ok(response)
233
4252
    }
234

            
235
    /// The introduction has been completed and the service has replied with a
236
    /// RENDEZVOUS1 message, whose body is in `msg`.
237
    ///
238
    /// Handle it by computing and verifying the MAC, and if it's legit return a
239
    /// key generator based on the result of the key exchange.
240
2
    pub fn client_receive_rend(&self, msg: &[u8]) -> Result<HsNtorHkdfKeyGenerator> {
241
2
        let state = self;
242

            
243
        // Extract the public key of the service from the message
244
2
        let mut cur = Reader::from_slice(msg);
245
2
        let Y: curve25519::PublicKey = cur
246
2
            .extract()
247
            .map_err(|e| Error::from_bytes_err(e, "hs_ntor handshake"))?;
248
2
        let mac_tag: MacTag = cur
249
2
            .extract()
250
            .map_err(|e| Error::from_bytes_err(e, "hs_ntor handshake"))?;
251

            
252
        // Get EXP(Y,x) and EXP(B,x)
253
2
        let xy = state.x.diffie_hellman(&Y);
254
2
        let xb = state.x.diffie_hellman(&state.service_info.B);
255

            
256
2
        let (keygen, my_mac_tag) = get_rendezvous_key_material(
257
2
            &xy,
258
2
            &xb,
259
2
            &state.service_info.auth_key,
260
2
            &state.service_info.B,
261
2
            &state.X,
262
2
            &Y,
263
2
        )?;
264

            
265
        // It isn't totally necessary to do this & as constant-time, but why tempt fate?
266
2
        let okay = my_mac_tag.ct_eq(&mac_tag)
267
2
            & ct::bool_to_choice(xy.was_contributory())
268
2
            & ct::bool_to_choice(xb.was_contributory());
269

            
270
        // Validate the MAC!
271
2
        if !bool::from(okay) {
272
            return Err(Error::BadCircHandshakeAuth);
273
2
        }
274

            
275
2
        Ok(keygen)
276
2
    }
277
}
278

            
279
/// Encrypt the 'plaintext' using 'enc_key'. Then compute the intro cell MAC
280
/// using 'mac_key' over the text `(other_text, public_key, plaintext)`
281
/// and return (ciphertext, mac_tag).
282
#[cfg(any(test, feature = "hs-client"))]
283
4252
fn encrypt_and_mac(
284
4252
    plaintext: &[u8],
285
4252
    other_data: &[u8],
286
4252
    public_key: &curve25519::PublicKey,
287
4252
    enc_key: &EncKey,
288
4252
    mac_key: MacKey,
289
4252
) -> (Vec<u8>, MacTag) {
290
4252
    let mut ciphertext = plaintext.to_vec();
291
    // Encrypt the introduction data using 'enc_key'
292
4252
    let zero_iv = Default::default();
293
4252
    let mut cipher = Aes256Ctr::new((&**enc_key).into(), &zero_iv);
294
4252
    cipher.apply_keystream(&mut ciphertext);
295

            
296
    // Now staple the other INTRODUCE1 data right before the ciphertext to
297
    // create the body of the MAC tag
298
4252
    let mut mac_body: Vec<u8> = Vec::new();
299
4252
    mac_body.extend(other_data);
300
4252
    mac_body.extend(public_key.as_bytes());
301
4252
    mac_body.extend(&ciphertext);
302
4252
    let mac_tag = hs_mac(&mac_key, &mac_body);
303

            
304
4252
    (ciphertext, mac_tag)
305
4252
}
306

            
307
/*********************** Server Side Code ************************************/
308

            
309
/// Conduct the HS Ntor handshake as the service.
310
///
311
/// Return a key generator which is the result of the key exchange, the
312
/// RENDEZVOUS1 response to send to the client, and the introduction plaintext that we decrypted.
313
///
314
/// The response to the client is:
315
/// ```text
316
///    SERVER_PK   Y                         [PK_PUBKEY_LEN bytes]
317
///    AUTH        AUTH_INPUT_MAC            [MAC_LEN bytes]
318
/// ```
319
#[cfg(any(test, feature = "hs-service"))]
320
1
pub fn server_receive_intro<R>(
321
1
    rng: &mut R,
322
1
    k_hss_ntor: &HsSvcNtorKeypair,
323
1
    auth_key: &HsIntroPtSessionIdKey,
324
1
    subcredential: &[Subcredential],
325
1
    intro_header: &[u8],
326
1
    msg: &[u8],
327
1
) -> Result<(HsNtorHkdfKeyGenerator, Vec<u8>, Vec<u8>)>
328
1
where
329
1
    R: rand::Rng + rand::CryptoRng,
330
{
331
1
    let y = curve25519::StaticSecret::random_from_rng(rng);
332
1
    server_receive_intro_no_keygen(&y, k_hss_ntor, auth_key, subcredential, intro_header, msg)
333
1
}
334

            
335
/// Helper: Like server_receive_intro, but take an ephemeral key rather than a RNG.
336
#[cfg(any(test, feature = "hs-service"))]
337
2
fn server_receive_intro_no_keygen(
338
2
    // This should be an EphemeralSecret, but using a StaticSecret is necessary
339
2
    // so that we can make one from raw bytes in our test.
340
2
    y: &curve25519::StaticSecret,
341
2
    k_hss_ntor: &HsSvcNtorKeypair,
342
2
    auth_key: &HsIntroPtSessionIdKey,
343
2
    subcredential: &[Subcredential],
344
2
    intro_header: &[u8],
345
2
    msg: &[u8],
346
2
) -> Result<(HsNtorHkdfKeyGenerator, Vec<u8>, Vec<u8>)> {
347
    // Extract all the useful pieces from the message
348
2
    let mut cur = Reader::from_slice(msg);
349
2
    let X: curve25519::PublicKey = cur
350
2
        .extract()
351
        .map_err(|e| Error::from_bytes_err(e, "hs ntor handshake"))?;
352
2
    let ciphertext = &mut cur
353
2
        .take_all_but(HS_MAC_LEN)
354
        .map_err(|e| Error::from_bytes_err(e, "hs ntor handshake"))?
355
        .to_vec();
356
2
    let mac_tag: MacTag = cur
357
2
        .extract()
358
        .map_err(|e| Error::from_bytes_err(e, "hs ntor handshake"))?;
359

            
360
    // Now derive keys needed for handling the INTRO1 cell
361
2
    let bx = k_hss_ntor.secret().as_ref().diffie_hellman(&X);
362

            
363
    // We have to do this for every possible subcredential to find out which
364
    // one, if any, gives a valid encryption key.  We don't break on our first
365
    // success, to avoid a timing sidechannel.
366
    //
367
    // TODO SPEC: Document this behavior and explain why it's necessary and okay.
368
2
    let mut found_dec_key = None;
369

            
370
2
    for subcredential in subcredential {
371
        let (dec_key, mac_key) =
372
2
            get_introduce_key_material(&bx, auth_key, &X, k_hss_ntor.public(), subcredential)?; // This can only fail with a Bug, so it's okay to bail early.
373

            
374
        // Now validate the MAC: Staple the previous parts of the INTRODUCE2
375
        // message, along with the ciphertext, to create the body of the MAC tag.
376
2
        let mut mac_body: Vec<u8> = Vec::new();
377
2
        mac_body.extend(intro_header);
378
2
        mac_body.extend(X.as_bytes());
379
2
        mac_body.extend(&ciphertext[..]);
380
2
        let my_mac_tag = hs_mac(&mac_key, &mac_body);
381

            
382
2
        if my_mac_tag == mac_tag {
383
            // TODO: We could use CtOption here.
384
2
            found_dec_key = Some(dec_key);
385
        }
386
    }
387

            
388
2
    let Some(dec_key) = found_dec_key else {
389
        return Err(Error::BadCircHandshakeAuth);
390
    };
391

            
392
    // Decrypt the ENCRYPTED_DATA from the intro cell
393
2
    let zero_iv = Default::default();
394
2
    let mut cipher = Aes256Ctr::new((&*dec_key).into(), &zero_iv);
395
2
    cipher.apply_keystream(ciphertext);
396
2
    let plaintext = ciphertext; // it's now decrypted
397

            
398
    // Generate ephemeral keys for this handshake
399
2
    let Y = curve25519::PublicKey::from(y);
400

            
401
    // Compute EXP(X,y) and EXP(X,b)
402
2
    let xy = y.diffie_hellman(&X);
403
2
    let xb = k_hss_ntor.secret().as_ref().diffie_hellman(&X);
404

            
405
    // It isn't totally necessary to do this & as constant-time, but why tempt fate?
406
    let okay =
407
2
        ct::bool_to_choice(xy.was_contributory()) & ct::bool_to_choice(xb.was_contributory());
408
2
    if !bool::from(okay) {
409
        return Err(Error::BadCircHandshakeAuth);
410
2
    }
411

            
412
    let (keygen, auth_input_mac) =
413
2
        get_rendezvous_key_material(&xy, &xb, auth_key, k_hss_ntor.public(), &X, &Y)?;
414

            
415
    // Set up RENDEZVOUS1 reply to the client
416
2
    let mut reply: Vec<u8> = Vec::new();
417
2
    reply
418
2
        .write(&Y)
419
2
        .and_then(|_| reply.write(&auth_input_mac))
420
2
        .map_err(into_internal!("Can't encode hs-ntor server handshake."))?;
421

            
422
2
    Ok((keygen, reply, plaintext.clone()))
423
2
}
424

            
425
/*********************** Helper functions ************************************/
426

            
427
/// Helper function: Compute the part of the HS ntor handshake that generates
428
/// key material for creating and handling INTRODUCE1 cells. Function used
429
/// by both client and service. Specifically, calculate the following:
430
///
431
/// ```pseudocode
432
///  intro_secret_hs_input = EXP(B,x) | AUTH_KEY | X | B | PROTOID
433
///  info = m_hsexpand | subcredential
434
///  hs_keys = KDF(intro_secret_hs_input | t_hsenc | info, S_KEY_LEN+MAC_LEN)
435
///  ENC_KEY = hs_keys[0:S_KEY_LEN]
436
///  MAC_KEY = hs_keys[S_KEY_LEN:S_KEY_LEN+MAC_KEY_LEN]
437
/// ```
438
///
439
/// Return (ENC_KEY, MAC_KEY).
440
4254
fn get_introduce_key_material(
441
4254
    bx: &curve25519::SharedSecret,
442
4254
    auth_key: &ed25519::PublicKey,
443
4254
    X: &curve25519::PublicKey,
444
4254
    B: &curve25519::PublicKey,
445
4254
    subcredential: &Subcredential,
446
4254
) -> std::result::Result<(EncKey, MacKey), tor_error::Bug> {
447
4254
    let hs_ntor_protoid_constant = &b"tor-hs-ntor-curve25519-sha3-256-1"[..];
448
4254
    let hs_ntor_key_constant = &b"tor-hs-ntor-curve25519-sha3-256-1:hs_key_extract"[..];
449
4254
    let hs_ntor_expand_constant = &b"tor-hs-ntor-curve25519-sha3-256-1:hs_key_expand"[..];
450

            
451
    // Construct hs_keys = KDF(intro_secret_hs_input | t_hsenc | info, S_KEY_LEN+MAC_LEN)
452
    // Start by getting 'intro_secret_hs_input'
453
4254
    let mut secret_input = SecretBuf::new();
454
4254
    secret_input
455
4254
        .write(bx) // EXP(B,x)
456
4254
        .and_then(|_| secret_input.write(auth_key)) // AUTH_KEY
457
4254
        .and_then(|_| secret_input.write(X)) // X
458
4254
        .and_then(|_| secret_input.write(B)) // B
459
4254
        .and_then(|_| secret_input.write(hs_ntor_protoid_constant)) // PROTOID
460
        // Now fold in the t_hsenc
461
4254
        .and_then(|_| secret_input.write(hs_ntor_key_constant))
462
        // and fold in the 'info'
463
4254
        .and_then(|_| secret_input.write(hs_ntor_expand_constant))
464
4254
        .and_then(|_| secret_input.write(subcredential))
465
4254
        .map_err(into_internal!("Can't generate hs-ntor kdf input."))?;
466

            
467
4254
    let hs_keys = ShakeKdf::new()
468
4254
        .derive(&secret_input[..], 32 + 32)
469
4254
        .map_err(into_internal!("Can't compute SHAKE"))?;
470
    // Extract the keys into arrays
471
4254
    let enc_key = Zeroizing::new(
472
4254
        hs_keys[0..32]
473
4254
            .try_into()
474
4254
            .map_err(into_internal!("converting enc_key"))?,
475
    );
476
4254
    let mac_key = hs_keys[32..64]
477
4254
        .try_into()
478
4254
        .map_err(into_internal!("converting mac_key"))?;
479

            
480
4254
    Ok((enc_key, mac_key))
481
4254
}
482

            
483
/// Helper function: Compute the last part of the HS ntor handshake which
484
/// derives key material necessary to create and handle RENDEZVOUS1
485
/// cells. Function used by both client and service. The actual calculations is
486
/// as follows:
487
///
488
///  rend_secret_hs_input = EXP(X,y) | EXP(X,b) | AUTH_KEY | B | X | Y | PROTOID
489
///  NTOR_KEY_SEED = MAC(rend_secret_hs_input, t_hsenc)
490
///  verify = MAC(rend_secret_hs_input, t_hsverify)
491
///  auth_input = verify | AUTH_KEY | B | Y | X | PROTOID | "Server"
492
///  AUTH_INPUT_MAC = MAC(auth_input, t_hsmac)
493
///
494
/// Return (keygen, AUTH_INPUT_MAC), where keygen is a key generator based on
495
/// NTOR_KEY_SEED.
496
4
fn get_rendezvous_key_material(
497
4
    xy: &curve25519::SharedSecret,
498
4
    xb: &curve25519::SharedSecret,
499
4
    auth_key: &ed25519::PublicKey,
500
4
    B: &curve25519::PublicKey,
501
4
    X: &curve25519::PublicKey,
502
4
    Y: &curve25519::PublicKey,
503
4
) -> StdResult<(HsNtorHkdfKeyGenerator, AuthInputMac), tor_error::Bug> {
504
4
    let hs_ntor_protoid_constant = &b"tor-hs-ntor-curve25519-sha3-256-1"[..];
505
4
    let hs_ntor_mac_constant = &b"tor-hs-ntor-curve25519-sha3-256-1:hs_mac"[..];
506
4
    let hs_ntor_verify_constant = &b"tor-hs-ntor-curve25519-sha3-256-1:hs_verify"[..];
507
4
    let server_string_constant = &b"Server"[..];
508
4
    let hs_ntor_expand_constant = &b"tor-hs-ntor-curve25519-sha3-256-1:hs_key_expand"[..];
509
4
    let hs_ntor_key_constant = &b"tor-hs-ntor-curve25519-sha3-256-1:hs_key_extract"[..];
510

            
511
    // Start with rend_secret_hs_input
512
4
    let mut secret_input = SecretBuf::new();
513
4
    secret_input
514
4
        .write(xy) // EXP(X,y)
515
4
        .and_then(|_| secret_input.write(xb)) // EXP(X,b)
516
4
        .and_then(|_| secret_input.write(auth_key)) // AUTH_KEY
517
4
        .and_then(|_| secret_input.write(B)) // B
518
4
        .and_then(|_| secret_input.write(X)) // X
519
4
        .and_then(|_| secret_input.write(Y)) // Y
520
4
        .and_then(|_| secret_input.write(hs_ntor_protoid_constant)) // PROTOID
521
4
        .map_err(into_internal!(
522
            "Can't encode input to hs-ntor key derivation."
523
        ))?;
524

            
525
    // Build NTOR_KEY_SEED and verify
526
4
    let ntor_key_seed = hs_mac(&secret_input, hs_ntor_key_constant);
527
4
    let verify = hs_mac(&secret_input, hs_ntor_verify_constant);
528

            
529
    // Start building 'auth_input'
530
4
    let mut auth_input = Vec::new();
531
4
    auth_input
532
4
        .write(&verify)
533
4
        .and_then(|_| auth_input.write(auth_key)) // AUTH_KEY
534
4
        .and_then(|_| auth_input.write(B)) // B
535
4
        .and_then(|_| auth_input.write(Y)) // Y
536
4
        .and_then(|_| auth_input.write(X)) // X
537
4
        .and_then(|_| auth_input.write(hs_ntor_protoid_constant)) // PROTOID
538
4
        .and_then(|_| auth_input.write(server_string_constant)) // "Server"
539
4
        .map_err(into_internal!("Can't encode auth-input for hs-ntor."))?;
540

            
541
    // Get AUTH_INPUT_MAC
542
4
    let auth_input_mac = hs_mac(&auth_input, hs_ntor_mac_constant);
543

            
544
    // Now finish up with the KDF construction
545
4
    let mut kdf_seed = SecretBuf::new();
546
4
    kdf_seed
547
4
        .write(&ntor_key_seed)
548
4
        .and_then(|_| kdf_seed.write(hs_ntor_expand_constant))
549
4
        .map_err(into_internal!("Can't encode kdf-input for hs-ntor."))?;
550
4
    let keygen = HsNtorHkdfKeyGenerator::new(kdf_seed);
551

            
552
4
    Ok((keygen, auth_input_mac))
553
4
}
554

            
555
/*********************** Unit Tests ******************************************/
556

            
557
#[cfg(test)]
558
mod test {
559
    // @@ begin test lint list maintained by maint/add_warning @@
560
    #![allow(clippy::bool_assert_comparison)]
561
    #![allow(clippy::clone_on_copy)]
562
    #![allow(clippy::dbg_macro)]
563
    #![allow(clippy::mixed_attributes_style)]
564
    #![allow(clippy::print_stderr)]
565
    #![allow(clippy::print_stdout)]
566
    #![allow(clippy::single_char_pattern)]
567
    #![allow(clippy::unwrap_used)]
568
    #![allow(clippy::unchecked_time_subtraction)]
569
    #![allow(clippy::useless_vec)]
570
    #![allow(clippy::needless_pass_by_value)]
571
    #![allow(clippy::string_slice)] // See arti#2571
572
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
573
    use super::*;
574
    use hex_literal::hex;
575
    use tor_basic_utils::test_rng::testing_rng;
576

            
577
    #[test]
578
    /// Basic HS Ntor test that does the handshake between client and service
579
    /// and makes sure that the resulting keys and KDF is legit.
580
    fn hs_ntor() -> Result<()> {
581
        let mut rng = testing_rng();
582

            
583
        // Let's initialize keys for the client (and the intro point)
584
        let intro_b_privkey = curve25519::StaticSecret::random_from_rng(&mut rng);
585
        let intro_b_pubkey = curve25519::PublicKey::from(&intro_b_privkey);
586
        let intro_auth_key_privkey = ed25519::Keypair::generate(&mut rng);
587
        let intro_auth_key_pubkey = ed25519::PublicKey::from(&intro_auth_key_privkey);
588
        drop(intro_auth_key_privkey); // not actually used in this part of the protocol.
589

            
590
        // Create keys for client and service
591
        let client_keys = HsNtorServiceInfo::new(
592
            intro_b_pubkey.into(),
593
            intro_auth_key_pubkey.into(),
594
            [5; 32].into(),
595
        );
596

            
597
        let k_hss_ntor = HsSvcNtorKeypair::from_secret_key(intro_b_privkey.into());
598
        let auth_key = intro_auth_key_pubkey.into();
599
        let subcredentials = vec![[5; 32].into()];
600

            
601
        // Client: Sends an encrypted INTRODUCE1 cell
602
        let state = HsNtorClientState::new(&mut rng, client_keys);
603
        let cmsg = state.client_send_intro(&[66; 10], &[42; 60])?;
604
        assert_eq!(cmsg.len() + 10, INTRO1_TARGET_LEN);
605

            
606
        // Service: Decrypt INTRODUCE1 cell, and reply with RENDEZVOUS1 cell
607
        let (skeygen, smsg, s_plaintext) = server_receive_intro(
608
            &mut rng,
609
            &k_hss_ntor,
610
            &auth_key,
611
            &subcredentials[..],
612
            &[66; 10],
613
            &cmsg,
614
        )?;
615

            
616
        // Check that the plaintext received by the service is the one that the
617
        // client sent
618
        assert_eq!(s_plaintext[0..60], vec![42; 60]);
619

            
620
        // Client: Receive RENDEZVOUS1 and create key material
621
        let ckeygen = state.client_receive_rend(&smsg)?;
622

            
623
        // Test that RENDEZVOUS1 key material match
624
        let skeys = skeygen.expand(128)?;
625
        let ckeys = ckeygen.expand(128)?;
626
        assert_eq!(skeys, ckeys);
627

            
628
        Ok(())
629
    }
630

            
631
    #[test]
632
    /// Test vectors generated with hs_ntor_ref.py from little-t-tor.
633
    fn ntor_mac() {
634
        let result = hs_mac("who".as_bytes(), b"knows?");
635
        assert_eq!(
636
            &result,
637
            &hex!("5e7da329630fdaa3eab7498bb1dc625bbb9ca968f10392b6af92d51d5db17473").into()
638
        );
639

            
640
        let result = hs_mac("gone".as_bytes(), b"by");
641
        assert_eq!(
642
            &result,
643
            &hex!("90071aabb06d3f7c777db41542f4790c7dd9e2e7b2b842f54c9c42bbdb37e9a0").into()
644
        );
645
    }
646

            
647
    /// A set of test vectors generated with C tor and chutney.
648
    #[test]
649
    fn testvec() {
650
        let kp_hs_ipt_sid =
651
            hex!("34E171E4358E501BFF21ED907E96AC6BFEF697C779D040BBAF49ACC30FC5D21F");
652
        let subcredential =
653
            hex!("0085D26A9DEBA252263BF0231AEAC59B17CA11BAD8A218238AD6487CBAD68B57");
654
        let kp_hss_ntor = hex!("8E5127A40E83AABF6493E41F142B6EE3604B85A3961CD7E38D247239AFF71979");
655
        let ks_hss_ntor = hex!("A0ED5DBF94EEB2EDB3B514E4CF6ABFF6022051CC5F103391F1970A3FCD15296A");
656
        let key_x = hex!("60B4D6BF5234DCF87A4E9D7487BDF3F4A69B6729835E825CA29089CFDDA1E341");
657
        let key_y = hex!("68CB5188CA0CD7924250404FAB54EE1392D3D2B9C049A2E446513875952F8F55");
658

            
659
        // Information about the service.
660
        let kp_hs_ipt_sid: HsIntroPtSessionIdKey = ed25519::PublicKey::from_bytes(&kp_hs_ipt_sid)
661
            .unwrap()
662
            .into();
663
        let subcredential: Subcredential = subcredential.into();
664
        let kp_hss_ntor: HsSvcNtorKey = curve25519::PublicKey::from(kp_hss_ntor).into();
665

            
666
        let service_info = HsNtorServiceInfo {
667
            B: kp_hss_ntor,
668
            auth_key: kp_hs_ipt_sid.clone(),
669
            subcredential: subcredential.clone(),
670
        };
671

            
672
        // The client has to generate an ephemeral keypair.
673
        let key_x: curve25519::StaticSecret = curve25519::StaticSecret::from(key_x);
674

            
675
        // Information about the message to be sent to the service in the
676
        // INTRODUCE1 cell.
677
        let intro_header = hex!(
678
            "000000000000000000000000000000000000000002002034E171E4358E501BFF
679
            21ED907E96AC6BFEF697C779D040BBAF49ACC30FC5D21F00"
680
        );
681
        let intro_body = hex!(
682
            "6BD364C12638DD5C3BE23D76ACA05B04E6CE932C0101000100200DE6130E4FCA
683
             C4EDDA24E21220CC3EADAE403EF6B7D11C8273AC71908DE565450300067F0000
684
             0113890214F823C4F8CC085C792E0AEE0283FE00AD7520B37D0320728D5DF39B
685
             7B7077A0118A900FF4456C382F0041300ACF9C58E51C392795EF870000000000
686
             0000000000000000000000000000000000000000000000000000000000000000
687
             000000000000000000000000000000000000000000000000000000000000"
688
        );
689
        // Now try to do the handshake...
690
        let mut client_state = HsNtorClientState::new_no_keygen(service_info, key_x);
691
        // (Do not pad, since C tor's padding algorithm didn't match ours when
692
        // these test vectors were generated.)
693
        client_state.set_intro1_target_len(0);
694
        let encrypted_body = client_state
695
            .client_send_intro(&intro_header, &intro_body)
696
            .unwrap();
697

            
698
        let mut cell_out = intro_header.to_vec();
699
        cell_out.extend(&encrypted_body);
700
        let expected = &hex!(
701
            "000000000000000000000000000000000000000002002034E171E4358E501BFF
702
             21ED907E96AC6BFEF697C779D040BBAF49ACC30FC5D21F00BF04348B46D09AED
703
             726F1D66C618FDEA1DE58E8CB8B89738D7356A0C59111D5DADBECCCB38E37830
704
             4DCC179D3D9E437B452AF5702CED2CCFEC085BC02C4C175FA446525C1B9D5530
705
             563C362FDFFB802DAB8CD9EBC7A5EE17DA62E37DEEB0EB187FBB48C63298B0E8
706
             3F391B7566F42ADC97C46BA7588278273A44CE96BC68FFDAE31EF5F0913B9A9C
707
             7E0F173DBC0BDDCD4ACB4C4600980A7DDD9EAEC6E7F3FA3FC37CD95E5B8BFB3E
708
             35717012B78B4930569F895CB349A07538E42309C993223AEA77EF8AEA64F25D
709
             DEE97DA623F1AEC0A47F150002150455845C385E5606E41A9A199E7111D54EF2
710
             D1A51B7554D8B3692D85AC587FB9E69DF990EFB776D8"
711
        );
712
        assert_eq!(&cell_out, &expected);
713

            
714
        // ===
715
        // Okay, we have the message to send to the onion service.
716
        // ===
717

            
718
        // This corresponds to the public key above...
719
        let ks_hss_ntor = curve25519::StaticSecret::from(ks_hss_ntor).into();
720
        let k_hss_ntor = HsSvcNtorKeypair::from_secret_key(ks_hss_ntor);
721
        let key_y = curve25519::StaticSecret::from(key_y);
722
        let subcredentials = vec![subcredential];
723

            
724
        let (service_keygen, service_reply, service_plaintext) = server_receive_intro_no_keygen(
725
            &key_y,
726
            &k_hss_ntor,
727
            &kp_hs_ipt_sid,
728
            &subcredentials[..],
729
            &intro_header,
730
            &encrypted_body,
731
        )
732
        .unwrap();
733

            
734
        // Did we recover the plaintext correctly?
735
        assert_eq!(&service_plaintext, &intro_body);
736

            
737
        let expected_reply = hex!(
738
            "8fbe0db4d4a9c7ff46701e3e0ee7fd05cd28be4f302460addeec9e93354ee700
739
             4A92E8437B8424D5E5EC279245D5C72B25A0327ACF6DAF902079FCB643D8B208"
740
        );
741
        assert_eq!(&service_reply, &expected_reply);
742

            
743
        // Let's see if the client handles this reply!
744
        let client_keygen = client_state.client_receive_rend(&service_reply).unwrap();
745
        let bytes_client = client_keygen.expand(128).unwrap();
746
        let bytes_service = service_keygen.expand(128).unwrap();
747
        let mut key_seed =
748
            hex!("4D0C72FE8AFF35559D95ECC18EB5A36883402B28CDFD48C8A530A5A3D7D578DB").to_vec();
749
        key_seed.extend(b"tor-hs-ntor-curve25519-sha3-256-1:hs_key_expand");
750
        let bytes_expected = HsNtorHkdfKeyGenerator::new(key_seed.into())
751
            .expand(128)
752
            .unwrap();
753
        assert_eq!(&bytes_client, &bytes_service);
754
        assert_eq!(&bytes_client, &bytes_expected);
755
    }
756
}