1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57 /* ====================================================================
58  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  *    notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in
69  *    the documentation and/or other materials provided with the
70  *    distribution.
71  *
72  * 3. All advertising materials mentioning features or use of this
73  *    software must display the following acknowledgment:
74  *    "This product includes software developed by the OpenSSL Project
75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76  *
77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78  *    endorse or promote products derived from this software without
79  *    prior written permission. For written permission, please contact
80  *    openssl-core@openssl.org.
81  *
82  * 5. Products derived from this software may not be called "OpenSSL"
83  *    nor may "OpenSSL" appear in their names without prior written
84  *    permission of the OpenSSL Project.
85  *
86  * 6. Redistributions of any form whatsoever must retain the following
87  *    acknowledgment:
88  *    "This product includes software developed by the OpenSSL Project
89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90  *
91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102  * OF THE POSSIBILITY OF SUCH DAMAGE.
103  * ====================================================================
104  *
105  * This product includes cryptographic software written by Eric Young
106  * (eay@cryptsoft.com).  This product includes software written by Tim
107  * Hudson (tjh@cryptsoft.com).
108  *
109  */
110 /* ====================================================================
111  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
112  *
113  * Portions of the attached software ("Contribution") are developed by
114  * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
115  *
116  * The Contribution is licensed pursuant to the OpenSSL open source
117  * license provided above.
118  *
119  * ECC cipher suite support in OpenSSL originally written by
120  * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
121  *
122  */
123 /* ====================================================================
124  * Copyright 2005 Nokia. All rights reserved.
125  *
126  * The portions of the attached software ("Contribution") is developed by
127  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
128  * license.
129  *
130  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
131  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
132  * support (see RFC 4279) to OpenSSL.
133  *
134  * No patent licenses or other rights except those expressly stated in
135  * the OpenSSL open source license shall be deemed granted or received
136  * expressly, by implication, estoppel, or otherwise.
137  *
138  * No assurances are provided by Nokia that the Contribution does not
139  * infringe the patent or other intellectual property rights of any third
140  * party or that the license provides you with all the necessary rights
141  * to make use of the Contribution.
142  *
143  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
144  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
145  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
146  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
147  * OTHERWISE. */
148 
149 #include <openssl/ssl.h>
150 
151 #include <assert.h>
152 #include <string.h>
153 
154 #include <openssl/bn.h>
155 #include <openssl/buf.h>
156 #include <openssl/bytestring.h>
157 #include <openssl/cipher.h>
158 #include <openssl/dh.h>
159 #include <openssl/ec.h>
160 #include <openssl/ecdsa.h>
161 #include <openssl/err.h>
162 #include <openssl/evp.h>
163 #include <openssl/hmac.h>
164 #include <openssl/md5.h>
165 #include <openssl/mem.h>
166 #include <openssl/nid.h>
167 #include <openssl/rand.h>
168 #include <openssl/sha.h>
169 #include <openssl/x509.h>
170 
171 #include "internal.h"
172 #include "../crypto/internal.h"
173 #include "../crypto/dh/internal.h"
174 
175 
176 static int ssl3_get_initial_bytes(SSL *ssl);
177 static int ssl3_get_v2_client_hello(SSL *ssl);
178 static int ssl3_get_client_hello(SSL *ssl);
179 static int ssl3_send_server_hello(SSL *ssl);
180 static int ssl3_send_server_certificate(SSL *ssl);
181 static int ssl3_send_certificate_status(SSL *ssl);
182 static int ssl3_send_server_key_exchange(SSL *ssl);
183 static int ssl3_send_certificate_request(SSL *ssl);
184 static int ssl3_send_server_hello_done(SSL *ssl);
185 static int ssl3_get_client_certificate(SSL *ssl);
186 static int ssl3_get_client_key_exchange(SSL *ssl);
187 static int ssl3_get_cert_verify(SSL *ssl);
188 static int ssl3_get_next_proto(SSL *ssl);
189 static int ssl3_get_channel_id(SSL *ssl);
190 static int ssl3_send_new_session_ticket(SSL *ssl);
191 
ssl3_accept(SSL * ssl)192 int ssl3_accept(SSL *ssl) {
193   BUF_MEM *buf = NULL;
194   uint32_t alg_a;
195   int ret = -1;
196   int state, skip = 0;
197 
198   assert(ssl->handshake_func == ssl3_accept);
199   assert(ssl->server);
200 
201   for (;;) {
202     state = ssl->state;
203 
204     switch (ssl->state) {
205       case SSL_ST_ACCEPT:
206         ssl_do_info_callback(ssl, SSL_CB_HANDSHAKE_START, 1);
207 
208         if (ssl->init_buf == NULL) {
209           buf = BUF_MEM_new();
210           if (!buf || !BUF_MEM_reserve(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
211             ret = -1;
212             goto end;
213           }
214           ssl->init_buf = buf;
215           buf = NULL;
216         }
217         ssl->init_num = 0;
218 
219         /* Enable a write buffer. This groups handshake messages within a flight
220          * into a single write. */
221         if (!ssl_init_wbio_buffer(ssl)) {
222           ret = -1;
223           goto end;
224         }
225 
226         if (!ssl3_init_handshake_buffer(ssl)) {
227           OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
228           ret = -1;
229           goto end;
230         }
231 
232         if (!ssl->s3->have_version && !SSL_IS_DTLS(ssl)) {
233           ssl->state = SSL3_ST_SR_INITIAL_BYTES;
234         } else {
235           ssl->state = SSL3_ST_SR_CLNT_HELLO_A;
236         }
237         break;
238 
239       case SSL3_ST_SR_INITIAL_BYTES:
240         assert(!SSL_IS_DTLS(ssl));
241         ret = ssl3_get_initial_bytes(ssl);
242         if (ret <= 0) {
243           goto end;
244         }
245         /* ssl3_get_initial_bytes sets ssl->state to one of
246          * SSL3_ST_SR_V2_CLIENT_HELLO or SSL3_ST_SR_CLNT_HELLO_A on success. */
247         break;
248 
249       case SSL3_ST_SR_V2_CLIENT_HELLO:
250         assert(!SSL_IS_DTLS(ssl));
251         ret = ssl3_get_v2_client_hello(ssl);
252         if (ret <= 0) {
253           goto end;
254         }
255         ssl->state = SSL3_ST_SR_CLNT_HELLO_A;
256         break;
257 
258       case SSL3_ST_SR_CLNT_HELLO_A:
259       case SSL3_ST_SR_CLNT_HELLO_B:
260       case SSL3_ST_SR_CLNT_HELLO_C:
261         ret = ssl3_get_client_hello(ssl);
262         if (ret <= 0) {
263           goto end;
264         }
265         ssl->method->received_flight(ssl);
266         ssl->state = SSL3_ST_SW_SRVR_HELLO_A;
267         break;
268 
269       case SSL3_ST_SW_SRVR_HELLO_A:
270       case SSL3_ST_SW_SRVR_HELLO_B:
271         ret = ssl3_send_server_hello(ssl);
272         if (ret <= 0) {
273           goto end;
274         }
275         if (ssl->hit) {
276           if (ssl->tlsext_ticket_expected) {
277             ssl->state = SSL3_ST_SW_SESSION_TICKET_A;
278           } else {
279             ssl->state = SSL3_ST_SW_CHANGE_A;
280           }
281         } else {
282           ssl->state = SSL3_ST_SW_CERT_A;
283         }
284         break;
285 
286       case SSL3_ST_SW_CERT_A:
287       case SSL3_ST_SW_CERT_B:
288         if (ssl_cipher_uses_certificate_auth(ssl->s3->tmp.new_cipher)) {
289           ret = ssl3_send_server_certificate(ssl);
290           if (ret <= 0) {
291             goto end;
292           }
293           if (ssl->s3->tmp.certificate_status_expected) {
294             ssl->state = SSL3_ST_SW_CERT_STATUS_A;
295           } else {
296             ssl->state = SSL3_ST_SW_KEY_EXCH_A;
297           }
298         } else {
299           skip = 1;
300           ssl->state = SSL3_ST_SW_KEY_EXCH_A;
301         }
302         break;
303 
304       case SSL3_ST_SW_CERT_STATUS_A:
305       case SSL3_ST_SW_CERT_STATUS_B:
306         ret = ssl3_send_certificate_status(ssl);
307         if (ret <= 0) {
308           goto end;
309         }
310         ssl->state = SSL3_ST_SW_KEY_EXCH_A;
311         break;
312 
313       case SSL3_ST_SW_KEY_EXCH_A:
314       case SSL3_ST_SW_KEY_EXCH_B:
315       case SSL3_ST_SW_KEY_EXCH_C:
316         alg_a = ssl->s3->tmp.new_cipher->algorithm_auth;
317 
318         /* PSK ciphers send ServerKeyExchange if there is an identity hint. */
319         if (ssl_cipher_requires_server_key_exchange(ssl->s3->tmp.new_cipher) ||
320             ((alg_a & SSL_aPSK) && ssl->psk_identity_hint)) {
321           ret = ssl3_send_server_key_exchange(ssl);
322           if (ret <= 0) {
323             goto end;
324           }
325         } else {
326           skip = 1;
327         }
328 
329         ssl->state = SSL3_ST_SW_CERT_REQ_A;
330         break;
331 
332       case SSL3_ST_SW_CERT_REQ_A:
333       case SSL3_ST_SW_CERT_REQ_B:
334         if (ssl->s3->tmp.cert_request) {
335           ret = ssl3_send_certificate_request(ssl);
336           if (ret <= 0) {
337             goto end;
338           }
339         } else {
340           skip = 1;
341         }
342         ssl->state = SSL3_ST_SW_SRVR_DONE_A;
343         break;
344 
345       case SSL3_ST_SW_SRVR_DONE_A:
346       case SSL3_ST_SW_SRVR_DONE_B:
347         ret = ssl3_send_server_hello_done(ssl);
348         if (ret <= 0) {
349           goto end;
350         }
351         ssl->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
352         ssl->state = SSL3_ST_SW_FLUSH;
353         break;
354 
355       case SSL3_ST_SR_CERT_A:
356         if (ssl->s3->tmp.cert_request) {
357           ret = ssl3_get_client_certificate(ssl);
358           if (ret <= 0) {
359             goto end;
360           }
361         }
362         ssl->state = SSL3_ST_SR_KEY_EXCH_A;
363         break;
364 
365       case SSL3_ST_SR_KEY_EXCH_A:
366       case SSL3_ST_SR_KEY_EXCH_B:
367         ret = ssl3_get_client_key_exchange(ssl);
368         if (ret <= 0) {
369           goto end;
370         }
371         ssl->state = SSL3_ST_SR_CERT_VRFY_A;
372         break;
373 
374       case SSL3_ST_SR_CERT_VRFY_A:
375         ret = ssl3_get_cert_verify(ssl);
376         if (ret <= 0) {
377           goto end;
378         }
379 
380         ssl->state = SSL3_ST_SR_CHANGE;
381         break;
382 
383       case SSL3_ST_SR_CHANGE:
384         ret = ssl->method->ssl_read_change_cipher_spec(ssl);
385         if (ret <= 0) {
386           goto end;
387         }
388 
389         if (!tls1_change_cipher_state(ssl, SSL3_CHANGE_CIPHER_SERVER_READ)) {
390           ret = -1;
391           goto end;
392         }
393 
394         if (ssl->s3->next_proto_neg_seen) {
395           ssl->state = SSL3_ST_SR_NEXT_PROTO_A;
396         } else if (ssl->s3->tlsext_channel_id_valid) {
397           ssl->state = SSL3_ST_SR_CHANNEL_ID_A;
398         } else {
399           ssl->state = SSL3_ST_SR_FINISHED_A;
400         }
401         break;
402 
403       case SSL3_ST_SR_NEXT_PROTO_A:
404         ret = ssl3_get_next_proto(ssl);
405         if (ret <= 0) {
406           goto end;
407         }
408         if (ssl->s3->tlsext_channel_id_valid) {
409           ssl->state = SSL3_ST_SR_CHANNEL_ID_A;
410         } else {
411           ssl->state = SSL3_ST_SR_FINISHED_A;
412         }
413         break;
414 
415       case SSL3_ST_SR_CHANNEL_ID_A:
416         ret = ssl3_get_channel_id(ssl);
417         if (ret <= 0) {
418           goto end;
419         }
420         ssl->state = SSL3_ST_SR_FINISHED_A;
421         break;
422 
423       case SSL3_ST_SR_FINISHED_A:
424         ret = ssl3_get_finished(ssl);
425         if (ret <= 0) {
426           goto end;
427         }
428 
429         ssl->method->received_flight(ssl);
430         if (ssl->hit) {
431           ssl->state = SSL_ST_OK;
432         } else if (ssl->tlsext_ticket_expected) {
433           ssl->state = SSL3_ST_SW_SESSION_TICKET_A;
434         } else {
435           ssl->state = SSL3_ST_SW_CHANGE_A;
436         }
437 
438         /* If this is a full handshake with ChannelID then record the hashshake
439          * hashes in |ssl->session| in case we need them to verify a ChannelID
440          * signature on a resumption of this session in the future. */
441         if (!ssl->hit && ssl->s3->tlsext_channel_id_valid) {
442           ret = tls1_record_handshake_hashes_for_channel_id(ssl);
443           if (ret <= 0) {
444             goto end;
445           }
446         }
447         break;
448 
449       case SSL3_ST_SW_SESSION_TICKET_A:
450       case SSL3_ST_SW_SESSION_TICKET_B:
451         ret = ssl3_send_new_session_ticket(ssl);
452         if (ret <= 0) {
453           goto end;
454         }
455         ssl->state = SSL3_ST_SW_CHANGE_A;
456         break;
457 
458       case SSL3_ST_SW_CHANGE_A:
459       case SSL3_ST_SW_CHANGE_B:
460         ret = ssl->method->send_change_cipher_spec(ssl, SSL3_ST_SW_CHANGE_A,
461                                                    SSL3_ST_SW_CHANGE_B);
462         if (ret <= 0) {
463           goto end;
464         }
465         ssl->state = SSL3_ST_SW_FINISHED_A;
466 
467         if (!tls1_change_cipher_state(ssl, SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
468           ret = -1;
469           goto end;
470         }
471         break;
472 
473       case SSL3_ST_SW_FINISHED_A:
474       case SSL3_ST_SW_FINISHED_B:
475         ret = ssl3_send_finished(ssl, SSL3_ST_SW_FINISHED_A,
476                                  SSL3_ST_SW_FINISHED_B);
477         if (ret <= 0) {
478           goto end;
479         }
480         ssl->state = SSL3_ST_SW_FLUSH;
481         if (ssl->hit) {
482           ssl->s3->tmp.next_state = SSL3_ST_SR_CHANGE;
483         } else {
484           ssl->s3->tmp.next_state = SSL_ST_OK;
485         }
486         break;
487 
488       case SSL3_ST_SW_FLUSH:
489         if (BIO_flush(ssl->wbio) <= 0) {
490           ssl->rwstate = SSL_WRITING;
491           ret = -1;
492           goto end;
493         }
494 
495         ssl->state = ssl->s3->tmp.next_state;
496         if (ssl->state != SSL_ST_OK) {
497           ssl->method->expect_flight(ssl);
498         }
499         break;
500 
501       case SSL_ST_OK:
502         /* clean a few things up */
503         ssl3_cleanup_key_block(ssl);
504 
505         /* In DTLS, |init_buf| cannot be released because post-handshake
506          * retransmit relies on that buffer being available as scratch space.
507          *
508          * TODO(davidben): Fix this. */
509         if (!SSL_IS_DTLS(ssl)) {
510           BUF_MEM_free(ssl->init_buf);
511           ssl->init_buf = NULL;
512           ssl->init_num = 0;
513         }
514 
515         /* remove buffering on output */
516         ssl_free_wbio_buffer(ssl);
517 
518         /* If we aren't retaining peer certificates then we can discard it
519          * now. */
520         if (ssl->ctx->retain_only_sha256_of_client_certs) {
521           X509_free(ssl->session->peer);
522           ssl->session->peer = NULL;
523           sk_X509_pop_free(ssl->session->cert_chain, X509_free);
524           ssl->session->cert_chain = NULL;
525         }
526 
527         if (SSL_IS_DTLS(ssl)) {
528           ssl->d1->handshake_read_seq = 0;
529           ssl->d1->handshake_write_seq = 0;
530           ssl->d1->next_handshake_write_seq = 0;
531         }
532 
533         ssl->s3->initial_handshake_complete = 1;
534 
535         ssl_update_cache(ssl, SSL_SESS_CACHE_SERVER);
536 
537         ssl_do_info_callback(ssl, SSL_CB_HANDSHAKE_DONE, 1);
538 
539         ret = 1;
540         goto end;
541 
542       default:
543         OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_STATE);
544         ret = -1;
545         goto end;
546     }
547 
548     if (!ssl->s3->tmp.reuse_message && !skip && ssl->state != state) {
549       int new_state = ssl->state;
550       ssl->state = state;
551       ssl_do_info_callback(ssl, SSL_CB_ACCEPT_LOOP, 1);
552       ssl->state = new_state;
553     }
554     skip = 0;
555   }
556 
557 end:
558   BUF_MEM_free(buf);
559   ssl_do_info_callback(ssl, SSL_CB_ACCEPT_EXIT, ret);
560   return ret;
561 }
562 
ssl3_get_initial_bytes(SSL * ssl)563 static int ssl3_get_initial_bytes(SSL *ssl) {
564   /* Read the first 5 bytes, the size of the TLS record header. This is
565    * sufficient to detect a V2ClientHello and ensures that we never read beyond
566    * the first record. */
567   int ret = ssl_read_buffer_extend_to(ssl, SSL3_RT_HEADER_LENGTH);
568   if (ret <= 0) {
569     return ret;
570   }
571   assert(ssl_read_buffer_len(ssl) == SSL3_RT_HEADER_LENGTH);
572   const uint8_t *p = ssl_read_buffer(ssl);
573 
574   /* Some dedicated error codes for protocol mixups should the application wish
575    * to interpret them differently. (These do not overlap with ClientHello or
576    * V2ClientHello.) */
577   if (strncmp("GET ", (const char *)p, 4) == 0 ||
578       strncmp("POST ", (const char *)p, 5) == 0 ||
579       strncmp("HEAD ", (const char *)p, 5) == 0 ||
580       strncmp("PUT ", (const char *)p, 4) == 0) {
581     OPENSSL_PUT_ERROR(SSL, SSL_R_HTTP_REQUEST);
582     return -1;
583   }
584   if (strncmp("CONNE", (const char *)p, 5) == 0) {
585     OPENSSL_PUT_ERROR(SSL, SSL_R_HTTPS_PROXY_REQUEST);
586     return -1;
587   }
588 
589   /* Determine if this is a V2ClientHello. */
590   if ((p[0] & 0x80) && p[2] == SSL2_MT_CLIENT_HELLO &&
591       p[3] >= SSL3_VERSION_MAJOR) {
592     /* This is a V2ClientHello. */
593     ssl->state = SSL3_ST_SR_V2_CLIENT_HELLO;
594     return 1;
595   }
596 
597   /* Fall through to the standard logic. */
598   ssl->state = SSL3_ST_SR_CLNT_HELLO_A;
599   return 1;
600 }
601 
ssl3_get_v2_client_hello(SSL * ssl)602 static int ssl3_get_v2_client_hello(SSL *ssl) {
603   const uint8_t *p;
604   int ret;
605   CBS v2_client_hello, cipher_specs, session_id, challenge;
606   size_t msg_length, rand_len;
607   uint8_t msg_type;
608   uint16_t version, cipher_spec_length, session_id_length, challenge_length;
609   CBB client_hello, hello_body, cipher_suites;
610   uint8_t random[SSL3_RANDOM_SIZE];
611 
612   /* Determine the length of the V2ClientHello. */
613   assert(ssl_read_buffer_len(ssl) >= SSL3_RT_HEADER_LENGTH);
614   p = ssl_read_buffer(ssl);
615   msg_length = ((p[0] & 0x7f) << 8) | p[1];
616   if (msg_length > (1024 * 4)) {
617     OPENSSL_PUT_ERROR(SSL, SSL_R_RECORD_TOO_LARGE);
618     return -1;
619   }
620   if (msg_length < SSL3_RT_HEADER_LENGTH - 2) {
621     /* Reject lengths that are too short early. We have already read
622      * |SSL3_RT_HEADER_LENGTH| bytes, so we should not attempt to process an
623      * (invalid) V2ClientHello which would be shorter than that. */
624     OPENSSL_PUT_ERROR(SSL, SSL_R_RECORD_LENGTH_MISMATCH);
625     return -1;
626   }
627 
628   /* Read the remainder of the V2ClientHello. */
629   ret = ssl_read_buffer_extend_to(ssl, 2 + msg_length);
630   if (ret <= 0) {
631     return ret;
632   }
633   assert(ssl_read_buffer_len(ssl) == msg_length + 2);
634   CBS_init(&v2_client_hello, ssl_read_buffer(ssl) + 2, msg_length);
635 
636   /* The V2ClientHello without the length is incorporated into the handshake
637    * hash. */
638   if (!ssl3_update_handshake_hash(ssl, CBS_data(&v2_client_hello),
639                                   CBS_len(&v2_client_hello))) {
640     return -1;
641   }
642 
643   ssl_do_msg_callback(ssl, 0 /* read */, SSL2_VERSION, 0,
644                       CBS_data(&v2_client_hello), CBS_len(&v2_client_hello));
645 
646   if (!CBS_get_u8(&v2_client_hello, &msg_type) ||
647       !CBS_get_u16(&v2_client_hello, &version) ||
648       !CBS_get_u16(&v2_client_hello, &cipher_spec_length) ||
649       !CBS_get_u16(&v2_client_hello, &session_id_length) ||
650       !CBS_get_u16(&v2_client_hello, &challenge_length) ||
651       !CBS_get_bytes(&v2_client_hello, &cipher_specs, cipher_spec_length) ||
652       !CBS_get_bytes(&v2_client_hello, &session_id, session_id_length) ||
653       !CBS_get_bytes(&v2_client_hello, &challenge, challenge_length) ||
654       CBS_len(&v2_client_hello) != 0) {
655     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
656     return -1;
657   }
658 
659   /* msg_type has already been checked. */
660   assert(msg_type == SSL2_MT_CLIENT_HELLO);
661 
662   /* The client_random is the V2ClientHello challenge. Truncate or
663    * left-pad with zeros as needed. */
664   memset(random, 0, SSL3_RANDOM_SIZE);
665   rand_len = CBS_len(&challenge);
666   if (rand_len > SSL3_RANDOM_SIZE) {
667     rand_len = SSL3_RANDOM_SIZE;
668   }
669   memcpy(random + (SSL3_RANDOM_SIZE - rand_len), CBS_data(&challenge),
670          rand_len);
671 
672   /* Write out an equivalent SSLv3 ClientHello. */
673   CBB_zero(&client_hello);
674   if (!CBB_init_fixed(&client_hello, (uint8_t *)ssl->init_buf->data,
675                       ssl->init_buf->max) ||
676       !CBB_add_u8(&client_hello, SSL3_MT_CLIENT_HELLO) ||
677       !CBB_add_u24_length_prefixed(&client_hello, &hello_body) ||
678       !CBB_add_u16(&hello_body, version) ||
679       !CBB_add_bytes(&hello_body, random, SSL3_RANDOM_SIZE) ||
680       /* No session id. */
681       !CBB_add_u8(&hello_body, 0) ||
682       !CBB_add_u16_length_prefixed(&hello_body, &cipher_suites)) {
683     CBB_cleanup(&client_hello);
684     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
685     return -1;
686   }
687 
688   /* Copy the cipher suites. */
689   while (CBS_len(&cipher_specs) > 0) {
690     uint32_t cipher_spec;
691     if (!CBS_get_u24(&cipher_specs, &cipher_spec)) {
692       CBB_cleanup(&client_hello);
693       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
694       return -1;
695     }
696 
697     /* Skip SSLv2 ciphers. */
698     if ((cipher_spec & 0xff0000) != 0) {
699       continue;
700     }
701     if (!CBB_add_u16(&cipher_suites, cipher_spec)) {
702       CBB_cleanup(&client_hello);
703       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
704       return -1;
705     }
706   }
707 
708   /* Add the null compression scheme and finish. */
709   if (!CBB_add_u8(&hello_body, 1) || !CBB_add_u8(&hello_body, 0) ||
710       !CBB_finish(&client_hello, NULL, &ssl->init_buf->length)) {
711     CBB_cleanup(&client_hello);
712     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
713     return -1;
714   }
715 
716   /* Mark the message for "re"-use by the version-specific method. */
717   ssl->s3->tmp.reuse_message = 1;
718   ssl->s3->tmp.message_type = SSL3_MT_CLIENT_HELLO;
719   ssl->s3->tmp.message_complete = 1;
720 
721   /* Consume and discard the V2ClientHello. */
722   ssl_read_buffer_consume(ssl, 2 + msg_length);
723   ssl_read_buffer_discard(ssl);
724 
725   return 1;
726 }
727 
ssl3_get_client_hello(SSL * ssl)728 static int ssl3_get_client_hello(SSL *ssl) {
729   int ok, al = SSL_AD_INTERNAL_ERROR, ret = -1;
730   long n;
731   const SSL_CIPHER *c;
732   STACK_OF(SSL_CIPHER) *ciphers = NULL;
733   struct ssl_early_callback_ctx early_ctx;
734   CBS client_hello;
735   uint16_t client_version;
736   CBS client_random, session_id, cipher_suites, compression_methods;
737   SSL_SESSION *session = NULL;
738 
739   /* We do this so that we will respond with our native type. If we are TLSv1
740    * and we get SSLv3, we will respond with TLSv1, This down switching should
741    * be handled by a different method. If we are SSLv3, we will respond with
742    * SSLv3, even if prompted with TLSv1. */
743   switch (ssl->state) {
744     case SSL3_ST_SR_CLNT_HELLO_A:
745       n = ssl->method->ssl_get_message(ssl, SSL3_MT_CLIENT_HELLO,
746                                        ssl_hash_message, &ok);
747 
748       if (!ok) {
749         return n;
750       }
751 
752       ssl->state = SSL3_ST_SR_CLNT_HELLO_B;
753       /* fallthrough */
754     case SSL3_ST_SR_CLNT_HELLO_B:
755     case SSL3_ST_SR_CLNT_HELLO_C:
756       /* We have previously parsed the ClientHello message, and can't call
757        * ssl_get_message again without hashing the message into the Finished
758        * digest again. */
759       n = ssl->init_num;
760 
761       memset(&early_ctx, 0, sizeof(early_ctx));
762       early_ctx.ssl = ssl;
763       early_ctx.client_hello = ssl->init_msg;
764       early_ctx.client_hello_len = n;
765       if (!ssl_early_callback_init(&early_ctx)) {
766         al = SSL_AD_DECODE_ERROR;
767         OPENSSL_PUT_ERROR(SSL, SSL_R_CLIENTHELLO_PARSE_FAILED);
768         goto f_err;
769       }
770 
771       if (ssl->state == SSL3_ST_SR_CLNT_HELLO_B &&
772           ssl->ctx->select_certificate_cb != NULL) {
773         ssl->state = SSL3_ST_SR_CLNT_HELLO_C;
774         switch (ssl->ctx->select_certificate_cb(&early_ctx)) {
775           case 0:
776             ssl->rwstate = SSL_CERTIFICATE_SELECTION_PENDING;
777             goto err;
778 
779           case -1:
780             /* Connection rejected. */
781             al = SSL_AD_ACCESS_DENIED;
782             OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
783             goto f_err;
784 
785           default:
786             /* fallthrough */;
787         }
788       }
789       ssl->state = SSL3_ST_SR_CLNT_HELLO_C;
790       break;
791 
792     default:
793       OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_STATE);
794       return -1;
795   }
796 
797   CBS_init(&client_hello, ssl->init_msg, n);
798   if (!CBS_get_u16(&client_hello, &client_version) ||
799       !CBS_get_bytes(&client_hello, &client_random, SSL3_RANDOM_SIZE) ||
800       !CBS_get_u8_length_prefixed(&client_hello, &session_id) ||
801       CBS_len(&session_id) > SSL_MAX_SSL_SESSION_ID_LENGTH) {
802     al = SSL_AD_DECODE_ERROR;
803     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
804     goto f_err;
805   }
806 
807   /* use version from inside client hello, not from record header (may differ:
808    * see RFC 2246, Appendix E, second paragraph) */
809   ssl->client_version = client_version;
810 
811   /* Load the client random. */
812   memcpy(ssl->s3->client_random, CBS_data(&client_random), SSL3_RANDOM_SIZE);
813 
814   if (SSL_IS_DTLS(ssl)) {
815     CBS cookie;
816 
817     if (!CBS_get_u8_length_prefixed(&client_hello, &cookie) ||
818         CBS_len(&cookie) > DTLS1_COOKIE_LENGTH) {
819       al = SSL_AD_DECODE_ERROR;
820       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
821       goto f_err;
822     }
823   }
824 
825   /* Note: This codepath may run twice if |ssl_get_prev_session| completes
826    * asynchronously.
827    *
828    * TODO(davidben): Clean up the order of events around ClientHello
829    * processing. */
830   if (!ssl->s3->have_version) {
831     /* Select version to use */
832     uint16_t version = ssl3_get_mutual_version(ssl, client_version);
833     if (version == 0) {
834       OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_PROTOCOL);
835       ssl->version = ssl->client_version;
836       al = SSL_AD_PROTOCOL_VERSION;
837       goto f_err;
838     }
839     ssl->version = version;
840     ssl->s3->enc_method = ssl3_get_enc_method(version);
841     assert(ssl->s3->enc_method != NULL);
842     /* At this point, the connection's version is known and |ssl->version| is
843      * fixed. Begin enforcing the record-layer version. */
844     ssl->s3->have_version = 1;
845   } else if (SSL_IS_DTLS(ssl) ? (ssl->client_version > ssl->version)
846                             : (ssl->client_version < ssl->version)) {
847     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_VERSION_NUMBER);
848     al = SSL_AD_PROTOCOL_VERSION;
849     goto f_err;
850   }
851 
852   ssl->hit = 0;
853   int send_new_ticket = 0;
854   switch (ssl_get_prev_session(ssl, &session, &send_new_ticket, &early_ctx)) {
855     case ssl_session_success:
856       break;
857     case ssl_session_error:
858       goto err;
859     case ssl_session_retry:
860       ssl->rwstate = SSL_PENDING_SESSION;
861       goto err;
862   }
863   ssl->tlsext_ticket_expected = send_new_ticket;
864 
865   /* The EMS state is needed when making the resumption decision, but
866    * extensions are not normally parsed until later. This detects the EMS
867    * extension for the resumption decision and it's checked against the result
868    * of the normal parse later in this function. */
869   const uint8_t *ems_data;
870   size_t ems_len;
871   int have_extended_master_secret =
872       ssl->version != SSL3_VERSION &&
873       SSL_early_callback_ctx_extension_get(&early_ctx,
874                                            TLSEXT_TYPE_extended_master_secret,
875                                            &ems_data, &ems_len) &&
876       ems_len == 0;
877 
878   if (session != NULL) {
879     if (session->extended_master_secret &&
880         !have_extended_master_secret) {
881       /* A ClientHello without EMS that attempts to resume a session with EMS
882        * is fatal to the connection. */
883       al = SSL_AD_HANDSHAKE_FAILURE;
884       OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
885       goto f_err;
886     }
887 
888     ssl->hit =
889         /* Only resume if the session's version matches the negotiated version:
890          * most clients do not accept a mismatch. */
891         ssl->version == session->ssl_version &&
892         /* If the client offers the EMS extension, but the previous session
893          * didn't use it, then negotiate a new session. */
894         have_extended_master_secret == session->extended_master_secret;
895   }
896 
897   if (ssl->hit) {
898     /* Use the new session. */
899     SSL_SESSION_free(ssl->session);
900     ssl->session = session;
901     session = NULL;
902 
903     ssl->verify_result = ssl->session->verify_result;
904   } else {
905     if (!ssl_get_new_session(ssl, 1 /* server */)) {
906       goto err;
907     }
908 
909     /* Clear the session ID if we want the session to be single-use. */
910     if (!(ssl->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)) {
911       ssl->session->session_id_length = 0;
912     }
913   }
914 
915   if (ssl->ctx->dos_protection_cb != NULL &&
916       ssl->ctx->dos_protection_cb(&early_ctx) == 0) {
917     /* Connection rejected for DOS reasons. */
918     al = SSL_AD_ACCESS_DENIED;
919     OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
920     goto f_err;
921   }
922 
923   if (!CBS_get_u16_length_prefixed(&client_hello, &cipher_suites) ||
924       CBS_len(&cipher_suites) == 0 ||
925       CBS_len(&cipher_suites) % 2 != 0 ||
926       !CBS_get_u8_length_prefixed(&client_hello, &compression_methods) ||
927       CBS_len(&compression_methods) == 0) {
928     al = SSL_AD_DECODE_ERROR;
929     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
930     goto f_err;
931   }
932 
933   ciphers = ssl_bytes_to_cipher_list(ssl, &cipher_suites);
934   if (ciphers == NULL) {
935     goto err;
936   }
937 
938   /* If it is a hit, check that the cipher is in the list. */
939   if (ssl->hit) {
940     size_t j;
941     int found_cipher = 0;
942     uint32_t id = ssl->session->cipher->id;
943 
944     for (j = 0; j < sk_SSL_CIPHER_num(ciphers); j++) {
945       c = sk_SSL_CIPHER_value(ciphers, j);
946       if (c->id == id) {
947         found_cipher = 1;
948         break;
949       }
950     }
951 
952     if (!found_cipher) {
953       /* we need to have the cipher in the cipher list if we are asked to reuse
954        * it */
955       al = SSL_AD_ILLEGAL_PARAMETER;
956       OPENSSL_PUT_ERROR(SSL, SSL_R_REQUIRED_CIPHER_MISSING);
957       goto f_err;
958     }
959   }
960 
961   /* Only null compression is supported. */
962   if (memchr(CBS_data(&compression_methods), 0,
963              CBS_len(&compression_methods)) == NULL) {
964     al = SSL_AD_ILLEGAL_PARAMETER;
965     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_COMPRESSION_SPECIFIED);
966     goto f_err;
967   }
968 
969   /* TLS extensions. */
970   if (ssl->version >= SSL3_VERSION &&
971       !ssl_parse_clienthello_tlsext(ssl, &client_hello)) {
972     OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
973     goto err;
974   }
975 
976   /* There should be nothing left over in the record. */
977   if (CBS_len(&client_hello) != 0) {
978     /* wrong packet length */
979     al = SSL_AD_DECODE_ERROR;
980     OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_PACKET_LENGTH);
981     goto f_err;
982   }
983 
984   if (have_extended_master_secret != ssl->s3->tmp.extended_master_secret) {
985     al = SSL_AD_INTERNAL_ERROR;
986     OPENSSL_PUT_ERROR(SSL, SSL_R_EMS_STATE_INCONSISTENT);
987     goto f_err;
988   }
989 
990   /* Given ciphers and SSL_get_ciphers, we must pick a cipher */
991   if (!ssl->hit) {
992     if (ciphers == NULL) {
993       al = SSL_AD_ILLEGAL_PARAMETER;
994       OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CIPHERS_PASSED);
995       goto f_err;
996     }
997 
998     /* Let cert callback update server certificates if required */
999     if (ssl->cert->cert_cb) {
1000       int rv = ssl->cert->cert_cb(ssl, ssl->cert->cert_cb_arg);
1001       if (rv == 0) {
1002         al = SSL_AD_INTERNAL_ERROR;
1003         OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_CB_ERROR);
1004         goto f_err;
1005       }
1006       if (rv < 0) {
1007         ssl->rwstate = SSL_X509_LOOKUP;
1008         goto err;
1009       }
1010     }
1011     c = ssl3_choose_cipher(ssl, ciphers, ssl_get_cipher_preferences(ssl));
1012 
1013     if (c == NULL) {
1014       al = SSL_AD_HANDSHAKE_FAILURE;
1015       OPENSSL_PUT_ERROR(SSL, SSL_R_NO_SHARED_CIPHER);
1016       goto f_err;
1017     }
1018     ssl->session->cipher = c;
1019     ssl->s3->tmp.new_cipher = c;
1020 
1021     /* Determine whether to request a client certificate. */
1022     ssl->s3->tmp.cert_request = !!(ssl->verify_mode & SSL_VERIFY_PEER);
1023     /* Only request a certificate if Channel ID isn't negotiated. */
1024     if ((ssl->verify_mode & SSL_VERIFY_PEER_IF_NO_OBC) &&
1025         ssl->s3->tlsext_channel_id_valid) {
1026       ssl->s3->tmp.cert_request = 0;
1027     }
1028     /* CertificateRequest may only be sent in certificate-based ciphers. */
1029     if (!ssl_cipher_uses_certificate_auth(ssl->s3->tmp.new_cipher)) {
1030       ssl->s3->tmp.cert_request = 0;
1031     }
1032   } else {
1033     /* Session-id reuse */
1034     ssl->s3->tmp.new_cipher = ssl->session->cipher;
1035     ssl->s3->tmp.cert_request = 0;
1036   }
1037 
1038   /* Now that the cipher is known, initialize the handshake hash. */
1039   if (!ssl3_init_handshake_hash(ssl)) {
1040     goto f_err;
1041   }
1042 
1043   /* In TLS 1.2, client authentication requires hashing the handshake transcript
1044    * under a different hash. Otherwise, release the handshake buffer. */
1045   if (!ssl->s3->tmp.cert_request ||
1046       ssl3_protocol_version(ssl) < TLS1_2_VERSION) {
1047     ssl3_free_handshake_buffer(ssl);
1048   }
1049 
1050   /* we now have the following setup;
1051    * client_random
1052    * cipher_list        - our prefered list of ciphers
1053    * ciphers            - the clients prefered list of ciphers
1054    * compression        - basically ignored right now
1055    * ssl version is set - sslv3
1056    * ssl->session         - The ssl session has been setup.
1057    * ssl->hit             - session reuse flag
1058    * ssl->tmp.new_cipher  - the new cipher to use. */
1059 
1060   ret = 1;
1061 
1062   if (0) {
1063   f_err:
1064     ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
1065   }
1066 
1067 err:
1068   sk_SSL_CIPHER_free(ciphers);
1069   SSL_SESSION_free(session);
1070   return ret;
1071 }
1072 
ssl3_send_server_hello(SSL * ssl)1073 static int ssl3_send_server_hello(SSL *ssl) {
1074   if (ssl->state == SSL3_ST_SW_SRVR_HELLO_B) {
1075     return ssl_do_write(ssl);
1076   }
1077 
1078   assert(ssl->state == SSL3_ST_SW_SRVR_HELLO_A);
1079 
1080   /* We only accept ChannelIDs on connections with ECDHE in order to avoid a
1081    * known attack while we fix ChannelID itself. */
1082   if (ssl->s3->tlsext_channel_id_valid &&
1083       (ssl->s3->tmp.new_cipher->algorithm_mkey & SSL_kECDHE) == 0) {
1084     ssl->s3->tlsext_channel_id_valid = 0;
1085   }
1086 
1087   /* If this is a resumption and the original handshake didn't support
1088    * ChannelID then we didn't record the original handshake hashes in the
1089    * session and so cannot resume with ChannelIDs. */
1090   if (ssl->hit && ssl->session->original_handshake_hash_len == 0) {
1091     ssl->s3->tlsext_channel_id_valid = 0;
1092   }
1093 
1094   if (!ssl_fill_hello_random(ssl->s3->server_random, SSL3_RANDOM_SIZE,
1095                              1 /* server */)) {
1096     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1097     return -1;
1098   }
1099 
1100   CBB cbb, session_id;
1101   size_t length;
1102   CBB_zero(&cbb);
1103   if (!CBB_init_fixed(&cbb, ssl_handshake_start(ssl),
1104                       ssl->init_buf->max - SSL_HM_HEADER_LENGTH(ssl)) ||
1105       !CBB_add_u16(&cbb, ssl->version) ||
1106       !CBB_add_bytes(&cbb, ssl->s3->server_random, SSL3_RANDOM_SIZE) ||
1107       !CBB_add_u8_length_prefixed(&cbb, &session_id) ||
1108       !CBB_add_bytes(&session_id, ssl->session->session_id,
1109                      ssl->session->session_id_length) ||
1110       !CBB_add_u16(&cbb, ssl_cipher_get_value(ssl->s3->tmp.new_cipher)) ||
1111       !CBB_add_u8(&cbb, 0 /* no compression */) ||
1112       !ssl_add_serverhello_tlsext(ssl, &cbb) ||
1113       !CBB_finish(&cbb, NULL, &length) ||
1114       !ssl_set_handshake_header(ssl, SSL3_MT_SERVER_HELLO, length)) {
1115     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1116     CBB_cleanup(&cbb);
1117     return -1;
1118   }
1119 
1120   ssl->state = SSL3_ST_SW_SRVR_HELLO_B;
1121   return ssl_do_write(ssl);
1122 }
1123 
ssl3_send_server_certificate(SSL * ssl)1124 static int ssl3_send_server_certificate(SSL *ssl) {
1125   if (ssl->state == SSL3_ST_SW_CERT_A) {
1126     if (!ssl3_output_cert_chain(ssl)) {
1127       return 0;
1128     }
1129     ssl->state = SSL3_ST_SW_CERT_B;
1130   }
1131 
1132   /* SSL3_ST_SW_CERT_B */
1133   return ssl_do_write(ssl);
1134 }
1135 
ssl3_send_certificate_status(SSL * ssl)1136 static int ssl3_send_certificate_status(SSL *ssl) {
1137   if (ssl->state == SSL3_ST_SW_CERT_STATUS_A) {
1138     CBB out, ocsp_response;
1139     size_t length;
1140 
1141     CBB_zero(&out);
1142     if (!CBB_init_fixed(&out, ssl_handshake_start(ssl),
1143                         ssl->init_buf->max - SSL_HM_HEADER_LENGTH(ssl)) ||
1144         !CBB_add_u8(&out, TLSEXT_STATUSTYPE_ocsp) ||
1145         !CBB_add_u24_length_prefixed(&out, &ocsp_response) ||
1146         !CBB_add_bytes(&ocsp_response, ssl->ctx->ocsp_response,
1147                        ssl->ctx->ocsp_response_length) ||
1148         !CBB_finish(&out, NULL, &length) ||
1149         !ssl_set_handshake_header(ssl, SSL3_MT_CERTIFICATE_STATUS, length)) {
1150       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1151       CBB_cleanup(&out);
1152       return -1;
1153     }
1154 
1155     ssl->state = SSL3_ST_SW_CERT_STATUS_B;
1156   }
1157 
1158   /* SSL3_ST_SW_CERT_STATUS_B */
1159   return ssl_do_write(ssl);
1160 }
1161 
ssl3_send_server_key_exchange(SSL * ssl)1162 static int ssl3_send_server_key_exchange(SSL *ssl) {
1163   if (ssl->state == SSL3_ST_SW_KEY_EXCH_C) {
1164     return ssl_do_write(ssl);
1165   }
1166 
1167   CBB cbb, child;
1168   if (!CBB_init_fixed(&cbb, ssl_handshake_start(ssl),
1169                       ssl->init_buf->max - SSL_HM_HEADER_LENGTH(ssl))) {
1170     goto err;
1171   }
1172 
1173   if (ssl->state == SSL3_ST_SW_KEY_EXCH_A) {
1174     /* This is the first iteration, so write parameters. */
1175     uint32_t alg_k = ssl->s3->tmp.new_cipher->algorithm_mkey;
1176     uint32_t alg_a = ssl->s3->tmp.new_cipher->algorithm_auth;
1177 
1178     /* PSK ciphers begin with an identity hint. */
1179     if (alg_a & SSL_aPSK) {
1180       size_t len =
1181           (ssl->psk_identity_hint == NULL) ? 0 : strlen(ssl->psk_identity_hint);
1182       if (!CBB_add_u16_length_prefixed(&cbb, &child) ||
1183           !CBB_add_bytes(&child, (const uint8_t *)ssl->psk_identity_hint,
1184                          len)) {
1185         goto err;
1186       }
1187     }
1188 
1189     if (alg_k & SSL_kDHE) {
1190       /* Determine the group to use. */
1191       DH *params = ssl->cert->dh_tmp;
1192       if (params == NULL && ssl->cert->dh_tmp_cb != NULL) {
1193         params = ssl->cert->dh_tmp_cb(ssl, 0, 1024);
1194       }
1195       if (params == NULL) {
1196         OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_TMP_DH_KEY);
1197         ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1198         goto err;
1199       }
1200       ssl->session->key_exchange_info = DH_num_bits(params);
1201 
1202       /* Set up DH, generate a key, and emit the public half. */
1203       DH *dh = DHparams_dup(params);
1204       if (dh == NULL) {
1205         goto err;
1206       }
1207 
1208       SSL_ECDH_CTX_init_for_dhe(&ssl->s3->tmp.ecdh_ctx, dh);
1209       if (!CBB_add_u16_length_prefixed(&cbb, &child) ||
1210           !BN_bn2cbb_padded(&child, BN_num_bytes(params->p), params->p) ||
1211           !CBB_add_u16_length_prefixed(&cbb, &child) ||
1212           !BN_bn2cbb_padded(&child, BN_num_bytes(params->g), params->g) ||
1213           !CBB_add_u16_length_prefixed(&cbb, &child) ||
1214           !SSL_ECDH_CTX_offer(&ssl->s3->tmp.ecdh_ctx, &child)) {
1215         goto err;
1216       }
1217     } else if (alg_k & SSL_kECDHE) {
1218       /* Determine the group to use. */
1219       uint16_t group_id;
1220       if (!tls1_get_shared_group(ssl, &group_id)) {
1221         OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_TMP_ECDH_KEY);
1222         ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1223         goto err;
1224       }
1225       ssl->session->key_exchange_info = group_id;
1226 
1227       /* Set up ECDH, generate a key, and emit the public half. */
1228       if (!SSL_ECDH_CTX_init(&ssl->s3->tmp.ecdh_ctx, group_id) ||
1229           !CBB_add_u8(&cbb, NAMED_CURVE_TYPE) ||
1230           !CBB_add_u16(&cbb, group_id) ||
1231           !CBB_add_u8_length_prefixed(&cbb, &child) ||
1232           !SSL_ECDH_CTX_offer(&ssl->s3->tmp.ecdh_ctx, &child)) {
1233         goto err;
1234       }
1235     } else if (alg_k & SSL_kCECPQ1) {
1236       if (!SSL_ECDH_CTX_init(&ssl->s3->tmp.ecdh_ctx, SSL_GROUP_CECPQ1) ||
1237           !CBB_add_u16_length_prefixed(&cbb, &child) ||
1238           !SSL_ECDH_CTX_offer(&ssl->s3->tmp.ecdh_ctx, &child)) {
1239         goto err;
1240       }
1241     } else {
1242       assert(alg_k & SSL_kPSK);
1243     }
1244 
1245     /* Otherwise, restore |cbb| from the previous iteration.
1246      * TODO(davidben): When |ssl->init_buf| is gone, come up with a simpler
1247      * pattern. Probably keep the |CBB| around in the handshake state. */
1248   } else if (!CBB_did_write(&cbb, ssl->init_num - SSL_HM_HEADER_LENGTH(ssl))) {
1249     goto err;
1250   }
1251 
1252   /* Add a signature. */
1253   if (ssl_cipher_uses_certificate_auth(ssl->s3->tmp.new_cipher)) {
1254     if (!ssl_has_private_key(ssl)) {
1255       ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1256       goto err;
1257     }
1258 
1259     const size_t max_sig_len = ssl_private_key_max_signature_len(ssl);
1260     size_t sig_len;
1261     enum ssl_private_key_result_t sign_result;
1262     if (ssl->state == SSL3_ST_SW_KEY_EXCH_A) {
1263       /* This is the first iteration, so set up the signature. Sample the
1264        * parameter length before adding a signature algorithm. */
1265       if (!CBB_flush(&cbb)) {
1266         goto err;
1267       }
1268       size_t params_len = CBB_len(&cbb);
1269 
1270       /* Determine signature algorithm. */
1271       const EVP_MD *md;
1272       if (ssl3_protocol_version(ssl) >= TLS1_2_VERSION) {
1273         md = tls1_choose_signing_digest(ssl);
1274         if (!tls12_add_sigandhash(ssl, &cbb, md)) {
1275           OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1276           ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1277           goto err;
1278         }
1279       } else if (ssl_private_key_type(ssl) == EVP_PKEY_RSA) {
1280         md = EVP_md5_sha1();
1281       } else {
1282         md = EVP_sha1();
1283       }
1284 
1285       /* Compute the digest and sign it. */
1286       uint8_t digest[EVP_MAX_MD_SIZE];
1287       unsigned digest_len = 0;
1288       EVP_MD_CTX md_ctx;
1289       EVP_MD_CTX_init(&md_ctx);
1290       int digest_ret =
1291           EVP_DigestInit_ex(&md_ctx, md, NULL) &&
1292           EVP_DigestUpdate(&md_ctx, ssl->s3->client_random, SSL3_RANDOM_SIZE) &&
1293           EVP_DigestUpdate(&md_ctx, ssl->s3->server_random, SSL3_RANDOM_SIZE) &&
1294           EVP_DigestUpdate(&md_ctx, CBB_data(&cbb), params_len) &&
1295           EVP_DigestFinal_ex(&md_ctx, digest, &digest_len);
1296       EVP_MD_CTX_cleanup(&md_ctx);
1297       uint8_t *ptr;
1298       if (!digest_ret ||
1299           !CBB_add_u16_length_prefixed(&cbb, &child) ||
1300           !CBB_reserve(&child, &ptr, max_sig_len)) {
1301         goto err;
1302       }
1303       sign_result = ssl_private_key_sign(ssl, ptr, &sig_len, max_sig_len, md,
1304                                          digest, digest_len);
1305     } else {
1306       assert(ssl->state == SSL3_ST_SW_KEY_EXCH_B);
1307 
1308       /* Retry the signature. */
1309       uint8_t *ptr;
1310       if (!CBB_add_u16_length_prefixed(&cbb, &child) ||
1311           !CBB_reserve(&child, &ptr, max_sig_len)) {
1312         goto err;
1313       }
1314       sign_result =
1315           ssl_private_key_sign_complete(ssl, ptr, &sig_len, max_sig_len);
1316     }
1317 
1318     switch (sign_result) {
1319       case ssl_private_key_success:
1320         if (!CBB_did_write(&child, sig_len)) {
1321           goto err;
1322         }
1323         break;
1324       case ssl_private_key_failure:
1325         goto err;
1326       case ssl_private_key_retry:
1327         /* Discard the unfinished signature and save the state of |cbb| for the
1328          * next iteration. */
1329         CBB_discard_child(&cbb);
1330         ssl->init_num = SSL_HM_HEADER_LENGTH(ssl) + CBB_len(&cbb);
1331         ssl->rwstate = SSL_PRIVATE_KEY_OPERATION;
1332         ssl->state = SSL3_ST_SW_KEY_EXCH_B;
1333         goto err;
1334     }
1335   }
1336 
1337   size_t length;
1338   if (!CBB_finish(&cbb, NULL, &length) ||
1339       !ssl_set_handshake_header(ssl, SSL3_MT_SERVER_KEY_EXCHANGE, length)) {
1340     goto err;
1341   }
1342   ssl->state = SSL3_ST_SW_KEY_EXCH_C;
1343   return ssl_do_write(ssl);
1344 
1345 err:
1346   CBB_cleanup(&cbb);
1347   return -1;
1348 }
1349 
ssl3_send_certificate_request(SSL * ssl)1350 static int ssl3_send_certificate_request(SSL *ssl) {
1351   uint8_t *p, *d;
1352   size_t i;
1353   int j, nl, off, n;
1354   STACK_OF(X509_NAME) *sk = NULL;
1355   X509_NAME *name;
1356   BUF_MEM *buf;
1357 
1358   if (ssl->state == SSL3_ST_SW_CERT_REQ_A) {
1359     buf = ssl->init_buf;
1360 
1361     d = p = ssl_handshake_start(ssl);
1362 
1363     /* get the list of acceptable cert types */
1364     p++;
1365     n = ssl3_get_req_cert_type(ssl, p);
1366     d[0] = n;
1367     p += n;
1368     n++;
1369 
1370     if (ssl3_protocol_version(ssl) >= TLS1_2_VERSION) {
1371       const uint8_t *psigs;
1372       nl = tls12_get_psigalgs(ssl, &psigs);
1373       s2n(nl, p);
1374       memcpy(p, psigs, nl);
1375       p += nl;
1376       n += nl + 2;
1377     }
1378 
1379     off = n;
1380     p += 2;
1381     n += 2;
1382 
1383     sk = SSL_get_client_CA_list(ssl);
1384     nl = 0;
1385     if (sk != NULL) {
1386       for (i = 0; i < sk_X509_NAME_num(sk); i++) {
1387         name = sk_X509_NAME_value(sk, i);
1388         j = i2d_X509_NAME(name, NULL);
1389         if (!BUF_MEM_grow_clean(buf, SSL_HM_HEADER_LENGTH(ssl) + n + j + 2)) {
1390           OPENSSL_PUT_ERROR(SSL, ERR_R_BUF_LIB);
1391           goto err;
1392         }
1393         p = ssl_handshake_start(ssl) + n;
1394         s2n(j, p);
1395         i2d_X509_NAME(name, &p);
1396         n += 2 + j;
1397         nl += 2 + j;
1398       }
1399     }
1400 
1401     /* else no CA names */
1402     p = ssl_handshake_start(ssl) + off;
1403     s2n(nl, p);
1404 
1405     if (!ssl_set_handshake_header(ssl, SSL3_MT_CERTIFICATE_REQUEST, n)) {
1406       goto err;
1407     }
1408     ssl->state = SSL3_ST_SW_CERT_REQ_B;
1409   }
1410 
1411   /* SSL3_ST_SW_CERT_REQ_B */
1412   return ssl_do_write(ssl);
1413 
1414 err:
1415   return -1;
1416 }
1417 
ssl3_send_server_hello_done(SSL * ssl)1418 static int ssl3_send_server_hello_done(SSL *ssl) {
1419   if (ssl->state == SSL3_ST_SW_SRVR_DONE_A) {
1420     if (!ssl_set_handshake_header(ssl, SSL3_MT_SERVER_HELLO_DONE, 0)) {
1421       return -1;
1422     }
1423     ssl->state = SSL3_ST_SW_SRVR_DONE_B;
1424   }
1425 
1426   /* SSL3_ST_SW_SRVR_DONE_B */
1427   return ssl_do_write(ssl);
1428 }
1429 
ssl3_get_client_certificate(SSL * ssl)1430 static int ssl3_get_client_certificate(SSL *ssl) {
1431   int ok, al, ret = -1;
1432   X509 *x = NULL;
1433   unsigned long n;
1434   STACK_OF(X509) *sk = NULL;
1435   SHA256_CTX sha256;
1436   CBS certificate_msg, certificate_list;
1437   int is_first_certificate = 1;
1438 
1439   assert(ssl->s3->tmp.cert_request);
1440   n = ssl->method->ssl_get_message(ssl, -1, ssl_hash_message, &ok);
1441 
1442   if (!ok) {
1443     return n;
1444   }
1445 
1446   if (ssl->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
1447     if (ssl->version == SSL3_VERSION &&
1448         ssl->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
1449       /* In SSL 3.0, the Certificate message is omitted to signal no certificate. */
1450       if ((ssl->verify_mode & SSL_VERIFY_PEER) &&
1451           (ssl->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
1452         OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
1453         al = SSL_AD_HANDSHAKE_FAILURE;
1454         goto f_err;
1455       }
1456 
1457       ssl->s3->tmp.reuse_message = 1;
1458       return 1;
1459     }
1460 
1461     al = SSL_AD_UNEXPECTED_MESSAGE;
1462     OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
1463     goto f_err;
1464   }
1465 
1466   CBS_init(&certificate_msg, ssl->init_msg, n);
1467 
1468   sk = sk_X509_new_null();
1469   if (sk == NULL) {
1470     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1471     goto err;
1472   }
1473 
1474   if (!CBS_get_u24_length_prefixed(&certificate_msg, &certificate_list) ||
1475       CBS_len(&certificate_msg) != 0) {
1476     al = SSL_AD_DECODE_ERROR;
1477     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1478     goto f_err;
1479   }
1480 
1481   while (CBS_len(&certificate_list) > 0) {
1482     CBS certificate;
1483     const uint8_t *data;
1484 
1485     if (!CBS_get_u24_length_prefixed(&certificate_list, &certificate)) {
1486       al = SSL_AD_DECODE_ERROR;
1487       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1488       goto f_err;
1489     }
1490 
1491     if (is_first_certificate && ssl->ctx->retain_only_sha256_of_client_certs) {
1492       /* If this is the first certificate, and we don't want to keep peer
1493        * certificates in memory, then we hash it right away. */
1494       SHA256_Init(&sha256);
1495       SHA256_Update(&sha256, CBS_data(&certificate), CBS_len(&certificate));
1496       SHA256_Final(ssl->session->peer_sha256, &sha256);
1497       ssl->session->peer_sha256_valid = 1;
1498     }
1499     is_first_certificate = 0;
1500 
1501     /* A u24 length cannot overflow a long. */
1502     data = CBS_data(&certificate);
1503     x = d2i_X509(NULL, &data, (long)CBS_len(&certificate));
1504     if (x == NULL) {
1505       al = SSL_AD_BAD_CERTIFICATE;
1506       OPENSSL_PUT_ERROR(SSL, ERR_R_ASN1_LIB);
1507       goto f_err;
1508     }
1509     if (data != CBS_data(&certificate) + CBS_len(&certificate)) {
1510       al = SSL_AD_DECODE_ERROR;
1511       OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_LENGTH_MISMATCH);
1512       goto f_err;
1513     }
1514     if (!sk_X509_push(sk, x)) {
1515       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1516       goto err;
1517     }
1518     x = NULL;
1519   }
1520 
1521   if (sk_X509_num(sk) <= 0) {
1522     /* No client certificate so the handshake buffer may be discarded. */
1523     ssl3_free_handshake_buffer(ssl);
1524 
1525     /* TLS does not mind 0 certs returned */
1526     if (ssl->version == SSL3_VERSION) {
1527       al = SSL_AD_HANDSHAKE_FAILURE;
1528       OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CERTIFICATES_RETURNED);
1529       goto f_err;
1530     } else if ((ssl->verify_mode & SSL_VERIFY_PEER) &&
1531                (ssl->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
1532       /* Fail for TLS only if we required a certificate */
1533       OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
1534       al = SSL_AD_HANDSHAKE_FAILURE;
1535       goto f_err;
1536     }
1537   } else {
1538     if (ssl_verify_cert_chain(ssl, sk) <= 0) {
1539       al = ssl_verify_alarm_type(ssl->verify_result);
1540       OPENSSL_PUT_ERROR(SSL, SSL_R_CERTIFICATE_VERIFY_FAILED);
1541       goto f_err;
1542     }
1543   }
1544 
1545   X509_free(ssl->session->peer);
1546   ssl->session->peer = sk_X509_shift(sk);
1547   ssl->session->verify_result = ssl->verify_result;
1548 
1549   sk_X509_pop_free(ssl->session->cert_chain, X509_free);
1550   ssl->session->cert_chain = sk;
1551   /* Inconsistency alert: cert_chain does *not* include the peer's own
1552    * certificate, while we do include it in s3_clnt.c */
1553 
1554   sk = NULL;
1555 
1556   ret = 1;
1557 
1558   if (0) {
1559   f_err:
1560     ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
1561   }
1562 
1563 err:
1564   X509_free(x);
1565   sk_X509_pop_free(sk, X509_free);
1566   return ret;
1567 }
1568 
ssl3_get_client_key_exchange(SSL * ssl)1569 static int ssl3_get_client_key_exchange(SSL *ssl) {
1570   int al;
1571   CBS client_key_exchange;
1572   uint32_t alg_k;
1573   uint32_t alg_a;
1574   uint8_t *premaster_secret = NULL;
1575   size_t premaster_secret_len = 0;
1576   uint8_t *decrypt_buf = NULL;
1577 
1578   unsigned psk_len = 0;
1579   uint8_t psk[PSK_MAX_PSK_LEN];
1580 
1581   if (ssl->state == SSL3_ST_SR_KEY_EXCH_A) {
1582     int ok;
1583     const long n = ssl->method->ssl_get_message(
1584         ssl, SSL3_MT_CLIENT_KEY_EXCHANGE, ssl_hash_message, &ok);
1585     if (!ok) {
1586       return n;
1587     }
1588   }
1589 
1590   CBS_init(&client_key_exchange, ssl->init_msg, ssl->init_num);
1591   alg_k = ssl->s3->tmp.new_cipher->algorithm_mkey;
1592   alg_a = ssl->s3->tmp.new_cipher->algorithm_auth;
1593 
1594   /* If using a PSK key exchange, prepare the pre-shared key. */
1595   if (alg_a & SSL_aPSK) {
1596     CBS psk_identity;
1597 
1598     /* If using PSK, the ClientKeyExchange contains a psk_identity. If PSK,
1599      * then this is the only field in the message. */
1600     if (!CBS_get_u16_length_prefixed(&client_key_exchange, &psk_identity) ||
1601         ((alg_k & SSL_kPSK) && CBS_len(&client_key_exchange) != 0)) {
1602       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1603       al = SSL_AD_DECODE_ERROR;
1604       goto f_err;
1605     }
1606 
1607     if (ssl->psk_server_callback == NULL) {
1608       OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_NO_SERVER_CB);
1609       al = SSL_AD_INTERNAL_ERROR;
1610       goto f_err;
1611     }
1612 
1613     if (CBS_len(&psk_identity) > PSK_MAX_IDENTITY_LEN ||
1614         CBS_contains_zero_byte(&psk_identity)) {
1615       OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
1616       al = SSL_AD_ILLEGAL_PARAMETER;
1617       goto f_err;
1618     }
1619 
1620     if (!CBS_strdup(&psk_identity, &ssl->session->psk_identity)) {
1621       al = SSL_AD_INTERNAL_ERROR;
1622       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1623       goto f_err;
1624     }
1625 
1626     /* Look up the key for the identity. */
1627     psk_len = ssl->psk_server_callback(ssl, ssl->session->psk_identity, psk,
1628                                        sizeof(psk));
1629     if (psk_len > PSK_MAX_PSK_LEN) {
1630       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1631       al = SSL_AD_INTERNAL_ERROR;
1632       goto f_err;
1633     } else if (psk_len == 0) {
1634       /* PSK related to the given identity not found */
1635       OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
1636       al = SSL_AD_UNKNOWN_PSK_IDENTITY;
1637       goto f_err;
1638     }
1639   }
1640 
1641   /* Depending on the key exchange method, compute |premaster_secret| and
1642    * |premaster_secret_len|. */
1643   if (alg_k & SSL_kRSA) {
1644     /* Allocate a buffer large enough for an RSA decryption. */
1645     const size_t rsa_size = ssl_private_key_max_signature_len(ssl);
1646     decrypt_buf = OPENSSL_malloc(rsa_size);
1647     if (decrypt_buf == NULL) {
1648       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1649       goto err;
1650     }
1651 
1652     enum ssl_private_key_result_t decrypt_result;
1653     size_t decrypt_len;
1654     if (ssl->state == SSL3_ST_SR_KEY_EXCH_A) {
1655       if (!ssl_has_private_key(ssl) ||
1656           ssl_private_key_type(ssl) != EVP_PKEY_RSA) {
1657         al = SSL_AD_HANDSHAKE_FAILURE;
1658         OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_RSA_CERTIFICATE);
1659         goto f_err;
1660       }
1661       CBS encrypted_premaster_secret;
1662       if (ssl->version > SSL3_VERSION) {
1663         if (!CBS_get_u16_length_prefixed(&client_key_exchange,
1664                                          &encrypted_premaster_secret) ||
1665             CBS_len(&client_key_exchange) != 0) {
1666           al = SSL_AD_DECODE_ERROR;
1667           OPENSSL_PUT_ERROR(SSL,
1668                             SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
1669           goto f_err;
1670         }
1671       } else {
1672         encrypted_premaster_secret = client_key_exchange;
1673       }
1674 
1675       /* Decrypt with no padding. PKCS#1 padding will be removed as part of the
1676        * timing-sensitive code below. */
1677       decrypt_result = ssl_private_key_decrypt(
1678           ssl, decrypt_buf, &decrypt_len, rsa_size,
1679           CBS_data(&encrypted_premaster_secret),
1680           CBS_len(&encrypted_premaster_secret));
1681     } else {
1682       assert(ssl->state == SSL3_ST_SR_KEY_EXCH_B);
1683       /* Complete async decrypt. */
1684       decrypt_result = ssl_private_key_decrypt_complete(
1685           ssl, decrypt_buf, &decrypt_len, rsa_size);
1686     }
1687 
1688     switch (decrypt_result) {
1689       case ssl_private_key_success:
1690         break;
1691       case ssl_private_key_failure:
1692         goto err;
1693       case ssl_private_key_retry:
1694         ssl->rwstate = SSL_PRIVATE_KEY_OPERATION;
1695         ssl->state = SSL3_ST_SR_KEY_EXCH_B;
1696         goto err;
1697     }
1698 
1699     if (decrypt_len != rsa_size) {
1700       al = SSL_AD_DECRYPT_ERROR;
1701       OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
1702       goto f_err;
1703     }
1704 
1705     /* Prepare a random premaster, to be used on invalid padding. See RFC 5246,
1706      * section 7.4.7.1. */
1707     premaster_secret_len = SSL_MAX_MASTER_KEY_LENGTH;
1708     premaster_secret = OPENSSL_malloc(premaster_secret_len);
1709     if (premaster_secret == NULL) {
1710       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1711       goto err;
1712     }
1713     if (!RAND_bytes(premaster_secret, premaster_secret_len)) {
1714       goto err;
1715     }
1716 
1717     /* The smallest padded premaster is 11 bytes of overhead. Small keys are
1718      * publicly invalid. */
1719     if (decrypt_len < 11 + premaster_secret_len) {
1720       al = SSL_AD_DECRYPT_ERROR;
1721       OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
1722       goto f_err;
1723     }
1724 
1725     /* Check the padding. See RFC 3447, section 7.2.2. */
1726     size_t padding_len = decrypt_len - premaster_secret_len;
1727     uint8_t good = constant_time_eq_int_8(decrypt_buf[0], 0) &
1728                    constant_time_eq_int_8(decrypt_buf[1], 2);
1729     size_t i;
1730     for (i = 2; i < padding_len - 1; i++) {
1731       good &= ~constant_time_is_zero_8(decrypt_buf[i]);
1732     }
1733     good &= constant_time_is_zero_8(decrypt_buf[padding_len - 1]);
1734 
1735     /* The premaster secret must begin with |client_version|. This too must be
1736      * checked in constant time (http://eprint.iacr.org/2003/052/). */
1737     good &= constant_time_eq_8(decrypt_buf[padding_len],
1738                                (unsigned)(ssl->client_version >> 8));
1739     good &= constant_time_eq_8(decrypt_buf[padding_len + 1],
1740                                (unsigned)(ssl->client_version & 0xff));
1741 
1742     /* Select, in constant time, either the decrypted premaster or the random
1743      * premaster based on |good|. */
1744     for (i = 0; i < premaster_secret_len; i++) {
1745       premaster_secret[i] = constant_time_select_8(
1746           good, decrypt_buf[padding_len + i], premaster_secret[i]);
1747     }
1748 
1749     OPENSSL_free(decrypt_buf);
1750     decrypt_buf = NULL;
1751   } else if (alg_k & (SSL_kECDHE|SSL_kDHE|SSL_kCECPQ1)) {
1752     /* Parse the ClientKeyExchange. */
1753     CBS peer_key;
1754     if (!SSL_ECDH_CTX_get_key(&ssl->s3->tmp.ecdh_ctx, &client_key_exchange,
1755                               &peer_key) ||
1756         CBS_len(&client_key_exchange) != 0) {
1757       al = SSL_AD_DECODE_ERROR;
1758       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1759       goto f_err;
1760     }
1761 
1762     /* Compute the premaster. */
1763     uint8_t alert;
1764     if (!SSL_ECDH_CTX_finish(&ssl->s3->tmp.ecdh_ctx, &premaster_secret,
1765                              &premaster_secret_len, &alert, CBS_data(&peer_key),
1766                              CBS_len(&peer_key))) {
1767       al = alert;
1768       goto f_err;
1769     }
1770 
1771     /* The key exchange state may now be discarded. */
1772     SSL_ECDH_CTX_cleanup(&ssl->s3->tmp.ecdh_ctx);
1773   } else if (alg_k & SSL_kPSK) {
1774     /* For plain PSK, other_secret is a block of 0s with the same length as the
1775      * pre-shared key. */
1776     premaster_secret_len = psk_len;
1777     premaster_secret = OPENSSL_malloc(premaster_secret_len);
1778     if (premaster_secret == NULL) {
1779       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1780       goto err;
1781     }
1782     memset(premaster_secret, 0, premaster_secret_len);
1783   } else {
1784     al = SSL_AD_HANDSHAKE_FAILURE;
1785     OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CIPHER_TYPE);
1786     goto f_err;
1787   }
1788 
1789   /* For a PSK cipher suite, the actual pre-master secret is combined with the
1790    * pre-shared key. */
1791   if (alg_a & SSL_aPSK) {
1792     CBB new_premaster, child;
1793     uint8_t *new_data;
1794     size_t new_len;
1795 
1796     CBB_zero(&new_premaster);
1797     if (!CBB_init(&new_premaster, 2 + psk_len + 2 + premaster_secret_len) ||
1798         !CBB_add_u16_length_prefixed(&new_premaster, &child) ||
1799         !CBB_add_bytes(&child, premaster_secret, premaster_secret_len) ||
1800         !CBB_add_u16_length_prefixed(&new_premaster, &child) ||
1801         !CBB_add_bytes(&child, psk, psk_len) ||
1802         !CBB_finish(&new_premaster, &new_data, &new_len)) {
1803       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1804       CBB_cleanup(&new_premaster);
1805       goto err;
1806     }
1807 
1808     OPENSSL_cleanse(premaster_secret, premaster_secret_len);
1809     OPENSSL_free(premaster_secret);
1810     premaster_secret = new_data;
1811     premaster_secret_len = new_len;
1812   }
1813 
1814   /* Compute the master secret */
1815   ssl->session->master_key_length = tls1_generate_master_secret(
1816       ssl, ssl->session->master_key, premaster_secret, premaster_secret_len);
1817   if (ssl->session->master_key_length == 0) {
1818     goto err;
1819   }
1820   ssl->session->extended_master_secret = ssl->s3->tmp.extended_master_secret;
1821 
1822   OPENSSL_cleanse(premaster_secret, premaster_secret_len);
1823   OPENSSL_free(premaster_secret);
1824   return 1;
1825 
1826 f_err:
1827   ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
1828 err:
1829   if (premaster_secret != NULL) {
1830     OPENSSL_cleanse(premaster_secret, premaster_secret_len);
1831     OPENSSL_free(premaster_secret);
1832   }
1833   OPENSSL_free(decrypt_buf);
1834 
1835   return -1;
1836 }
1837 
ssl3_get_cert_verify(SSL * ssl)1838 static int ssl3_get_cert_verify(SSL *ssl) {
1839   int al, ok, ret = 0;
1840   long n;
1841   CBS certificate_verify, signature;
1842   X509 *peer = ssl->session->peer;
1843   EVP_PKEY *pkey = NULL;
1844   const EVP_MD *md = NULL;
1845   uint8_t digest[EVP_MAX_MD_SIZE];
1846   size_t digest_length;
1847   EVP_PKEY_CTX *pctx = NULL;
1848 
1849   /* Only RSA and ECDSA client certificates are supported, so a
1850    * CertificateVerify is required if and only if there's a client certificate.
1851    * */
1852   if (peer == NULL) {
1853     ssl3_free_handshake_buffer(ssl);
1854     return 1;
1855   }
1856 
1857   n = ssl->method->ssl_get_message(ssl, SSL3_MT_CERTIFICATE_VERIFY,
1858                                    ssl_dont_hash_message, &ok);
1859 
1860   if (!ok) {
1861     return n;
1862   }
1863 
1864   /* Filter out unsupported certificate types. */
1865   pkey = X509_get_pubkey(peer);
1866   if (pkey == NULL) {
1867     goto err;
1868   }
1869   if (!(X509_certificate_type(peer, pkey) & EVP_PKT_SIGN) ||
1870       (pkey->type != EVP_PKEY_RSA && pkey->type != EVP_PKEY_EC)) {
1871     al = SSL_AD_UNSUPPORTED_CERTIFICATE;
1872     OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
1873     goto f_err;
1874   }
1875 
1876   CBS_init(&certificate_verify, ssl->init_msg, n);
1877 
1878   /* Determine the digest type if needbe. */
1879   if (ssl3_protocol_version(ssl) >= TLS1_2_VERSION) {
1880     uint8_t hash, signature_type;
1881     if (!CBS_get_u8(&certificate_verify, &hash) ||
1882         !CBS_get_u8(&certificate_verify, &signature_type)) {
1883       al = SSL_AD_DECODE_ERROR;
1884       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1885       goto f_err;
1886     }
1887     if (!tls12_check_peer_sigalg(ssl, &md, &al, hash, signature_type, pkey)) {
1888       goto f_err;
1889     }
1890   }
1891 
1892   /* Compute the digest. */
1893   if (!ssl3_cert_verify_hash(ssl, digest, &digest_length, &md, pkey->type)) {
1894     goto err;
1895   }
1896 
1897   /* The handshake buffer is no longer necessary, and we may hash the current
1898    * message.*/
1899   ssl3_free_handshake_buffer(ssl);
1900   if (!ssl3_hash_current_message(ssl)) {
1901     goto err;
1902   }
1903 
1904   /* Parse and verify the signature. */
1905   if (!CBS_get_u16_length_prefixed(&certificate_verify, &signature) ||
1906       CBS_len(&certificate_verify) != 0) {
1907     al = SSL_AD_DECODE_ERROR;
1908     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1909     goto f_err;
1910   }
1911 
1912   pctx = EVP_PKEY_CTX_new(pkey, NULL);
1913   if (pctx == NULL) {
1914     goto err;
1915   }
1916   int sig_ok = EVP_PKEY_verify_init(pctx) &&
1917                EVP_PKEY_CTX_set_signature_md(pctx, md) &&
1918                EVP_PKEY_verify(pctx, CBS_data(&signature), CBS_len(&signature),
1919                                digest, digest_length);
1920 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
1921   sig_ok = 1;
1922   ERR_clear_error();
1923 #endif
1924   if (!sig_ok) {
1925     al = SSL_AD_DECRYPT_ERROR;
1926     OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SIGNATURE);
1927     goto f_err;
1928   }
1929 
1930   ret = 1;
1931 
1932   if (0) {
1933   f_err:
1934     ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
1935   }
1936 
1937 err:
1938   EVP_PKEY_CTX_free(pctx);
1939   EVP_PKEY_free(pkey);
1940 
1941   return ret;
1942 }
1943 
1944 /* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It
1945  * sets the next_proto member in s if found */
ssl3_get_next_proto(SSL * ssl)1946 static int ssl3_get_next_proto(SSL *ssl) {
1947   int ok;
1948   long n;
1949   CBS next_protocol, selected_protocol, padding;
1950 
1951   /* Clients cannot send a NextProtocol message if we didn't see the extension
1952    * in their ClientHello */
1953   if (!ssl->s3->next_proto_neg_seen) {
1954     OPENSSL_PUT_ERROR(SSL, SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
1955     return -1;
1956   }
1957 
1958   n = ssl->method->ssl_get_message(ssl, SSL3_MT_NEXT_PROTO, ssl_hash_message,
1959                                    &ok);
1960 
1961   if (!ok) {
1962     return n;
1963   }
1964 
1965   CBS_init(&next_protocol, ssl->init_msg, n);
1966 
1967   /* The payload looks like:
1968    *   uint8 proto_len;
1969    *   uint8 proto[proto_len];
1970    *   uint8 padding_len;
1971    *   uint8 padding[padding_len]; */
1972   if (!CBS_get_u8_length_prefixed(&next_protocol, &selected_protocol) ||
1973       !CBS_get_u8_length_prefixed(&next_protocol, &padding) ||
1974       CBS_len(&next_protocol) != 0 ||
1975       !CBS_stow(&selected_protocol, &ssl->s3->next_proto_negotiated,
1976                 &ssl->s3->next_proto_negotiated_len)) {
1977     return 0;
1978   }
1979 
1980   return 1;
1981 }
1982 
1983 /* ssl3_get_channel_id reads and verifies a ClientID handshake message. */
ssl3_get_channel_id(SSL * ssl)1984 static int ssl3_get_channel_id(SSL *ssl) {
1985   int ret = -1, ok;
1986   long n;
1987   uint8_t channel_id_hash[EVP_MAX_MD_SIZE];
1988   size_t channel_id_hash_len;
1989   const uint8_t *p;
1990   uint16_t extension_type;
1991   EC_GROUP *p256 = NULL;
1992   EC_KEY *key = NULL;
1993   EC_POINT *point = NULL;
1994   ECDSA_SIG sig;
1995   BIGNUM x, y;
1996   CBS encrypted_extensions, extension;
1997 
1998   n = ssl->method->ssl_get_message(ssl, SSL3_MT_CHANNEL_ID_ENCRYPTED_EXTENSIONS,
1999                                    ssl_dont_hash_message, &ok);
2000 
2001   if (!ok) {
2002     return n;
2003   }
2004 
2005   /* Before incorporating the EncryptedExtensions message to the handshake
2006    * hash, compute the hash that should have been signed. */
2007   if (!tls1_channel_id_hash(ssl, channel_id_hash, &channel_id_hash_len)) {
2008     return -1;
2009   }
2010   assert(channel_id_hash_len == SHA256_DIGEST_LENGTH);
2011 
2012   if (!ssl3_hash_current_message(ssl)) {
2013     return -1;
2014   }
2015 
2016   CBS_init(&encrypted_extensions, ssl->init_msg, n);
2017 
2018   /* EncryptedExtensions could include multiple extensions, but the only
2019    * extension that could be negotiated is ChannelID, so there can only be one
2020    * entry.
2021    *
2022    * The payload looks like:
2023    *   uint16 extension_type
2024    *   uint16 extension_len;
2025    *   uint8 x[32];
2026    *   uint8 y[32];
2027    *   uint8 r[32];
2028    *   uint8 s[32]; */
2029 
2030   if (!CBS_get_u16(&encrypted_extensions, &extension_type) ||
2031       !CBS_get_u16_length_prefixed(&encrypted_extensions, &extension) ||
2032       CBS_len(&encrypted_extensions) != 0 ||
2033       extension_type != TLSEXT_TYPE_channel_id ||
2034       CBS_len(&extension) != TLSEXT_CHANNEL_ID_SIZE) {
2035     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_MESSAGE);
2036     return -1;
2037   }
2038 
2039   p256 = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
2040   if (!p256) {
2041     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_P256_SUPPORT);
2042     return -1;
2043   }
2044 
2045   BN_init(&x);
2046   BN_init(&y);
2047   sig.r = BN_new();
2048   sig.s = BN_new();
2049   if (sig.r == NULL || sig.s == NULL) {
2050     goto err;
2051   }
2052 
2053   p = CBS_data(&extension);
2054   if (BN_bin2bn(p + 0, 32, &x) == NULL ||
2055       BN_bin2bn(p + 32, 32, &y) == NULL ||
2056       BN_bin2bn(p + 64, 32, sig.r) == NULL ||
2057       BN_bin2bn(p + 96, 32, sig.s) == NULL) {
2058     goto err;
2059   }
2060 
2061   point = EC_POINT_new(p256);
2062   if (!point ||
2063       !EC_POINT_set_affine_coordinates_GFp(p256, point, &x, &y, NULL)) {
2064     goto err;
2065   }
2066 
2067   key = EC_KEY_new();
2068   if (!key || !EC_KEY_set_group(key, p256) ||
2069       !EC_KEY_set_public_key(key, point)) {
2070     goto err;
2071   }
2072 
2073   /* We stored the handshake hash in |tlsext_channel_id| the first time that we
2074    * were called. */
2075   if (!ECDSA_do_verify(channel_id_hash, channel_id_hash_len, &sig, key)) {
2076     OPENSSL_PUT_ERROR(SSL, SSL_R_CHANNEL_ID_SIGNATURE_INVALID);
2077     ssl->s3->tlsext_channel_id_valid = 0;
2078     goto err;
2079   }
2080 
2081   memcpy(ssl->s3->tlsext_channel_id, p, 64);
2082   ret = 1;
2083 
2084 err:
2085   BN_free(&x);
2086   BN_free(&y);
2087   BN_free(sig.r);
2088   BN_free(sig.s);
2089   EC_KEY_free(key);
2090   EC_POINT_free(point);
2091   EC_GROUP_free(p256);
2092   return ret;
2093 }
2094 
2095 /* send a new session ticket (not necessarily for a new session) */
ssl3_send_new_session_ticket(SSL * ssl)2096 static int ssl3_send_new_session_ticket(SSL *ssl) {
2097   int ret = -1;
2098   uint8_t *session = NULL;
2099   size_t session_len;
2100   EVP_CIPHER_CTX ctx;
2101   HMAC_CTX hctx;
2102 
2103   EVP_CIPHER_CTX_init(&ctx);
2104   HMAC_CTX_init(&hctx);
2105 
2106   if (ssl->state == SSL3_ST_SW_SESSION_TICKET_A) {
2107     uint8_t *p, *macstart;
2108     int len;
2109     unsigned int hlen;
2110     SSL_CTX *tctx = ssl->initial_ctx;
2111     uint8_t iv[EVP_MAX_IV_LENGTH];
2112     uint8_t key_name[16];
2113     /* The maximum overhead of encrypting the session is 16 (key name) + IV +
2114      * one block of encryption overhead + HMAC.  */
2115     const size_t max_ticket_overhead =
2116         16 + EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE;
2117 
2118     /* Serialize the SSL_SESSION to be encoded into the ticket. */
2119     if (!SSL_SESSION_to_bytes_for_ticket(ssl->session, &session,
2120                                          &session_len)) {
2121       goto err;
2122     }
2123 
2124     /* If the session is too long, emit a dummy value rather than abort the
2125      * connection. */
2126     if (session_len > 0xFFFF - max_ticket_overhead) {
2127       static const char kTicketPlaceholder[] = "TICKET TOO LARGE";
2128       const size_t placeholder_len = strlen(kTicketPlaceholder);
2129 
2130       OPENSSL_free(session);
2131       session = NULL;
2132 
2133       p = ssl_handshake_start(ssl);
2134       /* Emit ticket_lifetime_hint. */
2135       l2n(0, p);
2136       /* Emit ticket. */
2137       s2n(placeholder_len, p);
2138       memcpy(p, kTicketPlaceholder, placeholder_len);
2139       p += placeholder_len;
2140 
2141       len = p - ssl_handshake_start(ssl);
2142       if (!ssl_set_handshake_header(ssl, SSL3_MT_NEW_SESSION_TICKET, len)) {
2143         goto err;
2144       }
2145       ssl->state = SSL3_ST_SW_SESSION_TICKET_B;
2146       return ssl_do_write(ssl);
2147     }
2148 
2149     /* Grow buffer if need be: the length calculation is as follows:
2150      * handshake_header_length + 4 (ticket lifetime hint) + 2 (ticket length) +
2151      * max_ticket_overhead + * session_length */
2152     if (!BUF_MEM_grow(ssl->init_buf, SSL_HM_HEADER_LENGTH(ssl) + 6 +
2153                                        max_ticket_overhead + session_len)) {
2154       goto err;
2155     }
2156     p = ssl_handshake_start(ssl);
2157     /* Initialize HMAC and cipher contexts. If callback present it does all the
2158      * work otherwise use generated values from parent ctx. */
2159     if (tctx->tlsext_ticket_key_cb) {
2160       if (tctx->tlsext_ticket_key_cb(ssl, key_name, iv, &ctx, &hctx,
2161                                      1 /* encrypt */) < 0) {
2162         goto err;
2163       }
2164     } else {
2165       if (!RAND_bytes(iv, 16) ||
2166           !EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
2167                               tctx->tlsext_tick_aes_key, iv) ||
2168           !HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16, tlsext_tick_md(),
2169                         NULL)) {
2170         goto err;
2171       }
2172       memcpy(key_name, tctx->tlsext_tick_key_name, 16);
2173     }
2174 
2175     /* Ticket lifetime hint (advisory only): We leave this unspecified for
2176      * resumed session (for simplicity), and guess that tickets for new
2177      * sessions will live as long as their sessions. */
2178     l2n(ssl->hit ? 0 : ssl->session->timeout, p);
2179 
2180     /* Skip ticket length for now */
2181     p += 2;
2182     /* Output key name */
2183     macstart = p;
2184     memcpy(p, key_name, 16);
2185     p += 16;
2186     /* output IV */
2187     memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
2188     p += EVP_CIPHER_CTX_iv_length(&ctx);
2189     /* Encrypt session data */
2190     if (!EVP_EncryptUpdate(&ctx, p, &len, session, session_len)) {
2191       goto err;
2192     }
2193     p += len;
2194     if (!EVP_EncryptFinal_ex(&ctx, p, &len)) {
2195       goto err;
2196     }
2197     p += len;
2198 
2199     if (!HMAC_Update(&hctx, macstart, p - macstart) ||
2200         !HMAC_Final(&hctx, p, &hlen)) {
2201       goto err;
2202     }
2203 
2204     p += hlen;
2205     /* Now write out lengths: p points to end of data written */
2206     /* Total length */
2207     len = p - ssl_handshake_start(ssl);
2208     /* Skip ticket lifetime hint */
2209     p = ssl_handshake_start(ssl) + 4;
2210     s2n(len - 6, p);
2211     if (!ssl_set_handshake_header(ssl, SSL3_MT_NEW_SESSION_TICKET, len)) {
2212       goto err;
2213     }
2214     ssl->state = SSL3_ST_SW_SESSION_TICKET_B;
2215   }
2216 
2217   /* SSL3_ST_SW_SESSION_TICKET_B */
2218   ret = ssl_do_write(ssl);
2219 
2220 err:
2221   OPENSSL_free(session);
2222   EVP_CIPHER_CTX_cleanup(&ctx);
2223   HMAC_CTX_cleanup(&hctx);
2224   return ret;
2225 }
2226