connection_or.c 26 KB

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