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
use msgs::enums::{CipherSuite, HashAlgorithm, SignatureAlgorithm, NamedCurve};
use msgs::handshake::{SignatureAndHashAlgorithm, KeyExchangeAlgorithm};
use msgs::handshake::SupportedSignatureAlgorithms;
use msgs::handshake::{ClientECDHParams, ServerECDHParams};
use msgs::codec::{Reader, Codec};
use util;

use ring;
use untrusted;

#[allow(non_camel_case_types)]
#[derive(Debug, PartialEq)]
pub enum BulkAlgorithm {
  AES_128_GCM,
  AES_256_GCM,
  CHACHA20_POLY1305
}

/// The result of a key exchange.  This has our public key,
/// and the agreed premaster secret.
pub struct KeyExchangeResult {
  pub pubkey: Vec<u8>,
  pub premaster_secret: Vec<u8>
}

/// An in-progress key exchange.  This has the algorithm,
/// our private key, and our public key.
pub struct KeyExchange {
  alg: &'static ring::agreement::Algorithm,
  privkey: ring::agreement::EphemeralPrivateKey,
  pub pubkey: Vec<u8>
}

impl KeyExchange {
  pub fn named_curve_to_ecdh_alg(named_curve: &NamedCurve) -> Option<&'static ring::agreement::Algorithm> {
    match named_curve {
      &NamedCurve::X25519 => Some(&ring::agreement::X25519),
      &NamedCurve::secp256r1 => Some(&ring::agreement::ECDH_P256),
      &NamedCurve::secp384r1 => Some(&ring::agreement::ECDH_P384),
      _ => None
    }
  }

  pub fn client_ecdhe(kx_params: &Vec<u8>) -> Option<KeyExchangeResult> {
    let mut rd = Reader::init(&kx_params);
    let ecdh_params = try_ret!(ServerECDHParams::read(&mut rd));

    try_ret!(KeyExchange::start_ecdhe(&ecdh_params.curve_params.named_curve))
      .complete(&ecdh_params.public.0)
  }

  pub fn start_ecdhe(named_curve: &NamedCurve) -> Option<KeyExchange> {
    let alg = try_ret!(KeyExchange::named_curve_to_ecdh_alg(named_curve));
    let rng = ring::rand::SystemRandom::new();
    let ours = ring::agreement::EphemeralPrivateKey::generate(alg, &rng)
      .unwrap();

    let mut pubkey = Vec::new();
    pubkey.resize(ours.public_key_len(), 0u8);
    ours.compute_public_key(pubkey.as_mut_slice()).unwrap();

    Some(KeyExchange { alg: alg, privkey: ours, pubkey: pubkey })
  }

  pub fn server_complete(self, kx_params: &[u8]) -> Option<KeyExchangeResult> {
    let mut rd = Reader::init(kx_params);
    let ecdh_params = ClientECDHParams::read(&mut rd).unwrap();

    self.complete(&ecdh_params.public.0)
  }

  fn complete(self, peer: &[u8]) -> Option<KeyExchangeResult> {
    let secret = ring::agreement::agree_ephemeral(
      self.privkey,
      self.alg,
      untrusted::Input::from(peer),
      (),
      |v| { let mut r = Vec::new(); r.extend_from_slice(v); Ok(r) }
    );

    if secret.is_err() {
      return None;
    }

    Some(KeyExchangeResult { pubkey: self.pubkey, premaster_secret: secret.unwrap() })
  }
}

/// A cipher suite supported by rustls.
///
/// All possible instances of this class are provided by the library in
/// the ALL_CIPHERSUITES array.
#[derive(Debug)]
pub struct SupportedCipherSuite {
  /// The TLS enumeration naming this cipher suite.
  pub suite: CipherSuite,
  pub kx: KeyExchangeAlgorithm,
  pub bulk: BulkAlgorithm,
  pub hash: HashAlgorithm,
  pub sign: SignatureAlgorithm,
  pub mac_key_len: usize,
  pub enc_key_len: usize,
  pub fixed_iv_len: usize,

