blob: 0f81929cc4e42e20af91ce9c731df706c1fa9715 [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"
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +010022#include "webrtc/base/timeutils.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000023
24namespace rtc {
25
26// Forward declaration due to circular dependency with SSLCertificate.
27class SSLCertChain;
28
29// Abstract interface overridden by SSL library specific
30// implementations.
31
32// A somewhat opaque type used to encapsulate a certificate.
33// Wraps the SSL library's notion of a certificate, with reference counting.
34// The SSLCertificate object is pretty much immutable once created.
35// (The OpenSSL implementation only does reference counting and
36// possibly caching of intermediate results.)
37class SSLCertificate {
38 public:
torbjornge8dc0812016-02-15 09:35:54 -080039 // Parses and builds a certificate from a PEM encoded string.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000040 // Returns NULL on failure.
41 // The length of the string representation of the certificate is
42 // stored in *pem_length if it is non-NULL, and only if
43 // parsing was successful.
44 // Caller is responsible for freeing the returned object.
45 static SSLCertificate* FromPEMString(const std::string& pem_string);
46 virtual ~SSLCertificate() {}
47
48 // Returns a new SSLCertificate object instance wrapping the same
49 // underlying certificate, including its chain if present.
50 // Caller is responsible for freeing the returned object.
51 virtual SSLCertificate* GetReference() const = 0;
52
53 // Provides the cert chain, or returns false. The caller owns the chain.
54 // The chain includes a copy of each certificate, excluding the leaf.
55 virtual bool GetChain(SSLCertChain** chain) const = 0;
56
57 // Returns a PEM encoded string representation of the certificate.
58 virtual std::string ToPEMString() const = 0;
59
60 // Provides a DER encoded binary representation of the certificate.
61 virtual void ToDER(Buffer* der_buffer) const = 0;
62
63 // Gets the name of the digest algorithm that was used to compute this
64 // certificate's signature.
65 virtual bool GetSignatureDigestAlgorithm(std::string* algorithm) const = 0;
66
67 // Compute the digest of the certificate given algorithm
68 virtual bool ComputeDigest(const std::string& algorithm,
69 unsigned char* digest,
70 size_t size,
71 size_t* length) const = 0;
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +010072
hbos3980d462015-12-09 05:26:49 -080073 // Returns the time in seconds relative to epoch, 1970-01-01T00:00:00Z (UTC),
74 // or -1 if an expiration time could not be retrieved.
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +010075 virtual int64_t CertificateExpirationTime() const = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000076};
77
78// SSLCertChain is a simple wrapper for a vector of SSLCertificates. It serves
79// primarily to ensure proper memory management (especially deletion) of the
80// SSLCertificate pointers.
81class SSLCertChain {
82 public:
83 // These constructors copy the provided SSLCertificate(s), so the caller
84 // retains ownership.
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +000085 explicit SSLCertChain(const std::vector<SSLCertificate*>& certs);
86 explicit SSLCertChain(const SSLCertificate* cert);
87 ~SSLCertChain();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000088
89 // Vector access methods.
90 size_t GetSize() const { return certs_.size(); }
91
92 // Returns a temporary reference, only valid until the chain is destroyed.
93 const SSLCertificate& Get(size_t pos) const { return *(certs_[pos]); }
94
95 // Returns a new SSLCertChain object instance wrapping the same underlying
96 // certificate chain. Caller is responsible for freeing the returned object.
97 SSLCertChain* Copy() const {
98 return new SSLCertChain(certs_);
99 }
100
101 private:
102 // Helper function for duplicating a vector of certificates.
103 static SSLCertificate* DupCert(const SSLCertificate* cert) {
104 return cert->GetReference();
105 }
106
107 // Helper function for deleting a vector of certificates.
108 static void DeleteCert(SSLCertificate* cert) { delete cert; }
109
110 std::vector<SSLCertificate*> certs_;
111
henrikg3c089d72015-09-16 05:37:44 -0700112 RTC_DISALLOW_COPY_AND_ASSIGN(SSLCertChain);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000113};
114
torbjorng4e572472015-10-08 09:42:49 -0700115// KT_DEFAULT is currently an alias for KT_RSA. This is likely to change.
116// KT_LAST is intended for vector declarations and loops over all key types;
117// it does not represent any key type in itself.
Henrik Boström9b5476d2015-09-22 14:12:57 +0200118// TODO(hbos,torbjorng): Don't change KT_DEFAULT without first updating
119// PeerConnectionFactory_nativeCreatePeerConnection's certificate generation
120// code.
Henrik Boström5e56c592015-08-11 10:33:13 +0200121enum KeyType { KT_RSA, KT_ECDSA, KT_LAST, KT_DEFAULT = KT_RSA };
122
torbjorng4e572472015-10-08 09:42:49 -0700123static const int kRsaDefaultModSize = 1024;
124static const int kRsaDefaultExponent = 0x10001; // = 2^16+1 = 65537
125static const int kRsaMinModSize = 1024;
126static const int kRsaMaxModSize = 8192;
127
torbjornge8dc0812016-02-15 09:35:54 -0800128// Certificate default validity lifetime.
129static const int kDefaultCertificateLifetime = 60 * 60 * 24 * 30; // 30 days
130// Certificate validity window.
131// This is to compensate for slightly incorrect system clocks.
132static const int kCertificateWindow = -60 * 60 * 24;
133
torbjorng4e572472015-10-08 09:42:49 -0700134struct RSAParams {
135 unsigned int mod_size;
136 unsigned int pub_exp;
137};
138
139enum ECCurve { EC_NIST_P256, /* EC_FANCY, */ EC_LAST };
140
141class KeyParams {
142 public:
143 // Generate a KeyParams object from a simple KeyType, using default params.
144 explicit KeyParams(KeyType key_type = KT_DEFAULT);
145
146 // Generate a a KeyParams for RSA with explicit parameters.
147 static KeyParams RSA(int mod_size = kRsaDefaultModSize,
148 int pub_exp = kRsaDefaultExponent);
149
150 // Generate a a KeyParams for ECDSA specifying the curve.
151 static KeyParams ECDSA(ECCurve curve = EC_NIST_P256);
152
153 // Check validity of a KeyParams object. Since the factory functions have
154 // no way of returning errors, this function can be called after creation
155 // to make sure the parameters are OK.
156 bool IsValid() const;
157
158 RSAParams rsa_params() const;
159
160 ECCurve ec_curve() const;
161
162 KeyType type() const { return type_; }
163
164 private:
165 KeyType type_;
166 union {
167 RSAParams rsa;
168 ECCurve curve;
169 } params_;
170};
171
Henrik Boström9b5476d2015-09-22 14:12:57 +0200172// TODO(hbos): Remove once rtc::KeyType (to be modified) and
173// blink::WebRTCKeyType (to be landed) match. By using this function in Chromium
174// appropriately we can change KeyType enum -> class without breaking Chromium.
175KeyType IntKeyTypeFamilyToKeyType(int key_type_family);
176
torbjorng4e572472015-10-08 09:42:49 -0700177// Parameters for generating a certificate. If |common_name| is non-empty, it
178// will be used for the certificate's subject and issuer name, otherwise a
179// random string will be used.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000180struct SSLIdentityParams {
181 std::string common_name;
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100182 time_t not_before; // Absolute time since epoch in seconds.
183 time_t not_after; // Absolute time since epoch in seconds.
torbjorng4e572472015-10-08 09:42:49 -0700184 KeyParams key_params;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000185};
186
187// Our identity in an SSL negotiation: a keypair and certificate (both
188// with the same public key).
189// This too is pretty much immutable once created.
190class SSLIdentity {
191 public:
192 // Generates an identity (keypair and self-signed certificate). If
torbjornge8dc0812016-02-15 09:35:54 -0800193 // |common_name| is non-empty, it will be used for the certificate's subject
194 // and issuer name, otherwise a random string will be used. The key type and
195 // parameters are defined in |key_param|. The certificate's lifetime in
196 // seconds from the current time is defined in |certificate_lifetime|; it
197 // should be a non-negative number.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000198 // Returns NULL on failure.
199 // Caller is responsible for freeing the returned object.
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200200 static SSLIdentity* Generate(const std::string& common_name,
torbjornge8dc0812016-02-15 09:35:54 -0800201 const KeyParams& key_param,
202 time_t certificate_lifetime);
203 static SSLIdentity* Generate(const std::string& common_name,
204 const KeyParams& key_param) {
205 return Generate(common_name, key_param, kDefaultCertificateLifetime);
206 }
torbjorng4e572472015-10-08 09:42:49 -0700207 static SSLIdentity* Generate(const std::string& common_name,
208 KeyType key_type) {
209 return Generate(common_name, KeyParams(key_type));
210 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000211
212 // Generates an identity with the specified validity period.
torbjornge8dc0812016-02-15 09:35:54 -0800213 // TODO(torbjorng): Now that Generate() accepts relevant params, make tests
214 // use that instead of this function.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000215 static SSLIdentity* GenerateForTest(const SSLIdentityParams& params);
216
217 // Construct an identity from a private key and a certificate.
218 static SSLIdentity* FromPEMStrings(const std::string& private_key,
219 const std::string& certificate);
220
221 virtual ~SSLIdentity() {}
222
223 // Returns a new SSLIdentity object instance wrapping the same
224 // identity information.
225 // Caller is responsible for freeing the returned object.
Henrik Boström87713d02015-08-25 09:53:21 +0200226 // TODO(hbos,torbjorng): Rename to a less confusing name.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000227 virtual SSLIdentity* GetReference() const = 0;
228
229 // Returns a temporary reference to the certificate.
230 virtual const SSLCertificate& certificate() const = 0;
231
232 // Helpers for parsing converting between PEM and DER format.
233 static bool PemToDer(const std::string& pem_type,
234 const std::string& pem_string,
235 std::string* der);
236 static std::string DerToPem(const std::string& pem_type,
237 const unsigned char* data,
238 size_t length);
239};
240
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100241// Convert from ASN1 time as restricted by RFC 5280 to seconds from 1970-01-01
242// 00.00 ("epoch"). If the ASN1 time cannot be read, return -1. The data at
243// |s| is not 0-terminated; its char count is defined by |length|.
244int64_t ASN1TimeToSec(const unsigned char* s, size_t length, bool long_format);
245
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000246extern const char kPemTypeCertificate[];
247extern const char kPemTypeRsaPrivateKey[];
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200248extern const char kPemTypeEcPrivateKey[];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000249
250} // namespace rtc
251
252#endif // WEBRTC_BASE_SSLIDENTITY_H_