rustls 0.1.0

Rustls is a modern TLS library written in Rust.
Documentation
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
use msgs::enums::{ContentType, HandshakeType, ProtocolVersion};
use msgs::enums::{Compression, NamedCurve, ECPointFormat, CipherSuite};
use msgs::enums::{ExtensionType, AlertDescription};
use msgs::enums::ClientCertificateType;
use msgs::message::{Message, MessagePayload};
use msgs::base::Payload;
use msgs::handshake::{HandshakePayload, SupportedSignatureAlgorithms};
use msgs::handshake::{HandshakeMessagePayload, ServerHelloPayload, Random};
use msgs::handshake::{ClientHelloPayload, ServerExtension};
use msgs::handshake::ConvertProtocolNameList;
use msgs::handshake::SignatureAndHashAlgorithm;
use msgs::handshake::{EllipticCurveList, SupportedCurves};
use msgs::handshake::{ECPointFormatList, SupportedPointFormats};
use msgs::handshake::{ServerECDHParams, DigitallySignedStruct};
use msgs::handshake::{ServerKeyExchangePayload, ECDHEServerKeyExchange};
use msgs::handshake::CertificateRequestPayload;
use msgs::handshake::SupportedMandatedSignatureAlgorithms;
use msgs::ccs::ChangeCipherSpecPayload;
use msgs::codec::Codec;
use server::{ServerSessionImpl, ConnState};
use suites;
use sign;
use verify;
use util;
use error::TLSError;
use handshake::Expectation;

use std::sync::Arc;
use std::mem;

macro_rules! extract_handshake(
  ( $m:expr, $t:path ) => (
    match $m.payload {
      MessagePayload::Handshake(ref hsp) => match hsp.payload {
        $t(ref hm) => Some(hm),
        _ => None
      },
      _ => None
    }
  )
);

pub type HandleFunction = fn(&mut ServerSessionImpl, m: &Message) -> Result<ConnState, TLSError>;

/* These are effectively operations on the ServerSessionImpl, variant on the
 * connection state. They must not have state of their own -- so they're
 * functions rather than a trait. */
pub struct Handler {
  pub expect: Expectation,
  pub handle: HandleFunction
}

fn process_extensions(sess: &mut ServerSessionImpl, hello: &ClientHelloPayload)
  -> Result<Vec<ServerExtension>, TLSError> {
  let mut ret = Vec::new();

  /* ALPN */
  let our_protocols = &sess.config.alpn_protocols;
  let maybe_their_protocols = hello.get_alpn_extension();
  if let Some(their_protocols) = maybe_their_protocols {
    let their_proto_strings = their_protocols.to_strings();

    if their_proto_strings.contains(&"".to_string()) {
      return Err(TLSError::PeerMisbehavedError("client offered empty ALPN protocol".to_string()));
    }

    sess.alpn_protocol = util::first_in_both(&our_protocols, &their_proto_strings);
    match sess.alpn_protocol {
      Some(ref selected_protocol) => {
        info!("Chosen ALPN protocol {:?}", selected_protocol);
        ret.push(ServerExtension::make_alpn(selected_protocol.clone()))
      },
      _ => {}
    };
  }

  /* Renegotiation.
   * (We don't do reneg at all, but would support the secure version if we did.) */
  let secure_reneg_offered =
    hello.find_extension(ExtensionType::RenegotiationInfo).is_some() ||
    hello.cipher_suites.contains(&CipherSuite::TLS_EMPTY_RENEGOTIATION_INFO_SCSV);

  if secure_reneg_offered {
    ret.push(ServerExtension::make_empty_renegotiation_info());
  }

  Ok(ret)
}

