diff --git a/builds/gnu/Makefile.am b/builds/gnu/Makefile.am index 91a89e755..b87cccacc 100644 --- a/builds/gnu/Makefile.am +++ b/builds/gnu/Makefile.am @@ -192,6 +192,9 @@ src_libbitcoin_network_la_SOURCES = \ ${srcdir}/../../src/tls/schedule.cpp \ ${srcdir}/../../src/tls/server.cpp \ ${srcdir}/../../src/tls/stream.cpp \ + ${srcdir}/../../src/tor/cell.cpp \ + ${srcdir}/../../src/tor/certificate.cpp \ + ${srcdir}/../../src/tor/link.cpp \ ${srcdir}/../../src/ws/frame.cpp \ ${srcdir}/../../src/ws/handshake.cpp \ ${srcdir}/../../src/ws/reader.cpp \ @@ -601,6 +604,16 @@ include_bitcoin_network_tls_HEADERS = \ ${srcdir}/../../include/bitcoin/network/tls/stream.hpp \ ${srcdir}/../../include/bitcoin/network/tls/tls.hpp +include_bitcoin_network_tordir = \ + ${includedir}/bitcoin/network/tor + +include_bitcoin_network_tor_HEADERS = \ + ${srcdir}/../../include/bitcoin/network/tor/cell.hpp \ + ${srcdir}/../../include/bitcoin/network/tor/certificate.hpp \ + ${srcdir}/../../include/bitcoin/network/tor/constants.hpp \ + ${srcdir}/../../include/bitcoin/network/tor/link.hpp \ + ${srcdir}/../../include/bitcoin/network/tor/tor.hpp + include_bitcoin_network_wsdir = \ ${includedir}/bitcoin/network/ws @@ -795,6 +808,9 @@ test_libbitcoin_network_test_SOURCES = \ ${srcdir}/../../test/tls/server.cpp \ ${srcdir}/../../test/tls/server_hello.cpp \ ${srcdir}/../../test/tls/socket.cpp \ + ${srcdir}/../../test/tor/cell.cpp \ + ${srcdir}/../../test/tor/certificate.cpp \ + ${srcdir}/../../test/tor/link.cpp \ ${srcdir}/../../test/ws/frame.cpp \ ${srcdir}/../../test/ws/handshake.cpp \ ${srcdir}/../../test/ws/reader.cpp \ 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 edb3d1238..fe73e225d 100644 --- a/builds/msvc/vs2026/libbitcoin-network-test/libbitcoin-network-test.vcxproj +++ b/builds/msvc/vs2026/libbitcoin-network-test/libbitcoin-network-test.vcxproj @@ -274,6 +274,9 @@ $(IntDir)test_tls_socket.obj + + + 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 ff368cad0..f5dcb147e 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 @@ -73,12 +73,15 @@ {D28FC18A-8B81-4247-0000-000000000006} - + {D28FC18A-8B81-4247-0000-000000000007} - + {D28FC18A-8B81-4247-0000-000000000008} + + {D28FC18A-8B81-4247-0000-000000000009} + @@ -537,6 +540,15 @@ src\tls + + src\tor + + + src\tor + + + src\tor + src\ws diff --git a/builds/msvc/vs2026/libbitcoin-network/libbitcoin-network.vcxproj b/builds/msvc/vs2026/libbitcoin-network/libbitcoin-network.vcxproj index ef8475844..5d0a8fcb0 100644 --- a/builds/msvc/vs2026/libbitcoin-network/libbitcoin-network.vcxproj +++ b/builds/msvc/vs2026/libbitcoin-network/libbitcoin-network.vcxproj @@ -279,6 +279,9 @@ $(IntDir)src_tls_stream.obj + + + @@ -489,6 +492,11 @@ + + + + + diff --git a/builds/msvc/vs2026/libbitcoin-network/libbitcoin-network.vcxproj.filters b/builds/msvc/vs2026/libbitcoin-network/libbitcoin-network.vcxproj.filters index dc1ec4228..df8eb27d4 100644 --- a/builds/msvc/vs2026/libbitcoin-network/libbitcoin-network.vcxproj.filters +++ b/builds/msvc/vs2026/libbitcoin-network/libbitcoin-network.vcxproj.filters @@ -112,72 +112,78 @@ {564EB540-D6B6-425C-0000-000000000004} - + {564EB540-D6B6-425C-0000-000000000005} - + {564EB540-D6B6-425C-0000-000000000006} - + {564EB540-D6B6-425C-0000-000000000007} - + {564EB540-D6B6-425C-0000-000000000008} - + {564EB540-D6B6-425C-0000-000000000009} - + {564EB540-D6B6-425C-0000-000000000010} - + {564EB540-D6B6-425C-0000-000000000011} - + {564EB540-D6B6-425C-0000-0000000000A2} - + {564EB540-D6B6-425C-0000-0000000000B2} - + {564EB540-D6B6-425C-0000-0000000000C2} - + {564EB540-D6B6-425C-0000-0000000000D2} - + {564EB540-D6B6-425C-0000-0000000000E2} - + {564EB540-D6B6-425C-0000-0000000000F2} - + {564EB540-D6B6-425C-0000-000000000003} - + {564EB540-D6B6-425C-0000-000000000004} - + {564EB540-D6B6-425C-0000-000000000005} - + {564EB540-D6B6-425C-0000-000000000006} - + {564EB540-D6B6-425C-0000-000000000007} - + {564EB540-D6B6-425C-0000-000000000008} - + {564EB540-D6B6-425C-0000-000000000009} - + {564EB540-D6B6-425C-0000-000000000010} - + {564EB540-D6B6-425C-0000-000000000011} + + {564EB540-D6B6-425C-0000-000000000012} + + + {564EB540-D6B6-425C-0000-0000000000A3} + @@ -612,6 +618,15 @@ src\tls + + src\tor + + + src\tor + + + src\tor + src\ws @@ -1220,6 +1235,21 @@ include\bitcoin\network\tls + + include\bitcoin\network\tor + + + include\bitcoin\network\tor + + + include\bitcoin\network\tor + + + include\bitcoin\network\tor + + + include\bitcoin\network\tor + include\bitcoin\network\ws diff --git a/include/bitcoin/network.hpp b/include/bitcoin/network.hpp index 2a02dedc7..d8daa766b 100644 --- a/include/bitcoin/network.hpp +++ b/include/bitcoin/network.hpp @@ -211,6 +211,11 @@ #include #include #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 index eaa4b439e..9bc0bd044 100644 --- a/include/bitcoin/network/tls/client.hpp +++ b/include/bitcoin/network/tls/client.hpp @@ -27,11 +27,10 @@ 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. +/// TLS 1.3 client connection (rfc8446), offer of context, no psk or early data. +/// Server authentication ECDSA P-256/P-384 or RSA-PSS (anchored or not), +/// optional client authentication (P-256/P-384). Sends client hello on +/// construction. Not thread safe. class BCT_API client final : public connection { @@ -41,7 +40,7 @@ class BCT_API client final typedef system::x25519::key key; typedef system::data_array<32> random; - /// The context must outlive the client. + /// Context must outlive client. client(const context& context) NOEXCEPT; /// Fixed client random and x25519 ephemeral secret (test vectors). @@ -49,10 +48,10 @@ class BCT_API client final const key& ephemeral) NOEXCEPT; ~client() NOEXCEPT override; - /// The server sent a HelloRetryRequest. + /// Server sent HelloRetryRequest. bool is_retried() const NOEXCEPT; - /// The server requested a client certificate. + /// Server requested client certificate. bool is_requested() const NOEXCEPT; protected: diff --git a/include/bitcoin/network/tls/connection.hpp b/include/bitcoin/network/tls/connection.hpp index b4fe0ed32..39e9640e7 100644 --- a/include/bitcoin/network/tls/connection.hpp +++ b/include/bitcoin/network/tls/connection.hpp @@ -28,20 +28,18 @@ 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. +/// TLS 1.3 connection (rfc8446) records, alerts, framing, data, key updates. +/// Handshake by client or server, transport bytes 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. + /// Consume transport bytes, false once failed (alert in output) or closed. bool receive(const const_byte_span& data) NOEXCEPT; - /// Transport bytes to be sent (the caller consumes them). + /// Transport bytes to send (caller consumes them). system::data_chunk& output() NOEXCEPT; /// Protect application data into output (once established). @@ -53,22 +51,22 @@ class BCT_API connection /// Received application bytes not yet read. size_t readable() const NOEXCEPT; - /// Queue a key update into output, optionally requesting the peer's. + /// Queue key update into output, optionally requesting peer's. bool update(bool request) NOEXCEPT; /// Queue close_notify into output (once). void close() NOEXCEPT; - /// The handshake is complete (peer finished verified). + /// Handshake complete (peer finished verified). bool is_established() const NOEXCEPT; - /// The peer sent close_notify. + /// 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. + /// Connection failed, alert sent or received. bool is_failed() const NOEXCEPT; uint8_t failure() const NOEXCEPT; bool is_failure_received() const NOEXCEPT; @@ -83,7 +81,7 @@ class BCT_API connection protected: typedef const_byte_span span; - /// The context must outlive the connection. + /// Context must outlive connection. connection(const context& context, bool server) NOEXCEPT; virtual ~connection() NOEXCEPT; @@ -98,18 +96,18 @@ class BCT_API connection 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). + /// CertificateVerify of transcript by context key (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). + /// True if leaf signed transcript by 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. + /// Role handshake of 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). + /// True if compatibility change_cipher_spec may be received (5). virtual bool is_handshaking() const NOEXCEPT = 0; /// Records and keys. @@ -125,7 +123,7 @@ class BCT_API connection void add_transcript(const span& message) NOEXCEPT; schedule::secret transcript() const NOEXCEPT; - /// Application traffic secrets (7.1), from the handshake secret. + /// Application traffic secrets (7.1) from handshake secret. void derive_traffic() NOEXCEPT; // Configuration. diff --git a/include/bitcoin/network/tls/context.hpp b/include/bitcoin/network/tls/context.hpp index 2fcfb60c0..9a8a5b916 100644 --- a/include/bitcoin/network/tls/context.hpp +++ b/include/bitcoin/network/tls/context.hpp @@ -26,9 +26,8 @@ namespace libbitcoin { namespace network { namespace tls { -/// Credentials and peer verification configuration, shared by the -/// connections of a server or of a client. Not thread safe during -/// configuration. +/// Credentials and peer verification, shared by server or client connections. +/// Not thread safe during configuration. class BCT_API context final { public: @@ -37,8 +36,7 @@ class BCT_API context final 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). + /// Client hello suites, groups, key share groups, schemes, session id size. struct offer { codes suites @@ -72,44 +70,42 @@ class BCT_API context final context() NOEXCEPT; ~context() NOEXCEPT; - /// Set the certificate chain (leaf first) from "CERTIFICATE" blocks, of a - /// P-256 or P-384 leaf, with later certificates passed through unparsed. - /// False if malformed or the key does not match. + /// Set chain (leaf first, P-256/P-384) from "CERTIFICATE" blocks, rest + /// unparsed, false if malformed or key mismatch. bool set_chain(const std::string& text) NOEXCEPT; - /// Set the P-256 or P-384 private key from a key block (encrypted if - /// password). False if malformed or the key does not match the chain. + /// Set P-256/P-384 key from block (encrypted if password), false if + /// malformed or chain mismatch. bool set_key(const std::string& text, const std::string& password) NOEXCEPT; /// Add verification anchors from "CERTIFICATE" blocks. bool add_anchors(const std::string& text) NOEXCEPT; - /// Peer verification (request a certificate, and require it). + /// Peer verification (request and require certificate). void set_verify(bool request, bool require) NOEXCEPT; - /// Fix the verification time (unix seconds), zero for the current time. + /// Fix verification time (unix seconds), zero for current time. void set_time(uint64_t seconds) NOEXCEPT; - /// The offer of a client. + /// Client offer. void set_offer(const offer& value) NOEXCEPT; - /// The server name sent by a client (sni), none if empty. + /// Server name sent by 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. + /// Client accepts any server certificate, bound by caller (e.g. Tor CERTS). void set_unanchored(bool value) NOEXCEPT; - /// True if the chain and key are set (server). + /// True if chain and key set (server). bool is_ready() const NOEXCEPT; - /// True if anchors are set or unanchored, and any chain has its key. + /// True if anchored 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. + /// Private key curve and key of that curve. system::x509::curve curve() const NOEXCEPT; const system::x509::secret& key() const NOEXCEPT; const system::x509::secret384& key384() const NOEXCEPT; diff --git a/include/bitcoin/network/tls/server.hpp b/include/bitcoin/network/tls/server.hpp index 950d67620..d397627b2 100644 --- a/include/bitcoin/network/tls/server.hpp +++ b/include/bitcoin/network/tls/server.hpp @@ -27,10 +27,10 @@ namespace libbitcoin { namespace network { 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. Not thread safe. +/// TLS 1.3 server connection (rfc8446), no psk or early data. +/// x25519/P-256/P-384 exchange, ECDSA P-256/P-384 server authentication, +/// optional client authentication (P-256/P-384), AES-GCM or ChaCha20-Poly1305. +/// Not thread safe. class BCT_API server final : public connection { diff --git a/include/bitcoin/network/tls/stream.hpp b/include/bitcoin/network/tls/stream.hpp index 7589bd599..6cc1cb464 100644 --- a/include/bitcoin/network/tls/stream.hpp +++ b/include/bitcoin/network/tls/stream.hpp @@ -31,11 +31,10 @@ namespace libbitcoin { namespace network { namespace tls { -/// 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 +/// TLS 1.3 server or client connection over tcp socket. +/// Read fills first non-empty buffer, write protects sequence as one record +/// (up to maximum_plaintext). Read records (alerts, key updates) are sent in +/// order with written records. Calls sequenced on socket executor; read and /// write chains may overlap each other but not themselves. class BCT_API stream { @@ -46,12 +45,11 @@ class BCT_API stream typedef std::function io_handler; using executor_type = io::socket::executor_type; - /// Assume ownership of the connected tcp socket, as server or client. - /// The context must outlive the stream. + /// Own connected tcp socket as server or client, context outlives stream. stream(io::socket&& socket, const context& context, bool as_server) NOEXCEPT; - /// The executor and the socket of the stream. + /// Stream executor and socket. executor_type get_executor() NOEXCEPT; io::socket& next_layer() NOEXCEPT; const io::socket& next_layer() const NOEXCEPT; @@ -59,7 +57,7 @@ class BCT_API stream /// Peer certificate chain (once the handshake completes). const system::x509::certificates& peer() const NOEXCEPT; - /// Perform the handshake (a client hello is sent first). + /// Perform handshake (client hello sent first). void async_handshake(result_handler&& handler) NOEXCEPT; /// Read received application bytes. @@ -70,12 +68,11 @@ class BCT_API stream template void async_write_some(const Buffers& buffers, Handler&& handler) NOEXCEPT; - /// Write application bytes (blocking), with no asynchronous - /// write in progress. + /// Write application bytes (blocking), no asynchronous write in progress. template size_t write_some(const Buffers& buffers, code& ec) NOEXCEPT; - /// Send close_notify and await the peer's. + /// Send close_notify, await peer's. void async_shutdown(result_handler&& handler) NOEXCEPT; private: diff --git a/include/bitcoin/network/tls/tls.hpp b/include/bitcoin/network/tls/tls.hpp index c50f16174..25295cc57 100644 --- a/include/bitcoin/network/tls/tls.hpp +++ b/include/bitcoin/network/tls/tls.hpp @@ -19,19 +19,18 @@ #ifndef LIBBITCOIN_NETWORK_TLS_TLS_HPP #define LIBBITCOIN_NETWORK_TLS_TLS_HPP -// TLS 1.3 server and client (rfc8446), the only protocol version supported. +// TLS 1.3 server and client (rfc8446), 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). -// Signing: ECDSA P-256 with SHA-256 or P-384 with SHA-384, by the key -// (constant time, rfc6979 nonce). -// 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. A client may be unanchored, leaving the -// server certificate to be bound by the caller. +// Key exchange: X25519, P-256, P-384 (HelloRetryRequest for preferred +// mutual group when client shares none). +// Signing: ECDSA P-256/SHA-256 or P-384/SHA-384 (constant time, +// rfc6979 nonce). +// Verify: ECDSA P-256/SHA-256, P-384/SHA-384, client also RSA-PSS +// with SHA-256/384/512. +// Trust: configured anchors only (no system store), self-signed +// allowed. Client may be unanchored, caller binds server. // Not supported: TLS 1.2 and earlier, RSA signing, Ed25519, resumption, // pre-shared keys, 0-RTT, OCSP and CRL. diff --git a/include/bitcoin/network/tor/cell.hpp b/include/bitcoin/network/tor/cell.hpp new file mode 100644 index 000000000..b7aba85e7 --- /dev/null +++ b/include/bitcoin/network/tor/cell.hpp @@ -0,0 +1,55 @@ +/** + * 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_TOR_CELL_HPP +#define LIBBITCOIN_NETWORK_TOR_CELL_HPP + +#include +#include + +namespace libbitcoin { +namespace network { +namespace tor { + +/// A channel cell (tor-spec 3): circuit id, command and payload. +struct cell +{ + uint32_t circuit{}; + uint8_t command{}; + system::data_chunk payload{}; +}; + +/// True if command has variable length payload (tor-spec 3). +constexpr bool is_variable(uint8_t value) NOEXCEPT +{ + return (value == command::versions) || (value >= command::vpadding); +} + +/// Encode cell, fixed payload zero padded, circuit id 4 or narrow 2 bytes. +BCT_API system::data_chunk encode(const cell& value, + bool narrow=false) NOEXCEPT; + +/// Decode cell at front of data, returning size, zero if data incomplete. +BCT_API size_t decode(cell& out, const_byte_span data, + bool narrow=false) NOEXCEPT; + +} // namespace tor +} // namespace network +} // namespace libbitcoin + +#endif diff --git a/include/bitcoin/network/tor/certificate.hpp b/include/bitcoin/network/tor/certificate.hpp new file mode 100644 index 000000000..c016e4bac --- /dev/null +++ b/include/bitcoin/network/tor/certificate.hpp @@ -0,0 +1,80 @@ +/** + * 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_TOR_CERTIFICATE_HPP +#define LIBBITCOIN_NETWORK_TOR_CERTIFICATE_HPP + +#include + +namespace libbitcoin { +namespace network { +namespace tor { + +/// Tor certificate (cert-spec 2.1), certified key signed by Ed25519 key. +struct certificate +{ + uint8_t type{}; + + /// Expiration, hours since unix epoch. + uint32_t expiration{}; + + uint8_t key_type{}; + system::ed25519::key key{}; + + /// Signing key, if included (extension 4). + bool has_signer{}; + system::ed25519::key signer{}; + + system::data_chunk signed_data{}; + system::ed25519::signature signature{}; +}; + +/// RSA identity certificate of Ed25519 identity (cert-spec 2.3). +struct crosscert +{ + system::ed25519::key key{}; + + /// Expiration, hours since unix epoch. + uint32_t expiration{}; + + system::data_chunk signed_data{}; + system::data_chunk signature{}; +}; + +/// Parse v1 certificate, false if malformed or unknown validating extension. +BCT_API bool parse(certificate& out, const_byte_span data) NOEXCEPT; + +/// Parse cross-certificate, false if malformed. +BCT_API bool parse(crosscert& out, const_byte_span data) NOEXCEPT; + +/// True if certificate signed by key. +BCT_API bool is_signed_by(const certificate& value, + const system::ed25519::key& key) NOEXCEPT; + +/// True if cross-certificate signed by RSA key. +BCT_API bool is_signed_by(const crosscert& value, + const system::rsa::public_key& key) NOEXCEPT; + +/// True if expiration (hours) not after time (unix seconds). +BCT_API bool is_expired(uint32_t expiration, uint64_t time) NOEXCEPT; + +} // namespace tor +} // namespace network +} // namespace libbitcoin + +#endif diff --git a/include/bitcoin/network/tor/constants.hpp b/include/bitcoin/network/tor/constants.hpp new file mode 100644 index 000000000..3106ac05c --- /dev/null +++ b/include/bitcoin/network/tor/constants.hpp @@ -0,0 +1,94 @@ +/** + * 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_TOR_CONSTANTS_HPP +#define LIBBITCOIN_NETWORK_TOR_CONSTANTS_HPP + +#include + +namespace libbitcoin { +namespace network { +namespace tor { + +/// Tor wire values (tor-spec, cert-spec). + +/// Link protocol versions (4: four byte circuit ids, 5: link padding). +constexpr std::array link_versions{ 4, 5 }; + +/// Cell sizes (tor-spec 3), VERSIONS cell has narrow circuit ids. +constexpr size_t narrow_circuit_size = 2; +constexpr size_t circuit_size = 4; +constexpr size_t payload_size = 509; + +/// Channel commands (tor-spec 3). +namespace command +{ + constexpr uint8_t padding = 0; + constexpr uint8_t create = 1; + constexpr uint8_t created = 2; + constexpr uint8_t relay = 3; + constexpr uint8_t destroy = 4; + constexpr uint8_t create_fast = 5; + constexpr uint8_t created_fast = 6; + constexpr uint8_t versions = 7; + constexpr uint8_t netinfo = 8; + constexpr uint8_t relay_early = 9; + constexpr uint8_t create2 = 10; + constexpr uint8_t created2 = 11; + constexpr uint8_t padding_negotiate = 12; + constexpr uint8_t vpadding = 128; + constexpr uint8_t certs = 129; + constexpr uint8_t auth_challenge = 130; + constexpr uint8_t authenticate = 131; + constexpr uint8_t authorize = 132; +} + +/// Certificate types of CERTS cell and Tor certificates (tor-spec 4.2). +namespace certificate_type +{ + constexpr uint8_t link_x509 = 1; + constexpr uint8_t rsa_identity = 2; + constexpr uint8_t authenticate_x509 = 3; + constexpr uint8_t identity_signing = 4; + constexpr uint8_t signing_link = 5; + constexpr uint8_t signing_authenticate = 6; + constexpr uint8_t rsa_crosscert = 7; +} + +/// Certified key types (cert-spec 2.1). +namespace key_type +{ + constexpr uint8_t ed25519 = 1; + constexpr uint8_t sha256_rsa = 2; + constexpr uint8_t sha256_x509 = 3; +} + +/// Certificate version, extension and flag (cert-spec 2.1, 2.2). +constexpr uint8_t certificate_version = 1; +constexpr uint8_t signed_with_ed25519 = 4; +constexpr uint8_t affects_validation = 1; + +/// NETINFO address types (tor-spec 4.5). +constexpr uint8_t address_ipv4 = 4; +constexpr uint8_t address_ipv6 = 6; + +} // namespace tor +} // namespace network +} // namespace libbitcoin + +#endif diff --git a/include/bitcoin/network/tor/link.hpp b/include/bitcoin/network/tor/link.hpp new file mode 100644 index 000000000..240ff2be3 --- /dev/null +++ b/include/bitcoin/network/tor/link.hpp @@ -0,0 +1,113 @@ +/** + * 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_TOR_LINK_HPP +#define LIBBITCOIN_NETWORK_TOR_LINK_HPP + +#include +#include +#include + +namespace libbitcoin { +namespace network { +namespace tor { + +/// Initiator link handshake (tor-spec 4) over TLS application data to relay. +/// Sends VERSIONS on construction, receives VERSIONS, CERTS (validated to +/// relay TLS certificate), AUTH_CHALLENGE (ignored) and NETINFO, then sends +/// NETINFO. Initiator does not authenticate. Not thread safe. +class BCT_API link +{ +public: + DELETE_COPY_MOVE(link); + + /// Reason for failed handshake. + enum class failure : uint8_t + { + none, + malformed, + unexpected, + version, + certificate, + expired + }; + + /// Relay TLS certificate sha256, relay address, validation time (unix). + link(const system::hash_digest& certificate, + const system::ip::address& relay, uint64_t time) NOEXCEPT; + + /// Consume received bytes, false once failed. + bool receive(const const_byte_span& data) NOEXCEPT; + + /// Bytes to send (caller consumes them). + system::data_chunk& output() NOEXCEPT; + + /// Bytes received after responder NETINFO (channel cells). + system::data_chunk& remainder() NOEXCEPT; + + bool is_established() const NOEXCEPT; + bool is_failed() const NOEXCEPT; + failure reason() const NOEXCEPT; + + /// Negotiated link protocol version. + uint16_t version() const NOEXCEPT; + + /// Relay identities, sha1 of der RSA key and Ed25519 key (established). + const system::short_hash& rsa_identity() const NOEXCEPT; + const system::ed25519::key& ed25519_identity() const NOEXCEPT; + +protected: + bool fail(failure value) NOEXCEPT; + bool handle_cell(const cell& value) NOEXCEPT; + bool handle_versions(const cell& value) NOEXCEPT; + bool handle_certs(const cell& value) NOEXCEPT; + bool handle_netinfo(const cell& value) NOEXCEPT; + void send_netinfo() NOEXCEPT; + +private: + enum class state + { + versions, + certs, + netinfo, + established + }; + + // Configuration. + const system::hash_digest certificate_; + const system::ip::address relay_; + const uint64_t time_; + + // State. + state state_{ state::versions }; + failure failure_{ failure::none }; + uint16_t version_{}; + bool challenged_{}; + system::short_hash rsa_identity_{}; + system::ed25519::key ed25519_identity_{}; + + // Buffers. + system::data_chunk input_{}; + system::data_chunk output_{}; +}; + +} // namespace tor +} // namespace network +} // namespace libbitcoin + +#endif diff --git a/include/bitcoin/network/tor/tor.hpp b/include/bitcoin/network/tor/tor.hpp new file mode 100644 index 000000000..7ac33184c --- /dev/null +++ b/include/bitcoin/network/tor/tor.hpp @@ -0,0 +1,27 @@ +/** + * 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_TOR_TOR_HPP +#define LIBBITCOIN_NETWORK_TOR_TOR_HPP + +#include +#include +#include +#include + +#endif diff --git a/src/net/socket_connect.cpp b/src/net/socket_connect.cpp index e7f429a2f..0cd1a8df4 100644 --- a/src/net/socket_connect.cpp +++ b/src/net/socket_connect.cpp @@ -324,7 +324,7 @@ void socket::do_upgrade(const result_handler& handler) NOEXCEPT // Extract to temporary to avoid dangling reference after destruction. auto socket = std::move(get_base()); - // TLS context is applied to the socket, the inbound side serving. + // TLS context applied to socket, inbound side serving. auto& stream = socket_.emplace(std::move(socket), std::get>(context_).get(), inbound_); diff --git a/src/tls/client.cpp b/src/tls/client.cpp index d00641efb..d89b71868 100644 --- a/src/tls/client.cpp +++ b/src/tls/client.cpp @@ -149,7 +149,7 @@ bool client::handle_message(uint8_t type, const span& message, if (type == handshake::key_update) return handle_key_update(body); - // Tickets are ignored, as there is no resumption (4.6.1). + // Tickets ignored, no resumption (4.6.1). if (type == handshake::new_session_ticket) return true; @@ -190,8 +190,7 @@ bool client::handle_message(uint8_t type, const span& message, // Client hello. // ---------------------------------------------------------------------------- -// ClientHello (4.1.2), the second after a HelloRetryRequest shares only its -// group and echoes any cookie. +// ClientHello (4.1.2), after HelloRetryRequest shares its group, echoes cookie. void client::send_hello() NOEXCEPT { const auto& offer = context_.offered(); @@ -261,8 +260,8 @@ void client::send_hello() NOEXCEPT 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). +// Compatibility mode (session id) sends once, unprotected, before second +// ClientHello or first protected record (D.4). void client::send_compatibility() NOEXCEPT { if (session_.empty() || compatibility_sent_) @@ -299,7 +298,7 @@ bool client::handle_server_hello(const span& message, const span& body) NOEXCEPT !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. + // Extensions unique and requested (4.2), retry may add cookie. std::vector seen{}; uint16_t selected{}, group{}; span cookie{}, exchange{}; @@ -385,7 +384,7 @@ bool client::handle_server_hello(const span& message, const span& body) NOEXCEPT server_handshake_ = keys.derive_secret(handshake_secret_, "s hs traffic", hash); - // All later client records, including alerts, are protected (5.1). + // Later client records, including alerts, are protected (5.1). send_compatibility(); set_send(client_handshake_); set_receive(server_handshake_); @@ -393,8 +392,7 @@ bool client::handle_server_hello(const span& message, const span& body) NOEXCEPT 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. +// HelloRetryRequest (4.1.4), once, unshared group or cookie, changing hello. bool client::handle_retry(const span& message, bool keyed, uint16_t group, const span& cookie) NOEXCEPT { @@ -408,7 +406,7 @@ bool client::handle_retry(const span& message, bool keyed, uint16_t group, if (!keyed && cookie.empty()) return fail(alert::illegal_parameter); - // The transcript restarts with a hash of the first client hello (4.4.1). + // Transcript restarts with hash of first client hello (4.4.1). transcript_.reset(suite_); const auto hash = schedule{ suite_ }.hash(hello_); writer synthetic{}; @@ -430,7 +428,7 @@ bool client::handle_retry(const span& message, bool keyed, uint16_t group, // Encrypted extensions. // ---------------------------------------------------------------------------- -// Only an acknowledgment of the server name, or the server groups (4.2). +// Only server name acknowledgment or server groups (4.2). bool client::handle_encrypted_extensions(const span& message, const span& body) NOEXCEPT { @@ -468,7 +466,7 @@ bool client::handle_encrypted_extensions(const span& message, // Server authentication. // ---------------------------------------------------------------------------- -// CertificateRequest (4.3.2), signature_algorithms is required. +// CertificateRequest (4.3.2), signature_algorithms required. bool client::handle_certificate_request(const span& message, const span& body) NOEXCEPT { @@ -508,7 +506,7 @@ bool client::handle_certificate_request(const span& message, if (algorithms.empty()) return fail(alert::missing_extension); - // Without an acceptable key the client sends an empty Certificate. + // Without acceptable key client sends empty Certificate. const auto scheme = (context_.curve() == x509::curve::secp256r1) ? ecdsa_secp256r1_sha256 : ecdsa_secp384r1_sha384; authenticate_ = context_.is_ready() && contains(algorithms, scheme); @@ -527,7 +525,7 @@ bool client::handle_certificate(const span& message, const span& body) NOEXCEPT if (chain.empty()) return fail(alert::decode_error); - // Unanchored, the leaf is bound to an identity by the caller. + // Unanchored, caller binds leaf to identity. if (!context_.unanchored()) { const auto ec = x509::verify(chain, context_.anchors(), @@ -573,7 +571,7 @@ bool client::handle_finished(const span& message, const span& body) NOEXCEPT !constant_time_equal(expected, body)) return fail(alert::decrypt_error); - // Application secrets follow the server finished (7.1). + // Application secrets follow server finished (7.1). add_transcript(message); derive_traffic(); send_flight(); @@ -612,7 +610,7 @@ void client::send_flight() NOEXCEPT // Keys. // ---------------------------------------------------------------------------- -// The key share of the group, the ephemeral key generated on first use. +// Group key share, ephemeral key generated on first use. data_chunk client::share(uint16_t group) NOEXCEPT { if (group == secp256r1_group) diff --git a/src/tls/connection.cpp b/src/tls/connection.cpp index 528c59201..8a95c3a5e 100644 --- a/src/tls/connection.cpp +++ b/src/tls/connection.cpp @@ -69,7 +69,7 @@ static void write_signature(writer& out, uint16_t scheme, out.write_vector_16(Curve::encode(signature)); } -// The content signed by CertificateVerify (4.4.3). +// Content signed by CertificateVerify (4.4.3). static data_chunk verify_content(std::string_view label, const schedule::secret& transcript) NOEXCEPT { @@ -168,7 +168,7 @@ 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). + // Send key rotated within AES-GCM record limit (5.5). if (send_.sequence() >= maximum_records) send_update(false); @@ -264,7 +264,7 @@ bool connection::receive(const const_byte_span& data) NOEXCEPT bool connection::handle_record(uint8_t type, const span& header, const span& fragment) NOEXCEPT { - // A compatibility change_cipher_spec is unprotected and ignored (5). + // Compatibility change_cipher_spec unprotected and ignored (5). if (type == content::change_cipher_spec) { if (!is_handshaking() || (!is_one(fragment.size())) || @@ -332,7 +332,7 @@ bool connection::handle_alert(const span& content) NOEXCEPT if (content.size() != two) return fail(alert::decode_error); - // Closure alerts are not errors (6.1). + // Closure alerts not errors (6.1). const auto description = content[one]; if (description == alert::close_notify) { @@ -376,7 +376,7 @@ bool connection::handle_handshake(const span& content) NOEXCEPT if (!handle_message(type, message, body)) return false; - // Handshake messages must not span a change of receive keys (5.1). + // Handshake messages must not span receive key change (5.1). if ((epoch != receive_epoch_) && !handshake_.empty()) return fail(alert::unexpected_message); } @@ -420,7 +420,7 @@ bool connection::handle_key_update(const span& body) NOEXCEPT return true; } -// KeyUpdate under the current send key, then the next send key (4.6.3). +// KeyUpdate under current send key, then next send key (4.6.3). void connection::send_update(bool request) NOEXCEPT { writer update{}; @@ -502,7 +502,7 @@ data_chunk connection::make_certificate(const context::chain& chain) NOEXCEPT return make_message(handshake::certificate, certificate.data()); } -// Certificate (4.4.2) of an empty request context, the chain may be empty. +// Certificate (4.4.2), empty request context, chain may be empty. bool connection::parse_certificate(x509::certificates& out, uint8_t& alert, const span& body) NOEXCEPT { diff --git a/src/tls/context.cpp b/src/tls/context.cpp index 9c93b04a8..dd975e711 100644 --- a/src/tls/context.cpp +++ b/src/tls/context.cpp @@ -63,7 +63,7 @@ bool context::set_chain(const std::string& text) NOEXCEPT !is_framed(block.data)) return false; - // The key of the leaf signs, by ECDSA only. + // Leaf key signs, ECDSA only. if (value.empty() && (leaf.key_type != x509::key_type::ec)) return false; diff --git a/src/tls/server.cpp b/src/tls/server.cpp index 40b849d25..b7af3f808 100644 --- a/src/tls/server.cpp +++ b/src/tls/server.cpp @@ -489,7 +489,7 @@ 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. + // CertificateRequest schemes by leaf curve. const auto& leaf = peer_.front(); const auto ec = (leaf.key_type == x509::key_type::ec); const auto p256 = ec && (scheme == ecdsa_secp256r1_sha256) && diff --git a/src/tls/stream.cpp b/src/tls/stream.cpp index d59c8186e..7112e1009 100644 --- a/src/tls/stream.cpp +++ b/src/tls/stream.cpp @@ -39,7 +39,7 @@ stream::stream(io::socket&& socket, const context& context, context_(context), input_(record_header_size + maximum_ciphertext) { - // The connections are not movable, so are constructed in place. + // Connections not movable, constructed in place. if (as_server) connection_ = &role_.emplace(context); else @@ -84,7 +84,7 @@ void stream::async_handshake(result_handler&& handler) NOEXCEPT return; } - // A client sends its hello, a server has no output. + // Client sends hello, server has no output. flush(std::bind(&stream::handle_hello, this, _1, std::move(handler))); } diff --git a/src/tor/cell.cpp b/src/tor/cell.cpp new file mode 100644 index 000000000..cc0b86da5 --- /dev/null +++ b/src/tor/cell.cpp @@ -0,0 +1,86 @@ +/** + * 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 + +// tor-spec 3 (cell packet format) + +namespace libbitcoin { +namespace network { +namespace tor { + +using namespace system; + +data_chunk encode(const cell& value, bool narrow) NOEXCEPT +{ + BC_ASSERT(is_variable(value.command) || + (value.payload.size() <= payload_size)); + + data_chunk out{}; + write::bytes::data sink(out); + if (narrow) + sink.write_2_bytes_big_endian(narrow_cast(value.circuit)); + else + sink.write_4_bytes_big_endian(value.circuit); + + sink.write_byte(value.command); + if (is_variable(value.command)) + { + const auto size = value.payload.size(); + sink.write_2_bytes_big_endian(possible_narrow_cast(size)); + sink.write_bytes(value.payload); + } + else + { + sink.write_bytes(value.payload); + sink.write_bytes(data_chunk(payload_size - value.payload.size())); + } + + sink.flush(); + return out; +} + +size_t decode(cell& out, const_byte_span data, bool narrow) NOEXCEPT +{ + read::bytes::copy source({ data.begin(), data.end() }); + const uint32_t circuit = narrow ? source.read_2_bytes_big_endian() : + source.read_4_bytes_big_endian(); + const auto command = source.read_byte(); + + size_t length{ payload_size }; + if (is_variable(command)) + length = source.read_2_bytes_big_endian(); + + auto payload = source.read_bytes(length); + if (!source) + return zero; + + // Circuit id, command and any length precede payload. + const auto circuit_bytes = narrow ? narrow_circuit_size : circuit_size; + const auto length_bytes = is_variable(command) ? sizeof(uint16_t) : zero; + + out = { circuit, command, std::move(payload) }; + return circuit_bytes + sizeof(command) + length_bytes + length; +} + +} // namespace tor +} // namespace network +} // namespace libbitcoin diff --git a/src/tor/certificate.cpp b/src/tor/certificate.cpp new file mode 100644 index 000000000..e23b22ea1 --- /dev/null +++ b/src/tor/certificate.cpp @@ -0,0 +1,124 @@ +/** + * 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 + +// cert-spec 2 (ed25519 certificates), 2.3 (rsa cross-certificate) + +namespace libbitcoin { +namespace network { +namespace tor { + +using namespace system; + +constexpr uint64_t seconds_per_hour = 3600; + +// Cross-certificate signs digest of this, key and expiration (cert-spec 2.3). +constexpr auto crosscert_prefix = to_array( + "Tor TLS RSA/Ed25519 cross-certificate"); + +bool parse(certificate& out, const_byte_span data) NOEXCEPT +{ + read::bytes::copy source({ data.begin(), data.end() }); + certificate value{}; + const auto version = source.read_byte(); + value.type = source.read_byte(); + value.expiration = source.read_4_bytes_big_endian(); + value.key_type = source.read_byte(); + value.key = source.read_forward(); + + // Some relays declare link certificate digest as a key (tor 40124). + if ((value.type == certificate_type::signing_link) && + (value.key_type == key_type::ed25519)) + value.key_type = key_type::sha256_x509; + + const auto extensions = source.read_byte(); + for (size_t index{}; index < extensions; ++index) + { + const auto size = source.read_2_bytes_big_endian(); + const auto type = source.read_byte(); + const auto flags = source.read_byte(); + const auto body = source.read_bytes(size); + if (type == signed_with_ed25519) + { + if (value.has_signer || (body.size() != ed25519::key_size)) + return false; + + std::copy(body.begin(), body.end(), value.signer.begin()); + value.has_signer = true; + } + else if (is_nonzero(bit_and(flags, affects_validation))) + { + return false; + } + } + + value.signature = source.read_forward(); + if (!source || !source.is_exhausted() || (version != certificate_version)) + return false; + + const auto end = std::prev(data.end(), ed25519::signature_size); + value.signed_data.assign(data.begin(), end); + out = std::move(value); + return true; +} + +bool parse(crosscert& out, const_byte_span data) NOEXCEPT +{ + read::bytes::copy source({ data.begin(), data.end() }); + crosscert value{}; + value.key = source.read_forward(); + value.expiration = source.read_4_bytes_big_endian(); + const auto size = source.read_byte(); + value.signature = source.read_bytes(size); + if (!source || !source.is_exhausted()) + return false; + + const auto signed_size = ed25519::key_size + sizeof(value.expiration); + const auto end = std::next(data.begin(), signed_size); + value.signed_data.assign(data.begin(), end); + out = std::move(value); + return true; +} + +bool is_signed_by(const certificate& value, + const ed25519::key& key) NOEXCEPT +{ + return ed25519::verify(value.signature, key, value.signed_data); +} + +bool is_signed_by(const crosscert& value, + const rsa::public_key& key) NOEXCEPT +{ + accumulator hasher{}; + hasher.write(crosscert_prefix); + hasher.write(value.signed_data); + return rsa::verify_pkcs1(key, value.signature, hasher.flush()); +} + +bool is_expired(uint32_t expiration, uint64_t time) NOEXCEPT +{ + return time >= (expiration * seconds_per_hour); +} + +} // namespace tor +} // namespace network +} // namespace libbitcoin diff --git a/src/tor/link.cpp b/src/tor/link.cpp new file mode 100644 index 000000000..a35d1c3f9 --- /dev/null +++ b/src/tor/link.cpp @@ -0,0 +1,322 @@ +/** + * 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 +#include + +// tor-spec 4 (negotiating and initializing channels) + +namespace libbitcoin { +namespace network { +namespace tor { + +using namespace system; + +static bool contains(const std::vector& list, uint8_t value) NOEXCEPT +{ + return std::find(list.cbegin(), list.cend(), value) != list.cend(); +} + +// Construct. +// ---------------------------------------------------------------------------- + +link::link(const hash_digest& certificate, const ip::address& relay, + uint64_t time) NOEXCEPT + : certificate_(certificate), relay_(relay), time_(time) +{ + data_chunk versions{}; + write::bytes::data sink(versions); + for (const auto version: link_versions) + sink.write_2_bytes_big_endian(version); + + sink.flush(); + output_ = encode({ zero, command::versions, versions }, true); +} + +// Properties. +// ---------------------------------------------------------------------------- + +data_chunk& link::output() NOEXCEPT +{ + return output_; +} + +data_chunk& link::remainder() NOEXCEPT +{ + return input_; +} + +bool link::is_established() const NOEXCEPT +{ + return state_ == state::established; +} + +bool link::is_failed() const NOEXCEPT +{ + return failure_ != failure::none; +} + +link::failure link::reason() const NOEXCEPT +{ + return failure_; +} + +uint16_t link::version() const NOEXCEPT +{ + return version_; +} + +const short_hash& link::rsa_identity() const NOEXCEPT +{ + return rsa_identity_; +} + +const ed25519::key& link::ed25519_identity() const NOEXCEPT +{ + return ed25519_identity_; +} + +// Cells. +// ---------------------------------------------------------------------------- + +bool link::fail(failure value) NOEXCEPT +{ + failure_ = value; + return false; +} + +bool link::receive(const const_byte_span& data) NOEXCEPT +{ + if (is_failed()) + return false; + + input_.insert(input_.end(), data.begin(), data.end()); + + // VERSIONS cell has narrow circuit ids (tor-spec 4.1). + size_t start{}; + while (!is_established() && !is_failed()) + { + cell value{}; + const auto available = const_byte_span{ input_ }.subspan(start); + const auto size = decode(value, available, state_ == state::versions); + if (is_zero(size)) + break; + + start += size; + handle_cell(value); + } + + input_.erase(input_.begin(), std::next(input_.begin(), start)); + return !is_failed(); +} + +// Responder sends VERSIONS, CERTS, AUTH_CHALLENGE, NETINFO, any padding. +bool link::handle_cell(const cell& value) NOEXCEPT +{ + const auto padding = (value.command == command::padding) || + (value.command == command::vpadding); + + switch (state_) + { + case state::versions: + { + if (value.command == command::versions) + return handle_versions(value); + + break; + } + case state::certs: + { + if (padding) + return true; + + if (value.command == command::certs) + return handle_certs(value); + + break; + } + case state::netinfo: + { + if (padding) + return true; + + if (!challenged_ && (value.command == command::auth_challenge)) + { + challenged_ = true; + return true; + } + + if (value.command == command::netinfo) + return handle_netinfo(value); + + break; + } + default: + { + break; + } + } + + return fail(failure::unexpected); +} + +// Highest version offered by both (tor-spec 4.1). +bool link::handle_versions(const cell& value) NOEXCEPT +{ + const auto& payload = value.payload; + if (is_odd(payload.size())) + return fail(failure::malformed); + + read::bytes::copy source(payload); + while (!source.is_exhausted()) + { + const auto offered = source.read_2_bytes_big_endian(); + if (std::find(link_versions.cbegin(), link_versions.cend(), offered) + != link_versions.cend()) + version_ = std::max(version_, offered); + } + + if (is_zero(version_)) + return fail(failure::version); + + state_ = state::certs; + return true; +} + +// Responder chain (tor-spec 4.2): Ed25519 identity certifies signing key, +// signing key certifies TLS certificate digest, RSA identity certifies +// Ed25519 identity. +bool link::handle_certs(const cell& value) NOEXCEPT +{ + read::bytes::copy source(value.payload); + const auto count = source.read_byte(); + std::vector types{}; + std::array bodies{}; + for (size_t index{}; index < count; ++index) + { + const auto type = source.read_byte(); + const auto size = source.read_2_bytes_big_endian(); + auto body = source.read_bytes(size); + if (!source) + return fail(failure::malformed); + + if (contains(types, type)) + return fail(failure::certificate); + + types.push_back(type); + if (type < bodies.size()) + bodies.at(type) = std::move(body); + } + + if (!source.is_exhausted()) + return fail(failure::malformed); + + x509::certificate identity{}; + rsa::public_key rsa_key{}; + if (!x509::parse(identity, bodies.at(certificate_type::rsa_identity)) || + (identity.key_type != x509::key_type::rsa) || + !rsa::decode(rsa_key, identity.public_key)) + return fail(failure::certificate); + + certificate signing{}; + if (!parse(signing, bodies.at(certificate_type::identity_signing)) || + (signing.type != certificate_type::identity_signing) || + (signing.key_type != key_type::ed25519) || !signing.has_signer || + !is_signed_by(signing, signing.signer)) + return fail(failure::certificate); + + certificate binding{}; + if (!parse(binding, bodies.at(certificate_type::signing_link)) || + (binding.type != certificate_type::signing_link) || + (binding.key_type != key_type::sha256_x509) || + (binding.key != certificate_) || !is_signed_by(binding, signing.key)) + return fail(failure::certificate); + + crosscert cross{}; + if (!parse(cross, bodies.at(certificate_type::rsa_crosscert)) || + (cross.key != signing.signer) || !is_signed_by(cross, rsa_key)) + return fail(failure::certificate); + + if (is_expired(signing.expiration, time_) || + is_expired(binding.expiration, time_) || + is_expired(cross.expiration, time_)) + return fail(failure::expired); + + rsa_identity_ = sha1_hash(identity.public_key); + ed25519_identity_ = signing.signer; + state_ = state::netinfo; + return true; +} + +// Responder time and addresses unused (tor-spec 4.5). +bool link::handle_netinfo(const cell& value) NOEXCEPT +{ + read::bytes::copy source(value.payload); + source.read_4_bytes_big_endian(); + source.read_byte(); + source.skip_bytes(source.read_byte()); + const auto addresses = source.read_byte(); + for (size_t index{}; index < addresses; ++index) + { + source.read_byte(); + source.skip_bytes(source.read_byte()); + } + + if (!source) + return fail(failure::malformed); + + send_netinfo(); + state_ = state::established; + return true; +} + +// Client sends no time and no own addresses (tor-spec 4.5). +void link::send_netinfo() NOEXCEPT +{ + data_chunk payload{}; + write::bytes::data sink(payload); + sink.write_4_bytes_big_endian(0); + if (relay_.is_v4()) + { + const auto& bytes = relay_.to_v4().to_bytes(); + sink.write_byte(address_ipv4); + sink.write_byte(possible_narrow_cast(bytes.size())); + sink.write_bytes(bytes); + } + else + { + const auto& bytes = relay_.to_v6().to_bytes(); + sink.write_byte(address_ipv6); + sink.write_byte(possible_narrow_cast(bytes.size())); + sink.write_bytes(bytes); + } + + sink.write_byte(0); + sink.flush(); + + const auto netinfo = encode({ zero, command::netinfo, payload }); + output_.insert(output_.end(), netinfo.begin(), netinfo.end()); +} + +} // namespace tor +} // namespace network +} // namespace libbitcoin diff --git a/test/tls/client.cpp b/test/tls/client.cpp index 4c19a020d..70b397a9f 100644 --- a/test/tls/client.cpp +++ b/test/tls/client.cpp @@ -27,7 +27,7 @@ using namespace tls; const auto client_secret = base16_array("0101010101010101010101010101010101010101010101010101010101010101"); const auto server_secret = base16_array("0202020202020202020202020202020202020202020202020202020202020202"); -// The legacy session id of a client hello record. +// Legacy session id of client hello record. static data_chunk session_of(const data_chunk& record) { tls::reader source{ record }; @@ -115,8 +115,7 @@ static data_chunk x25519_share() return data_chunk(x25519::key_size, 0x09); } -// A client with a fixed x25519 key past a server hello for its share, and a -// sender under the server handshake traffic secret. +// Client (fixed x25519) past server hello, sender under server handshake key. struct server_flight { server_flight() diff --git a/test/tls/fixtures.hpp b/test/tls/fixtures.hpp index c00ee1709..22d44b571 100644 --- a/test/tls/fixtures.hpp +++ b/test/tls/fixtures.hpp @@ -58,7 +58,7 @@ inline const identity& server_identity() return value; } -// A server context with the server identity, optionally requesting a client. +// Server context with server identity, optionally requesting client. struct server_setup { server_setup(bool request=false, bool require=false) @@ -72,7 +72,7 @@ struct server_setup tls::context context{}; }; -// A client context verifying the server identity, or the given chain. +// Client context verifying server identity, or given chain. struct client_setup { client_setup(const std::string& anchors=server_identity().chain) @@ -84,7 +84,7 @@ struct client_setup tls::context context{}; }; -// Move bytes between the peers until neither has output. +// Move bytes between peers until neither has output. inline void exchange(tls::client& client, tls::server& server) { while (!client.output().empty() || !server.output().empty()) diff --git a/test/tls/socket.cpp b/test/tls/socket.cpp index 7b315c867..50253ed64 100644 --- a/test/tls/socket.cpp +++ b/test/tls/socket.cpp @@ -145,8 +145,7 @@ struct server_fixture std::future accepted{}; }; -// A client context verifying the server, optionally presenting a client -// certificate. +// Client context verifying server, optionally presenting client certificate. struct client_setup { client_setup(const server_fixture& server, bool present) @@ -164,7 +163,7 @@ struct client_setup tls::context context{}; }; -// The client over a blocking loopback socket. +// Client over blocking loopback socket. struct tls_peer { tls_peer(const server_fixture& server, bool present) diff --git a/test/tor/cell.cpp b/test/tor/cell.cpp new file mode 100644 index 000000000..41bb79390 --- /dev/null +++ b/test/tor/cell.cpp @@ -0,0 +1,110 @@ +/** + * 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 "../test.hpp" + +BC_AUTO_TEST_SUITE(tor_cell_tests) + +using namespace bc::system; +using namespace tor; + +const auto versions = base16_chunk("00040005"); +const auto versions_cell = base16_chunk("00000700040004" "0005"); +const auto netinfo = base16_chunk("0000000004047f00000100"); + +BC_AUTO_TEST_CASE(tor_cell__is_variable__commands__expected) +{ + BC_REQUIRE(is_variable(command::versions)); + BC_REQUIRE(is_variable(command::vpadding)); + BC_REQUIRE(is_variable(command::certs)); + BC_REQUIRE(is_variable(command::auth_challenge)); + BC_REQUIRE(!is_variable(command::padding)); + BC_REQUIRE(!is_variable(command::netinfo)); + BC_REQUIRE(!is_variable(command::create2)); +} + +BC_AUTO_TEST_CASE(tor_cell__encode__narrow_versions__expected) +{ + BC_REQUIRE_EQUAL(encode({ 0, command::versions, versions }, true), versions_cell); +} + +BC_AUTO_TEST_CASE(tor_cell__encode__fixed__zero_padded) +{ + const auto encoded = encode({ 0x01020304, command::netinfo, netinfo }); + const auto expected = splice(base16_chunk("0102030408"), netinfo); + const data_chunk head{ encoded.begin(), std::next(encoded.begin(), expected.size()) }; + const data_chunk tail{ std::next(encoded.begin(), expected.size()), encoded.end() }; + BC_REQUIRE_EQUAL(encoded.size(), circuit_size + 1u + payload_size); + BC_REQUIRE_EQUAL(head, expected); + BC_REQUIRE_EQUAL(tail, data_chunk(payload_size - netinfo.size())); +} + +BC_AUTO_TEST_CASE(tor_cell__encode__variable__length_prefixed) +{ + BC_REQUIRE_EQUAL(encode({ 0, command::vpadding, base16_chunk("abcd") }), base16_chunk("0000000080" "0002" "abcd")); +} + +BC_AUTO_TEST_CASE(tor_cell__decode__narrow_versions__expected) +{ + cell out{}; + BC_REQUIRE_EQUAL(decode(out, versions_cell, true), versions_cell.size()); + BC_REQUIRE_EQUAL(out.circuit, 0u); + BC_REQUIRE_EQUAL(out.command, command::versions); + BC_REQUIRE_EQUAL(out.payload, versions); +} + +BC_AUTO_TEST_CASE(tor_cell__decode__fixed__round_trip) +{ + const auto encoded = encode({ 42, command::netinfo, netinfo }); + cell out{}; + BC_REQUIRE_EQUAL(decode(out, encoded), encoded.size()); + BC_REQUIRE_EQUAL(out.circuit, 42u); + BC_REQUIRE_EQUAL(out.command, command::netinfo); + BC_REQUIRE_EQUAL(out.payload.size(), payload_size); +} + +BC_AUTO_TEST_CASE(tor_cell__decode__variable_followed__first_cell_size) +{ + const auto first = encode({ 0, command::vpadding, base16_chunk("abcd") }); + const auto data = splice(first, encode({ 0, command::padding, {} })); + cell out{}; + BC_REQUIRE_EQUAL(decode(out, data), first.size()); + BC_REQUIRE_EQUAL(out.payload, base16_chunk("abcd")); +} + +BC_AUTO_TEST_CASE(tor_cell__decode__incomplete_fixed__zero) +{ + auto encoded = encode({ 0, command::netinfo, netinfo }); + encoded.pop_back(); + cell out{}; + BC_REQUIRE_EQUAL(decode(out, encoded), 0u); +} + +BC_AUTO_TEST_CASE(tor_cell__decode__incomplete_variable__zero) +{ + cell out{}; + BC_REQUIRE_EQUAL(decode(out, base16_chunk("0000000080" "0002" "ab")), 0u); +} + +BC_AUTO_TEST_CASE(tor_cell__decode__incomplete_header__zero) +{ + cell out{}; + BC_REQUIRE_EQUAL(decode(out, base16_chunk("000000")), 0u); +} + +BC_AUTO_TEST_SUITE_END() diff --git a/test/tor/certificate.cpp b/test/tor/certificate.cpp new file mode 100644 index 000000000..846d6dc50 --- /dev/null +++ b/test/tor/certificate.cpp @@ -0,0 +1,195 @@ +/** + * 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 "../test.hpp" + +BC_AUTO_TEST_SUITE(tor_certificate_tests) + +using namespace bc::system; +using namespace tor; + +// A chutney CERTS cell (as in arti tor-cert testvec_certs.rs). +const auto identity_key = base16_array("dcb604db2034b00fd16986d4adb9d16b21cb4e4457a33dec0f538903683e96e9"); +const auto signing_key = base16_array("f82294b866a31f01fc5d0da8572850a9b929545c3266558d7d2316e3b74172b0"); +const auto link_digest = base16_array("b4fd606b64e4cbd466b8d76cb131069bae6f3aa1878857c9f624e31d77a799b8"); +const auto signing_certificate = base16_chunk("01040006cc2a01f82294b866a31f01fc5d0da8572850a9b929545c3266558d7d2316e3b74172b00100200400dcb604db2034b00fd16986d4adb9d16b21cb4e4457a33dec0f538903683e96e9ff1a5203fa27f86ef7528d89a0845d2520166e340754ffea2aae0f612b7ce5da094a0236cdac45034b0b6842c18e7f6b51b93a3cf7e60663b8ad061c30a62602"); +const auto link_certificate = base16_chunk("01050006c98a03b4fd606b64e4cbd466b8d76cb131069bae6f3aa1878857c9f624e31d77a799b8007173e5f8068431d0d3f5ee16b4c9ffd59df373e152a87281bae744aa5fcf72171bf4b27c4e8fc1c6a9fc5ca11058bc49647063d7903cfd9f512f89099b27bc0c"); +const auto rsa_key = base16_chunk("30818902818100d38b1e6ceb946e0db0751f4cbace3dcb9688b6c25304227b4710c35afb73627e50500f5913e158b621802612d1c75827003703338375237552eb3cd3c12f6ab3604e60c1a2d26bb1fbad206ff023969a90909d6a65a5458a5312c26ebd3a3dad30302d4515cdcd264146ac18e6fc60a04bd3ec327f04294d96ba5aa25b464c3f0203010001"); +const auto rsa_crosscert = base16_chunk("dcb604db2034b00fd16986d4adb9d16b21cb4e4457a33dec0f538903683e96e90006da3a805cf6006f9179066534de6b45ad47a5c469063ee462762723396dc9f25452a0a52da3f5087dd239f2a311f6b0d4dfeff4abd089dc3d0237a0abab19eb2045b91cdcaf04be0a72d548a27bf2e77bd876ecfe5e1be622350da6bf31f6e306ed896488dd5b39409b23fc3eb7b2c9f7328eb18da36d54d80575899ea6507ccbfcdf1f"); +const auto signature = data_chunk(ed25519::signature_size, 0x00); + +// A certificate of the signing key with the extensions. +static data_chunk with_extensions(const data_chunk& extensions, uint8_t count) +{ + const auto head = base16_chunk("01040006cc2a01"); + const auto body = build_chunk({ head, signing_key, to_chunk(count) }); + return build_chunk({ body, extensions, signature }); +} + +// certificate + +BC_AUTO_TEST_CASE(tor_certificate__parse__signing__expected) +{ + certificate out{}; + BC_REQUIRE(parse(out, signing_certificate)); + BC_REQUIRE_EQUAL(out.type, certificate_type::identity_signing); + BC_REQUIRE_EQUAL(out.expiration, 0x0006cc2a_u32); + BC_REQUIRE_EQUAL(out.key_type, key_type::ed25519); + BC_REQUIRE_EQUAL(out.key, signing_key); + BC_REQUIRE(out.has_signer); + BC_REQUIRE_EQUAL(out.signer, identity_key); + BC_REQUIRE_EQUAL(out.signed_data.size(), signing_certificate.size() - ed25519::signature_size); +} + +BC_AUTO_TEST_CASE(tor_certificate__is_signed_by__signing_by_identity__true) +{ + certificate out{}; + BC_REQUIRE(parse(out, signing_certificate)); + BC_REQUIRE(is_signed_by(out, identity_key)); + BC_REQUIRE(!is_signed_by(out, signing_key)); +} + +BC_AUTO_TEST_CASE(tor_certificate__parse__link__expected) +{ + certificate out{}; + BC_REQUIRE(parse(out, link_certificate)); + BC_REQUIRE_EQUAL(out.type, certificate_type::signing_link); + BC_REQUIRE_EQUAL(out.expiration, 0x0006c98a_u32); + BC_REQUIRE_EQUAL(out.key_type, key_type::sha256_x509); + BC_REQUIRE_EQUAL(out.key, link_digest); + BC_REQUIRE(!out.has_signer); +} + +BC_AUTO_TEST_CASE(tor_certificate__is_signed_by__link_by_signing__true) +{ + certificate out{}; + BC_REQUIRE(parse(out, link_certificate)); + BC_REQUIRE(is_signed_by(out, signing_key)); + BC_REQUIRE(!is_signed_by(out, identity_key)); +} + +BC_AUTO_TEST_CASE(tor_certificate__parse__link_declared_key__digest) +{ + // The key type follows the version, type and expiration. + auto data = link_certificate; + data.at(6) = key_type::ed25519; + certificate out{}; + BC_REQUIRE(parse(out, data)); + BC_REQUIRE_EQUAL(out.key_type, key_type::sha256_x509); +} + +BC_AUTO_TEST_CASE(tor_certificate__parse__unrecognized_extension__ignored) +{ + const auto data = with_extensions(base16_chunk("0001" "99" "00" "ff"), 1); + certificate out{}; + BC_REQUIRE(parse(out, data)); + BC_REQUIRE(!out.has_signer); +} + +BC_AUTO_TEST_CASE(tor_certificate__parse__unrecognized_affecting_extension__false) +{ + const auto data = with_extensions(base16_chunk("0001" "99" "01" "ff"), 1); + certificate out{}; + BC_REQUIRE(!parse(out, data)); +} + +BC_AUTO_TEST_CASE(tor_certificate__parse__duplicate_signer__false) +{ + const auto signer = splice(base16_chunk("0020" "04" "00"), identity_key); + const auto data = with_extensions(splice(signer, signer), 2); + certificate out{}; + BC_REQUIRE(!parse(out, data)); +} + +BC_AUTO_TEST_CASE(tor_certificate__parse__short_signer__false) +{ + const auto data = with_extensions(base16_chunk("0001" "04" "00" "ff"), 1); + certificate out{}; + BC_REQUIRE(!parse(out, data)); +} + +BC_AUTO_TEST_CASE(tor_certificate__parse__version_two__false) +{ + auto data = signing_certificate; + data.front() = 2; + certificate out{}; + BC_REQUIRE(!parse(out, data)); +} + +BC_AUTO_TEST_CASE(tor_certificate__parse__trailing_byte__false) +{ + const auto data = splice(signing_certificate, base16_chunk("00")); + certificate out{}; + BC_REQUIRE(!parse(out, data)); +} + +BC_AUTO_TEST_CASE(tor_certificate__parse__truncated__false) +{ + auto data = signing_certificate; + data.pop_back(); + certificate out{}; + BC_REQUIRE(!parse(out, data)); +} + +// crosscert + +BC_AUTO_TEST_CASE(tor_certificate__parse_crosscert__chutney__expected) +{ + crosscert out{}; + BC_REQUIRE(parse(out, rsa_crosscert)); + BC_REQUIRE_EQUAL(out.key, identity_key); + BC_REQUIRE_EQUAL(out.expiration, 0x0006da3a_u32); + BC_REQUIRE_EQUAL(out.signed_data.size(), 36u); + BC_REQUIRE_EQUAL(out.signature.size(), 128u); +} + +BC_AUTO_TEST_CASE(tor_certificate__is_signed_by__crosscert_by_rsa_identity__true) +{ + crosscert out{}; + rsa::public_key key{}; + BC_REQUIRE(parse(out, rsa_crosscert)); + BC_REQUIRE(rsa::decode(key, rsa_key)); + BC_REQUIRE(is_signed_by(out, key)); +} + +BC_AUTO_TEST_CASE(tor_certificate__is_signed_by__altered_crosscert__false) +{ + auto data = rsa_crosscert; + data.front() ^= 0x01; + crosscert out{}; + rsa::public_key key{}; + BC_REQUIRE(parse(out, data)); + BC_REQUIRE(rsa::decode(key, rsa_key)); + BC_REQUIRE(!is_signed_by(out, key)); +} + +BC_AUTO_TEST_CASE(tor_certificate__parse_crosscert__trailing_byte__false) +{ + crosscert out{}; + BC_REQUIRE(!parse(out, splice(rsa_crosscert, base16_chunk("00")))); +} + +// is_expired + +BC_AUTO_TEST_CASE(tor_certificate__is_expired__expiration__true) +{ + BC_REQUIRE(is_expired(0x0006c98a, 1601316000)); + BC_REQUIRE(!is_expired(0x0006c98a, 1601315999)); +} + +BC_AUTO_TEST_SUITE_END() diff --git a/test/tor/link.cpp b/test/tor/link.cpp new file mode 100644 index 000000000..8b5a0fcd9 --- /dev/null +++ b/test/tor/link.cpp @@ -0,0 +1,250 @@ +/** + * 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 "../test.hpp" + +BC_AUTO_TEST_SUITE(tor_link_tests) + +using namespace bc::system; +using namespace tor; + +// A chutney CERTS cell (as in arti tor-cell testvec_chanmsg.rs), valid at the +// time, for the TLS certificate digest. +constexpr uint64_t now = 1601000000; +const auto link_digest = base16_array("b4fd606b64e4cbd466b8d76cb131069bae6f3aa1878857c9f624e31d77a799b8"); +const auto identity_key = base16_array("dcb604db2034b00fd16986d4adb9d16b21cb4e4457a33dec0f538903683e96e9"); +const auto rsa_identity = base16_array("2f1fb49bb332a9eec617e41e911c33fb3890aef3"); +const auto link_x509 = base16_chunk("3082023a308201a3a003020102020872ab0fe86c771604300d06092a864886f70d01010b0500301f311d301b06035504030c147777772e74636a76356b766a646472322e636f6d301e170d3230303632373030303030305a170d3231303231363233353935395a301c311a301806035504030c117777772e617775676863646e732e6e657430820122300d06092a864886f70d01010105000382010f003082010a0282010100fe255e99e10be986dda5dfb4ad7c39e8efe4e5d79e105ab976942b6829386eb1d7b7afb5ed4fcbec8c1a34c34fd2ed182f8b42a0363453b55ee371f21347235277e2357f28aa10dd82d4248f7d1894ab5d2979654f71c350f73ad9f918d71f34f1505f77ec16391c8340f392f3684ba4bb6a7b022c3954c1158f152f9e3b4e328fab2e4e881903ca0e32204b0fda8ab62b6e215a7bdec3f2ae41dc58eec1252f643a1812a5d71802f48d6133df79955e01f0287bb4ab8cf95bebcd2ec66ef5b38c7b5ec08ded3d6e2a1d57289d773d5cb932803b6d97784d1da36ae71c073adbb7393714001cd7a082512772a7076dc01166417af7c50aef7f15fd0806eb07ff0203010001300d06092a864886f70d01010b050003818100cda4e06bb6bb238b91188a077eeb0a4722518090fd116af6cdeeb0e85cf6d8e242cf861f973a252eb5116709373b5ac817e6f848e2cbd76aef684350d3416aee5f33d56b96982509cdaf11cca7260e5adf6ddd0d017ae9a575c999adae50b3fb7027e810d47c8c5c14618c0aa10d307e304fbe50e868adecb2c9536e2db51be0"); +const auto rsa_x509 = base16_chunk("308201b930820122a0030201020208607c28be6c390943300d06092a864886f70d01010b0500301f311d301b06035504030c147777772e74636a76356b766a646472322e636f6d301e170d3230303831303030303030305a170d3231303831303030303030305a301f311d301b06035504030c147777772e74636a76356b766a646472322e636f6d30819f300d06092a864886f70d010101050003818d0030818902818100d38b1e6ceb946e0db0751f4cbace3dcb9688b6c25304227b4710c35afb73627e50500f5913e158b621802612d1c75827003703338375237552eb3cd3c12f6ab3604e60c1a2d26bb1fbad206ff023969a90909d6a65a5458a5312c26ebd3a3dad30302d4515cdcd264146ac18e6fc60a04bd3ec327f04294d96ba5aa25b464c3f0203010001300d06092a864886f70d01010b0500038181003bce561ea7f95cc00b78aab5d69573ff301c282a751d4a651921d042f1becdba24d918a6d8a5e138dc07bba0b335478ae37abd2c93a93932442ae9084329e846170fe0fc4a50aafc804f311cc3ca4f41d845a7ba5901cbbc3e021e9794aac70ce1f37b0a951592db1b64f2b4afb81ae52dbd9b6fede96a5fb8125eb6251ee50a"); +const auto signing_certificate = base16_chunk("01040006cc2a01f82294b866a31f01fc5d0da8572850a9b929545c3266558d7d2316e3b74172b00100200400dcb604db2034b00fd16986d4adb9d16b21cb4e4457a33dec0f538903683e96e9ff1a5203fa27f86ef7528d89a0845d2520166e340754ffea2aae0f612b7ce5da094a0236cdac45034b0b6842c18e7f6b51b93a3cf7e60663b8ad061c30a62602"); +const auto link_certificate = base16_chunk("01050006c98a03b4fd606b64e4cbd466b8d76cb131069bae6f3aa1878857c9f624e31d77a799b8007173e5f8068431d0d3f5ee16b4c9ffd59df373e152a87281bae744aa5fcf72171bf4b27c4e8fc1c6a9fc5ca11058bc49647063d7903cfd9f512f89099b27bc0c"); +const auto rsa_crosscert = base16_chunk("dcb604db2034b00fd16986d4adb9d16b21cb4e4457a33dec0f538903683e96e90006da3a805cf6006f9179066534de6b45ad47a5c469063ee462762723396dc9f25452a0a52da3f5087dd239f2a311f6b0d4dfeff4abd089dc3d0237a0abab19eb2045b91cdcaf04be0a72d548a27bf2e77bd876ecfe5e1be622350da6bf31f6e306ed896488dd5b39409b23fc3eb7b2c9f7328eb18da36d54d80575899ea6507ccbfcdf1f"); +const auto relay_netinfo = base16_chunk("5f6f80e104047f0000010104047f000001"); +const auto client_netinfo = base16_chunk("0000000004047f00000100"); +const auto localhost = ip::address{ ip::ipv4{ { 127, 0, 0, 1 } } }; + +struct entry +{ + uint8_t type; + data_chunk body; +}; + +using entries = std::vector; + +static data_chunk certs_of(const entries& list) +{ + data_chunk out{}; + write::bytes::data sink(out); + sink.write_byte(possible_narrow_cast(list.size())); + for (const auto& value: list) + { + const auto size = possible_narrow_cast(value.body.size()); + sink.write_byte(value.type); + sink.write_2_bytes_big_endian(size); + sink.write_bytes(value.body); + } + + sink.flush(); + return out; +} + +static entries chutney() +{ + return + { + { certificate_type::link_x509, link_x509 }, + { certificate_type::rsa_identity, rsa_x509 }, + { certificate_type::identity_signing, signing_certificate }, + { certificate_type::signing_link, link_certificate }, + { certificate_type::rsa_crosscert, rsa_crosscert } + }; +} + +static data_chunk versions_of(const data_chunk& versions) +{ + return encode({ 0, command::versions, versions }, true); +} + +// The responder handshake: VERSIONS, CERTS, AUTH_CHALLENGE and NETINFO. +static data_chunk responder(const entries& list=chutney(), + const data_chunk& versions=base16_chunk("00030004" "0005")) +{ + const auto methods = base16_chunk("00010001"); + const auto challenge = splice(data_chunk(32, 0x07), methods); + return build_chunk( + { + versions_of(versions), + encode({ 0, command::certs, certs_of(list) }), + encode({ 0, command::auth_challenge, challenge }), + encode({ 0, command::netinfo, relay_netinfo }) + }); +} + +static entries without(uint8_t type) +{ + auto list = chutney(); + std::erase_if(list, [=](const entry& value) NOEXCEPT + { + return value.type == type; + }); + + return list; +} + +BC_AUTO_TEST_CASE(tor_link__construct__versions_output) +{ + tor::link handshake{ link_digest, localhost, now }; + BC_REQUIRE_EQUAL(handshake.output(), versions_of(base16_chunk("00040005"))); + BC_REQUIRE(!handshake.is_established()); + BC_REQUIRE(!handshake.is_failed()); +} + +BC_AUTO_TEST_CASE(tor_link__receive__chutney__established) +{ + tor::link handshake{ link_digest, localhost, now }; + handshake.output().clear(); + const auto received = handshake.receive(responder()); + const auto expected = encode({ 0, command::netinfo, client_netinfo }); + + BC_REQUIRE(received); + BC_REQUIRE(handshake.is_established()); + BC_REQUIRE_EQUAL(handshake.version(), 5u); + BC_REQUIRE_EQUAL(handshake.rsa_identity(), rsa_identity); + BC_REQUIRE_EQUAL(handshake.ed25519_identity(), identity_key); + BC_REQUIRE_EQUAL(handshake.output(), expected); + BC_REQUIRE(handshake.remainder().empty()); +} + +BC_AUTO_TEST_CASE(tor_link__receive__split__established) +{ + tor::link handshake{ link_digest, localhost, now }; + const auto data = responder(); + const auto half = data.size() / 2u; + const auto first = handshake.receive({ data.data(), half }); + const auto established_early = handshake.is_established(); + const auto second = handshake.receive({ std::next(data.data(), half), data.size() - half }); + + BC_REQUIRE(first); + BC_REQUIRE(!established_early); + BC_REQUIRE(second); + BC_REQUIRE(handshake.is_established()); +} + +BC_AUTO_TEST_CASE(tor_link__receive__trailing_cell__remainder) +{ + tor::link handshake{ link_digest, localhost, now }; + const auto trailing = encode({ 0, command::padding, {} }); + BC_REQUIRE(handshake.receive(splice(responder(), trailing))); + BC_REQUIRE(handshake.is_established()); + BC_REQUIRE_EQUAL(handshake.remainder(), trailing); +} + +BC_AUTO_TEST_CASE(tor_link__receive__padding_between__established) +{ + tor::link handshake{ link_digest, localhost, now }; + const auto padding = encode({ 0, command::vpadding, base16_chunk("00") }); + const auto data = build_chunk( + { + versions_of(base16_chunk("0004")), + padding, + encode({ 0, command::certs, certs_of(chutney()) }), + padding, + encode({ 0, command::netinfo, relay_netinfo }) + }); + + BC_REQUIRE(handshake.receive(data)); + BC_REQUIRE(handshake.is_established()); + BC_REQUIRE_EQUAL(handshake.version(), 4u); +} + +BC_AUTO_TEST_CASE(tor_link__receive__no_common_version__version) +{ + tor::link handshake{ link_digest, localhost, now }; + BC_REQUIRE(!handshake.receive(responder(chutney(), base16_chunk("00030006")))); + BC_REQUIRE(handshake.reason() == tor::link::failure::version); +} + +BC_AUTO_TEST_CASE(tor_link__receive__odd_versions__malformed) +{ + tor::link handshake{ link_digest, localhost, now }; + BC_REQUIRE(!handshake.receive(versions_of(base16_chunk("000400")))); + BC_REQUIRE(handshake.reason() == tor::link::failure::malformed); +} + +BC_AUTO_TEST_CASE(tor_link__receive__netinfo_before_certs__unexpected) +{ + tor::link handshake{ link_digest, localhost, now }; + const auto data = splice(versions_of(base16_chunk("0004")), encode({ 0, command::netinfo, relay_netinfo })); + BC_REQUIRE(!handshake.receive(data)); + BC_REQUIRE(handshake.reason() == tor::link::failure::unexpected); +} + +BC_AUTO_TEST_CASE(tor_link__receive__other_tls_certificate__certificate) +{ + tor::link handshake{ null_hash, localhost, now }; + BC_REQUIRE(!handshake.receive(responder())); + BC_REQUIRE(handshake.reason() == tor::link::failure::certificate); +} + +BC_AUTO_TEST_CASE(tor_link__receive__expired_link_certificate__expired) +{ + tor::link handshake{ link_digest, localhost, 1601316000 }; + BC_REQUIRE(!handshake.receive(responder())); + BC_REQUIRE(handshake.reason() == tor::link::failure::expired); +} + +BC_AUTO_TEST_CASE(tor_link__receive__without_crosscert__certificate) +{ + tor::link handshake{ link_digest, localhost, now }; + BC_REQUIRE(!handshake.receive(responder(without(certificate_type::rsa_crosscert)))); + BC_REQUIRE(handshake.reason() == tor::link::failure::certificate); +} + +BC_AUTO_TEST_CASE(tor_link__receive__without_rsa_identity__certificate) +{ + tor::link handshake{ link_digest, localhost, now }; + BC_REQUIRE(!handshake.receive(responder(without(certificate_type::rsa_identity)))); + BC_REQUIRE(handshake.reason() == tor::link::failure::certificate); +} + +BC_AUTO_TEST_CASE(tor_link__receive__duplicate_type__certificate) +{ + auto list = chutney(); + list.push_back({ certificate_type::link_x509, link_x509 }); + tor::link handshake{ link_digest, localhost, now }; + BC_REQUIRE(!handshake.receive(responder(list))); + BC_REQUIRE(handshake.reason() == tor::link::failure::certificate); +} + +BC_AUTO_TEST_CASE(tor_link__receive__link_signed_by_identity__certificate) +{ + auto list = without(certificate_type::identity_signing); + list.push_back({ certificate_type::identity_signing, link_certificate }); + tor::link handshake{ link_digest, localhost, now }; + BC_REQUIRE(!handshake.receive(responder(list))); + BC_REQUIRE(handshake.reason() == tor::link::failure::certificate); +} + +BC_AUTO_TEST_CASE(tor_link__receive__after_failure__false) +{ + tor::link handshake{ null_hash, localhost, now }; + BC_REQUIRE(!handshake.receive(responder())); + BC_REQUIRE(!handshake.receive(responder())); +} + +BC_AUTO_TEST_SUITE_END()