x509_certificate.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. #ifndef NET_CERT_X509_CERTIFICATE_H_
  5. #define NET_CERT_X509_CERTIFICATE_H_
  6. #include <stddef.h>
  7. #include <string.h>
  8. #include <string>
  9. #include <vector>
  10. #include "base/containers/span.h"
  11. #include "base/gtest_prod_util.h"
  12. #include "base/memory/ref_counted.h"
  13. #include "base/strings/string_piece.h"
  14. #include "base/time/time.h"
  15. #include "net/base/hash_value.h"
  16. #include "net/base/net_export.h"
  17. #include "net/cert/x509_cert_types.h"
  18. #include "third_party/boringssl/src/include/openssl/base.h"
  19. namespace base {
  20. class Pickle;
  21. class PickleIterator;
  22. }
  23. namespace net {
  24. class X509Certificate;
  25. typedef std::vector<scoped_refptr<X509Certificate> > CertificateList;
  26. // A X.509 certificate represents a particular identity or end-entity
  27. // certificate, such as an SSL server identity or an SSL client certificate. An
  28. // X509Certificate contains this leaf certificate accessible via cert_buffer().
  29. // An X509Certificate may also contain 0 or more intermediary X.509 certificates
  30. // that are used to build a path to a root certificate. These are accessed via
  31. // intermediate_buffers().
  32. class NET_EXPORT X509Certificate
  33. : public base::RefCountedThreadSafe<X509Certificate> {
  34. public:
  35. enum PublicKeyType {
  36. kPublicKeyTypeUnknown,
  37. kPublicKeyTypeRSA,
  38. kPublicKeyTypeDSA,
  39. kPublicKeyTypeECDSA,
  40. kPublicKeyTypeDH,
  41. kPublicKeyTypeECDH
  42. };
  43. enum Format {
  44. // The data contains a single DER-encoded certificate, or a PEM-encoded
  45. // DER certificate with the PEM encoding block name of "CERTIFICATE".
  46. // Any subsequent blocks will be ignored.
  47. FORMAT_SINGLE_CERTIFICATE = 1 << 0,
  48. // The data contains a sequence of one or more PEM-encoded, DER
  49. // certificates, with the PEM encoding block name of "CERTIFICATE".
  50. // All PEM blocks will be parsed, until the first error is encountered.
  51. FORMAT_PEM_CERT_SEQUENCE = 1 << 1,
  52. // The data contains a PKCS#7 SignedData structure, whose certificates
  53. // member is to be used to initialize the certificate and intermediates.
  54. // The data may further be encoded using PEM, specifying block names of
  55. // either "PKCS7" or "CERTIFICATE".
  56. FORMAT_PKCS7 = 1 << 2,
  57. // Automatically detect the format.
  58. FORMAT_AUTO = FORMAT_SINGLE_CERTIFICATE | FORMAT_PEM_CERT_SEQUENCE |
  59. FORMAT_PKCS7,
  60. };
  61. // Create an X509Certificate from a CRYPTO_BUFFER containing the DER-encoded
  62. // representation. Returns NULL on failure to parse or extract data from the
  63. // the certificate. Note that this does not guarantee the certificate is
  64. // fully parsed and validated, only that the members of this class, such as
  65. // subject, issuer, expiry times, and serial number, could be successfully
  66. // initialized from the certificate.
  67. static scoped_refptr<X509Certificate> CreateFromBuffer(
  68. bssl::UniquePtr<CRYPTO_BUFFER> cert_buffer,
  69. std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates);
  70. // Options for configuring certificate parsing.
  71. // Do not use without consulting //net owners.
  72. struct UnsafeCreateOptions {
  73. bool printable_string_is_utf8 = false;
  74. };
  75. // Create an X509Certificate with non-standard parsing options.
  76. // Do not use without consulting //net owners.
  77. static scoped_refptr<X509Certificate> CreateFromBufferUnsafeOptions(
  78. bssl::UniquePtr<CRYPTO_BUFFER> cert_buffer,
  79. std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates,
  80. UnsafeCreateOptions options);
  81. // Create an X509Certificate from a chain of DER encoded certificates. The
  82. // first certificate in the chain is the end-entity certificate to which a
  83. // handle is returned. The other certificates in the chain are intermediate
  84. // certificates.
  85. static scoped_refptr<X509Certificate> CreateFromDERCertChain(
  86. const std::vector<base::StringPiece>& der_certs);
  87. // Create an X509Certificate from a chain of DER encoded certificates with
  88. // non-standard parsing options.
  89. // Do not use without consulting //net owners.
  90. static scoped_refptr<X509Certificate> CreateFromDERCertChainUnsafeOptions(
  91. const std::vector<base::StringPiece>& der_certs,
  92. UnsafeCreateOptions options);
  93. // Create an X509Certificate from the DER-encoded representation.
  94. // Returns NULL on failure.
  95. static scoped_refptr<X509Certificate> CreateFromBytes(
  96. base::span<const uint8_t> data);
  97. // Create an X509Certificate with non-standard parsing options.
  98. // Do not use without consulting //net owners.
  99. static scoped_refptr<X509Certificate> CreateFromBytesUnsafeOptions(
  100. base::span<const uint8_t> data,
  101. UnsafeCreateOptions options);
  102. // Create an X509Certificate from the representation stored in the given
  103. // pickle. The data for this object is found relative to the given
  104. // pickle_iter, which should be passed to the pickle's various Read* methods.
  105. // Returns NULL on failure.
  106. static scoped_refptr<X509Certificate> CreateFromPickle(
  107. base::PickleIterator* pickle_iter);
  108. // Create an X509Certificate from the representation stored in the given
  109. // pickle with non-standard parsing options.
  110. // Do not use without consulting //net owners.
  111. static scoped_refptr<X509Certificate> CreateFromPickleUnsafeOptions(
  112. base::PickleIterator* pickle_iter,
  113. UnsafeCreateOptions options);
  114. // Parses all of the certificates possible from |data|. |format| is a
  115. // bit-wise OR of Format, indicating the possible formats the
  116. // certificates may have been serialized as. If an error occurs, an empty
  117. // collection will be returned.
  118. static CertificateList CreateCertificateListFromBytes(
  119. base::span<const uint8_t> data,
  120. int format);
  121. X509Certificate(const X509Certificate&) = delete;
  122. X509Certificate& operator=(const X509Certificate&) = delete;
  123. // Appends a representation of this object to the given pickle.
  124. // The Pickle contains the certificate and any certificates that were
  125. // stored in |intermediate_ca_certs_| at the time it was serialized.
  126. // The format is [int count], [data - this certificate],
  127. // [data - intermediate1], ... [data - intermediateN].
  128. // All certificates are stored in DER form.
  129. void Persist(base::Pickle* pickle) const;
  130. // The serial number, DER encoded, possibly including a leading 00 byte.
  131. const std::string& serial_number() const { return serial_number_; }
  132. // The subject of the certificate. For HTTPS server certificates, this
  133. // represents the web server. The common name of the subject should match
  134. // the host name of the web server.
  135. const CertPrincipal& subject() const { return subject_; }
  136. // The issuer of the certificate.
  137. const CertPrincipal& issuer() const { return issuer_; }
  138. // Time period during which the certificate is valid. More precisely, this
  139. // certificate is invalid before the |valid_start| date and invalid after
  140. // the |valid_expiry| date.
  141. // If we were unable to parse either date from the certificate (or if the cert
  142. // lacks either date), the date will be null (i.e., is_null() will be true).
  143. const base::Time& valid_start() const { return valid_start_; }
  144. const base::Time& valid_expiry() const { return valid_expiry_; }
  145. // Gets the subjectAltName extension field from the certificate, if any.
  146. // For future extension; currently this only returns those name types that
  147. // are required for HTTP certificate name verification - see VerifyHostname.
  148. // Returns true if any dNSName or iPAddress SAN was present. If |dns_names|
  149. // is non-null, it will be set to all dNSNames present. If |ip_addrs| is
  150. // non-null, it will be set to all iPAddresses present.
  151. bool GetSubjectAltName(std::vector<std::string>* dns_names,
  152. std::vector<std::string>* ip_addrs) const;
  153. // Convenience method that returns whether this certificate has expired as of
  154. // now.
  155. bool HasExpired() const;
  156. // Returns true if this object and |other| represent the same certificate.
  157. // Does not consider any associated intermediates.
  158. bool EqualsExcludingChain(const X509Certificate* other) const;
  159. // Returns true if this object and |other| represent the same certificate
  160. // and intermediates.
  161. bool EqualsIncludingChain(const X509Certificate* other) const;
  162. // Do any of the given issuer names appear in this cert's chain of trust?
  163. // |valid_issuers| is a list of DER-encoded X.509 DistinguishedNames.
  164. bool IsIssuedByEncoded(const std::vector<std::string>& valid_issuers) const;
  165. // Verifies that |hostname| matches this certificate.
  166. // Does not verify that the certificate is valid, only that the certificate
  167. // matches this host.
  168. bool VerifyNameMatch(const std::string& hostname) const;
  169. // Returns the PEM encoded data from a DER encoded certificate. If the
  170. // return value is true, then the PEM encoded certificate is written to
  171. // |pem_encoded|.
  172. static bool GetPEMEncodedFromDER(base::StringPiece der_encoded,
  173. std::string* pem_encoded);
  174. // Returns the PEM encoded data from a CRYPTO_BUFFER. If the return value is
  175. // true, then the PEM encoded certificate is written to |pem_encoded|.
  176. static bool GetPEMEncoded(const CRYPTO_BUFFER* cert_buffer,
  177. std::string* pem_encoded);
  178. // Encodes the entire certificate chain (this certificate and any
  179. // intermediate certificates stored in |intermediate_ca_certs_|) as a series
  180. // of PEM encoded strings. Returns true if all certificates were encoded,
  181. // storing the result in |*pem_encoded|, with this certificate stored as
  182. // the first element.
  183. bool GetPEMEncodedChain(std::vector<std::string>* pem_encoded) const;
  184. // Sets |*size_bits| to be the length of the public key in bits, and sets
  185. // |*type| to one of the |PublicKeyType| values. In case of
  186. // |kPublicKeyTypeUnknown|, |*size_bits| will be set to 0.
  187. static void GetPublicKeyInfo(const CRYPTO_BUFFER* cert_buffer,
  188. size_t* size_bits,
  189. PublicKeyType* type);
  190. // Returns the CRYPTO_BUFFER holding this certificate's DER encoded data. The
  191. // data is not guaranteed to be valid DER or to encode a valid Certificate
  192. // object.
  193. CRYPTO_BUFFER* cert_buffer() const { return cert_buffer_.get(); }
  194. // Returns the associated intermediate certificates that were specified
  195. // during creation of this object, if any. The intermediates are not
  196. // guaranteed to be valid DER or to encode valid Certificate objects.
  197. // Ownership follows the "get" rule: it is the caller's responsibility to
  198. // retain the elements of the result.
  199. const std::vector<bssl::UniquePtr<CRYPTO_BUFFER>>& intermediate_buffers()
  200. const {
  201. return intermediate_ca_certs_;
  202. }
  203. // Creates a CRYPTO_BUFFER from the DER-encoded representation. Unlike
  204. // creating a CRYPTO_BUFFER directly, this function does some minimal
  205. // checking to reject obviously invalid inputs.
  206. // Returns NULL on failure.
  207. static bssl::UniquePtr<CRYPTO_BUFFER> CreateCertBufferFromBytes(
  208. base::span<const uint8_t> data);
  209. // Creates all possible CRYPTO_BUFFERs from |data| encoded in a specific
  210. // |format|. Returns an empty collection on failure.
  211. static std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> CreateCertBuffersFromBytes(
  212. base::span<const uint8_t> data,
  213. Format format);
  214. // Calculates the SHA-256 fingerprint of the certificate. Returns an empty
  215. // (all zero) fingerprint on failure.
  216. static SHA256HashValue CalculateFingerprint256(
  217. const CRYPTO_BUFFER* cert_buffer);
  218. // Calculates the SHA-256 fingerprint for the complete chain, including the
  219. // leaf certificate and all intermediate CA certificates. Returns an empty
  220. // (all zero) fingerprint on failure.
  221. SHA256HashValue CalculateChainFingerprint256() const;
  222. // Returns true if the certificate is self-signed.
  223. static bool IsSelfSigned(const CRYPTO_BUFFER* cert_buffer);
  224. private:
  225. friend class base::RefCountedThreadSafe<X509Certificate>;
  226. friend class TestRootCerts; // For unit tests
  227. FRIEND_TEST_ALL_PREFIXES(X509CertificateNameVerifyTest, VerifyHostname);
  228. FRIEND_TEST_ALL_PREFIXES(X509CertificateTest, SerialNumbers);
  229. // Construct an X509Certificate from a CRYPTO_BUFFER containing the
  230. // DER-encoded representation.
  231. X509Certificate(bssl::UniquePtr<CRYPTO_BUFFER> cert_buffer,
  232. std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates);
  233. X509Certificate(bssl::UniquePtr<CRYPTO_BUFFER> cert_buffer,
  234. std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates,
  235. UnsafeCreateOptions options);
  236. ~X509Certificate();
  237. // Common object initialization code. Called by the constructors only.
  238. bool Initialize(UnsafeCreateOptions options);
  239. // Verifies that |hostname| matches one of the certificate names or IP
  240. // addresses supplied, based on TLS name matching rules - specifically,
  241. // following http://tools.ietf.org/html/rfc6125.
  242. // The members of |cert_san_dns_names| and |cert_san_ipaddrs| must be filled
  243. // from the dNSName and iPAddress components of the subject alternative name
  244. // extension, if present. Note these IP addresses are NOT ascii-encoded:
  245. // they must be 4 or 16 bytes of network-ordered data, for IPv4 and IPv6
  246. // addresses, respectively.
  247. static bool VerifyHostname(const std::string& hostname,
  248. const std::vector<std::string>& cert_san_dns_names,
  249. const std::vector<std::string>& cert_san_ip_addrs);
  250. // The subject of the certificate.
  251. CertPrincipal subject_;
  252. // The issuer of the certificate.
  253. CertPrincipal issuer_;
  254. // This certificate is not valid before |valid_start_|
  255. base::Time valid_start_;
  256. // This certificate is not valid after |valid_expiry_|
  257. base::Time valid_expiry_;
  258. // The serial number of this certificate, DER encoded.
  259. std::string serial_number_;
  260. // A handle to the DER encoded certificate data.
  261. bssl::UniquePtr<CRYPTO_BUFFER> cert_buffer_;
  262. // Untrusted intermediate certificates associated with this certificate
  263. // that may be needed for chain building.
  264. std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediate_ca_certs_;
  265. };
  266. } // namespace net
  267. #endif // NET_CERT_X509_CERTIFICATE_H_