Don't show supervised user as "already on this device" while they're being imported.
[chromium-blink-merge.git] / net / cert / x509_certificate.h
blob11ac0bb673074c0a88b9e405c941acbc957e29db
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 class Pickle;
37 class PickleIterator;
39 namespace net {
41 class CRLSet;
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> {
52 public:
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.
56 #if defined(OS_WIN)
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_CERTS)
63 typedef struct CERTCertificateStr* OSCertHandle;
64 #else
65 // TODO(ericroman): not implemented
66 typedef void* OSCertHandle;
67 #endif
69 typedef std::vector<OSCertHandle> OSCertHandles;
71 enum PublicKeyType {
72 kPublicKeyTypeUnknown,
73 kPublicKeyTypeRSA,
74 kPublicKeyTypeDSA,
75 kPublicKeyTypeECDSA,
76 kPublicKeyTypeDH,
77 kPublicKeyTypeECDH
80 // Predicate functor used in maps when X509Certificate is used as the key.
81 class NET_EXPORT LessThan {
82 public:
83 bool operator()(const scoped_refptr<X509Certificate>& lhs,
84 const scoped_refptr<X509Certificate>& rhs) const;
87 enum Format {
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 |
106 FORMAT_PKCS7,
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.
113 enum PickleType {
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
122 // or 64 bits.
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
134 // SSL connections.
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);
158 #if defined(USE_NSS_CERTS)
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,
167 int length,
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;
174 #endif
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(PickleIterator* pickle_iter,
183 PickleType type);
185 // Parses all of the certificates possible from |data|. |format| is a
186 // bit-wise OR of Format, indicating the possible formats the
187 // certificates may have been serialized as. If an error occurs, an empty
188 // collection will be returned.
189 static CertificateList CreateCertificateListFromBytes(const char* data,
190 int length,
191 int format);
193 // Appends a representation of this object to the given pickle.
194 void Persist(Pickle* pickle);
196 // The serial number, DER encoded, possibly including a leading 00 byte.
197 const std::string& serial_number() const { return serial_number_; }
199 // The subject of the certificate. For HTTPS server certificates, this
200 // represents the web server. The common name of the subject should match
201 // the host name of the web server.
202 const CertPrincipal& subject() const { return subject_; }
204 // The issuer of the certificate.
205 const CertPrincipal& issuer() const { return issuer_; }
207 // Time period during which the certificate is valid. More precisely, this
208 // certificate is invalid before the |valid_start| date and invalid after
209 // the |valid_expiry| date.
210 // If we were unable to parse either date from the certificate (or if the cert
211 // lacks either date), the date will be null (i.e., is_null() will be true).
212 const base::Time& valid_start() const { return valid_start_; }
213 const base::Time& valid_expiry() const { return valid_expiry_; }
215 // The fingerprint of this certificate.
216 const SHA1HashValue& fingerprint() const { return fingerprint_; }
218 // The fingerprint of the intermediate CA certificates.
219 const SHA1HashValue& ca_fingerprint() const {
220 return ca_fingerprint_;
223 // Gets the DNS names in the certificate. Pursuant to RFC 2818, Section 3.1
224 // Server Identity, if the certificate has a subjectAltName extension of
225 // type dNSName, this method gets the DNS names in that extension.
226 // Otherwise, it gets the common name in the subject field.
227 void GetDNSNames(std::vector<std::string>* dns_names) const;
229 // Gets the subjectAltName extension field from the certificate, if any.
230 // For future extension; currently this only returns those name types that
231 // are required for HTTP certificate name verification - see VerifyHostname.
232 // Unrequired parameters may be passed as NULL.
233 void GetSubjectAltName(std::vector<std::string>* dns_names,
234 std::vector<std::string>* ip_addrs) const;
236 // Convenience method that returns whether this certificate has expired as of
237 // now.
238 bool HasExpired() const;
240 // Returns true if this object and |other| represent the same certificate.
241 bool Equals(const X509Certificate* other) const;
243 // Returns intermediate certificates added via AddIntermediateCertificate().
244 // Ownership follows the "get" rule: it is the caller's responsibility to
245 // retain the elements of the result.
246 const OSCertHandles& GetIntermediateCertificates() const {
247 return intermediate_ca_certs_;
250 #if defined(OS_MACOSX)
251 // Does this certificate's usage allow SSL client authentication?
252 bool SupportsSSLClientAuth() const;
254 // Returns a new CFMutableArrayRef containing this certificate and its
255 // intermediate certificates in the form expected by Security.framework
256 // and Keychain Services, or NULL on failure.
257 // The first item in the array will be this certificate, followed by its
258 // intermediates, if any.
259 CFMutableArrayRef CreateOSCertChainForCert() const;
260 #endif
262 // Do any of the given issuer names appear in this cert's chain of trust?
263 // |valid_issuers| is a list of DER-encoded X.509 DistinguishedNames.
264 bool IsIssuedByEncoded(const std::vector<std::string>& valid_issuers);
266 #if defined(OS_WIN)
267 // Returns a new PCCERT_CONTEXT containing this certificate and its
268 // intermediate certificates, or NULL on failure. The returned
269 // PCCERT_CONTEXT *MUST NOT* be stored in an X509Certificate, as this will
270 // cause os_cert_handle() to return incorrect results. This function is only
271 // necessary if the CERT_CONTEXT.hCertStore member will be accessed or
272 // enumerated, which is generally true for any CryptoAPI functions involving
273 // certificate chains, including validation or certificate display.
275 // Remarks:
276 // Depending on the CryptoAPI function, Windows may need to access the
277 // HCERTSTORE that the passed-in PCCERT_CONTEXT belongs to, such as to
278 // locate additional intermediates. However, all certificate handles are added
279 // to a NULL HCERTSTORE, allowing the system to manage the resources. As a
280 // result, intermediates for |cert_handle_| cannot be located simply via
281 // |cert_handle_->hCertStore|, as it refers to a magic value indicating
282 // "only this certificate".
284 // To avoid this problems, a new in-memory HCERTSTORE is created containing
285 // just this certificate and its intermediates. The handle to the version of
286 // the current certificate in the new HCERTSTORE is then returned, with the
287 // PCCERT_CONTEXT's HCERTSTORE set to be automatically freed when the returned
288 // certificate handle is freed.
290 // This function is only needed when the HCERTSTORE of the os_cert_handle()
291 // will be accessed, which is generally only during certificate validation
292 // or display. While the returned PCCERT_CONTEXT and its HCERTSTORE can
293 // safely be used on multiple threads if no further modifications happen, it
294 // is generally preferable for each thread that needs such a context to
295 // obtain its own, rather than risk thread-safety issues by sharing.
297 // Because of how X509Certificate caching is implemented, attempting to
298 // create an X509Certificate from the returned PCCERT_CONTEXT may result in
299 // the original handle (and thus the originall HCERTSTORE) being returned by
300 // os_cert_handle(). For this reason, the returned PCCERT_CONTEXT *MUST NOT*
301 // be stored in an X509Certificate.
302 PCCERT_CONTEXT CreateOSCertChainForCert() const;
303 #endif
305 #if defined(USE_OPENSSL_CERTS)
306 // Returns a handle to a global, in-memory certificate store. We
307 // use it for test code, e.g. importing the test server's certificate.
308 static X509_STORE* cert_store();
309 #endif
311 // Verifies that |hostname| matches this certificate.
312 // Does not verify that the certificate is valid, only that the certificate
313 // matches this host.
314 // Returns true if it matches, and updates |*common_name_fallback_used|,
315 // setting it to true if a fallback to the CN was used, rather than
316 // subjectAltName.
317 bool VerifyNameMatch(const std::string& hostname,
318 bool* common_name_fallback_used) const;
320 // Obtains the DER encoded certificate data for |cert_handle|. On success,
321 // returns true and writes the DER encoded certificate to |*der_encoded|.
322 static bool GetDEREncoded(OSCertHandle cert_handle,
323 std::string* der_encoded);
325 // Returns the PEM encoded data from a DER encoded certificate. If the return
326 // value is true, then the PEM encoded certificate is written to
327 // |pem_encoded|.
328 static bool GetPEMEncodedFromDER(const std::string& der_encoded,
329 std::string* pem_encoded);
331 // Returns the PEM encoded data from an OSCertHandle. If the return value is
332 // true, then the PEM encoded certificate is written to |pem_encoded|.
333 static bool GetPEMEncoded(OSCertHandle cert_handle,
334 std::string* pem_encoded);
336 // Encodes the entire certificate chain (this certificate and any
337 // intermediate certificates stored in |intermediate_ca_certs_|) as a series
338 // of PEM encoded strings. Returns true if all certificates were encoded,
339 // storig the result in |*pem_encoded|, with this certificate stored as
340 // the first element.
341 bool GetPEMEncodedChain(std::vector<std::string>* pem_encoded) const;
343 // Sets |*size_bits| to be the length of the public key in bits, and sets
344 // |*type| to one of the |PublicKeyType| values. In case of
345 // |kPublicKeyTypeUnknown|, |*size_bits| will be set to 0.
346 static void GetPublicKeyInfo(OSCertHandle cert_handle,
347 size_t* size_bits,
348 PublicKeyType* type);
350 // Returns the OSCertHandle of this object. Because of caching, this may
351 // differ from the OSCertHandle originally supplied during initialization.
352 // Note: On Windows, CryptoAPI may return unexpected results if this handle
353 // is used across multiple threads. For more details, see
354 // CreateOSCertChainForCert().
355 OSCertHandle os_cert_handle() const { return cert_handle_; }
357 // Returns true if two OSCertHandles refer to identical certificates.
358 static bool IsSameOSCert(OSCertHandle a, OSCertHandle b);
360 // Creates an OS certificate handle from the DER-encoded representation.
361 // Returns NULL on failure.
362 static OSCertHandle CreateOSCertHandleFromBytes(const char* data,
363 int length);
365 #if defined(USE_NSS_CERTS)
366 // Creates an OS certificate handle from the DER-encoded representation.
367 // Returns NULL on failure. Sets the default nickname if |nickname| is
368 // non-NULL.
369 static OSCertHandle CreateOSCertHandleFromBytesWithNickname(
370 const char* data,
371 int length,
372 const char* nickname);
373 #endif
375 // Creates all possible OS certificate handles from |data| encoded in a
376 // specific |format|. Returns an empty collection on failure.
377 static OSCertHandles CreateOSCertHandlesFromBytes(
378 const char* data,
379 int length,
380 Format format);
382 // Duplicates (or adds a reference to) an OS certificate handle.
383 static OSCertHandle DupOSCertHandle(OSCertHandle cert_handle);
385 // Frees (or releases a reference to) an OS certificate handle.
386 static void FreeOSCertHandle(OSCertHandle cert_handle);
388 // Calculates the SHA-1 fingerprint of the certificate. Returns an empty
389 // (all zero) fingerprint on failure.
391 // For calculating fingerprints, prefer SHA-1 for performance when indexing,
392 // but callers should use IsSameOSCert() before assuming two certificates are
393 // the same.
394 static SHA1HashValue CalculateFingerprint(OSCertHandle cert_handle);
396 // Calculates the SHA-256 fingerprint of the certificate. Returns an empty
397 // (all zero) fingerprint on failure.
398 static SHA256HashValue CalculateFingerprint256(OSCertHandle cert_handle);
400 // Calculates the SHA-1 fingerprint of the intermediate CA certificates.
401 // Returns an empty (all zero) fingerprint on failure.
403 // See SHA-1 caveat on CalculateFingerprint().
404 static SHA1HashValue CalculateCAFingerprint(
405 const OSCertHandles& intermediates);
407 // Calculates the SHA-256 fingerprint of the intermediate CA certificates.
408 // Returns an empty (all zero) fingerprint on failure.
410 // As part of the cross-platform implementation of this function, it currently
411 // copies the certificate bytes into local variables which makes it
412 // potentially slower than implementing it directly for each platform. For
413 // now, the expected consumers are not performance critical, but if
414 // performance is a concern going forward, it may warrant implementing this on
415 // a per-platform basis.
416 static SHA256HashValue CalculateCAFingerprint256(
417 const OSCertHandles& intermediates);
419 // Calculates the SHA-256 fingerprint for the complete chain, including the
420 // leaf certificate and all intermediate CA certificates. Returns an empty
421 // (all zero) fingerprint on failure.
422 static SHA256HashValue CalculateChainFingerprint256(
423 OSCertHandle leaf,
424 const OSCertHandles& intermediates);
426 // Returns true if the certificate is self-signed.
427 static bool IsSelfSigned(OSCertHandle cert_handle);
429 private:
430 friend class base::RefCountedThreadSafe<X509Certificate>;
431 friend class TestRootCerts; // For unit tests
433 FRIEND_TEST_ALL_PREFIXES(X509CertificateNameVerifyTest, VerifyHostname);
434 FRIEND_TEST_ALL_PREFIXES(X509CertificateTest, SerialNumbers);
436 // Construct an X509Certificate from a handle to the certificate object
437 // in the underlying crypto library.
438 X509Certificate(OSCertHandle cert_handle,
439 const OSCertHandles& intermediates);
441 ~X509Certificate();
443 // Common object initialization code. Called by the constructors only.
444 void Initialize();
446 #if defined(USE_OPENSSL_CERTS)
447 // Resets the store returned by cert_store() to default state. Used by
448 // TestRootCerts to undo modifications.
449 static void ResetCertStore();
450 #endif
452 // Verifies that |hostname| matches one of the certificate names or IP
453 // addresses supplied, based on TLS name matching rules - specifically,
454 // following http://tools.ietf.org/html/rfc6125.
455 // |cert_common_name| is the Subject CN, e.g. from X509Certificate::subject().
456 // The members of |cert_san_dns_names| and |cert_san_ipaddrs| must be filled
457 // from the dNSName and iPAddress components of the subject alternative name
458 // extension, if present. Note these IP addresses are NOT ascii-encoded:
459 // they must be 4 or 16 bytes of network-ordered data, for IPv4 and IPv6
460 // addresses, respectively.
461 // |common_name_fallback_used| will be updated to true if cert_common_name
462 // was used to match the hostname, or false if either of the |cert_san_*|
463 // parameters was used to match the hostname.
464 static bool VerifyHostname(const std::string& hostname,
465 const std::string& cert_common_name,
466 const std::vector<std::string>& cert_san_dns_names,
467 const std::vector<std::string>& cert_san_ip_addrs,
468 bool* common_name_fallback_used);
470 // Reads a single certificate from |pickle_iter| and returns a
471 // platform-specific certificate handle. The format of the certificate
472 // stored in |pickle_iter| is not guaranteed to be the same across different
473 // underlying cryptographic libraries, nor acceptable to CreateFromBytes().
474 // Returns an invalid handle, NULL, on failure.
475 // NOTE: This should not be used for any new code. It is provided for
476 // migration purposes and should eventually be removed.
477 static OSCertHandle ReadOSCertHandleFromPickle(PickleIterator* pickle_iter);
479 // Writes a single certificate to |pickle| in DER form. Returns false on
480 // failure.
481 static bool WriteOSCertHandleToPickle(OSCertHandle handle, Pickle* pickle);
483 // The subject of the certificate.
484 CertPrincipal subject_;
486 // The issuer of the certificate.
487 CertPrincipal issuer_;
489 // This certificate is not valid before |valid_start_|
490 base::Time valid_start_;
492 // This certificate is not valid after |valid_expiry_|
493 base::Time valid_expiry_;
495 // The fingerprint of this certificate.
496 SHA1HashValue fingerprint_;
498 // The fingerprint of the intermediate CA certificates.
499 SHA1HashValue ca_fingerprint_;
501 // The serial number of this certificate, DER encoded.
502 std::string serial_number_;
504 // A handle to the certificate object in the underlying crypto library.
505 OSCertHandle cert_handle_;
507 // Untrusted intermediate certificates associated with this certificate
508 // that may be needed for chain building.
509 OSCertHandles intermediate_ca_certs_;
511 #if defined(USE_NSS_CERTS)
512 // This stores any default nickname that has been set on the certificate
513 // at creation time with CreateFromBytesWithNickname.
514 // If this is empty, then GetDefaultNickname will return a generated name
515 // based on the type of the certificate.
516 std::string default_nickname_;
517 #endif
519 DISALLOW_COPY_AND_ASSIGN(X509Certificate);
522 } // namespace net
524 #endif // NET_CERT_X509_CERTIFICATE_H_