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