18 #include <boost/bind.hpp> 19 #include <boost/signals2/signal.hpp> 20 #include <boost/algorithm/string/split.hpp> 21 #include <boost/algorithm/string/classification.hpp> 22 #include <boost/algorithm/string/replace.hpp> 24 #include <event2/bufferevent.h> 25 #include <event2/buffer.h> 26 #include <event2/util.h> 27 #include <event2/event.h> 28 #include <event2/thread.h> 33 static const int TOR_COOKIE_SIZE = 32;
35 static const int TOR_NONCE_SIZE = 32;
37 static const std::string TOR_SAFE_SERVERKEY =
"Tor safe cookie authentication server-to-controller hash";
39 static const std::string TOR_SAFE_CLIENTKEY =
"Tor safe cookie authentication controller-to-server hash";
41 static const float RECONNECT_TIMEOUT_START = 1.0;
43 static const float RECONNECT_TIMEOUT_EXP = 1.5;
48 static const int MAX_LINE_LENGTH = 100000;
75 typedef std::function<void(TorControlConnection &,const TorControlReply &)>
ReplyHandlerCB;
89 bool Connect(
const std::string &target,
const ConnectionCB& connected,
const ConnectionCB& disconnected);
100 bool Command(
const std::string &cmd,
const ReplyHandlerCB& reply_handler);
103 boost::signals2::signal<void(TorControlConnection &,const TorControlReply &)>
async_handler;
119 static void readcb(
struct bufferevent *bev,
void *ctx);
120 static void eventcb(
struct bufferevent *bev,
short what,
void *ctx);
124 base(_base), b_conn(0)
137 struct evbuffer *input = bufferevent_get_input(bev);
138 size_t n_read_out = 0;
142 while((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) !=
nullptr)
144 std::string s(line, n_read_out);
149 self->message.code =
atoi(s.substr(0,3));
150 self->message.lines.push_back(s.substr(4));
154 if (self->message.code >= 600) {
157 self->async_handler(*
self, self->message);
159 if (!self->reply_handlers.empty()) {
161 self->reply_handlers.front()(*
self,
self->message);
162 self->reply_handlers.pop_front();
167 self->message.Clear();
173 if (evbuffer_get_length(input) > MAX_LINE_LENGTH) {
174 LogPrintf(
"tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
182 if (what & BEV_EVENT_CONNECTED) {
184 self->connected(*
self);
185 }
else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
186 if (what & BEV_EVENT_ERROR) {
192 self->disconnected(*
self);
201 struct sockaddr_storage connect_to_addr;
202 int connect_to_addrlen =
sizeof(connect_to_addr);
203 if (evutil_parse_sockaddr_port(target.c_str(),
204 (
struct sockaddr*)&connect_to_addr, &connect_to_addrlen)<0) {
205 LogPrintf(
"tor: Error parsing socket address %s\n", target);
210 b_conn = bufferevent_socket_new(
base, -1, BEV_OPT_CLOSE_ON_FREE);
214 bufferevent_enable(
b_conn, EV_READ|EV_WRITE);
219 if (bufferevent_socket_connect(
b_conn, (
struct sockaddr*)&connect_to_addr, connect_to_addrlen) < 0) {
220 LogPrintf(
"tor: Error connecting to address %s\n", target);
238 struct evbuffer *buf = bufferevent_get_output(
b_conn);
241 evbuffer_add(buf, cmd.data(), cmd.size());
242 evbuffer_add(buf,
"\r\n", 2);
254 static std::pair<std::string,std::string> SplitTorReplyLine(
const std::string &s)
258 while (ptr < s.size() && s[ptr] !=
' ') {
259 type.push_back(s[ptr]);
264 return make_pair(type, s.substr(ptr));
273 static std::map<std::string,std::string> ParseTorReplyMapping(
const std::string &s)
275 std::map<std::string,std::string> mapping;
277 while (ptr < s.size()) {
278 std::string key, value;
279 while (ptr < s.size() && s[ptr] !=
'=' && s[ptr] !=
' ') {
280 key.push_back(s[ptr]);
284 return std::map<std::string,std::string>();
288 if (ptr < s.size() && s[ptr] ==
'"') {
290 bool escape_next =
false;
291 while (ptr < s.size() && (escape_next || s[ptr] !=
'"')) {
293 escape_next = (s[ptr] ==
'\\' && !escape_next);
294 value.push_back(s[ptr]);
298 return std::map<std::string,std::string>();
310 std::string escaped_value;
311 for (
size_t i = 0; i < value.size(); ++i) {
312 if (value[i] ==
'\\') {
318 if (value[i] ==
'n') {
319 escaped_value.push_back(
'\n');
320 }
else if (value[i] ==
't') {
321 escaped_value.push_back(
'\t');
322 }
else if (value[i] ==
'r') {
323 escaped_value.push_back(
'\r');
324 }
else if (
'0' <= value[i] && value[i] <=
'7') {
329 for (j = 1; j < 3 && (i+j) < value.size() &&
'0' <= value[i+j] && value[i+j] <=
'7'; ++j) {}
333 if (j == 3 && value[i] >
'3') {
336 escaped_value.push_back(strtol(value.substr(i, j).c_str(),
nullptr, 8));
340 escaped_value.push_back(value[i]);
343 escaped_value.push_back(value[i]);
346 value = escaped_value;
348 while (ptr < s.size() && s[ptr] !=
' ') {
349 value.push_back(s[ptr]);
353 if (ptr < s.size() && s[ptr] ==
' ')
355 mapping[key] = value;
371 return std::make_pair(
false,
"");
375 while ((n=fread(buffer, 1,
sizeof(buffer), f)) > 0) {
380 return std::make_pair(
false,
"");
382 retval.append(buffer, buffer+n);
383 if (retval.size() > maxsize)
387 return std::make_pair(
true,retval);
393 static bool WriteBinaryFile(
const fs::path &filename,
const std::string &
data)
398 if (fwrite(data.data(), 1, data.size(),
f) != data.size()) {
418 fs::path GetPrivateKeyFile();
451 static void reconnect_cb(evutil_socket_t
fd,
short what,
void *arg);
456 target(_target), conn(
base), reconnect(true), reconnect_ev(0),
457 reconnect_timeout(RECONNECT_TIMEOUT_START)
461 LogPrintf(
"tor: Failed to create event for reconnection: out of memory?\n");
465 LogPrintf(
"tor: Initiating connection to Tor control port %s failed\n", _target);
488 if (reply.
code == 250) {
490 for (
const std::string &s : reply.
lines) {
491 std::map<std::string,std::string> m = ParseTorReplyMapping(s);
492 std::map<std::string,std::string>::iterator i;
493 if ((i = m.find(
"ServiceID")) != m.end())
495 if ((i = m.find(
"PrivateKey")) != m.end())
499 LogPrintf(
"tor: Error parsing ADD_ONION parameters:\n");
500 for (
const std::string &s : reply.
lines) {
514 }
else if (reply.
code == 510) {
515 LogPrintf(
"tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)\n");
517 LogPrintf(
"tor: Add onion failed; error code %d\n", reply.
code);
523 if (reply.
code == 250) {
544 LogPrintf(
"tor: Authentication failed\n");
564 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)
566 CHMAC_SHA256 computeHash((
const uint8_t*)key.data(), key.size());
570 computeHash.Write(serverNonce.data(), serverNonce.size());
571 computeHash.Finalize(computedHash.data());
577 if (reply.
code == 250) {
579 std::pair<std::string,std::string> l = SplitTorReplyLine(reply.
lines[0]);
580 if (l.first ==
"AUTHCHALLENGE") {
581 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
586 std::vector<uint8_t> serverHash =
ParseHex(m[
"SERVERHASH"]);
587 std::vector<uint8_t> serverNonce =
ParseHex(m[
"SERVERNONCE"]);
589 if (serverNonce.size() != 32) {
590 LogPrintf(
"tor: ServerNonce is not 32 bytes, as required by spec\n");
594 std::vector<uint8_t> computedServerHash = ComputeResponse(TOR_SAFE_SERVERKEY,
cookie,
clientNonce, serverNonce);
595 if (computedServerHash != serverHash) {
596 LogPrintf(
"tor: ServerHash %s does not match expected ServerHash %s\n",
HexStr(serverHash),
HexStr(computedServerHash));
600 std::vector<uint8_t> computedClientHash = ComputeResponse(TOR_SAFE_CLIENTKEY,
cookie,
clientNonce, serverNonce);
603 LogPrintf(
"tor: Invalid reply to AUTHCHALLENGE\n");
606 LogPrintf(
"tor: SAFECOOKIE authentication challenge failed\n");
612 if (reply.
code == 250) {
613 std::set<std::string> methods;
614 std::string cookiefile;
620 for (
const std::string &s : reply.
lines) {
621 std::pair<std::string,std::string> l = SplitTorReplyLine(s);
622 if (l.first ==
"AUTH") {
623 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
624 std::map<std::string,std::string>::iterator i;
625 if ((i = m.find(
"METHODS")) != m.end())
626 boost::split(methods, i->second, boost::is_any_of(
","));
627 if ((i = m.find(
"COOKIEFILE")) != m.end())
628 cookiefile = i->second;
629 }
else if (l.first ==
"VERSION") {
630 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
631 std::map<std::string,std::string>::iterator i;
632 if ((i = m.find(
"Tor")) != m.end()) {
637 for (
const std::string &s : methods) {
645 std::string torpassword =
gArgs.
GetArg(
"-torpassword",
"");
646 if (!torpassword.empty()) {
647 if (methods.count(
"HASHEDPASSWORD")) {
649 boost::replace_all(torpassword,
"\"",
"\\\"");
652 LogPrintf(
"tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available\n");
654 }
else if (methods.count(
"NULL")) {
657 }
else if (methods.count(
"SAFECOOKIE")) {
659 LogPrint(
BCLog::TOR,
"tor: Using SAFECOOKIE authentication, reading cookie authentication from %s\n", cookiefile);
660 std::pair<bool,std::string> status_cookie = ReadBinaryFile(cookiefile, TOR_COOKIE_SIZE);
661 if (status_cookie.first && status_cookie.second.size() == TOR_COOKIE_SIZE) {
663 cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
664 clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
668 if (status_cookie.first) {
669 LogPrintf(
"tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec\n", cookiefile, TOR_COOKIE_SIZE);
671 LogPrintf(
"tor: Authentication cookie %s could not be opened (check permissions)\n", cookiefile);
674 }
else if (methods.count(
"HASHEDPASSWORD")) {
675 LogPrintf(
"tor: The only supported authentication mechanism left is password, but no password provided with -torpassword\n");
677 LogPrintf(
"tor: No supported authentication method\n");
680 LogPrintf(
"tor: Requesting protocol info failed\n");
689 LogPrintf(
"tor: Error sending initial protocolinfo command\n");
717 LogPrintf(
"tor: Re-initiating connection to Tor control port %s failed\n",
target);
733 static struct event_base *gBase;
734 static boost::thread torControlThread;
736 static void TorControlThread()
740 event_base_dispatch(gBase);
747 evthread_use_windows_threads();
749 evthread_use_pthreads();
751 gBase = event_base_new();
753 LogPrintf(
"tor: Unable to create event_base\n");
757 torControlThread = boost::thread(boost::bind(&
TraceThread<
void (*)()>,
"torcontrol", &TorControlThread));
764 event_base_loopbreak(gBase);
771 torControlThread.join();
772 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
assert(len-trim+(2 *lenIndices)<=WIDTH)
unsigned short GetListenPort()
if(a.IndicesBefore(b, len, lenIndices))
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.
std::string ToString() const
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.
PlatformStyle::TableColorType type
bool RemoveLocal(const CService &addr)
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
static void eventcb(struct bufferevent *bev, short what, void *ctx)
static const size_t OUTPUT_SIZE
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.
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.
uint32_t ch(uint32_t x, uint32_t y, uint32_t z)
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)