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