blob: 1514e52be1f63c935ff3060449ebec75bbb957db [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 {
hbose29352b2016-08-25 03:52:38 -070046 // TODO(bemasc): Move this computation to a helper class that caches these
47 // values to reduce CPU use in |StatsCollector::GetStats|. This will require
48 // adding a fast |SSLCertificate::Equals| to detect certificate changes.
49 std::string digest_algorithm;
50 if (!GetSignatureDigestAlgorithm(&digest_algorithm))
51 return nullptr;
52
53 // |SSLFingerprint::Create| can fail if the algorithm returned by
54 // |SSLCertificate::GetSignatureDigestAlgorithm| is not supported by the
55 // implementation of |SSLCertificate::ComputeDigest|. This currently happens
56 // with MD5- and SHA-224-signed certificates when linked to libNSS.
57 std::unique_ptr<SSLFingerprint> ssl_fingerprint(
58 SSLFingerprint::Create(digest_algorithm, this));
59 if (!ssl_fingerprint)
60 return nullptr;
61 std::string fingerprint = ssl_fingerprint->GetRfc4572Fingerprint();
62
63 Buffer der_buffer;
64 ToDER(&der_buffer);
65 std::string der_base64;
66 Base64::EncodeFromArray(der_buffer.data(), der_buffer.size(), &der_base64);
67
Taylor Brandstetterc3928662018-02-23 13:04:51 -080068 return rtc::MakeUnique<SSLCertificateStats>(std::move(fingerprint),
69 std::move(digest_algorithm),
70 std::move(der_base64), nullptr);
71}
72
73std::unique_ptr<SSLCertificate> SSLCertificate::GetUniqueReference() const {
74 return WrapUnique(GetReference());
hbose29352b2016-08-25 03:52:38 -070075}
76
torbjorng4e572472015-10-08 09:42:49 -070077KeyParams::KeyParams(KeyType key_type) {
78 if (key_type == KT_ECDSA) {
79 type_ = KT_ECDSA;
80 params_.curve = EC_NIST_P256;
81 } else if (key_type == KT_RSA) {
82 type_ = KT_RSA;
83 params_.rsa.mod_size = kRsaDefaultModSize;
84 params_.rsa.pub_exp = kRsaDefaultExponent;
85 } else {
86 RTC_NOTREACHED();
87 }
88}
89
90// static
91KeyParams KeyParams::RSA(int mod_size, int pub_exp) {
92 KeyParams kt(KT_RSA);
93 kt.params_.rsa.mod_size = mod_size;
94 kt.params_.rsa.pub_exp = pub_exp;
95 return kt;
96}
97
98// static
99KeyParams KeyParams::ECDSA(ECCurve curve) {
100 KeyParams kt(KT_ECDSA);
101 kt.params_.curve = curve;
102 return kt;
103}
104
105bool KeyParams::IsValid() const {
106 if (type_ == KT_RSA) {
107 return (params_.rsa.mod_size >= kRsaMinModSize &&
108 params_.rsa.mod_size <= kRsaMaxModSize &&
109 params_.rsa.pub_exp > params_.rsa.mod_size);
110 } else if (type_ == KT_ECDSA) {
111 return (params_.curve == EC_NIST_P256);
112 }
113 return false;
114}
115
116RSAParams KeyParams::rsa_params() const {
117 RTC_DCHECK(type_ == KT_RSA);
118 return params_.rsa;
119}
120
121ECCurve KeyParams::ec_curve() const {
122 RTC_DCHECK(type_ == KT_ECDSA);
123 return params_.curve;
124}
125
Henrik Boström9b5476d2015-09-22 14:12:57 +0200126KeyType IntKeyTypeFamilyToKeyType(int key_type_family) {
127 return static_cast<KeyType>(key_type_family);
128}
129
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000130bool SSLIdentity::PemToDer(const std::string& pem_type,
131 const std::string& pem_string,
132 std::string* der) {
133 // Find the inner body. We need this to fulfill the contract of
134 // returning pem_length.
135 size_t header = pem_string.find("-----BEGIN " + pem_type + "-----");
136 if (header == std::string::npos)
137 return false;
138
139 size_t body = pem_string.find("\n", header);
140 if (body == std::string::npos)
141 return false;
142
143 size_t trailer = pem_string.find("-----END " + pem_type + "-----");
144 if (trailer == std::string::npos)
145 return false;
146
147 std::string inner = pem_string.substr(body + 1, trailer - (body + 1));
148
149 *der = Base64::Decode(inner, Base64::DO_PARSE_WHITE |
150 Base64::DO_PAD_ANY |
151 Base64::DO_TERM_BUFFER);
152 return true;
153}
154
155std::string SSLIdentity::DerToPem(const std::string& pem_type,
156 const unsigned char* data,
157 size_t length) {
158 std::stringstream result;
159
160 result << "-----BEGIN " << pem_type << "-----\n";
161
162 std::string b64_encoded;
163 Base64::EncodeFromArray(data, length, &b64_encoded);
164
165 // Divide the Base-64 encoded data into 64-character chunks, as per
166 // 4.3.2.4 of RFC 1421.
167 static const size_t kChunkSize = 64;
168 size_t chunks = (b64_encoded.size() + (kChunkSize - 1)) / kChunkSize;
169 for (size_t i = 0, chunk_offset = 0; i < chunks;
170 ++i, chunk_offset += kChunkSize) {
171 result << b64_encoded.substr(chunk_offset, kChunkSize);
172 result << "\n";
173 }
174
175 result << "-----END " << pem_type << "-----\n";
176
177 return result.str();
178}
179
David Benjamin3df76b12017-09-29 12:27:18 -0400180SSLCertChain::SSLCertChain(std::vector<std::unique_ptr<SSLCertificate>> certs)
181 : certs_(std::move(certs)) {}
182
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000183SSLCertChain::SSLCertChain(const std::vector<SSLCertificate*>& certs) {
nisseede5da42017-01-12 05:15:36 -0800184 RTC_DCHECK(!certs.empty());
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000185 certs_.resize(certs.size());
David Benjamin3df76b12017-09-29 12:27:18 -0400186 std::transform(
187 certs.begin(), certs.end(), certs_.begin(),
188 [](const SSLCertificate* cert) -> std::unique_ptr<SSLCertificate> {
189 return cert->GetUniqueReference();
190 });
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000191}
192
193SSLCertChain::SSLCertChain(const SSLCertificate* cert) {
David Benjamin3df76b12017-09-29 12:27:18 -0400194 certs_.push_back(cert->GetUniqueReference());
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000195}
196
David Benjamin3df76b12017-09-29 12:27:18 -0400197SSLCertChain::~SSLCertChain() {}
198
199SSLCertChain* SSLCertChain::Copy() const {
200 std::vector<std::unique_ptr<SSLCertificate>> new_certs(certs_.size());
201 std::transform(certs_.begin(), certs_.end(), new_certs.begin(),
202 [](const std::unique_ptr<SSLCertificate>& cert)
203 -> std::unique_ptr<SSLCertificate> {
204 return cert->GetUniqueReference();
205 });
206 return new SSLCertChain(std::move(new_certs));
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000207}
208
Taylor Brandstetterc3928662018-02-23 13:04:51 -0800209std::unique_ptr<SSLCertChain> SSLCertChain::UniqueCopy() const {
210 return WrapUnique(Copy());
211}
212
213std::unique_ptr<SSLCertificateStats> SSLCertChain::GetStats() const {
214 // We have a linked list of certificates, starting with the first element of
215 // |certs_| and ending with the last element of |certs_|. The "issuer" of a
216 // certificate is the next certificate in the chain. Stats are produced for
217 // each certificate in the list. Here, the "issuer" is the issuer's stats.
218 std::unique_ptr<SSLCertificateStats> issuer;
219 // The loop runs in reverse so that the |issuer| is known before the
220 // certificate issued by |issuer|.
221 for (ptrdiff_t i = certs_.size() - 1; i >= 0; --i) {
222 std::unique_ptr<SSLCertificateStats> new_stats = certs_[i]->GetStats();
223 if (new_stats) {
224 new_stats->issuer = std::move(issuer);
225 }
226 issuer = std::move(new_stats);
227 }
228 return issuer;
229}
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
Jian Cui0a8798b2017-11-16 16:58:02 -0800268// static
269SSLIdentity* SSLIdentity::FromPEMChainStrings(
270 const std::string& private_key,
271 const std::string& certificate_chain) {
272 return OpenSSLIdentity::FromPEMChainStrings(private_key, certificate_chain);
273}
274
hbos6b470a92016-04-28 05:14:21 -0700275bool operator==(const SSLIdentity& a, const SSLIdentity& b) {
276 return static_cast<const OpenSSLIdentity&>(a) ==
277 static_cast<const OpenSSLIdentity&>(b);
278}
279bool operator!=(const SSLIdentity& a, const SSLIdentity& b) {
280 return !(a == b);
281}
282
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100283// Read |n| bytes from ASN1 number string at *|pp| and return the numeric value.
284// Update *|pp| and *|np| to reflect number of read bytes.
285static inline int ASN1ReadInt(const unsigned char** pp, size_t* np, size_t n) {
286 const unsigned char* p = *pp;
287 int x = 0;
288 for (size_t i = 0; i < n; i++)
289 x = 10 * x + p[i] - '0';
290 *pp = p + n;
291 *np = *np - n;
292 return x;
293}
294
295int64_t ASN1TimeToSec(const unsigned char* s, size_t length, bool long_format) {
296 size_t bytes_left = length;
297
298 // Make sure the string ends with Z. Doing it here protects the strspn call
299 // from running off the end of the string in Z's absense.
300 if (length == 0 || s[length - 1] != 'Z')
301 return -1;
302
303 // Make sure we only have ASCII digits so that we don't need to clutter the
304 // code below and ASN1ReadInt with error checking.
305 size_t n = strspn(reinterpret_cast<const char*>(s), "0123456789");
306 if (n + 1 != length)
307 return -1;
308
309 int year;
310
311 // Read out ASN1 year, in either 2-char "UTCTIME" or 4-char "GENERALIZEDTIME"
312 // format. Both format use UTC in this context.
313 if (long_format) {
314 // ASN1 format: yyyymmddhh[mm[ss[.fff]]]Z where the Z is literal, but
315 // RFC 5280 requires us to only support exactly yyyymmddhhmmssZ.
316
317 if (bytes_left < 11)
318 return -1;
319
320 year = ASN1ReadInt(&s, &bytes_left, 4);
321 year -= 1900;
322 } else {
323 // ASN1 format: yymmddhhmm[ss]Z where the Z is literal, but RFC 5280
324 // requires us to only support exactly yymmddhhmmssZ.
325
326 if (bytes_left < 9)
327 return -1;
328
329 year = ASN1ReadInt(&s, &bytes_left, 2);
330 if (year < 50) // Per RFC 5280 4.1.2.5.1
331 year += 100;
332 }
333
334 std::tm tm;
335 tm.tm_year = year;
336
337 // Read out remaining ASN1 time data and store it in |tm| in documented
338 // std::tm format.
339 tm.tm_mon = ASN1ReadInt(&s, &bytes_left, 2) - 1;
340 tm.tm_mday = ASN1ReadInt(&s, &bytes_left, 2);
341 tm.tm_hour = ASN1ReadInt(&s, &bytes_left, 2);
342 tm.tm_min = ASN1ReadInt(&s, &bytes_left, 2);
343 tm.tm_sec = ASN1ReadInt(&s, &bytes_left, 2);
344
345 if (bytes_left != 1) {
346 // Now just Z should remain. Its existence was asserted above.
347 return -1;
348 }
349
350 return TmToSeconds(tm);
351}
352
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000353} // namespace rtc