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