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