rendclient.c 48 KB

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