rendclient.c 34 KB

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