1 /* Copyright (c) 2016-2019, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
6 * \brief Implement next generation hidden service client functionality
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 /* Return a human-readable string for the client fetch status code. */
52 fetch_status_to_string(hs_client_fetch_status_t status
)
55 case HS_CLIENT_FETCH_ERROR
:
56 return "Internal error";
57 case HS_CLIENT_FETCH_LAUNCHED
:
58 return "Descriptor fetch launched";
59 case HS_CLIENT_FETCH_HAVE_DESC
:
60 return "Already have descriptor";
61 case HS_CLIENT_FETCH_NO_HSDIRS
:
62 return "No more HSDir available to query";
63 case HS_CLIENT_FETCH_NOT_ALLOWED
:
64 return "Fetching descriptors is not allowed";
65 case HS_CLIENT_FETCH_MISSING_INFO
:
66 return "Missing directory information";
67 case HS_CLIENT_FETCH_PENDING
:
68 return "Pending descriptor fetch";
70 return "(Unknown client fetch status code)";
74 /* Return true iff tor should close the SOCKS request(s) for the descriptor
75 * fetch that ended up with this given status code. */
77 fetch_status_should_close_socks(hs_client_fetch_status_t status
)
80 case HS_CLIENT_FETCH_NO_HSDIRS
:
81 /* No more HSDir to query, we can't complete the SOCKS request(s). */
82 case HS_CLIENT_FETCH_ERROR
:
83 /* The fetch triggered an internal error. */
84 case HS_CLIENT_FETCH_NOT_ALLOWED
:
85 /* Client is not allowed to fetch (FetchHidServDescriptors 0). */
87 case HS_CLIENT_FETCH_MISSING_INFO
:
88 case HS_CLIENT_FETCH_HAVE_DESC
:
89 case HS_CLIENT_FETCH_PENDING
:
90 case HS_CLIENT_FETCH_LAUNCHED
:
91 /* The rest doesn't require tor to close the SOCKS request(s). */
101 /* Cancel all descriptor fetches currently in progress. */
103 cancel_descriptor_fetches(void)
106 connection_list_by_type_state(CONN_TYPE_DIR
, DIR_PURPOSE_FETCH_HSDESC
);
107 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
108 const hs_ident_dir_conn_t
*ident
= TO_DIR_CONN(conn
)->hs_ident
;
109 if (BUG(ident
== NULL
)) {
110 /* A directory connection fetching a service descriptor can't have an
111 * empty hidden service identifier. */
114 log_debug(LD_REND
, "Marking for close a directory connection fetching "
115 "a hidden service descriptor for service %s.",
116 safe_str_client(ed25519_fmt(&ident
->identity_pk
)));
117 connection_mark_for_close(conn
);
118 } SMARTLIST_FOREACH_END(conn
);
120 /* No ownership of the objects in this list. */
121 smartlist_free(conns
);
122 log_info(LD_REND
, "Hidden service client descriptor fetches cancelled.");
125 /* Get all connections that are waiting on a circuit and flag them back to
126 * waiting for a hidden service descriptor for the given service key
127 * service_identity_pk. */
129 flag_all_conn_wait_desc(const ed25519_public_key_t
*service_identity_pk
)
131 tor_assert(service_identity_pk
);
134 connection_list_by_type_state(CONN_TYPE_AP
, AP_CONN_STATE_CIRCUIT_WAIT
);
136 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
137 edge_connection_t
*edge_conn
;
138 if (BUG(!CONN_IS_EDGE(conn
))) {
141 edge_conn
= TO_EDGE_CONN(conn
);
142 if (edge_conn
->hs_ident
&&
143 ed25519_pubkey_eq(&edge_conn
->hs_ident
->identity_pk
,
144 service_identity_pk
)) {
145 connection_ap_mark_as_waiting_for_renddesc(TO_ENTRY_CONN(conn
));
147 } SMARTLIST_FOREACH_END(conn
);
149 smartlist_free(conns
);
152 /* Remove tracked HSDir requests from our history for this hidden service
153 * identity public key. */
155 purge_hid_serv_request(const ed25519_public_key_t
*identity_pk
)
157 char base64_blinded_pk
[ED25519_BASE64_LEN
+ 1];
158 ed25519_public_key_t blinded_pk
;
160 tor_assert(identity_pk
);
162 /* Get blinded pubkey of hidden service. It is possible that we just moved
163 * to a new time period meaning that we won't be able to purge the request
164 * from the previous time period. That is fine because they will expire at
165 * some point and we don't care about those anymore. */
166 hs_build_blinded_pubkey(identity_pk
, NULL
, 0,
167 hs_get_time_period_num(0), &blinded_pk
);
168 if (BUG(ed25519_public_to_base64(base64_blinded_pk
, &blinded_pk
) < 0)) {
171 /* Purge last hidden service request from cache for this blinded key. */
172 hs_purge_hid_serv_from_last_hid_serv_requests(base64_blinded_pk
);
175 /* Return true iff there is at least one pending directory descriptor request
176 * for the service identity_pk. */
178 directory_request_is_pending(const ed25519_public_key_t
*identity_pk
)
182 connection_list_by_type_purpose(CONN_TYPE_DIR
, DIR_PURPOSE_FETCH_HSDESC
);
184 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
185 const hs_ident_dir_conn_t
*ident
= TO_DIR_CONN(conn
)->hs_ident
;
186 if (BUG(ident
== NULL
)) {
187 /* A directory connection fetching a service descriptor can't have an
188 * empty hidden service identifier. */
191 if (!ed25519_pubkey_eq(identity_pk
, &ident
->identity_pk
)) {
196 } SMARTLIST_FOREACH_END(conn
);
198 /* No ownership of the objects in this list. */
199 smartlist_free(conns
);
203 /* Helper function that changes the state of an entry connection to waiting
204 * for a circuit. For this to work properly, the connection timestamps are set
205 * to now and the connection is then marked as pending for a circuit. */
207 mark_conn_as_waiting_for_circuit(connection_t
*conn
, time_t now
)
211 /* Because the connection can now proceed to opening circuit and ultimately
212 * connect to the service, reset those timestamp so the connection is
213 * considered "fresh" and can continue without being closed too early. */
214 conn
->timestamp_created
= now
;
215 conn
->timestamp_last_read_allowed
= now
;
216 conn
->timestamp_last_write_allowed
= now
;
217 /* Change connection's state into waiting for a circuit. */
218 conn
->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
220 connection_ap_mark_as_pending_circuit(TO_ENTRY_CONN(conn
));
223 /* We failed to fetch a descriptor for the service with <b>identity_pk</b>
224 * because of <b>status</b>. Find all pending SOCKS connections for this
225 * service that are waiting on the descriptor and close them with
228 close_all_socks_conns_waiting_for_desc(const ed25519_public_key_t
*identity_pk
,
229 hs_client_fetch_status_t status
,
232 unsigned int count
= 0;
233 time_t now
= approx_time();
235 connection_list_by_type_state(CONN_TYPE_AP
, AP_CONN_STATE_RENDDESC_WAIT
);
237 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, base_conn
) {
238 entry_connection_t
*entry_conn
= TO_ENTRY_CONN(base_conn
);
239 const edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(entry_conn
);
241 /* Only consider the entry connections that matches the service for which
242 * we tried to get the descriptor */
243 if (!edge_conn
->hs_ident
||
244 !ed25519_pubkey_eq(identity_pk
,
245 &edge_conn
->hs_ident
->identity_pk
)) {
248 assert_connection_ok(base_conn
, now
);
249 /* Unattach the entry connection which will close for the reason. */
250 connection_mark_unattached_ap(entry_conn
, reason
);
252 } SMARTLIST_FOREACH_END(base_conn
);
255 char onion_address
[HS_SERVICE_ADDR_LEN_BASE32
+ 1];
256 hs_build_address(identity_pk
, HS_VERSION_THREE
, onion_address
);
257 log_notice(LD_REND
, "Closed %u streams for service %s.onion "
258 "for reason %s. Fetch status: %s.",
259 count
, safe_str_client(onion_address
),
260 stream_end_reason_to_string(reason
),
261 fetch_status_to_string(status
));
264 /* No ownership of the object(s) in this list. */
265 smartlist_free(conns
);
268 /* Find all pending SOCKS connection waiting for a descriptor and retry them
269 * all. This is called when the directory information changed. */
271 retry_all_socks_conn_waiting_for_desc(void)
274 connection_list_by_type_state(CONN_TYPE_AP
, AP_CONN_STATE_RENDDESC_WAIT
);
276 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, base_conn
) {
277 hs_client_fetch_status_t status
;
278 const edge_connection_t
*edge_conn
=
279 ENTRY_TO_EDGE_CONN(TO_ENTRY_CONN(base_conn
));
281 /* Ignore non HS or non v3 connection. */
282 if (edge_conn
->hs_ident
== NULL
) {
285 /* In this loop, we will possibly try to fetch a descriptor for the
286 * pending connections because we just got more directory information.
287 * However, the refetch process can cleanup all SOCKS request to the same
288 * service if an internal error happens. Thus, we can end up with closed
289 * connections in our list. */
290 if (base_conn
->marked_for_close
) {
294 /* XXX: There is an optimization we could do which is that for a service
295 * key, we could check if we can fetch and remember that decision. */
297 /* Order a refetch in case it works this time. */
298 status
= hs_client_refetch_hsdesc(&edge_conn
->hs_ident
->identity_pk
);
299 if (status
== HS_CLIENT_FETCH_HAVE_DESC
) {
300 /* This is a rare case where a SOCKS connection is in state waiting for
301 * a descriptor but we do have it in the cache.
303 * This can happen is tor comes back from suspend where it previously
304 * had the descriptor but the intro points were not usuable. Once it
305 * came back to life, the intro point failure cache was cleaned up and
306 * thus the descriptor became usable again leaving us in this code path.
308 * We'll mark the connection as waiting for a circuit so the descriptor
309 * can be retried. This is safe because a connection in state waiting
310 * for a descriptor can not be in the entry connection pending list. */
311 mark_conn_as_waiting_for_circuit(base_conn
, approx_time());
314 /* In the case of an error, either all SOCKS connections have been
315 * closed or we are still missing directory information. Leave the
316 * connection in renddesc wait state so when we get more info, we'll be
317 * able to try it again. */
318 } SMARTLIST_FOREACH_END(base_conn
);
320 /* We don't have ownership of those objects. */
321 smartlist_free(conns
);
324 /* A v3 HS circuit successfully connected to the hidden service. Update the
325 * stream state at <b>hs_conn_ident</b> appropriately. */
327 note_connection_attempt_succeeded(const hs_ident_edge_conn_t
*hs_conn_ident
)
329 tor_assert(hs_conn_ident
);
331 /* Remove from the hid serv cache all requests for that service so we can
332 * query the HSDir again later on for various reasons. */
333 purge_hid_serv_request(&hs_conn_ident
->identity_pk
);
335 /* The v2 subsystem cleans up the intro point time out flag at this stage.
336 * We don't try to do it here because we still need to keep intact the intro
337 * point state for future connections. Even though we are able to connect to
338 * the service, doesn't mean we should reset the timed out intro points.
340 * It is not possible to have successfully connected to an intro point
341 * present in our cache that was on error or timed out. Every entry in that
342 * cache have a 2 minutes lifetime so ultimately the intro point(s) state
343 * will be reset and thus possible to be retried. */
346 /* Given the pubkey of a hidden service in <b>onion_identity_pk</b>, fetch its
347 * descriptor by launching a dir connection to <b>hsdir</b>. Return a
348 * hs_client_fetch_status_t status code depending on how it went. */
349 static hs_client_fetch_status_t
350 directory_launch_v3_desc_fetch(const ed25519_public_key_t
*onion_identity_pk
,
351 const routerstatus_t
*hsdir
)
353 uint64_t current_time_period
= hs_get_time_period_num(0);
354 ed25519_public_key_t blinded_pubkey
;
355 char base64_blinded_pubkey
[ED25519_BASE64_LEN
+ 1];
356 hs_ident_dir_conn_t hs_conn_dir_ident
;
360 tor_assert(onion_identity_pk
);
362 /* Get blinded pubkey */
363 hs_build_blinded_pubkey(onion_identity_pk
, NULL
, 0,
364 current_time_period
, &blinded_pubkey
);
365 /* ...and base64 it. */
366 retval
= ed25519_public_to_base64(base64_blinded_pubkey
, &blinded_pubkey
);
367 if (BUG(retval
< 0)) {
368 return HS_CLIENT_FETCH_ERROR
;
371 /* Copy onion pk to a dir_ident so that we attach it to the dir conn */
372 hs_ident_dir_conn_init(onion_identity_pk
, &blinded_pubkey
,
375 /* Setup directory request */
376 directory_request_t
*req
=
377 directory_request_new(DIR_PURPOSE_FETCH_HSDESC
);
378 directory_request_set_routerstatus(req
, hsdir
);
379 directory_request_set_indirection(req
, DIRIND_ANONYMOUS
);
380 directory_request_set_resource(req
, base64_blinded_pubkey
);
381 directory_request_fetch_set_hs_ident(req
, &hs_conn_dir_ident
);
382 directory_initiate_request(req
);
383 directory_request_free(req
);
385 log_info(LD_REND
, "Descriptor fetch request for service %s with blinded "
386 "key %s to directory %s",
387 safe_str_client(ed25519_fmt(onion_identity_pk
)),
388 safe_str_client(base64_blinded_pubkey
),
389 safe_str_client(routerstatus_describe(hsdir
)));
391 /* Fire a REQUESTED event on the control port. */
392 hs_control_desc_event_requested(onion_identity_pk
, base64_blinded_pubkey
,
395 /* Cleanup memory. */
396 memwipe(&blinded_pubkey
, 0, sizeof(blinded_pubkey
));
397 memwipe(base64_blinded_pubkey
, 0, sizeof(base64_blinded_pubkey
));
398 memwipe(&hs_conn_dir_ident
, 0, sizeof(hs_conn_dir_ident
));
400 return HS_CLIENT_FETCH_LAUNCHED
;
403 /** Return the HSDir we should use to fetch the descriptor of the hidden
404 * service with identity key <b>onion_identity_pk</b>. */
405 STATIC routerstatus_t
*
406 pick_hsdir_v3(const ed25519_public_key_t
*onion_identity_pk
)
409 char base64_blinded_pubkey
[ED25519_BASE64_LEN
+ 1];
410 uint64_t current_time_period
= hs_get_time_period_num(0);
411 smartlist_t
*responsible_hsdirs
= NULL
;
412 ed25519_public_key_t blinded_pubkey
;
413 routerstatus_t
*hsdir_rs
= NULL
;
415 tor_assert(onion_identity_pk
);
417 /* Get blinded pubkey of hidden service */
418 hs_build_blinded_pubkey(onion_identity_pk
, NULL
, 0,
419 current_time_period
, &blinded_pubkey
);
420 /* ...and base64 it. */
421 retval
= ed25519_public_to_base64(base64_blinded_pubkey
, &blinded_pubkey
);
422 if (BUG(retval
< 0)) {
426 /* Get responsible hsdirs of service for this time period */
427 responsible_hsdirs
= smartlist_new();
429 hs_get_responsible_hsdirs(&blinded_pubkey
, current_time_period
,
430 0, 1, responsible_hsdirs
);
432 log_debug(LD_REND
, "Found %d responsible HSDirs and about to pick one.",
433 smartlist_len(responsible_hsdirs
));
435 /* Pick an HSDir from the responsible ones. The ownership of
436 * responsible_hsdirs is given to this function so no need to free it. */
437 hsdir_rs
= hs_pick_hsdir(responsible_hsdirs
, base64_blinded_pubkey
);
442 /** Fetch a v3 descriptor using the given <b>onion_identity_pk</b>.
444 * On success, HS_CLIENT_FETCH_LAUNCHED is returned. Otherwise, an error from
445 * hs_client_fetch_status_t is returned. */
446 MOCK_IMPL(STATIC hs_client_fetch_status_t
,
447 fetch_v3_desc
, (const ed25519_public_key_t
*onion_identity_pk
))
449 routerstatus_t
*hsdir_rs
=NULL
;
451 tor_assert(onion_identity_pk
);
453 hsdir_rs
= pick_hsdir_v3(onion_identity_pk
);
455 log_info(LD_REND
, "Couldn't pick a v3 hsdir.");
456 return HS_CLIENT_FETCH_NO_HSDIRS
;
459 return directory_launch_v3_desc_fetch(onion_identity_pk
, hsdir_rs
);
462 /* Make sure that the given v3 origin circuit circ is a valid correct
463 * introduction circuit. This will BUG() on any problems and hard assert if
464 * the anonymity of the circuit is not ok. Return 0 on success else -1 where
465 * the circuit should be mark for closed immediately. */
467 intro_circ_is_ok(const origin_circuit_t
*circ
)
473 if (BUG(TO_CIRCUIT(circ
)->purpose
!= CIRCUIT_PURPOSE_C_INTRODUCING
&&
474 TO_CIRCUIT(circ
)->purpose
!= CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
&&
475 TO_CIRCUIT(circ
)->purpose
!= CIRCUIT_PURPOSE_C_INTRODUCE_ACKED
)) {
478 if (BUG(circ
->hs_ident
== NULL
)) {
481 if (BUG(!hs_ident_intro_circ_is_valid(circ
->hs_ident
))) {
485 /* This can stop the tor daemon but we want that since if we don't have
486 * anonymity on this circuit, something went really wrong. */
487 assert_circ_anonymity_ok(circ
, get_options());
491 /* Find a descriptor intro point object that matches the given ident in the
492 * given descriptor desc. Return NULL if not found. */
493 static const hs_desc_intro_point_t
*
494 find_desc_intro_point_by_ident(const hs_ident_circuit_t
*ident
,
495 const hs_descriptor_t
*desc
)
497 const hs_desc_intro_point_t
*intro_point
= NULL
;
502 SMARTLIST_FOREACH_BEGIN(desc
->encrypted_data
.intro_points
,
503 const hs_desc_intro_point_t
*, ip
) {
504 if (ed25519_pubkey_eq(&ident
->intro_auth_pk
,
505 &ip
->auth_key_cert
->signed_key
)) {
509 } SMARTLIST_FOREACH_END(ip
);
514 /* Find a descriptor intro point object from the descriptor object desc that
515 * matches the given legacy identity digest in legacy_id. Return NULL if not
517 static hs_desc_intro_point_t
*
518 find_desc_intro_point_by_legacy_id(const char *legacy_id
,
519 const hs_descriptor_t
*desc
)
521 hs_desc_intro_point_t
*ret_ip
= NULL
;
523 tor_assert(legacy_id
);
526 /* We will go over every intro point and try to find which one is linked to
527 * that circuit. Those lists are small so it's not that expensive. */
528 SMARTLIST_FOREACH_BEGIN(desc
->encrypted_data
.intro_points
,
529 hs_desc_intro_point_t
*, ip
) {
530 SMARTLIST_FOREACH_BEGIN(ip
->link_specifiers
,
531 const hs_desc_link_specifier_t
*, lspec
) {
532 /* Not all tor node have an ed25519 identity key so we still rely on the
533 * legacy identity digest. */
534 if (lspec
->type
!= LS_LEGACY_ID
) {
537 if (fast_memneq(legacy_id
, lspec
->u
.legacy_id
, DIGEST_LEN
)) {
543 } SMARTLIST_FOREACH_END(lspec
);
544 } SMARTLIST_FOREACH_END(ip
);
550 /* Send an INTRODUCE1 cell along the intro circuit and populate the rend
551 * circuit identifier with the needed key material for the e2e encryption.
552 * Return 0 on success, -1 if there is a transient error such that an action
553 * has been taken to recover and -2 if there is a permanent error indicating
554 * that both circuits were closed. */
556 send_introduce1(origin_circuit_t
*intro_circ
,
557 origin_circuit_t
*rend_circ
)
560 char onion_address
[HS_SERVICE_ADDR_LEN_BASE32
+ 1];
561 const ed25519_public_key_t
*service_identity_pk
= NULL
;
562 const hs_desc_intro_point_t
*ip
;
564 tor_assert(rend_circ
);
565 if (intro_circ_is_ok(intro_circ
) < 0) {
569 service_identity_pk
= &intro_circ
->hs_ident
->identity_pk
;
570 /* For logging purposes. There will be a time where the hs_ident will have a
571 * version number but for now there is none because it's all v3. */
572 hs_build_address(service_identity_pk
, HS_VERSION_THREE
, onion_address
);
574 log_info(LD_REND
, "Sending INTRODUCE1 cell to service %s on circuit %u",
575 safe_str_client(onion_address
), TO_CIRCUIT(intro_circ
)->n_circ_id
);
577 /* 1) Get descriptor from our cache. */
578 const hs_descriptor_t
*desc
=
579 hs_cache_lookup_as_client(service_identity_pk
);
580 if (desc
== NULL
|| !hs_client_any_intro_points_usable(service_identity_pk
,
582 log_info(LD_REND
, "Request to %s %s. Trying to fetch a new descriptor.",
583 safe_str_client(onion_address
),
584 (desc
) ? "didn't have usable intro points" :
585 "didn't have a descriptor");
586 hs_client_refetch_hsdesc(service_identity_pk
);
587 /* We just triggered a refetch, make sure every connections are back
588 * waiting for that descriptor. */
589 flag_all_conn_wait_desc(service_identity_pk
);
590 /* We just asked for a refetch so this is a transient error. */
594 /* We need to find which intro point in the descriptor we are connected to
596 ip
= find_desc_intro_point_by_ident(intro_circ
->hs_ident
, desc
);
597 if (BUG(ip
== NULL
)) {
598 /* If we can find a descriptor from this introduction circuit ident, we
599 * must have a valid intro point object. Permanent error. */
603 /* Send the INTRODUCE1 cell. */
604 if (hs_circ_send_introduce1(intro_circ
, rend_circ
, ip
,
605 desc
->subcredential
) < 0) {
606 if (TO_CIRCUIT(intro_circ
)->marked_for_close
) {
607 /* If the introduction circuit was closed, we were unable to send the
608 * cell for some reasons. In any case, the intro circuit has to be
609 * closed by the above function. We'll return a transient error so tor
610 * can recover and pick a new intro point. To avoid picking that same
611 * intro point, we'll note down the intro point failure so it doesn't
613 hs_cache_client_intro_state_note(service_identity_pk
,
614 &intro_circ
->hs_ident
->intro_auth_pk
,
615 INTRO_POINT_FAILURE_GENERIC
);
617 /* It is also possible that the rendezvous circuit was closed due to being
618 * unable to use the rendezvous point node_t so in that case, we also want
619 * to recover and let tor pick a new one. */
623 /* Cell has been sent successfully. Copy the introduction point
624 * authentication and encryption key in the rendezvous circuit identifier so
625 * we can compute the ntor keys when we receive the RENDEZVOUS2 cell. */
626 memcpy(&rend_circ
->hs_ident
->intro_enc_pk
, &ip
->enc_key
,
627 sizeof(rend_circ
->hs_ident
->intro_enc_pk
));
628 ed25519_pubkey_copy(&rend_circ
->hs_ident
->intro_auth_pk
,
629 &intro_circ
->hs_ident
->intro_auth_pk
);
631 /* Now, we wait for an ACK or NAK on this circuit. */
632 circuit_change_purpose(TO_CIRCUIT(intro_circ
),
633 CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
);
634 /* Set timestamp_dirty, because circuit_expire_building expects it to
635 * specify when a circuit entered the _C_INTRODUCE_ACK_WAIT state. */
636 TO_CIRCUIT(intro_circ
)->timestamp_dirty
= time(NULL
);
637 pathbias_count_use_attempt(intro_circ
);
644 /* Permanent error: it is possible that the intro circuit was closed prior
645 * because we weren't able to send the cell. Make sure we don't double close
646 * it which would result in a warning. */
647 if (!TO_CIRCUIT(intro_circ
)->marked_for_close
) {
648 circuit_mark_for_close(TO_CIRCUIT(intro_circ
), END_CIRC_REASON_INTERNAL
);
650 circuit_mark_for_close(TO_CIRCUIT(rend_circ
), END_CIRC_REASON_INTERNAL
);
658 memwipe(onion_address
, 0, sizeof(onion_address
));
662 /* Using the introduction circuit circ, setup the authentication key of the
663 * intro point this circuit has extended to. */
665 setup_intro_circ_auth_key(origin_circuit_t
*circ
)
667 const hs_descriptor_t
*desc
;
668 const hs_desc_intro_point_t
*ip
;
672 desc
= hs_cache_lookup_as_client(&circ
->hs_ident
->identity_pk
);
673 if (BUG(desc
== NULL
)) {
674 /* Opening intro circuit without the descriptor is no good... */
678 /* We will go over every intro point and try to find which one is linked to
679 * that circuit. Those lists are small so it's not that expensive. */
680 ip
= find_desc_intro_point_by_legacy_id(
681 circ
->build_state
->chosen_exit
->identity_digest
, desc
);
683 /* We got it, copy its authentication key to the identifier. */
684 ed25519_pubkey_copy(&circ
->hs_ident
->intro_auth_pk
,
685 &ip
->auth_key_cert
->signed_key
);
689 /* Reaching this point means we didn't find any intro point for this circuit
690 * which is not suppose to happen. */
691 tor_assert_nonfatal_unreached();
697 /* Called when an introduction circuit has opened. */
699 client_intro_circ_has_opened(origin_circuit_t
*circ
)
702 tor_assert(TO_CIRCUIT(circ
)->purpose
== CIRCUIT_PURPOSE_C_INTRODUCING
);
703 log_info(LD_REND
, "Introduction circuit %u has opened. Attaching streams.",
704 (unsigned int) TO_CIRCUIT(circ
)->n_circ_id
);
706 /* This is an introduction circuit so we'll attach the correct
707 * authentication key to the circuit identifier so it can be identified
708 * properly later on. */
709 setup_intro_circ_auth_key(circ
);
711 connection_ap_attach_pending(1);
714 /* Called when a rendezvous circuit has opened. */
716 client_rendezvous_circ_has_opened(origin_circuit_t
*circ
)
719 tor_assert(TO_CIRCUIT(circ
)->purpose
== CIRCUIT_PURPOSE_C_ESTABLISH_REND
);
721 const extend_info_t
*rp_ei
= circ
->build_state
->chosen_exit
;
723 /* Check that we didn't accidentally choose a node that does not understand
724 * the v3 rendezvous protocol */
726 const node_t
*rp_node
= node_get_by_id(rp_ei
->identity_digest
);
728 if (BUG(!node_supports_v3_rendezvous_point(rp_node
))) {
734 log_info(LD_REND
, "Rendezvous circuit has opened to %s.",
735 safe_str_client(extend_info_describe(rp_ei
)));
737 /* Ignore returned value, nothing we can really do. On failure, the circuit
738 * will be marked for close. */
739 hs_circ_send_establish_rendezvous(circ
);
741 /* Register rend circuit in circuitmap if it's still alive. */
742 if (!TO_CIRCUIT(circ
)->marked_for_close
) {
743 hs_circuitmap_register_rend_circ_client_side(circ
,
744 circ
->hs_ident
->rendezvous_cookie
);
748 /* This is an helper function that convert a descriptor intro point object ip
749 * to a newly allocated extend_info_t object fully initialized. Return NULL if
750 * we can't convert it for which chances are that we are missing or malformed
751 * link specifiers. */
752 STATIC extend_info_t
*
753 desc_intro_point_to_extend_info(const hs_desc_intro_point_t
*ip
)
756 smartlist_t
*lspecs
= smartlist_new();
760 /* We first encode the descriptor link specifiers into the binary
761 * representation which is a trunnel object. */
762 SMARTLIST_FOREACH_BEGIN(ip
->link_specifiers
,
763 const hs_desc_link_specifier_t
*, desc_lspec
) {
764 link_specifier_t
*lspec
= hs_desc_lspec_to_trunnel(desc_lspec
);
765 smartlist_add(lspecs
, lspec
);
766 } SMARTLIST_FOREACH_END(desc_lspec
);
768 /* Explicitly put the direct connection option to 0 because this is client
769 * side and there is no such thing as a non anonymous client. */
770 ei
= hs_get_extend_info_from_lspecs(lspecs
, &ip
->onion_key
, 0);
772 SMARTLIST_FOREACH(lspecs
, link_specifier_t
*, ls
, link_specifier_free(ls
));
773 smartlist_free(lspecs
);
777 /* Return true iff the intro point ip for the service service_pk is usable.
778 * This function checks if the intro point is in the client intro state cache
779 * and checks at the failures. It is considered usable if:
780 * - No error happened (INTRO_POINT_FAILURE_GENERIC)
781 * - It is not flagged as timed out (INTRO_POINT_FAILURE_TIMEOUT)
782 * - The unreachable count is lower than
783 * MAX_INTRO_POINT_REACHABILITY_FAILURES (INTRO_POINT_FAILURE_UNREACHABLE)
786 intro_point_is_usable(const ed25519_public_key_t
*service_pk
,
787 const hs_desc_intro_point_t
*ip
)
789 const hs_cache_intro_state_t
*state
;
791 tor_assert(service_pk
);
794 state
= hs_cache_client_intro_state_find(service_pk
,
795 &ip
->auth_key_cert
->signed_key
);
797 /* This means we've never encountered any problem thus usable. */
801 log_info(LD_REND
, "Intro point with auth key %s had an error. Not usable",
802 safe_str_client(ed25519_fmt(&ip
->auth_key_cert
->signed_key
)));
805 if (state
->timed_out
) {
806 log_info(LD_REND
, "Intro point with auth key %s timed out. Not usable",
807 safe_str_client(ed25519_fmt(&ip
->auth_key_cert
->signed_key
)));
810 if (state
->unreachable_count
>= MAX_INTRO_POINT_REACHABILITY_FAILURES
) {
811 log_info(LD_REND
, "Intro point with auth key %s unreachable. Not usable",
812 safe_str_client(ed25519_fmt(&ip
->auth_key_cert
->signed_key
)));
822 /* Using a descriptor desc, return a newly allocated extend_info_t object of a
823 * randomly picked introduction point from its list. Return NULL if none are
825 STATIC extend_info_t
*
826 client_get_random_intro(const ed25519_public_key_t
*service_pk
)
828 extend_info_t
*ei
= NULL
, *ei_excluded
= NULL
;
829 smartlist_t
*usable_ips
= NULL
;
830 const hs_descriptor_t
*desc
;
831 const hs_desc_encrypted_data_t
*enc_data
;
832 const or_options_t
*options
= get_options();
833 /* Calculate the onion address for logging purposes */
834 char onion_address
[HS_SERVICE_ADDR_LEN_BASE32
+ 1];
836 tor_assert(service_pk
);
838 desc
= hs_cache_lookup_as_client(service_pk
);
839 /* Assume the service is v3 if the descriptor is missing. This is ok,
840 * because we only use the address in log messages */
841 hs_build_address(service_pk
,
842 desc
? desc
->plaintext_data
.version
: HS_VERSION_THREE
,
844 if (desc
== NULL
|| !hs_client_any_intro_points_usable(service_pk
,
846 log_info(LD_REND
, "Unable to randomly select an introduction point "
847 "for service %s because descriptor %s. We can't connect.",
848 safe_str_client(onion_address
),
849 (desc
) ? "doesn't have any usable intro points"
850 : "is missing (assuming v3 onion address)");
854 enc_data
= &desc
->encrypted_data
;
855 usable_ips
= smartlist_new();
856 smartlist_add_all(usable_ips
, enc_data
->intro_points
);
857 while (smartlist_len(usable_ips
) != 0) {
859 const hs_desc_intro_point_t
*ip
;
861 /* Pick a random intro point and immediately remove it from the usable
862 * list so we don't pick it again if we have to iterate more. */
863 idx
= crypto_rand_int(smartlist_len(usable_ips
));
864 ip
= smartlist_get(usable_ips
, idx
);
865 smartlist_del(usable_ips
, idx
);
867 /* We need to make sure we have a usable intro points which is in a good
868 * state in our cache. */
869 if (!intro_point_is_usable(service_pk
, ip
)) {
873 /* Generate an extend info object from the intro point object. */
874 ei
= desc_intro_point_to_extend_info(ip
);
876 /* We can get here for instance if the intro point is a private address
877 * and we aren't allowed to extend to those. */
878 log_info(LD_REND
, "Unable to select introduction point with auth key %s "
879 "for service %s, because we could not extend to it.",
880 safe_str_client(ed25519_fmt(&ip
->auth_key_cert
->signed_key
)),
881 safe_str_client(onion_address
));
885 /* Test the pick against ExcludeNodes. */
886 if (routerset_contains_extendinfo(options
->ExcludeNodes
, ei
)) {
887 /* If this pick is in the ExcludeNodes list, we keep its reference so if
888 * we ever end up not being able to pick anything else and StrictNodes is
889 * unset, we'll use it. */
891 /* If something was already here free it. After the loop is gone we
892 * will examine the last excluded intro point, and that's fine since
893 * that's random anyway */
894 extend_info_free(ei_excluded
);
900 /* Good pick! Let's go with this. */
904 /* Reaching this point means a couple of things. Either we can't use any of
905 * the intro point listed because the IP address can't be extended to or it
906 * is listed in the ExcludeNodes list. In the later case, if StrictNodes is
907 * set, we are forced to not use anything. */
909 if (options
->StrictNodes
) {
910 log_warn(LD_REND
, "Every introduction point for service %s is in the "
911 "ExcludeNodes set and StrictNodes is set. We can't connect.",
912 safe_str_client(onion_address
));
913 extend_info_free(ei
);
916 log_fn(LOG_PROTOCOL_WARN
, LD_REND
, "Every introduction point for service "
917 "%s is unusable or we can't extend to it. We can't connect.",
918 safe_str_client(onion_address
));
922 smartlist_free(usable_ips
);
923 memwipe(onion_address
, 0, sizeof(onion_address
));
927 /* For this introduction circuit, we'll look at if we have any usable
928 * introduction point left for this service. If so, we'll use the circuit to
929 * re-extend to a new intro point. Else, we'll close the circuit and its
930 * corresponding rendezvous circuit. Return 0 if we are re-extending else -1
931 * if we are closing the circuits.
933 * This is called when getting an INTRODUCE_ACK cell with a NACK. */
935 close_or_reextend_intro_circ(origin_circuit_t
*intro_circ
)
938 const hs_descriptor_t
*desc
;
939 origin_circuit_t
*rend_circ
;
941 tor_assert(intro_circ
);
943 desc
= hs_cache_lookup_as_client(&intro_circ
->hs_ident
->identity_pk
);
944 if (BUG(desc
== NULL
)) {
945 /* We can't continue without a descriptor. */
948 /* We still have the descriptor, great! Let's try to see if we can
949 * re-extend by looking up if there are any usable intro points. */
950 if (!hs_client_any_intro_points_usable(&intro_circ
->hs_ident
->identity_pk
,
954 /* Try to re-extend now. */
955 if (hs_client_reextend_intro_circuit(intro_circ
) < 0) {
958 /* Success on re-extending. Don't return an error. */
963 /* Change the intro circuit purpose before so we don't report an intro point
964 * failure again triggering an extra descriptor fetch. The circuit can
965 * already be closed on failure to re-extend. */
966 if (!TO_CIRCUIT(intro_circ
)->marked_for_close
) {
967 circuit_change_purpose(TO_CIRCUIT(intro_circ
),
968 CIRCUIT_PURPOSE_C_INTRODUCE_ACKED
);
969 circuit_mark_for_close(TO_CIRCUIT(intro_circ
), END_CIRC_REASON_FINISHED
);
971 /* Close the related rendezvous circuit. */
972 rend_circ
= hs_circuitmap_get_rend_circ_client_side(
973 intro_circ
->hs_ident
->rendezvous_cookie
);
974 /* The rendezvous circuit might have collapsed while the INTRODUCE_ACK was
975 * inflight so we can't expect one every time. */
977 circuit_mark_for_close(TO_CIRCUIT(rend_circ
), END_CIRC_REASON_FINISHED
);
984 /* Called when we get an INTRODUCE_ACK success status code. Do the appropriate
985 * actions for the rendezvous point and finally close intro_circ. */
987 handle_introduce_ack_success(origin_circuit_t
*intro_circ
)
989 origin_circuit_t
*rend_circ
= NULL
;
991 tor_assert(intro_circ
);
993 log_info(LD_REND
, "Received INTRODUCE_ACK ack! Informing rendezvous");
995 /* Get the rendezvous circuit for this rendezvous cookie. */
996 uint8_t *rendezvous_cookie
= intro_circ
->hs_ident
->rendezvous_cookie
;
998 hs_circuitmap_get_established_rend_circ_client_side(rendezvous_cookie
);
999 if (rend_circ
== NULL
) {
1000 log_warn(LD_REND
, "Can't find any rendezvous circuit. Stopping");
1004 assert_circ_anonymity_ok(rend_circ
, get_options());
1006 /* It is possible to get a RENDEZVOUS2 cell before the INTRODUCE_ACK which
1007 * means that the circuit will be joined and already transmitting data. In
1008 * that case, simply skip the purpose change and close the intro circuit
1009 * like it should be. */
1010 if (TO_CIRCUIT(rend_circ
)->purpose
== CIRCUIT_PURPOSE_C_REND_JOINED
) {
1013 circuit_change_purpose(TO_CIRCUIT(rend_circ
),
1014 CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
);
1015 /* Set timestamp_dirty, because circuit_expire_building expects it to
1016 * specify when a circuit entered the
1017 * CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED state. */
1018 TO_CIRCUIT(rend_circ
)->timestamp_dirty
= time(NULL
);
1021 /* We don't need the intro circuit anymore. It did what it had to do! */
1022 circuit_change_purpose(TO_CIRCUIT(intro_circ
),
1023 CIRCUIT_PURPOSE_C_INTRODUCE_ACKED
);
1024 circuit_mark_for_close(TO_CIRCUIT(intro_circ
), END_CIRC_REASON_FINISHED
);
1026 /* XXX: Close pending intro circuits we might have in parallel. */
1030 /* Called when we get an INTRODUCE_ACK failure status code. Depending on our
1031 * failure cache status, either close the circuit or re-extend to a new
1032 * introduction point. */
1034 handle_introduce_ack_bad(origin_circuit_t
*circ
, int status
)
1038 log_info(LD_REND
, "Received INTRODUCE_ACK nack by %s. Reason: %u",
1039 safe_str_client(extend_info_describe(circ
->build_state
->chosen_exit
)),
1042 /* It's a NAK. The introduction point didn't relay our request. */
1043 circuit_change_purpose(TO_CIRCUIT(circ
), CIRCUIT_PURPOSE_C_INTRODUCING
);
1045 /* Note down this failure in the intro point failure cache. Depending on how
1046 * many times we've tried this intro point, close it or reextend. */
1047 hs_cache_client_intro_state_note(&circ
->hs_ident
->identity_pk
,
1048 &circ
->hs_ident
->intro_auth_pk
,
1049 INTRO_POINT_FAILURE_GENERIC
);
1052 /* Called when we get an INTRODUCE_ACK on the intro circuit circ. The encoded
1053 * cell is in payload of length payload_len. Return 0 on success else a
1054 * negative value. The circuit is either close or reuse to re-extend to a new
1055 * introduction point. */
1057 handle_introduce_ack(origin_circuit_t
*circ
, const uint8_t *payload
,
1060 int status
, ret
= -1;
1063 tor_assert(circ
->build_state
);
1064 tor_assert(circ
->build_state
->chosen_exit
);
1065 assert_circ_anonymity_ok(circ
, get_options());
1066 tor_assert(payload
);
1068 status
= hs_cell_parse_introduce_ack(payload
, payload_len
);
1070 case HS_CELL_INTRO_ACK_SUCCESS
:
1072 handle_introduce_ack_success(circ
);
1074 case HS_CELL_INTRO_ACK_FAILURE
:
1075 case HS_CELL_INTRO_ACK_BADFMT
:
1076 case HS_CELL_INTRO_ACK_NORELAY
:
1077 handle_introduce_ack_bad(circ
, status
);
1078 /* We are going to see if we have to close the circuits (IP and RP) or we
1079 * can re-extend to a new intro point. */
1080 ret
= close_or_reextend_intro_circ(circ
);
1083 log_info(LD_PROTOCOL
, "Unknown INTRODUCE_ACK status code %u from %s",
1085 safe_str_client(extend_info_describe(circ
->build_state
->chosen_exit
)));
1093 /* Called when we get a RENDEZVOUS2 cell on the rendezvous circuit circ. The
1094 * encoded cell is in payload of length payload_len. Return 0 on success or a
1095 * negative value on error. On error, the circuit is marked for close. */
1097 handle_rendezvous2(origin_circuit_t
*circ
, const uint8_t *payload
,
1101 curve25519_public_key_t server_pk
;
1102 uint8_t auth_mac
[DIGEST256_LEN
] = {0};
1103 uint8_t handshake_info
[CURVE25519_PUBKEY_LEN
+ sizeof(auth_mac
)] = {0};
1104 hs_ntor_rend_cell_keys_t keys
;
1105 const hs_ident_circuit_t
*ident
;
1108 tor_assert(payload
);
1110 /* Make things easier. */
1111 ident
= circ
->hs_ident
;
1114 if (hs_cell_parse_rendezvous2(payload
, payload_len
, handshake_info
,
1115 sizeof(handshake_info
)) < 0) {
1118 /* Get from the handshake info the SERVER_PK and AUTH_MAC. */
1119 memcpy(&server_pk
, handshake_info
, CURVE25519_PUBKEY_LEN
);
1120 memcpy(auth_mac
, handshake_info
+ CURVE25519_PUBKEY_LEN
, sizeof(auth_mac
));
1122 /* Generate the handshake info. */
1123 if (hs_ntor_client_get_rendezvous1_keys(&ident
->intro_auth_pk
,
1124 &ident
->rendezvous_client_kp
,
1125 &ident
->intro_enc_pk
, &server_pk
,
1127 log_info(LD_REND
, "Unable to compute the rendezvous keys.");
1131 /* Critical check, make sure that the MAC matches what we got with what we
1132 * computed just above. */
1133 if (!hs_ntor_client_rendezvous2_mac_is_good(&keys
, auth_mac
)) {
1134 log_info(LD_REND
, "Invalid MAC in RENDEZVOUS2. Rejecting cell.");
1138 /* Setup the e2e encryption on the circuit and finalize its state. */
1139 if (hs_circuit_setup_e2e_rend_circ(circ
, keys
.ntor_key_seed
,
1140 sizeof(keys
.ntor_key_seed
), 0) < 0) {
1141 log_info(LD_REND
, "Unable to setup the e2e encryption.");
1144 /* Success. Hidden service connection finalized! */
1149 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_TORPROTOCOL
);
1151 memwipe(&keys
, 0, sizeof(keys
));
1155 /* Return true iff the client can fetch a descriptor for this service public
1156 * identity key and status_out if not NULL is untouched. If the client can
1157 * _not_ fetch the descriptor and if status_out is not NULL, it is set with
1158 * the fetch status code. */
1160 can_client_refetch_desc(const ed25519_public_key_t
*identity_pk
,
1161 hs_client_fetch_status_t
*status_out
)
1163 hs_client_fetch_status_t status
;
1165 tor_assert(identity_pk
);
1167 /* Are we configured to fetch descriptors? */
1168 if (!get_options()->FetchHidServDescriptors
) {
1169 log_warn(LD_REND
, "We received an onion address for a hidden service "
1170 "descriptor but we are configured to not fetch.");
1171 status
= HS_CLIENT_FETCH_NOT_ALLOWED
;
1175 /* Without a live consensus we can't do any client actions. It is needed to
1176 * compute the hashring for a service. */
1177 if (!networkstatus_get_live_consensus(approx_time())) {
1178 log_info(LD_REND
, "Can't fetch descriptor for service %s because we "
1179 "are missing a live consensus. Stalling connection.",
1180 safe_str_client(ed25519_fmt(identity_pk
)));
1181 status
= HS_CLIENT_FETCH_MISSING_INFO
;
1185 if (!router_have_minimum_dir_info()) {
1186 log_info(LD_REND
, "Can't fetch descriptor for service %s because we "
1187 "dont have enough descriptors. Stalling connection.",
1188 safe_str_client(ed25519_fmt(identity_pk
)));
1189 status
= HS_CLIENT_FETCH_MISSING_INFO
;
1193 /* Check if fetching a desc for this HS is useful to us right now */
1195 const hs_descriptor_t
*cached_desc
= NULL
;
1196 cached_desc
= hs_cache_lookup_as_client(identity_pk
);
1197 if (cached_desc
&& hs_client_any_intro_points_usable(identity_pk
,
1199 log_info(LD_GENERAL
, "We would fetch a v3 hidden service descriptor "
1200 "but we already have a usable descriptor.");
1201 status
= HS_CLIENT_FETCH_HAVE_DESC
;
1206 /* Don't try to refetch while we have a pending request for it. */
1207 if (directory_request_is_pending(identity_pk
)) {
1208 log_info(LD_REND
, "Already a pending directory request. Waiting on it.");
1209 status
= HS_CLIENT_FETCH_PENDING
;
1213 /* Yes, client can fetch! */
1217 *status_out
= status
;
1222 /* Return the client auth in the map using the service identity public key.
1223 * Return NULL if it does not exist in the map. */
1224 static hs_client_service_authorization_t
*
1225 find_client_auth(const ed25519_public_key_t
*service_identity_pk
)
1227 /* If the map is not allocated, we can assume that we do not have any client
1228 * auth information. */
1229 if (!client_auths
) {
1232 return digest256map_get(client_auths
, service_identity_pk
->pubkey
);
1239 /** A circuit just finished connecting to a hidden service that the stream
1240 * <b>conn</b> has been waiting for. Let the HS subsystem know about this. */
1242 hs_client_note_connection_attempt_succeeded(const edge_connection_t
*conn
)
1244 tor_assert(connection_edge_is_rendezvous_stream(conn
));
1246 if (BUG(conn
->rend_data
&& conn
->hs_ident
)) {
1247 log_warn(LD_BUG
, "Stream had both rend_data and hs_ident..."
1248 "Prioritizing hs_ident");
1251 if (conn
->hs_ident
) { /* It's v3: pass it to the prop224 handler */
1252 note_connection_attempt_succeeded(conn
->hs_ident
);
1254 } else if (conn
->rend_data
) { /* It's v2: pass it to the legacy handler */
1255 rend_client_note_connection_attempt_ended(conn
->rend_data
);
1260 /* With the given encoded descriptor in desc_str and the service key in
1261 * service_identity_pk, decode the descriptor and set the desc pointer with a
1262 * newly allocated descriptor object.
1264 * Return 0 on success else a negative value and desc is set to NULL. */
1266 hs_client_decode_descriptor(const char *desc_str
,
1267 const ed25519_public_key_t
*service_identity_pk
,
1268 hs_descriptor_t
**desc
)
1271 uint8_t subcredential
[DIGEST256_LEN
];
1272 ed25519_public_key_t blinded_pubkey
;
1273 hs_client_service_authorization_t
*client_auth
= NULL
;
1274 curve25519_secret_key_t
*client_auht_sk
= NULL
;
1276 tor_assert(desc_str
);
1277 tor_assert(service_identity_pk
);
1280 /* Check if we have a client authorization for this service in the map. */
1281 client_auth
= find_client_auth(service_identity_pk
);
1283 client_auht_sk
= &client_auth
->enc_seckey
;
1286 /* Create subcredential for this HS so that we can decrypt */
1288 uint64_t current_time_period
= hs_get_time_period_num(0);
1289 hs_build_blinded_pubkey(service_identity_pk
, NULL
, 0, current_time_period
,
1291 hs_get_subcredential(service_identity_pk
, &blinded_pubkey
, subcredential
);
1294 /* Parse descriptor */
1295 ret
= hs_desc_decode_descriptor(desc_str
, subcredential
,
1296 client_auht_sk
, desc
);
1297 memwipe(subcredential
, 0, sizeof(subcredential
));
1302 /* Make sure the descriptor signing key cross certifies with the computed
1303 * blinded key. Without this validation, anyone knowing the subcredential
1304 * and onion address can forge a descriptor. */
1305 tor_cert_t
*cert
= (*desc
)->plaintext_data
.signing_key_cert
;
1306 if (tor_cert_checksig(cert
,
1307 &blinded_pubkey
, approx_time()) < 0) {
1308 log_warn(LD_GENERAL
, "Descriptor signing key certificate signature "
1309 "doesn't validate with computed blinded key: %s",
1310 tor_cert_describe_signature_status(cert
));
1319 /* Return true iff there are at least one usable intro point in the service
1320 * descriptor desc. */
1322 hs_client_any_intro_points_usable(const ed25519_public_key_t
*service_pk
,
1323 const hs_descriptor_t
*desc
)
1325 tor_assert(service_pk
);
1328 SMARTLIST_FOREACH_BEGIN(desc
->encrypted_data
.intro_points
,
1329 const hs_desc_intro_point_t
*, ip
) {
1330 if (intro_point_is_usable(service_pk
, ip
)) {
1333 } SMARTLIST_FOREACH_END(ip
);
1340 /** Launch a connection to a hidden service directory to fetch a hidden
1341 * service descriptor using <b>identity_pk</b> to get the necessary keys.
1343 * A hs_client_fetch_status_t code is returned. */
1345 hs_client_refetch_hsdesc(const ed25519_public_key_t
*identity_pk
)
1347 hs_client_fetch_status_t status
;
1349 tor_assert(identity_pk
);
1351 if (!can_client_refetch_desc(identity_pk
, &status
)) {
1355 /* Try to fetch the desc and if we encounter an unrecoverable error, mark
1356 * the desc as unavailable for now. */
1357 status
= fetch_v3_desc(identity_pk
);
1358 if (fetch_status_should_close_socks(status
)) {
1359 close_all_socks_conns_waiting_for_desc(identity_pk
, status
,
1360 END_STREAM_REASON_RESOLVEFAILED
);
1361 /* Remove HSDir fetch attempts so that we can retry later if the user
1362 * wants us to regardless of if we closed any connections. */
1363 purge_hid_serv_request(identity_pk
);
1368 /* This is called when we are trying to attach an AP connection to these
1369 * hidden service circuits from connection_ap_handshake_attach_circuit().
1370 * Return 0 on success, -1 for a transient error that is actions were
1371 * triggered to recover or -2 for a permenent error where both circuits will
1374 * The following supports every hidden service version. */
1376 hs_client_send_introduce1(origin_circuit_t
*intro_circ
,
1377 origin_circuit_t
*rend_circ
)
1379 return (intro_circ
->hs_ident
) ? send_introduce1(intro_circ
, rend_circ
) :
1380 rend_client_send_introduction(intro_circ
,
1384 /* Called when the client circuit circ has been established. It can be either
1385 * an introduction or rendezvous circuit. This function handles all hidden
1386 * service versions. */
1388 hs_client_circuit_has_opened(origin_circuit_t
*circ
)
1392 /* Handle both version. v2 uses rend_data and v3 uses the hs circuit
1393 * identifier hs_ident. Can't be both. */
1394 switch (TO_CIRCUIT(circ
)->purpose
) {
1395 case CIRCUIT_PURPOSE_C_INTRODUCING
:
1396 if (circ
->hs_ident
) {
1397 client_intro_circ_has_opened(circ
);
1399 rend_client_introcirc_has_opened(circ
);
1402 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
1403 if (circ
->hs_ident
) {
1404 client_rendezvous_circ_has_opened(circ
);
1406 rend_client_rendcirc_has_opened(circ
);
1410 tor_assert_nonfatal_unreached();
1414 /* Called when we receive a RENDEZVOUS_ESTABLISHED cell. Change the state of
1415 * the circuit to CIRCUIT_PURPOSE_C_REND_READY. Return 0 on success else a
1416 * negative value and the circuit marked for close. */
1418 hs_client_receive_rendezvous_acked(origin_circuit_t
*circ
,
1419 const uint8_t *payload
, size_t payload_len
)
1422 tor_assert(payload
);
1426 if (TO_CIRCUIT(circ
)->purpose
!= CIRCUIT_PURPOSE_C_ESTABLISH_REND
) {
1427 log_warn(LD_PROTOCOL
, "Got a RENDEZVOUS_ESTABLISHED but we were not "
1428 "expecting one. Closing circuit.");
1432 log_info(LD_REND
, "Received an RENDEZVOUS_ESTABLISHED. This circuit is "
1433 "now ready for rendezvous.");
1434 circuit_change_purpose(TO_CIRCUIT(circ
), CIRCUIT_PURPOSE_C_REND_READY
);
1436 /* Set timestamp_dirty, because circuit_expire_building expects it to
1437 * specify when a circuit entered the _C_REND_READY state. */
1438 TO_CIRCUIT(circ
)->timestamp_dirty
= time(NULL
);
1440 /* From a path bias point of view, this circuit is now successfully used.
1441 * Waiting any longer opens us up to attacks from malicious hidden services.
1442 * They could induce the client to attempt to connect to their hidden
1443 * service and never reply to the client's rend requests */
1444 pathbias_mark_use_success(circ
);
1446 /* If we already have the introduction circuit built, make sure we send
1447 * the INTRODUCE cell _now_ */
1448 connection_ap_attach_pending(1);
1452 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_TORPROTOCOL
);
1456 #define client_service_authorization_free(auth) \
1457 FREE_AND_NULL(hs_client_service_authorization_t, \
1458 client_service_authorization_free_, (auth))
1461 client_service_authorization_free_(hs_client_service_authorization_t
*auth
)
1464 memwipe(auth
, 0, sizeof(*auth
));
1469 /** Helper for digest256map_free. */
1471 client_service_authorization_free_void(void *auth
)
1473 client_service_authorization_free_(auth
);
1477 client_service_authorization_free_all(void)
1479 if (!client_auths
) {
1482 digest256map_free(client_auths
, client_service_authorization_free_void
);
1485 /* Check if the auth key file name is valid or not. Return 1 if valid,
1486 * otherwise return 0. */
1488 auth_key_filename_is_valid(const char *filename
)
1491 const char *valid_extension
= ".auth_private";
1493 tor_assert(filename
);
1495 /* The length of the filename must be greater than the length of the
1496 * extension and the valid extension must be at the end of filename. */
1497 if (!strcmpend(filename
, valid_extension
) &&
1498 strlen(filename
) != strlen(valid_extension
)) {
1507 STATIC hs_client_service_authorization_t
*
1508 parse_auth_file_content(const char *client_key_str
)
1510 char *onion_address
= NULL
;
1511 char *auth_type
= NULL
;
1512 char *key_type
= NULL
;
1513 char *seckey_b32
= NULL
;
1514 hs_client_service_authorization_t
*auth
= NULL
;
1515 smartlist_t
*fields
= smartlist_new();
1517 tor_assert(client_key_str
);
1519 smartlist_split_string(fields
, client_key_str
, ":",
1520 SPLIT_SKIP_SPACE
, 0);
1521 /* Wrong number of fields. */
1522 if (smartlist_len(fields
) != 4) {
1526 onion_address
= smartlist_get(fields
, 0);
1527 auth_type
= smartlist_get(fields
, 1);
1528 key_type
= smartlist_get(fields
, 2);
1529 seckey_b32
= smartlist_get(fields
, 3);
1531 /* Currently, the only supported auth type is "descriptor" and the only
1532 * supported key type is "x25519". */
1533 if (strcmp(auth_type
, "descriptor") || strcmp(key_type
, "x25519")) {
1537 if (strlen(seckey_b32
) != BASE32_NOPAD_LEN(CURVE25519_PUBKEY_LEN
)) {
1538 log_warn(LD_REND
, "Client authorization encoded base32 private key "
1539 "length is invalid: %s", seckey_b32
);
1543 auth
= tor_malloc_zero(sizeof(hs_client_service_authorization_t
));
1544 if (base32_decode((char *) auth
->enc_seckey
.secret_key
,
1545 sizeof(auth
->enc_seckey
.secret_key
),
1546 seckey_b32
, strlen(seckey_b32
)) < 0) {
1549 strncpy(auth
->onion_address
, onion_address
, HS_SERVICE_ADDR_LEN_BASE32
);
1555 client_service_authorization_free(auth
);
1557 /* It is also a good idea to wipe the private key. */
1559 memwipe(seckey_b32
, 0, strlen(seckey_b32
));
1562 SMARTLIST_FOREACH(fields
, char *, s
, tor_free(s
));
1563 smartlist_free(fields
);
1567 /* From a set of <b>options</b>, setup every client authorization detail
1568 * found. Return 0 on success or -1 on failure. If <b>validate_only</b>
1569 * is set, parse, warn and return as normal, but don't actually change
1570 * the configuration. */
1572 hs_config_client_authorization(const or_options_t
*options
,
1576 digest256map_t
*auths
= digest256map_new();
1577 char *key_dir
= NULL
;
1578 smartlist_t
*file_list
= NULL
;
1579 char *client_key_str
= NULL
;
1580 char *client_key_file_path
= NULL
;
1582 tor_assert(options
);
1584 /* There is no client auth configured. We can just silently ignore this
1586 if (!options
->ClientOnionAuthDir
) {
1591 key_dir
= tor_strdup(options
->ClientOnionAuthDir
);
1593 /* Make sure the directory exists and is private enough. */
1594 if (check_private_dir(key_dir
, 0, options
->User
) < 0) {
1598 file_list
= tor_listdir(key_dir
);
1599 if (file_list
== NULL
) {
1600 log_warn(LD_REND
, "Client authorization key directory %s can't be listed.",
1605 SMARTLIST_FOREACH_BEGIN(file_list
, char *, filename
) {
1607 hs_client_service_authorization_t
*auth
= NULL
;
1608 ed25519_public_key_t identity_pk
;
1609 log_info(LD_REND
, "Loading a client authorization key file %s...",
1612 if (!auth_key_filename_is_valid(filename
)) {
1613 log_notice(LD_REND
, "Client authorization unrecognized filename %s. "
1614 "File must end in .auth_private. Ignoring.",
1619 /* Create a full path for a file. */
1620 client_key_file_path
= hs_path_from_filename(key_dir
, filename
);
1621 client_key_str
= read_file_to_str(client_key_file_path
, 0, NULL
);
1622 /* Free the file path immediately after using it. */
1623 tor_free(client_key_file_path
);
1625 /* If we cannot read the file, continue with the next file. */
1626 if (!client_key_str
) {
1627 log_warn(LD_REND
, "The file %s cannot be read.", filename
);
1631 auth
= parse_auth_file_content(client_key_str
);
1632 /* Free immediately after using it. */
1633 tor_free(client_key_str
);
1636 /* Parse the onion address to get an identity public key and use it
1637 * as a key of global map in the future. */
1638 if (hs_parse_address(auth
->onion_address
, &identity_pk
,
1640 client_service_authorization_free(auth
);
1641 log_warn(LD_REND
, "The onion address \"%s\" is invalid in "
1642 "file %s", filename
, auth
->onion_address
);
1646 if (digest256map_get(auths
, identity_pk
.pubkey
)) {
1647 client_service_authorization_free(auth
);
1648 log_warn(LD_REND
, "Duplicate authorization for the same hidden "
1649 "service address %s.",
1650 safe_str_client(auth
->onion_address
));
1654 digest256map_set(auths
, identity_pk
.pubkey
, auth
);
1655 log_info(LD_REND
, "Loaded a client authorization key file %s.",
1658 } SMARTLIST_FOREACH_END(filename
);
1665 tor_free(client_key_str
);
1666 tor_free(client_key_file_path
);
1668 SMARTLIST_FOREACH(file_list
, char *, s
, tor_free(s
));
1669 smartlist_free(file_list
);
1672 if (!validate_only
&& ret
== 0) {
1673 client_service_authorization_free_all();
1674 client_auths
= auths
;
1676 digest256map_free(auths
, client_service_authorization_free_void
);
1682 /* This is called when a descriptor has arrived following a fetch request and
1683 * has been stored in the client cache. Every entry connection that matches
1684 * the service identity key in the ident will get attached to the hidden
1685 * service circuit. */
1687 hs_client_desc_has_arrived(const hs_ident_dir_conn_t
*ident
)
1689 time_t now
= time(NULL
);
1690 smartlist_t
*conns
= NULL
;
1694 conns
= connection_list_by_type_state(CONN_TYPE_AP
,
1695 AP_CONN_STATE_RENDDESC_WAIT
);
1696 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, base_conn
) {
1697 const hs_descriptor_t
*desc
;
1698 entry_connection_t
*entry_conn
= TO_ENTRY_CONN(base_conn
);
1699 const edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(entry_conn
);
1701 /* Only consider the entry connections that matches the service for which
1702 * we just fetched its descriptor. */
1703 if (!edge_conn
->hs_ident
||
1704 !ed25519_pubkey_eq(&ident
->identity_pk
,
1705 &edge_conn
->hs_ident
->identity_pk
)) {
1708 assert_connection_ok(base_conn
, now
);
1710 /* We were just called because we stored the descriptor for this service
1711 * so not finding a descriptor means we have a bigger problem. */
1712 desc
= hs_cache_lookup_as_client(&ident
->identity_pk
);
1713 if (BUG(desc
== NULL
)) {
1717 if (!hs_client_any_intro_points_usable(&ident
->identity_pk
, desc
)) {
1718 log_info(LD_REND
, "Hidden service descriptor is unusable. "
1719 "Closing streams.");
1720 connection_mark_unattached_ap(entry_conn
,
1721 END_STREAM_REASON_RESOLVEFAILED
);
1722 /* We are unable to use the descriptor so remove the directory request
1723 * from the cache so the next connection can try again. */
1724 note_connection_attempt_succeeded(edge_conn
->hs_ident
);
1728 log_info(LD_REND
, "Descriptor has arrived. Launching circuits.");
1730 /* Mark connection as waiting for a circuit since we do have a usable
1731 * descriptor now. */
1732 mark_conn_as_waiting_for_circuit(base_conn
, now
);
1733 } SMARTLIST_FOREACH_END(base_conn
);
1736 /* We don't have ownership of the objects in this list. */
1737 smartlist_free(conns
);
1740 /* Return a newly allocated extend_info_t for a randomly chosen introduction
1741 * point for the given edge connection identifier ident. Return NULL if we
1742 * can't pick any usable introduction points. */
1744 hs_client_get_random_intro_from_edge(const edge_connection_t
*edge_conn
)
1746 tor_assert(edge_conn
);
1748 return (edge_conn
->hs_ident
) ?
1749 client_get_random_intro(&edge_conn
->hs_ident
->identity_pk
) :
1750 rend_client_get_random_intro(edge_conn
->rend_data
);
1753 /* Called when get an INTRODUCE_ACK cell on the introduction circuit circ.
1754 * Return 0 on success else a negative value is returned. The circuit will be
1755 * closed or reuse to extend again to another intro point. */
1757 hs_client_receive_introduce_ack(origin_circuit_t
*circ
,
1758 const uint8_t *payload
, size_t payload_len
)
1763 tor_assert(payload
);
1765 if (TO_CIRCUIT(circ
)->purpose
!= CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
) {
1766 log_warn(LD_PROTOCOL
, "Unexpected INTRODUCE_ACK on circuit %u.",
1767 (unsigned int) TO_CIRCUIT(circ
)->n_circ_id
);
1768 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_TORPROTOCOL
);
1772 ret
= (circ
->hs_ident
) ? handle_introduce_ack(circ
, payload
, payload_len
) :
1773 rend_client_introduction_acked(circ
, payload
,
1775 /* For path bias: This circuit was used successfully. NACK or ACK counts. */
1776 pathbias_mark_use_success(circ
);
1782 /* Called when get a RENDEZVOUS2 cell on the rendezvous circuit circ. Return
1783 * 0 on success else a negative value is returned. The circuit will be closed
1786 hs_client_receive_rendezvous2(origin_circuit_t
*circ
,
1787 const uint8_t *payload
, size_t payload_len
)
1792 tor_assert(payload
);
1794 /* Circuit can possibly be in both state because we could receive a
1795 * RENDEZVOUS2 cell before the INTRODUCE_ACK has been received. */
1796 if (TO_CIRCUIT(circ
)->purpose
!= CIRCUIT_PURPOSE_C_REND_READY
&&
1797 TO_CIRCUIT(circ
)->purpose
!= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
) {
1798 log_warn(LD_PROTOCOL
, "Unexpected RENDEZVOUS2 cell on circuit %u. "
1800 (unsigned int) TO_CIRCUIT(circ
)->n_circ_id
);
1801 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_TORPROTOCOL
);
1805 log_info(LD_REND
, "Got RENDEZVOUS2 cell from hidden service on circuit %u.",
1806 TO_CIRCUIT(circ
)->n_circ_id
);
1808 ret
= (circ
->hs_ident
) ? handle_rendezvous2(circ
, payload
, payload_len
) :
1809 rend_client_receive_rendezvous(circ
, payload
,
1815 /* Extend the introduction circuit circ to another valid introduction point
1816 * for the hidden service it is trying to connect to, or mark it and launch a
1817 * new circuit if we can't extend it. Return 0 on success or possible
1818 * success. Return -1 and mark the introduction circuit for close on permanent
1821 * On failure, the caller is responsible for marking the associated rendezvous
1822 * circuit for close. */
1824 hs_client_reextend_intro_circuit(origin_circuit_t
*circ
)
1831 ei
= (circ
->hs_ident
) ?
1832 client_get_random_intro(&circ
->hs_ident
->identity_pk
) :
1833 rend_client_get_random_intro(circ
->rend_data
);
1835 log_warn(LD_REND
, "No usable introduction points left. Closing.");
1836 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_INTERNAL
);
1840 if (circ
->remaining_relay_early_cells
) {
1841 log_info(LD_REND
, "Re-extending circ %u, this time to %s.",
1842 (unsigned int) TO_CIRCUIT(circ
)->n_circ_id
,
1843 safe_str_client(extend_info_describe(ei
)));
1844 ret
= circuit_extend_to_new_exit(circ
, ei
);
1846 /* We were able to extend so update the timestamp so we avoid expiring
1847 * this circuit too early. The intro circuit is short live so the
1848 * linkability issue is minimized, we just need the circuit to hold a
1849 * bit longer so we can introduce. */
1850 TO_CIRCUIT(circ
)->timestamp_dirty
= time(NULL
);
1853 log_info(LD_REND
, "Closing intro circ %u (out of RELAY_EARLY cells).",
1854 (unsigned int) TO_CIRCUIT(circ
)->n_circ_id
);
1855 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_FINISHED
);
1856 /* connection_ap_handshake_attach_circuit will launch a new intro circ. */
1861 extend_info_free(ei
);
1865 /* Close all client introduction circuits related to the given descriptor.
1866 * This is called with a descriptor that is about to get replaced in the
1869 * Even though the introduction point might be exactly the same, we'll rebuild
1870 * them if needed but the odds are very low that an existing matching
1871 * introduction circuit exists at that stage. */
1873 hs_client_close_intro_circuits_from_desc(const hs_descriptor_t
*desc
)
1875 origin_circuit_t
*ocirc
= NULL
;
1879 /* We iterate over all client intro circuits because they aren't kept in the
1880 * HS circuitmap. That is probably something we want to do one day. */
1881 while ((ocirc
= circuit_get_next_intro_circ(ocirc
, true))) {
1882 if (ocirc
->hs_ident
== NULL
) {
1883 /* Not a v3 circuit, ignore it. */
1887 /* Does it match any IP in the given descriptor? If not, ignore. */
1888 if (find_desc_intro_point_by_ident(ocirc
->hs_ident
, desc
) == NULL
) {
1892 /* We have a match. Close the circuit as consider it expired. */
1893 circuit_mark_for_close(TO_CIRCUIT(ocirc
), END_CIRC_REASON_FINISHED
);
1897 /* Release all the storage held by the client subsystem. */
1899 hs_client_free_all(void)
1901 /* Purge the hidden service request cache. */
1902 hs_purge_last_hid_serv_requests();
1903 client_service_authorization_free_all();
1906 /* Purge all potentially remotely-detectable state held in the hidden
1907 * service client code. Called on SIGNAL NEWNYM. */
1909 hs_client_purge_state(void)
1912 rend_client_purge_state();
1914 /* Cancel all descriptor fetches. Do this first so once done we are sure
1915 * that our descriptor cache won't modified. */
1916 cancel_descriptor_fetches();
1917 /* Purge the introduction point state cache. */
1918 hs_cache_client_intro_state_purge();
1919 /* Purge the descriptor cache. */
1920 hs_cache_purge_as_client();
1921 /* Purge the last hidden service request cache. */
1922 hs_purge_last_hid_serv_requests();
1924 log_info(LD_REND
, "Hidden service client state has been purged.");
1927 /* Called when our directory information has changed. */
1929 hs_client_dir_info_changed(void)
1931 /* We have possibly reached the minimum directory information or new
1932 * consensus so retry all pending SOCKS connection in
1933 * AP_CONN_STATE_RENDDESC_WAIT state in order to fetch the descriptor. */
1934 retry_all_socks_conn_waiting_for_desc();
1937 #ifdef TOR_UNIT_TESTS
1939 STATIC digest256map_t
*
1940 get_hs_client_auths_map(void)
1942 return client_auths
;
1945 #endif /* defined(TOR_UNIT_TESTS) */