Skip to content

Commit 2feec3c

Browse files
committed
net: don't bind on 0.0.0.0 if binds are restricted to Tor
The semantic of `-bind` is to restrict the binding only to some address. If not specified, then the user does not care and we bind to `0.0.0.0`. If specified then we should honor the restriction and bind only to the specified address. Before this change, if no `-bind` is given then we would bind to `0.0.0.0:8333` and to `127.0.0.1:8334` (incoming Tor) which is ok - the user does not care to restrict the binding. However, if only `-bind=addr:port=onion` is given (without ordinary `-bind=`) then we would bind to `addr:port` _and_ to `0.0.0.0:8333` in addition. Change the above to not do the additional bind: if only `-bind=addr:port=onion` is given (without ordinary `-bind=`) then bind to `addr:port` (only) and consider incoming connections to that as Tor and do not advertise it. I.e. a Tor-only node.
1 parent 4da26fb commit 2feec3c

File tree

5 files changed

+129
-29
lines changed

5 files changed

+129
-29
lines changed

src/init.cpp

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1721,25 +1721,34 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
17211721
return InitError(ResolveErrMsg("bind", bind_arg));
17221722
}
17231723

1724-
if (connOptions.onion_binds.empty()) {
1725-
connOptions.onion_binds.push_back(DefaultOnionServiceTarget());
1726-
}
1727-
1728-
if (args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) {
1729-
const auto bind_addr = connOptions.onion_binds.front();
1730-
if (connOptions.onion_binds.size() > 1) {
1731-
InitWarning(strprintf(_("More than one onion bind address is provided. Using %s for the automatically created Tor onion service."), bind_addr.ToStringIPPort()));
1732-
}
1733-
StartTorControl(bind_addr);
1734-
}
1735-
17361724
for (const std::string& strBind : args.GetArgs("-whitebind")) {
17371725
NetWhitebindPermissions whitebind;
17381726
bilingual_str error;
17391727
if (!NetWhitebindPermissions::TryParse(strBind, whitebind, error)) return InitError(error);
17401728
connOptions.vWhiteBinds.push_back(whitebind);
17411729
}
17421730

