Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1213)

Side by Side Diff: net/base/x509_certificate.h

Issue 13006020: net: extract net/cert out of net/base (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: rebase Created 7 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « net/base/x509_cert_types_win.cc ('k') | net/base/x509_certificate.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
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_BASE_X509_CERTIFICATE_H_
6 #define NET_BASE_X509_CERTIFICATE_H_
7
8 #include <string.h>
9
10 #include <string>
11 #include <vector>
12
13 #include "base/gtest_prod_util.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/string_piece.h"
16 #include "base/time.h"
17 #include "net/base/cert_type.h"
18 #include "net/base/net_export.h"
19 #include "net/base/x509_cert_types.h"
20
21 #if defined(OS_WIN)
22 #include <windows.h>
23 #include <wincrypt.h>
24 #elif defined(OS_MACOSX)
25 #include <CoreFoundation/CFArray.h>
26 #include <Security/SecBase.h>
27
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;
35 #endif
36
37 class Pickle;
38 class PickleIterator;
39
40 namespace crypto {
41 class RSAPrivateKey;
42 } // namespace crypto
43
44 namespace net {
45
46 class CRLSet;
47 class CertVerifyResult;
48
49 typedef std::vector<scoped_refptr<X509Certificate> > CertificateList;
50
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> {
57 public:
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.
61 #if defined(OS_WIN)
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;
69 #else
70 // TODO(ericroman): not implemented
71 typedef void* OSCertHandle;
72 #endif
73
74 typedef std::vector<OSCertHandle> OSCertHandles;
75
76 enum PublicKeyType {
77 kPublicKeyTypeUnknown,
78 kPublicKeyTypeRSA,
79 kPublicKeyTypeDSA,
80 kPublicKeyTypeECDSA,
81 kPublicKeyTypeDH,
82 kPublicKeyTypeECDH
83 };
84
85 // Predicate functor used in maps when X509Certificate is used as the key.
86 class NET_EXPORT LessThan {
87 public:
88 bool operator() (X509Certificate* lhs, X509Certificate* rhs) const;
89 };
90
91 enum Format {
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,
96
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,
101
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,
107
108 // Automatically detect the format.
109 FORMAT_AUTO = FORMAT_SINGLE_CERTIFICATE | FORMAT_PEM_CERT_SEQUENCE |
110 FORMAT_PKCS7,
111 };
112
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.
117 enum PickleType {
118 // When reading a certificate from a Pickle, the Pickle only contains a
119 // single certificate.
120 PICKLETYPE_SINGLE_CERTIFICATE,
121
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
126 // or 64 bits.
127 PICKLETYPE_CERTIFICATE_CHAIN_V2,
128
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,
135 };
136
137 // Creates a X509Certificate from the ground up. Used by tests that simulate
138 // SSL connections.
139 X509Certificate(const std::string& subject, const std::string& issuer,
140 base::Time start_date, base::Time expiration_date);
141
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);
147
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);
155
156 // Create an X509Certificate from the DER-encoded representation.
157 // Returns NULL on failure.
158 //
159 // The returned pointer must be stored in a scoped_refptr<X509Certificate>.
160 static X509Certificate* CreateFromBytes(const char* data, int length);
161
162 #if defined(USE_NSS)
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>.
167 //
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,
171 int length,
172 const char* nickname);
173
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;
178 #endif
179
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.
184 //
185 // The returned pointer must be stored in a scoped_refptr<X509Certificate>.
186 static X509Certificate* CreateFromPickle(const Pickle& pickle,
187 PickleIterator* pickle_iter,
188 PickleType type);
189
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,
195 int length,
196 int format);
197
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.
202 //
203 // |subject| is a distinguished name defined in RFC4514.
204 //
205 // An example:
206 // CN=Michael Wong,O=FooBar Corporation,DC=foobar,DC=com
207 //
208 // SECURITY WARNING
209 //
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.
214 //
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);
220
221 // Appends a representation of this object to the given pickle.
222 void Persist(Pickle* pickle);
223
224 // The serial number, DER encoded, possibly including a leading 00 byte.
225 const std::string& serial_number() const { return serial_number_; }
226
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_; }
231
232 // The issuer of the certificate.
233 const CertPrincipal& issuer() const { return issuer_; }
234
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_; }
242
243 // The fingerprint of this certificate.
244 const SHA1HashValue& fingerprint() const { return fingerprint_; }
245
246 // The fingerprint of the intermediate CA certificates.
247 const SHA1HashValue& ca_fingerprint() const {
248 return ca_fingerprint_;
249 }
250
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;
256
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;
263
264 // Convenience method that returns whether this certificate has expired as of
265 // now.
266 bool HasExpired() const;
267
268 // Returns true if this object and |other| represent the same certificate.
269 bool Equals(const X509Certificate* other) const;
270
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_;
276 }
277
278 #if defined(OS_MACOSX)
279 // Does this certificate's usage allow SSL client authentication?
280 bool SupportsSSLClientAuth() const;
281
282 // Creates the chain of certs to use for this client identity cert.
283 CFArrayRef CreateClientCertificateChain() const;
284
285 // Returns a new CFArrayRef containing this certificate and its intermediate
286 // certificates in the form expected by Security.framework and Keychain
287 // Services, or NULL on failure.
288 // The first item in the array will be this certificate, followed by its
289 // intermediates, if any.
290 CFArrayRef CreateOSCertChainForCert() const;
291 #endif
292
293 // Do any of the given issuer names appear in this cert's chain of trust?
294 // |valid_issuers| is a list of DER-encoded X.509 DistinguishedNames.
295 bool IsIssuedByEncoded(const std::vector<std::string>& valid_issuers);
296
297 #if defined(OS_WIN)
298 // Returns a new PCCERT_CONTEXT containing this certificate and its
299 // intermediate certificates, or NULL on failure. The returned
300 // PCCERT_CONTEXT *MUST NOT* be stored in an X509Certificate, as this will
301 // cause os_cert_handle() to return incorrect results. This function is only
302 // necessary if the CERT_CONTEXT.hCertStore member will be accessed or
303 // enumerated, which is generally true for any CryptoAPI functions involving
304 // certificate chains, including validation or certificate display.
305 //
306 // Remarks:
307 // Depending on the CryptoAPI function, Windows may need to access the
308 // HCERTSTORE that the passed-in PCCERT_CONTEXT belongs to, such as to
309 // locate additional intermediates. However, all certificate handles are added
310 // to a NULL HCERTSTORE, allowing the system to manage the resources. As a
311 // result, intermediates for |cert_handle_| cannot be located simply via
312 // |cert_handle_->hCertStore|, as it refers to a magic value indicating
313 // "only this certificate".
314 //
315 // To avoid this problems, a new in-memory HCERTSTORE is created containing
316 // just this certificate and its intermediates. The handle to the version of
317 // the current certificate in the new HCERTSTORE is then returned, with the
318 // PCCERT_CONTEXT's HCERTSTORE set to be automatically freed when the returned
319 // certificate handle is freed.
320 //
321 // This function is only needed when the HCERTSTORE of the os_cert_handle()
322 // will be accessed, which is generally only during certificate validation
323 // or display. While the returned PCCERT_CONTEXT and its HCERTSTORE can
324 // safely be used on multiple threads if no further modifications happen, it
325 // is generally preferable for each thread that needs such a context to
326 // obtain its own, rather than risk thread-safety issues by sharing.
327 //
328 // Because of how X509Certificate caching is implemented, attempting to
329 // create an X509Certificate from the returned PCCERT_CONTEXT may result in
330 // the original handle (and thus the originall HCERTSTORE) being returned by
331 // os_cert_handle(). For this reason, the returned PCCERT_CONTEXT *MUST NOT*
332 // be stored in an X509Certificate.
333 PCCERT_CONTEXT CreateOSCertChainForCert() const;
334 #endif
335
336 #if defined(USE_OPENSSL)
337 // Returns a handle to a global, in-memory certificate store. We
338 // use it for test code, e.g. importing the test server's certificate.
339 static X509_STORE* cert_store();
340 #endif
341
342 // Verifies that |hostname| matches this certificate.
343 // Does not verify that the certificate is valid, only that the certificate
344 // matches this host.
345 // Returns true if it matches.
346 bool VerifyNameMatch(const std::string& hostname) const;
347
348 // Obtains the DER encoded certificate data for |cert_handle|. On success,
349 // returns true and writes the DER encoded certificate to |*der_encoded|.
350 static bool GetDEREncoded(OSCertHandle cert_handle,
351 std::string* der_encoded);
352
353 // Returns the PEM encoded data from an OSCertHandle. If the return value is
354 // true, then the PEM encoded certificate is written to |pem_encoded|.
355 static bool GetPEMEncoded(OSCertHandle cert_handle,
356 std::string* pem_encoded);
357
358 // Encodes the entire certificate chain (this certificate and any
359 // intermediate certificates stored in |intermediate_ca_certs_|) as a series
360 // of PEM encoded strings. Returns true if all certificates were encoded,
361 // storig the result in |*pem_encoded|, with this certificate stored as
362 // the first element.
363 bool GetPEMEncodedChain(std::vector<std::string>* pem_encoded) const;
364
365 // Sets |*size_bits| to be the length of the public key in bits, and sets
366 // |*type| to one of the |PublicKeyType| values. In case of
367 // |kPublicKeyTypeUnknown|, |*size_bits| will be set to 0.
368 static void GetPublicKeyInfo(OSCertHandle cert_handle,
369 size_t* size_bits,
370 PublicKeyType* type);
371
372 // Returns the OSCertHandle of this object. Because of caching, this may
373 // differ from the OSCertHandle originally supplied during initialization.
374 // Note: On Windows, CryptoAPI may return unexpected results if this handle
375 // is used across multiple threads. For more details, see
376 // CreateOSCertChainForCert().
377 OSCertHandle os_cert_handle() const { return cert_handle_; }
378
379 // Returns true if two OSCertHandles refer to identical certificates.
380 static bool IsSameOSCert(OSCertHandle a, OSCertHandle b);
381
382 // Creates an OS certificate handle from the DER-encoded representation.
383 // Returns NULL on failure.
384 static OSCertHandle CreateOSCertHandleFromBytes(const char* data,
385 int length);
386
387 #if defined(USE_NSS)
388 // Creates an OS certificate handle from the DER-encoded representation.
389 // Returns NULL on failure. Sets the default nickname if |nickname| is
390 // non-NULL.
391 static OSCertHandle CreateOSCertHandleFromBytesWithNickname(
392 const char* data,
393 int length,
394 const char* nickname);
395 #endif
396
397 // Creates all possible OS certificate handles from |data| encoded in a
398 // specific |format|. Returns an empty collection on failure.
399 static OSCertHandles CreateOSCertHandlesFromBytes(
400 const char* data,
401 int length,
402 Format format);
403
404 // Duplicates (or adds a reference to) an OS certificate handle.
405 static OSCertHandle DupOSCertHandle(OSCertHandle cert_handle);
406
407 // Frees (or releases a reference to) an OS certificate handle.
408 static void FreeOSCertHandle(OSCertHandle cert_handle);
409
410 // Calculates the SHA-1 fingerprint of the certificate. Returns an empty
411 // (all zero) fingerprint on failure.
412 static SHA1HashValue CalculateFingerprint(OSCertHandle cert_handle);
413
414 // Calculates the SHA-1 fingerprint of the intermediate CA certificates.
415 // Returns an empty (all zero) fingerprint on failure.
416 static SHA1HashValue CalculateCAFingerprint(
417 const OSCertHandles& intermediates);
418
419 private:
420 friend class base::RefCountedThreadSafe<X509Certificate>;
421 friend class TestRootCerts; // For unit tests
422
423 FRIEND_TEST_ALL_PREFIXES(X509CertificateNameVerifyTest, VerifyHostname);
424 FRIEND_TEST_ALL_PREFIXES(X509CertificateTest, SerialNumbers);
425
426 // Construct an X509Certificate from a handle to the certificate object
427 // in the underlying crypto library.
428 X509Certificate(OSCertHandle cert_handle,
429 const OSCertHandles& intermediates);
430
431 ~X509Certificate();
432
433 // Common object initialization code. Called by the constructors only.
434 void Initialize();
435
436 #if defined(USE_OPENSSL)
437 // Resets the store returned by cert_store() to default state. Used by
438 // TestRootCerts to undo modifications.
439 static void ResetCertStore();
440 #endif
441
442 // Verifies that |hostname| matches one of the certificate names or IP
443 // addresses supplied, based on TLS name matching rules - specifically,
444 // following http://tools.ietf.org/html/rfc6125.
445 // |cert_common_name| is the Subject CN, e.g. from X509Certificate::subject().
446 // The members of |cert_san_dns_names| and |cert_san_ipaddrs| must be filled
447 // from the dNSName and iPAddress components of the subject alternative name
448 // extension, if present. Note these IP addresses are NOT ascii-encoded:
449 // they must be 4 or 16 bytes of network-ordered data, for IPv4 and IPv6
450 // addresses, respectively.
451 static bool VerifyHostname(const std::string& hostname,
452 const std::string& cert_common_name,
453 const std::vector<std::string>& cert_san_dns_names,
454 const std::vector<std::string>& cert_san_ip_addrs);
455
456 // Reads a single certificate from |pickle_iter| and returns a
457 // platform-specific certificate handle. The format of the certificate
458 // stored in |pickle_iter| is not guaranteed to be the same across different
459 // underlying cryptographic libraries, nor acceptable to CreateFromBytes().
460 // Returns an invalid handle, NULL, on failure.
461 // NOTE: This should not be used for any new code. It is provided for
462 // migration purposes and should eventually be removed.
463 static OSCertHandle ReadOSCertHandleFromPickle(PickleIterator* pickle_iter);
464
465 // Writes a single certificate to |pickle| in DER form. Returns false on
466 // failure.
467 static bool WriteOSCertHandleToPickle(OSCertHandle handle, Pickle* pickle);
468
469 // The subject of the certificate.
470 CertPrincipal subject_;
471
472 // The issuer of the certificate.
473 CertPrincipal issuer_;
474
475 // This certificate is not valid before |valid_start_|
476 base::Time valid_start_;
477
478 // This certificate is not valid after |valid_expiry_|
479 base::Time valid_expiry_;
480
481 // The fingerprint of this certificate.
482 SHA1HashValue fingerprint_;
483
484 // The fingerprint of the intermediate CA certificates.
485 SHA1HashValue ca_fingerprint_;
486
487 // The serial number of this certificate, DER encoded.
488 std::string serial_number_;
489
490 // A handle to the certificate object in the underlying crypto library.
491 OSCertHandle cert_handle_;
492
493 // Untrusted intermediate certificates associated with this certificate
494 // that may be needed for chain building.
495 OSCertHandles intermediate_ca_certs_;
496
497 #if defined(USE_NSS)
498 // This stores any default nickname that has been set on the certificate
499 // at creation time with CreateFromBytesWithNickname.
500 // If this is empty, then GetDefaultNickname will return a generated name
501 // based on the type of the certificate.
502 std::string default_nickname_;
503 #endif
504
505 DISALLOW_COPY_AND_ASSIGN(X509Certificate);
506 };
507
508 } // namespace net
509
510 #endif // NET_BASE_X509_CERTIFICATE_H_
OLDNEW
« no previous file with comments | « net/base/x509_cert_types_win.cc ('k') | net/base/x509_certificate.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698