rendclient.c 51 KB

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