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