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