19 #include <boost/bind.hpp> 20 #include <boost/signals2/signal.hpp> 21 #include <boost/algorithm/string/split.hpp> 22 #include <boost/algorithm/string/classification.hpp> 23 #include <boost/algorithm/string/replace.hpp> 25 #include <event2/bufferevent.h> 26 #include <event2/buffer.h> 27 #include <event2/util.h> 28 #include <event2/event.h> 29 #include <event2/thread.h> 34 static const int TOR_COOKIE_SIZE = 32;
36 static const int TOR_NONCE_SIZE = 32;
38 static const std::string TOR_SAFE_SERVERKEY =
"Tor safe cookie authentication server-to-controller hash";
40 static const std::string TOR_SAFE_CLIENTKEY =
"Tor safe cookie authentication controller-to-server hash";
42 static const float RECONNECT_TIMEOUT_START = 1.0;
44 static const float RECONNECT_TIMEOUT_EXP = 1.5;
49 static const int MAX_LINE_LENGTH = 100000;
76 typedef std::function<void(TorControlConnection &,const TorControlReply &)>
ReplyHandlerCB;
90 bool Connect(
const std::string &target,
const ConnectionCB& connected,
const ConnectionCB& disconnected);
101 bool Command(
const std::string &cmd,
const ReplyHandlerCB& reply_handler);
104 boost::signals2::signal<void(TorControlConnection &,const TorControlReply &)>
async_handler;
120 static void readcb(
struct bufferevent *bev,
void *ctx);
121 static void eventcb(
struct bufferevent *bev,
short what,
void *ctx);
125 base(_base), b_conn(nullptr)
138 struct evbuffer *input = bufferevent_get_input(bev);
139 size_t n_read_out = 0;
143 while((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) !=
nullptr)
145 std::string s(line, n_read_out);
150 self->message.code =
atoi(s.substr(0,3));
151 self->message.lines.push_back(s.substr(4));
155 if (self->message.code >= 600) {
158 self->async_handler(*
self, self->message);
160 if (!self->reply_handlers.empty()) {
162 self->reply_handlers.front()(*
self,
self->message);
163 self->reply_handlers.pop_front();
168 self->message.Clear();
174 if (evbuffer_get_length(input) > MAX_LINE_LENGTH) {
175 LogPrintf(
"tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
183 if (what & BEV_EVENT_CONNECTED) {
185 self->connected(*
self);
186 }
else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
187 if (what & BEV_EVENT_ERROR) {
193 self->disconnected(*
self);
202 struct sockaddr_storage connect_to_addr;
203 int connect_to_addrlen =
sizeof(connect_to_addr);
204 if (evutil_parse_sockaddr_port(target.c_str(),
205 (
struct sockaddr*)&connect_to_addr, &connect_to_addrlen)<0) {
206 LogPrintf(
"tor: Error parsing socket address %s\n", target);
211 b_conn = bufferevent_socket_new(
base, -1, BEV_OPT_CLOSE_ON_FREE);
215 bufferevent_enable(
b_conn, EV_READ|EV_WRITE);
220 if (bufferevent_socket_connect(
b_conn, (
struct sockaddr*)&connect_to_addr, connect_to_addrlen) < 0) {
221 LogPrintf(
"tor: Error connecting to address %s\n", target);
239 struct evbuffer *buf = bufferevent_get_output(
b_conn);
242 evbuffer_add(buf, cmd.data(), cmd.size());
243 evbuffer_add(buf,
"\r\n", 2);
255 static std::pair<std::string,std::string> SplitTorReplyLine(
const std::string &s)
259 while (ptr < s.size() && s[ptr] !=
' ') {
260 type.push_back(s[ptr]);
265 return make_pair(type, s.substr(ptr));
274 static std::map<std::string,std::string> ParseTorReplyMapping(
const std::string &s)
276 std::map<std::string,std::string> mapping;
278 while (ptr < s.size()) {
279 std::string key, value;
280 while (ptr < s.size() && s[ptr] !=
'=' && s[ptr] !=
' ') {
281 key.push_back(s[ptr]);
285 return std::map<std::string,std::string>();
289 if (ptr < s.size() && s[ptr] ==
'"') {
291 bool escape_next =
false;
292 while (ptr < s.size() && (escape_next || s[ptr] !=
'"')) {
294 escape_next = (s[ptr] ==
'\\' && !escape_next);
295 value.push_back(s[ptr]);
299 return std::map<std::string,std::string>();
311 std::string escaped_value;
312 for (
size_t i = 0; i < value.size(); ++i) {
313 if (value[i] ==
'\\') {
319 if (value[i] ==
'n') {
320 escaped_value.push_back(
'\n');
321 }
else if (value[i] ==
't') {
322 escaped_value.push_back(
'\t');
323 }
else if (value[i] ==
'r') {
324 escaped_value.push_back(
'\r');
325 }
else if (
'0' <= value[i] && value[i] <=
'7') {
330 for (j = 1; j < 3 && (i+j) < value.size() &&
'0' <= value[i+j] && value[i+j] <=
'7'; ++j) {}
334 if (j == 3 && value[i] >
'3') {
337 escaped_value.push_back(strtol(value.substr(i, j).c_str(),
nullptr, 8));
341 escaped_value.push_back(value[i]);
344 escaped_value.push_back(value[i]);
347 value = escaped_value;
349 while (ptr < s.size() && s[ptr] !=
' ') {
350 value.push_back(s[ptr]);
354 if (ptr < s.size() && s[ptr] ==
' ')
356 mapping[key] = value;
368 static std::pair<bool,std::string> ReadBinaryFile(
const fs::path &filename,
size_t maxsize=std::numeric_limits<size_t>::max())
372 return std::make_pair(
false,
"");
376 while ((n=fread(buffer, 1,
sizeof(buffer), f)) > 0) {
381 return std::make_pair(
false,
"");
383 retval.append(buffer, buffer+n);
384 if (retval.size() > maxsize)
388 return std::make_pair(
true,retval);
394 static bool WriteBinaryFile(
const fs::path &filename,
const std::string &data)
399 if (fwrite(data.data(), 1, data.size(), f) != data.size()) {
419 fs::path GetPrivateKeyFile();
452 static void reconnect_cb(evutil_socket_t fd,
short what,
void *arg);
457 target(_target), conn(
base), reconnect(true), reconnect_ev(0),
458 reconnect_timeout(RECONNECT_TIMEOUT_START)
462 LogPrintf(
"tor: Failed to create event for reconnection: out of memory?\n");
466 LogPrintf(
"tor: Initiating connection to Tor control port %s failed\n", _target);
489 if (reply.
code == 250) {
491 for (
const std::string &s : reply.
lines) {
492 std::map<std::string,std::string> m = ParseTorReplyMapping(s);
493 std::map<std::string,std::string>::iterator i;
494 if ((i = m.find(
"ServiceID")) != m.end())
496 if ((i = m.find(
"PrivateKey")) != m.end())
500 LogPrintf(
"tor: Error parsing ADD_ONION parameters:\n");
501 for (
const std::string &s : reply.
lines) {
515 }
else if (reply.
code == 510) {
516 LogPrintf(
"tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)\n");
518 LogPrintf(
"tor: Add onion failed; error code %d\n", reply.
code);
524 if (reply.
code == 250) {
545 LogPrintf(
"tor: Authentication failed\n");
565 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)
567 CHMAC_SHA256 computeHash((
const uint8_t*)key.data(), key.size());
571 computeHash.Write(serverNonce.data(), serverNonce.size());
572 computeHash.Finalize(computedHash.data());
578 if (reply.
code == 250) {
580 std::pair<std::string,std::string> l = SplitTorReplyLine(reply.
lines[0]);
581 if (l.first ==
"AUTHCHALLENGE") {
582 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
587 std::vector<uint8_t> serverHash =
ParseHex(m[
"SERVERHASH"]);
588 std::vector<uint8_t> serverNonce =
ParseHex(m[
"SERVERNONCE"]);
590 if (serverNonce.size() != 32) {
591 LogPrintf(
"tor: ServerNonce is not 32 bytes, as required by spec\n");
595 std::vector<uint8_t> computedServerHash = ComputeResponse(TOR_SAFE_SERVERKEY,
cookie,
clientNonce, serverNonce);
596 if (computedServerHash != serverHash) {
597 LogPrintf(
"tor: ServerHash %s does not match expected ServerHash %s\n",
HexStr(serverHash),
HexStr(computedServerHash));
601 std::vector<uint8_t> computedClientHash = ComputeResponse(TOR_SAFE_CLIENTKEY,
cookie,
clientNonce, serverNonce);
604 LogPrintf(
"tor: Invalid reply to AUTHCHALLENGE\n");
607 LogPrintf(
"tor: SAFECOOKIE authentication challenge failed\n");
613 if (reply.
code == 250) {
614 std::set<std::string> methods;
615 std::string cookiefile;
621 for (
const std::string &s : reply.
lines) {
622 std::pair<std::string,std::string> l = SplitTorReplyLine(s);
623 if (l.first ==
"AUTH") {
624 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
625 std::map<std::string,std::string>::iterator i;
626 if ((i = m.find(
"METHODS")) != m.end())
627 boost::split(methods, i->second, boost::is_any_of(
","));
628 if ((i = m.find(
"COOKIEFILE")) != m.end())
629 cookiefile = i->second;
630 }
else if (l.first ==
"VERSION") {
631 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
632 std::map<std::string,std::string>::iterator i;
633 if ((i = m.find(
"Tor")) != m.end()) {
638 for (
const std::string &s : methods) {
646 std::string torpassword =
gArgs.
GetArg(
"-torpassword",
"");
647 if (!torpassword.empty()) {
648 if (methods.count(
"HASHEDPASSWORD")) {
650 boost::replace_all(torpassword,
"\"",
"\\\"");
653 LogPrintf(
"tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available\n");
655 }
else if (methods.count(
"NULL")) {
658 }
else if (methods.count(
"SAFECOOKIE")) {
660 LogPrint(
BCLog::TOR,
"tor: Using SAFECOOKIE authentication, reading cookie authentication from %s\n", cookiefile);
661 std::pair<bool,std::string> status_cookie = ReadBinaryFile(cookiefile, TOR_COOKIE_SIZE);
662 if (status_cookie.first && status_cookie.second.size() == TOR_COOKIE_SIZE) {
664 cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
665 clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
669 if (status_cookie.first) {
670 LogPrintf(
"tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec\n", cookiefile, TOR_COOKIE_SIZE);
672 LogPrintf(
"tor: Authentication cookie %s could not be opened (check permissions)\n", cookiefile);
675 }
else if (methods.count(
"HASHEDPASSWORD")) {
676 LogPrintf(
"tor: The only supported authentication mechanism left is password, but no password provided with -torpassword\n");
678 LogPrintf(
"tor: No supported authentication method\n");
681 LogPrintf(
"tor: Requesting protocol info failed\n");
690 LogPrintf(
"tor: Error sending initial protocolinfo command\n");
718 LogPrintf(
"tor: Re-initiating connection to Tor control port %s failed\n",
target);
734 static struct event_base *gBase;
735 static boost::thread torControlThread;
737 static void TorControlThread()
741 event_base_dispatch(gBase);
748 evthread_use_windows_threads();
750 evthread_use_pthreads();
752 gBase = event_base_new();
754 LogPrintf(
"tor: Unable to create event_base\n");
758 torControlThread = boost::thread(boost::bind(&
TraceThread<
void (*)()>,
"torcontrol", &TorControlThread));
765 event_base_loopbreak(gBase);
772 torControlThread.join();
773 event_base_free(gBase);
void authchallenge_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHCHALLENGE result.
bool AddLocal(const CService &addr, int nScore)
FILE * fopen(const fs::path &p, const char *mode)
std::function< void(TorControlConnection &)> disconnected
Callback when connection lost.
std::function< void(TorControlConnection &)> ConnectionCB
struct bufferevent * b_conn
Connection to control socket.
std::vector< uint8_t > clientNonce
ClientNonce for SAFECOOKIE auth.
CService LookupNumeric(const char *pszName, int portDefault)
Reply from Tor, can be single or multi-line.
bool Connect(const std::string &target, const ConnectionCB &connected, const ConnectionCB &disconnected)
Connect to a Tor control port.
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
void SetLimited(enum Network net, bool fLimited)
Make a particular network entirely off-limits (no automatic connects to it)
A hasher class for HMAC-SHA-256.
void protocolinfo_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for PROTOCOLINFO result.
void Reconnect()
Reconnect, after getting disconnected.
std::vector< std::string > lines
unsigned short GetListenPort()
std::deque< ReplyHandlerCB > reply_handlers
Response handlers.
std::function< void(TorControlConnection &, const TorControlReply &)> ReplyHandlerCB
void disconnected_cb(TorControlConnection &conn)
Callback after connection lost or failed connection attempt.
static void readcb(struct bufferevent *bev, void *ctx)
Libevent handlers: internal.
fs::path GetPrivateKeyFile()
Get name fo file to store private key in.
struct event * reconnect_ev
TorControlConnection(struct event_base *base)
Create a new TorControlConnection.
const std::string DEFAULT_TOR_CONTROL
Default control port.
std::vector< uint8_t > cookie
Cookie for SAFECOOKIE auth.
TorControlConnection conn
A combination of a network address (CNetAddr) and a (TCP) port.
TorController(struct event_base *base, const std::string &target)
void TraceThread(const char *name, Callable func)
static void reconnect_cb(evutil_socket_t fd, short what, void *arg)
Callback for reconnect timer.
void add_onion_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for ADD_ONION result.
bool SetProxy(enum Network net, const proxyType &addrProxy)
struct timeval MillisToTimeval(int64_t nTimeout)
Convert milliseconds to a struct timeval for e.g.
#define LogPrint(category,...)
void auth_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHENTICATE result.
bool RemoveLocal(const CService &addr)
static void eventcb(struct bufferevent *bev, short what, void *ctx)
static const size_t OUTPUT_SIZE
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
bool Command(const std::string &cmd, const ReplyHandlerCB &reply_handler)
Send a command, register a handler for the reply.
void StartTorControl(boost::thread_group &threadGroup, CScheduler &scheduler)
void GetRandBytes(unsigned char *buf, int num)
Functions to gather random data via the OpenSSL PRNG.
void connected_cb(TorControlConnection &conn)
Callback after successful connection.
std::string ToString() const
const fs::path & GetDataDir(bool fNetSpecific)
Controller that connects to Tor control socket, authenticate, then create and maintain an ephemeral h...
void InterruptTorControl()
Low-level handling for Tor control connection.
bool Disconnect()
Disconnect from Tor control port.
boost::signals2::signal< void(TorControlConnection &, const TorControlReply &)> async_handler
Response handlers for async replies.
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
TorControlReply message
Message being received.
int atoi(const std::string &str)
struct event_base * base
Libevent event base.
std::function< void(TorControlConnection &)> connected
Callback when ready for use.
std::vector< unsigned char > ParseHex(const char *psz)