LibsslTLSContext.cc 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2006 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "LibsslTLSContext.h"
  36. #include <cassert>
  37. #include <sstream>
  38. #include <openssl/err.h>
  39. #include <openssl/pkcs12.h>
  40. #include <openssl/bio.h>
  41. #include "LogFactory.h"
  42. #include "Logger.h"
  43. #include "fmt.h"
  44. #include "message.h"
  45. #include "BufferedFile.h"
  46. namespace {
  47. struct bio_deleter {
  48. void operator()(BIO* b)
  49. {
  50. if (b)
  51. BIO_free(b);
  52. }
  53. };
  54. typedef std::unique_ptr<BIO, bio_deleter> bio_t;
  55. struct p12_deleter {
  56. void operator()(PKCS12* p)
  57. {
  58. if (p)
  59. PKCS12_free(p);
  60. }
  61. };
  62. typedef std::unique_ptr<PKCS12, p12_deleter> p12_t;
  63. struct pkey_deleter {
  64. void operator()(EVP_PKEY* x)
  65. {
  66. if (x)
  67. EVP_PKEY_free(x);
  68. }
  69. };
  70. typedef std::unique_ptr<EVP_PKEY, pkey_deleter> pkey_t;
  71. struct x509_deleter {
  72. void operator()(X509* x)
  73. {
  74. if (x)
  75. X509_free(x);
  76. }
  77. };
  78. typedef std::unique_ptr<X509, x509_deleter> x509_t;
  79. struct x509_sk_deleter {
  80. void operator()(STACK_OF(X509) * x)
  81. {
  82. if (x)
  83. sk_X509_pop_free(x, X509_free);
  84. }
  85. };
  86. typedef std::unique_ptr<STACK_OF(X509), x509_sk_deleter> x509_sk_t;
  87. } // namespace
  88. namespace aria2 {
  89. TLSContext* TLSContext::make(TLSSessionSide side, TLSVersion minVer)
  90. {
  91. return new OpenSSLTLSContext(side, minVer);
  92. }
  93. OpenSSLTLSContext::OpenSSLTLSContext(TLSSessionSide side, TLSVersion minVer)
  94. : sslCtx_(nullptr), side_(side), verifyPeer_(true)
  95. {
  96. sslCtx_ = SSL_CTX_new(SSLv23_method());
  97. if (sslCtx_) {
  98. good_ = true;
  99. }
  100. else {
  101. good_ = false;
  102. A2_LOG_ERROR(fmt("SSL_CTX_new() failed. Cause: %s",
  103. ERR_error_string(ERR_get_error(), nullptr)));
  104. return;
  105. }
  106. long ver_opts = 0;
  107. switch (minVer) {
  108. #ifdef TLS1_3_VERSION
  109. case TLS_PROTO_TLS13:
  110. ver_opts |= SSL_OP_NO_TLSv1_2;
  111. // fall through
  112. #endif // TLS1_3_VERSION
  113. case TLS_PROTO_TLS12:
  114. ver_opts |= SSL_OP_NO_TLSv1_1;
  115. // fall through
  116. case TLS_PROTO_TLS11:
  117. ver_opts |= SSL_OP_NO_TLSv1;
  118. ver_opts |= SSL_OP_NO_SSLv3;
  119. break;
  120. default:
  121. assert(0);
  122. abort();
  123. };
  124. // Disable SSLv2 and enable all workarounds for buggy servers
  125. SSL_CTX_set_options(sslCtx_, SSL_OP_ALL | SSL_OP_NO_SSLv2 | ver_opts
  126. #ifdef SSL_OP_SINGLE_ECDH_USE
  127. | SSL_OP_SINGLE_ECDH_USE
  128. #endif // SSL_OP_SINGLE_ECDH_USE
  129. #ifdef SSL_OP_NO_COMPRESSION
  130. | SSL_OP_NO_COMPRESSION
  131. #endif // SSL_OP_NO_COMPRESSION
  132. );
  133. SSL_CTX_set_mode(sslCtx_, SSL_MODE_AUTO_RETRY);
  134. SSL_CTX_set_mode(sslCtx_, SSL_MODE_ENABLE_PARTIAL_WRITE);
  135. #ifdef SSL_MODE_RELEASE_BUFFERS
  136. /* keep memory usage low */
  137. SSL_CTX_set_mode(sslCtx_, SSL_MODE_RELEASE_BUFFERS);
  138. #endif
  139. if (SSL_CTX_set_cipher_list(sslCtx_, "HIGH:!aNULL:!eNULL") == 0) {
  140. good_ = false;
  141. A2_LOG_ERROR(fmt("SSL_CTX_set_cipher_list() failed. Cause: %s",
  142. ERR_error_string(ERR_get_error(), nullptr)));
  143. }
  144. #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
  145. # ifndef OPENSSL_NO_ECDH
  146. auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  147. if (ecdh == nullptr) {
  148. A2_LOG_WARN(fmt("Failed to enable ECDHE cipher suites. Cause: %s",
  149. ERR_error_string(ERR_get_error(), nullptr)));
  150. }
  151. else {
  152. SSL_CTX_set_tmp_ecdh(sslCtx_, ecdh);
  153. EC_KEY_free(ecdh);
  154. }
  155. # endif // OPENSSL_NO_ECDH
  156. #endif // OPENSSL_VERSION_NUMBER >= 0x0090800fL
  157. }
  158. OpenSSLTLSContext::~OpenSSLTLSContext() { SSL_CTX_free(sslCtx_); }
  159. bool OpenSSLTLSContext::good() const { return good_; }
  160. bool OpenSSLTLSContext::addCredentialFile(const std::string& certfile,
  161. const std::string& keyfile)
  162. {
  163. if (keyfile.empty()) {
  164. return addP12CredentialFile(certfile);
  165. }
  166. if (SSL_CTX_use_PrivateKey_file(sslCtx_, keyfile.c_str(), SSL_FILETYPE_PEM) !=
  167. 1) {
  168. A2_LOG_ERROR(fmt("Failed to load private key from %s. Cause: %s",
  169. keyfile.c_str(),
  170. ERR_error_string(ERR_get_error(), nullptr)));
  171. return false;
  172. }
  173. if (SSL_CTX_use_certificate_chain_file(sslCtx_, certfile.c_str()) != 1) {
  174. A2_LOG_ERROR(fmt("Failed to load certificate from %s. Cause: %s",
  175. certfile.c_str(),
  176. ERR_error_string(ERR_get_error(), nullptr)));
  177. return false;
  178. }
  179. A2_LOG_INFO(fmt("Credential files(cert=%s, key=%s) were successfully added.",
  180. certfile.c_str(), keyfile.c_str()));
  181. return true;
  182. }
  183. bool OpenSSLTLSContext::addP12CredentialFile(const std::string& p12file)
  184. {
  185. std::stringstream ss;
  186. BufferedFile(p12file.c_str(), BufferedFile::READ).transfer(ss);
  187. auto data = ss.str();
  188. void* ptr = const_cast<char*>(data.c_str());
  189. size_t len = data.length();
  190. bio_t bio(BIO_new_mem_buf(ptr, len));
  191. if (!bio) {
  192. A2_LOG_ERROR("Failed to open PKCS12 file: no memory.");
  193. return false;
  194. }
  195. p12_t p12(d2i_PKCS12_bio(bio.get(), nullptr));
  196. if (!p12) {
  197. if (side_ == TLS_SERVER) {
  198. A2_LOG_ERROR(fmt("Failed to open PKCS12 file: %s. "
  199. "If you meant to use PEM, you'll also have to specify "
  200. "--rpc-private-key. See the manual.",
  201. ERR_error_string(ERR_get_error(), nullptr)));
  202. }
  203. else {
  204. A2_LOG_ERROR(fmt("Failed to open PKCS12 file: %s. "
  205. "If you meant to use PEM, you'll also have to specify "
  206. "--private-key. See the manual.",
  207. ERR_error_string(ERR_get_error(), nullptr)));
  208. }
  209. return false;
  210. }
  211. EVP_PKEY* pkey;
  212. X509* cert;
  213. STACK_OF(X509)* ca = nullptr;
  214. if (!PKCS12_parse(p12.get(), "", &pkey, &cert, &ca)) {
  215. if (side_ == TLS_SERVER) {
  216. A2_LOG_ERROR(fmt("Failed to parse PKCS12 file: %s. "
  217. "If you meant to use PEM, you'll also have to specify "
  218. "--rpc-private-key. See the manual.",
  219. ERR_error_string(ERR_get_error(), nullptr)));
  220. }
  221. else {
  222. A2_LOG_ERROR(fmt("Failed to parse PKCS12 file: %s. "
  223. "If you meant to use PEM, you'll also have to specify "
  224. "--private-key. See the manual.",
  225. ERR_error_string(ERR_get_error(), nullptr)));
  226. }
  227. return false;
  228. }
  229. pkey_t pkey_holder(pkey);
  230. x509_t cert_holder(cert);
  231. x509_sk_t ca_holder(ca);
  232. if (!pkey || !cert) {
  233. A2_LOG_ERROR(fmt("Failed to use PKCS12 file: no pkey or cert %s",
  234. ERR_error_string(ERR_get_error(), nullptr)));
  235. return false;
  236. }
  237. if (!SSL_CTX_use_PrivateKey(sslCtx_, pkey)) {
  238. A2_LOG_ERROR(fmt("Failed to use PKCS12 file pkey: %s",
  239. ERR_error_string(ERR_get_error(), nullptr)));
  240. return false;
  241. }
  242. if (!SSL_CTX_use_certificate(sslCtx_, cert)) {
  243. A2_LOG_ERROR(fmt("Failed to use PKCS12 file cert: %s",
  244. ERR_error_string(ERR_get_error(), nullptr)));
  245. return false;
  246. }
  247. if (ca && sk_X509_num(ca) && !SSL_CTX_add_extra_chain_cert(sslCtx_, ca)) {
  248. A2_LOG_ERROR(fmt("Failed to use PKCS12 file chain: %s",
  249. ERR_error_string(ERR_get_error(), nullptr)));
  250. return false;
  251. }
  252. A2_LOG_INFO("Using certificate and key from PKCS12 file");
  253. return true;
  254. }
  255. bool OpenSSLTLSContext::addSystemTrustedCACerts()
  256. {
  257. if (SSL_CTX_set_default_verify_paths(sslCtx_) != 1) {
  258. A2_LOG_INFO(fmt(MSG_LOADING_SYSTEM_TRUSTED_CA_CERTS_FAILED,
  259. ERR_error_string(ERR_get_error(), nullptr)));
  260. return false;
  261. }
  262. else {
  263. A2_LOG_INFO("System trusted CA certificates were successfully added.");
  264. return true;
  265. }
  266. }
  267. bool OpenSSLTLSContext::addTrustedCACertFile(const std::string& certfile)
  268. {
  269. if (SSL_CTX_load_verify_locations(sslCtx_, certfile.c_str(), nullptr) != 1) {
  270. A2_LOG_ERROR(fmt(MSG_LOADING_TRUSTED_CA_CERT_FAILED, certfile.c_str(),
  271. ERR_error_string(ERR_get_error(), nullptr)));
  272. return false;
  273. }
  274. else {
  275. A2_LOG_INFO("Trusted CA certificates were successfully added.");
  276. return true;
  277. }
  278. }
  279. } // namespace aria2