23#include <boost/signals2/signal.hpp>
25#include <event2/buffer.h>
26#include <event2/bufferevent.h>
27#include <event2/event.h>
28#include <event2/thread.h>
29#include <event2/util.h>
45 "Tor safe cookie authentication server-to-controller hash";
48 "Tor safe cookie authentication controller-to-server hash";
165 self->message.code =
atoi(s.substr(0, 3));
166 self->message.lines.push_back(s.substr(4));
171 if (
self->message.code >= 600) {
176 if (!
self->reply_handlers.empty()) {
179 self->reply_handlers.pop_front();
182 "tor: Received unexpected sync reply %i\n",
186 self->message.Clear();
194 LogPrintf(
"tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
208 "tor: Error connecting to Tor control socket\n");
285 while (ptr < s.size() && s[ptr] !=
' ') {
286 type.push_back(s[ptr]);
289 if (ptr < s.size()) {
305 std::map<std::string, std::string>
mapping;
307 while (ptr < s.size()) {
308 std::string key, value;
309 while (ptr < s.size() && s[ptr] !=
'=' && s[ptr] !=
' ') {
310 key.push_back(s[ptr]);
314 if (ptr == s.size()) {
315 return std::map<std::string, std::string>();
324 if (ptr < s.size() && s[ptr] ==
'"') {
328 while (ptr < s.size() && (
escape_next || s[ptr] !=
'"')) {
331 value.push_back(s[ptr]);
335 if (ptr == s.size()) {
336 return std::map<std::string, std::string>();
353 for (
size_t i = 0; i < value.size(); ++i) {
354 if (value[i] ==
'\\') {
360 if (value[i] ==
'n') {
362 }
else if (value[i] ==
't') {
364 }
else if (value[i] ==
'r') {
366 }
else if (
'0' <= value[i] && value[i] <=
'7') {
371 for (
j = 1;
j < 3 && (i +
j) < value.size() &&
372 '0' <= value[i +
j] && value[i +
j] <=
'7';
378 if (
j == 3 && value[i] >
'3') {
396 while (ptr < s.size() && s[ptr] !=
' ') {
397 value.push_back(s[ptr]);
401 if (ptr < s.size() && s[ptr] ==
' ') {
468 reconnect(
true), reconnect_ev(0),
473 "tor: Failed to create event for reconnection: out of memory?\n");
478 std::placeholders::_1),
480 std::placeholders::_1))) {
481 LogPrintf(
"tor: Initiating connection to Tor control port %s failed\n",
505 if (reply.
code == 250) {
507 for (
const std::string &s : reply.
lines) {
509 std::map<std::string, std::string>::iterator i;
510 if ((i = m.find(
"ServiceID")) != m.end()) {
513 if ((i = m.find(
"PrivateKey")) != m.end()) {
518 LogPrintf(
"tor: Error parsing ADD_ONION parameters:\n");
519 for (
const std::string &s : reply.
lines) {
526 LogPrintf(
"tor: Got service ID %s, advertising service %s\n",
532 LogPrintf(
"tor: Error writing service private key to %s\n",
537 }
else if (reply.
code == 510) {
538 LogPrintf(
"tor: Add onion failed with unrecognized command (You "
539 "probably need to upgrade Tor)\n");
541 LogPrintf(
"tor: Add onion failed; error code %d\n", reply.
code);
547 if (reply.
code == 250) {
573 std::placeholders::_1, std::placeholders::_2));
575 LogPrintf(
"tor: Authentication failed\n");
595static std::vector<uint8_t>
597 const std::vector<uint8_t> &clientNonce,
602 computeHash.Write(clientNonce.data(), clientNonce.size());
610 if (reply.
code == 250) {
612 "tor: SAFECOOKIE authentication challenge successful\n");
613 std::pair<std::string, std::string>
l =
615 if (
l.first ==
"AUTHCHALLENGE") {
616 std::map<std::string, std::string> m =
619 LogPrintf(
"tor: Error parsing AUTHCHALLENGE parameters: %s\n",
626 "tor: AUTHCHALLENGE ServerHash %s ServerNonce %s\n",
630 "tor: ServerNonce is not 32 bytes, as required by spec\n");
637 LogPrintf(
"tor: ServerHash %s does not match expected "
647 std::placeholders::_1,
648 std::placeholders::_2));
650 LogPrintf(
"tor: Invalid reply to AUTHCHALLENGE\n");
653 LogPrintf(
"tor: SAFECOOKIE authentication challenge failed\n");
659 if (reply.
code == 250) {
668 for (
const std::string &s : reply.
lines) {
670 if (
l.first ==
"AUTH") {
671 std::map<std::string, std::string> m =
673 std::map<std::string, std::string>::iterator i;
674 if ((i = m.find(
"METHODS")) != m.end()) {
675 std::vector<std::string>
m_vec =
679 if ((i = m.find(
"COOKIEFILE")) != m.end()) {
682 }
else if (
l.first ==
"VERSION") {
683 std::map<std::string, std::string> m =
685 std::map<std::string, std::string>::iterator i;
686 if ((i = m.find(
"Tor")) != m.end()) {
692 for (
const std::string &s :
methods) {
704 if (
methods.count(
"HASHEDPASSWORD")) {
706 "tor: Using HASHEDPASSWORD authentication\n");
710 std::placeholders::_1,
711 std::placeholders::_2));
713 LogPrintf(
"tor: Password provided with -torpassword, but "
714 "HASHEDPASSWORD authentication is not available\n");
716 }
else if (
methods.count(
"NULL")) {
719 this, std::placeholders::_1,
720 std::placeholders::_2));
721 }
else if (
methods.count(
"SAFECOOKIE")) {
724 "tor: Using SAFECOOKIE authentication, "
725 "reading cookie authentication from %s\n",
740 std::placeholders::_1,
741 std::placeholders::_2));
744 LogPrintf(
"tor: Authentication cookie %s is not exactly %i "
745 "bytes, as is required by the spec\n",
748 LogPrintf(
"tor: Authentication cookie %s could not be "
749 "opened (check permissions)\n",
753 }
else if (
methods.count(
"HASHEDPASSWORD")) {
754 LogPrintf(
"tor: The only supported authentication mechanism left "
755 "is password, but no password provided with "
758 LogPrintf(
"tor: No supported authentication method\n");
761 LogPrintf(
"tor: Requesting protocol info failed\n");
769 if (!
_conn.Command(
"PROTOCOLINFO 1",
771 std::placeholders::_1,
772 std::placeholders::_2))) {
773 LogPrintf(
"tor: Error sending initial protocolinfo command\n");
788 "tor: Not connected to Tor control port %s, trying to reconnect\n",
805 std::placeholders::_1),
807 std::placeholders::_1))) {
809 "tor: Re-initiating connection to Tor control port %s failed\n",
843 LogPrintf(
"tor: Unable to create event_base\n");
const CChainParams & Params()
Return the currently selected parameters.
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
uint16_t OnionServiceTargetPort() const
A hasher class for HMAC-SHA-256.
static const size_t OUTPUT_SIZE
A combination of a network address (CNetAddr) and a (TCP) port.
std::string ToStringIPPort() const
std::string ToString() const
Low-level handling for Tor control connection.
TorControlReply message
Message being received.
std::deque< ReplyHandlerCB > reply_handlers
Response handlers.
bool Connect(const std::string &tor_control_center, const ConnectionCB &connected, const ConnectionCB &disconnected)
Connect to a Tor control port.
TorControlConnection(struct event_base *base)
Create a new TorControlConnection.
bool Command(const std::string &cmd, const ReplyHandlerCB &reply_handler)
Send a command, register a handler for the reply.
std::function< void(TorControlConnection &)> connected
Callback when ready for use.
boost::signals2::signal< void(TorControlConnection &, const TorControlReply &)> async_handler
Response handlers for async replies.
static void readcb(struct bufferevent *bev, void *ctx)
Libevent handlers: internal.
std::function< void(TorControlConnection &)> disconnected
Callback when connection lost.
static void eventcb(struct bufferevent *bev, short what, void *ctx)
std::function< void(TorControlConnection &, const TorControlReply &)> ReplyHandlerCB
void Disconnect()
Disconnect from Tor control port.
struct bufferevent * b_conn
Connection to control socket.
struct event_base * base
Libevent event base.
std::function< void(TorControlConnection &)> ConnectionCB
Reply from Tor, can be single or multi-line.
std::vector< std::string > lines
Controller that connects to Tor control socket, authenticate, then create and maintain an ephemeral o...
TorControlConnection conn
static void reconnect_cb(evutil_socket_t fd, short what, void *arg)
Callback for reconnect timer.
fs::path GetPrivateKeyFile()
Get name fo file to store private key in.
std::vector< uint8_t > clientNonce
ClientNonce for SAFECOOKIE auth.
void connected_cb(TorControlConnection &conn)
Callback after successful connection.
void add_onion_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for ADD_ONION result.
const std::string m_tor_control_center
void disconnected_cb(TorControlConnection &conn)
Callback after connection lost or failed connection attempt.
void authchallenge_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHCHALLENGE result.
std::vector< uint8_t > cookie
Cookie for SAFECOOKIE auth.
struct event * reconnect_ev
TorController(struct event_base *base, const std::string &tor_control_center, const CService &target)
void auth_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHENTICATE result.
void Reconnect()
Reconnect, after getting disconnected.
void protocolinfo_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for PROTOCOLINFO result.
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
#define LogPrint(category,...)
static std::string PathToString(const path &path)
Convert path object to byte string.
static path PathFromString(const std::string &string)
Convert byte string to path object.
void TraceThread(const char *thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
void RemoveLocal(const CService &addr)
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
bool AddLocal(const CService &addr, int nScore)
@ NET_ONION
TOR (v2 or v3)
CService LookupNumeric(const std::string &name, uint16_t portDefault, DNSLookupFn dns_lookup_function)
Resolve a service string with a numeric IP to its first corresponding service.
bool SetProxy(enum Network net, const proxyType &addrProxy)
void GetRandBytes(Span< uint8_t > bytes) noexcept
Overall design of the RNG and entropy sources.
T GetRand(T nMax=std::numeric_limits< T >::max()) noexcept
Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limi...
bool WriteBinaryFile(const fs::path &filename, const std::string &data)
Write contents of std::string to a file.
std::pair< bool, std::string > ReadBinaryFile(const fs::path &filename, size_t maxsize=std::numeric_limits< size_t >::max())
Read full contents of a file and return them in a std::string.
static uint16_t GetDefaultPort()
void ReplaceAll(std::string &in_out, const std::string &search, const std::string &substitute)
std::vector< std::string > SplitString(std::string_view str, char sep)
struct timeval MillisToTimeval(int64_t nTimeout)
Convert milliseconds to a struct timeval for e.g.
static const std::string TOR_SAFE_CLIENTKEY
For computing clientHash in SAFECOOKIE.
CService DefaultOnionServiceTarget()
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)
Compute Tor SAFECOOKIE response.
static const int MAX_LINE_LENGTH
Maximum length for lines received on TorControlConnection.
static const float RECONNECT_TIMEOUT_EXP
Exponential backoff configuration - growth factor.
const std::string DEFAULT_TOR_CONTROL
Default control port.
static void TorControlThread(CService onion_service_target)
std::pair< std::string, std::string > SplitTorReplyLine(const std::string &s)
static const std::string TOR_SAFE_SERVERKEY
For computing serverHash in SAFECOOKIE.
static const int TOR_COOKIE_SIZE
Tor cookie size (from control-spec.txt)
static struct event_base * gBase
static const int TOR_NONCE_SIZE
Size of client/server nonce for SAFECOOKIE.
void InterruptTorControl()
std::map< std::string, std::string > ParseTorReplyMapping(const std::string &s)
Parse reply arguments in the form 'METHODS=COOKIE,SAFECOOKIE COOKIEFILE=".../control_auth_cookie"'.
static std::thread torControlThread
static const float RECONNECT_TIMEOUT_START
Exponential backoff configuration - initial timeout in seconds.
void StartTorControl(CService onion_service_target)
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
template std::vector< std::byte > ParseHex(std::string_view)
int atoi(const std::string &str)
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.