connection_or.c 35 KB

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