blob: af0149bb62d8d3518186fc8adeb03821600d9ec3 [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11// Handling of certificates and keypairs for SSLStreamAdapter's peer mode.
12
13#ifndef WEBRTC_BASE_SSLIDENTITY_H_
14#define WEBRTC_BASE_SSLIDENTITY_H_
15
16#include <algorithm>
jbauch555604a2016-04-26 03:13:22 -070017#include <memory>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000018#include <string>
19#include <vector>
20
21#include "webrtc/base/buffer.h"
22#include "webrtc/base/messagedigest.h"
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +010023#include "webrtc/base/timeutils.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000024
25namespace rtc {
26
27// Forward declaration due to circular dependency with SSLCertificate.
28class SSLCertChain;
29
30// Abstract interface overridden by SSL library specific
31// implementations.
32
33// A somewhat opaque type used to encapsulate a certificate.
34// Wraps the SSL library's notion of a certificate, with reference counting.
35// The SSLCertificate object is pretty much immutable once created.
36// (The OpenSSL implementation only does reference counting and
37// possibly caching of intermediate results.)
38class SSLCertificate {
39 public:
torbjornge8dc0812016-02-15 09:35:54 -080040 // Parses and builds a certificate from a PEM encoded string.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000041 // Returns NULL on failure.
42 // The length of the string representation of the certificate is
43 // stored in *pem_length if it is non-NULL, and only if
44 // parsing was successful.
45 // Caller is responsible for freeing the returned object.
46 static SSLCertificate* FromPEMString(const std::string& pem_string);
47 virtual ~SSLCertificate() {}
48
49 // Returns a new SSLCertificate object instance wrapping the same
50 // underlying certificate, including its chain if present.
51 // Caller is responsible for freeing the returned object.
52 virtual SSLCertificate* GetReference() const = 0;
53
kwibergf5d47862016-03-15 12:53:24 -070054 // Provides the cert chain, or null. The chain includes a copy of each
55 // certificate, excluding the leaf.
jbauch555604a2016-04-26 03:13:22 -070056 virtual std::unique_ptr<SSLCertChain> GetChain() const = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000057
58 // Returns a PEM encoded string representation of the certificate.
59 virtual std::string ToPEMString() const = 0;
60
61 // Provides a DER encoded binary representation of the certificate.
62 virtual void ToDER(Buffer* der_buffer) const = 0;
63
64 // Gets the name of the digest algorithm that was used to compute this
65 // certificate's signature.
66 virtual bool GetSignatureDigestAlgorithm(std::string* algorithm) const = 0;
67
68 // Compute the digest of the certificate given algorithm
69 virtual bool ComputeDigest(const std::string& algorithm,
70 unsigned char* digest,
71 size_t size,
72 size_t* length) const = 0;
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +010073
hbos3980d462015-12-09 05:26:49 -080074 // Returns the time in seconds relative to epoch, 1970-01-01T00:00:00Z (UTC),
75 // or -1 if an expiration time could not be retrieved.
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +010076 virtual int64_t CertificateExpirationTime() const = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000077};
78
79// SSLCertChain is a simple wrapper for a vector of SSLCertificates. It serves
80// primarily to ensure proper memory management (especially deletion) of the
81// SSLCertificate pointers.
82class SSLCertChain {
83 public:
84 // These constructors copy the provided SSLCertificate(s), so the caller
85 // retains ownership.
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +000086 explicit SSLCertChain(const std::vector<SSLCertificate*>& certs);
87 explicit SSLCertChain(const SSLCertificate* cert);
88 ~SSLCertChain();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000089
90 // Vector access methods.
91 size_t GetSize() const { return certs_.size(); }
92
93 // Returns a temporary reference, only valid until the chain is destroyed.
94 const SSLCertificate& Get(size_t pos) const { return *(certs_[pos]); }
95
96 // Returns a new SSLCertChain object instance wrapping the same underlying
97 // certificate chain. Caller is responsible for freeing the returned object.
98 SSLCertChain* Copy() const {
99 return new SSLCertChain(certs_);
100 }
101
102 private:
103 // Helper function for duplicating a vector of certificates.
104 static SSLCertificate* DupCert(const SSLCertificate* cert) {
105 return cert->GetReference();
106 }
107
108 // Helper function for deleting a vector of certificates.
109 static void DeleteCert(SSLCertificate* cert) { delete cert; }
110
111 std::vector<SSLCertificate*> certs_;
112
henrikg3c089d72015-09-16 05:37:44 -0700113 RTC_DISALLOW_COPY_AND_ASSIGN(SSLCertChain);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000114};
115
torbjorng4e572472015-10-08 09:42:49 -0700116// KT_DEFAULT is currently an alias for KT_RSA. This is likely to change.
117// KT_LAST is intended for vector declarations and loops over all key types;
118// it does not represent any key type in itself.
Henrik Boström9b5476d2015-09-22 14:12:57 +0200119// TODO(hbos,torbjorng): Don't change KT_DEFAULT without first updating
120// PeerConnectionFactory_nativeCreatePeerConnection's certificate generation
121// code.
Henrik Boström5e56c592015-08-11 10:33:13 +0200122enum KeyType { KT_RSA, KT_ECDSA, KT_LAST, KT_DEFAULT = KT_RSA };
123
torbjorng4e572472015-10-08 09:42:49 -0700124static const int kRsaDefaultModSize = 1024;
125static const int kRsaDefaultExponent = 0x10001; // = 2^16+1 = 65537
126static const int kRsaMinModSize = 1024;
127static const int kRsaMaxModSize = 8192;
128
torbjornge8dc0812016-02-15 09:35:54 -0800129// Certificate default validity lifetime.
Torbjorn Granlund1d846b22016-03-31 16:21:04 +0200130static const int kDefaultCertificateLifetimeInSeconds =
131 60 * 60 * 24 * 30; // 30 days
torbjornge8dc0812016-02-15 09:35:54 -0800132// Certificate validity window.
133// This is to compensate for slightly incorrect system clocks.
Torbjorn Granlund1d846b22016-03-31 16:21:04 +0200134static const int kCertificateWindowInSeconds = -60 * 60 * 24;
torbjornge8dc0812016-02-15 09:35:54 -0800135
torbjorng4e572472015-10-08 09:42:49 -0700136struct RSAParams {
137 unsigned int mod_size;
138 unsigned int pub_exp;
139};
140
141enum ECCurve { EC_NIST_P256, /* EC_FANCY, */ EC_LAST };
142
143class KeyParams {
144 public:
145 // Generate a KeyParams object from a simple KeyType, using default params.
146 explicit KeyParams(KeyType key_type = KT_DEFAULT);
147
148 // Generate a a KeyParams for RSA with explicit parameters.
149 static KeyParams RSA(int mod_size = kRsaDefaultModSize,
150 int pub_exp = kRsaDefaultExponent);
151
152 // Generate a a KeyParams for ECDSA specifying the curve.
153 static KeyParams ECDSA(ECCurve curve = EC_NIST_P256);
154
155 // Check validity of a KeyParams object. Since the factory functions have
156 // no way of returning errors, this function can be called after creation
157 // to make sure the parameters are OK.
158 bool IsValid() const;
159
160 RSAParams rsa_params() const;
161
162 ECCurve ec_curve() const;
163
164 KeyType type() const { return type_; }
165
166 private:
167 KeyType type_;
168 union {
169 RSAParams rsa;
170 ECCurve curve;
171 } params_;
172};
173
Henrik Boström9b5476d2015-09-22 14:12:57 +0200174// TODO(hbos): Remove once rtc::KeyType (to be modified) and
175// blink::WebRTCKeyType (to be landed) match. By using this function in Chromium
176// appropriately we can change KeyType enum -> class without breaking Chromium.
177KeyType IntKeyTypeFamilyToKeyType(int key_type_family);
178
torbjorng4e572472015-10-08 09:42:49 -0700179// Parameters for generating a certificate. If |common_name| is non-empty, it
180// will be used for the certificate's subject and issuer name, otherwise a
181// random string will be used.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000182struct SSLIdentityParams {
183 std::string common_name;
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100184 time_t not_before; // Absolute time since epoch in seconds.
185 time_t not_after; // Absolute time since epoch in seconds.
torbjorng4e572472015-10-08 09:42:49 -0700186 KeyParams key_params;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000187};
188
189// Our identity in an SSL negotiation: a keypair and certificate (both
190// with the same public key).
191// This too is pretty much immutable once created.
192class SSLIdentity {
193 public:
194 // Generates an identity (keypair and self-signed certificate). If
torbjornge8dc0812016-02-15 09:35:54 -0800195 // |common_name| is non-empty, it will be used for the certificate's subject
196 // and issuer name, otherwise a random string will be used. The key type and
197 // parameters are defined in |key_param|. The certificate's lifetime in
198 // seconds from the current time is defined in |certificate_lifetime|; it
199 // should be a non-negative number.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000200 // Returns NULL on failure.
201 // Caller is responsible for freeing the returned object.
Torbjorn Granlund1d846b22016-03-31 16:21:04 +0200202 static SSLIdentity* GenerateWithExpiration(const std::string& common_name,
203 const KeyParams& key_param,
204 time_t certificate_lifetime);
torbjornge8dc0812016-02-15 09:35:54 -0800205 static SSLIdentity* Generate(const std::string& common_name,
Torbjorn Granlunda3dc79e2016-02-16 13:33:53 +0100206 const KeyParams& key_param);
torbjorng4e572472015-10-08 09:42:49 -0700207 static SSLIdentity* Generate(const std::string& common_name,
Torbjorn Granlunda3dc79e2016-02-16 13:33:53 +0100208 KeyType key_type);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000209
210 // Generates an identity with the specified validity period.
torbjornge8dc0812016-02-15 09:35:54 -0800211 // TODO(torbjorng): Now that Generate() accepts relevant params, make tests
212 // use that instead of this function.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000213 static SSLIdentity* GenerateForTest(const SSLIdentityParams& params);
214
215 // Construct an identity from a private key and a certificate.
216 static SSLIdentity* FromPEMStrings(const std::string& private_key,
217 const std::string& certificate);
218
219 virtual ~SSLIdentity() {}
220
221 // Returns a new SSLIdentity object instance wrapping the same
222 // identity information.
223 // Caller is responsible for freeing the returned object.
Henrik Boström87713d02015-08-25 09:53:21 +0200224 // TODO(hbos,torbjorng): Rename to a less confusing name.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000225 virtual SSLIdentity* GetReference() const = 0;
226
227 // Returns a temporary reference to the certificate.
228 virtual const SSLCertificate& certificate() const = 0;
229
230 // Helpers for parsing converting between PEM and DER format.
231 static bool PemToDer(const std::string& pem_type,
232 const std::string& pem_string,
233 std::string* der);
234 static std::string DerToPem(const std::string& pem_type,
235 const unsigned char* data,
236 size_t length);
237};
238
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100239// Convert from ASN1 time as restricted by RFC 5280 to seconds from 1970-01-01
240// 00.00 ("epoch"). If the ASN1 time cannot be read, return -1. The data at
241// |s| is not 0-terminated; its char count is defined by |length|.
242int64_t ASN1TimeToSec(const unsigned char* s, size_t length, bool long_format);
243
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000244extern const char kPemTypeCertificate[];
245extern const char kPemTypeRsaPrivateKey[];
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200246extern const char kPemTypeEcPrivateKey[];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000247
248} // namespace rtc
249
250#endif // WEBRTC_BASE_SSLIDENTITY_H_