blob: 7aa99467fc9a6438321c6c72a3bba75916b0f44a [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
115 if (!X509_sign(x509, pkey, EVP_sha1()))
116 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() {
160 CRYPTO_add(&pkey_->references, 1, CRYPTO_LOCK_EVP_PKEY);
161}
162
163#ifdef _DEBUG
164// Print a certificate to the log, for debugging.
165static void PrintCert(X509* x509) {
166 BIO* temp_memory_bio = BIO_new(BIO_s_mem());
167 if (!temp_memory_bio) {
168 LOG_F(LS_ERROR) << "Failed to allocate temporary memory bio";
169 return;
170 }
171 X509_print_ex(temp_memory_bio, x509, XN_FLAG_SEP_CPLUS_SPC, 0);
172 BIO_write(temp_memory_bio, "\0", 1);
173 char* buffer;
174 BIO_get_mem_data(temp_memory_bio, &buffer);
175 LOG(LS_VERBOSE) << buffer;
176 BIO_free(temp_memory_bio);
177}
178#endif
179
180OpenSSLCertificate* OpenSSLCertificate::Generate(
181 OpenSSLKeyPair* key_pair, const SSLIdentityParams& params) {
182 SSLIdentityParams actual_params(params);
183 if (actual_params.common_name.empty()) {
184 // Use a random string, arbitrarily 8chars long.
185 actual_params.common_name = CreateRandomString(8);
186 }
187 X509* x509 = MakeCertificate(key_pair->pkey(), actual_params);
188 if (!x509) {
189 LogSSLErrors("Generating certificate");
190 return NULL;
191 }
192#ifdef _DEBUG
193 PrintCert(x509);
194#endif
195 OpenSSLCertificate* ret = new OpenSSLCertificate(x509);
196 X509_free(x509);
197 return ret;
198}
199
200OpenSSLCertificate* OpenSSLCertificate::FromPEMString(
201 const std::string& pem_string) {
202 BIO* bio = BIO_new_mem_buf(const_cast<char*>(pem_string.c_str()), -1);
203 if (!bio)
204 return NULL;
205 BIO_set_mem_eof_return(bio, 0);
206 X509 *x509 = PEM_read_bio_X509(bio, NULL, NULL,
207 const_cast<char*>("\0"));
208 BIO_free(bio); // Frees the BIO, but not the pointed-to string.
209
210 if (!x509)
211 return NULL;
212
213 OpenSSLCertificate* ret = new OpenSSLCertificate(x509);
214 X509_free(x509);
215 return ret;
216}
217
218// NOTE: This implementation only functions correctly after InitializeSSL
219// and before CleanupSSL.
220bool OpenSSLCertificate::GetSignatureDigestAlgorithm(
221 std::string* algorithm) const {
222 return OpenSSLDigest::GetDigestName(
223 EVP_get_digestbyobj(x509_->sig_alg->algorithm), algorithm);
224}
225
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000226bool OpenSSLCertificate::GetChain(SSLCertChain** chain) const {
227 // Chains are not yet supported when using OpenSSL.
228 // OpenSSLStreamAdapter::SSLVerifyCallback currently requires the remote
229 // certificate to be self-signed.
230 return false;
231}
232
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000233bool OpenSSLCertificate::ComputeDigest(const std::string& algorithm,
234 unsigned char* digest,
235 size_t size,
236 size_t* length) const {
237 return ComputeDigest(x509_, algorithm, digest, size, length);
238}
239
240bool OpenSSLCertificate::ComputeDigest(const X509* x509,
241 const std::string& algorithm,
242 unsigned char* digest,
243 size_t size,
244 size_t* length) {
245 const EVP_MD *md;
246 unsigned int n;
247
248 if (!OpenSSLDigest::GetDigestEVP(algorithm, &md))
249 return false;
250
251 if (size < static_cast<size_t>(EVP_MD_size(md)))
252 return false;
253
254 X509_digest(x509, md, digest, &n);
255
256 *length = n;
257
258 return true;
259}
260
261OpenSSLCertificate::~OpenSSLCertificate() {
262 X509_free(x509_);
263}
264
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000265OpenSSLCertificate* OpenSSLCertificate::GetReference() const {
266 return new OpenSSLCertificate(x509_);
267}
268
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000269std::string OpenSSLCertificate::ToPEMString() const {
270 BIO* bio = BIO_new(BIO_s_mem());
271 if (!bio) {
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000272 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000273 }
274 if (!PEM_write_bio_X509(bio, x509_)) {
275 BIO_free(bio);
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000276 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000277 }
278 BIO_write(bio, "\0", 1);
279 char* buffer;
280 BIO_get_mem_data(bio, &buffer);
281 std::string ret(buffer);
282 BIO_free(bio);
283 return ret;
284}
285
286void OpenSSLCertificate::ToDER(Buffer* der_buffer) const {
287 // In case of failure, make sure to leave the buffer empty.
Karl Wiberg94784372015-04-20 14:03:07 +0200288 der_buffer->SetSize(0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000289
290 // Calculates the DER representation of the certificate, from scratch.
291 BIO* bio = BIO_new(BIO_s_mem());
292 if (!bio) {
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000293 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000294 }
295 if (!i2d_X509_bio(bio, x509_)) {
296 BIO_free(bio);
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000297 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000298 }
299 char* data;
300 size_t length = BIO_get_mem_data(bio, &data);
301 der_buffer->SetData(data, length);
302 BIO_free(bio);
303}
304
305void OpenSSLCertificate::AddReference() const {
306 ASSERT(x509_ != NULL);
307 CRYPTO_add(&x509_->references, 1, CRYPTO_LOCK_X509);
308}
309
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000310OpenSSLIdentity::OpenSSLIdentity(OpenSSLKeyPair* key_pair,
311 OpenSSLCertificate* certificate)
312 : key_pair_(key_pair), certificate_(certificate) {
313 ASSERT(key_pair != NULL);
314 ASSERT(certificate != NULL);
315}
316
317OpenSSLIdentity::~OpenSSLIdentity() = default;
318
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000319OpenSSLIdentity* OpenSSLIdentity::GenerateInternal(
320 const SSLIdentityParams& params) {
321 OpenSSLKeyPair *key_pair = OpenSSLKeyPair::Generate();
322 if (key_pair) {
323 OpenSSLCertificate *certificate = OpenSSLCertificate::Generate(
324 key_pair, params);
325 if (certificate)
326 return new OpenSSLIdentity(key_pair, certificate);
327 delete key_pair;
328 }
329 LOG(LS_INFO) << "Identity generation failed";
330 return NULL;
331}
332
333OpenSSLIdentity* OpenSSLIdentity::Generate(const std::string& common_name) {
334 SSLIdentityParams params;
335 params.common_name = common_name;
336 params.not_before = CERTIFICATE_WINDOW;
337 params.not_after = CERTIFICATE_LIFETIME;
338 return GenerateInternal(params);
339}
340
341OpenSSLIdentity* OpenSSLIdentity::GenerateForTest(
342 const SSLIdentityParams& params) {
343 return GenerateInternal(params);
344}
345
346SSLIdentity* OpenSSLIdentity::FromPEMStrings(
347 const std::string& private_key,
348 const std::string& certificate) {
349 scoped_ptr<OpenSSLCertificate> cert(
350 OpenSSLCertificate::FromPEMString(certificate));
351 if (!cert) {
352 LOG(LS_ERROR) << "Failed to create OpenSSLCertificate from PEM string.";
353 return NULL;
354 }
355
356 BIO* bio = BIO_new_mem_buf(const_cast<char*>(private_key.c_str()), -1);
357 if (!bio) {
358 LOG(LS_ERROR) << "Failed to create a new BIO buffer.";
359 return NULL;
360 }
361 BIO_set_mem_eof_return(bio, 0);
362 EVP_PKEY *pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL,
363 const_cast<char*>("\0"));
364 BIO_free(bio); // Frees the BIO, but not the pointed-to string.
365
366 if (!pkey) {
367 LOG(LS_ERROR) << "Failed to create the private key from PEM string.";
368 return NULL;
369 }
370
371 return new OpenSSLIdentity(new OpenSSLKeyPair(pkey),
372 cert.release());
373}
374
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000375const OpenSSLCertificate& OpenSSLIdentity::certificate() const {
376 return *certificate_;
377}
378
379OpenSSLIdentity* OpenSSLIdentity::GetReference() const {
380 return new OpenSSLIdentity(key_pair_->GetReference(),
381 certificate_->GetReference());
382}
383
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000384bool OpenSSLIdentity::ConfigureIdentity(SSL_CTX* ctx) {
385 // 1 is the documented success return code.
386 if (SSL_CTX_use_certificate(ctx, certificate_->x509()) != 1 ||
387 SSL_CTX_use_PrivateKey(ctx, key_pair_->pkey()) != 1) {
388 LogSSLErrors("Configuring key and certificate");
389 return false;
390 }
391 return true;
392}
393
394} // namespace rtc
395
396#endif // HAVE_OPENSSL_SSL_H