23#include <boost/signals2/signal.hpp>
25#include <event2/buffer.h>
26#include <event2/bufferevent.h>
27#include <event2/event.h>
28#include <event2/thread.h>
29#include <event2/util.h>
45 "Tor safe cookie authentication server-to-controller hash";
48 "Tor safe cookie authentication controller-to-server hash";
100 bool Connect(
const std::string &tor_control_center,
136 static void readcb(
struct bufferevent *bev,
void *
ctx);
137 static void eventcb(
struct bufferevent *bev,
short what,
void *
ctx);
141 : base(_base), b_conn(nullptr) {}
151 struct evbuffer *input = bufferevent_get_input(bev);
152 size_t n_read_out = 0;
156 while ((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) !=
158 std::string s(line, n_read_out);
182 "tor: Received unexpected sync reply %i\n",
194 LogPrintf(
"tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
202 if (what & BEV_EVENT_CONNECTED) {
205 }
else if (what & (BEV_EVENT_EOF | BEV_EVENT_ERROR)) {
206 if (what & BEV_EVENT_ERROR) {
208 "tor: Error connecting to Tor control socket\n");
224 struct sockaddr_storage connect_to_addr;
225 int connect_to_addrlen =
sizeof(connect_to_addr);
226 if (evutil_parse_sockaddr_port(tor_control_center.c_str(),
227 (
struct sockaddr *)&connect_to_addr,
228 &connect_to_addrlen) < 0) {
229 LogPrintf(
"tor: Error parsing socket address %s\n", tor_control_center);
234 b_conn = bufferevent_socket_new(
base, -1, BEV_OPT_CLOSE_ON_FREE);
240 bufferevent_enable(
b_conn, EV_READ | EV_WRITE);
245 if (bufferevent_socket_connect(
b_conn, (
struct sockaddr *)&connect_to_addr,
246 connect_to_addrlen) < 0) {
247 LogPrintf(
"tor: Error connecting to address %s\n", tor_control_center);
265 struct evbuffer *buf = bufferevent_get_output(
b_conn);
269 evbuffer_add(buf, cmd.data(), cmd.size());
270 evbuffer_add(buf,
"\r\n", 2);
285 while (ptr < s.size() && s[ptr] !=
' ') {
286 type.push_back(s[ptr]);
289 if (ptr < s.size()) {
293 return make_pair(type, s.substr(ptr));
305 std::map<std::string, std::string> mapping;
307 while (ptr < s.size()) {
308 std::string key, value;
309 while (ptr < s.size() && s[ptr] !=
'=' && s[ptr] !=
' ') {
310 key.push_back(s[ptr]);
314 if (ptr == s.size()) {
315 return std::map<std::string, std::string>();
324 if (ptr < s.size() && s[ptr] ==
'"') {
327 bool escape_next =
false;
328 while (ptr < s.size() && (escape_next || s[ptr] !=
'"')) {
330 escape_next = (s[ptr] ==
'\\' && !escape_next);
331 value.push_back(s[ptr]);
335 if (ptr == s.size()) {
336 return std::map<std::string, std::string>();
352 std::string escaped_value;
353 for (
size_t i = 0; i < value.size(); ++i) {
354 if (value[i] ==
'\\') {
360 if (value[i] ==
'n') {
361 escaped_value.push_back(
'\n');
362 }
else if (value[i] ==
't') {
363 escaped_value.push_back(
'\t');
364 }
else if (value[i] ==
'r') {
365 escaped_value.push_back(
'\r');
366 }
else if (
'0' <= value[i] && value[i] <=
'7') {
371 for (j = 1; j < 3 && (i + j) < value.size() &&
372 '0' <= value[i + j] && value[i + j] <=
'7';
378 if (j == 3 && value[i] >
'3') {
381 escaped_value.push_back(
382 strtol(value.substr(i, j).c_str(), NULL, 8));
386 escaped_value.push_back(value[i]);
389 escaped_value.push_back(value[i]);
392 value = escaped_value;
396 while (ptr < s.size() && s[ptr] !=
' ') {
397 value.push_back(s[ptr]);
401 if (ptr < s.size() && s[ptr] ==
' ') {
405 mapping[key] = value;
419 const std::string &tor_control_center,
461 static void reconnect_cb(evutil_socket_t fd,
short what,
void *arg);
465 const std::string &tor_control_center,
467 : base(_base), m_tor_control_center(tor_control_center), conn(base),
468 reconnect(true), reconnect_ev(0),
473 "tor: Failed to create event for reconnection: out of memory?\n");
478 std::placeholders::_1),
480 std::placeholders::_1))) {
481 LogPrintf(
"tor: Initiating connection to Tor control port %s failed\n",
505 if (reply.
code == 250) {
507 for (
const std::string &s : reply.
lines) {
509 std::map<std::string, std::string>::iterator i;
510 if ((i = m.find(
"ServiceID")) != m.end()) {
513 if ((i = m.find(
"PrivateKey")) != m.end()) {
518 LogPrintf(
"tor: Error parsing ADD_ONION parameters:\n");
519 for (
const std::string &s : reply.
lines) {
527 "Got service ID %s, advertising service %s\n",
533 LogPrintf(
"tor: Error writing service private key to %s\n",
538 }
else if (reply.
code == 510) {
539 LogPrintf(
"tor: Add onion failed with unrecognized command (You "
540 "probably need to upgrade Tor)\n");
542 LogPrintf(
"tor: Add onion failed; error code %d\n", reply.
code);
548 if (reply.
code == 250) {
574 std::placeholders::_1, std::placeholders::_2));
576 LogPrintf(
"tor: Authentication failed\n");
596static std::vector<uint8_t>
598 const std::vector<uint8_t> &clientNonce,
599 const std::vector<uint8_t> &serverNonce) {
600 CHMAC_SHA256 computeHash((
const uint8_t *)key.data(), key.size());
602 computeHash.
Write(cookie.data(), cookie.size());
603 computeHash.
Write(clientNonce.data(), clientNonce.size());
604 computeHash.
Write(serverNonce.data(), serverNonce.size());
605 computeHash.
Finalize(computedHash.data());
611 if (reply.
code == 250) {
613 "tor: SAFECOOKIE authentication challenge successful\n");
614 std::pair<std::string, std::string> l =
616 if (l.first ==
"AUTHCHALLENGE") {
617 std::map<std::string, std::string> m =
620 LogPrintf(
"tor: Error parsing AUTHCHALLENGE parameters: %s\n",
624 std::vector<uint8_t> serverHash =
ParseHex(m[
"SERVERHASH"]);
625 std::vector<uint8_t> serverNonce =
ParseHex(m[
"SERVERNONCE"]);
627 "tor: AUTHCHALLENGE ServerHash %s ServerNonce %s\n",
629 if (serverNonce.size() != 32) {
631 "tor: ServerNonce is not 32 bytes, as required by spec\n");
637 if (computedServerHash != serverHash) {
638 LogPrintf(
"tor: ServerHash %s does not match expected "
648 std::placeholders::_1,
649 std::placeholders::_2));
651 LogPrintf(
"tor: Invalid reply to AUTHCHALLENGE\n");
654 LogPrintf(
"tor: SAFECOOKIE authentication challenge failed\n");
660 if (reply.
code == 250) {
661 std::set<std::string> methods;
662 std::string cookiefile;
669 for (
const std::string &s : reply.
lines) {
671 if (l.first ==
"AUTH") {
672 std::map<std::string, std::string> m =
674 std::map<std::string, std::string>::iterator i;
675 if ((i = m.find(
"METHODS")) != m.end()) {
676 std::vector<std::string> m_vec =
678 methods = std::set<std::string>(m_vec.begin(), m_vec.end());
680 if ((i = m.find(
"COOKIEFILE")) != m.end()) {
681 cookiefile = i->second;
683 }
else if (l.first ==
"VERSION") {
684 std::map<std::string, std::string> m =
686 std::map<std::string, std::string>::iterator i;
687 if ((i = m.find(
"Tor")) != m.end()) {
693 for (
const std::string &s : methods) {
703 std::string torpassword =
gArgs.
GetArg(
"-torpassword",
"");
704 if (!torpassword.empty()) {
705 if (methods.count(
"HASHEDPASSWORD")) {
707 "tor: Using HASHEDPASSWORD authentication\n");
709 _conn.
Command(
"AUTHENTICATE \"" + torpassword +
"\"",
711 std::placeholders::_1,
712 std::placeholders::_2));
714 LogPrintf(
"tor: Password provided with -torpassword, but "
715 "HASHEDPASSWORD authentication is not available\n");
717 }
else if (methods.count(
"NULL")) {
720 this, std::placeholders::_1,
721 std::placeholders::_2));
722 }
else if (methods.count(
"SAFECOOKIE")) {
725 "tor: Using SAFECOOKIE authentication, "
726 "reading cookie authentication from %s\n",
728 std::pair<bool, std::string> status_cookie =
730 if (status_cookie.first &&
735 cookie = std::vector<uint8_t>(status_cookie.second.begin(),
736 status_cookie.second.end());
741 std::placeholders::_1,
742 std::placeholders::_2));
744 if (status_cookie.first) {
745 LogPrintf(
"tor: Authentication cookie %s is not exactly %i "
746 "bytes, as is required by the spec\n",
749 LogPrintf(
"tor: Authentication cookie %s could not be "
750 "opened (check permissions)\n",
754 }
else if (methods.count(
"HASHEDPASSWORD")) {
755 LogPrintf(
"tor: The only supported authentication mechanism left "
756 "is password, but no password provided with "
759 LogPrintf(
"tor: No supported authentication method\n");
762 LogPrintf(
"tor: Requesting protocol info failed\n");
770 if (!_conn.
Command(
"PROTOCOLINFO 1",
772 std::placeholders::_1,
773 std::placeholders::_2))) {
774 LogPrintf(
"tor: Error sending initial protocolinfo command\n");
789 "tor: Not connected to Tor control port %s, trying to reconnect\n",
806 std::placeholders::_1),
808 std::placeholders::_1))) {
810 "tor: Re-initiating connection to Tor control port %s failed\n",
830 onion_service_target);
832 event_base_dispatch(
gBase);
838 evthread_use_windows_threads();
840 evthread_use_pthreads();
842 gBase = event_base_new();
844 LogPrintf(
"tor: Unable to create event_base\n");
858 gBase, -1, EV_TIMEOUT,
859 [](evutil_socket_t,
short,
void *) { event_base_loopbreak(
gBase); },
867 event_base_free(
gBase);
873 struct in_addr onion_service_target;
874 onion_service_target.s_addr = htonl(INADDR_LOOPBACK);
const CChainParams & Params()
Return the currently selected parameters.
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
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.
static const size_t OUTPUT_SIZE
CHMAC_SHA256 & Write(const uint8_t *data, size_t len)
void Finalize(uint8_t hash[OUTPUT_SIZE])
A combination of a network address (CNetAddr) and a (TCP) port.
std::string ToStringIPPort() const
std::string ToString() const
Low-level handling for Tor control connection.
TorControlReply message
Message being received.
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.
boost::signals2::signal< void(TorControlConnection &, const TorControlReply &)> async_handler
Response handlers for async replies.
static void readcb(struct bufferevent *bev, void *ctx)
Libevent handlers: internal.
std::function< void(TorControlConnection &)> disconnected
Callback when connection lost.
static void eventcb(struct bufferevent *bev, short what, void *ctx)
std::function< void(TorControlConnection &, const TorControlReply &)> ReplyHandlerCB
void Disconnect()
Disconnect from Tor control port.
struct bufferevent * b_conn
Connection to control socket.
struct event_base * base
Libevent event base.
std::function< void(TorControlConnection &)> ConnectionCB
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 fo 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
TorController(struct event_base *base, const std::string &tor_control_center, const CService &target)
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 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)
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
bool AddLocal(const CService &addr, int nScore)
@ NET_ONION
TOR (v2 or v3)
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(Span< uint8_t > 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=std::numeric_limits< size_t >::max())
Read full contents of a file and return them in a std::string.
static uint16_t GetDefaultPort()
void ReplaceAll(std::string &in_out, const std::string &search, const std::string &substitute)
std::vector< std::string > SplitString(std::string_view str, char sep)
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)
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
template std::vector< std::byte > ParseHex(std::string_view)
int atoi(const std::string &str)
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.