28#include <boost/signals2/signal.hpp>
29#include <boost/algorithm/string/split.hpp>
30#include <boost/algorithm/string/classification.hpp>
31#include <boost/algorithm/string/replace.hpp>
33#include <event2/bufferevent.h>
34#include <event2/buffer.h>
35#include <event2/util.h>
36#include <event2/event.h>
37#include <event2/thread.h>
46static const std::string
TOR_SAFE_SERVERKEY =
"Tor safe cookie authentication server-to-controller hash";
48static const std::string
TOR_SAFE_CLIENTKEY =
"Tor safe cookie authentication controller-to-server hash";
62 base(_base), b_conn(nullptr)
75 struct evbuffer *input = bufferevent_get_input(bev);
76 size_t n_read_out = 0;
80 while((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) !=
nullptr)
82 std::string s(line, n_read_out);
87 self->message.code = LocaleIndependentAtoi<int>(s.substr(0,3));
88 self->message.lines.push_back(s.substr(4));
92 if (self->message.code >= 600) {
95 self->async_handler(*
self, self->message);
97 if (!self->reply_handlers.empty()) {
99 self->reply_handlers.front()(*
self,
self->message);
100 self->reply_handlers.pop_front();
105 self->message.Clear();
112 LogPrintf(
"tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
120 if (what & BEV_EVENT_CONNECTED) {
122 self->connected(*
self);
123 }
else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
124 if (what & BEV_EVENT_ERROR) {
130 self->disconnected(*
self);
142 LogPrintf(
"tor: Failed to look up control center %s\n", tor_control_center);
146 struct sockaddr_storage control_address;
147 socklen_t control_address_len =
sizeof(control_address);
148 if (!control_service.
GetSockAddr(
reinterpret_cast<struct sockaddr*
>(&control_address), &control_address_len)) {
149 LogPrintf(
"tor: Error parsing socket address %s\n", tor_control_center);
154 b_conn = bufferevent_socket_new(
base, -1, BEV_OPT_CLOSE_ON_FREE);
159 bufferevent_enable(
b_conn, EV_READ|EV_WRITE);
164 if (bufferevent_socket_connect(
b_conn,
reinterpret_cast<struct sockaddr*
>(&control_address), control_address_len) < 0) {
165 LogPrintf(
"tor: Error connecting to address %s\n", tor_control_center);
182 struct evbuffer *buf = bufferevent_get_output(
b_conn);
185 evbuffer_add(buf, cmd.data(), cmd.size());
186 evbuffer_add(buf,
"\r\n", 2);
202 while (ptr < s.size() && s[ptr] !=
' ') {
203 type.push_back(s[ptr]);
208 return make_pair(type, s.substr(ptr));
219 std::map<std::string,std::string> mapping;
221 while (ptr < s.size()) {
222 std::string key, value;
223 while (ptr < s.size() && s[ptr] !=
'=' && s[ptr] !=
' ') {
224 key.push_back(s[ptr]);
228 return std::map<std::string,std::string>();
232 if (ptr < s.size() && s[ptr] ==
'"') {
234 bool escape_next =
false;
235 while (ptr < s.size() && (escape_next || s[ptr] !=
'"')) {
237 escape_next = (s[ptr] ==
'\\' && !escape_next);
238 value.push_back(s[ptr]);
242 return std::map<std::string,std::string>();
254 std::string escaped_value;
255 for (
size_t i = 0; i < value.size(); ++i) {
256 if (value[i] ==
'\\') {
262 if (value[i] ==
'n') {
263 escaped_value.push_back(
'\n');
264 }
else if (value[i] ==
't') {
265 escaped_value.push_back(
'\t');
266 }
else if (value[i] ==
'r') {
267 escaped_value.push_back(
'\r');
268 }
else if (
'0' <= value[i] && value[i] <=
'7') {
273 for (j = 1; j < 3 && (i+j) < value.size() &&
'0' <= value[i+j] && value[i+j] <=
'7'; ++j) {}
277 if (j == 3 && value[i] >
'3') {
280 escaped_value.push_back(strtol(value.substr(i, j).c_str(),
nullptr, 8));
284 escaped_value.push_back(value[i]);
287 escaped_value.push_back(value[i]);
290 value = escaped_value;
292 while (ptr < s.size() && s[ptr] !=
' ') {
293 value.push_back(s[ptr]);
297 if (ptr < s.size() && s[ptr] ==
' ')
299 mapping[key] = value;
306 m_tor_control_center(tor_control_center), conn(base), reconnect(true), reconnect_ev(0),
312 LogPrintf(
"tor: Failed to create event for reconnection: out of memory?\n");
339 if (reply.
code == 250) {
341 for (
const std::string &s : reply.
lines) {
343 std::map<std::string,std::string>::iterator i;
344 if ((i = m.find(
"ServiceID")) != m.end())
346 if ((i = m.find(
"PrivateKey")) != m.end())
350 LogPrintf(
"tor: Error parsing ADD_ONION parameters:\n");
351 for (
const std::string &s : reply.
lines) {
365 }
else if (reply.
code == 510) {
366 LogPrintf(
"tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)\n");
368 LogPrintf(
"tor: Add onion failed; error code %d\n", reply.
code);
374 if (reply.
code == 250) {
395 LogPrintf(
"tor: Authentication failed\n");
415static 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)
417 CHMAC_SHA256 computeHash((
const uint8_t*)key.data(), key.size());
419 computeHash.
Write(cookie.data(), cookie.size());
420 computeHash.
Write(clientNonce.data(), clientNonce.size());
421 computeHash.
Write(serverNonce.data(), serverNonce.size());
422 computeHash.
Finalize(computedHash.data());
428 if (reply.
code == 250) {
431 if (l.first ==
"AUTHCHALLENGE") {
437 std::vector<uint8_t> serverHash =
ParseHex(m[
"SERVERHASH"]);
438 std::vector<uint8_t> serverNonce =
ParseHex(m[
"SERVERNONCE"]);
440 if (serverNonce.size() != 32) {
441 LogPrintf(
"tor: ServerNonce is not 32 bytes, as required by spec\n");
446 if (computedServerHash != serverHash) {
447 LogPrintf(
"tor: ServerHash %s does not match expected ServerHash %s\n",
HexStr(serverHash),
HexStr(computedServerHash));
454 LogPrintf(
"tor: Invalid reply to AUTHCHALLENGE\n");
457 LogPrintf(
"tor: SAFECOOKIE authentication challenge failed\n");
463 if (reply.
code == 250) {
464 std::set<std::string> methods;
465 std::string cookiefile;
471 for (
const std::string &s : reply.
lines) {
473 if (l.first ==
"AUTH") {
475 std::map<std::string,std::string>::iterator i;
476 if ((i = m.find(
"METHODS")) != m.end())
477 boost::split(methods, i->second, boost::is_any_of(
","));
478 if ((i = m.find(
"COOKIEFILE")) != m.end())
479 cookiefile = i->second;
480 }
else if (l.first ==
"VERSION") {
482 std::map<std::string,std::string>::iterator i;
483 if ((i = m.find(
"Tor")) != m.end()) {
488 for (
const std::string &s : methods) {
496 std::string torpassword =
gArgs.
GetArg(
"-torpassword",
"");
497 if (!torpassword.empty()) {
498 if (methods.count(
"HASHEDPASSWORD")) {
500 boost::replace_all(torpassword,
"\"",
"\\\"");
501 _conn.
Command(
"AUTHENTICATE \"" + torpassword +
"\"", std::bind(&
TorController::auth_cb,
this, std::placeholders::_1, std::placeholders::_2));
503 LogPrintf(
"tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available\n");
505 }
else if (methods.count(
"NULL")) {
508 }
else if (methods.count(
"SAFECOOKIE")) {
510 LogPrint(
BCLog::TOR,
"tor: Using SAFECOOKIE authentication, reading cookie authentication from %s\n", cookiefile);
512 if (status_cookie.first && status_cookie.second.size() ==
TOR_COOKIE_SIZE) {
514 cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
519 if (status_cookie.first) {
520 LogPrintf(
"tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec\n", cookiefile,
TOR_COOKIE_SIZE);
522 LogPrintf(
"tor: Authentication cookie %s could not be opened (check permissions)\n", cookiefile);
525 }
else if (methods.count(
"HASHEDPASSWORD")) {
526 LogPrintf(
"tor: The only supported authentication mechanism left is password, but no password provided with -torpassword\n");
528 LogPrintf(
"tor: No supported authentication method\n");
531 LogPrintf(
"tor: Requesting protocol info failed\n");
540 LogPrintf(
"tor: Error sending initial protocolinfo command\n");
592 event_base_dispatch(
gBase);
599 evthread_use_windows_threads();
601 evthread_use_pthreads();
603 gBase = event_base_new();
605 LogPrintf(
"tor: Unable to create event_base\n");
618 event_base_once(
gBase, -1, EV_TIMEOUT, [](evutil_socket_t,
short,
void*) {
619 event_base_loopbreak(
gBase);
620 },
nullptr,
nullptr);
628 event_base_free(
gBase);
635 struct in_addr onion_service_target;
636 onion_service_target.s_addr = htonl(INADDR_LOOPBACK);
const CChainParams & Params()
Return the currently selected parameters.
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
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.
CHMAC_SHA256 & Write(const unsigned char *data, size_t len)
void Finalize(unsigned char hash[OUTPUT_SIZE])
static const size_t OUTPUT_SIZE
A combination of a network address (CNetAddr) and a (TCP) port.
std::string ToStringIPPort() const
std::string ToString() const
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Obtain the IPv4/6 socket address this represents.
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 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 prepare application code for transition from boost::filesystem library to std::...
#define LogPrint(category,...)
static std::string PathToString(const path &path)
Convert path object to byte string.
static path PathFromString(const std::string &string)
Convert byte string to path object.
void TraceThread(const char *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)
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
@ NET_ONION
TOR (v2 or v3)
bool Lookup(const std::string &name, std::vector< CService > &vAddr, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
Resolve a service string to its corresponding service.
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.
bool SetProxy(enum Network net, const proxyType &addrProxy)
void GetRandBytes(unsigned char *buf, int num) 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=std::numeric_limits< size_t >::max())
Read full contents of a file and return them in a std::string.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::vector< unsigned char > ParseHex(const char *psz)
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
void SetSyscallSandboxPolicy(SyscallSandboxPolicy syscall_policy)
Force the current thread (and threads created from the current thread) into a restricted-service oper...
static secp256k1_context * ctx
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 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 int MAX_LINE_LENGTH
Maximum length for lines received on TorControlConnection.
static const float RECONNECT_TIMEOUT_EXP
Exponential backoff configuration - growth factor.
const std::string DEFAULT_TOR_CONTROL
Default control port.
static void TorControlThread(CService onion_service_target)
std::pair< std::string, std::string > SplitTorReplyLine(const std::string &s)
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()
std::map< std::string, std::string > ParseTorReplyMapping(const std::string &s)
Parse reply arguments in the form 'METHODS=COOKIE,SAFECOOKIE COOKIEFILE=".../control_auth_cookie"'.
static std::thread torControlThread
static const float RECONNECT_TIMEOUT_START
Exponential backoff configuration - initial timeout in seconds.
void StartTorControl(CService onion_service_target)