rendclient.c 35 KB

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