hs_client.c 71 KB

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