rendclient.c 37 KB

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