rendclient.c 52 KB

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