hs_client.c 68 KB

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