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