blob: 7dc14fc477bebc3348bdc0cea0a2b686c361e905 [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 {
JiaYang (佳扬) Liu01aeaee2015-04-22 12:18:33 -0700222 int nid = OBJ_obj2nid(x509_->sig_alg->algorithm);
223 switch (nid) {
224 case NID_md5WithRSA:
225 case NID_md5WithRSAEncryption:
226 *algorithm = DIGEST_MD5;
227 break;
228 case NID_ecdsa_with_SHA1:
229 case NID_dsaWithSHA1:
230 case NID_dsaWithSHA1_2:
231 case NID_sha1WithRSA:
232 case NID_sha1WithRSAEncryption:
233 *algorithm = DIGEST_SHA_1;
234 break;
235 case NID_ecdsa_with_SHA224:
236 case NID_sha224WithRSAEncryption:
237 case NID_dsa_with_SHA224:
238 *algorithm = DIGEST_SHA_224;
239 break;
240 case NID_ecdsa_with_SHA256:
241 case NID_sha256WithRSAEncryption:
242 case NID_dsa_with_SHA256:
243 *algorithm = DIGEST_SHA_256;
244 break;
245 case NID_ecdsa_with_SHA384:
246 case NID_sha384WithRSAEncryption:
247 *algorithm = DIGEST_SHA_384;
248 break;
249 case NID_ecdsa_with_SHA512:
250 case NID_sha512WithRSAEncryption:
251 *algorithm = DIGEST_SHA_512;
252 break;
253 default:
254 // Unknown algorithm. There are several unhandled options that are less
255 // common and more complex.
256 LOG(LS_ERROR) << "Unknown signature algorithm NID: " << nid;
257 algorithm->clear();
258 return false;
259 }
260 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000261}
262
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000263bool OpenSSLCertificate::GetChain(SSLCertChain** chain) const {
264 // Chains are not yet supported when using OpenSSL.
265 // OpenSSLStreamAdapter::SSLVerifyCallback currently requires the remote
266 // certificate to be self-signed.
267 return false;
268}
269
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000270bool OpenSSLCertificate::ComputeDigest(const std::string& algorithm,
271 unsigned char* digest,
272 size_t size,
273 size_t* length) const {
274 return ComputeDigest(x509_, algorithm, digest, size, length);
275}
276
277bool OpenSSLCertificate::ComputeDigest(const X509* x509,
278 const std::string& algorithm,
279 unsigned char* digest,
280 size_t size,
281 size_t* length) {
282 const EVP_MD *md;
283 unsigned int n;
284
285 if (!OpenSSLDigest::GetDigestEVP(algorithm, &md))
286 return false;
287
288 if (size < static_cast<size_t>(EVP_MD_size(md)))
289 return false;
290
291 X509_digest(x509, md, digest, &n);
292
293 *length = n;
294
295 return true;
296}
297
298OpenSSLCertificate::~OpenSSLCertificate() {
299 X509_free(x509_);
300}
301
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000302OpenSSLCertificate* OpenSSLCertificate::GetReference() const {
303 return new OpenSSLCertificate(x509_);
304}
305
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000306std::string OpenSSLCertificate::ToPEMString() const {
307 BIO* bio = BIO_new(BIO_s_mem());
308 if (!bio) {
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000309 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000310 }
311 if (!PEM_write_bio_X509(bio, x509_)) {
312 BIO_free(bio);
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000313 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000314 }
315 BIO_write(bio, "\0", 1);
316 char* buffer;
317 BIO_get_mem_data(bio, &buffer);
318 std::string ret(buffer);
319 BIO_free(bio);
320 return ret;
321}
322
323void OpenSSLCertificate::ToDER(Buffer* der_buffer) const {
324 // In case of failure, make sure to leave the buffer empty.
Karl Wiberg94784372015-04-20 14:03:07 +0200325 der_buffer->SetSize(0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000326
327 // Calculates the DER representation of the certificate, from scratch.
328 BIO* bio = BIO_new(BIO_s_mem());
329 if (!bio) {
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000330 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000331 }
332 if (!i2d_X509_bio(bio, x509_)) {
333 BIO_free(bio);
andrew@webrtc.orga5b78692014-08-28 16:28:26 +0000334 FATAL() << "unreachable code";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000335 }
336 char* data;
337 size_t length = BIO_get_mem_data(bio, &data);
338 der_buffer->SetData(data, length);
339 BIO_free(bio);
340}
341
342void OpenSSLCertificate::AddReference() const {
343 ASSERT(x509_ != NULL);
344 CRYPTO_add(&x509_->references, 1, CRYPTO_LOCK_X509);
345}
346
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000347OpenSSLIdentity::OpenSSLIdentity(OpenSSLKeyPair* key_pair,
348 OpenSSLCertificate* certificate)
349 : key_pair_(key_pair), certificate_(certificate) {
350 ASSERT(key_pair != NULL);
351 ASSERT(certificate != NULL);
352}
353
354OpenSSLIdentity::~OpenSSLIdentity() = default;
355
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000356OpenSSLIdentity* OpenSSLIdentity::GenerateInternal(
357 const SSLIdentityParams& params) {
358 OpenSSLKeyPair *key_pair = OpenSSLKeyPair::Generate();
359 if (key_pair) {
360 OpenSSLCertificate *certificate = OpenSSLCertificate::Generate(
361 key_pair, params);
362 if (certificate)
363 return new OpenSSLIdentity(key_pair, certificate);
364 delete key_pair;
365 }
366 LOG(LS_INFO) << "Identity generation failed";
367 return NULL;
368}
369
370OpenSSLIdentity* OpenSSLIdentity::Generate(const std::string& common_name) {
371 SSLIdentityParams params;
372 params.common_name = common_name;
373 params.not_before = CERTIFICATE_WINDOW;
374 params.not_after = CERTIFICATE_LIFETIME;
375 return GenerateInternal(params);
376}
377
378OpenSSLIdentity* OpenSSLIdentity::GenerateForTest(
379 const SSLIdentityParams& params) {
380 return GenerateInternal(params);
381}
382
383SSLIdentity* OpenSSLIdentity::FromPEMStrings(
384 const std::string& private_key,
385 const std::string& certificate) {
386 scoped_ptr<OpenSSLCertificate> cert(
387 OpenSSLCertificate::FromPEMString(certificate));
388 if (!cert) {
389 LOG(LS_ERROR) << "Failed to create OpenSSLCertificate from PEM string.";
390 return NULL;
391 }
392
393 BIO* bio = BIO_new_mem_buf(const_cast<char*>(private_key.c_str()), -1);
394 if (!bio) {
395 LOG(LS_ERROR) << "Failed to create a new BIO buffer.";
396 return NULL;
397 }
398 BIO_set_mem_eof_return(bio, 0);
399 EVP_PKEY *pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL,
400 const_cast<char*>("\0"));
401 BIO_free(bio); // Frees the BIO, but not the pointed-to string.
402
403 if (!pkey) {
404 LOG(LS_ERROR) << "Failed to create the private key from PEM string.";
405 return NULL;
406 }
407
408 return new OpenSSLIdentity(new OpenSSLKeyPair(pkey),
409 cert.release());
410}
411
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000412const OpenSSLCertificate& OpenSSLIdentity::certificate() const {
413 return *certificate_;
414}
415
416OpenSSLIdentity* OpenSSLIdentity::GetReference() const {
417 return new OpenSSLIdentity(key_pair_->GetReference(),
418 certificate_->GetReference());
419}
420
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000421bool OpenSSLIdentity::ConfigureIdentity(SSL_CTX* ctx) {
422 // 1 is the documented success return code.
423 if (SSL_CTX_use_certificate(ctx, certificate_->x509()) != 1 ||
424 SSL_CTX_use_PrivateKey(ctx, key_pair_->pkey()) != 1) {
425 LogSSLErrors("Configuring key and certificate");
426 return false;
427 }
428 return true;
429}
430
431} // namespace rtc
432
433#endif // HAVE_OPENSSL_SSL_H