fn emit_server_hello(sess: &mut ServerSessionImpl, hello: &ClientHelloPayload) -> Result<(), TLSError> {
  sess.handshake_data.generate_server_random();
  let sessid = sess.config.session_storage.generate();
  let extensions = try!(process_extensions(sess, hello));

  let sh = Message {
    typ: ContentType::Handshake,
    version: ProtocolVersion::TLSv1_2,
    payload: MessagePayload::Handshake(
      HandshakeMessagePayload {
        typ: HandshakeType::ServerHello,
        payload: HandshakePayload::ServerHello(
          ServerHelloPayload {
            server_version: ProtocolVersion::TLSv1_2,
            random: Random::from_slice(&sess.handshake_data.secrets.server_random),
            session_id: sessid,
            cipher_suite: sess.handshake_data.ciphersuite.unwrap().suite.clone(),
            compression_method: Compression::Null,
            extensions: extensions
          }
        )
      }
    )
  };

  debug!("sending server hello {:?}", sh);
  sess.handshake_data.transcript.add_message(&sh);
  sess.common.send_msg(&sh, false);
  Ok(())
}

fn emit_certificate(sess: &mut ServerSessionImpl) {
  let cert_chain = sess.handshake_data.server_cert_chain.as_ref().unwrap().clone();

  let c = Message {
    typ: ContentType::Handshake,
    version: ProtocolVersion::TLSv1_2,
    payload: MessagePayload::Handshake(
      HandshakeMessagePayload {
        typ: HandshakeType::Certificate,
        payload: HandshakePayload::Certificate(cert_chain)
      }
    )
  };

  sess.handshake_data.transcript.add_message(&c);
  sess.common.send_msg(&c, false);
}

fn emit_server_kx(sess: &mut ServerSessionImpl,
                  sigalg: &SignatureAndHashAlgorithm,
                  curve: &NamedCurve,
                  signer: Arc<Box<sign::Signer>>) -> Result<(), TLSError> {
  let kx = try!({
    let scs = sess.handshake_data.ciphersuite.as_ref().unwrap();
    scs.start_server_kx(curve)
      .ok_or_else(|| TLSError::PeerMisbehavedError("key exchange failed".to_string()))
  });
  let secdh = ServerECDHParams::new(curve, &kx.pubkey);

  let mut msg = Vec::new();
  msg.extend(&sess.handshake_data.secrets.client_random);
  msg.extend(&sess.handshake_data.secrets.server_random);
  secdh.encode(&mut msg);

  let sig = try!(
    signer.sign(&sigalg.hash, &msg)
    .map_err(|_| TLSError::General("signing failed".to_string()))
  );

  let skx = ServerKeyExchangePayload::ECDHE(
    ECDHEServerKeyExchange {
      params: secdh,
      dss: DigitallySignedStruct::new(sigalg, sig)
    }
  );

  let m = Message {
    typ: ContentType::Handshake,
    version: ProtocolVersion::TLSv1_2,
    payload: MessagePayload::Handshake(
      HandshakeMessagePayload {
        typ: HandshakeType::ServerKeyExchange,
        payload: HandshakePayload::ServerKeyExchange(skx)
      }
    )
  };

  sess.handshake_data.kx_data = Some(kx);
  sess.handshake_data.transcript.add_message(&m);
  sess.common.send_msg(&m, false);
  Ok(())
}

fn emit_certificate_req(sess: &mut ServerSessionImpl) {
  if !sess.config.client_auth_offer {
    return;
  }

  let names = sess.config.client_auth_roots.get_subjects();

  let cr = CertificateRequestPayload {
    certtypes: vec![ ClientCertificateType::RSASign,
                     ClientCertificateType::ECDSASign ],
    sigalgs: SupportedSignatureAlgorithms::supported_verify(),
    canames: names
  };

  let m = Message {
    typ: ContentType::Handshake,
    version: ProtocolVersion::TLSv1_2,
    payload: MessagePayload::Handshake(
      HandshakeMessagePayload {
        typ: HandshakeType::CertificateRequest,
        payload: HandshakePayload::CertificateRequest(cr)
      }
    )
  };

  debug!("Sending CertificateRequest {:?}", m);
  sess.handshake_data.transcript.add_message(&m);
  sess.common.send_msg(&m, false);
  sess.handshake_data.doing_client_auth = true;
}

fn emit_server_hello_done(sess: &mut ServerSessionImpl) {
  let m = Message {
    typ: ContentType::Handshake,
    version: ProtocolVersion::TLSv1_2,
    payload: MessagePayload::Handshake(
      HandshakeMessagePayload {
        typ: HandshakeType::ServerHelloDone,
        payload: HandshakePayload::ServerHelloDone
      }
    )
  };

  sess.handshake_data.transcript.add_message(&m);
  sess.common.send_msg(&m, false);
}

