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