rendclient.c 34 KB

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