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