1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
use crate::aead::{ChaCha8PacketKey, PlaintextHeaderKey, HEADER_KEYPAIR};
use crate::dh::DiffieHellman;
use crate::keylog::KeyLog;
use ed25519_dalek::{Keypair, PublicKey};
use quinn_proto::crypto::{
    ClientConfig, ExportKeyingMaterialError, KeyPair, Keys, ServerConfig, Session,
};
use quinn_proto::transport_parameters::TransportParameters;
use quinn_proto::{ConnectError, ConnectionId, Side, TransportError, TransportErrorCode};
use ring::aead;
use std::io::Cursor;
use std::sync::Arc;
use subtle::ConstantTimeEq;
use xoodoo::Xoodyak;

/// Noise configuration struct.
#[derive(Default)]
pub struct NoiseConfig {
    /// Keypair to use. If none is provided one will be generated.
    pub keypair: Option<Keypair>,
    /// The remote public key. This needs to be set.
    pub remote_public_key: Option<PublicKey>,
    /// Optional private shared key usable as a password for private networks.
    pub psk: Option<[u8; 32]>,
    /// Enables keylogging for debugging purposes to the path provided by `SSLKEYLOGFILE`.
    pub keylogger: Option<Arc<dyn KeyLog>>,
}

impl Clone for NoiseConfig {
    fn clone(&self) -> Self {
        let keypair = self
            .keypair
            .as_ref()
            .map(|keypair| Keypair::from_bytes(&keypair.to_bytes()).unwrap());
        Self {
            keypair,
            remote_public_key: self.remote_public_key,
            psk: self.psk,
            keylogger: self.keylogger.clone(),
        }
    }
}

impl ClientConfig<NoiseSession> for NoiseConfig {
    fn new() -> Self {
        Default::default()
    }

    fn start_session(
        &self,
        _: &str,
        params: &TransportParameters,
    ) -> Result<NoiseSession, ConnectError> {
        Ok(NoiseConfig::start_session(self, Side::Client, params))
    }
}

impl ServerConfig<NoiseSession> for Arc<NoiseConfig> {
    fn new() -> Self {
        Default::default()
    }

    fn start_session(&self, params: &TransportParameters) -> NoiseSession {
        NoiseConfig::start_session(self, Side::Server, params)
    }
}

impl NoiseConfig {
    fn start_session(&self, side: Side, params: &TransportParameters) -> NoiseSession {
        let mut rng = rand_core::OsRng {};
        let s = if let Some(keypair) = self.keypair.as_ref() {
            Keypair::from_bytes(&keypair.to_bytes()).unwrap()
        } else {
            Keypair::generate(&mut rng)
        };
        let e = Keypair::generate(&mut rng);
        NoiseSession {
            xoodyak: Xoodyak::hash(),
            state: State::Initial,
            side,
            e,
            s,
            psk: self.psk.unwrap_or_default(),
            transport_parameters: *params,
            remote_transport_parameters: None,
            remote_e: None,
            remote_s: self.remote_public_key,
            zero_rtt_key: None,
            keylogger: self.keylogger.clone(),
        }
    }
}

pub struct NoiseSession {
    xoodyak: Xoodyak,
    state: State,
    side: Side,
    e: Keypair,
    s: Keypair,
    psk: [u8; 32],
    transport_parameters: TransportParameters,
    remote_transport_parameters: Option<TransportParameters>,
    remote_e: Option<PublicKey>,
    remote_s: Option<PublicKey>,
    zero_rtt_key: Option<ChaCha8PacketKey>,
    keylogger: Option<Arc<dyn KeyLog>>,
}

