Abort handshake if signature algorithm used not supported by peer.
[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(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 /* Check signature algorithm is consistent with sent supported signature
684  * algorithms and if so return relevant digest.
685  */
686 int tls12_check_peer_sigalg(const EVP_MD **pmd, SSL *s,
687                                 const unsigned char *sig, EVP_PKEY *pkey)
688         {
689         const unsigned char *sent_sigs;
690         size_t sent_sigslen, i;
691         int sigalg = tls12_get_sigid(pkey);
692         /* Should never happen */
693         if (sigalg == -1)
694                 return -1;
695         /* Check key type is consistent with signature */
696         if (sigalg != (int)sig[1])
697                 {
698                 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_WRONG_SIGNATURE_TYPE);
699                 return 0;
700                 }
701         /* Check signature matches a type we sent */
702         sent_sigslen = tls12_get_psigalgs(s, &sent_sigs);
703         for (i = 0; i < sent_sigslen; i+=2, sent_sigs+=2)
704                 {
705                 if (sig[0] == sent_sigs[0] && sig[1] == sent_sigs[1])
706                         break;
707                 }
708         /* Allow fallback to SHA1 if not strict mode */
709         if (i == sent_sigslen && (sig[0] != TLSEXT_hash_sha1 || s->cert->cert_flags & SSL_CERT_FLAG_TLS_STRICT))
710                 {
711                 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_WRONG_SIGNATURE_TYPE);
712                 return 0;
713                 }
714         *pmd = tls12_get_hash(sig[0]);
715         if (*pmd == NULL)
716                 {
717                 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_UNKNOWN_DIGEST);
718                 return 0;
719                 }
720         return 1;
721         }
722 /* Get a mask of disabled algorithms: an algorithm is disabled
723  * if it isn't supported or doesn't appear in supported signature
724  * algorithms. Unlike ssl_cipher_get_disabled this applies to a specific
725  * session and not global settings.
726  * 
727  */
728 void ssl_set_client_disabled(SSL *s)
729         {
730         CERT *c = s->cert;
731         const unsigned char *sigalgs;
732         size_t i, sigalgslen;
733         int have_rsa = 0, have_dsa = 0, have_ecdsa = 0;
734         c->mask_a = 0;
735         c->mask_k = 0;
736         /* If less than TLS 1.2 don't allow TLS 1.2 only ciphers */
737         if (TLS1_get_version(s) < TLS1_2_VERSION)
738                 c->mask_ssl = SSL_TLSV1_2;
739         else
740                 c->mask_ssl = 0;
741         /* Now go through all signature algorithms seeing if we support
742          * any for RSA, DSA, ECDSA. Do this for all versions not just
743          * TLS 1.2.
744          */
745         sigalgslen = tls12_get_psigalgs(s, &sigalgs);
746         for (i = 0; i < sigalgslen; i += 2, sigalgs += 2)
747                 {
748                 switch(sigalgs[1])
749                         {
750 #ifndef OPENSSL_NO_RSA
751                 case TLSEXT_signature_rsa:
752                         have_rsa = 1;
753                         break;
754 #endif
755 #ifndef OPENSSL_NO_DSA
756                 case TLSEXT_signature_dsa:
757                         have_dsa = 1;
758                         break;
759 #endif
760 #ifndef OPENSSL_NO_ECDSA
761                 case TLSEXT_signature_ecdsa:
762                         have_ecdsa = 1;
763                         break;
764 #endif
765                         }
766                 }
767         /* Disable auth and static DH if we don't include any appropriate
768          * signature algorithms.
769          */
770         if (!have_rsa)
771                 {
772                 c->mask_a |= SSL_aRSA;
773                 c->mask_k |= SSL_kDHr|SSL_kECDHr;
774                 }
775         if (!have_dsa)
776                 {
777                 c->mask_a |= SSL_aDSS;
778                 c->mask_k |= SSL_kDHd;
779                 }
780         if (!have_ecdsa)
781                 {
782                 c->mask_a |= SSL_aECDSA;
783                 c->mask_k |= SSL_kECDHe;
784                 }
785 #ifndef OPENSSL_NO_KRB5
786         if (!kssl_tgt_is_available(s->kssl_ctx))
787                 {
788                 c->mask_a |= SSL_aKRB5;
789                 c->mask_k |= SSL_kKRB5;
790                 }
791 #endif
792 #ifndef OPENSSL_NO_PSK
793         /* with PSK there must be client callback set */
794         if (!s->psk_client_callback)
795                 {
796                 c->mask_a |= SSL_aPSK;
797                 c->mask_k |= SSL_kPSK;
798                 }
799 #endif /* OPENSSL_NO_PSK */
800         c->valid = 1;
801         }
802
803 /* byte_compare is a compare function for qsort(3) that compares bytes. */
804 static int byte_compare(const void *in_a, const void *in_b)
805         {
806         unsigned char a = *((const unsigned char*) in_a);
807         unsigned char b = *((const unsigned char*) in_b);
808
809         if (a > b)
810                 return 1;
811         else if (a < b)
812                 return -1;
813         return 0;
814 }
815
816 unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *p, unsigned char *limit)
817         {
818         int extdatalen=0;
819         unsigned char *ret = p;
820 #ifndef OPENSSL_NO_EC
821         /* See if we support any ECC ciphersuites */
822         int using_ecc = 0;
823         if (s->version != DTLS1_VERSION && s->version >= TLS1_VERSION)
824                 {
825                 int i;
826                 unsigned long alg_k, alg_a;
827                 STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(s);
828
829                 for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++)
830                         {
831                         SSL_CIPHER *c = sk_SSL_CIPHER_value(cipher_stack, i);
832
833                         alg_k = c->algorithm_mkey;
834                         alg_a = c->algorithm_auth;
835                         if ((alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)
836                                 || (alg_a & SSL_aECDSA)))
837                                 {
838                                 using_ecc = 1;
839                                 break;
840                                 }
841                         }
842                 }
843 #endif
844
845         /* don't add extensions for SSLv3 unless doing secure renegotiation */
846         if (s->client_version == SSL3_VERSION
847                                         && !s->s3->send_connection_binding)
848                 return p;
849
850         ret+=2;
851
852         if (ret>=limit) return NULL; /* this really never occurs, but ... */
853
854         if (s->tlsext_hostname != NULL)
855                 { 
856                 /* Add TLS extension servername to the Client Hello message */
857                 unsigned long size_str;
858                 long lenmax; 
859
860                 /* check for enough space.
861                    4 for the servername type and entension length
862                    2 for servernamelist length
863                    1 for the hostname type
864                    2 for hostname length
865                    + hostname length 
866                 */
867                    
868                 if ((lenmax = limit - ret - 9) < 0 
869                     || (size_str = strlen(s->tlsext_hostname)) > (unsigned long)lenmax) 
870                         return NULL;
871                         
872                 /* extension type and length */
873                 s2n(TLSEXT_TYPE_server_name,ret); 
874                 s2n(size_str+5,ret);
875                 
876                 /* length of servername list */
877                 s2n(size_str+3,ret);
878         
879                 /* hostname type, length and hostname */
880                 *(ret++) = (unsigned char) TLSEXT_NAMETYPE_host_name;
881                 s2n(size_str,ret);
882                 memcpy(ret, s->tlsext_hostname, size_str);
883                 ret+=size_str;
884                 }
885
886         /* Add RI if renegotiating */
887         if (s->renegotiate)
888           {
889           int el;
890           
891           if(!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0))
892               {
893               SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
894               return NULL;
895               }
896
897           if((limit - p - 4 - el) < 0) return NULL;
898           
899           s2n(TLSEXT_TYPE_renegotiate,ret);
900           s2n(el,ret);
901
902           if(!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el))
903               {
904               SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
905               return NULL;
906               }
907
908           ret += el;
909         }
910
911 #ifndef OPENSSL_NO_SRP
912         /* Add SRP username if there is one */
913         if (s->srp_ctx.login != NULL)
914                 { /* Add TLS extension SRP username to the Client Hello message */
915
916                 int login_len = strlen(s->srp_ctx.login);       
917                 if (login_len > 255 || login_len == 0)
918                         {
919                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
920                         return NULL;
921                         } 
922
923                 /* check for enough space.
924                    4 for the srp type type and entension length
925                    1 for the srp user identity
926                    + srp user identity length 
927                 */
928                 if ((limit - ret - 5 - login_len) < 0) return NULL; 
929
930                 /* fill in the extension */
931                 s2n(TLSEXT_TYPE_srp,ret);
932                 s2n(login_len+1,ret);
933                 (*ret++) = (unsigned char) login_len;
934                 memcpy(ret, s->srp_ctx.login, login_len);
935                 ret+=login_len;
936                 }
937 #endif
938
939 #ifndef OPENSSL_NO_EC
940         if (using_ecc)
941                 {
942                 /* Add TLS extension ECPointFormats to the ClientHello message */
943                 long lenmax; 
944                 const unsigned char *plist;
945                 size_t plistlen;
946                 /* If we have a custom point format list use it otherwise
947                  * use default */
948                 plist = s->tlsext_ecpointformatlist;
949                 if (plist)
950                         plistlen = s->tlsext_ecpointformatlist_length;
951                 else
952                         {
953                         plist = ecformats_default;
954                         plistlen = sizeof(ecformats_default);
955                         }
956
957                 if ((lenmax = limit - ret - 5) < 0) return NULL; 
958                 if (plistlen > (size_t)lenmax) return NULL;
959                 if (plistlen > 255)
960                         {
961                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
962                         return NULL;
963                         }
964                 
965                 s2n(TLSEXT_TYPE_ec_point_formats,ret);
966                 s2n(plistlen + 1,ret);
967                 *(ret++) = (unsigned char)plistlen ;
968                 memcpy(ret, plist, plistlen);
969                 ret+=plistlen;
970
971                 /* Add TLS extension EllipticCurves to the ClientHello message */
972                 plist = s->tlsext_ellipticcurvelist;
973                 tls1_get_curvelist(s, 0, &plist, &plistlen);
974
975                 if ((lenmax = limit - ret - 6) < 0) return NULL; 
976                 if (plistlen > (size_t)lenmax) return NULL;
977                 if (plistlen > 65532)
978                         {
979                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
980                         return NULL;
981                         }
982                 
983                 s2n(TLSEXT_TYPE_elliptic_curves,ret);
984                 s2n(plistlen + 2, ret);
985
986                 /* NB: draft-ietf-tls-ecc-12.txt uses a one-byte prefix for
987                  * elliptic_curve_list, but the examples use two bytes.
988                  * http://www1.ietf.org/mail-archive/web/tls/current/msg00538.html
989                  * resolves this to two bytes.
990                  */
991                 s2n(plistlen, ret);
992                 memcpy(ret, plist, plistlen);
993                 ret+=plistlen;
994                 }
995 #endif /* OPENSSL_NO_EC */
996
997         if (!(SSL_get_options(s) & SSL_OP_NO_TICKET))
998                 {
999                 int ticklen;
1000                 if (!s->new_session && s->session && s->session->tlsext_tick)
1001                         ticklen = s->session->tlsext_ticklen;
1002                 else if (s->session && s->tlsext_session_ticket &&
1003                          s->tlsext_session_ticket->data)
1004                         {
1005                         ticklen = s->tlsext_session_ticket->length;
1006                         s->session->tlsext_tick = OPENSSL_malloc(ticklen);
1007                         if (!s->session->tlsext_tick)
1008                                 return NULL;
1009                         memcpy(s->session->tlsext_tick,
1010                                s->tlsext_session_ticket->data,
1011                                ticklen);
1012                         s->session->tlsext_ticklen = ticklen;
1013                         }
1014                 else
1015                         ticklen = 0;
1016                 if (ticklen == 0 && s->tlsext_session_ticket &&
1017                     s->tlsext_session_ticket->data == NULL)
1018                         goto skip_ext;
1019                 /* Check for enough room 2 for extension type, 2 for len
1020                  * rest for ticket
1021                  */
1022                 if ((long)(limit - ret - 4 - ticklen) < 0) return NULL;
1023                 s2n(TLSEXT_TYPE_session_ticket,ret); 
1024                 s2n(ticklen,ret);
1025                 if (ticklen)
1026                         {
1027                         memcpy(ret, s->session->tlsext_tick, ticklen);
1028                         ret += ticklen;
1029                         }
1030                 }
1031                 skip_ext:
1032
1033         if (TLS1_get_client_version(s) >= TLS1_2_VERSION)
1034                 {
1035                 size_t salglen;
1036                 const unsigned char *salg;
1037                 salglen = tls12_get_psigalgs(s, &salg);
1038                 if ((size_t)(limit - ret) < salglen + 6)
1039                         return NULL; 
1040                 s2n(TLSEXT_TYPE_signature_algorithms,ret);
1041                 s2n(salglen + 2, ret);
1042                 s2n(salglen, ret);
1043                 memcpy(ret, salg, salglen);
1044                 ret += salglen;
1045                 }
1046
1047 #ifdef TLSEXT_TYPE_opaque_prf_input
1048         if (s->s3->client_opaque_prf_input != NULL &&
1049             s->version != DTLS1_VERSION)
1050                 {
1051                 size_t col = s->s3->client_opaque_prf_input_len;
1052                 
1053                 if ((long)(limit - ret - 6 - col < 0))
1054                         return NULL;
1055                 if (col > 0xFFFD) /* can't happen */
1056                         return NULL;
1057
1058                 s2n(TLSEXT_TYPE_opaque_prf_input, ret); 
1059                 s2n(col + 2, ret);
1060                 s2n(col, ret);
1061                 memcpy(ret, s->s3->client_opaque_prf_input, col);
1062                 ret += col;
1063                 }
1064 #endif
1065
1066         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp &&
1067             s->version != DTLS1_VERSION)
1068                 {
1069                 int i;
1070                 long extlen, idlen, itmp;
1071                 OCSP_RESPID *id;
1072
1073                 idlen = 0;
1074                 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
1075                         {
1076                         id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
1077                         itmp = i2d_OCSP_RESPID(id, NULL);
1078                         if (itmp <= 0)
1079                                 return NULL;
1080                         idlen += itmp + 2;
1081                         }
1082
1083                 if (s->tlsext_ocsp_exts)
1084                         {
1085                         extlen = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL);
1086                         if (extlen < 0)
1087                                 return NULL;
1088                         }
1089                 else
1090                         extlen = 0;
1091                         
1092                 if ((long)(limit - ret - 7 - extlen - idlen) < 0) return NULL;
1093                 s2n(TLSEXT_TYPE_status_request, ret);
1094                 if (extlen + idlen > 0xFFF0)
1095                         return NULL;
1096                 s2n(extlen + idlen + 5, ret);
1097                 *(ret++) = TLSEXT_STATUSTYPE_ocsp;
1098                 s2n(idlen, ret);
1099                 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
1100                         {
1101                         /* save position of id len */
1102                         unsigned char *q = ret;
1103                         id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
1104                         /* skip over id len */
1105                         ret += 2;
1106                         itmp = i2d_OCSP_RESPID(id, &ret);
1107                         /* write id len */
1108                         s2n(itmp, q);
1109                         }
1110                 s2n(extlen, ret);
1111                 if (extlen > 0)
1112                         i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret);
1113                 }
1114
1115 #ifndef OPENSSL_NO_HEARTBEATS
1116         /* Add Heartbeat extension */
1117         s2n(TLSEXT_TYPE_heartbeat,ret);
1118         s2n(1,ret);
1119         /* Set mode:
1120          * 1: peer may send requests
1121          * 2: peer not allowed to send requests
1122          */
1123         if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1124                 *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1125         else
1126                 *(ret++) = SSL_TLSEXT_HB_ENABLED;
1127 #endif
1128
1129 #ifndef OPENSSL_NO_NEXTPROTONEG
1130         if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len)
1131                 {
1132                 /* The client advertises an emtpy extension to indicate its
1133                  * support for Next Protocol Negotiation */
1134                 if (limit - ret - 4 < 0)
1135                         return NULL;
1136                 s2n(TLSEXT_TYPE_next_proto_neg,ret);
1137                 s2n(0,ret);
1138                 }
1139 #endif
1140
1141         if(SSL_get_srtp_profiles(s))
1142                 {
1143                 int el;
1144
1145                 ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0);
1146                 
1147                 if((limit - p - 4 - el) < 0) return NULL;
1148
1149                 s2n(TLSEXT_TYPE_use_srtp,ret);
1150                 s2n(el,ret);
1151
1152                 if(ssl_add_clienthello_use_srtp_ext(s, ret, &el, el))
1153                         {
1154                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1155                         return NULL;
1156                         }
1157                 ret += el;
1158                 }
1159
1160         /* Add TLS extension Server_Authz_DataFormats to the ClientHello */
1161         /* 2 bytes for extension type */
1162         /* 2 bytes for extension length */
1163         /* 1 byte for the list length */
1164         /* 1 byte for the list (we only support audit proofs) */
1165         if (s->ctx->tlsext_authz_server_audit_proof_cb != NULL)
1166                 {
1167                 size_t lenmax;
1168                 const unsigned short ext_len = 2;
1169                 const unsigned char list_len = 1;
1170
1171                 if ((lenmax = limit - ret - 6) < 0) return NULL;
1172
1173                 s2n(TLSEXT_TYPE_server_authz, ret);
1174                 /* Extension length: 2 bytes */
1175                 s2n(ext_len, ret);
1176                 *(ret++) = list_len;
1177                 *(ret++) = TLSEXT_AUTHZDATAFORMAT_audit_proof;
1178                 }
1179
1180         if ((extdatalen = ret-p-2) == 0)
1181                 return p;
1182
1183         s2n(extdatalen,p);
1184         return ret;
1185         }
1186
1187 unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *p, unsigned char *limit)
1188         {
1189         int extdatalen=0;
1190         unsigned char *ret = p;
1191 #ifndef OPENSSL_NO_NEXTPROTONEG
1192         int next_proto_neg_seen;
1193 #endif
1194
1195         /* don't add extensions for SSLv3, unless doing secure renegotiation */
1196         if (s->version == SSL3_VERSION && !s->s3->send_connection_binding)
1197                 return p;
1198         
1199         ret+=2;
1200         if (ret>=limit) return NULL; /* this really never occurs, but ... */
1201
1202         if (!s->hit && s->servername_done == 1 && s->session->tlsext_hostname != NULL)
1203                 { 
1204                 if ((long)(limit - ret - 4) < 0) return NULL; 
1205
1206                 s2n(TLSEXT_TYPE_server_name,ret);
1207                 s2n(0,ret);
1208                 }
1209
1210         if(s->s3->send_connection_binding)
1211         {
1212           int el;
1213           
1214           if(!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0))
1215               {
1216               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1217               return NULL;
1218               }
1219
1220           if((limit - p - 4 - el) < 0) return NULL;
1221           
1222           s2n(TLSEXT_TYPE_renegotiate,ret);
1223           s2n(el,ret);
1224
1225           if(!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el))
1226               {
1227               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1228               return NULL;
1229               }
1230
1231           ret += el;
1232         }
1233
1234 #ifndef OPENSSL_NO_EC
1235         if (s->tlsext_ecpointformatlist != NULL &&
1236             s->version != DTLS1_VERSION)
1237                 {
1238                 /* Add TLS extension ECPointFormats to the ServerHello message */
1239                 long lenmax; 
1240
1241                 if ((lenmax = limit - ret - 5) < 0) return NULL; 
1242                 if (s->tlsext_ecpointformatlist_length > (unsigned long)lenmax) return NULL;
1243                 if (s->tlsext_ecpointformatlist_length > 255)
1244                         {
1245                         SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1246                         return NULL;
1247                         }
1248                 
1249                 s2n(TLSEXT_TYPE_ec_point_formats,ret);
1250                 s2n(s->tlsext_ecpointformatlist_length + 1,ret);
1251                 *(ret++) = (unsigned char) s->tlsext_ecpointformatlist_length;
1252                 memcpy(ret, s->tlsext_ecpointformatlist, s->tlsext_ecpointformatlist_length);
1253                 ret+=s->tlsext_ecpointformatlist_length;
1254
1255                 }
1256         /* Currently the server should not respond with a SupportedCurves extension */
1257 #endif /* OPENSSL_NO_EC */
1258
1259         if (s->tlsext_ticket_expected
1260                 && !(SSL_get_options(s) & SSL_OP_NO_TICKET)) 
1261                 { 
1262                 if ((long)(limit - ret - 4) < 0) return NULL; 
1263                 s2n(TLSEXT_TYPE_session_ticket,ret);
1264                 s2n(0,ret);
1265                 }
1266
1267         if (s->tlsext_status_expected)
1268                 { 
1269                 if ((long)(limit - ret - 4) < 0) return NULL; 
1270                 s2n(TLSEXT_TYPE_status_request,ret);
1271                 s2n(0,ret);
1272                 }
1273
1274 #ifdef TLSEXT_TYPE_opaque_prf_input
1275         if (s->s3->server_opaque_prf_input != NULL &&
1276             s->version != DTLS1_VERSION)
1277                 {
1278                 size_t sol = s->s3->server_opaque_prf_input_len;
1279                 
1280                 if ((long)(limit - ret - 6 - sol) < 0)
1281                         return NULL;
1282                 if (sol > 0xFFFD) /* can't happen */
1283                         return NULL;
1284
1285                 s2n(TLSEXT_TYPE_opaque_prf_input, ret); 
1286                 s2n(sol + 2, ret);
1287                 s2n(sol, ret);
1288                 memcpy(ret, s->s3->server_opaque_prf_input, sol);
1289                 ret += sol;
1290                 }
1291 #endif
1292
1293         if(s->srtp_profile)
1294                 {
1295                 int el;
1296
1297                 ssl_add_serverhello_use_srtp_ext(s, 0, &el, 0);
1298                 
1299                 if((limit - p - 4 - el) < 0) return NULL;
1300
1301                 s2n(TLSEXT_TYPE_use_srtp,ret);
1302                 s2n(el,ret);
1303
1304                 if(ssl_add_serverhello_use_srtp_ext(s, ret, &el, el))
1305                         {
1306                         SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1307                         return NULL;
1308                         }
1309                 ret+=el;
1310                 }
1311
1312         if (((s->s3->tmp.new_cipher->id & 0xFFFF)==0x80 || (s->s3->tmp.new_cipher->id & 0xFFFF)==0x81) 
1313                 && (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG))
1314                 { const unsigned char cryptopro_ext[36] = {
1315                         0xfd, 0xe8, /*65000*/
1316                         0x00, 0x20, /*32 bytes length*/
1317                         0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85, 
1318                         0x03,   0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06, 
1319                         0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08, 
1320                         0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17};
1321                         if (limit-ret<36) return NULL;
1322                         memcpy(ret,cryptopro_ext,36);
1323                         ret+=36;
1324
1325                 }
1326
1327 #ifndef OPENSSL_NO_HEARTBEATS
1328         /* Add Heartbeat extension if we've received one */
1329         if (s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED)
1330                 {
1331                 s2n(TLSEXT_TYPE_heartbeat,ret);
1332                 s2n(1,ret);
1333                 /* Set mode:
1334                  * 1: peer may send requests
1335                  * 2: peer not allowed to send requests
1336                  */
1337                 if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1338                         *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1339                 else
1340                         *(ret++) = SSL_TLSEXT_HB_ENABLED;
1341
1342                 }
1343 #endif
1344
1345 #ifndef OPENSSL_NO_NEXTPROTONEG
1346         next_proto_neg_seen = s->s3->next_proto_neg_seen;
1347         s->s3->next_proto_neg_seen = 0;
1348         if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb)
1349                 {
1350                 const unsigned char *npa;
1351                 unsigned int npalen;
1352                 int r;
1353
1354                 r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen, s->ctx->next_protos_advertised_cb_arg);
1355                 if (r == SSL_TLSEXT_ERR_OK)
1356                         {
1357                         if ((long)(limit - ret - 4 - npalen) < 0) return NULL;
1358                         s2n(TLSEXT_TYPE_next_proto_neg,ret);
1359                         s2n(npalen,ret);
1360                         memcpy(ret, npa, npalen);
1361                         ret += npalen;
1362                         s->s3->next_proto_neg_seen = 1;
1363                         }
1364                 }
1365 #endif
1366
1367         /* If the client supports authz then see whether we have any to offer
1368          * to it. */
1369         if (s->s3->tlsext_authz_client_types_len)
1370                 {
1371                 size_t authz_length;
1372                 /* By now we already know the new cipher, so we can look ahead
1373                  * to see whether the cert we are going to send
1374                  * has any authz data attached to it. */
1375                 const unsigned char* authz = ssl_get_authz_data(s, &authz_length);
1376                 const unsigned char* const orig_authz = authz;
1377                 size_t i;
1378                 unsigned authz_count = 0;
1379
1380                 /* The authz data contains a number of the following structures:
1381                  *      uint8_t authz_type
1382                  *      uint16_t length
1383                  *      uint8_t data[length]
1384                  *
1385                  * First we walk over it to find the number of authz elements. */
1386                 for (i = 0; i < authz_length; i++)
1387                         {
1388                         unsigned short length;
1389                         unsigned char type;
1390
1391                         type = *(authz++);
1392                         if (memchr(s->s3->tlsext_authz_client_types,
1393                                    type,
1394                                    s->s3->tlsext_authz_client_types_len) != NULL)
1395                                 authz_count++;
1396
1397                         n2s(authz, length);
1398                         /* n2s increments authz by 2 */
1399                         i += 2;
1400                         authz += length;
1401                         i += length;
1402                         }
1403
1404                 if (authz_count)
1405                         {
1406                         /* Add TLS extension server_authz to the ServerHello message
1407                          * 2 bytes for extension type
1408                          * 2 bytes for extension length
1409                          * 1 byte for the list length
1410                          * n bytes for the list */
1411                         const unsigned short ext_len = 1 + authz_count;
1412
1413                         if ((long)(limit - ret - 4 - ext_len) < 0) return NULL;
1414                         s2n(TLSEXT_TYPE_server_authz, ret);
1415                         s2n(ext_len, ret);
1416                         *(ret++) = authz_count;
1417                         s->s3->tlsext_authz_promised_to_client = 1;
1418                         }
1419
1420                 authz = orig_authz;
1421                 for (i = 0; i < authz_length; i++)
1422                         {
1423                         unsigned short length;
1424                         unsigned char type;
1425
1426                         authz_count++;
1427                         type = *(authz++);
1428                         if (memchr(s->s3->tlsext_authz_client_types,
1429                                    type,
1430                                    s->s3->tlsext_authz_client_types_len) != NULL)
1431                                 *(ret++) = type;
1432                         n2s(authz, length);
1433                         /* n2s increments authz by 2 */
1434                         i += 2;
1435                         authz += length;
1436                         i += length;
1437                         }
1438                 }
1439
1440         if ((extdatalen = ret-p-2)== 0) 
1441                 return p;
1442
1443         s2n(extdatalen,p);
1444         return ret;
1445         }
1446
1447 static int ssl_scan_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al) 
1448         {       
1449         unsigned short type;
1450         unsigned short size;
1451         unsigned short len;
1452         unsigned char *data = *p;
1453         int renegotiate_seen = 0;
1454
1455         s->servername_done = 0;
1456         s->tlsext_status_type = -1;
1457 #ifndef OPENSSL_NO_NEXTPROTONEG
1458         s->s3->next_proto_neg_seen = 0;
1459 #endif
1460
1461 #ifndef OPENSSL_NO_HEARTBEATS
1462         s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
1463                                SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
1464 #endif
1465         /* Clear any signature algorithms extension received */
1466         if (s->cert->peer_sigalgs)
1467                 {
1468                 OPENSSL_free(s->cert->peer_sigalgs);
1469                 s->cert->peer_sigalgs = NULL;
1470                 }
1471         /* Clear any shared sigtnature algorithms */
1472         if (s->cert->shared_sigalgs)
1473                 {
1474                 OPENSSL_free(s->cert->shared_sigalgs);
1475                 s->cert->shared_sigalgs = NULL;
1476                 }
1477
1478         if (data >= (d+n-2))
1479                 goto ri_check;
1480         n2s(data,len);
1481
1482         if (data > (d+n-len)) 
1483                 goto ri_check;
1484
1485         while (data <= (d+n-4))
1486                 {
1487                 n2s(data,type);
1488                 n2s(data,size);
1489
1490                 if (data+size > (d+n))
1491                         goto ri_check;
1492 #if 0
1493                 fprintf(stderr,"Received extension type %d size %d\n",type,size);
1494 #endif
1495                 if (s->tlsext_debug_cb)
1496                         s->tlsext_debug_cb(s, 0, type, data, size,
1497                                                 s->tlsext_debug_arg);
1498 /* The servername extension is treated as follows:
1499
1500    - Only the hostname type is supported with a maximum length of 255.
1501    - The servername is rejected if too long or if it contains zeros,
1502      in which case an fatal alert is generated.
1503    - The servername field is maintained together with the session cache.
1504    - When a session is resumed, the servername call back invoked in order
1505      to allow the application to position itself to the right context. 
1506    - The servername is acknowledged if it is new for a session or when 
1507      it is identical to a previously used for the same session. 
1508      Applications can control the behaviour.  They can at any time
1509      set a 'desirable' servername for a new SSL object. This can be the
1510      case for example with HTTPS when a Host: header field is received and
1511      a renegotiation is requested. In this case, a possible servername
1512      presented in the new client hello is only acknowledged if it matches
1513      the value of the Host: field. 
1514    - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
1515      if they provide for changing an explicit servername context for the session,
1516      i.e. when the session has been established with a servername extension. 
1517    - On session reconnect, the servername extension may be absent. 
1518
1519 */      
1520
1521                 if (type == TLSEXT_TYPE_server_name)
1522                         {
1523                         unsigned char *sdata;
1524                         int servname_type;
1525                         int dsize; 
1526                 
1527                         if (size < 2) 
1528                                 {
1529                                 *al = SSL_AD_DECODE_ERROR;
1530                                 return 0;
1531                                 }
1532                         n2s(data,dsize);  
1533                         size -= 2;
1534                         if (dsize > size  ) 
1535                                 {
1536                                 *al = SSL_AD_DECODE_ERROR;
1537                                 return 0;
1538                                 } 
1539
1540                         sdata = data;
1541                         while (dsize > 3) 
1542                                 {
1543                                 servname_type = *(sdata++); 
1544                                 n2s(sdata,len);
1545                                 dsize -= 3;
1546
1547                                 if (len > dsize) 
1548                                         {
1549                                         *al = SSL_AD_DECODE_ERROR;
1550                                         return 0;
1551                                         }
1552                                 if (s->servername_done == 0)
1553                                 switch (servname_type)
1554                                         {
1555                                 case TLSEXT_NAMETYPE_host_name:
1556                                         if (!s->hit)
1557                                                 {
1558                                                 if(s->session->tlsext_hostname)
1559                                                         {
1560                                                         *al = SSL_AD_DECODE_ERROR;
1561                                                         return 0;
1562                                                         }
1563                                                 if (len > TLSEXT_MAXLEN_host_name)
1564                                                         {
1565                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
1566                                                         return 0;
1567                                                         }
1568                                                 if ((s->session->tlsext_hostname = OPENSSL_malloc(len+1)) == NULL)
1569                                                         {
1570                                                         *al = TLS1_AD_INTERNAL_ERROR;
1571                                                         return 0;
1572                                                         }
1573                                                 memcpy(s->session->tlsext_hostname, sdata, len);
1574                                                 s->session->tlsext_hostname[len]='\0';
1575                                                 if (strlen(s->session->tlsext_hostname) != len) {
1576                                                         OPENSSL_free(s->session->tlsext_hostname);
1577                                                         s->session->tlsext_hostname = NULL;
1578                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
1579                                                         return 0;
1580                                                 }
1581                                                 s->servername_done = 1; 
1582
1583                                                 }
1584                                         else 
1585                                                 s->servername_done = s->session->tlsext_hostname
1586                                                         && strlen(s->session->tlsext_hostname) == len 
1587                                                         && strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0;
1588                                         
1589                                         break;
1590
1591                                 default:
1592                                         break;
1593                                         }
1594                                  
1595                                 dsize -= len;
1596                                 }
1597                         if (dsize != 0) 
1598                                 {
1599                                 *al = SSL_AD_DECODE_ERROR;
1600                                 return 0;
1601                                 }
1602
1603                         }
1604 #ifndef OPENSSL_NO_SRP
1605                 else if (type == TLSEXT_TYPE_srp)
1606                         {
1607                         if (size <= 0 || ((len = data[0])) != (size -1))
1608                                 {
1609                                 *al = SSL_AD_DECODE_ERROR;
1610                                 return 0;
1611                                 }
1612                         if (s->srp_ctx.login != NULL)
1613                                 {
1614                                 *al = SSL_AD_DECODE_ERROR;
1615                                 return 0;
1616                                 }
1617                         if ((s->srp_ctx.login = OPENSSL_malloc(len+1)) == NULL)
1618                                 return -1;
1619                         memcpy(s->srp_ctx.login, &data[1], len);
1620                         s->srp_ctx.login[len]='\0';
1621   
1622                         if (strlen(s->srp_ctx.login) != len) 
1623                                 {
1624                                 *al = SSL_AD_DECODE_ERROR;
1625                                 return 0;
1626                                 }
1627                         }
1628 #endif
1629
1630 #ifndef OPENSSL_NO_EC
1631                 else if (type == TLSEXT_TYPE_ec_point_formats &&
1632                      s->version != DTLS1_VERSION)
1633                         {
1634                         unsigned char *sdata = data;
1635                         int ecpointformatlist_length = *(sdata++);
1636
1637                         if (ecpointformatlist_length != size - 1)
1638                                 {
1639                                 *al = TLS1_AD_DECODE_ERROR;
1640                                 return 0;
1641                                 }
1642                         if (!s->hit)
1643                                 {
1644                                 if(s->session->tlsext_ecpointformatlist)
1645                                         {
1646                                         OPENSSL_free(s->session->tlsext_ecpointformatlist);
1647                                         s->session->tlsext_ecpointformatlist = NULL;
1648                                         }
1649                                 s->session->tlsext_ecpointformatlist_length = 0;
1650                                 if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
1651                                         {
1652                                         *al = TLS1_AD_INTERNAL_ERROR;
1653                                         return 0;
1654                                         }
1655                                 s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
1656                                 memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
1657                                 }
1658 #if 0
1659                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ", s->session->tlsext_ecpointformatlist_length);
1660                         sdata = s->session->tlsext_ecpointformatlist;
1661                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
1662                                 fprintf(stderr,"%i ",*(sdata++));
1663                         fprintf(stderr,"\n");
1664 #endif
1665                         }
1666                 else if (type == TLSEXT_TYPE_elliptic_curves &&
1667                      s->version != DTLS1_VERSION)
1668                         {
1669                         unsigned char *sdata = data;
1670                         int ellipticcurvelist_length = (*(sdata++) << 8);
1671                         ellipticcurvelist_length += (*(sdata++));
1672
1673                         if (ellipticcurvelist_length != size - 2)
1674                                 {
1675                                 *al = TLS1_AD_DECODE_ERROR;
1676                                 return 0;
1677                                 }
1678                         if (!s->hit)
1679                                 {
1680                                 if(s->session->tlsext_ellipticcurvelist)
1681                                         {
1682                                         *al = TLS1_AD_DECODE_ERROR;
1683                                         return 0;
1684                                         }
1685                                 s->session->tlsext_ellipticcurvelist_length = 0;
1686                                 if ((s->session->tlsext_ellipticcurvelist = OPENSSL_malloc(ellipticcurvelist_length)) == NULL)
1687                                         {
1688                                         *al = TLS1_AD_INTERNAL_ERROR;
1689                                         return 0;
1690                                         }
1691                                 s->session->tlsext_ellipticcurvelist_length = ellipticcurvelist_length;
1692                                 memcpy(s->session->tlsext_ellipticcurvelist, sdata, ellipticcurvelist_length);
1693                                 }
1694 #if 0
1695                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ", s->session->tlsext_ellipticcurvelist_length);
1696                         sdata = s->session->tlsext_ellipticcurvelist;
1697                         for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++)
1698                                 fprintf(stderr,"%i ",*(sdata++));
1699                         fprintf(stderr,"\n");
1700 #endif
1701                         }
1702 #endif /* OPENSSL_NO_EC */
1703 #ifdef TLSEXT_TYPE_opaque_prf_input
1704                 else if (type == TLSEXT_TYPE_opaque_prf_input &&
1705                      s->version != DTLS1_VERSION)
1706                         {
1707                         unsigned char *sdata = data;
1708
1709                         if (size < 2)
1710                                 {
1711                                 *al = SSL_AD_DECODE_ERROR;
1712                                 return 0;
1713                                 }
1714                         n2s(sdata, s->s3->client_opaque_prf_input_len);
1715                         if (s->s3->client_opaque_prf_input_len != size - 2)
1716                                 {
1717                                 *al = SSL_AD_DECODE_ERROR;
1718                                 return 0;
1719                                 }
1720
1721                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
1722                                 OPENSSL_free(s->s3->client_opaque_prf_input);
1723                         if (s->s3->client_opaque_prf_input_len == 0)
1724                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
1725                         else
1726                                 s->s3->client_opaque_prf_input = BUF_memdup(sdata, s->s3->client_opaque_prf_input_len);
1727                         if (s->s3->client_opaque_prf_input == NULL)
1728                                 {
1729                                 *al = TLS1_AD_INTERNAL_ERROR;
1730                                 return 0;
1731                                 }
1732                         }
1733 #endif
1734                 else if (type == TLSEXT_TYPE_session_ticket)
1735                         {
1736                         if (s->tls_session_ticket_ext_cb &&
1737                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
1738                                 {
1739                                 *al = TLS1_AD_INTERNAL_ERROR;
1740                                 return 0;
1741                                 }
1742                         }
1743                 else if (type == TLSEXT_TYPE_renegotiate)
1744                         {
1745                         if(!ssl_parse_clienthello_renegotiate_ext(s, data, size, al))
1746                                 return 0;
1747                         renegotiate_seen = 1;
1748                         }
1749                 else if (type == TLSEXT_TYPE_signature_algorithms)
1750                         {
1751                         int dsize;
1752                         if (s->cert->peer_sigalgs || size < 2) 
1753                                 {
1754                                 *al = SSL_AD_DECODE_ERROR;
1755                                 return 0;
1756                                 }
1757                         n2s(data,dsize);
1758                         size -= 2;
1759                         if (dsize != size || dsize & 1 || !dsize) 
1760                                 {
1761                                 *al = SSL_AD_DECODE_ERROR;
1762                                 return 0;
1763                                 }
1764                         if (!tls1_process_sigalgs(s, data, dsize))
1765                                 {
1766                                 *al = SSL_AD_DECODE_ERROR;
1767                                 return 0;
1768                                 }
1769                         /* If sigalgs received and no shared algorithms fatal
1770                          * error.
1771                          */
1772                         if (s->cert->peer_sigalgs && !s->cert->shared_sigalgs)
1773                                 {
1774                                 SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
1775                                         SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
1776                                 *al = SSL_AD_ILLEGAL_PARAMETER;
1777                                 return 0;
1778                                 }
1779                         }
1780                 else if (type == TLSEXT_TYPE_status_request &&
1781                          s->version != DTLS1_VERSION && s->ctx->tlsext_status_cb)
1782                         {
1783                 
1784                         if (size < 5) 
1785                                 {
1786                                 *al = SSL_AD_DECODE_ERROR;
1787                                 return 0;
1788                                 }
1789
1790                         s->tlsext_status_type = *data++;
1791                         size--;
1792                         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp)
1793                                 {
1794                                 const unsigned char *sdata;
1795                                 int dsize;
1796                                 /* Read in responder_id_list */
1797                                 n2s(data,dsize);
1798                                 size -= 2;
1799                                 if (dsize > size  ) 
1800                                         {
1801                                         *al = SSL_AD_DECODE_ERROR;
1802                                         return 0;
1803                                         }
1804                                 while (dsize > 0)
1805                                         {
1806                                         OCSP_RESPID *id;
1807                                         int idsize;
1808                                         if (dsize < 4)
1809                                                 {
1810                                                 *al = SSL_AD_DECODE_ERROR;
1811                                                 return 0;
1812                                                 }
1813                                         n2s(data, idsize);
1814                                         dsize -= 2 + idsize;
1815                                         size -= 2 + idsize;
1816                                         if (dsize < 0)
1817                                                 {
1818                                                 *al = SSL_AD_DECODE_ERROR;
1819                                                 return 0;
1820                                                 }
1821                                         sdata = data;
1822                                         data += idsize;
1823                                         id = d2i_OCSP_RESPID(NULL,
1824                                                                 &sdata, idsize);
1825                                         if (!id)
1826                                                 {
1827                                                 *al = SSL_AD_DECODE_ERROR;
1828                                                 return 0;
1829                                                 }
1830                                         if (data != sdata)
1831                                                 {
1832                                                 OCSP_RESPID_free(id);
1833                                                 *al = SSL_AD_DECODE_ERROR;
1834                                                 return 0;
1835                                                 }
1836                                         if (!s->tlsext_ocsp_ids
1837                                                 && !(s->tlsext_ocsp_ids =
1838                                                 sk_OCSP_RESPID_new_null()))
1839                                                 {
1840                                                 OCSP_RESPID_free(id);
1841                                                 *al = SSL_AD_INTERNAL_ERROR;
1842                                                 return 0;
1843                                                 }
1844                                         if (!sk_OCSP_RESPID_push(
1845                                                         s->tlsext_ocsp_ids, id))
1846                                                 {
1847                                                 OCSP_RESPID_free(id);
1848                                                 *al = SSL_AD_INTERNAL_ERROR;
1849                                                 return 0;
1850                                                 }
1851                                         }
1852
1853                                 /* Read in request_extensions */
1854                                 if (size < 2)
1855                                         {
1856                                         *al = SSL_AD_DECODE_ERROR;
1857                                         return 0;
1858                                         }
1859                                 n2s(data,dsize);
1860                                 size -= 2;
1861                                 if (dsize != size)
1862                                         {
1863                                         *al = SSL_AD_DECODE_ERROR;
1864                                         return 0;
1865                                         }
1866                                 sdata = data;
1867                                 if (dsize > 0)
1868                                         {
1869                                         if (s->tlsext_ocsp_exts)
1870                                                 {
1871                                                 sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
1872                                                                            X509_EXTENSION_free);
1873                                                 }
1874
1875                                         s->tlsext_ocsp_exts =
1876                                                 d2i_X509_EXTENSIONS(NULL,
1877                                                         &sdata, dsize);
1878                                         if (!s->tlsext_ocsp_exts
1879                                                 || (data + dsize != sdata))
1880                                                 {
1881                                                 *al = SSL_AD_DECODE_ERROR;
1882                                                 return 0;
1883                                                 }
1884                                         }
1885                                 }
1886                                 /* We don't know what to do with any other type
1887                                 * so ignore it.
1888                                 */
1889                                 else
1890                                         s->tlsext_status_type = -1;
1891                         }
1892 #ifndef OPENSSL_NO_HEARTBEATS
1893                 else if (type == TLSEXT_TYPE_heartbeat)
1894                         {
1895                         switch(data[0])
1896                                 {
1897                                 case 0x01:      /* Client allows us to send HB requests */
1898                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
1899                                                         break;
1900                                 case 0x02:      /* Client doesn't accept HB requests */
1901                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
1902                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1903                                                         break;
1904                                 default:        *al = SSL_AD_ILLEGAL_PARAMETER;
1905                                                         return 0;
1906                                 }
1907                         }
1908 #endif
1909 #ifndef OPENSSL_NO_NEXTPROTONEG
1910                 else if (type == TLSEXT_TYPE_next_proto_neg &&
1911                          s->s3->tmp.finish_md_len == 0)
1912                         {
1913                         /* We shouldn't accept this extension on a
1914                          * renegotiation.
1915                          *
1916                          * s->new_session will be set on renegotiation, but we
1917                          * probably shouldn't rely that it couldn't be set on
1918                          * the initial renegotation too in certain cases (when
1919                          * there's some other reason to disallow resuming an
1920                          * earlier session -- the current code won't be doing
1921                          * anything like that, but this might change).
1922
1923                          * A valid sign that there's been a previous handshake
1924                          * in this connection is if s->s3->tmp.finish_md_len >
1925                          * 0.  (We are talking about a check that will happen
1926                          * in the Hello protocol round, well before a new
1927                          * Finished message could have been computed.) */
1928                         s->s3->next_proto_neg_seen = 1;
1929                         }
1930 #endif
1931
1932                 /* session ticket processed earlier */
1933                 else if (type == TLSEXT_TYPE_use_srtp)
1934                         {
1935                         if(ssl_parse_clienthello_use_srtp_ext(s, data, size,
1936                                                               al))
1937                                 return 0;
1938                         }
1939
1940                 else if (type == TLSEXT_TYPE_server_authz)
1941                         {
1942                         unsigned char *sdata = data;
1943                         unsigned char server_authz_dataformatlist_length;
1944
1945                         if (size == 0)
1946                                 {
1947                                 *al = TLS1_AD_DECODE_ERROR;
1948                                 return 0;
1949                                 }
1950
1951                         server_authz_dataformatlist_length = *(sdata++);
1952
1953                         if (server_authz_dataformatlist_length != size - 1)
1954                                 {
1955                                 *al = TLS1_AD_DECODE_ERROR;
1956                                 return 0;
1957                                 }
1958
1959                         /* Successful session resumption uses the same authz
1960                          * information as the original session so we ignore this
1961                          * in the case of a session resumption. */
1962                         if (!s->hit)
1963                                 {
1964                                 size_t i;
1965                                 if (s->s3->tlsext_authz_client_types != NULL)
1966                                         OPENSSL_free(s->s3->tlsext_authz_client_types);
1967                                 s->s3->tlsext_authz_client_types =
1968                                         OPENSSL_malloc(server_authz_dataformatlist_length);
1969                                 if (!s->s3->tlsext_authz_client_types)
1970                                         {
1971                                         *al = TLS1_AD_INTERNAL_ERROR;
1972                                         return 0;
1973                                         }
1974
1975                                 s->s3->tlsext_authz_client_types_len =
1976                                         server_authz_dataformatlist_length;
1977                                 memcpy(s->s3->tlsext_authz_client_types,
1978                                        sdata,
1979                                        server_authz_dataformatlist_length);
1980
1981                                 /* Sort the types in order to check for duplicates. */
1982                                 qsort(s->s3->tlsext_authz_client_types,
1983                                       server_authz_dataformatlist_length,
1984                                       1 /* element size */,
1985                                       byte_compare);
1986
1987                                 for (i = 0; i < server_authz_dataformatlist_length; i++)
1988                                         {
1989                                         if (i > 0 &&
1990                                             s->s3->tlsext_authz_client_types[i] ==
1991                                               s->s3->tlsext_authz_client_types[i-1])
1992                                                 {
1993                                                 *al = TLS1_AD_DECODE_ERROR;
1994                                                 return 0;
1995                                                 }
1996                                         }
1997                                 }
1998                         }
1999
2000                 data+=size;
2001                 }
2002
2003         *p = data;
2004
2005         ri_check:
2006
2007         /* Need RI if renegotiating */
2008
2009         if (!renegotiate_seen && s->renegotiate &&
2010                 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
2011                 {
2012                 *al = SSL_AD_HANDSHAKE_FAILURE;
2013                 SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
2014                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2015                 return 0;
2016                 }
2017         /* If no signature algorithms extension set default values */
2018         if (!s->cert->peer_sigalgs)
2019                 ssl_cert_set_default_md(s->cert);
2020
2021         return 1;
2022         }
2023
2024 int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n) 
2025         {
2026         int al = -1;
2027         if (ssl_scan_clienthello_tlsext(s, p, d, n, &al) <= 0) 
2028                 {
2029                 ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2030                 return 0;
2031                 }
2032
2033         if (ssl_check_clienthello_tlsext(s) <= 0) 
2034                 {
2035                 SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT,SSL_R_CLIENTHELLO_TLSEXT);
2036                 return 0;
2037                 }
2038         return 1;
2039 }
2040
2041 #ifndef OPENSSL_NO_NEXTPROTONEG
2042 /* ssl_next_proto_validate validates a Next Protocol Negotiation block. No
2043  * elements of zero length are allowed and the set of elements must exactly fill
2044  * the length of the block. */
2045 static char ssl_next_proto_validate(unsigned char *d, unsigned len)
2046         {
2047         unsigned int off = 0;
2048
2049         while (off < len)
2050                 {
2051                 if (d[off] == 0)
2052                         return 0;
2053                 off += d[off];
2054                 off++;
2055                 }
2056
2057         return off == len;
2058         }
2059 #endif
2060
2061 static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
2062         {
2063         unsigned short length;
2064         unsigned short type;
2065         unsigned short size;
2066         unsigned char *data = *p;
2067         int tlsext_servername = 0;
2068         int renegotiate_seen = 0;
2069
2070 #ifndef OPENSSL_NO_NEXTPROTONEG
2071         s->s3->next_proto_neg_seen = 0;
2072 #endif
2073
2074 #ifndef OPENSSL_NO_HEARTBEATS
2075         s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
2076                                SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
2077 #endif
2078
2079         if (data >= (d+n-2))
2080                 goto ri_check;
2081
2082         n2s(data,length);
2083         if (data+length != d+n)
2084                 {
2085                 *al = SSL_AD_DECODE_ERROR;
2086                 return 0;
2087                 }
2088
2089         while(data <= (d+n-4))
2090                 {
2091                 n2s(data,type);
2092                 n2s(data,size);
2093
2094                 if (data+size > (d+n))
2095                         goto ri_check;
2096
2097                 if (s->tlsext_debug_cb)
2098                         s->tlsext_debug_cb(s, 1, type, data, size,
2099                                                 s->tlsext_debug_arg);
2100
2101                 if (type == TLSEXT_TYPE_server_name)
2102                         {
2103                         if (s->tlsext_hostname == NULL || size > 0)
2104                                 {
2105                                 *al = TLS1_AD_UNRECOGNIZED_NAME;
2106                                 return 0;
2107                                 }
2108                         tlsext_servername = 1;   
2109                         }
2110
2111 #ifndef OPENSSL_NO_EC
2112                 else if (type == TLSEXT_TYPE_ec_point_formats &&
2113                      s->version != DTLS1_VERSION)
2114                         {
2115                         unsigned char *sdata = data;
2116                         int ecpointformatlist_length = *(sdata++);
2117
2118                         if (ecpointformatlist_length != size - 1)
2119                                 {
2120                                 *al = TLS1_AD_DECODE_ERROR;
2121                                 return 0;
2122                                 }
2123                         s->session->tlsext_ecpointformatlist_length = 0;
2124                         if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist);
2125                         if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
2126                                 {
2127                                 *al = TLS1_AD_INTERNAL_ERROR;
2128                                 return 0;
2129                                 }
2130                         s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
2131                         memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
2132 #if 0
2133                         fprintf(stderr,"ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist ");
2134                         sdata = s->session->tlsext_ecpointformatlist;
2135                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2136                                 fprintf(stderr,"%i ",*(sdata++));
2137                         fprintf(stderr,"\n");
2138 #endif
2139                         }
2140 #endif /* OPENSSL_NO_EC */
2141
2142                 else if (type == TLSEXT_TYPE_session_ticket)
2143                         {
2144                         if (s->tls_session_ticket_ext_cb &&
2145                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
2146                                 {
2147                                 *al = TLS1_AD_INTERNAL_ERROR;
2148                                 return 0;
2149                                 }
2150                         if ((SSL_get_options(s) & SSL_OP_NO_TICKET)
2151                                 || (size > 0))
2152                                 {
2153                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2154                                 return 0;
2155                                 }
2156                         s->tlsext_ticket_expected = 1;
2157                         }
2158 #ifdef TLSEXT_TYPE_opaque_prf_input
2159                 else if (type == TLSEXT_TYPE_opaque_prf_input &&
2160                      s->version != DTLS1_VERSION)
2161                         {
2162                         unsigned char *sdata = data;
2163
2164                         if (size < 2)
2165                                 {
2166                                 *al = SSL_AD_DECODE_ERROR;
2167                                 return 0;
2168                                 }
2169                         n2s(sdata, s->s3->server_opaque_prf_input_len);
2170                         if (s->s3->server_opaque_prf_input_len != size - 2)
2171                                 {
2172                                 *al = SSL_AD_DECODE_ERROR;
2173                                 return 0;
2174                                 }
2175                         
2176                         if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
2177                                 OPENSSL_free(s->s3->server_opaque_prf_input);
2178                         if (s->s3->server_opaque_prf_input_len == 0)
2179                                 s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2180                         else
2181                                 s->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len);
2182
2183                         if (s->s3->server_opaque_prf_input == NULL)
2184                                 {
2185                                 *al = TLS1_AD_INTERNAL_ERROR;
2186                                 return 0;
2187                                 }
2188                         }
2189 #endif
2190                 else if (type == TLSEXT_TYPE_status_request &&
2191                          s->version != DTLS1_VERSION)
2192                         {
2193                         /* MUST be empty and only sent if we've requested
2194                          * a status request message.
2195                          */ 
2196                         if ((s->tlsext_status_type == -1) || (size > 0))
2197                                 {
2198                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2199                                 return 0;
2200                                 }
2201                         /* Set flag to expect CertificateStatus message */
2202                         s->tlsext_status_expected = 1;
2203                         }
2204 #ifndef OPENSSL_NO_NEXTPROTONEG
2205                 else if (type == TLSEXT_TYPE_next_proto_neg &&
2206                          s->s3->tmp.finish_md_len == 0)
2207                         {
2208                         unsigned char *selected;
2209                         unsigned char selected_len;
2210
2211                         /* We must have requested it. */
2212                         if ((s->ctx->next_proto_select_cb == NULL))
2213                                 {
2214                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2215                                 return 0;
2216                                 }
2217                         /* The data must be valid */
2218                         if (!ssl_next_proto_validate(data, size))
2219                                 {
2220                                 *al = TLS1_AD_DECODE_ERROR;
2221                                 return 0;
2222                                 }
2223                         if (s->ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK)
2224                                 {
2225                                 *al = TLS1_AD_INTERNAL_ERROR;
2226                                 return 0;
2227                                 }
2228                         s->next_proto_negotiated = OPENSSL_malloc(selected_len);
2229                         if (!s->next_proto_negotiated)
2230                                 {
2231                                 *al = TLS1_AD_INTERNAL_ERROR;
2232                                 return 0;
2233                                 }
2234                         memcpy(s->next_proto_negotiated, selected, selected_len);
2235                         s->next_proto_negotiated_len = selected_len;
2236                         s->s3->next_proto_neg_seen = 1;
2237                         }
2238 #endif
2239                 else if (type == TLSEXT_TYPE_renegotiate)
2240                         {
2241                         if(!ssl_parse_serverhello_renegotiate_ext(s, data, size, al))
2242                                 return 0;
2243                         renegotiate_seen = 1;
2244                         }
2245 #ifndef OPENSSL_NO_HEARTBEATS
2246                 else if (type == TLSEXT_TYPE_heartbeat)
2247                         {
2248                         switch(data[0])
2249                                 {
2250                                 case 0x01:      /* Server allows us to send HB requests */
2251                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2252                                                         break;
2253                                 case 0x02:      /* Server doesn't accept HB requests */
2254                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2255                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2256                                                         break;
2257                                 default:        *al = SSL_AD_ILLEGAL_PARAMETER;
2258                                                         return 0;
2259                                 }
2260                         }
2261 #endif
2262                 else if (type == TLSEXT_TYPE_use_srtp)
2263                         {
2264                         if(ssl_parse_serverhello_use_srtp_ext(s, data, size,
2265                                                               al))
2266                                 return 0;
2267                         }
2268
2269                 else if (type == TLSEXT_TYPE_server_authz)
2270                         {
2271                         /* We only support audit proofs. It's an error to send
2272                          * an authz hello extension if the client
2273                          * didn't request a proof. */
2274                         unsigned char *sdata = data;
2275                         unsigned char server_authz_dataformatlist_length;
2276
2277                         if (!s->ctx->tlsext_authz_server_audit_proof_cb)
2278                                 {
2279                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2280                                 return 0;
2281                                 }
2282
2283                         if (!size)
2284                                 {
2285                                 *al = TLS1_AD_DECODE_ERROR;
2286                                 return 0;
2287                                 }
2288
2289                         server_authz_dataformatlist_length = *(sdata++);
2290                         if (server_authz_dataformatlist_length != size - 1)
2291                                 {
2292                                 *al = TLS1_AD_DECODE_ERROR;
2293                                 return 0;
2294                                 }
2295
2296                         /* We only support audit proofs, so a legal ServerHello
2297                          * authz list contains exactly one entry. */
2298                         if (server_authz_dataformatlist_length != 1 ||
2299                                 sdata[0] != TLSEXT_AUTHZDATAFORMAT_audit_proof)
2300                                 {
2301                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2302                                 return 0;
2303                                 }
2304
2305                         s->s3->tlsext_authz_server_promised = 1;
2306                         }
2307  
2308                 data += size;
2309                 }
2310
2311         if (data != d+n)
2312                 {
2313                 *al = SSL_AD_DECODE_ERROR;
2314                 return 0;
2315                 }
2316
2317         if (!s->hit && tlsext_servername == 1)
2318                 {
2319                 if (s->tlsext_hostname)
2320                         {
2321                         if (s->session->tlsext_hostname == NULL)
2322                                 {
2323                                 s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);   
2324                                 if (!s->session->tlsext_hostname)
2325                                         {
2326                                         *al = SSL_AD_UNRECOGNIZED_NAME;
2327                                         return 0;
2328                                         }
2329                                 }
2330                         else 
2331                                 {
2332                                 *al = SSL_AD_DECODE_ERROR;
2333                                 return 0;
2334                                 }
2335                         }
2336                 }
2337
2338         *p = data;
2339
2340         ri_check:
2341
2342         /* Determine if we need to see RI. Strictly speaking if we want to
2343          * avoid an attack we should *always* see RI even on initial server
2344          * hello because the client doesn't see any renegotiation during an
2345          * attack. However this would mean we could not connect to any server
2346          * which doesn't support RI so for the immediate future tolerate RI
2347          * absence on initial connect only.
2348          */
2349         if (!renegotiate_seen
2350                 && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
2351                 && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
2352                 {
2353                 *al = SSL_AD_HANDSHAKE_FAILURE;
2354                 SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT,
2355                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2356                 return 0;
2357                 }
2358
2359         return 1;
2360         }
2361
2362
2363 int ssl_prepare_clienthello_tlsext(SSL *s)
2364         {
2365
2366 #ifdef TLSEXT_TYPE_opaque_prf_input
2367         {
2368                 int r = 1;
2369         
2370                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
2371                         {
2372                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
2373                         if (!r)
2374                                 return -1;
2375                         }
2376
2377                 if (s->tlsext_opaque_prf_input != NULL)
2378                         {
2379                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
2380                                 OPENSSL_free(s->s3->client_opaque_prf_input);
2381
2382                         if (s->tlsext_opaque_prf_input_len == 0)
2383                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2384                         else
2385                                 s->s3->client_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
2386                         if (s->s3->client_opaque_prf_input == NULL)
2387                                 {
2388                                 SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
2389                                 return -1;
2390                                 }
2391                         s->s3->client_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2392                         }
2393
2394                 if (r == 2)
2395                         /* at callback's request, insist on receiving an appropriate server opaque PRF input */
2396                         s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2397         }
2398 #endif
2399
2400         return 1;
2401         }
2402
2403 int ssl_prepare_serverhello_tlsext(SSL *s)
2404         {
2405 #ifndef OPENSSL_NO_EC
2406         /* If we are server and using an ECC cipher suite, send the point formats we support 
2407          * if the client sent us an ECPointsFormat extension.  Note that the server is not
2408          * supposed to send an EllipticCurves extension.
2409          */
2410
2411         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2412         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2413         int using_ecc = (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA);
2414         using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL);
2415         
2416         if (using_ecc)
2417                 {
2418                 if (s->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->tlsext_ecpointformatlist);
2419                 if ((s->tlsext_ecpointformatlist = OPENSSL_malloc(3)) == NULL)
2420                         {
2421                         SSLerr(SSL_F_SSL_PREPARE_SERVERHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
2422                         return -1;
2423                         }
2424                 s->tlsext_ecpointformatlist_length = 3;
2425                 s->tlsext_ecpointformatlist[0] = TLSEXT_ECPOINTFORMAT_uncompressed;
2426                 s->tlsext_ecpointformatlist[1] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
2427                 s->tlsext_ecpointformatlist[2] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
2428                 }
2429 #endif /* OPENSSL_NO_EC */
2430
2431         return 1;
2432         }
2433
2434 static int ssl_check_clienthello_tlsext(SSL *s)
2435         {
2436         int ret=SSL_TLSEXT_ERR_NOACK;
2437         int al = SSL_AD_UNRECOGNIZED_NAME;
2438
2439 #ifndef OPENSSL_NO_EC
2440         /* The handling of the ECPointFormats extension is done elsewhere, namely in 
2441          * ssl3_choose_cipher in s3_lib.c.
2442          */
2443         /* The handling of the EllipticCurves extension is done elsewhere, namely in 
2444          * ssl3_choose_cipher in s3_lib.c.
2445          */
2446 #endif
2447
2448         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
2449                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
2450         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
2451                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
2452
2453         /* If status request then ask callback what to do.
2454          * Note: this must be called after servername callbacks in case 
2455          * the certificate has changed.
2456          */
2457         if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb)
2458                 {
2459                 int r;
2460                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2461                 switch (r)
2462                         {
2463                         /* We don't want to send a status request response */
2464                         case SSL_TLSEXT_ERR_NOACK:
2465                                 s->tlsext_status_expected = 0;
2466                                 break;
2467                         /* status request response should be sent */
2468                         case SSL_TLSEXT_ERR_OK:
2469                                 if (s->tlsext_ocsp_resp)
2470                                         s->tlsext_status_expected = 1;
2471                                 else
2472                                         s->tlsext_status_expected = 0;
2473                                 break;
2474                         /* something bad happened */
2475                         case SSL_TLSEXT_ERR_ALERT_FATAL:
2476                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2477                                 al = SSL_AD_INTERNAL_ERROR;
2478                                 goto err;
2479                         }
2480                 }
2481         else
2482                 s->tlsext_status_expected = 0;
2483
2484 #ifdef TLSEXT_TYPE_opaque_prf_input
2485         {
2486                 /* This sort of belongs into ssl_prepare_serverhello_tlsext(),
2487                  * but we might be sending an alert in response to the client hello,
2488                  * so this has to happen here in ssl_check_clienthello_tlsext(). */
2489
2490                 int r = 1;
2491         
2492                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
2493                         {
2494                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
2495                         if (!r)
2496                                 {
2497                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2498                                 al = SSL_AD_INTERNAL_ERROR;
2499                                 goto err;
2500                                 }
2501                         }
2502
2503                 if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
2504                         OPENSSL_free(s->s3->server_opaque_prf_input);
2505                 s->s3->server_opaque_prf_input = NULL;
2506
2507                 if (s->tlsext_opaque_prf_input != NULL)
2508                         {
2509                         if (s->s3->client_opaque_prf_input != NULL &&
2510                                 s->s3->client_opaque_prf_input_len == s->tlsext_opaque_prf_input_len)
2511                                 {
2512                                 /* can only use this extension if we have a server opaque PRF input
2513                                  * of the same length as the client opaque PRF input! */
2514
2515                                 if (s->tlsext_opaque_prf_input_len == 0)
2516                                         s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2517                                 else
2518                                         s->s3->server_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
2519                                 if (s->s3->server_opaque_prf_input == NULL)
2520                                         {
2521                                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2522                                         al = SSL_AD_INTERNAL_ERROR;
2523                                         goto err;
2524                                         }
2525                                 s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2526                                 }
2527                         }
2528
2529                 if (r == 2 && s->s3->server_opaque_prf_input == NULL)
2530                         {
2531                         /* The callback wants to enforce use of the extension,
2532                          * but we can't do that with the client opaque PRF input;
2533                          * abort the handshake.
2534                          */
2535                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2536                         al = SSL_AD_HANDSHAKE_FAILURE;
2537                         }
2538         }
2539
2540 #endif
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                 case SSL_TLSEXT_ERR_NOACK:
2553                         s->servername_done=0;
2554                         default:
2555                 return 1;
2556                 }
2557         }
2558
2559 int ssl_check_serverhello_tlsext(SSL *s)
2560         {
2561         int ret=SSL_TLSEXT_ERR_NOACK;
2562         int al = SSL_AD_UNRECOGNIZED_NAME;
2563
2564 #ifndef OPENSSL_NO_EC
2565         /* If we are client and using an elliptic curve cryptography cipher
2566          * suite, then if server returns an EC point formats lists extension
2567          * it must contain uncompressed.
2568          */
2569         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2570         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2571         if ((s->tlsext_ecpointformatlist != NULL) && (s->tlsext_ecpointformatlist_length > 0) && 
2572             (s->session->tlsext_ecpointformatlist != NULL) && (s->session->tlsext_ecpointformatlist_length > 0) && 
2573             ((alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA)))
2574                 {
2575                 /* we are using an ECC cipher */
2576                 size_t i;
2577                 unsigned char *list;
2578                 int found_uncompressed = 0;
2579                 list = s->session->tlsext_ecpointformatlist;
2580                 for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2581                         {
2582                         if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed)
2583                                 {
2584                                 found_uncompressed = 1;
2585                                 break;
2586                                 }
2587                         }
2588                 if (!found_uncompressed)
2589                         {
2590                         SSLerr(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT,SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
2591                         return -1;
2592                         }
2593                 }
2594         ret = SSL_TLSEXT_ERR_OK;
2595 #endif /* OPENSSL_NO_EC */
2596
2597         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
2598                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
2599         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
2600                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
2601
2602 #ifdef TLSEXT_TYPE_opaque_prf_input
2603         if (s->s3->server_opaque_prf_input_len > 0)
2604                 {
2605                 /* This case may indicate that we, as a client, want to insist on using opaque PRF inputs.
2606                  * So first verify that we really have a value from the server too. */
2607
2608                 if (s->s3->server_opaque_prf_input == NULL)
2609                         {
2610                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2611                         al = SSL_AD_HANDSHAKE_FAILURE;
2612                         }
2613                 
2614                 /* Anytime the server *has* sent an opaque PRF input, we need to check
2615                  * that we have a client opaque PRF input of the same size. */
2616                 if (s->s3->client_opaque_prf_input == NULL ||
2617                     s->s3->client_opaque_prf_input_len != s->s3->server_opaque_prf_input_len)
2618                         {
2619                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2620                         al = SSL_AD_ILLEGAL_PARAMETER;
2621                         }
2622                 }
2623 #endif
2624
2625         /* If we've requested certificate status and we wont get one
2626          * tell the callback
2627          */
2628         if ((s->tlsext_status_type != -1) && !(s->tlsext_status_expected)
2629                         && s->ctx && s->ctx->tlsext_status_cb)
2630                 {
2631                 int r;
2632                 /* Set resp to NULL, resplen to -1 so callback knows
2633                  * there is no response.
2634                  */
2635                 if (s->tlsext_ocsp_resp)
2636                         {
2637                         OPENSSL_free(s->tlsext_ocsp_resp);
2638                         s->tlsext_ocsp_resp = NULL;
2639                         }
2640                 s->tlsext_ocsp_resplen = -1;
2641                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2642                 if (r == 0)
2643                         {
2644                         al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
2645                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2646                         }
2647                 if (r < 0)
2648                         {
2649                         al = SSL_AD_INTERNAL_ERROR;
2650                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2651                         }
2652                 }
2653
2654         switch (ret)
2655                 {
2656                 case SSL_TLSEXT_ERR_ALERT_FATAL:
2657                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2658                         return -1;
2659
2660                 case SSL_TLSEXT_ERR_ALERT_WARNING:
2661                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
2662                         return 1; 
2663                                         
2664                 case SSL_TLSEXT_ERR_NOACK:
2665                         s->servername_done=0;
2666                         default:
2667                 return 1;
2668                 }
2669         }
2670
2671 int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n) 
2672         {
2673         int al = -1;
2674         if (s->version < SSL3_VERSION)
2675                 return 1;
2676         if (ssl_scan_serverhello_tlsext(s, p, d, n, &al) <= 0) 
2677                 {
2678                 ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2679                 return 0;
2680                 }
2681
2682         if (ssl_check_serverhello_tlsext(s) <= 0) 
2683                 {
2684                 SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT,SSL_R_SERVERHELLO_TLSEXT);
2685                 return 0;
2686                 }
2687         return 1;
2688 }
2689
2690 /* Since the server cache lookup is done early on in the processing of the
2691  * ClientHello, and other operations depend on the result, we need to handle
2692  * any TLS session ticket extension at the same time.
2693  *
2694  *   session_id: points at the session ID in the ClientHello. This code will
2695  *       read past the end of this in order to parse out the session ticket
2696  *       extension, if any.
2697  *   len: the length of the session ID.
2698  *   limit: a pointer to the first byte after the ClientHello.
2699  *   ret: (output) on return, if a ticket was decrypted, then this is set to
2700  *       point to the resulting session.
2701  *
2702  * If s->tls_session_secret_cb is set then we are expecting a pre-shared key
2703  * ciphersuite, in which case we have no use for session tickets and one will
2704  * never be decrypted, nor will s->tlsext_ticket_expected be set to 1.
2705  *
2706  * Returns:
2707  *   -1: fatal error, either from parsing or decrypting the ticket.
2708  *    0: no ticket was found (or was ignored, based on settings).
2709  *    1: a zero length extension was found, indicating that the client supports
2710  *       session tickets but doesn't currently have one to offer.
2711  *    2: either s->tls_session_secret_cb was set, or a ticket was offered but
2712  *       couldn't be decrypted because of a non-fatal error.
2713  *    3: a ticket was successfully decrypted and *ret was set.
2714  *
2715  * Side effects:
2716  *   Sets s->tlsext_ticket_expected to 1 if the server will have to issue
2717  *   a new session ticket to the client because the client indicated support
2718  *   (and s->tls_session_secret_cb is NULL) but the client either doesn't have
2719  *   a session ticket or we couldn't use the one it gave us, or if
2720  *   s->ctx->tlsext_ticket_key_cb asked to renew the client's ticket.
2721  *   Otherwise, s->tlsext_ticket_expected is set to 0.
2722  */
2723 int tls1_process_ticket(SSL *s, unsigned char *session_id, int len,
2724                         const unsigned char *limit, SSL_SESSION **ret)
2725         {
2726         /* Point after session ID in client hello */
2727         const unsigned char *p = session_id + len;
2728         unsigned short i;
2729
2730         *ret = NULL;
2731         s->tlsext_ticket_expected = 0;
2732
2733         /* If tickets disabled behave as if no ticket present
2734          * to permit stateful resumption.
2735          */
2736         if (SSL_get_options(s) & SSL_OP_NO_TICKET)
2737                 return 0;
2738         if ((s->version <= SSL3_VERSION) || !limit)
2739                 return 0;
2740         if (p >= limit)
2741                 return -1;
2742         /* Skip past DTLS cookie */
2743         if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER)
2744                 {
2745                 i = *(p++);
2746                 p+= i;
2747                 if (p >= limit)
2748                         return -1;
2749                 }
2750         /* Skip past cipher list */
2751         n2s(p, i);
2752         p+= i;
2753         if (p >= limit)
2754                 return -1;
2755         /* Skip past compression algorithm list */
2756         i = *(p++);
2757         p += i;
2758         if (p > limit)
2759                 return -1;
2760         /* Now at start of extensions */
2761         if ((p + 2) >= limit)
2762                 return 0;
2763         n2s(p, i);
2764         while ((p + 4) <= limit)
2765                 {
2766                 unsigned short type, size;
2767                 n2s(p, type);
2768                 n2s(p, size);
2769                 if (p + size > limit)
2770                         return 0;
2771                 if (type == TLSEXT_TYPE_session_ticket)
2772                         {
2773                         int r;
2774                         if (size == 0)
2775                                 {
2776                                 /* The client will accept a ticket but doesn't
2777                                  * currently have one. */
2778                                 s->tlsext_ticket_expected = 1;
2779                                 return 1;
2780                                 }
2781                         if (s->tls_session_secret_cb)
2782                                 {
2783                                 /* Indicate that the ticket couldn't be
2784                                  * decrypted rather than generating the session
2785                                  * from ticket now, trigger abbreviated
2786                                  * handshake based on external mechanism to
2787                                  * calculate the master secret later. */
2788                                 return 2;
2789                                 }
2790                         r = tls_decrypt_ticket(s, p, size, session_id, len, ret);
2791                         switch (r)
2792                                 {
2793                                 case 2: /* ticket couldn't be decrypted */
2794                                         s->tlsext_ticket_expected = 1;
2795                                         return 2;
2796                                 case 3: /* ticket was decrypted */
2797                                         return r;
2798                                 case 4: /* ticket decrypted but need to renew */
2799                                         s->tlsext_ticket_expected = 1;
2800                                         return 3;
2801                                 default: /* fatal error */
2802                                         return -1;
2803                                 }
2804                         }
2805                 p += size;
2806                 }
2807         return 0;
2808         }
2809
2810 /* tls_decrypt_ticket attempts to decrypt a session ticket.
2811  *
2812  *   etick: points to the body of the session ticket extension.
2813  *   eticklen: the length of the session tickets extenion.
2814  *   sess_id: points at the session ID.
2815  *   sesslen: the length of the session ID.
2816  *   psess: (output) on return, if a ticket was decrypted, then this is set to
2817  *       point to the resulting session.
2818  *
2819  * Returns:
2820  *   -1: fatal error, either from parsing or decrypting the ticket.
2821  *    2: the ticket couldn't be decrypted.
2822  *    3: a ticket was successfully decrypted and *psess was set.
2823  *    4: same as 3, but the ticket needs to be renewed.
2824  */
2825 static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen,
2826                                 const unsigned char *sess_id, int sesslen,
2827                                 SSL_SESSION **psess)
2828         {
2829         SSL_SESSION *sess;
2830         unsigned char *sdec;
2831         const unsigned char *p;
2832         int slen, mlen, renew_ticket = 0;
2833         unsigned char tick_hmac[EVP_MAX_MD_SIZE];
2834         HMAC_CTX hctx;
2835         EVP_CIPHER_CTX ctx;
2836         SSL_CTX *tctx = s->initial_ctx;
2837         /* Need at least keyname + iv + some encrypted data */
2838         if (eticklen < 48)
2839                 return 2;
2840         /* Initialize session ticket encryption and HMAC contexts */
2841         HMAC_CTX_init(&hctx);
2842         EVP_CIPHER_CTX_init(&ctx);
2843         if (tctx->tlsext_ticket_key_cb)
2844                 {
2845                 unsigned char *nctick = (unsigned char *)etick;
2846                 int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
2847                                                         &ctx, &hctx, 0);
2848                 if (rv < 0)
2849                         return -1;
2850                 if (rv == 0)
2851                         return 2;
2852                 if (rv == 2)
2853                         renew_ticket = 1;
2854                 }
2855         else
2856                 {
2857                 /* Check key name matches */
2858                 if (memcmp(etick, tctx->tlsext_tick_key_name, 16))
2859                         return 2;
2860                 HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
2861                                         tlsext_tick_md(), NULL);
2862                 EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
2863                                 tctx->tlsext_tick_aes_key, etick + 16);
2864                 }
2865         /* Attempt to process session ticket, first conduct sanity and
2866          * integrity checks on ticket.
2867          */
2868         mlen = HMAC_size(&hctx);
2869         if (mlen < 0)
2870                 {
2871                 EVP_CIPHER_CTX_cleanup(&ctx);
2872                 return -1;
2873                 }
2874         eticklen -= mlen;
2875         /* Check HMAC of encrypted ticket */
2876         HMAC_Update(&hctx, etick, eticklen);
2877         HMAC_Final(&hctx, tick_hmac, NULL);
2878         HMAC_CTX_cleanup(&hctx);
2879         if (memcmp(tick_hmac, etick + eticklen, mlen))
2880                 return 2;
2881         /* Attempt to decrypt session data */
2882         /* Move p after IV to start of encrypted ticket, update length */
2883         p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx);
2884         eticklen -= 16 + EVP_CIPHER_CTX_iv_length(&ctx);
2885         sdec = OPENSSL_malloc(eticklen);
2886         if (!sdec)
2887                 {
2888                 EVP_CIPHER_CTX_cleanup(&ctx);
2889                 return -1;
2890                 }
2891         EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen);
2892         if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0)
2893                 return 2;
2894         slen += mlen;
2895         EVP_CIPHER_CTX_cleanup(&ctx);
2896         p = sdec;
2897
2898         sess = d2i_SSL_SESSION(NULL, &p, slen);
2899         OPENSSL_free(sdec);
2900         if (sess)
2901                 {
2902                 /* The session ID, if non-empty, is used by some clients to
2903                  * detect that the ticket has been accepted. So we copy it to
2904                  * the session structure. If it is empty set length to zero
2905                  * as required by standard.
2906                  */
2907                 if (sesslen)
2908                         memcpy(sess->session_id, sess_id, sesslen);
2909                 sess->session_id_length = sesslen;
2910                 *psess = sess;
2911                 if (renew_ticket)
2912                         return 4;
2913                 else
2914                         return 3;
2915                 }
2916         ERR_clear_error();
2917         /* For session parse failure, indicate that we need to send a new
2918          * ticket. */
2919         return 2;
2920         }
2921
2922 /* Tables to translate from NIDs to TLS v1.2 ids */
2923
2924 typedef struct 
2925         {
2926         int nid;
2927         int id;
2928         } tls12_lookup;
2929
2930 static tls12_lookup tls12_md[] = {
2931         {NID_md5, TLSEXT_hash_md5},
2932         {NID_sha1, TLSEXT_hash_sha1},
2933         {NID_sha224, TLSEXT_hash_sha224},
2934         {NID_sha256, TLSEXT_hash_sha256},
2935         {NID_sha384, TLSEXT_hash_sha384},
2936         {NID_sha512, TLSEXT_hash_sha512}
2937 };
2938
2939 static tls12_lookup tls12_sig[] = {
2940         {EVP_PKEY_RSA, TLSEXT_signature_rsa},
2941         {EVP_PKEY_DSA, TLSEXT_signature_dsa},
2942         {EVP_PKEY_EC, TLSEXT_signature_ecdsa}
2943 };
2944
2945 static int tls12_find_id(int nid, tls12_lookup *table, size_t tlen)
2946         {
2947         size_t i;
2948         for (i = 0; i < tlen; i++)
2949                 {
2950                 if (table[i].nid == nid)
2951                         return table[i].id;
2952                 }
2953         return -1;
2954         }
2955
2956 static int tls12_find_nid(int id, tls12_lookup *table, size_t tlen)
2957         {
2958         size_t i;
2959         for (i = 0; i < tlen; i++)
2960                 {
2961                 if ((table[i].id) == id)
2962                         return table[i].nid;
2963                 }
2964         return NID_undef;
2965         }
2966
2967 int tls12_get_sigandhash(unsigned char *p, const EVP_PKEY *pk, const EVP_MD *md)
2968         {
2969         int sig_id, md_id;
2970         if (!md)
2971                 return 0;
2972         md_id = tls12_find_id(EVP_MD_type(md), tls12_md,
2973                                 sizeof(tls12_md)/sizeof(tls12_lookup));
2974         if (md_id == -1)
2975                 return 0;
2976         sig_id = tls12_get_sigid(pk);
2977         if (sig_id == -1)
2978                 return 0;
2979         p[0] = (unsigned char)md_id;
2980         p[1] = (unsigned char)sig_id;
2981         return 1;
2982         }
2983
2984 int tls12_get_sigid(const EVP_PKEY *pk)
2985         {
2986         return tls12_find_id(pk->type, tls12_sig,
2987                                 sizeof(tls12_sig)/sizeof(tls12_lookup));
2988         }
2989
2990 const EVP_MD *tls12_get_hash(unsigned char hash_alg)
2991         {
2992         switch(hash_alg)
2993                 {
2994 #ifndef OPENSSL_NO_MD5
2995                 case TLSEXT_hash_md5:
2996 #ifdef OPENSSL_FIPS
2997                 if (FIPS_mode())
2998                         return NULL;
2999 #endif
3000                 return EVP_md5();
3001 #endif
3002 #ifndef OPENSSL_NO_SHA
3003                 case TLSEXT_hash_sha1:
3004                 return EVP_sha1();
3005 #endif
3006 #ifndef OPENSSL_NO_SHA256
3007                 case TLSEXT_hash_sha224:
3008                 return EVP_sha224();
3009
3010                 case TLSEXT_hash_sha256:
3011                 return EVP_sha256();
3012 #endif
3013 #ifndef OPENSSL_NO_SHA512
3014                 case TLSEXT_hash_sha384:
3015                 return EVP_sha384();
3016
3017                 case TLSEXT_hash_sha512:
3018                 return EVP_sha512();
3019 #endif
3020                 default:
3021                 return NULL;
3022
3023                 }
3024         }
3025
3026 static int tls12_get_pkey_idx(unsigned char sig_alg)
3027         {
3028         switch(sig_alg)
3029                 {
3030 #ifndef OPENSSL_NO_RSA
3031         case TLSEXT_signature_rsa:
3032                 return SSL_PKEY_RSA_SIGN;
3033 #endif
3034 #ifndef OPENSSL_NO_DSA
3035         case TLSEXT_signature_dsa:
3036                 return SSL_PKEY_DSA_SIGN;
3037 #endif
3038 #ifndef OPENSSL_NO_ECDSA
3039         case TLSEXT_signature_ecdsa:
3040                 return SSL_PKEY_ECC;
3041 #endif
3042                 }
3043         return -1;
3044         }
3045
3046 /* Convert TLS 1.2 signature algorithm extension values into NIDs */
3047 static void tls1_lookup_sigalg(int *phash_nid, int *psign_nid,
3048                         int *psignhash_nid, const unsigned char *data)
3049         {
3050         int sign_nid = 0, hash_nid = 0;
3051         if (!phash_nid && !psign_nid && !psignhash_nid)
3052                 return;
3053         if (phash_nid || psignhash_nid)
3054                 {
3055                 hash_nid = tls12_find_nid(data[0], tls12_md,
3056                                         sizeof(tls12_md)/sizeof(tls12_lookup));
3057                 if (phash_nid)
3058                         *phash_nid = hash_nid;
3059                 }
3060         if (psign_nid || psignhash_nid)
3061                 {
3062                 sign_nid = tls12_find_nid(data[1], tls12_sig,
3063                                         sizeof(tls12_sig)/sizeof(tls12_lookup));
3064                 if (psign_nid)
3065                         *psign_nid = sign_nid;
3066                 }
3067         if (psignhash_nid)
3068                 {
3069                 if (sign_nid && hash_nid)
3070                         OBJ_find_sigid_by_algs(psignhash_nid,
3071                                                         hash_nid, sign_nid);
3072                 else
3073                         *psignhash_nid = NID_undef;
3074                 }
3075         }
3076 /* Given preference and allowed sigalgs set shared sigalgs */
3077 static int tls12_do_shared_sigalgs(TLS_SIGALGS *shsig,
3078                                 const unsigned char *pref, size_t preflen,
3079                                 const unsigned char *allow, size_t allowlen)
3080         {
3081         const unsigned char *ptmp, *atmp;
3082         size_t i, j, nmatch = 0;
3083         for (i = 0, ptmp = pref; i < preflen; i+=2, ptmp+=2)
3084                 {
3085                 /* Skip disabled hashes or signature algorithms */
3086                 if (tls12_get_hash(ptmp[0]) == NULL)
3087                         continue;
3088                 if (tls12_get_pkey_idx(ptmp[1]) == -1)
3089                         continue;
3090                 for (j = 0, atmp = allow; j < allowlen; j+=2, atmp+=2)
3091                         {
3092                         if (ptmp[0] == atmp[0] && ptmp[1] == atmp[1])
3093                                 {
3094                                 nmatch++;
3095                                 if (shsig)
3096                                         {
3097                                         shsig->rhash = ptmp[0];
3098                                         shsig->rsign = ptmp[1];
3099                                         tls1_lookup_sigalg(&shsig->hash_nid,
3100                                                 &shsig->sign_nid,
3101                                                 &shsig->signandhash_nid,
3102                                                 ptmp);
3103                                         shsig++;
3104                                         }
3105                                 break;
3106                                 }
3107                         }
3108                 }
3109         return nmatch;
3110         }
3111
3112 /* Set shared signature algorithms for SSL structures */
3113 static int tls1_set_shared_sigalgs(SSL *s)
3114         {
3115         const unsigned char *pref, *allow, *conf;
3116         size_t preflen, allowlen, conflen;
3117         size_t nmatch;
3118         TLS_SIGALGS *salgs = NULL;
3119         CERT *c = s->cert;
3120         /* If client use client signature algorithms if not NULL */
3121         if (!s->server && c->client_sigalgs)
3122                 {
3123                 conf = c->client_sigalgs;
3124                 conflen = c->client_sigalgslen;
3125                 }
3126         else if (c->conf_sigalgs)
3127                 {
3128                 conf = c->conf_sigalgs;
3129                 conflen = c->conf_sigalgslen;
3130                 }
3131         else
3132                 {
3133                 conf = tls12_sigalgs;
3134                 conflen = sizeof(tls12_sigalgs);
3135 #ifdef OPENSSL_FIPS
3136                 if (FIPS_mode())
3137                         conflen -= 2;
3138 #endif
3139                 }
3140         if(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE)
3141                 {
3142                 pref = conf;
3143                 preflen = conflen;
3144                 allow = c->peer_sigalgs;
3145                 allowlen = c->peer_sigalgslen;
3146                 }
3147         else
3148                 {
3149                 allow = conf;
3150                 allowlen = conflen;
3151                 pref = c->peer_sigalgs;
3152                 preflen = c->peer_sigalgslen;
3153                 }
3154         nmatch = tls12_do_shared_sigalgs(NULL, pref, preflen, allow, allowlen);
3155         if (!nmatch)
3156                 return 1;
3157         salgs = OPENSSL_malloc(nmatch * sizeof(TLS_SIGALGS));
3158         if (!salgs)
3159                 return 0;
3160         nmatch = tls12_do_shared_sigalgs(salgs, pref, preflen, allow, allowlen);
3161         c->shared_sigalgs = salgs;
3162         c->shared_sigalgslen = nmatch;
3163         return 1;
3164         }
3165                 
3166
3167 /* Set preferred digest for each key type */
3168
3169 int tls1_process_sigalgs(SSL *s, const unsigned char *data, int dsize)
3170         {
3171         int idx;
3172         size_t i;
3173         const EVP_MD *md;
3174         CERT *c = s->cert;
3175         TLS_SIGALGS *sigptr;
3176         /* Extension ignored for TLS versions below 1.2 */
3177         if (TLS1_get_version(s) < TLS1_2_VERSION)
3178                 return 1;
3179         /* Should never happen */
3180         if (!c)
3181                 return 0;
3182
3183         c->pkeys[SSL_PKEY_DSA_SIGN].digest = NULL;
3184         c->pkeys[SSL_PKEY_RSA_SIGN].digest = NULL;
3185         c->pkeys[SSL_PKEY_RSA_ENC].digest = NULL;
3186         c->pkeys[SSL_PKEY_ECC].digest = NULL;
3187
3188         c->peer_sigalgs = OPENSSL_malloc(dsize);
3189         if (!c->peer_sigalgs)
3190                 return 0;
3191         c->peer_sigalgslen = dsize;
3192         memcpy(c->peer_sigalgs, data, dsize);
3193
3194         tls1_set_shared_sigalgs(s);
3195
3196         for (i = 0, sigptr = c->shared_sigalgs;
3197                         i < c->shared_sigalgslen; i++, sigptr++)
3198                 {
3199                 idx = tls12_get_pkey_idx(sigptr->rsign);
3200                 if (idx > 0 && c->pkeys[idx].digest == NULL)
3201                         {
3202                         md = tls12_get_hash(sigptr->rhash);
3203                         c->pkeys[idx].digest = md;
3204                         if (idx == SSL_PKEY_RSA_SIGN)
3205                                 c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
3206                         }
3207
3208                 }
3209         /* In strict mode leave unset digests as NULL to indicate we can't
3210          * use the certificate for signing.
3211          */
3212         if (!(s->cert->cert_flags & SSL_CERT_FLAG_TLS_STRICT))
3213                 {
3214                 /* Set any remaining keys to default values. NOTE: if alg is
3215                  * not supported it stays as NULL.
3216                  */
3217 #ifndef OPENSSL_NO_DSA
3218                 if (!c->pkeys[SSL_PKEY_DSA_SIGN].digest)
3219                         c->pkeys[SSL_PKEY_DSA_SIGN].digest = EVP_sha1();
3220 #endif
3221 #ifndef OPENSSL_NO_RSA
3222                 if (!c->pkeys[SSL_PKEY_RSA_SIGN].digest)
3223                         {
3224                         c->pkeys[SSL_PKEY_RSA_SIGN].digest = EVP_sha1();
3225                         c->pkeys[SSL_PKEY_RSA_ENC].digest = EVP_sha1();
3226                         }
3227 #endif
3228 #ifndef OPENSSL_NO_ECDSA
3229                 if (!c->pkeys[SSL_PKEY_ECC].digest)
3230                         c->pkeys[SSL_PKEY_ECC].digest = EVP_sha1();
3231 #endif
3232                 }
3233         return 1;
3234         }
3235
3236
3237 int SSL_get_sigalgs(SSL *s, int idx,
3238                         int *psign, int *phash, int *psignhash,
3239                         unsigned char *rsig, unsigned char *rhash)
3240         {
3241         const unsigned char *psig = s->cert->peer_sigalgs;
3242         if (psig == NULL)
3243                 return 0;
3244         if (idx >= 0)
3245                 {
3246                 idx <<= 1;
3247                 if (idx >= (int)s->cert->peer_sigalgslen)
3248                         return 0;
3249                 psig += idx;
3250                 if (rhash)
3251                         *rhash = psig[0];
3252                 if (rsig)
3253                         *rsig = psig[1];
3254                 tls1_lookup_sigalg(phash, psign, psignhash, psig);
3255                 }
3256         return s->cert->peer_sigalgslen / 2;
3257         }
3258
3259 int SSL_get_shared_sigalgs(SSL *s, int idx,
3260                         int *psign, int *phash, int *psignhash,
3261                         unsigned char *rsig, unsigned char *rhash)
3262         {
3263         TLS_SIGALGS *shsigalgs = s->cert->shared_sigalgs;
3264         if (!shsigalgs || idx >= (int)s->cert->shared_sigalgslen)
3265                 return 0;
3266         shsigalgs += idx;
3267         if (phash)
3268                 *phash = shsigalgs->hash_nid;
3269         if (psign)
3270                 *psign = shsigalgs->sign_nid;
3271         if (psignhash)
3272                 *psignhash = shsigalgs->signandhash_nid;
3273         if (rsig)
3274                 *rsig = shsigalgs->rsign;
3275         if (rhash)
3276                 *rhash = shsigalgs->rhash;
3277         return s->cert->shared_sigalgslen;
3278         }
3279         
3280
3281 #ifndef OPENSSL_NO_HEARTBEATS
3282 int
3283 tls1_process_heartbeat(SSL *s)
3284         {
3285         unsigned char *p = &s->s3->rrec.data[0], *pl;
3286         unsigned short hbtype;
3287         unsigned int payload;
3288         unsigned int padding = 16; /* Use minimum padding */
3289
3290         /* Read type and payload length first */
3291         hbtype = *p++;
3292         n2s(p, payload);
3293         pl = p;
3294
3295         if (s->msg_callback)
3296                 s->msg_callback(0, s->version, TLS1_RT_HEARTBEAT,
3297                         &s->s3->rrec.data[0], s->s3->rrec.length,
3298                         s, s->msg_callback_arg);
3299
3300         if (hbtype == TLS1_HB_REQUEST)
3301                 {
3302                 unsigned char *buffer, *bp;
3303                 int r;
3304
3305                 /* Allocate memory for the response, size is 1 bytes
3306                  * message type, plus 2 bytes payload length, plus
3307                  * payload, plus padding
3308                  */
3309                 buffer = OPENSSL_malloc(1 + 2 + payload + padding);
3310                 bp = buffer;
3311                 
3312                 /* Enter response type, length and copy payload */
3313                 *bp++ = TLS1_HB_RESPONSE;
3314                 s2n(payload, bp);
3315                 memcpy(bp, pl, payload);
3316                 bp += payload;
3317                 /* Random padding */
3318                 RAND_pseudo_bytes(bp, padding);
3319
3320                 r = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buffer, 3 + payload + padding);
3321
3322                 if (r >= 0 && s->msg_callback)
3323                         s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
3324                                 buffer, 3 + payload + padding,
3325                                 s, s->msg_callback_arg);
3326
3327                 OPENSSL_free(buffer);
3328
3329                 if (r < 0)
3330                         return r;
3331                 }
3332         else if (hbtype == TLS1_HB_RESPONSE)
3333                 {
3334                 unsigned int seq;
3335                 
3336                 /* We only send sequence numbers (2 bytes unsigned int),
3337                  * and 16 random bytes, so we just try to read the
3338                  * sequence number */
3339                 n2s(pl, seq);
3340                 
3341                 if (payload == 18 && seq == s->tlsext_hb_seq)
3342                         {
3343                         s->tlsext_hb_seq++;
3344                         s->tlsext_hb_pending = 0;
3345                         }
3346                 }
3347
3348         return 0;
3349         }
3350
3351 int
3352 tls1_heartbeat(SSL *s)
3353         {
3354         unsigned char *buf, *p;
3355         int ret;
3356         unsigned int payload = 18; /* Sequence number + random bytes */
3357         unsigned int padding = 16; /* Use minimum padding */
3358
3359         /* Only send if peer supports and accepts HB requests... */
3360         if (!(s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) ||
3361             s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_SEND_REQUESTS)
3362                 {
3363                 SSLerr(SSL_F_TLS1_HEARTBEAT,SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT);
3364                 return -1;
3365                 }
3366
3367         /* ...and there is none in flight yet... */
3368         if (s->tlsext_hb_pending)
3369                 {
3370                 SSLerr(SSL_F_TLS1_HEARTBEAT,SSL_R_TLS_HEARTBEAT_PENDING);
3371                 return -1;
3372                 }
3373                 
3374         /* ...and no handshake in progress. */
3375         if (SSL_in_init(s) || s->in_handshake)
3376                 {
3377                 SSLerr(SSL_F_TLS1_HEARTBEAT,SSL_R_UNEXPECTED_MESSAGE);
3378                 return -1;
3379                 }
3380                 
3381         /* Check if padding is too long, payload and padding
3382          * must not exceed 2^14 - 3 = 16381 bytes in total.
3383          */
3384         OPENSSL_assert(payload + padding <= 16381);
3385
3386         /* Create HeartBeat message, we just use a sequence number
3387          * as payload to distuingish different messages and add
3388          * some random stuff.
3389          *  - Message Type, 1 byte
3390          *  - Payload Length, 2 bytes (unsigned int)
3391          *  - Payload, the sequence number (2 bytes uint)
3392          *  - Payload, random bytes (16 bytes uint)
3393          *  - Padding
3394          */
3395         buf = OPENSSL_malloc(1 + 2 + payload + padding);
3396         p = buf;
3397         /* Message Type */
3398         *p++ = TLS1_HB_REQUEST;
3399         /* Payload length (18 bytes here) */
3400         s2n(payload, p);
3401         /* Sequence number */
3402         s2n(s->tlsext_hb_seq, p);
3403         /* 16 random bytes */
3404         RAND_pseudo_bytes(p, 16);
3405         p += 16;
3406         /* Random padding */
3407         RAND_pseudo_bytes(p, padding);
3408
3409         ret = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buf, 3 + payload + padding);
3410         if (ret >= 0)
3411                 {
3412                 if (s->msg_callback)
3413                         s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
3414                                 buf, 3 + payload + padding,
3415                                 s, s->msg_callback_arg);
3416
3417                 s->tlsext_hb_pending = 1;
3418                 }
3419                 
3420         OPENSSL_free(buf);
3421
3422         return ret;
3423         }
3424 #endif
3425
3426 #define MAX_SIGALGLEN   (TLSEXT_hash_num * TLSEXT_signature_num * 2)
3427
3428 typedef struct
3429         {
3430         size_t sigalgcnt;
3431         int sigalgs[MAX_SIGALGLEN];
3432         } sig_cb_st;
3433
3434 static int sig_cb(const char *elem, int len, void *arg)
3435         {
3436         sig_cb_st *sarg = arg;
3437         size_t i;
3438         char etmp[20], *p;
3439         int sig_alg, hash_alg;
3440         if (sarg->sigalgcnt == MAX_SIGALGLEN)
3441                 return 0;
3442         if (len > (int)(sizeof(etmp) - 1))
3443                 return 0;
3444         memcpy(etmp, elem, len);
3445         etmp[len] = 0;
3446         p = strchr(etmp, '+');
3447         if (!p)
3448                 return 0;
3449         *p = 0;
3450         p++;
3451         if (!*p)
3452                 return 0;
3453
3454         if (!strcmp(etmp, "RSA"))
3455                 sig_alg = EVP_PKEY_RSA;
3456         else if (!strcmp(etmp, "DSA"))
3457                 sig_alg = EVP_PKEY_DSA;
3458         else if (!strcmp(etmp, "ECDSA"))
3459                 sig_alg = EVP_PKEY_EC;
3460         else return 0;
3461
3462         hash_alg = OBJ_sn2nid(p);
3463         if (hash_alg == NID_undef)
3464                 hash_alg = OBJ_ln2nid(p);
3465         if (hash_alg == NID_undef)
3466                 return 0;
3467
3468         for (i = 0; i < sarg->sigalgcnt; i+=2)
3469                 {
3470                 if (sarg->sigalgs[i] == sig_alg
3471                         && sarg->sigalgs[i + 1] == hash_alg)
3472                         return 0;
3473                 }
3474         sarg->sigalgs[sarg->sigalgcnt++] = hash_alg;
3475         sarg->sigalgs[sarg->sigalgcnt++] = sig_alg;
3476         return 1;
3477         }
3478
3479 /* Set suppored signature algorithms based on a colon separated list
3480  * of the form sig+hash e.g. RSA+SHA512:DSA+SHA512 */
3481 int tls1_set_sigalgs_list(CERT *c, const char *str, int client)
3482         {
3483         sig_cb_st sig;
3484         sig.sigalgcnt = 0;
3485         if (!CONF_parse_list(str, ':', 1, sig_cb, &sig))
3486                 return 0;
3487         return tls1_set_sigalgs(c, sig.sigalgs, sig.sigalgcnt, client);
3488         }
3489
3490 int tls1_set_sigalgs(CERT *c, const int *psig_nids, size_t salglen, int client)
3491         {
3492         unsigned char *sigalgs, *sptr;
3493         int rhash, rsign;
3494         size_t i;
3495         if (salglen & 1)
3496                 return 0;
3497         sigalgs = OPENSSL_malloc(salglen);
3498         if (sigalgs == NULL)
3499                 return 0;
3500         for (i = 0, sptr = sigalgs; i < salglen; i+=2)
3501                 {
3502                 rhash = tls12_find_id(*psig_nids++, tls12_md,
3503                                         sizeof(tls12_md)/sizeof(tls12_lookup));
3504                 rsign = tls12_find_id(*psig_nids++, tls12_sig,
3505                                 sizeof(tls12_sig)/sizeof(tls12_lookup));
3506
3507                 if (rhash == -1 || rsign == -1)
3508                         goto err;
3509                 *sptr++ = rhash;
3510                 *sptr++ = rsign;
3511                 }
3512
3513         if (client)
3514                 {
3515                 if (c->client_sigalgs)
3516                         OPENSSL_free(c->client_sigalgs);
3517                 c->client_sigalgs = sigalgs;
3518                 c->client_sigalgslen = salglen;
3519                 }
3520         else
3521                 {
3522                 if (c->conf_sigalgs)
3523                         OPENSSL_free(c->conf_sigalgs);
3524                 c->conf_sigalgs = sigalgs;
3525                 c->conf_sigalgslen = salglen;
3526                 }
3527
3528         return 1;
3529
3530         err:
3531         OPENSSL_free(sigalgs);
3532         return 0;
3533         }
3534
3535 static int tls1_check_sig_alg(CERT *c, X509 *x, int default_nid)
3536         {
3537         int sig_nid;
3538         size_t i;
3539         if (default_nid == -1)
3540                 return 1;
3541         sig_nid = X509_get_signature_nid(x);
3542         if (default_nid)
3543                 return sig_nid == default_nid ? 1 : 0;
3544         for (i = 0; i < c->shared_sigalgslen; i++)
3545                 if (sig_nid == c->shared_sigalgs[i].signandhash_nid)
3546                         return 1;
3547         return 0;
3548         }
3549
3550 /* Check certificate chain is consistent with TLS extensions and is
3551  * usable by server.
3552  */
3553 int tls1_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain,
3554                                                                         int idx)
3555         {
3556         int i;
3557         int rv = CERT_PKEY_INVALID;
3558         CERT_PKEY *cpk = NULL;
3559         CERT *c = s->cert;
3560         if (idx != -1)
3561                 {
3562