rendclient.c 35 KB

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