http: Restore requirement of IPv4 bind success #36187

pull hodlinator wants to merge 6 commits into bitcoin:master from hodlinator:2026/09/req_all_binds changing 5 files +103 −31
  1. hodlinator commented at 7:51 PM on September 7, 2026: contributor

    Problem

    When bitcoind starts and the HTTP IPv4 listen address is occupied by another process, but the IPv6 address is available, the server fails open and generates a cookie file. When bitcoin-cli runs it picks up the cookie file and sends the credentials in plain text to the non-bitcoind process running on the default IPv4 port. An attacker can then use the credentials to commandeer bitcoind over IPv6.

    Solution

    Safe defaults:

    • When running with default settings, require that the IPv4 bind succeeds.
    • When -rpcbind is specified, require that all HTTP listen socket binds succeed (fail closed-behavior).

    Node operators who only have IPv6 are now required to override -rpcbind and -rpcallowip to only specify the working interface and allowed subnet if they were not doing so already.

    The problem of bitcoin-cli sending the credentials to what could possibly be the wrong process remains only in non-default setups.

    History

    40b556d3742a1f65d67e2d4c760d0b13fe8be5b7 from 2015 switched the HTTP server from Boost Asio to LibEvent, and binding switched from an attempt at dual-binding IPv4+v6 and falling back to IPv4-only (rpcserver.cpp / StartRPCThreads()), to binding IPv4 or IPv6 (httpserver.cpp / HTTPBindAddresses()). The current PR restores the prior behavior of IPv4 being mandatory.

    #14968 from 2018 was an attempt to change the behavior to require all binds to succeed. But it ran into issues with poor IPv6 support on CI.

    Severity

    This credential exfiltration attack requires capability to launch processes on the bitcoind host. If we are on the same account we can already read the cookie credentials off disk. So it's only really interesting when an attacker is on a different user account on the same host.

  2. DrahtBot added the label RPC/REST/ZMQ on Sep 7, 2026
  3. DrahtBot commented at 7:51 PM on September 7, 2026: contributor

    <!--e57a25ab6845829454e8d69fc972939a-->

    The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

    <!--006a51241073e994b41acfe9ec718e94-->

    External sites

    <!--021abf342d371248e50ceaed478a90ca-->

    Reviews

    See the guideline and AI policy for information on the review process.

    Type Reviewers
    ACK l0rinc, janb84
    Concept ACK sedited
    Stale ACK winterrdog

    If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore.

    <!--174a7506f384e20aa4161008e828411d-->

    Conflicts

    Reviewers, this pull request conflicts with the following ones:

    • #36204 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36204.svg"></sub> (http: disconnect clients that never finish a request by janb84)
    • #35355 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35355.svg"></sub> (Use atomics for determining whether trace logging is enabled by ajtowns)
    • #34520 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/34520.svg"></sub> (refactor: Add [[nodiscard]] to functions returning bool+mutable ref by maflcko)

    If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

    <!--5faf32d7da4f0f540f40219e4f7537a3-->

  4. l0rinc commented at 7:55 PM on September 7, 2026: contributor

    Concept ACK, thanks for pushing the fix

  5. hodlinator marked this as a draft on Sep 7, 2026
  6. hodlinator renamed this:
    http: Require all binds to succeed
    http: Require default IPv4 bind to succeed (again)
    on Sep 7, 2026
  7. hodlinator commented at 8:07 PM on September 7, 2026: contributor

    For some reason thought that we weren't enabling the HTTP subsystem by default. Going to re-work the code slightly. Put in draft.

  8. hodlinator force-pushed on Sep 7, 2026
  9. DrahtBot added the label CI failed on Sep 7, 2026
  10. DrahtBot removed the label CI failed on Sep 7, 2026
  11. hodlinator marked this as ready for review on Sep 8, 2026
  12. hodlinator force-pushed on Sep 8, 2026
  13. in test/functional/rpc_bind.py:123 in 64fd5cef0c
     118 | +                self.cleanup_partially_started_nodes()
     119 | +        self.nodes[0].rpchost = None
     120 | +
     121 | +        assert_equal(started, False)
     122 | +        assert_equal(credential_captured, False)
     123 | +        assert started or 'Unable to start HTTP server' in error
    


    janb84 commented at 9:18 AM on September 8, 2026:

    NIT: Leftover assert on started, Line 121 asserts that started is false so started cannot be true at this point.

            assert 'Unable to start HTTP server' in error
    
  14. in src/httpserver.cpp:230 in 64fd5cef0c outdated
     228 | -        endpoints.emplace_back("::1", http_port);
     229 | +        // We allow the default IPv6 bind to fail, but IPv4 is required even
     230 | +        // with the default port as bitcoin-cli will default to handing RPC
     231 | +        // credentials in plaintext to whatever process is running on that port.
     232 | +        endpoints.push_back({.address = "::1", .port = http_port, .required = false});
     233 |          endpoints.emplace_back("127.0.0.1", http_port);
    


    janb84 commented at 9:48 AM on September 8, 2026:

    NIT: I would keep the style of the 2 lines the same (helps the OCD people)

            endpoints.push_back({.address = "127.0.0.1", .port = http_port});
    

    hodlinator commented at 7:19 PM on September 8, 2026:

    Will do if others agree, holding off for now.


    winterrdog commented at 10:39 PM on September 10, 2026:

    one of the "others" has arrived 😁


    anyway, i agree with @janb84

    when i first looked at the code, i thought there might be a subtle reason for using one over the other, but later on i realised they do the same thing. so i think sticking to the same pattern makes sense. whether you use emplace_back() or push_back() is up to you, as long as there is some symmetry

  15. in src/httpserver.cpp:1366 in 64fd5cef0c
    1366 |              if (!result) {
    1367 | -                LogWarning("Binding RPC on address %s failed: %s", addr->ToStringAddrPort(), result.error());
    1368 | +                LogWarning("Binding %s RPC on address %s failed: %s",
    1369 | +                           required ? "required" : "optional",
    1370 | +                           addr->ToStringAddrPort(), result.error());
    1371 | +                if (required) required_failure = true;
    


    janb84 commented at 10:25 AM on September 8, 2026:

    non blocking, micro nit: Currently even the required entry/bindings failure only logs as a LogWarning. Is that the correct level for something that aborts startup ?

    if (required) {
        LogError("Binding required RPC endpoint %s failed: %s", addr->ToStringAddrPort(), result.error());
        required_failure = true;
    } else {
        LogWarning("Binding optional RPC endpoint %s failed: %s", addr->ToStringAddrPort(), result.error());
    }
    
  16. janb84 commented at 10:27 AM on September 8, 2026: contributor

    Concept ACK 64fd5cef0c938d3d1e7f69d6be2f255b6eafc1e2

    Looks good, some suggestion NITS.

    NITl Commit message of c309e5fb73 has a typo / grammar issue "and without this change that one would Mac CI would fail with:"

  17. hodlinator force-pushed on Sep 8, 2026
  18. hodlinator force-pushed on Sep 8, 2026
  19. DrahtBot added the label CI failed on Sep 8, 2026
  20. hodlinator commented at 8:08 PM on September 8, 2026: contributor

    Latest push addresses all but 1 comment from #36187#pullrequestreview-5139772278

  21. DrahtBot removed the label CI failed on Sep 8, 2026
  22. sedited commented at 3:28 PM on September 9, 2026: contributor

    Concept ACK

  23. in src/httpserver.cpp:1392 in 690a4b1a6c
    1393 |      if (!bind_success) {
    1394 |          LogError("Unable to bind any endpoint for RPC server");
    1395 |          return false;
    1396 | +    } else if (required_failure) {
    1397 | +        g_http_server->StopListening();
    1398 | +        LogError("Unable to bind all required endpoints for RPC server");
    


    winterrdog commented at 10:23 PM on September 10, 2026:

    from the PR description:

    Node runners who only have IPv6 are now required to override -rpcbind to only specify the working interface if they were not doing so already.

    can we make the IPv6-only case a bit more actionable in the error message ?

    with the new defaults, an IPv6-only host will fail because the required 127.0.0.1 bind will never succeed, but the user may not know that they need to override -rpcbind to use only their IPv6 address. mayhaps the error could point them towards -rpcbind rather than just reporting that a required endpoint failed

    i was thinking of sth like (feel free to put a spin to it):

            LogError("Unable to bind all required endpoints for RPC server. If this host does not support IPv4, specify the IPv6 RPC address with -rpcbind.");
    

    hodlinator commented at 11:10 AM on September 11, 2026:

    Good point. Default behavior for IPv6-only hosts should at least be to get an informative error message.

  24. winterrdog commented at 10:40 PM on September 10, 2026: contributor

    concept ACK

    this makes sense since bitcoin-cli defaults to IPv4, so bitcoind should have a corresponding IPv4 listener, already working by default as well

  25. hodlinator force-pushed on Sep 11, 2026
  26. hodlinator commented at 11:13 AM on September 11, 2026: contributor

    Latest push avoids stringly typing endpoints_seen and addresses points from #36187#pullrequestreview-5172841125.

  27. hodlinator commented at 9:40 AM on September 21, 2026: contributor

    Updated PR description, primarily the History-section.

  28. hodlinator renamed this:
    http: Require default IPv4 bind to succeed (again)
    http: Restore requirement of IPv4 bind success
    on Sep 21, 2026
  29. sedited requested review from winterrdog on Nov 4, 2026
  30. sedited requested review from janb84 on Nov 4, 2026
  31. sedited removed review request from winterrdog on Nov 4, 2026
  32. sedited requested review from l0rinc on Nov 4, 2026
  33. sedited requested review from winterrdog on Nov 4, 2026
  34. in src/httpserver.cpp:213 in 05de7be9d7 outdated
     205 | @@ -205,19 +206,34 @@ static void RejectRequest(std::unique_ptr<HTTPRequest> hreq)
     206 |      WriteNoStoreErrorReply(*hreq, HTTP_SERVICE_UNAVAILABLE);
     207 |  }
     208 |  
     209 | -static std::vector<std::pair<std::string, uint16_t>> GetBindAddresses()
     210 | +struct BindAddress {
     211 | +    std::string address;
     212 | +    uint16_t port;
     213 | +    bool required{true};
     214 | +};
    


    janb84 commented at 2:23 PM on November 5, 2026:

    NIT: current BindAddress keeps the address as a string, and InitHTTPServer parses it later with Lookup. This "late" lookup has the consequence that an invalid -rpcbind value is only detected inside the bind loop. Resulting that possible earlier endpoints may already be listening, and StopListening() has to undo them.

    I think we can do this lookup (with fAllowLookup=false) sooner, as pure numeric parse without DNS (So it is safe to call it in GetBindAddresses) and store it typed. This is the same way the lookup is done in the bind loop. This has the benefit that any invalid -rpcbind address fails before any socket is opened, equal to the port logic. And, to me, failing fast without the "risk" of opening sockets, is the better security posture.

    <details> <summary>patch</summary>

    diff --git a/src/httpserver.cpp b/src/httpserver.cpp
    index 10f1cb85f8..6b21120c29 100644
    --- a/src/httpserver.cpp
    +++ b/src/httpserver.cpp
    @@ -207,8 +207,7 @@ static void RejectRequest(std::unique_ptr<HTTPRequest> hreq)
     }
     
     struct BindAddress {
    -    std::string address;
    -    uint16_t port;
    +    CService addr;
         bool required{true};
     };
     
    @@ -232,8 +231,10 @@ static std::vector<BindAddress> GetBindAddresses()
             // We allow the default IPv6 bind to fail, but IPv4 is required even
             // with the default port as bitcoin-cli will default to handing RPC
             // credentials in plaintext to whatever process is running on that port.
    -        endpoints.push_back({.address = "::1",       .port = http_port, .required = false});
    -        endpoints.push_back({.address = "127.0.0.1", .port = http_port, .required = true});
    +        // Numeric literals always parse, InitHTTPAllowList relies on the same.
    +        // Never fall back to CService{}, which is [::]:0 and binds every interface.
    +        endpoints.push_back({.addr = Lookup("::1", http_port, /*fAllowLookup=*/false).value(),       .required = false});
    +        endpoints.push_back({.addr = Lookup("127.0.0.1", http_port, /*fAllowLookup=*/false).value(), .required = true});
             if (!gArgs.GetArgs("-rpcallowip").empty()) {
                 LogWarning("Option -rpcallowip was specified without -rpcbind; this doesn't usually make sense");
             }
    @@ -248,7 +249,14 @@ static std::vector<BindAddress> GetBindAddresses()
                     LogError("%s\n", InvalidPortErrMsg("-rpcbind", strRPCBind).original);
                     return {}; // empty
                 }
    -            endpoints.emplace_back(host, port);
    +            // Don't allow hostname lookups when binding to local interfaces.
    +            const std::optional<CService> addr{Lookup(host, port, /*fAllowLookup=*/false)};
    +            if (!addr) {
    +                LogError("Could not bind RPC on address \"%s\" port %i: Address lookup failed "
    +                         "(only numeric addresses are allowed).", host, port);
    +                return {}; // empty
    +            }
    +            endpoints.push_back({.addr = *addr, .required = true});
             }
         }
         return endpoints;
    @@ -1361,32 +1369,22 @@ bool InitHTTPServer()
                 LogWarning("%s", msg);
             }
         };
    -    for (const auto& [address_string, port, required] : endpoints) {
    -        // Don't allow hostname lookups when binding to local interfaces. This
    -        // means numeric collisions on available interfaces detected by endpoints_seen
    -        // are probably just repeated instances - skip without logging why.
    -        const std::optional<CService> addr{Lookup(address_string, port, /*fAllowLookup=*/false)};
    -        if (addr) {
    -            if (!endpoints_seen.insert(*addr).second) continue;
    -            LogInfo("Binding RPC on address %s port %i", address_string, port);
    -            if (addr->IsBindAny()) {
    -                LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet");
    -            }
    -            auto result{g_http_server->BindAndStartListening(addr.value())};
    -            if (!result) {
    -                on_failure(required,
    -                           strprintf("Binding RPC on %s address %s failed: %s",
    -                                     required ? "required" : "optional",
    -                                     addr->ToStringAddrPort(), result.error()));
    -            } else {
    -                bind_success = true;
    -            }
    -        } else {
    +    for (const auto& [addr, required] : endpoints) {
    +        // Addresses are numeric, so collisions detected by endpoints_seen are
    +        // probably just repeated instances - skip without logging why.
    +        if (!endpoints_seen.insert(addr).second) continue;
    +        LogInfo("Binding RPC on address %s", addr.ToStringAddrPort());
    +        if (addr.IsBindAny()) {
    +            LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet");
    +        }
    +        auto result{g_http_server->BindAndStartListening(addr)};
    +        if (!result) {
                 on_failure(required,
    -                       strprintf("Could not bind RPC on %s address \"%s\" port %i: Address lookup failed "
    -                                 "(only numeric addresses are allowed).",
    +                       strprintf("Binding RPC on %s address %s failed: %s",
                                      required ? "required" : "optional",
    -                                 address_string, port));
    +                                 addr.ToStringAddrPort(), result.error()));
    +        } else {
    +            bind_success = true;
             }
         }
     
    
    

    </details>


    winterrdog commented at 11:39 PM on November 5, 2026:

    +1, i think it makes sense to fail-fast

    went ahead and extended your patch a little by making InitHTTPServer() fail fast (as well) when a required endpoint fails to bind. this removes the need for bind_success, required_failure, and the failure-handling helper. we just handle the failure where it happens and return immediately.

    i think this will make the control flow simpler and easier to follow, with less state to keep track of. plus, it also avoids attempting further binds when we already know startup cannot succeed

    <details><summary><i>extended</i> patch</summary>

    diff --git a/src/httpserver.cpp b/src/httpserver.cpp
    index 10f1cb85f8..88f87e9ac9 100644
    --- a/src/httpserver.cpp
    +++ b/src/httpserver.cpp
    @@ -207,8 +207,7 @@ static void RejectRequest(std::unique_ptr<HTTPRequest> hreq)
     }
     
     struct BindAddress {
    -    std::string address;
    -    uint16_t port;
    +    CService addr;
         bool required{true};
     };
     
    @@ -232,8 +231,10 @@ static std::vector<BindAddress> GetBindAddresses()
             // We allow the default IPv6 bind to fail, but IPv4 is required even
             // with the default port as bitcoin-cli will default to handing RPC
             // credentials in plaintext to whatever process is running on that port.
    -        endpoints.push_back({.address = "::1",       .port = http_port, .required = false});
    -        endpoints.push_back({.address = "127.0.0.1", .port = http_port, .required = true});
    +        // Numeric literals always parse, InitHTTPAllowList relies on the same.
    +        // Never fall back to CService{}, which is [::]:0 and binds every interface.
    +        endpoints.push_back({.addr = Lookup("127.0.0.1", http_port, /*fAllowLookup=*/false).value(), .required = true});
    +        endpoints.push_back({.addr = Lookup("::1", http_port, /*fAllowLookup=*/false).value(), .required = false});
             if (!gArgs.GetArgs("-rpcallowip").empty()) {
                 LogWarning("Option -rpcallowip was specified without -rpcbind; this doesn't usually make sense");
             }
    @@ -248,7 +249,15 @@ static std::vector<BindAddress> GetBindAddresses()
                     LogError("%s\n", InvalidPortErrMsg("-rpcbind", strRPCBind).original);
                     return {}; // empty
                 }
    -            endpoints.emplace_back(host, port);
    +            // Don't allow hostname lookups when binding to local interfaces.
    +            const std::optional<CService> addr{Lookup(host, port, /*fAllowLookup=*/false)};
    +            if (!addr) {
    +                LogError("Could not bind RPC on address \"%s\" port %i: Address lookup failed "
    +                         "(only numeric addresses are allowed).",
    +                         host, port);
    +                return {}; // empty
    +            }
    +            endpoints.push_back({.addr = *addr, .required = true});
             }
         }
         return endpoints;
    @@ -1350,58 +1359,38 @@ bool InitHTTPServer()
     
         // Bind HTTP server to specified addresses
         std::vector<BindAddress> endpoints{GetBindAddresses()};
    +    if (endpoints.empty()) {
    +        LogError("Unable to bind any endpoint for RPC server");
    +        return false;
    +    }
    +
         std::set<CService> endpoints_seen;
    -    bool bind_success{false};
    -    bool required_failure{false};
    -    auto on_failure = [&required_failure](bool required, std::string_view msg) {
    -        if (required) {
    -            LogError("%s", msg);
    -            required_failure = true;
    -        } else {
    -            LogWarning("%s", msg);
    +    for (const auto& [addr, required] : endpoints) {
    +        // Addresses are numeric, so collisions detected by endpoints_seen are
    +        // probably just repeated instances - skip without logging why.
    +        if (!endpoints_seen.insert(addr).second) continue;
    +        LogInfo("Binding RPC on address %s", addr.ToStringAddrPort());
    +        if (addr.IsBindAny()) {
    +            LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet");
             }
    -    };
    -    for (const auto& [address_string, port, required] : endpoints) {
    -        // Don't allow hostname lookups when binding to local interfaces. This
    -        // means numeric collisions on available interfaces detected by endpoints_seen
    -        // are probably just repeated instances - skip without logging why.
    -        const std::optional<CService> addr{Lookup(address_string, port, /*fAllowLookup=*/false)};
    -        if (addr) {
    -            if (!endpoints_seen.insert(*addr).second) continue;
    -            LogInfo("Binding RPC on address %s port %i", address_string, port);
    -            if (addr->IsBindAny()) {
    -                LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet");
    -            }
    -            auto result{g_http_server->BindAndStartListening(addr.value())};
    -            if (!result) {
    -                on_failure(required,
    -                           strprintf("Binding RPC on %s address %s failed: %s",
    +        auto result{g_http_server->BindAndStartListening(addr)};
    +        if (!result) {
    +            const auto msg{strprintf("Binding RPC on %s address %s failed: %s",
                                          required ? "required" : "optional",
    -                                     addr->ToStringAddrPort(), result.error()));
    -            } else {
    -                bind_success = true;
    +                                     addr.ToStringAddrPort(), result.error())};
    +            if (required) {
    +                LogError("%s", msg);
    +                g_http_server->StopListening();
    +                if (BindDefaultLoopbackAddresses()) {
    +                    LogError("Unable to bind default required IPv4 endpoint. Ensure the "
    +                             "port is free and retry, or specify endpoints via -rpcbind.");
    +                } else {
    +                    LogError("Unable to bind all specified endpoints for RPC server.");
    +                }
    +                return false;
                 }
    -        } else {
    -            on_failure(required,
    -                       strprintf("Could not bind RPC on %s address \"%s\" port %i: Address lookup failed "
    -                                 "(only numeric addresses are allowed).",
    -                                 required ? "required" : "optional",
    -                                 address_string, port));
    -        }
    -    }
    -
    -    if (!bind_success) {
    -        LogError("Unable to bind any endpoint for RPC server");
    -        return false;
    -    } else if (required_failure) {
    -        g_http_server->StopListening();
    -        if (BindDefaultLoopbackAddresses()) {
    -            LogError("Unable to bind default required IPv4 endpoint. Ensure the "
    -                     "port is free and retry, or specify endpoints via -rpcbind.");
    -        } else {
    -            LogError("Unable to bind all specified endpoints for RPC server.");
    +            LogWarning("%s", msg);
             }
    -        return false;
         }
     
         LogDebug(BCLog::HTTP, "Initialized HTTP server");
    
    

    </details>

    WDYT ?


    hodlinator commented at 11:27 AM on November 9, 2026:

    thread #36187 (review):

    Good ideas! Added as refactor-commit in the middle. Nice to get rid of the on_failure-lambda.

  35. janb84 commented at 2:47 PM on November 5, 2026: contributor

    ACK 05de7be9d745df64b04fbedc08abd2fd5159b837

    This PR will solve the problem stated in the PR description. Some observations/ NITS:

    "Node runners who only have IPv6 are now required to override -rpcbind to only specify the working interface if they were not doing so already."

    Isn't it more correct to say that: "Node runners who only have IPv6 are now required to override -rpcbind and -rpcallowip to only specify the working interface if they were not doing so already." Without -rpcallowip=::1 it will still fail.

    The code will solve a ipv4 squatter situation, but not the case when there is a ipv6 sqatter and localhost is used for bitcoin-cli , 'bitcoin-cli -rpcconnect=localhost` tries [::1] before 127.0.0.1 . Not a blocker because 127.0.0.1 is explicitly used but just an observation.

    Found a non-blocking NIT in the code, see below.

  36. DrahtBot requested review from sedited on Nov 5, 2026
  37. in src/httpserver.cpp:236 in 05de7be9d7
     236 | +    if (BindDefaultLoopbackAddresses()) {
     237 | +        // We allow the default IPv6 bind to fail, but IPv4 is required even
     238 | +        // with the default port as bitcoin-cli will default to handing RPC
     239 | +        // credentials in plaintext to whatever process is running on that port.
     240 | +        endpoints.push_back({.address = "::1",       .port = http_port, .required = false});
     241 | +        endpoints.push_back({.address = "127.0.0.1", .port = http_port, .required = true});
    


    winterrdog commented at 9:15 PM on November 5, 2026:

    not a blocker, just wanted to understand why IPv4 does not come first in the vector, given that it is the required endpoint for successful startup ?


    hodlinator commented at 10:30 AM on November 9, 2026:

    re #36187 (review):

    I prefer maintaining the same order as on master.


    winterrdog commented at 7:50 PM on November 9, 2026:

    i had put IPv4 first mostly because bitcoin-cli defaults to 127.0.0.1. so, if that endpoint cannot be bound, we already know that the default client cannot safely connect to bitcoind

    with this ordering, we can abort before even attempting IPv6, rather than starting an RPC server that bitcoin-cli cannot reliably reach.

    that was my reasoning


    hodlinator commented at 7:49 AM on November 16, 2026:

    Yes, it comes down to keeping the diffs clear vs avoiding unnecessary work in the case that IPv6 binding succeeds but then IPv4 binding fails. I guess optimizing for the end state after the PR is also an aspect in your favor. I'll swap the order if I need to re-touch, unless others are against the swap.

  38. in src/httpserver.cpp:1352 in 05de7be9d7 outdated
    1348 | @@ -1351,29 +1349,59 @@ bool InitHTTPServer()
    1349 |      g_http_server->SetMaxConnections(std::max(gArgs.GetArg<int>("-rpcmaxconnections", DEFAULT_MAX_HTTP_CONNECTIONS), 1));
    1350 |  
    1351 |      // Bind HTTP server to specified addresses
    1352 | -    std::vector<std::pair<std::string, uint16_t>> endpoints{GetBindAddresses()};
    1353 | +    std::vector<BindAddress> endpoints{GetBindAddresses()};
    


    winterrdog commented at 9:32 PM on November 5, 2026:

    GetBindAddresses() can sometimes return an empty vector. I think we could handle that here and return early

  39. DrahtBot requested review from winterrdog on Nov 5, 2026
  40. hodlinator force-pushed on Nov 9, 2026
  41. hodlinator commented at 11:53 AM on November 9, 2026: contributor

    Pushed 1e5767518ac5e1b760401deeb353cf02743c85ce to address latest round of review.

  42. janb84 commented at 12:46 PM on November 9, 2026: contributor

    t ACK 1e5767518ac5e1b760401deeb353cf02743c85ce

    As per description, this PR closes a real credential leak. Checked, verified and tested.

    Thanks for taking the lookup suggestion!

    LGTM !

  43. winterrdog commented at 7:54 PM on November 9, 2026: contributor

    tested ACK 1e5767518ac5e1b760401deeb353cf02743c85ce

    successfully built and tested with clang++-20 on Debian, targeting x86_64

  44. in src/httpserver.cpp:1371 in 1e5767518a
    1387 | -        return false;
    1388 | +    std::set<CService> endpoints_seen;
    1389 | +    for (const auto& [addr, required] : endpoints) {
    1390 | +        // Addresses are numeric, so collisions detected by endpoints_seen are
    1391 | +        // probably just repeated instances - skip without logging why.
    1392 | +        if (!endpoints_seen.insert(addr).second) continue;
    


    l0rinc commented at 9:37 PM on November 9, 2026:

    1e57675 http: fail closed on partial binds:

    Could we deduplicate while building endpoints? It's quadratic, but likely a lot faster because we don't expect many element. Then the bind loop can use the collected list directly without keeping a separate set.

    <details> <summary>Deduplicate while collecting RPC endpoints</summary>

    diff --git a/src/httpserver.cpp b/src/httpserver.cpp
    index 83cf042a3e..eb085dc50d 100644
    --- a/src/httpserver.cpp
    +++ b/src/httpserver.cpp
    @@ -28,12 +28,12 @@
     #include <util/time.h>
     #include <util/translation.h>
     
    +#include <algorithm>
     #include <condition_variable>
     #include <cstdio>
     #include <cstdlib>
     #include <memory>
     #include <optional>
    -#include <set>
     #include <span>
     #include <string>
     #include <string_view>
    @@ -257,6 +257,8 @@ static std::vector<BindAddress> GetBindAddresses()
                              "(only numeric addresses are allowed).", host, port);
                     return {}; // empty
                 }
    +            // Skip repeated endpoints, binding the same one twice would fail.
    +            if (std::ranges::find(endpoints, *addr, &BindAddress::addr) != endpoints.end()) continue;
                 endpoints.push_back({.addr = *addr, .required = true});
             }
         }
    @@ -1393,12 +1395,7 @@ bool InitHTTPServer()
             return false;
         }
     
    -    std::set<CService> endpoints_seen;
         for (const auto& [addr, required] : endpoints) {
    -        // Addresses are numeric, so collisions detected by endpoints_seen are
    -        // probably just repeated instances - skip without logging why.
    -        if (!endpoints_seen.insert(addr).second) continue;
    -
             LogInfo("Binding RPC on address %s", addr.ToStringAddrPort());
             if (addr.IsBindAny()) {
                 LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet");
    

    </details>


    hodlinator commented at 9:22 AM on November 10, 2026:

    re #36187 (review):

    Was thinking deduplicating on the receiver side was somehow better defensive programming, but within the same file it's not that important, and we indeed do not expect many bind-addresses. Taken.

  45. in test/functional/rpc_bind.py:211 in 1e5767518a
     207 | @@ -141,6 +208,8 @@ def _run_loopback_tests(self):
     208 |              # check only IPv4 localhost (explicit)
     209 |              self.run_bind_test(['127.0.0.1'], '127.0.0.1', ['127.0.0.1'],
     210 |                  [('127.0.0.1', self.defaultport)])
     211 | +            self.run_bind_test(['127.0.0.1'], '127.0.0.1', ['127.0.0.1', '127.0.0.1'],
    


    l0rinc commented at 9:38 PM on November 9, 2026:

    1e57675 http: fail closed on partial binds:

    nit: move a repeated endpoint to the existing multi-port case and drop this separate restart.

    <details> <summary>Combine duplicate and multi-port coverage</summary>

    diff --git a/test/functional/rpc_bind.py b/test/functional/rpc_bind.py
    index ffc23c57de..450e00df58 100755
    --- a/test/functional/rpc_bind.py
    +++ b/test/functional/rpc_bind.py
    @@ -208,13 +208,11 @@ class RPCBindTest(BitcoinTestFramework):
                 # check only IPv4 localhost (explicit)
                 self.run_bind_test(['127.0.0.1'], '127.0.0.1', ['127.0.0.1'],
                     [('127.0.0.1', self.defaultport)])
    -            self.run_bind_test(['127.0.0.1'], '127.0.0.1', ['127.0.0.1', '127.0.0.1'],
    -                [('127.0.0.1', self.defaultport)])
                 # check only IPv4 localhost (explicit) with alternative port
                 self.run_bind_test(['127.0.0.1'], '127.0.0.1:32171', ['127.0.0.1:32171'],
                     [('127.0.0.1', 32171)])
    -            # check only IPv4 localhost (explicit) with multiple alternative ports on same host
    -            self.run_bind_test(['127.0.0.1'], '127.0.0.1:32171', ['127.0.0.1:32171', '127.0.0.1:32172'],
    +            # check only IPv4 localhost (explicit) with multiple alternative ports on same host, one of them repeated
    +            self.run_bind_test(['127.0.0.1'], '127.0.0.1:32171', ['127.0.0.1:32171', '127.0.0.1:32172', '127.0.0.1:32171'],
                     [('127.0.0.1', 32171), ('127.0.0.1', 32172)])
             else:
                 # check default without rpcallowip (IPv4 and IPv6 localhost)
    

    </details>


    hodlinator commented at 10:03 AM on November 10, 2026:

    re #36187 (review):

    Taken, although I opted for repeating 127.0.0.1:32172 so one can more easily compare.

  46. in test/functional/rpc_bind.py:192 in 1e5767518a
     187 | @@ -124,6 +188,9 @@ def run_test(self):
     188 |          self.defaultport = rpc_port(0)
     189 |  
     190 |          if not self.options.run_nonloopback:
     191 | +            if not self.options.run_ipv4:
     192 | +                for explicit_binds in [False, True]:
    


    l0rinc commented at 9:39 PM on November 9, 2026:

    1e57675 http: fail closed on partial binds:

    If we move this to the end of the else branch in _run_loopback_tests(), it would remove the extra check and leave run_test() unchanged.

    <details> <summary>Run partial-bind cases after the existing loopback tests</summary>

    diff --git a/test/functional/rpc_bind.py b/test/functional/rpc_bind.py
    index 450e00df58..5d923f8415 100755
    --- a/test/functional/rpc_bind.py
    +++ b/test/functional/rpc_bind.py
    @@ -188,9 +188,6 @@ class RPCBindTest(BitcoinTestFramework):
             self.defaultport = rpc_port(0)
     
             if not self.options.run_nonloopback:
    -            if not self.options.run_ipv4:
    -                for explicit_binds in [False, True]:
    -                    self.run_partial_bind_test(explicit_binds)
                 self._run_loopback_tests()
                 if self.options.run_ipv4:
                     self.run_invalid_bind_test(['127.0.0.1'], ['127.0.0.1:notaport', '127.0.0.1:-18443', '127.0.0.1:0', '127.0.0.1:65536'])
    @@ -227,6 +224,8 @@ class RPCBindTest(BitcoinTestFramework):
                 # check both IPv4 and IPv6 localhost (explicit)
                 self.run_bind_test(['127.0.0.1'], '127.0.0.1', ['127.0.0.1', '[::1]'],
                     [('127.0.0.1', self.defaultport), ('::1', self.defaultport)])
    +            for explicit_binds in [False, True]:
    +                self.run_partial_bind_test(explicit_binds)
     
         def _run_nonloopback_tests(self):
             self.log.info("Using interface %s for testing" % self.non_loopback_ip)
    

    </details>

  47. in test/functional/rpc_bind.py:121 in 1e5767518a
     116 | +                started = False
     117 | +                error = str(e)
     118 | +                self.cleanup_partially_started_nodes()
     119 | +        self.nodes[0].rpchost = None
     120 | +
     121 | +        assert_equal(started, False)
    


    l0rinc commented at 9:40 PM on November 9, 2026:

    1e57675 http: fail closed on partial binds:

    I'd keep the credential capture in the characterization commit and use assert_start_raises_init_error() for the permanent regression test.

    <details> <summary>Use the existing startup-error helper</summary>

    diff --git a/test/functional/rpc_bind.py b/test/functional/rpc_bind.py
    index 5d923f8415..02b42fce35 100755
    --- a/test/functional/rpc_bind.py
    +++ b/test/functional/rpc_bind.py
    @@ -5,13 +5,11 @@
     """Test running bitcoind with the -rpcbind and -rpcallowip options."""
     
     import socket
    -import subprocess
    -import time
     
     from test_framework.netutil import NETWORK_ERRORS, all_interfaces, addr_to_hex, get_bind_addrs, test_ipv6_local
     from test_framework.test_framework import BitcoinTestFramework, SkipTest
    -from test_framework.test_node import ErrorMatch, FailedToStartError
    -from test_framework.util import assert_equal, get_auth_cookie, rpc_port, str_to_b64str
    +from test_framework.test_node import ErrorMatch
    +from test_framework.util import assert_equal, rpc_port
     
     class RPCBindTest(BitcoinTestFramework):
         def set_test_params(self):
    @@ -64,63 +62,12 @@ class RPCBindTest(BitcoinTestFramework):
     
         def run_partial_bind_test(self, explicit_binds):
             self.log.info(f'Check startup when the {"explicit" if explicit_binds else "default IPv4"} RPC address is already owned')
    -        self.nodes[0].rpchost = '[::1]'
    -        error = ''
    -        credential_captured = False
    -        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    -            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    -            sock.bind(('127.0.0.1', self.defaultport))
    -            sock.listen()
    -            sock.settimeout(0.1)
    -            try:
    -                extra_args = ['-disablewallet', '-nolisten']
    -                if explicit_binds:
    -                    extra_args += ['-rpcallowip=127.0.0.1', '-rpcbind=127.0.0.1', '-rpcbind=[::1]']
    -                self.start_node(0, extra_args=extra_args)
    -                started = True
    -                cli = subprocess.Popen([
    -                    self.nodes[0].binaries.paths.bitcoincli,
    -                    f'-datadir={self.nodes[0].datadir_path}',
    -                    '-noipcconnect',
    -                    '-rpcclienttimeout=2',
    -                    'getblockcount',
    -                ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    -                try:
    -                    conn = None
    -                    deadline = time.monotonic() + 5
    -                    while conn is None and time.monotonic() < deadline:
    -                        try:
    -                            conn = sock.accept()[0]
    -                        except TimeoutError:
    -                            if cli.poll() is not None:
    -                                _, stderr = cli.communicate()
    -                                raise AssertionError(f'bitcoin-cli exited before connecting: {stderr.decode()}')
    -                    assert conn is not None
    -                    with conn:
    -                        conn.settimeout(5)
    -                        request = b''
    -                        while b'\r\n\r\n' not in request:
    -                            chunk = conn.recv(4096)
    -                            assert chunk
    -                            request += chunk
    -                        conn.sendall(b'HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\nConnection: close\r\n\r\n')
    -                    cli.communicate(timeout=5)
    -                finally:
    -                    if cli.poll() is None:
    -                        cli.kill()
    -                        cli.wait()
    -                user, password = get_auth_cookie(self.nodes[0].datadir_path, self.chain)
    -                credential_captured = f'Authorization: Basic {str_to_b64str(f"{user}:{password}")}\r\n'.encode() in request
    -                self.stop_node(0)
    -            except FailedToStartError as e:
    -                started = False
    -                error = str(e)
    -                self.cleanup_partially_started_nodes()
    -        self.nodes[0].rpchost = None
    -
    -        assert_equal(started, False)
    -        assert_equal(credential_captured, False)
    -        assert 'Unable to start HTTP server' in error
    +        extra_args = ['-disablewallet', '-nolisten']
    +        if explicit_binds:
    +            extra_args += ['-rpcallowip=127.0.0.1', '-rpcbind=127.0.0.1', '-rpcbind=[::1]']
    +        with socket.create_server(('127.0.0.1', self.defaultport)):
    +            with self.nodes[0].assert_debug_log([f'Binding RPC on required address 127.0.0.1:{self.defaultport} failed:']):
    +                self.nodes[0].assert_start_raises_init_error(extra_args, 'Error: Unable to start HTTP server. See debug log for details.')
     
         def run_allowip_test(self, allow_ips, rpchost, rpcport):
             '''
    

    </details>


    hodlinator commented at 10:07 AM on November 10, 2026:

    re #36187 (review):

    Flipping the assert_equal()s felt clear, but agree that it's good to keep the test simpler going forward. Taken with little modification. Simplified the initial characterization commit as well to make the diff smaller.

  48. in src/httpserver.cpp:1386 in 1e5767518a
    1402 | +                                     addr.ToStringAddrPort(), result.error())};
    1403 | +            if (required) {
    1404 | +                LogError("%s", msg);
    1405 | +                g_http_server->StopListening();
    1406 | +                if (BindDefaultLoopbackAddresses()) {
    1407 | +                    LogError("Unable to bind default required IPv4 endpoint. Ensure the "
    


    l0rinc commented at 9:40 PM on November 9, 2026:

    1e57675 http: fail closed on partial binds:

    My understanding is that without -rpcallowip, the suggested -rpcbind is ignored and an IPv6-only host gets the same startup failure again.

    <details> <summary>Include both required options in the IPv4 failure hint</summary>

    diff --git a/src/httpserver.cpp b/src/httpserver.cpp
    index eb085dc50d..ad873c770f 100644
    --- a/src/httpserver.cpp
    +++ b/src/httpserver.cpp
    @@ -1410,7 +1410,8 @@ bool InitHTTPServer()
                     g_http_server->StopListening();
                     if (BindDefaultLoopbackAddresses()) {
                         LogError("Unable to bind default required IPv4 endpoint. Ensure the "
    -                             "port is free and retry, or specify endpoints via -rpcbind.");
    +                             "port is free and retry, or specify endpoints via -rpcbind "
    +                             "together with -rpcallowip.");
                     } else {
                         LogError("Unable to bind all specified endpoints for RPC server.");
                     }
    

    </details>

  49. l0rinc commented at 9:46 PM on November 9, 2026: contributor

    I'll review this in more detail a bit later, left a few low-effort suggestions in the meantime...

  50. DrahtBot requested review from l0rinc on Nov 9, 2026
  51. hodlinator force-pushed on Nov 11, 2026
  52. hodlinator commented at 3:48 PM on November 11, 2026: contributor

    Pushed new version based on l0rinc's initial feedback, sorry for invalidating the 2 ACKs.

  53. hodlinator commented at 7:22 PM on November 11, 2026: contributor

    Removed AI Disclaimer from PR desc as it could be taken as avoidance of responsibility. Credits for finding the credential exfiltration vulnerability and the initial broad strokes solution still go in part to LLMs.

  54. in src/httpserver.cpp:261 in a8e7faa477
     257 | +                LogError("Could not lookup RPC bind address \"%s\" port %i "
     258 | +                         "(only numeric addresses are allowed).", host, port);
     259 | +                return {}; // empty
     260 | +            }
     261 | +            // Skip repeated endpoints, binding the same one twice would fail.
     262 | +            if (std::ranges::find(endpoints, *addr, &BindAddress::addr) == endpoints.end()) {
    


    l0rinc commented at 8:41 PM on November 11, 2026:

    a8e7faa http: fail closed on partial binds:

    (edited) CService equality ignores the IPv6 scope ID, so the new dedupe drops -rpcbind=[fe80::1%2] after -rpcbind=[fe80::1%1] without a warning, while master attempts both binds. ToStringAddrPort() comparison should probably fix it.

    <details> <summary>Bind one link-local address on two interfaces</summary>

    diff --git a/src/test/httpserver_tests.cpp b/src/test/httpserver_tests.cpp
    index 3a5947a7d7..f961682a73 100644
    --- a/src/test/httpserver_tests.cpp
    +++ b/src/test/httpserver_tests.cpp
    @@ -857,6 +857,23 @@ BOOST_AUTO_TEST_CASE(http_should_disconnect_tests)
         }
     }
     
    +BOOST_AUTO_TEST_CASE(rpc_bind_scopes)
    +{
    +    // Same link-local address on two interfaces: both must be bound
    +    const char* argv[]{"", "-rpcbind=[fe80::1%1]", "-rpcbind=[fe80::1%2]"};
    +    std::string error;
    +    BOOST_REQUIRE(gArgs.ParseParameters(std::size(argv), argv, error));
    +
    +    int sockets{0};
    +    CreateSock = [&sockets, create_sock{CreateSock}](int domain, int type, int protocol) {
    +        ++sockets;
    +        return create_sock(domain, type, protocol);
    +    };
    +    BOOST_CHECK(InitHTTPServer());
    +    StopHTTPServer();
    +    BOOST_CHECK_EQUAL(sockets, 2);
    +}
    +
     BOOST_AUTO_TEST_CASE(http_server_socket_tests)
     {
         // Hard code the timestamp for the Date header in the HTTP response
    

    </details>


    hodlinator commented at 1:28 PM on November 13, 2026:

    Thanks for finding this! Added the test and fixed in latest push, but I had to expose an accessor for CNetAddr::m_scope_id.

  55. l0rinc changes_requested
  56. in test/functional/rpc_bind.py:69 in a8e7faa477
      64 | +        self.log.info(f'Check startup when the {"explicit" if explicit_binds else "default IPv4"} RPC address is already owned')
      65 | +        extra_args = ['-disablewallet', '-nolisten']
      66 | +        if explicit_binds:
      67 | +            extra_args += ['-rpcallowip=127.0.0.1', '-rpcbind=127.0.0.1', '-rpcbind=[::1]']
      68 | +
      69 | +        with socket.create_server(('127.0.0.1', self.defaultport), reuse_port=True), \
    


    l0rinc commented at 8:15 AM on November 12, 2026:

    a8e7faa http: fail closed on partial binds:

    I don't think reuse_port=True is needed: create_server() already sets SO_REUSEADDR on POSIX, and both occupied-port cases pass without it on macOS and Linux. The characterization commit has the same flag.

    nit: since this statement changes anyway, a parenthesized with gets rid of the weird trailing backslash.

    <details> <summary>Reserve the IPv4 port without SO_REUSEPORT</summary>

    diff --git a/test/functional/rpc_bind.py b/test/functional/rpc_bind.py
    index 8682b2581f..2ca7a206c0 100755
    --- a/test/functional/rpc_bind.py
    +++ b/test/functional/rpc_bind.py
    @@ -66,8 +66,10 @@ class RPCBindTest(BitcoinTestFramework):
             if explicit_binds:
                 extra_args += ['-rpcallowip=127.0.0.1', '-rpcbind=127.0.0.1', '-rpcbind=[::1]']
     
    -        with socket.create_server(('127.0.0.1', self.defaultport), reuse_port=True), \
    -             self.nodes[0].assert_debug_log([f'Binding RPC on required address 127.0.0.1:{self.defaultport} failed:']):
    +        with (
    +            socket.create_server(('127.0.0.1', self.defaultport)),
    +            self.nodes[0].assert_debug_log([f'Binding RPC on required address 127.0.0.1:{self.defaultport} failed:']),
    +        ):
                 self.nodes[0].assert_start_raises_init_error(extra_args, 'Error: Unable to start HTTP server. See debug log for details.')
     
         def run_allowip_test(self, allow_ips, rpchost, rpcport):
    

    </details>


    l0rinc commented at 8:15 AM on November 12, 2026:

    f103468 test: characterize partial HTTP binds:

    nit: assert_equal(started, True) can never fail, since a failing start_node() already leaves the function before it. Dropping started and the initial credential_captured = False changes nothing, and the TODO fits on the start_node() line itself.

    <details> <summary>Remove dead startup state from the characterization</summary>

    --- a/test/functional/rpc_bind.py
    +++ b/test/functional/rpc_bind.py
    @@ -69,12 +69,9 @@
                 extra_args += ['-rpcallowip=127.0.0.1', '-rpcbind=127.0.0.1', '-rpcbind=[::1]']
     
             self.nodes[0].rpchost = '[::1]'
    -        credential_captured = False
    -        started = False
             with socket.create_server(('127.0.0.1', self.defaultport), reuse_port=True) as sock:
                 sock.settimeout(0.1)
    -            self.start_node(0, extra_args=extra_args)
    -            started = True # Not set if start_node() raises FailedToStartError
    +            self.start_node(0, extra_args=extra_args)  # TODO: an occupied RPC listener must abort startup to protect credentials
                 cli = subprocess.Popen([
                     self.nodes[0].binaries.paths.bitcoincli,
                     f'-datadir={self.nodes[0].datadir_path}',
    @@ -111,7 +108,6 @@
                 self.stop_node(0)
             self.nodes[0].rpchost = None
     
    -        assert_equal(started, True)  # TODO: an occupied RPC listener must abort startup to protect credentials
             assert_equal(credential_captured, True)  # TODO: a client credential must not reach another process's listener
     
         def run_allowip_test(self, allow_ips, rpchost, rpcport):
    

    </details>


    hodlinator commented at 1:37 PM on November 13, 2026:

    create_server() already sets SO_REUSEADDR on POSIX

    True (https://docs.python.org/3/library/socket.html#socket.create_server), removed in latest push.

  57. in src/httpserver.cpp:221 in a8e7faa477 outdated
     217 | +{
     218 | +    // Default to loopback if not allowing external IPs
     219 | +    return gArgs.GetArgs("-rpcallowip").empty() || gArgs.GetArgs("-rpcbind").empty();
     220 | +}
     221 | +
     222 | +static std::vector<BindAddress> GetBindAddresses()
    


    l0rinc commented at 8:15 AM on November 12, 2026:

    85e3162 refactor: Lookup bind addresses already during GetBindAddresses():

    This refactor already changes the endpoint type, so it seems like the natural place to introduce BindAddress, with just the CService for now. The fail-closed commit would then only need to add required, and the endpoint types wouldn't change twice.

    <details> <summary>Introduce the wrapper before adding bind requirements</summary>

    --- a/src/httpserver.cpp
    +++ b/src/httpserver.cpp
    @@ -206,10 +206,14 @@
         WriteNoStoreErrorReply(*hreq, HTTP_SERVICE_UNAVAILABLE);
     }
     
    -static std::vector<CService> GetBindAddresses()
    +struct BindAddress {
    +    CService addr;
    +};
    +
    +static std::vector<BindAddress> GetBindAddresses()
     {
         uint16_t http_port{static_cast<uint16_t>(gArgs.GetIntArg("-rpcport", BaseParams().RPCPort()))};
    -    std::vector<CService> endpoints;
    +    std::vector<BindAddress> endpoints;
     
         // Determine what addresses to bind to
         // To prevent misconfiguration and accidental exposure of the RPC
    @@ -219,8 +223,8 @@
         if (gArgs.GetArgs("-rpcallowip").empty() || gArgs.GetArgs("-rpcbind").empty()) { // Default to loopback if not allowing external IPs
             // Numeric literals always parse, InitHTTPAllowList() relies on the same.
             // Never fall back to CService{}, which is [::]:0 and binds every interface.
    -        endpoints.push_back(Lookup("::1", http_port, /*fAllowLookup=*/false).value());
    -        endpoints.push_back(Lookup("127.0.0.1", http_port, /*fAllowLookup=*/false).value());
    +        endpoints.push_back({.addr = Lookup("::1", http_port, /*fAllowLookup=*/false).value()});
    +        endpoints.push_back({.addr = Lookup("127.0.0.1", http_port, /*fAllowLookup=*/false).value()});
     
             if (!gArgs.GetArgs("-rpcallowip").empty()) {
                 LogWarning("Option -rpcallowip was specified without -rpcbind; this doesn't usually make sense");
    @@ -243,7 +247,7 @@
                                "(only numeric addresses are allowed).", host, port);
                     continue;
                 }
    -            endpoints.push_back(*addr);
    +            endpoints.push_back({.addr = *addr});
             }
         }
         return endpoints;
    @@ -1373,9 +1377,9 @@
         g_http_server->SetMaxConnections(std::max(gArgs.GetArg<int>("-rpcmaxconnections", DEFAULT_MAX_HTTP_CONNECTIONS), 1));
     
         // Bind HTTP server to specified addresses
    -    std::vector<CService> endpoints{GetBindAddresses()};
    +    auto endpoints{GetBindAddresses()};
         bool bind_success{false};
    -    for (const auto& addr : endpoints) {
    +    for (const auto& [addr] : endpoints) {
             LogInfo("Binding RPC on address %s", addr.ToStringAddrPort());
             if (addr.IsBindAny()) {
                 LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet");
    

    </details>

  58. in src/httpserver.cpp:1364 in a8e7faa477 outdated
    1377 | -                bind_success = true;
    1378 | -            }
    1379 | -        } else {
    1380 | -            LogWarning("Could not bind RPC on address %s port %i: Address lookup failed.", address_string, port);
    1381 | -        }
    1382 | +    std::vector<BindAddress> endpoints{GetBindAddresses()};
    


    l0rinc commented at 8:42 AM on November 12, 2026:

    a8e7faa http: fail closed on partial binds:

    nit: the initializers and ranges already have unambiguous types, so auto works for endpoints, both ports, the lookup result and the -rpcbind loop element. Reading the port with GetArg<uint16_t> also removes the static_cast, and CheckHostPortOptions() already rejects an out-of-range -rpcport at startup.

    <details> <summary>Deduce types supplied by initializers and ranges</summary>

    diff --git a/src/httpserver.cpp b/src/httpserver.cpp
    index adb85f43d3..070e14d402 100644
    --- a/src/httpserver.cpp
    +++ b/src/httpserver.cpp
    @@ -220,7 +220,7 @@ static bool BindDefaultLoopbackAddresses()
     
     static std::vector<BindAddress> GetBindAddresses()
     {
    -    uint16_t http_port{static_cast<uint16_t>(gArgs.GetIntArg("-rpcport", BaseParams().RPCPort()))};
    +    auto http_port{gArgs.GetArg<uint16_t>("-rpcport", BaseParams().RPCPort())};
         std::vector<BindAddress> endpoints;
     
         // Determine what addresses to bind to
    @@ -243,15 +243,15 @@ static std::vector<BindAddress> GetBindAddresses()
                 LogWarning("Option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect");
             }
         } else { // Specific bind addresses
    -        for (const std::string& strRPCBind : gArgs.GetArgs("-rpcbind")) {
    -            uint16_t port{http_port};
    +        for (const auto& strRPCBind : gArgs.GetArgs("-rpcbind")) {
    +            auto port{http_port};
                 std::string host;
                 if (!SplitHostPort(strRPCBind, port, host)) {
                     LogError("%s\n", InvalidPortErrMsg("-rpcbind", strRPCBind).original);
                     return {}; // empty
                 }
                 // Don't allow hostname lookups when binding to local interfaces.
    -            const std::optional<CService> addr{Lookup(host, port, /*fAllowLookup=*/false)};
    +            const auto addr{Lookup(host, port, /*fAllowLookup=*/false)};
                 if (!addr) {
                     LogError("Could not lookup RPC bind address \"%s\" port %i "
                              "(only numeric addresses are allowed).", host, port);
    @@ -1390,7 +1390,7 @@ bool InitHTTPServer()
         g_http_server->SetMaxConnections(std::max(gArgs.GetArg<int>("-rpcmaxconnections", DEFAULT_MAX_HTTP_CONNECTIONS), 1));
     
         // Bind HTTP server to specified addresses
    -    std::vector<BindAddress> endpoints{GetBindAddresses()};
    +    auto endpoints{GetBindAddresses()};
         if (endpoints.empty()) {
             // GetBindAddresses() already emitted a LogError() before returning empty.
             return false;
    

    </details>


    hodlinator commented at 2:49 PM on November 13, 2026:

    Good point regarding GetArg<uint16_t>()! Kept slightly more explicit local type info in the other cases for now.

  59. in src/httpserver.cpp:254 in a8e7faa477
     249 | @@ -232,7 +250,17 @@ static std::vector<std::pair<std::string, uint16_t>> GetBindAddresses()
     250 |                  LogError("%s\n", InvalidPortErrMsg("-rpcbind", strRPCBind).original);
     251 |                  return {}; // empty
     252 |              }
     253 | -            endpoints.emplace_back(host, port);
     254 | +            // Don't allow hostname lookups when binding to local interfaces.
     255 | +            const std::optional<CService> addr{Lookup(host, port, /*fAllowLookup=*/false)};
    


    l0rinc commented at 8:42 AM on November 12, 2026:

    a8e7faa http: fail closed on partial binds:

    nit: with the lookup in the if initializer, addr only lives in the branch that uses it, and the happy path comes first (similarly to a try/catch) - the same in the parsing refactor would also drop its continue.

    <details> <summary>Scope the lookup result to its branch</summary>

    diff --git a/src/httpserver.cpp b/src/httpserver.cpp
    index 070e14d402..80a0d97726 100644
    --- a/src/httpserver.cpp
    +++ b/src/httpserver.cpp
    @@ -251,16 +251,16 @@ static std::vector<BindAddress> GetBindAddresses()
                     return {}; // empty
                 }
                 // Don't allow hostname lookups when binding to local interfaces.
    -            const auto addr{Lookup(host, port, /*fAllowLookup=*/false)};
    -            if (!addr) {
    +            if (const auto addr{Lookup(host, port, /*fAllowLookup=*/false)}) {
    +                // Skip repeated endpoints, binding the same one twice would fail.
    +                if (std::ranges::find(endpoints, *addr, &BindAddress::addr) == endpoints.end()) {
    +                    endpoints.push_back({.addr = *addr, .required = true});
    +                }
    +            } else {
                     LogError("Could not lookup RPC bind address \"%s\" port %i "
                              "(only numeric addresses are allowed).", host, port);
                     return {}; // empty
                 }
    -            // Skip repeated endpoints, binding the same one twice would fail.
    -            if (std::ranges::find(endpoints, *addr, &BindAddress::addr) == endpoints.end()) {
    -                endpoints.push_back({.addr = *addr, .required = true});
    -            }
             }
         }
         return endpoints;
    

    </details>

  60. in src/httpserver.cpp:1371 in a8e7faa477
    1387 |  
    1388 | -    if (!bind_success) {
    1389 | -        LogError("Unable to bind any endpoint for RPC server");
    1390 | -        return false;
    1391 | +    for (const auto& [addr, required] : endpoints) {
    1392 | +        LogInfo("Binding RPC on address %s", addr.ToStringAddrPort());
    


    l0rinc commented at 8:42 AM on November 12, 2026:

    a8e7faa http: fail closed on partial binds:

    nit: some of these messages quote the bind address and some don't. Single quotes throughout would make them consistent, and the lookup error would no longer need escaped double quotes.

    <details> <summary>Use single quotes around RPC bind addresses</summary>

    diff --git a/src/httpserver.cpp b/src/httpserver.cpp
    index 80a0d97726..4ad082523b 100644
    --- a/src/httpserver.cpp
    +++ b/src/httpserver.cpp
    @@ -257,8 +257,7 @@ static std::vector<BindAddress> GetBindAddresses()
                         endpoints.push_back({.addr = *addr, .required = true});
                     }
                 } else {
    -                LogError("Could not lookup RPC bind address \"%s\" port %i "
    -                         "(only numeric addresses are allowed).", host, port);
    +                LogError("Could not lookup RPC bind address '%s' port %i (only numeric addresses are allowed).", host, port);
                     return {}; // empty
                 }
             }
    @@ -1397,13 +1396,13 @@ bool InitHTTPServer()
         }
     
         for (const auto& [addr, required] : endpoints) {
    -        LogInfo("Binding RPC on address %s", addr.ToStringAddrPort());
    +        LogInfo("Binding RPC on address '%s'", addr.ToStringAddrPort());
             if (addr.IsBindAny()) {
                 LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet");
             }
             auto result{g_http_server->BindAndStartListening(addr)};
             if (!result) {
    -            const auto msg{strprintf("Binding RPC on %s address %s failed: %s",
    +            const auto msg{strprintf("Binding RPC on %s address '%s' failed: %s",
                                          required ? "required" : "optional",
                                          addr.ToStringAddrPort(), result.error())};
                 if (required) {
    diff --git a/test/functional/rpc_bind.py b/test/functional/rpc_bind.py
    index 2ca7a206c0..9ef2e5b6c9 100755
    --- a/test/functional/rpc_bind.py
    +++ b/test/functional/rpc_bind.py
    @@ -68,7 +68,7 @@ class RPCBindTest(BitcoinTestFramework):
     
             with (
                 socket.create_server(('127.0.0.1', self.defaultport)),
    -            self.nodes[0].assert_debug_log([f'Binding RPC on required address 127.0.0.1:{self.defaultport} failed:']),
    +            self.nodes[0].assert_debug_log([f"Binding RPC on required address '127.0.0.1:{self.defaultport}' failed:"]),
             ):
                 self.nodes[0].assert_start_raises_init_error(extra_args, 'Error: Unable to start HTTP server. See debug log for details.')
     
    

    </details>

  61. in src/httpserver.cpp:1377 in a8e7faa477
    1393 | +        if (addr.IsBindAny()) {
    1394 | +            LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet");
    1395 | +        }
    1396 | +        auto result{g_http_server->BindAndStartListening(addr)};
    1397 | +        if (!result) {
    1398 | +            const auto msg{strprintf("Binding RPC on %s address %s failed: %s",
    


    l0rinc commented at 8:42 AM on November 12, 2026:

    a8e7faa http: fail closed on partial binds:

    Since required already picks the branch, each branch can log its own message, which drops the temporary msg and its required ? "required" : "optional" ternary.

    <details> <summary>Inline required and optional failure messages</summary>

    diff --git a/src/httpserver.cpp b/src/httpserver.cpp
    index 4ad082523b..3fcea1c04f 100644
    --- a/src/httpserver.cpp
    +++ b/src/httpserver.cpp
    @@ -1402,11 +1402,8 @@ bool InitHTTPServer()
             }
             auto result{g_http_server->BindAndStartListening(addr)};
             if (!result) {
    -            const auto msg{strprintf("Binding RPC on %s address '%s' failed: %s",
    -                                     required ? "required" : "optional",
    -                                     addr.ToStringAddrPort(), result.error())};
                 if (required) {
    -                LogError("%s", msg);
    +                LogError("Binding RPC on required address '%s' failed: %s", addr.ToStringAddrPort(), result.error());
                     g_http_server->StopListening();
                     if (BindDefaultLoopbackAddresses()) {
                         LogError("Unable to bind default required IPv4 endpoint. Ensure the port is free "
    @@ -1416,7 +1413,7 @@ bool InitHTTPServer()
                     }
                     return false;
                 }
    -            LogWarning("%s", msg);
    +            LogWarning("Binding RPC on optional address '%s' failed: %s", addr.ToStringAddrPort(), result.error());
             }
         }
     
    

    </details>


    hodlinator commented at 1:44 PM on November 13, 2026:

    There's no clear winner to me, but guess avoiding an extra branch is nice and msg was just used in 2 places.

  62. l0rinc changes_requested
  63. l0rinc commented at 9:43 AM on November 12, 2026: contributor

    Thanks for taking my earlier suggestions! I went over the change more thoroughly now and left a few nits and cleanups. The reason I'm not acking yet is that the new deduplication drops IPv6 binds that differ only in their scope.

  64. test: characterize partial HTTP binds
    When the IPv4 RPC address is already owned, the server starts on its remaining IPv6 listener for both default and explicit bind configurations. bitcoin-cli then sends the generated cookie to the other process on its default IPv4 destination.
    
    Record the partial startup and exact captured Authorization credential for the following fail-closed fix.
    33eafabc10
  65. test: Cover the same local IPv6 address bound on two interfaces 94d1ec575c
  66. test: Remove attempt to bind RPC to 127.1.1.1
    The next commit requires all binds to succeed, and without this change that one would fail on Mac CI with:
    [InitHTTPServer] [warning] Binding RPC on address 127.1.1.1:19036 failed: Unable to bind to 127.1.1.1:19036 on this computer (bind returned error Can't assign requested address (49))
    
    The options in this test are there to verify log censorship of sensitive data and bind-addresses were made non-sensitive in #26829 / b9d567454159f062ce84353f5821d6e6daf433bd. That commit added the missing -rpcallowip option to actually make -rpcbind not be ignored any longer. That commit added 127.0.0.1 in addition to the already existing 127.1.1.1, probably because the latter would fail by itself.
    a75cfc7371
  67. hodlinator force-pushed on Nov 13, 2026
  68. hodlinator commented at 2:56 PM on November 13, 2026: contributor

    Latest push addresses #36187 (review) and #36187#pullrequestreview-5871193906 + adds anonymous namespace to make BindAddress fully local to httpserver.cpp.

  69. in src/httpserver.cpp:249 in 418aeaf90c outdated
     241 | @@ -232,12 +242,25 @@ static std::vector<std::pair<std::string, uint16_t>> GetBindAddresses()
     242 |                  LogError("%s\n", InvalidPortErrMsg("-rpcbind", strRPCBind).original);
     243 |                  return {}; // empty
     244 |              }
     245 | -            endpoints.emplace_back(host, port);
     246 | +            // Don't allow hostname lookups when binding to local interfaces.
     247 | +            if (const std::optional addr{Lookup(host, port, /*fAllowLookup=*/false)}) {
     248 | +                // Skip repeated endpoints, binding the same one twice would fail.
     249 | +                if (std::ranges::find_if(endpoints, [&addr](const BindAddress& e) {
     250 | +                        return *addr == e.addr && addr->GetScope() == e.addr.GetScope();
    


    l0rinc commented at 6:26 PM on November 13, 2026:

    418aeaf http: Skip duplicate bind addresses:

    This looked fishy: why compare internal CService state separately after ==? Extending the shared operator here looks tempting, but it would also change peer connection deduplication, inbound onion listener matching and AddrMan key lookup, so we definitely should not do it in this PR. And if we do that, ordering and hashing should also be adjusted in a separate follow-up.

    The explicit scope check seems fine here, but maybe we could add a comment explaining why it is needed, something like:

    // CService equality ignores IPv6 scope IDs, but binding must distinguish interfaces
    return *addr == e.addr && addr->GetScope() == e.addr.GetScope();
    

    hodlinator commented at 9:57 AM on November 14, 2026:

    Agreed, I independently realized this while thinking it over again yesterday. Pushed a variation of the comment. Also realized the "Don't allow hostname lookups when binding to local interfaces."-comment above applies to other Lookup() calls so extracted allow_names-variable and hoisted it up above.

  70. l0rinc approved
  71. l0rinc commented at 6:39 PM on November 13, 2026: contributor

    ACK 44bcdbd1c6bb8409434af09f3bfa0581b5867e42

    If you need to touch this again, consider using a smaller reproducer in the characterization commit (showing that startup succeeds despite the occupied IPv4 port), with the full credential-capture proof in a collapsible section of the PR description as an optional demo. That would avoid removing all that code we just introduced in the earlier commit.

  72. DrahtBot requested review from winterrdog on Nov 13, 2026
  73. DrahtBot requested review from janb84 on Nov 13, 2026
  74. refactor: Lookup bind addresses already during GetBindAddresses()
    Allows us to catch fail earlier and have simpler code in a later commit where binds are required to succeed.
    
    Co-authored-by: janb84 <githubjanb.drainer976@passmail.net>
    Co-authored-by: winterrdog <winterrdog@protonmail.ch>
    8c468b068a
  75. http: Skip duplicate bind addresses
    While the search is quadratic, we don't expect many local bind addresses.
    6751f8f657
  76. http: fail closed on partial binds
    When any RPC bind succeeds, initialization ignores every other endpoint failure. A process that already owns the default IPv4 port can therefore receive bitcoin-cli credentials while the node continues on IPv6.
    
    Switch to safe defaults through only making the default IPv6 address optional, requiring all others. Hosts intentionally providing only an IPv6 interface must use -rpcbind to set that endpoint explicitly.
    
    This carries the fail-closed policy from bitcoin/bitcoin#14968 now that the in-tree socket implementation reports each bind result.
    
    Co-authored-by: laanwj <126646+laanwj@users.noreply.github.com>
    Co-authored-by: Lőrinc <pap.lorinc@gmail.com>
    061eb6f434
  77. hodlinator force-pushed on Nov 14, 2026
  78. l0rinc commented at 7:59 PM on November 15, 2026: contributor

    reACK 061eb6f43458d15bb12330b0667240a3a7d6e4da

    Just the explanatory comment and the shared allow_names variable and the lambda capture cleanup since my last ack.

  79. fanquake commented at 11:02 AM on November 16, 2026: member
  80. in test/functional/rpc_bind.py:72 in 061eb6f434
      67 | +            extra_args += ['-rpcallowip=127.0.0.1', '-rpcbind=127.0.0.1', '-rpcbind=[::1]']
      68 | +
      69 | +        with (socket.create_server(('127.0.0.1', self.defaultport)),
      70 | +              self.nodes[0].assert_debug_log([f"Binding RPC on required address '127.0.0.1:{self.defaultport}' failed:"])):
      71 | +            self.nodes[0].assert_start_raises_init_error(extra_args, 'Error: Unable to start HTTP server. See debug log for details.')
      72 | +
    


    janb84 commented at 2:15 PM on November 18, 2026:

    Nit, non-block. Adding something like the test below will fix 2 of the gaps in test as reported by corecheck.

    
        def run_optional_ipv6_bind_test(self):
            self.log.info('Check that the node starts on IPv4 when the default IPv6 RPC address is already owned')
            self.nodes[0].rpchost = None
            with socket.create_server(('::1', self.defaultport), family=socket.AF_INET6):
                with self.nodes[0].assert_debug_log([f"Binding RPC on optional address '[::1]:{self.defaultport}' failed:"]):
                    self.start_node(0, ['-disablewallet', '-nolisten'])
                assert_equal(set(get_bind_addrs(self.nodes[0].process.pid)), {(addr_to_hex('127.0.0.1'), self.defaultport)})
                self.stop_node(0)
    
        def run_unbindable_bind_test(self):
            self.log.info('Check that startup fails when an explicit RPC address cannot be bound, even if others succeed')
            # 192.0.2.1 (TEST-NET-1, RFC 5737) is not assigned to a local interface,
            # so bind() fails with EADDRNOTAVAIL rather than EADDRINUSE.
            extra_args = ['-disablewallet', '-nolisten', '-rpcallowip=127.0.0.1', '-rpcbind=127.0.0.1', '-rpcbind=192.0.2.1']
            with self.nodes[0].assert_debug_log([
                f"Binding RPC on address '127.0.0.1:{self.defaultport}'",
                f"Binding RPC on required address '192.0.2.1:{self.defaultport}' failed:",
            ]):
                self.nodes[0].assert_start_raises_init_error(extra_args, 'Error: Unable to start HTTP server. See debug log for details.')
    
        def run_unresolvable_bind_test(self):
            self.log.info('Check that startup fails when an explicit RPC address is not numeric, even if others are')
            extra_args = ['-disablewallet', '-nolisten', '-rpcallowip=127.0.0.1', '-rpcbind=127.0.0.1', '-rpcbind=localhost']
            with self.nodes[0].assert_debug_log(
                [f"Could not lookup RPC bind address 'localhost' port {self.defaultport} (only numeric addresses are allowed)."],
                unexpected_msgs=["Binding RPC on address"],  # fails before any bind is attempted
            ):
                self.nodes[0].assert_start_raises_init_error(extra_args, 'Error: Unable to start HTTP server. See debug log for details.')
    
    
  81. janb84 commented at 3:02 PM on November 18, 2026: contributor

    re ACK 061eb6f43458d15bb12330b0667240a3a7d6e4da

    There are some behavioral changes in startup, maybe consider adding a release-note (Ralph suggested the same, but cryptic in his reasoning). The change that could use a release note is for Ipv6 only hosts, a host or jail without 127.0.0.1 / ipv4 used to start (on master) on ::1 alone. The same functionality now needs -rpcbind=[::1] -rpcallowip=::1 other wise the node will error out.

  82. hodlinator commented at 8:53 PM on November 18, 2026: contributor

    Thanks for the review @janb84! As stated out-of-band, starting to write the release notes you suggested motivated me to look into being less harsh on IPv6-only hosts.

    Upon failure to bind the IPv4 loopback port, we could create an IPv4 socket and try to bind it to a random ephemeral port. If that also fails, we could assume that we don't have an IPv4 stack at all and let the IPv6-only bind be sufficient. I'll need some more time to investigate this.


github-metadata-mirror

This is a metadata mirror of the GitHub repository bitcoin/bitcoin. This site is not affiliated with GitHub. Content is generated from a GitHub metadata backup.
generated: 2026-11-25 17:51 UTC

This site is hosted by @0xB10C
More mirrored repositories can be found on mirror.b10c.me