hs_client.c 70 KB

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