connection_or.c 26 KB

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