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