blob: feda6744f07df80e3a09a6bf9a37a24cd2c1c98a [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
39// Certificate validity lifetime
40static const int CERTIFICATE_LIFETIME = 60*60*24*30; // 30 days, arbitrarily
41// Certificate validity window.
42// This is to compensate for slightly incorrect system clocks.
43static const int CERTIFICATE_WINDOW = -60*60*24;
44
45// Generate a key pair. Caller is responsible for freeing the returned object.
torbjorng4e572472015-10-08 09:42:49 -070046static EVP_PKEY* MakeKey(const KeyParams& key_params) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000047 LOG(LS_INFO) << "Making key pair";
48 EVP_PKEY* pkey = EVP_PKEY_new();
torbjorng4e572472015-10-08 09:42:49 -070049 if (key_params.type() == KT_RSA) {
50 int key_length = key_params.rsa_params().mod_size;
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020051 BIGNUM* exponent = BN_new();
52 RSA* rsa = RSA_new();
53 if (!pkey || !exponent || !rsa ||
torbjorng4e572472015-10-08 09:42:49 -070054 !BN_set_word(exponent, key_params.rsa_params().pub_exp) ||
55 !RSA_generate_key_ex(rsa, key_length, exponent, NULL) ||
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020056 !EVP_PKEY_assign_RSA(pkey, rsa)) {
57 EVP_PKEY_free(pkey);
58 BN_free(exponent);
59 RSA_free(rsa);
60 LOG(LS_ERROR) << "Failed to make RSA key pair";
61 return NULL;
62 }
63 // ownership of rsa struct was assigned, don't free it.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000064 BN_free(exponent);
torbjorng4e572472015-10-08 09:42:49 -070065 } else if (key_params.type() == KT_ECDSA) {
66 if (key_params.ec_curve() == EC_NIST_P256) {
67 EC_KEY* ec_key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
68 if (!pkey || !ec_key || !EC_KEY_generate_key(ec_key) ||
69 !EVP_PKEY_assign_EC_KEY(pkey, ec_key)) {
70 EVP_PKEY_free(pkey);
71 EC_KEY_free(ec_key);
72 LOG(LS_ERROR) << "Failed to make EC key pair";
73 return NULL;
74 }
75 // ownership of ec_key struct was assigned, don't free it.
76 } else {
77 // Add generation of any other curves here.
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020078 EVP_PKEY_free(pkey);
torbjorng4e572472015-10-08 09:42:49 -070079 LOG(LS_ERROR) << "ECDSA key requested for unknown curve";
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020080 return NULL;
81 }
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020082 } else {
83 EVP_PKEY_free(pkey);
84 LOG(LS_ERROR) << "Key type requested not understood";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000085 return NULL;
86 }
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020087
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000088 LOG(LS_INFO) << "Returning key pair";
89 return pkey;
90}
91
92// Generate a self-signed certificate, with the public key from the
93// given key pair. Caller is responsible for freeing the returned object.
94static X509* MakeCertificate(EVP_PKEY* pkey, const SSLIdentityParams& params) {
95 LOG(LS_INFO) << "Making certificate for " << params.common_name;
96 X509* x509 = NULL;
97 BIGNUM* serial_number = NULL;
98 X509_NAME* name = NULL;
99
100 if ((x509=X509_new()) == NULL)
101 goto error;
102
103 if (!X509_set_pubkey(x509, pkey))
104 goto error;
105
106 // serial number
107 // temporary reference to serial number inside x509 struct
108 ASN1_INTEGER* asn1_serial_number;
109 if ((serial_number = BN_new()) == NULL ||
110 !BN_pseudo_rand(serial_number, SERIAL_RAND_BITS, 0, 0) ||
111 (asn1_serial_number = X509_get_serialNumber(x509)) == NULL ||
112 !BN_to_ASN1_INTEGER(serial_number, asn1_serial_number))
113 goto error;
114
115 if (!X509_set_version(x509, 0L)) // version 1
116 goto error;
117
118 // There are a lot of possible components for the name entries. In
119 // our P2P SSL mode however, the certificates are pre-exchanged
120 // (through the secure XMPP channel), and so the certificate
121 // identification is arbitrary. It can't be empty, so we set some
122 // arbitrary common_name. Note that this certificate goes out in
123 // clear during SSL negotiation, so there may be a privacy issue in
124 // putting anything recognizable here.
125 if ((name = X509_NAME_new()) == NULL ||
126 !X509_NAME_add_entry_by_NID(
127 name, NID_commonName, MBSTRING_UTF8,
128 (unsigned char*)params.common_name.c_str(), -1, -1, 0) ||
129 !X509_set_subject_name(x509, name) ||
130 !X509_set_issuer_name(x509, name))
131 goto error;
132
133 if (!X509_gmtime_adj(X509_get_notBefore(x509), params.not_before) ||
134 !X509_gmtime_adj(X509_get_notAfter(x509), params.not_after))
135 goto error;
136
Joachim Bauch1b794d52015-05-12 03:32:11 +0200137 if (!X509_sign(x509, pkey, EVP_sha256()))
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000138 goto error;
139
140 BN_free(serial_number);
141 X509_NAME_free(name);
142 LOG(LS_INFO) << "Returning certificate";
143 return x509;
144
145 error:
146 BN_free(serial_number);
147 X509_NAME_free(name);
148 X509_free(x509);
149 return NULL;
150}
151
152// This dumps the SSL error stack to the log.
153static void LogSSLErrors(const std::string& prefix) {
154 char error_buf[200];
155 unsigned long err;
156
157 while ((err = ERR_get_error()) != 0) {
158 ERR_error_string_n(err, error_buf, sizeof(error_buf));
159 LOG(LS_ERROR) << prefix << ": " << error_buf << "\n";
160 }
161}
162
torbjorng4e572472015-10-08 09:42:49 -0700163OpenSSLKeyPair* OpenSSLKeyPair::Generate(const KeyParams& key_params) {
164 EVP_PKEY* pkey = MakeKey(key_params);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000165 if (!pkey) {
166 LogSSLErrors("Generating key pair");
167 return NULL;
168 }
169 return new OpenSSLKeyPair(pkey);
170}
171
172OpenSSLKeyPair::~OpenSSLKeyPair() {
173 EVP_PKEY_free(pkey_);
174}
175
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000176OpenSSLKeyPair* OpenSSLKeyPair::GetReference() {
177 AddReference();
178 return new OpenSSLKeyPair(pkey_);
179}
180
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000181void OpenSSLKeyPair::AddReference() {
Jiayang Liu770cc382015-05-28 15:36:29 -0700182#if defined(OPENSSL_IS_BORINGSSL)
183 EVP_PKEY_up_ref(pkey_);
184#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000185 CRYPTO_add(&pkey_->references, 1, CRYPTO_LOCK_EVP_PKEY);
Jiayang Liu770cc382015-05-28 15:36:29 -0700186#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000187}
188
189#ifdef _DEBUG
190// Print a certificate to the log, for debugging.
191static void PrintCert(X509* x509) {
192 BIO* temp_memory_bio = BIO_new(BIO_s_mem());
193 if (!temp_memory_bio) {
194 LOG_F(LS_ERROR) << "Failed to allocate temporary memory bio";
195 return;
196 }
197 X509_print_ex(temp_memory_bio, x509, XN_FLAG_SEP_CPLUS_SPC, 0);
198 BIO_write(temp_memory_bio, "\0", 1);
199 char* buffer;
200 BIO_get_mem_data(temp_memory_bio, &buffer);
201 LOG(LS_VERBOSE) << buffer;
202 BIO_free(temp_memory_bio);
203}
204#endif
205
206OpenSSLCertificate* OpenSSLCertificate::Generate(
207 OpenSSLKeyPair* key_pair, const SSLIdentityParams& params) {
208 SSLIdentityParams actual_params(params);
209 if (actual_params.common_name.empty()) {
210 // Use a random string, arbitrarily 8chars long.
211 actual_params.common_name = CreateRandomString(8);
212 }
213 X509* x509 = MakeCertificate(key_pair->pkey(), actual_params);
214 if (!x509) {
215 LogSSLErrors("Generating certificate");
216 return NULL;
217 }
218#ifdef _DEBUG
219 PrintCert(x509);
220#endif
221 OpenSSLCertificate* ret = new OpenSSLCertificate(x509);
222 X509_free(x509);
223 return ret;
224}
225
226OpenSSLCertificate* OpenSSLCertificate::FromPEMString(
227 const std::string& pem_string) {
228 BIO* bio = BIO_new_mem_buf(const_cast<char*>(pem_string.c_str()), -1);
229 if (!bio)
230 return NULL;
231 BIO_set_mem_eof_return(bio, 0);
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200232 X509* x509 = PEM_read_bio_X509(bio, NULL, NULL, const_cast<char*>("\0"));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000233 BIO_free(bio); // Frees the BIO, but not the pointed-to string.
234
235 if (!x509)
236 return NULL;
237
238 OpenSSLCertificate* ret = new OpenSSLCertificate(x509);
239 X509_free(x509);
240 return ret;
241}
242
243// NOTE: This implementation only functions correctly after InitializeSSL
244// and before CleanupSSL.
245bool OpenSSLCertificate::GetSignatureDigestAlgorithm(
246 std::string* algorithm) const {
JiaYang (佳扬) Liu01aeaee2015-04-22 12:18:33 -0700247 int nid = OBJ_obj2nid(x509_->sig_alg->algorithm);
248 switch (nid) {
249 case NID_md5WithRSA:
250 case NID_md5WithRSAEncryption:
251 *algorithm = DIGEST_MD5;
252 break;
253 case NID_ecdsa_with_SHA1:
254 case NID_dsaWithSHA1:
255 case NID_dsaWithSHA1_2:
256 case NID_sha1WithRSA:
257 case NID_sha1WithRSAEncryption:
258 *algorithm = DIGEST_SHA_1;
259 break;
260 case NID_ecdsa_with_SHA224:
261 case NID_sha224WithRSAEncryption:
262 case NID_dsa_with_SHA224:
263 *algorithm = DIGEST_SHA_224;
264 break;
265 case NID_ecdsa_with_SHA256:
266 case NID_sha256WithRSAEncryption:
267 case NID_dsa_with_SHA256:
268 *algorithm = DIGEST_SHA_256;
269 break;
270 case NID_ecdsa_with_SHA384:
271 case NID_sha384WithRSAEncryption:
272 *algorithm = DIGEST_SHA_384;
273 break;
274 case NID_ecdsa_with_SHA512:
275 case NID_sha512WithRSAEncryption:
276 *algorithm = DIGEST_SHA_512;
277 break;
278 default:
279 // Unknown algorithm. There are several unhandled options that are less
280 // common and more complex.
281 LOG(LS_ERROR) << "Unknown signature algorithm NID: " << nid;
282 algorithm->clear();
283 return false;
284 }
285 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000286}
287
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000288bool OpenSSLCertificate::GetChain(SSLCertChain** chain) const {
289 // Chains are not yet supported when using OpenSSL.
290 // OpenSSLStreamAdapter::SSLVerifyCallback currently requires the remote
291 // certificate to be self-signed.
292 return false;
293}
294
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000295bool OpenSSLCertificate::ComputeDigest(const std::string& algorithm,
296 unsigned char* digest,
297 size_t size,
298 size_t* length) const {
299 return ComputeDigest(x509_, algorithm, digest, size, length);
300}
301
302bool OpenSSLCertificate::ComputeDigest(const X509* x509,
303 const std::string& algorithm,
304 unsigned char* digest,
305 size_t size,
306 size_t* length) {
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200307 const EVP_MD* md;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000308 unsigned int n;
309
310 if (!OpenSSLDigest::GetDigestEVP(algorithm, &md))
311 return false;
312
313 if (size < static_cast<size_t>(EVP_MD_size(md)))
314 return false;
315
316 X509_digest(x509, md, digest, &n);
317
318 *length = n;
319
320 return true;
321}
322
323OpenSSLCertificate::~OpenSSLCertificate() {
324 X509_free(x509_);
325}
326
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000327OpenSSLCertificate* OpenSSLCertificate::GetReference() const {
328 return new OpenSSLCertificate(x509_);
329}
330
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000331std::string OpenSSLCertificate::ToPEMString() const {
332 BIO* bio = BIO_new(BIO_s_mem());
333 if (!bio) {
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000334 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000335 }
336 if (!PEM_write_bio_X509(bio, x509_)) {
337 BIO_free(bio);
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000338 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000339 }
340 BIO_write(bio, "\0", 1);
341 char* buffer;
342 BIO_get_mem_data(bio, &buffer);
343 std::string ret(buffer);
344 BIO_free(bio);
345 return ret;
346}
347
348void OpenSSLCertificate::ToDER(Buffer* der_buffer) const {
349 // In case of failure, make sure to leave the buffer empty.
Karl Wiberg94784372015-04-20 14:03:07 +0200350 der_buffer->SetSize(0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000351
352 // Calculates the DER representation of the certificate, from scratch.
353 BIO* bio = BIO_new(BIO_s_mem());
354 if (!bio) {
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000355 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000356 }
357 if (!i2d_X509_bio(bio, x509_)) {
358 BIO_free(bio);
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000359 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000360 }
361 char* data;
362 size_t length = BIO_get_mem_data(bio, &data);
363 der_buffer->SetData(data, length);
364 BIO_free(bio);
365}
366
367void OpenSSLCertificate::AddReference() const {
368 ASSERT(x509_ != NULL);
Jiayang Liu770cc382015-05-28 15:36:29 -0700369#if defined(OPENSSL_IS_BORINGSSL)
370 X509_up_ref(x509_);
371#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000372 CRYPTO_add(&x509_->references, 1, CRYPTO_LOCK_X509);
Jiayang Liu770cc382015-05-28 15:36:29 -0700373#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000374}
375
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000376OpenSSLIdentity::OpenSSLIdentity(OpenSSLKeyPair* key_pair,
377 OpenSSLCertificate* certificate)
378 : key_pair_(key_pair), certificate_(certificate) {
379 ASSERT(key_pair != NULL);
380 ASSERT(certificate != NULL);
381}
382
383OpenSSLIdentity::~OpenSSLIdentity() = default;
384
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000385OpenSSLIdentity* OpenSSLIdentity::GenerateInternal(
386 const SSLIdentityParams& params) {
torbjorng4e572472015-10-08 09:42:49 -0700387 OpenSSLKeyPair* key_pair = OpenSSLKeyPair::Generate(params.key_params);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000388 if (key_pair) {
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200389 OpenSSLCertificate* certificate =
390 OpenSSLCertificate::Generate(key_pair, params);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000391 if (certificate)
392 return new OpenSSLIdentity(key_pair, certificate);
393 delete key_pair;
394 }
395 LOG(LS_INFO) << "Identity generation failed";
396 return NULL;
397}
398
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200399OpenSSLIdentity* OpenSSLIdentity::Generate(const std::string& common_name,
torbjorng4e572472015-10-08 09:42:49 -0700400 const KeyParams& key_params) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000401 SSLIdentityParams params;
torbjorng4e572472015-10-08 09:42:49 -0700402 params.key_params = key_params;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000403 params.common_name = common_name;
404 params.not_before = CERTIFICATE_WINDOW;
405 params.not_after = CERTIFICATE_LIFETIME;
406 return GenerateInternal(params);
407}
408
409OpenSSLIdentity* OpenSSLIdentity::GenerateForTest(
410 const SSLIdentityParams& params) {
411 return GenerateInternal(params);
412}
413
414SSLIdentity* OpenSSLIdentity::FromPEMStrings(
415 const std::string& private_key,
416 const std::string& certificate) {
417 scoped_ptr<OpenSSLCertificate> cert(
418 OpenSSLCertificate::FromPEMString(certificate));
419 if (!cert) {
420 LOG(LS_ERROR) << "Failed to create OpenSSLCertificate from PEM string.";
421 return NULL;
422 }
423
424 BIO* bio = BIO_new_mem_buf(const_cast<char*>(private_key.c_str()), -1);
425 if (!bio) {
426 LOG(LS_ERROR) << "Failed to create a new BIO buffer.";
427 return NULL;
428 }
429 BIO_set_mem_eof_return(bio, 0);
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200430 EVP_PKEY* pkey =
431 PEM_read_bio_PrivateKey(bio, NULL, NULL, const_cast<char*>("\0"));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000432 BIO_free(bio); // Frees the BIO, but not the pointed-to string.
433
434 if (!pkey) {
435 LOG(LS_ERROR) << "Failed to create the private key from PEM string.";
436 return NULL;
437 }
438
439 return new OpenSSLIdentity(new OpenSSLKeyPair(pkey),
440 cert.release());
441}
442
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000443const OpenSSLCertificate& OpenSSLIdentity::certificate() const {
444 return *certificate_;
445}
446
447OpenSSLIdentity* OpenSSLIdentity::GetReference() const {
448 return new OpenSSLIdentity(key_pair_->GetReference(),
449 certificate_->GetReference());
450}
451
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000452bool OpenSSLIdentity::ConfigureIdentity(SSL_CTX* ctx) {
453 // 1 is the documented success return code.
454 if (SSL_CTX_use_certificate(ctx, certificate_->x509()) != 1 ||
455 SSL_CTX_use_PrivateKey(ctx, key_pair_->pkey()) != 1) {
456 LogSSLErrors("Configuring key and certificate");
457 return false;
458 }
459 return true;
460}
461
462} // namespace rtc
463
464#endif // HAVE_OPENSSL_SSL_H