blob: be0f3aa1076c031c99a341e16ff97aaad0bce42c [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>
17#include <string>
18#include <vector>
19
20#include "webrtc/base/buffer.h"
21#include "webrtc/base/messagedigest.h"
kwibergf5d47862016-03-15 12:53:24 -070022#include "webrtc/base/scoped_ptr.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.
56 virtual rtc::scoped_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.
130static const int kDefaultCertificateLifetime = 60 * 60 * 24 * 30; // 30 days
131// Certificate validity window.
132// This is to compensate for slightly incorrect system clocks.
133static const int kCertificateWindow = -60 * 60 * 24;
134
torbjorng4e572472015-10-08 09:42:49 -0700135struct RSAParams {
136 unsigned int mod_size;
137 unsigned int pub_exp;
138};
139
140enum ECCurve { EC_NIST_P256, /* EC_FANCY, */ EC_LAST };
141
142class KeyParams {
143 public:
144 // Generate a KeyParams object from a simple KeyType, using default params.
145 explicit KeyParams(KeyType key_type = KT_DEFAULT);
146
147 // Generate a a KeyParams for RSA with explicit parameters.
148 static KeyParams RSA(int mod_size = kRsaDefaultModSize,
149 int pub_exp = kRsaDefaultExponent);
150
151 // Generate a a KeyParams for ECDSA specifying the curve.
152 static KeyParams ECDSA(ECCurve curve = EC_NIST_P256);
153
154 // Check validity of a KeyParams object. Since the factory functions have
155 // no way of returning errors, this function can be called after creation
156 // to make sure the parameters are OK.
157 bool IsValid() const;
158
159 RSAParams rsa_params() const;
160
161 ECCurve ec_curve() const;
162
163 KeyType type() const { return type_; }
164
165 private:
166 KeyType type_;
167 union {
168 RSAParams rsa;
169 ECCurve curve;
170 } params_;
171};
172
Henrik Boström9b5476d2015-09-22 14:12:57 +0200173// TODO(hbos): Remove once rtc::KeyType (to be modified) and
174// blink::WebRTCKeyType (to be landed) match. By using this function in Chromium
175// appropriately we can change KeyType enum -> class without breaking Chromium.
176KeyType IntKeyTypeFamilyToKeyType(int key_type_family);
177
torbjorng4e572472015-10-08 09:42:49 -0700178// Parameters for generating a certificate. If |common_name| is non-empty, it
179// will be used for the certificate's subject and issuer name, otherwise a
180// random string will be used.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000181struct SSLIdentityParams {
182 std::string common_name;
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100183 time_t not_before; // Absolute time since epoch in seconds.
184 time_t not_after; // Absolute time since epoch in seconds.
torbjorng4e572472015-10-08 09:42:49 -0700185 KeyParams key_params;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000186};
187
188// Our identity in an SSL negotiation: a keypair and certificate (both
189// with the same public key).
190// This too is pretty much immutable once created.
191class SSLIdentity {
192 public:
193 // Generates an identity (keypair and self-signed certificate). If
torbjornge8dc0812016-02-15 09:35:54 -0800194 // |common_name| is non-empty, it will be used for the certificate's subject
195 // and issuer name, otherwise a random string will be used. The key type and
196 // parameters are defined in |key_param|. The certificate's lifetime in
197 // seconds from the current time is defined in |certificate_lifetime|; it
198 // should be a non-negative number.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000199 // Returns NULL on failure.
200 // Caller is responsible for freeing the returned object.
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200201 static SSLIdentity* Generate(const std::string& common_name,
torbjornge8dc0812016-02-15 09:35:54 -0800202 const KeyParams& key_param,
203 time_t certificate_lifetime);
204 static SSLIdentity* Generate(const std::string& common_name,
Torbjorn Granlunda3dc79e2016-02-16 13:33:53 +0100205 const KeyParams& key_param);
torbjorng4e572472015-10-08 09:42:49 -0700206 static SSLIdentity* Generate(const std::string& common_name,
Torbjorn Granlunda3dc79e2016-02-16 13:33:53 +0100207 KeyType key_type);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000208
209 // Generates an identity with the specified validity period.
torbjornge8dc0812016-02-15 09:35:54 -0800210 // TODO(torbjorng): Now that Generate() accepts relevant params, make tests
211 // use that instead of this function.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000212 static SSLIdentity* GenerateForTest(const SSLIdentityParams& params);
213
214 // Construct an identity from a private key and a certificate.
215 static SSLIdentity* FromPEMStrings(const std::string& private_key,
216 const std::string& certificate);
217
218 virtual ~SSLIdentity() {}
219
220 // Returns a new SSLIdentity object instance wrapping the same
221 // identity information.
222 // Caller is responsible for freeing the returned object.
Henrik Boström87713d02015-08-25 09:53:21 +0200223 // TODO(hbos,torbjorng): Rename to a less confusing name.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000224 virtual SSLIdentity* GetReference() const = 0;
225
226 // Returns a temporary reference to the certificate.
227 virtual const SSLCertificate& certificate() const = 0;
228
229 // Helpers for parsing converting between PEM and DER format.
230 static bool PemToDer(const std::string& pem_type,
231 const std::string& pem_string,
232 std::string* der);
233 static std::string DerToPem(const std::string& pem_type,
234 const unsigned char* data,
235 size_t length);
236};
237
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100238// Convert from ASN1 time as restricted by RFC 5280 to seconds from 1970-01-01
239// 00.00 ("epoch"). If the ASN1 time cannot be read, return -1. The data at
240// |s| is not 0-terminated; its char count is defined by |length|.
241int64_t ASN1TimeToSec(const unsigned char* s, size_t length, bool long_format);
242
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000243extern const char kPemTypeCertificate[];
244extern const char kPemTypeRsaPrivateKey[];
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200245extern const char kPemTypeEcPrivateKey[];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000246
247} // namespace rtc
248
249#endif // WEBRTC_BASE_SSLIDENTITY_H_