rendclient.c 50 KB

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