blob: f20c5470ef4739266f41b27e8bf40b95c358626a [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 // Provides the cert chain, or null. The chain includes a copy of each
71 // certificate, excluding the leaf.
72 virtual std::unique_ptr<SSLCertChain> GetChain() const = 0;
73
74 // Returns a PEM encoded string representation of the certificate.
75 virtual std::string ToPEMString() const = 0;
76
77 // Provides a DER encoded binary representation of the certificate.
78 virtual void ToDER(Buffer* der_buffer) const = 0;
79
80 // Gets the name of the digest algorithm that was used to compute this
81 // certificate's signature.
82 virtual bool GetSignatureDigestAlgorithm(std::string* algorithm) const = 0;
83
84 // Compute the digest of the certificate given algorithm
85 virtual bool ComputeDigest(const std::string& algorithm,
86 unsigned char* digest,
87 size_t size,
88 size_t* length) const = 0;
89
90 // Returns the time in seconds relative to epoch, 1970-01-01T00:00:00Z (UTC),
91 // or -1 if an expiration time could not be retrieved.
92 virtual int64_t CertificateExpirationTime() const = 0;
93
94 // Gets information (fingerprint, etc.) about this certificate and its chain
95 // (if it has a certificate chain). This is used for certificate stats, see
96 // https://w3c.github.io/webrtc-stats/#certificatestats-dict*.
97 std::unique_ptr<SSLCertificateStats> GetStats() const;
98
99 private:
100 std::unique_ptr<SSLCertificateStats> GetStats(
101 std::unique_ptr<SSLCertificateStats> issuer) const;
102};
103
104// SSLCertChain is a simple wrapper for a vector of SSLCertificates. It serves
105// primarily to ensure proper memory management (especially deletion) of the
106// SSLCertificate pointers.
107class SSLCertChain {
108 public:
David Benjamin3df76b12017-09-29 12:27:18 -0400109 explicit SSLCertChain(std::vector<std::unique_ptr<SSLCertificate>> certs);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200110 // These constructors copy the provided SSLCertificate(s), so the caller
111 // retains ownership.
112 explicit SSLCertChain(const std::vector<SSLCertificate*>& certs);
113 explicit SSLCertChain(const SSLCertificate* cert);
114 ~SSLCertChain();
115
116 // Vector access methods.
117 size_t GetSize() const { return certs_.size(); }
118
119 // Returns a temporary reference, only valid until the chain is destroyed.
120 const SSLCertificate& Get(size_t pos) const { return *(certs_[pos]); }
121
122 // Returns a new SSLCertChain object instance wrapping the same underlying
123 // certificate chain. Caller is responsible for freeing the returned object.
David Benjamin3df76b12017-09-29 12:27:18 -0400124 SSLCertChain* Copy() const;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200125
126 private:
David Benjamin3df76b12017-09-29 12:27:18 -0400127 std::vector<std::unique_ptr<SSLCertificate>> certs_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200128
129 RTC_DISALLOW_COPY_AND_ASSIGN(SSLCertChain);
130};
131
132// KT_LAST is intended for vector declarations and loops over all key types;
133// it does not represent any key type in itself.
134// KT_DEFAULT is used as the default KeyType for KeyParams.
135enum KeyType { KT_RSA, KT_ECDSA, KT_LAST, KT_DEFAULT = KT_ECDSA };
136
137static const int kRsaDefaultModSize = 1024;
138static const int kRsaDefaultExponent = 0x10001; // = 2^16+1 = 65537
139static const int kRsaMinModSize = 1024;
140static const int kRsaMaxModSize = 8192;
141
142// Certificate default validity lifetime.
143static const int kDefaultCertificateLifetimeInSeconds =
144 60 * 60 * 24 * 30; // 30 days
145// Certificate validity window.
146// This is to compensate for slightly incorrect system clocks.
147static const int kCertificateWindowInSeconds = -60 * 60 * 24;
148
149struct RSAParams {
150 unsigned int mod_size;
151 unsigned int pub_exp;
152};
153
154enum ECCurve { EC_NIST_P256, /* EC_FANCY, */ EC_LAST };
155
156class KeyParams {
157 public:
158 // Generate a KeyParams object from a simple KeyType, using default params.
159 explicit KeyParams(KeyType key_type = KT_DEFAULT);
160
161 // Generate a a KeyParams for RSA with explicit parameters.
162 static KeyParams RSA(int mod_size = kRsaDefaultModSize,
163 int pub_exp = kRsaDefaultExponent);
164
165 // Generate a a KeyParams for ECDSA specifying the curve.
166 static KeyParams ECDSA(ECCurve curve = EC_NIST_P256);
167
168 // Check validity of a KeyParams object. Since the factory functions have
169 // no way of returning errors, this function can be called after creation
170 // to make sure the parameters are OK.
171 bool IsValid() const;
172
173 RSAParams rsa_params() const;
174
175 ECCurve ec_curve() const;
176
177 KeyType type() const { return type_; }
178
179 private:
180 KeyType type_;
181 union {
182 RSAParams rsa;
183 ECCurve curve;
184 } params_;
185};
186
187// TODO(hbos): Remove once rtc::KeyType (to be modified) and
188// blink::WebRTCKeyType (to be landed) match. By using this function in Chromium
189// appropriately we can change KeyType enum -> class without breaking Chromium.
190KeyType IntKeyTypeFamilyToKeyType(int key_type_family);
191
192// Parameters for generating a certificate. If |common_name| is non-empty, it
193// will be used for the certificate's subject and issuer name, otherwise a
194// random string will be used.
195struct SSLIdentityParams {
196 std::string common_name;
197 time_t not_before; // Absolute time since epoch in seconds.
198 time_t not_after; // Absolute time since epoch in seconds.
199 KeyParams key_params;
200};
201
202// Our identity in an SSL negotiation: a keypair and certificate (both
203// with the same public key).
204// This too is pretty much immutable once created.
205class SSLIdentity {
206 public:
207 // Generates an identity (keypair and self-signed certificate). If
208 // |common_name| is non-empty, it will be used for the certificate's subject
209 // and issuer name, otherwise a random string will be used. The key type and
210 // parameters are defined in |key_param|. The certificate's lifetime in
211 // seconds from the current time is defined in |certificate_lifetime|; it
212 // should be a non-negative number.
213 // Returns null on failure.
214 // Caller is responsible for freeing the returned object.
215 static SSLIdentity* GenerateWithExpiration(const std::string& common_name,
216 const KeyParams& key_param,
217 time_t certificate_lifetime);
218 static SSLIdentity* Generate(const std::string& common_name,
219 const KeyParams& key_param);
220 static SSLIdentity* Generate(const std::string& common_name,
221 KeyType key_type);
222
223 // Generates an identity with the specified validity period.
224 // TODO(torbjorng): Now that Generate() accepts relevant params, make tests
225 // use that instead of this function.
226 static SSLIdentity* GenerateForTest(const SSLIdentityParams& params);
227
228 // Construct an identity from a private key and a certificate.
229 static SSLIdentity* FromPEMStrings(const std::string& private_key,
230 const std::string& certificate);
231
232 virtual ~SSLIdentity() {}
233
234 // Returns a new SSLIdentity object instance wrapping the same
235 // identity information.
236 // Caller is responsible for freeing the returned object.
237 // TODO(hbos,torbjorng): Rename to a less confusing name.
238 virtual SSLIdentity* GetReference() const = 0;
239
240 // Returns a temporary reference to the certificate.
241 virtual const SSLCertificate& certificate() const = 0;
242 virtual std::string PrivateKeyToPEMString() const = 0;
243 virtual std::string PublicKeyToPEMString() const = 0;
244
245 // Helpers for parsing converting between PEM and DER format.
246 static bool PemToDer(const std::string& pem_type,
247 const std::string& pem_string,
248 std::string* der);
249 static std::string DerToPem(const std::string& pem_type,
250 const unsigned char* data,
251 size_t length);
252};
253
254bool operator==(const SSLIdentity& a, const SSLIdentity& b);
255bool operator!=(const SSLIdentity& a, const SSLIdentity& b);
256
257// Convert from ASN1 time as restricted by RFC 5280 to seconds from 1970-01-01
258// 00.00 ("epoch"). If the ASN1 time cannot be read, return -1. The data at
259// |s| is not 0-terminated; its char count is defined by |length|.
260int64_t ASN1TimeToSec(const unsigned char* s, size_t length, bool long_format);
261
262extern const char kPemTypeCertificate[];
263extern const char kPemTypeRsaPrivateKey[];
264extern const char kPemTypeEcPrivateKey[];
265
266} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000267
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200268#endif // RTC_BASE_SSLIDENTITY_H_