hs_client.c 66 KB

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