1 /*
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
31 namespace 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.
37 static const int KEY_LENGTH = 1024;
38
39 // Random bits for certificate serial number
40 static const int SERIAL_RAND_BITS = 64;
41
42 // Certificate validity lifetime
43 static 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.
46 static const int CERTIFICATE_WINDOW = -60*60*24;
47
48 // Generate a key pair. Caller is responsible for freeing the returned object.
MakeKey()49 static 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.
MakeCertificate(EVP_PKEY * pkey,const SSLIdentityParams & params)72 static 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.
LogSSLErrors(const std::string & prefix)131 static 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
Generate()141 OpenSSLKeyPair* 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
~OpenSSLKeyPair()150 OpenSSLKeyPair::~OpenSSLKeyPair() {
151 EVP_PKEY_free(pkey_);
152 }
153
AddReference()154 void OpenSSLKeyPair::AddReference() {
155 CRYPTO_add(&pkey_->references, 1, CRYPTO_LOCK_EVP_PKEY);
156 }
157
158 #ifdef _DEBUG
159 // Print a certificate to the log, for debugging.
PrintCert(X509 * x509)160 static void PrintCert(X509* x509) {
161 BIO* temp_memory_bio = BIO_new(BIO_s_mem());
162 if (!temp_memory_bio) {
163 LOG_F(LS_ERROR) << "Failed to allocate temporary memory bio";
164 return;
165 }
166 X509_print_ex(temp_memory_bio, x509, XN_FLAG_SEP_CPLUS_SPC, 0);
167 BIO_write(temp_memory_bio, "\0", 1);
168 char* buffer;
169 BIO_get_mem_data(temp_memory_bio, &buffer);
170 LOG(LS_VERBOSE) << buffer;
171 BIO_free(temp_memory_bio);
172 }
173 #endif
174
Generate(OpenSSLKeyPair * key_pair,const SSLIdentityParams & params)175 OpenSSLCertificate* OpenSSLCertificate::Generate(
176 OpenSSLKeyPair* key_pair, const SSLIdentityParams& params) {
177 SSLIdentityParams actual_params(params);
178 if (actual_params.common_name.empty()) {
179 // Use a random string, arbitrarily 8chars long.
180 actual_params.common_name = CreateRandomString(8);
181 }
182 X509* x509 = MakeCertificate(key_pair->pkey(), actual_params);
183 if (!x509) {
184 LogSSLErrors("Generating certificate");
185 return NULL;
186 }
187 #ifdef _DEBUG
188 PrintCert(x509);
189 #endif
190 OpenSSLCertificate* ret = new OpenSSLCertificate(x509);
191 X509_free(x509);
192 return ret;
193 }
194
FromPEMString(const std::string & pem_string)195 OpenSSLCertificate* OpenSSLCertificate::FromPEMString(
196 const std::string& pem_string) {
197 BIO* bio = BIO_new_mem_buf(const_cast<char*>(pem_string.c_str()), -1);
198 if (!bio)
199 return NULL;
200 BIO_set_mem_eof_return(bio, 0);
201 X509 *x509 = PEM_read_bio_X509(bio, NULL, NULL,
202 const_cast<char*>("\0"));
203 BIO_free(bio); // Frees the BIO, but not the pointed-to string.
204
205 if (!x509)
206 return NULL;
207
208 OpenSSLCertificate* ret = new OpenSSLCertificate(x509);
209 X509_free(x509);
210 return ret;
211 }
212
213 // NOTE: This implementation only functions correctly after InitializeSSL
214 // and before CleanupSSL.
GetSignatureDigestAlgorithm(std::string * algorithm) const215 bool OpenSSLCertificate::GetSignatureDigestAlgorithm(
216 std::string* algorithm) const {
217 return OpenSSLDigest::GetDigestName(
218 EVP_get_digestbyobj(x509_->sig_alg->algorithm), algorithm);
219 }
220
ComputeDigest(const std::string & algorithm,unsigned char * digest,size_t size,size_t * length) const221 bool OpenSSLCertificate::ComputeDigest(const std::string& algorithm,
222 unsigned char* digest,
223 size_t size,
224 size_t* length) const {
225 return ComputeDigest(x509_, algorithm, digest, size, length);
226 }
227
ComputeDigest(const X509 * x509,const std::string & algorithm,unsigned char * digest,size_t size,size_t * length)228 bool OpenSSLCertificate::ComputeDigest(const X509* x509,
229 const std::string& algorithm,
230 unsigned char* digest,
231 size_t size,
232 size_t* length) {
233 const EVP_MD *md;
234 unsigned int n;
235
236 if (!OpenSSLDigest::GetDigestEVP(algorithm, &md))
237 return false;
238
239 if (size < static_cast<size_t>(EVP_MD_size(md)))
240 return false;
241
242 X509_digest(x509, md, digest, &n);
243
244 *length = n;
245
246 return true;
247 }
248
~OpenSSLCertificate()249 OpenSSLCertificate::~OpenSSLCertificate() {
250 X509_free(x509_);
251 }
252
ToPEMString() const253 std::string OpenSSLCertificate::ToPEMString() const {
254 BIO* bio = BIO_new(BIO_s_mem());
255 if (!bio) {
256 FATAL() << "unreachable code";
257 }
258 if (!PEM_write_bio_X509(bio, x509_)) {
259 BIO_free(bio);
260 FATAL() << "unreachable code";
261 }
262 BIO_write(bio, "\0", 1);
263 char* buffer;
264 BIO_get_mem_data(bio, &buffer);
265 std::string ret(buffer);
266 BIO_free(bio);
267 return ret;
268 }
269
ToDER(Buffer * der_buffer) const270 void OpenSSLCertificate::ToDER(Buffer* der_buffer) const {
271 // In case of failure, make sure to leave the buffer empty.
272 der_buffer->SetData(NULL, 0);
273
274 // Calculates the DER representation of the certificate, from scratch.
275 BIO* bio = BIO_new(BIO_s_mem());
276 if (!bio) {
277 FATAL() << "unreachable code";
278 }
279 if (!i2d_X509_bio(bio, x509_)) {
280 BIO_free(bio);
281 FATAL() << "unreachable code";
282 }
283 char* data;
284 size_t length = BIO_get_mem_data(bio, &data);
285 der_buffer->SetData(data, length);
286 BIO_free(bio);
287 }
288
AddReference() const289 void OpenSSLCertificate::AddReference() const {
290 ASSERT(x509_ != NULL);
291 CRYPTO_add(&x509_->references, 1, CRYPTO_LOCK_X509);
292 }
293
GenerateInternal(const SSLIdentityParams & params)294 OpenSSLIdentity* OpenSSLIdentity::GenerateInternal(
295 const SSLIdentityParams& params) {
296 OpenSSLKeyPair *key_pair = OpenSSLKeyPair::Generate();
297 if (key_pair) {
298 OpenSSLCertificate *certificate = OpenSSLCertificate::Generate(
299 key_pair, params);
300 if (certificate)
301 return new OpenSSLIdentity(key_pair, certificate);
302 delete key_pair;
303 }
304 LOG(LS_INFO) << "Identity generation failed";
305 return NULL;
306 }
307
Generate(const std::string & common_name)308 OpenSSLIdentity* OpenSSLIdentity::Generate(const std::string& common_name) {
309 SSLIdentityParams params;
310 params.common_name = common_name;
311 params.not_before = CERTIFICATE_WINDOW;
312 params.not_after = CERTIFICATE_LIFETIME;
313 return GenerateInternal(params);
314 }
315
GenerateForTest(const SSLIdentityParams & params)316 OpenSSLIdentity* OpenSSLIdentity::GenerateForTest(
317 const SSLIdentityParams& params) {
318 return GenerateInternal(params);
319 }
320
FromPEMStrings(const std::string & private_key,const std::string & certificate)321 SSLIdentity* OpenSSLIdentity::FromPEMStrings(
322 const std::string& private_key,
323 const std::string& certificate) {
324 scoped_ptr<OpenSSLCertificate> cert(
325 OpenSSLCertificate::FromPEMString(certificate));
326 if (!cert) {
327 LOG(LS_ERROR) << "Failed to create OpenSSLCertificate from PEM string.";
328 return NULL;
329 }
330
331 BIO* bio = BIO_new_mem_buf(const_cast<char*>(private_key.c_str()), -1);
332 if (!bio) {
333 LOG(LS_ERROR) << "Failed to create a new BIO buffer.";
334 return NULL;
335 }
336 BIO_set_mem_eof_return(bio, 0);
337 EVP_PKEY *pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL,
338 const_cast<char*>("\0"));
339 BIO_free(bio); // Frees the BIO, but not the pointed-to string.
340
341 if (!pkey) {
342 LOG(LS_ERROR) << "Failed to create the private key from PEM string.";
343 return NULL;
344 }
345
346 return new OpenSSLIdentity(new OpenSSLKeyPair(pkey),
347 cert.release());
348 }
349
ConfigureIdentity(SSL_CTX * ctx)350 bool OpenSSLIdentity::ConfigureIdentity(SSL_CTX* ctx) {
351 // 1 is the documented success return code.
352 if (SSL_CTX_use_certificate(ctx, certificate_->x509()) != 1 ||
353 SSL_CTX_use_PrivateKey(ctx, key_pair_->pkey()) != 1) {
354 LogSSLErrors("Configuring key and certificate");
355 return false;
356 }
357 return true;
358 }
359
360 } // namespace rtc
361
362 #endif // HAVE_OPENSSL_SSL_H
363