DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (27bbc1fba015)

VCS Links

Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "PublicKeyPinningService.h"

#include "RootCertificateTelemetryUtils.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/Base64.h"
#include "mozilla/BinarySearch.h"
#include "mozilla/Casting.h"
#include "mozilla/Logging.h"
#include "mozilla/Telemetry.h"
#include "nsDependentString.h"
#include "nsISiteSecurityService.h"
#include "nsServiceManagerUtils.h"
#include "nsSiteSecurityService.h"
#include "mozpkix/pkixtypes.h"
#include "seccomon.h"
#include "sechash.h"

#include "StaticHPKPins.h"  // autogenerated by genHPKPStaticpins.js

using namespace mozilla;
using namespace mozilla::pkix;
using namespace mozilla::psm;

LazyLogModule gPublicKeyPinningLog("PublicKeyPinningService");

/**
 Computes in the location specified by base64Out the SHA256 digest
 of the DER Encoded subject Public Key Info for the given cert
*/
static nsresult GetBase64HashSPKI(const CERTCertificate* cert,
                                  nsACString& hashSPKIDigest) {
  hashSPKIDigest.Truncate();
  Digest digest;
  nsresult rv = digest.DigestBuf(SEC_OID_SHA256, cert->derPublicKey.data,
                                 cert->derPublicKey.len);
  if (NS_FAILED(rv)) {
    return rv;
  }
  return Base64Encode(nsDependentCSubstring(
                          BitwiseCast<char*, unsigned char*>(digest.get().data),
                          digest.get().len),
                      hashSPKIDigest);
}

/*
 * Sets certMatchesPinset to true if a given cert matches any fingerprints from
 * the given pinset or the dynamicFingerprints array, or to false otherwise.
 */
static nsresult EvalCert(const CERTCertificate* cert,
                         const StaticFingerprints* fingerprints,
                         const nsTArray<nsCString>* dynamicFingerprints,
                         /*out*/ bool& certMatchesPinset) {
  certMatchesPinset = false;
  if (!fingerprints && !dynamicFingerprints) {
    MOZ_LOG(gPublicKeyPinningLog, LogLevel::Debug,
            ("pkpin: No hashes found\n"));
    return NS_ERROR_INVALID_ARG;
  }

  nsAutoCString base64Out;
  nsresult rv = GetBase64HashSPKI(cert, base64Out);
  if (NS_FAILED(rv)) {
    MOZ_LOG(gPublicKeyPinningLog, LogLevel::Debug,
            ("pkpin: GetBase64HashSPKI failed!\n"));
    return rv;
  }

  if (fingerprints) {
    for (size_t i = 0; i < fingerprints->size; i++) {
      if (base64Out.Equals(fingerprints->data[i])) {
        MOZ_LOG(gPublicKeyPinningLog, LogLevel::Debug,
                ("pkpin: found pin base_64 ='%s'\n", base64Out.get()));
        certMatchesPinset = true;
        return NS_OK;
      }
    }
  }
  if (dynamicFingerprints) {
    for (size_t i = 0; i < dynamicFingerprints->Length(); i++) {
      if (base64Out.Equals((*dynamicFingerprints)[i])) {
        MOZ_LOG(gPublicKeyPinningLog, LogLevel::Debug,
                ("pkpin: found pin base_64 ='%s'\n", base64Out.get()));
        certMatchesPinset = true;
        return NS_OK;
      }
    }
  }
  return NS_OK;
}

/*
 * Sets certListIntersectsPinset to true if a given chain matches any
 * fingerprints from the given static fingerprints or the
 * dynamicFingerprints array, or to false otherwise.
 */
