1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2011, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
7 * \brief Client code to access location-hidden services.
11 #include "circuitbuild.h"
12 #include "circuitlist.h"
13 #include "circuituse.h"
15 #include "connection.h"
16 #include "connection_edge.h"
17 #include "directory.h"
20 #include "rendclient.h"
21 #include "rendcommon.h"
23 #include "routerlist.h"
25 static extend_info_t
*rend_client_get_random_intro_impl(
26 const rend_cache_entry_t
*rend_query
,
27 const int strict
, const int warnings
);
29 /** Called when we've established a circuit to an introduction point:
30 * send the introduction request. */
32 rend_client_introcirc_has_opened(origin_circuit_t
*circ
)
34 tor_assert(circ
->_base
.purpose
== CIRCUIT_PURPOSE_C_INTRODUCING
);
35 tor_assert(circ
->cpath
);
37 log_info(LD_REND
,"introcirc is open");
38 connection_ap_attach_pending();
41 /** Send the establish-rendezvous cell along a rendezvous circuit. if
42 * it fails, mark the circ for close and return -1. else return 0.
45 rend_client_send_establish_rendezvous(origin_circuit_t
*circ
)
47 tor_assert(circ
->_base
.purpose
== CIRCUIT_PURPOSE_C_ESTABLISH_REND
);
48 tor_assert(circ
->rend_data
);
49 log_info(LD_REND
, "Sending an ESTABLISH_RENDEZVOUS cell");
51 if (crypto_rand(circ
->rend_data
->rend_cookie
, REND_COOKIE_LEN
) < 0) {
52 log_warn(LD_BUG
, "Internal error: Couldn't produce random cookie.");
53 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_INTERNAL
);
56 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ
),
57 RELAY_COMMAND_ESTABLISH_RENDEZVOUS
,
58 circ
->rend_data
->rend_cookie
,
60 circ
->cpath
->prev
)<0) {
61 /* circ is already marked for close */
62 log_warn(LD_GENERAL
, "Couldn't send ESTABLISH_RENDEZVOUS cell");
69 /** Extend the introduction circuit <b>circ</b> to another valid
70 * introduction point for the hidden service it is trying to connect
71 * to, or mark it and launch a new circuit if we can't extend it.
72 * Return 0 on success. Return -1 and mark the introduction
75 * On failure, the caller is responsible for marking the associated
76 * rendezvous circuit for close. */
78 rend_client_reextend_intro_circuit(origin_circuit_t
*circ
)
80 extend_info_t
*extend_info
;
82 extend_info
= rend_client_get_random_intro(circ
->rend_data
);
85 "No usable introduction points left for %s. Closing.",
86 safe_str_client(circ
->rend_data
->onion_address
));
87 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_INTERNAL
);
90 if (circ
->remaining_relay_early_cells
) {
92 "Re-extending circ %d, this time to %s.",
93 circ
->_base
.n_circ_id
, extend_info
->nickname
);
94 result
= circuit_extend_to_new_exit(circ
, extend_info
);
97 "Building a new introduction circuit, this time to %s.",
98 extend_info
->nickname
);
99 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_FINISHED
);
100 if (!circuit_launch_by_extend_info(CIRCUIT_PURPOSE_C_INTRODUCING
,
102 CIRCLAUNCH_IS_INTERNAL
)) {
103 log_warn(LD_REND
, "Building introduction circuit failed.");
109 extend_info_free(extend_info
);
113 /** Called when we're trying to connect an ap conn; sends an INTRODUCE1 cell
114 * down introcirc if possible.
117 rend_client_send_introduction(origin_circuit_t
*introcirc
,
118 origin_circuit_t
*rendcirc
)
122 char payload
[RELAY_PAYLOAD_SIZE
];
123 char tmp
[RELAY_PAYLOAD_SIZE
];
124 rend_cache_entry_t
*entry
;
127 crypto_pk_env_t
*intro_key
= NULL
;
129 tor_assert(introcirc
->_base
.purpose
== CIRCUIT_PURPOSE_C_INTRODUCING
);
130 tor_assert(rendcirc
->_base
.purpose
== CIRCUIT_PURPOSE_C_REND_READY
);
131 tor_assert(introcirc
->rend_data
);
132 tor_assert(rendcirc
->rend_data
);
133 tor_assert(!rend_cmp_service_ids(introcirc
->rend_data
->onion_address
,
134 rendcirc
->rend_data
->onion_address
));
136 if (rend_cache_lookup_entry(introcirc
->rend_data
->onion_address
, -1,
139 "query %s didn't have valid rend desc in cache. "
140 "Refetching descriptor.",
141 safe_str_client(introcirc
->rend_data
->onion_address
));
142 rend_client_refetch_v2_renddesc(introcirc
->rend_data
);
146 while ((conn
= connection_get_by_type_state_rendquery(CONN_TYPE_AP
,
147 AP_CONN_STATE_CIRCUIT_WAIT
,
148 introcirc
->rend_data
->onion_address
))) {
149 conn
->state
= AP_CONN_STATE_RENDDESC_WAIT
;
156 /* first 20 bytes of payload are the hash of Bob's pk */
158 SMARTLIST_FOREACH(entry
->parsed
->intro_nodes
, rend_intro_point_t
*,
160 if (!memcmp(introcirc
->build_state
->chosen_exit
->identity_digest
,
161 intro
->extend_info
->identity_digest
, DIGEST_LEN
)) {
162 intro_key
= intro
->intro_key
;
167 log_info(LD_REND
, "Could not find intro key for %s at %s; we "
168 "have a v2 rend desc with %d intro points. "
169 "Trying a different intro point...",
170 safe_str_client(introcirc
->rend_data
->onion_address
),
171 introcirc
->build_state
->chosen_exit
->nickname
,
172 smartlist_len(entry
->parsed
->intro_nodes
));
174 if (rend_client_reextend_intro_circuit(introcirc
)) {
180 if (crypto_pk_get_digest(intro_key
, payload
)<0) {
181 log_warn(LD_BUG
, "Internal error: couldn't hash public key.");
185 /* Initialize the pending_final_cpath and start the DH handshake. */
186 cpath
= rendcirc
->build_state
->pending_final_cpath
;
188 cpath
= rendcirc
->build_state
->pending_final_cpath
=
189 tor_malloc_zero(sizeof(crypt_path_t
));
190 cpath
->magic
= CRYPT_PATH_MAGIC
;
191 if (!(cpath
->dh_handshake_state
= crypto_dh_new(DH_TYPE_REND
))) {
192 log_warn(LD_BUG
, "Internal error: couldn't allocate DH.");
195 if (crypto_dh_generate_public(cpath
->dh_handshake_state
)<0) {
196 log_warn(LD_BUG
, "Internal error: couldn't generate g^x.");
201 /* If version is 3, write (optional) auth data and timestamp. */
202 if (entry
->parsed
->protocols
& (1<<3)) {
203 tmp
[0] = 3; /* version 3 of the cell format */
204 tmp
[1] = (uint8_t)introcirc
->rend_data
->auth_type
; /* auth type, if any */
206 if (introcirc
->rend_data
->auth_type
!= REND_NO_AUTH
) {
207 set_uint16(tmp
+2, htons(REND_DESC_COOKIE_LEN
));
208 memcpy(tmp
+4, introcirc
->rend_data
->descriptor_cookie
,
209 REND_DESC_COOKIE_LEN
);
210 v3_shift
+= 2+REND_DESC_COOKIE_LEN
;
212 set_uint32(tmp
+v3_shift
+1, htonl((uint32_t)time(NULL
)));
214 } /* if version 2 only write version number */
215 else if (entry
->parsed
->protocols
& (1<<2)) {
216 tmp
[0] = 2; /* version 2 of the cell format */
219 /* write the remaining items into tmp */
220 if (entry
->parsed
->protocols
& (1<<3) || entry
->parsed
->protocols
& (1<<2)) {
221 /* version 2 format */
222 extend_info_t
*extend_info
= rendcirc
->build_state
->chosen_exit
;
225 set_uint32(tmp
+v3_shift
+1, tor_addr_to_ipv4h(&extend_info
->addr
));
226 set_uint16(tmp
+v3_shift
+5, htons(extend_info
->port
));
227 memcpy(tmp
+v3_shift
+7, extend_info
->identity_digest
, DIGEST_LEN
);
228 klen
= crypto_pk_asn1_encode(extend_info
->onion_key
,
229 tmp
+v3_shift
+7+DIGEST_LEN
+2,
230 sizeof(tmp
)-(v3_shift
+7+DIGEST_LEN
+2));
231 set_uint16(tmp
+v3_shift
+7+DIGEST_LEN
, htons(klen
));
232 memcpy(tmp
+v3_shift
+7+DIGEST_LEN
+2+klen
, rendcirc
->rend_data
->rend_cookie
,
234 dh_offset
= v3_shift
+7+DIGEST_LEN
+2+klen
+REND_COOKIE_LEN
;
237 strncpy(tmp
, rendcirc
->build_state
->chosen_exit
->nickname
,
238 (MAX_NICKNAME_LEN
+1)); /* nul pads */
239 memcpy(tmp
+MAX_NICKNAME_LEN
+1, rendcirc
->rend_data
->rend_cookie
,
241 dh_offset
= MAX_NICKNAME_LEN
+1+REND_COOKIE_LEN
;
244 if (crypto_dh_get_public(cpath
->dh_handshake_state
, tmp
+dh_offset
,
246 log_warn(LD_BUG
, "Internal error: couldn't extract g^x.");
250 note_crypto_pk_op(REND_CLIENT
);
251 /*XXX maybe give crypto_pk_public_hybrid_encrypt a max_len arg,
252 * to avoid buffer overflows? */
253 r
= crypto_pk_public_hybrid_encrypt(intro_key
, payload
+DIGEST_LEN
,
254 sizeof(payload
)-DIGEST_LEN
,
256 (int)(dh_offset
+DH_KEY_LEN
),
257 PK_PKCS1_OAEP_PADDING
, 0);
259 log_warn(LD_BUG
,"Internal error: hybrid pk encrypt failed.");
263 payload_len
= DIGEST_LEN
+ r
;
264 tor_assert(payload_len
<= RELAY_PAYLOAD_SIZE
); /* we overran something */
266 log_info(LD_REND
, "Sending an INTRODUCE1 cell");
267 if (relay_send_command_from_edge(0, TO_CIRCUIT(introcirc
),
268 RELAY_COMMAND_INTRODUCE1
,
269 payload
, payload_len
,
270 introcirc
->cpath
->prev
)<0) {
271 /* introcirc is already marked for close. leave rendcirc alone. */
272 log_warn(LD_BUG
, "Couldn't send INTRODUCE1 cell");
276 /* Now, we wait for an ACK or NAK on this circuit. */
277 introcirc
->_base
.purpose
= CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
;
281 if (!introcirc
->_base
.marked_for_close
)
282 circuit_mark_for_close(TO_CIRCUIT(introcirc
), END_CIRC_REASON_INTERNAL
);
283 circuit_mark_for_close(TO_CIRCUIT(rendcirc
), END_CIRC_REASON_INTERNAL
);
287 /** Called when a rendezvous circuit is open; sends a establish
288 * rendezvous circuit as appropriate. */
290 rend_client_rendcirc_has_opened(origin_circuit_t
*circ
)
292 tor_assert(circ
->_base
.purpose
== CIRCUIT_PURPOSE_C_ESTABLISH_REND
);
294 log_info(LD_REND
,"rendcirc is open");
296 /* generate a rendezvous cookie, store it in circ */
297 if (rend_client_send_establish_rendezvous(circ
) < 0) {
302 /** Called when get an ACK or a NAK for a REND_INTRODUCE1 cell.
305 rend_client_introduction_acked(origin_circuit_t
*circ
,
306 const uint8_t *request
, size_t request_len
)
308 origin_circuit_t
*rendcirc
;
309 (void) request
; // XXXX Use this.
311 if (circ
->_base
.purpose
!= CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
) {
312 log_warn(LD_PROTOCOL
,
313 "Received REND_INTRODUCE_ACK on unexpected circuit %d.",
314 circ
->_base
.n_circ_id
);
315 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_TORPROTOCOL
);
319 tor_assert(circ
->build_state
->chosen_exit
);
320 tor_assert(circ
->rend_data
);
322 if (request_len
== 0) {
323 /* It's an ACK; the introduction point relayed our introduction request. */
324 /* Locate the rend circ which is waiting to hear about this ack,
327 log_info(LD_REND
,"Received ack. Telling rend circ...");
328 rendcirc
= circuit_get_by_rend_query_and_purpose(
329 circ
->rend_data
->onion_address
, CIRCUIT_PURPOSE_C_REND_READY
);
330 if (rendcirc
) { /* remember the ack */
331 rendcirc
->_base
.purpose
= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
;
333 log_info(LD_REND
,"...Found no rend circ. Dropping on the floor.");
335 /* close the circuit: we won't need it anymore. */
336 circ
->_base
.purpose
= CIRCUIT_PURPOSE_C_INTRODUCE_ACKED
;
337 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_FINISHED
);
339 /* It's a NAK; the introduction point didn't relay our request. */
340 circ
->_base
.purpose
= CIRCUIT_PURPOSE_C_INTRODUCING
;
341 /* Remove this intro point from the set of viable introduction
342 * points. If any remain, extend to a new one and try again.
343 * If none remain, refetch the service descriptor.
345 log_info(LD_REND
, "Got nack for %s from %s...",
346 safe_str_client(circ
->rend_data
->onion_address
),
347 circ
->build_state
->chosen_exit
->nickname
);
348 if (rend_client_remove_intro_point(circ
->build_state
->chosen_exit
,
349 circ
->rend_data
) > 0) {
350 /* There are introduction points left. Re-extend the circuit to
351 * another intro point and try again. */
352 int result
= rend_client_reextend_intro_circuit(circ
);
353 /* XXXX If that call failed, should we close the rend circuit,
361 /** The period for which a hidden service directory cannot be queried for
362 * the same descriptor ID again. */
363 #define REND_HID_SERV_DIR_REQUERY_PERIOD (15 * 60)
365 /** Contains the last request times to hidden service directories for
366 * certain queries; keys are strings consisting of base32-encoded
367 * hidden service directory identities and base32-encoded descriptor IDs;
368 * values are pointers to timestamps of the last requests. */
369 static strmap_t
*last_hid_serv_requests
= NULL
;
371 /** Look up the last request time to hidden service directory <b>hs_dir</b>
372 * for descriptor ID <b>desc_id_base32</b>. If <b>set</b> is non-zero,
373 * assign the current time <b>now</b> and return that. Otherwise, return
374 * the most recent request time, or 0 if no such request has been sent
377 lookup_last_hid_serv_request(routerstatus_t
*hs_dir
,
378 const char *desc_id_base32
, time_t now
, int set
)
380 char hsdir_id_base32
[REND_DESC_ID_V2_LEN_BASE32
+ 1];
381 char hsdir_desc_comb_id
[2 * REND_DESC_ID_V2_LEN_BASE32
+ 1];
382 time_t *last_request_ptr
;
383 base32_encode(hsdir_id_base32
, sizeof(hsdir_id_base32
),
384 hs_dir
->identity_digest
, DIGEST_LEN
);
385 tor_snprintf(hsdir_desc_comb_id
, sizeof(hsdir_desc_comb_id
), "%s%s",
386 hsdir_id_base32
, desc_id_base32
);
389 last_request_ptr
= tor_malloc_zero(sizeof(time_t));
390 *last_request_ptr
= now
;
391 oldptr
= strmap_set(last_hid_serv_requests
, hsdir_desc_comb_id
,
395 last_request_ptr
= strmap_get_lc(last_hid_serv_requests
,
397 return (last_request_ptr
) ? *last_request_ptr
: 0;
400 /** Clean the history of request times to hidden service directories, so that
401 * it does not contain requests older than REND_HID_SERV_DIR_REQUERY_PERIOD
402 * seconds any more. */
404 directory_clean_last_hid_serv_requests(void)
407 time_t cutoff
= time(NULL
) - REND_HID_SERV_DIR_REQUERY_PERIOD
;
408 if (!last_hid_serv_requests
)
409 last_hid_serv_requests
= strmap_new();
410 for (iter
= strmap_iter_init(last_hid_serv_requests
);
411 !strmap_iter_done(iter
); ) {
415 strmap_iter_get(iter
, &key
, &val
);
416 ent
= (time_t *) val
;
418 iter
= strmap_iter_next_rmv(last_hid_serv_requests
, iter
);
421 iter
= strmap_iter_next(last_hid_serv_requests
, iter
);
426 /** Determine the responsible hidden service directories for <b>desc_id</b>
427 * and fetch the descriptor belonging to that ID from one of them. Only
428 * send a request to hidden service directories that we did not try within
429 * the last REND_HID_SERV_DIR_REQUERY_PERIOD seconds; on success, return 1,
430 * in the case that no hidden service directory is left to ask for the
431 * descriptor, return 0, and in case of a failure -1. <b>query</b> is only
432 * passed for pretty log statements. */
434 directory_get_from_hs_dir(const char *desc_id
, const rend_data_t
*rend_query
)
436 smartlist_t
*responsible_dirs
= smartlist_create();
437 routerstatus_t
*hs_dir
;
438 char desc_id_base32
[REND_DESC_ID_V2_LEN_BASE32
+ 1];
439 time_t now
= time(NULL
);
440 char descriptor_cookie_base64
[3*REND_DESC_COOKIE_LEN_BASE64
];
442 tor_assert(rend_query
);
443 /* Determine responsible dirs. Even if we can't get all we want,
444 * work with the ones we have. If it's empty, we'll notice below. */
445 hid_serv_get_responsible_directories(responsible_dirs
, desc_id
);
447 base32_encode(desc_id_base32
, sizeof(desc_id_base32
),
448 desc_id
, DIGEST_LEN
);
450 /* Only select those hidden service directories to which we did not send
451 * a request recently and for which we have a router descriptor here. */
452 directory_clean_last_hid_serv_requests(); /* Clean request history first. */
454 SMARTLIST_FOREACH(responsible_dirs
, routerstatus_t
*, dir
, {
455 if (lookup_last_hid_serv_request(dir
, desc_id_base32
, 0, 0) +
456 REND_HID_SERV_DIR_REQUERY_PERIOD
>= now
||
457 !router_get_by_digest(dir
->identity_digest
))
458 SMARTLIST_DEL_CURRENT(responsible_dirs
, dir
);
461 hs_dir
= smartlist_choose(responsible_dirs
);
462 smartlist_free(responsible_dirs
);
464 log_info(LD_REND
, "Could not pick one of the responsible hidden "
465 "service directories, because we requested them all "
466 "recently without success.");
470 /* Remember, that we are requesting a descriptor from this hidden service
472 lookup_last_hid_serv_request(hs_dir
, desc_id_base32
, now
, 1);
474 /* Encode descriptor cookie for logging purposes. */
475 if (rend_query
->auth_type
!= REND_NO_AUTH
) {
476 if (base64_encode(descriptor_cookie_base64
,
477 sizeof(descriptor_cookie_base64
),
478 rend_query
->descriptor_cookie
, REND_DESC_COOKIE_LEN
)<0) {
479 log_warn(LD_BUG
, "Could not base64-encode descriptor cookie.");
482 /* Remove == signs and newline. */
483 descriptor_cookie_base64
[strlen(descriptor_cookie_base64
)-3] = '\0';
485 strlcpy(descriptor_cookie_base64
, "(none)",
486 sizeof(descriptor_cookie_base64
));
489 /* Send fetch request. (Pass query and possibly descriptor cookie so that
490 * they can be written to the directory connection and be referred to when
491 * the response arrives. */
492 directory_initiate_command_routerstatus_rend(hs_dir
,
493 DIR_PURPOSE_FETCH_RENDDESC_V2
,
494 ROUTER_PURPOSE_GENERAL
,
495 1, desc_id_base32
, NULL
, 0, 0,
497 log_info(LD_REND
, "Sending fetch request for v2 descriptor for "
498 "service '%s' with descriptor ID '%s', auth type %d, "
499 "and descriptor cookie '%s' to hidden service "
500 "directory '%s' on port %d.",
501 rend_query
->onion_address
, desc_id_base32
,
502 rend_query
->auth_type
,
503 (rend_query
->auth_type
== REND_NO_AUTH
? "[none]" :
504 escaped_safe_str_client(descriptor_cookie_base64
)),
505 hs_dir
->nickname
, hs_dir
->dir_port
);
509 /** Unless we already have a descriptor for <b>rend_query</b> with at least
510 * one (possibly) working introduction point in it, start a connection to a
511 * hidden service directory to fetch a v2 rendezvous service descriptor. */
513 rend_client_refetch_v2_renddesc(const rend_data_t
*rend_query
)
515 char descriptor_id
[DIGEST_LEN
];
516 int replicas_left_to_try
[REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS
];
518 rend_cache_entry_t
*e
= NULL
;
519 tor_assert(rend_query
);
520 /* Are we configured to fetch descriptors? */
521 if (!get_options()->FetchHidServDescriptors
) {
522 log_warn(LD_REND
, "We received an onion address for a v2 rendezvous "
523 "service descriptor, but are not fetching service descriptors.");
526 /* Before fetching, check if we already have the descriptor here. */
527 if (rend_cache_lookup_entry(rend_query
->onion_address
, -1, &e
) > 0) {
528 log_info(LD_REND
, "We would fetch a v2 rendezvous descriptor, but we "
529 "already have that descriptor here. Not fetching.");
532 log_debug(LD_REND
, "Fetching v2 rendezvous descriptor for service %s",
533 safe_str_client(rend_query
->onion_address
));
534 /* Randomly iterate over the replicas until a descriptor can be fetched
535 * from one of the consecutive nodes, or no options are left. */
536 tries_left
= REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS
;
537 for (i
= 0; i
< REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS
; i
++)
538 replicas_left_to_try
[i
] = i
;
539 while (tries_left
> 0) {
540 int rand
= crypto_rand_int(tries_left
);
541 int chosen_replica
= replicas_left_to_try
[rand
];
542 replicas_left_to_try
[rand
] = replicas_left_to_try
[--tries_left
];
544 if (rend_compute_v2_desc_id(descriptor_id
, rend_query
->onion_address
,
545 rend_query
->auth_type
== REND_STEALTH_AUTH
?
546 rend_query
->descriptor_cookie
: NULL
,
547 time(NULL
), chosen_replica
) < 0) {
548 log_warn(LD_REND
, "Internal error: Computing v2 rendezvous "
549 "descriptor ID did not succeed.");
552 if (directory_get_from_hs_dir(descriptor_id
, rend_query
) != 0)
553 return; /* either success or failure, but we're done */
555 /* If we come here, there are no hidden service directories left. */
556 log_info(LD_REND
, "Could not pick one of the responsible hidden "
557 "service directories to fetch descriptors, because "
558 "we already tried them all unsuccessfully.");
559 /* Close pending connections. */
560 rend_client_desc_trynow(rend_query
->onion_address
);
564 /** Cancel all rendezvous descriptor fetches currently in progress.
567 rend_client_cancel_descriptor_fetches(void)
569 smartlist_t
*connection_array
= get_connection_array();
571 SMARTLIST_FOREACH_BEGIN(connection_array
, connection_t
*, conn
) {
572 if (conn
->type
== CONN_TYPE_DIR
&&
573 (conn
->purpose
== DIR_PURPOSE_FETCH_RENDDESC
||
574 conn
->purpose
== DIR_PURPOSE_FETCH_RENDDESC_V2
)) {
575 /* It's a rendezvous descriptor fetch in progress -- cancel it
576 * by marking the connection for close.
578 * Even if this connection has already reached EOF, this is
579 * enough to make sure that if the descriptor hasn't been
580 * processed yet, it won't be. See the end of
581 * connection_handle_read; connection_reached_eof (indirectly)
582 * processes whatever response the connection received. */
584 const rend_data_t
*rd
= (TO_DIR_CONN(conn
))->rend_data
;
586 log_warn(LD_BUG
| LD_REND
,
587 "Marking for close dir conn fetching rendezvous "
588 "descriptor for unknown service!");
590 log_debug(LD_REND
, "Marking for close dir conn fetching "
591 "rendezvous descriptor for service %s",
592 safe_str(rd
->onion_address
));
594 connection_mark_for_close(conn
);
596 } SMARTLIST_FOREACH_END(conn
);
599 /** Remove failed_intro from ent. If ent now has no intro points, or
600 * service is unrecognized, then launch a new renddesc fetch.
603 * Return -1 if error, 0 if no intro points remain or service
604 * unrecognized, 1 if recognized and some intro points remain.
607 rend_client_remove_intro_point(extend_info_t
*failed_intro
,
608 const rend_data_t
*rend_query
)
611 rend_cache_entry_t
*ent
;
614 r
= rend_cache_lookup_entry(rend_query
->onion_address
, -1, &ent
);
616 log_warn(LD_BUG
, "Malformed service ID %s.",
617 escaped_safe_str_client(rend_query
->onion_address
));
621 log_info(LD_REND
, "Unknown service %s. Re-fetching descriptor.",
622 escaped_safe_str_client(rend_query
->onion_address
));
623 rend_client_refetch_v2_renddesc(rend_query
);
627 for (i
= 0; i
< smartlist_len(ent
->parsed
->intro_nodes
); i
++) {
628 rend_intro_point_t
*intro
= smartlist_get(ent
->parsed
->intro_nodes
, i
);
629 if (!memcmp(failed_intro
->identity_digest
,
630 intro
->extend_info
->identity_digest
, DIGEST_LEN
)) {
631 rend_intro_point_free(intro
);
632 smartlist_del(ent
->parsed
->intro_nodes
, i
);
637 if (! rend_client_any_intro_points_usable(ent
)) {
639 "No more intro points remain for %s. Re-fetching descriptor.",
640 escaped_safe_str_client(rend_query
->onion_address
));
641 rend_client_refetch_v2_renddesc(rend_query
);
643 /* move all pending streams back to renddesc_wait */
644 while ((conn
= connection_get_by_type_state_rendquery(CONN_TYPE_AP
,
645 AP_CONN_STATE_CIRCUIT_WAIT
,
646 rend_query
->onion_address
))) {
647 conn
->state
= AP_CONN_STATE_RENDDESC_WAIT
;
652 log_info(LD_REND
,"%d options left for %s.",
653 smartlist_len(ent
->parsed
->intro_nodes
),
654 escaped_safe_str_client(rend_query
->onion_address
));
658 /** Called when we receive a RENDEZVOUS_ESTABLISHED cell; changes the state of
659 * the circuit to C_REND_READY.
662 rend_client_rendezvous_acked(origin_circuit_t
*circ
, const uint8_t *request
,
667 /* we just got an ack for our establish-rendezvous. switch purposes. */
668 if (circ
->_base
.purpose
!= CIRCUIT_PURPOSE_C_ESTABLISH_REND
) {
669 log_warn(LD_PROTOCOL
,"Got a rendezvous ack when we weren't expecting one. "
671 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_TORPROTOCOL
);
674 log_info(LD_REND
,"Got rendezvous ack. This circuit is now ready for "
676 circ
->_base
.purpose
= CIRCUIT_PURPOSE_C_REND_READY
;
677 /* XXXX023 This is a pretty brute-force approach. It'd be better to
678 * attach only the connections that are waiting on this circuit, rather
679 * than trying to attach them all. See comments bug 743. */
680 /* If we already have the introduction circuit built, make sure we send
681 * the INTRODUCE cell _now_ */
682 connection_ap_attach_pending();
686 /** Bob sent us a rendezvous cell; join the circuits. */
688 rend_client_receive_rendezvous(origin_circuit_t
*circ
, const uint8_t *request
,
692 char keys
[DIGEST_LEN
+CPATH_KEY_MATERIAL_LEN
];
694 if ((circ
->_base
.purpose
!= CIRCUIT_PURPOSE_C_REND_READY
&&
695 circ
->_base
.purpose
!= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
)
696 || !circ
->build_state
->pending_final_cpath
) {
697 log_warn(LD_PROTOCOL
,"Got rendezvous2 cell from hidden service, but not "
698 "expecting it. Closing.");
699 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_TORPROTOCOL
);
703 if (request_len
!= DH_KEY_LEN
+DIGEST_LEN
) {
704 log_warn(LD_PROTOCOL
,"Incorrect length (%d) on RENDEZVOUS2 cell.",
709 log_info(LD_REND
,"Got RENDEZVOUS2 cell from hidden service.");
711 /* first DH_KEY_LEN bytes are g^y from bob. Finish the dh handshake...*/
712 tor_assert(circ
->build_state
);
713 tor_assert(circ
->build_state
->pending_final_cpath
);
714 hop
= circ
->build_state
->pending_final_cpath
;
715 tor_assert(hop
->dh_handshake_state
);
716 if (crypto_dh_compute_secret(LOG_PROTOCOL_WARN
,
717 hop
->dh_handshake_state
, (char*)request
,
719 keys
, DIGEST_LEN
+CPATH_KEY_MATERIAL_LEN
)<0) {
720 log_warn(LD_GENERAL
, "Couldn't complete DH handshake.");
723 /* ... and set up cpath. */
724 if (circuit_init_cpath_crypto(hop
, keys
+DIGEST_LEN
, 0)<0)
727 /* Check whether the digest is right... */
728 if (memcmp(keys
, request
+DH_KEY_LEN
, DIGEST_LEN
)) {
729 log_warn(LD_PROTOCOL
, "Incorrect digest of key material.");
733 crypto_dh_free(hop
->dh_handshake_state
);
734 hop
->dh_handshake_state
= NULL
;
736 /* All is well. Extend the circuit. */
737 circ
->_base
.purpose
= CIRCUIT_PURPOSE_C_REND_JOINED
;
738 hop
->state
= CPATH_STATE_OPEN
;
739 /* set the windows to default. these are the windows
740 * that alice thinks bob has.
742 hop
->package_window
= circuit_initial_package_window();
743 hop
->deliver_window
= CIRCWINDOW_START
;
745 onion_append_to_cpath(&circ
->cpath
, hop
);
746 circ
->build_state
->pending_final_cpath
= NULL
; /* prevent double-free */
747 /* XXXX023 This is a pretty brute-force approach. It'd be better to
748 * attach only the connections that are waiting on this circuit, rather
749 * than trying to attach them all. See comments bug 743. */
750 connection_ap_attach_pending();
751 memset(keys
, 0, sizeof(keys
));
754 memset(keys
, 0, sizeof(keys
));
755 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_TORPROTOCOL
);
759 /** Find all the apconns in state AP_CONN_STATE_RENDDESC_WAIT that are
760 * waiting on <b>query</b>. If there's a working cache entry here with at
761 * least one intro point, move them to the next state. */
763 rend_client_desc_trynow(const char *query
)
765 edge_connection_t
*conn
;
766 rend_cache_entry_t
*entry
;
767 time_t now
= time(NULL
);
769 smartlist_t
*conns
= get_connection_array();
770 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, _conn
) {
771 if (_conn
->type
!= CONN_TYPE_AP
||
772 _conn
->state
!= AP_CONN_STATE_RENDDESC_WAIT
||
773 _conn
->marked_for_close
)
775 conn
= TO_EDGE_CONN(_conn
);
776 if (!conn
->rend_data
)
778 if (rend_cmp_service_ids(query
, conn
->rend_data
->onion_address
))
780 assert_connection_ok(TO_CONN(conn
), now
);
781 if (rend_cache_lookup_entry(conn
->rend_data
->onion_address
, -1,
783 rend_client_any_intro_points_usable(entry
)) {
784 /* either this fetch worked, or it failed but there was a
785 * valid entry from before which we should reuse */
786 log_info(LD_REND
,"Rend desc is usable. Launching circuits.");
787 conn
->_base
.state
= AP_CONN_STATE_CIRCUIT_WAIT
;
789 /* restart their timeout values, so they get a fair shake at
790 * connecting to the hidden service. */
791 conn
->_base
.timestamp_created
= now
;
792 conn
->_base
.timestamp_lastread
= now
;
793 conn
->_base
.timestamp_lastwritten
= now
;
795 if (connection_ap_handshake_attach_circuit(conn
) < 0) {
796 /* it will never work */
797 log_warn(LD_REND
,"Rendezvous attempt failed. Closing.");
798 if (!conn
->_base
.marked_for_close
)
799 connection_mark_unattached_ap(conn
, END_STREAM_REASON_CANT_ATTACH
);
801 } else { /* 404, or fetch didn't get that far */
802 log_notice(LD_REND
,"Closing stream for '%s.onion': hidden service is "
803 "unavailable (try again later).",
804 safe_str_client(query
));
805 connection_mark_unattached_ap(conn
, END_STREAM_REASON_RESOLVEFAILED
);
807 } SMARTLIST_FOREACH_END(_conn
);
810 /** Return a newly allocated extend_info_t* for a randomly chosen introduction
811 * point for the named hidden service. Return NULL if all introduction points
812 * have been tried and failed.
815 rend_client_get_random_intro(const rend_data_t
*rend_query
)
817 extend_info_t
*result
;
818 rend_cache_entry_t
*entry
;
820 if (rend_cache_lookup_entry(rend_query
->onion_address
, -1, &entry
) < 1) {
822 "Query '%s' didn't have valid rend desc in cache. Failing.",
823 safe_str_client(rend_query
->onion_address
));
827 /* See if we can get a node that complies with ExcludeNodes */
828 if ((result
= rend_client_get_random_intro_impl(entry
, 1, 1)))
830 /* If not, and StrictNodes is not set, see if we can return any old node
832 if (!get_options()->StrictNodes
)
833 return rend_client_get_random_intro_impl(entry
, 0, 1);
837 /** As rend_client_get_random_intro, except assume that StrictNodes is set
838 * iff <b>strict</b> is true. If <b>warnings</b> is false, don't complain
839 * to the user when we're out of nodes, even if StrictNodes is true.
841 static extend_info_t
*
842 rend_client_get_random_intro_impl(const rend_cache_entry_t
*entry
,
848 rend_intro_point_t
*intro
;
849 routerinfo_t
*router
;
850 or_options_t
*options
= get_options();
851 smartlist_t
*usable_nodes
;
854 /* We'll keep a separate list of the usable nodes. If this becomes empty,
855 * no nodes are usable. */
856 usable_nodes
= smartlist_create();
857 smartlist_add_all(usable_nodes
, entry
->parsed
->intro_nodes
);
860 if (smartlist_len(usable_nodes
) == 0) {
861 if (n_excluded
&& get_options()->StrictNodes
&& warnings
) {
862 /* We only want to warn if StrictNodes is really set. Otherwise
863 * we're just about to retry anyways.
865 log_warn(LD_REND
, "All introduction points for hidden service are "
866 "at excluded relays, and StrictNodes is set. Skipping.");
868 smartlist_free(usable_nodes
);
872 i
= crypto_rand_int(smartlist_len(usable_nodes
));
873 intro
= smartlist_get(usable_nodes
, i
);
874 /* Do we need to look up the router or is the extend info complete? */
875 if (!intro
->extend_info
->onion_key
) {
876 if (tor_digest_is_zero(intro
->extend_info
->identity_digest
))
877 router
= router_get_by_hexdigest(intro
->extend_info
->nickname
);
879 router
= router_get_by_digest(intro
->extend_info
->identity_digest
);
881 log_info(LD_REND
, "Unknown router with nickname '%s'; trying another.",
882 intro
->extend_info
->nickname
);
883 smartlist_del(usable_nodes
, i
);
886 extend_info_free(intro
->extend_info
);
887 intro
->extend_info
= extend_info_from_router(router
);
889 /* Check if we should refuse to talk to this router. */
890 if (options
->ExcludeNodes
&& strict
&&
891 routerset_contains_extendinfo(options
->ExcludeNodes
,
892 intro
->extend_info
)) {
894 smartlist_del(usable_nodes
, i
);
898 smartlist_free(usable_nodes
);
899 return extend_info_dup(intro
->extend_info
);
902 /** Return true iff any introduction points still listed in <b>entry</b> are
905 rend_client_any_intro_points_usable(const rend_cache_entry_t
*entry
)
907 return rend_client_get_random_intro_impl(
908 entry
, get_options()->StrictNodes
, 0) != NULL
;
911 /** Client-side authorizations for hidden services; map of onion address to
912 * rend_service_authorization_t*. */
913 static strmap_t
*auth_hid_servs
= NULL
;
915 /** Look up the client-side authorization for the hidden service with
916 * <b>onion_address</b>. Return NULL if no authorization is available for
918 rend_service_authorization_t
*
919 rend_client_lookup_service_authorization(const char *onion_address
)
921 tor_assert(onion_address
);
922 if (!auth_hid_servs
) return NULL
;
923 return strmap_get(auth_hid_servs
, onion_address
);
926 /** Helper: Free storage held by rend_service_authorization_t. */
928 rend_service_authorization_free(rend_service_authorization_t
*auth
)
933 /** Helper for strmap_free. */
935 rend_service_authorization_strmap_item_free(void *service_auth
)
937 rend_service_authorization_free(service_auth
);
940 /** Release all the storage held in auth_hid_servs.
943 rend_service_authorization_free_all(void)
945 if (!auth_hid_servs
) {
948 strmap_free(auth_hid_servs
, rend_service_authorization_strmap_item_free
);
949 auth_hid_servs
= NULL
;
952 /** Parse <b>config_line</b> as a client-side authorization for a hidden
953 * service and add it to the local map of hidden service authorizations.
954 * Return 0 for success and -1 for failure. */
956 rend_parse_service_authorization(or_options_t
*options
, int validate_only
)
960 strmap_t
*parsed
= strmap_new();
961 smartlist_t
*sl
= smartlist_create();
962 rend_service_authorization_t
*auth
= NULL
;
964 for (line
= options
->HidServAuth
; line
; line
= line
->next
) {
965 char *onion_address
, *descriptor_cookie
;
966 char descriptor_cookie_tmp
[REND_DESC_COOKIE_LEN
+2];
967 char descriptor_cookie_base64ext
[REND_DESC_COOKIE_LEN_BASE64
+2+1];
968 int auth_type_val
= 0;
970 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
););
972 smartlist_split_string(sl
, line
->value
, " ",
973 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 3);
974 if (smartlist_len(sl
) < 2) {
975 log_warn(LD_CONFIG
, "Configuration line does not consist of "
976 "\"onion-address authorization-cookie [service-name]\": "
977 "'%s'", line
->value
);
980 auth
= tor_malloc_zero(sizeof(rend_service_authorization_t
));
981 /* Parse onion address. */
982 onion_address
= smartlist_get(sl
, 0);
983 if (strlen(onion_address
) != REND_SERVICE_ADDRESS_LEN
||
984 strcmpend(onion_address
, ".onion")) {
985 log_warn(LD_CONFIG
, "Onion address has wrong format: '%s'",
989 strlcpy(auth
->onion_address
, onion_address
, REND_SERVICE_ID_LEN_BASE32
+1);
990 if (!rend_valid_service_id(auth
->onion_address
)) {
991 log_warn(LD_CONFIG
, "Onion address has wrong format: '%s'",
995 /* Parse descriptor cookie. */
996 descriptor_cookie
= smartlist_get(sl
, 1);
997 if (strlen(descriptor_cookie
) != REND_DESC_COOKIE_LEN_BASE64
) {
998 log_warn(LD_CONFIG
, "Authorization cookie has wrong length: '%s'",
1002 /* Add trailing zero bytes (AA) to make base64-decoding happy. */
1003 tor_snprintf(descriptor_cookie_base64ext
,
1004 REND_DESC_COOKIE_LEN_BASE64
+2+1,
1005 "%sAA", descriptor_cookie
);
1006 if (base64_decode(descriptor_cookie_tmp
, sizeof(descriptor_cookie_tmp
),
1007 descriptor_cookie_base64ext
,
1008 strlen(descriptor_cookie_base64ext
)) < 0) {
1009 log_warn(LD_CONFIG
, "Decoding authorization cookie failed: '%s'",
1013 auth_type_val
= (descriptor_cookie_tmp
[16] >> 4) + 1;
1014 if (auth_type_val
< 1 || auth_type_val
> 2) {
1015 log_warn(LD_CONFIG
, "Authorization cookie has unknown authorization "
1019 auth
->auth_type
= auth_type_val
== 1 ? REND_BASIC_AUTH
: REND_STEALTH_AUTH
;
1020 memcpy(auth
->descriptor_cookie
, descriptor_cookie_tmp
,
1021 REND_DESC_COOKIE_LEN
);
1022 if (strmap_get(parsed
, auth
->onion_address
)) {
1023 log_warn(LD_CONFIG
, "Duplicate authorization for the same hidden "
1027 strmap_set(parsed
, auth
->onion_address
, auth
);
1035 rend_service_authorization_free(auth
);
1036 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
););
1038 if (!validate_only
&& res
== 0) {
1039 rend_service_authorization_free_all();
1040 auth_hid_servs
= parsed
;
1042 strmap_free(parsed
, rend_service_authorization_strmap_item_free
);