connection_or.c 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185
  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-2011, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file connection_or.c
  8. * \brief Functions to handle OR connections, TLS handshaking, and
  9. * cells on the network.
  10. **/
  11. #include "or.h"
  12. #include "buffers.h"
  13. #include "circuitbuild.h"
  14. #include "circuitlist.h"
  15. #include "command.h"
  16. #include "config.h"
  17. #include "connection.h"
  18. #include "connection_or.h"
  19. #include "control.h"
  20. #include "dirserv.h"
  21. #include "geoip.h"
  22. #include "main.h"
  23. #include "networkstatus.h"
  24. #include "nodelist.h"
  25. #include "reasons.h"
  26. #include "relay.h"
  27. #include "rephist.h"
  28. #include "router.h"
  29. #include "routerlist.h"
  30. #ifdef USE_BUFFEREVENTS
  31. #include <event2/bufferevent_ssl.h>
  32. #endif
  33. static int connection_tls_finish_handshake(or_connection_t *conn);
  34. static int connection_or_launch_v3_or_handshake(or_connection_t *conn);
  35. static int connection_or_process_cells_from_inbuf(or_connection_t *conn);
  36. static int connection_or_check_valid_tls_handshake(or_connection_t *conn,
  37. int started_here,
  38. char *digest_rcvd_out);
  39. static void connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn);
  40. #ifdef USE_BUFFEREVENTS
  41. static void connection_or_handle_event_cb(struct bufferevent *bufev,
  42. short event, void *arg);
  43. #include <event2/buffer.h>/*XXXX REMOVE */
  44. #endif
  45. /**************************************************************/
  46. /** Map from identity digest of connected OR or desired OR to a connection_t
  47. * with that identity digest. If there is more than one such connection_t,
  48. * they form a linked list, with next_with_same_id as the next pointer. */
  49. static digestmap_t *orconn_identity_map = NULL;
  50. /** If conn is listed in orconn_identity_map, remove it, and clear
  51. * conn->identity_digest. Otherwise do nothing. */
  52. void
  53. connection_or_remove_from_identity_map(or_connection_t *conn)
  54. {
  55. or_connection_t *tmp;
  56. tor_assert(conn);
  57. if (!orconn_identity_map)
  58. return;
  59. tmp = digestmap_get(orconn_identity_map, conn->identity_digest);
  60. if (!tmp) {
  61. if (!tor_digest_is_zero(conn->identity_digest)) {
  62. log_warn(LD_BUG, "Didn't find connection '%s' on identity map when "
  63. "trying to remove it.",
  64. conn->nickname ? conn->nickname : "NULL");
  65. }
  66. return;
  67. }
  68. if (conn == tmp) {
  69. if (conn->next_with_same_id)
  70. digestmap_set(orconn_identity_map, conn->identity_digest,
  71. conn->next_with_same_id);
  72. else
  73. digestmap_remove(orconn_identity_map, conn->identity_digest);
  74. } else {
  75. while (tmp->next_with_same_id) {
  76. if (tmp->next_with_same_id == conn) {
  77. tmp->next_with_same_id = conn->next_with_same_id;
  78. break;
  79. }
  80. tmp = tmp->next_with_same_id;
  81. }
  82. }
  83. memset(conn->identity_digest, 0, DIGEST_LEN);
  84. conn->next_with_same_id = NULL;
  85. }
  86. /** Remove all entries from the identity-to-orconn map, and clear
  87. * all identities in OR conns.*/
  88. void
  89. connection_or_clear_identity_map(void)
  90. {
  91. smartlist_t *conns = get_connection_array();
  92. SMARTLIST_FOREACH(conns, connection_t *, conn,
  93. {
  94. if (conn->type == CONN_TYPE_OR) {
  95. or_connection_t *or_conn = TO_OR_CONN(conn);
  96. memset(or_conn->identity_digest, 0, DIGEST_LEN);
  97. or_conn->next_with_same_id = NULL;
  98. }
  99. });
  100. digestmap_free(orconn_identity_map, NULL);
  101. orconn_identity_map = NULL;
  102. }
  103. /** Change conn->identity_digest to digest, and add conn into
  104. * orconn_digest_map. */
  105. static void
  106. connection_or_set_identity_digest(or_connection_t *conn, const char *digest)
  107. {
  108. or_connection_t *tmp;
  109. tor_assert(conn);
  110. tor_assert(digest);
  111. if (!orconn_identity_map)
  112. orconn_identity_map = digestmap_new();
  113. if (tor_memeq(conn->identity_digest, digest, DIGEST_LEN))
  114. return;
  115. /* If the identity was set previously, remove the old mapping. */
  116. if (! tor_digest_is_zero(conn->identity_digest))
  117. connection_or_remove_from_identity_map(conn);
  118. memcpy(conn->identity_digest, digest, DIGEST_LEN);
  119. /* If we're setting the ID to zero, don't add a mapping. */
  120. if (tor_digest_is_zero(digest))
  121. return;
  122. tmp = digestmap_set(orconn_identity_map, digest, conn);
  123. conn->next_with_same_id = tmp;
  124. #if 1
  125. /* Testing code to check for bugs in representation. */
  126. for (; tmp; tmp = tmp->next_with_same_id) {
  127. tor_assert(tor_memeq(tmp->identity_digest, digest, DIGEST_LEN));
  128. tor_assert(tmp != conn);
  129. }
  130. #endif
  131. }
  132. /**************************************************************/
  133. /** Map from a string describing what a non-open OR connection was doing when
  134. * failed, to an intptr_t describing the count of connections that failed that
  135. * way. Note that the count is stored _as_ the pointer.
  136. */
  137. static strmap_t *broken_connection_counts;
  138. /** If true, do not record information in <b>broken_connection_counts</b>. */
  139. static int disable_broken_connection_counts = 0;
  140. /** Record that an OR connection failed in <b>state</b>. */
  141. static void
  142. note_broken_connection(const char *state)
  143. {
  144. void *ptr;
  145. intptr_t val;
  146. if (disable_broken_connection_counts)
  147. return;
  148. if (!broken_connection_counts)
  149. broken_connection_counts = strmap_new();
  150. ptr = strmap_get(broken_connection_counts, state);
  151. val = (intptr_t)ptr;
  152. val++;
  153. ptr = (void*)val;
  154. strmap_set(broken_connection_counts, state, ptr);
  155. }
  156. /** Forget all recorded states for failed connections. If
  157. * <b>stop_recording</b> is true, don't record any more. */
  158. void
  159. clear_broken_connection_map(int stop_recording)
  160. {
  161. if (broken_connection_counts)
  162. strmap_free(broken_connection_counts, NULL);
  163. broken_connection_counts = NULL;
  164. if (stop_recording)
  165. disable_broken_connection_counts = 1;
  166. }
  167. /** Write a detailed description the state of <b>orconn</b> into the
  168. * <b>buflen</b>-byte buffer at <b>buf</b>. This description includes not
  169. * only the OR-conn level state but also the TLS state. It's useful for
  170. * diagnosing broken handshakes. */
  171. static void
  172. connection_or_get_state_description(or_connection_t *orconn,
  173. char *buf, size_t buflen)
  174. {
  175. connection_t *conn = TO_CONN(orconn);
  176. const char *conn_state;
  177. char tls_state[256];
  178. tor_assert(conn->type == CONN_TYPE_OR);
  179. conn_state = conn_state_to_string(conn->type, conn->state);
  180. tor_tls_get_state_description(orconn->tls, tls_state, sizeof(tls_state));
  181. tor_snprintf(buf, buflen, "%s with SSL state %s", conn_state, tls_state);
  182. }
  183. /** Record the current state of <b>orconn</b> as the state of a broken
  184. * connection. */
  185. static void
  186. connection_or_note_state_when_broken(or_connection_t *orconn)
  187. {
  188. char buf[256];
  189. if (disable_broken_connection_counts)
  190. return;
  191. connection_or_get_state_description(orconn, buf, sizeof(buf));
  192. log_info(LD_HANDSHAKE,"Connection died in state '%s'", buf);
  193. note_broken_connection(buf);
  194. }
  195. /** Helper type used to sort connection states and find the most frequent. */
  196. typedef struct broken_state_count_t {
  197. intptr_t count;
  198. const char *state;
  199. } broken_state_count_t;
  200. /** Helper function used to sort broken_state_count_t by frequency. */
  201. static int
  202. broken_state_count_compare(const void **a_ptr, const void **b_ptr)
  203. {
  204. const broken_state_count_t *a = *a_ptr, *b = *b_ptr;
  205. if (b->count < a->count)
  206. return -1;
  207. else if (b->count == a->count)
  208. return 0;
  209. else
  210. return 1;
  211. }
  212. /** Upper limit on the number of different states to report for connection
  213. * failure. */
  214. #define MAX_REASONS_TO_REPORT 10
  215. /** Report a list of the top states for failed OR connections at log level
  216. * <b>severity</b>, in log domain <b>domain</b>. */
  217. void
  218. connection_or_report_broken_states(int severity, int domain)
  219. {
  220. int total = 0;
  221. smartlist_t *items;
  222. if (!broken_connection_counts || disable_broken_connection_counts)
  223. return;
  224. items = smartlist_create();
  225. STRMAP_FOREACH(broken_connection_counts, state, void *, countptr) {
  226. broken_state_count_t *c = tor_malloc(sizeof(broken_state_count_t));
  227. c->count = (intptr_t)countptr;
  228. total += (int)c->count;
  229. c->state = state;
  230. smartlist_add(items, c);
  231. } STRMAP_FOREACH_END;
  232. smartlist_sort(items, broken_state_count_compare);
  233. log(severity, domain, "%d connections have failed%s", total,
  234. smartlist_len(items) > MAX_REASONS_TO_REPORT ? ". Top reasons:" : ":");
  235. SMARTLIST_FOREACH_BEGIN(items, const broken_state_count_t *, c) {
  236. if (c_sl_idx > MAX_REASONS_TO_REPORT)
  237. break;
  238. log(severity, domain,
  239. " %d connections died in state %s", (int)c->count, c->state);
  240. } SMARTLIST_FOREACH_END(c);
  241. SMARTLIST_FOREACH(items, broken_state_count_t *, c, tor_free(c));
  242. smartlist_free(items);
  243. }
  244. /**************************************************************/
  245. /** Pack the cell_t host-order structure <b>src</b> into network-order
  246. * in the buffer <b>dest</b>. See tor-spec.txt for details about the
  247. * wire format.
  248. *
  249. * Note that this function doesn't touch <b>dst</b>-\>next: the caller
  250. * should set it or clear it as appropriate.
  251. */
  252. void
  253. cell_pack(packed_cell_t *dst, const cell_t *src)
  254. {
  255. char *dest = dst->body;
  256. set_uint16(dest, htons(src->circ_id));
  257. *(uint8_t*)(dest+2) = src->command;
  258. memcpy(dest+3, src->payload, CELL_PAYLOAD_SIZE);
  259. }
  260. /** Unpack the network-order buffer <b>src</b> into a host-order
  261. * cell_t structure <b>dest</b>.
  262. */
  263. static void
  264. cell_unpack(cell_t *dest, const char *src)
  265. {
  266. dest->circ_id = ntohs(get_uint16(src));
  267. dest->command = *(uint8_t*)(src+2);
  268. memcpy(dest->payload, src+3, CELL_PAYLOAD_SIZE);
  269. }
  270. /** Write the header of <b>cell</b> into the first VAR_CELL_HEADER_SIZE
  271. * bytes of <b>hdr_out</b>. */
  272. void
  273. var_cell_pack_header(const var_cell_t *cell, char *hdr_out)
  274. {
  275. set_uint16(hdr_out, htons(cell->circ_id));
  276. set_uint8(hdr_out+2, cell->command);
  277. set_uint16(hdr_out+3, htons(cell->payload_len));
  278. }
  279. /** Allocate and return a new var_cell_t with <b>payload_len</b> bytes of
  280. * payload space. */
  281. var_cell_t *
  282. var_cell_new(uint16_t payload_len)
  283. {
  284. size_t size = STRUCT_OFFSET(var_cell_t, payload) + payload_len;
  285. var_cell_t *cell = tor_malloc(size);
  286. cell->payload_len = payload_len;
  287. cell->command = 0;
  288. cell->circ_id = 0;
  289. return cell;
  290. }
  291. /** Release all space held by <b>cell</b>. */
  292. void
  293. var_cell_free(var_cell_t *cell)
  294. {
  295. tor_free(cell);
  296. }
  297. /** We've received an EOF from <b>conn</b>. Mark it for close and return. */
  298. int
  299. connection_or_reached_eof(or_connection_t *conn)
  300. {
  301. log_info(LD_OR,"OR connection reached EOF. Closing.");
  302. connection_mark_for_close(TO_CONN(conn));
  303. return 0;
  304. }
  305. /** Handle any new bytes that have come in on connection <b>conn</b>.
  306. * If conn is in 'open' state, hand it to
  307. * connection_or_process_cells_from_inbuf()
  308. * (else do nothing).
  309. */
  310. int
  311. connection_or_process_inbuf(or_connection_t *conn)
  312. {
  313. int ret;
  314. tor_assert(conn);
  315. switch (conn->_base.state) {
  316. case OR_CONN_STATE_PROXY_HANDSHAKING:
  317. ret = connection_read_proxy_handshake(TO_CONN(conn));
  318. /* start TLS after handshake completion, or deal with error */
  319. if (ret == 1) {
  320. tor_assert(TO_CONN(conn)->proxy_state == PROXY_CONNECTED);
  321. if (connection_tls_start_handshake(conn, 0) < 0)
  322. ret = -1;
  323. }
  324. if (ret < 0) {
  325. connection_mark_for_close(TO_CONN(conn));
  326. }
  327. return ret;
  328. #ifdef USE_BUFFEREVENTS
  329. case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
  330. if (tor_tls_server_got_renegotiate(conn->tls))
  331. connection_or_tls_renegotiated_cb(conn->tls, conn);
  332. if (conn->_base.marked_for_close)
  333. return 0;
  334. /* fall through. */
  335. #endif
  336. case OR_CONN_STATE_OPEN:
  337. case OR_CONN_STATE_OR_HANDSHAKING_V2:
  338. case OR_CONN_STATE_OR_HANDSHAKING_V3:
  339. return connection_or_process_cells_from_inbuf(conn);
  340. default:
  341. return 0; /* don't do anything */
  342. }
  343. }
  344. /** When adding cells to an OR connection's outbuf, keep adding until the
  345. * outbuf is at least this long, or we run out of cells. */
  346. #define OR_CONN_HIGHWATER (32*1024)
  347. /** Add cells to an OR connection's outbuf whenever the outbuf's data length
  348. * drops below this size. */
  349. #define OR_CONN_LOWWATER (16*1024)
  350. /** Called whenever we have flushed some data on an or_conn: add more data
  351. * from active circuits. */
  352. int
  353. connection_or_flushed_some(or_connection_t *conn)
  354. {
  355. size_t datalen = connection_get_outbuf_len(TO_CONN(conn));
  356. /* If we're under the low water mark, add cells until we're just over the
  357. * high water mark. */
  358. if (datalen < OR_CONN_LOWWATER) {
  359. ssize_t n = CEIL_DIV(OR_CONN_HIGHWATER - datalen, CELL_NETWORK_SIZE);
  360. time_t now = approx_time();
  361. while (conn->active_circuits && n > 0) {
  362. int flushed;
  363. flushed = connection_or_flush_from_first_active_circuit(conn, 1, now);
  364. n -= flushed;
  365. }
  366. }
  367. return 0;
  368. }
  369. /** Connection <b>conn</b> has finished writing and has no bytes left on
  370. * its outbuf.
  371. *
  372. * Otherwise it's in state "open": stop writing and return.
  373. *
  374. * If <b>conn</b> is broken, mark it for close and return -1, else
  375. * return 0.
  376. */
  377. int
  378. connection_or_finished_flushing(or_connection_t *conn)
  379. {
  380. tor_assert(conn);
  381. assert_connection_ok(TO_CONN(conn),0);
  382. switch (conn->_base.state) {
  383. case OR_CONN_STATE_PROXY_HANDSHAKING:
  384. case OR_CONN_STATE_OPEN:
  385. case OR_CONN_STATE_OR_HANDSHAKING_V2:
  386. break;
  387. default:
  388. log_err(LD_BUG,"Called in unexpected state %d.", conn->_base.state);
  389. tor_fragile_assert();
  390. return -1;
  391. }
  392. return 0;
  393. }
  394. /** Connected handler for OR connections: begin the TLS handshake.
  395. */
  396. int
  397. connection_or_finished_connecting(or_connection_t *or_conn)
  398. {
  399. const int proxy_type = or_conn->proxy_type;
  400. connection_t *conn;
  401. tor_assert(or_conn);
  402. conn = TO_CONN(or_conn);
  403. tor_assert(conn->state == OR_CONN_STATE_CONNECTING);
  404. log_debug(LD_HANDSHAKE,"OR connect() to router at %s:%u finished.",
  405. conn->address,conn->port);
  406. control_event_bootstrap(BOOTSTRAP_STATUS_HANDSHAKE, 0);
  407. if (proxy_type != PROXY_NONE) {
  408. /* start proxy handshake */
  409. if (connection_proxy_connect(conn, proxy_type) < 0) {
  410. connection_mark_for_close(conn);
  411. return -1;
  412. }
  413. connection_start_reading(conn);
  414. conn->state = OR_CONN_STATE_PROXY_HANDSHAKING;
  415. return 0;
  416. }
  417. if (connection_tls_start_handshake(or_conn, 0) < 0) {
  418. /* TLS handshaking error of some kind. */
  419. connection_mark_for_close(conn);
  420. return -1;
  421. }
  422. return 0;
  423. }
  424. /* Called when we're about to finally unlink and free an OR connection:
  425. * perform necessary accounting and cleanup */
  426. void
  427. connection_or_about_to_close(or_connection_t *or_conn)
  428. {
  429. time_t now = time(NULL);
  430. connection_t *conn = TO_CONN(or_conn);
  431. /* Remember why we're closing this connection. */
  432. if (conn->state != OR_CONN_STATE_OPEN) {
  433. /* Inform any pending (not attached) circs that they should
  434. * give up. */
  435. circuit_n_conn_done(TO_OR_CONN(conn), 0);
  436. /* now mark things down as needed */
  437. if (connection_or_nonopen_was_started_here(or_conn)) {
  438. const or_options_t *options = get_options();
  439. connection_or_note_state_when_broken(or_conn);
  440. rep_hist_note_connect_failed(or_conn->identity_digest, now);
  441. entry_guard_register_connect_status(or_conn->identity_digest,0,
  442. !options->HTTPSProxy, now);
  443. if (conn->state >= OR_CONN_STATE_TLS_HANDSHAKING) {
  444. int reason = tls_error_to_orconn_end_reason(or_conn->tls_error);
  445. control_event_or_conn_status(or_conn, OR_CONN_EVENT_FAILED,
  446. reason);
  447. if (!authdir_mode_tests_reachability(options))
  448. control_event_bootstrap_problem(
  449. orconn_end_reason_to_control_string(reason), reason);
  450. }
  451. }
  452. } else if (conn->hold_open_until_flushed) {
  453. /* We only set hold_open_until_flushed when we're intentionally
  454. * closing a connection. */
  455. rep_hist_note_disconnect(or_conn->identity_digest, now);
  456. control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
  457. tls_error_to_orconn_end_reason(or_conn->tls_error));
  458. } else if (!tor_digest_is_zero(or_conn->identity_digest)) {
  459. rep_hist_note_connection_died(or_conn->identity_digest, now);
  460. control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
  461. tls_error_to_orconn_end_reason(or_conn->tls_error));
  462. }
  463. /* Now close all the attached circuits on it. */
  464. circuit_unlink_all_from_or_conn(TO_OR_CONN(conn),
  465. END_CIRC_REASON_OR_CONN_CLOSED);
  466. }
  467. /** Return 1 if identity digest <b>id_digest</b> is known to be a
  468. * currently or recently running relay. Otherwise return 0. */
  469. int
  470. connection_or_digest_is_known_relay(const char *id_digest)
  471. {
  472. if (router_get_consensus_status_by_id(id_digest))
  473. return 1; /* It's in the consensus: "yes" */
  474. if (router_get_by_id_digest(id_digest))
  475. return 1; /* Not in the consensus, but we have a descriptor for
  476. * it. Probably it was in a recent consensus. "Yes". */
  477. return 0;
  478. }
  479. /** Set the per-conn read and write limits for <b>conn</b>. If it's a known
  480. * relay, we will rely on the global read and write buckets, so give it
  481. * per-conn limits that are big enough they'll never matter. But if it's
  482. * not a known relay, first check if we set PerConnBwRate/Burst, then
  483. * check if the consensus sets them, else default to 'big enough'.
  484. *
  485. * If <b>reset</b> is true, set the bucket to be full. Otherwise, just
  486. * clip the bucket if it happens to be <em>too</em> full.
  487. */
  488. static void
  489. connection_or_update_token_buckets_helper(or_connection_t *conn, int reset,
  490. const or_options_t *options)
  491. {
  492. int rate, burst; /* per-connection rate limiting params */
  493. if (connection_or_digest_is_known_relay(conn->identity_digest)) {
  494. /* It's in the consensus, or we have a descriptor for it meaning it
  495. * was probably in a recent consensus. It's a recognized relay:
  496. * give it full bandwidth. */
  497. rate = (int)options->BandwidthRate;
  498. burst = (int)options->BandwidthBurst;
  499. } else {
  500. /* Not a recognized relay. Squeeze it down based on the suggested
  501. * bandwidth parameters in the consensus, but allow local config
  502. * options to override. */
  503. rate = options->PerConnBWRate ? (int)options->PerConnBWRate :
  504. networkstatus_get_param(NULL, "perconnbwrate",
  505. (int)options->BandwidthRate, 1, INT32_MAX);
  506. burst = options->PerConnBWBurst ? (int)options->PerConnBWBurst :
  507. networkstatus_get_param(NULL, "perconnbwburst",
  508. (int)options->BandwidthBurst, 1, INT32_MAX);
  509. }
  510. conn->bandwidthrate = rate;
  511. conn->bandwidthburst = burst;
  512. #ifdef USE_BUFFEREVENTS
  513. {
  514. const struct timeval *tick = tor_libevent_get_one_tick_timeout();
  515. struct ev_token_bucket_cfg *cfg, *old_cfg;
  516. int64_t rate64 = (((int64_t)rate) * options->TokenBucketRefillInterval)
  517. / 1000;
  518. /* This can't overflow, since TokenBucketRefillInterval <= 1000,
  519. * and rate started out less than INT_MAX. */
  520. int rate_per_tick = (int) rate64;
  521. cfg = ev_token_bucket_cfg_new(rate_per_tick, burst, rate_per_tick,
  522. burst, tick);
  523. old_cfg = conn->bucket_cfg;
  524. if (conn->_base.bufev)
  525. tor_set_bufferevent_rate_limit(conn->_base.bufev, cfg);
  526. if (old_cfg)
  527. ev_token_bucket_cfg_free(old_cfg);
  528. conn->bucket_cfg = cfg;
  529. (void) reset; /* No way to do this with libevent yet. */
  530. }
  531. #else
  532. if (reset) { /* set up the token buckets to be full */
  533. conn->read_bucket = conn->write_bucket = burst;
  534. return;
  535. }
  536. /* If the new token bucket is smaller, take out the extra tokens.
  537. * (If it's larger, don't -- the buckets can grow to reach the cap.) */
  538. if (conn->read_bucket > burst)
  539. conn->read_bucket = burst;
  540. if (conn->write_bucket > burst)
  541. conn->write_bucket = burst;
  542. #endif
  543. }
  544. /** Either our set of relays or our per-conn rate limits have changed.
  545. * Go through all the OR connections and update their token buckets to make
  546. * sure they don't exceed their maximum values. */
  547. void
  548. connection_or_update_token_buckets(smartlist_t *conns,
  549. const or_options_t *options)
  550. {
  551. SMARTLIST_FOREACH(conns, connection_t *, conn,
  552. {
  553. if (connection_speaks_cells(conn))
  554. connection_or_update_token_buckets_helper(TO_OR_CONN(conn), 0, options);
  555. });
  556. }
  557. /** If we don't necessarily know the router we're connecting to, but we
  558. * have an addr/port/id_digest, then fill in as much as we can. Start
  559. * by checking to see if this describes a router we know. */
  560. void
  561. connection_or_init_conn_from_address(or_connection_t *conn,
  562. const tor_addr_t *addr, uint16_t port,
  563. const char *id_digest,
  564. int started_here)
  565. {
  566. const node_t *r = node_get_by_id(id_digest);
  567. connection_or_set_identity_digest(conn, id_digest);
  568. connection_or_update_token_buckets_helper(conn, 1, get_options());
  569. conn->_base.port = port;
  570. tor_addr_copy(&conn->_base.addr, addr);
  571. tor_addr_copy(&conn->real_addr, addr);
  572. if (r) {
  573. tor_addr_t node_addr;
  574. node_get_addr(r, &node_addr);
  575. /* XXXX proposal 118 will make this more complex. */
  576. if (tor_addr_eq(&conn->_base.addr, &node_addr))
  577. conn->is_canonical = 1;
  578. if (!started_here) {
  579. /* Override the addr/port, so our log messages will make sense.
  580. * This is dangerous, since if we ever try looking up a conn by
  581. * its actual addr/port, we won't remember. Careful! */
  582. /* XXXX arma: this is stupid, and it's the reason we need real_addr
  583. * to track is_canonical properly. What requires it? */
  584. /* XXXX <arma> i believe the reason we did this, originally, is because
  585. * we wanted to log what OR a connection was to, and if we logged the
  586. * right IP address and port 56244, that wouldn't be as helpful. now we
  587. * log the "right" port too, so we know if it's moria1 or moria2.
  588. */
  589. tor_addr_copy(&conn->_base.addr, &node_addr);
  590. conn->_base.port = node_get_orport(r);
  591. }
  592. conn->nickname = tor_strdup(node_get_nickname(r));
  593. tor_free(conn->_base.address);
  594. conn->_base.address = tor_dup_addr(&node_addr);
  595. } else {
  596. const char *n;
  597. /* If we're an authoritative directory server, we may know a
  598. * nickname for this router. */
  599. n = dirserv_get_nickname_by_digest(id_digest);
  600. if (n) {
  601. conn->nickname = tor_strdup(n);
  602. } else {
  603. conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
  604. conn->nickname[0] = '$';
  605. base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
  606. conn->identity_digest, DIGEST_LEN);
  607. }
  608. tor_free(conn->_base.address);
  609. conn->_base.address = tor_dup_addr(addr);
  610. }
  611. }
  612. /** Return true iff <b>a</b> is "better" than <b>b</b> for new circuits.
  613. *
  614. * A more canonical connection is always better than a less canonical
  615. * connection. That aside, a connection is better if it has circuits and the
  616. * other does not, or if it was created more recently.
  617. *
  618. * Requires that both input connections are open; not is_bad_for_new_circs,
  619. * and not impossibly non-canonical.
  620. *
  621. * If <b>forgive_new_connections</b> is true, then we do not call
  622. * <b>a</b>better than <b>b</b> simply because b has no circuits,
  623. * unless b is also relatively old.
  624. */
  625. static int
  626. connection_or_is_better(time_t now,
  627. const or_connection_t *a,
  628. const or_connection_t *b,
  629. int forgive_new_connections)
  630. {
  631. int newer;
  632. /** Do not definitively deprecate a new connection with no circuits on it
  633. * until this much time has passed. */
  634. #define NEW_CONN_GRACE_PERIOD (15*60)
  635. if (b->is_canonical && !a->is_canonical)
  636. return 0; /* A canonical connection is better than a non-canonical
  637. * one, no matter how new it is or which has circuits. */
  638. newer = b->_base.timestamp_created < a->_base.timestamp_created;
  639. if (
  640. /* We prefer canonical connections regardless of newness. */
  641. (!b->is_canonical && a->is_canonical) ||
  642. /* If both have circuits we prefer the newer: */
  643. (b->n_circuits && a->n_circuits && newer) ||
  644. /* If neither has circuits we prefer the newer: */
  645. (!b->n_circuits && !a->n_circuits && newer))
  646. return 1;
  647. /* If one has no circuits and the other does... */
  648. if (!b->n_circuits && a->n_circuits) {
  649. /* Then it's bad, unless it's in its grace period and we're forgiving. */
  650. if (forgive_new_connections &&
  651. now < b->_base.timestamp_created + NEW_CONN_GRACE_PERIOD)
  652. return 0;
  653. else
  654. return 1;
  655. }
  656. return 0;
  657. }
  658. /** Return the OR connection we should use to extend a circuit to the router
  659. * whose identity is <b>digest</b>, and whose address we believe (or have been
  660. * told in an extend cell) is <b>target_addr</b>. If there is no good
  661. * connection, set *<b>msg_out</b> to a message describing the connection's
  662. * state and our next action, and set <b>launch_out</b> to a boolean for
  663. * whether we should launch a new connection or not.
  664. */
  665. or_connection_t *
  666. connection_or_get_for_extend(const char *digest,
  667. const tor_addr_t *target_addr,
  668. const char **msg_out,
  669. int *launch_out)
  670. {
  671. or_connection_t *conn, *best=NULL;
  672. int n_inprogress_goodaddr = 0, n_old = 0, n_noncanonical = 0, n_possible = 0;
  673. time_t now = approx_time();
  674. tor_assert(msg_out);
  675. tor_assert(launch_out);
  676. if (!orconn_identity_map) {
  677. *msg_out = "Router not connected (nothing is). Connecting.";
  678. *launch_out = 1;
  679. return NULL;
  680. }
  681. conn = digestmap_get(orconn_identity_map, digest);
  682. for (; conn; conn = conn->next_with_same_id) {
  683. tor_assert(conn->_base.magic == OR_CONNECTION_MAGIC);
  684. tor_assert(conn->_base.type == CONN_TYPE_OR);
  685. tor_assert(tor_memeq(conn->identity_digest, digest, DIGEST_LEN));
  686. if (conn->_base.marked_for_close)
  687. continue;
  688. /* Never return a non-open connection. */
  689. if (conn->_base.state != OR_CONN_STATE_OPEN) {
  690. /* If the address matches, don't launch a new connection for this
  691. * circuit. */
  692. if (!tor_addr_compare(&conn->real_addr, target_addr, CMP_EXACT))
  693. ++n_inprogress_goodaddr;
  694. continue;
  695. }
  696. /* Never return a connection that shouldn't be used for circs. */
  697. if (conn->is_bad_for_new_circs) {
  698. ++n_old;
  699. continue;
  700. }
  701. /* Never return a non-canonical connection using a recent link protocol
  702. * if the address is not what we wanted.
  703. *
  704. * (For old link protocols, we can't rely on is_canonical getting
  705. * set properly if we're talking to the right address, since we might
  706. * have an out-of-date descriptor, and we will get no NETINFO cell to
  707. * tell us about the right address.) */
  708. if (!conn->is_canonical && conn->link_proto >= 2 &&
  709. tor_addr_compare(&conn->real_addr, target_addr, CMP_EXACT)) {
  710. ++n_noncanonical;
  711. continue;
  712. }
  713. ++n_possible;
  714. if (!best) {
  715. best = conn; /* If we have no 'best' so far, this one is good enough. */
  716. continue;
  717. }
  718. if (connection_or_is_better(now, conn, best, 0))
  719. best = conn;
  720. }
  721. if (best) {
  722. *msg_out = "Connection is fine; using it.";
  723. *launch_out = 0;
  724. return best;
  725. } else if (n_inprogress_goodaddr) {
  726. *msg_out = "Connection in progress; waiting.";
  727. *launch_out = 0;
  728. return NULL;
  729. } else if (n_old || n_noncanonical) {
  730. *msg_out = "Connections all too old, or too non-canonical. "
  731. " Launching a new one.";
  732. *launch_out = 1;
  733. return NULL;
  734. } else {
  735. *msg_out = "Not connected. Connecting.";
  736. *launch_out = 1;
  737. return NULL;
  738. }
  739. }
  740. /** How old do we let a connection to an OR get before deciding it's
  741. * too old for new circuits? */
  742. #define TIME_BEFORE_OR_CONN_IS_TOO_OLD (60*60*24*7)
  743. /** Given the head of the linked list for all the or_connections with a given
  744. * identity, set elements of that list as is_bad_for_new_circs as
  745. * appropriate. Helper for connection_or_set_bad_connections().
  746. *
  747. * Specifically, we set the is_bad_for_new_circs flag on:
  748. * - all connections if <b>force</b> is true.
  749. * - all connections that are too old.
  750. * - all open non-canonical connections for which a canonical connection
  751. * exists to the same router.
  752. * - all open canonical connections for which a 'better' canonical
  753. * connection exists to the same router.
  754. * - all open non-canonical connections for which a 'better' non-canonical
  755. * connection exists to the same router at the same address.
  756. *
  757. * See connection_or_is_better() for our idea of what makes one OR connection
  758. * better than another.
  759. */
  760. static void
  761. connection_or_group_set_badness(or_connection_t *head, int force)
  762. {
  763. or_connection_t *or_conn = NULL, *best = NULL;
  764. int n_old = 0, n_inprogress = 0, n_canonical = 0, n_other = 0;
  765. time_t now = time(NULL);
  766. /* Pass 1: expire everything that's old, and see what the status of
  767. * everything else is. */
  768. for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
  769. if (or_conn->_base.marked_for_close ||
  770. or_conn->is_bad_for_new_circs)
  771. continue;
  772. if (force ||
  773. or_conn->_base.timestamp_created + TIME_BEFORE_OR_CONN_IS_TOO_OLD
  774. < now) {
  775. log_info(LD_OR,
  776. "Marking OR conn to %s:%d as too old for new circuits "
  777. "(fd %d, %d secs old).",
  778. or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
  779. (int)(now - or_conn->_base.timestamp_created));
  780. or_conn->is_bad_for_new_circs = 1;
  781. }
  782. if (or_conn->is_bad_for_new_circs) {
  783. ++n_old;
  784. } else if (or_conn->_base.state != OR_CONN_STATE_OPEN) {
  785. ++n_inprogress;
  786. } else if (or_conn->is_canonical) {
  787. ++n_canonical;
  788. } else {
  789. ++n_other;
  790. }
  791. }
  792. /* Pass 2: We know how about how good the best connection is.
  793. * expire everything that's worse, and find the very best if we can. */
  794. for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
  795. if (or_conn->_base.marked_for_close ||
  796. or_conn->is_bad_for_new_circs)
  797. continue; /* This one doesn't need to be marked bad. */
  798. if (or_conn->_base.state != OR_CONN_STATE_OPEN)
  799. continue; /* Don't mark anything bad until we have seen what happens
  800. * when the connection finishes. */
  801. if (n_canonical && !or_conn->is_canonical) {
  802. /* We have at least one open canonical connection to this router,
  803. * and this one is open but not canonical. Mark it bad. */
  804. log_info(LD_OR,
  805. "Marking OR conn to %s:%d as unsuitable for new circuits: "
  806. "(fd %d, %d secs old). It is not canonical, and we have "
  807. "another connection to that OR that is.",
  808. or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
  809. (int)(now - or_conn->_base.timestamp_created));
  810. or_conn->is_bad_for_new_circs = 1;
  811. continue;
  812. }
  813. if (!best || connection_or_is_better(now, or_conn, best, 0))
  814. best = or_conn;
  815. }
  816. if (!best)
  817. return;
  818. /* Pass 3: One connection to OR is best. If it's canonical, mark as bad
  819. * every other open connection. If it's non-canonical, mark as bad
  820. * every other open connection to the same address.
  821. *
  822. * XXXX This isn't optimal; if we have connections to an OR at multiple
  823. * addresses, we'd like to pick the best _for each address_, and mark as
  824. * bad every open connection that isn't best for its address. But this
  825. * can only occur in cases where the other OR is old (so we have no
  826. * canonical connection to it), or where all the connections to the OR are
  827. * at noncanonical addresses and we have no good direct connection (which
  828. * means we aren't at risk of attaching circuits to it anyway). As
  829. * 0.1.2.x dies out, the first case will go away, and the second one is
  830. * "mostly harmless", so a fix can wait until somebody is bored.
  831. */
  832. for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
  833. if (or_conn->_base.marked_for_close ||
  834. or_conn->is_bad_for_new_circs ||
  835. or_conn->_base.state != OR_CONN_STATE_OPEN)
  836. continue;
  837. if (or_conn != best && connection_or_is_better(now, best, or_conn, 1)) {
  838. /* This isn't the best conn, _and_ the best conn is better than it,
  839. even when we're being forgiving. */
  840. if (best->is_canonical) {
  841. log_info(LD_OR,
  842. "Marking OR conn to %s:%d as unsuitable for new circuits: "
  843. "(fd %d, %d secs old). We have a better canonical one "
  844. "(fd %d; %d secs old).",
  845. or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
  846. (int)(now - or_conn->_base.timestamp_created),
  847. best->_base.s, (int)(now - best->_base.timestamp_created));
  848. or_conn->is_bad_for_new_circs = 1;
  849. } else if (!tor_addr_compare(&or_conn->real_addr,
  850. &best->real_addr, CMP_EXACT)) {
  851. log_info(LD_OR,
  852. "Marking OR conn to %s:%d as unsuitable for new circuits: "
  853. "(fd %d, %d secs old). We have a better one with the "
  854. "same address (fd %d; %d secs old).",
  855. or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
  856. (int)(now - or_conn->_base.timestamp_created),
  857. best->_base.s, (int)(now - best->_base.timestamp_created));
  858. or_conn->is_bad_for_new_circs = 1;
  859. }
  860. }
  861. }
  862. }
  863. /** Go through all the OR connections (or if <b>digest</b> is non-NULL, just
  864. * the OR connections with that digest), and set the is_bad_for_new_circs
  865. * flag based on the rules in connection_or_group_set_badness() (or just
  866. * always set it if <b>force</b> is true).
  867. */
  868. void
  869. connection_or_set_bad_connections(const char *digest, int force)
  870. {
  871. if (!orconn_identity_map)
  872. return;
  873. DIGESTMAP_FOREACH(orconn_identity_map, identity, or_connection_t *, conn) {
  874. if (!digest || tor_memeq(digest, conn->identity_digest, DIGEST_LEN))
  875. connection_or_group_set_badness(conn, force);
  876. } DIGESTMAP_FOREACH_END;
  877. }
  878. /** <b>conn</b> is in the 'connecting' state, and it failed to complete
  879. * a TCP connection. Send notifications appropriately.
  880. *
  881. * <b>reason</b> specifies the or_conn_end_reason for the failure;
  882. * <b>msg</b> specifies the strerror-style error message.
  883. */
  884. void
  885. connection_or_connect_failed(or_connection_t *conn,
  886. int reason, const char *msg)
  887. {
  888. control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED, reason);
  889. if (!authdir_mode_tests_reachability(get_options()))
  890. control_event_bootstrap_problem(msg, reason);
  891. }
  892. /** Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
  893. * handshake with an OR with identity digest <b>id_digest</b>.
  894. *
  895. * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
  896. * return that connection. If the connect() is in progress, set the
  897. * new conn's state to 'connecting' and return it. If connect() succeeds,
  898. * call connection_tls_start_handshake() on it.
  899. *
  900. * This function is called from router_retry_connections(), for
  901. * ORs connecting to ORs, and circuit_establish_circuit(), for
  902. * OPs connecting to ORs.
  903. *
  904. * Return the launched conn, or NULL if it failed.
  905. */
  906. or_connection_t *
  907. connection_or_connect(const tor_addr_t *_addr, uint16_t port,
  908. const char *id_digest)
  909. {
  910. or_connection_t *conn;
  911. const or_options_t *options = get_options();
  912. int socket_error = 0;
  913. tor_addr_t addr;
  914. int r;
  915. tor_addr_t proxy_addr;
  916. uint16_t proxy_port;
  917. int proxy_type;
  918. tor_assert(_addr);
  919. tor_assert(id_digest);
  920. tor_addr_copy(&addr, _addr);
  921. if (server_mode(options) && router_digest_is_me(id_digest)) {
  922. log_info(LD_PROTOCOL,"Client asked me to connect to myself. Refusing.");
  923. return NULL;
  924. }
  925. conn = or_connection_new(AF_INET);
  926. /* set up conn so it's got all the data we need to remember */
  927. connection_or_init_conn_from_address(conn, &addr, port, id_digest, 1);
  928. conn->_base.state = OR_CONN_STATE_CONNECTING;
  929. control_event_or_conn_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
  930. /* If we are using a proxy server, find it and use it. */
  931. r = get_proxy_addrport(&proxy_addr, &proxy_port, &proxy_type, TO_CONN(conn));
  932. if (r == 0) {
  933. conn->proxy_type = proxy_type;
  934. if (proxy_type != PROXY_NONE) {
  935. tor_addr_copy(&addr, &proxy_addr);
  936. port = proxy_port;
  937. conn->_base.proxy_state = PROXY_INFANT;
  938. }
  939. } else {
  940. log_warn(LD_GENERAL, "Tried to connect through proxy, but proxy address "
  941. "could not be found.");
  942. connection_free(TO_CONN(conn));
  943. return NULL;
  944. }
  945. switch (connection_connect(TO_CONN(conn), conn->_base.address,
  946. &addr, port, &socket_error)) {
  947. case -1:
  948. /* If the connection failed immediately, and we're using
  949. * a proxy, our proxy is down. Don't blame the Tor server. */
  950. if (conn->_base.proxy_state == PROXY_INFANT)
  951. entry_guard_register_connect_status(conn->identity_digest,
  952. 0, 1, time(NULL));
  953. connection_or_connect_failed(conn,
  954. errno_to_orconn_end_reason(socket_error),
  955. tor_socket_strerror(socket_error));
  956. connection_free(TO_CONN(conn));
  957. return NULL;
  958. case 0:
  959. connection_watch_events(TO_CONN(conn), READ_EVENT | WRITE_EVENT);
  960. /* writable indicates finish, readable indicates broken link,
  961. error indicates broken link on windows */
  962. return conn;
  963. /* case 1: fall through */
  964. }
  965. if (connection_or_finished_connecting(conn) < 0) {
  966. /* already marked for close */
  967. return NULL;
  968. }
  969. return conn;
  970. }
  971. /** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
  972. * we initiated the connection, else it's 1.
  973. *
  974. * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and
  975. * pass <b>conn</b> to connection_tls_continue_handshake().
  976. *
  977. * Return -1 if <b>conn</b> is broken, else return 0.
  978. */
  979. int
  980. connection_tls_start_handshake(or_connection_t *conn, int receiving)
  981. {
  982. conn->_base.state = OR_CONN_STATE_TLS_HANDSHAKING;
  983. tor_assert(!conn->tls);
  984. conn->tls = tor_tls_new(conn->_base.s, receiving);
  985. tor_tls_set_logged_address(conn->tls, // XXX client and relay?
  986. escaped_safe_str(conn->_base.address));
  987. if (!conn->tls) {
  988. log_warn(LD_BUG,"tor_tls_new failed. Closing.");
  989. return -1;
  990. }
  991. #ifdef USE_BUFFEREVENTS
  992. if (connection_type_uses_bufferevent(TO_CONN(conn))) {
  993. const int filtering = get_options()->_UseFilteringSSLBufferevents;
  994. struct bufferevent *b =
  995. tor_tls_init_bufferevent(conn->tls, conn->_base.bufev, conn->_base.s,
  996. receiving, filtering);
  997. if (!b) {
  998. log_warn(LD_BUG,"tor_tls_init_bufferevent failed. Closing.");
  999. return -1;
  1000. }
  1001. conn->_base.bufev = b;
  1002. if (conn->bucket_cfg)
  1003. tor_set_bufferevent_rate_limit(conn->_base.bufev, conn->bucket_cfg);
  1004. connection_enable_rate_limiting(TO_CONN(conn));
  1005. connection_configure_bufferevent_callbacks(TO_CONN(conn));
  1006. bufferevent_setcb(b,
  1007. connection_handle_read_cb,
  1008. connection_handle_write_cb,
  1009. connection_or_handle_event_cb,/* overriding this one*/
  1010. TO_CONN(conn));
  1011. }
  1012. #endif
  1013. connection_start_reading(TO_CONN(conn));
  1014. log_debug(LD_HANDSHAKE,"starting TLS handshake on fd %d", conn->_base.s);
  1015. note_crypto_pk_op(receiving ? TLS_HANDSHAKE_S : TLS_HANDSHAKE_C);
  1016. IF_HAS_BUFFEREVENT(TO_CONN(conn), {
  1017. /* ???? */;
  1018. }) ELSE_IF_NO_BUFFEREVENT {
  1019. if (connection_tls_continue_handshake(conn) < 0)
  1020. return -1;
  1021. }
  1022. return 0;
  1023. }
  1024. /** Invoked on the server side from inside tor_tls_read() when the server
  1025. * gets a successful TLS renegotiation from the client. */
  1026. static void
  1027. connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn)
  1028. {
  1029. or_connection_t *conn = _conn;
  1030. (void)tls;
  1031. /* Don't invoke this again. */
  1032. tor_tls_set_renegotiate_callback(tls, NULL, NULL);
  1033. tor_tls_block_renegotiation(tls);
  1034. if (connection_tls_finish_handshake(conn) < 0) {
  1035. /* XXXX_TLS double-check that it's ok to do this from inside read. */
  1036. /* XXXX_TLS double-check that this verifies certificates. */
  1037. connection_mark_for_close(TO_CONN(conn));
  1038. }
  1039. }
  1040. /** Move forward with the tls handshake. If it finishes, hand
  1041. * <b>conn</b> to connection_tls_finish_handshake().
  1042. *
  1043. * Return -1 if <b>conn</b> is broken, else return 0.
  1044. */
  1045. int
  1046. connection_tls_continue_handshake(or_connection_t *conn)
  1047. {
  1048. int result;
  1049. check_no_tls_errors();
  1050. again:
  1051. if (conn->_base.state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
  1052. // log_notice(LD_OR, "Renegotiate with %p", conn->tls);
  1053. result = tor_tls_renegotiate(conn->tls);
  1054. // log_notice(LD_OR, "Result: %d", result);
  1055. } else {
  1056. tor_assert(conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING);
  1057. // log_notice(LD_OR, "Continue handshake with %p", conn->tls);
  1058. result = tor_tls_handshake(conn->tls);
  1059. // log_notice(LD_OR, "Result: %d", result);
  1060. }
  1061. switch (result) {
  1062. CASE_TOR_TLS_ERROR_ANY:
  1063. log_info(LD_OR,"tls error [%s]. breaking connection.",
  1064. tor_tls_err_to_string(result));
  1065. return -1;
  1066. case TOR_TLS_DONE:
  1067. if (! tor_tls_used_v1_handshake(conn->tls)) {
  1068. if (!tor_tls_is_server(conn->tls)) {
  1069. if (conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING) {
  1070. if (tor_tls_received_v3_certificate(conn->tls)) {
  1071. log_notice(LD_OR, "Client got a v3 cert! Moving on to v3 "
  1072. "handshake.");
  1073. return connection_or_launch_v3_or_handshake(conn);
  1074. } else {
  1075. log_debug(LD_OR, "Done with initial SSL handshake (client-side). "
  1076. "Requesting renegotiation.");
  1077. conn->_base.state = OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING;
  1078. goto again;
  1079. }
  1080. }
  1081. // log_notice(LD_OR,"Done. state was %d.", conn->_base.state);
  1082. } else {
  1083. /* v2/v3 handshake, but not a client. */
  1084. log_debug(LD_OR, "Done with initial SSL handshake (server-side). "
  1085. "Expecting renegotiation or VERSIONS cell");
  1086. tor_tls_set_renegotiate_callback(conn->tls,
  1087. connection_or_tls_renegotiated_cb,
  1088. conn);
  1089. conn->_base.state = OR_CONN_STATE_TLS_SERVER_RENEGOTIATING;
  1090. connection_stop_writing(TO_CONN(conn));
  1091. connection_start_reading(TO_CONN(conn));
  1092. return 0;
  1093. }
  1094. }
  1095. return connection_tls_finish_handshake(conn);
  1096. case TOR_TLS_WANTWRITE:
  1097. connection_start_writing(TO_CONN(conn));
  1098. log_debug(LD_OR,"wanted write");
  1099. return 0;
  1100. case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
  1101. log_debug(LD_OR,"wanted read");
  1102. return 0;
  1103. case TOR_TLS_CLOSE:
  1104. log_info(LD_OR,"tls closed. breaking connection.");
  1105. return -1;
  1106. }
  1107. return 0;
  1108. }
  1109. #ifdef USE_BUFFEREVENTS
  1110. static void
  1111. connection_or_handle_event_cb(struct bufferevent *bufev, short event,
  1112. void *arg)
  1113. {
  1114. struct or_connection_t *conn = TO_OR_CONN(arg);
  1115. /* XXXX cut-and-paste code; should become a function. */
  1116. if (event & BEV_EVENT_CONNECTED) {
  1117. if (conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING) {
  1118. if (tor_tls_finish_handshake(conn->tls) < 0) {
  1119. log_warn(LD_OR, "Problem finishing handshake");
  1120. connection_mark_for_close(TO_CONN(conn));
  1121. return;
  1122. }
  1123. }
  1124. if (! tor_tls_used_v1_handshake(conn->tls)) {
  1125. if (!tor_tls_is_server(conn->tls)) {
  1126. if (conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING) {
  1127. if (tor_tls_received_v3_certificate(conn->tls)) {
  1128. log_notice(LD_OR, "Client got a v3 cert!");
  1129. if (connection_or_launch_v3_or_handshake(conn) < 0)
  1130. connection_mark_for_close(TO_CONN(conn));
  1131. return;
  1132. } else {
  1133. conn->_base.state = OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING;
  1134. tor_tls_unblock_renegotiation(conn->tls);
  1135. if (bufferevent_ssl_renegotiate(conn->_base.bufev)<0) {
  1136. log_warn(LD_OR, "Start_renegotiating went badly.");
  1137. connection_mark_for_close(TO_CONN(conn));
  1138. }
  1139. tor_tls_unblock_renegotiation(conn->tls);
  1140. return; /* ???? */
  1141. }
  1142. }
  1143. } else if (tor_tls_get_num_server_handshakes(conn->tls) == 1) {
  1144. /* v2 or v3 handshake, as a server. Only got one handshake, so
  1145. * wait for the next one. */
  1146. tor_tls_set_renegotiate_callback(conn->tls,
  1147. connection_or_tls_renegotiated_cb,
  1148. conn);
  1149. conn->_base.state = OR_CONN_STATE_TLS_SERVER_RENEGOTIATING;
  1150. /* return 0; */
  1151. return; /* ???? */
  1152. } else {
  1153. const int handshakes = tor_tls_get_num_server_handshakes(conn->tls);
  1154. tor_assert(handshakes >= 2);
  1155. if (handshakes == 2) {
  1156. /* v2 handshake, as a server. Two handshakes happened already,
  1157. * so we treat renegotiation as done.
  1158. */
  1159. connection_or_tls_renegotiated_cb(conn->tls, conn);
  1160. } else {
  1161. log_warn(LD_OR, "More than two handshakes done on connection. "
  1162. "Closing.");
  1163. connection_mark_for_close(TO_CONN(conn));
  1164. }
  1165. return;
  1166. }
  1167. }
  1168. connection_watch_events(TO_CONN(conn), READ_EVENT|WRITE_EVENT);
  1169. if (connection_tls_finish_handshake(conn) < 0)
  1170. connection_mark_for_close(TO_CONN(conn)); /* ???? */
  1171. return;
  1172. }
  1173. if (event & BEV_EVENT_ERROR) {
  1174. unsigned long err;
  1175. while ((err = bufferevent_get_openssl_error(bufev))) {
  1176. tor_tls_log_one_error(conn->tls, err, LOG_WARN, LD_OR,
  1177. "handshaking (with bufferevent)");
  1178. }
  1179. }
  1180. connection_handle_event_cb(bufev, event, arg);
  1181. }
  1182. #endif
  1183. /** Return 1 if we initiated this connection, or 0 if it started
  1184. * out as an incoming connection.
  1185. */
  1186. int
  1187. connection_or_nonopen_was_started_here(or_connection_t *conn)
  1188. {
  1189. tor_assert(conn->_base.type == CONN_TYPE_OR);
  1190. if (!conn->tls)
  1191. return 1; /* it's still in proxy states or something */
  1192. if (conn->handshake_state)
  1193. return conn->handshake_state->started_here;
  1194. return !tor_tls_is_server(conn->tls);
  1195. }
  1196. /** Set the circid_type field of <b>conn</b> (which determines which part of
  1197. * the circuit ID space we're willing to use) based on comparing our ID to
  1198. * <b>identity_rcvd</b> */
  1199. void
  1200. connection_or_set_circid_type(or_connection_t *conn,
  1201. crypto_pk_env_t *identity_rcvd)
  1202. {
  1203. const int started_here = connection_or_nonopen_was_started_here(conn);
  1204. crypto_pk_env_t *our_identity =
  1205. started_here ? get_tlsclient_identity_key() :
  1206. get_server_identity_key();
  1207. if (identity_rcvd) {
  1208. if (crypto_pk_cmp_keys(our_identity, identity_rcvd)<0) {
  1209. conn->circ_id_type = CIRC_ID_TYPE_LOWER;
  1210. } else {
  1211. conn->circ_id_type = CIRC_ID_TYPE_HIGHER;
  1212. }
  1213. } else {
  1214. conn->circ_id_type = CIRC_ID_TYPE_NEITHER;
  1215. }
  1216. }
  1217. /** <b>Conn</b> just completed its handshake. Return 0 if all is well, and
  1218. * return -1 if he is lying, broken, or otherwise something is wrong.
  1219. *
  1220. * If we initiated this connection (<b>started_here</b> is true), make sure
  1221. * the other side sent a correctly formed certificate. If I initiated the
  1222. * connection, make sure it's the right guy.
  1223. *
  1224. * Otherwise (if we _didn't_ initiate this connection), it's okay for
  1225. * the certificate to be weird or absent.
  1226. *
  1227. * If we return 0, and the certificate is as expected, write a hash of the
  1228. * identity key into <b>digest_rcvd_out</b>, which must have DIGEST_LEN
  1229. * space in it.
  1230. * If the certificate is invalid or missing on an incoming connection,
  1231. * we return 0 and set <b>digest_rcvd_out</b> to DIGEST_LEN NUL bytes.
  1232. * (If we return -1, the contents of this buffer are undefined.)
  1233. *
  1234. * As side effects,
  1235. * 1) Set conn->circ_id_type according to tor-spec.txt.
  1236. * 2) If we're an authdirserver and we initiated the connection: drop all
  1237. * descriptors that claim to be on that IP/port but that aren't
  1238. * this guy; and note that this guy is reachable.
  1239. * 3) If this is a bridge and we didn't configure its identity
  1240. * fingerprint, remember the keyid we just learned.
  1241. */
  1242. static int
  1243. connection_or_check_valid_tls_handshake(or_connection_t *conn,
  1244. int started_here,
  1245. char *digest_rcvd_out)
  1246. {
  1247. crypto_pk_env_t *identity_rcvd=NULL;
  1248. const or_options_t *options = get_options();
  1249. int severity = server_mode(options) ? LOG_PROTOCOL_WARN : LOG_WARN;
  1250. const char *safe_address =
  1251. started_here ? conn->_base.address :
  1252. safe_str_client(conn->_base.address);
  1253. const char *conn_type = started_here ? "outgoing" : "incoming";
  1254. int has_cert = 0;
  1255. check_no_tls_errors();
  1256. has_cert = tor_tls_peer_has_cert(conn->tls);
  1257. if (started_here && !has_cert) {
  1258. log_info(LD_HANDSHAKE,"Tried connecting to router at %s:%d, but it didn't "
  1259. "send a cert! Closing.",
  1260. safe_address, conn->_base.port);
  1261. return -1;
  1262. } else if (!has_cert) {
  1263. log_debug(LD_HANDSHAKE,"Got incoming connection with no certificate. "
  1264. "That's ok.");
  1265. }
  1266. check_no_tls_errors();
  1267. if (has_cert) {
  1268. int v = tor_tls_verify(started_here?severity:LOG_INFO,
  1269. conn->tls, &identity_rcvd);
  1270. if (started_here && v<0) {
  1271. log_fn(severity,LD_HANDSHAKE,"Tried connecting to router at %s:%d: It"
  1272. " has a cert but it's invalid. Closing.",
  1273. safe_address, conn->_base.port);
  1274. return -1;
  1275. } else if (v<0) {
  1276. log_info(LD_HANDSHAKE,"Incoming connection gave us an invalid cert "
  1277. "chain; ignoring.");
  1278. } else {
  1279. log_debug(LD_HANDSHAKE,
  1280. "The certificate seems to be valid on %s connection "
  1281. "with %s:%d", conn_type, safe_address, conn->_base.port);
  1282. }
  1283. check_no_tls_errors();
  1284. }
  1285. if (identity_rcvd) {
  1286. crypto_pk_get_digest(identity_rcvd, digest_rcvd_out);
  1287. } else {
  1288. memset(digest_rcvd_out, 0, DIGEST_LEN);
  1289. }
  1290. connection_or_set_circid_type(conn, identity_rcvd);
  1291. crypto_free_pk_env(identity_rcvd);
  1292. if (started_here)
  1293. return connection_or_client_learned_peer_id(conn,
  1294. (const uint8_t*)digest_rcvd_out);
  1295. return 0;
  1296. }
  1297. /** Called when we (as a connection initiator) have definitively,
  1298. * authenticatedly, learned that ID of the Tor instance on the other
  1299. * side of <b>conn</b> is <b>peer_id</b>. For v1 and v2 handshakes,
  1300. * this is right after we get a certificate chain in a TLS handshake
  1301. * or renegotiation. For v3 handshakes, this is right after we get a
  1302. * certificate chain in a CERT cell.
  1303. *
  1304. * If we want any particular ID before, record the one we got.
  1305. *
  1306. * If we wanted an ID, but we didn't get it, log a warning and return -1.
  1307. *
  1308. * If we're testing reachability, remember what we learned.
  1309. *
  1310. * Return 0 on success, -1 on failure.
  1311. */
  1312. int
  1313. connection_or_client_learned_peer_id(or_connection_t *conn,
  1314. const uint8_t *peer_id)
  1315. {
  1316. int as_expected = 1;
  1317. const or_options_t *options = get_options();
  1318. int severity = server_mode(options) ? LOG_PROTOCOL_WARN : LOG_WARN;
  1319. if (tor_digest_is_zero(conn->identity_digest)) {
  1320. connection_or_set_identity_digest(conn, (const char*)peer_id);
  1321. tor_free(conn->nickname);
  1322. conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
  1323. conn->nickname[0] = '$';
  1324. base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
  1325. conn->identity_digest, DIGEST_LEN);
  1326. log_info(LD_HANDSHAKE, "Connected to router %s at %s:%d without knowing "
  1327. "its key. Hoping for the best.",
  1328. conn->nickname, conn->_base.address, conn->_base.port);
  1329. /* if it's a bridge and we didn't know its identity fingerprint, now
  1330. * we do -- remember it for future attempts. */
  1331. learned_router_identity(&conn->_base.addr, conn->_base.port,
  1332. (const char*)peer_id);
  1333. }
  1334. if (tor_memneq(peer_id, conn->identity_digest, DIGEST_LEN)) {
  1335. /* I was aiming for a particular digest. I didn't get it! */
  1336. char seen[HEX_DIGEST_LEN+1];
  1337. char expected[HEX_DIGEST_LEN+1];
  1338. base16_encode(seen, sizeof(seen), (const char*)peer_id, DIGEST_LEN);
  1339. base16_encode(expected, sizeof(expected), conn->identity_digest,
  1340. DIGEST_LEN);
  1341. log_fn(severity, LD_HANDSHAKE,
  1342. "Tried connecting to router at %s:%d, but identity key was not "
  1343. "as expected: wanted %s but got %s.",
  1344. conn->_base.address, conn->_base.port, expected, seen);
  1345. entry_guard_register_connect_status(conn->identity_digest, 0, 1,
  1346. time(NULL));
  1347. control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED,
  1348. END_OR_CONN_REASON_OR_IDENTITY);
  1349. if (!authdir_mode_tests_reachability(options))
  1350. control_event_bootstrap_problem("foo", END_OR_CONN_REASON_OR_IDENTITY);
  1351. as_expected = 0;
  1352. }
  1353. if (authdir_mode_tests_reachability(options)) {
  1354. dirserv_orconn_tls_done(conn->_base.address, conn->_base.port,
  1355. (const char*)peer_id, as_expected);
  1356. }
  1357. if (!as_expected)
  1358. return -1;
  1359. return 0;
  1360. }
  1361. /** The v1/v2 TLS handshake is finished.
  1362. *
  1363. * Make sure we are happy with the person we just handshaked with.
  1364. *
  1365. * If he initiated the connection, make sure he's not already connected,
  1366. * then initialize conn from the information in router.
  1367. *
  1368. * If all is successful, call circuit_n_conn_done() to handle events
  1369. * that have been pending on the <tls handshake completion. Also set the
  1370. * directory to be dirty (only matters if I'm an authdirserver).
  1371. *
  1372. * If this is a v2 TLS handshake, send a versions cell.
  1373. */
  1374. static int
  1375. connection_tls_finish_handshake(or_connection_t *conn)
  1376. {
  1377. char digest_rcvd[DIGEST_LEN];
  1378. int started_here = connection_or_nonopen_was_started_here(conn);
  1379. log_debug(LD_HANDSHAKE,"%s tls handshake on %p with %s done. verifying.",
  1380. started_here?"outgoing":"incoming",
  1381. conn,
  1382. safe_str_client(conn->_base.address));
  1383. directory_set_dirty();
  1384. if (connection_or_check_valid_tls_handshake(conn, started_here,
  1385. digest_rcvd) < 0)
  1386. return -1;
  1387. circuit_build_times_network_is_live(&circ_times);
  1388. if (tor_tls_used_v1_handshake(conn->tls)) {
  1389. conn->link_proto = 1;
  1390. if (!started_here) {
  1391. connection_or_init_conn_from_address(conn, &conn->_base.addr,
  1392. conn->_base.port, digest_rcvd, 0);
  1393. }
  1394. tor_tls_block_renegotiation(conn->tls);
  1395. return connection_or_set_state_open(conn);
  1396. } else {
  1397. conn->_base.state = OR_CONN_STATE_OR_HANDSHAKING_V2;
  1398. if (connection_init_or_handshake_state(conn, started_here) < 0)
  1399. return -1;
  1400. if (!started_here) {
  1401. connection_or_init_conn_from_address(conn, &conn->_base.addr,
  1402. conn->_base.port, digest_rcvd, 0);
  1403. }
  1404. return connection_or_send_versions(conn, 0);
  1405. }
  1406. }
  1407. /**
  1408. * Called as client when initial TLS handshake is done, and we notice
  1409. * that we got a v3-handshake signalling certificate from the server.
  1410. * Set up structures, do bookkeeping, and send the versions cell.
  1411. * Return 0 on success and -1 on failure.
  1412. */
  1413. static int
  1414. connection_or_launch_v3_or_handshake(or_connection_t *conn)
  1415. {
  1416. tor_assert(connection_or_nonopen_was_started_here(conn));
  1417. tor_assert(tor_tls_received_v3_certificate(conn->tls));
  1418. circuit_build_times_network_is_live(&circ_times);
  1419. conn->_base.state = OR_CONN_STATE_OR_HANDSHAKING_V3;
  1420. if (connection_init_or_handshake_state(conn, 1) < 0)
  1421. return -1;
  1422. return connection_or_send_versions(conn, 1);
  1423. }
  1424. /** Allocate a new connection handshake state for the connection
  1425. * <b>conn</b>. Return 0 on success, -1 on failure. */
  1426. int
  1427. connection_init_or_handshake_state(or_connection_t *conn, int started_here)
  1428. {
  1429. or_handshake_state_t *s;
  1430. s = conn->handshake_state = tor_malloc_zero(sizeof(or_handshake_state_t));
  1431. s->started_here = started_here ? 1 : 0;
  1432. return 0;
  1433. }
  1434. /** Free all storage held by <b>state</b>. */
  1435. void
  1436. or_handshake_state_free(or_handshake_state_t *state)
  1437. {
  1438. if (!state)
  1439. return;
  1440. crypto_free_digest_env(state->digest_sent);
  1441. crypto_free_digest_env(state->digest_received);
  1442. tor_cert_free(state->auth_cert);
  1443. tor_cert_free(state->id_cert);
  1444. memset(state, 0xBE, sizeof(or_handshake_state_t));
  1445. tor_free(state);
  1446. }
  1447. /**
  1448. * Remember that <b>cell</b> has been transmitted (if <b>incoming</b> is
  1449. * false) or received (if <b>incoming is true) during a V3 handshake using
  1450. * <b>state</b>.
  1451. *
  1452. * (We don't record the cell, but we keep a digest of everything sent or
  1453. * received during the v3 handshake, and the client signs it in an
  1454. * authenticate cell.)
  1455. */
  1456. void
  1457. or_handshake_state_record_cell(or_handshake_state_t *state,
  1458. const cell_t *cell,
  1459. int incoming)
  1460. {
  1461. crypto_digest_env_t *d, **dptr;
  1462. packed_cell_t packed;
  1463. if (!incoming) {
  1464. log_warn(LD_BUG, "We shouldn't be sending any non-variable-length cells "
  1465. "whilemaking a handshake digest. But we think we are.");
  1466. }
  1467. dptr = incoming ? &state->digest_received : &state->digest_sent;
  1468. if (! *dptr)
  1469. *dptr = crypto_new_digest256_env(DIGEST_SHA256);
  1470. d = *dptr;
  1471. /* Re-packing like this is a little inefficient, but we don't have to do
  1472. this very often at all. */
  1473. cell_pack(&packed, cell);
  1474. crypto_digest_add_bytes(d, packed.body, sizeof(packed.body));
  1475. memset(&packed, 0, sizeof(packed));
  1476. }
  1477. /** Remember that a variable-length <b>cell</b> has been transmitted (if
  1478. * <b>incoming</b> is false) or received (if <b>incoming is true) during a V3
  1479. * handshake using <b>state</b>.
  1480. *
  1481. * (We don't record the cell, but we keep a digest of everything sent or
  1482. * received during the v3 handshake, and the client signs it in an
  1483. * authenticate cell.)
  1484. */
  1485. void
  1486. or_handshake_state_record_var_cell(or_handshake_state_t *state,
  1487. const var_cell_t *cell,
  1488. int incoming)
  1489. {
  1490. crypto_digest_env_t *d, **dptr;
  1491. char buf[VAR_CELL_HEADER_SIZE];
  1492. dptr = incoming ? &state->digest_received : &state->digest_sent;
  1493. if (! *dptr)
  1494. *dptr = crypto_new_digest256_env(DIGEST_SHA256);
  1495. d = *dptr;
  1496. var_cell_pack_header(cell, buf);
  1497. crypto_digest_add_bytes(d, buf, sizeof(buf));
  1498. crypto_digest_add_bytes(d, (const char *)cell->payload, cell->payload_len);
  1499. memset(buf, 0, sizeof(buf));
  1500. }
  1501. /** Set <b>conn</b>'s state to OR_CONN_STATE_OPEN, and tell other subsystems
  1502. * as appropriate. Called when we are done with all TLS and OR handshaking.
  1503. */
  1504. int
  1505. connection_or_set_state_open(or_connection_t *conn)
  1506. {
  1507. int started_here = connection_or_nonopen_was_started_here(conn);
  1508. time_t now = time(NULL);
  1509. conn->_base.state = OR_CONN_STATE_OPEN;
  1510. control_event_or_conn_status(conn, OR_CONN_EVENT_CONNECTED, 0);
  1511. if (started_here) {
  1512. circuit_build_times_network_is_live(&circ_times);
  1513. rep_hist_note_connect_succeeded(conn->identity_digest, now);
  1514. if (entry_guard_register_connect_status(conn->identity_digest,
  1515. 1, 0, now) < 0) {
  1516. /* Close any circuits pending on this conn. We leave it in state
  1517. * 'open' though, because it didn't actually *fail* -- we just
  1518. * chose not to use it. (Otherwise
  1519. * connection_about_to_close_connection() will call a big pile of
  1520. * functions to indicate we shouldn't try it again.) */
  1521. log_debug(LD_OR, "New entry guard was reachable, but closing this "
  1522. "connection so we can retry the earlier entry guards.");
  1523. circuit_n_conn_done(conn, 0);
  1524. return -1;
  1525. }
  1526. router_set_status(conn->identity_digest, 1);
  1527. } else {
  1528. /* only report it to the geoip module if it's not a known router */
  1529. if (!router_get_by_id_digest(conn->identity_digest)) {
  1530. if (tor_addr_family(&TO_CONN(conn)->addr) == AF_INET) {
  1531. /*XXXX IP6 support ipv6 geoip.*/
  1532. uint32_t a = tor_addr_to_ipv4h(&TO_CONN(conn)->addr);
  1533. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, a, now);
  1534. }
  1535. }
  1536. }
  1537. or_handshake_state_free(conn->handshake_state);
  1538. conn->handshake_state = NULL;
  1539. IF_HAS_BUFFEREVENT(TO_CONN(conn), {
  1540. connection_watch_events(TO_CONN(conn), READ_EVENT|WRITE_EVENT);
  1541. }) ELSE_IF_NO_BUFFEREVENT {
  1542. connection_start_reading(TO_CONN(conn));
  1543. }
  1544. circuit_n_conn_done(conn, 1); /* send the pending creates, if any. */
  1545. return 0;
  1546. }
  1547. /** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s outbuf.
  1548. * For cells that use or affect a circuit, this should only be called by
  1549. * connection_or_flush_from_first_active_circuit().
  1550. */
  1551. void
  1552. connection_or_write_cell_to_buf(const cell_t *cell, or_connection_t *conn)
  1553. {
  1554. packed_cell_t networkcell;
  1555. tor_assert(cell);
  1556. tor_assert(conn);
  1557. cell_pack(&networkcell, cell);
  1558. connection_write_to_buf(networkcell.body, CELL_NETWORK_SIZE, TO_CONN(conn));
  1559. if (conn->_base.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
  1560. or_handshake_state_record_cell(conn->handshake_state, cell, 0);
  1561. if (cell->command != CELL_PADDING)
  1562. conn->timestamp_last_added_nonpadding = approx_time();
  1563. }
  1564. /** Pack a variable-length <b>cell</b> into wire-format, and write it onto
  1565. * <b>conn</b>'s outbuf. Right now, this <em>DOES NOT</em> support cells that
  1566. * affect a circuit.
  1567. */
  1568. void
  1569. connection_or_write_var_cell_to_buf(const var_cell_t *cell,
  1570. or_connection_t *conn)
  1571. {
  1572. char hdr[VAR_CELL_HEADER_SIZE];
  1573. tor_assert(cell);
  1574. tor_assert(conn);
  1575. var_cell_pack_header(cell, hdr);
  1576. connection_write_to_buf(hdr, sizeof(hdr), TO_CONN(conn));
  1577. connection_write_to_buf((char*)cell->payload,
  1578. cell->payload_len, TO_CONN(conn));
  1579. if (conn->_base.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
  1580. or_handshake_state_record_var_cell(conn->handshake_state, cell, 0);
  1581. if (cell->command != CELL_PADDING)
  1582. conn->timestamp_last_added_nonpadding = approx_time();
  1583. }
  1584. /** See whether there's a variable-length cell waiting on <b>or_conn</b>'s
  1585. * inbuf. Return values as for fetch_var_cell_from_buf(). */
  1586. static int
  1587. connection_fetch_var_cell_from_buf(or_connection_t *or_conn, var_cell_t **out)
  1588. {
  1589. connection_t *conn = TO_CONN(or_conn);
  1590. IF_HAS_BUFFEREVENT(conn, {
  1591. struct evbuffer *input = bufferevent_get_input(conn->bufev);
  1592. return fetch_var_cell_from_evbuffer(input, out, or_conn->link_proto);
  1593. }) ELSE_IF_NO_BUFFEREVENT {
  1594. return fetch_var_cell_from_buf(conn->inbuf, out, or_conn->link_proto);
  1595. }
  1596. }
  1597. /** Process cells from <b>conn</b>'s inbuf.
  1598. *
  1599. * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
  1600. * and hand it to command_process_cell().
  1601. *
  1602. * Always return 0.
  1603. */
  1604. static int
  1605. connection_or_process_cells_from_inbuf(or_connection_t *conn)
  1606. {
  1607. var_cell_t *var_cell;
  1608. while (1) {
  1609. log_debug(LD_OR,
  1610. "%d: starting, inbuf_datalen %d (%d pending in tls object).",
  1611. conn->_base.s,(int)connection_get_inbuf_len(TO_CONN(conn)),
  1612. tor_tls_get_pending_bytes(conn->tls));
  1613. if (connection_fetch_var_cell_from_buf(conn, &var_cell)) {
  1614. if (!var_cell)
  1615. return 0; /* not yet. */
  1616. circuit_build_times_network_is_live(&circ_times);
  1617. command_process_var_cell(var_cell, conn);
  1618. var_cell_free(var_cell);
  1619. } else {
  1620. char buf[CELL_NETWORK_SIZE];
  1621. cell_t cell;
  1622. if (connection_get_inbuf_len(TO_CONN(conn))
  1623. < CELL_NETWORK_SIZE) /* whole response available? */
  1624. return 0; /* not yet */
  1625. circuit_build_times_network_is_live(&circ_times);
  1626. connection_fetch_from_buf(buf, CELL_NETWORK_SIZE, TO_CONN(conn));
  1627. /* retrieve cell info from buf (create the host-order struct from the
  1628. * network-order string) */
  1629. cell_unpack(&cell, buf);
  1630. command_process_cell(&cell, conn);
  1631. }
  1632. }
  1633. }
  1634. /** Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
  1635. * onto OR connection <b>conn</b>. Don't perform range-checking on reason:
  1636. * we may want to propagate reasons from other cells.
  1637. *
  1638. * Return 0.
  1639. */
  1640. int
  1641. connection_or_send_destroy(circid_t circ_id, or_connection_t *conn, int reason)
  1642. {
  1643. cell_t cell;
  1644. tor_assert(conn);
  1645. memset(&cell, 0, sizeof(cell_t));
  1646. cell.circ_id = circ_id;
  1647. cell.command = CELL_DESTROY;
  1648. cell.payload[0] = (uint8_t) reason;
  1649. log_debug(LD_OR,"Sending destroy (circID %d).", circ_id);
  1650. connection_or_write_cell_to_buf(&cell, conn);
  1651. return 0;
  1652. }
  1653. /** Array of recognized link protocol versions. */
  1654. static const uint16_t or_protocol_versions[] = { 1, 2, 3 };
  1655. /** Number of versions in <b>or_protocol_versions</b>. */
  1656. static const int n_or_protocol_versions =
  1657. (int)( sizeof(or_protocol_versions)/sizeof(uint16_t) );
  1658. /** Return true iff <b>v</b> is a link protocol version that this Tor
  1659. * implementation believes it can support. */
  1660. int
  1661. is_or_protocol_version_known(uint16_t v)
  1662. {
  1663. int i;
  1664. for (i = 0; i < n_or_protocol_versions; ++i) {
  1665. if (or_protocol_versions[i] == v)
  1666. return 1;
  1667. }
  1668. return 0;
  1669. }
  1670. /** Send a VERSIONS cell on <b>conn</b>, telling the other host about the
  1671. * link protocol versions that this Tor can support.
  1672. *
  1673. * If <b>v3_plus</b>, this is part of a V3 protocol handshake, so only
  1674. * allow protocol version v3 or later. If not <b>v3_plus</b>, this is
  1675. * not part of a v3 protocol handshake, so don't allow protocol v3 or
  1676. * later.
  1677. **/
  1678. int
  1679. connection_or_send_versions(or_connection_t *conn, int v3_plus)
  1680. {
  1681. var_cell_t *cell;
  1682. int i;
  1683. int n_versions = 0;
  1684. const int min_version = v3_plus ? 3 : 0;
  1685. const int max_version = v3_plus ? UINT16_MAX : 2;
  1686. tor_assert(conn->handshake_state &&
  1687. !conn->handshake_state->sent_versions_at);
  1688. cell = var_cell_new(n_or_protocol_versions * 2);
  1689. cell->command = CELL_VERSIONS;
  1690. for (i = 0; i < n_or_protocol_versions; ++i) {
  1691. uint16_t v = or_protocol_versions[i];
  1692. if (v < min_version || v > max_version)
  1693. continue;
  1694. set_uint16(cell->payload+(2*n_versions), htons(v));
  1695. ++n_versions;
  1696. }
  1697. cell->payload_len = n_versions * 2;
  1698. connection_or_write_var_cell_to_buf(cell, conn);
  1699. conn->handshake_state->sent_versions_at = time(NULL);
  1700. var_cell_free(cell);
  1701. return 0;
  1702. }
  1703. /** Send a NETINFO cell on <b>conn</b>, telling the other server what we know
  1704. * about their address, our address, and the current time. */
  1705. int
  1706. connection_or_send_netinfo(or_connection_t *conn)
  1707. {
  1708. cell_t cell;
  1709. time_t now = time(NULL);
  1710. const routerinfo_t *me;
  1711. int len;
  1712. uint8_t *out;
  1713. memset(&cell, 0, sizeof(cell_t));
  1714. cell.command = CELL_NETINFO;
  1715. /* Timestamp. */
  1716. set_uint32(cell.payload, htonl((uint32_t)now));
  1717. /* Their address. */
  1718. out = cell.payload + 4;
  1719. len = append_address_to_payload(out, &conn->_base.addr);
  1720. if (len<0)
  1721. return -1;
  1722. out += len;
  1723. /* My address. */
  1724. if ((me = router_get_my_routerinfo())) {
  1725. tor_addr_t my_addr;
  1726. *out++ = 1; /* only one address is supported. */
  1727. tor_addr_from_ipv4h(&my_addr, me->addr);
  1728. len = append_address_to_payload(out, &my_addr);
  1729. if (len < 0)
  1730. return -1;
  1731. } else {
  1732. *out = 0;
  1733. }
  1734. connection_or_write_cell_to_buf(&cell, conn);
  1735. return 0;
  1736. }
  1737. /** Send a CERT cell on the connection <b>conn</b>. Return 0 on success, -1
  1738. * on failure. */
  1739. int
  1740. connection_or_send_cert_cell(or_connection_t *conn)
  1741. {
  1742. const tor_cert_t *link_cert = NULL, *id_cert = NULL;
  1743. const uint8_t *link_encoded = NULL, *id_encoded = NULL;
  1744. size_t link_len, id_len;
  1745. var_cell_t *cell;
  1746. size_t cell_len;
  1747. int pos;
  1748. int server_mode;
  1749. tor_assert(conn->_base.state == OR_CONN_STATE_OR_HANDSHAKING_V3);
  1750. if (! conn->handshake_state)
  1751. return -1;
  1752. server_mode = ! conn->handshake_state->started_here;
  1753. if (tor_tls_get_my_certs(server_mode, &link_cert, &id_cert) < 0)
  1754. return -1;
  1755. tor_cert_get_der(link_cert, &link_encoded, &link_len);
  1756. tor_cert_get_der(id_cert, &id_encoded, &id_len);
  1757. cell_len = 1 /* 1 octet: num certs in cell */ +
  1758. 2 * ( 1 + 2 ) /* For each cert: 1 octet for type, 2 for length */ +
  1759. link_len + id_len;
  1760. cell = var_cell_new(cell_len);
  1761. cell->command = CELL_CERT;
  1762. cell->payload[0] = 2;
  1763. pos = 1;
  1764. if (server_mode)
  1765. cell->payload[pos] = OR_CERT_TYPE_TLS_LINK; /* Link cert */
  1766. else
  1767. cell->payload[pos] = OR_CERT_TYPE_AUTH_1024; /* client authentication */
  1768. set_uint16(&cell->payload[pos+1], htons(link_len));
  1769. memcpy(&cell->payload[pos+3], link_encoded, link_len);
  1770. pos += 3 + link_len;
  1771. cell->payload[pos] = OR_CERT_TYPE_ID_1024; /* ID cert */
  1772. set_uint16(&cell->payload[pos+1], htons(id_len));
  1773. memcpy(&cell->payload[pos+3], id_encoded, id_len);
  1774. pos += 3 + id_len;
  1775. tor_assert(pos == (int)cell_len); /* Otherwise we just smashed the heap */
  1776. connection_or_write_var_cell_to_buf(cell, conn);
  1777. var_cell_free(cell);
  1778. return 0;
  1779. }
  1780. /** Send an AUTH_CHALLENGE cell on the connection <b>conn</b>. Return 0
  1781. * on success, -1 on failure. */
  1782. int
  1783. connection_or_send_auth_challenge_cell(or_connection_t *conn)
  1784. {
  1785. var_cell_t *cell;
  1786. uint8_t *cp;
  1787. uint8_t challenge[OR_AUTH_CHALLENGE_LEN];
  1788. tor_assert(conn->_base.state == OR_CONN_STATE_OR_HANDSHAKING_V3);
  1789. if (! conn->handshake_state)
  1790. return -1;
  1791. if (crypto_rand((char*)challenge, OR_AUTH_CHALLENGE_LEN) < 0)
  1792. return -1;
  1793. cell = var_cell_new(OR_AUTH_CHALLENGE_LEN + 4);
  1794. cell->command = CELL_AUTH_CHALLENGE;
  1795. memcpy(cell->payload, challenge, OR_AUTH_CHALLENGE_LEN);
  1796. cp = cell->payload + OR_AUTH_CHALLENGE_LEN;
  1797. set_uint16(cp, htons(1)); /* We recognize one authentication type. */
  1798. set_uint16(cp+2, htons(AUTHTYPE_RSA_SHA256_TLSSECRET));
  1799. connection_or_write_var_cell_to_buf(cell, conn);
  1800. var_cell_free(cell);
  1801. memset(challenge, 0, sizeof(challenge));
  1802. return 0;
  1803. }
  1804. /** Compute the main body of an AUTHENTICATE cell that a client can use
  1805. * to authenticate itself on a v3 handshake for <b>conn</b>. Write it to the
  1806. * <b>outlen</b>-byte buffer at <b>out</b>.
  1807. *
  1808. * If <b>server</b> is true, only calculate the first
  1809. * V3_AUTH_FIXED_PART_LEN bytes -- the part of the authenticator that's
  1810. * determined by the rest of the handshake, and which match the provided value
  1811. * exactly.
  1812. *
  1813. * If <b>server</b> is false and <b>signing_key</b> is NULL, calculate the
  1814. * first V3_AUTH_BODY_LEN bytes of the authenticator (that is, everything
  1815. * that should be signed), but don't actually sign it.
  1816. *
  1817. * If <b>server</b> is false and <b>signing_key</b> is provided, calculate the
  1818. * entire authenticator, signed with <b>signing_key</b>.
  1819. */
  1820. int
  1821. connection_or_compute_authenticate_cell_body(or_connection_t *conn,
  1822. uint8_t *out, size_t outlen,
  1823. crypto_pk_env_t *signing_key,
  1824. int server)
  1825. {
  1826. uint8_t *ptr;
  1827. /* assert state is reasonable XXXX */
  1828. if (outlen < V3_AUTH_FIXED_PART_LEN ||
  1829. (!server && outlen < V3_AUTH_BODY_LEN))
  1830. return -1;
  1831. ptr = out;
  1832. /* Type: 8 bytes. */
  1833. memcpy(ptr, "AUTH0001", 8);
  1834. ptr += 8;
  1835. {
  1836. const tor_cert_t *id_cert=NULL, *link_cert=NULL;
  1837. const uint8_t *my_id, *their_id, *client_id, *server_id;
  1838. if (tor_tls_get_my_certs(0, &link_cert, &id_cert))
  1839. return -1;
  1840. my_id = (uint8_t*)tor_cert_get_id_digests(id_cert)->d[DIGEST_SHA256];
  1841. their_id = (uint8_t*)
  1842. tor_cert_get_id_digests(conn->handshake_state->id_cert)->d[DIGEST_SHA256];
  1843. client_id = server ? their_id : my_id;
  1844. server_id = server ? my_id : their_id;
  1845. /* Client ID digest: 32 octets. */
  1846. memcpy(ptr, client_id, 32);
  1847. ptr += 32;
  1848. /* Server ID digest: 32 octets. */
  1849. memcpy(ptr, server_id, 32);
  1850. ptr += 32;
  1851. }
  1852. {
  1853. crypto_digest_env_t *server_d, *client_d;
  1854. if (server) {
  1855. server_d = conn->handshake_state->digest_sent;
  1856. client_d = conn->handshake_state->digest_received;
  1857. } else {
  1858. client_d = conn->handshake_state->digest_sent;
  1859. server_d = conn->handshake_state->digest_received;
  1860. }
  1861. /* Server log digest : 32 octets */
  1862. crypto_digest_get_digest(server_d, (char*)ptr, 32);
  1863. ptr += 32;
  1864. /* Client log digest : 32 octets */
  1865. crypto_digest_get_digest(client_d, (char*)ptr, 32);
  1866. ptr += 32;
  1867. }
  1868. {
  1869. /* Digest of cert used on TLS link : 32 octets. */
  1870. const tor_cert_t *cert = NULL;
  1871. tor_cert_t *freecert = NULL;
  1872. if (server) {
  1873. tor_tls_get_my_certs(1, &cert, NULL);
  1874. } else {
  1875. freecert = tor_tls_get_peer_cert(conn->tls);
  1876. cert = freecert;
  1877. }
  1878. if (!cert)
  1879. return -1;
  1880. memcpy(ptr, tor_cert_get_cert_digests(cert)->d[DIGEST_SHA256], 32);
  1881. if (freecert)
  1882. tor_cert_free(freecert);
  1883. ptr += 32;
  1884. }
  1885. /* HMAC of clientrandom and serverrandom using master key : 32 octets */
  1886. tor_tls_get_tlssecrets(conn->tls, ptr);
  1887. ptr += 32;
  1888. tor_assert(ptr - out == V3_AUTH_FIXED_PART_LEN);
  1889. if (server)
  1890. return ptr-out;
  1891. /* Time: 8 octets. */
  1892. {
  1893. uint64_t now = time(NULL);
  1894. if ((time_t)now < 0)
  1895. return -1;
  1896. set_uint32(ptr, htonl((uint32_t)(now>>32)));
  1897. set_uint32(ptr+4, htonl((uint32_t)now));
  1898. ptr += 8;
  1899. }
  1900. /* Nonce: 16 octets. */
  1901. crypto_rand((char*)ptr, 16);
  1902. ptr += 16;
  1903. tor_assert(ptr - out == V3_AUTH_BODY_LEN);
  1904. if (!signing_key)
  1905. return ptr - out;
  1906. {
  1907. int siglen;
  1908. char d[32];
  1909. crypto_digest256(d, (char*)out, ptr-out, DIGEST_SHA256);
  1910. siglen = crypto_pk_private_sign(signing_key,
  1911. (char*)ptr, outlen - (ptr-out),
  1912. d, 32);
  1913. if (siglen < 0)
  1914. return -1;
  1915. ptr += siglen;
  1916. tor_assert(ptr <= out+outlen);
  1917. return ptr - out;
  1918. }
  1919. }
  1920. /** Send an AUTHENTICATE cell on the connection <b>conn</b>. Return 0 on
  1921. * success, -1 on failure */
  1922. int
  1923. connection_or_send_authenticate_cell(or_connection_t *conn, int authtype)
  1924. {
  1925. var_cell_t *cell;
  1926. crypto_pk_env_t *pk = tor_tls_get_my_client_auth_key();
  1927. int authlen;
  1928. int cell_maxlen;
  1929. /* XXXX make sure we're actually supposed to send this! */
  1930. if (!pk)
  1931. return -1;/*XXXX log*/
  1932. if (authtype != AUTHTYPE_RSA_SHA256_TLSSECRET)
  1933. return -1;/*XXXX log*/
  1934. cell_maxlen = 4 + /* overhead */
  1935. V3_AUTH_BODY_LEN + /* Authentication body */
  1936. crypto_pk_keysize(pk) + /* Max signature length */
  1937. 16 /* just in case XXXX */ ;
  1938. cell = var_cell_new(cell_maxlen);
  1939. set_uint16(cell->payload, htons(AUTHTYPE_RSA_SHA256_TLSSECRET));
  1940. /* skip over length ; we don't know that yet. */
  1941. authlen = connection_or_compute_authenticate_cell_body(conn,
  1942. cell->payload+4,
  1943. cell_maxlen-4,
  1944. pk,
  1945. 0 /* not server */);
  1946. if (authlen < 0) {
  1947. /* XXXX log */
  1948. var_cell_free(cell);
  1949. return -1;
  1950. }
  1951. tor_assert(authlen + 4 <= cell->payload_len);
  1952. set_uint16(cell->payload+2, htons(authlen));
  1953. cell->payload_len = authlen + 4;
  1954. connection_or_write_var_cell_to_buf(cell, conn);
  1955. var_cell_free(cell);
  1956. return 0;
  1957. }