rendclient.c 34 KB

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