hs_client.c 75 KB

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