Home | History | Annotate | Download | only in base
      1 /*
      2  * libjingle
      3  * Copyright 2004, Google Inc.
      4  *
      5  * Redistribution and use in source and binary forms, with or without
      6  * modification, are permitted provided that the following conditions are met:
      7  *
      8  *  1. Redistributions of source code must retain the above copyright notice,
      9  *     this list of conditions and the following disclaimer.
     10  *  2. Redistributions in binary form must reproduce the above copyright notice,
     11  *     this list of conditions and the following disclaimer in the documentation
     12  *     and/or other materials provided with the distribution.
     13  *  3. The name of the author may not be used to endorse or promote products
     14  *     derived from this software without specific prior written permission.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
     17  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
     18  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
     19  * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     20  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
     22  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
     23  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
     24  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
     25  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     26  */
     27 
     28 // Handling of certificates and keypairs for SSLStreamAdapter's peer mode.
     29 
     30 #ifndef TALK_BASE_SSLIDENTITY_H_
     31 #define TALK_BASE_SSLIDENTITY_H_
     32 
     33 #include <algorithm>
     34 #include <string>
     35 #include <vector>
     36 
     37 #include "talk/base/buffer.h"
     38 #include "talk/base/messagedigest.h"
     39 
     40 namespace talk_base {
     41 
     42 // Forward declaration due to circular dependency with SSLCertificate.
     43 class SSLCertChain;
     44 
     45 // Abstract interface overridden by SSL library specific
     46 // implementations.
     47 
     48 // A somewhat opaque type used to encapsulate a certificate.
     49 // Wraps the SSL library's notion of a certificate, with reference counting.
     50 // The SSLCertificate object is pretty much immutable once created.
     51 // (The OpenSSL implementation only does reference counting and
     52 // possibly caching of intermediate results.)
     53 class SSLCertificate {
     54  public:
     55   // Parses and build a certificate from a PEM encoded string.
     56   // Returns NULL on failure.
     57   // The length of the string representation of the certificate is
     58   // stored in *pem_length if it is non-NULL, and only if
     59   // parsing was successful.
     60   // Caller is responsible for freeing the returned object.
     61   static SSLCertificate* FromPEMString(const std::string& pem_string);
     62   virtual ~SSLCertificate() {}
     63 
     64   // Returns a new SSLCertificate object instance wrapping the same
     65   // underlying certificate, including its chain if present.
     66   // Caller is responsible for freeing the returned object.
     67   virtual SSLCertificate* GetReference() const = 0;
     68 
     69   // Provides the cert chain, or returns false.  The caller owns the chain.
     70   // The chain includes a copy of each certificate, excluding the leaf.
     71   virtual bool GetChain(SSLCertChain** chain) const = 0;
     72 
     73   // Returns a PEM encoded string representation of the certificate.
     74   virtual std::string ToPEMString() const = 0;
     75 
     76   // Provides a DER encoded binary representation of the certificate.
     77   virtual void ToDER(Buffer* der_buffer) const = 0;
     78 
     79   // Gets the name of the digest algorithm that was used to compute this
     80   // certificate's signature.
     81   virtual bool GetSignatureDigestAlgorithm(std::string* algorithm) const = 0;
     82 
     83   // Compute the digest of the certificate given algorithm
     84   virtual bool ComputeDigest(const std::string& algorithm,
     85                              unsigned char* digest,
     86                              size_t size,
     87                              size_t* length) const = 0;
     88 };
     89 
     90 // SSLCertChain is a simple wrapper for a vector of SSLCertificates. It serves
     91 // primarily to ensure proper memory management (especially deletion) of the
     92 // SSLCertificate pointers.
     93 class SSLCertChain {
     94  public:
     95   // These constructors copy the provided SSLCertificate(s), so the caller
     96   // retains ownership.
     97   explicit SSLCertChain(const std::vector<SSLCertificate*>& certs) {
     98     ASSERT(!certs.empty());
     99     certs_.resize(certs.size());
    100     std::transform(certs.begin(), certs.end(), certs_.begin(), DupCert);
    101   }
    102   explicit SSLCertChain(const SSLCertificate* cert) {
    103     certs_.push_back(cert->GetReference());
    104   }
    105 
    106   ~SSLCertChain() {
    107     std::for_each(certs_.begin(), certs_.end(), DeleteCert);
    108   }
    109 
    110   // Vector access methods.
    111   size_t GetSize() const { return certs_.size(); }
    112 
    113   // Returns a temporary reference, only valid until the chain is destroyed.
    114   const SSLCertificate& Get(size_t pos) const { return *(certs_[pos]); }
    115 
    116   // Returns a new SSLCertChain object instance wrapping the same underlying
    117   // certificate chain.  Caller is responsible for freeing the returned object.
    118   SSLCertChain* Copy() const {
    119     return new SSLCertChain(certs_);
    120   }
    121 
    122  private:
    123   // Helper function for duplicating a vector of certificates.
    124   static SSLCertificate* DupCert(const SSLCertificate* cert) {
    125     return cert->GetReference();
    126   }
    127 
    128   // Helper function for deleting a vector of certificates.
    129   static void DeleteCert(SSLCertificate* cert) { delete cert; }
    130 
    131   std::vector<SSLCertificate*> certs_;
    132 
    133   DISALLOW_COPY_AND_ASSIGN(SSLCertChain);
    134 };
    135 
    136 // Parameters for generating an identity for testing. If common_name is
    137 // non-empty, it will be used for the certificate's subject and issuer name,
    138 // otherwise a random string will be used. |not_before| and |not_after| are
    139 // offsets to the current time in number of seconds.
    140 struct SSLIdentityParams {
    141   std::string common_name;
    142   int not_before;  // in seconds.
    143   int not_after;  // in seconds.
    144 };
    145 
    146 // Our identity in an SSL negotiation: a keypair and certificate (both
    147 // with the same public key).
    148 // This too is pretty much immutable once created.
    149 class SSLIdentity {
    150  public:
    151   // Generates an identity (keypair and self-signed certificate). If
    152   // common_name is non-empty, it will be used for the certificate's
    153   // subject and issuer name, otherwise a random string will be used.
    154   // Returns NULL on failure.
    155   // Caller is responsible for freeing the returned object.
    156   static SSLIdentity* Generate(const std::string& common_name);
    157 
    158   // Generates an identity with the specified validity period.
    159   static SSLIdentity* GenerateForTest(const SSLIdentityParams& params);
    160 
    161   // Construct an identity from a private key and a certificate.
    162   static SSLIdentity* FromPEMStrings(const std::string& private_key,
    163                                      const std::string& certificate);
    164 
    165   virtual ~SSLIdentity() {}
    166 
    167   // Returns a new SSLIdentity object instance wrapping the same
    168   // identity information.
    169   // Caller is responsible for freeing the returned object.
    170   virtual SSLIdentity* GetReference() const = 0;
    171 
    172   // Returns a temporary reference to the certificate.
    173   virtual const SSLCertificate& certificate() const = 0;
    174 
    175   // Helpers for parsing converting between PEM and DER format.
    176   static bool PemToDer(const std::string& pem_type,
    177                        const std::string& pem_string,
    178                        std::string* der);
    179   static std::string DerToPem(const std::string& pem_type,
    180                               const unsigned char* data,
    181                               size_t length);
    182 };
    183 
    184 extern const char kPemTypeCertificate[];
    185 extern const char kPemTypeRsaPrivateKey[];
    186 
    187 }  // namespace talk_base
    188 
    189 #endif  // TALK_BASE_SSLIDENTITY_H_
    190