connection_or.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char connection_or_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file connection_or.c
  10. * \brief Functions to handle OR connections, TLS handshaking, and
  11. * cells on the network.
  12. **/
  13. #include "or.h"
  14. static int connection_tls_finish_handshake(or_connection_t *conn);
  15. static int connection_or_process_cells_from_inbuf(or_connection_t *conn);
  16. static int connection_or_send_versions(or_connection_t *conn);
  17. static int connection_init_or_handshake_state(or_connection_t *conn,
  18. int started_here);
  19. /**************************************************************/
  20. /** Map from identity digest of connected OR or desired OR to a connection_t
  21. * with that identity digest. If there is more than one such connection_t,
  22. * they form a linked list, with next_with_same_id as the next pointer. */
  23. static digestmap_t *orconn_identity_map = NULL;
  24. /** If conn is listed in orconn_identity_map, remove it, and clear
  25. * conn->identity_digest. Otherwise do nothing. */
  26. void
  27. connection_or_remove_from_identity_map(or_connection_t *conn)
  28. {
  29. or_connection_t *tmp;
  30. tor_assert(conn);
  31. if (!orconn_identity_map)
  32. return;
  33. tmp = digestmap_get(orconn_identity_map, conn->identity_digest);
  34. if (!tmp) {
  35. if (!tor_digest_is_zero(conn->identity_digest)) {
  36. log_warn(LD_BUG, "Didn't find connection on identity map when "
  37. "trying to remove it.");
  38. }
  39. return;
  40. }
  41. if (conn == tmp) {
  42. if (conn->next_with_same_id)
  43. digestmap_set(orconn_identity_map, conn->identity_digest,
  44. conn->next_with_same_id);
  45. else
  46. digestmap_remove(orconn_identity_map, conn->identity_digest);
  47. } else {
  48. while (tmp->next_with_same_id) {
  49. if (tmp->next_with_same_id == conn) {
  50. tmp->next_with_same_id = conn->next_with_same_id;
  51. break;
  52. }
  53. tmp = tmp->next_with_same_id;
  54. }
  55. }
  56. memset(conn->identity_digest, 0, DIGEST_LEN);
  57. conn->next_with_same_id = NULL;
  58. }
  59. /** Remove all entries from the identity-to-orconn map, and clear
  60. * all identities in OR conns.*/
  61. void
  62. connection_or_clear_identity_map(void)
  63. {
  64. smartlist_t *conns = get_connection_array();
  65. SMARTLIST_FOREACH(conns, connection_t *, conn,
  66. {
  67. if (conn->type == CONN_TYPE_OR) {
  68. or_connection_t *or_conn = TO_OR_CONN(conn);
  69. memset(or_conn->identity_digest, 0, DIGEST_LEN);
  70. or_conn->next_with_same_id = NULL;
  71. }
  72. });
  73. if (orconn_identity_map) {
  74. digestmap_free(orconn_identity_map, NULL);
  75. orconn_identity_map = NULL;
  76. }
  77. }
  78. /** Change conn->identity_digest to digest, and add conn into
  79. * orconn_digest_map. */
  80. static void
  81. connection_or_set_identity_digest(or_connection_t *conn, const char *digest)
  82. {
  83. or_connection_t *tmp;
  84. tor_assert(conn);
  85. tor_assert(digest);
  86. if (!orconn_identity_map)
  87. orconn_identity_map = digestmap_new();
  88. if (!memcmp(conn->identity_digest, digest, DIGEST_LEN))
  89. return;
  90. /* If the identity was set previously, remove the old mapping. */
  91. if (! tor_digest_is_zero(conn->identity_digest))
  92. connection_or_remove_from_identity_map(conn);
  93. memcpy(conn->identity_digest, digest, DIGEST_LEN);
  94. /* If we're setting the ID to zero, don't add a mapping. */
  95. if (tor_digest_is_zero(digest))
  96. return;
  97. tmp = digestmap_set(orconn_identity_map, digest, conn);
  98. conn->next_with_same_id = tmp;
  99. #if 1
  100. /* Testing code to check for bugs in representation. */
  101. for (; tmp; tmp = tmp->next_with_same_id) {
  102. tor_assert(!memcmp(tmp->identity_digest, digest, DIGEST_LEN));
  103. tor_assert(tmp != conn);
  104. }
  105. #endif
  106. }
  107. /** Pack the cell_t host-order structure <b>src</b> into network-order
  108. * in the buffer <b>dest</b>. See tor-spec.txt for details about the
  109. * wire format.
  110. *
  111. * Note that this function doesn't touch <b>dst</b>-\>next: the caller
  112. * should set it or clear it as appropriate.
  113. */
  114. void
  115. cell_pack(packed_cell_t *dst, const cell_t *src)
  116. {
  117. char *dest = dst->body;
  118. *(uint16_t*)dest = htons(src->circ_id);
  119. *(uint8_t*)(dest+2) = src->command;
  120. memcpy(dest+3, src->payload, CELL_PAYLOAD_SIZE);
  121. }
  122. /** Unpack the network-order buffer <b>src</b> into a host-order
  123. * cell_t structure <b>dest</b>.
  124. */
  125. static void
  126. cell_unpack(cell_t *dest, const char *src)
  127. {
  128. dest->circ_id = ntohs(*(uint16_t*)(src));
  129. dest->command = *(uint8_t*)(src+2);
  130. memcpy(dest->payload, src+3, CELL_PAYLOAD_SIZE);
  131. }
  132. int
  133. connection_or_reached_eof(or_connection_t *conn)
  134. {
  135. log_info(LD_OR,"OR connection reached EOF. Closing.");
  136. connection_mark_for_close(TO_CONN(conn));
  137. return 0;
  138. }
  139. /** Read conn's inbuf. If the http response from the proxy is all
  140. * here, make sure it's good news, and begin the tls handshake. If
  141. * it's bad news, close the connection and return -1. Else return 0
  142. * and hope for better luck next time.
  143. */
  144. static int
  145. connection_or_read_proxy_response(or_connection_t *or_conn)
  146. {
  147. char *headers;
  148. char *reason=NULL;
  149. int status_code;
  150. time_t date_header;
  151. connection_t *conn = TO_CONN(or_conn);
  152. switch (fetch_from_buf_http(conn->inbuf,
  153. &headers, MAX_HEADERS_SIZE,
  154. NULL, NULL, 10000, 0)) {
  155. case -1: /* overflow */
  156. log_warn(LD_PROTOCOL,
  157. "Your https proxy sent back an oversized response. Closing.");
  158. return -1;
  159. case 0:
  160. log_info(LD_OR,"https proxy response not all here yet. Waiting.");
  161. return 0;
  162. /* case 1, fall through */
  163. }
  164. if (parse_http_response(headers, &status_code, &date_header,
  165. NULL, &reason) < 0) {
  166. log_warn(LD_OR,
  167. "Unparseable headers from proxy (connecting to '%s'). Closing.",
  168. conn->address);
  169. tor_free(headers);
  170. return -1;
  171. }
  172. if (!reason) reason = tor_strdup("[no reason given]");
  173. if (status_code == 200) {
  174. log_info(LD_OR,
  175. "HTTPS connect to '%s' successful! (200 %s) Starting TLS.",
  176. conn->address, escaped(reason));
  177. tor_free(reason);
  178. if (connection_tls_start_handshake(or_conn, 0) < 0) {
  179. /* TLS handshaking error of some kind. */
  180. connection_mark_for_close(conn);
  181. return -1;
  182. }
  183. return 0;
  184. }
  185. /* else, bad news on the status code */
  186. log_warn(LD_OR,
  187. "The https proxy sent back an unexpected status code %d (%s). "
  188. "Closing.",
  189. status_code, escaped(reason));
  190. tor_free(reason);
  191. connection_mark_for_close(conn);
  192. return -1;
  193. }
  194. /** Handle any new bytes that have come in on connection <b>conn</b>.
  195. * If conn is in 'open' state, hand it to
  196. * connection_or_process_cells_from_inbuf()
  197. * (else do nothing).
  198. */
  199. int
  200. connection_or_process_inbuf(or_connection_t *conn)
  201. {
  202. tor_assert(conn);
  203. switch (conn->_base.state) {
  204. case OR_CONN_STATE_PROXY_READING:
  205. return connection_or_read_proxy_response(conn);
  206. case OR_CONN_STATE_OPEN:
  207. return connection_or_process_cells_from_inbuf(conn);
  208. default:
  209. return 0; /* don't do anything */
  210. }
  211. }
  212. /** When adding cells to an OR connection's outbuf, keep adding until the
  213. * outbuf is at least this long, or we run out of cells. */
  214. #define OR_CONN_HIGHWATER (32*1024)
  215. /** Add cells to an OR connection's outbuf whenever the outbuf's data length
  216. * drops below this size. */
  217. #define OR_CONN_LOWWATER (16*1024)
  218. /** Called whenever we have flushed some data on an or_conn: add more data
  219. * from active circuits. */
  220. int
  221. connection_or_flushed_some(or_connection_t *conn)
  222. {
  223. size_t datalen = buf_datalen(conn->_base.outbuf);
  224. /* If we're under the low water mark, add cells until we're just over the
  225. * high water mark. */
  226. if (datalen < OR_CONN_LOWWATER) {
  227. int n = (OR_CONN_HIGHWATER - datalen + CELL_NETWORK_SIZE-1)
  228. / CELL_NETWORK_SIZE;
  229. while (conn->active_circuits && n > 0) {
  230. int flushed = connection_or_flush_from_first_active_circuit(conn, 1);
  231. n -= flushed;
  232. }
  233. }
  234. return 0;
  235. }
  236. /** Connection <b>conn</b> has finished writing and has no bytes left on
  237. * its outbuf.
  238. *
  239. * Otherwise it's in state "open": stop writing and return.
  240. *
  241. * If <b>conn</b> is broken, mark it for close and return -1, else
  242. * return 0.
  243. */
  244. int
  245. connection_or_finished_flushing(or_connection_t *conn)
  246. {
  247. tor_assert(conn);
  248. assert_connection_ok(TO_CONN(conn),0);
  249. switch (conn->_base.state) {
  250. case OR_CONN_STATE_PROXY_FLUSHING:
  251. log_debug(LD_OR,"finished sending CONNECT to proxy.");
  252. conn->_base.state = OR_CONN_STATE_PROXY_READING;
  253. connection_stop_writing(TO_CONN(conn));
  254. break;
  255. case OR_CONN_STATE_OPEN:
  256. connection_stop_writing(TO_CONN(conn));
  257. break;
  258. default:
  259. log_err(LD_BUG,"Called in unexpected state %d.", conn->_base.state);
  260. tor_fragile_assert();
  261. return -1;
  262. }
  263. return 0;
  264. }
  265. /** Connected handler for OR connections: begin the TLS handshake.
  266. */
  267. int
  268. connection_or_finished_connecting(or_connection_t *or_conn)
  269. {
  270. connection_t *conn;
  271. tor_assert(or_conn);
  272. conn = TO_CONN(or_conn);
  273. tor_assert(conn->state == OR_CONN_STATE_CONNECTING);
  274. log_debug(LD_OR,"OR connect() to router at %s:%u finished.",
  275. conn->address,conn->port);
  276. if (get_options()->HttpsProxy) {
  277. char buf[1024];
  278. char addrbuf[INET_NTOA_BUF_LEN];
  279. struct in_addr in;
  280. char *base64_authenticator=NULL;
  281. const char *authenticator = get_options()->HttpsProxyAuthenticator;
  282. in.s_addr = htonl(conn->addr);
  283. tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
  284. if (authenticator) {
  285. base64_authenticator = alloc_http_authenticator(authenticator);
  286. if (!base64_authenticator)
  287. log_warn(LD_OR, "Encoding https authenticator failed");
  288. }
  289. if (base64_authenticator) {
  290. tor_snprintf(buf, sizeof(buf), "CONNECT %s:%d HTTP/1.1\r\n"
  291. "Proxy-Authorization: Basic %s\r\n\r\n", addrbuf,
  292. conn->port, base64_authenticator);
  293. tor_free(base64_authenticator);
  294. } else {
  295. tor_snprintf(buf, sizeof(buf), "CONNECT %s:%d HTTP/1.0\r\n\r\n",
  296. addrbuf, conn->port);
  297. }
  298. connection_write_to_buf(buf, strlen(buf), conn);
  299. conn->state = OR_CONN_STATE_PROXY_FLUSHING;
  300. return 0;
  301. }
  302. if (connection_tls_start_handshake(or_conn, 0) < 0) {
  303. /* TLS handshaking error of some kind. */
  304. connection_mark_for_close(conn);
  305. return -1;
  306. }
  307. return 0;
  308. }
  309. /** If we don't necessarily know the router we're connecting to, but we
  310. * have an addr/port/id_digest, then fill in as much as we can. Start
  311. * by checking to see if this describes a router we know. */
  312. static void
  313. connection_or_init_conn_from_address(or_connection_t *conn,
  314. uint32_t addr, uint16_t port,
  315. const char *id_digest,
  316. int started_here)
  317. {
  318. or_options_t *options = get_options();
  319. routerinfo_t *r = router_get_by_digest(id_digest);
  320. conn->bandwidthrate = (int)options->BandwidthRate;
  321. conn->read_bucket = conn->bandwidthburst = (int)options->BandwidthBurst;
  322. connection_or_set_identity_digest(conn, id_digest);
  323. conn->_base.addr = addr;
  324. conn->_base.port = port;
  325. conn->real_addr = addr;
  326. if (r) {
  327. if (conn->_base.addr == r->addr)
  328. conn->is_canonical = 1;
  329. if (!started_here) {
  330. /* Override the addr/port, so our log messages will make sense.
  331. * This is dangerous, since if we ever try looking up a conn by
  332. * its actual addr/port, we won't remember. Careful! */
  333. /* XXXX020 this is stupid, and it's the reason we need real_addr to
  334. * track is_canonical properly. */
  335. conn->_base.addr = r->addr;
  336. conn->_base.port = r->or_port;
  337. }
  338. conn->nickname = tor_strdup(r->nickname);
  339. tor_free(conn->_base.address);
  340. conn->_base.address = tor_strdup(r->address);
  341. } else {
  342. const char *n;
  343. /* If we're an authoritative directory server, we may know a
  344. * nickname for this router. */
  345. n = dirserv_get_nickname_by_digest(id_digest);
  346. if (n) {
  347. conn->nickname = tor_strdup(n);
  348. } else {
  349. conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
  350. conn->nickname[0] = '$';
  351. base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
  352. conn->identity_digest, DIGEST_LEN);
  353. }
  354. tor_free(conn->_base.address);
  355. conn->_base.address = tor_dup_addr(addr);
  356. }
  357. }
  358. /** Return the best connection of type OR with the
  359. * digest <b>digest</b> that we have, or NULL if we have none.
  360. *
  361. * 1) Don't return it if it's marked for close.
  362. * 2) If there are any open conns, ignore non-open conns.
  363. * 3) If there are any non-obsolete conns, ignore obsolete conns.
  364. * 4) Then if there are any non-empty conns, ignore empty conns.
  365. * 5) Of the remaining conns, prefer newer conns.
  366. */
  367. or_connection_t *
  368. connection_or_get_by_identity_digest(const char *digest)
  369. {
  370. int newer;
  371. or_connection_t *conn, *best=NULL;
  372. if (!orconn_identity_map)
  373. return NULL;
  374. conn = digestmap_get(orconn_identity_map, digest);
  375. for (; conn; conn = conn->next_with_same_id) {
  376. tor_assert(conn->_base.magic == OR_CONNECTION_MAGIC);
  377. tor_assert(conn->_base.type == CONN_TYPE_OR);
  378. tor_assert(!memcmp(conn->identity_digest, digest, DIGEST_LEN));
  379. if (conn->_base.marked_for_close)
  380. continue;
  381. if (!best) {
  382. best = conn; /* whatever it is, it's better than nothing. */
  383. continue;
  384. }
  385. if (best->_base.state == OR_CONN_STATE_OPEN &&
  386. conn->_base.state != OR_CONN_STATE_OPEN)
  387. continue; /* avoid non-open conns if we can */
  388. newer = best->_base.timestamp_created < conn->_base.timestamp_created;
  389. if (!best->_base.or_is_obsolete && conn->_base.or_is_obsolete)
  390. continue; /* We never prefer obsolete over non-obsolete connections. */
  391. if (
  392. /* We prefer non-obsolete connections: */
  393. (best->_base.or_is_obsolete && !conn->_base.or_is_obsolete) ||
  394. /* If both have circuits we prefer the newer: */
  395. (best->n_circuits && conn->n_circuits && newer) ||
  396. /* If neither has circuits we prefer the newer: */
  397. (!best->n_circuits && !conn->n_circuits && newer) ||
  398. /* We prefer connections with circuits: */
  399. (!best->n_circuits && conn->n_circuits)) {
  400. best = conn;
  401. };
  402. }
  403. return best;
  404. }
  405. /** Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
  406. * handshake with an OR with identity digest <b>id_digest</b>.
  407. *
  408. * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
  409. * return that connection. If the connect() is in progress, set the
  410. * new conn's state to 'connecting' and return it. If connect() succeeds,
  411. * call connection_tls_start_handshake() on it.
  412. *
  413. * This function is called from router_retry_connections(), for
  414. * ORs connecting to ORs, and circuit_establish_circuit(), for
  415. * OPs connecting to ORs.
  416. *
  417. * Return the launched conn, or NULL if it failed.
  418. */
  419. or_connection_t *
  420. connection_or_connect(uint32_t addr, uint16_t port, const char *id_digest)
  421. {
  422. or_connection_t *conn;
  423. or_options_t *options = get_options();
  424. tor_assert(id_digest);
  425. if (server_mode(options) && router_digest_is_me(id_digest)) {
  426. log_info(LD_PROTOCOL,"Client asked me to connect to myself. Refusing.");
  427. return NULL;
  428. }
  429. conn = TO_OR_CONN(connection_new(CONN_TYPE_OR, AF_INET));
  430. /* set up conn so it's got all the data we need to remember */
  431. connection_or_init_conn_from_address(conn, addr, port, id_digest, 1);
  432. conn->_base.state = OR_CONN_STATE_CONNECTING;
  433. control_event_or_conn_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
  434. if (options->HttpsProxy) {
  435. /* we shouldn't connect directly. use the https proxy instead. */
  436. addr = options->HttpsProxyAddr;
  437. port = options->HttpsProxyPort;
  438. }
  439. switch (connection_connect(TO_CONN(conn), conn->_base.address, addr, port)) {
  440. case -1:
  441. /* If the connection failed immediately, and we're using
  442. * an https proxy, our https proxy is down. Don't blame the
  443. * Tor server. */
  444. if (!options->HttpsProxy) {
  445. entry_guard_register_connect_status(conn->identity_digest, 0,
  446. time(NULL));
  447. router_set_status(conn->identity_digest, 0);
  448. }
  449. control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED,
  450. END_OR_CONN_REASON_TCP_REFUSED);
  451. connection_free(TO_CONN(conn));
  452. return NULL;
  453. case 0:
  454. connection_watch_events(TO_CONN(conn), EV_READ | EV_WRITE);
  455. /* writable indicates finish, readable indicates broken link,
  456. error indicates broken link on windows */
  457. return conn;
  458. /* case 1: fall through */
  459. }
  460. if (connection_or_finished_connecting(conn) < 0) {
  461. /* already marked for close */
  462. return NULL;
  463. }
  464. return conn;
  465. }
  466. /** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
  467. * we initiated the connection, else it's 1.
  468. *
  469. * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and
  470. * pass <b>conn</b> to connection_tls_continue_handshake().
  471. *
  472. * Return -1 if <b>conn</b> is broken, else return 0.
  473. */
  474. int
  475. connection_tls_start_handshake(or_connection_t *conn, int receiving)
  476. {
  477. conn->_base.state = OR_CONN_STATE_TLS_HANDSHAKING;
  478. conn->tls = tor_tls_new(conn->_base.s, receiving);
  479. if (!conn->tls) {
  480. log_warn(LD_BUG,"tor_tls_new failed. Closing.");
  481. return -1;
  482. }
  483. connection_start_reading(TO_CONN(conn));
  484. log_debug(LD_OR,"starting TLS handshake on fd %d", conn->_base.s);
  485. note_crypto_pk_op(receiving ? TLS_HANDSHAKE_S : TLS_HANDSHAKE_C);
  486. if (connection_tls_continue_handshake(conn) < 0) {
  487. return -1;
  488. }
  489. return 0;
  490. }
  491. /** Move forward with the tls handshake. If it finishes, hand
  492. * <b>conn</b> to connection_tls_finish_handshake().
  493. *
  494. * Return -1 if <b>conn</b> is broken, else return 0.
  495. */
  496. int
  497. connection_tls_continue_handshake(or_connection_t *conn)
  498. {
  499. check_no_tls_errors();
  500. switch (tor_tls_handshake(conn->tls)) {
  501. CASE_TOR_TLS_ERROR_ANY:
  502. log_info(LD_OR,"tls error. breaking connection.");
  503. return -1;
  504. case TOR_TLS_DONE:
  505. return connection_tls_finish_handshake(conn);
  506. case TOR_TLS_WANTWRITE:
  507. connection_start_writing(TO_CONN(conn));
  508. log_debug(LD_OR,"wanted write");
  509. return 0;
  510. case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
  511. log_debug(LD_OR,"wanted read");
  512. return 0;
  513. case TOR_TLS_CLOSE:
  514. log_info(LD_OR,"tls closed. breaking connection.");
  515. return -1;
  516. }
  517. return 0;
  518. }
  519. /** Return 1 if we initiated this connection, or 0 if it started
  520. * out as an incoming connection.
  521. */
  522. int
  523. connection_or_nonopen_was_started_here(or_connection_t *conn)
  524. {
  525. tor_assert(conn->_base.type == CONN_TYPE_OR);
  526. if (!conn->tls)
  527. return 1; /* it's still in proxy states or something */
  528. return !tor_tls_is_server(conn->tls);
  529. }
  530. /** <b>Conn</b> just completed its handshake. Return 0 if all is well, and
  531. * return -1 if he is lying, broken, or otherwise something is wrong.
  532. *
  533. * If we initiated this connection (<b>started_here</b> is true), make sure
  534. * the other side sent sent a correctly formed certificate. If I initiated the
  535. * connection, make sure it's the right guy.
  536. *
  537. * Otherwise (if we _didn't_ initiate this connection), it's okay for
  538. * the certificate to be weird or absent.
  539. *
  540. * If we return 0, and the certificate is as expected, write a hash of the
  541. * identity key into digest_rcvd, which must have DIGEST_LEN space in it. (If
  542. * we return -1 this buffer is undefined.) If the certificate is invalid
  543. * or missing on an incoming connection, we return 0 and set digest_rcvd to
  544. * DIGEST_LEN 0 bytes.
  545. *
  546. * As side effects,
  547. * 1) Set conn->circ_id_type according to tor-spec.txt.
  548. * 2) If we're an authdirserver and we initiated the connection: drop all
  549. * descriptors that claim to be on that IP/port but that aren't
  550. * this guy; and note that this guy is reachable.
  551. */
  552. static int
  553. connection_or_check_valid_handshake(or_connection_t *conn, int started_here,
  554. char *digest_rcvd)
  555. {
  556. crypto_pk_env_t *identity_rcvd=NULL;
  557. or_options_t *options = get_options();
  558. int severity = server_mode(options) ? LOG_PROTOCOL_WARN : LOG_WARN;
  559. const char *safe_address =
  560. started_here ? conn->_base.address : safe_str(conn->_base.address);
  561. const char *conn_type = started_here ? "outgoing" : "incoming";
  562. int has_cert = 0, has_identity = 0;
  563. check_no_tls_errors();
  564. has_cert = tor_tls_peer_has_cert(conn->tls);
  565. if (started_here && !has_cert) {
  566. log_info(LD_PROTOCOL,"Tried connecting to router at %s:%d, but it didn't "
  567. "send a cert! Closing.",
  568. safe_address, conn->_base.port);
  569. return -1;
  570. } else if (!has_cert) {
  571. log_debug(LD_PROTOCOL,"Got incoming connection with no certificate. "
  572. "That's ok.");
  573. }
  574. check_no_tls_errors();
  575. if (has_cert) {
  576. int v = tor_tls_verify_v1(started_here?severity:LOG_INFO,
  577. conn->tls, &identity_rcvd);
  578. if (started_here && v<0) {
  579. log_fn(severity,LD_OR,"Tried connecting to router at %s:%d: It"
  580. " has a cert but it's invalid. Closing.",
  581. safe_address, conn->_base.port);
  582. return -1;
  583. } else if (v<0) {
  584. log_info(LD_PROTOCOL,"Incoming connection gave us an invalid cert "
  585. "chain; ignoring.");
  586. } else {
  587. log_debug(LD_OR,"The certificate seems to be valid on %s connection "
  588. "with %s:%d", conn_type, safe_address, conn->_base.port);
  589. }
  590. check_no_tls_errors();
  591. }
  592. if (identity_rcvd) {
  593. has_identity=1;
  594. crypto_pk_get_digest(identity_rcvd, digest_rcvd);
  595. if (crypto_pk_cmp_keys(get_identity_key(), identity_rcvd)<0) {
  596. conn->circ_id_type = CIRC_ID_TYPE_LOWER;
  597. } else {
  598. conn->circ_id_type = CIRC_ID_TYPE_HIGHER;
  599. }
  600. crypto_free_pk_env(identity_rcvd);
  601. } else {
  602. memset(digest_rcvd, 0, DIGEST_LEN);
  603. conn->circ_id_type = CIRC_ID_TYPE_NEITHER;
  604. }
  605. if (started_here && tor_digest_is_zero(conn->identity_digest)) {
  606. memcpy(conn->identity_digest, digest_rcvd, DIGEST_LEN);
  607. tor_free(conn->nickname);
  608. conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
  609. conn->nickname[0] = '$';
  610. base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
  611. conn->identity_digest, DIGEST_LEN);
  612. log_info(LD_OR, "Connected to router %s at %s:%d without knowing "
  613. "its key. Hoping for the best.",
  614. conn->nickname, conn->_base.address, conn->_base.port);
  615. }
  616. if (started_here) {
  617. int as_advertised = 1;
  618. tor_assert(has_cert);
  619. tor_assert(has_identity);
  620. if (memcmp(digest_rcvd, conn->identity_digest, DIGEST_LEN)) {
  621. /* I was aiming for a particular digest. I didn't get it! */
  622. char seen[HEX_DIGEST_LEN+1];
  623. char expected[HEX_DIGEST_LEN+1];
  624. base16_encode(seen, sizeof(seen), digest_rcvd, DIGEST_LEN);
  625. base16_encode(expected, sizeof(expected), conn->identity_digest,
  626. DIGEST_LEN);
  627. log_fn(severity, LD_OR,
  628. "Tried connecting to router at %s:%d, but identity key was not "
  629. "as expected: wanted %s but got %s.",
  630. conn->_base.address, conn->_base.port, expected, seen);
  631. entry_guard_register_connect_status(conn->identity_digest,0,time(NULL));
  632. router_set_status(conn->identity_digest, 0);
  633. control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED,
  634. END_OR_CONN_REASON_OR_IDENTITY);
  635. as_advertised = 0;
  636. }
  637. if (authdir_mode_tests_reachability(options)) {
  638. /* We initiated this connection to address:port. Drop all routers
  639. * with the same address:port and a different key.
  640. */
  641. dirserv_orconn_tls_done(conn->_base.address, conn->_base.port,
  642. digest_rcvd, as_advertised);
  643. }
  644. if (!as_advertised)
  645. return -1;
  646. }
  647. return 0;
  648. }
  649. /** The tls handshake is finished.
  650. *
  651. * Make sure we are happy with the person we just handshaked with.
  652. *
  653. * If he initiated the connection, make sure he's not already connected,
  654. * then initialize conn from the information in router.
  655. *
  656. * If all is successful, call circuit_n_conn_done() to handle events
  657. * that have been pending on the <tls handshake completion. Also set the
  658. * directory to be dirty (only matters if I'm an authdirserver).
  659. */
  660. static int
  661. connection_tls_finish_handshake(or_connection_t *conn)
  662. {
  663. char digest_rcvd[DIGEST_LEN];
  664. int started_here = connection_or_nonopen_was_started_here(conn);
  665. log_debug(LD_OR,"tls handshake done. verifying.");
  666. /* V1 only XXXX020 */
  667. if (connection_or_check_valid_handshake(conn, started_here, digest_rcvd) < 0)
  668. return -1;
  669. if (!started_here) { /* V1 only XXXX020 */
  670. connection_or_init_conn_from_address(conn,conn->_base.addr,
  671. conn->_base.port, digest_rcvd, 0);
  672. }
  673. directory_set_dirty();
  674. if (tor_tls_used_v1_handshake(conn->tls)) {
  675. conn->link_proto = 1;
  676. return connection_or_set_state_open(conn);
  677. } else {
  678. conn->_base.state = OR_CONN_STATE_OR_HANDSHAKING;
  679. if (connection_init_or_handshake_state(conn, started_here) < 0)
  680. return -1;
  681. return connection_or_send_versions(conn);
  682. }
  683. }
  684. /** DOCDOC */
  685. static int
  686. connection_init_or_handshake_state(or_connection_t *conn, int started_here)
  687. {
  688. or_handshake_state_t *s;
  689. s = conn->handshake_state = tor_malloc_zero(sizeof(or_handshake_state_t));
  690. s->started_here = started_here ? 1 : 0;
  691. if (tor_tls_get_random_values(conn->tls,
  692. conn->handshake_state->client_random,
  693. conn->handshake_state->server_random) < 0)
  694. return -1;
  695. if (started_here) {
  696. if (tor_tls_get_cert_digests(conn->tls,
  697. s->client_cert_digest,
  698. s->server_cert_digest)<0)
  699. return -1;
  700. } else {
  701. if (tor_tls_get_cert_digests(conn->tls,
  702. s->server_cert_digest,
  703. s->client_cert_digest)<0)
  704. return -1;
  705. }
  706. return 0;
  707. }
  708. /** DOCDOC */
  709. void
  710. or_handshake_state_free(or_handshake_state_t *state)
  711. {
  712. tor_assert(state);
  713. if (state->signing_key)
  714. crypto_free_pk_env(state->signing_key);
  715. memset(state, 0xBE, sizeof(or_handshake_state_t));
  716. tor_free(state);
  717. }
  718. /**DOCDOC*/
  719. int
  720. connection_or_set_state_open(or_connection_t *conn)
  721. {
  722. int started_here = connection_or_nonopen_was_started_here(conn);
  723. conn->_base.state = OR_CONN_STATE_OPEN;
  724. control_event_or_conn_status(conn, OR_CONN_EVENT_CONNECTED, 0);
  725. if (started_here) {
  726. rep_hist_note_connect_succeeded(conn->identity_digest, time(NULL));
  727. if (entry_guard_register_connect_status(conn->identity_digest, 1,
  728. time(NULL)) < 0) {
  729. /* pending circs get closed in circuit_about_to_close_connection() */
  730. return -1;
  731. }
  732. router_set_status(conn->identity_digest, 1);
  733. }
  734. connection_watch_events(TO_CONN(conn), EV_READ);
  735. circuit_n_conn_done(conn, 1); /* send the pending creates, if any. */
  736. return 0;
  737. }
  738. /** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s outbuf.
  739. * For cells that use or affect a circuit, this should only be called by
  740. * connection_or_flush_from_first_active_circuit()
  741. */
  742. void
  743. connection_or_write_cell_to_buf(const cell_t *cell, or_connection_t *conn)
  744. {
  745. packed_cell_t networkcell;
  746. tor_assert(cell);
  747. tor_assert(conn);
  748. cell_pack(&networkcell, cell);
  749. connection_write_to_buf(networkcell.body, CELL_NETWORK_SIZE, TO_CONN(conn));
  750. }
  751. /** Process cells from <b>conn</b>'s inbuf.
  752. *
  753. * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
  754. * and hand it to command_process_cell().
  755. *
  756. * Always return 0.
  757. */
  758. static int
  759. connection_or_process_cells_from_inbuf(or_connection_t *conn)
  760. {
  761. char buf[CELL_NETWORK_SIZE];
  762. cell_t cell;
  763. loop:
  764. log_debug(LD_OR,
  765. "%d: starting, inbuf_datalen %d (%d pending in tls object).",
  766. conn->_base.s,(int)buf_datalen(conn->_base.inbuf),
  767. tor_tls_get_pending_bytes(conn->tls));
  768. if (buf_datalen(conn->_base.inbuf) < CELL_NETWORK_SIZE) /* whole response
  769. available? */
  770. return 0; /* not yet */
  771. connection_fetch_from_buf(buf, CELL_NETWORK_SIZE, TO_CONN(conn));
  772. /* retrieve cell info from buf (create the host-order struct from the
  773. * network-order string) */
  774. cell_unpack(&cell, buf);
  775. command_process_cell(&cell, conn);
  776. goto loop; /* process the remainder of the buffer */
  777. }
  778. /** Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
  779. * onto OR connection <b>conn</b>. Don't perform range-checking on reason:
  780. * we may want to propagate reasons from other cells.
  781. *
  782. * Return 0.
  783. */
  784. int
  785. connection_or_send_destroy(uint16_t circ_id, or_connection_t *conn, int reason)
  786. {
  787. cell_t cell;
  788. tor_assert(conn);
  789. memset(&cell, 0, sizeof(cell_t));
  790. cell.circ_id = circ_id;
  791. cell.command = CELL_DESTROY;
  792. cell.payload[0] = (uint8_t) reason;
  793. log_debug(LD_OR,"Sending destroy (circID %d).", circ_id);
  794. #if 0
  795. /* XXXX020 Actually, don't kill the cell queue: it may have data that we're
  796. * waiting to flush. We need to do something more sensible here. */
  797. /* Clear the cell queue on the circuit, so that our destroy cell will
  798. * be the very next thing written.*/
  799. circ = circuit_get_by_circid_orconn(circ_id, conn);
  800. circuit_clear_cell_queue(circ, conn);
  801. #endif
  802. connection_or_write_cell_to_buf(&cell, conn);
  803. return 0;
  804. }
  805. /** DOCDOC */
  806. static int
  807. connection_or_send_versions(or_connection_t *conn)
  808. {
  809. cell_t cell;
  810. uint8_t versions[] = { 1 };
  811. int n_versions = sizeof(versions) / sizeof(uint8_t);
  812. int i;
  813. tor_assert(conn->handshake_state &&
  814. !conn->handshake_state->sent_versions_at);
  815. memset(&cell, 0, sizeof(cell_t));
  816. cell.command = CELL_VERSIONS;
  817. set_uint16(cell.payload, htons(n_versions));
  818. for (i = 0; i < n_versions; ++i) {
  819. uint8_t v = versions[i];
  820. tor_assert(v > 0 && v < 128);
  821. cell.payload[2+i] = v;
  822. }
  823. connection_or_write_cell_to_buf(&cell, conn);
  824. conn->handshake_state->sent_versions_at = time(NULL);
  825. return 0;
  826. }
  827. /** DOCDOC */
  828. int
  829. connection_or_send_netinfo(or_connection_t *conn)
  830. {
  831. cell_t cell;
  832. time_t now = time(NULL);
  833. routerinfo_t *me;
  834. memset(&cell, 0, sizeof(cell_t));
  835. cell.command = CELL_NETINFO;
  836. /* Their address. */
  837. set_uint32(cell.payload, htonl(now));
  838. cell.payload[4] = RESOLVED_TYPE_IPV4;
  839. cell.payload[5] = 4;
  840. set_uint32(cell.payload+6, htonl(conn->_base.addr));
  841. /* My address. */
  842. if ((me = router_get_my_routerinfo())) {
  843. cell.payload[10] = 1; /* only one address is supported. */
  844. cell.payload[11] = RESOLVED_TYPE_IPV4;
  845. cell.payload[12] = 4;
  846. set_uint32(cell.payload+13, htonl(me->addr));
  847. } else {
  848. cell.payload[10] = 0;
  849. }
  850. connection_or_write_cell_to_buf(&cell, conn);
  851. return 0;
  852. }
  853. #define LINK_AUTH_STRING "Tor initiator certificate verification"
  854. /** DOCDOC */
  855. int
  856. connection_or_compute_link_auth_hmac(or_connection_t *conn,
  857. char *hmac_out)
  858. {
  859. char buf[64 + 2*TOR_TLS_RANDOM_LEN + 2*DIGEST_LEN];
  860. char *cp;
  861. or_handshake_state_t *s;
  862. tor_assert(conn);
  863. tor_assert(conn->handshake_state);
  864. tor_assert(conn->tls);
  865. s = conn->handshake_state;
  866. /* Fill the buffer. */
  867. strlcpy(buf, LINK_AUTH_STRING, sizeof(buf));
  868. cp = buf+strlen(buf);
  869. ++cp; /* Skip the NUL */
  870. memcpy(cp, s->client_random, TOR_TLS_RANDOM_LEN);
  871. cp += TOR_TLS_RANDOM_LEN;
  872. memcpy(cp, s->server_random, TOR_TLS_RANDOM_LEN);
  873. cp += TOR_TLS_RANDOM_LEN;
  874. memcpy(cp, s->client_cert_digest, DIGEST_LEN);
  875. cp += DIGEST_LEN;
  876. memcpy(cp, s->server_cert_digest, DIGEST_LEN);
  877. cp += DIGEST_LEN;
  878. tor_assert(cp < buf+sizeof(buf));
  879. if (tor_tls_hmac_with_master_secret(conn->tls, hmac_out, buf, cp-buf) < 0)
  880. return -1;
  881. return 0;
  882. }