Hush Full Node software. We were censored from Github, this is where all development happens now. https://hush.is
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

779 lines
30 KiB

// Copyright (c) 2015-2017 The Bitcoin Core developers
// Copyright (c) 2017 The Zcash developers
4 years ago
// Copyright (c) 2019-2020 The Hush developers
// Distributed under the GPLv3 software license, see the accompanying
// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html
#include "torcontrol.h"
#include "utilstrencodings.h"
#include "net.h"
#include "util.h"
#include "crypto/hmac_sha256.h"
#include <vector>
#include <deque>
#include <set>
#include <stdlib.h>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/signals2/signal.hpp>
#include <boost/foreach.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/util.h>
#include <event2/event.h>
#include <event2/thread.h>
/** Default control port */
const std::string DEFAULT_TOR_CONTROL = "127.0.0.1:9051";
/** Tor cookie size (from control-spec.txt) */
static const int TOR_COOKIE_SIZE = 32;
/** Size of client/server nonce for SAFECOOKIE */
static const int TOR_NONCE_SIZE = 32;
/** For computing serverHash in SAFECOOKIE */
static const std::string TOR_SAFE_SERVERKEY = "Tor safe cookie authentication server-to-controller hash";
/** For computing clientHash in SAFECOOKIE */
static const std::string TOR_SAFE_CLIENTKEY = "Tor safe cookie authentication controller-to-server hash";
/** Exponential backoff configuration - initial timeout in seconds */
static const float RECONNECT_TIMEOUT_START = 1.0;
/** Exponential backoff configuration - growth factor */
static const float RECONNECT_TIMEOUT_EXP = 1.5;
/** Maximum length for lines received on TorControlConnection.
* tor-control-spec.txt mentions that there is explicitly no limit defined to line length,
* this is belt-and-suspenders sanity limit to prevent memory exhaustion.
*/
static const int MAX_LINE_LENGTH = 100000;
/****** Low-level TorControlConnection ********/
/** Reply from Tor, can be single or multi-line */
class TorControlReply
{
public:
TorControlReply() { Clear(); }
int code;
std::vector<std::string> lines;
void Clear()
{
code = 0;
lines.clear();
}
};
/** Low-level handling for Tor control connection.
* Speaks the SMTP-like protocol as defined in torspec/control-spec.txt
*/
class TorControlConnection
{
public:
typedef boost::function<void(TorControlConnection&)> ConnectionCB;
typedef boost::function<void(TorControlConnection &,const TorControlReply &)> ReplyHandlerCB;
/** Create a new TorControlConnection.
*/
TorControlConnection(struct event_base *base);
~TorControlConnection();
/**
* Connect to a Tor control port.
* target is address of the form host:port.
* connected is the handler that is called when connection is successfully established.
* disconnected is a handler that is called when the connection is broken.
* Return true on success.
*/
bool Connect(const std::string &target, const ConnectionCB& connected, const ConnectionCB& disconnected);
/**
* Disconnect from Tor control port.
*/
bool Disconnect();
/** Send a command, register a handler for the reply.
* A trailing CRLF is automatically added.
* Return true on success.
*/
bool Command(const std::string &cmd, const ReplyHandlerCB& reply_handler);
/** Response handlers for async replies */
boost::signals2::signal<void(TorControlConnection &,const TorControlReply &)> async_handler;
private:
/** Callback when ready for use */
boost::function<void(TorControlConnection&)> connected;
/** Callback when connection lost */
boost::function<void(TorControlConnection&)> disconnected;
/** Libevent event base */
struct event_base *base;
/** Connection to control socket */
struct bufferevent *b_conn;
/** Message being received */
TorControlReply message;
/** Response handlers */
std::deque<ReplyHandlerCB> reply_handlers;
/** Libevent handlers: internal */
static void readcb(struct bufferevent *bev, void *ctx);
static void eventcb(struct bufferevent *bev, short what, void *ctx);
};
TorControlConnection::TorControlConnection(struct event_base *base):
base(base), b_conn(0)
{
}
TorControlConnection::~TorControlConnection()
{
if (b_conn)
bufferevent_free(b_conn);
}
void TorControlConnection::readcb(struct bufferevent *bev, void *ctx)
{
TorControlConnection *self = (TorControlConnection*)ctx;
struct evbuffer *input = bufferevent_get_input(bev);
size_t n_read_out = 0;
char *line;
assert(input);
// If there is not a whole line to read, evbuffer_readln returns NULL
while((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) != NULL)
{
std::string s(line, n_read_out);
free(line);
if (s.size() < 4) // Short line
continue;
// <status>(-|+| )<data><CRLF>
self->message.code = atoi(s.substr(0,3));
self->message.lines.push_back(s.substr(4));
char ch = s[3]; // '-','+' or ' '
if (ch == ' ') {
// Final line, dispatch reply and clean up
if (self->message.code >= 600) {
// Dispatch async notifications to async handler
// Synchronous and asynchronous messages are never interleaved
self->async_handler(*self, self->message);
} else {
if (!self->reply_handlers.empty()) {
// Invoke reply handler with message
self->reply_handlers.front()(*self, self->message);
self->reply_handlers.pop_front();
} else {
LogPrint("tor", "tor: Received unexpected sync reply %i\n", self->message.code);
}
}
self->message.Clear();
}
}
// Check for size of buffer - protect against memory exhaustion with very long lines
// Do this after evbuffer_readln to make sure all full lines have been
// removed from the buffer. Everything left is an incomplete line.
if (evbuffer_get_length(input) > MAX_LINE_LENGTH) {
LogPrintf("tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
self->Disconnect();
}
}
void TorControlConnection::eventcb(struct bufferevent *bev, short what, void *ctx)
{
TorControlConnection *self = (TorControlConnection*)ctx;
if (what & BEV_EVENT_CONNECTED) {
LogPrint("tor", "tor: Successfully connected!\n");
self->connected(*self);
} else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
if (what & BEV_EVENT_ERROR)
LogPrint("tor", "tor: Error connecting to Tor control socket\n");
else
LogPrint("tor", "tor: End of stream\n");
self->Disconnect();
self->disconnected(*self);
}
}
bool TorControlConnection::Connect(const std::string &target, const ConnectionCB& connected, const ConnectionCB& disconnected)
{
if (b_conn)
Disconnect();
// Parse target address:port
struct sockaddr_storage connect_to_addr;
int connect_to_addrlen = sizeof(connect_to_addr);
if (evutil_parse_sockaddr_port(target.c_str(),
(struct sockaddr*)&connect_to_addr, &connect_to_addrlen)<0) {
LogPrintf("tor: Error parsing socket address %s\n", target);
return false;
}
// Create a new socket, set up callbacks and enable notification bits
b_conn = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
if (!b_conn)
return false;
bufferevent_setcb(b_conn, TorControlConnection::readcb, NULL, TorControlConnection::eventcb, this);
bufferevent_enable(b_conn, EV_READ|EV_WRITE);
this->connected = connected;
this->disconnected = disconnected;
// Finally, connect to target
if (bufferevent_socket_connect(b_conn, (struct sockaddr*)&connect_to_addr, connect_to_addrlen) < 0) {
LogPrintf("tor: Error connecting to address %s\n", target);
return false;
}
return true;
}
bool TorControlConnection::Disconnect()
{
if (b_conn)
bufferevent_free(b_conn);
b_conn = 0;
return true;
}
bool TorControlConnection::Command(const std::string &cmd, const ReplyHandlerCB& reply_handler)
{
if (!b_conn)
return false;
struct evbuffer *buf = bufferevent_get_output(b_conn);
if (!buf)
return false;
evbuffer_add(buf, cmd.data(), cmd.size());
evbuffer_add(buf, "\r\n", 2);
reply_handlers.push_back(reply_handler);
return true;
}
/****** General parsing utilities ********/
/* Split reply line in the form 'AUTH METHODS=...' into a type
* 'AUTH' and arguments 'METHODS=...'.
* Grammar is implicitly defined in https://spec.torproject.org/control-spec by
* the server reply formats for PROTOCOLINFO (S3.21) and AUTHCHALLENGE (S3.24).
*/
static std::pair<std::string,std::string> SplitTorReplyLine(const std::string &s)
{
size_t ptr=0;
std::string type;
while (ptr < s.size() && s[ptr] != ' ') {
type.push_back(s[ptr]);
++ptr;
}
if (ptr < s.size())
++ptr; // skip ' '
return make_pair(type, s.substr(ptr));
}
/** Parse reply arguments in the form 'METHODS=COOKIE,SAFECOOKIE COOKIEFILE=".../control_auth_cookie"'.
* Returns a map of keys to values, or an empty map if there was an error.
* Grammar is implicitly defined in https://spec.torproject.org/control-spec by
* the server reply formats for PROTOCOLINFO (S3.21), AUTHCHALLENGE (S3.24),
* and ADD_ONION (S3.27). See also sections 2.1 and 2.3.
*/
static std::map<std::string,std::string> ParseTorReplyMapping(const std::string &s)
{
std::map<std::string,std::string> mapping;
size_t ptr=0;
while (ptr < s.size()) {
std::string key, value;
while (ptr < s.size() && s[ptr] != '=' && s[ptr] != ' ') {
key.push_back(s[ptr]);
++ptr;
}
if (ptr == s.size()) // unexpected end of line
return std::map<std::string,std::string>();
if (s[ptr] == ' ') // The remaining string is an OptArguments
break;
++ptr; // skip '='
if (ptr < s.size() && s[ptr] == '"') { // Quoted string
++ptr; // skip opening '"'
bool escape_next = false;
while (ptr < s.size() && (escape_next || s[ptr] != '"')) {
// Repeated backslashes must be interpreted as pairs
escape_next = (s[ptr] == '\\' && !escape_next);
value.push_back(s[ptr]);
++ptr;
}
if (ptr == s.size()) // unexpected end of line
return std::map<std::string,std::string>();
++ptr; // skip closing '"'
/**
* Unescape value. Per https://spec.torproject.org/control-spec section 2.1.1:
*
* For future-proofing, controller implementors MAY use the following
* rules to be compatible with buggy Tor implementations and with
* future ones that implement the spec as intended:
*
* Read \n \t \r and \0 ... \377 as C escapes.
* Treat a backslash followed by any other character as that character.
*/
std::string escaped_value;
for (size_t i = 0; i < value.size(); ++i) {
if (value[i] == '\\') {
// This will always be valid, because if the QuotedString
// ended in an odd number of backslashes, then the parser
// would already have returned above, due to a missing
// terminating double-quote.
++i;
if (value[i] == 'n') {
escaped_value.push_back('\n');
} else if (value[i] == 't') {
escaped_value.push_back('\t');
} else if (value[i] == 'r') {
escaped_value.push_back('\r');
} else if ('0' <= value[i] && value[i] <= '7') {
size_t j;
// Octal escape sequences have a limit of three octal digits,
// but terminate at the first character that is not a valid
// octal digit if encountered sooner.
for (j = 1; j < 3 && (i+j) < value.size() && '0' <= value[i+j] && value[i+j] <= '7'; ++j) {}
// Tor restricts first digit to 0-3 for three-digit octals.
// A leading digit of 4-7 would therefore be interpreted as
// a two-digit octal.
if (j == 3 && value[i] > '3') {
j--;
}
escaped_value.push_back(strtol(value.substr(i, j).c_str(), NULL, 8));
// Account for automatic incrementing at loop end
i += j - 1;
} else {
escaped_value.push_back(value[i]);
}
} else {
escaped_value.push_back(value[i]);
}
}
value = escaped_value;
} else { // Unquoted value. Note that values can contain '=' at will, just no spaces
while (ptr < s.size() && s[ptr] != ' ') {
value.push_back(s[ptr]);
++ptr;
}
}
if (ptr < s.size() && s[ptr] == ' ')
++ptr; // skip ' ' after key=value
mapping[key] = value;
}
return mapping;
}
/** Read full contents of a file and return them in a std::string.
* Returns a pair <status, string>.
* If an error occured, status will be false, otherwise status will be true and the data will be returned in string.
*
* @param maxsize Puts a maximum size limit on the file that is read. If the file is larger than this, truncated data
* (with len > maxsize) will be returned.
*/
static std::pair<bool,std::string> ReadBinaryFile(const std::string &filename, size_t maxsize=std::numeric_limits<size_t>::max())
{
FILE *f = fopen(filename.c_str(), "rb");
if (f == NULL)
return std::make_pair(false,"");
std::string retval;
char buffer[128];
size_t n;
while ((n=fread(buffer, 1, sizeof(buffer), f)) > 0) {
// Check for reading errors so we don't return any data if we couldn't
// read the entire file (or up to maxsize)
if (ferror(f)) {
fclose(f);
return std::make_pair(false,"");
}
retval.append(buffer, buffer+n);
if (retval.size() > maxsize)
break;
}
fclose(f);
return std::make_pair(true,retval);
}
/** Write contents of std::string to a file.
* @return true on success.
*/
static bool WriteBinaryFile(const std::string &filename, const std::string &data)
{
FILE *f = fopen(filename.c_str(), "wb");
if (f == NULL)
return false;
if (fwrite(data.data(), 1, data.size(), f) != data.size()) {
fclose(f);
return false;
}
fclose(f);
return true;
}
/****** Bitcoin specific TorController implementation ********/
/** Controller that connects to Tor control socket, authenticate, then create
* and maintain a ephemeral hidden service.
*/
class TorController
{
public:
TorController(struct event_base* base, const std::string& target);
~TorController();
Squashed commit of the following: commit 5e7222e4bc0401ef8c6d8049b12a62d4854ac85c Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Thu Mar 1 21:20:51 2018 +0200 Cleanup commit 2e1bc7a7cd6c72e7c3d2ff74cb30f7a56515006c Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Thu Mar 1 21:19:53 2018 +0200 Cleanup commit edd7fa87fb2c839c17457ff004d258a049df832f Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Thu Mar 1 21:18:57 2018 +0200 Cleanup commit ee34e1433806655a7123f0617802aa4771507dff Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Thu Mar 1 21:18:10 2018 +0200 Cleanup commit 20779e4021b8ab95a87289d2741ad2f0fbc7fb39 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Thu Mar 1 21:16:52 2018 +0200 Cleanup commit 084e1aa563807f5625ad3aaff376b598e139f2a7 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 18:42:49 2018 +0200 Fix typo commit c61a7c2319d3b9b96d1b5ad52ecf9d4f2fd92658 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 18:37:43 2018 +0200 Cleanup commit e435c0229b0cbe3f4a77f43b01ca87ed0552d405 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 18:17:58 2018 +0200 Fix typos commit e05bff3fea8915e95a473fe3266b2b1f727deca0 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 17:59:32 2018 +0200 Fix typo commit 8c55c7840232cef7fa4389a12f6f220e86f5f581 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 17:46:33 2018 +0200 Fix typos commit a1edfcc5cc29d815ba7e8c4baaf14c23ef93af64 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 17:39:41 2018 +0200 Fix typos commit 2ce2c4d180e936ccc5c10745a6430fda5de38a9b Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 17:14:10 2018 +0200 Fix typo commit 5bdc6cd5bc9cff93aa48fbdeda36d4d9774bfa18 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 17:12:14 2018 +0200 Fix typo commit d08749f549575efc6f44a7f80850bc439c12ad5c Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 16:54:06 2018 +0200 Revert one change commit a734bb1191c692f09f58bcc8e85160ce7c839905 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 16:52:45 2018 +0200 Fix typo commit 95fbc8d94bbefc0db989c83d0f053111bfed45e7 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 16:51:33 2018 +0200 Fix typos commit d17d540a83d035cf9a200f9a8b19f0fab6084728 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 16:49:36 2018 +0200 Fix typo commit c4bf4402210bcb926ccfb3928afeb3a8a7490b42 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 16:48:09 2018 +0200 Fix typo commit 25e7990848a1d723702e2d041c04bc68a6c1275f Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 16:47:01 2018 +0200 Fix typo commit d72ffb5b0253e0d7b992ffe13c40695421378dc3 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 16:45:20 2018 +0200 Fix typo commit 705e6f271192a575cc99d794545b0efe75d964c4 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 16:41:19 2018 +0200 Revert one change commit 4fd26cd29e21c42b027e37da2616761ebc399d16 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 16:39:41 2018 +0200 Revert commit commit 8a5cc627b1048368fe8807973d1f542bab2e045f Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 16:28:56 2018 +0200 Fix typo commit 0a24baa7258c0ae0f244d82af8d0831b148ab012 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 16:15:45 2018 +0200 Fix typo commit 38f93ecd90171fb881243f0de55b3452daccff20 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 15:56:49 2018 +0200 Fix typos commit 15446fd62400c36c2a51f7e6f13725cc8adfd924 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 15:48:00 2018 +0200 Fix typos commit 76533b41986bbc5826070a1e644215a74757c1db Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 15:04:38 2018 +0200 Fix typo commit aea330c2b0bf76975ec69142a732288cc8b192bd Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 14:46:29 2018 +0200 Fix typo commit 8b1b1d0be1dc44f36c22c54d1a3d56d84d456b92 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 14:40:23 2018 +0200 Fix typo commit 46ea76785a26cf20a664ed211c8f3fb9a283e127 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 14:14:17 2018 +0200 Fix typo commit e0d7c5748545dd0975507ad603623072fcc6bdea Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 14:08:24 2018 +0200 Fix typo commit 604d5a244323b17ba596b12d245407e1cf63a375 Merge: 6c081ca 1c65b2b Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 09:03:23 2018 +0200 Merge pull request #36 from rex4539/patch-36 Fix typo commit 6c081caf28b7cef9e62ed523284dff90e4add16d Merge: 899e5d2 88fa2d9 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 09:02:49 2018 +0200 Merge pull request #35 from rex4539/patch-35 Fix typo commit 899e5d2c343ac7ea5069b8548e5df86c8e963e21 Merge: 6380c7f 40e73e2 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 09:02:16 2018 +0200 Merge pull request #34 from rex4539/patch-34 Fix typo commit 6380c7f740246474c69d8145bde61688551efe83 Merge: f592274 4567667 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 09:01:47 2018 +0200 Merge pull request #33 from rex4539/patch-33 Fix typos commit f592274a713162da0083bd6d22fb47cb1afcdba9 Merge: d86ef7e 4aeaa3a Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 09:01:14 2018 +0200 Merge pull request #32 from rex4539/patch-32 Fix typo commit d86ef7e5e4f7e9c2014358ec5b647d1815eb304d Merge: fe0b432 5cdd1b2 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 09:00:41 2018 +0200 Merge pull request #31 from rex4539/patch-31 Fix typo commit fe0b432ee125ae0b876af2c26139dfc979005a3b Merge: 6fd6d0d 70130d0 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 09:00:12 2018 +0200 Merge pull request #30 from rex4539/patch-30 Fix typos commit 6fd6d0dcf3714118a623c0d8d84aabb4578410a8 Merge: 389660f 3377426 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:59:42 2018 +0200 Merge pull request #29 from rex4539/patch-29 Fix typo commit 389660f856cb60ff475a8757aad3873b99213cc0 Merge: a0b85ce 40643eb Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:59:15 2018 +0200 Merge pull request #28 from rex4539/patch-28 Fix typo commit a0b85ce3b4d2e6596da0727e05c1fe15c289b1e7 Merge: 6f9a1c7 23ead80 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:58:42 2018 +0200 Merge pull request #27 from rex4539/patch-27 Fix typo commit 6f9a1c71a680bb3ed1c249dd42bf0a54663d0af3 Merge: b880547 3612eab Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:58:06 2018 +0200 Merge pull request #26 from rex4539/patch-26 Patch 26 commit b880547415afeae36bd19867388e60a3040a15ca Merge: a3b7da2 5c3177f Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:57:24 2018 +0200 Merge pull request #25 from rex4539/patch-25 Fix typo commit a3b7da2c6d6691f38751292e1aea63498a325788 Merge: edd8586 60026ef Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:56:52 2018 +0200 Merge pull request #24 from rex4539/patch-24 Fix typo commit edd8586fdf8c112f4c513804610c237d7e2e80ef Merge: 0c28eb7 f979c00 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:56:12 2018 +0200 Merge pull request #23 from rex4539/patch-23 Fix typo commit 0c28eb7717821b1d68016f40911d07f2a7231b4f Merge: 775beb6 c900722 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:55:42 2018 +0200 Merge pull request #22 from rex4539/patch-22 Fix typo commit 775beb625beb1fc5f72388c076b295de4b8ff039 Merge: a0cf889 1027543 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:55:16 2018 +0200 Merge pull request #21 from rex4539/patch-21 Fix typo commit a0cf88971e756c37c406bab3066c11d6fc7f6d74 Merge: 4504b48 f3fa89b Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:54:44 2018 +0200 Merge pull request #20 from rex4539/patch-20 Fix typo commit 4504b4824b3438e931ca8d24a56b1887657e87cd Merge: dd0bcbf 2699eca Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:54:20 2018 +0200 Merge pull request #19 from rex4539/patch-19 Fix typo commit dd0bcbfc89293e9760156d5534f3a558451e1f29 Merge: abfb65a f02ef2e Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:53:46 2018 +0200 Merge pull request #18 from rex4539/patch-18 Fix typos commit abfb65afaed49c34b9875df79f6fe6eb2b7bf769 Merge: 68b46b7 6485c90 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:53:08 2018 +0200 Merge pull request #17 from rex4539/patch-17 Fix typo commit 68b46b75d2e5b7ae97e83fc5541c46b4907a7899 Merge: a131e84 fcc0828 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:52:39 2018 +0200 Merge pull request #16 from rex4539/patch-16 Fix typo commit a131e844652e58aff78fa8952e7547a9ba82b8a1 Merge: 8487c0e 8a688ff Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:51:54 2018 +0200 Merge pull request #15 from rex4539/patch-15 Fix typo commit 8487c0e39092b74e977c7a60f4a07a27606756a8 Merge: bcc4cb4 bb60b83 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:51:28 2018 +0200 Merge pull request #14 from rex4539/patch-14 Fix typos commit bcc4cb46130e789faa9adae9b159ca818f67ec52 Merge: 23e66e9 53539bb Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:51:00 2018 +0200 Merge pull request #13 from rex4539/patch-13 Fix typos commit 23e66e956bff2d6935c7a4dd570d457294018a77 Merge: 56956cf 0808445 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:50:27 2018 +0200 Merge pull request #12 from rex4539/patch-12 Fix typo commit 56956cf23ba1208aa39cb3ab1ef60375c6630263 Merge: 77007d4 7a4f064 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:49:59 2018 +0200 Merge pull request #11 from rex4539/patch-11 Fix typo commit 77007d49fa1d8cb80aef02bea1dd15e522a47c90 Merge: e78ad0c 48c33fb Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:49:16 2018 +0200 Merge pull request #10 from rex4539/patch-10 Fix typo commit e78ad0cf0d91955a848f5e953a042eabdcdac198 Merge: 38a3e08 809f01c Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:48:33 2018 +0200 Merge pull request #9 from rex4539/patch-9 Fix typo commit 38a3e08699fe4c4ec715b1783dba18bff6b829fb Merge: eee3c28 fec279c Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:48:05 2018 +0200 Merge pull request #8 from rex4539/patch-8 Fix typo commit eee3c286eb84f994310142a9e7fdbd36a671e593 Merge: 702635b cf81b4e Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:47:33 2018 +0200 Merge pull request #7 from rex4539/patch-7 Fix typo commit 702635bb34abb2f83ded27ae95deefd5b6e7df93 Merge: d7497ea 3bbcc3d Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:47:01 2018 +0200 Merge pull request #6 from rex4539/patch-6 Fix typo commit d7497ea070e03380cf1d4f533b7dc4b881f724f8 Merge: bfcc1e8 f639727 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:45:33 2018 +0200 Merge pull request #5 from rex4539/patch-5 Fix typos commit bfcc1e8ae2094ca4e9837f623999705f538aff04 Merge: f4440ec 55262fe Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:45:05 2018 +0200 Merge pull request #4 from rex4539/patch-4 Remove space for word "backup" commit f4440ecd4a7367e6bc4a5f75bea112290017ed2b Merge: f8b487f 61d5279 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:44:31 2018 +0200 Merge pull request #3 from rex4539/patch-3 Fix typos in zmq.md commit f8b487f5699990fabc7fc383d02bc728db3cb9aa Merge: 60104a7 f2ce50f Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:42:51 2018 +0200 Merge pull request #2 from rex4539/patch-2 Fix typo in security-warnings.md commit 60104a7034f55284afb814e81a1430a8b2b0d8d1 Merge: be262f0 af7dfe0 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:41:48 2018 +0200 Merge pull request #1 from rex4539/patch-1 Fix typos commit 1c65b2bd0c49f7f392d0e3a2db14ce1366a87171 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 07:35:26 2018 +0200 Fix typo commit 88fa2d966a3b462ed34a9a4659fc390711cc0276 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 07:21:00 2018 +0200 Fix typo commit 40e73e258671f21d2b2205509e9cae1f50294752 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 07:14:21 2018 +0200 Fix typo commit 4567667fcc8b4197dfd51da34fe82b0f2fb78127 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 06:44:40 2018 +0200 Fix typos commit 4aeaa3a3d6335302c53c0f5f4ef81de05e266479 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 05:55:25 2018 +0200 Fix typo commit 5cdd1b29b4c90492aa15fed7940984e1d675052f Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 05:36:46 2018 +0200 Fix typo commit 70130d05f1646c8b9fb1f33c4efbe2a5fcf7138b Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 05:28:21 2018 +0200 Fix typos commit 33774261b1c63e5640aa1dd251edb67892ed7a5b Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 05:00:56 2018 +0200 Fix typo commit 40643ebfcd85ee257a4576e85d2fb6c73dad17b5 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 04:51:57 2018 +0200 Fix typo commit 23ead80e05116ebfeaac0a00d5bd4a158fbeb54e Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 04:29:53 2018 +0200 Fix typo commit 3612eaba2dcf273e94cac9ad889723776ce55108 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 04:19:36 2018 +0200 Fix typos commit 5c3177f5d191d1f4e4d9f78ae4b75381010f7768 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 04:13:03 2018 +0200 Fix typo commit 60026efe27a39300e428879ad8dba94f19934870 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 04:08:09 2018 +0200 Fix typo commit f979c0074efd66804f229c8b3cc6e812d7f26406 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 04:01:44 2018 +0200 Fix typo commit c9007220a8a727c1cfe3b25b453c178eacd431f3 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 03:52:33 2018 +0200 Fix typo commit 1027543bd30701c4b09aa66226281a10563db910 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 03:36:19 2018 +0200 Fix typo commit f3fa89bcd30e0cb45ff4391e78d02452c9227be0 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 03:34:37 2018 +0200 Fix typo commit 2699eca938f1e413a29d4408a271aaafd27969cc Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 03:30:29 2018 +0200 Fix typo commit f02ef2e495fe43142d305f5c4f40dcfa3d2cb423 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 03:22:36 2018 +0200 Fix typos commit 6485c908433bb91fd70d7e18cf3611c9a96115a7 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 03:10:06 2018 +0200 Fix typo commit fcc082850564b14b86b1932dfc5a099816c72ef1 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 03:06:26 2018 +0200 Fix typo commit 8a688ff7405d67bd4c77b0aa0ebdd4b4a8a9a6a7 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 03:02:50 2018 +0200 Fix typo commit bb60b83853ed0a82ca47dd58d55f1849ddcf23ab Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 02:59:25 2018 +0200 Fix typos commit 53539bb720c7676b9d37e25dde3423db3aa7bfa1 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 02:50:55 2018 +0200 Fix typos commit 080844581d6488ab797ac188acae9c4b2e1d0c59 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 01:05:54 2018 +0200 Fix typo commit 7a4f0649ac5e71f39f0bef7f2e1fcb6fafad0291 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 00:16:31 2018 +0200 Fix typo commit 48c33fb3f9ab1ad287987d147ee4bbe186f7ade1 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 00:07:42 2018 +0200 Fix typo commit 809f01ca4f785a7b5bc9cc2c388e0ae814ecaa95 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 00:02:34 2018 +0200 Fix typo commit fec279cac89aa917be929447c81177811728361a Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Mon Feb 26 23:55:27 2018 +0200 Fix typo commit cf81b4e12399570545372d4c9daceca8e70142d5 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Mon Feb 26 23:48:43 2018 +0200 Fix typo commit 3bbcc3d9986caf8df99bec5d8a18d0f0c8990e06 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Mon Feb 26 23:28:52 2018 +0200 Fix typo commit f639727525dbd23f5f2d0f89e7be13d868e984c3 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Mon Feb 26 23:13:12 2018 +0200 Fix typos commit 55262fe9c5e1e127c6b817a0c2ab3f9db3ac35b9 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Mon Feb 26 22:46:52 2018 +0200 Remove space for word "backup" commit 61d52797d4d26a90dcc15e2bcd6f19a5f36faac3 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Mon Feb 26 22:23:31 2018 +0200 Fix typos in zmq.md commit f2ce50f10e67b4265e559a432681bc44828ae59b Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Mon Feb 26 22:12:58 2018 +0200 Fix typo in security-warnings.md commit af7dfe046c12109e44ddc18dff07ede8755cf4f9 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Mon Feb 26 21:59:24 2018 +0200 Fix typos Signed-off-by: Daira Hopwood <daira@jacaranda.org>
6 years ago
/** Get name for file to store private key in */
std::string GetPrivateKeyFile();
/** Reconnect, after getting disconnected */
void Reconnect();
private:
struct event_base* base;
std::string target;
TorControlConnection conn;
std::string private_key;
std::string service_id;
bool reconnect;
struct event *reconnect_ev;
float reconnect_timeout;
CService service;
/** Cooie for SAFECOOKIE auth */
std::vector<uint8_t> cookie;
/** ClientNonce for SAFECOOKIE auth */
std::vector<uint8_t> clientNonce;
/** Callback for ADD_ONION result */
void add_onion_cb(TorControlConnection& conn, const TorControlReply& reply);
/** Callback for AUTHENTICATE result */
void auth_cb(TorControlConnection& conn, const TorControlReply& reply);
/** Callback for AUTHCHALLENGE result */
void authchallenge_cb(TorControlConnection& conn, const TorControlReply& reply);
/** Callback for PROTOCOLINFO result */
void protocolinfo_cb(TorControlConnection& conn, const TorControlReply& reply);
/** Callback after successful connection */
void connected_cb(TorControlConnection& conn);
/** Callback after connection lost or failed connection attempt */
void disconnected_cb(TorControlConnection& conn);
/** Callback for reconnect timer */
static void reconnect_cb(evutil_socket_t fd, short what, void *arg);
};
TorController::TorController(struct event_base* baseIn, const std::string& target):
base(baseIn),
target(target), conn(base), reconnect(true), reconnect_ev(0),
reconnect_timeout(RECONNECT_TIMEOUT_START)
{
reconnect_ev = event_new(base, -1, 0, reconnect_cb, this);
if (!reconnect_ev)
LogPrintf("tor: Failed to create event for reconnection: out of memory?\n");
// Start connection attempts immediately
if (!conn.Connect(target, boost::bind(&TorController::connected_cb, this, _1),
boost::bind(&TorController::disconnected_cb, this, _1) )) {
LogPrintf("tor: Initiating connection to Tor control port %s failed\n", target);
}
// Read service private key if cached
std::pair<bool,std::string> pkf = ReadBinaryFile(GetPrivateKeyFile());
if (pkf.first) {
LogPrint("tor", "tor: Reading cached private key from %s\n", GetPrivateKeyFile());
private_key = pkf.second;
}
}
TorController::~TorController()
{
if (reconnect_ev) {
event_free(reconnect_ev);
reconnect_ev = 0;
}
if (service.IsValid()) {
RemoveLocal(service);
}
}
void TorController::add_onion_cb(TorControlConnection& conn, const TorControlReply& reply)
{
if (reply.code == 250) {
LogPrint("tor", "tor: ADD_ONION successful\n");
BOOST_FOREACH(const std::string &s, reply.lines) {
std::map<std::string,std::string> m = ParseTorReplyMapping(s);
std::map<std::string,std::string>::iterator i;
if ((i = m.find("ServiceID")) != m.end())
service_id = i->second;
if ((i = m.find("PrivateKey")) != m.end())
private_key = i->second;
}
if (service_id.empty()) {
LogPrintf("tor: Error parsing ADD_ONION parameters:\n");
for (const std::string &s : reply.lines) {
LogPrintf(" %s\n", SanitizeString(s));
}
return;
}
service = CService(service_id+".onion", GetListenPort(), false);
LogPrintf("tor: Got service ID %s, advertizing service %s\n", service_id, service.ToString());
if (WriteBinaryFile(GetPrivateKeyFile(), private_key)) {
LogPrint("tor", "tor: Cached service private key to %s\n", GetPrivateKeyFile());
} else {
LogPrintf("tor: Error writing service private key to %s\n", GetPrivateKeyFile());
}
AddLocal(service, LOCAL_MANUAL);
// ... onion requested - keep connection open
} else if (reply.code == 510) { // 510 Unrecognized command
LogPrintf("tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)\n");
} else {
LogPrintf("tor: Add onion failed; error code %d\n", reply.code);
}
}
void TorController::auth_cb(TorControlConnection& conn, const TorControlReply& reply)
{
if (reply.code == 250) {
LogPrint("tor", "tor: Authentication successful\n");
// Now that we know Tor is running setup the proxy for onion addresses
// if -onion isn't set to something else.
if (GetArg("-onion", "") == "") {
proxyType addrOnion = proxyType(CService("127.0.0.1", 9050), true);
SetProxy(NET_ONION, addrOnion);
SetLimited(NET_ONION, false);
}
// Finally - now create the service
if (private_key.empty()) // No private key, generate one
private_key = "NEW:RSA1024"; // Explicitly request RSA1024 - see issue #9214
// Request hidden service, redirect port.
// Note that the 'virtual' port doesn't have to be the same as our internal port, but this is just a convenient
// choice. TODO; refactor the shutdown sequence some day.
conn.Command(strprintf("ADD_ONION %s Port=%i,127.0.0.1:%i", private_key, GetListenPort(), GetListenPort()),
boost::bind(&TorController::add_onion_cb, this, _1, _2));
} else {
LogPrintf("tor: Authentication failed\n");
}
}
/** Compute Tor SAFECOOKIE response.
*
* ServerHash is computed as:
* HMAC-SHA256("Tor safe cookie authentication server-to-controller hash",
* CookieString | ClientNonce | ServerNonce)
* (with the HMAC key as its first argument)
*
* After a controller sends a successful AUTHCHALLENGE command, the
* next command sent on the connection must be an AUTHENTICATE command,
* and the only authentication string which that AUTHENTICATE command
* will accept is:
*
* HMAC-SHA256("Tor safe cookie authentication controller-to-server hash",
* CookieString | ClientNonce | ServerNonce)
*
*/
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)
{
CHMAC_SHA256 computeHash((const uint8_t*)key.data(), key.size());
std::vector<uint8_t> computedHash(CHMAC_SHA256::OUTPUT_SIZE, 0);
computeHash.Write(begin_ptr(cookie), cookie.size());
computeHash.Write(begin_ptr(clientNonce), clientNonce.size());
computeHash.Write(begin_ptr(serverNonce), serverNonce.size());
computeHash.Finalize(begin_ptr(computedHash));
return computedHash;
}
void TorController::authchallenge_cb(TorControlConnection& conn, const TorControlReply& reply)
{
if (reply.code == 250) {
LogPrint("tor", "tor: SAFECOOKIE authentication challenge successful\n");
std::pair<std::string,std::string> l = SplitTorReplyLine(reply.lines[0]);
if (l.first == "AUTHCHALLENGE") {
std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
if (m.empty()) {
LogPrintf("tor: Error parsing AUTHCHALLENGE parameters: %s\n", SanitizeString(l.second));
return;
}
std::vector<uint8_t> serverHash = ParseHex(m["SERVERHASH"]);
std::vector<uint8_t> serverNonce = ParseHex(m["SERVERNONCE"]);
LogPrint("tor", "tor: AUTHCHALLENGE ServerHash %s ServerNonce %s\n", HexStr(serverHash), HexStr(serverNonce));
if (serverNonce.size() != 32) {
LogPrintf("tor: ServerNonce is not 32 bytes, as required by spec\n");
return;
}
std::vector<uint8_t> computedServerHash = ComputeResponse(TOR_SAFE_SERVERKEY, cookie, clientNonce, serverNonce);
if (computedServerHash != serverHash) {
LogPrintf("tor: ServerHash %s does not match expected ServerHash %s\n", HexStr(serverHash), HexStr(computedServerHash));
return;
}
std::vector<uint8_t> computedClientHash = ComputeResponse(TOR_SAFE_CLIENTKEY, cookie, clientNonce, serverNonce);
conn.Command("AUTHENTICATE " + HexStr(computedClientHash), boost::bind(&TorController::auth_cb, this, _1, _2));
} else {
LogPrintf("tor: Invalid reply to AUTHCHALLENGE\n");
}
} else {
LogPrintf("tor: SAFECOOKIE authentication challenge failed\n");
}
}
void TorController::protocolinfo_cb(TorControlConnection& conn, const TorControlReply& reply)
{
if (reply.code == 250) {
std::set<std::string> methods;
std::string cookiefile;
/*
* 250-AUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE="/home/x/.tor/control_auth_cookie"
* 250-AUTH METHODS=NULL
* 250-AUTH METHODS=HASHEDPASSWORD
*/
BOOST_FOREACH(const std::string &s, reply.lines) {
std::pair<std::string,std::string> l = SplitTorReplyLine(s);
if (l.first == "AUTH") {
std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
std::map<std::string,std::string>::iterator i;
if ((i = m.find("METHODS")) != m.end())
boost::split(methods, i->second, boost::is_any_of(","));
if ((i = m.find("COOKIEFILE")) != m.end())
cookiefile = i->second;
} else if (l.first == "VERSION") {
std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
std::map<std::string,std::string>::iterator i;
if ((i = m.find("Tor")) != m.end()) {
LogPrint("tor", "tor: Connected to Tor version %s\n", i->second);
}
}
}
BOOST_FOREACH(const std::string &s, methods) {
LogPrint("tor", "tor: Supported authentication method: %s\n", s);
}
// Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD
/* Authentication:
* cookie: hex-encoded ~/.tor/control_auth_cookie
* password: "password"
*/
std::string torpassword = GetArg("-torpassword", "");
if (!torpassword.empty()) {
if (methods.count("HASHEDPASSWORD")) {
LogPrint("tor", "tor: Using HASHEDPASSWORD authentication\n");
boost::replace_all(torpassword, "\"", "\\\"");
conn.Command("AUTHENTICATE \"" + torpassword + "\"", boost::bind(&TorController::auth_cb, this, _1, _2));
} else {
LogPrintf("tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available\n");
}
} else if (methods.count("NULL")) {
LogPrint("tor", "tor: Using NULL authentication\n");
conn.Command("AUTHENTICATE", boost::bind(&TorController::auth_cb, this, _1, _2));
} else if (methods.count("SAFECOOKIE")) {
// Cookie: hexdump -e '32/1 "%02x""\n"' ~/.tor/control_auth_cookie
LogPrint("tor", "tor: Using SAFECOOKIE authentication, reading cookie authentication from %s\n", cookiefile);
std::pair<bool,std::string> status_cookie = ReadBinaryFile(cookiefile, TOR_COOKIE_SIZE);
if (status_cookie.first && status_cookie.second.size() == TOR_COOKIE_SIZE) {
// conn.Command("AUTHENTICATE " + HexStr(status_cookie.second), boost::bind(&TorController::auth_cb, this, _1, _2));
cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
GetRandBytes(&clientNonce[0], TOR_NONCE_SIZE);
conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(clientNonce), boost::bind(&TorController::authchallenge_cb, this, _1, _2));
} else {
if (status_cookie.first) {
LogPrintf("tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec\n", cookiefile, TOR_COOKIE_SIZE);
} else {
LogPrintf("tor: Authentication cookie %s could not be opened (check permissions)\n", cookiefile);
}
}
} else if (methods.count("HASHEDPASSWORD")) {
LogPrintf("tor: The only supported authentication mechanism left is password, but no password provided with -torpassword\n");
} else {
LogPrintf("tor: No supported authentication method\n");
}
} else {
LogPrintf("tor: Requesting protocol info failed\n");
}
}
void TorController::connected_cb(TorControlConnection& conn)
{
reconnect_timeout = RECONNECT_TIMEOUT_START;
// First send a PROTOCOLINFO command to figure out what authentication is expected
if (!conn.Command("PROTOCOLINFO 1", boost::bind(&TorController::protocolinfo_cb, this, _1, _2)))
LogPrintf("tor: Error sending initial protocolinfo command\n");
}
void TorController::disconnected_cb(TorControlConnection& conn)
{
// Stop advertizing service when disconnected
if (service.IsValid())
RemoveLocal(service);
service = CService();
if (!reconnect)
return;
LogPrint("tor", "tor: Not connected to Tor control port %s, trying to reconnect\n", target);
// Single-shot timer for reconnect. Use exponential backoff.
struct timeval time = MillisToTimeval(int64_t(reconnect_timeout * 1000.0));
if (reconnect_ev)
event_add(reconnect_ev, &time);
reconnect_timeout *= RECONNECT_TIMEOUT_EXP;
}
void TorController::Reconnect()
{
/* Try to reconnect and reestablish if we get booted - for example, Tor
* may be restarting.
*/
if (!conn.Connect(target, boost::bind(&TorController::connected_cb, this, _1),
boost::bind(&TorController::disconnected_cb, this, _1) )) {
LogPrintf("tor: Re-initiating connection to Tor control port %s failed\n", target);
}
}
std::string TorController::GetPrivateKeyFile()
{
return (GetDataDir() / "onion_private_key").string();
}
void TorController::reconnect_cb(evutil_socket_t fd, short what, void *arg)
{
TorController *self = (TorController*)arg;
self->Reconnect();
}
/****** Thread ********/
static struct event_base *gBase;
static boost::thread torControlThread;
static void TorControlThread()
{
TorController ctrl(gBase, GetArg("-torcontrol", DEFAULT_TOR_CONTROL));
event_base_dispatch(gBase);
}
void StartTorControl(boost::thread_group& threadGroup, CScheduler& scheduler)
{
assert(!gBase);
#ifdef WIN32
evthread_use_windows_threads();
#else
evthread_use_pthreads();
#endif
gBase = event_base_new();
if (!gBase) {
LogPrintf("tor: Unable to create event_base\n");
return;
}
torControlThread = boost::thread(boost::bind(&TraceThread<void (*)()>, "torcontrol", &TorControlThread));
}
void InterruptTorControl()
{
if (gBase) {
LogPrintf("tor: Thread interrupt\n");
event_base_loopbreak(gBase);
}
}
void StopTorControl()
{
if (gBase) {
torControlThread.join();
event_base_free(gBase);
gBase = 0;
}
}