Removed 'anonymous' from namespace, added whitespace in thread_restrictions.cc
[chromium-blink-merge.git] / net / cert / x509_certificate.h
blob3cd1ad77a4da5525a3451faf30f11beb19b7045f
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_
8 #include <string.h>
10 #include <string>
11 #include <vector>
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"
21 #if defined(OS_WIN)
22 #include <windows.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_CERTS)
32 // Forward declaration; real one in <cert.h>
33 struct CERTCertificateStr;
34 #endif
36 namespace base {
37 class Pickle;
38 class PickleIterator;
41 namespace net {
43 class CRLSet;
44 class CertVerifyResult;
46 typedef std::vector<scoped_refptr<X509Certificate> > CertificateList;
48 // X509Certificate represents a X.509 certificate, which is comprised a
49 // particular identity or end-entity certificate, such as an SSL server
50 // identity or an SSL client certificate, and zero or more intermediate
51 // certificates that may be used to build a path to a root certificate.
52 class NET_EXPORT X509Certificate
53 : public base::RefCountedThreadSafe<X509Certificate> {
54 public:
55 // An OSCertHandle is a handle to a certificate object in the underlying
56 // crypto library. We assume that OSCertHandle is a pointer type on all
57 // platforms and that NULL represents an invalid OSCertHandle.
58 #if defined(OS_WIN)
59 typedef PCCERT_CONTEXT OSCertHandle;
60 #elif defined(OS_MACOSX)
61 typedef SecCertificateRef OSCertHandle;
62 #elif defined(USE_OPENSSL_CERTS)
63 typedef X509* OSCertHandle;
64 #elif defined(USE_NSS_CERTS)
65 typedef struct CERTCertificateStr* OSCertHandle;
66 #else
67 // TODO(ericroman): not implemented
68 typedef void* OSCertHandle;
69 #endif
71 typedef std::vector<OSCertHandle> OSCertHandles;
73 enum PublicKeyType {
74 kPublicKeyTypeUnknown,
75 kPublicKeyTypeRSA,
76 kPublicKeyTypeDSA,
77 kPublicKeyTypeECDSA,
78 kPublicKeyTypeDH,
79 kPublicKeyTypeECDH
82 // Predicate functor used in maps when X509Certificate is used as the key.
83 class NET_EXPORT LessThan {
84 public:
85 bool operator()(const scoped_refptr<X509Certificate>& lhs,
86 const scoped_refptr<X509Certificate>& rhs) const;
89 enum Format {
90 // The data contains a single DER-encoded certificate, or a PEM-encoded
91 // DER certificate with the PEM encoding block name of "CERTIFICATE".
92 // Any subsequent blocks will be ignored.
93 FORMAT_SINGLE_CERTIFICATE = 1 << 0,
95 // The data contains a sequence of one or more PEM-encoded, DER
96 // certificates, with the PEM encoding block name of "CERTIFICATE".
97 // All PEM blocks will be parsed, until the first error is encountered.
98 FORMAT_PEM_CERT_SEQUENCE = 1 << 1,
100 // The data contains a PKCS#7 SignedData structure, whose certificates
101 // member is to be used to initialize the certificate and intermediates.
102 // The data may further be encoded using PEM, specifying block names of
103 // either "PKCS7" or "CERTIFICATE".
104 FORMAT_PKCS7 = 1 << 2,
106 // Automatically detect the format.
107 FORMAT_AUTO = FORMAT_SINGLE_CERTIFICATE | FORMAT_PEM_CERT_SEQUENCE |
108 FORMAT_PKCS7,
111 // PickleType is intended for deserializing certificates that were pickled
112 // by previous releases as part of a net::HttpResponseInfo.
113 // When serializing certificates to a new base::Pickle,
114 // PICKLETYPE_CERTIFICATE_CHAIN_V3 is always used.
115 enum PickleType {
116 // When reading a certificate from a Pickle, the Pickle only contains a
117 // single certificate.
118 PICKLETYPE_SINGLE_CERTIFICATE,
120 // When reading a certificate from a Pickle, the Pickle contains the
121 // the certificate plus any certificates that were stored in
122 // |intermediate_ca_certificates_| at the time it was serialized.
123 // The count of certificates is stored as a size_t, which is either 32
124 // or 64 bits.
125 PICKLETYPE_CERTIFICATE_CHAIN_V2,
127 // The Pickle contains the certificate and any certificates that were
128 // stored in |intermediate_ca_certs_| at the time it was serialized.
129 // The format is [int count], [data - this certificate],
130 // [data - intermediate1], ... [data - intermediateN].
131 // All certificates are stored in DER form.
132 PICKLETYPE_CERTIFICATE_CHAIN_V3,
135 // Creates a X509Certificate from the ground up. Used by tests that simulate
136 // SSL connections.
137 X509Certificate(const std::string& subject, const std::string& issuer,
138 base::Time start_date, base::Time expiration_date);
140 // Create an X509Certificate from a handle to the certificate object in the
141 // underlying crypto library. The returned pointer must be stored in a
142 // scoped_refptr<X509Certificate>.
143 static X509Certificate* CreateFromHandle(OSCertHandle cert_handle,
144 const OSCertHandles& intermediates);
146 // Create an X509Certificate from a chain of DER encoded certificates. The
147 // first certificate in the chain is the end-entity certificate to which a
148 // handle is returned. The other certificates in the chain are intermediate
149 // certificates. The returned pointer must be stored in a
150 // scoped_refptr<X509Certificate>.
151 static X509Certificate* CreateFromDERCertChain(
152 const std::vector<base::StringPiece>& der_certs);
154 // Create an X509Certificate from the DER-encoded representation.
155 // Returns NULL on failure.
157 // The returned pointer must be stored in a scoped_refptr<X509Certificate>.
158 static X509Certificate* CreateFromBytes(const char* data, int length);
160 #if defined(USE_NSS_CERTS)
161 // Create an X509Certificate from the DER-encoded representation.
162 // |nickname| can be NULL if an auto-generated nickname is desired.
163 // Returns NULL on failure. The returned pointer must be stored in a
164 // scoped_refptr<X509Certificate>.
166 // This function differs from CreateFromBytes in that it takes a
167 // nickname that will be used when the certificate is imported into PKCS#11.
168 static X509Certificate* CreateFromBytesWithNickname(const char* data,
169 int length,
170 const char* nickname);
172 // The default nickname of the certificate, based on the certificate type
173 // passed in. If this object was created using CreateFromBytesWithNickname,
174 // then this will return the nickname specified upon creation.
175 std::string GetDefaultNickname(CertType type) const;
176 #endif
178 // Create an X509Certificate from the representation stored in the given
179 // pickle. The data for this object is found relative to the given
180 // pickle_iter, which should be passed to the pickle's various Read* methods.
181 // Returns NULL on failure.
183 // The returned pointer must be stored in a scoped_refptr<X509Certificate>.
184 static X509Certificate* CreateFromPickle(base::PickleIterator* pickle_iter,
185 PickleType type);
187 // Parses all of the certificates possible from |data|. |format| is a
188 // bit-wise OR of Format, indicating the possible formats the
189 // certificates may have been serialized as. If an error occurs, an empty
190 // collection will be returned.
191 static CertificateList CreateCertificateListFromBytes(const char* data,
192 int length,
193 int format);
195 // Appends a representation of this object to the given pickle.
196 void Persist(base::Pickle* pickle);
198 // The serial number, DER encoded, possibly including a leading 00 byte.
199 const std::string& serial_number() const { return serial_number_; }
201 // The subject of the certificate. For HTTPS server certificates, this
202 // represents the web server. The common name of the subject should match
203 // the host name of the web server.
204 const CertPrincipal& subject() const { return subject_; }
206 // The issuer of the certificate.
207 const CertPrincipal& issuer() const { return issuer_; }
209 // Time period during which the certificate is valid. More precisely, this
210 // certificate is invalid before the |valid_start| date and invalid after
211 // the |valid_expiry| date.
212 // If we were unable to parse either date from the certificate (or if the cert
213 // lacks either date), the date will be null (i.e., is_null() will be true).
214 const base::Time& valid_start() const { return valid_start_; }
215 const base::Time& valid_expiry() const { return valid_expiry_; }
217 // The fingerprint of this certificate.
218 const SHA1HashValue& fingerprint() const { return fingerprint_; }
220 // The fingerprint of the intermediate CA certificates.
221 const SHA1HashValue& ca_fingerprint() const {
222 return ca_fingerprint_;
225 // Gets the DNS names in the certificate. Pursuant to RFC 2818, Section 3.1
226 // Server Identity, if the certificate has a subjectAltName extension of
227 // type dNSName, this method gets the DNS names in that extension.
228 // Otherwise, it gets the common name in the subject field.
229 void GetDNSNames(std::vector<std::string>* dns_names) const;
231 // Gets the subjectAltName extension field from the certificate, if any.
232 // For future extension; currently this only returns those name types that
233 // are required for HTTP certificate name verification - see VerifyHostname.
234 // Unrequired parameters may be passed as NULL.
235 void GetSubjectAltName(std::vector<std::string>* dns_names,
236 std::vector<std::string>* ip_addrs) const;
238 // Convenience method that returns whether this certificate has expired as of
239 // now.
240 bool HasExpired() const;
242 // Returns true if this object and |other| represent the same certificate.
243 bool Equals(const X509Certificate* other) const;
245 // Returns intermediate certificates added via AddIntermediateCertificate().
246 // Ownership follows the "get" rule: it is the caller's responsibility to
247 // retain the elements of the result.
248 const OSCertHandles& GetIntermediateCertificates() const {
249 return intermediate_ca_certs_;
252 #if defined(OS_MACOSX)
253 // Does this certificate's usage allow SSL client authentication?
254 bool SupportsSSLClientAuth() const;
256 // Returns a new CFMutableArrayRef containing this certificate and its
257 // intermediate certificates in the form expected by Security.framework
258 // and Keychain Services, or NULL on failure.
259 // The first item in the array will be this certificate, followed by its
260 // intermediates, if any.
261 CFMutableArrayRef CreateOSCertChainForCert() const;
262 #endif
264 // Do any of the given issuer names appear in this cert's chain of trust?
265 // |valid_issuers| is a list of DER-encoded X.509 DistinguishedNames.
266 bool IsIssuedByEncoded(const std::vector<std::string>& valid_issuers);
268 #if defined(OS_WIN)
269 // Returns a new PCCERT_CONTEXT containing this certificate and its
270 // intermediate certificates, or NULL on failure. The returned
271 // PCCERT_CONTEXT *MUST NOT* be stored in an X509Certificate, as this will
272 // cause os_cert_handle() to return incorrect results. This function is only
273 // necessary if the CERT_CONTEXT.hCertStore member will be accessed or
274 // enumerated, which is generally true for any CryptoAPI functions involving
275 // certificate chains, including validation or certificate display.
277 // Remarks:
278 // Depending on the CryptoAPI function, Windows may need to access the
279 // HCERTSTORE that the passed-in PCCERT_CONTEXT belongs to, such as to
280 // locate additional intermediates. However, all certificate handles are added
281 // to a NULL HCERTSTORE, allowing the system to manage the resources. As a
282 // result, intermediates for |cert_handle_| cannot be located simply via
283 // |cert_handle_->hCertStore|, as it refers to a magic value indicating
284 // "only this certificate".
286 // To avoid this problems, a new in-memory HCERTSTORE is created containing
287 // just this certificate and its intermediates. The handle to the version of
288 // the current certificate in the new HCERTSTORE is then returned, with the
289 // PCCERT_CONTEXT's HCERTSTORE set to be automatically freed when the returned
290 // certificate handle is freed.
292 // This function is only needed when the HCERTSTORE of the os_cert_handle()
293 // will be accessed, which is generally only during certificate validation
294 // or display. While the returned PCCERT_CONTEXT and its HCERTSTORE can
295 // safely be used on multiple threads if no further modifications happen, it
296 // is generally preferable for each thread that needs such a context to
297 // obtain its own, rather than risk thread-safety issues by sharing.
299 // Because of how X509Certificate caching is implemented, attempting to
300 // create an X509Certificate from the returned PCCERT_CONTEXT may result in
301 // the original handle (and thus the originall HCERTSTORE) being returned by
302 // os_cert_handle(). For this reason, the returned PCCERT_CONTEXT *MUST NOT*
303 // be stored in an X509Certificate.
304 PCCERT_CONTEXT CreateOSCertChainForCert() const;
305 #endif
307 #if defined(USE_OPENSSL_CERTS)
308 // Returns a handle to a global, in-memory certificate store. We
309 // use it for test code, e.g. importing the test server's certificate.
310 static X509_STORE* cert_store();
311 #endif
313 // Verifies that |hostname| matches this certificate.
314 // Does not verify that the certificate is valid, only that the certificate
315 // matches this host.
316 // Returns true if it matches, and updates |*common_name_fallback_used|,
317 // setting it to true if a fallback to the CN was used, rather than
318 // subjectAltName.
319 bool VerifyNameMatch(const std::string& hostname,
320 bool* common_name_fallback_used) const;
322 // Obtains the DER encoded certificate data for |cert_handle|. On success,
323 // returns true and writes the DER encoded certificate to |*der_encoded|.
324 static bool GetDEREncoded(OSCertHandle cert_handle,
325 std::string* der_encoded);
327 // Returns the PEM encoded data from a DER encoded certificate. If the return
328 // value is true, then the PEM encoded certificate is written to
329 // |pem_encoded|.
330 static bool GetPEMEncodedFromDER(const std::string& der_encoded,
331 std::string* pem_encoded);
333 // Returns the PEM encoded data from an OSCertHandle. If the return value is
334 // true, then the PEM encoded certificate is written to |pem_encoded|.
335 static bool GetPEMEncoded(OSCertHandle cert_handle,
336 std::string* pem_encoded);
338 // Encodes the entire certificate chain (this certificate and any
339 // intermediate certificates stored in |intermediate_ca_certs_|) as a series
340 // of PEM encoded strings. Returns true if all certificates were encoded,
341 // storig the result in |*pem_encoded|, with this certificate stored as
342 // the first element.
343 bool GetPEMEncodedChain(std::vector<std::string>* pem_encoded) const;
345 // Sets |*size_bits| to be the length of the public key in bits, and sets
346 // |*type| to one of the |PublicKeyType| values. In case of
347 // |kPublicKeyTypeUnknown|, |*size_bits| will be set to 0.
348 static void GetPublicKeyInfo(OSCertHandle cert_handle,
349 size_t* size_bits,
350 PublicKeyType* type);
352 // Returns the OSCertHandle of this object. Because of caching, this may
353 // differ from the OSCertHandle originally supplied during initialization.
354 // Note: On Windows, CryptoAPI may return unexpected results if this handle
355 // is used across multiple threads. For more details, see
356 // CreateOSCertChainForCert().
357 OSCertHandle os_cert_handle() const { return cert_handle_; }
359 // Returns true if two OSCertHandles refer to identical certificates.
360 static bool IsSameOSCert(OSCertHandle a, OSCertHandle b);
362 // Creates an OS certificate handle from the DER-encoded representation.
363 // Returns NULL on failure.
364 static OSCertHandle CreateOSCertHandleFromBytes(const char* data,
365 int length);
367 #if defined(USE_NSS_CERTS)
368 // Creates an OS certificate handle from the DER-encoded representation.
369 // Returns NULL on failure. Sets the default nickname if |nickname| is
370 // non-NULL.
371 static OSCertHandle CreateOSCertHandleFromBytesWithNickname(
372 const char* data,
373 int length,
374 const char* nickname);
375 #endif
377 // Creates all possible OS certificate handles from |data| encoded in a
378 // specific |format|. Returns an empty collection on failure.
379 static OSCertHandles CreateOSCertHandlesFromBytes(
380 const char* data,
381 int length,
382 Format format);
384 // Duplicates (or adds a reference to) an OS certificate handle.
385 static OSCertHandle DupOSCertHandle(OSCertHandle cert_handle);
387 // Frees (or releases a reference to) an OS certificate handle.
388 static void FreeOSCertHandle(OSCertHandle cert_handle);
390 // Calculates the SHA-1 fingerprint of the certificate. Returns an empty
391 // (all zero) fingerprint on failure.
393 // For calculating fingerprints, prefer SHA-1 for performance when indexing,
394 // but callers should use IsSameOSCert() before assuming two certificates are
395 // the same.
396 static SHA1HashValue CalculateFingerprint(OSCertHandle cert_handle);
398 // Calculates the SHA-256 fingerprint of the certificate. Returns an empty
399 // (all zero) fingerprint on failure.
400 static SHA256HashValue CalculateFingerprint256(OSCertHandle cert_handle);
402 // Calculates the SHA-1 fingerprint of the intermediate CA certificates.
403 // Returns an empty (all zero) fingerprint on failure.
405 // See SHA-1 caveat on CalculateFingerprint().
406 static SHA1HashValue CalculateCAFingerprint(
407 const OSCertHandles& intermediates);
409 // Calculates the SHA-256 fingerprint of the intermediate CA certificates.
410 // Returns an empty (all zero) fingerprint on failure.
412 // As part of the cross-platform implementation of this function, it currently
413 // copies the certificate bytes into local variables which makes it
414 // potentially slower than implementing it directly for each platform. For
415 // now, the expected consumers are not performance critical, but if
416 // performance is a concern going forward, it may warrant implementing this on
417 // a per-platform basis.
418 static SHA256HashValue CalculateCAFingerprint256(
419 const OSCertHandles& intermediates);
421 // Calculates the SHA-256 fingerprint for the complete chain, including the
422 // leaf certificate and all intermediate CA certificates. Returns an empty
423 // (all zero) fingerprint on failure.
424 static SHA256HashValue CalculateChainFingerprint256(
425 OSCertHandle leaf,
426 const OSCertHandles& intermediates);
428 // Returns true if the certificate is self-signed.
429 static bool IsSelfSigned(OSCertHandle cert_handle);
431 private:
432 friend class base::RefCountedThreadSafe<X509Certificate>;
433 friend class TestRootCerts; // For unit tests
435 FRIEND_TEST_ALL_PREFIXES(X509CertificateNameVerifyTest, VerifyHostname);
436 FRIEND_TEST_ALL_PREFIXES(X509CertificateTest, SerialNumbers);
438 // Construct an X509Certificate from a handle to the certificate object
439 // in the underlying crypto library.
440 X509Certificate(OSCertHandle cert_handle,
441 const OSCertHandles& intermediates);
443 ~X509Certificate();
445 // Common object initialization code. Called by the constructors only.
446 void Initialize();
448 #if defined(USE_OPENSSL_CERTS)
449 // Resets the store returned by cert_store() to default state. Used by
450 // TestRootCerts to undo modifications.
451 static void ResetCertStore();
452 #endif
454 // Verifies that |hostname| matches one of the certificate names or IP
455 // addresses supplied, based on TLS name matching rules - specifically,
456 // following http://tools.ietf.org/html/rfc6125.
457 // |cert_common_name| is the Subject CN, e.g. from X509Certificate::subject().
458 // The members of |cert_san_dns_names| and |cert_san_ipaddrs| must be filled
459 // from the dNSName and iPAddress components of the subject alternative name
460 // extension, if present. Note these IP addresses are NOT ascii-encoded:
461 // they must be 4 or 16 bytes of network-ordered data, for IPv4 and IPv6
462 // addresses, respectively.
463 // |common_name_fallback_used| will be updated to true if cert_common_name
464 // was used to match the hostname, or false if either of the |cert_san_*|
465 // parameters was used to match the hostname.
466 static bool VerifyHostname(const std::string& hostname,
467 const std::string& cert_common_name,
468 const std::vector<std::string>& cert_san_dns_names,
469 const std::vector<std::string>& cert_san_ip_addrs,
470 bool* common_name_fallback_used);
472 // Reads a single certificate from |pickle_iter| and returns a
473 // platform-specific certificate handle. The format of the certificate
474 // stored in |pickle_iter| is not guaranteed to be the same across different
475 // underlying cryptographic libraries, nor acceptable to CreateFromBytes().
476 // Returns an invalid handle, NULL, on failure.
477 // NOTE: This should not be used for any new code. It is provided for
478 // migration purposes and should eventually be removed.
479 static OSCertHandle ReadOSCertHandleFromPickle(
480 base::PickleIterator* pickle_iter);
482 // Writes a single certificate to |pickle| in DER form. Returns false on
483 // failure.
484 static bool WriteOSCertHandleToPickle(OSCertHandle handle,
485 base::Pickle* pickle);
487 // The subject of the certificate.
488 CertPrincipal subject_;
490 // The issuer of the certificate.
491 CertPrincipal issuer_;
493 // This certificate is not valid before |valid_start_|
494 base::Time valid_start_;
496 // This certificate is not valid after |valid_expiry_|
497 base::Time valid_expiry_;
499 // The fingerprint of this certificate.
500 SHA1HashValue fingerprint_;
502 // The fingerprint of the intermediate CA certificates.
503 SHA1HashValue ca_fingerprint_;
505 // The serial number of this certificate, DER encoded.
506 std::string serial_number_;
508 // A handle to the certificate object in the underlying crypto library.
509 OSCertHandle cert_handle_;
511 // Untrusted intermediate certificates associated with this certificate
512 // that may be needed for chain building.
513 OSCertHandles intermediate_ca_certs_;
515 #if defined(USE_NSS_CERTS)
516 // This stores any default nickname that has been set on the certificate
517 // at creation time with CreateFromBytesWithNickname.
518 // If this is empty, then GetDefaultNickname will return a generated name
519 // based on the type of the certificate.
520 std::string default_nickname_;
521 #endif
523 DISALLOW_COPY_AND_ASSIGN(X509Certificate);
526 } // namespace net
528 #endif // NET_CERT_X509_CERTIFICATE_H_