Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(500)

Side by Side Diff: net/cert/cert_verify_proc_builtin.cc

Issue 2755483008: Add initial CertVerifyProcBuiltin. (Closed)
Patch Set: Created 3 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « net/cert/cert_verify_proc_builtin.h ('k') | net/cert/cert_verify_proc_unittest.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright (c) 2017 The Chromium Authors. All rights reserved.
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_builtin.h"
6
7 #include <string>
8 #include <vector>
9
10 #if defined(USE_NSS_CERTS)
11 #include <cert.h>
12 #include <pk11pub.h>
13 #endif
14
15 #include "base/logging.h"
16 #include "base/memory/ptr_util.h"
17 #include "base/sha1.h"
18 #include "base/strings/string_piece.h"
19 #include "crypto/sha2.h"
20 #include "net/base/net_errors.h"
21 #include "net/cert/asn1_util.h"
22 #include "net/cert/cert_status_flags.h"
23 #include "net/cert/cert_verify_proc.h"
24 #include "net/cert/cert_verify_result.h"
25 #include "net/cert/internal/cert_errors.h"
26 #include "net/cert/internal/cert_issuer_source_static.h"
27 #include "net/cert/internal/parsed_certificate.h"
28 #include "net/cert/internal/path_builder.h"
29 #include "net/cert/internal/signature_policy.h"
30 #include "net/cert/internal/trust_store_collection.h"
31 #include "net/cert/internal/trust_store_in_memory.h"
32 #include "net/cert/internal/verify_certificate_chain.h"
33 #include "net/cert/x509_certificate.h"
34 #include "net/cert/x509_util.h"
35 #include "net/der/encode_values.h"
36
37 #if defined(USE_NSS_CERTS)
38 #include "crypto/nss_util.h"
39 #include "net/cert/internal/cert_issuer_source_nss.h"
40 #include "net/cert/internal/trust_store_nss.h"
41 #endif
42
43 namespace net {
44
45 namespace {
46
47 class CertVerifyProcBuiltin : public CertVerifyProc {
48 public:
49 CertVerifyProcBuiltin();
50
51 bool SupportsAdditionalTrustAnchors() const override;
52 bool SupportsOCSPStapling() const override;
53
54 protected:
55 ~CertVerifyProcBuiltin() override;
56
57 private:
58 int VerifyInternal(X509Certificate* cert,
59 const std::string& hostname,
60 const std::string& ocsp_response,
61 int flags,
62 CRLSet* crl_set,
63 const CertificateList& additional_trust_anchors,
64 CertVerifyResult* verify_result) override;
65 };
66
67 CertVerifyProcBuiltin::CertVerifyProcBuiltin() {}
68
69 CertVerifyProcBuiltin::~CertVerifyProcBuiltin() {}
70
71 bool CertVerifyProcBuiltin::SupportsAdditionalTrustAnchors() const {
72 return true;
73 }
74
75 bool CertVerifyProcBuiltin::SupportsOCSPStapling() const {
76 // TODO(crbug.com/649017): Implement.
77 return false;
78 }
79
80 scoped_refptr<ParsedCertificate> ParseCertificateFromOSHandle(
81 X509Certificate::OSCertHandle cert_handle,
82 CertErrors* errors) {
83 std::string cert_bytes;
84 if (!X509Certificate::GetDEREncoded(cert_handle, &cert_bytes))
85 return nullptr;
86 return ParsedCertificate::Create(x509_util::CreateCryptoBuffer(cert_bytes),
87 {}, errors);
88 }
89
90 void AddIntermediatesToIssuerSource(X509Certificate* cert,
91 CertIssuerSourceStatic* intermediates) {
92 auto cert_handles = cert->GetIntermediateCertificates();
93 CertErrors errors;
94 for (auto it = cert_handles.begin(); it != cert_handles.end(); ++it) {
95 auto cert = ParseCertificateFromOSHandle(*it, &errors);
96 if (cert)
97 intermediates->AddCert(std::move(cert));
98 // TODO(crbug.com/634443): Surface these parsing errors?
99 }
100 }
101
102 // The SystemTrustStore interface augments the TrustStore interface with some
103 // additional functionality:
104 //
105 // * Determine if a trust anchor was one of the known roots
106 // * Determine if a trust anchor was one of the "extra" ones that
107 // was specified during verification.
108 //
109 // Implementations of SystemTrustStore create an effective trust
110 // store that is the composition of:
111 //
112 // (1) System trust store
113 // (2) |additional_trust_anchors|.
114 // (3) Test certificates (if they are separate from system trust store)
115 class SystemTrustStore {
116 public:
117 virtual TrustStore* GetTrustStore() = 0;
118
119 // TODO(eroman): Can this be exposed through the TrustStore
120 // interface instead?
121 virtual CertIssuerSource* GetCertIssuerSource() = 0;
122
123 // IsKnownRoot returns true if the given trust anchor is a standard one (as
124 // opposed to a user-installed root)
125 virtual bool IsKnownRoot(
126 const scoped_refptr<TrustAnchor>& trust_anchor) const = 0;
127
128 virtual bool IsAdditionalTrustAnchor(
129 const scoped_refptr<TrustAnchor>& trust_anchor) const = 0;
130 };
131
132 #if defined(USE_NSS_CERTS)
133 class SystemTrustStoreNSS : public SystemTrustStore {
134 public:
135 explicit SystemTrustStoreNSS(const CertificateList& additional_trust_anchors)
136 : trust_store_nss_(trustSSL) {
137 CertErrors errors;
138
139 trust_store_.AddTrustStore(&additional_trust_store_);
140 for (const auto& x590_cert : additional_trust_anchors) {
141 scoped_refptr<ParsedCertificate> cert =
142 ParseCertificateFromOSHandle(x590_cert->os_cert_handle(), &errors);
143 if (cert) {
144 additional_trust_store_.AddTrustAnchor(
145 TrustAnchor::CreateFromCertificateNoConstraints(cert));
146 }
147 // TODO(eroman): Surface parsing errors of additional trust anchor.
148 }
149
150 trust_store_.AddTrustStore(&trust_store_nss_);
151 }
152
153 TrustStore* GetTrustStore() override { return &trust_store_; }
154
155 CertIssuerSource* GetCertIssuerSource() override {
156 return &cert_issuer_source_nss_;
157 }
158
159 // IsKnownRoot returns true if the given trust anchor is a standard one (as
160 // opposed to a user-installed root)
161 bool IsKnownRoot(
162 const scoped_refptr<TrustAnchor>& trust_anchor) const override {
163 // TODO(eroman): Based on how the TrustAnchors are created by this
164 // integration, there will always be an associated certificate. However this
165 // contradicts the API for TrustAnchor that states it is optional.
166 DCHECK(trust_anchor->cert());
167
168 // TODO(eroman): The overall approach of IsKnownRoot() is inefficient -- it
169 // requires searching for the trust anchor by name in NSS (path building
mattm 2017/03/16 02:58:23 I think you could use CERT_FindCertByDERCert inste
eroman 2017/03/16 17:35:40 Good idea, Done.
170 // already did this), and then testing matches for equality.
171 crypto::EnsureNSSInit();
172 SECItem name;
173 // Use the original issuer value instead of the normalized version. NSS does
174 // a less extensive normalization in its Name comparisons, so our normalized
175 // version may not match the unnormalized version.
176 name.len = trust_anchor->cert()->tbs().subject_tlv.Length();
177 name.data = const_cast<uint8_t*>(
178 trust_anchor->cert()->tbs().issuer_tlv.UnsafeData());
179 // |validOnly| in CERT_CreateSubjectCertList controls whether to return only
180 // certs that are valid at |sorttime|. Expiration isn't meaningful for trust
181 // anchors, so request all the matches.
182 CERTCertList* found_certs = CERT_CreateSubjectCertList(
183 nullptr /* certList */, CERT_GetDefaultCertDB(), &name,
184 PR_Now() /* sorttime */, PR_FALSE /* validOnly */);
185 if (!found_certs)
186 return false;
187
188 // Search through the matches and find the first one that matches the given
189 // |trust_anchor|. Equality is determined by having the two certificates'
190 // DER match.
191 CERTCertificate* root_cert = nullptr;
192 for (CERTCertListNode* node = CERT_LIST_HEAD(found_certs);
193 !CERT_LIST_END(node, found_certs); node = CERT_LIST_NEXT(node)) {
194 if (trust_anchor->cert()->der_cert() ==
195 der::Input(node->cert->derCert.data, node->cert->derCert.len)) {
196 root_cert = node->cert;
197 break;
198 }
199 }
200
201 return IsKnownRoot(root_cert);
202 }
203
204 bool IsAdditionalTrustAnchor(
205 const scoped_refptr<TrustAnchor>& trust_anchor) const override {
206 return additional_trust_store_.Contains(trust_anchor.get());
207 }
208
209 private:
210 // TODO(eroman): This function was copied verbatim from
211 // cert_verify_proc_nss.cc
212 //
213 // IsKnownRoot returns true if the given certificate is one that we believe
214 // is a standard (as opposed to user-installed) root.
215 bool IsKnownRoot(CERTCertificate* root) const {
216 if (!root || !root->slot)
217 return false;
218
219 // This magic name is taken from
220 // http://bonsai.mozilla.org/cvsblame.cgi?file=mozilla/security/nss/lib/ckfw /builtins/constants.c&rev=1.13&mark=86,89#79
221 return 0 == strcmp(PK11_GetSlotName(root->slot), "NSS Builtin Objects");
222 }
223
224 TrustStoreCollection trust_store_;
225 TrustStoreInMemory additional_trust_store_;
226
227 TrustStoreNSS trust_store_nss_;
228 CertIssuerSourceNSS cert_issuer_source_nss_;
229 };
230 #endif
231
232 std::unique_ptr<SystemTrustStore> CreateSystemTrustStore(
233 const CertificateList& additional_trust_anchors) {
234 #if defined(USE_NSS_CERTS)
235 return base::MakeUnique<SystemTrustStoreNSS>(additional_trust_anchors);
236 #else
237 LOG(ERROR)
mattm 2017/03/16 02:58:24 NOT_IMPLEMENTED() ?
eroman 2017/03/16 17:35:40 Done.
238 << "TODO(crbug.com/649017): Integrate with other system trust stores.";
239 return nullptr;
240 #endif
241 }
242
243 // Appends the SHA1 and SHA256 hashes of |spki_bytes| to |*hashes|.
244 void AppendPublicKeyHashes(const der::Input& spki_bytes,
245 HashValueVector* hashes) {
246 HashValue sha1(HASH_VALUE_SHA1);
247 base::SHA1HashBytes(spki_bytes.UnsafeData(), spki_bytes.Length(),
248 sha1.data());
249 hashes->push_back(sha1);
250
251 HashValue sha256(HASH_VALUE_SHA256);
252 crypto::SHA256HashString(spki_bytes.AsStringPiece(), sha256.data(),
253 crypto::kSHA256Length);
254 hashes->push_back(sha256);
255 }
256
257 // Appends the SubjectPublicKeyInfo hashes for all certificates (and trust
258 // anchor) in |partial_path| to |*hashes|.
259 void AppendPublicKeyHashes(const CertPathBuilder::ResultPath& partial_path,
260 HashValueVector* hashes) {
261 for (const scoped_refptr<ParsedCertificate>& cert : partial_path.path.certs)
262 AppendPublicKeyHashes(cert->tbs().spki_tlv, hashes);
263
264 if (partial_path.path.trust_anchor)
265 AppendPublicKeyHashes(partial_path.path.trust_anchor->spki(), hashes);
266 }
267
268 // Sets the bits on |cert_status| for all the errors encountered during the path
269 // building of |partial_path|.
270 void MapPathBuilderErrorsToCertStatus(
271 const CertPathBuilder::ResultPath& partial_path,
272 CertStatus* cert_status) {
273 // If path building was successful, there are no errors to map (there may have
274 // been warnings but they do not map to CertStatus).
275 if (partial_path.valid)
276 return;
277
278 VLOG(1) << partial_path.errors.ToDebugString();
mattm 2017/03/16 02:58:24 Is this temporary? should it be DVLOG?
eroman 2017/03/16 17:35:40 I changed it to LOG(ERROR) so it is in line with h
279
280 if (partial_path.errors.ContainsError(kRsaModulusTooSmall))
281 *cert_status |= CERT_STATUS_WEAK_KEY;
282
283 if (partial_path.errors.ContainsError(kValidityFailedNotAfter) ||
284 partial_path.errors.ContainsError(kValidityFailedNotBefore)) {
285 *cert_status |= CERT_STATUS_DATE_INVALID;
286 }
287
288 // IMPORTANT: If the path was invalid for a reason that was not
289 // explicity checked above, set a general error. This is important as
290 // |cert_status| is what ultimately indicates whether verification was
291 // successful or not (absense of errors implies success).
292 if (!IsCertStatusError(*cert_status))
293 *cert_status |= CERT_STATUS_INVALID;
294 }
295
296 X509Certificate::OSCertHandle CreateOSCertHandle(
297 const scoped_refptr<ParsedCertificate>& certificate) {
298 return X509Certificate::CreateOSCertHandleFromBytes(
299 reinterpret_cast<const char*>(certificate->der_cert().UnsafeData()),
300 certificate->der_cert().Length());
301 }
302
303 // Creates a X509Certificate (chain) to return as the verified result.
304 //
305 // * |target_cert|: The original X509Certificate that was passed in to
306 // VerifyInternal()
307 // * |path|: The result (possibly failed) from path building.
308 scoped_refptr<X509Certificate> CreateVerifiedCertChain(
309 X509Certificate* target_cert,
310 const CertPathBuilder::ResultPath& path) {
311 X509Certificate::OSCertHandles intermediates;
312
313 // Skip the first certificate in the path as that is the target certificate
314 for (size_t i = 1; i < path.path.certs.size(); ++i)
315 intermediates.push_back(CreateOSCertHandle(path.path.certs[i]));
316
317 if (path.path.trust_anchor) {
318 // TODO(eroman): This assumes that TrustAnchor::cert() cannot be null,
319 // which disagrees with the documentation.
320 intermediates.push_back(CreateOSCertHandle(path.path.trust_anchor->cert()));
321 }
322
323 scoped_refptr<X509Certificate> result = X509Certificate::CreateFromHandle(
324 target_cert->os_cert_handle(), intermediates);
325
326 for (const X509Certificate::OSCertHandle handle : intermediates)
327 X509Certificate::FreeOSCertHandle(handle);
328
329 return result;
330 }
331
332 // TODO(crbug.com/649017): Make use of |flags|, |crl_set|, and |ocsp_response|.
333 // Also handle key usages, policies and EV.
334 //
335 // Any failure short-circuits from the function must set
336 // |verify_result->cert_status|.
337 void DoVerify(X509Certificate* input_cert,
338 const std::string& hostname,
339 const std::string& ocsp_response,
340 int flags,
341 CRLSet* crl_set,
342 const CertificateList& additional_trust_anchors,
343 CertVerifyResult* verify_result) {
344 CertErrors errors;
345
346 // Parse the target certificate.
347 scoped_refptr<ParsedCertificate> target =
348 ParseCertificateFromOSHandle(input_cert->os_cert_handle(), &errors);
349 if (!target) {
350 // TODO(crbug.com/634443): Surface these parsing errors?
351 verify_result->cert_status |= CERT_STATUS_INVALID;
352 return;
353 }
354
355 std::unique_ptr<SystemTrustStore> trust_store =
356 CreateSystemTrustStore(additional_trust_anchors);
357
358 // TODO(eroman): The path building code in this file enforces its idea of weak
359 // keys, and separately cert_verify_proc.cc also checks the chains with its
360 // own policy. These policies should be aligned, to give path building the
361 // best chance of finding a good path.
362 // Another difference to resolve is the path building here does not check the
363 // target certificate's key strength, whereas cert_verify_proc.cc does.
364 SimpleSignaturePolicy signature_policy(1024);
365
366 // Use the current time.
367 der::GeneralizedTime verification_time;
368 if (!der::EncodeTimeAsGeneralizedTime(base::Time::Now(),
369 &verification_time)) {
370 // This really shouldn't be possible unless Time::Now() returned
371 // something crazy.
372 verify_result->cert_status |= CERT_STATUS_DATE_INVALID;
373 return;
374 }
375
376 // Initialize the path builder.
377 CertPathBuilder::Result result;
378 CertPathBuilder path_builder(target, trust_store->GetTrustStore(),
379 &signature_policy, verification_time, &result);
380
381 // Allow the path builder to discover intermediates from the trust store.
382 if (trust_store->GetCertIssuerSource())
383 path_builder.AddCertIssuerSource(trust_store->GetCertIssuerSource());
384
385 // Allow the path builder to discover the explicitly provided intermediates in
386 // |input_cert|.
387 CertIssuerSourceStatic intermediates;
388 AddIntermediatesToIssuerSource(input_cert, &intermediates);
389 path_builder.AddCertIssuerSource(&intermediates);
390
391 // TODO(crbug.com/649017): Allow the path builder to discover intermediates
392 // through AIA fetching.
393
394 path_builder.Run();
395
396 if (result.best_result_index >= result.paths.size()) {
397 // TODO(eroman): Is this case reachable?
398 verify_result->cert_status |= CERT_STATUS_AUTHORITY_INVALID;
399 return;
400 }
401
402 // Use the best path that was built. This could be a partial path, or it could
403 // be a valid complete path.
404 const CertPathBuilder::ResultPath& partial_path =
405 *result.paths[result.best_result_index].get();
406
407 if (partial_path.path.trust_anchor) {
408 verify_result->is_issued_by_known_root =
409 trust_store->IsKnownRoot(partial_path.path.trust_anchor);
410
411 verify_result->is_issued_by_additional_trust_anchor =
412 trust_store->IsAdditionalTrustAnchor(partial_path.path.trust_anchor);
413 } else {
414 verify_result->cert_status |= CERT_STATUS_AUTHORITY_INVALID;
415 }
416
417 verify_result->verified_cert =
418 CreateVerifiedCertChain(input_cert, partial_path);
419
420 AppendPublicKeyHashes(partial_path, &verify_result->public_key_hashes);
421 MapPathBuilderErrorsToCertStatus(partial_path, &verify_result->cert_status);
422 }
423
424 int CertVerifyProcBuiltin::VerifyInternal(
425 X509Certificate* input_cert,
426 const std::string& hostname,
427 const std::string& ocsp_response,
428 int flags,
429 CRLSet* crl_set,
430 const CertificateList& additional_trust_anchors,
431 CertVerifyResult* verify_result) {
432 DoVerify(input_cert, hostname, ocsp_response, flags, crl_set,
433 additional_trust_anchors, verify_result);
434
435 return IsCertStatusError(verify_result->cert_status)
436 ? MapCertStatusToNetError(verify_result->cert_status)
437 : OK;
438 }
439
440 } // namespace
441
442 scoped_refptr<CertVerifyProc> CreateCertVerifyProcBuiltin() {
443 return scoped_refptr<CertVerifyProc>(new CertVerifyProcBuiltin());
444 }
445
446 } // namespace net
OLDNEW
« no previous file with comments | « net/cert/cert_verify_proc_builtin.h ('k') | net/cert/cert_verify_proc_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698