hs_client.c 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392
  1. /* Copyright (c) 2016-2017, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file hs_client.c
  5. * \brief Implement next generation hidden service client functionality
  6. **/
  7. #define HS_CLIENT_PRIVATE
  8. #include "or.h"
  9. #include "hs_circuit.h"
  10. #include "hs_ident.h"
  11. #include "connection_edge.h"
  12. #include "container.h"
  13. #include "rendclient.h"
  14. #include "hs_descriptor.h"
  15. #include "hs_cache.h"
  16. #include "hs_cell.h"
  17. #include "hs_ident.h"
  18. #include "config.h"
  19. #include "directory.h"
  20. #include "hs_client.h"
  21. #include "router.h"
  22. #include "routerset.h"
  23. #include "circuitlist.h"
  24. #include "circuituse.h"
  25. #include "connection.h"
  26. #include "nodelist.h"
  27. #include "circpathbias.h"
  28. #include "connection.h"
  29. #include "hs_ntor.h"
  30. #include "circuitbuild.h"
  31. #include "networkstatus.h"
  32. /* Cancel all descriptor fetches currently in progress. */
  33. static void
  34. cancel_descriptor_fetches(void)
  35. {
  36. smartlist_t *conns =
  37. connection_list_by_type_state(CONN_TYPE_DIR, DIR_PURPOSE_FETCH_HSDESC);
  38. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  39. const hs_ident_dir_conn_t *ident = TO_DIR_CONN(conn)->hs_ident;
  40. if (BUG(ident == NULL)) {
  41. /* A directory connection fetching a service descriptor can't have an
  42. * empty hidden service identifier. */
  43. continue;
  44. }
  45. log_debug(LD_REND, "Marking for close a directory connection fetching "
  46. "a hidden service descriptor for service %s.",
  47. safe_str_client(ed25519_fmt(&ident->identity_pk)));
  48. connection_mark_for_close(conn);
  49. } SMARTLIST_FOREACH_END(conn);
  50. /* No ownership of the objects in this list. */
  51. smartlist_free(conns);
  52. log_info(LD_REND, "Hidden service client descriptor fetches cancelled.");
  53. }
  54. /* Get all connections that are waiting on a circuit and flag them back to
  55. * waiting for a hidden service descriptor for the given service key
  56. * service_identity_pk. */
  57. static void
  58. flag_all_conn_wait_desc(const ed25519_public_key_t *service_identity_pk)
  59. {
  60. tor_assert(service_identity_pk);
  61. smartlist_t *conns =
  62. connection_list_by_type_state(CONN_TYPE_AP, AP_CONN_STATE_CIRCUIT_WAIT);
  63. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  64. edge_connection_t *edge_conn;
  65. if (BUG(!CONN_IS_EDGE(conn))) {
  66. continue;
  67. }
  68. edge_conn = TO_EDGE_CONN(conn);
  69. if (edge_conn->hs_ident &&
  70. ed25519_pubkey_eq(&edge_conn->hs_ident->identity_pk,
  71. service_identity_pk)) {
  72. connection_ap_mark_as_non_pending_circuit(TO_ENTRY_CONN(conn));
  73. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  74. }
  75. } SMARTLIST_FOREACH_END(conn);
  76. smartlist_free(conns);
  77. }
  78. /* Remove tracked HSDir requests from our history for this hidden service
  79. * identity public key. */
  80. static void
  81. purge_hid_serv_request(const ed25519_public_key_t *identity_pk)
  82. {
  83. char base64_blinded_pk[ED25519_BASE64_LEN + 1];
  84. ed25519_public_key_t blinded_pk;
  85. tor_assert(identity_pk);
  86. /* Get blinded pubkey of hidden service. It is possible that we just moved
  87. * to a new time period meaning that we won't be able to purge the request
  88. * from the previous time period. That is fine because they will expire at
  89. * some point and we don't care about those anymore. */
  90. hs_build_blinded_pubkey(identity_pk, NULL, 0,
  91. hs_get_time_period_num(0), &blinded_pk);
  92. if (BUG(ed25519_public_to_base64(base64_blinded_pk, &blinded_pk) < 0)) {
  93. return;
  94. }
  95. /* Purge last hidden service request from cache for this blinded key. */
  96. hs_purge_hid_serv_from_last_hid_serv_requests(base64_blinded_pk);
  97. }
  98. /* Return true iff there is at least one pending directory descriptor request
  99. * for the service identity_pk. */
  100. static int
  101. directory_request_is_pending(const ed25519_public_key_t *identity_pk)
  102. {
  103. int ret = 0;
  104. smartlist_t *conns =
  105. connection_list_by_type_purpose(CONN_TYPE_DIR, DIR_PURPOSE_FETCH_HSDESC);
  106. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  107. const hs_ident_dir_conn_t *ident = TO_DIR_CONN(conn)->hs_ident;
  108. if (BUG(ident == NULL)) {
  109. /* A directory connection fetching a service descriptor can't have an
  110. * empty hidden service identifier. */
  111. continue;
  112. }
  113. if (!ed25519_pubkey_eq(identity_pk, &ident->identity_pk)) {
  114. continue;
  115. }
  116. ret = 1;
  117. break;
  118. } SMARTLIST_FOREACH_END(conn);
  119. /* No ownership of the objects in this list. */
  120. smartlist_free(conns);
  121. return ret;
  122. }
  123. /* A v3 HS circuit successfully connected to the hidden service. Update the
  124. * stream state at <b>hs_conn_ident</b> appropriately. */
  125. static void
  126. note_connection_attempt_succeeded(const hs_ident_edge_conn_t *hs_conn_ident)
  127. {
  128. tor_assert(hs_conn_ident);
  129. /* Remove from the hid serv cache all requests for that service so we can
  130. * query the HSDir again later on for various reasons. */
  131. purge_hid_serv_request(&hs_conn_ident->identity_pk);
  132. /* The v2 subsystem cleans up the intro point time out flag at this stage.
  133. * We don't try to do it here because we still need to keep intact the intro
  134. * point state for future connections. Even though we are able to connect to
  135. * the service, doesn't mean we should reset the timed out intro points.
  136. *
  137. * It is not possible to have successfully connected to an intro point
  138. * present in our cache that was on error or timed out. Every entry in that
  139. * cache have a 2 minutes lifetime so ultimately the intro point(s) state
  140. * will be reset and thus possible to be retried. */
  141. }
  142. /* Given the pubkey of a hidden service in <b>onion_identity_pk</b>, fetch its
  143. * descriptor by launching a dir connection to <b>hsdir</b>. Return a
  144. * hs_client_fetch_status_t status code depending on how it went. */
  145. static hs_client_fetch_status_t
  146. directory_launch_v3_desc_fetch(const ed25519_public_key_t *onion_identity_pk,
  147. const routerstatus_t *hsdir)
  148. {
  149. uint64_t current_time_period = hs_get_time_period_num(0);
  150. ed25519_public_key_t blinded_pubkey;
  151. char base64_blinded_pubkey[ED25519_BASE64_LEN + 1];
  152. hs_ident_dir_conn_t hs_conn_dir_ident;
  153. int retval;
  154. tor_assert(hsdir);
  155. tor_assert(onion_identity_pk);
  156. /* Get blinded pubkey */
  157. hs_build_blinded_pubkey(onion_identity_pk, NULL, 0,
  158. current_time_period, &blinded_pubkey);
  159. /* ...and base64 it. */
  160. retval = ed25519_public_to_base64(base64_blinded_pubkey, &blinded_pubkey);
  161. if (BUG(retval < 0)) {
  162. return HS_CLIENT_FETCH_ERROR;
  163. }
  164. /* Copy onion pk to a dir_ident so that we attach it to the dir conn */
  165. hs_ident_dir_conn_init(onion_identity_pk, &blinded_pubkey,
  166. &hs_conn_dir_ident);
  167. /* Setup directory request */
  168. directory_request_t *req =
  169. directory_request_new(DIR_PURPOSE_FETCH_HSDESC);
  170. directory_request_set_routerstatus(req, hsdir);
  171. directory_request_set_indirection(req, DIRIND_ANONYMOUS);
  172. directory_request_set_resource(req, base64_blinded_pubkey);
  173. directory_request_fetch_set_hs_ident(req, &hs_conn_dir_ident);
  174. directory_initiate_request(req);
  175. directory_request_free(req);
  176. log_info(LD_REND, "Descriptor fetch request for service %s with blinded "
  177. "key %s to directory %s",
  178. safe_str_client(ed25519_fmt(onion_identity_pk)),
  179. safe_str_client(base64_blinded_pubkey),
  180. safe_str_client(routerstatus_describe(hsdir)));
  181. /* Cleanup memory. */
  182. memwipe(&blinded_pubkey, 0, sizeof(blinded_pubkey));
  183. memwipe(base64_blinded_pubkey, 0, sizeof(base64_blinded_pubkey));
  184. memwipe(&hs_conn_dir_ident, 0, sizeof(hs_conn_dir_ident));
  185. return HS_CLIENT_FETCH_LAUNCHED;
  186. }
  187. /** Return the HSDir we should use to fetch the descriptor of the hidden
  188. * service with identity key <b>onion_identity_pk</b>. */
  189. STATIC routerstatus_t *
  190. pick_hsdir_v3(const ed25519_public_key_t *onion_identity_pk)
  191. {
  192. int retval;
  193. char base64_blinded_pubkey[ED25519_BASE64_LEN + 1];
  194. uint64_t current_time_period = hs_get_time_period_num(0);
  195. smartlist_t *responsible_hsdirs;
  196. ed25519_public_key_t blinded_pubkey;
  197. routerstatus_t *hsdir_rs = NULL;
  198. tor_assert(onion_identity_pk);
  199. responsible_hsdirs = smartlist_new();
  200. /* Get blinded pubkey of hidden service */
  201. hs_build_blinded_pubkey(onion_identity_pk, NULL, 0,
  202. current_time_period, &blinded_pubkey);
  203. /* ...and base64 it. */
  204. retval = ed25519_public_to_base64(base64_blinded_pubkey, &blinded_pubkey);
  205. if (BUG(retval < 0)) {
  206. return NULL;
  207. }
  208. /* Get responsible hsdirs of service for this time period */
  209. hs_get_responsible_hsdirs(&blinded_pubkey, current_time_period,
  210. 0, 1, responsible_hsdirs);
  211. log_debug(LD_REND, "Found %d responsible HSDirs and about to pick one.",
  212. smartlist_len(responsible_hsdirs));
  213. /* Pick an HSDir from the responsible ones. The ownership of
  214. * responsible_hsdirs is given to this function so no need to free it. */
  215. hsdir_rs = hs_pick_hsdir(responsible_hsdirs, base64_blinded_pubkey);
  216. return hsdir_rs;
  217. }
  218. /** Fetch a v3 descriptor using the given <b>onion_identity_pk</b>.
  219. *
  220. * On success, HS_CLIENT_FETCH_LAUNCHED is returned. Otherwise, an error from
  221. * hs_client_fetch_status_t is returned. */
  222. static hs_client_fetch_status_t
  223. fetch_v3_desc(const ed25519_public_key_t *onion_identity_pk)
  224. {
  225. routerstatus_t *hsdir_rs =NULL;
  226. tor_assert(onion_identity_pk);
  227. hsdir_rs = pick_hsdir_v3(onion_identity_pk);
  228. if (!hsdir_rs) {
  229. log_info(LD_REND, "Couldn't pick a v3 hsdir.");
  230. return HS_CLIENT_FETCH_NO_HSDIRS;
  231. }
  232. return directory_launch_v3_desc_fetch(onion_identity_pk, hsdir_rs);
  233. }
  234. /* Make sure that the given v3 origin circuit circ is a valid correct
  235. * introduction circuit. This will BUG() on any problems and hard assert if
  236. * the anonymity of the circuit is not ok. Return 0 on success else -1 where
  237. * the circuit should be mark for closed immediately. */
  238. static int
  239. intro_circ_is_ok(const origin_circuit_t *circ)
  240. {
  241. int ret = 0;
  242. tor_assert(circ);
  243. if (BUG(TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
  244. TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
  245. TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACKED)) {
  246. ret = -1;
  247. }
  248. if (BUG(circ->hs_ident == NULL)) {
  249. ret = -1;
  250. }
  251. if (BUG(!hs_ident_intro_circ_is_valid(circ->hs_ident))) {
  252. ret = -1;
  253. }
  254. /* This can stop the tor daemon but we want that since if we don't have
  255. * anonymity on this circuit, something went really wrong. */
  256. assert_circ_anonymity_ok(circ, get_options());
  257. return ret;
  258. }
  259. /* Find a descriptor intro point object that matches the given ident in the
  260. * given descriptor desc. Return NULL if not found. */
  261. static const hs_desc_intro_point_t *
  262. find_desc_intro_point_by_ident(const hs_ident_circuit_t *ident,
  263. const hs_descriptor_t *desc)
  264. {
  265. const hs_desc_intro_point_t *intro_point = NULL;
  266. tor_assert(ident);
  267. tor_assert(desc);
  268. SMARTLIST_FOREACH_BEGIN(desc->encrypted_data.intro_points,
  269. const hs_desc_intro_point_t *, ip) {
  270. if (ed25519_pubkey_eq(&ident->intro_auth_pk,
  271. &ip->auth_key_cert->signed_key)) {
  272. intro_point = ip;
  273. break;
  274. }
  275. } SMARTLIST_FOREACH_END(ip);
  276. return intro_point;
  277. }
  278. /* Find a descriptor intro point object from the descriptor object desc that
  279. * matches the given legacy identity digest in legacy_id. Return NULL if not
  280. * found. */
  281. static hs_desc_intro_point_t *
  282. find_desc_intro_point_by_legacy_id(const char *legacy_id,
  283. const hs_descriptor_t *desc)
  284. {
  285. hs_desc_intro_point_t *ret_ip = NULL;
  286. tor_assert(legacy_id);
  287. tor_assert(desc);
  288. /* We will go over every intro point and try to find which one is linked to
  289. * that circuit. Those lists are small so it's not that expensive. */
  290. SMARTLIST_FOREACH_BEGIN(desc->encrypted_data.intro_points,
  291. hs_desc_intro_point_t *, ip) {
  292. SMARTLIST_FOREACH_BEGIN(ip->link_specifiers,
  293. const hs_desc_link_specifier_t *, lspec) {
  294. /* Not all tor node have an ed25519 identity key so we still rely on the
  295. * legacy identity digest. */
  296. if (lspec->type != LS_LEGACY_ID) {
  297. continue;
  298. }
  299. if (fast_memneq(legacy_id, lspec->u.legacy_id, DIGEST_LEN)) {
  300. break;
  301. }
  302. /* Found it. */
  303. ret_ip = ip;
  304. goto end;
  305. } SMARTLIST_FOREACH_END(lspec);
  306. } SMARTLIST_FOREACH_END(ip);
  307. end:
  308. return ret_ip;
  309. }
  310. /* Send an INTRODUCE1 cell along the intro circuit and populate the rend
  311. * circuit identifier with the needed key material for the e2e encryption.
  312. * Return 0 on success, -1 if there is a transient error such that an action
  313. * has been taken to recover and -2 if there is a permanent error indicating
  314. * that both circuits were closed. */
  315. static int
  316. send_introduce1(origin_circuit_t *intro_circ,
  317. origin_circuit_t *rend_circ)
  318. {
  319. int status;
  320. char onion_address[HS_SERVICE_ADDR_LEN_BASE32 + 1];
  321. const ed25519_public_key_t *service_identity_pk = NULL;
  322. const hs_desc_intro_point_t *ip;
  323. tor_assert(rend_circ);
  324. if (intro_circ_is_ok(intro_circ) < 0) {
  325. goto perm_err;
  326. }
  327. service_identity_pk = &intro_circ->hs_ident->identity_pk;
  328. /* For logging purposes. There will be a time where the hs_ident will have a
  329. * version number but for now there is none because it's all v3. */
  330. hs_build_address(service_identity_pk, HS_VERSION_THREE, onion_address);
  331. log_info(LD_REND, "Sending INTRODUCE1 cell to service %s on circuit %u",
  332. safe_str_client(onion_address), TO_CIRCUIT(intro_circ)->n_circ_id);
  333. /* 1) Get descriptor from our cache. */
  334. const hs_descriptor_t *desc =
  335. hs_cache_lookup_as_client(service_identity_pk);
  336. if (desc == NULL || !hs_client_any_intro_points_usable(service_identity_pk,
  337. desc)) {
  338. log_info(LD_REND, "Request to %s %s. Trying to fetch a new descriptor.",
  339. safe_str_client(onion_address),
  340. (desc) ? "didn't have usable intro points" :
  341. "didn't have a descriptor");
  342. hs_client_refetch_hsdesc(service_identity_pk);
  343. /* We just triggered a refetch, make sure every connections are back
  344. * waiting for that descriptor. */
  345. flag_all_conn_wait_desc(service_identity_pk);
  346. /* We just asked for a refetch so this is a transient error. */
  347. goto tran_err;
  348. }
  349. /* We need to find which intro point in the descriptor we are connected to
  350. * on intro_circ. */
  351. ip = find_desc_intro_point_by_ident(intro_circ->hs_ident, desc);
  352. if (BUG(ip == NULL)) {
  353. /* If we can find a descriptor from this introduction circuit ident, we
  354. * must have a valid intro point object. Permanent error. */
  355. goto perm_err;
  356. }
  357. /* Send the INTRODUCE1 cell. */
  358. if (hs_circ_send_introduce1(intro_circ, rend_circ, ip,
  359. desc->subcredential) < 0) {
  360. /* Unable to send the cell, the intro circuit has been marked for close so
  361. * this is a permanent error. */
  362. tor_assert_nonfatal(TO_CIRCUIT(intro_circ)->marked_for_close);
  363. goto perm_err;
  364. }
  365. /* Cell has been sent successfully. Copy the introduction point
  366. * authentication and encryption key in the rendezvous circuit identifier so
  367. * we can compute the ntor keys when we receive the RENDEZVOUS2 cell. */
  368. memcpy(&rend_circ->hs_ident->intro_enc_pk, &ip->enc_key,
  369. sizeof(rend_circ->hs_ident->intro_enc_pk));
  370. ed25519_pubkey_copy(&rend_circ->hs_ident->intro_auth_pk,
  371. &intro_circ->hs_ident->intro_auth_pk);
  372. /* Now, we wait for an ACK or NAK on this circuit. */
  373. circuit_change_purpose(TO_CIRCUIT(intro_circ),
  374. CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT);
  375. /* Set timestamp_dirty, because circuit_expire_building expects it to
  376. * specify when a circuit entered the _C_INTRODUCE_ACK_WAIT state. */
  377. TO_CIRCUIT(intro_circ)->timestamp_dirty = time(NULL);
  378. pathbias_count_use_attempt(intro_circ);
  379. /* Success. */
  380. status = 0;
  381. goto end;
  382. perm_err:
  383. /* Permanent error: it is possible that the intro circuit was closed prior
  384. * because we weren't able to send the cell. Make sure we don't double close
  385. * it which would result in a warning. */
  386. if (!TO_CIRCUIT(intro_circ)->marked_for_close) {
  387. circuit_mark_for_close(TO_CIRCUIT(intro_circ), END_CIRC_REASON_INTERNAL);
  388. }
  389. circuit_mark_for_close(TO_CIRCUIT(rend_circ), END_CIRC_REASON_INTERNAL);
  390. status = -2;
  391. goto end;
  392. tran_err:
  393. status = -1;
  394. end:
  395. memwipe(onion_address, 0, sizeof(onion_address));
  396. return status;
  397. }
  398. /* Using the introduction circuit circ, setup the authentication key of the
  399. * intro point this circuit has extended to. */
  400. static void
  401. setup_intro_circ_auth_key(origin_circuit_t *circ)
  402. {
  403. const hs_descriptor_t *desc;
  404. const hs_desc_intro_point_t *ip;
  405. tor_assert(circ);
  406. desc = hs_cache_lookup_as_client(&circ->hs_ident->identity_pk);
  407. if (BUG(desc == NULL)) {
  408. /* Opening intro circuit without the descriptor is no good... */
  409. goto end;
  410. }
  411. /* We will go over every intro point and try to find which one is linked to
  412. * that circuit. Those lists are small so it's not that expensive. */
  413. ip = find_desc_intro_point_by_legacy_id(
  414. circ->build_state->chosen_exit->identity_digest, desc);
  415. if (ip) {
  416. /* We got it, copy its authentication key to the identifier. */
  417. ed25519_pubkey_copy(&circ->hs_ident->intro_auth_pk,
  418. &ip->auth_key_cert->signed_key);
  419. goto end;
  420. }
  421. /* Reaching this point means we didn't find any intro point for this circuit
  422. * which is not suppose to happen. */
  423. tor_assert_nonfatal_unreached();
  424. end:
  425. return;
  426. }
  427. /* Called when an introduction circuit has opened. */
  428. static void
  429. client_intro_circ_has_opened(origin_circuit_t *circ)
  430. {
  431. tor_assert(circ);
  432. tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  433. log_info(LD_REND, "Introduction circuit %u has opened. Attaching streams.",
  434. (unsigned int) TO_CIRCUIT(circ)->n_circ_id);
  435. /* This is an introduction circuit so we'll attach the correct
  436. * authentication key to the circuit identifier so it can be identified
  437. * properly later on. */
  438. setup_intro_circ_auth_key(circ);
  439. connection_ap_attach_pending(1);
  440. }
  441. /* Called when a rendezvous circuit has opened. */
  442. static void
  443. client_rendezvous_circ_has_opened(origin_circuit_t *circ)
  444. {
  445. tor_assert(circ);
  446. tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
  447. const extend_info_t *rp_ei = circ->build_state->chosen_exit;
  448. /* Check that we didn't accidentally choose a node that does not understand
  449. * the v3 rendezvous protocol */
  450. if (rp_ei) {
  451. const node_t *rp_node = node_get_by_id(rp_ei->identity_digest);
  452. if (rp_node) {
  453. if (BUG(!node_supports_v3_rendezvous_point(rp_node))) {
  454. return;
  455. }
  456. }
  457. }
  458. log_info(LD_REND, "Rendezvous circuit has opened to %s.",
  459. safe_str_client(extend_info_describe(rp_ei)));
  460. /* Ignore returned value, nothing we can really do. On failure, the circuit
  461. * will be marked for close. */
  462. hs_circ_send_establish_rendezvous(circ);
  463. /* Register rend circuit in circuitmap if it's still alive. */
  464. if (!TO_CIRCUIT(circ)->marked_for_close) {
  465. hs_circuitmap_register_rend_circ_client_side(circ,
  466. circ->hs_ident->rendezvous_cookie);
  467. }
  468. }
  469. /* This is an helper function that convert a descriptor intro point object ip
  470. * to a newly allocated extend_info_t object fully initialized. Return NULL if
  471. * we can't convert it for which chances are that we are missing or malformed
  472. * link specifiers. */
  473. STATIC extend_info_t *
  474. desc_intro_point_to_extend_info(const hs_desc_intro_point_t *ip)
  475. {
  476. extend_info_t *ei;
  477. smartlist_t *lspecs = smartlist_new();
  478. tor_assert(ip);
  479. /* We first encode the descriptor link specifiers into the binary
  480. * representation which is a trunnel object. */
  481. SMARTLIST_FOREACH_BEGIN(ip->link_specifiers,
  482. const hs_desc_link_specifier_t *, desc_lspec) {
  483. link_specifier_t *lspec = hs_desc_lspec_to_trunnel(desc_lspec);
  484. smartlist_add(lspecs, lspec);
  485. } SMARTLIST_FOREACH_END(desc_lspec);
  486. /* Explicitely put the direct connection option to 0 because this is client
  487. * side and there is no such thing as a non anonymous client. */
  488. ei = hs_get_extend_info_from_lspecs(lspecs, &ip->onion_key, 0);
  489. SMARTLIST_FOREACH(lspecs, link_specifier_t *, ls, link_specifier_free(ls));
  490. smartlist_free(lspecs);
  491. return ei;
  492. }
  493. /* Return true iff the intro point ip for the service service_pk is usable.
  494. * This function checks if the intro point is in the client intro state cache
  495. * and checks at the failures. It is considered usable if:
  496. * - No error happened (INTRO_POINT_FAILURE_GENERIC)
  497. * - It is not flagged as timed out (INTRO_POINT_FAILURE_TIMEOUT)
  498. * - The unreachable count is lower than
  499. * MAX_INTRO_POINT_REACHABILITY_FAILURES (INTRO_POINT_FAILURE_UNREACHABLE)
  500. */
  501. static int
  502. intro_point_is_usable(const ed25519_public_key_t *service_pk,
  503. const hs_desc_intro_point_t *ip)
  504. {
  505. const hs_cache_intro_state_t *state;
  506. tor_assert(service_pk);
  507. tor_assert(ip);
  508. state = hs_cache_client_intro_state_find(service_pk,
  509. &ip->auth_key_cert->signed_key);
  510. if (state == NULL) {
  511. /* This means we've never encountered any problem thus usable. */
  512. goto usable;
  513. }
  514. if (state->error) {
  515. log_info(LD_REND, "Intro point with auth key %s had an error. Not usable",
  516. safe_str_client(ed25519_fmt(&ip->auth_key_cert->signed_key)));
  517. goto not_usable;
  518. }
  519. if (state->timed_out) {
  520. log_info(LD_REND, "Intro point with auth key %s timed out. Not usable",
  521. safe_str_client(ed25519_fmt(&ip->auth_key_cert->signed_key)));
  522. goto not_usable;
  523. }
  524. if (state->unreachable_count >= MAX_INTRO_POINT_REACHABILITY_FAILURES) {
  525. log_info(LD_REND, "Intro point with auth key %s unreachable. Not usable",
  526. safe_str_client(ed25519_fmt(&ip->auth_key_cert->signed_key)));
  527. goto not_usable;
  528. }
  529. usable:
  530. return 1;
  531. not_usable:
  532. return 0;
  533. }
  534. /* Using a descriptor desc, return a newly allocated extend_info_t object of a
  535. * randomly picked introduction point from its list. Return NULL if none are
  536. * usable. */
  537. STATIC extend_info_t *
  538. client_get_random_intro(const ed25519_public_key_t *service_pk)
  539. {
  540. extend_info_t *ei = NULL, *ei_excluded = NULL;
  541. smartlist_t *usable_ips = NULL;
  542. const hs_descriptor_t *desc;
  543. const hs_desc_encrypted_data_t *enc_data;
  544. const or_options_t *options = get_options();
  545. tor_assert(service_pk);
  546. desc = hs_cache_lookup_as_client(service_pk);
  547. if (desc == NULL || !hs_client_any_intro_points_usable(service_pk,
  548. desc)) {
  549. log_info(LD_REND, "Unable to randomly select an introduction point "
  550. "because descriptor %s.",
  551. (desc) ? "doesn't have usable intro point" : "is missing");
  552. goto end;
  553. }
  554. enc_data = &desc->encrypted_data;
  555. usable_ips = smartlist_new();
  556. smartlist_add_all(usable_ips, enc_data->intro_points);
  557. while (smartlist_len(usable_ips) != 0) {
  558. int idx;
  559. const hs_desc_intro_point_t *ip;
  560. /* Pick a random intro point and immediately remove it from the usable
  561. * list so we don't pick it again if we have to iterate more. */
  562. idx = crypto_rand_int(smartlist_len(usable_ips));
  563. ip = smartlist_get(usable_ips, idx);
  564. smartlist_del(usable_ips, idx);
  565. /* We need to make sure we have a usable intro points which is in a good
  566. * state in our cache. */
  567. if (!intro_point_is_usable(service_pk, ip)) {
  568. continue;
  569. }
  570. /* Generate an extend info object from the intro point object. */
  571. ei = desc_intro_point_to_extend_info(ip);
  572. if (ei == NULL) {
  573. /* We can get here for instance if the intro point is a private address
  574. * and we aren't allowed to extend to those. */
  575. continue;
  576. }
  577. /* Test the pick against ExcludeNodes. */
  578. if (routerset_contains_extendinfo(options->ExcludeNodes, ei)) {
  579. /* If this pick is in the ExcludeNodes list, we keep its reference so if
  580. * we ever end up not being able to pick anything else and StrictNodes is
  581. * unset, we'll use it. */
  582. if (ei_excluded) {
  583. /* If something was already here free it. After the loop is gone we
  584. * will examine the last excluded intro point, and that's fine since
  585. * that's random anyway */
  586. extend_info_free(ei_excluded);
  587. }
  588. ei_excluded = ei;
  589. continue;
  590. }
  591. /* Good pick! Let's go with this. */
  592. goto end;
  593. }
  594. /* Reaching this point means a couple of things. Either we can't use any of
  595. * the intro point listed because the IP address can't be extended to or it
  596. * is listed in the ExcludeNodes list. In the later case, if StrictNodes is
  597. * set, we are forced to not use anything. */
  598. ei = ei_excluded;
  599. if (options->StrictNodes) {
  600. log_warn(LD_REND, "Every introduction points are in the ExcludeNodes set "
  601. "and StrictNodes is set. We can't connect.");
  602. extend_info_free(ei);
  603. ei = NULL;
  604. }
  605. end:
  606. smartlist_free(usable_ips);
  607. return ei;
  608. }
  609. /* For this introduction circuit, we'll look at if we have any usable
  610. * introduction point left for this service. If so, we'll use the circuit to
  611. * re-extend to a new intro point. Else, we'll close the circuit and its
  612. * corresponding rendezvous circuit. Return 0 if we are re-extending else -1
  613. * if we are closing the circuits.
  614. *
  615. * This is called when getting an INTRODUCE_ACK cell with a NACK. */
  616. static int
  617. close_or_reextend_intro_circ(origin_circuit_t *intro_circ)
  618. {
  619. int ret = -1;
  620. const hs_descriptor_t *desc;
  621. origin_circuit_t *rend_circ;
  622. tor_assert(intro_circ);
  623. desc = hs_cache_lookup_as_client(&intro_circ->hs_ident->identity_pk);
  624. if (BUG(desc == NULL)) {
  625. /* We can't continue without a descriptor. */
  626. goto close;
  627. }
  628. /* We still have the descriptor, great! Let's try to see if we can
  629. * re-extend by looking up if there are any usable intro points. */
  630. if (!hs_client_any_intro_points_usable(&intro_circ->hs_ident->identity_pk,
  631. desc)) {
  632. goto close;
  633. }
  634. /* Try to re-extend now. */
  635. if (hs_client_reextend_intro_circuit(intro_circ) < 0) {
  636. goto close;
  637. }
  638. /* Success on re-extending. Don't return an error. */
  639. ret = 0;
  640. goto end;
  641. close:
  642. /* Change the intro circuit purpose before so we don't report an intro point
  643. * failure again triggering an extra descriptor fetch. The circuit can
  644. * already be closed on failure to re-extend. */
  645. if (!TO_CIRCUIT(intro_circ)->marked_for_close) {
  646. circuit_change_purpose(TO_CIRCUIT(intro_circ),
  647. CIRCUIT_PURPOSE_C_INTRODUCE_ACKED);
  648. circuit_mark_for_close(TO_CIRCUIT(intro_circ), END_CIRC_REASON_FINISHED);
  649. }
  650. /* Close the related rendezvous circuit. */
  651. rend_circ = hs_circuitmap_get_rend_circ_client_side(
  652. intro_circ->hs_ident->rendezvous_cookie);
  653. /* The rendezvous circuit might have collapsed while the INTRODUCE_ACK was
  654. * inflight so we can't expect one every time. */
  655. if (rend_circ) {
  656. circuit_mark_for_close(TO_CIRCUIT(rend_circ), END_CIRC_REASON_FINISHED);
  657. }
  658. end:
  659. return ret;
  660. }
  661. /* Called when we get an INTRODUCE_ACK success status code. Do the appropriate
  662. * actions for the rendezvous point and finally close intro_circ. */
  663. static void
  664. handle_introduce_ack_success(origin_circuit_t *intro_circ)
  665. {
  666. origin_circuit_t *rend_circ = NULL;
  667. tor_assert(intro_circ);
  668. log_info(LD_REND, "Received INTRODUCE_ACK ack! Informing rendezvous");
  669. /* Get the rendezvous circuit for this rendezvous cookie. */
  670. uint8_t *rendezvous_cookie = intro_circ->hs_ident->rendezvous_cookie;
  671. rend_circ = hs_circuitmap_get_rend_circ_client_side(rendezvous_cookie);
  672. if (rend_circ == NULL) {
  673. log_warn(LD_REND, "Can't find any rendezvous circuit. Stopping");
  674. goto end;
  675. }
  676. assert_circ_anonymity_ok(rend_circ, get_options());
  677. /* It is possible to get a RENDEZVOUS2 cell before the INTRODUCE_ACK which
  678. * means that the circuit will be joined and already transmitting data. In
  679. * that case, simply skip the purpose change and close the intro circuit
  680. * like it should be. */
  681. if (TO_CIRCUIT(rend_circ)->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
  682. goto end;
  683. }
  684. circuit_change_purpose(TO_CIRCUIT(rend_circ),
  685. CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED);
  686. /* Set timestamp_dirty, because circuit_expire_building expects it to
  687. * specify when a circuit entered the
  688. * CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED state. */
  689. TO_CIRCUIT(rend_circ)->timestamp_dirty = time(NULL);
  690. end:
  691. /* We don't need the intro circuit anymore. It did what it had to do! */
  692. circuit_change_purpose(TO_CIRCUIT(intro_circ),
  693. CIRCUIT_PURPOSE_C_INTRODUCE_ACKED);
  694. circuit_mark_for_close(TO_CIRCUIT(intro_circ), END_CIRC_REASON_FINISHED);
  695. /* XXX: Close pending intro circuits we might have in parallel. */
  696. return;
  697. }
  698. /* Called when we get an INTRODUCE_ACK failure status code. Depending on our
  699. * failure cache status, either close the circuit or re-extend to a new
  700. * introduction point. */
  701. static void
  702. handle_introduce_ack_bad(origin_circuit_t *circ, int status)
  703. {
  704. tor_assert(circ);
  705. log_info(LD_REND, "Received INTRODUCE_ACK nack by %s. Reason: %u",
  706. safe_str_client(extend_info_describe(circ->build_state->chosen_exit)),
  707. status);
  708. /* It's a NAK. The introduction point didn't relay our request. */
  709. circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_C_INTRODUCING);
  710. /* Note down this failure in the intro point failure cache. Depending on how
  711. * many times we've tried this intro point, close it or reextend. */
  712. hs_cache_client_intro_state_note(&circ->hs_ident->identity_pk,
  713. &circ->hs_ident->intro_auth_pk,
  714. INTRO_POINT_FAILURE_GENERIC);
  715. }
  716. /* Called when we get an INTRODUCE_ACK on the intro circuit circ. The encoded
  717. * cell is in payload of length payload_len. Return 0 on success else a
  718. * negative value. The circuit is either close or reuse to re-extend to a new
  719. * introduction point. */
  720. static int
  721. handle_introduce_ack(origin_circuit_t *circ, const uint8_t *payload,
  722. size_t payload_len)
  723. {
  724. int status, ret = -1;
  725. tor_assert(circ);
  726. tor_assert(circ->build_state);
  727. tor_assert(circ->build_state->chosen_exit);
  728. assert_circ_anonymity_ok(circ, get_options());
  729. tor_assert(payload);
  730. status = hs_cell_parse_introduce_ack(payload, payload_len);
  731. switch (status) {
  732. case HS_CELL_INTRO_ACK_SUCCESS:
  733. ret = 0;
  734. handle_introduce_ack_success(circ);
  735. goto end;
  736. case HS_CELL_INTRO_ACK_FAILURE:
  737. case HS_CELL_INTRO_ACK_BADFMT:
  738. case HS_CELL_INTRO_ACK_NORELAY:
  739. handle_introduce_ack_bad(circ, status);
  740. /* We are going to see if we have to close the circuits (IP and RP) or we
  741. * can re-extend to a new intro point. */
  742. ret = close_or_reextend_intro_circ(circ);
  743. break;
  744. default:
  745. log_info(LD_PROTOCOL, "Unknown INTRODUCE_ACK status code %u from %s",
  746. status,
  747. safe_str_client(extend_info_describe(circ->build_state->chosen_exit)));
  748. break;
  749. }
  750. end:
  751. return ret;
  752. }
  753. /* Called when we get a RENDEZVOUS2 cell on the rendezvous circuit circ. The
  754. * encoded cell is in payload of length payload_len. Return 0 on success or a
  755. * negative value on error. On error, the circuit is marked for close. */
  756. STATIC int
  757. handle_rendezvous2(origin_circuit_t *circ, const uint8_t *payload,
  758. size_t payload_len)
  759. {
  760. int ret = -1;
  761. curve25519_public_key_t server_pk;
  762. uint8_t auth_mac[DIGEST256_LEN] = {0};
  763. uint8_t handshake_info[CURVE25519_PUBKEY_LEN + sizeof(auth_mac)] = {0};
  764. hs_ntor_rend_cell_keys_t keys;
  765. const hs_ident_circuit_t *ident;
  766. tor_assert(circ);
  767. tor_assert(payload);
  768. /* Make things easier. */
  769. ident = circ->hs_ident;
  770. tor_assert(ident);
  771. if (hs_cell_parse_rendezvous2(payload, payload_len, handshake_info,
  772. sizeof(handshake_info)) < 0) {
  773. goto err;
  774. }
  775. /* Get from the handshake info the SERVER_PK and AUTH_MAC. */
  776. memcpy(&server_pk, handshake_info, CURVE25519_PUBKEY_LEN);
  777. memcpy(auth_mac, handshake_info + CURVE25519_PUBKEY_LEN, sizeof(auth_mac));
  778. /* Generate the handshake info. */
  779. if (hs_ntor_client_get_rendezvous1_keys(&ident->intro_auth_pk,
  780. &ident->rendezvous_client_kp,
  781. &ident->intro_enc_pk, &server_pk,
  782. &keys) < 0) {
  783. log_info(LD_REND, "Unable to compute the rendezvous keys.");
  784. goto err;
  785. }
  786. /* Critical check, make sure that the MAC matches what we got with what we
  787. * computed just above. */
  788. if (!hs_ntor_client_rendezvous2_mac_is_good(&keys, auth_mac)) {
  789. log_info(LD_REND, "Invalid MAC in RENDEZVOUS2. Rejecting cell.");
  790. goto err;
  791. }
  792. /* Setup the e2e encryption on the circuit and finalize its state. */
  793. if (hs_circuit_setup_e2e_rend_circ(circ, keys.ntor_key_seed,
  794. sizeof(keys.ntor_key_seed), 0) < 0) {
  795. log_info(LD_REND, "Unable to setup the e2e encryption.");
  796. goto err;
  797. }
  798. /* Success. Hidden service connection finalized! */
  799. ret = 0;
  800. goto end;
  801. err:
  802. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  803. end:
  804. memwipe(&keys, 0, sizeof(keys));
  805. return ret;
  806. }
  807. /* ========== */
  808. /* Public API */
  809. /* ========== */
  810. /** A circuit just finished connecting to a hidden service that the stream
  811. * <b>conn</b> has been waiting for. Let the HS subsystem know about this. */
  812. void
  813. hs_client_note_connection_attempt_succeeded(const edge_connection_t *conn)
  814. {
  815. tor_assert(connection_edge_is_rendezvous_stream(conn));
  816. if (BUG(conn->rend_data && conn->hs_ident)) {
  817. log_warn(LD_BUG, "Stream had both rend_data and hs_ident..."
  818. "Prioritizing hs_ident");
  819. }
  820. if (conn->hs_ident) { /* It's v3: pass it to the prop224 handler */
  821. note_connection_attempt_succeeded(conn->hs_ident);
  822. return;
  823. } else if (conn->rend_data) { /* It's v2: pass it to the legacy handler */
  824. rend_client_note_connection_attempt_ended(conn->rend_data);
  825. return;
  826. }
  827. }
  828. /* With the given encoded descriptor in desc_str and the service key in
  829. * service_identity_pk, decode the descriptor and set the desc pointer with a
  830. * newly allocated descriptor object.
  831. *
  832. * Return 0 on success else a negative value and desc is set to NULL. */
  833. int
  834. hs_client_decode_descriptor(const char *desc_str,
  835. const ed25519_public_key_t *service_identity_pk,
  836. hs_descriptor_t **desc)
  837. {
  838. int ret;
  839. uint8_t subcredential[DIGEST256_LEN];
  840. ed25519_public_key_t blinded_pubkey;
  841. tor_assert(desc_str);
  842. tor_assert(service_identity_pk);
  843. tor_assert(desc);
  844. /* Create subcredential for this HS so that we can decrypt */
  845. {
  846. uint64_t current_time_period = hs_get_time_period_num(0);
  847. hs_build_blinded_pubkey(service_identity_pk, NULL, 0, current_time_period,
  848. &blinded_pubkey);
  849. hs_get_subcredential(service_identity_pk, &blinded_pubkey, subcredential);
  850. }
  851. /* Parse descriptor */
  852. ret = hs_desc_decode_descriptor(desc_str, subcredential, desc);
  853. memwipe(subcredential, 0, sizeof(subcredential));
  854. if (ret < 0) {
  855. log_warn(LD_GENERAL, "Could not parse received descriptor as client.");
  856. if (get_options()->SafeLogging_ == SAFELOG_SCRUB_NONE) {
  857. log_warn(LD_GENERAL, "%s", escaped(desc_str));
  858. }
  859. goto err;
  860. }
  861. /* Make sure the descriptor signing key cross certifies with the computed
  862. * blinded key. Without this validation, anyone knowing the subcredential
  863. * and onion address can forge a descriptor. */
  864. if (tor_cert_checksig((*desc)->plaintext_data.signing_key_cert,
  865. &blinded_pubkey, approx_time()) < 0) {
  866. log_warn(LD_GENERAL, "Descriptor signing key certificate signature "
  867. "doesn't validate with computed blinded key.");
  868. goto err;
  869. }
  870. return 0;
  871. err:
  872. return -1;
  873. }
  874. /* Return true iff there are at least one usable intro point in the service
  875. * descriptor desc. */
  876. int
  877. hs_client_any_intro_points_usable(const ed25519_public_key_t *service_pk,
  878. const hs_descriptor_t *desc)
  879. {
  880. tor_assert(service_pk);
  881. tor_assert(desc);
  882. SMARTLIST_FOREACH_BEGIN(desc->encrypted_data.intro_points,
  883. const hs_desc_intro_point_t *, ip) {
  884. if (intro_point_is_usable(service_pk, ip)) {
  885. goto usable;
  886. }
  887. } SMARTLIST_FOREACH_END(ip);
  888. return 0;
  889. usable:
  890. return 1;
  891. }
  892. /** Launch a connection to a hidden service directory to fetch a hidden
  893. * service descriptor using <b>identity_pk</b> to get the necessary keys.
  894. *
  895. * A hs_client_fetch_status_t code is returned. */
  896. int
  897. hs_client_refetch_hsdesc(const ed25519_public_key_t *identity_pk)
  898. {
  899. tor_assert(identity_pk);
  900. /* Are we configured to fetch descriptors? */
  901. if (!get_options()->FetchHidServDescriptors) {
  902. log_warn(LD_REND, "We received an onion address for a hidden service "
  903. "descriptor but we are configured to not fetch.");
  904. return HS_CLIENT_FETCH_NOT_ALLOWED;
  905. }
  906. /* Without a live consensus we can't do any client actions. It is needed to
  907. * compute the hashring for a service. */
  908. if (!networkstatus_get_live_consensus(approx_time())) {
  909. log_info(LD_REND, "Can't fetch descriptor for service %s because we "
  910. "are missing a live consensus. Stalling connection.",
  911. safe_str_client(ed25519_fmt(identity_pk)));
  912. return HS_CLIENT_FETCH_MISSING_INFO;
  913. }
  914. if (!router_have_minimum_dir_info()) {
  915. log_info(LD_REND, "Can't fetch descriptor for service %s because we "
  916. "dont have enough descriptors. Stalling connection.",
  917. safe_str_client(ed25519_fmt(identity_pk)));
  918. return HS_CLIENT_FETCH_MISSING_INFO;
  919. }
  920. /* Check if fetching a desc for this HS is useful to us right now */
  921. {
  922. const hs_descriptor_t *cached_desc = NULL;
  923. cached_desc = hs_cache_lookup_as_client(identity_pk);
  924. if (cached_desc && hs_client_any_intro_points_usable(identity_pk,
  925. cached_desc)) {
  926. log_info(LD_GENERAL, "We would fetch a v3 hidden service descriptor "
  927. "but we already have a usable descriptor.");
  928. return HS_CLIENT_FETCH_HAVE_DESC;
  929. }
  930. }
  931. /* Don't try to refetch while we have a pending request for it. */
  932. if (directory_request_is_pending(identity_pk)) {
  933. log_info(LD_REND, "Already a pending directory request. Waiting on it.");
  934. return HS_CLIENT_FETCH_PENDING;
  935. }
  936. return fetch_v3_desc(identity_pk);
  937. }
  938. /* This is called when we are trying to attach an AP connection to these
  939. * hidden service circuits from connection_ap_handshake_attach_circuit().
  940. * Return 0 on success, -1 for a transient error that is actions were
  941. * triggered to recover or -2 for a permenent error where both circuits will
  942. * marked for close.
  943. *
  944. * The following supports every hidden service version. */
  945. int
  946. hs_client_send_introduce1(origin_circuit_t *intro_circ,
  947. origin_circuit_t *rend_circ)
  948. {
  949. return (intro_circ->hs_ident) ? send_introduce1(intro_circ, rend_circ) :
  950. rend_client_send_introduction(intro_circ,
  951. rend_circ);
  952. }
  953. /* Called when the client circuit circ has been established. It can be either
  954. * an introduction or rendezvous circuit. This function handles all hidden
  955. * service versions. */
  956. void
  957. hs_client_circuit_has_opened(origin_circuit_t *circ)
  958. {
  959. tor_assert(circ);
  960. /* Handle both version. v2 uses rend_data and v3 uses the hs circuit
  961. * identifier hs_ident. Can't be both. */
  962. switch (TO_CIRCUIT(circ)->purpose) {
  963. case CIRCUIT_PURPOSE_C_INTRODUCING:
  964. if (circ->hs_ident) {
  965. client_intro_circ_has_opened(circ);
  966. } else {
  967. rend_client_introcirc_has_opened(circ);
  968. }
  969. break;
  970. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  971. if (circ->hs_ident) {
  972. client_rendezvous_circ_has_opened(circ);
  973. } else {
  974. rend_client_rendcirc_has_opened(circ);
  975. }
  976. break;
  977. default:
  978. tor_assert_nonfatal_unreached();
  979. }
  980. }
  981. /* Called when we receive a RENDEZVOUS_ESTABLISHED cell. Change the state of
  982. * the circuit to CIRCUIT_PURPOSE_C_REND_READY. Return 0 on success else a
  983. * negative value and the circuit marked for close. */
  984. int
  985. hs_client_receive_rendezvous_acked(origin_circuit_t *circ,
  986. const uint8_t *payload, size_t payload_len)
  987. {
  988. tor_assert(circ);
  989. tor_assert(payload);
  990. (void) payload_len;
  991. if (TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND) {
  992. log_warn(LD_PROTOCOL, "Got a RENDEZVOUS_ESTABLISHED but we were not "
  993. "expecting one. Closing circuit.");
  994. goto err;
  995. }
  996. log_info(LD_REND, "Received an RENDEZVOUS_ESTABLISHED. This circuit is "
  997. "now ready for rendezvous.");
  998. circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_C_REND_READY);
  999. /* Set timestamp_dirty, because circuit_expire_building expects it to
  1000. * specify when a circuit entered the _C_REND_READY state. */
  1001. TO_CIRCUIT(circ)->timestamp_dirty = time(NULL);
  1002. /* From a path bias point of view, this circuit is now successfully used.
  1003. * Waiting any longer opens us up to attacks from malicious hidden services.
  1004. * They could induce the client to attempt to connect to their hidden
  1005. * service and never reply to the client's rend requests */
  1006. pathbias_mark_use_success(circ);
  1007. /* If we already have the introduction circuit built, make sure we send
  1008. * the INTRODUCE cell _now_ */
  1009. connection_ap_attach_pending(1);
  1010. return 0;
  1011. err:
  1012. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  1013. return -1;
  1014. }
  1015. /* This is called when a descriptor has arrived following a fetch request and
  1016. * has been stored in the client cache. Every entry connection that matches
  1017. * the service identity key in the ident will get attached to the hidden
  1018. * service circuit. */
  1019. void
  1020. hs_client_desc_has_arrived(const hs_ident_dir_conn_t *ident)
  1021. {
  1022. time_t now = time(NULL);
  1023. smartlist_t *conns = NULL;
  1024. tor_assert(ident);
  1025. conns = connection_list_by_type_state(CONN_TYPE_AP,
  1026. AP_CONN_STATE_RENDDESC_WAIT);
  1027. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  1028. const hs_descriptor_t *desc;
  1029. entry_connection_t *entry_conn = TO_ENTRY_CONN(base_conn);
  1030. const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(entry_conn);
  1031. /* Only consider the entry connections that matches the service for which
  1032. * we just fetched its descriptor. */
  1033. if (!edge_conn->hs_ident ||
  1034. !ed25519_pubkey_eq(&ident->identity_pk,
  1035. &edge_conn->hs_ident->identity_pk)) {
  1036. continue;
  1037. }
  1038. assert_connection_ok(base_conn, now);
  1039. /* We were just called because we stored the descriptor for this service
  1040. * so not finding a descriptor means we have a bigger problem. */
  1041. desc = hs_cache_lookup_as_client(&ident->identity_pk);
  1042. if (BUG(desc == NULL)) {
  1043. goto end;
  1044. }
  1045. if (!hs_client_any_intro_points_usable(&ident->identity_pk, desc)) {
  1046. log_info(LD_REND, "Hidden service descriptor is unusable. "
  1047. "Closing streams.");
  1048. connection_mark_unattached_ap(entry_conn,
  1049. END_STREAM_REASON_RESOLVEFAILED);
  1050. /* We are unable to use the descriptor so remove the directory request
  1051. * from the cache so the next connection can try again. */
  1052. note_connection_attempt_succeeded(edge_conn->hs_ident);
  1053. goto end;
  1054. }
  1055. log_info(LD_REND, "Descriptor has arrived. Launching circuits.");
  1056. /* Because the connection can now proceed to opening circuit and
  1057. * ultimately connect to the service, reset those timestamp so the
  1058. * connection is considered "fresh" and can continue without being closed
  1059. * too early. */
  1060. base_conn->timestamp_created = now;
  1061. base_conn->timestamp_lastread = now;
  1062. base_conn->timestamp_lastwritten = now;
  1063. /* Change connection's state into waiting for a circuit. */
  1064. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1065. connection_ap_mark_as_pending_circuit(entry_conn);
  1066. } SMARTLIST_FOREACH_END(base_conn);
  1067. end:
  1068. /* We don't have ownership of the objects in this list. */
  1069. smartlist_free(conns);
  1070. }
  1071. /* Return a newly allocated extend_info_t for a randomly chosen introduction
  1072. * point for the given edge connection identifier ident. Return NULL if we
  1073. * can't pick any usable introduction points. */
  1074. extend_info_t *
  1075. hs_client_get_random_intro_from_edge(const edge_connection_t *edge_conn)
  1076. {
  1077. tor_assert(edge_conn);
  1078. return (edge_conn->hs_ident) ?
  1079. client_get_random_intro(&edge_conn->hs_ident->identity_pk) :
  1080. rend_client_get_random_intro(edge_conn->rend_data);
  1081. }
  1082. /* Called when get an INTRODUCE_ACK cell on the introduction circuit circ.
  1083. * Return 0 on success else a negative value is returned. The circuit will be
  1084. * closed or reuse to extend again to another intro point. */
  1085. int
  1086. hs_client_receive_introduce_ack(origin_circuit_t *circ,
  1087. const uint8_t *payload, size_t payload_len)
  1088. {
  1089. int ret = -1;
  1090. tor_assert(circ);
  1091. tor_assert(payload);
  1092. if (TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
  1093. log_warn(LD_PROTOCOL, "Unexpected INTRODUCE_ACK on circuit %u.",
  1094. (unsigned int) TO_CIRCUIT(circ)->n_circ_id);
  1095. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  1096. goto end;
  1097. }
  1098. ret = (circ->hs_ident) ? handle_introduce_ack(circ, payload, payload_len) :
  1099. rend_client_introduction_acked(circ, payload,
  1100. payload_len);
  1101. /* For path bias: This circuit was used successfully. NACK or ACK counts. */
  1102. pathbias_mark_use_success(circ);
  1103. end:
  1104. return ret;
  1105. }
  1106. /* Called when get a RENDEZVOUS2 cell on the rendezvous circuit circ. Return
  1107. * 0 on success else a negative value is returned. The circuit will be closed
  1108. * on error. */
  1109. int
  1110. hs_client_receive_rendezvous2(origin_circuit_t *circ,
  1111. const uint8_t *payload, size_t payload_len)
  1112. {
  1113. int ret = -1;
  1114. tor_assert(circ);
  1115. tor_assert(payload);
  1116. /* Circuit can possibly be in both state because we could receive a
  1117. * RENDEZVOUS2 cell before the INTRODUCE_ACK has been received. */
  1118. if (TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
  1119. TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
  1120. log_warn(LD_PROTOCOL, "Unexpected RENDEZVOUS2 cell on circuit %u. "
  1121. "Closing circuit.",
  1122. (unsigned int) TO_CIRCUIT(circ)->n_circ_id);
  1123. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  1124. goto end;
  1125. }
  1126. log_info(LD_REND, "Got RENDEZVOUS2 cell from hidden service on circuit %u.",
  1127. TO_CIRCUIT(circ)->n_circ_id);
  1128. ret = (circ->hs_ident) ? handle_rendezvous2(circ, payload, payload_len) :
  1129. rend_client_receive_rendezvous(circ, payload,
  1130. payload_len);
  1131. end:
  1132. return ret;
  1133. }
  1134. /* Extend the introduction circuit circ to another valid introduction point
  1135. * for the hidden service it is trying to connect to, or mark it and launch a
  1136. * new circuit if we can't extend it. Return 0 on success or possible
  1137. * success. Return -1 and mark the introduction circuit for close on permanent
  1138. * failure.
  1139. *
  1140. * On failure, the caller is responsible for marking the associated rendezvous
  1141. * circuit for close. */
  1142. int
  1143. hs_client_reextend_intro_circuit(origin_circuit_t *circ)
  1144. {
  1145. int ret = -1;
  1146. extend_info_t *ei;
  1147. tor_assert(circ);
  1148. ei = (circ->hs_ident) ?
  1149. client_get_random_intro(&circ->hs_ident->identity_pk) :
  1150. rend_client_get_random_intro(circ->rend_data);
  1151. if (ei == NULL) {
  1152. log_warn(LD_REND, "No usable introduction points left. Closing.");
  1153. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
  1154. goto end;
  1155. }
  1156. if (circ->remaining_relay_early_cells) {
  1157. log_info(LD_REND, "Re-extending circ %u, this time to %s.",
  1158. (unsigned int) TO_CIRCUIT(circ)->n_circ_id,
  1159. safe_str_client(extend_info_describe(ei)));
  1160. ret = circuit_extend_to_new_exit(circ, ei);
  1161. if (ret == 0) {
  1162. /* We were able to extend so update the timestamp so we avoid expiring
  1163. * this circuit too early. The intro circuit is short live so the
  1164. * linkability issue is minimized, we just need the circuit to hold a
  1165. * bit longer so we can introduce. */
  1166. TO_CIRCUIT(circ)->timestamp_dirty = time(NULL);
  1167. }
  1168. } else {
  1169. log_info(LD_REND, "Closing intro circ %u (out of RELAY_EARLY cells).",
  1170. (unsigned int) TO_CIRCUIT(circ)->n_circ_id);
  1171. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  1172. /* connection_ap_handshake_attach_circuit will launch a new intro circ. */
  1173. ret = 0;
  1174. }
  1175. end:
  1176. extend_info_free(ei);
  1177. return ret;
  1178. }
  1179. /* Release all the storage held by the client subsystem. */
  1180. void
  1181. hs_client_free_all(void)
  1182. {
  1183. /* Purge the hidden service request cache. */
  1184. hs_purge_last_hid_serv_requests();
  1185. }
  1186. /* Purge all potentially remotely-detectable state held in the hidden
  1187. * service client code. Called on SIGNAL NEWNYM. */
  1188. void
  1189. hs_client_purge_state(void)
  1190. {
  1191. /* v2 subsystem. */
  1192. rend_client_purge_state();
  1193. /* Cancel all descriptor fetches. Do this first so once done we are sure
  1194. * that our descriptor cache won't modified. */
  1195. cancel_descriptor_fetches();
  1196. /* Purge the introduction point state cache. */
  1197. hs_cache_client_intro_state_purge();
  1198. /* Purge the descriptor cache. */
  1199. hs_cache_purge_as_client();
  1200. /* Purge the last hidden service request cache. */
  1201. hs_purge_last_hid_serv_requests();
  1202. log_info(LD_REND, "Hidden service client state has been purged.");
  1203. }