hs_client.c 66 KB

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