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