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) {
526 LogPrintf(
"tor: Got service ID %s, advertising service %s\n",
532 LogPrintf(
"tor: Error writing service private key to %s\n",
537 }
else if (reply.
code == 510) {
538 LogPrintf(
"tor: Add onion failed with unrecognized command (You "
539 "probably need to upgrade Tor)\n");
541 LogPrintf(
"tor: Add onion failed; error code %d\n", reply.
code);
547 if (reply.
code == 250) {
573 std::placeholders::_1, std::placeholders::_2));
575 LogPrintf(
"tor: Authentication failed\n");
595static std::vector<uint8_t>
597 const std::vector<uint8_t> &clientNonce,
598 const std::vector<uint8_t> &serverNonce) {
599 CHMAC_SHA256 computeHash((
const uint8_t *)key.data(), key.size());
601 computeHash.
Write(cookie.data(), cookie.size());
602 computeHash.
Write(clientNonce.data(), clientNonce.size());
603 computeHash.
Write(serverNonce.data(), serverNonce.size());
604 computeHash.
Finalize(computedHash.data());
610 if (reply.
code == 250) {
612 "tor: SAFECOOKIE authentication challenge successful\n");
613 std::pair<std::string, std::string> l =
615 if (l.first ==
"AUTHCHALLENGE") {
616 std::map<std::string, std::string> m =
619 LogPrintf(
"tor: Error parsing AUTHCHALLENGE parameters: %s\n",
623 std::vector<uint8_t> serverHash =
ParseHex(m[
"SERVERHASH"]);
624 std::vector<uint8_t> serverNonce =
ParseHex(m[
"SERVERNONCE"]);
626 "tor: AUTHCHALLENGE ServerHash %s ServerNonce %s\n",
628 if (serverNonce.size() != 32) {
630 "tor: ServerNonce is not 32 bytes, as required by spec\n");
636 if (computedServerHash != serverHash) {
637 LogPrintf(
"tor: ServerHash %s does not match expected "
647 std::placeholders::_1,
648 std::placeholders::_2));
650 LogPrintf(
"tor: Invalid reply to AUTHCHALLENGE\n");
653 LogPrintf(
"tor: SAFECOOKIE authentication challenge failed\n");
659 if (reply.
code == 250) {
660 std::set<std::string> methods;
661 std::string cookiefile;
668 for (
const std::string &s : reply.
lines) {
670 if (l.first ==
"AUTH") {
671 std::map<std::string, std::string> m =
673 std::map<std::string, std::string>::iterator i;
674 if ((i = m.find(
"METHODS")) != m.end()) {
675 std::vector<std::string> m_vec =
677 methods = std::set<std::string>(m_vec.begin(), m_vec.end());
679 if ((i = m.find(
"COOKIEFILE")) != m.end()) {
680 cookiefile = i->second;
682 }
else if (l.first ==
"VERSION") {
683 std::map<std::string, std::string> m =
685 std::map<std::string, std::string>::iterator i;
686 if ((i = m.find(
"Tor")) != m.end()) {
692 for (
const std::string &s : methods) {
702 std::string torpassword =
gArgs.
GetArg(
"-torpassword",
"");
703 if (!torpassword.empty()) {
704 if (methods.count(
"HASHEDPASSWORD")) {
706 "tor: Using HASHEDPASSWORD authentication\n");
708 _conn.
Command(
"AUTHENTICATE \"" + torpassword +
"\"",
710 std::placeholders::_1,
711 std::placeholders::_2));
713 LogPrintf(
"tor: Password provided with -torpassword, but "
714 "HASHEDPASSWORD authentication is not available\n");
716 }
else if (methods.count(
"NULL")) {
719 this, std::placeholders::_1,
720 std::placeholders::_2));
721 }
else if (methods.count(
"SAFECOOKIE")) {
724 "tor: Using SAFECOOKIE authentication, "
725 "reading cookie authentication from %s\n",
727 std::pair<bool, std::string> status_cookie =
729 if (status_cookie.first &&
734 cookie = std::vector<uint8_t>(status_cookie.second.begin(),
735 status_cookie.second.end());
740 std::placeholders::_1,
741 std::placeholders::_2));
743 if (status_cookie.first) {
744 LogPrintf(
"tor: Authentication cookie %s is not exactly %i "
745 "bytes, as is required by the spec\n",
748 LogPrintf(
"tor: Authentication cookie %s could not be "
749 "opened (check permissions)\n",
753 }
else if (methods.count(
"HASHEDPASSWORD")) {
754 LogPrintf(
"tor: The only supported authentication mechanism left "
755 "is password, but no password provided with "
758 LogPrintf(
"tor: No supported authentication method\n");
761 LogPrintf(
"tor: Requesting protocol info failed\n");
769 if (!_conn.
Command(
"PROTOCOLINFO 1",
771 std::placeholders::_1,
772 std::placeholders::_2))) {
773 LogPrintf(
"tor: Error sending initial protocolinfo command\n");
788 "tor: Not connected to Tor control port %s, trying to reconnect\n",
805 std::placeholders::_1),
807 std::placeholders::_1))) {
809 "tor: Re-initiating connection to Tor control port %s failed\n",
829 onion_service_target);
831 event_base_dispatch(
gBase);
837 evthread_use_windows_threads();
839 evthread_use_pthreads();
841 gBase = event_base_new();
843 LogPrintf(
"tor: Unable to create event_base\n");
857 gBase, -1, EV_TIMEOUT,
858 [](evutil_socket_t,
short,
void *) { event_base_loopbreak(
gBase); },
866 event_base_free(
gBase);
872 struct in_addr onion_service_target;
873 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,...)
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.