rendclient.c 37 KB

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