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 <assert.h>
150#include <stdio.h>
151#include <string.h>
152
153#include <openssl/bn.h>
154#include <openssl/buf.h>
155#include <openssl/bytestring.h>
156#include <openssl/cipher.h>
157#include <openssl/dh.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/obj.h>
166#include <openssl/rand.h>
167#include <openssl/sha.h>
168#include <openssl/x509.h>
169
170#include "internal.h"
171#include "../crypto/internal.h"
172#include "../crypto/dh/internal.h"
173
174
175/* INITIAL_SNIFF_BUFFER_SIZE is the number of bytes read in the initial sniff
176 * buffer. */
177#define INITIAL_SNIFF_BUFFER_SIZE 8
178
179int ssl3_accept(SSL *s) {
180  BUF_MEM *buf = NULL;
181  uint32_t alg_a;
182  void (*cb)(const SSL *ssl, int type, int val) = NULL;
183  int ret = -1;
184  int new_state, state, skip = 0;
185
186  assert(s->handshake_func == ssl3_accept);
187  assert(s->server);
188  assert(!SSL_IS_DTLS(s));
189
190  ERR_clear_error();
191  ERR_clear_system_error();
192
193  if (s->info_callback != NULL) {
194    cb = s->info_callback;
195  } else if (s->ctx->info_callback != NULL) {
196    cb = s->ctx->info_callback;
197  }
198
199  s->in_handshake++;
200
201  if (s->cert == NULL) {
202    OPENSSL_PUT_ERROR(SSL, ssl3_accept, SSL_R_NO_CERTIFICATE_SET);
203    return -1;
204  }
205
206  for (;;) {
207    state = s->state;
208
209    switch (s->state) {
210      case SSL_ST_ACCEPT:
211        if (cb != NULL) {
212          cb(s, SSL_CB_HANDSHAKE_START, 1);
213        }
214
215        if (s->init_buf == NULL) {
216          buf = BUF_MEM_new();
217          if (!buf || !BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
218            ret = -1;
219            goto end;
220          }
221          s->init_buf = buf;
222          buf = NULL;
223        }
224        s->init_num = 0;
225
226        /* Enable a write buffer. This groups handshake messages within a flight
227         * into a single write. */
228        if (!ssl_init_wbio_buffer(s, 1)) {
229          ret = -1;
230          goto end;
231        }
232
233        if (!ssl3_init_finished_mac(s)) {
234          OPENSSL_PUT_ERROR(SSL, ssl3_accept, ERR_R_INTERNAL_ERROR);
235          ret = -1;
236          goto end;
237        }
238
239        if (!s->s3->have_version) {
240          s->state = SSL3_ST_SR_INITIAL_BYTES;
241        } else {
242          s->state = SSL3_ST_SR_CLNT_HELLO_A;
243        }
244        break;
245
246      case SSL3_ST_SR_INITIAL_BYTES:
247        ret = ssl3_get_initial_bytes(s);
248        if (ret <= 0) {
249          goto end;
250        }
251        /* ssl3_get_initial_bytes sets s->state to one of
252         * SSL3_ST_SR_V2_CLIENT_HELLO or SSL3_ST_SR_CLNT_HELLO_A on success. */
253        break;
254
255      case SSL3_ST_SR_V2_CLIENT_HELLO:
256        ret = ssl3_get_v2_client_hello(s);
257        if (ret <= 0) {
258          goto end;
259        }
260        s->state = SSL3_ST_SR_CLNT_HELLO_A;
261        break;
262
263      case SSL3_ST_SR_CLNT_HELLO_A:
264      case SSL3_ST_SR_CLNT_HELLO_B:
265      case SSL3_ST_SR_CLNT_HELLO_C:
266      case SSL3_ST_SR_CLNT_HELLO_D:
267        s->shutdown = 0;
268        ret = ssl3_get_client_hello(s);
269        if (ret <= 0) {
270          goto end;
271        }
272        s->state = SSL3_ST_SW_SRVR_HELLO_A;
273        s->init_num = 0;
274        break;
275
276      case SSL3_ST_SW_SRVR_HELLO_A:
277      case SSL3_ST_SW_SRVR_HELLO_B:
278        ret = ssl3_send_server_hello(s);
279        if (ret <= 0) {
280          goto end;
281        }
282        if (s->hit) {
283          if (s->tlsext_ticket_expected) {
284            s->state = SSL3_ST_SW_SESSION_TICKET_A;
285          } else {
286            s->state = SSL3_ST_SW_CHANGE_A;
287          }
288        } else {
289          s->state = SSL3_ST_SW_CERT_A;
290        }
291        s->init_num = 0;
292        break;
293
294      case SSL3_ST_SW_CERT_A:
295      case SSL3_ST_SW_CERT_B:
296        if (ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher)) {
297          ret = ssl3_send_server_certificate(s);
298          if (ret <= 0) {
299            goto end;
300          }
301          if (s->s3->tmp.certificate_status_expected) {
302            s->state = SSL3_ST_SW_CERT_STATUS_A;
303          } else {
304            s->state = SSL3_ST_SW_KEY_EXCH_A;
305          }
306        } else {
307          skip = 1;
308          s->state = SSL3_ST_SW_KEY_EXCH_A;
309        }
310        s->init_num = 0;
311        break;
312
313      case SSL3_ST_SW_KEY_EXCH_A:
314      case SSL3_ST_SW_KEY_EXCH_B:
315        alg_a = s->s3->tmp.new_cipher->algorithm_auth;
316
317        /* Send a ServerKeyExchange message if:
318         * - The key exchange is ephemeral or anonymous
319         *   Diffie-Hellman.
320         * - There is a PSK identity hint.
321         *
322         * TODO(davidben): This logic is currently duplicated in d1_srvr.c. Fix
323         * this. In the meantime, keep them in sync. */
324        if (ssl_cipher_requires_server_key_exchange(s->s3->tmp.new_cipher) ||
325            ((alg_a & SSL_aPSK) && s->psk_identity_hint)) {
326          ret = ssl3_send_server_key_exchange(s);
327          if (ret <= 0) {
328            goto end;
329          }
330        } else {
331          skip = 1;
332        }
333
334        s->state = SSL3_ST_SW_CERT_REQ_A;
335        s->init_num = 0;
336        break;
337
338      case SSL3_ST_SW_CERT_REQ_A:
339      case SSL3_ST_SW_CERT_REQ_B:
340        if (s->s3->tmp.cert_request) {
341          ret = ssl3_send_certificate_request(s);
342          if (ret <= 0) {
343            goto end;
344          }
345        } else {
346          skip = 1;
347        }
348        s->state = SSL3_ST_SW_SRVR_DONE_A;
349        s->init_num = 0;
350        break;
351
352      case SSL3_ST_SW_SRVR_DONE_A:
353      case SSL3_ST_SW_SRVR_DONE_B:
354        ret = ssl3_send_server_done(s);
355        if (ret <= 0) {
356          goto end;
357        }
358        s->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
359        s->state = SSL3_ST_SW_FLUSH;
360        s->init_num = 0;
361        break;
362
363      case SSL3_ST_SW_FLUSH:
364        /* This code originally checked to see if any data was pending using
365         * BIO_CTRL_INFO and then flushed. This caused problems as documented
366         * in PR#1939. The proposed fix doesn't completely resolve this issue
367         * as buggy implementations of BIO_CTRL_PENDING still exist. So instead
368         * we just flush unconditionally. */
369        s->rwstate = SSL_WRITING;
370        if (BIO_flush(s->wbio) <= 0) {
371          ret = -1;
372          goto end;
373        }
374        s->rwstate = SSL_NOTHING;
375
376        s->state = s->s3->tmp.next_state;
377        break;
378
379      case SSL3_ST_SR_CERT_A:
380      case SSL3_ST_SR_CERT_B:
381        if (s->s3->tmp.cert_request) {
382          ret = ssl3_get_client_certificate(s);
383          if (ret <= 0) {
384            goto end;
385          }
386        }
387        s->init_num = 0;
388        s->state = SSL3_ST_SR_KEY_EXCH_A;
389        break;
390
391      case SSL3_ST_SR_KEY_EXCH_A:
392      case SSL3_ST_SR_KEY_EXCH_B:
393        ret = ssl3_get_client_key_exchange(s);
394        if (ret <= 0) {
395          goto end;
396        }
397        s->state = SSL3_ST_SR_CERT_VRFY_A;
398        s->init_num = 0;
399        break;
400
401      case SSL3_ST_SR_CERT_VRFY_A:
402      case SSL3_ST_SR_CERT_VRFY_B:
403        ret = ssl3_get_cert_verify(s);
404        if (ret <= 0) {
405          goto end;
406        }
407
408        s->state = SSL3_ST_SR_CHANGE;
409        s->init_num = 0;
410        break;
411
412      case SSL3_ST_SR_CHANGE: {
413        char next_proto_neg = 0;
414        char channel_id = 0;
415        next_proto_neg = s->s3->next_proto_neg_seen;
416        channel_id = s->s3->tlsext_channel_id_valid;
417
418        /* At this point, the next message must be entirely behind a
419         * ChangeCipherSpec. */
420        if (!ssl3_expect_change_cipher_spec(s)) {
421          ret = -1;
422          goto end;
423        }
424        if (next_proto_neg) {
425          s->state = SSL3_ST_SR_NEXT_PROTO_A;
426        } else if (channel_id) {
427          s->state = SSL3_ST_SR_CHANNEL_ID_A;
428        } else {
429          s->state = SSL3_ST_SR_FINISHED_A;
430        }
431        break;
432      }
433
434      case SSL3_ST_SR_NEXT_PROTO_A:
435      case SSL3_ST_SR_NEXT_PROTO_B:
436        ret = ssl3_get_next_proto(s);
437        if (ret <= 0) {
438          goto end;
439        }
440        s->init_num = 0;
441        if (s->s3->tlsext_channel_id_valid) {
442          s->state = SSL3_ST_SR_CHANNEL_ID_A;
443        } else {
444          s->state = SSL3_ST_SR_FINISHED_A;
445        }
446        break;
447
448      case SSL3_ST_SR_CHANNEL_ID_A:
449      case SSL3_ST_SR_CHANNEL_ID_B:
450        ret = ssl3_get_channel_id(s);
451        if (ret <= 0) {
452          goto end;
453        }
454        s->init_num = 0;
455        s->state = SSL3_ST_SR_FINISHED_A;
456        break;
457
458      case SSL3_ST_SR_FINISHED_A:
459      case SSL3_ST_SR_FINISHED_B:
460        ret =
461            ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A, SSL3_ST_SR_FINISHED_B);
462        if (ret <= 0) {
463          goto end;
464        }
465
466        if (s->hit) {
467          s->state = SSL_ST_OK;
468        } else if (s->tlsext_ticket_expected) {
469          s->state = SSL3_ST_SW_SESSION_TICKET_A;
470        } else {
471          s->state = SSL3_ST_SW_CHANGE_A;
472        }
473        /* If this is a full handshake with ChannelID then record the hashshake
474         * hashes in |s->session| in case we need them to verify a ChannelID
475         * signature on a resumption of this session in the future. */
476        if (!s->hit && s->s3->tlsext_channel_id_new) {
477          ret = tls1_record_handshake_hashes_for_channel_id(s);
478          if (ret <= 0) {
479            goto end;
480          }
481        }
482        s->init_num = 0;
483        break;
484
485      case SSL3_ST_SW_SESSION_TICKET_A:
486      case SSL3_ST_SW_SESSION_TICKET_B:
487        ret = ssl3_send_new_session_ticket(s);
488        if (ret <= 0) {
489          goto end;
490        }
491        s->state = SSL3_ST_SW_CHANGE_A;
492        s->init_num = 0;
493        break;
494
495      case SSL3_ST_SW_CHANGE_A:
496      case SSL3_ST_SW_CHANGE_B:
497        s->session->cipher = s->s3->tmp.new_cipher;
498        if (!s->enc_method->setup_key_block(s)) {
499          ret = -1;
500          goto end;
501        }
502
503        ret = ssl3_send_change_cipher_spec(s, SSL3_ST_SW_CHANGE_A,
504                                           SSL3_ST_SW_CHANGE_B);
505        if (ret <= 0) {
506          goto end;
507        }
508        s->state = SSL3_ST_SW_FINISHED_A;
509        s->init_num = 0;
510
511        if (!s->enc_method->change_cipher_state(
512                s, SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
513          ret = -1;
514          goto end;
515        }
516        break;
517
518      case SSL3_ST_SW_FINISHED_A:
519      case SSL3_ST_SW_FINISHED_B:
520        ret =
521            ssl3_send_finished(s, SSL3_ST_SW_FINISHED_A, SSL3_ST_SW_FINISHED_B,
522                               s->enc_method->server_finished_label,
523                               s->enc_method->server_finished_label_len);
524        if (ret <= 0) {
525          goto end;
526        }
527        s->state = SSL3_ST_SW_FLUSH;
528        if (s->hit) {
529          s->s3->tmp.next_state = SSL3_ST_SR_CHANGE;
530        } else {
531          s->s3->tmp.next_state = SSL_ST_OK;
532        }
533        s->init_num = 0;
534        break;
535
536      case SSL_ST_OK:
537        /* clean a few things up */
538        ssl3_cleanup_key_block(s);
539
540        BUF_MEM_free(s->init_buf);
541        s->init_buf = NULL;
542
543        /* remove buffering on output */
544        ssl_free_wbio_buffer(s);
545
546        s->init_num = 0;
547
548        /* If we aren't retaining peer certificates then we can discard it
549         * now. */
550        if (s->ctx->retain_only_sha256_of_client_certs) {
551          X509_free(s->session->peer);
552          s->session->peer = NULL;
553        }
554
555        s->s3->initial_handshake_complete = 1;
556
557        ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
558
559        if (cb != NULL) {
560          cb(s, SSL_CB_HANDSHAKE_DONE, 1);
561        }
562
563        ret = 1;
564        goto end;
565
566      default:
567        OPENSSL_PUT_ERROR(SSL, ssl3_accept, SSL_R_UNKNOWN_STATE);
568        ret = -1;
569        goto end;
570    }
571
572    if (!s->s3->tmp.reuse_message && !skip && cb != NULL && s->state != state) {
573      new_state = s->state;
574      s->state = state;
575      cb(s, SSL_CB_ACCEPT_LOOP, 1);
576      s->state = new_state;
577    }
578    skip = 0;
579  }
580
581end:
582  s->in_handshake--;
583  BUF_MEM_free(buf);
584  if (cb != NULL) {
585    cb(s, SSL_CB_ACCEPT_EXIT, ret);
586  }
587  return ret;
588}
589
590static int ssl3_read_sniff_buffer(SSL *s, size_t n) {
591  if (s->s3->sniff_buffer == NULL) {
592    s->s3->sniff_buffer = BUF_MEM_new();
593  }
594  if (s->s3->sniff_buffer == NULL || !BUF_MEM_grow(s->s3->sniff_buffer, n)) {
595    return -1;
596  }
597
598  while (s->s3->sniff_buffer_len < n) {
599    int ret;
600
601    s->rwstate = SSL_READING;
602    ret = BIO_read(s->rbio, s->s3->sniff_buffer->data + s->s3->sniff_buffer_len,
603                   n - s->s3->sniff_buffer_len);
604    if (ret <= 0) {
605      return ret;
606    }
607    s->rwstate = SSL_NOTHING;
608    s->s3->sniff_buffer_len += ret;
609  }
610
611  return 1;
612}
613
614int ssl3_get_initial_bytes(SSL *s) {
615  int ret;
616  const uint8_t *p;
617
618  /* Read the first 8 bytes. To recognize a ClientHello or V2ClientHello only
619   * needs the first 6 bytes, but 8 is needed to recognize CONNECT below. */
620  ret = ssl3_read_sniff_buffer(s, INITIAL_SNIFF_BUFFER_SIZE);
621  if (ret <= 0) {
622    return ret;
623  }
624  assert(s->s3->sniff_buffer_len >= INITIAL_SNIFF_BUFFER_SIZE);
625  p = (const uint8_t *)s->s3->sniff_buffer->data;
626
627  /* Some dedicated error codes for protocol mixups should the application wish
628   * to interpret them differently. (These do not overlap with ClientHello or
629   * V2ClientHello.) */
630  if (strncmp("GET ", (const char *)p, 4) == 0 ||
631      strncmp("POST ", (const char *)p, 5) == 0 ||
632      strncmp("HEAD ", (const char *)p, 5) == 0 ||
633      strncmp("PUT ", (const char *)p, 4) == 0) {
634    OPENSSL_PUT_ERROR(SSL, ssl3_get_initial_bytes, SSL_R_HTTP_REQUEST);
635    return -1;
636  }
637  if (strncmp("CONNECT ", (const char *)p, 8) == 0) {
638    OPENSSL_PUT_ERROR(SSL, ssl3_get_initial_bytes, SSL_R_HTTPS_PROXY_REQUEST);
639    return -1;
640  }
641
642  /* Determine if this is a ClientHello or V2ClientHello. */
643  if ((p[0] & 0x80) && p[2] == SSL2_MT_CLIENT_HELLO &&
644      p[3] >= SSL3_VERSION_MAJOR) {
645    /* This is a V2ClientHello. */
646    s->state = SSL3_ST_SR_V2_CLIENT_HELLO;
647    return 1;
648  }
649  if (p[0] == SSL3_RT_HANDSHAKE && p[1] >= SSL3_VERSION_MAJOR &&
650      p[5] == SSL3_MT_CLIENT_HELLO) {
651    /* This is a ClientHello. Initialize the record layer with the already
652     * consumed data and continue the handshake. */
653    if (!ssl3_setup_read_buffer(s)) {
654      return -1;
655    }
656    assert(s->rstate == SSL_ST_READ_HEADER);
657    /* There cannot have already been data in the record layer. */
658    assert(s->s3->rbuf.left == 0);
659    memcpy(s->s3->rbuf.buf, p, s->s3->sniff_buffer_len);
660    s->s3->rbuf.offset = 0;
661    s->s3->rbuf.left = s->s3->sniff_buffer_len;
662    s->packet_length = 0;
663
664    BUF_MEM_free(s->s3->sniff_buffer);
665    s->s3->sniff_buffer = NULL;
666    s->s3->sniff_buffer_len = 0;
667
668    s->state = SSL3_ST_SR_CLNT_HELLO_A;
669    return 1;
670  }
671
672  OPENSSL_PUT_ERROR(SSL, ssl3_get_initial_bytes, SSL_R_UNKNOWN_PROTOCOL);
673  return -1;
674}
675
676int ssl3_get_v2_client_hello(SSL *s) {
677  const uint8_t *p;
678  int ret;
679  CBS v2_client_hello, cipher_specs, session_id, challenge;
680  size_t msg_length, rand_len, len;
681  uint8_t msg_type;
682  uint16_t version, cipher_spec_length, session_id_length, challenge_length;
683  CBB client_hello, hello_body, cipher_suites;
684  uint8_t random[SSL3_RANDOM_SIZE];
685
686  /* Read the remainder of the V2ClientHello. We have previously read 8 bytes
687   * in ssl3_get_initial_bytes. */
688  assert(s->s3->sniff_buffer_len >= INITIAL_SNIFF_BUFFER_SIZE);
689  p = (const uint8_t *)s->s3->sniff_buffer->data;
690  msg_length = ((p[0] & 0x7f) << 8) | p[1];
691  if (msg_length > (1024 * 4)) {
692    OPENSSL_PUT_ERROR(SSL, ssl3_get_v2_client_hello, SSL_R_RECORD_TOO_LARGE);
693    return -1;
694  }
695  if (msg_length < INITIAL_SNIFF_BUFFER_SIZE - 2) {
696    /* Reject lengths that are too short early. We have already read 8 bytes,
697     * so we should not attempt to process an (invalid) V2ClientHello which
698     * would be shorter than that. */
699    OPENSSL_PUT_ERROR(SSL, ssl3_get_v2_client_hello,
700                      SSL_R_RECORD_LENGTH_MISMATCH);
701    return -1;
702  }
703
704  ret = ssl3_read_sniff_buffer(s, msg_length + 2);
705  if (ret <= 0) {
706    return ret;
707  }
708  assert(s->s3->sniff_buffer_len == msg_length + 2);
709  CBS_init(&v2_client_hello, (const uint8_t *)s->s3->sniff_buffer->data + 2,
710           msg_length);
711
712  /* The V2ClientHello without the length is incorporated into the Finished
713   * hash. */
714  if (!ssl3_finish_mac(s, CBS_data(&v2_client_hello),
715                       CBS_len(&v2_client_hello))) {
716    return -1;
717  }
718  if (s->msg_callback) {
719    s->msg_callback(0, SSL2_VERSION, 0, CBS_data(&v2_client_hello),
720                    CBS_len(&v2_client_hello), s, s->msg_callback_arg);
721  }
722
723  if (!CBS_get_u8(&v2_client_hello, &msg_type) ||
724      !CBS_get_u16(&v2_client_hello, &version) ||
725      !CBS_get_u16(&v2_client_hello, &cipher_spec_length) ||
726      !CBS_get_u16(&v2_client_hello, &session_id_length) ||
727      !CBS_get_u16(&v2_client_hello, &challenge_length) ||
728      !CBS_get_bytes(&v2_client_hello, &cipher_specs, cipher_spec_length) ||
729      !CBS_get_bytes(&v2_client_hello, &session_id, session_id_length) ||
730      !CBS_get_bytes(&v2_client_hello, &challenge, challenge_length) ||
731      CBS_len(&v2_client_hello) != 0) {
732    OPENSSL_PUT_ERROR(SSL, ssl3_get_v2_client_hello, SSL_R_DECODE_ERROR);
733    return -1;
734  }
735
736  /* msg_type has already been checked. */
737  assert(msg_type == SSL2_MT_CLIENT_HELLO);
738
739  /* The client_random is the V2ClientHello challenge. Truncate or
740   * left-pad with zeros as needed. */
741  memset(random, 0, SSL3_RANDOM_SIZE);
742  rand_len = CBS_len(&challenge);
743  if (rand_len > SSL3_RANDOM_SIZE) {
744    rand_len = SSL3_RANDOM_SIZE;
745  }
746  memcpy(random + (SSL3_RANDOM_SIZE - rand_len), CBS_data(&challenge),
747         rand_len);
748
749  /* Write out an equivalent SSLv3 ClientHello. */
750  if (!CBB_init_fixed(&client_hello, (uint8_t *)s->init_buf->data,
751                      s->init_buf->max)) {
752    OPENSSL_PUT_ERROR(SSL, ssl3_get_v2_client_hello, ERR_R_MALLOC_FAILURE);
753    return -1;
754  }
755  if (!CBB_add_u8(&client_hello, SSL3_MT_CLIENT_HELLO) ||
756      !CBB_add_u24_length_prefixed(&client_hello, &hello_body) ||
757      !CBB_add_u16(&hello_body, version) ||
758      !CBB_add_bytes(&hello_body, random, SSL3_RANDOM_SIZE) ||
759      /* No session id. */
760      !CBB_add_u8(&hello_body, 0) ||
761      !CBB_add_u16_length_prefixed(&hello_body, &cipher_suites)) {
762    CBB_cleanup(&client_hello);
763    OPENSSL_PUT_ERROR(SSL, ssl3_get_v2_client_hello, ERR_R_INTERNAL_ERROR);
764    return -1;
765  }
766
767  /* Copy the cipher suites. */
768  while (CBS_len(&cipher_specs) > 0) {
769    uint32_t cipher_spec;
770    if (!CBS_get_u24(&cipher_specs, &cipher_spec)) {
771      CBB_cleanup(&client_hello);
772      OPENSSL_PUT_ERROR(SSL, ssl3_get_v2_client_hello, SSL_R_DECODE_ERROR);
773      return -1;
774    }
775
776    /* Skip SSLv2 ciphers. */
777    if ((cipher_spec & 0xff0000) != 0) {
778      continue;
779    }
780    if (!CBB_add_u16(&cipher_suites, cipher_spec)) {
781      CBB_cleanup(&client_hello);
782      OPENSSL_PUT_ERROR(SSL, ssl3_get_v2_client_hello, ERR_R_INTERNAL_ERROR);
783      return -1;
784    }
785  }
786
787  /* Add the null compression scheme and finish. */
788  if (!CBB_add_u8(&hello_body, 1) || !CBB_add_u8(&hello_body, 0) ||
789      !CBB_finish(&client_hello, NULL, &len)) {
790    CBB_cleanup(&client_hello);
791    OPENSSL_PUT_ERROR(SSL, ssl3_get_v2_client_hello, ERR_R_INTERNAL_ERROR);
792    return -1;
793  }
794
795  /* Mark the message for "re"-use by the version-specific method. */
796  s->s3->tmp.reuse_message = 1;
797  s->s3->tmp.message_type = SSL3_MT_CLIENT_HELLO;
798  /* The handshake message header is 4 bytes. */
799  s->s3->tmp.message_size = len - 4;
800
801  /* Drop the sniff buffer. */
802  BUF_MEM_free(s->s3->sniff_buffer);
803  s->s3->sniff_buffer = NULL;
804  s->s3->sniff_buffer_len = 0;
805
806  return 1;
807}
808
809int ssl3_get_client_hello(SSL *s) {
810  int ok, al = SSL_AD_INTERNAL_ERROR, ret = -1;
811  long n;
812  const SSL_CIPHER *c;
813  STACK_OF(SSL_CIPHER) *ciphers = NULL;
814  struct ssl_early_callback_ctx early_ctx;
815  CBS client_hello;
816  uint16_t client_version;
817  CBS client_random, session_id, cipher_suites, compression_methods;
818
819  /* We do this so that we will respond with our native type. If we are TLSv1
820   * and we get SSLv3, we will respond with TLSv1, This down switching should
821   * be handled by a different method. If we are SSLv3, we will respond with
822   * SSLv3, even if prompted with TLSv1. */
823  switch (s->state) {
824    case SSL3_ST_SR_CLNT_HELLO_A:
825    case SSL3_ST_SR_CLNT_HELLO_B:
826      n = s->method->ssl_get_message(
827          s, SSL3_ST_SR_CLNT_HELLO_A, SSL3_ST_SR_CLNT_HELLO_B,
828          SSL3_MT_CLIENT_HELLO, SSL3_RT_MAX_PLAIN_LENGTH,
829          ssl_hash_message, &ok);
830
831      if (!ok) {
832        return n;
833      }
834
835      s->state = SSL3_ST_SR_CLNT_HELLO_C;
836      /* fallthrough */
837    case SSL3_ST_SR_CLNT_HELLO_C:
838    case SSL3_ST_SR_CLNT_HELLO_D:
839      /* We have previously parsed the ClientHello message, and can't call
840       * ssl_get_message again without hashing the message into the Finished
841       * digest again. */
842      n = s->init_num;
843
844      memset(&early_ctx, 0, sizeof(early_ctx));
845      early_ctx.ssl = s;
846      early_ctx.client_hello = s->init_msg;
847      early_ctx.client_hello_len = n;
848      if (!ssl_early_callback_init(&early_ctx)) {
849        al = SSL_AD_DECODE_ERROR;
850        OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello,
851                          SSL_R_CLIENTHELLO_PARSE_FAILED);
852        goto f_err;
853      }
854
855      if (s->state == SSL3_ST_SR_CLNT_HELLO_C &&
856          s->ctx->select_certificate_cb != NULL) {
857        s->state = SSL3_ST_SR_CLNT_HELLO_D;
858        switch (s->ctx->select_certificate_cb(&early_ctx)) {
859          case 0:
860            s->rwstate = SSL_CERTIFICATE_SELECTION_PENDING;
861            goto err;
862
863          case -1:
864            /* Connection rejected. */
865            al = SSL_AD_ACCESS_DENIED;
866            OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello,
867                              SSL_R_CONNECTION_REJECTED);
868            goto f_err;
869
870          default:
871            /* fallthrough */;
872        }
873      }
874      s->state = SSL3_ST_SR_CLNT_HELLO_D;
875      break;
876
877    default:
878      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_UNKNOWN_STATE);
879      return -1;
880  }
881
882  CBS_init(&client_hello, s->init_msg, n);
883  if (!CBS_get_u16(&client_hello, &client_version) ||
884      !CBS_get_bytes(&client_hello, &client_random, SSL3_RANDOM_SIZE) ||
885      !CBS_get_u8_length_prefixed(&client_hello, &session_id) ||
886      CBS_len(&session_id) > SSL_MAX_SSL_SESSION_ID_LENGTH) {
887    al = SSL_AD_DECODE_ERROR;
888    OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
889    goto f_err;
890  }
891
892  /* use version from inside client hello, not from record header (may differ:
893   * see RFC 2246, Appendix E, second paragraph) */
894  s->client_version = client_version;
895
896  /* Load the client random. */
897  memcpy(s->s3->client_random, CBS_data(&client_random), SSL3_RANDOM_SIZE);
898
899  if (SSL_IS_DTLS(s)) {
900    CBS cookie;
901
902    if (!CBS_get_u8_length_prefixed(&client_hello, &cookie) ||
903        CBS_len(&cookie) > DTLS1_COOKIE_LENGTH) {
904      al = SSL_AD_DECODE_ERROR;
905      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
906      goto f_err;
907    }
908  }
909
910  /* Note: This codepath may run twice if |ssl_get_prev_session| completes
911   * asynchronously.
912   *
913   * TODO(davidben): Clean up the order of events around ClientHello
914   * processing. */
915  if (!s->s3->have_version) {
916    /* Select version to use */
917    uint16_t version = ssl3_get_mutual_version(s, client_version);
918    if (version == 0) {
919      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_UNSUPPORTED_PROTOCOL);
920      s->version = s->client_version;
921      al = SSL_AD_PROTOCOL_VERSION;
922      goto f_err;
923    }
924    s->version = version;
925    s->enc_method = ssl3_get_enc_method(version);
926    assert(s->enc_method != NULL);
927    /* At this point, the connection's version is known and |s->version| is
928     * fixed. Begin enforcing the record-layer version. */
929    s->s3->have_version = 1;
930  } else if (SSL_IS_DTLS(s) ? (s->client_version > s->version)
931                            : (s->client_version < s->version)) {
932    OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_WRONG_VERSION_NUMBER);
933    al = SSL_AD_PROTOCOL_VERSION;
934    goto f_err;
935  }
936
937  s->hit = 0;
938  int session_ret = ssl_get_prev_session(s, &early_ctx);
939  if (session_ret == PENDING_SESSION) {
940    s->rwstate = SSL_PENDING_SESSION;
941    goto err;
942  } else if (session_ret == -1) {
943    goto err;
944  }
945
946  /* The EMS state is needed when making the resumption decision, but
947   * extensions are not normally parsed until later. This detects the EMS
948   * extension for the resumption decision and it's checked against the result
949   * of the normal parse later in this function. */
950  const uint8_t *ems_data;
951  size_t ems_len;
952  int have_extended_master_secret =
953      s->version != SSL3_VERSION &&
954      SSL_early_callback_ctx_extension_get(&early_ctx,
955                                           TLSEXT_TYPE_extended_master_secret,
956                                           &ems_data, &ems_len) &&
957      ems_len == 0;
958
959  if (session_ret == 1) {
960    if (s->session->extended_master_secret &&
961        !have_extended_master_secret) {
962      /* A ClientHello without EMS that attempts to resume a session with EMS
963       * is fatal to the connection. */
964      al = SSL_AD_HANDSHAKE_FAILURE;
965      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello,
966                        SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
967      goto f_err;
968    }
969
970    s->hit =
971        /* Only resume if the session's version matches the negotiated version:
972         * most clients do not accept a mismatch. */
973        s->version == s->session->ssl_version &&
974        /* If the client offers the EMS extension, but the previous session
975         * didn't use it, then negotiate a new session. */
976        have_extended_master_secret == s->session->extended_master_secret;
977  }
978
979  if (!s->hit && !ssl_get_new_session(s, 1)) {
980    goto err;
981  }
982
983  if (s->ctx->dos_protection_cb != NULL && s->ctx->dos_protection_cb(&early_ctx) == 0) {
984    /* Connection rejected for DOS reasons. */
985    al = SSL_AD_ACCESS_DENIED;
986    OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_CONNECTION_REJECTED);
987    goto f_err;
988  }
989
990  if (!CBS_get_u16_length_prefixed(&client_hello, &cipher_suites) ||
991      CBS_len(&cipher_suites) == 0 ||
992      CBS_len(&cipher_suites) % 2 != 0 ||
993      !CBS_get_u8_length_prefixed(&client_hello, &compression_methods) ||
994      CBS_len(&compression_methods) == 0) {
995    al = SSL_AD_DECODE_ERROR;
996    OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
997    goto f_err;
998  }
999
1000  ciphers = ssl_bytes_to_cipher_list(s, &cipher_suites);
1001  if (ciphers == NULL) {
1002    goto err;
1003  }
1004
1005  /* If it is a hit, check that the cipher is in the list. */
1006  if (s->hit) {
1007    size_t j;
1008    int found_cipher = 0;
1009    uint32_t id = s->session->cipher->id;
1010
1011    for (j = 0; j < sk_SSL_CIPHER_num(ciphers); j++) {
1012      c = sk_SSL_CIPHER_value(ciphers, j);
1013      if (c->id == id) {
1014        found_cipher = 1;
1015        break;
1016      }
1017    }
1018
1019    if (!found_cipher) {
1020      /* we need to have the cipher in the cipher list if we are asked to reuse
1021       * it */
1022      al = SSL_AD_ILLEGAL_PARAMETER;
1023      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello,
1024                        SSL_R_REQUIRED_CIPHER_MISSING);
1025      goto f_err;
1026    }
1027  }
1028
1029  /* Only null compression is supported. */
1030  if (memchr(CBS_data(&compression_methods), 0,
1031             CBS_len(&compression_methods)) == NULL) {
1032    al = SSL_AD_ILLEGAL_PARAMETER;
1033    OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello,
1034                      SSL_R_NO_COMPRESSION_SPECIFIED);
1035    goto f_err;
1036  }
1037
1038  /* TLS extensions. */
1039  if (s->version >= SSL3_VERSION &&
1040      !ssl_parse_clienthello_tlsext(s, &client_hello)) {
1041    OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_PARSE_TLSEXT);
1042    goto err;
1043  }
1044
1045  /* There should be nothing left over in the record. */
1046  if (CBS_len(&client_hello) != 0) {
1047    /* wrong packet length */
1048    al = SSL_AD_DECODE_ERROR;
1049    OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_BAD_PACKET_LENGTH);
1050    goto f_err;
1051  }
1052
1053  if (have_extended_master_secret != s->s3->tmp.extended_master_secret) {
1054    al = SSL_AD_INTERNAL_ERROR;
1055    OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_EMS_STATE_INCONSISTENT);
1056    goto f_err;
1057  }
1058
1059  /* Given ciphers and SSL_get_ciphers, we must pick a cipher */
1060  if (!s->hit) {
1061    if (ciphers == NULL) {
1062      al = SSL_AD_ILLEGAL_PARAMETER;
1063      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_CIPHERS_PASSED);
1064      goto f_err;
1065    }
1066
1067    /* Let cert callback update server certificates if required */
1068    if (s->cert->cert_cb) {
1069      int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1070      if (rv == 0) {
1071        al = SSL_AD_INTERNAL_ERROR;
1072        OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_CERT_CB_ERROR);
1073        goto f_err;
1074      }
1075      if (rv < 0) {
1076        s->rwstate = SSL_X509_LOOKUP;
1077        goto err;
1078      }
1079      s->rwstate = SSL_NOTHING;
1080    }
1081    c = ssl3_choose_cipher(s, ciphers, ssl_get_cipher_preferences(s));
1082
1083    if (c == NULL) {
1084      al = SSL_AD_HANDSHAKE_FAILURE;
1085      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_SHARED_CIPHER);
1086      goto f_err;
1087    }
1088    s->s3->tmp.new_cipher = c;
1089
1090    /* Determine whether to request a client certificate. */
1091    s->s3->tmp.cert_request = !!(s->verify_mode & SSL_VERIFY_PEER);
1092    /* Only request a certificate if Channel ID isn't negotiated. */
1093    if ((s->verify_mode & SSL_VERIFY_PEER_IF_NO_OBC) &&
1094        s->s3->tlsext_channel_id_valid) {
1095      s->s3->tmp.cert_request = 0;
1096    }
1097    /* Plain PSK forbids Certificate and CertificateRequest. */
1098    if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK) {
1099      s->s3->tmp.cert_request = 0;
1100    }
1101  } else {
1102    /* Session-id reuse */
1103    s->s3->tmp.new_cipher = s->session->cipher;
1104    s->s3->tmp.cert_request = 0;
1105  }
1106
1107  /* In TLS 1.2, client authentication requires hashing the handshake transcript
1108   * under a different hash. Otherwise, release the handshake buffer. */
1109  if ((!SSL_USE_SIGALGS(s) || !s->s3->tmp.cert_request) &&
1110      !ssl3_digest_cached_records(s, free_handshake_buffer)) {
1111    goto f_err;
1112  }
1113
1114  /* we now have the following setup;
1115   * client_random
1116   * cipher_list        - our prefered list of ciphers
1117   * ciphers            - the clients prefered list of ciphers
1118   * compression        - basically ignored right now
1119   * ssl version is set - sslv3
1120   * s->session         - The ssl session has been setup.
1121   * s->hit             - session reuse flag
1122   * s->tmp.new_cipher  - the new cipher to use. */
1123
1124  if (ret < 0) {
1125    ret = -ret;
1126  }
1127
1128  if (0) {
1129  f_err:
1130    ssl3_send_alert(s, SSL3_AL_FATAL, al);
1131  }
1132
1133err:
1134  sk_SSL_CIPHER_free(ciphers);
1135  return ret;
1136}
1137
1138int ssl3_send_server_hello(SSL *s) {
1139  uint8_t *buf;
1140  uint8_t *p, *d;
1141  int sl;
1142  unsigned long l;
1143
1144  if (s->state == SSL3_ST_SW_SRVR_HELLO_A) {
1145    /* We only accept ChannelIDs on connections with ECDHE in order to avoid a
1146     * known attack while we fix ChannelID itself. */
1147    if (s->s3->tlsext_channel_id_valid &&
1148        (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kECDHE) == 0) {
1149      s->s3->tlsext_channel_id_valid = 0;
1150    }
1151
1152    /* If this is a resumption and the original handshake didn't support
1153     * ChannelID then we didn't record the original handshake hashes in the
1154     * session and so cannot resume with ChannelIDs. */
1155    if (s->hit && s->s3->tlsext_channel_id_new &&
1156        s->session->original_handshake_hash_len == 0) {
1157      s->s3->tlsext_channel_id_valid = 0;
1158    }
1159
1160    buf = (uint8_t *)s->init_buf->data;
1161    /* Do the message type and length last */
1162    d = p = ssl_handshake_start(s);
1163
1164    *(p++) = s->version >> 8;
1165    *(p++) = s->version & 0xff;
1166
1167    /* Random stuff */
1168    if (!ssl_fill_hello_random(s->s3->server_random, SSL3_RANDOM_SIZE,
1169                               1 /* server */)) {
1170      OPENSSL_PUT_ERROR(SSL, ssl3_send_server_hello, ERR_R_INTERNAL_ERROR);
1171      return -1;
1172    }
1173    memcpy(p, s->s3->server_random, SSL3_RANDOM_SIZE);
1174    p += SSL3_RANDOM_SIZE;
1175
1176    /* There are several cases for the session ID to send
1177     * back in the server hello:
1178     * - For session reuse from the session cache, we send back the old session
1179     *   ID.
1180     * - If stateless session reuse (using a session ticket) is successful, we
1181     *   send back the client's "session ID" (which doesn't actually identify
1182     *   the session).
1183     * - If it is a new session, we send back the new session ID.
1184     * - However, if we want the new session to be single-use, we send back a
1185     *   0-length session ID.
1186     * s->hit is non-zero in either case of session reuse, so the following
1187     * won't overwrite an ID that we're supposed to send back. */
1188    if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER) && !s->hit) {
1189      s->session->session_id_length = 0;
1190    }
1191
1192    sl = s->session->session_id_length;
1193    if (sl > (int)sizeof(s->session->session_id)) {
1194      OPENSSL_PUT_ERROR(SSL, ssl3_send_server_hello, ERR_R_INTERNAL_ERROR);
1195      return -1;
1196    }
1197    *(p++) = sl;
1198    memcpy(p, s->session->session_id, sl);
1199    p += sl;
1200
1201    /* put the cipher */
1202    s2n(ssl_cipher_get_value(s->s3->tmp.new_cipher), p);
1203
1204    /* put the compression method */
1205    *(p++) = 0;
1206    if (ssl_prepare_serverhello_tlsext(s) <= 0) {
1207      OPENSSL_PUT_ERROR(SSL, ssl3_send_server_hello, SSL_R_SERVERHELLO_TLSEXT);
1208      return -1;
1209    }
1210    p = ssl_add_serverhello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH);
1211    if (p == NULL) {
1212      OPENSSL_PUT_ERROR(SSL, ssl3_send_server_hello, ERR_R_INTERNAL_ERROR);
1213      return -1;
1214    }
1215
1216    /* do the header */
1217    l = (p - d);
1218    if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l)) {
1219      return -1;
1220    }
1221    s->state = SSL3_ST_SW_SRVR_HELLO_B;
1222  }
1223
1224  /* SSL3_ST_SW_SRVR_HELLO_B */
1225  return ssl_do_write(s);
1226}
1227
1228int ssl3_send_server_done(SSL *s) {
1229  if (s->state == SSL3_ST_SW_SRVR_DONE_A) {
1230    if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0)) {
1231      return -1;
1232    }
1233    s->state = SSL3_ST_SW_SRVR_DONE_B;
1234  }
1235
1236  /* SSL3_ST_SW_SRVR_DONE_B */
1237  return ssl_do_write(s);
1238}
1239
1240int ssl3_send_server_key_exchange(SSL *s) {
1241  DH *dh = NULL, *dhp;
1242  EC_KEY *ecdh = NULL;
1243  uint8_t *encodedPoint = NULL;
1244  int encodedlen = 0;
1245  uint16_t curve_id = 0;
1246  BN_CTX *bn_ctx = NULL;
1247  const char *psk_identity_hint = NULL;
1248  size_t psk_identity_hint_len = 0;
1249  EVP_PKEY *pkey;
1250  uint8_t *p, *d;
1251  int al, i;
1252  uint32_t alg_k;
1253  uint32_t alg_a;
1254  int n;
1255  CERT *cert;
1256  BIGNUM *r[4];
1257  int nr[4], kn;
1258  BUF_MEM *buf;
1259  EVP_MD_CTX md_ctx;
1260
1261  EVP_MD_CTX_init(&md_ctx);
1262  if (s->state == SSL3_ST_SW_KEY_EXCH_A) {
1263    alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1264    alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1265    cert = s->cert;
1266
1267    buf = s->init_buf;
1268
1269    r[0] = r[1] = r[2] = r[3] = NULL;
1270    n = 0;
1271    if (alg_a & SSL_aPSK) {
1272      /* size for PSK identity hint */
1273      psk_identity_hint = s->psk_identity_hint;
1274      if (psk_identity_hint) {
1275        psk_identity_hint_len = strlen(psk_identity_hint);
1276      } else {
1277        psk_identity_hint_len = 0;
1278      }
1279      n += 2 + psk_identity_hint_len;
1280    }
1281
1282    if (alg_k & SSL_kDHE) {
1283      dhp = cert->dh_tmp;
1284      if (dhp == NULL && s->cert->dh_tmp_cb != NULL) {
1285        dhp = s->cert->dh_tmp_cb(s, 0, 1024);
1286      }
1287      if (dhp == NULL) {
1288        al = SSL_AD_HANDSHAKE_FAILURE;
1289        OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange,
1290                          SSL_R_MISSING_TMP_DH_KEY);
1291        goto f_err;
1292      }
1293
1294      if (s->s3->tmp.dh != NULL) {
1295        OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange,
1296                          ERR_R_INTERNAL_ERROR);
1297        goto err;
1298      }
1299      dh = DHparams_dup(dhp);
1300      if (dh == NULL) {
1301        OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_DH_LIB);
1302        goto err;
1303      }
1304      s->s3->tmp.dh = dh;
1305
1306      if (!DH_generate_key(dh)) {
1307        OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_DH_LIB);
1308        goto err;
1309      }
1310
1311      r[0] = dh->p;
1312      r[1] = dh->g;
1313      r[2] = dh->pub_key;
1314    } else if (alg_k & SSL_kECDHE) {
1315      /* Determine the curve to use. */
1316      int nid = NID_undef;
1317      if (cert->ecdh_nid != NID_undef) {
1318        nid = cert->ecdh_nid;
1319      } else if (cert->ecdh_tmp_cb != NULL) {
1320        /* Note: |ecdh_tmp_cb| does NOT pass ownership of the result
1321         * to the caller. */
1322        EC_KEY *template = s->cert->ecdh_tmp_cb(s, 0, 1024);
1323        if (template != NULL && EC_KEY_get0_group(template) != NULL) {
1324          nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(template));
1325        }
1326      } else {
1327        nid = tls1_get_shared_curve(s);
1328      }
1329      if (nid == NID_undef) {
1330        al = SSL_AD_HANDSHAKE_FAILURE;
1331        OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange,
1332                          SSL_R_MISSING_TMP_ECDH_KEY);
1333        goto f_err;
1334      }
1335
1336      if (s->s3->tmp.ecdh != NULL) {
1337        OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange,
1338                          ERR_R_INTERNAL_ERROR);
1339        goto err;
1340      }
1341      ecdh = EC_KEY_new_by_curve_name(nid);
1342      if (ecdh == NULL) {
1343        goto err;
1344      }
1345      s->s3->tmp.ecdh = ecdh;
1346
1347      if (!EC_KEY_generate_key(ecdh)) {
1348        OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
1349        goto err;
1350      }
1351
1352      /* We only support ephemeral ECDH keys over named (not generic) curves. */
1353      const EC_GROUP *group = EC_KEY_get0_group(ecdh);
1354      if (!tls1_ec_nid2curve_id(&curve_id, EC_GROUP_get_curve_name(group))) {
1355        OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange,
1356                          SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1357        goto err;
1358      }
1359
1360      /* Encode the public key. First check the size of encoding and allocate
1361       * memory accordingly. */
1362      encodedlen =
1363          EC_POINT_point2oct(group, EC_KEY_get0_public_key(ecdh),
1364                             POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL);
1365
1366      encodedPoint = (uint8_t *)OPENSSL_malloc(encodedlen * sizeof(uint8_t));
1367      bn_ctx = BN_CTX_new();
1368      if (encodedPoint == NULL || bn_ctx == NULL) {
1369        OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange,
1370                          ERR_R_MALLOC_FAILURE);
1371        goto err;
1372      }
1373
1374      encodedlen = EC_POINT_point2oct(group, EC_KEY_get0_public_key(ecdh),
1375                                      POINT_CONVERSION_UNCOMPRESSED,
1376                                      encodedPoint, encodedlen, bn_ctx);
1377
1378      if (encodedlen == 0) {
1379        OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
1380        goto err;
1381      }
1382
1383      BN_CTX_free(bn_ctx);
1384      bn_ctx = NULL;
1385
1386      /* We only support named (not generic) curves in ECDH ephemeral key
1387       * exchanges. In this situation, we need four additional bytes to encode
1388       * the entire ServerECDHParams structure. */
1389      n += 4 + encodedlen;
1390
1391      /* We'll generate the serverKeyExchange message explicitly so we can set
1392       * these to NULLs */
1393      r[0] = NULL;
1394      r[1] = NULL;
1395      r[2] = NULL;
1396      r[3] = NULL;
1397    } else if (!(alg_k & SSL_kPSK)) {
1398      al = SSL_AD_HANDSHAKE_FAILURE;
1399      OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange,
1400                        SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1401      goto f_err;
1402    }
1403
1404    for (i = 0; i < 4 && r[i] != NULL; i++) {
1405      nr[i] = BN_num_bytes(r[i]);
1406      n += 2 + nr[i];
1407    }
1408
1409    if (ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher)) {
1410      pkey = ssl_get_sign_pkey(s, s->s3->tmp.new_cipher);
1411      if (pkey == NULL) {
1412        al = SSL_AD_DECODE_ERROR;
1413        goto f_err;
1414      }
1415      kn = EVP_PKEY_size(pkey);
1416    } else {
1417      pkey = NULL;
1418      kn = 0;
1419    }
1420
1421    if (!BUF_MEM_grow_clean(buf, n + SSL_HM_HEADER_LENGTH(s) + kn)) {
1422      OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_LIB_BUF);
1423      goto err;
1424    }
1425    d = p = ssl_handshake_start(s);
1426
1427    for (i = 0; i < 4 && r[i] != NULL; i++) {
1428      s2n(nr[i], p);
1429      BN_bn2bin(r[i], p);
1430      p += nr[i];
1431    }
1432
1433    /* Note: ECDHE PSK ciphersuites use SSL_kECDHE and SSL_aPSK. When one of
1434     * them is used, the server key exchange record needs to have both the
1435     * psk_identity_hint and the ServerECDHParams. */
1436    if (alg_a & SSL_aPSK) {
1437      /* copy PSK identity hint (if provided) */
1438      s2n(psk_identity_hint_len, p);
1439      if (psk_identity_hint_len > 0) {
1440        memcpy(p, psk_identity_hint, psk_identity_hint_len);
1441        p += psk_identity_hint_len;
1442      }
1443    }
1444
1445    if (alg_k & SSL_kECDHE) {
1446      /* We only support named (not generic) curves. In this situation, the
1447       * serverKeyExchange message has:
1448       * [1 byte CurveType], [2 byte CurveName]
1449       * [1 byte length of encoded point], followed by
1450       * the actual encoded point itself. */
1451      *(p++) = NAMED_CURVE_TYPE;
1452      *(p++) = (uint8_t)(curve_id >> 8);
1453      *(p++) = (uint8_t)(curve_id & 0xff);
1454      *(p++) = encodedlen;
1455      memcpy(p, encodedPoint, encodedlen);
1456      p += encodedlen;
1457      OPENSSL_free(encodedPoint);
1458      encodedPoint = NULL;
1459    }
1460
1461    /* not anonymous */
1462    if (pkey != NULL) {
1463      /* n is the length of the params, they start at &(d[4]) and p points to
1464       * the space at the end. */
1465      const EVP_MD *md;
1466      size_t sig_len = EVP_PKEY_size(pkey);
1467
1468      /* Determine signature algorithm. */
1469      if (SSL_USE_SIGALGS(s)) {
1470        md = tls1_choose_signing_digest(s, pkey);
1471        if (!tls12_get_sigandhash(p, pkey, md)) {
1472          /* Should never happen */
1473          al = SSL_AD_INTERNAL_ERROR;
1474          OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange,
1475                            ERR_R_INTERNAL_ERROR);
1476          goto f_err;
1477        }
1478        p += 2;
1479      } else if (pkey->type == EVP_PKEY_RSA) {
1480        md = EVP_md5_sha1();
1481      } else {
1482        md = EVP_sha1();
1483      }
1484
1485      if (!EVP_DigestSignInit(&md_ctx, NULL, md, NULL, pkey) ||
1486          !EVP_DigestSignUpdate(&md_ctx, s->s3->client_random,
1487                                SSL3_RANDOM_SIZE) ||
1488          !EVP_DigestSignUpdate(&md_ctx, s->s3->server_random,
1489                                SSL3_RANDOM_SIZE) ||
1490          !EVP_DigestSignUpdate(&md_ctx, d, n) ||
1491          !EVP_DigestSignFinal(&md_ctx, &p[2], &sig_len)) {
1492        OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_LIB_EVP);
1493        goto err;
1494      }
1495
1496      s2n(sig_len, p);
1497      n += sig_len + 2;
1498      if (SSL_USE_SIGALGS(s)) {
1499        n += 2;
1500      }
1501    }
1502
1503    if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n)) {
1504      goto err;
1505    }
1506  }
1507
1508  s->state = SSL3_ST_SW_KEY_EXCH_B;
1509  EVP_MD_CTX_cleanup(&md_ctx);
1510  return ssl_do_write(s);
1511
1512f_err:
1513  ssl3_send_alert(s, SSL3_AL_FATAL, al);
1514err:
1515  OPENSSL_free(encodedPoint);
1516  BN_CTX_free(bn_ctx);
1517  EVP_MD_CTX_cleanup(&md_ctx);
1518  return -1;
1519}
1520
1521int ssl3_send_certificate_request(SSL *s) {
1522  uint8_t *p, *d;
1523  size_t i;
1524  int j, nl, off, n;
1525  STACK_OF(X509_NAME) *sk = NULL;
1526  X509_NAME *name;
1527  BUF_MEM *buf;
1528
1529  if (s->state == SSL3_ST_SW_CERT_REQ_A) {
1530    buf = s->init_buf;
1531
1532    d = p = ssl_handshake_start(s);
1533
1534    /* get the list of acceptable cert types */
1535    p++;
1536    n = ssl3_get_req_cert_type(s, p);
1537    d[0] = n;
1538    p += n;
1539    n++;
1540
1541    if (SSL_USE_SIGALGS(s)) {
1542      const uint8_t *psigs;
1543      nl = tls12_get_psigalgs(s, &psigs);
1544      s2n(nl, p);
1545      memcpy(p, psigs, nl);
1546      p += nl;
1547      n += nl + 2;
1548    }
1549
1550    off = n;
1551    p += 2;
1552    n += 2;
1553
1554    sk = SSL_get_client_CA_list(s);
1555    nl = 0;
1556    if (sk != NULL) {
1557      for (i = 0; i < sk_X509_NAME_num(sk); i++) {
1558        name = sk_X509_NAME_value(sk, i);
1559        j = i2d_X509_NAME(name, NULL);
1560        if (!BUF_MEM_grow_clean(buf, SSL_HM_HEADER_LENGTH(s) + n + j + 2)) {
1561          OPENSSL_PUT_ERROR(SSL, ssl3_send_certificate_request, ERR_R_BUF_LIB);
1562          goto err;
1563        }
1564        p = ssl_handshake_start(s) + n;
1565        s2n(j, p);
1566        i2d_X509_NAME(name, &p);
1567        n += 2 + j;
1568        nl += 2 + j;
1569      }
1570    }
1571
1572    /* else no CA names */
1573    p = ssl_handshake_start(s) + off;
1574    s2n(nl, p);
1575
1576    if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n)) {
1577      goto err;
1578    }
1579    s->state = SSL3_ST_SW_CERT_REQ_B;
1580  }
1581
1582  /* SSL3_ST_SW_CERT_REQ_B */
1583  return ssl_do_write(s);
1584
1585err:
1586  return -1;
1587}
1588
1589int ssl3_get_client_key_exchange(SSL *s) {
1590  int al, ok;
1591  long n;
1592  CBS client_key_exchange;
1593  uint32_t alg_k;
1594  uint32_t alg_a;
1595  uint8_t *premaster_secret = NULL;
1596  size_t premaster_secret_len = 0;
1597  RSA *rsa = NULL;
1598  uint8_t *decrypt_buf = NULL;
1599  EVP_PKEY *pkey = NULL;
1600  BIGNUM *pub = NULL;
1601  DH *dh_srvr;
1602
1603  EC_KEY *srvr_ecdh = NULL;
1604  EVP_PKEY *clnt_pub_pkey = NULL;
1605  EC_POINT *clnt_ecpoint = NULL;
1606  BN_CTX *bn_ctx = NULL;
1607  unsigned int psk_len = 0;
1608  uint8_t psk[PSK_MAX_PSK_LEN];
1609
1610  n = s->method->ssl_get_message(s, SSL3_ST_SR_KEY_EXCH_A,
1611                                 SSL3_ST_SR_KEY_EXCH_B,
1612                                 SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, /* ??? */
1613                                 ssl_hash_message, &ok);
1614
1615  if (!ok) {
1616    return n;
1617  }
1618
1619  CBS_init(&client_key_exchange, s->init_msg, n);
1620
1621  alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1622  alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1623
1624  /* If using a PSK key exchange, prepare the pre-shared key. */
1625  if (alg_a & SSL_aPSK) {
1626    CBS psk_identity;
1627
1628    /* If using PSK, the ClientKeyExchange contains a psk_identity. If PSK,
1629     * then this is the only field in the message. */
1630    if (!CBS_get_u16_length_prefixed(&client_key_exchange, &psk_identity) ||
1631        ((alg_k & SSL_kPSK) && CBS_len(&client_key_exchange) != 0)) {
1632      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DECODE_ERROR);
1633      al = SSL_AD_DECODE_ERROR;
1634      goto f_err;
1635    }
1636
1637    if (s->psk_server_callback == NULL) {
1638      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
1639                        SSL_R_PSK_NO_SERVER_CB);
1640      al = SSL_AD_INTERNAL_ERROR;
1641      goto f_err;
1642    }
1643
1644    if (CBS_len(&psk_identity) > PSK_MAX_IDENTITY_LEN ||
1645        CBS_contains_zero_byte(&psk_identity)) {
1646      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
1647                        SSL_R_DATA_LENGTH_TOO_LONG);
1648      al = SSL_AD_ILLEGAL_PARAMETER;
1649      goto f_err;
1650    }
1651
1652    if (!CBS_strdup(&psk_identity, &s->session->psk_identity)) {
1653      al = SSL_AD_INTERNAL_ERROR;
1654      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
1655                        ERR_R_MALLOC_FAILURE);
1656      goto f_err;
1657    }
1658
1659    /* Look up the key for the identity. */
1660    psk_len =
1661        s->psk_server_callback(s, s->session->psk_identity, psk, sizeof(psk));
1662    if (psk_len > PSK_MAX_PSK_LEN) {
1663      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
1664                        ERR_R_INTERNAL_ERROR);
1665      al = SSL_AD_INTERNAL_ERROR;
1666      goto f_err;
1667    } else if (psk_len == 0) {
1668      /* PSK related to the given identity not found */
1669      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
1670                        SSL_R_PSK_IDENTITY_NOT_FOUND);
1671      al = SSL_AD_UNKNOWN_PSK_IDENTITY;
1672      goto f_err;
1673    }
1674  }
1675
1676  /* Depending on the key exchange method, compute |premaster_secret| and
1677   * |premaster_secret_len|. */
1678  if (alg_k & SSL_kRSA) {
1679    CBS encrypted_premaster_secret;
1680    uint8_t rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
1681    uint8_t good;
1682    size_t rsa_size, decrypt_len, premaster_index, j;
1683
1684    pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
1685    if (pkey == NULL || pkey->type != EVP_PKEY_RSA || pkey->pkey.rsa == NULL) {
1686      al = SSL_AD_HANDSHAKE_FAILURE;
1687      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
1688                        SSL_R_MISSING_RSA_CERTIFICATE);
1689      goto f_err;
1690    }
1691    rsa = pkey->pkey.rsa;
1692
1693    /* TLS and [incidentally] DTLS{0xFEFF} */
1694    if (s->version > SSL3_VERSION) {
1695      CBS copy = client_key_exchange;
1696      if (!CBS_get_u16_length_prefixed(&client_key_exchange,
1697                                       &encrypted_premaster_secret) ||
1698          CBS_len(&client_key_exchange) != 0) {
1699        if (!(s->options & SSL_OP_TLS_D5_BUG)) {
1700          al = SSL_AD_DECODE_ERROR;
1701          OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
1702                            SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
1703          goto f_err;
1704        } else {
1705          encrypted_premaster_secret = copy;
1706        }
1707      }
1708    } else {
1709      encrypted_premaster_secret = client_key_exchange;
1710    }
1711
1712    /* Reject overly short RSA keys because we want to be sure that the buffer
1713     * size makes it safe to iterate over the entire size of a premaster secret
1714     * (SSL_MAX_MASTER_KEY_LENGTH). The actual expected size is larger due to
1715     * RSA padding, but the bound is sufficient to be safe. */
1716    rsa_size = RSA_size(rsa);
1717    if (rsa_size < SSL_MAX_MASTER_KEY_LENGTH) {
1718      al = SSL_AD_DECRYPT_ERROR;
1719      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
1720                        SSL_R_DECRYPTION_FAILED);
1721      goto f_err;
1722    }
1723
1724    /* We must not leak whether a decryption failure occurs because of
1725     * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
1726     * section 7.4.7.1). The code follows that advice of the TLS RFC and
1727     * generates a random premaster secret for the case that the decrypt fails.
1728     * See https://tools.ietf.org/html/rfc5246#section-7.4.7.1 */
1729    if (!RAND_bytes(rand_premaster_secret, sizeof(rand_premaster_secret))) {
1730      goto err;
1731    }
1732
1733    /* Allocate a buffer large enough for an RSA decryption. */
1734    decrypt_buf = OPENSSL_malloc(rsa_size);
1735    if (decrypt_buf == NULL) {
1736      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
1737                        ERR_R_MALLOC_FAILURE);
1738      goto err;
1739    }
1740
1741    /* Decrypt with no padding. PKCS#1 padding will be removed as part of the
1742     * timing-sensitive code below. */
1743    if (!RSA_decrypt(rsa, &decrypt_len, decrypt_buf, rsa_size,
1744                     CBS_data(&encrypted_premaster_secret),
1745                     CBS_len(&encrypted_premaster_secret), RSA_NO_PADDING)) {
1746      goto err;
1747    }
1748    if (decrypt_len != rsa_size) {
1749      /* This should never happen, but do a check so we do not read
1750       * uninitialized memory. */
1751      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
1752                        ERR_R_INTERNAL_ERROR);
1753      goto err;
1754    }
1755
1756    /* Remove the PKCS#1 padding and adjust |decrypt_len| as appropriate.
1757     * |good| will be 0xff if the premaster is acceptable and zero otherwise.
1758     * */
1759    good =
1760        constant_time_eq_int_8(RSA_message_index_PKCS1_type_2(
1761                                   decrypt_buf, decrypt_len, &premaster_index),
1762                               1);
1763    decrypt_len = decrypt_len - premaster_index;
1764
1765    /* decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. */
1766    good &= constant_time_eq_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
1767
1768    /* Copy over the unpadded premaster. Whatever the value of
1769     * |decrypt_good_mask|, copy as if the premaster were the right length. It
1770     * is important the memory access pattern be constant. */
1771    premaster_secret =
1772        BUF_memdup(decrypt_buf + (rsa_size - SSL_MAX_MASTER_KEY_LENGTH),
1773                   SSL_MAX_MASTER_KEY_LENGTH);
1774    if (premaster_secret == NULL) {
1775      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
1776                        ERR_R_MALLOC_FAILURE);
1777      goto err;
1778    }
1779    OPENSSL_free(decrypt_buf);
1780    decrypt_buf = NULL;
1781
1782    /* If the version in the decrypted pre-master secret is correct then
1783     * version_good will be 0xff, otherwise it'll be zero. The
1784     * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
1785     * (http://eprint.iacr.org/2003/052/) exploits the version number check as
1786     * a "bad version oracle". Thus version checks are done in constant time
1787     * and are treated like any other decryption error. */
1788    good &= constant_time_eq_8(premaster_secret[0],
1789                               (unsigned)(s->client_version >> 8));
1790    good &= constant_time_eq_8(premaster_secret[1],
1791                               (unsigned)(s->client_version & 0xff));
1792
1793    /* Now copy rand_premaster_secret over premaster_secret using
1794     * decrypt_good_mask. */
1795    for (j = 0; j < sizeof(rand_premaster_secret); j++) {
1796      premaster_secret[j] = constant_time_select_8(good, premaster_secret[j],
1797                                                   rand_premaster_secret[j]);
1798    }
1799
1800    premaster_secret_len = sizeof(rand_premaster_secret);
1801  } else if (alg_k & SSL_kDHE) {
1802    CBS dh_Yc;
1803    int dh_len;
1804
1805    if (!CBS_get_u16_length_prefixed(&client_key_exchange, &dh_Yc) ||
1806        CBS_len(&dh_Yc) == 0 || CBS_len(&client_key_exchange) != 0) {
1807      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
1808                        SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
1809      al = SSL_R_DECODE_ERROR;
1810      goto f_err;
1811    }
1812
1813    if (s->s3->tmp.dh == NULL) {
1814      al = SSL_AD_HANDSHAKE_FAILURE;
1815      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
1816                        SSL_R_MISSING_TMP_DH_KEY);
1817      goto f_err;
1818    }
1819    dh_srvr = s->s3->tmp.dh;
1820
1821    pub = BN_bin2bn(CBS_data(&dh_Yc), CBS_len(&dh_Yc), NULL);
1822    if (pub == NULL) {
1823      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_BN_LIB);
1824      goto err;
1825    }
1826
1827    /* Allocate a buffer for the premaster secret. */
1828    premaster_secret = OPENSSL_malloc(DH_size(dh_srvr));
1829    if (premaster_secret == NULL) {
1830      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
1831                        ERR_R_MALLOC_FAILURE);
1832      BN_clear_free(pub);
1833      goto err;
1834    }
1835
1836    dh_len = DH_compute_key(premaster_secret, pub, dh_srvr);
1837    if (dh_len <= 0) {
1838      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_DH_LIB);
1839      BN_clear_free(pub);
1840      goto err;
1841    }
1842
1843    DH_free(s->s3->tmp.dh);
1844    s->s3->tmp.dh = NULL;
1845    BN_clear_free(pub);
1846    pub = NULL;
1847
1848    premaster_secret_len = dh_len;
1849  } else if (alg_k & SSL_kECDHE) {
1850    int field_size = 0, ecdh_len;
1851    const EC_KEY *tkey;
1852    const EC_GROUP *group;
1853    const BIGNUM *priv_key;
1854    CBS ecdh_Yc;
1855
1856    /* initialize structures for server's ECDH key pair */
1857    srvr_ecdh = EC_KEY_new();
1858    if (srvr_ecdh == NULL) {
1859      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
1860                        ERR_R_MALLOC_FAILURE);
1861      goto err;
1862    }
1863
1864    /* Use the ephermeral values we saved when generating the ServerKeyExchange
1865     * msg. */
1866    tkey = s->s3->tmp.ecdh;
1867
1868    group = EC_KEY_get0_group(tkey);
1869    priv_key = EC_KEY_get0_private_key(tkey);
1870
1871    if (!EC_KEY_set_group(srvr_ecdh, group) ||
1872        !EC_KEY_set_private_key(srvr_ecdh, priv_key)) {
1873      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_EC_LIB);
1874      goto err;
1875    }
1876
1877    /* Let's get client's public key */
1878    clnt_ecpoint = EC_POINT_new(group);
1879    if (clnt_ecpoint == NULL) {
1880      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
1881                        ERR_R_MALLOC_FAILURE);
1882      goto err;
1883    }
1884
1885    /* Get client's public key from encoded point in the ClientKeyExchange
1886     * message. */
1887    if (!CBS_get_u8_length_prefixed(&client_key_exchange, &ecdh_Yc) ||
1888        CBS_len(&client_key_exchange) != 0) {
1889      al = SSL_AD_DECODE_ERROR;
1890      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DECODE_ERROR);
1891      goto f_err;
1892    }
1893
1894    bn_ctx = BN_CTX_new();
1895    if (bn_ctx == NULL) {
1896      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
1897                        ERR_R_MALLOC_FAILURE);
1898      goto err;
1899    }
1900
1901    if (!EC_POINT_oct2point(group, clnt_ecpoint, CBS_data(&ecdh_Yc),
1902                            CBS_len(&ecdh_Yc), bn_ctx)) {
1903      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_EC_LIB);
1904      goto err;
1905    }
1906
1907    /* Allocate a buffer for both the secret and the PSK. */
1908    field_size = EC_GROUP_get_degree(group);
1909    if (field_size <= 0) {
1910      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_ECDH_LIB);
1911      goto err;
1912    }
1913
1914    ecdh_len = (field_size + 7) / 8;
1915    premaster_secret = OPENSSL_malloc(ecdh_len);
1916    if (premaster_secret == NULL) {
1917      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
1918                        ERR_R_MALLOC_FAILURE);
1919      goto err;
1920    }
1921
1922    /* Compute the shared pre-master secret */
1923    ecdh_len = ECDH_compute_key(premaster_secret, ecdh_len, clnt_ecpoint,
1924                                srvr_ecdh, NULL);
1925    if (ecdh_len <= 0) {
1926      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_ECDH_LIB);
1927      goto err;
1928    }
1929
1930    EVP_PKEY_free(clnt_pub_pkey);
1931    clnt_pub_pkey = NULL;
1932    EC_POINT_free(clnt_ecpoint);
1933    clnt_ecpoint = NULL;
1934    EC_KEY_free(srvr_ecdh);
1935    srvr_ecdh = NULL;
1936    BN_CTX_free(bn_ctx);
1937    bn_ctx = NULL;
1938    EC_KEY_free(s->s3->tmp.ecdh);
1939    s->s3->tmp.ecdh = NULL;
1940
1941    premaster_secret_len = ecdh_len;
1942  } else if (alg_k & SSL_kPSK) {
1943    /* For plain PSK, other_secret is a block of 0s with the same length as the
1944     * pre-shared key. */
1945    premaster_secret_len = psk_len;
1946    premaster_secret = OPENSSL_malloc(premaster_secret_len);
1947    if (premaster_secret == NULL) {
1948      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
1949                        ERR_R_MALLOC_FAILURE);
1950      goto err;
1951    }
1952    memset(premaster_secret, 0, premaster_secret_len);
1953  } else {
1954    al = SSL_AD_HANDSHAKE_FAILURE;
1955    OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
1956                      SSL_R_UNKNOWN_CIPHER_TYPE);
1957    goto f_err;
1958  }
1959
1960  /* For a PSK cipher suite, the actual pre-master secret is combined with the
1961   * pre-shared key. */
1962  if (alg_a & SSL_aPSK) {
1963    CBB new_premaster, child;
1964    uint8_t *new_data;
1965    size_t new_len;
1966
1967    if (!CBB_init(&new_premaster, 2 + psk_len + 2 + premaster_secret_len)) {
1968      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
1969                        ERR_R_MALLOC_FAILURE);
1970      goto err;
1971    }
1972    if (!CBB_add_u16_length_prefixed(&new_premaster, &child) ||
1973        !CBB_add_bytes(&child, premaster_secret, premaster_secret_len) ||
1974        !CBB_add_u16_length_prefixed(&new_premaster, &child) ||
1975        !CBB_add_bytes(&child, psk, psk_len) ||
1976        !CBB_finish(&new_premaster, &new_data, &new_len)) {
1977      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
1978                        ERR_R_INTERNAL_ERROR);
1979      CBB_cleanup(&new_premaster);
1980      goto err;
1981    }
1982
1983    OPENSSL_cleanse(premaster_secret, premaster_secret_len);
1984    OPENSSL_free(premaster_secret);
1985    premaster_secret = new_data;
1986    premaster_secret_len = new_len;
1987  }
1988
1989  /* Compute the master secret */
1990  s->session->master_key_length = s->enc_method->generate_master_secret(
1991      s, s->session->master_key, premaster_secret, premaster_secret_len);
1992  if (s->session->master_key_length == 0) {
1993    goto err;
1994  }
1995  s->session->extended_master_secret = s->s3->tmp.extended_master_secret;
1996
1997  OPENSSL_cleanse(premaster_secret, premaster_secret_len);
1998  OPENSSL_free(premaster_secret);
1999  return 1;
2000
2001f_err:
2002  ssl3_send_alert(s, SSL3_AL_FATAL, al);
2003err:
2004  if (premaster_secret) {
2005    if (premaster_secret_len) {
2006      OPENSSL_cleanse(premaster_secret, premaster_secret_len);
2007    }
2008    OPENSSL_free(premaster_secret);
2009  }
2010  OPENSSL_free(decrypt_buf);
2011  EVP_PKEY_free(clnt_pub_pkey);
2012  EC_POINT_free(clnt_ecpoint);
2013  EC_KEY_free(srvr_ecdh);
2014  BN_CTX_free(bn_ctx);
2015
2016  return -1;
2017}
2018
2019int ssl3_get_cert_verify(SSL *s) {
2020  int al, ok, ret = 0;
2021  long n;
2022  CBS certificate_verify, signature;
2023  X509 *peer = s->session->peer;
2024  EVP_PKEY *pkey = NULL;
2025  const EVP_MD *md = NULL;
2026  uint8_t digest[EVP_MAX_MD_SIZE];
2027  size_t digest_length;
2028  EVP_PKEY_CTX *pctx = NULL;
2029
2030  /* Only RSA and ECDSA client certificates are supported, so a
2031   * CertificateVerify is required if and only if there's a client certificate.
2032   * */
2033  if (peer == NULL) {
2034    if (s->s3->handshake_buffer &&
2035        !ssl3_digest_cached_records(s, free_handshake_buffer)) {
2036      return -1;
2037    }
2038    return 1;
2039  }
2040
2041  n = s->method->ssl_get_message(
2042      s, SSL3_ST_SR_CERT_VRFY_A, SSL3_ST_SR_CERT_VRFY_B,
2043      SSL3_MT_CERTIFICATE_VERIFY, SSL3_RT_MAX_PLAIN_LENGTH,
2044      ssl_dont_hash_message, &ok);
2045
2046  if (!ok) {
2047    return n;
2048  }
2049
2050  /* Filter out unsupported certificate types. */
2051  pkey = X509_get_pubkey(peer);
2052  if (pkey == NULL) {
2053    goto err;
2054  }
2055  if (!(X509_certificate_type(peer, pkey) & EVP_PKT_SIGN) ||
2056      (pkey->type != EVP_PKEY_RSA && pkey->type != EVP_PKEY_EC)) {
2057    al = SSL_AD_UNSUPPORTED_CERTIFICATE;
2058    OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify,
2059                      SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
2060    goto f_err;
2061  }
2062
2063  CBS_init(&certificate_verify, s->init_msg, n);
2064
2065  /* Determine the digest type if needbe. */
2066  if (SSL_USE_SIGALGS(s) &&
2067      !tls12_check_peer_sigalg(&md, &al, s, &certificate_verify, pkey)) {
2068    goto f_err;
2069  }
2070
2071  /* Compute the digest. */
2072  if (!ssl3_cert_verify_hash(s, digest, &digest_length, &md, pkey)) {
2073    goto err;
2074  }
2075
2076  /* The handshake buffer is no longer necessary, and we may hash the current
2077   * message.*/
2078  if (s->s3->handshake_buffer &&
2079      !ssl3_digest_cached_records(s, free_handshake_buffer)) {
2080    goto err;
2081  }
2082  if (!ssl3_hash_current_message(s)) {
2083    goto err;
2084  }
2085
2086  /* Parse and verify the signature. */
2087  if (!CBS_get_u16_length_prefixed(&certificate_verify, &signature) ||
2088      CBS_len(&certificate_verify) != 0) {
2089    al = SSL_AD_DECODE_ERROR;
2090    OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, SSL_R_DECODE_ERROR);
2091    goto f_err;
2092  }
2093
2094  pctx = EVP_PKEY_CTX_new(pkey, NULL);
2095  if (pctx == NULL) {
2096    goto err;
2097  }
2098  if (!EVP_PKEY_verify_init(pctx) ||
2099      !EVP_PKEY_CTX_set_signature_md(pctx, md) ||
2100      !EVP_PKEY_verify(pctx, CBS_data(&signature), CBS_len(&signature), digest,
2101                       digest_length)) {
2102    al = SSL_AD_DECRYPT_ERROR;
2103    OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, SSL_R_BAD_SIGNATURE);
2104    goto f_err;
2105  }
2106
2107  ret = 1;
2108
2109  if (0) {
2110  f_err:
2111    ssl3_send_alert(s, SSL3_AL_FATAL, al);
2112  }
2113
2114err:
2115  EVP_PKEY_CTX_free(pctx);
2116  EVP_PKEY_free(pkey);
2117
2118  return ret;
2119}
2120
2121int ssl3_get_client_certificate(SSL *s) {
2122  int i, ok, al, ret = -1;
2123  X509 *x = NULL;
2124  unsigned long n;
2125  STACK_OF(X509) *sk = NULL;
2126  SHA256_CTX sha256;
2127  CBS certificate_msg, certificate_list;
2128  int is_first_certificate = 1;
2129
2130  n = s->method->ssl_get_message(s, SSL3_ST_SR_CERT_A, SSL3_ST_SR_CERT_B, -1,
2131                                 (long)s->max_cert_list, ssl_hash_message, &ok);
2132
2133  if (!ok) {
2134    return n;
2135  }
2136
2137  if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
2138    if ((s->verify_mode & SSL_VERIFY_PEER) &&
2139        (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2140      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate,
2141                        SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2142      al = SSL_AD_HANDSHAKE_FAILURE;
2143      goto f_err;
2144    }
2145
2146    /* If tls asked for a client cert, the client must return a 0 list */
2147    if (s->version > SSL3_VERSION && s->s3->tmp.cert_request) {
2148      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate,
2149                        SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
2150      al = SSL_AD_UNEXPECTED_MESSAGE;
2151      goto f_err;
2152    }
2153    s->s3->tmp.reuse_message = 1;
2154
2155    return 1;
2156  }
2157
2158  if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
2159    al = SSL_AD_UNEXPECTED_MESSAGE;
2160    OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate,
2161                      SSL_R_WRONG_MESSAGE_TYPE);
2162    goto f_err;
2163  }
2164
2165  CBS_init(&certificate_msg, s->init_msg, n);
2166
2167  sk = sk_X509_new_null();
2168  if (sk == NULL) {
2169    OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_MALLOC_FAILURE);
2170    goto err;
2171  }
2172
2173  if (!CBS_get_u24_length_prefixed(&certificate_msg, &certificate_list) ||
2174      CBS_len(&certificate_msg) != 0) {
2175    al = SSL_AD_DECODE_ERROR;
2176    OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_DECODE_ERROR);
2177    goto f_err;
2178  }
2179
2180  while (CBS_len(&certificate_list) > 0) {
2181    CBS certificate;
2182    const uint8_t *data;
2183
2184    if (!CBS_get_u24_length_prefixed(&certificate_list, &certificate)) {
2185      al = SSL_AD_DECODE_ERROR;
2186      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_DECODE_ERROR);
2187      goto f_err;
2188    }
2189
2190    if (is_first_certificate && s->ctx->retain_only_sha256_of_client_certs) {
2191      /* If this is the first certificate, and we don't want to keep peer
2192       * certificates in memory, then we hash it right away. */
2193      SHA256_Init(&sha256);
2194      SHA256_Update(&sha256, CBS_data(&certificate), CBS_len(&certificate));
2195      SHA256_Final(s->session->peer_sha256, &sha256);
2196      s->session->peer_sha256_valid = 1;
2197    }
2198    is_first_certificate = 0;
2199
2200    data = CBS_data(&certificate);
2201    x = d2i_X509(NULL, &data, CBS_len(&certificate));
2202    if (x == NULL) {
2203      al = SSL_AD_BAD_CERTIFICATE;
2204      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_ASN1_LIB);
2205      goto f_err;
2206    }
2207    if (data != CBS_data(&certificate) + CBS_len(&certificate)) {
2208      al = SSL_AD_DECODE_ERROR;
2209      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate,
2210                        SSL_R_CERT_LENGTH_MISMATCH);
2211      goto f_err;
2212    }
2213    if (!sk_X509_push(sk, x)) {
2214      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_MALLOC_FAILURE);
2215      goto err;
2216    }
2217    x = NULL;
2218  }
2219
2220  if (sk_X509_num(sk) <= 0) {
2221    /* TLS does not mind 0 certs returned */
2222    if (s->version == SSL3_VERSION) {
2223      al = SSL_AD_HANDSHAKE_FAILURE;
2224      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate,
2225                        SSL_R_NO_CERTIFICATES_RETURNED);
2226      goto f_err;
2227    }
2228    /* Fail for TLS only if we required a certificate */
2229    else if ((s->verify_mode & SSL_VERIFY_PEER) &&
2230             (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2231      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate,
2232                        SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2233      al = SSL_AD_HANDSHAKE_FAILURE;
2234      goto f_err;
2235    }
2236    /* No client certificate so digest cached records */
2237    if (s->s3->handshake_buffer &&
2238        !ssl3_digest_cached_records(s, free_handshake_buffer)) {
2239      al = SSL_AD_INTERNAL_ERROR;
2240      goto f_err;
2241    }
2242  } else {
2243    i = ssl_verify_cert_chain(s, sk);
2244    if (i <= 0) {
2245      al = ssl_verify_alarm_type(s->verify_result);
2246      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate,
2247                        SSL_R_CERTIFICATE_VERIFY_FAILED);
2248      goto f_err;
2249    }
2250  }
2251
2252  X509_free(s->session->peer);
2253  s->session->peer = sk_X509_shift(sk);
2254  s->session->verify_result = s->verify_result;
2255
2256  /* With the current implementation, sess_cert will always be NULL when we
2257   * arrive here. */
2258  if (s->session->sess_cert == NULL) {
2259    s->session->sess_cert = ssl_sess_cert_new();
2260    if (s->session->sess_cert == NULL) {
2261      OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_MALLOC_FAILURE);
2262      goto err;
2263    }
2264  }
2265  sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
2266  s->session->sess_cert->cert_chain = sk;
2267  /* Inconsistency alert: cert_chain does *not* include the peer's own
2268   * certificate, while we do include it in s3_clnt.c */
2269
2270  sk = NULL;
2271
2272  ret = 1;
2273
2274  if (0) {
2275  f_err:
2276    ssl3_send_alert(s, SSL3_AL_FATAL, al);
2277  }
2278
2279err:
2280  X509_free(x);
2281  sk_X509_pop_free(sk, X509_free);
2282  return ret;
2283}
2284
2285int ssl3_send_server_certificate(SSL *s) {
2286  CERT_PKEY *cpk;
2287
2288  if (s->state == SSL3_ST_SW_CERT_A) {
2289    cpk = ssl_get_server_send_pkey(s);
2290    if (cpk == NULL) {
2291      OPENSSL_PUT_ERROR(SSL, ssl3_send_server_certificate,
2292                        ERR_R_INTERNAL_ERROR);
2293      return 0;
2294    }
2295
2296    if (!ssl3_output_cert_chain(s, cpk)) {
2297      return 0;
2298    }
2299    s->state = SSL3_ST_SW_CERT_B;
2300  }
2301
2302  /* SSL3_ST_SW_CERT_B */
2303  return ssl_do_write(s);
2304}
2305
2306/* send a new session ticket (not necessarily for a new session) */
2307int ssl3_send_new_session_ticket(SSL *s) {
2308  int ret = -1;
2309  uint8_t *session = NULL;
2310  size_t session_len;
2311  EVP_CIPHER_CTX ctx;
2312  HMAC_CTX hctx;
2313
2314  EVP_CIPHER_CTX_init(&ctx);
2315  HMAC_CTX_init(&hctx);
2316
2317  if (s->state == SSL3_ST_SW_SESSION_TICKET_A) {
2318    uint8_t *p, *macstart;
2319    int len;
2320    unsigned int hlen;
2321    SSL_CTX *tctx = s->initial_ctx;
2322    uint8_t iv[EVP_MAX_IV_LENGTH];
2323    uint8_t key_name[16];
2324    /* The maximum overhead of encrypting the session is 16 (key name) + IV +
2325     * one block of encryption overhead + HMAC.  */
2326    const size_t max_ticket_overhead =
2327        16 + EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE;
2328
2329    /* Serialize the SSL_SESSION to be encoded into the ticket. */
2330    if (!SSL_SESSION_to_bytes_for_ticket(s->session, &session, &session_len)) {
2331      goto err;
2332    }
2333
2334    /* If the session is too long, emit a dummy value rather than abort the
2335     * connection. */
2336    if (session_len > 0xFFFF - max_ticket_overhead) {
2337      static const char kTicketPlaceholder[] = "TICKET TOO LARGE";
2338      const size_t placeholder_len = strlen(kTicketPlaceholder);
2339
2340      OPENSSL_free(session);
2341      session = NULL;
2342
2343      p = ssl_handshake_start(s);
2344      /* Emit ticket_lifetime_hint. */
2345      l2n(0, p);
2346      /* Emit ticket. */
2347      s2n(placeholder_len, p);
2348      memcpy(p, kTicketPlaceholder, placeholder_len);
2349      p += placeholder_len;
2350
2351      len = p - ssl_handshake_start(s);
2352      if (!ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len)) {
2353        goto err;
2354      }
2355      s->state = SSL3_ST_SW_SESSION_TICKET_B;
2356      return ssl_do_write(s);
2357    }
2358
2359    /* Grow buffer if need be: the length calculation is as follows:
2360     * handshake_header_length + 4 (ticket lifetime hint) + 2 (ticket length) +
2361     * max_ticket_overhead + * session_length */
2362    if (!BUF_MEM_grow(s->init_buf, SSL_HM_HEADER_LENGTH(s) + 6 +
2363                                       max_ticket_overhead + session_len)) {
2364      goto err;
2365    }
2366    p = ssl_handshake_start(s);
2367    /* Initialize HMAC and cipher contexts. If callback present it does all the
2368     * work otherwise use generated values from parent ctx. */
2369    if (tctx->tlsext_ticket_key_cb) {
2370      if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx, &hctx,
2371                                     1 /* encrypt */) < 0) {
2372        goto err;
2373      }
2374    } else {
2375      if (!RAND_bytes(iv, 16) ||
2376          !EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
2377                              tctx->tlsext_tick_aes_key, iv) ||
2378          !HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16, tlsext_tick_md(),
2379                        NULL)) {
2380        goto err;
2381      }
2382      memcpy(key_name, tctx->tlsext_tick_key_name, 16);
2383    }
2384
2385    /* Ticket lifetime hint (advisory only): We leave this unspecified for
2386     * resumed session (for simplicity), and guess that tickets for new
2387     * sessions will live as long as their sessions. */
2388    l2n(s->hit ? 0 : s->session->timeout, p);
2389
2390    /* Skip ticket length for now */
2391    p += 2;
2392    /* Output key name */
2393    macstart = p;
2394    memcpy(p, key_name, 16);
2395    p += 16;
2396    /* output IV */
2397    memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
2398    p += EVP_CIPHER_CTX_iv_length(&ctx);
2399    /* Encrypt session data */
2400    if (!EVP_EncryptUpdate(&ctx, p, &len, session, session_len)) {
2401      goto err;
2402    }
2403    p += len;
2404    if (!EVP_EncryptFinal_ex(&ctx, p, &len)) {
2405      goto err;
2406    }
2407    p += len;
2408
2409    if (!HMAC_Update(&hctx, macstart, p - macstart) ||
2410        !HMAC_Final(&hctx, p, &hlen)) {
2411      goto err;
2412    }
2413
2414    p += hlen;
2415    /* Now write out lengths: p points to end of data written */
2416    /* Total length */
2417    len = p - ssl_handshake_start(s);
2418    /* Skip ticket lifetime hint */
2419    p = ssl_handshake_start(s) + 4;
2420    s2n(len - 6, p);
2421    if (!ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len)) {
2422      goto err;
2423    }
2424    s->state = SSL3_ST_SW_SESSION_TICKET_B;
2425  }
2426
2427  /* SSL3_ST_SW_SESSION_TICKET_B */
2428  ret = ssl_do_write(s);
2429
2430err:
2431  OPENSSL_free(session);
2432  EVP_CIPHER_CTX_cleanup(&ctx);
2433  HMAC_CTX_cleanup(&hctx);
2434  return ret;
2435}
2436
2437/* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It
2438 * sets the next_proto member in s if found */
2439int ssl3_get_next_proto(SSL *s) {
2440  int ok;
2441  long n;
2442  CBS next_protocol, selected_protocol, padding;
2443
2444  /* Clients cannot send a NextProtocol message if we didn't see the extension
2445   * in their ClientHello */
2446  if (!s->s3->next_proto_neg_seen) {
2447    OPENSSL_PUT_ERROR(SSL, ssl3_get_next_proto,
2448                      SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
2449    return -1;
2450  }
2451
2452  n = s->method->ssl_get_message(s, SSL3_ST_SR_NEXT_PROTO_A,
2453                                 SSL3_ST_SR_NEXT_PROTO_B, SSL3_MT_NEXT_PROTO,
2454                                 514, /* See the payload format below */
2455                                 ssl_hash_message, &ok);
2456
2457  if (!ok) {
2458    return n;
2459  }
2460
2461  /* s->state doesn't reflect whether ChangeCipherSpec has been received in
2462   * this handshake, but s->s3->change_cipher_spec does (will be reset by
2463   * ssl3_get_finished).
2464   *
2465   * TODO(davidben): Is this check now redundant with
2466   * SSL3_FLAGS_EXPECT_CCS? */
2467  if (!s->s3->change_cipher_spec) {
2468    OPENSSL_PUT_ERROR(SSL, ssl3_get_next_proto,
2469                      SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
2470    return -1;
2471  }
2472
2473  CBS_init(&next_protocol, s->init_msg, n);
2474
2475  /* The payload looks like:
2476   *   uint8 proto_len;
2477   *   uint8 proto[proto_len];
2478   *   uint8 padding_len;
2479   *   uint8 padding[padding_len]; */
2480  if (!CBS_get_u8_length_prefixed(&next_protocol, &selected_protocol) ||
2481      !CBS_get_u8_length_prefixed(&next_protocol, &padding) ||
2482      CBS_len(&next_protocol) != 0 ||
2483      !CBS_stow(&selected_protocol, &s->next_proto_negotiated,
2484                &s->next_proto_negotiated_len)) {
2485    return 0;
2486  }
2487
2488  return 1;
2489}
2490
2491/* ssl3_get_channel_id reads and verifies a ClientID handshake message. */
2492int ssl3_get_channel_id(SSL *s) {
2493  int ret = -1, ok;
2494  long n;
2495  EVP_MD_CTX md_ctx;
2496  uint8_t channel_id_hash[SHA256_DIGEST_LENGTH];
2497  unsigned int channel_id_hash_len;
2498  const uint8_t *p;
2499  uint16_t extension_type, expected_extension_type;
2500  EC_GROUP *p256 = NULL;
2501  EC_KEY *key = NULL;
2502  EC_POINT *point = NULL;
2503  ECDSA_SIG sig;
2504  BIGNUM x, y;
2505  CBS encrypted_extensions, extension;
2506
2507  n = s->method->ssl_get_message(
2508      s, SSL3_ST_SR_CHANNEL_ID_A, SSL3_ST_SR_CHANNEL_ID_B,
2509      SSL3_MT_ENCRYPTED_EXTENSIONS, 2 + 2 + TLSEXT_CHANNEL_ID_SIZE,
2510      ssl_dont_hash_message, &ok);
2511
2512  if (!ok) {
2513    return n;
2514  }
2515
2516  /* Before incorporating the EncryptedExtensions message to the handshake
2517   * hash, compute the hash that should have been signed. */
2518  channel_id_hash_len = sizeof(channel_id_hash);
2519  EVP_MD_CTX_init(&md_ctx);
2520  if (!EVP_DigestInit_ex(&md_ctx, EVP_sha256(), NULL) ||
2521      !tls1_channel_id_hash(&md_ctx, s) ||
2522      !EVP_DigestFinal(&md_ctx, channel_id_hash, &channel_id_hash_len)) {
2523    EVP_MD_CTX_cleanup(&md_ctx);
2524    return -1;
2525  }
2526  EVP_MD_CTX_cleanup(&md_ctx);
2527  assert(channel_id_hash_len == SHA256_DIGEST_LENGTH);
2528
2529  if (!ssl3_hash_current_message(s)) {
2530    return -1;
2531  }
2532
2533  /* s->state doesn't reflect whether ChangeCipherSpec has been received in
2534   * this handshake, but s->s3->change_cipher_spec does (will be reset by
2535   * ssl3_get_finished).
2536   *
2537   * TODO(davidben): Is this check now redundant with SSL3_FLAGS_EXPECT_CCS? */
2538  if (!s->s3->change_cipher_spec) {
2539    OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id,
2540                      SSL_R_GOT_CHANNEL_ID_BEFORE_A_CCS);
2541    return -1;
2542  }
2543
2544  CBS_init(&encrypted_extensions, s->init_msg, n);
2545
2546  /* EncryptedExtensions could include multiple extensions, but the only
2547   * extension that could be negotiated is ChannelID, so there can only be one
2548   * entry.
2549   *
2550   * The payload looks like:
2551   *   uint16 extension_type
2552   *   uint16 extension_len;
2553   *   uint8 x[32];
2554   *   uint8 y[32];
2555   *   uint8 r[32];
2556   *   uint8 s[32]; */
2557  expected_extension_type = TLSEXT_TYPE_channel_id;
2558  if (s->s3->tlsext_channel_id_new) {
2559    expected_extension_type = TLSEXT_TYPE_channel_id_new;
2560  }
2561
2562  if (!CBS_get_u16(&encrypted_extensions, &extension_type) ||
2563      !CBS_get_u16_length_prefixed(&encrypted_extensions, &extension) ||
2564      CBS_len(&encrypted_extensions) != 0 ||
2565      extension_type != expected_extension_type ||
2566      CBS_len(&extension) != TLSEXT_CHANNEL_ID_SIZE) {
2567    OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id, SSL_R_INVALID_MESSAGE);
2568    return -1;
2569  }
2570
2571  p256 = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
2572  if (!p256) {
2573    OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id, SSL_R_NO_P256_SUPPORT);
2574    return -1;
2575  }
2576
2577  BN_init(&x);
2578  BN_init(&y);
2579  sig.r = BN_new();
2580  sig.s = BN_new();
2581  if (sig.r == NULL || sig.s == NULL) {
2582    goto err;
2583  }
2584
2585  p = CBS_data(&extension);
2586  if (BN_bin2bn(p + 0, 32, &x) == NULL ||
2587      BN_bin2bn(p + 32, 32, &y) == NULL ||
2588      BN_bin2bn(p + 64, 32, sig.r) == NULL ||
2589      BN_bin2bn(p + 96, 32, sig.s) == NULL) {
2590    goto err;
2591  }
2592
2593  point = EC_POINT_new(p256);
2594  if (!point || !EC_POINT_set_affine_coordinates_GFp(p256, point, &x, &y, NULL)) {
2595    goto err;
2596  }
2597
2598  key = EC_KEY_new();
2599  if (!key || !EC_KEY_set_group(key, p256) ||
2600      !EC_KEY_set_public_key(key, point)) {
2601    goto err;
2602  }
2603
2604  /* We stored the handshake hash in |tlsext_channel_id| the first time that we
2605   * were called. */
2606  if (!ECDSA_do_verify(channel_id_hash, channel_id_hash_len, &sig, key)) {
2607    OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id,
2608                      SSL_R_CHANNEL_ID_SIGNATURE_INVALID);
2609    s->s3->tlsext_channel_id_valid = 0;
2610    goto err;
2611  }
2612
2613  memcpy(s->s3->tlsext_channel_id, p, 64);
2614  ret = 1;
2615
2616err:
2617  BN_free(&x);
2618  BN_free(&y);
2619  BN_free(sig.r);
2620  BN_free(sig.s);
2621  EC_KEY_free(key);
2622  EC_POINT_free(point);
2623  EC_GROUP_free(p256);
2624  return ret;
2625}
2626