blob: 85ef176de09097c40e8c900b22f3bd90e9d0b13c [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>
Jian Cui0a8798b2017-11-16 16:58:02 -080019#include <openssl/bn.h>
20#include <openssl/crypto.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000021#include <openssl/err.h>
22#include <openssl/pem.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000023#include <openssl/rsa.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000024
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"
Jian Cui0a8798b2017-11-16 16:58:02 -080030#include "rtc_base/ptr_util.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000031
32namespace rtc {
33
34// We could have exposed a myriad of parameters for the crypto stuff,
35// but keeping it simple seems best.
36
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000037// Random bits for certificate serial number
38static const int SERIAL_RAND_BITS = 64;
39
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000040// Generate a key pair. Caller is responsible for freeing the returned object.
torbjorng4e572472015-10-08 09:42:49 -070041static EVP_PKEY* MakeKey(const KeyParams& key_params) {
Mirko Bonadei675513b2017-11-09 11:09:25 +010042 RTC_LOG(LS_INFO) << "Making key pair";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000043 EVP_PKEY* pkey = EVP_PKEY_new();
torbjorng4e572472015-10-08 09:42:49 -070044 if (key_params.type() == KT_RSA) {
45 int key_length = key_params.rsa_params().mod_size;
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020046 BIGNUM* exponent = BN_new();
47 RSA* rsa = RSA_new();
48 if (!pkey || !exponent || !rsa ||
torbjorng4e572472015-10-08 09:42:49 -070049 !BN_set_word(exponent, key_params.rsa_params().pub_exp) ||
deadbeef37f5ecf2017-02-27 14:06:41 -080050 !RSA_generate_key_ex(rsa, key_length, exponent, nullptr) ||
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020051 !EVP_PKEY_assign_RSA(pkey, rsa)) {
52 EVP_PKEY_free(pkey);
53 BN_free(exponent);
54 RSA_free(rsa);
Mirko Bonadei675513b2017-11-09 11:09:25 +010055 RTC_LOG(LS_ERROR) << "Failed to make RSA key pair";
deadbeef37f5ecf2017-02-27 14:06:41 -080056 return nullptr;
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020057 }
58 // ownership of rsa struct was assigned, don't free it.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000059 BN_free(exponent);
torbjorng4e572472015-10-08 09:42:49 -070060 } else if (key_params.type() == KT_ECDSA) {
61 if (key_params.ec_curve() == EC_NIST_P256) {
62 EC_KEY* ec_key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
ssarohabbfed522016-12-11 18:42:07 -080063
64 // Ensure curve name is included when EC key is serialized.
65 // Without this call, OpenSSL versions before 1.1.0 will create
66 // certificates that don't work for TLS.
67 // This is a no-op for BoringSSL and OpenSSL 1.1.0+
68 EC_KEY_set_asn1_flag(ec_key, OPENSSL_EC_NAMED_CURVE);
69
torbjorng4e572472015-10-08 09:42:49 -070070 if (!pkey || !ec_key || !EC_KEY_generate_key(ec_key) ||
71 !EVP_PKEY_assign_EC_KEY(pkey, ec_key)) {
72 EVP_PKEY_free(pkey);
73 EC_KEY_free(ec_key);
Mirko Bonadei675513b2017-11-09 11:09:25 +010074 RTC_LOG(LS_ERROR) << "Failed to make EC key pair";
deadbeef37f5ecf2017-02-27 14:06:41 -080075 return nullptr;
torbjorng4e572472015-10-08 09:42:49 -070076 }
77 // ownership of ec_key struct was assigned, don't free it.
78 } else {
79 // Add generation of any other curves here.
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020080 EVP_PKEY_free(pkey);
Mirko Bonadei675513b2017-11-09 11:09:25 +010081 RTC_LOG(LS_ERROR) << "ECDSA key requested for unknown curve";
deadbeef37f5ecf2017-02-27 14:06:41 -080082 return nullptr;
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020083 }
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020084 } else {
85 EVP_PKEY_free(pkey);
Mirko Bonadei675513b2017-11-09 11:09:25 +010086 RTC_LOG(LS_ERROR) << "Key type requested not understood";
deadbeef37f5ecf2017-02-27 14:06:41 -080087 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000088 }
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020089
Mirko Bonadei675513b2017-11-09 11:09:25 +010090 RTC_LOG(LS_INFO) << "Returning key pair";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000091 return pkey;
92}
93
94// Generate a self-signed certificate, with the public key from the
95// given key pair. Caller is responsible for freeing the returned object.
96static X509* MakeCertificate(EVP_PKEY* pkey, const SSLIdentityParams& params) {
Mirko Bonadei675513b2017-11-09 11:09:25 +010097 RTC_LOG(LS_INFO) << "Making certificate for " << params.common_name;
deadbeef37f5ecf2017-02-27 14:06:41 -080098 X509* x509 = nullptr;
99 BIGNUM* serial_number = nullptr;
100 X509_NAME* name = nullptr;
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100101 time_t epoch_off = 0; // Time offset since epoch.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000102
deadbeef37f5ecf2017-02-27 14:06:41 -0800103 if ((x509 = X509_new()) == nullptr)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000104 goto error;
105
106 if (!X509_set_pubkey(x509, pkey))
107 goto error;
108
109 // serial number
110 // temporary reference to serial number inside x509 struct
111 ASN1_INTEGER* asn1_serial_number;
deadbeef37f5ecf2017-02-27 14:06:41 -0800112 if ((serial_number = BN_new()) == nullptr ||
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000113 !BN_pseudo_rand(serial_number, SERIAL_RAND_BITS, 0, 0) ||
deadbeef37f5ecf2017-02-27 14:06:41 -0800114 (asn1_serial_number = X509_get_serialNumber(x509)) == nullptr ||
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000115 !BN_to_ASN1_INTEGER(serial_number, asn1_serial_number))
116 goto error;
117
torbjorngf8160352016-03-29 07:57:43 -0700118 if (!X509_set_version(x509, 2L)) // version 3
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000119 goto error;
120
121 // There are a lot of possible components for the name entries. In
122 // our P2P SSL mode however, the certificates are pre-exchanged
123 // (through the secure XMPP channel), and so the certificate
124 // identification is arbitrary. It can't be empty, so we set some
125 // arbitrary common_name. Note that this certificate goes out in
126 // clear during SSL negotiation, so there may be a privacy issue in
127 // putting anything recognizable here.
deadbeef37f5ecf2017-02-27 14:06:41 -0800128 if ((name = X509_NAME_new()) == nullptr ||
129 !X509_NAME_add_entry_by_NID(name, NID_commonName, MBSTRING_UTF8,
130 (unsigned char*)params.common_name.c_str(),
131 -1, -1, 0) ||
132 !X509_set_subject_name(x509, name) || !X509_set_issuer_name(x509, name))
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000133 goto error;
134
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100135 if (!X509_time_adj(X509_get_notBefore(x509), params.not_before, &epoch_off) ||
136 !X509_time_adj(X509_get_notAfter(x509), params.not_after, &epoch_off))
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000137 goto error;
138
Joachim Bauch1b794d52015-05-12 03:32:11 +0200139 if (!X509_sign(x509, pkey, EVP_sha256()))
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000140 goto error;
141
142 BN_free(serial_number);
143 X509_NAME_free(name);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100144 RTC_LOG(LS_INFO) << "Returning certificate";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000145 return x509;
146
Jian Cui0a8798b2017-11-16 16:58:02 -0800147error:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000148 BN_free(serial_number);
149 X509_NAME_free(name);
150 X509_free(x509);
deadbeef37f5ecf2017-02-27 14:06:41 -0800151 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000152}
153
154// This dumps the SSL error stack to the log.
155static void LogSSLErrors(const std::string& prefix) {
156 char error_buf[200];
157 unsigned long err;
158
159 while ((err = ERR_get_error()) != 0) {
160 ERR_error_string_n(err, error_buf, sizeof(error_buf));
Mirko Bonadei675513b2017-11-09 11:09:25 +0100161 RTC_LOG(LS_ERROR) << prefix << ": " << error_buf << "\n";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000162 }
163}
164
torbjorng4e572472015-10-08 09:42:49 -0700165OpenSSLKeyPair* OpenSSLKeyPair::Generate(const KeyParams& key_params) {
166 EVP_PKEY* pkey = MakeKey(key_params);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000167 if (!pkey) {
168 LogSSLErrors("Generating key pair");
deadbeef37f5ecf2017-02-27 14:06:41 -0800169 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000170 }
171 return new OpenSSLKeyPair(pkey);
172}
173
hbos6b470a92016-04-28 05:14:21 -0700174OpenSSLKeyPair* OpenSSLKeyPair::FromPrivateKeyPEMString(
175 const std::string& pem_string) {
176 BIO* bio = BIO_new_mem_buf(const_cast<char*>(pem_string.c_str()), -1);
177 if (!bio) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100178 RTC_LOG(LS_ERROR) << "Failed to create a new BIO buffer.";
hbos6b470a92016-04-28 05:14:21 -0700179 return nullptr;
180 }
181 BIO_set_mem_eof_return(bio, 0);
182 EVP_PKEY* pkey =
183 PEM_read_bio_PrivateKey(bio, nullptr, nullptr, const_cast<char*>("\0"));
184 BIO_free(bio); // Frees the BIO, but not the pointed-to string.
185 if (!pkey) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100186 RTC_LOG(LS_ERROR) << "Failed to create the private key from PEM string.";
hbos6b470a92016-04-28 05:14:21 -0700187 return nullptr;
188 }
189 if (EVP_PKEY_missing_parameters(pkey) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100190 RTC_LOG(LS_ERROR)
191 << "The resulting key pair is missing public key parameters.";
hbos6b470a92016-04-28 05:14:21 -0700192 EVP_PKEY_free(pkey);
193 return nullptr;
194 }
195 return new OpenSSLKeyPair(pkey);
196}
197
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000198OpenSSLKeyPair::~OpenSSLKeyPair() {
199 EVP_PKEY_free(pkey_);
200}
201
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000202OpenSSLKeyPair* OpenSSLKeyPair::GetReference() {
203 AddReference();
204 return new OpenSSLKeyPair(pkey_);
205}
206
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000207void OpenSSLKeyPair::AddReference() {
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100208#if defined(OPENSSL_IS_BORINGSSL)
Jiayang Liu770cc382015-05-28 15:36:29 -0700209 EVP_PKEY_up_ref(pkey_);
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100210#else
211 CRYPTO_add(&pkey_->references, 1, CRYPTO_LOCK_EVP_PKEY);
212#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000213}
214
hbos6b470a92016-04-28 05:14:21 -0700215std::string OpenSSLKeyPair::PrivateKeyToPEMString() const {
216 BIO* temp_memory_bio = BIO_new(BIO_s_mem());
217 if (!temp_memory_bio) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100218 RTC_LOG_F(LS_ERROR) << "Failed to allocate temporary memory bio";
hbos6b470a92016-04-28 05:14:21 -0700219 RTC_NOTREACHED();
220 return "";
221 }
Jian Cui0a8798b2017-11-16 16:58:02 -0800222 if (!PEM_write_bio_PrivateKey(temp_memory_bio, pkey_, nullptr, nullptr, 0,
223 nullptr, nullptr)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100224 RTC_LOG_F(LS_ERROR) << "Failed to write private key";
hbos6b470a92016-04-28 05:14:21 -0700225 BIO_free(temp_memory_bio);
226 RTC_NOTREACHED();
227 return "";
228 }
229 BIO_write(temp_memory_bio, "\0", 1);
230 char* buffer;
231 BIO_get_mem_data(temp_memory_bio, &buffer);
232 std::string priv_key_str = buffer;
233 BIO_free(temp_memory_bio);
234 return priv_key_str;
235}
236
237std::string OpenSSLKeyPair::PublicKeyToPEMString() const {
238 BIO* temp_memory_bio = BIO_new(BIO_s_mem());
239 if (!temp_memory_bio) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100240 RTC_LOG_F(LS_ERROR) << "Failed to allocate temporary memory bio";
hbos6b470a92016-04-28 05:14:21 -0700241 RTC_NOTREACHED();
242 return "";
243 }
244 if (!PEM_write_bio_PUBKEY(temp_memory_bio, pkey_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100245 RTC_LOG_F(LS_ERROR) << "Failed to write public key";
hbos6b470a92016-04-28 05:14:21 -0700246 BIO_free(temp_memory_bio);
247 RTC_NOTREACHED();
248 return "";
249 }
250 BIO_write(temp_memory_bio, "\0", 1);
251 char* buffer;
252 BIO_get_mem_data(temp_memory_bio, &buffer);
253 std::string pub_key_str = buffer;
254 BIO_free(temp_memory_bio);
255 return pub_key_str;
256}
257
258bool OpenSSLKeyPair::operator==(const OpenSSLKeyPair& other) const {
259 return EVP_PKEY_cmp(this->pkey_, other.pkey_) == 1;
260}
261
262bool OpenSSLKeyPair::operator!=(const OpenSSLKeyPair& other) const {
263 return !(*this == other);
264}
265
tfarinaa41ab932015-10-30 16:08:48 -0700266#if !defined(NDEBUG)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000267// Print a certificate to the log, for debugging.
268static void PrintCert(X509* x509) {
269 BIO* temp_memory_bio = BIO_new(BIO_s_mem());
270 if (!temp_memory_bio) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100271 RTC_LOG_F(LS_ERROR) << "Failed to allocate temporary memory bio";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000272 return;
273 }
274 X509_print_ex(temp_memory_bio, x509, XN_FLAG_SEP_CPLUS_SPC, 0);
275 BIO_write(temp_memory_bio, "\0", 1);
276 char* buffer;
277 BIO_get_mem_data(temp_memory_bio, &buffer);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100278 RTC_LOG(LS_VERBOSE) << buffer;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000279 BIO_free(temp_memory_bio);
280}
281#endif
282
Jian Cui0a8798b2017-11-16 16:58:02 -0800283OpenSSLCertificate::OpenSSLCertificate(X509* x509) : x509_(x509) {
284 AddReference();
285}
286
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000287OpenSSLCertificate* OpenSSLCertificate::Generate(
Jian Cui0a8798b2017-11-16 16:58:02 -0800288 OpenSSLKeyPair* key_pair,
289 const SSLIdentityParams& params) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000290 SSLIdentityParams actual_params(params);
291 if (actual_params.common_name.empty()) {
292 // Use a random string, arbitrarily 8chars long.
293 actual_params.common_name = CreateRandomString(8);
294 }
295 X509* x509 = MakeCertificate(key_pair->pkey(), actual_params);
296 if (!x509) {
297 LogSSLErrors("Generating certificate");
deadbeef37f5ecf2017-02-27 14:06:41 -0800298 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000299 }
tfarinaa41ab932015-10-30 16:08:48 -0700300#if !defined(NDEBUG)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000301 PrintCert(x509);
302#endif
303 OpenSSLCertificate* ret = new OpenSSLCertificate(x509);
304 X509_free(x509);
305 return ret;
306}
307
308OpenSSLCertificate* OpenSSLCertificate::FromPEMString(
309 const std::string& pem_string) {
310 BIO* bio = BIO_new_mem_buf(const_cast<char*>(pem_string.c_str()), -1);
311 if (!bio)
deadbeef37f5ecf2017-02-27 14:06:41 -0800312 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000313 BIO_set_mem_eof_return(bio, 0);
deadbeef37f5ecf2017-02-27 14:06:41 -0800314 X509* x509 =
315 PEM_read_bio_X509(bio, nullptr, nullptr, const_cast<char*>("\0"));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000316 BIO_free(bio); // Frees the BIO, but not the pointed-to string.
317
318 if (!x509)
deadbeef37f5ecf2017-02-27 14:06:41 -0800319 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000320
321 OpenSSLCertificate* ret = new OpenSSLCertificate(x509);
322 X509_free(x509);
323 return ret;
324}
325
326// NOTE: This implementation only functions correctly after InitializeSSL
327// and before CleanupSSL.
328bool OpenSSLCertificate::GetSignatureDigestAlgorithm(
329 std::string* algorithm) const {
JiaYang (佳扬) Liu01aeaee2015-04-22 12:18:33 -0700330 int nid = OBJ_obj2nid(x509_->sig_alg->algorithm);
331 switch (nid) {
332 case NID_md5WithRSA:
333 case NID_md5WithRSAEncryption:
334 *algorithm = DIGEST_MD5;
335 break;
336 case NID_ecdsa_with_SHA1:
337 case NID_dsaWithSHA1:
338 case NID_dsaWithSHA1_2:
339 case NID_sha1WithRSA:
340 case NID_sha1WithRSAEncryption:
341 *algorithm = DIGEST_SHA_1;
342 break;
343 case NID_ecdsa_with_SHA224:
344 case NID_sha224WithRSAEncryption:
345 case NID_dsa_with_SHA224:
346 *algorithm = DIGEST_SHA_224;
347 break;
348 case NID_ecdsa_with_SHA256:
349 case NID_sha256WithRSAEncryption:
350 case NID_dsa_with_SHA256:
351 *algorithm = DIGEST_SHA_256;
352 break;
353 case NID_ecdsa_with_SHA384:
354 case NID_sha384WithRSAEncryption:
355 *algorithm = DIGEST_SHA_384;
356 break;
357 case NID_ecdsa_with_SHA512:
358 case NID_sha512WithRSAEncryption:
359 *algorithm = DIGEST_SHA_512;
360 break;
361 default:
362 // Unknown algorithm. There are several unhandled options that are less
363 // common and more complex.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100364 RTC_LOG(LS_ERROR) << "Unknown signature algorithm NID: " << nid;
JiaYang (佳扬) Liu01aeaee2015-04-22 12:18:33 -0700365 algorithm->clear();
366 return false;
367 }
368 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000369}
370
jbauch555604a2016-04-26 03:13:22 -0700371std::unique_ptr<SSLCertChain> OpenSSLCertificate::GetChain() const {
kwibergf5d47862016-03-15 12:53:24 -0700372 return nullptr;
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000373}
374
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000375bool OpenSSLCertificate::ComputeDigest(const std::string& algorithm,
376 unsigned char* digest,
377 size_t size,
378 size_t* length) const {
379 return ComputeDigest(x509_, algorithm, digest, size, length);
380}
381
382bool OpenSSLCertificate::ComputeDigest(const X509* x509,
383 const std::string& algorithm,
384 unsigned char* digest,
385 size_t size,
386 size_t* length) {
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200387 const EVP_MD* md;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000388 unsigned int n;
389
390 if (!OpenSSLDigest::GetDigestEVP(algorithm, &md))
391 return false;
392
393 if (size < static_cast<size_t>(EVP_MD_size(md)))
394 return false;
395
396 X509_digest(x509, md, digest, &n);
397
398 *length = n;
399
400 return true;
401}
402
403OpenSSLCertificate::~OpenSSLCertificate() {
404 X509_free(x509_);
405}
406
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000407OpenSSLCertificate* OpenSSLCertificate::GetReference() const {
408 return new OpenSSLCertificate(x509_);
409}
410
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000411std::string OpenSSLCertificate::ToPEMString() const {
412 BIO* bio = BIO_new(BIO_s_mem());
413 if (!bio) {
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000414 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000415 }
416 if (!PEM_write_bio_X509(bio, x509_)) {
417 BIO_free(bio);
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000418 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000419 }
420 BIO_write(bio, "\0", 1);
421 char* buffer;
422 BIO_get_mem_data(bio, &buffer);
423 std::string ret(buffer);
424 BIO_free(bio);
425 return ret;
426}
427
428void OpenSSLCertificate::ToDER(Buffer* der_buffer) const {
429 // In case of failure, make sure to leave the buffer empty.
Karl Wiberg94784372015-04-20 14:03:07 +0200430 der_buffer->SetSize(0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000431
432 // Calculates the DER representation of the certificate, from scratch.
433 BIO* bio = BIO_new(BIO_s_mem());
434 if (!bio) {
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000435 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000436 }
437 if (!i2d_X509_bio(bio, x509_)) {
438 BIO_free(bio);
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000439 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000440 }
441 char* data;
442 size_t length = BIO_get_mem_data(bio, &data);
443 der_buffer->SetData(data, length);
444 BIO_free(bio);
445}
446
447void OpenSSLCertificate::AddReference() const {
deadbeef37f5ecf2017-02-27 14:06:41 -0800448 RTC_DCHECK(x509_ != nullptr);
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100449#if defined(OPENSSL_IS_BORINGSSL)
Jiayang Liu770cc382015-05-28 15:36:29 -0700450 X509_up_ref(x509_);
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100451#else
452 CRYPTO_add(&x509_->references, 1, CRYPTO_LOCK_X509);
453#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000454}
455
hbos6b470a92016-04-28 05:14:21 -0700456bool OpenSSLCertificate::operator==(const OpenSSLCertificate& other) const {
Jian Cui0a8798b2017-11-16 16:58:02 -0800457 return X509_cmp(x509_, other.x509_) == 0;
hbos6b470a92016-04-28 05:14:21 -0700458}
459
460bool OpenSSLCertificate::operator!=(const OpenSSLCertificate& other) const {
461 return !(*this == other);
462}
463
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100464// Documented in sslidentity.h.
465int64_t OpenSSLCertificate::CertificateExpirationTime() const {
466 ASN1_TIME* expire_time = X509_get_notAfter(x509_);
467 bool long_format;
468
469 if (expire_time->type == V_ASN1_UTCTIME) {
470 long_format = false;
471 } else if (expire_time->type == V_ASN1_GENERALIZEDTIME) {
472 long_format = true;
473 } else {
474 return -1;
475 }
476
477 return ASN1TimeToSec(expire_time->data, expire_time->length, long_format);
478}
479
Jian Cui0a8798b2017-11-16 16:58:02 -0800480OpenSSLIdentity::OpenSSLIdentity(
481 std::unique_ptr<OpenSSLKeyPair> key_pair,
482 std::unique_ptr<OpenSSLCertificate> certificate)
483 : key_pair_(std::move(key_pair)) {
484 RTC_DCHECK(key_pair_ != nullptr);
deadbeef37f5ecf2017-02-27 14:06:41 -0800485 RTC_DCHECK(certificate != nullptr);
Jian Cui0a8798b2017-11-16 16:58:02 -0800486 std::vector<std::unique_ptr<SSLCertificate>> certs;
487 certs.push_back(std::move(certificate));
488 cert_chain_.reset(new SSLCertChain(std::move(certs)));
489}
490
491OpenSSLIdentity::OpenSSLIdentity(std::unique_ptr<OpenSSLKeyPair> key_pair,
492 std::unique_ptr<SSLCertChain> cert_chain)
493 : key_pair_(std::move(key_pair)), cert_chain_(std::move(cert_chain)) {
494 RTC_DCHECK(key_pair_ != nullptr);
495 RTC_DCHECK(cert_chain_ != nullptr);
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000496}
497
498OpenSSLIdentity::~OpenSSLIdentity() = default;
499
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000500OpenSSLIdentity* OpenSSLIdentity::GenerateInternal(
501 const SSLIdentityParams& params) {
Jian Cui0a8798b2017-11-16 16:58:02 -0800502 std::unique_ptr<OpenSSLKeyPair> key_pair(
503 OpenSSLKeyPair::Generate(params.key_params));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000504 if (key_pair) {
Jian Cui0a8798b2017-11-16 16:58:02 -0800505 std::unique_ptr<OpenSSLCertificate> certificate(
506 OpenSSLCertificate::Generate(key_pair.get(), params));
507 if (certificate != nullptr)
508 return new OpenSSLIdentity(std::move(key_pair), std::move(certificate));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000509 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100510 RTC_LOG(LS_INFO) << "Identity generation failed";
deadbeef37f5ecf2017-02-27 14:06:41 -0800511 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000512}
513
Torbjorn Granlund1d846b22016-03-31 16:21:04 +0200514OpenSSLIdentity* OpenSSLIdentity::GenerateWithExpiration(
515 const std::string& common_name,
516 const KeyParams& key_params,
517 time_t certificate_lifetime) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000518 SSLIdentityParams params;
torbjorng4e572472015-10-08 09:42:49 -0700519 params.key_params = key_params;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000520 params.common_name = common_name;
deadbeef37f5ecf2017-02-27 14:06:41 -0800521 time_t now = time(nullptr);
Torbjorn Granlund1d846b22016-03-31 16:21:04 +0200522 params.not_before = now + kCertificateWindowInSeconds;
torbjornge8dc0812016-02-15 09:35:54 -0800523 params.not_after = now + certificate_lifetime;
Torbjorn Granlund1d846b22016-03-31 16:21:04 +0200524 if (params.not_before > params.not_after)
525 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000526 return GenerateInternal(params);
527}
528
529OpenSSLIdentity* OpenSSLIdentity::GenerateForTest(
530 const SSLIdentityParams& params) {
531 return GenerateInternal(params);
532}
533
Jian Cui0a8798b2017-11-16 16:58:02 -0800534SSLIdentity* OpenSSLIdentity::FromPEMStrings(const std::string& private_key,
535 const std::string& certificate) {
jbauch555604a2016-04-26 03:13:22 -0700536 std::unique_ptr<OpenSSLCertificate> cert(
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000537 OpenSSLCertificate::FromPEMString(certificate));
538 if (!cert) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100539 RTC_LOG(LS_ERROR) << "Failed to create OpenSSLCertificate from PEM string.";
hbos6b470a92016-04-28 05:14:21 -0700540 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000541 }
542
Jian Cui0a8798b2017-11-16 16:58:02 -0800543 std::unique_ptr<OpenSSLKeyPair> key_pair(
544 OpenSSLKeyPair::FromPrivateKeyPEMString(private_key));
hbos6b470a92016-04-28 05:14:21 -0700545 if (!key_pair) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100546 RTC_LOG(LS_ERROR) << "Failed to create key pair from PEM string.";
hbos6b470a92016-04-28 05:14:21 -0700547 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000548 }
549
Jian Cui0a8798b2017-11-16 16:58:02 -0800550 return new OpenSSLIdentity(std::move(key_pair), std::move(cert));
551}
552
553SSLIdentity* OpenSSLIdentity::FromPEMChainStrings(
554 const std::string& private_key,
555 const std::string& certificate_chain) {
556 BIO* bio =
557 BIO_new_mem_buf(certificate_chain.data(), certificate_chain.size());
558 if (!bio)
559 return nullptr;
560 BIO_set_mem_eof_return(bio, 0);
561 std::vector<std::unique_ptr<SSLCertificate>> certs;
562 while (true) {
563 X509* x509 =
564 PEM_read_bio_X509(bio, nullptr, nullptr, const_cast<char*>("\0"));
565 if (x509 == nullptr) {
566 uint32_t err = ERR_peek_error();
567 if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
568 ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
569 break;
570 }
571 RTC_LOG(LS_ERROR) << "Failed to parse certificate from PEM string.";
572 BIO_free(bio);
573 return nullptr;
574 }
575 certs.emplace_back(new OpenSSLCertificate(x509));
576 X509_free(x509);
577 }
578 BIO_free(bio);
579 if (certs.empty()) {
580 RTC_LOG(LS_ERROR) << "Found no certificates in PEM string.";
581 return nullptr;
582 }
583
584 std::unique_ptr<OpenSSLKeyPair> key_pair(
585 OpenSSLKeyPair::FromPrivateKeyPEMString(private_key));
586 if (!key_pair) {
587 RTC_LOG(LS_ERROR) << "Failed to create key pair from PEM string.";
588 return nullptr;
589 }
590
591 return new OpenSSLIdentity(std::move(key_pair),
592 MakeUnique<SSLCertChain>(std::move(certs)));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000593}
594
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000595const OpenSSLCertificate& OpenSSLIdentity::certificate() const {
Jian Cui0a8798b2017-11-16 16:58:02 -0800596 return *static_cast<const OpenSSLCertificate*>(&cert_chain_->Get(0));
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000597}
598
599OpenSSLIdentity* OpenSSLIdentity::GetReference() const {
Jian Cui0a8798b2017-11-16 16:58:02 -0800600 return new OpenSSLIdentity(WrapUnique(key_pair_->GetReference()),
601 WrapUnique(certificate().GetReference()));
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000602}
603
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000604bool OpenSSLIdentity::ConfigureIdentity(SSL_CTX* ctx) {
605 // 1 is the documented success return code.
Jian Cui0a8798b2017-11-16 16:58:02 -0800606 const OpenSSLCertificate* cert = &certificate();
607 if (SSL_CTX_use_certificate(ctx, cert->x509()) != 1 ||
608 SSL_CTX_use_PrivateKey(ctx, key_pair_->pkey()) != 1) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000609 LogSSLErrors("Configuring key and certificate");
610 return false;
611 }
Jian Cui0a8798b2017-11-16 16:58:02 -0800612 // If a chain is available, use it.
613 for (size_t i = 1; i < cert_chain_->GetSize(); ++i) {
614 cert = static_cast<const OpenSSLCertificate*>(&cert_chain_->Get(i));
615 if (SSL_CTX_add1_chain_cert(ctx, cert->x509()) != 1) {
616 LogSSLErrors("Configuring intermediate certificate");
617 return false;
618 }
619 }
620
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000621 return true;
622}
623
hbos6b470a92016-04-28 05:14:21 -0700624std::string OpenSSLIdentity::PrivateKeyToPEMString() const {
625 return key_pair_->PrivateKeyToPEMString();
626}
627
628std::string OpenSSLIdentity::PublicKeyToPEMString() const {
629 return key_pair_->PublicKeyToPEMString();
630}
631
632bool OpenSSLIdentity::operator==(const OpenSSLIdentity& other) const {
633 return *this->key_pair_ == *other.key_pair_ &&
Jian Cui0a8798b2017-11-16 16:58:02 -0800634 this->certificate() == other.certificate();
hbos6b470a92016-04-28 05:14:21 -0700635}
636
637bool OpenSSLIdentity::operator!=(const OpenSSLIdentity& other) const {
638 return !(*this == other);
639}
640
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000641} // namespace rtc