rendclient.c 34 KB

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