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