1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to. The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 * must display the following acknowledgement:
32 * "This product includes cryptographic software written by
33 * Eric Young (eay@cryptsoft.com)"
34 * The word 'cryptographic' can be left out if the rouines from the library
35 * being used are not cryptographic related :-).
36 * 4. If you include any Windows specific code (or a derivative thereof) from
37 * the apps directory (application code) you must include an acknowledgement:
38 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed. i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.]
57 /* ====================================================================
58 * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
60 * Redistribution and use in source and binary forms, with or without
61 * modification, are permitted provided that the following conditions
64 * 1. Redistributions of source code must retain the above copyright
65 * notice, this list of conditions and the following disclaimer.
67 * 2. Redistributions in binary form must reproduce the above copyright
68 * notice, this list of conditions and the following disclaimer in
69 * the documentation and/or other materials provided with the
72 * 3. All advertising materials mentioning features or use of this
73 * software must display the following acknowledgment:
74 * "This product includes software developed by the OpenSSL Project
75 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78 * endorse or promote products derived from this software without
79 * prior written permission. For written permission, please contact
80 * openssl-core@openssl.org.
82 * 5. Products derived from this software may not be called "OpenSSL"
83 * nor may "OpenSSL" appear in their names without prior written
84 * permission of the OpenSSL Project.
86 * 6. Redistributions of any form whatsoever must retain the following
88 * "This product includes software developed by the OpenSSL Project
89 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
95 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102 * OF THE POSSIBILITY OF SUCH DAMAGE.
103 * ====================================================================
105 * This product includes cryptographic software written by Eric Young
106 * (eay@cryptsoft.com). This product includes software written by Tim
107 * Hudson (tjh@cryptsoft.com). */
113 #include <openssl/bytestring.h>
114 #include <openssl/evp.h>
115 #include <openssl/hmac.h>
116 #include <openssl/mem.h>
117 #include <openssl/obj.h>
118 #include <openssl/rand.h>
120 #include "ssl_locl.h"
121 static int tls_decrypt_ticket(SSL *s, const unsigned char *tick, int ticklen,
122 const unsigned char *sess_id, int sesslen,
123 SSL_SESSION **psess);
124 static int ssl_check_clienthello_tlsext(SSL *s);
125 static int ssl_check_serverhello_tlsext(SSL *s);
127 SSL3_ENC_METHOD TLSv1_enc_data={
130 tls1_setup_key_block,
131 tls1_generate_master_secret,
132 tls1_change_cipher_state,
133 tls1_final_finish_mac,
134 TLS1_FINISH_MAC_LENGTH,
135 tls1_cert_verify_mac,
136 TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
137 TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
139 tls1_export_keying_material,
141 SSL3_HM_HEADER_LENGTH,
142 ssl3_set_handshake_header,
146 SSL3_ENC_METHOD TLSv1_1_enc_data={
149 tls1_setup_key_block,
150 tls1_generate_master_secret,
151 tls1_change_cipher_state,
152 tls1_final_finish_mac,
153 TLS1_FINISH_MAC_LENGTH,
154 tls1_cert_verify_mac,
155 TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
156 TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
158 tls1_export_keying_material,
159 SSL_ENC_FLAG_EXPLICIT_IV,
160 SSL3_HM_HEADER_LENGTH,
161 ssl3_set_handshake_header,
165 SSL3_ENC_METHOD TLSv1_2_enc_data={
168 tls1_setup_key_block,
169 tls1_generate_master_secret,
170 tls1_change_cipher_state,
171 tls1_final_finish_mac,
172 TLS1_FINISH_MAC_LENGTH,
173 tls1_cert_verify_mac,
174 TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
175 TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
177 tls1_export_keying_material,
178 SSL_ENC_FLAG_EXPLICIT_IV|SSL_ENC_FLAG_SIGALGS|SSL_ENC_FLAG_SHA256_PRF
179 |SSL_ENC_FLAG_TLS1_2_CIPHERS,
180 SSL3_HM_HEADER_LENGTH,
181 ssl3_set_handshake_header,
185 static int compare_uint16_t(const void *p1, const void *p2)
187 uint16_t u1 = *((const uint16_t*)p1);
188 uint16_t u2 = *((const uint16_t*)p2);
203 /* Per http://tools.ietf.org/html/rfc5246#section-7.4.1.4, there may not be more
204 * than one extension of the same type in a ClientHello or ServerHello. This
205 * function does an initial scan over the extensions block to filter those
207 static int tls1_check_duplicate_extensions(const CBS *cbs)
209 CBS extensions = *cbs;
210 size_t num_extensions = 0, i = 0;
211 uint16_t *extension_types = NULL;
214 /* First pass: count the extensions. */
215 while (CBS_len(&extensions) > 0)
220 if (!CBS_get_u16(&extensions, &type) ||
221 !CBS_get_u16_length_prefixed(&extensions, &extension))
229 if (num_extensions == 0)
234 extension_types = (uint16_t*)OPENSSL_malloc(sizeof(uint16_t) * num_extensions);
235 if (extension_types == NULL)
237 OPENSSL_PUT_ERROR(SSL, tls1_check_duplicate_extensions, ERR_R_MALLOC_FAILURE);
241 /* Second pass: gather the extension types. */
243 for (i = 0; i < num_extensions; i++)
247 if (!CBS_get_u16(&extensions, &extension_types[i]) ||
248 !CBS_get_u16_length_prefixed(&extensions, &extension))
250 /* This should not happen. */
254 assert(CBS_len(&extensions) == 0);
256 /* Sort the extensions and make sure there are no duplicates. */
257 qsort(extension_types, num_extensions, sizeof(uint16_t), compare_uint16_t);
258 for (i = 1; i < num_extensions; i++)
260 if (extension_types[i-1] == extension_types[i])
269 OPENSSL_free(extension_types);
273 char ssl_early_callback_init(struct ssl_early_callback_ctx *ctx)
275 CBS client_hello, session_id, cipher_suites, compression_methods, extensions;
277 CBS_init(&client_hello, ctx->client_hello, ctx->client_hello_len);
279 /* Skip client version. */
280 if (!CBS_skip(&client_hello, 2))
283 /* Skip client nonce. */
284 if (!CBS_skip(&client_hello, 32))
287 /* Extract session_id. */
288 if (!CBS_get_u8_length_prefixed(&client_hello, &session_id))
290 ctx->session_id = CBS_data(&session_id);
291 ctx->session_id_len = CBS_len(&session_id);
293 /* Skip past DTLS cookie */
294 if (SSL_IS_DTLS(ctx->ssl))
298 if (!CBS_get_u8_length_prefixed(&client_hello, &cookie))
302 /* Extract cipher_suites. */
303 if (!CBS_get_u16_length_prefixed(&client_hello, &cipher_suites) ||
304 CBS_len(&cipher_suites) < 2 ||
305 (CBS_len(&cipher_suites) & 1) != 0)
307 ctx->cipher_suites = CBS_data(&cipher_suites);
308 ctx->cipher_suites_len = CBS_len(&cipher_suites);
310 /* Extract compression_methods. */
311 if (!CBS_get_u8_length_prefixed(&client_hello, &compression_methods) ||
312 CBS_len(&compression_methods) < 1)
314 ctx->compression_methods = CBS_data(&compression_methods);
315 ctx->compression_methods_len = CBS_len(&compression_methods);
317 /* If the ClientHello ends here then it's valid, but doesn't have any
318 * extensions. (E.g. SSLv3.) */
319 if (CBS_len(&client_hello) == 0)
321 ctx->extensions = NULL;
322 ctx->extensions_len = 0;
326 /* Extract extensions and check it is valid. */
327 if (!CBS_get_u16_length_prefixed(&client_hello, &extensions) ||
328 !tls1_check_duplicate_extensions(&extensions) ||
329 CBS_len(&client_hello) != 0)
331 ctx->extensions = CBS_data(&extensions);
332 ctx->extensions_len = CBS_len(&extensions);
338 SSL_early_callback_ctx_extension_get(const struct ssl_early_callback_ctx *ctx,
339 uint16_t extension_type,
340 const unsigned char **out_data,
345 CBS_init(&extensions, ctx->extensions, ctx->extensions_len);
347 while (CBS_len(&extensions) != 0)
352 /* Decode the next extension. */
353 if (!CBS_get_u16(&extensions, &type) ||
354 !CBS_get_u16_length_prefixed(&extensions, &extension))
357 if (type == extension_type)
359 *out_data = CBS_data(&extension);
360 *out_len = CBS_len(&extension);
369 static const int nid_list[] =
371 NID_sect163k1, /* sect163k1 (1) */
372 NID_sect163r1, /* sect163r1 (2) */
373 NID_sect163r2, /* sect163r2 (3) */
374 NID_sect193r1, /* sect193r1 (4) */
375 NID_sect193r2, /* sect193r2 (5) */
376 NID_sect233k1, /* sect233k1 (6) */
377 NID_sect233r1, /* sect233r1 (7) */
378 NID_sect239k1, /* sect239k1 (8) */
379 NID_sect283k1, /* sect283k1 (9) */
380 NID_sect283r1, /* sect283r1 (10) */
381 NID_sect409k1, /* sect409k1 (11) */
382 NID_sect409r1, /* sect409r1 (12) */
383 NID_sect571k1, /* sect571k1 (13) */
384 NID_sect571r1, /* sect571r1 (14) */
385 NID_secp160k1, /* secp160k1 (15) */
386 NID_secp160r1, /* secp160r1 (16) */
387 NID_secp160r2, /* secp160r2 (17) */
388 NID_secp192k1, /* secp192k1 (18) */
389 NID_X9_62_prime192v1, /* secp192r1 (19) */
390 NID_secp224k1, /* secp224k1 (20) */
391 NID_secp224r1, /* secp224r1 (21) */
392 NID_secp256k1, /* secp256k1 (22) */
393 NID_X9_62_prime256v1, /* secp256r1 (23) */
394 NID_secp384r1, /* secp384r1 (24) */
395 NID_secp521r1, /* secp521r1 (25) */
396 NID_brainpoolP256r1, /* brainpoolP256r1 (26) */
397 NID_brainpoolP384r1, /* brainpoolP384r1 (27) */
398 NID_brainpoolP512r1 /* brainpool512r1 (28) */
401 static const uint8_t ecformats_default[] =
403 TLSEXT_ECPOINTFORMAT_uncompressed,
406 static const uint16_t eccurves_default[] =
408 23, /* secp256r1 (23) */
409 24, /* secp384r1 (24) */
410 25, /* secp521r1 (25) */
413 int tls1_ec_curve_id2nid(uint16_t curve_id)
415 /* ECC curves from draft-ietf-tls-ecc-12.txt (Oct. 17, 2005) */
416 if (curve_id < 1 || curve_id > sizeof(nid_list)/sizeof(nid_list[0]))
418 return nid_list[curve_id-1];
421 uint16_t tls1_ec_nid2curve_id(int nid)
424 for (i = 0; i < sizeof(nid_list)/sizeof(nid_list[0]); i++)
426 /* nid_list[i] stores the NID corresponding to curve ID i+1. */
427 if (nid == nid_list[i])
430 /* Use 0 for non-existent curve ID. Note: this assumes that curve ID 0
431 * will never be allocated. */
435 /* tls1_get_curvelist sets |*out_curve_ids| and |*out_curve_ids_len| to the list
436 * of allowed curve IDs. If |get_client_curves| is non-zero, return the client
437 * curve list. Otherwise, return the preferred list. */
438 static void tls1_get_curvelist(SSL *s, int get_client_curves,
439 const uint16_t **out_curve_ids, size_t *out_curve_ids_len)
441 if (get_client_curves)
443 *out_curve_ids = s->session->tlsext_ellipticcurvelist;
444 *out_curve_ids_len = s->session->tlsext_ellipticcurvelist_length;
448 *out_curve_ids = s->tlsext_ellipticcurvelist;
449 *out_curve_ids_len = s->tlsext_ellipticcurvelist_length;
452 *out_curve_ids = eccurves_default;
453 *out_curve_ids_len = sizeof(eccurves_default) / sizeof(eccurves_default[0]);
457 int tls1_check_curve(SSL *s, CBS *cbs, uint16_t *out_curve_id)
461 const uint16_t *curves;
462 size_t curves_len, i;
464 /* Only support named curves. */
465 if (!CBS_get_u8(cbs, &curve_type) ||
466 curve_type != NAMED_CURVE_TYPE ||
467 !CBS_get_u16(cbs, &curve_id))
470 tls1_get_curvelist(s, 0, &curves, &curves_len);
471 for (i = 0; i < curves_len; i++)
473 if (curve_id == curves[i])
475 *out_curve_id = curve_id;
482 int tls1_get_shared_curve(SSL *s)
484 const uint16_t *pref, *supp;
485 size_t preflen, supplen, i, j;
487 /* Can't do anything on client side */
491 /* Return first preference shared curve */
492 tls1_get_curvelist(s, !!(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE),
494 tls1_get_curvelist(s, !(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE),
496 for (i = 0; i < preflen; i++)
498 for (j = 0; j < supplen; j++)
500 if (pref[i] == supp[j])
501 return tls1_ec_curve_id2nid(pref[i]);
507 /* NOTE: tls1_ec_curve_id2nid and tls1_set_curves assume that
509 * (a) 0 is not a valid curve ID.
511 * (b) The largest curve ID is 31.
513 * Those implementations must be revised before adding support for curve IDs
514 * that break these assumptions. */
515 OPENSSL_COMPILE_ASSERT(
516 (sizeof(nid_list) / sizeof(nid_list[0])) < 32, small_curve_ids);
518 int tls1_set_curves(uint16_t **out_curve_ids, size_t *out_curve_ids_len,
519 const int *curves, size_t ncurves)
523 /* Bitmap of curves included to detect duplicates: only works
524 * while curve ids < 32
526 uint32_t dup_list = 0;
527 curve_ids = (uint16_t*)OPENSSL_malloc(ncurves * sizeof(uint16_t));
530 for (i = 0; i < ncurves; i++)
534 id = tls1_ec_nid2curve_id(curves[i]);
535 idmask = ((uint32_t)1) << id;
536 if (!id || (dup_list & idmask))
538 OPENSSL_free(curve_ids);
545 OPENSSL_free(*out_curve_ids);
546 *out_curve_ids = curve_ids;
547 *out_curve_ids_len = ncurves;
551 /* tls1_curve_params_from_ec_key sets |*out_curve_id| and |*out_comp_id| to the
552 * TLS curve ID and point format, respectively, for |ec|. It returns one on
553 * success and zero on failure. */
554 static int tls1_curve_params_from_ec_key(uint16_t *out_curve_id, uint8_t *out_comp_id, EC_KEY *ec)
562 grp = EC_KEY_get0_group(ec);
566 /* Determine curve ID */
567 nid = EC_GROUP_get_curve_name(grp);
568 id = tls1_ec_nid2curve_id(nid);
572 /* Set the named curve ID. Arbitrary explicit curves are not
578 if (EC_KEY_get0_public_key(ec) == NULL)
580 if (EC_KEY_get_conv_form(ec) == POINT_CONVERSION_COMPRESSED)
581 *out_comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
583 *out_comp_id = TLSEXT_ECPOINTFORMAT_uncompressed;
588 /* Check an EC key is compatible with extensions */
589 static int tls1_check_ec_key(SSL *s,
590 const uint16_t *curve_id, const uint8_t *comp_id)
592 const uint16_t *curves;
593 size_t curves_len, i;
595 /* If point formats extension present check it, otherwise everything
596 * is supported (see RFC4492).
598 if (comp_id && s->session->tlsext_ecpointformatlist)
600 uint8_t *p = s->session->tlsext_ecpointformatlist;
601 size_t plen = s->session->tlsext_ecpointformatlist_length;
602 for (i = 0; i < plen; i++)
604 if (*comp_id == p[i])
612 /* Check curve is consistent with client and server preferences */
613 for (j = 0; j <= 1; j++)
615 tls1_get_curvelist(s, j, &curves, &curves_len);
616 for (i = 0; i < curves_len; i++)
618 if (curves[i] == *curve_id)
623 /* For clients can only check sent curve list */
630 static void tls1_get_formatlist(SSL *s, const unsigned char **pformats,
633 /* If we have a custom point format list use it otherwise
635 if (s->tlsext_ecpointformatlist)
637 *pformats = s->tlsext_ecpointformatlist;
638 *pformatslen = s->tlsext_ecpointformatlist_length;
642 *pformats = ecformats_default;
643 *pformatslen = sizeof(ecformats_default);
647 /* Check cert parameters compatible with extensions: currently just checks
648 * EC certificates have compatible curves and compression.
650 static int tls1_check_cert_param(SSL *s, X509 *x, int set_ee_md)
656 pkey = X509_get_pubkey(x);
659 /* If not EC nothing to do */
660 if (pkey->type != EVP_PKEY_EC)
665 rv = tls1_curve_params_from_ec_key(&curve_id, &comp_id, pkey->pkey.ec);
669 /* Can't check curve_id for client certs as we don't have a
670 * supported curves extension.
672 return tls1_check_ec_key(s, s->server ? &curve_id : NULL, &comp_id);
674 /* Check EC temporary key is compatible with client extensions */
675 int tls1_check_ec_tmp_key(SSL *s, unsigned long cid)
678 EC_KEY *ec = s->cert->ecdh_tmp;
679 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
680 /* Allow any curve: not just those peer supports */
681 if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
684 if (s->cert->ecdh_tmp_auto)
686 /* Need a shared curve */
687 return tls1_get_shared_curve(s) != NID_undef;
691 if (s->cert->ecdh_tmp_cb)
696 if (!tls1_curve_params_from_ec_key(&curve_id, NULL, ec))
698 /* Set this to allow use of invalid curves for testing */
702 return tls1_check_ec_key(s, &curve_id, NULL);
708 /* List of supported signature algorithms and hashes. Should make this
709 * customisable at some point, for now include everything we support.
712 #define tlsext_sigalg_rsa(md) md, TLSEXT_signature_rsa,
714 #define tlsext_sigalg_ecdsa(md) md, TLSEXT_signature_ecdsa,
716 #define tlsext_sigalg(md) \
717 tlsext_sigalg_rsa(md) \
718 tlsext_sigalg_ecdsa(md)
720 static const uint8_t tls12_sigalgs[] = {
721 tlsext_sigalg(TLSEXT_hash_sha512)
722 tlsext_sigalg(TLSEXT_hash_sha384)
723 tlsext_sigalg(TLSEXT_hash_sha256)
724 tlsext_sigalg(TLSEXT_hash_sha224)
725 tlsext_sigalg(TLSEXT_hash_sha1)
727 size_t tls12_get_psigalgs(SSL *s, const unsigned char **psigs)
729 /* If server use client authentication sigalgs if not NULL */
730 if (s->server && s->cert->client_sigalgs)
732 *psigs = s->cert->client_sigalgs;
733 return s->cert->client_sigalgslen;
735 else if (s->cert->conf_sigalgs)
737 *psigs = s->cert->conf_sigalgs;
738 return s->cert->conf_sigalgslen;
742 *psigs = tls12_sigalgs;
743 return sizeof(tls12_sigalgs);
747 /* tls12_check_peer_sigalg parses a SignatureAndHashAlgorithm out of
748 * |cbs|. It checks it is consistent with |s|'s sent supported
749 * signature algorithms and, if so, writes the relevant digest into
750 * |*out_md| and returns 1. Otherwise it returns 0 and writes an alert
753 int tls12_check_peer_sigalg(const EVP_MD **out_md, int *out_alert,
754 SSL *s, CBS *cbs, EVP_PKEY *pkey)
756 const unsigned char *sent_sigs;
757 size_t sent_sigslen, i;
758 int sigalg = tls12_get_sigid(pkey);
759 uint8_t hash, signature;
760 /* Should never happen */
763 OPENSSL_PUT_ERROR(SSL, tls12_check_peer_sigalg, ERR_R_INTERNAL_ERROR);
764 *out_alert = SSL_AD_INTERNAL_ERROR;
767 if (!CBS_get_u8(cbs, &hash) ||
768 !CBS_get_u8(cbs, &signature))
770 OPENSSL_PUT_ERROR(SSL, tls12_check_peer_sigalg, SSL_R_DECODE_ERROR);
771 *out_alert = SSL_AD_DECODE_ERROR;
774 /* Check key type is consistent with signature */
775 if (sigalg != signature)
777 OPENSSL_PUT_ERROR(SSL, tls12_check_peer_sigalg, SSL_R_WRONG_SIGNATURE_TYPE);
778 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
781 if (pkey->type == EVP_PKEY_EC)
785 /* Check compression and curve matches extensions */
786 if (!tls1_curve_params_from_ec_key(&curve_id, &comp_id, pkey->pkey.ec))
788 *out_alert = SSL_AD_INTERNAL_ERROR;
791 if (!s->server && !tls1_check_ec_key(s, &curve_id, &comp_id))
793 OPENSSL_PUT_ERROR(SSL, tls12_check_peer_sigalg, SSL_R_WRONG_CURVE);
794 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
799 /* Check signature matches a type we sent */
800 sent_sigslen = tls12_get_psigalgs(s, &sent_sigs);
801 for (i = 0; i < sent_sigslen; i+=2, sent_sigs+=2)
803 if (hash == sent_sigs[0] && signature == sent_sigs[1])
806 /* Allow fallback to SHA1 if not strict mode */
807 if (i == sent_sigslen && (hash != TLSEXT_hash_sha1 || s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT))
809 OPENSSL_PUT_ERROR(SSL, tls12_check_peer_sigalg, SSL_R_WRONG_SIGNATURE_TYPE);
810 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
813 *out_md = tls12_get_hash(hash);
816 OPENSSL_PUT_ERROR(SSL, tls12_check_peer_sigalg, SSL_R_UNKNOWN_DIGEST);
817 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
820 /* Store the digest used so applications can retrieve it if they
823 if (s->session && s->session->sess_cert)
824 s->session->sess_cert->peer_key->digest = *out_md;
827 /* Get a mask of disabled algorithms: an algorithm is disabled
828 * if it isn't supported or doesn't appear in supported signature
829 * algorithms. Unlike ssl_cipher_get_disabled this applies to a specific
830 * session and not global settings.
833 void ssl_set_client_disabled(SSL *s)
836 const unsigned char *sigalgs;
837 size_t i, sigalgslen;
838 int have_rsa = 0, have_ecdsa = 0;
841 /* Don't allow TLS 1.2 only ciphers if we don't suppport them */
842 if (!SSL_CLIENT_USE_TLS1_2_CIPHERS(s))
843 c->mask_ssl = SSL_TLSV1_2;
846 /* Now go through all signature algorithms seeing if we support
847 * any for RSA, DSA, ECDSA. Do this for all versions not just
850 sigalgslen = tls12_get_psigalgs(s, &sigalgs);
851 for (i = 0; i < sigalgslen; i += 2, sigalgs += 2)
855 case TLSEXT_signature_rsa:
858 case TLSEXT_signature_ecdsa:
863 /* Disable auth if we don't include any appropriate signature
868 c->mask_a |= SSL_aRSA;
872 c->mask_a |= SSL_aECDSA;
874 /* with PSK there must be client callback set */
875 if (!s->psk_client_callback)
877 c->mask_a |= SSL_aPSK;
878 c->mask_k |= SSL_kPSK;
883 /* header_len is the length of the ClientHello header written so far, used to
884 * compute padding. It does not include the record header. Pass 0 if no padding
886 unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *buf, unsigned char *limit, size_t header_len)
889 unsigned char *ret = buf;
890 unsigned char *orig = buf;
891 /* See if we support any ECC ciphersuites */
893 if (s->version >= TLS1_VERSION || SSL_IS_DTLS(s))
896 unsigned long alg_k, alg_a;
897 STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(s);
899 for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++)
901 const SSL_CIPHER *c = sk_SSL_CIPHER_value(cipher_stack, i);
903 alg_k = c->algorithm_mkey;
904 alg_a = c->algorithm_auth;
905 if ((alg_k & SSL_kEECDH) || (alg_a & SSL_aECDSA))
913 /* don't add extensions for SSLv3 unless doing secure renegotiation */
914 if (s->client_version == SSL3_VERSION
915 && !s->s3->send_connection_binding)
920 if (ret>=limit) return NULL; /* this really never occurs, but ... */
922 if (s->tlsext_hostname != NULL)
924 /* Add TLS extension servername to the Client Hello message */
925 unsigned long size_str;
928 /* check for enough space.
929 4 for the servername type and entension length
930 2 for servernamelist length
931 1 for the hostname type
932 2 for hostname length
936 if ((lenmax = limit - ret - 9) < 0
937 || (size_str = strlen(s->tlsext_hostname)) > (unsigned long)lenmax)
940 /* extension type and length */
941 s2n(TLSEXT_TYPE_server_name,ret);
944 /* length of servername list */
947 /* hostname type, length and hostname */
948 *(ret++) = (unsigned char) TLSEXT_NAMETYPE_host_name;
950 memcpy(ret, s->tlsext_hostname, size_str);
954 /* Add RI if renegotiating */
959 if(!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0))
961 OPENSSL_PUT_ERROR(SSL, ssl_add_clienthello_tlsext, ERR_R_INTERNAL_ERROR);
965 if((limit - ret - 4 - el) < 0) return NULL;
967 s2n(TLSEXT_TYPE_renegotiate,ret);
970 if(!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el))
972 OPENSSL_PUT_ERROR(SSL, ssl_add_clienthello_tlsext, ERR_R_INTERNAL_ERROR);
979 if (!(SSL_get_options(s) & SSL_OP_NO_TICKET))
982 if (!s->new_session && s->session && s->session->tlsext_tick)
983 ticklen = s->session->tlsext_ticklen;
984 else if (s->session && s->tlsext_session_ticket &&
985 s->tlsext_session_ticket->data)
987 s->session->tlsext_tick = BUF_memdup(
988 s->tlsext_session_ticket->data,
989 s->tlsext_session_ticket->length);
990 if (!s->session->tlsext_tick)
992 ticklen = s->tlsext_session_ticket->length;
993 s->session->tlsext_ticklen = ticklen;
997 if (ticklen == 0 && s->tlsext_session_ticket &&
998 s->tlsext_session_ticket->data == NULL)
1000 /* Check for enough room 2 for extension type, 2 for len
1003 if ((long)(limit - ret - 4 - ticklen) < 0) return NULL;
1004 s2n(TLSEXT_TYPE_session_ticket,ret);
1008 memcpy(ret, s->session->tlsext_tick, ticklen);
1014 if (SSL_USE_SIGALGS(s))
1017 const unsigned char *salg;
1018 salglen = tls12_get_psigalgs(s, &salg);
1019 if ((size_t)(limit - ret) < salglen + 6)
1021 s2n(TLSEXT_TYPE_signature_algorithms,ret);
1022 s2n(salglen + 2, ret);
1024 memcpy(ret, salg, salglen);
1028 if (s->ocsp_stapling_enabled)
1030 /* The status_request extension is excessively extensible at
1031 * every layer. On the client, only support requesting OCSP
1032 * responses with an empty responder_id_list and no
1034 if (limit - ret - 4 - 1 - 2 - 2 < 0) return NULL;
1036 s2n(TLSEXT_TYPE_status_request, ret);
1037 s2n(1 + 2 + 2, ret);
1039 *(ret++) = TLSEXT_STATUSTYPE_ocsp;
1040 /* responder_id_list - empty */
1042 /* request_extensions - empty */
1046 if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len)
1048 /* The client advertises an emtpy extension to indicate its
1049 * support for Next Protocol Negotiation */
1050 if (limit - ret - 4 < 0)
1052 s2n(TLSEXT_TYPE_next_proto_neg,ret);
1056 if (s->signed_cert_timestamps_enabled && !s->s3->tmp.finish_md_len)
1058 /* The client advertises an empty extension to indicate its support for
1059 * certificate timestamps. */
1060 if (limit - ret - 4 < 0)
1062 s2n(TLSEXT_TYPE_certificate_timestamp,ret);
1066 if (s->alpn_client_proto_list && !s->s3->tmp.finish_md_len)
1068 if ((size_t)(limit - ret) < 6 + s->alpn_client_proto_list_len)
1070 s2n(TLSEXT_TYPE_application_layer_protocol_negotiation,ret);
1071 s2n(2 + s->alpn_client_proto_list_len,ret);
1072 s2n(s->alpn_client_proto_list_len,ret);
1073 memcpy(ret, s->alpn_client_proto_list,
1074 s->alpn_client_proto_list_len);
1075 ret += s->alpn_client_proto_list_len;
1078 if (s->tlsext_channel_id_enabled)
1080 /* The client advertises an emtpy extension to indicate its
1081 * support for Channel ID. */
1082 if (limit - ret - 4 < 0)
1084 if (s->ctx->tlsext_channel_id_enabled_new)
1085 s2n(TLSEXT_TYPE_channel_id_new,ret);
1087 s2n(TLSEXT_TYPE_channel_id,ret);
1091 if(SSL_get_srtp_profiles(s))
1095 ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0);
1097 if((limit - ret - 4 - el) < 0) return NULL;
1099 s2n(TLSEXT_TYPE_use_srtp,ret);
1102 if(!ssl_add_clienthello_use_srtp_ext(s, ret, &el, el))
1104 OPENSSL_PUT_ERROR(SSL, ssl_add_clienthello_tlsext, ERR_R_INTERNAL_ERROR);
1112 /* Add TLS extension ECPointFormats to the ClientHello message */
1114 const uint8_t *formats;
1115 const uint16_t *curves;
1116 size_t formats_len, curves_len, i;
1118 tls1_get_formatlist(s, &formats, &formats_len);
1120 if ((lenmax = limit - ret - 5) < 0) return NULL;
1121 if (formats_len > (size_t)lenmax) return NULL;
1122 if (formats_len > 255)
1124 OPENSSL_PUT_ERROR(SSL, ssl_add_clienthello_tlsext, ERR_R_INTERNAL_ERROR);
1128 s2n(TLSEXT_TYPE_ec_point_formats,ret);
1129 s2n(formats_len + 1,ret);
1130 *(ret++) = (unsigned char)formats_len;
1131 memcpy(ret, formats, formats_len);
1134 /* Add TLS extension EllipticCurves to the ClientHello message */
1135 tls1_get_curvelist(s, 0, &curves, &curves_len);
1137 if ((lenmax = limit - ret - 6) < 0) return NULL;
1138 if ((curves_len * 2) > (size_t)lenmax) return NULL;
1139 if ((curves_len * 2) > 65532)
1141 OPENSSL_PUT_ERROR(SSL, ssl_add_clienthello_tlsext, ERR_R_INTERNAL_ERROR);
1145 s2n(TLSEXT_TYPE_elliptic_curves,ret);
1146 s2n((curves_len * 2) + 2, ret);
1148 /* NB: draft-ietf-tls-ecc-12.txt uses a one-byte prefix for
1149 * elliptic_curve_list, but the examples use two bytes.
1150 * http://www1.ietf.org/mail-archive/web/tls/current/msg00538.html
1151 * resolves this to two bytes.
1153 s2n(curves_len * 2, ret);
1154 for (i = 0; i < curves_len; i++)
1156 s2n(curves[i], ret);
1160 #ifdef TLSEXT_TYPE_padding
1161 /* Add padding to workaround bugs in F5 terminators.
1162 * See https://tools.ietf.org/html/draft-agl-tls-padding-03
1164 * NB: because this code works out the length of all existing
1165 * extensions it MUST always appear last. */
1168 header_len += ret - orig;
1169 if (header_len > 0xff && header_len < 0x200)
1171 size_t padding_len = 0x200 - header_len;
1172 /* Extensions take at least four bytes to encode. Always
1173 * include least one byte of data if including the
1174 * extension. WebSphere Application Server 7.0 is
1175 * intolerant to the last extension being zero-length. */
1176 if (padding_len >= 4 + 1)
1180 if (limit - ret - 4 - (long)padding_len < 0)
1183 s2n(TLSEXT_TYPE_padding, ret);
1184 s2n(padding_len, ret);
1185 memset(ret, 0, padding_len);
1191 if ((extdatalen = ret-orig-2)== 0)
1194 s2n(extdatalen, orig);
1198 unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *buf, unsigned char *limit)
1201 unsigned char *orig = buf;
1202 unsigned char *ret = buf;
1203 int next_proto_neg_seen;
1204 unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1205 unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1206 int using_ecc = (alg_k & SSL_kEECDH) || (alg_a & SSL_aECDSA);
1207 using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL);
1208 /* don't add extensions for SSLv3, unless doing secure renegotiation */
1209 if (s->version == SSL3_VERSION && !s->s3->send_connection_binding)
1213 if (ret>=limit) return NULL; /* this really never occurs, but ... */
1215 if (!s->hit && s->should_ack_sni && s->session->tlsext_hostname != NULL)
1217 if ((long)(limit - ret - 4) < 0) return NULL;
1219 s2n(TLSEXT_TYPE_server_name,ret);
1223 if(s->s3->send_connection_binding)
1227 if(!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0))
1229 OPENSSL_PUT_ERROR(SSL, ssl_add_serverhello_tlsext, ERR_R_INTERNAL_ERROR);
1233 if((limit - ret - 4 - el) < 0) return NULL;
1235 s2n(TLSEXT_TYPE_renegotiate,ret);
1238 if(!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el))
1240 OPENSSL_PUT_ERROR(SSL, ssl_add_serverhello_tlsext, ERR_R_INTERNAL_ERROR);
1249 const unsigned char *plist;
1251 /* Add TLS extension ECPointFormats to the ServerHello message */
1254 tls1_get_formatlist(s, &plist, &plistlen);
1256 if ((lenmax = limit - ret - 5) < 0) return NULL;
1257 if (plistlen > (size_t)lenmax) return NULL;
1260 OPENSSL_PUT_ERROR(SSL, ssl_add_serverhello_tlsext, ERR_R_INTERNAL_ERROR);
1264 s2n(TLSEXT_TYPE_ec_point_formats,ret);
1265 s2n(plistlen + 1,ret);
1266 *(ret++) = (unsigned char) plistlen;
1267 memcpy(ret, plist, plistlen);
1271 /* Currently the server should not respond with a SupportedCurves extension */
1273 if (s->tlsext_ticket_expected
1274 && !(SSL_get_options(s) & SSL_OP_NO_TICKET))
1276 if ((long)(limit - ret - 4) < 0) return NULL;
1277 s2n(TLSEXT_TYPE_session_ticket,ret);
1281 if (s->s3->tmp.certificate_status_expected)
1283 if ((long)(limit - ret - 4) < 0) return NULL;
1284 s2n(TLSEXT_TYPE_status_request,ret);
1292 ssl_add_serverhello_use_srtp_ext(s, 0, &el, 0);
1294 if((limit - ret - 4 - el) < 0) return NULL;
1296 s2n(TLSEXT_TYPE_use_srtp,ret);
1299 if(!ssl_add_serverhello_use_srtp_ext(s, ret, &el, el))
1301 OPENSSL_PUT_ERROR(SSL, ssl_add_serverhello_tlsext, ERR_R_INTERNAL_ERROR);
1307 next_proto_neg_seen = s->s3->next_proto_neg_seen;
1308 s->s3->next_proto_neg_seen = 0;
1309 if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb)
1311 const unsigned char *npa;
1312 unsigned int npalen;
1315 r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen, s->ctx->next_protos_advertised_cb_arg);
1316 if (r == SSL_TLSEXT_ERR_OK)
1318 if ((long)(limit - ret - 4 - npalen) < 0) return NULL;
1319 s2n(TLSEXT_TYPE_next_proto_neg,ret);
1321 memcpy(ret, npa, npalen);
1323 s->s3->next_proto_neg_seen = 1;
1327 if (s->s3->alpn_selected)
1329 const uint8_t *selected = s->s3->alpn_selected;
1330 size_t len = s->s3->alpn_selected_len;
1332 if ((long)(limit - ret - 4 - 2 - 1 - len) < 0)
1334 s2n(TLSEXT_TYPE_application_layer_protocol_negotiation,ret);
1338 memcpy(ret, selected, len);
1342 /* If the client advertised support for Channel ID, and we have it
1343 * enabled, then we want to echo it back. */
1344 if (s->s3->tlsext_channel_id_valid)
1346 if (limit - ret - 4 < 0)
1348 if (s->s3->tlsext_channel_id_new)
1349 s2n(TLSEXT_TYPE_channel_id_new,ret);
1351 s2n(TLSEXT_TYPE_channel_id,ret);
1355 if ((extdatalen = ret-orig-2) == 0)
1358 s2n(extdatalen, orig);
1362 /* tls1_alpn_handle_client_hello is called to process the ALPN extension in a
1364 * cbs: the contents of the extension, not including the type and length.
1365 * out_alert: a pointer to the alert value to send in the event of a zero
1368 * returns: 1 on success. */
1369 static int tls1_alpn_handle_client_hello(SSL *s, CBS *cbs, int *out_alert)
1371 CBS protocol_name_list, protocol_name_list_copy;
1372 const unsigned char *selected;
1373 unsigned char selected_len;
1376 if (s->ctx->alpn_select_cb == NULL)
1379 if (!CBS_get_u16_length_prefixed(cbs, &protocol_name_list) ||
1380 CBS_len(cbs) != 0 ||
1381 CBS_len(&protocol_name_list) < 2)
1384 /* Validate the protocol list. */
1385 protocol_name_list_copy = protocol_name_list;
1386 while (CBS_len(&protocol_name_list_copy) > 0)
1390 if (!CBS_get_u8_length_prefixed(&protocol_name_list_copy, &protocol_name))
1394 r = s->ctx->alpn_select_cb(s, &selected, &selected_len,
1395 CBS_data(&protocol_name_list), CBS_len(&protocol_name_list),
1396 s->ctx->alpn_select_cb_arg);
1397 if (r == SSL_TLSEXT_ERR_OK) {
1398 if (s->s3->alpn_selected)
1399 OPENSSL_free(s->s3->alpn_selected);
1400 s->s3->alpn_selected = BUF_memdup(selected, selected_len);
1401 if (!s->s3->alpn_selected)
1403 *out_alert = SSL_AD_INTERNAL_ERROR;
1406 s->s3->alpn_selected_len = selected_len;
1411 *out_alert = SSL_AD_DECODE_ERROR;
1415 static int ssl_scan_clienthello_tlsext(SSL *s, CBS *cbs, int *out_alert)
1417 int renegotiate_seen = 0;
1421 s->should_ack_sni = 0;
1422 s->s3->next_proto_neg_seen = 0;
1423 s->s3->tmp.certificate_status_expected = 0;
1425 if (s->s3->alpn_selected)
1427 OPENSSL_free(s->s3->alpn_selected);
1428 s->s3->alpn_selected = NULL;
1431 /* Clear any signature algorithms extension received */
1432 if (s->cert->peer_sigalgs)
1434 OPENSSL_free(s->cert->peer_sigalgs);
1435 s->cert->peer_sigalgs = NULL;
1437 /* Clear any shared sigtnature algorithms */
1438 if (s->cert->shared_sigalgs)
1440 OPENSSL_free(s->cert->shared_sigalgs);
1441 s->cert->shared_sigalgs = NULL;
1443 /* Clear certificate digests and validity flags */
1444 for (i = 0; i < SSL_PKEY_NUM; i++)
1446 s->cert->pkeys[i].digest = NULL;
1447 s->cert->pkeys[i].valid_flags = 0;
1450 /* There may be no extensions. */
1451 if (CBS_len(cbs) == 0)
1456 /* Decode the extensions block and check it is valid. */
1457 if (!CBS_get_u16_length_prefixed(cbs, &extensions) ||
1458 !tls1_check_duplicate_extensions(&extensions))
1460 *out_alert = SSL_AD_DECODE_ERROR;
1464 while (CBS_len(&extensions) != 0)
1469 /* Decode the next extension. */
1470 if (!CBS_get_u16(&extensions, &type) ||
1471 !CBS_get_u16_length_prefixed(&extensions, &extension))
1473 *out_alert = SSL_AD_DECODE_ERROR;
1477 if (s->tlsext_debug_cb)
1479 s->tlsext_debug_cb(s, 0, type, (unsigned char*)CBS_data(&extension),
1480 CBS_len(&extension), s->tlsext_debug_arg);
1483 /* The servername extension is treated as follows:
1485 - Only the hostname type is supported with a maximum length of 255.
1486 - The servername is rejected if too long or if it contains zeros,
1487 in which case an fatal alert is generated.
1488 - The servername field is maintained together with the session cache.
1489 - When a session is resumed, the servername call back invoked in order
1490 to allow the application to position itself to the right context.
1491 - The servername is acknowledged if it is new for a session or when
1492 it is identical to a previously used for the same session.
1493 Applications can control the behaviour. They can at any time
1494 set a 'desirable' servername for a new SSL object. This can be the
1495 case for example with HTTPS when a Host: header field is received and
1496 a renegotiation is requested. In this case, a possible servername
1497 presented in the new client hello is only acknowledged if it matches
1498 the value of the Host: field.
1499 - Applications must use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
1500 if they provide for changing an explicit servername context for the session,
1501 i.e. when the session has been established with a servername extension.
1502 - On session reconnect, the servername extension may be absent.
1506 if (type == TLSEXT_TYPE_server_name)
1508 CBS server_name_list;
1509 char have_seen_host_name = 0;
1511 if (!CBS_get_u16_length_prefixed(&extension, &server_name_list) ||
1512 CBS_len(&server_name_list) < 1 ||
1513 CBS_len(&extension) != 0)
1515 *out_alert = SSL_AD_DECODE_ERROR;
1519 /* Decode each ServerName in the extension. */
1520 while (CBS_len(&server_name_list) > 0)
1525 /* Decode the NameType. */
1526 if (!CBS_get_u8(&server_name_list, &name_type))
1528 *out_alert = SSL_AD_DECODE_ERROR;
1532 /* Only host_name is supported. */
1533 if (name_type != TLSEXT_NAMETYPE_host_name)
1536 if (have_seen_host_name)
1538 /* The ServerNameList MUST NOT contain
1539 * more than one name of the same
1541 *out_alert = SSL_AD_DECODE_ERROR;
1545 have_seen_host_name = 1;
1547 if (!CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||
1548 CBS_len(&host_name) < 1)
1550 *out_alert = SSL_AD_DECODE_ERROR;
1554 if (CBS_len(&host_name) > TLSEXT_MAXLEN_host_name ||
1555 CBS_contains_zero_byte(&host_name))
1557 *out_alert = SSL_AD_UNRECOGNIZED_NAME;
1563 assert(s->session->tlsext_hostname == NULL);
1564 if (s->session->tlsext_hostname)
1566 /* This should be impossible. */
1567 *out_alert = SSL_AD_DECODE_ERROR;
1571 /* Copy the hostname as a string. */
1572 if (!CBS_strdup(&host_name, &s->session->tlsext_hostname))
1574 *out_alert = SSL_AD_INTERNAL_ERROR;
1578 s->should_ack_sni = 1;
1583 else if (type == TLSEXT_TYPE_ec_point_formats)
1585 CBS ec_point_format_list;
1587 if (!CBS_get_u8_length_prefixed(&extension, &ec_point_format_list) ||
1588 CBS_len(&extension) != 0)
1590 *out_alert = SSL_AD_DECODE_ERROR;
1596 if (!CBS_stow(&ec_point_format_list,
1597 &s->session->tlsext_ecpointformatlist,
1598 &s->session->tlsext_ecpointformatlist_length))
1600 *out_alert = SSL_AD_INTERNAL_ERROR;
1605 else if (type == TLSEXT_TYPE_elliptic_curves)
1607 CBS elliptic_curve_list;
1608 size_t i, num_curves;
1610 if (!CBS_get_u16_length_prefixed(&extension, &elliptic_curve_list) ||
1611 CBS_len(&elliptic_curve_list) == 0 ||
1612 (CBS_len(&elliptic_curve_list) & 1) != 0 ||
1613 CBS_len(&extension) != 0)
1615 *out_alert = SSL_AD_DECODE_ERROR;
1621 if (s->session->tlsext_ellipticcurvelist)
1623 OPENSSL_free(s->session->tlsext_ellipticcurvelist);
1624 s->session->tlsext_ellipticcurvelist_length = 0;
1626 s->session->tlsext_ellipticcurvelist =
1627 (uint16_t*)OPENSSL_malloc(CBS_len(&elliptic_curve_list));
1628 if (s->session->tlsext_ellipticcurvelist == NULL)
1630 *out_alert = SSL_AD_INTERNAL_ERROR;
1633 num_curves = CBS_len(&elliptic_curve_list) / 2;
1634 for (i = 0; i < num_curves; i++)
1636 if (!CBS_get_u16(&elliptic_curve_list,
1637 &s->session->tlsext_ellipticcurvelist[i]))
1639 *out_alert = SSL_AD_INTERNAL_ERROR;
1643 if (CBS_len(&elliptic_curve_list) != 0)
1645 *out_alert = SSL_AD_INTERNAL_ERROR;
1648 s->session->tlsext_ellipticcurvelist_length = num_curves;
1651 else if (type == TLSEXT_TYPE_session_ticket)
1653 if (s->tls_session_ticket_ext_cb &&
1654 !s->tls_session_ticket_ext_cb(s, CBS_data(&extension), CBS_len(&extension), s->tls_session_ticket_ext_cb_arg))
1656 *out_alert = SSL_AD_INTERNAL_ERROR;
1660 else if (type == TLSEXT_TYPE_renegotiate)
1662 if (!ssl_parse_clienthello_renegotiate_ext(s, &extension, out_alert))
1664 renegotiate_seen = 1;
1666 else if (type == TLSEXT_TYPE_signature_algorithms)
1668 CBS supported_signature_algorithms;
1670 if (!CBS_get_u16_length_prefixed(&extension, &supported_signature_algorithms) ||
1671 CBS_len(&extension) != 0)
1673 *out_alert = SSL_AD_DECODE_ERROR;
1677 /* Ensure the signature algorithms are non-empty. It
1678 * contains a list of SignatureAndHashAlgorithms
1679 * which are two bytes each. */
1680 if (CBS_len(&supported_signature_algorithms) == 0 ||
1681 (CBS_len(&supported_signature_algorithms) % 2) != 0)
1683 *out_alert = SSL_AD_DECODE_ERROR;
1687 if (!tls1_process_sigalgs(s, &supported_signature_algorithms))
1689 *out_alert = SSL_AD_DECODE_ERROR;
1692 /* If sigalgs received and no shared algorithms fatal
1695 if (s->cert->peer_sigalgs && !s->cert->shared_sigalgs)
1697 OPENSSL_PUT_ERROR(SSL, ssl_add_serverhello_tlsext, SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
1698 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
1703 else if (type == TLSEXT_TYPE_next_proto_neg &&
1704 s->s3->tmp.finish_md_len == 0 &&
1705 s->s3->alpn_selected == NULL)
1707 /* The extension must be empty. */
1708 if (CBS_len(&extension) != 0)
1710 *out_alert = SSL_AD_DECODE_ERROR;
1714 /* We shouldn't accept this extension on a
1717 * s->new_session will be set on renegotiation, but we
1718 * probably shouldn't rely that it couldn't be set on
1719 * the initial renegotation too in certain cases (when
1720 * there's some other reason to disallow resuming an
1721 * earlier session -- the current code won't be doing
1722 * anything like that, but this might change).
1724 * A valid sign that there's been a previous handshake
1725 * in this connection is if s->s3->tmp.finish_md_len >
1726 * 0. (We are talking about a check that will happen
1727 * in the Hello protocol round, well before a new
1728 * Finished message could have been computed.) */
1729 s->s3->next_proto_neg_seen = 1;
1732 else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation &&
1733 s->ctx->alpn_select_cb &&
1734 s->s3->tmp.finish_md_len == 0)
1736 if (!tls1_alpn_handle_client_hello(s, &extension, out_alert))
1738 /* ALPN takes precedence over NPN. */
1739 s->s3->next_proto_neg_seen = 0;
1742 else if (type == TLSEXT_TYPE_channel_id &&
1743 s->tlsext_channel_id_enabled)
1745 /* The extension must be empty. */
1746 if (CBS_len(&extension) != 0)
1748 *out_alert = SSL_AD_DECODE_ERROR;
1752 s->s3->tlsext_channel_id_valid = 1;
1755 else if (type == TLSEXT_TYPE_channel_id_new &&
1756 s->tlsext_channel_id_enabled)
1758 /* The extension must be empty. */
1759 if (CBS_len(&extension) != 0)
1761 *out_alert = SSL_AD_DECODE_ERROR;
1765 s->s3->tlsext_channel_id_valid = 1;
1766 s->s3->tlsext_channel_id_new = 1;
1770 /* session ticket processed earlier */
1771 else if (type == TLSEXT_TYPE_use_srtp)
1773 if (!ssl_parse_clienthello_use_srtp_ext(s, &extension, out_alert))
1780 /* Need RI if renegotiating */
1782 if (!renegotiate_seen && s->renegotiate &&
1783 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
1785 *out_alert = SSL_AD_HANDSHAKE_FAILURE;
1786 OPENSSL_PUT_ERROR(SSL, ssl_scan_clienthello_tlsext, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
1789 /* If no signature algorithms extension set default values */
1790 if (!s->cert->peer_sigalgs)
1791 ssl_cert_set_default_md(s->cert);
1796 int ssl_parse_clienthello_tlsext(SSL *s, CBS *cbs)
1799 if (ssl_scan_clienthello_tlsext(s, cbs, &alert) <= 0)
1801 ssl3_send_alert(s, SSL3_AL_FATAL, alert);
1805 if (ssl_check_clienthello_tlsext(s) <= 0)
1807 OPENSSL_PUT_ERROR(SSL, ssl_parse_clienthello_tlsext, SSL_R_CLIENTHELLO_TLSEXT);
1813 /* ssl_next_proto_validate validates a Next Protocol Negotiation block. No
1814 * elements of zero length are allowed and the set of elements must exactly fill
1815 * the length of the block. */
1816 static char ssl_next_proto_validate(const CBS *cbs)
1820 while (CBS_len(©) != 0)
1823 if (!CBS_get_u8_length_prefixed(©, &proto) ||
1824 CBS_len(&proto) == 0)
1832 static int ssl_scan_serverhello_tlsext(SSL *s, CBS *cbs, int *out_alert)
1834 int tlsext_servername = 0;
1835 int renegotiate_seen = 0;
1838 /* TODO(davidben): Move all of these to some per-handshake state that
1839 * gets systematically reset on a new handshake; perhaps allocate it
1840 * fresh each time so it's not even kept around post-handshake. */
1841 s->s3->next_proto_neg_seen = 0;
1843 s->tlsext_ticket_expected = 0;
1844 s->s3->tmp.certificate_status_expected = 0;
1846 if (s->s3->alpn_selected)
1848 OPENSSL_free(s->s3->alpn_selected);
1849 s->s3->alpn_selected = NULL;
1852 /* There may be no extensions. */
1853 if (CBS_len(cbs) == 0)
1858 /* Decode the extensions block and check it is valid. */
1859 if (!CBS_get_u16_length_prefixed(cbs, &extensions) ||
1860 !tls1_check_duplicate_extensions(&extensions))
1862 *out_alert = SSL_AD_DECODE_ERROR;
1866 while (CBS_len(&extensions) != 0)
1871 /* Decode the next extension. */
1872 if (!CBS_get_u16(&extensions, &type) ||
1873 !CBS_get_u16_length_prefixed(&extensions, &extension))
1875 *out_alert = SSL_AD_DECODE_ERROR;
1879 if (s->tlsext_debug_cb)
1881 s->tlsext_debug_cb(s, 1, type, (unsigned char*)CBS_data(&extension),
1882 CBS_len(&extension), s->tlsext_debug_arg);
1885 if (type == TLSEXT_TYPE_server_name)
1887 /* The extension must be empty. */
1888 if (CBS_len(&extension) != 0)
1890 *out_alert = SSL_AD_DECODE_ERROR;
1893 /* We must have sent it in ClientHello. */
1894 if (s->tlsext_hostname == NULL)
1896 *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
1899 tlsext_servername = 1;
1901 else if (type == TLSEXT_TYPE_ec_point_formats)
1903 CBS ec_point_format_list;
1905 if (!CBS_get_u8_length_prefixed(&extension, &ec_point_format_list) ||
1906 CBS_len(&extension) != 0)
1908 *out_alert = SSL_AD_DECODE_ERROR;
1914 if (!CBS_stow(&ec_point_format_list,
1915 &s->session->tlsext_ecpointformatlist,
1916 &s->session->tlsext_ecpointformatlist_length))
1918 *out_alert = SSL_AD_INTERNAL_ERROR;
1923 else if (type == TLSEXT_TYPE_session_ticket)
1925 if (s->tls_session_ticket_ext_cb &&
1926 !s->tls_session_ticket_ext_cb(s, CBS_data(&extension), CBS_len(&extension),
1927 s->tls_session_ticket_ext_cb_arg))
1929 *out_alert = SSL_AD_INTERNAL_ERROR;
1933 if ((SSL_get_options(s) & SSL_OP_NO_TICKET) || CBS_len(&extension) > 0)
1935 *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
1939 s->tlsext_ticket_expected = 1;
1941 else if (type == TLSEXT_TYPE_status_request)
1943 /* The extension MUST be empty and may only sent if
1944 * we've requested a status request message. */
1945 if (CBS_len(&extension) != 0)
1947 *out_alert = SSL_AD_DECODE_ERROR;
1950 if (!s->ocsp_stapling_enabled)
1952 *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
1955 /* Set a flag to expect a CertificateStatus message */
1956 s->s3->tmp.certificate_status_expected = 1;
1958 else if (type == TLSEXT_TYPE_next_proto_neg && s->s3->tmp.finish_md_len == 0) {
1959 unsigned char *selected;
1960 unsigned char selected_len;
1962 /* We must have requested it. */
1963 if (s->ctx->next_proto_select_cb == NULL)
1965 *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
1969 /* The data must be valid. */
1970 if (!ssl_next_proto_validate(&extension))
1972 *out_alert = SSL_AD_DECODE_ERROR;
1976 if (s->ctx->next_proto_select_cb(s, &selected, &selected_len,
1977 CBS_data(&extension), CBS_len(&extension),
1978 s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK)
1980 *out_alert = SSL_AD_INTERNAL_ERROR;
1984 s->next_proto_negotiated = BUF_memdup(selected, selected_len);
1985 if (s->next_proto_negotiated == NULL)
1987 *out_alert = SSL_AD_INTERNAL_ERROR;
1990 s->next_proto_negotiated_len = selected_len;
1991 s->s3->next_proto_neg_seen = 1;
1993 else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation)
1995 CBS protocol_name_list, protocol_name;
1997 /* We must have requested it. */
1998 if (s->alpn_client_proto_list == NULL)
2000 *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
2004 /* The extension data consists of a ProtocolNameList
2005 * which must have exactly one ProtocolName. Each of
2006 * these is length-prefixed. */
2007 if (!CBS_get_u16_length_prefixed(&extension, &protocol_name_list) ||
2008 CBS_len(&extension) != 0 ||
2009 !CBS_get_u8_length_prefixed(&protocol_name_list, &protocol_name) ||
2010 CBS_len(&protocol_name_list) != 0)
2012 *out_alert = SSL_AD_DECODE_ERROR;
2016 if (!CBS_stow(&protocol_name,
2017 &s->s3->alpn_selected,
2018 &s->s3->alpn_selected_len))
2020 *out_alert = SSL_AD_INTERNAL_ERROR;
2025 else if (type == TLSEXT_TYPE_channel_id)
2027 if (CBS_len(&extension) != 0)
2029 *out_alert = SSL_AD_DECODE_ERROR;
2032 s->s3->tlsext_channel_id_valid = 1;
2034 else if (type == TLSEXT_TYPE_channel_id_new)
2036 if (CBS_len(&extension) != 0)
2038 *out_alert = SSL_AD_DECODE_ERROR;
2041 s->s3->tlsext_channel_id_valid = 1;
2042 s->s3->tlsext_channel_id_new = 1;
2044 else if (type == TLSEXT_TYPE_certificate_timestamp)
2046 if (CBS_len(&extension) == 0)
2048 *out_alert = SSL_AD_DECODE_ERROR;
2052 /* Session resumption uses the original session information. */
2055 if (!CBS_stow(&extension,
2056 &s->session->tlsext_signed_cert_timestamp_list,
2057 &s->session->tlsext_signed_cert_timestamp_list_length))
2059 *out_alert = SSL_AD_INTERNAL_ERROR;
2064 else if (type == TLSEXT_TYPE_renegotiate)
2066 if (!ssl_parse_serverhello_renegotiate_ext(s, &extension, out_alert))
2068 renegotiate_seen = 1;
2070 else if (type == TLSEXT_TYPE_use_srtp)
2072 if (!ssl_parse_serverhello_use_srtp_ext(s, &extension, out_alert))
2077 if (!s->hit && tlsext_servername == 1)
2079 if (s->tlsext_hostname)
2081 if (s->session->tlsext_hostname == NULL)
2083 s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);
2084 if (!s->session->tlsext_hostname)
2086 *out_alert = SSL_AD_UNRECOGNIZED_NAME;
2092 *out_alert = SSL_AD_DECODE_ERROR;
2100 /* Determine if we need to see RI. Strictly speaking if we want to
2101 * avoid an attack we should *always* see RI even on initial server
2102 * hello because the client doesn't see any renegotiation during an
2103 * attack. However this would mean we could not connect to any server
2104 * which doesn't support RI so for the immediate future tolerate RI
2105 * absence on initial connect only.
2107 if (!renegotiate_seen
2108 && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
2109 && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
2111 *out_alert = SSL_AD_HANDSHAKE_FAILURE;
2112 OPENSSL_PUT_ERROR(SSL, ssl_scan_serverhello_tlsext, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2120 int ssl_prepare_clienthello_tlsext(SSL *s)
2125 int ssl_prepare_serverhello_tlsext(SSL *s)
2130 static int ssl_check_clienthello_tlsext(SSL *s)
2132 int ret=SSL_TLSEXT_ERR_NOACK;
2133 int al = SSL_AD_UNRECOGNIZED_NAME;
2135 /* The handling of the ECPointFormats extension is done elsewhere, namely in
2136 * ssl3_choose_cipher in s3_lib.c.
2138 /* The handling of the EllipticCurves extension is done elsewhere, namely in
2139 * ssl3_choose_cipher in s3_lib.c.
2142 if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0)
2143 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
2144 else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)
2145 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
2149 case SSL_TLSEXT_ERR_ALERT_FATAL:
2150 ssl3_send_alert(s,SSL3_AL_FATAL,al);
2153 case SSL_TLSEXT_ERR_ALERT_WARNING:
2154 ssl3_send_alert(s,SSL3_AL_WARNING,al);
2157 case SSL_TLSEXT_ERR_NOACK:
2158 s->should_ack_sni = 0;
2166 static int ssl_check_serverhello_tlsext(SSL *s)
2168 int ret=SSL_TLSEXT_ERR_NOACK;
2169 int al = SSL_AD_UNRECOGNIZED_NAME;
2171 /* If we are client and using an elliptic curve cryptography cipher
2172 * suite, then if server returns an EC point formats lists extension
2173 * it must contain uncompressed.
2175 unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2176 unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2177 if ((s->tlsext_ecpointformatlist != NULL) && (s->tlsext_ecpointformatlist_length > 0) &&
2178 (s->session->tlsext_ecpointformatlist != NULL) && (s->session->tlsext_ecpointformatlist_length > 0) &&
2179 ((alg_k & SSL_kEECDH) || (alg_a & SSL_aECDSA)))
2181 /* we are using an ECC cipher */
2183 unsigned char *list;
2184 int found_uncompressed = 0;
2185 list = s->session->tlsext_ecpointformatlist;
2186 for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2188 if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed)
2190 found_uncompressed = 1;
2194 if (!found_uncompressed)
2196 OPENSSL_PUT_ERROR(SSL, ssl_check_serverhello_tlsext, SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
2200 ret = SSL_TLSEXT_ERR_OK;
2202 if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0)
2203 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
2204 else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)
2205 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
2209 case SSL_TLSEXT_ERR_ALERT_FATAL:
2210 ssl3_send_alert(s,SSL3_AL_FATAL,al);
2213 case SSL_TLSEXT_ERR_ALERT_WARNING:
2214 ssl3_send_alert(s,SSL3_AL_WARNING,al);
2222 int ssl_parse_serverhello_tlsext(SSL *s, CBS *cbs)
2225 if (s->version < SSL3_VERSION)
2228 if (ssl_scan_serverhello_tlsext(s, cbs, &alert) <= 0)
2230 ssl3_send_alert(s, SSL3_AL_FATAL, alert);
2234 if (ssl_check_serverhello_tlsext(s) <= 0)
2236 OPENSSL_PUT_ERROR(SSL, ssl_parse_serverhello_tlsext, SSL_R_SERVERHELLO_TLSEXT);
2243 /* Since the server cache lookup is done early on in the processing of the
2244 * ClientHello, and other operations depend on the result, we need to handle
2245 * any TLS session ticket extension at the same time.
2247 * ctx: contains the early callback context, which is the result of a
2248 * shallow parse of the ClientHello.
2249 * ret: (output) on return, if a ticket was decrypted, then this is set to
2250 * point to the resulting session.
2252 * If s->tls_session_secret_cb is set then we are expecting a pre-shared key
2253 * ciphersuite, in which case we have no use for session tickets and one will
2254 * never be decrypted, nor will s->tlsext_ticket_expected be set to 1.
2257 * -1: fatal error, either from parsing or decrypting the ticket.
2258 * 0: no ticket was found (or was ignored, based on settings).
2259 * 1: a zero length extension was found, indicating that the client supports
2260 * session tickets but doesn't currently have one to offer.
2261 * 2: either s->tls_session_secret_cb was set, or a ticket was offered but
2262 * couldn't be decrypted because of a non-fatal error.
2263 * 3: a ticket was successfully decrypted and *ret was set.
2266 * Sets s->tlsext_ticket_expected to 1 if the server will have to issue
2267 * a new session ticket to the client because the client indicated support
2268 * (and s->tls_session_secret_cb is NULL) but the client either doesn't have
2269 * a session ticket or we couldn't use the one it gave us, or if
2270 * s->ctx->tlsext_ticket_key_cb asked to renew the client's ticket.
2271 * Otherwise, s->tlsext_ticket_expected is set to 0.
2273 int tls1_process_ticket(SSL *s, const struct ssl_early_callback_ctx *ctx,
2277 s->tlsext_ticket_expected = 0;
2278 const unsigned char *data;
2282 /* If tickets disabled behave as if no ticket present
2283 * to permit stateful resumption.
2285 if (SSL_get_options(s) & SSL_OP_NO_TICKET)
2287 if ((s->version <= SSL3_VERSION) && !ctx->extensions)
2289 if (!SSL_early_callback_ctx_extension_get(
2290 ctx, TLSEXT_TYPE_session_ticket, &data, &len))
2296 /* The client will accept a ticket but doesn't
2297 * currently have one. */
2298 s->tlsext_ticket_expected = 1;
2301 if (s->tls_session_secret_cb)
2303 /* Indicate that the ticket couldn't be
2304 * decrypted rather than generating the session
2305 * from ticket now, trigger abbreviated
2306 * handshake based on external mechanism to
2307 * calculate the master secret later. */
2310 r = tls_decrypt_ticket(s, data, len, ctx->session_id,
2311 ctx->session_id_len, ret);
2314 case 2: /* ticket couldn't be decrypted */
2315 s->tlsext_ticket_expected = 1;
2317 case 3: /* ticket was decrypted */
2319 case 4: /* ticket decrypted but need to renew */
2320 s->tlsext_ticket_expected = 1;
2322 default: /* fatal error */
2327 /* tls_decrypt_ticket attempts to decrypt a session ticket.
2329 * etick: points to the body of the session ticket extension.
2330 * eticklen: the length of the session tickets extenion.
2331 * sess_id: points at the session ID.
2332 * sesslen: the length of the session ID.
2333 * psess: (output) on return, if a ticket was decrypted, then this is set to
2334 * point to the resulting session.
2337 * -1: fatal error, either from parsing or decrypting the ticket.
2338 * 2: the ticket couldn't be decrypted.
2339 * 3: a ticket was successfully decrypted and *psess was set.
2340 * 4: same as 3, but the ticket needs to be renewed.
2342 static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen,
2343 const unsigned char *sess_id, int sesslen,
2344 SSL_SESSION **psess)
2347 unsigned char *sdec;
2348 const unsigned char *p;
2349 int slen, mlen, renew_ticket = 0;
2350 unsigned char tick_hmac[EVP_MAX_MD_SIZE];
2353 SSL_CTX *tctx = s->initial_ctx;
2354 /* Need at least keyname + iv + some encrypted data */
2357 /* Initialize session ticket encryption and HMAC contexts */
2358 HMAC_CTX_init(&hctx);
2359 EVP_CIPHER_CTX_init(&ctx);
2360 if (tctx->tlsext_ticket_key_cb)
2362 unsigned char *nctick = (unsigned char *)etick;
2363 int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
2374 /* Check key name matches */
2375 if (memcmp(etick, tctx->tlsext_tick_key_name, 16))
2377 HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
2378 tlsext_tick_md(), NULL);
2379 EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
2380 tctx->tlsext_tick_aes_key, etick + 16);
2382 /* Attempt to process session ticket, first conduct sanity and
2383 * integrity checks on ticket.
2385 mlen = HMAC_size(&hctx);
2388 EVP_CIPHER_CTX_cleanup(&ctx);
2392 /* Check HMAC of encrypted ticket */
2393 HMAC_Update(&hctx, etick, eticklen);
2394 HMAC_Final(&hctx, tick_hmac, NULL);
2395 HMAC_CTX_cleanup(&hctx);
2396 if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen))
2398 /* Attempt to decrypt session data */
2399 /* Move p after IV to start of encrypted ticket, update length */
2400 p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx);
2401 eticklen -= 16 + EVP_CIPHER_CTX_iv_length(&ctx);
2402 sdec = OPENSSL_malloc(eticklen);
2405 EVP_CIPHER_CTX_cleanup(&ctx);
2408 EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen);
2409 if (EVP_DecryptFinal_ex(&ctx, sdec + slen, &mlen) <= 0)
2411 EVP_CIPHER_CTX_cleanup(&ctx);
2416 EVP_CIPHER_CTX_cleanup(&ctx);
2419 sess = d2i_SSL_SESSION(NULL, &p, slen);
2423 /* The session ID, if non-empty, is used by some clients to
2424 * detect that the ticket has been accepted. So we copy it to
2425 * the session structure. If it is empty set length to zero
2426 * as required by standard.
2429 memcpy(sess->session_id, sess_id, sesslen);
2430 sess->session_id_length = sesslen;
2438 /* For session parse failure, indicate that we need to send a new
2443 /* Tables to translate from NIDs to TLS v1.2 ids */
2451 static const tls12_lookup tls12_md[] = {
2452 {NID_md5, TLSEXT_hash_md5},
2453 {NID_sha1, TLSEXT_hash_sha1},
2454 {NID_sha224, TLSEXT_hash_sha224},
2455 {NID_sha256, TLSEXT_hash_sha256},
2456 {NID_sha384, TLSEXT_hash_sha384},
2457 {NID_sha512, TLSEXT_hash_sha512}
2460 static const tls12_lookup tls12_sig[] = {
2461 {EVP_PKEY_RSA, TLSEXT_signature_rsa},
2462 {EVP_PKEY_EC, TLSEXT_signature_ecdsa}
2465 static int tls12_find_id(int nid, const tls12_lookup *table, size_t tlen)
2468 for (i = 0; i < tlen; i++)
2470 if (table[i].nid == nid)
2476 static int tls12_find_nid(int id, const tls12_lookup *table, size_t tlen)
2479 for (i = 0; i < tlen; i++)
2481 if ((table[i].id) == id)
2482 return table[i].nid;
2487 int tls12_get_sigandhash(unsigned char *p, const EVP_PKEY *pk, const EVP_MD *md)
2492 md_id = tls12_find_id(EVP_MD_type(md), tls12_md,
2493 sizeof(tls12_md)/sizeof(tls12_lookup));
2496 sig_id = tls12_get_sigid(pk);
2499 p[0] = (unsigned char)md_id;
2500 p[1] = (unsigned char)sig_id;
2504 int tls12_get_sigid(const EVP_PKEY *pk)
2506 return tls12_find_id(pk->type, tls12_sig,
2507 sizeof(tls12_sig)/sizeof(tls12_lookup));
2510 const EVP_MD *tls12_get_hash(unsigned char hash_alg)
2514 case TLSEXT_hash_md5:
2516 case TLSEXT_hash_sha1:
2518 case TLSEXT_hash_sha224:
2519 return EVP_sha224();
2521 case TLSEXT_hash_sha256:
2522 return EVP_sha256();
2523 case TLSEXT_hash_sha384:
2524 return EVP_sha384();
2526 case TLSEXT_hash_sha512:
2527 return EVP_sha512();
2534 static int tls12_get_pkey_idx(unsigned char sig_alg)
2538 case TLSEXT_signature_rsa:
2539 return SSL_PKEY_RSA_SIGN;
2540 case TLSEXT_signature_ecdsa:
2541 return SSL_PKEY_ECC;
2546 /* Convert TLS 1.2 signature algorithm extension values into NIDs */
2547 static void tls1_lookup_sigalg(int *phash_nid, int *psign_nid,
2548 int *psignhash_nid, const unsigned char *data)
2550 int sign_nid = 0, hash_nid = 0;
2551 if (!phash_nid && !psign_nid && !psignhash_nid)
2553 if (phash_nid || psignhash_nid)
2555 hash_nid = tls12_find_nid(data[0], tls12_md,
2556 sizeof(tls12_md)/sizeof(tls12_lookup));
2558 *phash_nid = hash_nid;
2560 if (psign_nid || psignhash_nid)
2562 sign_nid = tls12_find_nid(data[1], tls12_sig,
2563 sizeof(tls12_sig)/sizeof(tls12_lookup));
2565 *psign_nid = sign_nid;
2569 if (sign_nid && hash_nid)
2570 OBJ_find_sigid_by_algs(psignhash_nid,
2571 hash_nid, sign_nid);
2573 *psignhash_nid = NID_undef;
2576 /* Given preference and allowed sigalgs set shared sigalgs */
2577 static int tls12_do_shared_sigalgs(TLS_SIGALGS *shsig,
2578 const unsigned char *pref, size_t preflen,
2579 const unsigned char *allow, size_t allowlen)
2581 const unsigned char *ptmp, *atmp;
2582 size_t i, j, nmatch = 0;
2583 for (i = 0, ptmp = pref; i < preflen; i+=2, ptmp+=2)
2585 /* Skip disabled hashes or signature algorithms */
2586 if (tls12_get_hash(ptmp[0]) == NULL)
2588 if (tls12_get_pkey_idx(ptmp[1]) == -1)
2590 for (j = 0, atmp = allow; j < allowlen; j+=2, atmp+=2)
2592 if (ptmp[0] == atmp[0] && ptmp[1] == atmp[1])
2597 shsig->rhash = ptmp[0];
2598 shsig->rsign = ptmp[1];
2599 tls1_lookup_sigalg(&shsig->hash_nid,
2601 &shsig->signandhash_nid,
2612 /* Set shared signature algorithms for SSL structures */
2613 static int tls1_set_shared_sigalgs(SSL *s)
2615 const unsigned char *pref, *allow, *conf;
2616 size_t preflen, allowlen, conflen;
2618 TLS_SIGALGS *salgs = NULL;
2620 if (c->shared_sigalgs)
2622 OPENSSL_free(c->shared_sigalgs);
2623 c->shared_sigalgs = NULL;
2625 /* If client use client signature algorithms if not NULL */
2626 if (!s->server && c->client_sigalgs)
2628 conf = c->client_sigalgs;
2629 conflen = c->client_sigalgslen;
2631 else if (c->conf_sigalgs)
2633 conf = c->conf_sigalgs;
2634 conflen = c->conf_sigalgslen;
2637 conflen = tls12_get_psigalgs(s, &conf);
2638 if(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE)
2642 allow = c->peer_sigalgs;
2643 allowlen = c->peer_sigalgslen;
2649 pref = c->peer_sigalgs;
2650 preflen = c->peer_sigalgslen;
2652 nmatch = tls12_do_shared_sigalgs(NULL, pref, preflen, allow, allowlen);
2655 salgs = OPENSSL_malloc(nmatch * sizeof(TLS_SIGALGS));
2658 nmatch = tls12_do_shared_sigalgs(salgs, pref, preflen, allow, allowlen);
2659 c->shared_sigalgs = salgs;
2660 c->shared_sigalgslen = nmatch;
2665 /* Set preferred digest for each key type */
2667 int tls1_process_sigalgs(SSL *s, const CBS *sigalgs)
2673 TLS_SIGALGS *sigptr;
2675 /* Extension ignored for inappropriate versions */
2676 if (!SSL_USE_SIGALGS(s))
2678 /* Length must be even */
2679 if (CBS_len(sigalgs) % 2 != 0)
2681 /* Should never happen */
2685 if (!CBS_stow(sigalgs, &c->peer_sigalgs, &c->peer_sigalgslen))
2688 tls1_set_shared_sigalgs(s);
2690 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
2691 if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
2693 /* Use first set signature preference to force message
2694 * digest, ignoring any peer preferences.
2696 const unsigned char *sigs = NULL;
2698 sigs = c->conf_sigalgs;
2700 sigs = c->client_sigalgs;
2703 idx = tls12_get_pkey_idx(sigs[1]);
2704 md = tls12_get_hash(sigs[0]);
2705 c->pkeys[idx].digest = md;
2706 c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
2707 if (idx == SSL_PKEY_RSA_SIGN)
2709 c->pkeys[SSL_PKEY_RSA_ENC].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
2710 c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
2716 for (i = 0, sigptr = c->shared_sigalgs;
2717 i < c->shared_sigalgslen; i++, sigptr++)
2719 idx = tls12_get_pkey_idx(sigptr->rsign);
2720 if (idx > 0 && c->pkeys[idx].digest == NULL)
2722 md = tls12_get_hash(sigptr->rhash);
2723 c->pkeys[idx].digest = md;
2724 c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
2725 if (idx == SSL_PKEY_RSA_SIGN)
2727 c->pkeys[SSL_PKEY_RSA_ENC].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
2728 c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
2733 /* In strict mode leave unset digests as NULL to indicate we can't
2734 * use the certificate for signing.
2736 if (!(s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT))
2738 /* Set any remaining keys to default values. NOTE: if alg is
2739 * not supported it stays as NULL.
2741 if (!c->pkeys[SSL_PKEY_RSA_SIGN].digest)
2743 c->pkeys[SSL_PKEY_RSA_SIGN].digest = EVP_sha1();
2744 c->pkeys[SSL_PKEY_RSA_ENC].digest = EVP_sha1();
2746 if (!c->pkeys[SSL_PKEY_ECC].digest)
2747 c->pkeys[SSL_PKEY_ECC].digest = EVP_sha1();
2753 int SSL_get_sigalgs(SSL *s, int idx,
2754 int *psign, int *phash, int *psignhash,
2755 unsigned char *rsig, unsigned char *rhash)
2757 const unsigned char *psig = s->cert->peer_sigalgs;
2763 if (idx >= (int)s->cert->peer_sigalgslen)
2770 tls1_lookup_sigalg(phash, psign, psignhash, psig);
2772 return s->cert->peer_sigalgslen / 2;
2775 int SSL_get_shared_sigalgs(SSL *s, int idx,
2776 int *psign, int *phash, int *psignhash,
2777 unsigned char *rsig, unsigned char *rhash)
2779 TLS_SIGALGS *shsigalgs = s->cert->shared_sigalgs;
2780 if (!shsigalgs || idx >= (int)s->cert->shared_sigalgslen)
2784 *phash = shsigalgs->hash_nid;
2786 *psign = shsigalgs->sign_nid;
2788 *psignhash = shsigalgs->signandhash_nid;
2790 *rsig = shsigalgs->rsign;
2792 *rhash = shsigalgs->rhash;
2793 return s->cert->shared_sigalgslen;
2796 /* tls1_channel_id_hash calculates the signed data for a Channel ID on the given
2797 * SSL connection and writes it to |md|. */
2799 tls1_channel_id_hash(EVP_MD_CTX *md, SSL *s)
2802 unsigned char temp_digest[EVP_MAX_MD_SIZE];
2803 unsigned temp_digest_len;
2805 static const char kClientIDMagic[] = "TLS Channel ID signature";
2807 if (s->s3->handshake_buffer)
2808 if (!ssl3_digest_cached_records(s))
2811 EVP_DigestUpdate(md, kClientIDMagic, sizeof(kClientIDMagic));
2813 if (s->hit && s->s3->tlsext_channel_id_new)
2815 static const char kResumptionMagic[] = "Resumption";
2816 EVP_DigestUpdate(md, kResumptionMagic,
2817 sizeof(kResumptionMagic));
2818 if (s->session->original_handshake_hash_len == 0)
2820 EVP_DigestUpdate(md, s->session->original_handshake_hash,
2821 s->session->original_handshake_hash_len);
2824 EVP_MD_CTX_init(&ctx);
2825 for (i = 0; i < SSL_MAX_DIGEST; i++)
2827 if (s->s3->handshake_dgst[i] == NULL)
2829 EVP_MD_CTX_copy_ex(&ctx, s->s3->handshake_dgst[i]);
2830 EVP_DigestFinal_ex(&ctx, temp_digest, &temp_digest_len);
2831 EVP_DigestUpdate(md, temp_digest, temp_digest_len);
2833 EVP_MD_CTX_cleanup(&ctx);
2838 /* tls1_record_handshake_hashes_for_channel_id records the current handshake
2839 * hashes in |s->session| so that Channel ID resumptions can sign that data. */
2840 int tls1_record_handshake_hashes_for_channel_id(SSL *s)
2843 /* This function should never be called for a resumed session because
2844 * the handshake hashes that we wish to record are for the original,
2845 * full handshake. */
2848 /* It only makes sense to call this function if Channel IDs have been
2850 if (!s->s3->tlsext_channel_id_new)
2853 digest_len = tls1_handshake_digest(
2854 s, s->session->original_handshake_hash,
2855 sizeof(s->session->original_handshake_hash));
2859 s->session->original_handshake_hash_len = digest_len;
2864 int tls1_set_sigalgs(CERT *c, const int *psig_nids, size_t salglen, int client)
2866 unsigned char *sigalgs, *sptr;
2871 sigalgs = OPENSSL_malloc(salglen);
2872 if (sigalgs == NULL)
2874 for (i = 0, sptr = sigalgs; i < salglen; i+=2)
2876 rhash = tls12_find_id(*psig_nids++, tls12_md,
2877 sizeof(tls12_md)/sizeof(tls12_lookup));
2878 rsign = tls12_find_id(*psig_nids++, tls12_sig,
2879 sizeof(tls12_sig)/sizeof(tls12_lookup));
2881 if (rhash == -1 || rsign == -1)
2889 if (c->client_sigalgs)
2890 OPENSSL_free(c->client_sigalgs);
2891 c->client_sigalgs = sigalgs;
2892 c->client_sigalgslen = salglen;
2896 if (c->conf_sigalgs)
2897 OPENSSL_free(c->conf_sigalgs);
2898 c->conf_sigalgs = sigalgs;
2899 c->conf_sigalgslen = salglen;
2905 OPENSSL_free(sigalgs);
2909 static int tls1_check_sig_alg(CERT *c, X509 *x, int default_nid)
2913 if (default_nid == -1)
2915 sig_nid = X509_get_signature_nid(x);
2917 return sig_nid == default_nid ? 1 : 0;
2918 for (i = 0; i < c->shared_sigalgslen; i++)
2919 if (sig_nid == c->shared_sigalgs[i].signandhash_nid)
2923 /* Check to see if a certificate issuer name matches list of CA names */
2924 static int ssl_check_ca_name(STACK_OF(X509_NAME) *names, X509 *x)
2928 nm = X509_get_issuer_name(x);
2929 for (i = 0; i < sk_X509_NAME_num(names); i++)
2931 if(!X509_NAME_cmp(nm, sk_X509_NAME_value(names, i)))
2937 /* Check certificate chain is consistent with TLS extensions and is
2938 * usable by server. This servers two purposes: it allows users to
2939 * check chains before passing them to the server and it allows the
2940 * server to check chains before attempting to use them.
2943 /* Flags which need to be set for a certificate when stict mode not set */
2945 #define CERT_PKEY_VALID_FLAGS \
2946 (CERT_PKEY_EE_SIGNATURE|CERT_PKEY_EE_PARAM)
2947 /* Strict mode flags */
2948 #define CERT_PKEY_STRICT_FLAGS \
2949 (CERT_PKEY_VALID_FLAGS|CERT_PKEY_CA_SIGNATURE|CERT_PKEY_CA_PARAM \
2950 | CERT_PKEY_ISSUER_NAME|CERT_PKEY_CERT_TYPE)
2952 int tls1_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain,
2957 int check_flags = 0, strict_mode;
2958 CERT_PKEY *cpk = NULL;
2960 /* idx == -1 means checking server chains */
2963 /* idx == -2 means checking client certificate chains */
2967 idx = cpk - c->pkeys;
2970 cpk = c->pkeys + idx;
2972 pk = cpk->privatekey;
2974 strict_mode = c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT;
2975 /* If no cert or key, forget it */
2978 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
2979 /* Allow any certificate to pass test */
2980 if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
2982 rv = CERT_PKEY_STRICT_FLAGS|CERT_PKEY_EXPLICIT_SIGN|CERT_PKEY_VALID|CERT_PKEY_SIGN;
2983 cpk->valid_flags = rv;
2992 idx = ssl_cert_type(x, pk);
2995 cpk = c->pkeys + idx;
2996 if (c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)
2997 check_flags = CERT_PKEY_STRICT_FLAGS;
2999 check_flags = CERT_PKEY_VALID_FLAGS;
3003 /* Check all signature algorithms are consistent with
3004 * signature algorithms extension if TLS 1.2 or later
3007 if (TLS1_get_version(s) >= TLS1_2_VERSION && strict_mode)
3010 unsigned char rsign = 0;
3011 if (c->peer_sigalgs)
3013 /* If no sigalgs extension use defaults from RFC5246 */
3018 case SSL_PKEY_RSA_ENC:
3019 case SSL_PKEY_RSA_SIGN:
3020 rsign = TLSEXT_signature_rsa;
3021 default_nid = NID_sha1WithRSAEncryption;
3025 rsign = TLSEXT_signature_ecdsa;
3026 default_nid = NID_ecdsa_with_SHA1;
3034 /* If peer sent no signature algorithms extension and we
3035 * have set preferred signature algorithms check we support
3038 if (default_nid > 0 && c->conf_sigalgs)
3041 const unsigned char *p = c->conf_sigalgs;
3042 for (j = 0; j < c->conf_sigalgslen; j += 2, p += 2)
3044 if (p[0] == TLSEXT_hash_sha1 && p[1] == rsign)
3047 if (j == c->conf_sigalgslen)
3055 /* Check signature algorithm of each cert in chain */
3056 if (!tls1_check_sig_alg(c, x, default_nid))
3058 if (!check_flags) goto end;
3061 rv |= CERT_PKEY_EE_SIGNATURE;
3062 rv |= CERT_PKEY_CA_SIGNATURE;
3063 for (i = 0; i < sk_X509_num(chain); i++)
3065 if (!tls1_check_sig_alg(c, sk_X509_value(chain, i),
3070 rv &= ~CERT_PKEY_CA_SIGNATURE;
3078 /* Else not TLS 1.2, so mark EE and CA signing algorithms OK */
3079 else if(check_flags)
3080 rv |= CERT_PKEY_EE_SIGNATURE|CERT_PKEY_CA_SIGNATURE;
3082 /* Check cert parameters are consistent */
3083 if (tls1_check_cert_param(s, x, check_flags ? 1 : 2))
3084 rv |= CERT_PKEY_EE_PARAM;
3085 else if (!check_flags)
3088 rv |= CERT_PKEY_CA_PARAM;
3089 /* In strict mode check rest of chain too */
3090 else if (strict_mode)
3092 rv |= CERT_PKEY_CA_PARAM;
3093 for (i = 0; i < sk_X509_num(chain); i++)
3095 X509 *ca = sk_X509_value(chain, i);
3096 if (!tls1_check_cert_param(s, ca, 0))
3100 rv &= ~CERT_PKEY_CA_PARAM;
3108 if (!s->server && strict_mode)
3110 STACK_OF(X509_NAME) *ca_dn;
3111 uint8_t check_type = 0;
3115 check_type = TLS_CT_RSA_SIGN;
3118 check_type = TLS_CT_ECDSA_SIGN;
3123 if (s->s3->tmp.certificate_types &&
3124 memchr(s->s3->tmp.certificate_types, check_type, s->s3->tmp.num_certificate_types))
3126 rv |= CERT_PKEY_CERT_TYPE;
3128 if (!(rv & CERT_PKEY_CERT_TYPE) && !check_flags)
3132 rv |= CERT_PKEY_CERT_TYPE;
3135 ca_dn = s->s3->tmp.ca_names;
3137 if (!sk_X509_NAME_num(ca_dn))
3138 rv |= CERT_PKEY_ISSUER_NAME;
3140 if (!(rv & CERT_PKEY_ISSUER_NAME))
3142 if (ssl_check_ca_name(ca_dn, x))
3143 rv |= CERT_PKEY_ISSUER_NAME;
3145 if (!(rv & CERT_PKEY_ISSUER_NAME))
3147 for (i = 0; i < sk_X509_num(chain); i++)
3149 X509 *xtmp = sk_X509_value(chain, i);
3150 if (ssl_check_ca_name(ca_dn, xtmp))
3152 rv |= CERT_PKEY_ISSUER_NAME;
3157 if (!check_flags && !(rv & CERT_PKEY_ISSUER_NAME))
3161 rv |= CERT_PKEY_ISSUER_NAME|CERT_PKEY_CERT_TYPE;
3163 if (!check_flags || (rv & check_flags) == check_flags)
3164 rv |= CERT_PKEY_VALID;
3168 if (TLS1_get_version(s) >= TLS1_2_VERSION)
3170 if (cpk->valid_flags & CERT_PKEY_EXPLICIT_SIGN)
3171 rv |= CERT_PKEY_EXPLICIT_SIGN|CERT_PKEY_SIGN;
3172 else if (cpk->digest)
3173 rv |= CERT_PKEY_SIGN;
3176 rv |= CERT_PKEY_SIGN|CERT_PKEY_EXPLICIT_SIGN;
3178 /* When checking a CERT_PKEY structure all flags are irrelevant
3179 * if the chain is invalid.
3183 if (rv & CERT_PKEY_VALID)
3184 cpk->valid_flags = rv;
3187 /* Preserve explicit sign flag, clear rest */
3188 cpk->valid_flags &= CERT_PKEY_EXPLICIT_SIGN;
3195 /* Set validity of certificates in an SSL structure */
3196 void tls1_set_cert_validity(SSL *s)
3198 tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_ENC);
3199 tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_SIGN);
3200 tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_ECC);
3202 /* User level utiity function to check a chain is suitable */
3203 int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain)
3205 return tls1_check_chain(s, x, pk, chain, -1);