39 #include <event2/buffer.h>
40 #include <event2/bufferevent.h>
41 #include <event2/event.h>
42 #include <event2/thread.h>
43 #include <event2/util.h>
52 static const std::string
TOR_SAFE_SERVERKEY =
"Tor safe cookie authentication server-to-controller hash";
54 static const std::string
TOR_SAFE_CLIENTKEY =
"Tor safe cookie authentication controller-to-server hash";
82 struct evbuffer *input = bufferevent_get_input(bev);
83 size_t n_read_out = 0;
87 while((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) !=
nullptr)
89 std::string s(line, n_read_out);
94 self->message.code = ToIntegral<int>(s.substr(0, 3)).value_or(0);
95 self->message.lines.push_back(s.substr(4));
99 if (self->message.code >= 600) {
104 if (!self->reply_handlers.empty()) {
106 self->reply_handlers.front()(*
self,
self->message);
107 self->reply_handlers.pop_front();
112 self->message.Clear();
119 LogPrintf(
"tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
127 if (what & BEV_EVENT_CONNECTED) {
129 self->connected(*
self);
130 }
else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
131 if (what & BEV_EVENT_ERROR) {
137 self->disconnected(*
self);
148 if (!control_service.has_value()) {
149 LogPrintf(
"tor: Failed to look up control center %s\n", tor_control_center);
153 struct sockaddr_storage control_address;
154 socklen_t control_address_len =
sizeof(control_address);
155 if (!control_service.value().GetSockAddr(
reinterpret_cast<struct sockaddr*
>(&control_address), &control_address_len)) {
156 LogPrintf(
"tor: Error parsing socket address %s\n", tor_control_center);
161 b_conn = bufferevent_socket_new(
base, -1, BEV_OPT_CLOSE_ON_FREE);
166 bufferevent_enable(
b_conn, EV_READ|EV_WRITE);
171 if (bufferevent_socket_connect(
b_conn,
reinterpret_cast<struct sockaddr*
>(&control_address), control_address_len) < 0) {
172 LogPrintf(
"tor: Error connecting to address %s\n", tor_control_center);
189 struct evbuffer *buf = bufferevent_get_output(
b_conn);
192 evbuffer_add(buf,
cmd.data(),
cmd.size());
193 evbuffer_add(buf,
"\r\n", 2);
209 while (ptr < s.size() && s[ptr] !=
' ') {
210 type.push_back(s[ptr]);
215 return make_pair(type, s.substr(ptr));
226 std::map<std::string,std::string> mapping;
228 while (ptr < s.size()) {
229 std::string key, value;
230 while (ptr < s.size() && s[ptr] !=
'=' && s[ptr] !=
' ') {
231 key.push_back(s[ptr]);
235 return std::map<std::string,std::string>();
239 if (ptr < s.size() && s[ptr] ==
'"') {
241 bool escape_next =
false;
242 while (ptr < s.size() && (escape_next || s[ptr] !=
'"')) {
244 escape_next = (s[ptr] ==
'\\' && !escape_next);
245 value.push_back(s[ptr]);
249 return std::map<std::string,std::string>();
261 std::string escaped_value;
262 for (
size_t i = 0; i < value.size(); ++i) {
263 if (value[i] ==
'\\') {
269 if (value[i] ==
'n') {
270 escaped_value.push_back(
'\n');
271 }
else if (value[i] ==
't') {
272 escaped_value.push_back(
'\t');
273 }
else if (value[i] ==
'r') {
274 escaped_value.push_back(
'\r');
275 }
else if (
'0' <= value[i] && value[i] <=
'7') {
280 for (j = 1; j < 3 && (i+j) < value.size() &&
'0' <= value[i+j] && value[i+j] <=
'7'; ++j) {}
284 if (j == 3 && value[i] >
'3') {
287 const auto end{i + j};
291 val += value[i++] -
'0';
293 escaped_value.push_back(
char(val));
297 escaped_value.push_back(value[i]);
300 escaped_value.push_back(value[i]);
303 value = escaped_value;
305 while (ptr < s.size() && s[ptr] !=
' ') {
306 value.push_back(s[ptr]);
310 if (ptr < s.size() && s[ptr] ==
' ')
312 mapping[key] = value;
319 m_tor_control_center(tor_control_center), conn(base), reconnect(true), reconnect_timeout(
RECONNECT_TIMEOUT_START),
324 LogPrintf(
"tor: Failed to create event for reconnection: out of memory?\n");
352 std::string socks_location;
353 if (reply.
code == 250) {
354 for (
const auto& line : reply.
lines) {
355 if (0 == line.compare(0, 20,
"net/listeners/socks=")) {
356 const std::string port_list_str = line.substr(20);
357 std::vector<std::string> port_list =
SplitString(port_list_str,
' ');
359 for (
auto& portstr : port_list) {
360 if (portstr.empty())
continue;
361 if ((portstr[0] ==
'"' || portstr[0] ==
'\'') && portstr.size() >= 2 && (*portstr.rbegin() == portstr[0])) {
362 portstr = portstr.substr(1, portstr.size() - 2);
363 if (portstr.empty())
continue;
365 socks_location = portstr;
366 if (0 == portstr.compare(0, 10,
"127.0.0.1:")) {
373 if (!socks_location.empty()) {
376 LogPrintf(
"tor: Get SOCKS port command returned nothing\n");
378 }
else if (reply.
code == 510) {
379 LogPrintf(
"tor: Get SOCKS port command failed with unrecognized command (You probably should upgrade Tor)\n");
381 LogPrintf(
"tor: Get SOCKS port command failed; error code %d\n", reply.
code);
386 if (!socks_location.empty()) {
401 const bool onion_allowed_by_onlynet{
403 std::any_of(onlynets.begin(), onlynets.end(), [](
const auto& n) {
404 return ParseNetwork(n) == NET_ONION;
407 if (onion_allowed_by_onlynet) {
418 if (reply.
code == 250) {
420 for (
const std::string &s : reply.
lines) {
422 std::map<std::string,std::string>::iterator i;
423 if ((i =
m.find(
"ServiceID")) !=
m.end())
425 if ((i =
m.find(
"PrivateKey")) !=
m.end())
429 LogPrintf(
"tor: Error parsing ADD_ONION parameters:\n");
430 for (
const std::string &s : reply.
lines) {
444 }
else if (reply.
code == 510) {
445 LogPrintf(
"tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)\n");
447 LogPrintf(
"tor: Add onion failed; error code %d\n", reply.
code);
453 if (reply.
code == 250) {
471 LogPrintf(
"tor: Authentication failed\n");
491 static std::vector<uint8_t>
ComputeResponse(
const std::string &key,
const std::vector<uint8_t> &cookie,
const std::vector<uint8_t> &clientNonce,
const std::vector<uint8_t> &serverNonce)
493 CHMAC_SHA256 computeHash((
const uint8_t*)key.data(), key.size());
495 computeHash.
Write(cookie.data(), cookie.size());
496 computeHash.
Write(clientNonce.data(), clientNonce.size());
497 computeHash.
Write(serverNonce.data(), serverNonce.size());
498 computeHash.
Finalize(computedHash.data());
504 if (reply.
code == 250) {
507 if (l.first ==
"AUTHCHALLENGE") {
513 std::vector<uint8_t> serverHash =
ParseHex(
m[
"SERVERHASH"]);
514 std::vector<uint8_t> serverNonce =
ParseHex(
m[
"SERVERNONCE"]);
516 if (serverNonce.size() != 32) {
517 LogPrintf(
"tor: ServerNonce is not 32 bytes, as required by spec\n");
522 if (computedServerHash != serverHash) {
523 LogPrintf(
"tor: ServerHash %s does not match expected ServerHash %s\n",
HexStr(serverHash),
HexStr(computedServerHash));
530 LogPrintf(
"tor: Invalid reply to AUTHCHALLENGE\n");
533 LogPrintf(
"tor: SAFECOOKIE authentication challenge failed\n");
539 if (reply.
code == 250) {
540 std::set<std::string> methods;
541 std::string cookiefile;
547 for (
const std::string &s : reply.
lines) {
549 if (l.first ==
"AUTH") {
551 std::map<std::string,std::string>::iterator i;
552 if ((i =
m.find(
"METHODS")) !=
m.end()) {
553 std::vector<std::string> m_vec =
SplitString(i->second,
',');
554 methods = std::set<std::string>(m_vec.begin(), m_vec.end());
556 if ((i =
m.find(
"COOKIEFILE")) !=
m.end())
557 cookiefile = i->second;
558 }
else if (l.first ==
"VERSION") {
560 std::map<std::string,std::string>::iterator i;
561 if ((i =
m.find(
"Tor")) !=
m.end()) {
566 for (
const std::string &s : methods) {
574 std::string torpassword =
gArgs.
GetArg(
"-torpassword",
"");
575 if (!torpassword.empty()) {
576 if (methods.count(
"HASHEDPASSWORD")) {
579 _conn.
Command(
"AUTHENTICATE \"" + torpassword +
"\"", std::bind(&
TorController::auth_cb,
this, std::placeholders::_1, std::placeholders::_2));
581 LogPrintf(
"tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available\n");
583 }
else if (methods.count(
"NULL")) {
586 }
else if (methods.count(
"SAFECOOKIE")) {
588 LogPrint(
BCLog::TOR,
"Using SAFECOOKIE authentication, reading cookie authentication from %s\n", cookiefile);
590 if (status_cookie.first && status_cookie.second.size() ==
TOR_COOKIE_SIZE) {
592 cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
597 if (status_cookie.first) {
598 LogPrintf(
"tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec\n", cookiefile,
TOR_COOKIE_SIZE);
600 LogPrintf(
"tor: Authentication cookie %s could not be opened (check permissions)\n", cookiefile);
603 }
else if (methods.count(
"HASHEDPASSWORD")) {
604 LogPrintf(
"tor: The only supported authentication mechanism left is password, but no password provided with -torpassword\n");
606 LogPrintf(
"tor: No supported authentication method\n");
609 LogPrintf(
"tor: Requesting protocol info failed\n");
618 LogPrintf(
"tor: Error sending initial protocolinfo command\n");
669 event_base_dispatch(
gBase);
676 evthread_use_windows_threads();
678 evthread_use_pthreads();
680 gBase = event_base_new();
682 LogPrintf(
"tor: Unable to create event_base\n");
695 event_base_once(
gBase, -1, EV_TIMEOUT, [](evutil_socket_t,
short,
void*) {
696 event_base_loopbreak(
gBase);
697 },
nullptr,
nullptr);
705 event_base_free(
gBase);
712 struct in_addr onion_service_target;
713 onion_service_target.s_addr = htonl(INADDR_LOOPBACK);
const CChainParams & Params()
Return the currently selected parameters.
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
#define Assume(val)
Assume is the identity function.
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
uint16_t OnionServiceTargetPort() const
A hasher class for HMAC-SHA-256.
void Finalize(unsigned char hash[OUTPUT_SIZE])
CHMAC_SHA256 & Write(const unsigned char *data, size_t len)
static const size_t OUTPUT_SIZE
A combination of a network address (CNetAddr) and a (TCP) port.
std::string ToStringAddrPort() const
void Add(Network net) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Low-level handling for Tor control connection.
std::deque< ReplyHandlerCB > reply_handlers
Response handlers.
bool Connect(const std::string &tor_control_center, const ConnectionCB &connected, const ConnectionCB &disconnected)
Connect to a Tor control port.
TorControlConnection(struct event_base *base)
Create a new TorControlConnection.
bool Command(const std::string &cmd, const ReplyHandlerCB &reply_handler)
Send a command, register a handler for the reply.
std::function< void(TorControlConnection &)> connected
Callback when ready for use.
static void readcb(struct bufferevent *bev, void *ctx)
Libevent handlers: internal.
std::function< void(TorControlConnection &, const TorControlReply &)> ReplyHandlerCB
static void eventcb(struct bufferevent *bev, short what, void *ctx)
std::function< void(TorControlConnection &)> disconnected
Callback when connection lost.
std::function< void(TorControlConnection &)> ConnectionCB
void Disconnect()
Disconnect from Tor control port.
struct bufferevent * b_conn
Connection to control socket.
struct event_base * base
Libevent event base.
Reply from Tor, can be single or multi-line.
std::vector< std::string > lines
Controller that connects to Tor control socket, authenticate, then create and maintain an ephemeral o...
TorControlConnection conn
static void reconnect_cb(evutil_socket_t fd, short what, void *arg)
Callback for reconnect timer.
fs::path GetPrivateKeyFile()
Get name of file to store private key in.
std::vector< uint8_t > clientNonce
ClientNonce for SAFECOOKIE auth.
void connected_cb(TorControlConnection &conn)
Callback after successful connection.
void get_socks_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for GETINFO net/listeners/socks result.
void add_onion_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for ADD_ONION result.
const std::string m_tor_control_center
void disconnected_cb(TorControlConnection &conn)
Callback after connection lost or failed connection attempt.
void authchallenge_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHCHALLENGE result.
std::vector< uint8_t > cookie
Cookie for SAFECOOKIE auth.
struct event * reconnect_ev
void auth_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHENTICATE result.
void Reconnect()
Reconnect, after getting disconnected.
void protocolinfo_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for PROTOCOLINFO result.
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
#define LogPrint(category,...)
#define LogPrintfCategory(category,...)
static std::string PathToString(const path &path)
Convert path object to a byte string.
static path PathFromString(const std::string &string)
Convert byte string to path object.
void TraceThread(std::string_view thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
void RemoveLocal(const CService &addr)
bool AddLocal(const CService &addr_, int nScore)
@ NET_ONION
TOR (v2 or v3)
std::vector< CService > Lookup(const std::string &name, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
Resolve a service string to its corresponding service.
bool SetProxy(enum Network net, const Proxy &addrProxy)
ReachableNets g_reachable_nets
CService LookupNumeric(const std::string &name, uint16_t portDefault, DNSLookupFn dns_lookup_function)
Resolve a service string with a numeric IP to its first corresponding service.
void GetRandBytes(Span< unsigned char > bytes) noexcept
Overall design of the RNG and entropy sources.
bool WriteBinaryFile(const fs::path &filename, const std::string &data)
Write contents of std::string to a file.
std::pair< bool, std::string > ReadBinaryFile(const fs::path &filename, size_t maxsize)
Read full contents of a file and return them in a std::string.
std::vector< Byte > ParseHex(std::string_view hex_str)
Like TryParseHex, but returns an empty vector on invalid input.
std::vector< std::string > SplitString(std::string_view str, char sep)
std::string ToString(const T &t)
Locale-independent version of std::to_string.
struct timeval MillisToTimeval(int64_t nTimeout)
Convert milliseconds to a struct timeval for e.g.
static const std::string TOR_SAFE_CLIENTKEY
For computing clientHash in SAFECOOKIE.
CService DefaultOnionServiceTarget()
static const int MAX_LINE_LENGTH
Maximum length for lines received on TorControlConnection.
std::pair< std::string, std::string > SplitTorReplyLine(const std::string &s)
static std::vector< uint8_t > ComputeResponse(const std::string &key, const std::vector< uint8_t > &cookie, const std::vector< uint8_t > &clientNonce, const std::vector< uint8_t > &serverNonce)
Compute Tor SAFECOOKIE response.
static const float RECONNECT_TIMEOUT_EXP
Exponential backoff configuration - growth factor.
const std::string DEFAULT_TOR_CONTROL
Default control ip and port.
static void TorControlThread(CService onion_service_target)
static const std::string TOR_SAFE_SERVERKEY
For computing serverHash in SAFECOOKIE.
static const int TOR_COOKIE_SIZE
Tor cookie size (from control-spec.txt)
static struct event_base * gBase
static const int TOR_NONCE_SIZE
Size of client/server nonce for SAFECOOKIE.
void InterruptTorControl()
static std::thread torControlThread
static const float RECONNECT_TIMEOUT_START
Exponential backoff configuration - initial timeout in seconds.
static const uint16_t DEFAULT_TOR_SOCKS_PORT
void StartTorControl(CService onion_service_target)
std::map< std::string, std::string > ParseTorReplyMapping(const std::string &s)
Parse reply arguments in the form 'METHODS=COOKIE,SAFECOOKIE COOKIEFILE=".../control_auth_cookie"'.
constexpr int DEFAULT_TOR_CONTROL_PORT
Functionality for communicating with Tor.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.
void ReplaceAll(std::string &in_out, const std::string &search, const std::string &substitute)