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