blob: d14610b0f9a4871590ddebe1cbf0b0d2d73df418 [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020013#ifndef RTC_BASE_SSLIDENTITY_H_
14#define RTC_BASE_SSLIDENTITY_H_
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000015
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020016#include <algorithm>
17#include <memory>
18#include <string>
19#include <vector>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000020
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "rtc_base/buffer.h"
22#include "rtc_base/constructormagic.h"
23#include "rtc_base/messagedigest.h"
24#include "rtc_base/timeutils.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020025
26namespace rtc {
27
28// Forward declaration due to circular dependency with SSLCertificate.
29class SSLCertChain;
30
31struct SSLCertificateStats {
32 SSLCertificateStats(std::string&& fingerprint,
33 std::string&& fingerprint_algorithm,
34 std::string&& base64_certificate,
35 std::unique_ptr<SSLCertificateStats>&& issuer);
36 ~SSLCertificateStats();
37 std::string fingerprint;
38 std::string fingerprint_algorithm;
39 std::string base64_certificate;
40 std::unique_ptr<SSLCertificateStats> issuer;
41};
42
43// Abstract interface overridden by SSL library specific
44// implementations.
45
46// A somewhat opaque type used to encapsulate a certificate.
47// Wraps the SSL library's notion of a certificate, with reference counting.
48// The SSLCertificate object is pretty much immutable once created.
49// (The OpenSSL implementation only does reference counting and
50// possibly caching of intermediate results.)
51class SSLCertificate {
52 public:
53 // Parses and builds a certificate from a PEM encoded string.
54 // Returns null on failure.
55 // The length of the string representation of the certificate is
56 // stored in *pem_length if it is non-null, and only if
57 // parsing was successful.
58 // Caller is responsible for freeing the returned object.
59 static SSLCertificate* FromPEMString(const std::string& pem_string);
60 virtual ~SSLCertificate() {}
61
62 // Returns a new SSLCertificate object instance wrapping the same
David Benjamin3df76b12017-09-29 12:27:18 -040063 // underlying certificate, including its chain if present. Caller is
64 // responsible for freeing the returned object. Use GetUniqueReference
65 // instead.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020066 virtual SSLCertificate* GetReference() const = 0;
67
David Benjamin3df76b12017-09-29 12:27:18 -040068 std::unique_ptr<SSLCertificate> GetUniqueReference() const;
69
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020070 // Returns a PEM encoded string representation of the certificate.
71 virtual std::string ToPEMString() const = 0;
72
73 // Provides a DER encoded binary representation of the certificate.
74 virtual void ToDER(Buffer* der_buffer) const = 0;
75
76 // Gets the name of the digest algorithm that was used to compute this
77 // certificate's signature.
78 virtual bool GetSignatureDigestAlgorithm(std::string* algorithm) const = 0;
79
80 // Compute the digest of the certificate given algorithm
81 virtual bool ComputeDigest(const std::string& algorithm,
82 unsigned char* digest,
83 size_t size,
84 size_t* length) const = 0;
85
86 // Returns the time in seconds relative to epoch, 1970-01-01T00:00:00Z (UTC),
87 // or -1 if an expiration time could not be retrieved.
88 virtual int64_t CertificateExpirationTime() const = 0;
89
Taylor Brandstetterc3928662018-02-23 13:04:51 -080090 // Gets information (fingerprint, etc.) about this certificate. This is used
91 // for certificate stats, see
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020092 // https://w3c.github.io/webrtc-stats/#certificatestats-dict*.
93 std::unique_ptr<SSLCertificateStats> GetStats() const;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020094};
95
96// SSLCertChain is a simple wrapper for a vector of SSLCertificates. It serves
97// primarily to ensure proper memory management (especially deletion) of the
98// SSLCertificate pointers.
99class SSLCertChain {
100 public:
David Benjamin3df76b12017-09-29 12:27:18 -0400101 explicit SSLCertChain(std::vector<std::unique_ptr<SSLCertificate>> certs);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200102 // These constructors copy the provided SSLCertificate(s), so the caller
103 // retains ownership.
104 explicit SSLCertChain(const std::vector<SSLCertificate*>& certs);
105 explicit SSLCertChain(const SSLCertificate* cert);
106 ~SSLCertChain();
107
108 // Vector access methods.
109 size_t GetSize() const { return certs_.size(); }
110
111 // Returns a temporary reference, only valid until the chain is destroyed.
112 const SSLCertificate& Get(size_t pos) const { return *(certs_[pos]); }
113
114 // Returns a new SSLCertChain object instance wrapping the same underlying
115 // certificate chain. Caller is responsible for freeing the returned object.
David Benjamin3df76b12017-09-29 12:27:18 -0400116 SSLCertChain* Copy() const;
Taylor Brandstetterc3928662018-02-23 13:04:51 -0800117 // Same as above, but returning a unique_ptr for convenience.
118 std::unique_ptr<SSLCertChain> UniqueCopy() const;
119
120 // Gets information (fingerprint, etc.) about this certificate chain. This is
121 // used for certificate stats, see
122 // https://w3c.github.io/webrtc-stats/#certificatestats-dict*.
123 std::unique_ptr<SSLCertificateStats> GetStats() const;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200124
125 private:
David Benjamin3df76b12017-09-29 12:27:18 -0400126 std::vector<std::unique_ptr<SSLCertificate>> certs_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200127
128 RTC_DISALLOW_COPY_AND_ASSIGN(SSLCertChain);
129};
130
131// KT_LAST is intended for vector declarations and loops over all key types;
132// it does not represent any key type in itself.
133// KT_DEFAULT is used as the default KeyType for KeyParams.
134enum KeyType { KT_RSA, KT_ECDSA, KT_LAST, KT_DEFAULT = KT_ECDSA };
135
136static const int kRsaDefaultModSize = 1024;
137static const int kRsaDefaultExponent = 0x10001; // = 2^16+1 = 65537
138static const int kRsaMinModSize = 1024;
139static const int kRsaMaxModSize = 8192;
140
141// Certificate default validity lifetime.
142static const int kDefaultCertificateLifetimeInSeconds =
143 60 * 60 * 24 * 30; // 30 days
144// Certificate validity window.
145// This is to compensate for slightly incorrect system clocks.
146static const int kCertificateWindowInSeconds = -60 * 60 * 24;
147
148struct RSAParams {
149 unsigned int mod_size;
150 unsigned int pub_exp;
151};
152
153enum ECCurve { EC_NIST_P256, /* EC_FANCY, */ EC_LAST };
154
155class KeyParams {
156 public:
157 // Generate a KeyParams object from a simple KeyType, using default params.
158 explicit KeyParams(KeyType key_type = KT_DEFAULT);
159
160 // Generate a a KeyParams for RSA with explicit parameters.
161 static KeyParams RSA(int mod_size = kRsaDefaultModSize,
162 int pub_exp = kRsaDefaultExponent);
163
164 // Generate a a KeyParams for ECDSA specifying the curve.
165 static KeyParams ECDSA(ECCurve curve = EC_NIST_P256);
166
167 // Check validity of a KeyParams object. Since the factory functions have
168 // no way of returning errors, this function can be called after creation
169 // to make sure the parameters are OK.
170 bool IsValid() const;
171
172 RSAParams rsa_params() const;
173
174 ECCurve ec_curve() const;
175
176 KeyType type() const { return type_; }
177
178 private:
179 KeyType type_;
180 union {
181 RSAParams rsa;
182 ECCurve curve;
183 } params_;
184};
185
186// TODO(hbos): Remove once rtc::KeyType (to be modified) and
187// blink::WebRTCKeyType (to be landed) match. By using this function in Chromium
188// appropriately we can change KeyType enum -> class without breaking Chromium.
189KeyType IntKeyTypeFamilyToKeyType(int key_type_family);
190
191// Parameters for generating a certificate. If |common_name| is non-empty, it
192// will be used for the certificate's subject and issuer name, otherwise a
193// random string will be used.
194struct SSLIdentityParams {
195 std::string common_name;
196 time_t not_before; // Absolute time since epoch in seconds.
197 time_t not_after; // Absolute time since epoch in seconds.
198 KeyParams key_params;
199};
200
201// Our identity in an SSL negotiation: a keypair and certificate (both
202// with the same public key).
203// This too is pretty much immutable once created.
204class SSLIdentity {
205 public:
206 // Generates an identity (keypair and self-signed certificate). If
207 // |common_name| is non-empty, it will be used for the certificate's subject
208 // and issuer name, otherwise a random string will be used. The key type and
209 // parameters are defined in |key_param|. The certificate's lifetime in
210 // seconds from the current time is defined in |certificate_lifetime|; it
211 // should be a non-negative number.
212 // Returns null on failure.
213 // Caller is responsible for freeing the returned object.
214 static SSLIdentity* GenerateWithExpiration(const std::string& common_name,
215 const KeyParams& key_param,
216 time_t certificate_lifetime);
217 static SSLIdentity* Generate(const std::string& common_name,
218 const KeyParams& key_param);
219 static SSLIdentity* Generate(const std::string& common_name,
220 KeyType key_type);
221
222 // Generates an identity with the specified validity period.
223 // TODO(torbjorng): Now that Generate() accepts relevant params, make tests
224 // use that instead of this function.
225 static SSLIdentity* GenerateForTest(const SSLIdentityParams& params);
226
227 // Construct an identity from a private key and a certificate.
228 static SSLIdentity* FromPEMStrings(const std::string& private_key,
229 const std::string& certificate);
230
Jian Cui0a8798b2017-11-16 16:58:02 -0800231 // Construct an identity from a private key and a certificate chain.
232 static SSLIdentity* FromPEMChainStrings(const std::string& private_key,
233 const std::string& certificate_chain);
234
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200235 virtual ~SSLIdentity() {}
236
237 // Returns a new SSLIdentity object instance wrapping the same
238 // identity information.
239 // Caller is responsible for freeing the returned object.
240 // TODO(hbos,torbjorng): Rename to a less confusing name.
241 virtual SSLIdentity* GetReference() const = 0;
242
Taylor Brandstetterc3928662018-02-23 13:04:51 -0800243 // Returns a temporary reference to the end-entity (leaf) certificate.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200244 virtual const SSLCertificate& certificate() const = 0;
Taylor Brandstetterc3928662018-02-23 13:04:51 -0800245 // Returns a temporary reference to the entire certificate chain.
246 virtual const SSLCertChain& cert_chain() const = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200247 virtual std::string PrivateKeyToPEMString() const = 0;
248 virtual std::string PublicKeyToPEMString() const = 0;
249
250 // Helpers for parsing converting between PEM and DER format.
251 static bool PemToDer(const std::string& pem_type,
252 const std::string& pem_string,
253 std::string* der);
254 static std::string DerToPem(const std::string& pem_type,
255 const unsigned char* data,
256 size_t length);
257};
258
259bool operator==(const SSLIdentity& a, const SSLIdentity& b);
260bool operator!=(const SSLIdentity& a, const SSLIdentity& b);
261
262// Convert from ASN1 time as restricted by RFC 5280 to seconds from 1970-01-01
263// 00.00 ("epoch"). If the ASN1 time cannot be read, return -1. The data at
264// |s| is not 0-terminated; its char count is defined by |length|.
265int64_t ASN1TimeToSec(const unsigned char* s, size_t length, bool long_format);
266
267extern const char kPemTypeCertificate[];
268extern const char kPemTypeRsaPrivateKey[];
269extern const char kPemTypeEcPrivateKey[];
270
271} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000272
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200273#endif // RTC_BASE_SSLIDENTITY_H_