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