f0291b115f4a8dcc9042b8e77a5334a4a83e29c7
[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 /*
508  * Return |nmatch|th shared curve or NID_undef if there is no match.
509  * For nmatch == -1, return number of  matches
510  * For nmatch == -2, return the NID of the curve to use for
511  * an EC tmp key, or NID_undef if there is no match.
512  */
513 int tls1_shared_curve(SSL *s, int nmatch)
514         {
515         const unsigned char *pref, *supp;
516         size_t num_pref, num_supp, i, j;
517         int k;
518         /* Can't do anything on client side */
519         if (s->server == 0)
520                 return -1;
521         if (nmatch == -2)
522                 {
523                 if (tls1_suiteb(s))
524                         {
525                         /* For Suite B ciphersuite determines curve: we 
526                          * already know these are acceptable due to previous
527                          * checks.
528                          */
529                         unsigned long cid = s->s3->tmp.new_cipher->id;
530                         if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
531                                 return NID_X9_62_prime256v1; /* P-256 */
532                         if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
533                                 return NID_secp384r1; /* P-384 */
534                         /* Should never happen */
535                         return NID_undef;
536                         }
537                 /* If not Suite B just return first preference shared curve */
538                 nmatch = 0;
539                 }
540         /*
541          * Avoid truncation. tls1_get_curvelist takes an int
542          * but s->options is a long...
543          */
544         if (!tls1_get_curvelist(s, (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) != 0,
545                         &supp, &num_supp))
546                 /* In practice, NID_undef == 0 but let's be precise. */
547                 return nmatch == -1 ? 0 : NID_undef;
548         if(!tls1_get_curvelist(s, !(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE),
549                         &pref, &num_pref))
550                 return nmatch == -1 ? 0 : NID_undef;
551         k = 0;
552         for (i = 0; i < num_pref; i++, pref+=2)
553                 {
554                 const unsigned char *tsupp = supp;
555                 for (j = 0; j < num_supp; j++, tsupp+=2)
556                         {
557                         if (pref[0] == tsupp[0] && pref[1] == tsupp[1])
558                                 {
559                                 if (!tls_curve_allowed(s, pref, SSL_SECOP_CURVE_SHARED))
560                                         continue;
561                                 if (nmatch == k)
562                                         {
563                                         int id = (pref[0] << 8) | pref[1];
564                                         return tls1_ec_curve_id2nid(id);
565                                         }
566                                 k++;
567                                 }
568                         }
569                 }
570         if (nmatch == -1)
571                 return k;
572         /* Out of range (nmatch > k). */
573         return NID_undef;
574         }
575
576 int tls1_set_curves(unsigned char **pext, size_t *pextlen,
577                         int *curves, size_t ncurves)
578         {
579         unsigned char *clist, *p;
580         size_t i;
581         /* Bitmap of curves included to detect duplicates: only works
582          * while curve ids < 32 
583          */
584         unsigned long dup_list = 0;
585         clist = OPENSSL_malloc(ncurves * 2);
586         if (!clist)
587                 return 0;
588         for (i = 0, p = clist; i < ncurves; i++)
589                 {
590                 unsigned long idmask;
591                 int id;
592                 id = tls1_ec_nid2curve_id(curves[i]);
593                 idmask = 1L << id;
594                 if (!id || (dup_list & idmask))
595                         {
596                         OPENSSL_free(clist);
597                         return 0;
598                         }
599                 dup_list |= idmask;
600                 s2n(id, p);
601                 }
602         if (*pext)
603                 OPENSSL_free(*pext);
604         *pext = clist;
605         *pextlen = ncurves * 2;
606         return 1;
607         }
608
609 #define MAX_CURVELIST   28
610
611 typedef struct
612         {
613         size_t nidcnt;
614         int nid_arr[MAX_CURVELIST];
615         } nid_cb_st;
616
617 static int nid_cb(const char *elem, int len, void *arg)
618         {
619         nid_cb_st *narg = arg;
620         size_t i;
621         int nid;
622         char etmp[20];
623         if (narg->nidcnt == MAX_CURVELIST)
624                 return 0;
625         if (len > (int)(sizeof(etmp) - 1))
626                 return 0;
627         memcpy(etmp, elem, len);
628         etmp[len] = 0;
629         nid = EC_curve_nist2nid(etmp);
630         if (nid == NID_undef)
631                 nid = OBJ_sn2nid(etmp);
632         if (nid == NID_undef)
633                 nid = OBJ_ln2nid(etmp);
634         if (nid == NID_undef)
635                 return 0;
636         for (i = 0; i < narg->nidcnt; i++)
637                 if (narg->nid_arr[i] == nid)
638                         return 0;
639         narg->nid_arr[narg->nidcnt++] = nid;
640         return 1;
641         }
642 /* Set curves based on a colon separate list */
643 int tls1_set_curves_list(unsigned char **pext, size_t *pextlen, 
644                                 const char *str)
645         {
646         nid_cb_st ncb;
647         ncb.nidcnt = 0;
648         if (!CONF_parse_list(str, ':', 1, nid_cb, &ncb))
649                 return 0;
650         if (pext == NULL)
651                 return 1;
652         return tls1_set_curves(pext, pextlen, ncb.nid_arr, ncb.nidcnt);
653         }
654 /* For an EC key set TLS id and required compression based on parameters */
655 static int tls1_set_ec_id(unsigned char *curve_id, unsigned char *comp_id,
656                                 EC_KEY *ec)
657         {
658         int is_prime, id;
659         const EC_GROUP *grp;
660         const EC_METHOD *meth;
661         if (!ec)
662                 return 0;
663         /* Determine if it is a prime field */
664         grp = EC_KEY_get0_group(ec);
665         if (!grp)
666                 return 0;
667         meth = EC_GROUP_method_of(grp);
668         if (!meth)
669                 return 0;
670         if (EC_METHOD_get_field_type(meth) == NID_X9_62_prime_field)
671                 is_prime = 1;
672         else
673                 is_prime = 0;
674         /* Determine curve ID */
675         id = EC_GROUP_get_curve_name(grp);
676         id = tls1_ec_nid2curve_id(id);
677         /* If we have an ID set it, otherwise set arbitrary explicit curve */
678         if (id)
679                 {
680                 curve_id[0] = 0;
681                 curve_id[1] = (unsigned char)id;
682                 }
683         else
684                 {
685                 curve_id[0] = 0xff;
686                 if (is_prime)
687                         curve_id[1] = 0x01;
688                 else
689                         curve_id[1] = 0x02;
690                 }
691         if (comp_id)
692                 {
693                 if (EC_KEY_get0_public_key(ec) == NULL)
694                         return 0;
695                 if (EC_KEY_get_conv_form(ec) == POINT_CONVERSION_COMPRESSED)
696                         {
697                         if (is_prime)
698                                 *comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
699                         else
700                                 *comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
701                         }
702                 else
703                         *comp_id = TLSEXT_ECPOINTFORMAT_uncompressed;
704                 }
705         return 1;
706         }
707 /* Check an EC key is compatible with extensions */
708 static int tls1_check_ec_key(SSL *s,
709                         unsigned char *curve_id, unsigned char *comp_id)
710         {
711         const unsigned char *pformats, *pcurves;
712         size_t num_formats, num_curves, i;
713         int j;
714         /* If point formats extension present check it, otherwise everything
715          * is supported (see RFC4492).
716          */
717         if (comp_id && s->session->tlsext_ecpointformatlist)
718                 {
719                 pformats = s->session->tlsext_ecpointformatlist;
720                 num_formats = s->session->tlsext_ecpointformatlist_length;
721                 for (i = 0; i < num_formats; i++, pformats++)
722                         {
723                         if (*comp_id == *pformats)
724                                 break;
725                         }
726                 if (i == num_formats)
727                         return 0;
728                 }
729         if (!curve_id)
730                 return 1;
731         /* Check curve is consistent with client and server preferences */
732         for (j = 0; j <= 1; j++)
733                 {
734                 if (!tls1_get_curvelist(s, j, &pcurves, &num_curves))
735                         return 0;
736                 for (i = 0; i < num_curves; i++, pcurves += 2)
737                         {
738                         if (pcurves[0] == curve_id[0] &&
739                             pcurves[1] == curve_id[1])
740                                 break;
741                         }
742                 if (i == num_curves)
743                         return 0;
744                 /* For clients can only check sent curve list */
745                 if (!s->server)
746                         break;
747                 }
748         return 1;
749         }
750
751 static void tls1_get_formatlist(SSL *s, const unsigned char **pformats,
752                                         size_t *num_formats)
753         {
754         /* If we have a custom point format list use it otherwise
755          * use default */
756         if (s->tlsext_ecpointformatlist)
757                 {
758                 *pformats = s->tlsext_ecpointformatlist;
759                 *num_formats = s->tlsext_ecpointformatlist_length;
760                 }
761         else
762                 {
763                 *pformats = ecformats_default;
764                 /* For Suite B we don't support char2 fields */
765                 if (tls1_suiteb(s))
766                         *num_formats = sizeof(ecformats_default) - 1;
767                 else
768                         *num_formats = sizeof(ecformats_default);
769                 }
770         }
771
772 /* Check cert parameters compatible with extensions: currently just checks
773  * EC certificates have compatible curves and compression.
774  */
775 static int tls1_check_cert_param(SSL *s, X509 *x, int set_ee_md)
776         {
777         unsigned char comp_id, curve_id[2];
778         EVP_PKEY *pkey;
779         int rv;
780         pkey = X509_get_pubkey(x);
781         if (!pkey)
782                 return 0;
783         /* If not EC nothing to do */
784         if (pkey->type != EVP_PKEY_EC)
785                 {
786                 EVP_PKEY_free(pkey);
787                 return 1;
788                 }
789         rv = tls1_set_ec_id(curve_id, &comp_id, pkey->pkey.ec);
790         EVP_PKEY_free(pkey);
791         if (!rv)
792                 return 0;
793         /* Can't check curve_id for client certs as we don't have a
794          * supported curves extension.
795          */
796         rv = tls1_check_ec_key(s, s->server ? curve_id : NULL, &comp_id);
797         if (!rv)
798                 return 0;
799         /* Special case for suite B. We *MUST* sign using SHA256+P-256 or
800          * SHA384+P-384, adjust digest if necessary.
801          */
802         if (set_ee_md && tls1_suiteb(s))
803                 {
804                 int check_md;
805                 size_t i;
806                 CERT *c = s->cert;
807                 if (curve_id[0])
808                         return 0;
809                 /* Check to see we have necessary signing algorithm */
810                 if (curve_id[1] == TLSEXT_curve_P_256)
811                         check_md = NID_ecdsa_with_SHA256;
812                 else if (curve_id[1] == TLSEXT_curve_P_384)
813                         check_md = NID_ecdsa_with_SHA384;
814                 else
815                         return 0; /* Should never happen */
816                 for (i = 0; i < c->shared_sigalgslen; i++)
817                         if (check_md == c->shared_sigalgs[i].signandhash_nid)
818                                 break;
819                 if (i == c->shared_sigalgslen)
820                         return 0;
821                 if (set_ee_md == 2)
822                         {
823                         if (check_md == NID_ecdsa_with_SHA256)
824                                 c->pkeys[SSL_PKEY_ECC].digest = EVP_sha256();
825                         else
826                                 c->pkeys[SSL_PKEY_ECC].digest = EVP_sha384();
827                         }
828                 }
829         return rv;
830         }
831 #ifndef OPENSSL_NO_ECDH
832 /* Check EC temporary key is compatible with client extensions */
833 int tls1_check_ec_tmp_key(SSL *s, unsigned long cid)
834         {
835         unsigned char curve_id[2];
836         EC_KEY *ec = s->cert->ecdh_tmp;
837 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
838         /* Allow any curve: not just those peer supports */
839         if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
840                 return 1;
841 #endif
842         /* If Suite B, AES128 MUST use P-256 and AES256 MUST use P-384,
843          * no other curves permitted.
844          */
845         if (tls1_suiteb(s))
846                 {
847                 /* Curve to check determined by ciphersuite */
848                 if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
849                         curve_id[1] = TLSEXT_curve_P_256;
850                 else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
851                         curve_id[1] = TLSEXT_curve_P_384;
852                 else
853                         return 0;
854                 curve_id[0] = 0;
855                 /* Check this curve is acceptable */
856                 if (!tls1_check_ec_key(s, curve_id, NULL))
857                         return 0;
858                 /* If auto or setting curve from callback assume OK */
859                 if (s->cert->ecdh_tmp_auto || s->cert->ecdh_tmp_cb)
860                         return 1;
861                 /* Otherwise check curve is acceptable */
862                 else 
863                         {
864                         unsigned char curve_tmp[2];
865                         if (!ec)
866                                 return 0;
867                         if (!tls1_set_ec_id(curve_tmp, NULL, ec))
868                                 return 0;
869                         if (!curve_tmp[0] || curve_tmp[1] == curve_id[1])
870                                 return 1;
871                         return 0;
872                         }
873                         
874                 }
875         if (s->cert->ecdh_tmp_auto)
876                 {
877                 /* Need a shared curve */
878                 if (tls1_shared_curve(s, 0))
879                         return 1;
880                 else return 0;
881                 }
882         if (!ec)
883                 {
884                 if (s->cert->ecdh_tmp_cb)
885                         return 1;
886                 else
887                         return 0;
888                 }
889         if (!tls1_set_ec_id(curve_id, NULL, ec))
890                 return 0;
891 /* Set this to allow use of invalid curves for testing */
892 #if 0
893         return 1;
894 #else
895         return tls1_check_ec_key(s, curve_id, NULL);
896 #endif
897         }
898 #endif /* OPENSSL_NO_ECDH */
899
900 #else
901
902 static int tls1_check_cert_param(SSL *s, X509 *x, int set_ee_md)
903         {
904         return 1;
905         }
906
907 #endif /* OPENSSL_NO_EC */
908
909 #ifndef OPENSSL_NO_TLSEXT
910
911 /* List of supported signature algorithms and hashes. Should make this
912  * customisable at some point, for now include everything we support.
913  */
914
915 #ifdef OPENSSL_NO_RSA
916 #define tlsext_sigalg_rsa(md) /* */
917 #else
918 #define tlsext_sigalg_rsa(md) md, TLSEXT_signature_rsa,
919 #endif
920
921 #ifdef OPENSSL_NO_DSA
922 #define tlsext_sigalg_dsa(md) /* */
923 #else
924 #define tlsext_sigalg_dsa(md) md, TLSEXT_signature_dsa,
925 #endif
926
927 #ifdef OPENSSL_NO_ECDSA
928 #define tlsext_sigalg_ecdsa(md) /* */
929 #else
930 #define tlsext_sigalg_ecdsa(md) md, TLSEXT_signature_ecdsa,
931 #endif
932
933 #define tlsext_sigalg(md) \
934                 tlsext_sigalg_rsa(md) \
935                 tlsext_sigalg_dsa(md) \
936                 tlsext_sigalg_ecdsa(md)
937
938 static unsigned char tls12_sigalgs[] = {
939 #ifndef OPENSSL_NO_SHA512
940         tlsext_sigalg(TLSEXT_hash_sha512)
941         tlsext_sigalg(TLSEXT_hash_sha384)
942 #endif
943 #ifndef OPENSSL_NO_SHA256
944         tlsext_sigalg(TLSEXT_hash_sha256)
945         tlsext_sigalg(TLSEXT_hash_sha224)
946 #endif
947 #ifndef OPENSSL_NO_SHA
948         tlsext_sigalg(TLSEXT_hash_sha1)
949 #endif
950 };
951 #ifndef OPENSSL_NO_ECDSA
952 static unsigned char suiteb_sigalgs[] = {
953         tlsext_sigalg_ecdsa(TLSEXT_hash_sha256)
954         tlsext_sigalg_ecdsa(TLSEXT_hash_sha384)
955 };
956 #endif
957 size_t tls12_get_psigalgs(SSL *s, const unsigned char **psigs)
958         {
959         /* If Suite B mode use Suite B sigalgs only, ignore any other
960          * preferences.
961          */
962 #ifndef OPENSSL_NO_EC
963         switch (tls1_suiteb(s))
964                 {
965         case SSL_CERT_FLAG_SUITEB_128_LOS:
966                 *psigs = suiteb_sigalgs;
967                 return sizeof(suiteb_sigalgs);
968
969         case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
970                 *psigs = suiteb_sigalgs;
971                 return 2;
972
973         case SSL_CERT_FLAG_SUITEB_192_LOS:
974                 *psigs = suiteb_sigalgs + 2;
975                 return 2;
976                 }
977 #endif
978         /* If server use client authentication sigalgs if not NULL */
979         if (s->server && s->cert->client_sigalgs)
980                 {
981                 *psigs = s->cert->client_sigalgs;
982                 return s->cert->client_sigalgslen;
983                 }
984         else if (s->cert->conf_sigalgs)
985                 {
986                 *psigs = s->cert->conf_sigalgs;
987                 return s->cert->conf_sigalgslen;
988                 }
989         else
990                 {
991                 *psigs = tls12_sigalgs;
992                 return sizeof(tls12_sigalgs);
993                 }
994         }
995 /* Check signature algorithm is consistent with sent supported signature
996  * algorithms and if so return relevant digest.
997  */
998 int tls12_check_peer_sigalg(const EVP_MD **pmd, SSL *s,
999                                 const unsigned char *sig, EVP_PKEY *pkey)
1000         {
1001         const unsigned char *sent_sigs;
1002         size_t sent_sigslen, i;
1003         int sigalg = tls12_get_sigid(pkey);
1004         /* Should never happen */
1005         if (sigalg == -1)
1006                 return -1;
1007         /* Check key type is consistent with signature */
1008         if (sigalg != (int)sig[1])
1009                 {
1010                 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_WRONG_SIGNATURE_TYPE);
1011                 return 0;
1012                 }
1013 #ifndef OPENSSL_NO_EC
1014         if (pkey->type == EVP_PKEY_EC)
1015                 {
1016                 unsigned char curve_id[2], comp_id;
1017                 /* Check compression and curve matches extensions */
1018                 if (!tls1_set_ec_id(curve_id, &comp_id, pkey->pkey.ec))
1019                         return 0;
1020                 if (!s->server && !tls1_check_ec_key(s, curve_id, &comp_id))
1021                         {
1022                         SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_WRONG_CURVE);
1023                         return 0;
1024                         }
1025                 /* If Suite B only P-384+SHA384 or P-256+SHA-256 allowed */
1026                 if (tls1_suiteb(s))
1027                         {
1028                         if (curve_id[0])
1029                                 return 0;
1030                         if (curve_id[1] == TLSEXT_curve_P_256)
1031                                 {
1032                                 if (sig[0] != TLSEXT_hash_sha256)
1033                                         {
1034                                         SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,
1035                                                 SSL_R_ILLEGAL_SUITEB_DIGEST);
1036                                         return 0;
1037                                         }
1038                                 }
1039                         else if (curve_id[1] == TLSEXT_curve_P_384)
1040                                 {
1041                                 if (sig[0] != TLSEXT_hash_sha384)
1042                                         {
1043                                         SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,
1044                                                 SSL_R_ILLEGAL_SUITEB_DIGEST);
1045                                         return 0;
1046                                         }
1047                                 }
1048                         else
1049                                 return 0;
1050                         }
1051                 }
1052         else if (tls1_suiteb(s))
1053                 return 0;
1054 #endif
1055
1056         /* Check signature matches a type we sent */
1057         sent_sigslen = tls12_get_psigalgs(s, &sent_sigs);
1058         for (i = 0; i < sent_sigslen; i+=2, sent_sigs+=2)
1059                 {
1060                 if (sig[0] == sent_sigs[0] && sig[1] == sent_sigs[1])
1061                         break;
1062                 }
1063         /* Allow fallback to SHA1 if not strict mode */
1064         if (i == sent_sigslen && (sig[0] != TLSEXT_hash_sha1 || s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT))
1065                 {
1066                 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_WRONG_SIGNATURE_TYPE);
1067                 return 0;
1068                 }
1069         *pmd = tls12_get_hash(sig[0]);
1070         if (*pmd == NULL)
1071                 {
1072                 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_UNKNOWN_DIGEST);
1073                 return 0;
1074                 }
1075         /* Make sure security callback allows algorithm */
1076         if (!ssl_security(s, SSL_SECOP_SIGALG_CHECK,
1077                                 EVP_MD_size(*pmd) * 4, EVP_MD_type(*pmd),
1078                                                                 (void *)sig))
1079                 {
1080                 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_WRONG_SIGNATURE_TYPE);
1081                 return 0;
1082                 }
1083         /* Store the digest used so applications can retrieve it if they
1084          * wish.
1085          */
1086         if (s->session && s->session->sess_cert)
1087                 s->session->sess_cert->peer_key->digest = *pmd;
1088         return 1;
1089         }
1090
1091 /* Get a mask of disabled algorithms: an algorithm is disabled
1092  * if it isn't supported or doesn't appear in supported signature
1093  * algorithms. Unlike ssl_cipher_get_disabled this applies to a specific
1094  * session and not global settings.
1095  * 
1096  */
1097 void ssl_set_client_disabled(SSL *s)
1098         {
1099         CERT *c = s->cert;
1100         c->mask_a = 0;
1101         c->mask_k = 0;
1102         /* Don't allow TLS 1.2 only ciphers if we don't suppport them */
1103         if (!SSL_CLIENT_USE_TLS1_2_CIPHERS(s))
1104                 c->mask_ssl = SSL_TLSV1_2;
1105         else
1106                 c->mask_ssl = 0;
1107         ssl_set_sig_mask(&c->mask_a, s, SSL_SECOP_SIGALG_MASK);
1108         /* Disable static DH if we don't include any appropriate
1109          * signature algorithms.
1110          */
1111         if (c->mask_a & SSL_aRSA)
1112                 c->mask_k |= SSL_kDHr|SSL_kECDHr;
1113         if (c->mask_a & SSL_aDSS)
1114                 c->mask_k |= SSL_kDHd;
1115         if (c->mask_a & SSL_aECDSA)
1116                 c->mask_k |= SSL_kECDHe;
1117 #ifndef OPENSSL_NO_KRB5
1118         if (!kssl_tgt_is_available(s->kssl_ctx))
1119                 {
1120                 c->mask_a |= SSL_aKRB5;
1121                 c->mask_k |= SSL_kKRB5;
1122                 }
1123 #endif
1124 #ifndef OPENSSL_NO_PSK
1125         /* with PSK there must be client callback set */
1126         if (!s->psk_client_callback)
1127                 {
1128                 c->mask_a |= SSL_aPSK;
1129                 c->mask_k |= SSL_kPSK;
1130                 }
1131 #endif /* OPENSSL_NO_PSK */
1132 #ifndef OPENSSL_NO_SRP
1133         if (!(s->srp_ctx.srp_Mask & SSL_kSRP))
1134                 {
1135                 c->mask_a |= SSL_aSRP;
1136                 c->mask_k |= SSL_kSRP;
1137                 }
1138 #endif
1139         c->valid = 1;
1140         }
1141
1142 int ssl_cipher_disabled(SSL *s, const SSL_CIPHER *c, int op)
1143         {
1144         CERT *ct = s->cert;
1145         if (c->algorithm_ssl & ct->mask_ssl || c->algorithm_mkey & ct->mask_k || c->algorithm_auth & ct->mask_a)
1146                 return 1;
1147         return !ssl_security(s, op, c->strength_bits, 0, (void *)c);
1148         }
1149
1150 static int tls_use_ticket(SSL *s)
1151         {
1152         if (s->options & SSL_OP_NO_TICKET)
1153                 return 0;
1154         return ssl_security(s, SSL_SECOP_TICKET, 0, 0, NULL);
1155         }
1156
1157 unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *buf, unsigned char *limit, int *al)
1158         {
1159         int extdatalen=0;
1160         unsigned char *orig = buf;
1161         unsigned char *ret = buf;
1162 #ifndef OPENSSL_NO_EC
1163         /* See if we support any ECC ciphersuites */
1164         int using_ecc = 0;
1165         if (s->version >= TLS1_VERSION || SSL_IS_DTLS(s))
1166                 {
1167                 int i;
1168                 unsigned long alg_k, alg_a;
1169                 STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(s);
1170
1171                 for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++)
1172                         {
1173                         SSL_CIPHER *c = sk_SSL_CIPHER_value(cipher_stack, i);
1174
1175                         alg_k = c->algorithm_mkey;
1176                         alg_a = c->algorithm_auth;
1177                         if ((alg_k & (SSL_kECDHE|SSL_kECDHr|SSL_kECDHe)
1178                                 || (alg_a & SSL_aECDSA)))
1179                                 {
1180                                 using_ecc = 1;
1181                                 break;
1182                                 }
1183                         }
1184                 }
1185 #endif
1186
1187         ret+=2;
1188
1189         if (ret>=limit) return NULL; /* this really never occurs, but ... */
1190
1191         /* Add RI if renegotiating */
1192         if (s->renegotiate)
1193           {
1194           int el;
1195
1196           if(!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0))
1197               {
1198               SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1199               return NULL;
1200               }
1201
1202           if((limit - ret - 4 - el) < 0) return NULL;
1203
1204           s2n(TLSEXT_TYPE_renegotiate,ret);
1205           s2n(el,ret);
1206
1207           if(!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el))
1208               {
1209               SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1210               return NULL;
1211               }
1212
1213           ret += el;
1214         }
1215         /* Only add RI for SSLv3 */
1216         if (s->client_version == SSL3_VERSION)
1217                 goto done;
1218
1219         if (s->tlsext_hostname != NULL)
1220                 { 
1221                 /* Add TLS extension servername to the Client Hello message */
1222                 unsigned long size_str;
1223                 long lenmax; 
1224
1225                 /* check for enough space.
1226                    4 for the servername type and entension length
1227                    2 for servernamelist length
1228                    1 for the hostname type
1229                    2 for hostname length
1230                    + hostname length 
1231                 */
1232                    
1233                 if ((lenmax = limit - ret - 9) < 0 
1234                     || (size_str = strlen(s->tlsext_hostname)) > (unsigned long)lenmax) 
1235                         return NULL;
1236                         
1237                 /* extension type and length */
1238                 s2n(TLSEXT_TYPE_server_name,ret); 
1239                 s2n(size_str+5,ret);
1240                 
1241                 /* length of servername list */
1242                 s2n(size_str+3,ret);
1243         
1244                 /* hostname type, length and hostname */
1245                 *(ret++) = (unsigned char) TLSEXT_NAMETYPE_host_name;
1246                 s2n(size_str,ret);
1247                 memcpy(ret, s->tlsext_hostname, size_str);
1248                 ret+=size_str;
1249                 }
1250
1251 #ifndef OPENSSL_NO_SRP
1252         /* Add SRP username if there is one */
1253         if (s->srp_ctx.login != NULL)
1254                 { /* Add TLS extension SRP username to the Client Hello message */
1255
1256                 int login_len = strlen(s->srp_ctx.login);       
1257                 if (login_len > 255 || login_len == 0)
1258                         {
1259                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1260                         return NULL;
1261                         } 
1262
1263                 /* check for enough space.
1264                    4 for the srp type type and entension length
1265                    1 for the srp user identity
1266                    + srp user identity length 
1267                 */
1268                 if ((limit - ret - 5 - login_len) < 0) return NULL; 
1269
1270                 /* fill in the extension */
1271                 s2n(TLSEXT_TYPE_srp,ret);
1272                 s2n(login_len+1,ret);
1273                 (*ret++) = (unsigned char) login_len;
1274                 memcpy(ret, s->srp_ctx.login, login_len);
1275                 ret+=login_len;
1276                 }
1277 #endif
1278
1279 #ifndef OPENSSL_NO_EC
1280         if (using_ecc)
1281                 {
1282                 /* Add TLS extension ECPointFormats to the ClientHello message */
1283                 long lenmax; 
1284                 const unsigned char *pcurves, *pformats;
1285                 size_t num_curves, num_formats, curves_list_len;
1286                 size_t i;
1287                 unsigned char *etmp;
1288
1289                 tls1_get_formatlist(s, &pformats, &num_formats);
1290
1291                 if ((lenmax = limit - ret - 5) < 0) return NULL; 
1292                 if (num_formats > (size_t)lenmax) return NULL;
1293                 if (num_formats > 255)
1294                         {
1295                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1296                         return NULL;
1297                         }
1298                 
1299                 s2n(TLSEXT_TYPE_ec_point_formats,ret);
1300                 /* The point format list has 1-byte length. */
1301                 s2n(num_formats + 1,ret);
1302                 *(ret++) = (unsigned char)num_formats ;
1303                 memcpy(ret, pformats, num_formats);
1304                 ret+=num_formats;
1305
1306                 /* Add TLS extension EllipticCurves to the ClientHello message */
1307                 pcurves = s->tlsext_ellipticcurvelist;
1308                 if (!tls1_get_curvelist(s, 0, &pcurves, &num_curves))
1309                         return NULL;
1310
1311                 if ((lenmax = limit - ret - 6) < 0) return NULL; 
1312                 if (num_curves > (size_t)lenmax / 2) return NULL;
1313                 if (num_curves > 65532 / 2)
1314                         {
1315                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1316                         return NULL;
1317                         }
1318
1319                 
1320                 s2n(TLSEXT_TYPE_elliptic_curves,ret);
1321                 etmp = ret + 4;
1322                 /* Copy curve ID if supported */
1323                 for (i = 0; i < num_curves; i++, pcurves += 2)
1324                         {
1325                         if (tls_curve_allowed(s, pcurves, SSL_SECOP_CURVE_SUPPORTED))
1326                                 {
1327                                 *etmp++ = pcurves[0];
1328                                 *etmp++ = pcurves[1];
1329                                 }
1330                         }
1331
1332                 curves_list_len = etmp - ret - 4;
1333
1334                 s2n(curves_list_len + 2, ret);
1335                 s2n(curves_list_len, ret);
1336                 ret += curves_list_len;
1337                 }
1338 #endif /* OPENSSL_NO_EC */
1339
1340         if (tls_use_ticket(s))
1341                 {
1342                 int ticklen;
1343                 if (!s->new_session && s->session && s->session->tlsext_tick)
1344                         ticklen = s->session->tlsext_ticklen;
1345                 else if (s->session && s->tlsext_session_ticket &&
1346                          s->tlsext_session_ticket->data)
1347                         {
1348                         ticklen = s->tlsext_session_ticket->length;
1349                         s->session->tlsext_tick = OPENSSL_malloc(ticklen);
1350                         if (!s->session->tlsext_tick)
1351                                 return NULL;
1352                         memcpy(s->session->tlsext_tick,
1353                                s->tlsext_session_ticket->data,
1354                                ticklen);
1355                         s->session->tlsext_ticklen = ticklen;
1356                         }
1357                 else
1358                         ticklen = 0;
1359                 if (ticklen == 0 && s->tlsext_session_ticket &&
1360                     s->tlsext_session_ticket->data == NULL)
1361                         goto skip_ext;
1362                 /* Check for enough room 2 for extension type, 2 for len
1363                  * rest for ticket
1364                  */
1365                 if ((long)(limit - ret - 4 - ticklen) < 0) return NULL;
1366                 s2n(TLSEXT_TYPE_session_ticket,ret); 
1367                 s2n(ticklen,ret);
1368                 if (ticklen)
1369                         {
1370                         memcpy(ret, s->session->tlsext_tick, ticklen);
1371                         ret += ticklen;
1372                         }
1373                 }
1374                 skip_ext:
1375
1376         if (SSL_USE_SIGALGS(s))
1377                 {
1378                 size_t salglen;
1379                 const unsigned char *salg;
1380                 unsigned char *etmp;
1381                 salglen = tls12_get_psigalgs(s, &salg);
1382                 if ((size_t)(limit - ret) < salglen + 6)
1383                         return NULL; 
1384                 s2n(TLSEXT_TYPE_signature_algorithms,ret);
1385                 etmp = ret;
1386                 /* Skip over lengths for now */
1387                 ret += 4;
1388                 salglen = tls12_copy_sigalgs(s, ret, salg, salglen);
1389                 /* Fill in lengths */
1390                 s2n(salglen + 2, etmp);
1391                 s2n(salglen, etmp);
1392                 ret += salglen;
1393                 }
1394
1395 #ifdef TLSEXT_TYPE_opaque_prf_input
1396         if (s->s3->client_opaque_prf_input != NULL)
1397                 {
1398                 size_t col = s->s3->client_opaque_prf_input_len;
1399                 
1400                 if ((long)(limit - ret - 6 - col) < 0)
1401                         return NULL;
1402                 if (col > 0xFFFD) /* can't happen */
1403                         return NULL;
1404
1405                 s2n(TLSEXT_TYPE_opaque_prf_input, ret); 
1406                 s2n(col + 2, ret);
1407                 s2n(col, ret);
1408                 memcpy(ret, s->s3->client_opaque_prf_input, col);
1409                 ret += col;
1410                 }
1411 #endif
1412
1413         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp)
1414                 {
1415                 int i;
1416                 long extlen, idlen, itmp;
1417                 OCSP_RESPID *id;
1418
1419                 idlen = 0;
1420                 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
1421                         {
1422                         id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
1423                         itmp = i2d_OCSP_RESPID(id, NULL);
1424                         if (itmp <= 0)
1425                                 return NULL;
1426                         idlen += itmp + 2;
1427                         }
1428
1429                 if (s->tlsext_ocsp_exts)
1430                         {
1431                         extlen = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL);
1432                         if (extlen < 0)
1433                                 return NULL;
1434                         }
1435                 else
1436                         extlen = 0;
1437                         
1438                 if ((long)(limit - ret - 7 - extlen - idlen) < 0) return NULL;
1439                 s2n(TLSEXT_TYPE_status_request, ret);
1440                 if (extlen + idlen > 0xFFF0)
1441                         return NULL;
1442                 s2n(extlen + idlen + 5, ret);
1443                 *(ret++) = TLSEXT_STATUSTYPE_ocsp;
1444                 s2n(idlen, ret);
1445                 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
1446                         {
1447                         /* save position of id len */
1448                         unsigned char *q = ret;
1449                         id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
1450                         /* skip over id len */
1451                         ret += 2;
1452                         itmp = i2d_OCSP_RESPID(id, &ret);
1453                         /* write id len */
1454                         s2n(itmp, q);
1455                         }
1456                 s2n(extlen, ret);
1457                 if (extlen > 0)
1458                         i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret);
1459                 }
1460
1461 #ifndef OPENSSL_NO_HEARTBEATS
1462         /* Add Heartbeat extension */
1463         if ((limit - ret - 4 - 1) < 0)
1464                 return NULL;
1465         s2n(TLSEXT_TYPE_heartbeat,ret);
1466         s2n(1,ret);
1467         /* Set mode:
1468          * 1: peer may send requests
1469          * 2: peer not allowed to send requests
1470          */
1471         if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1472                 *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1473         else
1474                 *(ret++) = SSL_TLSEXT_HB_ENABLED;
1475 #endif
1476
1477 #ifndef OPENSSL_NO_NEXTPROTONEG
1478         if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len)
1479                 {
1480                 /* The client advertises an emtpy extension to indicate its
1481                  * support for Next Protocol Negotiation */
1482                 if (limit - ret - 4 < 0)
1483                         return NULL;
1484                 s2n(TLSEXT_TYPE_next_proto_neg,ret);
1485                 s2n(0,ret);
1486                 }
1487 #endif
1488
1489         if (s->alpn_client_proto_list && !s->s3->tmp.finish_md_len)
1490                 {
1491                 if ((size_t)(limit - ret) < 6 + s->alpn_client_proto_list_len)
1492                         return NULL;
1493                 s2n(TLSEXT_TYPE_application_layer_protocol_negotiation,ret);
1494                 s2n(2 + s->alpn_client_proto_list_len,ret);
1495                 s2n(s->alpn_client_proto_list_len,ret);
1496                 memcpy(ret, s->alpn_client_proto_list,
1497                        s->alpn_client_proto_list_len);
1498                 ret += s->alpn_client_proto_list_len;
1499                 }
1500
1501         if(SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s))
1502                 {
1503                 int el;
1504
1505                 ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0);
1506                 
1507                 if((limit - ret - 4 - el) < 0) return NULL;
1508
1509                 s2n(TLSEXT_TYPE_use_srtp,ret);
1510                 s2n(el,ret);
1511
1512                 if(ssl_add_clienthello_use_srtp_ext(s, ret, &el, el))
1513                         {
1514                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1515                         return NULL;
1516                         }
1517                 ret += el;
1518                 }
1519         custom_ext_init(&s->cert->cli_ext);
1520         /* Add custom TLS Extensions to ClientHello */
1521         if (!custom_ext_add(s, 0, &ret, limit, al))
1522                 return NULL;
1523 #ifdef TLSEXT_TYPE_encrypt_then_mac
1524         s2n(TLSEXT_TYPE_encrypt_then_mac,ret);
1525         s2n(0,ret);
1526 #endif
1527
1528         /* Add padding to workaround bugs in F5 terminators.
1529          * See https://tools.ietf.org/html/draft-agl-tls-padding-03
1530          *
1531          * NB: because this code works out the length of all existing
1532          * extensions it MUST always appear last.
1533          */
1534         if (s->options & SSL_OP_TLSEXT_PADDING)
1535                 {
1536                 int hlen = ret - (unsigned char *)s->init_buf->data;
1537                 /* The code in s23_clnt.c to build ClientHello messages
1538                  * includes the 5-byte record header in the buffer, while
1539                  * the code in s3_clnt.c does not.
1540                  */
1541                 if (s->state == SSL23_ST_CW_CLNT_HELLO_A)
1542                         hlen -= 5;
1543                 if (hlen > 0xff && hlen < 0x200)
1544                         {
1545                         hlen = 0x200 - hlen;
1546                         if (hlen >= 4)
1547                                 hlen -= 4;
1548                         else
1549                                 hlen = 0;
1550
1551                         s2n(TLSEXT_TYPE_padding, ret);
1552                         s2n(hlen, ret);
1553                         memset(ret, 0, hlen);
1554                         ret += hlen;
1555                         }
1556                 }
1557
1558         done:
1559
1560         if ((extdatalen = ret-orig-2)== 0) 
1561                 return orig;
1562
1563         s2n(extdatalen, orig);
1564         return ret;
1565         }
1566
1567 unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *buf, unsigned char *limit, int *al)
1568         {
1569         int extdatalen=0;
1570         unsigned char *orig = buf;
1571         unsigned char *ret = buf;
1572 #ifndef OPENSSL_NO_NEXTPROTONEG
1573         int next_proto_neg_seen;
1574 #endif
1575 #ifndef OPENSSL_NO_EC
1576         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1577         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1578         int using_ecc = (alg_k & (SSL_kECDHE|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA);
1579         using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL);
1580 #endif
1581         
1582         ret+=2;
1583         if (ret>=limit) return NULL; /* this really never occurs, but ... */
1584
1585         if(s->s3->send_connection_binding)
1586         {
1587           int el;
1588           
1589           if(!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0))
1590               {
1591               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1592               return NULL;
1593               }
1594
1595           if((limit - ret - 4 - el) < 0) return NULL;
1596           
1597           s2n(TLSEXT_TYPE_renegotiate,ret);
1598           s2n(el,ret);
1599
1600           if(!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el))
1601               {
1602               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1603               return NULL;
1604               }
1605
1606           ret += el;
1607         }
1608
1609         /* Only add RI for SSLv3 */
1610         if (s->version == SSL3_VERSION)
1611                 goto done;
1612
1613         if (!s->hit && s->servername_done == 1 && s->session->tlsext_hostname != NULL)
1614                 {
1615                 if ((long)(limit - ret - 4) < 0) return NULL;
1616
1617                 s2n(TLSEXT_TYPE_server_name,ret);
1618                 s2n(0,ret);
1619                 }
1620
1621 #ifndef OPENSSL_NO_EC
1622         if (using_ecc)
1623                 {
1624                 const unsigned char *plist;
1625                 size_t plistlen;
1626                 /* Add TLS extension ECPointFormats to the ServerHello message */
1627                 long lenmax; 
1628
1629                 tls1_get_formatlist(s, &plist, &plistlen);
1630
1631                 if ((lenmax = limit - ret - 5) < 0) return NULL; 
1632                 if (plistlen > (size_t)lenmax) return NULL;
1633                 if (plistlen > 255)
1634                         {
1635                         SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1636                         return NULL;
1637                         }
1638                 
1639                 s2n(TLSEXT_TYPE_ec_point_formats,ret);
1640                 s2n(plistlen + 1,ret);
1641                 *(ret++) = (unsigned char) plistlen;
1642                 memcpy(ret, plist, plistlen);
1643                 ret+=plistlen;
1644
1645                 }
1646         /* Currently the server should not respond with a SupportedCurves extension */
1647 #endif /* OPENSSL_NO_EC */
1648
1649         if (s->tlsext_ticket_expected && tls_use_ticket(s))
1650                 { 
1651                 if ((long)(limit - ret - 4) < 0) return NULL; 
1652                 s2n(TLSEXT_TYPE_session_ticket,ret);
1653                 s2n(0,ret);
1654                 }
1655
1656         if (s->tlsext_status_expected)
1657                 { 
1658                 if ((long)(limit - ret - 4) < 0) return NULL; 
1659                 s2n(TLSEXT_TYPE_status_request,ret);
1660                 s2n(0,ret);
1661                 }
1662
1663 #ifdef TLSEXT_TYPE_opaque_prf_input
1664         if (s->s3->server_opaque_prf_input != NULL)
1665                 {
1666                 size_t sol = s->s3->server_opaque_prf_input_len;
1667                 
1668                 if ((long)(limit - ret - 6 - sol) < 0)
1669                         return NULL;
1670                 if (sol > 0xFFFD) /* can't happen */
1671                         return NULL;
1672
1673                 s2n(TLSEXT_TYPE_opaque_prf_input, ret); 
1674                 s2n(sol + 2, ret);
1675                 s2n(sol, ret);
1676                 memcpy(ret, s->s3->server_opaque_prf_input, sol);
1677                 ret += sol;
1678                 }
1679 #endif
1680
1681         if(SSL_IS_DTLS(s) && s->srtp_profile)
1682                 {
1683                 int el;
1684
1685                 ssl_add_serverhello_use_srtp_ext(s, 0, &el, 0);
1686                 
1687                 if((limit - ret - 4 - el) < 0) return NULL;
1688
1689                 s2n(TLSEXT_TYPE_use_srtp,ret);
1690                 s2n(el,ret);
1691
1692                 if(ssl_add_serverhello_use_srtp_ext(s, ret, &el, el))
1693                         {
1694                         SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1695                         return NULL;
1696                         }
1697                 ret+=el;
1698                 }
1699
1700         if (((s->s3->tmp.new_cipher->id & 0xFFFF)==0x80 || (s->s3->tmp.new_cipher->id & 0xFFFF)==0x81) 
1701                 && (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG))
1702                 { const unsigned char cryptopro_ext[36] = {
1703                         0xfd, 0xe8, /*65000*/
1704                         0x00, 0x20, /*32 bytes length*/
1705                         0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85, 
1706                         0x03,   0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06, 
1707                         0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08, 
1708                         0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17};
1709                         if (limit-ret<36) return NULL;
1710                         memcpy(ret,cryptopro_ext,36);
1711                         ret+=36;
1712
1713                 }
1714
1715 #ifndef OPENSSL_NO_HEARTBEATS
1716         /* Add Heartbeat extension if we've received one */
1717         if (s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED)
1718                 {
1719                 if ((limit - ret - 4 - 1) < 0)
1720                         return NULL;
1721                 s2n(TLSEXT_TYPE_heartbeat,ret);
1722                 s2n(1,ret);
1723                 /* Set mode:
1724                  * 1: peer may send requests
1725                  * 2: peer not allowed to send requests
1726                  */
1727                 if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1728                         *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1729                 else
1730                         *(ret++) = SSL_TLSEXT_HB_ENABLED;
1731
1732                 }
1733 #endif
1734
1735 #ifndef OPENSSL_NO_NEXTPROTONEG
1736         next_proto_neg_seen = s->s3->next_proto_neg_seen;
1737         s->s3->next_proto_neg_seen = 0;
1738         if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb)
1739                 {
1740                 const unsigned char *npa;
1741                 unsigned int npalen;
1742                 int r;
1743
1744                 r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen, s->ctx->next_protos_advertised_cb_arg);
1745                 if (r == SSL_TLSEXT_ERR_OK)
1746                         {
1747                         if ((long)(limit - ret - 4 - npalen) < 0) return NULL;
1748                         s2n(TLSEXT_TYPE_next_proto_neg,ret);
1749                         s2n(npalen,ret);
1750                         memcpy(ret, npa, npalen);
1751                         ret += npalen;
1752                         s->s3->next_proto_neg_seen = 1;
1753                         }
1754                 }
1755 #endif
1756         if (!custom_ext_add(s, 1, &ret, limit, al))
1757                 return NULL;
1758 #ifdef TLSEXT_TYPE_encrypt_then_mac
1759         if (s->s3->flags & TLS1_FLAGS_ENCRYPT_THEN_MAC)
1760                 {
1761                 /* Don't use encrypt_then_mac if AEAD or RC4
1762                  * might want to disable for other cases too.
1763                  */
1764                 if (s->s3->tmp.new_cipher->algorithm_mac == SSL_AEAD
1765                     || s->s3->tmp.new_cipher->algorithm_enc == SSL_RC4)
1766                         s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;
1767                 else
1768                         {
1769                         s2n(TLSEXT_TYPE_encrypt_then_mac,ret);
1770                         s2n(0,ret);
1771                         }
1772                 }
1773 #endif
1774
1775         if (s->s3->alpn_selected)
1776                 {
1777                 const unsigned char *selected = s->s3->alpn_selected;
1778                 unsigned len = s->s3->alpn_selected_len;
1779
1780                 if ((long)(limit - ret - 4 - 2 - 1 - len) < 0)
1781                         return NULL;
1782                 s2n(TLSEXT_TYPE_application_layer_protocol_negotiation,ret);
1783                 s2n(3 + len,ret);
1784                 s2n(1 + len,ret);
1785                 *ret++ = len;
1786                 memcpy(ret, selected, len);
1787                 ret += len;
1788                 }
1789
1790         done:
1791
1792         if ((extdatalen = ret-orig-2)== 0) 
1793                 return orig;
1794
1795         s2n(extdatalen, orig);
1796         return ret;
1797         }
1798
1799 /* tls1_alpn_handle_client_hello is called to process the ALPN extension in a
1800  * ClientHello.
1801  *   data: the contents of the extension, not including the type and length.
1802  *   data_len: the number of bytes in |data|
1803  *   al: a pointer to the alert value to send in the event of a non-zero
1804  *       return.
1805  *
1806  *   returns: 0 on success. */
1807 static int tls1_alpn_handle_client_hello(SSL *s, const unsigned char *data,
1808                                          unsigned data_len, int *al)
1809         {
1810         unsigned i;
1811         unsigned proto_len;
1812         const unsigned char *selected;
1813         unsigned char selected_len;
1814         int r;
1815
1816         if (s->ctx->alpn_select_cb == NULL)
1817                 return 0;
1818
1819         if (data_len < 2)
1820                 goto parse_error;
1821
1822         /* data should contain a uint16 length followed by a series of 8-bit,
1823          * length-prefixed strings. */
1824         i = ((unsigned) data[0]) << 8 |
1825             ((unsigned) data[1]);
1826         data_len -= 2;
1827         data += 2;
1828         if (data_len != i)
1829                 goto parse_error;
1830
1831         if (data_len < 2)
1832                 goto parse_error;
1833
1834         for (i = 0; i < data_len;)
1835                 {
1836                 proto_len = data[i];
1837                 i++;
1838
1839                 if (proto_len == 0)
1840                         goto parse_error;
1841
1842                 if (i + proto_len < i || i + proto_len > data_len)
1843                         goto parse_error;
1844
1845                 i += proto_len;
1846                 }
1847
1848         r = s->ctx->alpn_select_cb(s, &selected, &selected_len, data, data_len,
1849                                    s->ctx->alpn_select_cb_arg);
1850         if (r == SSL_TLSEXT_ERR_OK) {
1851                 if (s->s3->alpn_selected)
1852                         OPENSSL_free(s->s3->alpn_selected);
1853                 s->s3->alpn_selected = OPENSSL_malloc(selected_len);
1854                 if (!s->s3->alpn_selected)
1855                         {
1856                         *al = SSL_AD_INTERNAL_ERROR;
1857                         return -1;
1858                         }
1859                 memcpy(s->s3->alpn_selected, selected, selected_len);
1860                 s->s3->alpn_selected_len = selected_len;
1861         }
1862         return 0;
1863
1864 parse_error:
1865         *al = SSL_AD_DECODE_ERROR;
1866         return -1;
1867         }
1868
1869 #ifndef OPENSSL_NO_EC
1870 /* ssl_check_for_safari attempts to fingerprint Safari using OS X
1871  * SecureTransport using the TLS extension block in |d|, of length |n|.
1872  * Safari, since 10.6, sends exactly these extensions, in this order:
1873  *   SNI,
1874  *   elliptic_curves
1875  *   ec_point_formats
1876  *
1877  * We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,
1878  * but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.
1879  * Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from
1880  * 10.8..10.8.3 (which don't work).
1881  */
1882 static void ssl_check_for_safari(SSL *s, const unsigned char *data, const unsigned char *d, int n) {
1883         unsigned short type, size;
1884         static const unsigned char kSafariExtensionsBlock[] = {
1885                 0x00, 0x0a,  /* elliptic_curves extension */
1886                 0x00, 0x08,  /* 8 bytes */
1887                 0x00, 0x06,  /* 6 bytes of curve ids */
1888                 0x00, 0x17,  /* P-256 */
1889                 0x00, 0x18,  /* P-384 */
1890                 0x00, 0x19,  /* P-521 */
1891
1892                 0x00, 0x0b,  /* ec_point_formats */
1893                 0x00, 0x02,  /* 2 bytes */
1894                 0x01,        /* 1 point format */
1895                 0x00,        /* uncompressed */
1896         };
1897
1898         /* The following is only present in TLS 1.2 */
1899         static const unsigned char kSafariTLS12ExtensionsBlock[] = {
1900                 0x00, 0x0d,  /* signature_algorithms */
1901                 0x00, 0x0c,  /* 12 bytes */
1902                 0x00, 0x0a,  /* 10 bytes */
1903                 0x05, 0x01,  /* SHA-384/RSA */
1904                 0x04, 0x01,  /* SHA-256/RSA */
1905                 0x02, 0x01,  /* SHA-1/RSA */
1906                 0x04, 0x03,  /* SHA-256/ECDSA */
1907                 0x02, 0x03,  /* SHA-1/ECDSA */
1908         };
1909
1910         if (data >= (d+n-2))
1911                 return;
1912         data += 2;
1913
1914         if (data > (d+n-4))
1915                 return;
1916         n2s(data,type);
1917         n2s(data,size);
1918
1919         if (type != TLSEXT_TYPE_server_name)
1920                 return;
1921
1922         if (data+size > d+n)
1923                 return;
1924         data += size;
1925
1926         if (TLS1_get_client_version(s) >= TLS1_2_VERSION)
1927                 {
1928                 const size_t len1 = sizeof(kSafariExtensionsBlock);
1929                 const size_t len2 = sizeof(kSafariTLS12ExtensionsBlock);
1930
1931                 if (data + len1 + len2 != d+n)
1932                         return;
1933                 if (memcmp(data, kSafariExtensionsBlock, len1) != 0)
1934                         return;
1935                 if (memcmp(data + len1, kSafariTLS12ExtensionsBlock, len2) != 0)
1936                         return;
1937                 }
1938         else
1939                 {
1940                 const size_t len = sizeof(kSafariExtensionsBlock);
1941
1942                 if (data + len != d+n)
1943                         return;
1944                 if (memcmp(data, kSafariExtensionsBlock, len) != 0)
1945                         return;
1946                 }
1947
1948         s->s3->is_probably_safari = 1;
1949 }
1950 #endif /* !OPENSSL_NO_EC */
1951
1952
1953 static int ssl_scan_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al) 
1954         {       
1955         unsigned short type;
1956         unsigned short size;
1957         unsigned short len;
1958         unsigned char *data = *p;
1959         int renegotiate_seen = 0;
1960
1961         s->servername_done = 0;
1962         s->tlsext_status_type = -1;
1963 #ifndef OPENSSL_NO_NEXTPROTONEG
1964         s->s3->next_proto_neg_seen = 0;
1965 #endif
1966
1967         if (s->s3->alpn_selected)
1968                 {
1969                 OPENSSL_free(s->s3->alpn_selected);
1970                 s->s3->alpn_selected = NULL;
1971                 }
1972
1973 #ifndef OPENSSL_NO_HEARTBEATS
1974         s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
1975                                SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
1976 #endif
1977
1978 #ifndef OPENSSL_NO_EC
1979         if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
1980                 ssl_check_for_safari(s, data, d, n);
1981 #endif /* !OPENSSL_NO_EC */
1982
1983         /* Clear any signature algorithms extension received */
1984         if (s->cert->peer_sigalgs)
1985                 {
1986                 OPENSSL_free(s->cert->peer_sigalgs);
1987                 s->cert->peer_sigalgs = NULL;
1988                 }
1989
1990 #ifdef TLSEXT_TYPE_encrypt_then_mac
1991         s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;
1992 #endif
1993
1994         if (data >= (d+n-2))
1995                 goto ri_check;
1996         n2s(data,len);
1997
1998         if (data > (d+n-len)) 
1999                 goto ri_check;
2000
2001         while (data <= (d+n-4))
2002                 {
2003                 n2s(data,type);
2004                 n2s(data,size);
2005
2006                 if (data+size > (d+n))
2007                         goto ri_check;
2008 #if 0
2009                 fprintf(stderr,"Received extension type %d size %d\n",type,size);
2010 #endif
2011                 if (s->tlsext_debug_cb)
2012                         s->tlsext_debug_cb(s, 0, type, data, size,
2013                                                 s->tlsext_debug_arg);
2014                 if (type == TLSEXT_TYPE_renegotiate)
2015                         {
2016                         if(!ssl_parse_clienthello_renegotiate_ext(s, data, size, al))
2017                                 return 0;
2018                         renegotiate_seen = 1;
2019                         }
2020                 else if (s->version == SSL3_VERSION)
2021                         {}
2022 /* The servername extension is treated as follows:
2023
2024    - Only the hostname type is supported with a maximum length of 255.
2025    - The servername is rejected if too long or if it contains zeros,
2026      in which case an fatal alert is generated.
2027    - The servername field is maintained together with the session cache.
2028    - When a session is resumed, the servername call back invoked in order
2029      to allow the application to position itself to the right context. 
2030    - The servername is acknowledged if it is new for a session or when 
2031      it is identical to a previously used for the same session. 
2032      Applications can control the behaviour.  They can at any time
2033      set a 'desirable' servername for a new SSL object. This can be the
2034      case for example with HTTPS when a Host: header field is received and
2035      a renegotiation is requested. In this case, a possible servername
2036      presented in the new client hello is only acknowledged if it matches
2037      the value of the Host: field. 
2038    - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
2039      if they provide for changing an explicit servername context for the session,
2040      i.e. when the session has been established with a servername extension. 
2041    - On session reconnect, the servername extension may be absent. 
2042
2043 */      
2044
2045                 else if (type == TLSEXT_TYPE_server_name)
2046                         {
2047                         unsigned char *sdata;
2048                         int servname_type;
2049                         int dsize; 
2050                 
2051                         if (size < 2) 
2052                                 {
2053                                 *al = SSL_AD_DECODE_ERROR;
2054                                 return 0;
2055                                 }
2056                         n2s(data,dsize);  
2057                         size -= 2;
2058                         if (dsize > size  ) 
2059                                 {
2060                                 *al = SSL_AD_DECODE_ERROR;
2061                                 return 0;
2062                                 } 
2063
2064                         sdata = data;
2065                         while (dsize > 3) 
2066                                 {
2067                                 servname_type = *(sdata++); 
2068                                 n2s(sdata,len);
2069                                 dsize -= 3;
2070
2071                                 if (len > dsize) 
2072                                         {
2073                                         *al = SSL_AD_DECODE_ERROR;
2074                                         return 0;
2075                                         }
2076                                 if (s->servername_done == 0)
2077                                 switch (servname_type)
2078                                         {
2079                                 case TLSEXT_NAMETYPE_host_name:
2080                                         if (!s->hit)
2081                                                 {
2082                                                 if(s->session->tlsext_hostname)
2083                                                         {
2084                                                         *al = SSL_AD_DECODE_ERROR;
2085                                                         return 0;
2086                                                         }
2087                                                 if (len > TLSEXT_MAXLEN_host_name)
2088                                                         {
2089                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
2090                                                         return 0;
2091                                                         }
2092                                                 if ((s->session->tlsext_hostname = OPENSSL_malloc(len+1)) == NULL)
2093                                                         {
2094                                                         *al = TLS1_AD_INTERNAL_ERROR;
2095                                                         return 0;
2096                                                         }
2097                                                 memcpy(s->session->tlsext_hostname, sdata, len);
2098                                                 s->session->tlsext_hostname[len]='\0';
2099                                                 if (strlen(s->session->tlsext_hostname) != len) {
2100                                                         OPENSSL_free(s->session->tlsext_hostname);
2101                                                         s->session->tlsext_hostname = NULL;
2102                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
2103                                                         return 0;
2104                                                 }
2105                                                 s->servername_done = 1; 
2106
2107                                                 }
2108                                         else 
2109                                                 s->servername_done = s->session->tlsext_hostname
2110                                                         && strlen(s->session->tlsext_hostname) == len 
2111                                                         && strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0;
2112                                         
2113                                         break;
2114
2115                                 default:
2116                                         break;
2117                                         }
2118                                  
2119                                 dsize -= len;
2120                                 }
2121                         if (dsize != 0) 
2122                                 {
2123                                 *al = SSL_AD_DECODE_ERROR;
2124                                 return 0;
2125                                 }
2126
2127                         }
2128 #ifndef OPENSSL_NO_SRP
2129                 else if (type == TLSEXT_TYPE_srp)
2130                         {
2131                         if (size <= 0 || ((len = data[0])) != (size -1))
2132                                 {
2133                                 *al = SSL_AD_DECODE_ERROR;
2134                                 return 0;
2135                                 }
2136                         if (s->srp_ctx.login != NULL)
2137                                 {
2138                                 *al = SSL_AD_DECODE_ERROR;
2139                                 return 0;
2140                                 }
2141                         if ((s->srp_ctx.login = OPENSSL_malloc(len+1)) == NULL)
2142                                 return -1;
2143                         memcpy(s->srp_ctx.login, &data[1], len);
2144                         s->srp_ctx.login[len]='\0';
2145   
2146                         if (strlen(s->srp_ctx.login) != len) 
2147                                 {
2148                                 *al = SSL_AD_DECODE_ERROR;
2149                                 return 0;
2150                                 }
2151                         }
2152 #endif
2153
2154 #ifndef OPENSSL_NO_EC
2155                 else if (type == TLSEXT_TYPE_ec_point_formats)
2156                         {
2157                         unsigned char *sdata = data;
2158                         int ecpointformatlist_length = *(sdata++);
2159
2160                         if (ecpointformatlist_length != size - 1 || 
2161                                 ecpointformatlist_length < 1)
2162                                 {
2163                                 *al = TLS1_AD_DECODE_ERROR;
2164                                 return 0;
2165                                 }
2166                         if (!s->hit)
2167                                 {
2168                                 if(s->session->tlsext_ecpointformatlist)
2169                                         {
2170                                         OPENSSL_free(s->session->tlsext_ecpointformatlist);
2171                                         s->session->tlsext_ecpointformatlist = NULL;
2172                                         }
2173                                 s->session->tlsext_ecpointformatlist_length = 0;
2174                                 if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
2175                                         {
2176                                         *al = TLS1_AD_INTERNAL_ERROR;
2177                                         return 0;
2178                                         }
2179                                 s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
2180                                 memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
2181                                 }
2182 #if 0
2183                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ", s->session->tlsext_ecpointformatlist_length);
2184                         sdata = s->session->tlsext_ecpointformatlist;
2185                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2186                                 fprintf(stderr,"%i ",*(sdata++));
2187                         fprintf(stderr,"\n");
2188 #endif
2189                         }
2190                 else if (type == TLSEXT_TYPE_elliptic_curves)
2191                         {
2192                         unsigned char *sdata = data;
2193                         int ellipticcurvelist_length = (*(sdata++) << 8);
2194                         ellipticcurvelist_length += (*(sdata++));
2195
2196                         if (ellipticcurvelist_length != size - 2 ||
2197                                 ellipticcurvelist_length < 1 ||
2198                                 /* Each NamedCurve is 2 bytes. */
2199                                 ellipticcurvelist_length & 1)
2200                                 {
2201                                 *al = TLS1_AD_DECODE_ERROR;
2202                                 return 0;
2203                                 }
2204                         if (!s->hit)
2205                                 {
2206                                 if(s->session->tlsext_ellipticcurvelist)
2207                                         {
2208                                         *al = TLS1_AD_DECODE_ERROR;
2209                                         return 0;
2210                                         }
2211                                 s->session->tlsext_ellipticcurvelist_length = 0;
2212                                 if ((s->session->tlsext_ellipticcurvelist = OPENSSL_malloc(ellipticcurvelist_length)) == NULL)
2213                                         {
2214                                         *al = TLS1_AD_INTERNAL_ERROR;
2215                                         return 0;
2216                                         }
2217                                 s->session->tlsext_ellipticcurvelist_length = ellipticcurvelist_length;
2218                                 memcpy(s->session->tlsext_ellipticcurvelist, sdata, ellipticcurvelist_length);
2219                                 }
2220 #if 0
2221                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ", s->session->tlsext_ellipticcurvelist_length);
2222                         sdata = s->session->tlsext_ellipticcurvelist;
2223                         for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++)
2224                                 fprintf(stderr,"%i ",*(sdata++));
2225                         fprintf(stderr,"\n");
2226 #endif
2227                         }
2228 #endif /* OPENSSL_NO_EC */
2229 #ifdef TLSEXT_TYPE_opaque_prf_input
2230                 else if (type == TLSEXT_TYPE_opaque_prf_input)
2231                         {
2232                         unsigned char *sdata = data;
2233
2234                         if (size < 2)
2235                                 {
2236                                 *al = SSL_AD_DECODE_ERROR;
2237                                 return 0;
2238                                 }
2239                         n2s(sdata, s->s3->client_opaque_prf_input_len);
2240                         if (s->s3->client_opaque_prf_input_len != size - 2)
2241                                 {
2242                                 *al = SSL_AD_DECODE_ERROR;
2243                                 return 0;
2244                                 }
2245
2246                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
2247                                 OPENSSL_free(s->s3->client_opaque_prf_input);
2248                         if (s->s3->client_opaque_prf_input_len == 0)
2249                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2250                         else
2251                                 s->s3->client_opaque_prf_input = BUF_memdup(sdata, s->s3->client_opaque_prf_input_len);
2252                         if (s->s3->client_opaque_prf_input == NULL)
2253                                 {
2254                                 *al = TLS1_AD_INTERNAL_ERROR;
2255                                 return 0;
2256                                 }
2257                         }
2258 #endif
2259                 else if (type == TLSEXT_TYPE_session_ticket)
2260                         {
2261                         if (s->tls_session_ticket_ext_cb &&
2262                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
2263                                 {
2264                                 *al = TLS1_AD_INTERNAL_ERROR;
2265                                 return 0;
2266                                 }
2267                         }
2268                 else if (type == TLSEXT_TYPE_signature_algorithms)
2269                         {
2270                         int dsize;
2271                         if (s->cert->peer_sigalgs || size < 2) 
2272                                 {
2273                                 *al = SSL_AD_DECODE_ERROR;
2274                                 return 0;
2275                                 }
2276                         n2s(data,dsize);
2277                         size -= 2;
2278                         if (dsize != size || dsize & 1 || !dsize) 
2279                                 {
2280                                 *al = SSL_AD_DECODE_ERROR;
2281                                 return 0;
2282                                 }
2283                         if (!tls1_save_sigalgs(s, data, dsize))
2284                                 {
2285                                 *al = SSL_AD_DECODE_ERROR;
2286                                 return 0;
2287                                 }
2288                         }
2289                 else if (type == TLSEXT_TYPE_status_request)
2290                         {
2291                 
2292                         if (size < 5) 
2293                                 {
2294                                 *al = SSL_AD_DECODE_ERROR;
2295                                 return 0;
2296                                 }
2297
2298                         s->tlsext_status_type = *data++;
2299                         size--;
2300                         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp)
2301                                 {
2302                                 const unsigned char *sdata;
2303                                 int dsize;
2304                                 /* Read in responder_id_list */
2305                                 n2s(data,dsize);
2306                                 size -= 2;
2307                                 if (dsize > size  ) 
2308                                         {
2309                                         *al = SSL_AD_DECODE_ERROR;
2310                                         return 0;
2311                                         }
2312                                 while (dsize > 0)
2313                                         {
2314                                         OCSP_RESPID *id;
2315                                         int idsize;
2316                                         if (dsize < 4)
2317                                                 {
2318                                                 *al = SSL_AD_DECODE_ERROR;
2319                                                 return 0;
2320                                                 }
2321                                         n2s(data, idsize);
2322                                         dsize -= 2 + idsize;
2323                                         size -= 2 + idsize;
2324                                         if (dsize < 0)
2325                                                 {
2326                                                 *al = SSL_AD_DECODE_ERROR;
2327                                                 return 0;
2328                                                 }
2329                                         sdata = data;
2330                                         data += idsize;
2331                                         id = d2i_OCSP_RESPID(NULL,
2332                                                                 &sdata, idsize);
2333                                         if (!id)
2334                                                 {
2335                                                 *al = SSL_AD_DECODE_ERROR;
2336                                                 return 0;
2337                                                 }
2338                                         if (data != sdata)
2339                                                 {
2340                                                 OCSP_RESPID_free(id);
2341                                                 *al = SSL_AD_DECODE_ERROR;
2342                                                 return 0;
2343                                                 }
2344                                         if (!s->tlsext_ocsp_ids
2345                                                 && !(s->tlsext_ocsp_ids =
2346                                                 sk_OCSP_RESPID_new_null()))
2347                                                 {
2348                                                 OCSP_RESPID_free(id);
2349                                                 *al = SSL_AD_INTERNAL_ERROR;
2350                                                 return 0;
2351                                                 }
2352                                         if (!sk_OCSP_RESPID_push(
2353                                                         s->tlsext_ocsp_ids, id))
2354                                                 {
2355                                                 OCSP_RESPID_free(id);
2356                                                 *al = SSL_AD_INTERNAL_ERROR;
2357                                                 return 0;
2358                                                 }
2359                                         }
2360
2361                                 /* Read in request_extensions */
2362                                 if (size < 2)
2363                                         {
2364                                         *al = SSL_AD_DECODE_ERROR;
2365                                         return 0;
2366                                         }
2367                                 n2s(data,dsize);
2368                                 size -= 2;
2369                                 if (dsize != size)
2370                                         {
2371                                         *al = SSL_AD_DECODE_ERROR;
2372                                         return 0;
2373                                         }
2374                                 sdata = data;
2375                                 if (dsize > 0)
2376                                         {
2377                                         if (s->tlsext_ocsp_exts)
2378                                                 {
2379                                                 sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
2380                                                                            X509_EXTENSION_free);
2381                                                 }
2382
2383                                         s->tlsext_ocsp_exts =
2384                                                 d2i_X509_EXTENSIONS(NULL,
2385                                                         &sdata, dsize);
2386                                         if (!s->tlsext_ocsp_exts
2387                                                 || (data + dsize != sdata))
2388                                                 {
2389                                                 *al = SSL_AD_DECODE_ERROR;
2390                                                 return 0;
2391                                                 }
2392                                         }
2393                                 }
2394                                 /* We don't know what to do with any other type
2395                                 * so ignore it.
2396                                 */
2397                                 else
2398                                         s->tlsext_status_type = -1;
2399                         }
2400 #ifndef OPENSSL_NO_HEARTBEATS
2401                 else if (type == TLSEXT_TYPE_heartbeat)
2402                         {
2403                         switch(data[0])
2404                                 {
2405                                 case 0x01:      /* Client allows us to send HB requests */
2406                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2407                                                         break;
2408                                 case 0x02:      /* Client doesn't accept HB requests */
2409                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2410                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2411                                                         break;
2412                                 default:        *al = SSL_AD_ILLEGAL_PARAMETER;
2413                                                         return 0;
2414                                 }
2415                         }
2416 #endif
2417 #ifndef OPENSSL_NO_NEXTPROTONEG
2418                 else if (type == TLSEXT_TYPE_next_proto_neg &&
2419                          s->s3->tmp.finish_md_len == 0 &&
2420                          s->s3->alpn_selected == NULL)
2421                         {
2422                         /* We shouldn't accept this extension on a
2423                          * renegotiation.
2424                          *
2425                          * s->new_session will be set on renegotiation, but we
2426                          * probably shouldn't rely that it couldn't be set on
2427                          * the initial renegotation too in certain cases (when
2428                          * there's some other reason to disallow resuming an
2429                          * earlier session -- the current code won't be doing
2430                          * anything like that, but this might change).
2431
2432                          * A valid sign that there's been a previous handshake
2433                          * in this connection is if s->s3->tmp.finish_md_len >
2434                          * 0.  (We are talking about a check that will happen
2435                          * in the Hello protocol round, well before a new
2436                          * Finished message could have been computed.) */
2437                         s->s3->next_proto_neg_seen = 1;
2438                         }
2439 #endif
2440
2441                 else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation &&
2442                          s->ctx->alpn_select_cb &&
2443                          s->s3->tmp.finish_md_len == 0)
2444                         {
2445                         if (tls1_alpn_handle_client_hello(s, data, size, al) != 0)
2446                                 return 0;
2447 #ifndef OPENSSL_NO_NEXTPROTONEG
2448                         /* ALPN takes precedence over NPN. */
2449                         s->s3->next_proto_neg_seen = 0;
2450 #endif
2451                         }
2452
2453                 /* session ticket processed earlier */
2454                 else if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s)
2455                                 && type == TLSEXT_TYPE_use_srtp)
2456                         {
2457                         if(ssl_parse_clienthello_use_srtp_ext(s, data, size,
2458                                                               al))
2459                                 return 0;
2460                         }
2461 #ifdef TLSEXT_TYPE_encrypt_then_mac
2462                 else if (type == TLSEXT_TYPE_encrypt_then_mac)
2463                         s->s3->flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC;
2464 #endif
2465                 /* If this ClientHello extension was unhandled and this is 
2466                  * a nonresumed connection, check whether the extension is a 
2467                  * custom TLS Extension (has a custom_srv_ext_record), and if
2468                  * so call the callback and record the extension number so that
2469                  * an appropriate ServerHello may be later returned.
2470                  */
2471                 else if (!s->hit)
2472                         {
2473                         if (custom_ext_parse(s, 1, type, data, size, al) <= 0)
2474                                 return 0;
2475                         }
2476
2477                 data+=size;
2478                 }
2479
2480         *p = data;
2481
2482         ri_check:
2483
2484         /* Need RI if renegotiating */
2485
2486         if (!renegotiate_seen && s->renegotiate &&
2487                 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
2488                 {
2489                 *al = SSL_AD_HANDSHAKE_FAILURE;
2490                 SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
2491                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2492                 return 0;
2493                 }
2494
2495         return 1;
2496         }
2497
2498 int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n) 
2499         {
2500         int al = -1;
2501         custom_ext_init(&s->cert->srv_ext);
2502         if (ssl_scan_clienthello_tlsext(s, p, d, n, &al) <= 0) 
2503                 {
2504                 ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2505                 return 0;
2506                 }
2507
2508         if (ssl_check_clienthello_tlsext_early(s) <= 0) 
2509                 {
2510                 SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT,SSL_R_CLIENTHELLO_TLSEXT);
2511                 return 0;
2512                 }
2513         return 1;
2514 }
2515
2516 #ifndef OPENSSL_NO_NEXTPROTONEG
2517 /* ssl_next_proto_validate validates a Next Protocol Negotiation block. No
2518  * elements of zero length are allowed and the set of elements must exactly fill
2519  * the length of the block. */
2520 static char ssl_next_proto_validate(unsigned char *d, unsigned len)
2521         {
2522         unsigned int off = 0;
2523
2524         while (off < len)
2525                 {
2526                 if (d[off] == 0)
2527                         return 0;
2528                 off += d[off];
2529                 off++;
2530                 }
2531
2532         return off == len;
2533         }
2534 #endif
2535
2536 static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
2537         {
2538         unsigned short length;
2539         unsigned short type;
2540         unsigned short size;
2541         unsigned char *data = *p;
2542         int tlsext_servername = 0;
2543         int renegotiate_seen = 0;
2544
2545 #ifndef OPENSSL_NO_NEXTPROTONEG
2546         s->s3->next_proto_neg_seen = 0;
2547 #endif
2548         s->tlsext_ticket_expected = 0;
2549
2550         if (s->s3->alpn_selected)
2551                 {
2552                 OPENSSL_free(s->s3->alpn_selected);
2553                 s->s3->alpn_selected = NULL;
2554                 }
2555
2556 #ifndef OPENSSL_NO_HEARTBEATS
2557         s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
2558                                SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
2559 #endif
2560
2561 #ifdef TLSEXT_TYPE_encrypt_then_mac
2562         s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;
2563 #endif
2564
2565         if (data >= (d+n-2))
2566                 goto ri_check;
2567
2568         n2s(data,length);
2569         if (data+length != d+n)
2570                 {
2571                 *al = SSL_AD_DECODE_ERROR;
2572                 return 0;
2573                 }
2574
2575         while(data <= (d+n-4))
2576                 {
2577                 n2s(data,type);
2578                 n2s(data,size);
2579
2580                 if (data+size > (d+n))
2581                         goto ri_check;
2582
2583                 if (s->tlsext_debug_cb)
2584                         s->tlsext_debug_cb(s, 1, type, data, size,
2585                                                 s->tlsext_debug_arg);
2586
2587
2588                 if (type == TLSEXT_TYPE_renegotiate)
2589                         {
2590                         if(!ssl_parse_serverhello_renegotiate_ext(s, data, size, al))
2591                                 return 0;
2592                         renegotiate_seen = 1;
2593                         }
2594                 else if (s->version == SSL3_VERSION)
2595                         {}
2596                 else if (type == TLSEXT_TYPE_server_name)
2597                         {
2598                         if (s->tlsext_hostname == NULL || size > 0)
2599                                 {
2600                                 *al = TLS1_AD_UNRECOGNIZED_NAME;
2601                                 return 0;
2602                                 }
2603                         tlsext_servername = 1;   
2604                         }
2605
2606 #ifndef OPENSSL_NO_EC
2607                 else if (type == TLSEXT_TYPE_ec_point_formats)
2608                         {
2609                         unsigned char *sdata = data;
2610                         int ecpointformatlist_length = *(sdata++);
2611
2612                         if (ecpointformatlist_length != size - 1)
2613                                 {
2614                                 *al = TLS1_AD_DECODE_ERROR;
2615                                 return 0;
2616                                 }
2617                         if (!s->hit)
2618                                 {
2619                                 s->session->tlsext_ecpointformatlist_length = 0;
2620                                 if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist);
2621                                 if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
2622                                         {
2623                                         *al = TLS1_AD_INTERNAL_ERROR;
2624                                         return 0;
2625                                         }
2626                                 s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
2627                                 memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
2628                                 }
2629 #if 0
2630                         fprintf(stderr,"ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist ");
2631                         sdata = s->session->tlsext_ecpointformatlist;
2632                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2633                                 fprintf(stderr,"%i ",*(sdata++));
2634                         fprintf(stderr,"\n");
2635 #endif
2636                         }
2637 #endif /* OPENSSL_NO_EC */
2638
2639                 else if (type == TLSEXT_TYPE_session_ticket)
2640                         {
2641                         if (s->tls_session_ticket_ext_cb &&
2642                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
2643                                 {
2644                                 *al = TLS1_AD_INTERNAL_ERROR;
2645                                 return 0;
2646                                 }
2647                         if (!tls_use_ticket(s) || (size > 0))
2648                                 {
2649                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2650                                 return 0;
2651                                 }
2652                         s->tlsext_ticket_expected = 1;
2653                         }
2654 #ifdef TLSEXT_TYPE_opaque_prf_input
2655                 else if (type == TLSEXT_TYPE_opaque_prf_input)
2656                         {
2657                         unsigned char *sdata = data;
2658
2659                         if (size < 2)
2660                                 {
2661                                 *al = SSL_AD_DECODE_ERROR;
2662                                 return 0;
2663                                 }
2664                         n2s(sdata, s->s3->server_opaque_prf_input_len);
2665                         if (s->s3->server_opaque_prf_input_len != size - 2)
2666                                 {
2667                                 *al = SSL_AD_DECODE_ERROR;
2668                                 return 0;
2669                                 }
2670                         
2671                         if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
2672                                 OPENSSL_free(s->s3->server_opaque_prf_input);
2673                         if (s->s3->server_opaque_prf_input_len == 0)
2674                                 s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2675                         else
2676                                 s->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len);
2677
2678                         if (s->s3->server_opaque_prf_input == NULL)
2679                                 {
2680                                 *al = TLS1_AD_INTERNAL_ERROR;
2681                                 return 0;
2682                                 }
2683                         }
2684 #endif
2685                 else if (type == TLSEXT_TYPE_status_request)
2686                         {
2687                         /* MUST be empty and only sent if we've requested
2688                          * a status request message.
2689                          */ 
2690                         if ((s->tlsext_status_type == -1) || (size > 0))
2691                                 {
2692                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2693                                 return 0;
2694                                 }
2695                         /* Set flag to expect CertificateStatus message */
2696                         s->tlsext_status_expected = 1;
2697                         }
2698 #ifndef OPENSSL_NO_NEXTPROTONEG
2699                 else if (type == TLSEXT_TYPE_next_proto_neg &&
2700                          s->s3->tmp.finish_md_len == 0)
2701                         {
2702                         unsigned char *selected;
2703                         unsigned char selected_len;
2704
2705                         /* We must have requested it. */
2706                         if (s->ctx->next_proto_select_cb == NULL)
2707                                 {
2708                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2709                                 return 0;
2710                                 }
2711                         /* The data must be valid */
2712                         if (!ssl_next_proto_validate(data, size))
2713                                 {
2714                                 *al = TLS1_AD_DECODE_ERROR;
2715                                 return 0;
2716                                 }
2717                         if (s->ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK)
2718                                 {
2719                                 *al = TLS1_AD_INTERNAL_ERROR;
2720                                 return 0;
2721                                 }
2722                         s->next_proto_negotiated = OPENSSL_malloc(selected_len);
2723                         if (!s->next_proto_negotiated)
2724                                 {
2725                                 *al = TLS1_AD_INTERNAL_ERROR;
2726                                 return 0;
2727                                 }
2728                         memcpy(s->next_proto_negotiated, selected, selected_len);
2729                         s->next_proto_negotiated_len = selected_len;
2730                         s->s3->next_proto_neg_seen = 1;
2731                         }
2732 #endif
2733
2734                 else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation)
2735                         {
2736                         unsigned len;
2737
2738                         /* We must have requested it. */
2739                         if (s->alpn_client_proto_list == NULL)
2740                                 {
2741                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2742                                 return 0;
2743                                 }
2744                         if (size < 4)
2745                                 {
2746                                 *al = TLS1_AD_DECODE_ERROR;
2747                                 return 0;
2748                                 }
2749                         /* The extension data consists of:
2750                          *   uint16 list_length
2751                          *   uint8 proto_length;
2752                          *   uint8 proto[proto_length]; */
2753                         len = data[0];
2754                         len <<= 8;
2755                         len |= data[1];
2756                         if (len != (unsigned) size - 2)
2757                                 {
2758                                 *al = TLS1_AD_DECODE_ERROR;
2759                                 return 0;
2760                                 }
2761                         len = data[2];
2762                         if (len != (unsigned) size - 3)
2763                                 {
2764                                 *al = TLS1_AD_DECODE_ERROR;
2765                                 return 0;
2766                                 }
2767                         if (s->s3->alpn_selected)
2768                                 OPENSSL_free(s->s3->alpn_selected);
2769                         s->s3->alpn_selected = OPENSSL_malloc(len);
2770                         if (!s->s3->alpn_selected)
2771                                 {
2772                                 *al = TLS1_AD_INTERNAL_ERROR;
2773                                 return 0;
2774                                 }
2775                         memcpy(s->s3->alpn_selected, data + 3, len);
2776                         s->s3->alpn_selected_len = len;
2777                         }
2778 #ifndef OPENSSL_NO_HEARTBEATS
2779                 else if (type == TLSEXT_TYPE_heartbeat)
2780                         {
2781                         switch(data[0])
2782                                 {
2783                                 case 0x01:      /* Server allows us to send HB requests */
2784                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2785                                                         break;
2786                                 case 0x02:      /* Server doesn't accept HB requests */
2787                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2788                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2789                                                         break;
2790                                 default:        *al = SSL_AD_ILLEGAL_PARAMETER;
2791                                                         return 0;
2792                                 }
2793                         }
2794 #endif
2795                 else if (SSL_IS_DTLS(s) && type == TLSEXT_TYPE_use_srtp)
2796                         {
2797                         if(ssl_parse_serverhello_use_srtp_ext(s, data, size,
2798                                                               al))
2799                                 return 0;
2800                         }
2801 #ifdef TLSEXT_TYPE_encrypt_then_mac
2802                 else if (type == TLSEXT_TYPE_encrypt_then_mac)
2803                         {
2804                         /* Ignore if inappropriate ciphersuite */
2805                         if (s->s3->tmp.new_cipher->algorithm_mac != SSL_AEAD
2806                             && s->s3->tmp.new_cipher->algorithm_enc != SSL_RC4)
2807                                 s->s3->flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC;
2808                         }
2809 #endif
2810                 /* If this extension type was not otherwise handled, but 
2811                  * matches a custom_cli_ext_record, then send it to the c
2812                  * callback */
2813                 else if (custom_ext_parse(s, 0, type, data, size, al) <= 0)
2814                                 return 0;
2815  
2816                 data += size;
2817                 }
2818
2819         if (data != d+n)
2820                 {
2821                 *al = SSL_AD_DECODE_ERROR;
2822                 return 0;
2823                 }
2824
2825         if (!s->hit && tlsext_servername == 1)
2826                 {
2827                 if (s->tlsext_hostname)
2828                         {
2829                         if (s->session->tlsext_hostname == NULL)
2830                                 {
2831                                 s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);   
2832                                 if (!s->session->tlsext_hostname)
2833                                         {
2834                                         *al = SSL_AD_UNRECOGNIZED_NAME;
2835                                         return 0;
2836                                         }
2837                                 }
2838                         else 
2839                                 {
2840                                 *al = SSL_AD_DECODE_ERROR;
2841                                 return 0;
2842                                 }
2843                         }
2844                 }
2845
2846         *p = data;
2847
2848         ri_check:
2849
2850         /* Determine if we need to see RI. Strictly speaking if we want to
2851          * avoid an attack we should *always* see RI even on initial server
2852          * hello because the client doesn't see any renegotiation during an
2853          * attack. However this would mean we could not connect to any server
2854          * which doesn't support RI so for the immediate future tolerate RI
2855          * absence on initial connect only.
2856          */
2857         if (!renegotiate_seen
2858                 && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
2859                 && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
2860                 {
2861                 *al = SSL_AD_HANDSHAKE_FAILURE;
2862                 SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT,
2863                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2864                 return 0;
2865                 }
2866
2867         return 1;
2868         }
2869
2870
2871 int ssl_prepare_clienthello_tlsext(SSL *s)
2872         {
2873
2874 #ifdef TLSEXT_TYPE_opaque_prf_input
2875         {
2876                 int r = 1;
2877         
2878                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
2879                         {
2880                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
2881                         if (!r)
2882                                 return -1;
2883                         }
2884
2885                 if (s->tlsext_opaque_prf_input != NULL)
2886                         {
2887                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
2888                                 OPENSSL_free(s->s3->client_opaque_prf_input);
2889
2890                         if (s->tlsext_opaque_prf_input_len == 0)
2891                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2892                         else
2893                                 s->s3->client_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
2894                         if (s->s3->client_opaque_prf_input == NULL)
2895                                 {
2896                                 SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
2897                                 return -1;
2898                                 }
2899                         s->s3->client_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2900                         }
2901
2902                 if (r == 2)
2903                         /* at callback's request, insist on receiving an appropriate server opaque PRF input */
2904                         s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2905         }
2906 #endif
2907
2908         return 1;
2909         }
2910
2911 int ssl_prepare_serverhello_tlsext(SSL *s)
2912         {
2913         return 1;
2914         }
2915
2916 static int ssl_check_clienthello_tlsext_early(SSL *s)
2917         {
2918         int ret=SSL_TLSEXT_ERR_NOACK;
2919         int al = SSL_AD_UNRECOGNIZED_NAME;
2920
2921 #ifndef OPENSSL_NO_EC
2922         /* The handling of the ECPointFormats extension is done elsewhere, namely in 
2923          * ssl3_choose_cipher in s3_lib.c.
2924          */
2925         /* The handling of the EllipticCurves extension is done elsewhere, namely in 
2926          * ssl3_choose_cipher in s3_lib.c.
2927          */
2928 #endif
2929
2930         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
2931                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
2932         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
2933                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
2934
2935 #ifdef TLSEXT_TYPE_opaque_prf_input
2936         {
2937                 /* This sort of belongs into ssl_prepare_serverhello_tlsext(),
2938                  * but we might be sending an alert in response to the client hello,
2939                  * so this has to happen here in
2940                  * ssl_check_clienthello_tlsext_early(). */
2941
2942                 int r = 1;
2943         
2944                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
2945                         {
2946                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
2947                         if (!r)
2948                                 {
2949                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2950                                 al = SSL_AD_INTERNAL_ERROR;
2951                                 goto err;
2952                                 }
2953                         }
2954
2955                 if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
2956                         OPENSSL_free(s->s3->server_opaque_prf_input);
2957                 s->s3->server_opaque_prf_input = NULL;
2958
2959                 if (s->tlsext_opaque_prf_input != NULL)
2960                         {
2961                         if (s->s3->client_opaque_prf_input != NULL &&
2962                                 s->s3->client_opaque_prf_input_len == s->tlsext_opaque_prf_input_len)
2963                                 {
2964                                 /* can only use this extension if we have a server opaque PRF input
2965                                  * of the same length as the client opaque PRF input! */
2966
2967                                 if (s->tlsext_opaque_prf_input_len == 0)
2968                                         s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2969                                 else
2970                                         s->s3->server_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
2971                                 if (s->s3->server_opaque_prf_input == NULL)
2972                                         {
2973                                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2974                                         al = SSL_AD_INTERNAL_ERROR;
2975                                         goto err;
2976                                         }
2977                                 s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2978                                 }
2979                         }
2980
2981                 if (r == 2 && s->s3->server_opaque_prf_input == NULL)
2982                         {
2983                         /* The callback wants to enforce use of the extension,
2984                          * but we can't do that with the client opaque PRF input;
2985                          * abort the handshake.
2986                          */
2987                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2988                         al = SSL_AD_HANDSHAKE_FAILURE;
2989                         }
2990         }
2991
2992  err:
2993 #endif
2994         switch (ret)
2995                 {
2996                 case SSL_TLSEXT_ERR_ALERT_FATAL:
2997                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2998                         return -1;
2999
3000                 case SSL_TLSEXT_ERR_ALERT_WARNING:
3001                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
3002                         return 1; 
3003                                         
3004                 case SSL_TLSEXT_ERR_NOACK:
3005                         s->servername_done=0;
3006                         default:
3007                 return 1;
3008                 }
3009         }
3010
3011 int tls1_set_server_sigalgs(SSL *s)
3012         {
3013         int al;
3014         size_t i;
3015         /* Clear any shared sigtnature algorithms */
3016         if (s->cert->shared_sigalgs)
3017                 {
3018                 OPENSSL_free(s->cert->shared_sigalgs);
3019                 s->cert->shared_sigalgs = NULL;
3020                 }
3021         /* Clear certificate digests and validity flags */
3022         for (i = 0; i < SSL_PKEY_NUM; i++)
3023                 {
3024                 s->cert->pkeys[i].digest = NULL;
3025                 s->cert->pkeys[i].valid_flags = 0;
3026                 }
3027
3028         /* If sigalgs received process it. */
3029         if (s->cert->peer_sigalgs)
3030                 {
3031                 if (!tls1_process_sigalgs(s))
3032                         {
3033                         SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS,
3034                                         ERR_R_MALLOC_FAILURE);
3035                         al = SSL_AD_INTERNAL_ERROR;
3036                         goto err;
3037                         }
3038                 /* Fatal error is no shared signature algorithms */
3039                 if (!s->cert->shared_sigalgs)
3040                         {
3041                         SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS,
3042                                         SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
3043                         al = SSL_AD_ILLEGAL_PARAMETER;
3044                         goto err;
3045                         }
3046                 }
3047         else
3048                 ssl_cert_set_default_md(s->cert);
3049         return 1;
3050         err:
3051         ssl3_send_alert(s, SSL3_AL_FATAL, al);
3052         return 0;
3053         }
3054
3055 int ssl_check_clienthello_tlsext_late(SSL *s)
3056         {
3057         int ret = SSL_TLSEXT_ERR_OK;
3058         int al;
3059
3060         /* If status request then ask callback what to do.
3061          * Note: this must be called after servername callbacks in case
3062          * the certificate has changed, and must be called after the cipher
3063          * has been chosen because this may influence which certificate is sent
3064          */
3065         if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb)
3066                 {
3067                 int r;
3068                 CERT_PKEY *certpkey;
3069                 certpkey = ssl_get_server_send_pkey(s);
3070                 /* If no certificate can't return certificate status */
3071                 if (certpkey == NULL)
3072                         {
3073                         s->tlsext_status_expected = 0;
3074                         return 1;
3075                         }
3076                 /* Set current certificate to one we will use so
3077                  * SSL_get_certificate et al can pick it up.
3078                  */
3079                 s->cert->key = certpkey;
3080                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
3081                 switch (r)
3082                         {
3083                         /* We don't want to send a status request response */
3084                         case SSL_TLSEXT_ERR_NOACK:
3085                                 s->tlsext_status_expected = 0;
3086                                 break;
3087                         /* status request response should be sent */
3088                         case SSL_TLSEXT_ERR_OK:
3089                                 if (s->tlsext_ocsp_resp)
3090                                         s->tlsext_status_expected = 1;
3091                                 else
3092                                         s->tlsext_status_expected = 0;
3093                                 break;
3094                         /* something bad happened */
3095                         case SSL_TLSEXT_ERR_ALERT_FATAL:
3096                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3097                                 al = SSL_AD_INTERNAL_ERROR;
3098                                 goto err;
3099                         }
3100                 }
3101         else
3102                 s->tlsext_status_expected = 0;
3103
3104  err:
3105         switch (ret)
3106                 {
3107                 case SSL_TLSEXT_ERR_ALERT_FATAL:
3108                         ssl3_send_alert(s, SSL3_AL_FATAL, al);
3109                         return -1;
3110
3111                 case SSL_TLSEXT_ERR_ALERT_WARNING:
3112                         ssl3_send_alert(s, SSL3_AL_WARNING, al);
3113                         return 1; 
3114
3115                 default:
3116                         return 1;
3117                 }
3118         }
3119
3120 int ssl_check_serverhello_tlsext(SSL *s)
3121         {
3122         int ret=SSL_TLSEXT_ERR_NOACK;
3123         int al = SSL_AD_UNRECOGNIZED_NAME;
3124
3125 #ifndef OPENSSL_NO_EC
3126         /* If we are client and using an elliptic curve cryptography cipher
3127          * suite, then if server returns an EC point formats lists extension
3128          * it must contain uncompressed.
3129          */
3130         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3131         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
3132         if ((s->tlsext_ecpointformatlist != NULL) && (s->tlsext_ecpointformatlist_length > 0) && 
3133             (s->session->tlsext_ecpointformatlist != NULL) && (s->session->tlsext_ecpointformatlist_length > 0) && 
3134             ((alg_k & (SSL_kECDHE|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA)))
3135                 {
3136                 /* we are using an ECC cipher */
3137                 size_t i;
3138                 unsigned char *list;
3139                 int found_uncompressed = 0;
3140                 list = s->session->tlsext_ecpointformatlist;
3141                 for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
3142                         {
3143                         if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed)
3144                                 {
3145                                 found_uncompressed = 1;
3146                                 break;
3147                                 }
3148                         }
3149                 if (!found_uncompressed)
3150                         {
3151                         SSLerr(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT,SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
3152                         return -1;
3153                         }
3154                 }
3155         ret = SSL_TLSEXT_ERR_OK;
3156 #endif /* OPENSSL_NO_EC */
3157
3158         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
3159                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
3160         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
3161                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
3162
3163 #ifdef TLSEXT_TYPE_opaque_prf_input
3164         if (s->s3->server_opaque_prf_input_len > 0)
3165                 {
3166                 /* This case may indicate that we, as a client, want to insist on using opaque PRF inputs.
3167                  * So first verify that we really have a value from the server too. */
3168
3169                 if (s->s3->server_opaque_prf_input == NULL)
3170                         {
3171                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3172                         al = SSL_AD_HANDSHAKE_FAILURE;
3173                         }
3174                 
3175                 /* Anytime the server *has* sent an opaque PRF input, we need to check
3176                  * that we have a client opaque PRF input of the same size. */
3177                 if (s->s3->client_opaque_prf_input == NULL ||
3178                     s->s3->client_opaque_prf_input_len != s->s3->server_opaque_prf_input_len)
3179                         {
3180                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3181                         al = SSL_AD_ILLEGAL_PARAMETER;
3182                         }
3183                 }
3184 #endif
3185
3186         /* If we've requested certificate status and we wont get one
3187          * tell the callback
3188          */
3189         if ((s->tlsext_status_type != -1) && !(s->tlsext_status_expected)
3190                         && s->ctx && s->ctx->tlsext_status_cb)
3191                 {
3192                 int r;
3193                 /* Set resp to NULL, resplen to -1 so callback knows
3194                  * there is no response.
3195                  */
3196                 if (s->tlsext_ocsp_resp)
3197                         {
3198                         OPENSSL_free(s->tlsext_ocsp_resp);
3199                         s->tlsext_ocsp_resp = NULL;
3200                         }
3201                 s->tlsext_ocsp_resplen = -1;
3202                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
3203                 if (r == 0)
3204                         {
3205                         al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
3206                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3207                         }
3208                 if (r < 0)
3209                         {
3210                         al = SSL_AD_INTERNAL_ERROR;
3211                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3212                         }
3213                 }
3214
3215         switch (ret)
3216                 {
3217                 case SSL_TLSEXT_ERR_ALERT_FATAL:
3218                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
3219                         return -1;
3220
3221                 case SSL_TLSEXT_ERR_ALERT_WARNING:
3222                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
3223                         return 1; 
3224                                         
3225                 case SSL_TLSEXT_ERR_NOACK:
3226                         s->servername_done=0;
3227                         default:
3228                 return 1;
3229                 }
3230         }
3231
3232 int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n) 
3233         {
3234         int al = -1;
3235         if (s->version < SSL3_VERSION)
3236                 return 1;
3237         if (ssl_scan_serverhello_tlsext(s, p, d, n, &al) <= 0) 
3238                 {
3239                 ssl3_send_alert(s,SSL3_AL_FATAL,al); 
3240                 return 0;
3241                 }
3242
3243         if (ssl_check_serverhello_tlsext(s) <= 0) 
3244                 {
3245                 SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT,SSL_R_SERVERHELLO_TLSEXT);
3246                 return 0;
3247                 }
3248         return 1;
3249 }
3250
3251 /* Since the server cache lookup is done early on in the processing of the
3252  * ClientHello, and other operations depend on the result, we need to handle
3253  * any TLS session ticket extension at the same time.
3254  *
3255  *   session_id: points at the session ID in the ClientHello. This code will
3256  *       read past the end of this in order to parse out the session ticket
3257  *       extension, if any.
3258  *   len: the length of the session ID.
3259  *   limit: a pointer to the first byte after the ClientHello.
3260  *   ret: (output) on return, if a ticket was decrypted, then this is set to
3261  *       point to the resulting session.
3262  *
3263  * If s->tls_session_secret_cb is set then we are expecting a pre-shared key
3264  * ciphersuite, in which case we have no use for session tickets and one will
3265  * never be decrypted, nor will s->tlsext_ticket_expected be set to 1.
3266  *
3267  * Returns:
3268  *   -1: fatal error, either from parsing or decrypting the ticket.
3269  *    0: no ticket was found (or was ignored, based on settings).
3270  *    1: a zero length extension was found, indicating that the client supports
3271  *       session tickets but doesn't currently have one to offer.
3272  *    2: either s->tls_session_secret_cb was set, or a ticket was offered but
3273  *       couldn't be decrypted because of a non-fatal error.
3274  *    3: a ticket was successfully decrypted and *ret was set.
3275  *
3276  * Side effects:
3277  *   Sets s->tlsext_ticket_expected to 1 if the server will have to issue
3278  *   a new session ticket to the client because the client indicated support
3279  *   (and s->tls_session_secret_cb is NULL) but the client either doesn't have
3280  *   a session ticket or we couldn't use the one it gave us, or if
3281  *   s->ctx->tlsext_ticket_key_cb asked to renew the client's ticket.
3282  *   Otherwise, s->tlsext_ticket_expected is set to 0.
3283  */
3284 int tls1_process_ticket(SSL *s, unsigned char *session_id, int len,
3285                         const unsigned char *limit, SSL_SESSION **ret)
3286         {
3287         /* Point after session ID in client hello */
3288         const unsigned char *p = session_id + len;
3289         unsigned short i;
3290
3291         *ret = NULL;
3292         s->tlsext_ticket_expected = 0;
3293
3294         /* If tickets disabled behave as if no ticket present
3295          * to permit stateful resumption.
3296          */
3297         if (!tls_use_ticket(s))
3298                 return 0;
3299         if ((s->version <= SSL3_VERSION) || !limit)
3300                 return 0;
3301         if (p >= limit)
3302                 return -1;
3303         /* Skip past DTLS cookie */
3304         if (SSL_IS_DTLS(s))
3305                 {
3306                 i = *(p++);
3307                 p+= i;
3308                 if (p >= limit)
3309                         return -1;
3310                 }
3311         /* Skip past cipher list */
3312         n2s(p, i);
3313         p+= i;
3314         if (p >= limit)
3315                 return -1;
3316         /* Skip past compression algorithm list */
3317         i = *(p++);
3318         p += i;
3319         if (p > limit)
3320                 return -1;
3321         /* Now at start of extensions */
3322         if ((p + 2) >= limit)
3323                 return 0;
3324         n2s(p, i);
3325         while ((p + 4) <= limit)
3326                 {
3327                 unsigned short type, size;
3328                 n2s(p, type);
3329                 n2s(p, size);
3330                 if (p + size > limit)
3331                         return 0;
3332                 if (type == TLSEXT_TYPE_session_ticket)
3333                         {
3334                         int r;
3335                         if (size == 0)
3336                                 {
3337                                 /* The client will accept a ticket but doesn't
3338                                  * currently have one. */
3339                                 s->tlsext_ticket_expected = 1;
3340                                 return 1;
3341                                 }
3342                         if (s->tls_session_secret_cb)
3343                                 {
3344                                 /* Indicate that the ticket couldn't be
3345                                  * decrypted rather than generating the session
3346                                  * from ticket now, trigger abbreviated
3347                                  * handshake based on external mechanism to
3348                                  * calculate the master secret later. */
3349                                 return 2;
3350                                 }
3351                         r = tls_decrypt_ticket(s, p, size, session_id, len, ret);
3352                         switch (r)
3353                                 {
3354                                 case 2: /* ticket couldn't be decrypted */
3355                                         s->tlsext_ticket_expected = 1;
3356                                         return 2;
3357                                 case 3: /* ticket was decrypted */
3358                                         return r;
3359                                 case 4: /* ticket decrypted but need to renew */
3360                                         s->tlsext_ticket_expected = 1;
3361                                         return 3;
3362                                 default: /* fatal error */
3363                                         return -1;
3364                                 }
3365                         }
3366                 p += size;
3367                 }
3368         return 0;
3369         }
3370
3371 /* tls_decrypt_ticket attempts to decrypt a session ticket.
3372  *
3373  *   etick: points to the body of the session ticket extension.
3374  *   eticklen: the length of the session tickets extenion.
3375  *   sess_id: points at the session ID.
3376  *   sesslen: the length of the session ID.
3377  *   psess: (output) on return, if a ticket was decrypted, then this is set to
3378  *       point to the resulting session.
3379  *
3380  * Returns:
3381  *   -1: fatal error, either from parsing or decrypting the ticket.
3382  *    2: the ticket couldn't be decrypted.
3383  *    3: a ticket was successfully decrypted and *psess was set.
3384  *    4: same as 3, but the ticket needs to be renewed.
3385  */
3386 static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen,
3387                                 const unsigned char *sess_id, int sesslen,
3388                                 SSL_SESSION **psess)
3389         {
3390         SSL_SESSION *sess;
3391         unsigned char *sdec;
3392         const unsigned char *p;
3393         int slen, mlen, renew_ticket = 0;
3394         unsigned char tick_hmac[EVP_MAX_MD_SIZE];
3395         HMAC_CTX hctx;
3396         EVP_CIPHER_CTX ctx;
3397         SSL_CTX *tctx = s->initial_ctx;
3398         /* Need at least keyname + iv + some encrypted data */
3399         if (eticklen < 48)
3400                 return 2;
3401         /* Initialize session ticket encryption and HMAC contexts */
3402         HMAC_CTX_init(&hctx);
3403         EVP_CIPHER_CTX_init(&ctx);
3404         if (tctx->tlsext_ticket_key_cb)
3405                 {
3406                 unsigned char *nctick = (unsigned char *)etick;
3407                 int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
3408                                                         &ctx, &hctx, 0);
3409                 if (rv < 0)
3410                         return -1;
3411                 if (rv == 0)
3412                         return 2;
3413                 if (rv == 2)
3414                         renew_ticket = 1;
3415                 }
3416         else
3417                 {
3418                 /* Check key name matches */
3419                 if (memcmp(etick, tctx->tlsext_tick_key_name, 16))
3420                         return 2;
3421                 HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3422                                         tlsext_tick_md(), NULL);
3423                 EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3424                                 tctx->tlsext_tick_aes_key, etick + 16);
3425                 }
3426         /* Attempt to process session ticket, first conduct sanity and
3427          * integrity checks on ticket.
3428          */
3429         mlen = HMAC_size(&hctx);
3430         if (mlen < 0)
3431                 {
3432                 EVP_CIPHER_CTX_cleanup(&ctx);
3433                 return -1;
3434                 }
3435         eticklen -= mlen;
3436         /* Check HMAC of encrypted ticket */
3437         HMAC_Update(&hctx, etick, eticklen);
3438         HMAC_Final(&hctx, tick_hmac, NULL);
3439         HMAC_CTX_cleanup(&hctx);
3440         if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen))
3441                 {
3442                 EVP_CIPHER_CTX_cleanup(&ctx);
3443                 return 2;
3444                 }
3445         /* Attempt to decrypt session data */
3446         /* Move p after IV to start of encrypted ticket, update length */
3447         p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx);
3448         eticklen -= 16 + EVP_CIPHER_CTX_iv_length(&ctx);
3449         sdec = OPENSSL_malloc(eticklen);
3450         if (!sdec)
3451                 {
3452                 EVP_CIPHER_CTX_cleanup(&ctx);
3453                 return -1;
3454                 }
3455         EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen);
3456         if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0)
3457                 {
3458                 EVP_CIPHER_CTX_cleanup(&ctx);
3459                 OPENSSL_free(sdec);
3460                 return 2;
3461                 }
3462         slen += mlen;
3463         EVP_CIPHER_CTX_cleanup(&ctx);
3464         p = sdec;
3465
3466         sess = d2i_SSL_SESSION(NULL, &p, slen);
3467         OPENSSL_free(sdec);
3468         if (sess)
3469                 {
3470                 /* The session ID, if non-empty, is used by some clients to
3471                  * detect that the ticket has been accepted. So we copy it to
3472                  * the session structure. If it is empty set length to zero
3473                  * as required by standard.
3474                  */
3475                 if (sesslen)
3476                         memcpy(sess->session_id, sess_id, sesslen);
3477                 sess->session_id_length = sesslen;
3478                 *psess = sess;
3479                 if (renew_ticket)
3480                         return 4;
3481                 else
3482                         return 3;
3483                 }
3484         ERR_clear_error();
3485         /* For session parse failure, indicate that we need to send a new
3486          * ticket. */
3487         return 2;
3488         }
3489
3490 /* Tables to translate from NIDs to TLS v1.2 ids */
3491
3492 typedef struct 
3493         {
3494         int nid;
3495         int id;
3496         } tls12_lookup;
3497
3498 static tls12_lookup tls12_md[] = {
3499         {NID_md5, TLSEXT_hash_md5},
3500         {NID_sha1, TLSEXT_hash_sha1},
3501         {NID_sha224, TLSEXT_hash_sha224},
3502         {NID_sha256, TLSEXT_hash_sha256},
3503         {NID_sha384, TLSEXT_hash_sha384},
3504         {NID_sha512, TLSEXT_hash_sha512}
3505 };
3506
3507 static tls12_lookup tls12_sig[] = {
3508         {EVP_PKEY_RSA, TLSEXT_signature_rsa},
3509         {EVP_PKEY_DSA, TLSEXT_signature_dsa},
3510         {EVP_PKEY_EC, TLSEXT_signature_ecdsa}
3511 };
3512
3513 static int tls12_find_id(int nid, tls12_lookup *table, size_t tlen)
3514         {
3515         size_t i;
3516         for (i = 0; i < tlen; i++)
3517                 {
3518                 if (table[i].nid == nid)
3519                         return table[i].id;
3520                 }
3521         return -1;
3522         }
3523
3524 static int tls12_find_nid(int id, tls12_lookup *table, size_t tlen)
3525         {
3526         size_t i;
3527         for (i = 0; i < tlen; i++)
3528                 {
3529                 if ((table[i].id) == id)
3530                         return table[i].nid;
3531                 }
3532         return NID_undef;
3533         }
3534
3535 int tls12_get_sigandhash(unsigned char *p, const EVP_PKEY *pk, const EVP_MD *md)
3536         {
3537         int sig_id, md_id;
3538         if (!md)
3539                 return 0;
3540         md_id = tls12_find_id(EVP_MD_type(md), tls12_md,
3541                                 sizeof(tls12_md)/sizeof(tls12_lookup));
3542         if (md_id == -1)
3543                 return 0;
3544         sig_id = tls12_get_sigid(pk);
3545         if (sig_id == -1)
3546                 return 0;
3547         p[0] = (unsigned char)md_id;
3548         p[1] = (unsigned char)sig_id;
3549         return 1;
3550         }
3551
3552 int tls12_get_sigid(const EVP_PKEY *pk)
3553         {
3554         return tls12_find_id(pk->type, tls12_sig,
3555                                 sizeof(tls12_sig)/sizeof(tls12_lookup));
3556         }
3557
3558 typedef struct 
3559         {
3560         int nid;
3561         int secbits;
3562         const EVP_MD *(*mfunc)(void);
3563         } tls12_hash_info;
3564
3565 static const tls12_hash_info tls12_md_info[] = {
3566 #ifdef OPENSSL_NO_MD5
3567         {NID_md5, 64, 0},
3568 #else
3569         {NID_md5, 64, EVP_md5},
3570 #endif
3571 #ifdef OPENSSL_NO_SHA
3572         {NID_sha1, 80, 0},
3573 #else
3574         {NID_sha1, 80, EVP_sha1},
3575 #endif