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