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