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.

954 lines
28 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright 2008 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_adapter.h"
  11. #include <errno.h>
  12. #include <openssl/bio.h>
  13. #include <openssl/err.h>
  14. #include <openssl/rand.h>
  15. #include <openssl/x509.h>
  16. #include <string.h>
  17. #include <time.h>
  18. #include <memory>
  19. #include "rtc_base/checks.h"
  20. #include "rtc_base/location.h"
  21. #include "rtc_base/logging.h"
  22. #include "rtc_base/numerics/safe_conversions.h"
  23. #include "rtc_base/openssl.h"
  24. #include "rtc_base/openssl_certificate.h"
  25. #include "rtc_base/openssl_utility.h"
  26. #include "rtc_base/string_encode.h"
  27. #include "rtc_base/thread.h"
  28. //////////////////////////////////////////////////////////////////////
  29. // SocketBIO
  30. //////////////////////////////////////////////////////////////////////
  31. static int socket_write(BIO* h, const char* buf, int num);
  32. static int socket_read(BIO* h, char* buf, int size);
  33. static int socket_puts(BIO* h, const char* str);
  34. static long socket_ctrl(BIO* h, int cmd, long arg1, void* arg2); // NOLINT
  35. static int socket_new(BIO* h);
  36. static int socket_free(BIO* data);
  37. static BIO_METHOD* BIO_socket_method() {
  38. static BIO_METHOD* methods = [] {
  39. BIO_METHOD* methods = BIO_meth_new(BIO_TYPE_BIO, "socket");
  40. BIO_meth_set_write(methods, socket_write);
  41. BIO_meth_set_read(methods, socket_read);
  42. BIO_meth_set_puts(methods, socket_puts);
  43. BIO_meth_set_ctrl(methods, socket_ctrl);
  44. BIO_meth_set_create(methods, socket_new);
  45. BIO_meth_set_destroy(methods, socket_free);
  46. return methods;
  47. }();
  48. return methods;
  49. }
  50. static BIO* BIO_new_socket(rtc::AsyncSocket* socket) {
  51. BIO* ret = BIO_new(BIO_socket_method());
  52. if (ret == nullptr) {
  53. return nullptr;
  54. }
  55. BIO_set_data(ret, socket);
  56. return ret;
  57. }
  58. static int socket_new(BIO* b) {
  59. BIO_set_shutdown(b, 0);
  60. BIO_set_init(b, 1);
  61. BIO_set_data(b, 0);
  62. return 1;
  63. }
  64. static int socket_free(BIO* b) {
  65. if (b == nullptr)
  66. return 0;
  67. return 1;
  68. }
  69. static int socket_read(BIO* b, char* out, int outl) {
  70. if (!out)
  71. return -1;
  72. rtc::AsyncSocket* socket = static_cast<rtc::AsyncSocket*>(BIO_get_data(b));
  73. BIO_clear_retry_flags(b);
  74. int result = socket->Recv(out, outl, nullptr);
  75. if (result > 0) {
  76. return result;
  77. } else if (socket->IsBlocking()) {
  78. BIO_set_retry_read(b);
  79. }
  80. return -1;
  81. }
  82. static int socket_write(BIO* b, const char* in, int inl) {
  83. if (!in)
  84. return -1;
  85. rtc::AsyncSocket* socket = static_cast<rtc::AsyncSocket*>(BIO_get_data(b));
  86. BIO_clear_retry_flags(b);
  87. int result = socket->Send(in, inl);
  88. if (result > 0) {
  89. return result;
  90. } else if (socket->IsBlocking()) {
  91. BIO_set_retry_write(b);
  92. }
  93. return -1;
  94. }
  95. static int socket_puts(BIO* b, const char* str) {
  96. return socket_write(b, str, rtc::checked_cast<int>(strlen(str)));
  97. }
  98. static long socket_ctrl(BIO* b, int cmd, long num, void* ptr) { // NOLINT
  99. switch (cmd) {
  100. case BIO_CTRL_RESET:
  101. return 0;
  102. case BIO_CTRL_EOF: {
  103. rtc::AsyncSocket* socket = static_cast<rtc::AsyncSocket*>(ptr);
  104. // 1 means socket closed.
  105. return (socket->GetState() == rtc::AsyncSocket::CS_CLOSED) ? 1 : 0;
  106. }
  107. case BIO_CTRL_WPENDING:
  108. case BIO_CTRL_PENDING:
  109. return 0;
  110. case BIO_CTRL_FLUSH:
  111. return 1;
  112. default:
  113. return 0;
  114. }
  115. }
  116. static void LogSslError() {
  117. // Walk down the error stack to find the SSL error.
  118. uint32_t error_code;
  119. const char* file;
  120. int line;
  121. do {
  122. error_code = ERR_get_error_line(&file, &line);
  123. if (ERR_GET_LIB(error_code) == ERR_LIB_SSL) {
  124. RTC_LOG(LS_ERROR) << "ERR_LIB_SSL: " << error_code << ", " << file << ":"
  125. << line;
  126. break;
  127. }
  128. } while (error_code != 0);
  129. }
  130. /////////////////////////////////////////////////////////////////////////////
  131. // OpenSSLAdapter
  132. /////////////////////////////////////////////////////////////////////////////
  133. namespace rtc {
  134. bool OpenSSLAdapter::InitializeSSL() {
  135. if (!SSL_library_init())
  136. return false;
  137. #if !defined(ADDRESS_SANITIZER) || !defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
  138. // Loading the error strings crashes mac_asan. Omit this debugging aid there.
  139. SSL_load_error_strings();
  140. #endif
  141. ERR_load_BIO_strings();
  142. OpenSSL_add_all_algorithms();
  143. RAND_poll();
  144. return true;
  145. }
  146. bool OpenSSLAdapter::CleanupSSL() {
  147. return true;
  148. }
  149. OpenSSLAdapter::OpenSSLAdapter(AsyncSocket* socket,
  150. OpenSSLSessionCache* ssl_session_cache,
  151. SSLCertificateVerifier* ssl_cert_verifier)
  152. : SSLAdapter(socket),
  153. ssl_session_cache_(ssl_session_cache),
  154. ssl_cert_verifier_(ssl_cert_verifier),
  155. state_(SSL_NONE),
  156. role_(SSL_CLIENT),
  157. ssl_read_needs_write_(false),
  158. ssl_write_needs_read_(false),
  159. restartable_(false),
  160. ssl_(nullptr),
  161. ssl_ctx_(nullptr),
  162. ssl_mode_(SSL_MODE_TLS),
  163. ignore_bad_cert_(false),
  164. custom_cert_verifier_status_(false) {
  165. // If a factory is used, take a reference on the factory's SSL_CTX.
  166. // Otherwise, we'll create our own later.
  167. // Either way, we'll release our reference via SSL_CTX_free() in Cleanup().
  168. if (ssl_session_cache_ != nullptr) {
  169. ssl_ctx_ = ssl_session_cache_->GetSSLContext();
  170. RTC_DCHECK(ssl_ctx_);
  171. // Note: if using OpenSSL, requires version 1.1.0 or later.
  172. SSL_CTX_up_ref(ssl_ctx_);
  173. }
  174. }
  175. OpenSSLAdapter::~OpenSSLAdapter() {
  176. Cleanup();
  177. }
  178. void OpenSSLAdapter::SetIgnoreBadCert(bool ignore) {
  179. ignore_bad_cert_ = ignore;
  180. }
  181. void OpenSSLAdapter::SetAlpnProtocols(const std::vector<std::string>& protos) {
  182. alpn_protocols_ = protos;
  183. }
  184. void OpenSSLAdapter::SetEllipticCurves(const std::vector<std::string>& curves) {
  185. elliptic_curves_ = curves;
  186. }
  187. void OpenSSLAdapter::SetMode(SSLMode mode) {
  188. RTC_DCHECK(!ssl_ctx_);
  189. RTC_DCHECK(state_ == SSL_NONE);
  190. ssl_mode_ = mode;
  191. }
  192. void OpenSSLAdapter::SetCertVerifier(
  193. SSLCertificateVerifier* ssl_cert_verifier) {
  194. RTC_DCHECK(!ssl_ctx_);
  195. ssl_cert_verifier_ = ssl_cert_verifier;
  196. }
  197. void OpenSSLAdapter::SetIdentity(SSLIdentity* identity) {
  198. RTC_DCHECK(!identity_);
  199. identity_.reset(static_cast<OpenSSLIdentity*>(identity));
  200. }
  201. void OpenSSLAdapter::SetRole(SSLRole role) {
  202. role_ = role;
  203. }
  204. AsyncSocket* OpenSSLAdapter::Accept(SocketAddress* paddr) {
  205. RTC_DCHECK(role_ == SSL_SERVER);
  206. AsyncSocket* socket = SSLAdapter::Accept(paddr);
  207. if (!socket) {
  208. return nullptr;
  209. }
  210. SSLAdapter* adapter = SSLAdapter::Create(socket);
  211. adapter->SetIdentity(identity_->GetReference());
  212. adapter->SetRole(rtc::SSL_SERVER);
  213. adapter->SetIgnoreBadCert(ignore_bad_cert_);
  214. adapter->StartSSL("", false);
  215. return adapter;
  216. }
  217. int OpenSSLAdapter::StartSSL(const char* hostname, bool restartable) {
  218. if (state_ != SSL_NONE)
  219. return -1;
  220. ssl_host_name_ = hostname;
  221. restartable_ = restartable;
  222. if (socket_->GetState() != Socket::CS_CONNECTED) {
  223. state_ = SSL_WAIT;
  224. return 0;
  225. }
  226. state_ = SSL_CONNECTING;
  227. if (int err = BeginSSL()) {
  228. Error("BeginSSL", err, false);
  229. return err;
  230. }
  231. return 0;
  232. }
  233. int OpenSSLAdapter::BeginSSL() {
  234. RTC_LOG(LS_INFO) << "OpenSSLAdapter::BeginSSL: " << ssl_host_name_;
  235. RTC_DCHECK(state_ == SSL_CONNECTING);
  236. int err = 0;
  237. BIO* bio = nullptr;
  238. // First set up the context. We should either have a factory, with its own
  239. // pre-existing context, or be running standalone, in which case we will
  240. // need to create one, and specify |false| to disable session caching.
  241. if (ssl_session_cache_ == nullptr) {
  242. RTC_DCHECK(!ssl_ctx_);
  243. ssl_ctx_ = CreateContext(ssl_mode_, false);
  244. }
  245. if (!ssl_ctx_) {
  246. err = -1;
  247. goto ssl_error;
  248. }
  249. if (identity_ && !identity_->ConfigureIdentity(ssl_ctx_)) {
  250. SSL_CTX_free(ssl_ctx_);
  251. err = -1;
  252. goto ssl_error;
  253. }
  254. bio = BIO_new_socket(socket_);
  255. if (!bio) {
  256. err = -1;
  257. goto ssl_error;
  258. }
  259. ssl_ = SSL_new(ssl_ctx_);
  260. if (!ssl_) {
  261. err = -1;
  262. goto ssl_error;
  263. }
  264. SSL_set_app_data(ssl_, this);
  265. // SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER allows different buffers to be passed
  266. // into SSL_write when a record could only be partially transmitted (and thus
  267. // requires another call to SSL_write to finish transmission). This allows us
  268. // to copy the data into our own buffer when this occurs, since the original
  269. // buffer can't safely be accessed after control exits Send.
  270. // TODO(deadbeef): Do we want SSL_MODE_ENABLE_PARTIAL_WRITE? It doesn't
  271. // appear Send handles partial writes properly, though maybe we never notice
  272. // since we never send more than 16KB at once..
  273. SSL_set_mode(ssl_, SSL_MODE_ENABLE_PARTIAL_WRITE |
  274. SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  275. // Enable SNI, if a hostname is supplied.
  276. if (!ssl_host_name_.empty()) {
  277. SSL_set_tlsext_host_name(ssl_, ssl_host_name_.c_str());
  278. // Enable session caching, if configured and a hostname is supplied.
  279. if (ssl_session_cache_ != nullptr) {
  280. SSL_SESSION* cached = ssl_session_cache_->LookupSession(ssl_host_name_);
  281. if (cached) {
  282. if (SSL_set_session(ssl_, cached) == 0) {
  283. RTC_LOG(LS_WARNING) << "Failed to apply SSL session from cache";
  284. err = -1;
  285. goto ssl_error;
  286. }
  287. RTC_LOG(LS_INFO) << "Attempting to resume SSL session to "
  288. << ssl_host_name_;
  289. }
  290. }
  291. }
  292. #ifdef OPENSSL_IS_BORINGSSL
  293. // Set a couple common TLS extensions; even though we don't use them yet.
  294. SSL_enable_ocsp_stapling(ssl_);
  295. SSL_enable_signed_cert_timestamps(ssl_);
  296. #endif
  297. if (!alpn_protocols_.empty()) {
  298. std::string tls_alpn_string = TransformAlpnProtocols(alpn_protocols_);
  299. if (!tls_alpn_string.empty()) {
  300. SSL_set_alpn_protos(
  301. ssl_, reinterpret_cast<const unsigned char*>(tls_alpn_string.data()),
  302. rtc::dchecked_cast<unsigned>(tls_alpn_string.size()));
  303. }
  304. }
  305. if (!elliptic_curves_.empty()) {
  306. SSL_set1_curves_list(ssl_, rtc::join(elliptic_curves_, ':').c_str());
  307. }
  308. // Now that the initial config is done, transfer ownership of |bio| to the
  309. // SSL object. If ContinueSSL() fails, the bio will be freed in Cleanup().
  310. SSL_set_bio(ssl_, bio, bio);
  311. bio = nullptr;
  312. // Do the connect.
  313. err = ContinueSSL();
  314. if (err != 0) {
  315. goto ssl_error;
  316. }
  317. return err;
  318. ssl_error:
  319. Cleanup();
  320. if (bio) {
  321. BIO_free(bio);
  322. }
  323. return err;
  324. }
  325. int OpenSSLAdapter::ContinueSSL() {
  326. RTC_DCHECK(state_ == SSL_CONNECTING);
  327. // Clear the DTLS timer
  328. Thread::Current()->Clear(this, MSG_TIMEOUT);
  329. int code = (role_ == SSL_CLIENT) ? SSL_connect(ssl_) : SSL_accept(ssl_);
  330. switch (SSL_get_error(ssl_, code)) {
  331. case SSL_ERROR_NONE:
  332. if (!SSLPostConnectionCheck(ssl_, ssl_host_name_)) {
  333. RTC_LOG(LS_ERROR) << "TLS post connection check failed";
  334. // make sure we close the socket
  335. Cleanup();
  336. // The connect failed so return -1 to shut down the socket
  337. return -1;
  338. }
  339. state_ = SSL_CONNECTED;
  340. AsyncSocketAdapter::OnConnectEvent(this);
  341. // TODO(benwright): Refactor this code path.
  342. // Don't let ourselves go away during the callbacks
  343. // PRefPtr<OpenSSLAdapter> lock(this);
  344. // RTC_LOG(LS_INFO) << " -- onStreamReadable";
  345. // AsyncSocketAdapter::OnReadEvent(this);
  346. // RTC_LOG(LS_INFO) << " -- onStreamWriteable";
  347. // AsyncSocketAdapter::OnWriteEvent(this);
  348. break;
  349. case SSL_ERROR_WANT_READ:
  350. RTC_LOG(LS_VERBOSE) << " -- error want read";
  351. struct timeval timeout;
  352. if (DTLSv1_get_timeout(ssl_, &timeout)) {
  353. int delay = timeout.tv_sec * 1000 + timeout.tv_usec / 1000;
  354. Thread::Current()->PostDelayed(RTC_FROM_HERE, delay, this, MSG_TIMEOUT,
  355. 0);
  356. }
  357. break;
  358. case SSL_ERROR_WANT_WRITE:
  359. break;
  360. case SSL_ERROR_ZERO_RETURN:
  361. default:
  362. RTC_LOG(LS_WARNING) << "ContinueSSL -- error " << code;
  363. return (code != 0) ? code : -1;
  364. }
  365. return 0;
  366. }
  367. void OpenSSLAdapter::Error(const char* context, int err, bool signal) {
  368. RTC_LOG(LS_WARNING) << "OpenSSLAdapter::Error(" << context << ", " << err
  369. << ")";
  370. state_ = SSL_ERROR;
  371. SetError(err);
  372. if (signal) {
  373. AsyncSocketAdapter::OnCloseEvent(this, err);
  374. }
  375. }
  376. void OpenSSLAdapter::Cleanup() {
  377. RTC_LOG(LS_INFO) << "OpenSSLAdapter::Cleanup";
  378. state_ = SSL_NONE;
  379. ssl_read_needs_write_ = false;
  380. ssl_write_needs_read_ = false;
  381. custom_cert_verifier_status_ = false;
  382. pending_data_.Clear();
  383. if (ssl_) {
  384. SSL_free(ssl_);
  385. ssl_ = nullptr;
  386. }
  387. if (ssl_ctx_) {
  388. SSL_CTX_free(ssl_ctx_);
  389. ssl_ctx_ = nullptr;
  390. }
  391. identity_.reset();
  392. // Clear the DTLS timer
  393. Thread::Current()->Clear(this, MSG_TIMEOUT);
  394. }
  395. int OpenSSLAdapter::DoSslWrite(const void* pv, size_t cb, int* error) {
  396. // If we have pending data (that was previously only partially written by
  397. // SSL_write), we shouldn't be attempting to write anything else.
  398. RTC_DCHECK(pending_data_.empty() || pv == pending_data_.data());
  399. RTC_DCHECK(error != nullptr);
  400. ssl_write_needs_read_ = false;
  401. int ret = SSL_write(ssl_, pv, checked_cast<int>(cb));
  402. *error = SSL_get_error(ssl_, ret);
  403. switch (*error) {
  404. case SSL_ERROR_NONE:
  405. // Success!
  406. return ret;
  407. case SSL_ERROR_WANT_READ:
  408. RTC_LOG(LS_INFO) << " -- error want read";
  409. ssl_write_needs_read_ = true;
  410. SetError(EWOULDBLOCK);
  411. break;
  412. case SSL_ERROR_WANT_WRITE:
  413. RTC_LOG(LS_INFO) << " -- error want write";
  414. SetError(EWOULDBLOCK);
  415. break;
  416. case SSL_ERROR_ZERO_RETURN:
  417. SetError(EWOULDBLOCK);
  418. // do we need to signal closure?
  419. break;
  420. case SSL_ERROR_SSL:
  421. LogSslError();
  422. Error("SSL_write", ret ? ret : -1, false);
  423. break;
  424. default:
  425. Error("SSL_write", ret ? ret : -1, false);
  426. break;
  427. }
  428. return SOCKET_ERROR;
  429. }
  430. ///////////////////////////////////////////////////////////////////////////////
  431. // AsyncSocket Implementation
  432. ///////////////////////////////////////////////////////////////////////////////
  433. int OpenSSLAdapter::Send(const void* pv, size_t cb) {
  434. switch (state_) {
  435. case SSL_NONE:
  436. return AsyncSocketAdapter::Send(pv, cb);
  437. case SSL_WAIT:
  438. case SSL_CONNECTING:
  439. SetError(ENOTCONN);
  440. return SOCKET_ERROR;
  441. case SSL_CONNECTED:
  442. break;
  443. case SSL_ERROR:
  444. default:
  445. return SOCKET_ERROR;
  446. }
  447. int ret;
  448. int error;
  449. if (!pending_data_.empty()) {
  450. ret = DoSslWrite(pending_data_.data(), pending_data_.size(), &error);
  451. if (ret != static_cast<int>(pending_data_.size())) {
  452. // We couldn't finish sending the pending data, so we definitely can't
  453. // send any more data. Return with an EWOULDBLOCK error.
  454. SetError(EWOULDBLOCK);
  455. return SOCKET_ERROR;
  456. }
  457. // We completed sending the data previously passed into SSL_write! Now
  458. // we're allowed to send more data.
  459. pending_data_.Clear();
  460. }
  461. // OpenSSL will return an error if we try to write zero bytes
  462. if (cb == 0) {
  463. return 0;
  464. }
  465. ret = DoSslWrite(pv, cb, &error);
  466. // If SSL_write fails with SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE, this
  467. // means the underlying socket is blocked on reading or (more typically)
  468. // writing. When this happens, OpenSSL requires that the next call to
  469. // SSL_write uses the same arguments (though, with
  470. // SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER, the actual buffer pointer may be
  471. // different).
  472. //
  473. // However, after Send exits, we will have lost access to data the user of
  474. // this class is trying to send, and there's no guarantee that the user of
  475. // this class will call Send with the same arguements when it fails. So, we
  476. // buffer the data ourselves. When we know the underlying socket is writable
  477. // again from OnWriteEvent (or if Send is called again before that happens),
  478. // we'll retry sending this buffered data.
  479. if (error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE) {
  480. // Shouldn't be able to get to this point if we already have pending data.
  481. RTC_DCHECK(pending_data_.empty());
  482. RTC_LOG(LS_WARNING)
  483. << "SSL_write couldn't write to the underlying socket; buffering data.";
  484. pending_data_.SetData(static_cast<const uint8_t*>(pv), cb);
  485. // Since we're taking responsibility for sending this data, return its full
  486. // size. The user of this class can consider it sent.
  487. return rtc::dchecked_cast<int>(cb);
  488. }
  489. return ret;
  490. }
  491. int OpenSSLAdapter::SendTo(const void* pv,
  492. size_t cb,
  493. const SocketAddress& addr) {
  494. if (socket_->GetState() == Socket::CS_CONNECTED &&
  495. addr == socket_->GetRemoteAddress()) {
  496. return Send(pv, cb);
  497. }
  498. SetError(ENOTCONN);
  499. return SOCKET_ERROR;
  500. }
  501. int OpenSSLAdapter::Recv(void* pv, size_t cb, int64_t* timestamp) {
  502. switch (state_) {
  503. case SSL_NONE:
  504. return AsyncSocketAdapter::Recv(pv, cb, timestamp);
  505. case SSL_WAIT:
  506. case SSL_CONNECTING:
  507. SetError(ENOTCONN);
  508. return SOCKET_ERROR;
  509. case SSL_CONNECTED:
  510. break;
  511. case SSL_ERROR:
  512. default:
  513. return SOCKET_ERROR;
  514. }
  515. // Don't trust OpenSSL with zero byte reads
  516. if (cb == 0) {
  517. return 0;
  518. }
  519. ssl_read_needs_write_ = false;
  520. int code = SSL_read(ssl_, pv, checked_cast<int>(cb));
  521. int error = SSL_get_error(ssl_, code);
  522. switch (error) {
  523. case SSL_ERROR_NONE:
  524. return code;
  525. case SSL_ERROR_WANT_READ:
  526. SetError(EWOULDBLOCK);
  527. break;
  528. case SSL_ERROR_WANT_WRITE:
  529. ssl_read_needs_write_ = true;
  530. SetError(EWOULDBLOCK);
  531. break;
  532. case SSL_ERROR_ZERO_RETURN:
  533. SetError(EWOULDBLOCK);
  534. // do we need to signal closure?
  535. break;
  536. case SSL_ERROR_SSL:
  537. LogSslError();
  538. Error("SSL_read", (code ? code : -1), false);
  539. break;
  540. default:
  541. Error("SSL_read", (code ? code : -1), false);
  542. break;
  543. }
  544. return SOCKET_ERROR;
  545. }
  546. int OpenSSLAdapter::RecvFrom(void* pv,
  547. size_t cb,
  548. SocketAddress* paddr,
  549. int64_t* timestamp) {
  550. if (socket_->GetState() == Socket::CS_CONNECTED) {
  551. int ret = Recv(pv, cb, timestamp);
  552. *paddr = GetRemoteAddress();
  553. return ret;
  554. }
  555. SetError(ENOTCONN);
  556. return SOCKET_ERROR;
  557. }
  558. int OpenSSLAdapter::Close() {
  559. Cleanup();
  560. state_ = restartable_ ? SSL_WAIT : SSL_NONE;
  561. return AsyncSocketAdapter::Close();
  562. }
  563. Socket::ConnState OpenSSLAdapter::GetState() const {
  564. ConnState state = socket_->GetState();
  565. if ((state == CS_CONNECTED) &&
  566. ((state_ == SSL_WAIT) || (state_ == SSL_CONNECTING))) {
  567. state = CS_CONNECTING;
  568. }
  569. return state;
  570. }
  571. bool OpenSSLAdapter::IsResumedSession() {
  572. return (ssl_ && SSL_session_reused(ssl_) == 1);
  573. }
  574. void OpenSSLAdapter::OnMessage(Message* msg) {
  575. if (MSG_TIMEOUT == msg->message_id) {
  576. RTC_LOG(LS_INFO) << "DTLS timeout expired";
  577. DTLSv1_handle_timeout(ssl_);
  578. ContinueSSL();
  579. }
  580. }
  581. void OpenSSLAdapter::OnConnectEvent(AsyncSocket* socket) {
  582. RTC_LOG(LS_INFO) << "OpenSSLAdapter::OnConnectEvent";
  583. if (state_ != SSL_WAIT) {
  584. RTC_DCHECK(state_ == SSL_NONE);
  585. AsyncSocketAdapter::OnConnectEvent(socket);
  586. return;
  587. }
  588. state_ = SSL_CONNECTING;
  589. if (int err = BeginSSL()) {
  590. AsyncSocketAdapter::OnCloseEvent(socket, err);
  591. }
  592. }
  593. void OpenSSLAdapter::OnReadEvent(AsyncSocket* socket) {
  594. if (state_ == SSL_NONE) {
  595. AsyncSocketAdapter::OnReadEvent(socket);
  596. return;
  597. }
  598. if (state_ == SSL_CONNECTING) {
  599. if (int err = ContinueSSL()) {
  600. Error("ContinueSSL", err);
  601. }
  602. return;
  603. }
  604. if (state_ != SSL_CONNECTED) {
  605. return;
  606. }
  607. // Don't let ourselves go away during the callbacks
  608. // PRefPtr<OpenSSLAdapter> lock(this); // TODO(benwright): fix this
  609. if (ssl_write_needs_read_) {
  610. AsyncSocketAdapter::OnWriteEvent(socket);
  611. }
  612. AsyncSocketAdapter::OnReadEvent(socket);
  613. }
  614. void OpenSSLAdapter::OnWriteEvent(AsyncSocket* socket) {
  615. if (state_ == SSL_NONE) {
  616. AsyncSocketAdapter::OnWriteEvent(socket);
  617. return;
  618. }
  619. if (state_ == SSL_CONNECTING) {
  620. if (int err = ContinueSSL()) {
  621. Error("ContinueSSL", err);
  622. }
  623. return;
  624. }
  625. if (state_ != SSL_CONNECTED) {
  626. return;
  627. }
  628. // Don't let ourselves go away during the callbacks
  629. // PRefPtr<OpenSSLAdapter> lock(this); // TODO(benwright): fix this
  630. if (ssl_read_needs_write_) {
  631. AsyncSocketAdapter::OnReadEvent(socket);
  632. }
  633. // If a previous SSL_write failed due to the underlying socket being blocked,
  634. // this will attempt finishing the write operation.
  635. if (!pending_data_.empty()) {
  636. int error;
  637. if (DoSslWrite(pending_data_.data(), pending_data_.size(), &error) ==
  638. static_cast<int>(pending_data_.size())) {
  639. pending_data_.Clear();
  640. }
  641. }
  642. AsyncSocketAdapter::OnWriteEvent(socket);
  643. }
  644. void OpenSSLAdapter::OnCloseEvent(AsyncSocket* socket, int err) {
  645. RTC_LOG(LS_INFO) << "OpenSSLAdapter::OnCloseEvent(" << err << ")";
  646. AsyncSocketAdapter::OnCloseEvent(socket, err);
  647. }
  648. bool OpenSSLAdapter::SSLPostConnectionCheck(SSL* ssl, const std::string& host) {
  649. bool is_valid_cert_name =
  650. openssl::VerifyPeerCertMatchesHost(ssl, host) &&
  651. (SSL_get_verify_result(ssl) == X509_V_OK || custom_cert_verifier_status_);
  652. if (!is_valid_cert_name && ignore_bad_cert_) {
  653. RTC_DLOG(LS_WARNING) << "Other TLS post connection checks failed. "
  654. "ignore_bad_cert_ set to true. Overriding name "
  655. "verification failure!";
  656. is_valid_cert_name = true;
  657. }
  658. return is_valid_cert_name;
  659. }
  660. #if !defined(NDEBUG)
  661. // We only use this for tracing and so it is only needed in debug mode
  662. void OpenSSLAdapter::SSLInfoCallback(const SSL* s, int where, int ret) {
  663. const char* str = "undefined";
  664. int w = where & ~SSL_ST_MASK;
  665. if (w & SSL_ST_CONNECT) {
  666. str = "SSL_connect";
  667. } else if (w & SSL_ST_ACCEPT) {
  668. str = "SSL_accept";
  669. }
  670. if (where & SSL_CB_LOOP) {
  671. RTC_DLOG(LS_INFO) << str << ":" << SSL_state_string_long(s);
  672. } else if (where & SSL_CB_ALERT) {
  673. str = (where & SSL_CB_READ) ? "read" : "write";
  674. RTC_DLOG(LS_INFO) << "SSL3 alert " << str << ":"
  675. << SSL_alert_type_string_long(ret) << ":"
  676. << SSL_alert_desc_string_long(ret);
  677. } else if (where & SSL_CB_EXIT) {
  678. if (ret == 0) {
  679. RTC_DLOG(LS_INFO) << str << ":failed in " << SSL_state_string_long(s);
  680. } else if (ret < 0) {
  681. RTC_DLOG(LS_INFO) << str << ":error in " << SSL_state_string_long(s);
  682. }
  683. }
  684. }
  685. #endif
  686. int OpenSSLAdapter::SSLVerifyCallback(int ok, X509_STORE_CTX* store) {
  687. #if !defined(NDEBUG)
  688. if (!ok) {
  689. char data[256];
  690. X509* cert = X509_STORE_CTX_get_current_cert(store);
  691. int depth = X509_STORE_CTX_get_error_depth(store);
  692. int err = X509_STORE_CTX_get_error(store);
  693. RTC_DLOG(LS_INFO) << "Error with certificate at depth: " << depth;
  694. X509_NAME_oneline(X509_get_issuer_name(cert), data, sizeof(data));
  695. RTC_DLOG(LS_INFO) << " issuer = " << data;
  696. X509_NAME_oneline(X509_get_subject_name(cert), data, sizeof(data));
  697. RTC_DLOG(LS_INFO) << " subject = " << data;
  698. RTC_DLOG(LS_INFO) << " err = " << err << ":"
  699. << X509_verify_cert_error_string(err);
  700. }
  701. #endif
  702. // Get our stream pointer from the store
  703. SSL* ssl = reinterpret_cast<SSL*>(
  704. X509_STORE_CTX_get_ex_data(store, SSL_get_ex_data_X509_STORE_CTX_idx()));
  705. OpenSSLAdapter* stream =
  706. reinterpret_cast<OpenSSLAdapter*>(SSL_get_app_data(ssl));
  707. if (!ok && stream->ssl_cert_verifier_ != nullptr) {
  708. RTC_LOG(LS_INFO) << "Invoking SSL Verify Callback.";
  709. const OpenSSLCertificate cert(X509_STORE_CTX_get_current_cert(store));
  710. if (stream->ssl_cert_verifier_->Verify(cert)) {
  711. stream->custom_cert_verifier_status_ = true;
  712. RTC_LOG(LS_INFO) << "Validated certificate using custom callback";
  713. ok = true;
  714. } else {
  715. RTC_LOG(LS_INFO) << "Failed to verify certificate using custom callback";
  716. }
  717. }
  718. // Should only be used for debugging and development.
  719. if (!ok && stream->ignore_bad_cert_) {
  720. RTC_DLOG(LS_WARNING) << "Ignoring cert error while verifying cert chain";
  721. ok = 1;
  722. }
  723. return ok;
  724. }
  725. int OpenSSLAdapter::NewSSLSessionCallback(SSL* ssl, SSL_SESSION* session) {
  726. OpenSSLAdapter* stream =
  727. reinterpret_cast<OpenSSLAdapter*>(SSL_get_app_data(ssl));
  728. RTC_DCHECK(stream->ssl_session_cache_);
  729. RTC_LOG(LS_INFO) << "Caching SSL session for " << stream->ssl_host_name_;
  730. stream->ssl_session_cache_->AddSession(stream->ssl_host_name_, session);
  731. return 1; // We've taken ownership of the session; OpenSSL shouldn't free it.
  732. }
  733. SSL_CTX* OpenSSLAdapter::CreateContext(SSLMode mode, bool enable_cache) {
  734. SSL_CTX* ctx =
  735. SSL_CTX_new(mode == SSL_MODE_DTLS ? DTLS_method() : TLS_method());
  736. if (ctx == nullptr) {
  737. unsigned long error = ERR_get_error(); // NOLINT: type used by OpenSSL.
  738. RTC_LOG(LS_WARNING) << "SSL_CTX creation failed: " << '"'
  739. << ERR_reason_error_string(error) << "\" "
  740. << "(error=" << error << ')';
  741. return nullptr;
  742. }
  743. #ifndef WEBRTC_EXCLUDE_BUILT_IN_SSL_ROOT_CERTS
  744. if (!openssl::LoadBuiltinSSLRootCertificates(ctx)) {
  745. RTC_LOG(LS_ERROR) << "SSL_CTX creation failed: Failed to load any trusted "
  746. "ssl root certificates.";
  747. SSL_CTX_free(ctx);
  748. return nullptr;
  749. }
  750. #endif // WEBRTC_EXCLUDE_BUILT_IN_SSL_ROOT_CERTS
  751. #if !defined(NDEBUG)
  752. SSL_CTX_set_info_callback(ctx, SSLInfoCallback);
  753. #endif
  754. SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, SSLVerifyCallback);
  755. SSL_CTX_set_verify_depth(ctx, 4);
  756. // Use defaults, but disable HMAC-SHA256 and HMAC-SHA384 ciphers
  757. // (note that SHA256 and SHA384 only select legacy CBC ciphers).
  758. // Additionally disable HMAC-SHA1 ciphers in ECDSA. These are the remaining
  759. // CBC-mode ECDSA ciphers.
  760. SSL_CTX_set_cipher_list(
  761. ctx, "ALL:!SHA256:!SHA384:!aPSK:!ECDSA+SHA1:!ADH:!LOW:!EXP:!MD5");
  762. if (mode == SSL_MODE_DTLS) {
  763. SSL_CTX_set_read_ahead(ctx, 1);
  764. }
  765. if (enable_cache) {
  766. SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT);
  767. SSL_CTX_sess_set_new_cb(ctx, &OpenSSLAdapter::NewSSLSessionCallback);
  768. }
  769. return ctx;
  770. }
  771. std::string TransformAlpnProtocols(
  772. const std::vector<std::string>& alpn_protocols) {
  773. // Transforms the alpn_protocols list to the format expected by
  774. // Open/BoringSSL. This requires joining the protocols into a single string
  775. // and prepending a character with the size of the protocol string before
  776. // each protocol.
  777. std::string transformed_alpn;
  778. for (const std::string& proto : alpn_protocols) {
  779. if (proto.size() == 0 || proto.size() > 0xFF) {
  780. RTC_LOG(LS_ERROR) << "OpenSSLAdapter::Error("
  781. << "TransformAlpnProtocols received proto with size "
  782. << proto.size() << ")";
  783. return "";
  784. }
  785. transformed_alpn += static_cast<char>(proto.size());
  786. transformed_alpn += proto;
  787. RTC_LOG(LS_VERBOSE) << "TransformAlpnProtocols: Adding proto: " << proto;
  788. }
  789. return transformed_alpn;
  790. }
  791. //////////////////////////////////////////////////////////////////////
  792. // OpenSSLAdapterFactory
  793. //////////////////////////////////////////////////////////////////////
  794. OpenSSLAdapterFactory::OpenSSLAdapterFactory() = default;
  795. OpenSSLAdapterFactory::~OpenSSLAdapterFactory() = default;
  796. void OpenSSLAdapterFactory::SetMode(SSLMode mode) {
  797. RTC_DCHECK(!ssl_session_cache_);
  798. ssl_mode_ = mode;
  799. }
  800. void OpenSSLAdapterFactory::SetCertVerifier(
  801. SSLCertificateVerifier* ssl_cert_verifier) {
  802. RTC_DCHECK(!ssl_session_cache_);
  803. ssl_cert_verifier_ = ssl_cert_verifier;
  804. }
  805. OpenSSLAdapter* OpenSSLAdapterFactory::CreateAdapter(AsyncSocket* socket) {
  806. if (ssl_session_cache_ == nullptr) {
  807. SSL_CTX* ssl_ctx = OpenSSLAdapter::CreateContext(ssl_mode_, true);
  808. if (ssl_ctx == nullptr) {
  809. return nullptr;
  810. }
  811. // The OpenSSLSessionCache will upref the ssl_ctx.
  812. ssl_session_cache_ =
  813. std::make_unique<OpenSSLSessionCache>(ssl_mode_, ssl_ctx);
  814. SSL_CTX_free(ssl_ctx);
  815. }
  816. return new OpenSSLAdapter(socket, ssl_session_cache_.get(),
  817. ssl_cert_verifier_);
  818. }
  819. } // namespace rtc