rendclient.c 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2017, 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 "control.h"
  17. #include "crypto_rand.h"
  18. #include "crypto_util.h"
  19. #include "directory.h"
  20. #include "hs_circuit.h"
  21. #include "hs_client.h"
  22. #include "hs_common.h"
  23. #include "main.h"
  24. #include "networkstatus.h"
  25. #include "nodelist.h"
  26. #include "relay.h"
  27. #include "rendclient.h"
  28. #include "rendcommon.h"
  29. #include "rephist.h"
  30. #include "router.h"
  31. #include "routerlist.h"
  32. #include "routerset.h"
  33. #include "dir_connection_st.h"
  34. #include "entry_connection_st.h"
  35. static extend_info_t *rend_client_get_random_intro_impl(
  36. const rend_cache_entry_t *rend_query,
  37. const int strict, const int warnings);
  38. /** Purge all potentially remotely-detectable state held in the hidden
  39. * service client code. Called on SIGNAL NEWNYM. */
  40. void
  41. rend_client_purge_state(void)
  42. {
  43. rend_cache_purge();
  44. rend_cache_failure_purge();
  45. rend_client_cancel_descriptor_fetches();
  46. hs_purge_last_hid_serv_requests();
  47. }
  48. /** Called when we've established a circuit to an introduction point:
  49. * send the introduction request. */
  50. void
  51. rend_client_introcirc_has_opened(origin_circuit_t *circ)
  52. {
  53. tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  54. tor_assert(circ->cpath);
  55. log_info(LD_REND,"introcirc is open");
  56. connection_ap_attach_pending(1);
  57. }
  58. /** Send the establish-rendezvous cell along a rendezvous circuit. if
  59. * it fails, mark the circ for close and return -1. else return 0.
  60. */
  61. static int
  62. rend_client_send_establish_rendezvous(origin_circuit_t *circ)
  63. {
  64. tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
  65. tor_assert(circ->rend_data);
  66. log_info(LD_REND, "Sending an ESTABLISH_RENDEZVOUS cell");
  67. crypto_rand(circ->rend_data->rend_cookie, REND_COOKIE_LEN);
  68. /* Set timestamp_dirty, because circuit_expire_building expects it,
  69. * and the rend cookie also means we've used the circ. */
  70. circ->base_.timestamp_dirty = time(NULL);
  71. /* We've attempted to use this circuit. Probe it if we fail */
  72. pathbias_count_use_attempt(circ);
  73. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  74. RELAY_COMMAND_ESTABLISH_RENDEZVOUS,
  75. circ->rend_data->rend_cookie,
  76. REND_COOKIE_LEN,
  77. circ->cpath->prev)<0) {
  78. /* circ is already marked for close */
  79. log_warn(LD_GENERAL, "Couldn't send ESTABLISH_RENDEZVOUS cell");
  80. return -1;
  81. }
  82. return 0;
  83. }
  84. /** Called when we're trying to connect an ap conn; sends an INTRODUCE1 cell
  85. * down introcirc if possible.
  86. */
  87. int
  88. rend_client_send_introduction(origin_circuit_t *introcirc,
  89. origin_circuit_t *rendcirc)
  90. {
  91. const or_options_t *options = get_options();
  92. size_t payload_len;
  93. int r, v3_shift = 0;
  94. char payload[RELAY_PAYLOAD_SIZE];
  95. char tmp[RELAY_PAYLOAD_SIZE];
  96. rend_cache_entry_t *entry = NULL;
  97. crypt_path_t *cpath;
  98. off_t dh_offset;
  99. crypto_pk_t *intro_key = NULL;
  100. int status = 0;
  101. const char *onion_address;
  102. tor_assert(introcirc->base_.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  103. tor_assert(rendcirc->base_.purpose == CIRCUIT_PURPOSE_C_REND_READY);
  104. tor_assert(introcirc->rend_data);
  105. tor_assert(rendcirc->rend_data);
  106. tor_assert(!rend_cmp_service_ids(rend_data_get_address(introcirc->rend_data),
  107. rend_data_get_address(rendcirc->rend_data)));
  108. assert_circ_anonymity_ok(introcirc, options);
  109. assert_circ_anonymity_ok(rendcirc, options);
  110. onion_address = rend_data_get_address(introcirc->rend_data);
  111. r = rend_cache_lookup_entry(onion_address, -1, &entry);
  112. /* An invalid onion address is not possible else we have a big issue. */
  113. tor_assert(r != -EINVAL);
  114. if (r < 0 || !rend_client_any_intro_points_usable(entry)) {
  115. /* If the descriptor is not found or the intro points are not usable
  116. * anymore, trigger a fetch. */
  117. log_info(LD_REND,
  118. "query %s didn't have valid rend desc in cache. "
  119. "Refetching descriptor.",
  120. safe_str_client(onion_address));
  121. rend_client_refetch_v2_renddesc(introcirc->rend_data);
  122. {
  123. connection_t *conn;
  124. while ((conn = connection_get_by_type_state_rendquery(CONN_TYPE_AP,
  125. AP_CONN_STATE_CIRCUIT_WAIT, onion_address))) {
  126. connection_ap_mark_as_non_pending_circuit(TO_ENTRY_CONN(conn));
  127. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  128. }
  129. }
  130. status = -1;
  131. goto cleanup;
  132. }
  133. /* first 20 bytes of payload are the hash of the service's pk */
  134. intro_key = NULL;
  135. SMARTLIST_FOREACH(entry->parsed->intro_nodes, rend_intro_point_t *,
  136. intro, {
  137. if (tor_memeq(introcirc->build_state->chosen_exit->identity_digest,
  138. intro->extend_info->identity_digest, DIGEST_LEN)) {
  139. intro_key = intro->intro_key;
  140. break;
  141. }
  142. });
  143. if (!intro_key) {
  144. log_info(LD_REND, "Could not find intro key for %s at %s; we "
  145. "have a v2 rend desc with %d intro points. "
  146. "Trying a different intro point...",
  147. safe_str_client(onion_address),
  148. safe_str_client(extend_info_describe(
  149. introcirc->build_state->chosen_exit)),
  150. smartlist_len(entry->parsed->intro_nodes));
  151. if (hs_client_reextend_intro_circuit(introcirc)) {
  152. status = -2;
  153. goto perm_err;
  154. } else {
  155. status = -1;
  156. goto cleanup;
  157. }
  158. }
  159. if (crypto_pk_get_digest(intro_key, payload)<0) {
  160. log_warn(LD_BUG, "Internal error: couldn't hash public key.");
  161. status = -2;
  162. goto perm_err;
  163. }
  164. /* Initialize the pending_final_cpath and start the DH handshake. */
  165. cpath = rendcirc->build_state->pending_final_cpath;
  166. if (!cpath) {
  167. cpath = rendcirc->build_state->pending_final_cpath =
  168. tor_malloc_zero(sizeof(crypt_path_t));
  169. cpath->magic = CRYPT_PATH_MAGIC;
  170. if (!(cpath->rend_dh_handshake_state = crypto_dh_new(DH_TYPE_REND))) {
  171. log_warn(LD_BUG, "Internal error: couldn't allocate DH.");
  172. status = -2;
  173. goto perm_err;
  174. }
  175. if (crypto_dh_generate_public(cpath->rend_dh_handshake_state)<0) {
  176. log_warn(LD_BUG, "Internal error: couldn't generate g^x.");
  177. status = -2;
  178. goto perm_err;
  179. }
  180. }
  181. /* If version is 3, write (optional) auth data and timestamp. */
  182. if (entry->parsed->protocols & (1<<3)) {
  183. tmp[0] = 3; /* version 3 of the cell format */
  184. /* auth type, if any */
  185. tmp[1] = (uint8_t) TO_REND_DATA_V2(introcirc->rend_data)->auth_type;
  186. v3_shift = 1;
  187. if (tmp[1] != REND_NO_AUTH) {
  188. set_uint16(tmp+2, htons(REND_DESC_COOKIE_LEN));
  189. memcpy(tmp+4, TO_REND_DATA_V2(introcirc->rend_data)->descriptor_cookie,
  190. REND_DESC_COOKIE_LEN);
  191. v3_shift += 2+REND_DESC_COOKIE_LEN;
  192. }
  193. /* Once this held a timestamp. */
  194. set_uint32(tmp+v3_shift+1, 0);
  195. v3_shift += 4;
  196. } /* if version 2 only write version number */
  197. else if (entry->parsed->protocols & (1<<2)) {
  198. tmp[0] = 2; /* version 2 of the cell format */
  199. }
  200. /* write the remaining items into tmp */
  201. if (entry->parsed->protocols & (1<<3) || entry->parsed->protocols & (1<<2)) {
  202. /* version 2 format */
  203. extend_info_t *extend_info = rendcirc->build_state->chosen_exit;
  204. int klen;
  205. /* nul pads */
  206. set_uint32(tmp+v3_shift+1, tor_addr_to_ipv4n(&extend_info->addr));
  207. set_uint16(tmp+v3_shift+5, htons(extend_info->port));
  208. memcpy(tmp+v3_shift+7, extend_info->identity_digest, DIGEST_LEN);
  209. klen = crypto_pk_asn1_encode(extend_info->onion_key,
  210. tmp+v3_shift+7+DIGEST_LEN+2,
  211. sizeof(tmp)-(v3_shift+7+DIGEST_LEN+2));
  212. if (klen < 0) {
  213. log_warn(LD_BUG,"Internal error: can't encode public key.");
  214. status = -2;
  215. goto perm_err;
  216. }
  217. set_uint16(tmp+v3_shift+7+DIGEST_LEN, htons(klen));
  218. memcpy(tmp+v3_shift+7+DIGEST_LEN+2+klen, rendcirc->rend_data->rend_cookie,
  219. REND_COOKIE_LEN);
  220. dh_offset = v3_shift+7+DIGEST_LEN+2+klen+REND_COOKIE_LEN;
  221. } else {
  222. /* Version 0. */
  223. strncpy(tmp, rendcirc->build_state->chosen_exit->nickname,
  224. (MAX_NICKNAME_LEN+1)); /* nul pads */
  225. memcpy(tmp+MAX_NICKNAME_LEN+1, rendcirc->rend_data->rend_cookie,
  226. REND_COOKIE_LEN);
  227. dh_offset = MAX_NICKNAME_LEN+1+REND_COOKIE_LEN;
  228. }
  229. if (crypto_dh_get_public(cpath->rend_dh_handshake_state, tmp+dh_offset,
  230. DH_KEY_LEN)<0) {
  231. log_warn(LD_BUG, "Internal error: couldn't extract g^x.");
  232. status = -2;
  233. goto perm_err;
  234. }
  235. /*XXX maybe give crypto_pk_obsolete_public_hybrid_encrypt a max_len arg,
  236. * to avoid buffer overflows? */
  237. r = crypto_pk_obsolete_public_hybrid_encrypt(intro_key, payload+DIGEST_LEN,
  238. sizeof(payload)-DIGEST_LEN,
  239. tmp,
  240. (int)(dh_offset+DH_KEY_LEN),
  241. PK_PKCS1_OAEP_PADDING, 0);
  242. if (r<0) {
  243. log_warn(LD_BUG,"Internal error: hybrid pk encrypt failed.");
  244. status = -2;
  245. goto perm_err;
  246. }
  247. payload_len = DIGEST_LEN + r;
  248. tor_assert(payload_len <= RELAY_PAYLOAD_SIZE); /* we overran something */
  249. /* Copy the rendezvous cookie from rendcirc to introcirc, so that
  250. * when introcirc gets an ack, we can change the state of the right
  251. * rendezvous circuit. */
  252. memcpy(introcirc->rend_data->rend_cookie, rendcirc->rend_data->rend_cookie,
  253. REND_COOKIE_LEN);
  254. log_info(LD_REND, "Sending an INTRODUCE1 cell");
  255. if (relay_send_command_from_edge(0, TO_CIRCUIT(introcirc),
  256. RELAY_COMMAND_INTRODUCE1,
  257. payload, payload_len,
  258. introcirc->cpath->prev)<0) {
  259. /* introcirc is already marked for close. leave rendcirc alone. */
  260. log_warn(LD_BUG, "Couldn't send INTRODUCE1 cell");
  261. status = -2;
  262. goto cleanup;
  263. }
  264. /* Now, we wait for an ACK or NAK on this circuit. */
  265. circuit_change_purpose(TO_CIRCUIT(introcirc),
  266. CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT);
  267. /* Set timestamp_dirty, because circuit_expire_building expects it
  268. * to specify when a circuit entered the _C_INTRODUCE_ACK_WAIT
  269. * state. */
  270. introcirc->base_.timestamp_dirty = time(NULL);
  271. pathbias_count_use_attempt(introcirc);
  272. goto cleanup;
  273. perm_err:
  274. if (!introcirc->base_.marked_for_close)
  275. circuit_mark_for_close(TO_CIRCUIT(introcirc), END_CIRC_REASON_INTERNAL);
  276. circuit_mark_for_close(TO_CIRCUIT(rendcirc), END_CIRC_REASON_INTERNAL);
  277. cleanup:
  278. memwipe(payload, 0, sizeof(payload));
  279. memwipe(tmp, 0, sizeof(tmp));
  280. return status;
  281. }
  282. /** Called when a rendezvous circuit is open; sends a establish
  283. * rendezvous circuit as appropriate. */
  284. void
  285. rend_client_rendcirc_has_opened(origin_circuit_t *circ)
  286. {
  287. tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
  288. log_info(LD_REND,"rendcirc is open");
  289. /* generate a rendezvous cookie, store it in circ */
  290. if (rend_client_send_establish_rendezvous(circ) < 0) {
  291. return;
  292. }
  293. }
  294. /**
  295. * Called to close other intro circuits we launched in parallel.
  296. */
  297. static void
  298. rend_client_close_other_intros(const uint8_t *rend_pk_digest)
  299. {
  300. /* abort parallel intro circs, if any */
  301. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, c) {
  302. if ((c->purpose == CIRCUIT_PURPOSE_C_INTRODUCING ||
  303. c->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) &&
  304. !c->marked_for_close && CIRCUIT_IS_ORIGIN(c)) {
  305. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(c);
  306. if (oc->rend_data &&
  307. rend_circuit_pk_digest_eq(oc, rend_pk_digest)) {
  308. log_info(LD_REND|LD_CIRC, "Closing introduction circuit %d that we "
  309. "built in parallel (Purpose %d).", oc->global_identifier,
  310. c->purpose);
  311. circuit_mark_for_close(c, END_CIRC_REASON_IP_NOW_REDUNDANT);
  312. }
  313. }
  314. }
  315. SMARTLIST_FOREACH_END(c);
  316. }
  317. /** Called when get an ACK or a NAK for a REND_INTRODUCE1 cell.
  318. */
  319. int
  320. rend_client_introduction_acked(origin_circuit_t *circ,
  321. const uint8_t *request, size_t request_len)
  322. {
  323. const or_options_t *options = get_options();
  324. origin_circuit_t *rendcirc;
  325. (void) request; // XXXX Use this.
  326. tor_assert(circ->build_state);
  327. tor_assert(circ->build_state->chosen_exit);
  328. assert_circ_anonymity_ok(circ, options);
  329. tor_assert(circ->rend_data);
  330. if (request_len == 0) {
  331. /* It's an ACK; the introduction point relayed our introduction request. */
  332. /* Locate the rend circ which is waiting to hear about this ack,
  333. * and tell it.
  334. */
  335. log_info(LD_REND,"Received ack. Telling rend circ...");
  336. rendcirc = circuit_get_ready_rend_circ_by_rend_data(circ->rend_data);
  337. if (rendcirc) { /* remember the ack */
  338. assert_circ_anonymity_ok(rendcirc, options);
  339. circuit_change_purpose(TO_CIRCUIT(rendcirc),
  340. CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED);
  341. /* Set timestamp_dirty, because circuit_expire_building expects
  342. * it to specify when a circuit entered the
  343. * _C_REND_READY_INTRO_ACKED state. */
  344. rendcirc->base_.timestamp_dirty = time(NULL);
  345. } else {
  346. log_info(LD_REND,"...Found no rend circ. Dropping on the floor.");
  347. }
  348. /* close the circuit: we won't need it anymore. */
  349. circuit_change_purpose(TO_CIRCUIT(circ),
  350. CIRCUIT_PURPOSE_C_INTRODUCE_ACKED);
  351. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  352. /* close any other intros launched in parallel */
  353. rend_client_close_other_intros(rend_data_get_pk_digest(circ->rend_data,
  354. NULL));
  355. } else {
  356. /* It's a NAK; the introduction point didn't relay our request. */
  357. circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_C_INTRODUCING);
  358. /* Remove this intro point from the set of viable introduction
  359. * points. If any remain, extend to a new one and try again.
  360. * If none remain, refetch the service descriptor.
  361. */
  362. log_info(LD_REND, "Got nack for %s from %s...",
  363. safe_str_client(rend_data_get_address(circ->rend_data)),
  364. safe_str_client(extend_info_describe(circ->build_state->chosen_exit)));
  365. if (rend_client_report_intro_point_failure(circ->build_state->chosen_exit,
  366. circ->rend_data,
  367. INTRO_POINT_FAILURE_GENERIC)>0) {
  368. /* There are introduction points left. Re-extend the circuit to
  369. * another intro point and try again. */
  370. int result = hs_client_reextend_intro_circuit(circ);
  371. /* XXXX If that call failed, should we close the rend circuit,
  372. * too? */
  373. return result;
  374. } else {
  375. /* Close circuit because no more intro points are usable thus not
  376. * useful anymore. Change it's purpose before so we don't report an
  377. * intro point failure again triggering an extra descriptor fetch. */
  378. circuit_change_purpose(TO_CIRCUIT(circ),
  379. CIRCUIT_PURPOSE_C_INTRODUCE_ACKED);
  380. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  381. }
  382. }
  383. return 0;
  384. }
  385. /** Determine the responsible hidden service directories for <b>desc_id</b>
  386. * and fetch the descriptor with that ID from one of them. Only
  387. * send a request to a hidden service directory that we have not yet tried
  388. * during this attempt to connect to this hidden service; on success, return 1,
  389. * in the case that no hidden service directory is left to ask for the
  390. * descriptor, return 0, and in case of a failure -1. */
  391. static int
  392. directory_get_from_hs_dir(const char *desc_id,
  393. const rend_data_t *rend_query,
  394. routerstatus_t *rs_hsdir)
  395. {
  396. routerstatus_t *hs_dir = rs_hsdir;
  397. char *hsdir_fp;
  398. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  399. char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
  400. const rend_data_v2_t *rend_data;
  401. #ifdef ENABLE_TOR2WEB_MODE
  402. const int tor2web_mode = get_options()->Tor2webMode;
  403. const int how_to_fetch = tor2web_mode ? DIRIND_ONEHOP : DIRIND_ANONYMOUS;
  404. #else
  405. const int how_to_fetch = DIRIND_ANONYMOUS;
  406. #endif /* defined(ENABLE_TOR2WEB_MODE) */
  407. tor_assert(desc_id);
  408. tor_assert(rend_query);
  409. rend_data = TO_REND_DATA_V2(rend_query);
  410. base32_encode(desc_id_base32, sizeof(desc_id_base32),
  411. desc_id, DIGEST_LEN);
  412. /* Automatically pick an hs dir if none given. */
  413. if (!rs_hsdir) {
  414. /* Determine responsible dirs. Even if we can't get all we want, work with
  415. * the ones we have. If it's empty, we'll notice in hs_pick_hsdir(). */
  416. smartlist_t *responsible_dirs = smartlist_new();
  417. hid_serv_get_responsible_directories(responsible_dirs, desc_id);
  418. hs_dir = hs_pick_hsdir(responsible_dirs, desc_id_base32);
  419. if (!hs_dir) {
  420. /* No suitable hs dir can be found, stop right now. */
  421. control_event_hsv2_descriptor_failed(rend_query, NULL,
  422. "QUERY_NO_HSDIR");
  423. control_event_hs_descriptor_content(rend_data_get_address(rend_query),
  424. desc_id_base32, NULL, NULL);
  425. return 0;
  426. }
  427. }
  428. /* Add a copy of the HSDir identity digest to the query so we can track it
  429. * on the control port. */
  430. hsdir_fp = tor_memdup(hs_dir->identity_digest,
  431. sizeof(hs_dir->identity_digest));
  432. smartlist_add(rend_query->hsdirs_fp, hsdir_fp);
  433. /* Encode descriptor cookie for logging purposes. Also, if the cookie is
  434. * malformed, no fetch is triggered thus this needs to be done before the
  435. * fetch request. */
  436. if (rend_data->auth_type != REND_NO_AUTH) {
  437. if (base64_encode(descriptor_cookie_base64,
  438. sizeof(descriptor_cookie_base64),
  439. rend_data->descriptor_cookie,
  440. REND_DESC_COOKIE_LEN,
  441. 0)<0) {
  442. log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
  443. control_event_hsv2_descriptor_failed(rend_query, hsdir_fp, "BAD_DESC");
  444. control_event_hs_descriptor_content(rend_data_get_address(rend_query),
  445. desc_id_base32, hsdir_fp, NULL);
  446. return 0;
  447. }
  448. /* Remove == signs. */
  449. descriptor_cookie_base64[strlen(descriptor_cookie_base64)-2] = '\0';
  450. } else {
  451. strlcpy(descriptor_cookie_base64, "(none)",
  452. sizeof(descriptor_cookie_base64));
  453. }
  454. /* Send fetch request. (Pass query and possibly descriptor cookie so that
  455. * they can be written to the directory connection and be referred to when
  456. * the response arrives. */
  457. directory_request_t *req =
  458. directory_request_new(DIR_PURPOSE_FETCH_RENDDESC_V2);
  459. directory_request_set_routerstatus(req, hs_dir);
  460. directory_request_set_indirection(req, how_to_fetch);
  461. directory_request_set_resource(req, desc_id_base32);
  462. directory_request_set_rend_query(req, rend_query);
  463. directory_initiate_request(req);
  464. directory_request_free(req);
  465. log_info(LD_REND, "Sending fetch request for v2 descriptor for "
  466. "service '%s' with descriptor ID '%s', auth type %d, "
  467. "and descriptor cookie '%s' to hidden service "
  468. "directory %s",
  469. rend_data->onion_address, desc_id_base32,
  470. rend_data->auth_type,
  471. (rend_data->auth_type == REND_NO_AUTH ? "[none]" :
  472. escaped_safe_str_client(descriptor_cookie_base64)),
  473. routerstatus_describe(hs_dir));
  474. control_event_hs_descriptor_requested(rend_data->onion_address,
  475. rend_data->auth_type,
  476. hs_dir->identity_digest,
  477. desc_id_base32, NULL);
  478. return 1;
  479. }
  480. /** Remove tracked HSDir requests from our history for this hidden service
  481. * descriptor <b>desc_id</b> (of size DIGEST_LEN) */
  482. static void
  483. purge_v2_hidserv_req(const char *desc_id)
  484. {
  485. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  486. /* The hsdir request tracker stores v2 keys using the base32 encoded
  487. desc_id. Do it: */
  488. base32_encode(desc_id_base32, sizeof(desc_id_base32), desc_id,
  489. DIGEST_LEN);
  490. hs_purge_hid_serv_from_last_hid_serv_requests(desc_id_base32);
  491. }
  492. /** Fetch a v2 descriptor using the given descriptor id. If any hsdir(s) are
  493. * given, they will be used instead.
  494. *
  495. * On success, 1 is returned. If no hidden service is left to ask, return 0.
  496. * On error, -1 is returned. */
  497. static int
  498. fetch_v2_desc_by_descid(const char *desc_id,
  499. const rend_data_t *rend_query, smartlist_t *hsdirs)
  500. {
  501. int ret;
  502. tor_assert(rend_query);
  503. if (!hsdirs) {
  504. ret = directory_get_from_hs_dir(desc_id, rend_query, NULL);
  505. goto end; /* either success or failure, but we're done */
  506. }
  507. /* Using the given hsdir list, trigger a fetch on each of them. */
  508. SMARTLIST_FOREACH_BEGIN(hsdirs, routerstatus_t *, hs_dir) {
  509. /* This should always be a success. */
  510. ret = directory_get_from_hs_dir(desc_id, rend_query, hs_dir);
  511. tor_assert(ret);
  512. } SMARTLIST_FOREACH_END(hs_dir);
  513. /* Everything went well. */
  514. ret = 0;
  515. end:
  516. return ret;
  517. }
  518. /** Fetch a v2 descriptor using the onion address in the given query object.
  519. * This will compute the descriptor id for each replicas and fetch it on the
  520. * given hsdir(s) if any or the responsible ones that are chosen
  521. * automatically.
  522. *
  523. * On success, 1 is returned. If no hidden service is left to ask, return 0.
  524. * On error, -1 is returned. */
  525. static int
  526. fetch_v2_desc_by_addr(rend_data_t *rend_query, smartlist_t *hsdirs)
  527. {
  528. char descriptor_id[DIGEST_LEN];
  529. int replicas_left_to_try[REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS];
  530. int i, tries_left, ret;
  531. rend_data_v2_t *rend_data = TO_REND_DATA_V2(rend_query);
  532. /* Randomly iterate over the replicas until a descriptor can be fetched
  533. * from one of the consecutive nodes, or no options are left. */
  534. for (i = 0; i < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; i++) {
  535. replicas_left_to_try[i] = i;
  536. }
  537. tries_left = REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS;
  538. while (tries_left > 0) {
  539. int rand_val = crypto_rand_int(tries_left);
  540. int chosen_replica = replicas_left_to_try[rand_val];
  541. replicas_left_to_try[rand_val] = replicas_left_to_try[--tries_left];
  542. ret = rend_compute_v2_desc_id(descriptor_id,
  543. rend_data->onion_address,
  544. rend_data->auth_type == REND_STEALTH_AUTH ?
  545. rend_data->descriptor_cookie : NULL,
  546. time(NULL), chosen_replica);
  547. if (ret < 0) {
  548. /* Normally, on failure the descriptor_id is untouched but let's be
  549. * safe in general in case the function changes at some point. */
  550. goto end;
  551. }
  552. if (tor_memcmp(descriptor_id, rend_data->descriptor_id[chosen_replica],
  553. sizeof(descriptor_id)) != 0) {
  554. /* Not equal from what we currently have so purge the last hid serv
  555. * request cache and update the descriptor ID with the new value. */
  556. purge_v2_hidserv_req(rend_data->descriptor_id[chosen_replica]);
  557. memcpy(rend_data->descriptor_id[chosen_replica], descriptor_id,
  558. sizeof(rend_data->descriptor_id[chosen_replica]));
  559. }
  560. /* Trigger the fetch with the computed descriptor ID. */
  561. ret = fetch_v2_desc_by_descid(descriptor_id, rend_query, hsdirs);
  562. if (ret != 0) {
  563. /* Either on success or failure, as long as we tried a fetch we are
  564. * done here. */
  565. goto end;
  566. }
  567. }
  568. /* If we come here, there are no hidden service directories left. */
  569. log_info(LD_REND, "Could not pick one of the responsible hidden "
  570. "service directories to fetch descriptors, because "
  571. "we already tried them all unsuccessfully.");
  572. ret = 0;
  573. end:
  574. memwipe(descriptor_id, 0, sizeof(descriptor_id));
  575. return ret;
  576. }
  577. /** Fetch a v2 descriptor using the given query. If any hsdir are specified,
  578. * use them for the fetch.
  579. *
  580. * On success, 1 is returned. If no hidden service is left to ask, return 0.
  581. * On error, -1 is returned. */
  582. int
  583. rend_client_fetch_v2_desc(rend_data_t *query, smartlist_t *hsdirs)
  584. {
  585. int ret;
  586. rend_data_v2_t *rend_data;
  587. const char *onion_address;
  588. tor_assert(query);
  589. /* Get the version 2 data structure of the query. */
  590. rend_data = TO_REND_DATA_V2(query);
  591. onion_address = rend_data_get_address(query);
  592. /* Depending on what's available in the rend data query object, we will
  593. * trigger a fetch by HS address or using a descriptor ID. */
  594. if (onion_address[0] != '\0') {
  595. ret = fetch_v2_desc_by_addr(query, hsdirs);
  596. } else if (!tor_digest_is_zero(rend_data->desc_id_fetch)) {
  597. ret = fetch_v2_desc_by_descid(rend_data->desc_id_fetch, query,
  598. hsdirs);
  599. } else {
  600. /* Query data is invalid. */
  601. ret = -1;
  602. goto error;
  603. }
  604. error:
  605. return ret;
  606. }
  607. /** Unless we already have a descriptor for <b>rend_query</b> with at least
  608. * one (possibly) working introduction point in it, start a connection to a
  609. * hidden service directory to fetch a v2 rendezvous service descriptor. */
  610. void
  611. rend_client_refetch_v2_renddesc(rend_data_t *rend_query)
  612. {
  613. rend_cache_entry_t *e = NULL;
  614. const char *onion_address = rend_data_get_address(rend_query);
  615. tor_assert(rend_query);
  616. /* Before fetching, check if we already have a usable descriptor here. */
  617. if (rend_cache_lookup_entry(onion_address, -1, &e) == 0 &&
  618. rend_client_any_intro_points_usable(e)) {
  619. log_info(LD_REND, "We would fetch a v2 rendezvous descriptor, but we "
  620. "already have a usable descriptor here. Not fetching.");
  621. return;
  622. }
  623. /* Are we configured to fetch descriptors? */
  624. if (!get_options()->FetchHidServDescriptors) {
  625. log_warn(LD_REND, "We received an onion address for a v2 rendezvous "
  626. "service descriptor, but are not fetching service descriptors.");
  627. return;
  628. }
  629. log_debug(LD_REND, "Fetching v2 rendezvous descriptor for service %s",
  630. safe_str_client(onion_address));
  631. rend_client_fetch_v2_desc(rend_query, NULL);
  632. /* We don't need to look the error code because either on failure or
  633. * success, the necessary steps to continue the HS connection will be
  634. * triggered once the descriptor arrives or if all fetch failed. */
  635. return;
  636. }
  637. /** Cancel all rendezvous descriptor fetches currently in progress.
  638. */
  639. void
  640. rend_client_cancel_descriptor_fetches(void)
  641. {
  642. smartlist_t *connection_array = get_connection_array();
  643. SMARTLIST_FOREACH_BEGIN(connection_array, connection_t *, conn) {
  644. if (conn->type == CONN_TYPE_DIR &&
  645. conn->purpose == DIR_PURPOSE_FETCH_RENDDESC_V2) {
  646. /* It's a rendezvous descriptor fetch in progress -- cancel it
  647. * by marking the connection for close.
  648. *
  649. * Even if this connection has already reached EOF, this is
  650. * enough to make sure that if the descriptor hasn't been
  651. * processed yet, it won't be. See the end of
  652. * connection_handle_read; connection_reached_eof (indirectly)
  653. * processes whatever response the connection received. */
  654. const rend_data_t *rd = (TO_DIR_CONN(conn))->rend_data;
  655. if (!rd) {
  656. log_warn(LD_BUG | LD_REND,
  657. "Marking for close dir conn fetching rendezvous "
  658. "descriptor for unknown service!");
  659. } else {
  660. log_debug(LD_REND, "Marking for close dir conn fetching "
  661. "rendezvous descriptor for service %s",
  662. safe_str(rend_data_get_address(rd)));
  663. }
  664. connection_mark_for_close(conn);
  665. }
  666. } SMARTLIST_FOREACH_END(conn);
  667. }
  668. /** Mark <b>failed_intro</b> as a failed introduction point for the
  669. * hidden service specified by <b>rend_query</b>. If the HS now has no
  670. * usable intro points, or we do not have an HS descriptor for it,
  671. * then launch a new renddesc fetch.
  672. *
  673. * If <b>failure_type</b> is INTRO_POINT_FAILURE_GENERIC, remove the
  674. * intro point from (our parsed copy of) the HS descriptor.
  675. *
  676. * If <b>failure_type</b> is INTRO_POINT_FAILURE_TIMEOUT, mark the
  677. * intro point as 'timed out'; it will not be retried until the
  678. * current hidden service connection attempt has ended or it has
  679. * appeared in a newly fetched rendezvous descriptor.
  680. *
  681. * If <b>failure_type</b> is INTRO_POINT_FAILURE_UNREACHABLE,
  682. * increment the intro point's reachability-failure count; if it has
  683. * now failed MAX_INTRO_POINT_REACHABILITY_FAILURES or more times,
  684. * remove the intro point from (our parsed copy of) the HS descriptor.
  685. *
  686. * Return -1 if error, 0 if no usable intro points remain or service
  687. * unrecognized, 1 if recognized and some intro points remain.
  688. */
  689. int
  690. rend_client_report_intro_point_failure(extend_info_t *failed_intro,
  691. rend_data_t *rend_data,
  692. unsigned int failure_type)
  693. {
  694. int i, r;
  695. rend_cache_entry_t *ent;
  696. connection_t *conn;
  697. const char *onion_address = rend_data_get_address(rend_data);
  698. r = rend_cache_lookup_entry(onion_address, -1, &ent);
  699. if (r < 0) {
  700. /* Either invalid onion address or cache entry not found. */
  701. switch (-r) {
  702. case EINVAL:
  703. log_warn(LD_BUG, "Malformed service ID %s.",
  704. escaped_safe_str_client(onion_address));
  705. return -1;
  706. case ENOENT:
  707. log_info(LD_REND, "Unknown service %s. Re-fetching descriptor.",
  708. escaped_safe_str_client(onion_address));
  709. rend_client_refetch_v2_renddesc(rend_data);
  710. return 0;
  711. default:
  712. log_warn(LD_BUG, "Unknown cache lookup returned code: %d", r);
  713. return -1;
  714. }
  715. }
  716. /* The intro points are not checked here if they are usable or not because
  717. * this is called when an intro point circuit is closed thus there must be
  718. * at least one intro point that is usable and is about to be flagged. */
  719. for (i = 0; i < smartlist_len(ent->parsed->intro_nodes); i++) {
  720. rend_intro_point_t *intro = smartlist_get(ent->parsed->intro_nodes, i);
  721. if (tor_memeq(failed_intro->identity_digest,
  722. intro->extend_info->identity_digest, DIGEST_LEN)) {
  723. switch (failure_type) {
  724. default:
  725. log_warn(LD_BUG, "Unknown failure type %u. Removing intro point.",
  726. failure_type);
  727. tor_fragile_assert();
  728. /* fall through */
  729. case INTRO_POINT_FAILURE_GENERIC:
  730. rend_cache_intro_failure_note(failure_type,
  731. (uint8_t *)failed_intro->identity_digest,
  732. onion_address);
  733. rend_intro_point_free(intro);
  734. smartlist_del(ent->parsed->intro_nodes, i);
  735. break;
  736. case INTRO_POINT_FAILURE_TIMEOUT:
  737. intro->timed_out = 1;
  738. break;
  739. case INTRO_POINT_FAILURE_UNREACHABLE:
  740. ++(intro->unreachable_count);
  741. {
  742. int zap_intro_point =
  743. intro->unreachable_count >= MAX_INTRO_POINT_REACHABILITY_FAILURES;
  744. log_info(LD_REND, "Failed to reach this intro point %u times.%s",
  745. intro->unreachable_count,
  746. zap_intro_point ? " Removing from descriptor.": "");
  747. if (zap_intro_point) {
  748. rend_cache_intro_failure_note(
  749. failure_type,
  750. (uint8_t *) failed_intro->identity_digest, onion_address);
  751. rend_intro_point_free(intro);
  752. smartlist_del(ent->parsed->intro_nodes, i);
  753. }
  754. }
  755. break;
  756. }
  757. break;
  758. }
  759. }
  760. if (! rend_client_any_intro_points_usable(ent)) {
  761. log_info(LD_REND,
  762. "No more intro points remain for %s. Re-fetching descriptor.",
  763. escaped_safe_str_client(onion_address));
  764. rend_client_refetch_v2_renddesc(rend_data);
  765. /* move all pending streams back to renddesc_wait */
  766. /* NOTE: We can now do this faster, if we use pending_entry_connections */
  767. while ((conn = connection_get_by_type_state_rendquery(CONN_TYPE_AP,
  768. AP_CONN_STATE_CIRCUIT_WAIT,
  769. onion_address))) {
  770. connection_ap_mark_as_non_pending_circuit(TO_ENTRY_CONN(conn));
  771. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  772. }
  773. return 0;
  774. }
  775. log_info(LD_REND,"%d options left for %s.",
  776. smartlist_len(ent->parsed->intro_nodes),
  777. escaped_safe_str_client(onion_address));
  778. return 1;
  779. }
  780. /** The service sent us a rendezvous cell; join the circuits. */
  781. int
  782. rend_client_receive_rendezvous(origin_circuit_t *circ, const uint8_t *request,
  783. size_t request_len)
  784. {
  785. if (request_len != DH_KEY_LEN+DIGEST_LEN) {
  786. log_warn(LD_PROTOCOL,"Incorrect length (%d) on RENDEZVOUS2 cell.",
  787. (int)request_len);
  788. goto err;
  789. }
  790. if (hs_circuit_setup_e2e_rend_circ_legacy_client(circ, request) < 0) {
  791. log_warn(LD_GENERAL, "Failed to setup circ");
  792. goto err;
  793. }
  794. return 0;
  795. err:
  796. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  797. return -1;
  798. }
  799. /** Find all the apconns in state AP_CONN_STATE_RENDDESC_WAIT that are
  800. * waiting on <b>query</b>. If there's a working cache entry here with at
  801. * least one intro point, move them to the next state. */
  802. void
  803. rend_client_desc_trynow(const char *query)
  804. {
  805. entry_connection_t *conn;
  806. rend_cache_entry_t *entry;
  807. const rend_data_t *rend_data;
  808. time_t now = time(NULL);
  809. smartlist_t *conns = get_connection_array();
  810. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  811. if (base_conn->type != CONN_TYPE_AP ||
  812. base_conn->state != AP_CONN_STATE_RENDDESC_WAIT ||
  813. base_conn->marked_for_close)
  814. continue;
  815. conn = TO_ENTRY_CONN(base_conn);
  816. rend_data = ENTRY_TO_EDGE_CONN(conn)->rend_data;
  817. if (!rend_data)
  818. continue;
  819. const char *onion_address = rend_data_get_address(rend_data);
  820. if (rend_cmp_service_ids(query, onion_address))
  821. continue;
  822. assert_connection_ok(base_conn, now);
  823. if (rend_cache_lookup_entry(onion_address, -1,
  824. &entry) == 0 &&
  825. rend_client_any_intro_points_usable(entry)) {
  826. /* either this fetch worked, or it failed but there was a
  827. * valid entry from before which we should reuse */
  828. log_info(LD_REND,"Rend desc is usable. Launching circuits.");
  829. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  830. /* restart their timeout values, so they get a fair shake at
  831. * connecting to the hidden service. */
  832. base_conn->timestamp_created = now;
  833. base_conn->timestamp_last_read_allowed = now;
  834. base_conn->timestamp_last_write_allowed = now;
  835. connection_ap_mark_as_pending_circuit(conn);
  836. } else { /* 404, or fetch didn't get that far */
  837. log_notice(LD_REND,"Closing stream for '%s.onion': hidden service is "
  838. "unavailable (try again later).",
  839. safe_str_client(query));
  840. connection_mark_unattached_ap(conn, END_STREAM_REASON_RESOLVEFAILED);
  841. rend_client_note_connection_attempt_ended(rend_data);
  842. }
  843. } SMARTLIST_FOREACH_END(base_conn);
  844. }
  845. /** Clear temporary state used only during an attempt to connect to the
  846. * hidden service with <b>rend_data</b>. Called when a connection attempt
  847. * has ended; it is possible for this to be called multiple times while
  848. * handling an ended connection attempt, and any future changes to this
  849. * function must ensure it remains idempotent. */
  850. void
  851. rend_client_note_connection_attempt_ended(const rend_data_t *rend_data)
  852. {
  853. unsigned int have_onion = 0;
  854. rend_cache_entry_t *cache_entry = NULL;
  855. const char *onion_address = rend_data_get_address(rend_data);
  856. rend_data_v2_t *rend_data_v2 = TO_REND_DATA_V2(rend_data);
  857. if (onion_address[0] != '\0') {
  858. /* Ignore return value; we find an entry, or we don't. */
  859. (void) rend_cache_lookup_entry(onion_address, -1, &cache_entry);
  860. have_onion = 1;
  861. }
  862. /* Clear the timed_out flag on all remaining intro points for this HS. */
  863. if (cache_entry != NULL) {
  864. SMARTLIST_FOREACH(cache_entry->parsed->intro_nodes,
  865. rend_intro_point_t *, ip,
  866. ip->timed_out = 0; );
  867. }
  868. /* Remove the HS's entries in last_hid_serv_requests. */
  869. if (have_onion) {
  870. unsigned int replica;
  871. for (replica = 0; replica < ARRAY_LENGTH(rend_data_v2->descriptor_id);
  872. replica++) {
  873. const char *desc_id = rend_data_v2->descriptor_id[replica];
  874. purge_v2_hidserv_req(desc_id);
  875. }
  876. log_info(LD_REND, "Connection attempt for %s has ended; "
  877. "cleaning up temporary state.",
  878. safe_str_client(onion_address));
  879. } else {
  880. /* We only have an ID for a fetch. Probably used by HSFETCH. */
  881. purge_v2_hidserv_req(rend_data_v2->desc_id_fetch);
  882. }
  883. }
  884. /** Return a newly allocated extend_info_t* for a randomly chosen introduction
  885. * point for the named hidden service. Return NULL if all introduction points
  886. * have been tried and failed.
  887. */
  888. extend_info_t *
  889. rend_client_get_random_intro(const rend_data_t *rend_query)
  890. {
  891. int ret;
  892. extend_info_t *result;
  893. rend_cache_entry_t *entry;
  894. const char *onion_address = rend_data_get_address(rend_query);
  895. ret = rend_cache_lookup_entry(onion_address, -1, &entry);
  896. if (ret < 0 || !rend_client_any_intro_points_usable(entry)) {
  897. log_warn(LD_REND,
  898. "Query '%s' didn't have valid rend desc in cache. Failing.",
  899. safe_str_client(onion_address));
  900. /* XXX: Should we refetch the descriptor here if the IPs are not usable
  901. * anymore ?. */
  902. return NULL;
  903. }
  904. /* See if we can get a node that complies with ExcludeNodes */
  905. if ((result = rend_client_get_random_intro_impl(entry, 1, 1)))
  906. return result;
  907. /* If not, and StrictNodes is not set, see if we can return any old node
  908. */
  909. if (!get_options()->StrictNodes)
  910. return rend_client_get_random_intro_impl(entry, 0, 1);
  911. return NULL;
  912. }
  913. /** As rend_client_get_random_intro, except assume that StrictNodes is set
  914. * iff <b>strict</b> is true. If <b>warnings</b> is false, don't complain
  915. * to the user when we're out of nodes, even if StrictNodes is true.
  916. */
  917. static extend_info_t *
  918. rend_client_get_random_intro_impl(const rend_cache_entry_t *entry,
  919. const int strict,
  920. const int warnings)
  921. {
  922. int i;
  923. rend_intro_point_t *intro;
  924. const or_options_t *options = get_options();
  925. smartlist_t *usable_nodes;
  926. int n_excluded = 0;
  927. /* We'll keep a separate list of the usable nodes. If this becomes empty,
  928. * no nodes are usable. */
  929. usable_nodes = smartlist_new();
  930. smartlist_add_all(usable_nodes, entry->parsed->intro_nodes);
  931. /* Remove the intro points that have timed out during this HS
  932. * connection attempt from our list of usable nodes. */
  933. SMARTLIST_FOREACH(usable_nodes, rend_intro_point_t *, ip,
  934. if (ip->timed_out) {
  935. SMARTLIST_DEL_CURRENT(usable_nodes, ip);
  936. });
  937. again:
  938. if (smartlist_len(usable_nodes) == 0) {
  939. if (n_excluded && get_options()->StrictNodes && warnings) {
  940. /* We only want to warn if StrictNodes is really set. Otherwise
  941. * we're just about to retry anyways.
  942. */
  943. log_warn(LD_REND, "All introduction points for hidden service are "
  944. "at excluded relays, and StrictNodes is set. Skipping.");
  945. }
  946. smartlist_free(usable_nodes);
  947. return NULL;
  948. }
  949. i = crypto_rand_int(smartlist_len(usable_nodes));
  950. intro = smartlist_get(usable_nodes, i);
  951. if (BUG(!intro->extend_info)) {
  952. /* This should never happen, but it isn't fatal, just try another */
  953. smartlist_del(usable_nodes, i);
  954. goto again;
  955. }
  956. /* All version 2 HS descriptors come with a TAP onion key.
  957. * Clients used to try to get the TAP onion key from the consensus, but this
  958. * meant that hidden services could discover which consensus clients have. */
  959. if (!extend_info_supports_tap(intro->extend_info)) {
  960. log_info(LD_REND, "The HS descriptor is missing a TAP onion key for the "
  961. "intro-point relay '%s'; trying another.",
  962. safe_str_client(extend_info_describe(intro->extend_info)));
  963. smartlist_del(usable_nodes, i);
  964. goto again;
  965. }
  966. /* Check if we should refuse to talk to this router. */
  967. if (strict &&
  968. routerset_contains_extendinfo(options->ExcludeNodes,
  969. intro->extend_info)) {
  970. n_excluded++;
  971. smartlist_del(usable_nodes, i);
  972. goto again;
  973. }
  974. smartlist_free(usable_nodes);
  975. return extend_info_dup(intro->extend_info);
  976. }
  977. /** Return true iff any introduction points still listed in <b>entry</b> are
  978. * usable. */
  979. int
  980. rend_client_any_intro_points_usable(const rend_cache_entry_t *entry)
  981. {
  982. extend_info_t *extend_info =
  983. rend_client_get_random_intro_impl(entry, get_options()->StrictNodes, 0);
  984. int rv = (extend_info != NULL);
  985. extend_info_free(extend_info);
  986. return rv;
  987. }
  988. /** Client-side authorizations for hidden services; map of onion address to
  989. * rend_service_authorization_t*. */
  990. static strmap_t *auth_hid_servs = NULL;
  991. /** Look up the client-side authorization for the hidden service with
  992. * <b>onion_address</b>. Return NULL if no authorization is available for
  993. * that address. */
  994. rend_service_authorization_t*
  995. rend_client_lookup_service_authorization(const char *onion_address)
  996. {
  997. tor_assert(onion_address);
  998. if (!auth_hid_servs) return NULL;
  999. return strmap_get(auth_hid_servs, onion_address);
  1000. }
  1001. #define rend_service_authorization_free(val) \
  1002. FREE_AND_NULL(rend_service_authorization_t, \
  1003. rend_service_authorization_free_, (val))
  1004. /** Helper: Free storage held by rend_service_authorization_t. */
  1005. static void
  1006. rend_service_authorization_free_(rend_service_authorization_t *auth)
  1007. {
  1008. tor_free(auth);
  1009. }
  1010. /** Helper for strmap_free. */
  1011. static void
  1012. rend_service_authorization_free_void(void *service_auth)
  1013. {
  1014. rend_service_authorization_free_(service_auth);
  1015. }
  1016. /** Release all the storage held in auth_hid_servs.
  1017. */
  1018. void
  1019. rend_service_authorization_free_all(void)
  1020. {
  1021. if (!auth_hid_servs) {
  1022. return;
  1023. }
  1024. strmap_free(auth_hid_servs, rend_service_authorization_free_void);
  1025. auth_hid_servs = NULL;
  1026. }
  1027. /** Parse <b>config_line</b> as a client-side authorization for a hidden
  1028. * service and add it to the local map of hidden service authorizations.
  1029. * Return 0 for success and -1 for failure. */
  1030. int
  1031. rend_parse_service_authorization(const or_options_t *options,
  1032. int validate_only)
  1033. {
  1034. config_line_t *line;
  1035. int res = -1;
  1036. strmap_t *parsed = strmap_new();
  1037. smartlist_t *sl = smartlist_new();
  1038. rend_service_authorization_t *auth = NULL;
  1039. char *err_msg = NULL;
  1040. for (line = options->HidServAuth; line; line = line->next) {
  1041. char *onion_address, *descriptor_cookie;
  1042. auth = NULL;
  1043. SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
  1044. smartlist_clear(sl);
  1045. smartlist_split_string(sl, line->value, " ",
  1046. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
  1047. if (smartlist_len(sl) < 2) {
  1048. log_warn(LD_CONFIG, "Configuration line does not consist of "
  1049. "\"onion-address authorization-cookie [service-name]\": "
  1050. "'%s'", line->value);
  1051. goto err;
  1052. }
  1053. auth = tor_malloc_zero(sizeof(rend_service_authorization_t));
  1054. /* Parse onion address. */
  1055. onion_address = smartlist_get(sl, 0);
  1056. if (strlen(onion_address) != REND_SERVICE_ADDRESS_LEN ||
  1057. strcmpend(onion_address, ".onion")) {
  1058. log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
  1059. onion_address);
  1060. goto err;
  1061. }
  1062. strlcpy(auth->onion_address, onion_address, REND_SERVICE_ID_LEN_BASE32+1);
  1063. if (!rend_valid_v2_service_id(auth->onion_address)) {
  1064. log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
  1065. onion_address);
  1066. goto err;
  1067. }
  1068. /* Parse descriptor cookie. */
  1069. descriptor_cookie = smartlist_get(sl, 1);
  1070. if (rend_auth_decode_cookie(descriptor_cookie, auth->descriptor_cookie,
  1071. &auth->auth_type, &err_msg) < 0) {
  1072. tor_assert(err_msg);
  1073. log_warn(LD_CONFIG, "%s", err_msg);
  1074. tor_free(err_msg);
  1075. goto err;
  1076. }
  1077. if (strmap_get(parsed, auth->onion_address)) {
  1078. log_warn(LD_CONFIG, "Duplicate authorization for the same hidden "
  1079. "service.");
  1080. goto err;
  1081. }
  1082. strmap_set(parsed, auth->onion_address, auth);
  1083. auth = NULL;
  1084. }
  1085. res = 0;
  1086. goto done;
  1087. err:
  1088. res = -1;
  1089. done:
  1090. rend_service_authorization_free(auth);
  1091. SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
  1092. smartlist_free(sl);
  1093. if (!validate_only && res == 0) {
  1094. rend_service_authorization_free_all();
  1095. auth_hid_servs = parsed;
  1096. } else {
  1097. strmap_free(parsed, rend_service_authorization_free_void);
  1098. }
  1099. return res;
  1100. }
  1101. /* Can Tor client code make direct (non-anonymous) connections to introduction
  1102. * or rendezvous points?
  1103. * Returns true if tor was compiled with NON_ANONYMOUS_MODE_ENABLED, and is
  1104. * configured in Tor2web mode. */
  1105. int
  1106. rend_client_allow_non_anonymous_connection(const or_options_t *options)
  1107. {
  1108. /* Tor2web support needs to be compiled in to a tor binary. */
  1109. #ifdef NON_ANONYMOUS_MODE_ENABLED
  1110. /* Tor2web */
  1111. return options->Tor2webMode ? 1 : 0;
  1112. #else
  1113. (void)options;
  1114. return 0;
  1115. #endif /* defined(NON_ANONYMOUS_MODE_ENABLED) */
  1116. }
  1117. /* At compile-time, was non-anonymous mode enabled via
  1118. * NON_ANONYMOUS_MODE_ENABLED ? */
  1119. int
  1120. rend_client_non_anonymous_mode_enabled(const or_options_t *options)
  1121. {
  1122. (void)options;
  1123. /* Tor2web support needs to be compiled in to a tor binary. */
  1124. #ifdef NON_ANONYMOUS_MODE_ENABLED
  1125. /* Tor2web */
  1126. return 1;
  1127. #else
  1128. return 0;
  1129. #endif /* defined(NON_ANONYMOUS_MODE_ENABLED) */
  1130. }