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 <utility>
122 
123 #include <openssl/bn.h>
124 #include <openssl/bytestring.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 
135 BSSL_NAMESPACE_BEGIN
136 
CERT(const SSL_X509_METHOD * x509_method_arg)137 CERT::CERT(const SSL_X509_METHOD *x509_method_arg)
138     : x509_method(x509_method_arg) {}
139 
~CERT()140 CERT::~CERT() {
141   ssl_cert_clear_certs(this);
142   x509_method->cert_free(this);
143 }
144 
buffer_up_ref(CRYPTO_BUFFER * buffer)145 static CRYPTO_BUFFER *buffer_up_ref(CRYPTO_BUFFER *buffer) {
146   CRYPTO_BUFFER_up_ref(buffer);
147   return buffer;
148 }
149 
ssl_cert_dup(CERT * cert)150 UniquePtr<CERT> ssl_cert_dup(CERT *cert) {
151   UniquePtr<CERT> ret = MakeUnique<CERT>(cert->x509_method);
152   if (!ret) {
153     return nullptr;
154   }
155 
156   if (cert->chain) {
157     ret->chain.reset(sk_CRYPTO_BUFFER_deep_copy(
158         cert->chain.get(), buffer_up_ref, CRYPTO_BUFFER_free));
159     if (!ret->chain) {
160       return nullptr;
161     }
162   }
163 
164   ret->privatekey = UpRef(cert->privatekey);
165   ret->key_method = cert->key_method;
166 
167   if (!ret->sigalgs.CopyFrom(cert->sigalgs)) {
168     return nullptr;
169   }
170 
171   ret->cert_cb = cert->cert_cb;
172   ret->cert_cb_arg = cert->cert_cb_arg;
173 
174   ret->x509_method->cert_dup(ret.get(), cert);
175 
176   ret->signed_cert_timestamp_list = UpRef(cert->signed_cert_timestamp_list);
177   ret->ocsp_response = UpRef(cert->ocsp_response);
178 
179   ret->sid_ctx_length = cert->sid_ctx_length;
180   OPENSSL_memcpy(ret->sid_ctx, cert->sid_ctx, sizeof(ret->sid_ctx));
181 
182   if (cert->dc) {
183     ret->dc = cert->dc->Dup();
184     if (!ret->dc) {
185        return nullptr;
186     }
187   }
188 
189   ret->dc_privatekey = UpRef(cert->dc_privatekey);
190   ret->dc_key_method = cert->dc_key_method;
191 
192   return ret;
193 }
194 
195 // Free up and clear all certificates and chains
ssl_cert_clear_certs(CERT * cert)196 void ssl_cert_clear_certs(CERT *cert) {
197   if (cert == NULL) {
198     return;
199   }
200 
201   cert->x509_method->cert_clear(cert);
202 
203   cert->chain.reset();
204   cert->privatekey.reset();
205   cert->key_method = nullptr;
206 
207   cert->dc.reset();
208   cert->dc_privatekey.reset();
209   cert->dc_key_method = nullptr;
210 }
211 
ssl_cert_set_cert_cb(CERT * cert,int (* cb)(SSL * ssl,void * arg),void * arg)212 static void ssl_cert_set_cert_cb(CERT *cert, int (*cb)(SSL *ssl, void *arg),
213                                  void *arg) {
214   cert->cert_cb = cb;
215   cert->cert_cb_arg = arg;
216 }
217 
218 enum leaf_cert_and_privkey_result_t {
219   leaf_cert_and_privkey_error,
220   leaf_cert_and_privkey_ok,
221   leaf_cert_and_privkey_mismatch,
222 };
223 
224 // check_leaf_cert_and_privkey checks whether the certificate in |leaf_buffer|
225 // and the private key in |privkey| are suitable and coherent. It returns
226 // |leaf_cert_and_privkey_error| and pushes to the error queue if a problem is
227 // found. If the certificate and private key are valid, but incoherent, it
228 // returns |leaf_cert_and_privkey_mismatch|. Otherwise it returns
229 // |leaf_cert_and_privkey_ok|.
check_leaf_cert_and_privkey(CRYPTO_BUFFER * leaf_buffer,EVP_PKEY * privkey)230 static enum leaf_cert_and_privkey_result_t check_leaf_cert_and_privkey(
231     CRYPTO_BUFFER *leaf_buffer, EVP_PKEY *privkey) {
232   CBS cert_cbs;
233   CRYPTO_BUFFER_init_CBS(leaf_buffer, &cert_cbs);
234   UniquePtr<EVP_PKEY> pubkey = ssl_cert_parse_pubkey(&cert_cbs);
235   if (!pubkey) {
236     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
237     return leaf_cert_and_privkey_error;
238   }
239 
240   if (!ssl_is_key_type_supported(pubkey->type)) {
241     OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
242     return leaf_cert_and_privkey_error;
243   }
244 
245   // An ECC certificate may be usable for ECDH or ECDSA. We only support ECDSA
246   // certificates, so sanity-check the key usage extension.
247   if (pubkey->type == EVP_PKEY_EC &&
248       !ssl_cert_check_key_usage(&cert_cbs, key_usage_digital_signature)) {
249     OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
250     return leaf_cert_and_privkey_error;
251   }
252 
253   if (privkey != NULL &&
254       // Sanity-check that the private key and the certificate match.
255       !ssl_compare_public_and_private_key(pubkey.get(), privkey)) {
256     ERR_clear_error();
257     return leaf_cert_and_privkey_mismatch;
258   }
259 
260   return leaf_cert_and_privkey_ok;
261 }
262 
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)263 static int cert_set_chain_and_key(
264     CERT *cert, CRYPTO_BUFFER *const *certs, size_t num_certs,
265     EVP_PKEY *privkey, const SSL_PRIVATE_KEY_METHOD *privkey_method) {
266   if (num_certs == 0 ||
267       (privkey == NULL && privkey_method == NULL)) {
268     OPENSSL_PUT_ERROR(SSL, ERR_R_PASSED_NULL_PARAMETER);
269     return 0;
270   }
271 
272   if (privkey != NULL && privkey_method != NULL) {
273     OPENSSL_PUT_ERROR(SSL, SSL_R_CANNOT_HAVE_BOTH_PRIVKEY_AND_METHOD);
274     return 0;
275   }
276 
277   switch (check_leaf_cert_and_privkey(certs[0], privkey)) {
278     case leaf_cert_and_privkey_error:
279       return 0;
280     case leaf_cert_and_privkey_mismatch:
281       OPENSSL_PUT_ERROR(SSL, SSL_R_CERTIFICATE_AND_PRIVATE_KEY_MISMATCH);
282       return 0;
283     case leaf_cert_and_privkey_ok:
284       break;
285   }
286 
287   UniquePtr<STACK_OF(CRYPTO_BUFFER)> certs_sk(sk_CRYPTO_BUFFER_new_null());
288   if (!certs_sk) {
289     return 0;
290   }
291 
292   for (size_t i = 0; i < num_certs; i++) {
293     if (!PushToStack(certs_sk.get(), UpRef(certs[i]))) {
294       return 0;
295     }
296   }
297 
298   cert->privatekey = UpRef(privkey);
299   cert->key_method = privkey_method;
300 
301   cert->chain = std::move(certs_sk);
302   return 1;
303 }
304 
ssl_set_cert(CERT * cert,UniquePtr<CRYPTO_BUFFER> buffer)305 bool ssl_set_cert(CERT *cert, UniquePtr<CRYPTO_BUFFER> buffer) {
306   switch (check_leaf_cert_and_privkey(buffer.get(), cert->privatekey.get())) {
307     case leaf_cert_and_privkey_error:
308       return false;
309     case leaf_cert_and_privkey_mismatch:
310       // don't fail for a cert/key mismatch, just free current private key
311       // (when switching to a different cert & key, first this function should
312       // be used, then |ssl_set_pkey|.
313       cert->privatekey.reset();
314       break;
315     case leaf_cert_and_privkey_ok:
316       break;
317   }
318 
319   cert->x509_method->cert_flush_cached_leaf(cert);
320 
321   if (cert->chain != nullptr) {
322     CRYPTO_BUFFER_free(sk_CRYPTO_BUFFER_value(cert->chain.get(), 0));
323     sk_CRYPTO_BUFFER_set(cert->chain.get(), 0, buffer.release());
324     return true;
325   }
326 
327   cert->chain.reset(sk_CRYPTO_BUFFER_new_null());
328   if (cert->chain == nullptr) {
329     return false;
330   }
331 
332   if (!PushToStack(cert->chain.get(), std::move(buffer))) {
333     cert->chain.reset();
334     return false;
335   }
336 
337   return true;
338 }
339 
ssl_has_certificate(const SSL_HANDSHAKE * hs)340 bool ssl_has_certificate(const SSL_HANDSHAKE *hs) {
341   return hs->config->cert->chain != nullptr &&
342          sk_CRYPTO_BUFFER_value(hs->config->cert->chain.get(), 0) != nullptr &&
343          ssl_has_private_key(hs);
344 }
345 
ssl_parse_cert_chain(uint8_t * out_alert,UniquePtr<STACK_OF (CRYPTO_BUFFER)> * out_chain,UniquePtr<EVP_PKEY> * out_pubkey,uint8_t * out_leaf_sha256,CBS * cbs,CRYPTO_BUFFER_POOL * pool)346 bool ssl_parse_cert_chain(uint8_t *out_alert,
347                           UniquePtr<STACK_OF(CRYPTO_BUFFER)> *out_chain,
348                           UniquePtr<EVP_PKEY> *out_pubkey,
349                           uint8_t *out_leaf_sha256, CBS *cbs,
350                           CRYPTO_BUFFER_POOL *pool) {
351   out_chain->reset();
352   out_pubkey->reset();
353 
354   CBS certificate_list;
355   if (!CBS_get_u24_length_prefixed(cbs, &certificate_list)) {
356     *out_alert = SSL_AD_DECODE_ERROR;
357     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
358     return false;
359   }
360 
361   if (CBS_len(&certificate_list) == 0) {
362     return true;
363   }
364 
365   UniquePtr<STACK_OF(CRYPTO_BUFFER)> chain(sk_CRYPTO_BUFFER_new_null());
366   if (!chain) {
367     *out_alert = SSL_AD_INTERNAL_ERROR;
368     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
369     return false;
370   }
371 
372   UniquePtr<EVP_PKEY> pubkey;
373   while (CBS_len(&certificate_list) > 0) {
374     CBS certificate;
375     if (!CBS_get_u24_length_prefixed(&certificate_list, &certificate) ||
376         CBS_len(&certificate) == 0) {
377       *out_alert = SSL_AD_DECODE_ERROR;
378       OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_LENGTH_MISMATCH);
379       return false;
380     }
381 
382     if (sk_CRYPTO_BUFFER_num(chain.get()) == 0) {
383       pubkey = ssl_cert_parse_pubkey(&certificate);
384       if (!pubkey) {
385         *out_alert = SSL_AD_DECODE_ERROR;
386         return false;
387       }
388 
389       // Retain the hash of the leaf certificate if requested.
390       if (out_leaf_sha256 != NULL) {
391         SHA256(CBS_data(&certificate), CBS_len(&certificate), out_leaf_sha256);
392       }
393     }
394 
395     UniquePtr<CRYPTO_BUFFER> buf(
396         CRYPTO_BUFFER_new_from_CBS(&certificate, pool));
397     if (!buf ||
398         !PushToStack(chain.get(), std::move(buf))) {
399       *out_alert = SSL_AD_INTERNAL_ERROR;
400       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
401       return false;
402     }
403   }
404 
405   *out_chain = std::move(chain);
406   *out_pubkey = std::move(pubkey);
407   return true;
408 }
409 
ssl_add_cert_chain(SSL_HANDSHAKE * hs,CBB * cbb)410 bool ssl_add_cert_chain(SSL_HANDSHAKE *hs, CBB *cbb) {
411   if (!ssl_has_certificate(hs)) {
412     return CBB_add_u24(cbb, 0);
413   }
414 
415   CBB certs;
416   if (!CBB_add_u24_length_prefixed(cbb, &certs)) {
417     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
418     return false;
419   }
420 
421   STACK_OF(CRYPTO_BUFFER) *chain = hs->config->cert->chain.get();
422   for (size_t i = 0; i < sk_CRYPTO_BUFFER_num(chain); i++) {
423     CRYPTO_BUFFER *buffer = sk_CRYPTO_BUFFER_value(chain, i);
424     CBB child;
425     if (!CBB_add_u24_length_prefixed(&certs, &child) ||
426         !CBB_add_bytes(&child, CRYPTO_BUFFER_data(buffer),
427                        CRYPTO_BUFFER_len(buffer)) ||
428         !CBB_flush(&certs)) {
429       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
430       return false;
431     }
432   }
433 
434   return CBB_flush(cbb);
435 }
436 
437 // ssl_cert_skip_to_spki parses a DER-encoded, X.509 certificate from |in| and
438 // positions |*out_tbs_cert| to cover the TBSCertificate, starting at the
439 // subjectPublicKeyInfo.
ssl_cert_skip_to_spki(const CBS * in,CBS * out_tbs_cert)440 static bool ssl_cert_skip_to_spki(const CBS *in, CBS *out_tbs_cert) {
441   /* From RFC 5280, section 4.1
442    *    Certificate  ::=  SEQUENCE  {
443    *      tbsCertificate       TBSCertificate,
444    *      signatureAlgorithm   AlgorithmIdentifier,
445    *      signatureValue       BIT STRING  }
446 
447    * TBSCertificate  ::=  SEQUENCE  {
448    *      version         [0]  EXPLICIT Version DEFAULT v1,
449    *      serialNumber         CertificateSerialNumber,
450    *      signature            AlgorithmIdentifier,
451    *      issuer               Name,
452    *      validity             Validity,
453    *      subject              Name,
454    *      subjectPublicKeyInfo SubjectPublicKeyInfo,
455    *      ... } */
456   CBS buf = *in;
457 
458   CBS toplevel;
459   if (!CBS_get_asn1(&buf, &toplevel, CBS_ASN1_SEQUENCE) ||
460       CBS_len(&buf) != 0 ||
461       !CBS_get_asn1(&toplevel, out_tbs_cert, CBS_ASN1_SEQUENCE) ||
462       // version
463       !CBS_get_optional_asn1(
464           out_tbs_cert, NULL, NULL,
465           CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) ||
466       // serialNumber
467       !CBS_get_asn1(out_tbs_cert, NULL, CBS_ASN1_INTEGER) ||
468       // signature algorithm
469       !CBS_get_asn1(out_tbs_cert, NULL, CBS_ASN1_SEQUENCE) ||
470       // issuer
471       !CBS_get_asn1(out_tbs_cert, NULL, CBS_ASN1_SEQUENCE) ||
472       // validity
473       !CBS_get_asn1(out_tbs_cert, NULL, CBS_ASN1_SEQUENCE) ||
474       // subject
475       !CBS_get_asn1(out_tbs_cert, NULL, CBS_ASN1_SEQUENCE)) {
476     return false;
477   }
478 
479   return true;
480 }
481 
ssl_cert_parse_pubkey(const CBS * in)482 UniquePtr<EVP_PKEY> ssl_cert_parse_pubkey(const CBS *in) {
483   CBS buf = *in, tbs_cert;
484   if (!ssl_cert_skip_to_spki(&buf, &tbs_cert)) {
485     OPENSSL_PUT_ERROR(SSL, SSL_R_CANNOT_PARSE_LEAF_CERT);
486     return nullptr;
487   }
488 
489   return UniquePtr<EVP_PKEY>(EVP_parse_public_key(&tbs_cert));
490 }
491 
ssl_compare_public_and_private_key(const EVP_PKEY * pubkey,const EVP_PKEY * privkey)492 bool ssl_compare_public_and_private_key(const EVP_PKEY *pubkey,
493                                         const EVP_PKEY *privkey) {
494   if (EVP_PKEY_is_opaque(privkey)) {
495     // We cannot check an opaque private key and have to trust that it
496     // matches.
497     return true;
498   }
499 
500   switch (EVP_PKEY_cmp(pubkey, privkey)) {
501     case 1:
502       return true;
503     case 0:
504       OPENSSL_PUT_ERROR(X509, X509_R_KEY_VALUES_MISMATCH);
505       return false;
506     case -1:
507       OPENSSL_PUT_ERROR(X509, X509_R_KEY_TYPE_MISMATCH);
508       return false;
509     case -2:
510       OPENSSL_PUT_ERROR(X509, X509_R_UNKNOWN_KEY_TYPE);
511       return false;
512   }
513 
514   assert(0);
515   return false;
516 }
517 
ssl_cert_check_private_key(const CERT * cert,const EVP_PKEY * privkey)518 bool ssl_cert_check_private_key(const CERT *cert, const EVP_PKEY *privkey) {
519   if (privkey == nullptr) {
520     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_PRIVATE_KEY_ASSIGNED);
521     return false;
522   }
523 
524   if (cert->chain == nullptr ||
525       sk_CRYPTO_BUFFER_value(cert->chain.get(), 0) == nullptr) {
526     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CERTIFICATE_ASSIGNED);
527     return false;
528   }
529 
530   CBS cert_cbs;
531   CRYPTO_BUFFER_init_CBS(sk_CRYPTO_BUFFER_value(cert->chain.get(), 0),
532                          &cert_cbs);
533   UniquePtr<EVP_PKEY> pubkey = ssl_cert_parse_pubkey(&cert_cbs);
534   if (!pubkey) {
535     OPENSSL_PUT_ERROR(X509, X509_R_UNKNOWN_KEY_TYPE);
536     return false;
537   }
538 
539   return ssl_compare_public_and_private_key(pubkey.get(), privkey);
540 }
541 
ssl_cert_check_key_usage(const CBS * in,enum ssl_key_usage_t bit)542 bool ssl_cert_check_key_usage(const CBS *in, enum ssl_key_usage_t bit) {
543   CBS buf = *in;
544 
545   CBS tbs_cert, outer_extensions;
546   int has_extensions;
547   if (!ssl_cert_skip_to_spki(&buf, &tbs_cert) ||
548       // subjectPublicKeyInfo
549       !CBS_get_asn1(&tbs_cert, NULL, CBS_ASN1_SEQUENCE) ||
550       // issuerUniqueID
551       !CBS_get_optional_asn1(
552           &tbs_cert, NULL, NULL,
553           CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 1) ||
554       // subjectUniqueID
555       !CBS_get_optional_asn1(
556           &tbs_cert, NULL, NULL,
557           CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 2) ||
558       !CBS_get_optional_asn1(
559           &tbs_cert, &outer_extensions, &has_extensions,
560           CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 3)) {
561     OPENSSL_PUT_ERROR(SSL, SSL_R_CANNOT_PARSE_LEAF_CERT);
562     return false;
563   }
564 
565   if (!has_extensions) {
566     return true;
567   }
568 
569   CBS extensions;
570   if (!CBS_get_asn1(&outer_extensions, &extensions, CBS_ASN1_SEQUENCE)) {
571     OPENSSL_PUT_ERROR(SSL, SSL_R_CANNOT_PARSE_LEAF_CERT);
572     return false;
573   }
574 
575   while (CBS_len(&extensions) > 0) {
576     CBS extension, oid, contents;
577     if (!CBS_get_asn1(&extensions, &extension, CBS_ASN1_SEQUENCE) ||
578         !CBS_get_asn1(&extension, &oid, CBS_ASN1_OBJECT) ||
579         (CBS_peek_asn1_tag(&extension, CBS_ASN1_BOOLEAN) &&
580          !CBS_get_asn1(&extension, NULL, CBS_ASN1_BOOLEAN)) ||
581         !CBS_get_asn1(&extension, &contents, CBS_ASN1_OCTETSTRING) ||
582         CBS_len(&extension) != 0) {
583       OPENSSL_PUT_ERROR(SSL, SSL_R_CANNOT_PARSE_LEAF_CERT);
584       return false;
585     }
586 
587     static const uint8_t kKeyUsageOID[3] = {0x55, 0x1d, 0x0f};
588     if (CBS_len(&oid) != sizeof(kKeyUsageOID) ||
589         OPENSSL_memcmp(CBS_data(&oid), kKeyUsageOID, sizeof(kKeyUsageOID)) !=
590             0) {
591       continue;
592     }
593 
594     CBS bit_string;
595     if (!CBS_get_asn1(&contents, &bit_string, CBS_ASN1_BITSTRING) ||
596         CBS_len(&contents) != 0) {
597       OPENSSL_PUT_ERROR(SSL, SSL_R_CANNOT_PARSE_LEAF_CERT);
598       return false;
599     }
600 
601     // This is the KeyUsage extension. See
602     // https://tools.ietf.org/html/rfc5280#section-4.2.1.3
603     if (!CBS_is_valid_asn1_bitstring(&bit_string)) {
604       OPENSSL_PUT_ERROR(SSL, SSL_R_CANNOT_PARSE_LEAF_CERT);
605       return false;
606     }
607 
608     if (!CBS_asn1_bitstring_has_bit(&bit_string, bit)) {
609       OPENSSL_PUT_ERROR(SSL, SSL_R_KEY_USAGE_BIT_INCORRECT);
610       return false;
611     }
612 
613     return true;
614   }
615 
616   // No KeyUsage extension found.
617   return true;
618 }
619 
ssl_parse_client_CA_list(SSL * ssl,uint8_t * out_alert,CBS * cbs)620 UniquePtr<STACK_OF(CRYPTO_BUFFER)> ssl_parse_client_CA_list(SSL *ssl,
621                                                             uint8_t *out_alert,
622                                                             CBS *cbs) {
623   CRYPTO_BUFFER_POOL *const pool = ssl->ctx->pool;
624 
625   UniquePtr<STACK_OF(CRYPTO_BUFFER)> ret(sk_CRYPTO_BUFFER_new_null());
626   if (!ret) {
627     *out_alert = SSL_AD_INTERNAL_ERROR;
628     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
629     return nullptr;
630   }
631 
632   CBS child;
633   if (!CBS_get_u16_length_prefixed(cbs, &child)) {
634     *out_alert = SSL_AD_DECODE_ERROR;
635     OPENSSL_PUT_ERROR(SSL, SSL_R_LENGTH_MISMATCH);
636     return nullptr;
637   }
638 
639   while (CBS_len(&child) > 0) {
640     CBS distinguished_name;
641     if (!CBS_get_u16_length_prefixed(&child, &distinguished_name)) {
642       *out_alert = SSL_AD_DECODE_ERROR;
643       OPENSSL_PUT_ERROR(SSL, SSL_R_CA_DN_TOO_LONG);
644       return nullptr;
645     }
646 
647     UniquePtr<CRYPTO_BUFFER> buffer(
648         CRYPTO_BUFFER_new_from_CBS(&distinguished_name, pool));
649     if (!buffer ||
650         !PushToStack(ret.get(), std::move(buffer))) {
651       *out_alert = SSL_AD_INTERNAL_ERROR;
652       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
653       return nullptr;
654     }
655   }
656 
657   if (!ssl->ctx->x509_method->check_client_CA_list(ret.get())) {
658     *out_alert = SSL_AD_DECODE_ERROR;
659     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
660     return nullptr;
661   }
662 
663   return ret;
664 }
665 
ssl_has_client_CAs(const SSL_CONFIG * cfg)666 bool ssl_has_client_CAs(const SSL_CONFIG *cfg) {
667   const STACK_OF(CRYPTO_BUFFER) *names = cfg->client_CA.get();
668   if (names == nullptr) {
669     names = cfg->ssl->ctx->client_CA.get();
670   }
671   if (names == nullptr) {
672     return false;
673   }
674   return sk_CRYPTO_BUFFER_num(names) > 0;
675 }
676 
ssl_add_client_CA_list(SSL_HANDSHAKE * hs,CBB * cbb)677 bool ssl_add_client_CA_list(SSL_HANDSHAKE *hs, CBB *cbb) {
678   CBB child, name_cbb;
679   if (!CBB_add_u16_length_prefixed(cbb, &child)) {
680     return false;
681   }
682 
683   const STACK_OF(CRYPTO_BUFFER) *names = hs->config->client_CA.get();
684   if (names == NULL) {
685     names = hs->ssl->ctx->client_CA.get();
686   }
687   if (names == NULL) {
688     return CBB_flush(cbb);
689   }
690 
691   for (const CRYPTO_BUFFER *name : names) {
692     if (!CBB_add_u16_length_prefixed(&child, &name_cbb) ||
693         !CBB_add_bytes(&name_cbb, CRYPTO_BUFFER_data(name),
694                        CRYPTO_BUFFER_len(name))) {
695       return false;
696     }
697   }
698 
699   return CBB_flush(cbb);
700 }
701 
ssl_check_leaf_certificate(SSL_HANDSHAKE * hs,EVP_PKEY * pkey,const CRYPTO_BUFFER * leaf)702 bool ssl_check_leaf_certificate(SSL_HANDSHAKE *hs, EVP_PKEY *pkey,
703                                 const CRYPTO_BUFFER *leaf) {
704   assert(ssl_protocol_version(hs->ssl) < TLS1_3_VERSION);
705 
706   // Check the certificate's type matches the cipher.
707   if (!(hs->new_cipher->algorithm_auth & ssl_cipher_auth_mask_for_key(pkey))) {
708     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CERTIFICATE_TYPE);
709     return false;
710   }
711 
712   if (EVP_PKEY_id(pkey) == EVP_PKEY_EC) {
713     // Check the key's group and point format are acceptable.
714     EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(pkey);
715     uint16_t group_id;
716     if (!ssl_nid_to_group_id(
717             &group_id, EC_GROUP_get_curve_name(EC_KEY_get0_group(ec_key))) ||
718         !tls1_check_group_id(hs, group_id) ||
719         EC_KEY_get_conv_form(ec_key) != POINT_CONVERSION_UNCOMPRESSED) {
720       OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ECC_CERT);
721       return false;
722     }
723   }
724 
725   return true;
726 }
727 
ssl_on_certificate_selected(SSL_HANDSHAKE * hs)728 bool ssl_on_certificate_selected(SSL_HANDSHAKE *hs) {
729   SSL *const ssl = hs->ssl;
730   if (!ssl_has_certificate(hs)) {
731     // Nothing to do.
732     return true;
733   }
734 
735   if (!ssl->ctx->x509_method->ssl_auto_chain_if_needed(hs)) {
736     return false;
737   }
738 
739   CBS leaf;
740   CRYPTO_BUFFER_init_CBS(
741       sk_CRYPTO_BUFFER_value(hs->config->cert->chain.get(), 0), &leaf);
742 
743   if (ssl_signing_with_dc(hs)) {
744     hs->local_pubkey = UpRef(hs->config->cert->dc->pkey);
745   } else {
746     hs->local_pubkey = ssl_cert_parse_pubkey(&leaf);
747   }
748   return hs->local_pubkey != NULL;
749 }
750 
751 
752 // Delegated credentials.
753 
754 DC::DC() = default;
755 DC::~DC() = default;
756 
Dup()757 UniquePtr<DC> DC::Dup() {
758   bssl::UniquePtr<DC> ret = MakeUnique<DC>();
759   if (!ret) {
760     return nullptr;
761   }
762 
763   ret->raw = UpRef(raw);
764   ret->expected_cert_verify_algorithm = expected_cert_verify_algorithm;
765   ret->pkey = UpRef(pkey);
766   return ret;
767 }
768 
769 // static
Parse(CRYPTO_BUFFER * in,uint8_t * out_alert)770 UniquePtr<DC> DC::Parse(CRYPTO_BUFFER *in, uint8_t *out_alert) {
771   UniquePtr<DC> dc = MakeUnique<DC>();
772   if (!dc) {
773     *out_alert = SSL_AD_INTERNAL_ERROR;
774     return nullptr;
775   }
776 
777   dc->raw = UpRef(in);
778 
779   CBS pubkey, deleg, sig;
780   uint32_t valid_time;
781   uint16_t algorithm;
782   CRYPTO_BUFFER_init_CBS(dc->raw.get(), &deleg);
783   if (!CBS_get_u32(&deleg, &valid_time) ||
784       !CBS_get_u16(&deleg, &dc->expected_cert_verify_algorithm) ||
785       !CBS_get_u24_length_prefixed(&deleg, &pubkey) ||
786       !CBS_get_u16(&deleg, &algorithm) ||
787       !CBS_get_u16_length_prefixed(&deleg, &sig) ||
788       CBS_len(&deleg) != 0) {
789     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
790     *out_alert = SSL_AD_DECODE_ERROR;
791     return nullptr;
792   }
793 
794   dc->pkey.reset(EVP_parse_public_key(&pubkey));
795   if (dc->pkey == nullptr) {
796     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
797     *out_alert = SSL_AD_DECODE_ERROR;
798     return nullptr;
799   }
800 
801   return dc;
802 }
803 
804 // ssl_can_serve_dc returns true if the host has configured a DC that it can
805 // serve in the handshake. Specifically, it checks that a DC has been
806 // configured and that the DC signature algorithm is supported by the peer.
ssl_can_serve_dc(const SSL_HANDSHAKE * hs)807 static bool ssl_can_serve_dc(const SSL_HANDSHAKE *hs) {
808   // Check that a DC has been configured.
809   const CERT *cert = hs->config->cert.get();
810   if (cert->dc == nullptr ||
811       cert->dc->raw == nullptr ||
812       (cert->dc_privatekey == nullptr && cert->dc_key_method == nullptr)) {
813     return false;
814   }
815 
816   // Check that 1.3 or higher has been negotiated.
817   const DC *dc = cert->dc.get();
818   assert(hs->ssl->s3->have_version);
819   if (ssl_protocol_version(hs->ssl) < TLS1_3_VERSION) {
820     return false;
821   }
822 
823   // Check that the DC signature algorithm is supported by the peer.
824   Span<const uint16_t> peer_sigalgs = tls1_get_peer_verify_algorithms(hs);
825   bool sigalg_found = false;
826   for (uint16_t peer_sigalg : peer_sigalgs) {
827     if (dc->expected_cert_verify_algorithm == peer_sigalg) {
828       sigalg_found = true;
829       break;
830     }
831   }
832 
833   return sigalg_found;
834 }
835 
ssl_signing_with_dc(const SSL_HANDSHAKE * hs)836 bool ssl_signing_with_dc(const SSL_HANDSHAKE *hs) {
837   // As of draft-ietf-tls-subcert-03, only the server may use delegated
838   // credentials to authenticate itself.
839   return hs->ssl->server &&
840          hs->delegated_credential_requested &&
841          ssl_can_serve_dc(hs);
842 }
843 
cert_set_dc(CERT * cert,CRYPTO_BUFFER * const raw,EVP_PKEY * privkey,const SSL_PRIVATE_KEY_METHOD * key_method)844 static int cert_set_dc(CERT *cert, CRYPTO_BUFFER *const raw, EVP_PKEY *privkey,
845                        const SSL_PRIVATE_KEY_METHOD *key_method) {
846   if (privkey == nullptr && key_method == nullptr) {
847     OPENSSL_PUT_ERROR(SSL, ERR_R_PASSED_NULL_PARAMETER);
848     return 0;
849   }
850 
851   if (privkey != nullptr && key_method != nullptr) {
852     OPENSSL_PUT_ERROR(SSL, SSL_R_CANNOT_HAVE_BOTH_PRIVKEY_AND_METHOD);
853     return 0;
854   }
855 
856   uint8_t alert;
857   UniquePtr<DC> dc = DC::Parse(raw, &alert);
858   if (dc == nullptr) {
859     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_DELEGATED_CREDENTIAL);
860     return 0;
861   }
862 
863   if (privkey) {
864     // Check that the public and private keys match.
865     if (!ssl_compare_public_and_private_key(dc->pkey.get(), privkey)) {
866       OPENSSL_PUT_ERROR(SSL, SSL_R_CERTIFICATE_AND_PRIVATE_KEY_MISMATCH);
867       return 0;
868     }
869   }
870 
871   cert->dc = std::move(dc);
872   cert->dc_privatekey = UpRef(privkey);
873   cert->dc_key_method = key_method;
874 
875   return 1;
876 }
877 
878 BSSL_NAMESPACE_END
879 
880 using namespace bssl;
881 
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)882 int SSL_set_chain_and_key(SSL *ssl, CRYPTO_BUFFER *const *certs,
883                           size_t num_certs, EVP_PKEY *privkey,
884                           const SSL_PRIVATE_KEY_METHOD *privkey_method) {
885   if (!ssl->config) {
886     return 0;
887   }
888   return cert_set_chain_and_key(ssl->config->cert.get(), certs, num_certs,
889                                 privkey, privkey_method);
890 }
891 
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)892 int SSL_CTX_set_chain_and_key(SSL_CTX *ctx, CRYPTO_BUFFER *const *certs,
893                               size_t num_certs, EVP_PKEY *privkey,
894                               const SSL_PRIVATE_KEY_METHOD *privkey_method) {
895   return cert_set_chain_and_key(ctx->cert.get(), certs, num_certs, privkey,
896                                 privkey_method);
897 }
898 
SSL_CTX_use_certificate_ASN1(SSL_CTX * ctx,size_t der_len,const uint8_t * der)899 int SSL_CTX_use_certificate_ASN1(SSL_CTX *ctx, size_t der_len,
900                                  const uint8_t *der) {
901   UniquePtr<CRYPTO_BUFFER> buffer(CRYPTO_BUFFER_new(der, der_len, NULL));
902   if (!buffer) {
903     return 0;
904   }
905 
906   return ssl_set_cert(ctx->cert.get(), std::move(buffer));
907 }
908 
SSL_use_certificate_ASN1(SSL * ssl,const uint8_t * der,size_t der_len)909 int SSL_use_certificate_ASN1(SSL *ssl, const uint8_t *der, size_t der_len) {
910   UniquePtr<CRYPTO_BUFFER> buffer(CRYPTO_BUFFER_new(der, der_len, NULL));
911   if (!buffer || !ssl->config) {
912     return 0;
913   }
914 
915   return ssl_set_cert(ssl->config->cert.get(), std::move(buffer));
916 }
917 
SSL_CTX_set_cert_cb(SSL_CTX * ctx,int (* cb)(SSL * ssl,void * arg),void * arg)918 void SSL_CTX_set_cert_cb(SSL_CTX *ctx, int (*cb)(SSL *ssl, void *arg),
919                          void *arg) {
920   ssl_cert_set_cert_cb(ctx->cert.get(), cb, arg);
921 }
922 
SSL_set_cert_cb(SSL * ssl,int (* cb)(SSL * ssl,void * arg),void * arg)923 void SSL_set_cert_cb(SSL *ssl, int (*cb)(SSL *ssl, void *arg), void *arg) {
924   if (!ssl->config) {
925     return;
926   }
927   ssl_cert_set_cert_cb(ssl->config->cert.get(), cb, arg);
928 }
929 
STACK_OF(CRYPTO_BUFFER)930 const STACK_OF(CRYPTO_BUFFER) *SSL_get0_peer_certificates(const SSL *ssl) {
931   SSL_SESSION *session = SSL_get_session(ssl);
932   if (session == NULL) {
933     return NULL;
934   }
935 
936   return session->certs.get();
937 }
938 
STACK_OF(CRYPTO_BUFFER)939 const STACK_OF(CRYPTO_BUFFER) *SSL_get0_server_requested_CAs(const SSL *ssl) {
940   if (ssl->s3->hs == NULL) {
941     return NULL;
942   }
943   return ssl->s3->hs->ca_names.get();
944 }
945 
set_signed_cert_timestamp_list(CERT * cert,const uint8_t * list,size_t list_len)946 static int set_signed_cert_timestamp_list(CERT *cert, const uint8_t *list,
947                                           size_t list_len) {
948   CBS sct_list;
949   CBS_init(&sct_list, list, list_len);
950   if (!ssl_is_sct_list_valid(&sct_list)) {
951     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_SCT_LIST);
952     return 0;
953   }
954 
955   cert->signed_cert_timestamp_list.reset(
956       CRYPTO_BUFFER_new(CBS_data(&sct_list), CBS_len(&sct_list), nullptr));
957   return cert->signed_cert_timestamp_list != nullptr;
958 }
959 
SSL_CTX_set_signed_cert_timestamp_list(SSL_CTX * ctx,const uint8_t * list,size_t list_len)960 int SSL_CTX_set_signed_cert_timestamp_list(SSL_CTX *ctx, const uint8_t *list,
961                                            size_t list_len) {
962   return set_signed_cert_timestamp_list(ctx->cert.get(), list, list_len);
963 }
964 
SSL_set_signed_cert_timestamp_list(SSL * ssl,const uint8_t * list,size_t list_len)965 int SSL_set_signed_cert_timestamp_list(SSL *ssl, const uint8_t *list,
966                                        size_t list_len) {
967   if (!ssl->config) {
968     return 0;
969   }
970   return set_signed_cert_timestamp_list(ssl->config->cert.get(), list,
971                                         list_len);
972 }
973 
SSL_CTX_set_ocsp_response(SSL_CTX * ctx,const uint8_t * response,size_t response_len)974 int SSL_CTX_set_ocsp_response(SSL_CTX *ctx, const uint8_t *response,
975                               size_t response_len) {
976   ctx->cert->ocsp_response.reset(
977       CRYPTO_BUFFER_new(response, response_len, nullptr));
978   return ctx->cert->ocsp_response != nullptr;
979 }
980 
SSL_set_ocsp_response(SSL * ssl,const uint8_t * response,size_t response_len)981 int SSL_set_ocsp_response(SSL *ssl, const uint8_t *response,
982                           size_t response_len) {
983   if (!ssl->config) {
984     return 0;
985   }
986   ssl->config->cert->ocsp_response.reset(
987       CRYPTO_BUFFER_new(response, response_len, nullptr));
988   return ssl->config->cert->ocsp_response != nullptr;
989 }
990 
SSL_CTX_set0_client_CAs(SSL_CTX * ctx,STACK_OF (CRYPTO_BUFFER)* name_list)991 void SSL_CTX_set0_client_CAs(SSL_CTX *ctx, STACK_OF(CRYPTO_BUFFER) *name_list) {
992   ctx->x509_method->ssl_ctx_flush_cached_client_CA(ctx);
993   ctx->client_CA.reset(name_list);
994 }
995 
SSL_set0_client_CAs(SSL * ssl,STACK_OF (CRYPTO_BUFFER)* name_list)996 void SSL_set0_client_CAs(SSL *ssl, STACK_OF(CRYPTO_BUFFER) *name_list) {
997   if (!ssl->config) {
998     return;
999   }
1000   ssl->ctx->x509_method->ssl_flush_cached_client_CA(ssl->config.get());
1001   ssl->config->client_CA.reset(name_list);
1002 }
1003 
SSL_set1_delegated_credential(SSL * ssl,CRYPTO_BUFFER * dc,EVP_PKEY * pkey,const SSL_PRIVATE_KEY_METHOD * key_method)1004 int SSL_set1_delegated_credential(SSL *ssl, CRYPTO_BUFFER *dc, EVP_PKEY *pkey,
1005                                   const SSL_PRIVATE_KEY_METHOD *key_method) {
1006   if (!ssl->config) {
1007     return 0;
1008   }
1009 
1010   return cert_set_dc(ssl->config->cert.get(), dc, pkey, key_method);
1011 }
1012 
SSL_delegated_credential_used(const SSL * ssl)1013 int SSL_delegated_credential_used(const SSL *ssl) {
1014   return ssl->s3->delegated_credential_used;
1015 }
1016