connection_or.c 35 KB

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