diff --git a/builds/gnu/Makefile.am b/builds/gnu/Makefile.am
index f92bae854..91a89e755 100644
--- a/builds/gnu/Makefile.am
+++ b/builds/gnu/Makefile.am
@@ -184,7 +184,9 @@ src_libbitcoin_network_la_SOURCES = \
${srcdir}/../../src/sessions/session_peer.cpp \
${srcdir}/../../src/sessions/session_seed.cpp \
${srcdir}/../../src/sessions/session_server.cpp \
+ ${srcdir}/../../src/tls/client.cpp \
${srcdir}/../../src/tls/codec.cpp \
+ ${srcdir}/../../src/tls/connection.cpp \
${srcdir}/../../src/tls/context.cpp \
${srcdir}/../../src/tls/record.cpp \
${srcdir}/../../src/tls/schedule.cpp \
@@ -588,7 +590,9 @@ include_bitcoin_network_tlsdir = \
${includedir}/bitcoin/network/tls
include_bitcoin_network_tls_HEADERS = \
+ ${srcdir}/../../include/bitcoin/network/tls/client.hpp \
${srcdir}/../../include/bitcoin/network/tls/codec.hpp \
+ ${srcdir}/../../include/bitcoin/network/tls/connection.hpp \
${srcdir}/../../include/bitcoin/network/tls/constants.hpp \
${srcdir}/../../include/bitcoin/network/tls/context.hpp \
${srcdir}/../../include/bitcoin/network/tls/record.hpp \
diff --git a/builds/msvc/vs2026/libbitcoin-network-test/libbitcoin-network-test.vcxproj b/builds/msvc/vs2026/libbitcoin-network-test/libbitcoin-network-test.vcxproj
index f40f0bbb0..edb3d1238 100644
--- a/builds/msvc/vs2026/libbitcoin-network-test/libbitcoin-network-test.vcxproj
+++ b/builds/msvc/vs2026/libbitcoin-network-test/libbitcoin-network-test.vcxproj
@@ -295,7 +295,7 @@
-
+
diff --git a/builds/msvc/vs2026/libbitcoin-network-test/libbitcoin-network-test.vcxproj.filters b/builds/msvc/vs2026/libbitcoin-network-test/libbitcoin-network-test.vcxproj.filters
index 6e42eb3e5..ff368cad0 100644
--- a/builds/msvc/vs2026/libbitcoin-network-test/libbitcoin-network-test.vcxproj.filters
+++ b/builds/msvc/vs2026/libbitcoin-network-test/libbitcoin-network-test.vcxproj.filters
@@ -572,7 +572,7 @@
src
-
+
src\tls
diff --git a/builds/msvc/vs2026/libbitcoin-network/libbitcoin-network.vcxproj b/builds/msvc/vs2026/libbitcoin-network/libbitcoin-network.vcxproj
index aa8eaf080..ef8475844 100644
--- a/builds/msvc/vs2026/libbitcoin-network/libbitcoin-network.vcxproj
+++ b/builds/msvc/vs2026/libbitcoin-network/libbitcoin-network.vcxproj
@@ -267,7 +267,9 @@
+
+
$(IntDir)src_tls_context.obj
@@ -477,7 +479,9 @@
+
+
diff --git a/builds/msvc/vs2026/libbitcoin-network/libbitcoin-network.vcxproj.filters b/builds/msvc/vs2026/libbitcoin-network/libbitcoin-network.vcxproj.filters
index 86b7349ac..dc1ec4228 100644
--- a/builds/msvc/vs2026/libbitcoin-network/libbitcoin-network.vcxproj.filters
+++ b/builds/msvc/vs2026/libbitcoin-network/libbitcoin-network.vcxproj.filters
@@ -588,9 +588,15 @@
src
+
+ src\tls
+
src\tls
+
+ src\tls
+
src\tls
@@ -1184,9 +1190,15 @@
include\bitcoin\network
+
+ include\bitcoin\network\tls
+
include\bitcoin\network\tls
+
+ include\bitcoin\network\tls
+
include\bitcoin\network\tls
diff --git a/include/bitcoin/network.hpp b/include/bitcoin/network.hpp
index 867137fd3..2a02dedc7 100644
--- a/include/bitcoin/network.hpp
+++ b/include/bitcoin/network.hpp
@@ -201,7 +201,9 @@
#include
#include
#include
+#include
#include
+#include
#include
#include
#include
diff --git a/include/bitcoin/network/tls/client.hpp b/include/bitcoin/network/tls/client.hpp
new file mode 100644
index 000000000..eaa4b439e
--- /dev/null
+++ b/include/bitcoin/network/tls/client.hpp
@@ -0,0 +1,115 @@
+/**
+ * Copyright (c) 2011-2026 libbitcoin developers
+ *
+ * This file is part of libbitcoin.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+#ifndef LIBBITCOIN_NETWORK_TLS_CLIENT_HPP
+#define LIBBITCOIN_NETWORK_TLS_CLIENT_HPP
+
+#include
+#include
+#include
+
+namespace libbitcoin {
+namespace network {
+namespace tls {
+
+/// The client side of one TLS 1.3 connection (rfc8446): the suites, groups
+/// and signature schemes of the context offer, server authentication by
+/// ECDSA P-256 or P-384 or RSA-PSS (to anchors, or unanchored), optional
+/// client authentication (P-256 or P-384), without pre-shared keys or early
+/// data. The client hello is output on construction. Not thread safe.
+class BCT_API client final
+ : public connection
+{
+public:
+ DELETE_COPY_MOVE(client);
+
+ typedef system::x25519::key key;
+ typedef system::data_array<32> random;
+
+ /// The context must outlive the client.
+ client(const context& context) NOEXCEPT;
+
+ /// Fixed client random and x25519 ephemeral secret (test vectors).
+ client(const context& context, const random& random,
+ const key& ephemeral) NOEXCEPT;
+ ~client() NOEXCEPT override;
+
+ /// The server sent a HelloRetryRequest.
+ bool is_retried() const NOEXCEPT;
+
+ /// The server requested a client certificate.
+ bool is_requested() const NOEXCEPT;
+
+protected:
+ bool handle_message(uint8_t type, const span& message,
+ const span& body) NOEXCEPT override;
+ bool is_handshaking() const NOEXCEPT override;
+
+private:
+ typedef context::codes codes;
+
+ enum class state
+ {
+ server_hello,
+ encrypted_extensions,
+ certificate,
+ certificate_verify,
+ finished
+ };
+
+ void send_hello() NOEXCEPT;
+ void send_compatibility() NOEXCEPT;
+ void send_flight() NOEXCEPT;
+ bool handle_server_hello(const span& message, const span& body) NOEXCEPT;
+ bool handle_retry(const span& message, bool keyed, uint16_t group,
+ const span& cookie) NOEXCEPT;
+ bool handle_encrypted_extensions(const span& message,
+ const span& body) NOEXCEPT;
+ bool handle_certificate_request(const span& message,
+ const span& body) NOEXCEPT;
+ bool handle_certificate(const span& message, const span& body) NOEXCEPT;
+ bool handle_certificate_verify(const span& message,
+ const span& body) NOEXCEPT;
+ bool handle_finished(const span& message, const span& body) NOEXCEPT;
+ system::data_chunk share(uint16_t group) NOEXCEPT;
+ bool agree(system::data_chunk& shared, uint16_t group,
+ const span& peer) const NOEXCEPT;
+
+ // Configuration.
+ const random random_;
+ key secret_;
+ system::data_chunk session_{};
+ system::secp256r1::secret_t secret256_{};
+ system::secp384r1::secret_t secret384_{};
+
+ // Handshake state.
+ codes shared_;
+ state state_{ state::server_hello };
+ system::data_chunk hello_{};
+ system::data_chunk cookie_{};
+ bool retried_{};
+ bool requested_{};
+ bool authenticate_{};
+ bool compatibility_sent_{};
+};
+
+} // namespace tls
+} // namespace network
+} // namespace libbitcoin
+
+#endif
diff --git a/include/bitcoin/network/tls/connection.hpp b/include/bitcoin/network/tls/connection.hpp
new file mode 100644
index 000000000..b4fe0ed32
--- /dev/null
+++ b/include/bitcoin/network/tls/connection.hpp
@@ -0,0 +1,182 @@
+/**
+ * Copyright (c) 2011-2026 libbitcoin developers
+ *
+ * This file is part of libbitcoin.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+#ifndef LIBBITCOIN_NETWORK_TLS_CONNECTION_HPP
+#define LIBBITCOIN_NETWORK_TLS_CONNECTION_HPP
+
+#include
+#include
+#include
+#include
+
+namespace libbitcoin {
+namespace network {
+namespace tls {
+
+/// One TLS 1.3 connection (rfc8446): the record layer, alerts, handshake
+/// framing, application data and key updates, under the handshake of the
+/// client or server. Transport bytes are consumed by receive and produced into
+/// output. Not thread safe.
+class BCT_API connection
+{
+public:
+ DELETE_COPY_MOVE(connection);
+
+ /// Consume received transport bytes. False once failed, when output holds
+ /// any alert to be sent, or once the peer has sent close_notify.
+ bool receive(const const_byte_span& data) NOEXCEPT;
+
+ /// Transport bytes to be sent (the caller consumes them).
+ system::data_chunk& output() NOEXCEPT;
+
+ /// Protect application data into output (once established).
+ bool write(const const_byte_span& data) NOEXCEPT;
+
+ /// Move up to out.size() received application bytes into out.
+ size_t read(const byte_span& out) NOEXCEPT;
+
+ /// Received application bytes not yet read.
+ size_t readable() const NOEXCEPT;
+
+ /// Queue a key update into output, optionally requesting the peer's.
+ bool update(bool request) NOEXCEPT;
+
+ /// Queue close_notify into output (once).
+ void close() NOEXCEPT;
+
+ /// The handshake is complete (peer finished verified).
+ bool is_established() const NOEXCEPT;
+
+ /// The peer sent close_notify.
+ bool is_closed() const NOEXCEPT;
+
+ /// This side sent close_notify.
+ bool is_close_sent() const NOEXCEPT;
+
+ /// The connection failed, with the alert sent or received.
+ bool is_failed() const NOEXCEPT;
+ uint8_t failure() const NOEXCEPT;
+ bool is_failure_received() const NOEXCEPT;
+
+ /// Negotiated cipher suite and key exchange group.
+ uint16_t suite() const NOEXCEPT;
+ uint16_t group() const NOEXCEPT;
+
+ /// Peer certificate chain (empty if not authenticated).
+ const system::x509::certificates& peer() const NOEXCEPT;
+
+protected:
+ typedef const_byte_span span;
+
+ /// The context must outlive the connection.
+ connection(const context& context, bool server) NOEXCEPT;
+ virtual ~connection() NOEXCEPT;
+
+ /// Handshake messages.
+ /// -----------------------------------------------------------------------
+
+ static system::data_chunk make_message(uint8_t type,
+ const system::data_chunk& body) NOEXCEPT;
+ static system::data_chunk make_certificate(
+ const context::chain& chain) NOEXCEPT;
+ static bool parse_certificate(system::x509::certificates& out,
+ uint8_t& alert, const span& body) NOEXCEPT;
+ static uint8_t to_alert(const code& ec) NOEXCEPT;
+
+ /// CertificateVerify by the context key, of the transcript (4.4.3).
+ system::data_chunk make_verify(std::string_view label) const NOEXCEPT;
+
+ /// True if the leaf signed the transcript by the scheme (4.4.3).
+ bool is_verified(const system::x509::certificate& leaf, uint16_t scheme,
+ const span& signature, std::string_view label) const NOEXCEPT;
+
+ /// Handshake of the role, from the received handshake message.
+ virtual bool handle_message(uint8_t type, const span& message,
+ const span& body) NOEXCEPT = 0;
+
+ /// True if a compatibility change_cipher_spec may be received (5).
+ virtual bool is_handshaking() const NOEXCEPT = 0;
+
+ /// Records and keys.
+ /// -----------------------------------------------------------------------
+
+ bool fail(uint8_t alert) NOEXCEPT;
+ void establish() NOEXCEPT;
+ void seal(uint8_t type, const span& data) NOEXCEPT;
+ void send(uint8_t type, const span& data) NOEXCEPT;
+ void set_send(const schedule::secret& traffic) NOEXCEPT;
+ void set_receive(const schedule::secret& traffic) NOEXCEPT;
+ bool handle_key_update(const span& body) NOEXCEPT;
+ void add_transcript(const span& message) NOEXCEPT;
+ schedule::secret transcript() const NOEXCEPT;
+
+ /// Application traffic secrets (7.1), from the handshake secret.
+ void derive_traffic() NOEXCEPT;
+
+ // Configuration.
+ const context& context_;
+
+ // Negotiation.
+ uint16_t suite_{};
+ uint16_t group_{};
+ system::x509::certificates peer_{};
+ tls::transcript transcript_{};
+
+ // Keys.
+ schedule::secret handshake_secret_{};
+ schedule::secret client_handshake_{};
+ schedule::secret server_handshake_{};
+ schedule::secret client_traffic_{};
+ schedule::secret server_traffic_{};
+
+private:
+ bool handle_record(uint8_t type, const span& header,
+ const span& fragment) NOEXCEPT;
+ bool handle_content(uint8_t type, const span& content) NOEXCEPT;
+ bool handle_alert(const span& content) NOEXCEPT;
+ bool handle_handshake(const span& content) NOEXCEPT;
+ void send_update(bool request) NOEXCEPT;
+ schedule::secret& send_traffic() NOEXCEPT;
+ schedule::secret& receive_traffic() NOEXCEPT;
+
+ // State.
+ const bool server_;
+ uint8_t failure_{};
+ bool failed_{};
+ bool failure_received_{};
+ bool established_{};
+ bool closed_{};
+ bool close_sent_{};
+ size_t receive_epoch_{};
+
+ // Buffers.
+ system::data_chunk input_{};
+ system::data_chunk handshake_{};
+ system::data_chunk application_{};
+ system::data_chunk output_{};
+
+ // Records.
+ record send_{};
+ record receive_{};
+};
+
+} // namespace tls
+} // namespace network
+} // namespace libbitcoin
+
+#endif
diff --git a/include/bitcoin/network/tls/constants.hpp b/include/bitcoin/network/tls/constants.hpp
index f435eb5dd..4e727af69 100644
--- a/include/bitcoin/network/tls/constants.hpp
+++ b/include/bitcoin/network/tls/constants.hpp
@@ -94,6 +94,7 @@ namespace alert
constexpr uint8_t internal_error = 80;
constexpr uint8_t user_canceled = 90;
constexpr uint8_t missing_extension = 109;
+ constexpr uint8_t unsupported_extension = 110;
constexpr uint8_t certificate_required = 116;
}
@@ -114,6 +115,9 @@ constexpr uint16_t x25519_group = 0x001d;
/// Signature schemes (4.2.3).
constexpr uint16_t ecdsa_secp256r1_sha256 = 0x0403;
constexpr uint16_t ecdsa_secp384r1_sha384 = 0x0503;
+constexpr uint16_t rsa_pss_rsae_sha256 = 0x0804;
+constexpr uint16_t rsa_pss_rsae_sha384 = 0x0805;
+constexpr uint16_t rsa_pss_rsae_sha512 = 0x0806;
/// HelloRetryRequest random, SHA-256 of "HelloRetryRequest" (4.1.3).
constexpr system::data_array<32> retry_random
diff --git a/include/bitcoin/network/tls/context.hpp b/include/bitcoin/network/tls/context.hpp
index bc059c530..2fcfb60c0 100644
--- a/include/bitcoin/network/tls/context.hpp
+++ b/include/bitcoin/network/tls/context.hpp
@@ -20,19 +20,54 @@
#define LIBBITCOIN_NETWORK_TLS_CONTEXT_HPP
#include
+#include
namespace libbitcoin {
namespace network {
namespace tls {
-/// Server credentials and peer verification configuration, shared by the
-/// connections of a server. Not thread safe during configuration.
+/// Credentials and peer verification configuration, shared by the
+/// connections of a server or of a client. Not thread safe during
+/// configuration.
class BCT_API context final
{
public:
DELETE_COPY_MOVE(context);
typedef std::vector chain;
+ typedef std::vector codes;
+
+ /// The client hello offer: cipher suites, groups, groups of key shares,
+ /// signature schemes and legacy session id size (compatibility mode).
+ struct offer
+ {
+ codes suites
+ {
+ aes_128_gcm_sha256,
+ aes_256_gcm_sha384,
+ chacha20_poly1305_sha256
+ };
+
+ codes groups
+ {
+ x25519_group,
+ secp256r1_group,
+ secp384r1_group
+ };
+
+ codes shares{ x25519_group };
+
+ codes algorithms
+ {
+ ecdsa_secp256r1_sha256,
+ ecdsa_secp384r1_sha384,
+ rsa_pss_rsae_sha256,
+ rsa_pss_rsae_sha384,
+ rsa_pss_rsae_sha512
+ };
+
+ size_t session{ 32 };
+ };
context() NOEXCEPT;
~context() NOEXCEPT;
@@ -56,9 +91,22 @@ class BCT_API context final
/// Fix the verification time (unix seconds), zero for the current time.
void set_time(uint64_t seconds) NOEXCEPT;
- /// True if the chain and key are set.
+ /// The offer of a client.
+ void set_offer(const offer& value) NOEXCEPT;
+
+ /// The server name sent by a client (sni), none if empty.
+ void set_name(const std::string& name) NOEXCEPT;
+
+ /// A client accepts any server certificate, to be bound to an identity by
+ /// the caller (as by the Tor CERTS cell), otherwise verifies to anchors.
+ void set_unanchored(bool value) NOEXCEPT;
+
+ /// True if the chain and key are set (server).
bool is_ready() const NOEXCEPT;
+ /// True if anchors are set or unanchored, and any chain has its key.
+ bool is_client_ready() const NOEXCEPT;
+
const chain& certificates() const NOEXCEPT;
/// The curve of the private key, and the key of that curve.
@@ -70,6 +118,9 @@ class BCT_API context final
bool request() const NOEXCEPT;
bool require() const NOEXCEPT;
uint64_t time() const NOEXCEPT;
+ const offer& offered() const NOEXCEPT;
+ const std::string& name() const NOEXCEPT;
+ bool unanchored() const NOEXCEPT;
private:
bool matches() const NOEXCEPT;
@@ -80,10 +131,13 @@ class BCT_API context final
system::x509::curve curve_{};
system::data_chunk public_key_{};
system::x509::certificates anchors_{};
+ offer offer_{};
+ std::string name_{};
bool has_key_{};
uint64_t time_{};
bool request_{};
bool require_{};
+ bool unanchored_{};
};
} // namespace tls
diff --git a/include/bitcoin/network/tls/server.hpp b/include/bitcoin/network/tls/server.hpp
index 9cd1303dc..950d67620 100644
--- a/include/bitcoin/network/tls/server.hpp
+++ b/include/bitcoin/network/tls/server.hpp
@@ -20,9 +20,8 @@
#define LIBBITCOIN_NETWORK_TLS_SERVER_HPP
#include
+#include
#include
-#include
-#include
namespace libbitcoin {
namespace network {
@@ -31,10 +30,9 @@ namespace tls {
/// The server side of one TLS 1.3 connection (rfc8446): x25519, P-256 or P-384
/// key exchange, ECDSA P-256 or P-384 server authentication, optional client
/// authentication (P-256 or P-384), AES-128-GCM, AES-256-GCM or
-/// ChaCha20-Poly1305, without pre-shared keys or early data.
-/// Transport bytes are consumed by receive and produced into output. Not
-/// thread safe.
+/// ChaCha20-Poly1305, without pre-shared keys or early data. Not thread safe.
class BCT_API server final
+ : public connection
{
public:
DELETE_COPY_MOVE(server);
@@ -48,48 +46,12 @@ class BCT_API server final
/// Fixed server random and x25519 ephemeral secret (test vectors).
server(const context& context, const random& random,
const key& ephemeral) NOEXCEPT;
- ~server() NOEXCEPT;
+ ~server() NOEXCEPT override;
- /// Consume received transport bytes. False once failed, when output holds
- /// any alert to be sent, or once the peer has sent close_notify.
- bool receive(const const_byte_span& data) NOEXCEPT;
-
- /// Transport bytes to be sent (the caller consumes them).
- system::data_chunk& output() NOEXCEPT;
-
- /// Protect application data into output (once established).
- bool write(const const_byte_span& data) NOEXCEPT;
-
- /// Move up to out.size() received application bytes into out.
- size_t read(const byte_span& out) NOEXCEPT;
-
- /// Received application bytes not yet read.
- size_t readable() const NOEXCEPT;
-
- /// Queue close_notify into output (once).
- void close() NOEXCEPT;
-
- /// The handshake is complete (client finished verified).
- bool is_established() const NOEXCEPT;
-
- /// The peer sent close_notify.
- bool is_closed() const NOEXCEPT;
-
- /// This side sent close_notify.
- bool is_close_sent() const NOEXCEPT;
-
- /// The connection failed, with the alert sent or received.
- bool is_failed() const NOEXCEPT;
- uint8_t failure() const NOEXCEPT;
- bool is_failure_received() const NOEXCEPT;
-
- /// Negotiated cipher suite and key exchange group (once the client hello
- /// is accepted).
- uint16_t suite() const NOEXCEPT;
- uint16_t group() const NOEXCEPT;
-
- /// Verified client certificate chain (empty if not authenticated).
- const system::x509::certificates& peer() const NOEXCEPT;
+protected:
+ bool handle_message(uint8_t type, const span& message,
+ const span& body) NOEXCEPT override;
+ bool is_handshaking() const NOEXCEPT override;
private:
enum class state
@@ -98,73 +60,29 @@ class BCT_API server final
retry_hello,
client_certificate,
client_certificate_verify,
- client_finished,
- established,
- failed
+ client_finished
};
- typedef const_byte_span span;
-
- bool fail(uint8_t alert) NOEXCEPT;
- bool handle_record(uint8_t type, const span& header,
- const span& fragment) NOEXCEPT;
- bool handle_content(uint8_t type, const span& content) NOEXCEPT;
- bool handle_alert(const span& content) NOEXCEPT;
- bool handle_handshake(const span& content) NOEXCEPT;
- bool handle_message(uint8_t type, const span& message,
- const span& body) NOEXCEPT;
bool handle_client_hello(const span& message, const span& body) NOEXCEPT;
bool handle_certificate(const span& message, const span& body) NOEXCEPT;
bool handle_certificate_verify(const span& message,
const span& body) NOEXCEPT;
bool handle_finished(const span& message, const span& body) NOEXCEPT;
- bool handle_key_update(const span& body) NOEXCEPT;
-
void send_retry(const span& client_hello, const span& session) NOEXCEPT;
void send_hello(const random& value, const span& session,
const span& key_share) NOEXCEPT;
void send_flight() NOEXCEPT;
void send_compatibility(const span& session) NOEXCEPT;
- void send(uint8_t type, const span& data) NOEXCEPT;
- void send_update() NOEXCEPT;
bool exchange(system::data_chunk& shared, system::data_chunk& own,
const span& share) NOEXCEPT;
- void set_receive(const schedule::secret& traffic) NOEXCEPT;
- void add_transcript(const span& message) NOEXCEPT;
- schedule::secret transcript() const NOEXCEPT;
// Configuration.
- const context& context_;
const random random_;
key secret_;
- // Connection state.
+ // Handshake state.
state state_{ state::client_hello };
- uint16_t suite_{};
- uint16_t group_{};
- uint8_t failure_{};
- bool failure_received_{};
- bool closed_{};
- bool close_sent_{};
bool compatibility_sent_{};
- size_t receive_epoch_{};
- system::x509::certificates peer_{};
-
- // Buffers.
- system::data_chunk input_{};
- system::data_chunk handshake_{};
- system::data_chunk application_{};
- system::data_chunk output_{};
-
- // Keys.
- record send_{};
- record receive_{};
- tls::transcript transcript_{};
- schedule::secret handshake_secret_{};
- schedule::secret client_handshake_{};
- schedule::secret server_handshake_{};
- schedule::secret client_traffic_{};
- schedule::secret server_traffic_{};
};
} // namespace tls
diff --git a/include/bitcoin/network/tls/stream.hpp b/include/bitcoin/network/tls/stream.hpp
index b75b85aa7..7589bd599 100644
--- a/include/bitcoin/network/tls/stream.hpp
+++ b/include/bitcoin/network/tls/stream.hpp
@@ -22,6 +22,8 @@
#include
#include
#include
+#include
+#include
#include
#include
@@ -29,10 +31,10 @@ namespace libbitcoin {
namespace network {
namespace tls {
-/// The server side of a TLS 1.3 connection over a tcp socket. A read fills
-/// the first non-empty buffer of a sequence, a write protects the sequence as
-/// one record (up to maximum_plaintext). Records produced by reads (alerts and
-/// key updates) are sent in order with written records.
+/// The server or client side of a TLS 1.3 connection over a tcp socket. A
+/// read fills the first non-empty buffer of a sequence, a write protects the
+/// sequence as one record (up to maximum_plaintext). Records produced by reads
+/// (alerts and key updates) are sent in order with written records.
/// All calls must be sequenced on the underlying socket's executor. Read and
/// write chains may overlap each other but not themselves.
class BCT_API stream
@@ -44,16 +46,20 @@ class BCT_API stream
typedef std::function io_handler;
using executor_type = io::socket::executor_type;
- /// Assume ownership of the connected tcp socket.
+ /// Assume ownership of the connected tcp socket, as server or client.
/// The context must outlive the stream.
- stream(io::socket&& socket, const context& context) NOEXCEPT;
+ stream(io::socket&& socket, const context& context,
+ bool as_server) NOEXCEPT;
/// The executor and the socket of the stream.
executor_type get_executor() NOEXCEPT;
io::socket& next_layer() NOEXCEPT;
const io::socket& next_layer() const NOEXCEPT;
- /// Perform the server handshake.
+ /// Peer certificate chain (once the handshake completes).
+ const system::x509::certificates& peer() const NOEXCEPT;
+
+ /// Perform the handshake (a client hello is sent first).
void async_handshake(result_handler&& handler) NOEXCEPT;
/// Read received application bytes.
@@ -84,6 +90,8 @@ class BCT_API stream
code transport(const code& ec) const NOEXCEPT;
// handshake
+ void handle_hello(const code& ec,
+ const result_handler& handler) NOEXCEPT;
void handle_handshake(const code& ec,
const result_handler& handler) NOEXCEPT;
@@ -118,7 +126,8 @@ class BCT_API stream
// These are protected by stream (executor) sequencing.
io::socket socket_;
const context& context_;
- server server_;
+ std::variant role_{};
+ connection* connection_{};
system::data_chunk input_;
system::data_chunk plaintext_{};
system::data_chunk sending_{};
diff --git a/include/bitcoin/network/tls/tls.hpp b/include/bitcoin/network/tls/tls.hpp
index 25ed966e9..c50f16174 100644
--- a/include/bitcoin/network/tls/tls.hpp
+++ b/include/bitcoin/network/tls/tls.hpp
@@ -19,21 +19,25 @@
#ifndef LIBBITCOIN_NETWORK_TLS_TLS_HPP
#define LIBBITCOIN_NETWORK_TLS_TLS_HPP
-// TLS 1.3 server (rfc8446), the only protocol version supported.
+// TLS 1.3 server and client (rfc8446), the only protocol version supported.
// ----------------------------------------------------------------------------
// Cipher suites: TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384,
// TLS_CHACHA20_POLY1305_SHA256.
// Key exchange: X25519, P-256, P-384 (HelloRetryRequest for the preferred
// mutual group when the client shares none).
-// Server signing: ECDSA P-256 with SHA-256 or P-384 with SHA-384, by the key
+// Signing: ECDSA P-256 with SHA-256 or P-384 with SHA-384, by the key
// (constant time, rfc6979 nonce).
-// Client verify: ECDSA P-256 with SHA-256, P-384 with SHA-384.
+// Verify: ECDSA P-256 with SHA-256, P-384 with SHA-384, and by a
+// client also RSA-PSS with SHA-256, SHA-384 or SHA-512.
// Trust: configured anchors only (no system store); a self-signed
-// anchor is allowed.
-// Not supported: TLS 1.2 and earlier, RSA, Ed25519, resumption, pre-shared
-// keys, 0-RTT, OCSP and CRL.
+// anchor is allowed. A client may be unanchored, leaving the
+// server certificate to be bound by the caller.
+// Not supported: TLS 1.2 and earlier, RSA signing, Ed25519, resumption,
+// pre-shared keys, 0-RTT, OCSP and CRL.
+#include
#include
+#include
#include
#include
#include
diff --git a/src/net/socket_connect.cpp b/src/net/socket_connect.cpp
index 7a13a05e9..e7f429a2f 100644
--- a/src/net/socket_connect.cpp
+++ b/src/net/socket_connect.cpp
@@ -321,19 +321,12 @@ void socket::do_upgrade(const result_handler& handler) NOEXCEPT
if (std::holds_alternative>(context_))
{
- // The client role is not implemented.
- if (!inbound_)
- {
- handler(error::tls_alert_handshake_failure);
- return;
- }
-
// Extract to temporary to avoid dangling reference after destruction.
auto socket = std::move(get_base());
- // TLS context is applied to the socket.
+ // TLS context is applied to the socket, the inbound side serving.
auto& stream = socket_.emplace(std::move(socket),
- std::get>(context_).get());
+ std::get>(context_).get(), inbound_);
// Posts handler to socket strand.
stream.async_handshake(
diff --git a/src/tls/client.cpp b/src/tls/client.cpp
new file mode 100644
index 000000000..d00641efb
--- /dev/null
+++ b/src/tls/client.cpp
@@ -0,0 +1,663 @@
+/**
+ * Copyright (c) 2011-2026 libbitcoin developers
+ *
+ * This file is part of libbitcoin.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+#include
+
+#include
+#include
+#include
+
+// rfc8446 (tls 1.3), rfc6066 (server_name)
+
+namespace libbitcoin {
+namespace network {
+namespace tls {
+
+using namespace system;
+
+BC_PUSH_WARNING(NO_ARRAY_INDEXING)
+
+constexpr uint8_t compatibility_payload = 0x01;
+constexpr uint8_t host_name = 0x00;
+constexpr std::string_view server_verify{ "TLS 1.3, server CertificateVerify" };
+constexpr std::string_view client_verify{ "TLS 1.3, client CertificateVerify" };
+
+// Helpers.
+// ----------------------------------------------------------------------------
+
+static bool contains(const std::vector& list, uint16_t value) NOEXCEPT
+{
+ return std::find(list.cbegin(), list.cend(), value) != list.cend();
+}
+
+static void write_list(writer& out, const std::vector& list,
+ bool narrow) NOEXCEPT
+{
+ writer values{};
+ for (const auto value: list)
+ values.write_16(value);
+
+ if (narrow)
+ out.write_vector_8(values.data());
+ else
+ out.write_vector_16(values.data());
+}
+
+static void write_extension(writer& out, uint16_t type,
+ const data_chunk& data) NOEXCEPT
+{
+ out.write_16(type);
+ out.write_vector_16(data);
+}
+
+template
+static bool nist_agree(data_chunk& shared,
+ const typename Curve::secret_t& secret,
+ const const_byte_span& peer) NOEXCEPT
+{
+ typename Curve::point_t point{};
+ typename Curve::shared_t value{};
+ if (peer.size() != point.size())
+ return false;
+
+ std::copy(peer.begin(), peer.end(), point.begin());
+ const auto valid = Curve::agree(value, secret, point);
+ shared = to_chunk(value);
+ wipe(value);
+ return valid;
+}
+
+static client::random make_random() NOEXCEPT
+{
+ client::random value{};
+ maybe_random::fill(value);
+ return value;
+}
+
+static client::key make_secret() NOEXCEPT
+{
+ client::key value{};
+ maybe_random::fill(value);
+ return value;
+}
+
+// Construct.
+// ----------------------------------------------------------------------------
+
+client::client(const context& context) NOEXCEPT
+ : client(context, make_random(), make_secret())
+{
+}
+
+client::client(const context& context, const random& random,
+ const key& ephemeral) NOEXCEPT
+ : connection(context, false), random_(random), secret_(ephemeral),
+ session_(context.offered().session), shared_(context.offered().shares)
+{
+ maybe_random::fill(session_);
+ send_hello();
+}
+
+client::~client() NOEXCEPT
+{
+ wipe(secret_);
+ wipe(secret256_);
+ wipe(secret384_);
+}
+
+// Properties.
+// ----------------------------------------------------------------------------
+
+bool client::is_retried() const NOEXCEPT
+{
+ return retried_;
+}
+
+bool client::is_requested() const NOEXCEPT
+{
+ return requested_;
+}
+
+// Handshake.
+// ----------------------------------------------------------------------------
+
+bool client::is_handshaking() const NOEXCEPT
+{
+ return !is_established();
+}
+
+bool client::handle_message(uint8_t type, const span& message,
+ const span& body) NOEXCEPT
+{
+ if (is_established())
+ {
+ if (type == handshake::key_update)
+ return handle_key_update(body);
+
+ // Tickets are ignored, as there is no resumption (4.6.1).
+ if (type == handshake::new_session_ticket)
+ return true;
+
+ return fail(alert::unexpected_message);
+ }
+
+ switch (state_)
+ {
+ case state::server_hello:
+ if (type == handshake::server_hello)
+ return handle_server_hello(message, body);
+ break;
+ case state::encrypted_extensions:
+ if (type == handshake::encrypted_extensions)
+ return handle_encrypted_extensions(message, body);
+ break;
+ case state::certificate:
+ if (!requested_ && (type == handshake::certificate_request))
+ return handle_certificate_request(message, body);
+ if (type == handshake::certificate)
+ return handle_certificate(message, body);
+ break;
+ case state::certificate_verify:
+ if (type == handshake::certificate_verify)
+ return handle_certificate_verify(message, body);
+ break;
+ case state::finished:
+ if (type == handshake::finished)
+ return handle_finished(message, body);
+ break;
+ default:
+ break;
+ }
+
+ return fail(alert::unexpected_message);
+}
+
+// Client hello.
+// ----------------------------------------------------------------------------
+
+// ClientHello (4.1.2), the second after a HelloRetryRequest shares only its
+// group and echoes any cookie.
+void client::send_hello() NOEXCEPT
+{
+ const auto& offer = context_.offered();
+
+ writer versions{};
+ write_list(versions, { version_13 }, true);
+
+ writer groups{};
+ write_list(groups, offer.groups, false);
+
+ writer algorithms{};
+ write_list(algorithms, offer.algorithms, false);
+
+ writer entries{};
+ for (const auto group: shared_)
+ {
+ entries.write_16(group);
+ entries.write_vector_16(share(group));
+ }
+
+ writer shares{};
+ shares.write_vector_16(entries.data());
+
+ writer extensions{};
+ const auto& name = context_.name();
+ if (!name.empty())
+ {
+ writer server{};
+ server.write_8(host_name);
+ server.write_vector_16(data_chunk{ name.begin(), name.end() });
+
+ writer names{};
+ names.write_vector_16(server.data());
+ write_extension(extensions, extension::server_name, names.data());
+ }
+
+ write_extension(extensions, extension::supported_versions, versions.data());
+ write_extension(extensions, extension::supported_groups, groups.data());
+ write_extension(extensions, extension::signature_algorithms,
+ algorithms.data());
+ write_extension(extensions, extension::key_share, shares.data());
+
+ if (!cookie_.empty())
+ {
+ writer cookie{};
+ cookie.write_vector_16(cookie_);
+ write_extension(extensions, extension::cookie, cookie.data());
+ }
+
+ writer suites{};
+ write_list(suites, offer.suites, false);
+
+ writer body{};
+ body.write_16(legacy_version);
+ body.write_bytes(random_);
+ body.write_vector_8(session_);
+ body.write_bytes(suites.data());
+ body.write_vector_8(data_array{ 0x00 });
+ body.write_vector_16(extensions.data());
+
+ const auto hello = make_message(handshake::client_hello, body.data());
+ if (retried_)
+ add_transcript(hello);
+ else
+ hello_ = hello;
+
+ seal(content::handshake, hello);
+}
+
+// Sent once in compatibility mode (a nonempty session id), unprotected, before
+// the second ClientHello or the first protected record (D.4).
+void client::send_compatibility() NOEXCEPT
+{
+ if (session_.empty() || compatibility_sent_)
+ return;
+
+ const data_array payload{ compatibility_payload };
+ seal(content::change_cipher_spec, payload);
+ compatibility_sent_ = true;
+}
+
+// Server hello.
+// ----------------------------------------------------------------------------
+
+bool client::handle_server_hello(const span& message, const span& body) NOEXCEPT
+{
+ const auto& offer = context_.offered();
+ reader hello{ body };
+ const auto version = hello.read_16();
+ const auto value = hello.read_bytes(sizeof(random));
+ const auto session = hello.read_vector_8();
+ const auto suite = hello.read_16();
+ const auto compression = hello.read_8();
+ const auto extensions = hello.read_vector_16();
+ if (!hello.is_complete())
+ return fail(alert::decode_error);
+
+ if (version != legacy_version)
+ return fail(alert::protocol_version);
+
+ const auto retry = std::equal(value.begin(), value.end(),
+ retry_random.begin(), retry_random.end());
+ if (!std::equal(session.begin(), session.end(), session_.begin(),
+ session_.end()) || is_nonzero(compression) ||
+ !contains(offer.suites, suite) || (retried_ && (suite != suite_)))
+ return fail(alert::illegal_parameter);
+
+ // Extensions are unique and requested (4.2), a retry may add a cookie.
+ std::vector seen{};
+ uint16_t selected{}, group{};
+ span cookie{}, exchange{};
+ reader list{ extensions };
+ while (list && !list.is_complete())
+ {
+ const auto type = list.read_16();
+ const auto data = list.read_vector_16();
+ if (!list)
+ return fail(alert::decode_error);
+
+ if (contains(seen, type))
+ return fail(alert::illegal_parameter);
+
+ seen.push_back(type);
+ reader extension{ data };
+ switch (type)
+ {
+ case extension::supported_versions:
+ {
+ selected = extension.read_16();
+ break;
+ }
+ case extension::key_share:
+ {
+ group = extension.read_16();
+ if (!retry)
+ exchange = extension.read_vector_16();
+ break;
+ }
+ case extension::cookie:
+ {
+ if (!retry)
+ return fail(alert::unsupported_extension);
+
+ cookie = extension.read_vector_16();
+ break;
+ }
+ default:
+ {
+ return fail(alert::unsupported_extension);
+ }
+ }
+
+ if (!extension.is_complete())
+ return fail(alert::decode_error);
+ }
+
+ if (!list)
+ return fail(alert::decode_error);
+
+ if (selected != version_13)
+ return fail(alert::protocol_version);
+
+ const auto keyed = contains(seen, extension::key_share);
+ suite_ = suite;
+ if (retry)
+ return handle_retry(message, keyed, group, cookie);
+
+ if (!keyed)
+ return fail(alert::missing_extension);
+
+ data_chunk shared{};
+ if (!contains(shared_, group) || !agree(shared, group, exchange))
+ return fail(alert::illegal_parameter);
+
+ if (!retried_)
+ {
+ transcript_.reset(suite_);
+ add_transcript(hello_);
+ }
+
+ group_ = group;
+ add_transcript(message);
+
+ const schedule keys{ suite_ };
+ handshake_secret_ = keys.handshake_secret(keys.early_secret(), shared);
+ wipe(shared.data(), shared.size());
+
+ const auto hash = transcript();
+ client_handshake_ = keys.derive_secret(handshake_secret_,
+ "c hs traffic", hash);
+ server_handshake_ = keys.derive_secret(handshake_secret_,
+ "s hs traffic", hash);
+
+ // All later client records, including alerts, are protected (5.1).
+ send_compatibility();
+ set_send(client_handshake_);
+ set_receive(server_handshake_);
+ state_ = state::encrypted_extensions;
+ return true;
+}
+
+// HelloRetryRequest (4.1.4), at most once, for an offered group not shared
+// and/or a cookie, which must change the client hello.
+bool client::handle_retry(const span& message, bool keyed, uint16_t group,
+ const span& cookie) NOEXCEPT
+{
+ if (retried_)
+ return fail(alert::unexpected_message);
+
+ if (keyed && (!contains(context_.offered().groups, group) ||
+ contains(shared_, group)))
+ return fail(alert::illegal_parameter);
+
+ if (!keyed && cookie.empty())
+ return fail(alert::illegal_parameter);
+
+ // The transcript restarts with a hash of the first client hello (4.4.1).
+ transcript_.reset(suite_);
+ const auto hash = schedule{ suite_ }.hash(hello_);
+ writer synthetic{};
+ synthetic.write_8(handshake::message_hash);
+ synthetic.write_vector_24(hash);
+ add_transcript(synthetic.data());
+ add_transcript(message);
+
+ retried_ = true;
+ if (keyed)
+ shared_ = { group };
+
+ cookie_.assign(cookie.begin(), cookie.end());
+ send_compatibility();
+ send_hello();
+ return true;
+}
+
+// Encrypted extensions.
+// ----------------------------------------------------------------------------
+
+// Only an acknowledgment of the server name, or the server groups (4.2).
+bool client::handle_encrypted_extensions(const span& message,
+ const span& body) NOEXCEPT
+{
+ reader extensions{ body };
+ reader list{ extensions.read_vector_16() };
+ if (!extensions.is_complete())
+ return fail(alert::decode_error);
+
+ std::vector seen{};
+ while (list && !list.is_complete())
+ {
+ const auto type = list.read_16();
+ const auto data = list.read_vector_16();
+ if (!list)
+ return fail(alert::decode_error);
+
+ if (contains(seen, type))
+ return fail(alert::illegal_parameter);
+
+ seen.push_back(type);
+ const auto acknowledged = (type == extension::server_name) &&
+ !context_.name().empty() && data.empty();
+ if (!acknowledged && (type != extension::supported_groups))
+ return fail(alert::unsupported_extension);
+ }
+
+ if (!list)
+ return fail(alert::decode_error);
+
+ add_transcript(message);
+ state_ = state::certificate;
+ return true;
+}
+
+// Server authentication.
+// ----------------------------------------------------------------------------
+
+// CertificateRequest (4.3.2), signature_algorithms is required.
+bool client::handle_certificate_request(const span& message,
+ const span& body) NOEXCEPT
+{
+ reader request{ body };
+ const auto request_context = request.read_vector_8();
+ reader list{ request.read_vector_16() };
+ if (!request.is_complete())
+ return fail(alert::decode_error);
+
+ if (!request_context.empty())
+ return fail(alert::illegal_parameter);
+
+ std::vector seen{}, algorithms{};
+ while (list && !list.is_complete())
+ {
+ const auto type = list.read_16();
+ const auto data = list.read_vector_16();
+ if (!list)
+ return fail(alert::decode_error);
+
+ if (contains(seen, type))
+ return fail(alert::illegal_parameter);
+
+ seen.push_back(type);
+ if (type == extension::signature_algorithms)
+ {
+ reader source{ data };
+ algorithms = source.read_list_16();
+ if (!source.is_complete() || algorithms.empty())
+ return fail(alert::decode_error);
+ }
+ }
+
+ if (!list)
+ return fail(alert::decode_error);
+
+ if (algorithms.empty())
+ return fail(alert::missing_extension);
+
+ // Without an acceptable key the client sends an empty Certificate.
+ const auto scheme = (context_.curve() == x509::curve::secp256r1) ?
+ ecdsa_secp256r1_sha256 : ecdsa_secp384r1_sha384;
+ authenticate_ = context_.is_ready() && contains(algorithms, scheme);
+ requested_ = true;
+ add_transcript(message);
+ return true;
+}
+
+bool client::handle_certificate(const span& message, const span& body) NOEXCEPT
+{
+ uint8_t alert{};
+ x509::certificates chain{};
+ if (!parse_certificate(chain, alert, body))
+ return fail(alert);
+
+ if (chain.empty())
+ return fail(alert::decode_error);
+
+ // Unanchored, the leaf is bound to an identity by the caller.
+ if (!context_.unanchored())
+ {
+ const auto ec = x509::verify(chain, context_.anchors(),
+ context_.time(), x509::purpose::server);
+ if (ec)
+ return fail(to_alert(ec));
+ }
+
+ peer_ = std::move(chain);
+ add_transcript(message);
+ state_ = state::certificate_verify;
+ return true;
+}
+
+bool client::handle_certificate_verify(const span& message,
+ const span& body) NOEXCEPT
+{
+ reader verify{ body };
+ const auto scheme = verify.read_16();
+ const auto signature = verify.read_vector_16();
+ if (!verify.is_complete())
+ return fail(alert::decode_error);
+
+ if (!contains(context_.offered().algorithms, scheme))
+ return fail(alert::illegal_parameter);
+
+ if (!is_verified(peer_.front(), scheme, signature, server_verify))
+ return fail(alert::decrypt_error);
+
+ add_transcript(message);
+ state_ = state::finished;
+ return true;
+}
+
+// Finished.
+// ----------------------------------------------------------------------------
+
+bool client::handle_finished(const span& message, const span& body) NOEXCEPT
+{
+ const auto expected = schedule{ suite_ }.finished(server_handshake_,
+ transcript());
+ if ((body.size() != expected.size()) ||
+ !constant_time_equal(expected, body))
+ return fail(alert::decrypt_error);
+
+ // Application secrets follow the server finished (7.1).
+ add_transcript(message);
+ derive_traffic();
+ send_flight();
+ return true;
+}
+
+// Certificate and CertificateVerify if requested, then Finished (4.4).
+void client::send_flight() NOEXCEPT
+{
+ data_chunk messages{};
+ const auto append = [&](const data_chunk& message) NOEXCEPT
+ {
+ add_transcript(message);
+ messages.insert(messages.cend(), message.cbegin(), message.cend());
+ };
+
+ if (requested_)
+ {
+ append(make_certificate(authenticate_ ? context_.certificates() :
+ context::chain{}));
+
+ if (authenticate_)
+ append(make_verify(client_verify));
+ }
+
+ const auto verify_data = schedule{ suite_ }.finished(client_handshake_,
+ transcript());
+ append(make_message(handshake::finished, verify_data));
+ send(content::handshake, messages);
+
+ set_send(client_traffic_);
+ set_receive(server_traffic_);
+ establish();
+}
+
+// Keys.
+// ----------------------------------------------------------------------------
+
+// The key share of the group, the ephemeral key generated on first use.
+data_chunk client::share(uint16_t group) NOEXCEPT
+{
+ if (group == secp256r1_group)
+ {
+ secp256r1::point_t point{};
+ secret256_ = secp256r1::generate();
+ secp256r1::public_key(point, secret256_);
+ return to_chunk(point);
+ }
+
+ if (group == secp384r1_group)
+ {
+ secp384r1::point_t point{};
+ secret384_ = secp384r1::generate();
+ secp384r1::public_key(point, secret384_);
+ return to_chunk(point);
+ }
+
+ x25519::key point{};
+ x25519::multiply(point, secret_);
+ return to_chunk(point);
+}
+
+bool client::agree(data_chunk& shared, uint16_t group,
+ const span& peer) const NOEXCEPT
+{
+ if (group == secp256r1_group)
+ return nist_agree(shared, secret256_, peer);
+
+ if (group == secp384r1_group)
+ return nist_agree(shared, secret384_, peer);
+
+ x25519::key point{}, value{};
+ if (peer.size() != point.size())
+ return false;
+
+ std::copy(peer.begin(), peer.end(), point.begin());
+ const auto valid = x25519::multiply(value, secret_, point);
+ shared = to_chunk(value);
+ wipe(value);
+ return valid;
+}
+
+BC_POP_WARNING()
+
+} // namespace tls
+} // namespace network
+} // namespace libbitcoin
diff --git a/src/tls/connection.cpp b/src/tls/connection.cpp
new file mode 100644
index 000000000..528c59201
--- /dev/null
+++ b/src/tls/connection.cpp
@@ -0,0 +1,621 @@
+/**
+ * Copyright (c) 2011-2026 libbitcoin developers
+ *
+ * This file is part of libbitcoin.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+#include
+
+#include
+#include
+#include
+
+// rfc8446 (tls 1.3)
+
+namespace libbitcoin {
+namespace network {
+namespace tls {
+
+using namespace system;
+
+BC_PUSH_WARNING(NO_ARRAY_INDEXING)
+
+constexpr size_t maximum_message = 131072;
+constexpr size_t message_header_size = 4;
+constexpr size_t verify_padding = 64;
+constexpr uint8_t verify_pad = 0x20;
+constexpr uint8_t update_requested = 1;
+constexpr uint8_t update_not_requested = 0;
+constexpr uint8_t compatibility_payload = 0x01;
+constexpr uint64_t maximum_records = 16777216;
+
+static data_chunk to_bytes(const const_byte_span& bytes) NOEXCEPT
+{
+ return { bytes.begin(), bytes.end() };
+}
+
+template
+static bool verify_signature(const data_chunk& key, const const_byte_span& der,
+ const const_byte_span& digest) NOEXCEPT
+{
+ typename Curve::point_t point{};
+ typename Curve::signature_t signature{};
+ if ((key.size() != point.size()) || !Curve::decode(signature, der))
+ return false;
+
+ std::copy(key.cbegin(), key.cend(), point.begin());
+ return Curve::verify(signature, point, digest);
+}
+
+template
+static void write_signature(writer& out, uint16_t scheme,
+ const typename Curve::secret_t& key, const const_byte_span& digest) NOEXCEPT
+{
+ typename Curve::signature_t signature{};
+ Curve::sign(signature, key, digest);
+ out.write_16(scheme);
+ out.write_vector_16(Curve::encode(signature));
+}
+
+// The content signed by CertificateVerify (4.4.3).
+static data_chunk verify_content(std::string_view label,
+ const schedule::secret& transcript) NOEXCEPT
+{
+ data_chunk content(verify_padding, verify_pad);
+ content.insert(content.cend(), label.cbegin(), label.cend());
+ content.push_back(0x00);
+ content.insert(content.cend(), transcript.cbegin(), transcript.cend());
+ return content;
+}
+
+// Construct.
+// ----------------------------------------------------------------------------
+
+connection::connection(const context& context, bool server) NOEXCEPT
+ : context_(context), server_(server)
+{
+}
+
+connection::~connection() NOEXCEPT
+{
+ const auto clear = [](data_chunk& secret) NOEXCEPT
+ {
+ wipe(secret.data(), secret.size());
+ };
+
+ clear(handshake_secret_);
+ clear(client_handshake_);
+ clear(server_handshake_);
+ clear(client_traffic_);
+ clear(server_traffic_);
+}
+
+// Properties.
+// ----------------------------------------------------------------------------
+
+data_chunk& connection::output() NOEXCEPT
+{
+ return output_;
+}
+
+size_t connection::readable() const NOEXCEPT
+{
+ return application_.size();
+}
+
+bool connection::is_established() const NOEXCEPT
+{
+ return established_;
+}
+
+bool connection::is_closed() const NOEXCEPT
+{
+ return closed_;
+}
+
+bool connection::is_close_sent() const NOEXCEPT
+{
+ return close_sent_;
+}
+
+bool connection::is_failed() const NOEXCEPT
+{
+ return failed_;
+}
+
+uint8_t connection::failure() const NOEXCEPT
+{
+ return failure_;
+}
+
+bool connection::is_failure_received() const NOEXCEPT
+{
+ return failure_received_;
+}
+
+uint16_t connection::suite() const NOEXCEPT
+{
+ return suite_;
+}
+
+uint16_t connection::group() const NOEXCEPT
+{
+ return group_;
+}
+
+const x509::certificates& connection::peer() const NOEXCEPT
+{
+ return peer_;
+}
+
+// Application data.
+// ----------------------------------------------------------------------------
+
+bool connection::write(const const_byte_span& data) NOEXCEPT
+{
+ if (!is_established() || close_sent_)
+ return false;
+
+ // The send key is rotated within the AES-GCM record limit (5.5).
+ if (send_.sequence() >= maximum_records)
+ send_update(false);
+
+ send(content::application_data, data);
+ return true;
+}
+
+size_t connection::read(const byte_span& out) NOEXCEPT
+{
+ const auto size = std::min(out.size(), application_.size());
+ const auto end = std::next(application_.cbegin(), size);
+ std::copy(application_.cbegin(), end, out.begin());
+ application_.erase(application_.cbegin(), end);
+ return size;
+}
+
+bool connection::update(bool request) NOEXCEPT
+{
+ if (!is_established() || close_sent_)
+ return false;
+
+ send_update(request);
+ return true;
+}
+
+void connection::close() NOEXCEPT
+{
+ if (close_sent_ || is_failed())
+ return;
+
+ const data_array content{ alert_warning, alert::close_notify };
+ seal(content::alert, content);
+ close_sent_ = true;
+}
+
+// Records.
+// ----------------------------------------------------------------------------
+
+bool connection::fail(uint8_t description) NOEXCEPT
+{
+ if (is_failed())
+ return false;
+
+ failed_ = true;
+ failure_ = description;
+ const data_array content{ alert_fatal, description };
+ seal(content::alert, content);
+ return false;
+}
+
+void connection::establish() NOEXCEPT
+{
+ established_ = true;
+}
+
+bool connection::receive(const const_byte_span& data) NOEXCEPT
+{
+ if (is_failed() || closed_)
+ return false;
+
+ input_.insert(input_.cend(), data.begin(), data.end());
+
+ size_t start{};
+ while (!is_failed() && !closed_ &&
+ ((input_.size() - start) >= record_header_size))
+ {
+ const auto available = span{ input_ }.subspan(start);
+ reader header{ available.first(record_header_size) };
+ const auto type = header.read_8();
+ header.read_16();
+ const auto size = header.read_16();
+
+ if (size > maximum_ciphertext)
+ return fail(alert::record_overflow);
+
+ if (available.size() < (record_header_size + size))
+ break;
+
+ // Copies, since handlers may append to buffers.
+ const auto to = std::next(available.begin(), record_header_size);
+ const data_chunk head{ available.begin(), to };
+ const auto fragment = available.subspan(record_header_size, size);
+ start += record_header_size + size;
+
+ if (!handle_record(type, head, to_bytes(fragment)))
+ return false;
+ }
+
+ input_.erase(input_.cbegin(), std::next(input_.cbegin(), start));
+ return !is_failed();
+}
+
+bool connection::handle_record(uint8_t type, const span& header,
+ const span& fragment) NOEXCEPT
+{
+ // A compatibility change_cipher_spec is unprotected and ignored (5).
+ if (type == content::change_cipher_spec)
+ {
+ if (!is_handshaking() || (!is_one(fragment.size())) ||
+ (fragment.front() != compatibility_payload))
+ return fail(alert::unexpected_message);
+
+ return true;
+ }
+
+ if (!receive_.is_protected())
+ {
+ if (fragment.size() > maximum_plaintext)
+ return fail(alert::record_overflow);
+
+ if (type == content::application_data)
+ return fail(alert::unexpected_message);
+
+ return handle_content(type, fragment);
+ }
+
+ if (type != content::application_data)
+ return fail(alert::unexpected_message);
+
+ uint8_t inner{};
+ data_chunk content{};
+ if (!receive_.open(inner, content, header, fragment))
+ return fail(alert::bad_record_mac);
+
+ if (content.size() > maximum_plaintext)
+ return fail(alert::record_overflow);
+
+ return handle_content(inner, content);
+}
+
+bool connection::handle_content(uint8_t type, const span& content) NOEXCEPT
+{
+ switch (type)
+ {
+ case content::alert:
+ {
+ return handle_alert(content);
+ }
+ case content::handshake:
+ {
+ return handle_handshake(content);
+ }
+ case content::application_data:
+ {
+ if (!is_established())
+ return fail(alert::unexpected_message);
+
+ application_.insert(application_.cend(), content.begin(),
+ content.end());
+ return true;
+ }
+ default:
+ {
+ return fail(alert::unexpected_message);
+ }
+ }
+}
+
+bool connection::handle_alert(const span& content) NOEXCEPT
+{
+ if (content.size() != two)
+ return fail(alert::decode_error);
+
+ // Closure alerts are not errors (6.1).
+ const auto description = content[one];
+ if (description == alert::close_notify)
+ {
+ closed_ = true;
+ return true;
+ }
+
+ if (description == alert::user_canceled)
+ return true;
+
+ failed_ = true;
+ failure_ = description;
+ failure_received_ = true;
+ return false;
+}
+
+bool connection::handle_handshake(const span& content) NOEXCEPT
+{
+ if (content.empty())
+ return fail(alert::unexpected_message);
+
+ handshake_.insert(handshake_.cend(), content.begin(), content.end());
+ while (handshake_.size() >= message_header_size)
+ {
+ reader header{ span{ handshake_ }.first(message_header_size) };
+ const auto type = header.read_8();
+ const auto size = header.read_24();
+ if (size > maximum_message)
+ return fail(alert::decode_error);
+
+ const auto total = message_header_size + size;
+ if (handshake_.size() < total)
+ break;
+
+ const auto message = to_bytes(span{ handshake_ }.first(total));
+ const auto to = std::next(handshake_.cbegin(), total);
+ handshake_.erase(handshake_.cbegin(), to);
+
+ const auto epoch = receive_epoch_;
+ const auto body = span{ message }.subspan(message_header_size);
+ if (!handle_message(type, message, body))
+ return false;
+
+ // Handshake messages must not span a change of receive keys (5.1).
+ if ((epoch != receive_epoch_) && !handshake_.empty())
+ return fail(alert::unexpected_message);
+ }
+
+ return true;
+}
+
+void connection::seal(uint8_t type, const span& data) NOEXCEPT
+{
+ send_.seal(output_, type, data);
+}
+
+void connection::send(uint8_t type, const span& data) NOEXCEPT
+{
+ for (size_t start{}; start < data.size(); start += maximum_plaintext)
+ {
+ const auto size = std::min(maximum_plaintext, data.size() - start);
+ seal(type, data.subspan(start, size));
+ }
+}
+
+// Keys and transcript.
+// ----------------------------------------------------------------------------
+
+bool connection::handle_key_update(const span& body) NOEXCEPT
+{
+ if (body.size() != one)
+ return fail(alert::decode_error);
+
+ const auto request = body.front();
+ if ((request != update_not_requested) && (request != update_requested))
+ return fail(alert::illegal_parameter);
+
+ auto& traffic = receive_traffic();
+ traffic = schedule{ suite_ }.update(traffic);
+ set_receive(traffic);
+
+ if ((request == update_requested) && !close_sent_)
+ send_update(false);
+
+ return true;
+}
+
+// KeyUpdate under the current send key, then the next send key (4.6.3).
+void connection::send_update(bool request) NOEXCEPT
+{
+ writer update{};
+ update.write_8(request ? update_requested : update_not_requested);
+ send(content::handshake, make_message(handshake::key_update,
+ update.data()));
+
+ auto& traffic = send_traffic();
+ traffic = schedule{ suite_ }.update(traffic);
+ set_send(traffic);
+}
+
+schedule::secret& connection::send_traffic() NOEXCEPT
+{
+ return server_ ? server_traffic_ : client_traffic_;
+}
+
+schedule::secret& connection::receive_traffic() NOEXCEPT
+{
+ return server_ ? client_traffic_ : server_traffic_;
+}
+
+void connection::set_send(const schedule::secret& traffic) NOEXCEPT
+{
+ send_.set_secret(suite_, traffic);
+}
+
+void connection::set_receive(const schedule::secret& traffic) NOEXCEPT
+{
+ receive_.set_secret(suite_, traffic);
+ ++receive_epoch_;
+}
+
+void connection::derive_traffic() NOEXCEPT
+{
+ const schedule keys{ suite_ };
+ auto master = keys.master_secret(handshake_secret_);
+ const auto hash = transcript();
+ client_traffic_ = keys.derive_secret(master, "c ap traffic", hash);
+ server_traffic_ = keys.derive_secret(master, "s ap traffic", hash);
+ wipe(master.data(), master.size());
+}
+
+void connection::add_transcript(const span& message) NOEXCEPT
+{
+ transcript_.write(message);
+}
+
+schedule::secret connection::transcript() const NOEXCEPT
+{
+ return transcript_.hash();
+}
+
+// Handshake messages.
+// ----------------------------------------------------------------------------
+
+data_chunk connection::make_message(uint8_t type,
+ const data_chunk& body) NOEXCEPT
+{
+ writer out{};
+ out.write_8(type);
+ out.write_vector_24(body);
+ return out.data();
+}
+
+// Certificate (4.4.2), without extensions.
+data_chunk connection::make_certificate(const context::chain& chain) NOEXCEPT
+{
+ writer entries{};
+ for (const auto& certificate: chain)
+ {
+ entries.write_vector_24(certificate);
+ entries.write_16(0);
+ }
+
+ writer certificate{};
+ certificate.write_vector_8({});
+ certificate.write_vector_24(entries.data());
+ return make_message(handshake::certificate, certificate.data());
+}
+
+// Certificate (4.4.2) of an empty request context, the chain may be empty.
+bool connection::parse_certificate(x509::certificates& out, uint8_t& alert,
+ const span& body) NOEXCEPT
+{
+ reader certificate{ body };
+ const auto request_context = certificate.read_vector_8();
+ reader entries{ certificate.read_vector_24() };
+ alert = alert::decode_error;
+ if (!certificate.is_complete())
+ return false;
+
+ alert = alert::illegal_parameter;
+ if (!request_context.empty())
+ return false;
+
+ x509::certificates chain{};
+ while (entries && !entries.is_complete())
+ {
+ const auto der = entries.read_vector_24();
+ entries.read_vector_16();
+ alert = alert::decode_error;
+ if (!entries)
+ return false;
+
+ x509::certificate value{};
+ alert = alert::bad_certificate;
+ if (!x509::parse(value, der))
+ return false;
+
+ chain.push_back(std::move(value));
+ }
+
+ alert = alert::decode_error;
+ if (!entries)
+ return false;
+
+ out = std::move(chain);
+ return true;
+}
+
+uint8_t connection::to_alert(const code& ec) NOEXCEPT
+{
+ if (ec == system::error::certificate_expired ||
+ ec == system::error::certificate_not_yet_valid)
+ return alert::certificate_expired;
+
+ if (ec == system::error::chain_untrusted)
+ return alert::unknown_ca;
+
+ return alert::bad_certificate;
+}
+
+data_chunk connection::make_verify(std::string_view label) const NOEXCEPT
+{
+ const auto content = verify_content(label, transcript());
+ writer verify{};
+ if (context_.curve() == x509::curve::secp256r1)
+ write_signature(verify, ecdsa_secp256r1_sha256,
+ context_.key(), sha256_hash(content));
+ else
+ write_signature(verify, ecdsa_secp384r1_sha384,
+ context_.key384(), accumulator::hash(content));
+
+ return make_message(handshake::certificate_verify, verify.data());
+}
+
+bool connection::is_verified(const x509::certificate& leaf, uint16_t scheme,
+ const span& signature, std::string_view label) const NOEXCEPT
+{
+ const auto content = verify_content(label, transcript());
+ const auto ec = (leaf.key_type == x509::key_type::ec);
+ const auto rsa = (leaf.key_type == x509::key_type::rsa);
+ rsa::public_key key{};
+
+ switch (scheme)
+ {
+ case ecdsa_secp256r1_sha256:
+ {
+ return ec && (leaf.curve == x509::curve::secp256r1) &&
+ verify_signature(leaf.public_key, signature,
+ sha256_hash(content));
+ }
+ case ecdsa_secp384r1_sha384:
+ {
+ const auto digest = accumulator::hash(content);
+ return ec && (leaf.curve == x509::curve::secp384r1) &&
+ verify_signature(leaf.public_key, signature,
+ digest);
+ }
+ case rsa_pss_rsae_sha256:
+ {
+ return rsa && rsa::decode(key, leaf.public_key) &&
+ rsa::verify_pss(key, signature, sha256_hash(content));
+ }
+ case rsa_pss_rsae_sha384:
+ {
+ const auto digest = accumulator::hash(content);
+ return rsa && rsa::decode(key, leaf.public_key) &&
+ rsa::verify_pss(key, signature, digest);
+ }
+ case rsa_pss_rsae_sha512:
+ {
+ return rsa && rsa::decode(key, leaf.public_key) &&
+ rsa::verify_pss(key, signature, sha512_hash(content));
+ }
+ default:
+ {
+ return false;
+ }
+ }
+}
+
+BC_POP_WARNING()
+
+} // namespace tls
+} // namespace network
+} // namespace libbitcoin
diff --git a/src/tls/context.cpp b/src/tls/context.cpp
index 07ebd1829..9c93b04a8 100644
--- a/src/tls/context.cpp
+++ b/src/tls/context.cpp
@@ -63,6 +63,10 @@ bool context::set_chain(const std::string& text) NOEXCEPT
!is_framed(block.data))
return false;
+ // The key of the leaf signs, by ECDSA only.
+ if (value.empty() && (leaf.key_type != x509::key_type::ec))
+ return false;
+
value.push_back(block.data);
}
@@ -136,11 +140,32 @@ void context::set_time(uint64_t seconds) NOEXCEPT
time_ = seconds;
}
+void context::set_offer(const offer& value) NOEXCEPT
+{
+ offer_ = value;
+}
+
+void context::set_name(const std::string& name) NOEXCEPT
+{
+ name_ = name;
+}
+
+void context::set_unanchored(bool value) NOEXCEPT
+{
+ unanchored_ = value;
+}
+
bool context::is_ready() const NOEXCEPT
{
return has_key_ && !chain_.empty();
}
+bool context::is_client_ready() const NOEXCEPT
+{
+ const auto trusted = unanchored_ || !anchors_.empty();
+ return trusted && (has_key_ == !chain_.empty());
+}
+
const context::chain& context::certificates() const NOEXCEPT
{
return chain_;
@@ -176,6 +201,21 @@ bool context::require() const NOEXCEPT
return require_;
}
+const context::offer& context::offered() const NOEXCEPT
+{
+ return offer_;
+}
+
+const std::string& context::name() const NOEXCEPT
+{
+ return name_;
+}
+
+bool context::unanchored() const NOEXCEPT
+{
+ return unanchored_;
+}
+
uint64_t context::time() const NOEXCEPT
{
if (is_nonzero(time_))
diff --git a/src/tls/server.cpp b/src/tls/server.cpp
index cc8c52414..40b849d25 100644
--- a/src/tls/server.cpp
+++ b/src/tls/server.cpp
@@ -32,14 +32,7 @@ using namespace system;
BC_PUSH_WARNING(NO_ARRAY_INDEXING)
-constexpr size_t maximum_message = 131072;
-constexpr size_t message_header_size = 4;
-constexpr size_t verify_padding = 64;
-constexpr uint8_t verify_pad = 0x20;
-constexpr uint8_t update_requested = 1;
-constexpr uint8_t update_not_requested = 0;
constexpr uint8_t compatibility_payload = 0x01;
-constexpr uint64_t maximum_records = 16777216;
constexpr std::string_view server_verify{ "TLS 1.3, server CertificateVerify" };
constexpr std::string_view client_verify{ "TLS 1.3, client CertificateVerify" };
@@ -61,11 +54,6 @@ constexpr std::array preferred_groups
// Helpers.
// ----------------------------------------------------------------------------
-static data_chunk to_bytes(const const_byte_span& bytes) NOEXCEPT
-{
- return { bytes.begin(), bytes.end() };
-}
-
static bool contains(const std::vector& list, uint16_t value) NOEXCEPT
{
return std::find(list.cbegin(), list.cend(), value) != list.cend();
@@ -80,49 +68,6 @@ static bool to_list(std::vector& out, const const_byte_span& body,
return source.is_complete() && !out.empty();
}
-static data_chunk make_message(uint8_t type, const data_chunk& body) NOEXCEPT
-{
- writer out{};
- out.write_8(type);
- out.write_vector_24(body);
- return out.data();
-}
-
-static data_chunk verify_content(std::string_view label,
- const schedule::secret& transcript) NOEXCEPT
-{
- data_chunk content(verify_padding, verify_pad);
- content.insert(content.cend(), label.cbegin(), label.cend());
- content.push_back(0x00);
- content.insert(content.cend(), transcript.cbegin(), transcript.cend());
- return content;
-}
-
-static uint8_t to_alert(const code& ec) NOEXCEPT
-{
- if (ec == system::error::certificate_expired ||
- ec == system::error::certificate_not_yet_valid)
- return alert::certificate_expired;
-
- if (ec == system::error::chain_untrusted)
- return alert::unknown_ca;
-
- return alert::bad_certificate;
-}
-
-template
-static bool verify_signature(const data_chunk& key, const const_byte_span& der,
- const const_byte_span& digest) NOEXCEPT
-{
- typename Curve::point_t point{};
- typename Curve::signature_t signature{};
- if ((key.size() != point.size()) || !Curve::decode(signature, der))
- return false;
-
- std::copy(key.cbegin(), key.cend(), point.begin());
- return Curve::verify(signature, point, digest);
-}
-
// The shared secret and own key_share of an ephemeral key, false if the
// peer share is not a valid uncompressed point.
template
@@ -147,16 +92,6 @@ static bool nist_exchange(data_chunk& shared, data_chunk& own,
return valid;
}
-template
-static void write_signature(writer& out, uint16_t scheme,
- const typename Curve::secret_t& key, const const_byte_span& digest) NOEXCEPT
-{
- typename Curve::signature_t signature{};
- Curve::sign(signature, key, digest);
- out.write_16(scheme);
- out.write_vector_16(Curve::encode(signature));
-}
-
static server::random make_random() NOEXCEPT
{
server::random value{};
@@ -181,300 +116,34 @@ server::server(const context& context) NOEXCEPT
server::server(const context& context, const random& random,
const key& ephemeral) NOEXCEPT
- : context_(context), random_(random), secret_(ephemeral)
+ : connection(context, true), random_(random), secret_(ephemeral)
{
}
server::~server() NOEXCEPT
{
- const auto clear = [](data_chunk& secret) NOEXCEPT
- {
- wipe(secret.data(), secret.size());
- };
-
wipe(secret_);
- clear(handshake_secret_);
- clear(client_handshake_);
- clear(server_handshake_);
- clear(client_traffic_);
- clear(server_traffic_);
-}
-
-// Properties.
-// ----------------------------------------------------------------------------
-
-data_chunk& server::output() NOEXCEPT
-{
- return output_;
-}
-
-size_t server::readable() const NOEXCEPT
-{
- return application_.size();
-}
-
-bool server::is_established() const NOEXCEPT
-{
- return state_ == state::established;
-}
-
-bool server::is_closed() const NOEXCEPT
-{
- return closed_;
-}
-
-bool server::is_close_sent() const NOEXCEPT
-{
- return close_sent_;
-}
-
-bool server::is_failed() const NOEXCEPT
-{
- return state_ == state::failed;
-}
-
-uint8_t server::failure() const NOEXCEPT
-{
- return failure_;
-}
-
-bool server::is_failure_received() const NOEXCEPT
-{
- return failure_received_;
-}
-
-uint16_t server::suite() const NOEXCEPT
-{
- return suite_;
-}
-
-uint16_t server::group() const NOEXCEPT
-{
- return group_;
-}
-
-const x509::certificates& server::peer() const NOEXCEPT
-{
- return peer_;
-}
-
-// Application data.
-// ----------------------------------------------------------------------------
-
-bool server::write(const const_byte_span& data) NOEXCEPT
-{
- if (!is_established() || close_sent_)
- return false;
-
- // The send key is rotated within the AES-GCM record limit (5.5).
- if (send_.sequence() >= maximum_records)
- send_update();
-
- send(content::application_data, data);
- return true;
-}
-
-size_t server::read(const byte_span& out) NOEXCEPT
-{
- const auto size = std::min(out.size(), application_.size());
- const auto end = std::next(application_.cbegin(), size);
- std::copy(application_.cbegin(), end, out.begin());
- application_.erase(application_.cbegin(), end);
- return size;
-}
-
-void server::close() NOEXCEPT
-{
- if (close_sent_ || is_failed())
- return;
-
- const data_array content{ alert_warning, alert::close_notify };
- send_.seal(output_, content::alert, content);
- close_sent_ = true;
}
-// Records.
+// Handshake.
// ----------------------------------------------------------------------------
-bool server::fail(uint8_t description) NOEXCEPT
-{
- if (is_failed())
- return false;
-
- state_ = state::failed;
- failure_ = description;
- const data_array content{ alert_fatal, description };
- send_.seal(output_, content::alert, content);
- return false;
-}
-
-bool server::receive(const const_byte_span& data) NOEXCEPT
-{
- if (is_failed() || closed_)
- return false;
-
- input_.insert(input_.cend(), data.begin(), data.end());
-
- size_t start{};
- while (!is_failed() && !closed_ &&
- ((input_.size() - start) >= record_header_size))
- {
- const auto available = span{ input_ }.subspan(start);
- reader header{ available.first(record_header_size) };
- const auto type = header.read_8();
- header.read_16();
- const auto size = header.read_16();
-
- if (size > maximum_ciphertext)
- return fail(alert::record_overflow);
-
- if (available.size() < (record_header_size + size))
- break;
-
- // Copies, since handlers may append to buffers.
- const auto to = std::next(available.begin(), record_header_size);
- const data_chunk head{ available.begin(), to };
- const auto fragment = available.subspan(record_header_size, size);
- start += record_header_size + size;
-
- if (!handle_record(type, head, to_bytes(fragment)))
- return false;
- }
-
- input_.erase(input_.cbegin(), std::next(input_.cbegin(), start));
- return !is_failed();
-}
-
-bool server::handle_record(uint8_t type, const span& header,
- const span& fragment) NOEXCEPT
-{
- // A compatibility change_cipher_spec is unprotected and ignored (5).
- if (type == content::change_cipher_spec)
- {
- const auto handshaking =
- (state_ != state::client_hello) &&
- (state_ != state::established);
-
- if (!handshaking || (!is_one(fragment.size())) ||
- (fragment.front() != compatibility_payload))
- return fail(alert::unexpected_message);
-
- return true;
- }
-
- if (!receive_.is_protected())
- {
- if (fragment.size() > maximum_plaintext)
- return fail(alert::record_overflow);
-
- if (type == content::application_data)
- return fail(alert::unexpected_message);
-
- return handle_content(type, fragment);
- }
-
- if (type != content::application_data)
- return fail(alert::unexpected_message);
-
- uint8_t inner{};
- data_chunk content{};
- if (!receive_.open(inner, content, header, fragment))
- return fail(alert::bad_record_mac);
-
- if (content.size() > maximum_plaintext)
- return fail(alert::record_overflow);
-
- return handle_content(inner, content);
-}
-
-bool server::handle_content(uint8_t type, const span& content) NOEXCEPT
+bool server::is_handshaking() const NOEXCEPT
{
- switch (type)
- {
- case content::alert:
- {
- return handle_alert(content);
- }
- case content::handshake:
- {
- return handle_handshake(content);
- }
- case content::application_data:
- {
- if (!is_established())
- return fail(alert::unexpected_message);
-
- application_.insert(application_.cend(), content.begin(),
- content.end());
- return true;
- }
- default:
- {
- return fail(alert::unexpected_message);
- }
- }
+ return (state_ != state::client_hello) && !is_established();
}
-bool server::handle_alert(const span& content) NOEXCEPT
+bool server::handle_message(uint8_t type, const span& message,
+ const span& body) NOEXCEPT
{
- if (content.size() != two)
- return fail(alert::decode_error);
-
- // Closure alerts are not errors (6.1).
- const auto description = content[one];
- if (description == alert::close_notify)
+ if (is_established())
{
- closed_ = true;
- return true;
- }
-
- if (description == alert::user_canceled)
- return true;
+ if (type == handshake::key_update)
+ return handle_key_update(body);
- state_ = state::failed;
- failure_ = description;
- failure_received_ = true;
- return false;
-}
-
-bool server::handle_handshake(const span& content) NOEXCEPT
-{
- if (content.empty())
return fail(alert::unexpected_message);
-
- handshake_.insert(handshake_.cend(), content.begin(), content.end());
- while (handshake_.size() >= message_header_size)
- {
- reader header{ span{ handshake_ }.first(message_header_size) };
- const auto type = header.read_8();
- const auto size = header.read_24();
- if (size > maximum_message)
- return fail(alert::decode_error);
-
- const auto total = message_header_size + size;
- if (handshake_.size() < total)
- break;
-
- const auto message = to_bytes(span{ handshake_ }.first(total));
- const auto to = std::next(handshake_.cbegin(), total);
- handshake_.erase(handshake_.cbegin(), to);
-
- const auto epoch = receive_epoch_;
- const auto body = span{ message }.subspan(message_header_size);
- if (!handle_message(type, message, body))
- return false;
-
- // Handshake messages must not span a change of receive keys (5.1).
- if ((epoch != receive_epoch_) && !handshake_.empty())
- return fail(alert::unexpected_message);
}
- return true;
-}
-
-bool server::handle_message(uint8_t type, const span& message,
- const span& body) NOEXCEPT
-{
switch (state_)
{
case state::client_hello:
@@ -494,10 +163,6 @@ bool server::handle_message(uint8_t type, const span& message,
if (type == handshake::finished)
return handle_finished(message, body);
break;
- case state::established:
- if (type == handshake::key_update)
- return handle_key_update(body);
- break;
default:
break;
}
@@ -674,7 +339,7 @@ bool server::handle_client_hello(const span& message, const span& body) NOEXCEPT
server_handshake_ = keys.derive_secret(handshake_secret_,
"s hs traffic", hash);
- send_.set_secret(suite_, server_handshake_);
+ set_send(server_handshake_);
set_receive(client_handshake_);
send_flight();
@@ -722,7 +387,7 @@ void server::send_hello(const random& value, const span& session,
const auto hello = make_message(handshake::server_hello, body.data());
add_transcript(hello);
- send_.seal(output_, content::handshake, hello);
+ seal(content::handshake, hello);
send_compatibility(session);
}
@@ -734,7 +399,7 @@ void server::send_compatibility(const span& session) NOEXCEPT
return;
const data_array payload{ compatibility_payload };
- send_.seal(output_, content::change_cipher_spec, payload);
+ seal(content::change_cipher_spec, payload);
compatibility_sent_ = true;
}
@@ -772,53 +437,17 @@ void server::send_flight() NOEXCEPT
append(make_message(handshake::certificate_request, request.data()));
}
- // Certificate (4.4.2).
- writer entries{};
- for (const auto& certificate: context_.certificates())
- {
- entries.write_vector_24(certificate);
- entries.write_16(0);
- }
-
- writer certificate{};
- certificate.write_vector_8({});
- certificate.write_vector_24(entries.data());
- append(make_message(handshake::certificate, certificate.data()));
-
- // CertificateVerify (4.4.3).
- const auto content = verify_content(server_verify, transcript());
- writer verify{};
- if (context_.curve() == x509::curve::secp256r1)
- write_signature(verify, ecdsa_secp256r1_sha256,
- context_.key(), sha256_hash(content));
- else
- write_signature(verify, ecdsa_secp384r1_sha384,
- context_.key384(), accumulator::hash(content));
-
- append(make_message(handshake::certificate_verify, verify.data()));
-
- // Finished (4.4.4).
- const schedule keys{ suite_ };
- const auto verify_data = keys.finished(server_handshake_, transcript());
+ // Certificate (4.4.2), CertificateVerify (4.4.3), Finished (4.4.4).
+ append(make_certificate(context_.certificates()));
+ append(make_verify(server_verify));
+ const auto verify_data = schedule{ suite_ }.finished(server_handshake_,
+ transcript());
append(make_message(handshake::finished, verify_data));
send(content::handshake, messages);
// Application secrets follow the server finished (7.1).
- auto master = keys.master_secret(handshake_secret_);
- const auto hash = transcript();
- client_traffic_ = keys.derive_secret(master, "c ap traffic", hash);
- server_traffic_ = keys.derive_secret(master, "s ap traffic", hash);
- wipe(master.data(), master.size());
- send_.set_secret(suite_, server_traffic_);
-}
-
-void server::send(uint8_t type, const span& data) NOEXCEPT
-{
- for (size_t start{}; start < data.size(); start += maximum_plaintext)
- {
- const auto size = std::min(maximum_plaintext, data.size() - start);
- send_.seal(output_, type, data.subspan(start, size));
- }
+ derive_traffic();
+ set_send(server_traffic_);
}
// Client authentication.
@@ -826,32 +455,10 @@ void server::send(uint8_t type, const span& data) NOEXCEPT
bool server::handle_certificate(const span& message, const span& body) NOEXCEPT
{
- reader certificate{ body };
- const auto request_context = certificate.read_vector_8();
- reader entries{ certificate.read_vector_24() };
- if (!certificate.is_complete())
- return fail(alert::decode_error);
-
- if (!request_context.empty())
- return fail(alert::illegal_parameter);
-
+ uint8_t alert{};
x509::certificates chain{};
- while (entries && !entries.is_complete())
- {
- const auto der = entries.read_vector_24();
- entries.read_vector_16();
- if (!entries)
- return fail(alert::decode_error);
-
- x509::certificate value{};
- if (!x509::parse(value, der))
- return fail(alert::bad_certificate);
-
- chain.push_back(std::move(value));
- }
-
- if (!entries)
- return fail(alert::decode_error);
+ if (!parse_certificate(chain, alert, body))
+ return fail(alert);
add_transcript(message);
if (chain.empty())
@@ -882,29 +489,17 @@ bool server::handle_certificate_verify(const span& message,
if (!verify.is_complete())
return fail(alert::decode_error);
+ // The schemes of the CertificateRequest, by the curve of the leaf.
const auto& leaf = peer_.front();
- const auto content = verify_content(client_verify, transcript());
-
- auto valid = false;
- if ((scheme == ecdsa_secp256r1_sha256) &&
- (leaf.curve == x509::curve::secp256r1))
- {
- valid = verify_signature(leaf.public_key, signature,
- sha256_hash(content));
- }
- else if ((scheme == ecdsa_secp384r1_sha384) &&
- (leaf.curve == x509::curve::secp384r1))
- {
- const auto digest = accumulator::hash(content);
- valid = verify_signature(leaf.public_key, signature,
- digest);
- }
- else
- {
+ const auto ec = (leaf.key_type == x509::key_type::ec);
+ const auto p256 = ec && (scheme == ecdsa_secp256r1_sha256) &&
+ (leaf.curve == x509::curve::secp256r1);
+ const auto p384 = ec && (scheme == ecdsa_secp384r1_sha384) &&
+ (leaf.curve == x509::curve::secp384r1);
+ if (!p256 && !p384)
return fail(alert::illegal_parameter);
- }
- if (!valid)
+ if (!is_verified(leaf, scheme, signature, client_verify))
return fail(alert::decrypt_error);
add_transcript(message);
@@ -912,7 +507,7 @@ bool server::handle_certificate_verify(const span& message,
return true;
}
-// Finished and key update.
+// Finished.
// ----------------------------------------------------------------------------
bool server::handle_finished(const span& message, const span& body) NOEXCEPT
@@ -925,40 +520,11 @@ bool server::handle_finished(const span& message, const span& body) NOEXCEPT
add_transcript(message);
set_receive(client_traffic_);
- state_ = state::established;
- return true;
-}
-
-bool server::handle_key_update(const span& body) NOEXCEPT
-{
- if (body.size() != one)
- return fail(alert::decode_error);
-
- const auto request = body.front();
- if ((request != update_not_requested) && (request != update_requested))
- return fail(alert::illegal_parameter);
-
- client_traffic_ = schedule{ suite_ }.update(client_traffic_);
- set_receive(client_traffic_);
-
- if ((request == update_requested) && !close_sent_)
- send_update();
-
+ establish();
return true;
}
-// KeyUpdate under the current send key, then the next send key (4.6.3).
-void server::send_update() NOEXCEPT
-{
- writer update{};
- update.write_8(update_not_requested);
- send(content::handshake, make_message(handshake::key_update,
- update.data()));
- server_traffic_ = schedule{ suite_ }.update(server_traffic_);
- send_.set_secret(suite_, server_traffic_);
-}
-
-// Keys and transcript.
+// Keys.
// ----------------------------------------------------------------------------
bool server::exchange(data_chunk& shared, data_chunk& own,
@@ -983,22 +549,6 @@ bool server::exchange(data_chunk& shared, data_chunk& own,
return valid;
}
-void server::set_receive(const schedule::secret& traffic) NOEXCEPT
-{
- receive_.set_secret(suite_, traffic);
- ++receive_epoch_;
-}
-
-void server::add_transcript(const span& message) NOEXCEPT
-{
- transcript_.write(message);
-}
-
-schedule::secret server::transcript() const NOEXCEPT
-{
- return transcript_.hash();
-}
-
BC_POP_WARNING()
} // namespace tls
diff --git a/src/tls/stream.cpp b/src/tls/stream.cpp
index 3f1fabbd7..d59c8186e 100644
--- a/src/tls/stream.cpp
+++ b/src/tls/stream.cpp
@@ -33,12 +33,17 @@ BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
// Constructor.
// ----------------------------------------------------------------------------
-stream::stream(io::socket&& socket, const context& context) NOEXCEPT
+stream::stream(io::socket&& socket, const context& context,
+ bool as_server) NOEXCEPT
: socket_(std::move(socket)),
context_(context),
- server_(context),
input_(record_header_size + maximum_ciphertext)
{
+ // The connections are not movable, so are constructed in place.
+ if (as_server)
+ connection_ = &role_.emplace(context);
+ else
+ connection_ = &role_.emplace(context);
}
// Properties.
@@ -59,22 +64,44 @@ const io::socket& stream::next_layer() const NOEXCEPT
return socket_;
}
+const x509::certificates& stream::peer() const NOEXCEPT
+{
+ return connection_->peer();
+}
+
// Handshake.
// ----------------------------------------------------------------------------
void stream::async_handshake(result_handler&& handler) NOEXCEPT
{
- if (!context_.is_ready())
+ const auto ready = std::holds_alternative(role_) ?
+ context_.is_ready() : context_.is_client_ready();
+
+ if (!ready)
{
const code ec{ code{ error::tls_alert_internal_error } };
io::post(get_executor(), std::bind(std::move(handler), ec));
return;
}
- receive(std::bind(&stream::handle_handshake,
+ // A client sends its hello, a server has no output.
+ flush(std::bind(&stream::handle_hello,
this, _1, std::move(handler)));
}
+void stream::handle_hello(const code& ec,
+ const result_handler& handler) NOEXCEPT
+{
+ if (ec)
+ {
+ handler(ec);
+ return;
+ }
+
+ receive(std::bind(&stream::handle_handshake,
+ this, _1, handler));
+}
+
void stream::handle_handshake(const code& ec,
const result_handler& handler) NOEXCEPT
{
@@ -84,19 +111,19 @@ void stream::handle_handshake(const code& ec,
return;
}
- if (server_.is_failed())
+ if (connection_->is_failed())
{
handler(failure());
return;
}
- if (server_.is_closed())
+ if (connection_->is_closed())
{
handler(error::peer_disconnect);
return;
}
- if (server_.is_established())
+ if (connection_->is_established())
{
handler(error::success);
return;
@@ -133,19 +160,19 @@ bool stream::try_read(code& ec, size_t& size,
if (out.empty())
return true;
- if (is_nonzero(server_.readable()))
+ if (is_nonzero(connection_->readable()))
{
- size = server_.read(out);
+ size = connection_->read(out);
return true;
}
- if (server_.is_closed())
+ if (connection_->is_closed())
{
ec = error::peer_disconnect;
return true;
}
- if (server_.is_failed())
+ if (connection_->is_failed())
{
ec = failure();
return true;
@@ -189,9 +216,9 @@ void stream::do_write_some(const const_byte_span& data,
}
const auto size = std::min(data.size(), maximum_plaintext);
- if (!server_.write(data.first(size)))
+ if (!connection_->write(data.first(size)))
{
- const auto ec = server_.is_failed() ? failure() :
+ const auto ec = connection_->is_failed() ? failure() :
code{ error::connect_failed };
io::post(get_executor(), std::bind(handler, ec, zero));
@@ -217,13 +244,14 @@ size_t stream::do_write(const const_byte_span& data, code& ec) NOEXCEPT
return zero;
const auto size = std::min(data.size(), maximum_plaintext);
- if (!server_.write(data.first(size)))
+ if (!connection_->write(data.first(size)))
{
- ec = server_.is_failed() ? failure() : code{ error::connect_failed };
+ ec = connection_->is_failed() ? failure() :
+ code{ error::connect_failed };
return zero;
}
- auto& output = server_.output();
+ auto& output = connection_->output();
io::write(socket_, io::buffer(output), ec);
output.clear();
return ec ? zero : size;
@@ -234,14 +262,14 @@ size_t stream::do_write(const const_byte_span& data, code& ec) NOEXCEPT
void stream::async_shutdown(result_handler&& handler) NOEXCEPT
{
- if (server_.is_failed())
+ if (connection_->is_failed())
{
io::post(get_executor(),
std::bind(std::move(handler), code{ error::success }));
return;
}
- server_.close();
+ connection_->close();
flush(std::bind(&stream::handle_close_sent,
this, _1, std::move(handler)));
}
@@ -267,13 +295,13 @@ void stream::handle_close_received(const code& ec,
return;
}
- if (server_.is_failed())
+ if (connection_->is_failed())
{
handler(failure());
return;
}
- if (server_.is_closed())
+ if (connection_->is_closed())
{
handler(error::success);
return;
@@ -288,13 +316,13 @@ void stream::handle_close_received(const code& ec,
code stream::failure() const NOEXCEPT
{
- return code{ error::tls_to_error_code(server_.failure()) };
+ return code{ error::tls_to_error_code(connection_->failure()) };
}
// Closure of the transport without close_notify truncates the stream.
code stream::transport(const code& ec) const NOEXCEPT
{
- if (ec == error::peer_disconnect && !server_.is_closed())
+ if (ec == error::peer_disconnect && !connection_->is_closed())
return code{ error::tls_stream_truncated };
return ec;
@@ -329,8 +357,8 @@ void stream::handle_receive(const code& ec, size_t size) NOEXCEPT
return;
}
- server_.receive({ input_.data(), size });
- if (server_.output().empty())
+ connection_->receive({ input_.data(), size });
+ if (connection_->output().empty())
{
for (const auto& handler: handlers)
handler(error::success);
@@ -355,7 +383,7 @@ void stream::write_next() NOEXCEPT
std::vector handlers{};
handlers.swap(waiting_);
- auto& output = server_.output();
+ auto& output = connection_->output();
if (output.empty())
{
for (auto& handler: handlers)
diff --git a/test/tls/client.cpp b/test/tls/client.cpp
index 31809ed34..4c19a020d 100644
--- a/test/tls/client.cpp
+++ b/test/tls/client.cpp
@@ -16,575 +16,562 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see .
*/
-#include "client.hpp"
+#include "../test.hpp"
+#include "fixtures.hpp"
-#include
-#include
-
-namespace test {
+BC_AUTO_TEST_SUITE(tls_client_tests)
using namespace bc::system;
-using namespace network::tls;
-using reader = network::tls::reader;
-using writer = network::tls::writer;
+using namespace tls;
+
+const auto client_secret = base16_array("0101010101010101010101010101010101010101010101010101010101010101");
+const auto server_secret = base16_array("0202020202020202020202020202020202020202020202020202020202020202");
-constexpr size_t verify_padding = 64;
+// The legacy session id of a client hello record.
+static data_chunk session_of(const data_chunk& record)
+{
+ tls::reader source{ record };
+ source.read_bytes(record_header_size);
+ source.read_8();
+ source.read_24();
+ source.read_16();
+ source.read_bytes(sizeof(client::random));
+ const auto session = source.read_vector_8();
+ return { session.begin(), session.end() };
+}
-static data_chunk message_of(uint8_t type, const data_chunk& body)
+static data_chunk record_of(uint8_t type, const data_chunk& content)
{
- writer out{};
+ tls::writer out{};
out.write_8(type);
- out.write_vector_24(body);
+ out.write_16(legacy_version);
+ out.write_vector_16(content);
return out.data();
}
-static data_chunk verify_content(const std::string& label,
- const schedule::secret& hash)
+static data_chunk extension_of(uint16_t type, const data_chunk& data)
{
- const data_chunk padding(verify_padding, 0x20);
- const data_array separator{ 0x00 };
- return build_chunk({ padding, label, separator, hash });
+ tls::writer out{};
+ out.write_16(type);
+ out.write_vector_16(data);
+ return out.data();
}
-tls_client::tls_client(const options& value) NOEXCEPT
- : options_(value)
+static data_chunk versions_extension()
{
- maybe_random::fill(secret_);
- secret256_ = secp256r1::generate();
- secret384_ = secp384r1::generate();
- session_.resize(value.session);
- maybe_random::fill(session_);
+ return extension_of(extension::supported_versions, base16_chunk("0304"));
}
-data_chunk& tls_client::output() NOEXCEPT { return output_; }
-bool tls_client::is_established() const NOEXCEPT { return state_ == state::done; }
-bool tls_client::is_closed() const NOEXCEPT { return closed_; }
-bool tls_client::is_failed() const NOEXCEPT { return failed_; }
-uint8_t tls_client::failure() const NOEXCEPT { return failure_; }
-bool tls_client::is_retried() const NOEXCEPT { return retried_; }
-bool tls_client::is_requested() const NOEXCEPT { return requested_; }
-uint16_t tls_client::suite() const NOEXCEPT { return suite_; }
-
-void tls_client::start() NOEXCEPT
+static data_chunk share_extension(uint16_t group, const data_chunk& key)
{
- hello(false);
+ tls::writer share{};
+ share.write_16(group);
+ share.write_vector_16(key);
+ return extension_of(extension::key_share, share.data());
}
-void tls_client::hello(bool retry) NOEXCEPT
+static data_chunk retry_extension(uint16_t group)
{
- writer suites{};
- for (const auto suite: options_.suites)
- suites.write_16(suite);
-
- writer versions{};
- versions.write_16(version_13);
-
- writer groups{};
- for (const auto group: options_.groups)
- groups.write_16(group);
-
- writer algorithms{};
- for (const auto algorithm: options_.algorithms)
- algorithms.write_16(algorithm);
+ tls::writer share{};
+ share.write_16(group);
+ return extension_of(extension::key_share, share.data());
+}
- writer shares{};
- const auto shared = retry ? std::vector{ retry_group_ } : options_.shares;
- for (const auto group: shared)
- {
- shares.write_16(group);
- shares.write_vector_16(share(group));
- }
+static data_chunk cookie_extension(const data_chunk& cookie)
+{
+ tls::writer value{};
+ value.write_vector_16(cookie);
+ return extension_of(extension::cookie, value.data());
+}
- writer vector_versions{};
- vector_versions.write_vector_8(versions.data());
- writer vector_groups{};
- vector_groups.write_vector_16(groups.data());
- writer vector_algorithms{};
- vector_algorithms.write_vector_16(algorithms.data());
- writer vector_shares{};
- vector_shares.write_vector_16(shares.data());
-
- writer extensions{};
- extensions.write_16(extension::supported_versions);
- extensions.write_vector_16(vector_versions.data());
- extensions.write_16(extension::supported_groups);
- extensions.write_vector_16(vector_groups.data());
- extensions.write_16(extension::signature_algorithms);
- extensions.write_vector_16(vector_algorithms.data());
- extensions.write_16(extension::key_share);
- extensions.write_vector_16(vector_shares.data());
-
- data_array<32> random{};
- maybe_random::fill(random);
-
- writer body{};
- body.write_16(legacy_version);
+// ServerHello, or HelloRetryRequest by its random (4.1.3).
+static data_chunk hello_of(const data_chunk& session,
+ const data_chunk& extensions, const data_array<32>& random={},
+ uint16_t suite=aes_128_gcm_sha256, uint16_t version=legacy_version,
+ uint8_t compression=0)
+{
+ tls::writer body{};
+ body.write_16(version);
body.write_bytes(random);
- body.write_vector_8(session_);
- body.write_vector_16(suites.data());
- body.write_vector_8(data_array<1>{ 0x00 });
- body.write_vector_16(extensions.data());
-
- const auto message = message_of(handshake::client_hello, body.data());
- add(message);
- send_.seal(output_, content::handshake, message);
+ body.write_vector_8(session);
+ body.write_16(suite);
+ body.write_8(compression);
+ body.write_vector_16(extensions);
+ return message_of(handshake::server_hello, body.data());
}
-bool tls_client::fail(uint8_t alert) NOEXCEPT
+static data_chunk hello_record(const data_chunk& session,
+ const data_chunk& extensions, const data_array<32>& random={},
+ uint16_t suite=aes_128_gcm_sha256, uint16_t version=legacy_version,
+ uint8_t compression=0)
{
- if (failed_)
- return false;
-
- failed_ = true;
- failure_ = alert;
- const data_array<2> content{ alert_fatal, alert };
- send_.seal(output_, content::alert, content);
- return false;
+ const auto hello = hello_of(session, extensions, random, suite, version,
+ compression);
+ return record_of(content::handshake, hello);
}
-bool tls_client::receive(const const_byte_span& data) NOEXCEPT
+static data_chunk x25519_share()
{
- if (failed_)
- return false;
-
- input_.insert(input_.end(), data.begin(), data.end());
- while (!failed_ && !closed_ && input_.size() >= record_header_size)
- {
- reader header{ const_byte_span{ input_ }.first(record_header_size) };
- const auto type = header.read_8();
- header.read_16();
- const auto size = header.read_16();
- if (input_.size() < record_header_size + size)
- break;
-
- const auto head = data_chunk(input_.begin(), std::next(input_.begin(), record_header_size));
- const auto fragment = data_chunk(std::next(input_.begin(), record_header_size), std::next(input_.begin(), record_header_size + size));
- input_.erase(input_.begin(), std::next(input_.begin(), record_header_size + size));
-
- if (type == content::change_cipher_spec)
- continue;
-
- if (!receive_.is_protected())
- {
- if (!handle(type, fragment))
- return false;
-
- continue;
- }
-
- uint8_t inner{};
- data_chunk content{};
- if (!receive_.open(inner, content, head, fragment))
- return fail(alert::bad_record_mac);
-
- if (!handle(inner, content))
- return false;
- }
-
- return !failed_;
+ return data_chunk(x25519::key_size, 0x09);
}
-bool tls_client::handle(uint8_t type, const const_byte_span& content) NOEXCEPT
+// A client with a fixed x25519 key past a server hello for its share, and a
+// sender under the server handshake traffic secret.
+struct server_flight
{
- if (type == content::alert)
+ server_flight()
+ : client(setup.context, {}, client_secret)
{
- if ((content.size() == 2u) && (content[1] == alert::close_notify))
- {
- closed_ = true;
- return true;
- }
-
- failed_ = true;
- failure_ = content.size() == 2u ? content[1] : alert::decode_error;
- return false;
+ const auto hello = std::move(client.output());
+ client.output().clear();
+ const auto start = std::next(hello.begin(), record_header_size);
+ const data_chunk client_hello{ start, hello.end() };
+
+ x25519::key server_public{}, client_public{}, shared{};
+ x25519::multiply(server_public, server_secret);
+ x25519::multiply(client_public, client_secret);
+ x25519::multiply(shared, server_secret, client_public);
+
+ const auto share = share_extension(x25519_group,
+ to_chunk(server_public));
+ const auto extensions = splice(versions_extension(), share);
+ const auto server_hello = hello_of(session_of(hello), extensions);
+ BC_REQUIRE(client.receive(record_of(content::handshake,
+ server_hello)));
+
+ transcript.reset(aes_128_gcm_sha256);
+ transcript.write(client_hello);
+ transcript.write(server_hello);
+
+ const schedule keys{ aes_128_gcm_sha256 };
+ const auto secret = keys.handshake_secret(keys.early_secret(),
+ shared);
+ const auto traffic = keys.derive_secret(secret, "s hs traffic",
+ transcript.hash());
+ sender.set_secret(aes_128_gcm_sha256, traffic);
}
- if (type == content::application_data)
+ bool send(uint8_t type, const data_chunk& body)
{
- application_.insert(application_.end(), content.begin(), content.end());
- return true;
+ const auto message = message_of(type, body);
+ transcript.write(message);
+
+ data_chunk out{};
+ sender.seal(out, content::handshake, message);
+ return client.receive(out);
}
- if (type != content::handshake)
- return fail(alert::unexpected_message);
+ bool send_extensions(const data_chunk& extensions={})
+ {
+ tls::writer body{};
+ body.write_vector_16(extensions);
+ return send(handshake::encrypted_extensions, body.data());
+ }
- handshake_.insert(handshake_.end(), content.begin(), content.end());
- while (handshake_.size() >= 4u)
+ bool send_certificate()
{
- reader header{ const_byte_span{ handshake_ }.first(4) };
- const auto kind = header.read_8();
- const auto size = header.read_24();
- if (handshake_.size() < 4u + size)
- break;
-
- const auto message = data_chunk(handshake_.begin(), std::next(handshake_.begin(), 4u + size));
- handshake_.erase(handshake_.begin(), std::next(handshake_.begin(), 4u + size));
- const auto body = const_byte_span{ message }.subspan(4);
- if (!handle_message(kind, message, body))
- return false;
+ const auto& der = server_identity().certificate.encoding;
+ return send(handshake::certificate, certificate_of({}, entry_of(der)));
}
- return true;
+ client_setup setup{};
+ tls::client client;
+ record sender{};
+ tls::transcript transcript{};
+};
+
+// handshake
+
+BC_AUTO_TEST_CASE(tls_client__handshake__default__established)
+{
+ const server_setup setup{};
+ const client_setup config{};
+ tls::server server{ setup.context };
+ tls::client client{ config.context };
+ exchange(client, server);
+
+ BC_REQUIRE(client.is_established());
+ BC_REQUIRE(server.is_established());
+ BC_REQUIRE(!client.is_retried());
+ BC_REQUIRE(!client.is_requested());
+ BC_REQUIRE_EQUAL(client.suite(), aes_128_gcm_sha256);
+ BC_REQUIRE_EQUAL(client.group(), x25519_group);
+ BC_REQUIRE_EQUAL(client.peer().size(), 1u);
+ BC_REQUIRE_EQUAL(client.peer().front().encoding, server_identity().certificate.encoding);
}
-bool tls_client::handle_message(uint8_t type, const const_byte_span& message,
- const const_byte_span& body) NOEXCEPT
+BC_AUTO_TEST_CASE(tls_client__handshake__no_session__established)
{
- switch (state_)
- {
- case state::hello:
- if (type == handshake::server_hello)
- return handle_hello(message, body);
- break;
- case state::encrypted:
- if (type == handshake::encrypted_extensions)
- {
- add(message);
- state_ = state::certificate;
- return true;
- }
- break;
- case state::certificate:
- if (type == handshake::certificate_request)
- {
- add(message);
- requested_ = true;
- return true;
- }
- if (type == handshake::certificate)
- return handle_certificate(message, body);
- break;
- case state::verify:
- if (type == handshake::certificate_verify)
- return handle_verify(message, body);
- break;
- case state::finished:
- if (type == handshake::finished)
- return handle_finished(message, body);
- break;
- case state::done:
- if (type == handshake::key_update)
- {
- server_traffic_ = schedule{ suite_ }.update(server_traffic_);
- receive_.set_secret(suite_, server_traffic_);
- if (!body.empty() && (body.front() == 1u))
- update(false);
-
- return true;
- }
- break;
- }
+ const server_setup setup{};
+ client_setup config{};
+ auto offer = config.context.offered();
+ offer.session = 0;
+ config.context.set_offer(offer);
+ tls::server server{ setup.context };
+ tls::client client{ config.context };
+ exchange(client, server);
+
+ BC_REQUIRE(client.is_established());
+ BC_REQUIRE(server.is_established());
+}
- return fail(alert::unexpected_message);
+BC_AUTO_TEST_CASE(tls_client__handshake__server_name__sent_established)
+{
+ const server_setup setup{};
+ client_setup config{};
+ config.context.set_name("localhost");
+ tls::server server{ setup.context };
+ tls::client client{ config.context };
+ const auto name = to_chunk("localhost");
+ const auto& hello = client.output();
+ const auto sent = std::search(hello.begin(), hello.end(), name.begin(), name.end()) != hello.end();
+ exchange(client, server);
+
+ BC_REQUIRE(sent);
+ BC_REQUIRE(client.is_established());
}
-bool tls_client::handle_hello(const const_byte_span& message,
- const const_byte_span& body) NOEXCEPT
+BC_AUTO_TEST_CASE(tls_client__handshake__unanchored__peer_exposed)
{
- reader server_hello{ body };
- server_hello.read_16();
- const auto random = server_hello.read_bytes(32);
- server_hello.read_vector_8();
- suite_ = server_hello.read_16();
- server_hello.read_8();
- reader extensions{ server_hello.read_vector_16() };
- if (!server_hello.is_complete())
- return fail(alert::decode_error);
+ const server_setup setup{};
+ tls::context context{};
+ context.set_unanchored(true);
+ tls::server server{ setup.context };
+ tls::client client{ context };
+ exchange(client, server);
+
+ BC_REQUIRE(client.is_established());
+ BC_REQUIRE_EQUAL(client.peer().size(), 1u);
+ BC_REQUIRE_EQUAL(client.peer().front().encoding, server_identity().certificate.encoding);
+}
- if (std::equal(random.begin(), random.end(), retry_random.begin()))
- {
- if (retried_)
- return fail(alert::unexpected_message);
-
- while (extensions && !extensions.is_complete())
- {
- const auto type = extensions.read_16();
- reader data{ extensions.read_vector_16() };
- if (type == extension::key_share)
- retry_group_ = data.read_16();
- }
-
- retried_ = true;
- const auto first = hash();
- writer synthetic{};
- synthetic.write_8(handshake::message_hash);
- synthetic.write_vector_24(first);
- transcript_.clear();
- add(synthetic.data());
- add(message);
- hello(true);
- return true;
- }
+BC_AUTO_TEST_CASE(tls_client__handshake__untrusted__unknown_ca)
+{
+ const server_setup setup{};
+ const client_setup config{ make_identity(other_key, "other").chain };
+ tls::server server{ setup.context };
+ tls::client client{ config.context };
+ exchange(client, server);
+
+ BC_REQUIRE(client.is_failed());
+ BC_REQUIRE(!client.is_failure_received());
+ BC_REQUIRE_EQUAL(client.failure(), alert::unknown_ca);
+ BC_REQUIRE(server.is_failure_received());
+}
- uint16_t group{};
- const_byte_span peer{};
- while (extensions && !extensions.is_complete())
- {
- const auto type = extensions.read_16();
- reader data{ extensions.read_vector_16() };
- if (type == extension::key_share)
- {
- group = data.read_16();
- peer = data.read_vector_16();
- }
- }
+BC_AUTO_TEST_CASE(tls_client__handshake__no_share__retried_established)
+{
+ const server_setup setup{};
+ client_setup config{};
+ auto offer = config.context.offered();
+ offer.shares = {};
+ config.context.set_offer(offer);
+ tls::server server{ setup.context };
+ tls::client client{ config.context };
+ exchange(client, server);
+
+ BC_REQUIRE(client.is_retried());
+ BC_REQUIRE(client.is_established());
+ BC_REQUIRE_EQUAL(client.group(), x25519_group);
+}
- data_chunk shared{};
- if (!agree(shared, group, peer))
- return fail(alert::illegal_parameter);
-
- add(message);
- const schedule keys{ suite_ };
- handshake_secret_ = keys.handshake_secret(keys.early_secret(), shared);
- const auto transcript = hash();
- client_handshake_ = keys.derive_secret(handshake_secret_, "c hs traffic", transcript);
- server_handshake_ = keys.derive_secret(handshake_secret_, "s hs traffic", transcript);
- receive_.set_secret(suite_, server_handshake_);
- state_ = state::encrypted;
- return true;
-}
-
-bool tls_client::handle_certificate(const const_byte_span& message,
- const const_byte_span& body) NOEXCEPT
-{
- reader certificate{ body };
- certificate.read_vector_8();
- reader entries{ certificate.read_vector_24() };
- x509::certificates chain{};
- while (entries && !entries.is_complete())
- {
- const auto der = entries.read_vector_24();
- entries.read_vector_16();
- x509::certificate value{};
- if (!x509::parse(value, der))
- return fail(alert::bad_certificate);
+BC_AUTO_TEST_CASE(tls_client__handshake__requested_without_certificate__established)
+{
+ const server_setup setup{ true, false };
+ const client_setup config{};
+ tls::server server{ setup.context };
+ tls::client client{ config.context };
+ exchange(client, server);
+
+ BC_REQUIRE(client.is_requested());
+ BC_REQUIRE(client.is_established());
+ BC_REQUIRE(server.peer().empty());
+}
- chain.push_back(std::move(value));
- }
+BC_AUTO_TEST_CASE(tls_client__key_update__server_requested__both_keys_updated)
+{
+ const server_setup setup{};
+ const client_setup config{};
+ tls::server server{ setup.context };
+ tls::client client{ config.context };
+ exchange(client, server);
+
+ const auto updated = server.update(true);
+ exchange(client, server);
+
+ const auto request = to_chunk("after update");
+ const auto written = client.write(request) && server.write(request);
+ exchange(client, server);
+
+ BC_REQUIRE(updated);
+ BC_REQUIRE(written);
+ BC_REQUIRE_EQUAL(read_all(server), request);
+ BC_REQUIRE_EQUAL(read_all(client), request);
+}
- if (chain.empty())
- return fail(alert::decode_error);
+// server hello
- if (!options_.anchors.empty())
- {
- const auto time = is_zero(options_.time) ? chain.front().not_before : options_.time;
- if (x509::verify(chain, options_.anchors, time, x509::purpose::server))
- return fail(alert::bad_certificate);
- }
+BC_AUTO_TEST_CASE(tls_client__server_hello__session_mismatch__illegal_parameter)
+{
+ const client_setup config{};
+ tls::client client{ config.context };
+ const auto extensions = splice(versions_extension(), share_extension(x25519_group, x25519_share()));
+ BC_REQUIRE(!client.receive(hello_record(base16_chunk("00"), extensions)));
+ BC_REQUIRE_EQUAL(client.failure(), alert::illegal_parameter);
+}
- server_key_ = chain.front().public_key;
- add(message);
- state_ = state::verify;
- return true;
+BC_AUTO_TEST_CASE(tls_client__server_hello__unoffered_suite__illegal_parameter)
+{
+ const client_setup config{};
+ tls::client client{ config.context };
+ const auto session = session_of(client.output());
+ const auto extensions = splice(versions_extension(), share_extension(x25519_group, x25519_share()));
+ BC_REQUIRE(!client.receive(hello_record(session, extensions, {}, 0x1304)));
+ BC_REQUIRE_EQUAL(client.failure(), alert::illegal_parameter);
}
-bool tls_client::handle_verify(const const_byte_span& message,
- const const_byte_span& body) NOEXCEPT
+BC_AUTO_TEST_CASE(tls_client__server_hello__compression__illegal_parameter)
{
- reader verify{ body };
- const auto scheme = verify.read_16();
- const auto der = verify.read_vector_16();
- const auto content = verify_content("TLS 1.3, server CertificateVerify", hash());
+ const client_setup config{};
+ tls::client client{ config.context };
+ const auto session = session_of(client.output());
+ const auto extensions = splice(versions_extension(), share_extension(x25519_group, x25519_share()));
+ BC_REQUIRE(!client.receive(hello_record(session, extensions, {}, aes_128_gcm_sha256, legacy_version, 1)));
+ BC_REQUIRE_EQUAL(client.failure(), alert::illegal_parameter);
+}
- auto valid = false;
- if (scheme == ecdsa_secp256r1_sha256)
- {
- secp256r1::point_t point{};
- secp256r1::signature_t signature{};
- if ((server_key_.size() != point.size()) || !secp256r1::decode(signature, der))
- return fail(alert::illegal_parameter);
+BC_AUTO_TEST_CASE(tls_client__server_hello__legacy_version__protocol_version)
+{
+ const client_setup config{};
+ tls::client client{ config.context };
+ const auto session = session_of(client.output());
+ const auto extensions = splice(versions_extension(), share_extension(x25519_group, x25519_share()));
+ BC_REQUIRE(!client.receive(hello_record(session, extensions, {}, aes_128_gcm_sha256, 0x0302)));
+ BC_REQUIRE_EQUAL(client.failure(), alert::protocol_version);
+}
- std::copy(server_key_.cbegin(), server_key_.cend(), point.begin());
- valid = secp256r1::verify(signature, point, sha256_hash(content));
- }
- else if (scheme == ecdsa_secp384r1_sha384)
- {
- secp384r1::point_t point{};
- secp384r1::signature_t signature{};
- if ((server_key_.size() != point.size()) || !secp384r1::decode(signature, der))
- return fail(alert::illegal_parameter);
+BC_AUTO_TEST_CASE(tls_client__server_hello__without_supported_versions__protocol_version)
+{
+ const client_setup config{};
+ tls::client client{ config.context };
+ const auto session = session_of(client.output());
+ const auto extensions = share_extension(x25519_group, x25519_share());
+ BC_REQUIRE(!client.receive(hello_record(session, extensions)));
+ BC_REQUIRE_EQUAL(client.failure(), alert::protocol_version);
+}
- std::copy(server_key_.cbegin(), server_key_.cend(), point.begin());
- valid = secp384r1::verify(signature, point, accumulator::hash(content));
- }
- else
- {
- return fail(alert::illegal_parameter);
- }
+BC_AUTO_TEST_CASE(tls_client__server_hello__unsupported_extension__unsupported_extension)
+{
+ const client_setup config{};
+ tls::client client{ config.context };
+ const auto session = session_of(client.output());
+ const auto extensions = build_chunk({ versions_extension(), share_extension(x25519_group, x25519_share()), extension_of(extension::server_name, {}) });
+ BC_REQUIRE(!client.receive(hello_record(session, extensions)));
+ BC_REQUIRE_EQUAL(client.failure(), alert::unsupported_extension);
+}
- if (!valid)
- return fail(alert::decrypt_error);
+BC_AUTO_TEST_CASE(tls_client__server_hello__duplicate_extension__illegal_parameter)
+{
+ const client_setup config{};
+ tls::client client{ config.context };
+ const auto session = session_of(client.output());
+ const auto extensions = build_chunk({ versions_extension(), versions_extension(), share_extension(x25519_group, x25519_share()) });
+ BC_REQUIRE(!client.receive(hello_record(session, extensions)));
+ BC_REQUIRE_EQUAL(client.failure(), alert::illegal_parameter);
+}
- add(message);
- state_ = state::finished;
- return true;
+BC_AUTO_TEST_CASE(tls_client__server_hello__unshared_group__illegal_parameter)
+{
+ const client_setup config{};
+ tls::client client{ config.context };
+ const auto session = session_of(client.output());
+ const auto extensions = splice(versions_extension(), share_extension(secp256r1_group, x25519_share()));
+ BC_REQUIRE(!client.receive(hello_record(session, extensions)));
+ BC_REQUIRE_EQUAL(client.failure(), alert::illegal_parameter);
}
-bool tls_client::handle_finished(const const_byte_span& message,
- const const_byte_span& body) NOEXCEPT
+BC_AUTO_TEST_CASE(tls_client__server_hello__without_key_share__missing_extension)
{
- const schedule keys{ suite_ };
- const auto expected = keys.finished(server_handshake_, hash());
- if (!std::equal(body.begin(), body.end(), expected.begin(), expected.end()))
- return fail(alert::decrypt_error);
+ const client_setup config{};
+ tls::client client{ config.context };
+ const auto session = session_of(client.output());
+ BC_REQUIRE(!client.receive(hello_record(session, versions_extension())));
+ BC_REQUIRE_EQUAL(client.failure(), alert::missing_extension);
+}
- add(message);
- const auto master = keys.master_secret(handshake_secret_);
- const auto transcript = hash();
- client_traffic_ = keys.derive_secret(master, "c ap traffic", transcript);
- server_traffic_ = keys.derive_secret(master, "s ap traffic", transcript);
+BC_AUTO_TEST_CASE(tls_client__server_hello__truncated__decode_error)
+{
+ const client_setup config{};
+ tls::client client{ config.context };
+ const auto record = record_of(content::handshake, message_of(handshake::server_hello, base16_chunk("0303")));
+ BC_REQUIRE(!client.receive(record));
+ BC_REQUIRE_EQUAL(client.failure(), alert::decode_error);
+}
- send_.set_secret(suite_, client_handshake_);
- data_chunk flight{};
- if (requested_)
- {
- writer entries{};
- for (const auto& certificate: options_.chain)
- {
- entries.write_vector_24(certificate);
- entries.write_16(0);
- }
-
- writer certificate{};
- certificate.write_vector_8({});
- certificate.write_vector_24(entries.data());
- const auto certificate_message = message_of(handshake::certificate, certificate.data());
- add(certificate_message);
- flight.insert(flight.end(), certificate_message.begin(), certificate_message.end());
-
- if (!options_.chain.empty())
- {
- const auto content = verify_content("TLS 1.3, client CertificateVerify", hash());
- writer verify{};
- if (options_.key384)
- {
- secp384r1::signature_t signature{};
- secp384r1::sign(signature, *options_.key384, accumulator::hash(content));
- verify.write_16(ecdsa_secp384r1_sha384);
- verify.write_vector_16(secp384r1::encode(signature));
- }
- else
- {
- secp256r1::signature_t signature{};
- secp256r1::sign(signature, options_.key, sha256_hash(content));
- verify.write_16(ecdsa_secp256r1_sha256);
- verify.write_vector_16(secp256r1::encode(signature));
- }
-
- const auto verify_message = message_of(handshake::certificate_verify, verify.data());
- add(verify_message);
- flight.insert(flight.end(), verify_message.begin(), verify_message.end());
- }
- }
+// hello retry request
- const auto finished = message_of(handshake::finished, keys.finished(client_handshake_, hash()));
- add(finished);
- flight.insert(flight.end(), finished.begin(), finished.end());
- send_.seal(output_, content::handshake, flight);
+BC_AUTO_TEST_CASE(tls_client__retry__shared_group__illegal_parameter)
+{
+ const client_setup config{};
+ tls::client client{ config.context };
+ const auto session = session_of(client.output());
+ const auto extensions = splice(versions_extension(), retry_extension(x25519_group));
+ BC_REQUIRE(!client.receive(hello_record(session, extensions, retry_random)));
+ BC_REQUIRE_EQUAL(client.failure(), alert::illegal_parameter);
+}
- send_.set_secret(suite_, client_traffic_);
- receive_.set_secret(suite_, server_traffic_);
- state_ = state::done;
- return true;
+BC_AUTO_TEST_CASE(tls_client__retry__unoffered_group__illegal_parameter)
+{
+ client_setup config{};
+ auto offer = config.context.offered();
+ offer.groups = { x25519_group };
+ config.context.set_offer(offer);
+ tls::client client{ config.context };
+ const auto session = session_of(client.output());
+ const auto extensions = splice(versions_extension(), retry_extension(secp256r1_group));
+ BC_REQUIRE(!client.receive(hello_record(session, extensions, retry_random)));
+ BC_REQUIRE_EQUAL(client.failure(), alert::illegal_parameter);
}
-bool tls_client::write(const const_byte_span& data) NOEXCEPT
+BC_AUTO_TEST_CASE(tls_client__retry__unchanged__illegal_parameter)
{
- if (!is_established())
- return false;
+ const client_setup config{};
+ tls::client client{ config.context };
+ const auto session = session_of(client.output());
+ BC_REQUIRE(!client.receive(hello_record(session, versions_extension(), retry_random)));
+ BC_REQUIRE_EQUAL(client.failure(), alert::illegal_parameter);
+}
- send_.seal(output_, content::application_data, data);
- return true;
+BC_AUTO_TEST_CASE(tls_client__retry__twice__unexpected_message)
+{
+ const client_setup config{};
+ tls::client client{ config.context };
+ const auto session = session_of(client.output());
+ const auto first = splice(versions_extension(), retry_extension(secp256r1_group));
+ const auto second = splice(versions_extension(), retry_extension(secp384r1_group));
+ BC_REQUIRE(client.receive(hello_record(session, first, retry_random)));
+ BC_REQUIRE(!client.receive(hello_record(session, second, retry_random)));
+ BC_REQUIRE_EQUAL(client.failure(), alert::unexpected_message);
}
-data_chunk tls_client::read() NOEXCEPT
+BC_AUTO_TEST_CASE(tls_client__retry__cookie__echoed)
{
- auto out = std::move(application_);
- application_.clear();
- return out;
+ const client_setup config{};
+ tls::client client{ config.context };
+ const auto session = session_of(client.output());
+ client.output().clear();
+ const auto cookie = base16_chunk("c00c1e");
+ const auto extensions = build_chunk({ versions_extension(), retry_extension(secp256r1_group), cookie_extension(cookie) });
+ const auto received = client.receive(hello_record(session, extensions, retry_random));
+ const auto& hello = client.output();
+ const auto echoed = std::search(hello.begin(), hello.end(), cookie.begin(), cookie.end()) != hello.end();
+
+ BC_REQUIRE(received);
+ BC_REQUIRE(echoed);
+ BC_REQUIRE(client.is_retried());
}
-void tls_client::update(bool request) NOEXCEPT
+BC_AUTO_TEST_CASE(tls_client__server_hello__cookie__unsupported_extension)
{
- const data_array<1> value{ request ? uint8_t{ 1 } : uint8_t{ 0 } };
- send_.seal(output_, content::handshake, message_of(handshake::key_update, to_chunk(value)));
- client_traffic_ = schedule{ suite_ }.update(client_traffic_);
- send_.set_secret(suite_, client_traffic_);
+ const client_setup config{};
+ tls::client client{ config.context };
+ const auto session = session_of(client.output());
+ const auto extensions = build_chunk({ versions_extension(), share_extension(x25519_group, x25519_share()), cookie_extension(base16_chunk("c00c1e")) });
+ BC_REQUIRE(!client.receive(hello_record(session, extensions)));
+ BC_REQUIRE_EQUAL(client.failure(), alert::unsupported_extension);
}
-void tls_client::close() NOEXCEPT
+// encrypted server flight
+
+BC_AUTO_TEST_CASE(tls_client__encrypted_extensions__server_groups__accepted)
{
- const data_array<2> content{ alert_warning, alert::close_notify };
- send_.seal(output_, content::alert, content);
+ server_flight flight{};
+ tls::writer groups{};
+ groups.write_vector_16(base16_chunk("001d"));
+ BC_REQUIRE(flight.send_extensions(extension_of(extension::supported_groups, groups.data())));
+ BC_REQUIRE(!flight.client.is_failed());
}
-void tls_client::add(const const_byte_span& message) NOEXCEPT
+BC_AUTO_TEST_CASE(tls_client__encrypted_extensions__unrequested__unsupported_extension)
{
- transcript_.insert(transcript_.cend(), message.begin(), message.end());
+ server_flight flight{};
+ BC_REQUIRE(!flight.send_extensions(extension_of(16, base16_chunk("0000"))));
+ BC_REQUIRE_EQUAL(flight.client.failure(), alert::unsupported_extension);
}
-tls_client::secret tls_client::hash() NOEXCEPT
+BC_AUTO_TEST_CASE(tls_client__encrypted_extensions__unsent_server_name__unsupported_extension)
{
- return schedule{ suite_ }.hash(transcript_);
+ server_flight flight{};
+ BC_REQUIRE(!flight.send_extensions(extension_of(extension::server_name, {})));
+ BC_REQUIRE_EQUAL(flight.client.failure(), alert::unsupported_extension);
}
-data_chunk tls_client::share(uint16_t group) const NOEXCEPT
+BC_AUTO_TEST_CASE(tls_client__certificate__empty__decode_error)
{
- if (group == secp256r1_group)
- {
- secp256r1::point_t point{};
- secp256r1::public_key(point, secret256_);
- return to_chunk(point);
- }
+ server_flight flight{};
+ BC_REQUIRE(flight.send_extensions());
+ BC_REQUIRE(!flight.send(handshake::certificate, certificate_of({}, {})));
+ BC_REQUIRE_EQUAL(flight.client.failure(), alert::decode_error);
+}
- if (group == secp384r1_group)
- {
- secp384r1::point_t point{};
- secp384r1::public_key(point, secret384_);
- return to_chunk(point);
- }
+BC_AUTO_TEST_CASE(tls_client__certificate__request_context__illegal_parameter)
+{
+ server_flight flight{};
+ BC_REQUIRE(flight.send_extensions());
+ BC_REQUIRE(!flight.send(handshake::certificate, certificate_of(base16_chunk("01"), {})));
+ BC_REQUIRE_EQUAL(flight.client.failure(), alert::illegal_parameter);
+}
- x25519::key point{};
- x25519::multiply(point, secret_);
- return to_chunk(point);
+BC_AUTO_TEST_CASE(tls_client__certificate_request__without_algorithms__missing_extension)
+{
+ server_flight flight{};
+ BC_REQUIRE(flight.send_extensions());
+ BC_REQUIRE(!flight.send(handshake::certificate_request, base16_chunk("000000")));
+ BC_REQUIRE_EQUAL(flight.client.failure(), alert::missing_extension);
}
-bool tls_client::agree(data_chunk& shared, uint16_t group, const const_byte_span& peer) const NOEXCEPT
+BC_AUTO_TEST_CASE(tls_client__certificate_request__after_certificate__unexpected_message)
{
- if (group == secp256r1_group)
- {
- secp256r1::point_t point{};
- secp256r1::shared_t value{};
- if (peer.size() != point.size())
- return false;
-
- std::copy(peer.begin(), peer.end(), point.begin());
- const auto valid = secp256r1::agree(value, secret256_, point);
- shared = to_chunk(value);
- return valid;
- }
+ server_flight flight{};
+ BC_REQUIRE(flight.send_extensions());
+ BC_REQUIRE(flight.send_certificate());
+ BC_REQUIRE(!flight.send(handshake::certificate_request, base16_chunk("000000")));
+ BC_REQUIRE_EQUAL(flight.client.failure(), alert::unexpected_message);
+}
- if (group == secp384r1_group)
- {
- secp384r1::point_t point{};
- secp384r1::shared_t value{};
- if (peer.size() != point.size())
- return false;
-
- std::copy(peer.begin(), peer.end(), point.begin());
- const auto valid = secp384r1::agree(value, secret384_, point);
- shared = to_chunk(value);
- return valid;
- }
+BC_AUTO_TEST_CASE(tls_client__certificate_verify__unoffered_scheme__illegal_parameter)
+{
+ server_flight flight{};
+ BC_REQUIRE(flight.send_extensions());
+ BC_REQUIRE(flight.send_certificate());
+ BC_REQUIRE(!flight.send(handshake::certificate_verify, verify_of(0x0807, data_chunk(64, 0x01))));
+ BC_REQUIRE_EQUAL(flight.client.failure(), alert::illegal_parameter);
+}
- x25519::key point{}, value{};
- if (peer.size() != point.size())
- return false;
+BC_AUTO_TEST_CASE(tls_client__certificate_verify__invalid_signature__decrypt_error)
+{
+ server_flight flight{};
+ BC_REQUIRE(flight.send_extensions());
+ BC_REQUIRE(flight.send_certificate());
+ BC_REQUIRE(!flight.send(handshake::certificate_verify, verify_of(ecdsa_secp256r1_sha256, data_chunk(8, 0x01))));
+ BC_REQUIRE_EQUAL(flight.client.failure(), alert::decrypt_error);
+}
+
+BC_AUTO_TEST_CASE(tls_client__certificate_verify__rsa_scheme_ec_key__decrypt_error)
+{
+ server_flight flight{};
+ BC_REQUIRE(flight.send_extensions());
+ BC_REQUIRE(flight.send_certificate());
+ BC_REQUIRE(!flight.send(handshake::certificate_verify, verify_of(rsa_pss_rsae_sha256, data_chunk(256, 0x01))));
+ BC_REQUIRE_EQUAL(flight.client.failure(), alert::decrypt_error);
+}
- std::copy(peer.begin(), peer.end(), point.begin());
- const auto valid = x25519::multiply(value, secret_, point);
- shared = to_chunk(value);
- return valid;
+BC_AUTO_TEST_CASE(tls_client__finished__before_certificate__unexpected_message)
+{
+ server_flight flight{};
+ BC_REQUIRE(flight.send_extensions());
+ BC_REQUIRE(!flight.send(handshake::finished, data_chunk(32, 0x00)));
+ BC_REQUIRE_EQUAL(flight.client.failure(), alert::unexpected_message);
}
-} // namespace test
+BC_AUTO_TEST_SUITE_END()
diff --git a/test/tls/client.hpp b/test/tls/client.hpp
deleted file mode 100644
index d06496eae..000000000
--- a/test/tls/client.hpp
+++ /dev/null
@@ -1,128 +0,0 @@
-/**
- * Copyright (c) 2011-2026 libbitcoin developers
- *
- * This file is part of libbitcoin.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see .
- */
-#ifndef LIBBITCOIN_NETWORK_TEST_TLS_CLIENT_HPP
-#define LIBBITCOIN_NETWORK_TEST_TLS_CLIENT_HPP
-
-#include
-#include "../test.hpp"
-
-namespace test {
-
-/// Test harness TLS 1.3 client (in memory, not thread safe). Offers the
-/// suites, groups (with shares of some) and signature schemes of its options,
-/// verifies the server chain against anchors (if any) and its P-256 or P-384
-/// CertificateVerify, and optionally authenticates with a chain and its P-256
-/// (or P-384) key.
-class tls_client
-{
-public:
- struct options
- {
- std::vector suites{ network::tls::aes_128_gcm_sha256,
- network::tls::chacha20_poly1305_sha256 };
- std::vector groups{ network::tls::x25519_group,
- network::tls::secp256r1_group };
- std::vector shares{ network::tls::x25519_group };
- std::vector algorithms{ network::tls::ecdsa_secp256r1_sha256,
- network::tls::ecdsa_secp384r1_sha384 };
- size_t session{};
- system::x509::certificates anchors{};
- std::vector chain{};
- system::x509::secret key{};
- std::optional key384{};
- uint64_t time{};
- };
-
- tls_client(const options& value) NOEXCEPT;
-
- /// Produce the client hello into output.
- void start() NOEXCEPT;
-
- /// Consume server bytes. False once failed.
- bool receive(const const_byte_span& data) NOEXCEPT;
-
- system::data_chunk& output() NOEXCEPT;
- bool write(const const_byte_span& data) NOEXCEPT;
- system::data_chunk read() NOEXCEPT;
- void update(bool request) NOEXCEPT;
- void close() NOEXCEPT;
-
- bool is_established() const NOEXCEPT;
- bool is_closed() const NOEXCEPT;
- bool is_failed() const NOEXCEPT;
- uint8_t failure() const NOEXCEPT;
- bool is_retried() const NOEXCEPT;
- bool is_requested() const NOEXCEPT;
- uint16_t suite() const NOEXCEPT;
-
-private:
- typedef network::tls::schedule::secret secret;
-
- bool fail(uint8_t alert) NOEXCEPT;
- bool handle(uint8_t type, const const_byte_span& content) NOEXCEPT;
- bool handle_message(uint8_t type, const const_byte_span& message,
- const const_byte_span& body) NOEXCEPT;
- bool handle_hello(const const_byte_span& message,
- const const_byte_span& body) NOEXCEPT;
- bool handle_certificate(const const_byte_span& message,
- const const_byte_span& body) NOEXCEPT;
- bool handle_verify(const const_byte_span& message,
- const const_byte_span& body) NOEXCEPT;
- bool handle_finished(const const_byte_span& message,
- const const_byte_span& body) NOEXCEPT;
- void hello(bool retry) NOEXCEPT;
- system::data_chunk share(uint16_t group) const NOEXCEPT;
- bool agree(system::data_chunk& shared, uint16_t group,
- const const_byte_span& peer) const NOEXCEPT;
- void add(const const_byte_span& message) NOEXCEPT;
- secret hash() NOEXCEPT;
-
- enum class state { hello, encrypted, certificate, verify, finished, done };
-
- const options options_;
- system::x25519::key secret_{};
- system::secp256r1::secret_t secret256_{};
- system::secp384r1::secret_t secret384_{};
- system::data_chunk session_{};
- state state_{ state::hello };
- uint16_t suite_{};
- uint16_t retry_group_{};
- uint8_t failure_{};
- bool failed_{};
- bool closed_{};
- bool retried_{};
- bool requested_{};
- system::data_chunk server_key_{};
- system::data_chunk input_{};
- system::data_chunk handshake_{};
- system::data_chunk application_{};
- system::data_chunk output_{};
- network::tls::record send_{};
- network::tls::record receive_{};
- system::data_chunk transcript_{};
- secret handshake_secret_{};
- secret client_handshake_{};
- secret server_handshake_{};
- secret client_traffic_{};
- secret server_traffic_{};
-};
-
-} // namespace test
-
-#endif
diff --git a/test/tls/context.cpp b/test/tls/context.cpp
index bc977f0bb..b245ea839 100644
--- a/test/tls/context.cpp
+++ b/test/tls/context.cpp
@@ -220,6 +220,74 @@ BC_AUTO_TEST_CASE(tls_context__set_time__fixed__fixed)
BC_REQUIRE_EQUAL(context.time(), 42u);
}
+// client
+
+BC_AUTO_TEST_CASE(tls_context__construct__default__client_offer_not_ready)
+{
+ const tls::context context{};
+ const auto& offer = context.offered();
+ BC_REQUIRE_EQUAL(offer.suites.size(), 3u);
+ BC_REQUIRE_EQUAL(offer.groups.size(), 3u);
+ BC_REQUIRE_EQUAL(offer.shares.size(), 1u);
+ BC_REQUIRE_EQUAL(offer.shares.front(), x25519_group);
+ BC_REQUIRE_EQUAL(offer.algorithms.size(), 5u);
+ BC_REQUIRE_EQUAL(offer.session, 32u);
+ BC_REQUIRE(context.name().empty());
+ BC_REQUIRE(!context.unanchored());
+ BC_REQUIRE(!context.is_client_ready());
+}
+
+BC_AUTO_TEST_CASE(tls_context__set_offer__expected)
+{
+ tls::context context{};
+ tls::context::offer offer{};
+ offer.suites = { chacha20_poly1305_sha256 };
+ offer.session = 0;
+ context.set_offer(offer);
+ BC_REQUIRE_EQUAL(context.offered().suites.size(), 1u);
+ BC_REQUIRE_EQUAL(context.offered().suites.front(), chacha20_poly1305_sha256);
+ BC_REQUIRE_EQUAL(context.offered().session, 0u);
+}
+
+BC_AUTO_TEST_CASE(tls_context__set_name__expected)
+{
+ tls::context context{};
+ context.set_name("localhost");
+ BC_REQUIRE_EQUAL(context.name(), "localhost");
+}
+
+BC_AUTO_TEST_CASE(tls_context__set_unanchored__true__client_ready)
+{
+ tls::context context{};
+ context.set_unanchored(true);
+ BC_REQUIRE(context.unanchored());
+ BC_REQUIRE(context.is_client_ready());
+}
+
+BC_AUTO_TEST_CASE(tls_context__add_anchors__one__client_ready)
+{
+ tls::context context{};
+ BC_REQUIRE(context.add_anchors(certificate_of(key1)));
+ BC_REQUIRE(context.is_client_ready());
+}
+
+BC_AUTO_TEST_CASE(tls_context__set_chain__without_key__not_client_ready)
+{
+ tls::context context{};
+ BC_REQUIRE(context.add_anchors(certificate_of(key1)));
+ BC_REQUIRE(context.set_chain(certificate_of(key2)));
+ BC_REQUIRE(!context.is_client_ready());
+}
+
+BC_AUTO_TEST_CASE(tls_context__set_chain_and_key__anchored__client_ready)
+{
+ tls::context context{};
+ BC_REQUIRE(context.add_anchors(certificate_of(key1)));
+ BC_REQUIRE(context.set_chain(certificate_of(key2)));
+ BC_REQUIRE(context.set_key(x509::encode_private_key(key2), {}));
+ BC_REQUIRE(context.is_client_ready());
+}
+
BC_AUTO_TEST_CASE(tls_library__always__internal_tls)
{
BC_REQUIRE_EQUAL(tls_library(), "internal tls 1.3");
diff --git a/test/tls/fixtures.hpp b/test/tls/fixtures.hpp
new file mode 100644
index 000000000..c00ee1709
--- /dev/null
+++ b/test/tls/fixtures.hpp
@@ -0,0 +1,147 @@
+/**
+ * Copyright (c) 2011-2026 libbitcoin developers
+ *
+ * This file is part of libbitcoin.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+#ifndef LIBBITCOIN_NETWORK_TEST_TLS_FIXTURES_HPP
+#define LIBBITCOIN_NETWORK_TEST_TLS_FIXTURES_HPP
+
+#include "../test.hpp"
+
+constexpr uint64_t now = 1767225600;
+const auto server_key = system::base16_array("c9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721");
+const auto client_key = system::base16_array("0000000000000000000000000000000000000000000000000000000000000002");
+const auto other_key = system::base16_array("0000000000000000000000000000000000000000000000000000000000000003");
+
+struct identity
+{
+ std::string chain;
+ std::string key;
+ system::x509::certificate certificate;
+};
+
+inline identity make_identity(const system::x509::secret& key,
+ const std::string& name)
+{
+ system::x509::subject subject{};
+ subject.common_name = name;
+ subject.dns_names = { "localhost" };
+ subject.not_before = 1735689600;
+ subject.not_after = 2524608000;
+
+ system::data_chunk der{};
+ system::x509::build_self_signed(der, key, subject);
+
+ system::x509::certificate certificate{};
+ system::x509::parse(certificate, der);
+ const auto chain = system::x509::encode_certificate(der);
+ const auto secret = system::x509::encode_private_key(key);
+ return { chain, secret, certificate };
+}
+
+inline const identity& server_identity()
+{
+ static const auto value = make_identity(server_key, "server");
+ return value;
+}
+
+// A server context with the server identity, optionally requesting a client.
+struct server_setup
+{
+ server_setup(bool request=false, bool require=false)
+ {
+ context.set_chain(server_identity().chain);
+ context.set_key(server_identity().key, {});
+ context.set_verify(request, require);
+ context.set_time(now);
+ }
+
+ tls::context context{};
+};
+
+// A client context verifying the server identity, or the given chain.
+struct client_setup
+{
+ client_setup(const std::string& anchors=server_identity().chain)
+ {
+ context.add_anchors(anchors);
+ context.set_time(now);
+ }
+
+ tls::context context{};
+};
+
+// Move bytes between the peers until neither has output.
+inline void exchange(tls::client& client, tls::server& server)
+{
+ while (!client.output().empty() || !server.output().empty())
+ {
+ const auto to_server = std::move(client.output());
+ client.output().clear();
+ server.receive(to_server);
+
+ const auto to_client = std::move(server.output());
+ server.output().clear();
+ client.receive(to_client);
+ }
+}
+
+inline system::data_chunk read_all(tls::connection& connection)
+{
+ system::data_chunk out(connection.readable());
+ connection.read(out);
+ return out;
+}
+
+// Handshake messages.
+
+inline system::data_chunk message_of(uint8_t type,
+ const system::data_chunk& body)
+{
+ tls::writer out{};
+ out.write_8(type);
+ out.write_vector_24(body);
+ return out.data();
+}
+
+inline system::data_chunk entry_of(const system::data_chunk& der)
+{
+ tls::writer out{};
+ out.write_vector_24(der);
+ out.write_vector_16(system::data_chunk{});
+ return out.data();
+}
+
+inline system::data_chunk certificate_of(
+ const system::data_chunk& request_context,
+ const system::data_chunk& entries)
+{
+ tls::writer out{};
+ out.write_vector_8(request_context);
+ out.write_vector_24(entries);
+ return out.data();
+}
+
+inline system::data_chunk verify_of(uint16_t scheme,
+ const system::data_chunk& signature)
+{
+ tls::writer out{};
+ out.write_16(scheme);
+ out.write_vector_16(signature);
+ return out.data();
+}
+
+#endif
diff --git a/test/tls/server.cpp b/test/tls/server.cpp
index edfc54267..06e144356 100644
--- a/test/tls/server.cpp
+++ b/test/tls/server.cpp
@@ -17,19 +17,14 @@
* along with this program. If not, see .
*/
#include "../test.hpp"
-#include "client.hpp"
+#include "fixtures.hpp"
#include "rfc8448.hpp"
BC_AUTO_TEST_SUITE(tls_server_tests)
using namespace bc::system;
using namespace tls;
-using namespace test;
-
-constexpr uint64_t now = 1767225600;
-const auto server_key = base16_array("c9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721");
-const auto client_key = base16_array("0000000000000000000000000000000000000000000000000000000000000002");
-const auto other_key = base16_array("0000000000000000000000000000000000000000000000000000000000000003");
+using writer = network::tls::writer;
// A self-signed secp384r1 client identity (openssl).
const auto client384_key = base16_array("6bfc6ce1ef1beb42ecb60360242e9efab64189b1277c562b58eedad3b3586ff590179425f623bd9532ebd3091eb3cbb5");
@@ -50,49 +45,6 @@ const std::string client384_chain
"-----END CERTIFICATE-----\n"
};
-struct identity
-{
- std::string chain;
- std::string key;
- x509::certificate certificate;
-};
-
-static identity make_identity(const x509::secret& key, const std::string& name)
-{
- x509::subject subject{};
- subject.common_name = name;
- subject.dns_names = { "localhost" };
- subject.not_before = 1735689600;
- subject.not_after = 2524608000;
-
- data_chunk der{};
- x509::build_self_signed(der, key, subject);
-
- x509::certificate certificate{};
- x509::parse(certificate, der);
- return { x509::encode_certificate(der), x509::encode_private_key(key), certificate };
-}
-
-static const identity& server_identity()
-{
- static const auto value = make_identity(server_key, "server");
- return value;
-}
-
-// A server context with the server identity, optionally requesting a client.
-struct server_setup
-{
- server_setup(bool request=false, bool require=false)
- {
- context.set_chain(server_identity().chain);
- context.set_key(server_identity().key, {});
- context.set_verify(request, require);
- context.set_time(now);
- }
-
- tls::context context{};
-};
-
// The secp384r1 identity as a server.
static const identity& server384_identity()
{
@@ -120,44 +72,14 @@ struct server384_setup
tls::context context{};
};
-static tls_client::options client_options()
-{
- tls_client::options value{};
- value.anchors = { server_identity().certificate };
- value.time = now;
- return value;
-}
-
-// Move bytes between the peers until neither has output.
-static void exchange(tls_client& client, tls::server& server)
-{
- while (!client.output().empty() || !server.output().empty())
- {
- const auto to_server = std::move(client.output());
- client.output().clear();
- server.receive(to_server);
-
- const auto to_client = std::move(server.output());
- server.output().clear();
- client.receive(to_client);
- }
-}
-
-static data_chunk read_all(tls::server& server)
-{
- data_chunk out(server.readable());
- server.read(out);
- return out;
-}
-
// handshake
BC_AUTO_TEST_CASE(tls_server__handshake__default__established_aes)
{
const server_setup setup{};
tls::server server{ setup.context };
- tls_client client{ client_options() };
- client.start();
+ const client_setup config{};
+ tls::client client{ config.context };
exchange(client, server);
BC_REQUIRE(client.is_established());
BC_REQUIRE(server.is_established());
@@ -171,10 +93,11 @@ BC_AUTO_TEST_CASE(tls_server__handshake__chacha_only__established_chacha)
{
const server_setup setup{};
tls::server server{ setup.context };
- auto options = client_options();
- options.suites = { chacha20_poly1305_sha256 };
- tls_client client{ options };
- client.start();
+ client_setup config{};
+ auto offer = config.context.offered();
+ offer.suites = { chacha20_poly1305_sha256 };
+ config.context.set_offer(offer);
+ tls::client client{ config.context };
exchange(client, server);
BC_REQUIRE(server.is_established());
BC_REQUIRE_EQUAL(server.suite(), chacha20_poly1305_sha256);
@@ -184,10 +107,11 @@ BC_AUTO_TEST_CASE(tls_server__handshake__no_key_share__retried_established)
{
const server_setup setup{};
tls::server server{ setup.context };
- auto options = client_options();
- options.shares = {};
- tls_client client{ options };
- client.start();
+ client_setup config{};
+ auto offer = config.context.offered();
+ offer.shares = {};
+ config.context.set_offer(offer);
+ tls::client client{ config.context };
exchange(client, server);
BC_REQUIRE(client.is_retried());
BC_REQUIRE(client.is_established());
@@ -198,11 +122,12 @@ BC_AUTO_TEST_CASE(tls_server__handshake__compatibility_session__established)
{
const server_setup setup{};
tls::server server{ setup.context };
- auto options = client_options();
- options.session = 32;
- options.shares = {};
- tls_client client{ options };
- client.start();
+ client_setup config{};
+ auto offer = config.context.offered();
+ offer.session = 32;
+ offer.shares = {};
+ config.context.set_offer(offer);
+ tls::client client{ config.context };
exchange(client, server);
BC_REQUIRE(client.is_established());
BC_REQUIRE(server.is_established());
@@ -212,10 +137,11 @@ BC_AUTO_TEST_CASE(tls_server__handshake__no_common_suite__handshake_failure)
{
const server_setup setup{};
tls::server server{ setup.context };
- auto options = client_options();
- options.suites = { 0x1304 };
- tls_client client{ options };
- client.start();
+ client_setup config{};
+ auto offer = config.context.offered();
+ offer.suites = { 0x1304 };
+ config.context.set_offer(offer);
+ tls::client client{ config.context };
exchange(client, server);
BC_REQUIRE(server.is_failed());
BC_REQUIRE_EQUAL(server.failure(), alert::handshake_failure);
@@ -230,10 +156,11 @@ BC_AUTO_TEST_CASE(tls_server__handshake__aes256_only__established_aes256)
{
const server_setup setup{};
tls::server server{ setup.context };
- auto options = client_options();
- options.suites = { aes_256_gcm_sha384 };
- tls_client client{ options };
- client.start();
+ client_setup config{};
+ auto offer = config.context.offered();
+ offer.suites = { aes_256_gcm_sha384 };
+ config.context.set_offer(offer);
+ tls::client client{ config.context };
exchange(client, server);
BC_REQUIRE(server.is_established());
BC_REQUIRE_EQUAL(server.suite(), aes_256_gcm_sha384);
@@ -246,18 +173,19 @@ BC_AUTO_TEST_CASE(tls_server__handshake__aes256_only__established_aes256)
const data_chunk response(40000, 0x42);
BC_REQUIRE(server.write(response));
exchange(client, server);
- BC_REQUIRE_EQUAL(client.read(), response);
+ BC_REQUIRE_EQUAL(read_all(client), response);
}
BC_AUTO_TEST_CASE(tls_server__handshake__aes256_retried__established_aes256)
{
const server_setup setup{};
tls::server server{ setup.context };
- auto options = client_options();
- options.suites = { aes_256_gcm_sha384 };
- options.shares = {};
- tls_client client{ options };
- client.start();
+ client_setup config{};
+ auto offer = config.context.offered();
+ offer.suites = { aes_256_gcm_sha384 };
+ offer.shares = {};
+ config.context.set_offer(offer);
+ tls::client client{ config.context };
exchange(client, server);
BC_REQUIRE(client.is_retried());
BC_REQUIRE(server.is_established());
@@ -268,11 +196,12 @@ BC_AUTO_TEST_CASE(tls_server__handshake__secp256r1_share__established_secp256r1)
{
const server_setup setup{};
tls::server server{ setup.context };
- auto options = client_options();
- options.groups = { secp256r1_group };
- options.shares = { secp256r1_group };
- tls_client client{ options };
- client.start();
+ client_setup config{};
+ auto offer = config.context.offered();
+ offer.groups = { secp256r1_group };
+ offer.shares = { secp256r1_group };
+ config.context.set_offer(offer);
+ tls::client client{ config.context };
exchange(client, server);
BC_REQUIRE(!client.is_retried());
BC_REQUIRE(server.is_established());
@@ -283,11 +212,12 @@ BC_AUTO_TEST_CASE(tls_server__handshake__secp384r1_share__established_secp384r1)
{
const server_setup setup{};
tls::server server{ setup.context };
- auto options = client_options();
- options.groups = { secp384r1_group };
- options.shares = { secp384r1_group };
- tls_client client{ options };
- client.start();
+ client_setup config{};
+ auto offer = config.context.offered();
+ offer.groups = { secp384r1_group };
+ offer.shares = { secp384r1_group };
+ config.context.set_offer(offer);
+ tls::client client{ config.context };
exchange(client, server);
BC_REQUIRE(!client.is_retried());
BC_REQUIRE(server.is_established());
@@ -298,11 +228,12 @@ BC_AUTO_TEST_CASE(tls_server__handshake__nist_groups_no_share__retried_secp256r1
{
const server_setup setup{};
tls::server server{ setup.context };
- auto options = client_options();
- options.groups = { secp384r1_group, secp256r1_group };
- options.shares = {};
- tls_client client{ options };
- client.start();
+ client_setup config{};
+ auto offer = config.context.offered();
+ offer.groups = { secp384r1_group, secp256r1_group };
+ offer.shares = {};
+ config.context.set_offer(offer);
+ tls::client client{ config.context };
exchange(client, server);
BC_REQUIRE(client.is_retried());
BC_REQUIRE(server.is_established());
@@ -313,11 +244,12 @@ BC_AUTO_TEST_CASE(tls_server__handshake__share_of_less_preferred_group__not_retr
{
const server_setup setup{};
tls::server server{ setup.context };
- auto options = client_options();
- options.groups = { x25519_group, secp384r1_group };
- options.shares = { secp384r1_group };
- tls_client client{ options };
- client.start();
+ client_setup config{};
+ auto offer = config.context.offered();
+ offer.groups = { x25519_group, secp384r1_group };
+ offer.shares = { secp384r1_group };
+ config.context.set_offer(offer);
+ tls::client client{ config.context };
exchange(client, server);
BC_REQUIRE(!client.is_retried());
BC_REQUIRE(server.is_established());
@@ -328,10 +260,8 @@ BC_AUTO_TEST_CASE(tls_server__handshake__secp384r1_server__established)
{
const server384_setup setup{};
tls::server server{ setup.context };
- auto options = client_options();
- options.anchors = { server384_identity().certificate };
- tls_client client{ options };
- client.start();
+ client_setup config{ server384_identity().chain };
+ tls::client client{ config.context };
exchange(client, server);
BC_REQUIRE(client.is_established());
BC_REQUIRE(server.is_established());
@@ -341,14 +271,14 @@ BC_AUTO_TEST_CASE(tls_server__handshake__cnsa_client_secp384r1_server__establish
{
const server384_setup setup{};
tls::server server{ setup.context };
- auto options = client_options();
- options.anchors = { server384_identity().certificate };
- options.suites = { aes_256_gcm_sha384 };
- options.groups = { secp384r1_group };
- options.shares = { secp384r1_group };
- options.algorithms = { ecdsa_secp384r1_sha384 };
- tls_client client{ options };
- client.start();
+ client_setup config{ server384_identity().chain };
+ auto offer = config.context.offered();
+ offer.suites = { aes_256_gcm_sha384 };
+ offer.groups = { secp384r1_group };
+ offer.shares = { secp384r1_group };
+ offer.algorithms = { ecdsa_secp384r1_sha384 };
+ config.context.set_offer(offer);
+ tls::client client{ config.context };
exchange(client, server);
BC_REQUIRE(client.is_established());
BC_REQUIRE(server.is_established());
@@ -365,10 +295,11 @@ BC_AUTO_TEST_CASE(tls_server__handshake__cnsa_client_secp256r1_server__handshake
{
const server_setup setup{};
tls::server server{ setup.context };
- auto options = client_options();
- options.algorithms = { ecdsa_secp384r1_sha384 };
- tls_client client{ options };
- client.start();
+ client_setup config{};
+ auto offer = config.context.offered();
+ offer.algorithms = { ecdsa_secp384r1_sha384 };
+ config.context.set_offer(offer);
+ tls::client client{ config.context };
exchange(client, server);
BC_REQUIRE(server.is_failed());
BC_REQUIRE_EQUAL(server.failure(), alert::handshake_failure);
@@ -378,10 +309,11 @@ BC_AUTO_TEST_CASE(tls_server__key_update__aes256__both_keys_updated)
{
const server_setup setup{};
tls::server server{ setup.context };
- auto options = client_options();
- options.suites = { aes_256_gcm_sha384 };
- tls_client client{ options };
- client.start();
+ client_setup config{};
+ auto offer = config.context.offered();
+ offer.suites = { aes_256_gcm_sha384 };
+ config.context.set_offer(offer);
+ tls::client client{ config.context };
exchange(client, server);
client.update(true);
@@ -394,7 +326,7 @@ BC_AUTO_TEST_CASE(tls_server__key_update__aes256__both_keys_updated)
BC_REQUIRE(server.write(request));
exchange(client, server);
- BC_REQUIRE_EQUAL(client.read(), request);
+ BC_REQUIRE_EQUAL(read_all(client), request);
}
// application data, key update, close
@@ -403,8 +335,8 @@ BC_AUTO_TEST_CASE(tls_server__application_data__both_directions__expected)
{
const server_setup setup{};
tls::server server{ setup.context };
- tls_client client{ client_options() };
- client.start();
+ const client_setup config{};
+ tls::client client{ config.context };
exchange(client, server);
const auto request = to_chunk("GET / HTTP/1.1\r\n\r\n");
@@ -415,15 +347,15 @@ BC_AUTO_TEST_CASE(tls_server__application_data__both_directions__expected)
const data_chunk response(40000, 0x42);
BC_REQUIRE(server.write(response));
exchange(client, server);
- BC_REQUIRE_EQUAL(client.read(), response);
+ BC_REQUIRE_EQUAL(read_all(client), response);
}
BC_AUTO_TEST_CASE(tls_server__key_update__requested__both_keys_updated)
{
const server_setup setup{};
tls::server server{ setup.context };
- tls_client client{ client_options() };
- client.start();
+ const client_setup config{};
+ tls::client client{ config.context };
exchange(client, server);
client.update(true);
@@ -436,15 +368,15 @@ BC_AUTO_TEST_CASE(tls_server__key_update__requested__both_keys_updated)
BC_REQUIRE(server.write(request));
exchange(client, server);
- BC_REQUIRE_EQUAL(client.read(), request);
+ BC_REQUIRE_EQUAL(read_all(client), request);
}
BC_AUTO_TEST_CASE(tls_server__close__both_sides__closed)
{
const server_setup setup{};
tls::server server{ setup.context };
- tls_client client{ client_options() };
- client.start();
+ const client_setup config{};
+ tls::client client{ config.context };
exchange(client, server);
client.close();
@@ -491,8 +423,8 @@ BC_AUTO_TEST_CASE(tls_server__receive__tampered_record__bad_record_mac)
{
const server_setup setup{};
tls::server server{ setup.context };
- tls_client client{ client_options() };
- client.start();
+ const client_setup config{};
+ tls::client client{ config.context };
exchange(client, server);
BC_REQUIRE(client.write(to_chunk("data")));
@@ -517,8 +449,8 @@ BC_AUTO_TEST_CASE(tls_server__receive__split_records__established)
{
const server_setup setup{};
tls::server server{ setup.context };
- tls_client client{ client_options() };
- client.start();
+ const client_setup config{};
+ tls::client client{ config.context };
const auto hello = std::move(client.output());
client.output().clear();
@@ -562,11 +494,10 @@ BC_AUTO_TEST_CASE(tls_server__client_certificate__trusted__peer_verified)
setup.context.add_anchors(client_identity.chain);
tls::server server{ setup.context };
- auto options = client_options();
- options.chain = { client_identity.certificate.encoding };
- options.key = client_key;
- tls_client client{ options };
- client.start();
+ client_setup config{};
+ config.context.set_chain(client_identity.chain);
+ config.context.set_key(client_identity.key, {});
+ tls::client client{ config.context };
exchange(client, server);
BC_REQUIRE(client.is_requested());
BC_REQUIRE(server.is_established());
@@ -582,11 +513,10 @@ BC_AUTO_TEST_CASE(tls_server__client_certificate__secp384r1_trusted__peer_verifi
BC_REQUIRE(setup.context.add_anchors(client384_chain));
tls::server server{ setup.context };
- auto options = client_options();
- options.chain = { chain.front().encoding };
- options.key384 = client384_key;
- tls_client client{ options };
- client.start();
+ client_setup config{};
+ config.context.set_chain(client384_chain);
+ config.context.set_key(server384_identity().key, {});
+ tls::client client{ config.context };
exchange(client, server);
BC_REQUIRE(client.is_requested());
BC_REQUIRE(server.is_established());
@@ -598,8 +528,8 @@ BC_AUTO_TEST_CASE(tls_server__client_certificate__required_absent__certificate_r
{
server_setup setup{ true, true };
tls::server server{ setup.context };
- tls_client client{ client_options() };
- client.start();
+ const client_setup config{};
+ tls::client client{ config.context };
exchange(client, server);
BC_REQUIRE(server.is_failed());
BC_REQUIRE_EQUAL(server.failure(), alert::certificate_required);
@@ -609,8 +539,8 @@ BC_AUTO_TEST_CASE(tls_server__client_certificate__optional_absent__established)
{
server_setup setup{ true, false };
tls::server server{ setup.context };
- tls_client client{ client_options() };
- client.start();
+ const client_setup config{};
+ tls::client client{ config.context };
exchange(client, server);
BC_REQUIRE(server.is_established());
BC_REQUIRE(server.peer().empty());
@@ -624,11 +554,10 @@ BC_AUTO_TEST_CASE(tls_server__client_certificate__untrusted__unknown_ca)
setup.context.add_anchors(other_identity.chain);
tls::server server{ setup.context };
- auto options = client_options();
- options.chain = { client_identity.certificate.encoding };
- options.key = client_key;
- tls_client client{ options };
- client.start();
+ client_setup config{};
+ config.context.set_chain(client_identity.chain);
+ config.context.set_key(client_identity.key, {});
+ tls::client client{ config.context };
exchange(client, server);
BC_REQUIRE(server.is_failed());
BC_REQUIRE_EQUAL(server.failure(), alert::unknown_ca);
@@ -665,40 +594,6 @@ BC_AUTO_TEST_CASE(tls_server__receive__rfc8448_client_hello__rfc8448_server_hell
// protected client messages
-using writer = network::tls::writer;
-
-static data_chunk message_of(uint8_t type, const data_chunk& body)
-{
- writer out{};
- out.write_8(type);
- out.write_vector_24(body);
- return out.data();
-}
-
-static data_chunk entry_of(const data_chunk& der)
-{
- writer out{};
- out.write_vector_24(der);
- out.write_vector_16(data_chunk{});
- return out.data();
-}
-
-static data_chunk certificate_of(const data_chunk& request_context, const data_chunk& entries)
-{
- writer out{};
- out.write_vector_8(request_context);
- out.write_vector_24(entries);
- return out.data();
-}
-
-static data_chunk verify_of(uint16_t scheme, const data_chunk& signature)
-{
- writer out{};
- out.write_16(scheme);
- out.write_vector_16(signature);
- return out.data();
-}
-
// A server keyed by the rfc8448 client hello, with a client sender under the
// rfc8448 client handshake traffic secret.
struct rfc8448_setup
diff --git a/test/tls/socket.cpp b/test/tls/socket.cpp
index e7f0c4bfd..7b315c867 100644
--- a/test/tls/socket.cpp
+++ b/test/tls/socket.cpp
@@ -17,7 +17,6 @@
* along with this program. If not, see .
*/
#include "../test.hpp"
-#include "client.hpp"
#include
#include
@@ -146,14 +145,32 @@ struct server_fixture
std::future accepted{};
};
-// The harness client over a blocking loopback socket.
+// A client context verifying the server, optionally presenting a client
+// certificate.
+struct client_setup
+{
+ client_setup(const server_fixture& server, bool present)
+ {
+ using namespace system::x509;
+ context.add_anchors(encode_certificate(server.certificate.encoding));
+ context.set_time(1767225600);
+ if (!present)
+ return;
+
+ context.set_chain(encode_certificate(server.client.encoding));
+ context.set_key(encode_private_key(client_secret), {});
+ }
+
+ tls::context context{};
+};
+
+// The client over a blocking loopback socket.
struct tls_peer
{
- tls_peer(const test::tls_client::options& options, uint16_t port)
- : socket(io), client(options)
+ tls_peer(const server_fixture& server, bool present)
+ : setup(server, present), socket(io), client(setup.context)
{
- REQUIRE_SUCCESS(socket, connect, test::loopback(port));
- client.start();
+ REQUIRE_SUCCESS(socket, connect, test::loopback(server.port));
}
void flush()
@@ -201,7 +218,8 @@ struct tls_peer
BC_REQUIRE(!ec);
raw.insert(raw.cend(), buffer.cbegin(), std::next(buffer.cbegin(), count));
client.receive({ buffer.data(), count });
- const auto data = client.read();
+ system::data_chunk data(client.readable());
+ client.read(data);
out.insert(out.end(), data.begin(), data.end());
}
@@ -230,25 +248,13 @@ struct tls_peer
return false;
}
+ client_setup setup;
io::context io{};
io::socket socket;
- test::tls_client client;
+ tls::client client;
system::data_chunk raw{};
};
-static test::tls_client::options client_options(const server_fixture& server,
- bool present)
-{
- test::tls_client::options value{};
- value.anchors = { server.certificate };
- value.time = 1767225600;
- value.chain = present ?
- std::vector{ server.client.encoding } :
- std::vector{};
- value.key = client_secret;
- return value;
-}
-
static code tcp_write(const socket::ptr& server, const system::data_chunk& data)
{
const auto promise = std::make_shared>();
@@ -407,7 +413,7 @@ BC_AUTO_TEST_CASE(tls_socket__initialize_context__missing_authority_directory__t
BC_AUTO_TEST_CASE(tls_socket__accept__handshake_and_exchange__success)
{
server_fixture server{ false };
- tls_peer peer{ client_options(server, false), server.port };
+ tls_peer peer{ server, false };
peer.handshake();
BC_REQUIRE(peer.client.is_established());
BC_REQUIRE_EQUAL(server.accept_result(), error::success);
@@ -425,7 +431,7 @@ BC_AUTO_TEST_CASE(tls_socket__accept__handshake_and_exchange__success)
BC_AUTO_TEST_CASE(tls_socket__accept__response_of_many_records__exchanged)
{
server_fixture server{ false };
- tls_peer peer{ client_options(server, false), server.port };
+ tls_peer peer{ server, false };
peer.handshake();
BC_REQUIRE_EQUAL(server.accept_result(), error::success);
@@ -461,7 +467,7 @@ static size_t count_records(const system::data_chunk& raw)
BC_AUTO_TEST_CASE(tls_socket__accept__http_response__one_record)
{
server_fixture server{ false };
- tls_peer peer{ client_options(server, false), server.port };
+ tls_peer peer{ server, false };
peer.handshake();
BC_REQUIRE_EQUAL(server.accept_result(), error::success);
@@ -486,7 +492,7 @@ BC_AUTO_TEST_CASE(tls_socket__accept__http_response__one_record)
BC_AUTO_TEST_CASE(tls_socket__accept__trusted_client_certificate__success)
{
server_fixture server{ true };
- tls_peer peer{ client_options(server, true), server.port };
+ tls_peer peer{ server, true };
peer.handshake();
BC_REQUIRE(peer.client.is_requested());
BC_REQUIRE(peer.client.is_established());
@@ -496,7 +502,7 @@ BC_AUTO_TEST_CASE(tls_socket__accept__trusted_client_certificate__success)
BC_AUTO_TEST_CASE(tls_socket__accept__absent_client_certificate__failure)
{
server_fixture server{ true };
- tls_peer peer{ client_options(server, false), server.port };
+ tls_peer peer{ server, false };
peer.handshake();
BC_REQUIRE(peer.client.is_requested());
BC_REQUIRE_EQUAL(server.accept_result(), error::tls_alert_certificate_required);
@@ -505,7 +511,7 @@ BC_AUTO_TEST_CASE(tls_socket__accept__absent_client_certificate__failure)
BC_AUTO_TEST_CASE(tls_socket__lazy_stop__zero_connect_timeout__closed_without_close_notify)
{
server_fixture server{ false };
- tls_peer peer{ client_options(server, false), server.port };
+ tls_peer peer{ server, false };
peer.handshake();
BC_REQUIRE(peer.client.is_established());
BC_REQUIRE_EQUAL(server.accept_result(), error::success);
@@ -524,7 +530,7 @@ BC_AUTO_TEST_CASE(tls_socket__lazy_stop__zero_connect_timeout__closed_without_cl
BC_AUTO_TEST_CASE(tls_socket__lazy_stop__unanswered_connect_timeout__closed)
{
server_fixture server{ false, 100ms };
- tls_peer peer{ client_options(server, false), server.port };
+ tls_peer peer{ server, false };
peer.handshake();
const auto ec = server.accept_result();
BC_REQUIRE(ec == error::success || ec == error::operation_canceled);
@@ -540,7 +546,7 @@ BC_AUTO_TEST_CASE(tls_socket__lazy_stop__unanswered_connect_timeout__closed)
BC_AUTO_TEST_CASE(tls_socket__read__peer_close_notify__peer_disconnect)
{
server_fixture server{ false };
- tls_peer peer{ client_options(server, false), server.port };
+ tls_peer peer{ server, false };
peer.handshake();
BC_REQUIRE_EQUAL(server.accept_result(), error::success);
@@ -552,7 +558,7 @@ BC_AUTO_TEST_CASE(tls_socket__read__peer_close_notify__peer_disconnect)
BC_AUTO_TEST_CASE(tls_socket__read__transport_closed__tls_stream_truncated)
{
server_fixture server{ false };
- tls_peer peer{ client_options(server, false), server.port };
+ tls_peer peer{ server, false };
peer.handshake();
BC_REQUIRE_EQUAL(server.accept_result(), error::success);
@@ -563,7 +569,7 @@ BC_AUTO_TEST_CASE(tls_socket__read__transport_closed__tls_stream_truncated)
BC_AUTO_TEST_CASE(tls_socket__read__tampered_record__tls_alert_bad_record_mac)
{
server_fixture server{ false };
- tls_peer peer{ client_options(server, false), server.port };
+ tls_peer peer{ server, false };
peer.handshake();
BC_REQUIRE_EQUAL(server.accept_result(), error::success);
@@ -576,7 +582,7 @@ BC_AUTO_TEST_CASE(tls_socket__read__tampered_record__tls_alert_bad_record_mac)
BC_AUTO_TEST_CASE(tls_socket__read__requested_key_update__exchanged)
{
server_fixture server{ false };
- tls_peer peer{ client_options(server, false), server.port };
+ tls_peer peer{ server, false };
peer.handshake();
BC_REQUIRE_EQUAL(server.accept_result(), error::success);