fn incompatible(sess: &mut ServerSessionImpl, why: &str) -> TLSError {
  sess.common.send_fatal_alert(AlertDescription::HandshakeFailure);
  TLSError::PeerIncompatibleError(why.to_string())
}

fn handle_client_hello(sess: &mut ServerSessionImpl, m: &Message) -> Result<ConnState, TLSError> {
  let client_hello = extract_handshake!(m, HandshakePayload::ClientHello).unwrap();

  if client_hello.client_version.get_u16() < ProtocolVersion::TLSv1_2.get_u16() {
    sess.common.send_fatal_alert(AlertDescription::ProtocolVersion);
    return Err(TLSError::PeerIncompatibleError("client does not support TLSv1_2".to_string()));
  }

  if !client_hello.compression_methods.contains(&Compression::Null) {
    sess.common.send_fatal_alert(AlertDescription::IllegalParameter);
    return Err(TLSError::PeerIncompatibleError("client did not offer Null compression".to_string()));
  }

  if client_hello.has_duplicate_extension() {
    sess.common.send_fatal_alert(AlertDescription::DecodeError);
    return Err(TLSError::PeerMisbehavedError("client sent duplicate extensions".to_string()));
  }

  /* Save their Random. */
  client_hello.random.write_slice(&mut sess.handshake_data.secrets.client_random);

  let default_sigalgs_ext = SupportedSignatureAlgorithms::default();

  let sni_ext = client_hello.get_sni_extension();
  let sigalgs_ext = client_hello.get_sigalgs_extension()
    .unwrap_or(&default_sigalgs_ext);
  let eccurves_ext = try!(client_hello.get_eccurves_extension()
                          .ok_or_else(|| incompatible(sess, "client didn't describe ec curves")));
  let ecpoints_ext = try!(client_hello.get_ecpoints_extension()
                          .ok_or_else(|| incompatible(sess, "client didn't describe ec points")));

  debug!("we got a clienthello {:?}", client_hello);
  debug!("sni {:?}", sni_ext);
  debug!("sigalgs {:?}", sigalgs_ext);
  debug!("eccurves {:?}", eccurves_ext);
  debug!("ecpoints {:?}", ecpoints_ext);

  if !ecpoints_ext.contains(&ECPointFormat::Uncompressed) {
    sess.common.send_fatal_alert(AlertDescription::IllegalParameter);
    return Err(TLSError::PeerIncompatibleError("client didn't support uncompressed ec points".to_string()));
  }

  /* Choose a certificate. */
  let maybe_cert_key = sess.config.cert_resolver.resolve(sni_ext, sigalgs_ext, eccurves_ext, ecpoints_ext);
  if maybe_cert_key.is_err() {
    sess.common.send_fatal_alert(AlertDescription::AccessDenied);
    return Err(TLSError::General("no server certificate chain resolved".to_string()));
  }
  let (cert_chain, private_key) = maybe_cert_key.unwrap();

  /* Reduce our supported ciphersuites by the certificate. */
  let ciphersuites_suitable_for_cert = suites::reduce_given_sigalg(&sess.config.ciphersuites,
                                                                   &private_key.algorithm());
  sess.handshake_data.server_cert_chain = Some(cert_chain);

  let maybe_ciphersuite = if sess.config.ignore_client_order {
    suites::choose_ciphersuite_preferring_server(&client_hello.cipher_suites,
                                                 &ciphersuites_suitable_for_cert)
  } else {
    suites::choose_ciphersuite_preferring_client(&client_hello.cipher_suites,
                                                 &ciphersuites_suitable_for_cert)
  };

  if maybe_ciphersuite.is_none() {
    return Err(incompatible(sess, "no ciphersuites in common"));
  }

  sess.handshake_data.ciphersuite = maybe_ciphersuite;
  info!("decided upon suite {:?}", maybe_ciphersuite.as_ref().unwrap());

  /* Start handshake hash. */
  sess.handshake_data.start_handshake_hash();
  sess.handshake_data.transcript.add_message(m);

  /* Now we have chosen a ciphersuite, we can make kx decisions. */
  let sigalg = try!(
    sess.handshake_data.ciphersuite.as_ref().unwrap()
      .resolve_sig_alg(sigalgs_ext)
      .ok_or_else(|| incompatible(sess, "no supported sigalg"))
  );
  let eccurve = try!(
    util::first_in_both(EllipticCurveList::supported().as_slice(),
                        eccurves_ext.as_slice())
      .ok_or_else(|| incompatible(sess, "no supported curve"))
  );
  let ecpoint = try!(
    util::first_in_both(ECPointFormatList::supported().as_slice(),
                        ecpoints_ext.as_slice())
      .ok_or_else(|| incompatible(sess, "no supported point format"))
  );

  assert_eq!(ecpoint, ECPointFormat::Uncompressed);

  try!(emit_server_hello(sess, client_hello));
  emit_certificate(sess);
  try!(emit_server_kx(sess, &sigalg, &eccurve, private_key));
  emit_certificate_req(sess);
  emit_server_hello_done(sess);

  if sess.handshake_data.doing_client_auth {
    Ok(ConnState::ExpectCertificate)
  } else {
    Ok(ConnState::ExpectClientKX)
  }
}

