You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

357 lines
11 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  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. #include "rtc_base/openssl_identity.h"
  11. #include <memory>
  12. #include <utility>
  13. #include <vector>
  14. #if defined(WEBRTC_WIN)
  15. // Must be included first before openssl headers.
  16. #include "rtc_base/win32.h" // NOLINT
  17. #endif // WEBRTC_WIN
  18. #include <openssl/bio.h>
  19. #include <openssl/bn.h>
  20. #include <openssl/err.h>
  21. #include <openssl/pem.h>
  22. #include <openssl/rsa.h>
  23. #include <stdint.h>
  24. #include "absl/memory/memory.h"
  25. #include "rtc_base/checks.h"
  26. #include "rtc_base/logging.h"
  27. #include "rtc_base/numerics/safe_conversions.h"
  28. #include "rtc_base/openssl.h"
  29. #include "rtc_base/openssl_utility.h"
  30. namespace rtc {
  31. // We could have exposed a myriad of parameters for the crypto stuff,
  32. // but keeping it simple seems best.
  33. // Generate a key pair. Caller is responsible for freeing the returned object.
  34. static EVP_PKEY* MakeKey(const KeyParams& key_params) {
  35. RTC_LOG(LS_INFO) << "Making key pair";
  36. EVP_PKEY* pkey = EVP_PKEY_new();
  37. if (key_params.type() == KT_RSA) {
  38. int key_length = key_params.rsa_params().mod_size;
  39. BIGNUM* exponent = BN_new();
  40. RSA* rsa = RSA_new();
  41. if (!pkey || !exponent || !rsa ||
  42. !BN_set_word(exponent, key_params.rsa_params().pub_exp) ||
  43. !RSA_generate_key_ex(rsa, key_length, exponent, nullptr) ||
  44. !EVP_PKEY_assign_RSA(pkey, rsa)) {
  45. EVP_PKEY_free(pkey);
  46. BN_free(exponent);
  47. RSA_free(rsa);
  48. RTC_LOG(LS_ERROR) << "Failed to make RSA key pair";
  49. return nullptr;
  50. }
  51. // ownership of rsa struct was assigned, don't free it.
  52. BN_free(exponent);
  53. } else if (key_params.type() == KT_ECDSA) {
  54. if (key_params.ec_curve() == EC_NIST_P256) {
  55. EC_KEY* ec_key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  56. // Ensure curve name is included when EC key is serialized.
  57. // Without this call, OpenSSL versions before 1.1.0 will create
  58. // certificates that don't work for TLS.
  59. // This is a no-op for BoringSSL and OpenSSL 1.1.0+
  60. EC_KEY_set_asn1_flag(ec_key, OPENSSL_EC_NAMED_CURVE);
  61. if (!pkey || !ec_key || !EC_KEY_generate_key(ec_key) ||
  62. !EVP_PKEY_assign_EC_KEY(pkey, ec_key)) {
  63. EVP_PKEY_free(pkey);
  64. EC_KEY_free(ec_key);
  65. RTC_LOG(LS_ERROR) << "Failed to make EC key pair";
  66. return nullptr;
  67. }
  68. // ownership of ec_key struct was assigned, don't free it.
  69. } else {
  70. // Add generation of any other curves here.
  71. EVP_PKEY_free(pkey);
  72. RTC_LOG(LS_ERROR) << "ECDSA key requested for unknown curve";
  73. return nullptr;
  74. }
  75. } else {
  76. EVP_PKEY_free(pkey);
  77. RTC_LOG(LS_ERROR) << "Key type requested not understood";
  78. return nullptr;
  79. }
  80. RTC_LOG(LS_INFO) << "Returning key pair";
  81. return pkey;
  82. }
  83. OpenSSLKeyPair* OpenSSLKeyPair::Generate(const KeyParams& key_params) {
  84. EVP_PKEY* pkey = MakeKey(key_params);
  85. if (!pkey) {
  86. openssl::LogSSLErrors("Generating key pair");
  87. return nullptr;
  88. }
  89. return new OpenSSLKeyPair(pkey);
  90. }
  91. OpenSSLKeyPair* OpenSSLKeyPair::FromPrivateKeyPEMString(
  92. const std::string& pem_string) {
  93. BIO* bio = BIO_new_mem_buf(const_cast<char*>(pem_string.c_str()), -1);
  94. if (!bio) {
  95. RTC_LOG(LS_ERROR) << "Failed to create a new BIO buffer.";
  96. return nullptr;
  97. }
  98. BIO_set_mem_eof_return(bio, 0);
  99. EVP_PKEY* pkey =
  100. PEM_read_bio_PrivateKey(bio, nullptr, nullptr, const_cast<char*>("\0"));
  101. BIO_free(bio); // Frees the BIO, but not the pointed-to string.
  102. if (!pkey) {
  103. RTC_LOG(LS_ERROR) << "Failed to create the private key from PEM string.";
  104. return nullptr;
  105. }
  106. if (EVP_PKEY_missing_parameters(pkey) != 0) {
  107. RTC_LOG(LS_ERROR)
  108. << "The resulting key pair is missing public key parameters.";
  109. EVP_PKEY_free(pkey);
  110. return nullptr;
  111. }
  112. return new OpenSSLKeyPair(pkey);
  113. }
  114. OpenSSLKeyPair::~OpenSSLKeyPair() {
  115. EVP_PKEY_free(pkey_);
  116. }
  117. OpenSSLKeyPair* OpenSSLKeyPair::GetReference() {
  118. AddReference();
  119. return new OpenSSLKeyPair(pkey_);
  120. }
  121. void OpenSSLKeyPair::AddReference() {
  122. EVP_PKEY_up_ref(pkey_);
  123. }
  124. std::string OpenSSLKeyPair::PrivateKeyToPEMString() const {
  125. BIO* temp_memory_bio = BIO_new(BIO_s_mem());
  126. if (!temp_memory_bio) {
  127. RTC_LOG_F(LS_ERROR) << "Failed to allocate temporary memory bio";
  128. RTC_NOTREACHED();
  129. return "";
  130. }
  131. if (!PEM_write_bio_PrivateKey(temp_memory_bio, pkey_, nullptr, nullptr, 0,
  132. nullptr, nullptr)) {
  133. RTC_LOG_F(LS_ERROR) << "Failed to write private key";
  134. BIO_free(temp_memory_bio);
  135. RTC_NOTREACHED();
  136. return "";
  137. }
  138. BIO_write(temp_memory_bio, "\0", 1);
  139. char* buffer;
  140. BIO_get_mem_data(temp_memory_bio, &buffer);
  141. std::string priv_key_str = buffer;
  142. BIO_free(temp_memory_bio);
  143. return priv_key_str;
  144. }
  145. std::string OpenSSLKeyPair::PublicKeyToPEMString() const {
  146. BIO* temp_memory_bio = BIO_new(BIO_s_mem());
  147. if (!temp_memory_bio) {
  148. RTC_LOG_F(LS_ERROR) << "Failed to allocate temporary memory bio";
  149. RTC_NOTREACHED();
  150. return "";
  151. }
  152. if (!PEM_write_bio_PUBKEY(temp_memory_bio, pkey_)) {
  153. RTC_LOG_F(LS_ERROR) << "Failed to write public key";
  154. BIO_free(temp_memory_bio);
  155. RTC_NOTREACHED();
  156. return "";
  157. }
  158. BIO_write(temp_memory_bio, "\0", 1);
  159. char* buffer;
  160. BIO_get_mem_data(temp_memory_bio, &buffer);
  161. std::string pub_key_str = buffer;
  162. BIO_free(temp_memory_bio);
  163. return pub_key_str;
  164. }
  165. bool OpenSSLKeyPair::operator==(const OpenSSLKeyPair& other) const {
  166. return EVP_PKEY_cmp(this->pkey_, other.pkey_) == 1;
  167. }
  168. bool OpenSSLKeyPair::operator!=(const OpenSSLKeyPair& other) const {
  169. return !(*this == other);
  170. }
  171. OpenSSLIdentity::OpenSSLIdentity(
  172. std::unique_ptr<OpenSSLKeyPair> key_pair,
  173. std::unique_ptr<OpenSSLCertificate> certificate)
  174. : key_pair_(std::move(key_pair)) {
  175. RTC_DCHECK(key_pair_ != nullptr);
  176. RTC_DCHECK(certificate != nullptr);
  177. std::vector<std::unique_ptr<SSLCertificate>> certs;
  178. certs.push_back(std::move(certificate));
  179. cert_chain_.reset(new SSLCertChain(std::move(certs)));
  180. }
  181. OpenSSLIdentity::OpenSSLIdentity(std::unique_ptr<OpenSSLKeyPair> key_pair,
  182. std::unique_ptr<SSLCertChain> cert_chain)
  183. : key_pair_(std::move(key_pair)), cert_chain_(std::move(cert_chain)) {
  184. RTC_DCHECK(key_pair_ != nullptr);
  185. RTC_DCHECK(cert_chain_ != nullptr);
  186. }
  187. OpenSSLIdentity::~OpenSSLIdentity() = default;
  188. OpenSSLIdentity* OpenSSLIdentity::GenerateInternal(
  189. const SSLIdentityParams& params) {
  190. std::unique_ptr<OpenSSLKeyPair> key_pair(
  191. OpenSSLKeyPair::Generate(params.key_params));
  192. if (key_pair) {
  193. std::unique_ptr<OpenSSLCertificate> certificate(
  194. OpenSSLCertificate::Generate(key_pair.get(), params));
  195. if (certificate != nullptr)
  196. return new OpenSSLIdentity(std::move(key_pair), std::move(certificate));
  197. }
  198. RTC_LOG(LS_INFO) << "Identity generation failed";
  199. return nullptr;
  200. }
  201. OpenSSLIdentity* OpenSSLIdentity::GenerateWithExpiration(
  202. const std::string& common_name,
  203. const KeyParams& key_params,
  204. time_t certificate_lifetime) {
  205. SSLIdentityParams params;
  206. params.key_params = key_params;
  207. params.common_name = common_name;
  208. time_t now = time(nullptr);
  209. params.not_before = now + kCertificateWindowInSeconds;
  210. params.not_after = now + certificate_lifetime;
  211. if (params.not_before > params.not_after)
  212. return nullptr;
  213. return GenerateInternal(params);
  214. }
  215. OpenSSLIdentity* OpenSSLIdentity::GenerateForTest(
  216. const SSLIdentityParams& params) {
  217. return GenerateInternal(params);
  218. }
  219. SSLIdentity* OpenSSLIdentity::FromPEMStrings(const std::string& private_key,
  220. const std::string& certificate) {
  221. std::unique_ptr<OpenSSLCertificate> cert(
  222. OpenSSLCertificate::FromPEMString(certificate));
  223. if (!cert) {
  224. RTC_LOG(LS_ERROR) << "Failed to create OpenSSLCertificate from PEM string.";
  225. return nullptr;
  226. }
  227. std::unique_ptr<OpenSSLKeyPair> key_pair(
  228. OpenSSLKeyPair::FromPrivateKeyPEMString(private_key));
  229. if (!key_pair) {
  230. RTC_LOG(LS_ERROR) << "Failed to create key pair from PEM string.";
  231. return nullptr;
  232. }
  233. return new OpenSSLIdentity(std::move(key_pair), std::move(cert));
  234. }
  235. SSLIdentity* OpenSSLIdentity::FromPEMChainStrings(
  236. const std::string& private_key,
  237. const std::string& certificate_chain) {
  238. BIO* bio = BIO_new_mem_buf(certificate_chain.data(),
  239. rtc::dchecked_cast<int>(certificate_chain.size()));
  240. if (!bio)
  241. return nullptr;
  242. BIO_set_mem_eof_return(bio, 0);
  243. std::vector<std::unique_ptr<SSLCertificate>> certs;
  244. while (true) {
  245. X509* x509 =
  246. PEM_read_bio_X509(bio, nullptr, nullptr, const_cast<char*>("\0"));
  247. if (x509 == nullptr) {
  248. uint32_t err = ERR_peek_error();
  249. if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
  250. ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
  251. break;
  252. }
  253. RTC_LOG(LS_ERROR) << "Failed to parse certificate from PEM string.";
  254. BIO_free(bio);
  255. return nullptr;
  256. }
  257. certs.emplace_back(new OpenSSLCertificate(x509));
  258. X509_free(x509);
  259. }
  260. BIO_free(bio);
  261. if (certs.empty()) {
  262. RTC_LOG(LS_ERROR) << "Found no certificates in PEM string.";
  263. return nullptr;
  264. }
  265. std::unique_ptr<OpenSSLKeyPair> key_pair(
  266. OpenSSLKeyPair::FromPrivateKeyPEMString(private_key));
  267. if (!key_pair) {
  268. RTC_LOG(LS_ERROR) << "Failed to create key pair from PEM string.";
  269. return nullptr;
  270. }
  271. return new OpenSSLIdentity(std::move(key_pair),
  272. std::make_unique<SSLCertChain>(std::move(certs)));
  273. }
  274. const OpenSSLCertificate& OpenSSLIdentity::certificate() const {
  275. return *static_cast<const OpenSSLCertificate*>(&cert_chain_->Get(0));
  276. }
  277. const SSLCertChain& OpenSSLIdentity::cert_chain() const {
  278. return *cert_chain_.get();
  279. }
  280. OpenSSLIdentity* OpenSSLIdentity::GetReference() const {
  281. return new OpenSSLIdentity(absl::WrapUnique(key_pair_->GetReference()),
  282. cert_chain_->Clone());
  283. }
  284. bool OpenSSLIdentity::ConfigureIdentity(SSL_CTX* ctx) {
  285. // 1 is the documented success return code.
  286. const OpenSSLCertificate* cert = &certificate();
  287. if (SSL_CTX_use_certificate(ctx, cert->x509()) != 1 ||
  288. SSL_CTX_use_PrivateKey(ctx, key_pair_->pkey()) != 1) {
  289. openssl::LogSSLErrors("Configuring key and certificate");
  290. return false;
  291. }
  292. // If a chain is available, use it.
  293. for (size_t i = 1; i < cert_chain_->GetSize(); ++i) {
  294. cert = static_cast<const OpenSSLCertificate*>(&cert_chain_->Get(i));
  295. if (SSL_CTX_add1_chain_cert(ctx, cert->x509()) != 1) {
  296. openssl::LogSSLErrors("Configuring intermediate certificate");
  297. return false;
  298. }
  299. }
  300. return true;
  301. }
  302. std::string OpenSSLIdentity::PrivateKeyToPEMString() const {
  303. return key_pair_->PrivateKeyToPEMString();
  304. }
  305. std::string OpenSSLIdentity::PublicKeyToPEMString() const {
  306. return key_pair_->PublicKeyToPEMString();
  307. }
  308. bool OpenSSLIdentity::operator==(const OpenSSLIdentity& other) const {
  309. return *this->key_pair_ == *other.key_pair_ &&
  310. this->certificate() == other.certificate();
  311. }
  312. bool OpenSSLIdentity::operator!=(const OpenSSLIdentity& other) const {
  313. return !(*this == other);
  314. }
  315. } // namespace rtc