rendclient.c 34 KB

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