Serenity Operating System
at master 325 lines 11 kB view raw
1/* 2 * Copyright (c) 2020, Ali Mohammad Pur <mpfard@serenityos.org> 3 * 4 * SPDX-License-Identifier: BSD-2-Clause 5 */ 6 7#include <AK/Debug.h> 8#include <LibCore/DateTime.h> 9#include <LibCore/EventLoop.h> 10#include <LibCore/Timer.h> 11#include <LibCrypto/PK/Code/EMSA_PSS.h> 12#include <LibTLS/TLSv12.h> 13 14// Each record can hold at most 18432 bytes, leaving some headroom and rounding down to 15// a nice number gives us a maximum of 16 KiB for user-supplied application data, 16// which will be sent as a single record containing a single ApplicationData message. 17constexpr static size_t MaximumApplicationDataChunkSize = 16 * KiB; 18 19namespace TLS { 20 21ErrorOr<Bytes> TLSv12::read_some(Bytes bytes) 22{ 23 m_eof = false; 24 auto size_to_read = min(bytes.size(), m_context.application_buffer.size()); 25 if (size_to_read == 0) { 26 m_eof = true; 27 return Bytes {}; 28 } 29 30 TRY(m_context.application_buffer.slice(0, size_to_read)).span().copy_to(bytes); 31 m_context.application_buffer = TRY(m_context.application_buffer.slice(size_to_read, m_context.application_buffer.size() - size_to_read)); 32 return Bytes { bytes.data(), size_to_read }; 33} 34 35DeprecatedString TLSv12::read_line(size_t max_size) 36{ 37 if (!can_read_line()) 38 return {}; 39 40 auto* start = m_context.application_buffer.data(); 41 auto* newline = (u8*)memchr(m_context.application_buffer.data(), '\n', m_context.application_buffer.size()); 42 VERIFY(newline); 43 44 size_t offset = newline - start; 45 46 if (offset > max_size) 47 return {}; 48 49 DeprecatedString line { bit_cast<char const*>(start), offset, Chomp }; 50 // FIXME: Propagate errors. 51 m_context.application_buffer = MUST(m_context.application_buffer.slice(offset + 1, m_context.application_buffer.size() - offset - 1)); 52 53 return line; 54} 55 56ErrorOr<size_t> TLSv12::write_some(ReadonlyBytes bytes) 57{ 58 if (m_context.connection_status != ConnectionStatus::Established) { 59 dbgln_if(TLS_DEBUG, "write request while not connected"); 60 return AK::Error::from_string_literal("TLS write request while not connected"); 61 } 62 63 for (size_t offset = 0; offset < bytes.size(); offset += MaximumApplicationDataChunkSize) { 64 PacketBuilder builder { MessageType::ApplicationData, m_context.options.version, bytes.size() - offset }; 65 builder.append(bytes.slice(offset, min(bytes.size() - offset, MaximumApplicationDataChunkSize))); 66 auto packet = builder.build(); 67 68 update_packet(packet); 69 write_packet(packet); 70 } 71 72 return bytes.size(); 73} 74 75ErrorOr<NonnullOwnPtr<TLSv12>> TLSv12::connect(DeprecatedString const& host, u16 port, Options options) 76{ 77 Core::EventLoop loop; 78 OwnPtr<Core::Socket> tcp_socket = TRY(Core::TCPSocket::connect(host, port)); 79 TRY(tcp_socket->set_blocking(false)); 80 auto tls_socket = make<TLSv12>(move(tcp_socket), move(options)); 81 tls_socket->set_sni(host); 82 tls_socket->on_connected = [&] { 83 loop.quit(0); 84 }; 85 tls_socket->on_tls_error = [&](auto alert) { 86 loop.quit(256 - to_underlying(alert)); 87 }; 88 auto result = loop.exec(); 89 if (result == 0) 90 return tls_socket; 91 92 tls_socket->try_disambiguate_error(); 93 // FIXME: Should return richer information here. 94 return AK::Error::from_string_view(alert_name(static_cast<AlertDescription>(256 - result))); 95} 96 97ErrorOr<NonnullOwnPtr<TLSv12>> TLSv12::connect(DeprecatedString const& host, Core::Socket& underlying_stream, Options options) 98{ 99 TRY(underlying_stream.set_blocking(false)); 100 auto tls_socket = make<TLSv12>(&underlying_stream, move(options)); 101 tls_socket->set_sni(host); 102 Core::EventLoop loop; 103 tls_socket->on_connected = [&] { 104 loop.quit(0); 105 }; 106 tls_socket->on_tls_error = [&](auto alert) { 107 loop.quit(256 - to_underlying(alert)); 108 }; 109 auto result = loop.exec(); 110 if (result == 0) 111 return tls_socket; 112 113 tls_socket->try_disambiguate_error(); 114 // FIXME: Should return richer information here. 115 return AK::Error::from_string_view(alert_name(static_cast<AlertDescription>(256 - result))); 116} 117 118void TLSv12::setup_connection() 119{ 120 Core::deferred_invoke([this] { 121 auto& stream = underlying_stream(); 122 stream.on_ready_to_read = [this] { 123 auto result = read_from_socket(); 124 if (result.is_error()) 125 dbgln("Read error: {}", result.error()); 126 }; 127 128 m_handshake_timeout_timer = Core::Timer::create_single_shot( 129 m_max_wait_time_for_handshake_in_seconds * 1000, [&] { 130 dbgln("Handshake timeout :("); 131 auto timeout_diff = Core::DateTime::now().timestamp() - m_context.handshake_initiation_timestamp; 132 // If the timeout duration was actually within the max wait time (with a margin of error), 133 // we're not operating slow, so the server timed out. 134 // otherwise, it's our fault that the negotiation is taking too long, so extend the timer :P 135 if (timeout_diff < m_max_wait_time_for_handshake_in_seconds + 1) { 136 // The server did not respond fast enough, 137 // time the connection out. 138 alert(AlertLevel::Critical, AlertDescription::UserCanceled); 139 m_context.tls_buffer.clear(); 140 m_context.error_code = Error::TimedOut; 141 m_context.critical_error = (u8)Error::TimedOut; 142 check_connection_state(false); // Notify the client. 143 } else { 144 // Extend the timer, we are too slow. 145 m_handshake_timeout_timer->restart(m_max_wait_time_for_handshake_in_seconds * 1000); 146 } 147 }).release_value_but_fixme_should_propagate_errors(); 148 auto packet = build_hello(); 149 write_packet(packet); 150 write_into_socket(); 151 m_handshake_timeout_timer->start(); 152 m_context.handshake_initiation_timestamp = Core::DateTime::now().timestamp(); 153 }); 154 m_has_scheduled_write_flush = true; 155} 156 157void TLSv12::notify_client_for_app_data() 158{ 159 if (m_context.application_buffer.size() > 0) { 160 if (on_ready_to_read) 161 on_ready_to_read(); 162 } else { 163 if (m_context.connection_finished && !m_context.has_invoked_finish_or_error_callback) { 164 m_context.has_invoked_finish_or_error_callback = true; 165 if (on_tls_finished) 166 on_tls_finished(); 167 } 168 } 169 m_has_scheduled_app_data_flush = false; 170} 171 172ErrorOr<void> TLSv12::read_from_socket() 173{ 174 // If there's anything before we consume stuff, let the client know 175 // since we won't be consuming things if the connection is terminated. 176 notify_client_for_app_data(); 177 178 ScopeGuard notify_guard { 179 [this] { 180 // If anything new shows up, tell the client about the event. 181 notify_client_for_app_data(); 182 } 183 }; 184 185 if (!check_connection_state(true)) 186 return {}; 187 188 u8 buffer[16 * KiB]; 189 Bytes bytes { buffer, array_size(buffer) }; 190 Bytes read_bytes {}; 191 auto& stream = underlying_stream(); 192 do { 193 auto result = stream.read_some(bytes); 194 if (result.is_error()) { 195 if (result.error().is_errno() && result.error().code() != EINTR) { 196 if (result.error().code() != EAGAIN) 197 dbgln("TLS Socket read failed, error: {}", result.error()); 198 break; 199 } 200 continue; 201 } 202 read_bytes = result.release_value(); 203 consume(read_bytes); 204 } while (!read_bytes.is_empty() && !m_context.critical_error); 205 206 return {}; 207} 208 209void TLSv12::write_into_socket() 210{ 211 dbgln_if(TLS_DEBUG, "Flushing cached records: {} established? {}", m_context.tls_buffer.size(), is_established()); 212 213 m_has_scheduled_write_flush = false; 214 if (!check_connection_state(false)) 215 return; 216 217 MUST(flush()); 218} 219 220bool TLSv12::check_connection_state(bool read) 221{ 222 if (m_context.connection_finished) 223 return false; 224 225 if (m_context.close_notify) 226 m_context.connection_finished = true; 227 228 auto& stream = underlying_stream(); 229 230 if (!stream.is_open()) { 231 // an abrupt closure (the server is a jerk) 232 dbgln_if(TLS_DEBUG, "Socket not open, assuming abrupt closure"); 233 m_context.connection_finished = true; 234 m_context.connection_status = ConnectionStatus::Disconnected; 235 close(); 236 return false; 237 } 238 239 if (read && stream.is_eof()) { 240 if (m_context.application_buffer.size() == 0 && m_context.connection_status != ConnectionStatus::Disconnected) { 241 m_context.has_invoked_finish_or_error_callback = true; 242 if (on_tls_finished) 243 on_tls_finished(); 244 } 245 return false; 246 } 247 248 if (m_context.critical_error) { 249 dbgln_if(TLS_DEBUG, "CRITICAL ERROR {} :(", m_context.critical_error); 250 251 m_context.has_invoked_finish_or_error_callback = true; 252 if (on_tls_error) 253 on_tls_error((AlertDescription)m_context.critical_error); 254 m_context.connection_finished = true; 255 m_context.connection_status = ConnectionStatus::Disconnected; 256 close(); 257 return false; 258 } 259 260 if (((read && m_context.application_buffer.size() == 0) || !read) && m_context.connection_finished) { 261 if (m_context.application_buffer.size() == 0 && m_context.connection_status != ConnectionStatus::Disconnected) { 262 m_context.has_invoked_finish_or_error_callback = true; 263 if (on_tls_finished) 264 on_tls_finished(); 265 } 266 if (m_context.tls_buffer.size()) { 267 dbgln_if(TLS_DEBUG, "connection closed without finishing data transfer, {} bytes still in buffer and {} bytes in application buffer", 268 m_context.tls_buffer.size(), 269 m_context.application_buffer.size()); 270 } 271 if (!m_context.application_buffer.size()) { 272 return false; 273 } 274 } 275 return true; 276} 277 278ErrorOr<bool> TLSv12::flush() 279{ 280 auto out_bytes = m_context.tls_buffer.bytes(); 281 282 if (out_bytes.is_empty()) 283 return true; 284 285 if constexpr (TLS_DEBUG) { 286 dbgln("SENDING..."); 287 print_buffer(out_bytes); 288 } 289 290 auto& stream = underlying_stream(); 291 Optional<AK::Error> error; 292 size_t written; 293 do { 294 auto result = stream.write_some(out_bytes); 295 if (result.is_error() && result.error().code() != EINTR && result.error().code() != EAGAIN) { 296 error = result.release_error(); 297 dbgln("TLS Socket write error: {}", *error); 298 break; 299 } 300 written = result.value(); 301 out_bytes = out_bytes.slice(written); 302 } while (!out_bytes.is_empty()); 303 304 if (out_bytes.is_empty() && !error.has_value()) { 305 m_context.tls_buffer.clear(); 306 return true; 307 } 308 309 if (m_context.send_retries++ == 10) { 310 // drop the records, we can't send 311 dbgln_if(TLS_DEBUG, "Dropping {} bytes worth of TLS records as max retries has been reached", m_context.tls_buffer.size()); 312 m_context.tls_buffer.clear(); 313 m_context.send_retries = 0; 314 } 315 return false; 316} 317 318void TLSv12::close() 319{ 320 alert(AlertLevel::Critical, AlertDescription::CloseNotify); 321 // bye bye. 322 m_context.connection_status = ConnectionStatus::Disconnected; 323} 324 325}