Verify that we have a sensible message len and fail if not
[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         s->tlsext_ticket_expected = 0;
2564
2565         if (s->s3->alpn_selected)
2566                 {
2567                 OPENSSL_free(s->s3->alpn_selected);
2568                 s->s3->alpn_selected = NULL;
2569                 }
2570
2571 #ifndef OPENSSL_NO_HEARTBEATS
2572         s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
2573                                SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
2574 #endif
2575
2576         if (data >= (d+n-2))
2577                 goto ri_check;
2578
2579         n2s(data,length);
2580         if (data+length != d+n)
2581                 {
2582                 *al = SSL_AD_DECODE_ERROR;
2583                 return 0;
2584                 }
2585
2586         while(data <= (d+n-4))
2587                 {
2588                 n2s(data,type);
2589                 n2s(data,size);
2590
2591                 if (data+size > (d+n))
2592                         goto ri_check;
2593
2594                 if (s->tlsext_debug_cb)
2595                         s->tlsext_debug_cb(s, 1, type, data, size,
2596                                                 s->tlsext_debug_arg);
2597
2598                 if (type == TLSEXT_TYPE_server_name)
2599                         {
2600                         if (s->tlsext_hostname == NULL || size > 0)
2601                                 {
2602                                 *al = TLS1_AD_UNRECOGNIZED_NAME;
2603                                 return 0;
2604                                 }
2605                         tlsext_servername = 1;   
2606                         }
2607
2608 #ifndef OPENSSL_NO_EC
2609                 else if (type == TLSEXT_TYPE_ec_point_formats)
2610                         {
2611                         unsigned char *sdata = data;
2612                         int ecpointformatlist_length = *(sdata++);
2613
2614                         if (ecpointformatlist_length != size - 1)
2615                                 {
2616                                 *al = TLS1_AD_DECODE_ERROR;
2617                                 return 0;
2618                                 }
2619                         if (!s->hit)
2620                                 {
2621                                 s->session->tlsext_ecpointformatlist_length = 0;
2622                                 if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist);
2623                                 if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
2624                                         {
2625                                         *al = TLS1_AD_INTERNAL_ERROR;
2626                                         return 0;
2627                                         }
2628                                 s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
2629                                 memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
2630                                 }
2631 #if 0
2632                         fprintf(stderr,"ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist ");
2633                         sdata = s->session->tlsext_ecpointformatlist;
2634                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2635                                 fprintf(stderr,"%i ",*(sdata++));
2636                         fprintf(stderr,"\n");
2637 #endif
2638                         }
2639 #endif /* OPENSSL_NO_EC */
2640
2641                 else if (type == TLSEXT_TYPE_session_ticket)
2642                         {
2643                         if (s->tls_session_ticket_ext_cb &&
2644                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
2645                                 {
2646                                 *al = TLS1_AD_INTERNAL_ERROR;
2647                                 return 0;
2648                                 }
2649                         if ((SSL_get_options(s) & SSL_OP_NO_TICKET)
2650                                 || (size > 0))
2651                                 {
2652                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2653                                 return 0;
2654                                 }
2655                         s->tlsext_ticket_expected = 1;
2656                         }
2657 #ifdef TLSEXT_TYPE_opaque_prf_input
2658                 else if (type == TLSEXT_TYPE_opaque_prf_input)
2659                         {
2660                         unsigned char *sdata = data;
2661
2662                         if (size < 2)
2663                                 {
2664                                 *al = SSL_AD_DECODE_ERROR;
2665                                 return 0;
2666                                 }
2667                         n2s(sdata, s->s3->server_opaque_prf_input_len);
2668                         if (s->s3->server_opaque_prf_input_len != size - 2)
2669                                 {
2670                                 *al = SSL_AD_DECODE_ERROR;
2671                                 return 0;
2672                                 }
2673                         
2674                         if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
2675                                 OPENSSL_free(s->s3->server_opaque_prf_input);
2676                         if (s->s3->server_opaque_prf_input_len == 0)
2677                                 s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2678                         else
2679                                 s->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len);
2680
2681                         if (s->s3->server_opaque_prf_input == NULL)
2682                                 {
2683                                 *al = TLS1_AD_INTERNAL_ERROR;
2684                                 return 0;
2685                                 }
2686                         }
2687 #endif
2688                 else if (type == TLSEXT_TYPE_status_request)
2689                         {
2690                         /* MUST be empty and only sent if we've requested
2691                          * a status request message.
2692                          */ 
2693                         if ((s->tlsext_status_type == -1) || (size > 0))
2694                                 {
2695                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2696                                 return 0;
2697                                 }
2698                         /* Set flag to expect CertificateStatus message */
2699                         s->tlsext_status_expected = 1;
2700                         }
2701 #ifndef OPENSSL_NO_NEXTPROTONEG
2702                 else if (type == TLSEXT_TYPE_next_proto_neg &&
2703                          s->s3->tmp.finish_md_len == 0)
2704                         {
2705                         unsigned char *selected;
2706                         unsigned char selected_len;
2707
2708                         /* We must have requested it. */
2709                         if (s->ctx->next_proto_select_cb == NULL)
2710                                 {
2711                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2712                                 return 0;
2713                                 }
2714                         /* The data must be valid */
2715                         if (!ssl_next_proto_validate(data, size))
2716                                 {
2717                                 *al = TLS1_AD_DECODE_ERROR;
2718                                 return 0;
2719                                 }
2720                         if (s->ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK)
2721                                 {
2722                                 *al = TLS1_AD_INTERNAL_ERROR;
2723                                 return 0;
2724                                 }
2725                         s->next_proto_negotiated = OPENSSL_malloc(selected_len);
2726                         if (!s->next_proto_negotiated)
2727                                 {
2728                                 *al = TLS1_AD_INTERNAL_ERROR;
2729                                 return 0;
2730                                 }
2731                         memcpy(s->next_proto_negotiated, selected, selected_len);
2732                         s->next_proto_negotiated_len = selected_len;
2733                         s->s3->next_proto_neg_seen = 1;
2734                         }
2735 #endif
2736
2737                 else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation)
2738                         {
2739                         unsigned len;
2740
2741                         /* We must have requested it. */
2742                         if (s->alpn_client_proto_list == NULL)
2743                                 {
2744                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2745                                 return 0;
2746                                 }
2747                         if (size < 4)
2748                                 {
2749                                 *al = TLS1_AD_DECODE_ERROR;
2750                                 return 0;
2751                                 }
2752                         /* The extension data consists of:
2753                          *   uint16 list_length
2754                          *   uint8 proto_length;
2755                          *   uint8 proto[proto_length]; */
2756                         len = data[0];
2757                         len <<= 8;
2758                         len |= data[1];
2759                         if (len != (unsigned) size - 2)
2760                                 {
2761                                 *al = TLS1_AD_DECODE_ERROR;
2762                                 return 0;
2763                                 }
2764                         len = data[2];
2765                         if (len != (unsigned) size - 3)
2766                                 {
2767                                 *al = TLS1_AD_DECODE_ERROR;
2768                                 return 0;
2769                                 }
2770                         if (s->s3->alpn_selected)
2771                                 OPENSSL_free(s->s3->alpn_selected);
2772                         s->s3->alpn_selected = OPENSSL_malloc(len);
2773                         if (!s->s3->alpn_selected)
2774                                 {
2775                                 *al = TLS1_AD_INTERNAL_ERROR;
2776                                 return 0;
2777                                 }
2778                         memcpy(s->s3->alpn_selected, data + 3, len);
2779                         s->s3->alpn_selected_len = len;
2780                         }
2781
2782                 else if (type == TLSEXT_TYPE_renegotiate)
2783                         {
2784                         if(!ssl_parse_serverhello_renegotiate_ext(s, data, size, al))
2785                                 return 0;
2786                         renegotiate_seen = 1;
2787                         }
2788 #ifndef OPENSSL_NO_HEARTBEATS
2789                 else if (type == TLSEXT_TYPE_heartbeat)
2790                         {
2791                         switch(data[0])
2792                                 {
2793                                 case 0x01:      /* Server allows us to send HB requests */
2794                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2795                                                         break;
2796                                 case 0x02:      /* Server doesn't accept HB requests */
2797                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2798                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2799                                                         break;
2800                                 default:        *al = SSL_AD_ILLEGAL_PARAMETER;
2801                                                         return 0;
2802                                 }
2803                         }
2804 #endif
2805                 else if (SSL_IS_DTLS(s) && type == TLSEXT_TYPE_use_srtp)
2806                         {
2807                         if(ssl_parse_serverhello_use_srtp_ext(s, data, size,
2808                                                               al))
2809                                 return 0;
2810                         }
2811                 /* If this extension type was not otherwise handled, but 
2812                  * matches a custom_cli_ext_record, then send it to the c
2813                  * callback */
2814                 else if (custom_ext_parse(s, 0, type, data, size, al) <= 0)
2815                                 return 0;
2816  
2817                 data += size;
2818                 }
2819
2820         if (data != d+n)
2821                 {
2822                 *al = SSL_AD_DECODE_ERROR;
2823                 return 0;
2824                 }
2825
2826         if (!s->hit && tlsext_servername == 1)
2827                 {
2828                 if (s->tlsext_hostname)
2829                         {
2830                         if (s->session->tlsext_hostname == NULL)
2831                                 {
2832                                 s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);   
2833                                 if (!s->session->tlsext_hostname)
2834                                         {
2835                                         *al = SSL_AD_UNRECOGNIZED_NAME;
2836                                         return 0;
2837                                         }
2838                                 }
2839                         else 
2840                                 {
2841                                 *al = SSL_AD_DECODE_ERROR;
2842                                 return 0;
2843                                 }
2844                         }
2845                 }
2846
2847         *p = data;
2848
2849         ri_check:
2850
2851         /* Determine if we need to see RI. Strictly speaking if we want to
2852          * avoid an attack we should *always* see RI even on initial server
2853          * hello because the client doesn't see any renegotiation during an
2854          * attack. However this would mean we could not connect to any server
2855          * which doesn't support RI so for the immediate future tolerate RI
2856          * absence on initial connect only.
2857          */
2858         if (!renegotiate_seen
2859                 && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
2860                 && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
2861                 {
2862                 *al = SSL_AD_HANDSHAKE_FAILURE;
2863                 SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT,
2864                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2865                 return 0;
2866                 }
2867
2868         return 1;
2869         }
2870
2871
2872 int ssl_prepare_clienthello_tlsext(SSL *s)
2873         {
2874
2875 #ifdef TLSEXT_TYPE_opaque_prf_input
2876         {
2877                 int r = 1;
2878         
2879                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
2880                         {
2881                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
2882                         if (!r)
2883                                 return -1;
2884                         }
2885
2886                 if (s->tlsext_opaque_prf_input != NULL)
2887                         {
2888                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
2889                                 OPENSSL_free(s->s3->client_opaque_prf_input);
2890
2891                         if (s->tlsext_opaque_prf_input_len == 0)
2892                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2893                         else
2894                                 s->s3->client_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
2895                         if (s->s3->client_opaque_prf_input == NULL)
2896                                 {
2897                                 SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
2898                                 return -1;
2899                                 }
2900                         s->s3->client_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2901                         }
2902
2903                 if (r == 2)
2904                         /* at callback's request, insist on receiving an appropriate server opaque PRF input */
2905                         s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2906         }
2907 #endif
2908
2909         return 1;
2910         }
2911
2912 int ssl_prepare_serverhello_tlsext(SSL *s)
2913         {
2914         return 1;
2915         }
2916
2917 static int ssl_check_clienthello_tlsext_early(SSL *s)
2918         {
2919         int ret=SSL_TLSEXT_ERR_NOACK;
2920         int al = SSL_AD_UNRECOGNIZED_NAME;
2921
2922 #ifndef OPENSSL_NO_EC
2923         /* The handling of the ECPointFormats extension is done elsewhere, namely in 
2924          * ssl3_choose_cipher in s3_lib.c.
2925          */
2926         /* The handling of the EllipticCurves extension is done elsewhere, namely in 
2927          * ssl3_choose_cipher in s3_lib.c.
2928          */
2929 #endif
2930
2931         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
2932                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
2933         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
2934                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
2935
2936 #ifdef TLSEXT_TYPE_opaque_prf_input
2937         {
2938                 /* This sort of belongs into ssl_prepare_serverhello_tlsext(),
2939                  * but we might be sending an alert in response to the client hello,
2940                  * so this has to happen here in
2941                  * ssl_check_clienthello_tlsext_early(). */
2942
2943                 int r = 1;
2944         
2945                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
2946                         {
2947                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
2948                         if (!r)
2949                                 {
2950                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2951                                 al = SSL_AD_INTERNAL_ERROR;
2952                                 goto err;
2953                                 }
2954                         }
2955
2956                 if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
2957                         OPENSSL_free(s->s3->server_opaque_prf_input);
2958                 s->s3->server_opaque_prf_input = NULL;
2959
2960                 if (s->tlsext_opaque_prf_input != NULL)
2961                         {
2962                         if (s->s3->client_opaque_prf_input != NULL &&
2963                                 s->s3->client_opaque_prf_input_len == s->tlsext_opaque_prf_input_len)
2964                                 {
2965                                 /* can only use this extension if we have a server opaque PRF input
2966                                  * of the same length as the client opaque PRF input! */
2967
2968                                 if (s->tlsext_opaque_prf_input_len == 0)
2969                                         s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2970                                 else
2971                                         s->s3->server_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
2972                                 if (s->s3->server_opaque_prf_input == NULL)
2973                                         {
2974                                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2975                                         al = SSL_AD_INTERNAL_ERROR;
2976                                         goto err;
2977                                         }
2978                                 s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2979                                 }
2980                         }
2981
2982                 if (r == 2 && s->s3->server_opaque_prf_input == NULL)
2983                         {
2984                         /* The callback wants to enforce use of the extension,
2985                          * but we can't do that with the client opaque PRF input;
2986                          * abort the handshake.
2987                          */
2988                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2989                         al = SSL_AD_HANDSHAKE_FAILURE;
2990                         }
2991         }
2992
2993  err:
2994 #endif
2995         switch (ret)
2996                 {
2997                 case SSL_TLSEXT_ERR_ALERT_FATAL:
2998                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2999                         return -1;
3000
3001                 case SSL_TLSEXT_ERR_ALERT_WARNING:
3002                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
3003                         return 1; 
3004                                         
3005                 case SSL_TLSEXT_ERR_NOACK:
3006                         s->servername_done=0;
3007                         default:
3008                 return 1;
3009                 }
3010         }
3011
3012 int tls1_set_server_sigalgs(SSL *s)
3013         {
3014         int al;
3015         size_t i;
3016         /* Clear any shared sigtnature algorithms */
3017         if (s->cert->shared_sigalgs)
3018                 {
3019                 OPENSSL_free(s->cert->shared_sigalgs);
3020                 s->cert->shared_sigalgs = NULL;
3021                 }
3022         /* Clear certificate digests and validity flags */
3023         for (i = 0; i < SSL_PKEY_NUM; i++)
3024                 {
3025                 s->cert->pkeys[i].digest = NULL;
3026                 s->cert->pkeys[i].valid_flags = 0;
3027                 }
3028
3029         /* If sigalgs received process it. */
3030         if (s->cert->peer_sigalgs)
3031                 {
3032                 if (!tls1_process_sigalgs(s))
3033                         {
3034                         SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS,
3035                                         ERR_R_MALLOC_FAILURE);
3036                         al = SSL_AD_INTERNAL_ERROR;
3037                         goto err;
3038                         }
3039                 /* Fatal error is no shared signature algorithms */
3040                 if (!s->cert->shared_sigalgs)
3041                         {
3042                         SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS,
3043                                         SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
3044                         al = SSL_AD_ILLEGAL_PARAMETER;
3045                         goto err;
3046                         }
3047                 }
3048         else
3049                 ssl_cert_set_default_md(s->cert);
3050         return 1;
3051         err:
3052         ssl3_send_alert(s, SSL3_AL_FATAL, al);
3053         return 0;
3054         }
3055
3056 int ssl_check_clienthello_tlsext_late(SSL *s)
3057         {
3058         int ret = SSL_TLSEXT_ERR_OK;
3059         int al;
3060
3061         /* If status request then ask callback what to do.
3062          * Note: this must be called after servername callbacks in case
3063          * the certificate has changed, and must be called after the cipher
3064          * has been chosen because this may influence which certificate is sent
3065          */
3066         if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb)
3067                 {
3068                 int r;
3069                 CERT_PKEY *certpkey;
3070                 certpkey = ssl_get_server_send_pkey(s);
3071                 /* If no certificate can't return certificate status */
3072                 if (certpkey == NULL)
3073                         {
3074                         s->tlsext_status_expected = 0;
3075                         return 1;
3076                         }
3077                 /* Set current certificate to one we will use so
3078                  * SSL_get_certificate et al can pick it up.
3079                  */
3080                 s->cert->key = certpkey;
3081                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
3082                 switch (r)
3083                         {
3084                         /* We don't want to send a status request response */
3085                         case SSL_TLSEXT_ERR_NOACK:
3086                                 s->tlsext_status_expected = 0;
3087                                 break;
3088                         /* status request response should be sent */
3089                         case SSL_TLSEXT_ERR_OK:
3090                                 if (s->tlsext_ocsp_resp)
3091                                         s->tlsext_status_expected = 1;
3092                                 else
3093                                         s->tlsext_status_expected = 0;
3094                                 break;
3095                         /* something bad happened */
3096                         case SSL_TLSEXT_ERR_ALERT_FATAL:
3097                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3098                                 al = SSL_AD_INTERNAL_ERROR;
3099                                 goto err;
3100                         }
3101                 }
3102         else
3103                 s->tlsext_status_expected = 0;
3104
3105  err:
3106         switch (ret)
3107                 {
3108                 case SSL_TLSEXT_ERR_ALERT_FATAL:
3109                         ssl3_send_alert(s, SSL3_AL_FATAL, al);
3110                         return -1;
3111
3112                 case SSL_TLSEXT_ERR_ALERT_WARNING:
3113                         ssl3_send_alert(s, SSL3_AL_WARNING, al);
3114                         return 1; 
3115
3116                 default:
3117                         return 1;
3118                 }
3119         }
3120
3121 int ssl_check_serverhello_tlsext(SSL *s)
3122         {
3123         int ret=SSL_TLSEXT_ERR_NOACK;
3124         int al = SSL_AD_UNRECOGNIZED_NAME;
3125
3126 #ifndef OPENSSL_NO_EC
3127         /* If we are client and using an elliptic curve cryptography cipher
3128          * suite, then if server returns an EC point formats lists extension
3129          * it must contain uncompressed.
3130          */
3131         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3132         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
3133         if ((s->tlsext_ecpointformatlist != NULL) && (s->tlsext_ecpointformatlist_length > 0) && 
3134             (s->session->tlsext_ecpointformatlist != NULL) && (s->session->tlsext_ecpointformatlist_length > 0) && 
3135             ((alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA)))
3136                 {
3137                 /* we are using an ECC cipher */
3138                 size_t i;
3139                 unsigned char *list;
3140                 int found_uncompressed = 0;
3141                 list = s->session->tlsext_ecpointformatlist;
3142                 for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
3143                         {
3144                         if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed)
3145                                 {
3146                                 found_uncompressed = 1;
3147                                 break;
3148                                 }
3149                         }
3150                 if (!found_uncompressed)
3151                         {
3152                         SSLerr(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT,SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
3153                         return -1;
3154                         }
3155                 }
3156         ret = SSL_TLSEXT_ERR_OK;
3157 #endif /* OPENSSL_NO_EC */
3158
3159         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
3160                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
3161         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
3162                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
3163
3164 #ifdef TLSEXT_TYPE_opaque_prf_input
3165         if (s->s3->server_opaque_prf_input_len > 0)
3166                 {
3167                 /* This case may indicate that we, as a client, want to insist on using opaque PRF inputs.
3168                  * So first verify that we really have a value from the server too. */
3169
3170                 if (s->s3->server_opaque_prf_input == NULL)
3171                         {
3172                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3173                         al = SSL_AD_HANDSHAKE_FAILURE;
3174                         }
3175                 
3176                 /* Anytime the server *has* sent an opaque PRF input, we need to check
3177                  * that we have a client opaque PRF input of the same size. */
3178                 if (s->s3->client_opaque_prf_input == NULL ||
3179                     s->s3->client_opaque_prf_input_len != s->s3->server_opaque_prf_input_len)
3180                         {
3181                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3182                         al = SSL_AD_ILLEGAL_PARAMETER;
3183                         }
3184                 }
3185 #endif
3186
3187         /* If we've requested certificate status and we wont get one
3188          * tell the callback
3189          */
3190         if ((s->tlsext_status_type != -1) && !(s->tlsext_status_expected)
3191                         && s->ctx && s->ctx->tlsext_status_cb)
3192                 {
3193                 int r;
3194                 /* Set resp to NULL, resplen to -1 so callback knows
3195                  * there is no response.
3196                  */
3197                 if (s->tlsext_ocsp_resp)
3198                         {
3199                         OPENSSL_free(s->tlsext_ocsp_resp);
3200                         s->tlsext_ocsp_resp = NULL;
3201                         }
3202                 s->tlsext_ocsp_resplen = -1;
3203                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
3204                 if (r == 0)
3205                         {
3206                         al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
3207                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3208                         }
3209                 if (r < 0)
3210                         {
3211                         al = SSL_AD_INTERNAL_ERROR;
3212                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3213                         }
3214                 }
3215
3216         switch (ret)
3217                 {
3218                 case SSL_TLSEXT_ERR_ALERT_FATAL:
3219                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
3220                         return -1;
3221
3222                 case SSL_TLSEXT_ERR_ALERT_WARNING:
3223                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
3224                         return 1; 
3225                                         
3226                 case SSL_TLSEXT_ERR_NOACK:
3227                         s->servername_done=0;
3228                         default:
3229                 return 1;
3230                 }
3231         }
3232
3233 int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n) 
3234         {
3235         int al = -1;
3236         if (s->version < SSL3_VERSION)
3237                 return 1;
3238         if (ssl_scan_serverhello_tlsext(s, p, d, n, &al) <= 0) 
3239                 {
3240                 ssl3_send_alert(s,SSL3_AL_FATAL,al); 
3241                 return 0;
3242                 }
3243
3244         if (ssl_check_serverhello_tlsext(s) <= 0) 
3245                 {
3246                 SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT,SSL_R_SERVERHELLO_TLSEXT);
3247                 return 0;
3248                 }
3249         return 1;
3250 }
3251
3252 /* Since the server cache lookup is done early on in the processing of the
3253  * ClientHello, and other operations depend on the result, we need to handle
3254  * any TLS session ticket extension at the same time.
3255  *
3256  *   session_id: points at the session ID in the ClientHello. This code will
3257  *       read past the end of this in order to parse out the session ticket
3258  *       extension, if any.
3259  *   len: the length of the session ID.
3260  *   limit: a pointer to the first byte after the ClientHello.
3261  *   ret: (output) on return, if a ticket was decrypted, then this is set to
3262  *       point to the resulting session.
3263  *
3264  * If s->tls_session_secret_cb is set then we are expecting a pre-shared key
3265  * ciphersuite, in which case we have no use for session tickets and one will
3266  * never be decrypted, nor will s->tlsext_ticket_expected be set to 1.
3267  *
3268  * Returns:
3269  *   -1: fatal error, either from parsing or decrypting the ticket.
3270  *    0: no ticket was found (or was ignored, based on settings).
3271  *    1: a zero length extension was found, indicating that the client supports
3272  *       session tickets but doesn't currently have one to offer.
3273  *    2: either s->tls_session_secret_cb was set, or a ticket was offered but
3274  *       couldn't be decrypted because of a non-fatal error.
3275  *    3: a ticket was successfully decrypted and *ret was set.
3276  *
3277  * Side effects:
3278  *   Sets s->tlsext_ticket_expected to 1 if the server will have to issue
3279  *   a new session ticket to the client because the client indicated support
3280  *   (and s->tls_session_secret_cb is NULL) but the client either doesn't have
3281  *   a session ticket or we couldn't use the one it gave us, or if
3282  *   s->ctx->tlsext_ticket_key_cb asked to renew the client's ticket.
3283  *   Otherwise, s->tlsext_ticket_expected is set to 0.
3284  */
3285 int tls1_process_ticket(SSL *s, unsigned char *session_id, int len,
3286                         const unsigned char *limit, SSL_SESSION **ret)
3287         {
3288         /* Point after session ID in client hello */
3289         const unsigned char *p = session_id + len;
3290         unsigned short i;
3291
3292         *ret = NULL;
3293         s->tlsext_ticket_expected = 0;
3294
3295         /* If tickets disabled behave as if no ticket present
3296          * to permit stateful resumption.
3297          */
3298         if (SSL_get_options(s) & SSL_OP_NO_TICKET)
3299                 return 0;
3300         if ((s->version <= SSL3_VERSION) || !limit)
3301                 return 0;
3302         if (p >= limit)
3303                 return -1;
3304         /* Skip past DTLS cookie */
3305         if (SSL_IS_DTLS(s))
3306                 {
3307                 i = *(p++);
3308                 p+= i;
3309                 if (p >= limit)
3310                         return -1;
3311                 }
3312         /* Skip past cipher list */
3313         n2s(p, i);
3314         p+= i;
3315         if (p >= limit)
3316                 return -1;
3317         /* Skip past compression algorithm list */
3318         i = *(p++);
3319         p += i;
3320         if (p > limit)
3321                 return -1;
3322         /* Now at start of extensions */
3323         if ((p + 2) >= limit)
3324                 return 0;
3325         n2s(p, i);
3326         while ((p + 4) <= limit)
3327                 {
3328                 unsigned short type, size;
3329                 n2s(p, type);
3330                 n2s(p, size);
3331                 if (p + size > limit)
3332                         return 0;
3333                 if (type == TLSEXT_TYPE_session_ticket)
3334                         {
3335                         int r;
3336                         if (size == 0)
3337                                 {
3338                                 /* The client will accept a ticket but doesn't
3339                                  * currently have one. */
3340                                 s->tlsext_ticket_expected = 1;
3341                                 return 1;
3342                                 }
3343                         if (s->tls_session_secret_cb)
3344                                 {
3345                                 /* Indicate that the ticket couldn't be
3346                                  * decrypted rather than generating the session
3347                                  * from ticket now, trigger abbreviated
3348                                  * handshake based on external mechanism to
3349                                  * calculate the master secret later. */
3350                                 return 2;
3351                                 }
3352                         r = tls_decrypt_ticket(s, p, size, session_id, len, ret);
3353                         switch (r)
3354                                 {
3355                                 case 2: /* ticket couldn't be decrypted */
3356                                         s->tlsext_ticket_expected = 1;
3357                                         return 2;
3358                                 case 3: /* ticket was decrypted */
3359                                         return r;
3360                                 case 4: /* ticket decrypted but need to renew */
3361                                         s->tlsext_ticket_expected = 1;
3362                                         return 3;
3363                                 default: /* fatal error */
3364                                         return -1;
3365                                 }
3366                         }
3367                 p += size;
3368                 }
3369         return 0;
3370         }
3371
3372 /* tls_decrypt_ticket attempts to decrypt a session ticket.
3373  *
3374  *   etick: points to the body of the session ticket extension.
3375  *   eticklen: the length of the session tickets extenion.
3376  *   sess_id: points at the session ID.
3377  *   sesslen: the length of the session ID.
3378  *   psess: (output) on return, if a ticket was decrypted, then this is set to
3379  *       point to the resulting session.
3380  *
3381  * Returns:
3382  *   -1: fatal error, either from parsing or decrypting the ticket.
3383  *    2: the ticket couldn't be decrypted.
3384  *    3: a ticket was successfully decrypted and *psess was set.
3385  *    4: same as 3, but the ticket needs to be renewed.
3386  */
3387 static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen,
3388                                 const unsigned char *sess_id, int sesslen,
3389                                 SSL_SESSION **psess)
3390         {
3391         SSL_SESSION *sess;
3392         unsigned char *sdec;
3393         const unsigned char *p;
3394         int slen, mlen, renew_ticket = 0;
3395         unsigned char tick_hmac[EVP_MAX_MD_SIZE];
3396         HMAC_CTX hctx;
3397         EVP_CIPHER_CTX ctx;
3398         SSL_CTX *tctx = s->initial_ctx;
3399         /* Need at least keyname + iv + some encrypted data */
3400         if (eticklen < 48)
3401                 return 2;
3402         /* Initialize session ticket encryption and HMAC contexts */
3403         HMAC_CTX_init(&hctx);
3404         EVP_CIPHER_CTX_init(&ctx);
3405         if (tctx->tlsext_ticket_key_cb)
3406                 {
3407                 unsigned char *nctick = (unsigned char *)etick;
3408                 int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
3409                                                         &ctx, &hctx, 0);
3410                 if (rv < 0)
3411                         return -1;
3412                 if (rv == 0)
3413                         return 2;
3414                 if (rv == 2)
3415                         renew_ticket = 1;
3416                 }
3417         else
3418                 {
3419                 /* Check key name matches */
3420                 if (memcmp(etick, tctx->tlsext_tick_key_name, 16))
3421                         return 2;
3422                 HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3423                                         tlsext_tick_md(), NULL);
3424                 EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3425                                 tctx->tlsext_tick_aes_key, etick + 16);
3426                 }
3427         /* Attempt to process session ticket, first conduct sanity and
3428          * integrity checks on ticket.
3429          */
3430         mlen = HMAC_size(&hctx);
3431         if (mlen < 0)
3432                 {
3433                 EVP_CIPHER_CTX_cleanup(&ctx);
3434                 return -1;
3435                 }
3436         eticklen -= mlen;
3437         /* Check HMAC of encrypted ticket */
3438         HMAC_Update(&hctx, etick, eticklen);
3439         HMAC_Final(&hctx, tick_hmac, NULL);
3440         HMAC_CTX_cleanup(&hctx);
3441         if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen))
3442                 {
3443                 EVP_CIPHER_CTX_cleanup(&ctx);
3444                 return 2;
3445                 }
3446         /* Attempt to decrypt session data */
3447         /* Move p after IV to start of encrypted ticket, update length */
3448         p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx);
3449         eticklen -= 16 + EVP_CIPHER_CTX_iv_length(&ctx);
3450         sdec = OPENSSL_malloc(eticklen);
3451         if (!sdec)
3452                 {
3453                 EVP_CIPHER_CTX_cleanup(&ctx);
3454                 return -1;
3455                 }
3456         EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen);
3457         if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0)
3458                 {
3459                 EVP_CIPHER_CTX_cleanup(&ctx);
3460                 OPENSSL_free(sdec);
3461                 return 2;
3462                 }
3463         slen += mlen;
3464         EVP_CIPHER_CTX_cleanup(&ctx);
3465         p = sdec;
3466
3467         sess = d2i_SSL_SESSION(NULL, &p, slen);
3468         OPENSSL_free(sdec);
3469         if (sess)
3470                 {
3471                 /* The session ID, if non-empty, is used by some clients to
3472                  * detect that the ticket has been accepted. So we copy it to
3473                  * the session structure. If it is empty set length to zero
3474                  * as required by standard.
3475                  */
3476                 if (sesslen)
3477                         memcpy(sess->session_id, sess_id, sesslen);
3478                 sess->session_id_length = sesslen;
3479                 *psess = sess;
3480                 if (renew_ticket)
3481                         return 4;
3482                 else
3483                         return 3;
3484                 }
3485         ERR_clear_error();
3486         /* For session parse failure, indicate that we need to send a new
3487          * ticket. */
3488         return 2;
3489         }
3490
3491 /* Tables to translate from NIDs to TLS v1.2 ids */
3492
3493 typedef struct 
3494         {
3495         int nid;
3496         int id;
3497         } tls12_lookup;
3498
3499 static tls12_lookup tls12_md[] = {
3500         {NID_md5, TLSEXT_hash_md5},
3501         {NID_sha1, TLSEXT_hash_sha1},
3502         {NID_sha224, TLSEXT_hash_sha224},
3503         {NID_sha256, TLSEXT_hash_sha256},
3504         {NID_sha384, TLSEXT_hash_sha384},
3505         {NID_sha512, TLSEXT_hash_sha512}
3506 };
3507
3508 static tls12_lookup tls12_sig[] = {
3509         {EVP_PKEY_RSA, TLSEXT_signature_rsa},
3510         {EVP_PKEY_DSA, TLSEXT_signature_dsa},
3511         {EVP_PKEY_EC, TLSEXT_signature_ecdsa}
3512 };
3513
3514 static int tls12_find_id(int nid, tls12_lookup *table, size_t tlen)
3515         {
3516         size_t i;
3517         for (i = 0; i < tlen; i++)
3518                 {
3519                 if (table[i].nid == nid)
3520                         return table[i].id;
3521                 }
3522         return -1;
3523         }
3524
3525 static int tls12_find_nid(int id, tls12_lookup *table, size_t tlen)
3526         {
3527         size_t i;
3528         for (i = 0; i < tlen; i++)
3529                 {
3530                 if ((table[i].id) == id)
3531                         return table[i].nid;
3532                 }
3533         return NID_undef;
3534         }
3535
3536 int tls12_get_sigandhash(unsigned char *p, const EVP_PKEY *pk, const EVP_MD *md)
3537         {
3538         int sig_id, md_id;
3539         if (!md)
3540                 return 0;
3541         md_id = tls12_find_id(EVP_MD_type(md), tls12_md,
3542                                 sizeof(tls12_md)/sizeof(tls12_lookup));
3543         if (md_id == -1)
3544                 return 0;
3545         sig_id = tls12_get_sigid(pk);
3546         if (sig_id == -1)
3547                 return 0;
3548         p[0] = (unsigned char)md_id;
3549         p[1] = (unsigned char)sig_id;
3550         return 1;
3551         }
3552
3553 int tls12_get_sigid(const EVP_PKEY *pk)
3554         {
3555         return tls12_find_id(pk->type, tls12_sig,
3556                                 sizeof(tls12_sig)/sizeof(tls12_lookup));
3557         }
3558
3559 const EVP_MD *tls12_get_hash(unsigned char hash_alg)
3560         {
3561         switch(hash_alg)
3562                 {
3563 #ifndef OPENSSL_NO_MD5
3564                 case TLSEXT_hash_md5:
3565 #ifdef OPENSSL_FIPS
3566                 if (FIPS_mode())
3567                         return NULL;
3568 #endif
3569                 return EVP_md5();
3570 #endif
3571 #ifndef OPENSSL_NO_SHA
3572                 case TLSEXT_hash_sha1:
3573                 return EVP_sha1();
3574 #endif
3575 #ifndef OPENSSL_NO_SHA256
3576                 case TLSEXT_hash_sha224:
3577                 return EVP_sha224();
3578
3579                 case TLSEXT_hash_sha256:
3580                 return EVP_sha256();
3581 #endif
3582 #ifndef OPENSSL_NO_SHA512
3583                 case TLSEXT_hash_sha384:
3584                 return EVP_sha384();
3585
3586                 case TLSEXT_hash_sha512:
3587                 return EVP_sha512();
3588 #endif
3589                 default:
3590                 return NULL;
3591
3592                 }
3593         }
3594
3595 static int tls12_get_pkey_idx(unsigned char sig_alg)
3596         {
3597         switch(sig_alg)
3598                 {
3599 #ifndef OPENSSL_NO_RSA
3600         case TLSEXT_signature_rsa:
3601                 return SSL_PKEY_RSA_SIGN;
3602 #endif
3603 #ifndef OPENSSL_NO_DSA
3604         case TLSEXT_signature_dsa:
3605                 return SSL_PKEY_DSA_SIGN;
3606 #endif
3607 #ifndef OPENSSL_NO_ECDSA
3608         case TLSEXT_signature_ecdsa:
3609                 return SSL_PKEY_ECC;
3610 #endif
3611                 }
3612         return -1;
3613         }
3614
3615 /* Convert TLS 1.2 signature algorithm extension values into NIDs */
3616 static void tls1_lookup_sigalg(int *phash_nid, int *psign_nid,
3617                         int *psignhash_nid, const unsigned char *data)
3618         {
3619         int sign_nid = 0, hash_nid = 0;
3620         if (!phash_nid && !psign_nid && !psignhash_nid)
3621                 return;
3622         if (phash_nid || psignhash_nid)
3623                 {
3624                 hash_nid = tls12_find_nid(data[0], tls12_md,
3625                                         sizeof(tls12_md)/sizeof(tls12_lookup));
3626                 if (phash_nid)
3627                         *phash_nid = hash_nid;
3628                 }
3629         if (psign_nid || psignhash_nid)
3630                 {
3631                 sign_nid = tls12_find_nid(data[1], tls12_sig,
3632                                         sizeof(tls12_sig)/sizeof(tls12_lookup));
3633                 if (psign_nid)
3634                         *psign_nid = sign_nid;
3635                 }
3636         if (psignhash_nid)
3637                 {
3638                 if (sign_nid && hash_nid)
3639                         OBJ_find_sigid_by_algs(psignhash_nid,
3640                                                         hash_nid, sign_nid);
3641                 else
3642                         *psignhash_nid = NID_undef;
3643                 }
3644         }
3645 /* Given preference and allowed sigalgs set shared sigalgs */
3646 static int tls12_do_shared_sigalgs(TLS_SIGALGS *shsig,
3647                                 const unsigned char *pref, size_t preflen,
3648                                 const unsigned char *allow, size_t allowlen)
3649         {
3650         const unsigned char *ptmp, *atmp;
3651         size_t i, j, nmatch = 0;
3652         for (i = 0, ptmp = pref; i < preflen; i+=2, ptmp+=2)
3653                 {
3654                 /* Skip disabled hashes or signature algorithms */
3655                 if (tls12_get_hash(ptmp[0]) == NULL)
3656                         continue;
3657                 if (tls12_get_pkey_idx(ptmp[1]) == -1)
3658                         continue;
3659                 for (j = 0, atmp = allow; j < allowlen; j+=2, atmp+=2)
3660                         {
3661                         if (ptmp[0] == atmp[0] && ptmp[1] == atmp[1])
3662                                 {
3663                                 nmatch++;
3664                                 if (shsig)
3665                                         {
3666                                         shsig->rhash = ptmp[0];
3667                                         shsig->rsign = ptmp[1];
3668                                         tls1_lookup_sigalg(&shsig->hash_nid,
3669                                                 &shsig->sign_nid,
3670                                                 &shsig->signandhash_nid,
3671                                                 ptmp);
3672                                         shsig++;
3673                                         }
3674                                 break;
3675                                 }
3676                         }
3677                 }
3678         return nmatch;
3679         }
3680
3681 /* Set shared signature algorithms for SSL structures */
3682 static int tls1_set_shared_sigalgs(SSL *s)
3683         {
3684         const unsigned char *pref, *allow, *conf;
3685         size_t preflen, allowlen, conflen;
3686         size_t nmatch;
3687         TLS_SIGALGS *salgs = NULL;
3688         CERT *c = s->cert;
3689         unsigned int is_suiteb = tls1_suiteb(s);
3690         if (c->shared_sigalgs)
3691                 {
3692                 OPENSSL_free(c->shared_sigalgs);
3693                 c->shared_sigalgs = NULL;
3694                 }
3695         /* If client use client signature algorithms if not NULL */
3696         if (!s->server && c->client_sigalgs && !is_suiteb)
3697                 {
3698                 conf = c->client_sigalgs;
3699                 conflen = c->client_sigalgslen;
3700                 }
3701         else if (c->conf_sigalgs && !is_suiteb)
3702                 {
3703                 conf = c->conf_sigalgs;
3704                 conflen = c->conf_sigalgslen;
3705                 }
3706         else
3707                 conflen = tls12_get_psigalgs(s, &conf);
3708         if(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE || is_suiteb)
3709                 {
3710                 pref = conf;
3711                 preflen = conflen;
3712                 allow = c->peer_sigalgs;
3713                 allowlen = c->peer_sigalgslen;
3714                 }
3715         else
3716                 {
3717                 allow = conf;
3718                 allowlen = conflen;
3719                 pref = c->peer_sigalgs;
3720                 preflen = c->peer_sigalgslen;
3721                 }
3722         nmatch = tls12_do_shared_sigalgs(NULL, pref, preflen, allow, allowlen);
3723         if (!nmatch)
3724                 return 1;
3725         salgs = OPENSSL_malloc(nmatch * sizeof(TLS_SIGALGS));
3726         if (!salgs)
3727                 return 0;
3728         nmatch = tls12_do_shared_sigalgs(salgs, pref, preflen, allow, allowlen);
3729         c->shared_sigalgs = salgs;
3730         c->shared_sigalgslen = nmatch;
3731         return 1;
3732         }
3733                 
3734
3735 /* Set preferred digest for each key type */
3736
3737 int tls1_save_sigalgs(SSL *s, const unsigned char *data, int dsize)
3738         {
3739         CERT *c = s->cert;
3740         /* Extension ignored for inappropriate versions */
3741         if (!SSL_USE_SIGALGS(s))
3742                 return 1;
3743         /* Should never happen */
3744         if (!c)
3745                 return 0;
3746
3747         if (c->peer_sigalgs)
3748                 OPENSSL_free(c->peer_sigalgs);
3749         c->peer_sigalgs = OPENSSL_malloc(dsize);
3750         if (!c->peer_sigalgs)
3751                 return 0;
3752         c->peer_sigalgslen = dsize;
3753         memcpy(c->peer_sigalgs, data, dsize);
3754         return 1;
3755         }
3756
3757 int tls1_process_sigalgs(SSL *s)
3758         {
3759         int idx;
3760         size_t i;
3761         const EVP_MD *md;
3762         CERT *c = s->cert;
3763         TLS_SIGALGS *sigptr;
3764         if (!tls1_set_shared_sigalgs(s))
3765                 return 0;
3766
3767 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
3768         if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
3769                 {
3770                 /* Use first set signature preference to force message
3771                  * digest, ignoring any peer preferences.
3772                  */
3773                 const unsigned char *sigs = NULL;
3774                 if (s->server)
3775                         sigs = c->conf_sigalgs;
3776                 else
3777                         sigs = c->client_sigalgs;
3778                 if (sigs)
3779                         {
3780                         idx = tls12_get_pkey_idx(sigs[1]);
3781                         md = tls12_get_hash(sigs[0]);
3782                         c->pkeys[idx].digest = md;
3783                         c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3784                         if (idx == SSL_PKEY_RSA_SIGN)
3785                                 {
3786                                 c->pkeys[SSL_PKEY_RSA_ENC].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3787                                 c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
3788                                 }
3789                         }
3790                 }
3791 #endif
3792
3793         for (i = 0, sigptr = c->shared_sigalgs;
3794                         i < c->shared_sigalgslen; i++, sigptr++)
3795                 {
3796                 idx = tls12_get_pkey_idx(sigptr->rsign);
3797                 if (idx > 0 && c->pkeys[idx].digest == NULL)
3798                         {
3799                         md = tls12_get_hash(sigptr->rhash);
3800                         c->pkeys[idx].digest = md;
3801                         c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3802                         if (idx == SSL_PKEY_RSA_SIGN)
3803                                 {
3804                                 c->pkeys[SSL_PKEY_RSA_ENC].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3805                                 c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
3806                                 }
3807                         }
3808
3809                 }
3810         /* In strict mode leave unset digests as NULL to indicate we can't
3811          * use the certificate for signing.
3812          */
3813         if (!(s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT))
3814                 {
3815                 /* Set any remaining keys to default values. NOTE: if alg is
3816                  * not supported it stays as NULL.
3817                  */
3818 #ifndef OPENSSL_NO_DSA
3819                 if (!c->pkeys[SSL_PKEY_DSA_SIGN].digest)
3820                         c->pkeys[SSL_PKEY_DSA_SIGN].digest = EVP_sha1();
3821 #endif
3822 #ifndef OPENSSL_NO_RSA
3823                 if (!c->pkeys[SSL_PKEY_RSA_SIGN].digest)
3824                         {
3825                         c->pkeys[SSL_PKEY_RSA_SIGN].digest = EVP_sha1();
3826                         c->pkeys[SSL_PKEY_RSA_ENC].digest = EVP_sha1();
3827                         }
3828 #endif
3829 #ifndef OPENSSL_NO_ECDSA
3830                 if (!c->pkeys[SSL_PKEY_ECC].digest)
3831                         c->pkeys[SSL_PKEY_ECC].digest = EVP_sha1();
3832 #endif
3833                 }
3834         return 1;
3835         }
3836
3837
3838 int SSL_get_sigalgs(SSL *s, int idx,
3839                         int *psign, int *phash, int *psignhash,
3840                         unsigned char *rsig, unsigned char *rhash)
3841         {
3842         const unsigned char *psig = s->cert->peer_sigalgs;
3843         if (psig == NULL)
3844                 return 0;
3845         if (idx >= 0)
3846                 {
3847                 idx <<= 1;
3848                 if (idx >= (int)s->cert->peer_sigalgslen)
3849                         return 0;
3850                 psig += idx;
3851                 if (rhash)
3852                         *rhash = psig[0];
3853                 if (rsig)
3854                         *rsig = psig[1];
3855                 tls1_lookup_sigalg(phash, psign, psignhash, psig);
3856                 }
3857         return s->cert->peer_sigalgslen / 2;
3858         }
3859
3860 int SSL_get_shared_sigalgs(SSL *s, int idx,
3861                         int *psign, int *phash, int *psignhash,
3862                         unsigned char *rsig, unsigned char *rhash)
3863         {
3864         TLS_SIGALGS *shsigalgs = s->cert->shared_sigalgs;
3865         if (!shsigalgs || idx >= (int)s->cert->shared_sigalgslen)
3866                 return 0;
3867         shsigalgs += idx;
3868         if (phash)
3869                 *phash = shsigalgs->hash_nid;
3870         if (psign)
3871                 *psign = shsigalgs->sign_nid;
3872         if (psignhash)
3873                 *psignhash = shsigalgs->signandhash_nid;
3874         if (rsig)
3875                 *rsig = shsigalgs->rsign;
3876         if (rhash)
3877                 *rhash = shsigalgs->rhash;
3878         return s->cert->shared_sigalgslen;
3879         }
3880         
3881
3882 #ifndef OPENSSL_NO_HEARTBEATS
3883 int
3884 tls1_process_heartbeat(SSL *s)
3885         {
3886         unsigned char *p = &s->s3->rrec.data[0], *pl;
3887         unsigned short hbtype;
3888         unsigned int payload;
3889         unsigned int padding = 16; /* Use minimum padding */
3890
3891         if (s->msg_callback)
3892                 s->msg_callback(0, s->version, TLS1_RT_HEARTBEAT,
3893                         &s->s3->rrec.data[0], s->s3->rrec.length,
3894                         s, s->msg_callback_arg);
3895
3896         /* Read type and payload length first */
3897         if (1 + 2 + 16 > s->s3->rrec.length)
3898                 return 0; /* silently discard */
3899         hbtype = *p++;
3900         n2s(p, payload);
3901         if (1 + 2 + payload + 16 > s->s3->rrec.length)
3902                 return 0; /* silently discard per RFC 6520 sec. 4 */
3903         pl = p;
3904
3905         if (hbtype == TLS1_HB_REQUEST)
3906                 {
3907                 unsigned char *buffer, *bp;
3908                 int r;
3909
3910                 /* Allocate memory for the response, size is 1 bytes
3911                  * message type, plus 2 bytes payload length, plus
3912                  * payload, plus padding
3913                  */
3914                 buffer = OPENSSL_malloc(1 + 2 + payload + padding);
3915                 bp = buffer;
3916                 
3917                 /* Enter response type, length and copy payload */
3918                 *bp++ = TLS1_HB_RESPONSE;
3919                 s2n(payload, bp);
3920                 memcpy(bp, pl, payload);
3921                 bp += payload;
3922                 /* Random padding */
3923                 RAND_pseudo_bytes(bp, padding);
3924
3925                 r = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buffer, 3 + payload + padding);
3926
3927                 if (r >= 0 && s->msg_callback)
3928                         s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
3929                                 buffer, 3 + payload + padding,
3930                                 s, s->msg_callback_arg);
3931
3932                 OPENSSL_free(buffer);
3933
3934                 if (r < 0)
3935                         return r;
3936                 }
3937         else if (hbtype == TLS1_HB_RESPONSE)
3938                 {
3939                 unsigned int seq;
3940                 
3941                 /* We only send sequence numbers (2 bytes unsigned int),
3942                  * and 16 random bytes, so we just try to read the
3943                  * sequence number */
3944                 n2s(pl, seq);
3945                 
3946                 if (payload == 18 && seq == s->tlsext_hb_seq)
3947                         {
3948                         s->tlsext_hb_seq++;
3949                         s->tlsext_hb_pending = 0;
3950                         }
3951                 }
3952
3953         return 0;
3954         }
3955
3956 int
3957 tls1_heartbeat(SSL *s)
3958         {
3959         unsigned char *buf, *p;
3960         int ret;
3961         unsigned int payload = 18; /* Sequence number + random bytes */
3962         unsigned int padding = 16; /* Use minimum padding */
3963
3964         /* Only send if peer supports and accepts HB requests... */
3965         if (!(s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) ||
3966             s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_SEND_REQUESTS)
3967                 {
3968                 SSLerr(SSL_F_TLS1_HEARTBEAT,SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT);
3969                 return -1;
3970                 }
3971
3972         /* ...and there is none in flight yet... */
3973         if (s->tlsext_hb_pending)
3974                 {
3975                 SSLerr(SSL_F_TLS1_HEARTBEAT,SSL_R_TLS_HEARTBEAT_PENDING);
3976                 return -1;
3977                 }
3978                 
3979         /* ...and no handshake in progress. */
3980         if (SSL_in_init(s) || s->in_handshake)
3981                 {
3982                 SSLerr(SSL_F_TLS1_HEARTBEAT,SSL_R_UNEXPECTED_MESSAGE);
3983                 return -1;
3984                 }
3985                 
3986         /* Check if padding is too long, payload and padding
3987          * must not exceed 2^14 - 3 = 16381 bytes in total.
3988          */
3989         OPENSSL_assert(payload + padding <= 16381);
3990
3991         /* Create HeartBeat message, we just use a sequence number
3992          * as payload to distuingish different messages and add
3993          * some random stuff.
3994          *  - Message Type, 1 byte
3995          *  - Payload Length, 2 bytes (unsigned int)
3996          *  - Payload, the sequence number (2 bytes uint)
3997          *  - Payload, random bytes (16 bytes uint)
3998          *  - Padding
3999          */
4000         buf = OPENSSL_malloc(1 + 2 + payload + padding);
4001         p = buf;
4002         /* Message Type */
4003         *p++ = TLS1_HB_REQUEST;
4004         /* Payload length (18 bytes here) */
4005         s2n(payload, p);
4006         /* Sequence number */
4007         s2n(s->tlsext_hb_seq, p);
4008         /* 16 random bytes */
4009         RAND_pseudo_bytes(p, 16);
4010         p += 16;
4011         /* Random padding */
4012         RAND_pseudo_bytes(p, padding);
4013
4014         ret = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buf, 3 + payload + padding);
4015         if (ret >= 0)
4016                 {
4017                 if (s->msg_callback)
4018                         s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
4019                                 buf, 3 + payload + padding,
4020                                 s, s->msg_callback_arg);
4021
4022                 s->tlsext_hb_pending = 1;
4023                 }
4024                 
4025         OPENSSL_free(buf);
4026
4027         return ret;
4028         }
4029 #endif
4030
4031 #define MAX_SIGALGLEN   (TLSEXT_hash_num * TLSEXT_signature_num * 2)
4032
4033 typedef struct
4034         {
4035         size_t sigalgcnt;
4036         int sigalgs[MAX_SIGALGLEN];
4037         } sig_cb_st;
4038
4039 static int sig_cb(const char *elem, int len, void *arg)
4040         {
4041         sig_cb_st *sarg = arg;
4042         size_t i;
4043         char etmp[20], *p;
4044         int sig_alg, hash_alg;
4045         if (sarg->sigalgcnt == MAX_SIGALGLEN)
4046                 return 0;
4047         if (len > (int)(sizeof(etmp) - 1))
4048                 return 0;
4049         memcpy(etmp, elem, len);
4050         etmp[len] = 0;
4051         p = strchr(etmp, '+');
4052         if (!p)
4053                 return 0;
4054         *p = 0;
4055         p++;
4056         if (!*p)
4057                 return 0;
4058
4059         if (!strcmp(etmp, "RSA"))
4060                 sig_alg = EVP_PKEY_RSA;
4061         else if (!strcmp(etmp, "DSA"))
4062                 sig_alg = EVP_PKEY_DSA;
4063         else if (!strcmp(etmp, "ECDSA"))
4064                 sig_alg = EVP_PKEY_EC;
4065         else return 0;
4066
4067         hash_alg = OBJ_sn2nid(p);
4068         if (hash_alg == NID_undef)
4069                 hash_alg = OBJ_ln2nid(p);
4070         if (hash_alg == NID_undef)
4071                 return 0;
4072
4073         for (i = 0; i < sarg->sigalgcnt; i+=2)
4074                 {
4075                 if (sarg->sigalgs[i] == sig_alg
4076                         && sarg->sigalgs[i + 1] == hash_alg)
4077                         return 0;
4078                 }
4079         sarg->sigalgs[sarg->sigalgcnt++] = hash_alg;
4080         sarg->sigalgs[sarg->sigalgcnt++] = sig_alg;
4081         return 1;
4082         }
4083
4084 /* Set suppored signature algorithms based on a colon separated list
4085  * of the form sig+hash e.g. RSA+SHA512:DSA+SHA512 */
4086 int tls1_set_sigalgs_list(CERT *c, const char *str, int client)
4087         {
4088         sig_cb_st sig;
4089         sig.sigalgcnt = 0;
4090         if (!CONF_parse_list(str, ':', 1, sig_cb, &sig))
4091                 return 0;
4092         if (c == NULL)
4093                 return 1;
4094         return tls1_set_sigalgs(c, sig.sigalgs, sig.sigalgcnt, client);
4095         }
4096
4097 int tls1_set_sigalgs(CERT *c, const int *psig_nids, size_t salglen, int client)
4098         {
4099         unsigned char *sigalgs, *sptr;
4100         int rhash, rsign;
4101         size_t i;
4102         if (salglen & 1)
4103                 return 0;
4104         sigalgs = OPENSSL_malloc(salglen);
4105         if (sigalgs == NULL)
4106                 return 0;
4107         for (i = 0, sptr = sigalgs; i < salglen; i+=2)
4108                 {
4109                 rhash = tls12_find_id(*psig_nids++, tls12_md,
4110                                         sizeof(tls12_md)/sizeof(tls12_lookup));
4111                 rsign = tls12_find_id(*psig_nids++, tls12_sig,
4112                                 sizeof(tls12_sig)/sizeof(tls12_lookup));
4113
4114                 if (rhash == -1 || rsign == -1)
4115                         goto err;
4116                 *sptr++ = rhash;
4117                 *sptr++ = rsign;
4118                 }
4119
4120         if (client)
4121                 {
4122                 if (c->client_sigalgs)
4123                         OPENSSL_free(c->client_sigalgs);
4124                 c->client_sigalgs = sigalgs;
4125                 c->client_sigalgslen = salglen;
4126                 }
4127         else
4128                 {
4129                 if (c->conf_sigalgs)
4130                         OPENSSL_free(c->conf_sigalgs);
4131                 c->conf_sigalgs = sigalgs;
4132                 c->conf_sigalgslen = salglen;
4133                 }
4134
4135         return 1;
4136
4137         err:
4138         OPENSSL_free(sigalgs);
4139         return 0;
4140         }
4141
4142 static int tls1_check_sig_alg(CERT *c, X509 *x, int default_nid)
4143         {
4144         int sig_nid;
4145         size_t i;
4146         if (default_nid == -1)
4147                 return 1;
4148         sig_nid = X509_get_signature_nid(x);
4149         if (default_nid)
4150                 return sig_nid == default_nid ? 1 : 0;
4151         for (i = 0; i < c->shared_sigalgslen; i++)
4152                 if (sig_nid == c->shared_sigalgs[i].signandhash_nid)
4153                         return 1;
4154         return 0;
4155         }
4156 /* Check to see if a certificate issuer name matches list of CA names */
4157 static int ssl_check_ca_name(STACK_OF(X509_NAME) *names, X509 *x)
4158         {
4159         X509_NAME *nm;
4160         int i;
4161         nm = X509_get_issuer_name(x);
4162         for (i = 0; i < sk_X509_NAME_num(names); i++)
4163                 {
4164                 if(!X509_NAME_cmp(nm, sk_X509_NAME_value(names, i)))
4165                         return 1;
4166                 }
4167         return 0;
4168         }
4169
4170 /* Check certificate chain is consistent with TLS extensions and is
4171  * usable by server. This servers two purposes: it allows users to 
4172  * check chains before passing them to the server and it allows the
4173  * server to check chains before attempting to use them.
4174  */
4175
4176 /* Flags which need to be set for a certificate when stict mode not set */
4177
4178 #define CERT_PKEY_VALID_FLAGS \
4179         (CERT_PKEY_EE_SIGNATURE|CERT_PKEY_EE_PARAM)
4180 /* Strict mode flags */
4181 #define CERT_PKEY_STRICT_FLAGS \
4182          (CERT_PKEY_VALID_FLAGS|CERT_PKEY_CA_SIGNATURE|CERT_PKEY_CA_PARAM \
4183          | CERT_PKEY_ISSUER_NAME|CERT_PKEY_CERT_TYPE)
4184
4185 int tls1_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain,
4186                                                                         int idx)
4187         {
4188         int i;
4189         int rv = 0;
4190         int check_flags = 0, strict_mode;
4191         CERT_PKEY *cpk = NULL;
4192         CERT *c = s->cert;
4193         unsigned int suiteb_flags = tls1_suiteb(s);
4194         /* idx == -1 means checking server chains */
4195         if (idx != -1)
4196                 {
4197                 /* idx == -2 means checking client certificate chains */
4198                 if (idx == -2)
4199                         {
4200                         cpk = c->key;
4201                         idx = cpk - c->pkeys;
4202                         }
4203                 else
4204                         cpk = c->pkeys + idx;
4205                 x = cpk->x509;
4206                 pk = cpk->privatekey;
4207                 chain = cpk->chain;
4208                 strict_mode = c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT;
4209                 /* If no cert or key, forget it */
4210                 if (!x || !pk)
4211                         goto end;
4212 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
4213                 /* Allow any certificate to pass test */
4214                 if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
4215                         {
4216                         rv = CERT_PKEY_STRICT_FLAGS|CERT_PKEY_EXPLICIT_SIGN|CERT_PKEY_VALID|CERT_PKEY_SIGN;
4217                         cpk->valid_flags = rv;
4218                         return rv;
4219                         }
4220 #endif
4221                 }
4222         else
4223                 {
4224                 if (!x || !pk)
4225                         goto end;
4226                 idx = ssl_cert_type(x, pk);
4227                 if (idx == -1)
4228                         goto end;
4229                 cpk = c->pkeys + idx;
4230                 if (c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)
4231                         check_flags = CERT_PKEY_STRICT_FLAGS;
4232                 else
4233                         check_flags = CERT_PKEY_VALID_FLAGS;
4234                 strict_mode = 1;
4235                 }
4236
4237         if (suiteb_flags)
4238                 {
4239                 int ok;
4240                 if (check_flags)
4241                         check_flags |= CERT_PKEY_SUITEB;
4242                 ok = X509_chain_check_suiteb(NULL, x, chain, suiteb_flags);
4243                 if (ok == X509_V_OK)
4244                         rv |= CERT_PKEY_SUITEB;
4245                 else if (!check_flags)
4246                         goto end;
4247                 }
4248
4249         /* Check all signature algorithms are consistent with
4250          * signature algorithms extension if TLS 1.2 or later
4251          * and strict mode.
4252          */
4253         if (TLS1_get_version(s) >= TLS1_2_VERSION && strict_mode)
4254                 {
4255                 int default_nid;
4256                 unsigned char rsign = 0;
4257                 if (c->peer_sigalgs)
4258                         default_nid = 0;
4259                 /* If no sigalgs extension use defaults from RFC5246 */
4260                 else
4261                         {
4262                         switch(idx)
4263                                 {       
4264                         case SSL_PKEY_RSA_ENC:
4265                         case SSL_PKEY_RSA_SIGN:
4266                         case SSL_PKEY_DH_RSA:
4267                                 rsign = TLSEXT_signature_rsa;
4268                                 default_nid = NID_sha1WithRSAEncryption;
4269                                 break;
4270
4271                         case SSL_PKEY_DSA_SIGN:
4272                         case SSL_PKEY_DH_DSA:
4273                                 rsign = TLSEXT_signature_dsa;
4274                                 default_nid = NID_dsaWithSHA1;
4275                                 break;
4276
4277                         case SSL_PKEY_ECC:
4278                                 rsign = TLSEXT_signature_ecdsa;
4279                                 default_nid = NID_ecdsa_with_SHA1;
4280                                 break;
4281
4282                         default:
4283                                 default_nid = -1;
4284                                 break;
4285                                 }
4286                         }
4287                 /* If peer sent no signature algorithms extension and we
4288                  * have set preferred signature algorithms check we support
4289                  * sha1.
4290                  */
4291                 if (default_nid > 0 && c->conf_sigalgs)
4292                         {
4293                         size_t j;
4294                         const unsigned char *p = c->conf_sigalgs;
4295                         for (j = 0; j < c->conf_sigalgslen; j += 2, p += 2)
4296                                 {
4297                                 if (p[0] == TLSEXT_hash_sha1 && p[1] == rsign)
4298                                         break;
4299                                 }
4300                         if (j == c->conf_sigalgslen)
4301                                 {
4302                                 if (check_flags)
4303                                         goto skip_sigs;
4304                                 else
4305                                         goto end;
4306                                 }
4307                         }
4308                 /* Check signature algorithm of each cert in chain */
4309                 if (!tls1_check_sig_alg(c, x, default_nid))
4310                         {
4311                         if (!check_flags) goto end;
4312                         }
4313                 else
4314                         rv |= CERT_PKEY_EE_SIGNATURE;
4315                 rv |= CERT_PKEY_CA_SIGNATURE;
4316                 for (i = 0; i < sk_X509_num(chain); i++)
4317                         {
4318                         if (!tls1_check_sig_alg(c, sk_X509_value(chain, i),
4319                                                         default_nid))
4320                                 {
4321                                 if (check_flags)
4322                                         {
4323                                         rv &= ~CERT_PKEY_CA_SIGNATURE;
4324                                         break;
4325                                         }
4326                                 else
4327                                         goto end;
4328                                 }
4329                         }
4330                 }
4331         /* Else not TLS 1.2, so mark EE and CA signing algorithms OK */
4332         else if(check_flags)
4333                 rv |= CERT_PKEY_EE_SIGNATURE|CERT_PKEY_CA_SIGNATURE;
4334         skip_sigs:
4335         /* Check cert parameters are consistent */
4336         if (tls1_check_cert_param(s, x, check_flags ? 1 : 2))
4337                 rv |= CERT_PKEY_EE_PARAM;
4338         else if (!check_flags)
4339                 goto end;
4340         if (!s->server)
4341                 rv |= CERT_PKEY_CA_PARAM;
4342         /* In strict mode check rest of chain too */
4343         else if (strict_mode)
4344                 {
4345                 rv |= CERT_PKEY_CA_PARAM;
4346                 for (i = 0; i < sk_X509_num(chain); i++)
4347                         {
4348                         X509 *ca = sk_X509_value(chain, i);
4349                         if (!tls1_check_cert_param(s, ca, 0))
4350                                 {
4351                                 if (check_flags)
4352                                         {
4353                                         rv &= ~CERT_PKEY_CA_PARAM;
4354                                         break;
4355                                         }
4356                                 else
4357                                         goto end;
4358                                 }
4359                         }
4360                 }
4361         if (!s->server && strict_mode)
4362                 {
4363                 STACK_OF(X509_NAME) *ca_dn;
4364                 int check_type = 0;
4365                 switch (pk->type)
4366                         {
4367                 case EVP_PKEY_RSA:
4368                         check_type = TLS_CT_RSA_SIGN;
4369                         break;
4370                 case EVP_PKEY_DSA:
4371                         check_type = TLS_CT_DSS_SIGN;
4372                         break;
4373                 case EVP_PKEY_EC:
4374                         check_type = TLS_CT_ECDSA_SIGN;
4375                         break;
4376                 case EVP_PKEY_DH:
4377                 case EVP_PKEY_DHX:
4378                                 {
4379                                 int cert_type = X509_certificate_type(x, pk);
4380                                 if (cert_type & EVP_PKS_RSA)
4381                                         check_type = TLS_CT_RSA_FIXED_DH;
4382                                 if (cert_type & EVP_PKS_DSA)
4383                                         check_type = TLS_CT_DSS_FIXED_DH;
4384                                 }
4385                         }
4386                 if (check_type)
4387                         {
4388                         const unsigned char *ctypes;
4389                         int ctypelen;
4390                         if (c->ctypes)
4391                                 {
4392                                 ctypes = c->ctypes;
4393                                 ctypelen = (int)c->ctype_num;
4394                                 }
4395                         else
4396                                 {
4397                                 ctypes = (unsigned char *)s->s3->tmp.ctype;
4398                                 ctypelen = s->s3->tmp.ctype_num;
4399                                 }
4400                         for (i = 0; i < ctypelen; i++)
4401                                 {
4402                                 if (ctypes[i] == check_type)
4403                                         {
4404                                         rv |= CERT_PKEY_CERT_TYPE;
4405                                         break;
4406                                         }
4407                                 }
4408                         if (!(rv & CERT_PKEY_CERT_TYPE) && !check_flags)
4409                                 goto end;
4410                         }
4411                 else
4412                         rv |= CERT_PKEY_CERT_TYPE;
4413
4414
4415                 ca_dn = s->s3->tmp.ca_names;
4416
4417                 if (!sk_X509_NAME_num(ca_dn))
4418                         rv |= CERT_PKEY_ISSUER_NAME;
4419
4420                 if (!(rv & CERT_PKEY_ISSUER_NAME))
4421                         {
4422                         if (ssl_check_ca_name(ca_dn, x))
4423                                 rv |= CERT_PKEY_ISSUER_NAME;
4424                         }
4425                 if (!(rv & CERT_PKEY_ISSUER_NAME))
4426                         {
4427                         for (i = 0; i < sk_X509_num(chain); i++)
4428                                 {
4429                                 X509 *xtmp = sk_X509_value(chain, i);
4430                                 if (ssl_check_ca_name(ca_dn, xtmp))
4431                                         {
4432                                         rv |= CERT_PKEY_ISSUER_NAME;
4433                                         break;
4434                                         }
4435                                 }
4436                         }
4437                 if (!check_flags && !(rv & CERT_PKEY_ISSUER_NAME))
4438                         goto end;
4439                 }
4440         else
4441                 rv |= CERT_PKEY_ISSUER_NAME|CERT_PKEY_CERT_TYPE;
4442
4443         if (!check_flags || (rv & check_flags) == check_flags)
4444                 rv |= CERT_PKEY_VALID;
4445
4446         end:
4447
4448         if (TLS1_get_version(s) >= TLS1_2_VERSION)
4449                 {
4450                 if (cpk->valid_flags & CERT_PKEY_EXPLICIT_SIGN)
4451                         rv |= CERT_PKEY_EXPLICIT_SIGN|CERT_PKEY_SIGN;
4452                 else if (cpk->digest)
4453                         rv |= CERT_PKEY_SIGN;
4454                 }
4455         else
4456                 rv |= CERT_PKEY_SIGN|CERT_PKEY_EXPLICIT_SIGN;
4457
4458         /* When checking a CERT_PKEY structure all flags are irrelevant
4459          * if the chain is invalid.
4460          */
4461         if (!check_flags)
4462                 {
4463                 if (rv & CERT_PKEY_VALID)
4464                         cpk->valid_flags = rv;
4465                 else
4466                         {
4467                         /* Preserve explicit sign flag, clear rest */
4468                         cpk->valid_flags &= CERT_PKEY_EXPLICIT_SIGN;
4469                         return 0;
4470                         }
4471                 }
4472         return rv;
4473         }
4474
4475 /* Set validity of certificates in an SSL structure */
4476 void tls1_set_cert_validity(SSL *s)
4477         {
4478         tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_ENC);
4479         tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_SIGN);
4480         tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DSA_SIGN);
4481         tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DH_RSA);
4482         tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DH_DSA);
4483         tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_ECC);
4484         }
4485 /* User level utiity function to check a chain is suitable */
4486 int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain)
4487         {
4488         return tls1_check_chain(s, x, pk, chain, -1);
4489         }
4490
4491 #endif