Avoid crashing if we call num_usable_bridges() when bridges are not enabled
[tor/appveyor.git] / src / or / hs_client.c
blob9ac653c721411f2f6dd8034340835e45bee02e5b
1 /* Copyright (c) 2016-2017, 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 "or.h"
12 #include "hs_circuit.h"
13 #include "hs_ident.h"
14 #include "connection_edge.h"
15 #include "container.h"
16 #include "rendclient.h"
17 #include "hs_descriptor.h"
18 #include "hs_cache.h"
19 #include "hs_cell.h"
20 #include "hs_ident.h"
21 #include "config.h"
22 #include "directory.h"
23 #include "hs_client.h"
24 #include "router.h"
25 #include "routerset.h"
26 #include "circuitlist.h"
27 #include "circuituse.h"
28 #include "connection.h"
29 #include "nodelist.h"
30 #include "circpathbias.h"
31 #include "connection.h"
32 #include "hs_ntor.h"
33 #include "circuitbuild.h"
34 #include "networkstatus.h"
35 #include "reasons.h"
37 /* Return a human-readable string for the client fetch status code. */
38 static const char *
39 fetch_status_to_string(hs_client_fetch_status_t status)
41 switch (status) {
42 case HS_CLIENT_FETCH_ERROR:
43 return "Internal error";
44 case HS_CLIENT_FETCH_LAUNCHED:
45 return "Descriptor fetch launched";
46 case HS_CLIENT_FETCH_HAVE_DESC:
47 return "Already have descriptor";
48 case HS_CLIENT_FETCH_NO_HSDIRS:
49 return "No more HSDir available to query";
50 case HS_CLIENT_FETCH_NOT_ALLOWED:
51 return "Fetching descriptors is not allowed";
52 case HS_CLIENT_FETCH_MISSING_INFO:
53 return "Missing directory information";
54 case HS_CLIENT_FETCH_PENDING:
55 return "Pending descriptor fetch";
56 default:
57 return "(Unknown client fetch status code)";
61 /* Return true iff tor should close the SOCKS request(s) for the descriptor
62 * fetch that ended up with this given status code. */
63 static int
64 fetch_status_should_close_socks(hs_client_fetch_status_t status)
66 switch (status) {
67 case HS_CLIENT_FETCH_NO_HSDIRS:
68 /* No more HSDir to query, we can't complete the SOCKS request(s). */
69 case HS_CLIENT_FETCH_ERROR:
70 /* The fetch triggered an internal error. */
71 case HS_CLIENT_FETCH_NOT_ALLOWED:
72 /* Client is not allowed to fetch (FetchHidServDescriptors 0). */
73 goto close;
74 case HS_CLIENT_FETCH_MISSING_INFO:
75 case HS_CLIENT_FETCH_HAVE_DESC:
76 case HS_CLIENT_FETCH_PENDING:
77 case HS_CLIENT_FETCH_LAUNCHED:
78 /* The rest doesn't require tor to close the SOCKS request(s). */
79 goto no_close;
82 no_close:
83 return 0;
84 close:
85 return 1;
88 /* Cancel all descriptor fetches currently in progress. */
89 static void
90 cancel_descriptor_fetches(void)
92 smartlist_t *conns =
93 connection_list_by_type_state(CONN_TYPE_DIR, DIR_PURPOSE_FETCH_HSDESC);
94 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
95 const hs_ident_dir_conn_t *ident = TO_DIR_CONN(conn)->hs_ident;
96 if (BUG(ident == NULL)) {
97 /* A directory connection fetching a service descriptor can't have an
98 * empty hidden service identifier. */
99 continue;
101 log_debug(LD_REND, "Marking for close a directory connection fetching "
102 "a hidden service descriptor for service %s.",
103 safe_str_client(ed25519_fmt(&ident->identity_pk)));
104 connection_mark_for_close(conn);
105 } SMARTLIST_FOREACH_END(conn);
107 /* No ownership of the objects in this list. */
108 smartlist_free(conns);
109 log_info(LD_REND, "Hidden service client descriptor fetches cancelled.");
112 /* Get all connections that are waiting on a circuit and flag them back to
113 * waiting for a hidden service descriptor for the given service key
114 * service_identity_pk. */
115 static void
116 flag_all_conn_wait_desc(const ed25519_public_key_t *service_identity_pk)
118 tor_assert(service_identity_pk);
120 smartlist_t *conns =
121 connection_list_by_type_state(CONN_TYPE_AP, AP_CONN_STATE_CIRCUIT_WAIT);
123 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
124 edge_connection_t *edge_conn;
125 if (BUG(!CONN_IS_EDGE(conn))) {
126 continue;
128 edge_conn = TO_EDGE_CONN(conn);
129 if (edge_conn->hs_ident &&
130 ed25519_pubkey_eq(&edge_conn->hs_ident->identity_pk,
131 service_identity_pk)) {
132 connection_ap_mark_as_non_pending_circuit(TO_ENTRY_CONN(conn));
133 conn->state = AP_CONN_STATE_RENDDESC_WAIT;
135 } SMARTLIST_FOREACH_END(conn);
137 smartlist_free(conns);
140 /* Remove tracked HSDir requests from our history for this hidden service
141 * identity public key. */
142 static void
143 purge_hid_serv_request(const ed25519_public_key_t *identity_pk)
145 char base64_blinded_pk[ED25519_BASE64_LEN + 1];
146 ed25519_public_key_t blinded_pk;
148 tor_assert(identity_pk);
150 /* Get blinded pubkey of hidden service. It is possible that we just moved
151 * to a new time period meaning that we won't be able to purge the request
152 * from the previous time period. That is fine because they will expire at
153 * some point and we don't care about those anymore. */
154 hs_build_blinded_pubkey(identity_pk, NULL, 0,
155 hs_get_time_period_num(0), &blinded_pk);
156 if (BUG(ed25519_public_to_base64(base64_blinded_pk, &blinded_pk) < 0)) {
157 return;
159 /* Purge last hidden service request from cache for this blinded key. */
160 hs_purge_hid_serv_from_last_hid_serv_requests(base64_blinded_pk);
163 /* Return true iff there is at least one pending directory descriptor request
164 * for the service identity_pk. */
165 static int
166 directory_request_is_pending(const ed25519_public_key_t *identity_pk)
168 int ret = 0;
169 smartlist_t *conns =
170 connection_list_by_type_purpose(CONN_TYPE_DIR, DIR_PURPOSE_FETCH_HSDESC);
172 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
173 const hs_ident_dir_conn_t *ident = TO_DIR_CONN(conn)->hs_ident;
174 if (BUG(ident == NULL)) {
175 /* A directory connection fetching a service descriptor can't have an
176 * empty hidden service identifier. */
177 continue;
179 if (!ed25519_pubkey_eq(identity_pk, &ident->identity_pk)) {
180 continue;
182 ret = 1;
183 break;
184 } SMARTLIST_FOREACH_END(conn);
186 /* No ownership of the objects in this list. */
187 smartlist_free(conns);
188 return ret;
191 /* We failed to fetch a descriptor for the service with <b>identity_pk</b>
192 * because of <b>status</b>. Find all pending SOCKS connections for this
193 * service that are waiting on the descriptor and close them with
194 * <b>reason</b>. */
195 static void
196 close_all_socks_conns_waiting_for_desc(const ed25519_public_key_t *identity_pk,
197 hs_client_fetch_status_t status,
198 int reason)
200 unsigned int count = 0;
201 time_t now = approx_time();
202 smartlist_t *conns =
203 connection_list_by_type_state(CONN_TYPE_AP, AP_CONN_STATE_RENDDESC_WAIT);
205 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
206 entry_connection_t *entry_conn = TO_ENTRY_CONN(base_conn);
207 const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(entry_conn);
209 /* Only consider the entry connections that matches the service for which
210 * we tried to get the descriptor */
211 if (!edge_conn->hs_ident ||
212 !ed25519_pubkey_eq(identity_pk,
213 &edge_conn->hs_ident->identity_pk)) {
214 continue;
216 assert_connection_ok(base_conn, now);
217 /* Unattach the entry connection which will close for the reason. */
218 connection_mark_unattached_ap(entry_conn, reason);
219 count++;
220 } SMARTLIST_FOREACH_END(base_conn);
222 if (count > 0) {
223 char onion_address[HS_SERVICE_ADDR_LEN_BASE32 + 1];
224 hs_build_address(identity_pk, HS_VERSION_THREE, onion_address);
225 log_notice(LD_REND, "Closed %u streams for service %s.onion "
226 "for reason %s. Fetch status: %s.",
227 count, safe_str_client(onion_address),
228 stream_end_reason_to_string(reason),
229 fetch_status_to_string(status));
232 /* No ownership of the object(s) in this list. */
233 smartlist_free(conns);
236 /* Find all pending SOCKS connection waiting for a descriptor and retry them
237 * all. This is called when the directory information changed. */
238 static void
239 retry_all_socks_conn_waiting_for_desc(void)
241 smartlist_t *conns =
242 connection_list_by_type_state(CONN_TYPE_AP, AP_CONN_STATE_RENDDESC_WAIT);
244 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
245 hs_client_fetch_status_t status;
246 const edge_connection_t *edge_conn =
247 ENTRY_TO_EDGE_CONN(TO_ENTRY_CONN(base_conn));
249 /* Ignore non HS or non v3 connection. */
250 if (edge_conn->hs_ident == NULL) {
251 continue;
253 /* In this loop, we will possibly try to fetch a descriptor for the
254 * pending connections because we just got more directory information.
255 * However, the refetch process can cleanup all SOCKS request so the same
256 * service if an internal error happens. Thus, we can end up with closed
257 * connections in our list. */
258 if (base_conn->marked_for_close) {
259 continue;
262 /* XXX: There is an optimization we could do which is that for a service
263 * key, we could check if we can fetch and remember that decision. */
265 /* Order a refetch in case it works this time. */
266 status = hs_client_refetch_hsdesc(&edge_conn->hs_ident->identity_pk);
267 if (BUG(status == HS_CLIENT_FETCH_HAVE_DESC)) {
268 /* This case is unique because it can NOT happen in theory. Once we get
269 * a new descriptor, the HS client subsystem is notified immediately and
270 * the connections waiting for it are handled which means the state will
271 * change from renddesc wait state. Log this and continue to next
272 * connection. */
273 continue;
275 /* In the case of an error, either all SOCKS connections have been
276 * closed or we are still missing directory information. Leave the
277 * connection in renddesc wait state so when we get more info, we'll be
278 * able to try it again. */
279 } SMARTLIST_FOREACH_END(base_conn);
281 /* We don't have ownership of those objects. */
282 smartlist_free(conns);
285 /* A v3 HS circuit successfully connected to the hidden service. Update the
286 * stream state at <b>hs_conn_ident</b> appropriately. */
287 static void
288 note_connection_attempt_succeeded(const hs_ident_edge_conn_t *hs_conn_ident)
290 tor_assert(hs_conn_ident);
292 /* Remove from the hid serv cache all requests for that service so we can
293 * query the HSDir again later on for various reasons. */
294 purge_hid_serv_request(&hs_conn_ident->identity_pk);
296 /* The v2 subsystem cleans up the intro point time out flag at this stage.
297 * We don't try to do it here because we still need to keep intact the intro
298 * point state for future connections. Even though we are able to connect to
299 * the service, doesn't mean we should reset the timed out intro points.
301 * It is not possible to have successfully connected to an intro point
302 * present in our cache that was on error or timed out. Every entry in that
303 * cache have a 2 minutes lifetime so ultimately the intro point(s) state
304 * will be reset and thus possible to be retried. */
307 /* Given the pubkey of a hidden service in <b>onion_identity_pk</b>, fetch its
308 * descriptor by launching a dir connection to <b>hsdir</b>. Return a
309 * hs_client_fetch_status_t status code depending on how it went. */
310 static hs_client_fetch_status_t
311 directory_launch_v3_desc_fetch(const ed25519_public_key_t *onion_identity_pk,
312 const routerstatus_t *hsdir)
314 uint64_t current_time_period = hs_get_time_period_num(0);
315 ed25519_public_key_t blinded_pubkey;
316 char base64_blinded_pubkey[ED25519_BASE64_LEN + 1];
317 hs_ident_dir_conn_t hs_conn_dir_ident;
318 int retval;
320 tor_assert(hsdir);
321 tor_assert(onion_identity_pk);
323 /* Get blinded pubkey */
324 hs_build_blinded_pubkey(onion_identity_pk, NULL, 0,
325 current_time_period, &blinded_pubkey);
326 /* ...and base64 it. */
327 retval = ed25519_public_to_base64(base64_blinded_pubkey, &blinded_pubkey);
328 if (BUG(retval < 0)) {
329 return HS_CLIENT_FETCH_ERROR;
332 /* Copy onion pk to a dir_ident so that we attach it to the dir conn */
333 hs_ident_dir_conn_init(onion_identity_pk, &blinded_pubkey,
334 &hs_conn_dir_ident);
336 /* Setup directory request */
337 directory_request_t *req =
338 directory_request_new(DIR_PURPOSE_FETCH_HSDESC);
339 directory_request_set_routerstatus(req, hsdir);
340 directory_request_set_indirection(req, DIRIND_ANONYMOUS);
341 directory_request_set_resource(req, base64_blinded_pubkey);
342 directory_request_fetch_set_hs_ident(req, &hs_conn_dir_ident);
343 directory_initiate_request(req);
344 directory_request_free(req);
346 log_info(LD_REND, "Descriptor fetch request for service %s with blinded "
347 "key %s to directory %s",
348 safe_str_client(ed25519_fmt(onion_identity_pk)),
349 safe_str_client(base64_blinded_pubkey),
350 safe_str_client(routerstatus_describe(hsdir)));
352 /* Cleanup memory. */
353 memwipe(&blinded_pubkey, 0, sizeof(blinded_pubkey));
354 memwipe(base64_blinded_pubkey, 0, sizeof(base64_blinded_pubkey));
355 memwipe(&hs_conn_dir_ident, 0, sizeof(hs_conn_dir_ident));
357 return HS_CLIENT_FETCH_LAUNCHED;
360 /** Return the HSDir we should use to fetch the descriptor of the hidden
361 * service with identity key <b>onion_identity_pk</b>. */
362 STATIC routerstatus_t *
363 pick_hsdir_v3(const ed25519_public_key_t *onion_identity_pk)
365 int retval;
366 char base64_blinded_pubkey[ED25519_BASE64_LEN + 1];
367 uint64_t current_time_period = hs_get_time_period_num(0);
368 smartlist_t *responsible_hsdirs;
369 ed25519_public_key_t blinded_pubkey;
370 routerstatus_t *hsdir_rs = NULL;
372 tor_assert(onion_identity_pk);
374 responsible_hsdirs = smartlist_new();
376 /* Get blinded pubkey of hidden service */
377 hs_build_blinded_pubkey(onion_identity_pk, NULL, 0,
378 current_time_period, &blinded_pubkey);
379 /* ...and base64 it. */
380 retval = ed25519_public_to_base64(base64_blinded_pubkey, &blinded_pubkey);
381 if (BUG(retval < 0)) {
382 return NULL;
385 /* Get responsible hsdirs of service for this time period */
386 hs_get_responsible_hsdirs(&blinded_pubkey, current_time_period,
387 0, 1, responsible_hsdirs);
389 log_debug(LD_REND, "Found %d responsible HSDirs and about to pick one.",
390 smartlist_len(responsible_hsdirs));
392 /* Pick an HSDir from the responsible ones. The ownership of
393 * responsible_hsdirs is given to this function so no need to free it. */
394 hsdir_rs = hs_pick_hsdir(responsible_hsdirs, base64_blinded_pubkey);
396 return hsdir_rs;
399 /** Fetch a v3 descriptor using the given <b>onion_identity_pk</b>.
401 * On success, HS_CLIENT_FETCH_LAUNCHED is returned. Otherwise, an error from
402 * hs_client_fetch_status_t is returned. */
403 MOCK_IMPL(STATIC hs_client_fetch_status_t,
404 fetch_v3_desc, (const ed25519_public_key_t *onion_identity_pk))
406 routerstatus_t *hsdir_rs =NULL;
408 tor_assert(onion_identity_pk);
410 hsdir_rs = pick_hsdir_v3(onion_identity_pk);
411 if (!hsdir_rs) {
412 log_info(LD_REND, "Couldn't pick a v3 hsdir.");
413 return HS_CLIENT_FETCH_NO_HSDIRS;
416 return directory_launch_v3_desc_fetch(onion_identity_pk, hsdir_rs);
419 /* Make sure that the given v3 origin circuit circ is a valid correct
420 * introduction circuit. This will BUG() on any problems and hard assert if
421 * the anonymity of the circuit is not ok. Return 0 on success else -1 where
422 * the circuit should be mark for closed immediately. */
423 static int
424 intro_circ_is_ok(const origin_circuit_t *circ)
426 int ret = 0;
428 tor_assert(circ);
430 if (BUG(TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
431 TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
432 TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACKED)) {
433 ret = -1;
435 if (BUG(circ->hs_ident == NULL)) {
436 ret = -1;
438 if (BUG(!hs_ident_intro_circ_is_valid(circ->hs_ident))) {
439 ret = -1;
442 /* This can stop the tor daemon but we want that since if we don't have
443 * anonymity on this circuit, something went really wrong. */
444 assert_circ_anonymity_ok(circ, get_options());
445 return ret;
448 /* Find a descriptor intro point object that matches the given ident in the
449 * given descriptor desc. Return NULL if not found. */
450 static const hs_desc_intro_point_t *
451 find_desc_intro_point_by_ident(const hs_ident_circuit_t *ident,
452 const hs_descriptor_t *desc)
454 const hs_desc_intro_point_t *intro_point = NULL;
456 tor_assert(ident);
457 tor_assert(desc);
459 SMARTLIST_FOREACH_BEGIN(desc->encrypted_data.intro_points,
460 const hs_desc_intro_point_t *, ip) {
461 if (ed25519_pubkey_eq(&ident->intro_auth_pk,
462 &ip->auth_key_cert->signed_key)) {
463 intro_point = ip;
464 break;
466 } SMARTLIST_FOREACH_END(ip);
468 return intro_point;
471 /* Find a descriptor intro point object from the descriptor object desc that
472 * matches the given legacy identity digest in legacy_id. Return NULL if not
473 * found. */
474 static hs_desc_intro_point_t *
475 find_desc_intro_point_by_legacy_id(const char *legacy_id,
476 const hs_descriptor_t *desc)
478 hs_desc_intro_point_t *ret_ip = NULL;
480 tor_assert(legacy_id);
481 tor_assert(desc);
483 /* We will go over every intro point and try to find which one is linked to
484 * that circuit. Those lists are small so it's not that expensive. */
485 SMARTLIST_FOREACH_BEGIN(desc->encrypted_data.intro_points,
486 hs_desc_intro_point_t *, ip) {
487 SMARTLIST_FOREACH_BEGIN(ip->link_specifiers,
488 const hs_desc_link_specifier_t *, lspec) {
489 /* Not all tor node have an ed25519 identity key so we still rely on the
490 * legacy identity digest. */
491 if (lspec->type != LS_LEGACY_ID) {
492 continue;
494 if (fast_memneq(legacy_id, lspec->u.legacy_id, DIGEST_LEN)) {
495 break;
497 /* Found it. */
498 ret_ip = ip;
499 goto end;
500 } SMARTLIST_FOREACH_END(lspec);
501 } SMARTLIST_FOREACH_END(ip);
503 end:
504 return ret_ip;
507 /* Send an INTRODUCE1 cell along the intro circuit and populate the rend
508 * circuit identifier with the needed key material for the e2e encryption.
509 * Return 0 on success, -1 if there is a transient error such that an action
510 * has been taken to recover and -2 if there is a permanent error indicating
511 * that both circuits were closed. */
512 static int
513 send_introduce1(origin_circuit_t *intro_circ,
514 origin_circuit_t *rend_circ)
516 int status;
517 char onion_address[HS_SERVICE_ADDR_LEN_BASE32 + 1];
518 const ed25519_public_key_t *service_identity_pk = NULL;
519 const hs_desc_intro_point_t *ip;
521 tor_assert(rend_circ);
522 if (intro_circ_is_ok(intro_circ) < 0) {
523 goto perm_err;
526 service_identity_pk = &intro_circ->hs_ident->identity_pk;
527 /* For logging purposes. There will be a time where the hs_ident will have a
528 * version number but for now there is none because it's all v3. */
529 hs_build_address(service_identity_pk, HS_VERSION_THREE, onion_address);
531 log_info(LD_REND, "Sending INTRODUCE1 cell to service %s on circuit %u",
532 safe_str_client(onion_address), TO_CIRCUIT(intro_circ)->n_circ_id);
534 /* 1) Get descriptor from our cache. */
535 const hs_descriptor_t *desc =
536 hs_cache_lookup_as_client(service_identity_pk);
537 if (desc == NULL || !hs_client_any_intro_points_usable(service_identity_pk,
538 desc)) {
539 log_info(LD_REND, "Request to %s %s. Trying to fetch a new descriptor.",
540 safe_str_client(onion_address),
541 (desc) ? "didn't have usable intro points" :
542 "didn't have a descriptor");
543 hs_client_refetch_hsdesc(service_identity_pk);
544 /* We just triggered a refetch, make sure every connections are back
545 * waiting for that descriptor. */
546 flag_all_conn_wait_desc(service_identity_pk);
547 /* We just asked for a refetch so this is a transient error. */
548 goto tran_err;
551 /* We need to find which intro point in the descriptor we are connected to
552 * on intro_circ. */
553 ip = find_desc_intro_point_by_ident(intro_circ->hs_ident, desc);
554 if (BUG(ip == NULL)) {
555 /* If we can find a descriptor from this introduction circuit ident, we
556 * must have a valid intro point object. Permanent error. */
557 goto perm_err;
560 /* Send the INTRODUCE1 cell. */
561 if (hs_circ_send_introduce1(intro_circ, rend_circ, ip,
562 desc->subcredential) < 0) {
563 /* Unable to send the cell, the intro circuit has been marked for close so
564 * this is a permanent error. */
565 tor_assert_nonfatal(TO_CIRCUIT(intro_circ)->marked_for_close);
566 goto perm_err;
569 /* Cell has been sent successfully. Copy the introduction point
570 * authentication and encryption key in the rendezvous circuit identifier so
571 * we can compute the ntor keys when we receive the RENDEZVOUS2 cell. */
572 memcpy(&rend_circ->hs_ident->intro_enc_pk, &ip->enc_key,
573 sizeof(rend_circ->hs_ident->intro_enc_pk));
574 ed25519_pubkey_copy(&rend_circ->hs_ident->intro_auth_pk,
575 &intro_circ->hs_ident->intro_auth_pk);
577 /* Now, we wait for an ACK or NAK on this circuit. */
578 circuit_change_purpose(TO_CIRCUIT(intro_circ),
579 CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT);
580 /* Set timestamp_dirty, because circuit_expire_building expects it to
581 * specify when a circuit entered the _C_INTRODUCE_ACK_WAIT state. */
582 TO_CIRCUIT(intro_circ)->timestamp_dirty = time(NULL);
583 pathbias_count_use_attempt(intro_circ);
585 /* Success. */
586 status = 0;
587 goto end;
589 perm_err:
590 /* Permanent error: it is possible that the intro circuit was closed prior
591 * because we weren't able to send the cell. Make sure we don't double close
592 * it which would result in a warning. */
593 if (!TO_CIRCUIT(intro_circ)->marked_for_close) {
594 circuit_mark_for_close(TO_CIRCUIT(intro_circ), END_CIRC_REASON_INTERNAL);
596 circuit_mark_for_close(TO_CIRCUIT(rend_circ), END_CIRC_REASON_INTERNAL);
597 status = -2;
598 goto end;
600 tran_err:
601 status = -1;
603 end:
604 memwipe(onion_address, 0, sizeof(onion_address));
605 return status;
608 /* Using the introduction circuit circ, setup the authentication key of the
609 * intro point this circuit has extended to. */
610 static void
611 setup_intro_circ_auth_key(origin_circuit_t *circ)
613 const hs_descriptor_t *desc;
614 const hs_desc_intro_point_t *ip;
616 tor_assert(circ);
618 desc = hs_cache_lookup_as_client(&circ->hs_ident->identity_pk);
619 if (BUG(desc == NULL)) {
620 /* Opening intro circuit without the descriptor is no good... */
621 goto end;
624 /* We will go over every intro point and try to find which one is linked to
625 * that circuit. Those lists are small so it's not that expensive. */
626 ip = find_desc_intro_point_by_legacy_id(
627 circ->build_state->chosen_exit->identity_digest, desc);
628 if (ip) {
629 /* We got it, copy its authentication key to the identifier. */
630 ed25519_pubkey_copy(&circ->hs_ident->intro_auth_pk,
631 &ip->auth_key_cert->signed_key);
632 goto end;
635 /* Reaching this point means we didn't find any intro point for this circuit
636 * which is not suppose to happen. */
637 tor_assert_nonfatal_unreached();
639 end:
640 return;
643 /* Called when an introduction circuit has opened. */
644 static void
645 client_intro_circ_has_opened(origin_circuit_t *circ)
647 tor_assert(circ);
648 tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
649 log_info(LD_REND, "Introduction circuit %u has opened. Attaching streams.",
650 (unsigned int) TO_CIRCUIT(circ)->n_circ_id);
652 /* This is an introduction circuit so we'll attach the correct
653 * authentication key to the circuit identifier so it can be identified
654 * properly later on. */
655 setup_intro_circ_auth_key(circ);
657 connection_ap_attach_pending(1);
660 /* Called when a rendezvous circuit has opened. */
661 static void
662 client_rendezvous_circ_has_opened(origin_circuit_t *circ)
664 tor_assert(circ);
665 tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
667 const extend_info_t *rp_ei = circ->build_state->chosen_exit;
669 /* Check that we didn't accidentally choose a node that does not understand
670 * the v3 rendezvous protocol */
671 if (rp_ei) {
672 const node_t *rp_node = node_get_by_id(rp_ei->identity_digest);
673 if (rp_node) {
674 if (BUG(!node_supports_v3_rendezvous_point(rp_node))) {
675 return;
680 log_info(LD_REND, "Rendezvous circuit has opened to %s.",
681 safe_str_client(extend_info_describe(rp_ei)));
683 /* Ignore returned value, nothing we can really do. On failure, the circuit
684 * will be marked for close. */
685 hs_circ_send_establish_rendezvous(circ);
687 /* Register rend circuit in circuitmap if it's still alive. */
688 if (!TO_CIRCUIT(circ)->marked_for_close) {
689 hs_circuitmap_register_rend_circ_client_side(circ,
690 circ->hs_ident->rendezvous_cookie);
694 /* This is an helper function that convert a descriptor intro point object ip
695 * to a newly allocated extend_info_t object fully initialized. Return NULL if
696 * we can't convert it for which chances are that we are missing or malformed
697 * link specifiers. */
698 STATIC extend_info_t *
699 desc_intro_point_to_extend_info(const hs_desc_intro_point_t *ip)
701 extend_info_t *ei;
702 smartlist_t *lspecs = smartlist_new();
704 tor_assert(ip);
706 /* We first encode the descriptor link specifiers into the binary
707 * representation which is a trunnel object. */
708 SMARTLIST_FOREACH_BEGIN(ip->link_specifiers,
709 const hs_desc_link_specifier_t *, desc_lspec) {
710 link_specifier_t *lspec = hs_desc_lspec_to_trunnel(desc_lspec);
711 smartlist_add(lspecs, lspec);
712 } SMARTLIST_FOREACH_END(desc_lspec);
714 /* Explicitely put the direct connection option to 0 because this is client
715 * side and there is no such thing as a non anonymous client. */
716 ei = hs_get_extend_info_from_lspecs(lspecs, &ip->onion_key, 0);
718 SMARTLIST_FOREACH(lspecs, link_specifier_t *, ls, link_specifier_free(ls));
719 smartlist_free(lspecs);
720 return ei;
723 /* Return true iff the intro point ip for the service service_pk is usable.
724 * This function checks if the intro point is in the client intro state cache
725 * and checks at the failures. It is considered usable if:
726 * - No error happened (INTRO_POINT_FAILURE_GENERIC)
727 * - It is not flagged as timed out (INTRO_POINT_FAILURE_TIMEOUT)
728 * - The unreachable count is lower than
729 * MAX_INTRO_POINT_REACHABILITY_FAILURES (INTRO_POINT_FAILURE_UNREACHABLE)
731 static int
732 intro_point_is_usable(const ed25519_public_key_t *service_pk,
733 const hs_desc_intro_point_t *ip)
735 const hs_cache_intro_state_t *state;
737 tor_assert(service_pk);
738 tor_assert(ip);
740 state = hs_cache_client_intro_state_find(service_pk,
741 &ip->auth_key_cert->signed_key);
742 if (state == NULL) {
743 /* This means we've never encountered any problem thus usable. */
744 goto usable;
746 if (state->error) {
747 log_info(LD_REND, "Intro point with auth key %s had an error. Not usable",
748 safe_str_client(ed25519_fmt(&ip->auth_key_cert->signed_key)));
749 goto not_usable;
751 if (state->timed_out) {
752 log_info(LD_REND, "Intro point with auth key %s timed out. Not usable",
753 safe_str_client(ed25519_fmt(&ip->auth_key_cert->signed_key)));
754 goto not_usable;
756 if (state->unreachable_count >= MAX_INTRO_POINT_REACHABILITY_FAILURES) {
757 log_info(LD_REND, "Intro point with auth key %s unreachable. Not usable",
758 safe_str_client(ed25519_fmt(&ip->auth_key_cert->signed_key)));
759 goto not_usable;
762 usable:
763 return 1;
764 not_usable:
765 return 0;
768 /* Using a descriptor desc, return a newly allocated extend_info_t object of a
769 * randomly picked introduction point from its list. Return NULL if none are
770 * usable. */
771 STATIC extend_info_t *
772 client_get_random_intro(const ed25519_public_key_t *service_pk)
774 extend_info_t *ei = NULL, *ei_excluded = NULL;
775 smartlist_t *usable_ips = NULL;
776 const hs_descriptor_t *desc;
777 const hs_desc_encrypted_data_t *enc_data;
778 const or_options_t *options = get_options();
779 /* Calculate the onion address for logging purposes */
780 char onion_address[HS_SERVICE_ADDR_LEN_BASE32 + 1];
782 tor_assert(service_pk);
784 desc = hs_cache_lookup_as_client(service_pk);
785 /* Assume the service is v3 if the descriptor is missing. This is ok,
786 * because we only use the address in log messages */
787 hs_build_address(service_pk,
788 desc ? desc->plaintext_data.version : HS_VERSION_THREE,
789 onion_address);
790 if (desc == NULL || !hs_client_any_intro_points_usable(service_pk,
791 desc)) {
792 log_info(LD_REND, "Unable to randomly select an introduction point "
793 "for service %s because descriptor %s. We can't connect.",
794 safe_str_client(onion_address),
795 (desc) ? "doesn't have any usable intro points"
796 : "is missing (assuming v3 onion address)");
797 goto end;
800 enc_data = &desc->encrypted_data;
801 usable_ips = smartlist_new();
802 smartlist_add_all(usable_ips, enc_data->intro_points);
803 while (smartlist_len(usable_ips) != 0) {
804 int idx;
805 const hs_desc_intro_point_t *ip;
807 /* Pick a random intro point and immediately remove it from the usable
808 * list so we don't pick it again if we have to iterate more. */
809 idx = crypto_rand_int(smartlist_len(usable_ips));
810 ip = smartlist_get(usable_ips, idx);
811 smartlist_del(usable_ips, idx);
813 /* We need to make sure we have a usable intro points which is in a good
814 * state in our cache. */
815 if (!intro_point_is_usable(service_pk, ip)) {
816 continue;
819 /* Generate an extend info object from the intro point object. */
820 ei = desc_intro_point_to_extend_info(ip);
821 if (ei == NULL) {
822 /* We can get here for instance if the intro point is a private address
823 * and we aren't allowed to extend to those. */
824 log_info(LD_REND, "Unable to select introduction point with auth key %s "
825 "for service %s, because we could not extend to it.",
826 safe_str_client(ed25519_fmt(&ip->auth_key_cert->signed_key)),
827 safe_str_client(onion_address));
828 continue;
831 /* Test the pick against ExcludeNodes. */
832 if (routerset_contains_extendinfo(options->ExcludeNodes, ei)) {
833 /* If this pick is in the ExcludeNodes list, we keep its reference so if
834 * we ever end up not being able to pick anything else and StrictNodes is
835 * unset, we'll use it. */
836 if (ei_excluded) {
837 /* If something was already here free it. After the loop is gone we
838 * will examine the last excluded intro point, and that's fine since
839 * that's random anyway */
840 extend_info_free(ei_excluded);
842 ei_excluded = ei;
843 continue;
846 /* Good pick! Let's go with this. */
847 goto end;
850 /* Reaching this point means a couple of things. Either we can't use any of
851 * the intro point listed because the IP address can't be extended to or it
852 * is listed in the ExcludeNodes list. In the later case, if StrictNodes is
853 * set, we are forced to not use anything. */
854 ei = ei_excluded;
855 if (options->StrictNodes) {
856 log_warn(LD_REND, "Every introduction point for service %s is in the "
857 "ExcludeNodes set and StrictNodes is set. We can't connect.",
858 safe_str_client(onion_address));
859 extend_info_free(ei);
860 ei = NULL;
861 } else {
862 log_fn(LOG_PROTOCOL_WARN, LD_REND, "Every introduction point for service "
863 "%s is unusable or we can't extend to it. We can't connect.",
864 safe_str_client(onion_address));
867 end:
868 smartlist_free(usable_ips);
869 memwipe(onion_address, 0, sizeof(onion_address));
870 return ei;
873 /* For this introduction circuit, we'll look at if we have any usable
874 * introduction point left for this service. If so, we'll use the circuit to
875 * re-extend to a new intro point. Else, we'll close the circuit and its
876 * corresponding rendezvous circuit. Return 0 if we are re-extending else -1
877 * if we are closing the circuits.
879 * This is called when getting an INTRODUCE_ACK cell with a NACK. */
880 static int
881 close_or_reextend_intro_circ(origin_circuit_t *intro_circ)
883 int ret = -1;
884 const hs_descriptor_t *desc;
885 origin_circuit_t *rend_circ;
887 tor_assert(intro_circ);
889 desc = hs_cache_lookup_as_client(&intro_circ->hs_ident->identity_pk);
890 if (BUG(desc == NULL)) {
891 /* We can't continue without a descriptor. */
892 goto close;
894 /* We still have the descriptor, great! Let's try to see if we can
895 * re-extend by looking up if there are any usable intro points. */
896 if (!hs_client_any_intro_points_usable(&intro_circ->hs_ident->identity_pk,
897 desc)) {
898 goto close;
900 /* Try to re-extend now. */
901 if (hs_client_reextend_intro_circuit(intro_circ) < 0) {
902 goto close;
904 /* Success on re-extending. Don't return an error. */
905 ret = 0;
906 goto end;
908 close:
909 /* Change the intro circuit purpose before so we don't report an intro point
910 * failure again triggering an extra descriptor fetch. The circuit can
911 * already be closed on failure to re-extend. */
912 if (!TO_CIRCUIT(intro_circ)->marked_for_close) {
913 circuit_change_purpose(TO_CIRCUIT(intro_circ),
914 CIRCUIT_PURPOSE_C_INTRODUCE_ACKED);
915 circuit_mark_for_close(TO_CIRCUIT(intro_circ), END_CIRC_REASON_FINISHED);
917 /* Close the related rendezvous circuit. */
918 rend_circ = hs_circuitmap_get_rend_circ_client_side(
919 intro_circ->hs_ident->rendezvous_cookie);
920 /* The rendezvous circuit might have collapsed while the INTRODUCE_ACK was
921 * inflight so we can't expect one every time. */
922 if (rend_circ) {
923 circuit_mark_for_close(TO_CIRCUIT(rend_circ), END_CIRC_REASON_FINISHED);
926 end:
927 return ret;
930 /* Called when we get an INTRODUCE_ACK success status code. Do the appropriate
931 * actions for the rendezvous point and finally close intro_circ. */
932 static void
933 handle_introduce_ack_success(origin_circuit_t *intro_circ)
935 origin_circuit_t *rend_circ = NULL;
937 tor_assert(intro_circ);
939 log_info(LD_REND, "Received INTRODUCE_ACK ack! Informing rendezvous");
941 /* Get the rendezvous circuit for this rendezvous cookie. */
942 uint8_t *rendezvous_cookie = intro_circ->hs_ident->rendezvous_cookie;
943 rend_circ = hs_circuitmap_get_rend_circ_client_side(rendezvous_cookie);
944 if (rend_circ == NULL) {
945 log_warn(LD_REND, "Can't find any rendezvous circuit. Stopping");
946 goto end;
949 assert_circ_anonymity_ok(rend_circ, get_options());
951 /* It is possible to get a RENDEZVOUS2 cell before the INTRODUCE_ACK which
952 * means that the circuit will be joined and already transmitting data. In
953 * that case, simply skip the purpose change and close the intro circuit
954 * like it should be. */
955 if (TO_CIRCUIT(rend_circ)->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
956 goto end;
958 circuit_change_purpose(TO_CIRCUIT(rend_circ),
959 CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED);
960 /* Set timestamp_dirty, because circuit_expire_building expects it to
961 * specify when a circuit entered the
962 * CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED state. */
963 TO_CIRCUIT(rend_circ)->timestamp_dirty = time(NULL);
965 end:
966 /* We don't need the intro circuit anymore. It did what it had to do! */
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 /* XXX: Close pending intro circuits we might have in parallel. */
972 return;
975 /* Called when we get an INTRODUCE_ACK failure status code. Depending on our
976 * failure cache status, either close the circuit or re-extend to a new
977 * introduction point. */
978 static void
979 handle_introduce_ack_bad(origin_circuit_t *circ, int status)
981 tor_assert(circ);
983 log_info(LD_REND, "Received INTRODUCE_ACK nack by %s. Reason: %u",
984 safe_str_client(extend_info_describe(circ->build_state->chosen_exit)),
985 status);
987 /* It's a NAK. The introduction point didn't relay our request. */
988 circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_C_INTRODUCING);
990 /* Note down this failure in the intro point failure cache. Depending on how
991 * many times we've tried this intro point, close it or reextend. */
992 hs_cache_client_intro_state_note(&circ->hs_ident->identity_pk,
993 &circ->hs_ident->intro_auth_pk,
994 INTRO_POINT_FAILURE_GENERIC);
997 /* Called when we get an INTRODUCE_ACK on the intro circuit circ. The encoded
998 * cell is in payload of length payload_len. Return 0 on success else a
999 * negative value. The circuit is either close or reuse to re-extend to a new
1000 * introduction point. */
1001 static int
1002 handle_introduce_ack(origin_circuit_t *circ, const uint8_t *payload,
1003 size_t payload_len)
1005 int status, ret = -1;
1007 tor_assert(circ);
1008 tor_assert(circ->build_state);
1009 tor_assert(circ->build_state->chosen_exit);
1010 assert_circ_anonymity_ok(circ, get_options());
1011 tor_assert(payload);
1013 status = hs_cell_parse_introduce_ack(payload, payload_len);
1014 switch (status) {
1015 case HS_CELL_INTRO_ACK_SUCCESS:
1016 ret = 0;
1017 handle_introduce_ack_success(circ);
1018 goto end;
1019 case HS_CELL_INTRO_ACK_FAILURE:
1020 case HS_CELL_INTRO_ACK_BADFMT:
1021 case HS_CELL_INTRO_ACK_NORELAY:
1022 handle_introduce_ack_bad(circ, status);
1023 /* We are going to see if we have to close the circuits (IP and RP) or we
1024 * can re-extend to a new intro point. */
1025 ret = close_or_reextend_intro_circ(circ);
1026 break;
1027 default:
1028 log_info(LD_PROTOCOL, "Unknown INTRODUCE_ACK status code %u from %s",
1029 status,
1030 safe_str_client(extend_info_describe(circ->build_state->chosen_exit)));
1031 break;
1034 end:
1035 return ret;
1038 /* Called when we get a RENDEZVOUS2 cell on the rendezvous circuit circ. The
1039 * encoded cell is in payload of length payload_len. Return 0 on success or a
1040 * negative value on error. On error, the circuit is marked for close. */
1041 STATIC int
1042 handle_rendezvous2(origin_circuit_t *circ, const uint8_t *payload,
1043 size_t payload_len)
1045 int ret = -1;
1046 curve25519_public_key_t server_pk;
1047 uint8_t auth_mac[DIGEST256_LEN] = {0};
1048 uint8_t handshake_info[CURVE25519_PUBKEY_LEN + sizeof(auth_mac)] = {0};
1049 hs_ntor_rend_cell_keys_t keys;
1050 const hs_ident_circuit_t *ident;
1052 tor_assert(circ);
1053 tor_assert(payload);
1055 /* Make things easier. */
1056 ident = circ->hs_ident;
1057 tor_assert(ident);
1059 if (hs_cell_parse_rendezvous2(payload, payload_len, handshake_info,
1060 sizeof(handshake_info)) < 0) {
1061 goto err;
1063 /* Get from the handshake info the SERVER_PK and AUTH_MAC. */
1064 memcpy(&server_pk, handshake_info, CURVE25519_PUBKEY_LEN);
1065 memcpy(auth_mac, handshake_info + CURVE25519_PUBKEY_LEN, sizeof(auth_mac));
1067 /* Generate the handshake info. */
1068 if (hs_ntor_client_get_rendezvous1_keys(&ident->intro_auth_pk,
1069 &ident->rendezvous_client_kp,
1070 &ident->intro_enc_pk, &server_pk,
1071 &keys) < 0) {
1072 log_info(LD_REND, "Unable to compute the rendezvous keys.");
1073 goto err;
1076 /* Critical check, make sure that the MAC matches what we got with what we
1077 * computed just above. */
1078 if (!hs_ntor_client_rendezvous2_mac_is_good(&keys, auth_mac)) {
1079 log_info(LD_REND, "Invalid MAC in RENDEZVOUS2. Rejecting cell.");
1080 goto err;
1083 /* Setup the e2e encryption on the circuit and finalize its state. */
1084 if (hs_circuit_setup_e2e_rend_circ(circ, keys.ntor_key_seed,
1085 sizeof(keys.ntor_key_seed), 0) < 0) {
1086 log_info(LD_REND, "Unable to setup the e2e encryption.");
1087 goto err;
1089 /* Success. Hidden service connection finalized! */
1090 ret = 0;
1091 goto end;
1093 err:
1094 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
1095 end:
1096 memwipe(&keys, 0, sizeof(keys));
1097 return ret;
1100 /* Return true iff the client can fetch a descriptor for this service public
1101 * identity key and status_out if not NULL is untouched. If the client can
1102 * _not_ fetch the descriptor and if status_out is not NULL, it is set with
1103 * the fetch status code. */
1104 static unsigned int
1105 can_client_refetch_desc(const ed25519_public_key_t *identity_pk,
1106 hs_client_fetch_status_t *status_out)
1108 hs_client_fetch_status_t status;
1110 tor_assert(identity_pk);
1112 /* Are we configured to fetch descriptors? */
1113 if (!get_options()->FetchHidServDescriptors) {
1114 log_warn(LD_REND, "We received an onion address for a hidden service "
1115 "descriptor but we are configured to not fetch.");
1116 status = HS_CLIENT_FETCH_NOT_ALLOWED;
1117 goto cannot;
1120 /* Without a live consensus we can't do any client actions. It is needed to
1121 * compute the hashring for a service. */
1122 if (!networkstatus_get_live_consensus(approx_time())) {
1123 log_info(LD_REND, "Can't fetch descriptor for service %s because we "
1124 "are missing a live consensus. Stalling connection.",
1125 safe_str_client(ed25519_fmt(identity_pk)));
1126 status = HS_CLIENT_FETCH_MISSING_INFO;
1127 goto cannot;
1130 if (!router_have_minimum_dir_info()) {
1131 log_info(LD_REND, "Can't fetch descriptor for service %s because we "
1132 "dont have enough descriptors. Stalling connection.",
1133 safe_str_client(ed25519_fmt(identity_pk)));
1134 status = HS_CLIENT_FETCH_MISSING_INFO;
1135 goto cannot;
1138 /* Check if fetching a desc for this HS is useful to us right now */
1140 const hs_descriptor_t *cached_desc = NULL;
1141 cached_desc = hs_cache_lookup_as_client(identity_pk);
1142 if (cached_desc && hs_client_any_intro_points_usable(identity_pk,
1143 cached_desc)) {
1144 log_info(LD_GENERAL, "We would fetch a v3 hidden service descriptor "
1145 "but we already have a usable descriptor.");
1146 status = HS_CLIENT_FETCH_HAVE_DESC;
1147 goto cannot;
1151 /* Don't try to refetch while we have a pending request for it. */
1152 if (directory_request_is_pending(identity_pk)) {
1153 log_info(LD_REND, "Already a pending directory request. Waiting on it.");
1154 status = HS_CLIENT_FETCH_PENDING;
1155 goto cannot;
1158 /* Yes, client can fetch! */
1159 return 1;
1160 cannot:
1161 if (status_out) {
1162 *status_out = status;
1164 return 0;
1167 /* ========== */
1168 /* Public API */
1169 /* ========== */
1171 /** A circuit just finished connecting to a hidden service that the stream
1172 * <b>conn</b> has been waiting for. Let the HS subsystem know about this. */
1173 void
1174 hs_client_note_connection_attempt_succeeded(const edge_connection_t *conn)
1176 tor_assert(connection_edge_is_rendezvous_stream(conn));
1178 if (BUG(conn->rend_data && conn->hs_ident)) {
1179 log_warn(LD_BUG, "Stream had both rend_data and hs_ident..."
1180 "Prioritizing hs_ident");
1183 if (conn->hs_ident) { /* It's v3: pass it to the prop224 handler */
1184 note_connection_attempt_succeeded(conn->hs_ident);
1185 return;
1186 } else if (conn->rend_data) { /* It's v2: pass it to the legacy handler */
1187 rend_client_note_connection_attempt_ended(conn->rend_data);
1188 return;
1192 /* With the given encoded descriptor in desc_str and the service key in
1193 * service_identity_pk, decode the descriptor and set the desc pointer with a
1194 * newly allocated descriptor object.
1196 * Return 0 on success else a negative value and desc is set to NULL. */
1198 hs_client_decode_descriptor(const char *desc_str,
1199 const ed25519_public_key_t *service_identity_pk,
1200 hs_descriptor_t **desc)
1202 int ret;
1203 uint8_t subcredential[DIGEST256_LEN];
1204 ed25519_public_key_t blinded_pubkey;
1206 tor_assert(desc_str);
1207 tor_assert(service_identity_pk);
1208 tor_assert(desc);
1210 /* Create subcredential for this HS so that we can decrypt */
1212 uint64_t current_time_period = hs_get_time_period_num(0);
1213 hs_build_blinded_pubkey(service_identity_pk, NULL, 0, current_time_period,
1214 &blinded_pubkey);
1215 hs_get_subcredential(service_identity_pk, &blinded_pubkey, subcredential);
1218 /* Parse descriptor */
1219 ret = hs_desc_decode_descriptor(desc_str, subcredential, desc);
1220 memwipe(subcredential, 0, sizeof(subcredential));
1221 if (ret < 0) {
1222 log_warn(LD_GENERAL, "Could not parse received descriptor as client.");
1223 if (get_options()->SafeLogging_ == SAFELOG_SCRUB_NONE) {
1224 log_warn(LD_GENERAL, "%s", escaped(desc_str));
1226 goto err;
1229 /* Make sure the descriptor signing key cross certifies with the computed
1230 * blinded key. Without this validation, anyone knowing the subcredential
1231 * and onion address can forge a descriptor. */
1232 if (tor_cert_checksig((*desc)->plaintext_data.signing_key_cert,
1233 &blinded_pubkey, approx_time()) < 0) {
1234 log_warn(LD_GENERAL, "Descriptor signing key certificate signature "
1235 "doesn't validate with computed blinded key.");
1236 goto err;
1239 return 0;
1240 err:
1241 return -1;
1244 /* Return true iff there are at least one usable intro point in the service
1245 * descriptor desc. */
1247 hs_client_any_intro_points_usable(const ed25519_public_key_t *service_pk,
1248 const hs_descriptor_t *desc)
1250 tor_assert(service_pk);
1251 tor_assert(desc);
1253 SMARTLIST_FOREACH_BEGIN(desc->encrypted_data.intro_points,
1254 const hs_desc_intro_point_t *, ip) {
1255 if (intro_point_is_usable(service_pk, ip)) {
1256 goto usable;
1258 } SMARTLIST_FOREACH_END(ip);
1260 return 0;
1261 usable:
1262 return 1;
1265 /** Launch a connection to a hidden service directory to fetch a hidden
1266 * service descriptor using <b>identity_pk</b> to get the necessary keys.
1268 * A hs_client_fetch_status_t code is returned. */
1270 hs_client_refetch_hsdesc(const ed25519_public_key_t *identity_pk)
1272 hs_client_fetch_status_t status;
1274 tor_assert(identity_pk);
1276 if (!can_client_refetch_desc(identity_pk, &status)) {
1277 return status;
1280 /* Try to fetch the desc and if we encounter an unrecoverable error, mark
1281 * the desc as unavailable for now. */
1282 status = fetch_v3_desc(identity_pk);
1283 if (fetch_status_should_close_socks(status)) {
1284 close_all_socks_conns_waiting_for_desc(identity_pk, status,
1285 END_STREAM_REASON_RESOLVEFAILED);
1286 /* Remove HSDir fetch attempts so that we can retry later if the user
1287 * wants us to regardless of if we closed any connections. */
1288 purge_hid_serv_request(identity_pk);
1290 return status;
1293 /* This is called when we are trying to attach an AP connection to these
1294 * hidden service circuits from connection_ap_handshake_attach_circuit().
1295 * Return 0 on success, -1 for a transient error that is actions were
1296 * triggered to recover or -2 for a permenent error where both circuits will
1297 * marked for close.
1299 * The following supports every hidden service version. */
1301 hs_client_send_introduce1(origin_circuit_t *intro_circ,
1302 origin_circuit_t *rend_circ)
1304 return (intro_circ->hs_ident) ? send_introduce1(intro_circ, rend_circ) :
1305 rend_client_send_introduction(intro_circ,
1306 rend_circ);
1309 /* Called when the client circuit circ has been established. It can be either
1310 * an introduction or rendezvous circuit. This function handles all hidden
1311 * service versions. */
1312 void
1313 hs_client_circuit_has_opened(origin_circuit_t *circ)
1315 tor_assert(circ);
1317 /* Handle both version. v2 uses rend_data and v3 uses the hs circuit
1318 * identifier hs_ident. Can't be both. */
1319 switch (TO_CIRCUIT(circ)->purpose) {
1320 case CIRCUIT_PURPOSE_C_INTRODUCING:
1321 if (circ->hs_ident) {
1322 client_intro_circ_has_opened(circ);
1323 } else {
1324 rend_client_introcirc_has_opened(circ);
1326 break;
1327 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1328 if (circ->hs_ident) {
1329 client_rendezvous_circ_has_opened(circ);
1330 } else {
1331 rend_client_rendcirc_has_opened(circ);
1333 break;
1334 default:
1335 tor_assert_nonfatal_unreached();
1339 /* Called when we receive a RENDEZVOUS_ESTABLISHED cell. Change the state of
1340 * the circuit to CIRCUIT_PURPOSE_C_REND_READY. Return 0 on success else a
1341 * negative value and the circuit marked for close. */
1343 hs_client_receive_rendezvous_acked(origin_circuit_t *circ,
1344 const uint8_t *payload, size_t payload_len)
1346 tor_assert(circ);
1347 tor_assert(payload);
1349 (void) payload_len;
1351 if (TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND) {
1352 log_warn(LD_PROTOCOL, "Got a RENDEZVOUS_ESTABLISHED but we were not "
1353 "expecting one. Closing circuit.");
1354 goto err;
1357 log_info(LD_REND, "Received an RENDEZVOUS_ESTABLISHED. This circuit is "
1358 "now ready for rendezvous.");
1359 circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_C_REND_READY);
1361 /* Set timestamp_dirty, because circuit_expire_building expects it to
1362 * specify when a circuit entered the _C_REND_READY state. */
1363 TO_CIRCUIT(circ)->timestamp_dirty = time(NULL);
1365 /* From a path bias point of view, this circuit is now successfully used.
1366 * Waiting any longer opens us up to attacks from malicious hidden services.
1367 * They could induce the client to attempt to connect to their hidden
1368 * service and never reply to the client's rend requests */
1369 pathbias_mark_use_success(circ);
1371 /* If we already have the introduction circuit built, make sure we send
1372 * the INTRODUCE cell _now_ */
1373 connection_ap_attach_pending(1);
1375 return 0;
1376 err:
1377 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
1378 return -1;
1381 /* This is called when a descriptor has arrived following a fetch request and
1382 * has been stored in the client cache. Every entry connection that matches
1383 * the service identity key in the ident will get attached to the hidden
1384 * service circuit. */
1385 void
1386 hs_client_desc_has_arrived(const hs_ident_dir_conn_t *ident)
1388 time_t now = time(NULL);
1389 smartlist_t *conns = NULL;
1391 tor_assert(ident);
1393 conns = connection_list_by_type_state(CONN_TYPE_AP,
1394 AP_CONN_STATE_RENDDESC_WAIT);
1395 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
1396 const hs_descriptor_t *desc;
1397 entry_connection_t *entry_conn = TO_ENTRY_CONN(base_conn);
1398 const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(entry_conn);
1400 /* Only consider the entry connections that matches the service for which
1401 * we just fetched its descriptor. */
1402 if (!edge_conn->hs_ident ||
1403 !ed25519_pubkey_eq(&ident->identity_pk,
1404 &edge_conn->hs_ident->identity_pk)) {
1405 continue;
1407 assert_connection_ok(base_conn, now);
1409 /* We were just called because we stored the descriptor for this service
1410 * so not finding a descriptor means we have a bigger problem. */
1411 desc = hs_cache_lookup_as_client(&ident->identity_pk);
1412 if (BUG(desc == NULL)) {
1413 goto end;
1416 if (!hs_client_any_intro_points_usable(&ident->identity_pk, desc)) {
1417 log_info(LD_REND, "Hidden service descriptor is unusable. "
1418 "Closing streams.");
1419 connection_mark_unattached_ap(entry_conn,
1420 END_STREAM_REASON_RESOLVEFAILED);
1421 /* We are unable to use the descriptor so remove the directory request
1422 * from the cache so the next connection can try again. */
1423 note_connection_attempt_succeeded(edge_conn->hs_ident);
1424 goto end;
1427 log_info(LD_REND, "Descriptor has arrived. Launching circuits.");
1429 /* Because the connection can now proceed to opening circuit and
1430 * ultimately connect to the service, reset those timestamp so the
1431 * connection is considered "fresh" and can continue without being closed
1432 * too early. */
1433 base_conn->timestamp_created = now;
1434 base_conn->timestamp_lastread = now;
1435 base_conn->timestamp_lastwritten = now;
1436 /* Change connection's state into waiting for a circuit. */
1437 base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
1439 connection_ap_mark_as_pending_circuit(entry_conn);
1440 } SMARTLIST_FOREACH_END(base_conn);
1442 end:
1443 /* We don't have ownership of the objects in this list. */
1444 smartlist_free(conns);
1447 /* Return a newly allocated extend_info_t for a randomly chosen introduction
1448 * point for the given edge connection identifier ident. Return NULL if we
1449 * can't pick any usable introduction points. */
1450 extend_info_t *
1451 hs_client_get_random_intro_from_edge(const edge_connection_t *edge_conn)
1453 tor_assert(edge_conn);
1455 return (edge_conn->hs_ident) ?
1456 client_get_random_intro(&edge_conn->hs_ident->identity_pk) :
1457 rend_client_get_random_intro(edge_conn->rend_data);
1459 /* Called when get an INTRODUCE_ACK cell on the introduction circuit circ.
1460 * Return 0 on success else a negative value is returned. The circuit will be
1461 * closed or reuse to extend again to another intro point. */
1463 hs_client_receive_introduce_ack(origin_circuit_t *circ,
1464 const uint8_t *payload, size_t payload_len)
1466 int ret = -1;
1468 tor_assert(circ);
1469 tor_assert(payload);
1471 if (TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
1472 log_warn(LD_PROTOCOL, "Unexpected INTRODUCE_ACK on circuit %u.",
1473 (unsigned int) TO_CIRCUIT(circ)->n_circ_id);
1474 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
1475 goto end;
1478 ret = (circ->hs_ident) ? handle_introduce_ack(circ, payload, payload_len) :
1479 rend_client_introduction_acked(circ, payload,
1480 payload_len);
1481 /* For path bias: This circuit was used successfully. NACK or ACK counts. */
1482 pathbias_mark_use_success(circ);
1484 end:
1485 return ret;
1488 /* Called when get a RENDEZVOUS2 cell on the rendezvous circuit circ. Return
1489 * 0 on success else a negative value is returned. The circuit will be closed
1490 * on error. */
1492 hs_client_receive_rendezvous2(origin_circuit_t *circ,
1493 const uint8_t *payload, size_t payload_len)
1495 int ret = -1;
1497 tor_assert(circ);
1498 tor_assert(payload);
1500 /* Circuit can possibly be in both state because we could receive a
1501 * RENDEZVOUS2 cell before the INTRODUCE_ACK has been received. */
1502 if (TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
1503 TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
1504 log_warn(LD_PROTOCOL, "Unexpected RENDEZVOUS2 cell on circuit %u. "
1505 "Closing circuit.",
1506 (unsigned int) TO_CIRCUIT(circ)->n_circ_id);
1507 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
1508 goto end;
1511 log_info(LD_REND, "Got RENDEZVOUS2 cell from hidden service on circuit %u.",
1512 TO_CIRCUIT(circ)->n_circ_id);
1514 ret = (circ->hs_ident) ? handle_rendezvous2(circ, payload, payload_len) :
1515 rend_client_receive_rendezvous(circ, payload,
1516 payload_len);
1517 end:
1518 return ret;
1521 /* Extend the introduction circuit circ to another valid introduction point
1522 * for the hidden service it is trying to connect to, or mark it and launch a
1523 * new circuit if we can't extend it. Return 0 on success or possible
1524 * success. Return -1 and mark the introduction circuit for close on permanent
1525 * failure.
1527 * On failure, the caller is responsible for marking the associated rendezvous
1528 * circuit for close. */
1530 hs_client_reextend_intro_circuit(origin_circuit_t *circ)
1532 int ret = -1;
1533 extend_info_t *ei;
1535 tor_assert(circ);
1537 ei = (circ->hs_ident) ?
1538 client_get_random_intro(&circ->hs_ident->identity_pk) :
1539 rend_client_get_random_intro(circ->rend_data);
1540 if (ei == NULL) {
1541 log_warn(LD_REND, "No usable introduction points left. Closing.");
1542 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
1543 goto end;
1546 if (circ->remaining_relay_early_cells) {
1547 log_info(LD_REND, "Re-extending circ %u, this time to %s.",
1548 (unsigned int) TO_CIRCUIT(circ)->n_circ_id,
1549 safe_str_client(extend_info_describe(ei)));
1550 ret = circuit_extend_to_new_exit(circ, ei);
1551 if (ret == 0) {
1552 /* We were able to extend so update the timestamp so we avoid expiring
1553 * this circuit too early. The intro circuit is short live so the
1554 * linkability issue is minimized, we just need the circuit to hold a
1555 * bit longer so we can introduce. */
1556 TO_CIRCUIT(circ)->timestamp_dirty = time(NULL);
1558 } else {
1559 log_info(LD_REND, "Closing intro circ %u (out of RELAY_EARLY cells).",
1560 (unsigned int) TO_CIRCUIT(circ)->n_circ_id);
1561 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
1562 /* connection_ap_handshake_attach_circuit will launch a new intro circ. */
1563 ret = 0;
1566 end:
1567 extend_info_free(ei);
1568 return ret;
1571 /* Release all the storage held by the client subsystem. */
1572 void
1573 hs_client_free_all(void)
1575 /* Purge the hidden service request cache. */
1576 hs_purge_last_hid_serv_requests();
1579 /* Purge all potentially remotely-detectable state held in the hidden
1580 * service client code. Called on SIGNAL NEWNYM. */
1581 void
1582 hs_client_purge_state(void)
1584 /* v2 subsystem. */
1585 rend_client_purge_state();
1587 /* Cancel all descriptor fetches. Do this first so once done we are sure
1588 * that our descriptor cache won't modified. */
1589 cancel_descriptor_fetches();
1590 /* Purge the introduction point state cache. */
1591 hs_cache_client_intro_state_purge();
1592 /* Purge the descriptor cache. */
1593 hs_cache_purge_as_client();
1594 /* Purge the last hidden service request cache. */
1595 hs_purge_last_hid_serv_requests();
1597 log_info(LD_REND, "Hidden service client state has been purged.");
1600 /* Called when our directory information has changed. */
1601 void
1602 hs_client_dir_info_changed(void)
1604 /* We have possibly reached the minimum directory information or new
1605 * consensus so retry all pending SOCKS connection in
1606 * AP_CONN_STATE_RENDDESC_WAIT state in order to fetch the descriptor. */
1607 retry_all_socks_conn_waiting_for_desc();