Home | History | Annotate | Download | only in base
      1 // Copyright (c) 2011 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 #pragma once
      8 
      9 #include <string.h>
     10 
     11 #include <string>
     12 #include <vector>
     13 
     14 #include "base/gtest_prod_util.h"
     15 #include "base/memory/ref_counted.h"
     16 #include "base/string_piece.h"
     17 #include "base/time.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 #include "base/synchronization/lock.h"
     29 #elif defined(USE_OPENSSL)
     30 // Forward declaration; real one in <x509.h>
     31 struct x509_st;
     32 typedef struct x509_store_st X509_STORE;
     33 #elif defined(USE_NSS)
     34 // Forward declaration; real one in <cert.h>
     35 struct CERTCertificateStr;
     36 #endif
     37 
     38 class Pickle;
     39 
     40 namespace crypto {
     41 class StringPiece;
     42 class RSAPrivateKey;
     43 }  // namespace crypto
     44 
     45 namespace net {
     46 
     47 class CertVerifyResult;
     48 
     49 typedef std::vector<scoped_refptr<X509Certificate> > CertificateList;
     50 
     51 // X509Certificate represents an X.509 certificate used by SSL.
     52 class NET_EXPORT X509Certificate : public base::RefCountedThreadSafe<X509Certificate> {
     53  public:
     54   // A handle to the certificate object in the underlying crypto library.
     55   // We assume that OSCertHandle is a pointer type on all platforms and
     56   // NULL is an invalid OSCertHandle.
     57 #if defined(OS_WIN)
     58   typedef PCCERT_CONTEXT OSCertHandle;
     59 #elif defined(OS_MACOSX)
     60   typedef SecCertificateRef OSCertHandle;
     61 #elif defined(USE_OPENSSL)
     62   typedef struct x509_st* OSCertHandle;
     63 #elif defined(USE_NSS)
     64   typedef struct CERTCertificateStr* OSCertHandle;
     65 #else
     66   // TODO(ericroman): not implemented
     67   typedef void* OSCertHandle;
     68 #endif
     69 
     70   typedef std::vector<OSCertHandle> OSCertHandles;
     71 
     72   // Predicate functor used in maps when X509Certificate is used as the key.
     73   class LessThan {
     74    public:
     75     bool operator() (X509Certificate* lhs,  X509Certificate* rhs) const;
     76   };
     77 
     78   // Where the certificate comes from.  The enumeration constants are
     79   // listed in increasing order of preference.
     80   enum Source {
     81     SOURCE_UNUSED = 0,            // The source_ member is not used.
     82     SOURCE_LONE_CERT_IMPORT = 1,  // From importing a certificate without
     83                                   // any intermediate CA certificates.
     84     SOURCE_FROM_CACHE = 2,        // From the disk cache - which contains
     85                                   // intermediate CA certificates, but may be
     86                                   // stale.
     87     SOURCE_FROM_NETWORK = 3,      // From the network.
     88   };
     89 
     90   enum VerifyFlags {
     91     VERIFY_REV_CHECKING_ENABLED = 1 << 0,
     92     VERIFY_EV_CERT = 1 << 1,
     93   };
     94 
     95   enum Format {
     96     // The data contains a single DER-encoded certificate, or a PEM-encoded
     97     // DER certificate with the PEM encoding block name of "CERTIFICATE".
     98     // Any subsequent blocks will be ignored.
     99     FORMAT_SINGLE_CERTIFICATE = 1 << 0,
    100 
    101     // The data contains a sequence of one or more PEM-encoded, DER
    102     // certificates, with the PEM encoding block name of "CERTIFICATE".
    103     // All PEM blocks will be parsed, until the first error is encountered.
    104     FORMAT_PEM_CERT_SEQUENCE = 1 << 1,
    105 
    106     // The data contains a PKCS#7 SignedData structure, whose certificates
    107     // member is to be used to initialize the certificate and intermediates.
    108     // The data may further be encoded using PEM, specifying block names of
    109     // either "PKCS7" or "CERTIFICATE".
    110     FORMAT_PKCS7 = 1 << 2,
    111 
    112     // Automatically detect the format.
    113     FORMAT_AUTO = FORMAT_SINGLE_CERTIFICATE | FORMAT_PEM_CERT_SEQUENCE |
    114                   FORMAT_PKCS7,
    115   };
    116 
    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     PICKLETYPE_CERTIFICATE_CHAIN,
    126   };
    127 
    128   // Creates a X509Certificate from the ground up.  Used by tests that simulate
    129   // SSL connections.
    130   X509Certificate(const std::string& subject, const std::string& issuer,
    131                   base::Time start_date, base::Time expiration_date);
    132 
    133   // Create an X509Certificate from a handle to the certificate object in the
    134   // underlying crypto library. |source| specifies where |cert_handle| comes
    135   // from.  Given two certificate handles for the same certificate, our
    136   // certificate cache prefers the handle from the network because our HTTP
    137   // cache isn't caching the corresponding intermediate CA certificates yet
    138   // (http://crbug.com/7065).
    139   // The returned pointer must be stored in a scoped_refptr<X509Certificate>.
    140   static scoped_refptr<X509Certificate> CreateFromHandle(OSCertHandle cert_handle,
    141                                            Source source,
    142                                            const OSCertHandles& intermediates);
    143 
    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. See the comment for |CreateFromHandle| about the |source|
    148   // argument.
    149   // The returned pointer must be stored in a scoped_refptr<X509Certificate>.
    150   static scoped_refptr<X509Certificate> CreateFromDERCertChain(
    151       const std::vector<base::StringPiece>& der_certs);
    152 
    153   // Create an X509Certificate from the DER-encoded representation.
    154   // Returns NULL on failure.
    155   //
    156   // The returned pointer must be stored in a scoped_refptr<X509Certificate>.
    157   static scoped_refptr<X509Certificate> CreateFromBytes(const char* data, int length);
    158 
    159   // Create an X509Certificate from the representation stored in the given
    160   // pickle.  The data for this object is found relative to the given
    161   // pickle_iter, which should be passed to the pickle's various Read* methods.
    162   // Returns NULL on failure.
    163   //
    164   // The returned pointer must be stored in a scoped_refptr<X509Certificate>.
    165   static scoped_refptr<X509Certificate> CreateFromPickle(const Pickle& pickle,
    166                                            void** pickle_iter,
    167                                            PickleType type);
    168 
    169   // Parses all of the certificates possible from |data|. |format| is a
    170   // bit-wise OR of Format, indicating the possible formats the
    171   // certificates may have been serialized as. If an error occurs, an empty
    172   // collection will be returned.
    173   static CertificateList CreateCertificateListFromBytes(const char* data,
    174                                                         int length,
    175                                                         int format);
    176 
    177   // Create a self-signed certificate containing the public key in |key|.
    178   // Subject, serial number and validity period are given as parameters.
    179   // The certificate is signed by the private key in |key|. The hashing
    180   // algorithm for the signature is SHA-1.
    181   //
    182   // |subject| is a distinguished name defined in RFC4514.
    183   //
    184   // An example:
    185   // CN=Michael Wong,O=FooBar Corporation,DC=foobar,DC=com
    186   //
    187   // SECURITY WARNING
    188   //
    189   // Using self-signed certificates has the following security risks:
    190   // 1. Encryption without authentication and thus vulnerable to
    191   //    man-in-the-middle attacks.
    192   // 2. Self-signed certificates cannot be revoked.
    193   //
    194   // Use this certificate only after the above risks are acknowledged.
    195   static scoped_refptr<X509Certificate> CreateSelfSigned(crypto::RSAPrivateKey* key,
    196                                            const std::string& subject,
    197                                            uint32 serial_number,
    198                                            base::TimeDelta valid_duration);
    199 
    200   // Appends a representation of this object to the given pickle.
    201   void Persist(Pickle* pickle);
    202 
    203   // The subject of the certificate.  For HTTPS server certificates, this
    204   // represents the web server.  The common name of the subject should match
    205   // the host name of the web server.
    206   const CertPrincipal& subject() const { return subject_; }
    207 
    208   // The issuer of the certificate.
    209   const CertPrincipal& issuer() const { return issuer_; }
    210 
    211   // Time period during which the certificate is valid.  More precisely, this
    212   // certificate is invalid before the |valid_start| date and invalid after
    213   // the |valid_expiry| date.
    214   // If we were unable to parse either date from the certificate (or if the cert
    215   // lacks either date), the date will be null (i.e., is_null() will be true).
    216   const base::Time& valid_start() const { return valid_start_; }
    217   const base::Time& valid_expiry() const { return valid_expiry_; }
    218 
    219   // The fingerprint of this certificate.
    220   const SHA1Fingerprint& fingerprint() const { return fingerprint_; }
    221 
    222   // Gets the DNS names in the certificate.  Pursuant to RFC 2818, Section 3.1
    223   // Server Identity, if the certificate has a subjectAltName extension of
    224   // type dNSName, this method gets the DNS names in that extension.
    225   // Otherwise, it gets the common name in the subject field.
    226   void GetDNSNames(std::vector<std::string>* dns_names) const;
    227 
    228   // Convenience method that returns whether this certificate has expired as of
    229   // now.
    230   bool HasExpired() const;
    231 
    232   // Returns true if this object and |other| represent the same certificate.
    233   bool Equals(const X509Certificate* other) const;
    234 
    235   // Returns intermediate certificates added via AddIntermediateCertificate().
    236   // Ownership follows the "get" rule: it is the caller's responsibility to
    237   // retain the elements of the result.
    238   const OSCertHandles& GetIntermediateCertificates() const {
    239     return intermediate_ca_certs_;
    240   }
    241 
    242   // Returns true if I already contain the given intermediate cert.
    243   bool HasIntermediateCertificate(OSCertHandle cert);
    244 
    245   // Returns true if I already contain all the given intermediate certs.
    246   bool HasIntermediateCertificates(const OSCertHandles& certs);
    247 
    248 #if defined(OS_MACOSX)
    249   // Does this certificate's usage allow SSL client authentication?
    250   bool SupportsSSLClientAuth() const;
    251 
    252   // Do any of the given issuer names appear in this cert's chain of trust?
    253   bool IsIssuedBy(const std::vector<CertPrincipal>& valid_issuers);
    254 
    255   // Creates a security policy for SSL client certificates.
    256   static OSStatus CreateSSLClientPolicy(SecPolicyRef* outPolicy);
    257 
    258   // Adds all available SSL client identity certs to the given vector.
    259   // |server_domain| is a hint for which domain the cert is to be sent to
    260   // (a cert previously specified as the default for that domain will be given
    261   // precedence and returned first in the output vector.)
    262   // If valid_issuers is non-empty, only certs that were transitively issued by
    263   // one of the given names will be included in the list.
    264   static bool GetSSLClientCertificates(
    265       const std::string& server_domain,
    266       const std::vector<CertPrincipal>& valid_issuers,
    267       CertificateList* certs);
    268 
    269   // Creates the chain of certs to use for this client identity cert.
    270   CFArrayRef CreateClientCertificateChain() const;
    271 #endif
    272 
    273 #if defined(OS_WIN)
    274   // Returns a handle to a global, in-memory certificate store. We use it for
    275   // two purposes:
    276   // 1. Import server certificates into this store so that we can verify and
    277   //    display the certificates using CryptoAPI.
    278   // 2. Copy client certificates from the "MY" system certificate store into
    279   //    this store so that we can close the system store when we finish
    280   //    searching for client certificates.
    281   static HCERTSTORE cert_store();
    282 #endif
    283 
    284 #if defined(USE_OPENSSL)
    285   // Returns a handle to a global, in-memory certificate store. We
    286   // use it for test code, e.g. importing the test server's certificate.
    287   static X509_STORE* cert_store();
    288 #endif
    289 
    290 #if defined(ANDROID)
    291   // Returns the certificate chain in DER-encoded form, using the application DER
    292   // cache as appropriate.
    293   void GetChainDEREncodedBytes(std::vector<std::string>* chain_bytes) const;
    294 #endif
    295 
    296   // Verifies the certificate against the given hostname.  Returns OK if
    297   // successful or an error code upon failure.
    298   //
    299   // The |*verify_result| structure, including the |verify_result->cert_status|
    300   // bitmask, is always filled out regardless of the return value.  If the
    301   // certificate has multiple errors, the corresponding status flags are set in
    302   // |verify_result->cert_status|, and the error code for the most serious
    303   // error is returned.
    304   //
    305   // |flags| is bitwise OR'd of VerifyFlags.
    306   // If VERIFY_REV_CHECKING_ENABLED is set in |flags|, certificate revocation
    307   // checking is performed.  If VERIFY_EV_CERT is set in |flags| too,
    308   // EV certificate verification is performed.
    309   int Verify(const std::string& hostname,
    310              int flags,
    311              CertVerifyResult* verify_result) const;
    312 
    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.
    317   //
    318   // WARNING:  This function may return false negatives (for example, if
    319   //           |hostname| is an IP address literal) on some platforms.  Only
    320   //           use in cases where some false-positives are acceptible.
    321   bool VerifyNameMatch(const std::string& hostname) const;
    322 
    323   // This method returns the DER encoded certificate.
    324   // If the return value is true then the DER encoded certificate is available.
    325   // The content of the DER encoded certificate is written to |encoded|.
    326   bool GetDEREncoded(std::string* encoded);
    327 
    328   OSCertHandle os_cert_handle() const { return cert_handle_; }
    329 
    330   // Returns true if two OSCertHandles refer to identical certificates.
    331   static bool IsSameOSCert(OSCertHandle a, OSCertHandle b);
    332 
    333   // Creates an OS certificate handle from the BER-encoded representation.
    334   // Returns NULL on failure.
    335   static OSCertHandle CreateOSCertHandleFromBytes(const char* data,
    336                                                   int length);
    337 
    338   // Creates all possible OS certificate handles from |data| encoded in a
    339   // specific |format|. Returns an empty collection on failure.
    340   static OSCertHandles CreateOSCertHandlesFromBytes(
    341       const char* data, int length, Format format);
    342 
    343   // Duplicates (or adds a reference to) an OS certificate handle.
    344   static OSCertHandle DupOSCertHandle(OSCertHandle cert_handle);
    345 
    346   // Frees (or releases a reference to) an OS certificate handle.
    347   static void FreeOSCertHandle(OSCertHandle cert_handle);
    348 
    349  private:
    350   friend class base::RefCountedThreadSafe<X509Certificate>;
    351   friend class TestRootCerts;  // For unit tests
    352   FRIEND_TEST_ALL_PREFIXES(X509CertificateTest, Cache);
    353   FRIEND_TEST_ALL_PREFIXES(X509CertificateTest, IntermediateCertificates);
    354   FRIEND_TEST_ALL_PREFIXES(X509CertificateTest, SerialNumbers);
    355   FRIEND_TEST_ALL_PREFIXES(X509CertificateNameVerifyTest, VerifyHostname);
    356 
    357   // Construct an X509Certificate from a handle to the certificate object
    358   // in the underlying crypto library.
    359   X509Certificate(OSCertHandle cert_handle, Source source,
    360                   const OSCertHandles& intermediates);
    361 
    362   ~X509Certificate();
    363 
    364   // Common object initialization code.  Called by the constructors only.
    365   void Initialize();
    366 
    367 #if defined(OS_WIN)
    368   bool CheckEV(PCCERT_CHAIN_CONTEXT chain_context,
    369                const char* policy_oid) const;
    370   static bool IsIssuedByKnownRoot(PCCERT_CHAIN_CONTEXT chain_context);
    371 #endif
    372 #if defined(OS_MACOSX)
    373   static bool IsIssuedByKnownRoot(CFArrayRef chain);
    374 #endif
    375   bool VerifyEV() const;
    376 
    377 #if defined(USE_OPENSSL)
    378   // Resets the store returned by cert_store() to default state. Used by
    379   // TestRootCerts to undo modifications.
    380   static void ResetCertStore();
    381 #endif
    382 
    383   // Calculates the SHA-1 fingerprint of the certificate.  Returns an empty
    384   // (all zero) fingerprint on failure.
    385   static SHA1Fingerprint CalculateFingerprint(OSCertHandle cert_handle);
    386 
    387   // Verifies that |hostname| matches one of the names in |cert_names|, based on
    388   // TLS name matching rules, specifically following http://tools.ietf.org/html/draft-saintandre-tls-server-id-check-09#section-4.4.3
    389   // The members of |cert_names| must have been extracted from the Subject CN or
    390   // SAN fields of a certificate.
    391   // WARNING:  This function may return false negatives (for example, if
    392   //           |hostname| is an IP address literal) on some platforms.  Only
    393   //           use in cases where some false-positives are acceptible.
    394   static bool VerifyHostname(const std::string& hostname,
    395                              const std::vector<std::string>& cert_names);
    396 
    397   // The serial number, DER encoded.
    398   // NOTE: keep this method private, used by IsBlacklisted only.  To simplify
    399   // IsBlacklisted, we strip the leading 0 byte of a serial number, used to
    400   // encode a positive DER INTEGER (a signed type) with a most significant bit
    401   // of 1.  Other code must not use this method for general purpose until this
    402   // is fixed.
    403   const std::string& serial_number() const { return serial_number_; }
    404 
    405   // IsBlacklisted returns true if this certificate is explicitly blacklisted.
    406   bool IsBlacklisted() const;
    407 
    408   // IsPublicKeyBlacklisted returns true iff one of |public_key_hashes| (which
    409   // are SHA1 hashes of SubjectPublicKeyInfo structures) is explicitly blocked.
    410   static bool IsPublicKeyBlacklisted(
    411       const std::vector<SHA1Fingerprint>& public_key_hashes);
    412 
    413   // IsSHA1HashInSortedArray returns true iff |hash| is in |array|, a sorted
    414   // array of SHA1 hashes.
    415   static bool IsSHA1HashInSortedArray(const SHA1Fingerprint& hash,
    416                                       const uint8* array,
    417                                       size_t array_byte_len);
    418 
    419   // Reads a single certificate from |pickle| and returns a platform-specific
    420   // certificate handle. The format of the certificate stored in |pickle| is
    421   // not guaranteed to be the same across different underlying cryptographic
    422   // libraries, nor acceptable to CreateFromBytes(). Returns an invalid
    423   // handle, NULL, on failure.
    424   static OSCertHandle ReadCertHandleFromPickle(const Pickle& pickle,
    425                                                void** pickle_iter);
    426 
    427   // Writes a single certificate to |pickle|. Returns false on failure.
    428   static bool WriteCertHandleToPickle(OSCertHandle handle, Pickle* pickle);
    429 
    430 #ifdef ANDROID
    431 #if defined(USE_OPENSSL)
    432   // Returns the certificate in DER-encoded form, using the application DER
    433   // cache as appropriate. The returned string piece will be valid as long
    434   // as the handle is.
    435   static std::string GetDEREncodedBytes(OSCertHandle handle);
    436 #endif
    437 #endif
    438 
    439   // The subject of the certificate.
    440   CertPrincipal subject_;
    441 
    442   // The issuer of the certificate.
    443   CertPrincipal issuer_;
    444 
    445   // This certificate is not valid before |valid_start_|
    446   base::Time valid_start_;
    447 
    448   // This certificate is not valid after |valid_expiry_|
    449   base::Time valid_expiry_;
    450 
    451   // The fingerprint of this certificate.
    452   SHA1Fingerprint fingerprint_;
    453 
    454   // The serial number of this certificate, DER encoded.
    455   std::string serial_number_;
    456 
    457   // A handle to the certificate object in the underlying crypto library.
    458   OSCertHandle cert_handle_;
    459 
    460   // Untrusted intermediate certificates associated with this certificate
    461   // that may be needed for chain building.
    462   OSCertHandles intermediate_ca_certs_;
    463 
    464 #if defined(OS_MACOSX)
    465   // Blocks multiple threads from verifying the cert simultaneously.
    466   // (Marked mutable because it's used in a const method.)
    467   mutable base::Lock verification_lock_;
    468 #endif
    469 
    470   // Where the certificate comes from.
    471   Source source_;
    472 
    473   DISALLOW_COPY_AND_ASSIGN(X509Certificate);
    474 };
    475 
    476 }  // namespace net
    477 
    478 #endif  // NET_BASE_X509_CERTIFICATE_H_
    479