hs_client.c 57 KB

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