• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2017 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/cert/internal/revocation_checker.h"
6 
7 #include <string>
8 
9 #include "base/logging.h"
10 #include "base/strings/string_piece.h"
11 #include "crypto/sha2.h"
12 #include "net/cert/cert_net_fetcher.h"
13 #include "net/cert/ocsp_verify_result.h"
14 #include "net/cert/pki/common_cert_errors.h"
15 #include "net/cert/pki/crl.h"
16 #include "net/cert/pki/ocsp.h"
17 #include "net/cert/pki/parsed_certificate.h"
18 #include "net/cert/pki/trust_store.h"
19 #include "third_party/abseil-cpp/absl/types/optional.h"
20 #include "url/gurl.h"
21 
22 namespace net {
23 
24 namespace {
25 
MarkCertificateRevoked(CertErrors * errors)26 void MarkCertificateRevoked(CertErrors* errors) {
27   // TODO(eroman): Add a parameter to the error indicating which mechanism
28   // caused the revocation (i.e. CRLSet, OCSP, stapled OCSP, etc).
29   errors->AddError(cert_errors::kCertificateRevoked);
30 }
31 
32 // Checks the revocation status of |certs[target_cert_index]| according to
33 // |policy|. If the checks failed, returns false and adds errors to
34 // |cert_errors|.
35 //
36 // TODO(eroman): Make the verification time an input.
CheckCertRevocation(const ParsedCertificateList & certs,size_t target_cert_index,const RevocationPolicy & policy,base::TimeTicks deadline,base::StringPiece stapled_ocsp_response,absl::optional<int64_t> max_age_seconds,CertNetFetcher * net_fetcher,CertErrors * cert_errors,OCSPVerifyResult * stapled_ocsp_verify_result)37 bool CheckCertRevocation(const ParsedCertificateList& certs,
38                          size_t target_cert_index,
39                          const RevocationPolicy& policy,
40                          base::TimeTicks deadline,
41                          base::StringPiece stapled_ocsp_response,
42                          absl::optional<int64_t> max_age_seconds,
43                          CertNetFetcher* net_fetcher,
44                          CertErrors* cert_errors,
45                          OCSPVerifyResult* stapled_ocsp_verify_result) {
46   DCHECK_LT(target_cert_index, certs.size());
47   const ParsedCertificate* cert = certs[target_cert_index].get();
48   const ParsedCertificate* issuer_cert =
49       target_cert_index + 1 < certs.size() ? certs[target_cert_index + 1].get()
50                                            : nullptr;
51 
52   // Check using stapled OCSP, if available.
53   if (!stapled_ocsp_response.empty() && issuer_cert) {
54     OCSPVerifyResult::ResponseStatus response_details;
55     OCSPRevocationStatus ocsp_status = CheckOCSP(
56         stapled_ocsp_response, cert, issuer_cert, base::Time::Now().ToTimeT(),
57         max_age_seconds, &response_details);
58     if (stapled_ocsp_verify_result) {
59       stapled_ocsp_verify_result->response_status = response_details;
60       stapled_ocsp_verify_result->revocation_status = ocsp_status;
61     }
62 
63     // TODO(eroman): Save the stapled OCSP response to cache.
64     switch (ocsp_status) {
65       case OCSPRevocationStatus::REVOKED:
66         MarkCertificateRevoked(cert_errors);
67         return false;
68       case OCSPRevocationStatus::GOOD:
69         return true;
70       case OCSPRevocationStatus::UNKNOWN:
71         // TODO(eroman): If the OCSP response was invalid, should we keep
72         //               looking or fail?
73         break;
74     }
75   }
76 
77   if (!policy.check_revocation) {
78     // TODO(eroman): Should still check CRL/OCSP caches.
79     return true;
80   }
81 
82   bool found_revocation_info = false;
83 
84   // Check OCSP.
85   if (cert->has_authority_info_access()) {
86     // Try each of the OCSP URIs
87     for (const auto& ocsp_uri : cert->ocsp_uris()) {
88       // Only consider http:// URLs (https:// could create a circular
89       // dependency).
90       GURL parsed_ocsp_url(ocsp_uri);
91       if (!parsed_ocsp_url.is_valid() ||
92           !parsed_ocsp_url.SchemeIs(url::kHttpScheme)) {
93         continue;
94       }
95 
96       found_revocation_info = true;
97 
98       // Check the deadline after setting found_revocation_info, to not give a
99       // misleading kNoRevocationMechanism failure.
100       if (!deadline.is_null() && base::TimeTicks::Now() > deadline)
101         break;
102 
103       if (!policy.networking_allowed)
104         continue;
105 
106       if (!net_fetcher) {
107         LOG(ERROR) << "Cannot fetch OCSP as didn't specify a |net_fetcher|";
108         continue;
109       }
110 
111       // TODO(eroman): Duplication of work if there are multiple URLs to try.
112       // TODO(eroman): Are there cases where we would need to POST instead?
113       GURL get_url = CreateOCSPGetURL(cert, issuer_cert, ocsp_uri);
114       if (!get_url.is_valid()) {
115         // A failure here could mean an unexpected failure from BoringSSL, or a
116         // problem concatenating the URL.
117         continue;
118       }
119 
120       // Fetch it over network.
121       //
122       // TODO(eroman): Issue POST instead of GET if request is larger than 255
123       //               bytes?
124       // TODO(eroman): Improve interplay with HTTP cache.
125       std::unique_ptr<CertNetFetcher::Request> net_ocsp_request =
126           net_fetcher->FetchOcsp(get_url, CertNetFetcher::DEFAULT,
127                                  CertNetFetcher::DEFAULT);
128 
129       Error net_error;
130       std::vector<uint8_t> ocsp_response_bytes;
131       net_ocsp_request->WaitForResult(&net_error, &ocsp_response_bytes);
132 
133       if (net_error != OK)
134         continue;
135 
136       OCSPVerifyResult::ResponseStatus response_details;
137 
138       OCSPRevocationStatus ocsp_status = CheckOCSP(
139           std::string_view(
140               reinterpret_cast<const char*>(ocsp_response_bytes.data()),
141               ocsp_response_bytes.size()),
142           cert, issuer_cert, base::Time::Now().ToTimeT(), max_age_seconds,
143           &response_details);
144 
145       switch (ocsp_status) {
146         case OCSPRevocationStatus::REVOKED:
147           MarkCertificateRevoked(cert_errors);
148           return false;
149         case OCSPRevocationStatus::GOOD:
150           return true;
151         case OCSPRevocationStatus::UNKNOWN:
152           break;
153       }
154     }
155   }
156 
157   // Check CRLs.
158   ParsedExtension crl_dp_extension;
159   if (policy.crl_allowed &&
160       cert->GetExtension(der::Input(kCrlDistributionPointsOid),
161                          &crl_dp_extension)) {
162     std::vector<ParsedDistributionPoint> distribution_points;
163     if (ParseCrlDistributionPoints(crl_dp_extension.value,
164                                    &distribution_points)) {
165       for (const auto& distribution_point : distribution_points) {
166         if (distribution_point.crl_issuer) {
167           // Ignore indirect CRLs (CRL where CRLissuer != cert issuer), which
168           // are optional according to RFC 5280's profile.
169           continue;
170         }
171 
172         if (distribution_point.reasons) {
173           // Ignore CRLs that only contain some reasons. RFC 5280's profile
174           // requires that conforming CAs "MUST include at least one
175           // DistributionPoint that points to a CRL that covers the certificate
176           // for all reasons".
177           continue;
178         }
179 
180         if (!distribution_point.distribution_point_fullname) {
181           // Only distributionPoints with a fullName containing URIs are
182           // supported.
183           continue;
184         }
185 
186         for (const auto& crl_uri :
187              distribution_point.distribution_point_fullname
188                  ->uniform_resource_identifiers) {
189           // Only consider http:// URLs (https:// could create a circular
190           // dependency).
191           GURL parsed_crl_url(crl_uri);
192           if (!parsed_crl_url.is_valid() ||
193               !parsed_crl_url.SchemeIs(url::kHttpScheme)) {
194             continue;
195           }
196 
197           found_revocation_info = true;
198 
199           // Check the deadline after setting found_revocation_info, to not give
200           // a misleading kNoRevocationMechanism failure.
201           if (!deadline.is_null() && base::TimeTicks::Now() > deadline)
202             break;
203 
204           if (!policy.networking_allowed)
205             continue;
206 
207           if (!net_fetcher) {
208             LOG(ERROR) << "Cannot fetch CRL as didn't specify a |net_fetcher|";
209             continue;
210           }
211 
212           // Fetch it over network.
213           //
214           // Note that no attempt is made to refetch without cache if a cached
215           // CRL is too old, nor is there a separate CRL cache. It is assumed
216           // the CRL server will send reasonable HTTP caching headers.
217           std::unique_ptr<CertNetFetcher::Request> net_crl_request =
218               net_fetcher->FetchCrl(parsed_crl_url, CertNetFetcher::DEFAULT,
219                                     CertNetFetcher::DEFAULT);
220 
221           Error net_error;
222           std::vector<uint8_t> crl_response_bytes;
223           net_crl_request->WaitForResult(&net_error, &crl_response_bytes);
224 
225           if (net_error != OK)
226             continue;
227 
228           CRLRevocationStatus crl_status = CheckCRL(
229               std::string_view(
230                   reinterpret_cast<const char*>(crl_response_bytes.data()),
231                   crl_response_bytes.size()),
232               certs, target_cert_index, distribution_point,
233               base::Time::Now().ToTimeT(), max_age_seconds);
234 
235           switch (crl_status) {
236             case CRLRevocationStatus::REVOKED:
237               MarkCertificateRevoked(cert_errors);
238               return false;
239             case CRLRevocationStatus::GOOD:
240               return true;
241             case CRLRevocationStatus::UNKNOWN:
242               break;
243           }
244         }
245       }
246     }
247   }
248 
249   // Reaching here means that revocation checking was inconclusive. Determine
250   // whether failure to complete revocation checking constitutes an error.
251 
252   if (!found_revocation_info) {
253     if (policy.allow_missing_info) {
254       // If the certificate lacked any (recognized) revocation mechanisms, and
255       // the policy permits it, consider revocation checking a success.
256       return true;
257     } else {
258       // If the certificate lacked any (recognized) revocation mechanisms, and
259       // the policy forbids it, fail revocation checking.
260       cert_errors->AddError(cert_errors::kNoRevocationMechanism);
261       return false;
262     }
263   }
264 
265   // In soft-fail mode permit other failures.
266   // TODO(eroman): Add a warning to |cert_errors| indicating the failure.
267   if (policy.allow_unable_to_check)
268     return true;
269 
270   // Otherwise the policy doesn't allow revocation checking to fail.
271   cert_errors->AddError(cert_errors::kUnableToCheckRevocation);
272   return false;
273 }
274 
275 }  // namespace
276 
CheckValidatedChainRevocation(const ParsedCertificateList & certs,const RevocationPolicy & policy,base::TimeTicks deadline,base::StringPiece stapled_leaf_ocsp_response,CertNetFetcher * net_fetcher,CertPathErrors * errors,OCSPVerifyResult * stapled_ocsp_verify_result)277 void CheckValidatedChainRevocation(
278     const ParsedCertificateList& certs,
279     const RevocationPolicy& policy,
280     base::TimeTicks deadline,
281     base::StringPiece stapled_leaf_ocsp_response,
282     CertNetFetcher* net_fetcher,
283     CertPathErrors* errors,
284     OCSPVerifyResult* stapled_ocsp_verify_result) {
285   if (stapled_ocsp_verify_result)
286     *stapled_ocsp_verify_result = OCSPVerifyResult();
287 
288   // Check each certificate for revocation using OCSP/CRL. Checks proceed
289   // from the root certificate towards the leaf certificate. Revocation errors
290   // are added to |errors|.
291   for (size_t reverse_i = 0; reverse_i < certs.size(); ++reverse_i) {
292     size_t i = certs.size() - reverse_i - 1;
293 
294     // Trust anchors bypass OCSP/CRL revocation checks. (The only way to revoke
295     // trust anchors is via CRLSet or the built-in SPKI block list). Since
296     // |certs| must be a validated chain, the final cert must be a trust
297     // anchor.
298     if (reverse_i == 0)
299       continue;
300 
301     // TODO(eroman): Plumb stapled OCSP for non-leaf certificates from TLS?
302     base::StringPiece stapled_ocsp =
303         (i == 0) ? stapled_leaf_ocsp_response : base::StringPiece();
304 
305     absl::optional<int64_t> max_age_seconds;
306     if (policy.enforce_baseline_requirements) {
307       max_age_seconds = ((i == 0) ? kMaxRevocationLeafUpdateAge
308                                   : kMaxRevocationIntermediateUpdateAge)
309                             .InSeconds();
310     }
311 
312     // Check whether this certificate's revocation status complies with the
313     // policy.
314     bool cert_ok = CheckCertRevocation(
315         certs, i, policy, deadline, stapled_ocsp, max_age_seconds, net_fetcher,
316         errors->GetErrorsForCert(i),
317         (i == 0) ? stapled_ocsp_verify_result : nullptr);
318 
319     if (!cert_ok) {
320       // If any certificate in the chain fails revocation checks, the chain is
321       // revoked and no need to check revocation status for the remaining
322       // certificates.
323       DCHECK(errors->GetErrorsForCert(i)->ContainsAnyErrorWithSeverity(
324           CertError::SEVERITY_HIGH));
325       break;
326     }
327   }
328 }
329 
CheckChainRevocationUsingCRLSet(const CRLSet * crl_set,const ParsedCertificateList & certs,CertPathErrors * errors)330 CRLSet::Result CheckChainRevocationUsingCRLSet(
331     const CRLSet* crl_set,
332     const ParsedCertificateList& certs,
333     CertPathErrors* errors) {
334   // Iterate from the root certificate towards the leaf (the root certificate is
335   // also checked for revocation by CRLSet).
336   std::string issuer_spki_hash;
337   for (size_t reverse_i = 0; reverse_i < certs.size(); ++reverse_i) {
338     size_t i = certs.size() - reverse_i - 1;
339     const ParsedCertificate* cert = certs[i].get();
340 
341     // True if |cert| is the root of the chain.
342     const bool is_root = reverse_i == 0;
343     // True if |cert| is the leaf certificate of the chain.
344     const bool is_target = i == 0;
345 
346     // Check for revocation using the certificate's SPKI.
347     std::string spki_hash =
348         crypto::SHA256HashString(cert->tbs().spki_tlv.AsStringView());
349     CRLSet::Result result = crl_set->CheckSPKI(spki_hash);
350 
351     // Check for revocation using the certificate's Subject.
352     if (result != CRLSet::REVOKED) {
353       result = crl_set->CheckSubject(cert->tbs().subject_tlv.AsStringView(),
354                                      spki_hash);
355     }
356 
357     // Check for revocation using the certificate's serial number and issuer's
358     // SPKI.
359     if (result != CRLSet::REVOKED && !is_root) {
360       result = crl_set->CheckSerial(cert->tbs().serial_number.AsStringView(),
361                                     issuer_spki_hash);
362     }
363 
364     // Prepare for the next iteration.
365     issuer_spki_hash = std::move(spki_hash);
366 
367     switch (result) {
368       case CRLSet::REVOKED:
369         MarkCertificateRevoked(errors->GetErrorsForCert(i));
370         return CRLSet::Result::REVOKED;
371       case CRLSet::UNKNOWN:
372         // If the status is unknown, advance to the subordinate certificate.
373         break;
374       case CRLSet::GOOD:
375         if (is_target && !crl_set->IsExpired()) {
376           // If the target is covered by the CRLSet and known good, consider
377           // the entire chain to be valid (even though the revocation status
378           // of the intermediates may have been UNKNOWN).
379           //
380           // Only the leaf certificate is considered for coverage because some
381           // intermediates have CRLs with no revocations (after filtering) and
382           // those CRLs are pruned from the CRLSet at generation time.
383           return CRLSet::Result::GOOD;
384         }
385         break;
386     }
387   }
388 
389   // If no certificate was revoked, and the target was not known good, then
390   // the revocation status is still unknown.
391   return CRLSet::Result::UNKNOWN;
392 }
393 
394 }  // namespace net
395