control.c 18 KB

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