rendclient.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2011, 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 "relay.h"
  18. #include "rendclient.h"
  19. #include "rendcommon.h"
  20. #include "rephist.h"
  21. #include "routerlist.h"
  22. static extend_info_t *rend_client_get_random_intro_impl(
  23. const rend_cache_entry_t *rend_query,
  24. const int strict, const int warnings);
  25. /** Called when we've established a circuit to an introduction point:
  26. * send the introduction request. */
  27. void
  28. rend_client_introcirc_has_opened(origin_circuit_t *circ)
  29. {
  30. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  31. tor_assert(circ->cpath);
  32. log_info(LD_REND,"introcirc is open");
  33. connection_ap_attach_pending();
  34. }
  35. /** Send the establish-rendezvous cell along a rendezvous circuit. if
  36. * it fails, mark the circ for close and return -1. else return 0.
  37. */
  38. static int
  39. rend_client_send_establish_rendezvous(origin_circuit_t *circ)
  40. {
  41. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
  42. tor_assert(circ->rend_data);
  43. log_info(LD_REND, "Sending an ESTABLISH_RENDEZVOUS cell");
  44. if (crypto_rand(circ->rend_data->rend_cookie, REND_COOKIE_LEN) < 0) {
  45. log_warn(LD_BUG, "Internal error: Couldn't produce random cookie.");
  46. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
  47. return -1;
  48. }
  49. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  50. RELAY_COMMAND_ESTABLISH_RENDEZVOUS,
  51. circ->rend_data->rend_cookie,
  52. REND_COOKIE_LEN,
  53. circ->cpath->prev)<0) {
  54. /* circ is already marked for close */
  55. log_warn(LD_GENERAL, "Couldn't send ESTABLISH_RENDEZVOUS cell");
  56. return -1;
  57. }
  58. return 0;
  59. }
  60. /** Called when we're trying to connect an ap conn; sends an INTRODUCE1 cell
  61. * down introcirc if possible.
  62. */
  63. int
  64. rend_client_send_introduction(origin_circuit_t *introcirc,
  65. origin_circuit_t *rendcirc)
  66. {
  67. size_t payload_len;
  68. int r, v3_shift = 0;
  69. char payload[RELAY_PAYLOAD_SIZE];
  70. char tmp[RELAY_PAYLOAD_SIZE];
  71. rend_cache_entry_t *entry;
  72. crypt_path_t *cpath;
  73. off_t dh_offset;
  74. crypto_pk_env_t *intro_key = NULL;
  75. tor_assert(introcirc->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  76. tor_assert(rendcirc->_base.purpose == CIRCUIT_PURPOSE_C_REND_READY);
  77. tor_assert(introcirc->rend_data);
  78. tor_assert(rendcirc->rend_data);
  79. tor_assert(!rend_cmp_service_ids(introcirc->rend_data->onion_address,
  80. rendcirc->rend_data->onion_address));
  81. if (rend_cache_lookup_entry(introcirc->rend_data->onion_address, -1,
  82. &entry) < 1) {
  83. log_warn(LD_REND,
  84. "query %s didn't have valid rend desc in cache. Failing.",
  85. escaped_safe_str_client(introcirc->rend_data->onion_address));
  86. goto err;
  87. }
  88. /* first 20 bytes of payload are the hash of the intro key */
  89. intro_key = NULL;
  90. SMARTLIST_FOREACH(entry->parsed->intro_nodes, rend_intro_point_t *,
  91. intro, {
  92. if (!memcmp(introcirc->build_state->chosen_exit->identity_digest,
  93. intro->extend_info->identity_digest, DIGEST_LEN)) {
  94. intro_key = intro->intro_key;
  95. break;
  96. }
  97. });
  98. if (!intro_key) {
  99. log_info(LD_REND, "Our introduction point knowledge changed in "
  100. "mid-connect! Could not find intro key; we only have a "
  101. "v2 rend desc with %d intro points. Giving up.",
  102. smartlist_len(entry->parsed->intro_nodes));
  103. goto err;
  104. }
  105. if (crypto_pk_get_digest(intro_key, payload)<0) {
  106. log_warn(LD_BUG, "Internal error: couldn't hash public key.");
  107. goto err;
  108. }
  109. /* Initialize the pending_final_cpath and start the DH handshake. */
  110. cpath = rendcirc->build_state->pending_final_cpath;
  111. if (!cpath) {
  112. cpath = rendcirc->build_state->pending_final_cpath =
  113. tor_malloc_zero(sizeof(crypt_path_t));
  114. cpath->magic = CRYPT_PATH_MAGIC;
  115. if (!(cpath->dh_handshake_state = crypto_dh_new(DH_TYPE_REND))) {
  116. log_warn(LD_BUG, "Internal error: couldn't allocate DH.");
  117. goto err;
  118. }
  119. if (crypto_dh_generate_public(cpath->dh_handshake_state)<0) {
  120. log_warn(LD_BUG, "Internal error: couldn't generate g^x.");
  121. goto err;
  122. }
  123. }
  124. /* If version is 3, write (optional) auth data and timestamp. */
  125. if (entry->parsed->protocols & (1<<3)) {
  126. tmp[0] = 3; /* version 3 of the cell format */
  127. tmp[1] = (uint8_t)introcirc->rend_data->auth_type; /* auth type, if any */
  128. v3_shift = 1;
  129. if (introcirc->rend_data->auth_type != REND_NO_AUTH) {
  130. set_uint16(tmp+2, htons(REND_DESC_COOKIE_LEN));
  131. memcpy(tmp+4, introcirc->rend_data->descriptor_cookie,
  132. REND_DESC_COOKIE_LEN);
  133. v3_shift += 2+REND_DESC_COOKIE_LEN;
  134. }
  135. set_uint32(tmp+v3_shift+1, htonl((uint32_t)time(NULL)));
  136. v3_shift += 4;
  137. } /* if version 2 only write version number */
  138. else if (entry->parsed->protocols & (1<<2)) {
  139. tmp[0] = 2; /* version 2 of the cell format */
  140. }
  141. /* write the remaining items into tmp */
  142. if (entry->parsed->protocols & (1<<3) || entry->parsed->protocols & (1<<2)) {
  143. /* version 2 format */
  144. extend_info_t *extend_info = rendcirc->build_state->chosen_exit;
  145. int klen;
  146. /* nul pads */
  147. set_uint32(tmp+v3_shift+1, tor_addr_to_ipv4h(&extend_info->addr));
  148. set_uint16(tmp+v3_shift+5, htons(extend_info->port));
  149. memcpy(tmp+v3_shift+7, extend_info->identity_digest, DIGEST_LEN);
  150. klen = crypto_pk_asn1_encode(extend_info->onion_key,
  151. tmp+v3_shift+7+DIGEST_LEN+2,
  152. sizeof(tmp)-(v3_shift+7+DIGEST_LEN+2));
  153. set_uint16(tmp+v3_shift+7+DIGEST_LEN, htons(klen));
  154. memcpy(tmp+v3_shift+7+DIGEST_LEN+2+klen, rendcirc->rend_data->rend_cookie,
  155. REND_COOKIE_LEN);
  156. dh_offset = v3_shift+7+DIGEST_LEN+2+klen+REND_COOKIE_LEN;
  157. } else {
  158. /* Version 0. */
  159. strncpy(tmp, rendcirc->build_state->chosen_exit->nickname,
  160. (MAX_NICKNAME_LEN+1)); /* nul pads */
  161. memcpy(tmp+MAX_NICKNAME_LEN+1, rendcirc->rend_data->rend_cookie,
  162. REND_COOKIE_LEN);
  163. dh_offset = MAX_NICKNAME_LEN+1+REND_COOKIE_LEN;
  164. }
  165. if (crypto_dh_get_public(cpath->dh_handshake_state, tmp+dh_offset,
  166. DH_KEY_LEN)<0) {
  167. log_warn(LD_BUG, "Internal error: couldn't extract g^x.");
  168. goto err;
  169. }
  170. note_crypto_pk_op(REND_CLIENT);
  171. /*XXX maybe give crypto_pk_public_hybrid_encrypt a max_len arg,
  172. * to avoid buffer overflows? */
  173. r = crypto_pk_public_hybrid_encrypt(intro_key, payload+DIGEST_LEN,
  174. sizeof(payload)-DIGEST_LEN,
  175. tmp,
  176. (int)(dh_offset+DH_KEY_LEN),
  177. PK_PKCS1_OAEP_PADDING, 0);
  178. if (r<0) {
  179. log_warn(LD_BUG,"Internal error: hybrid pk encrypt failed.");
  180. goto err;
  181. }
  182. payload_len = DIGEST_LEN + r;
  183. tor_assert(payload_len <= RELAY_PAYLOAD_SIZE); /* we overran something */
  184. log_info(LD_REND, "Sending an INTRODUCE1 cell");
  185. if (relay_send_command_from_edge(0, TO_CIRCUIT(introcirc),
  186. RELAY_COMMAND_INTRODUCE1,
  187. payload, payload_len,
  188. introcirc->cpath->prev)<0) {
  189. /* introcirc is already marked for close. leave rendcirc alone. */
  190. log_warn(LD_BUG, "Couldn't send INTRODUCE1 cell");
  191. return -1;
  192. }
  193. /* Now, we wait for an ACK or NAK on this circuit. */
  194. introcirc->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT;
  195. return 0;
  196. err:
  197. circuit_mark_for_close(TO_CIRCUIT(introcirc), END_CIRC_REASON_INTERNAL);
  198. circuit_mark_for_close(TO_CIRCUIT(rendcirc), END_CIRC_REASON_INTERNAL);
  199. return -1;
  200. }
  201. /** Called when a rendezvous circuit is open; sends a establish
  202. * rendezvous circuit as appropriate. */
  203. void
  204. rend_client_rendcirc_has_opened(origin_circuit_t *circ)
  205. {
  206. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
  207. log_info(LD_REND,"rendcirc is open");
  208. /* generate a rendezvous cookie, store it in circ */
  209. if (rend_client_send_establish_rendezvous(circ) < 0) {
  210. return;
  211. }
  212. }
  213. /** Called when get an ACK or a NAK for a REND_INTRODUCE1 cell.
  214. */
  215. int
  216. rend_client_introduction_acked(origin_circuit_t *circ,
  217. const uint8_t *request, size_t request_len)
  218. {
  219. origin_circuit_t *rendcirc;
  220. (void) request; // XXXX Use this.
  221. if (circ->_base.purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
  222. log_warn(LD_PROTOCOL,
  223. "Received REND_INTRODUCE_ACK on unexpected circuit %d.",
  224. circ->_base.n_circ_id);
  225. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  226. return -1;
  227. }
  228. tor_assert(circ->build_state->chosen_exit);
  229. tor_assert(circ->rend_data);
  230. if (request_len == 0) {
  231. /* It's an ACK; the introduction point relayed our introduction request. */
  232. /* Locate the rend circ which is waiting to hear about this ack,
  233. * and tell it.
  234. */
  235. log_info(LD_REND,"Received ack. Telling rend circ...");
  236. rendcirc = circuit_get_by_rend_query_and_purpose(
  237. circ->rend_data->onion_address, CIRCUIT_PURPOSE_C_REND_READY);
  238. if (rendcirc) { /* remember the ack */
  239. rendcirc->_base.purpose = CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED;
  240. } else {
  241. log_info(LD_REND,"...Found no rend circ. Dropping on the floor.");
  242. }
  243. /* close the circuit: we won't need it anymore. */
  244. circ->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCE_ACKED;
  245. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  246. } else {
  247. /* It's a NAK; the introduction point didn't relay our request. */
  248. circ->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
  249. /* Remove this intro point from the set of viable introduction
  250. * points. If any remain, extend to a new one and try again.
  251. * If none remain, refetch the service descriptor.
  252. */
  253. if (rend_client_remove_intro_point(circ->build_state->chosen_exit,
  254. circ->rend_data) > 0) {
  255. /* There are introduction points left. Re-extend the circuit to
  256. * another intro point and try again. */
  257. extend_info_t *extend_info;
  258. int result;
  259. extend_info = rend_client_get_random_intro(circ->rend_data);
  260. if (!extend_info) {
  261. log_warn(LD_REND, "No introduction points left for %s. Closing.",
  262. escaped_safe_str_client(circ->rend_data->onion_address));
  263. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
  264. return -1;
  265. }
  266. if (circ->remaining_relay_early_cells) {
  267. log_info(LD_REND,
  268. "Got nack for %s from %s. Re-extending circ %d, "
  269. "this time to %s.",
  270. escaped_safe_str_client(circ->rend_data->onion_address),
  271. circ->build_state->chosen_exit->nickname,
  272. circ->_base.n_circ_id, extend_info->nickname);
  273. result = circuit_extend_to_new_exit(circ, extend_info);
  274. } else {
  275. log_info(LD_REND,
  276. "Got nack for %s from %s. Building a new introduction "
  277. "circuit, this time to %s.",
  278. escaped_safe_str_client(circ->rend_data->onion_address),
  279. circ->build_state->chosen_exit->nickname,
  280. extend_info->nickname);
  281. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  282. if (!circuit_launch_by_extend_info(CIRCUIT_PURPOSE_C_INTRODUCING,
  283. extend_info,
  284. CIRCLAUNCH_IS_INTERNAL)) {
  285. log_warn(LD_REND, "Building introduction circuit failed.");
  286. result = -1;
  287. } else {
  288. result = 0;
  289. }
  290. }
  291. extend_info_free(extend_info);
  292. return result;
  293. }
  294. }
  295. return 0;
  296. }
  297. /** The period for which a hidden service directory cannot be queried for
  298. * the same descriptor ID again. */
  299. #define REND_HID_SERV_DIR_REQUERY_PERIOD (15 * 60)
  300. /** Contains the last request times to hidden service directories for
  301. * certain queries; keys are strings consisting of base32-encoded
  302. * hidden service directory identities and base32-encoded descriptor IDs;
  303. * values are pointers to timestamps of the last requests. */
  304. static strmap_t *last_hid_serv_requests = NULL;
  305. /** Look up the last request time to hidden service directory <b>hs_dir</b>
  306. * for descriptor ID <b>desc_id_base32</b>. If <b>set</b> is non-zero,
  307. * assign the current time <b>now</b> and return that. Otherwise, return
  308. * the most recent request time, or 0 if no such request has been sent
  309. * before. */
  310. static time_t
  311. lookup_last_hid_serv_request(routerstatus_t *hs_dir,
  312. const char *desc_id_base32, time_t now, int set)
  313. {
  314. char hsdir_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  315. char hsdir_desc_comb_id[2 * REND_DESC_ID_V2_LEN_BASE32 + 1];
  316. time_t *last_request_ptr;
  317. base32_encode(hsdir_id_base32, sizeof(hsdir_id_base32),
  318. hs_dir->identity_digest, DIGEST_LEN);
  319. tor_snprintf(hsdir_desc_comb_id, sizeof(hsdir_desc_comb_id), "%s%s",
  320. hsdir_id_base32, desc_id_base32);
  321. if (set) {
  322. time_t *oldptr;
  323. last_request_ptr = tor_malloc_zero(sizeof(time_t));
  324. *last_request_ptr = now;
  325. oldptr = strmap_set(last_hid_serv_requests, hsdir_desc_comb_id,
  326. last_request_ptr);
  327. tor_free(oldptr);
  328. } else
  329. last_request_ptr = strmap_get_lc(last_hid_serv_requests,
  330. hsdir_desc_comb_id);
  331. return (last_request_ptr) ? *last_request_ptr : 0;
  332. }
  333. /** Clean the history of request times to hidden service directories, so that
  334. * it does not contain requests older than REND_HID_SERV_DIR_REQUERY_PERIOD
  335. * seconds any more. */
  336. static void
  337. directory_clean_last_hid_serv_requests(void)
  338. {
  339. strmap_iter_t *iter;
  340. time_t cutoff = time(NULL) - REND_HID_SERV_DIR_REQUERY_PERIOD;
  341. if (!last_hid_serv_requests)
  342. last_hid_serv_requests = strmap_new();
  343. for (iter = strmap_iter_init(last_hid_serv_requests);
  344. !strmap_iter_done(iter); ) {
  345. const char *key;
  346. void *val;
  347. time_t *ent;
  348. strmap_iter_get(iter, &key, &val);
  349. ent = (time_t *) val;
  350. if (*ent < cutoff) {
  351. iter = strmap_iter_next_rmv(last_hid_serv_requests, iter);
  352. tor_free(ent);
  353. } else {
  354. iter = strmap_iter_next(last_hid_serv_requests, iter);
  355. }
  356. }
  357. }
  358. /** Determine the responsible hidden service directories for <b>desc_id</b>
  359. * and fetch the descriptor belonging to that ID from one of them. Only
  360. * send a request to hidden service directories that we did not try within
  361. * the last REND_HID_SERV_DIR_REQUERY_PERIOD seconds; on success, return 1,
  362. * in the case that no hidden service directory is left to ask for the
  363. * descriptor, return 0, and in case of a failure -1. <b>query</b> is only
  364. * passed for pretty log statements. */
  365. static int
  366. directory_get_from_hs_dir(const char *desc_id, const rend_data_t *rend_query)
  367. {
  368. smartlist_t *responsible_dirs = smartlist_create();
  369. routerstatus_t *hs_dir;
  370. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  371. time_t now = time(NULL);
  372. char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
  373. tor_assert(desc_id);
  374. tor_assert(rend_query);
  375. /* Determine responsible dirs. Even if we can't get all we want,
  376. * work with the ones we have. If it's empty, we'll notice below. */
  377. hid_serv_get_responsible_directories(responsible_dirs, desc_id);
  378. base32_encode(desc_id_base32, sizeof(desc_id_base32),
  379. desc_id, DIGEST_LEN);
  380. /* Only select those hidden service directories to which we did not send
  381. * a request recently and for which we have a router descriptor here. */
  382. directory_clean_last_hid_serv_requests(); /* Clean request history first. */
  383. SMARTLIST_FOREACH(responsible_dirs, routerstatus_t *, dir, {
  384. if (lookup_last_hid_serv_request(dir, desc_id_base32, 0, 0) +
  385. REND_HID_SERV_DIR_REQUERY_PERIOD >= now ||
  386. !router_get_by_digest(dir->identity_digest))
  387. SMARTLIST_DEL_CURRENT(responsible_dirs, dir);
  388. });
  389. hs_dir = smartlist_choose(responsible_dirs);
  390. smartlist_free(responsible_dirs);
  391. if (!hs_dir) {
  392. log_info(LD_REND, "Could not pick one of the responsible hidden "
  393. "service directories, because we requested them all "
  394. "recently without success.");
  395. return 0;
  396. }
  397. /* Remember, that we are requesting a descriptor from this hidden service
  398. * directory now. */
  399. lookup_last_hid_serv_request(hs_dir, desc_id_base32, now, 1);
  400. /* Encode descriptor cookie for logging purposes. */
  401. if (rend_query->auth_type != REND_NO_AUTH) {
  402. if (base64_encode(descriptor_cookie_base64,
  403. sizeof(descriptor_cookie_base64),
  404. rend_query->descriptor_cookie, REND_DESC_COOKIE_LEN)<0) {
  405. log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
  406. return 0;
  407. }
  408. /* Remove == signs and newline. */
  409. descriptor_cookie_base64[strlen(descriptor_cookie_base64)-3] = '\0';
  410. } else {
  411. strlcpy(descriptor_cookie_base64, "(none)",
  412. sizeof(descriptor_cookie_base64));
  413. }
  414. /* Send fetch request. (Pass query and possibly descriptor cookie so that
  415. * they can be written to the directory connection and be referred to when
  416. * the response arrives. */
  417. directory_initiate_command_routerstatus_rend(hs_dir,
  418. DIR_PURPOSE_FETCH_RENDDESC_V2,
  419. ROUTER_PURPOSE_GENERAL,
  420. 1, desc_id_base32, NULL, 0, 0,
  421. rend_query);
  422. log_info(LD_REND, "Sending fetch request for v2 descriptor for "
  423. "service '%s' with descriptor ID '%s', auth type %d, "
  424. "and descriptor cookie '%s' to hidden service "
  425. "directory '%s' on port %d.",
  426. rend_query->onion_address, desc_id_base32,
  427. rend_query->auth_type,
  428. (rend_query->auth_type == REND_NO_AUTH ? "[none]" :
  429. escaped_safe_str_client(descriptor_cookie_base64)),
  430. hs_dir->nickname, hs_dir->dir_port);
  431. return 1;
  432. }
  433. /** Unless we already have a descriptor for <b>rend_query</b> with at least
  434. * one (possibly) working introduction point in it, start a connection to a
  435. * hidden service directory to fetch a v2 rendezvous service descriptor. */
  436. void
  437. rend_client_refetch_v2_renddesc(const rend_data_t *rend_query)
  438. {
  439. char descriptor_id[DIGEST_LEN];
  440. int replicas_left_to_try[REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS];
  441. int i, tries_left;
  442. rend_cache_entry_t *e = NULL;
  443. tor_assert(rend_query);
  444. /* Are we configured to fetch descriptors? */
  445. if (!get_options()->FetchHidServDescriptors) {
  446. log_warn(LD_REND, "We received an onion address for a v2 rendezvous "
  447. "service descriptor, but are not fetching service descriptors.");
  448. return;
  449. }
  450. /* Before fetching, check if we already have the descriptor here. */
  451. if (rend_cache_lookup_entry(rend_query->onion_address, -1, &e) > 0) {
  452. log_info(LD_REND, "We would fetch a v2 rendezvous descriptor, but we "
  453. "already have that descriptor here. Not fetching.");
  454. return;
  455. }
  456. log_debug(LD_REND, "Fetching v2 rendezvous descriptor for service %s",
  457. safe_str_client(rend_query->onion_address));
  458. /* Randomly iterate over the replicas until a descriptor can be fetched
  459. * from one of the consecutive nodes, or no options are left. */
  460. tries_left = REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS;
  461. for (i = 0; i < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; i++)
  462. replicas_left_to_try[i] = i;
  463. while (tries_left > 0) {
  464. int rand = crypto_rand_int(tries_left);
  465. int chosen_replica = replicas_left_to_try[rand];
  466. replicas_left_to_try[rand] = replicas_left_to_try[--tries_left];
  467. if (rend_compute_v2_desc_id(descriptor_id, rend_query->onion_address,
  468. rend_query->auth_type == REND_STEALTH_AUTH ?
  469. rend_query->descriptor_cookie : NULL,
  470. time(NULL), chosen_replica) < 0) {
  471. log_warn(LD_REND, "Internal error: Computing v2 rendezvous "
  472. "descriptor ID did not succeed.");
  473. return;
  474. }
  475. if (directory_get_from_hs_dir(descriptor_id, rend_query) != 0)
  476. return; /* either success or failure, but we're done */
  477. }
  478. /* If we come here, there are no hidden service directories left. */
  479. log_info(LD_REND, "Could not pick one of the responsible hidden "
  480. "service directories to fetch descriptors, because "
  481. "we already tried them all unsuccessfully.");
  482. /* Close pending connections. */
  483. rend_client_desc_trynow(rend_query->onion_address);
  484. return;
  485. }
  486. /** Remove failed_intro from ent. If ent now has no intro points, or
  487. * service is unrecognized, then launch a new renddesc fetch.
  488. *
  489. * Return -1 if error, 0 if no intro points remain or service
  490. * unrecognized, 1 if recognized and some intro points remain.
  491. */
  492. int
  493. rend_client_remove_intro_point(extend_info_t *failed_intro,
  494. const rend_data_t *rend_query)
  495. {
  496. int i, r;
  497. rend_cache_entry_t *ent;
  498. connection_t *conn;
  499. r = rend_cache_lookup_entry(rend_query->onion_address, -1, &ent);
  500. if (r<0) {
  501. log_warn(LD_BUG, "Malformed service ID %s.",
  502. escaped_safe_str_client(rend_query->onion_address));
  503. return -1;
  504. }
  505. if (r==0) {
  506. log_info(LD_REND, "Unknown service %s. Re-fetching descriptor.",
  507. escaped_safe_str_client(rend_query->onion_address));
  508. rend_client_refetch_v2_renddesc(rend_query);
  509. return 0;
  510. }
  511. for (i = 0; i < smartlist_len(ent->parsed->intro_nodes); i++) {
  512. rend_intro_point_t *intro = smartlist_get(ent->parsed->intro_nodes, i);
  513. if (!memcmp(failed_intro->identity_digest,
  514. intro->extend_info->identity_digest, DIGEST_LEN)) {
  515. rend_intro_point_free(intro);
  516. smartlist_del(ent->parsed->intro_nodes, i);
  517. break;
  518. }
  519. }
  520. if (! rend_client_any_intro_points_usable(ent)) {
  521. log_info(LD_REND,
  522. "No more intro points remain for %s. Re-fetching descriptor.",
  523. escaped_safe_str_client(rend_query->onion_address));
  524. rend_client_refetch_v2_renddesc(rend_query);
  525. /* move all pending streams back to renddesc_wait */
  526. while ((conn = connection_get_by_type_state_rendquery(CONN_TYPE_AP,
  527. AP_CONN_STATE_CIRCUIT_WAIT,
  528. rend_query->onion_address))) {
  529. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  530. }
  531. return 0;
  532. }
  533. log_info(LD_REND,"%d options left for %s.",
  534. smartlist_len(ent->parsed->intro_nodes),
  535. escaped_safe_str_client(rend_query->onion_address));
  536. return 1;
  537. }
  538. /** Called when we receive a RENDEZVOUS_ESTABLISHED cell; changes the state of
  539. * the circuit to C_REND_READY.
  540. */
  541. int
  542. rend_client_rendezvous_acked(origin_circuit_t *circ, const uint8_t *request,
  543. size_t request_len)
  544. {
  545. (void) request;
  546. (void) request_len;
  547. /* we just got an ack for our establish-rendezvous. switch purposes. */
  548. if (circ->_base.purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND) {
  549. log_warn(LD_PROTOCOL,"Got a rendezvous ack when we weren't expecting one. "
  550. "Closing circ.");
  551. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  552. return -1;
  553. }
  554. log_info(LD_REND,"Got rendezvous ack. This circuit is now ready for "
  555. "rendezvous.");
  556. circ->_base.purpose = CIRCUIT_PURPOSE_C_REND_READY;
  557. /* XXXX023 This is a pretty brute-force approach. It'd be better to
  558. * attach only the connections that are waiting on this circuit, rather
  559. * than trying to attach them all. See comments bug 743. */
  560. /* If we already have the introduction circuit built, make sure we send
  561. * the INTRODUCE cell _now_ */
  562. connection_ap_attach_pending();
  563. return 0;
  564. }
  565. /** Bob sent us a rendezvous cell; join the circuits. */
  566. int
  567. rend_client_receive_rendezvous(origin_circuit_t *circ, const uint8_t *request,
  568. size_t request_len)
  569. {
  570. crypt_path_t *hop;
  571. char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN];
  572. if ((circ->_base.purpose != CIRCUIT_PURPOSE_C_REND_READY &&
  573. circ->_base.purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)
  574. || !circ->build_state->pending_final_cpath) {
  575. log_warn(LD_PROTOCOL,"Got rendezvous2 cell from hidden service, but not "
  576. "expecting it. Closing.");
  577. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  578. return -1;
  579. }
  580. if (request_len != DH_KEY_LEN+DIGEST_LEN) {
  581. log_warn(LD_PROTOCOL,"Incorrect length (%d) on RENDEZVOUS2 cell.",
  582. (int)request_len);
  583. goto err;
  584. }
  585. log_info(LD_REND,"Got RENDEZVOUS2 cell from hidden service.");
  586. /* first DH_KEY_LEN bytes are g^y from bob. Finish the dh handshake...*/
  587. tor_assert(circ->build_state);
  588. tor_assert(circ->build_state->pending_final_cpath);
  589. hop = circ->build_state->pending_final_cpath;
  590. tor_assert(hop->dh_handshake_state);
  591. if (crypto_dh_compute_secret(LOG_PROTOCOL_WARN,
  592. hop->dh_handshake_state, (char*)request,
  593. DH_KEY_LEN,
  594. keys, DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
  595. log_warn(LD_GENERAL, "Couldn't complete DH handshake.");
  596. goto err;
  597. }
  598. /* ... and set up cpath. */
  599. if (circuit_init_cpath_crypto(hop, keys+DIGEST_LEN, 0)<0)
  600. goto err;
  601. /* Check whether the digest is right... */
  602. if (memcmp(keys, request+DH_KEY_LEN, DIGEST_LEN)) {
  603. log_warn(LD_PROTOCOL, "Incorrect digest of key material.");
  604. goto err;
  605. }
  606. crypto_dh_free(hop->dh_handshake_state);
  607. hop->dh_handshake_state = NULL;
  608. /* All is well. Extend the circuit. */
  609. circ->_base.purpose = CIRCUIT_PURPOSE_C_REND_JOINED;
  610. hop->state = CPATH_STATE_OPEN;
  611. /* set the windows to default. these are the windows
  612. * that alice thinks bob has.
  613. */
  614. hop->package_window = circuit_initial_package_window();
  615. hop->deliver_window = CIRCWINDOW_START;
  616. onion_append_to_cpath(&circ->cpath, hop);
  617. circ->build_state->pending_final_cpath = NULL; /* prevent double-free */
  618. /* XXXX023 This is a pretty brute-force approach. It'd be better to
  619. * attach only the connections that are waiting on this circuit, rather
  620. * than trying to attach them all. See comments bug 743. */
  621. connection_ap_attach_pending();
  622. memset(keys, 0, sizeof(keys));
  623. return 0;
  624. err:
  625. memset(keys, 0, sizeof(keys));
  626. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  627. return -1;
  628. }
  629. /** Find all the apconns in state AP_CONN_STATE_RENDDESC_WAIT that are
  630. * waiting on <b>query</b>. If there's a working cache entry here with at
  631. * least one intro point, move them to the next state. */
  632. void
  633. rend_client_desc_trynow(const char *query)
  634. {
  635. edge_connection_t *conn;
  636. rend_cache_entry_t *entry;
  637. time_t now = time(NULL);
  638. smartlist_t *conns = get_connection_array();
  639. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, _conn) {
  640. if (_conn->type != CONN_TYPE_AP ||
  641. _conn->state != AP_CONN_STATE_RENDDESC_WAIT ||
  642. _conn->marked_for_close)
  643. continue;
  644. conn = TO_EDGE_CONN(_conn);
  645. if (!conn->rend_data)
  646. continue;
  647. if (rend_cmp_service_ids(query, conn->rend_data->onion_address))
  648. continue;
  649. assert_connection_ok(TO_CONN(conn), now);
  650. if (rend_cache_lookup_entry(conn->rend_data->onion_address, -1,
  651. &entry) == 1 &&
  652. rend_client_any_intro_points_usable(entry)) {
  653. /* either this fetch worked, or it failed but there was a
  654. * valid entry from before which we should reuse */
  655. log_info(LD_REND,"Rend desc is usable. Launching circuits.");
  656. conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
  657. /* restart their timeout values, so they get a fair shake at
  658. * connecting to the hidden service. */
  659. conn->_base.timestamp_created = now;
  660. conn->_base.timestamp_lastread = now;
  661. conn->_base.timestamp_lastwritten = now;
  662. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  663. /* it will never work */
  664. log_warn(LD_REND,"Rendezvous attempt failed. Closing.");
  665. if (!conn->_base.marked_for_close)
  666. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  667. }
  668. } else { /* 404, or fetch didn't get that far */
  669. log_notice(LD_REND,"Closing stream for '%s.onion': hidden service is "
  670. "unavailable (try again later).",
  671. safe_str_client(query));
  672. connection_mark_unattached_ap(conn, END_STREAM_REASON_RESOLVEFAILED);
  673. }
  674. } SMARTLIST_FOREACH_END(_conn);
  675. }
  676. /** Return a newly allocated extend_info_t* for a randomly chosen introduction
  677. * point for the named hidden service. Return NULL if all introduction points
  678. * have been tried and failed.
  679. */
  680. extend_info_t *
  681. rend_client_get_random_intro(const rend_data_t *rend_query)
  682. {
  683. extend_info_t *result;
  684. rend_cache_entry_t *entry;
  685. if (rend_cache_lookup_entry(rend_query->onion_address, -1, &entry) < 1) {
  686. log_warn(LD_REND,
  687. "Query '%s' didn't have valid rend desc in cache. Failing.",
  688. safe_str_client(rend_query->onion_address));
  689. return NULL;
  690. }
  691. /* See if we can get a node that complies with ExcludeNodes */
  692. if ((result = rend_client_get_random_intro_impl(entry, 1, 1)))
  693. return result;
  694. /* If not, and StrictNodes is not set, see if we can return any old node
  695. */
  696. if (!get_options()->StrictNodes)
  697. return rend_client_get_random_intro_impl(entry, 0, 1);
  698. return NULL;
  699. }
  700. /** As rend_client_get_random_intro, except assume that StrictNodes is set
  701. * iff <b>strict</b> is true.
  702. */
  703. static extend_info_t *
  704. rend_client_get_random_intro_impl(const rend_cache_entry_t *entry,
  705. const int strict,
  706. const int warnings)
  707. {
  708. int i;
  709. rend_intro_point_t *intro;
  710. routerinfo_t *router;
  711. or_options_t *options = get_options();
  712. smartlist_t *usable_nodes;
  713. int n_excluded = 0;
  714. /* We'll keep a separate list of the usable nodes. If this becomes empty,
  715. * no nodes are usable. */
  716. usable_nodes = smartlist_create();
  717. smartlist_add_all(usable_nodes, entry->parsed->intro_nodes);
  718. again:
  719. if (smartlist_len(usable_nodes) == 0) {
  720. if (n_excluded && get_options()->StrictNodes && warnings) {
  721. /* We only want to warn if StrictNodes is really set. Otherwise
  722. * we're just about to retry anyways.
  723. */
  724. log_warn(LD_REND, "All introduction points for hidden service are "
  725. "at excluded relays, and StrictNodes is set. Skipping.");
  726. }
  727. smartlist_free(usable_nodes);
  728. return NULL;
  729. }
  730. i = crypto_rand_int(smartlist_len(usable_nodes));
  731. intro = smartlist_get(usable_nodes, i);
  732. /* Do we need to look up the router or is the extend info complete? */
  733. if (!intro->extend_info->onion_key) {
  734. if (tor_digest_is_zero(intro->extend_info->identity_digest))
  735. router = router_get_by_hexdigest(intro->extend_info->nickname);
  736. else
  737. router = router_get_by_digest(intro->extend_info->identity_digest);
  738. if (!router) {
  739. log_info(LD_REND, "Unknown router with nickname '%s'; trying another.",
  740. intro->extend_info->nickname);
  741. smartlist_del(usable_nodes, i);
  742. goto again;
  743. }
  744. extend_info_free(intro->extend_info);
  745. intro->extend_info = extend_info_from_router(router);
  746. }
  747. /* Check if we should refuse to talk to this router. */
  748. if (options->ExcludeNodes && strict &&
  749. routerset_contains_extendinfo(options->ExcludeNodes,
  750. intro->extend_info)) {
  751. n_excluded++;
  752. smartlist_del(usable_nodes, i);
  753. goto again;
  754. }
  755. smartlist_free(usable_nodes);
  756. return extend_info_dup(intro->extend_info);
  757. }
  758. /** Return true iff any introduction points still listed in <b>entry</b> are
  759. * usable. */
  760. int
  761. rend_client_any_intro_points_usable(const rend_cache_entry_t *entry)
  762. {
  763. return rend_client_get_random_intro_impl(
  764. entry, get_options()->StrictNodes, 0) != NULL;
  765. }
  766. /** Client-side authorizations for hidden services; map of onion address to
  767. * rend_service_authorization_t*. */
  768. static strmap_t *auth_hid_servs = NULL;
  769. /** Look up the client-side authorization for the hidden service with
  770. * <b>onion_address</b>. Return NULL if no authorization is available for
  771. * that address. */
  772. rend_service_authorization_t*
  773. rend_client_lookup_service_authorization(const char *onion_address)
  774. {
  775. tor_assert(onion_address);
  776. if (!auth_hid_servs) return NULL;
  777. return strmap_get(auth_hid_servs, onion_address);
  778. }
  779. /** Helper: Free storage held by rend_service_authorization_t. */
  780. static void
  781. rend_service_authorization_free(rend_service_authorization_t *auth)
  782. {
  783. tor_free(auth);
  784. }
  785. /** Helper for strmap_free. */
  786. static void
  787. rend_service_authorization_strmap_item_free(void *service_auth)
  788. {
  789. rend_service_authorization_free(service_auth);
  790. }
  791. /** Release all the storage held in auth_hid_servs.
  792. */
  793. void
  794. rend_service_authorization_free_all(void)
  795. {
  796. if (!auth_hid_servs) {
  797. return;
  798. }
  799. strmap_free(auth_hid_servs, rend_service_authorization_strmap_item_free);
  800. auth_hid_servs = NULL;
  801. }
  802. /** Parse <b>config_line</b> as a client-side authorization for a hidden
  803. * service and add it to the local map of hidden service authorizations.
  804. * Return 0 for success and -1 for failure. */
  805. int
  806. rend_parse_service_authorization(or_options_t *options, int validate_only)
  807. {
  808. config_line_t *line;
  809. int res = -1;
  810. strmap_t *parsed = strmap_new();
  811. smartlist_t *sl = smartlist_create();
  812. rend_service_authorization_t *auth = NULL;
  813. for (line = options->HidServAuth; line; line = line->next) {
  814. char *onion_address, *descriptor_cookie;
  815. char descriptor_cookie_tmp[REND_DESC_COOKIE_LEN+2];
  816. char descriptor_cookie_base64ext[REND_DESC_COOKIE_LEN_BASE64+2+1];
  817. int auth_type_val = 0;
  818. auth = NULL;
  819. SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
  820. smartlist_clear(sl);
  821. smartlist_split_string(sl, line->value, " ",
  822. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
  823. if (smartlist_len(sl) < 2) {
  824. log_warn(LD_CONFIG, "Configuration line does not consist of "
  825. "\"onion-address authorization-cookie [service-name]\": "
  826. "'%s'", line->value);
  827. goto err;
  828. }
  829. auth = tor_malloc_zero(sizeof(rend_service_authorization_t));
  830. /* Parse onion address. */
  831. onion_address = smartlist_get(sl, 0);
  832. if (strlen(onion_address) != REND_SERVICE_ADDRESS_LEN ||
  833. strcmpend(onion_address, ".onion")) {
  834. log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
  835. onion_address);
  836. goto err;
  837. }
  838. strlcpy(auth->onion_address, onion_address, REND_SERVICE_ID_LEN_BASE32+1);
  839. if (!rend_valid_service_id(auth->onion_address)) {
  840. log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
  841. onion_address);
  842. goto err;
  843. }
  844. /* Parse descriptor cookie. */
  845. descriptor_cookie = smartlist_get(sl, 1);
  846. if (strlen(descriptor_cookie) != REND_DESC_COOKIE_LEN_BASE64) {
  847. log_warn(LD_CONFIG, "Authorization cookie has wrong length: '%s'",
  848. descriptor_cookie);
  849. goto err;
  850. }
  851. /* Add trailing zero bytes (AA) to make base64-decoding happy. */
  852. tor_snprintf(descriptor_cookie_base64ext,
  853. REND_DESC_COOKIE_LEN_BASE64+2+1,
  854. "%sAA", descriptor_cookie);
  855. if (base64_decode(descriptor_cookie_tmp, sizeof(descriptor_cookie_tmp),
  856. descriptor_cookie_base64ext,
  857. strlen(descriptor_cookie_base64ext)) < 0) {
  858. log_warn(LD_CONFIG, "Decoding authorization cookie failed: '%s'",
  859. descriptor_cookie);
  860. goto err;
  861. }
  862. auth_type_val = (descriptor_cookie_tmp[16] >> 4) + 1;
  863. if (auth_type_val < 1 || auth_type_val > 2) {
  864. log_warn(LD_CONFIG, "Authorization cookie has unknown authorization "
  865. "type encoded.");
  866. goto err;
  867. }
  868. auth->auth_type = auth_type_val == 1 ? REND_BASIC_AUTH : REND_STEALTH_AUTH;
  869. memcpy(auth->descriptor_cookie, descriptor_cookie_tmp,
  870. REND_DESC_COOKIE_LEN);
  871. if (strmap_get(parsed, auth->onion_address)) {
  872. log_warn(LD_CONFIG, "Duplicate authorization for the same hidden "
  873. "service.");
  874. goto err;
  875. }
  876. strmap_set(parsed, auth->onion_address, auth);
  877. auth = NULL;
  878. }
  879. res = 0;
  880. goto done;
  881. err:
  882. res = -1;
  883. done:
  884. rend_service_authorization_free(auth);
  885. SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
  886. smartlist_free(sl);
  887. if (!validate_only && res == 0) {
  888. rend_service_authorization_free_all();
  889. auth_hid_servs = parsed;
  890. } else {
  891. strmap_free(parsed, rend_service_authorization_strmap_item_free);
  892. }
  893. return res;
  894. }