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