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
|
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_CERT_X509_CERTIFICATE_H_
#define NET_CERT_X509_CERTIFICATE_H_
#include <stddef.h>
#include <string.h>
#include <string>
#include <string_view>
#include <vector>
#include "base/containers/span.h"
#include "base/gtest_prod_util.h"
#include "base/memory/ref_counted.h"
#include "base/time/time.h"
#include "net/base/hash_value.h"
#include "net/base/net_export.h"
#include "net/cert/x509_cert_types.h"
#include "third_party/boringssl/src/include/openssl/base.h"
namespace base {
class Pickle;
class PickleIterator;
}
namespace net {
class X509Certificate;
typedef std::vector<scoped_refptr<X509Certificate> > CertificateList;
// A X.509 certificate represents a particular identity or end-entity
// certificate, such as an SSL server identity or an SSL client certificate. An
// X509Certificate contains this leaf certificate accessible via cert_buffer().
// An X509Certificate may also contain 0 or more intermediary X.509 certificates
// that are used to build a path to a root certificate. These are accessed via
// intermediate_buffers().
class NET_EXPORT X509Certificate
: public base::RefCountedThreadSafe<X509Certificate> {
public:
enum PublicKeyType {
kPublicKeyTypeUnknown,
kPublicKeyTypeRSA,
kPublicKeyTypeECDSA,
};
enum Format {
// The data contains a single DER-encoded certificate, or a PEM-encoded
// DER certificate with the PEM encoding block name of "CERTIFICATE".
// Any subsequent blocks will be ignored.
FORMAT_SINGLE_CERTIFICATE = 1 << 0,
// The data contains a sequence of one or more PEM-encoded, DER
// certificates, with the PEM encoding block name of "CERTIFICATE".
// All PEM blocks will be parsed, until the first error is encountered.
FORMAT_PEM_CERT_SEQUENCE = 1 << 1,
// The data contains a PKCS#7 SignedData structure, whose certificates
// member is to be used to initialize the certificate and intermediates.
// The data may further be encoded using PEM, specifying block names of
// either "PKCS7" or "CERTIFICATE".
FORMAT_PKCS7 = 1 << 2,
// Automatically detect the format.
FORMAT_AUTO = FORMAT_SINGLE_CERTIFICATE | FORMAT_PEM_CERT_SEQUENCE |
FORMAT_PKCS7,
};
// Create an X509Certificate from a CRYPTO_BUFFER containing the DER-encoded
// representation. Returns NULL on failure to parse or extract data from the
// the certificate. Note that this does not guarantee the certificate is
// fully parsed and validated, only that the members of this class, such as
// subject, issuer, expiry times, and serial number, could be successfully
// initialized from the certificate.
static scoped_refptr<X509Certificate> CreateFromBuffer(
bssl::UniquePtr<CRYPTO_BUFFER> cert_buffer,
std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates);
// Options for configuring certificate parsing.
// Do not use without consulting //net owners.
struct UnsafeCreateOptions {
bool printable_string_is_utf8 = false;
};
// Create an X509Certificate with non-standard parsing options.
// Do not use without consulting //net owners.
static scoped_refptr<X509Certificate> CreateFromBufferUnsafeOptions(
bssl::UniquePtr<CRYPTO_BUFFER> cert_buffer,
std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates,
UnsafeCreateOptions options);
// Create an X509Certificate from a chain of DER encoded certificates. The
// first certificate in the chain is the end-entity certificate to which a
// handle is returned. The other certificates in the chain are intermediate
// certificates.
static scoped_refptr<X509Certificate> CreateFromDERCertChain(
const std::vector<std::string_view>& der_certs);
// Create an X509Certificate from a chain of DER encoded certificates with
// non-standard parsing options.
// Do not use without consulting //net owners.
static scoped_refptr<X509Certificate> CreateFromDERCertChainUnsafeOptions(
const std::vector<std::string_view>& der_certs,
UnsafeCreateOptions options);
// Create an X509Certificate from the DER-encoded representation.
// Returns NULL on failure.
static scoped_refptr<X509Certificate> CreateFromBytes(
base::span<const uint8_t> data);
// Create an X509Certificate with non-standard parsing options.
// Do not use without consulting //net owners.
static scoped_refptr<X509Certificate> CreateFromBytesUnsafeOptions(
base::span<const uint8_t> data,
UnsafeCreateOptions options);
// Create an X509Certificate from the representation stored in the given
// pickle. The data for this object is found relative to the given
// pickle_iter, which should be passed to the pickle's various Read* methods.
// Returns NULL on failure.
static scoped_refptr<X509Certificate> CreateFromPickle(
base::PickleIterator* pickle_iter);
// Create an X509Certificate from the representation stored in the given
// pickle with non-standard parsing options.
// Do not use without consulting //net owners.
static scoped_refptr<X509Certificate> CreateFromPickleUnsafeOptions(
base::PickleIterator* pickle_iter,
UnsafeCreateOptions options);
// Parses all of the certificates possible from |data|. |format| is a
// bit-wise OR of Format, indicating the possible formats the
// certificates may have been serialized as. If an error occurs, an empty
// collection will be returned.
static CertificateList CreateCertificateListFromBytes(
base::span<const uint8_t> data,
int format);
// Return a X509Certificate object representing the same certificate but
// with a different set of intermediates. If |intermediates| are the same as
// |intermediate_ca_certs_|, it will return a reference to the same
// X509Certificate object rather than cloning.
scoped_refptr<X509Certificate> CloneWithDifferentIntermediates(
std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates);
X509Certificate(const X509Certificate&) = delete;
X509Certificate& operator=(const X509Certificate&) = delete;
// Appends a representation of this object to the given pickle.
// The Pickle contains the certificate and any certificates that were
// stored in |intermediate_ca_certs_| at the time it was serialized.
// The format is [int count], [data - this certificate],
// [data - intermediate1], ... [data - intermediateN].
// All certificates are stored in DER form.
void Persist(base::Pickle* pickle) const;
// The serial number, DER encoded, possibly including a leading 00 byte.
const std::string& serial_number() const { return parsed_.serial_number_; }
// The subject of the certificate. For HTTPS server certificates, this
// represents the web server. The common name of the subject should match
// the host name of the web server.
const CertPrincipal& subject() const { return parsed_.subject_; }
// The issuer of the certificate.
const CertPrincipal& issuer() const { return parsed_.issuer_; }
// Time period during which the certificate is valid. More precisely, this
// certificate is invalid before the |valid_start| date and invalid after
// the |valid_expiry| date.
// If we were unable to parse either date from the certificate (or if the cert
// lacks either date), the date will be null (i.e., is_null() will be true).
const base::Time& valid_start() const { return parsed_.valid_start_; }
const base::Time& valid_expiry() const { return parsed_.valid_expiry_; }
// Gets the subjectAltName extension field from the certificate, if any.
// For future extension; currently this only returns those name types that
// are required for HTTP certificate name verification - see VerifyHostname.
// Returns true if any dNSName or iPAddress SAN was present. If |dns_names|
// is non-null, it will be set to all dNSNames present. If |ip_addrs| is
// non-null, it will be set to all iPAddresses present.
bool GetSubjectAltName(std::vector<std::string>* dns_names,
std::vector<std::string>* ip_addrs) const;
// Convenience method that returns whether this certificate has expired as of
// now.
bool HasExpired() const;
// Returns true if this object and |other| represent the same certificate.
// Does not consider any associated intermediates.
bool EqualsExcludingChain(const X509Certificate* other) const;
// Returns true if this object and |other| represent the same certificate
// and intermediates.
bool EqualsIncludingChain(const X509Certificate* other) const;
// Do any of the given issuer names appear in this cert's chain of trust?
// |valid_issuers| is a list of DER-encoded X.509 DistinguishedNames.
bool IsIssuedByEncoded(const std::vector<std::string>& valid_issuers) const;
// Verifies that |hostname| matches this certificate.
// Does not verify that the certificate is valid, only that the certificate
// matches this host.
bool VerifyNameMatch(std::string_view hostname) const;
// Returns the PEM encoded data from a DER encoded certificate. If the
// return value is true, then the PEM encoded certificate is written to
// |pem_encoded|.
static bool GetPEMEncodedFromDER(std::string_view der_encoded,
std::string* pem_encoded);
// Returns the PEM encoded data from a CRYPTO_BUFFER. If the return value is
// true, then the PEM encoded certificate is written to |pem_encoded|.
static bool GetPEMEncoded(const CRYPTO_BUFFER* cert_buffer,
std::string* pem_encoded);
// Encodes the entire certificate chain (this certificate and any
// intermediate certificates stored in |intermediate_ca_certs_|) as a series
// of PEM encoded strings. Returns true if all certificates were encoded,
// storing the result in |*pem_encoded|, with this certificate stored as
// the first element.
bool GetPEMEncodedChain(std::vector<std::string>* pem_encoded) const;
// Sets |*size_bits| to be the length of the public key in bits, and sets
// |*type| to one of the |PublicKeyType| values. In case of
// |kPublicKeyTypeUnknown|, |*size_bits| will be set to 0.
static void GetPublicKeyInfo(const CRYPTO_BUFFER* cert_buffer,
size_t* size_bits,
PublicKeyType* type);
// Returns the bytes in CRYPTO_BUFFER that hold this certificate's DER encoded
// data. The data is not guaranteed to be valid DER or to encode a valid
// Certificate object.
base::span<const uint8_t> cert_span() const;
// Returns the CRYPTO_BUFFER holding this certificate's DER encoded data. The
// data is not guaranteed to be valid DER or to encode a valid Certificate
// object.
//
// To access the CRYPTO_BUFFER's bytes, use `cert_span()` above.
CRYPTO_BUFFER* cert_buffer() const { return cert_buffer_.get(); }
// Returns the associated intermediate certificates that were specified
// during creation of this object, if any. The intermediates are not
// guaranteed to be valid DER or to encode valid Certificate objects.
// Ownership follows the "get" rule: it is the caller's responsibility to
// retain the elements of the result.
const std::vector<bssl::UniquePtr<CRYPTO_BUFFER>>& intermediate_buffers()
const {
return intermediate_ca_certs_;
}
// Creates all possible CRYPTO_BUFFERs from |data| encoded in a specific
// |format|. Returns an empty collection on failure.
static std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> CreateCertBuffersFromBytes(
base::span<const uint8_t> data,
Format format);
// Calculates the SHA-256 fingerprint of the certificate. Returns an empty
// (all zero) fingerprint on failure.
static SHA256HashValue CalculateFingerprint256(
const CRYPTO_BUFFER* cert_buffer);
// Calculates the SHA-256 fingerprint for the complete chain, including the
// leaf certificate and all intermediate CA certificates. Returns an empty
// (all zero) fingerprint on failure.
SHA256HashValue CalculateChainFingerprint256() const;
// Returns true if the certificate is self-signed.
static bool IsSelfSigned(CRYPTO_BUFFER* cert_buffer);
private:
friend class base::RefCountedThreadSafe<X509Certificate>;
friend class TestRootCerts; // For unit tests
FRIEND_TEST_ALL_PREFIXES(X509CertificateNameVerifyTest, VerifyHostname);
FRIEND_TEST_ALL_PREFIXES(X509CertificateTest, SerialNumbers);
class ParsedFields {
public:
ParsedFields();
ParsedFields(const ParsedFields&);
ParsedFields(ParsedFields&&);
~ParsedFields();
bool Initialize(const CRYPTO_BUFFER* cert_buffer,
UnsafeCreateOptions options);
// The subject of the certificate.
CertPrincipal subject_;
// The issuer of the certificate.
CertPrincipal issuer_;
// This certificate is not valid before |valid_start_|
base::Time valid_start_;
// This certificate is not valid after |valid_expiry_|
base::Time valid_expiry_;
// The serial number of this certificate, DER encoded.
std::string serial_number_;
};
// Construct an X509Certificate from a CRYPTO_BUFFER containing the
// DER-encoded representation.
X509Certificate(ParsedFields parsed,
bssl::UniquePtr<CRYPTO_BUFFER> cert_buffer,
std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates);
// Copy |other|, except with a different set of intermediates.
X509Certificate(const X509Certificate& other,
std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates);
~X509Certificate();
// Verifies that |hostname| matches one of the certificate names or IP
// addresses supplied, based on TLS name matching rules - specifically,
// following http://tools.ietf.org/html/rfc6125.
// The members of |cert_san_dns_names| and |cert_san_ipaddrs| must be filled
// from the dNSName and iPAddress components of the subject alternative name
// extension, if present. Note these IP addresses are NOT ascii-encoded:
// they must be 4 or 16 bytes of network-ordered data, for IPv4 and IPv6
// addresses, respectively.
static bool VerifyHostname(std::string_view hostname,
const std::vector<std::string>& cert_san_dns_names,
const std::vector<std::string>& cert_san_ip_addrs);
// Fields that were parsed from |cert_buffer_|.
const ParsedFields parsed_;
// A handle to the DER encoded certificate data.
const bssl::UniquePtr<CRYPTO_BUFFER> cert_buffer_;
// Untrusted intermediate certificates associated with this certificate
// that may be needed for chain building.
const std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediate_ca_certs_;
};
} // namespace net
#endif // NET_CERT_X509_CERTIFICATE_H_
|