cert_verify_proc_nss.cc revision a36e5920737c6adbddd3e43b760e5de8431db6e0
1// Copyright (c) 2012 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_nss.h"
6
7#include <string>
8#include <vector>
9
10#include <cert.h>
11#include <nss.h>
12#include <prerror.h>
13#include <secerr.h>
14#include <sechash.h>
15#include <sslerr.h>
16
17#include "base/logging.h"
18#include "crypto/nss_util.h"
19#include "crypto/scoped_nss_types.h"
20#include "crypto/sha2.h"
21#include "net/base/net_errors.h"
22#include "net/cert/asn1_util.h"
23#include "net/cert/cert_status_flags.h"
24#include "net/cert/cert_verifier.h"
25#include "net/cert/cert_verify_result.h"
26#include "net/cert/crl_set.h"
27#include "net/cert/ev_root_ca_metadata.h"
28#include "net/cert/x509_certificate.h"
29#include "net/cert/x509_util_nss.h"
30
31#if defined(OS_IOS)
32#include <CommonCrypto/CommonDigest.h>
33#include "net/cert/x509_util_ios.h"
34#endif  // defined(OS_IOS)
35
36#define NSS_VERSION_NUM (NSS_VMAJOR * 10000 + NSS_VMINOR * 100 + NSS_VPATCH)
37#if NSS_VERSION_NUM < 31305
38// Added in NSS 3.13.5.
39#define SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED -8016
40#endif
41
42#if NSS_VERSION_NUM < 31402
43// Added in NSS 3.14.2.
44#define cert_pi_useOnlyTrustAnchors static_cast<CERTValParamInType>(14)
45#endif
46
47namespace net {
48
49namespace {
50
51typedef scoped_ptr_malloc<
52    CERTCertificatePolicies,
53    crypto::NSSDestroyer<CERTCertificatePolicies,
54                         CERT_DestroyCertificatePoliciesExtension> >
55    ScopedCERTCertificatePolicies;
56
57typedef scoped_ptr_malloc<
58    CERTCertList,
59    crypto::NSSDestroyer<CERTCertList, CERT_DestroyCertList> >
60    ScopedCERTCertList;
61
62// ScopedCERTValOutParam manages destruction of values in the CERTValOutParam
63// array that cvout points to.  cvout must be initialized as passed to
64// CERT_PKIXVerifyCert, so that the array must be terminated with
65// cert_po_end type.
66// When it goes out of scope, it destroys values of cert_po_trustAnchor
67// and cert_po_certList types, but doesn't release the array itself.
68class ScopedCERTValOutParam {
69 public:
70  explicit ScopedCERTValOutParam(CERTValOutParam* cvout) : cvout_(cvout) {}
71
72  ~ScopedCERTValOutParam() {
73    Clear();
74  }
75
76  // Free the internal resources, but do not release the array itself.
77  void Clear() {
78    if (cvout_ == NULL)
79      return;
80    for (CERTValOutParam *p = cvout_; p->type != cert_po_end; p++) {
81      switch (p->type) {
82        case cert_po_trustAnchor:
83          if (p->value.pointer.cert) {
84            CERT_DestroyCertificate(p->value.pointer.cert);
85            p->value.pointer.cert = NULL;
86          }
87          break;
88        case cert_po_certList:
89          if (p->value.pointer.chain) {
90            CERT_DestroyCertList(p->value.pointer.chain);
91            p->value.pointer.chain = NULL;
92          }
93          break;
94        default:
95          break;
96      }
97    }
98  }
99
100 private:
101  CERTValOutParam* cvout_;
102
103  DISALLOW_COPY_AND_ASSIGN(ScopedCERTValOutParam);
104};
105
106// Map PORT_GetError() return values to our network error codes.
107int MapSecurityError(int err) {
108  switch (err) {
109    case PR_DIRECTORY_LOOKUP_ERROR:  // DNS lookup error.
110      return ERR_NAME_NOT_RESOLVED;
111    case SEC_ERROR_INVALID_ARGS:
112      return ERR_INVALID_ARGUMENT;
113    case SSL_ERROR_BAD_CERT_DOMAIN:
114      return ERR_CERT_COMMON_NAME_INVALID;
115    case SEC_ERROR_INVALID_TIME:
116    case SEC_ERROR_EXPIRED_CERTIFICATE:
117    case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE:
118      return ERR_CERT_DATE_INVALID;
119    case SEC_ERROR_UNKNOWN_ISSUER:
120    case SEC_ERROR_UNTRUSTED_ISSUER:
121    case SEC_ERROR_CA_CERT_INVALID:
122      return ERR_CERT_AUTHORITY_INVALID;
123    // TODO(port): map ERR_CERT_NO_REVOCATION_MECHANISM.
124    case SEC_ERROR_OCSP_BAD_HTTP_RESPONSE:
125    case SEC_ERROR_OCSP_SERVER_ERROR:
126      return ERR_CERT_UNABLE_TO_CHECK_REVOCATION;
127    case SEC_ERROR_REVOKED_CERTIFICATE:
128    case SEC_ERROR_UNTRUSTED_CERT:  // Treat as revoked.
129      return ERR_CERT_REVOKED;
130    case SEC_ERROR_BAD_DER:
131    case SEC_ERROR_BAD_SIGNATURE:
132    case SEC_ERROR_CERT_NOT_VALID:
133    // TODO(port): add an ERR_CERT_WRONG_USAGE error code.
134    case SEC_ERROR_CERT_USAGES_INVALID:
135    case SEC_ERROR_INADEQUATE_KEY_USAGE:  // Key usage.
136    case SEC_ERROR_INADEQUATE_CERT_TYPE:  // Extended key usage and whether
137                                          // the certificate is a CA.
138    case SEC_ERROR_POLICY_VALIDATION_FAILED:
139    case SEC_ERROR_CERT_NOT_IN_NAME_SPACE:
140    case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID:
141    case SEC_ERROR_UNKNOWN_CRITICAL_EXTENSION:
142    case SEC_ERROR_EXTENSION_VALUE_INVALID:
143      return ERR_CERT_INVALID;
144    case SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED:
145      return ERR_CERT_WEAK_SIGNATURE_ALGORITHM;
146    default:
147      LOG(WARNING) << "Unknown error " << err << " mapped to net::ERR_FAILED";
148      return ERR_FAILED;
149  }
150}
151
152// Map PORT_GetError() return values to our cert status flags.
153CertStatus MapCertErrorToCertStatus(int err) {
154  int net_error = MapSecurityError(err);
155  return MapNetErrorToCertStatus(net_error);
156}
157
158// Saves some information about the certificate chain cert_list in
159// *verify_result.  The caller MUST initialize *verify_result before calling
160// this function.
161// Note that cert_list[0] is the end entity certificate.
162void GetCertChainInfo(CERTCertList* cert_list,
163                      CERTCertificate* root_cert,
164                      CertVerifyResult* verify_result) {
165  // NOTE: Using a NSS library before 3.12.3.1 will crash below.  To see the
166  // NSS version currently in use:
167  // 1. use ldd on the chrome executable for NSS's location (ie. libnss3.so*)
168  // 2. use ident libnss3.so* for the library's version
169  DCHECK(cert_list);
170
171  CERTCertificate* verified_cert = NULL;
172  std::vector<CERTCertificate*> verified_chain;
173  int i = 0;
174  for (CERTCertListNode* node = CERT_LIST_HEAD(cert_list);
175       !CERT_LIST_END(node, cert_list);
176       node = CERT_LIST_NEXT(node), ++i) {
177    if (i == 0) {
178      verified_cert = node->cert;
179    } else {
180      // Because of an NSS bug, CERT_PKIXVerifyCert may chain a self-signed
181      // certificate of a root CA to another certificate of the same root CA
182      // key.  Detect that error and ignore the root CA certificate.
183      // See https://bugzilla.mozilla.org/show_bug.cgi?id=721288.
184      if (node->cert->isRoot) {
185        // NOTE: isRoot doesn't mean the certificate is a trust anchor.  It
186        // means the certificate is self-signed.  Here we assume isRoot only
187        // implies the certificate is self-issued.
188        CERTCertListNode* next_node = CERT_LIST_NEXT(node);
189        CERTCertificate* next_cert;
190        if (!CERT_LIST_END(next_node, cert_list)) {
191          next_cert = next_node->cert;
192        } else {
193          next_cert = root_cert;
194        }
195        // Test that |node->cert| is actually a self-signed certificate
196        // whose key is equal to |next_cert|, and not a self-issued
197        // certificate signed by another key of the same CA.
198        if (next_cert && SECITEM_ItemsAreEqual(&node->cert->derPublicKey,
199                                               &next_cert->derPublicKey)) {
200          continue;
201        }
202      }
203      verified_chain.push_back(node->cert);
204    }
205
206    SECAlgorithmID& signature = node->cert->signature;
207    SECOidTag oid_tag = SECOID_FindOIDTag(&signature.algorithm);
208    switch (oid_tag) {
209      case SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION:
210        verify_result->has_md5 = true;
211        break;
212      case SEC_OID_PKCS1_MD2_WITH_RSA_ENCRYPTION:
213        verify_result->has_md2 = true;
214        break;
215      case SEC_OID_PKCS1_MD4_WITH_RSA_ENCRYPTION:
216        verify_result->has_md4 = true;
217        break;
218      default:
219        break;
220    }
221  }
222
223  if (root_cert)
224    verified_chain.push_back(root_cert);
225#if defined(OS_IOS)
226  verify_result->verified_cert =
227      x509_util_ios::CreateCertFromNSSHandles(verified_cert, verified_chain);
228#else
229  verify_result->verified_cert =
230      X509Certificate::CreateFromHandle(verified_cert, verified_chain);
231#endif  // defined(OS_IOS)
232}
233
234// IsKnownRoot returns true if the given certificate is one that we believe
235// is a standard (as opposed to user-installed) root.
236bool IsKnownRoot(CERTCertificate* root) {
237  if (!root || !root->slot)
238    return false;
239
240  // This magic name is taken from
241  // http://bonsai.mozilla.org/cvsblame.cgi?file=mozilla/security/nss/lib/ckfw/builtins/constants.c&rev=1.13&mark=86,89#79
242  return 0 == strcmp(PK11_GetSlotName(root->slot),
243                     "NSS Builtin Objects");
244}
245
246// Returns true if the given certificate is one of the additional trust anchors.
247bool IsAdditionalTrustAnchor(CERTCertList* additional_trust_anchors,
248                             CERTCertificate* root) {
249  if (!additional_trust_anchors || !root)
250    return false;
251  for (CERTCertListNode* node = CERT_LIST_HEAD(additional_trust_anchors);
252       !CERT_LIST_END(node, additional_trust_anchors);
253       node = CERT_LIST_NEXT(node)) {
254    if (CERT_CompareCerts(node->cert, root))
255      return true;
256  }
257  return false;
258}
259
260enum CRLSetResult {
261  kCRLSetOk,
262  kCRLSetRevoked,
263  kCRLSetUnknown,
264};
265
266// CheckRevocationWithCRLSet attempts to check each element of |cert_list|
267// against |crl_set|. It returns:
268//   kCRLSetRevoked: if any element of the chain is known to have been revoked.
269//   kCRLSetUnknown: if there is no fresh information about some element in
270//       the chain.
271//   kCRLSetOk: if every element in the chain is covered by a fresh CRLSet and
272//       is unrevoked.
273CRLSetResult CheckRevocationWithCRLSet(CERTCertList* cert_list,
274                                       CERTCertificate* root,
275                                       CRLSet* crl_set) {
276  std::vector<CERTCertificate*> certs;
277
278  if (cert_list) {
279    for (CERTCertListNode* node = CERT_LIST_HEAD(cert_list);
280         !CERT_LIST_END(node, cert_list);
281         node = CERT_LIST_NEXT(node)) {
282      certs.push_back(node->cert);
283    }
284  }
285  if (root)
286    certs.push_back(root);
287
288  bool covered = true;
289
290  // We iterate from the root certificate down to the leaf, keeping track of
291  // the issuer's SPKI at each step.
292  std::string issuer_spki_hash;
293  for (std::vector<CERTCertificate*>::reverse_iterator i = certs.rbegin();
294       i != certs.rend(); ++i) {
295    CERTCertificate* cert = *i;
296
297    base::StringPiece der(reinterpret_cast<char*>(cert->derCert.data),
298                          cert->derCert.len);
299
300    base::StringPiece spki;
301    if (!asn1::ExtractSPKIFromDERCert(der, &spki)) {
302      NOTREACHED();
303      covered = false;
304      continue;
305    }
306    const std::string spki_hash = crypto::SHA256HashString(spki);
307
308    base::StringPiece serial_number = base::StringPiece(
309        reinterpret_cast<char*>(cert->serialNumber.data),
310        cert->serialNumber.len);
311
312    CRLSet::Result result = crl_set->CheckSPKI(spki_hash);
313
314    if (result != CRLSet::REVOKED && !issuer_spki_hash.empty())
315      result = crl_set->CheckSerial(serial_number, issuer_spki_hash);
316
317    issuer_spki_hash = spki_hash;
318
319    switch (result) {
320      case CRLSet::REVOKED:
321        return kCRLSetRevoked;
322      case CRLSet::UNKNOWN:
323        covered = false;
324        continue;
325      case CRLSet::GOOD:
326        continue;
327      default:
328        NOTREACHED();
329        covered = false;
330        continue;
331    }
332  }
333
334  if (!covered || crl_set->IsExpired())
335    return kCRLSetUnknown;
336  return kCRLSetOk;
337}
338
339// Forward declarations.
340SECStatus RetryPKIXVerifyCertWithWorkarounds(
341    CERTCertificate* cert_handle, int num_policy_oids,
342    bool cert_io_enabled, std::vector<CERTValInParam>* cvin,
343    CERTValOutParam* cvout);
344SECOidTag GetFirstCertPolicy(CERTCertificate* cert_handle);
345
346// Call CERT_PKIXVerifyCert for the cert_handle.
347// Verification results are stored in an array of CERTValOutParam.
348// If |hard_fail| is true, and no policy_oids are supplied (eg: EV is NOT being
349// checked), then the failure to obtain valid CRL/OCSP information for all
350// certificates that contain CRL/OCSP URLs will cause the certificate to be
351// treated as if it was revoked. Since failures may be caused by transient
352// network failures or by malicious attackers, in general, hard_fail should be
353// false.
354// If policy_oids is not NULL and num_policy_oids is positive, policies
355// are also checked.
356// additional_trust_anchors is an optional list of certificates that can be
357// trusted as anchors when building a certificate chain.
358// Caller must initialize cvout before calling this function.
359SECStatus PKIXVerifyCert(CERTCertificate* cert_handle,
360                         bool check_revocation,
361                         bool hard_fail,
362                         bool cert_io_enabled,
363                         const SECOidTag* policy_oids,
364                         int num_policy_oids,
365                         CERTCertList* additional_trust_anchors,
366                         CERTValOutParam* cvout) {
367  bool use_crl = check_revocation;
368  bool use_ocsp = check_revocation;
369
370  // These CAs have multiple keys, which trigger two bugs in NSS's CRL code.
371  // 1. NSS may use one key to verify a CRL signed with another key,
372  //    incorrectly concluding that the CRL's signature is invalid.
373  //    Hopefully this bug will be fixed in NSS 3.12.9.
374  // 2. NSS considers all certificates issued by the CA as revoked when it
375  //    receives a CRL with an invalid signature.  This overly strict policy
376  //    has been relaxed in NSS 3.12.7.  See
377  //    https://bugzilla.mozilla.org/show_bug.cgi?id=562542.
378  // So we have to turn off CRL checking for these CAs.  See
379  // http://crbug.com/55695.
380  static const char* const kMultipleKeyCA[] = {
381    "CN=Microsoft Secure Server Authority,"
382    "DC=redmond,DC=corp,DC=microsoft,DC=com",
383    "CN=Microsoft Secure Server Authority",
384  };
385
386  if (!NSS_VersionCheck("3.12.7")) {
387    for (size_t i = 0; i < arraysize(kMultipleKeyCA); ++i) {
388      if (strcmp(cert_handle->issuerName, kMultipleKeyCA[i]) == 0) {
389        use_crl = false;
390        break;
391      }
392    }
393  }
394
395  PRUint64 revocation_method_flags =
396      CERT_REV_M_DO_NOT_TEST_USING_THIS_METHOD |
397      CERT_REV_M_ALLOW_NETWORK_FETCHING |
398      CERT_REV_M_IGNORE_IMPLICIT_DEFAULT_SOURCE |
399      CERT_REV_M_IGNORE_MISSING_FRESH_INFO |
400      CERT_REV_M_STOP_TESTING_ON_FRESH_INFO;
401  PRUint64 revocation_method_independent_flags =
402      CERT_REV_MI_TEST_ALL_LOCAL_INFORMATION_FIRST;
403  if (check_revocation && policy_oids && num_policy_oids > 0) {
404    // EV verification requires revocation checking.  Consider the certificate
405    // revoked if we don't have revocation info.
406    // TODO(wtc): Add a bool parameter to expressly specify we're doing EV
407    // verification or we want strict revocation flags.
408    revocation_method_flags |= CERT_REV_M_REQUIRE_INFO_ON_MISSING_SOURCE;
409    revocation_method_independent_flags |=
410        CERT_REV_MI_REQUIRE_SOME_FRESH_INFO_AVAILABLE;
411  } else if (check_revocation && hard_fail) {
412    revocation_method_flags |= CERT_REV_M_FAIL_ON_MISSING_FRESH_INFO;
413    revocation_method_independent_flags |=
414        CERT_REV_MI_REQUIRE_SOME_FRESH_INFO_AVAILABLE;
415  } else {
416    revocation_method_flags |= CERT_REV_M_SKIP_TEST_ON_MISSING_SOURCE;
417    revocation_method_independent_flags |=
418        CERT_REV_MI_NO_OVERALL_INFO_REQUIREMENT;
419  }
420  PRUint64 method_flags[2];
421  method_flags[cert_revocation_method_crl] = revocation_method_flags;
422  method_flags[cert_revocation_method_ocsp] = revocation_method_flags;
423
424  if (use_crl) {
425    method_flags[cert_revocation_method_crl] |=
426        CERT_REV_M_TEST_USING_THIS_METHOD;
427  }
428  if (use_ocsp) {
429    method_flags[cert_revocation_method_ocsp] |=
430        CERT_REV_M_TEST_USING_THIS_METHOD;
431  }
432
433  CERTRevocationMethodIndex preferred_revocation_methods[1];
434  if (use_ocsp) {
435    preferred_revocation_methods[0] = cert_revocation_method_ocsp;
436  } else {
437    preferred_revocation_methods[0] = cert_revocation_method_crl;
438  }
439
440  CERTRevocationFlags revocation_flags;
441  revocation_flags.leafTests.number_of_defined_methods =
442      arraysize(method_flags);
443  revocation_flags.leafTests.cert_rev_flags_per_method = method_flags;
444  revocation_flags.leafTests.number_of_preferred_methods =
445      arraysize(preferred_revocation_methods);
446  revocation_flags.leafTests.preferred_methods = preferred_revocation_methods;
447  revocation_flags.leafTests.cert_rev_method_independent_flags =
448      revocation_method_independent_flags;
449
450  revocation_flags.chainTests.number_of_defined_methods =
451      arraysize(method_flags);
452  revocation_flags.chainTests.cert_rev_flags_per_method = method_flags;
453  revocation_flags.chainTests.number_of_preferred_methods =
454      arraysize(preferred_revocation_methods);
455  revocation_flags.chainTests.preferred_methods = preferred_revocation_methods;
456  revocation_flags.chainTests.cert_rev_method_independent_flags =
457      revocation_method_independent_flags;
458
459
460  std::vector<CERTValInParam> cvin;
461  cvin.reserve(7);
462  CERTValInParam in_param;
463  in_param.type = cert_pi_revocationFlags;
464  in_param.value.pointer.revocation = &revocation_flags;
465  cvin.push_back(in_param);
466  if (policy_oids && num_policy_oids > 0) {
467    in_param.type = cert_pi_policyOID;
468    in_param.value.arraySize = num_policy_oids;
469    in_param.value.array.oids = policy_oids;
470    cvin.push_back(in_param);
471  }
472  if (additional_trust_anchors) {
473    in_param.type = cert_pi_trustAnchors;
474    in_param.value.pointer.chain = additional_trust_anchors;
475    cvin.push_back(in_param);
476    in_param.type = cert_pi_useOnlyTrustAnchors;
477    in_param.value.scalar.b = PR_FALSE;
478    cvin.push_back(in_param);
479  }
480  in_param.type = cert_pi_end;
481  cvin.push_back(in_param);
482
483  SECStatus rv = CERT_PKIXVerifyCert(cert_handle, certificateUsageSSLServer,
484                                     &cvin[0], cvout, NULL);
485  if (rv != SECSuccess) {
486    rv = RetryPKIXVerifyCertWithWorkarounds(cert_handle, num_policy_oids,
487                                            cert_io_enabled, &cvin, cvout);
488  }
489  return rv;
490}
491
492// PKIXVerifyCert calls this function to work around some bugs in
493// CERT_PKIXVerifyCert.  All the arguments of this function are either the
494// arguments or local variables of PKIXVerifyCert.
495SECStatus RetryPKIXVerifyCertWithWorkarounds(
496    CERTCertificate* cert_handle, int num_policy_oids,
497    bool cert_io_enabled, std::vector<CERTValInParam>* cvin,
498    CERTValOutParam* cvout) {
499  // We call this function when the first CERT_PKIXVerifyCert call in
500  // PKIXVerifyCert failed,  so we initialize |rv| to SECFailure.
501  SECStatus rv = SECFailure;
502  int nss_error = PORT_GetError();
503  CERTValInParam in_param;
504
505  // If we get SEC_ERROR_UNKNOWN_ISSUER, we may be missing an intermediate
506  // CA certificate, so we retry with cert_pi_useAIACertFetch.
507  // cert_pi_useAIACertFetch has several bugs in its error handling and
508  // error reporting (NSS bug 528743), so we don't use it by default.
509  // Note: When building a certificate chain, CERT_PKIXVerifyCert may
510  // incorrectly pick a CA certificate with the same subject name as the
511  // missing intermediate CA certificate, and  fail with the
512  // SEC_ERROR_BAD_SIGNATURE error (NSS bug 524013), so we also retry with
513  // cert_pi_useAIACertFetch on SEC_ERROR_BAD_SIGNATURE.
514  if (cert_io_enabled &&
515      (nss_error == SEC_ERROR_UNKNOWN_ISSUER ||
516       nss_error == SEC_ERROR_BAD_SIGNATURE)) {
517    DCHECK_EQ(cvin->back().type,  cert_pi_end);
518    cvin->pop_back();
519    in_param.type = cert_pi_useAIACertFetch;
520    in_param.value.scalar.b = PR_TRUE;
521    cvin->push_back(in_param);
522    in_param.type = cert_pi_end;
523    cvin->push_back(in_param);
524    rv = CERT_PKIXVerifyCert(cert_handle, certificateUsageSSLServer,
525                             &(*cvin)[0], cvout, NULL);
526    if (rv == SECSuccess)
527      return rv;
528    int new_nss_error = PORT_GetError();
529    if (new_nss_error == SEC_ERROR_INVALID_ARGS ||
530        new_nss_error == SEC_ERROR_UNKNOWN_AIA_LOCATION_TYPE ||
531        new_nss_error == SEC_ERROR_BAD_INFO_ACCESS_LOCATION ||
532        new_nss_error == SEC_ERROR_BAD_HTTP_RESPONSE ||
533        new_nss_error == SEC_ERROR_BAD_LDAP_RESPONSE ||
534        !IS_SEC_ERROR(new_nss_error)) {
535      // Use the original error code because of cert_pi_useAIACertFetch's
536      // bad error reporting.
537      PORT_SetError(nss_error);
538      return rv;
539    }
540    nss_error = new_nss_error;
541  }
542
543  // If an intermediate CA certificate has requireExplicitPolicy in its
544  // policyConstraints extension, CERT_PKIXVerifyCert fails with
545  // SEC_ERROR_POLICY_VALIDATION_FAILED because we didn't specify any
546  // certificate policy (NSS bug 552775).  So we retry with the certificate
547  // policy found in the server certificate.
548  if (nss_error == SEC_ERROR_POLICY_VALIDATION_FAILED &&
549      num_policy_oids == 0) {
550    SECOidTag policy = GetFirstCertPolicy(cert_handle);
551    if (policy != SEC_OID_UNKNOWN) {
552      DCHECK_EQ(cvin->back().type,  cert_pi_end);
553      cvin->pop_back();
554      in_param.type = cert_pi_policyOID;
555      in_param.value.arraySize = 1;
556      in_param.value.array.oids = &policy;
557      cvin->push_back(in_param);
558      in_param.type = cert_pi_end;
559      cvin->push_back(in_param);
560      rv = CERT_PKIXVerifyCert(cert_handle, certificateUsageSSLServer,
561                               &(*cvin)[0], cvout, NULL);
562      if (rv != SECSuccess) {
563        // Use the original error code.
564        PORT_SetError(nss_error);
565      }
566    }
567  }
568
569  return rv;
570}
571
572// Decodes the certificatePolicies extension of the certificate.  Returns
573// NULL if the certificate doesn't have the extension or the extension can't
574// be decoded.  The returned value must be freed with a
575// CERT_DestroyCertificatePoliciesExtension call.
576CERTCertificatePolicies* DecodeCertPolicies(
577    CERTCertificate* cert_handle) {
578  SECItem policy_ext;
579  SECStatus rv = CERT_FindCertExtension(cert_handle,
580                                        SEC_OID_X509_CERTIFICATE_POLICIES,
581                                        &policy_ext);
582  if (rv != SECSuccess)
583    return NULL;
584  CERTCertificatePolicies* policies =
585      CERT_DecodeCertificatePoliciesExtension(&policy_ext);
586  SECITEM_FreeItem(&policy_ext, PR_FALSE);
587  return policies;
588}
589
590// Returns the OID tag for the first certificate policy in the certificate's
591// certificatePolicies extension.  Returns SEC_OID_UNKNOWN if the certificate
592// has no certificate policy.
593SECOidTag GetFirstCertPolicy(CERTCertificate* cert_handle) {
594  ScopedCERTCertificatePolicies policies(DecodeCertPolicies(cert_handle));
595  if (!policies.get())
596    return SEC_OID_UNKNOWN;
597
598  CERTPolicyInfo* policy_info = policies->policyInfos[0];
599  if (!policy_info)
600    return SEC_OID_UNKNOWN;
601  if (policy_info->oid != SEC_OID_UNKNOWN)
602    return policy_info->oid;
603
604  // The certificate policy is unknown to NSS.  We need to create a dynamic
605  // OID tag for the policy.
606  SECOidData od;
607  od.oid.len = policy_info->policyID.len;
608  od.oid.data = policy_info->policyID.data;
609  od.offset = SEC_OID_UNKNOWN;
610  // NSS doesn't allow us to pass an empty description, so I use a hardcoded,
611  // default description here.  The description doesn't need to be unique for
612  // each OID.
613  od.desc = "a certificate policy";
614  od.mechanism = CKM_INVALID_MECHANISM;
615  od.supportedExtension = INVALID_CERT_EXTENSION;
616  return SECOID_AddEntry(&od);
617}
618
619HashValue CertPublicKeyHashSHA1(CERTCertificate* cert) {
620  HashValue hash(HASH_VALUE_SHA1);
621#if defined(OS_IOS)
622  CC_SHA1(cert->derPublicKey.data, cert->derPublicKey.len, hash.data());
623#else
624  SECStatus rv = HASH_HashBuf(HASH_AlgSHA1, hash.data(),
625                              cert->derPublicKey.data, cert->derPublicKey.len);
626  DCHECK_EQ(SECSuccess, rv);
627#endif
628  return hash;
629}
630
631HashValue CertPublicKeyHashSHA256(CERTCertificate* cert) {
632  HashValue hash(HASH_VALUE_SHA256);
633#if defined(OS_IOS)
634  CC_SHA256(cert->derPublicKey.data, cert->derPublicKey.len, hash.data());
635#else
636  SECStatus rv = HASH_HashBuf(HASH_AlgSHA256, hash.data(),
637                              cert->derPublicKey.data, cert->derPublicKey.len);
638  DCHECK_EQ(rv, SECSuccess);
639#endif
640  return hash;
641}
642
643void AppendPublicKeyHashes(CERTCertList* cert_list,
644                           CERTCertificate* root_cert,
645                           HashValueVector* hashes) {
646  for (CERTCertListNode* node = CERT_LIST_HEAD(cert_list);
647       !CERT_LIST_END(node, cert_list);
648       node = CERT_LIST_NEXT(node)) {
649    hashes->push_back(CertPublicKeyHashSHA1(node->cert));
650    hashes->push_back(CertPublicKeyHashSHA256(node->cert));
651  }
652  if (root_cert) {
653    hashes->push_back(CertPublicKeyHashSHA1(root_cert));
654    hashes->push_back(CertPublicKeyHashSHA256(root_cert));
655  }
656}
657
658// Returns true if |cert_handle| contains a policy OID that is an EV policy
659// OID according to |metadata|, storing the resulting policy OID in
660// |*ev_policy_oid|. A true return is not sufficient to establish that a
661// certificate is EV, but a false return is sufficient to establish the
662// certificate cannot be EV.
663bool IsEVCandidate(EVRootCAMetadata* metadata,
664                   CERTCertificate* cert_handle,
665                   SECOidTag* ev_policy_oid) {
666  DCHECK(cert_handle);
667  ScopedCERTCertificatePolicies policies(DecodeCertPolicies(cert_handle));
668  if (!policies.get())
669    return false;
670
671  CERTPolicyInfo** policy_infos = policies->policyInfos;
672  while (*policy_infos != NULL) {
673    CERTPolicyInfo* policy_info = *policy_infos++;
674    // If the Policy OID is unknown, that implicitly means it has not been
675    // registered as an EV policy.
676    if (policy_info->oid == SEC_OID_UNKNOWN)
677      continue;
678    if (metadata->IsEVPolicyOID(policy_info->oid)) {
679      *ev_policy_oid = policy_info->oid;
680      return true;
681    }
682  }
683
684  return false;
685}
686
687// Studied Mozilla's code (esp. security/manager/ssl/src/nsIdentityChecking.cpp
688// and nsNSSCertHelper.cpp) to learn how to verify EV certificate.
689// TODO(wtc): A possible optimization is that we get the trust anchor from
690// the first PKIXVerifyCert call.  We look up the EV policy for the trust
691// anchor.  If the trust anchor has no EV policy, we know the cert isn't EV.
692// Otherwise, we pass just that EV policy (as opposed to all the EV policies)
693// to the second PKIXVerifyCert call.
694bool VerifyEV(CERTCertificate* cert_handle,
695              int flags,
696              CRLSet* crl_set,
697              bool rev_checking_enabled,
698              EVRootCAMetadata* metadata,
699              SECOidTag ev_policy_oid,
700              CERTCertList* additional_trust_anchors) {
701  CERTValOutParam cvout[3];
702  int cvout_index = 0;
703  cvout[cvout_index].type = cert_po_certList;
704  cvout[cvout_index].value.pointer.chain = NULL;
705  int cvout_cert_list_index = cvout_index;
706  cvout_index++;
707  cvout[cvout_index].type = cert_po_trustAnchor;
708  cvout[cvout_index].value.pointer.cert = NULL;
709  int cvout_trust_anchor_index = cvout_index;
710  cvout_index++;
711  cvout[cvout_index].type = cert_po_end;
712  ScopedCERTValOutParam scoped_cvout(cvout);
713
714  SECStatus status = PKIXVerifyCert(
715      cert_handle,
716      rev_checking_enabled,
717      true, /* hard fail is implied in EV. */
718      flags & CertVerifier::VERIFY_CERT_IO_ENABLED,
719      &ev_policy_oid,
720      1,
721      additional_trust_anchors,
722      cvout);
723  if (status != SECSuccess)
724    return false;
725
726  CERTCertificate* root_ca =
727      cvout[cvout_trust_anchor_index].value.pointer.cert;
728  if (root_ca == NULL)
729    return false;
730
731  // This second PKIXVerifyCert call could have found a different certification
732  // path and one or more of the certificates on this new path, that weren't on
733  // the old path, might have been revoked.
734  if (crl_set) {
735    CRLSetResult crl_set_result = CheckRevocationWithCRLSet(
736        cvout[cvout_cert_list_index].value.pointer.chain,
737        cvout[cvout_trust_anchor_index].value.pointer.cert,
738        crl_set);
739    if (crl_set_result == kCRLSetRevoked)
740      return false;
741  }
742
743#if defined(OS_IOS)
744  SHA1HashValue fingerprint = x509_util_ios::CalculateFingerprintNSS(root_ca);
745#else
746  SHA1HashValue fingerprint =
747      X509Certificate::CalculateFingerprint(root_ca);
748#endif
749  return metadata->HasEVPolicyOID(fingerprint, ev_policy_oid);
750}
751
752CERTCertList* CertificateListToCERTCertList(const CertificateList& list) {
753  CERTCertList* result = CERT_NewCertList();
754  for (size_t i = 0; i < list.size(); ++i) {
755#if defined(OS_IOS)
756    // X509Certificate::os_cert_handle() on iOS is a SecCertificateRef; convert
757    // it to an NSS CERTCertificate.
758    CERTCertificate* cert = x509_util_ios::CreateNSSCertHandleFromOSHandle(
759        list[i]->os_cert_handle());
760#else
761    CERTCertificate* cert = list[i]->os_cert_handle();
762#endif
763    CERT_AddCertToListTail(result, CERT_DupCertificate(cert));
764  }
765  return result;
766}
767
768}  // namespace
769
770CertVerifyProcNSS::CertVerifyProcNSS() {}
771
772CertVerifyProcNSS::~CertVerifyProcNSS() {}
773
774bool CertVerifyProcNSS::SupportsAdditionalTrustAnchors() const {
775  // This requires APIs introduced in 3.14.2.
776  return NSS_VersionCheck("3.14.2");
777}
778
779int CertVerifyProcNSS::VerifyInternal(
780    X509Certificate* cert,
781    const std::string& hostname,
782    int flags,
783    CRLSet* crl_set,
784    const CertificateList& additional_trust_anchors,
785    CertVerifyResult* verify_result) {
786#if defined(OS_IOS)
787  // For iOS, the entire chain must be loaded into NSS's in-memory certificate
788  // store.
789  x509_util_ios::NSSCertChain scoped_chain(cert);
790  CERTCertificate* cert_handle = scoped_chain.cert_handle();
791#else
792  CERTCertificate* cert_handle = cert->os_cert_handle();
793#endif  // defined(OS_IOS)
794
795  // Make sure that the hostname matches with the common name of the cert.
796  SECStatus status = CERT_VerifyCertName(cert_handle, hostname.c_str());
797  if (status != SECSuccess)
798    verify_result->cert_status |= CERT_STATUS_COMMON_NAME_INVALID;
799
800  // Make sure that the cert is valid now.
801  SECCertTimeValidity validity = CERT_CheckCertValidTimes(
802      cert_handle, PR_Now(), PR_TRUE);
803  if (validity != secCertTimeValid)
804    verify_result->cert_status |= CERT_STATUS_DATE_INVALID;
805
806  CERTValOutParam cvout[3];
807  int cvout_index = 0;
808  cvout[cvout_index].type = cert_po_certList;
809  cvout[cvout_index].value.pointer.chain = NULL;
810  int cvout_cert_list_index = cvout_index;
811  cvout_index++;
812  cvout[cvout_index].type = cert_po_trustAnchor;
813  cvout[cvout_index].value.pointer.cert = NULL;
814  int cvout_trust_anchor_index = cvout_index;
815  cvout_index++;
816  cvout[cvout_index].type = cert_po_end;
817  ScopedCERTValOutParam scoped_cvout(cvout);
818
819  EVRootCAMetadata* metadata = EVRootCAMetadata::GetInstance();
820  SECOidTag ev_policy_oid = SEC_OID_UNKNOWN;
821  bool is_ev_candidate =
822      (flags & CertVerifier::VERIFY_EV_CERT) &&
823      IsEVCandidate(metadata, cert_handle, &ev_policy_oid);
824  bool cert_io_enabled = flags & CertVerifier::VERIFY_CERT_IO_ENABLED;
825  bool check_revocation =
826      cert_io_enabled &&
827      (flags & CertVerifier::VERIFY_REV_CHECKING_ENABLED);
828  if (check_revocation)
829    verify_result->cert_status |= CERT_STATUS_REV_CHECKING_ENABLED;
830
831  ScopedCERTCertList trust_anchors;
832  if (SupportsAdditionalTrustAnchors() && !additional_trust_anchors.empty()) {
833    trust_anchors.reset(
834        CertificateListToCERTCertList(additional_trust_anchors));
835  }
836
837  status = PKIXVerifyCert(cert_handle, check_revocation, false,
838                          cert_io_enabled, NULL, 0, trust_anchors.get(),
839                          cvout);
840
841  if (status == SECSuccess &&
842      (flags & CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS) &&
843      !IsKnownRoot(cvout[cvout_trust_anchor_index].value.pointer.cert)) {
844    // TODO(rsleevi): Optimize this by supplying the constructed chain to
845    // libpkix via cvin. Omitting for now, due to lack of coverage in upstream
846    // NSS tests for that feature.
847    scoped_cvout.Clear();
848    verify_result->cert_status |= CERT_STATUS_REV_CHECKING_ENABLED;
849    status = PKIXVerifyCert(cert_handle, true, true,
850                            cert_io_enabled, NULL, 0, trust_anchors.get(),
851                            cvout);
852  }
853
854  if (status == SECSuccess) {
855    AppendPublicKeyHashes(cvout[cvout_cert_list_index].value.pointer.chain,
856                          cvout[cvout_trust_anchor_index].value.pointer.cert,
857                          &verify_result->public_key_hashes);
858
859    verify_result->is_issued_by_known_root =
860        IsKnownRoot(cvout[cvout_trust_anchor_index].value.pointer.cert);
861    verify_result->is_issued_by_additional_trust_anchor =
862        IsAdditionalTrustAnchor(
863            trust_anchors.get(),
864            cvout[cvout_trust_anchor_index].value.pointer.cert);
865
866    GetCertChainInfo(cvout[cvout_cert_list_index].value.pointer.chain,
867                     cvout[cvout_trust_anchor_index].value.pointer.cert,
868                     verify_result);
869  }
870
871  CRLSetResult crl_set_result = kCRLSetUnknown;
872  if (crl_set) {
873    crl_set_result = CheckRevocationWithCRLSet(
874        cvout[cvout_cert_list_index].value.pointer.chain,
875        cvout[cvout_trust_anchor_index].value.pointer.cert,
876        crl_set);
877    if (crl_set_result == kCRLSetRevoked) {
878      PORT_SetError(SEC_ERROR_REVOKED_CERTIFICATE);
879      status = SECFailure;
880    }
881  }
882
883  if (status != SECSuccess) {
884    int err = PORT_GetError();
885    LOG(ERROR) << "CERT_PKIXVerifyCert for " << hostname
886               << " failed err=" << err;
887    // CERT_PKIXVerifyCert rerports the wrong error code for
888    // expired certificates (NSS bug 491174)
889    if (err == SEC_ERROR_CERT_NOT_VALID &&
890        (verify_result->cert_status & CERT_STATUS_DATE_INVALID))
891      err = SEC_ERROR_EXPIRED_CERTIFICATE;
892    CertStatus cert_status = MapCertErrorToCertStatus(err);
893    if (cert_status) {
894      verify_result->cert_status |= cert_status;
895      return MapCertStatusToNetError(verify_result->cert_status);
896    }
897    // |err| is not a certificate error.
898    return MapSecurityError(err);
899  }
900
901  if (IsCertStatusError(verify_result->cert_status))
902    return MapCertStatusToNetError(verify_result->cert_status);
903
904  if ((flags & CertVerifier::VERIFY_EV_CERT) && is_ev_candidate) {
905    check_revocation |=
906        crl_set_result != kCRLSetOk &&
907        cert_io_enabled &&
908        (flags & CertVerifier::VERIFY_REV_CHECKING_ENABLED_EV_ONLY);
909    if (check_revocation)
910      verify_result->cert_status |= CERT_STATUS_REV_CHECKING_ENABLED;
911
912    if (VerifyEV(cert_handle, flags, crl_set, check_revocation, metadata,
913                 ev_policy_oid, trust_anchors.get())) {
914      verify_result->cert_status |= CERT_STATUS_IS_EV;
915    }
916  }
917
918  return OK;
919}
920
921}  // namespace net
922