rendclient.c 34 KB

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