Skip to content

Blocking socket during handshake allows denial of service via partial TCP message #486

Description

@jyberg

Blocking socket during handshake allows denial of service via partial TCP message

Summary

The clickhouse-cpp client uses blocking sockets with no receive timeout during the TCP handshake phase. A malicious server, man-in-the-middle, or network fault that delivers a partial handshake response can cause the client thread to hang indefinitely on recv(), effectively denying service.

Environment

  • Library: clickhouse-cpp (all current versions)
  • Affected platforms: All (Linux, macOS, Windows)
  • Affected component: Client::Impl::Handshake() → ReceiveHello()

Root Cause

Three factors combine to create the vulnerability:

  1. connection_recv_timeout defaults to 0 (client.h, line 120), which means SO_RCVTIMEO is never effectively set — recv() blocks forever.

  2. Socket is switched to blocking mode after connect (socket.cpp, SocketConnect()): SetNonBlock(*s, false) is called once the connection succeeds.

  3. ReceiveHello() performs multiple sequential blocking reads (client.cpp, ReceiveHello()): 8 WireFormat::Read*() calls, each of which can individually block on recv() if data stops arriving mid-message.

Why SetConnectionRecvTimeout is not a viable workaround

SO_RCVTIMEO is set once on the socket during SocketConnect() and applies to all recv() calls for the socket's entire lifetime. Setting it to a short value (e.g. 10s) would protect the handshake, but would also kill long-running queries — a SELECT that takes minutes or hours to compute on the server side would timeout on the client before any data arrives.

There is currently no way to set a different timeout for the handshake vs. query execution.

Concrete attack / failure scenarios

Any of the following byte sequences sent by a rogue server (or injected by a MITM) after the client sends its Hello packet will hang the client thread forever:

Scenario 1: Single continuation byte (1 byte total)

0x80

The ReadVarint64() loop reads byte 0x80: continuation bit is set (meaning "more bytes follow"), value bits = 0. It loops to call ReadByte() again → recv() → blocks forever.

Scenario 2: Valid packet type + truncated string length (2 bytes total)

0x00 0x85
  • 0x00 = varint 0 = ServerCodes::Hello ✓
  • 0x85 = start of string length varint, continuation bit set → ReadByte() → recv() → blocks forever

Scenario 3: Valid header + truncated string body (7 bytes total)

0x00 0x0A 'C' 'l' 'i' 'c' 'k'
  • 0x00 = ServerCodes::Hello
  • 0x0A = string length 10
  • 5 of 10 expected bytes arrive

ReadAll() reads the 5 available bytes, loops back for the remaining 5 → recv() → blocks forever.

Scenario 4: Network fault mid-handshake

Server sends a valid Hello response, but TCP connection drops (RST lost, half-open state) between any two of the 8 read operations in ReceiveHello(). With no SO_RCVTIMEO, the client hangs indefinitely. Even TCP keepalive (disabled by default, 75s detection time when enabled) doesn't help against a server that keeps the connection open but stops sending.

Affected code path

Client::Impl::ResetConnection()
└─ Handshake()                              # client.cpp
   ├─ SendHello()                           # succeeds
   └─ ReceiveHello()                        # client.cpp:1065
      ├─ ReadVarint64 (packet_type)         ← BLOCK POINT 1
      ├─ ReadString   (server_name)         ← BLOCK POINT 2 (varint len + body)
      ├─ ReadUInt64   (version_major)       ← BLOCK POINT 3
      ├─ ReadUInt64   (version_minor)       ← BLOCK POINT 4
      ├─ ReadUInt64   (revision)            ← BLOCK POINT 5
      ├─ ReadString   (timezone)            ← BLOCK POINT 6
      ├─ ReadString   (display_name)        ← BLOCK POINT 7
      └─ ReadUInt64   (version_patch)       ← BLOCK POINT 8

Each Read* call eventually reaches:

WireFormat::ReadVarint64 / ReadAll
  → BufferedInput::DoNext
    → SocketInput::DoRead
      → ::recv(fd, buf, len, 0)   // blocks forever when SO_RCVTIMEO=0

Proposed fix

Add a handshake-scoped timeout that is independent of the query recv timeout. Two options:

