connection_or.c 26 KB

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