blob: 79e2ad56b7d749ea05682bc3db4836d819de8221 [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.
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020012#include "rtc_base/sslidentity.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000013
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +010014#include <ctime>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000015#include <string>
David Benjamin3df76b12017-09-29 12:27:18 -040016#include <utility>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000017
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "rtc_base/base64.h"
19#include "rtc_base/checks.h"
20#include "rtc_base/logging.h"
21#include "rtc_base/opensslidentity.h"
David Benjamin3df76b12017-09-29 12:27:18 -040022#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "rtc_base/sslfingerprint.h"
deadbeeff33491e2017-01-20 17:01:45 -080024
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000025namespace rtc {
26
27const char kPemTypeCertificate[] = "CERTIFICATE";
28const char kPemTypeRsaPrivateKey[] = "RSA PRIVATE KEY";
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020029const char kPemTypeEcPrivateKey[] = "EC PRIVATE KEY";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000030
hbose29352b2016-08-25 03:52:38 -070031SSLCertificateStats::SSLCertificateStats(
32 std::string&& fingerprint,
33 std::string&& fingerprint_algorithm,
34 std::string&& base64_certificate,
35 std::unique_ptr<SSLCertificateStats>&& issuer)
36 : fingerprint(std::move(fingerprint)),
37 fingerprint_algorithm(std::move(fingerprint_algorithm)),
38 base64_certificate(std::move(base64_certificate)),
39 issuer(std::move(issuer)) {
40}
41
42SSLCertificateStats::~SSLCertificateStats() {
43}
44
45std::unique_ptr<SSLCertificateStats> SSLCertificate::GetStats() const {
46 // We have a certificate and optionally a chain of certificates. This forms a
47 // linked list, starting with |this|, then the first element of |chain| and
48 // ending with the last element of |chain|. The "issuer" of a certificate is
49 // the next certificate in the chain. Stats are produced for each certificate
50 // in the list. Here, the "issuer" is the issuer's stats.
51 std::unique_ptr<SSLCertChain> chain = GetChain();
52 std::unique_ptr<SSLCertificateStats> issuer;
53 if (chain) {
54 // The loop runs in reverse so that the |issuer| is known before the
55 // |cert|'s stats.
56 for (ptrdiff_t i = chain->GetSize() - 1; i >= 0; --i) {
57 const SSLCertificate* cert = &chain->Get(i);
58 issuer = cert->GetStats(std::move(issuer));
59 }
60 }
61 return GetStats(std::move(issuer));
62}
63
David Benjamin3df76b12017-09-29 12:27:18 -040064std::unique_ptr<SSLCertificate> SSLCertificate::GetUniqueReference() const {
65 return WrapUnique(GetReference());
66}
67
hbose29352b2016-08-25 03:52:38 -070068std::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
David Benjamin3df76b12017-09-29 12:27:18 -0400202SSLCertChain::SSLCertChain(std::vector<std::unique_ptr<SSLCertificate>> certs)
203 : certs_(std::move(certs)) {}
204
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000205SSLCertChain::SSLCertChain(const std::vector<SSLCertificate*>& certs) {
nisseede5da42017-01-12 05:15:36 -0800206 RTC_DCHECK(!certs.empty());
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000207 certs_.resize(certs.size());
David Benjamin3df76b12017-09-29 12:27:18 -0400208 std::transform(
209 certs.begin(), certs.end(), certs_.begin(),
210 [](const SSLCertificate* cert) -> std::unique_ptr<SSLCertificate> {
211 return cert->GetUniqueReference();
212 });
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000213}
214
215SSLCertChain::SSLCertChain(const SSLCertificate* cert) {
David Benjamin3df76b12017-09-29 12:27:18 -0400216 certs_.push_back(cert->GetUniqueReference());
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000217}
218
David Benjamin3df76b12017-09-29 12:27:18 -0400219SSLCertChain::~SSLCertChain() {}
220
221SSLCertChain* SSLCertChain::Copy() const {
222 std::vector<std::unique_ptr<SSLCertificate>> new_certs(certs_.size());
223 std::transform(certs_.begin(), certs_.end(), new_certs.begin(),
224 [](const std::unique_ptr<SSLCertificate>& cert)
225 -> std::unique_ptr<SSLCertificate> {
226 return cert->GetUniqueReference();
227 });
228 return new SSLCertChain(std::move(new_certs));
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000229}
230
Torbjorn Granlunda3dc79e2016-02-16 13:33:53 +0100231// static
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000232SSLCertificate* SSLCertificate::FromPEMString(const std::string& pem_string) {
233 return OpenSSLCertificate::FromPEMString(pem_string);
234}
235
Torbjorn Granlunda3dc79e2016-02-16 13:33:53 +0100236// static
Torbjorn Granlund1d846b22016-03-31 16:21:04 +0200237SSLIdentity* SSLIdentity::GenerateWithExpiration(const std::string& common_name,
238 const KeyParams& key_params,
239 time_t certificate_lifetime) {
240 return OpenSSLIdentity::GenerateWithExpiration(common_name, key_params,
241 certificate_lifetime);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000242}
243
Torbjorn Granlunda3dc79e2016-02-16 13:33:53 +0100244// static
245SSLIdentity* SSLIdentity::Generate(const std::string& common_name,
246 const KeyParams& key_params) {
Torbjorn Granlund1d846b22016-03-31 16:21:04 +0200247 return OpenSSLIdentity::GenerateWithExpiration(
248 common_name, key_params, kDefaultCertificateLifetimeInSeconds);
Torbjorn Granlunda3dc79e2016-02-16 13:33:53 +0100249}
250
251// static
252SSLIdentity* SSLIdentity::Generate(const std::string& common_name,
253 KeyType key_type) {
Torbjorn Granlund1d846b22016-03-31 16:21:04 +0200254 return OpenSSLIdentity::GenerateWithExpiration(
255 common_name, KeyParams(key_type), kDefaultCertificateLifetimeInSeconds);
Torbjorn Granlunda3dc79e2016-02-16 13:33:53 +0100256}
257
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000258SSLIdentity* SSLIdentity::GenerateForTest(const SSLIdentityParams& params) {
259 return OpenSSLIdentity::GenerateForTest(params);
260}
261
Torbjorn Granlunda3dc79e2016-02-16 13:33:53 +0100262// static
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000263SSLIdentity* SSLIdentity::FromPEMStrings(const std::string& private_key,
264 const std::string& certificate) {
265 return OpenSSLIdentity::FromPEMStrings(private_key, certificate);
266}
267
hbos6b470a92016-04-28 05:14:21 -0700268bool operator==(const SSLIdentity& a, const SSLIdentity& b) {
269 return static_cast<const OpenSSLIdentity&>(a) ==
270 static_cast<const OpenSSLIdentity&>(b);
271}
272bool operator!=(const SSLIdentity& a, const SSLIdentity& b) {
273 return !(a == b);
274}
275
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100276// Read |n| bytes from ASN1 number string at *|pp| and return the numeric value.
277// Update *|pp| and *|np| to reflect number of read bytes.
278static inline int ASN1ReadInt(const unsigned char** pp, size_t* np, size_t n) {
279 const unsigned char* p = *pp;
280 int x = 0;
281 for (size_t i = 0; i < n; i++)
282 x = 10 * x + p[i] - '0';
283 *pp = p + n;
284 *np = *np - n;
285 return x;
286}
287
288int64_t ASN1TimeToSec(const unsigned char* s, size_t length, bool long_format) {
289 size_t bytes_left = length;
290
291 // Make sure the string ends with Z. Doing it here protects the strspn call
292 // from running off the end of the string in Z's absense.
293 if (length == 0 || s[length - 1] != 'Z')
294 return -1;
295
296 // Make sure we only have ASCII digits so that we don't need to clutter the
297 // code below and ASN1ReadInt with error checking.
298 size_t n = strspn(reinterpret_cast<const char*>(s), "0123456789");
299 if (n + 1 != length)
300 return -1;
301
302 int year;
303
304 // Read out ASN1 year, in either 2-char "UTCTIME" or 4-char "GENERALIZEDTIME"
305 // format. Both format use UTC in this context.
306 if (long_format) {
307 // ASN1 format: yyyymmddhh[mm[ss[.fff]]]Z where the Z is literal, but
308 // RFC 5280 requires us to only support exactly yyyymmddhhmmssZ.
309
310 if (bytes_left < 11)
311 return -1;
312
313 year = ASN1ReadInt(&s, &bytes_left, 4);
314 year -= 1900;
315 } else {
316 // ASN1 format: yymmddhhmm[ss]Z where the Z is literal, but RFC 5280
317 // requires us to only support exactly yymmddhhmmssZ.
318
319 if (bytes_left < 9)
320 return -1;
321
322 year = ASN1ReadInt(&s, &bytes_left, 2);
323 if (year < 50) // Per RFC 5280 4.1.2.5.1
324 year += 100;
325 }
326
327 std::tm tm;
328 tm.tm_year = year;
329
330 // Read out remaining ASN1 time data and store it in |tm| in documented
331 // std::tm format.
332 tm.tm_mon = ASN1ReadInt(&s, &bytes_left, 2) - 1;
333 tm.tm_mday = ASN1ReadInt(&s, &bytes_left, 2);
334 tm.tm_hour = ASN1ReadInt(&s, &bytes_left, 2);
335 tm.tm_min = ASN1ReadInt(&s, &bytes_left, 2);
336 tm.tm_sec = ASN1ReadInt(&s, &bytes_left, 2);
337
338 if (bytes_left != 1) {
339 // Now just Z should remain. Its existence was asserted above.
340 return -1;
341 }
342
343 return TmToSeconds(tm);
344}
345
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000346} // namespace rtc