rendclient.c 52 KB

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