control.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. /* Copyright 2004 Roger Dingledine, Nick Mathewson. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. const char control_c_id[] = "$Id$";
  5. /**
  6. * /file control.c
  7. *
  8. * /brief Implementation for Tor's control-socket interface.
  9. */
  10. #include "or.h"
  11. /* Protocol outline: a bidirectional stream, over which each side
  12. * sends a series of messages. Each message has a two-byte length field,
  13. * a two-byte typecode, and a variable-length body whose length is
  14. * given in the length field.
  15. *
  16. * By default, the server only sends messages in response to client messages.
  17. * Every client message gets a message in response. The client may, however,
  18. * _request_ that other messages be delivered asynchronously.
  19. *
  20. *
  21. * Every message type is either client-only or server-only, and every
  22. * server message type is either synchronous-only (only occurs in
  23. * response to a client request) or asynchronous-only (never is an
  24. * answer to a client request.
  25. *
  26. * See control-spec.txt for full details.
  27. */
  28. /* Recognized message type codes. */
  29. #define CONTROL_CMD_ERROR 0x0000
  30. #define CONTROL_CMD_DONE 0x0001
  31. #define CONTROL_CMD_SETCONF 0x0002
  32. #define CONTROL_CMD_GETCONF 0x0003
  33. #define CONTROL_CMD_CONFVALUE 0x0004
  34. #define CONTROL_CMD_SETEVENTS 0x0005
  35. #define CONTROL_CMD_EVENT 0x0006
  36. #define CONTROL_CMD_AUTHENTICATE 0x0007
  37. #define CONTROL_CMD_SAVECONF 0x0008
  38. #define _CONTROL_CMD_MAX_RECOGNIZED 0x0008
  39. /* Recognized error codes. */
  40. #define ERR_UNSPECIFIED 0x0000
  41. #define ERR_INTERNAL 0x0001
  42. #define ERR_UNRECOGNIZED_TYPE 0x0002
  43. #define ERR_SYNTAX 0x0003
  44. #define ERR_UNRECOGNIZED_CONFIG_KEY 0x0004
  45. #define ERR_INVALID_CONFIG_VALUE 0x0005
  46. #define ERR_UNRECOGNIZED_EVENT_CODE 0x0006
  47. #define ERR_UNAUTHORIZED 0x0007
  48. #define ERR_REJECTED_AUTHENTICATION 0x0008
  49. /* Recognized asynchronous event types. */
  50. #define _EVENT_MIN 0x0001
  51. #define EVENT_CIRCUIT_STATUS 0x0001
  52. #define EVENT_STREAM_STATUS 0x0002
  53. #define EVENT_OR_CONN_STATUS 0x0003
  54. #define EVENT_BANDWIDTH_USED 0x0004
  55. #define EVENT_WARNING 0x0005
  56. #define _EVENT_MAX 0x0005
  57. /** Array mapping from message type codes to human-readable message
  58. * type names. */
  59. static const char * CONTROL_COMMANDS[] = {
  60. "error",
  61. "done",
  62. "setconf",
  63. "getconf",
  64. "confvalue",
  65. "setevents",
  66. "events",
  67. "authenticate",
  68. "saveconf",
  69. };
  70. /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
  71. * connection is interested in events of type <b>e</b>. We use this
  72. * so that we can decide to skip generating event messages that nobody
  73. * has interest in without having to walk over the global connection
  74. * list to find out.
  75. **/
  76. static uint32_t global_event_mask = 0;
  77. /** Macro: true if any control connection is interested in events of type
  78. * <b>e</b>. */
  79. #define EVENT_IS_INTERESTING(e) (global_event_mask & (1<<(e)))
  80. /** If we're using cookie-type authentication, how long should our cookies be?
  81. */
  82. #define AUTHENTICATION_COOKIE_LEN 32
  83. /** If true, we've set authentication_cookie to a secret code and
  84. * stored it to disk. */
  85. static int authentication_cookie_is_set = 0;
  86. static char authentication_cookie[AUTHENTICATION_COOKIE_LEN];
  87. static void update_global_event_mask(void);
  88. static void send_control_message(connection_t *conn, uint16_t type,
  89. uint16_t len, const char *body);
  90. static void send_control_done(connection_t *conn);
  91. static void send_control_error(connection_t *conn, uint16_t error,
  92. const char *message);
  93. static void send_control_event(uint16_t event, uint16_t len, const char *body);
  94. static int handle_control_setconf(connection_t *conn, uint16_t len,
  95. char *body);
  96. static int handle_control_getconf(connection_t *conn, uint16_t len,
  97. const char *body);
  98. static int handle_control_setevents(connection_t *conn, uint16_t len,
  99. const char *body);
  100. static int handle_control_authenticate(connection_t *conn, uint16_t len,
  101. const char *body);
  102. static int handle_control_saveconf(connection_t *conn, uint16_t len,
  103. const char *body);
  104. /** Given a possibly invalid message type code <b>cmd</b>, return a
  105. * human-readable string equivalent. */
  106. static INLINE const char *
  107. control_cmd_to_string(uint16_t cmd)
  108. {
  109. return (cmd<=_CONTROL_CMD_MAX_RECOGNIZED) ? CONTROL_COMMANDS[cmd] : "Unknown";
  110. }
  111. /** Set <b>global_event_mask</b> to the bitwise OR of each live control
  112. * connection's event_mask field. */
  113. static void update_global_event_mask(void)
  114. {
  115. connection_t **conns;
  116. int n_conns, i;
  117. global_event_mask = 0;
  118. get_connection_array(&conns, &n_conns);
  119. for (i = 0; i < n_conns; ++i) {
  120. if (conns[i]->type == CONN_TYPE_CONTROL &&
  121. conns[i]->state == CONTROL_CONN_STATE_OPEN) {
  122. global_event_mask |= conns[i]->event_mask;
  123. }
  124. }
  125. }
  126. /** Send a message of type <b>type</b> containing <b>len</b> bytes
  127. * from <b>body</b> along the control connection <b>conn</b> */
  128. static void
  129. send_control_message(connection_t *conn, uint16_t type, uint16_t len,
  130. const char *body)
  131. {
  132. char buf[4];
  133. tor_assert(conn);
  134. tor_assert(len || !body);
  135. tor_assert(type <= _CONTROL_CMD_MAX_RECOGNIZED);
  136. set_uint16(buf, htons(len));
  137. set_uint16(buf+2, htons(type));
  138. connection_write_to_buf(buf, 4, conn);
  139. if (len)
  140. connection_write_to_buf(body, len, conn);
  141. }
  142. /** Send a "DONE" message down the control connection <b>conn</b> */
  143. static void
  144. send_control_done(connection_t *conn)
  145. {
  146. send_control_message(conn, CONTROL_CMD_DONE, 0, NULL);
  147. }
  148. /** Send an error message with error code <b>error</b> and body
  149. * <b>message</b> down the connection <b>conn</b> */
  150. static void
  151. send_control_error(connection_t *conn, uint16_t error, const char *message)
  152. {
  153. char buf[256];
  154. size_t len;
  155. set_uint16(buf, htons(error));
  156. len = strlen(message);
  157. tor_assert(len < (256-2));
  158. memcpy(buf+2, message, len);
  159. send_control_message(conn, CONTROL_CMD_ERROR, (uint16_t)(len+2), buf);
  160. }
  161. /** Send an 'event' message of event type <b>event</b>, containing
  162. * <b>len</b> bytes in <b>body</b> to every control connection that
  163. * is interested in it. */
  164. static void
  165. send_control_event(uint16_t event, uint16_t len, const char *body)
  166. {
  167. connection_t **conns;
  168. int n_conns, i;
  169. size_t buflen;
  170. char *buf;
  171. buflen = len + 2;
  172. buf = tor_malloc_zero(buflen);
  173. set_uint16(buf, htons(event));
  174. memcpy(buf+2, body, len);
  175. get_connection_array(&conns, &n_conns);
  176. for (i = 0; i < n_conns; ++i) {
  177. if (conns[i]->type == CONN_TYPE_CONTROL &&
  178. conns[i]->state == CONTROL_CONN_STATE_OPEN &&
  179. conns[i]->event_mask & (1<<event)) {
  180. send_control_message(conns[i], CONTROL_CMD_EVENT, (uint16_t)(buflen), buf);
  181. }
  182. }
  183. tor_free(buf);
  184. }
  185. /** Called when we receive a SETCONF message: parse the body and try
  186. * to update our configuration. Reply with a DONE or ERROR message. */
  187. static int
  188. handle_control_setconf(connection_t *conn, uint16_t len, char *body)
  189. {
  190. int r;
  191. struct config_line_t *lines=NULL;
  192. if (config_get_lines(body, &lines) < 0) {
  193. log_fn(LOG_WARN,"Controller gave us config lines we can't parse.");
  194. send_control_error(conn, ERR_SYNTAX, "Couldn't parse configuration");
  195. return 0;
  196. }
  197. if ((r=config_trial_assign(lines, 1)) < 0) {
  198. log_fn(LOG_WARN,"Controller gave us config lines that didn't validate.");
  199. if (r==-1) {
  200. send_control_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY,
  201. "Unrecognized option");
  202. } else {
  203. send_control_error(conn, ERR_INVALID_CONFIG_VALUE,"Invalid option value");
  204. }
  205. config_free_lines(lines);
  206. return 0;
  207. }
  208. config_free_lines(lines);
  209. if (options_act() < 0) { /* acting on them failed. die. */
  210. log_fn(LOG_ERR,"Acting on config options left us in a broken state. Dying.");
  211. exit(1);
  212. }
  213. send_control_done(conn);
  214. return 0;
  215. }
  216. /** Called when we receive a GETCONF message. Parse the request, and
  217. * reply with a CONFVALUE or an ERROR message */
  218. static int
  219. handle_control_getconf(connection_t *conn, uint16_t body_len, const char *body)
  220. {
  221. smartlist_t *questions = NULL;
  222. smartlist_t *answers = NULL;
  223. char *msg = NULL;
  224. size_t msg_len;
  225. or_options_t *options = get_options();
  226. questions = smartlist_create();
  227. smartlist_split_string(questions, body, "\n",
  228. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  229. answers = smartlist_create();
  230. SMARTLIST_FOREACH(questions, const char *, q,
  231. {
  232. int recognized = config_option_is_recognized(q);
  233. if (!recognized) {
  234. send_control_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, body);
  235. goto done;
  236. } else {
  237. struct config_line_t *answer = config_get_assigned_option(options,q);
  238. while (answer) {
  239. struct config_line_t *next;
  240. size_t alen = strlen(answer->key)+strlen(answer->value)+2;
  241. char *astr = tor_malloc(alen);
  242. tor_snprintf(astr, alen, "%s %s\n", answer->key, answer->value);
  243. smartlist_add(answers, astr);
  244. next = answer->next;
  245. tor_free(answer->key);
  246. tor_free(answer->value);
  247. tor_free(answer);
  248. answer = next;
  249. }
  250. }
  251. });
  252. msg = smartlist_join_strings(answers, "", 0, &msg_len);
  253. send_control_message(conn, CONTROL_CMD_CONFVALUE,
  254. (uint16_t)msg_len, msg_len?msg:NULL);
  255. done:
  256. if (answers) SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  257. if (questions) SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  258. smartlist_free(answers);
  259. smartlist_free(questions);
  260. tor_free(msg);
  261. return 0;
  262. }
  263. /** Called when we get a SETEVENTS message: update conn->event_mask,
  264. * and reply with DONE or ERROR. */
  265. static int
  266. handle_control_setevents(connection_t *conn, uint16_t len, const char *body)
  267. {
  268. uint16_t event_code;
  269. uint32_t event_mask = 0;
  270. if (len % 2) {
  271. send_control_error(conn, ERR_SYNTAX,
  272. "Odd number of bytes in setevents message");
  273. return 0;
  274. }
  275. for (; len; len -= 2, body += 2) {
  276. event_code = ntohs(get_uint16(body));
  277. if (event_code < _EVENT_MIN || event_code > _EVENT_MAX) {
  278. send_control_error(conn, ERR_UNRECOGNIZED_EVENT_CODE,
  279. "Unrecognized event code");
  280. return 0;
  281. }
  282. event_mask |= (1 << event_code);
  283. }
  284. conn->event_mask = event_mask;
  285. update_global_event_mask();
  286. send_control_done(conn);
  287. return 0;
  288. }
  289. /** Called when we get an AUTHENTICATE message. Check whether the
  290. * authentication is valid, and if so, update the connection's state to
  291. * OPEN. Reply with DONE or ERROR.
  292. */
  293. static int
  294. handle_control_authenticate(connection_t *conn, uint16_t len, const char *body)
  295. {
  296. or_options_t *options = get_options();
  297. if (options->CookieAuthentication) {
  298. if (len == AUTHENTICATION_COOKIE_LEN &&
  299. !memcmp(authentication_cookie, body, len)) {
  300. goto ok;
  301. }
  302. } else if (options->HashedControlPassword) {
  303. char expected[S2K_SPECIFIER_LEN+DIGEST_LEN];
  304. char received[DIGEST_LEN];
  305. if (base64_decode(expected,sizeof(expected),
  306. options->HashedControlPassword,
  307. strlen(options->HashedControlPassword))<0) {
  308. log_fn(LOG_WARN,"Couldn't decode HashedControlPassword: invalid base64");
  309. goto err;
  310. }
  311. secret_to_key(received,DIGEST_LEN,body,len,expected);
  312. if (!memcmp(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
  313. goto ok;
  314. goto err;
  315. } else {
  316. if (len == 0) {
  317. /* if Tor doesn't demand any stronger authentication, then
  318. * the controller can get in with a blank auth line. */
  319. goto ok;
  320. }
  321. goto err;
  322. }
  323. err:
  324. send_control_error(conn, ERR_REJECTED_AUTHENTICATION,"Authentication failed");
  325. return 0;
  326. ok:
  327. log_fn(LOG_INFO, "Authenticated control connection (%d)", conn->s);
  328. send_control_done(conn);
  329. conn->state = CONTROL_CONN_STATE_OPEN;
  330. return 0;
  331. }
  332. static int
  333. handle_control_saveconf(connection_t *conn, uint16_t len,
  334. const char *body)
  335. {
  336. if (save_current_config()<0) {
  337. send_control_error(conn, ERR_INTERNAL,
  338. "Unable to write configuration to disk.");
  339. } else {
  340. send_control_done(conn);
  341. }
  342. return 0;
  343. }
  344. /** Called when <b>conn</b> has no more bytes left on its outbuf. */
  345. int
  346. connection_control_finished_flushing(connection_t *conn) {
  347. tor_assert(conn);
  348. tor_assert(conn->type == CONN_TYPE_CONTROL);
  349. connection_stop_writing(conn);
  350. return 0;
  351. }
  352. /** Called when <b>conn</b> has gotten its socket closed. */
  353. int connection_control_reached_eof(connection_t *conn) {
  354. log_fn(LOG_INFO,"Control connection reached EOF. Closing.");
  355. connection_mark_for_close(conn);
  356. return 0;
  357. }
  358. /** Called when <b>conn</b> has received more bytes on its inbuf.
  359. */
  360. int
  361. connection_control_process_inbuf(connection_t *conn) {
  362. uint16_t body_len, command_type;
  363. char *body;
  364. tor_assert(conn);
  365. tor_assert(conn->type == CONN_TYPE_CONTROL);
  366. again:
  367. /* Try to suck a control message from the buffer. */
  368. switch (fetch_from_buf_control(conn->inbuf, &body_len, &command_type, &body))
  369. {
  370. case -1:
  371. tor_free(body);
  372. log_fn(LOG_WARN, "Error in control command. Failing.");
  373. return -1;
  374. case 0:
  375. /* Control command not all here yet. Wait. */
  376. return 0;
  377. case 1:
  378. /* We got a command. Process it. */
  379. break;
  380. default:
  381. tor_assert(0);
  382. }
  383. /* We got a command. If we need authentication, only authentication
  384. * commands will be considered. */
  385. if (conn->state == CONTROL_CONN_STATE_NEEDAUTH &&
  386. command_type != CONTROL_CMD_AUTHENTICATE) {
  387. log_fn(LOG_WARN, "Rejecting '%s' command; authentication needed.",
  388. control_cmd_to_string(command_type));
  389. send_control_error(conn, ERR_UNAUTHORIZED, "Authentication required");
  390. tor_free(body);
  391. goto again;
  392. }
  393. /* Okay, we're willing to process the command. */
  394. switch (command_type)
  395. {
  396. case CONTROL_CMD_SETCONF:
  397. if (handle_control_setconf(conn, body_len, body))
  398. return -1;
  399. break;
  400. case CONTROL_CMD_GETCONF:
  401. if (handle_control_getconf(conn, body_len, body))
  402. return -1;
  403. break;
  404. case CONTROL_CMD_SETEVENTS:
  405. if (handle_control_setevents(conn, body_len, body))
  406. return -1;
  407. break;
  408. case CONTROL_CMD_AUTHENTICATE:
  409. if (handle_control_authenticate(conn, body_len, body))
  410. return -1;
  411. break;
  412. case CONTROL_CMD_SAVECONF:
  413. if (handle_control_saveconf(conn, body_len, body))
  414. return -1;
  415. break;
  416. case CONTROL_CMD_ERROR:
  417. case CONTROL_CMD_DONE:
  418. case CONTROL_CMD_CONFVALUE:
  419. case CONTROL_CMD_EVENT:
  420. log_fn(LOG_WARN, "Received client-only '%s' command; ignoring.",
  421. control_cmd_to_string(command_type));
  422. send_control_error(conn, ERR_UNRECOGNIZED_TYPE,
  423. "Command type only valid from server to tor client");
  424. break;
  425. default:
  426. log_fn(LOG_WARN, "Received unrecognized command type %d; ignoring.",
  427. (int)command_type);
  428. send_control_error(conn, ERR_UNRECOGNIZED_TYPE,
  429. "Unrecognized command type");
  430. break;
  431. }
  432. tor_free(body);
  433. goto again; /* There might be more data. */
  434. }
  435. /** Something has happened to circuit <b>circ</b>: tell any interested
  436. * control connections. */
  437. int
  438. control_event_circuit_status(circuit_t *circ, circuit_status_event_t tp)
  439. {
  440. char *path, *msg;
  441. size_t path_len;
  442. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
  443. return 0;
  444. tor_assert(circ);
  445. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  446. path = circuit_list_path(circ,0);
  447. path_len = strlen(path);
  448. msg = tor_malloc(1+4+path_len+1); /* event, circid, path, NUL. */
  449. msg[0] = (uint8_t) tp;
  450. set_uint32(msg+1, htonl(circ->global_identifier));
  451. strlcpy(msg+5,path,path_len+1);
  452. send_control_event(EVENT_STREAM_STATUS, (uint16_t)(path_len+6), msg);
  453. tor_free(path);
  454. tor_free(msg);
  455. return 0;
  456. }
  457. /** Something has happened to the stream associated with AP connection
  458. * <b>conn</b>: tell any interested control connections. */
  459. int
  460. control_event_stream_status(connection_t *conn, stream_status_event_t tp)
  461. {
  462. char *msg;
  463. size_t len;
  464. tor_assert(conn->type == CONN_TYPE_AP);
  465. tor_assert(conn->socks_request);
  466. if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
  467. return 0;
  468. len = strlen(conn->socks_request->address);
  469. msg = tor_malloc(5+len+1);
  470. msg[0] = (uint8_t) tp;
  471. set_uint32(msg+1, htonl(conn->s)); /* ???? Is this a security problem? */
  472. strlcpy(msg+5, conn->socks_request->address, len+1);
  473. send_control_event(EVENT_STREAM_STATUS, (uint16_t)(5+len+1), msg);
  474. tor_free(msg);
  475. return 0;
  476. }
  477. /** Something has happened to the OR connection <b>conn</b>: tell any
  478. * interested control connections. */
  479. int
  480. control_event_or_conn_status(connection_t *conn,or_conn_status_event_t tp)
  481. {
  482. char buf[HEX_DIGEST_LEN+3]; /* status, dollar, identity, NUL */
  483. size_t len;
  484. tor_assert(conn->type == CONN_TYPE_OR);
  485. if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
  486. return 0;
  487. buf[0] = (uint8_t)tp;
  488. strlcpy(buf+1,conn->nickname,sizeof(buf)-1);
  489. len = strlen(buf+1);
  490. send_control_event(EVENT_OR_CONN_STATUS, (uint16_t)(len+1), buf);
  491. return 0;
  492. }
  493. /** A second or more has elapsed: tell any interested control
  494. * connections how much bandwidth we used. */
  495. int
  496. control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
  497. {
  498. char buf[8];
  499. if (!EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED))
  500. return 0;
  501. set_uint32(buf, htonl(n_read));
  502. set_uint32(buf+4, htonl(n_written));
  503. send_control_event(EVENT_BANDWIDTH_USED, 8, buf);
  504. return 0;
  505. }
  506. /** We got a log message: tell any interested control connections. */
  507. void
  508. control_event_logmsg(int severity, const char *msg)
  509. {
  510. size_t len;
  511. if (severity > LOG_WARN) /* Less important than warning? ignore for now. */
  512. return;
  513. if (!EVENT_IS_INTERESTING(EVENT_WARNING))
  514. return;
  515. len = strlen(msg);
  516. send_control_event(EVENT_WARNING, (uint16_t)(len+1), msg);
  517. }
  518. /** Choose a random authentication cookie and write it to disk.
  519. * Anybody who can read the cookie from disk will be considered
  520. * authorized to use the control connection. */
  521. int
  522. init_cookie_authentication(int enabled)
  523. {
  524. char fname[512];
  525. if (!enabled)
  526. authentication_cookie_is_set = 0;
  527. tor_snprintf(fname, sizeof(fname), "%s/control_auth_cookie",
  528. get_options()->DataDirectory);
  529. crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
  530. authentication_cookie_is_set = 1;
  531. if (write_bytes_to_file(fname, authentication_cookie,
  532. AUTHENTICATION_COOKIE_LEN, 1)) {
  533. log_fn(LOG_WARN,"Error writing authentication cookie.");
  534. return -1;
  535. }
  536. return 0;
  537. }