1 // Copyright 2019 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "net/test/cert_builder.h"
6
7 #include "base/files/file_path.h"
8 #include "base/memory/ptr_util.h"
9 #include "base/notreached.h"
10 #include "base/ranges/algorithm.h"
11 #include "base/strings/string_number_conversions.h"
12 #include "base/strings/string_util.h"
13 #include "base/time/time.h"
14 #include "crypto/ec_private_key.h"
15 #include "crypto/openssl_util.h"
16 #include "crypto/rsa_private_key.h"
17 #include "net/cert/asn1_util.h"
18 #include "net/cert/pki/certificate_policies.h"
19 #include "net/cert/pki/extended_key_usage.h"
20 #include "net/cert/pki/parse_certificate.h"
21 #include "net/cert/pki/verify_signed_data.h"
22 #include "net/cert/x509_util.h"
23 #include "net/der/encode_values.h"
24 #include "net/der/input.h"
25 #include "net/der/parse_values.h"
26 #include "net/der/parser.h"
27 #include "net/test/cert_test_util.h"
28 #include "net/test/key_util.h"
29 #include "net/test/test_data_directory.h"
30 #include "testing/gtest/include/gtest/gtest.h"
31 #include "third_party/abseil-cpp/absl/types/optional.h"
32 #include "third_party/boringssl/src/include/openssl/evp.h"
33 #include "third_party/boringssl/src/include/openssl/mem.h"
34 #include "url/gurl.h"
35
36 namespace net {
37
38 namespace {
39
40 constexpr char kSimpleChainHostname[] = "www.example.com";
41
Sha256WithRSAEncryption()42 std::string Sha256WithRSAEncryption() {
43 const uint8_t kSha256WithRSAEncryption[] = {0x30, 0x0D, 0x06, 0x09, 0x2a,
44 0x86, 0x48, 0x86, 0xf7, 0x0d,
45 0x01, 0x01, 0x0b, 0x05, 0x00};
46 return std::string(std::begin(kSha256WithRSAEncryption),
47 std::end(kSha256WithRSAEncryption));
48 }
49
Sha1WithRSAEncryption()50 std::string Sha1WithRSAEncryption() {
51 const uint8_t kSha1WithRSAEncryption[] = {0x30, 0x0D, 0x06, 0x09, 0x2a,
52 0x86, 0x48, 0x86, 0xf7, 0x0d,
53 0x01, 0x01, 0x05, 0x05, 0x00};
54 return std::string(std::begin(kSha1WithRSAEncryption),
55 std::end(kSha1WithRSAEncryption));
56 }
57
EcdsaWithSha256()58 std::string EcdsaWithSha256() {
59 const uint8_t kDer[] = {0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86,
60 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02};
61 return std::string(std::begin(kDer), std::end(kDer));
62 }
63
EcdsaWithSha1()64 std::string EcdsaWithSha1() {
65 const uint8_t kDer[] = {0x30, 0x09, 0x06, 0x07, 0x2a, 0x86,
66 0x48, 0xce, 0x3d, 0x04, 0x01};
67 return std::string(std::begin(kDer), std::end(kDer));
68 }
69
70 // Adds bytes (specified as a StringPiece) to the given CBB.
71 // The argument ordering follows the boringssl CBB_* api style.
CBBAddBytes(CBB * cbb,base::StringPiece bytes)72 bool CBBAddBytes(CBB* cbb, base::StringPiece bytes) {
73 return CBB_add_bytes(cbb, reinterpret_cast<const uint8_t*>(bytes.data()),
74 bytes.size());
75 }
76
77 // Adds bytes (from fixed size array) to the given CBB.
78 // The argument ordering follows the boringssl CBB_* api style.
79 template <size_t N>
CBBAddBytes(CBB * cbb,const uint8_t (& data)[N])80 bool CBBAddBytes(CBB* cbb, const uint8_t (&data)[N]) {
81 return CBB_add_bytes(cbb, data, N);
82 }
83
84 // Finalizes the CBB to a std::string.
FinishCBB(CBB * cbb)85 std::string FinishCBB(CBB* cbb) {
86 size_t cbb_len;
87 uint8_t* cbb_bytes;
88
89 if (!CBB_finish(cbb, &cbb_bytes, &cbb_len)) {
90 ADD_FAILURE() << "CBB_finish() failed";
91 return std::string();
92 }
93
94 bssl::UniquePtr<uint8_t> delete_bytes(cbb_bytes);
95 return std::string(reinterpret_cast<char*>(cbb_bytes), cbb_len);
96 }
97
98 // Finalizes the CBB to a std::vector.
FinishCBBToVector(CBB * cbb)99 std::vector<uint8_t> FinishCBBToVector(CBB* cbb) {
100 size_t cbb_len;
101 uint8_t* cbb_bytes;
102
103 if (!CBB_finish(cbb, &cbb_bytes, &cbb_len)) {
104 ADD_FAILURE() << "CBB_finish() failed";
105 return {};
106 }
107
108 bssl::UniquePtr<uint8_t> delete_bytes(cbb_bytes);
109 return std::vector<uint8_t>(cbb_bytes, cbb_bytes + cbb_len);
110 }
111
112 } // namespace
113
CertBuilder(CRYPTO_BUFFER * orig_cert,CertBuilder * issuer)114 CertBuilder::CertBuilder(CRYPTO_BUFFER* orig_cert, CertBuilder* issuer)
115 : CertBuilder(orig_cert, issuer, /*unique_subject_key_identifier=*/true) {}
116
117 // static
FromFile(const base::FilePath & cert_and_key_file,CertBuilder * issuer)118 std::unique_ptr<CertBuilder> CertBuilder::FromFile(
119 const base::FilePath& cert_and_key_file,
120 CertBuilder* issuer) {
121 scoped_refptr<X509Certificate> cert = ImportCertFromFile(cert_and_key_file);
122 if (!cert)
123 return nullptr;
124
125 bssl::UniquePtr<EVP_PKEY> private_key(
126 key_util::LoadEVP_PKEYFromPEM(cert_and_key_file));
127 if (!private_key)
128 return nullptr;
129
130 auto builder = base::WrapUnique(new CertBuilder(cert->cert_buffer(), issuer));
131 builder->key_ = std::move(private_key);
132 return builder;
133 }
134
135 // static
FromStaticCert(CRYPTO_BUFFER * cert,EVP_PKEY * key)136 std::unique_ptr<CertBuilder> CertBuilder::FromStaticCert(CRYPTO_BUFFER* cert,
137 EVP_PKEY* key) {
138 std::unique_ptr<CertBuilder> builder = base::WrapUnique(
139 new CertBuilder(cert, nullptr, /*unique_subject_key_identifier=*/false));
140 // |cert_|, |key_|, and |subject_tlv_| must be initialized for |builder| to
141 // function as the |issuer| of another CertBuilder.
142 builder->cert_ = bssl::UpRef(cert);
143 builder->key_ = bssl::UpRef(key);
144 base::StringPiece subject_tlv;
145 CHECK(asn1::ExtractSubjectFromDERCert(
146 x509_util::CryptoBufferAsStringPiece(cert), &subject_tlv));
147 builder->subject_tlv_ = std::string(subject_tlv);
148 return builder;
149 }
150
151 // static
FromStaticCertFile(const base::FilePath & cert_and_key_file)152 std::unique_ptr<CertBuilder> CertBuilder::FromStaticCertFile(
153 const base::FilePath& cert_and_key_file) {
154 scoped_refptr<X509Certificate> cert = ImportCertFromFile(cert_and_key_file);
155 if (!cert)
156 return nullptr;
157
158 bssl::UniquePtr<EVP_PKEY> private_key(
159 key_util::LoadEVP_PKEYFromPEM(cert_and_key_file));
160 if (!private_key)
161 return nullptr;
162
163 return CertBuilder::FromStaticCert(cert->cert_buffer(), private_key.get());
164 }
165
166 // static
FromSubjectPublicKeyInfo(base::span<const uint8_t> spki_der,CertBuilder * issuer)167 std::unique_ptr<CertBuilder> CertBuilder::FromSubjectPublicKeyInfo(
168 base::span<const uint8_t> spki_der,
169 CertBuilder* issuer) {
170 DCHECK(issuer);
171 auto builder = std::make_unique<CertBuilder>(/*orig_cert=*/nullptr, issuer);
172
173 CBS cbs;
174 CBS_init(&cbs, spki_der.data(), spki_der.size());
175 builder->key_ = bssl::UniquePtr<EVP_PKEY>(EVP_parse_public_key(&cbs));
176 // Check that there was no error in `EVP_parse_public_key` and that it
177 // consumed the entire public key.
178 if (!builder->key_ || (CBS_len(&cbs) != 0))
179 return nullptr;
180
181 return builder;
182 }
183
184 CertBuilder::~CertBuilder() = default;
185
186 // static
CreateSimpleChain(size_t chain_length)187 std::vector<std::unique_ptr<CertBuilder>> CertBuilder::CreateSimpleChain(
188 size_t chain_length) {
189 std::vector<std::unique_ptr<CertBuilder>> chain;
190 base::Time not_before = base::Time::Now() - base::Days(7);
191 base::Time not_after = base::Time::Now() + base::Days(7);
192 CertBuilder* parent_builder = nullptr;
193 for (size_t remaining_chain_length = chain_length; remaining_chain_length;
194 remaining_chain_length--) {
195 auto builder = std::make_unique<CertBuilder>(nullptr, parent_builder);
196 builder->SetValidity(not_before, not_after);
197 if (remaining_chain_length > 1) {
198 // CA properties:
199 builder->SetBasicConstraints(/*is_ca=*/true, /*path_len=*/-1);
200 builder->SetKeyUsages(
201 {KEY_USAGE_BIT_KEY_CERT_SIGN, KEY_USAGE_BIT_CRL_SIGN});
202 } else {
203 // Leaf properties:
204 builder->SetBasicConstraints(/*is_ca=*/false, /*path_len=*/-1);
205 builder->SetKeyUsages({KEY_USAGE_BIT_DIGITAL_SIGNATURE});
206 builder->SetExtendedKeyUsages({der::Input(kServerAuth)});
207 builder->SetSubjectAltName(kSimpleChainHostname);
208 }
209 parent_builder = builder.get();
210 chain.push_back(std::move(builder));
211 }
212 base::ranges::reverse(chain);
213 return chain;
214 }
215
216 // static
CreateSimpleChain3()217 std::array<std::unique_ptr<CertBuilder>, 3> CertBuilder::CreateSimpleChain3() {
218 auto chain = CreateSimpleChain(3);
219 return {std::move(chain[0]), std::move(chain[1]), std::move(chain[2])};
220 }
221
222 // static
CreateSimpleChain2()223 std::array<std::unique_ptr<CertBuilder>, 2> CertBuilder::CreateSimpleChain2() {
224 auto chain = CreateSimpleChain(2);
225 return {std::move(chain[0]), std::move(chain[1])};
226 }
227
228 // static
DefaultSignatureAlgorithmForKey(EVP_PKEY * key)229 absl::optional<SignatureAlgorithm> CertBuilder::DefaultSignatureAlgorithmForKey(
230 EVP_PKEY* key) {
231 if (EVP_PKEY_id(key) == EVP_PKEY_RSA)
232 return SignatureAlgorithm::kRsaPkcs1Sha256;
233 if (EVP_PKEY_id(key) == EVP_PKEY_EC)
234 return SignatureAlgorithm::kEcdsaSha256;
235 return absl::nullopt;
236 }
237
238 // static
SignData(SignatureAlgorithm signature_algorithm,base::StringPiece tbs_data,EVP_PKEY * key,CBB * out_signature)239 bool CertBuilder::SignData(SignatureAlgorithm signature_algorithm,
240 base::StringPiece tbs_data,
241 EVP_PKEY* key,
242 CBB* out_signature) {
243 if (!key)
244 return false;
245
246 int expected_pkey_id = 1;
247 const EVP_MD* digest;
248 switch (signature_algorithm) {
249 case SignatureAlgorithm::kRsaPkcs1Sha1:
250 expected_pkey_id = EVP_PKEY_RSA;
251 digest = EVP_sha1();
252 break;
253 case SignatureAlgorithm::kRsaPkcs1Sha256:
254 expected_pkey_id = EVP_PKEY_RSA;
255 digest = EVP_sha256();
256 break;
257 case SignatureAlgorithm::kRsaPkcs1Sha384:
258 expected_pkey_id = EVP_PKEY_RSA;
259 digest = EVP_sha384();
260 break;
261 case SignatureAlgorithm::kRsaPkcs1Sha512:
262 expected_pkey_id = EVP_PKEY_RSA;
263 digest = EVP_sha512();
264 break;
265
266 case SignatureAlgorithm::kEcdsaSha1:
267 expected_pkey_id = EVP_PKEY_EC;
268 digest = EVP_sha1();
269 break;
270 case SignatureAlgorithm::kEcdsaSha256:
271 expected_pkey_id = EVP_PKEY_EC;
272 digest = EVP_sha256();
273 break;
274 case SignatureAlgorithm::kEcdsaSha384:
275 expected_pkey_id = EVP_PKEY_EC;
276 digest = EVP_sha384();
277 break;
278 case SignatureAlgorithm::kEcdsaSha512:
279 expected_pkey_id = EVP_PKEY_EC;
280 digest = EVP_sha512();
281 break;
282
283 case SignatureAlgorithm::kRsaPssSha256:
284 case SignatureAlgorithm::kRsaPssSha384:
285 case SignatureAlgorithm::kRsaPssSha512:
286 // Unsupported algorithms.
287 return false;
288 }
289
290 return expected_pkey_id == EVP_PKEY_id(key) &&
291 SignDataWithDigest(digest, tbs_data, key, out_signature);
292 }
293
294 // static
SignDataWithDigest(const EVP_MD * digest,base::StringPiece tbs_data,EVP_PKEY * key,CBB * out_signature)295 bool CertBuilder::SignDataWithDigest(const EVP_MD* digest,
296 base::StringPiece tbs_data,
297 EVP_PKEY* key,
298 CBB* out_signature) {
299 const uint8_t* tbs_bytes = reinterpret_cast<const uint8_t*>(tbs_data.data());
300 bssl::ScopedEVP_MD_CTX ctx;
301 uint8_t* sig_out;
302 size_t sig_len;
303
304 return EVP_DigestSignInit(ctx.get(), nullptr, digest, nullptr, key) &&
305 EVP_DigestSign(ctx.get(), nullptr, &sig_len, tbs_bytes,
306 tbs_data.size()) &&
307 CBB_reserve(out_signature, &sig_out, sig_len) &&
308 EVP_DigestSign(ctx.get(), sig_out, &sig_len, tbs_bytes,
309 tbs_data.size()) &&
310 CBB_did_write(out_signature, sig_len);
311 }
312
313 // static
SignatureAlgorithmToDer(SignatureAlgorithm signature_algorithm)314 std::string CertBuilder::SignatureAlgorithmToDer(
315 SignatureAlgorithm signature_algorithm) {
316 switch (signature_algorithm) {
317 case SignatureAlgorithm::kRsaPkcs1Sha1:
318 return Sha1WithRSAEncryption();
319 case SignatureAlgorithm::kRsaPkcs1Sha256:
320 return Sha256WithRSAEncryption();
321 case SignatureAlgorithm::kEcdsaSha1:
322 return EcdsaWithSha1();
323 case SignatureAlgorithm::kEcdsaSha256:
324 return EcdsaWithSha256();
325 default:
326 ADD_FAILURE();
327 return std::string();
328 }
329 }
330
331 // static
MakeRandomHexString(size_t num_bytes)332 std::string CertBuilder::MakeRandomHexString(size_t num_bytes) {
333 std::vector<char> rand_bytes;
334 rand_bytes.resize(num_bytes);
335
336 base::RandBytes(rand_bytes.data(), rand_bytes.size());
337 return base::HexEncode(rand_bytes.data(), rand_bytes.size());
338 }
339
340 // static
BuildNameWithCommonNameOfType(base::StringPiece common_name,unsigned common_name_tag)341 std::vector<uint8_t> CertBuilder::BuildNameWithCommonNameOfType(
342 base::StringPiece common_name,
343 unsigned common_name_tag) {
344 // See RFC 4519.
345 static const uint8_t kCommonName[] = {0x55, 0x04, 0x03};
346
347 // See RFC 5280, section 4.1.2.4.
348 bssl::ScopedCBB cbb;
349 CBB rdns, rdn, attr, type, value;
350 if (!CBB_init(cbb.get(), 64) ||
351 !CBB_add_asn1(cbb.get(), &rdns, CBS_ASN1_SEQUENCE) ||
352 !CBB_add_asn1(&rdns, &rdn, CBS_ASN1_SET) ||
353 !CBB_add_asn1(&rdn, &attr, CBS_ASN1_SEQUENCE) ||
354 !CBB_add_asn1(&attr, &type, CBS_ASN1_OBJECT) ||
355 !CBBAddBytes(&type, kCommonName) ||
356 !CBB_add_asn1(&attr, &value, common_name_tag) ||
357 !CBBAddBytes(&value, common_name)) {
358 ADD_FAILURE();
359 return {};
360 }
361
362 return FinishCBBToVector(cbb.get());
363 }
364
SetCertificateVersion(CertificateVersion version)365 void CertBuilder::SetCertificateVersion(CertificateVersion version) {
366 version_ = version;
367 Invalidate();
368 }
369
SetExtension(const der::Input & oid,std::string value,bool critical)370 void CertBuilder::SetExtension(const der::Input& oid,
371 std::string value,
372 bool critical) {
373 auto& extension_value = extensions_[oid.AsString()];
374 extension_value.critical = critical;
375 extension_value.value = std::move(value);
376
377 Invalidate();
378 }
379
EraseExtension(const der::Input & oid)380 void CertBuilder::EraseExtension(const der::Input& oid) {
381 extensions_.erase(oid.AsString());
382
383 Invalidate();
384 }
385
ClearExtensions()386 void CertBuilder::ClearExtensions() {
387 extensions_.clear();
388 Invalidate();
389 }
390
SetBasicConstraints(bool is_ca,int path_len)391 void CertBuilder::SetBasicConstraints(bool is_ca, int path_len) {
392 // From RFC 5280:
393 //
394 // BasicConstraints ::= SEQUENCE {
395 // cA BOOLEAN DEFAULT FALSE,
396 // pathLenConstraint INTEGER (0..MAX) OPTIONAL }
397 bssl::ScopedCBB cbb;
398 CBB basic_constraints;
399 ASSERT_TRUE(CBB_init(cbb.get(), 64));
400 ASSERT_TRUE(CBB_add_asn1(cbb.get(), &basic_constraints, CBS_ASN1_SEQUENCE));
401 if (is_ca)
402 ASSERT_TRUE(CBB_add_asn1_bool(&basic_constraints, true));
403 if (path_len >= 0)
404 ASSERT_TRUE(CBB_add_asn1_uint64(&basic_constraints, path_len));
405
406 SetExtension(der::Input(kBasicConstraintsOid), FinishCBB(cbb.get()),
407 /*critical=*/true);
408 }
409
410 namespace {
AddNameConstraintsSubTrees(CBB * cbb,const std::vector<std::string> & dns_names)411 void AddNameConstraintsSubTrees(CBB* cbb,
412 const std::vector<std::string>& dns_names) {
413 CBB subtrees;
414 ASSERT_TRUE(CBB_add_asn1(
415 cbb, &subtrees, CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0));
416 for (const auto& name : dns_names) {
417 CBB subtree;
418 ASSERT_TRUE(CBB_add_asn1(&subtrees, &subtree, CBS_ASN1_SEQUENCE));
419 CBB general_name;
420 ASSERT_TRUE(
421 CBB_add_asn1(&subtree, &general_name, CBS_ASN1_CONTEXT_SPECIFIC | 2));
422 ASSERT_TRUE(CBBAddBytes(&general_name, name));
423 ASSERT_TRUE(CBB_flush(&subtrees));
424 }
425 ASSERT_TRUE(CBB_flush(cbb));
426 }
427 } // namespace
428
SetNameConstraintsDnsNames(const std::vector<std::string> & permitted_dns_names,const std::vector<std::string> & excluded_dns_names)429 void CertBuilder::SetNameConstraintsDnsNames(
430 const std::vector<std::string>& permitted_dns_names,
431 const std::vector<std::string>& excluded_dns_names) {
432 // From RFC 5280:
433 //
434 // id-ce-nameConstraints OBJECT IDENTIFIER ::= { id-ce 30 }
435 //
436 // NameConstraints ::= SEQUENCE {
437 // permittedSubtrees [0] GeneralSubtrees OPTIONAL,
438 // excludedSubtrees [1] GeneralSubtrees OPTIONAL }
439 //
440 // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
441 //
442 // GeneralSubtree ::= SEQUENCE {
443 // base GeneralName,
444 // minimum [0] BaseDistance DEFAULT 0,
445 // maximum [1] BaseDistance OPTIONAL }
446 //
447 // BaseDistance ::= INTEGER (0..MAX)
448
449 if (permitted_dns_names.empty() && excluded_dns_names.empty()) {
450 EraseExtension(der::Input(kNameConstraintsOid));
451 return;
452 }
453
454 bssl::ScopedCBB cbb;
455 CBB name_constraints;
456 ASSERT_TRUE(CBB_init(cbb.get(), 64));
457 ASSERT_TRUE(CBB_add_asn1(cbb.get(), &name_constraints, CBS_ASN1_SEQUENCE));
458 if (!permitted_dns_names.empty()) {
459 ASSERT_NO_FATAL_FAILURE(
460 AddNameConstraintsSubTrees(&name_constraints, permitted_dns_names));
461 }
462 if (!excluded_dns_names.empty()) {
463 ASSERT_NO_FATAL_FAILURE(
464 AddNameConstraintsSubTrees(&name_constraints, excluded_dns_names));
465 }
466 SetExtension(der::Input(kNameConstraintsOid), FinishCBB(cbb.get()),
467 /*critical=*/true);
468 }
469
SetCaIssuersUrl(const GURL & url)470 void CertBuilder::SetCaIssuersUrl(const GURL& url) {
471 SetCaIssuersAndOCSPUrls({url}, {});
472 }
473
SetCaIssuersAndOCSPUrls(const std::vector<GURL> & ca_issuers_urls,const std::vector<GURL> & ocsp_urls)474 void CertBuilder::SetCaIssuersAndOCSPUrls(
475 const std::vector<GURL>& ca_issuers_urls,
476 const std::vector<GURL>& ocsp_urls) {
477 std::vector<std::pair<der::Input, GURL>> entries;
478 for (const auto& url : ca_issuers_urls)
479 entries.emplace_back(der::Input(kAdCaIssuersOid), url);
480 for (const auto& url : ocsp_urls)
481 entries.emplace_back(der::Input(kAdOcspOid), url);
482
483 if (entries.empty()) {
484 EraseExtension(der::Input(kAuthorityInfoAccessOid));
485 return;
486 }
487
488 // From RFC 5280:
489 //
490 // AuthorityInfoAccessSyntax ::=
491 // SEQUENCE SIZE (1..MAX) OF AccessDescription
492 //
493 // AccessDescription ::= SEQUENCE {
494 // accessMethod OBJECT IDENTIFIER,
495 // accessLocation GeneralName }
496 bssl::ScopedCBB cbb;
497 CBB aia;
498 ASSERT_TRUE(CBB_init(cbb.get(), 64));
499 ASSERT_TRUE(CBB_add_asn1(cbb.get(), &aia, CBS_ASN1_SEQUENCE));
500
501 for (const auto& entry : entries) {
502 CBB access_description, access_method, access_location;
503 ASSERT_TRUE(CBB_add_asn1(&aia, &access_description, CBS_ASN1_SEQUENCE));
504 ASSERT_TRUE(
505 CBB_add_asn1(&access_description, &access_method, CBS_ASN1_OBJECT));
506 ASSERT_TRUE(CBBAddBytes(&access_method, entry.first.AsStringView()));
507 ASSERT_TRUE(CBB_add_asn1(&access_description, &access_location,
508 CBS_ASN1_CONTEXT_SPECIFIC | 6));
509 ASSERT_TRUE(CBBAddBytes(&access_location, entry.second.spec()));
510 ASSERT_TRUE(CBB_flush(&aia));
511 }
512
513 SetExtension(der::Input(kAuthorityInfoAccessOid), FinishCBB(cbb.get()));
514 }
515
SetCrlDistributionPointUrl(const GURL & url)516 void CertBuilder::SetCrlDistributionPointUrl(const GURL& url) {
517 SetCrlDistributionPointUrls({url});
518 }
519
SetCrlDistributionPointUrls(const std::vector<GURL> & urls)520 void CertBuilder::SetCrlDistributionPointUrls(const std::vector<GURL>& urls) {
521 bssl::ScopedCBB cbb;
522 ASSERT_TRUE(CBB_init(cbb.get(), 64));
523 CBB dps, dp, dp_name, dp_fullname;
524
525 // CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
526 ASSERT_TRUE(CBB_add_asn1(cbb.get(), &dps, CBS_ASN1_SEQUENCE));
527
528 // DistributionPoint ::= SEQUENCE {
529 // distributionPoint [0] DistributionPointName OPTIONAL,
530 // reasons [1] ReasonFlags OPTIONAL,
531 // cRLIssuer [2] GeneralNames OPTIONAL }
532 ASSERT_TRUE(CBB_add_asn1(&dps, &dp, CBS_ASN1_SEQUENCE));
533 ASSERT_TRUE(CBB_add_asn1(
534 &dp, &dp_name, CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0));
535
536 // DistributionPointName ::= CHOICE {
537 // fullName [0] GeneralNames,
538 // nameRelativeToCRLIssuer [1] RelativeDistinguishedName }
539 ASSERT_TRUE(
540 CBB_add_asn1(&dp_name, &dp_fullname,
541 CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0));
542
543 // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
544 // GeneralName ::= CHOICE {
545 // uniformResourceIdentifier [6] IA5String,
546 for (const auto& url : urls) {
547 CBB dp_url;
548 ASSERT_TRUE(
549 CBB_add_asn1(&dp_fullname, &dp_url, CBS_ASN1_CONTEXT_SPECIFIC | 6));
550 ASSERT_TRUE(CBBAddBytes(&dp_url, url.spec()));
551 ASSERT_TRUE(CBB_flush(&dp_fullname));
552 }
553
554 SetExtension(der::Input(kCrlDistributionPointsOid), FinishCBB(cbb.get()));
555 }
556
SetIssuerTLV(base::span<const uint8_t> issuer_tlv)557 void CertBuilder::SetIssuerTLV(base::span<const uint8_t> issuer_tlv) {
558 if (issuer_tlv.empty())
559 issuer_tlv_ = absl::nullopt;
560 else
561 issuer_tlv_ = std::string(issuer_tlv.begin(), issuer_tlv.end());
562 Invalidate();
563 }
564
SetSubjectCommonName(base::StringPiece common_name)565 void CertBuilder::SetSubjectCommonName(base::StringPiece common_name) {
566 SetSubjectTLV(
567 BuildNameWithCommonNameOfType(common_name, CBS_ASN1_UTF8STRING));
568 Invalidate();
569 }
570
SetSubjectTLV(base::span<const uint8_t> subject_tlv)571 void CertBuilder::SetSubjectTLV(base::span<const uint8_t> subject_tlv) {
572 subject_tlv_.assign(subject_tlv.begin(), subject_tlv.end());
573 Invalidate();
574 }
575
SetSubjectAltName(base::StringPiece dns_name)576 void CertBuilder::SetSubjectAltName(base::StringPiece dns_name) {
577 SetSubjectAltNames({std::string(dns_name)}, {});
578 }
579
SetSubjectAltNames(const std::vector<std::string> & dns_names,const std::vector<IPAddress> & ip_addresses)580 void CertBuilder::SetSubjectAltNames(
581 const std::vector<std::string>& dns_names,
582 const std::vector<IPAddress>& ip_addresses) {
583 // From RFC 5280:
584 //
585 // SubjectAltName ::= GeneralNames
586 //
587 // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
588 //
589 // GeneralName ::= CHOICE {
590 // ...
591 // dNSName [2] IA5String,
592 // ...
593 // iPAddress [7] OCTET STRING,
594 // ... }
595 ASSERT_GT(dns_names.size() + ip_addresses.size(), 0U);
596 bssl::ScopedCBB cbb;
597 CBB general_names;
598 ASSERT_TRUE(CBB_init(cbb.get(), 64));
599 ASSERT_TRUE(CBB_add_asn1(cbb.get(), &general_names, CBS_ASN1_SEQUENCE));
600 if (!dns_names.empty()) {
601 for (const auto& name : dns_names) {
602 CBB general_name;
603 ASSERT_TRUE(CBB_add_asn1(&general_names, &general_name,
604 CBS_ASN1_CONTEXT_SPECIFIC | 2));
605 ASSERT_TRUE(CBBAddBytes(&general_name, name));
606 ASSERT_TRUE(CBB_flush(&general_names));
607 }
608 }
609 if (!ip_addresses.empty()) {
610 for (const auto& addr : ip_addresses) {
611 CBB general_name;
612 ASSERT_TRUE(CBB_add_asn1(&general_names, &general_name,
613 CBS_ASN1_CONTEXT_SPECIFIC | 7));
614 ASSERT_TRUE(
615 CBB_add_bytes(&general_name, addr.bytes().data(), addr.size()));
616 ASSERT_TRUE(CBB_flush(&general_names));
617 }
618 }
619 SetExtension(der::Input(kSubjectAltNameOid), FinishCBB(cbb.get()));
620 }
621
SetKeyUsages(const std::vector<KeyUsageBit> & usages)622 void CertBuilder::SetKeyUsages(const std::vector<KeyUsageBit>& usages) {
623 ASSERT_GT(usages.size(), 0U);
624 int number_of_unused_bits = 0;
625 std::vector<uint8_t> bytes;
626 for (auto usage : usages) {
627 int bit_index = static_cast<int>(usage);
628
629 // Index of the byte that contains the bit.
630 size_t byte_index = bit_index / 8;
631
632 if (byte_index + 1 > bytes.size()) {
633 bytes.resize(byte_index + 1);
634 number_of_unused_bits = 8;
635 }
636
637 // Within a byte, bits are ordered from most significant to least
638 // significant. Convert |bit_index| to an index within the |byte_index|
639 // byte, measured from its least significant bit.
640 uint8_t bit_index_in_byte = 7 - (bit_index - byte_index * 8);
641
642 if (byte_index + 1 == bytes.size() &&
643 bit_index_in_byte < number_of_unused_bits) {
644 number_of_unused_bits = bit_index_in_byte;
645 }
646
647 bytes[byte_index] |= (1 << bit_index_in_byte);
648 }
649
650 // From RFC 5290:
651 // KeyUsage ::= BIT STRING {...}
652 bssl::ScopedCBB cbb;
653 CBB ku_cbb;
654 ASSERT_TRUE(CBB_init(cbb.get(), bytes.size() + 1));
655 ASSERT_TRUE(CBB_add_asn1(cbb.get(), &ku_cbb, CBS_ASN1_BITSTRING));
656 ASSERT_TRUE(CBB_add_u8(&ku_cbb, number_of_unused_bits));
657 ASSERT_TRUE(CBB_add_bytes(&ku_cbb, bytes.data(), bytes.size()));
658 SetExtension(der::Input(kKeyUsageOid), FinishCBB(cbb.get()),
659 /*critical=*/true);
660 }
661
SetExtendedKeyUsages(const std::vector<der::Input> & purpose_oids)662 void CertBuilder::SetExtendedKeyUsages(
663 const std::vector<der::Input>& purpose_oids) {
664 // From RFC 5280:
665 // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
666 // KeyPurposeId ::= OBJECT IDENTIFIER
667 ASSERT_GT(purpose_oids.size(), 0U);
668 bssl::ScopedCBB cbb;
669 CBB eku;
670 ASSERT_TRUE(CBB_init(cbb.get(), 64));
671 ASSERT_TRUE(CBB_add_asn1(cbb.get(), &eku, CBS_ASN1_SEQUENCE));
672
673 for (const auto& oid : purpose_oids) {
674 CBB purpose_cbb;
675 ASSERT_TRUE(CBB_add_asn1(&eku, &purpose_cbb, CBS_ASN1_OBJECT));
676 ASSERT_TRUE(CBBAddBytes(&purpose_cbb, oid.AsStringView()));
677 ASSERT_TRUE(CBB_flush(&eku));
678 }
679 SetExtension(der::Input(kExtKeyUsageOid), FinishCBB(cbb.get()));
680 }
681
SetCertificatePolicies(const std::vector<std::string> & policy_oids)682 void CertBuilder::SetCertificatePolicies(
683 const std::vector<std::string>& policy_oids) {
684 // From RFC 5280:
685 // certificatePolicies ::= SEQUENCE SIZE (1..MAX) OF PolicyInformation
686 //
687 // PolicyInformation ::= SEQUENCE {
688 // policyIdentifier CertPolicyId,
689 // policyQualifiers SEQUENCE SIZE (1..MAX) OF
690 // PolicyQualifierInfo OPTIONAL }
691 //
692 // CertPolicyId ::= OBJECT IDENTIFIER
693 if (policy_oids.empty()) {
694 EraseExtension(der::Input(kCertificatePoliciesOid));
695 return;
696 }
697
698 bssl::ScopedCBB cbb;
699 CBB certificate_policies;
700 ASSERT_TRUE(CBB_init(cbb.get(), 64));
701 ASSERT_TRUE(
702 CBB_add_asn1(cbb.get(), &certificate_policies, CBS_ASN1_SEQUENCE));
703 for (const auto& oid : policy_oids) {
704 CBB policy_information, policy_identifier;
705 ASSERT_TRUE(CBB_add_asn1(&certificate_policies, &policy_information,
706 CBS_ASN1_SEQUENCE));
707 ASSERT_TRUE(
708 CBB_add_asn1(&policy_information, &policy_identifier, CBS_ASN1_OBJECT));
709 ASSERT_TRUE(
710 CBB_add_asn1_oid_from_text(&policy_identifier, oid.data(), oid.size()));
711 ASSERT_TRUE(CBB_flush(&certificate_policies));
712 }
713
714 SetExtension(der::Input(kCertificatePoliciesOid), FinishCBB(cbb.get()));
715 }
716
SetPolicyMappings(const std::vector<std::pair<std::string,std::string>> & policy_mappings)717 void CertBuilder::SetPolicyMappings(
718 const std::vector<std::pair<std::string, std::string>>& policy_mappings) {
719 // From RFC 5280:
720 // PolicyMappings ::= SEQUENCE SIZE (1..MAX) OF SEQUENCE {
721 // issuerDomainPolicy CertPolicyId,
722 // subjectDomainPolicy CertPolicyId }
723 if (policy_mappings.empty()) {
724 EraseExtension(der::Input(kPolicyMappingsOid));
725 return;
726 }
727
728 bssl::ScopedCBB cbb;
729 CBB mappings_sequence;
730 ASSERT_TRUE(CBB_init(cbb.get(), 64));
731 ASSERT_TRUE(CBB_add_asn1(cbb.get(), &mappings_sequence, CBS_ASN1_SEQUENCE));
732 for (const auto& [issuer_domain_policy, subject_domain_policy] :
733 policy_mappings) {
734 CBB mapping_sequence;
735 CBB issuer_policy_object;
736 CBB subject_policy_object;
737 ASSERT_TRUE(
738 CBB_add_asn1(&mappings_sequence, &mapping_sequence, CBS_ASN1_SEQUENCE));
739
740 ASSERT_TRUE(CBB_add_asn1(&mapping_sequence, &issuer_policy_object,
741 CBS_ASN1_OBJECT));
742 ASSERT_TRUE(CBB_add_asn1_oid_from_text(&issuer_policy_object,
743 issuer_domain_policy.data(),
744 issuer_domain_policy.size()));
745
746 ASSERT_TRUE(CBB_add_asn1(&mapping_sequence, &subject_policy_object,
747 CBS_ASN1_OBJECT));
748 ASSERT_TRUE(CBB_add_asn1_oid_from_text(&subject_policy_object,
749 subject_domain_policy.data(),
750 subject_domain_policy.size()));
751
752 ASSERT_TRUE(CBB_flush(&mappings_sequence));
753 }
754
755 SetExtension(der::Input(kPolicyMappingsOid), FinishCBB(cbb.get()),
756 /*critical=*/true);
757 }
758
SetPolicyConstraints(absl::optional<uint64_t> require_explicit_policy,absl::optional<uint64_t> inhibit_policy_mapping)759 void CertBuilder::SetPolicyConstraints(
760 absl::optional<uint64_t> require_explicit_policy,
761 absl::optional<uint64_t> inhibit_policy_mapping) {
762 if (!require_explicit_policy.has_value() &&
763 !inhibit_policy_mapping.has_value()) {
764 EraseExtension(der::Input(kPolicyConstraintsOid));
765 return;
766 }
767
768 // From RFC 5280:
769 // PolicyConstraints ::= SEQUENCE {
770 // requireExplicitPolicy [0] SkipCerts OPTIONAL,
771 // inhibitPolicyMapping [1] SkipCerts OPTIONAL }
772 //
773 // SkipCerts ::= INTEGER (0..MAX)
774 bssl::ScopedCBB cbb;
775 CBB policy_constraints;
776 ASSERT_TRUE(CBB_init(cbb.get(), 64));
777 ASSERT_TRUE(CBB_add_asn1(cbb.get(), &policy_constraints, CBS_ASN1_SEQUENCE));
778 if (require_explicit_policy.has_value()) {
779 ASSERT_TRUE(CBB_add_asn1_uint64_with_tag(&policy_constraints,
780 *require_explicit_policy,
781 der::ContextSpecificPrimitive(0)));
782 }
783 if (inhibit_policy_mapping.has_value()) {
784 ASSERT_TRUE(CBB_add_asn1_uint64_with_tag(&policy_constraints,
785 *inhibit_policy_mapping,
786 der::ContextSpecificPrimitive(1)));
787 }
788
789 SetExtension(der::Input(kPolicyConstraintsOid), FinishCBB(cbb.get()),
790 /*critical=*/true);
791 }
792
SetInhibitAnyPolicy(uint64_t skip_certs)793 void CertBuilder::SetInhibitAnyPolicy(uint64_t skip_certs) {
794 // From RFC 5280:
795 // id-ce-inhibitAnyPolicy OBJECT IDENTIFIER ::= { id-ce 54 }
796 //
797 // InhibitAnyPolicy ::= SkipCerts
798 //
799 // SkipCerts ::= INTEGER (0..MAX)
800 bssl::ScopedCBB cbb;
801 ASSERT_TRUE(CBB_init(cbb.get(), 64));
802 ASSERT_TRUE(CBB_add_asn1_uint64(cbb.get(), skip_certs));
803 SetExtension(der::Input(kInhibitAnyPolicyOid), FinishCBB(cbb.get()),
804 /*critical=*/true);
805 }
806
SetValidity(base::Time not_before,base::Time not_after)807 void CertBuilder::SetValidity(base::Time not_before, base::Time not_after) {
808 // From RFC 5280:
809 // Validity ::= SEQUENCE {
810 // notBefore Time,
811 // notAfter Time }
812 bssl::ScopedCBB cbb;
813 CBB validity;
814 ASSERT_TRUE(CBB_init(cbb.get(), 64));
815 ASSERT_TRUE(CBB_add_asn1(cbb.get(), &validity, CBS_ASN1_SEQUENCE));
816 ASSERT_TRUE(x509_util::CBBAddTime(&validity, not_before));
817 ASSERT_TRUE(x509_util::CBBAddTime(&validity, not_after));
818 validity_tlv_ = FinishCBB(cbb.get());
819 Invalidate();
820 }
821
SetSubjectKeyIdentifier(const std::string & subject_key_identifier)822 void CertBuilder::SetSubjectKeyIdentifier(
823 const std::string& subject_key_identifier) {
824 ASSERT_FALSE(subject_key_identifier.empty());
825
826 // From RFC 5280:
827 // KeyIdentifier ::= OCTET STRING
828 // SubjectKeyIdentifier ::= KeyIdentifier
829 bssl::ScopedCBB cbb;
830 ASSERT_TRUE(CBB_init(cbb.get(), 32));
831
832 ASSERT_TRUE(CBB_add_asn1_octet_string(
833 cbb.get(),
834 reinterpret_cast<const uint8_t*>(subject_key_identifier.data()),
835 subject_key_identifier.size()));
836
837 // Replace the existing SKI. Note it MUST be non-critical, per RFC 5280.
838 SetExtension(der::Input(kSubjectKeyIdentifierOid), FinishCBB(cbb.get()),
839 /*critical=*/false);
840 }
841
SetAuthorityKeyIdentifier(const std::string & authority_key_identifier)842 void CertBuilder::SetAuthorityKeyIdentifier(
843 const std::string& authority_key_identifier) {
844 // If an empty AKI is presented, simply erase the existing one. Creating
845 // an empty AKI is technically valid, but there's no use case for this.
846 // An empty AKI would an empty (ergo, non-unique) SKI on the issuer,
847 // which would violate RFC 5280, so using the empty value as a placeholder
848 // unless and until a use case emerges is fine.
849 if (authority_key_identifier.empty()) {
850 EraseExtension(der::Input(kAuthorityKeyIdentifierOid));
851 return;
852 }
853
854 // From RFC 5280:
855 //
856 // AuthorityKeyIdentifier ::= SEQUENCE {
857 // keyIdentifier [0] KeyIdentifier OPTIONAL,
858 // authorityCertIssuer [1] GeneralNames OPTIONAL,
859 // authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL }
860 //
861 // KeyIdentifier ::= OCTET STRING
862 bssl::ScopedCBB cbb;
863 CBB aki, aki_value;
864 ASSERT_TRUE(CBB_init(cbb.get(), 32));
865 ASSERT_TRUE(CBB_add_asn1(cbb.get(), &aki, CBS_ASN1_SEQUENCE));
866 ASSERT_TRUE(CBB_add_asn1(&aki, &aki_value, CBS_ASN1_CONTEXT_SPECIFIC | 0));
867 ASSERT_TRUE(CBBAddBytes(&aki_value, authority_key_identifier));
868 ASSERT_TRUE(CBB_flush(&aki));
869
870 SetExtension(der::Input(kAuthorityKeyIdentifierOid), FinishCBB(cbb.get()));
871 }
872
SetSignatureAlgorithm(SignatureAlgorithm signature_algorithm)873 void CertBuilder::SetSignatureAlgorithm(
874 SignatureAlgorithm signature_algorithm) {
875 signature_algorithm_ = signature_algorithm;
876 Invalidate();
877 }
878
SetSignatureAlgorithmTLV(base::StringPiece signature_algorithm_tlv)879 void CertBuilder::SetSignatureAlgorithmTLV(
880 base::StringPiece signature_algorithm_tlv) {
881 SetOuterSignatureAlgorithmTLV(signature_algorithm_tlv);
882 SetTBSSignatureAlgorithmTLV(signature_algorithm_tlv);
883 }
884
SetOuterSignatureAlgorithmTLV(base::StringPiece signature_algorithm_tlv)885 void CertBuilder::SetOuterSignatureAlgorithmTLV(
886 base::StringPiece signature_algorithm_tlv) {
887 outer_signature_algorithm_tlv_ = std::string(signature_algorithm_tlv);
888 Invalidate();
889 }
890
SetTBSSignatureAlgorithmTLV(base::StringPiece signature_algorithm_tlv)891 void CertBuilder::SetTBSSignatureAlgorithmTLV(
892 base::StringPiece signature_algorithm_tlv) {
893 tbs_signature_algorithm_tlv_ = std::string(signature_algorithm_tlv);
894 Invalidate();
895 }
896
SetRandomSerialNumber()897 void CertBuilder::SetRandomSerialNumber() {
898 serial_number_ = base::RandUint64();
899 Invalidate();
900 }
901
GetCertBuffer()902 CRYPTO_BUFFER* CertBuilder::GetCertBuffer() {
903 if (!cert_)
904 GenerateCertificate();
905 return cert_.get();
906 }
907
DupCertBuffer()908 bssl::UniquePtr<CRYPTO_BUFFER> CertBuilder::DupCertBuffer() {
909 return bssl::UpRef(GetCertBuffer());
910 }
911
GetSubject()912 const std::string& CertBuilder::GetSubject() {
913 if (subject_tlv_.empty())
914 GenerateSubject();
915 return subject_tlv_;
916 }
917
GetSerialNumber()918 uint64_t CertBuilder::GetSerialNumber() {
919 if (!serial_number_)
920 serial_number_ = base::RandUint64();
921 return serial_number_;
922 }
923
GetSubjectKeyIdentifier()924 std::string CertBuilder::GetSubjectKeyIdentifier() {
925 std::string ski_oid = der::Input(kSubjectKeyIdentifierOid).AsString();
926 if (extensions_.find(ski_oid) == extensions_.end()) {
927 // If no SKI is present, this means that the certificate was either
928 // created by FromStaticCert() and lacked one, or it was explicitly
929 // deleted as an extension.
930 return std::string();
931 }
932
933 auto& extension_value = extensions_[ski_oid];
934 der::Input ski_value;
935 if (!ParseSubjectKeyIdentifier(der::Input(&extension_value.value),
936 &ski_value)) {
937 return std::string();
938 }
939 return ski_value.AsString();
940 }
941
GetValidity(base::Time * not_before,base::Time * not_after) const942 bool CertBuilder::GetValidity(base::Time* not_before,
943 base::Time* not_after) const {
944 der::GeneralizedTime not_before_generalized_time;
945 der::GeneralizedTime not_after_generalized_time;
946 if (!ParseValidity(der::Input(&validity_tlv_), ¬_before_generalized_time,
947 ¬_after_generalized_time) ||
948 !GeneralizedTimeToTime(not_before_generalized_time, not_before) ||
949 !GeneralizedTimeToTime(not_after_generalized_time, not_after)) {
950 return false;
951 }
952 return true;
953 }
954
GetKey()955 EVP_PKEY* CertBuilder::GetKey() {
956 if (!key_) {
957 switch (default_pkey_id_) {
958 case EVP_PKEY_RSA:
959 GenerateRSAKey();
960 break;
961 case EVP_PKEY_EC:
962 GenerateECKey();
963 break;
964 }
965 }
966 return key_.get();
967 }
968
GetX509Certificate()969 scoped_refptr<X509Certificate> CertBuilder::GetX509Certificate() {
970 return X509Certificate::CreateFromBuffer(DupCertBuffer(), {});
971 }
972
GetX509CertificateChain()973 scoped_refptr<X509Certificate> CertBuilder::GetX509CertificateChain() {
974 std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
975 // Add intermediates, not including the self-signed root.
976 for (CertBuilder* cert = issuer_; cert && cert != cert->issuer_;
977 cert = cert->issuer_) {
978 intermediates.push_back(cert->DupCertBuffer());
979 }
980 return X509Certificate::CreateFromBuffer(DupCertBuffer(),
981 std::move(intermediates));
982 }
983
GetX509CertificateFullChain()984 scoped_refptr<X509Certificate> CertBuilder::GetX509CertificateFullChain() {
985 std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
986 // Add intermediates and the self-signed root.
987 for (CertBuilder* cert = issuer_; cert; cert = cert->issuer_) {
988 intermediates.push_back(cert->DupCertBuffer());
989 if (cert == cert->issuer_)
990 break;
991 }
992 return X509Certificate::CreateFromBuffer(DupCertBuffer(),
993 std::move(intermediates));
994 }
995
GetDER()996 std::string CertBuilder::GetDER() {
997 return std::string(x509_util::CryptoBufferAsStringPiece(GetCertBuffer()));
998 }
999
GetPEM()1000 std::string CertBuilder::GetPEM() {
1001 std::string pem_encoded;
1002 EXPECT_TRUE(X509Certificate::GetPEMEncoded(GetCertBuffer(), &pem_encoded));
1003 return pem_encoded;
1004 }
1005
GetPEMFullChain()1006 std::string CertBuilder::GetPEMFullChain() {
1007 std::vector<std::string> pems;
1008 CertBuilder* cert = this;
1009 while (cert) {
1010 pems.push_back(cert->GetPEM());
1011 if (cert == cert->issuer_)
1012 break;
1013 cert = cert->issuer_;
1014 }
1015 return base::JoinString(pems, "\n");
1016 }
1017
GetPrivateKeyPEM()1018 std::string CertBuilder::GetPrivateKeyPEM() {
1019 std::string pem_encoded = key_util::PEMFromPrivateKey(GetKey());
1020 EXPECT_FALSE(pem_encoded.empty());
1021 return pem_encoded;
1022 }
1023
CertBuilder(CRYPTO_BUFFER * orig_cert,CertBuilder * issuer,bool unique_subject_key_identifier)1024 CertBuilder::CertBuilder(CRYPTO_BUFFER* orig_cert,
1025 CertBuilder* issuer,
1026 bool unique_subject_key_identifier)
1027 : issuer_(issuer) {
1028 if (!issuer_)
1029 issuer_ = this;
1030
1031 crypto::EnsureOpenSSLInit();
1032 if (orig_cert)
1033 InitFromCert(der::Input(x509_util::CryptoBufferAsStringPiece(orig_cert)));
1034
1035 if (unique_subject_key_identifier) {
1036 GenerateSubjectKeyIdentifier();
1037 SetAuthorityKeyIdentifier(issuer_->GetSubjectKeyIdentifier());
1038 }
1039 }
1040
Invalidate()1041 void CertBuilder::Invalidate() {
1042 cert_.reset();
1043 }
1044
GenerateECKey()1045 void CertBuilder::GenerateECKey() {
1046 auto private_key = crypto::ECPrivateKey::Create();
1047 key_ = bssl::UpRef(private_key->key());
1048 Invalidate();
1049 }
1050
GenerateRSAKey()1051 void CertBuilder::GenerateRSAKey() {
1052 auto private_key = crypto::RSAPrivateKey::Create(2048);
1053 key_ = bssl::UpRef(private_key->key());
1054 Invalidate();
1055 }
1056
UseKeyFromFile(const base::FilePath & key_file)1057 bool CertBuilder::UseKeyFromFile(const base::FilePath& key_file) {
1058 bssl::UniquePtr<EVP_PKEY> private_key(
1059 key_util::LoadEVP_PKEYFromPEM(key_file));
1060 if (!private_key)
1061 return false;
1062 key_ = std::move(private_key);
1063 Invalidate();
1064 return true;
1065 }
1066
GenerateSubjectKeyIdentifier()1067 void CertBuilder::GenerateSubjectKeyIdentifier() {
1068 // 20 bytes are chosen here for no other reason than it's compatible with
1069 // systems that assume the SKI is SHA-1(SPKI), which RFC 5280 notes as one
1070 // mechanism for generating an SKI, while also noting that random/unique
1071 // SKIs are also fine.
1072 std::string random_ski = base::RandBytesAsString(20);
1073 SetSubjectKeyIdentifier(random_ski);
1074 }
1075
GenerateSubject()1076 void CertBuilder::GenerateSubject() {
1077 ASSERT_TRUE(subject_tlv_.empty());
1078
1079 // Use a random common name comprised of 12 bytes in hex.
1080 std::string common_name = MakeRandomHexString(12);
1081
1082 SetSubjectCommonName(common_name);
1083 }
1084
InitFromCert(const der::Input & cert)1085 void CertBuilder::InitFromCert(const der::Input& cert) {
1086 extensions_.clear();
1087 Invalidate();
1088
1089 // From RFC 5280, section 4.1
1090 // Certificate ::= SEQUENCE {
1091 // tbsCertificate TBSCertificate,
1092 // signatureAlgorithm AlgorithmIdentifier,
1093 // signatureValue BIT STRING }
1094
1095 // TBSCertificate ::= SEQUENCE {
1096 // version [0] EXPLICIT Version DEFAULT v1,
1097 // serialNumber CertificateSerialNumber,
1098 // signature AlgorithmIdentifier,
1099 // issuer Name,
1100 // validity Validity,
1101 // subject Name,
1102 // subjectPublicKeyInfo SubjectPublicKeyInfo,
1103 // issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
1104 // -- If present, version MUST be v2 or v3
1105 // subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
1106 // -- If present, version MUST be v2 or v3
1107 // extensions [3] EXPLICIT Extensions OPTIONAL
1108 // -- If present, version MUST be v3
1109 // }
1110 der::Parser parser(cert);
1111 der::Parser certificate;
1112 der::Parser tbs_certificate;
1113 ASSERT_TRUE(parser.ReadSequence(&certificate));
1114 ASSERT_TRUE(certificate.ReadSequence(&tbs_certificate));
1115
1116 // version
1117 bool has_version;
1118 ASSERT_TRUE(tbs_certificate.SkipOptionalTag(
1119 der::kTagConstructed | der::kTagContextSpecific | 0, &has_version));
1120 if (has_version) {
1121 // TODO(mattm): could actually parse the version here instead of assuming
1122 // V3.
1123 version_ = CertificateVersion::V3;
1124 } else {
1125 version_ = CertificateVersion::V1;
1126 }
1127
1128 // serialNumber
1129 ASSERT_TRUE(tbs_certificate.SkipTag(der::kInteger));
1130
1131 // signature
1132 der::Input signature_algorithm_tlv;
1133 ASSERT_TRUE(tbs_certificate.ReadRawTLV(&signature_algorithm_tlv));
1134 auto signature_algorithm = ParseSignatureAlgorithm(signature_algorithm_tlv);
1135 ASSERT_TRUE(signature_algorithm);
1136 signature_algorithm_ = *signature_algorithm;
1137
1138 // issuer
1139 ASSERT_TRUE(tbs_certificate.SkipTag(der::kSequence));
1140
1141 // validity
1142 der::Input validity_tlv;
1143 ASSERT_TRUE(tbs_certificate.ReadRawTLV(&validity_tlv));
1144 validity_tlv_ = validity_tlv.AsString();
1145
1146 // subject
1147 ASSERT_TRUE(tbs_certificate.SkipTag(der::kSequence));
1148
1149 // subjectPublicKeyInfo
1150 der::Input spki_tlv;
1151 ASSERT_TRUE(tbs_certificate.ReadRawTLV(&spki_tlv));
1152 bssl::UniquePtr<EVP_PKEY> public_key;
1153 ASSERT_TRUE(ParsePublicKey(spki_tlv, &public_key));
1154 default_pkey_id_ = EVP_PKEY_id(public_key.get());
1155
1156 // issuerUniqueID
1157 bool unused;
1158 ASSERT_TRUE(tbs_certificate.SkipOptionalTag(der::ContextSpecificPrimitive(1),
1159 &unused));
1160 // subjectUniqueID
1161 ASSERT_TRUE(tbs_certificate.SkipOptionalTag(der::ContextSpecificPrimitive(2),
1162 &unused));
1163
1164 // extensions
1165 absl::optional<der::Input> extensions_tlv;
1166 ASSERT_TRUE(tbs_certificate.ReadOptionalTag(
1167 der::ContextSpecificConstructed(3), &extensions_tlv));
1168 if (extensions_tlv) {
1169 std::map<der::Input, ParsedExtension> parsed_extensions;
1170 ASSERT_TRUE(ParseExtensions(extensions_tlv.value(), &parsed_extensions));
1171
1172 for (const auto& parsed_extension : parsed_extensions) {
1173 SetExtension(parsed_extension.second.oid,
1174 parsed_extension.second.value.AsString(),
1175 parsed_extension.second.critical);
1176 }
1177 }
1178 }
1179
BuildTBSCertificate(base::StringPiece signature_algorithm_tlv,std::string * out)1180 void CertBuilder::BuildTBSCertificate(base::StringPiece signature_algorithm_tlv,
1181 std::string* out) {
1182 bssl::ScopedCBB cbb;
1183 CBB tbs_cert, version, extensions_context, extensions;
1184
1185 ASSERT_TRUE(CBB_init(cbb.get(), 64));
1186 ASSERT_TRUE(CBB_add_asn1(cbb.get(), &tbs_cert, CBS_ASN1_SEQUENCE));
1187 if (version_ != CertificateVersion::V1) {
1188 ASSERT_TRUE(
1189 CBB_add_asn1(&tbs_cert, &version,
1190 CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0));
1191 switch (version_) {
1192 case CertificateVersion::V2:
1193 ASSERT_TRUE(CBB_add_asn1_uint64(&version, 1));
1194 break;
1195 case CertificateVersion::V3:
1196 ASSERT_TRUE(CBB_add_asn1_uint64(&version, 2));
1197 break;
1198 case CertificateVersion::V1:
1199 NOTREACHED_NORETURN();
1200 }
1201 }
1202 ASSERT_TRUE(CBB_add_asn1_uint64(&tbs_cert, GetSerialNumber()));
1203 ASSERT_TRUE(CBBAddBytes(&tbs_cert, signature_algorithm_tlv));
1204 ASSERT_TRUE(CBBAddBytes(&tbs_cert, issuer_tlv_.has_value()
1205 ? *issuer_tlv_
1206 : issuer_->GetSubject()));
1207 ASSERT_TRUE(CBBAddBytes(&tbs_cert, validity_tlv_));
1208 ASSERT_TRUE(CBBAddBytes(&tbs_cert, GetSubject()));
1209 ASSERT_TRUE(GetKey());
1210 ASSERT_TRUE(EVP_marshal_public_key(&tbs_cert, GetKey()));
1211
1212 // Serialize all the extensions.
1213 if (!extensions_.empty()) {
1214 ASSERT_TRUE(
1215 CBB_add_asn1(&tbs_cert, &extensions_context,
1216 CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 3));
1217 ASSERT_TRUE(
1218 CBB_add_asn1(&extensions_context, &extensions, CBS_ASN1_SEQUENCE));
1219
1220 // Extension ::= SEQUENCE {
1221 // extnID OBJECT IDENTIFIER,
1222 // critical BOOLEAN DEFAULT FALSE,
1223 // extnValue OCTET STRING
1224 // -- contains the DER encoding of an ASN.1 value
1225 // -- corresponding to the extension type identified
1226 // -- by extnID
1227 // }
1228 for (const auto& extension_it : extensions_) {
1229 CBB extension_seq, oid, extn_value;
1230 ASSERT_TRUE(CBB_add_asn1(&extensions, &extension_seq, CBS_ASN1_SEQUENCE));
1231 ASSERT_TRUE(CBB_add_asn1(&extension_seq, &oid, CBS_ASN1_OBJECT));
1232 ASSERT_TRUE(CBBAddBytes(&oid, extension_it.first));
1233 if (extension_it.second.critical) {
1234 ASSERT_TRUE(CBB_add_asn1_bool(&extension_seq, true));
1235 }
1236
1237 ASSERT_TRUE(
1238 CBB_add_asn1(&extension_seq, &extn_value, CBS_ASN1_OCTETSTRING));
1239 ASSERT_TRUE(CBBAddBytes(&extn_value, extension_it.second.value));
1240 ASSERT_TRUE(CBB_flush(&extensions));
1241 }
1242 }
1243
1244 *out = FinishCBB(cbb.get());
1245 }
1246
GenerateCertificate()1247 void CertBuilder::GenerateCertificate() {
1248 ASSERT_FALSE(cert_);
1249
1250 absl::optional<SignatureAlgorithm> signature_algorithm = signature_algorithm_;
1251 if (!signature_algorithm)
1252 signature_algorithm = DefaultSignatureAlgorithmForKey(issuer_->GetKey());
1253 ASSERT_TRUE(signature_algorithm.has_value());
1254
1255 std::string signature_algorithm_tlv =
1256 !outer_signature_algorithm_tlv_.empty()
1257 ? outer_signature_algorithm_tlv_
1258 : SignatureAlgorithmToDer(*signature_algorithm);
1259 ASSERT_FALSE(signature_algorithm_tlv.empty());
1260
1261 std::string tbs_signature_algorithm_tlv =
1262 !tbs_signature_algorithm_tlv_.empty()
1263 ? tbs_signature_algorithm_tlv_
1264 : SignatureAlgorithmToDer(*signature_algorithm);
1265 ASSERT_FALSE(tbs_signature_algorithm_tlv.empty());
1266
1267 std::string tbs_cert;
1268 BuildTBSCertificate(tbs_signature_algorithm_tlv, &tbs_cert);
1269
1270 // Sign the TBSCertificate and write the entire certificate.
1271 bssl::ScopedCBB cbb;
1272 CBB cert, signature;
1273
1274 ASSERT_TRUE(CBB_init(cbb.get(), tbs_cert.size()));
1275 ASSERT_TRUE(CBB_add_asn1(cbb.get(), &cert, CBS_ASN1_SEQUENCE));
1276 ASSERT_TRUE(CBBAddBytes(&cert, tbs_cert));
1277 ASSERT_TRUE(CBBAddBytes(&cert, signature_algorithm_tlv));
1278 ASSERT_TRUE(CBB_add_asn1(&cert, &signature, CBS_ASN1_BITSTRING));
1279 ASSERT_TRUE(CBB_add_u8(&signature, 0 /* no unused bits */));
1280 ASSERT_TRUE(
1281 SignData(*signature_algorithm, tbs_cert, issuer_->GetKey(), &signature));
1282
1283 auto cert_der = FinishCBB(cbb.get());
1284 cert_ =
1285 x509_util::CreateCryptoBuffer(base::as_bytes(base::make_span(cert_der)));
1286 }
1287
1288 } // namespace net
1289