• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "net/cert/cert_verify_proc_android.h"
6 
7 #include <set>
8 #include <string>
9 #include <string_view>
10 #include <vector>
11 
12 #include "base/check_op.h"
13 #include "base/containers/adapters.h"
14 #include "base/metrics/histogram_functions.h"
15 #include "base/metrics/histogram_macros.h"
16 #include "base/notreached.h"
17 #include "crypto/sha2.h"
18 #include "net/android/cert_verify_result_android.h"
19 #include "net/android/network_library.h"
20 #include "net/base/net_errors.h"
21 #include "net/cert/asn1_util.h"
22 #include "net/cert/cert_net_fetcher.h"
23 #include "net/cert/cert_status_flags.h"
24 #include "net/cert/cert_verify_proc.h"
25 #include "net/cert/cert_verify_result.h"
26 #include "net/cert/crl_set.h"
27 #include "net/cert/known_roots.h"
28 #include "net/cert/test_root_certs.h"
29 #include "net/cert/x509_certificate.h"
30 #include "net/cert/x509_util.h"
31 #include "third_party/boringssl/src/pki/cert_errors.h"
32 #include "third_party/boringssl/src/pki/parsed_certificate.h"
33 #include "url/gurl.h"
34 
35 namespace net {
36 
37 namespace {
38 
39 // Android ignores the authType parameter to
40 // X509TrustManager.checkServerTrusted, so pass in a dummy value. See
41 // https://crbug.com/627154.
42 const char kAuthType[] = "RSA";
43 
44 // The maximum number of AIA fetches that TryVerifyWithAIAFetching() will
45 // attempt. If a valid chain cannot be built after this many fetches,
46 // TryVerifyWithAIAFetching() will give up and return
47 // CERT_VERIFY_STATUS_ANDROID_NO_TRUSTED_ROOT.
48 const unsigned int kMaxAIAFetches = 5;
49 
50 // Starting at certs[start], this function searches |certs| for an issuer of
51 // certs[start], then for an issuer of that issuer, and so on until it finds a
52 // certificate |cert| for which |certs| does not contain an issuer of
53 // |cert|. Returns a pointer to this |cert|, or nullptr if all certificates
54 // while path-building from |start| have an issuer in |certs| (including if
55 // there is a loop). Note that the returned certificate will be equal to |start|
56 // if |start| does not have an issuer in |certs|.
57 //
58 // TODO(estark): when searching for an issuer, this always uses the first
59 // encountered issuer in |certs|, and does not handle the situation where
60 // |certs| contains more than one issuer for a given certificate.
FindLastCertWithUnknownIssuer(const bssl::ParsedCertificateList & certs,const std::shared_ptr<const bssl::ParsedCertificate> & start)61 std::shared_ptr<const bssl::ParsedCertificate> FindLastCertWithUnknownIssuer(
62     const bssl::ParsedCertificateList& certs,
63     const std::shared_ptr<const bssl::ParsedCertificate>& start) {
64   DCHECK_GE(certs.size(), 1u);
65   std::set<std::shared_ptr<const bssl::ParsedCertificate>> used_in_path;
66   std::shared_ptr<const bssl::ParsedCertificate> last = start;
67   while (true) {
68     used_in_path.insert(last);
69     std::shared_ptr<const bssl::ParsedCertificate> last_issuer;
70     // Find an issuer for |last| (which might be |last| itself if self-signed).
71     for (const auto& cert : certs) {
72       if (cert->normalized_subject() == last->normalized_issuer()) {
73         last_issuer = cert;
74         break;
75       }
76     }
77     if (!last_issuer) {
78       // There is no issuer for |last| in |certs|.
79       return last;
80     }
81     if (last_issuer->normalized_subject() == last_issuer->normalized_issuer()) {
82       // A chain can be built from |start| to a self-signed certificate, so
83       // return nullptr to indicate that there is no certificate with an unknown
84       // issuer.
85       return nullptr;
86     }
87     if (used_in_path.find(last_issuer) != used_in_path.end()) {
88       // |certs| contains a loop.
89       return nullptr;
90     }
91     // Continue the search for |last_issuer|'s issuer.
92     last = last_issuer;
93   }
94   NOTREACHED();
95 }
96 
97 // Uses |fetcher| to fetch issuers from |uri|. If the fetch succeeds, the
98 // certificate is parsed and added to |cert_list|. Returns true if the fetch was
99 // successful and the result could be parsed as a certificate, and false
100 // otherwise.
PerformAIAFetchAndAddResultToVector(scoped_refptr<CertNetFetcher> fetcher,std::string_view uri,bssl::ParsedCertificateList * cert_list)101 bool PerformAIAFetchAndAddResultToVector(
102     scoped_refptr<CertNetFetcher> fetcher,
103     std::string_view uri,
104     bssl::ParsedCertificateList* cert_list) {
105   GURL url(uri);
106   if (!url.is_valid())
107     return false;
108   std::unique_ptr<CertNetFetcher::Request> request(fetcher->FetchCaIssuers(
109       url, CertNetFetcher::DEFAULT, CertNetFetcher::DEFAULT));
110   Error error;
111   std::vector<uint8_t> aia_fetch_bytes;
112   request->WaitForResult(&error, &aia_fetch_bytes);
113   if (error != OK)
114     return false;
115   bssl::CertErrors errors;
116   return bssl::ParsedCertificate::CreateAndAddToVector(
117       x509_util::CreateCryptoBuffer(aia_fetch_bytes),
118       x509_util::DefaultParseCertificateOptions(), cert_list, &errors);
119 }
120 
121 // Uses android::VerifyX509CertChain() to verify the certificates in |certs| for
122 // |hostname| and returns the verification status. If the verification was
123 // successful, this function populates |verify_result| and |verified_chain|;
124 // otherwise it leaves them untouched.
AttemptVerificationAfterAIAFetch(const bssl::ParsedCertificateList & certs,const std::string & hostname,CertVerifyResult * verify_result,std::vector<std::string> * verified_chain)125 android::CertVerifyStatusAndroid AttemptVerificationAfterAIAFetch(
126     const bssl::ParsedCertificateList& certs,
127     const std::string& hostname,
128     CertVerifyResult* verify_result,
129     std::vector<std::string>* verified_chain) {
130   std::vector<std::string> cert_bytes;
131   for (const auto& cert : certs) {
132     cert_bytes.push_back(cert->der_cert().AsString());
133   }
134 
135   bool is_issued_by_known_root;
136   std::vector<std::string> candidate_verified_chain;
137   android::CertVerifyStatusAndroid status;
138   android::VerifyX509CertChain(cert_bytes, kAuthType, hostname, &status,
139                                &is_issued_by_known_root,
140                                &candidate_verified_chain);
141 
142   if (status == android::CERT_VERIFY_STATUS_ANDROID_OK) {
143     verify_result->is_issued_by_known_root = is_issued_by_known_root;
144     *verified_chain = candidate_verified_chain;
145   }
146   return status;
147 }
148 
149 // After a CERT_VERIFY_STATUS_ANDROID_NO_TRUSTED_ROOT error is encountered, this
150 // function can be called to fetch intermediates and retry verification.
151 //
152 // It will start from the first certificate in |cert_bytes| and construct a
153 // chain as far as it can using certificates in |cert_bytes|, and then
154 // iteratively fetch issuers from any AIA URLs in the last certificate in this
155 // chain. It will fetch issuers until it encounters a chain that verifies with
156 // status CERT_VERIFY_STATUS_ANDROID_OK, or it runs out of AIA URLs to fetch, or
157 // it has attempted |kMaxAIAFetches| fetches.
158 //
159 // If it finds a chain that verifies successfully, it returns
160 // CERT_VERIFY_STATUS_ANDROID_OK and sets |verify_result| and |verified_chain|
161 // correspondingly. Otherwise, it returns
162 // CERT_VERIFY_STATUS_ANDROID_NO_TRUSTED_ROOT and does not modify
163 // |verify_result| or |verified_chain|.
TryVerifyWithAIAFetching(const std::vector<std::string> & cert_bytes,const std::string & hostname,scoped_refptr<CertNetFetcher> cert_net_fetcher,CertVerifyResult * verify_result,std::vector<std::string> * verified_chain)164 android::CertVerifyStatusAndroid TryVerifyWithAIAFetching(
165     const std::vector<std::string>& cert_bytes,
166     const std::string& hostname,
167     scoped_refptr<CertNetFetcher> cert_net_fetcher,
168     CertVerifyResult* verify_result,
169     std::vector<std::string>* verified_chain) {
170   if (!cert_net_fetcher)
171     return android::CERT_VERIFY_STATUS_ANDROID_NO_TRUSTED_ROOT;
172 
173   // Convert the certificates into ParsedCertificates for ease of pulling out
174   // AIA URLs.
175   bssl::CertErrors errors;
176   bssl::ParsedCertificateList certs;
177   for (const auto& cert : cert_bytes) {
178     if (!bssl::ParsedCertificate::CreateAndAddToVector(
179             x509_util::CreateCryptoBuffer(cert),
180             x509_util::DefaultParseCertificateOptions(), &certs, &errors)) {
181       return android::CERT_VERIFY_STATUS_ANDROID_NO_TRUSTED_ROOT;
182     }
183   }
184 
185   // Build a chain as far as possible from the target certificate at index 0,
186   // using the initially provided certificates.
187   std::shared_ptr<const bssl::ParsedCertificate> last_cert_with_unknown_issuer =
188       FindLastCertWithUnknownIssuer(certs, certs[0]);
189   if (!last_cert_with_unknown_issuer) {
190     // |certs| either contains a loop, or contains a full chain to a self-signed
191     // certificate. Do not attempt AIA fetches for such a chain.
192     return android::CERT_VERIFY_STATUS_ANDROID_NO_TRUSTED_ROOT;
193   }
194 
195   unsigned int num_aia_fetches = 0;
196   while (true) {
197     // If chain-building has terminated in a certificate that does not have an
198     // AIA URL, give up.
199     //
200     // TODO(estark): Instead of giving up at this point, it would be more robust
201     // to go back to the certificate before |last_cert| in the chain and attempt
202     // an AIA fetch from that point (if one hasn't already been done). This
203     // would accomodate chains where the server serves Leaf -> I1 signed by a
204     // root not in the client's trust store, but AIA fetching would yield an
205     // intermediate I2 signed by a root that *is* in the client's trust store.
206     if (!last_cert_with_unknown_issuer->has_authority_info_access())
207       return android::CERT_VERIFY_STATUS_ANDROID_NO_TRUSTED_ROOT;
208 
209     for (const auto& uri : last_cert_with_unknown_issuer->ca_issuers_uris()) {
210       num_aia_fetches++;
211       if (num_aia_fetches > kMaxAIAFetches)
212         return android::CERT_VERIFY_STATUS_ANDROID_NO_TRUSTED_ROOT;
213       if (!PerformAIAFetchAndAddResultToVector(cert_net_fetcher, uri, &certs))
214         continue;
215       android::CertVerifyStatusAndroid status =
216           AttemptVerificationAfterAIAFetch(certs, hostname, verify_result,
217                                            verified_chain);
218       if (status == android::CERT_VERIFY_STATUS_ANDROID_OK)
219         return status;
220     }
221 
222     // If verification still failed but the path expanded, continue to attempt
223     // AIA fetches.
224     std::shared_ptr<const bssl::ParsedCertificate>
225         new_last_cert_with_unknown_issuer =
226             FindLastCertWithUnknownIssuer(certs, last_cert_with_unknown_issuer);
227     if (!new_last_cert_with_unknown_issuer ||
228         new_last_cert_with_unknown_issuer == last_cert_with_unknown_issuer) {
229       // The last round of AIA fetches (if there were any) didn't expand the
230       // path, or it did such that |certs| now contains a full path to an
231       // (untrusted) root or a loop.
232       //
233       // TODO(estark): As above, it would be more robust to go back one
234       // certificate and attempt an AIA fetch from that point.
235       return android::CERT_VERIFY_STATUS_ANDROID_NO_TRUSTED_ROOT;
236     }
237     last_cert_with_unknown_issuer = new_last_cert_with_unknown_issuer;
238   }
239 
240   NOTREACHED();
241 }
242 
243 // Returns true if the certificate verification call was successful (regardless
244 // of its result), i.e. if |verify_result| was set. Otherwise returns false.
VerifyFromAndroidTrustManager(const std::vector<std::string> & cert_bytes,const std::string & hostname,int flags,scoped_refptr<CertNetFetcher> cert_net_fetcher,CertVerifyResult * verify_result)245 bool VerifyFromAndroidTrustManager(
246     const std::vector<std::string>& cert_bytes,
247     const std::string& hostname,
248     int flags,
249     scoped_refptr<CertNetFetcher> cert_net_fetcher,
250     CertVerifyResult* verify_result) {
251   android::CertVerifyStatusAndroid status;
252   std::vector<std::string> verified_chain;
253 
254   android::VerifyX509CertChain(cert_bytes, kAuthType, hostname, &status,
255                                &verify_result->is_issued_by_known_root,
256                                &verified_chain);
257 
258   // If verification resulted in a NO_TRUSTED_ROOT error, then fetch
259   // intermediates and retry.
260   if (status == android::CERT_VERIFY_STATUS_ANDROID_NO_TRUSTED_ROOT &&
261       !(flags & CertVerifyProc::VERIFY_DISABLE_NETWORK_FETCHES)) {
262     status = TryVerifyWithAIAFetching(cert_bytes, hostname,
263                                       std::move(cert_net_fetcher),
264                                       verify_result, &verified_chain);
265   }
266 
267   switch (status) {
268     case android::CERT_VERIFY_STATUS_ANDROID_FAILED:
269       return false;
270     case android::CERT_VERIFY_STATUS_ANDROID_OK:
271       break;
272     case android::CERT_VERIFY_STATUS_ANDROID_NO_TRUSTED_ROOT:
273       verify_result->cert_status |= CERT_STATUS_AUTHORITY_INVALID;
274       break;
275     case android::CERT_VERIFY_STATUS_ANDROID_EXPIRED:
276     case android::CERT_VERIFY_STATUS_ANDROID_NOT_YET_VALID:
277       verify_result->cert_status |= CERT_STATUS_DATE_INVALID;
278       break;
279     case android::CERT_VERIFY_STATUS_ANDROID_UNABLE_TO_PARSE:
280       verify_result->cert_status |= CERT_STATUS_INVALID;
281       break;
282     case android::CERT_VERIFY_STATUS_ANDROID_INCORRECT_KEY_USAGE:
283       verify_result->cert_status |= CERT_STATUS_INVALID;
284       break;
285     default:
286       NOTREACHED();
287   }
288 
289   // Save the verified chain.
290   if (!verified_chain.empty()) {
291     std::vector<std::string_view> verified_chain_pieces(verified_chain.size());
292     for (size_t i = 0; i < verified_chain.size(); i++) {
293       verified_chain_pieces[i] = std::string_view(verified_chain[i]);
294     }
295     scoped_refptr<X509Certificate> verified_cert =
296         X509Certificate::CreateFromDERCertChain(verified_chain_pieces);
297     if (verified_cert.get())
298       verify_result->verified_cert = std::move(verified_cert);
299     else
300       verify_result->cert_status |= CERT_STATUS_INVALID;
301   }
302 
303   // Extract the public key hashes and check whether or not any are known
304   // roots. Walk from the end of the chain (root) to leaf, to optimize for
305   // known root checks.
306   for (const auto& cert : base::Reversed(verified_chain)) {
307     std::string_view spki_bytes;
308     if (!asn1::ExtractSPKIFromDERCert(cert, &spki_bytes)) {
309       verify_result->cert_status |= CERT_STATUS_INVALID;
310       continue;
311     }
312 
313     HashValue sha256(HASH_VALUE_SHA256);
314     crypto::SHA256HashString(spki_bytes, sha256.data(), crypto::kSHA256Length);
315     verify_result->public_key_hashes.push_back(sha256);
316 
317     if (!verify_result->is_issued_by_known_root) {
318       verify_result->is_issued_by_known_root =
319           GetNetTrustAnchorHistogramIdForSPKI(sha256) != 0;
320     }
321   }
322 
323   // Reverse the hash list, to maintain the leaf->root ordering.
324   std::reverse(verify_result->public_key_hashes.begin(),
325                verify_result->public_key_hashes.end());
326 
327   return true;
328 }
329 
GetChainDEREncodedBytes(X509Certificate * cert,std::vector<std::string> * chain_bytes)330 void GetChainDEREncodedBytes(X509Certificate* cert,
331                              std::vector<std::string>* chain_bytes) {
332   chain_bytes->reserve(1 + cert->intermediate_buffers().size());
333   chain_bytes->emplace_back(
334       net::x509_util::CryptoBufferAsStringPiece(cert->cert_buffer()));
335   for (const auto& handle : cert->intermediate_buffers()) {
336     chain_bytes->emplace_back(
337         net::x509_util::CryptoBufferAsStringPiece(handle.get()));
338   }
339 }
340 
341 }  // namespace
342 
CertVerifyProcAndroid(scoped_refptr<CertNetFetcher> cert_net_fetcher,scoped_refptr<CRLSet> crl_set)343 CertVerifyProcAndroid::CertVerifyProcAndroid(
344     scoped_refptr<CertNetFetcher> cert_net_fetcher,
345     scoped_refptr<CRLSet> crl_set)
346     : CertVerifyProc(std::move(crl_set)),
347       cert_net_fetcher_(std::move(cert_net_fetcher)) {}
348 
349 CertVerifyProcAndroid::~CertVerifyProcAndroid() = default;
350 
VerifyInternal(X509Certificate * cert,const std::string & hostname,const std::string & ocsp_response,const std::string & sct_list,int flags,CertVerifyResult * verify_result,const NetLogWithSource & net_log)351 int CertVerifyProcAndroid::VerifyInternal(X509Certificate* cert,
352                                           const std::string& hostname,
353                                           const std::string& ocsp_response,
354                                           const std::string& sct_list,
355                                           int flags,
356                                           CertVerifyResult* verify_result,
357                                           const NetLogWithSource& net_log) {
358   std::vector<std::string> cert_bytes;
359   GetChainDEREncodedBytes(cert, &cert_bytes);
360   if (!VerifyFromAndroidTrustManager(cert_bytes, hostname, flags,
361                                      cert_net_fetcher_, verify_result)) {
362     return ERR_FAILED;
363   }
364 
365   if (IsCertStatusError(verify_result->cert_status))
366     return MapCertStatusToNetError(verify_result->cert_status);
367 
368   if (TestRootCerts::HasInstance() &&
369       !verify_result->verified_cert->intermediate_buffers().empty() &&
370       TestRootCerts::GetInstance()->IsKnownRoot(x509_util::CryptoBufferAsSpan(
371           verify_result->verified_cert->intermediate_buffers().back().get()))) {
372     verify_result->is_issued_by_known_root = true;
373   }
374 
375   LogNameNormalizationMetrics(".Android", verify_result->verified_cert.get(),
376                               verify_result->is_issued_by_known_root);
377 
378   return OK;
379 }
380 
381 }  // namespace net
382