blob: 7457ff56b7c92612d6e10deb0872b5eaba91d79a [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"
kwiberg4485ffb2016-04-26 08:14:39 -070022#include "webrtc/base/constructormagic.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000023#include "webrtc/base/messagedigest.h"
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +010024#include "webrtc/base/timeutils.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000025
26namespace rtc {
27
28// Forward declaration due to circular dependency with SSLCertificate.
29class SSLCertChain;
30
31// Abstract interface overridden by SSL library specific
32// implementations.
33
34// A somewhat opaque type used to encapsulate a certificate.
35// Wraps the SSL library's notion of a certificate, with reference counting.
36// The SSLCertificate object is pretty much immutable once created.
37// (The OpenSSL implementation only does reference counting and
38// possibly caching of intermediate results.)
39class SSLCertificate {
40 public:
torbjornge8dc0812016-02-15 09:35:54 -080041 // Parses and builds a certificate from a PEM encoded string.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000042 // Returns NULL on failure.
43 // The length of the string representation of the certificate is
44 // stored in *pem_length if it is non-NULL, and only if
45 // parsing was successful.
46 // Caller is responsible for freeing the returned object.
47 static SSLCertificate* FromPEMString(const std::string& pem_string);
48 virtual ~SSLCertificate() {}
49
50 // Returns a new SSLCertificate object instance wrapping the same
51 // underlying certificate, including its chain if present.
52 // Caller is responsible for freeing the returned object.
53 virtual SSLCertificate* GetReference() const = 0;
54
kwibergf5d47862016-03-15 12:53:24 -070055 // Provides the cert chain, or null. The chain includes a copy of each
56 // certificate, excluding the leaf.
jbauch555604a2016-04-26 03:13:22 -070057 virtual std::unique_ptr<SSLCertChain> GetChain() const = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000058
59 // Returns a PEM encoded string representation of the certificate.
60 virtual std::string ToPEMString() const = 0;
61
62 // Provides a DER encoded binary representation of the certificate.
63 virtual void ToDER(Buffer* der_buffer) const = 0;
64
65 // Gets the name of the digest algorithm that was used to compute this
66 // certificate's signature.
67 virtual bool GetSignatureDigestAlgorithm(std::string* algorithm) const = 0;
68
69 // Compute the digest of the certificate given algorithm
70 virtual bool ComputeDigest(const std::string& algorithm,
71 unsigned char* digest,
72 size_t size,
73 size_t* length) const = 0;
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +010074
hbos3980d462015-12-09 05:26:49 -080075 // Returns the time in seconds relative to epoch, 1970-01-01T00:00:00Z (UTC),
76 // or -1 if an expiration time could not be retrieved.
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +010077 virtual int64_t CertificateExpirationTime() const = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000078};
79
80// SSLCertChain is a simple wrapper for a vector of SSLCertificates. It serves
81// primarily to ensure proper memory management (especially deletion) of the
82// SSLCertificate pointers.
83class SSLCertChain {
84 public:
85 // These constructors copy the provided SSLCertificate(s), so the caller
86 // retains ownership.
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +000087 explicit SSLCertChain(const std::vector<SSLCertificate*>& certs);
88 explicit SSLCertChain(const SSLCertificate* cert);
89 ~SSLCertChain();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000090
91 // Vector access methods.
92 size_t GetSize() const { return certs_.size(); }
93
94 // Returns a temporary reference, only valid until the chain is destroyed.
95 const SSLCertificate& Get(size_t pos) const { return *(certs_[pos]); }
96
97 // Returns a new SSLCertChain object instance wrapping the same underlying
98 // certificate chain. Caller is responsible for freeing the returned object.
99 SSLCertChain* Copy() const {
100 return new SSLCertChain(certs_);
101 }
102
103 private:
104 // Helper function for duplicating a vector of certificates.
105 static SSLCertificate* DupCert(const SSLCertificate* cert) {
106 return cert->GetReference();
107 }
108
109 // Helper function for deleting a vector of certificates.
110 static void DeleteCert(SSLCertificate* cert) { delete cert; }
111
112 std::vector<SSLCertificate*> certs_;
113
henrikg3c089d72015-09-16 05:37:44 -0700114 RTC_DISALLOW_COPY_AND_ASSIGN(SSLCertChain);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000115};
116
torbjorng4e572472015-10-08 09:42:49 -0700117// KT_DEFAULT is currently an alias for KT_RSA. This is likely to change.
118// KT_LAST is intended for vector declarations and loops over all key types;
119// it does not represent any key type in itself.
Henrik Boström5e56c592015-08-11 10:33:13 +0200120enum KeyType { KT_RSA, KT_ECDSA, KT_LAST, KT_DEFAULT = KT_RSA };
121
torbjorng4e572472015-10-08 09:42:49 -0700122static const int kRsaDefaultModSize = 1024;
123static const int kRsaDefaultExponent = 0x10001; // = 2^16+1 = 65537
124static const int kRsaMinModSize = 1024;
125static const int kRsaMaxModSize = 8192;
126
torbjornge8dc0812016-02-15 09:35:54 -0800127// Certificate default validity lifetime.
Torbjorn Granlund1d846b22016-03-31 16:21:04 +0200128static const int kDefaultCertificateLifetimeInSeconds =
129 60 * 60 * 24 * 30; // 30 days
torbjornge8dc0812016-02-15 09:35:54 -0800130// Certificate validity window.
131// This is to compensate for slightly incorrect system clocks.
Torbjorn Granlund1d846b22016-03-31 16:21:04 +0200132static const int kCertificateWindowInSeconds = -60 * 60 * 24;
torbjornge8dc0812016-02-15 09:35:54 -0800133
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 Granlund1d846b22016-03-31 16:21:04 +0200200 static SSLIdentity* GenerateWithExpiration(const std::string& common_name,
201 const KeyParams& key_param,
202 time_t certificate_lifetime);
torbjornge8dc0812016-02-15 09:35:54 -0800203 static SSLIdentity* Generate(const std::string& common_name,
Torbjorn Granlunda3dc79e2016-02-16 13:33:53 +0100204 const KeyParams& key_param);
torbjorng4e572472015-10-08 09:42:49 -0700205 static SSLIdentity* Generate(const std::string& common_name,
Torbjorn Granlunda3dc79e2016-02-16 13:33:53 +0100206 KeyType key_type);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000207
208 // Generates an identity with the specified validity period.
torbjornge8dc0812016-02-15 09:35:54 -0800209 // TODO(torbjorng): Now that Generate() accepts relevant params, make tests
210 // use that instead of this function.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000211 static SSLIdentity* GenerateForTest(const SSLIdentityParams& params);
212
213 // Construct an identity from a private key and a certificate.
214 static SSLIdentity* FromPEMStrings(const std::string& private_key,
215 const std::string& certificate);
216
217 virtual ~SSLIdentity() {}
218
219 // Returns a new SSLIdentity object instance wrapping the same
220 // identity information.
221 // Caller is responsible for freeing the returned object.
Henrik Boström87713d02015-08-25 09:53:21 +0200222 // TODO(hbos,torbjorng): Rename to a less confusing name.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000223 virtual SSLIdentity* GetReference() const = 0;
224
225 // Returns a temporary reference to the certificate.
226 virtual const SSLCertificate& certificate() const = 0;
hbos6b470a92016-04-28 05:14:21 -0700227 virtual std::string PrivateKeyToPEMString() const = 0;
228 virtual std::string PublicKeyToPEMString() const = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000229
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
hbos6b470a92016-04-28 05:14:21 -0700239bool operator==(const SSLIdentity& a, const SSLIdentity& b);
240bool operator!=(const SSLIdentity& a, const SSLIdentity& b);
241
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100242// Convert from ASN1 time as restricted by RFC 5280 to seconds from 1970-01-01
243// 00.00 ("epoch"). If the ASN1 time cannot be read, return -1. The data at
244// |s| is not 0-terminated; its char count is defined by |length|.
245int64_t ASN1TimeToSec(const unsigned char* s, size_t length, bool long_format);
246
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000247extern const char kPemTypeCertificate[];
248extern const char kPemTypeRsaPrivateKey[];
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200249extern const char kPemTypeEcPrivateKey[];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000250
251} // namespace rtc
252
253#endif // WEBRTC_BASE_SSLIDENTITY_H_