blob: 8eb1c42d246a55fce191cc3162a0e26decf96a38 [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "rtc_base/opensslidentity.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000012
jbauch555604a2016-04-26 03:13:22 -070013#include <memory>
14
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000015// Must be included first before openssl headers.
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020016#include "rtc_base/win32.h" // NOLINT
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000017
18#include <openssl/bio.h>
19#include <openssl/err.h>
20#include <openssl/pem.h>
21#include <openssl/bn.h>
22#include <openssl/rsa.h>
23#include <openssl/crypto.h>
24
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "rtc_base/checks.h"
26#include "rtc_base/helpers.h"
27#include "rtc_base/logging.h"
28#include "rtc_base/openssl.h"
29#include "rtc_base/openssldigest.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000030
31namespace rtc {
32
33// We could have exposed a myriad of parameters for the crypto stuff,
34// but keeping it simple seems best.
35
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000036// Random bits for certificate serial number
37static const int SERIAL_RAND_BITS = 64;
38
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000039// Generate a key pair. Caller is responsible for freeing the returned object.
torbjorng4e572472015-10-08 09:42:49 -070040static EVP_PKEY* MakeKey(const KeyParams& key_params) {
Mirko Bonadei675513b2017-11-09 11:09:25 +010041 RTC_LOG(LS_INFO) << "Making key pair";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000042 EVP_PKEY* pkey = EVP_PKEY_new();
torbjorng4e572472015-10-08 09:42:49 -070043 if (key_params.type() == KT_RSA) {
44 int key_length = key_params.rsa_params().mod_size;
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020045 BIGNUM* exponent = BN_new();
46 RSA* rsa = RSA_new();
47 if (!pkey || !exponent || !rsa ||
torbjorng4e572472015-10-08 09:42:49 -070048 !BN_set_word(exponent, key_params.rsa_params().pub_exp) ||
deadbeef37f5ecf2017-02-27 14:06:41 -080049 !RSA_generate_key_ex(rsa, key_length, exponent, nullptr) ||
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020050 !EVP_PKEY_assign_RSA(pkey, rsa)) {
51 EVP_PKEY_free(pkey);
52 BN_free(exponent);
53 RSA_free(rsa);
Mirko Bonadei675513b2017-11-09 11:09:25 +010054 RTC_LOG(LS_ERROR) << "Failed to make RSA key pair";
deadbeef37f5ecf2017-02-27 14:06:41 -080055 return nullptr;
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020056 }
57 // ownership of rsa struct was assigned, don't free it.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000058 BN_free(exponent);
torbjorng4e572472015-10-08 09:42:49 -070059 } else if (key_params.type() == KT_ECDSA) {
60 if (key_params.ec_curve() == EC_NIST_P256) {
61 EC_KEY* ec_key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
ssarohabbfed522016-12-11 18:42:07 -080062
63 // Ensure curve name is included when EC key is serialized.
64 // Without this call, OpenSSL versions before 1.1.0 will create
65 // certificates that don't work for TLS.
66 // This is a no-op for BoringSSL and OpenSSL 1.1.0+
67 EC_KEY_set_asn1_flag(ec_key, OPENSSL_EC_NAMED_CURVE);
68
torbjorng4e572472015-10-08 09:42:49 -070069 if (!pkey || !ec_key || !EC_KEY_generate_key(ec_key) ||
70 !EVP_PKEY_assign_EC_KEY(pkey, ec_key)) {
71 EVP_PKEY_free(pkey);
72 EC_KEY_free(ec_key);
Mirko Bonadei675513b2017-11-09 11:09:25 +010073 RTC_LOG(LS_ERROR) << "Failed to make EC key pair";
deadbeef37f5ecf2017-02-27 14:06:41 -080074 return nullptr;
torbjorng4e572472015-10-08 09:42:49 -070075 }
76 // ownership of ec_key struct was assigned, don't free it.
77 } else {
78 // Add generation of any other curves here.
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020079 EVP_PKEY_free(pkey);
Mirko Bonadei675513b2017-11-09 11:09:25 +010080 RTC_LOG(LS_ERROR) << "ECDSA key requested for unknown curve";
deadbeef37f5ecf2017-02-27 14:06:41 -080081 return nullptr;
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020082 }
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020083 } else {
84 EVP_PKEY_free(pkey);
Mirko Bonadei675513b2017-11-09 11:09:25 +010085 RTC_LOG(LS_ERROR) << "Key type requested not understood";
deadbeef37f5ecf2017-02-27 14:06:41 -080086 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000087 }
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020088
Mirko Bonadei675513b2017-11-09 11:09:25 +010089 RTC_LOG(LS_INFO) << "Returning key pair";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000090 return pkey;
91}
92
93// Generate a self-signed certificate, with the public key from the
94// given key pair. Caller is responsible for freeing the returned object.
95static X509* MakeCertificate(EVP_PKEY* pkey, const SSLIdentityParams& params) {
Mirko Bonadei675513b2017-11-09 11:09:25 +010096 RTC_LOG(LS_INFO) << "Making certificate for " << params.common_name;
deadbeef37f5ecf2017-02-27 14:06:41 -080097 X509* x509 = nullptr;
98 BIGNUM* serial_number = nullptr;
99 X509_NAME* name = nullptr;
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100100 time_t epoch_off = 0; // Time offset since epoch.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000101
deadbeef37f5ecf2017-02-27 14:06:41 -0800102 if ((x509 = X509_new()) == nullptr)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000103 goto error;
104
105 if (!X509_set_pubkey(x509, pkey))
106 goto error;
107
108 // serial number
109 // temporary reference to serial number inside x509 struct
110 ASN1_INTEGER* asn1_serial_number;
deadbeef37f5ecf2017-02-27 14:06:41 -0800111 if ((serial_number = BN_new()) == nullptr ||
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000112 !BN_pseudo_rand(serial_number, SERIAL_RAND_BITS, 0, 0) ||
deadbeef37f5ecf2017-02-27 14:06:41 -0800113 (asn1_serial_number = X509_get_serialNumber(x509)) == nullptr ||
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000114 !BN_to_ASN1_INTEGER(serial_number, asn1_serial_number))
115 goto error;
116
torbjorngf8160352016-03-29 07:57:43 -0700117 if (!X509_set_version(x509, 2L)) // version 3
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000118 goto error;
119
120 // There are a lot of possible components for the name entries. In
121 // our P2P SSL mode however, the certificates are pre-exchanged
122 // (through the secure XMPP channel), and so the certificate
123 // identification is arbitrary. It can't be empty, so we set some
124 // arbitrary common_name. Note that this certificate goes out in
125 // clear during SSL negotiation, so there may be a privacy issue in
126 // putting anything recognizable here.
deadbeef37f5ecf2017-02-27 14:06:41 -0800127 if ((name = X509_NAME_new()) == nullptr ||
128 !X509_NAME_add_entry_by_NID(name, NID_commonName, MBSTRING_UTF8,
129 (unsigned char*)params.common_name.c_str(),
130 -1, -1, 0) ||
131 !X509_set_subject_name(x509, name) || !X509_set_issuer_name(x509, name))
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000132 goto error;
133
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100134 if (!X509_time_adj(X509_get_notBefore(x509), params.not_before, &epoch_off) ||
135 !X509_time_adj(X509_get_notAfter(x509), params.not_after, &epoch_off))
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000136 goto error;
137
Joachim Bauch1b794d52015-05-12 03:32:11 +0200138 if (!X509_sign(x509, pkey, EVP_sha256()))
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000139 goto error;
140
141 BN_free(serial_number);
142 X509_NAME_free(name);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100143 RTC_LOG(LS_INFO) << "Returning certificate";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000144 return x509;
145
146 error:
147 BN_free(serial_number);
148 X509_NAME_free(name);
149 X509_free(x509);
deadbeef37f5ecf2017-02-27 14:06:41 -0800150 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000151}
152
153// This dumps the SSL error stack to the log.
154static void LogSSLErrors(const std::string& prefix) {
155 char error_buf[200];
156 unsigned long err;
157
158 while ((err = ERR_get_error()) != 0) {
159 ERR_error_string_n(err, error_buf, sizeof(error_buf));
Mirko Bonadei675513b2017-11-09 11:09:25 +0100160 RTC_LOG(LS_ERROR) << prefix << ": " << error_buf << "\n";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000161 }
162}
163
torbjorng4e572472015-10-08 09:42:49 -0700164OpenSSLKeyPair* OpenSSLKeyPair::Generate(const KeyParams& key_params) {
165 EVP_PKEY* pkey = MakeKey(key_params);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000166 if (!pkey) {
167 LogSSLErrors("Generating key pair");
deadbeef37f5ecf2017-02-27 14:06:41 -0800168 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000169 }
170 return new OpenSSLKeyPair(pkey);
171}
172
hbos6b470a92016-04-28 05:14:21 -0700173OpenSSLKeyPair* OpenSSLKeyPair::FromPrivateKeyPEMString(
174 const std::string& pem_string) {
175 BIO* bio = BIO_new_mem_buf(const_cast<char*>(pem_string.c_str()), -1);
176 if (!bio) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100177 RTC_LOG(LS_ERROR) << "Failed to create a new BIO buffer.";
hbos6b470a92016-04-28 05:14:21 -0700178 return nullptr;
179 }
180 BIO_set_mem_eof_return(bio, 0);
181 EVP_PKEY* pkey =
182 PEM_read_bio_PrivateKey(bio, nullptr, nullptr, const_cast<char*>("\0"));
183 BIO_free(bio); // Frees the BIO, but not the pointed-to string.
184 if (!pkey) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100185 RTC_LOG(LS_ERROR) << "Failed to create the private key from PEM string.";
hbos6b470a92016-04-28 05:14:21 -0700186 return nullptr;
187 }
188 if (EVP_PKEY_missing_parameters(pkey) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100189 RTC_LOG(LS_ERROR)
190 << "The resulting key pair is missing public key parameters.";
hbos6b470a92016-04-28 05:14:21 -0700191 EVP_PKEY_free(pkey);
192 return nullptr;
193 }
194 return new OpenSSLKeyPair(pkey);
195}
196
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000197OpenSSLKeyPair::~OpenSSLKeyPair() {
198 EVP_PKEY_free(pkey_);
199}
200
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000201OpenSSLKeyPair* OpenSSLKeyPair::GetReference() {
202 AddReference();
203 return new OpenSSLKeyPair(pkey_);
204}
205
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000206void OpenSSLKeyPair::AddReference() {
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100207#if defined(OPENSSL_IS_BORINGSSL)
Jiayang Liu770cc382015-05-28 15:36:29 -0700208 EVP_PKEY_up_ref(pkey_);
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100209#else
210 CRYPTO_add(&pkey_->references, 1, CRYPTO_LOCK_EVP_PKEY);
211#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000212}
213
hbos6b470a92016-04-28 05:14:21 -0700214std::string OpenSSLKeyPair::PrivateKeyToPEMString() const {
215 BIO* temp_memory_bio = BIO_new(BIO_s_mem());
216 if (!temp_memory_bio) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100217 RTC_LOG_F(LS_ERROR) << "Failed to allocate temporary memory bio";
hbos6b470a92016-04-28 05:14:21 -0700218 RTC_NOTREACHED();
219 return "";
220 }
221 if (!PEM_write_bio_PrivateKey(
222 temp_memory_bio, pkey_, nullptr, nullptr, 0, nullptr, nullptr)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100223 RTC_LOG_F(LS_ERROR) << "Failed to write private key";
hbos6b470a92016-04-28 05:14:21 -0700224 BIO_free(temp_memory_bio);
225 RTC_NOTREACHED();
226 return "";
227 }
228 BIO_write(temp_memory_bio, "\0", 1);
229 char* buffer;
230 BIO_get_mem_data(temp_memory_bio, &buffer);
231 std::string priv_key_str = buffer;
232 BIO_free(temp_memory_bio);
233 return priv_key_str;
234}
235
236std::string OpenSSLKeyPair::PublicKeyToPEMString() const {
237 BIO* temp_memory_bio = BIO_new(BIO_s_mem());
238 if (!temp_memory_bio) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100239 RTC_LOG_F(LS_ERROR) << "Failed to allocate temporary memory bio";
hbos6b470a92016-04-28 05:14:21 -0700240 RTC_NOTREACHED();
241 return "";
242 }
243 if (!PEM_write_bio_PUBKEY(temp_memory_bio, pkey_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100244 RTC_LOG_F(LS_ERROR) << "Failed to write public key";
hbos6b470a92016-04-28 05:14:21 -0700245 BIO_free(temp_memory_bio);
246 RTC_NOTREACHED();
247 return "";
248 }
249 BIO_write(temp_memory_bio, "\0", 1);
250 char* buffer;
251 BIO_get_mem_data(temp_memory_bio, &buffer);
252 std::string pub_key_str = buffer;
253 BIO_free(temp_memory_bio);
254 return pub_key_str;
255}
256
257bool OpenSSLKeyPair::operator==(const OpenSSLKeyPair& other) const {
258 return EVP_PKEY_cmp(this->pkey_, other.pkey_) == 1;
259}
260
261bool OpenSSLKeyPair::operator!=(const OpenSSLKeyPair& other) const {
262 return !(*this == other);
263}
264
tfarinaa41ab932015-10-30 16:08:48 -0700265#if !defined(NDEBUG)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000266// Print a certificate to the log, for debugging.
267static void PrintCert(X509* x509) {
268 BIO* temp_memory_bio = BIO_new(BIO_s_mem());
269 if (!temp_memory_bio) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100270 RTC_LOG_F(LS_ERROR) << "Failed to allocate temporary memory bio";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000271 return;
272 }
273 X509_print_ex(temp_memory_bio, x509, XN_FLAG_SEP_CPLUS_SPC, 0);
274 BIO_write(temp_memory_bio, "\0", 1);
275 char* buffer;
276 BIO_get_mem_data(temp_memory_bio, &buffer);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100277 RTC_LOG(LS_VERBOSE) << buffer;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000278 BIO_free(temp_memory_bio);
279}
280#endif
281
282OpenSSLCertificate* OpenSSLCertificate::Generate(
283 OpenSSLKeyPair* key_pair, const SSLIdentityParams& params) {
284 SSLIdentityParams actual_params(params);
285 if (actual_params.common_name.empty()) {
286 // Use a random string, arbitrarily 8chars long.
287 actual_params.common_name = CreateRandomString(8);
288 }
289 X509* x509 = MakeCertificate(key_pair->pkey(), actual_params);
290 if (!x509) {
291 LogSSLErrors("Generating certificate");
deadbeef37f5ecf2017-02-27 14:06:41 -0800292 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000293 }
tfarinaa41ab932015-10-30 16:08:48 -0700294#if !defined(NDEBUG)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000295 PrintCert(x509);
296#endif
297 OpenSSLCertificate* ret = new OpenSSLCertificate(x509);
298 X509_free(x509);
299 return ret;
300}
301
302OpenSSLCertificate* OpenSSLCertificate::FromPEMString(
303 const std::string& pem_string) {
304 BIO* bio = BIO_new_mem_buf(const_cast<char*>(pem_string.c_str()), -1);
305 if (!bio)
deadbeef37f5ecf2017-02-27 14:06:41 -0800306 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000307 BIO_set_mem_eof_return(bio, 0);
deadbeef37f5ecf2017-02-27 14:06:41 -0800308 X509* x509 =
309 PEM_read_bio_X509(bio, nullptr, nullptr, const_cast<char*>("\0"));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000310 BIO_free(bio); // Frees the BIO, but not the pointed-to string.
311
312 if (!x509)
deadbeef37f5ecf2017-02-27 14:06:41 -0800313 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000314
315 OpenSSLCertificate* ret = new OpenSSLCertificate(x509);
316 X509_free(x509);
317 return ret;
318}
319
320// NOTE: This implementation only functions correctly after InitializeSSL
321// and before CleanupSSL.
322bool OpenSSLCertificate::GetSignatureDigestAlgorithm(
323 std::string* algorithm) const {
JiaYang (佳扬) Liu01aeaee2015-04-22 12:18:33 -0700324 int nid = OBJ_obj2nid(x509_->sig_alg->algorithm);
325 switch (nid) {
326 case NID_md5WithRSA:
327 case NID_md5WithRSAEncryption:
328 *algorithm = DIGEST_MD5;
329 break;
330 case NID_ecdsa_with_SHA1:
331 case NID_dsaWithSHA1:
332 case NID_dsaWithSHA1_2:
333 case NID_sha1WithRSA:
334 case NID_sha1WithRSAEncryption:
335 *algorithm = DIGEST_SHA_1;
336 break;
337 case NID_ecdsa_with_SHA224:
338 case NID_sha224WithRSAEncryption:
339 case NID_dsa_with_SHA224:
340 *algorithm = DIGEST_SHA_224;
341 break;
342 case NID_ecdsa_with_SHA256:
343 case NID_sha256WithRSAEncryption:
344 case NID_dsa_with_SHA256:
345 *algorithm = DIGEST_SHA_256;
346 break;
347 case NID_ecdsa_with_SHA384:
348 case NID_sha384WithRSAEncryption:
349 *algorithm = DIGEST_SHA_384;
350 break;
351 case NID_ecdsa_with_SHA512:
352 case NID_sha512WithRSAEncryption:
353 *algorithm = DIGEST_SHA_512;
354 break;
355 default:
356 // Unknown algorithm. There are several unhandled options that are less
357 // common and more complex.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100358 RTC_LOG(LS_ERROR) << "Unknown signature algorithm NID: " << nid;
JiaYang (佳扬) Liu01aeaee2015-04-22 12:18:33 -0700359 algorithm->clear();
360 return false;
361 }
362 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000363}
364
jbauch555604a2016-04-26 03:13:22 -0700365std::unique_ptr<SSLCertChain> OpenSSLCertificate::GetChain() const {
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000366 // Chains are not yet supported when using OpenSSL.
367 // OpenSSLStreamAdapter::SSLVerifyCallback currently requires the remote
368 // certificate to be self-signed.
kwibergf5d47862016-03-15 12:53:24 -0700369 return nullptr;
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000370}
371
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000372bool OpenSSLCertificate::ComputeDigest(const std::string& algorithm,
373 unsigned char* digest,
374 size_t size,
375 size_t* length) const {
376 return ComputeDigest(x509_, algorithm, digest, size, length);
377}
378
379bool OpenSSLCertificate::ComputeDigest(const X509* x509,
380 const std::string& algorithm,
381 unsigned char* digest,
382 size_t size,
383 size_t* length) {
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200384 const EVP_MD* md;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000385 unsigned int n;
386
387 if (!OpenSSLDigest::GetDigestEVP(algorithm, &md))
388 return false;
389
390 if (size < static_cast<size_t>(EVP_MD_size(md)))
391 return false;
392
393 X509_digest(x509, md, digest, &n);
394
395 *length = n;
396
397 return true;
398}
399
400OpenSSLCertificate::~OpenSSLCertificate() {
401 X509_free(x509_);
402}
403
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000404OpenSSLCertificate* OpenSSLCertificate::GetReference() const {
405 return new OpenSSLCertificate(x509_);
406}
407
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000408std::string OpenSSLCertificate::ToPEMString() const {
409 BIO* bio = BIO_new(BIO_s_mem());
410 if (!bio) {
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000411 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000412 }
413 if (!PEM_write_bio_X509(bio, x509_)) {
414 BIO_free(bio);
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000415 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000416 }
417 BIO_write(bio, "\0", 1);
418 char* buffer;
419 BIO_get_mem_data(bio, &buffer);
420 std::string ret(buffer);
421 BIO_free(bio);
422 return ret;
423}
424
425void OpenSSLCertificate::ToDER(Buffer* der_buffer) const {
426 // In case of failure, make sure to leave the buffer empty.
Karl Wiberg94784372015-04-20 14:03:07 +0200427 der_buffer->SetSize(0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000428
429 // Calculates the DER representation of the certificate, from scratch.
430 BIO* bio = BIO_new(BIO_s_mem());
431 if (!bio) {
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000432 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000433 }
434 if (!i2d_X509_bio(bio, x509_)) {
435 BIO_free(bio);
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000436 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000437 }
438 char* data;
439 size_t length = BIO_get_mem_data(bio, &data);
440 der_buffer->SetData(data, length);
441 BIO_free(bio);
442}
443
444void OpenSSLCertificate::AddReference() const {
deadbeef37f5ecf2017-02-27 14:06:41 -0800445 RTC_DCHECK(x509_ != nullptr);
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100446#if defined(OPENSSL_IS_BORINGSSL)
Jiayang Liu770cc382015-05-28 15:36:29 -0700447 X509_up_ref(x509_);
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100448#else
449 CRYPTO_add(&x509_->references, 1, CRYPTO_LOCK_X509);
450#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000451}
452
hbos6b470a92016-04-28 05:14:21 -0700453bool OpenSSLCertificate::operator==(const OpenSSLCertificate& other) const {
454 return X509_cmp(this->x509_, other.x509_) == 0;
455}
456
457bool OpenSSLCertificate::operator!=(const OpenSSLCertificate& other) const {
458 return !(*this == other);
459}
460
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100461// Documented in sslidentity.h.
462int64_t OpenSSLCertificate::CertificateExpirationTime() const {
463 ASN1_TIME* expire_time = X509_get_notAfter(x509_);
464 bool long_format;
465
466 if (expire_time->type == V_ASN1_UTCTIME) {
467 long_format = false;
468 } else if (expire_time->type == V_ASN1_GENERALIZEDTIME) {
469 long_format = true;
470 } else {
471 return -1;
472 }
473
474 return ASN1TimeToSec(expire_time->data, expire_time->length, long_format);
475}
476
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000477OpenSSLIdentity::OpenSSLIdentity(OpenSSLKeyPair* key_pair,
478 OpenSSLCertificate* certificate)
479 : key_pair_(key_pair), certificate_(certificate) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800480 RTC_DCHECK(key_pair != nullptr);
481 RTC_DCHECK(certificate != nullptr);
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000482}
483
484OpenSSLIdentity::~OpenSSLIdentity() = default;
485
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000486OpenSSLIdentity* OpenSSLIdentity::GenerateInternal(
487 const SSLIdentityParams& params) {
torbjorng4e572472015-10-08 09:42:49 -0700488 OpenSSLKeyPair* key_pair = OpenSSLKeyPair::Generate(params.key_params);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000489 if (key_pair) {
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200490 OpenSSLCertificate* certificate =
491 OpenSSLCertificate::Generate(key_pair, params);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000492 if (certificate)
493 return new OpenSSLIdentity(key_pair, certificate);
494 delete key_pair;
495 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100496 RTC_LOG(LS_INFO) << "Identity generation failed";
deadbeef37f5ecf2017-02-27 14:06:41 -0800497 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000498}
499
Torbjorn Granlund1d846b22016-03-31 16:21:04 +0200500OpenSSLIdentity* OpenSSLIdentity::GenerateWithExpiration(
501 const std::string& common_name,
502 const KeyParams& key_params,
503 time_t certificate_lifetime) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000504 SSLIdentityParams params;
torbjorng4e572472015-10-08 09:42:49 -0700505 params.key_params = key_params;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000506 params.common_name = common_name;
deadbeef37f5ecf2017-02-27 14:06:41 -0800507 time_t now = time(nullptr);
Torbjorn Granlund1d846b22016-03-31 16:21:04 +0200508 params.not_before = now + kCertificateWindowInSeconds;
torbjornge8dc0812016-02-15 09:35:54 -0800509 params.not_after = now + certificate_lifetime;
Torbjorn Granlund1d846b22016-03-31 16:21:04 +0200510 if (params.not_before > params.not_after)
511 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000512 return GenerateInternal(params);
513}
514
515OpenSSLIdentity* OpenSSLIdentity::GenerateForTest(
516 const SSLIdentityParams& params) {
517 return GenerateInternal(params);
518}
519
520SSLIdentity* OpenSSLIdentity::FromPEMStrings(
521 const std::string& private_key,
522 const std::string& certificate) {
jbauch555604a2016-04-26 03:13:22 -0700523 std::unique_ptr<OpenSSLCertificate> cert(
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000524 OpenSSLCertificate::FromPEMString(certificate));
525 if (!cert) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100526 RTC_LOG(LS_ERROR) << "Failed to create OpenSSLCertificate from PEM string.";
hbos6b470a92016-04-28 05:14:21 -0700527 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000528 }
529
hbos6b470a92016-04-28 05:14:21 -0700530 OpenSSLKeyPair* key_pair =
531 OpenSSLKeyPair::FromPrivateKeyPEMString(private_key);
532 if (!key_pair) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100533 RTC_LOG(LS_ERROR) << "Failed to create key pair from PEM string.";
hbos6b470a92016-04-28 05:14:21 -0700534 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000535 }
536
hbos6b470a92016-04-28 05:14:21 -0700537 return new OpenSSLIdentity(key_pair,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000538 cert.release());
539}
540
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000541const OpenSSLCertificate& OpenSSLIdentity::certificate() const {
542 return *certificate_;
543}
544
545OpenSSLIdentity* OpenSSLIdentity::GetReference() const {
546 return new OpenSSLIdentity(key_pair_->GetReference(),
547 certificate_->GetReference());
548}
549
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000550bool OpenSSLIdentity::ConfigureIdentity(SSL_CTX* ctx) {
551 // 1 is the documented success return code.
552 if (SSL_CTX_use_certificate(ctx, certificate_->x509()) != 1 ||
553 SSL_CTX_use_PrivateKey(ctx, key_pair_->pkey()) != 1) {
554 LogSSLErrors("Configuring key and certificate");
555 return false;
556 }
557 return true;
558}
559
hbos6b470a92016-04-28 05:14:21 -0700560std::string OpenSSLIdentity::PrivateKeyToPEMString() const {
561 return key_pair_->PrivateKeyToPEMString();
562}
563
564std::string OpenSSLIdentity::PublicKeyToPEMString() const {
565 return key_pair_->PublicKeyToPEMString();
566}
567
568bool OpenSSLIdentity::operator==(const OpenSSLIdentity& other) const {
569 return *this->key_pair_ == *other.key_pair_ &&
570 *this->certificate_ == *other.certificate_;
571}
572
573bool OpenSSLIdentity::operator!=(const OpenSSLIdentity& other) const {
574 return !(*this == other);
575}
576
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000577} // namespace rtc