1/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2 * All rights reserved.
3 *
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
7 *
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to.  The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14 *
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
21 *
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
24 * are met:
25 * 1. Redistributions of source code must retain the copyright
26 *    notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 *    notice, this list of conditions and the following disclaimer in the
29 *    documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 *    must display the following acknowledgement:
32 *    "This product includes cryptographic software written by
33 *     Eric Young (eay@cryptsoft.com)"
34 *    The word 'cryptographic' can be left out if the rouines from the library
35 *    being used are not cryptographic related :-).
36 * 4. If you include any Windows specific code (or a derivative thereof) from
37 *    the apps directory (application code) you must include an acknowledgement:
38 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39 *
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50 * SUCH DAMAGE.
51 *
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed.  i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.]
56 */
57/* ====================================================================
58 * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
59 *
60 * Redistribution and use in source and binary forms, with or without
61 * modification, are permitted provided that the following conditions
62 * are met:
63 *
64 * 1. Redistributions of source code must retain the above copyright
65 *    notice, this list of conditions and the following disclaimer.
66 *
67 * 2. Redistributions in binary form must reproduce the above copyright
68 *    notice, this list of conditions and the following disclaimer in
69 *    the documentation and/or other materials provided with the
70 *    distribution.
71 *
72 * 3. All advertising materials mentioning features or use of this
73 *    software must display the following acknowledgment:
74 *    "This product includes software developed by the OpenSSL Project
75 *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76 *
77 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78 *    endorse or promote products derived from this software without
79 *    prior written permission. For written permission, please contact
80 *    openssl-core@openssl.org.
81 *
82 * 5. Products derived from this software may not be called "OpenSSL"
83 *    nor may "OpenSSL" appear in their names without prior written
84 *    permission of the OpenSSL Project.
85 *
86 * 6. Redistributions of any form whatsoever must retain the following
87 *    acknowledgment:
88 *    "This product includes software developed by the OpenSSL Project
89 *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90 *
91 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102 * OF THE POSSIBILITY OF SUCH DAMAGE.
103 * ====================================================================
104 *
105 * This product includes cryptographic software written by Eric Young
106 * (eay@cryptsoft.com).  This product includes software written by Tim
107 * Hudson (tjh@cryptsoft.com).
108 *
109 */
110/* ====================================================================
111 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
112 *
113 * Portions of the attached software ("Contribution") are developed by
114 * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
115 *
116 * The Contribution is licensed pursuant to the OpenSSL open source
117 * license provided above.
118 *
119 * ECC cipher suite support in OpenSSL originally written by
120 * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
121 *
122 */
123/* ====================================================================
124 * Copyright 2005 Nokia. All rights reserved.
125 *
126 * The portions of the attached software ("Contribution") is developed by
127 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
128 * license.
129 *
130 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
131 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
132 * support (see RFC 4279) to OpenSSL.
133 *
134 * No patent licenses or other rights except those expressly stated in
135 * the OpenSSL open source license shall be deemed granted or received
136 * expressly, by implication, estoppel, or otherwise.
137 *
138 * No assurances are provided by Nokia that the Contribution does not
139 * infringe the patent or other intellectual property rights of any third
140 * party or that the license provides you with all the necessary rights
141 * to make use of the Contribution.
142 *
143 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
144 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
145 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
146 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
147 * OTHERWISE. */
148
149#include <openssl/ssl.h>
150
151#include <assert.h>
152#include <string.h>
153
154#include <openssl/bn.h>
155#include <openssl/buf.h>
156#include <openssl/bytestring.h>
157#include <openssl/cipher.h>
158#include <openssl/ec.h>
159#include <openssl/ecdsa.h>
160#include <openssl/err.h>
161#include <openssl/evp.h>
162#include <openssl/hmac.h>
163#include <openssl/md5.h>
164#include <openssl/mem.h>
165#include <openssl/nid.h>
166#include <openssl/rand.h>
167#include <openssl/x509.h>
168
169#include "internal.h"
170#include "../crypto/internal.h"
171
172
173namespace bssl {
174
175enum ssl_server_hs_state_t {
176  state_start_accept = 0,
177  state_read_client_hello,
178  state_select_certificate,
179  state_tls13,
180  state_select_parameters,
181  state_send_server_hello,
182  state_send_server_certificate,
183  state_send_server_key_exchange,
184  state_send_server_hello_done,
185  state_read_client_certificate,
186  state_verify_client_certificate,
187  state_read_client_key_exchange,
188  state_read_client_certificate_verify,
189  state_read_change_cipher_spec,
190  state_process_change_cipher_spec,
191  state_read_next_proto,
192  state_read_channel_id,
193  state_read_client_finished,
194  state_send_server_finished,
195  state_finish_server_handshake,
196  state_done,
197};
198
199int ssl_client_cipher_list_contains_cipher(const SSL_CLIENT_HELLO *client_hello,
200                                           uint16_t id) {
201  CBS cipher_suites;
202  CBS_init(&cipher_suites, client_hello->cipher_suites,
203           client_hello->cipher_suites_len);
204
205  while (CBS_len(&cipher_suites) > 0) {
206    uint16_t got_id;
207    if (!CBS_get_u16(&cipher_suites, &got_id)) {
208      return 0;
209    }
210
211    if (got_id == id) {
212      return 1;
213    }
214  }
215
216  return 0;
217}
218
219static int negotiate_version(SSL_HANDSHAKE *hs, uint8_t *out_alert,
220                             const SSL_CLIENT_HELLO *client_hello) {
221  SSL *const ssl = hs->ssl;
222  assert(!ssl->s3->have_version);
223  CBS supported_versions, versions;
224  if (ssl_client_hello_get_extension(client_hello, &supported_versions,
225                                     TLSEXT_TYPE_supported_versions)) {
226    if (!CBS_get_u8_length_prefixed(&supported_versions, &versions) ||
227        CBS_len(&supported_versions) != 0 ||
228        CBS_len(&versions) == 0) {
229      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
230      *out_alert = SSL_AD_DECODE_ERROR;
231      return 0;
232    }
233  } else {
234    // Convert the ClientHello version to an equivalent supported_versions
235    // extension.
236    static const uint8_t kTLSVersions[] = {
237        0x03, 0x03,  // TLS 1.2
238        0x03, 0x02,  // TLS 1.1
239        0x03, 0x01,  // TLS 1
240        0x03, 0x00,  // SSL 3
241    };
242
243    static const uint8_t kDTLSVersions[] = {
244        0xfe, 0xfd,  // DTLS 1.2
245        0xfe, 0xff,  // DTLS 1.0
246    };
247
248    size_t versions_len = 0;
249    if (SSL_is_dtls(ssl)) {
250      if (client_hello->version <= DTLS1_2_VERSION) {
251        versions_len = 4;
252      } else if (client_hello->version <= DTLS1_VERSION) {
253        versions_len = 2;
254      }
255      CBS_init(&versions, kDTLSVersions + sizeof(kDTLSVersions) - versions_len,
256               versions_len);
257    } else {
258      if (client_hello->version >= TLS1_2_VERSION) {
259        versions_len = 8;
260      } else if (client_hello->version >= TLS1_1_VERSION) {
261        versions_len = 6;
262      } else if (client_hello->version >= TLS1_VERSION) {
263        versions_len = 4;
264      } else if (client_hello->version >= SSL3_VERSION) {
265        versions_len = 2;
266      }
267      CBS_init(&versions, kTLSVersions + sizeof(kTLSVersions) - versions_len,
268               versions_len);
269    }
270  }
271
272  if (!ssl_negotiate_version(hs, out_alert, &ssl->version, &versions)) {
273    return 0;
274  }
275
276  // At this point, the connection's version is known and |ssl->version| is
277  // fixed. Begin enforcing the record-layer version.
278  ssl->s3->have_version = true;
279  ssl->s3->aead_write_ctx->SetVersionIfNullCipher(ssl->version);
280
281  // Handle FALLBACK_SCSV.
282  if (ssl_client_cipher_list_contains_cipher(client_hello,
283                                             SSL3_CK_FALLBACK_SCSV & 0xffff) &&
284      ssl_protocol_version(ssl) < hs->max_version) {
285    OPENSSL_PUT_ERROR(SSL, SSL_R_INAPPROPRIATE_FALLBACK);
286    *out_alert = SSL3_AD_INAPPROPRIATE_FALLBACK;
287    return 0;
288  }
289
290  return 1;
291}
292
293static UniquePtr<STACK_OF(SSL_CIPHER)> ssl_parse_client_cipher_list(
294    const SSL_CLIENT_HELLO *client_hello) {
295  CBS cipher_suites;
296  CBS_init(&cipher_suites, client_hello->cipher_suites,
297           client_hello->cipher_suites_len);
298
299  UniquePtr<STACK_OF(SSL_CIPHER)> sk(sk_SSL_CIPHER_new_null());
300  if (!sk) {
301    OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
302    return nullptr;
303  }
304
305  while (CBS_len(&cipher_suites) > 0) {
306    uint16_t cipher_suite;
307
308    if (!CBS_get_u16(&cipher_suites, &cipher_suite)) {
309      OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
310      return nullptr;
311    }
312
313    const SSL_CIPHER *c = SSL_get_cipher_by_value(cipher_suite);
314    if (c != NULL && !sk_SSL_CIPHER_push(sk.get(), c)) {
315      OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
316      return nullptr;
317    }
318  }
319
320  return sk;
321}
322
323// ssl_get_compatible_server_ciphers determines the key exchange and
324// authentication cipher suite masks compatible with the server configuration
325// and current ClientHello parameters of |hs|. It sets |*out_mask_k| to the key
326// exchange mask and |*out_mask_a| to the authentication mask.
327static void ssl_get_compatible_server_ciphers(SSL_HANDSHAKE *hs,
328                                              uint32_t *out_mask_k,
329                                              uint32_t *out_mask_a) {
330  SSL *const ssl = hs->ssl;
331  uint32_t mask_k = 0;
332  uint32_t mask_a = 0;
333
334  if (ssl_has_certificate(ssl)) {
335    mask_a |= ssl_cipher_auth_mask_for_key(hs->local_pubkey.get());
336    if (EVP_PKEY_id(hs->local_pubkey.get()) == EVP_PKEY_RSA) {
337      mask_k |= SSL_kRSA;
338    }
339  }
340
341  // Check for a shared group to consider ECDHE ciphers.
342  uint16_t unused;
343  if (tls1_get_shared_group(hs, &unused)) {
344    mask_k |= SSL_kECDHE;
345  }
346
347  // PSK requires a server callback.
348  if (ssl->psk_server_callback != NULL) {
349    mask_k |= SSL_kPSK;
350    mask_a |= SSL_aPSK;
351  }
352
353  *out_mask_k = mask_k;
354  *out_mask_a = mask_a;
355}
356
357static const SSL_CIPHER *ssl3_choose_cipher(
358    SSL_HANDSHAKE *hs, const SSL_CLIENT_HELLO *client_hello,
359    const struct ssl_cipher_preference_list_st *server_pref) {
360  SSL *const ssl = hs->ssl;
361  STACK_OF(SSL_CIPHER) *prio, *allow;
362  // in_group_flags will either be NULL, or will point to an array of bytes
363  // which indicate equal-preference groups in the |prio| stack. See the
364  // comment about |in_group_flags| in the |ssl_cipher_preference_list_st|
365  // struct.
366  const uint8_t *in_group_flags;
367  // group_min contains the minimal index so far found in a group, or -1 if no
368  // such value exists yet.
369  int group_min = -1;
370
371  UniquePtr<STACK_OF(SSL_CIPHER)> client_pref =
372      ssl_parse_client_cipher_list(client_hello);
373  if (!client_pref) {
374    return nullptr;
375  }
376
377  if (ssl->options & SSL_OP_CIPHER_SERVER_PREFERENCE) {
378    prio = server_pref->ciphers;
379    in_group_flags = server_pref->in_group_flags;
380    allow = client_pref.get();
381  } else {
382    prio = client_pref.get();
383    in_group_flags = NULL;
384    allow = server_pref->ciphers;
385  }
386
387  uint32_t mask_k, mask_a;
388  ssl_get_compatible_server_ciphers(hs, &mask_k, &mask_a);
389
390  for (size_t i = 0; i < sk_SSL_CIPHER_num(prio); i++) {
391    const SSL_CIPHER *c = sk_SSL_CIPHER_value(prio, i);
392
393    size_t cipher_index;
394    if (// Check if the cipher is supported for the current version.
395        SSL_CIPHER_get_min_version(c) <= ssl_protocol_version(ssl) &&
396        ssl_protocol_version(ssl) <= SSL_CIPHER_get_max_version(c) &&
397        // Check the cipher is supported for the server configuration.
398        (c->algorithm_mkey & mask_k) &&
399        (c->algorithm_auth & mask_a) &&
400        // Check the cipher is in the |allow| list.
401        sk_SSL_CIPHER_find(allow, &cipher_index, c)) {
402      if (in_group_flags != NULL && in_group_flags[i] == 1) {
403        // This element of |prio| is in a group. Update the minimum index found
404        // so far and continue looking.
405        if (group_min == -1 || (size_t)group_min > cipher_index) {
406          group_min = cipher_index;
407        }
408      } else {
409        if (group_min != -1 && (size_t)group_min < cipher_index) {
410          cipher_index = group_min;
411        }
412        return sk_SSL_CIPHER_value(allow, cipher_index);
413      }
414    }
415
416    if (in_group_flags != NULL && in_group_flags[i] == 0 && group_min != -1) {
417      // We are about to leave a group, but we found a match in it, so that's
418      // our answer.
419      return sk_SSL_CIPHER_value(allow, group_min);
420    }
421  }
422
423  return nullptr;
424}
425
426static enum ssl_hs_wait_t do_start_accept(SSL_HANDSHAKE *hs) {
427  ssl_do_info_callback(hs->ssl, SSL_CB_HANDSHAKE_START, 1);
428  hs->state = state_read_client_hello;
429  return ssl_hs_ok;
430}
431
432static enum ssl_hs_wait_t do_read_client_hello(SSL_HANDSHAKE *hs) {
433  SSL *const ssl = hs->ssl;
434
435  SSLMessage msg;
436  if (!ssl->method->get_message(ssl, &msg)) {
437    return ssl_hs_read_message;
438  }
439
440  if (!ssl_check_message_type(ssl, msg, SSL3_MT_CLIENT_HELLO)) {
441    return ssl_hs_error;
442  }
443
444  if (ssl->handoff) {
445    return ssl_hs_handoff;
446  }
447
448  SSL_CLIENT_HELLO client_hello;
449  if (!ssl_client_hello_init(ssl, &client_hello, msg)) {
450    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
451    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
452    return ssl_hs_error;
453  }
454
455  // Run the early callback.
456  if (ssl->ctx->select_certificate_cb != NULL) {
457    switch (ssl->ctx->select_certificate_cb(&client_hello)) {
458      case ssl_select_cert_retry:
459        return ssl_hs_certificate_selection_pending;
460
461      case ssl_select_cert_error:
462        // Connection rejected.
463        OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
464        ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
465        return ssl_hs_error;
466
467      default:
468        /* fallthrough */;
469    }
470  }
471
472  // Freeze the version range after the early callback.
473  if (!ssl_get_version_range(ssl, &hs->min_version, &hs->max_version)) {
474    return ssl_hs_error;
475  }
476
477  uint8_t alert = SSL_AD_DECODE_ERROR;
478  if (!negotiate_version(hs, &alert, &client_hello)) {
479    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
480    return ssl_hs_error;
481  }
482
483  hs->client_version = client_hello.version;
484  if (client_hello.random_len != SSL3_RANDOM_SIZE) {
485    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
486    return ssl_hs_error;
487  }
488  OPENSSL_memcpy(ssl->s3->client_random, client_hello.random,
489                 client_hello.random_len);
490
491  // Only null compression is supported. TLS 1.3 further requires the peer
492  // advertise no other compression.
493  if (OPENSSL_memchr(client_hello.compression_methods, 0,
494                     client_hello.compression_methods_len) == NULL ||
495      (ssl_protocol_version(ssl) >= TLS1_3_VERSION &&
496       client_hello.compression_methods_len != 1)) {
497    OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_COMPRESSION_LIST);
498    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
499    return ssl_hs_error;
500  }
501
502  // TLS extensions.
503  if (!ssl_parse_clienthello_tlsext(hs, &client_hello)) {
504    OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
505    return ssl_hs_error;
506  }
507
508  hs->state = state_select_certificate;
509  return ssl_hs_ok;
510}
511
512static enum ssl_hs_wait_t do_select_certificate(SSL_HANDSHAKE *hs) {
513  SSL *const ssl = hs->ssl;
514
515  SSLMessage msg;
516  if (!ssl->method->get_message(ssl, &msg)) {
517    return ssl_hs_read_message;
518  }
519
520  // Call |cert_cb| to update server certificates if required.
521  if (ssl->cert->cert_cb != NULL) {
522    int rv = ssl->cert->cert_cb(ssl, ssl->cert->cert_cb_arg);
523    if (rv == 0) {
524      OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_CB_ERROR);
525      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
526      return ssl_hs_error;
527    }
528    if (rv < 0) {
529      return ssl_hs_x509_lookup;
530    }
531  }
532
533  if (!ssl_on_certificate_selected(hs)) {
534    return ssl_hs_error;
535  }
536
537  if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
538    // Jump to the TLS 1.3 state machine.
539    hs->state = state_tls13;
540    return ssl_hs_ok;
541  }
542
543  SSL_CLIENT_HELLO client_hello;
544  if (!ssl_client_hello_init(ssl, &client_hello, msg)) {
545    return ssl_hs_error;
546  }
547
548  // Negotiate the cipher suite. This must be done after |cert_cb| so the
549  // certificate is finalized.
550  hs->new_cipher =
551      ssl3_choose_cipher(hs, &client_hello, ssl_get_cipher_preferences(ssl));
552  if (hs->new_cipher == NULL) {
553    OPENSSL_PUT_ERROR(SSL, SSL_R_NO_SHARED_CIPHER);
554    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
555    return ssl_hs_error;
556  }
557
558  hs->state = state_select_parameters;
559  return ssl_hs_ok;
560}
561
562static enum ssl_hs_wait_t do_tls13(SSL_HANDSHAKE *hs) {
563  enum ssl_hs_wait_t wait = tls13_server_handshake(hs);
564  if (wait == ssl_hs_ok) {
565    hs->state = state_finish_server_handshake;
566    return ssl_hs_ok;
567  }
568
569  return wait;
570}
571
572static enum ssl_hs_wait_t do_select_parameters(SSL_HANDSHAKE *hs) {
573  SSL *const ssl = hs->ssl;
574
575  SSLMessage msg;
576  if (!ssl->method->get_message(ssl, &msg)) {
577    return ssl_hs_read_message;
578  }
579
580  SSL_CLIENT_HELLO client_hello;
581  if (!ssl_client_hello_init(ssl, &client_hello, msg)) {
582    return ssl_hs_error;
583  }
584
585  // Determine whether we are doing session resumption.
586  UniquePtr<SSL_SESSION> session;
587  bool tickets_supported = false, renew_ticket = false;
588  enum ssl_hs_wait_t wait = ssl_get_prev_session(
589      ssl, &session, &tickets_supported, &renew_ticket, &client_hello);
590  if (wait != ssl_hs_ok) {
591    return wait;
592  }
593
594  if (session) {
595    if (session->extended_master_secret && !hs->extended_master_secret) {
596      // A ClientHello without EMS that attempts to resume a session with EMS
597      // is fatal to the connection.
598      OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
599      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
600      return ssl_hs_error;
601    }
602
603    if (!ssl_session_is_resumable(hs, session.get()) ||
604        // If the client offers the EMS extension, but the previous session
605        // didn't use it, then negotiate a new session.
606        hs->extended_master_secret != session->extended_master_secret) {
607      session.reset();
608    }
609  }
610
611  if (session) {
612    // Use the old session.
613    hs->ticket_expected = renew_ticket;
614    ssl->session = session.release();
615    ssl->s3->session_reused = true;
616  } else {
617    hs->ticket_expected = tickets_supported;
618    ssl_set_session(ssl, NULL);
619    if (!ssl_get_new_session(hs, 1 /* server */)) {
620      return ssl_hs_error;
621    }
622
623    // Clear the session ID if we want the session to be single-use.
624    if (!(ssl->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)) {
625      hs->new_session->session_id_length = 0;
626    }
627  }
628
629  if (ssl->ctx->dos_protection_cb != NULL &&
630      ssl->ctx->dos_protection_cb(&client_hello) == 0) {
631    // Connection rejected for DOS reasons.
632    OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
633    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
634    return ssl_hs_error;
635  }
636
637  if (ssl->session == NULL) {
638    hs->new_session->cipher = hs->new_cipher;
639
640    // Determine whether to request a client certificate.
641    hs->cert_request = !!(ssl->verify_mode & SSL_VERIFY_PEER);
642    // Only request a certificate if Channel ID isn't negotiated.
643    if ((ssl->verify_mode & SSL_VERIFY_PEER_IF_NO_OBC) &&
644        ssl->s3->tlsext_channel_id_valid) {
645      hs->cert_request = false;
646    }
647    // CertificateRequest may only be sent in certificate-based ciphers.
648    if (!ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
649      hs->cert_request = false;
650    }
651
652    if (!hs->cert_request) {
653      // OpenSSL returns X509_V_OK when no certificates are requested. This is
654      // classed by them as a bug, but it's assumed by at least NGINX.
655      hs->new_session->verify_result = X509_V_OK;
656    }
657  }
658
659  // HTTP/2 negotiation depends on the cipher suite, so ALPN negotiation was
660  // deferred. Complete it now.
661  uint8_t alert = SSL_AD_DECODE_ERROR;
662  if (!ssl_negotiate_alpn(hs, &alert, &client_hello)) {
663    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
664    return ssl_hs_error;
665  }
666
667  // Now that all parameters are known, initialize the handshake hash and hash
668  // the ClientHello.
669  if (!hs->transcript.InitHash(ssl_protocol_version(ssl), hs->new_cipher) ||
670      !ssl_hash_message(hs, msg)) {
671    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
672    return ssl_hs_error;
673  }
674
675  // Release the handshake buffer if client authentication isn't required.
676  if (!hs->cert_request) {
677    hs->transcript.FreeBuffer();
678  }
679
680  ssl->method->next_message(ssl);
681
682  hs->state = state_send_server_hello;
683  return ssl_hs_ok;
684}
685
686static enum ssl_hs_wait_t do_send_server_hello(SSL_HANDSHAKE *hs) {
687  SSL *const ssl = hs->ssl;
688
689  // We only accept ChannelIDs on connections with ECDHE in order to avoid a
690  // known attack while we fix ChannelID itself.
691  if (ssl->s3->tlsext_channel_id_valid &&
692      (hs->new_cipher->algorithm_mkey & SSL_kECDHE) == 0) {
693    ssl->s3->tlsext_channel_id_valid = false;
694  }
695
696  // If this is a resumption and the original handshake didn't support
697  // ChannelID then we didn't record the original handshake hashes in the
698  // session and so cannot resume with ChannelIDs.
699  if (ssl->session != NULL &&
700      ssl->session->original_handshake_hash_len == 0) {
701    ssl->s3->tlsext_channel_id_valid = false;
702  }
703
704  struct OPENSSL_timeval now;
705  ssl_get_current_time(ssl, &now);
706  ssl->s3->server_random[0] = now.tv_sec >> 24;
707  ssl->s3->server_random[1] = now.tv_sec >> 16;
708  ssl->s3->server_random[2] = now.tv_sec >> 8;
709  ssl->s3->server_random[3] = now.tv_sec;
710  if (!RAND_bytes(ssl->s3->server_random + 4, SSL3_RANDOM_SIZE - 4)) {
711    return ssl_hs_error;
712  }
713
714  // Implement the TLS 1.3 anti-downgrade feature, but with a different value.
715  //
716  // For draft TLS 1.3 versions, it is not safe to deploy this feature. However,
717  // some TLS terminators are non-compliant and copy the origin server's value,
718  // so we wish to measure eventual compatibility impact.
719  if (hs->max_version >= TLS1_3_VERSION) {
720    OPENSSL_memcpy(ssl->s3->server_random + SSL3_RANDOM_SIZE -
721                       sizeof(kDraftDowngradeRandom),
722                   kDraftDowngradeRandom, sizeof(kDraftDowngradeRandom));
723  }
724
725  const SSL_SESSION *session = hs->new_session.get();
726  if (ssl->session != NULL) {
727    session = ssl->session;
728  }
729
730  ScopedCBB cbb;
731  CBB body, session_id;
732  if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_SERVER_HELLO) ||
733      !CBB_add_u16(&body, ssl->version) ||
734      !CBB_add_bytes(&body, ssl->s3->server_random, SSL3_RANDOM_SIZE) ||
735      !CBB_add_u8_length_prefixed(&body, &session_id) ||
736      !CBB_add_bytes(&session_id, session->session_id,
737                     session->session_id_length) ||
738      !CBB_add_u16(&body, ssl_cipher_get_value(hs->new_cipher)) ||
739      !CBB_add_u8(&body, 0 /* no compression */) ||
740      !ssl_add_serverhello_tlsext(hs, &body) ||
741      !ssl_add_message_cbb(ssl, cbb.get())) {
742    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
743    return ssl_hs_error;
744  }
745
746  if (ssl->session != NULL) {
747    hs->state = state_send_server_finished;
748  } else {
749    hs->state = state_send_server_certificate;
750  }
751  return ssl_hs_ok;
752}
753
754static enum ssl_hs_wait_t do_send_server_certificate(SSL_HANDSHAKE *hs) {
755  SSL *const ssl = hs->ssl;
756  ScopedCBB cbb;
757
758  if (ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
759    if (!ssl_has_certificate(ssl)) {
760      OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CERTIFICATE_SET);
761      return ssl_hs_error;
762    }
763
764    if (!ssl_output_cert_chain(ssl)) {
765      return ssl_hs_error;
766    }
767
768    if (hs->certificate_status_expected) {
769      CBB body, ocsp_response;
770      if (!ssl->method->init_message(ssl, cbb.get(), &body,
771                                     SSL3_MT_CERTIFICATE_STATUS) ||
772          !CBB_add_u8(&body, TLSEXT_STATUSTYPE_ocsp) ||
773          !CBB_add_u24_length_prefixed(&body, &ocsp_response) ||
774          !CBB_add_bytes(&ocsp_response,
775                         CRYPTO_BUFFER_data(ssl->cert->ocsp_response),
776                         CRYPTO_BUFFER_len(ssl->cert->ocsp_response)) ||
777          !ssl_add_message_cbb(ssl, cbb.get())) {
778        OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
779        return ssl_hs_error;
780      }
781    }
782  }
783
784  // Assemble ServerKeyExchange parameters if needed.
785  uint32_t alg_k = hs->new_cipher->algorithm_mkey;
786  uint32_t alg_a = hs->new_cipher->algorithm_auth;
787  if (ssl_cipher_requires_server_key_exchange(hs->new_cipher) ||
788      ((alg_a & SSL_aPSK) && ssl->psk_identity_hint)) {
789
790    // Pre-allocate enough room to comfortably fit an ECDHE public key. Prepend
791    // the client and server randoms for the signing transcript.
792    CBB child;
793    if (!CBB_init(cbb.get(), SSL3_RANDOM_SIZE * 2 + 128) ||
794        !CBB_add_bytes(cbb.get(), ssl->s3->client_random, SSL3_RANDOM_SIZE) ||
795        !CBB_add_bytes(cbb.get(), ssl->s3->server_random, SSL3_RANDOM_SIZE)) {
796      return ssl_hs_error;
797    }
798
799    // PSK ciphers begin with an identity hint.
800    if (alg_a & SSL_aPSK) {
801      size_t len =
802          (ssl->psk_identity_hint == NULL) ? 0 : strlen(ssl->psk_identity_hint);
803      if (!CBB_add_u16_length_prefixed(cbb.get(), &child) ||
804          !CBB_add_bytes(&child, (const uint8_t *)ssl->psk_identity_hint,
805                         len)) {
806        return ssl_hs_error;
807      }
808    }
809
810    if (alg_k & SSL_kECDHE) {
811      // Determine the group to use.
812      uint16_t group_id;
813      if (!tls1_get_shared_group(hs, &group_id)) {
814        OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
815        ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
816        return ssl_hs_error;
817       }
818      hs->new_session->group_id = group_id;
819
820      // Set up ECDH, generate a key, and emit the public half.
821      hs->key_share = SSLKeyShare::Create(group_id);
822      if (!hs->key_share ||
823          !CBB_add_u8(cbb.get(), NAMED_CURVE_TYPE) ||
824          !CBB_add_u16(cbb.get(), group_id) ||
825          !CBB_add_u8_length_prefixed(cbb.get(), &child) ||
826          !hs->key_share->Offer(&child)) {
827        return ssl_hs_error;
828      }
829    } else {
830      assert(alg_k & SSL_kPSK);
831    }
832
833    if (!CBBFinishArray(cbb.get(), &hs->server_params)) {
834      return ssl_hs_error;
835    }
836  }
837
838  hs->state = state_send_server_key_exchange;
839  return ssl_hs_ok;
840}
841
842static enum ssl_hs_wait_t do_send_server_key_exchange(SSL_HANDSHAKE *hs) {
843  SSL *const ssl = hs->ssl;
844
845  if (hs->server_params.size() == 0) {
846    hs->state = state_send_server_hello_done;
847    return ssl_hs_ok;
848  }
849
850  ScopedCBB cbb;
851  CBB body, child;
852  if (!ssl->method->init_message(ssl, cbb.get(), &body,
853                                 SSL3_MT_SERVER_KEY_EXCHANGE) ||
854      // |hs->server_params| contains a prefix for signing.
855      hs->server_params.size() < 2 * SSL3_RANDOM_SIZE ||
856      !CBB_add_bytes(&body, hs->server_params.data() + 2 * SSL3_RANDOM_SIZE,
857                     hs->server_params.size() - 2 * SSL3_RANDOM_SIZE)) {
858    return ssl_hs_error;
859  }
860
861  // Add a signature.
862  if (ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
863    if (!ssl_has_private_key(ssl)) {
864      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
865      return ssl_hs_error;
866    }
867
868    // Determine the signature algorithm.
869    uint16_t signature_algorithm;
870    if (!tls1_choose_signature_algorithm(hs, &signature_algorithm)) {
871      return ssl_hs_error;
872    }
873    if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
874      if (!CBB_add_u16(&body, signature_algorithm)) {
875        OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
876        ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
877        return ssl_hs_error;
878      }
879    }
880
881    // Add space for the signature.
882    const size_t max_sig_len = EVP_PKEY_size(hs->local_pubkey.get());
883    uint8_t *ptr;
884    if (!CBB_add_u16_length_prefixed(&body, &child) ||
885        !CBB_reserve(&child, &ptr, max_sig_len)) {
886      return ssl_hs_error;
887    }
888
889    size_t sig_len;
890    switch (ssl_private_key_sign(hs, ptr, &sig_len, max_sig_len,
891                                 signature_algorithm, hs->server_params)) {
892      case ssl_private_key_success:
893        if (!CBB_did_write(&child, sig_len)) {
894          return ssl_hs_error;
895        }
896        break;
897      case ssl_private_key_failure:
898        return ssl_hs_error;
899      case ssl_private_key_retry:
900        return ssl_hs_private_key_operation;
901    }
902  }
903
904  if (!ssl_add_message_cbb(ssl, cbb.get())) {
905    return ssl_hs_error;
906  }
907
908  hs->server_params.Reset();
909
910  hs->state = state_send_server_hello_done;
911  return ssl_hs_ok;
912}
913
914static enum ssl_hs_wait_t do_send_server_hello_done(SSL_HANDSHAKE *hs) {
915  SSL *const ssl = hs->ssl;
916
917  ScopedCBB cbb;
918  CBB body;
919
920  if (hs->cert_request) {
921    CBB cert_types, sigalgs_cbb;
922    if (!ssl->method->init_message(ssl, cbb.get(), &body,
923                                   SSL3_MT_CERTIFICATE_REQUEST) ||
924        !CBB_add_u8_length_prefixed(&body, &cert_types) ||
925        !CBB_add_u8(&cert_types, SSL3_CT_RSA_SIGN) ||
926        (ssl_protocol_version(ssl) >= TLS1_VERSION &&
927         !CBB_add_u8(&cert_types, TLS_CT_ECDSA_SIGN)) ||
928        (ssl_protocol_version(ssl) >= TLS1_2_VERSION &&
929         (!CBB_add_u16_length_prefixed(&body, &sigalgs_cbb) ||
930          !tls12_add_verify_sigalgs(ssl, &sigalgs_cbb))) ||
931        !ssl_add_client_CA_list(ssl, &body) ||
932        !ssl_add_message_cbb(ssl, cbb.get())) {
933      OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
934      return ssl_hs_error;
935    }
936  }
937
938  if (!ssl->method->init_message(ssl, cbb.get(), &body,
939                                 SSL3_MT_SERVER_HELLO_DONE) ||
940      !ssl_add_message_cbb(ssl, cbb.get())) {
941    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
942    return ssl_hs_error;
943  }
944
945  hs->state = state_read_client_certificate;
946  return ssl_hs_flush;
947}
948
949static enum ssl_hs_wait_t do_read_client_certificate(SSL_HANDSHAKE *hs) {
950  SSL *const ssl = hs->ssl;
951
952  if (!hs->cert_request) {
953    hs->state = state_verify_client_certificate;
954    return ssl_hs_ok;
955  }
956
957  SSLMessage msg;
958  if (!ssl->method->get_message(ssl, &msg)) {
959    return ssl_hs_read_message;
960  }
961
962  if (msg.type != SSL3_MT_CERTIFICATE) {
963    if (ssl->version == SSL3_VERSION &&
964        msg.type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
965      // In SSL 3.0, the Certificate message is omitted to signal no
966      // certificate.
967      if (ssl->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) {
968        OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
969        ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
970        return ssl_hs_error;
971      }
972
973      // OpenSSL returns X509_V_OK when no certificates are received. This is
974      // classed by them as a bug, but it's assumed by at least NGINX.
975      hs->new_session->verify_result = X509_V_OK;
976      hs->state = state_verify_client_certificate;
977      return ssl_hs_ok;
978    }
979
980    OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
981    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
982    return ssl_hs_error;
983  }
984
985  if (!ssl_hash_message(hs, msg)) {
986    return ssl_hs_error;
987  }
988
989  CBS certificate_msg = msg.body;
990  uint8_t alert = SSL_AD_DECODE_ERROR;
991  UniquePtr<STACK_OF(CRYPTO_BUFFER)> chain;
992  if (!ssl_parse_cert_chain(&alert, &chain, &hs->peer_pubkey,
993                            ssl->retain_only_sha256_of_client_certs
994                                ? hs->new_session->peer_sha256
995                                : NULL,
996                            &certificate_msg, ssl->ctx->pool)) {
997    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
998    return ssl_hs_error;
999  }
1000  sk_CRYPTO_BUFFER_pop_free(hs->new_session->certs, CRYPTO_BUFFER_free);
1001  hs->new_session->certs = chain.release();
1002
1003  if (CBS_len(&certificate_msg) != 0 ||
1004      !ssl->ctx->x509_method->session_cache_objects(hs->new_session.get())) {
1005    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1006    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1007    return ssl_hs_error;
1008  }
1009
1010  if (sk_CRYPTO_BUFFER_num(hs->new_session->certs) == 0) {
1011    // No client certificate so the handshake buffer may be discarded.
1012    hs->transcript.FreeBuffer();
1013
1014    // In SSL 3.0, sending no certificate is signaled by omitting the
1015    // Certificate message.
1016    if (ssl->version == SSL3_VERSION) {
1017      OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CERTIFICATES_RETURNED);
1018      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1019      return ssl_hs_error;
1020    }
1021
1022    if (ssl->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) {
1023      // Fail for TLS only if we required a certificate
1024      OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
1025      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1026      return ssl_hs_error;
1027    }
1028
1029    // OpenSSL returns X509_V_OK when no certificates are received. This is
1030    // classed by them as a bug, but it's assumed by at least NGINX.
1031    hs->new_session->verify_result = X509_V_OK;
1032  } else if (ssl->retain_only_sha256_of_client_certs) {
1033    // The hash will have been filled in.
1034    hs->new_session->peer_sha256_valid = 1;
1035  }
1036
1037  ssl->method->next_message(ssl);
1038  hs->state = state_verify_client_certificate;
1039  return ssl_hs_ok;
1040}
1041
1042static enum ssl_hs_wait_t do_verify_client_certificate(SSL_HANDSHAKE *hs) {
1043  if (sk_CRYPTO_BUFFER_num(hs->new_session->certs) > 0) {
1044    switch (ssl_verify_peer_cert(hs)) {
1045      case ssl_verify_ok:
1046        break;
1047      case ssl_verify_invalid:
1048        return ssl_hs_error;
1049      case ssl_verify_retry:
1050        return ssl_hs_certificate_verify;
1051    }
1052  }
1053
1054  hs->state = state_read_client_key_exchange;
1055  return ssl_hs_ok;
1056}
1057
1058static enum ssl_hs_wait_t do_read_client_key_exchange(SSL_HANDSHAKE *hs) {
1059  SSL *const ssl = hs->ssl;
1060  SSLMessage msg;
1061  if (!ssl->method->get_message(ssl, &msg)) {
1062    return ssl_hs_read_message;
1063  }
1064
1065  if (!ssl_check_message_type(ssl, msg, SSL3_MT_CLIENT_KEY_EXCHANGE)) {
1066    return ssl_hs_error;
1067  }
1068
1069  CBS client_key_exchange = msg.body;
1070  uint32_t alg_k = hs->new_cipher->algorithm_mkey;
1071  uint32_t alg_a = hs->new_cipher->algorithm_auth;
1072
1073  // If using a PSK key exchange, parse the PSK identity.
1074  if (alg_a & SSL_aPSK) {
1075    CBS psk_identity;
1076
1077    // If using PSK, the ClientKeyExchange contains a psk_identity. If PSK,
1078    // then this is the only field in the message.
1079    if (!CBS_get_u16_length_prefixed(&client_key_exchange, &psk_identity) ||
1080        ((alg_k & SSL_kPSK) && CBS_len(&client_key_exchange) != 0)) {
1081      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1082      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1083      return ssl_hs_error;
1084    }
1085
1086    if (CBS_len(&psk_identity) > PSK_MAX_IDENTITY_LEN ||
1087        CBS_contains_zero_byte(&psk_identity)) {
1088      OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
1089      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
1090      return ssl_hs_error;
1091    }
1092
1093    if (!CBS_strdup(&psk_identity, &hs->new_session->psk_identity)) {
1094      OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1095      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1096      return ssl_hs_error;
1097    }
1098  }
1099
1100  // Depending on the key exchange method, compute |premaster_secret|.
1101  Array<uint8_t> premaster_secret;
1102  if (alg_k & SSL_kRSA) {
1103    CBS encrypted_premaster_secret;
1104    if (ssl->version > SSL3_VERSION) {
1105      if (!CBS_get_u16_length_prefixed(&client_key_exchange,
1106                                       &encrypted_premaster_secret) ||
1107          CBS_len(&client_key_exchange) != 0) {
1108        OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1109        ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1110        return ssl_hs_error;
1111      }
1112    } else {
1113      encrypted_premaster_secret = client_key_exchange;
1114    }
1115
1116    // Allocate a buffer large enough for an RSA decryption.
1117    Array<uint8_t> decrypt_buf;
1118    if (!decrypt_buf.Init(EVP_PKEY_size(hs->local_pubkey.get()))) {
1119      return ssl_hs_error;
1120    }
1121
1122    // Decrypt with no padding. PKCS#1 padding will be removed as part of the
1123    // timing-sensitive code below.
1124    size_t decrypt_len;
1125    switch (ssl_private_key_decrypt(hs, decrypt_buf.data(), &decrypt_len,
1126                                    decrypt_buf.size(),
1127                                    encrypted_premaster_secret)) {
1128      case ssl_private_key_success:
1129        break;
1130      case ssl_private_key_failure:
1131        return ssl_hs_error;
1132      case ssl_private_key_retry:
1133        return ssl_hs_private_key_operation;
1134    }
1135
1136    if (decrypt_len != decrypt_buf.size()) {
1137      OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
1138      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
1139      return ssl_hs_error;
1140    }
1141
1142    // Prepare a random premaster, to be used on invalid padding. See RFC 5246,
1143    // section 7.4.7.1.
1144    if (!premaster_secret.Init(SSL_MAX_MASTER_KEY_LENGTH) ||
1145        !RAND_bytes(premaster_secret.data(), premaster_secret.size())) {
1146      return ssl_hs_error;
1147    }
1148
1149    // The smallest padded premaster is 11 bytes of overhead. Small keys are
1150    // publicly invalid.
1151    if (decrypt_len < 11 + premaster_secret.size()) {
1152      OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
1153      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
1154      return ssl_hs_error;
1155    }
1156
1157    // Check the padding. See RFC 3447, section 7.2.2.
1158    size_t padding_len = decrypt_len - premaster_secret.size();
1159    uint8_t good = constant_time_eq_int_8(decrypt_buf[0], 0) &
1160                   constant_time_eq_int_8(decrypt_buf[1], 2);
1161    for (size_t i = 2; i < padding_len - 1; i++) {
1162      good &= ~constant_time_is_zero_8(decrypt_buf[i]);
1163    }
1164    good &= constant_time_is_zero_8(decrypt_buf[padding_len - 1]);
1165
1166    // The premaster secret must begin with |client_version|. This too must be
1167    // checked in constant time (http://eprint.iacr.org/2003/052/).
1168    good &= constant_time_eq_8(decrypt_buf[padding_len],
1169                               (unsigned)(hs->client_version >> 8));
1170    good &= constant_time_eq_8(decrypt_buf[padding_len + 1],
1171                               (unsigned)(hs->client_version & 0xff));
1172
1173    // Select, in constant time, either the decrypted premaster or the random
1174    // premaster based on |good|.
1175    for (size_t i = 0; i < premaster_secret.size(); i++) {
1176      premaster_secret[i] = constant_time_select_8(
1177          good, decrypt_buf[padding_len + i], premaster_secret[i]);
1178    }
1179  } else if (alg_k & SSL_kECDHE) {
1180    // Parse the ClientKeyExchange.
1181    CBS peer_key;
1182    if (!CBS_get_u8_length_prefixed(&client_key_exchange, &peer_key) ||
1183        CBS_len(&client_key_exchange) != 0) {
1184      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1185      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1186      return ssl_hs_error;
1187    }
1188
1189    // Compute the premaster.
1190    uint8_t alert = SSL_AD_DECODE_ERROR;
1191    if (!hs->key_share->Finish(&premaster_secret, &alert, peer_key)) {
1192      ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1193      return ssl_hs_error;
1194    }
1195
1196    // The key exchange state may now be discarded.
1197    hs->key_share.reset();
1198  } else if (!(alg_k & SSL_kPSK)) {
1199    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1200    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1201    return ssl_hs_error;
1202  }
1203
1204  // For a PSK cipher suite, the actual pre-master secret is combined with the
1205  // pre-shared key.
1206  if (alg_a & SSL_aPSK) {
1207    if (ssl->psk_server_callback == NULL) {
1208      OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1209      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1210      return ssl_hs_error;
1211    }
1212
1213    // Look up the key for the identity.
1214    uint8_t psk[PSK_MAX_PSK_LEN];
1215    unsigned psk_len = ssl->psk_server_callback(
1216        ssl, hs->new_session->psk_identity, psk, sizeof(psk));
1217    if (psk_len > PSK_MAX_PSK_LEN) {
1218      OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1219      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1220      return ssl_hs_error;
1221    } else if (psk_len == 0) {
1222      // PSK related to the given identity not found.
1223      OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
1224      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNKNOWN_PSK_IDENTITY);
1225      return ssl_hs_error;
1226    }
1227
1228    if (alg_k & SSL_kPSK) {
1229      // In plain PSK, other_secret is a block of 0s with the same length as the
1230      // pre-shared key.
1231      if (!premaster_secret.Init(psk_len)) {
1232        return ssl_hs_error;
1233      }
1234      OPENSSL_memset(premaster_secret.data(), 0, premaster_secret.size());
1235    }
1236
1237    ScopedCBB new_premaster;
1238    CBB child;
1239    if (!CBB_init(new_premaster.get(),
1240                  2 + psk_len + 2 + premaster_secret.size()) ||
1241        !CBB_add_u16_length_prefixed(new_premaster.get(), &child) ||
1242        !CBB_add_bytes(&child, premaster_secret.data(),
1243                       premaster_secret.size()) ||
1244        !CBB_add_u16_length_prefixed(new_premaster.get(), &child) ||
1245        !CBB_add_bytes(&child, psk, psk_len) ||
1246        !CBBFinishArray(new_premaster.get(), &premaster_secret)) {
1247      OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1248      return ssl_hs_error;
1249    }
1250  }
1251
1252  if (!ssl_hash_message(hs, msg)) {
1253    return ssl_hs_error;
1254  }
1255
1256  // Compute the master secret.
1257  hs->new_session->master_key_length = tls1_generate_master_secret(
1258      hs, hs->new_session->master_key, premaster_secret);
1259  if (hs->new_session->master_key_length == 0) {
1260    return ssl_hs_error;
1261  }
1262  hs->new_session->extended_master_secret = hs->extended_master_secret;
1263
1264  ssl->method->next_message(ssl);
1265  hs->state = state_read_client_certificate_verify;
1266  return ssl_hs_ok;
1267}
1268
1269static enum ssl_hs_wait_t do_read_client_certificate_verify(SSL_HANDSHAKE *hs) {
1270  SSL *const ssl = hs->ssl;
1271
1272  // Only RSA and ECDSA client certificates are supported, so a
1273  // CertificateVerify is required if and only if there's a client certificate.
1274  if (!hs->peer_pubkey) {
1275    hs->transcript.FreeBuffer();
1276    hs->state = state_read_change_cipher_spec;
1277    return ssl_hs_ok;
1278  }
1279
1280  SSLMessage msg;
1281  if (!ssl->method->get_message(ssl, &msg)) {
1282    return ssl_hs_read_message;
1283  }
1284
1285  if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE_VERIFY)) {
1286    return ssl_hs_error;
1287  }
1288
1289  CBS certificate_verify = msg.body, signature;
1290
1291  // Determine the signature algorithm.
1292  uint16_t signature_algorithm = 0;
1293  if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
1294    if (!CBS_get_u16(&certificate_verify, &signature_algorithm)) {
1295      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1296      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1297      return ssl_hs_error;
1298    }
1299    uint8_t alert = SSL_AD_DECODE_ERROR;
1300    if (!tls12_check_peer_sigalg(ssl, &alert, signature_algorithm)) {
1301      ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1302      return ssl_hs_error;
1303    }
1304    hs->new_session->peer_signature_algorithm = signature_algorithm;
1305  } else if (!tls1_get_legacy_signature_algorithm(&signature_algorithm,
1306                                                  hs->peer_pubkey.get())) {
1307    OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
1308    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNSUPPORTED_CERTIFICATE);
1309    return ssl_hs_error;
1310  }
1311
1312  // Parse and verify the signature.
1313  if (!CBS_get_u16_length_prefixed(&certificate_verify, &signature) ||
1314      CBS_len(&certificate_verify) != 0) {
1315    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1316    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1317    return ssl_hs_error;
1318  }
1319
1320  bool sig_ok;
1321  // The SSL3 construction for CertificateVerify does not decompose into a
1322  // single final digest and signature, and must be special-cased.
1323  if (ssl_protocol_version(ssl) == SSL3_VERSION) {
1324    uint8_t digest[EVP_MAX_MD_SIZE];
1325    size_t digest_len;
1326    if (!hs->transcript.GetSSL3CertVerifyHash(
1327            digest, &digest_len, hs->new_session.get(), signature_algorithm)) {
1328      return ssl_hs_error;
1329    }
1330
1331    UniquePtr<EVP_PKEY_CTX> pctx(
1332        EVP_PKEY_CTX_new(hs->peer_pubkey.get(), nullptr));
1333    sig_ok = pctx &&
1334             EVP_PKEY_verify_init(pctx.get()) &&
1335             EVP_PKEY_verify(pctx.get(), CBS_data(&signature),
1336                             CBS_len(&signature), digest, digest_len);
1337  } else {
1338    sig_ok =
1339        ssl_public_key_verify(ssl, signature, signature_algorithm,
1340                              hs->peer_pubkey.get(), hs->transcript.buffer());
1341  }
1342
1343#if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
1344  sig_ok = true;
1345  ERR_clear_error();
1346#endif
1347  if (!sig_ok) {
1348    OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SIGNATURE);
1349    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
1350    return ssl_hs_error;
1351  }
1352
1353  // The handshake buffer is no longer necessary, and we may hash the current
1354  // message.
1355  hs->transcript.FreeBuffer();
1356  if (!ssl_hash_message(hs, msg)) {
1357    return ssl_hs_error;
1358  }
1359
1360  ssl->method->next_message(ssl);
1361  hs->state = state_read_change_cipher_spec;
1362  return ssl_hs_ok;
1363}
1364
1365static enum ssl_hs_wait_t do_read_change_cipher_spec(SSL_HANDSHAKE *hs) {
1366  hs->state = state_process_change_cipher_spec;
1367  return ssl_hs_read_change_cipher_spec;
1368}
1369
1370static enum ssl_hs_wait_t do_process_change_cipher_spec(SSL_HANDSHAKE *hs) {
1371  if (!tls1_change_cipher_state(hs, evp_aead_open)) {
1372    return ssl_hs_error;
1373  }
1374
1375  hs->state = state_read_next_proto;
1376  return ssl_hs_ok;
1377}
1378
1379static enum ssl_hs_wait_t do_read_next_proto(SSL_HANDSHAKE *hs) {
1380  SSL *const ssl = hs->ssl;
1381
1382  if (!hs->next_proto_neg_seen) {
1383    hs->state = state_read_channel_id;
1384    return ssl_hs_ok;
1385  }
1386
1387  SSLMessage msg;
1388  if (!ssl->method->get_message(ssl, &msg)) {
1389    return ssl_hs_read_message;
1390  }
1391
1392  if (!ssl_check_message_type(ssl, msg, SSL3_MT_NEXT_PROTO) ||
1393      !ssl_hash_message(hs, msg)) {
1394    return ssl_hs_error;
1395  }
1396
1397  CBS next_protocol = msg.body, selected_protocol, padding;
1398  if (!CBS_get_u8_length_prefixed(&next_protocol, &selected_protocol) ||
1399      !CBS_get_u8_length_prefixed(&next_protocol, &padding) ||
1400      CBS_len(&next_protocol) != 0) {
1401    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1402    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1403    return ssl_hs_error;
1404  }
1405
1406  if (!ssl->s3->next_proto_negotiated.CopyFrom(selected_protocol)) {
1407    return ssl_hs_error;
1408  }
1409
1410  ssl->method->next_message(ssl);
1411  hs->state = state_read_channel_id;
1412  return ssl_hs_ok;
1413}
1414
1415static enum ssl_hs_wait_t do_read_channel_id(SSL_HANDSHAKE *hs) {
1416  SSL *const ssl = hs->ssl;
1417
1418  if (!ssl->s3->tlsext_channel_id_valid) {
1419    hs->state = state_read_client_finished;
1420    return ssl_hs_ok;
1421  }
1422
1423  SSLMessage msg;
1424  if (!ssl->method->get_message(ssl, &msg)) {
1425    return ssl_hs_read_message;
1426  }
1427
1428  if (!ssl_check_message_type(ssl, msg, SSL3_MT_CHANNEL_ID) ||
1429      !tls1_verify_channel_id(hs, msg) ||
1430      !ssl_hash_message(hs, msg)) {
1431    return ssl_hs_error;
1432  }
1433
1434  ssl->method->next_message(ssl);
1435  hs->state = state_read_client_finished;
1436  return ssl_hs_ok;
1437}
1438
1439static enum ssl_hs_wait_t do_read_client_finished(SSL_HANDSHAKE *hs) {
1440  SSL *const ssl = hs->ssl;
1441  enum ssl_hs_wait_t wait = ssl_get_finished(hs);
1442  if (wait != ssl_hs_ok) {
1443    return wait;
1444  }
1445
1446  if (ssl->session != NULL) {
1447    hs->state = state_finish_server_handshake;
1448  } else {
1449    hs->state = state_send_server_finished;
1450  }
1451
1452  // If this is a full handshake with ChannelID then record the handshake
1453  // hashes in |hs->new_session| in case we need them to verify a
1454  // ChannelID signature on a resumption of this session in the future.
1455  if (ssl->session == NULL && ssl->s3->tlsext_channel_id_valid &&
1456      !tls1_record_handshake_hashes_for_channel_id(hs)) {
1457    return ssl_hs_error;
1458  }
1459
1460  return ssl_hs_ok;
1461}
1462
1463static enum ssl_hs_wait_t do_send_server_finished(SSL_HANDSHAKE *hs) {
1464  SSL *const ssl = hs->ssl;
1465
1466  if (hs->ticket_expected) {
1467    const SSL_SESSION *session;
1468    UniquePtr<SSL_SESSION> session_copy;
1469    if (ssl->session == NULL) {
1470      // Fix the timeout to measure from the ticket issuance time.
1471      ssl_session_rebase_time(ssl, hs->new_session.get());
1472      session = hs->new_session.get();
1473    } else {
1474      // We are renewing an existing session. Duplicate the session to adjust
1475      // the timeout.
1476      session_copy = SSL_SESSION_dup(ssl->session, SSL_SESSION_INCLUDE_NONAUTH);
1477      if (!session_copy) {
1478        return ssl_hs_error;
1479      }
1480
1481      ssl_session_rebase_time(ssl, session_copy.get());
1482      session = session_copy.get();
1483    }
1484
1485    ScopedCBB cbb;
1486    CBB body, ticket;
1487    if (!ssl->method->init_message(ssl, cbb.get(), &body,
1488                                   SSL3_MT_NEW_SESSION_TICKET) ||
1489        !CBB_add_u32(&body, session->timeout) ||
1490        !CBB_add_u16_length_prefixed(&body, &ticket) ||
1491        !ssl_encrypt_ticket(ssl, &ticket, session) ||
1492        !ssl_add_message_cbb(ssl, cbb.get())) {
1493      return ssl_hs_error;
1494    }
1495  }
1496
1497  if (!ssl->method->add_change_cipher_spec(ssl) ||
1498      !tls1_change_cipher_state(hs, evp_aead_seal) ||
1499      !ssl_send_finished(hs)) {
1500    return ssl_hs_error;
1501  }
1502
1503  if (ssl->session != NULL) {
1504    hs->state = state_read_change_cipher_spec;
1505  } else {
1506    hs->state = state_finish_server_handshake;
1507  }
1508  return ssl_hs_flush;
1509}
1510
1511static enum ssl_hs_wait_t do_finish_server_handshake(SSL_HANDSHAKE *hs) {
1512  SSL *const ssl = hs->ssl;
1513
1514  ssl->method->on_handshake_complete(ssl);
1515
1516  // If we aren't retaining peer certificates then we can discard it now.
1517  if (hs->new_session != NULL && ssl->retain_only_sha256_of_client_certs) {
1518    sk_CRYPTO_BUFFER_pop_free(hs->new_session->certs, CRYPTO_BUFFER_free);
1519    hs->new_session->certs = NULL;
1520    ssl->ctx->x509_method->session_clear(hs->new_session.get());
1521  }
1522
1523  if (ssl->session != NULL) {
1524    SSL_SESSION_up_ref(ssl->session);
1525    ssl->s3->established_session.reset(ssl->session);
1526  } else {
1527    ssl->s3->established_session = std::move(hs->new_session);
1528    ssl->s3->established_session->not_resumable = 0;
1529  }
1530
1531  hs->handshake_finalized = true;
1532  ssl->s3->initial_handshake_complete = true;
1533  ssl_update_cache(hs, SSL_SESS_CACHE_SERVER);
1534
1535  hs->state = state_done;
1536  return ssl_hs_ok;
1537}
1538
1539enum ssl_hs_wait_t ssl_server_handshake(SSL_HANDSHAKE *hs) {
1540  while (hs->state != state_done) {
1541    enum ssl_hs_wait_t ret = ssl_hs_error;
1542    enum ssl_server_hs_state_t state =
1543        static_cast<enum ssl_server_hs_state_t>(hs->state);
1544    switch (state) {
1545      case state_start_accept:
1546        ret = do_start_accept(hs);
1547        break;
1548      case state_read_client_hello:
1549        ret = do_read_client_hello(hs);
1550        break;
1551      case state_select_certificate:
1552        ret = do_select_certificate(hs);
1553        break;
1554      case state_tls13:
1555        ret = do_tls13(hs);
1556        break;
1557      case state_select_parameters:
1558        ret = do_select_parameters(hs);
1559        break;
1560      case state_send_server_hello:
1561        ret = do_send_server_hello(hs);
1562        break;
1563      case state_send_server_certificate:
1564        ret = do_send_server_certificate(hs);
1565        break;
1566      case state_send_server_key_exchange:
1567        ret = do_send_server_key_exchange(hs);
1568        break;
1569      case state_send_server_hello_done:
1570        ret = do_send_server_hello_done(hs);
1571        break;
1572      case state_read_client_certificate:
1573        ret = do_read_client_certificate(hs);
1574        break;
1575      case state_verify_client_certificate:
1576        ret = do_verify_client_certificate(hs);
1577        break;
1578      case state_read_client_key_exchange:
1579        ret = do_read_client_key_exchange(hs);
1580        break;
1581      case state_read_client_certificate_verify:
1582        ret = do_read_client_certificate_verify(hs);
1583        break;
1584      case state_read_change_cipher_spec:
1585        ret = do_read_change_cipher_spec(hs);
1586        break;
1587      case state_process_change_cipher_spec:
1588        ret = do_process_change_cipher_spec(hs);
1589        break;
1590      case state_read_next_proto:
1591        ret = do_read_next_proto(hs);
1592        break;
1593      case state_read_channel_id:
1594        ret = do_read_channel_id(hs);
1595        break;
1596      case state_read_client_finished:
1597        ret = do_read_client_finished(hs);
1598        break;
1599      case state_send_server_finished:
1600        ret = do_send_server_finished(hs);
1601        break;
1602      case state_finish_server_handshake:
1603        ret = do_finish_server_handshake(hs);
1604        break;
1605      case state_done:
1606        ret = ssl_hs_ok;
1607        break;
1608    }
1609
1610    if (hs->state != state) {
1611      ssl_do_info_callback(hs->ssl, SSL_CB_ACCEPT_LOOP, 1);
1612    }
1613
1614    if (ret != ssl_hs_ok) {
1615      return ret;
1616    }
1617  }
1618
1619  ssl_do_info_callback(hs->ssl, SSL_CB_HANDSHAKE_DONE, 1);
1620  return ssl_hs_ok;
1621}
1622
1623const char *ssl_server_handshake_state(SSL_HANDSHAKE *hs) {
1624  enum ssl_server_hs_state_t state =
1625      static_cast<enum ssl_server_hs_state_t>(hs->state);
1626  switch (state) {
1627    case state_start_accept:
1628      return "TLS server start_accept";
1629    case state_read_client_hello:
1630      return "TLS server read_client_hello";
1631    case state_select_certificate:
1632      return "TLS server select_certificate";
1633    case state_tls13:
1634      return tls13_server_handshake_state(hs);
1635    case state_select_parameters:
1636      return "TLS server select_parameters";
1637    case state_send_server_hello:
1638      return "TLS server send_server_hello";
1639    case state_send_server_certificate:
1640      return "TLS server send_server_certificate";
1641    case state_send_server_key_exchange:
1642      return "TLS server send_server_key_exchange";
1643    case state_send_server_hello_done:
1644      return "TLS server send_server_hello_done";
1645    case state_read_client_certificate:
1646      return "TLS server read_client_certificate";
1647    case state_verify_client_certificate:
1648      return "TLS server verify_client_certificate";
1649    case state_read_client_key_exchange:
1650      return "TLS server read_client_key_exchange";
1651    case state_read_client_certificate_verify:
1652      return "TLS server read_client_certificate_verify";
1653    case state_read_change_cipher_spec:
1654      return "TLS server read_change_cipher_spec";
1655    case state_process_change_cipher_spec:
1656      return "TLS server process_change_cipher_spec";
1657    case state_read_next_proto:
1658      return "TLS server read_next_proto";
1659    case state_read_channel_id:
1660      return "TLS server read_channel_id";
1661    case state_read_client_finished:
1662      return "TLS server read_client_finished";
1663    case state_send_server_finished:
1664      return "TLS server send_server_finished";
1665    case state_finish_server_handshake:
1666      return "TLS server finish_server_handshake";
1667    case state_done:
1668      return "TLS server done";
1669  }
1670
1671  return "TLS server unknown";
1672}
1673
1674}
1675