static nsresult EvalChain(const RefPtr<nsNSSCertList>& certList,
                          const StaticFingerprints* fingerprints,
                          const nsTArray<nsCString>* dynamicFingerprints,
                          /*out*/ bool& certListIntersectsPinset) {
  certListIntersectsPinset = false;
  if (!fingerprints && !dynamicFingerprints) {
    MOZ_ASSERT(false, "Must pass in at least one type of pinset");
    return NS_ERROR_FAILURE;
  }

  certList->ForEachCertificateInChain(
      [&certListIntersectsPinset, &fingerprints, &dynamicFingerprints](
          nsCOMPtr<nsIX509Cert> aCert, bool aHasMore,
          /* out */ bool& aContinue) {
        // We need an owning handle when calling nsIX509Cert::GetCert().
        UniqueCERTCertificate nssCert(aCert->GetCert());
        MOZ_LOG(gPublicKeyPinningLog, LogLevel::Debug,
                ("pkpin: certArray subject: '%s'\n", nssCert->subjectName));
        MOZ_LOG(gPublicKeyPinningLog, LogLevel::Debug,
                ("pkpin: certArray issuer: '%s'\n", nssCert->issuerName));
        nsresult rv = EvalCert(nssCert.get(), fingerprints, dynamicFingerprints,
                               certListIntersectsPinset);
        if (NS_FAILED(rv)) {
          return rv;
        }

        if (certListIntersectsPinset) {
          aContinue = false;
        }
        return NS_OK;
      });

  if (!certListIntersectsPinset) {
    MOZ_LOG(gPublicKeyPinningLog, LogLevel::Debug,
            ("pkpin: no matches found\n"));
  }
  return NS_OK;
}

class TransportSecurityPreloadBinarySearchComparator {
 public:
  explicit TransportSecurityPreloadBinarySearchComparator(
      const char* aTargetHost)
      : mTargetHost(aTargetHost) {}

  int operator()(const TransportSecurityPreload& val) const {
    return strcmp(mTargetHost, val.mHost);
  }

 private:
  const char* mTargetHost;  // non-owning
};

nsresult PublicKeyPinningService::ChainMatchesPinset(
    const RefPtr<nsNSSCertList>& certList,
    const nsTArray<nsCString>& aSHA256keys,
    /*out*/ bool& chainMatchesPinset) {
  return EvalChain(certList, nullptr, &aSHA256keys, chainMatchesPinset);
}

#ifdef DEBUG
static Atomic<bool> sValidatedPinningPreloadList(false);

static void ValidatePinningPreloadList() {
  if (sValidatedPinningPreloadList) {
    return;
  }
  for (const auto& entry : kPublicKeyPinningPreloadList) {
    // If and only if a static entry is a Mozilla entry, it has a telemetry ID.
    MOZ_ASSERT((entry.mIsMoz && entry.mId != kUnknownId) ||
               (!entry.mIsMoz && entry.mId == kUnknownId));
  }
  sValidatedPinningPreloadList = true;
}
#endif  // DEBUG

// Returns via one of the output parameters the most relevant pinning
// information that is valid for the given host at the given time.
// Dynamic pins are prioritized over static pins.
static nsresult FindPinningInformation(
    const char* hostname, mozilla::pkix::Time time,
    const OriginAttributes& originAttributes,
    /*out*/ nsTArray<nsCString>& dynamicFingerprints,
    /*out*/ const TransportSecurityPreload*& staticFingerprints) {
#ifdef DEBUG
  ValidatePinningPreloadList();
#endif
  if (!hostname || hostname[0] == 0) {
    return NS_ERROR_INVALID_ARG;
  }
  staticFingerprints = nullptr;
  dynamicFingerprints.Clear();
  nsCOMPtr<nsISiteSecurityService> sssService =
      do_GetService(NS_SSSERVICE_CONTRACTID);
  if (!sssService) {
    return NS_ERROR_FAILURE;
  }
  const TransportSecurityPreload* foundEntry = nullptr;
  const char* evalHost = hostname;
  const char* evalPart;
  // Notice how the (xx = strchr) prevents pins for unqualified domain names.
  while (!foundEntry && (evalPart = strchr(evalHost, '.'))) {
    MOZ_LOG(gPublicKeyPinningLog, LogLevel::Debug,
            ("pkpin: Querying pinsets for host: '%s'\n", evalHost));
    // Attempt dynamic pins first
    nsresult rv;
    bool found;
    bool includeSubdomains;
    nsTArray<nsCString> pinArray;
    rv = sssService->GetKeyPinsForHostname(nsDependentCString(evalHost), time,
                                           originAttributes, pinArray,
                                           &includeSubdomains, &found);
    if (NS_FAILED(rv)) {
      return rv;
    }
    if (found && (evalHost == hostname || includeSubdomains)) {
      MOZ_LOG(gPublicKeyPinningLog, LogLevel::Debug,
              ("pkpin: Found dyn match for host: '%s'\n", evalHost));
      dynamicFingerprints = pinArray;
      return NS_OK;
    }

    size_t foundEntryIndex;
    if (BinarySearchIf(kPublicKeyPinningPreloadList, 0,
                       ArrayLength(kPublicKeyPinningPreloadList),
                       TransportSecurityPreloadBinarySearchComparator(evalHost),
                       &foundEntryIndex)) {
      foundEntry = &kPublicKeyPinningPreloadList[foundEntryIndex];
      MOZ_LOG(gPublicKeyPinningLog, LogLevel::Debug,
              ("pkpin: Found pinset for host: '%s'\n", evalHost));
      if (evalHost != hostname) {
        if (!foundEntry->mIncludeSubdomains) {
          // Does not apply to this host, continue iterating
          foundEntry = nullptr;
        }
      }
    } else {
      MOZ_LOG(gPublicKeyPinningLog, LogLevel::Debug,
              ("pkpin: Didn't find pinset for host: '%s'\n", evalHost));
    }
    // Add one for '.'
    evalHost = evalPart + 1;
  }

  if (foundEntry && foundEntry->pinset) {
    if (time > TimeFromEpochInSeconds(kPreloadPKPinsExpirationTime /
                                      PR_USEC_PER_SEC)) {
      return NS_OK;
    }
    staticFingerprints = foundEntry;
  }
  return NS_OK;
}

