blob: de4e6a771e04f5f0c1924ba83313f790a16988a2 [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
torbjorng335204c2015-10-08 02:30:14 -070036// Strength of generated keys. Those are RSA.
37static const int KEY_LENGTH = 1024;
38
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000039// Random bits for certificate serial number
40static const int SERIAL_RAND_BITS = 64;
41
42// Certificate validity lifetime
43static const int CERTIFICATE_LIFETIME = 60*60*24*30; // 30 days, arbitrarily
44// Certificate validity window.
45// This is to compensate for slightly incorrect system clocks.
46static const int CERTIFICATE_WINDOW = -60*60*24;
47
48// Generate a key pair. Caller is responsible for freeing the returned object.
torbjorng335204c2015-10-08 02:30:14 -070049static EVP_PKEY* MakeKey(KeyType key_type) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000050 LOG(LS_INFO) << "Making key pair";
51 EVP_PKEY* pkey = EVP_PKEY_new();
torbjorng335204c2015-10-08 02:30:14 -070052 if (key_type == KT_RSA) {
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020053 BIGNUM* exponent = BN_new();
54 RSA* rsa = RSA_new();
55 if (!pkey || !exponent || !rsa ||
torbjorng335204c2015-10-08 02:30:14 -070056 !BN_set_word(exponent, 0x10001) || // 65537 RSA exponent
57 !RSA_generate_key_ex(rsa, KEY_LENGTH, exponent, NULL) ||
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020058 !EVP_PKEY_assign_RSA(pkey, rsa)) {
59 EVP_PKEY_free(pkey);
60 BN_free(exponent);
61 RSA_free(rsa);
62 LOG(LS_ERROR) << "Failed to make RSA key pair";
63 return NULL;
64 }
65 // ownership of rsa struct was assigned, don't free it.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000066 BN_free(exponent);
torbjorng335204c2015-10-08 02:30:14 -070067 } else if (key_type == KT_ECDSA) {
68 EC_KEY* ec_key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
69 if (!pkey || !ec_key || !EC_KEY_generate_key(ec_key) ||
70 !EVP_PKEY_assign_EC_KEY(pkey, ec_key)) {
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020071 EVP_PKEY_free(pkey);
torbjorng335204c2015-10-08 02:30:14 -070072 EC_KEY_free(ec_key);
73 LOG(LS_ERROR) << "Failed to make EC key pair";
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020074 return NULL;
75 }
torbjorng335204c2015-10-08 02:30:14 -070076 // ownership of ec_key struct was assigned, don't free it.
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020077 } else {
78 EVP_PKEY_free(pkey);
79 LOG(LS_ERROR) << "Key type requested not understood";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000080 return NULL;
81 }
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020082
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000083 LOG(LS_INFO) << "Returning key pair";
84 return pkey;
85}
86
87// Generate a self-signed certificate, with the public key from the
88// given key pair. Caller is responsible for freeing the returned object.
89static X509* MakeCertificate(EVP_PKEY* pkey, const SSLIdentityParams& params) {
90 LOG(LS_INFO) << "Making certificate for " << params.common_name;
91 X509* x509 = NULL;
92 BIGNUM* serial_number = NULL;
93 X509_NAME* name = NULL;
94
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
128 if (!X509_gmtime_adj(X509_get_notBefore(x509), params.not_before) ||
129 !X509_gmtime_adj(X509_get_notAfter(x509), params.not_after))
130 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
torbjorng335204c2015-10-08 02:30:14 -0700158OpenSSLKeyPair* OpenSSLKeyPair::Generate(KeyType key_type) {
159 EVP_PKEY* pkey = MakeKey(key_type);
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#if defined(OPENSSL_IS_BORINGSSL)
178 EVP_PKEY_up_ref(pkey_);
179#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000180 CRYPTO_add(&pkey_->references, 1, CRYPTO_LOCK_EVP_PKEY);
Jiayang Liu770cc382015-05-28 15:36:29 -0700181#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000182}
183
184#ifdef _DEBUG
185// 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 }
213#ifdef _DEBUG
214 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
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000283bool OpenSSLCertificate::GetChain(SSLCertChain** chain) const {
284 // Chains are not yet supported when using OpenSSL.
285 // OpenSSLStreamAdapter::SSLVerifyCallback currently requires the remote
286 // certificate to be self-signed.
287 return false;
288}
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);
Jiayang Liu770cc382015-05-28 15:36:29 -0700364#if defined(OPENSSL_IS_BORINGSSL)
365 X509_up_ref(x509_);
366#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000367 CRYPTO_add(&x509_->references, 1, CRYPTO_LOCK_X509);
Jiayang Liu770cc382015-05-28 15:36:29 -0700368#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000369}
370
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000371OpenSSLIdentity::OpenSSLIdentity(OpenSSLKeyPair* key_pair,
372 OpenSSLCertificate* certificate)
373 : key_pair_(key_pair), certificate_(certificate) {
374 ASSERT(key_pair != NULL);
375 ASSERT(certificate != NULL);
376}
377
378OpenSSLIdentity::~OpenSSLIdentity() = default;
379
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000380OpenSSLIdentity* OpenSSLIdentity::GenerateInternal(
381 const SSLIdentityParams& params) {
torbjorng335204c2015-10-08 02:30:14 -0700382 OpenSSLKeyPair* key_pair = OpenSSLKeyPair::Generate(params.key_type);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000383 if (key_pair) {
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200384 OpenSSLCertificate* certificate =
385 OpenSSLCertificate::Generate(key_pair, params);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000386 if (certificate)
387 return new OpenSSLIdentity(key_pair, certificate);
388 delete key_pair;
389 }
390 LOG(LS_INFO) << "Identity generation failed";
391 return NULL;
392}
393
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200394OpenSSLIdentity* OpenSSLIdentity::Generate(const std::string& common_name,
torbjorng335204c2015-10-08 02:30:14 -0700395 KeyType key_type) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000396 SSLIdentityParams params;
397 params.common_name = common_name;
398 params.not_before = CERTIFICATE_WINDOW;
399 params.not_after = CERTIFICATE_LIFETIME;
torbjorng335204c2015-10-08 02:30:14 -0700400 params.key_type = key_type;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000401 return GenerateInternal(params);
402}
403
404OpenSSLIdentity* OpenSSLIdentity::GenerateForTest(
405 const SSLIdentityParams& params) {
406 return GenerateInternal(params);
407}
408
409SSLIdentity* OpenSSLIdentity::FromPEMStrings(
410 const std::string& private_key,
411 const std::string& certificate) {
412 scoped_ptr<OpenSSLCertificate> cert(
413 OpenSSLCertificate::FromPEMString(certificate));
414 if (!cert) {
415 LOG(LS_ERROR) << "Failed to create OpenSSLCertificate from PEM string.";
416 return NULL;
417 }
418
419 BIO* bio = BIO_new_mem_buf(const_cast<char*>(private_key.c_str()), -1);
420 if (!bio) {
421 LOG(LS_ERROR) << "Failed to create a new BIO buffer.";
422 return NULL;
423 }
424 BIO_set_mem_eof_return(bio, 0);
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +0200425 EVP_PKEY* pkey =
426 PEM_read_bio_PrivateKey(bio, NULL, NULL, const_cast<char*>("\0"));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000427 BIO_free(bio); // Frees the BIO, but not the pointed-to string.
428
429 if (!pkey) {
430 LOG(LS_ERROR) << "Failed to create the private key from PEM string.";
431 return NULL;
432 }
433
434 return new OpenSSLIdentity(new OpenSSLKeyPair(pkey),
435 cert.release());
436}
437
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000438const OpenSSLCertificate& OpenSSLIdentity::certificate() const {
439 return *certificate_;
440}
441
442OpenSSLIdentity* OpenSSLIdentity::GetReference() const {
443 return new OpenSSLIdentity(key_pair_->GetReference(),
444 certificate_->GetReference());
445}
446
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000447bool OpenSSLIdentity::ConfigureIdentity(SSL_CTX* ctx) {
448 // 1 is the documented success return code.
449 if (SSL_CTX_use_certificate(ctx, certificate_->x509()) != 1 ||
450 SSL_CTX_use_PrivateKey(ctx, key_pair_->pkey()) != 1) {
451 LogSSLErrors("Configuring key and certificate");
452 return false;
453 }
454 return true;
455}
456
457} // namespace rtc
458
459#endif // HAVE_OPENSSL_SSL_H