More tweaks for comments due indent issues
[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                 /*-
1275                  * check for enough space.
1276                  * 4 for the servername type and entension length
1277                  * 2 for servernamelist length
1278                  * 1 for the hostname type
1279                  * 2 for hostname length
1280                  * + hostname length 
1281                  */
1282                    
1283                 if ((lenmax = limit - ret - 9) < 0 
1284                     || (size_str = strlen(s->tlsext_hostname)) > (unsigned long)lenmax) 
1285                         return NULL;
1286                         
1287                 /* extension type and length */
1288                 s2n(TLSEXT_TYPE_server_name,ret); 
1289                 s2n(size_str+5,ret);
1290                 
1291                 /* length of servername list */
1292                 s2n(size_str+3,ret);
1293         
1294                 /* hostname type, length and hostname */
1295                 *(ret++) = (unsigned char) TLSEXT_NAMETYPE_host_name;
1296                 s2n(size_str,ret);
1297                 memcpy(ret, s->tlsext_hostname, size_str);
1298                 ret+=size_str;
1299                 }
1300
1301         /* Add RI if renegotiating */
1302         if (s->renegotiate)
1303           {
1304           int el;
1305           
1306           if(!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0))
1307               {
1308               SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1309               return NULL;
1310               }
1311
1312           if((limit - ret - 4 - el) < 0) return NULL;
1313           
1314           s2n(TLSEXT_TYPE_renegotiate,ret);
1315           s2n(el,ret);
1316
1317           if(!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el))
1318               {
1319               SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1320               return NULL;
1321               }
1322
1323           ret += el;
1324         }
1325
1326 #ifndef OPENSSL_NO_SRP
1327         /* Add SRP username if there is one */
1328         if (s->srp_ctx.login != NULL)
1329                 { /* Add TLS extension SRP username to the Client Hello message */
1330
1331                 int login_len = strlen(s->srp_ctx.login);       
1332                 if (login_len > 255 || login_len == 0)
1333                         {
1334                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1335                         return NULL;
1336                         } 
1337
1338                 /*-
1339                  * check for enough space.
1340                  * 4 for the srp type type and entension length
1341                  * 1 for the srp user identity
1342                  * + srp user identity length 
1343                  */
1344                 if ((limit - ret - 5 - login_len) < 0) return NULL; 
1345
1346                 /* fill in the extension */
1347                 s2n(TLSEXT_TYPE_srp,ret);
1348                 s2n(login_len+1,ret);
1349                 (*ret++) = (unsigned char) login_len;
1350                 memcpy(ret, s->srp_ctx.login, login_len);
1351                 ret+=login_len;
1352                 }
1353 #endif
1354
1355 #ifndef OPENSSL_NO_EC
1356         if (using_ecc)
1357                 {
1358                 /* Add TLS extension ECPointFormats to the ClientHello message */
1359                 long lenmax; 
1360                 const unsigned char *pcurves, *pformats;
1361                 size_t num_curves, num_formats, curves_list_len;
1362
1363                 tls1_get_formatlist(s, &pformats, &num_formats);
1364
1365                 if ((lenmax = limit - ret - 5) < 0) return NULL; 
1366                 if (num_formats > (size_t)lenmax) return NULL;
1367                 if (num_formats > 255)
1368                         {
1369                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1370                         return NULL;
1371                         }
1372                 
1373                 s2n(TLSEXT_TYPE_ec_point_formats,ret);
1374                 /* The point format list has 1-byte length. */
1375                 s2n(num_formats + 1,ret);
1376                 *(ret++) = (unsigned char)num_formats ;
1377                 memcpy(ret, pformats, num_formats);
1378                 ret+=num_formats;
1379
1380                 /* Add TLS extension EllipticCurves to the ClientHello message */
1381                 pcurves = s->tlsext_ellipticcurvelist;
1382                 if (!tls1_get_curvelist(s, 0, &pcurves, &num_curves))
1383                         return NULL;
1384
1385                 if ((lenmax = limit - ret - 6) < 0) return NULL; 
1386                 if (num_curves > (size_t)lenmax / 2) return NULL;
1387                 if (num_curves > 65532 / 2)
1388                         {
1389                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1390                         return NULL;
1391                         }
1392                 curves_list_len = 2*num_curves;
1393                 s2n(TLSEXT_TYPE_elliptic_curves,ret);
1394                 s2n(curves_list_len + 2, ret);
1395                 s2n(curves_list_len, ret);
1396                 memcpy(ret, pcurves, curves_list_len);
1397                 ret+=curves_list_len;
1398                 }
1399 #endif /* OPENSSL_NO_EC */
1400
1401         if (!(SSL_get_options(s) & SSL_OP_NO_TICKET))
1402                 {
1403                 int ticklen;
1404                 if (!s->new_session && s->session && s->session->tlsext_tick)
1405                         ticklen = s->session->tlsext_ticklen;
1406                 else if (s->session && s->tlsext_session_ticket &&
1407                          s->tlsext_session_ticket->data)
1408                         {
1409                         ticklen = s->tlsext_session_ticket->length;
1410                         s->session->tlsext_tick = OPENSSL_malloc(ticklen);
1411                         if (!s->session->tlsext_tick)
1412                                 return NULL;
1413                         memcpy(s->session->tlsext_tick,
1414                                s->tlsext_session_ticket->data,
1415                                ticklen);
1416                         s->session->tlsext_ticklen = ticklen;
1417                         }
1418                 else
1419                         ticklen = 0;
1420                 if (ticklen == 0 && s->tlsext_session_ticket &&
1421                     s->tlsext_session_ticket->data == NULL)
1422                         goto skip_ext;
1423                 /* Check for enough room 2 for extension type, 2 for len
1424                  * rest for ticket
1425                  */
1426                 if ((long)(limit - ret - 4 - ticklen) < 0) return NULL;
1427                 s2n(TLSEXT_TYPE_session_ticket,ret); 
1428                 s2n(ticklen,ret);
1429                 if (ticklen)
1430                         {
1431                         memcpy(ret, s->session->tlsext_tick, ticklen);
1432                         ret += ticklen;
1433                         }
1434                 }
1435                 skip_ext:
1436
1437         if (SSL_USE_SIGALGS(s))
1438                 {
1439                 size_t salglen;
1440                 const unsigned char *salg;
1441                 salglen = tls12_get_psigalgs(s, &salg);
1442                 if ((size_t)(limit - ret) < salglen + 6)
1443                         return NULL; 
1444                 s2n(TLSEXT_TYPE_signature_algorithms,ret);
1445                 s2n(salglen + 2, ret);
1446                 s2n(salglen, ret);
1447                 memcpy(ret, salg, salglen);
1448                 ret += salglen;
1449                 }
1450
1451 #ifdef TLSEXT_TYPE_opaque_prf_input
1452         if (s->s3->client_opaque_prf_input != NULL)
1453                 {
1454                 size_t col = s->s3->client_opaque_prf_input_len;
1455                 
1456                 if ((long)(limit - ret - 6 - col < 0))
1457                         return NULL;
1458                 if (col > 0xFFFD) /* can't happen */
1459                         return NULL;
1460
1461                 s2n(TLSEXT_TYPE_opaque_prf_input, ret); 
1462                 s2n(col + 2, ret);
1463                 s2n(col, ret);
1464                 memcpy(ret, s->s3->client_opaque_prf_input, col);
1465                 ret += col;
1466                 }
1467 #endif
1468
1469         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp)
1470                 {
1471                 int i;
1472                 long extlen, idlen, itmp;
1473                 OCSP_RESPID *id;
1474
1475                 idlen = 0;
1476                 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
1477                         {
1478                         id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
1479                         itmp = i2d_OCSP_RESPID(id, NULL);
1480                         if (itmp <= 0)
1481                                 return NULL;
1482                         idlen += itmp + 2;
1483                         }
1484
1485                 if (s->tlsext_ocsp_exts)
1486                         {
1487                         extlen = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL);
1488                         if (extlen < 0)
1489                                 return NULL;
1490                         }
1491                 else
1492                         extlen = 0;
1493                         
1494                 if ((long)(limit - ret - 7 - extlen - idlen) < 0) return NULL;
1495                 s2n(TLSEXT_TYPE_status_request, ret);
1496                 if (extlen + idlen > 0xFFF0)
1497                         return NULL;
1498                 s2n(extlen + idlen + 5, ret);
1499                 *(ret++) = TLSEXT_STATUSTYPE_ocsp;
1500                 s2n(idlen, ret);
1501                 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
1502                         {
1503                         /* save position of id len */
1504                         unsigned char *q = ret;
1505                         id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
1506                         /* skip over id len */
1507                         ret += 2;
1508                         itmp = i2d_OCSP_RESPID(id, &ret);
1509                         /* write id len */
1510                         s2n(itmp, q);
1511                         }
1512                 s2n(extlen, ret);
1513                 if (extlen > 0)
1514                         i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret);
1515                 }
1516
1517 #ifndef OPENSSL_NO_HEARTBEATS
1518         /* Add Heartbeat extension */
1519         if ((limit - ret - 4 - 1) < 0)
1520                 return NULL;
1521         s2n(TLSEXT_TYPE_heartbeat,ret);
1522         s2n(1,ret);
1523         /*-
1524          * Set mode:
1525          * 1: peer may send requests
1526          * 2: peer not allowed to send requests
1527          */
1528         if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1529                 *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1530         else
1531                 *(ret++) = SSL_TLSEXT_HB_ENABLED;
1532 #endif
1533
1534 #ifndef OPENSSL_NO_NEXTPROTONEG
1535         if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len)
1536                 {
1537                 /* The client advertises an emtpy extension to indicate its
1538                  * support for Next Protocol Negotiation */
1539                 if (limit - ret - 4 < 0)
1540                         return NULL;
1541                 s2n(TLSEXT_TYPE_next_proto_neg,ret);
1542                 s2n(0,ret);
1543                 }
1544 #endif
1545
1546         if (s->alpn_client_proto_list && !s->s3->tmp.finish_md_len)
1547                 {
1548                 if ((size_t)(limit - ret) < 6 + s->alpn_client_proto_list_len)
1549                         return NULL;
1550                 s2n(TLSEXT_TYPE_application_layer_protocol_negotiation,ret);
1551                 s2n(2 + s->alpn_client_proto_list_len,ret);
1552                 s2n(s->alpn_client_proto_list_len,ret);
1553                 memcpy(ret, s->alpn_client_proto_list,
1554                        s->alpn_client_proto_list_len);
1555                 ret += s->alpn_client_proto_list_len;
1556                 }
1557
1558 #ifndef OPENSSL_NO_SRTP
1559         if(SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s))
1560                 {
1561                 int el;
1562
1563                 ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0);
1564                 
1565                 if((limit - ret - 4 - el) < 0) return NULL;
1566
1567                 s2n(TLSEXT_TYPE_use_srtp,ret);
1568                 s2n(el,ret);
1569
1570                 if(ssl_add_clienthello_use_srtp_ext(s, ret, &el, el))
1571                         {
1572                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1573                         return NULL;
1574                         }
1575                 ret += el;
1576                 }
1577 #endif
1578         custom_ext_init(&s->cert->cli_ext);
1579         /* Add custom TLS Extensions to ClientHello */
1580         if (!custom_ext_add(s, 0, &ret, limit, al))
1581                 return NULL;
1582
1583         /* Add padding to workaround bugs in F5 terminators.
1584          * See https://tools.ietf.org/html/draft-agl-tls-padding-03
1585          *
1586          * NB: because this code works out the length of all existing
1587          * extensions it MUST always appear last.
1588          */
1589         if (s->options & SSL_OP_TLSEXT_PADDING)
1590                 {
1591                 int hlen = ret - (unsigned char *)s->init_buf->data;
1592                 /* The code in s23_clnt.c to build ClientHello messages
1593                  * includes the 5-byte record header in the buffer, while
1594                  * the code in s3_clnt.c does not.
1595                  */
1596                 if (s->state == SSL23_ST_CW_CLNT_HELLO_A)
1597                         hlen -= 5;
1598                 if (hlen > 0xff && hlen < 0x200)
1599                         {
1600                         hlen = 0x200 - hlen;
1601                         if (hlen >= 4)
1602                                 hlen -= 4;
1603                         else
1604                                 hlen = 0;
1605
1606                         s2n(TLSEXT_TYPE_padding, ret);
1607                         s2n(hlen, ret);
1608                         memset(ret, 0, hlen);
1609                         ret += hlen;
1610                         }
1611                 }
1612
1613         if ((extdatalen = ret-orig-2)== 0) 
1614                 return orig;
1615
1616         s2n(extdatalen, orig);
1617         return ret;
1618         }
1619
1620 unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *buf, unsigned char *limit, int *al)
1621         {
1622         int extdatalen=0;
1623         unsigned char *orig = buf;
1624         unsigned char *ret = buf;
1625 #ifndef OPENSSL_NO_NEXTPROTONEG
1626         int next_proto_neg_seen;
1627 #endif
1628 #ifndef OPENSSL_NO_EC
1629         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1630         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1631         int using_ecc = (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA);
1632         using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL);
1633 #endif
1634         /* don't add extensions for SSLv3, unless doing secure renegotiation */
1635         if (s->version == SSL3_VERSION && !s->s3->send_connection_binding)
1636                 return orig;
1637         
1638         ret+=2;
1639         if (ret>=limit) return NULL; /* this really never occurs, but ... */
1640
1641         if (!s->hit && s->servername_done == 1 && s->session->tlsext_hostname != NULL)
1642                 { 
1643                 if ((long)(limit - ret - 4) < 0) return NULL; 
1644
1645                 s2n(TLSEXT_TYPE_server_name,ret);
1646                 s2n(0,ret);
1647                 }
1648
1649         if(s->s3->send_connection_binding)
1650         {
1651           int el;
1652           
1653           if(!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0))
1654               {
1655               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1656               return NULL;
1657               }
1658
1659           if((limit - ret - 4 - el) < 0) return NULL;
1660           
1661           s2n(TLSEXT_TYPE_renegotiate,ret);
1662           s2n(el,ret);
1663
1664           if(!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el))
1665               {
1666               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1667               return NULL;
1668               }
1669
1670           ret += el;
1671         }
1672
1673 #ifndef OPENSSL_NO_EC
1674         if (using_ecc)
1675                 {
1676                 const unsigned char *plist;
1677                 size_t plistlen;
1678                 /* Add TLS extension ECPointFormats to the ServerHello message */
1679                 long lenmax; 
1680
1681                 tls1_get_formatlist(s, &plist, &plistlen);
1682
1683                 if ((lenmax = limit - ret - 5) < 0) return NULL; 
1684                 if (plistlen > (size_t)lenmax) return NULL;
1685                 if (plistlen > 255)
1686                         {
1687                         SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1688                         return NULL;
1689                         }
1690                 
1691                 s2n(TLSEXT_TYPE_ec_point_formats,ret);
1692                 s2n(plistlen + 1,ret);
1693                 *(ret++) = (unsigned char) plistlen;
1694                 memcpy(ret, plist, plistlen);
1695                 ret+=plistlen;
1696
1697                 }
1698         /* Currently the server should not respond with a SupportedCurves extension */
1699 #endif /* OPENSSL_NO_EC */
1700
1701         if (s->tlsext_ticket_expected
1702                 && !(SSL_get_options(s) & SSL_OP_NO_TICKET)) 
1703                 { 
1704                 if ((long)(limit - ret - 4) < 0) return NULL; 
1705                 s2n(TLSEXT_TYPE_session_ticket,ret);
1706                 s2n(0,ret);
1707                 }
1708
1709         if (s->tlsext_status_expected)
1710                 { 
1711                 if ((long)(limit - ret - 4) < 0) return NULL; 
1712                 s2n(TLSEXT_TYPE_status_request,ret);
1713                 s2n(0,ret);
1714                 }
1715
1716 #ifdef TLSEXT_TYPE_opaque_prf_input
1717         if (s->s3->server_opaque_prf_input != NULL)
1718                 {
1719                 size_t sol = s->s3->server_opaque_prf_input_len;
1720                 
1721                 if ((long)(limit - ret - 6 - sol) < 0)
1722                         return NULL;
1723                 if (sol > 0xFFFD) /* can't happen */
1724                         return NULL;
1725
1726                 s2n(TLSEXT_TYPE_opaque_prf_input, ret); 
1727                 s2n(sol + 2, ret);
1728                 s2n(sol, ret);
1729                 memcpy(ret, s->s3->server_opaque_prf_input, sol);
1730                 ret += sol;
1731                 }
1732 #endif
1733
1734 #ifndef OPENSSL_NO_SRTP
1735         if(SSL_IS_DTLS(s) && s->srtp_profile)
1736                 {
1737                 int el;
1738
1739                 ssl_add_serverhello_use_srtp_ext(s, 0, &el, 0);
1740                 
1741                 if((limit - ret - 4 - el) < 0) return NULL;
1742
1743                 s2n(TLSEXT_TYPE_use_srtp,ret);
1744                 s2n(el,ret);
1745
1746                 if(ssl_add_serverhello_use_srtp_ext(s, ret, &el, el))
1747                         {
1748                         SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1749                         return NULL;
1750                         }
1751                 ret+=el;
1752                 }
1753 #endif
1754
1755         if (((s->s3->tmp.new_cipher->id & 0xFFFF)==0x80 || (s->s3->tmp.new_cipher->id & 0xFFFF)==0x81) 
1756                 && (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG))
1757                 { const unsigned char cryptopro_ext[36] = {
1758                         0xfd, 0xe8, /*65000*/
1759                         0x00, 0x20, /*32 bytes length*/
1760                         0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85, 
1761                         0x03,   0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06, 
1762                         0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08, 
1763                         0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17};
1764                         if (limit-ret<36) return NULL;
1765                         memcpy(ret,cryptopro_ext,36);
1766                         ret+=36;
1767
1768                 }
1769
1770 #ifndef OPENSSL_NO_HEARTBEATS
1771         /* Add Heartbeat extension if we've received one */
1772         if (s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED)
1773                 {
1774                 if ((limit - ret - 4 - 1) < 0)
1775                         return NULL;
1776                 s2n(TLSEXT_TYPE_heartbeat,ret);
1777                 s2n(1,ret);
1778                 /*-
1779                  * Set mode:
1780                  * 1: peer may send requests
1781                  * 2: peer not allowed to send requests
1782                  */
1783                 if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1784                         *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1785                 else
1786                         *(ret++) = SSL_TLSEXT_HB_ENABLED;
1787
1788                 }
1789 #endif
1790
1791 #ifndef OPENSSL_NO_NEXTPROTONEG
1792         next_proto_neg_seen = s->s3->next_proto_neg_seen;
1793         s->s3->next_proto_neg_seen = 0;
1794         if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb)
1795                 {
1796                 const unsigned char *npa;
1797                 unsigned int npalen;
1798                 int r;
1799
1800                 r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen, s->ctx->next_protos_advertised_cb_arg);
1801                 if (r == SSL_TLSEXT_ERR_OK)
1802                         {
1803                         if ((long)(limit - ret - 4 - npalen) < 0) return NULL;
1804                         s2n(TLSEXT_TYPE_next_proto_neg,ret);
1805                         s2n(npalen,ret);
1806                         memcpy(ret, npa, npalen);
1807                         ret += npalen;
1808                         s->s3->next_proto_neg_seen = 1;
1809                         }
1810                 }
1811 #endif
1812         if (!custom_ext_add(s, 1, &ret, limit, al))
1813                 return NULL;
1814
1815         if (s->s3->alpn_selected)
1816                 {
1817                 const unsigned char *selected = s->s3->alpn_selected;
1818                 unsigned len = s->s3->alpn_selected_len;
1819
1820                 if ((long)(limit - ret - 4 - 2 - 1 - len) < 0)
1821                         return NULL;
1822                 s2n(TLSEXT_TYPE_application_layer_protocol_negotiation,ret);
1823                 s2n(3 + len,ret);
1824                 s2n(1 + len,ret);
1825                 *ret++ = len;
1826                 memcpy(ret, selected, len);
1827                 ret += len;
1828                 }
1829
1830         if ((extdatalen = ret-orig-2)== 0) 
1831                 return orig;
1832
1833         s2n(extdatalen, orig);
1834         return ret;
1835         }
1836
1837 #ifndef OPENSSL_NO_EC
1838 /*-
1839  * ssl_check_for_safari attempts to fingerprint Safari using OS X
1840  * SecureTransport using the TLS extension block in |d|, of length |n|.
1841  * Safari, since 10.6, sends exactly these extensions, in this order:
1842  *   SNI,
1843  *   elliptic_curves
1844  *   ec_point_formats
1845  *
1846  * We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,
1847  * but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.
1848  * Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from
1849  * 10.8..10.8.3 (which don't work).
1850  */
1851 static void ssl_check_for_safari(SSL *s, const unsigned char *data, const unsigned char *d, int n) {
1852         unsigned short type, size;
1853         static const unsigned char kSafariExtensionsBlock[] = {
1854                 0x00, 0x0a,  /* elliptic_curves extension */
1855                 0x00, 0x08,  /* 8 bytes */
1856                 0x00, 0x06,  /* 6 bytes of curve ids */
1857                 0x00, 0x17,  /* P-256 */
1858                 0x00, 0x18,  /* P-384 */
1859                 0x00, 0x19,  /* P-521 */
1860
1861                 0x00, 0x0b,  /* ec_point_formats */
1862                 0x00, 0x02,  /* 2 bytes */
1863                 0x01,        /* 1 point format */
1864                 0x00,        /* uncompressed */
1865         };
1866
1867         /* The following is only present in TLS 1.2 */
1868         static const unsigned char kSafariTLS12ExtensionsBlock[] = {
1869                 0x00, 0x0d,  /* signature_algorithms */
1870                 0x00, 0x0c,  /* 12 bytes */
1871                 0x00, 0x0a,  /* 10 bytes */
1872                 0x05, 0x01,  /* SHA-384/RSA */
1873                 0x04, 0x01,  /* SHA-256/RSA */
1874                 0x02, 0x01,  /* SHA-1/RSA */
1875                 0x04, 0x03,  /* SHA-256/ECDSA */
1876                 0x02, 0x03,  /* SHA-1/ECDSA */
1877         };
1878
1879         if (data >= (d+n-2))
1880                 return;
1881         data += 2;
1882
1883         if (data > (d+n-4))
1884                 return;
1885         n2s(data,type);
1886         n2s(data,size);
1887
1888         if (type != TLSEXT_TYPE_server_name)
1889                 return;
1890
1891         if (data+size > d+n)
1892                 return;
1893         data += size;
1894
1895         if (TLS1_get_client_version(s) >= TLS1_2_VERSION)
1896                 {
1897                 const size_t len1 = sizeof(kSafariExtensionsBlock);
1898                 const size_t len2 = sizeof(kSafariTLS12ExtensionsBlock);
1899
1900                 if (data + len1 + len2 != d+n)
1901                         return;
1902                 if (memcmp(data, kSafariExtensionsBlock, len1) != 0)
1903                         return;
1904                 if (memcmp(data + len1, kSafariTLS12ExtensionsBlock, len2) != 0)
1905                         return;
1906                 }
1907         else
1908                 {
1909                 const size_t len = sizeof(kSafariExtensionsBlock);
1910
1911                 if (data + len != d+n)
1912                         return;
1913                 if (memcmp(data, kSafariExtensionsBlock, len) != 0)
1914                         return;
1915                 }
1916
1917         s->s3->is_probably_safari = 1;
1918 }
1919 #endif /* !OPENSSL_NO_EC */
1920
1921 /* tls1_alpn_handle_client_hello is called to process the ALPN extension in a
1922  * ClientHello.
1923  *   data: the contents of the extension, not including the type and length.
1924  *   data_len: the number of bytes in |data|
1925  *   al: a pointer to the alert value to send in the event of a non-zero
1926  *       return.
1927  *
1928  *   returns: 0 on success. */
1929 static int tls1_alpn_handle_client_hello(SSL *s, const unsigned char *data,
1930                                          unsigned data_len, int *al)
1931         {
1932         unsigned i;
1933         unsigned proto_len;
1934         const unsigned char *selected;
1935         unsigned char selected_len;
1936         int r;
1937
1938         if (s->ctx->alpn_select_cb == NULL)
1939                 return 0;
1940
1941         if (data_len < 2)
1942                 goto parse_error;
1943
1944         /* data should contain a uint16 length followed by a series of 8-bit,
1945          * length-prefixed strings. */
1946         i = ((unsigned) data[0]) << 8 |
1947             ((unsigned) data[1]);
1948         data_len -= 2;
1949         data += 2;
1950         if (data_len != i)
1951                 goto parse_error;
1952
1953         if (data_len < 2)
1954                 goto parse_error;
1955
1956         for (i = 0; i < data_len;)
1957                 {
1958                 proto_len = data[i];
1959                 i++;
1960
1961                 if (proto_len == 0)
1962                         goto parse_error;
1963
1964                 if (i + proto_len < i || i + proto_len > data_len)
1965                         goto parse_error;
1966
1967                 i += proto_len;
1968                 }
1969
1970         r = s->ctx->alpn_select_cb(s, &selected, &selected_len, data, data_len,
1971                                    s->ctx->alpn_select_cb_arg);
1972         if (r == SSL_TLSEXT_ERR_OK) {
1973                 if (s->s3->alpn_selected)
1974                         OPENSSL_free(s->s3->alpn_selected);
1975                 s->s3->alpn_selected = OPENSSL_malloc(selected_len);
1976                 if (!s->s3->alpn_selected)
1977                         {
1978                         *al = SSL_AD_INTERNAL_ERROR;
1979                         return -1;
1980                         }
1981                 memcpy(s->s3->alpn_selected, selected, selected_len);
1982                 s->s3->alpn_selected_len = selected_len;
1983         }
1984         return 0;
1985
1986 parse_error:
1987         *al = SSL_AD_DECODE_ERROR;
1988         return -1;
1989         }
1990
1991 static int ssl_scan_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al) 
1992         {       
1993         unsigned short type;
1994         unsigned short size;
1995         unsigned short len;
1996         unsigned char *data = *p;
1997         int renegotiate_seen = 0;
1998
1999         s->servername_done = 0;
2000         s->tlsext_status_type = -1;
2001 #ifndef OPENSSL_NO_NEXTPROTONEG
2002         s->s3->next_proto_neg_seen = 0;
2003 #endif
2004
2005         if (s->s3->alpn_selected)
2006                 {
2007                 OPENSSL_free(s->s3->alpn_selected);
2008                 s->s3->alpn_selected = NULL;
2009                 }
2010
2011 #ifndef OPENSSL_NO_HEARTBEATS
2012         s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
2013                                SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
2014 #endif
2015
2016 #ifndef OPENSSL_NO_EC
2017         if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
2018                 ssl_check_for_safari(s, data, d, n);
2019 #endif /* !OPENSSL_NO_EC */
2020
2021         /* Clear any signature algorithms extension received */
2022         if (s->cert->peer_sigalgs)
2023                 {
2024                 OPENSSL_free(s->cert->peer_sigalgs);
2025                 s->cert->peer_sigalgs = NULL;
2026                 }
2027
2028 #ifndef OPENSSL_NO_SRP
2029         if (s->srp_ctx.login != NULL)
2030                 {
2031                 OPENSSL_free(s->srp_ctx.login);
2032                 s->srp_ctx.login = NULL;
2033                 }
2034 #endif
2035
2036         s->srtp_profile = NULL;
2037
2038         if (data >= (d+n-2))
2039                 goto ri_check;
2040         n2s(data,len);
2041
2042         if (data > (d+n-len)) 
2043                 goto ri_check;
2044
2045         while (data <= (d+n-4))
2046                 {
2047                 n2s(data,type);
2048                 n2s(data,size);
2049
2050                 if (data+size > (d+n))
2051                         goto ri_check;
2052 #if 0
2053                 fprintf(stderr,"Received extension type %d size %d\n",type,size);
2054 #endif
2055                 if (s->tlsext_debug_cb)
2056                         s->tlsext_debug_cb(s, 0, type, data, size,
2057                                                 s->tlsext_debug_arg);
2058 /*-
2059  * The servername extension is treated as follows:
2060  *
2061  * - Only the hostname type is supported with a maximum length of 255.
2062  * - The servername is rejected if too long or if it contains zeros,
2063  *   in which case an fatal alert is generated.
2064  * - The servername field is maintained together with the session cache.
2065  * - When a session is resumed, the servername call back invoked in order
2066  *   to allow the application to position itself to the right context. 
2067  * - The servername is acknowledged if it is new for a session or when 
2068  *   it is identical to a previously used for the same session. 
2069  *   Applications can control the behaviour.  They can at any time
2070  *   set a 'desirable' servername for a new SSL object. This can be the
2071  *   case for example with HTTPS when a Host: header field is received and
2072  *   a renegotiation is requested. In this case, a possible servername
2073  *   presented in the new client hello is only acknowledged if it matches
2074  *   the value of the Host: field. 
2075  * - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
2076  *   if they provide for changing an explicit servername context for the 
2077  *   session, i.e. when the session has been established with a servername 
2078  *   extension. 
2079  * - On session reconnect, the servername extension may be absent. 
2080  *
2081  */      
2082
2083                 if (type == TLSEXT_TYPE_server_name)
2084                         {
2085                         unsigned char *sdata;
2086                         int servname_type;
2087                         int dsize; 
2088                 
2089                         if (size < 2) 
2090                                 {
2091                                 *al = SSL_AD_DECODE_ERROR;
2092                                 return 0;
2093                                 }
2094                         n2s(data,dsize);  
2095                         size -= 2;
2096                         if (dsize > size  ) 
2097                                 {
2098                                 *al = SSL_AD_DECODE_ERROR;
2099                                 return 0;
2100                                 } 
2101
2102                         sdata = data;
2103                         while (dsize > 3) 
2104                                 {
2105                                 servname_type = *(sdata++); 
2106                                 n2s(sdata,len);
2107                                 dsize -= 3;
2108
2109                                 if (len > dsize) 
2110                                         {
2111                                         *al = SSL_AD_DECODE_ERROR;
2112                                         return 0;
2113                                         }
2114                                 if (s->servername_done == 0)
2115                                 switch (servname_type)
2116                                         {
2117                                 case TLSEXT_NAMETYPE_host_name:
2118                                         if (!s->hit)
2119                                                 {
2120                                                 if(s->session->tlsext_hostname)
2121                                                         {
2122                                                         *al = SSL_AD_DECODE_ERROR;
2123                                                         return 0;
2124                                                         }
2125                                                 if (len > TLSEXT_MAXLEN_host_name)
2126                                                         {
2127                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
2128                                                         return 0;
2129                                                         }
2130                                                 if ((s->session->tlsext_hostname = OPENSSL_malloc(len+1)) == NULL)
2131                                                         {
2132                                                         *al = TLS1_AD_INTERNAL_ERROR;
2133                                                         return 0;
2134                                                         }
2135                                                 memcpy(s->session->tlsext_hostname, sdata, len);
2136                                                 s->session->tlsext_hostname[len]='\0';
2137                                                 if (strlen(s->session->tlsext_hostname) != len) {
2138                                                         OPENSSL_free(s->session->tlsext_hostname);
2139                                                         s->session->tlsext_hostname = NULL;
2140                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
2141                                                         return 0;
2142                                                 }
2143                                                 s->servername_done = 1; 
2144
2145                                                 }
2146                                         else 
2147                                                 s->servername_done = s->session->tlsext_hostname
2148                                                         && strlen(s->session->tlsext_hostname) == len 
2149                                                         && strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0;
2150                                         
2151                                         break;
2152
2153                                 default:
2154                                         break;
2155                                         }
2156                                  
2157                                 dsize -= len;
2158                                 }
2159                         if (dsize != 0) 
2160                                 {
2161                                 *al = SSL_AD_DECODE_ERROR;
2162                                 return 0;
2163                                 }
2164
2165                         }
2166 #ifndef OPENSSL_NO_SRP
2167                 else if (type == TLSEXT_TYPE_srp)
2168                         {
2169                         if (size <= 0 || ((len = data[0])) != (size -1))
2170                                 {
2171                                 *al = SSL_AD_DECODE_ERROR;
2172                                 return 0;
2173                                 }
2174                         if (s->srp_ctx.login != NULL)
2175                                 {
2176                                 *al = SSL_AD_DECODE_ERROR;
2177                                 return 0;
2178                                 }
2179                         if ((s->srp_ctx.login = OPENSSL_malloc(len+1)) == NULL)
2180                                 return -1;
2181                         memcpy(s->srp_ctx.login, &data[1], len);
2182                         s->srp_ctx.login[len]='\0';
2183   
2184                         if (strlen(s->srp_ctx.login) != len) 
2185                                 {
2186                                 *al = SSL_AD_DECODE_ERROR;
2187                                 return 0;
2188                                 }
2189                         }
2190 #endif
2191
2192 #ifndef OPENSSL_NO_EC
2193                 else if (type == TLSEXT_TYPE_ec_point_formats)
2194                         {
2195                         unsigned char *sdata = data;
2196                         int ecpointformatlist_length = *(sdata++);
2197
2198                         if (ecpointformatlist_length != size - 1 || 
2199                                 ecpointformatlist_length < 1)
2200                                 {
2201                                 *al = TLS1_AD_DECODE_ERROR;
2202                                 return 0;
2203                                 }
2204                         if (!s->hit)
2205                                 {
2206                                 if(s->session->tlsext_ecpointformatlist)
2207                                         {
2208                                         OPENSSL_free(s->session->tlsext_ecpointformatlist);
2209                                         s->session->tlsext_ecpointformatlist = NULL;
2210                                         }
2211                                 s->session->tlsext_ecpointformatlist_length = 0;
2212                                 if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
2213                                         {
2214                                         *al = TLS1_AD_INTERNAL_ERROR;
2215                                         return 0;
2216                                         }
2217                                 s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
2218                                 memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
2219                                 }
2220 #if 0
2221                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ", s->session->tlsext_ecpointformatlist_length);
2222                         sdata = s->session->tlsext_ecpointformatlist;
2223                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2224                                 fprintf(stderr,"%i ",*(sdata++));
2225                         fprintf(stderr,"\n");
2226 #endif
2227                         }
2228                 else if (type == TLSEXT_TYPE_elliptic_curves)
2229                         {
2230                         unsigned char *sdata = data;
2231                         int ellipticcurvelist_length = (*(sdata++) << 8);
2232                         ellipticcurvelist_length += (*(sdata++));
2233
2234                         if (ellipticcurvelist_length != size - 2 ||
2235                                 ellipticcurvelist_length < 1 ||
2236                                 /* Each NamedCurve is 2 bytes. */
2237                                 ellipticcurvelist_length & 1)
2238                                 {
2239                                 *al = TLS1_AD_DECODE_ERROR;
2240                                 return 0;
2241                                 }
2242                         if (!s->hit)
2243                                 {
2244                                 if(s->session->tlsext_ellipticcurvelist)
2245                                         {
2246                                         *al = TLS1_AD_DECODE_ERROR;
2247                                         return 0;
2248                                         }
2249                                 s->session->tlsext_ellipticcurvelist_length = 0;
2250                                 if ((s->session->tlsext_ellipticcurvelist = OPENSSL_malloc(ellipticcurvelist_length)) == NULL)
2251                                         {
2252                                         *al = TLS1_AD_INTERNAL_ERROR;
2253                                         return 0;
2254                                         }
2255                                 s->session->tlsext_ellipticcurvelist_length = ellipticcurvelist_length;
2256                                 memcpy(s->session->tlsext_ellipticcurvelist, sdata, ellipticcurvelist_length);
2257                                 }
2258 #if 0
2259                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ", s->session->tlsext_ellipticcurvelist_length);
2260                         sdata = s->session->tlsext_ellipticcurvelist;
2261                         for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++)
2262                                 fprintf(stderr,"%i ",*(sdata++));
2263                         fprintf(stderr,"\n");
2264 #endif
2265                         }
2266 #endif /* OPENSSL_NO_EC */
2267 #ifdef TLSEXT_TYPE_opaque_prf_input
2268                 else if (type == TLSEXT_TYPE_opaque_prf_input)
2269                         {
2270                         unsigned char *sdata = data;
2271
2272                         if (size < 2)
2273                                 {
2274                                 *al = SSL_AD_DECODE_ERROR;
2275                                 return 0;
2276                                 }
2277                         n2s(sdata, s->s3->client_opaque_prf_input_len);
2278                         if (s->s3->client_opaque_prf_input_len != size - 2)
2279                                 {
2280                                 *al = SSL_AD_DECODE_ERROR;
2281                                 return 0;
2282                                 }
2283
2284                         if (s->s3->client_opaque_prf_input != NULL)
2285                                 {
2286                                 /* shouldn't really happen */
2287                                 OPENSSL_free(s->s3->client_opaque_prf_input);
2288                                 }
2289                                 
2290                         /* dummy byte just to get non-NULL */
2291                         if (s->s3->client_opaque_prf_input_len == 0)
2292                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1);
2293                         else
2294                                 s->s3->client_opaque_prf_input = BUF_memdup(sdata, s->s3->client_opaque_prf_input_len);
2295                         if (s->s3->client_opaque_prf_input == NULL)
2296                                 {
2297                                 *al = TLS1_AD_INTERNAL_ERROR;
2298                                 return 0;
2299                                 }
2300                         }
2301 #endif
2302                 else if (type == TLSEXT_TYPE_session_ticket)
2303                         {
2304                         if (s->tls_session_ticket_ext_cb &&
2305                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
2306                                 {
2307                                 *al = TLS1_AD_INTERNAL_ERROR;
2308                                 return 0;
2309                                 }
2310                         }
2311                 else if (type == TLSEXT_TYPE_renegotiate)
2312                         {
2313                         if(!ssl_parse_clienthello_renegotiate_ext(s, data, size, al))
2314                                 return 0;
2315                         renegotiate_seen = 1;
2316                         }
2317                 else if (type == TLSEXT_TYPE_signature_algorithms)
2318                         {
2319                         int dsize;
2320                         if (s->cert->peer_sigalgs || size < 2) 
2321                                 {
2322                                 *al = SSL_AD_DECODE_ERROR;
2323                                 return 0;
2324                                 }
2325                         n2s(data,dsize);
2326                         size -= 2;
2327                         if (dsize != size || dsize & 1 || !dsize) 
2328                                 {
2329                                 *al = SSL_AD_DECODE_ERROR;
2330                                 return 0;
2331                                 }
2332                         if (!tls1_save_sigalgs(s, data, dsize))
2333                                 {
2334                                 *al = SSL_AD_DECODE_ERROR;
2335                                 return 0;
2336                                 }
2337                         }
2338                 else if (type == TLSEXT_TYPE_status_request)
2339                         {
2340                 
2341                         if (size < 5) 
2342                                 {
2343                                 *al = SSL_AD_DECODE_ERROR;
2344                                 return 0;
2345                                 }
2346
2347                         s->tlsext_status_type = *data++;
2348                         size--;
2349                         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp)
2350                                 {
2351                                 const unsigned char *sdata;
2352                                 int dsize;
2353                                 /* Read in responder_id_list */
2354                                 n2s(data,dsize);
2355                                 size -= 2;
2356                                 if (dsize > size  ) 
2357                                         {
2358                                         *al = SSL_AD_DECODE_ERROR;
2359                                         return 0;
2360                                         }
2361                                 while (dsize > 0)
2362                                         {
2363                                         OCSP_RESPID *id;
2364                                         int idsize;
2365                                         if (dsize < 4)
2366                                                 {
2367                                                 *al = SSL_AD_DECODE_ERROR;
2368                                                 return 0;
2369                                                 }
2370                                         n2s(data, idsize);
2371                                         dsize -= 2 + idsize;
2372                                         size -= 2 + idsize;
2373                                         if (dsize < 0)
2374                                                 {
2375                                                 *al = SSL_AD_DECODE_ERROR;
2376                                                 return 0;
2377                                                 }
2378                                         sdata = data;
2379                                         data += idsize;
2380                                         id = d2i_OCSP_RESPID(NULL,
2381                                                                 &sdata, idsize);
2382                                         if (!id)
2383                                                 {
2384                                                 *al = SSL_AD_DECODE_ERROR;
2385                                                 return 0;
2386                                                 }
2387                                         if (data != sdata)
2388                                                 {
2389                                                 OCSP_RESPID_free(id);
2390                                                 *al = SSL_AD_DECODE_ERROR;
2391                                                 return 0;
2392                                                 }
2393                                         if (!s->tlsext_ocsp_ids
2394                                                 && !(s->tlsext_ocsp_ids =
2395                                                 sk_OCSP_RESPID_new_null()))
2396                                                 {
2397                                                 OCSP_RESPID_free(id);
2398                                                 *al = SSL_AD_INTERNAL_ERROR;
2399                                                 return 0;
2400                                                 }
2401                                         if (!sk_OCSP_RESPID_push(
2402                                                         s->tlsext_ocsp_ids, id))
2403                                                 {
2404                                                 OCSP_RESPID_free(id);
2405                                                 *al = SSL_AD_INTERNAL_ERROR;
2406                                                 return 0;
2407                                                 }
2408                                         }
2409
2410                                 /* Read in request_extensions */
2411                                 if (size < 2)
2412                                         {
2413                                         *al = SSL_AD_DECODE_ERROR;
2414                                         return 0;
2415                                         }
2416                                 n2s(data,dsize);
2417                                 size -= 2;
2418                                 if (dsize != size)
2419                                         {
2420                                         *al = SSL_AD_DECODE_ERROR;
2421                                         return 0;
2422                                         }
2423                                 sdata = data;
2424                                 if (dsize > 0)
2425                                         {
2426                                         if (s->tlsext_ocsp_exts)
2427                                                 {
2428                                                 sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
2429                                                                            X509_EXTENSION_free);
2430                                                 }
2431
2432                                         s->tlsext_ocsp_exts =
2433                                                 d2i_X509_EXTENSIONS(NULL,
2434                                                         &sdata, dsize);
2435                                         if (!s->tlsext_ocsp_exts
2436                                                 || (data + dsize != sdata))
2437                                                 {
2438                                                 *al = SSL_AD_DECODE_ERROR;
2439                                                 return 0;
2440                                                 }
2441                                         }
2442                                 }
2443                                 /* We don't know what to do with any other type
2444                                 * so ignore it.
2445                                 */
2446                                 else
2447                                         s->tlsext_status_type = -1;
2448                         }
2449 #ifndef OPENSSL_NO_HEARTBEATS
2450                 else if (type == TLSEXT_TYPE_heartbeat)
2451                         {
2452                         switch(data[0])
2453                                 {
2454                                 case 0x01:      /* Client allows us to send HB requests */
2455                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2456                                                         break;
2457                                 case 0x02:      /* Client doesn't accept HB requests */
2458                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2459                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2460                                                         break;
2461                                 default:        *al = SSL_AD_ILLEGAL_PARAMETER;
2462                                                         return 0;
2463                                 }
2464                         }
2465 #endif
2466 #ifndef OPENSSL_NO_NEXTPROTONEG
2467                 else if (type == TLSEXT_TYPE_next_proto_neg &&
2468                          s->s3->tmp.finish_md_len == 0 &&
2469                          s->s3->alpn_selected == NULL)
2470                         {
2471                         /*-
2472                          * We shouldn't accept this extension on a
2473                          * renegotiation.
2474                          *
2475                          * s->new_session will be set on renegotiation, but we
2476                          * probably shouldn't rely that it couldn't be set on
2477                          * the initial renegotation too in certain cases (when
2478                          * there's some other reason to disallow resuming an
2479                          * earlier session -- the current code won't be doing
2480                          * anything like that, but this might change).
2481                          *
2482                          * A valid sign that there's been a previous handshake
2483                          * in this connection is if s->s3->tmp.finish_md_len >
2484                          * 0.  (We are talking about a check that will happen
2485                          * in the Hello protocol round, well before a new
2486                          * Finished message could have been computed.) 
2487                          */
2488                         s->s3->next_proto_neg_seen = 1;
2489                         }
2490 #endif
2491
2492                 else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation &&
2493                          s->ctx->alpn_select_cb &&
2494                          s->s3->tmp.finish_md_len == 0)
2495                         {
2496                         if (tls1_alpn_handle_client_hello(s, data, size, al) != 0)
2497                                 return 0;
2498 #ifndef OPENSSL_NO_NEXTPROTONEG
2499                         /* ALPN takes precedence over NPN. */
2500                         s->s3->next_proto_neg_seen = 0;
2501 #endif
2502                         }
2503
2504                 /* session ticket processed earlier */
2505 #ifndef OPENSSL_NO_SRTP
2506                 else if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s)
2507                                 && type == TLSEXT_TYPE_use_srtp)
2508                         {
2509                         if(ssl_parse_clienthello_use_srtp_ext(s, data, size,
2510                                                               al))
2511                                 return 0;
2512                         }
2513 #endif
2514
2515                 data+=size;
2516                 }
2517
2518         *p = data;
2519
2520         ri_check:
2521
2522         /* Need RI if renegotiating */
2523
2524         if (!renegotiate_seen && s->renegotiate &&
2525                 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
2526                 {
2527                 *al = SSL_AD_HANDSHAKE_FAILURE;
2528                 SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
2529                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2530                 return 0;
2531                 }
2532
2533         return 1;
2534         }
2535
2536 /*
2537  * Parse any custom extensions found.  "data" is the start of the extension data
2538  * and "limit" is the end of the record. TODO: add strict syntax checking.
2539  */
2540
2541 static int ssl_scan_clienthello_custom_tlsext(SSL *s, const unsigned char *data, const unsigned char *limit, int *al) 
2542         {       
2543         unsigned short type, size, len;
2544         /* If resumed session or no custom extensions nothing to do */
2545         if (s->hit || s->cert->srv_ext.meths_count == 0)
2546                 return 1;
2547
2548         if (data >= limit - 2)
2549                 return 1;
2550         n2s(data, len);
2551
2552         if (data > limit - len) 
2553                 return 1;
2554
2555         while (data <= limit - 4)
2556                 {
2557                 n2s(data, type);
2558                 n2s(data, size);
2559
2560                 if (data+size > limit)
2561                         return 1;
2562                 if (custom_ext_parse(s, 1 /* server */, type, data, size, al) <= 0)
2563                         return 0;
2564
2565                 data+=size;
2566                 }
2567
2568         return 1;
2569         }
2570
2571 int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n) 
2572         {
2573         int al = -1;
2574         unsigned char *ptmp = *p;
2575         /*
2576          * Internally supported extensions are parsed first so SNI can be handled
2577          * before custom extensions. An application processing SNI will typically
2578          * switch the parent context using SSL_set_SSL_CTX and custom extensions
2579          * need to be handled by the new SSL_CTX structure.
2580          */
2581         if (ssl_scan_clienthello_tlsext(s, p, d, n, &al) <= 0) 
2582                 {
2583                 ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2584                 return 0;
2585                 }
2586
2587         if (ssl_check_clienthello_tlsext_early(s) <= 0) 
2588                 {
2589                 SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT,SSL_R_CLIENTHELLO_TLSEXT);
2590                 return 0;
2591                 }
2592
2593         custom_ext_init(&s->cert->srv_ext);
2594         if (ssl_scan_clienthello_custom_tlsext(s, ptmp, d + n, &al) <= 0) 
2595                 {
2596                 ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2597                 return 0;
2598                 }
2599
2600         return 1;
2601 }
2602
2603 #ifndef OPENSSL_NO_NEXTPROTONEG
2604 /* ssl_next_proto_validate validates a Next Protocol Negotiation block. No
2605  * elements of zero length are allowed and the set of elements must exactly fill
2606  * the length of the block. */
2607 static char ssl_next_proto_validate(unsigned char *d, unsigned len)
2608         {
2609         unsigned int off = 0;
2610
2611         while (off < len)
2612                 {
2613                 if (d[off] == 0)
2614                         return 0;
2615                 off += d[off];
2616                 off++;
2617                 }
2618
2619         return off == len;
2620         }
2621 #endif
2622
2623 static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
2624         {
2625         unsigned short length;
2626         unsigned short type;
2627         unsigned short size;
2628         unsigned char *data = *p;
2629         int tlsext_servername = 0;
2630         int renegotiate_seen = 0;
2631
2632 #ifndef OPENSSL_NO_NEXTPROTONEG
2633         s->s3->next_proto_neg_seen = 0;
2634 #endif
2635         s->tlsext_ticket_expected = 0;
2636
2637         if (s->s3->alpn_selected)
2638                 {
2639                 OPENSSL_free(s->s3->alpn_selected);
2640                 s->s3->alpn_selected = NULL;
2641                 }
2642
2643 #ifndef OPENSSL_NO_HEARTBEATS
2644         s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
2645                                SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
2646 #endif
2647
2648         if (data >= (d+n-2))
2649                 goto ri_check;
2650
2651         n2s(data,length);
2652         if (data+length != d+n)
2653                 {
2654                 *al = SSL_AD_DECODE_ERROR;
2655                 return 0;
2656                 }
2657
2658         while(data <= (d+n-4))
2659                 {
2660                 n2s(data,type);
2661                 n2s(data,size);
2662
2663                 if (data+size > (d+n))
2664                         goto ri_check;
2665
2666                 if (s->tlsext_debug_cb)
2667                         s->tlsext_debug_cb(s, 1, type, data, size,
2668                                                 s->tlsext_debug_arg);
2669
2670                 if (type == TLSEXT_TYPE_server_name)
2671                         {
2672                         if (s->tlsext_hostname == NULL || size > 0)
2673                                 {
2674                                 *al = TLS1_AD_UNRECOGNIZED_NAME;
2675                                 return 0;
2676                                 }
2677                         tlsext_servername = 1;   
2678                         }
2679
2680 #ifndef OPENSSL_NO_EC
2681                 else if (type == TLSEXT_TYPE_ec_point_formats)
2682                         {
2683                         unsigned char *sdata = data;
2684                         int ecpointformatlist_length = *(sdata++);
2685
2686                         if (ecpointformatlist_length != size - 1)
2687                                 {
2688                                 *al = TLS1_AD_DECODE_ERROR;
2689                                 return 0;
2690                                 }
2691                         if (!s->hit)
2692                                 {
2693                                 s->session->tlsext_ecpointformatlist_length = 0;
2694                                 if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist);
2695                                 if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
2696                                         {
2697                                         *al = TLS1_AD_INTERNAL_ERROR;
2698                                         return 0;
2699                                         }
2700                                 s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
2701                                 memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
2702                                 }
2703 #if 0
2704                         fprintf(stderr,"ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist ");
2705                         sdata = s->session->tlsext_ecpointformatlist;
2706                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2707                                 fprintf(stderr,"%i ",*(sdata++));
2708                         fprintf(stderr,"\n");
2709 #endif
2710                         }
2711 #endif /* OPENSSL_NO_EC */
2712
2713                 else if (type == TLSEXT_TYPE_session_ticket)
2714                         {
2715                         if (s->tls_session_ticket_ext_cb &&
2716                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
2717                                 {
2718                                 *al = TLS1_AD_INTERNAL_ERROR;
2719                                 return 0;
2720                                 }
2721                         if ((SSL_get_options(s) & SSL_OP_NO_TICKET)
2722                                 || (size > 0))
2723                                 {
2724                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2725                                 return 0;
2726                                 }
2727                         s->tlsext_ticket_expected = 1;
2728                         }
2729 #ifdef TLSEXT_TYPE_opaque_prf_input
2730                 else if (type == TLSEXT_TYPE_opaque_prf_input)
2731                         {
2732                         unsigned char *sdata = data;
2733
2734                         if (size < 2)
2735                                 {
2736                                 *al = SSL_AD_DECODE_ERROR;
2737                                 return 0;
2738                                 }
2739                         n2s(sdata, s->s3->server_opaque_prf_input_len);
2740                         if (s->s3->server_opaque_prf_input_len != size - 2)
2741                                 {
2742                                 *al = SSL_AD_DECODE_ERROR;
2743                                 return 0;
2744                                 }
2745                         
2746                         if (s->s3->server_opaque_prf_input != NULL)
2747                                 {
2748                                 /* shouldn't really happen */
2749                                 OPENSSL_free(s->s3->server_opaque_prf_input);
2750                                 }
2751                         if (s->s3->server_opaque_prf_input_len == 0)
2752                                 {
2753                                 /* dummy byte just to get non-NULL */
2754                                 s->s3->server_opaque_prf_input = OPENSSL_malloc(1);
2755                                 }
2756                         else
2757                                 {
2758                                 s->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len);
2759                                 }
2760
2761                         if (s->s3->server_opaque_prf_input == NULL)
2762                                 {
2763                                 *al = TLS1_AD_INTERNAL_ERROR;
2764                                 return 0;
2765                                 }
2766                         }
2767 #endif
2768                 else if (type == TLSEXT_TYPE_status_request)
2769                         {
2770                         /* MUST be empty and only sent if we've requested
2771                          * a status request message.
2772                          */ 
2773                         if ((s->tlsext_status_type == -1) || (size > 0))
2774                                 {
2775                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2776                                 return 0;
2777                                 }
2778                         /* Set flag to expect CertificateStatus message */
2779                         s->tlsext_status_expected = 1;
2780                         }
2781 #ifndef OPENSSL_NO_NEXTPROTONEG
2782                 else if (type == TLSEXT_TYPE_next_proto_neg &&
2783                          s->s3->tmp.finish_md_len == 0)
2784                         {
2785                         unsigned char *selected;
2786                         unsigned char selected_len;
2787
2788                         /* We must have requested it. */
2789                         if (s->ctx->next_proto_select_cb == NULL)
2790                                 {
2791                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2792                                 return 0;
2793                                 }
2794                         /* The data must be valid */
2795                         if (!ssl_next_proto_validate(data, size))
2796                                 {
2797                                 *al = TLS1_AD_DECODE_ERROR;
2798                                 return 0;
2799                                 }
2800                         if (s->ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK)
2801                                 {
2802                                 *al = TLS1_AD_INTERNAL_ERROR;
2803                                 return 0;
2804                                 }
2805                         s->next_proto_negotiated = OPENSSL_malloc(selected_len);
2806                         if (!s->next_proto_negotiated)
2807                                 {
2808                                 *al = TLS1_AD_INTERNAL_ERROR;
2809                                 return 0;
2810                                 }
2811                         memcpy(s->next_proto_negotiated, selected, selected_len);
2812                         s->next_proto_negotiated_len = selected_len;
2813                         s->s3->next_proto_neg_seen = 1;
2814                         }
2815 #endif
2816
2817                 else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation)
2818                         {
2819                         unsigned len;
2820
2821                         /* We must have requested it. */
2822                         if (s->alpn_client_proto_list == NULL)
2823                                 {
2824                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2825                                 return 0;
2826                                 }
2827                         if (size < 4)
2828                                 {
2829                                 *al = TLS1_AD_DECODE_ERROR;
2830                                 return 0;
2831                                 }
2832                         /*- 
2833                          * The extension data consists of:
2834                          *   uint16 list_length
2835                          *   uint8 proto_length;
2836                          *   uint8 proto[proto_length]; 
2837                          */
2838                         len = data[0];
2839                         len <<= 8;
2840                         len |= data[1];
2841                         if (len != (unsigned) size - 2)
2842                                 {
2843                                 *al = TLS1_AD_DECODE_ERROR;
2844                                 return 0;
2845                                 }
2846                         len = data[2];
2847                         if (len != (unsigned) size - 3)
2848                                 {
2849                                 *al = TLS1_AD_DECODE_ERROR;
2850                                 return 0;
2851                                 }
2852                         if (s->s3->alpn_selected)
2853                                 OPENSSL_free(s->s3->alpn_selected);
2854                         s->s3->alpn_selected = OPENSSL_malloc(len);
2855                         if (!s->s3->alpn_selected)
2856                                 {
2857                                 *al = TLS1_AD_INTERNAL_ERROR;
2858                                 return 0;
2859                                 }
2860                         memcpy(s->s3->alpn_selected, data + 3, len);
2861                         s->s3->alpn_selected_len = len;
2862                         }
2863
2864                 else if (type == TLSEXT_TYPE_renegotiate)
2865                         {
2866                         if(!ssl_parse_serverhello_renegotiate_ext(s, data, size, al))
2867                                 return 0;
2868                         renegotiate_seen = 1;
2869                         }
2870 #ifndef OPENSSL_NO_HEARTBEATS
2871                 else if (type == TLSEXT_TYPE_heartbeat)
2872                         {
2873                         switch(data[0])
2874                                 {
2875                                 case 0x01:      /* Server allows us to send HB requests */
2876                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2877                                                         break;
2878                                 case 0x02:      /* Server doesn't accept HB requests */
2879                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2880                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2881                                                         break;
2882                                 default:        *al = SSL_AD_ILLEGAL_PARAMETER;
2883                                                         return 0;
2884                                 }
2885                         }
2886 #endif
2887 #ifndef OPENSSL_NO_SRTP
2888                 else if (SSL_IS_DTLS(s) && type == TLSEXT_TYPE_use_srtp)
2889                         {
2890                         if(ssl_parse_serverhello_use_srtp_ext(s, data, size,
2891                                                               al))
2892                                 return 0;
2893                         }
2894 #endif
2895                 /* If this extension type was not otherwise handled, but 
2896                  * matches a custom_cli_ext_record, then send it to the c
2897                  * callback */
2898                 else if (custom_ext_parse(s, 0, type, data, size, al) <= 0)
2899                                 return 0;
2900  
2901                 data += size;
2902                 }
2903
2904         if (data != d+n)
2905                 {
2906                 *al = SSL_AD_DECODE_ERROR;
2907                 return 0;
2908                 }
2909
2910         if (!s->hit && tlsext_servername == 1)
2911                 {
2912                 if (s->tlsext_hostname)
2913                         {
2914                         if (s->session->tlsext_hostname == NULL)
2915                                 {
2916                                 s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);   
2917                                 if (!s->session->tlsext_hostname)
2918                                         {
2919                                         *al = SSL_AD_UNRECOGNIZED_NAME;
2920                                         return 0;
2921                                         }
2922                                 }
2923                         else 
2924                                 {
2925                                 *al = SSL_AD_DECODE_ERROR;
2926                                 return 0;
2927                                 }
2928                         }
2929                 }
2930
2931         *p = data;
2932
2933         ri_check:
2934
2935         /* Determine if we need to see RI. Strictly speaking if we want to
2936          * avoid an attack we should *always* see RI even on initial server
2937          * hello because the client doesn't see any renegotiation during an
2938          * attack. However this would mean we could not connect to any server
2939          * which doesn't support RI so for the immediate future tolerate RI
2940          * absence on initial connect only.
2941          */
2942         if (!renegotiate_seen
2943                 && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
2944                 && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
2945                 {
2946                 *al = SSL_AD_HANDSHAKE_FAILURE;
2947                 SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT,
2948                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2949                 return 0;
2950                 }
2951
2952         return 1;
2953         }
2954
2955
2956 int ssl_prepare_clienthello_tlsext(SSL *s)
2957         {
2958
2959 #ifdef TLSEXT_TYPE_opaque_prf_input
2960         {
2961                 int r = 1;
2962         
2963                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
2964                         {
2965                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
2966                         if (!r)
2967                                 return -1;
2968                         }
2969
2970                 if (s->tlsext_opaque_prf_input != NULL)
2971                         {
2972                         if (s->s3->client_opaque_prf_input != NULL)
2973                                 {
2974                                 /* shouldn't really happen */
2975                                 OPENSSL_free(s->s3->client_opaque_prf_input);
2976                                 }
2977
2978                         if (s->tlsext_opaque_prf_input_len == 0)
2979                                 {
2980                                 /* dummy byte just to get non-NULL */
2981                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1);
2982                                 }
2983                         else
2984                                 {
2985                                 s->s3->client_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
2986                                 }
2987                         if (s->s3->client_opaque_prf_input == NULL)
2988                                 {
2989                                 SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
2990                                 return -1;
2991                                 }
2992                         s->s3->client_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2993                         }
2994
2995                 if (r == 2)
2996                         /* at callback's request, insist on receiving an appropriate server opaque PRF input */
2997                         s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2998         }
2999 #endif
3000
3001         return 1;
3002         }
3003
3004 int ssl_prepare_serverhello_tlsext(SSL *s)
3005         {
3006         return 1;
3007         }
3008
3009 static int ssl_check_clienthello_tlsext_early(SSL *s)
3010         {
3011         int ret=SSL_TLSEXT_ERR_NOACK;
3012         int al = SSL_AD_UNRECOGNIZED_NAME;
3013
3014 #ifndef OPENSSL_NO_EC
3015         /* The handling of the ECPointFormats extension is done elsewhere, namely in 
3016          * ssl3_choose_cipher in s3_lib.c.
3017          */
3018         /* The handling of the EllipticCurves extension is done elsewhere, namely in 
3019          * ssl3_choose_cipher in s3_lib.c.
3020          */
3021 #endif
3022
3023         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
3024                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
3025         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
3026                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
3027
3028 #ifdef TLSEXT_TYPE_opaque_prf_input
3029         {
3030                 /* This sort of belongs into ssl_prepare_serverhello_tlsext(),
3031                  * but we might be sending an alert in response to the client hello,
3032                  * so this has to happen here in
3033                  * ssl_check_clienthello_tlsext_early(). */
3034
3035                 int r = 1;
3036         
3037                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
3038                         {
3039                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
3040                         if (!r)
3041                                 {
3042                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3043                                 al = SSL_AD_INTERNAL_ERROR;
3044                                 goto err;
3045                                 }
3046                         }
3047
3048                 if (s->s3->server_opaque_prf_input != NULL)
3049                         {
3050                         /* shouldn't really happen */
3051                         OPENSSL_free(s->s3->server_opaque_prf_input);
3052                         }
3053                 s->s3->server_opaque_prf_input = NULL;
3054
3055                 if (s->tlsext_opaque_prf_input != NULL)
3056                         {
3057                         if (s->s3->client_opaque_prf_input != NULL &&
3058                                 s->s3->client_opaque_prf_input_len == s->tlsext_opaque_prf_input_len)
3059                                 {
3060                                 /* can only use this extension if we have a server opaque PRF input
3061                                  * of the same length as the client opaque PRF input! */
3062
3063                                 if (s->tlsext_opaque_prf_input_len == 0)
3064                                         {
3065                                         /* dummy byte just to get non-NULL */
3066                                         s->s3->server_opaque_prf_input = OPENSSL_malloc(1);
3067                                         }
3068                                 else
3069                                         {
3070                                         s->s3->server_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
3071                                         }
3072                                 if (s->s3->server_opaque_prf_input == NULL)
3073                                         {
3074                                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3075                                         al = SSL_AD_INTERNAL_ERROR;
3076                                         goto err;
3077                                         }
3078                                 s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
3079                                 }
3080                         }
3081
3082                 if (r == 2 && s->s3->server_opaque_prf_input == NULL)
3083                         {
3084                         /* The callback wants to enforce use of the extension,
3085                          * but we can't do that with the client opaque PRF input;
3086                          * abort the handshake.
3087                          */
3088                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3089                         al = SSL_AD_HANDSHAKE_FAILURE;
3090                         }
3091         }
3092
3093  err:
3094 #endif
3095         switch (ret)
3096                 {
3097                 case SSL_TLSEXT_ERR_ALERT_FATAL:
3098                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
3099                         return -1;
3100
3101                 case SSL_TLSEXT_ERR_ALERT_WARNING:
3102                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
3103                         return 1; 
3104                                         
3105                 case SSL_TLSEXT_ERR_NOACK:
3106                         s->servername_done=0;
3107                         default:
3108                 return 1;
3109                 }
3110         }
3111
3112 int tls1_set_server_sigalgs(SSL *s)
3113         {
3114         int al;
3115         size_t i;
3116         /* Clear any shared sigtnature algorithms */
3117         if (s->cert->shared_sigalgs)
3118                 {
3119                 OPENSSL_free(s->cert->shared_sigalgs);
3120                 s->cert->shared_sigalgs = NULL;
3121                 }
3122         /* Clear certificate digests and validity flags */
3123         for (i = 0; i < SSL_PKEY_NUM; i++)
3124                 {
3125                 s->cert->pkeys[i].digest = NULL;
3126                 s->cert->pkeys[i].valid_flags = 0;
3127                 }
3128
3129         /* If sigalgs received process it. */
3130         if (s->cert->peer_sigalgs)
3131                 {
3132                 if (!tls1_process_sigalgs(s))
3133                         {
3134                         SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS,
3135                                         ERR_R_MALLOC_FAILURE);
3136                         al = SSL_AD_INTERNAL_ERROR;
3137                         goto err;
3138                         }
3139                 /* Fatal error is no shared signature algorithms */
3140                 if (!s->cert->shared_sigalgs)
3141                         {
3142                         SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS,
3143                                         SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
3144                         al = SSL_AD_ILLEGAL_PARAMETER;
3145                         goto err;
3146                         }
3147                 }
3148         else
3149                 ssl_cert_set_default_md(s->cert);
3150         return 1;
3151         err:
3152         ssl3_send_alert(s, SSL3_AL_FATAL, al);
3153         return 0;
3154         }
3155
3156 int ssl_check_clienthello_tlsext_late(SSL *s)
3157         {
3158         int ret = SSL_TLSEXT_ERR_OK;
3159         int al;
3160
3161         /* If status request then ask callback what to do.
3162          * Note: this must be called after servername callbacks in case
3163          * the certificate has changed, and must be called after the cipher
3164          * has been chosen because this may influence which certificate is sent
3165          */
3166         if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb)
3167                 {
3168                 int r;
3169                 CERT_PKEY *certpkey;
3170                 certpkey = ssl_get_server_send_pkey(s);
3171                 /* If no certificate can't return certificate status */
3172                 if (certpkey == NULL)
3173                         {
3174                         s->tlsext_status_expected = 0;
3175                         return 1;
3176                         }
3177                 /* Set current certificate to one we will use so
3178                  * SSL_get_certificate et al can pick it up.
3179                  */
3180                 s->cert->key = certpkey;
3181                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
3182                 switch (r)
3183                         {
3184                         /* We don't want to send a status request response */
3185                         case SSL_TLSEXT_ERR_NOACK:
3186                                 s->tlsext_status_expected = 0;
3187                                 break;
3188                         /* status request response should be sent */
3189                         case SSL_TLSEXT_ERR_OK:
3190                                 if (s->tlsext_ocsp_resp)
3191                                         s->tlsext_status_expected = 1;
3192                                 else
3193                                         s->tlsext_status_expected = 0;
3194                                 break;
3195                         /* something bad happened */
3196                         case SSL_TLSEXT_ERR_ALERT_FATAL:
3197                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3198                                 al = SSL_AD_INTERNAL_ERROR;
3199                                 goto err;
3200                         }
3201                 }
3202         else
3203                 s->tlsext_status_expected = 0;
3204
3205  err:
3206         switch (ret)
3207                 {
3208                 case SSL_TLSEXT_ERR_ALERT_FATAL:
3209                         ssl3_send_alert(s, SSL3_AL_FATAL, al);
3210                         return -1;
3211
3212                 case SSL_TLSEXT_ERR_ALERT_WARNING:
3213                         ssl3_send_alert(s, SSL3_AL_WARNING, al);
3214                         return 1; 
3215
3216                 default:
3217                         return 1;
3218                 }
3219         }
3220
3221 int ssl_check_serverhello_tlsext(SSL *s)
3222         {
3223         int ret=SSL_TLSEXT_ERR_NOACK;
3224         int al = SSL_AD_UNRECOGNIZED_NAME;
3225
3226 #ifndef OPENSSL_NO_EC
3227         /* If we are client and using an elliptic curve cryptography cipher
3228          * suite, then if server returns an EC point formats lists extension
3229          * it must contain uncompressed.
3230          */
3231         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3232         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
3233         if ((s->tlsext_ecpointformatlist != NULL) && (s->tlsext_ecpointformatlist_length > 0) && 
3234             (s->session->tlsext_ecpointformatlist != NULL) && (s->session->tlsext_ecpointformatlist_length > 0) && 
3235             ((alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA)))
3236                 {
3237                 /* we are using an ECC cipher */
3238                 size_t i;
3239                 unsigned char *list;
3240                 int found_uncompressed = 0;
3241                 list = s->session->tlsext_ecpointformatlist;
3242                 for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
3243                         {
3244                         if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed)
3245                                 {
3246                                 found_uncompressed = 1;
3247                                 break;
3248                                 }
3249                         }
3250                 if (!found_uncompressed)
3251                         {
3252                         SSLerr(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT,SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
3253                         return -1;
3254                         }
3255                 }
3256         ret = SSL_TLSEXT_ERR_OK;
3257 #endif /* OPENSSL_NO_EC */
3258
3259         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
3260                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
3261         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
3262                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
3263
3264 #ifdef TLSEXT_TYPE_opaque_prf_input
3265         if (s->s3->server_opaque_prf_input_len > 0)
3266                 {
3267                 /* This case may indicate that we, as a client, want to insist on using opaque PRF inputs.
3268                  * So first verify that we really have a value from the server too. */
3269
3270                 if (s->s3->server_opaque_prf_input == NULL)
3271                         {
3272                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3273                         al = SSL_AD_HANDSHAKE_FAILURE;
3274                         }
3275                 
3276                 /* Anytime the server *has* sent an opaque PRF input, we need to check
3277                  * that we have a client opaque PRF input of the same size. */
3278                 if (s->s3->client_opaque_prf_input == NULL ||
3279                     s->s3->client_opaque_prf_input_len != s->s3->server_opaque_prf_input_len)
3280                         {
3281                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3282                         al = SSL_AD_ILLEGAL_PARAMETER;
3283                         }
3284                 }
3285 #endif
3286
3287         /* If we've requested certificate status and we wont get one
3288          * tell the callback
3289          */
3290         if ((s->tlsext_status_type != -1) && !(s->tlsext_status_expected)
3291                         && s->ctx && s->ctx->tlsext_status_cb)
3292                 {
3293                 int r;
3294                 /* Set resp to NULL, resplen to -1 so callback knows
3295                  * there is no response.
3296                  */
3297                 if (s->tlsext_ocsp_resp)
3298                         {
3299                         OPENSSL_free(s->tlsext_ocsp_resp);
3300                         s->tlsext_ocsp_resp = NULL;
3301                         }
3302                 s->tlsext_ocsp_resplen = -1;
3303                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
3304                 if (r == 0)
3305                         {
3306                         al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
3307                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3308                         }
3309                 if (r < 0)
3310                         {
3311                         al = SSL_AD_INTERNAL_ERROR;
3312                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3313                         }
3314                 }
3315
3316         switch (ret)
3317                 {
3318                 case SSL_TLSEXT_ERR_ALERT_FATAL:
3319                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
3320                         return -1;
3321
3322                 case SSL_TLSEXT_ERR_ALERT_WARNING:
3323                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
3324                         return 1; 
3325                                         
3326                 case SSL_TLSEXT_ERR_NOACK:
3327                         s->servername_done=0;
3328                         default:
3329                 return 1;
3330                 }
3331         }
3332
3333 int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n) 
3334         {
3335         int al = -1;
3336         if (s->version < SSL3_VERSION)
3337                 return 1;
3338         if (ssl_scan_serverhello_tlsext(s, p, d, n, &al) <= 0) 
3339                 {
3340                 ssl3_send_alert(s,SSL3_AL_FATAL,al); 
3341                 return 0;
3342                 }
3343
3344         if (ssl_check_serverhello_tlsext(s) <= 0) 
3345                 {
3346                 SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT,SSL_R_SERVERHELLO_TLSEXT);
3347                 return 0;
3348                 }
3349         return 1;
3350 }
3351
3352 /*-
3353  * Since the server cache lookup is done early on in the processing of the
3354  * ClientHello, and other operations depend on the result, we need to handle
3355  * any TLS session ticket extension at the same time.
3356  *
3357  *   session_id: points at the session ID in the ClientHello. This code will
3358  *       read past the end of this in order to parse out the session ticket
3359  *       extension, if any.
3360  *   len: the length of the session ID.
3361  *   limit: a pointer to the first byte after the ClientHello.
3362  *   ret: (output) on return, if a ticket was decrypted, then this is set to
3363  *       point to the resulting session.
3364  *
3365  * If s->tls_session_secret_cb is set then we are expecting a pre-shared key
3366  * ciphersuite, in which case we have no use for session tickets and one will
3367  * never be decrypted, nor will s->tlsext_ticket_expected be set to 1.
3368  *
3369  * Returns:
3370  *   -1: fatal error, either from parsing or decrypting the ticket.
3371  *    0: no ticket was found (or was ignored, based on settings).
3372  *    1: a zero length extension was found, indicating that the client supports
3373  *       session tickets but doesn't currently have one to offer.
3374  *    2: either s->tls_session_secret_cb was set, or a ticket was offered but
3375  *       couldn't be decrypted because of a non-fatal error.
3376  *    3: a ticket was successfully decrypted and *ret was set.
3377  *
3378  * Side effects:
3379  *   Sets s->tlsext_ticket_expected to 1 if the server will have to issue
3380  *   a new session ticket to the client because the client indicated support
3381  *   (and s->tls_session_secret_cb is NULL) but the client either doesn't have
3382  *   a session ticket or we couldn't use the one it gave us, or if
3383  *   s->ctx->tlsext_ticket_key_cb asked to renew the client's ticket.
3384  *   Otherwise, s->tlsext_ticket_expected is set to 0.
3385  */
3386 int tls1_process_ticket(SSL *s, unsigned char *session_id, int len,
3387                         const unsigned char *limit, SSL_SESSION **ret)
3388         {
3389         /* Point after session ID in client hello */
3390         const unsigned char *p = session_id + len;
3391         unsigned short i;
3392
3393         *ret = NULL;
3394         s->tlsext_ticket_expected = 0;
3395
3396         /* If tickets disabled behave as if no ticket present
3397          * to permit stateful resumption.
3398          */
3399         if (SSL_get_options(s) & SSL_OP_NO_TICKET)
3400                 return 0;
3401         if ((s->version <= SSL3_VERSION) || !limit)
3402                 return 0;
3403         if (p >= limit)
3404                 return -1;
3405         /* Skip past DTLS cookie */
3406         if (SSL_IS_DTLS(s))
3407                 {
3408                 i = *(p++);
3409                 p+= i;
3410                 if (p >= limit)
3411                         return -1;
3412                 }
3413         /* Skip past cipher list */
3414         n2s(p, i);
3415         p+= i;
3416         if (p >= limit)
3417                 return -1;
3418         /* Skip past compression algorithm list */
3419         i = *(p++);
3420         p += i;
3421         if (p > limit)
3422                 return -1;
3423         /* Now at start of extensions */
3424         if ((p + 2) >= limit)
3425                 return 0;
3426         n2s(p, i);
3427         while ((p + 4) <= limit)
3428                 {
3429                 unsigned short type, size;
3430                 n2s(p, type);
3431                 n2s(p, size);
3432                 if (p + size > limit)
3433                         return 0;
3434                 if (type == TLSEXT_TYPE_session_ticket)
3435                         {
3436                         int r;
3437                         if (size == 0)
3438                                 {
3439                                 /* The client will accept a ticket but doesn't
3440                                  * currently have one. */
3441                                 s->tlsext_ticket_expected = 1;
3442                                 return 1;
3443                                 }
3444                         if (s->tls_session_secret_cb)
3445                                 {
3446                                 /* Indicate that the ticket couldn't be
3447                                  * decrypted rather than generating the session
3448                                  * from ticket now, trigger abbreviated
3449                                  * handshake based on external mechanism to
3450                                  * calculate the master secret later. */
3451                                 return 2;
3452                                 }
3453                         r = tls_decrypt_ticket(s, p, size, session_id, len, ret);
3454                         switch (r)
3455                                 {
3456                                 case 2: /* ticket couldn't be decrypted */
3457                                         s->tlsext_ticket_expected = 1;
3458                                         return 2;
3459                                 case 3: /* ticket was decrypted */
3460                                         return r;
3461                                 case 4: /* ticket decrypted but need to renew */
3462                                         s->tlsext_ticket_expected = 1;
3463                                         return 3;
3464                                 default: /* fatal error */
3465                                         return -1;
3466                                 }
3467                         }
3468                 p += size;
3469                 }
3470         return 0;
3471         }
3472
3473 /*-
3474  * tls_decrypt_ticket attempts to decrypt a session ticket.
3475  *
3476  *   etick: points to the body of the session ticket extension.
3477  *   eticklen: the length of the session tickets extenion.
3478  *   sess_id: points at the session ID.
3479  *   sesslen: the length of the session ID.
3480  *   psess: (output) on return, if a ticket was decrypted, then this is set to
3481  *       point to the resulting session.
3482  *
3483  * Returns:
3484  *   -1: fatal error, either from parsing or decrypting the ticket.
3485  *    2: the ticket couldn't be decrypted.
3486  *    3: a ticket was successfully decrypted and *psess was set.
3487  *    4: same as 3, but the ticket needs to be renewed.
3488  */
3489 static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen,
3490                                 const unsigned char *sess_id, int sesslen,
3491                                 SSL_SESSION **psess)
3492         {
3493         SSL_SESSION *sess;
3494         unsigned char *sdec;
3495         const unsigned char *p;
3496         int slen, mlen, renew_ticket = 0;
3497         unsigned char tick_hmac[EVP_MAX_MD_SIZE];
3498         HMAC_CTX hctx;
3499         EVP_CIPHER_CTX ctx;
3500         SSL_CTX *tctx = s->initial_ctx;
3501         /* Need at least keyname + iv + some encrypted data */
3502         if (eticklen < 48)
3503                 return 2;
3504         /* Initialize session ticket encryption and HMAC contexts */
3505         HMAC_CTX_init(&hctx);
3506         EVP_CIPHER_CTX_init(&ctx);
3507         if (tctx->tlsext_ticket_key_cb)
3508                 {
3509                 unsigned char *nctick = (unsigned char *)etick;
3510                 int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
3511                                                         &ctx, &hctx, 0);
3512                 if (rv < 0)
3513                         return -1;
3514                 if (rv == 0)
3515                         return 2;
3516                 if (rv == 2)
3517                         renew_ticket = 1;
3518                 }
3519         else
3520                 {
3521                 /* Check key name matches */
3522                 if (memcmp(etick, tctx->tlsext_tick_key_name, 16))
3523                         return 2;
3524                 HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3525                                         tlsext_tick_md(), NULL);
3526                 EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3527                                 tctx->tlsext_tick_aes_key, etick + 16);
3528                 }
3529         /* Attempt to process session ticket, first conduct sanity and
3530          * integrity checks on ticket.
3531          */
3532         mlen = HMAC_size(&hctx);
3533         if (mlen < 0)
3534                 {
3535                 EVP_CIPHER_CTX_cleanup(&ctx);
3536                 return -1;
3537                 }
3538         eticklen -= mlen;
3539         /* Check HMAC of encrypted ticket */
3540         HMAC_Update(&hctx, etick, eticklen);
3541         HMAC_Final(&hctx, tick_hmac, NULL);
3542         HMAC_CTX_cleanup(&hctx);
3543         if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen))
3544                 {
3545                 EVP_CIPHER_CTX_cleanup(&ctx);
3546                 return 2;
3547                 }
3548         /* Attempt to decrypt session data */
3549         /* Move p after IV to start of encrypted ticket, update length */
3550         p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx);
3551         eticklen -= 16 + EVP_CIPHER_CTX_iv_length(&ctx);
3552         sdec = OPENSSL_malloc(eticklen);
3553         if (!sdec)
3554                 {
3555                 EVP_CIPHER_CTX_cleanup(&ctx);
3556                 return -1;
3557                 }
3558         EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen);
3559         if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0)
3560                 {
3561                 EVP_CIPHER_CTX_cleanup(&ctx);
3562                 OPENSSL_free(sdec);
3563                 return 2;
3564                 }
3565         slen += mlen;
3566         EVP_CIPHER_CTX_cleanup(&ctx);
3567         p = sdec;
3568
3569         sess = d2i_SSL_SESSION(NULL, &p, slen);
3570         OPENSSL_free(sdec);
3571         if (sess)
3572                 {
3573                 /* The session ID, if non-empty, is used by some clients to
3574                  * detect that the ticket has been accepted. So we copy it to
3575                  * the session structure. If it is empty set length to zero
3576                  * as required by standard.
3577                  */
3578                 if (sesslen)
3579                         memcpy(sess->session_id, sess_id, sesslen);
3580                 sess->session_id_length = sesslen;
3581                 *psess = sess;
3582                 if (renew_ticket)
3583                         return 4;
3584                 else
3585                         return 3;
3586                 }
3587         ERR_clear_error();
3588         /* For session parse failure, indicate that we need to send a new
3589          * ticket. */
3590         return 2;
3591         }
3592
3593 /* Tables to translate from NIDs to TLS v1.2 ids */
3594
3595 typedef struct 
3596         {
3597         int nid;
3598         int id;
3599         } tls12_lookup;
3600
3601 static tls12_lookup tls12_md[] = {
3602         {NID_md5, TLSEXT_hash_md5},
3603         {NID_sha1, TLSEXT_hash_sha1},
3604         {NID_sha224, TLSEXT_hash_sha224},
3605         {NID_sha256, TLSEXT_hash_sha256},
3606         {NID_sha384, TLSEXT_hash_sha384},
3607         {NID_sha512, TLSEXT_hash_sha512}
3608 };
3609
3610 static tls12_lookup tls12_sig[] = {
3611         {EVP_PKEY_RSA, TLSEXT_signature_rsa},
3612         {EVP_PKEY_DSA, TLSEXT_signature_dsa},
3613         {EVP_PKEY_EC, TLSEXT_signature_ecdsa}
3614 };
3615
3616 static int tls12_find_id(int nid, tls12_lookup *table, size_t tlen)
3617         {
3618         size_t i;
3619         for (i = 0; i < tlen; i++)
3620                 {
3621                 if (table[i].nid == nid)
3622                         return table[i].id;
3623                 }
3624         return -1;
3625         }
3626
3627 static int tls12_find_nid(int id, tls12_lookup *table, size_t tlen)
3628         {
3629         size_t i;
3630         for (i = 0; i < tlen; i++)
3631                 {
3632                 if ((table[i].id) == id)
3633                         return table[i].nid;
3634                 }
3635         return NID_undef;
3636         }
3637
3638 int tls12_get_sigandhash(unsigned char *p, const EVP_PKEY *pk, const EVP_MD *md)
3639         {
3640         int sig_id, md_id;
3641         if (!md)
3642                 return 0;
3643         md_id = tls12_find_id(EVP_MD_type(md), tls12_md,
3644                                 sizeof(tls12_md)/sizeof(tls12_lookup));
3645         if (md_id == -1)
3646                 return 0;
3647         sig_id = tls12_get_sigid(pk);
3648         if (sig_id == -1)
3649                 return 0;
3650         p[0] = (unsigned char)md_id;
3651         p[1] = (unsigned char)sig_id;
3652         return 1;
3653         }
3654
3655 int tls12_get_sigid(const EVP_PKEY *pk)
3656         {
3657         return tls12_find_id(pk->type, tls12_sig,
3658                                 sizeof(tls12_sig)/sizeof(tls12_lookup));
3659         }
3660
3661 const EVP_MD *tls12_get_hash(unsigned char hash_alg)
3662         {
3663         switch(hash_alg)
3664                 {
3665 #ifndef OPENSSL_NO_MD5
3666                 case TLSEXT_hash_md5:
3667 #ifdef OPENSSL_FIPS
3668                 if (FIPS_mode())
3669                         return NULL;
3670 #endif
3671                 return EVP_md5();
3672 #endif
3673 #ifndef OPENSSL_NO_SHA
3674                 case TLSEXT_hash_sha1:
3675                 return EVP_sha1();
3676 #endif
3677 #ifndef OPENSSL_NO_SHA256
3678                 case TLSEXT_hash_sha224:
3679                 return EVP_sha224();
3680
3681                 case TLSEXT_hash_sha256:
3682                 return EVP_sha256();
3683 #endif
3684 #ifndef OPENSSL_NO_SHA512
3685                 case TLSEXT_hash_sha384:
3686                 return EVP_sha384();
3687
3688                 case TLSEXT_hash_sha512:
3689                 return EVP_sha512();
3690 #endif
3691                 default:
3692                 return NULL;
3693
3694                 }
3695         }
3696
3697 static int tls12_get_pkey_idx(unsigned char sig_alg)
3698         {
3699         switch(sig_alg)
3700                 {
3701 #ifndef OPENSSL_NO_RSA
3702         case TLSEXT_signature_rsa:
3703                 return SSL_PKEY_RSA_SIGN;
3704 #endif
3705 #ifndef OPENSSL_NO_DSA
3706         case TLSEXT_signature_dsa:
3707                 return SSL_PKEY_DSA_SIGN;
3708 #endif
3709 #ifndef OPENSSL_NO_ECDSA
3710         case TLSEXT_signature_ecdsa:
3711                 return SSL_PKEY_ECC;
3712 #endif
3713                 }
3714         return -1;
3715         }
3716
3717 /* Convert TLS 1.2 signature algorithm extension values into NIDs */
3718 static void tls1_lookup_sigalg(int *phash_nid, int *psign_nid,
3719                         int *psignhash_nid, const unsigned char *data)
3720         {
3721         int sign_nid = 0, hash_nid = 0;
3722         if (!phash_nid && !psign_nid && !psignhash_nid)
3723                 return;
3724         if (phash_nid || psignhash_nid)
3725                 {
3726                 hash_nid = tls12_find_nid(data[0], tls12_md,
3727                                         sizeof(tls12_md)/sizeof(tls12_lookup));
3728                 if (phash_nid)
3729                         *phash_nid = hash_nid;
3730                 }
3731         if (psign_nid || psignhash_nid)
3732                 {
3733                 sign_nid = tls12_find_nid(data[1], tls12_sig,
3734                                         sizeof(tls12_sig)/sizeof(tls12_lookup));
3735                 if (psign_nid)
3736                         *psign_nid = sign_nid;
3737                 }
3738         if (psignhash_nid)
3739                 {
3740                 if (sign_nid && hash_nid)
3741                         OBJ_find_sigid_by_algs(psignhash_nid,
3742                                                         hash_nid, sign_nid);
3743                 else
3744                         *psignhash_nid = NID_undef;
3745                 }
3746         }
3747 /* Given preference and allowed sigalgs set shared sigalgs */
3748 static int tls12_do_shared_sigalgs(TLS_SIGALGS *shsig,
3749                                 const unsigned char *pref, size_t preflen,
3750                                 const unsigned char *allow, size_t allowlen)
3751         {
3752         const unsigned char *ptmp, *atmp;
3753         size_t i, j, nmatch = 0;
3754         for (i = 0, ptmp = pref; i < preflen; i+=2, ptmp+=2)
3755                 {
3756                 /* Skip disabled hashes or signature algorithms */
3757                 if (tls12_get_hash(ptmp[0]) == NULL)
3758                         continue;
3759                 if (tls12_get_pkey_idx(ptmp[1]) == -1)
3760                         continue;
3761                 for (j = 0, atmp = allow; j < allowlen; j+=2, atmp+=2)
3762                         {
3763                         if (ptmp[0] == atmp[0] && ptmp[1] == atmp[1])
3764                                 {
3765                                 nmatch++;
3766                                 if (shsig)
3767                                         {
3768                                         shsig->rhash = ptmp[0];
3769                                         shsig->rsign = ptmp[1];
3770                                         tls1_lookup_sigalg(&shsig->hash_nid,
3771                                                 &shsig->sign_nid,
3772                                                 &shsig->signandhash_nid,
3773                                                 ptmp);
3774                                         shsig++;
3775                                         }
3776                                 break;
3777                                 }
3778                         }
3779                 }
3780         return nmatch;
3781         }
3782
3783 /* Set shared signature algorithms for SSL structures */
3784 static int tls1_set_shared_sigalgs(SSL *s)
3785         {
3786         const unsigned char *pref, *allow, *conf;
3787         size_t preflen, allowlen, conflen;
3788         size_t nmatch;
3789         TLS_SIGALGS *salgs = NULL;
3790         CERT *c = s->cert;
3791         unsigned int is_suiteb = tls1_suiteb(s);
3792         if (c->shared_sigalgs)
3793                 {
3794                 OPENSSL_free(c->shared_sigalgs);
3795                 c->shared_sigalgs = NULL;
3796                 }
3797         /* If client use client signature algorithms if not NULL */
3798         if (!s->server && c->client_sigalgs && !is_suiteb)
3799                 {
3800                 conf = c->client_sigalgs;
3801                 conflen = c->client_sigalgslen;
3802                 }
3803         else if (c->conf_sigalgs && !is_suiteb)
3804                 {
3805                 conf = c->conf_sigalgs;
3806                 conflen = c->conf_sigalgslen;
3807                 }
3808         else
3809                 conflen = tls12_get_psigalgs(s, &conf);
3810         if(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE || is_suiteb)
3811                 {
3812                 pref = conf;
3813                 preflen = conflen;
3814                 allow = c->peer_sigalgs;
3815                 allowlen = c->peer_sigalgslen;
3816                 }
3817         else
3818                 {
3819                 allow = conf;
3820                 allowlen = conflen;
3821                 pref = c->peer_sigalgs;
3822                 preflen = c->peer_sigalgslen;
3823                 }
3824         nmatch = tls12_do_shared_sigalgs(NULL, pref, preflen, allow, allowlen);
3825         if (!nmatch)
3826                 return 1;
3827         salgs = OPENSSL_malloc(nmatch * sizeof(TLS_SIGALGS));
3828         if (!salgs)
3829                 return 0;
3830         nmatch = tls12_do_shared_sigalgs(salgs, pref, preflen, allow, allowlen);
3831         c->shared_sigalgs = salgs;
3832         c->shared_sigalgslen = nmatch;
3833         return 1;
3834         }
3835                 
3836
3837 /* Set preferred digest for each key type */
3838
3839 int tls1_save_sigalgs(SSL *s, const unsigned char *data, int dsize)
3840         {
3841         CERT *c = s->cert;
3842         /* Extension ignored for inappropriate versions */
3843         if (!SSL_USE_SIGALGS(s))
3844                 return 1;
3845         /* Should never happen */
3846         if (!c)
3847                 return 0;
3848
3849         if (c->peer_sigalgs)
3850                 OPENSSL_free(c->peer_sigalgs);
3851         c->peer_sigalgs = OPENSSL_malloc(dsize);
3852         if (!c->peer_sigalgs)
3853                 return 0;
3854         c->peer_sigalgslen = dsize;
3855         memcpy(c->peer_sigalgs, data, dsize);
3856         return 1;
3857         }
3858
3859 int tls1_process_sigalgs(SSL *s)
3860         {
3861         int idx;
3862         size_t i;
3863         const EVP_MD *md;
3864         CERT *c = s->cert;
3865         TLS_SIGALGS *sigptr;
3866         if (!tls1_set_shared_sigalgs(s))
3867                 return 0;
3868
3869 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
3870         if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
3871                 {
3872                 /* Use first set signature preference to force message
3873                  * digest, ignoring any peer preferences.
3874                  */
3875                 const unsigned char *sigs = NULL;
3876                 if (s->server)
3877                         sigs = c->conf_sigalgs;
3878                 else
3879                         sigs = c->client_sigalgs;
3880                 if (sigs)
3881                         {
3882                         idx = tls12_get_pkey_idx(sigs[1]);
3883                         md = tls12_get_hash(sigs[0]);
3884                         c->pkeys[idx].digest = md;
3885                         c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3886                         if (idx == SSL_PKEY_RSA_SIGN)
3887                                 {
3888                                 c->pkeys[SSL_PKEY_RSA_ENC].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3889                                 c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
3890                                 }
3891                         }
3892                 }
3893 #endif
3894
3895         for (i = 0, sigptr = c->shared_sigalgs;
3896                         i < c->shared_sigalgslen; i++, sigptr++)
3897                 {
3898                 idx = tls12_get_pkey_idx(sigptr->rsign);
3899                 if (idx > 0 && c->pkeys[idx].digest == NULL)
3900                         {
3901                         md = tls12_get_hash(sigptr->rhash);
3902                         c->pkeys[idx].digest = md;
3903                         c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3904                         if (idx == SSL_PKEY_RSA_SIGN)
3905                                 {
3906                                 c->pkeys[SSL_PKEY_RSA_ENC].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3907                                 c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
3908                                 }
3909                         }
3910
3911                 }
3912         /* In strict mode leave unset digests as NULL to indicate we can't
3913          * use the certificate for signing.
3914          */
3915         if (!(s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT))
3916                 {
3917                 /* Set any remaining keys to default values. NOTE: if alg is
3918                  * not supported it stays as NULL.
3919                  */
3920 #ifndef OPENSSL_NO_DSA
3921                 if (!c->pkeys[SSL_PKEY_DSA_SIGN].digest)
3922                         c->pkeys[SSL_PKEY_DSA_SIGN].digest = EVP_sha1();
3923 #endif
3924 #ifndef OPENSSL_NO_RSA
3925                 if (!c->pkeys[SSL_PKEY_RSA_SIGN].digest)
3926                         {
3927                         c->pkeys[SSL_PKEY_RSA_SIGN].digest = EVP_sha1();
3928                         c->pkeys[SSL_PKEY_RSA_ENC].digest = EVP_sha1();
3929                         }
3930 #endif
3931 #ifndef OPENSSL_NO_ECDSA
3932                 if (!c->pkeys[SSL_PKEY_ECC].digest)
3933                         c->pkeys[SSL_PKEY_ECC].digest = EVP_sha1();
3934 #endif
3935                 }
3936         return 1;
3937         }
3938
3939
3940 int SSL_get_sigalgs(SSL *s, int idx,
3941                         int *psign, int *phash, int *psignhash,
3942                         unsigned char *rsig, unsigned char *rhash)
3943         {
3944         const unsigned char *psig = s->cert->peer_sigalgs;
3945         if (psig == NULL)
3946                 return 0;
3947         if (idx >= 0)
3948                 {
3949                 idx <<= 1;
3950                 if (idx >= (int)s->cert->peer_sigalgslen)
3951                         return 0;
3952                 psig += idx;
3953                 if (rhash)
3954                         *rhash = psig[0];
3955                 if (rsig)
3956                         *rsig = psig[1];
3957                 tls1_lookup_sigalg(phash, psign, psignhash, psig);
3958                 }
3959         return s->cert->peer_sigalgslen / 2;
3960         }
3961
3962 int SSL_get_shared_sigalgs(SSL *s, int idx,
3963                         int *psign, int *phash, int *psignhash,
3964                         unsigned char *rsig, unsigned char *rhash)
3965         {
3966         TLS_SIGALGS *shsigalgs = s->cert->shared_sigalgs;
3967         if (!shsigalgs || idx >= (int)s->cert->shared_sigalgslen)
3968                 return 0;
3969         shsigalgs += idx;
3970         if (phash)
3971                 *phash = shsigalgs->hash_nid;
3972         if (psign)
3973                 *psign = shsigalgs->sign_nid;
3974         if (psignhash)
3975                 *psignhash = shsigalgs->signandhash_nid;
3976         if (rsig)
3977                 *rsig = shsigalgs->rsign;
3978         if (rhash)
3979                 *rhash = shsigalgs->rhash;
3980         return s->cert->shared_sigalgslen;
3981         }
3982         
3983
3984 #ifndef OPENSSL_NO_HEARTBEATS
3985 int
3986 tls1_process_heartbeat(SSL *s)
3987         {
3988         unsigned char *p = &s->s3->rrec.data[0], *pl;
3989         unsigned short hbtype;
3990         unsigned int payload;
3991         unsigned int padding = 16; /* Use minimum padding */
3992
3993         if (s->msg_callback)
3994                 s->msg_callback(0, s->version, TLS1_RT_HEARTBEAT,
3995                         &s->s3->rrec.data[0], s->s3->rrec.length,
3996                         s, s->msg_callback_arg);
3997
3998         /* Read type and payload length first */
3999         if (1 + 2 + 16 > s->s3->rrec.length)
4000                 return 0; /* silently discard */
4001         hbtype = *p++;
4002         n2s(p, payload);
4003         if (1 + 2 + payload + 16 > s->s3->rrec.length)
4004                 return 0; /* silently discard per RFC 6520 sec. 4 */
4005         pl = p;
4006
4007         if (hbtype == TLS1_HB_REQUEST)
4008                 {
4009                 unsigned char *buffer, *bp;
4010                 int r;
4011
4012                 /* Allocate memory for the response, size is 1 bytes
4013                  * message type, plus 2 bytes payload length, plus
4014                  * payload, plus padding
4015                  */
4016                 buffer = OPENSSL_malloc(1 + 2 + payload + padding);
4017                 bp = buffer;
4018                 
4019                 /* Enter response type, length and copy payload */
4020                 *bp++ = TLS1_HB_RESPONSE;
4021                 s2n(payload, bp);
4022                 memcpy(bp, pl, payload);
4023                 bp += payload;
4024                 /* Random padding */
4025                 RAND_pseudo_bytes(bp, padding);
4026
4027                 r = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buffer, 3 + payload + padding);
4028
4029                 if (r >= 0 && s->msg_callback)
4030                         s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
4031                                 buffer, 3 + payload + padding,
4032                                 s, s->msg_callback_arg);
4033
4034                 OPENSSL_free(buffer);
4035
4036                 if (r < 0)
4037                         return r;
4038                 }
4039         else if (hbtype == TLS1_HB_RESPONSE)
4040                 {
4041                 unsigned int seq;
4042                 
4043                 /* We only send sequence numbers (2 bytes unsigned int),
4044                  * and 16 random bytes, so we just try to read the
4045                  * sequence number */
4046                 n2s(pl, seq);
4047                 
4048                 if (payload == 18 && seq == s->tlsext_hb_seq)
4049                         {
4050                         s->tlsext_hb_seq++;
4051                         s->tlsext_hb_pending = 0;
4052                         }
4053                 }
4054
4055         return 0;
4056         }
4057
4058 int
4059 tls1_heartbeat(SSL *s)
4060         {
4061         unsigned char *buf, *p;
4062         int ret;
4063         unsigned int payload = 18; /* Sequence number + random bytes */
4064         unsigned int padding = 16; /* Use minimum padding */
4065
4066         /* Only send if peer supports and accepts HB requests... */
4067         if (!(s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) ||
4068             s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_SEND_REQUESTS)
4069                 {
4070                 SSLerr(SSL_F_TLS1_HEARTBEAT,SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT);
4071                 return -1;
4072                 }
4073
4074         /* ...and there is none in flight yet... */
4075         if (s->tlsext_hb_pending)
4076                 {
4077                 SSLerr(SSL_F_TLS1_HEARTBEAT,SSL_R_TLS_HEARTBEAT_PENDING);
4078                 return -1;
4079                 }
4080                 
4081         /* ...and no handshake in progress. */
4082         if (SSL_in_init(s) || s->in_handshake)
4083                 {
4084                 SSLerr(SSL_F_TLS1_HEARTBEAT,SSL_R_UNEXPECTED_MESSAGE);
4085                 return -1;
4086                 }
4087                 
4088         /* Check if padding is too long, payload and padding
4089          * must not exceed 2^14 - 3 = 16381 bytes in total.
4090          */
4091         OPENSSL_assert(payload + padding <= 16381);
4092
4093         /*-
4094          * Create HeartBeat message, we just use a sequence number
4095          * as payload to distuingish different messages and add
4096          * some random stuff.
4097          *  - Message Type, 1 byte
4098          *  - Payload Length, 2 bytes (unsigned int)
4099          *  - Payload, the sequence number (2 bytes uint)
4100          *  - Payload, random bytes (16 bytes uint)
4101          *  - Padding
4102          */
4103         buf = OPENSSL_malloc(1 + 2 + payload + padding);
4104         p = buf;
4105         /* Message Type */
4106         *p++ = TLS1_HB_REQUEST;
4107         /* Payload length (18 bytes here) */
4108         s2n(payload, p);
4109         /* Sequence number */
4110         s2n(s->tlsext_hb_seq, p);
4111         /* 16 random bytes */
4112         RAND_pseudo_bytes(p, 16);
4113         p += 16;
4114         /* Random padding */
4115         RAND_pseudo_bytes(p, padding);
4116
4117         ret = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buf, 3 + payload + padding);
4118         if (ret >= 0)
4119                 {
4120                 if (s->msg_callback)
4121                         s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
4122                                 buf, 3 + payload + padding,
4123                                 s, s->msg_callback_arg);
4124
4125                 s->tlsext_hb_pending = 1;
4126                 }
4127                 
4128         OPENSSL_free(buf);
4129
4130         return ret;
4131         }
4132 #endif
4133
4134 #define MAX_SIGALGLEN   (TLSEXT_hash_num * TLSEXT_signature_num * 2)
4135
4136 typedef struct
4137         {
4138         size_t sigalgcnt;
4139         int sigalgs[MAX_SIGALGLEN];
4140         } sig_cb_st;
4141
4142 static int sig_cb(const char *elem, int len, void *arg)
4143         {
4144         sig_cb_st *sarg = arg;
4145         size_t i;
4146         char etmp[20], *p;
4147         int sig_alg, hash_alg;
4148         if (sarg->sigalgcnt == MAX_SIGALGLEN)
4149                 return 0;
4150         if (len > (int)(sizeof(etmp) - 1))
4151                 return 0;
4152         memcpy(etmp, elem, len);
4153         etmp[len] = 0;
4154         p = strchr(etmp, '+');
4155         if (!p)
4156                 return 0;
4157         *p = 0;
4158         p++;
4159         if (!*p)
4160                 return 0;
4161
4162         if (!strcmp(etmp, "RSA"))
4163                 sig_alg = EVP_PKEY_RSA;
4164         else if (!strcmp(etmp, "DSA"))
4165                 sig_alg = EVP_PKEY_DSA;
4166         else if (!strcmp(etmp, "ECDSA"))
4167                 sig_alg = EVP_PKEY_EC;
4168         else return 0;
4169
4170         hash_alg = OBJ_sn2nid(p);
4171         if (hash_alg == NID_undef)
4172                 hash_alg = OBJ_ln2nid(p);
4173         if (hash_alg == NID_undef)
4174                 return 0;
4175
4176         for (i = 0; i < sarg->sigalgcnt; i+=2)
4177                 {
4178                 if (sarg->sigalgs[i] == sig_alg
4179                         && sarg->sigalgs[i + 1] == hash_alg)
4180                         return 0;
4181                 }
4182         sarg->sigalgs[sarg->sigalgcnt++] = hash_alg;
4183         sarg->sigalgs[sarg->sigalgcnt++] = sig_alg;
4184         return 1;
4185         }
4186
4187 /* Set suppored signature algorithms based on a colon separated list
4188  * of the form sig+hash e.g. RSA+SHA512:DSA+SHA512 */
4189 int tls1_set_sigalgs_list(CERT *c, const char *str, int client)
4190         {
4191         sig_cb_st sig;
4192         sig.sigalgcnt = 0;
4193         if (!CONF_parse_list(str, ':', 1, sig_cb, &sig))
4194                 return 0;
4195         if (c == NULL)
4196                 return 1;
4197         return tls1_set_sigalgs(c, sig.sigalgs, sig.sigalgcnt, client);
4198         }
4199
4200 int tls1_set_sigalgs(CERT *c, const int *psig_nids, size_t salglen, int client)
4201         {
4202         unsigned char *sigalgs, *sptr;
4203         int rhash, rsign;
4204         size_t i;
4205         if (salglen & 1)
4206                 return 0;
4207         sigalgs = OPENSSL_malloc(salglen);
4208         if (sigalgs == NULL)
4209                 return 0;
4210         for (i = 0, sptr = sigalgs; i < salglen; i+=2)
4211                 {
4212                 rhash = tls12_find_id(*psig_nids++, tls12_md,
4213                                         sizeof(tls12_md)/sizeof(tls12_lookup));
4214                 rsign = tls12_find_id(*psig_nids++, tls12_sig,
4215                                 sizeof(tls12_sig)/sizeof(tls12_lookup));
4216
4217                 if (rhash == -1 || rsign == -1)
4218                         goto err;
4219                 *sptr++ = rhash;
4220                 *sptr++ = rsign;
4221                 }
4222
4223         if (client)
4224                 {
4225                 if (c->client_sigalgs)
4226                         OPENSSL_free(c->client_sigalgs);
4227                 c->client_sigalgs = sigalgs;
4228                 c->client_sigalgslen = salglen;
4229                 }
4230         else
4231                 {
4232                 if (c->conf_sigalgs)
4233                         OPENSSL_free(c->conf_sigalgs);
4234                 c->conf_sigalgs = sigalgs;
4235                 c->conf_sigalgslen = salglen;
4236                 }
4237
4238         return 1;
4239
4240         err:
4241         OPENSSL_free(sigalgs);
4242         return 0;
4243         }
4244
4245 static int tls1_check_sig_alg(CERT *c, X509 *x, int default_nid)
4246         {
4247         int sig_nid;
4248         size_t i;
4249         if (default_nid == -1)
4250                 return 1;
4251         sig_nid = X509_get_signature_nid(x);
4252         if (default_nid)
4253                 return sig_nid == default_nid ? 1 : 0;
4254         for (i = 0; i < c->shared_sigalgslen; i++)
4255                 if (sig_nid == c->shared_sigalgs[i].signandhash_nid)
4256                         return 1;
4257         return 0;
4258         }
4259 /* Check to see if a certificate issuer name matches list of CA names */
4260 static int ssl_check_ca_name(STACK_OF(X509_NAME) *names, X509 *x)
4261         {
4262         X509_NAME *nm;
4263         int i;
4264         nm = X509_get_issuer_name(x);
4265         for (i = 0; i < sk_X509_NAME_num(names); i++)
4266                 {
4267                 if(!X509_NAME_cmp(nm, sk_X509_NAME_value(names, i)))
4268                         return 1;
4269                 }
4270         return 0;
4271         }
4272
4273 /* Check certificate chain is consistent with TLS extensions and is
4274  * usable by server. This servers two purposes: it allows users to 
4275  * check chains before passing them to the server and it allows the
4276  * server to check chains before attempting to use them.
4277  */
4278
4279 /* Flags which need to be set for a certificate when stict mode not set */
4280
4281 #define CERT_PKEY_VALID_FLAGS \
4282         (CERT_PKEY_EE_SIGNATURE|CERT_PKEY_EE_PARAM)
4283 /* Strict mode flags */
4284 #define CERT_PKEY_STRICT_FLAGS \
4285          (CERT_PKEY_VALID_FLAGS|CERT_PKEY_CA_SIGNATURE|CERT_PKEY_CA_PARAM \
4286          | CERT_PKEY_ISSUER_NAME|CERT_PKEY_CERT_TYPE)
4287
4288 int tls1_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain,
4289                                                                         int idx)
4290         {
4291         int i;
4292         int rv = 0;
4293         int check_flags = 0, strict_mode;
4294         CERT_PKEY *cpk = NULL;
4295         CERT *c = s->cert;
4296         unsigned int suiteb_flags = tls1_suiteb(s);
4297         /* idx == -1 means checking server chains */
4298         if (idx != -1)
4299                 {
4300                 /* idx == -2 means checking client certificate chains */
4301                 if (idx == -2)
4302                         {
4303                         cpk = c->key;
4304                         idx = cpk - c->pkeys;
4305                         }
4306                 else
4307                         cpk = c->pkeys + idx;
4308                 x = cpk->x509;
4309                 pk = cpk->privatekey;
4310                 chain = cpk->chain;
4311                 strict_mode = c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT;
4312                 /* If no cert or key, forget it */
4313                 if (!x || !pk)
4314                         goto end;
4315 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
4316                 /* Allow any certificate to pass test */
4317                 if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
4318                         {
4319                         rv = CERT_PKEY_STRICT_FLAGS|CERT_PKEY_EXPLICIT_SIGN|CERT_PKEY_VALID|CERT_PKEY_SIGN;
4320                         cpk->valid_flags = rv;
4321                         return rv;
4322                         }
4323 #endif
4324                 }
4325         else
4326                 {
4327                 if (!x || !pk)
4328                         goto end;
4329                 idx = ssl_cert_type(x, pk);
4330                 if (idx == -1)
4331                         goto end;
4332                 cpk = c->pkeys + idx;
4333                 if (c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)
4334                         check_flags = CERT_PKEY_STRICT_FLAGS;
4335                 else
4336                         check_flags = CERT_PKEY_VALID_FLAGS;
4337                 strict_mode = 1;
4338                 }
4339
4340         if (suiteb_flags)
4341                 {
4342                 int ok;
4343                 if (check_flags)
4344                         check_flags |= CERT_PKEY_SUITEB;
4345                 ok = X509_chain_check_suiteb(NULL, x, chain, suiteb_flags);
4346                 if (ok == X509_V_OK)
4347                         rv |= CERT_PKEY_SUITEB;
4348                 else if (!check_flags)
4349                         goto end;
4350                 }
4351
4352         /* Check all signature algorithms are consistent with
4353          * signature algorithms extension if TLS 1.2 or later
4354          * and strict mode.
4355          */
4356         if (TLS1_get_version(s) >= TLS1_2_VERSION && strict_mode)
4357                 {
4358                 int default_nid;
4359                 unsigned char rsign = 0;
4360                 if (c->peer_sigalgs)
4361                         default_nid = 0;
4362                 /* If no sigalgs extension use defaults from RFC5246 */
4363                 else
4364                         {
4365                         switch(idx)
4366                                 {       
4367                         case SSL_PKEY_RSA_ENC:
4368                         case SSL_PKEY_RSA_SIGN:
4369                         case SSL_PKEY_DH_RSA:
4370                                 rsign = TLSEXT_signature_rsa;
4371                                 default_nid = NID_sha1WithRSAEncryption;
4372                                 break;
4373
4374                         case SSL_PKEY_DSA_SIGN:
4375                         case SSL_PKEY_DH_DSA:
4376                                 rsign = TLSEXT_signature_dsa;
4377                                 default_nid = NID_dsaWithSHA1;
4378                                 break;
4379
4380                         case SSL_PKEY_ECC:
4381                                 rsign = TLSEXT_signature_ecdsa;
4382                                 default_nid = NID_ecdsa_with_SHA1;
4383                                 break;
4384
4385                         default:
4386                                 default_nid = -1;
4387                                 break;
4388                                 }
4389                         }
4390                 /* If peer sent no signature algorithms extension and we
4391                  * have set preferred signature algorithms check we support
4392                  * sha1.
4393                  */
4394                 if (default_nid > 0 && c->conf_sigalgs)
4395                         {
4396                         size_t j;
4397                         const unsigned char *p = c->conf_sigalgs;
4398                         for (j = 0; j < c->conf_sigalgslen; j += 2, p += 2)
4399                                 {
4400                                 if (p[0] == TLSEXT_hash_sha1 && p[1] == rsign)
4401                                         break;
4402                                 }
4403                         if (j == c->conf_sigalgslen)
4404                                 {
4405                                 if (check_flags)
4406                                         goto skip_sigs;
4407                                 else
4408                                         goto end;
4409                                 }
4410                         }
4411                 /* Check signature algorithm of each cert in chain */
4412                 if (!tls1_check_sig_alg(c, x, default_nid))
4413                         {
4414                         if (!check_flags) goto end;
4415                         }
4416                 else
4417                         rv |= CERT_PKEY_EE_SIGNATURE;
4418                 rv |= CERT_PKEY_CA_SIGNATURE;
4419                 for (i = 0; i < sk_X509_num(chain); i++)
4420                         {
4421                         if (!tls1_check_sig_alg(c, sk_X509_value(chain, i),
4422                                                         default_nid))
4423                                 {
4424                                 if (check_flags)
4425                                         {
4426                                         rv &= ~CERT_PKEY_CA_SIGNATURE;
4427                                         break;
4428                                         }
4429                                 else
4430                                         goto end;
4431                                 }
4432                         }
4433                 }
4434         /* Else not TLS 1.2, so mark EE and CA signing algorithms OK */
4435         else if(check_flags)
4436                 rv |= CERT_PKEY_EE_SIGNATURE|CERT_PKEY_CA_SIGNATURE;
4437         skip_sigs:
4438         /* Check cert parameters are consistent */
4439         if (tls1_check_cert_param(s, x, check_flags ? 1 : 2))
4440                 rv |= CERT_PKEY_EE_PARAM;
4441         else if (!check_flags)
4442                 goto end;
4443         if (!s->server)
4444                 rv |= CERT_PKEY_CA_PARAM;
4445         /* In strict mode check rest of chain too */
4446         else if (strict_mode)
4447                 {
4448                 rv |= CERT_PKEY_CA_PARAM;
4449                 for (i = 0; i < sk_X509_num(chain); i++)
4450                         {
4451                         X509 *ca = sk_X509_value(chain, i);
4452                         if (!tls1_check_cert_param(s, ca, 0))
4453                                 {
4454                                 if (check_flags)
4455                                         {
4456                                         rv &= ~CERT_PKEY_CA_PARAM;
4457                                         break;
4458                                         }
4459                                 else
4460                                         goto end;
4461                                 }
4462                         }
4463                 }
4464         if (!s->server && strict_mode)
4465                 {
4466                 STACK_OF(X509_NAME) *ca_dn;
4467                 int check_type = 0;
4468                 switch (pk->type)
4469                         {
4470                 case EVP_PKEY_RSA:
4471                         check_type = TLS_CT_RSA_SIGN;
4472                         break;
4473                 case EVP_PKEY_DSA:
4474                         check_type = TLS_CT_DSS_SIGN;
4475                         break;
4476                 case EVP_PKEY_EC:
4477                         check_type = TLS_CT_ECDSA_SIGN;
4478                         break;
4479                 case EVP_PKEY_DH:
4480                 case EVP_PKEY_DHX:
4481                                 {
4482                                 int cert_type = X509_certificate_type(x, pk);
4483                                 if (cert_type & EVP_PKS_RSA)
4484                                         check_type = TLS_CT_RSA_FIXED_DH;
4485                                 if (cert_type & EVP_PKS_DSA)
4486                                         check_type = TLS_CT_DSS_FIXED_DH;
4487                                 }
4488                         }
4489                 if (check_type)
4490                         {
4491                         const unsigned char *ctypes;
4492                         int ctypelen;
4493                         if (c->ctypes)
4494                                 {
4495                                 ctypes = c->ctypes;
4496                                 ctypelen = (int)c->ctype_num;
4497                                 }
4498                         else
4499                                 {
4500                                 ctypes = (unsigned char *)s->s3->tmp.ctype;
4501                                 ctypelen = s->s3->tmp.ctype_num;
4502                                 }
4503                         for (i = 0; i < ctypelen; i++)
4504                                 {
4505                                 if (ctypes[i] == check_type)
4506                                         {
4507                                         rv |= CERT_PKEY_CERT_TYPE;
4508                                         break;
4509                                         }
4510                                 }
4511                         if (!(rv & CERT_PKEY_CERT_TYPE) && !check_flags)
4512                                 goto end;
4513                         }
4514                 else
4515                         rv |= CERT_PKEY_CERT_TYPE;
4516
4517
4518                 ca_dn = s->s3->tmp.ca_names;
4519
4520                 if (!sk_X509_NAME_num(ca_dn))
4521                         rv |= CERT_PKEY_ISSUER_NAME;
4522
4523                 if (!(rv & CERT_PKEY_ISSUER_NAME))
4524                         {
4525                         if (ssl_check_ca_name(ca_dn, x))
4526                                 rv |= CERT_PKEY_ISSUER_NAME;
4527                         }
4528                 if (!(rv & CERT_PKEY_ISSUER_NAME))
4529                         {
4530                         for (i = 0; i < sk_X509_num(chain); i++)
4531                                 {
4532                                 X509 *xtmp = sk_X509_value(chain, i);
4533                                 if (ssl_check_ca_name(ca_dn, xtmp))
4534                                         {
4535                                         rv |= CERT_PKEY_ISSUER_NAME;
4536                                         break;
4537                                         }
4538                                 }
4539                         }
4540                 if (!check_flags && !(rv & CERT_PKEY_ISSUER_NAME))
4541                         goto end;
4542                 }
4543         else
4544                 rv |= CERT_PKEY_ISSUER_NAME|CERT_PKEY_CERT_TYPE;
4545
4546         if (!check_flags || (rv & check_flags) == check_flags)
4547                 rv |= CERT_PKEY_VALID;
4548
4549         end:
4550
4551         if (TLS1_get_version(s) >= TLS1_2_VERSION)
4552                 {
4553                 if (cpk->valid_flags & CERT_PKEY_EXPLICIT_SIGN)
4554                         rv |= CERT_PKEY_EXPLICIT_SIGN|CERT_PKEY_SIGN;
4555                 else if (cpk->digest)
4556                         rv |= CERT_PKEY_SIGN;
4557                 }
4558         else
4559                 rv |= CERT_PKEY_SIGN|CERT_PKEY_EXPLICIT_SIGN;
4560
4561         /* When checking a CERT_PKEY structure all flags are irrelevant
4562          * if the chain is invalid.
4563          */
4564         if (!check_flags)
4565                 {
4566                 if (rv & CERT_PKEY_VALID)
4567                         cpk->valid_flags = rv;
4568                 else
4569                         {
4570                         /* Preserve explicit sign flag, clear rest */
4571                         cpk->valid_flags &= CERT_PKEY_EXPLICIT_SIGN;
4572                         return 0;
4573                         }
4574                 }
4575         return rv;
4576         }
4577
4578 /* Set validity of certificates in an SSL structure */
4579 void tls1_set_cert_validity(SSL *s)
4580         {
4581         tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_ENC);
4582         tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_SIGN);
4583         tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DSA_SIGN);
4584         tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DH_RSA);
4585         tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DH_DSA);
4586         tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_ECC);
4587         }
4588 /* User level utiity function to check a chain is suitable */
4589 int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain)
4590         {
4591         return tls1_check_chain(s, x, pk, chain, -1);
4592         }
4593
4594 #endif