// Returns true via the output parameter if the given certificate list meets
// pinning requirements for the given host at the given time. It must be the
// case that either there is an intersection between the set of hashes of
// subject public key info data in the list and the most relevant non-expired
// pinset for the host or there is no pinning information for the host.
static nsresult CheckPinsForHostname(
    const RefPtr<nsNSSCertList>& certList, const char* hostname,
    bool enforceTestMode, mozilla::pkix::Time time,
    const OriginAttributes& originAttributes,
    /*out*/ bool& chainHasValidPins,
    /*optional out*/ PinningTelemetryInfo* pinningTelemetryInfo) {
  chainHasValidPins = false;
  if (!certList) {
    return NS_ERROR_INVALID_ARG;
  }
  if (!hostname || hostname[0] == 0) {
    return NS_ERROR_INVALID_ARG;
  }

  nsTArray<nsCString> dynamicFingerprints;
  const TransportSecurityPreload* staticFingerprints = nullptr;
  nsresult rv = FindPinningInformation(hostname, time, originAttributes,
                                       dynamicFingerprints, staticFingerprints);
  // If we have no pinning information, the certificate chain trivially
  // validates with respect to pinning.
  if (dynamicFingerprints.Length() == 0 && !staticFingerprints) {
    chainHasValidPins = true;
    return NS_OK;
  }
  if (dynamicFingerprints.Length() > 0) {
    return EvalChain(certList, nullptr, &dynamicFingerprints,
                     chainHasValidPins);
  }
  if (staticFingerprints) {
    bool enforceTestModeResult;
    rv = EvalChain(certList, staticFingerprints->pinset, nullptr,
                   enforceTestModeResult);
    if (NS_FAILED(rv)) {
      return rv;
    }
    chainHasValidPins = enforceTestModeResult;
    if (staticFingerprints->mTestMode && !enforceTestMode) {
      chainHasValidPins = true;
    }

    if (pinningTelemetryInfo) {
      // If and only if a static entry is a Mozilla entry, it has a telemetry
      // ID.
      if ((staticFingerprints->mIsMoz &&
           staticFingerprints->mId == kUnknownId) ||
          (!staticFingerprints->mIsMoz &&
           staticFingerprints->mId != kUnknownId)) {
        return NS_ERROR_FAILURE;
      }

      Telemetry::HistogramID histogram;
      int32_t bucket;
      // We can collect per-host pinning violations for this host because it is
      // operationally critical to Firefox.
      if (staticFingerprints->mIsMoz) {
        histogram = staticFingerprints->mTestMode
                        ? Telemetry::CERT_PINNING_MOZ_TEST_RESULTS_BY_HOST
                        : Telemetry::CERT_PINNING_MOZ_RESULTS_BY_HOST;
        bucket = staticFingerprints->mId * 2 + (enforceTestModeResult ? 1 : 0);
      } else {
        histogram = staticFingerprints->mTestMode
                        ? Telemetry::CERT_PINNING_TEST_RESULTS
                        : Telemetry::CERT_PINNING_RESULTS;
        bucket = enforceTestModeResult ? 1 : 0;
      }
      pinningTelemetryInfo->accumulateResult = true;
      pinningTelemetryInfo->certPinningResultHistogram = Some(histogram);
      pinningTelemetryInfo->certPinningResultBucket = bucket;

      // We only collect per-CA pinning statistics upon failures.
      if (!enforceTestModeResult) {
        nsCOMPtr<nsIX509Cert> rootCert;
        rv = certList->GetRootCertificate(rootCert);
        if (NS_FAILED(rv)) {
          return rv;
        }
        if (rootCert) {
          UniqueCERTCertificate rootCertObj(rootCert->GetCert());
          if (!rootCertObj) {
            return NS_ERROR_FAILURE;
          }
          int32_t binNumber =
              RootCABinNumber(&rootCertObj->derCert, rootCertObj->slot);
          if (binNumber != ROOT_CERTIFICATE_UNKNOWN) {
            pinningTelemetryInfo->accumulateForRoot = true;
            pinningTelemetryInfo->rootBucket = binNumber;
          }
        }
      }
    }

    MOZ_LOG(gPublicKeyPinningLog, LogLevel::Debug,
            ("pkpin: Pin check %s for %s host '%s' (mode=%s)\n",
             enforceTestModeResult ? "passed" : "failed",
             staticFingerprints->mIsMoz ? "mozilla" : "non-mozilla", hostname,
             staticFingerprints->mTestMode ? "test" : "production"));
  }

  return NS_OK;
}