Option A: New connection_handshake_timeout option (recommended)

Add a dedicated option with a safe default:

DECLARE_FIELD(connection_handshake_timeout, std::chrono::milliseconds,
              SetConnectionHandshakeTimeout, std::chrono::seconds(30));

In ResetConnection(), temporarily apply it to the socket before Handshake(), then restore the user's connection_recv_timeout after:

void Client::Impl::ResetConnection() {
    auto socket = socket_factory_->connect(options_, current_endpoint_.value());

    // Apply handshake timeout
    SetSocketTimeout(socket->fd(), options_.connection_handshake_timeout);

    InitializeStreams(std::move(socket));
    inserting_ = false;

    if (!Handshake()) {
        throw ProtocolError("fail to connect to " + options_.host);
    }

    // Restore user's recv timeout (0 = infinite for long queries)
    SetSocketTimeout(socket->fd(), options_.connection_recv_timeout);
}

Option B: Reuse connection_connect_timeout for handshake

Apply the existing connection_connect_timeout (default 5s) as a temporary SO_RCVTIMEO during Handshake() only. No new options needed, but conflates two different operations.

Impact

  • Severity: Medium-High (denial of service / thread hang)
  • Attack vector: Network (MITM, rogue server, network fault)
  • User impact: Client thread hangs permanently, no recovery possible without process kill
  • Workaround: None that doesn't also break long-running queries

