hs_client.c 48 KB

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