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 27KB

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