xref: /aosp_15_r20/external/cronet/net/cert/cert_verify_proc.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2012 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_CERT_CERT_VERIFY_PROC_H_
6 #define NET_CERT_CERT_VERIFY_PROC_H_
7 
8 #include <string>
9 #include <vector>
10 
11 #include "base/feature_list.h"
12 #include "base/gtest_prod_util.h"
13 #include "base/memory/ref_counted.h"
14 #include "build/build_config.h"
15 #include "crypto/crypto_buildflags.h"
16 #include "net/base/hash_value.h"
17 #include "net/base/ip_address.h"
18 #include "net/base/net_export.h"
19 #include "net/cert/ct_log_verifier.h"
20 #include "net/cert/ct_policy_enforcer.h"
21 #include "net/cert/ct_verifier.h"
22 #include "net/net_buildflags.h"
23 #include "third_party/boringssl/src/pki/parsed_certificate.h"
24 
25 #if BUILDFLAG(CHROME_ROOT_STORE_SUPPORTED)
26 #include "net/cert/internal/trust_store_chrome.h"
27 #endif
28 
29 namespace net {
30 
31 class CertNetFetcher;
32 class CertVerifyResult;
33 class CRLSet;
34 class NetLogWithSource;
35 class X509Certificate;
36 typedef std::vector<scoped_refptr<X509Certificate>> CertificateList;
37 
38 // Class to perform certificate path building and verification for various
39 // certificate uses. All methods of this class must be thread-safe, as they
40 // may be called from various non-joinable worker threads.
41 class NET_EXPORT CertVerifyProc
42     : public base::RefCountedThreadSafe<CertVerifyProc> {
43  public:
44   enum VerifyFlags {
45     // If set, enables online revocation checking via CRLs and OCSP for the
46     // certificate chain.
47     // Note: has no effect if VERIFY_DISABLE_NETWORK_FETCHES is set.
48     VERIFY_REV_CHECKING_ENABLED = 1 << 0,
49 
50     // If set, this is equivalent to VERIFY_REV_CHECKING_ENABLED, in that it
51     // enables online revocation checking via CRLs or OCSP, but only
52     // for certificates issued by non-public trust anchors. Failure to check
53     // revocation is treated as a hard failure.
54     // Note: has no effect if VERIFY_DISABLE_NETWORK_FETCHES is set.
55     VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS = 1 << 1,
56 
57     // If set, certificates with SHA-1 signatures will be allowed, but only if
58     // they are issued by non-public trust anchors.
59     VERIFY_ENABLE_SHA1_LOCAL_ANCHORS = 1 << 2,
60 
61     // If set, disables the policy enforcement described at
62     // https://security.googleblog.com/2017/09/chromes-plan-to-distrust-symantec.html
63     VERIFY_DISABLE_SYMANTEC_ENFORCEMENT = 1 << 3,
64 
65     // Disable network fetches during verification. This will override
66     // VERIFY_REV_CHECKING_ENABLED and
67     // VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS if they are also specified.
68     // (Note that this entirely disables the online revocation/AIA code paths.
69     // Theoretically we could still check for cached results.)
70     VERIFY_DISABLE_NETWORK_FETCHES = 1 << 4,
71 
72     // Also update GetNetConstants() in net/log/net_log_util.cc when updating
73     // this enum.
74     VERIFY_FLAGS_LAST = VERIFY_DISABLE_NETWORK_FETCHES
75   };
76 
77   // The set factory parameters that are variable over time, but are expected to
78   // be consistent between multiple verifiers that are created. For example,
79   // CertNetFetcher is not in this struct as it is expected that different
80   // verifiers will have different net fetchers. (There is no technical
81   // restriction against creating different verifiers with different ImplParams,
82   // structuring the parameters this way just makes some APIs more convenient
83   // for the common case.)
84   struct NET_EXPORT ImplParams {
85     ImplParams();
86     ~ImplParams();
87     ImplParams(const ImplParams&);
88     ImplParams& operator=(const ImplParams& other);
89     ImplParams(ImplParams&&);
90     ImplParams& operator=(ImplParams&& other);
91 
92     scoped_refptr<CRLSet> crl_set;
93     std::vector<scoped_refptr<const net::CTLogVerifier>> ct_logs;
94     scoped_refptr<net::CTPolicyEnforcer> ct_policy_enforcer;
95 #if BUILDFLAG(CHROME_ROOT_STORE_SUPPORTED)
96     std::optional<net::ChromeRootStoreData> root_store_data;
97 #endif
98 #if BUILDFLAG(CHROME_ROOT_STORE_OPTIONAL)
99     bool use_chrome_root_store;
100 #endif
101   };
102 
103   // CIDR, consisting of an IP and a netmask.
104   struct NET_EXPORT CIDR {
105     net::IPAddress ip;
106     net::IPAddress mask;
107   };
108 
109   // Single certificate, with constraints.
110   struct NET_EXPORT CertificateWithConstraints {
111     CertificateWithConstraints();
112     ~CertificateWithConstraints();
113     CertificateWithConstraints(const CertificateWithConstraints&);
114     CertificateWithConstraints& operator=(
115         const CertificateWithConstraints& other);
116     CertificateWithConstraints(CertificateWithConstraints&&);
117     CertificateWithConstraints& operator=(CertificateWithConstraints&& other);
118 
119     std::shared_ptr<const bssl::ParsedCertificate> certificate;
120 
121     std::vector<std::string> permitted_dns_names;
122 
123     std::vector<CIDR> permitted_cidrs;
124   };
125 
126   // The set of parameters that are variable over time and can differ between
127   // different verifiers created by a CertVerifierProcFactory.
128   struct NET_EXPORT InstanceParams {
129     InstanceParams();
130     ~InstanceParams();
131     InstanceParams(const InstanceParams&);
132     InstanceParams& operator=(const InstanceParams& other);
133     InstanceParams(InstanceParams&&);
134     InstanceParams& operator=(InstanceParams&& other);
135 
136     // Additional trust anchors to consider during path validation. Ordinarily,
137     // implementations of CertVerifier use trust anchors from the configured
138     // system store. This is implementation-specific plumbing for passing
139     // additional anchors through.
140     bssl::ParsedCertificateList additional_trust_anchors;
141 
142     // Same as additional_trust_anchors, but embedded anchor constraints and
143     // NotBefore/NotAfter are enforced.
144     bssl::ParsedCertificateList
145         additional_trust_anchors_with_enforced_constraints;
146 
147     // Additional trust anchors to consider during path validation, but with
148     // name constraints specified outside of the certificate.
149     std::vector<CertificateWithConstraints>
150         additional_trust_anchors_with_constraints;
151 
152     // Additional temporary certs to consider as intermediates during path
153     // validation. Ordinarily, implementations of CertVerifier use intermediate
154     // certs from the configured system store. This is implementation-specific
155     // plumbing for passing additional intermediates through.
156     bssl::ParsedCertificateList additional_untrusted_authorities;
157 
158     //  Additional SPKIs to consider as distrusted during path validation.
159     std::vector<std::vector<uint8_t>> additional_distrusted_spkis;
160 
161     // If true, use the user-added certs in the system trust store for path
162     // validation.
163     // This only has an impact if the Chrome Root Store is being used.
164     bool include_system_trust_store = true;
165   };
166 
167   // These values are persisted to logs. Entries should not be renumbered and
168   // numeric values should never be reused.
169   enum class NameNormalizationResult {
170     kError = 0,
171     kByteEqual = 1,
172     kNormalized = 2,
173     kChainLengthOne = 3,
174     kMaxValue = kChainLengthOne
175   };
176 
177 #if !(BUILDFLAG(IS_FUCHSIA) || BUILDFLAG(IS_LINUX) || \
178       BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(CHROME_ROOT_STORE_ONLY))
179   // Creates and returns a CertVerifyProc that uses the system verifier.
180   // |cert_net_fetcher| may not be used, depending on the implementation.
181   static scoped_refptr<CertVerifyProc> CreateSystemVerifyProc(
182       scoped_refptr<CertNetFetcher> cert_net_fetcher,
183       scoped_refptr<CRLSet> crl_set);
184 #endif
185 
186 #if BUILDFLAG(IS_FUCHSIA)
187   // Creates and returns a CertVerifyProcBuiltin using the SSL SystemTrustStore.
188   static scoped_refptr<CertVerifyProc> CreateBuiltinVerifyProc(
189       scoped_refptr<CertNetFetcher> cert_net_fetcher,
190       scoped_refptr<CRLSet> crl_set,
191       std::unique_ptr<CTVerifier> ct_verifier,
192       scoped_refptr<CTPolicyEnforcer> ct_policy_enforcer,
193       const InstanceParams instance_params);
194 #endif
195 
196 #if BUILDFLAG(CHROME_ROOT_STORE_SUPPORTED)
197   // Creates and returns a CertVerifyProcBuiltin using the Chrome Root Store
198   // SystemTrustStore and the given |root_store_data|, which may be nullptr to
199   // use the default.
200   static scoped_refptr<CertVerifyProc> CreateBuiltinWithChromeRootStore(
201       scoped_refptr<CertNetFetcher> cert_net_fetcher,
202       scoped_refptr<CRLSet> crl_set,
203       std::unique_ptr<CTVerifier> ct_verifier,
204       scoped_refptr<CTPolicyEnforcer> ct_policy_enforcer,
205       const ChromeRootStoreData* root_store_data,
206       const InstanceParams instance_params);
207 #endif
208 
209   CertVerifyProc(const CertVerifyProc&) = delete;
210   CertVerifyProc& operator=(const CertVerifyProc&) = delete;
211 
212   // Verifies the certificate against the given hostname as an SSL server
213   // certificate. Returns OK if successful or an error code upon failure.
214   //
215   // The |*verify_result| structure, including the |verify_result->cert_status|
216   // bitmask, is always filled out regardless of the return value. If the
217   // certificate has multiple errors, the corresponding status flags are set in
218   // |verify_result->cert_status|, and the error code for the most serious
219   // error is returned.
220   //
221   // |ocsp_response|, if non-empty, is a stapled OCSP response to use.
222   //
223   // |sct_list|, if non-empty, is a SignedCertificateTimestampList from the TLS
224   // extension as described in RFC6962 section 3.3.1.
225   //
226   // |flags| is bitwise OR'd of VerifyFlags:
227   //
228   // If |time_now| is set it will be used as the current time, otherwise the
229   // system time will be used.
230   //
231   // If VERIFY_REV_CHECKING_ENABLED is set in |flags|, online certificate
232   // revocation checking is performed (i.e. OCSP and downloading CRLs). CRLSet
233   // based revocation checking is always enabled, regardless of this flag.
234   int Verify(X509Certificate* cert,
235              const std::string& hostname,
236              const std::string& ocsp_response,
237              const std::string& sct_list,
238              int flags,
239              CertVerifyResult* verify_result,
240              const NetLogWithSource& net_log,
241              std::optional<base::Time> time_now = std::nullopt);
242 
243  protected:
244   explicit CertVerifyProc(scoped_refptr<CRLSet> crl_set);
245   virtual ~CertVerifyProc();
246 
crl_set()247   CRLSet* crl_set() const { return crl_set_.get(); }
248 
249   // Record a histogram of whether Name normalization was used in verifying the
250   // chain. This should only be called for successfully validated chains.
251   static void LogNameNormalizationResult(const std::string& histogram_suffix,
252                                          NameNormalizationResult result);
253 
254   // Record a histogram of whether Name normalization was used in verifying the
255   // chain. This should only be called for successfully validated chains.
256   static void LogNameNormalizationMetrics(const std::string& histogram_suffix,
257                                           X509Certificate* verified_cert,
258                                           bool is_issued_by_known_root);
259 
260  private:
261   friend class base::RefCountedThreadSafe<CertVerifyProc>;
262   FRIEND_TEST_ALL_PREFIXES(CertVerifyProcTest, DigiNotarCerts);
263   FRIEND_TEST_ALL_PREFIXES(CertVerifyProcTest, TestHasTooLongValidity);
264   FRIEND_TEST_ALL_PREFIXES(CertVerifyProcTest,
265                            VerifyRejectsSHA1AfterDeprecationLegacyMode);
266   FRIEND_TEST_ALL_PREFIXES(CertVerifyProcTest, SymantecCertsRejected);
267 
268   // Performs the actual verification using the desired underlying
269   //
270   // On entry, |verify_result| will be default-initialized as a successful
271   // validation, with |verify_result->verified_cert| set to |cert|.
272   //
273   // Implementations are expected to fill in all applicable fields, excluding:
274   //
275   // * ocsp_result
276   // * has_sha1
277   //
278   // which will be filled in by |Verify()|. If an error code is returned,
279   // |verify_result->cert_status| should be non-zero, indicating an
280   // error occurred.
281   //
282   // If |time_now| is not nullopt, it will be used as the current time for
283   // certificate verification, if it is nullopt, the system time will be used
284   // instead. If a certificate verification fails with a NotBefore/NotAfter
285   // error when |time_now| is set, it will be retried with the system time.
286   //
287   // On success, net::OK should be returned, with |verify_result| updated to
288   // reflect the successfully verified chain.
289   virtual int VerifyInternal(X509Certificate* cert,
290                              const std::string& hostname,
291                              const std::string& ocsp_response,
292                              const std::string& sct_list,
293                              int flags,
294                              CertVerifyResult* verify_result,
295                              const NetLogWithSource& net_log,
296                              std::optional<base::Time> time_now) = 0;
297 
298   // HasNameConstraintsViolation returns true iff one of |public_key_hashes|
299   // (which are hashes of SubjectPublicKeyInfo structures) has name constraints
300   // imposed on it and the names in |dns_names| are not permitted.
301   static bool HasNameConstraintsViolation(
302       const HashValueVector& public_key_hashes,
303       const std::string& common_name,
304       const std::vector<std::string>& dns_names,
305       const std::vector<std::string>& ip_addrs);
306 
307   // Checks the validity period of the certificate against the maximum
308   // allowable validity period for publicly trusted certificates. Returns true
309   // if the validity period is too long.
310   static bool HasTooLongValidity(const X509Certificate& cert);
311 
312   const scoped_refptr<CRLSet> crl_set_;
313 };
314 
315 // Factory for creating new CertVerifyProcs when they need to be updated.
316 class NET_EXPORT CertVerifyProcFactory
317     : public base::RefCountedThreadSafe<CertVerifyProcFactory> {
318  public:
319 
320   // Create a new CertVerifyProc that uses the passed in CRLSet and
321   // ChromeRootStoreData.
322   virtual scoped_refptr<CertVerifyProc> CreateCertVerifyProc(
323       scoped_refptr<CertNetFetcher> cert_net_fetcher,
324       const CertVerifyProc::ImplParams& impl_params,
325       const CertVerifyProc::InstanceParams& instance_params) = 0;
326 
327  protected:
328   virtual ~CertVerifyProcFactory() = default;
329 
330  private:
331   friend class base::RefCountedThreadSafe<CertVerifyProcFactory>;
332 };
333 
334 }  // namespace net
335 
336 #endif  // NET_CERT_CERT_VERIFY_PROC_H_
337