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