connection_or.c 36 KB

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