Tidy up EC parameter check code: instead of accessing internal structures
[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 #endif
127
128 SSL3_ENC_METHOD TLSv1_enc_data={
129         tls1_enc,
130         tls1_mac,
131         tls1_setup_key_block,
132         tls1_generate_master_secret,
133         tls1_change_cipher_state,
134         tls1_final_finish_mac,
135         TLS1_FINISH_MAC_LENGTH,
136         tls1_cert_verify_mac,
137         TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
138         TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
139         tls1_alert_code,
140         tls1_export_keying_material,
141         };
142
143 long tls1_default_timeout(void)
144         {
145         /* 2 hours, the 24 hours mentioned in the TLSv1 spec
146          * is way too long for http, the cache would over fill */
147         return(60*60*2);
148         }
149
150 int tls1_new(SSL *s)
151         {
152         if (!ssl3_new(s)) return(0);
153         s->method->ssl_clear(s);
154         return(1);
155         }
156
157 void tls1_free(SSL *s)
158         {
159 #ifndef OPENSSL_NO_TLSEXT
160         if (s->tlsext_session_ticket)
161                 {
162                 OPENSSL_free(s->tlsext_session_ticket);
163                 }
164 #endif /* OPENSSL_NO_TLSEXT */
165         ssl3_free(s);
166         }
167
168 void tls1_clear(SSL *s)
169         {
170         ssl3_clear(s);
171         s->version = s->method->version;
172         }
173
174 #ifndef OPENSSL_NO_EC
175
176 static int nid_list[] =
177         {
178                 NID_sect163k1, /* sect163k1 (1) */
179                 NID_sect163r1, /* sect163r1 (2) */
180                 NID_sect163r2, /* sect163r2 (3) */
181                 NID_sect193r1, /* sect193r1 (4) */ 
182                 NID_sect193r2, /* sect193r2 (5) */ 
183                 NID_sect233k1, /* sect233k1 (6) */
184                 NID_sect233r1, /* sect233r1 (7) */ 
185                 NID_sect239k1, /* sect239k1 (8) */ 
186                 NID_sect283k1, /* sect283k1 (9) */
187                 NID_sect283r1, /* sect283r1 (10) */ 
188                 NID_sect409k1, /* sect409k1 (11) */ 
189                 NID_sect409r1, /* sect409r1 (12) */
190                 NID_sect571k1, /* sect571k1 (13) */ 
191                 NID_sect571r1, /* sect571r1 (14) */ 
192                 NID_secp160k1, /* secp160k1 (15) */
193                 NID_secp160r1, /* secp160r1 (16) */ 
194                 NID_secp160r2, /* secp160r2 (17) */ 
195                 NID_secp192k1, /* secp192k1 (18) */
196                 NID_X9_62_prime192v1, /* secp192r1 (19) */ 
197                 NID_secp224k1, /* secp224k1 (20) */ 
198                 NID_secp224r1, /* secp224r1 (21) */
199                 NID_secp256k1, /* secp256k1 (22) */ 
200                 NID_X9_62_prime256v1, /* secp256r1 (23) */ 
201                 NID_secp384r1, /* secp384r1 (24) */
202                 NID_secp521r1  /* secp521r1 (25) */     
203         };
204
205
206 static const unsigned char ecformats_default[] = 
207         {
208         TLSEXT_ECPOINTFORMAT_uncompressed,
209         TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime,
210         TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2
211         };
212
213 static const unsigned char eccurves_default[] =
214         {
215                 0,14, /* sect571r1 (14) */ 
216                 0,13, /* sect571k1 (13) */ 
217                 0,25, /* secp521r1 (25) */      
218                 0,11, /* sect409k1 (11) */ 
219                 0,12, /* sect409r1 (12) */
220                 0,24, /* secp384r1 (24) */
221                 0,9,  /* sect283k1 (9) */
222                 0,10, /* sect283r1 (10) */ 
223                 0,22, /* secp256k1 (22) */ 
224                 0,23, /* secp256r1 (23) */ 
225                 0,8,  /* sect239k1 (8) */ 
226                 0,6,  /* sect233k1 (6) */
227                 0,7,  /* sect233r1 (7) */ 
228                 0,20, /* secp224k1 (20) */ 
229                 0,21, /* secp224r1 (21) */
230                 0,4,  /* sect193r1 (4) */ 
231                 0,5,  /* sect193r2 (5) */ 
232                 0,18, /* secp192k1 (18) */
233                 0,19, /* secp192r1 (19) */ 
234                 0,1,  /* sect163k1 (1) */
235                 0,2,  /* sect163r1 (2) */
236                 0,3,  /* sect163r2 (3) */
237                 0,15, /* secp160k1 (15) */
238                 0,16, /* secp160r1 (16) */ 
239                 0,17, /* secp160r2 (17) */ 
240         };
241
242 int tls1_ec_curve_id2nid(int curve_id)
243         {
244         /* ECC curves from draft-ietf-tls-ecc-12.txt (Oct. 17, 2005) */
245         if ((curve_id < 1) || ((unsigned int)curve_id >
246                                 sizeof(nid_list)/sizeof(nid_list[0])))
247                 return 0;
248         return nid_list[curve_id-1];
249         }
250
251 int tls1_ec_nid2curve_id(int nid)
252         {
253         /* ECC curves from draft-ietf-tls-ecc-12.txt (Oct. 17, 2005) */
254         switch (nid)
255                 {
256         case NID_sect163k1: /* sect163k1 (1) */
257                 return 1;
258         case NID_sect163r1: /* sect163r1 (2) */
259                 return 2;
260         case NID_sect163r2: /* sect163r2 (3) */
261                 return 3;
262         case NID_sect193r1: /* sect193r1 (4) */ 
263                 return 4;
264         case NID_sect193r2: /* sect193r2 (5) */ 
265                 return 5;
266         case NID_sect233k1: /* sect233k1 (6) */
267                 return 6;
268         case NID_sect233r1: /* sect233r1 (7) */ 
269                 return 7;
270         case NID_sect239k1: /* sect239k1 (8) */ 
271                 return 8;
272         case NID_sect283k1: /* sect283k1 (9) */
273                 return 9;
274         case NID_sect283r1: /* sect283r1 (10) */ 
275                 return 10;
276         case NID_sect409k1: /* sect409k1 (11) */ 
277                 return 11;
278         case NID_sect409r1: /* sect409r1 (12) */
279                 return 12;
280         case NID_sect571k1: /* sect571k1 (13) */ 
281                 return 13;
282         case NID_sect571r1: /* sect571r1 (14) */ 
283                 return 14;
284         case NID_secp160k1: /* secp160k1 (15) */
285                 return 15;
286         case NID_secp160r1: /* secp160r1 (16) */ 
287                 return 16;
288         case NID_secp160r2: /* secp160r2 (17) */ 
289                 return 17;
290         case NID_secp192k1: /* secp192k1 (18) */
291                 return 18;
292         case NID_X9_62_prime192v1: /* secp192r1 (19) */ 
293                 return 19;
294         case NID_secp224k1: /* secp224k1 (20) */ 
295                 return 20;
296         case NID_secp224r1: /* secp224r1 (21) */
297                 return 21;
298         case NID_secp256k1: /* secp256k1 (22) */ 
299                 return 22;
300         case NID_X9_62_prime256v1: /* secp256r1 (23) */ 
301                 return 23;
302         case NID_secp384r1: /* secp384r1 (24) */
303                 return 24;
304         case NID_secp521r1:  /* secp521r1 (25) */       
305                 return 25;
306         default:
307                 return 0;
308                 }
309         }
310 /* Get curves list, if "sess" is set return client curves otherwise
311  * preferred list
312  */
313 static void tls1_get_curvelist(SSL *s, int sess,
314                                         const unsigned char **pcurves,
315                                         size_t *pcurveslen)
316         {
317         if (sess)
318                 {
319                 *pcurves = s->session->tlsext_ellipticcurvelist;
320                 *pcurveslen = s->session->tlsext_ellipticcurvelist_length;
321                 }
322         else
323                 {
324                 *pcurves = s->tlsext_ellipticcurvelist;
325                 *pcurveslen = s->tlsext_ellipticcurvelist_length;
326                 }
327         /* If not set use default: for now static structure */
328         if (!*pcurves)
329                 {
330                 *pcurves = eccurves_default;
331                 *pcurveslen = sizeof(eccurves_default);
332                 }
333         }
334
335 /* Return any common values from two lists. One list is used as a 
336  * preference list where we return the most preferred match.
337  */
338 int tls1_shared_list(SSL *s,
339                         const unsigned char *l1, size_t l1len,
340                         const unsigned char *l2, size_t l2len,
341                         int nmatch)
342         {
343         const unsigned char *pref, *supp;
344         size_t preflen, supplen, i, j;
345         int k;
346         l1len /= 2;
347         l2len /= 2;
348         if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE)
349                 {
350                 pref = l1;
351                 preflen = l1len;
352                 supp = l2;
353                 supplen = l2len;
354                 }
355         else
356                 {
357                 supp = l1;
358                 supplen = l1len;
359                 pref = l2;
360                 preflen = l2len;
361                 }
362         k = 0;
363         for (i = 0; i < preflen; i++, pref+=2)
364                 {
365                 const unsigned char *tsupp = supp;
366                 for (j = 0; j < supplen; j++, tsupp+=2)
367                         {
368                         if (pref[0] == tsupp[0] && pref[1] == tsupp[1])
369                                 {
370                                 if (nmatch == k)
371                                         return (pref[0] << 8) | pref[1];
372                                 k++;
373                                 }
374                         }
375                 }
376         if (nmatch == -1 && k > 0)
377                 return k;
378         return -1;
379         }
380
381 int tls1_shared_curve(SSL *s, int nmatch)
382         {
383         const unsigned char *l1, *l2;
384         size_t l1len, l2len;
385         int id;
386         /* Can't do anything on client side */
387         if (s->server == 0)
388                 return -1;
389         /* Get supported curves */
390         tls1_get_curvelist(s, 0, &l1, &l1len);
391         tls1_get_curvelist(s, 1, &l2, &l2len);
392
393         id = tls1_shared_list(s, l1, l1len, l2, l2len, nmatch);
394         if (nmatch == -1)
395                 return id;
396         return tls1_ec_curve_id2nid(id);
397         }
398
399 int tls1_set_curves(unsigned char **pext, size_t *pextlen,
400                         int *curves, size_t ncurves)
401         {
402         unsigned char *clist, *p;
403         size_t i;
404         /* Bitmap of curves included to detect duplicates: only works
405          * while curve ids < 32 
406          */
407         unsigned long dup_list = 0;
408         clist = OPENSSL_malloc(ncurves * 2);
409         if (!clist)
410                 return 0;
411         for (i = 0, p = clist; i < ncurves; i++)
412                 {
413                 unsigned long idmask;
414                 int id;
415                 id = tls1_ec_nid2curve_id(curves[i]);
416                 idmask = 1L << id;
417                 if (!id || (dup_list & idmask))
418                         {
419                         OPENSSL_free(clist);
420                         return 0;
421                         }
422                 dup_list |= idmask;
423                 s2n(id, p);
424                 }
425         if (*pext)
426                 OPENSSL_free(*pext);
427         *pext = clist;
428         *pextlen = ncurves * 2;
429         return 1;
430         }
431
432 #define MAX_CURVELIST   25
433
434 typedef struct
435         {
436         size_t nidcnt;
437         int nid_arr[MAX_CURVELIST];
438         } nid_cb_st;
439
440 static int nid_cb(const char *elem, int len, void *arg)
441         {
442         nid_cb_st *narg = arg;
443         size_t i;
444         int nid;
445         char etmp[20];
446         if (narg->nidcnt == MAX_CURVELIST)
447                 return 0;
448         if (len > (int)(sizeof(etmp) - 1))
449                 return 0;
450         memcpy(etmp, elem, len);
451         etmp[len] = 0;
452         nid = EC_curve_nist2nid(etmp);
453         if (nid == NID_undef)
454                 nid = OBJ_sn2nid(etmp);
455         if (nid == NID_undef)
456                 nid = OBJ_ln2nid(etmp);
457         if (nid == NID_undef)
458                 return 0;
459         for (i = 0; i < narg->nidcnt; i++)
460                 if (narg->nid_arr[i] == nid)
461                         return 0;
462         narg->nid_arr[narg->nidcnt++] = nid;
463         return 1;
464         }
465 /* Set curves based on a colon separate list */
466 int tls1_set_curves_list(unsigned char **pext, size_t *pextlen, 
467                                 const char *str)
468         {
469         nid_cb_st ncb;
470         ncb.nidcnt = 0;
471         if (!CONF_parse_list(str, ':', 1, nid_cb, &ncb))
472                 return 0;
473         return tls1_set_curves(pext, pextlen, ncb.nid_arr, ncb.nidcnt);
474         }
475 /* For an EC key set TLS id and required compression based on parameters */
476 static int tls1_set_ec_id(unsigned char *curve_id, unsigned char *comp_id,
477                                 EC_KEY *ec)
478         {
479         int is_prime, id;
480         const EC_GROUP *grp;
481         const EC_POINT *pt;
482         const EC_METHOD *meth;
483         if (!ec)
484                 return 0;
485         /* Determine if it is a prime field */
486         grp = EC_KEY_get0_group(ec);
487         pt = EC_KEY_get0_public_key(ec);
488         if (!grp || !pt)
489                 return 0;
490         meth = EC_GROUP_method_of(grp);
491         if (!meth)
492                 return 0;
493         if (EC_METHOD_get_field_type(meth) == NID_X9_62_prime_field)
494                 is_prime = 1;
495         else
496                 is_prime = 0;
497         /* Determine curve ID */
498         id = EC_GROUP_get_curve_name(grp);
499         id = tls1_ec_nid2curve_id(id);
500         /* If we have an ID set it, otherwise set arbitrary explicit curve */
501         if (id)
502                 {
503                 curve_id[0] = 0;
504                 curve_id[1] = (unsigned char)id;
505                 }
506         else
507                 {
508                 curve_id[0] = 0xff;
509                 if (is_prime)
510                         curve_id[1] = 0x01;
511                 else
512                         curve_id[1] = 0x02;
513                 }
514         if (comp_id)
515                 {
516                 if (EC_KEY_get_conv_form(ec) == POINT_CONVERSION_COMPRESSED)
517                         {
518                         if (is_prime)
519                                 *comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
520                         else
521                                 *comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
522                         }
523                 else
524                         *comp_id = TLSEXT_ECPOINTFORMAT_uncompressed;
525                 }
526         return 1;
527         }
528 /* Check an EC key is compatible with extensions */
529 static int tls1_check_ec_key(SSL *s,
530                         unsigned char *curve_id, unsigned char *comp_id)
531         {
532         const unsigned char *p;
533         size_t plen, i;
534         /* If point formats extension present check it, otherwise everything
535          * is supported (see RFC4492).
536          */
537         if (comp_id && s->session->tlsext_ecpointformatlist)
538                 {
539                 p = s->session->tlsext_ecpointformatlist;
540                 plen = s->session->tlsext_ecpointformatlist_length;
541                 for (i = 0; i < plen; i++, p++)
542                         {
543                         if (*comp_id == *p)
544                                 break;
545                         }
546                 if (i == plen)
547                         return 0;
548                 }
549         /* If curve list present check it, otherwise everything is
550          * supported.
551          */
552         if (s->session->tlsext_ellipticcurvelist)
553                 {
554                 p = s->session->tlsext_ellipticcurvelist;
555                 plen = s->session->tlsext_ellipticcurvelist_length;
556                 for (i = 0; i < plen; i+=2, p+=2)
557                         {
558                         if (p[0] == curve_id[0] && p[1] == curve_id[1])
559                                 return 1;
560                         }
561                 return 0;
562                 }
563         return 1;
564         }
565 /* Check EC server key is compatible with client extensions */
566 int tls1_check_ec_server_key(SSL *s)
567         {
568         int rv;
569         CERT_PKEY *cpk = s->cert->pkeys + SSL_PKEY_ECC;
570         EVP_PKEY *pkey;
571         unsigned char comp_id, curve_id[2];
572         if (!cpk->x509 || !cpk->privatekey)
573                 return 0;
574         pkey = X509_get_pubkey(cpk->x509);
575         if (!pkey)
576                 return 0;
577         rv = tls1_set_ec_id(curve_id, &comp_id, pkey->pkey.ec);
578         EVP_PKEY_free(pkey);
579         if (!rv)
580                 return 0;
581         return tls1_check_ec_key(s, curve_id, &comp_id);
582         }
583 /* Check EC temporary key is compatible with client extensions */
584 int tls1_check_ec_tmp_key(SSL *s)
585         {
586         unsigned char curve_id[2];
587         EC_KEY *ec = s->cert->ecdh_tmp;
588         if (!ec)
589                 {
590                 if (s->cert->ecdh_tmp_cb)
591                         return 1;
592                 else
593                         return 0;
594                 }
595         if (!tls1_set_ec_id(curve_id, NULL, ec))
596                 return 1;
597         return tls1_check_ec_key(s, curve_id, NULL);
598         }
599
600 #endif /* OPENSSL_NO_EC */
601
602 #ifndef OPENSSL_NO_TLSEXT
603
604 /* List of supported signature algorithms and hashes. Should make this
605  * customisable at some point, for now include everything we support.
606  */
607
608 #ifdef OPENSSL_NO_RSA
609 #define tlsext_sigalg_rsa(md) /* */
610 #else
611 #define tlsext_sigalg_rsa(md) md, TLSEXT_signature_rsa,
612 #endif
613
614 #ifdef OPENSSL_NO_DSA
615 #define tlsext_sigalg_dsa(md) /* */
616 #else
617 #define tlsext_sigalg_dsa(md) md, TLSEXT_signature_dsa,
618 #endif
619
620 #ifdef OPENSSL_NO_ECDSA
621 #define tlsext_sigalg_ecdsa(md) /* */
622 #else
623 #define tlsext_sigalg_ecdsa(md) md, TLSEXT_signature_ecdsa,
624 #endif
625
626 #define tlsext_sigalg(md) \
627                 tlsext_sigalg_rsa(md) \
628                 tlsext_sigalg_dsa(md) \
629                 tlsext_sigalg_ecdsa(md)
630
631 static unsigned char tls12_sigalgs[] = {
632 #ifndef OPENSSL_NO_SHA512
633         tlsext_sigalg(TLSEXT_hash_sha512)
634         tlsext_sigalg(TLSEXT_hash_sha384)
635 #endif
636 #ifndef OPENSSL_NO_SHA256
637         tlsext_sigalg(TLSEXT_hash_sha256)
638         tlsext_sigalg(TLSEXT_hash_sha224)
639 #endif
640 #ifndef OPENSSL_NO_SHA
641         tlsext_sigalg(TLSEXT_hash_sha1)
642 #endif
643 #ifndef OPENSSL_NO_MD5
644         tlsext_sigalg_rsa(TLSEXT_hash_md5)
645 #endif
646 };
647
648 int tls12_get_req_sig_algs(SSL *s, unsigned char *p)
649         {
650         size_t slen = sizeof(tls12_sigalgs);
651 #ifdef OPENSSL_FIPS
652         /* If FIPS mode don't include MD5 which is last */
653         if (FIPS_mode())
654                 slen -= 2;
655 #endif
656         if (p)
657                 memcpy(p, tls12_sigalgs, slen);
658         return (int)slen;
659         }
660
661 unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *p, unsigned char *limit)
662         {
663         int extdatalen=0;
664         unsigned char *ret = p;
665 #ifndef OPENSSL_NO_EC
666         /* See if we support any ECC ciphersuites */
667         int using_ecc = 0;
668         if (s->version != DTLS1_VERSION && s->version >= TLS1_VERSION)
669                 {
670                 int i;
671                 unsigned long alg_k, alg_a;
672                 STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(s);
673
674                 for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++)
675                         {
676                         SSL_CIPHER *c = sk_SSL_CIPHER_value(cipher_stack, i);
677
678                         alg_k = c->algorithm_mkey;
679                         alg_a = c->algorithm_auth;
680                         if ((alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)
681                                 || (alg_a & SSL_aECDSA)))
682                                 {
683                                 using_ecc = 1;
684                                 break;
685                                 }
686                         }
687                 }
688 #endif
689
690         /* don't add extensions for SSLv3 unless doing secure renegotiation */
691         if (s->client_version == SSL3_VERSION
692                                         && !s->s3->send_connection_binding)
693                 return p;
694
695         ret+=2;
696
697         if (ret>=limit) return NULL; /* this really never occurs, but ... */
698
699         if (s->tlsext_hostname != NULL)
700                 { 
701                 /* Add TLS extension servername to the Client Hello message */
702                 unsigned long size_str;
703                 long lenmax; 
704
705                 /* check for enough space.
706                    4 for the servername type and entension length
707                    2 for servernamelist length
708                    1 for the hostname type
709                    2 for hostname length
710                    + hostname length 
711                 */
712                    
713                 if ((lenmax = limit - ret - 9) < 0 
714                     || (size_str = strlen(s->tlsext_hostname)) > (unsigned long)lenmax) 
715                         return NULL;
716                         
717                 /* extension type and length */
718                 s2n(TLSEXT_TYPE_server_name,ret); 
719                 s2n(size_str+5,ret);
720                 
721                 /* length of servername list */
722                 s2n(size_str+3,ret);
723         
724                 /* hostname type, length and hostname */
725                 *(ret++) = (unsigned char) TLSEXT_NAMETYPE_host_name;
726                 s2n(size_str,ret);
727                 memcpy(ret, s->tlsext_hostname, size_str);
728                 ret+=size_str;
729                 }
730
731         /* Add RI if renegotiating */
732         if (s->renegotiate)
733           {
734           int el;
735           
736           if(!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0))
737               {
738               SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
739               return NULL;
740               }
741
742           if((limit - p - 4 - el) < 0) return NULL;
743           
744           s2n(TLSEXT_TYPE_renegotiate,ret);
745           s2n(el,ret);
746
747           if(!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el))
748               {
749               SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
750               return NULL;
751               }
752
753           ret += el;
754         }
755
756 #ifndef OPENSSL_NO_SRP
757         /* Add SRP username if there is one */
758         if (s->srp_ctx.login != NULL)
759                 { /* Add TLS extension SRP username to the Client Hello message */
760
761                 int login_len = strlen(s->srp_ctx.login);       
762                 if (login_len > 255 || login_len == 0)
763                         {
764                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
765                         return NULL;
766                         } 
767
768                 /* check for enough space.
769                    4 for the srp type type and entension length
770                    1 for the srp user identity
771                    + srp user identity length 
772                 */
773                 if ((limit - ret - 5 - login_len) < 0) return NULL; 
774
775                 /* fill in the extension */
776                 s2n(TLSEXT_TYPE_srp,ret);
777                 s2n(login_len+1,ret);
778                 (*ret++) = (unsigned char) login_len;
779                 memcpy(ret, s->srp_ctx.login, login_len);
780                 ret+=login_len;
781                 }
782 #endif
783
784 #ifndef OPENSSL_NO_EC
785         if (using_ecc)
786                 {
787                 /* Add TLS extension ECPointFormats to the ClientHello message */
788                 long lenmax; 
789                 const unsigned char *plist;
790                 size_t plistlen;
791                 /* If we have a custom point format list use it otherwise
792                  * use default */
793                 plist = s->tlsext_ecpointformatlist;
794                 if (plist)
795                         plistlen = s->tlsext_ecpointformatlist_length;
796                 else
797                         {
798                         plist = ecformats_default;
799                         plistlen = sizeof(ecformats_default);
800                         }
801
802                 if ((lenmax = limit - ret - 5) < 0) return NULL; 
803                 if (plistlen > (size_t)lenmax) return NULL;
804                 if (plistlen > 255)
805                         {
806                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
807                         return NULL;
808                         }
809                 
810                 s2n(TLSEXT_TYPE_ec_point_formats,ret);
811                 s2n(plistlen + 1,ret);
812                 *(ret++) = (unsigned char)plistlen ;
813                 memcpy(ret, plist, plistlen);
814                 ret+=plistlen;
815
816                 /* Add TLS extension EllipticCurves to the ClientHello message */
817                 plist = s->tlsext_ellipticcurvelist;
818                 tls1_get_curvelist(s, 0, &plist, &plistlen);
819
820                 if ((lenmax = limit - ret - 6) < 0) return NULL; 
821                 if (plistlen > (size_t)lenmax) return NULL;
822                 if (plistlen > 65532)
823                         {
824                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
825                         return NULL;
826                         }
827                 
828                 s2n(TLSEXT_TYPE_elliptic_curves,ret);
829                 s2n(plistlen + 2, ret);
830
831                 /* NB: draft-ietf-tls-ecc-12.txt uses a one-byte prefix for
832                  * elliptic_curve_list, but the examples use two bytes.
833                  * http://www1.ietf.org/mail-archive/web/tls/current/msg00538.html
834                  * resolves this to two bytes.
835                  */
836                 s2n(plistlen, ret);
837                 memcpy(ret, plist, plistlen);
838                 ret+=plistlen;
839                 }
840 #endif /* OPENSSL_NO_EC */
841
842         if (!(SSL_get_options(s) & SSL_OP_NO_TICKET))
843                 {
844                 int ticklen;
845                 if (!s->new_session && s->session && s->session->tlsext_tick)
846                         ticklen = s->session->tlsext_ticklen;
847                 else if (s->session && s->tlsext_session_ticket &&
848                          s->tlsext_session_ticket->data)
849                         {
850                         ticklen = s->tlsext_session_ticket->length;
851                         s->session->tlsext_tick = OPENSSL_malloc(ticklen);
852                         if (!s->session->tlsext_tick)
853                                 return NULL;
854                         memcpy(s->session->tlsext_tick,
855                                s->tlsext_session_ticket->data,
856                                ticklen);
857                         s->session->tlsext_ticklen = ticklen;
858                         }
859                 else
860                         ticklen = 0;
861                 if (ticklen == 0 && s->tlsext_session_ticket &&
862                     s->tlsext_session_ticket->data == NULL)
863                         goto skip_ext;
864                 /* Check for enough room 2 for extension type, 2 for len
865                  * rest for ticket
866                  */
867                 if ((long)(limit - ret - 4 - ticklen) < 0) return NULL;
868                 s2n(TLSEXT_TYPE_session_ticket,ret); 
869                 s2n(ticklen,ret);
870                 if (ticklen)
871                         {
872                         memcpy(ret, s->session->tlsext_tick, ticklen);
873                         ret += ticklen;
874                         }
875                 }
876                 skip_ext:
877
878         if (TLS1_get_client_version(s) >= TLS1_2_VERSION)
879                 {
880                 if ((size_t)(limit - ret) < sizeof(tls12_sigalgs) + 6)
881                         return NULL; 
882                 s2n(TLSEXT_TYPE_signature_algorithms,ret);
883                 s2n(sizeof(tls12_sigalgs) + 2, ret);
884                 s2n(sizeof(tls12_sigalgs), ret);
885                 memcpy(ret, tls12_sigalgs, sizeof(tls12_sigalgs));
886                 ret += sizeof(tls12_sigalgs);
887                 }
888
889 #ifdef TLSEXT_TYPE_opaque_prf_input
890         if (s->s3->client_opaque_prf_input != NULL &&
891             s->version != DTLS1_VERSION)
892                 {
893                 size_t col = s->s3->client_opaque_prf_input_len;
894                 
895                 if ((long)(limit - ret - 6 - col < 0))
896                         return NULL;
897                 if (col > 0xFFFD) /* can't happen */
898                         return NULL;
899
900                 s2n(TLSEXT_TYPE_opaque_prf_input, ret); 
901                 s2n(col + 2, ret);
902                 s2n(col, ret);
903                 memcpy(ret, s->s3->client_opaque_prf_input, col);
904                 ret += col;
905                 }
906 #endif
907
908         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp &&
909             s->version != DTLS1_VERSION)
910                 {
911                 int i;
912                 long extlen, idlen, itmp;
913                 OCSP_RESPID *id;
914
915                 idlen = 0;
916                 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
917                         {
918                         id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
919                         itmp = i2d_OCSP_RESPID(id, NULL);
920                         if (itmp <= 0)
921                                 return NULL;
922                         idlen += itmp + 2;
923                         }
924
925                 if (s->tlsext_ocsp_exts)
926                         {
927                         extlen = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL);
928                         if (extlen < 0)
929                                 return NULL;
930                         }
931                 else
932                         extlen = 0;
933                         
934                 if ((long)(limit - ret - 7 - extlen - idlen) < 0) return NULL;
935                 s2n(TLSEXT_TYPE_status_request, ret);
936                 if (extlen + idlen > 0xFFF0)
937                         return NULL;
938                 s2n(extlen + idlen + 5, ret);
939                 *(ret++) = TLSEXT_STATUSTYPE_ocsp;
940                 s2n(idlen, ret);
941                 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
942                         {
943                         /* save position of id len */
944                         unsigned char *q = ret;
945                         id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
946                         /* skip over id len */
947                         ret += 2;
948                         itmp = i2d_OCSP_RESPID(id, &ret);
949                         /* write id len */
950                         s2n(itmp, q);
951                         }
952                 s2n(extlen, ret);
953                 if (extlen > 0)
954                         i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret);
955                 }
956
957 #ifndef OPENSSL_NO_HEARTBEATS
958         /* Add Heartbeat extension */
959         s2n(TLSEXT_TYPE_heartbeat,ret);
960         s2n(1,ret);
961         /* Set mode:
962          * 1: peer may send requests
963          * 2: peer not allowed to send requests
964          */
965         if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
966                 *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
967         else
968                 *(ret++) = SSL_TLSEXT_HB_ENABLED;
969 #endif
970
971 #ifndef OPENSSL_NO_NEXTPROTONEG
972         if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len)
973                 {
974                 /* The client advertises an emtpy extension to indicate its
975                  * support for Next Protocol Negotiation */
976                 if (limit - ret - 4 < 0)
977                         return NULL;
978                 s2n(TLSEXT_TYPE_next_proto_neg,ret);
979                 s2n(0,ret);
980                 }
981 #endif
982
983         if(SSL_get_srtp_profiles(s))
984                 {
985                 int el;
986
987                 ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0);
988                 
989                 if((limit - p - 4 - el) < 0) return NULL;
990
991                 s2n(TLSEXT_TYPE_use_srtp,ret);
992                 s2n(el,ret);
993
994                 if(ssl_add_clienthello_use_srtp_ext(s, ret, &el, el))
995                         {
996                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
997                         return NULL;
998                         }
999                 ret += el;
1000                 }
1001
1002         if ((extdatalen = ret-p-2)== 0) 
1003                 return p;
1004
1005         s2n(extdatalen,p);
1006         return ret;
1007         }
1008
1009 unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *p, unsigned char *limit)
1010         {
1011         int extdatalen=0;
1012         unsigned char *ret = p;
1013 #ifndef OPENSSL_NO_NEXTPROTONEG
1014         int next_proto_neg_seen;
1015 #endif
1016
1017         /* don't add extensions for SSLv3, unless doing secure renegotiation */
1018         if (s->version == SSL3_VERSION && !s->s3->send_connection_binding)
1019                 return p;
1020         
1021         ret+=2;
1022         if (ret>=limit) return NULL; /* this really never occurs, but ... */
1023
1024         if (!s->hit && s->servername_done == 1 && s->session->tlsext_hostname != NULL)
1025                 { 
1026                 if ((long)(limit - ret - 4) < 0) return NULL; 
1027
1028                 s2n(TLSEXT_TYPE_server_name,ret);
1029                 s2n(0,ret);
1030                 }
1031
1032         if(s->s3->send_connection_binding)
1033         {
1034           int el;
1035           
1036           if(!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0))
1037               {
1038               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1039               return NULL;
1040               }
1041
1042           if((limit - p - 4 - el) < 0) return NULL;
1043           
1044           s2n(TLSEXT_TYPE_renegotiate,ret);
1045           s2n(el,ret);
1046
1047           if(!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el))
1048               {
1049               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1050               return NULL;
1051               }
1052
1053           ret += el;
1054         }
1055
1056 #ifndef OPENSSL_NO_EC
1057         if (s->tlsext_ecpointformatlist != NULL &&
1058             s->version != DTLS1_VERSION)
1059                 {
1060                 /* Add TLS extension ECPointFormats to the ServerHello message */
1061                 long lenmax; 
1062
1063                 if ((lenmax = limit - ret - 5) < 0) return NULL; 
1064                 if (s->tlsext_ecpointformatlist_length > (unsigned long)lenmax) return NULL;
1065                 if (s->tlsext_ecpointformatlist_length > 255)
1066                         {
1067                         SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1068                         return NULL;
1069                         }
1070                 
1071                 s2n(TLSEXT_TYPE_ec_point_formats,ret);
1072                 s2n(s->tlsext_ecpointformatlist_length + 1,ret);
1073                 *(ret++) = (unsigned char) s->tlsext_ecpointformatlist_length;
1074                 memcpy(ret, s->tlsext_ecpointformatlist, s->tlsext_ecpointformatlist_length);
1075                 ret+=s->tlsext_ecpointformatlist_length;
1076
1077                 }
1078         /* Currently the server should not respond with a SupportedCurves extension */
1079 #endif /* OPENSSL_NO_EC */
1080
1081         if (s->tlsext_ticket_expected
1082                 && !(SSL_get_options(s) & SSL_OP_NO_TICKET)) 
1083                 { 
1084                 if ((long)(limit - ret - 4) < 0) return NULL; 
1085                 s2n(TLSEXT_TYPE_session_ticket,ret);
1086                 s2n(0,ret);
1087                 }
1088
1089         if (s->tlsext_status_expected)
1090                 { 
1091                 if ((long)(limit - ret - 4) < 0) return NULL; 
1092                 s2n(TLSEXT_TYPE_status_request,ret);
1093                 s2n(0,ret);
1094                 }
1095
1096 #ifdef TLSEXT_TYPE_opaque_prf_input
1097         if (s->s3->server_opaque_prf_input != NULL &&
1098             s->version != DTLS1_VERSION)
1099                 {
1100                 size_t sol = s->s3->server_opaque_prf_input_len;
1101                 
1102                 if ((long)(limit - ret - 6 - sol) < 0)
1103                         return NULL;
1104                 if (sol > 0xFFFD) /* can't happen */
1105                         return NULL;
1106
1107                 s2n(TLSEXT_TYPE_opaque_prf_input, ret); 
1108                 s2n(sol + 2, ret);
1109                 s2n(sol, ret);
1110                 memcpy(ret, s->s3->server_opaque_prf_input, sol);
1111                 ret += sol;
1112                 }
1113 #endif
1114
1115         if(s->srtp_profile)
1116                 {
1117                 int el;
1118
1119                 ssl_add_serverhello_use_srtp_ext(s, 0, &el, 0);
1120                 
1121                 if((limit - p - 4 - el) < 0) return NULL;
1122
1123                 s2n(TLSEXT_TYPE_use_srtp,ret);
1124                 s2n(el,ret);
1125
1126                 if(ssl_add_serverhello_use_srtp_ext(s, ret, &el, el))
1127                         {
1128                         SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1129                         return NULL;
1130                         }
1131                 ret+=el;
1132                 }
1133
1134         if (((s->s3->tmp.new_cipher->id & 0xFFFF)==0x80 || (s->s3->tmp.new_cipher->id & 0xFFFF)==0x81) 
1135                 && (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG))
1136                 { const unsigned char cryptopro_ext[36] = {
1137                         0xfd, 0xe8, /*65000*/
1138                         0x00, 0x20, /*32 bytes length*/
1139                         0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85, 
1140                         0x03,   0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06, 
1141                         0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08, 
1142                         0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17};
1143                         if (limit-ret<36) return NULL;
1144                         memcpy(ret,cryptopro_ext,36);
1145                         ret+=36;
1146
1147                 }
1148
1149 #ifndef OPENSSL_NO_HEARTBEATS
1150         /* Add Heartbeat extension if we've received one */
1151         if (s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED)
1152                 {
1153                 s2n(TLSEXT_TYPE_heartbeat,ret);
1154                 s2n(1,ret);
1155                 /* Set mode:
1156                  * 1: peer may send requests
1157                  * 2: peer not allowed to send requests
1158                  */
1159                 if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1160                         *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1161                 else
1162                         *(ret++) = SSL_TLSEXT_HB_ENABLED;
1163
1164                 }
1165 #endif
1166
1167 #ifndef OPENSSL_NO_NEXTPROTONEG
1168         next_proto_neg_seen = s->s3->next_proto_neg_seen;
1169         s->s3->next_proto_neg_seen = 0;
1170         if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb)
1171                 {
1172                 const unsigned char *npa;
1173                 unsigned int npalen;
1174                 int r;
1175
1176                 r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen, s->ctx->next_protos_advertised_cb_arg);
1177                 if (r == SSL_TLSEXT_ERR_OK)
1178                         {
1179                         if ((long)(limit - ret - 4 - npalen) < 0) return NULL;
1180                         s2n(TLSEXT_TYPE_next_proto_neg,ret);
1181                         s2n(npalen,ret);
1182                         memcpy(ret, npa, npalen);
1183                         ret += npalen;
1184                         s->s3->next_proto_neg_seen = 1;
1185                         }
1186                 }
1187 #endif
1188
1189         if ((extdatalen = ret-p-2)== 0) 
1190                 return p;
1191
1192         s2n(extdatalen,p);
1193         return ret;
1194         }
1195
1196 int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
1197         {
1198         unsigned short type;
1199         unsigned short size;
1200         unsigned short len;
1201         unsigned char *data = *p;
1202         int renegotiate_seen = 0;
1203         int sigalg_seen = 0;
1204
1205         s->servername_done = 0;
1206         s->tlsext_status_type = -1;
1207 #ifndef OPENSSL_NO_NEXTPROTONEG
1208         s->s3->next_proto_neg_seen = 0;
1209 #endif
1210
1211 #ifndef OPENSSL_NO_HEARTBEATS
1212         s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
1213                                SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
1214 #endif
1215
1216         if (data >= (d+n-2))
1217                 goto ri_check;
1218         n2s(data,len);
1219
1220         if (data > (d+n-len)) 
1221                 goto ri_check;
1222
1223         while (data <= (d+n-4))
1224                 {
1225                 n2s(data,type);
1226                 n2s(data,size);
1227
1228                 if (data+size > (d+n))
1229                         goto ri_check;
1230 #if 0
1231                 fprintf(stderr,"Received extension type %d size %d\n",type,size);
1232 #endif
1233                 if (s->tlsext_debug_cb)
1234                         s->tlsext_debug_cb(s, 0, type, data, size,
1235                                                 s->tlsext_debug_arg);
1236 /* The servername extension is treated as follows:
1237
1238    - Only the hostname type is supported with a maximum length of 255.
1239    - The servername is rejected if too long or if it contains zeros,
1240      in which case an fatal alert is generated.
1241    - The servername field is maintained together with the session cache.
1242    - When a session is resumed, the servername call back invoked in order
1243      to allow the application to position itself to the right context. 
1244    - The servername is acknowledged if it is new for a session or when 
1245      it is identical to a previously used for the same session. 
1246      Applications can control the behaviour.  They can at any time
1247      set a 'desirable' servername for a new SSL object. This can be the
1248      case for example with HTTPS when a Host: header field is received and
1249      a renegotiation is requested. In this case, a possible servername
1250      presented in the new client hello is only acknowledged if it matches
1251      the value of the Host: field. 
1252    - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
1253      if they provide for changing an explicit servername context for the session,
1254      i.e. when the session has been established with a servername extension. 
1255    - On session reconnect, the servername extension may be absent. 
1256
1257 */      
1258
1259                 if (type == TLSEXT_TYPE_server_name)
1260                         {
1261                         unsigned char *sdata;
1262                         int servname_type;
1263                         int dsize; 
1264                 
1265                         if (size < 2) 
1266                                 {
1267                                 *al = SSL_AD_DECODE_ERROR;
1268                                 return 0;
1269                                 }
1270                         n2s(data,dsize);  
1271                         size -= 2;
1272                         if (dsize > size  ) 
1273                                 {
1274                                 *al = SSL_AD_DECODE_ERROR;
1275                                 return 0;
1276                                 } 
1277
1278                         sdata = data;
1279                         while (dsize > 3) 
1280                                 {
1281                                 servname_type = *(sdata++); 
1282                                 n2s(sdata,len);
1283                                 dsize -= 3;
1284
1285                                 if (len > dsize) 
1286                                         {
1287                                         *al = SSL_AD_DECODE_ERROR;
1288                                         return 0;
1289                                         }
1290                                 if (s->servername_done == 0)
1291                                 switch (servname_type)
1292                                         {
1293                                 case TLSEXT_NAMETYPE_host_name:
1294                                         if (!s->hit)
1295                                                 {
1296                                                 if(s->session->tlsext_hostname)
1297                                                         {
1298                                                         *al = SSL_AD_DECODE_ERROR;
1299                                                         return 0;
1300                                                         }
1301                                                 if (len > TLSEXT_MAXLEN_host_name)
1302                                                         {
1303                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
1304                                                         return 0;
1305                                                         }
1306                                                 if ((s->session->tlsext_hostname = OPENSSL_malloc(len+1)) == NULL)
1307                                                         {
1308                                                         *al = TLS1_AD_INTERNAL_ERROR;
1309                                                         return 0;
1310                                                         }
1311                                                 memcpy(s->session->tlsext_hostname, sdata, len);
1312                                                 s->session->tlsext_hostname[len]='\0';
1313                                                 if (strlen(s->session->tlsext_hostname) != len) {
1314                                                         OPENSSL_free(s->session->tlsext_hostname);
1315                                                         s->session->tlsext_hostname = NULL;
1316                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
1317                                                         return 0;
1318                                                 }
1319                                                 s->servername_done = 1; 
1320
1321                                                 }
1322                                         else 
1323                                                 s->servername_done = s->session->tlsext_hostname
1324                                                         && strlen(s->session->tlsext_hostname) == len 
1325                                                         && strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0;
1326                                         
1327                                         break;
1328
1329                                 default:
1330                                         break;
1331                                         }
1332                                  
1333                                 dsize -= len;
1334                                 }
1335                         if (dsize != 0) 
1336                                 {
1337                                 *al = SSL_AD_DECODE_ERROR;
1338                                 return 0;
1339                                 }
1340
1341                         }
1342 #ifndef OPENSSL_NO_SRP
1343                 else if (type == TLSEXT_TYPE_srp)
1344                         {
1345                         if (size <= 0 || ((len = data[0])) != (size -1))
1346                                 {
1347                                 *al = SSL_AD_DECODE_ERROR;
1348                                 return 0;
1349                                 }
1350                         if (s->srp_ctx.login != NULL)
1351                                 {
1352                                 *al = SSL_AD_DECODE_ERROR;
1353                                 return 0;
1354                                 }
1355                         if ((s->srp_ctx.login = OPENSSL_malloc(len+1)) == NULL)
1356                                 return -1;
1357                         memcpy(s->srp_ctx.login, &data[1], len);
1358                         s->srp_ctx.login[len]='\0';
1359   
1360                         if (strlen(s->srp_ctx.login) != len) 
1361                                 {
1362                                 *al = SSL_AD_DECODE_ERROR;
1363                                 return 0;
1364                                 }
1365                         }
1366 #endif
1367
1368 #ifndef OPENSSL_NO_EC
1369                 else if (type == TLSEXT_TYPE_ec_point_formats &&
1370                      s->version != DTLS1_VERSION)
1371                         {
1372                         unsigned char *sdata = data;
1373                         int ecpointformatlist_length = *(sdata++);
1374
1375                         if (ecpointformatlist_length != size - 1)
1376                                 {
1377                                 *al = TLS1_AD_DECODE_ERROR;
1378                                 return 0;
1379                                 }
1380                         if (!s->hit)
1381                                 {
1382                                 if(s->session->tlsext_ecpointformatlist)
1383                                         {
1384                                         OPENSSL_free(s->session->tlsext_ecpointformatlist);
1385                                         s->session->tlsext_ecpointformatlist = NULL;
1386                                         }
1387                                 s->session->tlsext_ecpointformatlist_length = 0;
1388                                 if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
1389                                         {
1390                                         *al = TLS1_AD_INTERNAL_ERROR;
1391                                         return 0;
1392                                         }
1393                                 s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
1394                                 memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
1395                                 }
1396 #if 0
1397                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ", s->session->tlsext_ecpointformatlist_length);
1398                         sdata = s->session->tlsext_ecpointformatlist;
1399                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
1400                                 fprintf(stderr,"%i ",*(sdata++));
1401                         fprintf(stderr,"\n");
1402 #endif
1403                         }
1404                 else if (type == TLSEXT_TYPE_elliptic_curves &&
1405                      s->version != DTLS1_VERSION)
1406                         {
1407                         unsigned char *sdata = data;
1408                         int ellipticcurvelist_length = (*(sdata++) << 8);
1409                         ellipticcurvelist_length += (*(sdata++));
1410
1411                         if (ellipticcurvelist_length != size - 2)
1412                                 {
1413                                 *al = TLS1_AD_DECODE_ERROR;
1414                                 return 0;
1415                                 }
1416                         if (!s->hit)
1417                                 {
1418                                 if(s->session->tlsext_ellipticcurvelist)
1419                                         {
1420                                         *al = TLS1_AD_DECODE_ERROR;
1421                                         return 0;
1422                                         }
1423                                 s->session->tlsext_ellipticcurvelist_length = 0;
1424                                 if ((s->session->tlsext_ellipticcurvelist = OPENSSL_malloc(ellipticcurvelist_length)) == NULL)
1425                                         {
1426                                         *al = TLS1_AD_INTERNAL_ERROR;
1427                                         return 0;
1428                                         }
1429                                 s->session->tlsext_ellipticcurvelist_length = ellipticcurvelist_length;
1430                                 memcpy(s->session->tlsext_ellipticcurvelist, sdata, ellipticcurvelist_length);
1431                                 }
1432 #if 0
1433                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ", s->session->tlsext_ellipticcurvelist_length);
1434                         sdata = s->session->tlsext_ellipticcurvelist;
1435                         for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++)
1436                                 fprintf(stderr,"%i ",*(sdata++));
1437                         fprintf(stderr,"\n");
1438 #endif
1439                         }
1440 #endif /* OPENSSL_NO_EC */
1441 #ifdef TLSEXT_TYPE_opaque_prf_input
1442                 else if (type == TLSEXT_TYPE_opaque_prf_input &&
1443                      s->version != DTLS1_VERSION)
1444                         {
1445                         unsigned char *sdata = data;
1446
1447                         if (size < 2)
1448                                 {
1449                                 *al = SSL_AD_DECODE_ERROR;
1450                                 return 0;
1451                                 }
1452                         n2s(sdata, s->s3->client_opaque_prf_input_len);
1453                         if (s->s3->client_opaque_prf_input_len != size - 2)
1454                                 {
1455                                 *al = SSL_AD_DECODE_ERROR;
1456                                 return 0;
1457                                 }
1458
1459                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
1460                                 OPENSSL_free(s->s3->client_opaque_prf_input);
1461                         if (s->s3->client_opaque_prf_input_len == 0)
1462                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
1463                         else
1464                                 s->s3->client_opaque_prf_input = BUF_memdup(sdata, s->s3->client_opaque_prf_input_len);
1465                         if (s->s3->client_opaque_prf_input == NULL)
1466                                 {
1467                                 *al = TLS1_AD_INTERNAL_ERROR;
1468                                 return 0;
1469                                 }
1470                         }
1471 #endif
1472                 else if (type == TLSEXT_TYPE_session_ticket)
1473                         {
1474                         if (s->tls_session_ticket_ext_cb &&
1475                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
1476                                 {
1477                                 *al = TLS1_AD_INTERNAL_ERROR;
1478                                 return 0;
1479                                 }
1480                         }
1481                 else if (type == TLSEXT_TYPE_renegotiate)
1482                         {
1483                         if(!ssl_parse_clienthello_renegotiate_ext(s, data, size, al))
1484                                 return 0;
1485                         renegotiate_seen = 1;
1486                         }
1487                 else if (type == TLSEXT_TYPE_signature_algorithms)
1488                         {
1489                         int dsize;
1490                         if (sigalg_seen || size < 2) 
1491                                 {
1492                                 *al = SSL_AD_DECODE_ERROR;
1493                                 return 0;
1494                                 }
1495                         sigalg_seen = 1;
1496                         n2s(data,dsize);
1497                         size -= 2;
1498                         if (dsize != size || dsize & 1) 
1499                                 {
1500                                 *al = SSL_AD_DECODE_ERROR;
1501                                 return 0;
1502                                 }
1503                         if (!tls1_process_sigalgs(s, data, dsize))
1504                                 {
1505                                 *al = SSL_AD_DECODE_ERROR;
1506                                 return 0;
1507                                 }
1508                         }
1509                 else if (type == TLSEXT_TYPE_status_request &&
1510                          s->version != DTLS1_VERSION && s->ctx->tlsext_status_cb)
1511                         {
1512                 
1513                         if (size < 5) 
1514                                 {
1515                                 *al = SSL_AD_DECODE_ERROR;
1516                                 return 0;
1517                                 }
1518
1519                         s->tlsext_status_type = *data++;
1520                         size--;
1521                         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp)
1522                                 {
1523                                 const unsigned char *sdata;
1524                                 int dsize;
1525                                 /* Read in responder_id_list */
1526                                 n2s(data,dsize);
1527                                 size -= 2;
1528                                 if (dsize > size  ) 
1529                                         {
1530                                         *al = SSL_AD_DECODE_ERROR;
1531                                         return 0;
1532                                         }
1533                                 while (dsize > 0)
1534                                         {
1535                                         OCSP_RESPID *id;
1536                                         int idsize;
1537                                         if (dsize < 4)
1538                                                 {
1539                                                 *al = SSL_AD_DECODE_ERROR;
1540                                                 return 0;
1541                                                 }
1542                                         n2s(data, idsize);
1543                                         dsize -= 2 + idsize;
1544                                         size -= 2 + idsize;
1545                                         if (dsize < 0)
1546                                                 {
1547                                                 *al = SSL_AD_DECODE_ERROR;
1548                                                 return 0;
1549                                                 }
1550                                         sdata = data;
1551                                         data += idsize;
1552                                         id = d2i_OCSP_RESPID(NULL,
1553                                                                 &sdata, idsize);
1554                                         if (!id)
1555                                                 {
1556                                                 *al = SSL_AD_DECODE_ERROR;
1557                                                 return 0;
1558                                                 }
1559                                         if (data != sdata)
1560                                                 {
1561                                                 OCSP_RESPID_free(id);
1562                                                 *al = SSL_AD_DECODE_ERROR;
1563                                                 return 0;
1564                                                 }
1565                                         if (!s->tlsext_ocsp_ids
1566                                                 && !(s->tlsext_ocsp_ids =
1567                                                 sk_OCSP_RESPID_new_null()))
1568                                                 {
1569                                                 OCSP_RESPID_free(id);
1570                                                 *al = SSL_AD_INTERNAL_ERROR;
1571                                                 return 0;
1572                                                 }
1573                                         if (!sk_OCSP_RESPID_push(
1574                                                         s->tlsext_ocsp_ids, id))
1575                                                 {
1576                                                 OCSP_RESPID_free(id);
1577                                                 *al = SSL_AD_INTERNAL_ERROR;
1578                                                 return 0;
1579                                                 }
1580                                         }
1581
1582                                 /* Read in request_extensions */
1583                                 if (size < 2)
1584                                         {
1585                                         *al = SSL_AD_DECODE_ERROR;
1586                                         return 0;
1587                                         }
1588                                 n2s(data,dsize);
1589                                 size -= 2;
1590                                 if (dsize != size)
1591                                         {
1592                                         *al = SSL_AD_DECODE_ERROR;
1593                                         return 0;
1594                                         }
1595                                 sdata = data;
1596                                 if (dsize > 0)
1597                                         {
1598                                         if (s->tlsext_ocsp_exts)
1599                                                 {
1600                                                 sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
1601                                                                            X509_EXTENSION_free);
1602                                                 }
1603
1604                                         s->tlsext_ocsp_exts =
1605                                                 d2i_X509_EXTENSIONS(NULL,
1606                                                         &sdata, dsize);
1607                                         if (!s->tlsext_ocsp_exts
1608                                                 || (data + dsize != sdata))
1609                                                 {
1610                                                 *al = SSL_AD_DECODE_ERROR;
1611                                                 return 0;
1612                                                 }
1613                                         }
1614                                 }
1615                                 /* We don't know what to do with any other type
1616                                 * so ignore it.
1617                                 */
1618                                 else
1619                                         s->tlsext_status_type = -1;
1620                         }
1621 #ifndef OPENSSL_NO_HEARTBEATS
1622                 else if (type == TLSEXT_TYPE_heartbeat)
1623                         {
1624                         switch(data[0])
1625                                 {
1626                                 case 0x01:      /* Client allows us to send HB requests */
1627                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
1628                                                         break;
1629                                 case 0x02:      /* Client doesn't accept HB requests */
1630                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
1631                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1632                                                         break;
1633                                 default:        *al = SSL_AD_ILLEGAL_PARAMETER;
1634                                                         return 0;
1635                                 }
1636                         }
1637 #endif
1638 #ifndef OPENSSL_NO_NEXTPROTONEG
1639                 else if (type == TLSEXT_TYPE_next_proto_neg &&
1640                          s->s3->tmp.finish_md_len == 0)
1641                         {
1642                         /* We shouldn't accept this extension on a
1643                          * renegotiation.
1644                          *
1645                          * s->new_session will be set on renegotiation, but we
1646                          * probably shouldn't rely that it couldn't be set on
1647                          * the initial renegotation too in certain cases (when
1648                          * there's some other reason to disallow resuming an
1649                          * earlier session -- the current code won't be doing
1650                          * anything like that, but this might change).
1651
1652                          * A valid sign that there's been a previous handshake
1653                          * in this connection is if s->s3->tmp.finish_md_len >
1654                          * 0.  (We are talking about a check that will happen
1655                          * in the Hello protocol round, well before a new
1656                          * Finished message could have been computed.) */
1657                         s->s3->next_proto_neg_seen = 1;
1658                         }
1659 #endif
1660
1661                 /* session ticket processed earlier */
1662                 else if (type == TLSEXT_TYPE_use_srtp)
1663                         {
1664                         if(ssl_parse_clienthello_use_srtp_ext(s, data, size,
1665                                                               al))
1666                                 return 0;
1667                         }
1668
1669                 data+=size;
1670                 }
1671                                 
1672         *p = data;
1673
1674         ri_check:
1675
1676         /* Need RI if renegotiating */
1677
1678         if (!renegotiate_seen && s->renegotiate &&
1679                 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
1680                 {
1681                 *al = SSL_AD_HANDSHAKE_FAILURE;
1682                 SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT,
1683                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
1684                 return 0;
1685                 }
1686
1687         return 1;
1688         }
1689
1690 #ifndef OPENSSL_NO_NEXTPROTONEG
1691 /* ssl_next_proto_validate validates a Next Protocol Negotiation block. No
1692  * elements of zero length are allowed and the set of elements must exactly fill
1693  * the length of the block. */
1694 static int ssl_next_proto_validate(unsigned char *d, unsigned len)
1695         {
1696         unsigned int off = 0;
1697
1698         while (off < len)
1699                 {
1700                 if (d[off] == 0)
1701                         return 0;
1702                 off += d[off];
1703                 off++;
1704                 }
1705
1706         return off == len;
1707         }
1708 #endif
1709
1710 int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
1711         {
1712         unsigned short length;
1713         unsigned short type;
1714         unsigned short size;
1715         unsigned char *data = *p;
1716         int tlsext_servername = 0;
1717         int renegotiate_seen = 0;
1718
1719 #ifndef OPENSSL_NO_NEXTPROTONEG
1720         s->s3->next_proto_neg_seen = 0;
1721 #endif
1722
1723 #ifndef OPENSSL_NO_HEARTBEATS
1724         s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
1725                                SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
1726 #endif
1727
1728         if (data >= (d+n-2))
1729                 goto ri_check;
1730
1731         n2s(data,length);
1732         if (data+length != d+n)
1733                 {
1734                 *al = SSL_AD_DECODE_ERROR;
1735                 return 0;
1736                 }
1737
1738         while(data <= (d+n-4))
1739                 {
1740                 n2s(data,type);
1741                 n2s(data,size);
1742
1743                 if (data+size > (d+n))
1744                         goto ri_check;
1745
1746                 if (s->tlsext_debug_cb)
1747                         s->tlsext_debug_cb(s, 1, type, data, size,
1748                                                 s->tlsext_debug_arg);
1749
1750                 if (type == TLSEXT_TYPE_server_name)
1751                         {
1752                         if (s->tlsext_hostname == NULL || size > 0)
1753                                 {
1754                                 *al = TLS1_AD_UNRECOGNIZED_NAME;
1755                                 return 0;
1756                                 }
1757                         tlsext_servername = 1;   
1758                         }
1759
1760 #ifndef OPENSSL_NO_EC
1761                 else if (type == TLSEXT_TYPE_ec_point_formats &&
1762                      s->version != DTLS1_VERSION)
1763                         {
1764                         unsigned char *sdata = data;
1765                         int ecpointformatlist_length = *(sdata++);
1766
1767                         if (ecpointformatlist_length != size - 1)
1768                                 {
1769                                 *al = TLS1_AD_DECODE_ERROR;
1770                                 return 0;
1771                                 }
1772                         s->session->tlsext_ecpointformatlist_length = 0;
1773                         if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist);
1774                         if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
1775                                 {
1776                                 *al = TLS1_AD_INTERNAL_ERROR;
1777                                 return 0;
1778                                 }
1779                         s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
1780                         memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
1781 #if 0
1782                         fprintf(stderr,"ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist ");
1783                         sdata = s->session->tlsext_ecpointformatlist;
1784                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
1785                                 fprintf(stderr,"%i ",*(sdata++));
1786                         fprintf(stderr,"\n");
1787 #endif
1788                         }
1789 #endif /* OPENSSL_NO_EC */
1790
1791                 else if (type == TLSEXT_TYPE_session_ticket)
1792                         {
1793                         if (s->tls_session_ticket_ext_cb &&
1794                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
1795                                 {
1796                                 *al = TLS1_AD_INTERNAL_ERROR;
1797                                 return 0;
1798                                 }
1799                         if ((SSL_get_options(s) & SSL_OP_NO_TICKET)
1800                                 || (size > 0))
1801                                 {
1802                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
1803                                 return 0;
1804                                 }
1805                         s->tlsext_ticket_expected = 1;
1806                         }
1807 #ifdef TLSEXT_TYPE_opaque_prf_input
1808                 else if (type == TLSEXT_TYPE_opaque_prf_input &&
1809                      s->version != DTLS1_VERSION)
1810                         {
1811                         unsigned char *sdata = data;
1812
1813                         if (size < 2)
1814                                 {
1815                                 *al = SSL_AD_DECODE_ERROR;
1816                                 return 0;
1817                                 }
1818                         n2s(sdata, s->s3->server_opaque_prf_input_len);
1819                         if (s->s3->server_opaque_prf_input_len != size - 2)
1820                                 {
1821                                 *al = SSL_AD_DECODE_ERROR;
1822                                 return 0;
1823                                 }
1824                         
1825                         if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
1826                                 OPENSSL_free(s->s3->server_opaque_prf_input);
1827                         if (s->s3->server_opaque_prf_input_len == 0)
1828                                 s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
1829                         else
1830                                 s->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len);
1831
1832                         if (s->s3->server_opaque_prf_input == NULL)
1833                                 {
1834                                 *al = TLS1_AD_INTERNAL_ERROR;
1835                                 return 0;
1836                                 }
1837                         }
1838 #endif
1839                 else if (type == TLSEXT_TYPE_status_request &&
1840                          s->version != DTLS1_VERSION)
1841                         {
1842                         /* MUST be empty and only sent if we've requested
1843                          * a status request message.
1844                          */ 
1845                         if ((s->tlsext_status_type == -1) || (size > 0))
1846                                 {
1847                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
1848                                 return 0;
1849                                 }
1850                         /* Set flag to expect CertificateStatus message */
1851                         s->tlsext_status_expected = 1;
1852                         }
1853 #ifndef OPENSSL_NO_NEXTPROTONEG
1854                 else if (type == TLSEXT_TYPE_next_proto_neg &&
1855                          s->s3->tmp.finish_md_len == 0)
1856                         {
1857                         unsigned char *selected;
1858                         unsigned char selected_len;
1859
1860                         /* We must have requested it. */
1861                         if ((s->ctx->next_proto_select_cb == NULL))
1862                                 {
1863                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
1864                                 return 0;
1865                                 }
1866                         /* The data must be valid */
1867                         if (!ssl_next_proto_validate(data, size))
1868                                 {
1869                                 *al = TLS1_AD_DECODE_ERROR;
1870                                 return 0;
1871                                 }
1872                         if (s->ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK)
1873                                 {
1874                                 *al = TLS1_AD_INTERNAL_ERROR;
1875                                 return 0;
1876                                 }
1877                         s->next_proto_negotiated = OPENSSL_malloc(selected_len);
1878                         if (!s->next_proto_negotiated)
1879                                 {
1880                                 *al = TLS1_AD_INTERNAL_ERROR;
1881                                 return 0;
1882                                 }
1883                         memcpy(s->next_proto_negotiated, selected, selected_len);
1884                         s->next_proto_negotiated_len = selected_len;
1885                         s->s3->next_proto_neg_seen = 1;
1886                         }
1887 #endif
1888                 else if (type == TLSEXT_TYPE_renegotiate)
1889                         {
1890                         if(!ssl_parse_serverhello_renegotiate_ext(s, data, size, al))
1891                                 return 0;
1892                         renegotiate_seen = 1;
1893                         }
1894 #ifndef OPENSSL_NO_HEARTBEATS
1895                 else if (type == TLSEXT_TYPE_heartbeat)
1896                         {
1897                         switch(data[0])
1898                                 {
1899                                 case 0x01:      /* Server allows us to send HB requests */
1900                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
1901                                                         break;
1902                                 case 0x02:      /* Server doesn't accept HB requests */
1903                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
1904                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1905                                                         break;
1906                                 default:        *al = SSL_AD_ILLEGAL_PARAMETER;
1907                                                         return 0;
1908                                 }
1909                         }
1910 #endif
1911                 else if (type == TLSEXT_TYPE_use_srtp)
1912                         {
1913                         if(ssl_parse_serverhello_use_srtp_ext(s, data, size,
1914                                                               al))
1915                                 return 0;
1916                         }
1917
1918                 data+=size;             
1919                 }
1920
1921         if (data != d+n)
1922                 {
1923                 *al = SSL_AD_DECODE_ERROR;
1924                 return 0;
1925                 }
1926
1927         if (!s->hit && tlsext_servername == 1)
1928                 {
1929                 if (s->tlsext_hostname)
1930                         {
1931                         if (s->session->tlsext_hostname == NULL)
1932                                 {
1933                                 s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);   
1934                                 if (!s->session->tlsext_hostname)
1935                                         {
1936                                         *al = SSL_AD_UNRECOGNIZED_NAME;
1937                                         return 0;
1938                                         }
1939                                 }
1940                         else 
1941                                 {
1942                                 *al = SSL_AD_DECODE_ERROR;
1943                                 return 0;
1944                                 }
1945                         }
1946                 }
1947
1948         *p = data;
1949
1950         ri_check:
1951
1952         /* Determine if we need to see RI. Strictly speaking if we want to
1953          * avoid an attack we should *always* see RI even on initial server
1954          * hello because the client doesn't see any renegotiation during an
1955          * attack. However this would mean we could not connect to any server
1956          * which doesn't support RI so for the immediate future tolerate RI
1957          * absence on initial connect only.
1958          */
1959         if (!renegotiate_seen
1960                 && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
1961                 && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
1962                 {
1963                 *al = SSL_AD_HANDSHAKE_FAILURE;
1964                 SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT,
1965                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
1966                 return 0;
1967                 }
1968
1969         return 1;
1970         }
1971
1972
1973 int ssl_prepare_clienthello_tlsext(SSL *s)
1974         {
1975
1976 #ifdef TLSEXT_TYPE_opaque_prf_input
1977         {
1978                 int r = 1;
1979         
1980                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
1981                         {
1982                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
1983                         if (!r)
1984                                 return -1;
1985                         }
1986
1987                 if (s->tlsext_opaque_prf_input != NULL)
1988                         {
1989                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
1990                                 OPENSSL_free(s->s3->client_opaque_prf_input);
1991
1992                         if (s->tlsext_opaque_prf_input_len == 0)
1993                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
1994                         else
1995                                 s->s3->client_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
1996                         if (s->s3->client_opaque_prf_input == NULL)
1997                                 {
1998                                 SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
1999                                 return -1;
2000                                 }
2001                         s->s3->client_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2002                         }
2003
2004                 if (r == 2)
2005                         /* at callback's request, insist on receiving an appropriate server opaque PRF input */
2006                         s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2007         }
2008 #endif
2009
2010         return 1;
2011         }
2012
2013 int ssl_prepare_serverhello_tlsext(SSL *s)
2014         {
2015 #ifndef OPENSSL_NO_EC
2016         /* If we are server and using an ECC cipher suite, send the point formats we support 
2017          * if the client sent us an ECPointsFormat extension.  Note that the server is not
2018          * supposed to send an EllipticCurves extension.
2019          */
2020
2021         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2022         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2023         int using_ecc = (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA);
2024         using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL);
2025         
2026         if (using_ecc)
2027                 {
2028                 if (s->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->tlsext_ecpointformatlist);
2029                 if ((s->tlsext_ecpointformatlist = OPENSSL_malloc(3)) == NULL)
2030                         {
2031                         SSLerr(SSL_F_SSL_PREPARE_SERVERHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
2032                         return -1;
2033                         }
2034                 s->tlsext_ecpointformatlist_length = 3;
2035                 s->tlsext_ecpointformatlist[0] = TLSEXT_ECPOINTFORMAT_uncompressed;
2036                 s->tlsext_ecpointformatlist[1] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
2037                 s->tlsext_ecpointformatlist[2] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
2038                 }
2039 #endif /* OPENSSL_NO_EC */
2040
2041         return 1;
2042         }
2043
2044 int ssl_check_clienthello_tlsext(SSL *s)
2045         {
2046         int ret=SSL_TLSEXT_ERR_NOACK;
2047         int al = SSL_AD_UNRECOGNIZED_NAME;
2048
2049 #ifndef OPENSSL_NO_EC
2050         /* The handling of the ECPointFormats extension is done elsewhere, namely in 
2051          * ssl3_choose_cipher in s3_lib.c.
2052          */
2053         /* The handling of the EllipticCurves extension is done elsewhere, namely in 
2054          * ssl3_choose_cipher in s3_lib.c.
2055          */
2056 #endif
2057
2058         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
2059                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
2060         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
2061                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
2062
2063         /* If status request then ask callback what to do.
2064          * Note: this must be called after servername callbacks in case 
2065          * the certificate has changed.
2066          */
2067         if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb)
2068                 {
2069                 int r;
2070                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2071                 switch (r)
2072                         {
2073                         /* We don't want to send a status request response */
2074                         case SSL_TLSEXT_ERR_NOACK:
2075                                 s->tlsext_status_expected = 0;
2076                                 break;
2077                         /* status request response should be sent */
2078                         case SSL_TLSEXT_ERR_OK:
2079                                 if (s->tlsext_ocsp_resp)
2080                                         s->tlsext_status_expected = 1;
2081                                 else
2082                                         s->tlsext_status_expected = 0;
2083                                 break;
2084                         /* something bad happened */
2085                         case SSL_TLSEXT_ERR_ALERT_FATAL:
2086                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2087                                 al = SSL_AD_INTERNAL_ERROR;
2088                                 goto err;
2089                         }
2090                 }
2091         else
2092                 s->tlsext_status_expected = 0;
2093
2094 #ifdef TLSEXT_TYPE_opaque_prf_input
2095         {
2096                 /* This sort of belongs into ssl_prepare_serverhello_tlsext(),
2097                  * but we might be sending an alert in response to the client hello,
2098                  * so this has to happen here in ssl_check_clienthello_tlsext(). */
2099
2100                 int r = 1;
2101         
2102                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
2103                         {
2104                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
2105                         if (!r)
2106                                 {
2107                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2108                                 al = SSL_AD_INTERNAL_ERROR;
2109                                 goto err;
2110                                 }
2111                         }
2112
2113                 if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
2114                         OPENSSL_free(s->s3->server_opaque_prf_input);
2115                 s->s3->server_opaque_prf_input = NULL;
2116
2117                 if (s->tlsext_opaque_prf_input != NULL)
2118                         {
2119                         if (s->s3->client_opaque_prf_input != NULL &&
2120                                 s->s3->client_opaque_prf_input_len == s->tlsext_opaque_prf_input_len)
2121                                 {
2122                                 /* can only use this extension if we have a server opaque PRF input
2123                                  * of the same length as the client opaque PRF input! */
2124
2125                                 if (s->tlsext_opaque_prf_input_len == 0)
2126                                         s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2127                                 else
2128                                         s->s3->server_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
2129                                 if (s->s3->server_opaque_prf_input == NULL)
2130                                         {
2131                                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2132                                         al = SSL_AD_INTERNAL_ERROR;
2133                                         goto err;
2134                                         }
2135                                 s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2136                                 }
2137                         }
2138
2139                 if (r == 2 && s->s3->server_opaque_prf_input == NULL)
2140                         {
2141                         /* The callback wants to enforce use of the extension,
2142                          * but we can't do that with the client opaque PRF input;
2143                          * abort the handshake.
2144                          */
2145                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2146                         al = SSL_AD_HANDSHAKE_FAILURE;
2147                         }
2148         }
2149
2150 #endif
2151  err:
2152         switch (ret)
2153                 {
2154                 case SSL_TLSEXT_ERR_ALERT_FATAL:
2155                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2156                         return -1;
2157
2158                 case SSL_TLSEXT_ERR_ALERT_WARNING:
2159                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
2160                         return 1; 
2161                                         
2162                 case SSL_TLSEXT_ERR_NOACK:
2163                         s->servername_done=0;
2164                         default:
2165                 return 1;
2166                 }
2167         }
2168
2169 int ssl_check_serverhello_tlsext(SSL *s)
2170         {
2171         int ret=SSL_TLSEXT_ERR_NOACK;
2172         int al = SSL_AD_UNRECOGNIZED_NAME;
2173
2174 #ifndef OPENSSL_NO_EC
2175         /* If we are client and using an elliptic curve cryptography cipher
2176          * suite, then if server returns an EC point formats lists extension
2177          * it must contain uncompressed.
2178          */
2179         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2180         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2181         if ((s->tlsext_ecpointformatlist != NULL) && (s->tlsext_ecpointformatlist_length > 0) && 
2182             (s->session->tlsext_ecpointformatlist != NULL) && (s->session->tlsext_ecpointformatlist_length > 0) && 
2183             ((alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA)))
2184                 {
2185                 /* we are using an ECC cipher */
2186                 size_t i;
2187                 unsigned char *list;
2188                 int found_uncompressed = 0;
2189                 list = s->session->tlsext_ecpointformatlist;
2190                 for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2191                         {
2192                         if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed)
2193                                 {
2194                                 found_uncompressed = 1;
2195                                 break;
2196                                 }
2197                         }
2198                 if (!found_uncompressed)
2199                         {
2200                         SSLerr(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT,SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
2201                         return -1;
2202                         }
2203                 }
2204         ret = SSL_TLSEXT_ERR_OK;
2205 #endif /* OPENSSL_NO_EC */
2206
2207         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
2208                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
2209         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
2210                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
2211
2212 #ifdef TLSEXT_TYPE_opaque_prf_input
2213         if (s->s3->server_opaque_prf_input_len > 0)
2214                 {
2215                 /* This case may indicate that we, as a client, want to insist on using opaque PRF inputs.
2216                  * So first verify that we really have a value from the server too. */
2217
2218                 if (s->s3->server_opaque_prf_input == NULL)
2219                         {
2220                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2221                         al = SSL_AD_HANDSHAKE_FAILURE;
2222                         }
2223                 
2224                 /* Anytime the server *has* sent an opaque PRF input, we need to check
2225                  * that we have a client opaque PRF input of the same size. */
2226                 if (s->s3->client_opaque_prf_input == NULL ||
2227                     s->s3->client_opaque_prf_input_len != s->s3->server_opaque_prf_input_len)
2228                         {
2229                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2230                         al = SSL_AD_ILLEGAL_PARAMETER;
2231                         }
2232                 }
2233 #endif
2234
2235         /* If we've requested certificate status and we wont get one
2236          * tell the callback
2237          */
2238         if ((s->tlsext_status_type != -1) && !(s->tlsext_status_expected)
2239                         && s->ctx && s->ctx->tlsext_status_cb)
2240                 {
2241                 int r;
2242                 /* Set resp to NULL, resplen to -1 so callback knows
2243                  * there is no response.
2244                  */
2245                 if (s->tlsext_ocsp_resp)
2246                         {
2247                         OPENSSL_free(s->tlsext_ocsp_resp);
2248                         s->tlsext_ocsp_resp = NULL;
2249                         }
2250                 s->tlsext_ocsp_resplen = -1;
2251                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2252                 if (r == 0)
2253                         {
2254                         al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
2255                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2256                         }
2257                 if (r < 0)
2258                         {
2259                         al = SSL_AD_INTERNAL_ERROR;
2260                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2261                         }
2262                 }
2263
2264         switch (ret)
2265                 {
2266                 case SSL_TLSEXT_ERR_ALERT_FATAL:
2267                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2268                         return -1;
2269
2270                 case SSL_TLSEXT_ERR_ALERT_WARNING:
2271                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
2272                         return 1; 
2273                                         
2274                 case SSL_TLSEXT_ERR_NOACK:
2275                         s->servername_done=0;
2276                         default:
2277                 return 1;
2278                 }
2279         }
2280
2281 /* Since the server cache lookup is done early on in the processing of the
2282  * ClientHello, and other operations depend on the result, we need to handle
2283  * any TLS session ticket extension at the same time.
2284  *
2285  *   session_id: points at the session ID in the ClientHello. This code will
2286  *       read past the end of this in order to parse out the session ticket
2287  *       extension, if any.
2288  *   len: the length of the session ID.
2289  *   limit: a pointer to the first byte after the ClientHello.
2290  *   ret: (output) on return, if a ticket was decrypted, then this is set to
2291  *       point to the resulting session.
2292  *
2293  * If s->tls_session_secret_cb is set then we are expecting a pre-shared key
2294  * ciphersuite, in which case we have no use for session tickets and one will
2295  * never be decrypted, nor will s->tlsext_ticket_expected be set to 1.
2296  *
2297  * Returns:
2298  *   -1: fatal error, either from parsing or decrypting the ticket.
2299  *    0: no ticket was found (or was ignored, based on settings).
2300  *    1: a zero length extension was found, indicating that the client supports
2301  *       session tickets but doesn't currently have one to offer.
2302  *    2: either s->tls_session_secret_cb was set, or a ticket was offered but
2303  *       couldn't be decrypted because of a non-fatal error.
2304  *    3: a ticket was successfully decrypted and *ret was set.
2305  *
2306  * Side effects:
2307  *   Sets s->tlsext_ticket_expected to 1 if the server will have to issue
2308  *   a new session ticket to the client because the client indicated support
2309  *   (and s->tls_session_secret_cb is NULL) but the client either doesn't have
2310  *   a session ticket or we couldn't use the one it gave us, or if
2311  *   s->ctx->tlsext_ticket_key_cb asked to renew the client's ticket.
2312  *   Otherwise, s->tlsext_ticket_expected is set to 0.
2313  */
2314 int tls1_process_ticket(SSL *s, unsigned char *session_id, int len,
2315                         const unsigned char *limit, SSL_SESSION **ret)
2316         {
2317         /* Point after session ID in client hello */
2318         const unsigned char *p = session_id + len;
2319         unsigned short i;
2320
2321         *ret = NULL;
2322         s->tlsext_ticket_expected = 0;
2323
2324         /* If tickets disabled behave as if no ticket present
2325          * to permit stateful resumption.
2326          */
2327         if (SSL_get_options(s) & SSL_OP_NO_TICKET)
2328                 return 0;
2329         if ((s->version <= SSL3_VERSION) || !limit)
2330                 return 0;
2331         if (p >= limit)
2332                 return -1;
2333         /* Skip past DTLS cookie */
2334         if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER)
2335                 {
2336                 i = *(p++);
2337                 p+= i;
2338                 if (p >= limit)
2339                         return -1;
2340                 }
2341         /* Skip past cipher list */
2342         n2s(p, i);
2343         p+= i;
2344         if (p >= limit)
2345                 return -1;
2346         /* Skip past compression algorithm list */
2347         i = *(p++);
2348         p += i;
2349         if (p > limit)
2350                 return -1;
2351         /* Now at start of extensions */
2352         if ((p + 2) >= limit)
2353                 return 0;
2354         n2s(p, i);
2355         while ((p + 4) <= limit)
2356                 {
2357                 unsigned short type, size;
2358                 n2s(p, type);
2359                 n2s(p, size);
2360                 if (p + size > limit)
2361                         return 0;
2362                 if (type == TLSEXT_TYPE_session_ticket)
2363                         {
2364                         int r;
2365                         if (size == 0)
2366                                 {
2367                                 /* The client will accept a ticket but doesn't
2368                                  * currently have one. */
2369                                 s->tlsext_ticket_expected = 1;
2370                                 return 1;
2371                                 }
2372                         if (s->tls_session_secret_cb)
2373                                 {
2374                                 /* Indicate that the ticket couldn't be
2375                                  * decrypted rather than generating the session
2376                                  * from ticket now, trigger abbreviated
2377                                  * handshake based on external mechanism to
2378                                  * calculate the master secret later. */
2379                                 return 2;
2380                                 }
2381                         r = tls_decrypt_ticket(s, p, size, session_id, len, ret);
2382                         switch (r)
2383                                 {
2384                                 case 2: /* ticket couldn't be decrypted */
2385                                         s->tlsext_ticket_expected = 1;
2386                                         return 2;
2387                                 case 3: /* ticket was decrypted */
2388                                         return r;
2389                                 case 4: /* ticket decrypted but need to renew */
2390                                         s->tlsext_ticket_expected = 1;
2391                                         return 3;
2392                                 default: /* fatal error */
2393                                         return -1;
2394                                 }
2395                         }
2396                 p += size;
2397                 }
2398         return 0;
2399         }
2400
2401 /* tls_decrypt_ticket attempts to decrypt a session ticket.
2402  *
2403  *   etick: points to the body of the session ticket extension.
2404  *   eticklen: the length of the session tickets extenion.
2405  *   sess_id: points at the session ID.
2406  *   sesslen: the length of the session ID.
2407  *   psess: (output) on return, if a ticket was decrypted, then this is set to
2408  *       point to the resulting session.
2409  *
2410  * Returns:
2411  *   -1: fatal error, either from parsing or decrypting the ticket.
2412  *    2: the ticket couldn't be decrypted.
2413  *    3: a ticket was successfully decrypted and *psess was set.
2414  *    4: same as 3, but the ticket needs to be renewed.
2415  */
2416 static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen,
2417                                 const unsigned char *sess_id, int sesslen,
2418                                 SSL_SESSION **psess)
2419         {
2420         SSL_SESSION *sess;
2421         unsigned char *sdec;
2422         const unsigned char *p;
2423         int slen, mlen, renew_ticket = 0;
2424         unsigned char tick_hmac[EVP_MAX_MD_SIZE];
2425         HMAC_CTX hctx;
2426         EVP_CIPHER_CTX ctx;
2427         SSL_CTX *tctx = s->initial_ctx;
2428         /* Need at least keyname + iv + some encrypted data */
2429         if (eticklen < 48)
2430                 return 2;
2431         /* Initialize session ticket encryption and HMAC contexts */
2432         HMAC_CTX_init(&hctx);
2433         EVP_CIPHER_CTX_init(&ctx);
2434         if (tctx->tlsext_ticket_key_cb)
2435                 {
2436                 unsigned char *nctick = (unsigned char *)etick;
2437                 int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
2438                                                         &ctx, &hctx, 0);
2439                 if (rv < 0)
2440                         return -1;
2441                 if (rv == 0)
2442                         return 2;
2443                 if (rv == 2)
2444                         renew_ticket = 1;
2445                 }
2446         else
2447                 {
2448                 /* Check key name matches */
2449                 if (memcmp(etick, tctx->tlsext_tick_key_name, 16))
2450                         return 2;
2451                 HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
2452                                         tlsext_tick_md(), NULL);
2453                 EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
2454                                 tctx->tlsext_tick_aes_key, etick + 16);
2455                 }
2456         /* Attempt to process session ticket, first conduct sanity and
2457          * integrity checks on ticket.
2458          */
2459         mlen = HMAC_size(&hctx);
2460         if (mlen < 0)
2461                 {
2462                 EVP_CIPHER_CTX_cleanup(&ctx);
2463                 return -1;
2464                 }
2465         eticklen -= mlen;
2466         /* Check HMAC of encrypted ticket */
2467         HMAC_Update(&hctx, etick, eticklen);
2468         HMAC_Final(&hctx, tick_hmac, NULL);
2469         HMAC_CTX_cleanup(&hctx);
2470         if (memcmp(tick_hmac, etick + eticklen, mlen))
2471                 return 2;
2472         /* Attempt to decrypt session data */
2473         /* Move p after IV to start of encrypted ticket, update length */
2474         p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx);
2475         eticklen -= 16 + EVP_CIPHER_CTX_iv_length(&ctx);
2476         sdec = OPENSSL_malloc(eticklen);
2477         if (!sdec)
2478                 {
2479                 EVP_CIPHER_CTX_cleanup(&ctx);
2480                 return -1;
2481                 }
2482         EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen);
2483         if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0)
2484                 return 2;
2485         slen += mlen;
2486         EVP_CIPHER_CTX_cleanup(&ctx);
2487         p = sdec;
2488
2489         sess = d2i_SSL_SESSION(NULL, &p, slen);
2490         OPENSSL_free(sdec);
2491         if (sess)
2492                 {
2493                 /* The session ID, if non-empty, is used by some clients to
2494                  * detect that the ticket has been accepted. So we copy it to
2495                  * the session structure. If it is empty set length to zero
2496                  * as required by standard.
2497                  */
2498                 if (sesslen)
2499                         memcpy(sess->session_id, sess_id, sesslen);
2500                 sess->session_id_length = sesslen;
2501                 *psess = sess;
2502                 if (renew_ticket)
2503                         return 4;
2504                 else
2505                         return 3;
2506                 }
2507         ERR_clear_error();
2508         /* For session parse failure, indicate that we need to send a new
2509          * ticket. */
2510         return 2;
2511         }
2512
2513 /* Tables to translate from NIDs to TLS v1.2 ids */
2514
2515 typedef struct 
2516         {
2517         int nid;
2518         int id;
2519         } tls12_lookup;
2520
2521 static tls12_lookup tls12_md[] = {
2522         {NID_md5, TLSEXT_hash_md5},
2523         {NID_sha1, TLSEXT_hash_sha1},
2524         {NID_sha224, TLSEXT_hash_sha224},
2525         {NID_sha256, TLSEXT_hash_sha256},
2526         {NID_sha384, TLSEXT_hash_sha384},
2527         {NID_sha512, TLSEXT_hash_sha512}
2528 };
2529
2530 static tls12_lookup tls12_sig[] = {
2531         {EVP_PKEY_RSA, TLSEXT_signature_rsa},
2532         {EVP_PKEY_DSA, TLSEXT_signature_dsa},
2533         {EVP_PKEY_EC, TLSEXT_signature_ecdsa}
2534 };
2535
2536 static int tls12_find_id(int nid, tls12_lookup *table, size_t tlen)
2537         {
2538         size_t i;
2539         for (i = 0; i < tlen; i++)
2540                 {
2541                 if (table[i].nid == nid)
2542                         return table[i].id;
2543                 }
2544         return -1;
2545         }
2546
2547 static int tls12_find_nid(int id, tls12_lookup *table, size_t tlen)
2548         {
2549         size_t i;
2550         for (i = 0; i < tlen; i++)
2551                 {
2552                 if ((table[i].id) == id)
2553                         return table[i].nid;
2554                 }
2555         return NID_undef;
2556         }
2557
2558 int tls12_get_sigandhash(unsigned char *p, const EVP_PKEY *pk, const EVP_MD *md)
2559         {
2560         int sig_id, md_id;
2561         if (!md)
2562                 return 0;
2563         md_id = tls12_find_id(EVP_MD_type(md), tls12_md,
2564                                 sizeof(tls12_md)/sizeof(tls12_lookup));
2565         if (md_id == -1)
2566                 return 0;
2567         sig_id = tls12_get_sigid(pk);
2568         if (sig_id == -1)
2569                 return 0;
2570         p[0] = (unsigned char)md_id;
2571         p[1] = (unsigned char)sig_id;
2572         return 1;
2573         }
2574
2575 int tls12_get_sigid(const EVP_PKEY *pk)
2576         {
2577         return tls12_find_id(pk->type, tls12_sig,
2578                                 sizeof(tls12_sig)/sizeof(tls12_lookup));
2579         }
2580
2581 const EVP_MD *tls12_get_hash(unsigned char hash_alg)
2582         {
2583         switch(hash_alg)
2584                 {
2585 #ifndef OPENSSL_NO_MD5
2586                 case TLSEXT_hash_md5:
2587 #ifdef OPENSSL_FIPS
2588                 if (FIPS_mode())
2589                         return NULL;
2590 #endif
2591                 return EVP_md5();
2592 #endif
2593 #ifndef OPENSSL_NO_SHA
2594                 case TLSEXT_hash_sha1:
2595                 return EVP_sha1();
2596 #endif
2597 #ifndef OPENSSL_NO_SHA256
2598                 case TLSEXT_hash_sha224:
2599                 return EVP_sha224();
2600
2601                 case TLSEXT_hash_sha256:
2602                 return EVP_sha256();
2603 #endif
2604 #ifndef OPENSSL_NO_SHA512
2605                 case TLSEXT_hash_sha384:
2606                 return EVP_sha384();
2607
2608                 case TLSEXT_hash_sha512:
2609                 return EVP_sha512();
2610 #endif
2611                 default:
2612                 return NULL;
2613
2614                 }
2615         }
2616
2617 /* Set preferred digest for each key type */
2618
2619 int tls1_process_sigalgs(SSL *s, const unsigned char *data, int dsize)
2620         {
2621         int i, idx;
2622         const EVP_MD *md;
2623         CERT *c = s->cert;
2624         TLS_SIGALGS *sigptr;
2625         /* Extension ignored for TLS versions below 1.2 */
2626         if (TLS1_get_version(s) < TLS1_2_VERSION)
2627                 return 1;
2628         /* Should never happen */
2629         if (!c)
2630                 return 0;
2631
2632         c->pkeys[SSL_PKEY_DSA_SIGN].digest = NULL;
2633         c->pkeys[SSL_PKEY_RSA_SIGN].digest = NULL;
2634         c->pkeys[SSL_PKEY_RSA_ENC].digest = NULL;
2635         c->pkeys[SSL_PKEY_ECC].digest = NULL;
2636
2637         if (c->sigalgs)
2638                 OPENSSL_free(c->sigalgs);
2639         c->sigalgs = OPENSSL_malloc((dsize/2) * sizeof(TLS_SIGALGS));
2640         if (!c->sigalgs)
2641                 return 0;
2642         c->sigalgslen = dsize/2;
2643
2644         for (i = 0, sigptr = c->sigalgs; i < dsize; i += 2, sigptr++)
2645                 {
2646                 sigptr->rhash = data[i];
2647                 sigptr->rsign = data[i + 1];
2648                 sigptr->hash_nid = tls12_find_nid(sigptr->rhash, tls12_md,
2649                                         sizeof(tls12_md)/sizeof(tls12_lookup));
2650                 sigptr->sign_nid = tls12_find_nid(sigptr->rsign, tls12_sig,
2651                                         sizeof(tls12_sig)/sizeof(tls12_lookup));
2652                 if (!OBJ_find_sigid_by_algs(&sigptr->signandhash_nid,
2653                                                 sigptr->hash_nid,
2654                                                 sigptr->sign_nid))
2655                         sigptr->signandhash_nid = NID_undef;
2656                 switch(sigptr->rsign)
2657                         {
2658 #ifndef OPENSSL_NO_RSA
2659                         case TLSEXT_signature_rsa:
2660                         idx = SSL_PKEY_RSA_SIGN;
2661                         break;
2662 #endif
2663 #ifndef OPENSSL_NO_DSA
2664                         case TLSEXT_signature_dsa:
2665                         idx = SSL_PKEY_DSA_SIGN;
2666                         break;
2667 #endif
2668 #ifndef OPENSSL_NO_ECDSA
2669                         case TLSEXT_signature_ecdsa:
2670                         idx = SSL_PKEY_ECC;
2671                         break;
2672 #endif
2673                         default:
2674                         continue;
2675                         }
2676
2677                 if (c->pkeys[idx].digest == NULL)
2678                         {
2679                         md = tls12_get_hash(sigptr->rhash);
2680                         if (md)
2681                                 {
2682                                 c->pkeys[idx].digest = md;
2683                                 if (idx == SSL_PKEY_RSA_SIGN)
2684                                         c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
2685                                 }
2686                         }
2687
2688                 }
2689
2690
2691         /* Set any remaining keys to default values. NOTE: if alg is not
2692          * supported it stays as NULL.
2693          */
2694 #ifndef OPENSSL_NO_DSA
2695         if (!c->pkeys[SSL_PKEY_DSA_SIGN].digest)
2696                 c->pkeys[SSL_PKEY_DSA_SIGN].digest = EVP_dss1();
2697 #endif
2698 #ifndef OPENSSL_NO_RSA
2699         if (!c->pkeys[SSL_PKEY_RSA_SIGN].digest)
2700                 {
2701                 c->pkeys[SSL_PKEY_RSA_SIGN].digest = EVP_sha1();
2702                 c->pkeys[SSL_PKEY_RSA_ENC].digest = EVP_sha1();
2703                 }
2704 #endif
2705 #ifndef OPENSSL_NO_ECDSA
2706         if (!c->pkeys[SSL_PKEY_ECC].digest)
2707                 c->pkeys[SSL_PKEY_ECC].digest = EVP_ecdsa();
2708 #endif
2709         return 1;
2710         }
2711
2712 #endif
2713
2714 int SSL_get_sigalgs(SSL *s, int idx,
2715                         int *psign, int *phash, int *psignandhash,
2716                         unsigned char *rsig, unsigned char *rhash)
2717         {
2718         if (s->cert->sigalgs == NULL)
2719                 return 0;
2720         if (idx >= 0)
2721                 {
2722                 TLS_SIGALGS *psig;
2723                 if (idx >= (int)s->cert->sigalgslen)
2724                         return 0;
2725                 psig = s->cert->sigalgs + idx;
2726                 if (psign)
2727                         *psign = psig->sign_nid;
2728                 if (phash)
2729                         *phash = psig->hash_nid;
2730                 if (psignandhash)
2731                         *psignandhash = psig->signandhash_nid;
2732                 if (rsig)
2733                         *rsig = psig->rsign;
2734                 if (rhash)
2735                         *rhash = psig->rhash;
2736                 }
2737         return s->cert->sigalgslen;
2738         }
2739         
2740
2741 #ifndef OPENSSL_NO_HEARTBEATS
2742 int
2743 tls1_process_heartbeat(SSL *s)
2744         {
2745         unsigned char *p = &s->s3->rrec.data[0], *pl;
2746         unsigned short hbtype;
2747         unsigned int payload;
2748         unsigned int padding = 16; /* Use minimum padding */
2749
2750         /* Read type and payload length first */
2751         hbtype = *p++;
2752         n2s(p, payload);
2753         pl = p;
2754
2755         if (s->msg_callback)
2756                 s->msg_callback(0, s->version, TLS1_RT_HEARTBEAT,
2757                         &s->s3->rrec.data[0], s->s3->rrec.length,
2758                         s, s->msg_callback_arg);
2759
2760         if (hbtype == TLS1_HB_REQUEST)
2761                 {
2762                 unsigned char *buffer, *bp;
2763                 int r;
2764
2765                 /* Allocate memory for the response, size is 1 bytes
2766                  * message type, plus 2 bytes payload length, plus
2767                  * payload, plus padding
2768                  */
2769                 buffer = OPENSSL_malloc(1 + 2 + payload + padding);
2770                 bp = buffer;
2771                 
2772                 /* Enter response type, length and copy payload */
2773                 *bp++ = TLS1_HB_RESPONSE;
2774                 s2n(payload, bp);
2775                 memcpy(bp, pl, payload);
2776                 bp += payload;
2777                 /* Random padding */
2778                 RAND_pseudo_bytes(bp, padding);
2779
2780                 r = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buffer, 3 + payload + padding);
2781
2782                 if (r >= 0 && s->msg_callback)
2783                         s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
2784                                 buffer, 3 + payload + padding,
2785                                 s, s->msg_callback_arg);
2786
2787                 OPENSSL_free(buffer);
2788
2789                 if (r < 0)
2790                         return r;
2791                 }
2792         else if (hbtype == TLS1_HB_RESPONSE)
2793                 {
2794                 unsigned int seq;
2795                 
2796                 /* We only send sequence numbers (2 bytes unsigned int),
2797                  * and 16 random bytes, so we just try to read the
2798                  * sequence number */
2799                 n2s(pl, seq);
2800                 
2801                 if (payload == 18 && seq == s->tlsext_hb_seq)
2802                         {
2803                         s->tlsext_hb_seq++;
2804                         s->tlsext_hb_pending = 0;
2805                         }
2806                 }
2807
2808         return 0;
2809         }
2810
2811 int
2812 tls1_heartbeat(SSL *s)
2813         {
2814         unsigned char *buf, *p;
2815         int ret;
2816         unsigned int payload = 18; /* Sequence number + random bytes */
2817         unsigned int padding = 16; /* Use minimum padding */
2818
2819         /* Only send if peer supports and accepts HB requests... */
2820         if (!(s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) ||
2821             s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_SEND_REQUESTS)
2822                 {
2823                 SSLerr(SSL_F_TLS1_HEARTBEAT,SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT);
2824                 return -1;
2825                 }
2826
2827         /* ...and there is none in flight yet... */
2828         if (s->tlsext_hb_pending)
2829                 {
2830                 SSLerr(SSL_F_TLS1_HEARTBEAT,SSL_R_TLS_HEARTBEAT_PENDING);
2831                 return -1;
2832                 }
2833                 
2834         /* ...and no handshake in progress. */
2835         if (SSL_in_init(s) || s->in_handshake)
2836                 {
2837                 SSLerr(SSL_F_TLS1_HEARTBEAT,SSL_R_UNEXPECTED_MESSAGE);
2838                 return -1;
2839                 }
2840                 
2841         /* Check if padding is too long, payload and padding
2842          * must not exceed 2^14 - 3 = 16381 bytes in total.
2843          */
2844         OPENSSL_assert(payload + padding <= 16381);
2845
2846         /* Create HeartBeat message, we just use a sequence number
2847          * as payload to distuingish different messages and add
2848          * some random stuff.
2849          *  - Message Type, 1 byte
2850          *  - Payload Length, 2 bytes (unsigned int)
2851          *  - Payload, the sequence number (2 bytes uint)
2852          *  - Payload, random bytes (16 bytes uint)
2853          *  - Padding
2854          */
2855         buf = OPENSSL_malloc(1 + 2 + payload + padding);
2856         p = buf;
2857         /* Message Type */
2858         *p++ = TLS1_HB_REQUEST;
2859         /* Payload length (18 bytes here) */
2860         s2n(payload, p);
2861         /* Sequence number */
2862         s2n(s->tlsext_hb_seq, p);
2863         /* 16 random bytes */
2864         RAND_pseudo_bytes(p, 16);
2865         p += 16;
2866         /* Random padding */
2867         RAND_pseudo_bytes(p, padding);
2868
2869         ret = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buf, 3 + payload + padding);
2870         if (ret >= 0)
2871                 {
2872                 if (s->msg_callback)
2873                         s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
2874                                 buf, 3 + payload + padding,
2875                                 s, s->msg_callback_arg);
2876
2877                 s->tlsext_hb_pending = 1;
2878                 }
2879                 
2880         OPENSSL_free(buf);
2881
2882         return ret;
2883         }
2884 #endif