t1_lib.c revision fdeb488e6332a17729db5a04236e48a46a019272
1/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2 * All rights reserved.
3 *
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.
7 *
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).
14 *
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.
21 *
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
24 * are met:
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)"
39 *
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
50 * SUCH DAMAGE.
51 *
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.]
56 */
57/* ====================================================================
58 * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
59 *
60 * Redistribution and use in source and binary forms, with or without
61 * modification, are permitted provided that the following conditions
62 * are met:
63 *
64 * 1. Redistributions of source code must retain the above copyright
65 *    notice, this list of conditions and the following disclaimer.
66 *
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
70 *    distribution.
71 *
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/)"
76 *
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.
81 *
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.
85 *
86 * 6. Redistributions of any form whatsoever must retain the following
87 *    acknowledgment:
88 *    "This product includes software developed by the OpenSSL Project
89 *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90 *
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 * ====================================================================
104 *
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). */
108
109#include <openssl/ssl.h>
110
111#include <assert.h>
112#include <limits.h>
113#include <stdio.h>
114#include <stdlib.h>
115#include <string.h>
116
117#include <openssl/bytestring.h>
118#include <openssl/digest.h>
119#include <openssl/err.h>
120#include <openssl/evp.h>
121#include <openssl/hmac.h>
122#include <openssl/mem.h>
123#include <openssl/obj.h>
124#include <openssl/rand.h>
125#include <openssl/type_check.h>
126
127#include "internal.h"
128
129
130static int ssl_check_clienthello_tlsext(SSL *s);
131static int ssl_check_serverhello_tlsext(SSL *s);
132
133const SSL3_ENC_METHOD TLSv1_enc_data = {
134    tls1_prf,
135    tls1_setup_key_block,
136    tls1_generate_master_secret,
137    tls1_change_cipher_state,
138    tls1_final_finish_mac,
139    tls1_cert_verify_mac,
140    TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
141    TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
142    tls1_alert_code,
143    tls1_export_keying_material,
144    0,
145};
146
147const SSL3_ENC_METHOD TLSv1_1_enc_data = {
148    tls1_prf,
149    tls1_setup_key_block,
150    tls1_generate_master_secret,
151    tls1_change_cipher_state,
152    tls1_final_finish_mac,
153    tls1_cert_verify_mac,
154    TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
155    TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
156    tls1_alert_code,
157    tls1_export_keying_material,
158    SSL_ENC_FLAG_EXPLICIT_IV,
159};
160
161const SSL3_ENC_METHOD TLSv1_2_enc_data = {
162    tls1_prf,
163    tls1_setup_key_block,
164    tls1_generate_master_secret,
165    tls1_change_cipher_state,
166    tls1_final_finish_mac,
167    tls1_cert_verify_mac,
168    TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
169    TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
170    tls1_alert_code,
171    tls1_export_keying_material,
172    SSL_ENC_FLAG_EXPLICIT_IV|SSL_ENC_FLAG_SIGALGS|SSL_ENC_FLAG_SHA256_PRF
173            |SSL_ENC_FLAG_TLS1_2_CIPHERS,
174};
175
176static int compare_uint16_t(const void *p1, const void *p2) {
177  uint16_t u1 = *((const uint16_t *)p1);
178  uint16_t u2 = *((const uint16_t *)p2);
179  if (u1 < u2) {
180    return -1;
181  } else if (u1 > u2) {
182    return 1;
183  } else {
184    return 0;
185  }
186}
187
188/* Per http://tools.ietf.org/html/rfc5246#section-7.4.1.4, there may not be
189 * more than one extension of the same type in a ClientHello or ServerHello.
190 * This function does an initial scan over the extensions block to filter those
191 * out. */
192static int tls1_check_duplicate_extensions(const CBS *cbs) {
193  CBS extensions = *cbs;
194  size_t num_extensions = 0, i = 0;
195  uint16_t *extension_types = NULL;
196  int ret = 0;
197
198  /* First pass: count the extensions. */
199  while (CBS_len(&extensions) > 0) {
200    uint16_t type;
201    CBS extension;
202
203    if (!CBS_get_u16(&extensions, &type) ||
204        !CBS_get_u16_length_prefixed(&extensions, &extension)) {
205      goto done;
206    }
207
208    num_extensions++;
209  }
210
211  if (num_extensions == 0) {
212    return 1;
213  }
214
215  extension_types =
216      (uint16_t *)OPENSSL_malloc(sizeof(uint16_t) * num_extensions);
217  if (extension_types == NULL) {
218    OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
219    goto done;
220  }
221
222  /* Second pass: gather the extension types. */
223  extensions = *cbs;
224  for (i = 0; i < num_extensions; i++) {
225    CBS extension;
226
227    if (!CBS_get_u16(&extensions, &extension_types[i]) ||
228        !CBS_get_u16_length_prefixed(&extensions, &extension)) {
229      /* This should not happen. */
230      goto done;
231    }
232  }
233  assert(CBS_len(&extensions) == 0);
234
235  /* Sort the extensions and make sure there are no duplicates. */
236  qsort(extension_types, num_extensions, sizeof(uint16_t), compare_uint16_t);
237  for (i = 1; i < num_extensions; i++) {
238    if (extension_types[i - 1] == extension_types[i]) {
239      goto done;
240    }
241  }
242
243  ret = 1;
244
245done:
246  OPENSSL_free(extension_types);
247  return ret;
248}
249
250char ssl_early_callback_init(struct ssl_early_callback_ctx *ctx) {
251  CBS client_hello, session_id, cipher_suites, compression_methods, extensions;
252
253  CBS_init(&client_hello, ctx->client_hello, ctx->client_hello_len);
254
255  if (/* Skip client version. */
256      !CBS_skip(&client_hello, 2) ||
257      /* Skip client nonce. */
258      !CBS_skip(&client_hello, 32) ||
259      /* Extract session_id. */
260      !CBS_get_u8_length_prefixed(&client_hello, &session_id)) {
261    return 0;
262  }
263
264  ctx->session_id = CBS_data(&session_id);
265  ctx->session_id_len = CBS_len(&session_id);
266
267  /* Skip past DTLS cookie */
268  if (SSL_IS_DTLS(ctx->ssl)) {
269    CBS cookie;
270
271    if (!CBS_get_u8_length_prefixed(&client_hello, &cookie)) {
272      return 0;
273    }
274  }
275
276  /* Extract cipher_suites. */
277  if (!CBS_get_u16_length_prefixed(&client_hello, &cipher_suites) ||
278      CBS_len(&cipher_suites) < 2 || (CBS_len(&cipher_suites) & 1) != 0) {
279    return 0;
280  }
281  ctx->cipher_suites = CBS_data(&cipher_suites);
282  ctx->cipher_suites_len = CBS_len(&cipher_suites);
283
284  /* Extract compression_methods. */
285  if (!CBS_get_u8_length_prefixed(&client_hello, &compression_methods) ||
286      CBS_len(&compression_methods) < 1) {
287    return 0;
288  }
289  ctx->compression_methods = CBS_data(&compression_methods);
290  ctx->compression_methods_len = CBS_len(&compression_methods);
291
292  /* If the ClientHello ends here then it's valid, but doesn't have any
293   * extensions. (E.g. SSLv3.) */
294  if (CBS_len(&client_hello) == 0) {
295    ctx->extensions = NULL;
296    ctx->extensions_len = 0;
297    return 1;
298  }
299
300  /* Extract extensions and check it is valid. */
301  if (!CBS_get_u16_length_prefixed(&client_hello, &extensions) ||
302      !tls1_check_duplicate_extensions(&extensions) ||
303      CBS_len(&client_hello) != 0) {
304    return 0;
305  }
306  ctx->extensions = CBS_data(&extensions);
307  ctx->extensions_len = CBS_len(&extensions);
308
309  return 1;
310}
311
312int SSL_early_callback_ctx_extension_get(
313    const struct ssl_early_callback_ctx *ctx, uint16_t extension_type,
314    const uint8_t **out_data, size_t *out_len) {
315  CBS extensions;
316
317  CBS_init(&extensions, ctx->extensions, ctx->extensions_len);
318
319  while (CBS_len(&extensions) != 0) {
320    uint16_t type;
321    CBS extension;
322
323    /* Decode the next extension. */
324    if (!CBS_get_u16(&extensions, &type) ||
325        !CBS_get_u16_length_prefixed(&extensions, &extension)) {
326      return 0;
327    }
328
329    if (type == extension_type) {
330      *out_data = CBS_data(&extension);
331      *out_len = CBS_len(&extension);
332      return 1;
333    }
334  }
335
336  return 0;
337}
338
339struct tls_curve {
340  uint16_t curve_id;
341  int nid;
342  const char curve_name[8];
343};
344
345/* ECC curves from RFC4492. */
346static const struct tls_curve tls_curves[] = {
347    {21, NID_secp224r1, "P-224"},
348    {23, NID_X9_62_prime256v1, "P-256"},
349    {24, NID_secp384r1, "P-384"},
350    {25, NID_secp521r1, "P-521"},
351};
352
353static const uint16_t eccurves_default[] = {
354    23, /* X9_62_prime256v1 */
355    24, /* secp384r1 */
356#if defined(BORINGSSL_ANDROID_SYSTEM)
357    25, /* secp521r1 */
358#endif
359};
360
361int tls1_ec_curve_id2nid(uint16_t curve_id) {
362  size_t i;
363  for (i = 0; i < sizeof(tls_curves) / sizeof(tls_curves[0]); i++) {
364    if (curve_id == tls_curves[i].curve_id) {
365      return tls_curves[i].nid;
366    }
367  }
368  return NID_undef;
369}
370
371int tls1_ec_nid2curve_id(uint16_t *out_curve_id, int nid) {
372  size_t i;
373  for (i = 0; i < sizeof(tls_curves) / sizeof(tls_curves[0]); i++) {
374    if (nid == tls_curves[i].nid) {
375      *out_curve_id = tls_curves[i].curve_id;
376      return 1;
377    }
378  }
379  return 0;
380}
381
382const char* tls1_ec_curve_id2name(uint16_t curve_id) {
383  size_t i;
384  for (i = 0; i < sizeof(tls_curves) / sizeof(tls_curves[0]); i++) {
385    if (curve_id == tls_curves[i].curve_id) {
386      return tls_curves[i].curve_name;
387    }
388  }
389  return NULL;
390}
391
392/* tls1_get_curvelist sets |*out_curve_ids| and |*out_curve_ids_len| to the
393 * list of allowed curve IDs. If |get_peer_curves| is non-zero, return the
394 * peer's curve list. Otherwise, return the preferred list. */
395static void tls1_get_curvelist(SSL *s, int get_peer_curves,
396                               const uint16_t **out_curve_ids,
397                               size_t *out_curve_ids_len) {
398  if (get_peer_curves) {
399    /* Only clients send a curve list, so this function is only called
400     * on the server. */
401    assert(s->server);
402    *out_curve_ids = s->s3->tmp.peer_ellipticcurvelist;
403    *out_curve_ids_len = s->s3->tmp.peer_ellipticcurvelist_length;
404    return;
405  }
406
407  *out_curve_ids = s->tlsext_ellipticcurvelist;
408  *out_curve_ids_len = s->tlsext_ellipticcurvelist_length;
409  if (!*out_curve_ids) {
410    *out_curve_ids = eccurves_default;
411    *out_curve_ids_len = sizeof(eccurves_default) / sizeof(eccurves_default[0]);
412  }
413}
414
415int tls1_check_curve(SSL *s, CBS *cbs, uint16_t *out_curve_id) {
416  uint8_t curve_type;
417  uint16_t curve_id;
418  const uint16_t *curves;
419  size_t curves_len, i;
420
421  /* Only support named curves. */
422  if (!CBS_get_u8(cbs, &curve_type) ||
423      curve_type != NAMED_CURVE_TYPE ||
424      !CBS_get_u16(cbs, &curve_id)) {
425    return 0;
426  }
427
428  tls1_get_curvelist(s, 0, &curves, &curves_len);
429  for (i = 0; i < curves_len; i++) {
430    if (curve_id == curves[i]) {
431      *out_curve_id = curve_id;
432      return 1;
433    }
434  }
435
436  return 0;
437}
438
439int tls1_get_shared_curve(SSL *s) {
440  const uint16_t *curves, *peer_curves, *pref, *supp;
441  size_t curves_len, peer_curves_len, pref_len, supp_len, i, j;
442
443  /* Can't do anything on client side */
444  if (s->server == 0) {
445    return NID_undef;
446  }
447
448  tls1_get_curvelist(s, 0 /* local curves */, &curves, &curves_len);
449  tls1_get_curvelist(s, 1 /* peer curves */, &peer_curves, &peer_curves_len);
450
451  if (peer_curves_len == 0) {
452    /* Clients are not required to send a supported_curves extension. In this
453     * case, the server is free to pick any curve it likes. See RFC 4492,
454     * section 4, paragraph 3. */
455    return (curves_len == 0) ? NID_undef : tls1_ec_curve_id2nid(curves[0]);
456  }
457
458  if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) {
459    pref = curves;
460    pref_len = curves_len;
461    supp = peer_curves;
462    supp_len = peer_curves_len;
463  } else {
464    pref = peer_curves;
465    pref_len = peer_curves_len;
466    supp = curves;
467    supp_len = curves_len;
468  }
469
470  for (i = 0; i < pref_len; i++) {
471    for (j = 0; j < supp_len; j++) {
472      if (pref[i] == supp[j]) {
473        return tls1_ec_curve_id2nid(pref[i]);
474      }
475    }
476  }
477
478  return NID_undef;
479}
480
481int tls1_set_curves(uint16_t **out_curve_ids, size_t *out_curve_ids_len,
482                    const int *curves, size_t ncurves) {
483  uint16_t *curve_ids;
484  size_t i;
485
486  curve_ids = (uint16_t *)OPENSSL_malloc(ncurves * sizeof(uint16_t));
487  if (curve_ids == NULL) {
488    return 0;
489  }
490
491  for (i = 0; i < ncurves; i++) {
492    if (!tls1_ec_nid2curve_id(&curve_ids[i], curves[i])) {
493      OPENSSL_free(curve_ids);
494      return 0;
495    }
496  }
497
498  OPENSSL_free(*out_curve_ids);
499  *out_curve_ids = curve_ids;
500  *out_curve_ids_len = ncurves;
501
502  return 1;
503}
504
505/* tls1_curve_params_from_ec_key sets |*out_curve_id| and |*out_comp_id| to the
506 * TLS curve ID and point format, respectively, for |ec|. It returns one on
507 * success and zero on failure. */
508static int tls1_curve_params_from_ec_key(uint16_t *out_curve_id,
509                                         uint8_t *out_comp_id, EC_KEY *ec) {
510  int nid;
511  uint16_t id;
512  const EC_GROUP *grp;
513
514  if (ec == NULL) {
515    return 0;
516  }
517
518  grp = EC_KEY_get0_group(ec);
519  if (grp == NULL) {
520    return 0;
521  }
522
523  /* Determine curve ID */
524  nid = EC_GROUP_get_curve_name(grp);
525  if (!tls1_ec_nid2curve_id(&id, nid)) {
526    return 0;
527  }
528
529  /* Set the named curve ID. Arbitrary explicit curves are not supported. */
530  *out_curve_id = id;
531
532  if (out_comp_id) {
533    if (EC_KEY_get0_public_key(ec) == NULL) {
534      return 0;
535    }
536    if (EC_KEY_get_conv_form(ec) == POINT_CONVERSION_COMPRESSED) {
537      *out_comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
538    } else {
539      *out_comp_id = TLSEXT_ECPOINTFORMAT_uncompressed;
540    }
541  }
542
543  return 1;
544}
545
546/* tls1_check_curve_id returns one if |curve_id| is consistent with both our
547 * and the peer's curve preferences. Note: if called as the client, only our
548 * preferences are checked; the peer (the server) does not send preferences. */
549static int tls1_check_curve_id(SSL *s, uint16_t curve_id) {
550  const uint16_t *curves;
551  size_t curves_len, i, get_peer_curves;
552
553  /* Check against our list, then the peer's list. */
554  for (get_peer_curves = 0; get_peer_curves <= 1; get_peer_curves++) {
555    if (get_peer_curves && !s->server) {
556      /* Servers do not present a preference list so, if we are a client, only
557       * check our list. */
558      continue;
559    }
560
561    tls1_get_curvelist(s, get_peer_curves, &curves, &curves_len);
562    if (get_peer_curves && curves_len == 0) {
563      /* Clients are not required to send a supported_curves extension. In this
564       * case, the server is free to pick any curve it likes. See RFC 4492,
565       * section 4, paragraph 3. */
566      continue;
567    }
568    for (i = 0; i < curves_len; i++) {
569      if (curves[i] == curve_id) {
570        break;
571      }
572    }
573
574    if (i == curves_len) {
575      return 0;
576    }
577  }
578
579  return 1;
580}
581
582int tls1_check_ec_cert(SSL *s, X509 *x) {
583  int ret = 0;
584  EVP_PKEY *pkey = X509_get_pubkey(x);
585  uint16_t curve_id;
586  uint8_t comp_id;
587
588  if (!pkey ||
589      pkey->type != EVP_PKEY_EC ||
590      !tls1_curve_params_from_ec_key(&curve_id, &comp_id, pkey->pkey.ec) ||
591      !tls1_check_curve_id(s, curve_id) ||
592      comp_id != TLSEXT_ECPOINTFORMAT_uncompressed) {
593    goto done;
594  }
595
596  ret = 1;
597
598done:
599  EVP_PKEY_free(pkey);
600  return ret;
601}
602
603int tls1_check_ec_tmp_key(SSL *s) {
604  if (s->cert->ecdh_nid != NID_undef) {
605    /* If the curve is preconfigured, ECDH is acceptable iff the peer supports
606     * the curve. */
607    uint16_t curve_id;
608    return tls1_ec_nid2curve_id(&curve_id, s->cert->ecdh_nid) &&
609           tls1_check_curve_id(s, curve_id);
610  }
611
612  if (s->cert->ecdh_tmp_cb != NULL) {
613    /* Assume the callback will provide an acceptable curve. */
614    return 1;
615  }
616
617  /* Otherwise, the curve gets selected automatically. ECDH is acceptable iff
618   * there is a shared curve. */
619  return tls1_get_shared_curve(s) != NID_undef;
620}
621
622/* List of supported signature algorithms and hashes. Should make this
623 * customisable at some point, for now include everything we support. */
624
625#define tlsext_sigalg_rsa(md) md, TLSEXT_signature_rsa,
626
627#define tlsext_sigalg_ecdsa(md) md, TLSEXT_signature_ecdsa,
628
629#define tlsext_sigalg(md) tlsext_sigalg_rsa(md) tlsext_sigalg_ecdsa(md)
630
631static const uint8_t tls12_sigalgs[] = {
632    tlsext_sigalg(TLSEXT_hash_sha512)
633    tlsext_sigalg(TLSEXT_hash_sha384)
634    tlsext_sigalg(TLSEXT_hash_sha256)
635    tlsext_sigalg(TLSEXT_hash_sha224)
636    tlsext_sigalg(TLSEXT_hash_sha1)
637};
638
639size_t tls12_get_psigalgs(SSL *s, const uint8_t **psigs) {
640  *psigs = tls12_sigalgs;
641  return sizeof(tls12_sigalgs);
642}
643
644/* tls12_check_peer_sigalg parses a SignatureAndHashAlgorithm out of |cbs|. It
645 * checks it is consistent with |s|'s sent supported signature algorithms and,
646 * if so, writes the relevant digest into |*out_md| and returns 1. Otherwise it
647 * returns 0 and writes an alert into |*out_alert|. */
648int tls12_check_peer_sigalg(const EVP_MD **out_md, int *out_alert, SSL *s,
649                            CBS *cbs, EVP_PKEY *pkey) {
650  const uint8_t *sent_sigs;
651  size_t sent_sigslen, i;
652  int sigalg = tls12_get_sigid(pkey->type);
653  uint8_t hash, signature;
654
655  /* Should never happen */
656  if (sigalg == -1) {
657    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
658    *out_alert = SSL_AD_INTERNAL_ERROR;
659    return 0;
660  }
661
662  if (!CBS_get_u8(cbs, &hash) ||
663      !CBS_get_u8(cbs, &signature)) {
664    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
665    *out_alert = SSL_AD_DECODE_ERROR;
666    return 0;
667  }
668
669  /* Check key type is consistent with signature */
670  if (sigalg != signature) {
671    OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SIGNATURE_TYPE);
672    *out_alert = SSL_AD_ILLEGAL_PARAMETER;
673    return 0;
674  }
675
676  if (pkey->type == EVP_PKEY_EC) {
677    uint16_t curve_id;
678    uint8_t comp_id;
679    /* Check compression and curve matches extensions */
680    if (!tls1_curve_params_from_ec_key(&curve_id, &comp_id, pkey->pkey.ec)) {
681      *out_alert = SSL_AD_INTERNAL_ERROR;
682      return 0;
683    }
684
685    if (s->server && (!tls1_check_curve_id(s, curve_id) ||
686                      comp_id != TLSEXT_ECPOINTFORMAT_uncompressed)) {
687      OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
688      *out_alert = SSL_AD_ILLEGAL_PARAMETER;
689      return 0;
690    }
691  }
692
693  /* Check signature matches a type we sent */
694  sent_sigslen = tls12_get_psigalgs(s, &sent_sigs);
695  for (i = 0; i < sent_sigslen; i += 2, sent_sigs += 2) {
696    if (hash == sent_sigs[0] && signature == sent_sigs[1]) {
697      break;
698    }
699  }
700
701  /* Allow fallback to SHA-1. */
702  if (i == sent_sigslen && hash != TLSEXT_hash_sha1) {
703    OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SIGNATURE_TYPE);
704    *out_alert = SSL_AD_ILLEGAL_PARAMETER;
705    return 0;
706  }
707
708  *out_md = tls12_get_hash(hash);
709  if (*out_md == NULL) {
710    OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_DIGEST);
711    *out_alert = SSL_AD_ILLEGAL_PARAMETER;
712    return 0;
713  }
714
715  return 1;
716}
717
718/* Get a mask of disabled algorithms: an algorithm is disabled if it isn't
719 * supported or doesn't appear in supported signature algorithms. Unlike
720 * ssl_cipher_get_disabled this applies to a specific session and not global
721 * settings. */
722void ssl_set_client_disabled(SSL *s) {
723  CERT *c = s->cert;
724  const uint8_t *sigalgs;
725  size_t i, sigalgslen;
726  int have_rsa = 0, have_ecdsa = 0;
727  c->mask_a = 0;
728  c->mask_k = 0;
729
730  /* Don't allow TLS 1.2 only ciphers if we don't suppport them */
731  if (!SSL_CLIENT_USE_TLS1_2_CIPHERS(s)) {
732    c->mask_ssl = SSL_TLSV1_2;
733  } else {
734    c->mask_ssl = 0;
735  }
736
737  /* Now go through all signature algorithms seeing if we support any for RSA,
738   * DSA, ECDSA. Do this for all versions not just TLS 1.2. */
739  sigalgslen = tls12_get_psigalgs(s, &sigalgs);
740  for (i = 0; i < sigalgslen; i += 2, sigalgs += 2) {
741    switch (sigalgs[1]) {
742      case TLSEXT_signature_rsa:
743        have_rsa = 1;
744        break;
745
746      case TLSEXT_signature_ecdsa:
747        have_ecdsa = 1;
748        break;
749    }
750  }
751
752  /* Disable auth if we don't include any appropriate signature algorithms. */
753  if (!have_rsa) {
754    c->mask_a |= SSL_aRSA;
755  }
756  if (!have_ecdsa) {
757    c->mask_a |= SSL_aECDSA;
758  }
759
760  /* with PSK there must be client callback set */
761  if (!s->psk_client_callback) {
762    c->mask_a |= SSL_aPSK;
763    c->mask_k |= SSL_kPSK;
764  }
765}
766
767/* tls_extension represents a TLS extension that is handled internally. The
768 * |init| function is called for each handshake, before any other functions of
769 * the extension. Then the add and parse callbacks are called as needed.
770 *
771 * The parse callbacks receive a |CBS| that contains the contents of the
772 * extension (i.e. not including the type and length bytes). If an extension is
773 * not received then the parse callbacks will be called with a NULL CBS so that
774 * they can do any processing needed to handle the absence of an extension.
775 *
776 * The add callbacks receive a |CBB| to which the extension can be appended but
777 * the function is responsible for appending the type and length bytes too.
778 *
779 * All callbacks return one for success and zero for error. If a parse function
780 * returns zero then a fatal alert with value |*out_alert| will be sent. If
781 * |*out_alert| isn't set, then a |decode_error| alert will be sent. */
782struct tls_extension {
783  uint16_t value;
784  void (*init)(SSL *ssl);
785
786  int (*add_clienthello)(SSL *ssl, CBB *out);
787  int (*parse_serverhello)(SSL *ssl, uint8_t *out_alert, CBS *contents);
788
789  int (*parse_clienthello)(SSL *ssl, uint8_t *out_alert, CBS *contents);
790  int (*add_serverhello)(SSL *ssl, CBB *out);
791};
792
793
794/* Server name indication (SNI).
795 *
796 * https://tools.ietf.org/html/rfc6066#section-3. */
797
798static void ext_sni_init(SSL *ssl) {
799  ssl->s3->tmp.should_ack_sni = 0;
800}
801
802static int ext_sni_add_clienthello(SSL *ssl, CBB *out) {
803  if (ssl->tlsext_hostname == NULL) {
804    return 1;
805  }
806
807  CBB contents, server_name_list, name;
808  if (!CBB_add_u16(out, TLSEXT_TYPE_server_name) ||
809      !CBB_add_u16_length_prefixed(out, &contents) ||
810      !CBB_add_u16_length_prefixed(&contents, &server_name_list) ||
811      !CBB_add_u8(&server_name_list, TLSEXT_NAMETYPE_host_name) ||
812      !CBB_add_u16_length_prefixed(&server_name_list, &name) ||
813      !CBB_add_bytes(&name, (const uint8_t *)ssl->tlsext_hostname,
814                     strlen(ssl->tlsext_hostname)) ||
815      !CBB_flush(out)) {
816    return 0;
817  }
818
819  return 1;
820}
821
822static int ext_sni_parse_serverhello(SSL *ssl, uint8_t *out_alert, CBS *contents) {
823  if (contents == NULL) {
824    return 1;
825  }
826
827  if (CBS_len(contents) != 0) {
828    return 0;
829  }
830
831  assert(ssl->tlsext_hostname != NULL);
832
833  if (!ssl->hit) {
834    assert(ssl->session->tlsext_hostname == NULL);
835    ssl->session->tlsext_hostname = BUF_strdup(ssl->tlsext_hostname);
836    if (!ssl->session->tlsext_hostname) {
837      *out_alert = SSL_AD_INTERNAL_ERROR;
838      return 0;
839    }
840  }
841
842  return 1;
843}
844
845static int ext_sni_parse_clienthello(SSL *ssl, uint8_t *out_alert, CBS *contents) {
846  if (contents == NULL) {
847    return 1;
848  }
849
850  /* The servername extension is treated as follows:
851   *
852   * - Only the hostname type is supported with a maximum length of 255.
853   * - The servername is rejected if too long or if it contains zeros, in
854   *   which case an fatal alert is generated.
855   * - The servername field is maintained together with the session cache.
856   * - When a session is resumed, the servername callback is invoked in order
857   *   to allow the application to position itself to the right context.
858   * - The servername is acknowledged if it is new for a session or when
859   *   it is identical to a previously used for the same session.
860   *   Applications can control the behaviour.  They can at any time
861   *   set a 'desirable' servername for a new SSL object. This can be the
862   *   case for example with HTTPS when a Host: header field is received and
863   *   a renegotiation is requested. In this case, a possible servername
864   *   presented in the new client hello is only acknowledged if it matches
865   *   the value of the Host: field.
866   * - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
867   *   if they provide for changing an explicit servername context for the
868   *   session,
869   *   i.e. when the session has been established with a servername extension.
870   */
871
872  CBS server_name_list;
873  char have_seen_host_name = 0;
874
875  if (!CBS_get_u16_length_prefixed(contents, &server_name_list) ||
876      CBS_len(&server_name_list) == 0 ||
877      CBS_len(contents) != 0) {
878    return 0;
879  }
880
881  /* Decode each ServerName in the extension. */
882  while (CBS_len(&server_name_list) > 0) {
883    uint8_t name_type;
884    CBS host_name;
885
886    if (!CBS_get_u8(&server_name_list, &name_type) ||
887        !CBS_get_u16_length_prefixed(&server_name_list, &host_name)) {
888      return 0;
889    }
890
891    /* Only host_name is supported. */
892    if (name_type != TLSEXT_NAMETYPE_host_name) {
893      continue;
894    }
895
896    if (have_seen_host_name) {
897      /* The ServerNameList MUST NOT contain more than one name of the same
898       * name_type. */
899      return 0;
900    }
901
902    have_seen_host_name = 1;
903
904    if (CBS_len(&host_name) == 0 ||
905        CBS_len(&host_name) > TLSEXT_MAXLEN_host_name ||
906        CBS_contains_zero_byte(&host_name)) {
907      *out_alert = SSL_AD_UNRECOGNIZED_NAME;
908      return 0;
909    }
910
911    if (!ssl->hit) {
912      assert(ssl->session->tlsext_hostname == NULL);
913      if (ssl->session->tlsext_hostname) {
914        /* This should be impossible. */
915        return 0;
916      }
917
918      /* Copy the hostname as a string. */
919      if (!CBS_strdup(&host_name, &ssl->session->tlsext_hostname)) {
920        *out_alert = SSL_AD_INTERNAL_ERROR;
921        return 0;
922      }
923
924      ssl->s3->tmp.should_ack_sni = 1;
925    }
926  }
927
928  return 1;
929}
930
931static int ext_sni_add_serverhello(SSL *ssl, CBB *out) {
932  if (ssl->hit ||
933      !ssl->s3->tmp.should_ack_sni ||
934      ssl->session->tlsext_hostname == NULL) {
935    return 1;
936  }
937
938  if (!CBB_add_u16(out, TLSEXT_TYPE_server_name) ||
939      !CBB_add_u16(out, 0 /* length */)) {
940    return 0;
941  }
942
943  return 1;
944}
945
946
947/* Renegotiation indication.
948 *
949 * https://tools.ietf.org/html/rfc5746 */
950
951static int ext_ri_add_clienthello(SSL *ssl, CBB *out) {
952  CBB contents, prev_finished;
953  if (!CBB_add_u16(out, TLSEXT_TYPE_renegotiate) ||
954      !CBB_add_u16_length_prefixed(out, &contents) ||
955      !CBB_add_u8_length_prefixed(&contents, &prev_finished) ||
956      !CBB_add_bytes(&prev_finished, ssl->s3->previous_client_finished,
957                     ssl->s3->previous_client_finished_len) ||
958      !CBB_flush(out)) {
959    return 0;
960  }
961
962  return 1;
963}
964
965static int ext_ri_parse_serverhello(SSL *ssl, uint8_t *out_alert,
966                                    CBS *contents) {
967  if (contents == NULL) {
968    /* No renegotiation extension received.
969     *
970     * Strictly speaking if we want to avoid an attack we should *always* see
971     * RI even on initial ServerHello because the client doesn't see any
972     * renegotiation during an attack. However this would mean we could not
973     * connect to any server which doesn't support RI.
974     *
975     * A lack of the extension is allowed if SSL_OP_LEGACY_SERVER_CONNECT is
976     * defined. */
977    if (ssl->options & SSL_OP_LEGACY_SERVER_CONNECT) {
978      return 1;
979    }
980
981    *out_alert = SSL_AD_HANDSHAKE_FAILURE;
982    OPENSSL_PUT_ERROR(SSL, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
983    return 0;
984  }
985
986  const size_t expected_len = ssl->s3->previous_client_finished_len +
987                              ssl->s3->previous_server_finished_len;
988
989  /* Check for logic errors */
990  assert(!expected_len || ssl->s3->previous_client_finished_len);
991  assert(!expected_len || ssl->s3->previous_server_finished_len);
992
993  /* Parse out the extension contents. */
994  CBS renegotiated_connection;
995  if (!CBS_get_u8_length_prefixed(contents, &renegotiated_connection) ||
996      CBS_len(contents) != 0) {
997    OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_ENCODING_ERR);
998    *out_alert = SSL_AD_ILLEGAL_PARAMETER;
999    return 0;
1000  }
1001
1002  /* Check that the extension matches. */
1003  if (CBS_len(&renegotiated_connection) != expected_len) {
1004    OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_MISMATCH);
1005    *out_alert = SSL_AD_HANDSHAKE_FAILURE;
1006    return 0;
1007  }
1008
1009  const uint8_t *d = CBS_data(&renegotiated_connection);
1010  if (CRYPTO_memcmp(d, ssl->s3->previous_client_finished,
1011        ssl->s3->previous_client_finished_len)) {
1012    OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_MISMATCH);
1013    *out_alert = SSL_AD_HANDSHAKE_FAILURE;
1014    return 0;
1015  }
1016  d += ssl->s3->previous_client_finished_len;
1017
1018  if (CRYPTO_memcmp(d, ssl->s3->previous_server_finished,
1019        ssl->s3->previous_server_finished_len)) {
1020    OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_MISMATCH);
1021    *out_alert = SSL_AD_ILLEGAL_PARAMETER;
1022    return 0;
1023  }
1024  ssl->s3->send_connection_binding = 1;
1025
1026  return 1;
1027}
1028
1029static int ext_ri_parse_clienthello(SSL *ssl, uint8_t *out_alert,
1030                                    CBS *contents) {
1031  /* Renegotiation isn't supported as a server so this function should never be
1032   * called after the initial handshake. */
1033  assert(!ssl->s3->initial_handshake_complete);
1034
1035  CBS fake_contents;
1036  static const uint8_t kFakeExtension[] = {0};
1037
1038  if (contents == NULL) {
1039    if (ssl->s3->send_connection_binding) {
1040      /* The renegotiation SCSV was received so pretend that we received a
1041       * renegotiation extension. */
1042      CBS_init(&fake_contents, kFakeExtension, sizeof(kFakeExtension));
1043      contents = &fake_contents;
1044      /* We require that the renegotiation extension is at index zero of
1045       * kExtensions. */
1046      ssl->s3->tmp.extensions.received |= (1u << 0);
1047    } else {
1048      return 1;
1049    }
1050  }
1051
1052  CBS renegotiated_connection;
1053
1054  if (!CBS_get_u8_length_prefixed(contents, &renegotiated_connection) ||
1055      CBS_len(contents) != 0) {
1056    OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_ENCODING_ERR);
1057    return 0;
1058  }
1059
1060  /* Check that the extension matches */
1061  if (!CBS_mem_equal(&renegotiated_connection, ssl->s3->previous_client_finished,
1062                     ssl->s3->previous_client_finished_len)) {
1063    OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_MISMATCH);
1064    *out_alert = SSL_AD_HANDSHAKE_FAILURE;
1065    return 0;
1066  }
1067
1068  ssl->s3->send_connection_binding = 1;
1069
1070  return 1;
1071}
1072
1073static int ext_ri_add_serverhello(SSL *ssl, CBB *out) {
1074  CBB contents, prev_finished;
1075  if (!CBB_add_u16(out, TLSEXT_TYPE_renegotiate) ||
1076      !CBB_add_u16_length_prefixed(out, &contents) ||
1077      !CBB_add_u8_length_prefixed(&contents, &prev_finished) ||
1078      !CBB_add_bytes(&prev_finished, ssl->s3->previous_client_finished,
1079                     ssl->s3->previous_client_finished_len) ||
1080      !CBB_add_bytes(&prev_finished, ssl->s3->previous_server_finished,
1081                     ssl->s3->previous_server_finished_len) ||
1082      !CBB_flush(out)) {
1083    return 0;
1084  }
1085
1086  return 1;
1087}
1088
1089
1090/* Extended Master Secret.
1091 *
1092 * https://tools.ietf.org/html/draft-ietf-tls-session-hash-05 */
1093
1094static void ext_ems_init(SSL *ssl) {
1095  ssl->s3->tmp.extended_master_secret = 0;
1096}
1097
1098static int ext_ems_add_clienthello(SSL *ssl, CBB *out) {
1099  if (ssl->version == SSL3_VERSION) {
1100    return 1;
1101  }
1102
1103  if (!CBB_add_u16(out, TLSEXT_TYPE_extended_master_secret) ||
1104      !CBB_add_u16(out, 0 /* length */)) {
1105    return 0;
1106  }
1107
1108  return 1;
1109}
1110
1111static int ext_ems_parse_serverhello(SSL *ssl, uint8_t *out_alert,
1112                                     CBS *contents) {
1113  if (contents == NULL) {
1114    return 1;
1115  }
1116
1117  if (ssl->version == SSL3_VERSION || CBS_len(contents) != 0) {
1118    return 0;
1119  }
1120
1121  ssl->s3->tmp.extended_master_secret = 1;
1122  return 1;
1123}
1124
1125static int ext_ems_parse_clienthello(SSL *ssl, uint8_t *out_alert, CBS *contents) {
1126  if (ssl->version == SSL3_VERSION || contents == NULL) {
1127    return 1;
1128  }
1129
1130  if (CBS_len(contents) != 0) {
1131    return 0;
1132  }
1133
1134  ssl->s3->tmp.extended_master_secret = 1;
1135  return 1;
1136}
1137
1138static int ext_ems_add_serverhello(SSL *ssl, CBB *out) {
1139  if (!ssl->s3->tmp.extended_master_secret) {
1140    return 1;
1141  }
1142
1143  if (!CBB_add_u16(out, TLSEXT_TYPE_extended_master_secret) ||
1144      !CBB_add_u16(out, 0 /* length */)) {
1145    return 0;
1146  }
1147
1148  return 1;
1149}
1150
1151
1152/* Session tickets.
1153 *
1154 * https://tools.ietf.org/html/rfc5077 */
1155
1156static int ext_ticket_add_clienthello(SSL *ssl, CBB *out) {
1157  if (SSL_get_options(ssl) & SSL_OP_NO_TICKET) {
1158    return 1;
1159  }
1160
1161  const uint8_t *ticket_data = NULL;
1162  int ticket_len = 0;
1163
1164  /* Renegotiation does not participate in session resumption. However, still
1165   * advertise the extension to avoid potentially breaking servers which carry
1166   * over the state from the previous handshake, such as OpenSSL servers
1167   * without upstream's 3c3f0259238594d77264a78944d409f2127642c4. */
1168  if (!ssl->s3->initial_handshake_complete &&
1169      ssl->session != NULL &&
1170      ssl->session->tlsext_tick != NULL) {
1171    ticket_data = ssl->session->tlsext_tick;
1172    ticket_len = ssl->session->tlsext_ticklen;
1173  }
1174
1175  CBB ticket;
1176  if (!CBB_add_u16(out, TLSEXT_TYPE_session_ticket) ||
1177      !CBB_add_u16_length_prefixed(out, &ticket) ||
1178      !CBB_add_bytes(&ticket, ticket_data, ticket_len) ||
1179      !CBB_flush(out)) {
1180    return 0;
1181  }
1182
1183  return 1;
1184}
1185
1186static int ext_ticket_parse_serverhello(SSL *ssl, uint8_t *out_alert,
1187                                        CBS *contents) {
1188  ssl->tlsext_ticket_expected = 0;
1189
1190  if (contents == NULL) {
1191    return 1;
1192  }
1193
1194  /* If |SSL_OP_NO_TICKET| is set then no extension will have been sent and
1195   * this function should never be called, even if the server tries to send the
1196   * extension. */
1197  assert((SSL_get_options(ssl) & SSL_OP_NO_TICKET) == 0);
1198
1199  if (CBS_len(contents) != 0) {
1200    return 0;
1201  }
1202
1203  ssl->tlsext_ticket_expected = 1;
1204  return 1;
1205}
1206
1207static int ext_ticket_parse_clienthello(SSL *ssl, uint8_t *out_alert, CBS *contents) {
1208  /* This function isn't used because the ticket extension from the client is
1209   * handled in ssl_session.c. */
1210  return 1;
1211}
1212
1213static int ext_ticket_add_serverhello(SSL *ssl, CBB *out) {
1214  if (!ssl->tlsext_ticket_expected) {
1215    return 1;
1216  }
1217
1218  /* If |SSL_OP_NO_TICKET| is set, |tlsext_ticket_expected| should never be
1219   * true. */
1220  assert((SSL_get_options(ssl) & SSL_OP_NO_TICKET) == 0);
1221
1222  if (!CBB_add_u16(out, TLSEXT_TYPE_session_ticket) ||
1223      !CBB_add_u16(out, 0 /* length */)) {
1224    return 0;
1225  }
1226
1227  return 1;
1228}
1229
1230
1231/* Signature Algorithms.
1232 *
1233 * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
1234
1235static int ext_sigalgs_add_clienthello(SSL *ssl, CBB *out) {
1236  if (ssl3_version_from_wire(ssl, ssl->client_version) < TLS1_2_VERSION) {
1237    return 1;
1238  }
1239
1240  const uint8_t *sigalgs_data;
1241  const size_t sigalgs_len = tls12_get_psigalgs(ssl, &sigalgs_data);
1242
1243  CBB contents, sigalgs;
1244  if (!CBB_add_u16(out, TLSEXT_TYPE_signature_algorithms) ||
1245      !CBB_add_u16_length_prefixed(out, &contents) ||
1246      !CBB_add_u16_length_prefixed(&contents, &sigalgs) ||
1247      !CBB_add_bytes(&sigalgs, sigalgs_data, sigalgs_len) ||
1248      !CBB_flush(out)) {
1249    return 0;
1250  }
1251
1252  return 1;
1253}
1254
1255static int ext_sigalgs_parse_serverhello(SSL *ssl, uint8_t *out_alert,
1256                                         CBS *contents) {
1257  if (contents != NULL) {
1258    /* Servers MUST NOT send this extension. */
1259    *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
1260    OPENSSL_PUT_ERROR(SSL, SSL_R_SIGNATURE_ALGORITHMS_EXTENSION_SENT_BY_SERVER);
1261    return 0;
1262  }
1263
1264  return 1;
1265}
1266
1267static int ext_sigalgs_parse_clienthello(SSL *ssl, uint8_t *out_alert,
1268                                         CBS *contents) {
1269  OPENSSL_free(ssl->cert->peer_sigalgs);
1270  ssl->cert->peer_sigalgs = NULL;
1271  ssl->cert->peer_sigalgslen = 0;
1272
1273  if (contents == NULL) {
1274    return 1;
1275  }
1276
1277  CBS supported_signature_algorithms;
1278  if (!CBS_get_u16_length_prefixed(contents, &supported_signature_algorithms) ||
1279      CBS_len(contents) != 0 ||
1280      CBS_len(&supported_signature_algorithms) == 0 ||
1281      !tls1_parse_peer_sigalgs(ssl, &supported_signature_algorithms)) {
1282    return 0;
1283  }
1284
1285  return 1;
1286}
1287
1288static int ext_sigalgs_add_serverhello(SSL *ssl, CBB *out) {
1289  /* Servers MUST NOT send this extension. */
1290  return 1;
1291}
1292
1293
1294/* OCSP Stapling.
1295 *
1296 * https://tools.ietf.org/html/rfc6066#section-8 */
1297
1298static void ext_ocsp_init(SSL *ssl) {
1299  ssl->s3->tmp.certificate_status_expected = 0;
1300}
1301
1302static int ext_ocsp_add_clienthello(SSL *ssl, CBB *out) {
1303  if (!ssl->ocsp_stapling_enabled) {
1304    return 1;
1305  }
1306
1307  CBB contents;
1308  if (!CBB_add_u16(out, TLSEXT_TYPE_status_request) ||
1309      !CBB_add_u16_length_prefixed(out, &contents) ||
1310      !CBB_add_u8(&contents, TLSEXT_STATUSTYPE_ocsp) ||
1311      !CBB_add_u16(&contents, 0 /* empty responder ID list */) ||
1312      !CBB_add_u16(&contents, 0 /* empty request extensions */) ||
1313      !CBB_flush(out)) {
1314    return 0;
1315  }
1316
1317  return 1;
1318}
1319
1320static int ext_ocsp_parse_serverhello(SSL *ssl, uint8_t *out_alert,
1321                                      CBS *contents) {
1322  if (contents == NULL) {
1323    return 1;
1324  }
1325
1326  if (CBS_len(contents) != 0) {
1327    return 0;
1328  }
1329
1330  ssl->s3->tmp.certificate_status_expected = 1;
1331  return 1;
1332}
1333
1334static int ext_ocsp_parse_clienthello(SSL *ssl, uint8_t *out_alert,
1335                                      CBS *contents) {
1336  if (contents == NULL) {
1337    return 1;
1338  }
1339
1340  uint8_t status_type;
1341  if (!CBS_get_u8(contents, &status_type)) {
1342    return 0;
1343  }
1344
1345  /* We cannot decide whether OCSP stapling will occur yet because the correct
1346   * SSL_CTX might not have been selected. */
1347  ssl->s3->tmp.ocsp_stapling_requested = status_type == TLSEXT_STATUSTYPE_ocsp;
1348
1349  return 1;
1350}
1351
1352static int ext_ocsp_add_serverhello(SSL *ssl, CBB *out) {
1353  /* The extension shouldn't be sent when resuming sessions. */
1354  if (ssl->hit ||
1355      !ssl->s3->tmp.ocsp_stapling_requested ||
1356      ssl->ctx->ocsp_response_length == 0) {
1357    return 1;
1358  }
1359
1360  ssl->s3->tmp.certificate_status_expected = 1;
1361
1362  return CBB_add_u16(out, TLSEXT_TYPE_status_request) &&
1363         CBB_add_u16(out, 0 /* length */);
1364}
1365
1366
1367/* Next protocol negotiation.
1368 *
1369 * https://htmlpreview.github.io/?https://github.com/agl/technotes/blob/master/nextprotoneg.html */
1370
1371static void ext_npn_init(SSL *ssl) {
1372  ssl->s3->next_proto_neg_seen = 0;
1373}
1374
1375static int ext_npn_add_clienthello(SSL *ssl, CBB *out) {
1376  if (ssl->s3->initial_handshake_complete ||
1377      ssl->ctx->next_proto_select_cb == NULL ||
1378      (ssl->options & SSL_OP_DISABLE_NPN) ||
1379      SSL_IS_DTLS(ssl)) {
1380    return 1;
1381  }
1382
1383  if (!CBB_add_u16(out, TLSEXT_TYPE_next_proto_neg) ||
1384      !CBB_add_u16(out, 0 /* length */)) {
1385    return 0;
1386  }
1387
1388  return 1;
1389}
1390
1391static int ext_npn_parse_serverhello(SSL *ssl, uint8_t *out_alert,
1392                                     CBS *contents) {
1393  if (contents == NULL) {
1394    return 1;
1395  }
1396
1397  /* If any of these are false then we should never have sent the NPN
1398   * extension in the ClientHello and thus this function should never have been
1399   * called. */
1400  assert(!ssl->s3->initial_handshake_complete);
1401  assert(!SSL_IS_DTLS(ssl));
1402  assert(ssl->ctx->next_proto_select_cb != NULL);
1403  assert(!(ssl->options & SSL_OP_DISABLE_NPN));
1404
1405  if (ssl->s3->alpn_selected != NULL) {
1406    /* NPN and ALPN may not be negotiated in the same connection. */
1407    *out_alert = SSL_AD_ILLEGAL_PARAMETER;
1408    OPENSSL_PUT_ERROR(SSL, SSL_R_NEGOTIATED_BOTH_NPN_AND_ALPN);
1409    return 0;
1410  }
1411
1412  const uint8_t *const orig_contents = CBS_data(contents);
1413  const size_t orig_len = CBS_len(contents);
1414
1415  while (CBS_len(contents) != 0) {
1416    CBS proto;
1417    if (!CBS_get_u8_length_prefixed(contents, &proto) ||
1418        CBS_len(&proto) == 0) {
1419      return 0;
1420    }
1421  }
1422
1423  uint8_t *selected;
1424  uint8_t selected_len;
1425  if (ssl->ctx->next_proto_select_cb(
1426          ssl, &selected, &selected_len, orig_contents, orig_len,
1427          ssl->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK) {
1428    *out_alert = SSL_AD_INTERNAL_ERROR;
1429    return 0;
1430  }
1431
1432  OPENSSL_free(ssl->next_proto_negotiated);
1433  ssl->next_proto_negotiated = BUF_memdup(selected, selected_len);
1434  if (ssl->next_proto_negotiated == NULL) {
1435    *out_alert = SSL_AD_INTERNAL_ERROR;
1436    return 0;
1437  }
1438
1439  ssl->next_proto_negotiated_len = selected_len;
1440  ssl->s3->next_proto_neg_seen = 1;
1441
1442  return 1;
1443}
1444
1445static int ext_npn_parse_clienthello(SSL *ssl, uint8_t *out_alert,
1446                                     CBS *contents) {
1447  if (contents != NULL && CBS_len(contents) != 0) {
1448    return 0;
1449  }
1450
1451  if (contents == NULL ||
1452      ssl->s3->initial_handshake_complete ||
1453      /* If the ALPN extension is seen before NPN, ignore it. (If ALPN is seen
1454       * afterwards, parsing the ALPN extension will clear
1455       * |next_proto_neg_seen|. */
1456      ssl->s3->alpn_selected != NULL ||
1457      ssl->ctx->next_protos_advertised_cb == NULL ||
1458      SSL_IS_DTLS(ssl)) {
1459    return 1;
1460  }
1461
1462  ssl->s3->next_proto_neg_seen = 1;
1463  return 1;
1464}
1465
1466static int ext_npn_add_serverhello(SSL *ssl, CBB *out) {
1467  /* |next_proto_neg_seen| might have been cleared when an ALPN extension was
1468   * parsed. */
1469  if (!ssl->s3->next_proto_neg_seen) {
1470    return 1;
1471  }
1472
1473  const uint8_t *npa;
1474  unsigned npa_len;
1475
1476  if (ssl->ctx->next_protos_advertised_cb(
1477          ssl, &npa, &npa_len, ssl->ctx->next_protos_advertised_cb_arg) !=
1478      SSL_TLSEXT_ERR_OK) {
1479    ssl->s3->next_proto_neg_seen = 0;
1480    return 1;
1481  }
1482
1483  CBB contents;
1484  if (!CBB_add_u16(out, TLSEXT_TYPE_next_proto_neg) ||
1485      !CBB_add_u16_length_prefixed(out, &contents) ||
1486      !CBB_add_bytes(&contents, npa, npa_len) ||
1487      !CBB_flush(out)) {
1488    return 0;
1489  }
1490
1491  return 1;
1492}
1493
1494
1495/* Signed certificate timestamps.
1496 *
1497 * https://tools.ietf.org/html/rfc6962#section-3.3.1 */
1498
1499static int ext_sct_add_clienthello(SSL *ssl, CBB *out) {
1500  if (!ssl->signed_cert_timestamps_enabled) {
1501    return 1;
1502  }
1503
1504  if (!CBB_add_u16(out, TLSEXT_TYPE_certificate_timestamp) ||
1505      !CBB_add_u16(out, 0 /* length */)) {
1506    return 0;
1507  }
1508
1509  return 1;
1510}
1511
1512static int ext_sct_parse_serverhello(SSL *ssl, uint8_t *out_alert,
1513                                     CBS *contents) {
1514  if (contents == NULL) {
1515    return 1;
1516  }
1517
1518  /* If this is false then we should never have sent the SCT extension in the
1519   * ClientHello and thus this function should never have been called. */
1520  assert(ssl->signed_cert_timestamps_enabled);
1521
1522  if (CBS_len(contents) == 0) {
1523    *out_alert = SSL_AD_DECODE_ERROR;
1524    return 0;
1525  }
1526
1527  /* Session resumption uses the original session information. */
1528  if (!ssl->hit &&
1529      !CBS_stow(contents, &ssl->session->tlsext_signed_cert_timestamp_list,
1530                &ssl->session->tlsext_signed_cert_timestamp_list_length)) {
1531    *out_alert = SSL_AD_INTERNAL_ERROR;
1532    return 0;
1533  }
1534
1535  return 1;
1536}
1537
1538static int ext_sct_parse_clienthello(SSL *ssl, uint8_t *out_alert,
1539                                     CBS *contents) {
1540  return contents == NULL || CBS_len(contents) == 0;
1541}
1542
1543static int ext_sct_add_serverhello(SSL *ssl, CBB *out) {
1544  /* The extension shouldn't be sent when resuming sessions. */
1545  if (ssl->hit ||
1546      ssl->ctx->signed_cert_timestamp_list_length == 0) {
1547    return 1;
1548  }
1549
1550  CBB contents;
1551  return CBB_add_u16(out, TLSEXT_TYPE_certificate_timestamp) &&
1552         CBB_add_u16_length_prefixed(out, &contents) &&
1553         CBB_add_bytes(&contents, ssl->ctx->signed_cert_timestamp_list,
1554                       ssl->ctx->signed_cert_timestamp_list_length) &&
1555         CBB_flush(out);
1556}
1557
1558
1559/* Application-level Protocol Negotiation.
1560 *
1561 * https://tools.ietf.org/html/rfc7301 */
1562
1563static void ext_alpn_init(SSL *ssl) {
1564  OPENSSL_free(ssl->s3->alpn_selected);
1565  ssl->s3->alpn_selected = NULL;
1566}
1567
1568static int ext_alpn_add_clienthello(SSL *ssl, CBB *out) {
1569  if (ssl->alpn_client_proto_list == NULL ||
1570      ssl->s3->initial_handshake_complete) {
1571    return 1;
1572  }
1573
1574  CBB contents, proto_list;
1575  if (!CBB_add_u16(out, TLSEXT_TYPE_application_layer_protocol_negotiation) ||
1576      !CBB_add_u16_length_prefixed(out, &contents) ||
1577      !CBB_add_u16_length_prefixed(&contents, &proto_list) ||
1578      !CBB_add_bytes(&proto_list, ssl->alpn_client_proto_list,
1579                     ssl->alpn_client_proto_list_len) ||
1580      !CBB_flush(out)) {
1581    return 0;
1582  }
1583
1584  return 1;
1585}
1586
1587static int ext_alpn_parse_serverhello(SSL *ssl, uint8_t *out_alert,
1588                                      CBS *contents) {
1589  if (contents == NULL) {
1590    return 1;
1591  }
1592
1593  assert(!ssl->s3->initial_handshake_complete);
1594  assert(ssl->alpn_client_proto_list != NULL);
1595
1596  if (ssl->s3->next_proto_neg_seen) {
1597    /* NPN and ALPN may not be negotiated in the same connection. */
1598    *out_alert = SSL_AD_ILLEGAL_PARAMETER;
1599    OPENSSL_PUT_ERROR(SSL, SSL_R_NEGOTIATED_BOTH_NPN_AND_ALPN);
1600    return 0;
1601  }
1602
1603  /* The extension data consists of a ProtocolNameList which must have
1604   * exactly one ProtocolName. Each of these is length-prefixed. */
1605  CBS protocol_name_list, protocol_name;
1606  if (!CBS_get_u16_length_prefixed(contents, &protocol_name_list) ||
1607      CBS_len(contents) != 0 ||
1608      !CBS_get_u8_length_prefixed(&protocol_name_list, &protocol_name) ||
1609      /* Empty protocol names are forbidden. */
1610      CBS_len(&protocol_name) == 0 ||
1611      CBS_len(&protocol_name_list) != 0) {
1612    return 0;
1613  }
1614
1615  if (!CBS_stow(&protocol_name, &ssl->s3->alpn_selected,
1616                &ssl->s3->alpn_selected_len)) {
1617    *out_alert = SSL_AD_INTERNAL_ERROR;
1618    return 0;
1619  }
1620
1621  return 1;
1622}
1623
1624static int ext_alpn_parse_clienthello(SSL *ssl, uint8_t *out_alert,
1625                                      CBS *contents) {
1626  if (contents == NULL) {
1627    return 1;
1628  }
1629
1630  if (ssl->ctx->alpn_select_cb == NULL ||
1631      ssl->s3->initial_handshake_complete) {
1632    return 1;
1633  }
1634
1635  /* ALPN takes precedence over NPN. */
1636  ssl->s3->next_proto_neg_seen = 0;
1637
1638  CBS protocol_name_list;
1639  if (!CBS_get_u16_length_prefixed(contents, &protocol_name_list) ||
1640      CBS_len(contents) != 0 ||
1641      CBS_len(&protocol_name_list) < 2) {
1642    return 0;
1643  }
1644
1645  /* Validate the protocol list. */
1646  CBS protocol_name_list_copy = protocol_name_list;
1647  while (CBS_len(&protocol_name_list_copy) > 0) {
1648    CBS protocol_name;
1649
1650    if (!CBS_get_u8_length_prefixed(&protocol_name_list_copy, &protocol_name) ||
1651        /* Empty protocol names are forbidden. */
1652        CBS_len(&protocol_name) == 0) {
1653      return 0;
1654    }
1655  }
1656
1657  const uint8_t *selected;
1658  uint8_t selected_len;
1659  if (ssl->ctx->alpn_select_cb(
1660          ssl, &selected, &selected_len, CBS_data(&protocol_name_list),
1661          CBS_len(&protocol_name_list),
1662          ssl->ctx->alpn_select_cb_arg) == SSL_TLSEXT_ERR_OK) {
1663    OPENSSL_free(ssl->s3->alpn_selected);
1664    ssl->s3->alpn_selected = BUF_memdup(selected, selected_len);
1665    if (ssl->s3->alpn_selected == NULL) {
1666      *out_alert = SSL_AD_INTERNAL_ERROR;
1667      return 0;
1668    }
1669    ssl->s3->alpn_selected_len = selected_len;
1670  }
1671
1672  return 1;
1673}
1674
1675static int ext_alpn_add_serverhello(SSL *ssl, CBB *out) {
1676  if (ssl->s3->alpn_selected == NULL) {
1677    return 1;
1678  }
1679
1680  CBB contents, proto_list, proto;
1681  if (!CBB_add_u16(out, TLSEXT_TYPE_application_layer_protocol_negotiation) ||
1682      !CBB_add_u16_length_prefixed(out, &contents) ||
1683      !CBB_add_u16_length_prefixed(&contents, &proto_list) ||
1684      !CBB_add_u8_length_prefixed(&proto_list, &proto) ||
1685      !CBB_add_bytes(&proto, ssl->s3->alpn_selected, ssl->s3->alpn_selected_len) ||
1686      !CBB_flush(out)) {
1687    return 0;
1688  }
1689
1690  return 1;
1691}
1692
1693
1694/* Channel ID.
1695 *
1696 * https://tools.ietf.org/html/draft-balfanz-tls-channelid-01 */
1697
1698static void ext_channel_id_init(SSL *ssl) {
1699  ssl->s3->tlsext_channel_id_valid = 0;
1700}
1701
1702static int ext_channel_id_add_clienthello(SSL *ssl, CBB *out) {
1703  if (!ssl->tlsext_channel_id_enabled ||
1704      SSL_IS_DTLS(ssl)) {
1705    return 1;
1706  }
1707
1708  if (!CBB_add_u16(out, TLSEXT_TYPE_channel_id) ||
1709      !CBB_add_u16(out, 0 /* length */)) {
1710    return 0;
1711  }
1712
1713  return 1;
1714}
1715
1716static int ext_channel_id_parse_serverhello(SSL *ssl, uint8_t *out_alert,
1717                                            CBS *contents) {
1718  if (contents == NULL) {
1719    return 1;
1720  }
1721
1722  assert(!SSL_IS_DTLS(ssl));
1723  assert(ssl->tlsext_channel_id_enabled);
1724
1725  if (CBS_len(contents) != 0) {
1726    return 0;
1727  }
1728
1729  ssl->s3->tlsext_channel_id_valid = 1;
1730  return 1;
1731}
1732
1733static int ext_channel_id_parse_clienthello(SSL *ssl, uint8_t *out_alert,
1734                                            CBS *contents) {
1735  if (contents == NULL ||
1736      !ssl->tlsext_channel_id_enabled ||
1737      SSL_IS_DTLS(ssl)) {
1738    return 1;
1739  }
1740
1741  if (CBS_len(contents) != 0) {
1742    return 0;
1743  }
1744
1745  ssl->s3->tlsext_channel_id_valid = 1;
1746  return 1;
1747}
1748
1749static int ext_channel_id_add_serverhello(SSL *ssl, CBB *out) {
1750  if (!ssl->s3->tlsext_channel_id_valid) {
1751    return 1;
1752  }
1753
1754  if (!CBB_add_u16(out, TLSEXT_TYPE_channel_id) ||
1755      !CBB_add_u16(out, 0 /* length */)) {
1756    return 0;
1757  }
1758
1759  return 1;
1760}
1761
1762
1763/* Secure Real-time Transport Protocol (SRTP) extension.
1764 *
1765 * https://tools.ietf.org/html/rfc5764 */
1766
1767
1768static void ext_srtp_init(SSL *ssl) {
1769  ssl->srtp_profile = NULL;
1770}
1771
1772static int ext_srtp_add_clienthello(SSL *ssl, CBB *out) {
1773  STACK_OF(SRTP_PROTECTION_PROFILE) *profiles = SSL_get_srtp_profiles(ssl);
1774  if (profiles == NULL) {
1775    return 1;
1776  }
1777  const size_t num_profiles = sk_SRTP_PROTECTION_PROFILE_num(profiles);
1778  if (num_profiles == 0) {
1779    return 1;
1780  }
1781
1782  CBB contents, profile_ids;
1783  if (!CBB_add_u16(out, TLSEXT_TYPE_srtp) ||
1784      !CBB_add_u16_length_prefixed(out, &contents) ||
1785      !CBB_add_u16_length_prefixed(&contents, &profile_ids)) {
1786    return 0;
1787  }
1788
1789  size_t i;
1790  for (i = 0; i < num_profiles; i++) {
1791    if (!CBB_add_u16(&profile_ids,
1792                     sk_SRTP_PROTECTION_PROFILE_value(profiles, i)->id)) {
1793      return 0;
1794    }
1795  }
1796
1797  if (!CBB_add_u8(&contents, 0 /* empty use_mki value */) ||
1798      !CBB_flush(out)) {
1799    return 0;
1800  }
1801
1802  return 1;
1803}
1804
1805static int ext_srtp_parse_serverhello(SSL *ssl, uint8_t *out_alert,
1806                                      CBS *contents) {
1807  if (contents == NULL) {
1808    return 1;
1809  }
1810
1811  /* The extension consists of a u16-prefixed profile ID list containing a
1812   * single uint16_t profile ID, then followed by a u8-prefixed srtp_mki field.
1813   *
1814   * See https://tools.ietf.org/html/rfc5764#section-4.1.1 */
1815  CBS profile_ids, srtp_mki;
1816  uint16_t profile_id;
1817  if (!CBS_get_u16_length_prefixed(contents, &profile_ids) ||
1818      !CBS_get_u16(&profile_ids, &profile_id) ||
1819      CBS_len(&profile_ids) != 0 ||
1820      !CBS_get_u8_length_prefixed(contents, &srtp_mki) ||
1821      CBS_len(contents) != 0) {
1822    OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
1823    return 0;
1824  }
1825
1826  if (CBS_len(&srtp_mki) != 0) {
1827    /* Must be no MKI, since we never offer one. */
1828    OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SRTP_MKI_VALUE);
1829    *out_alert = SSL_AD_ILLEGAL_PARAMETER;
1830    return 0;
1831  }
1832
1833  STACK_OF(SRTP_PROTECTION_PROFILE) *profiles = SSL_get_srtp_profiles(ssl);
1834
1835  /* Check to see if the server gave us something we support (and presumably
1836   * offered). */
1837  size_t i;
1838  for (i = 0; i < sk_SRTP_PROTECTION_PROFILE_num(profiles); i++) {
1839    const SRTP_PROTECTION_PROFILE *profile =
1840        sk_SRTP_PROTECTION_PROFILE_value(profiles, i);
1841
1842    if (profile->id == profile_id) {
1843      ssl->srtp_profile = profile;
1844      return 1;
1845    }
1846  }
1847
1848  OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
1849  *out_alert = SSL_AD_ILLEGAL_PARAMETER;
1850  return 0;
1851}
1852
1853static int ext_srtp_parse_clienthello(SSL *ssl, uint8_t *out_alert,
1854                                      CBS *contents) {
1855  if (contents == NULL) {
1856    return 1;
1857  }
1858
1859  CBS profile_ids, srtp_mki;
1860  if (!CBS_get_u16_length_prefixed(contents, &profile_ids) ||
1861      CBS_len(&profile_ids) < 2 ||
1862      !CBS_get_u8_length_prefixed(contents, &srtp_mki) ||
1863      CBS_len(contents) != 0) {
1864    OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
1865    return 0;
1866  }
1867  /* Discard the MKI value for now. */
1868
1869  const STACK_OF(SRTP_PROTECTION_PROFILE) *server_profiles =
1870      SSL_get_srtp_profiles(ssl);
1871
1872  /* Pick the server's most preferred profile. */
1873  size_t i;
1874  for (i = 0; i < sk_SRTP_PROTECTION_PROFILE_num(server_profiles); i++) {
1875    const SRTP_PROTECTION_PROFILE *server_profile =
1876        sk_SRTP_PROTECTION_PROFILE_value(server_profiles, i);
1877
1878    CBS profile_ids_tmp;
1879    CBS_init(&profile_ids_tmp, CBS_data(&profile_ids), CBS_len(&profile_ids));
1880
1881    while (CBS_len(&profile_ids_tmp) > 0) {
1882      uint16_t profile_id;
1883      if (!CBS_get_u16(&profile_ids_tmp, &profile_id)) {
1884        return 0;
1885      }
1886
1887      if (server_profile->id == profile_id) {
1888        ssl->srtp_profile = server_profile;
1889        return 1;
1890      }
1891    }
1892  }
1893
1894  return 1;
1895}
1896
1897static int ext_srtp_add_serverhello(SSL *ssl, CBB *out) {
1898  if (ssl->srtp_profile == NULL) {
1899    return 1;
1900  }
1901
1902  CBB contents, profile_ids;
1903  if (!CBB_add_u16(out, TLSEXT_TYPE_srtp) ||
1904      !CBB_add_u16_length_prefixed(out, &contents) ||
1905      !CBB_add_u16_length_prefixed(&contents, &profile_ids) ||
1906      !CBB_add_u16(&profile_ids, ssl->srtp_profile->id) ||
1907      !CBB_add_u8(&contents, 0 /* empty MKI */) ||
1908      !CBB_flush(out)) {
1909    return 0;
1910  }
1911
1912  return 1;
1913}
1914
1915
1916/* EC point formats.
1917 *
1918 * https://tools.ietf.org/html/rfc4492#section-5.1.2 */
1919
1920static int ssl_any_ec_cipher_suites_enabled(const SSL *ssl) {
1921  if (ssl->version < TLS1_VERSION && !SSL_IS_DTLS(ssl)) {
1922    return 0;
1923  }
1924
1925  const STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(ssl);
1926
1927  size_t i;
1928  for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++) {
1929    const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(cipher_stack, i);
1930
1931    const uint32_t alg_k = cipher->algorithm_mkey;
1932    const uint32_t alg_a = cipher->algorithm_auth;
1933    if ((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA)) {
1934      return 1;
1935    }
1936  }
1937
1938  return 0;
1939}
1940
1941static int ext_ec_point_add_extension(SSL *ssl, CBB *out) {
1942  CBB contents, formats;
1943  if (!CBB_add_u16(out, TLSEXT_TYPE_ec_point_formats) ||
1944      !CBB_add_u16_length_prefixed(out, &contents) ||
1945      !CBB_add_u8_length_prefixed(&contents, &formats) ||
1946      !CBB_add_u8(&formats, TLSEXT_ECPOINTFORMAT_uncompressed) ||
1947      !CBB_flush(out)) {
1948    return 0;
1949  }
1950
1951  return 1;
1952}
1953
1954static int ext_ec_point_add_clienthello(SSL *ssl, CBB *out) {
1955  if (!ssl_any_ec_cipher_suites_enabled(ssl)) {
1956    return 1;
1957  }
1958
1959  return ext_ec_point_add_extension(ssl, out);
1960}
1961
1962static int ext_ec_point_parse_serverhello(SSL *ssl, uint8_t *out_alert,
1963                                          CBS *contents) {
1964  if (contents == NULL) {
1965    return 1;
1966  }
1967
1968  CBS ec_point_format_list;
1969  if (!CBS_get_u8_length_prefixed(contents, &ec_point_format_list) ||
1970      CBS_len(contents) != 0) {
1971    return 0;
1972  }
1973
1974  /* Per RFC 4492, section 5.1.2, implementations MUST support the uncompressed
1975   * point format. */
1976  if (memchr(CBS_data(&ec_point_format_list), TLSEXT_ECPOINTFORMAT_uncompressed,
1977             CBS_len(&ec_point_format_list)) == NULL) {
1978    *out_alert = SSL_AD_ILLEGAL_PARAMETER;
1979    return 0;
1980  }
1981
1982  return 1;
1983}
1984
1985static int ext_ec_point_parse_clienthello(SSL *ssl, uint8_t *out_alert,
1986                                          CBS *contents) {
1987  return ext_ec_point_parse_serverhello(ssl, out_alert, contents);
1988}
1989
1990static int ext_ec_point_add_serverhello(SSL *ssl, CBB *out) {
1991  const uint32_t alg_k = ssl->s3->tmp.new_cipher->algorithm_mkey;
1992  const uint32_t alg_a = ssl->s3->tmp.new_cipher->algorithm_auth;
1993  const int using_ecc = (alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA);
1994
1995  if (!using_ecc) {
1996    return 1;
1997  }
1998
1999  return ext_ec_point_add_extension(ssl, out);
2000}
2001
2002
2003/* EC supported curves.
2004 *
2005 * https://tools.ietf.org/html/rfc4492#section-5.1.2 */
2006
2007static void ext_ec_curves_init(SSL *ssl) {
2008  OPENSSL_free(ssl->s3->tmp.peer_ellipticcurvelist);
2009  ssl->s3->tmp.peer_ellipticcurvelist = NULL;
2010  ssl->s3->tmp.peer_ellipticcurvelist_length = 0;
2011}
2012
2013static int ext_ec_curves_add_clienthello(SSL *ssl, CBB *out) {
2014  if (!ssl_any_ec_cipher_suites_enabled(ssl)) {
2015    return 1;
2016  }
2017
2018  CBB contents, curves_bytes;
2019  if (!CBB_add_u16(out, TLSEXT_TYPE_elliptic_curves) ||
2020      !CBB_add_u16_length_prefixed(out, &contents) ||
2021      !CBB_add_u16_length_prefixed(&contents, &curves_bytes)) {
2022    return 0;
2023  }
2024
2025  const uint16_t *curves;
2026  size_t curves_len;
2027  tls1_get_curvelist(ssl, 0, &curves, &curves_len);
2028
2029  size_t i;
2030  for (i = 0; i < curves_len; i++) {
2031    if (!CBB_add_u16(&curves_bytes, curves[i])) {
2032      return 0;
2033    }
2034  }
2035
2036  return CBB_flush(out);
2037}
2038
2039static int ext_ec_curves_parse_serverhello(SSL *ssl, uint8_t *out_alert,
2040                                           CBS *contents) {
2041  /* This extension is not expected to be echoed by servers and is ignored. */
2042  return 1;
2043}
2044
2045static int ext_ec_curves_parse_clienthello(SSL *ssl, uint8_t *out_alert,
2046                                           CBS *contents) {
2047  if (contents == NULL) {
2048    return 1;
2049  }
2050
2051  CBS elliptic_curve_list;
2052  if (!CBS_get_u16_length_prefixed(contents, &elliptic_curve_list) ||
2053      CBS_len(&elliptic_curve_list) == 0 ||
2054      (CBS_len(&elliptic_curve_list) & 1) != 0 ||
2055      CBS_len(contents) != 0) {
2056    return 0;
2057  }
2058
2059  ssl->s3->tmp.peer_ellipticcurvelist =
2060      (uint16_t *)OPENSSL_malloc(CBS_len(&elliptic_curve_list));
2061
2062  if (ssl->s3->tmp.peer_ellipticcurvelist == NULL) {
2063    *out_alert = SSL_AD_INTERNAL_ERROR;
2064    return 0;
2065  }
2066
2067  const size_t num_curves = CBS_len(&elliptic_curve_list) / 2;
2068  size_t i;
2069  for (i = 0; i < num_curves; i++) {
2070    if (!CBS_get_u16(&elliptic_curve_list,
2071                     &ssl->s3->tmp.peer_ellipticcurvelist[i])) {
2072      goto err;
2073    }
2074  }
2075
2076  assert(CBS_len(&elliptic_curve_list) == 0);
2077  ssl->s3->tmp.peer_ellipticcurvelist_length = num_curves;
2078
2079  return 1;
2080
2081err:
2082  OPENSSL_free(ssl->s3->tmp.peer_ellipticcurvelist);
2083  ssl->s3->tmp.peer_ellipticcurvelist = NULL;
2084  *out_alert = SSL_AD_INTERNAL_ERROR;
2085  return 0;
2086}
2087
2088static int ext_ec_curves_add_serverhello(SSL *ssl, CBB *out) {
2089  /* Servers don't echo this extension. */
2090  return 1;
2091}
2092
2093
2094/* kExtensions contains all the supported extensions. */
2095static const struct tls_extension kExtensions[] = {
2096  {
2097    /* The renegotiation extension must always be at index zero because the
2098     * |received| and |sent| bitsets need to be tweaked when the "extension" is
2099     * sent as an SCSV. */
2100    TLSEXT_TYPE_renegotiate,
2101    NULL,
2102    ext_ri_add_clienthello,
2103    ext_ri_parse_serverhello,
2104    ext_ri_parse_clienthello,
2105    ext_ri_add_serverhello,
2106  },
2107  {
2108    TLSEXT_TYPE_server_name,
2109    ext_sni_init,
2110    ext_sni_add_clienthello,
2111    ext_sni_parse_serverhello,
2112    ext_sni_parse_clienthello,
2113    ext_sni_add_serverhello,
2114  },
2115  {
2116    TLSEXT_TYPE_extended_master_secret,
2117    ext_ems_init,
2118    ext_ems_add_clienthello,
2119    ext_ems_parse_serverhello,
2120    ext_ems_parse_clienthello,
2121    ext_ems_add_serverhello,
2122  },
2123  {
2124    TLSEXT_TYPE_session_ticket,
2125    NULL,
2126    ext_ticket_add_clienthello,
2127    ext_ticket_parse_serverhello,
2128    ext_ticket_parse_clienthello,
2129    ext_ticket_add_serverhello,
2130  },
2131  {
2132    TLSEXT_TYPE_signature_algorithms,
2133    NULL,
2134    ext_sigalgs_add_clienthello,
2135    ext_sigalgs_parse_serverhello,
2136    ext_sigalgs_parse_clienthello,
2137    ext_sigalgs_add_serverhello,
2138  },
2139  {
2140    TLSEXT_TYPE_status_request,
2141    ext_ocsp_init,
2142    ext_ocsp_add_clienthello,
2143    ext_ocsp_parse_serverhello,
2144    ext_ocsp_parse_clienthello,
2145    ext_ocsp_add_serverhello,
2146  },
2147  {
2148    TLSEXT_TYPE_next_proto_neg,
2149    ext_npn_init,
2150    ext_npn_add_clienthello,
2151    ext_npn_parse_serverhello,
2152    ext_npn_parse_clienthello,
2153    ext_npn_add_serverhello,
2154  },
2155  {
2156    TLSEXT_TYPE_certificate_timestamp,
2157    NULL,
2158    ext_sct_add_clienthello,
2159    ext_sct_parse_serverhello,
2160    ext_sct_parse_clienthello,
2161    ext_sct_add_serverhello,
2162  },
2163  {
2164    TLSEXT_TYPE_application_layer_protocol_negotiation,
2165    ext_alpn_init,
2166    ext_alpn_add_clienthello,
2167    ext_alpn_parse_serverhello,
2168    ext_alpn_parse_clienthello,
2169    ext_alpn_add_serverhello,
2170  },
2171  {
2172    TLSEXT_TYPE_channel_id,
2173    ext_channel_id_init,
2174    ext_channel_id_add_clienthello,
2175    ext_channel_id_parse_serverhello,
2176    ext_channel_id_parse_clienthello,
2177    ext_channel_id_add_serverhello,
2178  },
2179  {
2180    TLSEXT_TYPE_srtp,
2181    ext_srtp_init,
2182    ext_srtp_add_clienthello,
2183    ext_srtp_parse_serverhello,
2184    ext_srtp_parse_clienthello,
2185    ext_srtp_add_serverhello,
2186  },
2187  {
2188    TLSEXT_TYPE_ec_point_formats,
2189    NULL,
2190    ext_ec_point_add_clienthello,
2191    ext_ec_point_parse_serverhello,
2192    ext_ec_point_parse_clienthello,
2193    ext_ec_point_add_serverhello,
2194  },
2195  {
2196    TLSEXT_TYPE_elliptic_curves,
2197    ext_ec_curves_init,
2198    ext_ec_curves_add_clienthello,
2199    ext_ec_curves_parse_serverhello,
2200    ext_ec_curves_parse_clienthello,
2201    ext_ec_curves_add_serverhello,
2202  },
2203};
2204
2205#define kNumExtensions (sizeof(kExtensions) / sizeof(struct tls_extension))
2206
2207OPENSSL_COMPILE_ASSERT(kNumExtensions <=
2208                           sizeof(((SSL *)NULL)->s3->tmp.extensions.sent) * 8,
2209                       too_many_extensions_for_sent_bitset);
2210OPENSSL_COMPILE_ASSERT(kNumExtensions <=
2211                           sizeof(((SSL *)NULL)->s3->tmp.extensions.received) *
2212                               8,
2213                       too_many_extensions_for_received_bitset);
2214
2215static const struct tls_extension *tls_extension_find(uint32_t *out_index,
2216                                                      uint16_t value) {
2217  unsigned i;
2218  for (i = 0; i < kNumExtensions; i++) {
2219    if (kExtensions[i].value == value) {
2220      *out_index = i;
2221      return &kExtensions[i];
2222    }
2223  }
2224
2225  return NULL;
2226}
2227
2228int SSL_extension_supported(unsigned extension_value) {
2229  uint32_t index;
2230  return extension_value == TLSEXT_TYPE_padding ||
2231         tls_extension_find(&index, extension_value) != NULL;
2232}
2233
2234int ssl_add_clienthello_tlsext(SSL *ssl, CBB *out, size_t header_len) {
2235  /* don't add extensions for SSLv3 unless doing secure renegotiation */
2236  if (ssl->client_version == SSL3_VERSION &&
2237      !ssl->s3->send_connection_binding) {
2238    return 1;
2239  }
2240
2241  size_t orig_len = CBB_len(out);
2242  CBB extensions;
2243  if (!CBB_add_u16_length_prefixed(out, &extensions)) {
2244    goto err;
2245  }
2246
2247  ssl->s3->tmp.extensions.sent = 0;
2248  ssl->s3->tmp.custom_extensions.sent = 0;
2249
2250  size_t i;
2251  for (i = 0; i < kNumExtensions; i++) {
2252    if (kExtensions[i].init != NULL) {
2253      kExtensions[i].init(ssl);
2254    }
2255  }
2256
2257  for (i = 0; i < kNumExtensions; i++) {
2258    const size_t len_before = CBB_len(&extensions);
2259    if (!kExtensions[i].add_clienthello(ssl, &extensions)) {
2260      OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_ADDING_EXTENSION);
2261      ERR_add_error_dataf("extension: %u", (unsigned)kExtensions[i].value);
2262      goto err;
2263    }
2264
2265    if (CBB_len(&extensions) != len_before) {
2266      ssl->s3->tmp.extensions.sent |= (1u << i);
2267    }
2268  }
2269
2270  if (!custom_ext_add_clienthello(ssl, &extensions)) {
2271    goto err;
2272  }
2273
2274  if (!SSL_IS_DTLS(ssl)) {
2275    header_len += CBB_len(&extensions) - orig_len;
2276    if (header_len > 0xff && header_len < 0x200) {
2277      /* Add padding to workaround bugs in F5 terminators. See RFC 7685.
2278       *
2279       * NB: because this code works out the length of all existing extensions
2280       * it MUST always appear last. */
2281      size_t padding_len = 0x200 - header_len;
2282      /* Extensions take at least four bytes to encode. Always include least
2283       * one byte of data if including the extension. WebSphere Application
2284       * Server 7.0 is intolerant to the last extension being zero-length. */
2285      if (padding_len >= 4 + 1) {
2286        padding_len -= 4;
2287      } else {
2288        padding_len = 1;
2289      }
2290
2291      uint8_t *padding_bytes;
2292      if (!CBB_add_u16(&extensions, TLSEXT_TYPE_padding) ||
2293          !CBB_add_u16(&extensions, padding_len) ||
2294          !CBB_add_space(&extensions, &padding_bytes, padding_len)) {
2295        goto err;
2296      }
2297
2298      memset(padding_bytes, 0, padding_len);
2299    }
2300  }
2301
2302  /* If only two bytes have been written then the extensions are actually empty
2303   * and those two bytes are the zero length. In that case, we don't bother
2304   * sending the extensions length. */
2305  if (CBB_len(&extensions) - orig_len == 2) {
2306    CBB_discard_child(out);
2307  }
2308
2309  return CBB_flush(out);
2310
2311err:
2312  OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
2313  return 0;
2314}
2315
2316int ssl_add_serverhello_tlsext(SSL *ssl, CBB *out) {
2317  const size_t orig_len = CBB_len(out);
2318
2319  CBB extensions;
2320  if (!CBB_add_u16_length_prefixed(out, &extensions)) {
2321    goto err;
2322  }
2323
2324  unsigned i;
2325  for (i = 0; i < kNumExtensions; i++) {
2326    if (!(ssl->s3->tmp.extensions.received & (1u << i))) {
2327      /* Don't send extensions that were not received. */
2328      continue;
2329    }
2330
2331    if (!kExtensions[i].add_serverhello(ssl, &extensions)) {
2332      OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_ADDING_EXTENSION);
2333      ERR_add_error_dataf("extension: %u", (unsigned)kExtensions[i].value);
2334      goto err;
2335    }
2336  }
2337
2338  if (!custom_ext_add_serverhello(ssl, &extensions)) {
2339    goto err;
2340  }
2341
2342  /* If only two bytes have been written then the extensions are actually empty
2343   * and those two bytes are the zero length. In that case, we don't bother
2344   * sending the extensions length. */
2345  if (CBB_len(&extensions) - orig_len == 2) {
2346    CBB_discard_child(out);
2347  }
2348
2349  return CBB_flush(out);
2350
2351err:
2352  OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
2353  return 0;
2354}
2355
2356static int ssl_scan_clienthello_tlsext(SSL *s, CBS *cbs, int *out_alert) {
2357  size_t i;
2358  for (i = 0; i < kNumExtensions; i++) {
2359    if (kExtensions[i].init != NULL) {
2360      kExtensions[i].init(s);
2361    }
2362  }
2363
2364  s->s3->tmp.extensions.received = 0;
2365  s->s3->tmp.custom_extensions.received = 0;
2366  /* The renegotiation extension must always be at index zero because the
2367   * |received| and |sent| bitsets need to be tweaked when the "extension" is
2368   * sent as an SCSV. */
2369  assert(kExtensions[0].value == TLSEXT_TYPE_renegotiate);
2370
2371  /* There may be no extensions. */
2372  if (CBS_len(cbs) != 0) {
2373    /* Decode the extensions block and check it is valid. */
2374    CBS extensions;
2375    if (!CBS_get_u16_length_prefixed(cbs, &extensions) ||
2376        !tls1_check_duplicate_extensions(&extensions)) {
2377      *out_alert = SSL_AD_DECODE_ERROR;
2378      return 0;
2379    }
2380
2381    while (CBS_len(&extensions) != 0) {
2382      uint16_t type;
2383      CBS extension;
2384
2385      /* Decode the next extension. */
2386      if (!CBS_get_u16(&extensions, &type) ||
2387          !CBS_get_u16_length_prefixed(&extensions, &extension)) {
2388        *out_alert = SSL_AD_DECODE_ERROR;
2389        return 0;
2390      }
2391
2392      /* RFC 5746 made the existence of extensions in SSL 3.0 somewhat
2393       * ambiguous. Ignore all but the renegotiation_info extension. */
2394      if (s->version == SSL3_VERSION && type != TLSEXT_TYPE_renegotiate) {
2395        continue;
2396      }
2397
2398      unsigned ext_index;
2399      const struct tls_extension *const ext =
2400          tls_extension_find(&ext_index, type);
2401
2402      if (ext == NULL) {
2403        if (!custom_ext_parse_clienthello(s, out_alert, type, &extension)) {
2404          OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_PARSING_EXTENSION);
2405          return 0;
2406        }
2407        continue;
2408      }
2409
2410      s->s3->tmp.extensions.received |= (1u << ext_index);
2411      uint8_t alert = SSL_AD_DECODE_ERROR;
2412      if (!ext->parse_clienthello(s, &alert, &extension)) {
2413        *out_alert = alert;
2414        OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_PARSING_EXTENSION);
2415        ERR_add_error_dataf("extension: %u", (unsigned)type);
2416        return 0;
2417      }
2418    }
2419  }
2420
2421  for (i = 0; i < kNumExtensions; i++) {
2422    if (!(s->s3->tmp.extensions.received & (1u << i))) {
2423      /* Extension wasn't observed so call the callback with a NULL
2424       * parameter. */
2425      uint8_t alert = SSL_AD_DECODE_ERROR;
2426      if (!kExtensions[i].parse_clienthello(s, &alert, NULL)) {
2427        OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_EXTENSION);
2428        ERR_add_error_dataf("extension: %u", (unsigned)kExtensions[i].value);
2429        *out_alert = alert;
2430        return 0;
2431      }
2432    }
2433  }
2434
2435  return 1;
2436}
2437
2438int ssl_parse_clienthello_tlsext(SSL *s, CBS *cbs) {
2439  int alert = -1;
2440  if (ssl_scan_clienthello_tlsext(s, cbs, &alert) <= 0) {
2441    ssl3_send_alert(s, SSL3_AL_FATAL, alert);
2442    return 0;
2443  }
2444
2445  if (ssl_check_clienthello_tlsext(s) <= 0) {
2446    OPENSSL_PUT_ERROR(SSL, SSL_R_CLIENTHELLO_TLSEXT);
2447    return 0;
2448  }
2449
2450  return 1;
2451}
2452
2453OPENSSL_COMPILE_ASSERT(kNumExtensions <= sizeof(uint32_t) * 8, too_many_bits);
2454
2455static int ssl_scan_serverhello_tlsext(SSL *s, CBS *cbs, int *out_alert) {
2456  uint32_t received = 0;
2457
2458  if (CBS_len(cbs) != 0) {
2459    /* Decode the extensions block and check it is valid. */
2460    CBS extensions;
2461    if (!CBS_get_u16_length_prefixed(cbs, &extensions) ||
2462        !tls1_check_duplicate_extensions(&extensions)) {
2463      *out_alert = SSL_AD_DECODE_ERROR;
2464      return 0;
2465    }
2466
2467
2468    while (CBS_len(&extensions) != 0) {
2469      uint16_t type;
2470      CBS extension;
2471
2472      /* Decode the next extension. */
2473      if (!CBS_get_u16(&extensions, &type) ||
2474          !CBS_get_u16_length_prefixed(&extensions, &extension)) {
2475        *out_alert = SSL_AD_DECODE_ERROR;
2476        return 0;
2477      }
2478
2479      unsigned ext_index;
2480      const struct tls_extension *const ext =
2481          tls_extension_find(&ext_index, type);
2482
2483      if (ext == NULL) {
2484        if (!custom_ext_parse_serverhello(s, out_alert, type, &extension)) {
2485          return 0;
2486        }
2487        continue;
2488      }
2489
2490      if (!(s->s3->tmp.extensions.sent & (1u << ext_index))) {
2491        /* If the extension was never sent then it is illegal. */
2492        OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
2493        ERR_add_error_dataf("extension :%u", (unsigned)type);
2494        *out_alert = SSL_AD_DECODE_ERROR;
2495        return 0;
2496      }
2497
2498      received |= (1u << ext_index);
2499
2500      uint8_t alert = SSL_AD_DECODE_ERROR;
2501      if (!ext->parse_serverhello(s, &alert, &extension)) {
2502        OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_PARSING_EXTENSION);
2503        ERR_add_error_dataf("extension: %u", (unsigned)type);
2504        *out_alert = alert;
2505        return 0;
2506      }
2507    }
2508  }
2509
2510  size_t i;
2511  for (i = 0; i < kNumExtensions; i++) {
2512    if (!(received & (1u << i))) {
2513      /* Extension wasn't observed so call the callback with a NULL
2514       * parameter. */
2515      uint8_t alert = SSL_AD_DECODE_ERROR;
2516      if (!kExtensions[i].parse_serverhello(s, &alert, NULL)) {
2517        OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_EXTENSION);
2518        ERR_add_error_dataf("extension: %u", (unsigned)kExtensions[i].value);
2519        *out_alert = alert;
2520        return 0;
2521      }
2522    }
2523  }
2524
2525  return 1;
2526}
2527
2528static int ssl_check_clienthello_tlsext(SSL *s) {
2529  int ret = SSL_TLSEXT_ERR_NOACK;
2530  int al = SSL_AD_UNRECOGNIZED_NAME;
2531
2532  /* The handling of the ECPointFormats extension is done elsewhere, namely in
2533   * ssl3_choose_cipher in s3_lib.c. */
2534
2535  if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) {
2536    ret = s->ctx->tlsext_servername_callback(s, &al,
2537                                             s->ctx->tlsext_servername_arg);
2538  } else if (s->initial_ctx != NULL &&
2539             s->initial_ctx->tlsext_servername_callback != 0) {
2540    ret = s->initial_ctx->tlsext_servername_callback(
2541        s, &al, s->initial_ctx->tlsext_servername_arg);
2542  }
2543
2544  switch (ret) {
2545    case SSL_TLSEXT_ERR_ALERT_FATAL:
2546      ssl3_send_alert(s, SSL3_AL_FATAL, al);
2547      return -1;
2548
2549    case SSL_TLSEXT_ERR_ALERT_WARNING:
2550      ssl3_send_alert(s, SSL3_AL_WARNING, al);
2551      return 1;
2552
2553    case SSL_TLSEXT_ERR_NOACK:
2554      s->s3->tmp.should_ack_sni = 0;
2555      return 1;
2556
2557    default:
2558      return 1;
2559  }
2560}
2561
2562static int ssl_check_serverhello_tlsext(SSL *s) {
2563  int ret = SSL_TLSEXT_ERR_OK;
2564  int al = SSL_AD_UNRECOGNIZED_NAME;
2565
2566  if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) {
2567    ret = s->ctx->tlsext_servername_callback(s, &al,
2568                                             s->ctx->tlsext_servername_arg);
2569  } else if (s->initial_ctx != NULL &&
2570             s->initial_ctx->tlsext_servername_callback != 0) {
2571    ret = s->initial_ctx->tlsext_servername_callback(
2572        s, &al, s->initial_ctx->tlsext_servername_arg);
2573  }
2574
2575  switch (ret) {
2576    case SSL_TLSEXT_ERR_ALERT_FATAL:
2577      ssl3_send_alert(s, SSL3_AL_FATAL, al);
2578      return -1;
2579
2580    case SSL_TLSEXT_ERR_ALERT_WARNING:
2581      ssl3_send_alert(s, SSL3_AL_WARNING, al);
2582      return 1;
2583
2584    default:
2585      return 1;
2586  }
2587}
2588
2589int ssl_parse_serverhello_tlsext(SSL *s, CBS *cbs) {
2590  int alert = -1;
2591  if (ssl_scan_serverhello_tlsext(s, cbs, &alert) <= 0) {
2592    ssl3_send_alert(s, SSL3_AL_FATAL, alert);
2593    return 0;
2594  }
2595
2596  if (ssl_check_serverhello_tlsext(s) <= 0) {
2597    OPENSSL_PUT_ERROR(SSL, SSL_R_SERVERHELLO_TLSEXT);
2598    return 0;
2599  }
2600
2601  return 1;
2602}
2603
2604int tls_process_ticket(SSL *ssl, SSL_SESSION **out_session,
2605                       int *out_send_ticket, const uint8_t *ticket,
2606                       size_t ticket_len, const uint8_t *session_id,
2607                       size_t session_id_len) {
2608  int ret = 1; /* Most errors are non-fatal. */
2609  SSL_CTX *ssl_ctx = ssl->initial_ctx;
2610  uint8_t *plaintext = NULL;
2611
2612  HMAC_CTX hmac_ctx;
2613  HMAC_CTX_init(&hmac_ctx);
2614  EVP_CIPHER_CTX cipher_ctx;
2615  EVP_CIPHER_CTX_init(&cipher_ctx);
2616
2617  *out_send_ticket = 0;
2618  *out_session = NULL;
2619
2620  if (session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
2621    goto done;
2622  }
2623
2624  if (ticket_len == 0) {
2625    /* The client will accept a ticket but doesn't currently have one. */
2626    *out_send_ticket = 1;
2627    goto done;
2628  }
2629
2630  /* Ensure there is room for the key name and the largest IV
2631   * |tlsext_ticket_key_cb| may try to consume. The real limit may be lower, but
2632   * the maximum IV length should be well under the minimum size for the
2633   * session material and HMAC. */
2634  if (ticket_len < SSL_TICKET_KEY_NAME_LEN + EVP_MAX_IV_LENGTH) {
2635    goto done;
2636  }
2637  const uint8_t *iv = ticket + SSL_TICKET_KEY_NAME_LEN;
2638
2639  if (ssl_ctx->tlsext_ticket_key_cb != NULL) {
2640    int cb_ret = ssl_ctx->tlsext_ticket_key_cb(ssl, (uint8_t*)ticket /* name */,
2641                                               (uint8_t*)iv, &cipher_ctx, &hmac_ctx,
2642                                               0 /* decrypt */);
2643    if (cb_ret < 0) {
2644      ret = 0;
2645      goto done;
2646    }
2647    if (cb_ret == 0) {
2648      goto done;
2649    }
2650    if (cb_ret == 2) {
2651      *out_send_ticket = 1;
2652    }
2653  } else {
2654    /* Check the key name matches. */
2655    if (memcmp(ticket, ssl_ctx->tlsext_tick_key_name,
2656               SSL_TICKET_KEY_NAME_LEN) != 0) {
2657      goto done;
2658    }
2659    if (!HMAC_Init_ex(&hmac_ctx, ssl_ctx->tlsext_tick_hmac_key,
2660                      sizeof(ssl_ctx->tlsext_tick_hmac_key), tlsext_tick_md(),
2661                      NULL) ||
2662        !EVP_DecryptInit_ex(&cipher_ctx, EVP_aes_128_cbc(), NULL,
2663                            ssl_ctx->tlsext_tick_aes_key, iv)) {
2664      ret = 0;
2665      goto done;
2666    }
2667  }
2668  size_t iv_len = EVP_CIPHER_CTX_iv_length(&cipher_ctx);
2669
2670  /* Check the MAC at the end of the ticket. */
2671  uint8_t mac[EVP_MAX_MD_SIZE];
2672  size_t mac_len = HMAC_size(&hmac_ctx);
2673  if (ticket_len < SSL_TICKET_KEY_NAME_LEN + iv_len + 1 + mac_len) {
2674    /* The ticket must be large enough for key name, IV, data, and MAC. */
2675    goto done;
2676  }
2677  HMAC_Update(&hmac_ctx, ticket, ticket_len - mac_len);
2678  HMAC_Final(&hmac_ctx, mac, NULL);
2679  if (CRYPTO_memcmp(mac, ticket + (ticket_len - mac_len), mac_len) != 0) {
2680    goto done;
2681  }
2682
2683  /* Decrypt the session data. */
2684  const uint8_t *ciphertext = ticket + SSL_TICKET_KEY_NAME_LEN + iv_len;
2685  size_t ciphertext_len = ticket_len - SSL_TICKET_KEY_NAME_LEN - iv_len -
2686                          mac_len;
2687  plaintext = OPENSSL_malloc(ciphertext_len);
2688  if (plaintext == NULL) {
2689    ret = 0;
2690    goto done;
2691  }
2692  if (ciphertext_len >= INT_MAX) {
2693    goto done;
2694  }
2695  int len1, len2;
2696  if (!EVP_DecryptUpdate(&cipher_ctx, plaintext, &len1, ciphertext,
2697                         (int)ciphertext_len) ||
2698      !EVP_DecryptFinal_ex(&cipher_ctx, plaintext + len1, &len2)) {
2699    ERR_clear_error(); /* Don't leave an error on the queue. */
2700    goto done;
2701  }
2702
2703  /* Decode the session. */
2704  SSL_SESSION *session = SSL_SESSION_from_bytes(plaintext, len1 + len2);
2705  if (session == NULL) {
2706    ERR_clear_error(); /* Don't leave an error on the queue. */
2707    goto done;
2708  }
2709
2710  /* Copy the client's session ID into the new session, to denote the ticket has
2711   * been accepted. */
2712  memcpy(session->session_id, session_id, session_id_len);
2713  session->session_id_length = session_id_len;
2714
2715  *out_session = session;
2716
2717done:
2718  OPENSSL_free(plaintext);
2719  HMAC_CTX_cleanup(&hmac_ctx);
2720  EVP_CIPHER_CTX_cleanup(&cipher_ctx);
2721  return ret;
2722}
2723
2724/* Tables to translate from NIDs to TLS v1.2 ids */
2725typedef struct {
2726  int nid;
2727  int id;
2728} tls12_lookup;
2729
2730static const tls12_lookup tls12_md[] = {{NID_md5, TLSEXT_hash_md5},
2731                                        {NID_sha1, TLSEXT_hash_sha1},
2732                                        {NID_sha224, TLSEXT_hash_sha224},
2733                                        {NID_sha256, TLSEXT_hash_sha256},
2734                                        {NID_sha384, TLSEXT_hash_sha384},
2735                                        {NID_sha512, TLSEXT_hash_sha512}};
2736
2737static const tls12_lookup tls12_sig[] = {{EVP_PKEY_RSA, TLSEXT_signature_rsa},
2738                                         {EVP_PKEY_EC, TLSEXT_signature_ecdsa}};
2739
2740static int tls12_find_id(int nid, const tls12_lookup *table, size_t tlen) {
2741  size_t i;
2742  for (i = 0; i < tlen; i++) {
2743    if (table[i].nid == nid) {
2744      return table[i].id;
2745    }
2746  }
2747
2748  return -1;
2749}
2750
2751int tls12_get_sigid(int pkey_type) {
2752  return tls12_find_id(pkey_type, tls12_sig,
2753                       sizeof(tls12_sig) / sizeof(tls12_lookup));
2754}
2755
2756int tls12_get_sigandhash(SSL *ssl, uint8_t *p, const EVP_MD *md) {
2757  int sig_id, md_id;
2758
2759  if (!md) {
2760    return 0;
2761  }
2762
2763  md_id = tls12_find_id(EVP_MD_type(md), tls12_md,
2764                        sizeof(tls12_md) / sizeof(tls12_lookup));
2765  if (md_id == -1) {
2766    return 0;
2767  }
2768
2769  sig_id = tls12_get_sigid(ssl_private_key_type(ssl));
2770  if (sig_id == -1) {
2771    return 0;
2772  }
2773
2774  p[0] = (uint8_t)md_id;
2775  p[1] = (uint8_t)sig_id;
2776  return 1;
2777}
2778
2779const EVP_MD *tls12_get_hash(uint8_t hash_alg) {
2780  switch (hash_alg) {
2781    case TLSEXT_hash_md5:
2782      return EVP_md5();
2783
2784    case TLSEXT_hash_sha1:
2785      return EVP_sha1();
2786
2787    case TLSEXT_hash_sha224:
2788      return EVP_sha224();
2789
2790    case TLSEXT_hash_sha256:
2791      return EVP_sha256();
2792
2793    case TLSEXT_hash_sha384:
2794      return EVP_sha384();
2795
2796    case TLSEXT_hash_sha512:
2797      return EVP_sha512();
2798
2799    default:
2800      return NULL;
2801  }
2802}
2803
2804/* tls12_get_pkey_type returns the EVP_PKEY type corresponding to TLS signature
2805 * algorithm |sig_alg|. It returns -1 if the type is unknown. */
2806static int tls12_get_pkey_type(uint8_t sig_alg) {
2807  switch (sig_alg) {
2808    case TLSEXT_signature_rsa:
2809      return EVP_PKEY_RSA;
2810
2811    case TLSEXT_signature_ecdsa:
2812      return EVP_PKEY_EC;
2813
2814    default:
2815      return -1;
2816  }
2817}
2818
2819OPENSSL_COMPILE_ASSERT(sizeof(TLS_SIGALGS) == 2,
2820    sizeof_tls_sigalgs_is_not_two);
2821
2822int tls1_parse_peer_sigalgs(SSL *ssl, const CBS *in_sigalgs) {
2823  /* Extension ignored for inappropriate versions */
2824  if (!SSL_USE_SIGALGS(ssl)) {
2825    return 1;
2826  }
2827
2828  CERT *const cert = ssl->cert;
2829  OPENSSL_free(cert->peer_sigalgs);
2830  cert->peer_sigalgs = NULL;
2831  cert->peer_sigalgslen = 0;
2832
2833  size_t num_sigalgs = CBS_len(in_sigalgs);
2834
2835  if (num_sigalgs % 2 != 0) {
2836    return 0;
2837  }
2838  num_sigalgs /= 2;
2839
2840  /* supported_signature_algorithms in the certificate request is
2841   * allowed to be empty. */
2842  if (num_sigalgs == 0) {
2843    return 1;
2844  }
2845
2846  /* This multiplication doesn't overflow because sizeof(TLS_SIGALGS) is two
2847   * (statically asserted above) and we just divided |num_sigalgs| by two. */
2848  cert->peer_sigalgs = OPENSSL_malloc(num_sigalgs * sizeof(TLS_SIGALGS));
2849  if (cert->peer_sigalgs == NULL) {
2850    return 0;
2851  }
2852  cert->peer_sigalgslen = num_sigalgs;
2853
2854  CBS sigalgs;
2855  CBS_init(&sigalgs, CBS_data(in_sigalgs), CBS_len(in_sigalgs));
2856
2857  size_t i;
2858  for (i = 0; i < num_sigalgs; i++) {
2859    TLS_SIGALGS *const sigalg = &cert->peer_sigalgs[i];
2860    if (!CBS_get_u8(&sigalgs, &sigalg->rhash) ||
2861        !CBS_get_u8(&sigalgs, &sigalg->rsign)) {
2862      return 0;
2863    }
2864  }
2865
2866  return 1;
2867}
2868
2869const EVP_MD *tls1_choose_signing_digest(SSL *ssl) {
2870  CERT *cert = ssl->cert;
2871  int type = ssl_private_key_type(ssl);
2872  size_t i, j;
2873
2874  static const int kDefaultDigestList[] = {NID_sha256, NID_sha384, NID_sha512,
2875                                           NID_sha224, NID_sha1};
2876
2877  const int *digest_nids = kDefaultDigestList;
2878  size_t num_digest_nids =
2879      sizeof(kDefaultDigestList) / sizeof(kDefaultDigestList[0]);
2880  if (cert->digest_nids != NULL) {
2881    digest_nids = cert->digest_nids;
2882    num_digest_nids = cert->num_digest_nids;
2883  }
2884
2885  for (i = 0; i < num_digest_nids; i++) {
2886    const int digest_nid = digest_nids[i];
2887    for (j = 0; j < cert->peer_sigalgslen; j++) {
2888      const EVP_MD *md = tls12_get_hash(cert->peer_sigalgs[j].rhash);
2889      if (md == NULL ||
2890          digest_nid != EVP_MD_type(md) ||
2891          tls12_get_pkey_type(cert->peer_sigalgs[j].rsign) != type) {
2892        continue;
2893      }
2894
2895      return md;
2896    }
2897  }
2898
2899  /* If no suitable digest may be found, default to SHA-1. */
2900  return EVP_sha1();
2901}
2902
2903int tls1_channel_id_hash(SSL *ssl, uint8_t *out, size_t *out_len) {
2904  int ret = 0;
2905  EVP_MD_CTX ctx;
2906
2907  EVP_MD_CTX_init(&ctx);
2908  if (!EVP_DigestInit_ex(&ctx, EVP_sha256(), NULL)) {
2909    goto err;
2910  }
2911
2912  static const char kClientIDMagic[] = "TLS Channel ID signature";
2913  EVP_DigestUpdate(&ctx, kClientIDMagic, sizeof(kClientIDMagic));
2914
2915  if (ssl->hit) {
2916    static const char kResumptionMagic[] = "Resumption";
2917    EVP_DigestUpdate(&ctx, kResumptionMagic, sizeof(kResumptionMagic));
2918    if (ssl->session->original_handshake_hash_len == 0) {
2919      OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
2920      goto err;
2921    }
2922    EVP_DigestUpdate(&ctx, ssl->session->original_handshake_hash,
2923                     ssl->session->original_handshake_hash_len);
2924  }
2925
2926  uint8_t handshake_hash[EVP_MAX_MD_SIZE];
2927  int handshake_hash_len = tls1_handshake_digest(ssl, handshake_hash,
2928                                                 sizeof(handshake_hash));
2929  if (handshake_hash_len < 0) {
2930    goto err;
2931  }
2932  EVP_DigestUpdate(&ctx, handshake_hash, (size_t)handshake_hash_len);
2933  unsigned len_u;
2934  EVP_DigestFinal_ex(&ctx, out, &len_u);
2935  *out_len = len_u;
2936
2937  ret = 1;
2938
2939err:
2940  EVP_MD_CTX_cleanup(&ctx);
2941  return ret;
2942}
2943
2944/* tls1_record_handshake_hashes_for_channel_id records the current handshake
2945 * hashes in |s->session| so that Channel ID resumptions can sign that data. */
2946int tls1_record_handshake_hashes_for_channel_id(SSL *s) {
2947  int digest_len;
2948  /* This function should never be called for a resumed session because the
2949   * handshake hashes that we wish to record are for the original, full
2950   * handshake. */
2951  if (s->hit) {
2952    return -1;
2953  }
2954
2955  digest_len =
2956      tls1_handshake_digest(s, s->session->original_handshake_hash,
2957                            sizeof(s->session->original_handshake_hash));
2958  if (digest_len < 0) {
2959    return -1;
2960  }
2961
2962  s->session->original_handshake_hash_len = digest_len;
2963
2964  return 1;
2965}
2966