Activity

  1. polyglotAI-bot commented on Nov 18, 2026

    @polyglotAI-bot
    Collaborator

    Recommendation: Keep open — fix needed
    The fix needs a receive timeout for the Hello exchange only. A maintainer picks option A (a new option) or option B (the connect timeout) of the issue, and the default.

    • Category: Bug
    • Classes: impact: Security (vulnerability), Stability · area: Connectivity
    • Status on master: Reproduced on main — the Client constructor does not return when the server sends a partial Hello, or nothing.
    • Breaking change: No — can be done without a break, also with a finite default, if the timeout applies only during Handshake().
    • Duplicates / related: Related: open PR Bound the TLS handshake by the connect timeout #583 (bounds the TLS handshake, not the Hello phase); when clickhouse-server died, clickhouse-cpp hang in recv while doing Insert #209 (open: a recv() hang during Insert, same missing default timeout).
    • Workaround: SetConnectionRecvTimeout bounds the handshake and lets the failover work (cases 6, 8); with the default interactive_delay, it stops a query only when the server sends nothing for longer than the timeout (cases 9, 10); this triage did not check which queries have such silent phases.

    Analysis: connection_recv_timeout is 0 (no timeout) by default (clickhouse/client.h:122), and SocketConnect() sets the socket back to blocking mode (clickhouse/base/socket.cpp:242, socket.cpp:249), so each recv() in ReceiveHello() (clickhouse/client.cpp:1202) waits until the peer closes the socket. The failover to the next endpoint does not run, because ResetConnectionEndpoint() (client.cpp:620) goes to the next endpoint only after an exception.

    Reproduction: complete program and output
    // Reproduction for clickhouse-cpp#486: the handshake has no timeout by default.
    // A fake server (in this process, on 127.0.0.1) accepts the connection, sends a
    // partial Hello packet, and then sends nothing. The real server is read from
    // CLICKHOUSE_HOST / CLICKHOUSE_PORT (defaults localhost, 9000).
    #include <clickhouse/client.h>
    
    #include <arpa/inet.h>
    #include <netinet/in.h>
    #include <sys/socket.h>
    #include <unistd.h>
    
    #include <atomic>
    #include <chrono>
    #include <cstdio>
    #include <cstdlib>
    #include <future>
    #include <string>
    #include <thread>
    #include <vector>
    
    using namespace clickhouse;
    using Clock = std::chrono::steady_clock;
    
    static double Since(Clock::time_point t0) {
        return std::chrono::duration<double>(Clock::now() - t0).count();
    }
    
    static void Drain(int fd) {
        char buf[4096];
        while (recv(fd, buf, sizeof(buf), MSG_DONTWAIT) > 0) {}
    }
    
    // Accepts one connection, sends `payload`, then sends nothing until Release().
    // Release() reads what the client sent (so close() sends FIN, not RST) and closes.
    class FakeServer {
    public:
        explicit FakeServer(std::string payload) : payload_(std::move(payload)) {
            listen_fd_ = socket(AF_INET, SOCK_STREAM, 0);
            sockaddr_in addr{};
            addr.sin_family = AF_INET;
            addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
            addr.sin_port = 0;
            bind(listen_fd_, reinterpret_cast<sockaddr*>(&addr), sizeof(addr));
            listen(listen_fd_, 1);
            socklen_t len = sizeof(addr);
            getsockname(listen_fd_, reinterpret_cast<sockaddr*>(&addr), &len);
            port_ = ntohs(addr.sin_port);
            thread_ = std::thread([this] {
                int fd = accept(listen_fd_, nullptr, nullptr);
                std::this_thread::sleep_for(std::chrono::milliseconds(100));
                Drain(fd);  // the client Hello
                if (!payload_.empty()) send(fd, payload_.data(), payload_.size(), 0);
                while (!released_) std::this_thread::sleep_for(std::chrono::milliseconds(20));
                Drain(fd);
                close(fd);
            });
        }
        ~FakeServer() { Release(); thread_.join(); close(listen_fd_); }
        void Release() { released_ = true; }
        uint16_t Port() const { return port_; }
    
    private:
        std::string payload_;
        int listen_fd_ = -1;
        uint16_t port_ = 0;
        std::atomic<bool> released_{false};
        std::thread thread_;
    };
    
    // Runs `fn` in a thread. If it does not return in `limit`, prints HANG, calls
    // `on_hang` (the fake server closes the socket), and then waits for the end.
    template <typename Fn, typename OnHang>
    static void Run(const char* name, std::chrono::seconds limit, Fn fn, OnHang on_hang) {
        auto t0 = Clock::now();
        std::promise<std::string> done;
        auto result = done.get_future();
        std::thread worker([&] {
            try {
                done.set_value(fn());
            } catch (const std::exception& e) {
                done.set_value(std::string("error: ") + e.what());
            }
        });
        if (result.wait_for(limit) == std::future_status::timeout) {
            std::printf("%-46s HANG: no return after %.1f s\n", name, Since(t0));
            on_hang();
            std::string late = result.get();
            std::printf("%-46s   then, after the fake server closed the socket: %s\n", "", late.c_str());
        } else {
            std::printf("%-46s %.1f s: %s\n", name, Since(t0), result.get().c_str());
        }
        worker.join();
    }
    
    int main() {
        const char* host_env = std::getenv("CLICKHOUSE_HOST");
        const char* port_env = std::getenv("CLICKHOUSE_PORT");
        const std::string host = host_env ? host_env : "localhost";
        const uint16_t port = static_cast<uint16_t>(port_env ? std::atoi(port_env) : 9000);
        const auto limit = std::chrono::seconds(5);
        const auto none = [] {};
    
        auto connect = [](ClientOptions opts) {
            Client client(opts);
            const auto& info = client.GetServerInfo();
            auto ep = client.GetCurrentEndpoint();
            return "connected to " + info.name + " " + std::to_string(info.version_major) + "." +
                   std::to_string(info.version_minor) + " at port " + std::to_string(ep ? ep->port : 0);
        };
    
        // 1. Control: the real server, default options.
        Run("real server, default options", limit,
            [&] { return connect(ClientOptions().SetHost(host).SetPort(port)); }, none);
    
        // 2-5. Fake server, default options (connection_recv_timeout = 0).
        const std::vector<std::pair<const char*, std::string>> payloads = {
            {"fake server sends nothing", std::string()},
            {"fake server sends 80", std::string("\x80", 1)},
            {"fake server sends 00 85", std::string("\x00\x85", 2)},
            {"fake server sends 00 0A 'Click'", std::string("\x00\x0A" "Click", 7)},
        };
        for (const auto& [name, payload] : payloads) {
            FakeServer fake(payload);
            Run(name, limit,
                [&] { return connect(ClientOptions().SetHost("127.0.0.1").SetPort(fake.Port())); },
                [&] { fake.Release(); });
        }
    
        // 6. Fake server, connection_recv_timeout = 1000 ms.
        {
            FakeServer fake(std::string("\x80", 1));
            Run("fake server sends 80, recv timeout 1000 ms", limit,
                [&] {
                    return connect(ClientOptions().SetHost("127.0.0.1").SetPort(fake.Port())
                                       .SetConnectionRecvTimeout(std::chrono::milliseconds(1000)));
                },
                [&] { fake.Release(); });
        }
    
        // 7-8. Two endpoints: first the fake server, then the real server.
        {
            FakeServer fake(std::string("\x80", 1));
            Run("endpoints {fake, real}, default options", limit,
                [&] {
                    return connect(ClientOptions().SetEndpoints({{"127.0.0.1", fake.Port()}, {host, port}}));
                },
                [&] { fake.Release(); });
        }
        {
            FakeServer fake(std::string("\x80", 1));
            Run("endpoints {fake, real}, recv timeout 1000 ms", limit,
                [&] {
                    return connect(ClientOptions().SetEndpoints({{"127.0.0.1", fake.Port()}, {host, port}})
                                       .SetConnectionRecvTimeout(std::chrono::milliseconds(1000)));
                },
                [&] { fake.Release(); });
        }
    
        // 9. The real server, recv timeout 1000 ms, a query that runs for 3 s.
        Run("real server, recv timeout 1000 ms, sleep(3)", std::chrono::seconds(10),
            [&] {
                Client client(ClientOptions().SetHost(host).SetPort(port)
                                  .SetConnectionRecvTimeout(std::chrono::milliseconds(1000)));
                std::string out;
                client.Select("SELECT sleep(3) AS s, 42 AS x", [&](const Block& block) {
                    if (block.GetRowCount() > 0) out = "query OK, x = " + std::to_string((*block[1]->As<ColumnUInt8>())[0]);
                });
                return out;
            },
            none);
    
        // 10. The same query, but the server sends progress only every 10 s
        //     (interactive_delay in the Query packet settings, in microseconds).
        Run("same, interactive_delay = 10 s", std::chrono::seconds(10),
            [&] {
                Client client(ClientOptions().SetHost(host).SetPort(port)
                                  .SetConnectionRecvTimeout(std::chrono::milliseconds(1000)));
                std::string out;
                Query query("SELECT sleep(3) AS s, 42 AS x");
                query.SetSetting("interactive_delay", QuerySettingsField{"10000000", QuerySettingsField::IMPORTANT});
                query.OnData([&](const Block& block) {
                    if (block.GetRowCount() > 0) out = "query OK, x = " + std::to_string((*block[1]->As<ColumnUInt8>())[0]);
                });
                client.Select(query);
                return out;
            },
            none);
        return 0;
    }

    Output on master (58453c2), ClickHouse 26.10, default 2.x build options:

    real server, default options                   0.0 s: connected to ClickHouse 26.10 at port 9000
    fake server sends nothing                      HANG: no return after 5.0 s
                                                     then, after the fake server closed the socket: error: connection closed by peer while reading
    fake server sends 80                           HANG: no return after 5.0 s
                                                     then, after the fake server closed the socket: error: connection closed by peer while reading
    fake server sends 00 85                        HANG: no return after 5.0 s
                                                     then, after the fake server closed the socket: error: connection closed by peer while reading
    fake server sends 00 0A 'Click'                HANG: no return after 5.0 s
                                                     then, after the fake server closed the socket: error: connection closed by peer while reading
    fake server sends 80, recv timeout 1000 ms     1.1 s: error: can't receive string data: Resource temporarily unavailable
    endpoints {fake, real}, default options        HANG: no return after 5.0 s
                                                     then, after the fake server closed the socket: error: connection closed by peer while reading
    endpoints {fake, real}, recv timeout 1000 ms   1.1 s: connected to ClickHouse 26.10 at port 9000
    real server, recv timeout 1000 ms, sleep(3)    3.0 s: query OK, x = 42
    same, interactive_delay = 10 s                 1.0 s: error: can't receive string data: Resource temporarily unavailable
    exit=0
    

    Automated triage by Polyglot AI. A maintainer makes the final decision. Shortened on 2026-11-20: the edit history has the first version.

  2. added
    bug
    on Nov 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions