rendclient.c 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2016, The Tor Project, Inc. */
  3. /* See LICENSE for licensing information */
  4. /**
  5. * \file rendclient.c
  6. * \brief Client code to access location-hidden services.
  7. **/
  8. #include "or.h"
  9. #include "circpathbias.h"
  10. #include "circuitbuild.h"
  11. #include "circuitlist.h"
  12. #include "circuituse.h"
  13. #include "config.h"
  14. #include "connection.h"
  15. #include "connection_edge.h"
  16. #include "directory.h"
  17. #include "main.h"
  18. #include "networkstatus.h"
  19. #include "nodelist.h"
  20. #include "relay.h"
  21. #include "rendclient.h"
  22. #include "rendcommon.h"
  23. #include "rephist.h"
  24. #include "router.h"
  25. #include "routerlist.h"
  26. #include "routerset.h"
  27. #include "control.h"
  28. static extend_info_t *rend_client_get_random_intro_impl(
  29. const rend_cache_entry_t *rend_query,
  30. const int strict, const int warnings);
  31. /** Purge all potentially remotely-detectable state held in the hidden
  32. * service client code. Called on SIGNAL NEWNYM. */
  33. void
  34. rend_client_purge_state(void)
  35. {
  36. rend_cache_purge();
  37. rend_cache_failure_purge();
  38. rend_client_cancel_descriptor_fetches();
  39. rend_client_purge_last_hid_serv_requests();
  40. }
  41. /** Called when we've established a circuit to an introduction point:
  42. * send the introduction request. */
  43. void
  44. rend_client_introcirc_has_opened(origin_circuit_t *circ)
  45. {
  46. tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  47. tor_assert(circ->cpath);
  48. log_info(LD_REND,"introcirc is open");
  49. connection_ap_attach_pending(1);
  50. }
  51. /** Send the establish-rendezvous cell along a rendezvous circuit. if
  52. * it fails, mark the circ for close and return -1. else return 0.
  53. */
  54. static int
  55. rend_client_send_establish_rendezvous(origin_circuit_t *circ)
  56. {
  57. tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
  58. tor_assert(circ->rend_data);
  59. log_info(LD_REND, "Sending an ESTABLISH_RENDEZVOUS cell");
  60. crypto_rand(circ->rend_data->rend_cookie, REND_COOKIE_LEN);
  61. /* Set timestamp_dirty, because circuit_expire_building expects it,
  62. * and the rend cookie also means we've used the circ. */
  63. circ->base_.timestamp_dirty = time(NULL);
  64. /* We've attempted to use this circuit. Probe it if we fail */
  65. pathbias_count_use_attempt(circ);
  66. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  67. RELAY_COMMAND_ESTABLISH_RENDEZVOUS,
  68. circ->rend_data->rend_cookie,
  69. REND_COOKIE_LEN,
  70. circ->cpath->prev)<0) {
  71. /* circ is already marked for close */
  72. log_warn(LD_GENERAL, "Couldn't send ESTABLISH_RENDEZVOUS cell");
  73. return -1;
  74. }
  75. return 0;
  76. }
  77. /** Extend the introduction circuit <b>circ</b> to another valid
  78. * introduction point for the hidden service it is trying to connect
  79. * to, or mark it and launch a new circuit if we can't extend it.
  80. * Return 0 on success or possible success. Return -1 and mark the
  81. * introduction circuit for close on permanent failure.
  82. *
  83. * On failure, the caller is responsible for marking the associated
  84. * rendezvous circuit for close. */
  85. static int
  86. rend_client_reextend_intro_circuit(origin_circuit_t *circ)
  87. {
  88. extend_info_t *extend_info;
  89. int result;
  90. extend_info = rend_client_get_random_intro(circ->rend_data);
  91. if (!extend_info) {
  92. log_warn(LD_REND,
  93. "No usable introduction points left for %s. Closing.",
  94. safe_str_client(circ->rend_data->onion_address));
  95. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
  96. return -1;
  97. }
  98. // XXX: should we not re-extend if hs_circ_has_timed_out?
  99. if (circ->remaining_relay_early_cells) {
  100. log_info(LD_REND,
  101. "Re-extending circ %u, this time to %s.",
  102. (unsigned)circ->base_.n_circ_id,
  103. safe_str_client(extend_info_describe(extend_info)));
  104. result = circuit_extend_to_new_exit(circ, extend_info);
  105. } else {
  106. log_info(LD_REND,
  107. "Closing intro circ %u (out of RELAY_EARLY cells).",
  108. (unsigned)circ->base_.n_circ_id);
  109. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  110. /* connection_ap_handshake_attach_circuit will launch a new intro circ. */
  111. result = 0;
  112. }
  113. extend_info_free(extend_info);
  114. return result;
  115. }
  116. /** Called when we're trying to connect an ap conn; sends an INTRODUCE1 cell
  117. * down introcirc if possible.
  118. */
  119. int
  120. rend_client_send_introduction(origin_circuit_t *introcirc,
  121. origin_circuit_t *rendcirc)
  122. {
  123. const or_options_t *options = get_options();
  124. size_t payload_len;
  125. int r, v3_shift = 0;
  126. char payload[RELAY_PAYLOAD_SIZE];
  127. char tmp[RELAY_PAYLOAD_SIZE];
  128. rend_cache_entry_t *entry = NULL;
  129. crypt_path_t *cpath;
  130. off_t dh_offset;
  131. crypto_pk_t *intro_key = NULL;
  132. int status = 0;
  133. tor_assert(introcirc->base_.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  134. tor_assert(rendcirc->base_.purpose == CIRCUIT_PURPOSE_C_REND_READY);
  135. tor_assert(introcirc->rend_data);
  136. tor_assert(rendcirc->rend_data);
  137. tor_assert(!rend_cmp_service_ids(introcirc->rend_data->onion_address,
  138. rendcirc->rend_data->onion_address));
  139. assert_circ_anonymity_ok(introcirc, options);
  140. assert_circ_anonymity_ok(rendcirc, options);
  141. r = rend_cache_lookup_entry(introcirc->rend_data->onion_address, -1,
  142. &entry);
  143. /* An invalid onion address is not possible else we have a big issue. */
  144. tor_assert(r != -EINVAL);
  145. if (r < 0 || !rend_client_any_intro_points_usable(entry)) {
  146. /* If the descriptor is not found or the intro points are not usable
  147. * anymore, trigger a fetch. */
  148. log_info(LD_REND,
  149. "query %s didn't have valid rend desc in cache. "
  150. "Refetching descriptor.",
  151. safe_str_client(introcirc->rend_data->onion_address));
  152. rend_client_refetch_v2_renddesc(introcirc->rend_data);
  153. {
  154. connection_t *conn;
  155. while ((conn = connection_get_by_type_state_rendquery(CONN_TYPE_AP,
  156. AP_CONN_STATE_CIRCUIT_WAIT,
  157. introcirc->rend_data->onion_address))) {
  158. connection_ap_mark_as_non_pending_circuit(TO_ENTRY_CONN(conn));
  159. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  160. }
  161. }
  162. status = -1;
  163. goto cleanup;
  164. }
  165. /* first 20 bytes of payload are the hash of the service's pk */
  166. intro_key = NULL;
  167. SMARTLIST_FOREACH(entry->parsed->intro_nodes, rend_intro_point_t *,
  168. intro, {
  169. if (tor_memeq(introcirc->build_state->chosen_exit->identity_digest,
  170. intro->extend_info->identity_digest, DIGEST_LEN)) {
  171. intro_key = intro->intro_key;
  172. break;
  173. }
  174. });
  175. if (!intro_key) {
  176. log_info(LD_REND, "Could not find intro key for %s at %s; we "
  177. "have a v2 rend desc with %d intro points. "
  178. "Trying a different intro point...",
  179. safe_str_client(introcirc->rend_data->onion_address),
  180. safe_str_client(extend_info_describe(
  181. introcirc->build_state->chosen_exit)),
  182. smartlist_len(entry->parsed->intro_nodes));
  183. if (rend_client_reextend_intro_circuit(introcirc)) {
  184. status = -2;
  185. goto perm_err;
  186. } else {
  187. status = -1;
  188. goto cleanup;
  189. }
  190. }
  191. if (crypto_pk_get_digest(intro_key, payload)<0) {
  192. log_warn(LD_BUG, "Internal error: couldn't hash public key.");
  193. status = -2;
  194. goto perm_err;
  195. }
  196. /* Initialize the pending_final_cpath and start the DH handshake. */
  197. cpath = rendcirc->build_state->pending_final_cpath;
  198. if (!cpath) {
  199. cpath = rendcirc->build_state->pending_final_cpath =
  200. tor_malloc_zero(sizeof(crypt_path_t));
  201. cpath->magic = CRYPT_PATH_MAGIC;
  202. if (!(cpath->rend_dh_handshake_state = crypto_dh_new(DH_TYPE_REND))) {
  203. log_warn(LD_BUG, "Internal error: couldn't allocate DH.");
  204. status = -2;
  205. goto perm_err;
  206. }
  207. if (crypto_dh_generate_public(cpath->rend_dh_handshake_state)<0) {
  208. log_warn(LD_BUG, "Internal error: couldn't generate g^x.");
  209. status = -2;
  210. goto perm_err;
  211. }
  212. }
  213. /* If version is 3, write (optional) auth data and timestamp. */
  214. if (entry->parsed->protocols & (1<<3)) {
  215. tmp[0] = 3; /* version 3 of the cell format */
  216. tmp[1] = (uint8_t)introcirc->rend_data->auth_type; /* auth type, if any */
  217. v3_shift = 1;
  218. if (introcirc->rend_data->auth_type != REND_NO_AUTH) {
  219. set_uint16(tmp+2, htons(REND_DESC_COOKIE_LEN));
  220. memcpy(tmp+4, introcirc->rend_data->descriptor_cookie,
  221. REND_DESC_COOKIE_LEN);
  222. v3_shift += 2+REND_DESC_COOKIE_LEN;
  223. }
  224. /* Once this held a timestamp. */
  225. set_uint32(tmp+v3_shift+1, 0);
  226. v3_shift += 4;
  227. } /* if version 2 only write version number */
  228. else if (entry->parsed->protocols & (1<<2)) {
  229. tmp[0] = 2; /* version 2 of the cell format */
  230. }
  231. /* write the remaining items into tmp */
  232. if (entry->parsed->protocols & (1<<3) || entry->parsed->protocols & (1<<2)) {
  233. /* version 2 format */
  234. extend_info_t *extend_info = rendcirc->build_state->chosen_exit;
  235. int klen;
  236. /* nul pads */
  237. set_uint32(tmp+v3_shift+1, tor_addr_to_ipv4n(&extend_info->addr));
  238. set_uint16(tmp+v3_shift+5, htons(extend_info->port));
  239. memcpy(tmp+v3_shift+7, extend_info->identity_digest, DIGEST_LEN);
  240. klen = crypto_pk_asn1_encode(extend_info->onion_key,
  241. tmp+v3_shift+7+DIGEST_LEN+2,
  242. sizeof(tmp)-(v3_shift+7+DIGEST_LEN+2));
  243. if (klen < 0) {
  244. log_warn(LD_BUG,"Internal error: can't encode public key.");
  245. status = -2;
  246. goto perm_err;
  247. }
  248. set_uint16(tmp+v3_shift+7+DIGEST_LEN, htons(klen));
  249. memcpy(tmp+v3_shift+7+DIGEST_LEN+2+klen, rendcirc->rend_data->rend_cookie,
  250. REND_COOKIE_LEN);
  251. dh_offset = v3_shift+7+DIGEST_LEN+2+klen+REND_COOKIE_LEN;
  252. } else {
  253. /* Version 0. */
  254. strncpy(tmp, rendcirc->build_state->chosen_exit->nickname,
  255. (MAX_NICKNAME_LEN+1)); /* nul pads */
  256. memcpy(tmp+MAX_NICKNAME_LEN+1, rendcirc->rend_data->rend_cookie,
  257. REND_COOKIE_LEN);
  258. dh_offset = MAX_NICKNAME_LEN+1+REND_COOKIE_LEN;
  259. }
  260. if (crypto_dh_get_public(cpath->rend_dh_handshake_state, tmp+dh_offset,
  261. DH_KEY_LEN)<0) {
  262. log_warn(LD_BUG, "Internal error: couldn't extract g^x.");
  263. status = -2;
  264. goto perm_err;
  265. }
  266. note_crypto_pk_op(REND_CLIENT);
  267. /*XXX maybe give crypto_pk_public_hybrid_encrypt a max_len arg,
  268. * to avoid buffer overflows? */
  269. r = crypto_pk_public_hybrid_encrypt(intro_key, payload+DIGEST_LEN,
  270. sizeof(payload)-DIGEST_LEN,
  271. tmp,
  272. (int)(dh_offset+DH_KEY_LEN),
  273. PK_PKCS1_OAEP_PADDING, 0);
  274. if (r<0) {
  275. log_warn(LD_BUG,"Internal error: hybrid pk encrypt failed.");
  276. status = -2;
  277. goto perm_err;
  278. }
  279. payload_len = DIGEST_LEN + r;
  280. tor_assert(payload_len <= RELAY_PAYLOAD_SIZE); /* we overran something */
  281. /* Copy the rendezvous cookie from rendcirc to introcirc, so that
  282. * when introcirc gets an ack, we can change the state of the right
  283. * rendezvous circuit. */
  284. memcpy(introcirc->rend_data->rend_cookie, rendcirc->rend_data->rend_cookie,
  285. REND_COOKIE_LEN);
  286. log_info(LD_REND, "Sending an INTRODUCE1 cell");
  287. if (relay_send_command_from_edge(0, TO_CIRCUIT(introcirc),
  288. RELAY_COMMAND_INTRODUCE1,
  289. payload, payload_len,
  290. introcirc->cpath->prev)<0) {
  291. /* introcirc is already marked for close. leave rendcirc alone. */
  292. log_warn(LD_BUG, "Couldn't send INTRODUCE1 cell");
  293. status = -2;
  294. goto cleanup;
  295. }
  296. /* Now, we wait for an ACK or NAK on this circuit. */
  297. circuit_change_purpose(TO_CIRCUIT(introcirc),
  298. CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT);
  299. /* Set timestamp_dirty, because circuit_expire_building expects it
  300. * to specify when a circuit entered the _C_INTRODUCE_ACK_WAIT
  301. * state. */
  302. introcirc->base_.timestamp_dirty = time(NULL);
  303. pathbias_count_use_attempt(introcirc);
  304. goto cleanup;
  305. perm_err:
  306. if (!introcirc->base_.marked_for_close)
  307. circuit_mark_for_close(TO_CIRCUIT(introcirc), END_CIRC_REASON_INTERNAL);
  308. circuit_mark_for_close(TO_CIRCUIT(rendcirc), END_CIRC_REASON_INTERNAL);
  309. cleanup:
  310. memwipe(payload, 0, sizeof(payload));
  311. memwipe(tmp, 0, sizeof(tmp));
  312. return status;
  313. }
  314. /** Called when a rendezvous circuit is open; sends a establish
  315. * rendezvous circuit as appropriate. */
  316. void
  317. rend_client_rendcirc_has_opened(origin_circuit_t *circ)
  318. {
  319. tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
  320. log_info(LD_REND,"rendcirc is open");
  321. /* generate a rendezvous cookie, store it in circ */
  322. if (rend_client_send_establish_rendezvous(circ) < 0) {
  323. return;
  324. }
  325. }
  326. /**
  327. * Called to close other intro circuits we launched in parallel.
  328. */
  329. static void
  330. rend_client_close_other_intros(const char *onion_address)
  331. {
  332. /* abort parallel intro circs, if any */
  333. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, c) {
  334. if ((c->purpose == CIRCUIT_PURPOSE_C_INTRODUCING ||
  335. c->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) &&
  336. !c->marked_for_close && CIRCUIT_IS_ORIGIN(c)) {
  337. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(c);
  338. if (oc->rend_data &&
  339. !rend_cmp_service_ids(onion_address,
  340. oc->rend_data->onion_address)) {
  341. log_info(LD_REND|LD_CIRC, "Closing introduction circuit %d that we "
  342. "built in parallel (Purpose %d).", oc->global_identifier,
  343. c->purpose);
  344. circuit_mark_for_close(c, END_CIRC_REASON_IP_NOW_REDUNDANT);
  345. }
  346. }
  347. }
  348. SMARTLIST_FOREACH_END(c);
  349. }
  350. /** Called when get an ACK or a NAK for a REND_INTRODUCE1 cell.
  351. */
  352. int
  353. rend_client_introduction_acked(origin_circuit_t *circ,
  354. const uint8_t *request, size_t request_len)
  355. {
  356. const or_options_t *options = get_options();
  357. origin_circuit_t *rendcirc;
  358. (void) request; // XXXX Use this.
  359. if (circ->base_.purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
  360. log_warn(LD_PROTOCOL,
  361. "Received REND_INTRODUCE_ACK on unexpected circuit %u.",
  362. (unsigned)circ->base_.n_circ_id);
  363. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  364. return -1;
  365. }
  366. tor_assert(circ->build_state);
  367. tor_assert(circ->build_state->chosen_exit);
  368. assert_circ_anonymity_ok(circ, options);
  369. tor_assert(circ->rend_data);
  370. /* For path bias: This circuit was used successfully. Valid
  371. * nacks and acks count. */
  372. pathbias_mark_use_success(circ);
  373. if (request_len == 0) {
  374. /* It's an ACK; the introduction point relayed our introduction request. */
  375. /* Locate the rend circ which is waiting to hear about this ack,
  376. * and tell it.
  377. */
  378. log_info(LD_REND,"Received ack. Telling rend circ...");
  379. rendcirc = circuit_get_ready_rend_circ_by_rend_data(circ->rend_data);
  380. if (rendcirc) { /* remember the ack */
  381. assert_circ_anonymity_ok(rendcirc, options);
  382. circuit_change_purpose(TO_CIRCUIT(rendcirc),
  383. CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED);
  384. /* Set timestamp_dirty, because circuit_expire_building expects
  385. * it to specify when a circuit entered the
  386. * _C_REND_READY_INTRO_ACKED state. */
  387. rendcirc->base_.timestamp_dirty = time(NULL);
  388. } else {
  389. log_info(LD_REND,"...Found no rend circ. Dropping on the floor.");
  390. }
  391. /* close the circuit: we won't need it anymore. */
  392. circuit_change_purpose(TO_CIRCUIT(circ),
  393. CIRCUIT_PURPOSE_C_INTRODUCE_ACKED);
  394. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  395. /* close any other intros launched in parallel */
  396. rend_client_close_other_intros(circ->rend_data->onion_address);
  397. } else {
  398. /* It's a NAK; the introduction point didn't relay our request. */
  399. circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_C_INTRODUCING);
  400. /* Remove this intro point from the set of viable introduction
  401. * points. If any remain, extend to a new one and try again.
  402. * If none remain, refetch the service descriptor.
  403. */
  404. log_info(LD_REND, "Got nack for %s from %s...",
  405. safe_str_client(circ->rend_data->onion_address),
  406. safe_str_client(extend_info_describe(circ->build_state->chosen_exit)));
  407. if (rend_client_report_intro_point_failure(circ->build_state->chosen_exit,
  408. circ->rend_data,
  409. INTRO_POINT_FAILURE_GENERIC)>0) {
  410. /* There are introduction points left. Re-extend the circuit to
  411. * another intro point and try again. */
  412. int result = rend_client_reextend_intro_circuit(circ);
  413. /* XXXX If that call failed, should we close the rend circuit,
  414. * too? */
  415. return result;
  416. } else {
  417. /* Close circuit because no more intro points are usable thus not
  418. * useful anymore. Change it's purpose before so we don't report an
  419. * intro point failure again triggering an extra descriptor fetch. */
  420. circuit_change_purpose(TO_CIRCUIT(circ),
  421. CIRCUIT_PURPOSE_C_INTRODUCE_ACKED);
  422. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  423. }
  424. }
  425. return 0;
  426. }
  427. /** The period for which a hidden service directory cannot be queried for
  428. * the same descriptor ID again. */
  429. #define REND_HID_SERV_DIR_REQUERY_PERIOD (15 * 60)
  430. /** Test networks generate a new consensus every 5 or 10 seconds.
  431. * So allow them to requery HSDirs much faster. */
  432. #define REND_HID_SERV_DIR_REQUERY_PERIOD_TESTING (5)
  433. /** Return the period for which a hidden service directory cannot be queried
  434. * for the same descriptor ID again, taking TestingTorNetwork into account. */
  435. static time_t
  436. hsdir_requery_period(const or_options_t *options)
  437. {
  438. tor_assert(options);
  439. if (options->TestingTorNetwork) {
  440. return REND_HID_SERV_DIR_REQUERY_PERIOD_TESTING;
  441. } else {
  442. return REND_HID_SERV_DIR_REQUERY_PERIOD;
  443. }
  444. }
  445. /** Contains the last request times to hidden service directories for
  446. * certain queries; each key is a string consisting of the
  447. * concatenation of a base32-encoded HS directory identity digest and
  448. * base32-encoded HS descriptor ID; each value is a pointer to a time_t
  449. * holding the time of the last request for that descriptor ID to that
  450. * HS directory. */
  451. static strmap_t *last_hid_serv_requests_ = NULL;
  452. /** Returns last_hid_serv_requests_, initializing it to a new strmap if
  453. * necessary. */
  454. static strmap_t *
  455. get_last_hid_serv_requests(void)
  456. {
  457. if (!last_hid_serv_requests_)
  458. last_hid_serv_requests_ = strmap_new();
  459. return last_hid_serv_requests_;
  460. }
  461. #define LAST_HID_SERV_REQUEST_KEY_LEN (REND_DESC_ID_V2_LEN_BASE32 + \
  462. REND_DESC_ID_V2_LEN_BASE32)
  463. /** Look up the last request time to hidden service directory <b>hs_dir</b>
  464. * for descriptor ID <b>desc_id_base32</b>. If <b>set</b> is non-zero,
  465. * assign the current time <b>now</b> and return that. Otherwise, return the
  466. * most recent request time, or 0 if no such request has been sent before.
  467. */
  468. static time_t
  469. lookup_last_hid_serv_request(routerstatus_t *hs_dir,
  470. const char *desc_id_base32,
  471. time_t now, int set)
  472. {
  473. char hsdir_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  474. char hsdir_desc_comb_id[LAST_HID_SERV_REQUEST_KEY_LEN + 1];
  475. time_t *last_request_ptr;
  476. strmap_t *last_hid_serv_requests = get_last_hid_serv_requests();
  477. base32_encode(hsdir_id_base32, sizeof(hsdir_id_base32),
  478. hs_dir->identity_digest, DIGEST_LEN);
  479. tor_snprintf(hsdir_desc_comb_id, sizeof(hsdir_desc_comb_id), "%s%s",
  480. hsdir_id_base32,
  481. desc_id_base32);
  482. /* XXX++?? tor_assert(strlen(hsdir_desc_comb_id) ==
  483. LAST_HID_SERV_REQUEST_KEY_LEN); */
  484. if (set) {
  485. time_t *oldptr;
  486. last_request_ptr = tor_malloc_zero(sizeof(time_t));
  487. *last_request_ptr = now;
  488. oldptr = strmap_set(last_hid_serv_requests, hsdir_desc_comb_id,
  489. last_request_ptr);
  490. tor_free(oldptr);
  491. } else
  492. last_request_ptr = strmap_get_lc(last_hid_serv_requests,
  493. hsdir_desc_comb_id);
  494. return (last_request_ptr) ? *last_request_ptr : 0;
  495. }
  496. /** Clean the history of request times to hidden service directories, so that
  497. * it does not contain requests older than REND_HID_SERV_DIR_REQUERY_PERIOD
  498. * seconds any more. */
  499. static void
  500. directory_clean_last_hid_serv_requests(time_t now)
  501. {
  502. strmap_iter_t *iter;
  503. time_t cutoff = now - hsdir_requery_period(get_options());
  504. strmap_t *last_hid_serv_requests = get_last_hid_serv_requests();
  505. for (iter = strmap_iter_init(last_hid_serv_requests);
  506. !strmap_iter_done(iter); ) {
  507. const char *key;
  508. void *val;
  509. time_t *ent;
  510. strmap_iter_get(iter, &key, &val);
  511. ent = (time_t *) val;
  512. if (*ent < cutoff) {
  513. iter = strmap_iter_next_rmv(last_hid_serv_requests, iter);
  514. tor_free(ent);
  515. } else {
  516. iter = strmap_iter_next(last_hid_serv_requests, iter);
  517. }
  518. }
  519. }
  520. /** Remove all requests related to the descriptor ID <b>desc_id</b> from the
  521. * history of times of requests to hidden service directories.
  522. * <b>desc_id</b> is an unencoded descriptor ID of size DIGEST_LEN.
  523. *
  524. * This is called from rend_client_note_connection_attempt_ended(), which
  525. * must be idempotent, so any future changes to this function must leave it
  526. * idempotent too. */
  527. static void
  528. purge_hid_serv_from_last_hid_serv_requests(const char *desc_id)
  529. {
  530. strmap_iter_t *iter;
  531. strmap_t *last_hid_serv_requests = get_last_hid_serv_requests();
  532. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  533. /* Key is stored with the base32 encoded desc_id. */
  534. base32_encode(desc_id_base32, sizeof(desc_id_base32), desc_id,
  535. DIGEST_LEN);
  536. for (iter = strmap_iter_init(last_hid_serv_requests);
  537. !strmap_iter_done(iter); ) {
  538. const char *key;
  539. void *val;
  540. strmap_iter_get(iter, &key, &val);
  541. /* XXX++?? tor_assert(strlen(key) == LAST_HID_SERV_REQUEST_KEY_LEN); */
  542. if (tor_memeq(key + LAST_HID_SERV_REQUEST_KEY_LEN -
  543. REND_DESC_ID_V2_LEN_BASE32,
  544. desc_id_base32,
  545. REND_DESC_ID_V2_LEN_BASE32)) {
  546. iter = strmap_iter_next_rmv(last_hid_serv_requests, iter);
  547. tor_free(val);
  548. } else {
  549. iter = strmap_iter_next(last_hid_serv_requests, iter);
  550. }
  551. }
  552. }
  553. /** Purge the history of request times to hidden service directories,
  554. * so that future lookups of an HS descriptor will not fail because we
  555. * accessed all of the HSDir relays responsible for the descriptor
  556. * recently. */
  557. void
  558. rend_client_purge_last_hid_serv_requests(void)
  559. {
  560. /* Don't create the table if it doesn't exist yet (and it may very
  561. * well not exist if the user hasn't accessed any HSes)... */
  562. strmap_t *old_last_hid_serv_requests = last_hid_serv_requests_;
  563. /* ... and let get_last_hid_serv_requests re-create it for us if
  564. * necessary. */
  565. last_hid_serv_requests_ = NULL;
  566. if (old_last_hid_serv_requests != NULL) {
  567. log_info(LD_REND, "Purging client last-HS-desc-request-time table");
  568. strmap_free(old_last_hid_serv_requests, tor_free_);
  569. }
  570. }
  571. /** This returns a good valid hs dir that should be used for the given
  572. * descriptor id.
  573. *
  574. * Return NULL on error else the hsdir node pointer. */
  575. static routerstatus_t *
  576. pick_hsdir(const char *desc_id, const char *desc_id_base32)
  577. {
  578. smartlist_t *responsible_dirs = smartlist_new();
  579. smartlist_t *usable_responsible_dirs = smartlist_new();
  580. const or_options_t *options = get_options();
  581. routerstatus_t *hs_dir;
  582. time_t now = time(NULL);
  583. int excluded_some;
  584. tor_assert(desc_id);
  585. tor_assert(desc_id_base32);
  586. /* Determine responsible dirs. Even if we can't get all we want, work with
  587. * the ones we have. If it's empty, we'll notice below. */
  588. hid_serv_get_responsible_directories(responsible_dirs, desc_id);
  589. /* Clean request history first. */
  590. directory_clean_last_hid_serv_requests(now);
  591. /* Only select those hidden service directories to which we did not send a
  592. * request recently and for which we have a router descriptor here. */
  593. SMARTLIST_FOREACH_BEGIN(responsible_dirs, routerstatus_t *, dir) {
  594. time_t last = lookup_last_hid_serv_request(dir, desc_id_base32,
  595. 0, 0);
  596. const node_t *node = node_get_by_id(dir->identity_digest);
  597. if (last + hsdir_requery_period(options) >= now ||
  598. !node || !node_has_descriptor(node)) {
  599. SMARTLIST_DEL_CURRENT(responsible_dirs, dir);
  600. continue;
  601. }
  602. if (!routerset_contains_node(options->ExcludeNodes, node)) {
  603. smartlist_add(usable_responsible_dirs, dir);
  604. }
  605. } SMARTLIST_FOREACH_END(dir);
  606. excluded_some =
  607. smartlist_len(usable_responsible_dirs) < smartlist_len(responsible_dirs);
  608. hs_dir = smartlist_choose(usable_responsible_dirs);
  609. if (!hs_dir && !options->StrictNodes) {
  610. hs_dir = smartlist_choose(responsible_dirs);
  611. }
  612. smartlist_free(responsible_dirs);
  613. smartlist_free(usable_responsible_dirs);
  614. if (!hs_dir) {
  615. log_info(LD_REND, "Could not pick one of the responsible hidden "
  616. "service directories, because we requested them all "
  617. "recently without success.");
  618. if (options->StrictNodes && excluded_some) {
  619. log_warn(LD_REND, "Could not pick a hidden service directory for the "
  620. "requested hidden service: they are all either down or "
  621. "excluded, and StrictNodes is set.");
  622. }
  623. } else {
  624. /* Remember that we are requesting a descriptor from this hidden service
  625. * directory now. */
  626. lookup_last_hid_serv_request(hs_dir, desc_id_base32, now, 1);
  627. }
  628. return hs_dir;
  629. }
  630. /** Determine the responsible hidden service directories for <b>desc_id</b>
  631. * and fetch the descriptor with that ID from one of them. Only
  632. * send a request to a hidden service directory that we have not yet tried
  633. * during this attempt to connect to this hidden service; on success, return 1,
  634. * in the case that no hidden service directory is left to ask for the
  635. * descriptor, return 0, and in case of a failure -1. */
  636. static int
  637. directory_get_from_hs_dir(const char *desc_id, const rend_data_t *rend_query,
  638. routerstatus_t *rs_hsdir)
  639. {
  640. routerstatus_t *hs_dir = rs_hsdir;
  641. char *hsdir_fp;
  642. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  643. char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
  644. #ifdef ENABLE_TOR2WEB_MODE
  645. const int tor2web_mode = get_options()->Tor2webMode;
  646. const int how_to_fetch = tor2web_mode ? DIRIND_ONEHOP : DIRIND_ANONYMOUS;
  647. #else
  648. const int how_to_fetch = DIRIND_ANONYMOUS;
  649. #endif
  650. tor_assert(desc_id);
  651. base32_encode(desc_id_base32, sizeof(desc_id_base32),
  652. desc_id, DIGEST_LEN);
  653. /* Automatically pick an hs dir if none given. */
  654. if (!rs_hsdir) {
  655. hs_dir = pick_hsdir(desc_id, desc_id_base32);
  656. if (!hs_dir) {
  657. /* No suitable hs dir can be found, stop right now. */
  658. return 0;
  659. }
  660. }
  661. /* Add a copy of the HSDir identity digest to the query so we can track it
  662. * on the control port. */
  663. hsdir_fp = tor_memdup(hs_dir->identity_digest,
  664. sizeof(hs_dir->identity_digest));
  665. smartlist_add(rend_query->hsdirs_fp, hsdir_fp);
  666. /* Encode descriptor cookie for logging purposes. Also, if the cookie is
  667. * malformed, no fetch is triggered thus this needs to be done before the
  668. * fetch request. */
  669. if (rend_query->auth_type != REND_NO_AUTH) {
  670. if (base64_encode(descriptor_cookie_base64,
  671. sizeof(descriptor_cookie_base64),
  672. rend_query->descriptor_cookie, REND_DESC_COOKIE_LEN,
  673. 0)<0) {
  674. log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
  675. return 0;
  676. }
  677. /* Remove == signs. */
  678. descriptor_cookie_base64[strlen(descriptor_cookie_base64)-2] = '\0';
  679. } else {
  680. strlcpy(descriptor_cookie_base64, "(none)",
  681. sizeof(descriptor_cookie_base64));
  682. }
  683. /* Send fetch request. (Pass query and possibly descriptor cookie so that
  684. * they can be written to the directory connection and be referred to when
  685. * the response arrives. */
  686. directory_initiate_command_routerstatus_rend(hs_dir,
  687. DIR_PURPOSE_FETCH_RENDDESC_V2,
  688. ROUTER_PURPOSE_GENERAL,
  689. how_to_fetch,
  690. desc_id_base32,
  691. NULL, 0, 0,
  692. rend_query);
  693. log_info(LD_REND, "Sending fetch request for v2 descriptor for "
  694. "service '%s' with descriptor ID '%s', auth type %d, "
  695. "and descriptor cookie '%s' to hidden service "
  696. "directory %s",
  697. rend_query->onion_address, desc_id_base32,
  698. rend_query->auth_type,
  699. (rend_query->auth_type == REND_NO_AUTH ? "[none]" :
  700. escaped_safe_str_client(descriptor_cookie_base64)),
  701. routerstatus_describe(hs_dir));
  702. control_event_hs_descriptor_requested(rend_query,
  703. hs_dir->identity_digest,
  704. desc_id_base32);
  705. return 1;
  706. }
  707. /** Fetch a v2 descriptor using the given descriptor id. If any hsdir(s) are
  708. * given, they will be used instead.
  709. *
  710. * On success, 1 is returned. If no hidden service is left to ask, return 0.
  711. * On error, -1 is returned. */
  712. static int
  713. fetch_v2_desc_by_descid(const char *desc_id, const rend_data_t *rend_query,
  714. smartlist_t *hsdirs)
  715. {
  716. int ret;
  717. tor_assert(rend_query);
  718. if (!hsdirs) {
  719. ret = directory_get_from_hs_dir(desc_id, rend_query, NULL);
  720. goto end; /* either success or failure, but we're done */
  721. }
  722. /* Using the given hsdir list, trigger a fetch on each of them. */
  723. SMARTLIST_FOREACH_BEGIN(hsdirs, routerstatus_t *, hs_dir) {
  724. /* This should always be a success. */
  725. ret = directory_get_from_hs_dir(desc_id, rend_query, hs_dir);
  726. tor_assert(ret);
  727. } SMARTLIST_FOREACH_END(hs_dir);
  728. /* Everything went well. */
  729. ret = 0;
  730. end:
  731. return ret;
  732. }
  733. /** Fetch a v2 descriptor using the onion address in the given query object.
  734. * This will compute the descriptor id for each replicas and fetch it on the
  735. * given hsdir(s) if any or the responsible ones that are choosen
  736. * automatically.
  737. *
  738. * On success, 1 is returned. If no hidden service is left to ask, return 0.
  739. * On error, -1 is returned. */
  740. static int
  741. fetch_v2_desc_by_addr(rend_data_t *query, smartlist_t *hsdirs)
  742. {
  743. char descriptor_id[DIGEST_LEN];
  744. int replicas_left_to_try[REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS];
  745. int i, tries_left, ret;
  746. tor_assert(query);
  747. /* Randomly iterate over the replicas until a descriptor can be fetched
  748. * from one of the consecutive nodes, or no options are left. */
  749. for (i = 0; i < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; i++) {
  750. replicas_left_to_try[i] = i;
  751. }
  752. tries_left = REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS;
  753. while (tries_left > 0) {
  754. int rand_val = crypto_rand_int(tries_left);
  755. int chosen_replica = replicas_left_to_try[rand_val];
  756. replicas_left_to_try[rand_val] = replicas_left_to_try[--tries_left];
  757. ret = rend_compute_v2_desc_id(descriptor_id, query->onion_address,
  758. query->auth_type == REND_STEALTH_AUTH ?
  759. query->descriptor_cookie : NULL,
  760. time(NULL), chosen_replica);
  761. if (ret < 0) {
  762. /* Normally, on failure the descriptor_id is untouched but let's be
  763. * safe in general in case the function changes at some point. */
  764. goto end;
  765. }
  766. if (tor_memcmp(descriptor_id, query->descriptor_id[chosen_replica],
  767. sizeof(descriptor_id)) != 0) {
  768. /* Not equal from what we currently have so purge the last hid serv
  769. * request cache and update the descriptor ID with the new value. */
  770. purge_hid_serv_from_last_hid_serv_requests(
  771. query->descriptor_id[chosen_replica]);
  772. memcpy(query->descriptor_id[chosen_replica], descriptor_id,
  773. sizeof(query->descriptor_id[chosen_replica]));
  774. }
  775. /* Trigger the fetch with the computed descriptor ID. */
  776. ret = fetch_v2_desc_by_descid(descriptor_id, query, hsdirs);
  777. if (ret != 0) {
  778. /* Either on success or failure, as long as we tried a fetch we are
  779. * done here. */
  780. goto end;
  781. }
  782. }
  783. /* If we come here, there are no hidden service directories left. */
  784. log_info(LD_REND, "Could not pick one of the responsible hidden "
  785. "service directories to fetch descriptors, because "
  786. "we already tried them all unsuccessfully.");
  787. ret = 0;
  788. end:
  789. memwipe(descriptor_id, 0, sizeof(descriptor_id));
  790. return ret;
  791. }
  792. /** Fetch a v2 descriptor using the given query. If any hsdir are specified,
  793. * use them for the fetch.
  794. *
  795. * On success, 1 is returned. If no hidden service is left to ask, return 0.
  796. * On error, -1 is returned. */
  797. int
  798. rend_client_fetch_v2_desc(rend_data_t *query, smartlist_t *hsdirs)
  799. {
  800. int ret;
  801. tor_assert(query);
  802. /* Depending on what's available in the rend data query object, we will
  803. * trigger a fetch by HS address or using a descriptor ID. */
  804. if (query->onion_address[0] != '\0') {
  805. ret = fetch_v2_desc_by_addr(query, hsdirs);
  806. } else if (!tor_digest_is_zero(query->desc_id_fetch)) {
  807. ret = fetch_v2_desc_by_descid(query->desc_id_fetch, query, hsdirs);
  808. } else {
  809. /* Query data is invalid. */
  810. ret = -1;
  811. goto error;
  812. }
  813. error:
  814. return ret;
  815. }
  816. /** Unless we already have a descriptor for <b>rend_query</b> with at least
  817. * one (possibly) working introduction point in it, start a connection to a
  818. * hidden service directory to fetch a v2 rendezvous service descriptor. */
  819. void
  820. rend_client_refetch_v2_renddesc(rend_data_t *rend_query)
  821. {
  822. rend_cache_entry_t *e = NULL;
  823. tor_assert(rend_query);
  824. /* Before fetching, check if we already have a usable descriptor here. */
  825. if (rend_cache_lookup_entry(rend_query->onion_address, -1, &e) == 0 &&
  826. rend_client_any_intro_points_usable(e)) {
  827. log_info(LD_REND, "We would fetch a v2 rendezvous descriptor, but we "
  828. "already have a usable descriptor here. Not fetching.");
  829. return;
  830. }
  831. /* Are we configured to fetch descriptors? */
  832. if (!get_options()->FetchHidServDescriptors) {
  833. log_warn(LD_REND, "We received an onion address for a v2 rendezvous "
  834. "service descriptor, but are not fetching service descriptors.");
  835. return;
  836. }
  837. log_debug(LD_REND, "Fetching v2 rendezvous descriptor for service %s",
  838. safe_str_client(rend_query->onion_address));
  839. rend_client_fetch_v2_desc(rend_query, NULL);
  840. /* We don't need to look the error code because either on failure or
  841. * success, the necessary steps to continue the HS connection will be
  842. * triggered once the descriptor arrives or if all fetch failed. */
  843. return;
  844. }
  845. /** Cancel all rendezvous descriptor fetches currently in progress.
  846. */
  847. void
  848. rend_client_cancel_descriptor_fetches(void)
  849. {
  850. smartlist_t *connection_array = get_connection_array();
  851. SMARTLIST_FOREACH_BEGIN(connection_array, connection_t *, conn) {
  852. if (conn->type == CONN_TYPE_DIR &&
  853. conn->purpose == DIR_PURPOSE_FETCH_RENDDESC_V2) {
  854. /* It's a rendezvous descriptor fetch in progress -- cancel it
  855. * by marking the connection for close.
  856. *
  857. * Even if this connection has already reached EOF, this is
  858. * enough to make sure that if the descriptor hasn't been
  859. * processed yet, it won't be. See the end of
  860. * connection_handle_read; connection_reached_eof (indirectly)
  861. * processes whatever response the connection received. */
  862. const rend_data_t *rd = (TO_DIR_CONN(conn))->rend_data;
  863. if (!rd) {
  864. log_warn(LD_BUG | LD_REND,
  865. "Marking for close dir conn fetching rendezvous "
  866. "descriptor for unknown service!");
  867. } else {
  868. log_debug(LD_REND, "Marking for close dir conn fetching "
  869. "rendezvous descriptor for service %s",
  870. safe_str(rd->onion_address));
  871. }
  872. connection_mark_for_close(conn);
  873. }
  874. } SMARTLIST_FOREACH_END(conn);
  875. }
  876. /** Mark <b>failed_intro</b> as a failed introduction point for the
  877. * hidden service specified by <b>rend_query</b>. If the HS now has no
  878. * usable intro points, or we do not have an HS descriptor for it,
  879. * then launch a new renddesc fetch.
  880. *
  881. * If <b>failure_type</b> is INTRO_POINT_FAILURE_GENERIC, remove the
  882. * intro point from (our parsed copy of) the HS descriptor.
  883. *
  884. * If <b>failure_type</b> is INTRO_POINT_FAILURE_TIMEOUT, mark the
  885. * intro point as 'timed out'; it will not be retried until the
  886. * current hidden service connection attempt has ended or it has
  887. * appeared in a newly fetched rendezvous descriptor.
  888. *
  889. * If <b>failure_type</b> is INTRO_POINT_FAILURE_UNREACHABLE,
  890. * increment the intro point's reachability-failure count; if it has
  891. * now failed MAX_INTRO_POINT_REACHABILITY_FAILURES or more times,
  892. * remove the intro point from (our parsed copy of) the HS descriptor.
  893. *
  894. * Return -1 if error, 0 if no usable intro points remain or service
  895. * unrecognized, 1 if recognized and some intro points remain.
  896. */
  897. int
  898. rend_client_report_intro_point_failure(extend_info_t *failed_intro,
  899. rend_data_t *rend_query,
  900. unsigned int failure_type)
  901. {
  902. int i, r;
  903. rend_cache_entry_t *ent;
  904. connection_t *conn;
  905. r = rend_cache_lookup_entry(rend_query->onion_address, -1, &ent);
  906. if (r < 0) {
  907. /* Either invalid onion address or cache entry not found. */
  908. switch (-r) {
  909. case EINVAL:
  910. log_warn(LD_BUG, "Malformed service ID %s.",
  911. escaped_safe_str_client(rend_query->onion_address));
  912. return -1;
  913. case ENOENT:
  914. log_info(LD_REND, "Unknown service %s. Re-fetching descriptor.",
  915. escaped_safe_str_client(rend_query->onion_address));
  916. rend_client_refetch_v2_renddesc(rend_query);
  917. return 0;
  918. default:
  919. log_warn(LD_BUG, "Unknown cache lookup returned code: %d", r);
  920. return -1;
  921. }
  922. }
  923. /* The intro points are not checked here if they are usable or not because
  924. * this is called when an intro point circuit is closed thus there must be
  925. * at least one intro point that is usable and is about to be flagged. */
  926. for (i = 0; i < smartlist_len(ent->parsed->intro_nodes); i++) {
  927. rend_intro_point_t *intro = smartlist_get(ent->parsed->intro_nodes, i);
  928. if (tor_memeq(failed_intro->identity_digest,
  929. intro->extend_info->identity_digest, DIGEST_LEN)) {
  930. switch (failure_type) {
  931. default:
  932. log_warn(LD_BUG, "Unknown failure type %u. Removing intro point.",
  933. failure_type);
  934. tor_fragile_assert();
  935. /* fall through */
  936. case INTRO_POINT_FAILURE_GENERIC:
  937. rend_cache_intro_failure_note(failure_type,
  938. (uint8_t *)failed_intro->identity_digest,
  939. rend_query->onion_address);
  940. rend_intro_point_free(intro);
  941. smartlist_del(ent->parsed->intro_nodes, i);
  942. break;
  943. case INTRO_POINT_FAILURE_TIMEOUT:
  944. intro->timed_out = 1;
  945. break;
  946. case INTRO_POINT_FAILURE_UNREACHABLE:
  947. ++(intro->unreachable_count);
  948. {
  949. int zap_intro_point =
  950. intro->unreachable_count >= MAX_INTRO_POINT_REACHABILITY_FAILURES;
  951. log_info(LD_REND, "Failed to reach this intro point %u times.%s",
  952. intro->unreachable_count,
  953. zap_intro_point ? " Removing from descriptor.": "");
  954. if (zap_intro_point) {
  955. rend_cache_intro_failure_note(
  956. failure_type,
  957. (uint8_t *) failed_intro->identity_digest,
  958. rend_query->onion_address);
  959. rend_intro_point_free(intro);
  960. smartlist_del(ent->parsed->intro_nodes, i);
  961. }
  962. }
  963. break;
  964. }
  965. break;
  966. }
  967. }
  968. if (! rend_client_any_intro_points_usable(ent)) {
  969. log_info(LD_REND,
  970. "No more intro points remain for %s. Re-fetching descriptor.",
  971. escaped_safe_str_client(rend_query->onion_address));
  972. rend_client_refetch_v2_renddesc(rend_query);
  973. /* move all pending streams back to renddesc_wait */
  974. /* NOTE: We can now do this faster, if we use pending_entry_connections */
  975. while ((conn = connection_get_by_type_state_rendquery(CONN_TYPE_AP,
  976. AP_CONN_STATE_CIRCUIT_WAIT,
  977. rend_query->onion_address))) {
  978. connection_ap_mark_as_non_pending_circuit(TO_ENTRY_CONN(conn));
  979. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  980. }
  981. return 0;
  982. }
  983. log_info(LD_REND,"%d options left for %s.",
  984. smartlist_len(ent->parsed->intro_nodes),
  985. escaped_safe_str_client(rend_query->onion_address));
  986. return 1;
  987. }
  988. /** Called when we receive a RENDEZVOUS_ESTABLISHED cell; changes the state of
  989. * the circuit to C_REND_READY.
  990. */
  991. int
  992. rend_client_rendezvous_acked(origin_circuit_t *circ, const uint8_t *request,
  993. size_t request_len)
  994. {
  995. (void) request;
  996. (void) request_len;
  997. /* we just got an ack for our establish-rendezvous. switch purposes. */
  998. if (circ->base_.purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND) {
  999. log_warn(LD_PROTOCOL,"Got a rendezvous ack when we weren't expecting one. "
  1000. "Closing circ.");
  1001. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  1002. return -1;
  1003. }
  1004. log_info(LD_REND,"Got rendezvous ack. This circuit is now ready for "
  1005. "rendezvous.");
  1006. circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_C_REND_READY);
  1007. /* Set timestamp_dirty, because circuit_expire_building expects it
  1008. * to specify when a circuit entered the _C_REND_READY state. */
  1009. circ->base_.timestamp_dirty = time(NULL);
  1010. /* From a path bias point of view, this circuit is now successfully used.
  1011. * Waiting any longer opens us up to attacks from malicious hidden services.
  1012. * They could induce the client to attempt to connect to their hidden
  1013. * service and never reply to the client's rend requests */
  1014. pathbias_mark_use_success(circ);
  1015. /* XXXX++ This is a pretty brute-force approach. It'd be better to
  1016. * attach only the connections that are waiting on this circuit, rather
  1017. * than trying to attach them all. See comments bug 743. */
  1018. /* If we already have the introduction circuit built, make sure we send
  1019. * the INTRODUCE cell _now_ */
  1020. connection_ap_attach_pending(1);
  1021. return 0;
  1022. }
  1023. /** The service sent us a rendezvous cell; join the circuits. */
  1024. int
  1025. rend_client_receive_rendezvous(origin_circuit_t *circ, const uint8_t *request,
  1026. size_t request_len)
  1027. {
  1028. crypt_path_t *hop;
  1029. char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN];
  1030. if ((circ->base_.purpose != CIRCUIT_PURPOSE_C_REND_READY &&
  1031. circ->base_.purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)
  1032. || !circ->build_state->pending_final_cpath) {
  1033. log_warn(LD_PROTOCOL,"Got rendezvous2 cell from hidden service, but not "
  1034. "expecting it. Closing.");
  1035. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  1036. return -1;
  1037. }
  1038. if (request_len != DH_KEY_LEN+DIGEST_LEN) {
  1039. log_warn(LD_PROTOCOL,"Incorrect length (%d) on RENDEZVOUS2 cell.",
  1040. (int)request_len);
  1041. goto err;
  1042. }
  1043. log_info(LD_REND,"Got RENDEZVOUS2 cell from hidden service.");
  1044. /* first DH_KEY_LEN bytes are g^y from the service. Finish the dh
  1045. * handshake...*/
  1046. tor_assert(circ->build_state);
  1047. tor_assert(circ->build_state->pending_final_cpath);
  1048. hop = circ->build_state->pending_final_cpath;
  1049. tor_assert(hop->rend_dh_handshake_state);
  1050. if (crypto_dh_compute_secret(LOG_PROTOCOL_WARN,
  1051. hop->rend_dh_handshake_state, (char*)request,
  1052. DH_KEY_LEN,
  1053. keys, DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
  1054. log_warn(LD_GENERAL, "Couldn't complete DH handshake.");
  1055. goto err;
  1056. }
  1057. /* ... and set up cpath. */
  1058. if (circuit_init_cpath_crypto(hop, keys+DIGEST_LEN, 0)<0)
  1059. goto err;
  1060. /* Check whether the digest is right... */
  1061. if (tor_memneq(keys, request+DH_KEY_LEN, DIGEST_LEN)) {
  1062. log_warn(LD_PROTOCOL, "Incorrect digest of key material.");
  1063. goto err;
  1064. }
  1065. crypto_dh_free(hop->rend_dh_handshake_state);
  1066. hop->rend_dh_handshake_state = NULL;
  1067. /* All is well. Extend the circuit. */
  1068. circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_C_REND_JOINED);
  1069. hop->state = CPATH_STATE_OPEN;
  1070. /* set the windows to default. these are the windows
  1071. * that the client thinks the service has.
  1072. */
  1073. hop->package_window = circuit_initial_package_window();
  1074. hop->deliver_window = CIRCWINDOW_START;
  1075. /* Now that this circuit has finished connecting to its destination,
  1076. * make sure circuit_get_open_circ_or_launch is willing to return it
  1077. * so we can actually use it. */
  1078. circ->hs_circ_has_timed_out = 0;
  1079. onion_append_to_cpath(&circ->cpath, hop);
  1080. circ->build_state->pending_final_cpath = NULL; /* prevent double-free */
  1081. circuit_try_attaching_streams(circ);
  1082. memwipe(keys, 0, sizeof(keys));
  1083. return 0;
  1084. err:
  1085. memwipe(keys, 0, sizeof(keys));
  1086. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  1087. return -1;
  1088. }
  1089. /** Find all the apconns in state AP_CONN_STATE_RENDDESC_WAIT that are
  1090. * waiting on <b>query</b>. If there's a working cache entry here with at
  1091. * least one intro point, move them to the next state. */
  1092. void
  1093. rend_client_desc_trynow(const char *query)
  1094. {
  1095. entry_connection_t *conn;
  1096. rend_cache_entry_t *entry;
  1097. const rend_data_t *rend_data;
  1098. time_t now = time(NULL);
  1099. smartlist_t *conns = get_connection_array();
  1100. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  1101. if (base_conn->type != CONN_TYPE_AP ||
  1102. base_conn->state != AP_CONN_STATE_RENDDESC_WAIT ||
  1103. base_conn->marked_for_close)
  1104. continue;
  1105. conn = TO_ENTRY_CONN(base_conn);
  1106. rend_data = ENTRY_TO_EDGE_CONN(conn)->rend_data;
  1107. if (!rend_data)
  1108. continue;
  1109. if (rend_cmp_service_ids(query, rend_data->onion_address))
  1110. continue;
  1111. assert_connection_ok(base_conn, now);
  1112. if (rend_cache_lookup_entry(rend_data->onion_address, -1,
  1113. &entry) == 0 &&
  1114. rend_client_any_intro_points_usable(entry)) {
  1115. /* either this fetch worked, or it failed but there was a
  1116. * valid entry from before which we should reuse */
  1117. log_info(LD_REND,"Rend desc is usable. Launching circuits.");
  1118. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1119. /* restart their timeout values, so they get a fair shake at
  1120. * connecting to the hidden service. */
  1121. base_conn->timestamp_created = now;
  1122. base_conn->timestamp_lastread = now;
  1123. base_conn->timestamp_lastwritten = now;
  1124. connection_ap_mark_as_pending_circuit(conn);
  1125. } else { /* 404, or fetch didn't get that far */
  1126. log_notice(LD_REND,"Closing stream for '%s.onion': hidden service is "
  1127. "unavailable (try again later).",
  1128. safe_str_client(query));
  1129. connection_mark_unattached_ap(conn, END_STREAM_REASON_RESOLVEFAILED);
  1130. rend_client_note_connection_attempt_ended(rend_data);
  1131. }
  1132. } SMARTLIST_FOREACH_END(base_conn);
  1133. }
  1134. /** Clear temporary state used only during an attempt to connect to the
  1135. * hidden service with <b>rend_data</b>. Called when a connection attempt
  1136. * has ended; it is possible for this to be called multiple times while
  1137. * handling an ended connection attempt, and any future changes to this
  1138. * function must ensure it remains idempotent. */
  1139. void
  1140. rend_client_note_connection_attempt_ended(const rend_data_t *rend_data)
  1141. {
  1142. unsigned int have_onion = 0;
  1143. rend_cache_entry_t *cache_entry = NULL;
  1144. if (*rend_data->onion_address != '\0') {
  1145. /* Ignore return value; we find an entry, or we don't. */
  1146. (void) rend_cache_lookup_entry(rend_data->onion_address, -1,
  1147. &cache_entry);
  1148. have_onion = 1;
  1149. }
  1150. /* Clear the timed_out flag on all remaining intro points for this HS. */
  1151. if (cache_entry != NULL) {
  1152. SMARTLIST_FOREACH(cache_entry->parsed->intro_nodes,
  1153. rend_intro_point_t *, ip,
  1154. ip->timed_out = 0; );
  1155. }
  1156. /* Remove the HS's entries in last_hid_serv_requests. */
  1157. if (have_onion) {
  1158. unsigned int replica;
  1159. for (replica = 0; replica < ARRAY_LENGTH(rend_data->descriptor_id);
  1160. replica++) {
  1161. const char *desc_id = rend_data->descriptor_id[replica];
  1162. purge_hid_serv_from_last_hid_serv_requests(desc_id);
  1163. }
  1164. log_info(LD_REND, "Connection attempt for %s has ended; "
  1165. "cleaning up temporary state.",
  1166. safe_str_client(rend_data->onion_address));
  1167. } else {
  1168. /* We only have an ID for a fetch. Probably used by HSFETCH. */
  1169. purge_hid_serv_from_last_hid_serv_requests(rend_data->desc_id_fetch);
  1170. }
  1171. }
  1172. /** Return a newly allocated extend_info_t* for a randomly chosen introduction
  1173. * point for the named hidden service. Return NULL if all introduction points
  1174. * have been tried and failed.
  1175. */
  1176. extend_info_t *
  1177. rend_client_get_random_intro(const rend_data_t *rend_query)
  1178. {
  1179. int ret;
  1180. extend_info_t *result;
  1181. rend_cache_entry_t *entry;
  1182. ret = rend_cache_lookup_entry(rend_query->onion_address, -1, &entry);
  1183. if (ret < 0 || !rend_client_any_intro_points_usable(entry)) {
  1184. log_warn(LD_REND,
  1185. "Query '%s' didn't have valid rend desc in cache. Failing.",
  1186. safe_str_client(rend_query->onion_address));
  1187. /* XXX: Should we refetch the descriptor here if the IPs are not usable
  1188. * anymore ?. */
  1189. return NULL;
  1190. }
  1191. /* See if we can get a node that complies with ExcludeNodes */
  1192. if ((result = rend_client_get_random_intro_impl(entry, 1, 1)))
  1193. return result;
  1194. /* If not, and StrictNodes is not set, see if we can return any old node
  1195. */
  1196. if (!get_options()->StrictNodes)
  1197. return rend_client_get_random_intro_impl(entry, 0, 1);
  1198. return NULL;
  1199. }
  1200. /** As rend_client_get_random_intro, except assume that StrictNodes is set
  1201. * iff <b>strict</b> is true. If <b>warnings</b> is false, don't complain
  1202. * to the user when we're out of nodes, even if StrictNodes is true.
  1203. */
  1204. static extend_info_t *
  1205. rend_client_get_random_intro_impl(const rend_cache_entry_t *entry,
  1206. const int strict,
  1207. const int warnings)
  1208. {
  1209. int i;
  1210. rend_intro_point_t *intro;
  1211. const or_options_t *options = get_options();
  1212. smartlist_t *usable_nodes;
  1213. int n_excluded = 0;
  1214. /* We'll keep a separate list of the usable nodes. If this becomes empty,
  1215. * no nodes are usable. */
  1216. usable_nodes = smartlist_new();
  1217. smartlist_add_all(usable_nodes, entry->parsed->intro_nodes);
  1218. /* Remove the intro points that have timed out during this HS
  1219. * connection attempt from our list of usable nodes. */
  1220. SMARTLIST_FOREACH(usable_nodes, rend_intro_point_t *, ip,
  1221. if (ip->timed_out) {
  1222. SMARTLIST_DEL_CURRENT(usable_nodes, ip);
  1223. });
  1224. again:
  1225. if (smartlist_len(usable_nodes) == 0) {
  1226. if (n_excluded && get_options()->StrictNodes && warnings) {
  1227. /* We only want to warn if StrictNodes is really set. Otherwise
  1228. * we're just about to retry anyways.
  1229. */
  1230. log_warn(LD_REND, "All introduction points for hidden service are "
  1231. "at excluded relays, and StrictNodes is set. Skipping.");
  1232. }
  1233. smartlist_free(usable_nodes);
  1234. return NULL;
  1235. }
  1236. i = crypto_rand_int(smartlist_len(usable_nodes));
  1237. intro = smartlist_get(usable_nodes, i);
  1238. if (BUG(!intro->extend_info)) {
  1239. /* This should never happen, but it isn't fatal, just try another */
  1240. smartlist_del(usable_nodes, i);
  1241. goto again;
  1242. }
  1243. /* All version 2 HS descriptors come with a TAP onion key.
  1244. * Clients used to try to get the TAP onion key from the consensus, but this
  1245. * meant that hidden services could discover which consensus clients have. */
  1246. if (!extend_info_supports_tap(intro->extend_info)) {
  1247. log_info(LD_REND, "The HS descriptor is missing a TAP onion key for the "
  1248. "intro-point relay '%s'; trying another.",
  1249. safe_str_client(extend_info_describe(intro->extend_info)));
  1250. smartlist_del(usable_nodes, i);
  1251. goto again;
  1252. }
  1253. /* Check if we should refuse to talk to this router. */
  1254. if (strict &&
  1255. routerset_contains_extendinfo(options->ExcludeNodes,
  1256. intro->extend_info)) {
  1257. n_excluded++;
  1258. smartlist_del(usable_nodes, i);
  1259. goto again;
  1260. }
  1261. smartlist_free(usable_nodes);
  1262. return extend_info_dup(intro->extend_info);
  1263. }
  1264. /** Return true iff any introduction points still listed in <b>entry</b> are
  1265. * usable. */
  1266. int
  1267. rend_client_any_intro_points_usable(const rend_cache_entry_t *entry)
  1268. {
  1269. extend_info_t *extend_info =
  1270. rend_client_get_random_intro_impl(entry, get_options()->StrictNodes, 0);
  1271. int rv = (extend_info != NULL);
  1272. extend_info_free(extend_info);
  1273. return rv;
  1274. }
  1275. /** Client-side authorizations for hidden services; map of onion address to
  1276. * rend_service_authorization_t*. */
  1277. static strmap_t *auth_hid_servs = NULL;
  1278. /** Look up the client-side authorization for the hidden service with
  1279. * <b>onion_address</b>. Return NULL if no authorization is available for
  1280. * that address. */
  1281. rend_service_authorization_t*
  1282. rend_client_lookup_service_authorization(const char *onion_address)
  1283. {
  1284. tor_assert(onion_address);
  1285. if (!auth_hid_servs) return NULL;
  1286. return strmap_get(auth_hid_servs, onion_address);
  1287. }
  1288. /** Helper: Free storage held by rend_service_authorization_t. */
  1289. static void
  1290. rend_service_authorization_free(rend_service_authorization_t *auth)
  1291. {
  1292. tor_free(auth);
  1293. }
  1294. /** Helper for strmap_free. */
  1295. static void
  1296. rend_service_authorization_strmap_item_free(void *service_auth)
  1297. {
  1298. rend_service_authorization_free(service_auth);
  1299. }
  1300. /** Release all the storage held in auth_hid_servs.
  1301. */
  1302. void
  1303. rend_service_authorization_free_all(void)
  1304. {
  1305. if (!auth_hid_servs) {
  1306. return;
  1307. }
  1308. strmap_free(auth_hid_servs, rend_service_authorization_strmap_item_free);
  1309. auth_hid_servs = NULL;
  1310. }
  1311. /** Parse <b>config_line</b> as a client-side authorization for a hidden
  1312. * service and add it to the local map of hidden service authorizations.
  1313. * Return 0 for success and -1 for failure. */
  1314. int
  1315. rend_parse_service_authorization(const or_options_t *options,
  1316. int validate_only)
  1317. {
  1318. config_line_t *line;
  1319. int res = -1;
  1320. strmap_t *parsed = strmap_new();
  1321. smartlist_t *sl = smartlist_new();
  1322. rend_service_authorization_t *auth = NULL;
  1323. char *err_msg = NULL;
  1324. for (line = options->HidServAuth; line; line = line->next) {
  1325. char *onion_address, *descriptor_cookie;
  1326. auth = NULL;
  1327. SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
  1328. smartlist_clear(sl);
  1329. smartlist_split_string(sl, line->value, " ",
  1330. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
  1331. if (smartlist_len(sl) < 2) {
  1332. log_warn(LD_CONFIG, "Configuration line does not consist of "
  1333. "\"onion-address authorization-cookie [service-name]\": "
  1334. "'%s'", line->value);
  1335. goto err;
  1336. }
  1337. auth = tor_malloc_zero(sizeof(rend_service_authorization_t));
  1338. /* Parse onion address. */
  1339. onion_address = smartlist_get(sl, 0);
  1340. if (strlen(onion_address) != REND_SERVICE_ADDRESS_LEN ||
  1341. strcmpend(onion_address, ".onion")) {
  1342. log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
  1343. onion_address);
  1344. goto err;
  1345. }
  1346. strlcpy(auth->onion_address, onion_address, REND_SERVICE_ID_LEN_BASE32+1);
  1347. if (!rend_valid_service_id(auth->onion_address)) {
  1348. log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
  1349. onion_address);
  1350. goto err;
  1351. }
  1352. /* Parse descriptor cookie. */
  1353. descriptor_cookie = smartlist_get(sl, 1);
  1354. if (rend_auth_decode_cookie(descriptor_cookie, auth->descriptor_cookie,
  1355. &auth->auth_type, &err_msg) < 0) {
  1356. tor_assert(err_msg);
  1357. log_warn(LD_CONFIG, "%s", err_msg);
  1358. tor_free(err_msg);
  1359. goto err;
  1360. }
  1361. if (strmap_get(parsed, auth->onion_address)) {
  1362. log_warn(LD_CONFIG, "Duplicate authorization for the same hidden "
  1363. "service.");
  1364. goto err;
  1365. }
  1366. strmap_set(parsed, auth->onion_address, auth);
  1367. auth = NULL;
  1368. }
  1369. res = 0;
  1370. goto done;
  1371. err:
  1372. res = -1;
  1373. done:
  1374. rend_service_authorization_free(auth);
  1375. SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
  1376. smartlist_free(sl);
  1377. if (!validate_only && res == 0) {
  1378. rend_service_authorization_free_all();
  1379. auth_hid_servs = parsed;
  1380. } else {
  1381. strmap_free(parsed, rend_service_authorization_strmap_item_free);
  1382. }
  1383. return res;
  1384. }
  1385. /* Can Tor client code make direct (non-anonymous) connections to introduction
  1386. * or rendezvous points?
  1387. * Returns true if tor was compiled with NON_ANONYMOUS_MODE_ENABLED, and is
  1388. * configured in Tor2web mode. */
  1389. int
  1390. rend_client_allow_non_anonymous_connection(const or_options_t *options)
  1391. {
  1392. /* Tor2web support needs to be compiled in to a tor binary. */
  1393. #ifdef NON_ANONYMOUS_MODE_ENABLED
  1394. /* Tor2web */
  1395. return options->Tor2webMode ? 1 : 0;
  1396. #else
  1397. (void)options;
  1398. return 0;
  1399. #endif
  1400. }
  1401. /* At compile-time, was non-anonymous mode enabled via
  1402. * NON_ANONYMOUS_MODE_ENABLED ? */
  1403. int
  1404. rend_client_non_anonymous_mode_enabled(const or_options_t *options)
  1405. {
  1406. (void)options;
  1407. /* Tor2web support needs to be compiled in to a tor binary. */
  1408. #ifdef NON_ANONYMOUS_MODE_ENABLED
  1409. /* Tor2web */
  1410. return 1;
  1411. #else
  1412. return 0;
  1413. #endif
  1414. }