henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame^] | 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. |
| 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. |
| 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. |
| 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 | |
| 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 | |
| 150 | OpenSSLKeyPair::~OpenSSLKeyPair() { |
| 151 | EVP_PKEY_free(pkey_); |
| 152 | } |
| 153 | |
| 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. |
| 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 | |
| 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 | |
| 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. |
| 215 | bool OpenSSLCertificate::GetSignatureDigestAlgorithm( |
| 216 | std::string* algorithm) const { |
| 217 | return OpenSSLDigest::GetDigestName( |
| 218 | EVP_get_digestbyobj(x509_->sig_alg->algorithm), algorithm); |
| 219 | } |
| 220 | |
| 221 | 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 | |
| 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 | |
| 249 | OpenSSLCertificate::~OpenSSLCertificate() { |
| 250 | X509_free(x509_); |
| 251 | } |
| 252 | |
| 253 | std::string OpenSSLCertificate::ToPEMString() const { |
| 254 | BIO* bio = BIO_new(BIO_s_mem()); |
| 255 | if (!bio) { |
| 256 | UNREACHABLE(); |
| 257 | return std::string(); |
| 258 | } |
| 259 | if (!PEM_write_bio_X509(bio, x509_)) { |
| 260 | BIO_free(bio); |
| 261 | UNREACHABLE(); |
| 262 | return std::string(); |
| 263 | } |
| 264 | BIO_write(bio, "\0", 1); |
| 265 | char* buffer; |
| 266 | BIO_get_mem_data(bio, &buffer); |
| 267 | std::string ret(buffer); |
| 268 | BIO_free(bio); |
| 269 | return ret; |
| 270 | } |
| 271 | |
| 272 | void OpenSSLCertificate::ToDER(Buffer* der_buffer) const { |
| 273 | // In case of failure, make sure to leave the buffer empty. |
| 274 | der_buffer->SetData(NULL, 0); |
| 275 | |
| 276 | // Calculates the DER representation of the certificate, from scratch. |
| 277 | BIO* bio = BIO_new(BIO_s_mem()); |
| 278 | if (!bio) { |
| 279 | UNREACHABLE(); |
| 280 | return; |
| 281 | } |
| 282 | if (!i2d_X509_bio(bio, x509_)) { |
| 283 | BIO_free(bio); |
| 284 | UNREACHABLE(); |
| 285 | return; |
| 286 | } |
| 287 | char* data; |
| 288 | size_t length = BIO_get_mem_data(bio, &data); |
| 289 | der_buffer->SetData(data, length); |
| 290 | BIO_free(bio); |
| 291 | } |
| 292 | |
| 293 | void OpenSSLCertificate::AddReference() const { |
| 294 | ASSERT(x509_ != NULL); |
| 295 | CRYPTO_add(&x509_->references, 1, CRYPTO_LOCK_X509); |
| 296 | } |
| 297 | |
| 298 | OpenSSLIdentity* OpenSSLIdentity::GenerateInternal( |
| 299 | const SSLIdentityParams& params) { |
| 300 | OpenSSLKeyPair *key_pair = OpenSSLKeyPair::Generate(); |
| 301 | if (key_pair) { |
| 302 | OpenSSLCertificate *certificate = OpenSSLCertificate::Generate( |
| 303 | key_pair, params); |
| 304 | if (certificate) |
| 305 | return new OpenSSLIdentity(key_pair, certificate); |
| 306 | delete key_pair; |
| 307 | } |
| 308 | LOG(LS_INFO) << "Identity generation failed"; |
| 309 | return NULL; |
| 310 | } |
| 311 | |
| 312 | OpenSSLIdentity* OpenSSLIdentity::Generate(const std::string& common_name) { |
| 313 | SSLIdentityParams params; |
| 314 | params.common_name = common_name; |
| 315 | params.not_before = CERTIFICATE_WINDOW; |
| 316 | params.not_after = CERTIFICATE_LIFETIME; |
| 317 | return GenerateInternal(params); |
| 318 | } |
| 319 | |
| 320 | OpenSSLIdentity* OpenSSLIdentity::GenerateForTest( |
| 321 | const SSLIdentityParams& params) { |
| 322 | return GenerateInternal(params); |
| 323 | } |
| 324 | |
| 325 | SSLIdentity* OpenSSLIdentity::FromPEMStrings( |
| 326 | const std::string& private_key, |
| 327 | const std::string& certificate) { |
| 328 | scoped_ptr<OpenSSLCertificate> cert( |
| 329 | OpenSSLCertificate::FromPEMString(certificate)); |
| 330 | if (!cert) { |
| 331 | LOG(LS_ERROR) << "Failed to create OpenSSLCertificate from PEM string."; |
| 332 | return NULL; |
| 333 | } |
| 334 | |
| 335 | BIO* bio = BIO_new_mem_buf(const_cast<char*>(private_key.c_str()), -1); |
| 336 | if (!bio) { |
| 337 | LOG(LS_ERROR) << "Failed to create a new BIO buffer."; |
| 338 | return NULL; |
| 339 | } |
| 340 | BIO_set_mem_eof_return(bio, 0); |
| 341 | EVP_PKEY *pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, |
| 342 | const_cast<char*>("\0")); |
| 343 | BIO_free(bio); // Frees the BIO, but not the pointed-to string. |
| 344 | |
| 345 | if (!pkey) { |
| 346 | LOG(LS_ERROR) << "Failed to create the private key from PEM string."; |
| 347 | return NULL; |
| 348 | } |
| 349 | |
| 350 | return new OpenSSLIdentity(new OpenSSLKeyPair(pkey), |
| 351 | cert.release()); |
| 352 | } |
| 353 | |
| 354 | bool OpenSSLIdentity::ConfigureIdentity(SSL_CTX* ctx) { |
| 355 | // 1 is the documented success return code. |
| 356 | if (SSL_CTX_use_certificate(ctx, certificate_->x509()) != 1 || |
| 357 | SSL_CTX_use_PrivateKey(ctx, key_pair_->pkey()) != 1) { |
| 358 | LogSSLErrors("Configuring key and certificate"); |
| 359 | return false; |
| 360 | } |
| 361 | return true; |
| 362 | } |
| 363 | |
| 364 | } // namespace rtc |
| 365 | |
| 366 | #endif // HAVE_OPENSSL_SSL_H |