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