nsresult PublicKeyPinningService::ChainHasValidPins(
    const RefPtr<nsNSSCertList>& certList, const char* hostname,
    mozilla::pkix::Time time, bool enforceTestMode,
    const OriginAttributes& originAttributes,
    /*out*/ bool& chainHasValidPins,
    /*optional out*/ PinningTelemetryInfo* pinningTelemetryInfo) {
  chainHasValidPins = false;
  if (!certList) {
    return NS_ERROR_INVALID_ARG;
  }
  if (!hostname || hostname[0] == 0) {
    return NS_ERROR_INVALID_ARG;
  }
  nsAutoCString canonicalizedHostname(CanonicalizeHostname(hostname));
  return CheckPinsForHostname(certList, canonicalizedHostname.get(),
                              enforceTestMode, time, originAttributes,
                              chainHasValidPins, pinningTelemetryInfo);
}

nsresult PublicKeyPinningService::HostHasPins(
    const char* hostname, mozilla::pkix::Time time, bool enforceTestMode,
    const OriginAttributes& originAttributes,
    /*out*/ bool& hostHasPins) {
  hostHasPins = false;
  nsAutoCString canonicalizedHostname(CanonicalizeHostname(hostname));
  nsTArray<nsCString> dynamicFingerprints;
  const TransportSecurityPreload* staticFingerprints = nullptr;
  nsresult rv = FindPinningInformation(canonicalizedHostname.get(), time,
                                       originAttributes, dynamicFingerprints,
                                       staticFingerprints);
  if (NS_FAILED(rv)) {
    return rv;
  }
  if (dynamicFingerprints.Length() > 0) {
    hostHasPins = true;
  } else if (staticFingerprints) {
    hostHasPins = !staticFingerprints->mTestMode || enforceTestMode;
  }
  return NS_OK;
}

nsAutoCString PublicKeyPinningService::CanonicalizeHostname(
    const char* hostname) {
  nsAutoCString canonicalizedHostname(hostname);
  ToLowerCase(canonicalizedHostname);
  while (canonicalizedHostname.Length() > 0 &&
         canonicalizedHostname.Last() == '.') {
    canonicalizedHostname.Truncate(canonicalizedHostname.Length() - 1);
  }
  return canonicalizedHostname;
}