rendclient.c 38 KB

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