cert_verify_proc_nss.cc revision 558790d6acca3451cf3a6b497803a5f07d0bec58
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  kCRLSetRevoked,
262  kCRLSetOk,
263  kCRLSetError,
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//   kCRLSetError: if an error occurs in processing.
270//   kCRLSetOk: if no element in the chain is known to have been revoked.
271CRLSetResult CheckRevocationWithCRLSet(CERTCertList* cert_list,
272                                       CERTCertificate* root,
273                                       CRLSet* crl_set) {
274  std::vector<CERTCertificate*> certs;
275
276  if (cert_list) {
277    for (CERTCertListNode* node = CERT_LIST_HEAD(cert_list);
278         !CERT_LIST_END(node, cert_list);
279         node = CERT_LIST_NEXT(node)) {
280      certs.push_back(node->cert);
281    }
282  }
283  if (root)
284    certs.push_back(root);
285
286  // We iterate from the root certificate down to the leaf, keeping track of
287  // the issuer's SPKI at each step.
288  std::string issuer_spki_hash;
289  for (std::vector<CERTCertificate*>::reverse_iterator i = certs.rbegin();
290       i != certs.rend(); ++i) {
291    CERTCertificate* cert = *i;
292
293    base::StringPiece der(reinterpret_cast<char*>(cert->derCert.data),
294                          cert->derCert.len);
295
296    base::StringPiece spki;
297    if (!asn1::ExtractSPKIFromDERCert(der, &spki)) {
298      NOTREACHED();
299      return kCRLSetError;
300    }
301    const std::string spki_hash = crypto::SHA256HashString(spki);
302
303    base::StringPiece serial_number = base::StringPiece(
304        reinterpret_cast<char*>(cert->serialNumber.data),
305        cert->serialNumber.len);
306
307    CRLSet::Result result = crl_set->CheckSPKI(spki_hash);
308
309    if (result != CRLSet::REVOKED && !issuer_spki_hash.empty())
310      result = crl_set->CheckSerial(serial_number, issuer_spki_hash);
311
312    issuer_spki_hash = spki_hash;
313
314    switch (result) {
315      case CRLSet::REVOKED:
316        return kCRLSetRevoked;
317      case CRLSet::UNKNOWN:
318      case CRLSet::GOOD:
319        continue;
320      default:
321        NOTREACHED();
322        return kCRLSetError;
323    }
324  }
325
326  return kCRLSetOk;
327}
328
329// Forward declarations.
330SECStatus RetryPKIXVerifyCertWithWorkarounds(
331    CERTCertificate* cert_handle, int num_policy_oids,
332    bool cert_io_enabled, std::vector<CERTValInParam>* cvin,
333    CERTValOutParam* cvout);
334SECOidTag GetFirstCertPolicy(CERTCertificate* cert_handle);
335
336// Call CERT_PKIXVerifyCert for the cert_handle.
337// Verification results are stored in an array of CERTValOutParam.
338// If |hard_fail| is true, and no policy_oids are supplied (eg: EV is NOT being
339// checked), then the failure to obtain valid CRL/OCSP information for all
340// certificates that contain CRL/OCSP URLs will cause the certificate to be
341// treated as if it was revoked. Since failures may be caused by transient
342// network failures or by malicious attackers, in general, hard_fail should be
343// false.
344// If policy_oids is not NULL and num_policy_oids is positive, policies
345// are also checked.
346// additional_trust_anchors is an optional list of certificates that can be
347// trusted as anchors when building a certificate chain.
348// Caller must initialize cvout before calling this function.
349SECStatus PKIXVerifyCert(CERTCertificate* cert_handle,
350                         bool check_revocation,
351                         bool hard_fail,
352                         bool cert_io_enabled,
353                         const SECOidTag* policy_oids,
354                         int num_policy_oids,
355                         CERTCertList* additional_trust_anchors,
356                         CERTValOutParam* cvout) {
357  bool use_crl = check_revocation;
358  bool use_ocsp = check_revocation;
359
360  // These CAs have multiple keys, which trigger two bugs in NSS's CRL code.
361  // 1. NSS may use one key to verify a CRL signed with another key,
362  //    incorrectly concluding that the CRL's signature is invalid.
363  //    Hopefully this bug will be fixed in NSS 3.12.9.
364  // 2. NSS considers all certificates issued by the CA as revoked when it
365  //    receives a CRL with an invalid signature.  This overly strict policy
366  //    has been relaxed in NSS 3.12.7.  See
367  //    https://bugzilla.mozilla.org/show_bug.cgi?id=562542.
368  // So we have to turn off CRL checking for these CAs.  See
369  // http://crbug.com/55695.
370  static const char* const kMultipleKeyCA[] = {
371    "CN=Microsoft Secure Server Authority,"
372    "DC=redmond,DC=corp,DC=microsoft,DC=com",
373    "CN=Microsoft Secure Server Authority",
374  };
375
376  if (!NSS_VersionCheck("3.12.7")) {
377    for (size_t i = 0; i < arraysize(kMultipleKeyCA); ++i) {
378      if (strcmp(cert_handle->issuerName, kMultipleKeyCA[i]) == 0) {
379        use_crl = false;
380        break;
381      }
382    }
383  }
384
385  PRUint64 revocation_method_flags =
386      CERT_REV_M_DO_NOT_TEST_USING_THIS_METHOD |
387      CERT_REV_M_ALLOW_NETWORK_FETCHING |
388      CERT_REV_M_IGNORE_IMPLICIT_DEFAULT_SOURCE |
389      CERT_REV_M_IGNORE_MISSING_FRESH_INFO |
390      CERT_REV_M_STOP_TESTING_ON_FRESH_INFO;
391  PRUint64 revocation_method_independent_flags =
392      CERT_REV_MI_TEST_ALL_LOCAL_INFORMATION_FIRST;
393  if (check_revocation && policy_oids && num_policy_oids > 0) {
394    // EV verification requires revocation checking.  Consider the certificate
395    // revoked if we don't have revocation info.
396    // TODO(wtc): Add a bool parameter to expressly specify we're doing EV
397    // verification or we want strict revocation flags.
398    revocation_method_flags |= CERT_REV_M_REQUIRE_INFO_ON_MISSING_SOURCE;
399    revocation_method_independent_flags |=
400        CERT_REV_MI_REQUIRE_SOME_FRESH_INFO_AVAILABLE;
401  } else if (check_revocation && hard_fail) {
402    revocation_method_flags |= CERT_REV_M_FAIL_ON_MISSING_FRESH_INFO;
403    revocation_method_independent_flags |=
404        CERT_REV_MI_REQUIRE_SOME_FRESH_INFO_AVAILABLE;
405  } else {
406    revocation_method_flags |= CERT_REV_M_SKIP_TEST_ON_MISSING_SOURCE;
407    revocation_method_independent_flags |=
408        CERT_REV_MI_NO_OVERALL_INFO_REQUIREMENT;
409  }
410  PRUint64 method_flags[2];
411  method_flags[cert_revocation_method_crl] = revocation_method_flags;
412  method_flags[cert_revocation_method_ocsp] = revocation_method_flags;
413
414  if (use_crl) {
415    method_flags[cert_revocation_method_crl] |=
416        CERT_REV_M_TEST_USING_THIS_METHOD;
417  }
418  if (use_ocsp) {
419    method_flags[cert_revocation_method_ocsp] |=
420        CERT_REV_M_TEST_USING_THIS_METHOD;
421  }
422
423  CERTRevocationMethodIndex preferred_revocation_methods[1];
424  if (use_ocsp) {
425    preferred_revocation_methods[0] = cert_revocation_method_ocsp;
426  } else {
427    preferred_revocation_methods[0] = cert_revocation_method_crl;
428  }
429
430  CERTRevocationFlags revocation_flags;
431  revocation_flags.leafTests.number_of_defined_methods =
432      arraysize(method_flags);
433  revocation_flags.leafTests.cert_rev_flags_per_method = method_flags;
434  revocation_flags.leafTests.number_of_preferred_methods =
435      arraysize(preferred_revocation_methods);
436  revocation_flags.leafTests.preferred_methods = preferred_revocation_methods;
437  revocation_flags.leafTests.cert_rev_method_independent_flags =
438      revocation_method_independent_flags;
439
440  revocation_flags.chainTests.number_of_defined_methods =
441      arraysize(method_flags);
442  revocation_flags.chainTests.cert_rev_flags_per_method = method_flags;
443  revocation_flags.chainTests.number_of_preferred_methods =
444      arraysize(preferred_revocation_methods);
445  revocation_flags.chainTests.preferred_methods = preferred_revocation_methods;
446  revocation_flags.chainTests.cert_rev_method_independent_flags =
447      revocation_method_independent_flags;
448
449
450  std::vector<CERTValInParam> cvin;
451  cvin.reserve(7);
452  CERTValInParam in_param;
453  in_param.type = cert_pi_revocationFlags;
454  in_param.value.pointer.revocation = &revocation_flags;
455  cvin.push_back(in_param);
456  if (policy_oids && num_policy_oids > 0) {
457    in_param.type = cert_pi_policyOID;
458    in_param.value.arraySize = num_policy_oids;
459    in_param.value.array.oids = policy_oids;
460    cvin.push_back(in_param);
461  }
462  if (additional_trust_anchors) {
463    in_param.type = cert_pi_trustAnchors;
464    in_param.value.pointer.chain = additional_trust_anchors;
465    cvin.push_back(in_param);
466    in_param.type = cert_pi_useOnlyTrustAnchors;
467    in_param.value.scalar.b = PR_FALSE;
468    cvin.push_back(in_param);
469  }
470  in_param.type = cert_pi_end;
471  cvin.push_back(in_param);
472
473  SECStatus rv = CERT_PKIXVerifyCert(cert_handle, certificateUsageSSLServer,
474                                     &cvin[0], cvout, NULL);
475  if (rv != SECSuccess) {
476    rv = RetryPKIXVerifyCertWithWorkarounds(cert_handle, num_policy_oids,
477                                            cert_io_enabled, &cvin, cvout);
478  }
479  return rv;
480}
481
482// PKIXVerifyCert calls this function to work around some bugs in
483// CERT_PKIXVerifyCert.  All the arguments of this function are either the
484// arguments or local variables of PKIXVerifyCert.
485SECStatus RetryPKIXVerifyCertWithWorkarounds(
486    CERTCertificate* cert_handle, int num_policy_oids,
487    bool cert_io_enabled, std::vector<CERTValInParam>* cvin,
488    CERTValOutParam* cvout) {
489  // We call this function when the first CERT_PKIXVerifyCert call in
490  // PKIXVerifyCert failed,  so we initialize |rv| to SECFailure.
491  SECStatus rv = SECFailure;
492  int nss_error = PORT_GetError();
493  CERTValInParam in_param;
494
495  // If we get SEC_ERROR_UNKNOWN_ISSUER, we may be missing an intermediate
496  // CA certificate, so we retry with cert_pi_useAIACertFetch.
497  // cert_pi_useAIACertFetch has several bugs in its error handling and
498  // error reporting (NSS bug 528743), so we don't use it by default.
499  // Note: When building a certificate chain, CERT_PKIXVerifyCert may
500  // incorrectly pick a CA certificate with the same subject name as the
501  // missing intermediate CA certificate, and  fail with the
502  // SEC_ERROR_BAD_SIGNATURE error (NSS bug 524013), so we also retry with
503  // cert_pi_useAIACertFetch on SEC_ERROR_BAD_SIGNATURE.
504  if (cert_io_enabled &&
505      (nss_error == SEC_ERROR_UNKNOWN_ISSUER ||
506       nss_error == SEC_ERROR_BAD_SIGNATURE)) {
507    DCHECK_EQ(cvin->back().type,  cert_pi_end);
508    cvin->pop_back();
509    in_param.type = cert_pi_useAIACertFetch;
510    in_param.value.scalar.b = PR_TRUE;
511    cvin->push_back(in_param);
512    in_param.type = cert_pi_end;
513    cvin->push_back(in_param);
514    rv = CERT_PKIXVerifyCert(cert_handle, certificateUsageSSLServer,
515                             &(*cvin)[0], cvout, NULL);
516    if (rv == SECSuccess)
517      return rv;
518    int new_nss_error = PORT_GetError();
519    if (new_nss_error == SEC_ERROR_INVALID_ARGS ||
520        new_nss_error == SEC_ERROR_UNKNOWN_AIA_LOCATION_TYPE ||
521        new_nss_error == SEC_ERROR_BAD_INFO_ACCESS_LOCATION ||
522        new_nss_error == SEC_ERROR_BAD_HTTP_RESPONSE ||
523        new_nss_error == SEC_ERROR_BAD_LDAP_RESPONSE ||
524        !IS_SEC_ERROR(new_nss_error)) {
525      // Use the original error code because of cert_pi_useAIACertFetch's
526      // bad error reporting.
527      PORT_SetError(nss_error);
528      return rv;
529    }
530    nss_error = new_nss_error;
531  }
532
533  // If an intermediate CA certificate has requireExplicitPolicy in its
534  // policyConstraints extension, CERT_PKIXVerifyCert fails with
535  // SEC_ERROR_POLICY_VALIDATION_FAILED because we didn't specify any
536  // certificate policy (NSS bug 552775).  So we retry with the certificate
537  // policy found in the server certificate.
538  if (nss_error == SEC_ERROR_POLICY_VALIDATION_FAILED &&
539      num_policy_oids == 0) {
540    SECOidTag policy = GetFirstCertPolicy(cert_handle);
541    if (policy != SEC_OID_UNKNOWN) {
542      DCHECK_EQ(cvin->back().type,  cert_pi_end);
543      cvin->pop_back();
544      in_param.type = cert_pi_policyOID;
545      in_param.value.arraySize = 1;
546      in_param.value.array.oids = &policy;
547      cvin->push_back(in_param);
548      in_param.type = cert_pi_end;
549      cvin->push_back(in_param);
550      rv = CERT_PKIXVerifyCert(cert_handle, certificateUsageSSLServer,
551                               &(*cvin)[0], cvout, NULL);
552      if (rv != SECSuccess) {
553        // Use the original error code.
554        PORT_SetError(nss_error);
555      }
556    }
557  }
558
559  return rv;
560}
561
562// Decodes the certificatePolicies extension of the certificate.  Returns
563// NULL if the certificate doesn't have the extension or the extension can't
564// be decoded.  The returned value must be freed with a
565// CERT_DestroyCertificatePoliciesExtension call.
566CERTCertificatePolicies* DecodeCertPolicies(
567    CERTCertificate* cert_handle) {
568  SECItem policy_ext;
569  SECStatus rv = CERT_FindCertExtension(cert_handle,
570                                        SEC_OID_X509_CERTIFICATE_POLICIES,
571                                        &policy_ext);
572  if (rv != SECSuccess)
573    return NULL;
574  CERTCertificatePolicies* policies =
575      CERT_DecodeCertificatePoliciesExtension(&policy_ext);
576  SECITEM_FreeItem(&policy_ext, PR_FALSE);
577  return policies;
578}
579
580// Returns the OID tag for the first certificate policy in the certificate's
581// certificatePolicies extension.  Returns SEC_OID_UNKNOWN if the certificate
582// has no certificate policy.
583SECOidTag GetFirstCertPolicy(CERTCertificate* cert_handle) {
584  ScopedCERTCertificatePolicies policies(DecodeCertPolicies(cert_handle));
585  if (!policies.get())
586    return SEC_OID_UNKNOWN;
587
588  CERTPolicyInfo* policy_info = policies->policyInfos[0];
589  if (!policy_info)
590    return SEC_OID_UNKNOWN;
591  if (policy_info->oid != SEC_OID_UNKNOWN)
592    return policy_info->oid;
593
594  // The certificate policy is unknown to NSS.  We need to create a dynamic
595  // OID tag for the policy.
596  SECOidData od;
597  od.oid.len = policy_info->policyID.len;
598  od.oid.data = policy_info->policyID.data;
599  od.offset = SEC_OID_UNKNOWN;
600  // NSS doesn't allow us to pass an empty description, so I use a hardcoded,
601  // default description here.  The description doesn't need to be unique for
602  // each OID.
603  od.desc = "a certificate policy";
604  od.mechanism = CKM_INVALID_MECHANISM;
605  od.supportedExtension = INVALID_CERT_EXTENSION;
606  return SECOID_AddEntry(&od);
607}
608
609HashValue CertPublicKeyHashSHA1(CERTCertificate* cert) {
610  HashValue hash(HASH_VALUE_SHA1);
611#if defined(OS_IOS)
612  CC_SHA1(cert->derPublicKey.data, cert->derPublicKey.len, hash.data());
613#else
614  SECStatus rv = HASH_HashBuf(HASH_AlgSHA1, hash.data(),
615                              cert->derPublicKey.data, cert->derPublicKey.len);
616  DCHECK_EQ(SECSuccess, rv);
617#endif
618  return hash;
619}
620
621HashValue CertPublicKeyHashSHA256(CERTCertificate* cert) {
622  HashValue hash(HASH_VALUE_SHA256);
623#if defined(OS_IOS)
624  CC_SHA256(cert->derPublicKey.data, cert->derPublicKey.len, hash.data());
625#else
626  SECStatus rv = HASH_HashBuf(HASH_AlgSHA256, hash.data(),
627                              cert->derPublicKey.data, cert->derPublicKey.len);
628  DCHECK_EQ(rv, SECSuccess);
629#endif
630  return hash;
631}
632
633void AppendPublicKeyHashes(CERTCertList* cert_list,
634                           CERTCertificate* root_cert,
635                           HashValueVector* hashes) {
636  for (CERTCertListNode* node = CERT_LIST_HEAD(cert_list);
637       !CERT_LIST_END(node, cert_list);
638       node = CERT_LIST_NEXT(node)) {
639    hashes->push_back(CertPublicKeyHashSHA1(node->cert));
640    hashes->push_back(CertPublicKeyHashSHA256(node->cert));
641  }
642  if (root_cert) {
643    hashes->push_back(CertPublicKeyHashSHA1(root_cert));
644    hashes->push_back(CertPublicKeyHashSHA256(root_cert));
645  }
646}
647
648// Returns true if |cert_handle| contains a policy OID that is an EV policy
649// OID according to |metadata|, storing the resulting policy OID in
650// |*ev_policy_oid|. A true return is not sufficient to establish that a
651// certificate is EV, but a false return is sufficient to establish the
652// certificate cannot be EV.
653bool IsEVCandidate(EVRootCAMetadata* metadata,
654                   CERTCertificate* cert_handle,
655                   SECOidTag* ev_policy_oid) {
656  DCHECK(cert_handle);
657  ScopedCERTCertificatePolicies policies(DecodeCertPolicies(cert_handle));
658  if (!policies.get())
659    return false;
660
661  CERTPolicyInfo** policy_infos = policies->policyInfos;
662  while (*policy_infos != NULL) {
663    CERTPolicyInfo* policy_info = *policy_infos++;
664    // If the Policy OID is unknown, that implicitly means it has not been
665    // registered as an EV policy.
666    if (policy_info->oid == SEC_OID_UNKNOWN)
667      continue;
668    if (metadata->IsEVPolicyOID(policy_info->oid)) {
669      *ev_policy_oid = policy_info->oid;
670      return true;
671    }
672  }
673
674  return false;
675}
676
677// Studied Mozilla's code (esp. security/manager/ssl/src/nsIdentityChecking.cpp
678// and nsNSSCertHelper.cpp) to learn how to verify EV certificate.
679// TODO(wtc): A possible optimization is that we get the trust anchor from
680// the first PKIXVerifyCert call.  We look up the EV policy for the trust
681// anchor.  If the trust anchor has no EV policy, we know the cert isn't EV.
682// Otherwise, we pass just that EV policy (as opposed to all the EV policies)
683// to the second PKIXVerifyCert call.
684bool VerifyEV(CERTCertificate* cert_handle,
685              int flags,
686              CRLSet* crl_set,
687              EVRootCAMetadata* metadata,
688              SECOidTag ev_policy_oid,
689              CERTCertList* additional_trust_anchors) {
690  CERTValOutParam cvout[3];
691  int cvout_index = 0;
692  cvout[cvout_index].type = cert_po_certList;
693  cvout[cvout_index].value.pointer.chain = NULL;
694  int cvout_cert_list_index = cvout_index;
695  cvout_index++;
696  cvout[cvout_index].type = cert_po_trustAnchor;
697  cvout[cvout_index].value.pointer.cert = NULL;
698  int cvout_trust_anchor_index = cvout_index;
699  cvout_index++;
700  cvout[cvout_index].type = cert_po_end;
701  ScopedCERTValOutParam scoped_cvout(cvout);
702
703  bool rev_checking_enabled =
704      (flags & CertVerifier::VERIFY_REV_CHECKING_ENABLED) ||
705      (flags & CertVerifier::VERIFY_REV_CHECKING_ENABLED_EV_ONLY);
706
707  SECStatus status = PKIXVerifyCert(
708      cert_handle,
709      rev_checking_enabled,
710      true, /* hard fail is implied in EV. */
711      flags & CertVerifier::VERIFY_CERT_IO_ENABLED,
712      &ev_policy_oid,
713      1,
714      additional_trust_anchors,
715      cvout);
716  if (status != SECSuccess)
717    return false;
718
719  CERTCertificate* root_ca =
720      cvout[cvout_trust_anchor_index].value.pointer.cert;
721  if (root_ca == NULL)
722    return false;
723
724  // This second PKIXVerifyCert call could have found a different certification
725  // path and one or more of the certificates on this new path, that weren't on
726  // the old path, might have been revoked.
727  if (crl_set) {
728    CRLSetResult crl_set_result = CheckRevocationWithCRLSet(
729        cvout[cvout_cert_list_index].value.pointer.chain,
730        cvout[cvout_trust_anchor_index].value.pointer.cert,
731        crl_set);
732    if (crl_set_result == kCRLSetRevoked)
733      return false;
734  }
735
736#if defined(OS_IOS)
737  SHA1HashValue fingerprint = x509_util_ios::CalculateFingerprintNSS(root_ca);
738#else
739  SHA1HashValue fingerprint =
740      X509Certificate::CalculateFingerprint(root_ca);
741#endif
742  return metadata->HasEVPolicyOID(fingerprint, ev_policy_oid);
743}
744
745CERTCertList* CertificateListToCERTCertList(const CertificateList& list) {
746  CERTCertList* result = CERT_NewCertList();
747  for (size_t i = 0; i < list.size(); ++i) {
748#if defined(OS_IOS)
749    // X509Certificate::os_cert_handle() on iOS is a SecCertificateRef; convert
750    // it to an NSS CERTCertificate.
751    CERTCertificate* cert = x509_util_ios::CreateNSSCertHandleFromOSHandle(
752        list[i]->os_cert_handle());
753#else
754    CERTCertificate* cert = list[i]->os_cert_handle();
755#endif
756    CERT_AddCertToListTail(result, CERT_DupCertificate(cert));
757  }
758  return result;
759}
760
761}  // namespace
762
763CertVerifyProcNSS::CertVerifyProcNSS() {}
764
765CertVerifyProcNSS::~CertVerifyProcNSS() {}
766
767bool CertVerifyProcNSS::SupportsAdditionalTrustAnchors() const {
768  // This requires APIs introduced in 3.14.2.
769  return NSS_VersionCheck("3.14.2");
770}
771
772int CertVerifyProcNSS::VerifyInternal(
773    X509Certificate* cert,
774    const std::string& hostname,
775    int flags,
776    CRLSet* crl_set,
777    const CertificateList& additional_trust_anchors,
778    CertVerifyResult* verify_result) {
779#if defined(OS_IOS)
780  // For iOS, the entire chain must be loaded into NSS's in-memory certificate
781  // store.
782  x509_util_ios::NSSCertChain scoped_chain(cert);
783  CERTCertificate* cert_handle = scoped_chain.cert_handle();
784#else
785  CERTCertificate* cert_handle = cert->os_cert_handle();
786#endif  // defined(OS_IOS)
787
788  // Make sure that the hostname matches with the common name of the cert.
789  SECStatus status = CERT_VerifyCertName(cert_handle, hostname.c_str());
790  if (status != SECSuccess)
791    verify_result->cert_status |= CERT_STATUS_COMMON_NAME_INVALID;
792
793  // Make sure that the cert is valid now.
794  SECCertTimeValidity validity = CERT_CheckCertValidTimes(
795      cert_handle, PR_Now(), PR_TRUE);
796  if (validity != secCertTimeValid)
797    verify_result->cert_status |= CERT_STATUS_DATE_INVALID;
798
799  CERTValOutParam cvout[3];
800  int cvout_index = 0;
801  cvout[cvout_index].type = cert_po_certList;
802  cvout[cvout_index].value.pointer.chain = NULL;
803  int cvout_cert_list_index = cvout_index;
804  cvout_index++;
805  cvout[cvout_index].type = cert_po_trustAnchor;
806  cvout[cvout_index].value.pointer.cert = NULL;
807  int cvout_trust_anchor_index = cvout_index;
808  cvout_index++;
809  cvout[cvout_index].type = cert_po_end;
810  ScopedCERTValOutParam scoped_cvout(cvout);
811
812  EVRootCAMetadata* metadata = EVRootCAMetadata::GetInstance();
813  SECOidTag ev_policy_oid = SEC_OID_UNKNOWN;
814  bool is_ev_candidate =
815      (flags & CertVerifier::VERIFY_EV_CERT) &&
816      IsEVCandidate(metadata, cert_handle, &ev_policy_oid);
817  bool cert_io_enabled = flags & CertVerifier::VERIFY_CERT_IO_ENABLED;
818  bool check_revocation =
819      cert_io_enabled &&
820      ((flags & CertVerifier::VERIFY_REV_CHECKING_ENABLED) ||
821       ((flags & CertVerifier::VERIFY_REV_CHECKING_ENABLED_EV_ONLY) &&
822        is_ev_candidate));
823  if (check_revocation)
824    verify_result->cert_status |= CERT_STATUS_REV_CHECKING_ENABLED;
825
826  ScopedCERTCertList trust_anchors;
827  if (SupportsAdditionalTrustAnchors() && !additional_trust_anchors.empty()) {
828    trust_anchors.reset(
829        CertificateListToCERTCertList(additional_trust_anchors));
830  }
831
832  status = PKIXVerifyCert(cert_handle, check_revocation, false,
833                          cert_io_enabled, NULL, 0, trust_anchors.get(),
834                          cvout);
835
836  if (status == SECSuccess &&
837      (flags & CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS) &&
838      !IsKnownRoot(cvout[cvout_trust_anchor_index].value.pointer.cert)) {
839    // TODO(rsleevi): Optimize this by supplying the constructed chain to
840    // libpkix via cvin. Omitting for now, due to lack of coverage in upstream
841    // NSS tests for that feature.
842    scoped_cvout.Clear();
843    verify_result->cert_status |= CERT_STATUS_REV_CHECKING_ENABLED;
844    status = PKIXVerifyCert(cert_handle, true, true,
845                            cert_io_enabled, NULL, 0, trust_anchors.get(),
846                            cvout);
847  }
848
849  if (status == SECSuccess) {
850    AppendPublicKeyHashes(cvout[cvout_cert_list_index].value.pointer.chain,
851                          cvout[cvout_trust_anchor_index].value.pointer.cert,
852                          &verify_result->public_key_hashes);
853
854    verify_result->is_issued_by_known_root =
855        IsKnownRoot(cvout[cvout_trust_anchor_index].value.pointer.cert);
856    verify_result->is_issued_by_additional_trust_anchor =
857        IsAdditionalTrustAnchor(
858            trust_anchors.get(),
859            cvout[cvout_trust_anchor_index].value.pointer.cert);
860
861    GetCertChainInfo(cvout[cvout_cert_list_index].value.pointer.chain,
862                     cvout[cvout_trust_anchor_index].value.pointer.cert,
863                     verify_result);
864  }
865
866  if (crl_set) {
867    CRLSetResult crl_set_result = CheckRevocationWithCRLSet(
868        cvout[cvout_cert_list_index].value.pointer.chain,
869        cvout[cvout_trust_anchor_index].value.pointer.cert,
870        crl_set);
871    if (crl_set_result == kCRLSetRevoked) {
872      PORT_SetError(SEC_ERROR_REVOKED_CERTIFICATE);
873      status = SECFailure;
874    }
875  }
876
877  if (status != SECSuccess) {
878    int err = PORT_GetError();
879    LOG(ERROR) << "CERT_PKIXVerifyCert for " << hostname
880               << " failed err=" << err;
881    // CERT_PKIXVerifyCert rerports the wrong error code for
882    // expired certificates (NSS bug 491174)
883    if (err == SEC_ERROR_CERT_NOT_VALID &&
884        (verify_result->cert_status & CERT_STATUS_DATE_INVALID))
885      err = SEC_ERROR_EXPIRED_CERTIFICATE;
886    CertStatus cert_status = MapCertErrorToCertStatus(err);
887    if (cert_status) {
888      verify_result->cert_status |= cert_status;
889      return MapCertStatusToNetError(verify_result->cert_status);
890    }
891    // |err| is not a certificate error.
892    return MapSecurityError(err);
893  }
894
895  if (IsCertStatusError(verify_result->cert_status))
896    return MapCertStatusToNetError(verify_result->cert_status);
897
898  if ((flags & CertVerifier::VERIFY_EV_CERT) && is_ev_candidate &&
899      VerifyEV(cert_handle, flags, crl_set, metadata, ev_policy_oid,
900               trust_anchors.get())) {
901    verify_result->cert_status |= CERT_STATUS_IS_EV;
902  }
903
904  return OK;
905}
906
907}  // namespace net
908