rendclient.c 35 KB

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