hs-v3: Remove BUG() that can occur normally
[tor.git] / src / feature / hs / hs_client.c
blobb045e1899b4a0337786665d4b3710b787ed8548e
1 /* Copyright (c) 2016-2019, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
4 /**
5 * \file hs_client.c
6 * \brief Implement next generation hidden service client functionality
7 **/
9 #define HS_CLIENT_PRIVATE
11 #include "core/or/or.h"
12 #include "app/config/config.h"
13 #include "core/crypto/hs_ntor.h"
14 #include "core/mainloop/connection.h"
15 #include "core/or/circuitbuild.h"
16 #include "core/or/circuitlist.h"
17 #include "core/or/circuituse.h"
18 #include "core/or/connection_edge.h"
19 #include "core/or/reasons.h"
20 #include "feature/client/circpathbias.h"
21 #include "feature/dirclient/dirclient.h"
22 #include "feature/dircommon/directory.h"
23 #include "feature/hs/hs_cache.h"
24 #include "feature/hs/hs_cell.h"
25 #include "feature/hs/hs_circuit.h"
26 #include "feature/hs/hs_circuitmap.h"
27 #include "feature/hs/hs_client.h"
28 #include "feature/hs/hs_control.h"
29 #include "feature/hs/hs_descriptor.h"
30 #include "feature/hs/hs_ident.h"
31 #include "feature/nodelist/describe.h"
32 #include "feature/nodelist/networkstatus.h"
33 #include "feature/nodelist/nodelist.h"
34 #include "feature/nodelist/routerset.h"
35 #include "feature/rend/rendclient.h"
36 #include "lib/crypt_ops/crypto_format.h"
37 #include "lib/crypt_ops/crypto_rand.h"
38 #include "lib/crypt_ops/crypto_util.h"
40 #include "core/or/cpath_build_state_st.h"
41 #include "feature/dircommon/dir_connection_st.h"
42 #include "core/or/entry_connection_st.h"
43 #include "core/or/extend_info_st.h"
44 #include "core/or/origin_circuit_st.h"
46 /* Client-side authorizations for hidden services; map of service identity
47 * public key to hs_client_service_authorization_t *. */
48 static digest256map_t *client_auths = NULL;
50 #include "trunnel/hs/cell_introduce1.h"
52 /* Return a human-readable string for the client fetch status code. */
53 static const char *
54 fetch_status_to_string(hs_client_fetch_status_t status)
56 switch (status) {
57 case HS_CLIENT_FETCH_ERROR:
58 return "Internal error";
59 case HS_CLIENT_FETCH_LAUNCHED:
60 return "Descriptor fetch launched";
61 case HS_CLIENT_FETCH_HAVE_DESC:
62 return "Already have descriptor";
63 case HS_CLIENT_FETCH_NO_HSDIRS:
64 return "No more HSDir available to query";
65 case HS_CLIENT_FETCH_NOT_ALLOWED:
66 return "Fetching descriptors is not allowed";
67 case HS_CLIENT_FETCH_MISSING_INFO:
68 return "Missing directory information";
69 case HS_CLIENT_FETCH_PENDING:
70 return "Pending descriptor fetch";
71 default:
72 return "(Unknown client fetch status code)";
76 /* Return true iff tor should close the SOCKS request(s) for the descriptor
77 * fetch that ended up with this given status code. */
78 static int
79 fetch_status_should_close_socks(hs_client_fetch_status_t status)
81 switch (status) {
82 case HS_CLIENT_FETCH_NO_HSDIRS:
83 /* No more HSDir to query, we can't complete the SOCKS request(s). */
84 case HS_CLIENT_FETCH_ERROR:
85 /* The fetch triggered an internal error. */
86 case HS_CLIENT_FETCH_NOT_ALLOWED:
87 /* Client is not allowed to fetch (FetchHidServDescriptors 0). */
88 goto close;
89 case HS_CLIENT_FETCH_MISSING_INFO:
90 case HS_CLIENT_FETCH_HAVE_DESC:
91 case HS_CLIENT_FETCH_PENDING:
92 case HS_CLIENT_FETCH_LAUNCHED:
93 /* The rest doesn't require tor to close the SOCKS request(s). */
94 goto no_close;
97 no_close:
98 return 0;
99 close:
100 return 1;
103 /* Cancel all descriptor fetches currently in progress. */
104 static void
105 cancel_descriptor_fetches(void)
107 smartlist_t *conns =
108 connection_list_by_type_state(CONN_TYPE_DIR, DIR_PURPOSE_FETCH_HSDESC);
109 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
110 const hs_ident_dir_conn_t *ident = TO_DIR_CONN(conn)->hs_ident;
111 if (BUG(ident == NULL)) {
112 /* A directory connection fetching a service descriptor can't have an
113 * empty hidden service identifier. */
114 continue;
116 log_debug(LD_REND, "Marking for close a directory connection fetching "
117 "a hidden service descriptor for service %s.",
118 safe_str_client(ed25519_fmt(&ident->identity_pk)));
119 connection_mark_for_close(conn);
120 } SMARTLIST_FOREACH_END(conn);
122 /* No ownership of the objects in this list. */
123 smartlist_free(conns);
124 log_info(LD_REND, "Hidden service client descriptor fetches cancelled.");
127 /* Get all connections that are waiting on a circuit and flag them back to
128 * waiting for a hidden service descriptor for the given service key
129 * service_identity_pk. */
130 static void
131 flag_all_conn_wait_desc(const ed25519_public_key_t *service_identity_pk)
133 tor_assert(service_identity_pk);
135 smartlist_t *conns =
136 connection_list_by_type_state(CONN_TYPE_AP, AP_CONN_STATE_CIRCUIT_WAIT);
138 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
139 edge_connection_t *edge_conn;
140 if (BUG(!CONN_IS_EDGE(conn))) {
141 continue;
143 edge_conn = TO_EDGE_CONN(conn);
144 if (edge_conn->hs_ident &&
145 ed25519_pubkey_eq(&edge_conn->hs_ident->identity_pk,
146 service_identity_pk)) {
147 connection_ap_mark_as_waiting_for_renddesc(TO_ENTRY_CONN(conn));
149 } SMARTLIST_FOREACH_END(conn);
151 smartlist_free(conns);
154 /* Remove tracked HSDir requests from our history for this hidden service
155 * identity public key. */
156 static void
157 purge_hid_serv_request(const ed25519_public_key_t *identity_pk)
159 char base64_blinded_pk[ED25519_BASE64_LEN + 1];
160 ed25519_public_key_t blinded_pk;
162 tor_assert(identity_pk);
164 /* Get blinded pubkey of hidden service. It is possible that we just moved
165 * to a new time period meaning that we won't be able to purge the request
166 * from the previous time period. That is fine because they will expire at
167 * some point and we don't care about those anymore. */
168 hs_build_blinded_pubkey(identity_pk, NULL, 0,
169 hs_get_time_period_num(0), &blinded_pk);
170 if (BUG(ed25519_public_to_base64(base64_blinded_pk, &blinded_pk) < 0)) {
171 return;
173 /* Purge last hidden service request from cache for this blinded key. */
174 hs_purge_hid_serv_from_last_hid_serv_requests(base64_blinded_pk);
177 /* Return true iff there is at least one pending directory descriptor request
178 * for the service identity_pk. */
179 static int
180 directory_request_is_pending(const ed25519_public_key_t *identity_pk)
182 int ret = 0;
183 smartlist_t *conns =
184 connection_list_by_type_purpose(CONN_TYPE_DIR, DIR_PURPOSE_FETCH_HSDESC);
186 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
187 const hs_ident_dir_conn_t *ident = TO_DIR_CONN(conn)->hs_ident;
188 if (BUG(ident == NULL)) {
189 /* A directory connection fetching a service descriptor can't have an
190 * empty hidden service identifier. */
191 continue;
193 if (!ed25519_pubkey_eq(identity_pk, &ident->identity_pk)) {
194 continue;
196 ret = 1;
197 break;
198 } SMARTLIST_FOREACH_END(conn);
200 /* No ownership of the objects in this list. */
201 smartlist_free(conns);
202 return ret;
205 /* Helper function that changes the state of an entry connection to waiting
206 * for a circuit. For this to work properly, the connection timestamps are set
207 * to now and the connection is then marked as pending for a circuit. */
208 static void
209 mark_conn_as_waiting_for_circuit(connection_t *conn, time_t now)
211 tor_assert(conn);
213 /* Because the connection can now proceed to opening circuit and ultimately
214 * connect to the service, reset those timestamp so the connection is
215 * considered "fresh" and can continue without being closed too early. */
216 conn->timestamp_created = now;
217 conn->timestamp_last_read_allowed = now;
218 conn->timestamp_last_write_allowed = now;
219 /* Change connection's state into waiting for a circuit. */
220 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
222 connection_ap_mark_as_pending_circuit(TO_ENTRY_CONN(conn));
225 /* We failed to fetch a descriptor for the service with <b>identity_pk</b>
226 * because of <b>status</b>. Find all pending SOCKS connections for this
227 * service that are waiting on the descriptor and close them with
228 * <b>reason</b>. */
229 static void
230 close_all_socks_conns_waiting_for_desc(const ed25519_public_key_t *identity_pk,
231 hs_client_fetch_status_t status,
232 int reason)
234 unsigned int count = 0;
235 time_t now = approx_time();
236 smartlist_t *conns =
237 connection_list_by_type_state(CONN_TYPE_AP, AP_CONN_STATE_RENDDESC_WAIT);
239 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
240 entry_connection_t *entry_conn = TO_ENTRY_CONN(base_conn);
241 const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(entry_conn);
243 /* Only consider the entry connections that matches the service for which
244 * we tried to get the descriptor */
245 if (!edge_conn->hs_ident ||
246 !ed25519_pubkey_eq(identity_pk,
247 &edge_conn->hs_ident->identity_pk)) {
248 continue;
250 assert_connection_ok(base_conn, now);
251 /* Unattach the entry connection which will close for the reason. */
252 connection_mark_unattached_ap(entry_conn, reason);
253 count++;
254 } SMARTLIST_FOREACH_END(base_conn);
256 if (count > 0) {
257 char onion_address[HS_SERVICE_ADDR_LEN_BASE32 + 1];
258 hs_build_address(identity_pk, HS_VERSION_THREE, onion_address);
259 log_notice(LD_REND, "Closed %u streams for service %s.onion "
260 "for reason %s. Fetch status: %s.",
261 count, safe_str_client(onion_address),
262 stream_end_reason_to_string(reason),
263 fetch_status_to_string(status));
266 /* No ownership of the object(s) in this list. */
267 smartlist_free(conns);
270 /* Find all pending SOCKS connection waiting for a descriptor and retry them
271 * all. This is called when the directory information changed. */
272 STATIC void
273 retry_all_socks_conn_waiting_for_desc(void)
275 smartlist_t *conns =
276 connection_list_by_type_state(CONN_TYPE_AP, AP_CONN_STATE_RENDDESC_WAIT);
278 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
279 hs_client_fetch_status_t status;
280 const edge_connection_t *edge_conn =
281 ENTRY_TO_EDGE_CONN(TO_ENTRY_CONN(base_conn));
283 /* Ignore non HS or non v3 connection. */
284 if (edge_conn->hs_ident == NULL) {
285 continue;
287 /* In this loop, we will possibly try to fetch a descriptor for the
288 * pending connections because we just got more directory information.
289 * However, the refetch process can cleanup all SOCKS request to the same
290 * service if an internal error happens. Thus, we can end up with closed
291 * connections in our list. */
292 if (base_conn->marked_for_close) {
293 continue;
296 /* XXX: There is an optimization we could do which is that for a service
297 * key, we could check if we can fetch and remember that decision. */
299 /* Order a refetch in case it works this time. */
300 status = hs_client_refetch_hsdesc(&edge_conn->hs_ident->identity_pk);
301 if (status == HS_CLIENT_FETCH_HAVE_DESC) {
302 /* This is a rare case where a SOCKS connection is in state waiting for
303 * a descriptor but we do have it in the cache.
305 * This can happen is tor comes back from suspend where it previously
306 * had the descriptor but the intro points were not usuable. Once it
307 * came back to life, the intro point failure cache was cleaned up and
308 * thus the descriptor became usable again leaving us in this code path.
310 * We'll mark the connection as waiting for a circuit so the descriptor
311 * can be retried. This is safe because a connection in state waiting
312 * for a descriptor can not be in the entry connection pending list. */
313 mark_conn_as_waiting_for_circuit(base_conn, approx_time());
314 continue;
316 /* In the case of an error, either all SOCKS connections have been
317 * closed or we are still missing directory information. Leave the
318 * connection in renddesc wait state so when we get more info, we'll be
319 * able to try it again. */
320 } SMARTLIST_FOREACH_END(base_conn);
322 /* We don't have ownership of those objects. */
323 smartlist_free(conns);
326 /* A v3 HS circuit successfully connected to the hidden service. Update the
327 * stream state at <b>hs_conn_ident</b> appropriately. */
328 static void
329 note_connection_attempt_succeeded(const hs_ident_edge_conn_t *hs_conn_ident)
331 tor_assert(hs_conn_ident);
333 /* Remove from the hid serv cache all requests for that service so we can
334 * query the HSDir again later on for various reasons. */
335 purge_hid_serv_request(&hs_conn_ident->identity_pk);
337 /* The v2 subsystem cleans up the intro point time out flag at this stage.
338 * We don't try to do it here because we still need to keep intact the intro
339 * point state for future connections. Even though we are able to connect to
340 * the service, doesn't mean we should reset the timed out intro points.
342 * It is not possible to have successfully connected to an intro point
343 * present in our cache that was on error or timed out. Every entry in that
344 * cache have a 2 minutes lifetime so ultimately the intro point(s) state
345 * will be reset and thus possible to be retried. */
348 /* Given the pubkey of a hidden service in <b>onion_identity_pk</b>, fetch its
349 * descriptor by launching a dir connection to <b>hsdir</b>. Return a
350 * hs_client_fetch_status_t status code depending on how it went. */
351 static hs_client_fetch_status_t
352 directory_launch_v3_desc_fetch(const ed25519_public_key_t *onion_identity_pk,
353 const routerstatus_t *hsdir)
355 uint64_t current_time_period = hs_get_time_period_num(0);
356 ed25519_public_key_t blinded_pubkey;
357 char base64_blinded_pubkey[ED25519_BASE64_LEN + 1];
358 hs_ident_dir_conn_t hs_conn_dir_ident;
359 int retval;
361 tor_assert(hsdir);
362 tor_assert(onion_identity_pk);
364 /* Get blinded pubkey */
365 hs_build_blinded_pubkey(onion_identity_pk, NULL, 0,
366 current_time_period, &blinded_pubkey);
367 /* ...and base64 it. */
368 retval = ed25519_public_to_base64(base64_blinded_pubkey, &blinded_pubkey);
369 if (BUG(retval < 0)) {
370 return HS_CLIENT_FETCH_ERROR;
373 /* Copy onion pk to a dir_ident so that we attach it to the dir conn */
374 hs_ident_dir_conn_init(onion_identity_pk, &blinded_pubkey,
375 &hs_conn_dir_ident);
377 /* Setup directory request */
378 directory_request_t *req =
379 directory_request_new(DIR_PURPOSE_FETCH_HSDESC);
380 directory_request_set_routerstatus(req, hsdir);
381 directory_request_set_indirection(req, DIRIND_ANONYMOUS);
382 directory_request_set_resource(req, base64_blinded_pubkey);
383 directory_request_fetch_set_hs_ident(req, &hs_conn_dir_ident);
384 directory_initiate_request(req);
385 directory_request_free(req);
387 log_info(LD_REND, "Descriptor fetch request for service %s with blinded "
388 "key %s to directory %s",
389 safe_str_client(ed25519_fmt(onion_identity_pk)),
390 safe_str_client(base64_blinded_pubkey),
391 safe_str_client(routerstatus_describe(hsdir)));
393 /* Fire a REQUESTED event on the control port. */
394 hs_control_desc_event_requested(onion_identity_pk, base64_blinded_pubkey,
395 hsdir);
397 /* Cleanup memory. */
398 memwipe(&blinded_pubkey, 0, sizeof(blinded_pubkey));
399 memwipe(base64_blinded_pubkey, 0, sizeof(base64_blinded_pubkey));
400 memwipe(&hs_conn_dir_ident, 0, sizeof(hs_conn_dir_ident));
402 return HS_CLIENT_FETCH_LAUNCHED;
405 /** Return the HSDir we should use to fetch the descriptor of the hidden
406 * service with identity key <b>onion_identity_pk</b>. */
407 STATIC routerstatus_t *
408 pick_hsdir_v3(const ed25519_public_key_t *onion_identity_pk)
410 int retval;
411 char base64_blinded_pubkey[ED25519_BASE64_LEN + 1];
412 uint64_t current_time_period = hs_get_time_period_num(0);
413 smartlist_t *responsible_hsdirs = NULL;
414 ed25519_public_key_t blinded_pubkey;
415 routerstatus_t *hsdir_rs = NULL;
417 tor_assert(onion_identity_pk);
419 /* Get blinded pubkey of hidden service */
420 hs_build_blinded_pubkey(onion_identity_pk, NULL, 0,
421 current_time_period, &blinded_pubkey);
422 /* ...and base64 it. */
423 retval = ed25519_public_to_base64(base64_blinded_pubkey, &blinded_pubkey);
424 if (BUG(retval < 0)) {
425 return NULL;
428 /* Get responsible hsdirs of service for this time period */
429 responsible_hsdirs = smartlist_new();
431 hs_get_responsible_hsdirs(&blinded_pubkey, current_time_period,
432 0, 1, responsible_hsdirs);
434 log_debug(LD_REND, "Found %d responsible HSDirs and about to pick one.",
435 smartlist_len(responsible_hsdirs));
437 /* Pick an HSDir from the responsible ones. The ownership of
438 * responsible_hsdirs is given to this function so no need to free it. */
439 hsdir_rs = hs_pick_hsdir(responsible_hsdirs, base64_blinded_pubkey);
441 return hsdir_rs;
444 /** Fetch a v3 descriptor using the given <b>onion_identity_pk</b>.
446 * On success, HS_CLIENT_FETCH_LAUNCHED is returned. Otherwise, an error from
447 * hs_client_fetch_status_t is returned. */
448 MOCK_IMPL(STATIC hs_client_fetch_status_t,
449 fetch_v3_desc, (const ed25519_public_key_t *onion_identity_pk))
451 routerstatus_t *hsdir_rs =NULL;
453 tor_assert(onion_identity_pk);
455 hsdir_rs = pick_hsdir_v3(onion_identity_pk);
456 if (!hsdir_rs) {
457 log_info(LD_REND, "Couldn't pick a v3 hsdir.");
458 return HS_CLIENT_FETCH_NO_HSDIRS;
461 return directory_launch_v3_desc_fetch(onion_identity_pk, hsdir_rs);
464 /* Make sure that the given v3 origin circuit circ is a valid correct
465 * introduction circuit. This will BUG() on any problems and hard assert if
466 * the anonymity of the circuit is not ok. Return 0 on success else -1 where
467 * the circuit should be mark for closed immediately. */
468 static int
469 intro_circ_is_ok(const origin_circuit_t *circ)
471 int ret = 0;
473 tor_assert(circ);
475 if (BUG(TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
476 TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
477 TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACKED)) {
478 ret = -1;
480 if (BUG(circ->hs_ident == NULL)) {
481 ret = -1;
483 if (BUG(!hs_ident_intro_circ_is_valid(circ->hs_ident))) {
484 ret = -1;
487 /* This can stop the tor daemon but we want that since if we don't have
488 * anonymity on this circuit, something went really wrong. */
489 assert_circ_anonymity_ok(circ, get_options());
490 return ret;
493 /* Find a descriptor intro point object that matches the given ident in the
494 * given descriptor desc. Return NULL if not found. */
495 static const hs_desc_intro_point_t *
496 find_desc_intro_point_by_ident(const hs_ident_circuit_t *ident,
497 const hs_descriptor_t *desc)
499 const hs_desc_intro_point_t *intro_point = NULL;
501 tor_assert(ident);
502 tor_assert(desc);
504 SMARTLIST_FOREACH_BEGIN(desc->encrypted_data.intro_points,
505 const hs_desc_intro_point_t *, ip) {
506 if (ed25519_pubkey_eq(&ident->intro_auth_pk,
507 &ip->auth_key_cert->signed_key)) {
508 intro_point = ip;
509 break;
511 } SMARTLIST_FOREACH_END(ip);
513 return intro_point;
516 /* Find a descriptor intro point object from the descriptor object desc that
517 * matches the given legacy identity digest in legacy_id. Return NULL if not
518 * found. */
519 static hs_desc_intro_point_t *
520 find_desc_intro_point_by_legacy_id(const char *legacy_id,
521 const hs_descriptor_t *desc)
523 hs_desc_intro_point_t *ret_ip = NULL;
525 tor_assert(legacy_id);
526 tor_assert(desc);
528 /* We will go over every intro point and try to find which one is linked to
529 * that circuit. Those lists are small so it's not that expensive. */
530 SMARTLIST_FOREACH_BEGIN(desc->encrypted_data.intro_points,
531 hs_desc_intro_point_t *, ip) {
532 SMARTLIST_FOREACH_BEGIN(ip->link_specifiers,
533 const hs_desc_link_specifier_t *, lspec) {
534 /* Not all tor node have an ed25519 identity key so we still rely on the
535 * legacy identity digest. */
536 if (lspec->type != LS_LEGACY_ID) {
537 continue;
539 if (fast_memneq(legacy_id, lspec->u.legacy_id, DIGEST_LEN)) {
540 break;
542 /* Found it. */
543 ret_ip = ip;
544 goto end;
545 } SMARTLIST_FOREACH_END(lspec);
546 } SMARTLIST_FOREACH_END(ip);
548 end:
549 return ret_ip;
552 /* Send an INTRODUCE1 cell along the intro circuit and populate the rend
553 * circuit identifier with the needed key material for the e2e encryption.
554 * Return 0 on success, -1 if there is a transient error such that an action
555 * has been taken to recover and -2 if there is a permanent error indicating
556 * that both circuits were closed. */
557 static int
558 send_introduce1(origin_circuit_t *intro_circ,
559 origin_circuit_t *rend_circ)
561 int status;
562 char onion_address[HS_SERVICE_ADDR_LEN_BASE32 + 1];
563 const ed25519_public_key_t *service_identity_pk = NULL;
564 const hs_desc_intro_point_t *ip;
566 tor_assert(rend_circ);
567 if (intro_circ_is_ok(intro_circ) < 0) {
568 goto perm_err;
571 service_identity_pk = &intro_circ->hs_ident->identity_pk;
572 /* For logging purposes. There will be a time where the hs_ident will have a
573 * version number but for now there is none because it's all v3. */
574 hs_build_address(service_identity_pk, HS_VERSION_THREE, onion_address);
576 log_info(LD_REND, "Sending INTRODUCE1 cell to service %s on circuit %u",
577 safe_str_client(onion_address), TO_CIRCUIT(intro_circ)->n_circ_id);
579 /* 1) Get descriptor from our cache. */
580 const hs_descriptor_t *desc =
581 hs_cache_lookup_as_client(service_identity_pk);
582 if (desc == NULL || !hs_client_any_intro_points_usable(service_identity_pk,
583 desc)) {
584 log_info(LD_REND, "Request to %s %s. Trying to fetch a new descriptor.",
585 safe_str_client(onion_address),
586 (desc) ? "didn't have usable intro points" :
587 "didn't have a descriptor");
588 hs_client_refetch_hsdesc(service_identity_pk);
589 /* We just triggered a refetch, make sure every connections are back
590 * waiting for that descriptor. */
591 flag_all_conn_wait_desc(service_identity_pk);
592 /* We just asked for a refetch so this is a transient error. */
593 goto tran_err;
596 /* We need to find which intro point in the descriptor we are connected to
597 * on intro_circ. */
598 ip = find_desc_intro_point_by_ident(intro_circ->hs_ident, desc);
599 if (ip == NULL) {
600 /* The following is possible if the descriptor was changed while we had
601 * this introduction circuit open and waiting for the rendezvous circuit to
602 * be ready. Which results in this situation where we can't find the
603 * corresponding intro point within the descriptor of the service. */
604 log_info(LD_REND, "Unable to find introduction point for service %s "
605 "while trying to send an INTRODUCE1 cell.",
606 safe_str_client(onion_address));
607 goto perm_err;
610 /* Send the INTRODUCE1 cell. */
611 if (hs_circ_send_introduce1(intro_circ, rend_circ, ip,
612 desc->subcredential) < 0) {
613 if (TO_CIRCUIT(intro_circ)->marked_for_close) {
614 /* If the introduction circuit was closed, we were unable to send the
615 * cell for some reasons. In any case, the intro circuit has to be
616 * closed by the above function. We'll return a transient error so tor
617 * can recover and pick a new intro point. To avoid picking that same
618 * intro point, we'll note down the intro point failure so it doesn't
619 * get reused. */
620 hs_cache_client_intro_state_note(service_identity_pk,
621 &intro_circ->hs_ident->intro_auth_pk,
622 INTRO_POINT_FAILURE_GENERIC);
624 /* It is also possible that the rendezvous circuit was closed due to being
625 * unable to use the rendezvous point node_t so in that case, we also want
626 * to recover and let tor pick a new one. */
627 goto tran_err;
630 /* Cell has been sent successfully. Copy the introduction point
631 * authentication and encryption key in the rendezvous circuit identifier so
632 * we can compute the ntor keys when we receive the RENDEZVOUS2 cell. */
633 memcpy(&rend_circ->hs_ident->intro_enc_pk, &ip->enc_key,
634 sizeof(rend_circ->hs_ident->intro_enc_pk));
635 ed25519_pubkey_copy(&rend_circ->hs_ident->intro_auth_pk,
636 &intro_circ->hs_ident->intro_auth_pk);
638 /* Now, we wait for an ACK or NAK on this circuit. */
639 circuit_change_purpose(TO_CIRCUIT(intro_circ),
640 CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT);
641 /* Set timestamp_dirty, because circuit_expire_building expects it to
642 * specify when a circuit entered the _C_INTRODUCE_ACK_WAIT state. */
643 TO_CIRCUIT(intro_circ)->timestamp_dirty = time(NULL);
644 pathbias_count_use_attempt(intro_circ);
646 /* Success. */
647 status = 0;
648 goto end;
650 perm_err:
651 /* Permanent error: it is possible that the intro circuit was closed prior
652 * because we weren't able to send the cell. Make sure we don't double close
653 * it which would result in a warning. */
654 if (!TO_CIRCUIT(intro_circ)->marked_for_close) {
655 circuit_mark_for_close(TO_CIRCUIT(intro_circ), END_CIRC_REASON_INTERNAL);
657 circuit_mark_for_close(TO_CIRCUIT(rend_circ), END_CIRC_REASON_INTERNAL);
658 status = -2;
659 goto end;
661 tran_err:
662 status = -1;
664 end:
665 memwipe(onion_address, 0, sizeof(onion_address));
666 return status;
669 /* Using the introduction circuit circ, setup the authentication key of the
670 * intro point this circuit has extended to. */
671 static void
672 setup_intro_circ_auth_key(origin_circuit_t *circ)
674 const hs_descriptor_t *desc;
675 const hs_desc_intro_point_t *ip;
677 tor_assert(circ);
679 desc = hs_cache_lookup_as_client(&circ->hs_ident->identity_pk);
680 if (desc == NULL) {
681 /* There is a very small race window between the opening of this circuit
682 * and the client descriptor cache that gets purged (NEWNYM) or the
683 * cleaned up because it expired. Mark the circuit for close so a new
684 * descriptor fetch can occur. */
685 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
686 goto end;
689 /* We will go over every intro point and try to find which one is linked to
690 * that circuit. Those lists are small so it's not that expensive. */
691 ip = find_desc_intro_point_by_legacy_id(
692 circ->build_state->chosen_exit->identity_digest, desc);
693 if (ip) {
694 /* We got it, copy its authentication key to the identifier. */
695 ed25519_pubkey_copy(&circ->hs_ident->intro_auth_pk,
696 &ip->auth_key_cert->signed_key);
697 goto end;
700 /* Reaching this point means we didn't find any intro point for this circuit
701 * which is not suppose to happen. */
702 tor_assert_nonfatal_unreached();
704 end:
705 return;
708 /* Called when an introduction circuit has opened. */
709 static void
710 client_intro_circ_has_opened(origin_circuit_t *circ)
712 tor_assert(circ);
713 tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
714 log_info(LD_REND, "Introduction circuit %u has opened. Attaching streams.",
715 (unsigned int) TO_CIRCUIT(circ)->n_circ_id);
717 /* This is an introduction circuit so we'll attach the correct
718 * authentication key to the circuit identifier so it can be identified
719 * properly later on. */
720 setup_intro_circ_auth_key(circ);
722 connection_ap_attach_pending(1);
725 /* Called when a rendezvous circuit has opened. */
726 static void
727 client_rendezvous_circ_has_opened(origin_circuit_t *circ)
729 tor_assert(circ);
730 tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
732 const extend_info_t *rp_ei = circ->build_state->chosen_exit;
734 /* Check that we didn't accidentally choose a node that does not understand
735 * the v3 rendezvous protocol */
736 if (rp_ei) {
737 const node_t *rp_node = node_get_by_id(rp_ei->identity_digest);
738 if (rp_node) {
739 if (BUG(!node_supports_v3_rendezvous_point(rp_node))) {
740 return;
745 log_info(LD_REND, "Rendezvous circuit has opened to %s.",
746 safe_str_client(extend_info_describe(rp_ei)));
748 /* Ignore returned value, nothing we can really do. On failure, the circuit
749 * will be marked for close. */
750 hs_circ_send_establish_rendezvous(circ);
752 /* Register rend circuit in circuitmap if it's still alive. */
753 if (!TO_CIRCUIT(circ)->marked_for_close) {
754 hs_circuitmap_register_rend_circ_client_side(circ,
755 circ->hs_ident->rendezvous_cookie);
759 /* This is an helper function that convert a descriptor intro point object ip
760 * to a newly allocated extend_info_t object fully initialized. Return NULL if
761 * we can't convert it for which chances are that we are missing or malformed
762 * link specifiers. */
763 STATIC extend_info_t *
764 desc_intro_point_to_extend_info(const hs_desc_intro_point_t *ip)
766 extend_info_t *ei;
767 smartlist_t *lspecs = smartlist_new();
769 tor_assert(ip);
771 /* We first encode the descriptor link specifiers into the binary
772 * representation which is a trunnel object. */
773 SMARTLIST_FOREACH_BEGIN(ip->link_specifiers,
774 const hs_desc_link_specifier_t *, desc_lspec) {
775 link_specifier_t *lspec = hs_desc_lspec_to_trunnel(desc_lspec);
776 smartlist_add(lspecs, lspec);
777 } SMARTLIST_FOREACH_END(desc_lspec);
779 /* Explicitly put the direct connection option to 0 because this is client
780 * side and there is no such thing as a non anonymous client. */
781 ei = hs_get_extend_info_from_lspecs(lspecs, &ip->onion_key, 0);
783 SMARTLIST_FOREACH(lspecs, link_specifier_t *, ls, link_specifier_free(ls));
784 smartlist_free(lspecs);
785 return ei;
788 /* Return true iff the intro point ip for the service service_pk is usable.
789 * This function checks if the intro point is in the client intro state cache
790 * and checks at the failures. It is considered usable if:
791 * - No error happened (INTRO_POINT_FAILURE_GENERIC)
792 * - It is not flagged as timed out (INTRO_POINT_FAILURE_TIMEOUT)
793 * - The unreachable count is lower than
794 * MAX_INTRO_POINT_REACHABILITY_FAILURES (INTRO_POINT_FAILURE_UNREACHABLE)
796 static int
797 intro_point_is_usable(const ed25519_public_key_t *service_pk,
798 const hs_desc_intro_point_t *ip)
800 const hs_cache_intro_state_t *state;
802 tor_assert(service_pk);
803 tor_assert(ip);
805 state = hs_cache_client_intro_state_find(service_pk,
806 &ip->auth_key_cert->signed_key);
807 if (state == NULL) {
808 /* This means we've never encountered any problem thus usable. */
809 goto usable;
811 if (state->error) {
812 log_info(LD_REND, "Intro point with auth key %s had an error. Not usable",
813 safe_str_client(ed25519_fmt(&ip->auth_key_cert->signed_key)));
814 goto not_usable;
816 if (state->timed_out) {
817 log_info(LD_REND, "Intro point with auth key %s timed out. Not usable",
818 safe_str_client(ed25519_fmt(&ip->auth_key_cert->signed_key)));
819 goto not_usable;
821 if (state->unreachable_count >= MAX_INTRO_POINT_REACHABILITY_FAILURES) {
822 log_info(LD_REND, "Intro point with auth key %s unreachable. Not usable",
823 safe_str_client(ed25519_fmt(&ip->auth_key_cert->signed_key)));
824 goto not_usable;
827 usable:
828 return 1;
829 not_usable:
830 return 0;
833 /* Using a descriptor desc, return a newly allocated extend_info_t object of a
834 * randomly picked introduction point from its list. Return NULL if none are
835 * usable. */
836 STATIC extend_info_t *
837 client_get_random_intro(const ed25519_public_key_t *service_pk)
839 extend_info_t *ei = NULL, *ei_excluded = NULL;
840 smartlist_t *usable_ips = NULL;
841 const hs_descriptor_t *desc;
842 const hs_desc_encrypted_data_t *enc_data;
843 const or_options_t *options = get_options();
844 /* Calculate the onion address for logging purposes */
845 char onion_address[HS_SERVICE_ADDR_LEN_BASE32 + 1];
847 tor_assert(service_pk);
849 desc = hs_cache_lookup_as_client(service_pk);
850 /* Assume the service is v3 if the descriptor is missing. This is ok,
851 * because we only use the address in log messages */
852 hs_build_address(service_pk,
853 desc ? desc->plaintext_data.version : HS_VERSION_THREE,
854 onion_address);
855 if (desc == NULL || !hs_client_any_intro_points_usable(service_pk,
856 desc)) {
857 log_info(LD_REND, "Unable to randomly select an introduction point "
858 "for service %s because descriptor %s. We can't connect.",
859 safe_str_client(onion_address),
860 (desc) ? "doesn't have any usable intro points"
861 : "is missing (assuming v3 onion address)");
862 goto end;
865 enc_data = &desc->encrypted_data;
866 usable_ips = smartlist_new();
867 smartlist_add_all(usable_ips, enc_data->intro_points);
868 while (smartlist_len(usable_ips) != 0) {
869 int idx;
870 const hs_desc_intro_point_t *ip;
872 /* Pick a random intro point and immediately remove it from the usable
873 * list so we don't pick it again if we have to iterate more. */
874 idx = crypto_rand_int(smartlist_len(usable_ips));
875 ip = smartlist_get(usable_ips, idx);
876 smartlist_del(usable_ips, idx);
878 /* We need to make sure we have a usable intro points which is in a good
879 * state in our cache. */
880 if (!intro_point_is_usable(service_pk, ip)) {
881 continue;
884 /* Generate an extend info object from the intro point object. */
885 ei = desc_intro_point_to_extend_info(ip);
886 if (ei == NULL) {
887 /* We can get here for instance if the intro point is a private address
888 * and we aren't allowed to extend to those. */
889 log_info(LD_REND, "Unable to select introduction point with auth key %s "
890 "for service %s, because we could not extend to it.",
891 safe_str_client(ed25519_fmt(&ip->auth_key_cert->signed_key)),
892 safe_str_client(onion_address));
893 continue;
896 /* Test the pick against ExcludeNodes. */
897 if (routerset_contains_extendinfo(options->ExcludeNodes, ei)) {
898 /* If this pick is in the ExcludeNodes list, we keep its reference so if
899 * we ever end up not being able to pick anything else and StrictNodes is
900 * unset, we'll use it. */
901 if (ei_excluded) {
902 /* If something was already here free it. After the loop is gone we
903 * will examine the last excluded intro point, and that's fine since
904 * that's random anyway */
905 extend_info_free(ei_excluded);
907 ei_excluded = ei;
908 continue;
911 /* Good pick! Let's go with this. */
912 goto end;
915 /* Reaching this point means a couple of things. Either we can't use any of
916 * the intro point listed because the IP address can't be extended to or it
917 * is listed in the ExcludeNodes list. In the later case, if StrictNodes is
918 * set, we are forced to not use anything. */
919 ei = ei_excluded;
920 if (options->StrictNodes) {
921 log_warn(LD_REND, "Every introduction point for service %s is in the "
922 "ExcludeNodes set and StrictNodes is set. We can't connect.",
923 safe_str_client(onion_address));
924 extend_info_free(ei);
925 ei = NULL;
926 } else {
927 log_fn(LOG_PROTOCOL_WARN, LD_REND, "Every introduction point for service "
928 "%s is unusable or we can't extend to it. We can't connect.",
929 safe_str_client(onion_address));
932 end:
933 smartlist_free(usable_ips);
934 memwipe(onion_address, 0, sizeof(onion_address));
935 return ei;
938 /* For this introduction circuit, we'll look at if we have any usable
939 * introduction point left for this service. If so, we'll use the circuit to
940 * re-extend to a new intro point. Else, we'll close the circuit and its
941 * corresponding rendezvous circuit. Return 0 if we are re-extending else -1
942 * if we are closing the circuits.
944 * This is called when getting an INTRODUCE_ACK cell with a NACK. */
945 static int
946 close_or_reextend_intro_circ(origin_circuit_t *intro_circ)
948 int ret = -1;
949 const hs_descriptor_t *desc;
950 origin_circuit_t *rend_circ;
952 tor_assert(intro_circ);
954 desc = hs_cache_lookup_as_client(&intro_circ->hs_ident->identity_pk);
955 if (BUG(desc == NULL)) {
956 /* We can't continue without a descriptor. */
957 goto close;
959 /* We still have the descriptor, great! Let's try to see if we can
960 * re-extend by looking up if there are any usable intro points. */
961 if (!hs_client_any_intro_points_usable(&intro_circ->hs_ident->identity_pk,
962 desc)) {
963 goto close;
965 /* Try to re-extend now. */
966 if (hs_client_reextend_intro_circuit(intro_circ) < 0) {
967 goto close;
969 /* Success on re-extending. Don't return an error. */
970 ret = 0;
971 goto end;
973 close:
974 /* Change the intro circuit purpose before so we don't report an intro point
975 * failure again triggering an extra descriptor fetch. The circuit can
976 * already be closed on failure to re-extend. */
977 if (!TO_CIRCUIT(intro_circ)->marked_for_close) {
978 circuit_change_purpose(TO_CIRCUIT(intro_circ),
979 CIRCUIT_PURPOSE_C_INTRODUCE_ACKED);
980 circuit_mark_for_close(TO_CIRCUIT(intro_circ), END_CIRC_REASON_FINISHED);
982 /* Close the related rendezvous circuit. */
983 rend_circ = hs_circuitmap_get_rend_circ_client_side(
984 intro_circ->hs_ident->rendezvous_cookie);
985 /* The rendezvous circuit might have collapsed while the INTRODUCE_ACK was
986 * inflight so we can't expect one every time. */
987 if (rend_circ) {
988 circuit_mark_for_close(TO_CIRCUIT(rend_circ), END_CIRC_REASON_FINISHED);
991 end:
992 return ret;
995 /* Called when we get an INTRODUCE_ACK success status code. Do the appropriate
996 * actions for the rendezvous point and finally close intro_circ. */
997 static void
998 handle_introduce_ack_success(origin_circuit_t *intro_circ)
1000 origin_circuit_t *rend_circ = NULL;
1002 tor_assert(intro_circ);
1004 log_info(LD_REND, "Received INTRODUCE_ACK ack! Informing rendezvous");
1006 /* Get the rendezvous circuit for this rendezvous cookie. */
1007 uint8_t *rendezvous_cookie = intro_circ->hs_ident->rendezvous_cookie;
1008 rend_circ =
1009 hs_circuitmap_get_established_rend_circ_client_side(rendezvous_cookie);
1010 if (rend_circ == NULL) {
1011 log_warn(LD_REND, "Can't find any rendezvous circuit. Stopping");
1012 goto end;
1015 assert_circ_anonymity_ok(rend_circ, get_options());
1017 /* It is possible to get a RENDEZVOUS2 cell before the INTRODUCE_ACK which
1018 * means that the circuit will be joined and already transmitting data. In
1019 * that case, simply skip the purpose change and close the intro circuit
1020 * like it should be. */
1021 if (TO_CIRCUIT(rend_circ)->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
1022 goto end;
1024 circuit_change_purpose(TO_CIRCUIT(rend_circ),
1025 CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED);
1026 /* Set timestamp_dirty, because circuit_expire_building expects it to
1027 * specify when a circuit entered the
1028 * CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED state. */
1029 TO_CIRCUIT(rend_circ)->timestamp_dirty = time(NULL);
1031 end:
1032 /* We don't need the intro circuit anymore. It did what it had to do! */
1033 circuit_change_purpose(TO_CIRCUIT(intro_circ),
1034 CIRCUIT_PURPOSE_C_INTRODUCE_ACKED);
1035 circuit_mark_for_close(TO_CIRCUIT(intro_circ), END_CIRC_REASON_FINISHED);
1037 /* XXX: Close pending intro circuits we might have in parallel. */
1038 return;
1041 /* Called when we get an INTRODUCE_ACK failure status code. Depending on our
1042 * failure cache status, either close the circuit or re-extend to a new
1043 * introduction point. */
1044 static void
1045 handle_introduce_ack_bad(origin_circuit_t *circ, int status)
1047 tor_assert(circ);
1049 log_info(LD_REND, "Received INTRODUCE_ACK nack by %s. Reason: %u",
1050 safe_str_client(extend_info_describe(circ->build_state->chosen_exit)),
1051 status);
1053 /* It's a NAK. The introduction point didn't relay our request. */
1054 circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_C_INTRODUCING);
1056 /* Note down this failure in the intro point failure cache. Depending on how
1057 * many times we've tried this intro point, close it or reextend. */
1058 hs_cache_client_intro_state_note(&circ->hs_ident->identity_pk,
1059 &circ->hs_ident->intro_auth_pk,
1060 INTRO_POINT_FAILURE_GENERIC);
1063 /* Called when we get an INTRODUCE_ACK on the intro circuit circ. The encoded
1064 * cell is in payload of length payload_len. Return 0 on success else a
1065 * negative value. The circuit is either close or reuse to re-extend to a new
1066 * introduction point. */
1067 static int
1068 handle_introduce_ack(origin_circuit_t *circ, const uint8_t *payload,
1069 size_t payload_len)
1071 int status, ret = -1;
1073 tor_assert(circ);
1074 tor_assert(circ->build_state);
1075 tor_assert(circ->build_state->chosen_exit);
1076 assert_circ_anonymity_ok(circ, get_options());
1077 tor_assert(payload);
1079 status = hs_cell_parse_introduce_ack(payload, payload_len);
1080 switch (status) {
1081 case TRUNNEL_HS_INTRO_ACK_STATUS_SUCCESS:
1082 ret = 0;
1083 handle_introduce_ack_success(circ);
1084 goto end;
1085 case TRUNNEL_HS_INTRO_ACK_STATUS_UNKNOWN_ID:
1086 case TRUNNEL_HS_INTRO_ACK_STATUS_BAD_FORMAT:
1087 /* It is possible that the intro point can send us an unknown status code
1088 * for the NACK that we do not know about like a new code for instance.
1089 * Just fallthrough so we can note down the NACK and re-extend. */
1090 default:
1091 handle_introduce_ack_bad(circ, status);
1092 /* We are going to see if we have to close the circuits (IP and RP) or we
1093 * can re-extend to a new intro point. */
1094 ret = close_or_reextend_intro_circ(circ);
1095 break;
1098 end:
1099 return ret;
1102 /* Called when we get a RENDEZVOUS2 cell on the rendezvous circuit circ. The
1103 * encoded cell is in payload of length payload_len. Return 0 on success or a
1104 * negative value on error. On error, the circuit is marked for close. */
1105 STATIC int
1106 handle_rendezvous2(origin_circuit_t *circ, const uint8_t *payload,
1107 size_t payload_len)
1109 int ret = -1;
1110 curve25519_public_key_t server_pk;
1111 uint8_t auth_mac[DIGEST256_LEN] = {0};
1112 uint8_t handshake_info[CURVE25519_PUBKEY_LEN + sizeof(auth_mac)] = {0};
1113 hs_ntor_rend_cell_keys_t keys;
1114 const hs_ident_circuit_t *ident;
1116 tor_assert(circ);
1117 tor_assert(payload);
1119 /* Make things easier. */
1120 ident = circ->hs_ident;
1121 tor_assert(ident);
1123 if (hs_cell_parse_rendezvous2(payload, payload_len, handshake_info,
1124 sizeof(handshake_info)) < 0) {
1125 goto err;
1127 /* Get from the handshake info the SERVER_PK and AUTH_MAC. */
1128 memcpy(&server_pk, handshake_info, CURVE25519_PUBKEY_LEN);
1129 memcpy(auth_mac, handshake_info + CURVE25519_PUBKEY_LEN, sizeof(auth_mac));
1131 /* Generate the handshake info. */
1132 if (hs_ntor_client_get_rendezvous1_keys(&ident->intro_auth_pk,
1133 &ident->rendezvous_client_kp,
1134 &ident->intro_enc_pk, &server_pk,
1135 &keys) < 0) {
1136 log_info(LD_REND, "Unable to compute the rendezvous keys.");
1137 goto err;
1140 /* Critical check, make sure that the MAC matches what we got with what we
1141 * computed just above. */
1142 if (!hs_ntor_client_rendezvous2_mac_is_good(&keys, auth_mac)) {
1143 log_info(LD_REND, "Invalid MAC in RENDEZVOUS2. Rejecting cell.");
1144 goto err;
1147 /* Setup the e2e encryption on the circuit and finalize its state. */
1148 if (hs_circuit_setup_e2e_rend_circ(circ, keys.ntor_key_seed,
1149 sizeof(keys.ntor_key_seed), 0) < 0) {
1150 log_info(LD_REND, "Unable to setup the e2e encryption.");
1151 goto err;
1153 /* Success. Hidden service connection finalized! */
1154 ret = 0;
1155 goto end;
1157 err:
1158 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
1159 end:
1160 memwipe(&keys, 0, sizeof(keys));
1161 return ret;
1164 /* Return true iff the client can fetch a descriptor for this service public
1165 * identity key and status_out if not NULL is untouched. If the client can
1166 * _not_ fetch the descriptor and if status_out is not NULL, it is set with
1167 * the fetch status code. */
1168 static unsigned int
1169 can_client_refetch_desc(const ed25519_public_key_t *identity_pk,
1170 hs_client_fetch_status_t *status_out)
1172 hs_client_fetch_status_t status;
1174 tor_assert(identity_pk);
1176 /* Are we configured to fetch descriptors? */
1177 if (!get_options()->FetchHidServDescriptors) {
1178 log_warn(LD_REND, "We received an onion address for a hidden service "
1179 "descriptor but we are configured to not fetch.");
1180 status = HS_CLIENT_FETCH_NOT_ALLOWED;
1181 goto cannot;
1184 /* Without a live consensus we can't do any client actions. It is needed to
1185 * compute the hashring for a service. */
1186 if (!networkstatus_get_live_consensus(approx_time())) {
1187 log_info(LD_REND, "Can't fetch descriptor for service %s because we "
1188 "are missing a live consensus. Stalling connection.",
1189 safe_str_client(ed25519_fmt(identity_pk)));
1190 status = HS_CLIENT_FETCH_MISSING_INFO;
1191 goto cannot;
1194 if (!router_have_minimum_dir_info()) {
1195 log_info(LD_REND, "Can't fetch descriptor for service %s because we "
1196 "dont have enough descriptors. Stalling connection.",
1197 safe_str_client(ed25519_fmt(identity_pk)));
1198 status = HS_CLIENT_FETCH_MISSING_INFO;
1199 goto cannot;
1202 /* Check if fetching a desc for this HS is useful to us right now */
1204 const hs_descriptor_t *cached_desc = NULL;
1205 cached_desc = hs_cache_lookup_as_client(identity_pk);
1206 if (cached_desc && hs_client_any_intro_points_usable(identity_pk,
1207 cached_desc)) {
1208 log_info(LD_GENERAL, "We would fetch a v3 hidden service descriptor "
1209 "but we already have a usable descriptor.");
1210 status = HS_CLIENT_FETCH_HAVE_DESC;
1211 goto cannot;
1215 /* Don't try to refetch while we have a pending request for it. */
1216 if (directory_request_is_pending(identity_pk)) {
1217 log_info(LD_REND, "Already a pending directory request. Waiting on it.");
1218 status = HS_CLIENT_FETCH_PENDING;
1219 goto cannot;
1222 /* Yes, client can fetch! */
1223 return 1;
1224 cannot:
1225 if (status_out) {
1226 *status_out = status;
1228 return 0;
1231 /* Return the client auth in the map using the service identity public key.
1232 * Return NULL if it does not exist in the map. */
1233 static hs_client_service_authorization_t *
1234 find_client_auth(const ed25519_public_key_t *service_identity_pk)
1236 /* If the map is not allocated, we can assume that we do not have any client
1237 * auth information. */
1238 if (!client_auths) {
1239 return NULL;
1241 return digest256map_get(client_auths, service_identity_pk->pubkey);
1244 /* ========== */
1245 /* Public API */
1246 /* ========== */
1248 /** A circuit just finished connecting to a hidden service that the stream
1249 * <b>conn</b> has been waiting for. Let the HS subsystem know about this. */
1250 void
1251 hs_client_note_connection_attempt_succeeded(const edge_connection_t *conn)
1253 tor_assert(connection_edge_is_rendezvous_stream(conn));
1255 if (BUG(conn->rend_data && conn->hs_ident)) {
1256 log_warn(LD_BUG, "Stream had both rend_data and hs_ident..."
1257 "Prioritizing hs_ident");
1260 if (conn->hs_ident) { /* It's v3: pass it to the prop224 handler */
1261 note_connection_attempt_succeeded(conn->hs_ident);
1262 return;
1263 } else if (conn->rend_data) { /* It's v2: pass it to the legacy handler */
1264 rend_client_note_connection_attempt_ended(conn->rend_data);
1265 return;
1269 /* With the given encoded descriptor in desc_str and the service key in
1270 * service_identity_pk, decode the descriptor and set the desc pointer with a
1271 * newly allocated descriptor object.
1273 * Return 0 on success else a negative value and desc is set to NULL. */
1275 hs_client_decode_descriptor(const char *desc_str,
1276 const ed25519_public_key_t *service_identity_pk,
1277 hs_descriptor_t **desc)
1279 int ret;
1280 uint8_t subcredential[DIGEST256_LEN];
1281 ed25519_public_key_t blinded_pubkey;
1282 hs_client_service_authorization_t *client_auth = NULL;
1283 curve25519_secret_key_t *client_auht_sk = NULL;
1285 tor_assert(desc_str);
1286 tor_assert(service_identity_pk);
1287 tor_assert(desc);
1289 /* Check if we have a client authorization for this service in the map. */
1290 client_auth = find_client_auth(service_identity_pk);
1291 if (client_auth) {
1292 client_auht_sk = &client_auth->enc_seckey;
1295 /* Create subcredential for this HS so that we can decrypt */
1297 uint64_t current_time_period = hs_get_time_period_num(0);
1298 hs_build_blinded_pubkey(service_identity_pk, NULL, 0, current_time_period,
1299 &blinded_pubkey);
1300 hs_get_subcredential(service_identity_pk, &blinded_pubkey, subcredential);
1303 /* Parse descriptor */
1304 ret = hs_desc_decode_descriptor(desc_str, subcredential,
1305 client_auht_sk, desc);
1306 memwipe(subcredential, 0, sizeof(subcredential));
1307 if (ret < 0) {
1308 goto err;
1311 /* Make sure the descriptor signing key cross certifies with the computed
1312 * blinded key. Without this validation, anyone knowing the subcredential
1313 * and onion address can forge a descriptor. */
1314 tor_cert_t *cert = (*desc)->plaintext_data.signing_key_cert;
1315 if (tor_cert_checksig(cert,
1316 &blinded_pubkey, approx_time()) < 0) {
1317 log_warn(LD_GENERAL, "Descriptor signing key certificate signature "
1318 "doesn't validate with computed blinded key: %s",
1319 tor_cert_describe_signature_status(cert));
1320 goto err;
1323 return 0;
1324 err:
1325 return -1;
1328 /* Return true iff there are at least one usable intro point in the service
1329 * descriptor desc. */
1331 hs_client_any_intro_points_usable(const ed25519_public_key_t *service_pk,
1332 const hs_descriptor_t *desc)
1334 tor_assert(service_pk);
1335 tor_assert(desc);
1337 SMARTLIST_FOREACH_BEGIN(desc->encrypted_data.intro_points,
1338 const hs_desc_intro_point_t *, ip) {
1339 if (intro_point_is_usable(service_pk, ip)) {
1340 goto usable;
1342 } SMARTLIST_FOREACH_END(ip);
1344 return 0;
1345 usable:
1346 return 1;
1349 /** Launch a connection to a hidden service directory to fetch a hidden
1350 * service descriptor using <b>identity_pk</b> to get the necessary keys.
1352 * A hs_client_fetch_status_t code is returned. */
1354 hs_client_refetch_hsdesc(const ed25519_public_key_t *identity_pk)
1356 hs_client_fetch_status_t status;
1358 tor_assert(identity_pk);
1360 if (!can_client_refetch_desc(identity_pk, &status)) {
1361 return status;
1364 /* Try to fetch the desc and if we encounter an unrecoverable error, mark
1365 * the desc as unavailable for now. */
1366 status = fetch_v3_desc(identity_pk);
1367 if (fetch_status_should_close_socks(status)) {
1368 close_all_socks_conns_waiting_for_desc(identity_pk, status,
1369 END_STREAM_REASON_RESOLVEFAILED);
1370 /* Remove HSDir fetch attempts so that we can retry later if the user
1371 * wants us to regardless of if we closed any connections. */
1372 purge_hid_serv_request(identity_pk);
1374 return status;
1377 /* This is called when we are trying to attach an AP connection to these
1378 * hidden service circuits from connection_ap_handshake_attach_circuit().
1379 * Return 0 on success, -1 for a transient error that is actions were
1380 * triggered to recover or -2 for a permenent error where both circuits will
1381 * marked for close.
1383 * The following supports every hidden service version. */
1385 hs_client_send_introduce1(origin_circuit_t *intro_circ,
1386 origin_circuit_t *rend_circ)
1388 return (intro_circ->hs_ident) ? send_introduce1(intro_circ, rend_circ) :
1389 rend_client_send_introduction(intro_circ,
1390 rend_circ);
1393 /* Called when the client circuit circ has been established. It can be either
1394 * an introduction or rendezvous circuit. This function handles all hidden
1395 * service versions. */
1396 void
1397 hs_client_circuit_has_opened(origin_circuit_t *circ)
1399 tor_assert(circ);
1401 /* Handle both version. v2 uses rend_data and v3 uses the hs circuit
1402 * identifier hs_ident. Can't be both. */
1403 switch (TO_CIRCUIT(circ)->purpose) {
1404 case CIRCUIT_PURPOSE_C_INTRODUCING:
1405 if (circ->hs_ident) {
1406 client_intro_circ_has_opened(circ);
1407 } else {
1408 rend_client_introcirc_has_opened(circ);
1410 break;
1411 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1412 if (circ->hs_ident) {
1413 client_rendezvous_circ_has_opened(circ);
1414 } else {
1415 rend_client_rendcirc_has_opened(circ);
1417 break;
1418 default:
1419 tor_assert_nonfatal_unreached();
1423 /* Called when we receive a RENDEZVOUS_ESTABLISHED cell. Change the state of
1424 * the circuit to CIRCUIT_PURPOSE_C_REND_READY. Return 0 on success else a
1425 * negative value and the circuit marked for close. */
1427 hs_client_receive_rendezvous_acked(origin_circuit_t *circ,
1428 const uint8_t *payload, size_t payload_len)
1430 tor_assert(circ);
1431 tor_assert(payload);
1433 (void) payload_len;
1435 if (TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND) {
1436 log_warn(LD_PROTOCOL, "Got a RENDEZVOUS_ESTABLISHED but we were not "
1437 "expecting one. Closing circuit.");
1438 goto err;
1441 log_info(LD_REND, "Received an RENDEZVOUS_ESTABLISHED. This circuit is "
1442 "now ready for rendezvous.");
1443 circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_C_REND_READY);
1445 /* Set timestamp_dirty, because circuit_expire_building expects it to
1446 * specify when a circuit entered the _C_REND_READY state. */
1447 TO_CIRCUIT(circ)->timestamp_dirty = time(NULL);
1449 /* From a path bias point of view, this circuit is now successfully used.
1450 * Waiting any longer opens us up to attacks from malicious hidden services.
1451 * They could induce the client to attempt to connect to their hidden
1452 * service and never reply to the client's rend requests */
1453 pathbias_mark_use_success(circ);
1455 /* If we already have the introduction circuit built, make sure we send
1456 * the INTRODUCE cell _now_ */
1457 connection_ap_attach_pending(1);
1459 return 0;
1460 err:
1461 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
1462 return -1;
1465 #define client_service_authorization_free(auth) \
1466 FREE_AND_NULL(hs_client_service_authorization_t, \
1467 client_service_authorization_free_, (auth))
1469 static void
1470 client_service_authorization_free_(hs_client_service_authorization_t *auth)
1472 if (auth) {
1473 memwipe(auth, 0, sizeof(*auth));
1475 tor_free(auth);
1478 /** Helper for digest256map_free. */
1479 static void
1480 client_service_authorization_free_void(void *auth)
1482 client_service_authorization_free_(auth);
1485 static void
1486 client_service_authorization_free_all(void)
1488 if (!client_auths) {
1489 return;
1491 digest256map_free(client_auths, client_service_authorization_free_void);
1494 /* Check if the auth key file name is valid or not. Return 1 if valid,
1495 * otherwise return 0. */
1496 STATIC int
1497 auth_key_filename_is_valid(const char *filename)
1499 int ret = 1;
1500 const char *valid_extension = ".auth_private";
1502 tor_assert(filename);
1504 /* The length of the filename must be greater than the length of the
1505 * extension and the valid extension must be at the end of filename. */
1506 if (!strcmpend(filename, valid_extension) &&
1507 strlen(filename) != strlen(valid_extension)) {
1508 ret = 1;
1509 } else {
1510 ret = 0;
1513 return ret;
1516 STATIC hs_client_service_authorization_t *
1517 parse_auth_file_content(const char *client_key_str)
1519 char *onion_address = NULL;
1520 char *auth_type = NULL;
1521 char *key_type = NULL;
1522 char *seckey_b32 = NULL;
1523 hs_client_service_authorization_t *auth = NULL;
1524 smartlist_t *fields = smartlist_new();
1526 tor_assert(client_key_str);
1528 smartlist_split_string(fields, client_key_str, ":",
1529 SPLIT_SKIP_SPACE, 0);
1530 /* Wrong number of fields. */
1531 if (smartlist_len(fields) != 4) {
1532 goto err;
1535 onion_address = smartlist_get(fields, 0);
1536 auth_type = smartlist_get(fields, 1);
1537 key_type = smartlist_get(fields, 2);
1538 seckey_b32 = smartlist_get(fields, 3);
1540 /* Currently, the only supported auth type is "descriptor" and the only
1541 * supported key type is "x25519". */
1542 if (strcmp(auth_type, "descriptor") || strcmp(key_type, "x25519")) {
1543 goto err;
1546 if (strlen(seckey_b32) != BASE32_NOPAD_LEN(CURVE25519_PUBKEY_LEN)) {
1547 log_warn(LD_REND, "Client authorization encoded base32 private key "
1548 "length is invalid: %s", seckey_b32);
1549 goto err;
1552 auth = tor_malloc_zero(sizeof(hs_client_service_authorization_t));
1553 if (base32_decode((char *) auth->enc_seckey.secret_key,
1554 sizeof(auth->enc_seckey.secret_key),
1555 seckey_b32, strlen(seckey_b32)) < 0) {
1556 goto err;
1558 strncpy(auth->onion_address, onion_address, HS_SERVICE_ADDR_LEN_BASE32);
1560 /* Success. */
1561 goto done;
1563 err:
1564 client_service_authorization_free(auth);
1565 done:
1566 /* It is also a good idea to wipe the private key. */
1567 if (seckey_b32) {
1568 memwipe(seckey_b32, 0, strlen(seckey_b32));
1570 tor_assert(fields);
1571 SMARTLIST_FOREACH(fields, char *, s, tor_free(s));
1572 smartlist_free(fields);
1573 return auth;
1576 /* From a set of <b>options</b>, setup every client authorization detail
1577 * found. Return 0 on success or -1 on failure. If <b>validate_only</b>
1578 * is set, parse, warn and return as normal, but don't actually change
1579 * the configuration. */
1581 hs_config_client_authorization(const or_options_t *options,
1582 int validate_only)
1584 int ret = -1;
1585 digest256map_t *auths = digest256map_new();
1586 char *key_dir = NULL;
1587 smartlist_t *file_list = NULL;
1588 char *client_key_str = NULL;
1589 char *client_key_file_path = NULL;
1591 tor_assert(options);
1593 /* There is no client auth configured. We can just silently ignore this
1594 * function. */
1595 if (!options->ClientOnionAuthDir) {
1596 ret = 0;
1597 goto end;
1600 key_dir = tor_strdup(options->ClientOnionAuthDir);
1602 /* Make sure the directory exists and is private enough. */
1603 if (check_private_dir(key_dir, 0, options->User) < 0) {
1604 goto end;
1607 file_list = tor_listdir(key_dir);
1608 if (file_list == NULL) {
1609 log_warn(LD_REND, "Client authorization key directory %s can't be listed.",
1610 key_dir);
1611 goto end;
1614 SMARTLIST_FOREACH_BEGIN(file_list, char *, filename) {
1616 hs_client_service_authorization_t *auth = NULL;
1617 ed25519_public_key_t identity_pk;
1618 log_info(LD_REND, "Loading a client authorization key file %s...",
1619 filename);
1621 if (!auth_key_filename_is_valid(filename)) {
1622 log_notice(LD_REND, "Client authorization unrecognized filename %s. "
1623 "File must end in .auth_private. Ignoring.",
1624 filename);
1625 continue;
1628 /* Create a full path for a file. */
1629 client_key_file_path = hs_path_from_filename(key_dir, filename);
1630 client_key_str = read_file_to_str(client_key_file_path, 0, NULL);
1631 /* Free the file path immediately after using it. */
1632 tor_free(client_key_file_path);
1634 /* If we cannot read the file, continue with the next file. */
1635 if (!client_key_str) {
1636 log_warn(LD_REND, "The file %s cannot be read.", filename);
1637 continue;
1640 auth = parse_auth_file_content(client_key_str);
1641 /* Free immediately after using it. */
1642 tor_free(client_key_str);
1644 if (auth) {
1645 /* Parse the onion address to get an identity public key and use it
1646 * as a key of global map in the future. */
1647 if (hs_parse_address(auth->onion_address, &identity_pk,
1648 NULL, NULL) < 0) {
1649 log_warn(LD_REND, "The onion address \"%s\" is invalid in "
1650 "file %s", filename, auth->onion_address);
1651 client_service_authorization_free(auth);
1652 continue;
1655 if (digest256map_get(auths, identity_pk.pubkey)) {
1656 log_warn(LD_REND, "Duplicate authorization for the same hidden "
1657 "service address %s.",
1658 safe_str_client_opts(options, auth->onion_address));
1659 client_service_authorization_free(auth);
1660 goto end;
1663 digest256map_set(auths, identity_pk.pubkey, auth);
1664 log_info(LD_REND, "Loaded a client authorization key file %s.",
1665 filename);
1667 } SMARTLIST_FOREACH_END(filename);
1669 /* Success. */
1670 ret = 0;
1672 end:
1673 tor_free(key_dir);
1674 tor_free(client_key_str);
1675 tor_free(client_key_file_path);
1676 if (file_list) {
1677 SMARTLIST_FOREACH(file_list, char *, s, tor_free(s));
1678 smartlist_free(file_list);
1681 if (!validate_only && ret == 0) {
1682 client_service_authorization_free_all();
1683 client_auths = auths;
1684 } else {
1685 digest256map_free(auths, client_service_authorization_free_void);
1688 return ret;
1691 /* This is called when a descriptor has arrived following a fetch request and
1692 * has been stored in the client cache. Every entry connection that matches
1693 * the service identity key in the ident will get attached to the hidden
1694 * service circuit. */
1695 void
1696 hs_client_desc_has_arrived(const hs_ident_dir_conn_t *ident)
1698 time_t now = time(NULL);
1699 smartlist_t *conns = NULL;
1701 tor_assert(ident);
1703 conns = connection_list_by_type_state(CONN_TYPE_AP,
1704 AP_CONN_STATE_RENDDESC_WAIT);
1705 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
1706 const hs_descriptor_t *desc;
1707 entry_connection_t *entry_conn = TO_ENTRY_CONN(base_conn);
1708 const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(entry_conn);
1710 /* Only consider the entry connections that matches the service for which
1711 * we just fetched its descriptor. */
1712 if (!edge_conn->hs_ident ||
1713 !ed25519_pubkey_eq(&ident->identity_pk,
1714 &edge_conn->hs_ident->identity_pk)) {
1715 continue;
1717 assert_connection_ok(base_conn, now);
1719 /* We were just called because we stored the descriptor for this service
1720 * so not finding a descriptor means we have a bigger problem. */
1721 desc = hs_cache_lookup_as_client(&ident->identity_pk);
1722 if (BUG(desc == NULL)) {
1723 goto end;
1726 if (!hs_client_any_intro_points_usable(&ident->identity_pk, desc)) {
1727 log_info(LD_REND, "Hidden service descriptor is unusable. "
1728 "Closing streams.");
1729 connection_mark_unattached_ap(entry_conn,
1730 END_STREAM_REASON_RESOLVEFAILED);
1731 /* We are unable to use the descriptor so remove the directory request
1732 * from the cache so the next connection can try again. */
1733 note_connection_attempt_succeeded(edge_conn->hs_ident);
1734 continue;
1737 log_info(LD_REND, "Descriptor has arrived. Launching circuits.");
1739 /* Mark connection as waiting for a circuit since we do have a usable
1740 * descriptor now. */
1741 mark_conn_as_waiting_for_circuit(base_conn, now);
1742 } SMARTLIST_FOREACH_END(base_conn);
1744 end:
1745 /* We don't have ownership of the objects in this list. */
1746 smartlist_free(conns);
1749 /* Return a newly allocated extend_info_t for a randomly chosen introduction
1750 * point for the given edge connection identifier ident. Return NULL if we
1751 * can't pick any usable introduction points. */
1752 extend_info_t *
1753 hs_client_get_random_intro_from_edge(const edge_connection_t *edge_conn)
1755 tor_assert(edge_conn);
1757 return (edge_conn->hs_ident) ?
1758 client_get_random_intro(&edge_conn->hs_ident->identity_pk) :
1759 rend_client_get_random_intro(edge_conn->rend_data);
1762 /* Called when get an INTRODUCE_ACK cell on the introduction circuit circ.
1763 * Return 0 on success else a negative value is returned. The circuit will be
1764 * closed or reuse to extend again to another intro point. */
1766 hs_client_receive_introduce_ack(origin_circuit_t *circ,
1767 const uint8_t *payload, size_t payload_len)
1769 int ret = -1;
1771 tor_assert(circ);
1772 tor_assert(payload);
1774 if (TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
1775 log_warn(LD_PROTOCOL, "Unexpected INTRODUCE_ACK on circuit %u.",
1776 (unsigned int) TO_CIRCUIT(circ)->n_circ_id);
1777 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
1778 goto end;
1781 ret = (circ->hs_ident) ? handle_introduce_ack(circ, payload, payload_len) :
1782 rend_client_introduction_acked(circ, payload,
1783 payload_len);
1784 /* For path bias: This circuit was used successfully. NACK or ACK counts. */
1785 pathbias_mark_use_success(circ);
1787 end:
1788 return ret;
1791 /* Called when get a RENDEZVOUS2 cell on the rendezvous circuit circ. Return
1792 * 0 on success else a negative value is returned. The circuit will be closed
1793 * on error. */
1795 hs_client_receive_rendezvous2(origin_circuit_t *circ,
1796 const uint8_t *payload, size_t payload_len)
1798 int ret = -1;
1800 tor_assert(circ);
1801 tor_assert(payload);
1803 /* Circuit can possibly be in both state because we could receive a
1804 * RENDEZVOUS2 cell before the INTRODUCE_ACK has been received. */
1805 if (TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
1806 TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
1807 log_warn(LD_PROTOCOL, "Unexpected RENDEZVOUS2 cell on circuit %u. "
1808 "Closing circuit.",
1809 (unsigned int) TO_CIRCUIT(circ)->n_circ_id);
1810 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
1811 goto end;
1814 log_info(LD_REND, "Got RENDEZVOUS2 cell from hidden service on circuit %u.",
1815 TO_CIRCUIT(circ)->n_circ_id);
1817 ret = (circ->hs_ident) ? handle_rendezvous2(circ, payload, payload_len) :
1818 rend_client_receive_rendezvous(circ, payload,
1819 payload_len);
1820 end:
1821 return ret;
1824 /* Extend the introduction circuit circ to another valid introduction point
1825 * for the hidden service it is trying to connect to, or mark it and launch a
1826 * new circuit if we can't extend it. Return 0 on success or possible
1827 * success. Return -1 and mark the introduction circuit for close on permanent
1828 * failure.
1830 * On failure, the caller is responsible for marking the associated rendezvous
1831 * circuit for close. */
1833 hs_client_reextend_intro_circuit(origin_circuit_t *circ)
1835 int ret = -1;
1836 extend_info_t *ei;
1838 tor_assert(circ);
1840 ei = (circ->hs_ident) ?
1841 client_get_random_intro(&circ->hs_ident->identity_pk) :
1842 rend_client_get_random_intro(circ->rend_data);
1843 if (ei == NULL) {
1844 log_warn(LD_REND, "No usable introduction points left. Closing.");
1845 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
1846 goto end;
1849 if (circ->remaining_relay_early_cells) {
1850 log_info(LD_REND, "Re-extending circ %u, this time to %s.",
1851 (unsigned int) TO_CIRCUIT(circ)->n_circ_id,
1852 safe_str_client(extend_info_describe(ei)));
1853 ret = circuit_extend_to_new_exit(circ, ei);
1854 if (ret == 0) {
1855 /* We were able to extend so update the timestamp so we avoid expiring
1856 * this circuit too early. The intro circuit is short live so the
1857 * linkability issue is minimized, we just need the circuit to hold a
1858 * bit longer so we can introduce. */
1859 TO_CIRCUIT(circ)->timestamp_dirty = time(NULL);
1861 } else {
1862 log_info(LD_REND, "Closing intro circ %u (out of RELAY_EARLY cells).",
1863 (unsigned int) TO_CIRCUIT(circ)->n_circ_id);
1864 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
1865 /* connection_ap_handshake_attach_circuit will launch a new intro circ. */
1866 ret = 0;
1869 end:
1870 extend_info_free(ei);
1871 return ret;
1874 /* Close all client introduction circuits related to the given descriptor.
1875 * This is called with a descriptor that is about to get replaced in the
1876 * client cache.
1878 * Even though the introduction point might be exactly the same, we'll rebuild
1879 * them if needed but the odds are very low that an existing matching
1880 * introduction circuit exists at that stage. */
1881 void
1882 hs_client_close_intro_circuits_from_desc(const hs_descriptor_t *desc)
1884 origin_circuit_t *ocirc = NULL;
1886 tor_assert(desc);
1888 /* We iterate over all client intro circuits because they aren't kept in the
1889 * HS circuitmap. That is probably something we want to do one day. */
1890 while ((ocirc = circuit_get_next_intro_circ(ocirc, true))) {
1891 if (ocirc->hs_ident == NULL) {
1892 /* Not a v3 circuit, ignore it. */
1893 continue;
1896 /* Does it match any IP in the given descriptor? If not, ignore. */
1897 if (find_desc_intro_point_by_ident(ocirc->hs_ident, desc) == NULL) {
1898 continue;
1901 /* We have a match. Close the circuit as consider it expired. */
1902 circuit_mark_for_close(TO_CIRCUIT(ocirc), END_CIRC_REASON_FINISHED);
1906 /* Release all the storage held by the client subsystem. */
1907 void
1908 hs_client_free_all(void)
1910 /* Purge the hidden service request cache. */
1911 hs_purge_last_hid_serv_requests();
1912 client_service_authorization_free_all();
1915 /* Purge all potentially remotely-detectable state held in the hidden
1916 * service client code. Called on SIGNAL NEWNYM. */
1917 void
1918 hs_client_purge_state(void)
1920 /* v2 subsystem. */
1921 rend_client_purge_state();
1923 /* Cancel all descriptor fetches. Do this first so once done we are sure
1924 * that our descriptor cache won't modified. */
1925 cancel_descriptor_fetches();
1926 /* Purge the introduction point state cache. */
1927 hs_cache_client_intro_state_purge();
1928 /* Purge the descriptor cache. */
1929 hs_cache_purge_as_client();
1930 /* Purge the last hidden service request cache. */
1931 hs_purge_last_hid_serv_requests();
1933 log_info(LD_REND, "Hidden service client state has been purged.");
1936 /* Called when our directory information has changed. */
1937 void
1938 hs_client_dir_info_changed(void)
1940 /* We have possibly reached the minimum directory information or new
1941 * consensus so retry all pending SOCKS connection in
1942 * AP_CONN_STATE_RENDDESC_WAIT state in order to fetch the descriptor. */
1943 retry_all_socks_conn_waiting_for_desc();
1946 #ifdef TOR_UNIT_TESTS
1948 STATIC digest256map_t *
1949 get_hs_client_auths_map(void)
1951 return client_auths;
1954 #endif /* defined(TOR_UNIT_TESTS) */