pub static EXPECT_CLIENT_HELLO: Handler = Handler {
  expect: Expectation {
    content_types: &[ContentType::Handshake],
    handshake_types: &[HandshakeType::ClientHello]
  },
  handle: handle_client_hello
};

/* --- Process client's Certificate for client auth --- */
fn handle_certificate(sess: &mut ServerSessionImpl, m: &Message) -> Result<ConnState, TLSError> {
  sess.handshake_data.transcript.add_message(m);
  let cert_chain = extract_handshake!(m, HandshakePayload::Certificate).unwrap();

  if cert_chain.len() == 0 && !sess.config.client_auth_mandatory {
    info!("client auth requested but no certificate supplied");
    sess.handshake_data.doing_client_auth = false;
    sess.handshake_data.transcript.abandon_client_auth();
    return Ok(ConnState::ExpectClientKX);
  }

  debug!("certs {:?}", cert_chain);

  try!(
    verify::verify_client_cert(&sess.config.client_auth_roots,
                               &cert_chain)
  );

  sess.handshake_data.valid_client_cert_chain = Some(cert_chain.clone());
  Ok(ConnState::ExpectClientKX)
}

pub static EXPECT_CERTIFICATE: Handler = Handler {
  expect: Expectation {
    content_types: &[ContentType::Handshake],
    handshake_types: &[HandshakeType::Certificate]
  },
  handle: handle_certificate
};

/* --- Process client's KeyExchange --- */
fn handle_client_kx(sess: &mut ServerSessionImpl, m: &Message) -> Result<ConnState, TLSError> {
  let client_kx = extract_handshake!(m, HandshakePayload::ClientKeyExchange).unwrap();
  sess.handshake_data.transcript.add_message(m);

  /* Complete key agreement, and set up encryption with the
   * resulting premaster secret. */
  let kx = mem::replace(&mut sess.handshake_data.kx_data, None).unwrap();
  let kxd = try!(
    kx.server_complete(&client_kx.0)
    .ok_or_else(|| TLSError::PeerMisbehavedError("key exchange completion failed".to_string()))
  );

  sess.secrets_current.init(&sess.handshake_data.secrets,
                            sess.handshake_data.ciphersuite.as_ref().unwrap().get_hash(),
                            &kxd.premaster_secret);
  sess.start_encryption();

  if sess.handshake_data.doing_client_auth {
    Ok(ConnState::ExpectCertificateVerify)
  } else {
    Ok(ConnState::ExpectCCS)
  }
}

pub static EXPECT_CLIENT_KX: Handler = Handler {
  expect: Expectation {
    content_types: &[ContentType::Handshake],
    handshake_types: &[HandshakeType::ClientKeyExchange]
  },
  handle: handle_client_kx
};

