rendclient.c 34 KB

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