Parse custom extensions after SNI.
[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         size_t i;
1912
1913         s->servername_done = 0;
1914         s->tlsext_status_type = -1;
1915 #ifndef OPENSSL_NO_NEXTPROTONEG
1916         s->s3->next_proto_neg_seen = 0;
1917 #endif
1918
1919         if (s->s3->alpn_selected)
1920                 {
1921                 OPENSSL_free(s->s3->alpn_selected);
1922                 s->s3->alpn_selected = NULL;
1923                 }
1924
1925 #ifndef OPENSSL_NO_HEARTBEATS
1926         s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
1927                                SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
1928 #endif
1929
1930 #ifndef OPENSSL_NO_EC
1931         if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
1932                 ssl_check_for_safari(s, data, d, n);
1933 #endif /* !OPENSSL_NO_EC */
1934
1935         /* Clear any signature algorithms extension received */
1936         if (s->cert->peer_sigalgs)
1937                 {
1938                 OPENSSL_free(s->cert->peer_sigalgs);
1939                 s->cert->peer_sigalgs = NULL;
1940                 }
1941         /* Clear any shared sigtnature algorithms */
1942         if (s->cert->shared_sigalgs)
1943                 {
1944                 OPENSSL_free(s->cert->shared_sigalgs);
1945                 s->cert->shared_sigalgs = NULL;
1946                 }
1947         /* Clear certificate digests and validity flags */
1948         for (i = 0; i < SSL_PKEY_NUM; i++)
1949                 {
1950                 s->cert->pkeys[i].digest = NULL;
1951                 s->cert->pkeys[i].valid_flags = 0;
1952                 }
1953
1954         if (data >= (d+n-2))
1955                 goto ri_check;
1956         n2s(data,len);
1957
1958         if (data > (d+n-len)) 
1959                 goto ri_check;
1960
1961         while (data <= (d+n-4))
1962                 {
1963                 n2s(data,type);
1964                 n2s(data,size);
1965
1966                 if (data+size > (d+n))
1967                         goto ri_check;
1968 #if 0
1969                 fprintf(stderr,"Received extension type %d size %d\n",type,size);
1970 #endif
1971                 if (s->tlsext_debug_cb)
1972                         s->tlsext_debug_cb(s, 0, type, data, size,
1973                                                 s->tlsext_debug_arg);
1974 /* The servername extension is treated as follows:
1975
1976    - Only the hostname type is supported with a maximum length of 255.
1977    - The servername is rejected if too long or if it contains zeros,
1978      in which case an fatal alert is generated.
1979    - The servername field is maintained together with the session cache.
1980    - When a session is resumed, the servername call back invoked in order
1981      to allow the application to position itself to the right context. 
1982    - The servername is acknowledged if it is new for a session or when 
1983      it is identical to a previously used for the same session. 
1984      Applications can control the behaviour.  They can at any time
1985      set a 'desirable' servername for a new SSL object. This can be the
1986      case for example with HTTPS when a Host: header field is received and
1987      a renegotiation is requested. In this case, a possible servername
1988      presented in the new client hello is only acknowledged if it matches
1989      the value of the Host: field. 
1990    - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
1991      if they provide for changing an explicit servername context for the session,
1992      i.e. when the session has been established with a servername extension. 
1993    - On session reconnect, the servername extension may be absent. 
1994
1995 */      
1996
1997                 if (type == TLSEXT_TYPE_server_name)
1998                         {
1999                         unsigned char *sdata;
2000                         int servname_type;
2001                         int dsize; 
2002                 
2003                         if (size < 2) 
2004                                 {
2005                                 *al = SSL_AD_DECODE_ERROR;
2006                                 return 0;
2007                                 }
2008                         n2s(data,dsize);  
2009                         size -= 2;
2010                         if (dsize > size  ) 
2011                                 {
2012                                 *al = SSL_AD_DECODE_ERROR;
2013                                 return 0;
2014                                 } 
2015
2016                         sdata = data;
2017                         while (dsize > 3) 
2018                                 {
2019                                 servname_type = *(sdata++); 
2020                                 n2s(sdata,len);
2021                                 dsize -= 3;
2022
2023                                 if (len > dsize) 
2024                                         {
2025                                         *al = SSL_AD_DECODE_ERROR;
2026                                         return 0;
2027                                         }
2028                                 if (s->servername_done == 0)
2029                                 switch (servname_type)
2030                                         {
2031                                 case TLSEXT_NAMETYPE_host_name:
2032                                         if (!s->hit)
2033                                                 {
2034                                                 if(s->session->tlsext_hostname)
2035                                                         {
2036                                                         *al = SSL_AD_DECODE_ERROR;
2037                                                         return 0;
2038                                                         }
2039                                                 if (len > TLSEXT_MAXLEN_host_name)
2040                                                         {
2041                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
2042                                                         return 0;
2043                                                         }
2044                                                 if ((s->session->tlsext_hostname = OPENSSL_malloc(len+1)) == NULL)
2045                                                         {
2046                                                         *al = TLS1_AD_INTERNAL_ERROR;
2047                                                         return 0;
2048                                                         }
2049                                                 memcpy(s->session->tlsext_hostname, sdata, len);
2050                                                 s->session->tlsext_hostname[len]='\0';
2051                                                 if (strlen(s->session->tlsext_hostname) != len) {
2052                                                         OPENSSL_free(s->session->tlsext_hostname);
2053                                                         s->session->tlsext_hostname = NULL;
2054                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
2055                                                         return 0;
2056                                                 }
2057                                                 s->servername_done = 1; 
2058
2059                                                 }
2060                                         else 
2061                                                 s->servername_done = s->session->tlsext_hostname
2062                                                         && strlen(s->session->tlsext_hostname) == len 
2063                                                         && strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0;
2064                                         
2065                                         break;
2066
2067                                 default:
2068                                         break;
2069                                         }
2070                                  
2071                                 dsize -= len;
2072                                 }
2073                         if (dsize != 0) 
2074                                 {
2075                                 *al = SSL_AD_DECODE_ERROR;
2076                                 return 0;
2077                                 }
2078
2079                         }
2080 #ifndef OPENSSL_NO_SRP
2081                 else if (type == TLSEXT_TYPE_srp)
2082                         {
2083                         if (size <= 0 || ((len = data[0])) != (size -1))
2084                                 {
2085                                 *al = SSL_AD_DECODE_ERROR;
2086                                 return 0;
2087                                 }
2088                         if (s->srp_ctx.login != NULL)
2089                                 {
2090                                 *al = SSL_AD_DECODE_ERROR;
2091                                 return 0;
2092                                 }
2093                         if ((s->srp_ctx.login = OPENSSL_malloc(len+1)) == NULL)
2094                                 return -1;
2095                         memcpy(s->srp_ctx.login, &data[1], len);
2096                         s->srp_ctx.login[len]='\0';
2097   
2098                         if (strlen(s->srp_ctx.login) != len) 
2099                                 {
2100                                 *al = SSL_AD_DECODE_ERROR;
2101                                 return 0;
2102                                 }
2103                         }
2104 #endif
2105
2106 #ifndef OPENSSL_NO_EC
2107                 else if (type == TLSEXT_TYPE_ec_point_formats)
2108                         {
2109                         unsigned char *sdata = data;
2110                         int ecpointformatlist_length = *(sdata++);
2111
2112                         if (ecpointformatlist_length != size - 1 || 
2113                                 ecpointformatlist_length < 1)
2114                                 {
2115                                 *al = TLS1_AD_DECODE_ERROR;
2116                                 return 0;
2117                                 }
2118                         if (!s->hit)
2119                                 {
2120                                 if(s->session->tlsext_ecpointformatlist)
2121                                         {
2122                                         OPENSSL_free(s->session->tlsext_ecpointformatlist);
2123                                         s->session->tlsext_ecpointformatlist = NULL;
2124                                         }
2125                                 s->session->tlsext_ecpointformatlist_length = 0;
2126                                 if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
2127                                         {
2128                                         *al = TLS1_AD_INTERNAL_ERROR;
2129                                         return 0;
2130                                         }
2131                                 s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
2132                                 memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
2133                                 }
2134 #if 0
2135                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ", s->session->tlsext_ecpointformatlist_length);
2136                         sdata = s->session->tlsext_ecpointformatlist;
2137                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2138                                 fprintf(stderr,"%i ",*(sdata++));
2139                         fprintf(stderr,"\n");
2140 #endif
2141                         }
2142                 else if (type == TLSEXT_TYPE_elliptic_curves)
2143                         {
2144                         unsigned char *sdata = data;
2145                         int ellipticcurvelist_length = (*(sdata++) << 8);
2146                         ellipticcurvelist_length += (*(sdata++));
2147
2148                         if (ellipticcurvelist_length != size - 2 ||
2149                                 ellipticcurvelist_length < 1)
2150                                 {
2151                                 *al = TLS1_AD_DECODE_ERROR;
2152                                 return 0;
2153                                 }
2154                         if (!s->hit)
2155                                 {
2156                                 if(s->session->tlsext_ellipticcurvelist)
2157                                         {
2158                                         *al = TLS1_AD_DECODE_ERROR;
2159                                         return 0;
2160                                         }
2161                                 s->session->tlsext_ellipticcurvelist_length = 0;
2162                                 if ((s->session->tlsext_ellipticcurvelist = OPENSSL_malloc(ellipticcurvelist_length)) == NULL)
2163                                         {
2164                                         *al = TLS1_AD_INTERNAL_ERROR;
2165                                         return 0;
2166                                         }
2167                                 s->session->tlsext_ellipticcurvelist_length = ellipticcurvelist_length;
2168                                 memcpy(s->session->tlsext_ellipticcurvelist, sdata, ellipticcurvelist_length);
2169                                 }
2170 #if 0
2171                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ", s->session->tlsext_ellipticcurvelist_length);
2172                         sdata = s->session->tlsext_ellipticcurvelist;
2173                         for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++)
2174                                 fprintf(stderr,"%i ",*(sdata++));
2175                         fprintf(stderr,"\n");
2176 #endif
2177                         }
2178 #endif /* OPENSSL_NO_EC */
2179 #ifdef TLSEXT_TYPE_opaque_prf_input
2180                 else if (type == TLSEXT_TYPE_opaque_prf_input)
2181                         {
2182                         unsigned char *sdata = data;
2183
2184                         if (size < 2)
2185                                 {
2186                                 *al = SSL_AD_DECODE_ERROR;
2187                                 return 0;
2188                                 }
2189                         n2s(sdata, s->s3->client_opaque_prf_input_len);
2190                         if (s->s3->client_opaque_prf_input_len != size - 2)
2191                                 {
2192                                 *al = SSL_AD_DECODE_ERROR;
2193                                 return 0;
2194                                 }
2195
2196                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
2197                                 OPENSSL_free(s->s3->client_opaque_prf_input);
2198                         if (s->s3->client_opaque_prf_input_len == 0)
2199                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2200                         else
2201                                 s->s3->client_opaque_prf_input = BUF_memdup(sdata, s->s3->client_opaque_prf_input_len);
2202                         if (s->s3->client_opaque_prf_input == NULL)
2203                                 {
2204                                 *al = TLS1_AD_INTERNAL_ERROR;
2205                                 return 0;
2206                                 }
2207                         }
2208 #endif
2209                 else if (type == TLSEXT_TYPE_session_ticket)
2210                         {
2211                         if (s->tls_session_ticket_ext_cb &&
2212                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
2213                                 {
2214                                 *al = TLS1_AD_INTERNAL_ERROR;
2215                                 return 0;
2216                                 }
2217                         }
2218                 else if (type == TLSEXT_TYPE_renegotiate)
2219                         {
2220                         if(!ssl_parse_clienthello_renegotiate_ext(s, data, size, al))
2221                                 return 0;
2222                         renegotiate_seen = 1;
2223                         }
2224                 else if (type == TLSEXT_TYPE_signature_algorithms)
2225                         {
2226                         int dsize;
2227                         if (s->cert->peer_sigalgs || size < 2) 
2228                                 {
2229                                 *al = SSL_AD_DECODE_ERROR;
2230                                 return 0;
2231                                 }
2232                         n2s(data,dsize);
2233                         size -= 2;
2234                         if (dsize != size || dsize & 1 || !dsize) 
2235                                 {
2236                                 *al = SSL_AD_DECODE_ERROR;
2237                                 return 0;
2238                                 }
2239                         if (!tls1_process_sigalgs(s, data, dsize))
2240                                 {
2241                                 *al = SSL_AD_DECODE_ERROR;
2242                                 return 0;
2243                                 }
2244                         /* If sigalgs received and no shared algorithms fatal
2245                          * error.
2246                          */
2247                         if (s->cert->peer_sigalgs && !s->cert->shared_sigalgs)
2248                                 {
2249                                 SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
2250                                         SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
2251                                 *al = SSL_AD_ILLEGAL_PARAMETER;
2252                                 return 0;
2253                                 }
2254                         }
2255                 else if (type == TLSEXT_TYPE_status_request)
2256                         {
2257                 
2258                         if (size < 5) 
2259                                 {
2260                                 *al = SSL_AD_DECODE_ERROR;
2261                                 return 0;
2262                                 }
2263
2264                         s->tlsext_status_type = *data++;
2265                         size--;
2266                         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp)
2267                                 {
2268                                 const unsigned char *sdata;
2269                                 int dsize;
2270                                 /* Read in responder_id_list */
2271                                 n2s(data,dsize);
2272                                 size -= 2;
2273                                 if (dsize > size  ) 
2274                                         {
2275                                         *al = SSL_AD_DECODE_ERROR;
2276                                         return 0;
2277                                         }
2278                                 while (dsize > 0)
2279                                         {
2280                                         OCSP_RESPID *id;
2281                                         int idsize;
2282                                         if (dsize < 4)
2283                                                 {
2284                                                 *al = SSL_AD_DECODE_ERROR;
2285                                                 return 0;
2286                                                 }
2287                                         n2s(data, idsize);
2288                                         dsize -= 2 + idsize;
2289                                         size -= 2 + idsize;
2290                                         if (dsize < 0)
2291                                                 {
2292                                                 *al = SSL_AD_DECODE_ERROR;
2293                                                 return 0;
2294                                                 }
2295                                         sdata = data;
2296                                         data += idsize;
2297                                         id = d2i_OCSP_RESPID(NULL,
2298                                                                 &sdata, idsize);
2299                                         if (!id)
2300                                                 {
2301                                                 *al = SSL_AD_DECODE_ERROR;
2302                                                 return 0;
2303                                                 }
2304                                         if (data != sdata)
2305                                                 {
2306                                                 OCSP_RESPID_free(id);
2307                                                 *al = SSL_AD_DECODE_ERROR;
2308                                                 return 0;
2309                                                 }
2310                                         if (!s->tlsext_ocsp_ids
2311                                                 && !(s->tlsext_ocsp_ids =
2312                                                 sk_OCSP_RESPID_new_null()))
2313                                                 {
2314                                                 OCSP_RESPID_free(id);
2315                                                 *al = SSL_AD_INTERNAL_ERROR;
2316                                                 return 0;
2317                                                 }
2318                                         if (!sk_OCSP_RESPID_push(
2319                                                         s->tlsext_ocsp_ids, id))
2320                                                 {
2321                                                 OCSP_RESPID_free(id);
2322                                                 *al = SSL_AD_INTERNAL_ERROR;
2323                                                 return 0;
2324                                                 }
2325                                         }
2326
2327                                 /* Read in request_extensions */
2328                                 if (size < 2)
2329                                         {
2330                                         *al = SSL_AD_DECODE_ERROR;
2331                                         return 0;
2332                                         }
2333                                 n2s(data,dsize);
2334                                 size -= 2;
2335                                 if (dsize != size)
2336                                         {
2337                                         *al = SSL_AD_DECODE_ERROR;
2338                                         return 0;
2339                                         }
2340                                 sdata = data;
2341                                 if (dsize > 0)
2342                                         {
2343                                         if (s->tlsext_ocsp_exts)
2344                                                 {
2345                                                 sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
2346                                                                            X509_EXTENSION_free);
2347                                                 }
2348
2349                                         s->tlsext_ocsp_exts =
2350                                                 d2i_X509_EXTENSIONS(NULL,
2351                                                         &sdata, dsize);
2352                                         if (!s->tlsext_ocsp_exts
2353                                                 || (data + dsize != sdata))
2354                                                 {
2355                                                 *al = SSL_AD_DECODE_ERROR;
2356                                                 return 0;
2357                                                 }
2358                                         }
2359                                 }
2360                                 /* We don't know what to do with any other type
2361                                 * so ignore it.
2362                                 */
2363                                 else
2364                                         s->tlsext_status_type = -1;
2365                         }
2366 #ifndef OPENSSL_NO_HEARTBEATS
2367                 else if (type == TLSEXT_TYPE_heartbeat)
2368                         {
2369                         switch(data[0])
2370                                 {
2371                                 case 0x01:      /* Client allows us to send HB requests */
2372                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2373                                                         break;
2374                                 case 0x02:      /* Client doesn't accept HB requests */
2375                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2376                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2377                                                         break;
2378                                 default:        *al = SSL_AD_ILLEGAL_PARAMETER;
2379                                                         return 0;
2380                                 }
2381                         }
2382 #endif
2383 #ifndef OPENSSL_NO_NEXTPROTONEG
2384                 else if (type == TLSEXT_TYPE_next_proto_neg &&
2385                          s->s3->tmp.finish_md_len == 0 &&
2386                          s->s3->alpn_selected == NULL)
2387                         {
2388                         /* We shouldn't accept this extension on a
2389                          * renegotiation.
2390                          *
2391                          * s->new_session will be set on renegotiation, but we
2392                          * probably shouldn't rely that it couldn't be set on
2393                          * the initial renegotation too in certain cases (when
2394                          * there's some other reason to disallow resuming an
2395                          * earlier session -- the current code won't be doing
2396                          * anything like that, but this might change).
2397
2398                          * A valid sign that there's been a previous handshake
2399                          * in this connection is if s->s3->tmp.finish_md_len >
2400                          * 0.  (We are talking about a check that will happen
2401                          * in the Hello protocol round, well before a new
2402                          * Finished message could have been computed.) */
2403                         s->s3->next_proto_neg_seen = 1;
2404                         }
2405 #endif
2406
2407                 else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation &&
2408                          s->ctx->alpn_select_cb &&
2409                          s->s3->tmp.finish_md_len == 0)
2410                         {
2411                         if (tls1_alpn_handle_client_hello(s, data, size, al) != 0)
2412                                 return 0;
2413 #ifndef OPENSSL_NO_NEXTPROTONEG
2414                         /* ALPN takes precedence over NPN. */
2415                         s->s3->next_proto_neg_seen = 0;
2416 #endif
2417                         }
2418
2419                 /* session ticket processed earlier */
2420                 else if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s)
2421                                 && type == TLSEXT_TYPE_use_srtp)
2422                         {
2423                         if(ssl_parse_clienthello_use_srtp_ext(s, data, size,
2424                                                               al))
2425                                 return 0;
2426                         }
2427
2428                 data+=size;
2429                 }
2430
2431         *p = data;
2432
2433         ri_check:
2434
2435         /* Need RI if renegotiating */
2436
2437         if (!renegotiate_seen && s->renegotiate &&
2438                 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
2439                 {
2440                 *al = SSL_AD_HANDSHAKE_FAILURE;
2441                 SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
2442                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2443                 return 0;
2444                 }
2445         /* If no signature algorithms extension set default values */
2446         if (!s->cert->peer_sigalgs)
2447                 ssl_cert_set_default_md(s->cert);
2448
2449         return 1;
2450         }
2451
2452 /*
2453  * Parse any custom extensions found.  "data" is the start of the extension data
2454  * and "limit" is the end of the record. TODO: add strict syntax checking.
2455  */
2456
2457 static int ssl_scan_clienthello_custom_tlsext(SSL *s, const unsigned char *data, const unsigned char *limit, int *al) 
2458         {       
2459         unsigned short type, size, len;
2460         /* If resumed session or no custom extensions nothing to do */
2461         if (s->hit || s->cert->srv_ext.meths_count == 0)
2462                 return 1;
2463
2464         if (data >= limit - 2)
2465                 return 1;
2466         n2s(data, len);
2467
2468         if (data > limit - len) 
2469                 return 1;
2470
2471         while (data <= limit - 4)
2472                 {
2473                 n2s(data, type);
2474                 n2s(data, size);
2475
2476                 if (data+size > limit)
2477                         return 1;
2478                 if (custom_ext_parse(s, 1 /* server */, type, data, size, al) <= 0)
2479                         return 0;
2480
2481                 data+=size;
2482                 }
2483
2484         return 1;
2485         }
2486
2487 int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n) 
2488         {
2489         int al = -1;
2490         unsigned char *ptmp = *p;
2491         /*
2492          * Internally supported extensions are parsed first so SNI can be handled
2493          * before custom extensions. An application processing SNI will typically
2494          * switch the parent context using SSL_set_SSL_CTX and custom extensions
2495          * need to be handled by the new SSL_CTX structure.
2496          */
2497         if (ssl_scan_clienthello_tlsext(s, p, d, n, &al) <= 0) 
2498                 {
2499                 ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2500                 return 0;
2501                 }
2502
2503         if (ssl_check_clienthello_tlsext_early(s) <= 0) 
2504                 {
2505                 SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT,SSL_R_CLIENTHELLO_TLSEXT);
2506                 return 0;
2507                 }
2508
2509         custom_ext_init(&s->cert->srv_ext);
2510         if (ssl_scan_clienthello_custom_tlsext(s, ptmp, d + n, &al) <= 0) 
2511                 {
2512                 ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2513                 return 0;
2514                 }
2515
2516         return 1;
2517 }
2518
2519 #ifndef OPENSSL_NO_NEXTPROTONEG
2520 /* ssl_next_proto_validate validates a Next Protocol Negotiation block. No
2521  * elements of zero length are allowed and the set of elements must exactly fill
2522  * the length of the block. */
2523 static char ssl_next_proto_validate(unsigned char *d, unsigned len)
2524         {
2525         unsigned int off = 0;
2526
2527         while (off < len)
2528                 {
2529                 if (d[off] == 0)
2530                         return 0;
2531                 off += d[off];
2532                 off++;
2533                 }
2534
2535         return off == len;
2536         }
2537 #endif
2538
2539 static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
2540         {
2541         unsigned short length;
2542         unsigned short type;
2543         unsigned short size;
2544         unsigned char *data = *p;
2545         int tlsext_servername = 0;
2546         int renegotiate_seen = 0;
2547
2548 #ifndef OPENSSL_NO_NEXTPROTONEG
2549         s->s3->next_proto_neg_seen = 0;
2550 #endif
2551
2552         if (s->s3->alpn_selected)
2553                 {
2554                 OPENSSL_free(s->s3->alpn_selected);
2555                 s->s3->alpn_selected = NULL;
2556                 }
2557
2558 #ifndef OPENSSL_NO_HEARTBEATS
2559         s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
2560                                SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
2561 #endif
2562
2563         if (data >= (d+n-2))
2564                 goto ri_check;
2565
2566         n2s(data,length);
2567         if (data+length != d+n)
2568                 {
2569                 *al = SSL_AD_DECODE_ERROR;
2570                 return 0;
2571                 }
2572
2573         while(data <= (d+n-4))
2574                 {
2575                 n2s(data,type);
2576                 n2s(data,size);
2577
2578                 if (data+size > (d+n))
2579                         goto ri_check;
2580
2581                 if (s->tlsext_debug_cb)
2582                         s->tlsext_debug_cb(s, 1, type, data, size,
2583                                                 s->tlsext_debug_arg);
2584
2585                 if (type == TLSEXT_TYPE_server_name)
2586                         {
2587                         if (s->tlsext_hostname == NULL || size > 0)
2588                                 {
2589                                 *al = TLS1_AD_UNRECOGNIZED_NAME;
2590                                 return 0;
2591                                 }
2592                         tlsext_servername = 1;   
2593                         }
2594
2595 #ifndef OPENSSL_NO_EC
2596                 else if (type == TLSEXT_TYPE_ec_point_formats)
2597                         {
2598                         unsigned char *sdata = data;
2599                         int ecpointformatlist_length = *(sdata++);
2600
2601                         if (ecpointformatlist_length != size - 1)
2602                                 {
2603                                 *al = TLS1_AD_DECODE_ERROR;
2604                                 return 0;
2605                                 }
2606                         if (!s->hit)
2607                                 {
2608                                 s->session->tlsext_ecpointformatlist_length = 0;
2609                                 if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist);
2610                                 if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
2611                                         {
2612                                         *al = TLS1_AD_INTERNAL_ERROR;
2613                                         return 0;
2614                                         }
2615                                 s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
2616                                 memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
2617                                 }
2618 #if 0
2619                         fprintf(stderr,"ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist ");
2620                         sdata = s->session->tlsext_ecpointformatlist;
2621                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2622                                 fprintf(stderr,"%i ",*(sdata++));
2623                         fprintf(stderr,"\n");
2624 #endif
2625                         }
2626 #endif /* OPENSSL_NO_EC */
2627
2628                 else if (type == TLSEXT_TYPE_session_ticket)
2629                         {
2630                         if (s->tls_session_ticket_ext_cb &&
2631                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
2632                                 {
2633                                 *al = TLS1_AD_INTERNAL_ERROR;
2634                                 return 0;
2635                                 }
2636                         if ((SSL_get_options(s) & SSL_OP_NO_TICKET)
2637                                 || (size > 0))
2638                                 {
2639                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2640                                 return 0;
2641                                 }
2642                         s->tlsext_ticket_expected = 1;
2643                         }
2644 #ifdef TLSEXT_TYPE_opaque_prf_input
2645                 else if (type == TLSEXT_TYPE_opaque_prf_input)
2646                         {
2647                         unsigned char *sdata = data;
2648
2649                         if (size < 2)
2650                                 {
2651                                 *al = SSL_AD_DECODE_ERROR;
2652                                 return 0;
2653                                 }
2654                         n2s(sdata, s->s3->server_opaque_prf_input_len);
2655                         if (s->s3->server_opaque_prf_input_len != size - 2)
2656                                 {
2657                                 *al = SSL_AD_DECODE_ERROR;
2658                                 return 0;
2659                                 }
2660                         
2661                         if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
2662                                 OPENSSL_free(s->s3->server_opaque_prf_input);
2663                         if (s->s3->server_opaque_prf_input_len == 0)
2664                                 s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2665                         else
2666                                 s->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len);
2667
2668                         if (s->s3->server_opaque_prf_input == NULL)
2669                                 {
2670                                 *al = TLS1_AD_INTERNAL_ERROR;
2671                                 return 0;
2672                                 }
2673                         }
2674 #endif
2675                 else if (type == TLSEXT_TYPE_status_request)
2676                         {
2677                         /* MUST be empty and only sent if we've requested
2678                          * a status request message.
2679                          */ 
2680                         if ((s->tlsext_status_type == -1) || (size > 0))
2681                                 {
2682                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2683                                 return 0;
2684                                 }
2685                         /* Set flag to expect CertificateStatus message */
2686                         s->tlsext_status_expected = 1;
2687                         }
2688 #ifndef OPENSSL_NO_NEXTPROTONEG
2689                 else if (type == TLSEXT_TYPE_next_proto_neg &&
2690                          s->s3->tmp.finish_md_len == 0)
2691                         {
2692                         unsigned char *selected;
2693                         unsigned char selected_len;
2694
2695                         /* We must have requested it. */
2696                         if (s->ctx->next_proto_select_cb == NULL)
2697                                 {
2698                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2699                                 return 0;
2700                                 }
2701                         /* The data must be valid */
2702                         if (!ssl_next_proto_validate(data, size))
2703                                 {
2704                                 *al = TLS1_AD_DECODE_ERROR;
2705                                 return 0;
2706                                 }
2707                         if (s->ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK)
2708                                 {
2709                                 *al = TLS1_AD_INTERNAL_ERROR;
2710                                 return 0;
2711                                 }
2712                         s->next_proto_negotiated = OPENSSL_malloc(selected_len);
2713                         if (!s->next_proto_negotiated)
2714                                 {
2715                                 *al = TLS1_AD_INTERNAL_ERROR;
2716                                 return 0;
2717                                 }
2718                         memcpy(s->next_proto_negotiated, selected, selected_len);
2719                         s->next_proto_negotiated_len = selected_len;
2720                         s->s3->next_proto_neg_seen = 1;
2721                         }
2722 #endif
2723
2724                 else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation)
2725                         {
2726                         unsigned len;
2727
2728                         /* We must have requested it. */
2729                         if (s->alpn_client_proto_list == NULL)
2730                                 {
2731                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2732                                 return 0;
2733                                 }
2734                         if (size < 4)
2735                                 {
2736                                 *al = TLS1_AD_DECODE_ERROR;
2737                                 return 0;
2738                                 }
2739                         /* The extension data consists of:
2740                          *   uint16 list_length
2741                          *   uint8 proto_length;
2742                          *   uint8 proto[proto_length]; */
2743                         len = data[0];
2744                         len <<= 8;
2745                         len |= data[1];
2746                         if (len != (unsigned) size - 2)
2747                                 {
2748                                 *al = TLS1_AD_DECODE_ERROR;
2749                                 return 0;
2750                                 }
2751                         len = data[2];
2752                         if (len != (unsigned) size - 3)
2753                                 {
2754                                 *al = TLS1_AD_DECODE_ERROR;
2755                                 return 0;
2756                                 }
2757                         if (s->s3->alpn_selected)
2758                                 OPENSSL_free(s->s3->alpn_selected);
2759                         s->s3->alpn_selected = OPENSSL_malloc(len);
2760                         if (!s->s3->alpn_selected)
2761                                 {
2762                                 *al = TLS1_AD_INTERNAL_ERROR;
2763                                 return 0;
2764                                 }
2765                         memcpy(s->s3->alpn_selected, data + 3, len);
2766                         s->s3->alpn_selected_len = len;
2767                         }
2768
2769                 else if (type == TLSEXT_TYPE_renegotiate)
2770                         {
2771                         if(!ssl_parse_serverhello_renegotiate_ext(s, data, size, al))
2772                                 return 0;
2773                         renegotiate_seen = 1;
2774                         }
2775 #ifndef OPENSSL_NO_HEARTBEATS
2776                 else if (type == TLSEXT_TYPE_heartbeat)
2777                         {
2778                         switch(data[0])
2779                                 {
2780                                 case 0x01:      /* Server allows us to send HB requests */
2781                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2782                                                         break;
2783                                 case 0x02:      /* Server doesn't accept HB requests */
2784                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2785                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2786                                                         break;
2787                                 default:        *al = SSL_AD_ILLEGAL_PARAMETER;
2788                                                         return 0;
2789                                 }
2790                         }
2791 #endif
2792                 else if (SSL_IS_DTLS(s) && type == TLSEXT_TYPE_use_srtp)
2793                         {
2794                         if(ssl_parse_serverhello_use_srtp_ext(s, data, size,
2795                                                               al))
2796                                 return 0;
2797                         }
2798                 /* If this extension type was not otherwise handled, but 
2799                  * matches a custom_cli_ext_record, then send it to the c
2800                  * callback */
2801                 else if (custom_ext_parse(s, 0, type, data, size, al) <= 0)
2802                                 return 0;
2803  
2804                 data += size;
2805                 }
2806
2807         if (data != d+n)
2808                 {
2809                 *al = SSL_AD_DECODE_ERROR;
2810                 return 0;
2811                 }
2812
2813         if (!s->hit && tlsext_servername == 1)
2814                 {
2815                 if (s->tlsext_hostname)
2816                         {
2817                         if (s->session->tlsext_hostname == NULL)
2818                                 {
2819                                 s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);   
2820                                 if (!s->session->tlsext_hostname)
2821                                         {
2822                                         *al = SSL_AD_UNRECOGNIZED_NAME;
2823                                         return 0;
2824                                         }
2825                                 }
2826                         else 
2827                                 {
2828                                 *al = SSL_AD_DECODE_ERROR;
2829                                 return 0;
2830                                 }
2831                         }
2832                 }
2833
2834         *p = data;
2835
2836         ri_check:
2837
2838         /* Determine if we need to see RI. Strictly speaking if we want to
2839          * avoid an attack we should *always* see RI even on initial server
2840          * hello because the client doesn't see any renegotiation during an
2841          * attack. However this would mean we could not connect to any server
2842          * which doesn't support RI so for the immediate future tolerate RI
2843          * absence on initial connect only.
2844          */
2845         if (!renegotiate_seen
2846                 && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
2847                 && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
2848                 {
2849                 *al = SSL_AD_HANDSHAKE_FAILURE;
2850                 SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT,
2851                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2852                 return 0;
2853                 }
2854
2855         return 1;
2856         }
2857
2858
2859 int ssl_prepare_clienthello_tlsext(SSL *s)
2860         {
2861
2862 #ifdef TLSEXT_TYPE_opaque_prf_input
2863         {
2864                 int r = 1;
2865         
2866                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
2867                         {
2868                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
2869                         if (!r)
2870                                 return -1;
2871                         }
2872
2873                 if (s->tlsext_opaque_prf_input != NULL)
2874                         {
2875                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
2876                                 OPENSSL_free(s->s3->client_opaque_prf_input);
2877
2878                         if (s->tlsext_opaque_prf_input_len == 0)
2879                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2880                         else
2881                                 s->s3->client_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
2882                         if (s->s3->client_opaque_prf_input == NULL)
2883                                 {
2884                                 SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
2885                                 return -1;
2886                                 }
2887                         s->s3->client_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2888                         }
2889
2890                 if (r == 2)
2891                         /* at callback's request, insist on receiving an appropriate server opaque PRF input */
2892                         s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2893         }
2894 #endif
2895
2896         return 1;
2897         }
2898
2899 int ssl_prepare_serverhello_tlsext(SSL *s)
2900         {
2901         return 1;
2902         }
2903
2904 static int ssl_check_clienthello_tlsext_early(SSL *s)
2905         {
2906         int ret=SSL_TLSEXT_ERR_NOACK;
2907         int al = SSL_AD_UNRECOGNIZED_NAME;
2908
2909 #ifndef OPENSSL_NO_EC
2910         /* The handling of the ECPointFormats extension is done elsewhere, namely in 
2911          * ssl3_choose_cipher in s3_lib.c.
2912          */
2913         /* The handling of the EllipticCurves extension is done elsewhere, namely in 
2914          * ssl3_choose_cipher in s3_lib.c.
2915          */
2916 #endif
2917
2918         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
2919                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
2920         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
2921                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
2922
2923 #ifdef TLSEXT_TYPE_opaque_prf_input
2924         {
2925                 /* This sort of belongs into ssl_prepare_serverhello_tlsext(),
2926                  * but we might be sending an alert in response to the client hello,
2927                  * so this has to happen here in
2928                  * ssl_check_clienthello_tlsext_early(). */
2929
2930                 int r = 1;
2931         
2932                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
2933                         {
2934                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
2935                         if (!r)
2936                                 {
2937                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2938                                 al = SSL_AD_INTERNAL_ERROR;
2939                                 goto err;
2940                                 }
2941                         }
2942
2943                 if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
2944                         OPENSSL_free(s->s3->server_opaque_prf_input);
2945                 s->s3->server_opaque_prf_input = NULL;
2946
2947                 if (s->tlsext_opaque_prf_input != NULL)
2948                         {
2949                         if (s->s3->client_opaque_prf_input != NULL &&
2950                                 s->s3->client_opaque_prf_input_len == s->tlsext_opaque_prf_input_len)
2951                                 {
2952                                 /* can only use this extension if we have a server opaque PRF input
2953                                  * of the same length as the client opaque PRF input! */
2954
2955                                 if (s->tlsext_opaque_prf_input_len == 0)
2956                                         s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2957                                 else
2958                                         s->s3->server_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
2959                                 if (s->s3->server_opaque_prf_input == NULL)
2960                                         {
2961                                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2962                                         al = SSL_AD_INTERNAL_ERROR;
2963                                         goto err;
2964                                         }
2965                                 s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2966                                 }
2967                         }
2968
2969                 if (r == 2 && s->s3->server_opaque_prf_input == NULL)
2970                         {
2971                         /* The callback wants to enforce use of the extension,
2972                          * but we can't do that with the client opaque PRF input;
2973                          * abort the handshake.
2974                          */
2975                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2976                         al = SSL_AD_HANDSHAKE_FAILURE;
2977                         }
2978         }
2979
2980  err:
2981 #endif
2982         switch (ret)
2983                 {
2984                 case SSL_TLSEXT_ERR_ALERT_FATAL:
2985                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2986                         return -1;
2987
2988                 case SSL_TLSEXT_ERR_ALERT_WARNING:
2989                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
2990                         return 1; 
2991                                         
2992                 case SSL_TLSEXT_ERR_NOACK:
2993                         s->servername_done=0;
2994                         default:
2995                 return 1;
2996                 }
2997         }
2998
2999 int ssl_check_clienthello_tlsext_late(SSL *s)
3000         {
3001         int ret = SSL_TLSEXT_ERR_OK;
3002         int al;
3003
3004         /* If status request then ask callback what to do.
3005          * Note: this must be called after servername callbacks in case
3006          * the certificate has changed, and must be called after the cipher
3007          * has been chosen because this may influence which certificate is sent
3008          */
3009         if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb)
3010                 {
3011                 int r;
3012                 CERT_PKEY *certpkey;
3013                 certpkey = ssl_get_server_send_pkey(s);
3014                 /* If no certificate can't return certificate status */
3015                 if (certpkey == NULL)
3016                         {
3017                         s->tlsext_status_expected = 0;
3018                         return 1;
3019                         }
3020                 /* Set current certificate to one we will use so
3021                  * SSL_get_certificate et al can pick it up.
3022                  */
3023                 s->cert->key = certpkey;
3024                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
3025                 switch (r)
3026                         {
3027                         /* We don't want to send a status request response */
3028                         case SSL_TLSEXT_ERR_NOACK:
3029                                 s->tlsext_status_expected = 0;
3030                                 break;
3031                         /* status request response should be sent */
3032                         case SSL_TLSEXT_ERR_OK:
3033                                 if (s->tlsext_ocsp_resp)
3034                                         s->tlsext_status_expected = 1;
3035                                 else
3036                                         s->tlsext_status_expected = 0;
3037                                 break;
3038                         /* something bad happened */
3039                         case SSL_TLSEXT_ERR_ALERT_FATAL:
3040                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3041                                 al = SSL_AD_INTERNAL_ERROR;
3042                                 goto err;
3043                         }
3044                 }
3045         else
3046                 s->tlsext_status_expected = 0;
3047
3048  err:
3049         switch (ret)
3050                 {
3051                 case SSL_TLSEXT_ERR_ALERT_FATAL:
3052                         ssl3_send_alert(s, SSL3_AL_FATAL, al);
3053                         return -1;
3054
3055                 case SSL_TLSEXT_ERR_ALERT_WARNING:
3056                         ssl3_send_alert(s, SSL3_AL_WARNING, al);
3057                         return 1; 
3058
3059                 default:
3060                         return 1;
3061                 }
3062         }
3063
3064 int ssl_check_serverhello_tlsext(SSL *s)
3065         {
3066         int ret=SSL_TLSEXT_ERR_NOACK;
3067         int al = SSL_AD_UNRECOGNIZED_NAME;
3068
3069 #ifndef OPENSSL_NO_EC
3070         /* If we are client and using an elliptic curve cryptography cipher
3071          * suite, then if server returns an EC point formats lists extension
3072          * it must contain uncompressed.
3073          */
3074         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3075         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
3076         if ((s->tlsext_ecpointformatlist != NULL) && (s->tlsext_ecpointformatlist_length > 0) && 
3077             (s->session->tlsext_ecpointformatlist != NULL) && (s->session->tlsext_ecpointformatlist_length > 0) && 
3078             ((alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA)))
3079                 {
3080                 /* we are using an ECC cipher */
3081                 size_t i;
3082                 unsigned char *list;
3083                 int found_uncompressed = 0;
3084                 list = s->session->tlsext_ecpointformatlist;
3085                 for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
3086                         {
3087                         if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed)
3088                                 {
3089                                 found_uncompressed = 1;
3090                                 break;
3091                                 }
3092                         }
3093                 if (!found_uncompressed)
3094                         {
3095                         SSLerr(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT,SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
3096                         return -1;
3097                         }
3098                 }
3099         ret = SSL_TLSEXT_ERR_OK;
3100 #endif /* OPENSSL_NO_EC */
3101
3102         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
3103                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
3104         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
3105                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
3106
3107 #ifdef TLSEXT_TYPE_opaque_prf_input
3108         if (s->s3->server_opaque_prf_input_len > 0)
3109                 {
3110                 /* This case may indicate that we, as a client, want to insist on using opaque PRF inputs.
3111                  * So first verify that we really have a value from the server too. */
3112
3113                 if (s->s3->server_opaque_prf_input == NULL)
3114                         {
3115                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3116                         al = SSL_AD_HANDSHAKE_FAILURE;
3117                         }
3118                 
3119                 /* Anytime the server *has* sent an opaque PRF input, we need to check
3120                  * that we have a client opaque PRF input of the same size. */
3121                 if (s->s3->client_opaque_prf_input == NULL ||
3122                     s->s3->client_opaque_prf_input_len != s->s3->server_opaque_prf_input_len)
3123                         {
3124                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3125                         al = SSL_AD_ILLEGAL_PARAMETER;
3126                         }
3127                 }
3128 #endif
3129
3130         /* If we've requested certificate status and we wont get one
3131          * tell the callback
3132          */
3133         if ((s->tlsext_status_type != -1) && !(s->tlsext_status_expected)
3134                         && s->ctx && s->ctx->tlsext_status_cb)
3135                 {
3136                 int r;
3137                 /* Set resp to NULL, resplen to -1 so callback knows
3138                  * there is no response.
3139                  */
3140                 if (s->tlsext_ocsp_resp)
3141                         {
3142                         OPENSSL_free(s->tlsext_ocsp_resp);
3143                         s->tlsext_ocsp_resp = NULL;
3144                         }
3145                 s->tlsext_ocsp_resplen = -1;
3146                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
3147                 if (r == 0)
3148                         {
3149                         al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
3150                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3151                         }
3152                 if (r < 0)
3153                         {
3154                         al = SSL_AD_INTERNAL_ERROR;
3155                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3156                         }
3157                 }
3158
3159         switch (ret)
3160                 {
3161                 case SSL_TLSEXT_ERR_ALERT_FATAL:
3162                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
3163                         return -1;
3164
3165                 case SSL_TLSEXT_ERR_ALERT_WARNING:
3166                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
3167                         return 1; 
3168                                         
3169                 case SSL_TLSEXT_ERR_NOACK:
3170                         s->servername_done=0;
3171                         default:
3172                 return 1;
3173                 }
3174         }
3175
3176 int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n) 
3177         {
3178         int al = -1;
3179         if (s->version < SSL3_VERSION)
3180                 return 1;
3181         if (ssl_scan_serverhello_tlsext(s, p, d, n, &al) <= 0) 
3182                 {
3183                 ssl3_send_alert(s,SSL3_AL_FATAL,al); 
3184                 return 0;
3185                 }
3186
3187         if (ssl_check_serverhello_tlsext(s) <= 0) 
3188                 {
3189                 SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT,SSL_R_SERVERHELLO_TLSEXT);
3190                 return 0;
3191                 }
3192         return 1;
3193 }
3194
3195 /* Since the server cache lookup is done early on in the processing of the
3196  * ClientHello, and other operations depend on the result, we need to handle
3197  * any TLS session ticket extension at the same time.
3198  *
3199  *   session_id: points at the session ID in the ClientHello. This code will
3200  *       read past the end of this in order to parse out the session ticket
3201  *       extension, if any.
3202  *   len: the length of the session ID.
3203  *   limit: a pointer to the first byte after the ClientHello.
3204  *   ret: (output) on return, if a ticket was decrypted, then this is set to
3205  *       point to the resulting session.
3206  *
3207  * If s->tls_session_secret_cb is set then we are expecting a pre-shared key
3208  * ciphersuite, in which case we have no use for session tickets and one will
3209  * never be decrypted, nor will s->tlsext_ticket_expected be set to 1.
3210  *
3211  * Returns:
3212  *   -1: fatal error, either from parsing or decrypting the ticket.
3213  *    0: no ticket was found (or was ignored, based on settings).
3214  *    1: a zero length extension was found, indicating that the client supports
3215  *       session tickets but doesn't currently have one to offer.
3216  *    2: either s->tls_session_secret_cb was set, or a ticket was offered but
3217  *       couldn't be decrypted because of a non-fatal error.
3218  *    3: a ticket was successfully decrypted and *ret was set.
3219  *
3220  * Side effects:
3221  *   Sets s->tlsext_ticket_expected to 1 if the server will have to issue
3222  *   a new session ticket to the client because the client indicated support
3223  *   (and s->tls_session_secret_cb is NULL) but the client either doesn't have
3224  *   a session ticket or we couldn't use the one it gave us, or if
3225  *   s->ctx->tlsext_ticket_key_cb asked to renew the client's ticket.
3226  *   Otherwise, s->tlsext_ticket_expected is set to 0.
3227  */
3228 int tls1_process_ticket(SSL *s, unsigned char *session_id, int len,
3229                         const unsigned char *limit, SSL_SESSION **ret)
3230         {
3231         /* Point after session ID in client hello */
3232         const unsigned char *p = session_id + len;
3233         unsigned short i;
3234
3235         *ret = NULL;
3236         s->tlsext_ticket_expected = 0;
3237
3238         /* If tickets disabled behave as if no ticket present
3239          * to permit stateful resumption.
3240          */
3241         if (SSL_get_options(s) & SSL_OP_NO_TICKET)
3242                 return 0;
3243         if ((s->version <= SSL3_VERSION) || !limit)
3244                 return 0;
3245         if (p >= limit)
3246                 return -1;
3247         /* Skip past DTLS cookie */
3248         if (SSL_IS_DTLS(s))
3249                 {
3250                 i = *(p++);
3251                 p+= i;
3252                 if (p >= limit)
3253                         return -1;
3254                 }
3255         /* Skip past cipher list */
3256         n2s(p, i);
3257         p+= i;
3258         if (p >= limit)
3259                 return -1;
3260         /* Skip past compression algorithm list */
3261         i = *(p++);
3262         p += i;
3263         if (p > limit)
3264                 return -1;
3265         /* Now at start of extensions */
3266         if ((p + 2) >= limit)
3267                 return 0;
3268         n2s(p, i);
3269         while ((p + 4) <= limit)
3270                 {
3271                 unsigned short type, size;
3272                 n2s(p, type);
3273                 n2s(p, size);
3274                 if (p + size > limit)
3275                         return 0;
3276                 if (type == TLSEXT_TYPE_session_ticket)
3277                         {
3278                         int r;
3279                         if (size == 0)
3280                                 {
3281                                 /* The client will accept a ticket but doesn't
3282                                  * currently have one. */
3283                                 s->tlsext_ticket_expected = 1;
3284                                 return 1;
3285                                 }
3286                         if (s->tls_session_secret_cb)
3287                                 {
3288                                 /* Indicate that the ticket couldn't be
3289                                  * decrypted rather than generating the session
3290                                  * from ticket now, trigger abbreviated
3291                                  * handshake based on external mechanism to
3292                                  * calculate the master secret later. */
3293                                 return 2;
3294                                 }
3295                         r = tls_decrypt_ticket(s, p, size, session_id, len, ret);
3296                         switch (r)
3297                                 {
3298                                 case 2: /* ticket couldn't be decrypted */
3299                                         s->tlsext_ticket_expected = 1;
3300                                         return 2;
3301                                 case 3: /* ticket was decrypted */
3302                                         return r;
3303                                 case 4: /* ticket decrypted but need to renew */
3304                                         s->tlsext_ticket_expected = 1;
3305                                         return 3;
3306                                 default: /* fatal error */
3307                                         return -1;
3308                                 }
3309                         }
3310                 p += size;
3311                 }
3312         return 0;
3313         }
3314
3315 /* tls_decrypt_ticket attempts to decrypt a session ticket.
3316  *
3317  *   etick: points to the body of the session ticket extension.
3318  *   eticklen: the length of the session tickets extenion.
3319  *   sess_id: points at the session ID.
3320  *   sesslen: the length of the session ID.
3321  *   psess: (output) on return, if a ticket was decrypted, then this is set to
3322  *       point to the resulting session.
3323  *
3324  * Returns:
3325  *   -1: fatal error, either from parsing or decrypting the ticket.
3326  *    2: the ticket couldn't be decrypted.
3327  *    3: a ticket was successfully decrypted and *psess was set.
3328  *    4: same as 3, but the ticket needs to be renewed.
3329  */
3330 static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen,
3331                                 const unsigned char *sess_id, int sesslen,
3332                                 SSL_SESSION **psess)
3333         {
3334         SSL_SESSION *sess;
3335         unsigned char *sdec;
3336         const unsigned char *p;
3337         int slen, mlen, renew_ticket = 0;
3338         unsigned char tick_hmac[EVP_MAX_MD_SIZE];
3339         HMAC_CTX hctx;
3340         EVP_CIPHER_CTX ctx;
3341         SSL_CTX *tctx = s->initial_ctx;
3342         /* Need at least keyname + iv + some encrypted data */
3343         if (eticklen < 48)
3344                 return 2;
3345         /* Initialize session ticket encryption and HMAC contexts */
3346         HMAC_CTX_init(&hctx);
3347         EVP_CIPHER_CTX_init(&ctx);
3348         if (tctx->tlsext_ticket_key_cb)
3349                 {
3350                 unsigned char *nctick = (unsigned char *)etick;
3351                 int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
3352                                                         &ctx, &hctx, 0);
3353                 if (rv < 0)
3354                         return -1;
3355                 if (rv == 0)
3356                         return 2;
3357                 if (rv == 2)
3358                         renew_ticket = 1;
3359                 }
3360         else
3361                 {
3362                 /* Check key name matches */
3363                 if (memcmp(etick, tctx->tlsext_tick_key_name, 16))
3364                         return 2;
3365                 HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3366                                         tlsext_tick_md(), NULL);
3367                 EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3368                                 tctx->tlsext_tick_aes_key, etick + 16);
3369                 }
3370         /* Attempt to process session ticket, first conduct sanity and
3371          * integrity checks on ticket.
3372          */
3373         mlen = HMAC_size(&hctx);
3374         if (mlen < 0)
3375                 {
3376                 EVP_CIPHER_CTX_cleanup(&ctx);
3377                 return -1;
3378                 }
3379         eticklen -= mlen;
3380         /* Check HMAC of encrypted ticket */
3381         HMAC_Update(&hctx, etick, eticklen);
3382         HMAC_Final(&hctx, tick_hmac, NULL);
3383         HMAC_CTX_cleanup(&hctx);
3384         if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen))
3385                 {
3386                 EVP_CIPHER_CTX_cleanup(&ctx);
3387                 return 2;
3388                 }
3389         /* Attempt to decrypt session data */
3390         /* Move p after IV to start of encrypted ticket, update length */
3391         p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx);
3392         eticklen -= 16 + EVP_CIPHER_CTX_iv_length(&ctx);
3393         sdec = OPENSSL_malloc(eticklen);
3394         if (!sdec)
3395                 {
3396                 EVP_CIPHER_CTX_cleanup(&ctx);
3397                 return -1;
3398                 }
3399         EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen);
3400         if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0)
3401                 {
3402                 EVP_CIPHER_CTX_cleanup(&ctx);
3403                 OPENSSL_free(sdec);
3404                 return 2;
3405                 }
3406         slen += mlen;
3407         EVP_CIPHER_CTX_cleanup(&ctx);
3408         p = sdec;
3409
3410         sess = d2i_SSL_SESSION(NULL, &p, slen);
3411         OPENSSL_free(sdec);
3412         if (sess)
3413                 {
3414                 /* The session ID, if non-empty, is used by some clients to
3415                  * detect that the ticket has been accepted. So we copy it to
3416                  * the session structure. If it is empty set length to zero
3417                  * as required by standard.
3418                  */
3419                 if (sesslen)
3420                         memcpy(sess->session_id, sess_id, sesslen);
3421                 sess->session_id_length = sesslen;
3422                 *psess = sess;
3423                 if (renew_ticket)
3424                         return 4;
3425                 else
3426                         return 3;
3427                 }
3428         ERR_clear_error();
3429         /* For session parse failure, indicate that we need to send a new
3430          * ticket. */
3431         return 2;
3432         }
3433
3434 /* Tables to translate from NIDs to TLS v1.2 ids */
3435
3436 typedef struct 
3437         {
3438         int nid;
3439         int id;
3440         } tls12_lookup;
3441
3442 static tls12_lookup tls12_md[] = {
3443         {NID_md5, TLSEXT_hash_md5},
3444         {NID_sha1, TLSEXT_hash_sha1},
3445         {NID_sha224, TLSEXT_hash_sha224},
3446         {NID_sha256, TLSEXT_hash_sha256},
3447         {NID_sha384, TLSEXT_hash_sha384},
3448         {NID_sha512, TLSEXT_hash_sha512}
3449 };
3450
3451 static tls12_lookup tls12_sig[] = {
3452         {EVP_PKEY_RSA, TLSEXT_signature_rsa},
3453         {EVP_PKEY_DSA, TLSEXT_signature_dsa},
3454         {EVP_PKEY_EC, TLSEXT_signature_ecdsa}
3455 };
3456
3457 static int tls12_find_id(int nid, tls12_lookup *table, size_t tlen)
3458         {
3459         size_t i;
3460         for (i = 0; i < tlen; i++)
3461                 {
3462                 if (table[i].nid == nid)
3463                         return table[i].id;
3464                 }
3465         return -1;
3466         }
3467
3468 static int tls12_find_nid(int id, tls12_lookup *table, size_t tlen)
3469         {
3470         size_t i;
3471         for (i = 0; i < tlen; i++)
3472                 {
3473                 if ((table[i].id) == id)
3474                         return table[i].nid;
3475                 }
3476         return NID_undef;
3477         }
3478
3479 int tls12_get_sigandhash(unsigned char *p, const EVP_PKEY *pk, const EVP_MD *md)
3480         {
3481         int sig_id, md_id;
3482         if (!md)
3483                 return 0;
3484         md_id = tls12_find_id(EVP_MD_type(md), tls12_md,
3485                                 sizeof(tls12_md)/sizeof(tls12_lookup));
3486         if (md_id == -1)
3487                 return 0;
3488         sig_id = tls12_get_sigid(pk);
3489         if (sig_id == -1)
3490                 return 0;
3491         p[0] = (unsigned char)md_id;
3492         p[1] = (unsigned char)sig_id;
3493         return 1;
3494         }
3495
3496 int tls12_get_sigid(const EVP_PKEY *pk)
3497         {
3498         return tls12_find_id(pk->type, tls12_sig,
3499                                 sizeof(tls12_sig)/sizeof(tls12_lookup));
3500         }
3501
3502 const EVP_MD *tls12_get_hash(unsigned char hash_alg)
3503         {
3504         switch(hash_alg)
3505                 {
3506 #ifndef OPENSSL_NO_MD5
3507                 case TLSEXT_hash_md5:
3508 #ifdef OPENSSL_FIPS
3509                 if (FIPS_mode())
3510                         return NULL;
3511 #endif
3512                 return EVP_md5();
3513 #endif
3514 #ifndef OPENSSL_NO_SHA
3515                 case TLSEXT_hash_sha1:
3516                 return EVP_sha1();
3517 #endif
3518 #ifndef OPENSSL_NO_SHA256
3519                 case TLSEXT_hash_sha224:
3520                 return EVP_sha224();
3521
3522                 case TLSEXT_hash_sha256:
3523                 return EVP_sha256();
3524 #endif
3525 #ifndef OPENSSL_NO_SHA512
3526                 case TLSEXT_hash_sha384:
3527                 return EVP_sha384();
3528
3529                 case TLSEXT_hash_sha512:
3530                 return EVP_sha512();
3531 #endif
3532                 default:
3533                 return NULL;
3534
3535                 }
3536         }
3537
3538 static int tls12_get_pkey_idx(unsigned char sig_alg)
3539         {
3540         switch(sig_alg)
3541                 {
3542 #ifndef OPENSSL_NO_RSA
3543         case TLSEXT_signature_rsa:
3544                 return SSL_PKEY_RSA_SIGN;
3545 #endif
3546 #ifndef OPENSSL_NO_DSA
3547         case TLSEXT_signature_dsa:
3548                 return SSL_PKEY_DSA_SIGN;
3549 #endif
3550 #ifndef OPENSSL_NO_ECDSA
3551         case TLSEXT_signature_ecdsa:
3552                 return SSL_PKEY_ECC;
3553 #endif
3554                 }
3555         return -1;
3556         }
3557
3558 /* Convert TLS 1.2 signature algorithm extension values into NIDs */
3559 static void tls1_lookup_sigalg(int *phash_nid, int *psign_nid,
3560                         int *psignhash_nid, const unsigned char *data)
3561         {
3562         int sign_nid = 0, hash_nid = 0;
3563         if (!phash_nid && !psign_nid && !psignhash_nid)
3564                 return;
3565         if (phash_nid || psignhash_nid)
3566                 {
3567                 hash_nid = tls12_find_nid(data[0], tls12_md,
3568                                         sizeof(tls12_md)/sizeof(tls12_lookup));
3569                 if (phash_nid)
3570                         *phash_nid = hash_nid;
3571                 }
3572         if (psign_nid || psignhash_nid)
3573                 {
3574                 sign_nid = tls12_find_nid(data[1], tls12_sig,
3575                                         sizeof(tls12_sig)/sizeof(tls12_lookup));
3576                 if (psign_nid)
3577                         *psign_nid = sign_nid;
3578                 }
3579         if (psignhash_nid)
3580                 {
3581                 if (sign_nid && hash_nid)
3582                         OBJ_find_sigid_by_algs(psignhash_nid,
3583                                                         hash_nid, sign_nid);
3584                 else
3585                         *psignhash_nid = NID_undef;
3586                 }
3587         }
3588 /* Given preference and allowed sigalgs set shared sigalgs */
3589 static int tls12_do_shared_sigalgs(TLS_SIGALGS *shsig,
3590                                 const unsigned char *pref, size_t preflen,
3591                                 const unsigned char *allow, size_t allowlen)
3592         {
3593         const unsigned char *ptmp, *atmp;
3594         size_t i, j, nmatch = 0;
3595         for (i = 0, ptmp = pref; i < preflen; i+=2, ptmp+=2)
3596                 {
3597                 /* Skip disabled hashes or signature algorithms */
3598                 if (tls12_get_hash(ptmp[0]) == NULL)
3599                         continue;
3600                 if (tls12_get_pkey_idx(ptmp[1]) == -1)
3601                         continue;
3602                 for (j = 0, atmp = allow; j < allowlen; j+=2, atmp+=2)
3603                         {
3604                         if (ptmp[0] == atmp[0] && ptmp[1] == atmp[1])
3605                                 {
3606                                 nmatch++;
3607                                 if (shsig)
3608                                         {
3609                                         shsig->rhash = ptmp[0];
3610                                         shsig->rsign = ptmp[1];
3611                                         tls1_lookup_sigalg(&shsig->hash_nid,
3612                                                 &shsig->sign_nid,
3613                                                 &shsig->signandhash_nid,
3614                                                 ptmp);
3615                                         shsig++;
3616                                         }
3617                                 break;
3618                                 }
3619                         }
3620                 }
3621         return nmatch;
3622         }
3623
3624 /* Set shared signature algorithms for SSL structures */
3625 static int tls1_set_shared_sigalgs(SSL *s)
3626         {
3627         const unsigned char *pref, *allow, *conf;
3628         size_t preflen, allowlen, conflen;
3629         size_t nmatch;
3630         TLS_SIGALGS *salgs = NULL;
3631         CERT *c = s->cert;
3632         unsigned int is_suiteb = tls1_suiteb(s);
3633         if (c->shared_sigalgs)
3634                 {
3635                 OPENSSL_free(c->shared_sigalgs);
3636                 c->shared_sigalgs = NULL;
3637                 }
3638         /* If client use client signature algorithms if not NULL */
3639         if (!s->server && c->client_sigalgs && !is_suiteb)
3640                 {
3641                 conf = c->client_sigalgs;
3642                 conflen = c->client_sigalgslen;
3643                 }
3644         else if (c->conf_sigalgs && !is_suiteb)
3645                 {
3646                 conf = c->conf_sigalgs;
3647                 conflen = c->conf_sigalgslen;
3648                 }
3649         else
3650                 conflen = tls12_get_psigalgs(s, &conf);
3651         if(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE || is_suiteb)
3652                 {
3653                 pref = conf;
3654                 preflen = conflen;
3655                 allow = c->peer_sigalgs;
3656                 allowlen = c->peer_sigalgslen;
3657                 }
3658         else
3659                 {
3660                 allow = conf;
3661                 allowlen = conflen;
3662                 pref = c->peer_sigalgs;
3663                 preflen = c->peer_sigalgslen;
3664                 }
3665         nmatch = tls12_do_shared_sigalgs(NULL, pref, preflen, allow, allowlen);
3666         if (!nmatch)
3667                 return 1;
3668         salgs = OPENSSL_malloc(nmatch * sizeof(TLS_SIGALGS));
3669         if (!salgs)
3670                 return 0;
3671         nmatch = tls12_do_shared_sigalgs(salgs, pref, preflen, allow, allowlen);
3672         c->shared_sigalgs = salgs;
3673         c->shared_sigalgslen = nmatch;
3674         return 1;
3675         }
3676                 
3677
3678 /* Set preferred digest for each key type */
3679
3680 int tls1_process_sigalgs(SSL *s, const unsigned char *data, int dsize)
3681         {
3682         int idx;
3683         size_t i;
3684         const EVP_MD *md;
3685         CERT *c = s->cert;
3686         TLS_SIGALGS *sigptr;
3687         /* Extension ignored for inappropriate versions */
3688         if (!SSL_USE_SIGALGS(s))
3689                 return 1;
3690         /* Should never happen */
3691         if (!c)
3692                 return 0;
3693
3694         if (c->peer_sigalgs)
3695                 OPENSSL_free(c->peer_sigalgs);
3696         c->peer_sigalgs = OPENSSL_malloc(dsize);
3697         if (!c->peer_sigalgs)
3698                 return 0;
3699         c->peer_sigalgslen = dsize;
3700         memcpy(c->peer_sigalgs, data, dsize);
3701
3702         tls1_set_shared_sigalgs(s);
3703
3704 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
3705         if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
3706                 {
3707                 /* Use first set signature preference to force message
3708                  * digest, ignoring any peer preferences.
3709                  */
3710                 const unsigned char *sigs = NULL;
3711                 if (s->server)
3712                         sigs = c->conf_sigalgs;
3713                 else
3714                         sigs = c->client_sigalgs;
3715                 if (sigs)
3716                         {
3717                         idx = tls12_get_pkey_idx(sigs[1]);
3718                         md = tls12_get_hash(sigs[0]);
3719                         c->pkeys[idx].digest = md;
3720                         c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3721                         if (idx == SSL_PKEY_RSA_SIGN)
3722                                 {
3723                                 c->pkeys[SSL_PKEY_RSA_ENC].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3724                                 c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
3725                                 }
3726                         }
3727                 }
3728 #endif
3729
3730         for (i = 0, sigptr = c->shared_sigalgs;
3731                         i < c->shared_sigalgslen; i++, sigptr++)
3732                 {
3733                 idx = tls12_get_pkey_idx(sigptr->rsign);
3734                 if (idx > 0 && c->pkeys[idx].digest == NULL)
3735                         {
3736                         md = tls12_get_hash(sigptr->rhash);
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                 }
3747         /* In strict mode leave unset digests as NULL to indicate we can't
3748          * use the certificate for signing.
3749          */
3750         if (!(s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT))
3751                 {
3752                 /* Set any remaining keys to default values. NOTE: if alg is
3753                  * not supported it stays as NULL.
3754                  */
3755 #ifndef OPENSSL_NO_DSA
3756                 if (!c->pkeys[SSL_PKEY_DSA_SIGN].digest)
3757                         c->pkeys[SSL_PKEY_DSA_SIGN].digest = EVP_sha1();
3758 #endif
3759 #ifndef OPENSSL_NO_RSA
3760                 if (!c->pkeys[SSL_PKEY_RSA_SIGN].digest)
3761                         {
3762                         c->pkeys[SSL_PKEY_RSA_SIGN].digest = EVP_sha1();
3763                         c->pkeys[SSL_PKEY_RSA_ENC].digest = EVP_sha1();
3764                         }
3765 #endif
3766 #ifndef OPENSSL_NO_ECDSA
3767                 if (!c->pkeys[SSL_PKEY_ECC].digest)
3768                         c->pkeys[SSL_PKEY_ECC].digest = EVP_sha1();
3769 #endif
3770                 }
3771         return 1;
3772         }
3773
3774
3775 int SSL_get_sigalgs(SSL *s, int idx,
3776                         int *psign, int *phash, int *psignhash,
3777                         unsigned char *rsig, unsigned char *rhash)
3778         {
3779         const unsigned char *psig = s->cert->peer_sigalgs;
3780         if (psig == NULL)
3781                 return 0;
3782         if (idx >= 0)
3783                 {
3784                 idx <<= 1;
3785                 if (idx >= (int)s->cert->peer_sigalgslen)
3786                         return 0;
3787                 psig += idx;
3788                 if (rhash)
3789                         *rhash = psig[0];
3790                 if (rsig)
3791                         *rsig = psig[1];
3792                 tls1_lookup_sigalg(phash, psign, psignhash, psig);
3793                 }
3794         return s->cert->peer_sigalgslen / 2;
3795         }
3796
3797 int SSL_get_shared_sigalgs(SSL *s, int idx,
3798                         int *psign, int *phash, int *psignhash,
3799                         unsigned char *rsig, unsigned char *rhash)
3800         {
3801         TLS_SIGALGS *shsigalgs = s->cert->shared_sigalgs;
3802         if (!shsigalgs || idx >= (int)s->cert->shared_sigalgslen)
3803                 return 0;
3804         shsigalgs += idx;
3805         if (phash)
3806                 *phash = shsigalgs->hash_nid;
3807         if (psign)
3808                 *psign = shsigalgs->sign_nid;
3809         if (psignhash)
3810                 *psignhash = shsigalgs->signandhash_nid;
3811         if (rsig)
3812                 *rsig = shsigalgs->rsign;
3813         if (rhash)
3814                 *rhash = shsigalgs->rhash;
3815         return s->cert->shared_sigalgslen;
3816         }
3817         
3818
3819 #ifndef OPENSSL_NO_HEARTBEATS
3820 int
3821 tls1_process_heartbeat(SSL *s)
3822         {
3823         unsigned char *p = &s->s3->rrec.data[0], *pl;
3824         unsigned short hbtype;
3825         unsigned int payload;
3826         unsigned int padding = 16; /* Use minimum padding */
3827
3828         if (s->msg_callback)
3829                 s->msg_callback(0, s->version, TLS1_RT_HEARTBEAT,
3830                         &s->s3->rrec.data[0], s->s3->rrec.length,
3831                         s, s->msg_callback_arg);
3832
3833         /* Read type and payload length first */
3834         if (1 + 2 + 16 > s->s3->rrec.length)
3835                 return 0; /* silently discard */
3836         hbtype = *p++;
3837         n2s(p, payload);
3838         if (1 + 2 + payload + 16 > s->s3->rrec.length)
3839                 return 0; /* silently discard per RFC 6520 sec. 4 */
3840         pl = p;
3841
3842         if (hbtype == TLS1_HB_REQUEST)
3843                 {
3844                 unsigned char *buffer, *bp;
3845                 int r;
3846
3847                 /* Allocate memory for the response, size is 1 bytes
3848                  * message type, plus 2 bytes payload length, plus
3849                  * payload, plus padding
3850                  */
3851                 buffer = OPENSSL_malloc(1 + 2 + payload + padding);
3852                 bp = buffer;
3853                 
3854                 /* Enter response type, length and copy payload */
3855                 *bp++ = TLS1_HB_RESPONSE;
3856                 s2n(payload, bp);
3857                 memcpy(bp, pl, payload);
3858                 bp += payload;
3859                 /* Random padding */
3860                 RAND_pseudo_bytes(bp, padding);
3861
3862                 r = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buffer, 3 + payload + padding);
3863
3864                 if (r >= 0 && s->msg_callback)
3865                         s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
3866                                 buffer, 3 + payload + padding,
3867                                 s, s->msg_callback_arg);
3868
3869                 OPENSSL_free(buffer);
3870
3871                 if (r < 0)
3872                         return r;
3873                 }
3874         else if (hbtype == TLS1_HB_RESPONSE)
3875                 {
3876                 unsigned int seq;
3877                 
3878                 /* We only send sequence numbers (2 bytes unsigned int),
3879                  * and 16 random bytes, so we just try to read the
3880                  * sequence number */
3881                 n2s(pl, seq);
3882                 
3883                 if (payload == 18 && seq == s->tlsext_hb_seq)
3884                         {
3885                         s->tlsext_hb_seq++;
3886                         s->tlsext_hb_pending = 0;
3887                         }
3888                 }
3889
3890         return 0;
3891         }
3892
3893 int
3894 tls1_heartbeat(SSL *s)
3895         {
3896         unsigned char *buf, *p;
3897         int ret;
3898         unsigned int payload = 18; /* Sequence number + random bytes */
3899         unsigned int padding = 16; /* Use minimum padding */
3900
3901         /* Only send if peer supports and accepts HB requests... */
3902         if (!(s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) ||
3903             s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_SEND_REQUESTS)
3904                 {
3905                 SSLerr(SSL_F_TLS1_HEARTBEAT,SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT);
3906                 return -1;
3907                 }
3908
3909         /* ...and there is none in flight yet... */
3910         if (s->tlsext_hb_pending)
3911                 {
3912                 SSLerr(SSL_F_TLS1_HEARTBEAT,SSL_R_TLS_HEARTBEAT_PENDING);
3913                 return -1;
3914                 }
3915                 
3916         /* ...and no handshake in progress. */
3917         if (SSL_in_init(s) || s->in_handshake)
3918                 {
3919                 SSLerr(SSL_F_TLS1_HEARTBEAT,SSL_R_UNEXPECTED_MESSAGE);
3920                 return -1;
3921                 }
3922                 
3923         /* Check if padding is too long, payload and padding
3924          * must not exceed 2^14 - 3 = 16381 bytes in total.
3925          */
3926         OPENSSL_assert(payload + padding <= 16381);
3927
3928         /* Create HeartBeat message, we just use a sequence number
3929          * as payload to distuingish different messages and add
3930          * some random stuff.
3931          *  - Message Type, 1 byte
3932          *  - Payload Length, 2 bytes (unsigned int)
3933          *  - Payload, the sequence number (2 bytes uint)
3934          *  - Payload, random bytes (16 bytes uint)
3935          *  - Padding
3936          */
3937         buf = OPENSSL_malloc(1 + 2 + payload + padding);
3938         p = buf;
3939         /* Message Type */
3940         *p++ = TLS1_HB_REQUEST;
3941         /* Payload length (18 bytes here) */
3942         s2n(payload, p);
3943         /* Sequence number */
3944         s2n(s->tlsext_hb_seq, p);
3945         /* 16 random bytes */
3946         RAND_pseudo_bytes(p, 16);
3947         p += 16;
3948         /* Random padding */
3949         RAND_pseudo_bytes(p, padding);
3950
3951         ret = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buf, 3 + payload + padding);
3952         if (ret >= 0)
3953                 {
3954                 if (s->msg_callback)
3955                         s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
3956                                 buf, 3 + payload + padding,
3957                                 s, s->msg_callback_arg);
3958
3959                 s->tlsext_hb_pending = 1;
3960                 }
3961                 
3962         OPENSSL_free(buf);
3963
3964         return ret;
3965         }
3966 #endif
3967
3968 #define MAX_SIGALGLEN   (TLSEXT_hash_num * TLSEXT_signature_num * 2)
3969
3970 typedef struct
3971         {
3972         size_t sigalgcnt;
3973         int sigalgs[MAX_SIGALGLEN];
3974         } sig_cb_st;
3975
3976 static int sig_cb(const char *elem, int len, void *arg)
3977         {
3978         sig_cb_st *sarg = arg;
3979         size_t i;
3980         char etmp[20], *p;
3981         int sig_alg, hash_alg;
3982         if (sarg->sigalgcnt == MAX_SIGALGLEN)
3983                 return 0;
3984         if (len > (int)(sizeof(etmp) - 1))
3985                 return 0;
3986         memcpy(etmp, elem, len);
3987         etmp[len] = 0;
3988         p = strchr(etmp, '+');
3989         if (!p)
3990                 return 0;
3991         *p = 0;
3992         p++;
3993         if (!*p)
3994                 return 0;
3995
3996         if (!strcmp(etmp, "RSA"))
3997                 sig_alg = EVP_PKEY_RSA;
3998         else if (!strcmp(etmp, "DSA"))
3999                 sig_alg = EVP_PKEY_DSA;
4000         else if (!strcmp(etmp, "ECDSA"))
4001                 sig_alg = EVP_PKEY_EC;
4002         else return 0;
4003
4004         hash_alg = OBJ_sn2nid(p);
4005         if (hash_alg == NID_undef)
4006                 hash_alg = OBJ_ln2nid(p);
4007         if (hash_alg == NID_undef)
4008                 return 0;
4009
4010         for (i = 0; i < sarg->sigalgcnt; i+=2)
4011                 {
4012                 if (sarg->sigalgs[i] == sig_alg
4013                         && sarg->sigalgs[i + 1] == hash_alg)
4014                         return 0;
4015                 }
4016         sarg->sigalgs[sarg->sigalgcnt++] = hash_alg;
4017         sarg->sigalgs[sarg->sigalgcnt++] = sig_alg;
4018         return 1;
4019         }
4020
4021 /* Set suppored signature algorithms based on a colon separated list
4022  * of the form sig+hash e.g. RSA+SHA512:DSA+SHA512 */
4023 int tls1_set_sigalgs_list(CERT *c, const char *str, int client)
4024         {
4025         sig_cb_st sig;
4026         sig.sigalgcnt = 0;
4027         if (!CONF_parse_list(str, ':', 1, sig_cb, &sig))
4028                 return 0;
4029         if (c == NULL)
4030                 return 1;
4031         return tls1_set_sigalgs(c, sig.sigalgs, sig.sigalgcnt, client);
4032         }
4033
4034 int tls1_set_sigalgs(CERT *c, const int *psig_nids, size_t salglen, int client)
4035         {
4036         unsigned char *sigalgs, *sptr;
4037         int rhash, rsign;
4038         size_t i;
4039         if (salglen & 1)
4040                 return 0;
4041         sigalgs = OPENSSL_malloc(salglen);
4042         if (sigalgs == NULL)
4043                 return 0;
4044         for (i = 0, sptr = sigalgs; i < salglen; i+=2)
4045                 {
4046                 rhash = tls12_find_id(*psig_nids++, tls12_md,
4047                                         sizeof(tls12_md)/sizeof(tls12_lookup));
4048                 rsign = tls12_find_id(*psig_nids++, tls12_sig,
4049                                 sizeof(tls12_sig)/sizeof(tls12_lookup));
4050
4051                 if (rhash == -1 || rsign == -1)
4052                         goto err;
4053                 *sptr++ = rhash;
4054                 *sptr++ = rsign;
4055                 }
4056
4057         if (client)
4058                 {
4059                 if (c->client_sigalgs)
4060                         OPENSSL_free(c->client_sigalgs);
4061                 c->client_sigalgs = sigalgs;
4062                 c->client_sigalgslen = salglen;
4063                 }
4064         else
4065                 {
4066                 if (c->conf_sigalgs)
4067                         OPENSSL_free(c->conf_sigalgs);
4068                 c->conf_sigalgs = sigalgs;
4069                 c->conf_sigalgslen = salglen;
4070                 }
4071
4072         return 1;
4073
4074         err:
4075         OPENSSL_free(sigalgs);
4076         return 0;
4077         }
4078
4079 static int tls1_check_sig_alg(CERT *c, X509 *x, int default_nid)
4080         {
4081         int sig_nid;
4082         size_t i;
4083         if (default_nid == -1)
4084                 return 1;
4085         sig_nid = X509_get_signature_nid(x);
4086         if (default_nid)
4087                 return sig_nid == default_nid ? 1 : 0;
4088         for (i = 0; i < c->shared_sigalgslen; i++)
4089                 if (sig_nid == c->shared_sigalgs[i].signandhash_nid)
4090                         return 1;
4091         return 0;
4092         }
4093 /* Check to see if a certificate issuer name matches list of CA names */
4094 static int ssl_check_ca_name(STACK_OF(X509_NAME) *names, X509 *x)
4095         {
4096         X509_NAME *nm;
4097         int i;
4098         nm = X509_get_issuer_name(x);
4099         for (i = 0; i < sk_X509_NAME_num(names); i++)
4100                 {
4101                 if(!X509_NAME_cmp(nm, sk_X509_NAME_value(names, i)))
4102                         return 1;
4103                 }
4104         return 0;
4105         }
4106
4107 /* Check certificate chain is consistent with TLS extensions and is
4108  * usable by server. This servers two purposes: it allows users to 
4109  * check chains before passing them to the server and it allows the
4110  * server to check chains before attempting to use them.
4111  */
4112
4113 /* Flags which need to be set for a certificate when stict mode not set */
4114
4115 #define CERT_PKEY_VALID_FLAGS \
4116         (CERT_PKEY_EE_SIGNATURE|CERT_PKEY_EE_PARAM)
4117 /* Strict mode flags */
4118 #define CERT_PKEY_STRICT_FLAGS \
4119          (CERT_PKEY_VALID_FLAGS|CERT_PKEY_CA_SIGNATURE|CERT_PKEY_CA_PARAM \
4120          | CERT_PKEY_ISSUER_NAME|CERT_PKEY_CERT_TYPE)
4121
4122 int tls1_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain,
4123                                                                         int idx)
4124         {
4125         int i;
4126         int rv = 0;
4127         int check_flags = 0, strict_mode;
4128         CERT_PKEY *cpk = NULL;
4129         CERT *c = s->cert;
4130         unsigned int suiteb_flags = tls1_suiteb(s);
4131         /* idx == -1 means checking server chains */
4132         if (idx != -1)
4133                 {
4134                 /* idx == -2 means checking client certificate chains */
4135                 if (idx == -2)
4136                         {
4137                         cpk = c->key;
4138                         idx = cpk - c->pkeys;
4139                         }
4140                 else
4141                         cpk = c->pkeys + idx;
4142                 x = cpk->x509;
4143                 pk = cpk->privatekey;
4144                 chain = cpk->chain;
4145                 strict_mode = c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT;
4146                 /* If no cert or key, forget it */
4147                 if (!x || !pk)
4148                         goto end;
4149 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
4150                 /* Allow any certificate to pass test */
4151                 if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
4152                         {
4153                         rv = CERT_PKEY_STRICT_FLAGS|CERT_PKEY_EXPLICIT_SIGN|CERT_PKEY_VALID|CERT_PKEY_SIGN;
4154                         cpk->valid_flags = rv;
4155                         return rv;
4156                         }
4157 #endif
4158                 }
4159         else
4160                 {
4161                 if (!x || !pk)
4162                         goto end;
4163                 idx = ssl_cert_type(x, pk);
4164                 if (idx == -1)
4165                         goto end;
4166                 cpk = c->pkeys + idx;
4167                 if (c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)
4168                         check_flags = CERT_PKEY_STRICT_FLAGS;
4169                 else
4170                         check_flags = CERT_PKEY_VALID_FLAGS;
4171                 strict_mode = 1;
4172                 }
4173
4174         if (suiteb_flags)
4175                 {
4176                 int ok;
4177                 if (check_flags)
4178                         check_flags |= CERT_PKEY_SUITEB;
4179                 ok = X509_chain_check_suiteb(NULL, x, chain, suiteb_flags);
4180                 if (ok != X509_V_OK)
4181                         {
4182                         if (check_flags)
4183                                 rv |= CERT_PKEY_SUITEB;
4184                         else
4185                                 goto end;
4186                         }
4187                 }
4188
4189         /* Check all signature algorithms are consistent with
4190          * signature algorithms extension if TLS 1.2 or later
4191          * and strict mode.
4192          */
4193         if (TLS1_get_version(s) >= TLS1_2_VERSION && strict_mode)
4194                 {
4195                 int default_nid;
4196                 unsigned char rsign = 0;
4197                 if (c->peer_sigalgs)
4198                         default_nid = 0;
4199                 /* If no sigalgs extension use defaults from RFC5246 */
4200                 else
4201                         {
4202                         switch(idx)
4203                                 {       
4204                         case SSL_PKEY_RSA_ENC:
4205                         case SSL_PKEY_RSA_SIGN:
4206                         case SSL_PKEY_DH_RSA:
4207                                 rsign = TLSEXT_signature_rsa;
4208                                 default_nid = NID_sha1WithRSAEncryption;
4209                                 break;
4210
4211                         case SSL_PKEY_DSA_SIGN:
4212                         case SSL_PKEY_DH_DSA:
4213                                 rsign = TLSEXT_signature_dsa;
4214                                 default_nid = NID_dsaWithSHA1;
4215                                 break;
4216
4217                         case SSL_PKEY_ECC:
4218                                 rsign = TLSEXT_signature_ecdsa;
4219                                 default_nid = NID_ecdsa_with_SHA1;
4220                                 break;
4221
4222                         default:
4223                                 default_nid = -1;
4224                                 break;
4225                                 }
4226                         }
4227                 /* If peer sent no signature algorithms extension and we
4228                  * have set preferred signature algorithms check we support
4229                  * sha1.
4230                  */
4231                 if (default_nid > 0 && c->conf_sigalgs)
4232                         {
4233                         size_t j;
4234                         const unsigned char *p = c->conf_sigalgs;
4235                         for (j = 0; j < c->conf_sigalgslen; j += 2, p += 2)
4236                                 {
4237                                 if (p[0] == TLSEXT_hash_sha1 && p[1] == rsign)
4238                                         break;
4239                                 }
4240                         if (j == c->conf_sigalgslen)
4241                                 {
4242                                 if (check_flags)
4243                                         goto skip_sigs;
4244                                 else
4245                                         goto end;
4246                                 }
4247                         }
4248                 /* Check signature algorithm of each cert in chain */
4249                 if (!tls1_check_sig_alg(c, x, default_nid))
4250                         {
4251                         if (!check_flags) goto end;
4252                         }
4253                 else
4254                         rv |= CERT_PKEY_EE_SIGNATURE;
4255                 rv |= CERT_PKEY_CA_SIGNATURE;
4256                 for (i = 0; i < sk_X509_num(chain); i++)
4257                         {
4258                         if (!tls1_check_sig_alg(c, sk_X509_value(chain, i),
4259                                                         default_nid))
4260                                 {
4261                                 if (check_flags)
4262                                         {
4263                                         rv &= ~CERT_PKEY_CA_SIGNATURE;
4264                                         break;
4265                                         }
4266                                 else
4267                                         goto end;
4268                                 }
4269                         }
4270                 }
4271         /* Else not TLS 1.2, so mark EE and CA signing algorithms OK */
4272         else if(check_flags)
4273                 rv |= CERT_PKEY_EE_SIGNATURE|CERT_PKEY_CA_SIGNATURE;
4274         skip_sigs:
4275         /* Check cert parameters are consistent */
4276         if (tls1_check_cert_param(s, x, check_flags ? 1 : 2))
4277                 rv |= CERT_PKEY_EE_PARAM;
4278         else if (!check_flags)
4279                 goto end;
4280         if (!s->server)
4281                 rv |= CERT_PKEY_CA_PARAM;
4282         /* In strict mode check rest of chain too */
4283         else if (strict_mode)
4284                 {
4285                 rv |= CERT_PKEY_CA_PARAM;
4286                 for (i = 0; i < sk_X509_num(chain); i++)
4287                         {
4288                         X509 *ca = sk_X509_value(chain, i);
4289                         if (!tls1_check_cert_param(s, ca, 0))
4290                                 {
4291                                 if (check_flags)
4292                                         {
4293                                         rv &= ~CERT_PKEY_CA_PARAM;
4294                                         break;
4295                                         }
4296                                 else
4297                                         goto end;
4298                                 }
4299                         }
4300                 }
4301         if (!s->server && strict_mode)
4302                 {
4303                 STACK_OF(X509_NAME) *ca_dn;
4304                 int check_type = 0;
4305                 switch (pk->type)
4306                         {
4307                 case EVP_PKEY_RSA:
4308                         check_type = TLS_CT_RSA_SIGN;
4309                         break;
4310                 case EVP_PKEY_DSA:
4311                         check_type = TLS_CT_DSS_SIGN;
4312                         break;
4313                 case EVP_PKEY_EC:
4314                         check_type = TLS_CT_ECDSA_SIGN;
4315                         break;
4316                 case EVP_PKEY_DH:
4317                 case EVP_PKEY_DHX:
4318                                 {
4319                                 int cert_type = X509_certificate_type(x, pk);
4320                                 if (cert_type & EVP_PKS_RSA)
4321                                         check_type = TLS_CT_RSA_FIXED_DH;
4322                                 if (cert_type & EVP_PKS_DSA)
4323                                         check_type = TLS_CT_DSS_FIXED_DH;
4324                                 }
4325                         }
4326                 if (check_type)
4327                         {
4328                         const unsigned char *ctypes;
4329                         int ctypelen;
4330                         if (c->ctypes)
4331                                 {
4332                                 ctypes = c->ctypes;
4333                                 ctypelen = (int)c->ctype_num;
4334                                 }
4335                         else
4336                                 {
4337                                 ctypes = (unsigned char *)s->s3->tmp.ctype;
4338                                 ctypelen = s->s3->tmp.ctype_num;
4339                                 }
4340                         for (i = 0; i < ctypelen; i++)
4341                                 {
4342                                 if (ctypes[i] == check_type)
4343                                         {
4344                                         rv |= CERT_PKEY_CERT_TYPE;
4345                                         break;
4346                                         }
4347                                 }
4348                         if (!(rv & CERT_PKEY_CERT_TYPE) && !check_flags)
4349                                 goto end;
4350                         }
4351                 else
4352                         rv |= CERT_PKEY_CERT_TYPE;
4353
4354
4355                 ca_dn = s->s3->tmp.ca_names;
4356
4357                 if (!sk_X509_NAME_num(ca_dn))
4358                         rv |= CERT_PKEY_ISSUER_NAME;
4359
4360                 if (!(rv & CERT_PKEY_ISSUER_NAME))
4361                         {
4362                         if (ssl_check_ca_name(ca_dn, x))
4363                                 rv |= CERT_PKEY_ISSUER_NAME;
4364                         }
4365                 if (!(rv & CERT_PKEY_ISSUER_NAME))
4366                         {
4367                         for (i = 0; i < sk_X509_num(chain); i++)
4368                                 {
4369                                 X509 *xtmp = sk_X509_value(chain, i);
4370                                 if (ssl_check_ca_name(ca_dn, xtmp))
4371                                         {
4372                                         rv |= CERT_PKEY_ISSUER_NAME;
4373                                         break;
4374                                         }
4375                                 }
4376                         }
4377                 if (!check_flags && !(rv & CERT_PKEY_ISSUER_NAME))
4378                         goto end;
4379                 }
4380         else
4381                 rv |= CERT_PKEY_ISSUER_NAME|CERT_PKEY_CERT_TYPE;
4382
4383         if (!check_flags || (rv & check_flags) == check_flags)
4384                 rv |= CERT_PKEY_VALID;
4385
4386         end:
4387
4388         if (TLS1_get_version(s) >= TLS1_2_VERSION)
4389                 {
4390                 if (cpk->valid_flags & CERT_PKEY_EXPLICIT_SIGN)
4391                         rv |= CERT_PKEY_EXPLICIT_SIGN|CERT_PKEY_SIGN;
4392                 else if (cpk->digest)
4393                         rv |= CERT_PKEY_SIGN;
4394                 }
4395         else
4396                 rv |= CERT_PKEY_SIGN|CERT_PKEY_EXPLICIT_SIGN;
4397
4398         /* When checking a CERT_PKEY structure all flags are irrelevant
4399          * if the chain is invalid.
4400          */
4401         if (!check_flags)
4402                 {
4403                 if (rv & CERT_PKEY_VALID)
4404                         cpk->valid_flags = rv;
4405                 else
4406                         {
4407                         /* Preserve explicit sign flag, clear rest */
4408                         cpk->valid_flags &= CERT_PKEY_EXPLICIT_SIGN;
4409                         return 0;
4410                         }
4411                 }
4412         return rv;
4413         }
4414
4415 /* Set validity of certificates in an SSL structure */
4416 void tls1_set_cert_validity(SSL *s)
4417         {
4418         tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_ENC);
4419         tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_SIGN);
4420         tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DSA_SIGN);
4421         tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DH_RSA);
4422         tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DH_DSA);
4423         tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_ECC);
4424         }
4425 /* User level utiity function to check a chain is suitable */
4426 int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain)
4427         {
4428         return tls1_check_chain(s, x, pk, chain, -1);
4429         }
4430
4431 #endif