mirror of
https://github.com/RGBCube/serenity
synced 2025-07-28 13:17:34 +00:00
Userland: Convert TLS::TLSv12 to a Core::Stream::Socket
This commit converts TLS::TLSv12 to a Core::Stream object, and in the process allows TLS to now wrap other Core::Stream::Socket objects. As a large part of LibHTTP and LibGemini depend on LibTLS's interface, this also converts those to support Core::Stream, which leads to a simplification of LibHTTP (as there's no need to care about the underlying socket type anymore). Note that RequestServer now controls the TLS socket options, which is a better place anyway, as RS is the first receiver of the user-requested options (though this is currently not particularly useful).
This commit is contained in:
parent
7a95c451a3
commit
aafc451016
47 changed files with 841 additions and 1157 deletions
|
@ -202,8 +202,8 @@ ssize_t TLSv12::handle_handshake_finished(ReadonlyBytes buffer, WritePacketStage
|
|||
m_handshake_timeout_timer = nullptr;
|
||||
}
|
||||
|
||||
if (on_tls_ready_to_write)
|
||||
on_tls_ready_to_write(*this);
|
||||
if (on_connected)
|
||||
on_connected();
|
||||
|
||||
return index + size;
|
||||
}
|
||||
|
|
|
@ -7,6 +7,7 @@
|
|||
#include <AK/Debug.h>
|
||||
#include <AK/Endian.h>
|
||||
#include <AK/MemoryStream.h>
|
||||
#include <LibCore/EventLoop.h>
|
||||
#include <LibCore/Timer.h>
|
||||
#include <LibCrypto/PK/Code/EMSA_PSS.h>
|
||||
#include <LibTLS/TLSv12.h>
|
||||
|
@ -32,7 +33,7 @@ void TLSv12::alert(AlertLevel level, AlertDescription code)
|
|||
{
|
||||
auto the_alert = build_alert(level == AlertLevel::Critical, (u8)code);
|
||||
write_packet(the_alert);
|
||||
flush();
|
||||
MUST(flush());
|
||||
}
|
||||
|
||||
void TLSv12::write_packet(ByteBuffer& packet)
|
||||
|
@ -41,7 +42,7 @@ void TLSv12::write_packet(ByteBuffer& packet)
|
|||
if (m_context.connection_status > ConnectionStatus::Disconnected) {
|
||||
if (!m_has_scheduled_write_flush && !immediate) {
|
||||
dbgln_if(TLS_DEBUG, "Scheduling write of {}", m_context.tls_buffer.size());
|
||||
deferred_invoke([this] { write_into_socket(); });
|
||||
Core::deferred_invoke([this] { write_into_socket(); });
|
||||
m_has_scheduled_write_flush = true;
|
||||
} else {
|
||||
// multiple packet are available, let's flush some out
|
||||
|
@ -540,15 +541,17 @@ ssize_t TLSv12::handle_message(ReadonlyBytes buffer)
|
|||
if (code == (u8)AlertDescription::CloseNotify) {
|
||||
res += 2;
|
||||
alert(AlertLevel::Critical, AlertDescription::CloseNotify);
|
||||
m_context.connection_finished = true;
|
||||
if (!m_context.cipher_spec_set) {
|
||||
// AWS CloudFront hits this.
|
||||
dbgln("Server sent a close notify and we haven't agreed on a cipher suite. Treating it as a handshake failure.");
|
||||
m_context.critical_error = (u8)AlertDescription::HandshakeFailure;
|
||||
try_disambiguate_error();
|
||||
}
|
||||
m_context.close_notify = true;
|
||||
}
|
||||
m_context.error_code = (Error)code;
|
||||
check_connection_state(false);
|
||||
notify_client_for_app_data(); // Give the user one more chance to observe the EOF
|
||||
}
|
||||
break;
|
||||
default:
|
||||
|
|
|
@ -6,6 +6,7 @@
|
|||
|
||||
#include <AK/Debug.h>
|
||||
#include <LibCore/DateTime.h>
|
||||
#include <LibCore/EventLoop.h>
|
||||
#include <LibCore/Timer.h>
|
||||
#include <LibCrypto/PK/Code/EMSA_PSS.h>
|
||||
#include <LibTLS/TLSv12.h>
|
||||
|
@ -17,24 +18,18 @@ constexpr static size_t MaximumApplicationDataChunkSize = 16 * KiB;
|
|||
|
||||
namespace TLS {
|
||||
|
||||
Optional<ByteBuffer> TLSv12::read()
|
||||
ErrorOr<size_t> TLSv12::read(Bytes bytes)
|
||||
{
|
||||
if (m_context.application_buffer.size()) {
|
||||
auto buf = move(m_context.application_buffer);
|
||||
return { move(buf) };
|
||||
m_eof = false;
|
||||
auto size_to_read = min(bytes.size(), m_context.application_buffer.size());
|
||||
if (size_to_read == 0) {
|
||||
m_eof = true;
|
||||
return 0;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
ByteBuffer TLSv12::read(size_t max_size)
|
||||
{
|
||||
if (m_context.application_buffer.size()) {
|
||||
auto length = min(m_context.application_buffer.size(), max_size);
|
||||
auto buf = m_context.application_buffer.slice(0, length);
|
||||
m_context.application_buffer = m_context.application_buffer.slice(length, m_context.application_buffer.size() - length);
|
||||
return buf;
|
||||
}
|
||||
return {};
|
||||
m_context.application_buffer.span().slice(0, size_to_read).copy_to(bytes);
|
||||
m_context.application_buffer = m_context.application_buffer.slice(size_to_read, m_context.application_buffer.size() - size_to_read);
|
||||
return size_to_read;
|
||||
}
|
||||
|
||||
String TLSv12::read_line(size_t max_size)
|
||||
|
@ -57,99 +52,112 @@ String TLSv12::read_line(size_t max_size)
|
|||
return line;
|
||||
}
|
||||
|
||||
bool TLSv12::write(ReadonlyBytes buffer)
|
||||
ErrorOr<size_t> TLSv12::write(ReadonlyBytes bytes)
|
||||
{
|
||||
if (m_context.connection_status != ConnectionStatus::Established) {
|
||||
dbgln_if(TLS_DEBUG, "write request while not connected");
|
||||
return false;
|
||||
return AK::Error::from_string_literal("TLS write request while not connected");
|
||||
}
|
||||
|
||||
for (size_t offset = 0; offset < buffer.size(); offset += MaximumApplicationDataChunkSize) {
|
||||
PacketBuilder builder { MessageType::ApplicationData, m_context.options.version, buffer.size() - offset };
|
||||
builder.append(buffer.slice(offset, min(buffer.size() - offset, MaximumApplicationDataChunkSize)));
|
||||
for (size_t offset = 0; offset < bytes.size(); offset += MaximumApplicationDataChunkSize) {
|
||||
PacketBuilder builder { MessageType::ApplicationData, m_context.options.version, bytes.size() - offset };
|
||||
builder.append(bytes.slice(offset, min(bytes.size() - offset, MaximumApplicationDataChunkSize)));
|
||||
auto packet = builder.build();
|
||||
|
||||
update_packet(packet);
|
||||
write_packet(packet);
|
||||
}
|
||||
|
||||
return true;
|
||||
return bytes.size();
|
||||
}
|
||||
|
||||
bool TLSv12::connect(const String& hostname, int port)
|
||||
ErrorOr<NonnullOwnPtr<TLSv12>> TLSv12::connect(const String& host, u16 port, Options options)
|
||||
{
|
||||
set_sni(hostname);
|
||||
return Core::Socket::connect(hostname, port);
|
||||
Core::EventLoop loop;
|
||||
OwnPtr<Core::Stream::Socket> tcp_socket = TRY(Core::Stream::TCPSocket::connect(host, port));
|
||||
TRY(tcp_socket->set_blocking(false));
|
||||
auto tls_socket = make<TLSv12>(move(tcp_socket), move(options));
|
||||
tls_socket->set_sni(host);
|
||||
tls_socket->on_connected = [&] {
|
||||
loop.quit(0);
|
||||
};
|
||||
tls_socket->on_tls_error = [&](auto alert) {
|
||||
loop.quit(256 - to_underlying(alert));
|
||||
};
|
||||
auto result = loop.exec();
|
||||
if (result == 0)
|
||||
return tls_socket;
|
||||
|
||||
tls_socket->try_disambiguate_error();
|
||||
// FIXME: Should return richer information here.
|
||||
return AK::Error::from_string_literal(alert_name(static_cast<AlertDescription>(256 - result)));
|
||||
}
|
||||
|
||||
bool TLSv12::common_connect(const struct sockaddr* saddr, socklen_t length)
|
||||
ErrorOr<NonnullOwnPtr<TLSv12>> TLSv12::connect(const String& host, Core::Stream::Socket& underlying_stream, Options options)
|
||||
{
|
||||
if (m_context.critical_error)
|
||||
return false;
|
||||
StreamVariantType socket { &underlying_stream };
|
||||
auto tls_socket = make<TLSv12>(&underlying_stream, move(options));
|
||||
tls_socket->set_sni(host);
|
||||
Core::EventLoop loop;
|
||||
tls_socket->on_connected = [&] {
|
||||
loop.quit(0);
|
||||
};
|
||||
tls_socket->on_tls_error = [&](auto alert) {
|
||||
loop.quit(256 - to_underlying(alert));
|
||||
};
|
||||
auto result = loop.exec();
|
||||
if (result == 0)
|
||||
return tls_socket;
|
||||
|
||||
if (Core::Socket::is_connected()) {
|
||||
if (is_established()) {
|
||||
VERIFY_NOT_REACHED();
|
||||
} else {
|
||||
Core::Socket::close(); // reuse?
|
||||
}
|
||||
}
|
||||
tls_socket->try_disambiguate_error();
|
||||
// FIXME: Should return richer information here.
|
||||
return AK::Error::from_string_literal(alert_name(static_cast<AlertDescription>(256 - result)));
|
||||
}
|
||||
|
||||
Core::Socket::on_connected = [this] {
|
||||
Core::Socket::on_ready_to_read = [this] {
|
||||
read_from_socket();
|
||||
void TLSv12::setup_connection()
|
||||
{
|
||||
Core::deferred_invoke([this] {
|
||||
auto& stream = underlying_stream();
|
||||
stream.on_ready_to_read = [this] {
|
||||
auto result = read_from_socket();
|
||||
if (result.is_error())
|
||||
dbgln("Read error: {}", result.error());
|
||||
};
|
||||
|
||||
m_handshake_timeout_timer = Core::Timer::create_single_shot(
|
||||
m_max_wait_time_for_handshake_in_seconds * 1000, [&] {
|
||||
dbgln("Handshake timeout :(");
|
||||
auto timeout_diff = Core::DateTime::now().timestamp() - m_context.handshake_initiation_timestamp;
|
||||
// If the timeout duration was actually within the max wait time (with a margin of error),
|
||||
// we're not operating slow, so the server timed out.
|
||||
// otherwise, it's our fault that the negotiation is taking too long, so extend the timer :P
|
||||
if (timeout_diff < m_max_wait_time_for_handshake_in_seconds + 1) {
|
||||
// The server did not respond fast enough,
|
||||
// time the connection out.
|
||||
alert(AlertLevel::Critical, AlertDescription::UserCanceled);
|
||||
m_context.tls_buffer.clear();
|
||||
m_context.error_code = Error::TimedOut;
|
||||
m_context.critical_error = (u8)Error::TimedOut;
|
||||
check_connection_state(false); // Notify the client.
|
||||
} else {
|
||||
// Extend the timer, we are too slow.
|
||||
m_handshake_timeout_timer->restart(m_max_wait_time_for_handshake_in_seconds * 1000);
|
||||
}
|
||||
});
|
||||
auto packet = build_hello();
|
||||
write_packet(packet);
|
||||
|
||||
deferred_invoke([&] {
|
||||
m_handshake_timeout_timer = Core::Timer::create_single_shot(
|
||||
m_max_wait_time_for_handshake_in_seconds * 1000, [&] {
|
||||
auto timeout_diff = Core::DateTime::now().timestamp() - m_context.handshake_initiation_timestamp;
|
||||
// If the timeout duration was actually within the max wait time (with a margin of error),
|
||||
// we're not operating slow, so the server timed out.
|
||||
// otherwise, it's our fault that the negotiation is taking too long, so extend the timer :P
|
||||
if (timeout_diff < m_max_wait_time_for_handshake_in_seconds + 1) {
|
||||
// The server did not respond fast enough,
|
||||
// time the connection out.
|
||||
alert(AlertLevel::Critical, AlertDescription::UserCanceled);
|
||||
m_context.connection_finished = true;
|
||||
m_context.tls_buffer.clear();
|
||||
m_context.error_code = Error::TimedOut;
|
||||
m_context.critical_error = (u8)Error::TimedOut;
|
||||
check_connection_state(false); // Notify the client.
|
||||
} else {
|
||||
// Extend the timer, we are too slow.
|
||||
m_handshake_timeout_timer->restart(m_max_wait_time_for_handshake_in_seconds * 1000);
|
||||
}
|
||||
},
|
||||
this);
|
||||
write_into_socket();
|
||||
m_handshake_timeout_timer->start();
|
||||
m_context.handshake_initiation_timestamp = Core::DateTime::now().timestamp();
|
||||
});
|
||||
m_has_scheduled_write_flush = true;
|
||||
|
||||
if (on_tls_connected)
|
||||
on_tls_connected();
|
||||
};
|
||||
bool success = Core::Socket::common_connect(saddr, length);
|
||||
if (!success)
|
||||
return false;
|
||||
|
||||
return true;
|
||||
write_into_socket();
|
||||
m_handshake_timeout_timer->start();
|
||||
m_context.handshake_initiation_timestamp = Core::DateTime::now().timestamp();
|
||||
});
|
||||
m_has_scheduled_write_flush = true;
|
||||
}
|
||||
|
||||
void TLSv12::notify_client_for_app_data()
|
||||
{
|
||||
if (m_context.application_buffer.size() > 0) {
|
||||
if (!m_has_scheduled_app_data_flush) {
|
||||
deferred_invoke([this] { notify_client_for_app_data(); });
|
||||
m_has_scheduled_app_data_flush = true;
|
||||
}
|
||||
if (on_tls_ready_to_read)
|
||||
on_tls_ready_to_read(*this);
|
||||
if (on_ready_to_read)
|
||||
on_ready_to_read();
|
||||
} else {
|
||||
if (m_context.connection_finished && !m_context.has_invoked_finish_or_error_callback) {
|
||||
m_context.has_invoked_finish_or_error_callback = true;
|
||||
|
@ -160,7 +168,7 @@ void TLSv12::notify_client_for_app_data()
|
|||
m_has_scheduled_app_data_flush = false;
|
||||
}
|
||||
|
||||
void TLSv12::read_from_socket()
|
||||
ErrorOr<void> TLSv12::read_from_socket()
|
||||
{
|
||||
// If there's anything before we consume stuff, let the client know
|
||||
// since we won't be consuming things if the connection is terminated.
|
||||
|
@ -173,12 +181,28 @@ void TLSv12::read_from_socket()
|
|||
}
|
||||
};
|
||||
|
||||
if (!check_connection_state(true)) {
|
||||
set_idle(true);
|
||||
return;
|
||||
}
|
||||
if (!check_connection_state(true))
|
||||
return {};
|
||||
|
||||
consume(Core::Socket::read(4 * MiB));
|
||||
u8 buffer[16 * KiB];
|
||||
Bytes bytes { buffer, array_size(buffer) };
|
||||
size_t nread = 0;
|
||||
auto& stream = underlying_stream();
|
||||
do {
|
||||
auto result = stream.read(bytes);
|
||||
if (result.is_error()) {
|
||||
if (result.error().is_errno() && result.error().code() != EINTR) {
|
||||
if (result.error().code() != EAGAIN)
|
||||
dbgln("TLS Socket read failed, error: {}", result.error());
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
nread = result.release_value();
|
||||
consume(bytes.slice(0, nread));
|
||||
} while (nread > 0 && !m_context.critical_error);
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
void TLSv12::write_into_socket()
|
||||
|
@ -188,14 +212,8 @@ void TLSv12::write_into_socket()
|
|||
m_has_scheduled_write_flush = false;
|
||||
if (!check_connection_state(false))
|
||||
return;
|
||||
flush();
|
||||
|
||||
if (!is_established())
|
||||
return;
|
||||
|
||||
if (!m_context.application_buffer.size()) // hey client, you still have stuff to read...
|
||||
if (on_tls_ready_to_write)
|
||||
on_tls_ready_to_write(*this);
|
||||
MUST(flush());
|
||||
}
|
||||
|
||||
bool TLSv12::check_connection_state(bool read)
|
||||
|
@ -203,16 +221,21 @@ bool TLSv12::check_connection_state(bool read)
|
|||
if (m_context.connection_finished)
|
||||
return false;
|
||||
|
||||
if (!Core::Socket::is_open() || !Core::Socket::is_connected()) {
|
||||
if (m_context.close_notify)
|
||||
m_context.connection_finished = true;
|
||||
|
||||
auto& stream = underlying_stream();
|
||||
|
||||
if (!stream.is_open()) {
|
||||
// an abrupt closure (the server is a jerk)
|
||||
dbgln_if(TLS_DEBUG, "Socket not open, assuming abrupt closure");
|
||||
m_context.connection_finished = true;
|
||||
m_context.connection_status = ConnectionStatus::Disconnected;
|
||||
Core::Socket::close();
|
||||
close();
|
||||
return false;
|
||||
}
|
||||
|
||||
if (read && Core::Socket::eof()) {
|
||||
if (read && stream.is_eof()) {
|
||||
if (m_context.application_buffer.size() == 0 && m_context.connection_status != ConnectionStatus::Disconnected) {
|
||||
m_context.has_invoked_finish_or_error_callback = true;
|
||||
if (on_tls_finished)
|
||||
|
@ -229,9 +252,10 @@ bool TLSv12::check_connection_state(bool read)
|
|||
on_tls_error((AlertDescription)m_context.critical_error);
|
||||
m_context.connection_finished = true;
|
||||
m_context.connection_status = ConnectionStatus::Disconnected;
|
||||
Core::Socket::close();
|
||||
close();
|
||||
return false;
|
||||
}
|
||||
|
||||
if (((read && m_context.application_buffer.size() == 0) || !read) && m_context.connection_finished) {
|
||||
if (m_context.application_buffer.size() == 0 && m_context.connection_status != ConnectionStatus::Disconnected) {
|
||||
m_context.has_invoked_finish_or_error_callback = true;
|
||||
|
@ -250,30 +274,51 @@ bool TLSv12::check_connection_state(bool read)
|
|||
return true;
|
||||
}
|
||||
|
||||
bool TLSv12::flush()
|
||||
ErrorOr<bool> TLSv12::flush()
|
||||
{
|
||||
auto out_buffer = write_buffer().data();
|
||||
size_t out_buffer_index { 0 };
|
||||
size_t out_buffer_length = write_buffer().size();
|
||||
auto out_bytes = m_context.tls_buffer.bytes();
|
||||
|
||||
if (out_buffer_length == 0)
|
||||
if (out_bytes.is_empty())
|
||||
return true;
|
||||
|
||||
if constexpr (TLS_DEBUG) {
|
||||
dbgln("SENDING...");
|
||||
print_buffer(out_buffer, out_buffer_length);
|
||||
print_buffer(out_bytes);
|
||||
}
|
||||
if (Core::Socket::write(&out_buffer[out_buffer_index], out_buffer_length)) {
|
||||
write_buffer().clear();
|
||||
|
||||
auto& stream = underlying_stream();
|
||||
Optional<AK::Error> error;
|
||||
size_t written;
|
||||
do {
|
||||
auto result = stream.write(out_bytes);
|
||||
if (result.is_error() && result.error().code() != EINTR && result.error().code() != EAGAIN) {
|
||||
error = result.release_error();
|
||||
dbgln("TLS Socket write error: {}", *error);
|
||||
break;
|
||||
}
|
||||
written = result.value();
|
||||
out_bytes = out_bytes.slice(written);
|
||||
} while (!out_bytes.is_empty());
|
||||
|
||||
if (out_bytes.is_empty() && !error.has_value()) {
|
||||
m_context.tls_buffer.clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
if (m_context.send_retries++ == 10) {
|
||||
// drop the records, we can't send
|
||||
dbgln_if(TLS_DEBUG, "Dropping {} bytes worth of TLS records as max retries has been reached", write_buffer().size());
|
||||
write_buffer().clear();
|
||||
dbgln_if(TLS_DEBUG, "Dropping {} bytes worth of TLS records as max retries has been reached", m_context.tls_buffer.size());
|
||||
m_context.tls_buffer.clear();
|
||||
m_context.send_retries = 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void TLSv12::close()
|
||||
{
|
||||
alert(AlertLevel::Critical, AlertDescription::CloseNotify);
|
||||
// bye bye.
|
||||
m_context.connection_status = ConnectionStatus::Disconnected;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -183,6 +183,7 @@ void TLSv12::set_root_certificates(Vector<Certificate> certificates)
|
|||
// FIXME: Figure out what we should do when our root certs are invalid.
|
||||
}
|
||||
m_context.root_certificates = move(certificates);
|
||||
dbgln_if(TLS_DEBUG, "{}: Set {} root certificates", this, m_context.root_certificates.size());
|
||||
}
|
||||
|
||||
bool Context::verify_chain() const
|
||||
|
@ -223,7 +224,7 @@ bool Context::verify_chain() const
|
|||
|
||||
auto ref = chain.get(it.value);
|
||||
if (!ref.has_value()) {
|
||||
dbgln("Certificate for {} is not signed by anyone we trust ({})", it.key, it.value);
|
||||
dbgln("{}: Certificate for {} is not signed by anyone we trust ({})", this, it.key, it.value);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
@ -301,50 +302,43 @@ void TLSv12::pseudorandom_function(Bytes output, ReadonlyBytes secret, const u8*
|
|||
}
|
||||
}
|
||||
|
||||
TLSv12::TLSv12(Core::Object* parent, Options options)
|
||||
: Core::Socket(Core::Socket::Type::TCP, parent)
|
||||
TLSv12::TLSv12(StreamVariantType stream, Options options)
|
||||
: m_stream(move(stream))
|
||||
{
|
||||
m_context.options = move(options);
|
||||
m_context.is_server = false;
|
||||
m_context.tls_buffer = {};
|
||||
#ifdef SOCK_NONBLOCK
|
||||
int fd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
|
||||
#else
|
||||
int fd = socket(AF_INET, SOCK_STREAM, 0);
|
||||
int option = 1;
|
||||
ioctl(fd, FIONBIO, &option);
|
||||
#endif
|
||||
if (fd < 0) {
|
||||
set_error(errno);
|
||||
} else {
|
||||
set_fd(fd);
|
||||
set_mode(Core::OpenMode::ReadWrite);
|
||||
set_error(0);
|
||||
}
|
||||
|
||||
set_root_certificates(m_context.options.root_certificates.has_value()
|
||||
? *m_context.options.root_certificates
|
||||
: DefaultRootCACertificates::the().certificates());
|
||||
|
||||
setup_connection();
|
||||
}
|
||||
|
||||
bool TLSv12::add_client_key(ReadonlyBytes certificate_pem_buffer, ReadonlyBytes rsa_key) // FIXME: This should not be bound to RSA
|
||||
Vector<Certificate> TLSv12::parse_pem_certificate(ReadonlyBytes certificate_pem_buffer, ReadonlyBytes rsa_key) // FIXME: This should not be bound to RSA
|
||||
{
|
||||
if (certificate_pem_buffer.is_empty() || rsa_key.is_empty()) {
|
||||
return true;
|
||||
return {};
|
||||
}
|
||||
|
||||
auto decoded_certificate = Crypto::decode_pem(certificate_pem_buffer);
|
||||
if (decoded_certificate.is_empty()) {
|
||||
dbgln("Certificate not PEM");
|
||||
return false;
|
||||
return {};
|
||||
}
|
||||
|
||||
auto maybe_certificate = Certificate::parse_asn1(decoded_certificate);
|
||||
if (!maybe_certificate.has_value()) {
|
||||
dbgln("Invalid certificate");
|
||||
return false;
|
||||
return {};
|
||||
}
|
||||
|
||||
Crypto::PK::RSA rsa(rsa_key);
|
||||
auto certificate = maybe_certificate.release_value();
|
||||
certificate.private_key = rsa.private_key();
|
||||
|
||||
return add_client_key(certificate);
|
||||
return { move(certificate) };
|
||||
}
|
||||
|
||||
Singleton<DefaultRootCACertificates> DefaultRootCACertificates::s_the;
|
||||
|
@ -364,5 +358,6 @@ DefaultRootCACertificates::DefaultRootCACertificates()
|
|||
cert.not_after = Crypto::ASN1::parse_generalized_time(config->read_entry(entity, "not_after", "")).value_or(next_year);
|
||||
m_ca_certificates.append(move(cert));
|
||||
}
|
||||
dbgln("Loaded {} CA Certificates", m_ca_certificates.size());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -10,8 +10,8 @@
|
|||
#include <AK/IPv4Address.h>
|
||||
#include <AK/WeakPtr.h>
|
||||
#include <LibCore/Notifier.h>
|
||||
#include <LibCore/Socket.h>
|
||||
#include <LibCore/TCPSocket.h>
|
||||
#include <LibCore/Stream.h>
|
||||
#include <LibCore/Timer.h>
|
||||
#include <LibCrypto/Authentication/HMAC.h>
|
||||
#include <LibCrypto/BigInt/UnsignedBigInteger.h>
|
||||
#include <LibCrypto/Cipher/AES.h>
|
||||
|
@ -215,7 +215,17 @@ struct Options {
|
|||
|
||||
#define OPTION_WITH_DEFAULTS(typ, name, ...) \
|
||||
static typ default_##name() { return typ { __VA_ARGS__ }; } \
|
||||
typ name = default_##name();
|
||||
typ name = default_##name(); \
|
||||
Options& set_##name(typ new_value)& \
|
||||
{ \
|
||||
name = move(new_value); \
|
||||
return *this; \
|
||||
} \
|
||||
Options&& set_##name(typ new_value)&& \
|
||||
{ \
|
||||
name = move(new_value); \
|
||||
return move(*this); \
|
||||
}
|
||||
|
||||
OPTION_WITH_DEFAULTS(Version, version, Version::V12)
|
||||
OPTION_WITH_DEFAULTS(Vector<SignatureAndHashAlgorithm>, supported_signature_algorithms,
|
||||
|
@ -227,6 +237,10 @@ struct Options {
|
|||
OPTION_WITH_DEFAULTS(bool, use_sni, true)
|
||||
OPTION_WITH_DEFAULTS(bool, use_compression, false)
|
||||
OPTION_WITH_DEFAULTS(bool, validate_certificates, true)
|
||||
OPTION_WITH_DEFAULTS(Optional<Vector<Certificate>>, root_certificates, )
|
||||
OPTION_WITH_DEFAULTS(Function<void(AlertDescription)>, alert_handler, [](auto) {})
|
||||
OPTION_WITH_DEFAULTS(Function<void()>, finish_callback, [] {})
|
||||
OPTION_WITH_DEFAULTS(Function<Vector<Certificate>()>, certificate_provider, [] { return Vector<Certificate> {}; })
|
||||
|
||||
#undef OPTION_WITH_DEFAULTS
|
||||
};
|
||||
|
@ -290,6 +304,7 @@ struct Context {
|
|||
ClientVerificationStaus client_verified { Verified };
|
||||
|
||||
bool connection_finished { false };
|
||||
bool close_notify { false };
|
||||
bool has_invoked_finish_or_error_callback { false };
|
||||
|
||||
// message flags
|
||||
|
@ -311,12 +326,55 @@ struct Context {
|
|||
} server_diffie_hellman_params;
|
||||
};
|
||||
|
||||
class TLSv12 : public Core::Socket {
|
||||
C_OBJECT(TLSv12)
|
||||
class TLSv12 final : public Core::Stream::Socket {
|
||||
private:
|
||||
Core::Stream::Socket& underlying_stream()
|
||||
{
|
||||
return *m_stream.visit([&](auto& stream) -> Core::Stream::Socket* { return stream; });
|
||||
}
|
||||
Core::Stream::Socket const& underlying_stream() const
|
||||
{
|
||||
return *m_stream.visit([&](auto& stream) -> Core::Stream::Socket const* { return stream; });
|
||||
}
|
||||
|
||||
public:
|
||||
ByteBuffer& write_buffer() { return m_context.tls_buffer; }
|
||||
virtual bool is_readable() const override { return true; }
|
||||
virtual bool is_writable() const override { return true; }
|
||||
|
||||
/// Reads into a buffer, with the maximum size being the size of the buffer.
|
||||
/// The amount of bytes read can be smaller than the size of the buffer.
|
||||
/// Returns either the amount of bytes read, or an errno in the case of
|
||||
/// failure.
|
||||
virtual ErrorOr<size_t> read(Bytes) override;
|
||||
|
||||
/// Tries to write the entire contents of the buffer. It is possible for
|
||||
/// less than the full buffer to be written. Returns either the amount of
|
||||
/// bytes written into the stream, or an errno in the case of failure.
|
||||
virtual ErrorOr<size_t> write(ReadonlyBytes) override;
|
||||
|
||||
virtual bool is_eof() const override { return m_context.connection_finished && m_context.application_buffer.is_empty(); }
|
||||
|
||||
virtual bool is_open() const override { return is_established(); }
|
||||
virtual void close() override;
|
||||
|
||||
virtual ErrorOr<size_t> pending_bytes() const override { return m_context.application_buffer.size(); }
|
||||
virtual ErrorOr<bool> can_read_without_blocking(int = 0) const override { return !m_context.application_buffer.is_empty(); }
|
||||
virtual ErrorOr<void> set_blocking(bool block) override
|
||||
{
|
||||
VERIFY(!block);
|
||||
return {};
|
||||
}
|
||||
virtual ErrorOr<void> set_close_on_exec(bool enabled) override { return underlying_stream().set_close_on_exec(enabled); }
|
||||
|
||||
virtual void set_notifications_enabled(bool enabled) override { underlying_stream().set_notifications_enabled(enabled); }
|
||||
|
||||
static ErrorOr<NonnullOwnPtr<TLSv12>> connect(String const& host, u16 port, Options = {});
|
||||
static ErrorOr<NonnullOwnPtr<TLSv12>> connect(String const& host, Core::Stream::Socket& underlying_stream, Options = {});
|
||||
|
||||
using StreamVariantType = Variant<OwnPtr<Core::Stream::Socket>, Core::Stream::Socket*>;
|
||||
explicit TLSv12(StreamVariantType, Options);
|
||||
|
||||
bool is_established() const { return m_context.connection_status == ConnectionStatus::Established; }
|
||||
virtual bool connect(const String&, int) override;
|
||||
|
||||
void set_sni(StringView sni)
|
||||
{
|
||||
|
@ -332,12 +390,7 @@ public:
|
|||
|
||||
void set_root_certificates(Vector<Certificate>);
|
||||
|
||||
bool add_client_key(ReadonlyBytes certificate_pem_buffer, ReadonlyBytes key_pem_buffer);
|
||||
bool add_client_key(Certificate certificate)
|
||||
{
|
||||
m_context.client_certificates.append(move(certificate));
|
||||
return true;
|
||||
}
|
||||
static Vector<Certificate> parse_pem_certificate(ReadonlyBytes certificate_pem_buffer, ReadonlyBytes key_pem_buffer);
|
||||
|
||||
ByteBuffer finish_build();
|
||||
|
||||
|
@ -363,35 +416,19 @@ public:
|
|||
return v == Version::V12;
|
||||
}
|
||||
|
||||
Optional<ByteBuffer> read();
|
||||
ByteBuffer read(size_t max_size);
|
||||
|
||||
bool write(ReadonlyBytes);
|
||||
void alert(AlertLevel, AlertDescription);
|
||||
|
||||
bool can_read_line() const { return m_context.application_buffer.size() && memchr(m_context.application_buffer.data(), '\n', m_context.application_buffer.size()); }
|
||||
bool can_read() const { return m_context.application_buffer.size() > 0; }
|
||||
String read_line(size_t max_size);
|
||||
|
||||
void set_on_tls_ready_to_write(Function<void(TLSv12&)> function)
|
||||
{
|
||||
on_tls_ready_to_write = move(function);
|
||||
if (on_tls_ready_to_write) {
|
||||
if (is_established())
|
||||
on_tls_ready_to_write(*this);
|
||||
}
|
||||
}
|
||||
|
||||
Function<void(TLSv12&)> on_tls_ready_to_read;
|
||||
Function<void(AlertDescription)> on_tls_error;
|
||||
Function<void()> on_tls_connected;
|
||||
Function<void()> on_tls_finished;
|
||||
Function<void(TLSv12&)> on_tls_certificate_request;
|
||||
Function<void()> on_connected;
|
||||
|
||||
private:
|
||||
explicit TLSv12(Core::Object* parent, Options = {});
|
||||
|
||||
virtual bool common_connect(const struct sockaddr*, socklen_t) override;
|
||||
void setup_connection();
|
||||
|
||||
void consume(ReadonlyBytes record);
|
||||
|
||||
|
@ -416,9 +453,9 @@ private:
|
|||
void build_rsa_pre_master_secret(PacketBuilder&);
|
||||
void build_dhe_rsa_pre_master_secret(PacketBuilder&);
|
||||
|
||||
bool flush();
|
||||
ErrorOr<bool> flush();
|
||||
void write_into_socket();
|
||||
void read_from_socket();
|
||||
ErrorOr<void> read_from_socket();
|
||||
|
||||
bool check_connection_state(bool read);
|
||||
void notify_client_for_app_data();
|
||||
|
@ -512,6 +549,8 @@ private:
|
|||
|
||||
void try_disambiguate_error() const;
|
||||
|
||||
bool m_eof { false };
|
||||
StreamVariantType m_stream;
|
||||
Context m_context;
|
||||
|
||||
OwnPtr<Crypto::Authentication::HMAC<Crypto::Hash::Manager>> m_hmac_local;
|
||||
|
@ -529,7 +568,6 @@ private:
|
|||
i32 m_max_wait_time_for_handshake_in_seconds { 10 };
|
||||
|
||||
RefPtr<Core::Timer> m_handshake_timeout_timer;
|
||||
Function<void(TLSv12&)> on_tls_ready_to_write;
|
||||
};
|
||||
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue