hs_client.c 57 KB

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