Repository navigation
net: add -outboundbind option for outgoing source address - #35027
8144225309 wants to merge 3 commits into
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. External sites
ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, this pull request conflicts with the following ones:
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. |
1dc1234 to
16eefb2
Compare
|
This might break a scenario where someone wants to listen on one IP, but load balance outgoing connections. A new option might be better? |
|
The original issue asks for |
16eefb2 to
13879e1
Compare
| @@ -1131,6 +1131,15 @@ class CConnman | |||
| } | |||
| } | |||
| m_onion_binds = connOptions.onion_binds; | |||
| // Use -bind addresses for outgoing connections (one per address family). | |||
| for (const auto& bind_addr : connOptions.vBinds) { | |||
| if (bind_addr.IsLocal()) continue; | |||
There was a problem hiding this comment.
IsLocal() also matches 0.0.0.0/8, not just loopback. The PR description says "loopback addresses are skipped", but the actual skip is broader. Worth a comment somewhere, clarifying that?
There was a problem hiding this comment.
Removed entirely. Addresses are used as given, then validated: parse, wildcard, and family checks, plus a trial bind() at init.
| // Use -bind addresses for outgoing connections (one per address family). | ||
| for (const auto& bind_addr : connOptions.vBinds) { | ||
| if (bind_addr.IsLocal()) continue; | ||
| if (bind_addr.IsIPv4() && !m_outbound_bind_v4) { |
There was a problem hiding this comment.
The listen path validates the address early through BindListenPort and surfaces errors at startup. Here we store it without checking if it's actually assigned to a local interface. Would it make sense to do a trial bind() or similar check here so a misconfigured address fails loudly at init rather than silently killing outbound for that family.
There was a problem hiding this comment.
Done. IsAddrBindable() does a trial bind() at init, so a misconfigured address fails startup. It has its own unit test.
| options.vBinds = {addr1, addr2}; | ||
| connman->Init(options); | ||
| BOOST_REQUIRE(connman->GetOutboundBindV4()); | ||
| BOOST_CHECK_EQUAL(connman->GetOutboundBindV4()->ToStringAddr(), "203.0.113.1"); |
There was a problem hiding this comment.
The test verifies that the first IPv4 address is stored, but doesn't check that m_outbound_bind_v6 stays empty. If the else if condition were weakened, an IPv4 address could leak into the IPv6 slot undetected. You can avoid this by including BOOST_CHECK(!connman->GetOutboundBindV6()); around here.
| LogError("Cannot get sockaddr for bind address %s\n", bind_addr->ToStringAddr()); | ||
| return {}; | ||
| } | ||
| if (sock->Bind(reinterpret_cast<struct sockaddr*>(&bind_sa), bind_len) == SOCKET_ERROR) { |
There was a problem hiding this comment.
I believe it would it be great to add a unit test that calls ConnectDirectly with a bind address, even if just to verify the syscall is attempted. Right now the unit test covers Init-time storage but this Bind() path has no automated coverage.
There was a problem hiding this comment.
Done. A unit test checks that ConnectDirectly() binds to the given source before connecting (recording mock socket via CreateSock), doesn't bind without one, and aborts on a failed bind.
Just because someone asked that way doesn't mean it's the best solution. I believe that as proposed here -bind=mypublicinterface would suddenly make my node unable to connect to stuff on my local lan (or, in VM on bridge interfaces)-- pretty surprising. I don't see any particular harm in making a separate obind to control output interfaces-- otherwise the OS's routing table makes binding decisions. |
|
On the LAN/bridge case, that's a real regression for multi-homed setups (VM bridges especially). A separate outbound-only option avoids it without forcing existing I'd lean towards |
13879e1 to
c55b58c
Compare
|
Force-pushed a redesign based on the feedback above:
|
c55b58c to
229af39
Compare
|
🚧 At least one of the CI tasks failed. HintsTry to run the tests locally, according to the documentation. However, a CI failure may still
Leave a comment here, if you need help tracking down a confusing failure. |
229af39 to
3e905a0
Compare
3e905a0 to
fa19b8c
Compare
|
Rebased after conflict with #35410: the outbound bind selection in |
| ), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); | ||
| argsman.AddArg("-bantime=<n>", strprintf("Default duration (in seconds) of manually configured bans (default: %u)", DEFAULT_MISBEHAVING_BANTIME), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); | ||
| argsman.AddArg("-bind=<addr>[:<port>][=onion]", strprintf("Bind to given address and always listen on it (default: 0.0.0.0). Use [host]:port notation for IPv6. Append =onion to tag any incoming connections to that address and port as incoming Tor connections (default: 127.0.0.1:%u=onion, testnet3: 127.0.0.1:%u=onion, testnet4: 127.0.0.1:%u=onion, signet: 127.0.0.1:%u=onion, regtest: 127.0.0.1:%u=onion)", defaultChainParams->GetDefaultPort() + 1, testnetChainParams->GetDefaultPort() + 1, testnet4ChainParams->GetDefaultPort() + 1, signetChainParams->GetDefaultPort() + 1, regtestChainParams->GetDefaultPort() + 1), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION); | ||
| argsman.AddArg("-outboundbind=<addr>", "Bind outgoing connections to the given local address (one per address family). The address must be on a local interface; outgoing connections will use it as their source IP. Use [host] notation for IPv6.", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION); |
There was a problem hiding this comment.
| argsman.AddArg("-outboundbind=<addr>", "Bind outgoing connections to the given local address (one per address family). The address must be on a local interface; outgoing connections will use it as their source IP. Use [host] notation for IPv6.", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION); | |
| argsman.AddArg("-outboundbind=<addr>", "Bind outgoing connections to the given local address (one per address family). The address must be on a local interface; outgoing connections will use it as their source IP. Use [address] notation for IPv6.", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION); |
Better use "address" as "host" could be mistaken for a hostname.
There was a problem hiding this comment.
Done. The help now says to give a bare address without a port (LookupHost() rejects a value with a port).
| for (const std::string& bind_arg : args.GetArgs("-outboundbind")) { | ||
| std::optional<CService> bind_addr = Lookup(bind_arg, /*portDefault=*/0, /*fAllowLookup=*/false); | ||
| if (!bind_addr.has_value()) { | ||
| return InitError(ResolveErrMsg("outboundbind", bind_arg)); | ||
| } | ||
| bilingual_str error; | ||
| if (!IsAddrBindable(*bind_addr, error)) { | ||
| return InitError(error); | ||
| } | ||
| connOptions.vOutboundBinds.push_back(bind_addr.value()); | ||
| } |
There was a problem hiding this comment.
I didn't test, but I guess this will allow ports to be included, e.g. -outboundbind=1.2.4.5:5678 which better not be allowed to avoid confusion. LookupHost() can be used to parse just an address.
There was a problem hiding this comment.
Done, switched to LookupHost() so a port is rejected at startup.
| struct sockaddr_storage sa; | ||
| socklen_t len = sizeof(sa); | ||
| if (!service.GetSockAddr(reinterpret_cast<struct sockaddr*>(&sa), &len)) { |
There was a problem hiding this comment.
If you want to have struct, that is fine. Just to mention that C++ can do without it:
| struct sockaddr_storage sa; | |
| socklen_t len = sizeof(sa); | |
| if (!service.GetSockAddr(reinterpret_cast<struct sockaddr*>(&sa), &len)) { | |
| sockaddr_storage sa; | |
| socklen_t len = sizeof(sa); | |
| if (!service.GetSockAddr(reinterpret_cast<sockaddr*>(&sa), &len)) { |
| std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing; | ||
| std::vector<NetWhitebindPermissions> vWhiteBinds; | ||
| std::vector<CService> vBinds; | ||
| std::vector<CService> vOutboundBinds; |
There was a problem hiding this comment.
In new code use snake_case.
| std::vector<CService> vOutboundBinds; | |
| std::vector<CService> outbound_binds; |
and also s/CService/CNetAddr/
There was a problem hiding this comment.
Done, and replaced the vector with one std::optional<CNetAddr> per family.
| m_onion_binds = connOptions.onion_binds; | ||
| // Use -outboundbind addresses for outgoing connections (one per address family). | ||
| for (const auto& bind_addr : connOptions.vOutboundBinds) { | ||
| if (bind_addr.IsLocal()) continue; |
There was a problem hiding this comment.
What's the reason to silently swallow such addresses? It would be more obvious if we return an error for those at startup, like we do for invalid values.
There was a problem hiding this comment.
No longer. A value that doesn't resolve, includes a port, is the wildcard, or isn't IPv4/IPv6 (a Tor or I2P address) is rejected at startup with its own error, and the effective address is then trial-bound. Nothing is dropped silently.
| options.vOutboundBinds = {addr1, addr2}; | ||
| connman->Init(options); | ||
| BOOST_REQUIRE(connman->GetOutboundBindV4()); | ||
| BOOST_CHECK_EQUAL(connman->GetOutboundBindV4()->ToStringAddr(), "203.0.113.1"); |
There was a problem hiding this comment.
Instead of hardcoding the string address again "203.0.113.1" better use addr1.ToStringAddr() (here and elsewhere).
| // CJDNS addresses must not match either IsIPv4() or IsIPv6(), so the | ||
| // outbound bind selection in ConnectNode (which only binds for clearnet | ||
| // families) correctly skips them. | ||
| g_reachable_nets.Add(NET_CJDNS); | ||
| const CService cjdns_service{LookupNumeric("fc00:1:2:3:4:5:6:7", 8333)}; | ||
| const CAddress cjdns_target{MaybeFlipIPv6toCJDNS(cjdns_service), NODE_NONE}; | ||
| BOOST_CHECK(cjdns_target.IsCJDNS()); | ||
| BOOST_CHECK(!cjdns_target.IsIPv4()); | ||
| BOOST_CHECK(!cjdns_target.IsIPv6()); |
There was a problem hiding this comment.
This is not testing the new feature. Better drop it.
There was a problem hiding this comment.
That block checked a CNetAddr property rather than the option, so I replaced it with a direct test of the feature: SelectOutboundBind() selects no source for a CJDNS target (and likewise Tor and I2P), in outbound_bind_address_selection.
| Requires two routable addresses on the machine. To set up: | ||
| Linux: | ||
| ifconfig lo:0 1.1.1.1/32 up && ifconfig lo:1 2.2.2.2/32 up | ||
| ifconfig lo:0 down && ifconfig lo:1 down # to remove | ||
| FreeBSD: | ||
| ifconfig lo0 1.1.1.1/32 alias && ifconfig lo0 2.2.2.2/32 alias | ||
| ifconfig lo0 1.1.1.1 -alias && ifconfig lo0 2.2.2.2 -alias # to remove |
There was a problem hiding this comment.
Recently the CI was extended to provide 1.1.1.5 and 1111:1111::5 on the VMs it creates to facilitate such tests. See ci/test/02_run_container.py and test/functional/feature_bind_port_discover.py and test/functional/feature_bind_port_externalip.py for example tests. It would be better if we keep the instructions consistent among tests.
There was a problem hiding this comment.
Done. The test binds 1.1.1.5/1111:1111::5 as the outgoing sources to a loopback destination (so the observed source differs from it), and self-skips when they're absent.
| - A new `-outboundbind=<addr>` option binds outgoing connections to the given | ||
| local address (one per address family). The address must be assigned to a | ||
| local interface. Proxied connections (Tor, I2P, SOCKS5) are not affected. | ||
| Existing `-bind` semantics are unchanged. (#6476) |
There was a problem hiding this comment.
The number at the end should be the PR that contains the change:
| Existing `-bind` semantics are unchanged. (#6476) | |
| Existing `-bind` semantics are unchanged. (#35027) |
| self.nodes[1].addnode(target, "onetry") | ||
| self.wait_until(lambda: len(self.nodes[0].getpeerinfo()) == 1) | ||
|
|
||
| self.log.info("Checking that node 0 sees inbound from ADDR2") |
There was a problem hiding this comment.
| self.log.info("Checking that node 0 sees inbound from ADDR2") | |
| self.log.info(f"Checking that node 0 sees inbound from {ADDR2}") |
(and below as well)
There was a problem hiding this comment.
Done (the test was rewritten).
|
@8144225309 this needs a rebase and there have been unaddressed review comments for two months now. Are you still working on this? |
|
Yes, rebasing now and addressing the review comments (LookupHost/CNetAddr storage, last-one-wins, CI-runnable functional test). Testing tonight; will push and update here once it's green. |
fa19b8c to
e0a1845
Compare
|
Rebased and addressed the review comments:
Per-commit details in the commit messages. |
Add -outboundbind=<addr> to set the source address of outgoing clearnet connections, one per address family, for multi-homed hosts. It is separate from -bind (listening only); without it, outbound follows the OS routing table as before. - The command line wins over the config file, as for other options. - Only clearnet is bound: Tor and I2P use their own transport, and CJDNS is direct but not IPv4/IPv6, so all three are unaffected. A proxy configured for a family leaves the option inert, with a startup warning. - A port, the wildcard, or a non-clearnet value is rejected at startup; the effective address per family is trial-bound, as -bind does via BindListenPort, so a command-line value can override a stale config-file one. - A failed bind at connect time aborts the connection, with no fallback, and is not counted against the peer in addrman, as proxy failures are not. Where available, IP_BIND_ADDRESS_NO_PORT keeps source port selection at connect() time. Use -nooutboundbind to disable the option. Based on vasild's 2023 sketch: bitcoin#6476 (comment) Closes bitcoin#6476
Unit tests: Init() stores the source per address family (an unset family stays unset); SelectOutboundBind() returns the per-family source and nothing for a non-clearnet (Tor/I2P/CJDNS) target; IsAddrBindable() reports whether an address can be bound; and ConnectDirectly() binds the socket before connecting (recording mock that accepts only the exact per-family sockaddr length), does not bind without a source, aborts on a failed bind, and reports local bind failures through bind_failed. Functional test: outgoing connections originate from the -outboundbind address for both families, with a loopback destination so the observed source differs from it. Also checks command-line-over-config override, the family-specific proxy warning (with an onion-only negative case), and startup rejection of an unassigned address, a port, the wildcard, a Tor address, and a CJDNS address. Skipped only when binding the CI source addresses themselves fails.
e0a1845 to
5baa78a
Compare
|
Rebased and fixed a few issues found while re-reviewing:
|
winterrdog
left a comment
There was a problem hiding this comment.
approach ACK
though, i might be TOO late for the name search party. i'd -exitbind in mind (inspired by TOR exit relays). will provide more review
| self.log.info('Check that a command-line -outboundbind overrides a config-file ' | ||
| 'one of the same family, even when the config-file address cannot ' | ||
| 'be bound to (only the effective address is validated)') | ||
| append_config(self.nodes[1].datadir_path, [f'outboundbind={UNASSIGNED_ADDR}']) | ||
| self.restart_node(1, [f'-outboundbind={ADDR4}']) | ||
| self.check_source(f'127.0.0.1:{self.port4}', ADDR4) | ||
|
|
There was a problem hiding this comment.
-nooutboundbind is documented in both the help text and commit message but it is not tested
could we add a functional test with outboundbind=<addr> in the config file and -nooutboundbind on the command line, asserting that the outgoing source is no longer the address in the configuration file ?
patch
diff --git a/test/functional/feature_bind_outgoing.py b/test/functional/feature_bind_outgoing.py
index f4a8d502aa..fb8b166fc5 100755
--- a/test/functional/feature_bind_outgoing.py
+++ b/test/functional/feature_bind_outgoing.py
@@ -164,6 +164,11 @@ class BindOutgoingTest(BitcoinTestFramework):
self.restart_node(1, [f'-outboundbind={ADDR4}'])
self.check_source(f'127.0.0.1:{self.port4}', ADDR4)
+ self.log.info('Check that -nooutboundbind discards a config-file -outboundbind')
+ self.restart_node(1, ['-nooutboundbind'])
+ self.check_source(f'127.0.0.1:{self.port4}', '127.0.0.1')
+ self.check_source(f'[::1]:{self.port6}', '::1')
+
self.log.info('Check that a configured proxy makes -outboundbind inert, '
'with a startup warning')
self.stop_node(1)| - A new `-outboundbind=<addr>` option binds outgoing clearnet connections to | ||
| the given local address (one per address family). The address must be | ||
| assigned to a local interface. Connections over Tor, I2P and CJDNS are not | ||
| affected. Existing `-bind` semantics are unchanged. (#35027) |
There was a problem hiding this comment.
i have a few thoughts on making the release note clearer.
"one per address family" might be a little broad. saying that one IPv4 and one IPv6 address can be configured independently makes it clearer what the option actually supports. similarly, "local source address" makes the distinction from the destination a bit clearer
there is also the -proxy interaction worth mentioning. when -proxy is configured for an address family, -outboundbind has no effect on that family, and a warning is logged at startup.
| - A new `-outboundbind=<addr>` option binds outgoing clearnet connections to | |
| the given local address (one per address family). The address must be | |
| assigned to a local interface. Connections over Tor, I2P and CJDNS are not | |
| affected. Existing `-bind` semantics are unchanged. (#35027) | |
| - A new `-outboundbind=<addr>` option binds outgoing clearnet connections to | |
| the given local source address. One IPv4 and one IPv6 address can be | |
| configured independently. The address must be assigned to a local | |
| interface. Connections over Tor, I2P and CJDNS are not affected. If | |
| `-proxy` is configured for an address family, `-outboundbind` has no | |
| effect on that family, and a warning is logged at startup. Existing | |
| `-bind` semantics are unchanged. (#35027) |
what do you think ?
| // -outboundbind only affects direct clearnet connections; a proxy configured | ||
| // for a family makes it inert for that family. |
There was a problem hiding this comment.
what happens when -outboundbind is combined with -onlynet? for instance, -onlynet=ipv4 with an IPv6 -outboundbind. users who pin their source address usually restrict networks too
the PR does not check reachable networks, so the address is trial-bound at startup but never used for automatic connections, and a user can never know about that. the proxy case already gets an InitWarning for the same reason i.e. the option is set but inert for that transport
could we add a similar warning when -outboundbind is set for a family excluded by -onlynet.. with a functional test covering the warning, if necessary ?
| std::unique_ptr<Sock> ConnectDirectly(const CService& dest, bool manual_connection, const std::optional<CNetAddr>& bind_addr = std::nullopt, bool* bind_failed = nullptr); | ||
|
|
||
| /** Create a socket and try to connect to the specified service, using the provided timeout. */ | ||
| std::unique_ptr<Sock> ConnectDirectly(const CService& dest, | ||
| bool manual_connection, | ||
| std::chrono::milliseconds timeout); | ||
| std::chrono::milliseconds timeout, | ||
| const std::optional<CNetAddr>& bind_addr = std::nullopt, | ||
| bool* bind_failed = nullptr); |
There was a problem hiding this comment.
a design question on ConnectDirectly
it adds a bool* bind_failed out-param. the developer notes prefer returning values over output parameters:
- Prefer returning values directly to using in-out or output parameters. Use
std::optionalwhere helpful for returning values.- Rationale: Less error-prone (no need for assumptions about what the output
is initialized to on failure), easier to read, and often the same or better
performance.
ConnectThroughProxy still uses the same pattern (proxyConnectionFailed), and the other ConnectDirectly callers (bitcoin-cli, torcontrol, and the proxy path) do not use outbound bind.
is adding another out-param here fine, given the existing pattern, or would returning the failure reason alongside the socket be preferable ?
not a blocker, just curious where you (& others) would draw the line
| # We need to bind to routable addresses for this test to exercise the relevant | ||
| # code. Both addresses are set in the CI environment, see | ||
| # ci/test/02_run_container.py. | ||
| # | ||
| # To set these routable addresses on the machine, use: | ||
| # Linux: | ||
| # ip addr add 1.1.1.5/32 dev INTERFACE_NAME && ip addr add 1111:1111::5/128 dev INTERFACE_NAME # to set up | ||
| # ip addr del 1.1.1.5/32 dev INTERFACE_NAME && ip addr del 1111:1111::5/128 dev INTERFACE_NAME # to remove it | ||
| # FreeBSD or macOS: | ||
| # ifconfig INTERFACE_NAME 1.1.1.5/32 alias && ifconfig INTERFACE_NAME inet6 1111:1111::5/128 alias # to set up | ||
| # ifconfig INTERFACE_NAME 1.1.1.5 -alias && ifconfig INTERFACE_NAME inet6 1111:1111::5 -alias # to remove it, after the test |
There was a problem hiding this comment.
small suggestion: could the PR description mention that feature_bind_outgoing.py needs 1.1.1.5 and 1111:1111::5 assigned to a non-loopback interface (CI sets them already), and that it skips otherwise ?
the setup commands are in the test file's header, but reviewers running it locally would likely look at the description first 🙂
i think other reviewers might find this helpful when testing locally. for running feature_bind_outgoing.py locally without touching a real interface, you can use a dummy device:
for linux
# create a dummy device and assign test IPs
sudo ip link add btc0 type dummy && sudo ip link set btc0 up
sudo ip addr add 1.1.1.5/32 dev btc0 && sudo ip addr add 1111:1111::5/128 dev btc0
# remove the dummy device/interface afterwards. drops the addresses with it
sudo ip link del btc0for freeBSD & netBSD
# switched to root first
su -
# create dummy device and assign test IPs
ifconfig lo1 create && ifconfig lo1 up
ifconfig lo1 inet 1.1.1.5/32 alias && ifconfig lo1 inet6 1111:1111::5/128 alias
# ctrl+D to leave root and run the functional test (feature_bind_outgoing.py)
# remove device when done (remember to switch back to root before doing this)
sudo ifconfig lo1 destroy| // Restore CreateSock on any exit path, including a throwing BOOST_REQUIRE, | ||
| // so a failure here does not leak the mock into later tests. | ||
| struct SockRestore { | ||
| const decltype(CreateSock) orig{CreateSock}; | ||
| ~SockRestore() { CreateSock = orig; } | ||
| } sock_restore; |
There was a problem hiding this comment.
SockRestore is duplicated across 2 test cases i.e. here and in is_addr_bindable. a shared fixture defines it once, so future CreateSock mocks reuse it instead of copy-pasting, and it still restores on a throwing BOOST_REQUIRE
patch
diff --git a/src/test/net_tests.cpp b/src/test/net_tests.cpp
index 400f19a1f2..41488e4237 100644
--- a/src/test/net_tests.cpp
+++ b/src/test/net_tests.cpp
@@ -1749,7 +1749,16 @@ BOOST_AUTO_TEST_CASE(outbound_bind_address_selection)
BOOST_CHECK(!connman->SelectOutboundBindPublic(cjdns));
}
-BOOST_AUTO_TEST_CASE(outbound_bind_connect)
+namespace {
+// Restore CreateSock on any exit path, including a throwing BOOST_REQUIRE,
+// so a failure does not leak the mock into later tests.
+struct SockFixture : RegTestingSetup {
+ const decltype(CreateSock) orig{CreateSock};
+ ~SockFixture() { CreateSock = orig; }
+};
+} // namespace
+
+BOOST_FIXTURE_TEST_CASE(outbound_bind_connect, SockFixture)
{
// ConnectDirectly() must bind() the socket to the given source address
// before connecting, and must not bind() when no address is given.
@@ -1798,13 +1807,6 @@ BOOST_AUTO_TEST_CASE(outbound_bind_connect)
bool& m_connect_called;
};
- // Restore CreateSock on any exit path, including a throwing BOOST_REQUIRE,
- // so a failure here does not leak the mock into later tests.
- struct SockRestore {
- const decltype(CreateSock) orig{CreateSock};
- ~SockRestore() { CreateSock = orig; }
- } sock_restore;
-
std::optional<CService> bound;
CreateSock = [&bound](int, int, int) { return std::make_unique<BindRecordingSock>(bound); };
@@ -1855,14 +1857,10 @@ BOOST_AUTO_TEST_CASE(outbound_bind_connect)
BOOST_CHECK(bind_failed);
}
-BOOST_AUTO_TEST_CASE(is_addr_bindable)
+BOOST_FIXTURE_TEST_CASE(is_addr_bindable, SockFixture)
{
// IsAddrBindable() trial-binds a fresh socket and reports the result.
const CNetAddr addr{LookupHost("127.0.0.1", /*fAllowLookup=*/false).value()};
- struct SockRestore {
- const decltype(CreateSock) orig{CreateSock};
- ~SockRestore() { CreateSock = orig; }
- } sock_restore;
bilingual_str error;
// Bind() succeeds -> bindable, error left empty.| if (bind_addr.IsIPv4()) { | ||
| if (!connOptions.outbound_bind_v4) connOptions.outbound_bind_v4 = bind_addr; | ||
| } else if (bind_addr.IsIPv6()) { | ||
| if (!connOptions.outbound_bind_v6) connOptions.outbound_bind_v6 = bind_addr; | ||
| } else if (bind_addr.IsCJDNS()) { | ||
| return InitError(strprintf(_("-outboundbind address '%s' is a CJDNS address (fc00::/8 while -cjdnsreachable is set), which cannot be a clearnet source"), bind_arg)); | ||
| } else { | ||
| // LookupHost() also accepts Tor/I2P addresses (via SetSpecial); | ||
| // they cannot be a clearnet source. | ||
| return InitError(strprintf(_("-outboundbind address '%s' is not an IPv4 or IPv6 address"), bind_arg)); | ||
| } |
There was a problem hiding this comment.
i think we could avoid invalid clearnet source addresses completely by introducing a dedicated type that can only represent a specific IPv4 or IPv6 address. once you have one, callers can rely on it being a valid clearnet source without having to keep checking
currently, that guarantee is maintained by convention between init and the connect path. a dedicated type would make it an invariant instead, so an invalid address cannot easily make its way into the connection code. i think that would make the code easier to reason about and protect against future regressions
patch
diff --git a/src/init.cpp b/src/init.cpp
index 812e456b7d..ce8f11dfe4 100644
--- a/src/init.cpp
+++ b/src/init.cpp
@@ -2208,32 +2208,18 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
// Classify fc00::/8 as CJDNS when -cjdnsreachable is set, the same
// way the connect path does.
const CNetAddr bind_addr{static_cast<CNetAddr>(MaybeFlipIPv6toCJDNS(CService{*lookup_addr, /*port=*/0}))};
- // The unspecified (wildcard) address pins nothing, so it is not a
- // usable source address. Any other unusable value is left to the
- // trial bind of the effective address below.
- if (bind_addr.IsBindAny()) {
- return InitError(strprintf(_("-outboundbind address '%s' is not a usable source address"), bind_arg));
- }
- // GetArgs() returns values in descending source precedence (command line
- // before config file), so keep the first per family: the command line
- // wins over the config file, and repeats resolve to the first given.
- if (bind_addr.IsIPv4()) {
- if (!connOptions.outbound_bind_v4) connOptions.outbound_bind_v4 = bind_addr;
- } else if (bind_addr.IsIPv6()) {
- if (!connOptions.outbound_bind_v6) connOptions.outbound_bind_v6 = bind_addr;
- } else if (bind_addr.IsCJDNS()) {
- return InitError(strprintf(_("-outboundbind address '%s' is a CJDNS address (fc00::/8 while -cjdnsreachable is set), which cannot be a clearnet source"), bind_arg));
- } else {
- // LookupHost() also accepts Tor/I2P addresses (via SetSpecial);
- // they cannot be a clearnet source.
- return InitError(strprintf(_("-outboundbind address '%s' is not an IPv4 or IPv6 address"), bind_arg));
+ const auto source{ClearnetSource::Make(bind_addr)};
+ if (!source) {
+ return InitError(strprintf(_("-outboundbind address '%s' must be a specific IPv4 or IPv6 address (not a wildcard, Tor, I2P or CJDNS address)"), bind_arg));
}
+ auto& slot{source->Addr().IsIPv4() ? connOptions.outbound_bind_v4 : connOptions.outbound_bind_v6};
+ if (!slot) slot = source;
}
// Check that the addresses that will be used can be bound to. Only the
// effective address per family is checked, so that a command-line
// -outboundbind can override a config-file one that is no longer assigned
// to this machine.
- for (const std::optional<CNetAddr>& bind_addr : {connOptions.outbound_bind_v4, connOptions.outbound_bind_v6}) {
+ for (const std::optional<ClearnetSource>& bind_addr : {connOptions.outbound_bind_v4, connOptions.outbound_bind_v6}) {
if (!bind_addr.has_value()) continue;
bilingual_str error;
if (!IsAddrBindable(*bind_addr, error)) {
diff --git a/src/net.h b/src/net.h
index f6019bf7e8..4052502235 100644
--- a/src/net.h
+++ b/src/net.h
@@ -1103,8 +1103,8 @@ public:
std::vector<NetWhitebindPermissions> vWhiteBinds;
std::vector<CService> vBinds;
//! Source address for outgoing connections, one per address family.
- std::optional<CNetAddr> outbound_bind_v4;
- std::optional<CNetAddr> outbound_bind_v6;
+ std::optional<ClearnetSource> outbound_bind_v4;
+ std::optional<ClearnetSource> outbound_bind_v6;
std::vector<CService> onion_binds;
/// True if the user did not specify -bind= or -whitebind= and thus
/// we should bind on `0.0.0.0` (IPv4) and `::` (IPv6).
@@ -1807,8 +1807,8 @@ private:
* the config file). Applied only to outgoing clearnet (IPv4/IPv6)
* connections; Tor, I2P and CJDNS are unaffected.
*/
- std::optional<CNetAddr> m_outbound_bind_v4;
- std::optional<CNetAddr> m_outbound_bind_v6;
+ std::optional<ClearnetSource> m_outbound_bind_v4;
+ std::optional<ClearnetSource> m_outbound_bind_v6;
/**
* Source address to bind for an outgoing connection to `target`: the
@@ -1817,7 +1817,7 @@ private:
* source is bound (the tun device selects it); Tor and I2P use their own
* transports.
*/
- std::optional<CNetAddr> SelectOutboundBind(const CService& target) const
+ std::optional<ClearnetSource> SelectOutboundBind(const CService& target) const
{
if (target.IsIPv4()) return m_outbound_bind_v4;
if (target.IsIPv6()) return m_outbound_bind_v6;
diff --git a/src/netbase.cpp b/src/netbase.cpp
index e7d5589f16..b5ec56ed31 100644
--- a/src/netbase.cpp
+++ b/src/netbase.cpp
@@ -648,7 +648,7 @@ static bool ConnectToSocket(const Sock& sock,
return true;
}
-std::unique_ptr<Sock> ConnectDirectly(const CService& dest, bool manual_connection, const std::optional<CNetAddr>& bind_addr, bool* bind_failed)
+std::unique_ptr<Sock> ConnectDirectly(const CService& dest, bool manual_connection, const std::optional<ClearnetSource>& bind_addr, bool* bind_failed)
{
return ConnectDirectly(dest, manual_connection, std::chrono::milliseconds{nConnectTimeout}, bind_addr, bind_failed);
}
@@ -656,7 +656,7 @@ std::unique_ptr<Sock> ConnectDirectly(const CService& dest, bool manual_connecti
std::unique_ptr<Sock> ConnectDirectly(const CService& dest,
bool manual_connection,
std::chrono::milliseconds timeout,
- const std::optional<CNetAddr>& bind_addr,
+ const std::optional<ClearnetSource>& bind_addr,
bool* bind_failed)
{
auto sock = CreateSock(dest.GetSAFamily(), SOCK_STREAM, IPPROTO_TCP);
@@ -667,11 +667,11 @@ std::unique_ptr<Sock> ConnectDirectly(const CService& dest,
// If a bind address is specified, bind to it before connecting.
if (bind_addr) {
- const CService bind_service{*bind_addr, /*port=*/0};
+ const CService bind_service{bind_addr->Addr(), /*port=*/0};
sockaddr_storage bind_sa;
socklen_t bind_len = sizeof(bind_sa);
- if (!bind_service.GetSockAddr(reinterpret_cast<sockaddr*>(&bind_sa), &bind_len)) {
- LogInfo("Cannot get sockaddr for bind address %s", bind_addr->ToStringAddr());
+ // NOTE: ClearnetSource is IPv4/IPv6 by construction, so a sockaddr always exists
+ if (!Assume(bind_service.GetSockAddr(reinterpret_cast<sockaddr*>(&bind_sa), &bind_len))) {
if (bind_failed) *bind_failed = true;
return {};
}
@@ -691,7 +691,7 @@ std::unique_ptr<Sock> ConnectDirectly(const CService& dest,
// source that is no longer bindable is an operator misconfiguration
// worth surfacing. The global log rate limiter bounds repetition.
LogWarning("Failed to bind to %s for outgoing connection to %s: %s",
- bind_addr->ToStringAddr(), dest.ToStringAddrPort(), NetworkErrorString(err));
+ bind_addr->Addr().ToStringAddr(), dest.ToStringAddrPort(), NetworkErrorString(err));
if (bind_failed) *bind_failed = true;
return {};
}
@@ -1018,25 +1018,25 @@ CService GetBindAddress(const Sock& sock)
return addr_bind;
}
-bool IsAddrBindable(const CNetAddr& addr, bilingual_str& error)
+bool IsAddrBindable(const ClearnetSource& source, bilingual_str& error)
{
- const CService service{addr, /*port=*/0};
+ const CService service{source.Addr(), /*port=*/0};
sockaddr_storage sa;
socklen_t len = sizeof(sa);
- if (!service.GetSockAddr(reinterpret_cast<sockaddr*>(&sa), &len)) {
- error = Untranslated(strprintf("Bind address family for %s not supported", addr.ToStringAddr()));
+ // NOTE: ClearnetSource is IPv4/IPv6 by construction, so a sockaddr always exists
+ if (!Assume(service.GetSockAddr(reinterpret_cast<sockaddr*>(&sa), &len))) {
return false;
}
std::unique_ptr<Sock> sock = CreateSock(service.GetSAFamily(), SOCK_STREAM, IPPROTO_TCP);
if (!sock) {
const int err{WSAGetLastError()};
- error = Untranslated(strprintf("Couldn't open socket for %s (socket returned error %s)", addr.ToStringAddr(), NetworkErrorString(err)));
+ error = Untranslated(strprintf("Couldn't open socket for %s (socket returned error %s)", source.Addr().ToStringAddr(), NetworkErrorString(err)));
return false;
}
if (sock->Bind(reinterpret_cast<sockaddr*>(&sa), len) == SOCKET_ERROR) {
const int err{WSAGetLastError()};
error = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"),
- addr.ToStringAddr(), NetworkErrorString(err));
+ source.Addr().ToStringAddr(), NetworkErrorString(err));
return false;
}
return true;
diff --git a/src/netbase.h b/src/netbase.h
index 748e5e2d92..45fcae1743 100644
--- a/src/netbase.h
+++ b/src/netbase.h
@@ -173,6 +173,26 @@ private:
extern ReachableNets g_reachable_nets;
+/**
+ * A local source address that is guaranteed usable for a clearnet connection:
+ * a specific (non-wildcard) IPv4 or IPv6 address. Tor, CJDNS, I2P and the wildcard
+ * address cannot be represented, so consumers need no checks.
+ */
+class ClearnetSource
+{
+public:
+ static std::optional<ClearnetSource> Make(const CNetAddr& addr)
+ {
+ if (addr.IsBindAny() || (!addr.IsIPv6() && !addr.IsIPv4())) return std::nullopt;
+ return ClearnetSource(addr);
+ }
+ const CNetAddr& Addr() const { return m_addr; }
+
+private:
+ explicit ClearnetSource(const CNetAddr& addr) : m_addr(addr) {}
+ CNetAddr m_addr;
+};
+
/**
* Wrapper for getaddrinfo(3). Do not use directly: call Lookup/LookupHost/LookupNumeric/LookupSubNet.
*/
@@ -303,7 +323,7 @@ extern std::function<std::unique_ptr<Sock>(int, int, int)> CreateSock;
*
* @param[in] dest The service to which to connect.
* @param[in] manual_connection Whether or not the connection was manually requested (e.g. through the addnode RPC)
- * @param[in] bind_addr If set, bind to this local address before connecting. On
+ * @param[in] bind_addr If set, bind to this local source address before connecting. On
* bind failure the connection is aborted; there is no fallback to a
* default source address.
* @param[out] bind_failed If not nullptr, set to true when the connection was
@@ -312,13 +332,13 @@ extern std::function<std::unique_ptr<Sock>(int, int, int)> CreateSock;
*
* @returns the connected socket if the operation succeeded, empty unique_ptr otherwise
*/
-std::unique_ptr<Sock> ConnectDirectly(const CService& dest, bool manual_connection, const std::optional<CNetAddr>& bind_addr = std::nullopt, bool* bind_failed = nullptr);
+std::unique_ptr<Sock> ConnectDirectly(const CService& dest, bool manual_connection, const std::optional<ClearnetSource>& bind_addr = std::nullopt, bool* bind_failed = nullptr);
/** Create a socket and try to connect to the specified service, using the provided timeout. */
std::unique_ptr<Sock> ConnectDirectly(const CService& dest,
bool manual_connection,
std::chrono::milliseconds timeout,
- const std::optional<CNetAddr>& bind_addr = std::nullopt,
+ const std::optional<ClearnetSource>& bind_addr = std::nullopt,
bool* bind_failed = nullptr);
/**
@@ -384,10 +404,10 @@ CService MaybeFlipIPv6toCJDNS(const CService& service);
CService GetBindAddress(const Sock& sock);
/**
- * Check whether a local address can be bound to (assigned to a local interface).
+ * Check whether a local source address can be bound to (assigned to a local interface).
* Attempts a real bind() syscall on a fresh socket; the socket is closed before
* return. Returns false with `error` populated on failure.
*/
-bool IsAddrBindable(const CNetAddr& addr, bilingual_str& error);
+bool IsAddrBindable(const ClearnetSource& source, bilingual_str& error);
#endif // BITCOIN_NETBASE_H
diff --git a/src/test/net_tests.cpp b/src/test/net_tests.cpp
index 400f19a1f2..92cadac01a 100644
--- a/src/test/net_tests.cpp
+++ b/src/test/net_tests.cpp
@@ -1711,30 +1711,30 @@ BOOST_AUTO_TEST_CASE(outbound_bind_address_selection)
const CNetAddr addr6{LookupHost("2001:db8::1", /*fAllowLookup=*/false).value()};
// An address is stored per family; an unset family stays unset.
- options.outbound_bind_v4 = addr4;
+ options.outbound_bind_v4 = ClearnetSource::Make(addr4);
connman->Init(options);
BOOST_REQUIRE(connman->GetOutboundBindV4());
- BOOST_CHECK_EQUAL(connman->GetOutboundBindV4()->ToStringAddr(), addr4.ToStringAddr());
+ BOOST_CHECK_EQUAL(connman->GetOutboundBindV4()->Addr().ToStringAddr(), addr4.ToStringAddr());
BOOST_CHECK(!connman->GetOutboundBindV6());
// With the v6 family unset, an IPv6 target selects nothing.
BOOST_CHECK(!connman->SelectOutboundBindPublic(CService{LookupHost("2001:db8::3", /*fAllowLookup=*/false).value(), /*port=*/8333}));
// Setting the other family leaves the first family's stored address intact.
connman = std::make_unique<ConnmanTestMsg>(seed, seed, *m_node.addrman, *m_node.netgroupman, Params());
- options.outbound_bind_v6 = addr6;
+ options.outbound_bind_v6 = ClearnetSource::Make(addr6);
connman->Init(options);
BOOST_REQUIRE(connman->GetOutboundBindV4());
BOOST_REQUIRE(connman->GetOutboundBindV6());
- BOOST_CHECK_EQUAL(connman->GetOutboundBindV6()->ToStringAddr(), addr6.ToStringAddr());
+ BOOST_CHECK_EQUAL(connman->GetOutboundBindV6()->Addr().ToStringAddr(), addr6.ToStringAddr());
// SelectOutboundBind() picks the configured source by the target's family,
// and binds nothing for a non-clearnet (Tor/I2P/CJDNS) target.
const auto sel4{connman->SelectOutboundBindPublic(CService{LookupHost("198.51.100.1", /*fAllowLookup=*/false).value(), /*port=*/8333})};
BOOST_REQUIRE(sel4);
- BOOST_CHECK_EQUAL(sel4->ToStringAddr(), addr4.ToStringAddr());
+ BOOST_CHECK_EQUAL(sel4->Addr().ToStringAddr(), addr4.ToStringAddr());
const auto sel6{connman->SelectOutboundBindPublic(CService{LookupHost("2001:db8::2", /*fAllowLookup=*/false).value(), /*port=*/8333})};
BOOST_REQUIRE(sel6);
- BOOST_CHECK_EQUAL(sel6->ToStringAddr(), addr6.ToStringAddr());
+ BOOST_CHECK_EQUAL(sel6->Addr().ToStringAddr(), addr6.ToStringAddr());
const CService onion{LookupHost("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion", /*fAllowLookup=*/false).value(), /*port=*/8333};
BOOST_CHECK(!connman->SelectOutboundBindPublic(onion));
CNetAddr i2p;
@@ -1809,19 +1809,19 @@ BOOST_AUTO_TEST_CASE(outbound_bind_connect)
CreateSock = [&bound](int, int, int) { return std::make_unique<BindRecordingSock>(bound); };
const CService dest{LookupNumeric("198.51.100.34", 8333)};
- const CNetAddr src{LookupHost("203.0.113.1", /*fAllowLookup=*/false).value()};
+ const auto src{ClearnetSource::Make(LookupHost("203.0.113.1", /*fAllowLookup=*/false).value())};
BOOST_REQUIRE(ConnectDirectly(dest, /*manual_connection=*/false, src));
BOOST_REQUIRE(bound.has_value());
- BOOST_CHECK_EQUAL(bound->ToStringAddrPort(), CService(src, /*port=*/0).ToStringAddrPort());
+ BOOST_CHECK_EQUAL(bound->ToStringAddrPort(), CService(src->Addr(), /*port=*/0).ToStringAddrPort());
// The same for IPv6.
bound.reset();
const CService dest6{LookupNumeric("2001:db8::1", 8333)};
- const CNetAddr src6{LookupHost("2001:db8::2", /*fAllowLookup=*/false).value()};
+ const auto src6{ClearnetSource::Make(LookupHost("2001:db8::2", /*fAllowLookup=*/false).value())};
BOOST_REQUIRE(ConnectDirectly(dest6, /*manual_connection=*/false, src6));
BOOST_REQUIRE(bound.has_value());
- BOOST_CHECK_EQUAL(bound->ToStringAddrPort(), CService(src6, /*port=*/0).ToStringAddrPort());
+ BOOST_CHECK_EQUAL(bound->ToStringAddrPort(), CService(src6->Addr(), /*port=*/0).ToStringAddrPort());
// The bind_failed out-param stays false when no bind was requested and on
// a successful bind, so the caller only skips addrman accounting when the
@@ -1843,22 +1843,12 @@ BOOST_AUTO_TEST_CASE(outbound_bind_connect)
BOOST_CHECK(!ConnectDirectly(dest, /*manual_connection=*/false, src, &bind_failed));
BOOST_CHECK(!connect_called);
BOOST_CHECK(bind_failed);
-
- // A non-clearnet source has no sockaddr: ConnectDirectly() aborts before
- // connecting (defensive; SelectOutboundBind() never yields such a source).
- // This local failure also reports bind_failed.
- CNetAddr onion_src;
- BOOST_REQUIRE(onion_src.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion"));
- CreateSock = [](int, int, int) { return std::make_unique<ZeroSock>(); };
- bind_failed = false;
- BOOST_CHECK(!ConnectDirectly(dest, /*manual_connection=*/false, onion_src, &bind_failed));
- BOOST_CHECK(bind_failed);
}
BOOST_AUTO_TEST_CASE(is_addr_bindable)
{
// IsAddrBindable() trial-binds a fresh socket and reports the result.
- const CNetAddr addr{LookupHost("127.0.0.1", /*fAllowLookup=*/false).value()};
+ const auto addr{ClearnetSource::Make(LookupHost("127.0.0.1", /*fAllowLookup=*/false).value()).value()};
struct SockRestore {
const decltype(CreateSock) orig{CreateSock};
~SockRestore() { CreateSock = orig; }
@@ -1891,13 +1881,6 @@ BOOST_AUTO_TEST_CASE(is_addr_bindable)
error = bilingual_str{};
BOOST_CHECK(!IsAddrBindable(addr, error));
BOOST_CHECK(!error.empty());
-
- // A non-clearnet address has no sockaddr -> not bindable, family error.
- CNetAddr onion;
- BOOST_REQUIRE(onion.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion"));
- error = bilingual_str{};
- BOOST_CHECK(!IsAddrBindable(onion, error));
- BOOST_CHECK(!error.empty());
}
BOOST_AUTO_TEST_SUITE_END()
diff --git a/src/test/util/net.h b/src/test/util/net.h
index 18665b3c04..bf0fc97ac5 100644
--- a/src/test/util/net.h
+++ b/src/test/util/net.h
@@ -89,9 +89,9 @@ struct ConnmanTestMsg : public CConnman {
return InitBinds(options);
}
- std::optional<CNetAddr> GetOutboundBindV4() const { return m_outbound_bind_v4; }
- std::optional<CNetAddr> GetOutboundBindV6() const { return m_outbound_bind_v6; }
- std::optional<CNetAddr> SelectOutboundBindPublic(const CService& target) const { return SelectOutboundBind(target); }
+ std::optional<ClearnetSource> GetOutboundBindV4() const { return m_outbound_bind_v4; }
+ std::optional<ClearnetSource> GetOutboundBindV6() const { return m_outbound_bind_v6; }
+ std::optional<ClearnetSource> SelectOutboundBindPublic(const CService& target) const { return SelectOutboundBind(target); }
void SocketHandlerPublic()
{
diff --git a/test/functional/feature_bind_outgoing.py b/test/functional/feature_bind_outgoing.py
index f4a8d502aa..a8102f6ca0 100755
--- a/test/functional/feature_bind_outgoing.py
+++ b/test/functional/feature_bind_outgoing.py
@@ -107,7 +107,7 @@ class BindOutgoingTest(BitcoinTestFramework):
for wildcard in ('0.0.0.0', '::'):
self.nodes[1].assert_start_raises_init_error(
extra_args=[f'-outboundbind={wildcard}'],
- expected_msg=f"Error: -outboundbind address '{wildcard}' is not a usable source address",
+ expected_msg=f"Error: -outboundbind address '{wildcard}' must be a specific IPv4 or IPv6 address",
match=ErrorMatch.PARTIAL_REGEX,
)
@@ -118,21 +118,6 @@ class BindOutgoingTest(BitcoinTestFramework):
match=ErrorMatch.PARTIAL_REGEX,
)
- self.log.info('Check that a non-clearnet (Tor) address is rejected at startup')
- self.nodes[1].assert_start_raises_init_error(
- extra_args=['-outboundbind=pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion'],
- expected_msg='is not an IPv4 or IPv6 address',
- match=ErrorMatch.PARTIAL_REGEX,
- )
-
- self.log.info('Check that an fc00::/8 address is rejected at startup when it '
- 'is a CJDNS address (-cjdnsreachable)')
- self.nodes[1].assert_start_raises_init_error(
- extra_args=['-cjdnsreachable', '-outboundbind=fc00:db8::1'],
- expected_msg='is a CJDNS address',
- match=ErrorMatch.PARTIAL_REGEX,
- )
-
self.log.info('Check that fc00::/8 stays a plain IPv6 source without -cjdnsreachable')
# Accepted by the parser (proven by reaching the later trial bind, which
# fails because the address is not assigned to this machine).what do you think ?

Closes #6476
Adds
-outboundbind=<addr>to set the source address of outgoing clearnetconnections, one per address family. It is separate from
-bind; without it,outbound follows the OS routing table as before.
IPv4/IPv6, and a proxy leaves the option inert for that family (with a
startup warning).
-bindviaBindListenPort; a port, the wildcard, or a non-clearnet value is rejected. Afailed bind at connect time aborts the connection, with no fallback.
Functional and unit tests cover both families, the startup rejections, and the
bind-before-connect path.
Based on vasild's approach in
#6476 (comment).