control.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2019, The Tor Project, Inc. */
  3. /* See LICENSE for licensing information */
  4. /**
  5. * \file control.c
  6. * \brief Implementation for Tor's control-socket interface.
  7. *
  8. * A "controller" is an external program that monitors and controls a Tor
  9. * instance via a text-based protocol. It connects to Tor via a connection
  10. * to a local socket.
  11. *
  12. * The protocol is line-driven. The controller sends commands terminated by a
  13. * CRLF. Tor sends lines that are either <em>replies</em> to what the
  14. * controller has said, or <em>events</em> that Tor sends to the controller
  15. * asynchronously based on occurrences in the Tor network model.
  16. *
  17. * See the control-spec.txt file in the torspec.git repository for full
  18. * details on protocol.
  19. *
  20. * This module generally has two kinds of entry points: those based on having
  21. * received a command on a controller socket, which are handled in
  22. * connection_control_process_inbuf(), and dispatched to individual functions
  23. * with names like control_handle_COMMANDNAME(); and those based on events
  24. * that occur elsewhere in Tor, which are handled by functions with names like
  25. * control_event_EVENTTYPE().
  26. *
  27. * Controller events are not sent immediately; rather, they are inserted into
  28. * the queued_control_events array, and flushed later from
  29. * flush_queued_events_cb(). Doing this simplifies our callgraph greatly,
  30. * by limiting the number of places in Tor that can call back into the network
  31. * stack.
  32. **/
  33. #define CONTROL_MODULE_PRIVATE
  34. #define CONTROL_PRIVATE
  35. #include "core/or/or.h"
  36. #include "app/config/config.h"
  37. #include "app/main/main.h"
  38. #include "core/mainloop/connection.h"
  39. #include "core/mainloop/mainloop.h"
  40. #include "core/or/connection_or.h"
  41. #include "core/proto/proto_control0.h"
  42. #include "core/proto/proto_http.h"
  43. #include "feature/control/control.h"
  44. #include "feature/control/control_auth.h"
  45. #include "feature/control/control_cmd.h"
  46. #include "feature/control/control_events.h"
  47. #include "feature/control/control_proto.h"
  48. #include "feature/rend/rendcommon.h"
  49. #include "feature/rend/rendservice.h"
  50. #include "lib/evloop/procmon.h"
  51. #include "feature/control/control_connection_st.h"
  52. #ifdef HAVE_UNISTD_H
  53. #include <unistd.h>
  54. #endif
  55. #ifdef HAVE_SYS_STAT_H
  56. #include <sys/stat.h>
  57. #endif
  58. /** Convert a connection_t* to an control_connection_t*; assert if the cast is
  59. * invalid. */
  60. control_connection_t *
  61. TO_CONTROL_CONN(connection_t *c)
  62. {
  63. tor_assert(c->magic == CONTROL_CONNECTION_MAGIC);
  64. return DOWNCAST(control_connection_t, c);
  65. }
  66. /** Create and add a new controller connection on <b>sock</b>. If
  67. * <b>CC_LOCAL_FD_IS_OWNER</b> is set in <b>flags</b>, this Tor process should
  68. * exit when the connection closes. If <b>CC_LOCAL_FD_IS_AUTHENTICATED</b>
  69. * is set, then the connection does not need to authenticate.
  70. */
  71. int
  72. control_connection_add_local_fd(tor_socket_t sock, unsigned flags)
  73. {
  74. if (BUG(! SOCKET_OK(sock)))
  75. return -1;
  76. const int is_owner = !!(flags & CC_LOCAL_FD_IS_OWNER);
  77. const int is_authenticated = !!(flags & CC_LOCAL_FD_IS_AUTHENTICATED);
  78. control_connection_t *control_conn = control_connection_new(AF_UNSPEC);
  79. connection_t *conn = TO_CONN(control_conn);
  80. conn->s = sock;
  81. tor_addr_make_unspec(&conn->addr);
  82. conn->port = 1;
  83. conn->address = tor_strdup("<local socket>");
  84. /* We take ownership of this socket so that later, when we close it,
  85. * we don't freak out. */
  86. tor_take_socket_ownership(sock);
  87. if (set_socket_nonblocking(sock) < 0 ||
  88. connection_add(conn) < 0) {
  89. connection_free(conn);
  90. return -1;
  91. }
  92. control_conn->is_owning_control_connection = is_owner;
  93. if (connection_init_accepted_conn(conn, NULL) < 0) {
  94. connection_mark_for_close(conn);
  95. return -1;
  96. }
  97. if (is_authenticated) {
  98. conn->state = CONTROL_CONN_STATE_OPEN;
  99. }
  100. return 0;
  101. }
  102. /** Write all of the open control ports to ControlPortWriteToFile */
  103. void
  104. control_ports_write_to_file(void)
  105. {
  106. smartlist_t *lines;
  107. char *joined = NULL;
  108. const or_options_t *options = get_options();
  109. if (!options->ControlPortWriteToFile)
  110. return;
  111. lines = smartlist_new();
  112. SMARTLIST_FOREACH_BEGIN(get_connection_array(), const connection_t *, conn) {
  113. if (conn->type != CONN_TYPE_CONTROL_LISTENER || conn->marked_for_close)
  114. continue;
  115. #ifdef AF_UNIX
  116. if (conn->socket_family == AF_UNIX) {
  117. smartlist_add_asprintf(lines, "UNIX_PORT=%s\n", conn->address);
  118. continue;
  119. }
  120. #endif /* defined(AF_UNIX) */
  121. smartlist_add_asprintf(lines, "PORT=%s:%d\n", conn->address, conn->port);
  122. } SMARTLIST_FOREACH_END(conn);
  123. joined = smartlist_join_strings(lines, "", 0, NULL);
  124. if (write_str_to_file(options->ControlPortWriteToFile, joined, 0) < 0) {
  125. log_warn(LD_CONTROL, "Writing %s failed: %s",
  126. options->ControlPortWriteToFile, strerror(errno));
  127. }
  128. #ifndef _WIN32
  129. if (options->ControlPortFileGroupReadable) {
  130. if (chmod(options->ControlPortWriteToFile, 0640)) {
  131. log_warn(LD_FS,"Unable to make %s group-readable.",
  132. options->ControlPortWriteToFile);
  133. }
  134. }
  135. #endif /* !defined(_WIN32) */
  136. tor_free(joined);
  137. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  138. smartlist_free(lines);
  139. }
  140. const struct signal_name_t signal_table[] = {
  141. { SIGHUP, "RELOAD" },
  142. { SIGHUP, "HUP" },
  143. { SIGINT, "SHUTDOWN" },
  144. { SIGUSR1, "DUMP" },
  145. { SIGUSR1, "USR1" },
  146. { SIGUSR2, "DEBUG" },
  147. { SIGUSR2, "USR2" },
  148. { SIGTERM, "HALT" },
  149. { SIGTERM, "TERM" },
  150. { SIGTERM, "INT" },
  151. { SIGNEWNYM, "NEWNYM" },
  152. { SIGCLEARDNSCACHE, "CLEARDNSCACHE"},
  153. { SIGHEARTBEAT, "HEARTBEAT"},
  154. { SIGACTIVE, "ACTIVE" },
  155. { SIGDORMANT, "DORMANT" },
  156. { 0, NULL },
  157. };
  158. /** Called when <b>conn</b> has no more bytes left on its outbuf. */
  159. int
  160. connection_control_finished_flushing(control_connection_t *conn)
  161. {
  162. tor_assert(conn);
  163. return 0;
  164. }
  165. /** Called when <b>conn</b> has gotten its socket closed. */
  166. int
  167. connection_control_reached_eof(control_connection_t *conn)
  168. {
  169. tor_assert(conn);
  170. log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
  171. connection_mark_for_close(TO_CONN(conn));
  172. return 0;
  173. }
  174. /** Shut down this Tor instance in the same way that SIGINT would, but
  175. * with a log message appropriate for the loss of an owning controller. */
  176. static void
  177. lost_owning_controller(const char *owner_type, const char *loss_manner)
  178. {
  179. log_notice(LD_CONTROL, "Owning controller %s has %s -- exiting now.",
  180. owner_type, loss_manner);
  181. activate_signal(SIGTERM);
  182. }
  183. /** Called when <b>conn</b> is being freed. */
  184. void
  185. connection_control_closed(control_connection_t *conn)
  186. {
  187. tor_assert(conn);
  188. conn->event_mask = 0;
  189. control_update_global_event_mask();
  190. /* Close all ephemeral Onion Services if any.
  191. * The list and it's contents are scrubbed/freed in connection_free_.
  192. */
  193. if (conn->ephemeral_onion_services) {
  194. SMARTLIST_FOREACH_BEGIN(conn->ephemeral_onion_services, char *, cp) {
  195. if (rend_valid_v2_service_id(cp)) {
  196. rend_service_del_ephemeral(cp);
  197. } else if (hs_address_is_valid(cp)) {
  198. hs_service_del_ephemeral(cp);
  199. } else {
  200. /* An invalid .onion in our list should NEVER happen */
  201. tor_fragile_assert();
  202. }
  203. } SMARTLIST_FOREACH_END(cp);
  204. }
  205. if (conn->is_owning_control_connection) {
  206. lost_owning_controller("connection", "closed");
  207. }
  208. }
  209. /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
  210. * stage of the protocol. */
  211. static int
  212. is_valid_initial_command(control_connection_t *conn, const char *cmd)
  213. {
  214. if (conn->base_.state == CONTROL_CONN_STATE_OPEN)
  215. return 1;
  216. if (!strcasecmp(cmd, "PROTOCOLINFO"))
  217. return (!conn->have_sent_protocolinfo &&
  218. conn->safecookie_client_hash == NULL);
  219. if (!strcasecmp(cmd, "AUTHCHALLENGE"))
  220. return (conn->safecookie_client_hash == NULL);
  221. if (!strcasecmp(cmd, "AUTHENTICATE") ||
  222. !strcasecmp(cmd, "QUIT"))
  223. return 1;
  224. return 0;
  225. }
  226. /** Do not accept any control command of more than 1MB in length. Anything
  227. * that needs to be anywhere near this long probably means that one of our
  228. * interfaces is broken. */
  229. #define MAX_COMMAND_LINE_LENGTH (1024*1024)
  230. /** Wrapper around peek_buf_has_control0 command: presents the same
  231. * interface as that underlying functions, but takes a connection_t intead of
  232. * a buf_t.
  233. */
  234. static int
  235. peek_connection_has_control0_command(connection_t *conn)
  236. {
  237. return peek_buf_has_control0_command(conn->inbuf);
  238. }
  239. static int
  240. peek_connection_has_http_command(connection_t *conn)
  241. {
  242. return peek_buf_has_http_command(conn->inbuf);
  243. }
  244. /**
  245. * Helper: take a nul-terminated command of given length, and find where the
  246. * command starts and the arguments begin. Separate them, allocate a new
  247. * string in <b>current_cmd_out</b> for the command, and return a pointer
  248. * to the arguments.
  249. **/
  250. STATIC char *
  251. control_split_incoming_command(char *incoming_cmd,
  252. size_t *data_len,
  253. char **current_cmd_out)
  254. {
  255. const bool is_multiline = *data_len && incoming_cmd[0] == '+';
  256. size_t cmd_len = 0;
  257. while (cmd_len < *data_len
  258. && !TOR_ISSPACE(incoming_cmd[cmd_len]))
  259. ++cmd_len;
  260. *current_cmd_out = tor_memdup_nulterm(incoming_cmd, cmd_len);
  261. char *args = incoming_cmd+cmd_len;
  262. tor_assert(*data_len>=cmd_len);
  263. *data_len -= cmd_len;
  264. if (is_multiline) {
  265. // Only match horizontal space: any line after the first is data,
  266. // not arguments.
  267. while ((*args == '\t' || *args == ' ') && *data_len) {
  268. ++args;
  269. --*data_len;
  270. }
  271. } else {
  272. while (TOR_ISSPACE(*args) && *data_len) {
  273. ++args;
  274. --*data_len;
  275. }
  276. }
  277. return args;
  278. }
  279. static const char CONTROLPORT_IS_NOT_AN_HTTP_PROXY_MSG[] =
  280. "HTTP/1.0 501 Tor ControlPort is not an HTTP proxy"
  281. "\r\nContent-Type: text/html; charset=iso-8859-1\r\n\r\n"
  282. "<html>\n"
  283. "<head>\n"
  284. "<title>Tor's ControlPort is not an HTTP proxy</title>\n"
  285. "</head>\n"
  286. "<body>\n"
  287. "<h1>Tor's ControlPort is not an HTTP proxy</h1>\n"
  288. "<p>\n"
  289. "It appears you have configured your web browser to use Tor's control port"
  290. " as an HTTP proxy.\n"
  291. "This is not correct: Tor's default SOCKS proxy port is 9050.\n"
  292. "Please configure your client accordingly.\n"
  293. "</p>\n"
  294. "<p>\n"
  295. "See <a href=\"https://www.torproject.org/documentation.html\">"
  296. "https://www.torproject.org/documentation.html</a> for more "
  297. "information.\n"
  298. "<!-- Plus this comment, to make the body response more than 512 bytes, so "
  299. " IE will be willing to display it. Comment comment comment comment "
  300. " comment comment comment comment comment comment comment comment.-->\n"
  301. "</p>\n"
  302. "</body>\n"
  303. "</html>\n";
  304. /** Return an error on a control connection that tried to use the v0 protocol.
  305. */
  306. static void
  307. control_send_v0_reject(control_connection_t *conn)
  308. {
  309. size_t body_len;
  310. char buf[128];
  311. set_uint16(buf+2, htons(0x0000)); /* type == error */
  312. set_uint16(buf+4, htons(0x0001)); /* code == internal error */
  313. strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
  314. "and later; upgrade your controller.",
  315. sizeof(buf)-6);
  316. body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
  317. set_uint16(buf+0, htons(body_len));
  318. connection_buf_add(buf, 4+body_len, TO_CONN(conn));
  319. connection_mark_and_flush(TO_CONN(conn));
  320. }
  321. /** Return an error on a control connection that tried to use HTTP.
  322. */
  323. static void
  324. control_send_http_reject(control_connection_t *conn)
  325. {
  326. connection_write_str_to_buf(CONTROLPORT_IS_NOT_AN_HTTP_PROXY_MSG, conn);
  327. log_notice(LD_CONTROL, "Received HTTP request on ControlPort");
  328. connection_mark_and_flush(TO_CONN(conn));
  329. }
  330. /** Check if a control connection has tried to use a known invalid protocol.
  331. * If it has, then:
  332. * - send a reject response,
  333. * - log a notice-level message, and
  334. * - return false. */
  335. static bool
  336. control_protocol_is_valid(control_connection_t *conn)
  337. {
  338. /* Detect v0 commands and send a "no more v0" message. */
  339. if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
  340. peek_connection_has_control0_command(TO_CONN(conn))) {
  341. control_send_v0_reject(conn);
  342. return 0;
  343. }
  344. /* If the user has the HTTP proxy port and the control port confused. */
  345. if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
  346. peek_connection_has_http_command(TO_CONN(conn))) {
  347. control_send_http_reject(conn);
  348. return 0;
  349. }
  350. return 1;
  351. }
  352. /** Called when data has arrived on a v1 control connection: Try to fetch
  353. * commands from conn->inbuf, and execute them.
  354. */
  355. int
  356. connection_control_process_inbuf(control_connection_t *conn)
  357. {
  358. size_t data_len;
  359. uint32_t cmd_data_len;
  360. char *args;
  361. tor_assert(conn);
  362. tor_assert(conn->base_.state == CONTROL_CONN_STATE_OPEN ||
  363. conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH);
  364. if (!conn->incoming_cmd) {
  365. conn->incoming_cmd = tor_malloc(1024);
  366. conn->incoming_cmd_len = 1024;
  367. conn->incoming_cmd_cur_len = 0;
  368. }
  369. if (!control_protocol_is_valid(conn)) {
  370. return 0;
  371. }
  372. again:
  373. while (1) {
  374. size_t last_idx;
  375. int r;
  376. /* First, fetch a line. */
  377. do {
  378. data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
  379. r = connection_buf_get_line(TO_CONN(conn),
  380. conn->incoming_cmd+conn->incoming_cmd_cur_len,
  381. &data_len);
  382. if (r == 0)
  383. /* Line not all here yet. Wait. */
  384. return 0;
  385. else if (r == -1) {
  386. if (data_len + conn->incoming_cmd_cur_len > MAX_COMMAND_LINE_LENGTH) {
  387. control_write_endreply(conn, 500, "Line too long.");
  388. connection_stop_reading(TO_CONN(conn));
  389. connection_mark_and_flush(TO_CONN(conn));
  390. }
  391. while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
  392. conn->incoming_cmd_len *= 2;
  393. conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
  394. conn->incoming_cmd_len);
  395. }
  396. } while (r != 1);
  397. tor_assert(data_len);
  398. last_idx = conn->incoming_cmd_cur_len;
  399. conn->incoming_cmd_cur_len += (int)data_len;
  400. /* We have appended a line to incoming_cmd. Is the command done? */
  401. if (last_idx == 0 && *conn->incoming_cmd != '+')
  402. /* One line command, didn't start with '+'. */
  403. break;
  404. /* XXXX this code duplication is kind of dumb. */
  405. if (last_idx+3 == conn->incoming_cmd_cur_len &&
  406. tor_memeq(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
  407. /* Just appended ".\r\n"; we're done. Remove it. */
  408. conn->incoming_cmd[last_idx] = '\0';
  409. conn->incoming_cmd_cur_len -= 3;
  410. break;
  411. } else if (last_idx+2 == conn->incoming_cmd_cur_len &&
  412. tor_memeq(conn->incoming_cmd + last_idx, ".\n", 2)) {
  413. /* Just appended ".\n"; we're done. Remove it. */
  414. conn->incoming_cmd[last_idx] = '\0';
  415. conn->incoming_cmd_cur_len -= 2;
  416. break;
  417. }
  418. /* Otherwise, read another line. */
  419. }
  420. data_len = conn->incoming_cmd_cur_len;
  421. /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
  422. * recognize it.
  423. */
  424. tor_free(conn->current_cmd);
  425. args = control_split_incoming_command(conn->incoming_cmd, &data_len,
  426. &conn->current_cmd);
  427. if (BUG(!conn->current_cmd))
  428. return -1;
  429. /* If the connection is already closing, ignore further commands */
  430. if (TO_CONN(conn)->marked_for_close) {
  431. return 0;
  432. }
  433. /* Otherwise, Quit is always valid. */
  434. if (!strcasecmp(conn->current_cmd, "QUIT")) {
  435. control_write_endreply(conn, 250, "closing connection");
  436. connection_mark_and_flush(TO_CONN(conn));
  437. return 0;
  438. }
  439. if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
  440. !is_valid_initial_command(conn, conn->current_cmd)) {
  441. control_write_endreply(conn, 514, "Authentication required.");
  442. connection_mark_for_close(TO_CONN(conn));
  443. return 0;
  444. }
  445. if (data_len >= UINT32_MAX) {
  446. control_write_endreply(conn, 500, "A 4GB command? Nice try.");
  447. connection_mark_for_close(TO_CONN(conn));
  448. return 0;
  449. }
  450. cmd_data_len = (uint32_t)data_len;
  451. if (handle_control_command(conn, cmd_data_len, args) < 0)
  452. return -1;
  453. conn->incoming_cmd_cur_len = 0;
  454. goto again;
  455. }
  456. /** Cached liveness for network liveness events and GETINFO
  457. */
  458. static int network_is_live = 0;
  459. int
  460. get_cached_network_liveness(void)
  461. {
  462. return network_is_live;
  463. }
  464. void
  465. set_cached_network_liveness(int liveness)
  466. {
  467. network_is_live = liveness;
  468. }
  469. /** A copy of the process specifier of Tor's owning controller, or
  470. * NULL if this Tor instance is not currently owned by a process. */
  471. static char *owning_controller_process_spec = NULL;
  472. /** A process-termination monitor for Tor's owning controller, or NULL
  473. * if this Tor instance is not currently owned by a process. */
  474. static tor_process_monitor_t *owning_controller_process_monitor = NULL;
  475. /** Process-termination monitor callback for Tor's owning controller
  476. * process. */
  477. static void
  478. owning_controller_procmon_cb(void *unused)
  479. {
  480. (void)unused;
  481. lost_owning_controller("process", "vanished");
  482. }
  483. /** Set <b>process_spec</b> as Tor's owning controller process.
  484. * Exit on failure. */
  485. void
  486. monitor_owning_controller_process(const char *process_spec)
  487. {
  488. const char *msg;
  489. tor_assert((owning_controller_process_spec == NULL) ==
  490. (owning_controller_process_monitor == NULL));
  491. if (owning_controller_process_spec != NULL) {
  492. if ((process_spec != NULL) && !strcmp(process_spec,
  493. owning_controller_process_spec)) {
  494. /* Same process -- return now, instead of disposing of and
  495. * recreating the process-termination monitor. */
  496. return;
  497. }
  498. /* We are currently owned by a process, and we should no longer be
  499. * owned by it. Free the process-termination monitor. */
  500. tor_process_monitor_free(owning_controller_process_monitor);
  501. owning_controller_process_monitor = NULL;
  502. tor_free(owning_controller_process_spec);
  503. owning_controller_process_spec = NULL;
  504. }
  505. tor_assert((owning_controller_process_spec == NULL) &&
  506. (owning_controller_process_monitor == NULL));
  507. if (process_spec == NULL)
  508. return;
  509. owning_controller_process_spec = tor_strdup(process_spec);
  510. owning_controller_process_monitor =
  511. tor_process_monitor_new(tor_libevent_get_base(),
  512. owning_controller_process_spec,
  513. LD_CONTROL,
  514. owning_controller_procmon_cb, NULL,
  515. &msg);
  516. if (owning_controller_process_monitor == NULL) {
  517. log_err(LD_BUG, "Couldn't create process-termination monitor for "
  518. "owning controller: %s. Exiting.",
  519. msg);
  520. owning_controller_process_spec = NULL;
  521. tor_shutdown_event_loop_and_exit(1);
  522. }
  523. }
  524. /** Free any leftover allocated memory of the control.c subsystem. */
  525. void
  526. control_free_all(void)
  527. {
  528. control_auth_free_all();
  529. control_events_free_all();
  530. control_cmd_free_all();
  531. control_event_bootstrap_reset();
  532. }