blob: bb651746fa4fc6b89d928ca89e589a6d2193a87d [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "rtc_base/opensslidentity.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000012
jbauch555604a2016-04-26 03:13:22 -070013#include <memory>
Benjamin Wrightd6f86e82018-05-08 13:12:25 -070014#include <utility>
15#include <vector>
jbauch555604a2016-04-26 03:13:22 -070016
Mirko Bonadeie0623852018-02-01 11:17:40 +010017#if defined(WEBRTC_WIN)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000018// Must be included first before openssl headers.
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "rtc_base/win32.h" // NOLINT
Mirko Bonadeie0623852018-02-01 11:17:40 +010020#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000021
22#include <openssl/bio.h>
Jian Cui0a8798b2017-11-16 16:58:02 -080023#include <openssl/bn.h>
24#include <openssl/crypto.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000025#include <openssl/err.h>
26#include <openssl/pem.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000027#include <openssl/rsa.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000028
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "rtc_base/checks.h"
30#include "rtc_base/helpers.h"
31#include "rtc_base/logging.h"
Mirko Bonadeia041f922018-05-23 10:22:36 +020032#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "rtc_base/openssl.h"
34#include "rtc_base/openssldigest.h"
Benjamin Wrightd6f86e82018-05-08 13:12:25 -070035#include "rtc_base/opensslutility.h"
Jian Cui0a8798b2017-11-16 16:58:02 -080036#include "rtc_base/ptr_util.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000037
38namespace rtc {
39
40// We could have exposed a myriad of parameters for the crypto stuff,
41// but keeping it simple seems best.
42
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000043// Generate a key pair. Caller is responsible for freeing the returned object.
torbjorng4e572472015-10-08 09:42:49 -070044static EVP_PKEY* MakeKey(const KeyParams& key_params) {
Mirko Bonadei675513b2017-11-09 11:09:25 +010045 RTC_LOG(LS_INFO) << "Making key pair";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000046 EVP_PKEY* pkey = EVP_PKEY_new();
torbjorng4e572472015-10-08 09:42:49 -070047 if (key_params.type() == KT_RSA) {
48 int key_length = key_params.rsa_params().mod_size;
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020049 BIGNUM* exponent = BN_new();
50 RSA* rsa = RSA_new();
51 if (!pkey || !exponent || !rsa ||
torbjorng4e572472015-10-08 09:42:49 -070052 !BN_set_word(exponent, key_params.rsa_params().pub_exp) ||
deadbeef37f5ecf2017-02-27 14:06:41 -080053 !RSA_generate_key_ex(rsa, key_length, exponent, nullptr) ||
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020054 !EVP_PKEY_assign_RSA(pkey, rsa)) {
55 EVP_PKEY_free(pkey);
56 BN_free(exponent);
57 RSA_free(rsa);
Mirko Bonadei675513b2017-11-09 11:09:25 +010058 RTC_LOG(LS_ERROR) << "Failed to make RSA key pair";
deadbeef37f5ecf2017-02-27 14:06:41 -080059 return nullptr;
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020060 }
61 // ownership of rsa struct was assigned, don't free it.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000062 BN_free(exponent);
torbjorng4e572472015-10-08 09:42:49 -070063 } else if (key_params.type() == KT_ECDSA) {
64 if (key_params.ec_curve() == EC_NIST_P256) {
65 EC_KEY* ec_key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
ssarohabbfed522016-12-11 18:42:07 -080066
67 // Ensure curve name is included when EC key is serialized.
68 // Without this call, OpenSSL versions before 1.1.0 will create
69 // certificates that don't work for TLS.
70 // This is a no-op for BoringSSL and OpenSSL 1.1.0+
71 EC_KEY_set_asn1_flag(ec_key, OPENSSL_EC_NAMED_CURVE);
72
torbjorng4e572472015-10-08 09:42:49 -070073 if (!pkey || !ec_key || !EC_KEY_generate_key(ec_key) ||
74 !EVP_PKEY_assign_EC_KEY(pkey, ec_key)) {
75 EVP_PKEY_free(pkey);
76 EC_KEY_free(ec_key);
Mirko Bonadei675513b2017-11-09 11:09:25 +010077 RTC_LOG(LS_ERROR) << "Failed to make EC key pair";
deadbeef37f5ecf2017-02-27 14:06:41 -080078 return nullptr;
torbjorng4e572472015-10-08 09:42:49 -070079 }
80 // ownership of ec_key struct was assigned, don't free it.
81 } else {
82 // Add generation of any other curves here.
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020083 EVP_PKEY_free(pkey);
Mirko Bonadei675513b2017-11-09 11:09:25 +010084 RTC_LOG(LS_ERROR) << "ECDSA key requested for unknown curve";
deadbeef37f5ecf2017-02-27 14:06:41 -080085 return nullptr;
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020086 }
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020087 } else {
88 EVP_PKEY_free(pkey);
Mirko Bonadei675513b2017-11-09 11:09:25 +010089 RTC_LOG(LS_ERROR) << "Key type requested not understood";
deadbeef37f5ecf2017-02-27 14:06:41 -080090 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000091 }
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020092
Mirko Bonadei675513b2017-11-09 11:09:25 +010093 RTC_LOG(LS_INFO) << "Returning key pair";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000094 return pkey;
95}
96
torbjorng4e572472015-10-08 09:42:49 -070097OpenSSLKeyPair* OpenSSLKeyPair::Generate(const KeyParams& key_params) {
98 EVP_PKEY* pkey = MakeKey(key_params);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000099 if (!pkey) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700100 openssl::LogSSLErrors("Generating key pair");
deadbeef37f5ecf2017-02-27 14:06:41 -0800101 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000102 }
103 return new OpenSSLKeyPair(pkey);
104}
105
hbos6b470a92016-04-28 05:14:21 -0700106OpenSSLKeyPair* OpenSSLKeyPair::FromPrivateKeyPEMString(
107 const std::string& pem_string) {
108 BIO* bio = BIO_new_mem_buf(const_cast<char*>(pem_string.c_str()), -1);
109 if (!bio) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100110 RTC_LOG(LS_ERROR) << "Failed to create a new BIO buffer.";
hbos6b470a92016-04-28 05:14:21 -0700111 return nullptr;
112 }
113 BIO_set_mem_eof_return(bio, 0);
114 EVP_PKEY* pkey =
115 PEM_read_bio_PrivateKey(bio, nullptr, nullptr, const_cast<char*>("\0"));
116 BIO_free(bio); // Frees the BIO, but not the pointed-to string.
117 if (!pkey) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100118 RTC_LOG(LS_ERROR) << "Failed to create the private key from PEM string.";
hbos6b470a92016-04-28 05:14:21 -0700119 return nullptr;
120 }
121 if (EVP_PKEY_missing_parameters(pkey) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100122 RTC_LOG(LS_ERROR)
123 << "The resulting key pair is missing public key parameters.";
hbos6b470a92016-04-28 05:14:21 -0700124 EVP_PKEY_free(pkey);
125 return nullptr;
126 }
127 return new OpenSSLKeyPair(pkey);
128}
129
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000130OpenSSLKeyPair::~OpenSSLKeyPair() {
131 EVP_PKEY_free(pkey_);
132}
133
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000134OpenSSLKeyPair* OpenSSLKeyPair::GetReference() {
135 AddReference();
136 return new OpenSSLKeyPair(pkey_);
137}
138
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000139void OpenSSLKeyPair::AddReference() {
Jiayang Liu770cc382015-05-28 15:36:29 -0700140 EVP_PKEY_up_ref(pkey_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000141}
142
hbos6b470a92016-04-28 05:14:21 -0700143std::string OpenSSLKeyPair::PrivateKeyToPEMString() const {
144 BIO* temp_memory_bio = BIO_new(BIO_s_mem());
145 if (!temp_memory_bio) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100146 RTC_LOG_F(LS_ERROR) << "Failed to allocate temporary memory bio";
hbos6b470a92016-04-28 05:14:21 -0700147 RTC_NOTREACHED();
148 return "";
149 }
Jian Cui0a8798b2017-11-16 16:58:02 -0800150 if (!PEM_write_bio_PrivateKey(temp_memory_bio, pkey_, nullptr, nullptr, 0,
151 nullptr, nullptr)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100152 RTC_LOG_F(LS_ERROR) << "Failed to write private key";
hbos6b470a92016-04-28 05:14:21 -0700153 BIO_free(temp_memory_bio);
154 RTC_NOTREACHED();
155 return "";
156 }
157 BIO_write(temp_memory_bio, "\0", 1);
158 char* buffer;
159 BIO_get_mem_data(temp_memory_bio, &buffer);
160 std::string priv_key_str = buffer;
161 BIO_free(temp_memory_bio);
162 return priv_key_str;
163}
164
165std::string OpenSSLKeyPair::PublicKeyToPEMString() const {
166 BIO* temp_memory_bio = BIO_new(BIO_s_mem());
167 if (!temp_memory_bio) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100168 RTC_LOG_F(LS_ERROR) << "Failed to allocate temporary memory bio";
hbos6b470a92016-04-28 05:14:21 -0700169 RTC_NOTREACHED();
170 return "";
171 }
172 if (!PEM_write_bio_PUBKEY(temp_memory_bio, pkey_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100173 RTC_LOG_F(LS_ERROR) << "Failed to write public key";
hbos6b470a92016-04-28 05:14:21 -0700174 BIO_free(temp_memory_bio);
175 RTC_NOTREACHED();
176 return "";
177 }
178 BIO_write(temp_memory_bio, "\0", 1);
179 char* buffer;
180 BIO_get_mem_data(temp_memory_bio, &buffer);
181 std::string pub_key_str = buffer;
182 BIO_free(temp_memory_bio);
183 return pub_key_str;
184}
185
186bool OpenSSLKeyPair::operator==(const OpenSSLKeyPair& other) const {
187 return EVP_PKEY_cmp(this->pkey_, other.pkey_) == 1;
188}
189
190bool OpenSSLKeyPair::operator!=(const OpenSSLKeyPair& other) const {
191 return !(*this == other);
192}
193
Jian Cui0a8798b2017-11-16 16:58:02 -0800194OpenSSLIdentity::OpenSSLIdentity(
195 std::unique_ptr<OpenSSLKeyPair> key_pair,
196 std::unique_ptr<OpenSSLCertificate> certificate)
197 : key_pair_(std::move(key_pair)) {
198 RTC_DCHECK(key_pair_ != nullptr);
deadbeef37f5ecf2017-02-27 14:06:41 -0800199 RTC_DCHECK(certificate != nullptr);
Jian Cui0a8798b2017-11-16 16:58:02 -0800200 std::vector<std::unique_ptr<SSLCertificate>> certs;
201 certs.push_back(std::move(certificate));
202 cert_chain_.reset(new SSLCertChain(std::move(certs)));
203}
204
205OpenSSLIdentity::OpenSSLIdentity(std::unique_ptr<OpenSSLKeyPair> key_pair,
206 std::unique_ptr<SSLCertChain> cert_chain)
207 : key_pair_(std::move(key_pair)), cert_chain_(std::move(cert_chain)) {
208 RTC_DCHECK(key_pair_ != nullptr);
209 RTC_DCHECK(cert_chain_ != nullptr);
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000210}
211
212OpenSSLIdentity::~OpenSSLIdentity() = default;
213
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000214OpenSSLIdentity* OpenSSLIdentity::GenerateInternal(
215 const SSLIdentityParams& params) {
Jian Cui0a8798b2017-11-16 16:58:02 -0800216 std::unique_ptr<OpenSSLKeyPair> key_pair(
217 OpenSSLKeyPair::Generate(params.key_params));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000218 if (key_pair) {
Jian Cui0a8798b2017-11-16 16:58:02 -0800219 std::unique_ptr<OpenSSLCertificate> certificate(
220 OpenSSLCertificate::Generate(key_pair.get(), params));
221 if (certificate != nullptr)
222 return new OpenSSLIdentity(std::move(key_pair), std::move(certificate));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000223 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100224 RTC_LOG(LS_INFO) << "Identity generation failed";
deadbeef37f5ecf2017-02-27 14:06:41 -0800225 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000226}
227
Torbjorn Granlund1d846b22016-03-31 16:21:04 +0200228OpenSSLIdentity* OpenSSLIdentity::GenerateWithExpiration(
229 const std::string& common_name,
230 const KeyParams& key_params,
231 time_t certificate_lifetime) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000232 SSLIdentityParams params;
torbjorng4e572472015-10-08 09:42:49 -0700233 params.key_params = key_params;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000234 params.common_name = common_name;
deadbeef37f5ecf2017-02-27 14:06:41 -0800235 time_t now = time(nullptr);
Torbjorn Granlund1d846b22016-03-31 16:21:04 +0200236 params.not_before = now + kCertificateWindowInSeconds;
torbjornge8dc0812016-02-15 09:35:54 -0800237 params.not_after = now + certificate_lifetime;
Torbjorn Granlund1d846b22016-03-31 16:21:04 +0200238 if (params.not_before > params.not_after)
239 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000240 return GenerateInternal(params);
241}
242
243OpenSSLIdentity* OpenSSLIdentity::GenerateForTest(
244 const SSLIdentityParams& params) {
245 return GenerateInternal(params);
246}
247
Jian Cui0a8798b2017-11-16 16:58:02 -0800248SSLIdentity* OpenSSLIdentity::FromPEMStrings(const std::string& private_key,
249 const std::string& certificate) {
jbauch555604a2016-04-26 03:13:22 -0700250 std::unique_ptr<OpenSSLCertificate> cert(
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000251 OpenSSLCertificate::FromPEMString(certificate));
252 if (!cert) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100253 RTC_LOG(LS_ERROR) << "Failed to create OpenSSLCertificate from PEM string.";
hbos6b470a92016-04-28 05:14:21 -0700254 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000255 }
256
Jian Cui0a8798b2017-11-16 16:58:02 -0800257 std::unique_ptr<OpenSSLKeyPair> key_pair(
258 OpenSSLKeyPair::FromPrivateKeyPEMString(private_key));
hbos6b470a92016-04-28 05:14:21 -0700259 if (!key_pair) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100260 RTC_LOG(LS_ERROR) << "Failed to create key pair from PEM string.";
hbos6b470a92016-04-28 05:14:21 -0700261 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000262 }
263
Jian Cui0a8798b2017-11-16 16:58:02 -0800264 return new OpenSSLIdentity(std::move(key_pair), std::move(cert));
265}
266
267SSLIdentity* OpenSSLIdentity::FromPEMChainStrings(
268 const std::string& private_key,
269 const std::string& certificate_chain) {
270 BIO* bio =
Mirko Bonadeia041f922018-05-23 10:22:36 +0200271 BIO_new_mem_buf(certificate_chain.data(),
272 rtc::dchecked_cast<int>(certificate_chain.size()));
Jian Cui0a8798b2017-11-16 16:58:02 -0800273 if (!bio)
274 return nullptr;
275 BIO_set_mem_eof_return(bio, 0);
276 std::vector<std::unique_ptr<SSLCertificate>> certs;
277 while (true) {
278 X509* x509 =
279 PEM_read_bio_X509(bio, nullptr, nullptr, const_cast<char*>("\0"));
280 if (x509 == nullptr) {
281 uint32_t err = ERR_peek_error();
282 if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
283 ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
284 break;
285 }
286 RTC_LOG(LS_ERROR) << "Failed to parse certificate from PEM string.";
287 BIO_free(bio);
288 return nullptr;
289 }
290 certs.emplace_back(new OpenSSLCertificate(x509));
291 X509_free(x509);
292 }
293 BIO_free(bio);
294 if (certs.empty()) {
295 RTC_LOG(LS_ERROR) << "Found no certificates in PEM string.";
296 return nullptr;
297 }
298
299 std::unique_ptr<OpenSSLKeyPair> key_pair(
300 OpenSSLKeyPair::FromPrivateKeyPEMString(private_key));
301 if (!key_pair) {
302 RTC_LOG(LS_ERROR) << "Failed to create key pair from PEM string.";
303 return nullptr;
304 }
305
306 return new OpenSSLIdentity(std::move(key_pair),
307 MakeUnique<SSLCertChain>(std::move(certs)));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000308}
309
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000310const OpenSSLCertificate& OpenSSLIdentity::certificate() const {
Jian Cui0a8798b2017-11-16 16:58:02 -0800311 return *static_cast<const OpenSSLCertificate*>(&cert_chain_->Get(0));
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000312}
313
Taylor Brandstetterc3928662018-02-23 13:04:51 -0800314const SSLCertChain& OpenSSLIdentity::cert_chain() const {
315 return *cert_chain_.get();
316}
317
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000318OpenSSLIdentity* OpenSSLIdentity::GetReference() const {
Jian Cui0a8798b2017-11-16 16:58:02 -0800319 return new OpenSSLIdentity(WrapUnique(key_pair_->GetReference()),
David Benjaminea84b6b2017-12-01 17:25:45 -0500320 WrapUnique(cert_chain_->Copy()));
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000321}
322
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000323bool OpenSSLIdentity::ConfigureIdentity(SSL_CTX* ctx) {
324 // 1 is the documented success return code.
Jian Cui0a8798b2017-11-16 16:58:02 -0800325 const OpenSSLCertificate* cert = &certificate();
326 if (SSL_CTX_use_certificate(ctx, cert->x509()) != 1 ||
327 SSL_CTX_use_PrivateKey(ctx, key_pair_->pkey()) != 1) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700328 openssl::LogSSLErrors("Configuring key and certificate");
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000329 return false;
330 }
Jian Cui0a8798b2017-11-16 16:58:02 -0800331 // If a chain is available, use it.
332 for (size_t i = 1; i < cert_chain_->GetSize(); ++i) {
333 cert = static_cast<const OpenSSLCertificate*>(&cert_chain_->Get(i));
334 if (SSL_CTX_add1_chain_cert(ctx, cert->x509()) != 1) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700335 openssl::LogSSLErrors("Configuring intermediate certificate");
Jian Cui0a8798b2017-11-16 16:58:02 -0800336 return false;
337 }
338 }
339
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000340 return true;
341}
342
hbos6b470a92016-04-28 05:14:21 -0700343std::string OpenSSLIdentity::PrivateKeyToPEMString() const {
344 return key_pair_->PrivateKeyToPEMString();
345}
346
347std::string OpenSSLIdentity::PublicKeyToPEMString() const {
348 return key_pair_->PublicKeyToPEMString();
349}
350
351bool OpenSSLIdentity::operator==(const OpenSSLIdentity& other) const {
352 return *this->key_pair_ == *other.key_pair_ &&
Jian Cui0a8798b2017-11-16 16:58:02 -0800353 this->certificate() == other.certificate();
hbos6b470a92016-04-28 05:14:21 -0700354}
355
356bool OpenSSLIdentity::operator!=(const OpenSSLIdentity& other) const {
357 return !(*this == other);
358}
359
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000360} // namespace rtc