1 /* Copyright (c) 2016, Google Inc.
2 *
3 * Permission to use, copy, modify, and/or distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
6 *
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14
15 #include <openssl/ssl.h>
16
17 #include <assert.h>
18 #include <string.h>
19
20 #include <tuple>
21
22 #include <openssl/aead.h>
23 #include <openssl/bytestring.h>
24 #include <openssl/digest.h>
25 #include <openssl/err.h>
26 #include <openssl/mem.h>
27 #include <openssl/rand.h>
28 #include <openssl/stack.h>
29
30 #include "../crypto/internal.h"
31 #include "internal.h"
32
33
34 BSSL_NAMESPACE_BEGIN
35
36 enum server_hs_state_t {
37 state_select_parameters = 0,
38 state_select_session,
39 state_send_hello_retry_request,
40 state_read_second_client_hello,
41 state_send_server_hello,
42 state_send_server_certificate_verify,
43 state_send_server_finished,
44 state_read_second_client_flight,
45 state_process_end_of_early_data,
46 state_read_client_certificate,
47 state_read_client_certificate_verify,
48 state_read_channel_id,
49 state_read_client_finished,
50 state_send_new_session_ticket,
51 state_done,
52 };
53
54 static const uint8_t kZeroes[EVP_MAX_MD_SIZE] = {0};
55
resolve_ecdhe_secret(SSL_HANDSHAKE * hs,bool * out_need_retry,SSL_CLIENT_HELLO * client_hello)56 static int resolve_ecdhe_secret(SSL_HANDSHAKE *hs, bool *out_need_retry,
57 SSL_CLIENT_HELLO *client_hello) {
58 SSL *const ssl = hs->ssl;
59 *out_need_retry = false;
60
61 // We only support connections that include an ECDHE key exchange.
62 CBS key_share;
63 if (!ssl_client_hello_get_extension(client_hello, &key_share,
64 TLSEXT_TYPE_key_share)) {
65 OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_KEY_SHARE);
66 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_MISSING_EXTENSION);
67 return 0;
68 }
69
70 bool found_key_share;
71 Array<uint8_t> dhe_secret;
72 uint8_t alert = SSL_AD_DECODE_ERROR;
73 if (!ssl_ext_key_share_parse_clienthello(hs, &found_key_share, &dhe_secret,
74 &alert, &key_share)) {
75 ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
76 return 0;
77 }
78
79 if (!found_key_share) {
80 *out_need_retry = true;
81 return 0;
82 }
83
84 return tls13_advance_key_schedule(hs, dhe_secret.data(), dhe_secret.size());
85 }
86
ssl_ext_supported_versions_add_serverhello(SSL_HANDSHAKE * hs,CBB * out)87 static int ssl_ext_supported_versions_add_serverhello(SSL_HANDSHAKE *hs,
88 CBB *out) {
89 CBB contents;
90 if (!CBB_add_u16(out, TLSEXT_TYPE_supported_versions) ||
91 !CBB_add_u16_length_prefixed(out, &contents) ||
92 !CBB_add_u16(&contents, hs->ssl->version) ||
93 !CBB_flush(out)) {
94 return 0;
95 }
96
97 return 1;
98 }
99
100 // CipherScorer produces a "score" for each possible cipher suite offered by
101 // the client.
102 class CipherScorer {
103 public:
CipherScorer(uint16_t group_id)104 CipherScorer(uint16_t group_id)
105 : aes_is_fine_(EVP_has_aes_hardware()),
106 security_128_is_fine_(group_id != SSL_CURVE_CECPQ2) {}
107
108 typedef std::tuple<bool, bool, bool> Score;
109
110 // MinScore returns a |Score| that will compare less than the score of all
111 // cipher suites.
MinScore() const112 Score MinScore() const {
113 return Score(false, false, false);
114 }
115
Evaluate(const SSL_CIPHER * a) const116 Score Evaluate(const SSL_CIPHER *a) const {
117 return Score(
118 // Something is always preferable to nothing.
119 true,
120 // Either 128-bit is fine, or 256-bit is preferred.
121 security_128_is_fine_ || a->algorithm_enc != SSL_AES128GCM,
122 // Either AES is fine, or else ChaCha20 is preferred.
123 aes_is_fine_ || a->algorithm_enc == SSL_CHACHA20POLY1305);
124 }
125
126 private:
127 const bool aes_is_fine_;
128 const bool security_128_is_fine_;
129 };
130
choose_tls13_cipher(const SSL * ssl,const SSL_CLIENT_HELLO * client_hello,uint16_t group_id)131 static const SSL_CIPHER *choose_tls13_cipher(
132 const SSL *ssl, const SSL_CLIENT_HELLO *client_hello, uint16_t group_id) {
133 if (client_hello->cipher_suites_len % 2 != 0) {
134 return nullptr;
135 }
136
137 CBS cipher_suites;
138 CBS_init(&cipher_suites, client_hello->cipher_suites,
139 client_hello->cipher_suites_len);
140
141 const uint16_t version = ssl_protocol_version(ssl);
142
143 const SSL_CIPHER *best = nullptr;
144 CipherScorer scorer(group_id);
145 CipherScorer::Score best_score = scorer.MinScore();
146
147 while (CBS_len(&cipher_suites) > 0) {
148 uint16_t cipher_suite;
149 if (!CBS_get_u16(&cipher_suites, &cipher_suite)) {
150 return nullptr;
151 }
152
153 // Limit to TLS 1.3 ciphers we know about.
154 const SSL_CIPHER *candidate = SSL_get_cipher_by_value(cipher_suite);
155 if (candidate == nullptr ||
156 SSL_CIPHER_get_min_version(candidate) > version ||
157 SSL_CIPHER_get_max_version(candidate) < version) {
158 continue;
159 }
160
161 const CipherScorer::Score candidate_score = scorer.Evaluate(candidate);
162 // |candidate_score| must be larger to displace the current choice. That way
163 // the client's order controls between ciphers with an equal score.
164 if (candidate_score > best_score) {
165 best = candidate;
166 best_score = candidate_score;
167 }
168 }
169
170 return best;
171 }
172
add_new_session_tickets(SSL_HANDSHAKE * hs,bool * out_sent_tickets)173 static bool add_new_session_tickets(SSL_HANDSHAKE *hs, bool *out_sent_tickets) {
174 SSL *const ssl = hs->ssl;
175 if (// If the client doesn't accept resumption with PSK_DHE_KE, don't send a
176 // session ticket.
177 !hs->accept_psk_mode ||
178 // We only implement stateless resumption in TLS 1.3, so skip sending
179 // tickets if disabled.
180 (SSL_get_options(ssl) & SSL_OP_NO_TICKET)) {
181 *out_sent_tickets = false;
182 return true;
183 }
184
185 // TLS 1.3 recommends single-use tickets, so issue multiple tickets in case
186 // the client makes several connections before getting a renewal.
187 static const int kNumTickets = 2;
188
189 // Rebase the session timestamp so that it is measured from ticket
190 // issuance.
191 ssl_session_rebase_time(ssl, hs->new_session.get());
192
193 for (int i = 0; i < kNumTickets; i++) {
194 UniquePtr<SSL_SESSION> session(
195 SSL_SESSION_dup(hs->new_session.get(), SSL_SESSION_INCLUDE_NONAUTH));
196 if (!session) {
197 return false;
198 }
199
200 if (!RAND_bytes((uint8_t *)&session->ticket_age_add, 4)) {
201 return false;
202 }
203 session->ticket_age_add_valid = true;
204 if (ssl->enable_early_data) {
205 session->ticket_max_early_data = kMaxEarlyDataAccepted;
206 }
207
208 static_assert(kNumTickets < 256, "Too many tickets");
209 uint8_t nonce[] = {static_cast<uint8_t>(i)};
210
211 ScopedCBB cbb;
212 CBB body, nonce_cbb, ticket, extensions;
213 if (!ssl->method->init_message(ssl, cbb.get(), &body,
214 SSL3_MT_NEW_SESSION_TICKET) ||
215 !CBB_add_u32(&body, session->timeout) ||
216 !CBB_add_u32(&body, session->ticket_age_add) ||
217 !CBB_add_u8_length_prefixed(&body, &nonce_cbb) ||
218 !CBB_add_bytes(&nonce_cbb, nonce, sizeof(nonce)) ||
219 !CBB_add_u16_length_prefixed(&body, &ticket) ||
220 !tls13_derive_session_psk(session.get(), nonce) ||
221 !ssl_encrypt_ticket(hs, &ticket, session.get()) ||
222 !CBB_add_u16_length_prefixed(&body, &extensions)) {
223 return false;
224 }
225
226 if (ssl->enable_early_data) {
227 CBB early_data_info;
228 if (!CBB_add_u16(&extensions, TLSEXT_TYPE_early_data) ||
229 !CBB_add_u16_length_prefixed(&extensions, &early_data_info) ||
230 !CBB_add_u32(&early_data_info, session->ticket_max_early_data) ||
231 !CBB_flush(&extensions)) {
232 return false;
233 }
234 }
235
236 // Add a fake extension. See draft-davidben-tls-grease-01.
237 if (!CBB_add_u16(&extensions,
238 ssl_get_grease_value(hs, ssl_grease_ticket_extension)) ||
239 !CBB_add_u16(&extensions, 0 /* empty */)) {
240 return false;
241 }
242
243 if (!ssl_add_message_cbb(ssl, cbb.get())) {
244 return false;
245 }
246 }
247
248 *out_sent_tickets = true;
249 return true;
250 }
251
do_select_parameters(SSL_HANDSHAKE * hs)252 static enum ssl_hs_wait_t do_select_parameters(SSL_HANDSHAKE *hs) {
253 // At this point, most ClientHello extensions have already been processed by
254 // the common handshake logic. Resolve the remaining non-PSK parameters.
255 SSL *const ssl = hs->ssl;
256 SSLMessage msg;
257 if (!ssl->method->get_message(ssl, &msg)) {
258 return ssl_hs_read_message;
259 }
260 SSL_CLIENT_HELLO client_hello;
261 if (!ssl_client_hello_init(ssl, &client_hello, msg)) {
262 OPENSSL_PUT_ERROR(SSL, SSL_R_CLIENTHELLO_PARSE_FAILED);
263 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
264 return ssl_hs_error;
265 }
266
267 OPENSSL_memcpy(hs->session_id, client_hello.session_id,
268 client_hello.session_id_len);
269 hs->session_id_len = client_hello.session_id_len;
270
271 uint16_t group_id;
272 if (!tls1_get_shared_group(hs, &group_id)) {
273 OPENSSL_PUT_ERROR(SSL, SSL_R_NO_SHARED_GROUP);
274 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
275 return ssl_hs_error;
276 }
277
278 // Negotiate the cipher suite.
279 hs->new_cipher = choose_tls13_cipher(ssl, &client_hello, group_id);
280 if (hs->new_cipher == NULL) {
281 OPENSSL_PUT_ERROR(SSL, SSL_R_NO_SHARED_CIPHER);
282 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
283 return ssl_hs_error;
284 }
285
286 // HTTP/2 negotiation depends on the cipher suite, so ALPN negotiation was
287 // deferred. Complete it now.
288 uint8_t alert = SSL_AD_DECODE_ERROR;
289 if (!ssl_negotiate_alpn(hs, &alert, &client_hello)) {
290 ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
291 return ssl_hs_error;
292 }
293
294 // The PRF hash is now known. Set up the key schedule and hash the
295 // ClientHello.
296 if (!hs->transcript.InitHash(ssl_protocol_version(ssl), hs->new_cipher)) {
297 return ssl_hs_error;
298 }
299
300 if (!ssl_hash_message(hs, msg)) {
301 return ssl_hs_error;
302 }
303
304 hs->tls13_state = state_select_session;
305 return ssl_hs_ok;
306 }
307
select_session(SSL_HANDSHAKE * hs,uint8_t * out_alert,UniquePtr<SSL_SESSION> * out_session,int32_t * out_ticket_age_skew,const SSLMessage & msg,const SSL_CLIENT_HELLO * client_hello)308 static enum ssl_ticket_aead_result_t select_session(
309 SSL_HANDSHAKE *hs, uint8_t *out_alert, UniquePtr<SSL_SESSION> *out_session,
310 int32_t *out_ticket_age_skew, const SSLMessage &msg,
311 const SSL_CLIENT_HELLO *client_hello) {
312 SSL *const ssl = hs->ssl;
313 *out_session = NULL;
314
315 // Decode the ticket if we agreed on a PSK key exchange mode.
316 CBS pre_shared_key;
317 if (!hs->accept_psk_mode ||
318 !ssl_client_hello_get_extension(client_hello, &pre_shared_key,
319 TLSEXT_TYPE_pre_shared_key)) {
320 return ssl_ticket_aead_ignore_ticket;
321 }
322
323 // Verify that the pre_shared_key extension is the last extension in
324 // ClientHello.
325 if (CBS_data(&pre_shared_key) + CBS_len(&pre_shared_key) !=
326 client_hello->extensions + client_hello->extensions_len) {
327 OPENSSL_PUT_ERROR(SSL, SSL_R_PRE_SHARED_KEY_MUST_BE_LAST);
328 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
329 return ssl_ticket_aead_error;
330 }
331
332 CBS ticket, binders;
333 uint32_t client_ticket_age;
334 if (!ssl_ext_pre_shared_key_parse_clienthello(hs, &ticket, &binders,
335 &client_ticket_age, out_alert,
336 &pre_shared_key)) {
337 return ssl_ticket_aead_error;
338 }
339
340 // TLS 1.3 session tickets are renewed separately as part of the
341 // NewSessionTicket.
342 bool unused_renew;
343 UniquePtr<SSL_SESSION> session;
344 enum ssl_ticket_aead_result_t ret =
345 ssl_process_ticket(hs, &session, &unused_renew, ticket, {});
346 switch (ret) {
347 case ssl_ticket_aead_success:
348 break;
349 case ssl_ticket_aead_error:
350 *out_alert = SSL_AD_INTERNAL_ERROR;
351 return ret;
352 default:
353 return ret;
354 }
355
356 if (!ssl_session_is_resumable(hs, session.get()) ||
357 // Historically, some TLS 1.3 tickets were missing ticket_age_add.
358 !session->ticket_age_add_valid) {
359 return ssl_ticket_aead_ignore_ticket;
360 }
361
362 // Recover the client ticket age and convert to seconds.
363 client_ticket_age -= session->ticket_age_add;
364 client_ticket_age /= 1000;
365
366 struct OPENSSL_timeval now;
367 ssl_get_current_time(ssl, &now);
368
369 // Compute the server ticket age in seconds.
370 assert(now.tv_sec >= session->time);
371 uint64_t server_ticket_age = now.tv_sec - session->time;
372
373 // To avoid overflowing |hs->ticket_age_skew|, we will not resume
374 // 68-year-old sessions.
375 if (server_ticket_age > INT32_MAX) {
376 return ssl_ticket_aead_ignore_ticket;
377 }
378
379 // TODO(davidben,svaldez): Measure this value to decide on tolerance. For
380 // now, accept all values. https://crbug.com/boringssl/113.
381 *out_ticket_age_skew =
382 (int32_t)client_ticket_age - (int32_t)server_ticket_age;
383
384 // Check the PSK binder.
385 if (!tls13_verify_psk_binder(hs, session.get(), msg, &binders)) {
386 *out_alert = SSL_AD_DECRYPT_ERROR;
387 return ssl_ticket_aead_error;
388 }
389
390 *out_session = std::move(session);
391 return ssl_ticket_aead_success;
392 }
393
do_select_session(SSL_HANDSHAKE * hs)394 static enum ssl_hs_wait_t do_select_session(SSL_HANDSHAKE *hs) {
395 SSL *const ssl = hs->ssl;
396 SSLMessage msg;
397 if (!ssl->method->get_message(ssl, &msg)) {
398 return ssl_hs_read_message;
399 }
400 SSL_CLIENT_HELLO client_hello;
401 if (!ssl_client_hello_init(ssl, &client_hello, msg)) {
402 OPENSSL_PUT_ERROR(SSL, SSL_R_CLIENTHELLO_PARSE_FAILED);
403 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
404 return ssl_hs_error;
405 }
406
407 uint8_t alert = SSL_AD_DECODE_ERROR;
408 UniquePtr<SSL_SESSION> session;
409 switch (select_session(hs, &alert, &session, &ssl->s3->ticket_age_skew, msg,
410 &client_hello)) {
411 case ssl_ticket_aead_ignore_ticket:
412 assert(!session);
413 if (!ssl_get_new_session(hs, 1 /* server */)) {
414 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
415 return ssl_hs_error;
416 }
417 break;
418
419 case ssl_ticket_aead_success:
420 // Carry over authentication information from the previous handshake into
421 // a fresh session.
422 hs->new_session =
423 SSL_SESSION_dup(session.get(), SSL_SESSION_DUP_AUTH_ONLY);
424
425 if (ssl->enable_early_data &&
426 // Early data must be acceptable for this ticket.
427 session->ticket_max_early_data != 0 &&
428 // The client must have offered early data.
429 hs->early_data_offered &&
430 // Channel ID is incompatible with 0-RTT.
431 !ssl->s3->channel_id_valid &&
432 // If Token Binding is negotiated, reject 0-RTT.
433 !ssl->s3->token_binding_negotiated &&
434 // The negotiated ALPN must match the one in the ticket.
435 MakeConstSpan(ssl->s3->alpn_selected) == session->early_alpn) {
436 ssl->s3->early_data_accepted = true;
437 }
438
439 if (hs->new_session == NULL) {
440 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
441 return ssl_hs_error;
442 }
443
444 ssl->s3->session_reused = true;
445
446 // Resumption incorporates fresh key material, so refresh the timeout.
447 ssl_session_renew_timeout(ssl, hs->new_session.get(),
448 ssl->session_ctx->session_psk_dhe_timeout);
449 break;
450
451 case ssl_ticket_aead_error:
452 ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
453 return ssl_hs_error;
454
455 case ssl_ticket_aead_retry:
456 hs->tls13_state = state_select_session;
457 return ssl_hs_pending_ticket;
458 }
459
460 // Record connection properties in the new session.
461 hs->new_session->cipher = hs->new_cipher;
462
463 // Store the initial negotiated ALPN in the session.
464 if (!hs->new_session->early_alpn.CopyFrom(ssl->s3->alpn_selected)) {
465 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
466 return ssl_hs_error;
467 }
468
469 if (ssl->ctx->dos_protection_cb != NULL &&
470 ssl->ctx->dos_protection_cb(&client_hello) == 0) {
471 // Connection rejected for DOS reasons.
472 OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
473 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
474 return ssl_hs_error;
475 }
476
477 size_t hash_len = EVP_MD_size(
478 ssl_get_handshake_digest(ssl_protocol_version(ssl), hs->new_cipher));
479
480 // Set up the key schedule and incorporate the PSK into the running secret.
481 if (ssl->s3->session_reused) {
482 if (!tls13_init_key_schedule(hs, hs->new_session->master_key,
483 hs->new_session->master_key_length)) {
484 return ssl_hs_error;
485 }
486 } else if (!tls13_init_key_schedule(hs, kZeroes, hash_len)) {
487 return ssl_hs_error;
488 }
489
490 if (ssl->s3->early_data_accepted) {
491 if (!tls13_derive_early_secrets(hs)) {
492 return ssl_hs_error;
493 }
494 } else if (hs->early_data_offered) {
495 ssl->s3->skip_early_data = true;
496 }
497
498 // Resolve ECDHE and incorporate it into the secret.
499 bool need_retry;
500 if (!resolve_ecdhe_secret(hs, &need_retry, &client_hello)) {
501 if (need_retry) {
502 ssl->s3->early_data_accepted = false;
503 ssl->s3->skip_early_data = true;
504 ssl->method->next_message(ssl);
505 if (!hs->transcript.UpdateForHelloRetryRequest()) {
506 return ssl_hs_error;
507 }
508 hs->tls13_state = state_send_hello_retry_request;
509 return ssl_hs_ok;
510 }
511 return ssl_hs_error;
512 }
513
514 ssl->method->next_message(ssl);
515 hs->tls13_state = state_send_server_hello;
516 return ssl_hs_ok;
517 }
518
do_send_hello_retry_request(SSL_HANDSHAKE * hs)519 static enum ssl_hs_wait_t do_send_hello_retry_request(SSL_HANDSHAKE *hs) {
520 SSL *const ssl = hs->ssl;
521
522
523 ScopedCBB cbb;
524 CBB body, session_id, extensions;
525 uint16_t group_id;
526 if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_SERVER_HELLO) ||
527 !CBB_add_u16(&body, TLS1_2_VERSION) ||
528 !CBB_add_bytes(&body, kHelloRetryRequest, SSL3_RANDOM_SIZE) ||
529 !CBB_add_u8_length_prefixed(&body, &session_id) ||
530 !CBB_add_bytes(&session_id, hs->session_id, hs->session_id_len) ||
531 !CBB_add_u16(&body, ssl_cipher_get_value(hs->new_cipher)) ||
532 !CBB_add_u8(&body, 0 /* no compression */) ||
533 !tls1_get_shared_group(hs, &group_id) ||
534 !CBB_add_u16_length_prefixed(&body, &extensions) ||
535 !CBB_add_u16(&extensions, TLSEXT_TYPE_supported_versions) ||
536 !CBB_add_u16(&extensions, 2 /* length */) ||
537 !CBB_add_u16(&extensions, ssl->version) ||
538 !CBB_add_u16(&extensions, TLSEXT_TYPE_key_share) ||
539 !CBB_add_u16(&extensions, 2 /* length */) ||
540 !CBB_add_u16(&extensions, group_id) ||
541 !ssl_add_message_cbb(ssl, cbb.get())) {
542 return ssl_hs_error;
543 }
544
545 if (!ssl->method->add_change_cipher_spec(ssl)) {
546 return ssl_hs_error;
547 }
548
549 hs->sent_hello_retry_request = true;
550 hs->tls13_state = state_read_second_client_hello;
551 return ssl_hs_flush;
552 }
553
do_read_second_client_hello(SSL_HANDSHAKE * hs)554 static enum ssl_hs_wait_t do_read_second_client_hello(SSL_HANDSHAKE *hs) {
555 SSL *const ssl = hs->ssl;
556 SSLMessage msg;
557 if (!ssl->method->get_message(ssl, &msg)) {
558 return ssl_hs_read_message;
559 }
560 if (!ssl_check_message_type(ssl, msg, SSL3_MT_CLIENT_HELLO)) {
561 return ssl_hs_error;
562 }
563 SSL_CLIENT_HELLO client_hello;
564 if (!ssl_client_hello_init(ssl, &client_hello, msg)) {
565 OPENSSL_PUT_ERROR(SSL, SSL_R_CLIENTHELLO_PARSE_FAILED);
566 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
567 return ssl_hs_error;
568 }
569
570 bool need_retry;
571 if (!resolve_ecdhe_secret(hs, &need_retry, &client_hello)) {
572 if (need_retry) {
573 // Only send one HelloRetryRequest.
574 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
575 OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
576 }
577 return ssl_hs_error;
578 }
579
580 if (!ssl_hash_message(hs, msg)) {
581 return ssl_hs_error;
582 }
583
584 ssl->method->next_message(ssl);
585 hs->tls13_state = state_send_server_hello;
586 return ssl_hs_ok;
587 }
588
do_send_server_hello(SSL_HANDSHAKE * hs)589 static enum ssl_hs_wait_t do_send_server_hello(SSL_HANDSHAKE *hs) {
590 SSL *const ssl = hs->ssl;
591
592 // Send a ServerHello.
593 ScopedCBB cbb;
594 CBB body, extensions, session_id;
595 if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_SERVER_HELLO) ||
596 !CBB_add_u16(&body, TLS1_2_VERSION) ||
597 !RAND_bytes(ssl->s3->server_random, sizeof(ssl->s3->server_random)) ||
598 !CBB_add_bytes(&body, ssl->s3->server_random, SSL3_RANDOM_SIZE) ||
599 !CBB_add_u8_length_prefixed(&body, &session_id) ||
600 !CBB_add_bytes(&session_id, hs->session_id, hs->session_id_len) ||
601 !CBB_add_u16(&body, ssl_cipher_get_value(hs->new_cipher)) ||
602 !CBB_add_u8(&body, 0) ||
603 !CBB_add_u16_length_prefixed(&body, &extensions) ||
604 !ssl_ext_pre_shared_key_add_serverhello(hs, &extensions) ||
605 !ssl_ext_key_share_add_serverhello(hs, &extensions) ||
606 !ssl_ext_supported_versions_add_serverhello(hs, &extensions) ||
607 !ssl_add_message_cbb(ssl, cbb.get())) {
608 return ssl_hs_error;
609 }
610
611 if (!hs->sent_hello_retry_request &&
612 !ssl->method->add_change_cipher_spec(ssl)) {
613 return ssl_hs_error;
614 }
615
616 // Derive and enable the handshake traffic secrets.
617 if (!tls13_derive_handshake_secrets(hs) ||
618 !tls13_set_traffic_key(ssl, ssl_encryption_handshake, evp_aead_seal,
619 hs->server_handshake_secret, hs->hash_len)) {
620 return ssl_hs_error;
621 }
622
623 // Send EncryptedExtensions.
624 if (!ssl->method->init_message(ssl, cbb.get(), &body,
625 SSL3_MT_ENCRYPTED_EXTENSIONS) ||
626 !ssl_add_serverhello_tlsext(hs, &body) ||
627 !ssl_add_message_cbb(ssl, cbb.get())) {
628 return ssl_hs_error;
629 }
630
631 if (!ssl->s3->session_reused) {
632 // Determine whether to request a client certificate.
633 hs->cert_request = !!(hs->config->verify_mode & SSL_VERIFY_PEER);
634 // Only request a certificate if Channel ID isn't negotiated.
635 if ((hs->config->verify_mode & SSL_VERIFY_PEER_IF_NO_OBC) &&
636 ssl->s3->channel_id_valid) {
637 hs->cert_request = false;
638 }
639 }
640
641 // Send a CertificateRequest, if necessary.
642 if (hs->cert_request) {
643 CBB cert_request_extensions, sigalg_contents, sigalgs_cbb;
644 if (!ssl->method->init_message(ssl, cbb.get(), &body,
645 SSL3_MT_CERTIFICATE_REQUEST) ||
646 !CBB_add_u8(&body, 0 /* no certificate_request_context. */) ||
647 !CBB_add_u16_length_prefixed(&body, &cert_request_extensions) ||
648 !CBB_add_u16(&cert_request_extensions,
649 TLSEXT_TYPE_signature_algorithms) ||
650 !CBB_add_u16_length_prefixed(&cert_request_extensions,
651 &sigalg_contents) ||
652 !CBB_add_u16_length_prefixed(&sigalg_contents, &sigalgs_cbb) ||
653 !tls12_add_verify_sigalgs(ssl, &sigalgs_cbb,
654 false /* online signature */)) {
655 return ssl_hs_error;
656 }
657
658 if (tls12_has_different_verify_sigalgs_for_certs(ssl)) {
659 if (!CBB_add_u16(&cert_request_extensions,
660 TLSEXT_TYPE_signature_algorithms_cert) ||
661 !CBB_add_u16_length_prefixed(&cert_request_extensions,
662 &sigalg_contents) ||
663 !CBB_add_u16_length_prefixed(&sigalg_contents, &sigalgs_cbb) ||
664 !tls12_add_verify_sigalgs(ssl, &sigalgs_cbb, true /* certs */)) {
665 return ssl_hs_error;
666 }
667 }
668
669 if (ssl_has_client_CAs(hs->config)) {
670 CBB ca_contents;
671 if (!CBB_add_u16(&cert_request_extensions,
672 TLSEXT_TYPE_certificate_authorities) ||
673 !CBB_add_u16_length_prefixed(&cert_request_extensions,
674 &ca_contents) ||
675 !ssl_add_client_CA_list(hs, &ca_contents) ||
676 !CBB_flush(&cert_request_extensions)) {
677 return ssl_hs_error;
678 }
679 }
680
681 if (!ssl_add_message_cbb(ssl, cbb.get())) {
682 return ssl_hs_error;
683 }
684 }
685
686 // Send the server Certificate message, if necessary.
687 if (!ssl->s3->session_reused) {
688 if (!ssl_has_certificate(hs)) {
689 OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CERTIFICATE_SET);
690 return ssl_hs_error;
691 }
692
693 if (!tls13_add_certificate(hs)) {
694 return ssl_hs_error;
695 }
696
697 hs->tls13_state = state_send_server_certificate_verify;
698 return ssl_hs_ok;
699 }
700
701 hs->tls13_state = state_send_server_finished;
702 return ssl_hs_ok;
703 }
704
do_send_server_certificate_verify(SSL_HANDSHAKE * hs)705 static enum ssl_hs_wait_t do_send_server_certificate_verify(SSL_HANDSHAKE *hs) {
706 switch (tls13_add_certificate_verify(hs)) {
707 case ssl_private_key_success:
708 hs->tls13_state = state_send_server_finished;
709 return ssl_hs_ok;
710
711 case ssl_private_key_retry:
712 hs->tls13_state = state_send_server_certificate_verify;
713 return ssl_hs_private_key_operation;
714
715 case ssl_private_key_failure:
716 return ssl_hs_error;
717 }
718
719 assert(0);
720 return ssl_hs_error;
721 }
722
do_send_server_finished(SSL_HANDSHAKE * hs)723 static enum ssl_hs_wait_t do_send_server_finished(SSL_HANDSHAKE *hs) {
724 SSL *const ssl = hs->ssl;
725 if (!tls13_add_finished(hs) ||
726 // Update the secret to the master secret and derive traffic keys.
727 !tls13_advance_key_schedule(hs, kZeroes, hs->hash_len) ||
728 !tls13_derive_application_secrets(hs) ||
729 !tls13_set_traffic_key(ssl, ssl_encryption_application, evp_aead_seal,
730 hs->server_traffic_secret_0, hs->hash_len)) {
731 return ssl_hs_error;
732 }
733
734 if (ssl->s3->early_data_accepted) {
735 // If accepting 0-RTT, we send tickets half-RTT. This gets the tickets on
736 // the wire sooner and also avoids triggering a write on |SSL_read| when
737 // processing the client Finished. This requires computing the client
738 // Finished early. See RFC 8446, section 4.6.1.
739 static const uint8_t kEndOfEarlyData[4] = {SSL3_MT_END_OF_EARLY_DATA, 0,
740 0, 0};
741 if (!hs->transcript.Update(kEndOfEarlyData)) {
742 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
743 return ssl_hs_error;
744 }
745
746 size_t finished_len;
747 if (!tls13_finished_mac(hs, hs->expected_client_finished, &finished_len,
748 false /* client */)) {
749 return ssl_hs_error;
750 }
751
752 if (finished_len != hs->hash_len) {
753 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
754 return ssl_hs_error;
755 }
756
757 // Feed the predicted Finished into the transcript. This allows us to derive
758 // the resumption secret early and send half-RTT tickets.
759 //
760 // TODO(davidben): This will need to be updated for DTLS 1.3.
761 assert(!SSL_is_dtls(hs->ssl));
762 assert(hs->hash_len <= 0xff);
763 uint8_t header[4] = {SSL3_MT_FINISHED, 0, 0,
764 static_cast<uint8_t>(hs->hash_len)};
765 bool unused_sent_tickets;
766 if (!hs->transcript.Update(header) ||
767 !hs->transcript.Update(
768 MakeConstSpan(hs->expected_client_finished, hs->hash_len)) ||
769 !tls13_derive_resumption_secret(hs) ||
770 !add_new_session_tickets(hs, &unused_sent_tickets)) {
771 return ssl_hs_error;
772 }
773 }
774
775 hs->tls13_state = state_read_second_client_flight;
776 return ssl_hs_flush;
777 }
778
do_read_second_client_flight(SSL_HANDSHAKE * hs)779 static enum ssl_hs_wait_t do_read_second_client_flight(SSL_HANDSHAKE *hs) {
780 SSL *const ssl = hs->ssl;
781 if (ssl->s3->early_data_accepted) {
782 if (!tls13_set_traffic_key(ssl, ssl_encryption_early_data, evp_aead_open,
783 hs->early_traffic_secret, hs->hash_len)) {
784 return ssl_hs_error;
785 }
786 hs->can_early_write = true;
787 hs->can_early_read = true;
788 hs->in_early_data = true;
789 }
790 hs->tls13_state = state_process_end_of_early_data;
791 return ssl->s3->early_data_accepted ? ssl_hs_read_end_of_early_data
792 : ssl_hs_ok;
793 }
794
do_process_end_of_early_data(SSL_HANDSHAKE * hs)795 static enum ssl_hs_wait_t do_process_end_of_early_data(SSL_HANDSHAKE *hs) {
796 SSL *const ssl = hs->ssl;
797 if (hs->early_data_offered) {
798 // If early data was not accepted, the EndOfEarlyData and ChangeCipherSpec
799 // message will be in the discarded early data.
800 if (hs->ssl->s3->early_data_accepted) {
801 SSLMessage msg;
802 if (!ssl->method->get_message(ssl, &msg)) {
803 return ssl_hs_read_message;
804 }
805
806 if (!ssl_check_message_type(ssl, msg, SSL3_MT_END_OF_EARLY_DATA)) {
807 return ssl_hs_error;
808 }
809 if (CBS_len(&msg.body) != 0) {
810 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
811 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
812 return ssl_hs_error;
813 }
814 ssl->method->next_message(ssl);
815 }
816 }
817 if (!tls13_set_traffic_key(ssl, ssl_encryption_handshake, evp_aead_open,
818 hs->client_handshake_secret, hs->hash_len)) {
819 return ssl_hs_error;
820 }
821 hs->tls13_state = ssl->s3->early_data_accepted
822 ? state_read_client_finished
823 : state_read_client_certificate;
824 return ssl_hs_ok;
825 }
826
do_read_client_certificate(SSL_HANDSHAKE * hs)827 static enum ssl_hs_wait_t do_read_client_certificate(SSL_HANDSHAKE *hs) {
828 SSL *const ssl = hs->ssl;
829 if (!hs->cert_request) {
830 // OpenSSL returns X509_V_OK when no certificates are requested. This is
831 // classed by them as a bug, but it's assumed by at least NGINX.
832 hs->new_session->verify_result = X509_V_OK;
833
834 // Skip this state.
835 hs->tls13_state = state_read_channel_id;
836 return ssl_hs_ok;
837 }
838
839 const bool allow_anonymous =
840 (hs->config->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) == 0;
841 SSLMessage msg;
842 if (!ssl->method->get_message(ssl, &msg)) {
843 return ssl_hs_read_message;
844 }
845 if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE) ||
846 !tls13_process_certificate(hs, msg, allow_anonymous) ||
847 !ssl_hash_message(hs, msg)) {
848 return ssl_hs_error;
849 }
850
851 ssl->method->next_message(ssl);
852 hs->tls13_state = state_read_client_certificate_verify;
853 return ssl_hs_ok;
854 }
855
do_read_client_certificate_verify(SSL_HANDSHAKE * hs)856 static enum ssl_hs_wait_t do_read_client_certificate_verify(
857 SSL_HANDSHAKE *hs) {
858 SSL *const ssl = hs->ssl;
859 if (sk_CRYPTO_BUFFER_num(hs->new_session->certs.get()) == 0) {
860 // Skip this state.
861 hs->tls13_state = state_read_channel_id;
862 return ssl_hs_ok;
863 }
864
865 SSLMessage msg;
866 if (!ssl->method->get_message(ssl, &msg)) {
867 return ssl_hs_read_message;
868 }
869
870 switch (ssl_verify_peer_cert(hs)) {
871 case ssl_verify_ok:
872 break;
873 case ssl_verify_invalid:
874 return ssl_hs_error;
875 case ssl_verify_retry:
876 hs->tls13_state = state_read_client_certificate_verify;
877 return ssl_hs_certificate_verify;
878 }
879
880 if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE_VERIFY) ||
881 !tls13_process_certificate_verify(hs, msg) ||
882 !ssl_hash_message(hs, msg)) {
883 return ssl_hs_error;
884 }
885
886 ssl->method->next_message(ssl);
887 hs->tls13_state = state_read_channel_id;
888 return ssl_hs_ok;
889 }
890
do_read_channel_id(SSL_HANDSHAKE * hs)891 static enum ssl_hs_wait_t do_read_channel_id(SSL_HANDSHAKE *hs) {
892 SSL *const ssl = hs->ssl;
893 if (!ssl->s3->channel_id_valid) {
894 hs->tls13_state = state_read_client_finished;
895 return ssl_hs_ok;
896 }
897
898 SSLMessage msg;
899 if (!ssl->method->get_message(ssl, &msg)) {
900 return ssl_hs_read_message;
901 }
902 if (!ssl_check_message_type(ssl, msg, SSL3_MT_CHANNEL_ID) ||
903 !tls1_verify_channel_id(hs, msg) ||
904 !ssl_hash_message(hs, msg)) {
905 return ssl_hs_error;
906 }
907
908 ssl->method->next_message(ssl);
909 hs->tls13_state = state_read_client_finished;
910 return ssl_hs_ok;
911 }
912
do_read_client_finished(SSL_HANDSHAKE * hs)913 static enum ssl_hs_wait_t do_read_client_finished(SSL_HANDSHAKE *hs) {
914 SSL *const ssl = hs->ssl;
915 SSLMessage msg;
916 if (!ssl->method->get_message(ssl, &msg)) {
917 return ssl_hs_read_message;
918 }
919 if (!ssl_check_message_type(ssl, msg, SSL3_MT_FINISHED) ||
920 // If early data was accepted, we've already computed the client Finished
921 // and derived the resumption secret.
922 !tls13_process_finished(hs, msg, ssl->s3->early_data_accepted) ||
923 // evp_aead_seal keys have already been switched.
924 !tls13_set_traffic_key(ssl, ssl_encryption_application, evp_aead_open,
925 hs->client_traffic_secret_0, hs->hash_len)) {
926 return ssl_hs_error;
927 }
928
929 if (!ssl->s3->early_data_accepted) {
930 if (!ssl_hash_message(hs, msg) ||
931 !tls13_derive_resumption_secret(hs)) {
932 return ssl_hs_error;
933 }
934
935 // We send post-handshake tickets as part of the handshake in 1-RTT.
936 hs->tls13_state = state_send_new_session_ticket;
937 } else {
938 // We already sent half-RTT tickets.
939 hs->tls13_state = state_done;
940 }
941
942 ssl->method->next_message(ssl);
943 return ssl_hs_ok;
944 }
945
do_send_new_session_ticket(SSL_HANDSHAKE * hs)946 static enum ssl_hs_wait_t do_send_new_session_ticket(SSL_HANDSHAKE *hs) {
947 bool sent_tickets;
948 if (!add_new_session_tickets(hs, &sent_tickets)) {
949 return ssl_hs_error;
950 }
951
952 hs->tls13_state = state_done;
953 return sent_tickets ? ssl_hs_flush : ssl_hs_ok;
954 }
955
tls13_server_handshake(SSL_HANDSHAKE * hs)956 enum ssl_hs_wait_t tls13_server_handshake(SSL_HANDSHAKE *hs) {
957 while (hs->tls13_state != state_done) {
958 enum ssl_hs_wait_t ret = ssl_hs_error;
959 enum server_hs_state_t state =
960 static_cast<enum server_hs_state_t>(hs->tls13_state);
961 switch (state) {
962 case state_select_parameters:
963 ret = do_select_parameters(hs);
964 break;
965 case state_select_session:
966 ret = do_select_session(hs);
967 break;
968 case state_send_hello_retry_request:
969 ret = do_send_hello_retry_request(hs);
970 break;
971 case state_read_second_client_hello:
972 ret = do_read_second_client_hello(hs);
973 break;
974 case state_send_server_hello:
975 ret = do_send_server_hello(hs);
976 break;
977 case state_send_server_certificate_verify:
978 ret = do_send_server_certificate_verify(hs);
979 break;
980 case state_send_server_finished:
981 ret = do_send_server_finished(hs);
982 break;
983 case state_read_second_client_flight:
984 ret = do_read_second_client_flight(hs);
985 break;
986 case state_process_end_of_early_data:
987 ret = do_process_end_of_early_data(hs);
988 break;
989 case state_read_client_certificate:
990 ret = do_read_client_certificate(hs);
991 break;
992 case state_read_client_certificate_verify:
993 ret = do_read_client_certificate_verify(hs);
994 break;
995 case state_read_channel_id:
996 ret = do_read_channel_id(hs);
997 break;
998 case state_read_client_finished:
999 ret = do_read_client_finished(hs);
1000 break;
1001 case state_send_new_session_ticket:
1002 ret = do_send_new_session_ticket(hs);
1003 break;
1004 case state_done:
1005 ret = ssl_hs_ok;
1006 break;
1007 }
1008
1009 if (hs->tls13_state != state) {
1010 ssl_do_info_callback(hs->ssl, SSL_CB_ACCEPT_LOOP, 1);
1011 }
1012
1013 if (ret != ssl_hs_ok) {
1014 return ret;
1015 }
1016 }
1017
1018 return ssl_hs_ok;
1019 }
1020
tls13_server_handshake_state(SSL_HANDSHAKE * hs)1021 const char *tls13_server_handshake_state(SSL_HANDSHAKE *hs) {
1022 enum server_hs_state_t state =
1023 static_cast<enum server_hs_state_t>(hs->tls13_state);
1024 switch (state) {
1025 case state_select_parameters:
1026 return "TLS 1.3 server select_parameters";
1027 case state_select_session:
1028 return "TLS 1.3 server select_session";
1029 case state_send_hello_retry_request:
1030 return "TLS 1.3 server send_hello_retry_request";
1031 case state_read_second_client_hello:
1032 return "TLS 1.3 server read_second_client_hello";
1033 case state_send_server_hello:
1034 return "TLS 1.3 server send_server_hello";
1035 case state_send_server_certificate_verify:
1036 return "TLS 1.3 server send_server_certificate_verify";
1037 case state_send_server_finished:
1038 return "TLS 1.3 server send_server_finished";
1039 case state_read_second_client_flight:
1040 return "TLS 1.3 server read_second_client_flight";
1041 case state_process_end_of_early_data:
1042 return "TLS 1.3 server process_end_of_early_data";
1043 case state_read_client_certificate:
1044 return "TLS 1.3 server read_client_certificate";
1045 case state_read_client_certificate_verify:
1046 return "TLS 1.3 server read_client_certificate_verify";
1047 case state_read_channel_id:
1048 return "TLS 1.3 server read_channel_id";
1049 case state_read_client_finished:
1050 return "TLS 1.3 server read_client_finished";
1051 case state_send_new_session_ticket:
1052 return "TLS 1.3 server send_new_session_ticket";
1053 case state_done:
1054 return "TLS 1.3 server done";
1055 }
1056
1057 return "TLS 1.3 server unknown";
1058 }
1059
1060 BSSL_NAMESPACE_END
1061