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