connection_or.c 26 KB

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