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 #ifndef NET_TEST_CERT_BUILDER_H_ 6 #define NET_TEST_CERT_BUILDER_H_ 7 8 #include <map> 9 #include <memory> 10 #include <string> 11 #include <vector> 12 13 #include "base/memory/raw_ptr.h" 14 #include "base/rand_util.h" 15 #include "base/strings/string_piece.h" 16 #include "net/base/ip_address.h" 17 #include "net/cert/x509_certificate.h" 18 #include "third_party/boringssl/src/include/openssl/base.h" 19 #include "third_party/boringssl/src/include/openssl/bytestring.h" 20 #include "third_party/boringssl/src/include/openssl/evp.h" 21 #include "third_party/boringssl/src/include/openssl/pool.h" 22 #include "third_party/boringssl/src/pki/parse_certificate.h" 23 #include "third_party/boringssl/src/pki/signature_algorithm.h" 24 25 class GURL; 26 27 namespace base { 28 class FilePath; 29 } 30 31 namespace net { 32 33 namespace der { 34 class Input; 35 } 36 37 // CertBuilder is a helper class to dynamically create a test certificate. 38 // 39 // CertBuilder is initialized using an existing certificate, from which it 40 // copies most properties (see InitFromCert for details). 41 // 42 // The subject, serial number, and key for the final certificate are chosen 43 // randomly. Using a randomized subject and serial number is important to defeat 44 // certificate caching done by NSS, which otherwise can make test outcomes 45 // dependent on ordering. 46 class CertBuilder { 47 public: 48 // Parameters for creating an embedded SignedCertificateTimestamp. 49 struct SctConfig { 50 SctConfig(); 51 SctConfig(std::string log_id, 52 bssl::UniquePtr<EVP_PKEY> log_key, 53 base::Time timestamp); 54 SctConfig(const SctConfig&); 55 SctConfig(SctConfig&&); 56 ~SctConfig(); 57 SctConfig& operator=(const SctConfig&); 58 SctConfig& operator=(SctConfig&&); 59 60 std::string log_id; 61 // Only EC keys are supported currently. 62 bssl::UniquePtr<EVP_PKEY> log_key; 63 base::Time timestamp; 64 }; 65 66 // Initializes the CertBuilder, if |orig_cert| is non-null it will be used as 67 // a template. If |issuer| is null then the generated certificate will be 68 // self-signed. Otherwise, it will be signed using |issuer|. 69 CertBuilder(CRYPTO_BUFFER* orig_cert, CertBuilder* issuer); 70 ~CertBuilder(); 71 72 // Initializes a CertBuilder using the certificate and private key from 73 // |cert_and_key_file| as a template. If |issuer| is null then the generated 74 // certificate will be self-signed. Otherwise, it will be signed using 75 // |issuer|. 76 static std::unique_ptr<CertBuilder> FromFile( 77 const base::FilePath& cert_and_key_file, 78 CertBuilder* issuer); 79 80 // Initializes a CertBuilder that will return a certificate for the provided 81 // public key |spki_der|. It will be signed with the |issuer|, this builder 82 // will not have a private key, so it cannot produce self-signed certificates 83 // and |issuer| cannot be null. 84 static std::unique_ptr<CertBuilder> FromSubjectPublicKeyInfo( 85 base::span<const uint8_t> spki_der, 86 CertBuilder* issuer); 87 88 // Creates a CertBuilder that will return a static |cert| and |key|. 89 // This may be passed as the |issuer| param of another CertBuilder to create 90 // a cert chain that ends in a pre-defined certificate. 91 static std::unique_ptr<CertBuilder> FromStaticCert(CRYPTO_BUFFER* cert, 92 EVP_PKEY* key); 93 // Like FromStaticCert, but loads the certificate and private key from the 94 // PEM file |cert_and_key_file|. 95 static std::unique_ptr<CertBuilder> FromStaticCertFile( 96 const base::FilePath& cert_and_key_file); 97 98 // Creates a simple chain of CertBuilders with no AIA or CrlDistributionPoint 99 // extensions, and leaf having a subjectAltName of www.example.com. 100 // The chain is returned in leaf-first order. 101 static std::vector<std::unique_ptr<CertBuilder>> CreateSimpleChain( 102 size_t chain_length); 103 104 // Creates a simple leaf->intermediate->root chain of CertBuilders with no AIA 105 // or CrlDistributionPoint extensions, and leaf having a subjectAltName of 106 // www.example.com. 107 static std::array<std::unique_ptr<CertBuilder>, 3> CreateSimpleChain3(); 108 109 // Creates a simple leaf->root chain of CertBuilders with no AIA or 110 // CrlDistributionPoint extensions, and leaf having a subjectAltName of 111 // www.example.com. 112 static std::array<std::unique_ptr<CertBuilder>, 2> CreateSimpleChain2(); 113 114 // Returns a compatible signature algorithm for |key|. 115 static absl::optional<bssl::SignatureAlgorithm> 116 DefaultSignatureAlgorithmForKey(EVP_PKEY* key); 117 118 // Signs |tbs_data| with |key| using |signature_algorithm| appending the 119 // signature onto |out_signature| and returns true if successful. 120 static bool SignData(bssl::SignatureAlgorithm signature_algorithm, 121 base::StringPiece tbs_data, 122 EVP_PKEY* key, 123 CBB* out_signature); 124 125 static bool SignDataWithDigest(const EVP_MD* digest, 126 base::StringPiece tbs_data, 127 EVP_PKEY* key, 128 CBB* out_signature); 129 130 // Returns a DER encoded AlgorithmIdentifier TLV for |signature_algorithm| 131 // empty string on error. 132 static std::string SignatureAlgorithmToDer( 133 bssl::SignatureAlgorithm signature_algorithm); 134 135 // Generates |num_bytes| random bytes, and then returns the hex encoding of 136 // those bytes. 137 static std::string MakeRandomHexString(size_t num_bytes); 138 139 // Builds a DER encoded X.501 Name TLV containing a commonName of 140 // |common_name| with type |common_name_tag|. 141 static std::vector<uint8_t> BuildNameWithCommonNameOfType( 142 base::StringPiece common_name, 143 unsigned common_name_tag); 144 145 // Set the version of the certificate. Note that only V3 certificates may 146 // contain extensions, so if |version| is |V1| or |V2| you may want to also 147 // call |ClearExtensions()| unless you intentionally want to generate an 148 // invalid certificate. 149 void SetCertificateVersion(bssl::CertificateVersion version); 150 151 // Sets a value for the indicated X.509 (v3) extension. 152 void SetExtension(const bssl::der::Input& oid, 153 std::string value, 154 bool critical = false); 155 156 // Removes an extension (if present). 157 void EraseExtension(const bssl::der::Input& oid); 158 159 // Removes all extensions. 160 void ClearExtensions(); 161 162 // Sets the basicConstraints extension. |path_len| may be negative to 163 // indicate the pathLenConstraint should be omitted. 164 void SetBasicConstraints(bool is_ca, int path_len); 165 166 // Sets the nameConstraints extension. |permitted_dns_names| lists permitted 167 // dnsName subtrees. |excluded_dns_names| lists excluded dnsName subtrees. If 168 // both lists are empty the extension is removed. 169 void SetNameConstraintsDnsNames( 170 const std::vector<std::string>& permitted_dns_names, 171 const std::vector<std::string>& excluded_dns_names); 172 173 // Sets an AIA extension with a single caIssuers access method. 174 void SetCaIssuersUrl(const GURL& url); 175 176 // Sets an AIA extension with the specified caIssuers and OCSP urls. Either 177 // list can have 0 or more URLs. If both are empty, the AIA extension is 178 // removed. 179 void SetCaIssuersAndOCSPUrls(const std::vector<GURL>& ca_issuers_urls, 180 const std::vector<GURL>& ocsp_urls); 181 182 // Sets a cRLDistributionPoints extension with a single DistributionPoint 183 // with |url| in distributionPoint.fullName. 184 void SetCrlDistributionPointUrl(const GURL& url); 185 186 // Sets a cRLDistributionPoints extension with a single DistributionPoint 187 // with |urls| in distributionPoints.fullName. 188 void SetCrlDistributionPointUrls(const std::vector<GURL>& urls); 189 190 // Sets the issuer bytes that will be encoded into the generated certificate. 191 // If this is not called, or |issuer_tlv| is empty, the subject field from 192 // the issuer CertBuilder will be used. 193 void SetIssuerTLV(base::span<const uint8_t> issuer_tlv); 194 195 // Sets the subject to a Name with a single commonName attribute with 196 // the value |common_name| tagged as a UTF8String. 197 void SetSubjectCommonName(base::StringPiece common_name); 198 199 // Sets the subject to |subject_tlv|. 200 void SetSubjectTLV(base::span<const uint8_t> subject_tlv); 201 202 // Sets the SAN for the certificate to a single dNSName. 203 void SetSubjectAltName(base::StringPiece dns_name); 204 205 // Sets the SAN for the certificate to the given dns names and ip addresses. 206 void SetSubjectAltNames(const std::vector<std::string>& dns_names, 207 const std::vector<IPAddress>& ip_addresses); 208 209 // Sets the keyUsage extension. |usages| should contain the bssl::KeyUsageBit 210 // values of the usages to set, and must not be empty. 211 void SetKeyUsages(const std::vector<bssl::KeyUsageBit>& usages); 212 213 // Sets the extendedKeyUsage extension. |usages| should contain the DER OIDs 214 // of the usage purposes to set, and must not be empty. 215 void SetExtendedKeyUsages(const std::vector<bssl::der::Input>& purpose_oids); 216 217 // Sets the certificatePolicies extension with the specified policyIdentifier 218 // OIDs, which must be specified in dotted string notation (e.g. "1.2.3.4"). 219 // If |policy_oids| is empty, the extension will be removed. 220 void SetCertificatePolicies(const std::vector<std::string>& policy_oids); 221 222 // Sets the policyMappings extension with the specified mappings, which are 223 // pairs of issuerDomainPolicy -> subjectDomainPolicy mappings in dotted 224 // string notation. 225 // If |policy_mappings| is empty, the extension will be removed. 226 void SetPolicyMappings( 227 const std::vector<std::pair<std::string, std::string>>& policy_mappings); 228 229 // Sets the PolicyConstraints extension. If both |require_explicit_policy| 230 // and |inhibit_policy_mapping| are nullopt, the PolicyConstraints extension 231 // will removed. 232 void SetPolicyConstraints(absl::optional<uint64_t> require_explicit_policy, 233 absl::optional<uint64_t> inhibit_policy_mapping); 234 235 // Sets the inhibitAnyPolicy extension. 236 void SetInhibitAnyPolicy(uint64_t skip_certs); 237 238 void SetValidity(base::Time not_before, base::Time not_after); 239 240 // Sets the Subject Key Identifier (SKI) extension to the specified string. 241 // By default, a unique SKI will be generated for each CertBuilder; however, 242 // this may be overridden to force multiple certificates to be considered 243 // during path building on systems that prioritize matching SKI to the 244 // Authority Key Identifier (AKI) extension, rather than using the 245 // Subject/Issuer name. Empty SKIs are not supported; use EraseExtension() 246 // for that. 247 void SetSubjectKeyIdentifier(const std::string& subject_key_identifier); 248 249 // Sets the Authority Key Identifier (AKI) extension to the specified 250 // string. 251 // Note: Only the keyIdentifier option is supported, and the value 252 // is the raw identifier (i.e. without DER encoding). Empty strings will 253 // result in the extension, if present, being erased. This ensures that it 254 // is safe to use SetAuthorityKeyIdentifier() with the result of the 255 // issuing CertBuilder's (if any) GetSubjectKeyIdentifier() without 256 // introducing AKI/SKI chain building issues. 257 void SetAuthorityKeyIdentifier(const std::string& authority_key_identifier); 258 259 // Sets the signature algorithm to use in generating the certificate's 260 // signature. The signature algorithm should be compatible with 261 // the type of |issuer_->GetKey()|. If this method is not called, and the 262 // CertBuilder was initialized from a template cert, the signature algorithm 263 // of that cert will be used, or if there was no template cert, a default 264 // algorithm will be used base on the signing key type. 265 void SetSignatureAlgorithm(bssl::SignatureAlgorithm signature_algorithm); 266 267 // Sets both signature AlgorithmIdentifier TLVs to encode in the generated 268 // certificate. 269 // This only affects the bytes written to the output - it does not affect what 270 // algorithm is actually used to perform the signature. To set the signature 271 // algorithm used to generate the certificate's signature, use 272 // |SetSignatureAlgorithm|. If this method is not called, the signature 273 // algorithm written to the output will be chosen to match the signature 274 // algorithm used to sign the certificate. 275 void SetSignatureAlgorithmTLV(base::StringPiece signature_algorithm_tlv); 276 277 // Set only the outer Certificate signatureAlgorithm TLV. See 278 // SetSignatureAlgorithmTLV comment for general notes. 279 void SetOuterSignatureAlgorithmTLV(base::StringPiece signature_algorithm_tlv); 280 281 // Set only the tbsCertificate signature TLV. See SetSignatureAlgorithmTLV 282 // comment for general notes. 283 void SetTBSSignatureAlgorithmTLV(base::StringPiece signature_algorithm_tlv); 284 285 void SetSerialNumber(uint64_t serial_number); 286 void SetRandomSerialNumber(); 287 288 // Sets the configuration that will be used to generate a 289 // SignedCertificateTimestampList extension in the certificate. 290 void SetSctConfig(std::vector<CertBuilder::SctConfig> sct_configs); 291 292 // Sets the private key for the generated certificate to an EC key. If a key 293 // was already set, it will be replaced. 294 void GenerateECKey(); 295 296 // Sets the private key for the generated certificate to a 2048-bit RSA key. 297 // RSA key generation is expensive, so this should not be used unless an RSA 298 // key is specifically needed. If a key was already set, it will be replaced. 299 void GenerateRSAKey(); 300 301 // Loads the private key for the generated certificate from |key_file|. 302 bool UseKeyFromFile(const base::FilePath& key_file); 303 304 // Sets the private key to be |key|. 305 void SetKey(bssl::UniquePtr<EVP_PKEY> key); 306 307 // Returns the CertBuilder that issues this certificate. (Will be |this| if 308 // certificate is self-signed.) issuer()309 CertBuilder* issuer() { return issuer_; } 310 311 // Returns a CRYPTO_BUFFER to the generated certificate. 312 CRYPTO_BUFFER* GetCertBuffer(); 313 314 bssl::UniquePtr<CRYPTO_BUFFER> DupCertBuffer(); 315 316 // Returns the subject of the generated certificate. 317 const std::string& GetSubject(); 318 319 // Returns the serial number for the generated certificate. 320 uint64_t GetSerialNumber(); 321 322 // Returns the subject key identifier for the generated certificate. If 323 // none is present, a random value will be generated. 324 // Note: The returned value will be the contents of the OCTET 325 // STRING/KeyIdentifier, without DER encoding, ensuring it's suitable for 326 // SetSubjectKeyIdentifier(). 327 std::string GetSubjectKeyIdentifier(); 328 329 // Parses and returns validity period for the generated certificate in 330 // |not_before| and |not_after|, returning true on success. 331 bool GetValidity(base::Time* not_before, base::Time* not_after) const; 332 333 // Returns the key for the generated certificate. 334 EVP_PKEY* GetKey(); 335 336 // Returns an X509Certificate for the generated certificate. 337 scoped_refptr<X509Certificate> GetX509Certificate(); 338 339 // Returns an X509Certificate for the generated certificate, including 340 // intermediate certificates (not including the self-signed root). 341 scoped_refptr<X509Certificate> GetX509CertificateChain(); 342 343 // Returns an X509Certificate for the generated certificate, including 344 // intermediate certificates and the self-signed root. 345 scoped_refptr<X509Certificate> GetX509CertificateFullChain(); 346 347 // Returns a copy of the certificate's DER. 348 std::string GetDER(); 349 350 // Returns a copy of the certificate as PEM encoded DER. 351 // Convenience method for debugging, to more easily log what cert is being 352 // created. 353 std::string GetPEM(); 354 355 // Returns the full chain (including root) as PEM. 356 // Convenience method for debugging, to more easily log what certs are being 357 // created. 358 std::string GetPEMFullChain(); 359 360 // Returns the private key as PEM. 361 // Convenience method for debugging, to more easily log what certs are being 362 // created. 363 std::string GetPrivateKeyPEM(); 364 365 private: 366 // Initializes the CertBuilder, if |orig_cert| is non-null it will be used as 367 // a template. If |issuer| is null then the generated certificate will be 368 // self-signed. Otherwise, it will be signed using |issuer|. 369 // |unique_subject_key_identifier| controls whether an ephemeral SKI will 370 // be generated for this certificate. In general, any manipulation of the 371 // certificate at all should result in a new SKI, to avoid issues on 372 // Windows CryptoAPI, but generating a unique SKI can create issues for 373 // macOS Security.framework if |orig_cert| has already issued certificates 374 // (including self-signed certs). The only time this is safe is thus 375 // when used in conjunction with FromStaticCert() and re-using the 376 // same key, thus this constructor is private. 377 CertBuilder(CRYPTO_BUFFER* orig_cert, 378 CertBuilder* issuer, 379 bool unique_subject_key_identifier); 380 381 // Marks the generated certificate DER as invalid, so it will need to 382 // be re-generated next time the DER is accessed. 383 void Invalidate(); 384 385 // Generates a random Subject Key Identifier for the certificate. This is 386 // necessary for Windows, which otherwises uses SKI/AKI matching for lookups 387 // with greater precedence than subject/issuer name matching, and on newer 388 // versions of Windows, limits the number of lookups+signature failures that 389 // can be performed. Rather than deriving from |key_|, generating a unique 390 // value is useful for signalling this is a "unique" and otherwise 391 // independent CA. 392 void GenerateSubjectKeyIdentifier(); 393 394 // Generates a random subject for the certificate, comprised of just a CN. 395 void GenerateSubject(); 396 397 // Parses |cert| and copies the following properties: 398 // * All extensions (dropping any duplicates) 399 // * Signature algorithm (from Certificate) 400 // * Validity (expiration) 401 void InitFromCert(const bssl::der::Input& cert); 402 403 // Assembles the CertBuilder into a TBSCertificate. 404 void BuildTBSCertificate(base::StringPiece signature_algorithm_tlv, 405 std::string* out); 406 407 void BuildSctListExtension(const std::string& pre_tbs_certificate, 408 std::string* out); 409 410 void GenerateCertificate(); 411 412 struct ExtensionValue { 413 bool critical = false; 414 std::string value; 415 }; 416 417 bssl::CertificateVersion version_ = bssl::CertificateVersion::V3; 418 std::string validity_tlv_; 419 absl::optional<std::string> issuer_tlv_; 420 std::string subject_tlv_; 421 absl::optional<bssl::SignatureAlgorithm> signature_algorithm_; 422 std::string outer_signature_algorithm_tlv_; 423 std::string tbs_signature_algorithm_tlv_; 424 uint64_t serial_number_ = 0; 425 int default_pkey_id_ = EVP_PKEY_EC; 426 427 std::vector<SctConfig> sct_configs_; 428 429 std::map<std::string, ExtensionValue> extensions_; 430 431 bssl::UniquePtr<CRYPTO_BUFFER> cert_; 432 bssl::UniquePtr<EVP_PKEY> key_; 433 434 raw_ptr<CertBuilder, DanglingUntriaged> issuer_ = nullptr; 435 }; 436 437 } // namespace net 438 439 #endif // NET_TEST_CERT_BUILDER_H_ 440