connection_or.c 35 KB

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