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