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.

torcontrol.cpp 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  1. // Copyright (c) 2015-2016 The Starwels developers
  2. // Copyright (c) 2017 The Zcash developers
  3. // Distributed under the MIT software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #include "torcontrol.h"
  6. #include "utilstrencodings.h"
  7. #include "netbase.h"
  8. #include "net.h"
  9. #include "util.h"
  10. #include "crypto/hmac_sha256.h"
  11. #include <vector>
  12. #include <deque>
  13. #include <set>
  14. #include <stdlib.h>
  15. #include <boost/bind.hpp>
  16. #include <boost/signals2/signal.hpp>
  17. #include <boost/algorithm/string/split.hpp>
  18. #include <boost/algorithm/string/classification.hpp>
  19. #include <boost/algorithm/string/replace.hpp>
  20. #include <event2/bufferevent.h>
  21. #include <event2/buffer.h>
  22. #include <event2/util.h>
  23. #include <event2/event.h>
  24. #include <event2/thread.h>
  25. /** Default control port */
  26. const std::string DEFAULT_TOR_CONTROL = "127.0.0.1:9051";
  27. /** Tor cookie size (from control-spec.txt) */
  28. static const int TOR_COOKIE_SIZE = 32;
  29. /** Size of client/server nonce for SAFECOOKIE */
  30. static const int TOR_NONCE_SIZE = 32;
  31. /** For computing serverHash in SAFECOOKIE */
  32. static const std::string TOR_SAFE_SERVERKEY = "Tor safe cookie authentication server-to-controller hash";
  33. /** For computing clientHash in SAFECOOKIE */
  34. static const std::string TOR_SAFE_CLIENTKEY = "Tor safe cookie authentication controller-to-server hash";
  35. /** Exponential backoff configuration - initial timeout in seconds */
  36. static const float RECONNECT_TIMEOUT_START = 1.0;
  37. /** Exponential backoff configuration - growth factor */
  38. static const float RECONNECT_TIMEOUT_EXP = 1.5;
  39. /** Maximum length for lines received on TorControlConnection.
  40. * tor-control-spec.txt mentions that there is explicitly no limit defined to line length,
  41. * this is belt-and-suspenders sanity limit to prevent memory exhaustion.
  42. */
  43. static const int MAX_LINE_LENGTH = 100000;
  44. /****** Low-level TorControlConnection ********/
  45. /** Reply from Tor, can be single or multi-line */
  46. class TorControlReply
  47. {
  48. public:
  49. TorControlReply() { Clear(); }
  50. int code;
  51. std::vector<std::string> lines;
  52. void Clear()
  53. {
  54. code = 0;
  55. lines.clear();
  56. }
  57. };
  58. /** Low-level handling for Tor control connection.
  59. * Speaks the SMTP-like protocol as defined in torspec/control-spec.txt
  60. */
  61. class TorControlConnection
  62. {
  63. public:
  64. typedef std::function<void(TorControlConnection&)> ConnectionCB;
  65. typedef std::function<void(TorControlConnection &,const TorControlReply &)> ReplyHandlerCB;
  66. /** Create a new TorControlConnection.
  67. */
  68. TorControlConnection(struct event_base *base);
  69. ~TorControlConnection();
  70. /**
  71. * Connect to a Tor control port.
  72. * target is address of the form host:port.
  73. * connected is the handler that is called when connection is successfully established.
  74. * disconnected is a handler that is called when the connection is broken.
  75. * Return true on success.
  76. */
  77. bool Connect(const std::string &target, const ConnectionCB& connected, const ConnectionCB& disconnected);
  78. /**
  79. * Disconnect from Tor control port.
  80. */
  81. bool Disconnect();
  82. /** Send a command, register a handler for the reply.
  83. * A trailing CRLF is automatically added.
  84. * Return true on success.
  85. */
  86. bool Command(const std::string &cmd, const ReplyHandlerCB& reply_handler);
  87. /** Response handlers for async replies */
  88. boost::signals2::signal<void(TorControlConnection &,const TorControlReply &)> async_handler;
  89. private:
  90. /** Callback when ready for use */
  91. std::function<void(TorControlConnection&)> connected;
  92. /** Callback when connection lost */
  93. std::function<void(TorControlConnection&)> disconnected;
  94. /** Libevent event base */
  95. struct event_base *base;
  96. /** Connection to control socket */
  97. struct bufferevent *b_conn;
  98. /** Message being received */
  99. TorControlReply message;
  100. /** Response handlers */
  101. std::deque<ReplyHandlerCB> reply_handlers;
  102. /** Libevent handlers: internal */
  103. static void readcb(struct bufferevent *bev, void *ctx);
  104. static void eventcb(struct bufferevent *bev, short what, void *ctx);
  105. };
  106. TorControlConnection::TorControlConnection(struct event_base *_base):
  107. base(_base), b_conn(0)
  108. {
  109. }
  110. TorControlConnection::~TorControlConnection()
  111. {
  112. if (b_conn)
  113. bufferevent_free(b_conn);
  114. }
  115. void TorControlConnection::readcb(struct bufferevent *bev, void *ctx)
  116. {
  117. TorControlConnection *self = (TorControlConnection*)ctx;
  118. struct evbuffer *input = bufferevent_get_input(bev);
  119. size_t n_read_out = 0;
  120. char *line;
  121. assert(input);
  122. // If there is not a whole line to read, evbuffer_readln returns nullptr
  123. while((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) != nullptr)
  124. {
  125. std::string s(line, n_read_out);
  126. free(line);
  127. if (s.size() < 4) // Short line
  128. continue;
  129. // <status>(-|+| )<data><CRLF>
  130. self->message.code = atoi(s.substr(0,3));
  131. self->message.lines.push_back(s.substr(4));
  132. char ch = s[3]; // '-','+' or ' '
  133. if (ch == ' ') {
  134. // Final line, dispatch reply and clean up
  135. if (self->message.code >= 600) {
  136. // Dispatch async notifications to async handler
  137. // Synchronous and asynchronous messages are never interleaved
  138. self->async_handler(*self, self->message);
  139. } else {
  140. if (!self->reply_handlers.empty()) {
  141. // Invoke reply handler with message
  142. self->reply_handlers.front()(*self, self->message);
  143. self->reply_handlers.pop_front();
  144. } else {
  145. LogPrint(BCLog::TOR, "tor: Received unexpected sync reply %i\n", self->message.code);
  146. }
  147. }
  148. self->message.Clear();
  149. }
  150. }
  151. // Check for size of buffer - protect against memory exhaustion with very long lines
  152. // Do this after evbuffer_readln to make sure all full lines have been
  153. // removed from the buffer. Everything left is an incomplete line.
  154. if (evbuffer_get_length(input) > MAX_LINE_LENGTH) {
  155. LogPrintf("tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
  156. self->Disconnect();
  157. }
  158. }
  159. void TorControlConnection::eventcb(struct bufferevent *bev, short what, void *ctx)
  160. {
  161. TorControlConnection *self = (TorControlConnection*)ctx;
  162. if (what & BEV_EVENT_CONNECTED) {
  163. LogPrint(BCLog::TOR, "tor: Successfully connected!\n");
  164. self->connected(*self);
  165. } else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
  166. if (what & BEV_EVENT_ERROR) {
  167. LogPrint(BCLog::TOR, "tor: Error connecting to Tor control socket\n");
  168. } else {
  169. LogPrint(BCLog::TOR, "tor: End of stream\n");
  170. }
  171. self->Disconnect();
  172. self->disconnected(*self);
  173. }
  174. }
  175. bool TorControlConnection::Connect(const std::string &target, const ConnectionCB& _connected, const ConnectionCB& _disconnected)
  176. {
  177. if (b_conn)
  178. Disconnect();
  179. // Parse target address:port
  180. struct sockaddr_storage connect_to_addr;
  181. int connect_to_addrlen = sizeof(connect_to_addr);
  182. if (evutil_parse_sockaddr_port(target.c_str(),
  183. (struct sockaddr*)&connect_to_addr, &connect_to_addrlen)<0) {
  184. LogPrintf("tor: Error parsing socket address %s\n", target);
  185. return false;
  186. }
  187. // Create a new socket, set up callbacks and enable notification bits
  188. b_conn = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
  189. if (!b_conn)
  190. return false;
  191. bufferevent_setcb(b_conn, TorControlConnection::readcb, nullptr, TorControlConnection::eventcb, this);
  192. bufferevent_enable(b_conn, EV_READ|EV_WRITE);
  193. this->connected = _connected;
  194. this->disconnected = _disconnected;
  195. // Finally, connect to target
  196. if (bufferevent_socket_connect(b_conn, (struct sockaddr*)&connect_to_addr, connect_to_addrlen) < 0) {
  197. LogPrintf("tor: Error connecting to address %s\n", target);
  198. return false;
  199. }
  200. return true;
  201. }
  202. bool TorControlConnection::Disconnect()
  203. {
  204. if (b_conn)
  205. bufferevent_free(b_conn);
  206. b_conn = 0;
  207. return true;
  208. }
  209. bool TorControlConnection::Command(const std::string &cmd, const ReplyHandlerCB& reply_handler)
  210. {
  211. if (!b_conn)
  212. return false;
  213. struct evbuffer *buf = bufferevent_get_output(b_conn);
  214. if (!buf)
  215. return false;
  216. evbuffer_add(buf, cmd.data(), cmd.size());
  217. evbuffer_add(buf, "\r\n", 2);
  218. reply_handlers.push_back(reply_handler);
  219. return true;
  220. }
  221. /****** General parsing utilities ********/
  222. /* Split reply line in the form 'AUTH METHODS=...' into a type
  223. * 'AUTH' and arguments 'METHODS=...'.
  224. * Grammar is implicitly defined in https://spec.torproject.org/control-spec by
  225. * the server reply formats for PROTOCOLINFO (S3.21) and AUTHCHALLENGE (S3.24).
  226. */
  227. static std::pair<std::string,std::string> SplitTorReplyLine(const std::string &s)
  228. {
  229. size_t ptr=0;
  230. std::string type;
  231. while (ptr < s.size() && s[ptr] != ' ') {
  232. type.push_back(s[ptr]);
  233. ++ptr;
  234. }
  235. if (ptr < s.size())
  236. ++ptr; // skip ' '
  237. return make_pair(type, s.substr(ptr));
  238. }
  239. /** Parse reply arguments in the form 'METHODS=COOKIE,SAFECOOKIE COOKIEFILE=".../control_auth_cookie"'.
  240. * Returns a map of keys to values, or an empty map if there was an error.
  241. * Grammar is implicitly defined in https://spec.torproject.org/control-spec by
  242. * the server reply formats for PROTOCOLINFO (S3.21), AUTHCHALLENGE (S3.24),
  243. * and ADD_ONION (S3.27). See also sections 2.1 and 2.3.
  244. */
  245. static std::map<std::string,std::string> ParseTorReplyMapping(const std::string &s)
  246. {
  247. std::map<std::string,std::string> mapping;
  248. size_t ptr=0;
  249. while (ptr < s.size()) {
  250. std::string key, value;
  251. while (ptr < s.size() && s[ptr] != '=' && s[ptr] != ' ') {
  252. key.push_back(s[ptr]);
  253. ++ptr;
  254. }
  255. if (ptr == s.size()) // unexpected end of line
  256. return std::map<std::string,std::string>();
  257. if (s[ptr] == ' ') // The remaining string is an OptArguments
  258. break;
  259. ++ptr; // skip '='
  260. if (ptr < s.size() && s[ptr] == '"') { // Quoted string
  261. ++ptr; // skip opening '"'
  262. bool escape_next = false;
  263. while (ptr < s.size() && (escape_next || s[ptr] != '"')) {
  264. // Repeated backslashes must be interpreted as pairs
  265. escape_next = (s[ptr] == '\\' && !escape_next);
  266. value.push_back(s[ptr]);
  267. ++ptr;
  268. }
  269. if (ptr == s.size()) // unexpected end of line
  270. return std::map<std::string,std::string>();
  271. ++ptr; // skip closing '"'
  272. /**
  273. * Unescape value. Per https://spec.torproject.org/control-spec section 2.1.1:
  274. *
  275. * For future-proofing, controller implementors MAY use the following
  276. * rules to be compatible with buggy Tor implementations and with
  277. * future ones that implement the spec as intended:
  278. *
  279. * Read \n \t \r and \0 ... \377 as C escapes.
  280. * Treat a backslash followed by any other character as that character.
  281. */
  282. std::string escaped_value;
  283. for (size_t i = 0; i < value.size(); ++i) {
  284. if (value[i] == '\\') {
  285. // This will always be valid, because if the QuotedString
  286. // ended in an odd number of backslashes, then the parser
  287. // would already have returned above, due to a missing
  288. // terminating double-quote.
  289. ++i;
  290. if (value[i] == 'n') {
  291. escaped_value.push_back('\n');
  292. } else if (value[i] == 't') {
  293. escaped_value.push_back('\t');
  294. } else if (value[i] == 'r') {
  295. escaped_value.push_back('\r');
  296. } else if ('0' <= value[i] && value[i] <= '7') {
  297. size_t j;
  298. // Octal escape sequences have a limit of three octal digits,
  299. // but terminate at the first character that is not a valid
  300. // octal digit if encountered sooner.
  301. for (j = 1; j < 3 && (i+j) < value.size() && '0' <= value[i+j] && value[i+j] <= '7'; ++j) {}
  302. // Tor restricts first digit to 0-3 for three-digit octals.
  303. // A leading digit of 4-7 would therefore be interpreted as
  304. // a two-digit octal.
  305. if (j == 3 && value[i] > '3') {
  306. j--;
  307. }
  308. escaped_value.push_back(strtol(value.substr(i, j).c_str(), nullptr, 8));
  309. // Account for automatic incrementing at loop end
  310. i += j - 1;
  311. } else {
  312. escaped_value.push_back(value[i]);
  313. }
  314. } else {
  315. escaped_value.push_back(value[i]);
  316. }
  317. }
  318. value = escaped_value;
  319. } else { // Unquoted value. Note that values can contain '=' at will, just no spaces
  320. while (ptr < s.size() && s[ptr] != ' ') {
  321. value.push_back(s[ptr]);
  322. ++ptr;
  323. }
  324. }
  325. if (ptr < s.size() && s[ptr] == ' ')
  326. ++ptr; // skip ' ' after key=value
  327. mapping[key] = value;
  328. }
  329. return mapping;
  330. }
  331. /** Read full contents of a file and return them in a std::string.
  332. * Returns a pair <status, string>.
  333. * If an error occurred, status will be false, otherwise status will be true and the data will be returned in string.
  334. *
  335. * @param maxsize Puts a maximum size limit on the file that is read. If the file is larger than this, truncated data
  336. * (with len > maxsize) will be returned.
  337. */
  338. static std::pair<bool,std::string> ReadBinaryFile(const fs::path &filename, size_t maxsize=std::numeric_limits<size_t>::max())
  339. {
  340. FILE *f = fsbridge::fopen(filename, "rb");
  341. if (f == nullptr)
  342. return std::make_pair(false,"");
  343. std::string retval;
  344. char buffer[128];
  345. size_t n;
  346. while ((n=fread(buffer, 1, sizeof(buffer), f)) > 0) {
  347. // Check for reading errors so we don't return any data if we couldn't
  348. // read the entire file (or up to maxsize)
  349. if (ferror(f)) {
  350. fclose(f);
  351. return std::make_pair(false,"");
  352. }
  353. retval.append(buffer, buffer+n);
  354. if (retval.size() > maxsize)
  355. break;
  356. }
  357. fclose(f);
  358. return std::make_pair(true,retval);
  359. }
  360. /** Write contents of std::string to a file.
  361. * @return true on success.
  362. */
  363. static bool WriteBinaryFile(const fs::path &filename, const std::string &data)
  364. {
  365. FILE *f = fsbridge::fopen(filename, "wb");
  366. if (f == nullptr)
  367. return false;
  368. if (fwrite(data.data(), 1, data.size(), f) != data.size()) {
  369. fclose(f);
  370. return false;
  371. }
  372. fclose(f);
  373. return true;
  374. }
  375. /****** Starwels specific TorController implementation ********/
  376. /** Controller that connects to Tor control socket, authenticate, then create
  377. * and maintain an ephemeral hidden service.
  378. */
  379. class TorController
  380. {
  381. public:
  382. TorController(struct event_base* base, const std::string& target);
  383. ~TorController();
  384. /** Get name fo file to store private key in */
  385. fs::path GetPrivateKeyFile();
  386. /** Reconnect, after getting disconnected */
  387. void Reconnect();
  388. private:
  389. struct event_base* base;
  390. std::string target;
  391. TorControlConnection conn;
  392. std::string private_key;
  393. std::string service_id;
  394. bool reconnect;
  395. struct event *reconnect_ev;
  396. float reconnect_timeout;
  397. CService service;
  398. /** Cookie for SAFECOOKIE auth */
  399. std::vector<uint8_t> cookie;
  400. /** ClientNonce for SAFECOOKIE auth */
  401. std::vector<uint8_t> clientNonce;
  402. /** Callback for ADD_ONION result */
  403. void add_onion_cb(TorControlConnection& conn, const TorControlReply& reply);
  404. /** Callback for AUTHENTICATE result */
  405. void auth_cb(TorControlConnection& conn, const TorControlReply& reply);
  406. /** Callback for AUTHCHALLENGE result */
  407. void authchallenge_cb(TorControlConnection& conn, const TorControlReply& reply);
  408. /** Callback for PROTOCOLINFO result */
  409. void protocolinfo_cb(TorControlConnection& conn, const TorControlReply& reply);
  410. /** Callback after successful connection */
  411. void connected_cb(TorControlConnection& conn);
  412. /** Callback after connection lost or failed connection attempt */
  413. void disconnected_cb(TorControlConnection& conn);
  414. /** Callback for reconnect timer */
  415. static void reconnect_cb(evutil_socket_t fd, short what, void *arg);
  416. };
  417. TorController::TorController(struct event_base* _base, const std::string& _target):
  418. base(_base),
  419. target(_target), conn(base), reconnect(true), reconnect_ev(0),
  420. reconnect_timeout(RECONNECT_TIMEOUT_START)
  421. {
  422. reconnect_ev = event_new(base, -1, 0, reconnect_cb, this);
  423. if (!reconnect_ev)
  424. LogPrintf("tor: Failed to create event for reconnection: out of memory?\n");
  425. // Start connection attempts immediately
  426. if (!conn.Connect(_target, boost::bind(&TorController::connected_cb, this, _1),
  427. boost::bind(&TorController::disconnected_cb, this, _1) )) {
  428. LogPrintf("tor: Initiating connection to Tor control port %s failed\n", _target);
  429. }
  430. // Read service private key if cached
  431. std::pair<bool,std::string> pkf = ReadBinaryFile(GetPrivateKeyFile());
  432. if (pkf.first) {
  433. LogPrint(BCLog::TOR, "tor: Reading cached private key from %s\n", GetPrivateKeyFile().string());
  434. private_key = pkf.second;
  435. }
  436. }
  437. TorController::~TorController()
  438. {
  439. if (reconnect_ev) {
  440. event_free(reconnect_ev);
  441. reconnect_ev = 0;
  442. }
  443. if (service.IsValid()) {
  444. RemoveLocal(service);
  445. }
  446. }
  447. void TorController::add_onion_cb(TorControlConnection& _conn, const TorControlReply& reply)
  448. {
  449. if (reply.code == 250) {
  450. LogPrint(BCLog::TOR, "tor: ADD_ONION successful\n");
  451. for (const std::string &s : reply.lines) {
  452. std::map<std::string,std::string> m = ParseTorReplyMapping(s);
  453. std::map<std::string,std::string>::iterator i;
  454. if ((i = m.find("ServiceID")) != m.end())
  455. service_id = i->second;
  456. if ((i = m.find("PrivateKey")) != m.end())
  457. private_key = i->second;
  458. }
  459. if (service_id.empty()) {
  460. LogPrintf("tor: Error parsing ADD_ONION parameters:\n");
  461. for (const std::string &s : reply.lines) {
  462. LogPrintf(" %s\n", SanitizeString(s));
  463. }
  464. return;
  465. }
  466. service = LookupNumeric(std::string(service_id+".onion").c_str(), GetListenPort());
  467. LogPrintf("tor: Got service ID %s, advertising service %s\n", service_id, service.ToString());
  468. if (WriteBinaryFile(GetPrivateKeyFile(), private_key)) {
  469. LogPrint(BCLog::TOR, "tor: Cached service private key to %s\n", GetPrivateKeyFile().string());
  470. } else {
  471. LogPrintf("tor: Error writing service private key to %s\n", GetPrivateKeyFile().string());
  472. }
  473. AddLocal(service, LOCAL_MANUAL);
  474. // ... onion requested - keep connection open
  475. } else if (reply.code == 510) { // 510 Unrecognized command
  476. LogPrintf("tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)\n");
  477. } else {
  478. LogPrintf("tor: Add onion failed; error code %d\n", reply.code);
  479. }
  480. }
  481. void TorController::auth_cb(TorControlConnection& _conn, const TorControlReply& reply)
  482. {
  483. if (reply.code == 250) {
  484. LogPrint(BCLog::TOR, "tor: Authentication successful\n");
  485. // Now that we know Tor is running setup the proxy for onion addresses
  486. // if -onion isn't set to something else.
  487. if (gArgs.GetArg("-onion", "") == "") {
  488. CService resolved(LookupNumeric("127.0.0.1", 9050));
  489. proxyType addrOnion = proxyType(resolved, true);
  490. SetProxy(NET_TOR, addrOnion);
  491. SetLimited(NET_TOR, false);
  492. }
  493. // Finally - now create the service
  494. if (private_key.empty()) // No private key, generate one
  495. private_key = "NEW:RSA1024"; // Explicitly request RSA1024 - see issue #9214
  496. // Request hidden service, redirect port.
  497. // Note that the 'virtual' port doesn't have to be the same as our internal port, but this is just a convenient
  498. // choice. TODO; refactor the shutdown sequence some day.
  499. _conn.Command(strprintf("ADD_ONION %s Port=%i,127.0.0.1:%i", private_key, GetListenPort(), GetListenPort()),
  500. boost::bind(&TorController::add_onion_cb, this, _1, _2));
  501. } else {
  502. LogPrintf("tor: Authentication failed\n");
  503. }
  504. }
  505. /** Compute Tor SAFECOOKIE response.
  506. *
  507. * ServerHash is computed as:
  508. * HMAC-SHA256("Tor safe cookie authentication server-to-controller hash",
  509. * CookieString | ClientNonce | ServerNonce)
  510. * (with the HMAC key as its first argument)
  511. *
  512. * After a controller sends a successful AUTHCHALLENGE command, the
  513. * next command sent on the connection must be an AUTHENTICATE command,
  514. * and the only authentication string which that AUTHENTICATE command
  515. * will accept is:
  516. *
  517. * HMAC-SHA256("Tor safe cookie authentication controller-to-server hash",
  518. * CookieString | ClientNonce | ServerNonce)
  519. *
  520. */
  521. 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)
  522. {
  523. CHMAC_SHA256 computeHash((const uint8_t*)key.data(), key.size());
  524. std::vector<uint8_t> computedHash(CHMAC_SHA256::OUTPUT_SIZE, 0);
  525. computeHash.Write(cookie.data(), cookie.size());
  526. computeHash.Write(clientNonce.data(), clientNonce.size());
  527. computeHash.Write(serverNonce.data(), serverNonce.size());
  528. computeHash.Finalize(computedHash.data());
  529. return computedHash;
  530. }
  531. void TorController::authchallenge_cb(TorControlConnection& _conn, const TorControlReply& reply)
  532. {
  533. if (reply.code == 250) {
  534. LogPrint(BCLog::TOR, "tor: SAFECOOKIE authentication challenge successful\n");
  535. std::pair<std::string,std::string> l = SplitTorReplyLine(reply.lines[0]);
  536. if (l.first == "AUTHCHALLENGE") {
  537. std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
  538. if (m.empty()) {
  539. LogPrintf("tor: Error parsing AUTHCHALLENGE parameters: %s\n", SanitizeString(l.second));
  540. return;
  541. }
  542. std::vector<uint8_t> serverHash = ParseHex(m["SERVERHASH"]);
  543. std::vector<uint8_t> serverNonce = ParseHex(m["SERVERNONCE"]);
  544. LogPrint(BCLog::TOR, "tor: AUTHCHALLENGE ServerHash %s ServerNonce %s\n", HexStr(serverHash), HexStr(serverNonce));
  545. if (serverNonce.size() != 32) {
  546. LogPrintf("tor: ServerNonce is not 32 bytes, as required by spec\n");
  547. return;
  548. }
  549. std::vector<uint8_t> computedServerHash = ComputeResponse(TOR_SAFE_SERVERKEY, cookie, clientNonce, serverNonce);
  550. if (computedServerHash != serverHash) {
  551. LogPrintf("tor: ServerHash %s does not match expected ServerHash %s\n", HexStr(serverHash), HexStr(computedServerHash));
  552. return;
  553. }
  554. std::vector<uint8_t> computedClientHash = ComputeResponse(TOR_SAFE_CLIENTKEY, cookie, clientNonce, serverNonce);
  555. _conn.Command("AUTHENTICATE " + HexStr(computedClientHash), boost::bind(&TorController::auth_cb, this, _1, _2));
  556. } else {
  557. LogPrintf("tor: Invalid reply to AUTHCHALLENGE\n");
  558. }
  559. } else {
  560. LogPrintf("tor: SAFECOOKIE authentication challenge failed\n");
  561. }
  562. }
  563. void TorController::protocolinfo_cb(TorControlConnection& _conn, const TorControlReply& reply)
  564. {
  565. if (reply.code == 250) {
  566. std::set<std::string> methods;
  567. std::string cookiefile;
  568. /*
  569. * 250-AUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE="/home/x/.tor/control_auth_cookie"
  570. * 250-AUTH METHODS=NULL
  571. * 250-AUTH METHODS=HASHEDPASSWORD
  572. */
  573. for (const std::string &s : reply.lines) {
  574. std::pair<std::string,std::string> l = SplitTorReplyLine(s);
  575. if (l.first == "AUTH") {
  576. std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
  577. std::map<std::string,std::string>::iterator i;
  578. if ((i = m.find("METHODS")) != m.end())
  579. boost::split(methods, i->second, boost::is_any_of(","));
  580. if ((i = m.find("COOKIEFILE")) != m.end())
  581. cookiefile = i->second;
  582. } else if (l.first == "VERSION") {
  583. std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
  584. std::map<std::string,std::string>::iterator i;
  585. if ((i = m.find("Tor")) != m.end()) {
  586. LogPrint(BCLog::TOR, "tor: Connected to Tor version %s\n", i->second);
  587. }
  588. }
  589. }
  590. for (const std::string &s : methods) {
  591. LogPrint(BCLog::TOR, "tor: Supported authentication method: %s\n", s);
  592. }
  593. // Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD
  594. /* Authentication:
  595. * cookie: hex-encoded ~/.tor/control_auth_cookie
  596. * password: "password"
  597. */
  598. std::string torpassword = gArgs.GetArg("-torpassword", "");
  599. if (!torpassword.empty()) {
  600. if (methods.count("HASHEDPASSWORD")) {
  601. LogPrint(BCLog::TOR, "tor: Using HASHEDPASSWORD authentication\n");
  602. boost::replace_all(torpassword, "\"", "\\\"");
  603. _conn.Command("AUTHENTICATE \"" + torpassword + "\"", boost::bind(&TorController::auth_cb, this, _1, _2));
  604. } else {
  605. LogPrintf("tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available\n");
  606. }
  607. } else if (methods.count("NULL")) {
  608. LogPrint(BCLog::TOR, "tor: Using NULL authentication\n");
  609. _conn.Command("AUTHENTICATE", boost::bind(&TorController::auth_cb, this, _1, _2));
  610. } else if (methods.count("SAFECOOKIE")) {
  611. // Cookie: hexdump -e '32/1 "%02x""\n"' ~/.tor/control_auth_cookie
  612. LogPrint(BCLog::TOR, "tor: Using SAFECOOKIE authentication, reading cookie authentication from %s\n", cookiefile);
  613. std::pair<bool,std::string> status_cookie = ReadBinaryFile(cookiefile, TOR_COOKIE_SIZE);
  614. if (status_cookie.first && status_cookie.second.size() == TOR_COOKIE_SIZE) {
  615. // _conn.Command("AUTHENTICATE " + HexStr(status_cookie.second), boost::bind(&TorController::auth_cb, this, _1, _2));
  616. cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
  617. clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
  618. GetRandBytes(clientNonce.data(), TOR_NONCE_SIZE);
  619. _conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(clientNonce), boost::bind(&TorController::authchallenge_cb, this, _1, _2));
  620. } else {
  621. if (status_cookie.first) {
  622. LogPrintf("tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec\n", cookiefile, TOR_COOKIE_SIZE);
  623. } else {
  624. LogPrintf("tor: Authentication cookie %s could not be opened (check permissions)\n", cookiefile);
  625. }
  626. }
  627. } else if (methods.count("HASHEDPASSWORD")) {
  628. LogPrintf("tor: The only supported authentication mechanism left is password, but no password provided with -torpassword\n");
  629. } else {
  630. LogPrintf("tor: No supported authentication method\n");
  631. }
  632. } else {
  633. LogPrintf("tor: Requesting protocol info failed\n");
  634. }
  635. }
  636. void TorController::connected_cb(TorControlConnection& _conn)
  637. {
  638. reconnect_timeout = RECONNECT_TIMEOUT_START;
  639. // First send a PROTOCOLINFO command to figure out what authentication is expected
  640. if (!_conn.Command("PROTOCOLINFO 1", boost::bind(&TorController::protocolinfo_cb, this, _1, _2)))
  641. LogPrintf("tor: Error sending initial protocolinfo command\n");
  642. }
  643. void TorController::disconnected_cb(TorControlConnection& _conn)
  644. {
  645. // Stop advertising service when disconnected
  646. if (service.IsValid())
  647. RemoveLocal(service);
  648. service = CService();
  649. if (!reconnect)
  650. return;
  651. LogPrint(BCLog::TOR, "tor: Not connected to Tor control port %s, trying to reconnect\n", target);
  652. // Single-shot timer for reconnect. Use exponential backoff.
  653. struct timeval time = MillisToTimeval(int64_t(reconnect_timeout * 1000.0));
  654. if (reconnect_ev)
  655. event_add(reconnect_ev, &time);
  656. reconnect_timeout *= RECONNECT_TIMEOUT_EXP;
  657. }
  658. void TorController::Reconnect()
  659. {
  660. /* Try to reconnect and reestablish if we get booted - for example, Tor
  661. * may be restarting.
  662. */
  663. if (!conn.Connect(target, boost::bind(&TorController::connected_cb, this, _1),
  664. boost::bind(&TorController::disconnected_cb, this, _1) )) {
  665. LogPrintf("tor: Re-initiating connection to Tor control port %s failed\n", target);
  666. }
  667. }
  668. fs::path TorController::GetPrivateKeyFile()
  669. {
  670. return GetDataDir() / "onion_private_key";
  671. }
  672. void TorController::reconnect_cb(evutil_socket_t fd, short what, void *arg)
  673. {
  674. TorController *self = (TorController*)arg;
  675. self->Reconnect();
  676. }
  677. /****** Thread ********/
  678. static struct event_base *gBase;
  679. static boost::thread torControlThread;
  680. static void TorControlThread()
  681. {
  682. TorController ctrl(gBase, gArgs.GetArg("-torcontrol", DEFAULT_TOR_CONTROL));
  683. event_base_dispatch(gBase);
  684. }
  685. void StartTorControl(boost::thread_group& threadGroup, CScheduler& scheduler)
  686. {
  687. assert(!gBase);
  688. #ifdef WIN32
  689. evthread_use_windows_threads();
  690. #else
  691. evthread_use_pthreads();
  692. #endif
  693. gBase = event_base_new();
  694. if (!gBase) {
  695. LogPrintf("tor: Unable to create event_base\n");
  696. return;
  697. }
  698. torControlThread = boost::thread(boost::bind(&TraceThread<void (*)()>, "torcontrol", &TorControlThread));
  699. }
  700. void InterruptTorControl()
  701. {
  702. if (gBase) {
  703. LogPrintf("tor: Thread interrupt\n");
  704. event_base_loopbreak(gBase);
  705. }
  706. }
  707. void StopTorControl()
  708. {
  709. if (gBase) {
  710. torControlThread.join();
  711. event_base_free(gBase);
  712. gBase = 0;
  713. }
  714. }