rendclient.c 36 KB

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