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