  /// This is a non-standard extension which extends the
  /// key block to provide an initial explicit nonce offset,
  /// in a deterministic and safe way.  GCM needs this,
  /// chacha20poly1305 works this way by design.
  pub explicit_nonce_len: usize
}

impl PartialEq for SupportedCipherSuite {
  fn eq(&self, other: &SupportedCipherSuite) -> bool {
    self.suite == other.suite
  }
}

impl SupportedCipherSuite {
  pub fn get_hash(&self) -> &'static ring::digest::Algorithm {
    match &self.hash {
      &HashAlgorithm::SHA1 => &ring::digest::SHA1,
      &HashAlgorithm::SHA256 => &ring::digest::SHA256,
      &HashAlgorithm::SHA384 => &ring::digest::SHA384,
      &HashAlgorithm::SHA512 => &ring::digest::SHA512,
      _ => unreachable!()
    }
  }

  /// We have parameters and a verified public key in `kx_params`.
  /// Generate an ephemeral key, generate the shared secret, and
  /// return it and the public half in a `KeyExchangeResult`.
  pub fn do_client_kx(&self, kx_params: &Vec<u8>) -> Option<KeyExchangeResult> {
    match &self.kx {
      &KeyExchangeAlgorithm::ECDHE => KeyExchange::client_ecdhe(kx_params),
      _ => None
    }
  }

  pub fn start_server_kx(&self, named_curve: &NamedCurve) -> Option<KeyExchange> {
    match &self.kx {
      &KeyExchangeAlgorithm::ECDHE => KeyExchange::start_ecdhe(named_curve),
      _ => None
    }
  }

  /// Resolve a single supported `SignatureAndHashAlgorithm` from the
  /// offered `SupportedSignatureAlgorithms`.  If we return None,
  /// the handshake terminates.
  pub fn resolve_sig_alg(&self, sigalgs: &SupportedSignatureAlgorithms) -> Option<SignatureAndHashAlgorithm> {
    let our_preference = vec![
      // Prefer the designated hash algorithm of this suite, for
      // security level consistency.
      SignatureAndHashAlgorithm { hash: self.hash, sign: self.sign },

      // Then prefer the right sign algorithm, with the best hashes
      // first.
      SignatureAndHashAlgorithm { hash: HashAlgorithm::SHA512, sign: self.sign },
      SignatureAndHashAlgorithm { hash: HashAlgorithm::SHA384, sign: self.sign },
      SignatureAndHashAlgorithm { hash: HashAlgorithm::SHA256, sign: self.sign }
    ];

    util::first_in_both(our_preference.as_slice(),
                        sigalgs.as_slice())
  }

  pub fn get_aead_alg(&self) -> &'static ring::aead::Algorithm {
    match &self.bulk {
      &BulkAlgorithm::AES_128_GCM => &ring::aead::AES_128_GCM,
      &BulkAlgorithm::AES_256_GCM => &ring::aead::AES_256_GCM,
      &BulkAlgorithm::CHACHA20_POLY1305 => &ring::aead::CHACHA20_POLY1305
    }
  }

  pub fn key_block_len(&self) -> usize {
    (self.mac_key_len + self.enc_key_len + self.fixed_iv_len) * 2 + self.explicit_nonce_len
  }
}

pub static TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: SupportedCipherSuite =
SupportedCipherSuite {
  suite: CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
  kx: KeyExchangeAlgorithm::ECDHE,
  sign: SignatureAlgorithm::ECDSA,
  bulk: BulkAlgorithm::CHACHA20_POLY1305,
  hash: HashAlgorithm::SHA256,
  mac_key_len: 0,
  enc_key_len: 32,
  fixed_iv_len: 12,
  explicit_nonce_len: 0
};

pub static TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: SupportedCipherSuite =
SupportedCipherSuite {
  suite: CipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
  kx: KeyExchangeAlgorithm::ECDHE,
  sign: SignatureAlgorithm::RSA,
  bulk: BulkAlgorithm::CHACHA20_POLY1305,
  hash: HashAlgorithm::SHA256,
  mac_key_len: 0,
  enc_key_len: 32,
  fixed_iv_len: 12,
  explicit_nonce_len: 0
};

