blob: dbb040ecf41d6ceaf7ca64f5ead6b000a40612f8 [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
36// Strength of generated keys. Those are RSA.
37static const int KEY_LENGTH = 1024;
38
39// 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.
49static EVP_PKEY* MakeKey() {
50 LOG(LS_INFO) << "Making key pair";
51 EVP_PKEY* pkey = EVP_PKEY_new();
52 // RSA_generate_key is deprecated. Use _ex version.
53 BIGNUM* exponent = BN_new();
54 RSA* rsa = RSA_new();
55 if (!pkey || !exponent || !rsa ||
56 !BN_set_word(exponent, 0x10001) || // 65537 RSA exponent
57 !RSA_generate_key_ex(rsa, KEY_LENGTH, exponent, NULL) ||
58 !EVP_PKEY_assign_RSA(pkey, rsa)) {
59 EVP_PKEY_free(pkey);
60 BN_free(exponent);
61 RSA_free(rsa);
62 return NULL;
63 }
64 // ownership of rsa struct was assigned, don't free it.
65 BN_free(exponent);
66 LOG(LS_INFO) << "Returning key pair";
67 return pkey;
68}
69
70// Generate a self-signed certificate, with the public key from the
71// given key pair. Caller is responsible for freeing the returned object.
72static X509* MakeCertificate(EVP_PKEY* pkey, const SSLIdentityParams& params) {
73 LOG(LS_INFO) << "Making certificate for " << params.common_name;
74 X509* x509 = NULL;
75 BIGNUM* serial_number = NULL;
76 X509_NAME* name = NULL;
77
78 if ((x509=X509_new()) == NULL)
79 goto error;
80
81 if (!X509_set_pubkey(x509, pkey))
82 goto error;
83
84 // serial number
85 // temporary reference to serial number inside x509 struct
86 ASN1_INTEGER* asn1_serial_number;
87 if ((serial_number = BN_new()) == NULL ||
88 !BN_pseudo_rand(serial_number, SERIAL_RAND_BITS, 0, 0) ||
89 (asn1_serial_number = X509_get_serialNumber(x509)) == NULL ||
90 !BN_to_ASN1_INTEGER(serial_number, asn1_serial_number))
91 goto error;
92
93 if (!X509_set_version(x509, 0L)) // version 1
94 goto error;
95
96 // There are a lot of possible components for the name entries. In
97 // our P2P SSL mode however, the certificates are pre-exchanged
98 // (through the secure XMPP channel), and so the certificate
99 // identification is arbitrary. It can't be empty, so we set some
100 // arbitrary common_name. Note that this certificate goes out in
101 // clear during SSL negotiation, so there may be a privacy issue in
102 // putting anything recognizable here.
103 if ((name = X509_NAME_new()) == NULL ||
104 !X509_NAME_add_entry_by_NID(
105 name, NID_commonName, MBSTRING_UTF8,
106 (unsigned char*)params.common_name.c_str(), -1, -1, 0) ||
107 !X509_set_subject_name(x509, name) ||
108 !X509_set_issuer_name(x509, name))
109 goto error;
110
111 if (!X509_gmtime_adj(X509_get_notBefore(x509), params.not_before) ||
112 !X509_gmtime_adj(X509_get_notAfter(x509), params.not_after))
113 goto error;
114
Joachim Bauch1b794d52015-05-12 03:32:11 +0200115 if (!X509_sign(x509, pkey, EVP_sha256()))
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000116 goto error;
117
118 BN_free(serial_number);
119 X509_NAME_free(name);
120 LOG(LS_INFO) << "Returning certificate";
121 return x509;
122
123 error:
124 BN_free(serial_number);
125 X509_NAME_free(name);
126 X509_free(x509);
127 return NULL;
128}
129
130// This dumps the SSL error stack to the log.
131static void LogSSLErrors(const std::string& prefix) {
132 char error_buf[200];
133 unsigned long err;
134
135 while ((err = ERR_get_error()) != 0) {
136 ERR_error_string_n(err, error_buf, sizeof(error_buf));
137 LOG(LS_ERROR) << prefix << ": " << error_buf << "\n";
138 }
139}
140
141OpenSSLKeyPair* OpenSSLKeyPair::Generate() {
142 EVP_PKEY* pkey = MakeKey();
143 if (!pkey) {
144 LogSSLErrors("Generating key pair");
145 return NULL;
146 }
147 return new OpenSSLKeyPair(pkey);
148}
149
150OpenSSLKeyPair::~OpenSSLKeyPair() {
151 EVP_PKEY_free(pkey_);
152}
153
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000154OpenSSLKeyPair* OpenSSLKeyPair::GetReference() {
155 AddReference();
156 return new OpenSSLKeyPair(pkey_);
157}
158
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000159void OpenSSLKeyPair::AddReference() {
Jiayang Liu770cc382015-05-28 15:36:29 -0700160#if defined(OPENSSL_IS_BORINGSSL)
161 EVP_PKEY_up_ref(pkey_);
162#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000163 CRYPTO_add(&pkey_->references, 1, CRYPTO_LOCK_EVP_PKEY);
Jiayang Liu770cc382015-05-28 15:36:29 -0700164#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000165}
166
167#ifdef _DEBUG
168// Print a certificate to the log, for debugging.
169static void PrintCert(X509* x509) {
170 BIO* temp_memory_bio = BIO_new(BIO_s_mem());
171 if (!temp_memory_bio) {
172 LOG_F(LS_ERROR) << "Failed to allocate temporary memory bio";
173 return;
174 }
175 X509_print_ex(temp_memory_bio, x509, XN_FLAG_SEP_CPLUS_SPC, 0);
176 BIO_write(temp_memory_bio, "\0", 1);
177 char* buffer;
178 BIO_get_mem_data(temp_memory_bio, &buffer);
179 LOG(LS_VERBOSE) << buffer;
180 BIO_free(temp_memory_bio);
181}
182#endif
183
184OpenSSLCertificate* OpenSSLCertificate::Generate(
185 OpenSSLKeyPair* key_pair, const SSLIdentityParams& params) {
186 SSLIdentityParams actual_params(params);
187 if (actual_params.common_name.empty()) {
188 // Use a random string, arbitrarily 8chars long.
189 actual_params.common_name = CreateRandomString(8);
190 }
191 X509* x509 = MakeCertificate(key_pair->pkey(), actual_params);
192 if (!x509) {
193 LogSSLErrors("Generating certificate");
194 return NULL;
195 }
196#ifdef _DEBUG
197 PrintCert(x509);
198#endif
199 OpenSSLCertificate* ret = new OpenSSLCertificate(x509);
200 X509_free(x509);
201 return ret;
202}
203
204OpenSSLCertificate* OpenSSLCertificate::FromPEMString(
205 const std::string& pem_string) {
206 BIO* bio = BIO_new_mem_buf(const_cast<char*>(pem_string.c_str()), -1);
207 if (!bio)
208 return NULL;
209 BIO_set_mem_eof_return(bio, 0);
210 X509 *x509 = PEM_read_bio_X509(bio, NULL, NULL,
211 const_cast<char*>("\0"));
212 BIO_free(bio); // Frees the BIO, but not the pointed-to string.
213
214 if (!x509)
215 return NULL;
216
217 OpenSSLCertificate* ret = new OpenSSLCertificate(x509);
218 X509_free(x509);
219 return ret;
220}
221
222// NOTE: This implementation only functions correctly after InitializeSSL
223// and before CleanupSSL.
224bool OpenSSLCertificate::GetSignatureDigestAlgorithm(
225 std::string* algorithm) const {
JiaYang (佳扬) Liu01aeaee2015-04-22 12:18:33 -0700226 int nid = OBJ_obj2nid(x509_->sig_alg->algorithm);
227 switch (nid) {
228 case NID_md5WithRSA:
229 case NID_md5WithRSAEncryption:
230 *algorithm = DIGEST_MD5;
231 break;
232 case NID_ecdsa_with_SHA1:
233 case NID_dsaWithSHA1:
234 case NID_dsaWithSHA1_2:
235 case NID_sha1WithRSA:
236 case NID_sha1WithRSAEncryption:
237 *algorithm = DIGEST_SHA_1;
238 break;
239 case NID_ecdsa_with_SHA224:
240 case NID_sha224WithRSAEncryption:
241 case NID_dsa_with_SHA224:
242 *algorithm = DIGEST_SHA_224;
243 break;
244 case NID_ecdsa_with_SHA256:
245 case NID_sha256WithRSAEncryption:
246 case NID_dsa_with_SHA256:
247 *algorithm = DIGEST_SHA_256;
248 break;
249 case NID_ecdsa_with_SHA384:
250 case NID_sha384WithRSAEncryption:
251 *algorithm = DIGEST_SHA_384;
252 break;
253 case NID_ecdsa_with_SHA512:
254 case NID_sha512WithRSAEncryption:
255 *algorithm = DIGEST_SHA_512;
256 break;
257 default:
258 // Unknown algorithm. There are several unhandled options that are less
259 // common and more complex.
260 LOG(LS_ERROR) << "Unknown signature algorithm NID: " << nid;
261 algorithm->clear();
262 return false;
263 }
264 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000265}
266
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000267bool OpenSSLCertificate::GetChain(SSLCertChain** chain) const {
268 // Chains are not yet supported when using OpenSSL.
269 // OpenSSLStreamAdapter::SSLVerifyCallback currently requires the remote
270 // certificate to be self-signed.
271 return false;
272}
273
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000274bool OpenSSLCertificate::ComputeDigest(const std::string& algorithm,
275 unsigned char* digest,
276 size_t size,
277 size_t* length) const {
278 return ComputeDigest(x509_, algorithm, digest, size, length);
279}
280
281bool OpenSSLCertificate::ComputeDigest(const X509* x509,
282 const std::string& algorithm,
283 unsigned char* digest,
284 size_t size,
285 size_t* length) {
286 const EVP_MD *md;
287 unsigned int n;
288
289 if (!OpenSSLDigest::GetDigestEVP(algorithm, &md))
290 return false;
291
292 if (size < static_cast<size_t>(EVP_MD_size(md)))
293 return false;
294
295 X509_digest(x509, md, digest, &n);
296
297 *length = n;
298
299 return true;
300}
301
302OpenSSLCertificate::~OpenSSLCertificate() {
303 X509_free(x509_);
304}
305
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000306OpenSSLCertificate* OpenSSLCertificate::GetReference() const {
307 return new OpenSSLCertificate(x509_);
308}
309
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000310std::string OpenSSLCertificate::ToPEMString() const {
311 BIO* bio = BIO_new(BIO_s_mem());
312 if (!bio) {
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000313 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000314 }
315 if (!PEM_write_bio_X509(bio, x509_)) {
316 BIO_free(bio);
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000317 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000318 }
319 BIO_write(bio, "\0", 1);
320 char* buffer;
321 BIO_get_mem_data(bio, &buffer);
322 std::string ret(buffer);
323 BIO_free(bio);
324 return ret;
325}
326
327void OpenSSLCertificate::ToDER(Buffer* der_buffer) const {
328 // In case of failure, make sure to leave the buffer empty.
Karl Wiberg94784372015-04-20 14:03:07 +0200329 der_buffer->SetSize(0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000330
331 // Calculates the DER representation of the certificate, from scratch.
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 (!i2d_X509_bio(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 char* data;
341 size_t length = BIO_get_mem_data(bio, &data);
342 der_buffer->SetData(data, length);
343 BIO_free(bio);
344}
345
346void OpenSSLCertificate::AddReference() const {
347 ASSERT(x509_ != NULL);
Jiayang Liu770cc382015-05-28 15:36:29 -0700348#if defined(OPENSSL_IS_BORINGSSL)
349 X509_up_ref(x509_);
350#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000351 CRYPTO_add(&x509_->references, 1, CRYPTO_LOCK_X509);
Jiayang Liu770cc382015-05-28 15:36:29 -0700352#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000353}
354
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000355OpenSSLIdentity::OpenSSLIdentity(OpenSSLKeyPair* key_pair,
356 OpenSSLCertificate* certificate)
357 : key_pair_(key_pair), certificate_(certificate) {
358 ASSERT(key_pair != NULL);
359 ASSERT(certificate != NULL);
360}
361
362OpenSSLIdentity::~OpenSSLIdentity() = default;
363
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000364OpenSSLIdentity* OpenSSLIdentity::GenerateInternal(
365 const SSLIdentityParams& params) {
366 OpenSSLKeyPair *key_pair = OpenSSLKeyPair::Generate();
367 if (key_pair) {
368 OpenSSLCertificate *certificate = OpenSSLCertificate::Generate(
369 key_pair, params);
370 if (certificate)
371 return new OpenSSLIdentity(key_pair, certificate);
372 delete key_pair;
373 }
374 LOG(LS_INFO) << "Identity generation failed";
375 return NULL;
376}
377
378OpenSSLIdentity* OpenSSLIdentity::Generate(const std::string& common_name) {
379 SSLIdentityParams params;
380 params.common_name = common_name;
381 params.not_before = CERTIFICATE_WINDOW;
382 params.not_after = CERTIFICATE_LIFETIME;
383 return GenerateInternal(params);
384}
385
386OpenSSLIdentity* OpenSSLIdentity::GenerateForTest(
387 const SSLIdentityParams& params) {
388 return GenerateInternal(params);
389}
390
391SSLIdentity* OpenSSLIdentity::FromPEMStrings(
392 const std::string& private_key,
393 const std::string& certificate) {
394 scoped_ptr<OpenSSLCertificate> cert(
395 OpenSSLCertificate::FromPEMString(certificate));
396 if (!cert) {
397 LOG(LS_ERROR) << "Failed to create OpenSSLCertificate from PEM string.";
398 return NULL;
399 }
400
401 BIO* bio = BIO_new_mem_buf(const_cast<char*>(private_key.c_str()), -1);
402 if (!bio) {
403 LOG(LS_ERROR) << "Failed to create a new BIO buffer.";
404 return NULL;
405 }
406 BIO_set_mem_eof_return(bio, 0);
407 EVP_PKEY *pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL,
408 const_cast<char*>("\0"));
409 BIO_free(bio); // Frees the BIO, but not the pointed-to string.
410
411 if (!pkey) {
412 LOG(LS_ERROR) << "Failed to create the private key from PEM string.";
413 return NULL;
414 }
415
416 return new OpenSSLIdentity(new OpenSSLKeyPair(pkey),
417 cert.release());
418}
419
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000420const OpenSSLCertificate& OpenSSLIdentity::certificate() const {
421 return *certificate_;
422}
423
424OpenSSLIdentity* OpenSSLIdentity::GetReference() const {
425 return new OpenSSLIdentity(key_pair_->GetReference(),
426 certificate_->GetReference());
427}
428
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000429bool OpenSSLIdentity::ConfigureIdentity(SSL_CTX* ctx) {
430 // 1 is the documented success return code.
431 if (SSL_CTX_use_certificate(ctx, certificate_->x509()) != 1 ||
432 SSL_CTX_use_PrivateKey(ctx, key_pair_->pkey()) != 1) {
433 LogSSLErrors("Configuring key and certificate");
434 return false;
435 }
436 return true;
437}
438
439} // namespace rtc
440
441#endif // HAVE_OPENSSL_SSL_H