connection_or.c 29 KB

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