Socket.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. /*
  2. * Copyright (c) 2020, Ali Mohammad Pur <ali.mpfard@gmail.com>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <LibCore/DateTime.h>
  27. #include <LibCore/Timer.h>
  28. #include <LibCrypto/ASN1/DER.h>
  29. #include <LibCrypto/PK/Code/EMSA_PSS.h>
  30. #include <LibTLS/TLSv12.h>
  31. namespace TLS {
  32. Optional<ByteBuffer> TLSv12::read()
  33. {
  34. if (m_context.application_buffer.size()) {
  35. auto buf = m_context.application_buffer.slice(0, m_context.application_buffer.size());
  36. m_context.application_buffer.clear();
  37. return buf;
  38. }
  39. return {};
  40. }
  41. ByteBuffer TLSv12::read(size_t max_size)
  42. {
  43. if (m_context.application_buffer.size()) {
  44. auto length = min(m_context.application_buffer.size(), max_size);
  45. auto buf = m_context.application_buffer.slice(0, length);
  46. m_context.application_buffer = m_context.application_buffer.slice(length, m_context.application_buffer.size() - length);
  47. return buf;
  48. }
  49. return {};
  50. }
  51. String TLSv12::read_line(size_t max_size)
  52. {
  53. if (!can_read_line())
  54. return {};
  55. auto* start = m_context.application_buffer.data();
  56. auto* newline = (u8*)memchr(m_context.application_buffer.data(), '\n', m_context.application_buffer.size());
  57. ASSERT(newline);
  58. size_t offset = newline - start;
  59. if (offset > max_size)
  60. return {};
  61. auto buffer = ByteBuffer::copy(start, offset);
  62. m_context.application_buffer = m_context.application_buffer.slice(offset + 1, m_context.application_buffer.size() - offset - 1);
  63. return String::copy(buffer);
  64. }
  65. bool TLSv12::write(const ByteBuffer& buffer)
  66. {
  67. if (m_context.connection_status != ConnectionStatus::Established) {
  68. #ifdef TLS_DEBUG
  69. dbg() << "write request while not connected";
  70. #endif
  71. return false;
  72. }
  73. PacketBuilder builder { MessageType::ApplicationData, m_context.version, buffer.size() };
  74. builder.append(buffer);
  75. auto packet = builder.build();
  76. update_packet(packet);
  77. write_packet(packet);
  78. return true;
  79. }
  80. bool TLSv12::connect(const String& hostname, int port)
  81. {
  82. set_sni(hostname);
  83. return Core::Socket::connect(hostname, port);
  84. }
  85. bool TLSv12::common_connect(const struct sockaddr* saddr, socklen_t length)
  86. {
  87. if (m_context.critical_error)
  88. return false;
  89. if (Core::Socket::is_connected()) {
  90. if (is_established()) {
  91. ASSERT_NOT_REACHED();
  92. } else {
  93. Core::Socket::close(); // reuse?
  94. }
  95. }
  96. Core::Socket::on_connected = [this] {
  97. Core::Socket::on_ready_to_read = [this] {
  98. read_from_socket();
  99. };
  100. auto packet = build_hello();
  101. write_packet(packet);
  102. deferred_invoke([&](auto&) {
  103. m_handshake_timeout_timer = Core::Timer::create_single_shot(
  104. m_max_wait_time_for_handshake_in_seconds * 1000, [&] {
  105. auto timeout_diff = Core::DateTime::now().timestamp() - m_context.handshake_initiation_timestamp;
  106. // If the timeout duration was actually within the max wait time (with a margin of error),
  107. // we're not operating slow, so the server timed out.
  108. // otherwise, it's our fault that the negotiation is taking too long, so extend the timer :P
  109. if (timeout_diff < m_max_wait_time_for_handshake_in_seconds + 1) {
  110. // The server did not respond fast enough,
  111. // time the connection out.
  112. alert(AlertLevel::Critical, AlertDescription::UserCanceled);
  113. m_context.connection_finished = true;
  114. m_context.tls_buffer.clear();
  115. m_context.error_code = Error::TimedOut;
  116. m_context.critical_error = (u8)Error::TimedOut;
  117. check_connection_state(false); // Notify the client.
  118. } else {
  119. // Extend the timer, we are too slow.
  120. m_handshake_timeout_timer->restart(m_max_wait_time_for_handshake_in_seconds * 1000);
  121. }
  122. },
  123. this);
  124. write_into_socket();
  125. m_handshake_timeout_timer->start();
  126. m_context.handshake_initiation_timestamp = Core::DateTime::now().timestamp();
  127. });
  128. m_has_scheduled_write_flush = true;
  129. if (on_tls_connected)
  130. on_tls_connected();
  131. };
  132. bool success = Core::Socket::common_connect(saddr, length);
  133. if (!success)
  134. return false;
  135. return true;
  136. }
  137. void TLSv12::read_from_socket()
  138. {
  139. if (m_context.application_buffer.size() > 0) {
  140. deferred_invoke([&](auto&) { read_from_socket(); });
  141. if (on_tls_ready_to_read)
  142. on_tls_ready_to_read(*this);
  143. }
  144. if (!check_connection_state(true))
  145. return;
  146. consume(Core::Socket::read(4096));
  147. }
  148. void TLSv12::write_into_socket()
  149. {
  150. #ifdef TLS_DEBUG
  151. dbg() << "Flushing cached records: " << m_context.tls_buffer.size() << " established? " << is_established();
  152. #endif
  153. m_has_scheduled_write_flush = false;
  154. if (!check_connection_state(false))
  155. return;
  156. flush();
  157. if (!is_established())
  158. return;
  159. if (!m_context.application_buffer.size()) // hey client, you still have stuff to read...
  160. if (on_tls_ready_to_write)
  161. on_tls_ready_to_write(*this);
  162. }
  163. bool TLSv12::check_connection_state(bool read)
  164. {
  165. if (!Core::Socket::is_open() || !Core::Socket::is_connected() || Core::Socket::eof()) {
  166. // an abrupt closure (the server is a jerk)
  167. #ifdef TLS_DEBUG
  168. dbg() << "Socket not open, assuming abrupt closure";
  169. #endif
  170. m_context.connection_finished = true;
  171. }
  172. if (m_context.critical_error) {
  173. #ifdef TLS_DEBUG
  174. dbg() << "CRITICAL ERROR " << m_context.critical_error << " :(";
  175. #endif
  176. if (on_tls_error)
  177. on_tls_error((AlertDescription)m_context.critical_error);
  178. return false;
  179. }
  180. if (((read && m_context.application_buffer.size() == 0) || !read) && m_context.connection_finished) {
  181. if (m_context.application_buffer.size() == 0) {
  182. if (on_tls_finished)
  183. on_tls_finished();
  184. }
  185. if (m_context.tls_buffer.size()) {
  186. #ifdef TLS_DEBUG
  187. dbg() << "connection closed without finishing data transfer, " << m_context.tls_buffer.size() << " bytes still in buffer & " << m_context.application_buffer.size() << " bytes in application buffer";
  188. #endif
  189. } else {
  190. m_context.connection_finished = false;
  191. #ifdef TLS_DEBUG
  192. dbg() << "FINISHED";
  193. #endif
  194. }
  195. if (!m_context.application_buffer.size()) {
  196. m_context.connection_status = ConnectionStatus::Disconnected;
  197. return false;
  198. }
  199. }
  200. return true;
  201. }
  202. bool TLSv12::flush()
  203. {
  204. auto out_buffer = write_buffer().data();
  205. size_t out_buffer_index { 0 };
  206. size_t out_buffer_length = write_buffer().size();
  207. if (out_buffer_length == 0)
  208. return true;
  209. #ifdef TLS_DEBUG
  210. dbg() << "SENDING...";
  211. print_buffer(out_buffer, out_buffer_length);
  212. #endif
  213. if (Core::Socket::write(&out_buffer[out_buffer_index], out_buffer_length)) {
  214. write_buffer().clear();
  215. return true;
  216. }
  217. if (m_context.send_retries++ == 10) {
  218. // drop the records, we can't send
  219. #ifdef TLS_DEBUG
  220. dbg() << "Dropping " << write_buffer().size() << " bytes worth of TLS records as max retries has been reached";
  221. #endif
  222. write_buffer().clear();
  223. m_context.send_retries = 0;
  224. }
  225. return false;
  226. }
  227. }