]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - crypto/openssl/ssl/t1_lib.c
openssh: cherry-pick OpenSSL 1.1.1 compatibility
[FreeBSD/FreeBSD.git] / crypto / openssl / ssl / t1_lib.c
1 /* ssl/t1_lib.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2018 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111
112 #include <stdio.h>
113 #include <openssl/objects.h>
114 #include <openssl/evp.h>
115 #include <openssl/hmac.h>
116 #ifndef OPENSSL_NO_EC
117 #ifdef OPENSSL_NO_EC2M
118 # include <openssl/ec.h>
119 #endif
120 #endif
121 #include <openssl/ocsp.h>
122 #include <openssl/rand.h>
123 #include "ssl_locl.h"
124
125 const char tls1_version_str[] = "TLSv1" OPENSSL_VERSION_PTEXT;
126
127 #ifndef OPENSSL_NO_TLSEXT
128 static int tls_decrypt_ticket(SSL *s, const unsigned char *tick, int ticklen,
129                               const unsigned char *sess_id, int sesslen,
130                               SSL_SESSION **psess);
131 static int ssl_check_clienthello_tlsext_early(SSL *s);
132 int ssl_check_serverhello_tlsext(SSL *s);
133 #endif
134
135 #define CHECKLEN(curr, val, limit) \
136     (((curr) >= (limit)) || (size_t)((limit) - (curr)) < (size_t)(val))
137
138 SSL3_ENC_METHOD TLSv1_enc_data = {
139     tls1_enc,
140     tls1_mac,
141     tls1_setup_key_block,
142     tls1_generate_master_secret,
143     tls1_change_cipher_state,
144     tls1_final_finish_mac,
145     TLS1_FINISH_MAC_LENGTH,
146     tls1_cert_verify_mac,
147     TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
148     TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
149     tls1_alert_code,
150     tls1_export_keying_material,
151     0,
152     SSL3_HM_HEADER_LENGTH,
153     ssl3_set_handshake_header,
154     ssl3_handshake_write
155 };
156
157 SSL3_ENC_METHOD TLSv1_1_enc_data = {
158     tls1_enc,
159     tls1_mac,
160     tls1_setup_key_block,
161     tls1_generate_master_secret,
162     tls1_change_cipher_state,
163     tls1_final_finish_mac,
164     TLS1_FINISH_MAC_LENGTH,
165     tls1_cert_verify_mac,
166     TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
167     TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
168     tls1_alert_code,
169     tls1_export_keying_material,
170     SSL_ENC_FLAG_EXPLICIT_IV,
171     SSL3_HM_HEADER_LENGTH,
172     ssl3_set_handshake_header,
173     ssl3_handshake_write
174 };
175
176 SSL3_ENC_METHOD TLSv1_2_enc_data = {
177     tls1_enc,
178     tls1_mac,
179     tls1_setup_key_block,
180     tls1_generate_master_secret,
181     tls1_change_cipher_state,
182     tls1_final_finish_mac,
183     TLS1_FINISH_MAC_LENGTH,
184     tls1_cert_verify_mac,
185     TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
186     TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
187     tls1_alert_code,
188     tls1_export_keying_material,
189     SSL_ENC_FLAG_EXPLICIT_IV | SSL_ENC_FLAG_SIGALGS | SSL_ENC_FLAG_SHA256_PRF
190         | SSL_ENC_FLAG_TLS1_2_CIPHERS,
191     SSL3_HM_HEADER_LENGTH,
192     ssl3_set_handshake_header,
193     ssl3_handshake_write
194 };
195
196 long tls1_default_timeout(void)
197 {
198     /*
199      * 2 hours, the 24 hours mentioned in the TLSv1 spec is way too long for
200      * http, the cache would over fill
201      */
202     return (60 * 60 * 2);
203 }
204
205 int tls1_new(SSL *s)
206 {
207     if (!ssl3_new(s))
208         return (0);
209     s->method->ssl_clear(s);
210     return (1);
211 }
212
213 void tls1_free(SSL *s)
214 {
215 #ifndef OPENSSL_NO_TLSEXT
216     if (s->tlsext_session_ticket) {
217         OPENSSL_free(s->tlsext_session_ticket);
218     }
219 #endif                          /* OPENSSL_NO_TLSEXT */
220     ssl3_free(s);
221 }
222
223 void tls1_clear(SSL *s)
224 {
225     ssl3_clear(s);
226     s->version = s->method->version;
227 }
228
229 #ifndef OPENSSL_NO_EC
230
231 static int nid_list[] = {
232     NID_sect163k1,              /* sect163k1 (1) */
233     NID_sect163r1,              /* sect163r1 (2) */
234     NID_sect163r2,              /* sect163r2 (3) */
235     NID_sect193r1,              /* sect193r1 (4) */
236     NID_sect193r2,              /* sect193r2 (5) */
237     NID_sect233k1,              /* sect233k1 (6) */
238     NID_sect233r1,              /* sect233r1 (7) */
239     NID_sect239k1,              /* sect239k1 (8) */
240     NID_sect283k1,              /* sect283k1 (9) */
241     NID_sect283r1,              /* sect283r1 (10) */
242     NID_sect409k1,              /* sect409k1 (11) */
243     NID_sect409r1,              /* sect409r1 (12) */
244     NID_sect571k1,              /* sect571k1 (13) */
245     NID_sect571r1,              /* sect571r1 (14) */
246     NID_secp160k1,              /* secp160k1 (15) */
247     NID_secp160r1,              /* secp160r1 (16) */
248     NID_secp160r2,              /* secp160r2 (17) */
249     NID_secp192k1,              /* secp192k1 (18) */
250     NID_X9_62_prime192v1,       /* secp192r1 (19) */
251     NID_secp224k1,              /* secp224k1 (20) */
252     NID_secp224r1,              /* secp224r1 (21) */
253     NID_secp256k1,              /* secp256k1 (22) */
254     NID_X9_62_prime256v1,       /* secp256r1 (23) */
255     NID_secp384r1,              /* secp384r1 (24) */
256     NID_secp521r1,              /* secp521r1 (25) */
257     NID_brainpoolP256r1,        /* brainpoolP256r1 (26) */
258     NID_brainpoolP384r1,        /* brainpoolP384r1 (27) */
259     NID_brainpoolP512r1         /* brainpool512r1 (28) */
260 };
261
262 static const unsigned char ecformats_default[] = {
263     TLSEXT_ECPOINTFORMAT_uncompressed,
264     TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime,
265     TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2
266 };
267
268 /* The client's default curves / the server's 'auto' curves. */
269 static const unsigned char eccurves_auto[] = {
270     /* Prefer P-256 which has the fastest and most secure implementations. */
271     0, 23,                      /* secp256r1 (23) */
272     /* Other >= 256-bit prime curves. */
273     0, 25,                      /* secp521r1 (25) */
274     0, 28,                      /* brainpool512r1 (28) */
275     0, 27,                      /* brainpoolP384r1 (27) */
276     0, 24,                      /* secp384r1 (24) */
277     0, 26,                      /* brainpoolP256r1 (26) */
278     0, 22,                      /* secp256k1 (22) */
279 # ifndef OPENSSL_NO_EC2M
280     /* >= 256-bit binary curves. */
281     0, 14,                      /* sect571r1 (14) */
282     0, 13,                      /* sect571k1 (13) */
283     0, 11,                      /* sect409k1 (11) */
284     0, 12,                      /* sect409r1 (12) */
285     0, 9,                       /* sect283k1 (9) */
286     0, 10,                      /* sect283r1 (10) */
287 # endif
288 };
289
290 static const unsigned char eccurves_all[] = {
291     /* Prefer P-256 which has the fastest and most secure implementations. */
292     0, 23,                      /* secp256r1 (23) */
293     /* Other >= 256-bit prime curves. */
294     0, 25,                      /* secp521r1 (25) */
295     0, 28,                      /* brainpool512r1 (28) */
296     0, 27,                      /* brainpoolP384r1 (27) */
297     0, 24,                      /* secp384r1 (24) */
298     0, 26,                      /* brainpoolP256r1 (26) */
299     0, 22,                      /* secp256k1 (22) */
300 # ifndef OPENSSL_NO_EC2M
301     /* >= 256-bit binary curves. */
302     0, 14,                      /* sect571r1 (14) */
303     0, 13,                      /* sect571k1 (13) */
304     0, 11,                      /* sect409k1 (11) */
305     0, 12,                      /* sect409r1 (12) */
306     0, 9,                       /* sect283k1 (9) */
307     0, 10,                      /* sect283r1 (10) */
308 # endif
309     /*
310      * Remaining curves disabled by default but still permitted if set
311      * via an explicit callback or parameters.
312      */
313     0, 20,                      /* secp224k1 (20) */
314     0, 21,                      /* secp224r1 (21) */
315     0, 18,                      /* secp192k1 (18) */
316     0, 19,                      /* secp192r1 (19) */
317     0, 15,                      /* secp160k1 (15) */
318     0, 16,                      /* secp160r1 (16) */
319     0, 17,                      /* secp160r2 (17) */
320 # ifndef OPENSSL_NO_EC2M
321     0, 8,                       /* sect239k1 (8) */
322     0, 6,                       /* sect233k1 (6) */
323     0, 7,                       /* sect233r1 (7) */
324     0, 4,                       /* sect193r1 (4) */
325     0, 5,                       /* sect193r2 (5) */
326     0, 1,                       /* sect163k1 (1) */
327     0, 2,                       /* sect163r1 (2) */
328     0, 3,                       /* sect163r2 (3) */
329 # endif
330 };
331
332 static const unsigned char suiteb_curves[] = {
333     0, TLSEXT_curve_P_256,
334     0, TLSEXT_curve_P_384
335 };
336
337 # ifdef OPENSSL_FIPS
338 /* Brainpool not allowed in FIPS mode */
339 static const unsigned char fips_curves_default[] = {
340 #  ifndef OPENSSL_NO_EC2M
341     0, 14,                      /* sect571r1 (14) */
342     0, 13,                      /* sect571k1 (13) */
343 #  endif
344     0, 25,                      /* secp521r1 (25) */
345 #  ifndef OPENSSL_NO_EC2M
346     0, 11,                      /* sect409k1 (11) */
347     0, 12,                      /* sect409r1 (12) */
348 #  endif
349     0, 24,                      /* secp384r1 (24) */
350 #  ifndef OPENSSL_NO_EC2M
351     0, 9,                       /* sect283k1 (9) */
352     0, 10,                      /* sect283r1 (10) */
353 #  endif
354     0, 22,                      /* secp256k1 (22) */
355     0, 23,                      /* secp256r1 (23) */
356 #  ifndef OPENSSL_NO_EC2M
357     0, 8,                       /* sect239k1 (8) */
358     0, 6,                       /* sect233k1 (6) */
359     0, 7,                       /* sect233r1 (7) */
360 #  endif
361     0, 20,                      /* secp224k1 (20) */
362     0, 21,                      /* secp224r1 (21) */
363 #  ifndef OPENSSL_NO_EC2M
364     0, 4,                       /* sect193r1 (4) */
365     0, 5,                       /* sect193r2 (5) */
366 #  endif
367     0, 18,                      /* secp192k1 (18) */
368     0, 19,                      /* secp192r1 (19) */
369 #  ifndef OPENSSL_NO_EC2M
370     0, 1,                       /* sect163k1 (1) */
371     0, 2,                       /* sect163r1 (2) */
372     0, 3,                       /* sect163r2 (3) */
373 #  endif
374     0, 15,                      /* secp160k1 (15) */
375     0, 16,                      /* secp160r1 (16) */
376     0, 17,                      /* secp160r2 (17) */
377 };
378 # endif
379
380 int tls1_ec_curve_id2nid(int curve_id)
381 {
382     /* ECC curves from RFC 4492 and RFC 7027 */
383     if ((curve_id < 1) || ((unsigned int)curve_id >
384                            sizeof(nid_list) / sizeof(nid_list[0])))
385         return 0;
386     return nid_list[curve_id - 1];
387 }
388
389 int tls1_ec_nid2curve_id(int nid)
390 {
391     /* ECC curves from RFC 4492 and RFC 7027 */
392     switch (nid) {
393     case NID_sect163k1:        /* sect163k1 (1) */
394         return 1;
395     case NID_sect163r1:        /* sect163r1 (2) */
396         return 2;
397     case NID_sect163r2:        /* sect163r2 (3) */
398         return 3;
399     case NID_sect193r1:        /* sect193r1 (4) */
400         return 4;
401     case NID_sect193r2:        /* sect193r2 (5) */
402         return 5;
403     case NID_sect233k1:        /* sect233k1 (6) */
404         return 6;
405     case NID_sect233r1:        /* sect233r1 (7) */
406         return 7;
407     case NID_sect239k1:        /* sect239k1 (8) */
408         return 8;
409     case NID_sect283k1:        /* sect283k1 (9) */
410         return 9;
411     case NID_sect283r1:        /* sect283r1 (10) */
412         return 10;
413     case NID_sect409k1:        /* sect409k1 (11) */
414         return 11;
415     case NID_sect409r1:        /* sect409r1 (12) */
416         return 12;
417     case NID_sect571k1:        /* sect571k1 (13) */
418         return 13;
419     case NID_sect571r1:        /* sect571r1 (14) */
420         return 14;
421     case NID_secp160k1:        /* secp160k1 (15) */
422         return 15;
423     case NID_secp160r1:        /* secp160r1 (16) */
424         return 16;
425     case NID_secp160r2:        /* secp160r2 (17) */
426         return 17;
427     case NID_secp192k1:        /* secp192k1 (18) */
428         return 18;
429     case NID_X9_62_prime192v1: /* secp192r1 (19) */
430         return 19;
431     case NID_secp224k1:        /* secp224k1 (20) */
432         return 20;
433     case NID_secp224r1:        /* secp224r1 (21) */
434         return 21;
435     case NID_secp256k1:        /* secp256k1 (22) */
436         return 22;
437     case NID_X9_62_prime256v1: /* secp256r1 (23) */
438         return 23;
439     case NID_secp384r1:        /* secp384r1 (24) */
440         return 24;
441     case NID_secp521r1:        /* secp521r1 (25) */
442         return 25;
443     case NID_brainpoolP256r1:  /* brainpoolP256r1 (26) */
444         return 26;
445     case NID_brainpoolP384r1:  /* brainpoolP384r1 (27) */
446         return 27;
447     case NID_brainpoolP512r1:  /* brainpool512r1 (28) */
448         return 28;
449     default:
450         return 0;
451     }
452 }
453
454 /*
455  * Get curves list, if "sess" is set return client curves otherwise
456  * preferred list.
457  * Sets |num_curves| to the number of curves in the list, i.e.,
458  * the length of |pcurves| is 2 * num_curves.
459  * Returns 1 on success and 0 if the client curves list has invalid format.
460  * The latter indicates an internal error: we should not be accepting such
461  * lists in the first place.
462  * TODO(emilia): we should really be storing the curves list in explicitly
463  * parsed form instead. (However, this would affect binary compatibility
464  * so cannot happen in the 1.0.x series.)
465  */
466 static int tls1_get_curvelist(SSL *s, int sess,
467                               const unsigned char **pcurves,
468                               size_t *num_curves)
469 {
470     size_t pcurveslen = 0;
471     if (sess) {
472         *pcurves = s->session->tlsext_ellipticcurvelist;
473         pcurveslen = s->session->tlsext_ellipticcurvelist_length;
474     } else {
475         /* For Suite B mode only include P-256, P-384 */
476         switch (tls1_suiteb(s)) {
477         case SSL_CERT_FLAG_SUITEB_128_LOS:
478             *pcurves = suiteb_curves;
479             pcurveslen = sizeof(suiteb_curves);
480             break;
481
482         case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
483             *pcurves = suiteb_curves;
484             pcurveslen = 2;
485             break;
486
487         case SSL_CERT_FLAG_SUITEB_192_LOS:
488             *pcurves = suiteb_curves + 2;
489             pcurveslen = 2;
490             break;
491         default:
492             *pcurves = s->tlsext_ellipticcurvelist;
493             pcurveslen = s->tlsext_ellipticcurvelist_length;
494         }
495         if (!*pcurves) {
496 # ifdef OPENSSL_FIPS
497             if (FIPS_mode()) {
498                 *pcurves = fips_curves_default;
499                 pcurveslen = sizeof(fips_curves_default);
500             } else
501 # endif
502             {
503                 if (!s->server || s->cert->ecdh_tmp_auto) {
504                     *pcurves = eccurves_auto;
505                     pcurveslen = sizeof(eccurves_auto);
506                 } else {
507                     *pcurves = eccurves_all;
508                     pcurveslen = sizeof(eccurves_all);
509                 }
510             }
511         }
512     }
513     /* We do not allow odd length arrays to enter the system. */
514     if (pcurveslen & 1) {
515         SSLerr(SSL_F_TLS1_GET_CURVELIST, ERR_R_INTERNAL_ERROR);
516         *num_curves = 0;
517         return 0;
518     } else {
519         *num_curves = pcurveslen / 2;
520         return 1;
521     }
522 }
523
524 /* Check a curve is one of our preferences */
525 int tls1_check_curve(SSL *s, const unsigned char *p, size_t len)
526 {
527     const unsigned char *curves;
528     size_t num_curves, i;
529     unsigned int suiteb_flags = tls1_suiteb(s);
530     if (len != 3 || p[0] != NAMED_CURVE_TYPE)
531         return 0;
532     /* Check curve matches Suite B preferences */
533     if (suiteb_flags) {
534         unsigned long cid = s->s3->tmp.new_cipher->id;
535         if (p[1])
536             return 0;
537         if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256) {
538             if (p[2] != TLSEXT_curve_P_256)
539                 return 0;
540         } else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384) {
541             if (p[2] != TLSEXT_curve_P_384)
542                 return 0;
543         } else                  /* Should never happen */
544             return 0;
545     }
546     if (!tls1_get_curvelist(s, 0, &curves, &num_curves))
547         return 0;
548     for (i = 0; i < num_curves; i++, curves += 2) {
549         if (p[1] == curves[0] && p[2] == curves[1])
550             return 1;
551     }
552     return 0;
553 }
554
555 /*-
556  * Return |nmatch|th shared curve or NID_undef if there is no match.
557  * For nmatch == -1, return number of  matches
558  * For nmatch == -2, return the NID of the curve to use for
559  * an EC tmp key, or NID_undef if there is no match.
560  */
561 int tls1_shared_curve(SSL *s, int nmatch)
562 {
563     const unsigned char *pref, *supp;
564     size_t num_pref, num_supp, i, j;
565     int k;
566     /* Can't do anything on client side */
567     if (s->server == 0)
568         return -1;
569     if (nmatch == -2) {
570         if (tls1_suiteb(s)) {
571             /*
572              * For Suite B ciphersuite determines curve: we already know
573              * these are acceptable due to previous checks.
574              */
575             unsigned long cid = s->s3->tmp.new_cipher->id;
576             if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
577                 return NID_X9_62_prime256v1; /* P-256 */
578             if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
579                 return NID_secp384r1; /* P-384 */
580             /* Should never happen */
581             return NID_undef;
582         }
583         /* If not Suite B just return first preference shared curve */
584         nmatch = 0;
585     }
586     /*
587      * Avoid truncation. tls1_get_curvelist takes an int
588      * but s->options is a long...
589      */
590     if (!tls1_get_curvelist
591         (s, (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) != 0, &supp,
592          &num_supp))
593         /* In practice, NID_undef == 0 but let's be precise. */
594         return nmatch == -1 ? 0 : NID_undef;
595     if (!tls1_get_curvelist
596         (s, !(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE), &pref,
597          &num_pref))
598         return nmatch == -1 ? 0 : NID_undef;
599
600     /*
601      * If the client didn't send the elliptic_curves extension all of them
602      * are allowed.
603      */
604     if (num_supp == 0 && (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) != 0) {
605         supp = eccurves_all;
606         num_supp = sizeof(eccurves_all) / 2;
607     } else if (num_pref == 0 &&
608         (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) == 0) {
609         pref = eccurves_all;
610         num_pref = sizeof(eccurves_all) / 2;
611     }
612
613     k = 0;
614     for (i = 0; i < num_pref; i++, pref += 2) {
615         const unsigned char *tsupp = supp;
616         for (j = 0; j < num_supp; j++, tsupp += 2) {
617             if (pref[0] == tsupp[0] && pref[1] == tsupp[1]) {
618                 if (nmatch == k) {
619                     int id = (pref[0] << 8) | pref[1];
620                     return tls1_ec_curve_id2nid(id);
621                 }
622                 k++;
623             }
624         }
625     }
626     if (nmatch == -1)
627         return k;
628     /* Out of range (nmatch > k). */
629     return NID_undef;
630 }
631
632 int tls1_set_curves(unsigned char **pext, size_t *pextlen,
633                     int *curves, size_t ncurves)
634 {
635     unsigned char *clist, *p;
636     size_t i;
637     /*
638      * Bitmap of curves included to detect duplicates: only works while curve
639      * ids < 32
640      */
641     unsigned long dup_list = 0;
642 # ifdef OPENSSL_NO_EC2M
643     EC_GROUP *curve;
644 # endif
645
646     clist = OPENSSL_malloc(ncurves * 2);
647     if (!clist)
648         return 0;
649     for (i = 0, p = clist; i < ncurves; i++) {
650         unsigned long idmask;
651         int id;
652         id = tls1_ec_nid2curve_id(curves[i]);
653 # ifdef OPENSSL_FIPS
654         /* NB: 25 is last curve ID supported by FIPS module */
655         if (FIPS_mode() && id > 25) {
656             OPENSSL_free(clist);
657             return 0;
658         }
659 # endif
660 # ifdef OPENSSL_NO_EC2M
661         curve = EC_GROUP_new_by_curve_name(curves[i]);
662         if (!curve || EC_METHOD_get_field_type(EC_GROUP_method_of(curve))
663             == NID_X9_62_characteristic_two_field) {
664             if (curve)
665                 EC_GROUP_free(curve);
666             OPENSSL_free(clist);
667             return 0;
668         } else
669             EC_GROUP_free(curve);
670 # endif
671         idmask = 1L << id;
672         if (!id || (dup_list & idmask)) {
673             OPENSSL_free(clist);
674             return 0;
675         }
676         dup_list |= idmask;
677         s2n(id, p);
678     }
679     if (*pext)
680         OPENSSL_free(*pext);
681     *pext = clist;
682     *pextlen = ncurves * 2;
683     return 1;
684 }
685
686 # define MAX_CURVELIST   28
687
688 typedef struct {
689     size_t nidcnt;
690     int nid_arr[MAX_CURVELIST];
691 } nid_cb_st;
692
693 static int nid_cb(const char *elem, int len, void *arg)
694 {
695     nid_cb_st *narg = arg;
696     size_t i;
697     int nid;
698     char etmp[20];
699     if (elem == NULL)
700         return 0;
701     if (narg->nidcnt == MAX_CURVELIST)
702         return 0;
703     if (len > (int)(sizeof(etmp) - 1))
704         return 0;
705     memcpy(etmp, elem, len);
706     etmp[len] = 0;
707     nid = EC_curve_nist2nid(etmp);
708     if (nid == NID_undef)
709         nid = OBJ_sn2nid(etmp);
710     if (nid == NID_undef)
711         nid = OBJ_ln2nid(etmp);
712     if (nid == NID_undef)
713         return 0;
714     for (i = 0; i < narg->nidcnt; i++)
715         if (narg->nid_arr[i] == nid)
716             return 0;
717     narg->nid_arr[narg->nidcnt++] = nid;
718     return 1;
719 }
720
721 /* Set curves based on a colon separate list */
722 int tls1_set_curves_list(unsigned char **pext, size_t *pextlen,
723                          const char *str)
724 {
725     nid_cb_st ncb;
726     ncb.nidcnt = 0;
727     if (!CONF_parse_list(str, ':', 1, nid_cb, &ncb))
728         return 0;
729     if (pext == NULL)
730         return 1;
731     return tls1_set_curves(pext, pextlen, ncb.nid_arr, ncb.nidcnt);
732 }
733
734 /* For an EC key set TLS id and required compression based on parameters */
735 static int tls1_set_ec_id(unsigned char *curve_id, unsigned char *comp_id,
736                           EC_KEY *ec)
737 {
738     int is_prime, id;
739     const EC_GROUP *grp;
740     const EC_METHOD *meth;
741     if (!ec)
742         return 0;
743     /* Determine if it is a prime field */
744     grp = EC_KEY_get0_group(ec);
745     if (!grp)
746         return 0;
747     meth = EC_GROUP_method_of(grp);
748     if (!meth)
749         return 0;
750     if (EC_METHOD_get_field_type(meth) == NID_X9_62_prime_field)
751         is_prime = 1;
752     else
753         is_prime = 0;
754     /* Determine curve ID */
755     id = EC_GROUP_get_curve_name(grp);
756     id = tls1_ec_nid2curve_id(id);
757     /* If we have an ID set it, otherwise set arbitrary explicit curve */
758     if (id) {
759         curve_id[0] = 0;
760         curve_id[1] = (unsigned char)id;
761     } else {
762         curve_id[0] = 0xff;
763         if (is_prime)
764             curve_id[1] = 0x01;
765         else
766             curve_id[1] = 0x02;
767     }
768     if (comp_id) {
769         if (EC_KEY_get0_public_key(ec) == NULL)
770             return 0;
771         if (EC_KEY_get_conv_form(ec) == POINT_CONVERSION_COMPRESSED) {
772             if (is_prime)
773                 *comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
774             else
775                 *comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
776         } else
777             *comp_id = TLSEXT_ECPOINTFORMAT_uncompressed;
778     }
779     return 1;
780 }
781
782 /* Check an EC key is compatible with extensions */
783 static int tls1_check_ec_key(SSL *s,
784                              unsigned char *curve_id, unsigned char *comp_id)
785 {
786     const unsigned char *pformats, *pcurves;
787     size_t num_formats, num_curves, i;
788     int j;
789     /*
790      * If point formats extension present check it, otherwise everything is
791      * supported (see RFC4492).
792      */
793     if (comp_id && s->session->tlsext_ecpointformatlist) {
794         pformats = s->session->tlsext_ecpointformatlist;
795         num_formats = s->session->tlsext_ecpointformatlist_length;
796         for (i = 0; i < num_formats; i++, pformats++) {
797             if (*comp_id == *pformats)
798                 break;
799         }
800         if (i == num_formats)
801             return 0;
802     }
803     if (!curve_id)
804         return 1;
805     /* Check curve is consistent with client and server preferences */
806     for (j = 0; j <= 1; j++) {
807         if (!tls1_get_curvelist(s, j, &pcurves, &num_curves))
808             return 0;
809         if (j == 1 && num_curves == 0) {
810             /*
811              * If we've not received any curves then skip this check.
812              * RFC 4492 does not require the supported elliptic curves extension
813              * so if it is not sent we can just choose any curve.
814              * It is invalid to send an empty list in the elliptic curves
815              * extension, so num_curves == 0 always means no extension.
816              */
817             break;
818         }
819         for (i = 0; i < num_curves; i++, pcurves += 2) {
820             if (pcurves[0] == curve_id[0] && pcurves[1] == curve_id[1])
821                 break;
822         }
823         if (i == num_curves)
824             return 0;
825         /* For clients can only check sent curve list */
826         if (!s->server)
827             return 1;
828     }
829     return 1;
830 }
831
832 static void tls1_get_formatlist(SSL *s, const unsigned char **pformats,
833                                 size_t *num_formats)
834 {
835     /*
836      * If we have a custom point format list use it otherwise use default
837      */
838     if (s->tlsext_ecpointformatlist) {
839         *pformats = s->tlsext_ecpointformatlist;
840         *num_formats = s->tlsext_ecpointformatlist_length;
841     } else {
842         *pformats = ecformats_default;
843         /* For Suite B we don't support char2 fields */
844         if (tls1_suiteb(s))
845             *num_formats = sizeof(ecformats_default) - 1;
846         else
847             *num_formats = sizeof(ecformats_default);
848     }
849 }
850
851 /*
852  * Check cert parameters compatible with extensions: currently just checks EC
853  * certificates have compatible curves and compression.
854  */
855 static int tls1_check_cert_param(SSL *s, X509 *x, int set_ee_md)
856 {
857     unsigned char comp_id, curve_id[2];
858     EVP_PKEY *pkey;
859     int rv;
860     pkey = X509_get_pubkey(x);
861     if (!pkey)
862         return 0;
863     /* If not EC nothing to do */
864     if (pkey->type != EVP_PKEY_EC) {
865         EVP_PKEY_free(pkey);
866         return 1;
867     }
868     rv = tls1_set_ec_id(curve_id, &comp_id, pkey->pkey.ec);
869     EVP_PKEY_free(pkey);
870     if (!rv)
871         return 0;
872     /*
873      * Can't check curve_id for client certs as we don't have a supported
874      * curves extension.
875      */
876     rv = tls1_check_ec_key(s, s->server ? curve_id : NULL, &comp_id);
877     if (!rv)
878         return 0;
879     /*
880      * Special case for suite B. We *MUST* sign using SHA256+P-256 or
881      * SHA384+P-384, adjust digest if necessary.
882      */
883     if (set_ee_md && tls1_suiteb(s)) {
884         int check_md;
885         size_t i;
886         CERT *c = s->cert;
887         if (curve_id[0])
888             return 0;
889         /* Check to see we have necessary signing algorithm */
890         if (curve_id[1] == TLSEXT_curve_P_256)
891             check_md = NID_ecdsa_with_SHA256;
892         else if (curve_id[1] == TLSEXT_curve_P_384)
893             check_md = NID_ecdsa_with_SHA384;
894         else
895             return 0;           /* Should never happen */
896         for (i = 0; i < c->shared_sigalgslen; i++)
897             if (check_md == c->shared_sigalgs[i].signandhash_nid)
898                 break;
899         if (i == c->shared_sigalgslen)
900             return 0;
901         if (set_ee_md == 2) {
902             if (check_md == NID_ecdsa_with_SHA256)
903                 c->pkeys[SSL_PKEY_ECC].digest = EVP_sha256();
904             else
905                 c->pkeys[SSL_PKEY_ECC].digest = EVP_sha384();
906         }
907     }
908     return rv;
909 }
910
911 # ifndef OPENSSL_NO_ECDH
912 /* Check EC temporary key is compatible with client extensions */
913 int tls1_check_ec_tmp_key(SSL *s, unsigned long cid)
914 {
915     unsigned char curve_id[2];
916     EC_KEY *ec = s->cert->ecdh_tmp;
917 #  ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
918     /* Allow any curve: not just those peer supports */
919     if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
920         return 1;
921 #  endif
922     /*
923      * If Suite B, AES128 MUST use P-256 and AES256 MUST use P-384, no other
924      * curves permitted.
925      */
926     if (tls1_suiteb(s)) {
927         /* Curve to check determined by ciphersuite */
928         if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
929             curve_id[1] = TLSEXT_curve_P_256;
930         else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
931             curve_id[1] = TLSEXT_curve_P_384;
932         else
933             return 0;
934         curve_id[0] = 0;
935         /* Check this curve is acceptable */
936         if (!tls1_check_ec_key(s, curve_id, NULL))
937             return 0;
938         /* If auto or setting curve from callback assume OK */
939         if (s->cert->ecdh_tmp_auto || s->cert->ecdh_tmp_cb)
940             return 1;
941         /* Otherwise check curve is acceptable */
942         else {
943             unsigned char curve_tmp[2];
944             if (!ec)
945                 return 0;
946             if (!tls1_set_ec_id(curve_tmp, NULL, ec))
947                 return 0;
948             if (!curve_tmp[0] || curve_tmp[1] == curve_id[1])
949                 return 1;
950             return 0;
951         }
952
953     }
954     if (s->cert->ecdh_tmp_auto) {
955         /* Need a shared curve */
956         if (tls1_shared_curve(s, 0))
957             return 1;
958         else
959             return 0;
960     }
961     if (!ec) {
962         if (s->cert->ecdh_tmp_cb)
963             return 1;
964         else
965             return 0;
966     }
967     if (!tls1_set_ec_id(curve_id, NULL, ec))
968         return 0;
969 /* Set this to allow use of invalid curves for testing */
970 #  if 0
971     return 1;
972 #  else
973     return tls1_check_ec_key(s, curve_id, NULL);
974 #  endif
975 }
976 # endif                         /* OPENSSL_NO_ECDH */
977
978 #else
979
980 static int tls1_check_cert_param(SSL *s, X509 *x, int set_ee_md)
981 {
982     return 1;
983 }
984
985 #endif                          /* OPENSSL_NO_EC */
986
987 #ifndef OPENSSL_NO_TLSEXT
988
989 /*
990  * List of supported signature algorithms and hashes. Should make this
991  * customisable at some point, for now include everything we support.
992  */
993
994 # ifdef OPENSSL_NO_RSA
995 #  define tlsext_sigalg_rsa(md) /* */
996 # else
997 #  define tlsext_sigalg_rsa(md) md, TLSEXT_signature_rsa,
998 # endif
999
1000 # ifdef OPENSSL_NO_DSA
1001 #  define tlsext_sigalg_dsa(md) /* */
1002 # else
1003 #  define tlsext_sigalg_dsa(md) md, TLSEXT_signature_dsa,
1004 # endif
1005
1006 # ifdef OPENSSL_NO_ECDSA
1007 #  define tlsext_sigalg_ecdsa(md)
1008                                 /* */
1009 # else
1010 #  define tlsext_sigalg_ecdsa(md) md, TLSEXT_signature_ecdsa,
1011 # endif
1012
1013 # define tlsext_sigalg(md) \
1014                 tlsext_sigalg_rsa(md) \
1015                 tlsext_sigalg_dsa(md) \
1016                 tlsext_sigalg_ecdsa(md)
1017
1018 static unsigned char tls12_sigalgs[] = {
1019 # ifndef OPENSSL_NO_SHA512
1020     tlsext_sigalg(TLSEXT_hash_sha512)
1021         tlsext_sigalg(TLSEXT_hash_sha384)
1022 # endif
1023 # ifndef OPENSSL_NO_SHA256
1024         tlsext_sigalg(TLSEXT_hash_sha256)
1025         tlsext_sigalg(TLSEXT_hash_sha224)
1026 # endif
1027 # ifndef OPENSSL_NO_SHA
1028         tlsext_sigalg(TLSEXT_hash_sha1)
1029 # endif
1030 };
1031
1032 # ifndef OPENSSL_NO_ECDSA
1033 static unsigned char suiteb_sigalgs[] = {
1034     tlsext_sigalg_ecdsa(TLSEXT_hash_sha256)
1035         tlsext_sigalg_ecdsa(TLSEXT_hash_sha384)
1036 };
1037 # endif
1038 size_t tls12_get_psigalgs(SSL *s, int sent, const unsigned char **psigs)
1039 {
1040     /*
1041      * If Suite B mode use Suite B sigalgs only, ignore any other
1042      * preferences.
1043      */
1044 # ifndef OPENSSL_NO_EC
1045     switch (tls1_suiteb(s)) {
1046     case SSL_CERT_FLAG_SUITEB_128_LOS:
1047         *psigs = suiteb_sigalgs;
1048         return sizeof(suiteb_sigalgs);
1049
1050     case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
1051         *psigs = suiteb_sigalgs;
1052         return 2;
1053
1054     case SSL_CERT_FLAG_SUITEB_192_LOS:
1055         *psigs = suiteb_sigalgs + 2;
1056         return 2;
1057     }
1058 # endif
1059     /* If server use client authentication sigalgs if not NULL */
1060     if (s->server == sent && s->cert->client_sigalgs) {
1061         *psigs = s->cert->client_sigalgs;
1062         return s->cert->client_sigalgslen;
1063     } else if (s->cert->conf_sigalgs) {
1064         *psigs = s->cert->conf_sigalgs;
1065         return s->cert->conf_sigalgslen;
1066     } else {
1067         *psigs = tls12_sigalgs;
1068         return sizeof(tls12_sigalgs);
1069     }
1070 }
1071
1072 /*
1073  * Check signature algorithm is consistent with sent supported signature
1074  * algorithms and if so return relevant digest.
1075  */
1076 int tls12_check_peer_sigalg(const EVP_MD **pmd, SSL *s,
1077                             const unsigned char *sig, EVP_PKEY *pkey)
1078 {
1079     const unsigned char *sent_sigs;
1080     size_t sent_sigslen, i;
1081     int sigalg = tls12_get_sigid(pkey);
1082     /* Should never happen */
1083     if (sigalg == -1)
1084         return -1;
1085     /* Check key type is consistent with signature */
1086     if (sigalg != (int)sig[1]) {
1087         SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_SIGNATURE_TYPE);
1088         return 0;
1089     }
1090 # ifndef OPENSSL_NO_EC
1091     if (pkey->type == EVP_PKEY_EC) {
1092         unsigned char curve_id[2], comp_id;
1093         /* Check compression and curve matches extensions */
1094         if (!tls1_set_ec_id(curve_id, &comp_id, pkey->pkey.ec))
1095             return 0;
1096         if (!s->server && !tls1_check_ec_key(s, curve_id, &comp_id)) {
1097             SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_CURVE);
1098             return 0;
1099         }
1100         /* If Suite B only P-384+SHA384 or P-256+SHA-256 allowed */
1101         if (tls1_suiteb(s)) {
1102             if (curve_id[0])
1103                 return 0;
1104             if (curve_id[1] == TLSEXT_curve_P_256) {
1105                 if (sig[0] != TLSEXT_hash_sha256) {
1106                     SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,
1107                            SSL_R_ILLEGAL_SUITEB_DIGEST);
1108                     return 0;
1109                 }
1110             } else if (curve_id[1] == TLSEXT_curve_P_384) {
1111                 if (sig[0] != TLSEXT_hash_sha384) {
1112                     SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,
1113                            SSL_R_ILLEGAL_SUITEB_DIGEST);
1114                     return 0;
1115                 }
1116             } else
1117                 return 0;
1118         }
1119     } else if (tls1_suiteb(s))
1120         return 0;
1121 # endif
1122
1123     /* Check signature matches a type we sent */
1124     sent_sigslen = tls12_get_psigalgs(s, 1, &sent_sigs);
1125     for (i = 0; i < sent_sigslen; i += 2, sent_sigs += 2) {
1126         if (sig[0] == sent_sigs[0] && sig[1] == sent_sigs[1])
1127             break;
1128     }
1129     /* Allow fallback to SHA1 if not strict mode */
1130     if (i == sent_sigslen
1131         && (sig[0] != TLSEXT_hash_sha1
1132             || s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)) {
1133         SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_SIGNATURE_TYPE);
1134         return 0;
1135     }
1136     *pmd = tls12_get_hash(sig[0]);
1137     if (*pmd == NULL) {
1138         SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_UNKNOWN_DIGEST);
1139         return 0;
1140     }
1141     /*
1142      * Store the digest used so applications can retrieve it if they wish.
1143      */
1144     if (s->session && s->session->sess_cert)
1145         s->session->sess_cert->peer_key->digest = *pmd;
1146     return 1;
1147 }
1148
1149 /*
1150  * Get a mask of disabled algorithms: an algorithm is disabled if it isn't
1151  * supported or doesn't appear in supported signature algorithms. Unlike
1152  * ssl_cipher_get_disabled this applies to a specific session and not global
1153  * settings.
1154  */
1155 void ssl_set_client_disabled(SSL *s)
1156 {
1157     CERT *c = s->cert;
1158     const unsigned char *sigalgs;
1159     size_t i, sigalgslen;
1160     int have_rsa = 0, have_dsa = 0, have_ecdsa = 0;
1161     c->mask_a = 0;
1162     c->mask_k = 0;
1163     /* Don't allow TLS 1.2 only ciphers if we don't suppport them */
1164     if (!SSL_CLIENT_USE_TLS1_2_CIPHERS(s))
1165         c->mask_ssl = SSL_TLSV1_2;
1166     else
1167         c->mask_ssl = 0;
1168     /*
1169      * Now go through all signature algorithms seeing if we support any for
1170      * RSA, DSA, ECDSA. Do this for all versions not just TLS 1.2.
1171      */
1172     sigalgslen = tls12_get_psigalgs(s, 1, &sigalgs);
1173     for (i = 0; i < sigalgslen; i += 2, sigalgs += 2) {
1174         switch (sigalgs[1]) {
1175 # ifndef OPENSSL_NO_RSA
1176         case TLSEXT_signature_rsa:
1177             have_rsa = 1;
1178             break;
1179 # endif
1180 # ifndef OPENSSL_NO_DSA
1181         case TLSEXT_signature_dsa:
1182             have_dsa = 1;
1183             break;
1184 # endif
1185 # ifndef OPENSSL_NO_ECDSA
1186         case TLSEXT_signature_ecdsa:
1187             have_ecdsa = 1;
1188             break;
1189 # endif
1190         }
1191     }
1192     /*
1193      * Disable auth and static DH if we don't include any appropriate
1194      * signature algorithms.
1195      */
1196     if (!have_rsa) {
1197         c->mask_a |= SSL_aRSA;
1198         c->mask_k |= SSL_kDHr | SSL_kECDHr;
1199     }
1200     if (!have_dsa) {
1201         c->mask_a |= SSL_aDSS;
1202         c->mask_k |= SSL_kDHd;
1203     }
1204     if (!have_ecdsa) {
1205         c->mask_a |= SSL_aECDSA;
1206         c->mask_k |= SSL_kECDHe;
1207     }
1208 # ifndef OPENSSL_NO_KRB5
1209     if (!kssl_tgt_is_available(s->kssl_ctx)) {
1210         c->mask_a |= SSL_aKRB5;
1211         c->mask_k |= SSL_kKRB5;
1212     }
1213 # endif
1214 # ifndef OPENSSL_NO_PSK
1215     /* with PSK there must be client callback set */
1216     if (!s->psk_client_callback) {
1217         c->mask_a |= SSL_aPSK;
1218         c->mask_k |= SSL_kPSK;
1219     }
1220 # endif                         /* OPENSSL_NO_PSK */
1221 # ifndef OPENSSL_NO_SRP
1222     if (!(s->srp_ctx.srp_Mask & SSL_kSRP)) {
1223         c->mask_a |= SSL_aSRP;
1224         c->mask_k |= SSL_kSRP;
1225     }
1226 # endif
1227     c->valid = 1;
1228 }
1229
1230 unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *buf,
1231                                           unsigned char *limit, int *al)
1232 {
1233     int extdatalen = 0;
1234     unsigned char *orig = buf;
1235     unsigned char *ret = buf;
1236 # ifndef OPENSSL_NO_EC
1237     /* See if we support any ECC ciphersuites */
1238     int using_ecc = 0;
1239     if (s->version >= TLS1_VERSION || SSL_IS_DTLS(s)) {
1240         int i;
1241         unsigned long alg_k, alg_a;
1242         STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(s);
1243
1244         for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++) {
1245             SSL_CIPHER *c = sk_SSL_CIPHER_value(cipher_stack, i);
1246
1247             alg_k = c->algorithm_mkey;
1248             alg_a = c->algorithm_auth;
1249             if ((alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe)
1250                  || (alg_a & SSL_aECDSA))) {
1251                 using_ecc = 1;
1252                 break;
1253             }
1254         }
1255     }
1256 # endif
1257
1258     /* don't add extensions for SSLv3 unless doing secure renegotiation */
1259     if (s->client_version == SSL3_VERSION && !s->s3->send_connection_binding)
1260         return orig;
1261
1262     ret += 2;
1263
1264     if (ret >= limit)
1265         return NULL;            /* this really never occurs, but ... */
1266
1267     if (s->tlsext_hostname != NULL) {
1268         /* Add TLS extension servername to the Client Hello message */
1269         size_t size_str;
1270
1271         /*-
1272          * check for enough space.
1273          * 4 for the servername type and entension length
1274          * 2 for servernamelist length
1275          * 1 for the hostname type
1276          * 2 for hostname length
1277          * + hostname length
1278          */
1279         size_str = strlen(s->tlsext_hostname);
1280         if (CHECKLEN(ret, 9 + size_str, limit))
1281             return NULL;
1282
1283         /* extension type and length */
1284         s2n(TLSEXT_TYPE_server_name, ret);
1285         s2n(size_str + 5, ret);
1286
1287         /* length of servername list */
1288         s2n(size_str + 3, ret);
1289
1290         /* hostname type, length and hostname */
1291         *(ret++) = (unsigned char)TLSEXT_NAMETYPE_host_name;
1292         s2n(size_str, ret);
1293         memcpy(ret, s->tlsext_hostname, size_str);
1294         ret += size_str;
1295     }
1296
1297     /* Add RI if renegotiating */
1298     if (s->renegotiate) {
1299         int el;
1300
1301         if (!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0)) {
1302             SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1303             return NULL;
1304         }
1305
1306         if ((limit - ret - 4 - el) < 0)
1307             return NULL;
1308
1309         s2n(TLSEXT_TYPE_renegotiate, ret);
1310         s2n(el, ret);
1311
1312         if (!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el)) {
1313             SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1314             return NULL;
1315         }
1316
1317         ret += el;
1318     }
1319 # ifndef OPENSSL_NO_SRP
1320     /* Add SRP username if there is one */
1321     if (s->srp_ctx.login != NULL) { /* Add TLS extension SRP username to the
1322                                      * Client Hello message */
1323
1324         size_t login_len = strlen(s->srp_ctx.login);
1325         if (login_len > 255 || login_len == 0) {
1326             SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1327             return NULL;
1328         }
1329
1330         /*-
1331          * check for enough space.
1332          * 4 for the srp type type and entension length
1333          * 1 for the srp user identity
1334          * + srp user identity length
1335          */
1336         if (CHECKLEN(ret, 5 + login_len, limit))
1337             return NULL;
1338
1339         /* fill in the extension */
1340         s2n(TLSEXT_TYPE_srp, ret);
1341         s2n(login_len + 1, ret);
1342         (*ret++) = (unsigned char)login_len;
1343         memcpy(ret, s->srp_ctx.login, login_len);
1344         ret += login_len;
1345     }
1346 # endif
1347
1348 # ifndef OPENSSL_NO_EC
1349     if (using_ecc) {
1350         /*
1351          * Add TLS extension ECPointFormats to the ClientHello message
1352          */
1353         const unsigned char *pcurves, *pformats;
1354         size_t num_curves, num_formats, curves_list_len;
1355
1356         tls1_get_formatlist(s, &pformats, &num_formats);
1357
1358         if (num_formats > 255) {
1359             SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1360             return NULL;
1361         }
1362         /*-
1363          * check for enough space.
1364          * 4 bytes for the ec point formats type and extension length
1365          * 1 byte for the length of the formats
1366          * + formats length
1367          */
1368         if (CHECKLEN(ret, 5 + num_formats, limit))
1369             return NULL;
1370
1371         s2n(TLSEXT_TYPE_ec_point_formats, ret);
1372         /* The point format list has 1-byte length. */
1373         s2n(num_formats + 1, ret);
1374         *(ret++) = (unsigned char)num_formats;
1375         memcpy(ret, pformats, num_formats);
1376         ret += num_formats;
1377
1378         /*
1379          * Add TLS extension EllipticCurves to the ClientHello message
1380          */
1381         pcurves = s->tlsext_ellipticcurvelist;
1382         if (!tls1_get_curvelist(s, 0, &pcurves, &num_curves))
1383             return NULL;
1384
1385         if (num_curves > 65532 / 2) {
1386             SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1387             return NULL;
1388         }
1389         curves_list_len = 2 * num_curves;
1390         /*-
1391          * check for enough space.
1392          * 4 bytes for the ec curves type and extension length
1393          * 2 bytes for the curve list length
1394          * + curve list length
1395          */
1396         if (CHECKLEN(ret, 6 + curves_list_len, limit))
1397             return NULL;
1398
1399         s2n(TLSEXT_TYPE_elliptic_curves, ret);
1400         s2n(curves_list_len + 2, ret);
1401         s2n(curves_list_len, ret);
1402         memcpy(ret, pcurves, curves_list_len);
1403         ret += curves_list_len;
1404     }
1405 # endif                         /* OPENSSL_NO_EC */
1406
1407     if (!(SSL_get_options(s) & SSL_OP_NO_TICKET)) {
1408         size_t ticklen;
1409         if (!s->new_session && s->session && s->session->tlsext_tick)
1410             ticklen = s->session->tlsext_ticklen;
1411         else if (s->session && s->tlsext_session_ticket &&
1412                  s->tlsext_session_ticket->data) {
1413             ticklen = s->tlsext_session_ticket->length;
1414             s->session->tlsext_tick = OPENSSL_malloc(ticklen);
1415             if (!s->session->tlsext_tick)
1416                 return NULL;
1417             memcpy(s->session->tlsext_tick,
1418                    s->tlsext_session_ticket->data, ticklen);
1419             s->session->tlsext_ticklen = ticklen;
1420         } else
1421             ticklen = 0;
1422         if (ticklen == 0 && s->tlsext_session_ticket &&
1423             s->tlsext_session_ticket->data == NULL)
1424             goto skip_ext;
1425         /*
1426          * Check for enough room 2 for extension type, 2 for len rest for
1427          * ticket
1428          */
1429         if (CHECKLEN(ret, 4 + ticklen, limit))
1430             return NULL;
1431         s2n(TLSEXT_TYPE_session_ticket, ret);
1432         s2n(ticklen, ret);
1433         if (ticklen > 0) {
1434             memcpy(ret, s->session->tlsext_tick, ticklen);
1435             ret += ticklen;
1436         }
1437     }
1438  skip_ext:
1439
1440     if (SSL_CLIENT_USE_SIGALGS(s)) {
1441         size_t salglen;
1442         const unsigned char *salg;
1443         salglen = tls12_get_psigalgs(s, 1, &salg);
1444
1445         /*-
1446          * check for enough space.
1447          * 4 bytes for the sigalgs type and extension length
1448          * 2 bytes for the sigalg list length
1449          * + sigalg list length
1450          */
1451         if (CHECKLEN(ret, salglen + 6, limit))
1452             return NULL;
1453         s2n(TLSEXT_TYPE_signature_algorithms, ret);
1454         s2n(salglen + 2, ret);
1455         s2n(salglen, ret);
1456         memcpy(ret, salg, salglen);
1457         ret += salglen;
1458     }
1459 # ifdef TLSEXT_TYPE_opaque_prf_input
1460     if (s->s3->client_opaque_prf_input != NULL) {
1461         size_t col = s->s3->client_opaque_prf_input_len;
1462
1463         if ((long)(limit - ret - 6 - col < 0))
1464             return NULL;
1465         if (col > 0xFFFD)       /* can't happen */
1466             return NULL;
1467
1468         s2n(TLSEXT_TYPE_opaque_prf_input, ret);
1469         s2n(col + 2, ret);
1470         s2n(col, ret);
1471         memcpy(ret, s->s3->client_opaque_prf_input, col);
1472         ret += col;
1473     }
1474 # endif
1475
1476     if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) {
1477         int i;
1478         size_t extlen, idlen;
1479         int lentmp;
1480         OCSP_RESPID *id;
1481
1482         idlen = 0;
1483         for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++) {
1484             id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
1485             lentmp = i2d_OCSP_RESPID(id, NULL);
1486             if (lentmp <= 0)
1487                 return NULL;
1488             idlen += (size_t)lentmp + 2;
1489         }
1490
1491         if (s->tlsext_ocsp_exts) {
1492             lentmp = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL);
1493             if (lentmp < 0)
1494                 return NULL;
1495             extlen = (size_t)lentmp;
1496         } else
1497             extlen = 0;
1498
1499         if (extlen + idlen > 0xFFF0)
1500             return NULL;
1501         /*
1502          * 2 bytes for status request type
1503          * 2 bytes for status request len
1504          * 1 byte for OCSP request type
1505          * 2 bytes for length of ids
1506          * 2 bytes for length of extensions
1507          * + length of ids
1508          * + length of extensions
1509          */
1510         if (CHECKLEN(ret, 9 + idlen + extlen, limit))
1511             return NULL;
1512
1513         s2n(TLSEXT_TYPE_status_request, ret);
1514         s2n(extlen + idlen + 5, ret);
1515         *(ret++) = TLSEXT_STATUSTYPE_ocsp;
1516         s2n(idlen, ret);
1517         for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++) {
1518             /* save position of id len */
1519             unsigned char *q = ret;
1520             id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
1521             /* skip over id len */
1522             ret += 2;
1523             lentmp = i2d_OCSP_RESPID(id, &ret);
1524             /* write id len */
1525             s2n(lentmp, q);
1526         }
1527         s2n(extlen, ret);
1528         if (extlen > 0)
1529             i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret);
1530     }
1531 # ifndef OPENSSL_NO_HEARTBEATS
1532     /* Add Heartbeat extension */
1533
1534     /*-
1535      * check for enough space.
1536      * 4 bytes for the heartbeat ext type and extension length
1537      * 1 byte for the mode
1538      */
1539     if (CHECKLEN(ret, 5, limit))
1540         return NULL;
1541
1542     s2n(TLSEXT_TYPE_heartbeat, ret);
1543     s2n(1, ret);
1544     /*-
1545      * Set mode:
1546      * 1: peer may send requests
1547      * 2: peer not allowed to send requests
1548      */
1549     if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1550         *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1551     else
1552         *(ret++) = SSL_TLSEXT_HB_ENABLED;
1553 # endif
1554
1555 # ifndef OPENSSL_NO_NEXTPROTONEG
1556     if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len) {
1557         /*
1558          * The client advertises an emtpy extension to indicate its support
1559          * for Next Protocol Negotiation
1560          */
1561
1562         /*-
1563          * check for enough space.
1564          * 4 bytes for the NPN ext type and extension length
1565          */
1566         if (CHECKLEN(ret, 4, limit))
1567             return NULL;
1568         s2n(TLSEXT_TYPE_next_proto_neg, ret);
1569         s2n(0, ret);
1570     }
1571 # endif
1572
1573     if (s->alpn_client_proto_list && !s->s3->tmp.finish_md_len) {
1574         /*-
1575          * check for enough space.
1576          * 4 bytes for the ALPN type and extension length
1577          * 2 bytes for the ALPN protocol list length
1578          * + ALPN protocol list length
1579          */
1580         if (CHECKLEN(ret, 6 + s->alpn_client_proto_list_len, limit))
1581             return NULL;
1582         s2n(TLSEXT_TYPE_application_layer_protocol_negotiation, ret);
1583         s2n(2 + s->alpn_client_proto_list_len, ret);
1584         s2n(s->alpn_client_proto_list_len, ret);
1585         memcpy(ret, s->alpn_client_proto_list, s->alpn_client_proto_list_len);
1586         ret += s->alpn_client_proto_list_len;
1587         s->cert->alpn_sent = 1;
1588     }
1589 # ifndef OPENSSL_NO_SRTP
1590     if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s)) {
1591         int el;
1592
1593         ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0);
1594
1595         /*-
1596          * check for enough space.
1597          * 4 bytes for the SRTP type and extension length
1598          * + SRTP profiles length
1599          */
1600         if (CHECKLEN(ret, 4 + el, limit))
1601             return NULL;
1602
1603         s2n(TLSEXT_TYPE_use_srtp, ret);
1604         s2n(el, ret);
1605
1606         if (ssl_add_clienthello_use_srtp_ext(s, ret, &el, el)) {
1607             SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1608             return NULL;
1609         }
1610         ret += el;
1611     }
1612 # endif
1613     custom_ext_init(&s->cert->cli_ext);
1614     /* Add custom TLS Extensions to ClientHello */
1615     if (!custom_ext_add(s, 0, &ret, limit, al))
1616         return NULL;
1617
1618     /*
1619      * Add padding to workaround bugs in F5 terminators. See
1620      * https://tools.ietf.org/html/draft-agl-tls-padding-03 NB: because this
1621      * code works out the length of all existing extensions it MUST always
1622      * appear last.
1623      */
1624     if (s->options & SSL_OP_TLSEXT_PADDING) {
1625         int hlen = ret - (unsigned char *)s->init_buf->data;
1626         /*
1627          * The code in s23_clnt.c to build ClientHello messages includes the
1628          * 5-byte record header in the buffer, while the code in s3_clnt.c
1629          * does not.
1630          */
1631         if (s->state == SSL23_ST_CW_CLNT_HELLO_A)
1632             hlen -= 5;
1633         if (hlen > 0xff && hlen < 0x200) {
1634             hlen = 0x200 - hlen;
1635             if (hlen >= 4)
1636                 hlen -= 4;
1637             else
1638                 hlen = 0;
1639
1640             /*-
1641              * check for enough space. Strictly speaking we know we've already
1642              * got enough space because to get here the message size is < 0x200,
1643              * but we know that we've allocated far more than that in the buffer
1644              * - but for consistency and robustness we're going to check anyway.
1645              *
1646              * 4 bytes for the padding type and extension length
1647              * + padding length
1648              */
1649             if (CHECKLEN(ret, 4 + hlen, limit))
1650                 return NULL;
1651             s2n(TLSEXT_TYPE_padding, ret);
1652             s2n(hlen, ret);
1653             memset(ret, 0, hlen);
1654             ret += hlen;
1655         }
1656     }
1657
1658     if ((extdatalen = ret - orig - 2) == 0)
1659         return orig;
1660
1661     s2n(extdatalen, orig);
1662     return ret;
1663 }
1664
1665 unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *buf,
1666                                           unsigned char *limit, int *al)
1667 {
1668     int extdatalen = 0;
1669     unsigned char *orig = buf;
1670     unsigned char *ret = buf;
1671 # ifndef OPENSSL_NO_NEXTPROTONEG
1672     int next_proto_neg_seen;
1673 # endif
1674 # ifndef OPENSSL_NO_EC
1675     unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1676     unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1677     int using_ecc = (alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe))
1678         || (alg_a & SSL_aECDSA);
1679     using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL);
1680 # endif
1681     /*
1682      * don't add extensions for SSLv3, unless doing secure renegotiation
1683      */
1684     if (s->version == SSL3_VERSION && !s->s3->send_connection_binding)
1685         return orig;
1686
1687     ret += 2;
1688     if (ret >= limit)
1689         return NULL;            /* this really never occurs, but ... */
1690
1691     if (!s->hit && s->servername_done == 1
1692         && s->session->tlsext_hostname != NULL) {
1693         if ((long)(limit - ret - 4) < 0)
1694             return NULL;
1695
1696         s2n(TLSEXT_TYPE_server_name, ret);
1697         s2n(0, ret);
1698     }
1699
1700     if (s->s3->send_connection_binding) {
1701         int el;
1702
1703         if (!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0)) {
1704             SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1705             return NULL;
1706         }
1707
1708         /*-
1709          * check for enough space.
1710          * 4 bytes for the reneg type and extension length
1711          * + reneg data length
1712          */
1713         if (CHECKLEN(ret, 4 + el, limit))
1714             return NULL;
1715
1716         s2n(TLSEXT_TYPE_renegotiate, ret);
1717         s2n(el, ret);
1718
1719         if (!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el)) {
1720             SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1721             return NULL;
1722         }
1723
1724         ret += el;
1725     }
1726 # ifndef OPENSSL_NO_EC
1727     if (using_ecc) {
1728         const unsigned char *plist;
1729         size_t plistlen;
1730         /*
1731          * Add TLS extension ECPointFormats to the ServerHello message
1732          */
1733
1734         tls1_get_formatlist(s, &plist, &plistlen);
1735
1736         if (plistlen > 255) {
1737             SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1738             return NULL;
1739         }
1740
1741         /*-
1742          * check for enough space.
1743          * 4 bytes for the ec points format type and extension length
1744          * 1 byte for the points format list length
1745          * + length of points format list
1746          */
1747         if (CHECKLEN(ret, 5 + plistlen, limit))
1748             return NULL;
1749
1750         s2n(TLSEXT_TYPE_ec_point_formats, ret);
1751         s2n(plistlen + 1, ret);
1752         *(ret++) = (unsigned char)plistlen;
1753         memcpy(ret, plist, plistlen);
1754         ret += plistlen;
1755
1756     }
1757     /*
1758      * Currently the server should not respond with a SupportedCurves
1759      * extension
1760      */
1761 # endif                         /* OPENSSL_NO_EC */
1762
1763     if (s->tlsext_ticket_expected && !(SSL_get_options(s) & SSL_OP_NO_TICKET)) {
1764         /*-
1765          * check for enough space.
1766          * 4 bytes for the Ticket type and extension length
1767          */
1768         if (CHECKLEN(ret, 4, limit))
1769             return NULL;
1770         s2n(TLSEXT_TYPE_session_ticket, ret);
1771         s2n(0, ret);
1772     } else {
1773         /* if we don't add the above TLSEXT, we can't add a session ticket later */
1774         s->tlsext_ticket_expected = 0;
1775     }
1776
1777     if (s->tlsext_status_expected) {
1778         /*-
1779          * check for enough space.
1780          * 4 bytes for the Status request type and extension length
1781          */
1782         if (CHECKLEN(ret, 4, limit))
1783             return NULL;
1784         s2n(TLSEXT_TYPE_status_request, ret);
1785         s2n(0, ret);
1786     }
1787 # ifdef TLSEXT_TYPE_opaque_prf_input
1788     if (s->s3->server_opaque_prf_input != NULL) {
1789         size_t sol = s->s3->server_opaque_prf_input_len;
1790
1791         if ((long)(limit - ret - 6 - sol) < 0)
1792             return NULL;
1793         if (sol > 0xFFFD)       /* can't happen */
1794             return NULL;
1795
1796         s2n(TLSEXT_TYPE_opaque_prf_input, ret);
1797         s2n(sol + 2, ret);
1798         s2n(sol, ret);
1799         memcpy(ret, s->s3->server_opaque_prf_input, sol);
1800         ret += sol;
1801     }
1802 # endif
1803
1804 # ifndef OPENSSL_NO_SRTP
1805     if (SSL_IS_DTLS(s) && s->srtp_profile) {
1806         int el;
1807
1808         ssl_add_serverhello_use_srtp_ext(s, 0, &el, 0);
1809
1810         /*-
1811          * check for enough space.
1812          * 4 bytes for the SRTP profiles type and extension length
1813          * + length of the SRTP profiles list
1814          */
1815         if (CHECKLEN(ret, 4 + el, limit))
1816             return NULL;
1817
1818         s2n(TLSEXT_TYPE_use_srtp, ret);
1819         s2n(el, ret);
1820
1821         if (ssl_add_serverhello_use_srtp_ext(s, ret, &el, el)) {
1822             SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1823             return NULL;
1824         }
1825         ret += el;
1826     }
1827 # endif
1828
1829     if (((s->s3->tmp.new_cipher->id & 0xFFFF) == 0x80
1830          || (s->s3->tmp.new_cipher->id & 0xFFFF) == 0x81)
1831         && (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG)) {
1832         const unsigned char cryptopro_ext[36] = {
1833             0xfd, 0xe8,         /* 65000 */
1834             0x00, 0x20,         /* 32 bytes length */
1835             0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85,
1836             0x03, 0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06,
1837             0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08,
1838             0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17
1839         };
1840
1841         /* check for enough space. */
1842         if (CHECKLEN(ret, sizeof(cryptopro_ext), limit))
1843             return NULL;
1844         memcpy(ret, cryptopro_ext, sizeof(cryptopro_ext));
1845         ret += sizeof(cryptopro_ext);
1846
1847     }
1848 # ifndef OPENSSL_NO_HEARTBEATS
1849     /* Add Heartbeat extension if we've received one */
1850     if (s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) {
1851         /*-
1852          * check for enough space.
1853          * 4 bytes for the Heartbeat type and extension length
1854          * 1 byte for the mode
1855          */
1856         if (CHECKLEN(ret, 5, limit))
1857             return NULL;
1858         s2n(TLSEXT_TYPE_heartbeat, ret);
1859         s2n(1, ret);
1860         /*-
1861          * Set mode:
1862          * 1: peer may send requests
1863          * 2: peer not allowed to send requests
1864          */
1865         if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1866             *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1867         else
1868             *(ret++) = SSL_TLSEXT_HB_ENABLED;
1869
1870     }
1871 # endif
1872
1873 # ifndef OPENSSL_NO_NEXTPROTONEG
1874     next_proto_neg_seen = s->s3->next_proto_neg_seen;
1875     s->s3->next_proto_neg_seen = 0;
1876     if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb) {
1877         const unsigned char *npa;
1878         unsigned int npalen;
1879         int r;
1880
1881         r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen,
1882                                               s->
1883                                               ctx->next_protos_advertised_cb_arg);
1884         if (r == SSL_TLSEXT_ERR_OK) {
1885             /*-
1886              * check for enough space.
1887              * 4 bytes for the NPN type and extension length
1888              * + length of protocols list
1889              */
1890             if (CHECKLEN(ret, 4 + npalen, limit))
1891                 return NULL;
1892             s2n(TLSEXT_TYPE_next_proto_neg, ret);
1893             s2n(npalen, ret);
1894             memcpy(ret, npa, npalen);
1895             ret += npalen;
1896             s->s3->next_proto_neg_seen = 1;
1897         }
1898     }
1899 # endif
1900     if (!custom_ext_add(s, 1, &ret, limit, al))
1901         return NULL;
1902
1903     if (s->s3->alpn_selected) {
1904         const unsigned char *selected = s->s3->alpn_selected;
1905         size_t len = s->s3->alpn_selected_len;
1906
1907         /*-
1908          * check for enough space.
1909          * 4 bytes for the ALPN type and extension length
1910          * 2 bytes for ALPN data length
1911          * 1 byte for selected protocol length
1912          * + length of the selected protocol
1913          */
1914         if (CHECKLEN(ret, 7 + len, limit))
1915             return NULL;
1916         s2n(TLSEXT_TYPE_application_layer_protocol_negotiation, ret);
1917         s2n(3 + len, ret);
1918         s2n(1 + len, ret);
1919         *ret++ = (unsigned char)len;
1920         memcpy(ret, selected, len);
1921         ret += len;
1922     }
1923
1924     if ((extdatalen = ret - orig - 2) == 0)
1925         return orig;
1926
1927     s2n(extdatalen, orig);
1928     return ret;
1929 }
1930
1931 # ifndef OPENSSL_NO_EC
1932 /*-
1933  * ssl_check_for_safari attempts to fingerprint Safari using OS X
1934  * SecureTransport using the TLS extension block in |d|, of length |n|.
1935  * Safari, since 10.6, sends exactly these extensions, in this order:
1936  *   SNI,
1937  *   elliptic_curves
1938  *   ec_point_formats
1939  *
1940  * We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,
1941  * but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.
1942  * Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from
1943  * 10.8..10.8.3 (which don't work).
1944  */
1945 static void ssl_check_for_safari(SSL *s, const unsigned char *data,
1946                                  const unsigned char *limit)
1947 {
1948     unsigned short type, size;
1949     static const unsigned char kSafariExtensionsBlock[] = {
1950         0x00, 0x0a,             /* elliptic_curves extension */
1951         0x00, 0x08,             /* 8 bytes */
1952         0x00, 0x06,             /* 6 bytes of curve ids */
1953         0x00, 0x17,             /* P-256 */
1954         0x00, 0x18,             /* P-384 */
1955         0x00, 0x19,             /* P-521 */
1956
1957         0x00, 0x0b,             /* ec_point_formats */
1958         0x00, 0x02,             /* 2 bytes */
1959         0x01,                   /* 1 point format */
1960         0x00,                   /* uncompressed */
1961     };
1962
1963     /* The following is only present in TLS 1.2 */
1964     static const unsigned char kSafariTLS12ExtensionsBlock[] = {
1965         0x00, 0x0d,             /* signature_algorithms */
1966         0x00, 0x0c,             /* 12 bytes */
1967         0x00, 0x0a,             /* 10 bytes */
1968         0x05, 0x01,             /* SHA-384/RSA */
1969         0x04, 0x01,             /* SHA-256/RSA */
1970         0x02, 0x01,             /* SHA-1/RSA */
1971         0x04, 0x03,             /* SHA-256/ECDSA */
1972         0x02, 0x03,             /* SHA-1/ECDSA */
1973     };
1974
1975     if (limit - data <= 2)
1976         return;
1977     data += 2;
1978
1979     if (limit - data < 4)
1980         return;
1981     n2s(data, type);
1982     n2s(data, size);
1983
1984     if (type != TLSEXT_TYPE_server_name)
1985         return;
1986
1987     if (limit - data < size)
1988         return;
1989     data += size;
1990
1991     if (TLS1_get_client_version(s) >= TLS1_2_VERSION) {
1992         const size_t len1 = sizeof(kSafariExtensionsBlock);
1993         const size_t len2 = sizeof(kSafariTLS12ExtensionsBlock);
1994
1995         if (limit - data != (int)(len1 + len2))
1996             return;
1997         if (memcmp(data, kSafariExtensionsBlock, len1) != 0)
1998             return;
1999         if (memcmp(data + len1, kSafariTLS12ExtensionsBlock, len2) != 0)
2000             return;
2001     } else {
2002         const size_t len = sizeof(kSafariExtensionsBlock);
2003
2004         if (limit - data != (int)(len))
2005             return;
2006         if (memcmp(data, kSafariExtensionsBlock, len) != 0)
2007             return;
2008     }
2009
2010     s->s3->is_probably_safari = 1;
2011 }
2012 # endif                         /* !OPENSSL_NO_EC */
2013
2014 /*
2015  * tls1_alpn_handle_client_hello is called to save the ALPN extension in a
2016  * ClientHello.  data: the contents of the extension, not including the type
2017  * and length.  data_len: the number of bytes in |data| al: a pointer to the
2018  * alert value to send in the event of a non-zero return.  returns: 0 on
2019  * success.
2020  */
2021 static int tls1_alpn_handle_client_hello(SSL *s, const unsigned char *data,
2022                                          unsigned data_len, int *al)
2023 {
2024     unsigned i;
2025     unsigned proto_len;
2026
2027     if (data_len < 2)
2028         goto parse_error;
2029
2030     /*
2031      * data should contain a uint16 length followed by a series of 8-bit,
2032      * length-prefixed strings.
2033      */
2034     i = ((unsigned)data[0]) << 8 | ((unsigned)data[1]);
2035     data_len -= 2;
2036     data += 2;
2037     if (data_len != i)
2038         goto parse_error;
2039
2040     if (data_len < 2)
2041         goto parse_error;
2042
2043     for (i = 0; i < data_len;) {
2044         proto_len = data[i];
2045         i++;
2046
2047         if (proto_len == 0)
2048             goto parse_error;
2049
2050         if (i + proto_len < i || i + proto_len > data_len)
2051             goto parse_error;
2052
2053         i += proto_len;
2054     }
2055
2056     if (s->cert->alpn_proposed != NULL)
2057         OPENSSL_free(s->cert->alpn_proposed);
2058     s->cert->alpn_proposed = OPENSSL_malloc(data_len);
2059     if (s->cert->alpn_proposed == NULL) {
2060         *al = SSL_AD_INTERNAL_ERROR;
2061         return -1;
2062     }
2063     memcpy(s->cert->alpn_proposed, data, data_len);
2064     s->cert->alpn_proposed_len = data_len;
2065     return 0;
2066
2067  parse_error:
2068     *al = SSL_AD_DECODE_ERROR;
2069     return -1;
2070 }
2071
2072 /*
2073  * Process the ALPN extension in a ClientHello.
2074  * al: a pointer to the alert value to send in the event of a failure.
2075  * returns 1 on success, 0 on failure: al set only on failure
2076  */
2077 static int tls1_alpn_handle_client_hello_late(SSL *s, int *al)
2078 {
2079     const unsigned char *selected = NULL;
2080     unsigned char selected_len = 0;
2081
2082     if (s->ctx->alpn_select_cb != NULL && s->cert->alpn_proposed != NULL) {
2083         int r = s->ctx->alpn_select_cb(s, &selected, &selected_len,
2084                                        s->cert->alpn_proposed,
2085                                        s->cert->alpn_proposed_len,
2086                                        s->ctx->alpn_select_cb_arg);
2087
2088         if (r == SSL_TLSEXT_ERR_OK) {
2089             OPENSSL_free(s->s3->alpn_selected);
2090             s->s3->alpn_selected = OPENSSL_malloc(selected_len);
2091             if (s->s3->alpn_selected == NULL) {
2092                 *al = SSL_AD_INTERNAL_ERROR;
2093                 return 0;
2094             }
2095             memcpy(s->s3->alpn_selected, selected, selected_len);
2096             s->s3->alpn_selected_len = selected_len;
2097 # ifndef OPENSSL_NO_NEXTPROTONEG
2098             /* ALPN takes precedence over NPN. */
2099             s->s3->next_proto_neg_seen = 0;
2100 # endif
2101         }
2102     }
2103
2104     return 1;
2105 }
2106
2107 static int ssl_scan_clienthello_tlsext(SSL *s, unsigned char **p,
2108                                        unsigned char *limit, int *al)
2109 {
2110     unsigned short type;
2111     unsigned short size;
2112     unsigned short len;
2113     unsigned char *data = *p;
2114     int renegotiate_seen = 0;
2115
2116     s->servername_done = 0;
2117     s->tlsext_status_type = -1;
2118 # ifndef OPENSSL_NO_NEXTPROTONEG
2119     s->s3->next_proto_neg_seen = 0;
2120 # endif
2121
2122     if (s->s3->alpn_selected) {
2123         OPENSSL_free(s->s3->alpn_selected);
2124         s->s3->alpn_selected = NULL;
2125     }
2126     s->s3->alpn_selected_len = 0;
2127     if (s->cert->alpn_proposed) {
2128         OPENSSL_free(s->cert->alpn_proposed);
2129         s->cert->alpn_proposed = NULL;
2130     }
2131     s->cert->alpn_proposed_len = 0;
2132 # ifndef OPENSSL_NO_HEARTBEATS
2133     s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
2134                              SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
2135 # endif
2136
2137 # ifndef OPENSSL_NO_EC
2138     if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
2139         ssl_check_for_safari(s, data, limit);
2140 # endif                         /* !OPENSSL_NO_EC */
2141
2142     /* Clear any signature algorithms extension received */
2143     if (s->cert->peer_sigalgs) {
2144         OPENSSL_free(s->cert->peer_sigalgs);
2145         s->cert->peer_sigalgs = NULL;
2146     }
2147 # ifndef OPENSSL_NO_SRP
2148     if (s->srp_ctx.login != NULL) {
2149         OPENSSL_free(s->srp_ctx.login);
2150         s->srp_ctx.login = NULL;
2151     }
2152 # endif
2153
2154     s->srtp_profile = NULL;
2155
2156     if (data == limit)
2157         goto ri_check;
2158
2159     if (limit - data < 2)
2160         goto err;
2161
2162     n2s(data, len);
2163
2164     if (limit - data != len)
2165         goto err;
2166
2167     while (limit - data >= 4) {
2168         n2s(data, type);
2169         n2s(data, size);
2170
2171         if (limit - data < size)
2172             goto err;
2173 # if 0
2174         fprintf(stderr, "Received extension type %d size %d\n", type, size);
2175 # endif
2176         if (s->tlsext_debug_cb)
2177             s->tlsext_debug_cb(s, 0, type, data, size, s->tlsext_debug_arg);
2178 /*-
2179  * The servername extension is treated as follows:
2180  *
2181  * - Only the hostname type is supported with a maximum length of 255.
2182  * - The servername is rejected if too long or if it contains zeros,
2183  *   in which case an fatal alert is generated.
2184  * - The servername field is maintained together with the session cache.
2185  * - When a session is resumed, the servername call back invoked in order
2186  *   to allow the application to position itself to the right context.
2187  * - The servername is acknowledged if it is new for a session or when
2188  *   it is identical to a previously used for the same session.
2189  *   Applications can control the behaviour.  They can at any time
2190  *   set a 'desirable' servername for a new SSL object. This can be the
2191  *   case for example with HTTPS when a Host: header field is received and
2192  *   a renegotiation is requested. In this case, a possible servername
2193  *   presented in the new client hello is only acknowledged if it matches
2194  *   the value of the Host: field.
2195  * - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
2196  *   if they provide for changing an explicit servername context for the
2197  *   session, i.e. when the session has been established with a servername
2198  *   extension.
2199  * - On session reconnect, the servername extension may be absent.
2200  *
2201  */
2202
2203         if (type == TLSEXT_TYPE_server_name) {
2204             unsigned char *sdata;
2205             int servname_type;
2206             int dsize;
2207
2208             if (size < 2)
2209                 goto err;
2210             n2s(data, dsize);
2211             size -= 2;
2212             if (dsize > size)
2213                 goto err;
2214
2215             sdata = data;
2216             while (dsize > 3) {
2217                 servname_type = *(sdata++);
2218                 n2s(sdata, len);
2219                 dsize -= 3;
2220
2221                 if (len > dsize)
2222                     goto err;
2223
2224                 if (s->servername_done == 0)
2225                     switch (servname_type) {
2226                     case TLSEXT_NAMETYPE_host_name:
2227                         if (!s->hit) {
2228                             if (s->session->tlsext_hostname)
2229                                 goto err;
2230
2231                             if (len > TLSEXT_MAXLEN_host_name) {
2232                                 *al = TLS1_AD_UNRECOGNIZED_NAME;
2233                                 return 0;
2234                             }
2235                             if ((s->session->tlsext_hostname =
2236                                  OPENSSL_malloc(len + 1)) == NULL) {
2237                                 *al = TLS1_AD_INTERNAL_ERROR;
2238                                 return 0;
2239                             }
2240                             memcpy(s->session->tlsext_hostname, sdata, len);
2241                             s->session->tlsext_hostname[len] = '\0';
2242                             if (strlen(s->session->tlsext_hostname) != len) {
2243                                 OPENSSL_free(s->session->tlsext_hostname);
2244                                 s->session->tlsext_hostname = NULL;
2245                                 *al = TLS1_AD_UNRECOGNIZED_NAME;
2246                                 return 0;
2247                             }
2248                             s->servername_done = 1;
2249
2250                         } else
2251                             s->servername_done = s->session->tlsext_hostname
2252                                 && strlen(s->session->tlsext_hostname) == len
2253                                 && strncmp(s->session->tlsext_hostname,
2254                                            (char *)sdata, len) == 0;
2255
2256                         break;
2257
2258                     default:
2259                         break;
2260                     }
2261
2262                 dsize -= len;
2263             }
2264             if (dsize != 0)
2265                 goto err;
2266
2267         }
2268 # ifndef OPENSSL_NO_SRP
2269         else if (type == TLSEXT_TYPE_srp) {
2270             if (size == 0 || ((len = data[0])) != (size - 1))
2271                 goto err;
2272             if (s->srp_ctx.login != NULL)
2273                 goto err;
2274             if ((s->srp_ctx.login = OPENSSL_malloc(len + 1)) == NULL)
2275                 return -1;
2276             memcpy(s->srp_ctx.login, &data[1], len);
2277             s->srp_ctx.login[len] = '\0';
2278
2279             if (strlen(s->srp_ctx.login) != len)
2280                 goto err;
2281         }
2282 # endif
2283
2284 # ifndef OPENSSL_NO_EC
2285         else if (type == TLSEXT_TYPE_ec_point_formats) {
2286             unsigned char *sdata = data;
2287             int ecpointformatlist_length;
2288
2289             if (size == 0)
2290                 goto err;
2291
2292             ecpointformatlist_length = *(sdata++);
2293             if (ecpointformatlist_length != size - 1 ||
2294                 ecpointformatlist_length < 1)
2295                 goto err;
2296             if (!s->hit) {
2297                 if (s->session->tlsext_ecpointformatlist) {
2298                     OPENSSL_free(s->session->tlsext_ecpointformatlist);
2299                     s->session->tlsext_ecpointformatlist = NULL;
2300                 }
2301                 s->session->tlsext_ecpointformatlist_length = 0;
2302                 if ((s->session->tlsext_ecpointformatlist =
2303                      OPENSSL_malloc(ecpointformatlist_length)) == NULL) {
2304                     *al = TLS1_AD_INTERNAL_ERROR;
2305                     return 0;
2306                 }
2307                 s->session->tlsext_ecpointformatlist_length =
2308                     ecpointformatlist_length;
2309                 memcpy(s->session->tlsext_ecpointformatlist, sdata,
2310                        ecpointformatlist_length);
2311             }
2312 #  if 0
2313             fprintf(stderr,
2314                     "ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ",
2315                     s->session->tlsext_ecpointformatlist_length);
2316             sdata = s->session->tlsext_ecpointformatlist;
2317             for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2318                 fprintf(stderr, "%i ", *(sdata++));
2319             fprintf(stderr, "\n");
2320 #  endif
2321         } else if (type == TLSEXT_TYPE_elliptic_curves) {
2322             unsigned char *sdata = data;
2323             int ellipticcurvelist_length = (*(sdata++) << 8);
2324             ellipticcurvelist_length += (*(sdata++));
2325
2326             if (ellipticcurvelist_length != size - 2 ||
2327                 ellipticcurvelist_length < 1 ||
2328                 /* Each NamedCurve is 2 bytes. */
2329                 ellipticcurvelist_length & 1)
2330                     goto err;
2331
2332             if (!s->hit) {
2333                 if (s->session->tlsext_ellipticcurvelist)
2334                     goto err;
2335
2336                 s->session->tlsext_ellipticcurvelist_length = 0;
2337                 if ((s->session->tlsext_ellipticcurvelist =
2338                      OPENSSL_malloc(ellipticcurvelist_length)) == NULL) {
2339                     *al = TLS1_AD_INTERNAL_ERROR;
2340                     return 0;
2341                 }
2342                 s->session->tlsext_ellipticcurvelist_length =
2343                     ellipticcurvelist_length;
2344                 memcpy(s->session->tlsext_ellipticcurvelist, sdata,
2345                        ellipticcurvelist_length);
2346             }
2347 #  if 0
2348             fprintf(stderr,
2349                     "ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ",
2350                     s->session->tlsext_ellipticcurvelist_length);
2351             sdata = s->session->tlsext_ellipticcurvelist;
2352             for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++)
2353                 fprintf(stderr, "%i ", *(sdata++));
2354             fprintf(stderr, "\n");
2355 #  endif
2356         }
2357 # endif                         /* OPENSSL_NO_EC */
2358 # ifdef TLSEXT_TYPE_opaque_prf_input
2359         else if (type == TLSEXT_TYPE_opaque_prf_input) {
2360             unsigned char *sdata = data;
2361
2362             if (size < 2) {
2363                 *al = SSL_AD_DECODE_ERROR;
2364                 return 0;
2365             }
2366             n2s(sdata, s->s3->client_opaque_prf_input_len);
2367             if (s->s3->client_opaque_prf_input_len != size - 2) {
2368                 *al = SSL_AD_DECODE_ERROR;
2369                 return 0;
2370             }
2371
2372             if (s->s3->client_opaque_prf_input != NULL) {
2373                 /* shouldn't really happen */
2374                 OPENSSL_free(s->s3->client_opaque_prf_input);
2375             }
2376
2377             /* dummy byte just to get non-NULL */
2378             if (s->s3->client_opaque_prf_input_len == 0)
2379                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1);
2380             else
2381                 s->s3->client_opaque_prf_input =
2382                     BUF_memdup(sdata, s->s3->client_opaque_prf_input_len);
2383             if (s->s3->client_opaque_prf_input == NULL) {
2384                 *al = TLS1_AD_INTERNAL_ERROR;
2385                 return 0;
2386             }
2387         }
2388 # endif
2389         else if (type == TLSEXT_TYPE_session_ticket) {
2390             if (s->tls_session_ticket_ext_cb &&
2391                 !s->tls_session_ticket_ext_cb(s, data, size,
2392                                               s->tls_session_ticket_ext_cb_arg))
2393             {
2394                 *al = TLS1_AD_INTERNAL_ERROR;
2395                 return 0;
2396             }
2397         } else if (type == TLSEXT_TYPE_renegotiate) {
2398             if (!ssl_parse_clienthello_renegotiate_ext(s, data, size, al))
2399                 return 0;
2400             renegotiate_seen = 1;
2401         } else if (type == TLSEXT_TYPE_signature_algorithms) {
2402             int dsize;
2403             if (s->cert->peer_sigalgs || size < 2)
2404                 goto err;
2405             n2s(data, dsize);
2406             size -= 2;
2407             if (dsize != size || dsize & 1 || !dsize)
2408                 goto err;
2409             if (!tls1_save_sigalgs(s, data, dsize))
2410                 goto err;
2411         } else if (type == TLSEXT_TYPE_status_request && !s->hit) {
2412             if (size < 5)
2413                 goto err;
2414
2415             s->tlsext_status_type = *data++;
2416             size--;
2417             if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) {
2418                 const unsigned char *sdata;
2419                 int dsize;
2420                 /* Read in responder_id_list */
2421                 n2s(data, dsize);
2422                 size -= 2;
2423                 if (dsize > size)
2424                     goto err;
2425
2426                 /*
2427                  * We remove any OCSP_RESPIDs from a previous handshake
2428                  * to prevent unbounded memory growth - CVE-2016-6304
2429                  */
2430                 sk_OCSP_RESPID_pop_free(s->tlsext_ocsp_ids,
2431                                         OCSP_RESPID_free);
2432                 if (dsize > 0) {
2433                     s->tlsext_ocsp_ids = sk_OCSP_RESPID_new_null();
2434                     if (s->tlsext_ocsp_ids == NULL) {
2435                         *al = SSL_AD_INTERNAL_ERROR;
2436                         return 0;
2437                     }
2438                 } else {
2439                     s->tlsext_ocsp_ids = NULL;
2440                 }
2441
2442                 while (dsize > 0) {
2443                     OCSP_RESPID *id;
2444                     int idsize;
2445                     if (dsize < 4)
2446                         goto err;
2447                     n2s(data, idsize);
2448                     dsize -= 2 + idsize;
2449                     size -= 2 + idsize;
2450                     if (dsize < 0)
2451                         goto err;
2452                     sdata = data;
2453                     data += idsize;
2454                     id = d2i_OCSP_RESPID(NULL, &sdata, idsize);
2455                     if (!id)
2456                         goto err;
2457                     if (data != sdata) {
2458                         OCSP_RESPID_free(id);
2459                         goto err;
2460                     }
2461                     if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) {
2462                         OCSP_RESPID_free(id);
2463                         *al = SSL_AD_INTERNAL_ERROR;
2464                         return 0;
2465                     }
2466                 }
2467
2468                 /* Read in request_extensions */
2469                 if (size < 2)
2470                     goto err;
2471                 n2s(data, dsize);
2472                 size -= 2;
2473                 if (dsize != size)
2474                     goto err;
2475                 sdata = data;
2476                 if (dsize > 0) {
2477                     if (s->tlsext_ocsp_exts) {
2478                         sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
2479                                                    X509_EXTENSION_free);
2480                     }
2481
2482                     s->tlsext_ocsp_exts =
2483                         d2i_X509_EXTENSIONS(NULL, &sdata, dsize);
2484                     if (!s->tlsext_ocsp_exts || (data + dsize != sdata))
2485                         goto err;
2486                 }
2487             }
2488             /*
2489              * We don't know what to do with any other type * so ignore it.
2490              */
2491             else
2492                 s->tlsext_status_type = -1;
2493         }
2494 # ifndef OPENSSL_NO_HEARTBEATS
2495         else if (type == TLSEXT_TYPE_heartbeat) {
2496             switch (data[0]) {
2497             case 0x01:         /* Client allows us to send HB requests */
2498                 s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2499                 break;
2500             case 0x02:         /* Client doesn't accept HB requests */
2501                 s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2502                 s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2503                 break;
2504             default:
2505                 *al = SSL_AD_ILLEGAL_PARAMETER;
2506                 return 0;
2507             }
2508         }
2509 # endif
2510 # ifndef OPENSSL_NO_NEXTPROTONEG
2511         else if (type == TLSEXT_TYPE_next_proto_neg &&
2512                  s->s3->tmp.finish_md_len == 0) {
2513             /*-
2514              * We shouldn't accept this extension on a
2515              * renegotiation.
2516              *
2517              * s->new_session will be set on renegotiation, but we
2518              * probably shouldn't rely that it couldn't be set on
2519              * the initial renegotation too in certain cases (when
2520              * there's some other reason to disallow resuming an
2521              * earlier session -- the current code won't be doing
2522              * anything like that, but this might change).
2523              *
2524              * A valid sign that there's been a previous handshake
2525              * in this connection is if s->s3->tmp.finish_md_len >
2526              * 0.  (We are talking about a check that will happen
2527              * in the Hello protocol round, well before a new
2528              * Finished message could have been computed.)
2529              */
2530             s->s3->next_proto_neg_seen = 1;
2531         }
2532 # endif
2533
2534         else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation &&
2535                  s->s3->tmp.finish_md_len == 0) {
2536             if (tls1_alpn_handle_client_hello(s, data, size, al) != 0)
2537                 return 0;
2538         }
2539
2540         /* session ticket processed earlier */
2541 # ifndef OPENSSL_NO_SRTP
2542         else if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s)
2543                  && type == TLSEXT_TYPE_use_srtp) {
2544             if (ssl_parse_clienthello_use_srtp_ext(s, data, size, al))
2545                 return 0;
2546         }
2547 # endif
2548
2549         data += size;
2550     }
2551
2552     /* Spurious data on the end */
2553     if (data != limit)
2554         goto err;
2555
2556     *p = data;
2557
2558  ri_check:
2559
2560     /* Need RI if renegotiating */
2561
2562     if (!renegotiate_seen && s->renegotiate &&
2563         !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
2564         *al = SSL_AD_HANDSHAKE_FAILURE;
2565         SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
2566                SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2567         return 0;
2568     }
2569
2570     return 1;
2571 err:
2572     *al = SSL_AD_DECODE_ERROR;
2573     return 0;
2574 }
2575
2576 /*
2577  * Parse any custom extensions found.  "data" is the start of the extension data
2578  * and "limit" is the end of the record. TODO: add strict syntax checking.
2579  */
2580
2581 static int ssl_scan_clienthello_custom_tlsext(SSL *s,
2582                                               const unsigned char *data,
2583                                               const unsigned char *limit,
2584                                               int *al)
2585 {
2586     unsigned short type, size, len;
2587     /* If resumed session or no custom extensions nothing to do */
2588     if (s->hit || s->cert->srv_ext.meths_count == 0)
2589         return 1;
2590
2591     if (limit - data <= 2)
2592         return 1;
2593     n2s(data, len);
2594
2595     if (limit - data < len)
2596         return 1;
2597
2598     while (limit - data >= 4) {
2599         n2s(data, type);
2600         n2s(data, size);
2601
2602         if (limit - data < size)
2603             return 1;
2604         if (custom_ext_parse(s, 1 /* server */ , type, data, size, al) <= 0)
2605             return 0;
2606
2607         data += size;
2608     }
2609
2610     return 1;
2611 }
2612
2613 int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p,
2614                                  unsigned char *limit)
2615 {
2616     int al = -1;
2617     unsigned char *ptmp = *p;
2618     /*
2619      * Internally supported extensions are parsed first so SNI can be handled
2620      * before custom extensions. An application processing SNI will typically
2621      * switch the parent context using SSL_set_SSL_CTX and custom extensions
2622      * need to be handled by the new SSL_CTX structure.
2623      */
2624     if (ssl_scan_clienthello_tlsext(s, p, limit, &al) <= 0) {
2625         ssl3_send_alert(s, SSL3_AL_FATAL, al);
2626         return 0;
2627     }
2628
2629     if (ssl_check_clienthello_tlsext_early(s) <= 0) {
2630         SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT, SSL_R_CLIENTHELLO_TLSEXT);
2631         return 0;
2632     }
2633
2634     custom_ext_init(&s->cert->srv_ext);
2635     if (ssl_scan_clienthello_custom_tlsext(s, ptmp, limit, &al) <= 0) {
2636         ssl3_send_alert(s, SSL3_AL_FATAL, al);
2637         return 0;
2638     }
2639
2640     return 1;
2641 }
2642
2643 # ifndef OPENSSL_NO_NEXTPROTONEG
2644 /*
2645  * ssl_next_proto_validate validates a Next Protocol Negotiation block. No
2646  * elements of zero length are allowed and the set of elements must exactly
2647  * fill the length of the block.
2648  */
2649 static char ssl_next_proto_validate(unsigned char *d, unsigned len)
2650 {
2651     unsigned int off = 0;
2652
2653     while (off < len) {
2654         if (d[off] == 0)
2655             return 0;
2656         off += d[off];
2657         off++;
2658     }
2659
2660     return off == len;
2661 }
2662 # endif
2663
2664 static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p,
2665                                        unsigned char *d, int n, int *al)
2666 {
2667     unsigned short length;
2668     unsigned short type;
2669     unsigned short size;
2670     unsigned char *data = *p;
2671     int tlsext_servername = 0;
2672     int renegotiate_seen = 0;
2673
2674 # ifndef OPENSSL_NO_NEXTPROTONEG
2675     s->s3->next_proto_neg_seen = 0;
2676 # endif
2677     s->tlsext_ticket_expected = 0;
2678
2679     if (s->s3->alpn_selected) {
2680         OPENSSL_free(s->s3->alpn_selected);
2681         s->s3->alpn_selected = NULL;
2682     }
2683 # ifndef OPENSSL_NO_HEARTBEATS
2684     s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
2685                              SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
2686 # endif
2687
2688     if ((d + n) - data <= 2)
2689         goto ri_check;
2690
2691     n2s(data, length);
2692     if ((d + n) - data != length) {
2693         *al = SSL_AD_DECODE_ERROR;
2694         return 0;
2695     }
2696
2697     while ((d + n) - data >= 4) {
2698         n2s(data, type);
2699         n2s(data, size);
2700
2701         if ((d + n) - data < size)
2702             goto ri_check;
2703
2704         if (s->tlsext_debug_cb)
2705             s->tlsext_debug_cb(s, 1, type, data, size, s->tlsext_debug_arg);
2706
2707         if (type == TLSEXT_TYPE_server_name) {
2708             if (s->tlsext_hostname == NULL || size > 0) {
2709                 *al = TLS1_AD_UNRECOGNIZED_NAME;
2710                 return 0;
2711             }
2712             tlsext_servername = 1;
2713         }
2714 # ifndef OPENSSL_NO_EC
2715         else if (type == TLSEXT_TYPE_ec_point_formats) {
2716             unsigned char *sdata = data;
2717             int ecpointformatlist_length;
2718
2719             if (size == 0) {
2720                 *al = TLS1_AD_DECODE_ERROR;
2721                 return 0;
2722             }
2723
2724             ecpointformatlist_length = *(sdata++);
2725             if (ecpointformatlist_length != size - 1) {
2726                 *al = TLS1_AD_DECODE_ERROR;
2727                 return 0;
2728             }
2729             if (!s->hit) {
2730                 s->session->tlsext_ecpointformatlist_length = 0;
2731                 if (s->session->tlsext_ecpointformatlist != NULL)
2732                     OPENSSL_free(s->session->tlsext_ecpointformatlist);
2733                 if ((s->session->tlsext_ecpointformatlist =
2734                      OPENSSL_malloc(ecpointformatlist_length)) == NULL) {
2735                     *al = TLS1_AD_INTERNAL_ERROR;
2736                     return 0;
2737                 }
2738                 s->session->tlsext_ecpointformatlist_length =
2739                     ecpointformatlist_length;
2740                 memcpy(s->session->tlsext_ecpointformatlist, sdata,
2741                        ecpointformatlist_length);
2742             }
2743 #  if 0
2744             fprintf(stderr,
2745                     "ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist ");
2746             sdata = s->session->tlsext_ecpointformatlist;
2747             for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2748                 fprintf(stderr, "%i ", *(sdata++));
2749             fprintf(stderr, "\n");
2750 #  endif
2751         }
2752 # endif                         /* OPENSSL_NO_EC */
2753
2754         else if (type == TLSEXT_TYPE_session_ticket) {
2755             if (s->tls_session_ticket_ext_cb &&
2756                 !s->tls_session_ticket_ext_cb(s, data, size,
2757                                               s->tls_session_ticket_ext_cb_arg))
2758             {
2759                 *al = TLS1_AD_INTERNAL_ERROR;
2760                 return 0;
2761             }
2762             if ((SSL_get_options(s) & SSL_OP_NO_TICKET)
2763                 || (size > 0)) {
2764                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2765                 return 0;
2766             }
2767             s->tlsext_ticket_expected = 1;
2768         }
2769 # ifdef TLSEXT_TYPE_opaque_prf_input
2770         else if (type == TLSEXT_TYPE_opaque_prf_input) {
2771             unsigned char *sdata = data;
2772
2773             if (size < 2) {
2774                 *al = SSL_AD_DECODE_ERROR;
2775                 return 0;
2776             }
2777             n2s(sdata, s->s3->server_opaque_prf_input_len);
2778             if (s->s3->server_opaque_prf_input_len != size - 2) {
2779                 *al = SSL_AD_DECODE_ERROR;
2780                 return 0;
2781             }
2782
2783             if (s->s3->server_opaque_prf_input != NULL) {
2784                 /* shouldn't really happen */
2785                 OPENSSL_free(s->s3->server_opaque_prf_input);
2786             }
2787             if (s->s3->server_opaque_prf_input_len == 0) {
2788                 /* dummy byte just to get non-NULL */
2789                 s->s3->server_opaque_prf_input = OPENSSL_malloc(1);
2790             } else {
2791                 s->s3->server_opaque_prf_input =
2792                     BUF_memdup(sdata, s->s3->server_opaque_prf_input_len);
2793             }
2794
2795             if (s->s3->server_opaque_prf_input == NULL) {
2796                 *al = TLS1_AD_INTERNAL_ERROR;
2797                 return 0;
2798             }
2799         }
2800 # endif
2801         else if (type == TLSEXT_TYPE_status_request) {
2802             /*
2803              * MUST be empty and only sent if we've requested a status
2804              * request message.
2805              */
2806             if ((s->tlsext_status_type == -1) || (size > 0)) {
2807                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2808                 return 0;
2809             }
2810             /* Set flag to expect CertificateStatus message */
2811             s->tlsext_status_expected = 1;
2812         }
2813 # ifndef OPENSSL_NO_NEXTPROTONEG
2814         else if (type == TLSEXT_TYPE_next_proto_neg &&
2815                  s->s3->tmp.finish_md_len == 0) {
2816             unsigned char *selected;
2817             unsigned char selected_len;
2818
2819             /* We must have requested it. */
2820             if (s->ctx->next_proto_select_cb == NULL) {
2821                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2822                 return 0;
2823             }
2824             /* The data must be valid */
2825             if (!ssl_next_proto_validate(data, size)) {
2826                 *al = TLS1_AD_DECODE_ERROR;
2827                 return 0;
2828             }
2829             if (s->
2830                 ctx->next_proto_select_cb(s, &selected, &selected_len, data,
2831                                           size,
2832                                           s->ctx->next_proto_select_cb_arg) !=
2833                 SSL_TLSEXT_ERR_OK) {
2834                 *al = TLS1_AD_INTERNAL_ERROR;
2835                 return 0;
2836             }
2837             /*
2838              * Could be non-NULL if server has sent multiple NPN extensions in
2839              * a single Serverhello
2840              */
2841             OPENSSL_free(s->next_proto_negotiated);
2842             s->next_proto_negotiated = OPENSSL_malloc(selected_len);
2843             if (!s->next_proto_negotiated) {
2844                 *al = TLS1_AD_INTERNAL_ERROR;
2845                 return 0;
2846             }
2847             memcpy(s->next_proto_negotiated, selected, selected_len);
2848             s->next_proto_negotiated_len = selected_len;
2849             s->s3->next_proto_neg_seen = 1;
2850         }
2851 # endif
2852
2853         else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation) {
2854             unsigned len;
2855
2856             /* We must have requested it. */
2857             if (!s->cert->alpn_sent) {
2858                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2859                 return 0;
2860             }
2861             if (size < 4) {
2862                 *al = TLS1_AD_DECODE_ERROR;
2863                 return 0;
2864             }
2865             /*-
2866              * The extension data consists of:
2867              *   uint16 list_length
2868              *   uint8 proto_length;
2869              *   uint8 proto[proto_length];
2870              */
2871             len = data[0];
2872             len <<= 8;
2873             len |= data[1];
2874             if (len != (unsigned)size - 2) {
2875                 *al = TLS1_AD_DECODE_ERROR;
2876                 return 0;
2877             }
2878             len = data[2];
2879             if (len != (unsigned)size - 3) {
2880                 *al = TLS1_AD_DECODE_ERROR;
2881                 return 0;
2882             }
2883             if (s->s3->alpn_selected)
2884                 OPENSSL_free(s->s3->alpn_selected);
2885             s->s3->alpn_selected = OPENSSL_malloc(len);
2886             if (!s->s3->alpn_selected) {
2887                 *al = TLS1_AD_INTERNAL_ERROR;
2888                 return 0;
2889             }
2890             memcpy(s->s3->alpn_selected, data + 3, len);
2891             s->s3->alpn_selected_len = len;
2892         }
2893
2894         else if (type == TLSEXT_TYPE_renegotiate) {
2895             if (!ssl_parse_serverhello_renegotiate_ext(s, data, size, al))
2896                 return 0;
2897             renegotiate_seen = 1;
2898         }
2899 # ifndef OPENSSL_NO_HEARTBEATS
2900         else if (type == TLSEXT_TYPE_heartbeat) {
2901             switch (data[0]) {
2902             case 0x01:         /* Server allows us to send HB requests */
2903                 s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2904                 break;
2905             case 0x02:         /* Server doesn't accept HB requests */
2906                 s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2907                 s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2908                 break;
2909             default:
2910                 *al = SSL_AD_ILLEGAL_PARAMETER;
2911                 return 0;
2912             }
2913         }
2914 # endif
2915 # ifndef OPENSSL_NO_SRTP
2916         else if (SSL_IS_DTLS(s) && type == TLSEXT_TYPE_use_srtp) {
2917             if (ssl_parse_serverhello_use_srtp_ext(s, data, size, al))
2918                 return 0;
2919         }
2920 # endif
2921         /*
2922          * If this extension type was not otherwise handled, but matches a
2923          * custom_cli_ext_record, then send it to the c callback
2924          */
2925         else if (custom_ext_parse(s, 0, type, data, size, al) <= 0)
2926             return 0;
2927
2928         data += size;
2929     }
2930
2931     if (data != d + n) {
2932         *al = SSL_AD_DECODE_ERROR;
2933         return 0;
2934     }
2935
2936     if (!s->hit && tlsext_servername == 1) {
2937         if (s->tlsext_hostname) {
2938             if (s->session->tlsext_hostname == NULL) {
2939                 s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);
2940                 if (!s->session->tlsext_hostname) {
2941                     *al = SSL_AD_UNRECOGNIZED_NAME;
2942                     return 0;
2943                 }
2944             } else {
2945                 *al = SSL_AD_DECODE_ERROR;
2946                 return 0;
2947             }
2948         }
2949     }
2950
2951     *p = data;
2952
2953  ri_check:
2954
2955     /*
2956      * Determine if we need to see RI. Strictly speaking if we want to avoid
2957      * an attack we should *always* see RI even on initial server hello
2958      * because the client doesn't see any renegotiation during an attack.
2959      * However this would mean we could not connect to any server which
2960      * doesn't support RI so for the immediate future tolerate RI absence on
2961      * initial connect only.
2962      */
2963     if (!renegotiate_seen && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
2964         && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
2965         *al = SSL_AD_HANDSHAKE_FAILURE;
2966         SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT,
2967                SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2968         return 0;
2969     }
2970
2971     return 1;
2972 }
2973
2974 int ssl_prepare_clienthello_tlsext(SSL *s)
2975 {
2976
2977 # ifdef TLSEXT_TYPE_opaque_prf_input
2978     {
2979         int r = 1;
2980
2981         if (s->ctx->tlsext_opaque_prf_input_callback != 0) {
2982             r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0,
2983                                                          s->
2984                                                          ctx->tlsext_opaque_prf_input_callback_arg);
2985             if (!r)
2986                 return -1;
2987         }
2988
2989         if (s->tlsext_opaque_prf_input != NULL) {
2990             if (s->s3->client_opaque_prf_input != NULL) {
2991                 /* shouldn't really happen */
2992                 OPENSSL_free(s->s3->client_opaque_prf_input);
2993             }
2994
2995             if (s->tlsext_opaque_prf_input_len == 0) {
2996                 /* dummy byte just to get non-NULL */
2997                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1);
2998             } else {
2999                 s->s3->client_opaque_prf_input =
3000                     BUF_memdup(s->tlsext_opaque_prf_input,
3001                                s->tlsext_opaque_prf_input_len);
3002             }
3003             if (s->s3->client_opaque_prf_input == NULL) {
3004                 SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,
3005                        ERR_R_MALLOC_FAILURE);
3006                 return -1;
3007             }
3008             s->s3->client_opaque_prf_input_len =
3009                 s->tlsext_opaque_prf_input_len;
3010         }
3011
3012         if (r == 2)
3013             /*
3014              * at callback's request, insist on receiving an appropriate
3015              * server opaque PRF input
3016              */
3017             s->s3->server_opaque_prf_input_len =
3018                 s->tlsext_opaque_prf_input_len;
3019     }
3020 # endif
3021
3022     s->cert->alpn_sent = 0;
3023     return 1;
3024 }
3025
3026 int ssl_prepare_serverhello_tlsext(SSL *s)
3027 {
3028     return 1;
3029 }
3030
3031 static int ssl_check_clienthello_tlsext_early(SSL *s)
3032 {
3033     int ret = SSL_TLSEXT_ERR_NOACK;
3034     int al = SSL_AD_UNRECOGNIZED_NAME;
3035
3036 # ifndef OPENSSL_NO_EC
3037     /*
3038      * The handling of the ECPointFormats extension is done elsewhere, namely
3039      * in ssl3_choose_cipher in s3_lib.c.
3040      */
3041     /*
3042      * The handling of the EllipticCurves extension is done elsewhere, namely
3043      * in ssl3_choose_cipher in s3_lib.c.
3044      */
3045 # endif
3046
3047     if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0)
3048         ret =
3049             s->ctx->tlsext_servername_callback(s, &al,
3050                                                s->ctx->tlsext_servername_arg);
3051     else if (s->initial_ctx != NULL
3052              && s->initial_ctx->tlsext_servername_callback != 0)
3053         ret =
3054             s->initial_ctx->tlsext_servername_callback(s, &al,
3055                                                        s->
3056                                                        initial_ctx->tlsext_servername_arg);
3057
3058 # ifdef TLSEXT_TYPE_opaque_prf_input
3059     {
3060         /*
3061          * This sort of belongs into ssl_prepare_serverhello_tlsext(), but we
3062          * might be sending an alert in response to the client hello, so this
3063          * has to happen here in ssl_check_clienthello_tlsext_early().
3064          */
3065
3066         int r = 1;
3067
3068         if (s->ctx->tlsext_opaque_prf_input_callback != 0) {
3069             r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0,
3070                                                          s->
3071                                                          ctx->tlsext_opaque_prf_input_callback_arg);
3072             if (!r) {
3073                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3074                 al = SSL_AD_INTERNAL_ERROR;
3075                 goto err;
3076             }
3077         }
3078
3079         if (s->s3->server_opaque_prf_input != NULL) {
3080             /* shouldn't really happen */
3081             OPENSSL_free(s->s3->server_opaque_prf_input);
3082         }
3083         s->s3->server_opaque_prf_input = NULL;
3084
3085         if (s->tlsext_opaque_prf_input != NULL) {
3086             if (s->s3->client_opaque_prf_input != NULL &&
3087                 s->s3->client_opaque_prf_input_len ==
3088                 s->tlsext_opaque_prf_input_len) {
3089                 /*
3090                  * can only use this extension if we have a server opaque PRF
3091                  * input of the same length as the client opaque PRF input!
3092                  */
3093
3094                 if (s->tlsext_opaque_prf_input_len == 0) {
3095                     /* dummy byte just to get non-NULL */
3096                     s->s3->server_opaque_prf_input = OPENSSL_malloc(1);
3097                 } else {
3098                     s->s3->server_opaque_prf_input =
3099                         BUF_memdup(s->tlsext_opaque_prf_input,
3100                                    s->tlsext_opaque_prf_input_len);
3101                 }
3102                 if (s->s3->server_opaque_prf_input == NULL) {
3103                     ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3104                     al = SSL_AD_INTERNAL_ERROR;
3105                     goto err;
3106                 }
3107                 s->s3->server_opaque_prf_input_len =
3108                     s->tlsext_opaque_prf_input_len;
3109             }
3110         }
3111
3112         if (r == 2 && s->s3->server_opaque_prf_input == NULL) {
3113             /*
3114              * The callback wants to enforce use of the extension, but we
3115              * can't do that with the client opaque PRF input; abort the
3116              * handshake.
3117              */
3118             ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3119             al = SSL_AD_HANDSHAKE_FAILURE;
3120         }
3121     }
3122
3123  err:
3124 # endif
3125     switch (ret) {
3126     case SSL_TLSEXT_ERR_ALERT_FATAL:
3127         ssl3_send_alert(s, SSL3_AL_FATAL, al);
3128         return -1;
3129
3130     case SSL_TLSEXT_ERR_ALERT_WARNING:
3131         ssl3_send_alert(s, SSL3_AL_WARNING, al);
3132         return 1;
3133
3134     case SSL_TLSEXT_ERR_NOACK:
3135         s->servername_done = 0;
3136     default:
3137         return 1;
3138     }
3139 }
3140
3141 int tls1_set_server_sigalgs(SSL *s)
3142 {
3143     int al;
3144     size_t i;
3145     /* Clear any shared sigtnature algorithms */
3146     if (s->cert->shared_sigalgs) {
3147         OPENSSL_free(s->cert->shared_sigalgs);
3148         s->cert->shared_sigalgs = NULL;
3149         s->cert->shared_sigalgslen = 0;
3150     }
3151     /* Clear certificate digests and validity flags */
3152     for (i = 0; i < SSL_PKEY_NUM; i++) {
3153         s->cert->pkeys[i].digest = NULL;
3154         s->cert->pkeys[i].valid_flags = 0;
3155     }
3156
3157     /* If sigalgs received process it. */
3158     if (s->cert->peer_sigalgs) {
3159         if (!tls1_process_sigalgs(s)) {
3160             SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS, ERR_R_MALLOC_FAILURE);
3161             al = SSL_AD_INTERNAL_ERROR;
3162             goto err;
3163         }
3164         /* Fatal error is no shared signature algorithms */
3165         if (!s->cert->shared_sigalgs) {
3166             SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS,
3167                    SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
3168             al = SSL_AD_HANDSHAKE_FAILURE;
3169             goto err;
3170         }
3171     } else
3172         ssl_cert_set_default_md(s->cert);
3173     return 1;
3174  err:
3175     ssl3_send_alert(s, SSL3_AL_FATAL, al);
3176     return 0;
3177 }
3178
3179 /*
3180  * Upon success, returns 1.
3181  * Upon failure, returns 0 and sets |al| to the appropriate fatal alert.
3182  */
3183 int ssl_check_clienthello_tlsext_late(SSL *s, int *al)
3184 {
3185
3186     /*
3187      * If status request then ask callback what to do. Note: this must be
3188      * called after servername callbacks in case the certificate has changed,
3189      * and must be called after the cipher has been chosen because this may
3190      * influence which certificate is sent
3191      */
3192     if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb) {
3193         int ret;
3194         CERT_PKEY *certpkey;
3195         certpkey = ssl_get_server_send_pkey(s);
3196         /* If no certificate can't return certificate status */
3197         if (certpkey != NULL) {
3198             /*
3199              * Set current certificate to one we will use so SSL_get_certificate
3200              * et al can pick it up.
3201              */
3202             s->cert->key = certpkey;
3203             ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
3204             switch (ret) {
3205                 /* We don't want to send a status request response */
3206             case SSL_TLSEXT_ERR_NOACK:
3207                 s->tlsext_status_expected = 0;
3208                 break;
3209                 /* status request response should be sent */
3210             case SSL_TLSEXT_ERR_OK:
3211                 if (s->tlsext_ocsp_resp)
3212                     s->tlsext_status_expected = 1;
3213                 break;
3214                 /* something bad happened */
3215             case SSL_TLSEXT_ERR_ALERT_FATAL:
3216             default:
3217                 *al = SSL_AD_INTERNAL_ERROR;
3218                 return 0;
3219             }
3220         }
3221     }
3222
3223     if (!tls1_alpn_handle_client_hello_late(s, al)) {
3224         return 0;
3225     }
3226
3227     return 1;
3228 }
3229
3230 int ssl_check_serverhello_tlsext(SSL *s)
3231 {
3232     int ret = SSL_TLSEXT_ERR_NOACK;
3233     int al = SSL_AD_UNRECOGNIZED_NAME;
3234
3235 # ifndef OPENSSL_NO_EC
3236     /*
3237      * If we are client and using an elliptic curve cryptography cipher
3238      * suite, then if server returns an EC point formats lists extension it
3239      * must contain uncompressed.
3240      */
3241     unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3242     unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
3243     if ((s->tlsext_ecpointformatlist != NULL)
3244         && (s->tlsext_ecpointformatlist_length > 0)
3245         && (s->session->tlsext_ecpointformatlist != NULL)
3246         && (s->session->tlsext_ecpointformatlist_length > 0)
3247         && ((alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe))
3248             || (alg_a & SSL_aECDSA))) {
3249         /* we are using an ECC cipher */
3250         size_t i;
3251         unsigned char *list;
3252         int found_uncompressed = 0;
3253         list = s->session->tlsext_ecpointformatlist;
3254         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++) {
3255             if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed) {
3256                 found_uncompressed = 1;
3257                 break;
3258             }
3259         }
3260         if (!found_uncompressed) {
3261             SSLerr(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT,
3262                    SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
3263             return -1;
3264         }
3265     }
3266     ret = SSL_TLSEXT_ERR_OK;
3267 # endif                         /* OPENSSL_NO_EC */
3268
3269     if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0)
3270         ret =
3271             s->ctx->tlsext_servername_callback(s, &al,
3272                                                s->ctx->tlsext_servername_arg);
3273     else if (s->initial_ctx != NULL
3274              && s->initial_ctx->tlsext_servername_callback != 0)
3275         ret =
3276             s->initial_ctx->tlsext_servername_callback(s, &al,
3277                                                        s->
3278                                                        initial_ctx->tlsext_servername_arg);
3279
3280 # ifdef TLSEXT_TYPE_opaque_prf_input
3281     if (s->s3->server_opaque_prf_input_len > 0) {
3282         /*
3283          * This case may indicate that we, as a client, want to insist on
3284          * using opaque PRF inputs. So first verify that we really have a
3285          * value from the server too.
3286          */
3287
3288         if (s->s3->server_opaque_prf_input == NULL) {
3289             ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3290             al = SSL_AD_HANDSHAKE_FAILURE;
3291         }
3292
3293         /*
3294          * Anytime the server *has* sent an opaque PRF input, we need to
3295          * check that we have a client opaque PRF input of the same size.
3296          */
3297         if (s->s3->client_opaque_prf_input == NULL ||
3298             s->s3->client_opaque_prf_input_len !=
3299             s->s3->server_opaque_prf_input_len) {
3300             ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3301             al = SSL_AD_ILLEGAL_PARAMETER;
3302         }
3303     }
3304 # endif
3305
3306     OPENSSL_free(s->tlsext_ocsp_resp);
3307     s->tlsext_ocsp_resp = NULL;
3308     s->tlsext_ocsp_resplen = -1;
3309     /*
3310      * If we've requested certificate status and we wont get one tell the
3311      * callback
3312      */
3313     if ((s->tlsext_status_type != -1) && !(s->tlsext_status_expected)
3314         && !(s->hit) && s->ctx && s->ctx->tlsext_status_cb) {
3315         int r;
3316         /*
3317          * Call callback with resp == NULL and resplen == -1 so callback
3318          * knows there is no response
3319          */
3320         r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
3321         if (r == 0) {
3322             al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
3323             ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3324         }
3325         if (r < 0) {
3326             al = SSL_AD_INTERNAL_ERROR;
3327             ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3328         }
3329     }
3330
3331     switch (ret) {
3332     case SSL_TLSEXT_ERR_ALERT_FATAL:
3333         ssl3_send_alert(s, SSL3_AL_FATAL, al);
3334         return -1;
3335
3336     case SSL_TLSEXT_ERR_ALERT_WARNING:
3337         ssl3_send_alert(s, SSL3_AL_WARNING, al);
3338         return 1;
3339
3340     case SSL_TLSEXT_ERR_NOACK:
3341         s->servername_done = 0;
3342     default:
3343         return 1;
3344     }
3345 }
3346
3347 int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d,
3348                                  int n)
3349 {
3350     int al = -1;
3351     if (s->version < SSL3_VERSION)
3352         return 1;
3353     if (ssl_scan_serverhello_tlsext(s, p, d, n, &al) <= 0) {
3354         ssl3_send_alert(s, SSL3_AL_FATAL, al);
3355         return 0;
3356     }
3357
3358     if (ssl_check_serverhello_tlsext(s) <= 0) {
3359         SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT, SSL_R_SERVERHELLO_TLSEXT);
3360         return 0;
3361     }
3362     return 1;
3363 }
3364
3365 /*-
3366  * Since the server cache lookup is done early on in the processing of the
3367  * ClientHello, and other operations depend on the result, we need to handle
3368  * any TLS session ticket extension at the same time.
3369  *
3370  *   session_id: points at the session ID in the ClientHello. This code will
3371  *       read past the end of this in order to parse out the session ticket
3372  *       extension, if any.
3373  *   len: the length of the session ID.
3374  *   limit: a pointer to the first byte after the ClientHello.
3375  *   ret: (output) on return, if a ticket was decrypted, then this is set to
3376  *       point to the resulting session.
3377  *
3378  * If s->tls_session_secret_cb is set then we are expecting a pre-shared key
3379  * ciphersuite, in which case we have no use for session tickets and one will
3380  * never be decrypted, nor will s->tlsext_ticket_expected be set to 1.
3381  *
3382  * Returns:
3383  *   -1: fatal error, either from parsing or decrypting the ticket.
3384  *    0: no ticket was found (or was ignored, based on settings).
3385  *    1: a zero length extension was found, indicating that the client supports
3386  *       session tickets but doesn't currently have one to offer.
3387  *    2: either s->tls_session_secret_cb was set, or a ticket was offered but
3388  *       couldn't be decrypted because of a non-fatal error.
3389  *    3: a ticket was successfully decrypted and *ret was set.
3390  *
3391  * Side effects:
3392  *   Sets s->tlsext_ticket_expected to 1 if the server will have to issue
3393  *   a new session ticket to the client because the client indicated support
3394  *   (and s->tls_session_secret_cb is NULL) but the client either doesn't have
3395  *   a session ticket or we couldn't use the one it gave us, or if
3396  *   s->ctx->tlsext_ticket_key_cb asked to renew the client's ticket.
3397  *   Otherwise, s->tlsext_ticket_expected is set to 0.
3398  */
3399 int tls1_process_ticket(SSL *s, unsigned char *session_id, int len,
3400                         const unsigned char *limit, SSL_SESSION **ret)
3401 {
3402     /* Point after session ID in client hello */
3403     const unsigned char *p = session_id + len;
3404     unsigned short i;
3405
3406     *ret = NULL;
3407     s->tlsext_ticket_expected = 0;
3408
3409     /*
3410      * If tickets disabled behave as if no ticket present to permit stateful
3411      * resumption.
3412      */
3413     if (SSL_get_options(s) & SSL_OP_NO_TICKET)
3414         return 0;
3415     if ((s->version <= SSL3_VERSION) || !limit)
3416         return 0;
3417     if (p >= limit)
3418         return -1;
3419     /* Skip past DTLS cookie */
3420     if (SSL_IS_DTLS(s)) {
3421         i = *(p++);
3422
3423         if (limit - p <= i)
3424             return -1;
3425
3426         p += i;
3427     }
3428     /* Skip past cipher list */
3429     n2s(p, i);
3430     if (limit - p <= i)
3431         return -1;
3432     p += i;
3433
3434     /* Skip past compression algorithm list */
3435     i = *(p++);
3436     if (limit - p < i)
3437         return -1;
3438     p += i;
3439
3440     /* Now at start of extensions */
3441     if (limit - p <= 2)
3442         return 0;
3443     n2s(p, i);
3444     while (limit - p >= 4) {
3445         unsigned short type, size;
3446         n2s(p, type);
3447         n2s(p, size);
3448         if (limit - p < size)
3449             return 0;
3450         if (type == TLSEXT_TYPE_session_ticket) {
3451             int r;
3452             if (size == 0) {
3453                 /*
3454                  * The client will accept a ticket but doesn't currently have
3455                  * one.
3456                  */
3457                 s->tlsext_ticket_expected = 1;
3458                 return 1;
3459             }
3460             if (s->tls_session_secret_cb) {
3461                 /*
3462                  * Indicate that the ticket couldn't be decrypted rather than
3463                  * generating the session from ticket now, trigger
3464                  * abbreviated handshake based on external mechanism to
3465                  * calculate the master secret later.
3466                  */
3467                 return 2;
3468             }
3469             r = tls_decrypt_ticket(s, p, size, session_id, len, ret);
3470             switch (r) {
3471             case 2:            /* ticket couldn't be decrypted */
3472                 s->tlsext_ticket_expected = 1;
3473                 return 2;
3474             case 3:            /* ticket was decrypted */
3475                 return r;
3476             case 4:            /* ticket decrypted but need to renew */
3477                 s->tlsext_ticket_expected = 1;
3478                 return 3;
3479             default:           /* fatal error */
3480                 return -1;
3481             }
3482         }
3483         p += size;
3484     }
3485     return 0;
3486 }
3487
3488 /*-
3489  * tls_decrypt_ticket attempts to decrypt a session ticket.
3490  *
3491  *   etick: points to the body of the session ticket extension.
3492  *   eticklen: the length of the session tickets extenion.
3493  *   sess_id: points at the session ID.
3494  *   sesslen: the length of the session ID.
3495  *   psess: (output) on return, if a ticket was decrypted, then this is set to
3496  *       point to the resulting session.
3497  *
3498  * Returns:
3499  *   -1: fatal error, either from parsing or decrypting the ticket.
3500  *    2: the ticket couldn't be decrypted.
3501  *    3: a ticket was successfully decrypted and *psess was set.
3502  *    4: same as 3, but the ticket needs to be renewed.
3503  */
3504 static int tls_decrypt_ticket(SSL *s, const unsigned char *etick,
3505                               int eticklen, const unsigned char *sess_id,
3506                               int sesslen, SSL_SESSION **psess)
3507 {
3508     SSL_SESSION *sess;
3509     unsigned char *sdec;
3510     const unsigned char *p;
3511     int slen, mlen, renew_ticket = 0;
3512     unsigned char tick_hmac[EVP_MAX_MD_SIZE];
3513     HMAC_CTX hctx;
3514     EVP_CIPHER_CTX ctx;
3515     SSL_CTX *tctx = s->initial_ctx;
3516
3517     /* Need at least keyname + iv */
3518     if (eticklen < 16 + EVP_MAX_IV_LENGTH)
3519         return 2;
3520
3521     /* Initialize session ticket encryption and HMAC contexts */
3522     HMAC_CTX_init(&hctx);
3523     EVP_CIPHER_CTX_init(&ctx);
3524     if (tctx->tlsext_ticket_key_cb) {
3525         unsigned char *nctick = (unsigned char *)etick;
3526         int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
3527                                             &ctx, &hctx, 0);
3528         if (rv < 0)
3529             goto err;
3530         if (rv == 0) {
3531             HMAC_CTX_cleanup(&hctx);
3532             EVP_CIPHER_CTX_cleanup(&ctx);
3533             return 2;
3534         }
3535         if (rv == 2)
3536             renew_ticket = 1;
3537     } else {
3538         /* Check key name matches */
3539         if (memcmp(etick, tctx->tlsext_tick_key_name, 16))
3540             return 2;
3541         if (HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3542                          tlsext_tick_md(), NULL) <= 0
3543                 || EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3544                                       tctx->tlsext_tick_aes_key,
3545                                       etick + 16) <= 0) {
3546             goto err;
3547        }
3548     }
3549     /*
3550      * Attempt to process session ticket, first conduct sanity and integrity
3551      * checks on ticket.
3552      */
3553     mlen = HMAC_size(&hctx);
3554     if (mlen < 0) {
3555         goto err;
3556     }
3557     /* Sanity check ticket length: must exceed keyname + IV + HMAC */
3558     if (eticklen <= 16 + EVP_CIPHER_CTX_iv_length(&ctx) + mlen) {
3559         HMAC_CTX_cleanup(&hctx);
3560         EVP_CIPHER_CTX_cleanup(&ctx);
3561         return 2;
3562     }
3563
3564     eticklen -= mlen;
3565     /* Check HMAC of encrypted ticket */
3566     if (HMAC_Update(&hctx, etick, eticklen) <= 0
3567             || HMAC_Final(&hctx, tick_hmac, NULL) <= 0) {
3568         goto err;
3569     }
3570     HMAC_CTX_cleanup(&hctx);
3571     if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen)) {
3572         EVP_CIPHER_CTX_cleanup(&ctx);
3573         return 2;
3574     }
3575     /* Attempt to decrypt session data */
3576     /* Move p after IV to start of encrypted ticket, update length */
3577     p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx);
3578     eticklen -= 16 + EVP_CIPHER_CTX_iv_length(&ctx);
3579     sdec = OPENSSL_malloc(eticklen);
3580     if (sdec == NULL
3581             || EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen) <= 0) {
3582         EVP_CIPHER_CTX_cleanup(&ctx);
3583         OPENSSL_free(sdec);
3584         return -1;
3585     }
3586     if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0) {
3587         EVP_CIPHER_CTX_cleanup(&ctx);
3588         OPENSSL_free(sdec);
3589         return 2;
3590     }
3591     slen += mlen;
3592     EVP_CIPHER_CTX_cleanup(&ctx);
3593     p = sdec;
3594
3595     sess = d2i_SSL_SESSION(NULL, &p, slen);
3596     slen -= p - sdec;
3597     OPENSSL_free(sdec);
3598     if (sess) {
3599         /* Some additional consistency checks */
3600         if (slen != 0 || sess->session_id_length != 0) {
3601             SSL_SESSION_free(sess);
3602             return 2;
3603         }
3604         /*
3605          * The session ID, if non-empty, is used by some clients to detect
3606          * that the ticket has been accepted. So we copy it to the session
3607          * structure. If it is empty set length to zero as required by
3608          * standard.
3609          */
3610         if (sesslen)
3611             memcpy(sess->session_id, sess_id, sesslen);
3612         sess->session_id_length = sesslen;
3613         *psess = sess;
3614         if (renew_ticket)
3615             return 4;
3616         else
3617             return 3;
3618     }
3619     ERR_clear_error();
3620     /*
3621      * For session parse failure, indicate that we need to send a new ticket.
3622      */
3623     return 2;
3624 err:
3625     EVP_CIPHER_CTX_cleanup(&ctx);
3626     HMAC_CTX_cleanup(&hctx);
3627     return -1;
3628 }
3629
3630 /* Tables to translate from NIDs to TLS v1.2 ids */
3631
3632 typedef struct {
3633     int nid;
3634     int id;
3635 } tls12_lookup;
3636
3637 static tls12_lookup tls12_md[] = {
3638     {NID_md5, TLSEXT_hash_md5},
3639     {NID_sha1, TLSEXT_hash_sha1},
3640     {NID_sha224, TLSEXT_hash_sha224},
3641     {NID_sha256, TLSEXT_hash_sha256},
3642     {NID_sha384, TLSEXT_hash_sha384},
3643     {NID_sha512, TLSEXT_hash_sha512}
3644 };
3645
3646 static tls12_lookup tls12_sig[] = {
3647     {EVP_PKEY_RSA, TLSEXT_signature_rsa},
3648     {EVP_PKEY_DSA, TLSEXT_signature_dsa},
3649     {EVP_PKEY_EC, TLSEXT_signature_ecdsa}
3650 };
3651
3652 static int tls12_find_id(int nid, tls12_lookup *table, size_t tlen)
3653 {
3654     size_t i;
3655     for (i = 0; i < tlen; i++) {
3656         if (table[i].nid == nid)
3657             return table[i].id;
3658     }
3659     return -1;
3660 }
3661
3662 static int tls12_find_nid(int id, tls12_lookup *table, size_t tlen)
3663 {
3664     size_t i;
3665     for (i = 0; i < tlen; i++) {
3666         if ((table[i].id) == id)
3667             return table[i].nid;
3668     }
3669     return NID_undef;
3670 }
3671
3672 int tls12_get_sigandhash(unsigned char *p, const EVP_PKEY *pk,
3673                          const EVP_MD *md)
3674 {
3675     int sig_id, md_id;
3676     if (!md)
3677         return 0;
3678     md_id = tls12_find_id(EVP_MD_type(md), tls12_md,
3679                           sizeof(tls12_md) / sizeof(tls12_lookup));
3680     if (md_id == -1)
3681         return 0;
3682     sig_id = tls12_get_sigid(pk);
3683     if (sig_id == -1)
3684         return 0;
3685     p[0] = (unsigned char)md_id;
3686     p[1] = (unsigned char)sig_id;
3687     return 1;
3688 }
3689
3690 int tls12_get_sigid(const EVP_PKEY *pk)
3691 {
3692     return tls12_find_id(pk->type, tls12_sig,
3693                          sizeof(tls12_sig) / sizeof(tls12_lookup));
3694 }
3695
3696 const EVP_MD *tls12_get_hash(unsigned char hash_alg)
3697 {
3698     switch (hash_alg) {
3699 # ifndef OPENSSL_NO_MD5
3700     case TLSEXT_hash_md5:
3701 #  ifdef OPENSSL_FIPS
3702         if (FIPS_mode())
3703             return NULL;
3704 #  endif
3705         return EVP_md5();
3706 # endif
3707 # ifndef OPENSSL_NO_SHA
3708     case TLSEXT_hash_sha1:
3709         return EVP_sha1();
3710 # endif
3711 # ifndef OPENSSL_NO_SHA256
3712     case TLSEXT_hash_sha224:
3713         return EVP_sha224();
3714
3715     case TLSEXT_hash_sha256:
3716         return EVP_sha256();
3717 # endif
3718 # ifndef OPENSSL_NO_SHA512
3719     case TLSEXT_hash_sha384:
3720         return EVP_sha384();
3721
3722     case TLSEXT_hash_sha512:
3723         return EVP_sha512();
3724 # endif
3725     default:
3726         return NULL;
3727
3728     }
3729 }
3730
3731 static int tls12_get_pkey_idx(unsigned char sig_alg)
3732 {
3733     switch (sig_alg) {
3734 # ifndef OPENSSL_NO_RSA
3735     case TLSEXT_signature_rsa:
3736         return SSL_PKEY_RSA_SIGN;
3737 # endif
3738 # ifndef OPENSSL_NO_DSA
3739     case TLSEXT_signature_dsa:
3740         return SSL_PKEY_DSA_SIGN;
3741 # endif
3742 # ifndef OPENSSL_NO_ECDSA
3743     case TLSEXT_signature_ecdsa:
3744         return SSL_PKEY_ECC;
3745 # endif
3746     }
3747     return -1;
3748 }
3749
3750 /* Convert TLS 1.2 signature algorithm extension values into NIDs */
3751 static void tls1_lookup_sigalg(int *phash_nid, int *psign_nid,
3752                                int *psignhash_nid, const unsigned char *data)
3753 {
3754     int sign_nid = NID_undef, hash_nid = NID_undef;
3755     if (!phash_nid && !psign_nid && !psignhash_nid)
3756         return;
3757     if (phash_nid || psignhash_nid) {
3758         hash_nid = tls12_find_nid(data[0], tls12_md,
3759                                   sizeof(tls12_md) / sizeof(tls12_lookup));
3760         if (phash_nid)
3761             *phash_nid = hash_nid;
3762     }
3763     if (psign_nid || psignhash_nid) {
3764         sign_nid = tls12_find_nid(data[1], tls12_sig,
3765                                   sizeof(tls12_sig) / sizeof(tls12_lookup));
3766         if (psign_nid)
3767             *psign_nid = sign_nid;
3768     }
3769     if (psignhash_nid) {
3770         if (sign_nid == NID_undef || hash_nid == NID_undef
3771                 || OBJ_find_sigid_by_algs(psignhash_nid, hash_nid,
3772                                           sign_nid) <= 0)
3773             *psignhash_nid = NID_undef;
3774     }
3775 }
3776
3777 /* Given preference and allowed sigalgs set shared sigalgs */
3778 static int tls12_do_shared_sigalgs(TLS_SIGALGS *shsig,
3779                                    const unsigned char *pref, size_t preflen,
3780                                    const unsigned char *allow,
3781                                    size_t allowlen)
3782 {
3783     const unsigned char *ptmp, *atmp;
3784     size_t i, j, nmatch = 0;
3785     for (i = 0, ptmp = pref; i < preflen; i += 2, ptmp += 2) {
3786         /* Skip disabled hashes or signature algorithms */
3787         if (tls12_get_hash(ptmp[0]) == NULL)
3788             continue;
3789         if (tls12_get_pkey_idx(ptmp[1]) == -1)
3790             continue;
3791         for (j = 0, atmp = allow; j < allowlen; j += 2, atmp += 2) {
3792             if (ptmp[0] == atmp[0] && ptmp[1] == atmp[1]) {
3793                 nmatch++;
3794                 if (shsig) {
3795                     shsig->rhash = ptmp[0];
3796                     shsig->rsign = ptmp[1];
3797                     tls1_lookup_sigalg(&shsig->hash_nid,
3798                                        &shsig->sign_nid,
3799                                        &shsig->signandhash_nid, ptmp);
3800                     shsig++;
3801                 }
3802                 break;
3803             }
3804         }
3805     }
3806     return nmatch;
3807 }
3808
3809 /* Set shared signature algorithms for SSL structures */
3810 static int tls1_set_shared_sigalgs(SSL *s)
3811 {
3812     const unsigned char *pref, *allow, *conf;
3813     size_t preflen, allowlen, conflen;
3814     size_t nmatch;
3815     TLS_SIGALGS *salgs = NULL;
3816     CERT *c = s->cert;
3817     unsigned int is_suiteb = tls1_suiteb(s);
3818     if (c->shared_sigalgs) {
3819         OPENSSL_free(c->shared_sigalgs);
3820         c->shared_sigalgs = NULL;
3821         c->shared_sigalgslen = 0;
3822     }
3823     /* If client use client signature algorithms if not NULL */
3824     if (!s->server && c->client_sigalgs && !is_suiteb) {
3825         conf = c->client_sigalgs;
3826         conflen = c->client_sigalgslen;
3827     } else if (c->conf_sigalgs && !is_suiteb) {
3828         conf = c->conf_sigalgs;
3829         conflen = c->conf_sigalgslen;
3830     } else
3831         conflen = tls12_get_psigalgs(s, 0, &conf);
3832     if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE || is_suiteb) {
3833         pref = conf;
3834         preflen = conflen;
3835         allow = c->peer_sigalgs;
3836         allowlen = c->peer_sigalgslen;
3837     } else {
3838         allow = conf;
3839         allowlen = conflen;
3840         pref = c->peer_sigalgs;
3841         preflen = c->peer_sigalgslen;
3842     }
3843     nmatch = tls12_do_shared_sigalgs(NULL, pref, preflen, allow, allowlen);
3844     if (nmatch) {
3845         salgs = OPENSSL_malloc(nmatch * sizeof(TLS_SIGALGS));
3846         if (!salgs)
3847             return 0;
3848         nmatch = tls12_do_shared_sigalgs(salgs, pref, preflen, allow, allowlen);
3849     } else {
3850         salgs = NULL;
3851     }
3852     c->shared_sigalgs = salgs;
3853     c->shared_sigalgslen = nmatch;
3854     return 1;
3855 }
3856
3857 /* Set preferred digest for each key type */
3858
3859 int tls1_save_sigalgs(SSL *s, const unsigned char *data, int dsize)
3860 {
3861     CERT *c = s->cert;
3862     /* Extension ignored for inappropriate versions */
3863     if (!SSL_USE_SIGALGS(s))
3864         return 1;
3865     /* Should never happen */
3866     if (!c)
3867         return 0;
3868
3869     if (c->peer_sigalgs)
3870         OPENSSL_free(c->peer_sigalgs);
3871     c->peer_sigalgs = OPENSSL_malloc(dsize);
3872     if (!c->peer_sigalgs)
3873         return 0;
3874     c->peer_sigalgslen = dsize;
3875     memcpy(c->peer_sigalgs, data, dsize);
3876     return 1;
3877 }
3878
3879 int tls1_process_sigalgs(SSL *s)
3880 {
3881     int idx;
3882     size_t i;
3883     const EVP_MD *md;
3884     CERT *c = s->cert;
3885     TLS_SIGALGS *sigptr;
3886     if (!tls1_set_shared_sigalgs(s))
3887         return 0;
3888
3889 # ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
3890     if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL) {
3891         /*
3892          * Use first set signature preference to force message digest,
3893          * ignoring any peer preferences.
3894          */
3895         const unsigned char *sigs = NULL;
3896         if (s->server)
3897             sigs = c->conf_sigalgs;
3898         else
3899             sigs = c->client_sigalgs;
3900         if (sigs) {
3901             idx = tls12_get_pkey_idx(sigs[1]);
3902             md = tls12_get_hash(sigs[0]);
3903             c->pkeys[idx].digest = md;
3904             c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3905             if (idx == SSL_PKEY_RSA_SIGN) {
3906                 c->pkeys[SSL_PKEY_RSA_ENC].valid_flags =
3907                     CERT_PKEY_EXPLICIT_SIGN;
3908                 c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
3909             }
3910         }
3911     }
3912 # endif
3913
3914     for (i = 0, sigptr = c->shared_sigalgs;
3915          i < c->shared_sigalgslen; i++, sigptr++) {
3916         idx = tls12_get_pkey_idx(sigptr->rsign);
3917         if (idx > 0 && c->pkeys[idx].digest == NULL) {
3918             md = tls12_get_hash(sigptr->rhash);
3919             c->pkeys[idx].digest = md;
3920             c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3921             if (idx == SSL_PKEY_RSA_SIGN) {
3922                 c->pkeys[SSL_PKEY_RSA_ENC].valid_flags =
3923                     CERT_PKEY_EXPLICIT_SIGN;
3924                 c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
3925             }
3926         }
3927
3928     }
3929     /*
3930      * In strict mode leave unset digests as NULL to indicate we can't use
3931      * the certificate for signing.
3932      */
3933     if (!(s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)) {
3934         /*
3935          * Set any remaining keys to default values. NOTE: if alg is not
3936          * supported it stays as NULL.
3937          */
3938 # ifndef OPENSSL_NO_DSA
3939         if (!c->pkeys[SSL_PKEY_DSA_SIGN].digest)
3940             c->pkeys[SSL_PKEY_DSA_SIGN].digest = EVP_sha1();
3941 # endif
3942 # ifndef OPENSSL_NO_RSA
3943         if (!c->pkeys[SSL_PKEY_RSA_SIGN].digest) {
3944             c->pkeys[SSL_PKEY_RSA_SIGN].digest = EVP_sha1();
3945             c->pkeys[SSL_PKEY_RSA_ENC].digest = EVP_sha1();
3946         }
3947 # endif
3948 # ifndef OPENSSL_NO_ECDSA
3949         if (!c->pkeys[SSL_PKEY_ECC].digest)
3950             c->pkeys[SSL_PKEY_ECC].digest = EVP_sha1();
3951 # endif
3952     }
3953     return 1;
3954 }
3955
3956 int SSL_get_sigalgs(SSL *s, int idx,
3957                     int *psign, int *phash, int *psignhash,
3958                     unsigned char *rsig, unsigned char *rhash)
3959 {
3960     const unsigned char *psig = s->cert->peer_sigalgs;
3961     if (psig == NULL)
3962         return 0;
3963     if (idx >= 0) {
3964         idx <<= 1;
3965         if (idx >= (int)s->cert->peer_sigalgslen)
3966             return 0;
3967         psig += idx;
3968         if (rhash)
3969             *rhash = psig[0];
3970         if (rsig)
3971             *rsig = psig[1];
3972         tls1_lookup_sigalg(phash, psign, psignhash, psig);
3973     }
3974     return s->cert->peer_sigalgslen / 2;
3975 }
3976
3977 int SSL_get_shared_sigalgs(SSL *s, int idx,
3978                            int *psign, int *phash, int *psignhash,
3979                            unsigned char *rsig, unsigned char *rhash)
3980 {
3981     TLS_SIGALGS *shsigalgs = s->cert->shared_sigalgs;
3982     if (!shsigalgs || idx >= (int)s->cert->shared_sigalgslen)
3983         return 0;
3984     shsigalgs += idx;
3985     if (phash)
3986         *phash = shsigalgs->hash_nid;
3987     if (psign)
3988         *psign = shsigalgs->sign_nid;
3989     if (psignhash)
3990         *psignhash = shsigalgs->signandhash_nid;
3991     if (rsig)
3992         *rsig = shsigalgs->rsign;
3993     if (rhash)
3994         *rhash = shsigalgs->rhash;
3995     return s->cert->shared_sigalgslen;
3996 }
3997
3998 # ifndef OPENSSL_NO_HEARTBEATS
3999 int tls1_process_heartbeat(SSL *s)
4000 {
4001     unsigned char *p = &s->s3->rrec.data[0], *pl;
4002     unsigned short hbtype;
4003     unsigned int payload;
4004     unsigned int padding = 16;  /* Use minimum padding */
4005
4006     if (s->msg_callback)
4007         s->msg_callback(0, s->version, TLS1_RT_HEARTBEAT,
4008                         &s->s3->rrec.data[0], s->s3->rrec.length,
4009                         s, s->msg_callback_arg);
4010
4011     /* Read type and payload length first */
4012     if (1 + 2 + 16 > s->s3->rrec.length)
4013         return 0;               /* silently discard */
4014     hbtype = *p++;
4015     n2s(p, payload);
4016     if (1 + 2 + payload + 16 > s->s3->rrec.length)
4017         return 0;               /* silently discard per RFC 6520 sec. 4 */
4018     pl = p;
4019
4020     if (hbtype == TLS1_HB_REQUEST) {
4021         unsigned char *buffer, *bp;
4022         int r;
4023
4024         /*
4025          * Allocate memory for the response, size is 1 bytes message type,
4026          * plus 2 bytes payload length, plus payload, plus padding
4027          */
4028         buffer = OPENSSL_malloc(1 + 2 + payload + padding);
4029         if (buffer == NULL)
4030             return -1;
4031         bp = buffer;
4032
4033         /* Enter response type, length and copy payload */
4034         *bp++ = TLS1_HB_RESPONSE;
4035         s2n(payload, bp);
4036         memcpy(bp, pl, payload);
4037         bp += payload;
4038         /* Random padding */
4039         if (RAND_bytes(bp, padding) <= 0) {
4040             OPENSSL_free(buffer);
4041             return -1;
4042         }
4043
4044         r = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buffer,
4045                              3 + payload + padding);
4046
4047         if (r >= 0 && s->msg_callback)
4048             s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
4049                             buffer, 3 + payload + padding,
4050                             s, s->msg_callback_arg);
4051
4052         OPENSSL_free(buffer);
4053
4054         if (r < 0)
4055             return r;
4056     } else if (hbtype == TLS1_HB_RESPONSE) {
4057         unsigned int seq;
4058
4059         /*
4060          * We only send sequence numbers (2 bytes unsigned int), and 16
4061          * random bytes, so we just try to read the sequence number
4062          */
4063         n2s(pl, seq);
4064
4065         if (payload == 18 && seq == s->tlsext_hb_seq) {
4066             s->tlsext_hb_seq++;
4067             s->tlsext_hb_pending = 0;
4068         }
4069     }
4070
4071     return 0;
4072 }
4073
4074 int tls1_heartbeat(SSL *s)
4075 {
4076     unsigned char *buf, *p;
4077     int ret = -1;
4078     unsigned int payload = 18;  /* Sequence number + random bytes */
4079     unsigned int padding = 16;  /* Use minimum padding */
4080
4081     /* Only send if peer supports and accepts HB requests... */
4082     if (!(s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) ||
4083         s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_SEND_REQUESTS) {
4084         SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT);
4085         return -1;
4086     }
4087
4088     /* ...and there is none in flight yet... */
4089     if (s->tlsext_hb_pending) {
4090         SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PENDING);
4091         return -1;
4092     }
4093
4094     /* ...and no handshake in progress. */
4095     if (SSL_in_init(s) || s->in_handshake) {
4096         SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_UNEXPECTED_MESSAGE);
4097         return -1;
4098     }
4099
4100     /*
4101      * Check if padding is too long, payload and padding must not exceed 2^14
4102      * - 3 = 16381 bytes in total.
4103      */
4104     OPENSSL_assert(payload + padding <= 16381);
4105
4106     /*-
4107      * Create HeartBeat message, we just use a sequence number
4108      * as payload to distuingish different messages and add
4109      * some random stuff.
4110      *  - Message Type, 1 byte
4111      *  - Payload Length, 2 bytes (unsigned int)
4112      *  - Payload, the sequence number (2 bytes uint)
4113      *  - Payload, random bytes (16 bytes uint)
4114      *  - Padding
4115      */
4116     buf = OPENSSL_malloc(1 + 2 + payload + padding);
4117     if (buf == NULL)
4118         return -1;
4119     p = buf;
4120     /* Message Type */
4121     *p++ = TLS1_HB_REQUEST;
4122     /* Payload length (18 bytes here) */
4123     s2n(payload, p);
4124     /* Sequence number */
4125     s2n(s->tlsext_hb_seq, p);
4126     /* 16 random bytes */
4127     if (RAND_bytes(p, 16) <= 0) {
4128         SSLerr(SSL_F_TLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
4129         goto err;
4130     }
4131     p += 16;
4132     /* Random padding */
4133     if (RAND_bytes(p, padding) <= 0) {
4134         SSLerr(SSL_F_TLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
4135         goto err;
4136     }
4137
4138     ret = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buf, 3 + payload + padding);
4139     if (ret >= 0) {
4140         if (s->msg_callback)
4141             s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
4142                             buf, 3 + payload + padding,
4143                             s, s->msg_callback_arg);
4144
4145         s->tlsext_hb_pending = 1;
4146     }
4147
4148 err:
4149     OPENSSL_free(buf);
4150
4151     return ret;
4152 }
4153 # endif
4154
4155 # define MAX_SIGALGLEN   (TLSEXT_hash_num * TLSEXT_signature_num * 2)
4156
4157 typedef struct {
4158     size_t sigalgcnt;
4159     int sigalgs[MAX_SIGALGLEN];
4160 } sig_cb_st;
4161
4162 static int sig_cb(const char *elem, int len, void *arg)
4163 {
4164     sig_cb_st *sarg = arg;
4165     size_t i;
4166     char etmp[20], *p;
4167     int sig_alg, hash_alg;
4168     if (elem == NULL)
4169         return 0;
4170     if (sarg->sigalgcnt == MAX_SIGALGLEN)
4171         return 0;
4172     if (len > (int)(sizeof(etmp) - 1))
4173         return 0;
4174     memcpy(etmp, elem, len);
4175     etmp[len] = 0;
4176     p = strchr(etmp, '+');
4177     if (!p)
4178         return 0;
4179     *p = 0;
4180     p++;
4181     if (!*p)
4182         return 0;
4183
4184     if (!strcmp(etmp, "RSA"))
4185         sig_alg = EVP_PKEY_RSA;
4186     else if (!strcmp(etmp, "DSA"))
4187         sig_alg = EVP_PKEY_DSA;
4188     else if (!strcmp(etmp, "ECDSA"))
4189         sig_alg = EVP_PKEY_EC;
4190     else
4191         return 0;
4192
4193     hash_alg = OBJ_sn2nid(p);
4194     if (hash_alg == NID_undef)
4195         hash_alg = OBJ_ln2nid(p);
4196     if (hash_alg == NID_undef)
4197         return 0;
4198
4199     for (i = 0; i < sarg->sigalgcnt; i += 2) {
4200         if (sarg->sigalgs[i] == sig_alg && sarg->sigalgs[i + 1] == hash_alg)
4201             return 0;
4202     }
4203     sarg->sigalgs[sarg->sigalgcnt++] = hash_alg;
4204     sarg->sigalgs[sarg->sigalgcnt++] = sig_alg;
4205     return 1;
4206 }
4207
4208 /*
4209  * Set suppored signature algorithms based on a colon separated list of the
4210  * form sig+hash e.g. RSA+SHA512:DSA+SHA512
4211  */
4212 int tls1_set_sigalgs_list(CERT *c, const char *str, int client)
4213 {
4214     sig_cb_st sig;
4215     sig.sigalgcnt = 0;
4216     if (!CONF_parse_list(str, ':', 1, sig_cb, &sig))
4217         return 0;
4218     if (c == NULL)
4219         return 1;
4220     return tls1_set_sigalgs(c, sig.sigalgs, sig.sigalgcnt, client);
4221 }
4222
4223 int tls1_set_sigalgs(CERT *c, const int *psig_nids, size_t salglen,
4224                      int client)
4225 {
4226     unsigned char *sigalgs, *sptr;
4227     int rhash, rsign;
4228     size_t i;
4229     if (salglen & 1)
4230         return 0;
4231     sigalgs = OPENSSL_malloc(salglen);
4232     if (sigalgs == NULL)
4233         return 0;
4234     for (i = 0, sptr = sigalgs; i < salglen; i += 2) {
4235         rhash = tls12_find_id(*psig_nids++, tls12_md,
4236                               sizeof(tls12_md) / sizeof(tls12_lookup));
4237         rsign = tls12_find_id(*psig_nids++, tls12_sig,
4238                               sizeof(tls12_sig) / sizeof(tls12_lookup));
4239
4240         if (rhash == -1 || rsign == -1)
4241             goto err;
4242         *sptr++ = rhash;
4243         *sptr++ = rsign;
4244     }
4245
4246     if (client) {
4247         if (c->client_sigalgs)
4248             OPENSSL_free(c->client_sigalgs);
4249         c->client_sigalgs = sigalgs;
4250         c->client_sigalgslen = salglen;
4251     } else {
4252         if (c->conf_sigalgs)
4253             OPENSSL_free(c->conf_sigalgs);
4254         c->conf_sigalgs = sigalgs;
4255         c->conf_sigalgslen = salglen;
4256     }
4257
4258     return 1;
4259
4260  err:
4261     OPENSSL_free(sigalgs);
4262     return 0;
4263 }
4264
4265 static int tls1_check_sig_alg(CERT *c, X509 *x, int default_nid)
4266 {
4267     int sig_nid;
4268     size_t i;
4269     if (default_nid == -1)
4270         return 1;
4271     sig_nid = X509_get_signature_nid(x);
4272     if (default_nid)
4273         return sig_nid == default_nid ? 1 : 0;
4274     for (i = 0; i < c->shared_sigalgslen; i++)
4275         if (sig_nid == c->shared_sigalgs[i].signandhash_nid)
4276             return 1;
4277     return 0;
4278 }
4279
4280 /* Check to see if a certificate issuer name matches list of CA names */
4281 static int ssl_check_ca_name(STACK_OF(X509_NAME) *names, X509 *x)
4282 {
4283     X509_NAME *nm;
4284     int i;
4285     nm = X509_get_issuer_name(x);
4286     for (i = 0; i < sk_X509_NAME_num(names); i++) {
4287         if (!X509_NAME_cmp(nm, sk_X509_NAME_value(names, i)))
4288             return 1;
4289     }
4290     return 0;
4291 }
4292
4293 /*
4294  * Check certificate chain is consistent with TLS extensions and is usable by
4295  * server. This servers two purposes: it allows users to check chains before
4296  * passing them to the server and it allows the server to check chains before
4297  * attempting to use them.
4298  */
4299
4300 /* Flags which need to be set for a certificate when stict mode not set */
4301
4302 # define CERT_PKEY_VALID_FLAGS \
4303         (CERT_PKEY_EE_SIGNATURE|CERT_PKEY_EE_PARAM)
4304 /* Strict mode flags */
4305 # define CERT_PKEY_STRICT_FLAGS \
4306          (CERT_PKEY_VALID_FLAGS|CERT_PKEY_CA_SIGNATURE|CERT_PKEY_CA_PARAM \
4307          | CERT_PKEY_ISSUER_NAME|CERT_PKEY_CERT_TYPE)
4308
4309 int tls1_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain,
4310                      int idx)
4311 {
4312     int i;
4313     int rv = 0;
4314     int check_flags = 0, strict_mode;
4315     CERT_PKEY *cpk = NULL;
4316     CERT *c = s->cert;
4317     unsigned int suiteb_flags = tls1_suiteb(s);
4318     /* idx == -1 means checking server chains */
4319     if (idx != -1) {
4320         /* idx == -2 means checking client certificate chains */
4321         if (idx == -2) {
4322             cpk = c->key;
4323             idx = cpk - c->pkeys;
4324         } else
4325             cpk = c->pkeys + idx;
4326         x = cpk->x509;
4327         pk = cpk->privatekey;
4328         chain = cpk->chain;
4329         strict_mode = c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT;
4330         /* If no cert or key, forget it */
4331         if (!x || !pk)
4332             goto end;
4333 # ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
4334         /* Allow any certificate to pass test */
4335         if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL) {
4336             rv = CERT_PKEY_STRICT_FLAGS | CERT_PKEY_EXPLICIT_SIGN |
4337                 CERT_PKEY_VALID | CERT_PKEY_SIGN;
4338             cpk->valid_flags = rv;
4339             return rv;
4340         }
4341 # endif
4342     } else {
4343         if (!x || !pk)
4344             return 0;
4345         idx = ssl_cert_type(x, pk);
4346         if (idx == -1)
4347             return 0;
4348         cpk = c->pkeys + idx;
4349         if (c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)
4350             check_flags = CERT_PKEY_STRICT_FLAGS;
4351         else
4352             check_flags = CERT_PKEY_VALID_FLAGS;
4353         strict_mode = 1;
4354     }
4355
4356     if (suiteb_flags) {
4357         int ok;
4358         if (check_flags)
4359             check_flags |= CERT_PKEY_SUITEB;
4360         ok = X509_chain_check_suiteb(NULL, x, chain, suiteb_flags);
4361         if (ok == X509_V_OK)
4362             rv |= CERT_PKEY_SUITEB;
4363         else if (!check_flags)
4364             goto end;
4365     }
4366
4367     /*
4368      * Check all signature algorithms are consistent with signature
4369      * algorithms extension if TLS 1.2 or later and strict mode.
4370      */
4371     if (TLS1_get_version(s) >= TLS1_2_VERSION && strict_mode) {
4372         int default_nid;
4373         unsigned char rsign = 0;
4374         if (c->peer_sigalgs)
4375             default_nid = 0;
4376         /* If no sigalgs extension use defaults from RFC5246 */
4377         else {
4378             switch (idx) {
4379             case SSL_PKEY_RSA_ENC:
4380             case SSL_PKEY_RSA_SIGN:
4381             case SSL_PKEY_DH_RSA:
4382                 rsign = TLSEXT_signature_rsa;
4383                 default_nid = NID_sha1WithRSAEncryption;
4384                 break;
4385
4386             case SSL_PKEY_DSA_SIGN:
4387             case SSL_PKEY_DH_DSA:
4388                 rsign = TLSEXT_signature_dsa;
4389                 default_nid = NID_dsaWithSHA1;
4390                 break;
4391
4392             case SSL_PKEY_ECC:
4393                 rsign = TLSEXT_signature_ecdsa;
4394                 default_nid = NID_ecdsa_with_SHA1;
4395                 break;
4396
4397             default:
4398                 default_nid = -1;
4399                 break;
4400             }
4401         }
4402         /*
4403          * If peer sent no signature algorithms extension and we have set
4404          * preferred signature algorithms check we support sha1.
4405          */
4406         if (default_nid > 0 && c->conf_sigalgs) {
4407             size_t j;
4408             const unsigned char *p = c->conf_sigalgs;
4409             for (j = 0; j < c->conf_sigalgslen; j += 2, p += 2) {
4410                 if (p[0] == TLSEXT_hash_sha1 && p[1] == rsign)
4411                     break;
4412             }
4413             if (j == c->conf_sigalgslen) {
4414                 if (check_flags)
4415                     goto skip_sigs;
4416                 else
4417                     goto end;
4418             }
4419         }
4420         /* Check signature algorithm of each cert in chain */
4421         if (!tls1_check_sig_alg(c, x, default_nid)) {
4422             if (!check_flags)
4423                 goto end;
4424         } else
4425             rv |= CERT_PKEY_EE_SIGNATURE;
4426         rv |= CERT_PKEY_CA_SIGNATURE;
4427         for (i = 0; i < sk_X509_num(chain); i++) {
4428             if (!tls1_check_sig_alg(c, sk_X509_value(chain, i), default_nid)) {
4429                 if (check_flags) {
4430                     rv &= ~CERT_PKEY_CA_SIGNATURE;
4431                     break;
4432                 } else
4433                     goto end;
4434             }
4435         }
4436     }
4437     /* Else not TLS 1.2, so mark EE and CA signing algorithms OK */
4438     else if (check_flags)
4439         rv |= CERT_PKEY_EE_SIGNATURE | CERT_PKEY_CA_SIGNATURE;
4440  skip_sigs:
4441     /* Check cert parameters are consistent */
4442     if (tls1_check_cert_param(s, x, check_flags ? 1 : 2))
4443         rv |= CERT_PKEY_EE_PARAM;
4444     else if (!check_flags)
4445         goto end;
4446     if (!s->server)
4447         rv |= CERT_PKEY_CA_PARAM;
4448     /* In strict mode check rest of chain too */
4449     else if (strict_mode) {
4450         rv |= CERT_PKEY_CA_PARAM;
4451         for (i = 0; i < sk_X509_num(chain); i++) {
4452             X509 *ca = sk_X509_value(chain, i);
4453             if (!tls1_check_cert_param(s, ca, 0)) {
4454                 if (check_flags) {
4455                     rv &= ~CERT_PKEY_CA_PARAM;
4456                     break;
4457                 } else
4458                     goto end;
4459             }
4460         }
4461     }
4462     if (!s->server && strict_mode) {
4463         STACK_OF(X509_NAME) *ca_dn;
4464         int check_type = 0;
4465         switch (pk->type) {
4466         case EVP_PKEY_RSA:
4467             check_type = TLS_CT_RSA_SIGN;
4468             break;
4469         case EVP_PKEY_DSA:
4470             check_type = TLS_CT_DSS_SIGN;
4471             break;
4472         case EVP_PKEY_EC:
4473             check_type = TLS_CT_ECDSA_SIGN;
4474             break;
4475         case EVP_PKEY_DH:
4476         case EVP_PKEY_DHX:
4477             {
4478                 int cert_type = X509_certificate_type(x, pk);
4479                 if (cert_type & EVP_PKS_RSA)
4480                     check_type = TLS_CT_RSA_FIXED_DH;
4481                 if (cert_type & EVP_PKS_DSA)
4482                     check_type = TLS_CT_DSS_FIXED_DH;
4483             }
4484         }
4485         if (check_type) {
4486             const unsigned char *ctypes;
4487             int ctypelen;
4488             if (c->ctypes) {
4489                 ctypes = c->ctypes;
4490                 ctypelen = (int)c->ctype_num;
4491             } else {
4492                 ctypes = (unsigned char *)s->s3->tmp.ctype;
4493                 ctypelen = s->s3->tmp.ctype_num;
4494             }
4495             for (i = 0; i < ctypelen; i++) {
4496                 if (ctypes[i] == check_type) {
4497                     rv |= CERT_PKEY_CERT_TYPE;
4498                     break;
4499                 }
4500             }
4501             if (!(rv & CERT_PKEY_CERT_TYPE) && !check_flags)
4502                 goto end;
4503         } else
4504             rv |= CERT_PKEY_CERT_TYPE;
4505
4506         ca_dn = s->s3->tmp.ca_names;
4507
4508         if (!sk_X509_NAME_num(ca_dn))
4509             rv |= CERT_PKEY_ISSUER_NAME;
4510
4511         if (!(rv & CERT_PKEY_ISSUER_NAME)) {
4512             if (ssl_check_ca_name(ca_dn, x))
4513                 rv |= CERT_PKEY_ISSUER_NAME;
4514         }
4515         if (!(rv & CERT_PKEY_ISSUER_NAME)) {
4516             for (i = 0; i < sk_X509_num(chain); i++) {
4517                 X509 *xtmp = sk_X509_value(chain, i);
4518                 if (ssl_check_ca_name(ca_dn, xtmp)) {
4519                     rv |= CERT_PKEY_ISSUER_NAME;
4520                     break;
4521                 }
4522             }
4523         }
4524         if (!check_flags && !(rv & CERT_PKEY_ISSUER_NAME))
4525             goto end;
4526     } else
4527         rv |= CERT_PKEY_ISSUER_NAME | CERT_PKEY_CERT_TYPE;
4528
4529     if (!check_flags || (rv & check_flags) == check_flags)
4530         rv |= CERT_PKEY_VALID;
4531
4532  end:
4533
4534     if (TLS1_get_version(s) >= TLS1_2_VERSION) {
4535         if (cpk->valid_flags & CERT_PKEY_EXPLICIT_SIGN)
4536             rv |= CERT_PKEY_EXPLICIT_SIGN | CERT_PKEY_SIGN;
4537         else if (cpk->digest)
4538             rv |= CERT_PKEY_SIGN;
4539     } else
4540         rv |= CERT_PKEY_SIGN | CERT_PKEY_EXPLICIT_SIGN;
4541
4542     /*
4543      * When checking a CERT_PKEY structure all flags are irrelevant if the
4544      * chain is invalid.
4545      */
4546     if (!check_flags) {
4547         if (rv & CERT_PKEY_VALID)
4548             cpk->valid_flags = rv;
4549         else {
4550             /* Preserve explicit sign flag, clear rest */
4551             cpk->valid_flags &= CERT_PKEY_EXPLICIT_SIGN;
4552             return 0;
4553         }
4554     }
4555     return rv;
4556 }
4557
4558 /* Set validity of certificates in an SSL structure */
4559 void tls1_set_cert_validity(SSL *s)
4560 {
4561     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_ENC);
4562     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_SIGN);
4563     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DSA_SIGN);
4564     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DH_RSA);
4565     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DH_DSA);
4566     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_ECC);
4567 }
4568
4569 /* User level utiity function to check a chain is suitable */
4570 int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain)
4571 {
4572     return tls1_check_chain(s, x, pk, chain, -1);
4573 }
4574
4575 #endif