blob: 269bfced1706f612a8f82ab566eea28ce4b4bb53 [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
110 if (!X509_set_version(x509, 0L)) // version 1
111 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() {
Jiayang Liu770cc382015-05-28 15:36:29 -0700177 EVP_PKEY_up_ref(pkey_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000178}
179
tfarinaa41ab932015-10-30 16:08:48 -0700180#if !defined(NDEBUG)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000181// Print a certificate to the log, for debugging.
182static void PrintCert(X509* x509) {
183 BIO* temp_memory_bio = BIO_new(BIO_s_mem());
184 if (!temp_memory_bio) {
185 LOG_F(LS_ERROR) << "Failed to allocate temporary memory bio";
186 return;
187 }
188 X509_print_ex(temp_memory_bio, x509, XN_FLAG_SEP_CPLUS_SPC, 0);
189 BIO_write(temp_memory_bio, "\0", 1);
190 char* buffer;
191 BIO_get_mem_data(temp_memory_bio, &buffer);
192 LOG(LS_VERBOSE) << buffer;
193 BIO_free(temp_memory_bio);
194}
195#endif
196
197OpenSSLCertificate* OpenSSLCertificate::Generate(
198 OpenSSLKeyPair* key_pair, const SSLIdentityParams& params) {
199 SSLIdentityParams actual_params(params);
200 if (actual_params.common_name.empty()) {
201 // Use a random string, arbitrarily 8chars long.
202 actual_params.common_name = CreateRandomString(8);
203 }
204 X509* x509 = MakeCertificate(key_pair->pkey(), actual_params);
205 if (!x509) {
206 LogSSLErrors("Generating certificate");
207 return NULL;
208 }
tfarinaa41ab932015-10-30 16:08:48 -0700209#if !defined(NDEBUG)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000210 PrintCert(x509);
211#endif
212 OpenSSLCertificate* ret = new OpenSSLCertificate(x509);
213 X509_free(x509);
214 return ret;
215}
216
217OpenSSLCertificate* OpenSSLCertificate::FromPEMString(
218 const std::string& pem_string) {
219 BIO* bio = BIO_new_mem_buf(const_cast<char*>(pem_string.c_str()), -1);
220 if (!bio)
221 return NULL;
222 BIO_set_mem_eof_return(bio, 0);
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200223 X509* x509 = PEM_read_bio_X509(bio, NULL, NULL, const_cast<char*>("\0"));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000224 BIO_free(bio); // Frees the BIO, but not the pointed-to string.
225
226 if (!x509)
227 return NULL;
228
229 OpenSSLCertificate* ret = new OpenSSLCertificate(x509);
230 X509_free(x509);
231 return ret;
232}
233
234// NOTE: This implementation only functions correctly after InitializeSSL
235// and before CleanupSSL.
236bool OpenSSLCertificate::GetSignatureDigestAlgorithm(
237 std::string* algorithm) const {
JiaYang (佳扬) Liu01aeaee2015-04-22 12:18:33 -0700238 int nid = OBJ_obj2nid(x509_->sig_alg->algorithm);
239 switch (nid) {
240 case NID_md5WithRSA:
241 case NID_md5WithRSAEncryption:
242 *algorithm = DIGEST_MD5;
243 break;
244 case NID_ecdsa_with_SHA1:
245 case NID_dsaWithSHA1:
246 case NID_dsaWithSHA1_2:
247 case NID_sha1WithRSA:
248 case NID_sha1WithRSAEncryption:
249 *algorithm = DIGEST_SHA_1;
250 break;
251 case NID_ecdsa_with_SHA224:
252 case NID_sha224WithRSAEncryption:
253 case NID_dsa_with_SHA224:
254 *algorithm = DIGEST_SHA_224;
255 break;
256 case NID_ecdsa_with_SHA256:
257 case NID_sha256WithRSAEncryption:
258 case NID_dsa_with_SHA256:
259 *algorithm = DIGEST_SHA_256;
260 break;
261 case NID_ecdsa_with_SHA384:
262 case NID_sha384WithRSAEncryption:
263 *algorithm = DIGEST_SHA_384;
264 break;
265 case NID_ecdsa_with_SHA512:
266 case NID_sha512WithRSAEncryption:
267 *algorithm = DIGEST_SHA_512;
268 break;
269 default:
270 // Unknown algorithm. There are several unhandled options that are less
271 // common and more complex.
272 LOG(LS_ERROR) << "Unknown signature algorithm NID: " << nid;
273 algorithm->clear();
274 return false;
275 }
276 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000277}
278
kwibergf5d47862016-03-15 12:53:24 -0700279rtc::scoped_ptr<SSLCertChain> OpenSSLCertificate::GetChain() const {
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000280 // Chains are not yet supported when using OpenSSL.
281 // OpenSSLStreamAdapter::SSLVerifyCallback currently requires the remote
282 // certificate to be self-signed.
kwibergf5d47862016-03-15 12:53:24 -0700283 return nullptr;
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000284}
285
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000286bool OpenSSLCertificate::ComputeDigest(const std::string& algorithm,
287 unsigned char* digest,
288 size_t size,
289 size_t* length) const {
290 return ComputeDigest(x509_, algorithm, digest, size, length);
291}
292
293bool OpenSSLCertificate::ComputeDigest(const X509* x509,
294 const std::string& algorithm,
295 unsigned char* digest,
296 size_t size,
297 size_t* length) {
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200298 const EVP_MD* md;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000299 unsigned int n;
300
301 if (!OpenSSLDigest::GetDigestEVP(algorithm, &md))
302 return false;
303
304 if (size < static_cast<size_t>(EVP_MD_size(md)))
305 return false;
306
307 X509_digest(x509, md, digest, &n);
308
309 *length = n;
310
311 return true;
312}
313
314OpenSSLCertificate::~OpenSSLCertificate() {
315 X509_free(x509_);
316}
317
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000318OpenSSLCertificate* OpenSSLCertificate::GetReference() const {
319 return new OpenSSLCertificate(x509_);
320}
321
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000322std::string OpenSSLCertificate::ToPEMString() const {
323 BIO* bio = BIO_new(BIO_s_mem());
324 if (!bio) {
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000325 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000326 }
327 if (!PEM_write_bio_X509(bio, x509_)) {
328 BIO_free(bio);
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000329 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000330 }
331 BIO_write(bio, "\0", 1);
332 char* buffer;
333 BIO_get_mem_data(bio, &buffer);
334 std::string ret(buffer);
335 BIO_free(bio);
336 return ret;
337}
338
339void OpenSSLCertificate::ToDER(Buffer* der_buffer) const {
340 // In case of failure, make sure to leave the buffer empty.
Karl Wiberg94784372015-04-20 14:03:07 +0200341 der_buffer->SetSize(0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000342
343 // Calculates the DER representation of the certificate, from scratch.
344 BIO* bio = BIO_new(BIO_s_mem());
345 if (!bio) {
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000346 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000347 }
348 if (!i2d_X509_bio(bio, x509_)) {
349 BIO_free(bio);
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000350 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000351 }
352 char* data;
353 size_t length = BIO_get_mem_data(bio, &data);
354 der_buffer->SetData(data, length);
355 BIO_free(bio);
356}
357
358void OpenSSLCertificate::AddReference() const {
359 ASSERT(x509_ != NULL);
Jiayang Liu770cc382015-05-28 15:36:29 -0700360 X509_up_ref(x509_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000361}
362
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100363// Documented in sslidentity.h.
364int64_t OpenSSLCertificate::CertificateExpirationTime() const {
365 ASN1_TIME* expire_time = X509_get_notAfter(x509_);
366 bool long_format;
367
368 if (expire_time->type == V_ASN1_UTCTIME) {
369 long_format = false;
370 } else if (expire_time->type == V_ASN1_GENERALIZEDTIME) {
371 long_format = true;
372 } else {
373 return -1;
374 }
375
376 return ASN1TimeToSec(expire_time->data, expire_time->length, long_format);
377}
378
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000379OpenSSLIdentity::OpenSSLIdentity(OpenSSLKeyPair* key_pair,
380 OpenSSLCertificate* certificate)
381 : key_pair_(key_pair), certificate_(certificate) {
382 ASSERT(key_pair != NULL);
383 ASSERT(certificate != NULL);
384}
385
386OpenSSLIdentity::~OpenSSLIdentity() = default;
387
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000388OpenSSLIdentity* OpenSSLIdentity::GenerateInternal(
389 const SSLIdentityParams& params) {
torbjorng4e572472015-10-08 09:42:49 -0700390 OpenSSLKeyPair* key_pair = OpenSSLKeyPair::Generate(params.key_params);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000391 if (key_pair) {
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200392 OpenSSLCertificate* certificate =
393 OpenSSLCertificate::Generate(key_pair, params);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000394 if (certificate)
395 return new OpenSSLIdentity(key_pair, certificate);
396 delete key_pair;
397 }
398 LOG(LS_INFO) << "Identity generation failed";
399 return NULL;
400}
401
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200402OpenSSLIdentity* OpenSSLIdentity::Generate(const std::string& common_name,
torbjornge8dc0812016-02-15 09:35:54 -0800403 const KeyParams& key_params,
404 time_t certificate_lifetime) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000405 SSLIdentityParams params;
torbjorng4e572472015-10-08 09:42:49 -0700406 params.key_params = key_params;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000407 params.common_name = common_name;
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100408 time_t now = time(NULL);
torbjornge8dc0812016-02-15 09:35:54 -0800409 params.not_before = now + kCertificateWindow;
410 params.not_after = now + certificate_lifetime;
411 RTC_DCHECK(params.not_before < params.not_after);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000412 return GenerateInternal(params);
413}
414
415OpenSSLIdentity* OpenSSLIdentity::GenerateForTest(
416 const SSLIdentityParams& params) {
417 return GenerateInternal(params);
418}
419
420SSLIdentity* OpenSSLIdentity::FromPEMStrings(
421 const std::string& private_key,
422 const std::string& certificate) {
423 scoped_ptr<OpenSSLCertificate> cert(
424 OpenSSLCertificate::FromPEMString(certificate));
425 if (!cert) {
426 LOG(LS_ERROR) << "Failed to create OpenSSLCertificate from PEM string.";
427 return NULL;
428 }
429
430 BIO* bio = BIO_new_mem_buf(const_cast<char*>(private_key.c_str()), -1);
431 if (!bio) {
432 LOG(LS_ERROR) << "Failed to create a new BIO buffer.";
433 return NULL;
434 }
435 BIO_set_mem_eof_return(bio, 0);
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200436 EVP_PKEY* pkey =
437 PEM_read_bio_PrivateKey(bio, NULL, NULL, const_cast<char*>("\0"));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000438 BIO_free(bio); // Frees the BIO, but not the pointed-to string.
439
440 if (!pkey) {
441 LOG(LS_ERROR) << "Failed to create the private key from PEM string.";
442 return NULL;
443 }
444
445 return new OpenSSLIdentity(new OpenSSLKeyPair(pkey),
446 cert.release());
447}
448
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000449const OpenSSLCertificate& OpenSSLIdentity::certificate() const {
450 return *certificate_;
451}
452
453OpenSSLIdentity* OpenSSLIdentity::GetReference() const {
454 return new OpenSSLIdentity(key_pair_->GetReference(),
455 certificate_->GetReference());
456}
457
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000458bool OpenSSLIdentity::ConfigureIdentity(SSL_CTX* ctx) {
459 // 1 is the documented success return code.
460 if (SSL_CTX_use_certificate(ctx, certificate_->x509()) != 1 ||
461 SSL_CTX_use_PrivateKey(ctx, key_pair_->pkey()) != 1) {
462 LogSSLErrors("Configuring key and certificate");
463 return false;
464 }
465 return true;
466}
467
468} // namespace rtc
469
470#endif // HAVE_OPENSSL_SSL_H