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