hs_client.c 56 KB

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