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