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  */
110 /* ====================================================================
111  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
112  * ECC cipher suite support in OpenSSL originally developed by
113  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. */
114 
115 #include <openssl/ssl.h>
116 
117 #include <assert.h>
118 #include <limits.h>
119 #include <string.h>
120 
121 #include <openssl/bn.h>
122 #include <openssl/buf.h>
123 #include <openssl/bytestring.h>
124 #include <openssl/dh.h>
125 #include <openssl/ec_key.h>
126 #include <openssl/err.h>
127 #include <openssl/mem.h>
128 #include <openssl/sha.h>
129 #include <openssl/x509.h>
130 
131 #include "../crypto/internal.h"
132 #include "internal.h"
133 
134 
ssl_cert_new(const SSL_X509_METHOD * x509_method)135 CERT *ssl_cert_new(const SSL_X509_METHOD *x509_method) {
136   CERT *ret = OPENSSL_malloc(sizeof(CERT));
137   if (ret == NULL) {
138     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
139     return NULL;
140   }
141   OPENSSL_memset(ret, 0, sizeof(CERT));
142   ret->x509_method = x509_method;
143 
144   return ret;
145 }
146 
buffer_up_ref(CRYPTO_BUFFER * buffer)147 static CRYPTO_BUFFER *buffer_up_ref(CRYPTO_BUFFER *buffer) {
148   CRYPTO_BUFFER_up_ref(buffer);
149   return buffer;
150 }
151 
ssl_cert_dup(CERT * cert)152 CERT *ssl_cert_dup(CERT *cert) {
153   CERT *ret = OPENSSL_malloc(sizeof(CERT));
154   if (ret == NULL) {
155     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
156     return NULL;
157   }
158   OPENSSL_memset(ret, 0, sizeof(CERT));
159 
160   ret->chain = sk_CRYPTO_BUFFER_deep_copy(cert->chain, buffer_up_ref,
161                                           CRYPTO_BUFFER_free);
162 
163   if (cert->privatekey != NULL) {
164     EVP_PKEY_up_ref(cert->privatekey);
165     ret->privatekey = cert->privatekey;
166   }
167 
168   ret->key_method = cert->key_method;
169   ret->x509_method = cert->x509_method;
170 
171   if (cert->dh_tmp != NULL) {
172     ret->dh_tmp = DHparams_dup(cert->dh_tmp);
173     if (ret->dh_tmp == NULL) {
174       OPENSSL_PUT_ERROR(SSL, ERR_R_DH_LIB);
175       goto err;
176     }
177   }
178   ret->dh_tmp_cb = cert->dh_tmp_cb;
179 
180   if (cert->sigalgs != NULL) {
181     ret->sigalgs =
182         BUF_memdup(cert->sigalgs, cert->num_sigalgs * sizeof(cert->sigalgs[0]));
183     if (ret->sigalgs == NULL) {
184       goto err;
185     }
186   }
187   ret->num_sigalgs = cert->num_sigalgs;
188 
189   ret->cert_cb = cert->cert_cb;
190   ret->cert_cb_arg = cert->cert_cb_arg;
191 
192   ret->x509_method->cert_dup(ret, cert);
193 
194   if (cert->signed_cert_timestamp_list != NULL) {
195     CRYPTO_BUFFER_up_ref(cert->signed_cert_timestamp_list);
196     ret->signed_cert_timestamp_list = cert->signed_cert_timestamp_list;
197   }
198 
199   if (cert->ocsp_response != NULL) {
200     CRYPTO_BUFFER_up_ref(cert->ocsp_response);
201     ret->ocsp_response = cert->ocsp_response;
202   }
203 
204   ret->sid_ctx_length = cert->sid_ctx_length;
205   OPENSSL_memcpy(ret->sid_ctx, cert->sid_ctx, sizeof(ret->sid_ctx));
206 
207   return ret;
208 
209 err:
210   ssl_cert_free(ret);
211   return NULL;
212 }
213 
214 /* Free up and clear all certificates and chains */
ssl_cert_clear_certs(CERT * cert)215 void ssl_cert_clear_certs(CERT *cert) {
216   if (cert == NULL) {
217     return;
218   }
219 
220   cert->x509_method->cert_clear(cert);
221 
222   sk_CRYPTO_BUFFER_pop_free(cert->chain, CRYPTO_BUFFER_free);
223   cert->chain = NULL;
224   EVP_PKEY_free(cert->privatekey);
225   cert->privatekey = NULL;
226   cert->key_method = NULL;
227 }
228 
ssl_cert_free(CERT * c)229 void ssl_cert_free(CERT *c) {
230   if (c == NULL) {
231     return;
232   }
233 
234   DH_free(c->dh_tmp);
235 
236   ssl_cert_clear_certs(c);
237   c->x509_method->cert_free(c);
238   OPENSSL_free(c->sigalgs);
239   CRYPTO_BUFFER_free(c->signed_cert_timestamp_list);
240   CRYPTO_BUFFER_free(c->ocsp_response);
241 
242   OPENSSL_free(c);
243 }
244 
ssl_cert_set_cert_cb(CERT * c,int (* cb)(SSL * ssl,void * arg),void * arg)245 static void ssl_cert_set_cert_cb(CERT *c, int (*cb)(SSL *ssl, void *arg),
246                                  void *arg) {
247   c->cert_cb = cb;
248   c->cert_cb_arg = arg;
249 }
250 
251 enum leaf_cert_and_privkey_result_t {
252   leaf_cert_and_privkey_error,
253   leaf_cert_and_privkey_ok,
254   leaf_cert_and_privkey_mismatch,
255 };
256 
257 /* check_leaf_cert_and_privkey checks whether the certificate in |leaf_buffer|
258  * and the private key in |privkey| are suitable and coherent. It returns
259  * |leaf_cert_and_privkey_error| and pushes to the error queue if a problem is
260  * found. If the certificate and private key are valid, but incoherent, it
261  * returns |leaf_cert_and_privkey_mismatch|. Otherwise it returns
262  * |leaf_cert_and_privkey_ok|. */
check_leaf_cert_and_privkey(CRYPTO_BUFFER * leaf_buffer,EVP_PKEY * privkey)263 static enum leaf_cert_and_privkey_result_t check_leaf_cert_and_privkey(
264     CRYPTO_BUFFER *leaf_buffer, EVP_PKEY *privkey) {
265   enum leaf_cert_and_privkey_result_t ret = leaf_cert_and_privkey_error;
266 
267   CBS cert_cbs;
268   CRYPTO_BUFFER_init_CBS(leaf_buffer, &cert_cbs);
269   EVP_PKEY *pubkey = ssl_cert_parse_pubkey(&cert_cbs);
270   if (pubkey == NULL) {
271     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
272     goto out;
273   }
274 
275   if (!ssl_is_key_type_supported(pubkey->type)) {
276     OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
277     goto out;
278   }
279 
280   /* An ECC certificate may be usable for ECDH or ECDSA. We only support ECDSA
281    * certificates, so sanity-check the key usage extension. */
282   if (pubkey->type == EVP_PKEY_EC &&
283       !ssl_cert_check_digital_signature_key_usage(&cert_cbs)) {
284     OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
285     goto out;
286   }
287 
288   if (privkey != NULL &&
289       /* Sanity-check that the private key and the certificate match. */
290       !ssl_compare_public_and_private_key(pubkey, privkey)) {
291     ERR_clear_error();
292     ret = leaf_cert_and_privkey_mismatch;
293     goto out;
294   }
295 
296   ret = leaf_cert_and_privkey_ok;
297 
298 out:
299   EVP_PKEY_free(pubkey);
300   return ret;
301 }
302 
cert_set_chain_and_key(CERT * cert,CRYPTO_BUFFER * const * certs,size_t num_certs,EVP_PKEY * privkey,const SSL_PRIVATE_KEY_METHOD * privkey_method)303 static int cert_set_chain_and_key(
304     CERT *cert, CRYPTO_BUFFER *const *certs, size_t num_certs,
305     EVP_PKEY *privkey, const SSL_PRIVATE_KEY_METHOD *privkey_method) {
306   if (num_certs == 0 ||
307       (privkey == NULL && privkey_method == NULL)) {
308     OPENSSL_PUT_ERROR(SSL, ERR_R_PASSED_NULL_PARAMETER);
309     return 0;
310   }
311 
312   if (privkey != NULL && privkey_method != NULL) {
313     OPENSSL_PUT_ERROR(SSL, SSL_R_CANNOT_HAVE_BOTH_PRIVKEY_AND_METHOD);
314     return 0;
315   }
316 
317   switch (check_leaf_cert_and_privkey(certs[0], privkey)) {
318     case leaf_cert_and_privkey_error:
319       return 0;
320     case leaf_cert_and_privkey_mismatch:
321       OPENSSL_PUT_ERROR(SSL, SSL_R_CERTIFICATE_AND_PRIVATE_KEY_MISMATCH);
322       return 0;
323     case leaf_cert_and_privkey_ok:
324       break;
325   }
326 
327   STACK_OF(CRYPTO_BUFFER) *certs_sk = sk_CRYPTO_BUFFER_new_null();
328   if (certs_sk == NULL) {
329     return 0;
330   }
331 
332   for (size_t i = 0; i < num_certs; i++) {
333     if (!sk_CRYPTO_BUFFER_push(certs_sk, certs[i])) {
334       sk_CRYPTO_BUFFER_pop_free(certs_sk, CRYPTO_BUFFER_free);
335       return 0;
336     }
337     CRYPTO_BUFFER_up_ref(certs[i]);
338   }
339 
340   EVP_PKEY_free(cert->privatekey);
341   cert->privatekey = privkey;
342   if (privkey != NULL) {
343     EVP_PKEY_up_ref(privkey);
344   }
345   cert->key_method = privkey_method;
346 
347   sk_CRYPTO_BUFFER_pop_free(cert->chain, CRYPTO_BUFFER_free);
348   cert->chain = certs_sk;
349 
350   return 1;
351 }
352 
SSL_set_chain_and_key(SSL * ssl,CRYPTO_BUFFER * const * certs,size_t num_certs,EVP_PKEY * privkey,const SSL_PRIVATE_KEY_METHOD * privkey_method)353 int SSL_set_chain_and_key(SSL *ssl, CRYPTO_BUFFER *const *certs,
354                           size_t num_certs, EVP_PKEY *privkey,
355                           const SSL_PRIVATE_KEY_METHOD *privkey_method) {
356   return cert_set_chain_and_key(ssl->cert, certs, num_certs, privkey,
357                                 privkey_method);
358 }
359 
SSL_CTX_set_chain_and_key(SSL_CTX * ctx,CRYPTO_BUFFER * const * certs,size_t num_certs,EVP_PKEY * privkey,const SSL_PRIVATE_KEY_METHOD * privkey_method)360 int SSL_CTX_set_chain_and_key(SSL_CTX *ctx, CRYPTO_BUFFER *const *certs,
361                               size_t num_certs, EVP_PKEY *privkey,
362                               const SSL_PRIVATE_KEY_METHOD *privkey_method) {
363   return cert_set_chain_and_key(ctx->cert, certs, num_certs, privkey,
364                                 privkey_method);
365 }
366 
ssl_set_cert(CERT * cert,CRYPTO_BUFFER * buffer)367 int ssl_set_cert(CERT *cert, CRYPTO_BUFFER *buffer) {
368   switch (check_leaf_cert_and_privkey(buffer, cert->privatekey)) {
369     case leaf_cert_and_privkey_error:
370       return 0;
371     case leaf_cert_and_privkey_mismatch:
372       /* don't fail for a cert/key mismatch, just free current private key
373        * (when switching to a different cert & key, first this function should
374        * be used, then |ssl_set_pkey|. */
375       EVP_PKEY_free(cert->privatekey);
376       cert->privatekey = NULL;
377       break;
378     case leaf_cert_and_privkey_ok:
379       break;
380   }
381 
382   cert->x509_method->cert_flush_cached_leaf(cert);
383 
384   if (cert->chain != NULL) {
385     CRYPTO_BUFFER_free(sk_CRYPTO_BUFFER_value(cert->chain, 0));
386     sk_CRYPTO_BUFFER_set(cert->chain, 0, buffer);
387     CRYPTO_BUFFER_up_ref(buffer);
388     return 1;
389   }
390 
391   cert->chain = sk_CRYPTO_BUFFER_new_null();
392   if (cert->chain == NULL) {
393     return 0;
394   }
395 
396   if (!sk_CRYPTO_BUFFER_push(cert->chain, buffer)) {
397     sk_CRYPTO_BUFFER_free(cert->chain);
398     cert->chain = NULL;
399     return 0;
400   }
401   CRYPTO_BUFFER_up_ref(buffer);
402 
403   return 1;
404 }
405 
SSL_CTX_use_certificate_ASN1(SSL_CTX * ctx,size_t der_len,const uint8_t * der)406 int SSL_CTX_use_certificate_ASN1(SSL_CTX *ctx, size_t der_len,
407                                  const uint8_t *der) {
408   CRYPTO_BUFFER *buffer = CRYPTO_BUFFER_new(der, der_len, NULL);
409   if (buffer == NULL) {
410     return 0;
411   }
412 
413   const int ok = ssl_set_cert(ctx->cert, buffer);
414   CRYPTO_BUFFER_free(buffer);
415   return ok;
416 }
417 
SSL_use_certificate_ASN1(SSL * ssl,const uint8_t * der,size_t der_len)418 int SSL_use_certificate_ASN1(SSL *ssl, const uint8_t *der, size_t der_len) {
419   CRYPTO_BUFFER *buffer = CRYPTO_BUFFER_new(der, der_len, NULL);
420   if (buffer == NULL) {
421     return 0;
422   }
423 
424   const int ok = ssl_set_cert(ssl->cert, buffer);
425   CRYPTO_BUFFER_free(buffer);
426   return ok;
427 }
428 
ssl_has_certificate(const SSL * ssl)429 int ssl_has_certificate(const SSL *ssl) {
430   return ssl->cert->chain != NULL &&
431          sk_CRYPTO_BUFFER_value(ssl->cert->chain, 0) != NULL &&
432          ssl_has_private_key(ssl);
433 }
434 
STACK_OF(CRYPTO_BUFFER)435 STACK_OF(CRYPTO_BUFFER) *ssl_parse_cert_chain(uint8_t *out_alert,
436                                               EVP_PKEY **out_pubkey,
437                                               uint8_t *out_leaf_sha256,
438                                               CBS *cbs,
439                                               CRYPTO_BUFFER_POOL *pool) {
440   *out_pubkey = NULL;
441 
442   STACK_OF(CRYPTO_BUFFER) *ret = sk_CRYPTO_BUFFER_new_null();
443   if (ret == NULL) {
444     *out_alert = SSL_AD_INTERNAL_ERROR;
445     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
446     return NULL;
447   }
448 
449   CBS certificate_list;
450   if (!CBS_get_u24_length_prefixed(cbs, &certificate_list)) {
451     *out_alert = SSL_AD_DECODE_ERROR;
452     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
453     goto err;
454   }
455 
456   while (CBS_len(&certificate_list) > 0) {
457     CBS certificate;
458     if (!CBS_get_u24_length_prefixed(&certificate_list, &certificate) ||
459         CBS_len(&certificate) == 0) {
460       *out_alert = SSL_AD_DECODE_ERROR;
461       OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_LENGTH_MISMATCH);
462       goto err;
463     }
464 
465     if (sk_CRYPTO_BUFFER_num(ret) == 0) {
466       *out_pubkey = ssl_cert_parse_pubkey(&certificate);
467       if (*out_pubkey == NULL) {
468         *out_alert = SSL_AD_DECODE_ERROR;
469         goto err;
470       }
471 
472       /* Retain the hash of the leaf certificate if requested. */
473       if (out_leaf_sha256 != NULL) {
474         SHA256(CBS_data(&certificate), CBS_len(&certificate), out_leaf_sha256);
475       }
476     }
477 
478     CRYPTO_BUFFER *buf =
479         CRYPTO_BUFFER_new_from_CBS(&certificate, pool);
480     if (buf == NULL) {
481       *out_alert = SSL_AD_DECODE_ERROR;
482       goto err;
483     }
484 
485     if (!sk_CRYPTO_BUFFER_push(ret, buf)) {
486       *out_alert = SSL_AD_INTERNAL_ERROR;
487       CRYPTO_BUFFER_free(buf);
488       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
489       goto err;
490     }
491   }
492 
493   return ret;
494 
495 err:
496   EVP_PKEY_free(*out_pubkey);
497   *out_pubkey = NULL;
498   sk_CRYPTO_BUFFER_pop_free(ret, CRYPTO_BUFFER_free);
499   return NULL;
500 }
501 
ssl_add_cert_chain(SSL * ssl,CBB * cbb)502 int ssl_add_cert_chain(SSL *ssl, CBB *cbb) {
503   if (!ssl_has_certificate(ssl)) {
504     return CBB_add_u24(cbb, 0);
505   }
506 
507   CBB certs;
508   if (!CBB_add_u24_length_prefixed(cbb, &certs)) {
509     goto err;
510   }
511 
512   STACK_OF(CRYPTO_BUFFER) *chain = ssl->cert->chain;
513   for (size_t i = 0; i < sk_CRYPTO_BUFFER_num(chain); i++) {
514     CRYPTO_BUFFER *buffer = sk_CRYPTO_BUFFER_value(chain, i);
515     CBB child;
516     if (!CBB_add_u24_length_prefixed(&certs, &child) ||
517         !CBB_add_bytes(&child, CRYPTO_BUFFER_data(buffer),
518                        CRYPTO_BUFFER_len(buffer)) ||
519         !CBB_flush(&certs)) {
520       goto err;
521     }
522   }
523 
524   return CBB_flush(cbb);
525 
526 err:
527   OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
528   return 0;
529 }
530 
531 /* ssl_cert_skip_to_spki parses a DER-encoded, X.509 certificate from |in| and
532  * positions |*out_tbs_cert| to cover the TBSCertificate, starting at the
533  * subjectPublicKeyInfo. */
ssl_cert_skip_to_spki(const CBS * in,CBS * out_tbs_cert)534 static int ssl_cert_skip_to_spki(const CBS *in, CBS *out_tbs_cert) {
535   /* From RFC 5280, section 4.1
536    *    Certificate  ::=  SEQUENCE  {
537    *      tbsCertificate       TBSCertificate,
538    *      signatureAlgorithm   AlgorithmIdentifier,
539    *      signatureValue       BIT STRING  }
540 
541    * TBSCertificate  ::=  SEQUENCE  {
542    *      version         [0]  EXPLICIT Version DEFAULT v1,
543    *      serialNumber         CertificateSerialNumber,
544    *      signature            AlgorithmIdentifier,
545    *      issuer               Name,
546    *      validity             Validity,
547    *      subject              Name,
548    *      subjectPublicKeyInfo SubjectPublicKeyInfo,
549    *      ... } */
550   CBS buf = *in;
551 
552   CBS toplevel;
553   if (!CBS_get_asn1(&buf, &toplevel, CBS_ASN1_SEQUENCE) ||
554       CBS_len(&buf) != 0 ||
555       !CBS_get_asn1(&toplevel, out_tbs_cert, CBS_ASN1_SEQUENCE) ||
556       /* version */
557       !CBS_get_optional_asn1(
558           out_tbs_cert, NULL, NULL,
559           CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) ||
560       /* serialNumber */
561       !CBS_get_asn1(out_tbs_cert, NULL, CBS_ASN1_INTEGER) ||
562       /* signature algorithm */
563       !CBS_get_asn1(out_tbs_cert, NULL, CBS_ASN1_SEQUENCE) ||
564       /* issuer */
565       !CBS_get_asn1(out_tbs_cert, NULL, CBS_ASN1_SEQUENCE) ||
566       /* validity */
567       !CBS_get_asn1(out_tbs_cert, NULL, CBS_ASN1_SEQUENCE) ||
568       /* subject */
569       !CBS_get_asn1(out_tbs_cert, NULL, CBS_ASN1_SEQUENCE)) {
570     return 0;
571   }
572 
573   return 1;
574 }
575 
ssl_cert_parse_pubkey(const CBS * in)576 EVP_PKEY *ssl_cert_parse_pubkey(const CBS *in) {
577   CBS buf = *in, tbs_cert;
578   if (!ssl_cert_skip_to_spki(&buf, &tbs_cert)) {
579     OPENSSL_PUT_ERROR(SSL, SSL_R_CANNOT_PARSE_LEAF_CERT);
580     return NULL;
581   }
582 
583   return EVP_parse_public_key(&tbs_cert);
584 }
585 
ssl_compare_public_and_private_key(const EVP_PKEY * pubkey,const EVP_PKEY * privkey)586 int ssl_compare_public_and_private_key(const EVP_PKEY *pubkey,
587                                        const EVP_PKEY *privkey) {
588   if (EVP_PKEY_is_opaque(privkey)) {
589     /* We cannot check an opaque private key and have to trust that it
590      * matches. */
591     return 1;
592   }
593 
594   int ret = 0;
595 
596   switch (EVP_PKEY_cmp(pubkey, privkey)) {
597     case 1:
598       ret = 1;
599       break;
600     case 0:
601       OPENSSL_PUT_ERROR(X509, X509_R_KEY_VALUES_MISMATCH);
602       break;
603     case -1:
604       OPENSSL_PUT_ERROR(X509, X509_R_KEY_TYPE_MISMATCH);
605       break;
606     case -2:
607       OPENSSL_PUT_ERROR(X509, X509_R_UNKNOWN_KEY_TYPE);
608     default:
609       assert(0);
610       break;
611   }
612 
613   return ret;
614 }
615 
ssl_cert_check_private_key(const CERT * cert,const EVP_PKEY * privkey)616 int ssl_cert_check_private_key(const CERT *cert, const EVP_PKEY *privkey) {
617   if (privkey == NULL) {
618     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_PRIVATE_KEY_ASSIGNED);
619     return 0;
620   }
621 
622   if (cert->chain == NULL ||
623       sk_CRYPTO_BUFFER_value(cert->chain, 0) == NULL) {
624     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CERTIFICATE_ASSIGNED);
625     return 0;
626   }
627 
628   CBS cert_cbs;
629   CRYPTO_BUFFER_init_CBS(sk_CRYPTO_BUFFER_value(cert->chain, 0), &cert_cbs);
630   EVP_PKEY *pubkey = ssl_cert_parse_pubkey(&cert_cbs);
631   if (!pubkey) {
632     OPENSSL_PUT_ERROR(X509, X509_R_UNKNOWN_KEY_TYPE);
633     return 0;
634   }
635 
636   const int ok = ssl_compare_public_and_private_key(pubkey, privkey);
637   EVP_PKEY_free(pubkey);
638   return ok;
639 }
640 
ssl_cert_check_digital_signature_key_usage(const CBS * in)641 int ssl_cert_check_digital_signature_key_usage(const CBS *in) {
642   CBS buf = *in;
643 
644   CBS tbs_cert, outer_extensions;
645   int has_extensions;
646   if (!ssl_cert_skip_to_spki(&buf, &tbs_cert) ||
647       /* subjectPublicKeyInfo */
648       !CBS_get_asn1(&tbs_cert, NULL, CBS_ASN1_SEQUENCE) ||
649       /* issuerUniqueID */
650       !CBS_get_optional_asn1(
651           &tbs_cert, NULL, NULL,
652           CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 1) ||
653       /* subjectUniqueID */
654       !CBS_get_optional_asn1(
655           &tbs_cert, NULL, NULL,
656           CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 2) ||
657       !CBS_get_optional_asn1(
658           &tbs_cert, &outer_extensions, &has_extensions,
659           CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 3)) {
660     goto parse_err;
661   }
662 
663   if (!has_extensions) {
664     return 1;
665   }
666 
667   CBS extensions;
668   if (!CBS_get_asn1(&outer_extensions, &extensions, CBS_ASN1_SEQUENCE)) {
669     goto parse_err;
670   }
671 
672   while (CBS_len(&extensions) > 0) {
673     CBS extension, oid, contents;
674     if (!CBS_get_asn1(&extensions, &extension, CBS_ASN1_SEQUENCE) ||
675         !CBS_get_asn1(&extension, &oid, CBS_ASN1_OBJECT) ||
676         (CBS_peek_asn1_tag(&extension, CBS_ASN1_BOOLEAN) &&
677          !CBS_get_asn1(&extension, NULL, CBS_ASN1_BOOLEAN)) ||
678         !CBS_get_asn1(&extension, &contents, CBS_ASN1_OCTETSTRING) ||
679         CBS_len(&extension) != 0) {
680       goto parse_err;
681     }
682 
683     static const uint8_t kKeyUsageOID[3] = {0x55, 0x1d, 0x0f};
684     if (CBS_len(&oid) != sizeof(kKeyUsageOID) ||
685         OPENSSL_memcmp(CBS_data(&oid), kKeyUsageOID, sizeof(kKeyUsageOID)) !=
686             0) {
687       continue;
688     }
689 
690     CBS bit_string;
691     if (!CBS_get_asn1(&contents, &bit_string, CBS_ASN1_BITSTRING) ||
692         CBS_len(&contents) != 0) {
693       goto parse_err;
694     }
695 
696     /* This is the KeyUsage extension. See
697      * https://tools.ietf.org/html/rfc5280#section-4.2.1.3 */
698     if (!CBS_is_valid_asn1_bitstring(&bit_string)) {
699       goto parse_err;
700     }
701 
702     if (!CBS_asn1_bitstring_has_bit(&bit_string, 0)) {
703       OPENSSL_PUT_ERROR(SSL, SSL_R_ECC_CERT_NOT_FOR_SIGNING);
704       return 0;
705     }
706 
707     return 1;
708   }
709 
710   /* No KeyUsage extension found. */
711   return 1;
712 
713 parse_err:
714   OPENSSL_PUT_ERROR(SSL, SSL_R_CANNOT_PARSE_LEAF_CERT);
715   return 0;
716 }
717 
STACK_OF(CRYPTO_BUFFER)718 STACK_OF(CRYPTO_BUFFER) *
719     ssl_parse_client_CA_list(SSL *ssl, uint8_t *out_alert, CBS *cbs) {
720   CRYPTO_BUFFER_POOL *const pool = ssl->ctx->pool;
721 
722   STACK_OF(CRYPTO_BUFFER) *ret = sk_CRYPTO_BUFFER_new_null();
723   if (ret == NULL) {
724     *out_alert = SSL_AD_INTERNAL_ERROR;
725     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
726     return NULL;
727   }
728 
729   CBS child;
730   if (!CBS_get_u16_length_prefixed(cbs, &child)) {
731     *out_alert = SSL_AD_DECODE_ERROR;
732     OPENSSL_PUT_ERROR(SSL, SSL_R_LENGTH_MISMATCH);
733     goto err;
734   }
735 
736   while (CBS_len(&child) > 0) {
737     CBS distinguished_name;
738     if (!CBS_get_u16_length_prefixed(&child, &distinguished_name)) {
739       *out_alert = SSL_AD_DECODE_ERROR;
740       OPENSSL_PUT_ERROR(SSL, SSL_R_CA_DN_TOO_LONG);
741       goto err;
742     }
743 
744     CRYPTO_BUFFER *buffer =
745         CRYPTO_BUFFER_new_from_CBS(&distinguished_name, pool);
746     if (buffer == NULL ||
747         !sk_CRYPTO_BUFFER_push(ret, buffer)) {
748       CRYPTO_BUFFER_free(buffer);
749       *out_alert = SSL_AD_INTERNAL_ERROR;
750       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
751       goto err;
752     }
753   }
754 
755   if (!ssl->ctx->x509_method->check_client_CA_list(ret)) {
756     *out_alert = SSL_AD_INTERNAL_ERROR;
757     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
758     goto err;
759   }
760 
761   return ret;
762 
763 err:
764   sk_CRYPTO_BUFFER_pop_free(ret, CRYPTO_BUFFER_free);
765   return NULL;
766 }
767 
ssl_add_client_CA_list(SSL * ssl,CBB * cbb)768 int ssl_add_client_CA_list(SSL *ssl, CBB *cbb) {
769   CBB child, name_cbb;
770   if (!CBB_add_u16_length_prefixed(cbb, &child)) {
771     return 0;
772   }
773 
774   STACK_OF(CRYPTO_BUFFER) *names = ssl->client_CA;
775   if (names == NULL) {
776     names = ssl->ctx->client_CA;
777   }
778   if (names == NULL) {
779     return CBB_flush(cbb);
780   }
781 
782   for (size_t i = 0; i < sk_CRYPTO_BUFFER_num(names); i++) {
783     const CRYPTO_BUFFER *name = sk_CRYPTO_BUFFER_value(names, i);
784 
785     if (!CBB_add_u16_length_prefixed(&child, &name_cbb) ||
786         !CBB_add_bytes(&name_cbb, CRYPTO_BUFFER_data(name),
787                        CRYPTO_BUFFER_len(name))) {
788       return 0;
789     }
790   }
791 
792   return CBB_flush(cbb);
793 }
794 
SSL_CTX_set_cert_cb(SSL_CTX * ctx,int (* cb)(SSL * ssl,void * arg),void * arg)795 void SSL_CTX_set_cert_cb(SSL_CTX *ctx, int (*cb)(SSL *ssl, void *arg),
796                          void *arg) {
797   ssl_cert_set_cert_cb(ctx->cert, cb, arg);
798 }
799 
SSL_set_cert_cb(SSL * ssl,int (* cb)(SSL * ssl,void * arg),void * arg)800 void SSL_set_cert_cb(SSL *ssl, int (*cb)(SSL *ssl, void *arg), void *arg) {
801   ssl_cert_set_cert_cb(ssl->cert, cb, arg);
802 }
803 
STACK_OF(CRYPTO_BUFFER)804 STACK_OF(CRYPTO_BUFFER) *SSL_get0_peer_certificates(const SSL *ssl) {
805   SSL_SESSION *session = SSL_get_session(ssl);
806   if (session == NULL) {
807     return NULL;
808   }
809 
810   return session->certs;
811 }
812 
STACK_OF(CRYPTO_BUFFER)813 STACK_OF(CRYPTO_BUFFER) *SSL_get0_server_requested_CAs(const SSL *ssl) {
814   if (ssl->s3->hs == NULL) {
815     return NULL;
816   }
817   return ssl->s3->hs->ca_names;
818 }
819 
ssl_check_leaf_certificate(SSL_HANDSHAKE * hs,EVP_PKEY * pkey,const CRYPTO_BUFFER * leaf)820 int ssl_check_leaf_certificate(SSL_HANDSHAKE *hs, EVP_PKEY *pkey,
821                                const CRYPTO_BUFFER *leaf) {
822   SSL *const ssl = hs->ssl;
823   assert(ssl3_protocol_version(ssl) < TLS1_3_VERSION);
824 
825   /* Check the certificate's type matches the cipher. */
826   int expected_type = ssl_cipher_get_key_type(hs->new_cipher);
827   assert(expected_type != EVP_PKEY_NONE);
828   if (pkey->type != expected_type) {
829     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CERTIFICATE_TYPE);
830     return 0;
831   }
832 
833   if (hs->new_cipher->algorithm_auth & SSL_aECDSA) {
834     CBS leaf_cbs;
835     CBS_init(&leaf_cbs, CRYPTO_BUFFER_data(leaf), CRYPTO_BUFFER_len(leaf));
836     /* ECDSA and ECDH certificates use the same public key format. Instead,
837      * they are distinguished by the key usage extension in the certificate. */
838     if (!ssl_cert_check_digital_signature_key_usage(&leaf_cbs)) {
839       return 0;
840     }
841 
842     EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(pkey);
843     if (ec_key == NULL) {
844       OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ECC_CERT);
845       return 0;
846     }
847 
848     /* Check the key's group and point format are acceptable. */
849     uint16_t group_id;
850     if (!ssl_nid_to_group_id(
851             &group_id, EC_GROUP_get_curve_name(EC_KEY_get0_group(ec_key))) ||
852         !tls1_check_group_id(ssl, group_id) ||
853         EC_KEY_get_conv_form(ec_key) != POINT_CONVERSION_UNCOMPRESSED) {
854       OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ECC_CERT);
855       return 0;
856     }
857   }
858 
859   return 1;
860 }
861 
set_signed_cert_timestamp_list(CERT * cert,const uint8_t * list,size_t list_len)862 static int set_signed_cert_timestamp_list(CERT *cert, const uint8_t *list,
863                                            size_t list_len) {
864   CBS sct_list;
865   CBS_init(&sct_list, list, list_len);
866   if (!ssl_is_sct_list_valid(&sct_list)) {
867     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_SCT_LIST);
868     return 0;
869   }
870 
871   CRYPTO_BUFFER_free(cert->signed_cert_timestamp_list);
872   cert->signed_cert_timestamp_list =
873       CRYPTO_BUFFER_new(CBS_data(&sct_list), CBS_len(&sct_list), NULL);
874   return cert->signed_cert_timestamp_list != NULL;
875 }
876 
SSL_CTX_set_signed_cert_timestamp_list(SSL_CTX * ctx,const uint8_t * list,size_t list_len)877 int SSL_CTX_set_signed_cert_timestamp_list(SSL_CTX *ctx, const uint8_t *list,
878                                            size_t list_len) {
879   return set_signed_cert_timestamp_list(ctx->cert, list, list_len);
880 }
881 
SSL_set_signed_cert_timestamp_list(SSL * ssl,const uint8_t * list,size_t list_len)882 int SSL_set_signed_cert_timestamp_list(SSL *ssl, const uint8_t *list,
883                                        size_t list_len) {
884   return set_signed_cert_timestamp_list(ssl->cert, list, list_len);
885 }
886 
SSL_CTX_set_ocsp_response(SSL_CTX * ctx,const uint8_t * response,size_t response_len)887 int SSL_CTX_set_ocsp_response(SSL_CTX *ctx, const uint8_t *response,
888                               size_t response_len) {
889   CRYPTO_BUFFER_free(ctx->cert->ocsp_response);
890   ctx->cert->ocsp_response = CRYPTO_BUFFER_new(response, response_len, NULL);
891   return ctx->cert->ocsp_response != NULL;
892 }
893 
SSL_set_ocsp_response(SSL * ssl,const uint8_t * response,size_t response_len)894 int SSL_set_ocsp_response(SSL *ssl, const uint8_t *response,
895                           size_t response_len) {
896   CRYPTO_BUFFER_free(ssl->cert->ocsp_response);
897   ssl->cert->ocsp_response = CRYPTO_BUFFER_new(response, response_len, NULL);
898   return ssl->cert->ocsp_response != NULL;
899 }
900