hs_client.c 68 KB

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