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.
5 #ifndef NET_CERT_X509_CERTIFICATE_H_
6 #define NET_CERT_X509_CERTIFICATE_H_
13 #include "base/gtest_prod_util.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/strings/string_piece.h"
16 #include "base/time/time.h"
17 #include "net/base/net_export.h"
18 #include "net/cert/cert_type.h"
19 #include "net/cert/x509_cert_types.h"
23 #include "crypto/wincrypt_shim.h"
24 #elif defined(OS_MACOSX)
25 #include <CoreFoundation/CFArray.h>
26 #include <Security/SecBase.h>
27 #elif defined(USE_OPENSSL_CERTS)
28 // Forward declaration; real one in <x509.h>
29 typedef struct x509_st X509
;
30 typedef struct x509_store_st X509_STORE
;
31 #elif defined(USE_NSS)
32 // Forward declaration; real one in <cert.h>
33 struct CERTCertificateStr
;
42 class CertVerifyResult
;
44 typedef std::vector
<scoped_refptr
<X509Certificate
> > CertificateList
;
46 // X509Certificate represents a X.509 certificate, which is comprised a
47 // particular identity or end-entity certificate, such as an SSL server
48 // identity or an SSL client certificate, and zero or more intermediate
49 // certificates that may be used to build a path to a root certificate.
50 class NET_EXPORT X509Certificate
51 : public base::RefCountedThreadSafe
<X509Certificate
> {
53 // An OSCertHandle is a handle to a certificate object in the underlying
54 // crypto library. We assume that OSCertHandle is a pointer type on all
55 // platforms and that NULL represents an invalid OSCertHandle.
57 typedef PCCERT_CONTEXT OSCertHandle
;
58 #elif defined(OS_MACOSX)
59 typedef SecCertificateRef OSCertHandle
;
60 #elif defined(USE_OPENSSL_CERTS)
61 typedef X509
* OSCertHandle
;
62 #elif defined(USE_NSS)
63 typedef struct CERTCertificateStr
* OSCertHandle
;
65 // TODO(ericroman): not implemented
66 typedef void* OSCertHandle
;
69 typedef std::vector
<OSCertHandle
> OSCertHandles
;
72 kPublicKeyTypeUnknown
,
80 // Predicate functor used in maps when X509Certificate is used as the key.
81 class NET_EXPORT LessThan
{
83 bool operator()(const scoped_refptr
<X509Certificate
>& lhs
,
84 const scoped_refptr
<X509Certificate
>& rhs
) const;
88 // The data contains a single DER-encoded certificate, or a PEM-encoded
89 // DER certificate with the PEM encoding block name of "CERTIFICATE".
90 // Any subsequent blocks will be ignored.
91 FORMAT_SINGLE_CERTIFICATE
= 1 << 0,
93 // The data contains a sequence of one or more PEM-encoded, DER
94 // certificates, with the PEM encoding block name of "CERTIFICATE".
95 // All PEM blocks will be parsed, until the first error is encountered.
96 FORMAT_PEM_CERT_SEQUENCE
= 1 << 1,
98 // The data contains a PKCS#7 SignedData structure, whose certificates
99 // member is to be used to initialize the certificate and intermediates.
100 // The data may further be encoded using PEM, specifying block names of
101 // either "PKCS7" or "CERTIFICATE".
102 FORMAT_PKCS7
= 1 << 2,
104 // Automatically detect the format.
105 FORMAT_AUTO
= FORMAT_SINGLE_CERTIFICATE
| FORMAT_PEM_CERT_SEQUENCE
|
109 // PickleType is intended for deserializing certificates that were pickled
110 // by previous releases as part of a net::HttpResponseInfo.
111 // When serializing certificates to a new Pickle,
112 // PICKLETYPE_CERTIFICATE_CHAIN_V3 is always used.
114 // When reading a certificate from a Pickle, the Pickle only contains a
115 // single certificate.
116 PICKLETYPE_SINGLE_CERTIFICATE
,
118 // When reading a certificate from a Pickle, the Pickle contains the
119 // the certificate plus any certificates that were stored in
120 // |intermediate_ca_certificates_| at the time it was serialized.
121 // The count of certificates is stored as a size_t, which is either 32
123 PICKLETYPE_CERTIFICATE_CHAIN_V2
,
125 // The Pickle contains the certificate and any certificates that were
126 // stored in |intermediate_ca_certs_| at the time it was serialized.
127 // The format is [int count], [data - this certificate],
128 // [data - intermediate1], ... [data - intermediateN].
129 // All certificates are stored in DER form.
130 PICKLETYPE_CERTIFICATE_CHAIN_V3
,
133 // Creates a X509Certificate from the ground up. Used by tests that simulate
135 X509Certificate(const std::string
& subject
, const std::string
& issuer
,
136 base::Time start_date
, base::Time expiration_date
);
138 // Create an X509Certificate from a handle to the certificate object in the
139 // underlying crypto library. The returned pointer must be stored in a
140 // scoped_refptr<X509Certificate>.
141 static X509Certificate
* CreateFromHandle(OSCertHandle cert_handle
,
142 const OSCertHandles
& intermediates
);
144 // Create an X509Certificate from a chain of DER encoded certificates. The
145 // first certificate in the chain is the end-entity certificate to which a
146 // handle is returned. The other certificates in the chain are intermediate
147 // certificates. The returned pointer must be stored in a
148 // scoped_refptr<X509Certificate>.
149 static X509Certificate
* CreateFromDERCertChain(
150 const std::vector
<base::StringPiece
>& der_certs
);
152 // Create an X509Certificate from the DER-encoded representation.
153 // Returns NULL on failure.
155 // The returned pointer must be stored in a scoped_refptr<X509Certificate>.
156 static X509Certificate
* CreateFromBytes(const char* data
, int length
);
159 // Create an X509Certificate from the DER-encoded representation.
160 // |nickname| can be NULL if an auto-generated nickname is desired.
161 // Returns NULL on failure. The returned pointer must be stored in a
162 // scoped_refptr<X509Certificate>.
164 // This function differs from CreateFromBytes in that it takes a
165 // nickname that will be used when the certificate is imported into PKCS#11.
166 static X509Certificate
* CreateFromBytesWithNickname(const char* data
,
168 const char* nickname
);
170 // The default nickname of the certificate, based on the certificate type
171 // passed in. If this object was created using CreateFromBytesWithNickname,
172 // then this will return the nickname specified upon creation.
173 std::string
GetDefaultNickname(CertType type
) const;
176 // Create an X509Certificate from the representation stored in the given
177 // pickle. The data for this object is found relative to the given
178 // pickle_iter, which should be passed to the pickle's various Read* methods.
179 // Returns NULL on failure.
181 // The returned pointer must be stored in a scoped_refptr<X509Certificate>.
182 static X509Certificate
* CreateFromPickle(const Pickle
& pickle
,
183 PickleIterator
* pickle_iter
,
186 // Parses all of the certificates possible from |data|. |format| is a
187 // bit-wise OR of Format, indicating the possible formats the
188 // certificates may have been serialized as. If an error occurs, an empty
189 // collection will be returned.
190 static CertificateList
CreateCertificateListFromBytes(const char* data
,
194 // Appends a representation of this object to the given pickle.
195 void Persist(Pickle
* pickle
);
197 // The serial number, DER encoded, possibly including a leading 00 byte.
198 const std::string
& serial_number() const { return serial_number_
; }
200 // The subject of the certificate. For HTTPS server certificates, this
201 // represents the web server. The common name of the subject should match
202 // the host name of the web server.
203 const CertPrincipal
& subject() const { return subject_
; }
205 // The issuer of the certificate.
206 const CertPrincipal
& issuer() const { return issuer_
; }
208 // Time period during which the certificate is valid. More precisely, this
209 // certificate is invalid before the |valid_start| date and invalid after
210 // the |valid_expiry| date.
211 // If we were unable to parse either date from the certificate (or if the cert
212 // lacks either date), the date will be null (i.e., is_null() will be true).
213 const base::Time
& valid_start() const { return valid_start_
; }
214 const base::Time
& valid_expiry() const { return valid_expiry_
; }
216 // The fingerprint of this certificate.
217 const SHA1HashValue
& fingerprint() const { return fingerprint_
; }
219 // The fingerprint of the intermediate CA certificates.
220 const SHA1HashValue
& ca_fingerprint() const {
221 return ca_fingerprint_
;
224 // Gets the DNS names in the certificate. Pursuant to RFC 2818, Section 3.1
225 // Server Identity, if the certificate has a subjectAltName extension of
226 // type dNSName, this method gets the DNS names in that extension.
227 // Otherwise, it gets the common name in the subject field.
228 void GetDNSNames(std::vector
<std::string
>* dns_names
) const;
230 // Gets the subjectAltName extension field from the certificate, if any.
231 // For future extension; currently this only returns those name types that
232 // are required for HTTP certificate name verification - see VerifyHostname.
233 // Unrequired parameters may be passed as NULL.
234 void GetSubjectAltName(std::vector
<std::string
>* dns_names
,
235 std::vector
<std::string
>* ip_addrs
) const;
237 // Convenience method that returns whether this certificate has expired as of
239 bool HasExpired() const;
241 // Returns true if this object and |other| represent the same certificate.
242 bool Equals(const X509Certificate
* other
) const;
244 // Returns intermediate certificates added via AddIntermediateCertificate().
245 // Ownership follows the "get" rule: it is the caller's responsibility to
246 // retain the elements of the result.
247 const OSCertHandles
& GetIntermediateCertificates() const {
248 return intermediate_ca_certs_
;
251 #if defined(OS_MACOSX)
252 // Does this certificate's usage allow SSL client authentication?
253 bool SupportsSSLClientAuth() const;
255 // Returns a new CFArrayRef containing this certificate and its intermediate
256 // certificates in the form expected by Security.framework and Keychain
257 // Services, or NULL on failure.
258 // The first item in the array will be this certificate, followed by its
259 // intermediates, if any.
260 CFArrayRef
CreateOSCertChainForCert() const;
263 // Do any of the given issuer names appear in this cert's chain of trust?
264 // |valid_issuers| is a list of DER-encoded X.509 DistinguishedNames.
265 bool IsIssuedByEncoded(const std::vector
<std::string
>& valid_issuers
);
268 // Returns a new PCCERT_CONTEXT containing this certificate and its
269 // intermediate certificates, or NULL on failure. The returned
270 // PCCERT_CONTEXT *MUST NOT* be stored in an X509Certificate, as this will
271 // cause os_cert_handle() to return incorrect results. This function is only
272 // necessary if the CERT_CONTEXT.hCertStore member will be accessed or
273 // enumerated, which is generally true for any CryptoAPI functions involving
274 // certificate chains, including validation or certificate display.
277 // Depending on the CryptoAPI function, Windows may need to access the
278 // HCERTSTORE that the passed-in PCCERT_CONTEXT belongs to, such as to
279 // locate additional intermediates. However, all certificate handles are added
280 // to a NULL HCERTSTORE, allowing the system to manage the resources. As a
281 // result, intermediates for |cert_handle_| cannot be located simply via
282 // |cert_handle_->hCertStore|, as it refers to a magic value indicating
283 // "only this certificate".
285 // To avoid this problems, a new in-memory HCERTSTORE is created containing
286 // just this certificate and its intermediates. The handle to the version of
287 // the current certificate in the new HCERTSTORE is then returned, with the
288 // PCCERT_CONTEXT's HCERTSTORE set to be automatically freed when the returned
289 // certificate handle is freed.
291 // This function is only needed when the HCERTSTORE of the os_cert_handle()
292 // will be accessed, which is generally only during certificate validation
293 // or display. While the returned PCCERT_CONTEXT and its HCERTSTORE can
294 // safely be used on multiple threads if no further modifications happen, it
295 // is generally preferable for each thread that needs such a context to
296 // obtain its own, rather than risk thread-safety issues by sharing.
298 // Because of how X509Certificate caching is implemented, attempting to
299 // create an X509Certificate from the returned PCCERT_CONTEXT may result in
300 // the original handle (and thus the originall HCERTSTORE) being returned by
301 // os_cert_handle(). For this reason, the returned PCCERT_CONTEXT *MUST NOT*
302 // be stored in an X509Certificate.
303 PCCERT_CONTEXT
CreateOSCertChainForCert() const;
306 #if defined(USE_OPENSSL_CERTS)
307 // Returns a handle to a global, in-memory certificate store. We
308 // use it for test code, e.g. importing the test server's certificate.
309 static X509_STORE
* cert_store();
312 // Verifies that |hostname| matches this certificate.
313 // Does not verify that the certificate is valid, only that the certificate
314 // matches this host.
315 // Returns true if it matches, and updates |*common_name_fallback_used|,
316 // setting it to true if a fallback to the CN was used, rather than
318 bool VerifyNameMatch(const std::string
& hostname
,
319 bool* common_name_fallback_used
) const;
321 // Obtains the DER encoded certificate data for |cert_handle|. On success,
322 // returns true and writes the DER encoded certificate to |*der_encoded|.
323 static bool GetDEREncoded(OSCertHandle cert_handle
,
324 std::string
* der_encoded
);
326 // Returns the PEM encoded data from a DER encoded certificate. If the return
327 // value is true, then the PEM encoded certificate is written to
329 static bool GetPEMEncodedFromDER(const std::string
& der_encoded
,
330 std::string
* pem_encoded
);
332 // Returns the PEM encoded data from an OSCertHandle. If the return value is
333 // true, then the PEM encoded certificate is written to |pem_encoded|.
334 static bool GetPEMEncoded(OSCertHandle cert_handle
,
335 std::string
* pem_encoded
);
337 // Encodes the entire certificate chain (this certificate and any
338 // intermediate certificates stored in |intermediate_ca_certs_|) as a series
339 // of PEM encoded strings. Returns true if all certificates were encoded,
340 // storig the result in |*pem_encoded|, with this certificate stored as
341 // the first element.
342 bool GetPEMEncodedChain(std::vector
<std::string
>* pem_encoded
) const;
344 // Sets |*size_bits| to be the length of the public key in bits, and sets
345 // |*type| to one of the |PublicKeyType| values. In case of
346 // |kPublicKeyTypeUnknown|, |*size_bits| will be set to 0.
347 static void GetPublicKeyInfo(OSCertHandle cert_handle
,
349 PublicKeyType
* type
);
351 // Returns the OSCertHandle of this object. Because of caching, this may
352 // differ from the OSCertHandle originally supplied during initialization.
353 // Note: On Windows, CryptoAPI may return unexpected results if this handle
354 // is used across multiple threads. For more details, see
355 // CreateOSCertChainForCert().
356 OSCertHandle
os_cert_handle() const { return cert_handle_
; }
358 // Returns true if two OSCertHandles refer to identical certificates.
359 static bool IsSameOSCert(OSCertHandle a
, OSCertHandle b
);
361 // Creates an OS certificate handle from the DER-encoded representation.
362 // Returns NULL on failure.
363 static OSCertHandle
CreateOSCertHandleFromBytes(const char* data
,
367 // Creates an OS certificate handle from the DER-encoded representation.
368 // Returns NULL on failure. Sets the default nickname if |nickname| is
370 static OSCertHandle
CreateOSCertHandleFromBytesWithNickname(
373 const char* nickname
);
376 // Creates all possible OS certificate handles from |data| encoded in a
377 // specific |format|. Returns an empty collection on failure.
378 static OSCertHandles
CreateOSCertHandlesFromBytes(
383 // Duplicates (or adds a reference to) an OS certificate handle.
384 static OSCertHandle
DupOSCertHandle(OSCertHandle cert_handle
);
386 // Frees (or releases a reference to) an OS certificate handle.
387 static void FreeOSCertHandle(OSCertHandle cert_handle
);
389 // Calculates the SHA-1 fingerprint of the certificate. Returns an empty
390 // (all zero) fingerprint on failure.
392 // For calculating fingerprints, prefer SHA-1 for performance when indexing,
393 // but callers should use IsSameOSCert() before assuming two certificates are
395 static SHA1HashValue
CalculateFingerprint(OSCertHandle cert_handle
);
397 // Calculates the SHA-256 fingerprint of the certificate. Returns an empty
398 // (all zero) fingerprint on failure.
399 static SHA256HashValue
CalculateFingerprint256(OSCertHandle cert_handle
);
401 // Calculates the SHA-1 fingerprint of the intermediate CA certificates.
402 // Returns an empty (all zero) fingerprint on failure.
404 // See SHA-1 caveat on CalculateFingerprint().
405 static SHA1HashValue
CalculateCAFingerprint(
406 const OSCertHandles
& intermediates
);
408 // Calculates the SHA-256 fingerprint of the intermediate CA certificates.
409 // Returns an empty (all zero) fingerprint on failure.
411 // As part of the cross-platform implementation of this function, it currently
412 // copies the certificate bytes into local variables which makes it
413 // potentially slower than implementing it directly for each platform. For
414 // now, the expected consumers are not performance critical, but if
415 // performance is a concern going forward, it may warrant implementing this on
416 // a per-platform basis.
417 static SHA256HashValue
CalculateCAFingerprint256(
418 const OSCertHandles
& intermediates
);
420 // Calculates the SHA-256 fingerprint for the complete chain, including the
421 // leaf certificate and all intermediate CA certificates. Returns an empty
422 // (all zero) fingerprint on failure.
423 static SHA256HashValue
CalculateChainFingerprint256(
425 const OSCertHandles
& intermediates
);
427 // Returns true if the certificate is self-signed.
428 static bool IsSelfSigned(OSCertHandle cert_handle
);
431 friend class base::RefCountedThreadSafe
<X509Certificate
>;
432 friend class TestRootCerts
; // For unit tests
434 FRIEND_TEST_ALL_PREFIXES(X509CertificateNameVerifyTest
, VerifyHostname
);
435 FRIEND_TEST_ALL_PREFIXES(X509CertificateTest
, SerialNumbers
);
437 // Construct an X509Certificate from a handle to the certificate object
438 // in the underlying crypto library.
439 X509Certificate(OSCertHandle cert_handle
,
440 const OSCertHandles
& intermediates
);
444 // Common object initialization code. Called by the constructors only.
447 #if defined(USE_OPENSSL_CERTS)
448 // Resets the store returned by cert_store() to default state. Used by
449 // TestRootCerts to undo modifications.
450 static void ResetCertStore();
453 // Verifies that |hostname| matches one of the certificate names or IP
454 // addresses supplied, based on TLS name matching rules - specifically,
455 // following http://tools.ietf.org/html/rfc6125.
456 // |cert_common_name| is the Subject CN, e.g. from X509Certificate::subject().
457 // The members of |cert_san_dns_names| and |cert_san_ipaddrs| must be filled
458 // from the dNSName and iPAddress components of the subject alternative name
459 // extension, if present. Note these IP addresses are NOT ascii-encoded:
460 // they must be 4 or 16 bytes of network-ordered data, for IPv4 and IPv6
461 // addresses, respectively.
462 // |common_name_fallback_used| will be updated to true if cert_common_name
463 // was used to match the hostname, or false if either of the |cert_san_*|
464 // parameters was used to match the hostname.
465 static bool VerifyHostname(const std::string
& hostname
,
466 const std::string
& cert_common_name
,
467 const std::vector
<std::string
>& cert_san_dns_names
,
468 const std::vector
<std::string
>& cert_san_ip_addrs
,
469 bool* common_name_fallback_used
);
471 // Reads a single certificate from |pickle_iter| and returns a
472 // platform-specific certificate handle. The format of the certificate
473 // stored in |pickle_iter| is not guaranteed to be the same across different
474 // underlying cryptographic libraries, nor acceptable to CreateFromBytes().
475 // Returns an invalid handle, NULL, on failure.
476 // NOTE: This should not be used for any new code. It is provided for
477 // migration purposes and should eventually be removed.
478 static OSCertHandle
ReadOSCertHandleFromPickle(PickleIterator
* pickle_iter
);
480 // Writes a single certificate to |pickle| in DER form. Returns false on
482 static bool WriteOSCertHandleToPickle(OSCertHandle handle
, Pickle
* pickle
);
484 // The subject of the certificate.
485 CertPrincipal subject_
;
487 // The issuer of the certificate.
488 CertPrincipal issuer_
;
490 // This certificate is not valid before |valid_start_|
491 base::Time valid_start_
;
493 // This certificate is not valid after |valid_expiry_|
494 base::Time valid_expiry_
;
496 // The fingerprint of this certificate.
497 SHA1HashValue fingerprint_
;
499 // The fingerprint of the intermediate CA certificates.
500 SHA1HashValue ca_fingerprint_
;
502 // The serial number of this certificate, DER encoded.
503 std::string serial_number_
;
505 // A handle to the certificate object in the underlying crypto library.
506 OSCertHandle cert_handle_
;
508 // Untrusted intermediate certificates associated with this certificate
509 // that may be needed for chain building.
510 OSCertHandles intermediate_ca_certs_
;
513 // This stores any default nickname that has been set on the certificate
514 // at creation time with CreateFromBytesWithNickname.
515 // If this is empty, then GetDefaultNickname will return a generated name
516 // based on the type of the certificate.
517 std::string default_nickname_
;
520 DISALLOW_COPY_AND_ASSIGN(X509Certificate
);
525 #endif // NET_CERT_X509_CERTIFICATE_H_