rendclient.c 32 KB

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