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.h"
17 #include "net/base/net_export.h"
18 #include "net/cert/cert_type.h"
19 #include "net/cert/x509_cert_types.h"
24 #elif defined(OS_MACOSX)
25 #include <CoreFoundation/CFArray.h>
26 #include <Security/SecBase.h>
28 #elif defined(USE_OPENSSL)
29 // Forward declaration; real one in <x509.h>
30 typedef struct x509_st X509
;
31 typedef struct x509_store_st X509_STORE
;
32 #elif defined(USE_NSS)
33 // Forward declaration; real one in <cert.h>
34 struct CERTCertificateStr
;
47 class CertVerifyResult
;
49 typedef std::vector
<scoped_refptr
<X509Certificate
> > CertificateList
;
51 // X509Certificate represents a X.509 certificate, which is comprised a
52 // particular identity or end-entity certificate, such as an SSL server
53 // identity or an SSL client certificate, and zero or more intermediate
54 // certificates that may be used to build a path to a root certificate.
55 class NET_EXPORT X509Certificate
56 : public base::RefCountedThreadSafe
<X509Certificate
> {
58 // An OSCertHandle is a handle to a certificate object in the underlying
59 // crypto library. We assume that OSCertHandle is a pointer type on all
60 // platforms and that NULL represents an invalid OSCertHandle.
62 typedef PCCERT_CONTEXT OSCertHandle
;
63 #elif defined(OS_MACOSX)
64 typedef SecCertificateRef OSCertHandle
;
65 #elif defined(USE_OPENSSL)
66 typedef X509
* OSCertHandle
;
67 #elif defined(USE_NSS)
68 typedef struct CERTCertificateStr
* OSCertHandle
;
70 // TODO(ericroman): not implemented
71 typedef void* OSCertHandle
;
74 typedef std::vector
<OSCertHandle
> OSCertHandles
;
77 kPublicKeyTypeUnknown
,
85 // Predicate functor used in maps when X509Certificate is used as the key.
86 class NET_EXPORT LessThan
{
88 bool operator() (X509Certificate
* lhs
, X509Certificate
* rhs
) const;
92 // The data contains a single DER-encoded certificate, or a PEM-encoded
93 // DER certificate with the PEM encoding block name of "CERTIFICATE".
94 // Any subsequent blocks will be ignored.
95 FORMAT_SINGLE_CERTIFICATE
= 1 << 0,
97 // The data contains a sequence of one or more PEM-encoded, DER
98 // certificates, with the PEM encoding block name of "CERTIFICATE".
99 // All PEM blocks will be parsed, until the first error is encountered.
100 FORMAT_PEM_CERT_SEQUENCE
= 1 << 1,
102 // The data contains a PKCS#7 SignedData structure, whose certificates
103 // member is to be used to initialize the certificate and intermediates.
104 // The data may further be encoded using PEM, specifying block names of
105 // either "PKCS7" or "CERTIFICATE".
106 FORMAT_PKCS7
= 1 << 2,
108 // Automatically detect the format.
109 FORMAT_AUTO
= FORMAT_SINGLE_CERTIFICATE
| FORMAT_PEM_CERT_SEQUENCE
|
113 // PickleType is intended for deserializing certificates that were pickled
114 // by previous releases as part of a net::HttpResponseInfo.
115 // When serializing certificates to a new Pickle,
116 // PICKLETYPE_CERTIFICATE_CHAIN_V3 is always used.
118 // When reading a certificate from a Pickle, the Pickle only contains a
119 // single certificate.
120 PICKLETYPE_SINGLE_CERTIFICATE
,
122 // When reading a certificate from a Pickle, the Pickle contains the
123 // the certificate plus any certificates that were stored in
124 // |intermediate_ca_certificates_| at the time it was serialized.
125 // The count of certificates is stored as a size_t, which is either 32
127 PICKLETYPE_CERTIFICATE_CHAIN_V2
,
129 // The Pickle contains the certificate and any certificates that were
130 // stored in |intermediate_ca_certs_| at the time it was serialized.
131 // The format is [int count], [data - this certificate],
132 // [data - intermediate1], ... [data - intermediateN].
133 // All certificates are stored in DER form.
134 PICKLETYPE_CERTIFICATE_CHAIN_V3
,
137 // Creates a X509Certificate from the ground up. Used by tests that simulate
139 X509Certificate(const std::string
& subject
, const std::string
& issuer
,
140 base::Time start_date
, base::Time expiration_date
);
142 // Create an X509Certificate from a handle to the certificate object in the
143 // underlying crypto library. The returned pointer must be stored in a
144 // scoped_refptr<X509Certificate>.
145 static X509Certificate
* CreateFromHandle(OSCertHandle cert_handle
,
146 const OSCertHandles
& intermediates
);
148 // Create an X509Certificate from a chain of DER encoded certificates. The
149 // first certificate in the chain is the end-entity certificate to which a
150 // handle is returned. The other certificates in the chain are intermediate
151 // certificates. The returned pointer must be stored in a
152 // scoped_refptr<X509Certificate>.
153 static X509Certificate
* CreateFromDERCertChain(
154 const std::vector
<base::StringPiece
>& der_certs
);
156 // Create an X509Certificate from the DER-encoded representation.
157 // Returns NULL on failure.
159 // The returned pointer must be stored in a scoped_refptr<X509Certificate>.
160 static X509Certificate
* CreateFromBytes(const char* data
, int length
);
163 // Create an X509Certificate from the DER-encoded representation.
164 // |nickname| can be NULL if an auto-generated nickname is desired.
165 // Returns NULL on failure. The returned pointer must be stored in a
166 // scoped_refptr<X509Certificate>.
168 // This function differs from CreateFromBytes in that it takes a
169 // nickname that will be used when the certificate is imported into PKCS#11.
170 static X509Certificate
* CreateFromBytesWithNickname(const char* data
,
172 const char* nickname
);
174 // The default nickname of the certificate, based on the certificate type
175 // passed in. If this object was created using CreateFromBytesWithNickname,
176 // then this will return the nickname specified upon creation.
177 std::string
GetDefaultNickname(CertType type
) const;
180 // Create an X509Certificate from the representation stored in the given
181 // pickle. The data for this object is found relative to the given
182 // pickle_iter, which should be passed to the pickle's various Read* methods.
183 // Returns NULL on failure.
185 // The returned pointer must be stored in a scoped_refptr<X509Certificate>.
186 static X509Certificate
* CreateFromPickle(const Pickle
& pickle
,
187 PickleIterator
* pickle_iter
,
190 // Parses all of the certificates possible from |data|. |format| is a
191 // bit-wise OR of Format, indicating the possible formats the
192 // certificates may have been serialized as. If an error occurs, an empty
193 // collection will be returned.
194 static CertificateList
CreateCertificateListFromBytes(const char* data
,
198 // Create a self-signed certificate containing the public key in |key|.
199 // Subject, serial number and validity period are given as parameters.
200 // The certificate is signed by the private key in |key|. The hashing
201 // algorithm for the signature is SHA-1.
203 // |subject| is a distinguished name defined in RFC4514.
206 // CN=Michael Wong,O=FooBar Corporation,DC=foobar,DC=com
210 // Using self-signed certificates has the following security risks:
211 // 1. Encryption without authentication and thus vulnerable to
212 // man-in-the-middle attacks.
213 // 2. Self-signed certificates cannot be revoked.
215 // Use this certificate only after the above risks are acknowledged.
216 static X509Certificate
* CreateSelfSigned(crypto::RSAPrivateKey
* key
,
217 const std::string
& subject
,
218 uint32 serial_number
,
219 base::TimeDelta valid_duration
);
221 // Appends a representation of this object to the given pickle.
222 void Persist(Pickle
* pickle
);
224 // The serial number, DER encoded, possibly including a leading 00 byte.
225 const std::string
& serial_number() const { return serial_number_
; }
227 // The subject of the certificate. For HTTPS server certificates, this
228 // represents the web server. The common name of the subject should match
229 // the host name of the web server.
230 const CertPrincipal
& subject() const { return subject_
; }
232 // The issuer of the certificate.
233 const CertPrincipal
& issuer() const { return issuer_
; }
235 // Time period during which the certificate is valid. More precisely, this
236 // certificate is invalid before the |valid_start| date and invalid after
237 // the |valid_expiry| date.
238 // If we were unable to parse either date from the certificate (or if the cert
239 // lacks either date), the date will be null (i.e., is_null() will be true).
240 const base::Time
& valid_start() const { return valid_start_
; }
241 const base::Time
& valid_expiry() const { return valid_expiry_
; }
243 // The fingerprint of this certificate.
244 const SHA1HashValue
& fingerprint() const { return fingerprint_
; }
246 // The fingerprint of the intermediate CA certificates.
247 const SHA1HashValue
& ca_fingerprint() const {
248 return ca_fingerprint_
;
251 // Gets the DNS names in the certificate. Pursuant to RFC 2818, Section 3.1
252 // Server Identity, if the certificate has a subjectAltName extension of
253 // type dNSName, this method gets the DNS names in that extension.
254 // Otherwise, it gets the common name in the subject field.
255 void GetDNSNames(std::vector
<std::string
>* dns_names
) const;
257 // Gets the subjectAltName extension field from the certificate, if any.
258 // For future extension; currently this only returns those name types that
259 // are required for HTTP certificate name verification - see VerifyHostname.
260 // Unrequired parameters may be passed as NULL.
261 void GetSubjectAltName(std::vector
<std::string
>* dns_names
,
262 std::vector
<std::string
>* ip_addrs
) const;
264 // Convenience method that returns whether this certificate has expired as of
266 bool HasExpired() const;
268 // Returns true if this object and |other| represent the same certificate.
269 bool Equals(const X509Certificate
* other
) const;
271 // Returns intermediate certificates added via AddIntermediateCertificate().
272 // Ownership follows the "get" rule: it is the caller's responsibility to
273 // retain the elements of the result.
274 const OSCertHandles
& GetIntermediateCertificates() const {
275 return intermediate_ca_certs_
;
278 #if defined(OS_MACOSX)
279 // Does this certificate's usage allow SSL client authentication?
280 bool SupportsSSLClientAuth() const;
282 // Returns a new CFArrayRef containing this certificate and its intermediate
283 // certificates in the form expected by Security.framework and Keychain
284 // Services, or NULL on failure.
285 // The first item in the array will be this certificate, followed by its
286 // intermediates, if any.
287 CFArrayRef
CreateOSCertChainForCert() const;
290 // Do any of the given issuer names appear in this cert's chain of trust?
291 // |valid_issuers| is a list of DER-encoded X.509 DistinguishedNames.
292 bool IsIssuedByEncoded(const std::vector
<std::string
>& valid_issuers
);
295 // Returns a new PCCERT_CONTEXT containing this certificate and its
296 // intermediate certificates, or NULL on failure. The returned
297 // PCCERT_CONTEXT *MUST NOT* be stored in an X509Certificate, as this will
298 // cause os_cert_handle() to return incorrect results. This function is only
299 // necessary if the CERT_CONTEXT.hCertStore member will be accessed or
300 // enumerated, which is generally true for any CryptoAPI functions involving
301 // certificate chains, including validation or certificate display.
304 // Depending on the CryptoAPI function, Windows may need to access the
305 // HCERTSTORE that the passed-in PCCERT_CONTEXT belongs to, such as to
306 // locate additional intermediates. However, all certificate handles are added
307 // to a NULL HCERTSTORE, allowing the system to manage the resources. As a
308 // result, intermediates for |cert_handle_| cannot be located simply via
309 // |cert_handle_->hCertStore|, as it refers to a magic value indicating
310 // "only this certificate".
312 // To avoid this problems, a new in-memory HCERTSTORE is created containing
313 // just this certificate and its intermediates. The handle to the version of
314 // the current certificate in the new HCERTSTORE is then returned, with the
315 // PCCERT_CONTEXT's HCERTSTORE set to be automatically freed when the returned
316 // certificate handle is freed.
318 // This function is only needed when the HCERTSTORE of the os_cert_handle()
319 // will be accessed, which is generally only during certificate validation
320 // or display. While the returned PCCERT_CONTEXT and its HCERTSTORE can
321 // safely be used on multiple threads if no further modifications happen, it
322 // is generally preferable for each thread that needs such a context to
323 // obtain its own, rather than risk thread-safety issues by sharing.
325 // Because of how X509Certificate caching is implemented, attempting to
326 // create an X509Certificate from the returned PCCERT_CONTEXT may result in
327 // the original handle (and thus the originall HCERTSTORE) being returned by
328 // os_cert_handle(). For this reason, the returned PCCERT_CONTEXT *MUST NOT*
329 // be stored in an X509Certificate.
330 PCCERT_CONTEXT
CreateOSCertChainForCert() const;
333 #if defined(USE_OPENSSL)
334 // Returns a handle to a global, in-memory certificate store. We
335 // use it for test code, e.g. importing the test server's certificate.
336 static X509_STORE
* cert_store();
339 // Verifies that |hostname| matches this certificate.
340 // Does not verify that the certificate is valid, only that the certificate
341 // matches this host.
342 // Returns true if it matches.
343 bool VerifyNameMatch(const std::string
& hostname
) const;
345 // Obtains the DER encoded certificate data for |cert_handle|. On success,
346 // returns true and writes the DER encoded certificate to |*der_encoded|.
347 static bool GetDEREncoded(OSCertHandle cert_handle
,
348 std::string
* der_encoded
);
350 // Returns the PEM encoded data from an OSCertHandle. If the return value is
351 // true, then the PEM encoded certificate is written to |pem_encoded|.
352 static bool GetPEMEncoded(OSCertHandle cert_handle
,
353 std::string
* pem_encoded
);
355 // Encodes the entire certificate chain (this certificate and any
356 // intermediate certificates stored in |intermediate_ca_certs_|) as a series
357 // of PEM encoded strings. Returns true if all certificates were encoded,
358 // storig the result in |*pem_encoded|, with this certificate stored as
359 // the first element.
360 bool GetPEMEncodedChain(std::vector
<std::string
>* pem_encoded
) const;
362 // Sets |*size_bits| to be the length of the public key in bits, and sets
363 // |*type| to one of the |PublicKeyType| values. In case of
364 // |kPublicKeyTypeUnknown|, |*size_bits| will be set to 0.
365 static void GetPublicKeyInfo(OSCertHandle cert_handle
,
367 PublicKeyType
* type
);
369 // Returns the OSCertHandle of this object. Because of caching, this may
370 // differ from the OSCertHandle originally supplied during initialization.
371 // Note: On Windows, CryptoAPI may return unexpected results if this handle
372 // is used across multiple threads. For more details, see
373 // CreateOSCertChainForCert().
374 OSCertHandle
os_cert_handle() const { return cert_handle_
; }
376 // Returns true if two OSCertHandles refer to identical certificates.
377 static bool IsSameOSCert(OSCertHandle a
, OSCertHandle b
);
379 // Creates an OS certificate handle from the DER-encoded representation.
380 // Returns NULL on failure.
381 static OSCertHandle
CreateOSCertHandleFromBytes(const char* data
,
385 // Creates an OS certificate handle from the DER-encoded representation.
386 // Returns NULL on failure. Sets the default nickname if |nickname| is
388 static OSCertHandle
CreateOSCertHandleFromBytesWithNickname(
391 const char* nickname
);
394 // Creates all possible OS certificate handles from |data| encoded in a
395 // specific |format|. Returns an empty collection on failure.
396 static OSCertHandles
CreateOSCertHandlesFromBytes(
401 // Duplicates (or adds a reference to) an OS certificate handle.
402 static OSCertHandle
DupOSCertHandle(OSCertHandle cert_handle
);
404 // Frees (or releases a reference to) an OS certificate handle.
405 static void FreeOSCertHandle(OSCertHandle cert_handle
);
407 // Calculates the SHA-1 fingerprint of the certificate. Returns an empty
408 // (all zero) fingerprint on failure.
409 static SHA1HashValue
CalculateFingerprint(OSCertHandle cert_handle
);
411 // Calculates the SHA-1 fingerprint of the intermediate CA certificates.
412 // Returns an empty (all zero) fingerprint on failure.
413 static SHA1HashValue
CalculateCAFingerprint(
414 const OSCertHandles
& intermediates
);
417 friend class base::RefCountedThreadSafe
<X509Certificate
>;
418 friend class TestRootCerts
; // For unit tests
420 FRIEND_TEST_ALL_PREFIXES(X509CertificateNameVerifyTest
, VerifyHostname
);
421 FRIEND_TEST_ALL_PREFIXES(X509CertificateTest
, SerialNumbers
);
423 // Construct an X509Certificate from a handle to the certificate object
424 // in the underlying crypto library.
425 X509Certificate(OSCertHandle cert_handle
,
426 const OSCertHandles
& intermediates
);
430 // Common object initialization code. Called by the constructors only.
433 #if defined(USE_OPENSSL)
434 // Resets the store returned by cert_store() to default state. Used by
435 // TestRootCerts to undo modifications.
436 static void ResetCertStore();
439 // Verifies that |hostname| matches one of the certificate names or IP
440 // addresses supplied, based on TLS name matching rules - specifically,
441 // following http://tools.ietf.org/html/rfc6125.
442 // |cert_common_name| is the Subject CN, e.g. from X509Certificate::subject().
443 // The members of |cert_san_dns_names| and |cert_san_ipaddrs| must be filled
444 // from the dNSName and iPAddress components of the subject alternative name
445 // extension, if present. Note these IP addresses are NOT ascii-encoded:
446 // they must be 4 or 16 bytes of network-ordered data, for IPv4 and IPv6
447 // addresses, respectively.
448 static bool VerifyHostname(const std::string
& hostname
,
449 const std::string
& cert_common_name
,
450 const std::vector
<std::string
>& cert_san_dns_names
,
451 const std::vector
<std::string
>& cert_san_ip_addrs
);
453 // Reads a single certificate from |pickle_iter| and returns a
454 // platform-specific certificate handle. The format of the certificate
455 // stored in |pickle_iter| is not guaranteed to be the same across different
456 // underlying cryptographic libraries, nor acceptable to CreateFromBytes().
457 // Returns an invalid handle, NULL, on failure.
458 // NOTE: This should not be used for any new code. It is provided for
459 // migration purposes and should eventually be removed.
460 static OSCertHandle
ReadOSCertHandleFromPickle(PickleIterator
* pickle_iter
);
462 // Writes a single certificate to |pickle| in DER form. Returns false on
464 static bool WriteOSCertHandleToPickle(OSCertHandle handle
, Pickle
* pickle
);
466 // The subject of the certificate.
467 CertPrincipal subject_
;
469 // The issuer of the certificate.
470 CertPrincipal issuer_
;
472 // This certificate is not valid before |valid_start_|
473 base::Time valid_start_
;
475 // This certificate is not valid after |valid_expiry_|
476 base::Time valid_expiry_
;
478 // The fingerprint of this certificate.
479 SHA1HashValue fingerprint_
;
481 // The fingerprint of the intermediate CA certificates.
482 SHA1HashValue ca_fingerprint_
;
484 // The serial number of this certificate, DER encoded.
485 std::string serial_number_
;
487 // A handle to the certificate object in the underlying crypto library.
488 OSCertHandle cert_handle_
;
490 // Untrusted intermediate certificates associated with this certificate
491 // that may be needed for chain building.
492 OSCertHandles intermediate_ca_certs_
;
495 // This stores any default nickname that has been set on the certificate
496 // at creation time with CreateFromBytesWithNickname.
497 // If this is empty, then GetDefaultNickname will return a generated name
498 // based on the type of the certificate.
499 std::string default_nickname_
;
502 DISALLOW_COPY_AND_ASSIGN(X509Certificate
);
507 #endif // NET_CERT_X509_CERTIFICATE_H_