rendclient.c 38 KB

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