Process signature algorithms before deciding on certificate.
[openssl.git] / ssl / t1_lib.c
1 /* ssl/t1_lib.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  * 
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  * 
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  * 
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from 
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  * 
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * 
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer. 
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111
112 #include <stdio.h>
113 #include <openssl/objects.h>
114 #include <openssl/evp.h>
115 #include <openssl/hmac.h>
116 #ifdef OPENSSL_NO_EC2M
117 #include <openssl/ec.h>
118 #endif
119 #include <openssl/ocsp.h>
120 #include <openssl/rand.h>
121 #include "ssl_locl.h"
122
123 const char tls1_version_str[]="TLSv1" OPENSSL_VERSION_PTEXT;
124
125 #ifndef OPENSSL_NO_TLSEXT
126 static int tls_decrypt_ticket(SSL *s, const unsigned char *tick, int ticklen,
127                                 const unsigned char *sess_id, int sesslen,
128                                 SSL_SESSION **psess);
129 static int ssl_check_clienthello_tlsext_early(SSL *s);
130 int ssl_check_serverhello_tlsext(SSL *s);
131 #endif
132
133 SSL3_ENC_METHOD TLSv1_enc_data={
134         tls1_enc,
135         tls1_mac,
136         tls1_setup_key_block,
137         tls1_generate_master_secret,
138         tls1_change_cipher_state,
139         tls1_final_finish_mac,
140         TLS1_FINISH_MAC_LENGTH,
141         tls1_cert_verify_mac,
142         TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
143         TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
144         tls1_alert_code,
145         tls1_export_keying_material,
146         0,
147         SSL3_HM_HEADER_LENGTH,
148         ssl3_set_handshake_header,
149         ssl3_handshake_write
150         };
151
152 SSL3_ENC_METHOD TLSv1_1_enc_data={
153         tls1_enc,
154         tls1_mac,
155         tls1_setup_key_block,
156         tls1_generate_master_secret,
157         tls1_change_cipher_state,
158         tls1_final_finish_mac,
159         TLS1_FINISH_MAC_LENGTH,
160         tls1_cert_verify_mac,
161         TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
162         TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
163         tls1_alert_code,
164         tls1_export_keying_material,
165         SSL_ENC_FLAG_EXPLICIT_IV,
166         SSL3_HM_HEADER_LENGTH,
167         ssl3_set_handshake_header,
168         ssl3_handshake_write
169         };
170
171 SSL3_ENC_METHOD TLSv1_2_enc_data={
172         tls1_enc,
173         tls1_mac,
174         tls1_setup_key_block,
175         tls1_generate_master_secret,
176         tls1_change_cipher_state,
177         tls1_final_finish_mac,
178         TLS1_FINISH_MAC_LENGTH,
179         tls1_cert_verify_mac,
180         TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
181         TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
182         tls1_alert_code,
183         tls1_export_keying_material,
184         SSL_ENC_FLAG_EXPLICIT_IV|SSL_ENC_FLAG_SIGALGS|SSL_ENC_FLAG_SHA256_PRF
185                 |SSL_ENC_FLAG_TLS1_2_CIPHERS,
186         SSL3_HM_HEADER_LENGTH,
187         ssl3_set_handshake_header,
188         ssl3_handshake_write
189         };
190
191 long tls1_default_timeout(void)
192         {
193         /* 2 hours, the 24 hours mentioned in the TLSv1 spec
194          * is way too long for http, the cache would over fill */
195         return(60*60*2);
196         }
197
198 int tls1_new(SSL *s)
199         {
200         if (!ssl3_new(s)) return(0);
201         s->method->ssl_clear(s);
202         return(1);
203         }
204
205 void tls1_free(SSL *s)
206         {
207 #ifndef OPENSSL_NO_TLSEXT
208         if (s->tlsext_session_ticket)
209                 {
210                 OPENSSL_free(s->tlsext_session_ticket);
211                 }
212 #endif /* OPENSSL_NO_TLSEXT */
213         ssl3_free(s);
214         }
215
216 void tls1_clear(SSL *s)
217         {
218         ssl3_clear(s);
219         s->version = s->method->version;
220         }
221
222 #ifndef OPENSSL_NO_EC
223
224 static int nid_list[] =
225         {
226                 NID_sect163k1, /* sect163k1 (1) */
227                 NID_sect163r1, /* sect163r1 (2) */
228                 NID_sect163r2, /* sect163r2 (3) */
229                 NID_sect193r1, /* sect193r1 (4) */ 
230                 NID_sect193r2, /* sect193r2 (5) */ 
231                 NID_sect233k1, /* sect233k1 (6) */
232                 NID_sect233r1, /* sect233r1 (7) */ 
233                 NID_sect239k1, /* sect239k1 (8) */ 
234                 NID_sect283k1, /* sect283k1 (9) */
235                 NID_sect283r1, /* sect283r1 (10) */ 
236                 NID_sect409k1, /* sect409k1 (11) */ 
237                 NID_sect409r1, /* sect409r1 (12) */
238                 NID_sect571k1, /* sect571k1 (13) */ 
239                 NID_sect571r1, /* sect571r1 (14) */ 
240                 NID_secp160k1, /* secp160k1 (15) */
241                 NID_secp160r1, /* secp160r1 (16) */ 
242                 NID_secp160r2, /* secp160r2 (17) */ 
243                 NID_secp192k1, /* secp192k1 (18) */
244                 NID_X9_62_prime192v1, /* secp192r1 (19) */ 
245                 NID_secp224k1, /* secp224k1 (20) */ 
246                 NID_secp224r1, /* secp224r1 (21) */
247                 NID_secp256k1, /* secp256k1 (22) */ 
248                 NID_X9_62_prime256v1, /* secp256r1 (23) */ 
249                 NID_secp384r1, /* secp384r1 (24) */
250                 NID_secp521r1,  /* secp521r1 (25) */    
251                 NID_brainpoolP256r1,  /* brainpoolP256r1 (26) */        
252                 NID_brainpoolP384r1,  /* brainpoolP384r1 (27) */        
253                 NID_brainpoolP512r1  /* brainpool512r1 (28) */  
254         };
255
256
257 static const unsigned char ecformats_default[] = 
258         {
259         TLSEXT_ECPOINTFORMAT_uncompressed,
260         TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime,
261         TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2
262         };
263
264 static const unsigned char eccurves_default[] =
265         {
266 #ifndef OPENSSL_NO_EC2M
267                 0,14, /* sect571r1 (14) */ 
268                 0,13, /* sect571k1 (13) */ 
269 #endif
270                 0,25, /* secp521r1 (25) */      
271                 0,28, /* brainpool512r1 (28) */ 
272 #ifndef OPENSSL_NO_EC2M
273                 0,11, /* sect409k1 (11) */ 
274                 0,12, /* sect409r1 (12) */
275 #endif
276                 0,27, /* brainpoolP384r1 (27) */        
277                 0,24, /* secp384r1 (24) */
278 #ifndef OPENSSL_NO_EC2M
279                 0,9,  /* sect283k1 (9) */
280                 0,10, /* sect283r1 (10) */ 
281 #endif
282                 0,26, /* brainpoolP256r1 (26) */        
283                 0,22, /* secp256k1 (22) */ 
284                 0,23, /* secp256r1 (23) */ 
285 #ifndef OPENSSL_NO_EC2M
286                 0,8,  /* sect239k1 (8) */ 
287                 0,6,  /* sect233k1 (6) */
288                 0,7,  /* sect233r1 (7) */ 
289 #endif
290                 0,20, /* secp224k1 (20) */ 
291                 0,21, /* secp224r1 (21) */
292 #ifndef OPENSSL_NO_EC2M
293                 0,4,  /* sect193r1 (4) */ 
294                 0,5,  /* sect193r2 (5) */ 
295 #endif
296                 0,18, /* secp192k1 (18) */
297                 0,19, /* secp192r1 (19) */ 
298 #ifndef OPENSSL_NO_EC2M
299                 0,1,  /* sect163k1 (1) */
300                 0,2,  /* sect163r1 (2) */
301                 0,3,  /* sect163r2 (3) */
302 #endif
303                 0,15, /* secp160k1 (15) */
304                 0,16, /* secp160r1 (16) */ 
305                 0,17, /* secp160r2 (17) */ 
306         };
307
308 static const unsigned char suiteb_curves[] =
309         {
310                 0, TLSEXT_curve_P_256,
311                 0, TLSEXT_curve_P_384
312         };
313
314 #ifdef OPENSSL_FIPS
315 /* Brainpool not allowed in FIPS mode */
316 static const unsigned char fips_curves_default[] =
317         {
318 #ifndef OPENSSL_NO_EC2M
319                 0,14, /* sect571r1 (14) */
320                 0,13, /* sect571k1 (13) */
321 #endif
322                 0,25, /* secp521r1 (25) */
323 #ifndef OPENSSL_NO_EC2M
324                 0,11, /* sect409k1 (11) */
325                 0,12, /* sect409r1 (12) */
326 #endif
327                 0,24, /* secp384r1 (24) */
328 #ifndef OPENSSL_NO_EC2M
329                 0,9,  /* sect283k1 (9) */
330                 0,10, /* sect283r1 (10) */
331 #endif
332                 0,22, /* secp256k1 (22) */
333                 0,23, /* secp256r1 (23) */
334 #ifndef OPENSSL_NO_EC2M
335                 0,8,  /* sect239k1 (8) */
336                 0,6,  /* sect233k1 (6) */
337                 0,7,  /* sect233r1 (7) */
338 #endif
339                 0,20, /* secp224k1 (20) */ 
340                 0,21, /* secp224r1 (21) */
341 #ifndef OPENSSL_NO_EC2M
342                 0,4,  /* sect193r1 (4) */
343                 0,5,  /* sect193r2 (5) */
344 #endif
345                 0,18, /* secp192k1 (18) */
346                 0,19, /* secp192r1 (19) */
347 #ifndef OPENSSL_NO_EC2M
348                 0,1,  /* sect163k1 (1) */
349                 0,2,  /* sect163r1 (2) */
350                 0,3,  /* sect163r2 (3) */
351 #endif
352                 0,15, /* secp160k1 (15) */
353                 0,16, /* secp160r1 (16) */
354                 0,17, /* secp160r2 (17) */
355         };
356 #endif
357
358 int tls1_ec_curve_id2nid(int curve_id)
359         {
360         /* ECC curves from RFC 4492 and RFC 7027 */
361         if ((curve_id < 1) || ((unsigned int)curve_id >
362                                 sizeof(nid_list)/sizeof(nid_list[0])))
363                 return 0;
364         return nid_list[curve_id-1];
365         }
366
367 int tls1_ec_nid2curve_id(int nid)
368         {
369         /* ECC curves from RFC 4492 and RFC 7027 */
370         switch (nid)
371                 {
372         case NID_sect163k1: /* sect163k1 (1) */
373                 return 1;
374         case NID_sect163r1: /* sect163r1 (2) */
375                 return 2;
376         case NID_sect163r2: /* sect163r2 (3) */
377                 return 3;
378         case NID_sect193r1: /* sect193r1 (4) */ 
379                 return 4;
380         case NID_sect193r2: /* sect193r2 (5) */ 
381                 return 5;
382         case NID_sect233k1: /* sect233k1 (6) */
383                 return 6;
384         case NID_sect233r1: /* sect233r1 (7) */ 
385                 return 7;
386         case NID_sect239k1: /* sect239k1 (8) */ 
387                 return 8;
388         case NID_sect283k1: /* sect283k1 (9) */
389                 return 9;
390         case NID_sect283r1: /* sect283r1 (10) */ 
391                 return 10;
392         case NID_sect409k1: /* sect409k1 (11) */ 
393                 return 11;
394         case NID_sect409r1: /* sect409r1 (12) */
395                 return 12;
396         case NID_sect571k1: /* sect571k1 (13) */ 
397                 return 13;
398         case NID_sect571r1: /* sect571r1 (14) */ 
399                 return 14;
400         case NID_secp160k1: /* secp160k1 (15) */
401                 return 15;
402         case NID_secp160r1: /* secp160r1 (16) */ 
403                 return 16;
404         case NID_secp160r2: /* secp160r2 (17) */ 
405                 return 17;
406         case NID_secp192k1: /* secp192k1 (18) */
407                 return 18;
408         case NID_X9_62_prime192v1: /* secp192r1 (19) */ 
409                 return 19;
410         case NID_secp224k1: /* secp224k1 (20) */ 
411                 return 20;
412         case NID_secp224r1: /* secp224r1 (21) */
413                 return 21;
414         case NID_secp256k1: /* secp256k1 (22) */ 
415                 return 22;
416         case NID_X9_62_prime256v1: /* secp256r1 (23) */ 
417                 return 23;
418         case NID_secp384r1: /* secp384r1 (24) */
419                 return 24;
420         case NID_secp521r1:  /* secp521r1 (25) */       
421                 return 25;
422         case NID_brainpoolP256r1:  /* brainpoolP256r1 (26) */
423                 return 26;
424         case NID_brainpoolP384r1:  /* brainpoolP384r1 (27) */
425                 return 27;
426         case NID_brainpoolP512r1:  /* brainpool512r1 (28) */
427                 return 28;
428         default:
429                 return 0;
430                 }
431         }
432 /* Get curves list, if "sess" is set return client curves otherwise
433  * preferred list
434  */
435 static void tls1_get_curvelist(SSL *s, int sess,
436                                         const unsigned char **pcurves,
437                                         size_t *pcurveslen)
438         {
439         if (sess)
440                 {
441                 *pcurves = s->session->tlsext_ellipticcurvelist;
442                 *pcurveslen = s->session->tlsext_ellipticcurvelist_length;
443                 return;
444                 }
445         /* For Suite B mode only include P-256, P-384 */
446         switch (tls1_suiteb(s))
447                 {
448         case SSL_CERT_FLAG_SUITEB_128_LOS:
449                 *pcurves = suiteb_curves;
450                 *pcurveslen = sizeof(suiteb_curves);
451                 break;
452
453         case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
454                 *pcurves = suiteb_curves;
455                 *pcurveslen = 2;
456                 break;
457
458         case SSL_CERT_FLAG_SUITEB_192_LOS:
459                 *pcurves = suiteb_curves + 2;
460                 *pcurveslen = 2;
461                 break;
462         default:
463                 *pcurves = s->tlsext_ellipticcurvelist;
464                 *pcurveslen = s->tlsext_ellipticcurvelist_length;
465                 }
466         if (!*pcurves)
467                 {
468 #ifdef OPENSSL_FIPS
469                 if (FIPS_mode())
470                         {
471                         *pcurves = fips_curves_default;
472                         *pcurveslen = sizeof(fips_curves_default);
473                         return;
474                         }
475 #endif
476                 *pcurves = eccurves_default;
477                 *pcurveslen = sizeof(eccurves_default);
478                 }
479         }
480 /* Check a curve is one of our preferences */
481 int tls1_check_curve(SSL *s, const unsigned char *p, size_t len)
482         {
483         const unsigned char *curves;
484         size_t curveslen, i;
485         unsigned int suiteb_flags = tls1_suiteb(s);
486         if (len != 3 || p[0] != NAMED_CURVE_TYPE)
487                 return 0;
488         /* Check curve matches Suite B preferences */
489         if (suiteb_flags)
490                 {
491                 unsigned long cid = s->s3->tmp.new_cipher->id;
492                 if (p[1])
493                         return 0;
494                 if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
495                         {
496                         if (p[2] != TLSEXT_curve_P_256)
497                                 return 0;
498                         }
499                 else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
500                         {
501                         if (p[2] != TLSEXT_curve_P_384)
502                                 return 0;
503                         }
504                 else    /* Should never happen */
505                         return 0;
506                 }
507         tls1_get_curvelist(s, 0, &curves, &curveslen);
508         for (i = 0; i < curveslen; i += 2, curves += 2)
509                 {
510                 if (p[1] == curves[0] && p[2] == curves[1])
511                         return 1;
512                 }
513         return 0;
514         }
515
516 /* Return nth shared curve. If nmatch == -1 return number of
517  * matches. For nmatch == -2 return the NID of the curve to use for
518  * an EC tmp key.
519  */
520
521 int tls1_shared_curve(SSL *s, int nmatch)
522         {
523         const unsigned char *pref, *supp;
524         size_t preflen, supplen, i, j;
525         int k;
526         /* Can't do anything on client side */
527         if (s->server == 0)
528                 return -1;
529         if (nmatch == -2)
530                 {
531                 if (tls1_suiteb(s))
532                         {
533                         /* For Suite B ciphersuite determines curve: we 
534                          * already know these are acceptable due to previous
535                          * checks.
536                          */
537                         unsigned long cid = s->s3->tmp.new_cipher->id;
538                         if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
539                                 return NID_X9_62_prime256v1; /* P-256 */
540                         if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
541                                 return NID_secp384r1; /* P-384 */
542                         /* Should never happen */
543                         return NID_undef;
544                         }
545                 /* If not Suite B just return first preference shared curve */
546                 nmatch = 0;
547                 }
548         tls1_get_curvelist(s, !!(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE),
549                                 &supp, &supplen);
550         tls1_get_curvelist(s, !(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE),
551                                 &pref, &preflen);
552         preflen /= 2;
553         supplen /= 2;
554         k = 0;
555         for (i = 0; i < preflen; i++, pref+=2)
556                 {
557                 const unsigned char *tsupp = supp;
558                 for (j = 0; j < supplen; j++, tsupp+=2)
559                         {
560                         if (pref[0] == tsupp[0] && pref[1] == tsupp[1])
561                                 {
562                                 if (nmatch == k)
563                                         {
564                                         int id = (pref[0] << 8) | pref[1];
565                                         return tls1_ec_curve_id2nid(id);
566                                         }
567                                 k++;
568                                 }
569                         }
570                 }
571         if (nmatch == -1)
572                 return k;
573         return 0;
574         }
575
576 int tls1_set_curves(unsigned char **pext, size_t *pextlen,
577                         int *curves, size_t ncurves)
578         {
579         unsigned char *clist, *p;
580         size_t i;
581         /* Bitmap of curves included to detect duplicates: only works
582          * while curve ids < 32 
583          */
584         unsigned long dup_list = 0;
585 #ifdef OPENSSL_NO_EC2M
586         EC_GROUP *curve;
587 #endif
588
589         clist = OPENSSL_malloc(ncurves * 2);
590         if (!clist)
591                 return 0;
592         for (i = 0, p = clist; i < ncurves; i++)
593                 {
594                 unsigned long idmask;
595                 int id;
596                 id = tls1_ec_nid2curve_id(curves[i]);
597 #ifdef OPENSSL_FIPS
598                 /* NB: 25 is last curve ID supported by FIPS module */
599                 if (FIPS_mode() && id > 25)
600                         {
601                         OPENSSL_free(clist);
602                         return 0;
603                         }
604 #endif
605 #ifdef OPENSSL_NO_EC2M
606                 curve = EC_GROUP_new_by_curve_name(curves[i]);
607                 if(!curve ||
608                         EC_METHOD_get_field_type(EC_GROUP_method_of(curve))
609                                 == NID_X9_62_characteristic_two_field)
610                         {
611                                 if(curve) EC_GROUP_free(curve);
612                                 OPENSSL_free(clist);
613                                 return 0;
614                         }
615                 else
616                         EC_GROUP_free(curve);
617 #endif
618                 idmask = 1L << id;
619                 if (!id || (dup_list & idmask))
620                         {
621                         OPENSSL_free(clist);
622                         return 0;
623                         }
624                 dup_list |= idmask;
625                 s2n(id, p);
626                 }
627         if (*pext)
628                 OPENSSL_free(*pext);
629         *pext = clist;
630         *pextlen = ncurves * 2;
631         return 1;
632         }
633
634 #define MAX_CURVELIST   28
635
636 typedef struct
637         {
638         size_t nidcnt;
639         int nid_arr[MAX_CURVELIST];
640         } nid_cb_st;
641
642 static int nid_cb(const char *elem, int len, void *arg)
643         {
644         nid_cb_st *narg = arg;
645         size_t i;
646         int nid;
647         char etmp[20];
648         if (narg->nidcnt == MAX_CURVELIST)
649                 return 0;
650         if (len > (int)(sizeof(etmp) - 1))
651                 return 0;
652         memcpy(etmp, elem, len);
653         etmp[len] = 0;
654         nid = EC_curve_nist2nid(etmp);
655         if (nid == NID_undef)
656                 nid = OBJ_sn2nid(etmp);
657         if (nid == NID_undef)
658                 nid = OBJ_ln2nid(etmp);
659         if (nid == NID_undef)
660                 return 0;
661         for (i = 0; i < narg->nidcnt; i++)
662                 if (narg->nid_arr[i] == nid)
663                         return 0;
664         narg->nid_arr[narg->nidcnt++] = nid;
665         return 1;
666         }
667 /* Set curves based on a colon separate list */
668 int tls1_set_curves_list(unsigned char **pext, size_t *pextlen, 
669                                 const char *str)
670         {
671         nid_cb_st ncb;
672         ncb.nidcnt = 0;
673         if (!CONF_parse_list(str, ':', 1, nid_cb, &ncb))
674                 return 0;
675         if (pext == NULL)
676                 return 1;
677         return tls1_set_curves(pext, pextlen, ncb.nid_arr, ncb.nidcnt);
678         }
679 /* For an EC key set TLS id and required compression based on parameters */
680 static int tls1_set_ec_id(unsigned char *curve_id, unsigned char *comp_id,
681                                 EC_KEY *ec)
682         {
683         int is_prime, id;
684         const EC_GROUP *grp;
685         const EC_METHOD *meth;
686         if (!ec)
687                 return 0;
688         /* Determine if it is a prime field */
689         grp = EC_KEY_get0_group(ec);
690         if (!grp)
691                 return 0;
692         meth = EC_GROUP_method_of(grp);
693         if (!meth)
694                 return 0;
695         if (EC_METHOD_get_field_type(meth) == NID_X9_62_prime_field)
696                 is_prime = 1;
697         else
698                 is_prime = 0;
699         /* Determine curve ID */
700         id = EC_GROUP_get_curve_name(grp);
701         id = tls1_ec_nid2curve_id(id);
702         /* If we have an ID set it, otherwise set arbitrary explicit curve */
703         if (id)
704                 {
705                 curve_id[0] = 0;
706                 curve_id[1] = (unsigned char)id;
707                 }
708         else
709                 {
710                 curve_id[0] = 0xff;
711                 if (is_prime)
712                         curve_id[1] = 0x01;
713                 else
714                         curve_id[1] = 0x02;
715                 }
716         if (comp_id)
717                 {
718                 if (EC_KEY_get0_public_key(ec) == NULL)
719                         return 0;
720                 if (EC_KEY_get_conv_form(ec) == POINT_CONVERSION_COMPRESSED)
721                         {
722                         if (is_prime)
723                                 *comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
724                         else
725                                 *comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
726                         }
727                 else
728                         *comp_id = TLSEXT_ECPOINTFORMAT_uncompressed;
729                 }
730         return 1;
731         }
732 /* Check an EC key is compatible with extensions */
733 static int tls1_check_ec_key(SSL *s,
734                         unsigned char *curve_id, unsigned char *comp_id)
735         {
736         const unsigned char *p;
737         size_t plen, i;
738         int j;
739         /* If point formats extension present check it, otherwise everything
740          * is supported (see RFC4492).
741          */
742         if (comp_id && s->session->tlsext_ecpointformatlist)
743                 {
744                 p = s->session->tlsext_ecpointformatlist;
745                 plen = s->session->tlsext_ecpointformatlist_length;
746                 for (i = 0; i < plen; i++, p++)
747                         {
748                         if (*comp_id == *p)
749                                 break;
750                         }
751                 if (i == plen)
752                         return 0;
753                 }
754         if (!curve_id)
755                 return 1;
756         /* Check curve is consistent with client and server preferences */
757         for (j = 0; j <= 1; j++)
758                 {
759                 tls1_get_curvelist(s, j, &p, &plen);
760                 for (i = 0; i < plen; i+=2, p+=2)
761                         {
762                         if (p[0] == curve_id[0] && p[1] == curve_id[1])
763                                 break;
764                         }
765                 if (i == plen)
766                         return 0;
767                 /* For clients can only check sent curve list */
768                 if (!s->server)
769                         return 1;
770                 }
771         return 1;
772         }
773
774 static void tls1_get_formatlist(SSL *s, const unsigned char **pformats,
775                                         size_t *pformatslen)
776         {
777         /* If we have a custom point format list use it otherwise
778          * use default */
779         if (s->tlsext_ecpointformatlist)
780                 {
781                 *pformats = s->tlsext_ecpointformatlist;
782                 *pformatslen = s->tlsext_ecpointformatlist_length;
783                 }
784         else
785                 {
786                 *pformats = ecformats_default;
787                 /* For Suite B we don't support char2 fields */
788                 if (tls1_suiteb(s))
789                         *pformatslen = sizeof(ecformats_default) - 1;
790                 else
791                         *pformatslen = sizeof(ecformats_default);
792                 }
793         }
794
795 /* Check cert parameters compatible with extensions: currently just checks
796  * EC certificates have compatible curves and compression.
797  */
798 static int tls1_check_cert_param(SSL *s, X509 *x, int set_ee_md)
799         {
800         unsigned char comp_id, curve_id[2];
801         EVP_PKEY *pkey;
802         int rv;
803         pkey = X509_get_pubkey(x);
804         if (!pkey)
805                 return 0;
806         /* If not EC nothing to do */
807         if (pkey->type != EVP_PKEY_EC)
808                 {
809                 EVP_PKEY_free(pkey);
810                 return 1;
811                 }
812         rv = tls1_set_ec_id(curve_id, &comp_id, pkey->pkey.ec);
813         EVP_PKEY_free(pkey);
814         if (!rv)
815                 return 0;
816         /* Can't check curve_id for client certs as we don't have a
817          * supported curves extension.
818          */
819         rv = tls1_check_ec_key(s, s->server ? curve_id : NULL, &comp_id);
820         if (!rv)
821                 return 0;
822         /* Special case for suite B. We *MUST* sign using SHA256+P-256 or
823          * SHA384+P-384, adjust digest if necessary.
824          */
825         if (set_ee_md && tls1_suiteb(s))
826                 {
827                 int check_md;
828                 size_t i;
829                 CERT *c = s->cert;
830                 if (curve_id[0])
831                         return 0;
832                 /* Check to see we have necessary signing algorithm */
833                 if (curve_id[1] == TLSEXT_curve_P_256)
834                         check_md = NID_ecdsa_with_SHA256;
835                 else if (curve_id[1] == TLSEXT_curve_P_384)
836                         check_md = NID_ecdsa_with_SHA384;
837                 else
838                         return 0; /* Should never happen */
839                 for (i = 0; i < c->shared_sigalgslen; i++)
840                         if (check_md == c->shared_sigalgs[i].signandhash_nid)
841                                 break;
842                 if (i == c->shared_sigalgslen)
843                         return 0;
844                 if (set_ee_md == 2)
845                         {
846                         if (check_md == NID_ecdsa_with_SHA256)
847                                 c->pkeys[SSL_PKEY_ECC].digest = EVP_sha256();
848                         else
849                                 c->pkeys[SSL_PKEY_ECC].digest = EVP_sha384();
850                         }
851                 }
852         return rv;
853         }
854 /* Check EC temporary key is compatible with client extensions */
855 int tls1_check_ec_tmp_key(SSL *s, unsigned long cid)
856         {
857         unsigned char curve_id[2];
858         EC_KEY *ec = s->cert->ecdh_tmp;
859 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
860         /* Allow any curve: not just those peer supports */
861         if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
862                 return 1;
863 #endif
864         /* If Suite B, AES128 MUST use P-256 and AES256 MUST use P-384,
865          * no other curves permitted.
866          */
867         if (tls1_suiteb(s))
868                 {
869                 /* Curve to check determined by ciphersuite */
870                 if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
871                         curve_id[1] = TLSEXT_curve_P_256;
872                 else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
873                         curve_id[1] = TLSEXT_curve_P_384;
874                 else
875                         return 0;
876                 curve_id[0] = 0;
877                 /* Check this curve is acceptable */
878                 if (!tls1_check_ec_key(s, curve_id, NULL))
879                         return 0;
880                 /* If auto or setting curve from callback assume OK */
881                 if (s->cert->ecdh_tmp_auto || s->cert->ecdh_tmp_cb)
882                         return 1;
883                 /* Otherwise check curve is acceptable */
884                 else 
885                         {
886                         unsigned char curve_tmp[2];
887                         if (!ec)
888                                 return 0;
889                         if (!tls1_set_ec_id(curve_tmp, NULL, ec))
890                                 return 0;
891                         if (!curve_tmp[0] || curve_tmp[1] == curve_id[1])
892                                 return 1;
893                         return 0;
894                         }
895                         
896                 }
897         if (s->cert->ecdh_tmp_auto)
898                 {
899                 /* Need a shared curve */
900                 if (tls1_shared_curve(s, 0))
901                         return 1;
902                 else return 0;
903                 }
904         if (!ec)
905                 {
906                 if (s->cert->ecdh_tmp_cb)
907                         return 1;
908                 else
909                         return 0;
910                 }
911         if (!tls1_set_ec_id(curve_id, NULL, ec))
912                 return 0;
913 /* Set this to allow use of invalid curves for testing */
914 #if 0
915         return 1;
916 #else
917         return tls1_check_ec_key(s, curve_id, NULL);
918 #endif
919         }
920
921 #else
922
923 static int tls1_check_cert_param(SSL *s, X509 *x, int set_ee_md)
924         {
925         return 1;
926         }
927
928 #endif /* OPENSSL_NO_EC */
929
930 #ifndef OPENSSL_NO_TLSEXT
931
932 /* List of supported signature algorithms and hashes. Should make this
933  * customisable at some point, for now include everything we support.
934  */
935
936 #ifdef OPENSSL_NO_RSA
937 #define tlsext_sigalg_rsa(md) /* */
938 #else
939 #define tlsext_sigalg_rsa(md) md, TLSEXT_signature_rsa,
940 #endif
941
942 #ifdef OPENSSL_NO_DSA
943 #define tlsext_sigalg_dsa(md) /* */
944 #else
945 #define tlsext_sigalg_dsa(md) md, TLSEXT_signature_dsa,
946 #endif
947
948 #ifdef OPENSSL_NO_ECDSA
949 #define tlsext_sigalg_ecdsa(md) /* */
950 #else
951 #define tlsext_sigalg_ecdsa(md) md, TLSEXT_signature_ecdsa,
952 #endif
953
954 #define tlsext_sigalg(md) \
955                 tlsext_sigalg_rsa(md) \
956                 tlsext_sigalg_dsa(md) \
957                 tlsext_sigalg_ecdsa(md)
958
959 static unsigned char tls12_sigalgs[] = {
960 #ifndef OPENSSL_NO_SHA512
961         tlsext_sigalg(TLSEXT_hash_sha512)
962         tlsext_sigalg(TLSEXT_hash_sha384)
963 #endif
964 #ifndef OPENSSL_NO_SHA256
965         tlsext_sigalg(TLSEXT_hash_sha256)
966         tlsext_sigalg(TLSEXT_hash_sha224)
967 #endif
968 #ifndef OPENSSL_NO_SHA
969         tlsext_sigalg(TLSEXT_hash_sha1)
970 #endif
971 };
972 #ifndef OPENSSL_NO_ECDSA
973 static unsigned char suiteb_sigalgs[] = {
974         tlsext_sigalg_ecdsa(TLSEXT_hash_sha256)
975         tlsext_sigalg_ecdsa(TLSEXT_hash_sha384)
976 };
977 #endif
978 size_t tls12_get_psigalgs(SSL *s, const unsigned char **psigs)
979         {
980         /* If Suite B mode use Suite B sigalgs only, ignore any other
981          * preferences.
982          */
983 #ifndef OPENSSL_NO_EC
984         switch (tls1_suiteb(s))
985                 {
986         case SSL_CERT_FLAG_SUITEB_128_LOS:
987                 *psigs = suiteb_sigalgs;
988                 return sizeof(suiteb_sigalgs);
989
990         case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
991                 *psigs = suiteb_sigalgs;
992                 return 2;
993
994         case SSL_CERT_FLAG_SUITEB_192_LOS:
995                 *psigs = suiteb_sigalgs + 2;
996                 return 2;
997                 }
998 #endif
999         /* If server use client authentication sigalgs if not NULL */
1000         if (s->server && s->cert->client_sigalgs)
1001                 {
1002                 *psigs = s->cert->client_sigalgs;
1003                 return s->cert->client_sigalgslen;
1004                 }
1005         else if (s->cert->conf_sigalgs)
1006                 {
1007                 *psigs = s->cert->conf_sigalgs;
1008                 return s->cert->conf_sigalgslen;
1009                 }
1010         else
1011                 {
1012                 *psigs = tls12_sigalgs;
1013                 return sizeof(tls12_sigalgs);
1014                 }
1015         }
1016 /* Check signature algorithm is consistent with sent supported signature
1017  * algorithms and if so return relevant digest.
1018  */
1019 int tls12_check_peer_sigalg(const EVP_MD **pmd, SSL *s,
1020                                 const unsigned char *sig, EVP_PKEY *pkey)
1021         {
1022         const unsigned char *sent_sigs;
1023         size_t sent_sigslen, i;
1024         int sigalg = tls12_get_sigid(pkey);
1025         /* Should never happen */
1026         if (sigalg == -1)
1027                 return -1;
1028         /* Check key type is consistent with signature */
1029         if (sigalg != (int)sig[1])
1030                 {
1031                 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_WRONG_SIGNATURE_TYPE);
1032                 return 0;
1033                 }
1034 #ifndef OPENSSL_NO_EC
1035         if (pkey->type == EVP_PKEY_EC)
1036                 {
1037                 unsigned char curve_id[2], comp_id;
1038                 /* Check compression and curve matches extensions */
1039                 if (!tls1_set_ec_id(curve_id, &comp_id, pkey->pkey.ec))
1040                         return 0;
1041                 if (!s->server && !tls1_check_ec_key(s, curve_id, &comp_id))
1042                         {
1043                         SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_WRONG_CURVE);
1044                         return 0;
1045                         }
1046                 /* If Suite B only P-384+SHA384 or P-256+SHA-256 allowed */
1047                 if (tls1_suiteb(s))
1048                         {
1049                         if (curve_id[0])
1050                                 return 0;
1051                         if (curve_id[1] == TLSEXT_curve_P_256)
1052                                 {
1053                                 if (sig[0] != TLSEXT_hash_sha256)
1054                                         {
1055                                         SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,
1056                                                 SSL_R_ILLEGAL_SUITEB_DIGEST);
1057                                         return 0;
1058                                         }
1059                                 }
1060                         else if (curve_id[1] == TLSEXT_curve_P_384)
1061                                 {
1062                                 if (sig[0] != TLSEXT_hash_sha384)
1063                                         {
1064                                         SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,
1065                                                 SSL_R_ILLEGAL_SUITEB_DIGEST);
1066                                         return 0;
1067                                         }
1068                                 }
1069                         else
1070                                 return 0;
1071                         }
1072                 }
1073         else if (tls1_suiteb(s))
1074                 return 0;
1075 #endif
1076
1077         /* Check signature matches a type we sent */
1078         sent_sigslen = tls12_get_psigalgs(s, &sent_sigs);
1079         for (i = 0; i < sent_sigslen; i+=2, sent_sigs+=2)
1080                 {
1081                 if (sig[0] == sent_sigs[0] && sig[1] == sent_sigs[1])
1082                         break;
1083                 }
1084         /* Allow fallback to SHA1 if not strict mode */
1085         if (i == sent_sigslen && (sig[0] != TLSEXT_hash_sha1 || s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT))
1086                 {
1087                 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_WRONG_SIGNATURE_TYPE);
1088                 return 0;
1089                 }
1090         *pmd = tls12_get_hash(sig[0]);
1091         if (*pmd == NULL)
1092                 {
1093                 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_UNKNOWN_DIGEST);
1094                 return 0;
1095                 }
1096         /* Store the digest used so applications can retrieve it if they
1097          * wish.
1098          */
1099         if (s->session && s->session->sess_cert)
1100                 s->session->sess_cert->peer_key->digest = *pmd;
1101         return 1;
1102         }
1103 /* Get a mask of disabled algorithms: an algorithm is disabled
1104  * if it isn't supported or doesn't appear in supported signature
1105  * algorithms. Unlike ssl_cipher_get_disabled this applies to a specific
1106  * session and not global settings.
1107  * 
1108  */
1109 void ssl_set_client_disabled(SSL *s)
1110         {
1111         CERT *c = s->cert;
1112         const unsigned char *sigalgs;
1113         size_t i, sigalgslen;
1114         int have_rsa = 0, have_dsa = 0, have_ecdsa = 0;
1115         c->mask_a = 0;
1116         c->mask_k = 0;
1117         /* Don't allow TLS 1.2 only ciphers if we don't suppport them */
1118         if (!SSL_CLIENT_USE_TLS1_2_CIPHERS(s))
1119                 c->mask_ssl = SSL_TLSV1_2;
1120         else
1121                 c->mask_ssl = 0;
1122         /* Now go through all signature algorithms seeing if we support
1123          * any for RSA, DSA, ECDSA. Do this for all versions not just
1124          * TLS 1.2.
1125          */
1126         sigalgslen = tls12_get_psigalgs(s, &sigalgs);
1127         for (i = 0; i < sigalgslen; i += 2, sigalgs += 2)
1128                 {
1129                 switch(sigalgs[1])
1130                         {
1131 #ifndef OPENSSL_NO_RSA
1132                 case TLSEXT_signature_rsa:
1133                         have_rsa = 1;
1134                         break;
1135 #endif
1136 #ifndef OPENSSL_NO_DSA
1137                 case TLSEXT_signature_dsa:
1138                         have_dsa = 1;
1139                         break;
1140 #endif
1141 #ifndef OPENSSL_NO_ECDSA
1142                 case TLSEXT_signature_ecdsa:
1143                         have_ecdsa = 1;
1144                         break;
1145 #endif
1146                         }
1147                 }
1148         /* Disable auth and static DH if we don't include any appropriate
1149          * signature algorithms.
1150          */
1151         if (!have_rsa)
1152                 {
1153                 c->mask_a |= SSL_aRSA;
1154                 c->mask_k |= SSL_kDHr|SSL_kECDHr;
1155                 }
1156         if (!have_dsa)
1157                 {
1158                 c->mask_a |= SSL_aDSS;
1159                 c->mask_k |= SSL_kDHd;
1160                 }
1161         if (!have_ecdsa)
1162                 {
1163                 c->mask_a |= SSL_aECDSA;
1164                 c->mask_k |= SSL_kECDHe;
1165                 }
1166 #ifndef OPENSSL_NO_KRB5
1167         if (!kssl_tgt_is_available(s->kssl_ctx))
1168                 {
1169                 c->mask_a |= SSL_aKRB5;
1170                 c->mask_k |= SSL_kKRB5;
1171                 }
1172 #endif
1173 #ifndef OPENSSL_NO_PSK
1174         /* with PSK there must be client callback set */
1175         if (!s->psk_client_callback)
1176                 {
1177                 c->mask_a |= SSL_aPSK;
1178                 c->mask_k |= SSL_kPSK;
1179                 }
1180 #endif /* OPENSSL_NO_PSK */
1181 #ifndef OPENSSL_NO_SRP
1182         if (!(s->srp_ctx.srp_Mask & SSL_kSRP))
1183                 {
1184                 c->mask_a |= SSL_aSRP;
1185                 c->mask_k |= SSL_kSRP;
1186                 }
1187 #endif
1188         c->valid = 1;
1189         }
1190
1191 unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *buf, unsigned char *limit, int *al)
1192         {
1193         int extdatalen=0;
1194         unsigned char *orig = buf;
1195         unsigned char *ret = buf;
1196 #ifndef OPENSSL_NO_EC
1197         /* See if we support any ECC ciphersuites */
1198         int using_ecc = 0;
1199         if (s->version >= TLS1_VERSION || SSL_IS_DTLS(s))
1200                 {
1201                 int i;
1202                 unsigned long alg_k, alg_a;
1203                 STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(s);
1204
1205                 for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++)
1206                         {
1207                         SSL_CIPHER *c = sk_SSL_CIPHER_value(cipher_stack, i);
1208
1209                         alg_k = c->algorithm_mkey;
1210                         alg_a = c->algorithm_auth;
1211                         if ((alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)
1212                                 || (alg_a & SSL_aECDSA)))
1213                                 {
1214                                 using_ecc = 1;
1215                                 break;
1216                                 }
1217                         }
1218                 }
1219 #endif
1220
1221         /* don't add extensions for SSLv3 unless doing secure renegotiation */
1222         if (s->client_version == SSL3_VERSION
1223                                         && !s->s3->send_connection_binding)
1224                 return orig;
1225
1226         ret+=2;
1227
1228         if (ret>=limit) return NULL; /* this really never occurs, but ... */
1229
1230         if (s->tlsext_hostname != NULL)
1231                 { 
1232                 /* Add TLS extension servername to the Client Hello message */
1233                 unsigned long size_str;
1234                 long lenmax; 
1235
1236                 /* check for enough space.
1237                    4 for the servername type and entension length
1238                    2 for servernamelist length
1239                    1 for the hostname type
1240                    2 for hostname length
1241                    + hostname length 
1242                 */
1243                    
1244                 if ((lenmax = limit - ret - 9) < 0 
1245                     || (size_str = strlen(s->tlsext_hostname)) > (unsigned long)lenmax) 
1246                         return NULL;
1247                         
1248                 /* extension type and length */
1249                 s2n(TLSEXT_TYPE_server_name,ret); 
1250                 s2n(size_str+5,ret);
1251                 
1252                 /* length of servername list */
1253                 s2n(size_str+3,ret);
1254         
1255                 /* hostname type, length and hostname */
1256                 *(ret++) = (unsigned char) TLSEXT_NAMETYPE_host_name;
1257                 s2n(size_str,ret);
1258                 memcpy(ret, s->tlsext_hostname, size_str);
1259                 ret+=size_str;
1260                 }
1261
1262         /* Add RI if renegotiating */
1263         if (s->renegotiate)
1264           {
1265           int el;
1266           
1267           if(!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0))
1268               {
1269               SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1270               return NULL;
1271               }
1272
1273           if((limit - ret - 4 - el) < 0) return NULL;
1274           
1275           s2n(TLSEXT_TYPE_renegotiate,ret);
1276           s2n(el,ret);
1277
1278           if(!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el))
1279               {
1280               SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1281               return NULL;
1282               }
1283
1284           ret += el;
1285         }
1286
1287 #ifndef OPENSSL_NO_SRP
1288         /* Add SRP username if there is one */
1289         if (s->srp_ctx.login != NULL)
1290                 { /* Add TLS extension SRP username to the Client Hello message */
1291
1292                 int login_len = strlen(s->srp_ctx.login);       
1293                 if (login_len > 255 || login_len == 0)
1294                         {
1295                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1296                         return NULL;
1297                         } 
1298
1299                 /* check for enough space.
1300                    4 for the srp type type and entension length
1301                    1 for the srp user identity
1302                    + srp user identity length 
1303                 */
1304                 if ((limit - ret - 5 - login_len) < 0) return NULL; 
1305
1306                 /* fill in the extension */
1307                 s2n(TLSEXT_TYPE_srp,ret);
1308                 s2n(login_len+1,ret);
1309                 (*ret++) = (unsigned char) login_len;
1310                 memcpy(ret, s->srp_ctx.login, login_len);
1311                 ret+=login_len;
1312                 }
1313 #endif
1314
1315 #ifndef OPENSSL_NO_EC
1316         if (using_ecc)
1317                 {
1318                 /* Add TLS extension ECPointFormats to the ClientHello message */
1319                 long lenmax; 
1320                 const unsigned char *plist;
1321                 size_t plistlen;
1322
1323                 tls1_get_formatlist(s, &plist, &plistlen);
1324
1325                 if ((lenmax = limit - ret - 5) < 0) return NULL; 
1326                 if (plistlen > (size_t)lenmax) return NULL;
1327                 if (plistlen > 255)
1328                         {
1329                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1330                         return NULL;
1331                         }
1332                 
1333                 s2n(TLSEXT_TYPE_ec_point_formats,ret);
1334                 s2n(plistlen + 1,ret);
1335                 *(ret++) = (unsigned char)plistlen ;
1336                 memcpy(ret, plist, plistlen);
1337                 ret+=plistlen;
1338
1339                 /* Add TLS extension EllipticCurves to the ClientHello message */
1340                 plist = s->tlsext_ellipticcurvelist;
1341                 tls1_get_curvelist(s, 0, &plist, &plistlen);
1342
1343                 if ((lenmax = limit - ret - 6) < 0) return NULL; 
1344                 if (plistlen > (size_t)lenmax) return NULL;
1345                 if (plistlen > 65532)
1346                         {
1347                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1348                         return NULL;
1349                         }
1350                 
1351                 s2n(TLSEXT_TYPE_elliptic_curves,ret);
1352                 s2n(plistlen + 2, ret);
1353                 s2n(plistlen, ret);
1354                 memcpy(ret, plist, plistlen);
1355                 ret+=plistlen;
1356                 }
1357 #endif /* OPENSSL_NO_EC */
1358
1359         if (!(SSL_get_options(s) & SSL_OP_NO_TICKET))
1360                 {
1361                 int ticklen;
1362                 if (!s->new_session && s->session && s->session->tlsext_tick)
1363                         ticklen = s->session->tlsext_ticklen;
1364                 else if (s->session && s->tlsext_session_ticket &&
1365                          s->tlsext_session_ticket->data)
1366                         {
1367                         ticklen = s->tlsext_session_ticket->length;
1368                         s->session->tlsext_tick = OPENSSL_malloc(ticklen);
1369                         if (!s->session->tlsext_tick)
1370                                 return NULL;
1371                         memcpy(s->session->tlsext_tick,
1372                                s->tlsext_session_ticket->data,
1373                                ticklen);
1374                         s->session->tlsext_ticklen = ticklen;
1375                         }
1376                 else
1377                         ticklen = 0;
1378                 if (ticklen == 0 && s->tlsext_session_ticket &&
1379                     s->tlsext_session_ticket->data == NULL)
1380                         goto skip_ext;
1381                 /* Check for enough room 2 for extension type, 2 for len
1382                  * rest for ticket
1383                  */
1384                 if ((long)(limit - ret - 4 - ticklen) < 0) return NULL;
1385                 s2n(TLSEXT_TYPE_session_ticket,ret); 
1386                 s2n(ticklen,ret);
1387                 if (ticklen)
1388                         {
1389                         memcpy(ret, s->session->tlsext_tick, ticklen);
1390                         ret += ticklen;
1391                         }
1392                 }
1393                 skip_ext:
1394
1395         if (SSL_USE_SIGALGS(s))
1396                 {
1397                 size_t salglen;
1398                 const unsigned char *salg;
1399                 salglen = tls12_get_psigalgs(s, &salg);
1400                 if ((size_t)(limit - ret) < salglen + 6)
1401                         return NULL; 
1402                 s2n(TLSEXT_TYPE_signature_algorithms,ret);
1403                 s2n(salglen + 2, ret);
1404                 s2n(salglen, ret);
1405                 memcpy(ret, salg, salglen);
1406                 ret += salglen;
1407                 }
1408
1409 #ifdef TLSEXT_TYPE_opaque_prf_input
1410         if (s->s3->client_opaque_prf_input != NULL)
1411                 {
1412                 size_t col = s->s3->client_opaque_prf_input_len;
1413                 
1414                 if ((long)(limit - ret - 6 - col < 0))
1415                         return NULL;
1416                 if (col > 0xFFFD) /* can't happen */
1417                         return NULL;
1418
1419                 s2n(TLSEXT_TYPE_opaque_prf_input, ret); 
1420                 s2n(col + 2, ret);
1421                 s2n(col, ret);
1422                 memcpy(ret, s->s3->client_opaque_prf_input, col);
1423                 ret += col;
1424                 }
1425 #endif
1426
1427         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp)
1428                 {
1429                 int i;
1430                 long extlen, idlen, itmp;
1431                 OCSP_RESPID *id;
1432
1433                 idlen = 0;
1434                 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
1435                         {
1436                         id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
1437                         itmp = i2d_OCSP_RESPID(id, NULL);
1438                         if (itmp <= 0)
1439                                 return NULL;
1440                         idlen += itmp + 2;
1441                         }
1442
1443                 if (s->tlsext_ocsp_exts)
1444                         {
1445                         extlen = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL);
1446                         if (extlen < 0)
1447                                 return NULL;
1448                         }
1449                 else
1450                         extlen = 0;
1451                         
1452                 if ((long)(limit - ret - 7 - extlen - idlen) < 0) return NULL;
1453                 s2n(TLSEXT_TYPE_status_request, ret);
1454                 if (extlen + idlen > 0xFFF0)
1455                         return NULL;
1456                 s2n(extlen + idlen + 5, ret);
1457                 *(ret++) = TLSEXT_STATUSTYPE_ocsp;
1458                 s2n(idlen, ret);
1459                 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
1460                         {
1461                         /* save position of id len */
1462                         unsigned char *q = ret;
1463                         id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
1464                         /* skip over id len */
1465                         ret += 2;
1466                         itmp = i2d_OCSP_RESPID(id, &ret);
1467                         /* write id len */
1468                         s2n(itmp, q);
1469                         }
1470                 s2n(extlen, ret);
1471                 if (extlen > 0)
1472                         i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret);
1473                 }
1474
1475 #ifndef OPENSSL_NO_HEARTBEATS
1476         /* Add Heartbeat extension */
1477         if ((limit - ret - 4 - 1) < 0)
1478                 return NULL;
1479         s2n(TLSEXT_TYPE_heartbeat,ret);
1480         s2n(1,ret);
1481         /* Set mode:
1482          * 1: peer may send requests
1483          * 2: peer not allowed to send requests
1484          */
1485         if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1486                 *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1487         else
1488                 *(ret++) = SSL_TLSEXT_HB_ENABLED;
1489 #endif
1490
1491 #ifndef OPENSSL_NO_NEXTPROTONEG
1492         if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len)
1493                 {
1494                 /* The client advertises an emtpy extension to indicate its
1495                  * support for Next Protocol Negotiation */
1496                 if (limit - ret - 4 < 0)
1497                         return NULL;
1498                 s2n(TLSEXT_TYPE_next_proto_neg,ret);
1499                 s2n(0,ret);
1500                 }
1501 #endif
1502
1503         if (s->alpn_client_proto_list && !s->s3->tmp.finish_md_len)
1504                 {
1505                 if ((size_t)(limit - ret) < 6 + s->alpn_client_proto_list_len)
1506                         return NULL;
1507                 s2n(TLSEXT_TYPE_application_layer_protocol_negotiation,ret);
1508                 s2n(2 + s->alpn_client_proto_list_len,ret);
1509                 s2n(s->alpn_client_proto_list_len,ret);
1510                 memcpy(ret, s->alpn_client_proto_list,
1511                        s->alpn_client_proto_list_len);
1512                 ret += s->alpn_client_proto_list_len;
1513                 }
1514
1515         if(SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s))
1516                 {
1517                 int el;
1518
1519                 ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0);
1520                 
1521                 if((limit - ret - 4 - el) < 0) return NULL;
1522
1523                 s2n(TLSEXT_TYPE_use_srtp,ret);
1524                 s2n(el,ret);
1525
1526                 if(ssl_add_clienthello_use_srtp_ext(s, ret, &el, el))
1527                         {
1528                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1529                         return NULL;
1530                         }
1531                 ret += el;
1532                 }
1533         custom_ext_init(&s->cert->cli_ext);
1534         /* Add custom TLS Extensions to ClientHello */
1535         if (!custom_ext_add(s, 0, &ret, limit, al))
1536                 return NULL;
1537
1538         /* Add padding to workaround bugs in F5 terminators.
1539          * See https://tools.ietf.org/html/draft-agl-tls-padding-03
1540          *
1541          * NB: because this code works out the length of all existing
1542          * extensions it MUST always appear last.
1543          */
1544         if (s->options & SSL_OP_TLSEXT_PADDING)
1545                 {
1546                 int hlen = ret - (unsigned char *)s->init_buf->data;
1547                 /* The code in s23_clnt.c to build ClientHello messages
1548                  * includes the 5-byte record header in the buffer, while
1549                  * the code in s3_clnt.c does not.
1550                  */
1551                 if (s->state == SSL23_ST_CW_CLNT_HELLO_A)
1552                         hlen -= 5;
1553                 if (hlen > 0xff && hlen < 0x200)
1554                         {
1555                         hlen = 0x200 - hlen;
1556                         if (hlen >= 4)
1557                                 hlen -= 4;
1558                         else
1559                                 hlen = 0;
1560
1561                         s2n(TLSEXT_TYPE_padding, ret);
1562                         s2n(hlen, ret);
1563                         memset(ret, 0, hlen);
1564                         ret += hlen;
1565                         }
1566                 }
1567
1568         if ((extdatalen = ret-orig-2)== 0) 
1569                 return orig;
1570
1571         s2n(extdatalen, orig);
1572         return ret;
1573         }
1574
1575 unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *buf, unsigned char *limit, int *al)
1576         {
1577         int extdatalen=0;
1578         unsigned char *orig = buf;
1579         unsigned char *ret = buf;
1580 #ifndef OPENSSL_NO_NEXTPROTONEG
1581         int next_proto_neg_seen;
1582 #endif
1583 #ifndef OPENSSL_NO_EC
1584         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1585         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1586         int using_ecc = (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA);
1587         using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL);
1588 #endif
1589         /* don't add extensions for SSLv3, unless doing secure renegotiation */
1590         if (s->version == SSL3_VERSION && !s->s3->send_connection_binding)
1591                 return orig;
1592         
1593         ret+=2;
1594         if (ret>=limit) return NULL; /* this really never occurs, but ... */
1595
1596         if (!s->hit && s->servername_done == 1 && s->session->tlsext_hostname != NULL)
1597                 { 
1598                 if ((long)(limit - ret - 4) < 0) return NULL; 
1599
1600                 s2n(TLSEXT_TYPE_server_name,ret);
1601                 s2n(0,ret);
1602                 }
1603
1604         if(s->s3->send_connection_binding)
1605         {
1606           int el;
1607           
1608           if(!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0))
1609               {
1610               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1611               return NULL;
1612               }
1613
1614           if((limit - ret - 4 - el) < 0) return NULL;
1615           
1616           s2n(TLSEXT_TYPE_renegotiate,ret);
1617           s2n(el,ret);
1618
1619           if(!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el))
1620               {
1621               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1622               return NULL;
1623               }
1624
1625           ret += el;
1626         }
1627
1628 #ifndef OPENSSL_NO_EC
1629         if (using_ecc)
1630                 {
1631                 const unsigned char *plist;
1632                 size_t plistlen;
1633                 /* Add TLS extension ECPointFormats to the ServerHello message */
1634                 long lenmax; 
1635
1636                 tls1_get_formatlist(s, &plist, &plistlen);
1637
1638                 if ((lenmax = limit - ret - 5) < 0) return NULL; 
1639                 if (plistlen > (size_t)lenmax) return NULL;
1640                 if (plistlen > 255)
1641                         {
1642                         SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1643                         return NULL;
1644                         }
1645                 
1646                 s2n(TLSEXT_TYPE_ec_point_formats,ret);
1647                 s2n(plistlen + 1,ret);
1648                 *(ret++) = (unsigned char) plistlen;
1649                 memcpy(ret, plist, plistlen);
1650                 ret+=plistlen;
1651
1652                 }
1653         /* Currently the server should not respond with a SupportedCurves extension */
1654 #endif /* OPENSSL_NO_EC */
1655
1656         if (s->tlsext_ticket_expected
1657                 && !(SSL_get_options(s) & SSL_OP_NO_TICKET)) 
1658                 { 
1659                 if ((long)(limit - ret - 4) < 0) return NULL; 
1660                 s2n(TLSEXT_TYPE_session_ticket,ret);
1661                 s2n(0,ret);
1662                 }
1663
1664         if (s->tlsext_status_expected)
1665                 { 
1666                 if ((long)(limit - ret - 4) < 0) return NULL; 
1667                 s2n(TLSEXT_TYPE_status_request,ret);
1668                 s2n(0,ret);
1669                 }
1670
1671 #ifdef TLSEXT_TYPE_opaque_prf_input
1672         if (s->s3->server_opaque_prf_input != NULL)
1673                 {
1674                 size_t sol = s->s3->server_opaque_prf_input_len;
1675                 
1676                 if ((long)(limit - ret - 6 - sol) < 0)
1677                         return NULL;
1678                 if (sol > 0xFFFD) /* can't happen */
1679                         return NULL;
1680
1681                 s2n(TLSEXT_TYPE_opaque_prf_input, ret); 
1682                 s2n(sol + 2, ret);
1683                 s2n(sol, ret);
1684                 memcpy(ret, s->s3->server_opaque_prf_input, sol);
1685                 ret += sol;
1686                 }
1687 #endif
1688
1689         if(SSL_IS_DTLS(s) && s->srtp_profile)
1690                 {
1691                 int el;
1692
1693                 ssl_add_serverhello_use_srtp_ext(s, 0, &el, 0);
1694                 
1695                 if((limit - ret - 4 - el) < 0) return NULL;
1696
1697                 s2n(TLSEXT_TYPE_use_srtp,ret);
1698                 s2n(el,ret);
1699
1700                 if(ssl_add_serverhello_use_srtp_ext(s, ret, &el, el))
1701                         {
1702                         SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1703                         return NULL;
1704                         }
1705                 ret+=el;
1706                 }
1707
1708         if (((s->s3->tmp.new_cipher->id & 0xFFFF)==0x80 || (s->s3->tmp.new_cipher->id & 0xFFFF)==0x81) 
1709                 && (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG))
1710                 { const unsigned char cryptopro_ext[36] = {
1711                         0xfd, 0xe8, /*65000*/
1712                         0x00, 0x20, /*32 bytes length*/
1713                         0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85, 
1714                         0x03,   0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06, 
1715                         0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08, 
1716                         0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17};
1717                         if (limit-ret<36) return NULL;
1718                         memcpy(ret,cryptopro_ext,36);
1719                         ret+=36;
1720
1721                 }
1722
1723 #ifndef OPENSSL_NO_HEARTBEATS
1724         /* Add Heartbeat extension if we've received one */
1725         if (s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED)
1726                 {
1727                 if ((limit - ret - 4 - 1) < 0)
1728                         return NULL;
1729                 s2n(TLSEXT_TYPE_heartbeat,ret);
1730                 s2n(1,ret);
1731                 /* Set mode:
1732                  * 1: peer may send requests
1733                  * 2: peer not allowed to send requests
1734                  */
1735                 if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1736                         *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1737                 else
1738                         *(ret++) = SSL_TLSEXT_HB_ENABLED;
1739
1740                 }
1741 #endif
1742
1743 #ifndef OPENSSL_NO_NEXTPROTONEG
1744         next_proto_neg_seen = s->s3->next_proto_neg_seen;
1745         s->s3->next_proto_neg_seen = 0;
1746         if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb)
1747                 {
1748                 const unsigned char *npa;
1749                 unsigned int npalen;
1750                 int r;
1751
1752                 r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen, s->ctx->next_protos_advertised_cb_arg);
1753                 if (r == SSL_TLSEXT_ERR_OK)
1754                         {
1755                         if ((long)(limit - ret - 4 - npalen) < 0) return NULL;
1756                         s2n(TLSEXT_TYPE_next_proto_neg,ret);
1757                         s2n(npalen,ret);
1758                         memcpy(ret, npa, npalen);
1759                         ret += npalen;
1760                         s->s3->next_proto_neg_seen = 1;
1761                         }
1762                 }
1763 #endif
1764         if (!custom_ext_add(s, 1, &ret, limit, al))
1765                 return NULL;
1766
1767         if (s->s3->alpn_selected)
1768                 {
1769                 const unsigned char *selected = s->s3->alpn_selected;
1770                 unsigned len = s->s3->alpn_selected_len;
1771
1772                 if ((long)(limit - ret - 4 - 2 - 1 - len) < 0)
1773                         return NULL;
1774                 s2n(TLSEXT_TYPE_application_layer_protocol_negotiation,ret);
1775                 s2n(3 + len,ret);
1776                 s2n(1 + len,ret);
1777                 *ret++ = len;
1778                 memcpy(ret, selected, len);
1779                 ret += len;
1780                 }
1781
1782         if ((extdatalen = ret-orig-2)== 0) 
1783                 return orig;
1784
1785         s2n(extdatalen, orig);
1786         return ret;
1787         }
1788
1789 #ifndef OPENSSL_NO_EC
1790 /* ssl_check_for_safari attempts to fingerprint Safari using OS X
1791  * SecureTransport using the TLS extension block in |d|, of length |n|.
1792  * Safari, since 10.6, sends exactly these extensions, in this order:
1793  *   SNI,
1794  *   elliptic_curves
1795  *   ec_point_formats
1796  *
1797  * We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,
1798  * but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.
1799  * Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from
1800  * 10.8..10.8.3 (which don't work).
1801  */
1802 static void ssl_check_for_safari(SSL *s, const unsigned char *data, const unsigned char *d, int n) {
1803         unsigned short type, size;
1804         static const unsigned char kSafariExtensionsBlock[] = {
1805                 0x00, 0x0a,  /* elliptic_curves extension */
1806                 0x00, 0x08,  /* 8 bytes */
1807                 0x00, 0x06,  /* 6 bytes of curve ids */
1808                 0x00, 0x17,  /* P-256 */
1809                 0x00, 0x18,  /* P-384 */
1810                 0x00, 0x19,  /* P-521 */
1811
1812                 0x00, 0x0b,  /* ec_point_formats */
1813                 0x00, 0x02,  /* 2 bytes */
1814                 0x01,        /* 1 point format */
1815                 0x00,        /* uncompressed */
1816         };
1817
1818         /* The following is only present in TLS 1.2 */
1819         static const unsigned char kSafariTLS12ExtensionsBlock[] = {
1820                 0x00, 0x0d,  /* signature_algorithms */
1821                 0x00, 0x0c,  /* 12 bytes */
1822                 0x00, 0x0a,  /* 10 bytes */
1823                 0x05, 0x01,  /* SHA-384/RSA */
1824                 0x04, 0x01,  /* SHA-256/RSA */
1825                 0x02, 0x01,  /* SHA-1/RSA */
1826                 0x04, 0x03,  /* SHA-256/ECDSA */
1827                 0x02, 0x03,  /* SHA-1/ECDSA */
1828         };
1829
1830         if (data >= (d+n-2))
1831                 return;
1832         data += 2;
1833
1834         if (data > (d+n-4))
1835                 return;
1836         n2s(data,type);
1837         n2s(data,size);
1838
1839         if (type != TLSEXT_TYPE_server_name)
1840                 return;
1841
1842         if (data+size > d+n)
1843                 return;
1844         data += size;
1845
1846         if (TLS1_get_client_version(s) >= TLS1_2_VERSION)
1847                 {
1848                 const size_t len1 = sizeof(kSafariExtensionsBlock);
1849                 const size_t len2 = sizeof(kSafariTLS12ExtensionsBlock);
1850
1851                 if (data + len1 + len2 != d+n)
1852                         return;
1853                 if (memcmp(data, kSafariExtensionsBlock, len1) != 0)
1854                         return;
1855                 if (memcmp(data + len1, kSafariTLS12ExtensionsBlock, len2) != 0)
1856                         return;
1857                 }
1858         else
1859                 {
1860                 const size_t len = sizeof(kSafariExtensionsBlock);
1861
1862                 if (data + len != d+n)
1863                         return;
1864                 if (memcmp(data, kSafariExtensionsBlock, len) != 0)
1865                         return;
1866                 }
1867
1868         s->s3->is_probably_safari = 1;
1869 }
1870 #endif /* !OPENSSL_NO_EC */
1871
1872 /* tls1_alpn_handle_client_hello is called to process the ALPN extension in a
1873  * ClientHello.
1874  *   data: the contents of the extension, not including the type and length.
1875  *   data_len: the number of bytes in |data|
1876  *   al: a pointer to the alert value to send in the event of a non-zero
1877  *       return.
1878  *
1879  *   returns: 0 on success. */
1880 static int tls1_alpn_handle_client_hello(SSL *s, const unsigned char *data,
1881                                          unsigned data_len, int *al)
1882         {
1883         unsigned i;
1884         unsigned proto_len;
1885         const unsigned char *selected;
1886         unsigned char selected_len;
1887         int r;
1888
1889         if (s->ctx->alpn_select_cb == NULL)
1890                 return 0;
1891
1892         if (data_len < 2)
1893                 goto parse_error;
1894
1895         /* data should contain a uint16 length followed by a series of 8-bit,
1896          * length-prefixed strings. */
1897         i = ((unsigned) data[0]) << 8 |
1898             ((unsigned) data[1]);
1899         data_len -= 2;
1900         data += 2;
1901         if (data_len != i)
1902                 goto parse_error;
1903
1904         if (data_len < 2)
1905                 goto parse_error;
1906
1907         for (i = 0; i < data_len;)
1908                 {
1909                 proto_len = data[i];
1910                 i++;
1911
1912                 if (proto_len == 0)
1913                         goto parse_error;
1914
1915                 if (i + proto_len < i || i + proto_len > data_len)
1916                         goto parse_error;
1917
1918                 i += proto_len;
1919                 }
1920
1921         r = s->ctx->alpn_select_cb(s, &selected, &selected_len, data, data_len,
1922                                    s->ctx->alpn_select_cb_arg);
1923         if (r == SSL_TLSEXT_ERR_OK) {
1924                 if (s->s3->alpn_selected)
1925                         OPENSSL_free(s->s3->alpn_selected);
1926                 s->s3->alpn_selected = OPENSSL_malloc(selected_len);
1927                 if (!s->s3->alpn_selected)
1928                         {
1929                         *al = SSL_AD_INTERNAL_ERROR;
1930                         return -1;
1931                         }
1932                 memcpy(s->s3->alpn_selected, selected, selected_len);
1933                 s->s3->alpn_selected_len = selected_len;
1934         }
1935         return 0;
1936
1937 parse_error:
1938         *al = SSL_AD_DECODE_ERROR;
1939         return -1;
1940         }
1941
1942 static int ssl_scan_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al) 
1943         {       
1944         unsigned short type;
1945         unsigned short size;
1946         unsigned short len;
1947         unsigned char *data = *p;
1948         int renegotiate_seen = 0;
1949
1950         s->servername_done = 0;
1951         s->tlsext_status_type = -1;
1952 #ifndef OPENSSL_NO_NEXTPROTONEG
1953         s->s3->next_proto_neg_seen = 0;
1954 #endif
1955
1956         if (s->s3->alpn_selected)
1957                 {
1958                 OPENSSL_free(s->s3->alpn_selected);
1959                 s->s3->alpn_selected = NULL;
1960                 }
1961
1962 #ifndef OPENSSL_NO_HEARTBEATS
1963         s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
1964                                SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
1965 #endif
1966
1967 #ifndef OPENSSL_NO_EC
1968         if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
1969                 ssl_check_for_safari(s, data, d, n);
1970 #endif /* !OPENSSL_NO_EC */
1971
1972         /* Clear any signature algorithms extension received */
1973         if (s->cert->peer_sigalgs)
1974                 {
1975                 OPENSSL_free(s->cert->peer_sigalgs);
1976                 s->cert->peer_sigalgs = NULL;
1977                 }
1978
1979         if (data >= (d+n-2))
1980                 goto ri_check;
1981         n2s(data,len);
1982
1983         if (data > (d+n-len)) 
1984                 goto ri_check;
1985
1986         while (data <= (d+n-4))
1987                 {
1988                 n2s(data,type);
1989                 n2s(data,size);
1990
1991                 if (data+size > (d+n))
1992                         goto ri_check;
1993 #if 0
1994                 fprintf(stderr,"Received extension type %d size %d\n",type,size);
1995 #endif
1996                 if (s->tlsext_debug_cb)
1997                         s->tlsext_debug_cb(s, 0, type, data, size,
1998                                                 s->tlsext_debug_arg);
1999 /* The servername extension is treated as follows:
2000
2001    - Only the hostname type is supported with a maximum length of 255.
2002    - The servername is rejected if too long or if it contains zeros,
2003      in which case an fatal alert is generated.
2004    - The servername field is maintained together with the session cache.
2005    - When a session is resumed, the servername call back invoked in order
2006      to allow the application to position itself to the right context. 
2007    - The servername is acknowledged if it is new for a session or when 
2008      it is identical to a previously used for the same session. 
2009      Applications can control the behaviour.  They can at any time
2010      set a 'desirable' servername for a new SSL object. This can be the
2011      case for example with HTTPS when a Host: header field is received and
2012      a renegotiation is requested. In this case, a possible servername
2013      presented in the new client hello is only acknowledged if it matches
2014      the value of the Host: field. 
2015    - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
2016      if they provide for changing an explicit servername context for the session,
2017      i.e. when the session has been established with a servername extension. 
2018    - On session reconnect, the servername extension may be absent. 
2019
2020 */      
2021
2022                 if (type == TLSEXT_TYPE_server_name)
2023                         {
2024                         unsigned char *sdata;
2025                         int servname_type;
2026                         int dsize; 
2027                 
2028                         if (size < 2) 
2029                                 {
2030                                 *al = SSL_AD_DECODE_ERROR;
2031                                 return 0;
2032                                 }
2033                         n2s(data,dsize);  
2034                         size -= 2;
2035                         if (dsize > size  ) 
2036                                 {
2037                                 *al = SSL_AD_DECODE_ERROR;
2038                                 return 0;
2039                                 } 
2040
2041                         sdata = data;
2042                         while (dsize > 3) 
2043                                 {
2044                                 servname_type = *(sdata++); 
2045                                 n2s(sdata,len);
2046                                 dsize -= 3;
2047
2048                                 if (len > dsize) 
2049                                         {
2050                                         *al = SSL_AD_DECODE_ERROR;
2051                                         return 0;
2052                                         }
2053                                 if (s->servername_done == 0)
2054                                 switch (servname_type)
2055                                         {
2056                                 case TLSEXT_NAMETYPE_host_name:
2057                                         if (!s->hit)
2058                                                 {
2059                                                 if(s->session->tlsext_hostname)
2060                                                         {
2061                                                         *al = SSL_AD_DECODE_ERROR;
2062                                                         return 0;
2063                                                         }
2064                                                 if (len > TLSEXT_MAXLEN_host_name)
2065                                                         {
2066                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
2067                                                         return 0;
2068                                                         }
2069                                                 if ((s->session->tlsext_hostname = OPENSSL_malloc(len+1)) == NULL)
2070                                                         {
2071                                                         *al = TLS1_AD_INTERNAL_ERROR;
2072                                                         return 0;
2073                                                         }
2074                                                 memcpy(s->session->tlsext_hostname, sdata, len);
2075                                                 s->session->tlsext_hostname[len]='\0';
2076                                                 if (strlen(s->session->tlsext_hostname) != len) {
2077                                                         OPENSSL_free(s->session->tlsext_hostname);
2078                                                         s->session->tlsext_hostname = NULL;
2079                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
2080                                                         return 0;
2081                                                 }
2082                                                 s->servername_done = 1; 
2083
2084                                                 }
2085                                         else 
2086                                                 s->servername_done = s->session->tlsext_hostname
2087                                                         && strlen(s->session->tlsext_hostname) == len 
2088                                                         && strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0;
2089                                         
2090                                         break;
2091
2092                                 default:
2093                                         break;
2094                                         }
2095                                  
2096                                 dsize -= len;
2097                                 }
2098                         if (dsize != 0) 
2099                                 {
2100                                 *al = SSL_AD_DECODE_ERROR;
2101                                 return 0;
2102                                 }
2103
2104                         }
2105 #ifndef OPENSSL_NO_SRP
2106                 else if (type == TLSEXT_TYPE_srp)
2107                         {
2108                         if (size <= 0 || ((len = data[0])) != (size -1))
2109                                 {
2110                                 *al = SSL_AD_DECODE_ERROR;
2111                                 return 0;
2112                                 }
2113                         if (s->srp_ctx.login != NULL)
2114                                 {
2115                                 *al = SSL_AD_DECODE_ERROR;
2116                                 return 0;
2117                                 }
2118                         if ((s->srp_ctx.login = OPENSSL_malloc(len+1)) == NULL)
2119                                 return -1;
2120                         memcpy(s->srp_ctx.login, &data[1], len);
2121                         s->srp_ctx.login[len]='\0';
2122   
2123                         if (strlen(s->srp_ctx.login) != len) 
2124                                 {
2125                                 *al = SSL_AD_DECODE_ERROR;
2126                                 return 0;
2127                                 }
2128                         }
2129 #endif
2130
2131 #ifndef OPENSSL_NO_EC
2132                 else if (type == TLSEXT_TYPE_ec_point_formats)
2133                         {
2134                         unsigned char *sdata = data;
2135                         int ecpointformatlist_length = *(sdata++);
2136
2137                         if (ecpointformatlist_length != size - 1 || 
2138                                 ecpointformatlist_length < 1)
2139                                 {
2140                                 *al = TLS1_AD_DECODE_ERROR;
2141                                 return 0;
2142                                 }
2143                         if (!s->hit)
2144                                 {
2145                                 if(s->session->tlsext_ecpointformatlist)
2146                                         {
2147                                         OPENSSL_free(s->session->tlsext_ecpointformatlist);
2148                                         s->session->tlsext_ecpointformatlist = NULL;
2149                                         }
2150                                 s->session->tlsext_ecpointformatlist_length = 0;
2151                                 if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
2152                                         {
2153                                         *al = TLS1_AD_INTERNAL_ERROR;
2154                                         return 0;
2155                                         }
2156                                 s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
2157                                 memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
2158                                 }
2159 #if 0
2160                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ", s->session->tlsext_ecpointformatlist_length);
2161                         sdata = s->session->tlsext_ecpointformatlist;
2162                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2163                                 fprintf(stderr,"%i ",*(sdata++));
2164                         fprintf(stderr,"\n");
2165 #endif
2166                         }
2167                 else if (type == TLSEXT_TYPE_elliptic_curves)
2168                         {
2169                         unsigned char *sdata = data;
2170                         int ellipticcurvelist_length = (*(sdata++) << 8);
2171                         ellipticcurvelist_length += (*(sdata++));
2172
2173                         if (ellipticcurvelist_length != size - 2 ||
2174                                 ellipticcurvelist_length < 1)
2175                                 {
2176                                 *al = TLS1_AD_DECODE_ERROR;
2177                                 return 0;
2178                                 }
2179                         if (!s->hit)
2180                                 {
2181                                 if(s->session->tlsext_ellipticcurvelist)
2182                                         {
2183                                         *al = TLS1_AD_DECODE_ERROR;
2184                                         return 0;
2185                                         }
2186                                 s->session->tlsext_ellipticcurvelist_length = 0;
2187                                 if ((s->session->tlsext_ellipticcurvelist = OPENSSL_malloc(ellipticcurvelist_length)) == NULL)
2188                                         {
2189                                         *al = TLS1_AD_INTERNAL_ERROR;
2190                                         return 0;
2191                                         }
2192                                 s->session->tlsext_ellipticcurvelist_length = ellipticcurvelist_length;
2193                                 memcpy(s->session->tlsext_ellipticcurvelist, sdata, ellipticcurvelist_length);
2194                                 }
2195 #if 0
2196                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ", s->session->tlsext_ellipticcurvelist_length);
2197                         sdata = s->session->tlsext_ellipticcurvelist;
2198                         for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++)
2199                                 fprintf(stderr,"%i ",*(sdata++));
2200                         fprintf(stderr,"\n");
2201 #endif
2202                         }
2203 #endif /* OPENSSL_NO_EC */
2204 #ifdef TLSEXT_TYPE_opaque_prf_input
2205                 else if (type == TLSEXT_TYPE_opaque_prf_input)
2206                         {
2207                         unsigned char *sdata = data;
2208
2209                         if (size < 2)
2210                                 {
2211                                 *al = SSL_AD_DECODE_ERROR;
2212                                 return 0;
2213                                 }
2214                         n2s(sdata, s->s3->client_opaque_prf_input_len);
2215                         if (s->s3->client_opaque_prf_input_len != size - 2)
2216                                 {
2217                                 *al = SSL_AD_DECODE_ERROR;
2218                                 return 0;
2219                                 }
2220
2221                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
2222                                 OPENSSL_free(s->s3->client_opaque_prf_input);
2223                         if (s->s3->client_opaque_prf_input_len == 0)
2224                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2225                         else
2226                                 s->s3->client_opaque_prf_input = BUF_memdup(sdata, s->s3->client_opaque_prf_input_len);
2227                         if (s->s3->client_opaque_prf_input == NULL)
2228                                 {
2229                                 *al = TLS1_AD_INTERNAL_ERROR;
2230                                 return 0;
2231                                 }
2232                         }
2233 #endif
2234                 else if (type == TLSEXT_TYPE_session_ticket)
2235                         {
2236                         if (s->tls_session_ticket_ext_cb &&
2237                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
2238                                 {
2239                                 *al = TLS1_AD_INTERNAL_ERROR;
2240                                 return 0;
2241                                 }
2242                         }
2243                 else if (type == TLSEXT_TYPE_renegotiate)
2244                         {
2245                         if(!ssl_parse_clienthello_renegotiate_ext(s, data, size, al))
2246                                 return 0;
2247                         renegotiate_seen = 1;
2248                         }
2249                 else if (type == TLSEXT_TYPE_signature_algorithms)
2250                         {
2251                         int dsize;
2252                         if (s->cert->peer_sigalgs || size < 2) 
2253                                 {
2254                                 *al = SSL_AD_DECODE_ERROR;
2255                                 return 0;
2256                                 }
2257                         n2s(data,dsize);
2258                         size -= 2;
2259                         if (dsize != size || dsize & 1 || !dsize) 
2260                                 {
2261                                 *al = SSL_AD_DECODE_ERROR;
2262                                 return 0;
2263                                 }
2264                         if (!tls1_save_sigalgs(s, data, dsize))
2265                                 {
2266                                 *al = SSL_AD_DECODE_ERROR;
2267                                 return 0;
2268                                 }
2269                         }
2270                 else if (type == TLSEXT_TYPE_status_request)
2271                         {
2272                 
2273                         if (size < 5) 
2274                                 {
2275                                 *al = SSL_AD_DECODE_ERROR;
2276                                 return 0;
2277                                 }
2278
2279                         s->tlsext_status_type = *data++;
2280                         size--;
2281                         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp)
2282                                 {
2283                                 const unsigned char *sdata;
2284                                 int dsize;
2285                                 /* Read in responder_id_list */
2286                                 n2s(data,dsize);
2287                                 size -= 2;
2288                                 if (dsize > size  ) 
2289                                         {
2290                                         *al = SSL_AD_DECODE_ERROR;
2291                                         return 0;
2292                                         }
2293                                 while (dsize > 0)
2294                                         {
2295                                         OCSP_RESPID *id;
2296                                         int idsize;
2297                                         if (dsize < 4)
2298                                                 {
2299                                                 *al = SSL_AD_DECODE_ERROR;
2300                                                 return 0;
2301                                                 }
2302                                         n2s(data, idsize);
2303                                         dsize -= 2 + idsize;
2304                                         size -= 2 + idsize;
2305                                         if (dsize < 0)
2306                                                 {
2307                                                 *al = SSL_AD_DECODE_ERROR;
2308                                                 return 0;
2309                                                 }
2310                                         sdata = data;
2311                                         data += idsize;
2312                                         id = d2i_OCSP_RESPID(NULL,
2313                                                                 &sdata, idsize);
2314                                         if (!id)
2315                                                 {
2316                                                 *al = SSL_AD_DECODE_ERROR;
2317                                                 return 0;
2318                                                 }
2319                                         if (data != sdata)
2320                                                 {
2321                                                 OCSP_RESPID_free(id);
2322                                                 *al = SSL_AD_DECODE_ERROR;
2323                                                 return 0;
2324                                                 }
2325                                         if (!s->tlsext_ocsp_ids
2326                                                 && !(s->tlsext_ocsp_ids =
2327                                                 sk_OCSP_RESPID_new_null()))
2328                                                 {
2329                                                 OCSP_RESPID_free(id);
2330                                                 *al = SSL_AD_INTERNAL_ERROR;
2331                                                 return 0;
2332                                                 }
2333                                         if (!sk_OCSP_RESPID_push(
2334                                                         s->tlsext_ocsp_ids, id))
2335                                                 {
2336                                                 OCSP_RESPID_free(id);
2337                                                 *al = SSL_AD_INTERNAL_ERROR;
2338                                                 return 0;
2339                                                 }
2340                                         }
2341
2342                                 /* Read in request_extensions */
2343                                 if (size < 2)
2344                                         {
2345                                         *al = SSL_AD_DECODE_ERROR;
2346                                         return 0;
2347                                         }
2348                                 n2s(data,dsize);
2349                                 size -= 2;
2350                                 if (dsize != size)
2351                                         {
2352                                         *al = SSL_AD_DECODE_ERROR;
2353                                         return 0;
2354                                         }
2355                                 sdata = data;
2356                                 if (dsize > 0)
2357                                         {
2358                                         if (s->tlsext_ocsp_exts)
2359                                                 {
2360                                                 sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
2361                                                                            X509_EXTENSION_free);
2362                                                 }
2363
2364                                         s->tlsext_ocsp_exts =
2365                                                 d2i_X509_EXTENSIONS(NULL,
2366                                                         &sdata, dsize);
2367                                         if (!s->tlsext_ocsp_exts
2368                                                 || (data + dsize != sdata))
2369                                                 {
2370                                                 *al = SSL_AD_DECODE_ERROR;
2371                                                 return 0;
2372                                                 }
2373                                         }
2374                                 }
2375                                 /* We don't know what to do with any other type
2376                                 * so ignore it.
2377                                 */
2378                                 else
2379                                         s->tlsext_status_type = -1;
2380                         }
2381 #ifndef OPENSSL_NO_HEARTBEATS
2382                 else if (type == TLSEXT_TYPE_heartbeat)
2383                         {
2384                         switch(data[0])
2385                                 {
2386                                 case 0x01:      /* Client allows us to send HB requests */
2387                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2388                                                         break;
2389                                 case 0x02:      /* Client doesn't accept HB requests */
2390                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2391                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2392                                                         break;
2393                                 default:        *al = SSL_AD_ILLEGAL_PARAMETER;
2394                                                         return 0;
2395                                 }
2396                         }
2397 #endif
2398 #ifndef OPENSSL_NO_NEXTPROTONEG
2399                 else if (type == TLSEXT_TYPE_next_proto_neg &&
2400                          s->s3->tmp.finish_md_len == 0 &&
2401                          s->s3->alpn_selected == NULL)
2402                         {
2403                         /* We shouldn't accept this extension on a
2404                          * renegotiation.
2405                          *
2406                          * s->new_session will be set on renegotiation, but we
2407                          * probably shouldn't rely that it couldn't be set on
2408                          * the initial renegotation too in certain cases (when
2409                          * there's some other reason to disallow resuming an
2410                          * earlier session -- the current code won't be doing
2411                          * anything like that, but this might change).
2412
2413                          * A valid sign that there's been a previous handshake
2414                          * in this connection is if s->s3->tmp.finish_md_len >
2415                          * 0.  (We are talking about a check that will happen
2416                          * in the Hello protocol round, well before a new
2417                          * Finished message could have been computed.) */
2418                         s->s3->next_proto_neg_seen = 1;
2419                         }
2420 #endif
2421
2422                 else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation &&
2423                          s->ctx->alpn_select_cb &&
2424                          s->s3->tmp.finish_md_len == 0)
2425                         {
2426                         if (tls1_alpn_handle_client_hello(s, data, size, al) != 0)
2427                                 return 0;
2428 #ifndef OPENSSL_NO_NEXTPROTONEG
2429                         /* ALPN takes precedence over NPN. */
2430                         s->s3->next_proto_neg_seen = 0;
2431 #endif
2432                         }
2433
2434                 /* session ticket processed earlier */
2435                 else if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s)
2436                                 && type == TLSEXT_TYPE_use_srtp)
2437                         {
2438                         if(ssl_parse_clienthello_use_srtp_ext(s, data, size,
2439                                                               al))
2440                                 return 0;
2441                         }
2442
2443                 data+=size;
2444                 }
2445
2446         *p = data;
2447
2448         ri_check:
2449
2450         /* Need RI if renegotiating */
2451
2452         if (!renegotiate_seen && s->renegotiate &&
2453                 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
2454                 {
2455                 *al = SSL_AD_HANDSHAKE_FAILURE;
2456                 SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
2457                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2458                 return 0;
2459                 }
2460
2461         return 1;
2462         }
2463
2464 /*
2465  * Parse any custom extensions found.  "data" is the start of the extension data
2466  * and "limit" is the end of the record. TODO: add strict syntax checking.
2467  */
2468
2469 static int ssl_scan_clienthello_custom_tlsext(SSL *s, const unsigned char *data, const unsigned char *limit, int *al) 
2470         {       
2471         unsigned short type, size, len;
2472         /* If resumed session or no custom extensions nothing to do */
2473         if (s->hit || s->cert->srv_ext.meths_count == 0)
2474                 return 1;
2475
2476         if (data >= limit - 2)
2477                 return 1;
2478         n2s(data, len);
2479
2480         if (data > limit - len) 
2481                 return 1;
2482
2483         while (data <= limit - 4)
2484                 {
2485                 n2s(data, type);
2486                 n2s(data, size);
2487
2488                 if (data+size > limit)
2489                         return 1;
2490                 if (custom_ext_parse(s, 1 /* server */, type, data, size, al) <= 0)
2491                         return 0;
2492
2493                 data+=size;
2494                 }
2495
2496         return 1;
2497         }
2498
2499 int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n) 
2500         {
2501         int al = -1;
2502         unsigned char *ptmp = *p;
2503         /*
2504          * Internally supported extensions are parsed first so SNI can be handled
2505          * before custom extensions. An application processing SNI will typically
2506          * switch the parent context using SSL_set_SSL_CTX and custom extensions
2507          * need to be handled by the new SSL_CTX structure.
2508          */
2509         if (ssl_scan_clienthello_tlsext(s, p, d, n, &al) <= 0) 
2510                 {
2511                 ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2512                 return 0;
2513                 }
2514
2515         if (ssl_check_clienthello_tlsext_early(s) <= 0) 
2516                 {
2517                 SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT,SSL_R_CLIENTHELLO_TLSEXT);
2518                 return 0;
2519                 }
2520
2521         custom_ext_init(&s->cert->srv_ext);
2522         if (ssl_scan_clienthello_custom_tlsext(s, ptmp, d + n, &al) <= 0) 
2523                 {
2524                 ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2525                 return 0;
2526                 }
2527
2528         return 1;
2529 }
2530
2531 #ifndef OPENSSL_NO_NEXTPROTONEG
2532 /* ssl_next_proto_validate validates a Next Protocol Negotiation block. No
2533  * elements of zero length are allowed and the set of elements must exactly fill
2534  * the length of the block. */
2535 static char ssl_next_proto_validate(unsigned char *d, unsigned len)
2536         {
2537         unsigned int off = 0;
2538
2539         while (off < len)
2540                 {
2541                 if (d[off] == 0)
2542                         return 0;
2543                 off += d[off];
2544                 off++;
2545                 }
2546
2547         return off == len;
2548         }
2549 #endif
2550
2551 static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
2552         {
2553         unsigned short length;
2554         unsigned short type;
2555         unsigned short size;
2556         unsigned char *data = *p;
2557         int tlsext_servername = 0;
2558         int renegotiate_seen = 0;
2559
2560 #ifndef OPENSSL_NO_NEXTPROTONEG
2561         s->s3->next_proto_neg_seen = 0;
2562 #endif
2563
2564         if (s->s3->alpn_selected)
2565                 {
2566                 OPENSSL_free(s->s3->alpn_selected);
2567                 s->s3->alpn_selected = NULL;
2568                 }
2569
2570 #ifndef OPENSSL_NO_HEARTBEATS
2571         s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
2572                                SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
2573 #endif
2574
2575         if (data >= (d+n-2))
2576                 goto ri_check;
2577
2578         n2s(data,length);
2579         if (data+length != d+n)
2580                 {
2581                 *al = SSL_AD_DECODE_ERROR;
2582                 return 0;
2583                 }
2584
2585         while(data <= (d+n-4))
2586                 {
2587                 n2s(data,type);
2588                 n2s(data,size);
2589
2590                 if (data+size > (d+n))
2591                         goto ri_check;
2592
2593                 if (s->tlsext_debug_cb)
2594                         s->tlsext_debug_cb(s, 1, type, data, size,
2595                                                 s->tlsext_debug_arg);
2596
2597                 if (type == TLSEXT_TYPE_server_name)
2598                         {
2599                         if (s->tlsext_hostname == NULL || size > 0)
2600                                 {
2601                                 *al = TLS1_AD_UNRECOGNIZED_NAME;
2602                                 return 0;
2603                                 }
2604                         tlsext_servername = 1;   
2605                         }
2606
2607 #ifndef OPENSSL_NO_EC
2608                 else if (type == TLSEXT_TYPE_ec_point_formats)
2609                         {
2610                         unsigned char *sdata = data;
2611                         int ecpointformatlist_length = *(sdata++);
2612
2613                         if (ecpointformatlist_length != size - 1)
2614                                 {
2615                                 *al = TLS1_AD_DECODE_ERROR;
2616                                 return 0;
2617                                 }
2618                         if (!s->hit)
2619                                 {
2620                                 s->session->tlsext_ecpointformatlist_length = 0;
2621                                 if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist);
2622                                 if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
2623                                         {
2624                                         *al = TLS1_AD_INTERNAL_ERROR;
2625                                         return 0;
2626                                         }
2627                                 s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
2628                                 memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
2629                                 }
2630 #if 0
2631                         fprintf(stderr,"ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist ");
2632                         sdata = s->session->tlsext_ecpointformatlist;
2633                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2634                                 fprintf(stderr,"%i ",*(sdata++));
2635                         fprintf(stderr,"\n");
2636 #endif
2637                         }
2638 #endif /* OPENSSL_NO_EC */
2639
2640                 else if (type == TLSEXT_TYPE_session_ticket)
2641                         {
2642                         if (s->tls_session_ticket_ext_cb &&
2643                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
2644                                 {
2645                                 *al = TLS1_AD_INTERNAL_ERROR;
2646                                 return 0;
2647                                 }
2648                         if ((SSL_get_options(s) & SSL_OP_NO_TICKET)
2649                                 || (size > 0))
2650                                 {
2651                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2652                                 return 0;
2653                                 }
2654                         s->tlsext_ticket_expected = 1;
2655                         }
2656 #ifdef TLSEXT_TYPE_opaque_prf_input
2657                 else if (type == TLSEXT_TYPE_opaque_prf_input)
2658                         {
2659                         unsigned char *sdata = data;
2660
2661                         if (size < 2)
2662                                 {
2663                                 *al = SSL_AD_DECODE_ERROR;
2664                                 return 0;
2665                                 }
2666                         n2s(sdata, s->s3->server_opaque_prf_input_len);
2667                         if (s->s3->server_opaque_prf_input_len != size - 2)
2668                                 {
2669                                 *al = SSL_AD_DECODE_ERROR;
2670                                 return 0;
2671                                 }
2672                         
2673                         if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
2674                                 OPENSSL_free(s->s3->server_opaque_prf_input);
2675                         if (s->s3->server_opaque_prf_input_len == 0)
2676                                 s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2677                         else
2678                                 s->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len);
2679
2680                         if (s->s3->server_opaque_prf_input == NULL)
2681                                 {
2682                                 *al = TLS1_AD_INTERNAL_ERROR;
2683                                 return 0;
2684                                 }
2685                         }
2686 #endif
2687                 else if (type == TLSEXT_TYPE_status_request)
2688                         {
2689                         /* MUST be empty and only sent if we've requested
2690                          * a status request message.
2691                          */ 
2692                         if ((s->tlsext_status_type == -1) || (size > 0))
2693                                 {
2694                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2695                                 return 0;
2696                                 }
2697                         /* Set flag to expect CertificateStatus message */
2698                         s->tlsext_status_expected = 1;
2699                         }
2700 #ifndef OPENSSL_NO_NEXTPROTONEG
2701                 else if (type == TLSEXT_TYPE_next_proto_neg &&
2702                          s->s3->tmp.finish_md_len == 0)
2703                         {
2704                         unsigned char *selected;
2705                         unsigned char selected_len;
2706
2707                         /* We must have requested it. */
2708                         if (s->ctx->next_proto_select_cb == NULL)
2709                                 {
2710                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2711                                 return 0;
2712                                 }
2713                         /* The data must be valid */
2714                         if (!ssl_next_proto_validate(data, size))
2715                                 {
2716                                 *al = TLS1_AD_DECODE_ERROR;
2717                                 return 0;
2718                                 }
2719                         if (s->ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK)
2720                                 {
2721                                 *al = TLS1_AD_INTERNAL_ERROR;
2722                                 return 0;
2723                                 }
2724                         s->next_proto_negotiated = OPENSSL_malloc(selected_len);
2725                         if (!s->next_proto_negotiated)
2726                                 {
2727                                 *al = TLS1_AD_INTERNAL_ERROR;
2728                                 return 0;
2729                                 }
2730                         memcpy(s->next_proto_negotiated, selected, selected_len);
2731                         s->next_proto_negotiated_len = selected_len;
2732                         s->s3->next_proto_neg_seen = 1;
2733                         }
2734 #endif
2735
2736                 else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation)
2737                         {
2738                         unsigned len;
2739
2740                         /* We must have requested it. */
2741                         if (s->alpn_client_proto_list == NULL)
2742                                 {
2743                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2744                                 return 0;
2745                                 }
2746                         if (size < 4)
2747                                 {
2748                                 *al = TLS1_AD_DECODE_ERROR;
2749                                 return 0;
2750                                 }
2751                         /* The extension data consists of:
2752                          *   uint16 list_length
2753                          *   uint8 proto_length;
2754                          *   uint8 proto[proto_length]; */
2755                         len = data[0];
2756                         len <<= 8;
2757                         len |= data[1];
2758                         if (len != (unsigned) size - 2)
2759                                 {
2760                                 *al = TLS1_AD_DECODE_ERROR;
2761                                 return 0;
2762                                 }
2763                         len = data[2];
2764                         if (len != (unsigned) size - 3)
2765                                 {
2766                                 *al = TLS1_AD_DECODE_ERROR;
2767                                 return 0;
2768                                 }
2769                         if (s->s3->alpn_selected)
2770                                 OPENSSL_free(s->s3->alpn_selected);
2771                         s->s3->alpn_selected = OPENSSL_malloc(len);
2772                         if (!s->s3->alpn_selected)
2773                                 {
2774                                 *al = TLS1_AD_INTERNAL_ERROR;
2775                                 return 0;
2776                                 }
2777                         memcpy(s->s3->alpn_selected, data + 3, len);
2778                         s->s3->alpn_selected_len = len;
2779                         }
2780
2781                 else if (type == TLSEXT_TYPE_renegotiate)
2782                         {
2783                         if(!ssl_parse_serverhello_renegotiate_ext(s, data, size, al))
2784                                 return 0;
2785                         renegotiate_seen = 1;
2786                         }
2787 #ifndef OPENSSL_NO_HEARTBEATS
2788                 else if (type == TLSEXT_TYPE_heartbeat)
2789                         {
2790                         switch(data[0])
2791                                 {
2792                                 case 0x01:      /* Server allows us to send HB requests */
2793                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2794                                                         break;
2795                                 case 0x02:      /* Server doesn't accept HB requests */
2796                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2797                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2798                                                         break;
2799                                 default:        *al = SSL_AD_ILLEGAL_PARAMETER;
2800                                                         return 0;
2801                                 }
2802                         }
2803 #endif
2804                 else if (SSL_IS_DTLS(s) && type == TLSEXT_TYPE_use_srtp)
2805                         {
2806                         if(ssl_parse_serverhello_use_srtp_ext(s, data, size,
2807                                                               al))
2808                                 return 0;
2809                         }
2810                 /* If this extension type was not otherwise handled, but 
2811                  * matches a custom_cli_ext_record, then send it to the c
2812                  * callback */
2813                 else if (custom_ext_parse(s, 0, type, data, size, al) <= 0)
2814                                 return 0;
2815  
2816                 data += size;
2817                 }
2818
2819         if (data != d+n)
2820                 {
2821                 *al = SSL_AD_DECODE_ERROR;
2822                 return 0;
2823                 }
2824
2825         if (!s->hit && tlsext_servername == 1)
2826                 {
2827                 if (s->tlsext_hostname)
2828                         {
2829                         if (s->session->tlsext_hostname == NULL)
2830                                 {
2831                                 s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);   
2832                                 if (!s->session->tlsext_hostname)
2833                                         {
2834                                         *al = SSL_AD_UNRECOGNIZED_NAME;
2835                                         return 0;
2836                                         }
2837                                 }
2838                         else 
2839                                 {
2840                                 *al = SSL_AD_DECODE_ERROR;
2841                                 return 0;
2842                                 }
2843                         }
2844                 }
2845
2846         *p = data;
2847
2848         ri_check:
2849
2850         /* Determine if we need to see RI. Strictly speaking if we want to
2851          * avoid an attack we should *always* see RI even on initial server
2852          * hello because the client doesn't see any renegotiation during an
2853          * attack. However this would mean we could not connect to any server
2854          * which doesn't support RI so for the immediate future tolerate RI
2855          * absence on initial connect only.
2856          */
2857         if (!renegotiate_seen
2858                 && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
2859                 && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
2860                 {
2861                 *al = SSL_AD_HANDSHAKE_FAILURE;
2862                 SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT,
2863                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2864                 return 0;
2865                 }
2866
2867         return 1;
2868         }
2869
2870
2871 int ssl_prepare_clienthello_tlsext(SSL *s)
2872         {
2873
2874 #ifdef TLSEXT_TYPE_opaque_prf_input
2875         {
2876                 int r = 1;
2877         
2878                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
2879                         {
2880                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
2881                         if (!r)
2882                                 return -1;
2883                         }
2884
2885                 if (s->tlsext_opaque_prf_input != NULL)
2886                         {
2887                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
2888                                 OPENSSL_free(s->s3->client_opaque_prf_input);
2889
2890                         if (s->tlsext_opaque_prf_input_len == 0)
2891                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2892                         else
2893                                 s->s3->client_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
2894                         if (s->s3->client_opaque_prf_input == NULL)
2895                                 {
2896                                 SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
2897                                 return -1;
2898                                 }
2899                         s->s3->client_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2900                         }
2901
2902                 if (r == 2)
2903                         /* at callback's request, insist on receiving an appropriate server opaque PRF input */
2904                         s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2905         }
2906 #endif
2907
2908         return 1;
2909         }
2910
2911 int ssl_prepare_serverhello_tlsext(SSL *s)
2912         {
2913         return 1;
2914         }
2915
2916 static int ssl_check_clienthello_tlsext_early(SSL *s)
2917         {
2918         int ret=SSL_TLSEXT_ERR_NOACK;
2919         int al = SSL_AD_UNRECOGNIZED_NAME;
2920
2921 #ifndef OPENSSL_NO_EC
2922         /* The handling of the ECPointFormats extension is done elsewhere, namely in 
2923          * ssl3_choose_cipher in s3_lib.c.
2924          */
2925         /* The handling of the EllipticCurves extension is done elsewhere, namely in 
2926          * ssl3_choose_cipher in s3_lib.c.
2927          */
2928 #endif
2929
2930         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
2931                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
2932         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
2933                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
2934
2935 #ifdef TLSEXT_TYPE_opaque_prf_input
2936         {
2937                 /* This sort of belongs into ssl_prepare_serverhello_tlsext(),
2938                  * but we might be sending an alert in response to the client hello,
2939                  * so this has to happen here in
2940                  * ssl_check_clienthello_tlsext_early(). */
2941
2942                 int r = 1;
2943         
2944                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
2945                         {
2946                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
2947                         if (!r)
2948                                 {
2949                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2950                                 al = SSL_AD_INTERNAL_ERROR;
2951                                 goto err;
2952                                 }
2953                         }
2954
2955                 if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
2956                         OPENSSL_free(s->s3->server_opaque_prf_input);
2957                 s->s3->server_opaque_prf_input = NULL;
2958
2959                 if (s->tlsext_opaque_prf_input != NULL)
2960                         {
2961                         if (s->s3->client_opaque_prf_input != NULL &&
2962                                 s->s3->client_opaque_prf_input_len == s->tlsext_opaque_prf_input_len)
2963                                 {
2964                                 /* can only use this extension if we have a server opaque PRF input
2965                                  * of the same length as the client opaque PRF input! */
2966
2967                                 if (s->tlsext_opaque_prf_input_len == 0)
2968                                         s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2969                                 else
2970                                         s->s3->server_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
2971                                 if (s->s3->server_opaque_prf_input == NULL)
2972                                         {
2973                                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2974                                         al = SSL_AD_INTERNAL_ERROR;
2975                                         goto err;
2976                                         }
2977                                 s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2978                                 }
2979                         }
2980
2981                 if (r == 2 && s->s3->server_opaque_prf_input == NULL)
2982                         {
2983                         /* The callback wants to enforce use of the extension,
2984                          * but we can't do that with the client opaque PRF input;
2985                          * abort the handshake.
2986                          */
2987                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2988                         al = SSL_AD_HANDSHAKE_FAILURE;
2989                         }
2990         }
2991
2992  err:
2993 #endif
2994         switch (ret)
2995                 {
2996                 case SSL_TLSEXT_ERR_ALERT_FATAL:
2997                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2998                         return -1;
2999
3000                 case SSL_TLSEXT_ERR_ALERT_WARNING:
3001                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
3002                         return 1; 
3003                                         
3004                 case SSL_TLSEXT_ERR_NOACK:
3005                         s->servername_done=0;
3006                         default:
3007                 return 1;
3008                 }
3009         }
3010
3011 int tls1_set_server_sigalgs(SSL *s)
3012         {
3013         int al;
3014         size_t i;
3015         /* Clear any shared sigtnature algorithms */
3016         if (s->cert->shared_sigalgs)
3017                 {
3018                 OPENSSL_free(s->cert->shared_sigalgs);
3019                 s->cert->shared_sigalgs = NULL;
3020                 }
3021         /* Clear certificate digests and validity flags */
3022         for (i = 0; i < SSL_PKEY_NUM; i++)
3023                 {
3024                 s->cert->pkeys[i].digest = NULL;
3025                 s->cert->pkeys[i].valid_flags = 0;
3026                 }
3027
3028         /* If sigalgs received process it. */
3029         if (s->cert->peer_sigalgs)
3030                 {
3031                 if (!tls1_process_sigalgs(s))
3032                         {
3033                         SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS,
3034                                         ERR_R_MALLOC_FAILURE);
3035                         al = SSL_AD_INTERNAL_ERROR;
3036                         goto err;
3037                         }
3038                 /* Fatal error is no shared signature algorithms */
3039                 if (!s->cert->shared_sigalgs)
3040                         {
3041                         SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS,
3042                                         SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
3043                         al = SSL_AD_ILLEGAL_PARAMETER;
3044                         goto err;
3045                         }
3046                 }
3047         else
3048                 ssl_cert_set_default_md(s->cert);
3049         return 1;
3050         err:
3051         ssl3_send_alert(s, SSL3_AL_FATAL, al);
3052         return 0;
3053         }
3054
3055 int ssl_check_clienthello_tlsext_late(SSL *s)
3056         {
3057         int ret = SSL_TLSEXT_ERR_OK;
3058         int al;
3059
3060         /* If status request then ask callback what to do.
3061          * Note: this must be called after servername callbacks in case
3062          * the certificate has changed, and must be called after the cipher
3063          * has been chosen because this may influence which certificate is sent
3064          */
3065         if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb)
3066                 {
3067                 int r;
3068                 CERT_PKEY *certpkey;
3069                 certpkey = ssl_get_server_send_pkey(s);
3070                 /* If no certificate can't return certificate status */
3071                 if (certpkey == NULL)
3072                         {
3073                         s->tlsext_status_expected = 0;
3074                         return 1;
3075                         }
3076                 /* Set current certificate to one we will use so
3077                  * SSL_get_certificate et al can pick it up.
3078                  */
3079                 s->cert->key = certpkey;
3080                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
3081                 switch (r)
3082                         {
3083                         /* We don't want to send a status request response */
3084                         case SSL_TLSEXT_ERR_NOACK:
3085                                 s->tlsext_status_expected = 0;
3086                                 break;
3087                         /* status request response should be sent */
3088                         case SSL_TLSEXT_ERR_OK:
3089                                 if (s->tlsext_ocsp_resp)
3090                                         s->tlsext_status_expected = 1;
3091                                 else
3092                                         s->tlsext_status_expected = 0;
3093                                 break;
3094                         /* something bad happened */
3095                         case SSL_TLSEXT_ERR_ALERT_FATAL:
3096                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3097                                 al = SSL_AD_INTERNAL_ERROR;
3098                                 goto err;
3099                         }