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