pub static TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: SupportedCipherSuite =
SupportedCipherSuite {
  suite: CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  kx: KeyExchangeAlgorithm::ECDHE,
  sign: SignatureAlgorithm::RSA,
  bulk: BulkAlgorithm::AES_128_GCM,
  hash: HashAlgorithm::SHA256,
  mac_key_len: 0,
  enc_key_len: 16,
  fixed_iv_len: 4,
  explicit_nonce_len: 8
};

pub static TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: SupportedCipherSuite =
SupportedCipherSuite {
  suite: CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  kx: KeyExchangeAlgorithm::ECDHE,
  sign: SignatureAlgorithm::RSA,
  bulk: BulkAlgorithm::AES_256_GCM,
  hash: HashAlgorithm::SHA384,
  mac_key_len: 0,
  enc_key_len: 32,
  fixed_iv_len: 4,
  explicit_nonce_len: 8
};

pub static TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: SupportedCipherSuite =
SupportedCipherSuite {
  suite: CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  kx: KeyExchangeAlgorithm::ECDHE,
  sign: SignatureAlgorithm::ECDSA,
  bulk: BulkAlgorithm::AES_128_GCM,
  hash: HashAlgorithm::SHA256,
  mac_key_len: 0,
  enc_key_len: 16,
  fixed_iv_len: 4,
  explicit_nonce_len: 8
};

pub static TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: SupportedCipherSuite =
SupportedCipherSuite {
  suite: CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  kx: KeyExchangeAlgorithm::ECDHE,
  sign: SignatureAlgorithm::ECDSA,
  bulk: BulkAlgorithm::AES_256_GCM,
  hash: HashAlgorithm::SHA384,
  mac_key_len: 0,
  enc_key_len: 32,
  fixed_iv_len: 4,
  explicit_nonce_len: 8
};

/// A list of all the cipher suites supported by rustls.
pub static ALL_CIPHERSUITES: [&'static SupportedCipherSuite; 6] = [
  &TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
  &TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
  &TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  &TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  &TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  &TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
];

/* These both O(N^2)! */
pub fn choose_ciphersuite_preferring_client(
    client_suites: &Vec<CipherSuite>,
    server_suites: &Vec<&'static SupportedCipherSuite>) -> Option<&'static SupportedCipherSuite> {
  for client_suite in client_suites {
    if let Some(selected) = server_suites.iter().find(|x| *client_suite == x.suite) {
      return Some(*selected);
    }
  }

  None
}

pub fn choose_ciphersuite_preferring_server(
    client_suites: &Vec<CipherSuite>,
    server_suites: &Vec<&'static SupportedCipherSuite>) -> Option<&'static SupportedCipherSuite> {
  if let Some(selected) = server_suites.iter().find(|x| client_suites.contains(&x.suite)) {
    return Some(*selected);
  }

  None
}

/// Return a list of the ciphersuites in `all` with the suites
/// incompatible with SignatureAlgorithm `sigalg` removed.
pub fn reduce_given_sigalg(all: &Vec<&'static SupportedCipherSuite>, sigalg: &SignatureAlgorithm)
  -> Vec<&'static SupportedCipherSuite> {
  all.iter()
     .filter(|&&suite| &suite.sign == sigalg)
     .cloned()
     .collect()
}

#[cfg(test)]
mod test {
  use msgs::enums::CipherSuite;

  #[test]
  fn test_client_pref() {
    let client = vec![
      CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
      CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
    ];
    let server = vec![
      &super::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
      &super::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
    ];
    let chosen = super::choose_ciphersuite_preferring_client(&client, &server);
    assert!(chosen.is_some());
    assert_eq!(chosen.unwrap(), &super::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256);
  }

  #[test]
  fn test_server_pref() {
    let client = vec![
      CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
      CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
    ];
    let server = vec![
      &super::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
      &super::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
    ];
    let chosen = super::choose_ciphersuite_preferring_server(&client, &server);
    assert!(chosen.is_some());
    assert_eq!(chosen.unwrap(), &super::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384);
  }
}