Commit bac43587 authored by Franziskus Kiefer's avatar Franziskus Kiefer

Bug 1479787 - merge mozpkix from mozilla-central to NSS

--HG--
extra : rebase_source : bbfc60dfad29adf314d5728897a16f36fb156457
parents cfd5fcba 667b270e
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This code is made available to you under your choice of the following sets
* of licensing terms:
*/
/* 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/.
*/
/* Copyright 2013 Mozilla Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef mozilla_pkix_Input_h
#define mozilla_pkix_Input_h
#include <algorithm>
#include "pkix/Result.h"
#include "stdint.h"
namespace mozilla { namespace pkix {
class Reader;
// An Input is a safety-oriented immutable weak reference to a array of bytes
// of a known size. The data can only be legally accessed by constructing a
// Reader object, which guarantees all accesses to the data are memory safe.
// Neither Input not Reader provide any facilities for modifying the data
// they reference.
//
// Inputs are small and should usually be passed by value, not by reference,
// though for inline functions the distinction doesn't matter:
//
// Result GoodExample(Input input);
// Result BadExample(const Input& input);
// Result WorseExample(const uint8_t* input, size_t len);
//
// Note that in the example, GoodExample has the same performance
// characteristics as WorseExample, but with much better safety guarantees.
class Input final
{
public:
typedef uint16_t size_type;
// This constructor is useful for inputs that are statically known to be of a
// fixed size, e.g.:
//
// static const uint8_t EXPECTED_BYTES[] = { 0x00, 0x01, 0x02 };
// const Input expected(EXPECTED_BYTES);
//
// This is equivalent to (and preferred over):
//
// static const uint8_t EXPECTED_BYTES[] = { 0x00, 0x01, 0x02 };
// Input expected;
// Result rv = expected.Init(EXPECTED_BYTES, sizeof EXPECTED_BYTES);
template <size_type N>
explicit Input(const uint8_t (&aData)[N])
: data(aData)
, len(N)
{
}
// Construct a valid, empty, Init-able Input.
Input()
: data(nullptr)
, len(0u)
{
}
// This is intentionally not explicit in order to allow value semantics.
Input(const Input&) = default;
// Initialize the input. data must be non-null and len must be less than
// 65536. Init may not be called more than once.
Result Init(const uint8_t* aData, size_t aLen)
{
if (this->data) {
// already initialized
return Result::FATAL_ERROR_INVALID_ARGS;
}
if (!aData || aLen > 0xffffu) {
// input too large
return Result::ERROR_BAD_DER;
}
this->data = aData;
this->len = aLen;
return Success;
}
// Initialize the input to be equivalent to the given input. Init may not be
// called more than once.
//
// This is basically operator=, but it wasn't given that name because
// normally callers do not check the result of operator=, and normally
// operator= can be used multiple times.
Result Init(Input other)
{
return Init(other.data, other.len);
}
// Returns the length of the input.
//
// Having the return type be size_type instead of size_t avoids the need for
// callers to ensure that the result is small enough.
size_type GetLength() const { return static_cast<size_type>(len); }
// Don't use this. It is here because we have some "friend" functions that we
// don't want to declare in this header file.
const uint8_t* UnsafeGetData() const { return data; }
private:
const uint8_t* data;
size_t len;
void operator=(const Input&) = delete; // Use Init instead.
};
inline bool
InputsAreEqual(const Input& a, const Input& b)
{
return a.GetLength() == b.GetLength() &&
std::equal(a.UnsafeGetData(), a.UnsafeGetData() + a.GetLength(), b.UnsafeGetData());
}
// An Reader is a cursor/iterator through the contents of an Input, designed to
// maximize safety during parsing while minimizing the performance cost of that
// safety. In particular, all methods do strict bounds checking to ensure
// buffer overflows are impossible, and they are all inline so that the
// compiler can coalesce as many of those checks together as possible.
//
// In general, Reader allows for one byte of lookahead and no backtracking.
// However, the Match* functions internally may have more lookahead.
class Reader final
{
public:
Reader()
: input(nullptr)
, end(nullptr)
{
}
explicit Reader(Input aInput)
: input(aInput.UnsafeGetData())
, end(aInput.UnsafeGetData() + aInput.GetLength())
{
}
Result Init(Input aInput)
{
if (this->input) {
return Result::FATAL_ERROR_INVALID_ARGS;
}
this->input = aInput.UnsafeGetData();
this->end = aInput.UnsafeGetData() + aInput.GetLength();
return Success;
}
bool Peek(uint8_t expectedByte) const
{
return input < end && *input == expectedByte;
}
Result Read(uint8_t& out)
{
Result rv = EnsureLength(1);
if (rv != Success) {
return rv;
}
out = *input++;
return Success;
}
Result Read(uint16_t& out)
{
Result rv = EnsureLength(2);
if (rv != Success) {
return rv;
}
out = *input++;
out <<= 8u;
out |= *input++;
return Success;
}
template <Input::size_type N>
bool MatchRest(const uint8_t (&toMatch)[N])
{
// Normally we use EnsureLength which compares (input + len < end), but
// here we want to be sure that there is nothing following the matched
// bytes
if (static_cast<size_t>(end - input) != N) {
return false;
}
if (!std::equal(input, end, toMatch)) {
return false;
}
input = end;
return true;
}
bool MatchRest(Input toMatch)
{
// Normally we use EnsureLength which compares (input + len < end), but
// here we want to be sure that there is nothing following the matched
// bytes
size_t remaining = static_cast<size_t>(end - input);
if (toMatch.GetLength() != remaining) {
return false;
}
if (!std::equal(input, end, toMatch.UnsafeGetData())) {
return false;
}
input = end;
return true;
}
Result Skip(Input::size_type len)
{
Result rv = EnsureLength(len);
if (rv != Success) {
return rv;
}
input += len;
return Success;
}
Result Skip(Input::size_type len, Reader& skipped)
{
Result rv = EnsureLength(len);
if (rv != Success) {
return rv;
}
rv = skipped.Init(input, len);
if (rv != Success) {
return rv;
}
input += len;
return Success;
}
Result Skip(Input::size_type len, /*out*/ Input& skipped)
{
Result rv = EnsureLength(len);
if (rv != Success) {
return rv;
}
rv = skipped.Init(input, len);
if (rv != Success) {
return rv;
}
input += len;
return Success;
}
void SkipToEnd()
{
input = end;
}
Result SkipToEnd(/*out*/ Input& skipped)
{
return Skip(static_cast<Input::size_type>(end - input), skipped);
}
Result EnsureLength(Input::size_type len)
{
if (static_cast<size_t>(end - input) < len) {
return Result::ERROR_BAD_DER;
}
return Success;
}
bool AtEnd() const { return input == end; }
class Mark final
{
public:
Mark(const Mark&) = default; // Intentionally not explicit.
private:
friend class Reader;
Mark(const Reader& aInput, const uint8_t* aMark) : input(aInput), mark(aMark) { }
const Reader& input;
const uint8_t* const mark;
void operator=(const Mark&) = delete;
};
Mark GetMark() const { return Mark(*this, input); }
Result GetInput(const Mark& mark, /*out*/ Input& item)
{
if (&mark.input != this || mark.mark > input) {
return NotReached("invalid mark", Result::FATAL_ERROR_INVALID_ARGS);
}
return item.Init(mark.mark,
static_cast<Input::size_type>(input - mark.mark));
}
private:
Result Init(const uint8_t* data, Input::size_type len)
{
if (input) {
// already initialized
return Result::FATAL_ERROR_INVALID_ARGS;
}
input = data;
end = data + len;
return Success;
}
const uint8_t* input;
const uint8_t* end;
Reader(const Reader&) = delete;
void operator=(const Reader&) = delete;
};
inline bool
InputContains(const Input& input, uint8_t toFind)
{
Reader reader(input);
for (;;) {
uint8_t b;
if (reader.Read(b) != Success) {
return false;
}
if (b == toFind) {
return true;
}
}
}
} } // namespace mozilla::pkix
#endif // mozilla_pkix_Input_h
This diff is collapsed.
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This code is made available to you under your choice of the following sets
* of licensing terms:
*/
/* 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/.
*/
/* Copyright 2014 Mozilla Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef mozilla_pkix_Time_h
#define mozilla_pkix_Time_h
#include <ctime>
#include <limits>
#include <stdint.h>
#include "pkix/Result.h"
namespace mozilla { namespace pkix {
// Time with a range from the first second of year 0 (AD) through at least the
// last second of year 9999, which is the range of legal times in X.509 and
// OCSP. This type has second-level precision. The time zone is always UTC.
//
// Pass by value, not by reference.
class Time final
{
public:
// Construct an uninitialized instance.
//
// This will fail to compile because there is no default constructor:
// Time x;
//
// This will succeed, leaving the time uninitialized:
// Time x(Time::uninitialized);
enum Uninitialized { uninitialized };
explicit Time(Uninitialized) { }
bool operator==(const Time& other) const
{
return elapsedSecondsAD == other.elapsedSecondsAD;
}
bool operator>(const Time& other) const
{
return elapsedSecondsAD > other.elapsedSecondsAD;
}
bool operator>=(const Time& other) const
{
return elapsedSecondsAD >= other.elapsedSecondsAD;
}
bool operator<(const Time& other) const
{
return elapsedSecondsAD < other.elapsedSecondsAD;
}
bool operator<=(const Time& other) const
{
return elapsedSecondsAD <= other.elapsedSecondsAD;
}
Result AddSeconds(uint64_t seconds)
{
if (std::numeric_limits<uint64_t>::max() - elapsedSecondsAD
< seconds) {
return Result::FATAL_ERROR_INVALID_ARGS; // integer overflow
}
elapsedSecondsAD += seconds;
return Success;
}
Result SubtractSeconds(uint64_t seconds)
{
if (seconds > elapsedSecondsAD) {
return Result::FATAL_ERROR_INVALID_ARGS; // integer overflow
}
elapsedSecondsAD -= seconds;
return Success;
}
static const uint64_t ONE_DAY_IN_SECONDS
= UINT64_C(24) * UINT64_C(60) * UINT64_C(60);
private:
// This constructor is hidden to prevent accidents like this:
//
// Time foo(time_t t)
// {
// // WRONG! 1970-01-01-00:00:00 == time_t(0), but not Time(0)!
// return Time(t);
// }
explicit Time(uint64_t aElapsedSecondsAD)
: elapsedSecondsAD(aElapsedSecondsAD)
{
}
friend Time TimeFromElapsedSecondsAD(uint64_t);
friend class Duration;
uint64_t elapsedSecondsAD;
};
inline Time TimeFromElapsedSecondsAD(uint64_t aElapsedSecondsAD)
{
return Time(aElapsedSecondsAD);
}
Time Now();
// Note the epoch is the unix epoch (ie 00:00:00 UTC, 1 January 1970)
Time TimeFromEpochInSeconds(uint64_t secondsSinceEpoch);
class Duration final
{
public:
Duration(Time timeA, Time timeB)
: durationInSeconds(timeA < timeB
? timeB.elapsedSecondsAD - timeA.elapsedSecondsAD
: timeA.elapsedSecondsAD - timeB.elapsedSecondsAD)
{
}
explicit Duration(uint64_t aDurationInSeconds)
: durationInSeconds(aDurationInSeconds)
{
}
bool operator>(const Duration& other) const
{
return durationInSeconds > other.durationInSeconds;
}
bool operator<(const Duration& other) const
{
return durationInSeconds < other.durationInSeconds;
}
private:
uint64_t durationInSeconds;
};
} } // namespace mozilla::pkix
#endif // mozilla_pkix_Time_h
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This code is made available to you under your choice of the following sets
* of licensing terms:
*/
/* 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/.
*/
/* Copyright 2013 Mozilla Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef mozilla_pkix_pkix_h
#define mozilla_pkix_pkix_h
#include "pkixtypes.h"
namespace mozilla { namespace pkix {
// ----------------------------------------------------------------------------
// LIMITED SUPPORT FOR CERTIFICATE POLICIES
//
// If SEC_OID_X509_ANY_POLICY is passed as the value of the requiredPolicy
// parameter then all policy validation will be skipped. Otherwise, path
// building and validation will be done for the given policy.
//
// In RFC 5280 terms:
//
// * user-initial-policy-set = { requiredPolicy }.
// * initial-explicit-policy = true
// * initial-any-policy-inhibit = false
//
// We allow intermediate cerificates to use this extension but since
// we do not process the inhibit anyPolicy extesion we will fail if this
// extension is present. TODO(bug 989051)
// Because we force explicit policy and because we prohibit policy mapping, we
// do not bother processing the policy mapping, or policy constraint.
//
// ----------------------------------------------------------------------------
// ERROR RANKING
//
// BuildCertChain prioritizes certain checks ahead of others so that when a
// certificate chain has multiple errors, the "most serious" error is
// returned. In practice, this ranking of seriousness is tied directly to how
// Firefox's certificate error override mechanism.
//
// The ranking is:
//
// 1. Active distrust (Result::ERROR_UNTRUSTED_CERT).
// 2. Problems with issuer-independent properties for CA certificates.
// 3. Unknown issuer (Result::ERROR_UNKNOWN_ISSUER).
// 4. Problems with issuer-independent properties for EE certificates.
// 5. Revocation.
//
// In particular, if BuildCertChain returns Result::ERROR_UNKNOWN_ISSUER then
// the caller can call CERT_CheckCertValidTimes to determine if the certificate
// is ALSO expired.
//
// It would be better if revocation were prioritized above expiration and
// unknown issuer. However, it is impossible to do revocation checking without
// knowing the issuer, since the issuer information is needed to validate the
// revocation information. Also, generally revocation checking only works
// during the validity period of the certificate.
//
// In general, when path building fails, BuildCertChain will return
// Result::ERROR_UNKNOWN_ISSUER. However, if all attempted paths resulted in
// the same error (which is trivially true when there is only one potential
// path), more specific errors will be returned.
//
// ----------------------------------------------------------------------------
// Meanings of specific error codes can be found in Result.h
// This function attempts to find a trustworthy path from the supplied
// certificate to a trust anchor. In the event that no trusted path is found,
// the method returns an error result; the error ranking is described above.
//
// Parameters:
// time:
// Timestamp for which the chain should be valid; this is useful to
// analyze whether a record was trustworthy when it was made.
// requiredKeyUsageIfPresent:
// What key usage bits must be set, if the extension is present at all,
// to be considered a valid chain. Multiple values should be OR'd
// together. If you don't want to specify anything, use
// KeyUsage::noParticularKeyUsageRequired.
// requiredEKUIfPresent:
// What extended key usage bits must be set, if the EKU extension
// exists, to be considered a valid chain. Multiple values should be
// OR'd together. If you don't want to specify anything, use
// KeyPurposeId::anyExtendedKeyUsage.
// requiredPolicy:
// This is the policy to apply; typically included in EV certificates.
// If there is no policy, pass in CertPolicyId::anyPolicy.
Result BuildCertChain(TrustDomain& trustDomain, Input cert,
Time time, EndEntityOrCA endEntityOrCA,
KeyUsage requiredKeyUsageIfPresent,
KeyPurposeId requiredEKUIfPresent,
const CertPolicyId& requiredPolicy,
/*optional*/ const Input* stapledOCSPResponse);
// Verify that the given end-entity cert, which is assumed to have been already
// validated with BuildCertChain, is valid for the given hostname. The matching
// function attempts to implement RFC 6125 with a couple of differences:
// - IP addresses are out of scope of RFC 6125, but this method accepts them for
// backward compatibility (see SearchNames in pkixnames.cpp)
// - A wildcard in a DNS-ID may only appear as the entirety of the first label.
Result CheckCertHostname(Input cert, Input hostname,
NameMatchingPolicy& nameMatchingPolicy);
// Construct an RFC-6960-encoded OCSP request, ready for submission to a
// responder, for the provided CertID. The request has no extensions.
static const size_t OCSP_REQUEST_MAX_LENGTH = 127;
Result CreateEncodedOCSPRequest(TrustDomain& trustDomain,
const CertID& certID,
/*out*/ uint8_t (&out)[OCSP_REQUEST_MAX_LENGTH],
/*out*/ size_t& outLen);
// The out parameter expired will be true if the response has expired. If the
// response also indicates a revoked or unknown certificate, that error
// will be returned. Otherwise, Result::ERROR_OCSP_OLD_RESPONSE will be
// returned for an expired response.
//
// The optional parameter thisUpdate will be the thisUpdate value of
// the encoded response if it is considered trustworthy. Only
// good, unknown, or revoked responses that verify correctly are considered
// trustworthy. If the response is not trustworthy, thisUpdate will be 0.
// Similarly, the optional parameter validThrough will be the time through
// which the encoded response is considered trustworthy (that is, as long as
// the given time at which to validate is less than or equal to validThrough,
// the response will be considered trustworthy).
Result VerifyEncodedOCSPResponse(TrustDomain& trustDomain,
const CertID& certID, Time time,
uint16_t maxLifetimeInDays,
Input encodedResponse,
/* out */ bool& expired,
/* optional out */ Time* thisUpdate = nullptr,
/* optional out */ Time* validThrough = nullptr);
// Check that the TLSFeature extensions in a given end-entity cert (which is
// assumed to have been already validated with BuildCertChain) are satisfied.
// The only feature which we cancurrently process a requirement for is
// status_request (OCSP stapling) so we reject any extension that specifies a
// requirement for another value. Empty extensions are also rejected.
Result CheckTLSFeaturesAreSatisfied(Input& cert,
const Input* stapledOCSPResponse);
} } // namespace mozilla::pkix
#endif // mozilla_pkix_pkix_h
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This code is made available to you under your choice of the following sets
* of licensing terms:
*/
/* 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/.
*/
/* Copyright 2013 Mozilla Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef mozilla_pkix_pkixnss_h
#define mozilla_pkix_pkixnss_h
#include "pkixtypes.h"
#include "prerror.h"
#include "seccomon.h"
namespace mozilla { namespace pkix {
// Verifies the PKCS#1.5 signature on the given data using the given RSA public
// key.
Result VerifyRSAPKCS1SignedDigestNSS(const SignedDigest& sd,
Input subjectPublicKeyInfo,
void* pkcs11PinArg);
// Verifies the ECDSA signature on the given data using the given ECC public
// key.
Result VerifyECDSASignedDigestNSS(const SignedDigest& sd,
Input subjectPublicKeyInfo,
void* pkcs11PinArg);
// Computes the digest of the given data using the given digest algorithm.
//
// item contains the data to hash.
// digestBuf must point to a buffer to where the digest will be written.
// digestBufLen must be the size of the buffer, which must be exactly equal
// to the size of the digest output (20 for SHA-1, 32 for SHA-256,
// etc.)
//
// TODO: Taking the output buffer as (uint8_t*, size_t) is counter to our
// other, extensive, memory safety efforts in mozilla::pkix, and we should find
// a way to provide a more-obviously-safe interface.
Result DigestBufNSS(Input item,