connection_or.c 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  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. set_uint16(hdr_out, htons(cell->circ_id));
  143. set_uint8(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. time_t now = time(NULL);
  258. /* If we're under the low water mark, add cells until we're just over the
  259. * high water mark. */
  260. if (datalen < OR_CONN_LOWWATER) {
  261. ssize_t n = (OR_CONN_HIGHWATER - datalen + CELL_NETWORK_SIZE-1)
  262. / CELL_NETWORK_SIZE;
  263. while (conn->active_circuits && n > 0) {
  264. int flushed;
  265. flushed = connection_or_flush_from_first_active_circuit(conn, 1, now);
  266. n -= flushed;
  267. }
  268. }
  269. return 0;
  270. }
  271. /** Connection <b>conn</b> has finished writing and has no bytes left on
  272. * its outbuf.
  273. *
  274. * Otherwise it's in state "open": stop writing and return.
  275. *
  276. * If <b>conn</b> is broken, mark it for close and return -1, else
  277. * return 0.
  278. */
  279. int
  280. connection_or_finished_flushing(or_connection_t *conn)
  281. {
  282. tor_assert(conn);
  283. assert_connection_ok(TO_CONN(conn),0);
  284. switch (conn->_base.state) {
  285. case OR_CONN_STATE_PROXY_FLUSHING:
  286. log_debug(LD_OR,"finished sending CONNECT to proxy.");
  287. conn->_base.state = OR_CONN_STATE_PROXY_READING;
  288. connection_stop_writing(TO_CONN(conn));
  289. break;
  290. case OR_CONN_STATE_OPEN:
  291. case OR_CONN_STATE_OR_HANDSHAKING:
  292. connection_stop_writing(TO_CONN(conn));
  293. break;
  294. default:
  295. log_err(LD_BUG,"Called in unexpected state %d.", conn->_base.state);
  296. tor_fragile_assert();
  297. return -1;
  298. }
  299. return 0;
  300. }
  301. /** Connected handler for OR connections: begin the TLS handshake.
  302. */
  303. int
  304. connection_or_finished_connecting(or_connection_t *or_conn)
  305. {
  306. connection_t *conn;
  307. tor_assert(or_conn);
  308. conn = TO_CONN(or_conn);
  309. tor_assert(conn->state == OR_CONN_STATE_CONNECTING);
  310. log_debug(LD_OR,"OR connect() to router at %s:%u finished.",
  311. conn->address,conn->port);
  312. control_event_bootstrap(BOOTSTRAP_STATUS_HANDSHAKE, 0);
  313. if (get_options()->HttpsProxy) {
  314. char buf[1024];
  315. char *base64_authenticator=NULL;
  316. const char *authenticator = get_options()->HttpsProxyAuthenticator;
  317. if (authenticator) {
  318. base64_authenticator = alloc_http_authenticator(authenticator);
  319. if (!base64_authenticator)
  320. log_warn(LD_OR, "Encoding https authenticator failed");
  321. }
  322. if (base64_authenticator) {
  323. tor_snprintf(buf, sizeof(buf), "CONNECT %s:%d HTTP/1.1\r\n"
  324. "Proxy-Authorization: Basic %s\r\n\r\n",
  325. fmt_addr(&conn->addr),
  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. fmt_addr(&conn->addr), 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. const tor_addr_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.port = port;
  358. tor_addr_copy(&conn->_base.addr, addr);
  359. tor_addr_copy(&conn->real_addr, addr);
  360. if (r) {
  361. /* XXXX proposal 118 will make this more complex. */
  362. if (tor_addr_eq_ipv4h(&conn->_base.addr, r->addr))
  363. conn->is_canonical = 1;
  364. if (!started_here) {
  365. /* Override the addr/port, so our log messages will make sense.
  366. * This is dangerous, since if we ever try looking up a conn by
  367. * its actual addr/port, we won't remember. Careful! */
  368. /* XXXX arma: this is stupid, and it's the reason we need real_addr
  369. * to track is_canonical properly. What requires it? */
  370. /* XXXX <arma> i believe the reason we did this, originally, is because
  371. * we wanted to log what OR a connection was to, and if we logged the
  372. * right IP address and port 56244, that wouldn't be as helpful. now we
  373. * log the "right" port too, so we know if it's moria1 or moria2.
  374. */
  375. tor_addr_from_ipv4h(&conn->_base.addr, r->addr);
  376. conn->_base.port = r->or_port;
  377. }
  378. conn->nickname = tor_strdup(r->nickname);
  379. tor_free(conn->_base.address);
  380. conn->_base.address = tor_strdup(r->address);
  381. } else {
  382. const char *n;
  383. /* If we're an authoritative directory server, we may know a
  384. * nickname for this router. */
  385. n = dirserv_get_nickname_by_digest(id_digest);
  386. if (n) {
  387. conn->nickname = tor_strdup(n);
  388. } else {
  389. conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
  390. conn->nickname[0] = '$';
  391. base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
  392. conn->identity_digest, DIGEST_LEN);
  393. }
  394. tor_free(conn->_base.address);
  395. conn->_base.address = tor_dup_addr(addr);
  396. }
  397. }
  398. /** Return the best connection of type OR with the
  399. * digest <b>digest</b> that we have, or NULL if we have none.
  400. *
  401. * 1) Don't return it if it's marked for close.
  402. * 2) If there are any open conns, ignore non-open conns.
  403. * 3) If there are any non-obsolete conns, ignore obsolete conns.
  404. * 4) Then if there are any non-empty conns, ignore empty conns.
  405. * 5) Of the remaining conns, prefer newer conns.
  406. */
  407. or_connection_t *
  408. connection_or_get_by_identity_digest(const char *digest)
  409. {
  410. int newer;
  411. or_connection_t *conn, *best=NULL;
  412. if (!orconn_identity_map)
  413. return NULL;
  414. conn = digestmap_get(orconn_identity_map, digest);
  415. for (; conn; conn = conn->next_with_same_id) {
  416. tor_assert(conn->_base.magic == OR_CONNECTION_MAGIC);
  417. tor_assert(conn->_base.type == CONN_TYPE_OR);
  418. tor_assert(!memcmp(conn->identity_digest, digest, DIGEST_LEN));
  419. if (conn->_base.marked_for_close)
  420. continue;
  421. if (!best) {
  422. best = conn; /* whatever it is, it's better than nothing. */
  423. continue;
  424. }
  425. if (best->_base.state == OR_CONN_STATE_OPEN &&
  426. conn->_base.state != OR_CONN_STATE_OPEN)
  427. continue; /* avoid non-open conns if we can */
  428. newer = best->_base.timestamp_created < conn->_base.timestamp_created;
  429. if (best->is_canonical && !conn->is_canonical)
  430. continue; /* A canonical connection is best. */
  431. if (!best->is_bad_for_new_circs && conn->is_bad_for_new_circs)
  432. continue; /* We never prefer obsolete over non-obsolete connections. */
  433. if (
  434. /* We prefer canonical connections: */
  435. (!best->is_canonical && conn->is_canonical) ||
  436. /* We prefer non-obsolete connections: */
  437. (best->is_bad_for_new_circs && !conn->is_bad_for_new_circs) ||
  438. /* If both have circuits we prefer the newer: */
  439. (best->n_circuits && conn->n_circuits && newer) ||
  440. /* If neither has circuits we prefer the newer: */
  441. (!best->n_circuits && !conn->n_circuits && newer) ||
  442. /* We prefer connections with circuits: */
  443. (!best->n_circuits && conn->n_circuits)) {
  444. best = conn;
  445. };
  446. }
  447. return best;
  448. }
  449. /** <b>conn</b> is in the 'connecting' state, and it failed to complete
  450. * a TCP connection. Send notifications appropriately.
  451. *
  452. * <b>reason</b> specifies the or_conn_end_reason for the failure;
  453. * <b>msg</b> specifies the strerror-style error message.
  454. */
  455. void
  456. connection_or_connect_failed(or_connection_t *conn,
  457. int reason, const char *msg)
  458. {
  459. control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED, reason);
  460. if (!authdir_mode_tests_reachability(get_options()))
  461. control_event_bootstrap_problem(msg, reason);
  462. }
  463. /** Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
  464. * handshake with an OR with identity digest <b>id_digest</b>.
  465. *
  466. * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
  467. * return that connection. If the connect() is in progress, set the
  468. * new conn's state to 'connecting' and return it. If connect() succeeds,
  469. * call connection_tls_start_handshake() on it.
  470. *
  471. * This function is called from router_retry_connections(), for
  472. * ORs connecting to ORs, and circuit_establish_circuit(), for
  473. * OPs connecting to ORs.
  474. *
  475. * Return the launched conn, or NULL if it failed.
  476. */
  477. or_connection_t *
  478. connection_or_connect(const tor_addr_t *_addr, uint16_t port,
  479. const char *id_digest)
  480. {
  481. or_connection_t *conn;
  482. or_options_t *options = get_options();
  483. int socket_error = 0;
  484. tor_addr_t addr;
  485. tor_assert(_addr);
  486. tor_assert(id_digest);
  487. tor_addr_copy(&addr, _addr);
  488. if (server_mode(options) && router_digest_is_me(id_digest)) {
  489. log_info(LD_PROTOCOL,"Client asked me to connect to myself. Refusing.");
  490. return NULL;
  491. }
  492. conn = or_connection_new(AF_INET);
  493. /* set up conn so it's got all the data we need to remember */
  494. connection_or_init_conn_from_address(conn, &addr, port, id_digest, 1);
  495. conn->_base.state = OR_CONN_STATE_CONNECTING;
  496. control_event_or_conn_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
  497. if (options->HttpsProxy) {
  498. /* we shouldn't connect directly. use the https proxy instead. */
  499. tor_addr_from_ipv4h(&addr, options->HttpsProxyAddr);
  500. port = options->HttpsProxyPort;
  501. }
  502. switch (connection_connect(TO_CONN(conn), conn->_base.address,
  503. &addr, port, &socket_error)) {
  504. case -1:
  505. /* If the connection failed immediately, and we're using
  506. * an https proxy, our https proxy is down. Don't blame the
  507. * Tor server. */
  508. if (!options->HttpsProxy) {
  509. entry_guard_register_connect_status(conn->identity_digest, 0,
  510. time(NULL));
  511. router_set_status(conn->identity_digest, 0);
  512. }
  513. connection_or_connect_failed(conn,
  514. errno_to_orconn_end_reason(socket_error),
  515. tor_socket_strerror(socket_error));
  516. connection_free(TO_CONN(conn));
  517. return NULL;
  518. case 0:
  519. connection_watch_events(TO_CONN(conn), EV_READ | EV_WRITE);
  520. /* writable indicates finish, readable indicates broken link,
  521. error indicates broken link on windows */
  522. return conn;
  523. /* case 1: fall through */
  524. }
  525. if (connection_or_finished_connecting(conn) < 0) {
  526. /* already marked for close */
  527. return NULL;
  528. }
  529. return conn;
  530. }
  531. /** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
  532. * we initiated the connection, else it's 1.
  533. *
  534. * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and
  535. * pass <b>conn</b> to connection_tls_continue_handshake().
  536. *
  537. * Return -1 if <b>conn</b> is broken, else return 0.
  538. */
  539. int
  540. connection_tls_start_handshake(or_connection_t *conn, int receiving)
  541. {
  542. conn->_base.state = OR_CONN_STATE_TLS_HANDSHAKING;
  543. conn->tls = tor_tls_new(conn->_base.s, receiving);
  544. tor_tls_set_logged_address(conn->tls, escaped_safe_str(conn->_base.address));
  545. if (!conn->tls) {
  546. log_warn(LD_BUG,"tor_tls_new failed. Closing.");
  547. return -1;
  548. }
  549. connection_start_reading(TO_CONN(conn));
  550. log_debug(LD_OR,"starting TLS handshake on fd %d", conn->_base.s);
  551. note_crypto_pk_op(receiving ? TLS_HANDSHAKE_S : TLS_HANDSHAKE_C);
  552. if (connection_tls_continue_handshake(conn) < 0) {
  553. return -1;
  554. }
  555. return 0;
  556. }
  557. /** Invoked on the server side from inside tor_tls_read() when the server
  558. * gets a successful TLS renegotiation from the client. */
  559. static void
  560. connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn)
  561. {
  562. or_connection_t *conn = _conn;
  563. (void)tls;
  564. /* Don't invoke this again. */
  565. tor_tls_set_renegotiate_callback(tls, NULL, NULL);
  566. if (connection_tls_finish_handshake(conn) < 0) {
  567. /* XXXX_TLS double-check that it's ok to do this from inside read. */
  568. /* XXXX_TLS double-check that this verifies certificates. */
  569. connection_mark_for_close(TO_CONN(conn));
  570. }
  571. }
  572. /** Move forward with the tls handshake. If it finishes, hand
  573. * <b>conn</b> to connection_tls_finish_handshake().
  574. *
  575. * Return -1 if <b>conn</b> is broken, else return 0.
  576. */
  577. int
  578. connection_tls_continue_handshake(or_connection_t *conn)
  579. {
  580. int result;
  581. check_no_tls_errors();
  582. again:
  583. if (conn->_base.state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
  584. // log_notice(LD_OR, "Renegotiate with %p", conn->tls);
  585. result = tor_tls_renegotiate(conn->tls);
  586. // log_notice(LD_OR, "Result: %d", result);
  587. } else {
  588. tor_assert(conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING);
  589. // log_notice(LD_OR, "Continue handshake with %p", conn->tls);
  590. result = tor_tls_handshake(conn->tls);
  591. // log_notice(LD_OR, "Result: %d", result);
  592. }
  593. switch (result) {
  594. CASE_TOR_TLS_ERROR_ANY:
  595. log_info(LD_OR,"tls error [%s]. breaking connection.",
  596. tor_tls_err_to_string(result));
  597. return -1;
  598. case TOR_TLS_DONE:
  599. if (! tor_tls_used_v1_handshake(conn->tls)) {
  600. if (!tor_tls_is_server(conn->tls)) {
  601. if (conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING) {
  602. // log_notice(LD_OR,"Done. state was TLS_HANDSHAKING.");
  603. conn->_base.state = OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING;
  604. goto again;
  605. }
  606. // log_notice(LD_OR,"Done. state was %d.", conn->_base.state);
  607. } else {
  608. /* improved handshake, but not a client. */
  609. tor_tls_set_renegotiate_callback(conn->tls,
  610. connection_or_tls_renegotiated_cb,
  611. conn);
  612. conn->_base.state = OR_CONN_STATE_TLS_SERVER_RENEGOTIATING;
  613. connection_stop_writing(TO_CONN(conn));
  614. connection_start_reading(TO_CONN(conn));
  615. return 0;
  616. }
  617. }
  618. return connection_tls_finish_handshake(conn);
  619. case TOR_TLS_WANTWRITE:
  620. connection_start_writing(TO_CONN(conn));
  621. log_debug(LD_OR,"wanted write");
  622. return 0;
  623. case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
  624. log_debug(LD_OR,"wanted read");
  625. return 0;
  626. case TOR_TLS_CLOSE:
  627. log_info(LD_OR,"tls closed. breaking connection.");
  628. return -1;
  629. }
  630. return 0;
  631. }
  632. /** Return 1 if we initiated this connection, or 0 if it started
  633. * out as an incoming connection.
  634. */
  635. int
  636. connection_or_nonopen_was_started_here(or_connection_t *conn)
  637. {
  638. tor_assert(conn->_base.type == CONN_TYPE_OR);
  639. if (!conn->tls)
  640. return 1; /* it's still in proxy states or something */
  641. if (conn->handshake_state)
  642. return conn->handshake_state->started_here;
  643. return !tor_tls_is_server(conn->tls);
  644. }
  645. /** <b>Conn</b> just completed its handshake. Return 0 if all is well, and
  646. * return -1 if he is lying, broken, or otherwise something is wrong.
  647. *
  648. * If we initiated this connection (<b>started_here</b> is true), make sure
  649. * the other side sent sent a correctly formed certificate. If I initiated the
  650. * connection, make sure it's the right guy.
  651. *
  652. * Otherwise (if we _didn't_ initiate this connection), it's okay for
  653. * the certificate to be weird or absent.
  654. *
  655. * If we return 0, and the certificate is as expected, write a hash of the
  656. * identity key into digest_rcvd, which must have DIGEST_LEN space in it. (If
  657. * we return -1 this buffer is undefined.) If the certificate is invalid
  658. * or missing on an incoming connection, we return 0 and set digest_rcvd to
  659. * DIGEST_LEN 0 bytes.
  660. *
  661. * As side effects,
  662. * 1) Set conn->circ_id_type according to tor-spec.txt.
  663. * 2) If we're an authdirserver and we initiated the connection: drop all
  664. * descriptors that claim to be on that IP/port but that aren't
  665. * this guy; and note that this guy is reachable.
  666. */
  667. static int
  668. connection_or_check_valid_tls_handshake(or_connection_t *conn,
  669. int started_here,
  670. char *digest_rcvd_out)
  671. {
  672. crypto_pk_env_t *identity_rcvd=NULL;
  673. or_options_t *options = get_options();
  674. int severity = server_mode(options) ? LOG_PROTOCOL_WARN : LOG_WARN;
  675. const char *safe_address =
  676. started_here ? conn->_base.address : safe_str(conn->_base.address);
  677. const char *conn_type = started_here ? "outgoing" : "incoming";
  678. int has_cert = 0, has_identity=0;
  679. check_no_tls_errors();
  680. has_cert = tor_tls_peer_has_cert(conn->tls);
  681. if (started_here && !has_cert) {
  682. log_info(LD_PROTOCOL,"Tried connecting to router at %s:%d, but it didn't "
  683. "send a cert! Closing.",
  684. safe_address, conn->_base.port);
  685. return -1;
  686. } else if (!has_cert) {
  687. log_debug(LD_PROTOCOL,"Got incoming connection with no certificate. "
  688. "That's ok.");
  689. }
  690. check_no_tls_errors();
  691. if (has_cert) {
  692. int v = tor_tls_verify(started_here?severity:LOG_INFO,
  693. conn->tls, &identity_rcvd);
  694. if (started_here && v<0) {
  695. log_fn(severity,LD_OR,"Tried connecting to router at %s:%d: It"
  696. " has a cert but it's invalid. Closing.",
  697. safe_address, conn->_base.port);
  698. return -1;
  699. } else if (v<0) {
  700. log_info(LD_PROTOCOL,"Incoming connection gave us an invalid cert "
  701. "chain; ignoring.");
  702. } else {
  703. log_debug(LD_OR,"The certificate seems to be valid on %s connection "
  704. "with %s:%d", conn_type, safe_address, conn->_base.port);
  705. }
  706. check_no_tls_errors();
  707. }
  708. if (identity_rcvd) {
  709. has_identity = 1;
  710. crypto_pk_get_digest(identity_rcvd, digest_rcvd_out);
  711. if (crypto_pk_cmp_keys(get_identity_key(), identity_rcvd)<0) {
  712. conn->circ_id_type = CIRC_ID_TYPE_LOWER;
  713. } else {
  714. conn->circ_id_type = CIRC_ID_TYPE_HIGHER;
  715. }
  716. crypto_free_pk_env(identity_rcvd);
  717. } else {
  718. memset(digest_rcvd_out, 0, DIGEST_LEN);
  719. conn->circ_id_type = CIRC_ID_TYPE_NEITHER;
  720. }
  721. if (started_here && tor_digest_is_zero(conn->identity_digest)) {
  722. connection_or_set_identity_digest(conn, digest_rcvd_out);
  723. tor_free(conn->nickname);
  724. conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
  725. conn->nickname[0] = '$';
  726. base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
  727. conn->identity_digest, DIGEST_LEN);
  728. log_info(LD_OR, "Connected to router %s at %s:%d without knowing "
  729. "its key. Hoping for the best.",
  730. conn->nickname, conn->_base.address, conn->_base.port);
  731. }
  732. if (started_here) {
  733. int as_advertised = 1;
  734. tor_assert(has_cert);
  735. tor_assert(has_identity);
  736. if (memcmp(digest_rcvd_out, conn->identity_digest, DIGEST_LEN)) {
  737. /* I was aiming for a particular digest. I didn't get it! */
  738. char seen[HEX_DIGEST_LEN+1];
  739. char expected[HEX_DIGEST_LEN+1];
  740. base16_encode(seen, sizeof(seen), digest_rcvd_out, DIGEST_LEN);
  741. base16_encode(expected, sizeof(expected), conn->identity_digest,
  742. DIGEST_LEN);
  743. log_fn(severity, LD_OR,
  744. "Tried connecting to router at %s:%d, but identity key was not "
  745. "as expected: wanted %s but got %s.",
  746. conn->_base.address, conn->_base.port, expected, seen);
  747. entry_guard_register_connect_status(conn->identity_digest,0,time(NULL));
  748. router_set_status(conn->identity_digest, 0);
  749. control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED,
  750. END_OR_CONN_REASON_OR_IDENTITY);
  751. if (!authdir_mode_tests_reachability(options))
  752. control_event_bootstrap_problem("foo", END_OR_CONN_REASON_OR_IDENTITY);
  753. as_advertised = 0;
  754. }
  755. if (authdir_mode_tests_reachability(options)) {
  756. /* We initiated this connection to address:port. Drop all routers
  757. * with the same address:port and a different key.
  758. */
  759. dirserv_orconn_tls_done(conn->_base.address, conn->_base.port,
  760. digest_rcvd_out, as_advertised);
  761. }
  762. if (!as_advertised)
  763. return -1;
  764. }
  765. return 0;
  766. }
  767. /** The tls handshake is finished.
  768. *
  769. * Make sure we are happy with the person we just handshaked with.
  770. *
  771. * If he initiated the connection, make sure he's not already connected,
  772. * then initialize conn from the information in router.
  773. *
  774. * If all is successful, call circuit_n_conn_done() to handle events
  775. * that have been pending on the <tls handshake completion. Also set the
  776. * directory to be dirty (only matters if I'm an authdirserver).
  777. */
  778. static int
  779. connection_tls_finish_handshake(or_connection_t *conn)
  780. {
  781. char digest_rcvd[DIGEST_LEN];
  782. int started_here = connection_or_nonopen_was_started_here(conn);
  783. log_debug(LD_OR,"tls handshake with %s done. verifying.",
  784. safe_str(conn->_base.address));
  785. directory_set_dirty();
  786. if (connection_or_check_valid_tls_handshake(conn, started_here,
  787. digest_rcvd) < 0)
  788. return -1;
  789. if (tor_tls_used_v1_handshake(conn->tls)) {
  790. conn->link_proto = 1;
  791. if (!started_here) {
  792. connection_or_init_conn_from_address(conn, &conn->_base.addr,
  793. conn->_base.port, digest_rcvd, 0);
  794. }
  795. return connection_or_set_state_open(conn);
  796. } else {
  797. conn->_base.state = OR_CONN_STATE_OR_HANDSHAKING;
  798. if (connection_init_or_handshake_state(conn, started_here) < 0)
  799. return -1;
  800. if (!started_here) {
  801. connection_or_init_conn_from_address(conn, &conn->_base.addr,
  802. conn->_base.port, digest_rcvd, 0);
  803. }
  804. return connection_or_send_versions(conn);
  805. }
  806. }
  807. /** Allocate a new connection handshake state for the connection
  808. * <b>conn</b>. Return 0 on success, -1 on failure. */
  809. static int
  810. connection_init_or_handshake_state(or_connection_t *conn, int started_here)
  811. {
  812. or_handshake_state_t *s;
  813. s = conn->handshake_state = tor_malloc_zero(sizeof(or_handshake_state_t));
  814. s->started_here = started_here ? 1 : 0;
  815. return 0;
  816. }
  817. /** Free all storage held by <b>state</b>. */
  818. void
  819. or_handshake_state_free(or_handshake_state_t *state)
  820. {
  821. tor_assert(state);
  822. memset(state, 0xBE, sizeof(or_handshake_state_t));
  823. tor_free(state);
  824. }
  825. /** Set <b>conn</b>'s state to OR_CONN_STATE_OPEN, and tell other subsystems
  826. * as appropriate. Called when we are done with all TLS and OR handshaking.
  827. */
  828. int
  829. connection_or_set_state_open(or_connection_t *conn)
  830. {
  831. int started_here = connection_or_nonopen_was_started_here(conn);
  832. time_t now = time(NULL);
  833. conn->_base.state = OR_CONN_STATE_OPEN;
  834. control_event_or_conn_status(conn, OR_CONN_EVENT_CONNECTED, 0);
  835. if (started_here) {
  836. rep_hist_note_connect_succeeded(conn->identity_digest, now);
  837. if (entry_guard_register_connect_status(conn->identity_digest,
  838. 1, now) < 0) {
  839. /* Close any circuits pending on this conn. We leave it in state
  840. * 'open' though, because it didn't actually *fail* -- we just
  841. * chose not to use it. (Otherwise
  842. * connection_about_to_close_connection() will call a big pile of
  843. * functions to indicate we shouldn't try it again.) */
  844. log_debug(LD_OR, "New entry guard was reachable, but closing this "
  845. "connection so we can retry the earlier entry guards.");
  846. circuit_n_conn_done(conn, 0);
  847. return -1;
  848. }
  849. router_set_status(conn->identity_digest, 1);
  850. } else {
  851. /* only report it to the geoip module if it's not a known router */
  852. if (!router_get_by_digest(conn->identity_digest)) {
  853. if (tor_addr_family(&TO_CONN(conn)->addr) == AF_INET) {
  854. /*XXXX IP6 support ipv6 geoip.*/
  855. uint32_t a = tor_addr_to_ipv4h(&TO_CONN(conn)->addr);
  856. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, a, now);
  857. }
  858. }
  859. }
  860. if (conn->handshake_state) {
  861. or_handshake_state_free(conn->handshake_state);
  862. conn->handshake_state = NULL;
  863. }
  864. connection_start_reading(TO_CONN(conn));
  865. circuit_n_conn_done(conn, 1); /* send the pending creates, if any. */
  866. return 0;
  867. }
  868. /** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s outbuf.
  869. * For cells that use or affect a circuit, this should only be called by
  870. * connection_or_flush_from_first_active_circuit().
  871. */
  872. void
  873. connection_or_write_cell_to_buf(const cell_t *cell, or_connection_t *conn)
  874. {
  875. packed_cell_t networkcell;
  876. tor_assert(cell);
  877. tor_assert(conn);
  878. cell_pack(&networkcell, cell);
  879. connection_write_to_buf(networkcell.body, CELL_NETWORK_SIZE, TO_CONN(conn));
  880. if (cell->command != CELL_PADDING)
  881. conn->timestamp_last_added_nonpadding = time(NULL);
  882. }
  883. /** Pack a variable-length <b>cell</b> into wire-format, and write it onto
  884. * <b>conn</b>'s outbuf. Right now, this <em>DOES NOT</em> support cells that
  885. * affect a circuit.
  886. */
  887. void
  888. connection_or_write_var_cell_to_buf(const var_cell_t *cell,
  889. or_connection_t *conn)
  890. {
  891. char hdr[VAR_CELL_HEADER_SIZE];
  892. tor_assert(cell);
  893. tor_assert(conn);
  894. var_cell_pack_header(cell, hdr);
  895. connection_write_to_buf(hdr, sizeof(hdr), TO_CONN(conn));
  896. connection_write_to_buf(cell->payload, cell->payload_len, TO_CONN(conn));
  897. if (cell->command != CELL_PADDING)
  898. conn->timestamp_last_added_nonpadding = time(NULL);
  899. }
  900. /** See whether there's a variable-length cell waiting on <b>conn</b>'s
  901. * inbuf. Return values as for fetch_var_cell_from_buf(). */
  902. static int
  903. connection_fetch_var_cell_from_buf(or_connection_t *conn, var_cell_t **out)
  904. {
  905. return fetch_var_cell_from_buf(conn->_base.inbuf, out, conn->link_proto);
  906. }
  907. /** Process cells from <b>conn</b>'s inbuf.
  908. *
  909. * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
  910. * and hand it to command_process_cell().
  911. *
  912. * Always return 0.
  913. */
  914. static int
  915. connection_or_process_cells_from_inbuf(or_connection_t *conn)
  916. {
  917. var_cell_t *var_cell;
  918. while (1) {
  919. log_debug(LD_OR,
  920. "%d: starting, inbuf_datalen %d (%d pending in tls object).",
  921. conn->_base.s,(int)buf_datalen(conn->_base.inbuf),
  922. tor_tls_get_pending_bytes(conn->tls));
  923. if (connection_fetch_var_cell_from_buf(conn, &var_cell)) {
  924. if (!var_cell)
  925. return 0; /* not yet. */
  926. command_process_var_cell(var_cell, conn);
  927. var_cell_free(var_cell);
  928. } else {
  929. char buf[CELL_NETWORK_SIZE];
  930. cell_t cell;
  931. if (buf_datalen(conn->_base.inbuf) < CELL_NETWORK_SIZE) /* whole response
  932. available? */
  933. return 0; /* not yet */
  934. connection_fetch_from_buf(buf, CELL_NETWORK_SIZE, TO_CONN(conn));
  935. /* retrieve cell info from buf (create the host-order struct from the
  936. * network-order string) */
  937. cell_unpack(&cell, buf);
  938. command_process_cell(&cell, conn);
  939. }
  940. }
  941. }
  942. /** Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
  943. * onto OR connection <b>conn</b>. Don't perform range-checking on reason:
  944. * we may want to propagate reasons from other cells.
  945. *
  946. * Return 0.
  947. */
  948. int
  949. connection_or_send_destroy(circid_t circ_id, or_connection_t *conn, int reason)
  950. {
  951. cell_t cell;
  952. tor_assert(conn);
  953. memset(&cell, 0, sizeof(cell_t));
  954. cell.circ_id = circ_id;
  955. cell.command = CELL_DESTROY;
  956. cell.payload[0] = (uint8_t) reason;
  957. log_debug(LD_OR,"Sending destroy (circID %d).", circ_id);
  958. /* XXXX It's possible that under some circumstances, we want the destroy
  959. * to take precedence over other data waiting on the circuit's cell queue.
  960. */
  961. connection_or_write_cell_to_buf(&cell, conn);
  962. return 0;
  963. }
  964. /** Array of recognized link protocol versions. */
  965. static const uint16_t or_protocol_versions[] = { 1, 2 };
  966. /** Number of versions in <b>or_protocol_versions</b>. */
  967. static const int n_or_protocol_versions =
  968. (int)( sizeof(or_protocol_versions)/sizeof(uint16_t) );
  969. /** Return true iff <b>v</b> is a link protocol version that this Tor
  970. * implementation believes it can support. */
  971. int
  972. is_or_protocol_version_known(uint16_t v)
  973. {
  974. int i;
  975. for (i = 0; i < n_or_protocol_versions; ++i) {
  976. if (or_protocol_versions[i] == v)
  977. return 1;
  978. }
  979. return 0;
  980. }
  981. /** Send a VERSIONS cell on <b>conn</b>, telling the other host about the
  982. * link protocol versions that this Tor can support. */
  983. static int
  984. connection_or_send_versions(or_connection_t *conn)
  985. {
  986. var_cell_t *cell;
  987. int i;
  988. tor_assert(conn->handshake_state &&
  989. !conn->handshake_state->sent_versions_at);
  990. cell = var_cell_new(n_or_protocol_versions * 2);
  991. cell->command = CELL_VERSIONS;
  992. for (i = 0; i < n_or_protocol_versions; ++i) {
  993. uint16_t v = or_protocol_versions[i];
  994. set_uint16(cell->payload+(2*i), htons(v));
  995. }
  996. connection_or_write_var_cell_to_buf(cell, conn);
  997. conn->handshake_state->sent_versions_at = time(NULL);
  998. var_cell_free(cell);
  999. return 0;
  1000. }
  1001. /** Send a NETINFO cell on <b>conn</b>, telling the other server what we know
  1002. * about their address, our address, and the current time. */
  1003. int
  1004. connection_or_send_netinfo(or_connection_t *conn)
  1005. {
  1006. cell_t cell;
  1007. time_t now = time(NULL);
  1008. routerinfo_t *me;
  1009. int len;
  1010. char *out;
  1011. memset(&cell, 0, sizeof(cell_t));
  1012. cell.command = CELL_NETINFO;
  1013. /* Timestamp. */
  1014. set_uint32(cell.payload, htonl((uint32_t)now));
  1015. /* Their address. */
  1016. out = cell.payload + 4;
  1017. len = append_address_to_payload(out, &conn->_base.addr);
  1018. if (len<0)
  1019. return -1;
  1020. out += len;
  1021. /* My address. */
  1022. if ((me = router_get_my_routerinfo())) {
  1023. tor_addr_t my_addr;
  1024. *out++ = 1; /* only one address is supported. */
  1025. tor_addr_from_ipv4h(&my_addr, me->addr);
  1026. len = append_address_to_payload(out, &my_addr);
  1027. if (len < 0)
  1028. return -1;
  1029. out += len;
  1030. } else {
  1031. *out++ = 0;
  1032. }
  1033. connection_or_write_cell_to_buf(&cell, conn);
  1034. return 0;
  1035. }