1731+
// If the user did not specify -bind= or -whitebind= then we bind
1732+
// on any address - 0.0.0.0 (IPv4) and :: (IPv6).
1733+
connOptions.bind_on_any = args.GetArgs("-bind").empty() && args.GetArgs("-whitebind").empty();
1734+
1735+
CService onion_service_target;
1736+
if (!connOptions.onion_binds.empty()) {
1737+
onion_service_target = connOptions.onion_binds.front();
1738+
} else {
1739+
onion_service_target = DefaultOnionServiceTarget();
1740+
connOptions.onion_binds.push_back(onion_service_target);
1741+
}
1742+
1743+
if (args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) {
1744+
if (connOptions.onion_binds.size() > 1) {
1745+
InitWarning(strprintf(_("More than one onion bind address is provided. Using %s "
1746+
"for the automatically created Tor onion service."),
1747+
onion_service_target.ToStringIPPort()));
1748+
}
1749+
StartTorControl(onion_service_target);
1750+
}
1751+
17431752
for (const auto& net : args.GetArgs("-whitelist")) {
17441753
NetWhitelistPermissions subnet;
17451754
bilingual_str error;

src/net.cpp

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2418,38 +2418,33 @@ bool CConnman::Bind(const CService &addr, unsigned int flags, NetPermissionFlags
24182418
return true;
24192419
}
24202420

2421-
bool CConnman::InitBinds(
2422-
const std::vector<CService>& binds,
2423-
const std::vector<NetWhitebindPermissions>& whiteBinds,
2424-
const std::vector<CService>& onion_binds)
2421+
bool CConnman::InitBinds(const Options& options)
24252422
{
24262423
bool fBound = false;
2427-
for (const auto& addrBind : binds) {
2424+
for (const auto& addrBind : options.vBinds) {
24282425
fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR), NetPermissionFlags::None);
24292426
}
2430-
for (const auto& addrBind : whiteBinds) {
2427+
for (const auto& addrBind : options.vWhiteBinds) {
24312428
fBound |= Bind(addrBind.m_service, (BF_EXPLICIT | BF_REPORT_ERROR), addrBind.m_flags);
24322429
}
2433-
if (binds.empty() && whiteBinds.empty()) {
2430+
for (const auto& addr_bind : options.onion_binds) {
2431+
fBound |= Bind(addr_bind, BF_EXPLICIT | BF_DONT_ADVERTISE, NetPermissionFlags::None);
2432+
}
2433+
if (options.bind_on_any) {
24342434
struct in_addr inaddr_any;
24352435
inaddr_any.s_addr = htonl(INADDR_ANY);
24362436
struct in6_addr inaddr6_any = IN6ADDR_ANY_INIT;
24372437
fBound |= Bind(CService(inaddr6_any, GetListenPort()), BF_NONE, NetPermissionFlags::None);
24382438
fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE, NetPermissionFlags::None);
24392439
}
2440-
2441-
for (const auto& addr_bind : onion_binds) {
2442-
fBound |= Bind(addr_bind, BF_EXPLICIT | BF_DONT_ADVERTISE, NetPermissionFlags::None);
2443-
}
2444-
24452440
return fBound;
24462441
}
24472442

24482443
bool CConnman::Start(CScheduler& scheduler, const Options& connOptions)
24492444
{
24502445
Init(connOptions);
24512446

2452-
if (fListen && !InitBinds(connOptions.vBinds, connOptions.vWhiteBinds, connOptions.onion_binds)) {
2447+
if (fListen && !InitBinds(connOptions)) {
24532448
if (clientInterface) {
24542449
clientInterface->ThreadSafeMessageBox(
24552450
_("Failed to listen on any port. Use -listen=0 if you want this."),

src/net.h

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -824,6 +824,9 @@ class CConnman
824824
std::vector<NetWhitebindPermissions> vWhiteBinds;
825825
std::vector<CService> vBinds;
826826
std::vector<CService> onion_binds;
827+
/// True if the user did not specify -bind= or -whitebind= and thus
828+
/// we should bind on `0.0.0.0` (IPv4) and `::` (IPv6).
829+
bool bind_on_any;
827830
bool m_use_addrman_outgoing = true;
828831
std::vector<std::string> m_specified_outgoing;
829832
std::vector<std::string> m_added_nodes;
@@ -1033,10 +1036,7 @@ class CConnman
10331036

10341037
bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions);
10351038
bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
1036-
bool InitBinds(
1037-
const std::vector<CService>& binds,
1038-
const std::vector<NetWhitebindPermissions>& whiteBinds,
1039-
const std::vector<CService>& onion_binds);
1039+
bool InitBinds(const Options& options);
10401040

10411041
void ThreadOpenAddedConnections();
10421042
void AddAddrFetch(const std::string& strDest);

test/functional/feature_bind_extra.py

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
#!/usr/bin/env python3
2+
# Copyright (c) 2014-2021 The Bitcoin Core developers
3+
# Distributed under the MIT software license, see the accompanying
4+
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
5+
"""
6+
Test starting bitcoind with -bind and/or -bind=...=onion and confirm
7+
that bind happens on the expected ports.
8+
"""
9+
10+
import sys
11+
12+
from test_framework.netutil import (
13+
addr_to_hex,
14+
get_bind_addrs,
15+
)
16+
from test_framework.test_framework import (
17+
BitcoinTestFramework,
18+
SkipTest,
19+
)
20+
from test_framework.util import (
21+
PORT_MIN,
22+
PORT_RANGE,
23+
assert_equal,
24+
rpc_port,
25+
)
26+
27+
class BindExtraTest(BitcoinTestFramework):
28+
def set_test_params(self):
29+
self.setup_clean_chain = True
30+
# Avoid any -bind= on the command line. Force the framework to avoid
31+
# adding -bind=127.0.0.1.
32+
self.bind_to_localhost_only = False
33+
self.num_nodes = 2
34+
35+
def setup_network(self):
36+
# Override setup_network() because we want to put the result of
37+
# p2p_port() in self.extra_args[], before the nodes are started.
38+
# p2p_port() is not usable in set_test_params() because PortSeed.n is
39+
# not set at that time.
40+
41+
# Due to OS-specific network stats queries, we only run on Linux.
42+
self.log.info("Checking for Linux")
43+
if not sys.platform.startswith('linux'):
44+
raise SkipTest("This test can only be run on Linux.")
45+
46+
loopback_ipv4 = addr_to_hex("127.0.0.1")
47+
48+
# Start custom ports after p2p and rpc ports.
49+
port = PORT_MIN + 2 * PORT_RANGE
50+
51+
# Array of tuples [command line arguments, expected bind addresses].
52+
self.expected = []
53+
54+
# Node0, no normal -bind=... with -bind=...=onion, thus only the tor target.
55+
self.expected.append(
56+
[
57+
[f"-bind=127.0.0.1:{port}=onion"],
58+
[(loopback_ipv4, port)]
59+
],
60+
)
61+
port += 1
62+
63+
# Node1, both -bind=... and -bind=...=onion.
64+
self.expected.append(
65+
[
66+
[f"-bind=127.0.0.1:{port}", f"-bind=127.0.0.1:{port + 1}=onion"],
67+
[(loopback_ipv4, port), (loopback_ipv4, port + 1)]
68+
],
69+
)
70+
port += 2
71+
72+
self.extra_args = list(map(lambda e: e[0], self.expected))
73+
self.add_nodes(self.num_nodes, self.extra_args)
74+
# Don't start the nodes, as some of them would collide trying to bind on the same port.
75+
76+
def run_test(self):
77+
for i in range(len(self.expected)):
78+
self.log.info(f"Starting node {i} with {self.expected[i][0]}")
79+
self.start_node(i)
80+
pid = self.nodes[i].process.pid
81+
binds = set(get_bind_addrs(pid))
82+
# Remove IPv6 addresses because on some CI environments "::1" is not configured
83+
# on the system (so our test_ipv6_local() would return False), but it is
84+
# possible to bind on "::". This makes it unpredictable whether to expect
85+
# that bitcoind has bound on "::1" (for RPC) and "::" (for P2P).
86+
ipv6_addr_len_bytes = 32
87+
binds = set(filter(lambda e: len(e[0]) != ipv6_addr_len_bytes, binds))
88+
# Remove RPC ports. They are not relevant for this test.
89+
binds = set(filter(lambda e: e[1] != rpc_port(i), binds))
90+
assert_equal(binds, set(self.expected[i][1]))
91+
self.stop_node(i)
92+
self.log.info(f"Stopped node {i}")
93+
94+
if __name__ == '__main__':
95+
BindExtraTest().main()

test/functional/test_runner.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,7 @@
138138
'interface_zmq.py',
139139
'rpc_invalid_address_message.py',
140140
'interface_bitcoin_cli.py',
141+
'feature_bind_extra.py',
141142
'mempool_resurrect.py',
142143
'wallet_txn_doublespend.py --mineblock',
143144
'tool_wallet.py --legacy-wallet',

0 commit comments

Comments
 (0)