1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #include "RootCertificateTelemetryUtils.h"
8 
9 #include "RootHashes.inc"  // Note: Generated by genRootCAHashes.js
10 #include "ScopedNSSTypes.h"
11 #include "mozilla/ArrayUtils.h"
12 #include "mozilla/Logging.h"
13 #include "nsINSSComponent.h"
14 #include "nsNSSCertHelper.h"
15 #include "nsServiceManagerUtils.h"
16 #include "pk11pub.h"
17 
18 namespace mozilla {
19 namespace psm {
20 
21 mozilla::LazyLogModule gPublicKeyPinningTelemetryLog(
22     "PublicKeyPinningTelemetryService");
23 
24 // Used in the BinarySearch method, this does a memcmp between the pointer
25 // provided to its construtor and whatever the binary search is looking for.
26 //
27 // This implementation assumes everything to be of HASH_LEN, so it should not
28 // be used generically.
29 class BinaryHashSearchArrayComparator {
30  public:
BinaryHashSearchArrayComparator(const uint8_t * aTarget,size_t len)31   explicit BinaryHashSearchArrayComparator(const uint8_t* aTarget, size_t len)
32       : mTarget(aTarget) {
33     MOZ_ASSERT(len == HASH_LEN, "Hashes should be of the same length.");
34   }
35 
operator ()(const CertAuthorityHash val) const36   int operator()(const CertAuthorityHash val) const {
37     return memcmp(mTarget, val.hash, HASH_LEN);
38   }
39 
40  private:
41   const uint8_t* mTarget;
42 };
43 
44 // Perform a hash of the provided cert, then search in the RootHashes.inc data
45 // structure for a matching bin number.
46 // If no matching root is found, this may be a CA from the softoken (cert9.db),
47 // it may be a CA from an external PKCS#11 token, or it may be a CA from OS
48 // storage (Enterprise Root).
49 // See also the constants in RootCertificateTelemetryUtils.h.
RootCABinNumber(Span<const uint8_t> cert)50 int32_t RootCABinNumber(Span<const uint8_t> cert) {
51   nsTArray<uint8_t> digestArray;
52 
53   // Compute SHA256 hash of the certificate
54   nsresult rv = Digest::DigestBuf(SEC_OID_SHA256, cert, digestArray);
55   if (NS_WARN_IF(NS_FAILED(rv))) {
56     return ROOT_CERTIFICATE_HASH_FAILURE;
57   }
58 
59   // Compare against list of stored hashes
60   size_t idx;
61 
62   MOZ_LOG(gPublicKeyPinningTelemetryLog, LogLevel::Debug,
63           ("pkpinTelem: First bytes %02x %02x %02x %02x\n",
64            digestArray.ElementAt(0), digestArray.ElementAt(1),
65            digestArray.ElementAt(2), digestArray.ElementAt(3)));
66 
67   if (mozilla::BinarySearchIf(ROOT_TABLE, 0, ArrayLength(ROOT_TABLE),
68                               BinaryHashSearchArrayComparator(
69                                   digestArray.Elements(), digestArray.Length()),
70                               &idx)) {
71     MOZ_LOG(gPublicKeyPinningTelemetryLog, LogLevel::Debug,
72             ("pkpinTelem: Telemetry index was %zu, bin is %d\n", idx,
73              ROOT_TABLE[idx].binNumber));
74     return (int32_t)ROOT_TABLE[idx].binNumber;
75   }
76 
77   // Didn't find this certificate in the built-in list. It may be an enterprise
78   // root (gathered from the OS) or it may be from the softoken or an external
79   // PKCS#11 token.
80   nsCOMPtr<nsINSSComponent> component(do_GetService(PSM_COMPONENT_CONTRACTID));
81   if (!component) {
82     return ROOT_CERTIFICATE_UNKNOWN;
83   }
84   nsTArray<nsTArray<uint8_t>> enterpriseRoots;
85   rv = component->GetEnterpriseRoots(enterpriseRoots);
86   if (NS_FAILED(rv)) {
87     return ROOT_CERTIFICATE_UNKNOWN;
88   }
89   for (const auto& enterpriseRoot : enterpriseRoots) {
90     if (enterpriseRoot.Length() == cert.size() &&
91         memcmp(enterpriseRoot.Elements(), cert.data(),
92                enterpriseRoot.Length()) == 0) {
93       return ROOT_CERTIFICATE_ENTERPRISE_ROOT;
94     }
95   }
96 
97   SECItem certItem = {siBuffer, const_cast<uint8_t*>(cert.data()),
98                       static_cast<unsigned int>(cert.size())};
99   UniquePK11SlotInfo softokenSlot(PK11_GetInternalKeySlot());
100   if (!softokenSlot) {
101     return ROOT_CERTIFICATE_UNKNOWN;
102   }
103   CK_OBJECT_HANDLE softokenCertHandle =
104       PK11_FindEncodedCertInSlot(softokenSlot.get(), &certItem, nullptr);
105   if (softokenCertHandle != CK_INVALID_HANDLE) {
106     return ROOT_CERTIFICATE_SOFTOKEN;
107   }
108   // In theory this should never find the certificate in the root module,
109   // because then it should have already matched our built-in list. This is
110   // here as a backstop to catch situations where a built-in root was added but
111   // the built-in telemetry information was not updated.
112   UniqueSECMODModule rootsModule(SECMOD_FindModule(kRootModuleName));
113   if (!rootsModule || rootsModule->slotCount != 1) {
114     return ROOT_CERTIFICATE_UNKNOWN;
115   }
116   CK_OBJECT_HANDLE builtinCertHandle =
117       PK11_FindEncodedCertInSlot(rootsModule->slots[0], &certItem, nullptr);
118   if (builtinCertHandle == CK_INVALID_HANDLE) {
119     return ROOT_CERTIFICATE_EXTERNAL_TOKEN;
120   }
121 
122   // We have no idea what this is.
123   return ROOT_CERTIFICATE_UNKNOWN;
124 }
125 
126 // Attempt to increment the appropriate bin in the provided Telemetry probe ID.
127 // If there was a hash failure, we do nothing.
AccumulateTelemetryForRootCA(mozilla::Telemetry::HistogramID probe,const Span<const uint8_t> cert)128 void AccumulateTelemetryForRootCA(mozilla::Telemetry::HistogramID probe,
129                                   const Span<const uint8_t> cert) {
130   int32_t binId = RootCABinNumber(cert);
131 
132   if (binId != ROOT_CERTIFICATE_HASH_FAILURE) {
133     Accumulate(probe, binId);
134   }
135 }
136 
137 }  // namespace psm
138 }  // namespace mozilla
139