/* --- Process client's certificate proof --- */
fn handle_certificate_verify(sess: &mut ServerSessionImpl, m: &Message) -> Result<ConnState, TLSError> {
  let rc = {
    let sig = extract_handshake!(m, HandshakePayload::CertificateVerify).unwrap();
    let certs = sess.handshake_data.valid_client_cert_chain.as_ref().unwrap();
    let handshake_msgs = sess.handshake_data.transcript.take_handshake_buf();

    verify::verify_signed_struct(&handshake_msgs, &certs[0], &sig)
  };

  if rc.is_err() {
    sess.common.send_fatal_alert(AlertDescription::AccessDenied);
    return Err(rc.unwrap_err());
  } else {
    debug!("client CertificateVerify OK");
  }

  sess.handshake_data.transcript.add_message(m);
  Ok(ConnState::ExpectCCS)
}

pub static EXPECT_CERTIFICATE_VERIFY: Handler = Handler {
  expect: Expectation {
    content_types: &[ContentType::Handshake],
    handshake_types: &[HandshakeType::CertificateVerify]
  },
  handle: handle_certificate_verify
};

/* --- Process client's ChangeCipherSpec --- */
fn handle_ccs(sess: &mut ServerSessionImpl, _m: &Message) -> Result<ConnState, TLSError> {
  /* CCS should not be received interleaved with fragmented handshake-level
   * message. */
  if !sess.common.handshake_joiner.empty() {
    warn!("CCS received interleaved with fragmented handshake");
    return Err(TLSError::InappropriateMessage {
      expect_types: vec![ ContentType::Handshake ],
      got_type: ContentType::ChangeCipherSpec
    });
  }

  sess.common.peer_now_encrypting();
  Ok(ConnState::ExpectFinished)
}

pub static EXPECT_CCS: Handler = Handler {
  expect: Expectation {
    content_types: &[ContentType::ChangeCipherSpec],
    handshake_types: &[]
  },
  handle: handle_ccs
};

/* --- Process client's Finished --- */
fn emit_ccs(sess: &mut ServerSessionImpl) {
  let m = Message {
    typ: ContentType::ChangeCipherSpec,
    version: ProtocolVersion::TLSv1_2,
    payload: MessagePayload::ChangeCipherSpec(ChangeCipherSpecPayload {})
  };

  sess.common.send_msg(&m, false);
  sess.common.we_now_encrypting();
}

fn emit_finished(sess: &mut ServerSessionImpl) {
  let vh = sess.handshake_data.transcript.get_current_hash();
  let verify_data = sess.secrets_current.server_verify_data(&vh);
  let verify_data_payload = Payload::new(verify_data);

  let f = Message {
    typ: ContentType::Handshake,
    version: ProtocolVersion::TLSv1_2,
    payload: MessagePayload::Handshake(
      HandshakeMessagePayload {
        typ: HandshakeType::Finished,
        payload: HandshakePayload::Finished(verify_data_payload)
      }
    )
  };

  sess.common.send_msg(&f, true);
}

fn handle_finished(sess: &mut ServerSessionImpl, m: &Message) -> Result<ConnState, TLSError> {
  let finished = extract_handshake!(m, HandshakePayload::Finished).unwrap();

  let vh = sess.handshake_data.transcript.get_current_hash();
  let expect_verify_data = sess.secrets_current.client_verify_data(&vh);

  use ring;
  try!(
    ring::constant_time::verify_slices_are_equal(&expect_verify_data, &finished.0)
      .map_err(|_| { error!("Finished wrong"); TLSError::DecryptError })
  );

  sess.handshake_data.transcript.add_message(m);
  emit_ccs(sess);
  emit_finished(sess);
  Ok(ConnState::Traffic)
}

pub static EXPECT_FINISHED: Handler = Handler {
  expect: Expectation {
    content_types: &[ContentType::Handshake],
    handshake_types: &[HandshakeType::Finished]
  },
  handle: handle_finished
};

/* --- Process traffic --- */
fn handle_traffic(sess: &mut ServerSessionImpl, m: &Message) -> Result<ConnState, TLSError> {
  sess.common.take_received_plaintext(m.get_opaque_payload().unwrap());
  Ok(ConnState::Traffic)
}

pub static TRAFFIC: Handler = Handler {
  expect: Expectation {
    content_types: &[ContentType::ApplicationData],
    handshake_types: &[]
  },
  handle: handle_traffic
};