make dist: only include files from practracker dir intentionally.
[tor.git] / src / feature / hs / hs_circuit.c
bloba6e86c5ab3b184c08a5a98b667d919dbdad45246
1 /* Copyright (c) 2017-2019, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
4 /**
5 * \file hs_circuit.c
6 **/
8 #define HS_CIRCUIT_PRIVATE
10 #include "core/or/or.h"
11 #include "app/config/config.h"
12 #include "core/crypto/hs_ntor.h"
13 #include "core/or/circuitbuild.h"
14 #include "core/or/circuitlist.h"
15 #include "core/or/circuituse.h"
16 #include "core/or/policies.h"
17 #include "core/or/relay.h"
18 #include "core/or/crypt_path.h"
19 #include "feature/client/circpathbias.h"
20 #include "feature/hs/hs_cell.h"
21 #include "feature/hs/hs_circuit.h"
22 #include "feature/hs/hs_circuitmap.h"
23 #include "feature/hs/hs_ident.h"
24 #include "feature/hs/hs_service.h"
25 #include "feature/nodelist/describe.h"
26 #include "feature/nodelist/nodelist.h"
27 #include "feature/rend/rendservice.h"
28 #include "feature/stats/rephist.h"
29 #include "lib/crypt_ops/crypto_dh.h"
30 #include "lib/crypt_ops/crypto_rand.h"
31 #include "lib/crypt_ops/crypto_util.h"
33 /* Trunnel. */
34 #include "trunnel/ed25519_cert.h"
35 #include "trunnel/hs/cell_common.h"
36 #include "trunnel/hs/cell_establish_intro.h"
38 #include "core/or/cpath_build_state_st.h"
39 #include "core/or/crypt_path_st.h"
40 #include "feature/nodelist/node_st.h"
41 #include "core/or/origin_circuit_st.h"
43 /* A circuit is about to become an e2e rendezvous circuit. Check
44 * <b>circ_purpose</b> and ensure that it's properly set. Return true iff
45 * circuit purpose is properly set, otherwise return false. */
46 static int
47 circuit_purpose_is_correct_for_rend(unsigned int circ_purpose,
48 int is_service_side)
50 if (is_service_side) {
51 if (circ_purpose != CIRCUIT_PURPOSE_S_CONNECT_REND) {
52 log_warn(LD_BUG,
53 "HS e2e circuit setup with wrong purpose (%d)", circ_purpose);
54 return 0;
58 if (!is_service_side) {
59 if (circ_purpose != CIRCUIT_PURPOSE_C_REND_READY &&
60 circ_purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
61 log_warn(LD_BUG,
62 "Client e2e circuit setup with wrong purpose (%d)", circ_purpose);
63 return 0;
67 return 1;
70 /* Create and return a crypt path for the final hop of a v3 prop224 rendezvous
71 * circuit. Initialize the crypt path crypto using the output material from the
72 * ntor key exchange at <b>ntor_key_seed</b>.
74 * If <b>is_service_side</b> is set, we are the hidden service and the final
75 * hop of the rendezvous circuit is the client on the other side. */
76 static crypt_path_t *
77 create_rend_cpath(const uint8_t *ntor_key_seed, size_t seed_len,
78 int is_service_side)
80 uint8_t keys[HS_NTOR_KEY_EXPANSION_KDF_OUT_LEN];
81 crypt_path_t *cpath = NULL;
83 /* Do the key expansion */
84 if (hs_ntor_circuit_key_expansion(ntor_key_seed, seed_len,
85 keys, sizeof(keys)) < 0) {
86 goto err;
89 /* Setup the cpath */
90 cpath = tor_malloc_zero(sizeof(crypt_path_t));
91 cpath->magic = CRYPT_PATH_MAGIC;
93 if (cpath_init_circuit_crypto(cpath, (char*)keys, sizeof(keys),
94 is_service_side, 1) < 0) {
95 tor_free(cpath);
96 goto err;
99 err:
100 memwipe(keys, 0, sizeof(keys));
101 return cpath;
104 /* We are a v2 legacy HS client: Create and return a crypt path for the hidden
105 * service on the other side of the rendezvous circuit <b>circ</b>. Initialize
106 * the crypt path crypto using the body of the RENDEZVOUS1 cell at
107 * <b>rend_cell_body</b> (which must be at least DH1024_KEY_LEN+DIGEST_LEN
108 * bytes).
110 static crypt_path_t *
111 create_rend_cpath_legacy(origin_circuit_t *circ, const uint8_t *rend_cell_body)
113 crypt_path_t *hop = NULL;
114 char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN];
116 /* first DH1024_KEY_LEN bytes are g^y from the service. Finish the dh
117 * handshake...*/
118 tor_assert(circ->build_state);
119 tor_assert(circ->build_state->pending_final_cpath);
120 hop = circ->build_state->pending_final_cpath;
122 tor_assert(hop->rend_dh_handshake_state);
123 if (crypto_dh_compute_secret(LOG_PROTOCOL_WARN, hop->rend_dh_handshake_state,
124 (char*)rend_cell_body, DH1024_KEY_LEN,
125 keys, DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
126 log_warn(LD_GENERAL, "Couldn't complete DH handshake.");
127 goto err;
129 /* ... and set up cpath. */
130 if (cpath_init_circuit_crypto(hop,
131 keys+DIGEST_LEN, sizeof(keys)-DIGEST_LEN,
132 0, 0) < 0)
133 goto err;
135 /* Check whether the digest is right... */
136 if (tor_memneq(keys, rend_cell_body+DH1024_KEY_LEN, DIGEST_LEN)) {
137 log_warn(LD_PROTOCOL, "Incorrect digest of key material.");
138 goto err;
141 /* clean up the crypto stuff we just made */
142 crypto_dh_free(hop->rend_dh_handshake_state);
143 hop->rend_dh_handshake_state = NULL;
145 goto done;
147 err:
148 hop = NULL;
150 done:
151 memwipe(keys, 0, sizeof(keys));
152 return hop;
155 /* Append the final <b>hop</b> to the cpath of the rend <b>circ</b>, and mark
156 * <b>circ</b> ready for use to transfer HS relay cells. */
157 static void
158 finalize_rend_circuit(origin_circuit_t *circ, crypt_path_t *hop,
159 int is_service_side)
161 tor_assert(circ);
162 tor_assert(hop);
164 /* Notify the circuit state machine that we are splicing this circuit */
165 int new_circ_purpose = is_service_side ?
166 CIRCUIT_PURPOSE_S_REND_JOINED : CIRCUIT_PURPOSE_C_REND_JOINED;
167 circuit_change_purpose(TO_CIRCUIT(circ), new_circ_purpose);
169 /* All is well. Extend the circuit. */
170 hop->state = CPATH_STATE_OPEN;
171 /* Set the windows to default. */
172 hop->package_window = circuit_initial_package_window();
173 hop->deliver_window = CIRCWINDOW_START;
175 /* Now that this circuit has finished connecting to its destination,
176 * make sure circuit_get_open_circ_or_launch is willing to return it
177 * so we can actually use it. */
178 circ->hs_circ_has_timed_out = 0;
180 /* Append the hop to the cpath of this circuit */
181 cpath_extend_linked_list(&circ->cpath, hop);
183 /* In legacy code, 'pending_final_cpath' points to the final hop we just
184 * appended to the cpath. We set the original pointer to NULL so that we
185 * don't double free it. */
186 if (circ->build_state) {
187 circ->build_state->pending_final_cpath = NULL;
190 /* Finally, mark circuit as ready to be used for client streams */
191 if (!is_service_side) {
192 circuit_try_attaching_streams(circ);
196 /* For a given circuit and a service introduction point object, register the
197 * intro circuit to the circuitmap. This supports legacy intro point. */
198 static void
199 register_intro_circ(const hs_service_intro_point_t *ip,
200 origin_circuit_t *circ)
202 tor_assert(ip);
203 tor_assert(circ);
205 if (ip->base.is_only_legacy) {
206 hs_circuitmap_register_intro_circ_v2_service_side(circ,
207 ip->legacy_key_digest);
208 } else {
209 hs_circuitmap_register_intro_circ_v3_service_side(circ,
210 &ip->auth_key_kp.pubkey);
214 /* Return the number of opened introduction circuit for the given circuit that
215 * is matching its identity key. */
216 static unsigned int
217 count_opened_desc_intro_point_circuits(const hs_service_t *service,
218 const hs_service_descriptor_t *desc)
220 unsigned int count = 0;
222 tor_assert(service);
223 tor_assert(desc);
225 DIGEST256MAP_FOREACH(desc->intro_points.map, key,
226 const hs_service_intro_point_t *, ip) {
227 const circuit_t *circ;
228 const origin_circuit_t *ocirc = hs_circ_service_get_intro_circ(ip);
229 if (ocirc == NULL) {
230 continue;
232 circ = TO_CIRCUIT(ocirc);
233 tor_assert(circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
234 circ->purpose == CIRCUIT_PURPOSE_S_INTRO);
235 /* Having a circuit not for the requested service is really bad. */
236 tor_assert(ed25519_pubkey_eq(&service->keys.identity_pk,
237 &ocirc->hs_ident->identity_pk));
238 /* Only count opened circuit and skip circuit that will be closed. */
239 if (!circ->marked_for_close && circ->state == CIRCUIT_STATE_OPEN) {
240 count++;
242 } DIGEST256MAP_FOREACH_END;
243 return count;
246 /* From a given service, rendezvous cookie and handshake info, create a
247 * rendezvous point circuit identifier. This can't fail. */
248 STATIC hs_ident_circuit_t *
249 create_rp_circuit_identifier(const hs_service_t *service,
250 const uint8_t *rendezvous_cookie,
251 const curve25519_public_key_t *server_pk,
252 const hs_ntor_rend_cell_keys_t *keys)
254 hs_ident_circuit_t *ident;
255 uint8_t handshake_info[CURVE25519_PUBKEY_LEN + DIGEST256_LEN];
257 tor_assert(service);
258 tor_assert(rendezvous_cookie);
259 tor_assert(server_pk);
260 tor_assert(keys);
262 ident = hs_ident_circuit_new(&service->keys.identity_pk,
263 HS_IDENT_CIRCUIT_RENDEZVOUS);
264 /* Copy the RENDEZVOUS_COOKIE which is the unique identifier. */
265 memcpy(ident->rendezvous_cookie, rendezvous_cookie,
266 sizeof(ident->rendezvous_cookie));
267 /* Build the HANDSHAKE_INFO which looks like this:
268 * SERVER_PK [32 bytes]
269 * AUTH_INPUT_MAC [32 bytes]
271 memcpy(handshake_info, server_pk->public_key, CURVE25519_PUBKEY_LEN);
272 memcpy(handshake_info + CURVE25519_PUBKEY_LEN, keys->rend_cell_auth_mac,
273 DIGEST256_LEN);
274 tor_assert(sizeof(ident->rendezvous_handshake_info) ==
275 sizeof(handshake_info));
276 memcpy(ident->rendezvous_handshake_info, handshake_info,
277 sizeof(ident->rendezvous_handshake_info));
278 /* Finally copy the NTOR_KEY_SEED for e2e encryption on the circuit. */
279 tor_assert(sizeof(ident->rendezvous_ntor_key_seed) ==
280 sizeof(keys->ntor_key_seed));
281 memcpy(ident->rendezvous_ntor_key_seed, keys->ntor_key_seed,
282 sizeof(ident->rendezvous_ntor_key_seed));
283 return ident;
286 /* From a given service and service intro point, create an introduction point
287 * circuit identifier. This can't fail. */
288 static hs_ident_circuit_t *
289 create_intro_circuit_identifier(const hs_service_t *service,
290 const hs_service_intro_point_t *ip)
292 hs_ident_circuit_t *ident;
294 tor_assert(service);
295 tor_assert(ip);
297 ident = hs_ident_circuit_new(&service->keys.identity_pk,
298 HS_IDENT_CIRCUIT_INTRO);
299 ed25519_pubkey_copy(&ident->intro_auth_pk, &ip->auth_key_kp.pubkey);
301 return ident;
304 /* For a given introduction point and an introduction circuit, send the
305 * ESTABLISH_INTRO cell. The service object is used for logging. This can fail
306 * and if so, the circuit is closed and the intro point object is flagged
307 * that the circuit is not established anymore which is important for the
308 * retry mechanism. */
309 static void
310 send_establish_intro(const hs_service_t *service,
311 hs_service_intro_point_t *ip, origin_circuit_t *circ)
313 ssize_t cell_len;
314 uint8_t payload[RELAY_PAYLOAD_SIZE];
316 tor_assert(service);
317 tor_assert(ip);
318 tor_assert(circ);
320 /* Encode establish intro cell. */
321 cell_len = hs_cell_build_establish_intro(circ->cpath->prev->rend_circ_nonce,
322 ip, payload);
323 if (cell_len < 0) {
324 log_warn(LD_REND, "Unable to encode ESTABLISH_INTRO cell for service %s "
325 "on circuit %u. Closing circuit.",
326 safe_str_client(service->onion_address),
327 TO_CIRCUIT(circ)->n_circ_id);
328 goto err;
331 /* Send the cell on the circuit. */
332 if (relay_send_command_from_edge(CONTROL_CELL_ID, TO_CIRCUIT(circ),
333 RELAY_COMMAND_ESTABLISH_INTRO,
334 (char *) payload, cell_len,
335 circ->cpath->prev) < 0) {
336 log_info(LD_REND, "Unable to send ESTABLISH_INTRO cell for service %s "
337 "on circuit %u.",
338 safe_str_client(service->onion_address),
339 TO_CIRCUIT(circ)->n_circ_id);
340 /* On error, the circuit has been closed. */
341 goto done;
344 /* Record the attempt to use this circuit. */
345 pathbias_count_use_attempt(circ);
346 goto done;
348 err:
349 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
350 done:
351 memwipe(payload, 0, sizeof(payload));
354 /* Return a string constant describing the anonymity of service. */
355 static const char *
356 get_service_anonymity_string(const hs_service_t *service)
358 if (service->config.is_single_onion) {
359 return "single onion";
360 } else {
361 return "hidden";
365 /* For a given service, the ntor onion key and a rendezvous cookie, launch a
366 * circuit to the rendezvous point specified by the link specifiers. On
367 * success, a circuit identifier is attached to the circuit with the needed
368 * data. This function will try to open a circuit for a maximum value of
369 * MAX_REND_FAILURES then it will give up. */
370 static void
371 launch_rendezvous_point_circuit(const hs_service_t *service,
372 const hs_service_intro_point_t *ip,
373 const hs_cell_introduce2_data_t *data)
375 int circ_needs_uptime;
376 time_t now = time(NULL);
377 extend_info_t *info = NULL;
378 origin_circuit_t *circ;
380 tor_assert(service);
381 tor_assert(ip);
382 tor_assert(data);
384 circ_needs_uptime = hs_service_requires_uptime_circ(service->config.ports);
386 /* Get the extend info data structure for the chosen rendezvous point
387 * specified by the given link specifiers. */
388 info = hs_get_extend_info_from_lspecs(data->link_specifiers,
389 &data->onion_pk,
390 service->config.is_single_onion);
391 if (info == NULL) {
392 /* We are done here, we can't extend to the rendezvous point.
393 * If you're running an IPv6-only v3 single onion service on 0.3.2 or with
394 * 0.3.2 clients, and somehow disable the option check, it will fail here.
396 log_fn(LOG_PROTOCOL_WARN, LD_REND,
397 "Not enough info to open a circuit to a rendezvous point for "
398 "%s service %s.",
399 get_service_anonymity_string(service),
400 safe_str_client(service->onion_address));
401 goto end;
404 for (int i = 0; i < MAX_REND_FAILURES; i++) {
405 int circ_flags = CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_IS_INTERNAL;
406 if (circ_needs_uptime) {
407 circ_flags |= CIRCLAUNCH_NEED_UPTIME;
409 /* Firewall and policies are checked when getting the extend info. */
410 if (service->config.is_single_onion) {
411 circ_flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
414 circ = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND, info,
415 circ_flags);
416 if (circ != NULL) {
417 /* Stop retrying, we have a circuit! */
418 break;
421 if (circ == NULL) {
422 log_warn(LD_REND, "Giving up on launching a rendezvous circuit to %s "
423 "for %s service %s",
424 safe_str_client(extend_info_describe(info)),
425 get_service_anonymity_string(service),
426 safe_str_client(service->onion_address));
427 goto end;
429 log_info(LD_REND, "Rendezvous circuit launched to %s with cookie %s "
430 "for %s service %s",
431 safe_str_client(extend_info_describe(info)),
432 safe_str_client(hex_str((const char *) data->rendezvous_cookie,
433 REND_COOKIE_LEN)),
434 get_service_anonymity_string(service),
435 safe_str_client(service->onion_address));
436 tor_assert(circ->build_state);
437 /* Rendezvous circuit have a specific timeout for the time spent on trying
438 * to connect to the rendezvous point. */
439 circ->build_state->expiry_time = now + MAX_REND_TIMEOUT;
441 /* Create circuit identifier and key material. */
443 hs_ntor_rend_cell_keys_t keys;
444 curve25519_keypair_t ephemeral_kp;
445 /* No need for extra strong, this is only for this circuit life time. This
446 * key will be used for the RENDEZVOUS1 cell that will be sent on the
447 * circuit once opened. */
448 curve25519_keypair_generate(&ephemeral_kp, 0);
449 if (hs_ntor_service_get_rendezvous1_keys(&ip->auth_key_kp.pubkey,
450 &ip->enc_key_kp,
451 &ephemeral_kp, &data->client_pk,
452 &keys) < 0) {
453 /* This should not really happened but just in case, don't make tor
454 * freak out, close the circuit and move on. */
455 log_info(LD_REND, "Unable to get RENDEZVOUS1 key material for "
456 "service %s",
457 safe_str_client(service->onion_address));
458 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
459 goto end;
461 circ->hs_ident = create_rp_circuit_identifier(service,
462 data->rendezvous_cookie,
463 &ephemeral_kp.pubkey, &keys);
464 memwipe(&ephemeral_kp, 0, sizeof(ephemeral_kp));
465 memwipe(&keys, 0, sizeof(keys));
466 tor_assert(circ->hs_ident);
469 end:
470 extend_info_free(info);
473 /* Return true iff the given service rendezvous circuit circ is allowed for a
474 * relaunch to the rendezvous point. */
475 static int
476 can_relaunch_service_rendezvous_point(const origin_circuit_t *circ)
478 tor_assert(circ);
479 /* This is initialized when allocating an origin circuit. */
480 tor_assert(circ->build_state);
481 tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
483 /* XXX: Retrying under certain condition. This is related to #22455. */
485 /* Avoid to relaunch twice a circuit to the same rendezvous point at the
486 * same time. */
487 if (circ->hs_service_side_rend_circ_has_been_relaunched) {
488 log_info(LD_REND, "Rendezvous circuit to %s has already been retried. "
489 "Skipping retry.",
490 safe_str_client(
491 extend_info_describe(circ->build_state->chosen_exit)));
492 goto disallow;
495 /* We check failure_count >= hs_get_service_max_rend_failures()-1 below, and
496 * the -1 is because we increment the failure count for our current failure
497 * *after* this clause. */
498 int max_rend_failures = hs_get_service_max_rend_failures() - 1;
500 /* A failure count that has reached maximum allowed or circuit that expired,
501 * we skip relaunching. */
502 if (circ->build_state->failure_count > max_rend_failures ||
503 circ->build_state->expiry_time <= time(NULL)) {
504 log_info(LD_REND, "Attempt to build a rendezvous circuit to %s has "
505 "failed with %d attempts and expiry time %ld. "
506 "Giving up building.",
507 safe_str_client(
508 extend_info_describe(circ->build_state->chosen_exit)),
509 circ->build_state->failure_count,
510 (long int) circ->build_state->expiry_time);
511 goto disallow;
514 /* Allowed to relaunch. */
515 return 1;
516 disallow:
517 return 0;
520 /* Retry the rendezvous point of circ by launching a new circuit to it. */
521 static void
522 retry_service_rendezvous_point(const origin_circuit_t *circ)
524 int flags = 0;
525 origin_circuit_t *new_circ;
526 cpath_build_state_t *bstate;
528 tor_assert(circ);
529 /* This is initialized when allocating an origin circuit. */
530 tor_assert(circ->build_state);
531 tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
533 /* Ease our life. */
534 bstate = circ->build_state;
536 log_info(LD_REND, "Retrying rendezvous point circuit to %s",
537 safe_str_client(extend_info_describe(bstate->chosen_exit)));
539 /* Get the current build state flags for the next circuit. */
540 flags |= (bstate->need_uptime) ? CIRCLAUNCH_NEED_UPTIME : 0;
541 flags |= (bstate->need_capacity) ? CIRCLAUNCH_NEED_CAPACITY : 0;
542 flags |= (bstate->is_internal) ? CIRCLAUNCH_IS_INTERNAL : 0;
544 /* We do NOT add the onehop tunnel flag even though it might be a single
545 * onion service. The reason is that if we failed once to connect to the RP
546 * with a direct connection, we consider that chances are that we will fail
547 * again so try a 3-hop circuit and hope for the best. Because the service
548 * has no anonymity (single onion), this change of behavior won't affect
549 * security directly. */
551 new_circ = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND,
552 bstate->chosen_exit, flags);
553 if (new_circ == NULL) {
554 log_warn(LD_REND, "Failed to launch rendezvous circuit to %s",
555 safe_str_client(extend_info_describe(bstate->chosen_exit)));
556 goto done;
559 /* Transfer build state information to the new circuit state in part to
560 * catch any other failures. */
561 new_circ->build_state->failure_count = bstate->failure_count+1;
562 new_circ->build_state->expiry_time = bstate->expiry_time;
563 new_circ->hs_ident = hs_ident_circuit_dup(circ->hs_ident);
565 done:
566 return;
569 /* Using the given descriptor intro point ip, the node of the
570 * rendezvous point rp_node and the service's subcredential, populate the
571 * already allocated intro1_data object with the needed key material and link
572 * specifiers.
574 * Return 0 on success or a negative value if we couldn't properly filled the
575 * introduce1 data from the RP node. In other word, it means the RP node is
576 * unusable to use in the introduction. */
577 static int
578 setup_introduce1_data(const hs_desc_intro_point_t *ip,
579 const node_t *rp_node,
580 const uint8_t *subcredential,
581 hs_cell_introduce1_data_t *intro1_data)
583 int ret = -1;
584 smartlist_t *rp_lspecs;
586 tor_assert(ip);
587 tor_assert(rp_node);
588 tor_assert(subcredential);
589 tor_assert(intro1_data);
591 /* Build the link specifiers from the node at the end of the rendezvous
592 * circuit that we opened for this introduction. */
593 rp_lspecs = node_get_link_specifier_smartlist(rp_node, 0);
594 if (smartlist_len(rp_lspecs) == 0) {
595 /* We can't rendezvous without link specifiers. */
596 smartlist_free(rp_lspecs);
597 goto end;
600 /* Populate the introduce1 data object. */
601 memset(intro1_data, 0, sizeof(hs_cell_introduce1_data_t));
602 if (ip->legacy.key != NULL) {
603 intro1_data->is_legacy = 1;
604 intro1_data->legacy_key = ip->legacy.key;
606 intro1_data->auth_pk = &ip->auth_key_cert->signed_key;
607 intro1_data->enc_pk = &ip->enc_key;
608 intro1_data->subcredential = subcredential;
609 intro1_data->link_specifiers = rp_lspecs;
610 intro1_data->onion_pk = node_get_curve25519_onion_key(rp_node);
611 if (intro1_data->onion_pk == NULL) {
612 /* We can't rendezvous without the curve25519 onion key. */
613 goto end;
615 /* Success, we have valid introduce data. */
616 ret = 0;
618 end:
619 return ret;
622 /* ========== */
623 /* Public API */
624 /* ========== */
626 /* Return an introduction point circuit matching the given intro point object.
627 * NULL is returned is no such circuit can be found. */
628 origin_circuit_t *
629 hs_circ_service_get_intro_circ(const hs_service_intro_point_t *ip)
631 tor_assert(ip);
633 if (ip->base.is_only_legacy) {
634 return hs_circuitmap_get_intro_circ_v2_service_side(ip->legacy_key_digest);
635 } else {
636 return hs_circuitmap_get_intro_circ_v3_service_side(
637 &ip->auth_key_kp.pubkey);
641 /* Called when we fail building a rendezvous circuit at some point other than
642 * the last hop: launches a new circuit to the same rendezvous point. This
643 * supports legacy service.
645 * We currently relaunch connections to rendezvous points if:
646 * - A rendezvous circuit timed out before connecting to RP.
647 * - The rendezvous circuit failed to connect to the RP.
649 * We avoid relaunching a connection to this rendezvous point if:
650 * - We have already tried MAX_REND_FAILURES times to connect to this RP,
651 * - We've been trying to connect to this RP for more than MAX_REND_TIMEOUT
652 * seconds, or
653 * - We've already retried this specific rendezvous circuit.
655 void
656 hs_circ_retry_service_rendezvous_point(origin_circuit_t *circ)
658 tor_assert(circ);
659 tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
661 /* Check if we are allowed to relaunch to the rendezvous point of circ. */
662 if (!can_relaunch_service_rendezvous_point(circ)) {
663 goto done;
666 /* Flag the circuit that we are relaunching, to avoid to relaunch twice a
667 * circuit to the same rendezvous point at the same time. */
668 circ->hs_service_side_rend_circ_has_been_relaunched = 1;
670 /* Legacy services don't have a hidden service ident. */
671 if (circ->hs_ident) {
672 retry_service_rendezvous_point(circ);
673 } else {
674 rend_service_relaunch_rendezvous(circ);
677 done:
678 return;
681 /* For a given service and a service intro point, launch a circuit to the
682 * extend info ei. If the service is a single onion, a one-hop circuit will be
683 * requested. Return 0 if the circuit was successfully launched and tagged
684 * with the correct identifier. On error, a negative value is returned. */
686 hs_circ_launch_intro_point(hs_service_t *service,
687 const hs_service_intro_point_t *ip,
688 extend_info_t *ei)
690 /* Standard flags for introduction circuit. */
691 int ret = -1, circ_flags = CIRCLAUNCH_NEED_UPTIME | CIRCLAUNCH_IS_INTERNAL;
692 origin_circuit_t *circ;
694 tor_assert(service);
695 tor_assert(ip);
696 tor_assert(ei);
698 /* Update circuit flags in case of a single onion service that requires a
699 * direct connection. */
700 if (service->config.is_single_onion) {
701 circ_flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
704 log_info(LD_REND, "Launching a circuit to intro point %s for service %s.",
705 safe_str_client(extend_info_describe(ei)),
706 safe_str_client(service->onion_address));
708 /* Note down the launch for the retry period. Even if the circuit fails to
709 * be launched, we still want to respect the retry period to avoid stress on
710 * the circuit subsystem. */
711 service->state.num_intro_circ_launched++;
712 circ = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO,
713 ei, circ_flags);
714 if (circ == NULL) {
715 goto end;
718 /* Setup the circuit identifier and attach it to it. */
719 circ->hs_ident = create_intro_circuit_identifier(service, ip);
720 tor_assert(circ->hs_ident);
721 /* Register circuit in the global circuitmap. */
722 register_intro_circ(ip, circ);
724 /* Success. */
725 ret = 0;
726 end:
727 return ret;
730 /* Called when a service introduction point circuit is done building. Given
731 * the service and intro point object, this function will send the
732 * ESTABLISH_INTRO cell on the circuit. Return 0 on success. Return 1 if the
733 * circuit has been repurposed to General because we already have too many
734 * opened. */
736 hs_circ_service_intro_has_opened(hs_service_t *service,
737 hs_service_intro_point_t *ip,
738 const hs_service_descriptor_t *desc,
739 origin_circuit_t *circ)
741 int ret = 0;
742 unsigned int num_intro_circ, num_needed_circ;
744 tor_assert(service);
745 tor_assert(ip);
746 tor_assert(desc);
747 tor_assert(circ);
749 /* Cound opened circuits that have sent ESTABLISH_INTRO cells or are already
750 * established introduction circuits */
751 num_intro_circ = count_opened_desc_intro_point_circuits(service, desc);
752 num_needed_circ = service->config.num_intro_points;
753 if (num_intro_circ > num_needed_circ) {
754 /* There are too many opened valid intro circuit for what the service
755 * needs so repurpose this one. */
757 /* XXX: Legacy code checks options->ExcludeNodes and if not NULL it just
758 * closes the circuit. I have NO idea why it does that so it hasn't been
759 * added here. I can only assume in case our ExcludeNodes list changes but
760 * in that case, all circuit are flagged unusable (config.c). --dgoulet */
762 log_info(LD_CIRC | LD_REND, "Introduction circuit just opened but we "
763 "have enough for service %s. Repurposing "
764 "it to general and leaving internal.",
765 safe_str_client(service->onion_address));
766 tor_assert(circ->build_state->is_internal);
767 /* Remove it from the circuitmap. */
768 hs_circuitmap_remove_circuit(TO_CIRCUIT(circ));
769 /* Cleaning up the hidden service identifier and repurpose. */
770 hs_ident_circuit_free(circ->hs_ident);
771 circ->hs_ident = NULL;
772 if (circuit_should_use_vanguards(TO_CIRCUIT(circ)->purpose))
773 circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_HS_VANGUARDS);
774 else
775 circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_C_GENERAL);
777 /* Inform that this circuit just opened for this new purpose. */
778 circuit_has_opened(circ);
779 /* This return value indicate to the caller that the IP object should be
780 * removed from the service because it's corresponding circuit has just
781 * been repurposed. */
782 ret = 1;
783 goto done;
786 log_info(LD_REND, "Introduction circuit %u established for service %s.",
787 TO_CIRCUIT(circ)->n_circ_id,
788 safe_str_client(service->onion_address));
789 circuit_log_path(LOG_INFO, LD_REND, circ);
791 /* Time to send an ESTABLISH_INTRO cell on this circuit. On error, this call
792 * makes sure the circuit gets closed. */
793 send_establish_intro(service, ip, circ);
795 done:
796 return ret;
799 /* Called when a service rendezvous point circuit is done building. Given the
800 * service and the circuit, this function will send a RENDEZVOUS1 cell on the
801 * circuit using the information in the circuit identifier. If the cell can't
802 * be sent, the circuit is closed. */
803 void
804 hs_circ_service_rp_has_opened(const hs_service_t *service,
805 origin_circuit_t *circ)
807 size_t payload_len;
808 uint8_t payload[RELAY_PAYLOAD_SIZE] = {0};
810 tor_assert(service);
811 tor_assert(circ);
812 tor_assert(circ->hs_ident);
814 /* Some useful logging. */
815 log_info(LD_REND, "Rendezvous circuit %u has opened with cookie %s "
816 "for service %s",
817 TO_CIRCUIT(circ)->n_circ_id,
818 hex_str((const char *) circ->hs_ident->rendezvous_cookie,
819 REND_COOKIE_LEN),
820 safe_str_client(service->onion_address));
821 circuit_log_path(LOG_INFO, LD_REND, circ);
823 /* This can't fail. */
824 payload_len = hs_cell_build_rendezvous1(
825 circ->hs_ident->rendezvous_cookie,
826 sizeof(circ->hs_ident->rendezvous_cookie),
827 circ->hs_ident->rendezvous_handshake_info,
828 sizeof(circ->hs_ident->rendezvous_handshake_info),
829 payload);
831 /* Pad the payload with random bytes so it matches the size of a legacy cell
832 * which is normally always bigger. Also, the size of a legacy cell is
833 * always smaller than the RELAY_PAYLOAD_SIZE so this is safe. */
834 if (payload_len < HS_LEGACY_RENDEZVOUS_CELL_SIZE) {
835 crypto_rand((char *) payload + payload_len,
836 HS_LEGACY_RENDEZVOUS_CELL_SIZE - payload_len);
837 payload_len = HS_LEGACY_RENDEZVOUS_CELL_SIZE;
840 if (relay_send_command_from_edge(CONTROL_CELL_ID, TO_CIRCUIT(circ),
841 RELAY_COMMAND_RENDEZVOUS1,
842 (const char *) payload, payload_len,
843 circ->cpath->prev) < 0) {
844 /* On error, circuit is closed. */
845 log_warn(LD_REND, "Unable to send RENDEZVOUS1 cell on circuit %u "
846 "for service %s",
847 TO_CIRCUIT(circ)->n_circ_id,
848 safe_str_client(service->onion_address));
849 goto done;
852 /* Setup end-to-end rendezvous circuit between the client and us. */
853 if (hs_circuit_setup_e2e_rend_circ(circ,
854 circ->hs_ident->rendezvous_ntor_key_seed,
855 sizeof(circ->hs_ident->rendezvous_ntor_key_seed),
856 1) < 0) {
857 log_warn(LD_GENERAL, "Failed to setup circ");
858 goto done;
861 done:
862 memwipe(payload, 0, sizeof(payload));
865 /* Circ has been expecting an INTRO_ESTABLISHED cell that just arrived. Handle
866 * the INTRO_ESTABLISHED cell payload of length payload_len arriving on the
867 * given introduction circuit circ. The service is only used for logging
868 * purposes. Return 0 on success else a negative value. */
870 hs_circ_handle_intro_established(const hs_service_t *service,
871 const hs_service_intro_point_t *ip,
872 origin_circuit_t *circ,
873 const uint8_t *payload, size_t payload_len)
875 int ret = -1;
877 tor_assert(service);
878 tor_assert(ip);
879 tor_assert(circ);
880 tor_assert(payload);
882 if (BUG(TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)) {
883 goto done;
886 /* Try to parse the payload into a cell making sure we do actually have a
887 * valid cell. For a legacy node, it's an empty payload so as long as we
888 * have the cell, we are good. */
889 if (!ip->base.is_only_legacy &&
890 hs_cell_parse_intro_established(payload, payload_len) < 0) {
891 log_warn(LD_REND, "Unable to parse the INTRO_ESTABLISHED cell on "
892 "circuit %u for service %s",
893 TO_CIRCUIT(circ)->n_circ_id,
894 safe_str_client(service->onion_address));
895 goto done;
898 /* Switch the purpose to a fully working intro point. */
899 circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_S_INTRO);
900 /* Getting a valid INTRODUCE_ESTABLISHED means we've successfully used the
901 * circuit so update our pathbias subsystem. */
902 pathbias_mark_use_success(circ);
903 /* Success. */
904 ret = 0;
906 done:
907 return ret;
910 /* We just received an INTRODUCE2 cell on the established introduction circuit
911 * circ. Handle the INTRODUCE2 payload of size payload_len for the given
912 * circuit and service. This cell is associated with the intro point object ip
913 * and the subcredential. Return 0 on success else a negative value. */
915 hs_circ_handle_introduce2(const hs_service_t *service,
916 const origin_circuit_t *circ,
917 hs_service_intro_point_t *ip,
918 const uint8_t *subcredential,
919 const uint8_t *payload, size_t payload_len)
921 int ret = -1;
922 time_t elapsed;
923 hs_cell_introduce2_data_t data;
925 tor_assert(service);
926 tor_assert(circ);
927 tor_assert(ip);
928 tor_assert(subcredential);
929 tor_assert(payload);
931 /* Populate the data structure with everything we need for the cell to be
932 * parsed, decrypted and key material computed correctly. */
933 data.auth_pk = &ip->auth_key_kp.pubkey;
934 data.enc_kp = &ip->enc_key_kp;
935 data.subcredential = subcredential;
936 data.payload = payload;
937 data.payload_len = payload_len;
938 data.link_specifiers = smartlist_new();
939 data.replay_cache = ip->replay_cache;
941 if (hs_cell_parse_introduce2(&data, circ, service) < 0) {
942 goto done;
945 /* Check whether we've seen this REND_COOKIE before to detect repeats. */
946 if (replaycache_add_test_and_elapsed(
947 service->state.replay_cache_rend_cookie,
948 data.rendezvous_cookie, sizeof(data.rendezvous_cookie),
949 &elapsed)) {
950 /* A Tor client will send a new INTRODUCE1 cell with the same REND_COOKIE
951 * as its previous one if its intro circ times out while in state
952 * CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT. If we received the first
953 * INTRODUCE1 cell (the intro-point relay converts it into an INTRODUCE2
954 * cell), we are already trying to connect to that rend point (and may
955 * have already succeeded); drop this cell. */
956 log_info(LD_REND, "We received an INTRODUCE2 cell with same REND_COOKIE "
957 "field %ld seconds ago. Dropping cell.",
958 (long int) elapsed);
959 goto done;
962 /* At this point, we just confirmed that the full INTRODUCE2 cell is valid
963 * so increment our counter that we've seen one on this intro point. */
964 ip->introduce2_count++;
966 /* Launch rendezvous circuit with the onion key and rend cookie. */
967 launch_rendezvous_point_circuit(service, ip, &data);
968 /* Success. */
969 ret = 0;
971 done:
972 link_specifier_smartlist_free(data.link_specifiers);
973 memwipe(&data, 0, sizeof(data));
974 return ret;
977 /* Circuit <b>circ</b> just finished the rend ntor key exchange. Use the key
978 * exchange output material at <b>ntor_key_seed</b> and setup <b>circ</b> to
979 * serve as a rendezvous end-to-end circuit between the client and the
980 * service. If <b>is_service_side</b> is set, then we are the hidden service
981 * and the other side is the client.
983 * Return 0 if the operation went well; in case of error return -1. */
985 hs_circuit_setup_e2e_rend_circ(origin_circuit_t *circ,
986 const uint8_t *ntor_key_seed, size_t seed_len,
987 int is_service_side)
989 if (BUG(!circuit_purpose_is_correct_for_rend(TO_CIRCUIT(circ)->purpose,
990 is_service_side))) {
991 return -1;
994 crypt_path_t *hop = create_rend_cpath(ntor_key_seed, seed_len,
995 is_service_side);
996 if (!hop) {
997 log_warn(LD_REND, "Couldn't get v3 %s cpath!",
998 is_service_side ? "service-side" : "client-side");
999 return -1;
1002 finalize_rend_circuit(circ, hop, is_service_side);
1004 return 0;
1007 /* We are a v2 legacy HS client and we just received a RENDEZVOUS1 cell
1008 * <b>rend_cell_body</b> on <b>circ</b>. Finish up the DH key exchange and then
1009 * extend the crypt path of <b>circ</b> so that the hidden service is on the
1010 * other side. */
1012 hs_circuit_setup_e2e_rend_circ_legacy_client(origin_circuit_t *circ,
1013 const uint8_t *rend_cell_body)
1016 if (BUG(!circuit_purpose_is_correct_for_rend(
1017 TO_CIRCUIT(circ)->purpose, 0))) {
1018 return -1;
1021 crypt_path_t *hop = create_rend_cpath_legacy(circ, rend_cell_body);
1022 if (!hop) {
1023 log_warn(LD_GENERAL, "Couldn't get v2 cpath.");
1024 return -1;
1027 finalize_rend_circuit(circ, hop, 0);
1029 return 0;
1032 /* Given the introduction circuit intro_circ, the rendezvous circuit
1033 * rend_circ, a descriptor intro point object ip and the service's
1034 * subcredential, send an INTRODUCE1 cell on intro_circ.
1036 * This will also setup the circuit identifier on rend_circ containing the key
1037 * material for the handshake and e2e encryption. Return 0 on success else
1038 * negative value. Because relay_send_command_from_edge() closes the circuit
1039 * on error, it is possible that intro_circ is closed on error. */
1041 hs_circ_send_introduce1(origin_circuit_t *intro_circ,
1042 origin_circuit_t *rend_circ,
1043 const hs_desc_intro_point_t *ip,
1044 const uint8_t *subcredential)
1046 int ret = -1;
1047 ssize_t payload_len;
1048 uint8_t payload[RELAY_PAYLOAD_SIZE] = {0};
1049 hs_cell_introduce1_data_t intro1_data;
1051 tor_assert(intro_circ);
1052 tor_assert(rend_circ);
1053 tor_assert(ip);
1054 tor_assert(subcredential);
1056 /* It is undefined behavior in hs_cell_introduce1_data_clear() if intro1_data
1057 * has been declared on the stack but not initialized. Here, we set it to 0.
1059 memset(&intro1_data, 0, sizeof(hs_cell_introduce1_data_t));
1061 /* This takes various objects in order to populate the introduce1 data
1062 * object which is used to build the content of the cell. */
1063 const node_t *exit_node = build_state_get_exit_node(rend_circ->build_state);
1064 if (exit_node == NULL) {
1065 log_info(LD_REND, "Unable to get rendezvous point for circuit %u. "
1066 "Failing.", TO_CIRCUIT(intro_circ)->n_circ_id);
1067 goto done;
1070 /* We should never select an invalid rendezvous point in theory but if we
1071 * do, this function will fail to populate the introduce data. */
1072 if (setup_introduce1_data(ip, exit_node, subcredential, &intro1_data) < 0) {
1073 log_warn(LD_REND, "Unable to setup INTRODUCE1 data. The chosen rendezvous "
1074 "point is unusable. Closing circuit.");
1075 goto close;
1078 /* Final step before we encode a cell, we setup the circuit identifier which
1079 * will generate both the rendezvous cookie and client keypair for this
1080 * connection. Those are put in the ident. */
1081 intro1_data.rendezvous_cookie = rend_circ->hs_ident->rendezvous_cookie;
1082 intro1_data.client_kp = &rend_circ->hs_ident->rendezvous_client_kp;
1084 memcpy(intro_circ->hs_ident->rendezvous_cookie,
1085 rend_circ->hs_ident->rendezvous_cookie,
1086 sizeof(intro_circ->hs_ident->rendezvous_cookie));
1088 /* From the introduce1 data object, this will encode the INTRODUCE1 cell
1089 * into payload which is then ready to be sent as is. */
1090 payload_len = hs_cell_build_introduce1(&intro1_data, payload);
1091 if (BUG(payload_len < 0)) {
1092 goto close;
1095 if (relay_send_command_from_edge(CONTROL_CELL_ID, TO_CIRCUIT(intro_circ),
1096 RELAY_COMMAND_INTRODUCE1,
1097 (const char *) payload, payload_len,
1098 intro_circ->cpath->prev) < 0) {
1099 /* On error, circuit is closed. */
1100 log_warn(LD_REND, "Unable to send INTRODUCE1 cell on circuit %u.",
1101 TO_CIRCUIT(intro_circ)->n_circ_id);
1102 goto done;
1105 /* Success. */
1106 ret = 0;
1107 goto done;
1109 close:
1110 circuit_mark_for_close(TO_CIRCUIT(rend_circ), END_CIRC_REASON_INTERNAL);
1111 done:
1112 hs_cell_introduce1_data_clear(&intro1_data);
1113 memwipe(payload, 0, sizeof(payload));
1114 return ret;
1117 /* Send an ESTABLISH_RENDEZVOUS cell along the rendezvous circuit circ. On
1118 * success, 0 is returned else -1 and the circuit is marked for close. */
1120 hs_circ_send_establish_rendezvous(origin_circuit_t *circ)
1122 ssize_t cell_len = 0;
1123 uint8_t cell[RELAY_PAYLOAD_SIZE] = {0};
1125 tor_assert(circ);
1126 tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
1128 log_info(LD_REND, "Send an ESTABLISH_RENDEZVOUS cell on circuit %u",
1129 TO_CIRCUIT(circ)->n_circ_id);
1131 /* Set timestamp_dirty, because circuit_expire_building expects it,
1132 * and the rend cookie also means we've used the circ. */
1133 TO_CIRCUIT(circ)->timestamp_dirty = time(NULL);
1135 /* We've attempted to use this circuit. Probe it if we fail */
1136 pathbias_count_use_attempt(circ);
1138 /* Generate the RENDEZVOUS_COOKIE and place it in the identifier so we can
1139 * complete the handshake when receiving the acknowledgement. */
1140 crypto_rand((char *) circ->hs_ident->rendezvous_cookie, HS_REND_COOKIE_LEN);
1141 /* Generate the client keypair. No need to be extra strong, not long term */
1142 curve25519_keypair_generate(&circ->hs_ident->rendezvous_client_kp, 0);
1144 cell_len =
1145 hs_cell_build_establish_rendezvous(circ->hs_ident->rendezvous_cookie,
1146 cell);
1147 if (BUG(cell_len < 0)) {
1148 goto err;
1151 if (relay_send_command_from_edge(CONTROL_CELL_ID, TO_CIRCUIT(circ),
1152 RELAY_COMMAND_ESTABLISH_RENDEZVOUS,
1153 (const char *) cell, cell_len,
1154 circ->cpath->prev) < 0) {
1155 /* Circuit has been marked for close */
1156 log_warn(LD_REND, "Unable to send ESTABLISH_RENDEZVOUS cell on "
1157 "circuit %u", TO_CIRCUIT(circ)->n_circ_id);
1158 memwipe(cell, 0, cell_len);
1159 goto err;
1162 memwipe(cell, 0, cell_len);
1163 return 0;
1164 err:
1165 return -1;
1168 /* We are about to close or free this <b>circ</b>. Clean it up from any
1169 * related HS data structures. This function can be called multiple times
1170 * safely for the same circuit. */
1171 void
1172 hs_circ_cleanup(circuit_t *circ)
1174 tor_assert(circ);
1176 /* If it's a service-side intro circ, notify the HS subsystem for the intro
1177 * point circuit closing so it can be dealt with cleanly. */
1178 if (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
1179 circ->purpose == CIRCUIT_PURPOSE_S_INTRO) {
1180 hs_service_intro_circ_has_closed(TO_ORIGIN_CIRCUIT(circ));
1183 /* Clear HS circuitmap token for this circ (if any). Very important to be
1184 * done after the HS subsystem has been notified of the close else the
1185 * circuit will not be found.
1187 * We do this at the close if possible because from that point on, the
1188 * circuit is good as dead. We can't rely on removing it in the circuit
1189 * free() function because we open a race window between the close and free
1190 * where we can't register a new circuit for the same intro point. */
1191 if (circ->hs_token) {
1192 hs_circuitmap_remove_circuit(circ);