impl NoiseSession {
    fn conn_id(&self) -> Option<&[u8; 32]> {
        match self.side {
            Side::Client => Some(self.e.public.as_bytes()),
            Side::Server => Some(self.remote_e.as_ref()?.as_bytes()),
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
enum State {
    Initial,
    ZeroRtt,
    Handshake,
    OneRtt,
    Data,
}

fn connection_refused(reason: &str) -> TransportError {
    TransportError {
        code: TransportErrorCode::CONNECTION_REFUSED,
        frame: None,
        reason: reason.to_string(),
    }
}

impl Session for NoiseSession {
    type HandshakeData = ();
    type Identity = PublicKey;
    type ClientConfig = NoiseConfig;
    type ServerConfig = Arc<NoiseConfig>;
    type HmacKey = ring::hmac::Key;
    type HandshakeTokenKey = ring::hkdf::Prk;
    type HeaderKey = PlaintextHeaderKey;
    type PacketKey = ChaCha8PacketKey;

    fn initial_keys(_: &ConnectionId, _: Side) -> Keys<Self> {
        Keys {
            header: HEADER_KEYPAIR,
            packet: KeyPair {
                local: ChaCha8PacketKey::new([0; 32]),
                remote: ChaCha8PacketKey::new([0; 32]),
            },
        }
    }

    fn next_1rtt_keys(&mut self) -> KeyPair<Self::PacketKey> {
        if !self.is_handshaking() {
            self.xoodyak.ratchet();
        }
        let mut client = [0; 32];
        self.xoodyak.squeeze_key(&mut client);
        let mut server = [0; 32];
        self.xoodyak.squeeze_key(&mut server);
        if let Some(keylogger) = self.keylogger.as_ref() {
            keylogger.log("CLIENT_KEY", self.conn_id().unwrap(), &client[..]);
            keylogger.log("SERVER_KEY", self.conn_id().unwrap(), &server[..]);
        }
        let client = ChaCha8PacketKey::new(client);
        let server = ChaCha8PacketKey::new(server);
        let key = match self.side {
            Side::Client => KeyPair {
                local: client,
                remote: server,
            },
            Side::Server => KeyPair {
                local: server,
                remote: client,
            },
        };
        key
    }

    fn read_handshake(&mut self, handshake: &[u8]) -> Result<bool, TransportError> {
        tracing::trace!("read_handshake {:?} {:?}", self.state, self.side);
        match (self.state, self.side) {
            (State::Initial, Side::Server) => {
                let (len, rest) = handshake.split_at(1);
                let (protocol_id, rest) = rest.split_at(len[0] as usize);
                if protocol_id != b"Noise_IKpsk1_Edx25519_ChaCha8Poly" {
                    return Err(connection_refused("unsupported protocol id"));
                }
                let (e, rest) = rest.split_at(32);
                self.xoodyak.absorb(protocol_id);
                self.xoodyak.absorb(e);
                self.xoodyak.absorb(self.s.public.as_bytes());
                let e = PublicKey::from_bytes(e)
                    .map_err(|_| connection_refused("invalid ephemeral public key"))?;
                self.remote_e = Some(e);
                let es = self.s.diffie_hellman(&e);
                self.xoodyak.absorb(&es);
                let mut key = [0; 32];
                self.xoodyak.squeeze(&mut key);
                self.xoodyak = Xoodyak::keyed(&key, None, None, None);
                let (remote_s, rest) = rest.split_at(32);
                let mut s = [0; 32];
                self.xoodyak.decrypt(&remote_s, &mut s);
                let s = PublicKey::from_bytes(&s)
                    .map_err(|_| connection_refused("invalid static public key"))?;
                self.remote_s = Some(s);
                let ss = self.s.diffie_hellman(&s);
                self.xoodyak.absorb(&ss);
                self.xoodyak.absorb(&self.psk);
                let (params, auth) = rest.split_at(rest.len() - 16);
                let mut transport_parameters = vec![0; params.len()];
                self.xoodyak.decrypt(&params, &mut transport_parameters);
                let mut tag = [0; 16];
                self.xoodyak.squeeze(&mut tag);
                if !bool::from(tag.ct_eq(&auth)) {
                    return Err(connection_refused("invalid authentication tag"));
                }
                self.remote_transport_parameters = Some(TransportParameters::read(
                    Side::Server,
                    &mut Cursor::new(&mut transport_parameters),
                )?);
                self.state = State::ZeroRtt;
                Ok(true)
            }
            (State::Handshake, Side::Client) => {
                let (remote_e, rest) = handshake.split_at(32);
                let mut e = [0; 32];
                self.xoodyak.decrypt(&remote_e, &mut e);
                let e = PublicKey::from_bytes(&e)
                    .map_err(|_| connection_refused("invalid ephemeral public key"))?;
                self.remote_e = Some(e);
                let ee = self.e.diffie_hellman(&e);
                self.xoodyak.absorb(&ee);
                let se = self.s.diffie_hellman(&e);
                self.xoodyak.absorb(&se);
                let (params, auth) = rest.split_at(rest.len() - 16);
                let mut transport_parameters = vec![0; params.len()];
                self.xoodyak.decrypt(&params, &mut transport_parameters);
                let mut tag = [0; 16];
                self.xoodyak.squeeze(&mut tag);
                if !bool::from(tag.ct_eq(&auth)) {
                    return Err(connection_refused("invalid authentication tag"));
                }
                self.remote_transport_parameters = Some(TransportParameters::read(
                    Side::Client,
                    &mut Cursor::new(&mut transport_parameters),
                )?);
                self.state = State::OneRtt;
                Ok(true)
            }
            _ => Err(TransportError {
                code: TransportErrorCode::CONNECTION_REFUSED,
                frame: None,
                reason: "unexpected crypto frame".to_string(),
            }),
        }
    }

    fn write_handshake(&mut self, handshake: &mut Vec<u8>) -> Option<Keys<Self>> {
        tracing::trace!("write_handshake {:?} {:?}", self.state, self.side);
        match (self.state, self.side) {
            (State::Initial, Side::Client) => {
                let protocol_id = b"Noise_IKpsk1_Edx25519_ChaCha8Poly";
                self.xoodyak.absorb(protocol_id);
                handshake.extend_from_slice(&[protocol_id.len() as u8]);
                handshake.extend_from_slice(protocol_id);
                self.xoodyak.absorb(self.e.public.as_bytes());
                handshake.extend_from_slice(self.e.public.as_bytes());
                let s = self.remote_s.unwrap();
                self.xoodyak.absorb(s.as_bytes());
                let es = self.e.diffie_hellman(&s);
                self.xoodyak.absorb(&es);
                let mut key = [0; 32];
                self.xoodyak.squeeze(&mut key);
                self.xoodyak = Xoodyak::keyed(&key, None, None, None);
                self.state = State::Handshake;
                let mut s = [0; 32];
                self.xoodyak.encrypt(self.s.public.as_bytes(), &mut s);
                handshake.extend_from_slice(&s);
                let s = self.remote_s.unwrap();
                let ss = self.s.diffie_hellman(&s);
                self.xoodyak.absorb(&ss);
                self.xoodyak.absorb(&self.psk);
                let mut transport_parameters = vec![];
                self.transport_parameters.write(&mut transport_parameters);
                self.xoodyak.encrypt_in_place(&mut transport_parameters);
                handshake.extend_from_slice(&transport_parameters);
                let mut tag = [0; 16];
                self.xoodyak.squeeze(&mut tag);
                handshake.extend_from_slice(&tag);
                self.state = State::ZeroRtt;
                None
            }
            (State::ZeroRtt, _) => {
                let packet = self.next_1rtt_keys();
                self.state = State::Handshake;
                self.zero_rtt_key = Some(packet.local.clone());
                Some(Keys {
                    header: HEADER_KEYPAIR,
                    packet,
                })
            }
            (State::Handshake, Side::Server) => {
                let mut e = [0; 32];
                self.xoodyak.encrypt(self.e.public.as_bytes(), &mut e);
                handshake.extend_from_slice(&e);
                let ee = self.e.diffie_hellman(&self.remote_e.unwrap());
                self.xoodyak.absorb(&ee);
                let se = self.e.diffie_hellman(&self.remote_s.unwrap());
                self.xoodyak.absorb(&se);
                let mut transport_parameters = vec![];
                self.transport_parameters.write(&mut transport_parameters);
                self.xoodyak.encrypt_in_place(&mut transport_parameters);
                handshake.extend_from_slice(&transport_parameters);
                let mut tag = [0; 16];
                self.xoodyak.squeeze(&mut tag);
                handshake.extend_from_slice(&tag);
                let packet = self.next_1rtt_keys();
                self.state = State::Data;
                Some(Keys {
                    header: HEADER_KEYPAIR,
                    packet,
                })
            }
            (State::OneRtt, _) => {
                let packet = self.next_1rtt_keys();
                self.state = State::Data;
                Some(Keys {
                    header: HEADER_KEYPAIR,
                    packet,
                })
            }
            _ => None,
        }
    }

    fn is_handshaking(&self) -> bool {
        self.state != State::Data
    }

    fn peer_identity(&self) -> Option<Self::Identity> {
        self.remote_s
    }

    fn transport_parameters(&self) -> Result<Option<TransportParameters>, TransportError> {
        if self.state == State::Handshake && self.side == Side::Client {
            Ok(Some(self.transport_parameters))
        } else {
            Ok(self.remote_transport_parameters)
        }
    }

    fn handshake_data(&self) -> Option<Self::HandshakeData> {
        Some(())
    }

    fn export_keying_material(
        &self,
        output: &mut [u8],
        label: &[u8],
        context: &[u8],
    ) -> Result<(), ExportKeyingMaterialError> {
        let mut xoodyak = self.xoodyak.clone();
        xoodyak.absorb(label);
        xoodyak.absorb(context);
        xoodyak.squeeze_key(output);
        Ok(())
    }

    fn early_crypto(&self) -> Option<(Self::HeaderKey, Self::PacketKey)> {
        Some((PlaintextHeaderKey, self.zero_rtt_key.clone().unwrap()))
    }

    fn early_data_accepted(&self) -> Option<bool> {
        Some(true)
    }

    fn retry_tag(orig_dst_cid: &ConnectionId, packet: &[u8]) -> [u8; 16] {
        let mut pseudo_packet = Vec::with_capacity(packet.len() + orig_dst_cid.len() + 1);
        pseudo_packet.push(orig_dst_cid.len() as u8);
        pseudo_packet.extend_from_slice(orig_dst_cid);
        pseudo_packet.extend_from_slice(packet);

        let nonce = aead::Nonce::assume_unique_for_key(RETRY_INTEGRITY_NONCE);
        let key = aead::LessSafeKey::new(
            aead::UnboundKey::new(&aead::AES_128_GCM, &RETRY_INTEGRITY_KEY).unwrap(),
        );

        let tag = key
            .seal_in_place_separate_tag(nonce, aead::Aad::from(pseudo_packet), &mut [])
            .unwrap();
        let mut result = [0; 16];
        result.copy_from_slice(tag.as_ref());
        result
    }

    fn is_valid_retry(orig_dst_cid: &ConnectionId, header: &[u8], payload: &[u8]) -> bool {
        let tag_start = match payload.len().checked_sub(16) {
            Some(x) => x,
            None => return false,
        };

        let mut pseudo_packet =
            Vec::with_capacity(header.len() + payload.len() + orig_dst_cid.len() + 1);
        pseudo_packet.push(orig_dst_cid.len() as u8);
        pseudo_packet.extend_from_slice(orig_dst_cid);
        pseudo_packet.extend_from_slice(header);
        let tag_start = tag_start + pseudo_packet.len();
        pseudo_packet.extend_from_slice(payload);

        let nonce = aead::Nonce::assume_unique_for_key(RETRY_INTEGRITY_NONCE);
        let key = aead::LessSafeKey::new(
            aead::UnboundKey::new(&aead::AES_128_GCM, &RETRY_INTEGRITY_KEY).unwrap(),
        );

        let (aad, tag) = pseudo_packet.split_at_mut(tag_start);
        key.open_in_place(nonce, aead::Aad::from(aad), tag).is_ok()
    }
}

const RETRY_INTEGRITY_KEY: [u8; 16] = [
    0xcc, 0xce, 0x18, 0x7e, 0xd0, 0x9a, 0x09, 0xd0, 0x57, 0x28, 0x15, 0x5a, 0x6c, 0xb9, 0x6b, 0xe1,
];
const RETRY_INTEGRITY_NONCE: [u8; 12] = [
    0xe5, 0x49, 0x30, 0xf9, 0x7f, 0x21, 0x36, 0xf0, 0x53, 0x0a, 0x8c, 0x1c,
];