blob: 645050a7e4b9deccc0b045d4539c6a2cc5f35b93 [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.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000012#include "webrtc/base/sslidentity.h"
13
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +010014#include <ctime>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000015#include <string>
16
17#include "webrtc/base/base64.h"
torbjorng4e572472015-10-08 09:42:49 -070018#include "webrtc/base/checks.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000019#include "webrtc/base/logging.h"
deadbeeff33491e2017-01-20 17:01:45 -080020#include "webrtc/base/sslconfig.h"
deadbeefeaa826c2017-01-20 15:15:58 -080021#include "webrtc/base/sslfingerprint.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000022
deadbeeff33491e2017-01-20 17:01:45 -080023#if SSL_USE_OPENSSL
24
25#include "webrtc/base/opensslidentity.h"
26
27#endif // SSL_USE_OPENSSL
28
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000029namespace rtc {
30
31const char kPemTypeCertificate[] = "CERTIFICATE";
32const char kPemTypeRsaPrivateKey[] = "RSA PRIVATE KEY";
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020033const char kPemTypeEcPrivateKey[] = "EC PRIVATE KEY";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000034
hbose29352b2016-08-25 03:52:38 -070035SSLCertificateStats::SSLCertificateStats(
36 std::string&& fingerprint,
37 std::string&& fingerprint_algorithm,
38 std::string&& base64_certificate,
39 std::unique_ptr<SSLCertificateStats>&& issuer)
40 : fingerprint(std::move(fingerprint)),
41 fingerprint_algorithm(std::move(fingerprint_algorithm)),
42 base64_certificate(std::move(base64_certificate)),
43 issuer(std::move(issuer)) {
44}
45
46SSLCertificateStats::~SSLCertificateStats() {
47}
48
49std::unique_ptr<SSLCertificateStats> SSLCertificate::GetStats() const {
50 // We have a certificate and optionally a chain of certificates. This forms a
51 // linked list, starting with |this|, then the first element of |chain| and
52 // ending with the last element of |chain|. The "issuer" of a certificate is
53 // the next certificate in the chain. Stats are produced for each certificate
54 // in the list. Here, the "issuer" is the issuer's stats.
55 std::unique_ptr<SSLCertChain> chain = GetChain();
56 std::unique_ptr<SSLCertificateStats> issuer;
57 if (chain) {
58 // The loop runs in reverse so that the |issuer| is known before the
59 // |cert|'s stats.
60 for (ptrdiff_t i = chain->GetSize() - 1; i >= 0; --i) {
61 const SSLCertificate* cert = &chain->Get(i);
62 issuer = cert->GetStats(std::move(issuer));
63 }
64 }
65 return GetStats(std::move(issuer));
66}
67
68std::unique_ptr<SSLCertificateStats> SSLCertificate::GetStats(
69 std::unique_ptr<SSLCertificateStats> issuer) const {
70 // TODO(bemasc): Move this computation to a helper class that caches these
71 // values to reduce CPU use in |StatsCollector::GetStats|. This will require
72 // adding a fast |SSLCertificate::Equals| to detect certificate changes.
73 std::string digest_algorithm;
74 if (!GetSignatureDigestAlgorithm(&digest_algorithm))
75 return nullptr;
76
77 // |SSLFingerprint::Create| can fail if the algorithm returned by
78 // |SSLCertificate::GetSignatureDigestAlgorithm| is not supported by the
79 // implementation of |SSLCertificate::ComputeDigest|. This currently happens
80 // with MD5- and SHA-224-signed certificates when linked to libNSS.
81 std::unique_ptr<SSLFingerprint> ssl_fingerprint(
82 SSLFingerprint::Create(digest_algorithm, this));
83 if (!ssl_fingerprint)
84 return nullptr;
85 std::string fingerprint = ssl_fingerprint->GetRfc4572Fingerprint();
86
87 Buffer der_buffer;
88 ToDER(&der_buffer);
89 std::string der_base64;
90 Base64::EncodeFromArray(der_buffer.data(), der_buffer.size(), &der_base64);
91
92 return std::unique_ptr<SSLCertificateStats>(new SSLCertificateStats(
93 std::move(fingerprint),
94 std::move(digest_algorithm),
95 std::move(der_base64),
96 std::move(issuer)));
97}
98
torbjorng4e572472015-10-08 09:42:49 -070099KeyParams::KeyParams(KeyType key_type) {
100 if (key_type == KT_ECDSA) {
101 type_ = KT_ECDSA;
102 params_.curve = EC_NIST_P256;
103 } else if (key_type == KT_RSA) {
104 type_ = KT_RSA;
105 params_.rsa.mod_size = kRsaDefaultModSize;
106 params_.rsa.pub_exp = kRsaDefaultExponent;
107 } else {
108 RTC_NOTREACHED();
109 }
110}
111
112// static
113KeyParams KeyParams::RSA(int mod_size, int pub_exp) {
114 KeyParams kt(KT_RSA);
115 kt.params_.rsa.mod_size = mod_size;
116 kt.params_.rsa.pub_exp = pub_exp;
117 return kt;
118}
119
120// static
121KeyParams KeyParams::ECDSA(ECCurve curve) {
122 KeyParams kt(KT_ECDSA);
123 kt.params_.curve = curve;
124 return kt;
125}
126
127bool KeyParams::IsValid() const {
128 if (type_ == KT_RSA) {
129 return (params_.rsa.mod_size >= kRsaMinModSize &&
130 params_.rsa.mod_size <= kRsaMaxModSize &&
131 params_.rsa.pub_exp > params_.rsa.mod_size);
132 } else if (type_ == KT_ECDSA) {
133 return (params_.curve == EC_NIST_P256);
134 }
135 return false;
136}
137
138RSAParams KeyParams::rsa_params() const {
139 RTC_DCHECK(type_ == KT_RSA);
140 return params_.rsa;
141}
142
143ECCurve KeyParams::ec_curve() const {
144 RTC_DCHECK(type_ == KT_ECDSA);
145 return params_.curve;
146}
147
Henrik Boström9b5476d2015-09-22 14:12:57 +0200148KeyType IntKeyTypeFamilyToKeyType(int key_type_family) {
149 return static_cast<KeyType>(key_type_family);
150}
151
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000152bool SSLIdentity::PemToDer(const std::string& pem_type,
153 const std::string& pem_string,
154 std::string* der) {
155 // Find the inner body. We need this to fulfill the contract of
156 // returning pem_length.
157 size_t header = pem_string.find("-----BEGIN " + pem_type + "-----");
158 if (header == std::string::npos)
159 return false;
160
161 size_t body = pem_string.find("\n", header);
162 if (body == std::string::npos)
163 return false;
164
165 size_t trailer = pem_string.find("-----END " + pem_type + "-----");
166 if (trailer == std::string::npos)
167 return false;
168
169 std::string inner = pem_string.substr(body + 1, trailer - (body + 1));
170
171 *der = Base64::Decode(inner, Base64::DO_PARSE_WHITE |
172 Base64::DO_PAD_ANY |
173 Base64::DO_TERM_BUFFER);
174 return true;
175}
176
177std::string SSLIdentity::DerToPem(const std::string& pem_type,
178 const unsigned char* data,
179 size_t length) {
180 std::stringstream result;
181
182 result << "-----BEGIN " << pem_type << "-----\n";
183
184 std::string b64_encoded;
185 Base64::EncodeFromArray(data, length, &b64_encoded);
186
187 // Divide the Base-64 encoded data into 64-character chunks, as per
188 // 4.3.2.4 of RFC 1421.
189 static const size_t kChunkSize = 64;
190 size_t chunks = (b64_encoded.size() + (kChunkSize - 1)) / kChunkSize;
191 for (size_t i = 0, chunk_offset = 0; i < chunks;
192 ++i, chunk_offset += kChunkSize) {
193 result << b64_encoded.substr(chunk_offset, kChunkSize);
194 result << "\n";
195 }
196
197 result << "-----END " << pem_type << "-----\n";
198
199 return result.str();
200}
201
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000202SSLCertChain::SSLCertChain(const std::vector<SSLCertificate*>& certs) {
nisseede5da42017-01-12 05:15:36 -0800203 RTC_DCHECK(!certs.empty());
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000204 certs_.resize(certs.size());
205 std::transform(certs.begin(), certs.end(), certs_.begin(), DupCert);
206}
207
208SSLCertChain::SSLCertChain(const SSLCertificate* cert) {
209 certs_.push_back(cert->GetReference());
210}
211
212SSLCertChain::~SSLCertChain() {
213 std::for_each(certs_.begin(), certs_.end(), DeleteCert);
214}
215
deadbeeff33491e2017-01-20 17:01:45 -0800216#if SSL_USE_OPENSSL
217
Torbjorn Granlunda3dc79e2016-02-16 13:33:53 +0100218// static
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000219SSLCertificate* SSLCertificate::FromPEMString(const std::string& pem_string) {
220 return OpenSSLCertificate::FromPEMString(pem_string);
221}
222
Torbjorn Granlunda3dc79e2016-02-16 13:33:53 +0100223// static
Torbjorn Granlund1d846b22016-03-31 16:21:04 +0200224SSLIdentity* SSLIdentity::GenerateWithExpiration(const std::string& common_name,
225 const KeyParams& key_params,
226 time_t certificate_lifetime) {
227 return OpenSSLIdentity::GenerateWithExpiration(common_name, key_params,
228 certificate_lifetime);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000229}
230
Torbjorn Granlunda3dc79e2016-02-16 13:33:53 +0100231// static
232SSLIdentity* SSLIdentity::Generate(const std::string& common_name,
233 const KeyParams& key_params) {
Torbjorn Granlund1d846b22016-03-31 16:21:04 +0200234 return OpenSSLIdentity::GenerateWithExpiration(
235 common_name, key_params, kDefaultCertificateLifetimeInSeconds);
Torbjorn Granlunda3dc79e2016-02-16 13:33:53 +0100236}
237
238// static
239SSLIdentity* SSLIdentity::Generate(const std::string& common_name,
240 KeyType key_type) {
Torbjorn Granlund1d846b22016-03-31 16:21:04 +0200241 return OpenSSLIdentity::GenerateWithExpiration(
242 common_name, KeyParams(key_type), kDefaultCertificateLifetimeInSeconds);
Torbjorn Granlunda3dc79e2016-02-16 13:33:53 +0100243}
244
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000245SSLIdentity* SSLIdentity::GenerateForTest(const SSLIdentityParams& params) {
246 return OpenSSLIdentity::GenerateForTest(params);
247}
248
Torbjorn Granlunda3dc79e2016-02-16 13:33:53 +0100249// static
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000250SSLIdentity* SSLIdentity::FromPEMStrings(const std::string& private_key,
251 const std::string& certificate) {
252 return OpenSSLIdentity::FromPEMStrings(private_key, certificate);
253}
254
hbos6b470a92016-04-28 05:14:21 -0700255bool operator==(const SSLIdentity& a, const SSLIdentity& b) {
256 return static_cast<const OpenSSLIdentity&>(a) ==
257 static_cast<const OpenSSLIdentity&>(b);
258}
259bool operator!=(const SSLIdentity& a, const SSLIdentity& b) {
260 return !(a == b);
261}
262
deadbeeff33491e2017-01-20 17:01:45 -0800263#else // !SSL_USE_OPENSSL
264
265#error "No SSL implementation"
266
267#endif // SSL_USE_OPENSSL
268
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100269// Read |n| bytes from ASN1 number string at *|pp| and return the numeric value.
270// Update *|pp| and *|np| to reflect number of read bytes.
271static inline int ASN1ReadInt(const unsigned char** pp, size_t* np, size_t n) {
272 const unsigned char* p = *pp;
273 int x = 0;
274 for (size_t i = 0; i < n; i++)
275 x = 10 * x + p[i] - '0';
276 *pp = p + n;
277 *np = *np - n;
278 return x;
279}
280
281int64_t ASN1TimeToSec(const unsigned char* s, size_t length, bool long_format) {
282 size_t bytes_left = length;
283
284 // Make sure the string ends with Z. Doing it here protects the strspn call
285 // from running off the end of the string in Z's absense.
286 if (length == 0 || s[length - 1] != 'Z')
287 return -1;
288
289 // Make sure we only have ASCII digits so that we don't need to clutter the
290 // code below and ASN1ReadInt with error checking.
291 size_t n = strspn(reinterpret_cast<const char*>(s), "0123456789");
292 if (n + 1 != length)
293 return -1;
294
295 int year;
296
297 // Read out ASN1 year, in either 2-char "UTCTIME" or 4-char "GENERALIZEDTIME"
298 // format. Both format use UTC in this context.
299 if (long_format) {
300 // ASN1 format: yyyymmddhh[mm[ss[.fff]]]Z where the Z is literal, but
301 // RFC 5280 requires us to only support exactly yyyymmddhhmmssZ.
302
303 if (bytes_left < 11)
304 return -1;
305
306 year = ASN1ReadInt(&s, &bytes_left, 4);
307 year -= 1900;
308 } else {
309 // ASN1 format: yymmddhhmm[ss]Z where the Z is literal, but RFC 5280
310 // requires us to only support exactly yymmddhhmmssZ.
311
312 if (bytes_left < 9)
313 return -1;
314
315 year = ASN1ReadInt(&s, &bytes_left, 2);
316 if (year < 50) // Per RFC 5280 4.1.2.5.1
317 year += 100;
318 }
319
320 std::tm tm;
321 tm.tm_year = year;
322
323 // Read out remaining ASN1 time data and store it in |tm| in documented
324 // std::tm format.
325 tm.tm_mon = ASN1ReadInt(&s, &bytes_left, 2) - 1;
326 tm.tm_mday = ASN1ReadInt(&s, &bytes_left, 2);
327 tm.tm_hour = ASN1ReadInt(&s, &bytes_left, 2);
328 tm.tm_min = ASN1ReadInt(&s, &bytes_left, 2);
329 tm.tm_sec = ASN1ReadInt(&s, &bytes_left, 2);
330
331 if (bytes_left != 1) {
332 // Now just Z should remain. Its existence was asserted above.
333 return -1;
334 }
335
336 return TmToSeconds(tm);
337}
338
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000339} // namespace rtc