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