blob: 24b97b136e84a5f80d908fd14c6f8111d58cfa99 [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#if HAVE_OPENSSL_SSL_H
12
13#include "webrtc/base/opensslidentity.h"
14
15// Must be included first before openssl headers.
16#include "webrtc/base/win32.h" // NOLINT
17
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
25#include "webrtc/base/checks.h"
26#include "webrtc/base/helpers.h"
27#include "webrtc/base/logging.h"
28#include "webrtc/base/openssl.h"
29#include "webrtc/base/openssldigest.h"
30
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) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000041 LOG(LS_INFO) << "Making key pair";
42 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) ||
49 !RSA_generate_key_ex(rsa, key_length, exponent, NULL) ||
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);
54 LOG(LS_ERROR) << "Failed to make RSA key pair";
55 return NULL;
56 }
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);
62 if (!pkey || !ec_key || !EC_KEY_generate_key(ec_key) ||
63 !EVP_PKEY_assign_EC_KEY(pkey, ec_key)) {
64 EVP_PKEY_free(pkey);
65 EC_KEY_free(ec_key);
66 LOG(LS_ERROR) << "Failed to make EC key pair";
67 return NULL;
68 }
69 // ownership of ec_key struct was assigned, don't free it.
70 } else {
71 // Add generation of any other curves here.
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020072 EVP_PKEY_free(pkey);
torbjorng4e572472015-10-08 09:42:49 -070073 LOG(LS_ERROR) << "ECDSA key requested for unknown curve";
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020074 return NULL;
75 }
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020076 } else {
77 EVP_PKEY_free(pkey);
78 LOG(LS_ERROR) << "Key type requested not understood";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000079 return NULL;
80 }
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020081
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000082 LOG(LS_INFO) << "Returning key pair";
83 return pkey;
84}
85
86// Generate a self-signed certificate, with the public key from the
87// given key pair. Caller is responsible for freeing the returned object.
88static X509* MakeCertificate(EVP_PKEY* pkey, const SSLIdentityParams& params) {
89 LOG(LS_INFO) << "Making certificate for " << params.common_name;
90 X509* x509 = NULL;
91 BIGNUM* serial_number = NULL;
92 X509_NAME* name = NULL;
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +010093 time_t epoch_off = 0; // Time offset since epoch.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000094
95 if ((x509=X509_new()) == NULL)
96 goto error;
97
98 if (!X509_set_pubkey(x509, pkey))
99 goto error;
100
101 // serial number
102 // temporary reference to serial number inside x509 struct
103 ASN1_INTEGER* asn1_serial_number;
104 if ((serial_number = BN_new()) == NULL ||
105 !BN_pseudo_rand(serial_number, SERIAL_RAND_BITS, 0, 0) ||
106 (asn1_serial_number = X509_get_serialNumber(x509)) == NULL ||
107 !BN_to_ASN1_INTEGER(serial_number, asn1_serial_number))
108 goto error;
109
torbjorngf8160352016-03-29 07:57:43 -0700110 if (!X509_set_version(x509, 2L)) // version 3
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000111 goto error;
112
113 // There are a lot of possible components for the name entries. In
114 // our P2P SSL mode however, the certificates are pre-exchanged
115 // (through the secure XMPP channel), and so the certificate
116 // identification is arbitrary. It can't be empty, so we set some
117 // arbitrary common_name. Note that this certificate goes out in
118 // clear during SSL negotiation, so there may be a privacy issue in
119 // putting anything recognizable here.
120 if ((name = X509_NAME_new()) == NULL ||
121 !X509_NAME_add_entry_by_NID(
122 name, NID_commonName, MBSTRING_UTF8,
123 (unsigned char*)params.common_name.c_str(), -1, -1, 0) ||
124 !X509_set_subject_name(x509, name) ||
125 !X509_set_issuer_name(x509, name))
126 goto error;
127
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100128 if (!X509_time_adj(X509_get_notBefore(x509), params.not_before, &epoch_off) ||
129 !X509_time_adj(X509_get_notAfter(x509), params.not_after, &epoch_off))
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000130 goto error;
131
Joachim Bauch1b794d52015-05-12 03:32:11 +0200132 if (!X509_sign(x509, pkey, EVP_sha256()))
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000133 goto error;
134
135 BN_free(serial_number);
136 X509_NAME_free(name);
137 LOG(LS_INFO) << "Returning certificate";
138 return x509;
139
140 error:
141 BN_free(serial_number);
142 X509_NAME_free(name);
143 X509_free(x509);
144 return NULL;
145}
146
147// This dumps the SSL error stack to the log.
148static void LogSSLErrors(const std::string& prefix) {
149 char error_buf[200];
150 unsigned long err;
151
152 while ((err = ERR_get_error()) != 0) {
153 ERR_error_string_n(err, error_buf, sizeof(error_buf));
154 LOG(LS_ERROR) << prefix << ": " << error_buf << "\n";
155 }
156}
157
torbjorng4e572472015-10-08 09:42:49 -0700158OpenSSLKeyPair* OpenSSLKeyPair::Generate(const KeyParams& key_params) {
159 EVP_PKEY* pkey = MakeKey(key_params);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000160 if (!pkey) {
161 LogSSLErrors("Generating key pair");
162 return NULL;
163 }
164 return new OpenSSLKeyPair(pkey);
165}
166
167OpenSSLKeyPair::~OpenSSLKeyPair() {
168 EVP_PKEY_free(pkey_);
169}
170
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000171OpenSSLKeyPair* OpenSSLKeyPair::GetReference() {
172 AddReference();
173 return new OpenSSLKeyPair(pkey_);
174}
175
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000176void OpenSSLKeyPair::AddReference() {
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100177#if defined(OPENSSL_IS_BORINGSSL)
Jiayang Liu770cc382015-05-28 15:36:29 -0700178 EVP_PKEY_up_ref(pkey_);
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100179#else
180 CRYPTO_add(&pkey_->references, 1, CRYPTO_LOCK_EVP_PKEY);
181#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000182}
183
tfarinaa41ab932015-10-30 16:08:48 -0700184#if !defined(NDEBUG)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000185// Print a certificate to the log, for debugging.
186static void PrintCert(X509* x509) {
187 BIO* temp_memory_bio = BIO_new(BIO_s_mem());
188 if (!temp_memory_bio) {
189 LOG_F(LS_ERROR) << "Failed to allocate temporary memory bio";
190 return;
191 }
192 X509_print_ex(temp_memory_bio, x509, XN_FLAG_SEP_CPLUS_SPC, 0);
193 BIO_write(temp_memory_bio, "\0", 1);
194 char* buffer;
195 BIO_get_mem_data(temp_memory_bio, &buffer);
196 LOG(LS_VERBOSE) << buffer;
197 BIO_free(temp_memory_bio);
198}
199#endif
200
201OpenSSLCertificate* OpenSSLCertificate::Generate(
202 OpenSSLKeyPair* key_pair, const SSLIdentityParams& params) {
203 SSLIdentityParams actual_params(params);
204 if (actual_params.common_name.empty()) {
205 // Use a random string, arbitrarily 8chars long.
206 actual_params.common_name = CreateRandomString(8);
207 }
208 X509* x509 = MakeCertificate(key_pair->pkey(), actual_params);
209 if (!x509) {
210 LogSSLErrors("Generating certificate");
211 return NULL;
212 }
tfarinaa41ab932015-10-30 16:08:48 -0700213#if !defined(NDEBUG)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000214 PrintCert(x509);
215#endif
216 OpenSSLCertificate* ret = new OpenSSLCertificate(x509);
217 X509_free(x509);
218 return ret;
219}
220
221OpenSSLCertificate* OpenSSLCertificate::FromPEMString(
222 const std::string& pem_string) {
223 BIO* bio = BIO_new_mem_buf(const_cast<char*>(pem_string.c_str()), -1);
224 if (!bio)
225 return NULL;
226 BIO_set_mem_eof_return(bio, 0);
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200227 X509* x509 = PEM_read_bio_X509(bio, NULL, NULL, const_cast<char*>("\0"));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000228 BIO_free(bio); // Frees the BIO, but not the pointed-to string.
229
230 if (!x509)
231 return NULL;
232
233 OpenSSLCertificate* ret = new OpenSSLCertificate(x509);
234 X509_free(x509);
235 return ret;
236}
237
238// NOTE: This implementation only functions correctly after InitializeSSL
239// and before CleanupSSL.
240bool OpenSSLCertificate::GetSignatureDigestAlgorithm(
241 std::string* algorithm) const {
JiaYang (佳扬) Liu01aeaee2015-04-22 12:18:33 -0700242 int nid = OBJ_obj2nid(x509_->sig_alg->algorithm);
243 switch (nid) {
244 case NID_md5WithRSA:
245 case NID_md5WithRSAEncryption:
246 *algorithm = DIGEST_MD5;
247 break;
248 case NID_ecdsa_with_SHA1:
249 case NID_dsaWithSHA1:
250 case NID_dsaWithSHA1_2:
251 case NID_sha1WithRSA:
252 case NID_sha1WithRSAEncryption:
253 *algorithm = DIGEST_SHA_1;
254 break;
255 case NID_ecdsa_with_SHA224:
256 case NID_sha224WithRSAEncryption:
257 case NID_dsa_with_SHA224:
258 *algorithm = DIGEST_SHA_224;
259 break;
260 case NID_ecdsa_with_SHA256:
261 case NID_sha256WithRSAEncryption:
262 case NID_dsa_with_SHA256:
263 *algorithm = DIGEST_SHA_256;
264 break;
265 case NID_ecdsa_with_SHA384:
266 case NID_sha384WithRSAEncryption:
267 *algorithm = DIGEST_SHA_384;
268 break;
269 case NID_ecdsa_with_SHA512:
270 case NID_sha512WithRSAEncryption:
271 *algorithm = DIGEST_SHA_512;
272 break;
273 default:
274 // Unknown algorithm. There are several unhandled options that are less
275 // common and more complex.
276 LOG(LS_ERROR) << "Unknown signature algorithm NID: " << nid;
277 algorithm->clear();
278 return false;
279 }
280 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000281}
282
kwibergf5d47862016-03-15 12:53:24 -0700283rtc::scoped_ptr<SSLCertChain> OpenSSLCertificate::GetChain() const {
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000284 // Chains are not yet supported when using OpenSSL.
285 // OpenSSLStreamAdapter::SSLVerifyCallback currently requires the remote
286 // certificate to be self-signed.
kwibergf5d47862016-03-15 12:53:24 -0700287 return nullptr;
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000288}
289
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000290bool OpenSSLCertificate::ComputeDigest(const std::string& algorithm,
291 unsigned char* digest,
292 size_t size,
293 size_t* length) const {
294 return ComputeDigest(x509_, algorithm, digest, size, length);
295}
296
297bool OpenSSLCertificate::ComputeDigest(const X509* x509,
298 const std::string& algorithm,
299 unsigned char* digest,
300 size_t size,
301 size_t* length) {
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200302 const EVP_MD* md;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000303 unsigned int n;
304
305 if (!OpenSSLDigest::GetDigestEVP(algorithm, &md))
306 return false;
307
308 if (size < static_cast<size_t>(EVP_MD_size(md)))
309 return false;
310
311 X509_digest(x509, md, digest, &n);
312
313 *length = n;
314
315 return true;
316}
317
318OpenSSLCertificate::~OpenSSLCertificate() {
319 X509_free(x509_);
320}
321
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000322OpenSSLCertificate* OpenSSLCertificate::GetReference() const {
323 return new OpenSSLCertificate(x509_);
324}
325
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000326std::string OpenSSLCertificate::ToPEMString() const {
327 BIO* bio = BIO_new(BIO_s_mem());
328 if (!bio) {
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000329 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000330 }
331 if (!PEM_write_bio_X509(bio, x509_)) {
332 BIO_free(bio);
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000333 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000334 }
335 BIO_write(bio, "\0", 1);
336 char* buffer;
337 BIO_get_mem_data(bio, &buffer);
338 std::string ret(buffer);
339 BIO_free(bio);
340 return ret;
341}
342
343void OpenSSLCertificate::ToDER(Buffer* der_buffer) const {
344 // In case of failure, make sure to leave the buffer empty.
Karl Wiberg94784372015-04-20 14:03:07 +0200345 der_buffer->SetSize(0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000346
347 // Calculates the DER representation of the certificate, from scratch.
348 BIO* bio = BIO_new(BIO_s_mem());
349 if (!bio) {
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000350 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000351 }
352 if (!i2d_X509_bio(bio, x509_)) {
353 BIO_free(bio);
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000354 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000355 }
356 char* data;
357 size_t length = BIO_get_mem_data(bio, &data);
358 der_buffer->SetData(data, length);
359 BIO_free(bio);
360}
361
362void OpenSSLCertificate::AddReference() const {
363 ASSERT(x509_ != NULL);
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100364#if defined(OPENSSL_IS_BORINGSSL)
Jiayang Liu770cc382015-05-28 15:36:29 -0700365 X509_up_ref(x509_);
Torbjorn Granlund9adc91d2016-03-24 14:05:06 +0100366#else
367 CRYPTO_add(&x509_->references, 1, CRYPTO_LOCK_X509);
368#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000369}
370
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100371// Documented in sslidentity.h.
372int64_t OpenSSLCertificate::CertificateExpirationTime() const {
373 ASN1_TIME* expire_time = X509_get_notAfter(x509_);
374 bool long_format;
375
376 if (expire_time->type == V_ASN1_UTCTIME) {
377 long_format = false;
378 } else if (expire_time->type == V_ASN1_GENERALIZEDTIME) {
379 long_format = true;
380 } else {
381 return -1;
382 }
383
384 return ASN1TimeToSec(expire_time->data, expire_time->length, long_format);
385}
386
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000387OpenSSLIdentity::OpenSSLIdentity(OpenSSLKeyPair* key_pair,
388 OpenSSLCertificate* certificate)
389 : key_pair_(key_pair), certificate_(certificate) {
390 ASSERT(key_pair != NULL);
391 ASSERT(certificate != NULL);
392}
393
394OpenSSLIdentity::~OpenSSLIdentity() = default;
395
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000396OpenSSLIdentity* OpenSSLIdentity::GenerateInternal(
397 const SSLIdentityParams& params) {
torbjorng4e572472015-10-08 09:42:49 -0700398 OpenSSLKeyPair* key_pair = OpenSSLKeyPair::Generate(params.key_params);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000399 if (key_pair) {
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200400 OpenSSLCertificate* certificate =
401 OpenSSLCertificate::Generate(key_pair, params);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000402 if (certificate)
403 return new OpenSSLIdentity(key_pair, certificate);
404 delete key_pair;
405 }
406 LOG(LS_INFO) << "Identity generation failed";
407 return NULL;
408}
409
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200410OpenSSLIdentity* OpenSSLIdentity::Generate(const std::string& common_name,
torbjornge8dc0812016-02-15 09:35:54 -0800411 const KeyParams& key_params,
412 time_t certificate_lifetime) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000413 SSLIdentityParams params;
torbjorng4e572472015-10-08 09:42:49 -0700414 params.key_params = key_params;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000415 params.common_name = common_name;
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100416 time_t now = time(NULL);
torbjornge8dc0812016-02-15 09:35:54 -0800417 params.not_before = now + kCertificateWindow;
418 params.not_after = now + certificate_lifetime;
419 RTC_DCHECK(params.not_before < params.not_after);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000420 return GenerateInternal(params);
421}
422
423OpenSSLIdentity* OpenSSLIdentity::GenerateForTest(
424 const SSLIdentityParams& params) {
425 return GenerateInternal(params);
426}
427
428SSLIdentity* OpenSSLIdentity::FromPEMStrings(
429 const std::string& private_key,
430 const std::string& certificate) {
431 scoped_ptr<OpenSSLCertificate> cert(
432 OpenSSLCertificate::FromPEMString(certificate));
433 if (!cert) {
434 LOG(LS_ERROR) << "Failed to create OpenSSLCertificate from PEM string.";
435 return NULL;
436 }
437
438 BIO* bio = BIO_new_mem_buf(const_cast<char*>(private_key.c_str()), -1);
439 if (!bio) {
440 LOG(LS_ERROR) << "Failed to create a new BIO buffer.";
441 return NULL;
442 }
443 BIO_set_mem_eof_return(bio, 0);
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200444 EVP_PKEY* pkey =
445 PEM_read_bio_PrivateKey(bio, NULL, NULL, const_cast<char*>("\0"));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000446 BIO_free(bio); // Frees the BIO, but not the pointed-to string.
447
448 if (!pkey) {
449 LOG(LS_ERROR) << "Failed to create the private key from PEM string.";
450 return NULL;
451 }
452
453 return new OpenSSLIdentity(new OpenSSLKeyPair(pkey),
454 cert.release());
455}
456
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000457const OpenSSLCertificate& OpenSSLIdentity::certificate() const {
458 return *certificate_;
459}
460
461OpenSSLIdentity* OpenSSLIdentity::GetReference() const {
462 return new OpenSSLIdentity(key_pair_->GetReference(),
463 certificate_->GetReference());
464}
465
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000466bool OpenSSLIdentity::ConfigureIdentity(SSL_CTX* ctx) {
467 // 1 is the documented success return code.
468 if (SSL_CTX_use_certificate(ctx, certificate_->x509()) != 1 ||
469 SSL_CTX_use_PrivateKey(ctx, key_pair_->pkey()) != 1) {
470 LogSSLErrors("Configuring key and certificate");
471 return false;
472 }
473 return true;
474}
475
476} // namespace rtc
477
478#endif // HAVE_OPENSSL_SSL_H