1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2009, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
7 * \brief Client code to access location-hidden services.
12 /** Called when we've established a circuit to an introduction point:
13 * send the introduction request. */
15 rend_client_introcirc_has_opened(origin_circuit_t
*circ
)
17 tor_assert(circ
->_base
.purpose
== CIRCUIT_PURPOSE_C_INTRODUCING
);
18 tor_assert(circ
->cpath
);
20 log_info(LD_REND
,"introcirc is open");
21 connection_ap_attach_pending();
24 /** Send the establish-rendezvous cell along a rendezvous circuit. if
25 * it fails, mark the circ for close and return -1. else return 0.
28 rend_client_send_establish_rendezvous(origin_circuit_t
*circ
)
30 tor_assert(circ
->_base
.purpose
== CIRCUIT_PURPOSE_C_ESTABLISH_REND
);
31 tor_assert(circ
->rend_data
);
32 log_info(LD_REND
, "Sending an ESTABLISH_RENDEZVOUS cell");
34 if (crypto_rand(circ
->rend_data
->rend_cookie
, REND_COOKIE_LEN
) < 0) {
35 log_warn(LD_BUG
, "Internal error: Couldn't produce random cookie.");
36 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_INTERNAL
);
39 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ
),
40 RELAY_COMMAND_ESTABLISH_RENDEZVOUS
,
41 circ
->rend_data
->rend_cookie
,
43 circ
->cpath
->prev
)<0) {
44 /* circ is already marked for close */
45 log_warn(LD_GENERAL
, "Couldn't send ESTABLISH_RENDEZVOUS cell");
52 /** Called when we're trying to connect an ap conn; sends an INTRODUCE1 cell
53 * down introcirc if possible.
56 rend_client_send_introduction(origin_circuit_t
*introcirc
,
57 origin_circuit_t
*rendcirc
)
61 char payload
[RELAY_PAYLOAD_SIZE
];
62 char tmp
[RELAY_PAYLOAD_SIZE
];
63 rend_cache_entry_t
*entry
;
66 crypto_pk_env_t
*intro_key
; /* either Bob's public key or an intro key. */
68 tor_assert(introcirc
->_base
.purpose
== CIRCUIT_PURPOSE_C_INTRODUCING
);
69 tor_assert(rendcirc
->_base
.purpose
== CIRCUIT_PURPOSE_C_REND_READY
);
70 tor_assert(introcirc
->rend_data
);
71 tor_assert(rendcirc
->rend_data
);
72 tor_assert(!rend_cmp_service_ids(introcirc
->rend_data
->onion_address
,
73 rendcirc
->rend_data
->onion_address
));
75 if (rend_cache_lookup_entry(introcirc
->rend_data
->onion_address
, -1,
78 "query %s didn't have valid rend desc in cache. Failing.",
79 escaped_safe_str(introcirc
->rend_data
->onion_address
));
83 /* first 20 bytes of payload are the hash of Bob's pk */
84 if (entry
->parsed
->version
== 0) { /* un-versioned descriptor */
85 intro_key
= entry
->parsed
->pk
;
86 } else { /* versioned descriptor */
88 SMARTLIST_FOREACH(entry
->parsed
->intro_nodes
, rend_intro_point_t
*,
90 if (!memcmp(introcirc
->build_state
->chosen_exit
->identity_digest
,
91 intro
->extend_info
->identity_digest
, DIGEST_LEN
)) {
92 intro_key
= intro
->intro_key
;
97 if (rend_cache_lookup_entry(introcirc
->rend_data
->onion_address
,
99 log_warn(LD_BUG
, "We have both a v0 and a v2 rend desc for this "
100 "service. The v2 desc doesn't contain the introduction "
101 "point (and key) to send an INTRODUCE1/2 cell to this "
102 "introduction point. Assuming the introduction point "
103 "is for v0 rend clients and using the service key "
104 "from the v0 desc instead. (This is probably a bug, "
105 "because we shouldn't even have both a v0 and a v2 "
106 "descriptor for the same service.)");
107 /* See flyspray task 1024. */
108 intro_key
= entry
->parsed
->pk
;
110 log_warn(LD_BUG
, "Internal error: could not find intro key; we "
111 "only have a v2 rend desc with %d intro points.",
112 smartlist_len(entry
->parsed
->intro_nodes
));
117 if (crypto_pk_get_digest(intro_key
, payload
)<0) {
118 log_warn(LD_BUG
, "Internal error: couldn't hash public key.");
122 /* Initialize the pending_final_cpath and start the DH handshake. */
123 cpath
= rendcirc
->build_state
->pending_final_cpath
;
125 cpath
= rendcirc
->build_state
->pending_final_cpath
=
126 tor_malloc_zero(sizeof(crypt_path_t
));
127 cpath
->magic
= CRYPT_PATH_MAGIC
;
128 if (!(cpath
->dh_handshake_state
= crypto_dh_new())) {
129 log_warn(LD_BUG
, "Internal error: couldn't allocate DH.");
132 if (crypto_dh_generate_public(cpath
->dh_handshake_state
)<0) {
133 log_warn(LD_BUG
, "Internal error: couldn't generate g^x.");
138 /* If version is 3, write (optional) auth data and timestamp. */
139 if (entry
->parsed
->protocols
& (1<<3)) {
140 tmp
[0] = 3; /* version 3 of the cell format */
141 tmp
[1] = (uint8_t)introcirc
->rend_data
->auth_type
; /* auth type, if any */
143 if (introcirc
->rend_data
->auth_type
!= REND_NO_AUTH
) {
144 set_uint16(tmp
+2, htons(REND_DESC_COOKIE_LEN
));
145 memcpy(tmp
+4, introcirc
->rend_data
->descriptor_cookie
,
146 REND_DESC_COOKIE_LEN
);
147 v3_shift
+= 2+REND_DESC_COOKIE_LEN
;
149 set_uint32(tmp
+v3_shift
+1, htonl((uint32_t)time(NULL
)));
151 } /* if version 2 only write version number */
152 else if (entry
->parsed
->protocols
& (1<<2)) {
153 tmp
[0] = 2; /* version 2 of the cell format */
156 /* write the remaining items into tmp */
157 if (entry
->parsed
->protocols
& (1<<3) || entry
->parsed
->protocols
& (1<<2)) {
158 /* version 2 format */
159 extend_info_t
*extend_info
= rendcirc
->build_state
->chosen_exit
;
162 set_uint32(tmp
+v3_shift
+1, tor_addr_to_ipv4h(&extend_info
->addr
));
163 set_uint16(tmp
+v3_shift
+5, htons(extend_info
->port
));
164 memcpy(tmp
+v3_shift
+7, extend_info
->identity_digest
, DIGEST_LEN
);
165 klen
= crypto_pk_asn1_encode(extend_info
->onion_key
,
166 tmp
+v3_shift
+7+DIGEST_LEN
+2,
167 sizeof(tmp
)-(v3_shift
+7+DIGEST_LEN
+2));
168 set_uint16(tmp
+v3_shift
+7+DIGEST_LEN
, htons(klen
));
169 memcpy(tmp
+v3_shift
+7+DIGEST_LEN
+2+klen
, rendcirc
->rend_data
->rend_cookie
,
171 dh_offset
= v3_shift
+7+DIGEST_LEN
+2+klen
+REND_COOKIE_LEN
;
174 strncpy(tmp
, rendcirc
->build_state
->chosen_exit
->nickname
,
175 (MAX_NICKNAME_LEN
+1)); /* nul pads */
176 memcpy(tmp
+MAX_NICKNAME_LEN
+1, rendcirc
->rend_data
->rend_cookie
,
178 dh_offset
= MAX_NICKNAME_LEN
+1+REND_COOKIE_LEN
;
181 if (crypto_dh_get_public(cpath
->dh_handshake_state
, tmp
+dh_offset
,
183 log_warn(LD_BUG
, "Internal error: couldn't extract g^x.");
187 note_crypto_pk_op(REND_CLIENT
);
188 /*XXX maybe give crypto_pk_public_hybrid_encrypt a max_len arg,
189 * to avoid buffer overflows? */
190 r
= crypto_pk_public_hybrid_encrypt(intro_key
, payload
+DIGEST_LEN
,
192 (int)(dh_offset
+DH_KEY_LEN
),
193 PK_PKCS1_OAEP_PADDING
, 0);
195 log_warn(LD_BUG
,"Internal error: hybrid pk encrypt failed.");
199 payload_len
= DIGEST_LEN
+ r
;
200 tor_assert(payload_len
<= RELAY_PAYLOAD_SIZE
); /* we overran something */
202 log_info(LD_REND
, "Sending an INTRODUCE1 cell");
203 if (relay_send_command_from_edge(0, TO_CIRCUIT(introcirc
),
204 RELAY_COMMAND_INTRODUCE1
,
205 payload
, payload_len
,
206 introcirc
->cpath
->prev
)<0) {
207 /* introcirc is already marked for close. leave rendcirc alone. */
208 log_warn(LD_BUG
, "Couldn't send INTRODUCE1 cell");
212 /* Now, we wait for an ACK or NAK on this circuit. */
213 introcirc
->_base
.purpose
= CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
;
217 circuit_mark_for_close(TO_CIRCUIT(introcirc
), END_CIRC_REASON_INTERNAL
);
218 circuit_mark_for_close(TO_CIRCUIT(rendcirc
), END_CIRC_REASON_INTERNAL
);
222 /** Called when a rendezvous circuit is open; sends a establish
223 * rendezvous circuit as appropriate. */
225 rend_client_rendcirc_has_opened(origin_circuit_t
*circ
)
227 tor_assert(circ
->_base
.purpose
== CIRCUIT_PURPOSE_C_ESTABLISH_REND
);
229 log_info(LD_REND
,"rendcirc is open");
231 /* generate a rendezvous cookie, store it in circ */
232 if (rend_client_send_establish_rendezvous(circ
) < 0) {
237 /** Called when get an ACK or a NAK for a REND_INTRODUCE1 cell.
240 rend_client_introduction_acked(origin_circuit_t
*circ
,
241 const char *request
, size_t request_len
)
243 origin_circuit_t
*rendcirc
;
244 (void) request
; // XXXX Use this.
246 if (circ
->_base
.purpose
!= CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
) {
247 log_warn(LD_PROTOCOL
,
248 "Received REND_INTRODUCE_ACK on unexpected circuit %d.",
249 circ
->_base
.n_circ_id
);
250 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_TORPROTOCOL
);
254 tor_assert(circ
->build_state
->chosen_exit
);
255 tor_assert(circ
->rend_data
);
257 if (request_len
== 0) {
258 /* It's an ACK; the introduction point relayed our introduction request. */
259 /* Locate the rend circ which is waiting to hear about this ack,
262 log_info(LD_REND
,"Received ack. Telling rend circ...");
263 rendcirc
= circuit_get_by_rend_query_and_purpose(
264 circ
->rend_data
->onion_address
, CIRCUIT_PURPOSE_C_REND_READY
);
265 if (rendcirc
) { /* remember the ack */
266 rendcirc
->_base
.purpose
= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
;
268 log_info(LD_REND
,"...Found no rend circ. Dropping on the floor.");
270 /* close the circuit: we won't need it anymore. */
271 circ
->_base
.purpose
= CIRCUIT_PURPOSE_C_INTRODUCE_ACKED
;
272 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_FINISHED
);
274 /* It's a NAK; the introduction point didn't relay our request. */
275 circ
->_base
.purpose
= CIRCUIT_PURPOSE_C_INTRODUCING
;
276 /* Remove this intro point from the set of viable introduction
277 * points. If any remain, extend to a new one and try again.
278 * If none remain, refetch the service descriptor.
280 if (rend_client_remove_intro_point(circ
->build_state
->chosen_exit
,
281 circ
->rend_data
) > 0) {
282 /* There are introduction points left. Re-extend the circuit to
283 * another intro point and try again. */
284 extend_info_t
*extend_info
;
286 extend_info
= rend_client_get_random_intro(circ
->rend_data
);
288 log_warn(LD_REND
, "No introduction points left for %s. Closing.",
289 escaped_safe_str(circ
->rend_data
->onion_address
));
290 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_INTERNAL
);
293 if (circ
->remaining_relay_early_cells
) {
295 "Got nack for %s from %s. Re-extending circ %d, "
297 escaped_safe_str(circ
->rend_data
->onion_address
),
298 circ
->build_state
->chosen_exit
->nickname
,
299 circ
->_base
.n_circ_id
, extend_info
->nickname
);
300 result
= circuit_extend_to_new_exit(circ
, extend_info
);
303 "Got nack for %s from %s. Building a new introduction "
304 "circuit, this time to %s.",
305 escaped_safe_str(circ
->rend_data
->onion_address
),
306 circ
->build_state
->chosen_exit
->nickname
,
307 extend_info
->nickname
);
308 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_FINISHED
);
309 if (!circuit_launch_by_extend_info(CIRCUIT_PURPOSE_C_INTRODUCING
,
311 CIRCLAUNCH_IS_INTERNAL
)) {
312 log_warn(LD_REND
, "Building introduction circuit failed.");
318 extend_info_free(extend_info
);
325 /** The period for which a hidden service directory cannot be queried for
326 * the same descriptor ID again. */
327 #define REND_HID_SERV_DIR_REQUERY_PERIOD (15 * 60)
329 /** Contains the last request times to hidden service directories for
330 * certain queries; keys are strings consisting of base32-encoded
331 * hidden service directory identities and base32-encoded descriptor IDs;
332 * values are pointers to timestamps of the last requests. */
333 static strmap_t
*last_hid_serv_requests
= NULL
;
335 /** Look up the last request time to hidden service directory <b>hs_dir</b>
336 * for descriptor ID <b>desc_id_base32</b>. If <b>set</b> is non-zero,
337 * assign the current time <b>now</b> and return that. Otherwise, return
338 * the most recent request time, or 0 if no such request has been sent
341 lookup_last_hid_serv_request(routerstatus_t
*hs_dir
,
342 const char *desc_id_base32
, time_t now
, int set
)
344 char hsdir_id_base32
[REND_DESC_ID_V2_LEN_BASE32
+ 1];
345 char hsdir_desc_comb_id
[2 * REND_DESC_ID_V2_LEN_BASE32
+ 1];
346 time_t *last_request_ptr
;
347 base32_encode(hsdir_id_base32
, sizeof(hsdir_id_base32
),
348 hs_dir
->identity_digest
, DIGEST_LEN
);
349 tor_snprintf(hsdir_desc_comb_id
, sizeof(hsdir_desc_comb_id
), "%s%s",
350 hsdir_id_base32
, desc_id_base32
);
352 last_request_ptr
= tor_malloc_zero(sizeof(time_t *));
353 *last_request_ptr
= now
;
354 strmap_set(last_hid_serv_requests
, hsdir_desc_comb_id
, last_request_ptr
);
356 last_request_ptr
= strmap_get_lc(last_hid_serv_requests
,
358 return (last_request_ptr
) ? *last_request_ptr
: 0;
361 /** Clean the history of request times to hidden service directories, so that
362 * it does not contain requests older than REND_HID_SERV_DIR_REQUERY_PERIOD
363 * seconds any more. */
365 directory_clean_last_hid_serv_requests(void)
368 time_t cutoff
= time(NULL
) - REND_HID_SERV_DIR_REQUERY_PERIOD
;
369 if (!last_hid_serv_requests
)
370 last_hid_serv_requests
= strmap_new();
371 for (iter
= strmap_iter_init(last_hid_serv_requests
);
372 !strmap_iter_done(iter
); ) {
376 strmap_iter_get(iter
, &key
, &val
);
377 ent
= (time_t *) val
;
379 iter
= strmap_iter_next_rmv(last_hid_serv_requests
, iter
);
382 iter
= strmap_iter_next(last_hid_serv_requests
, iter
);
387 /** Determine the responsible hidden service directories for <b>desc_id</b>
388 * and fetch the descriptor belonging to that ID from one of them. Only
389 * send a request to hidden service directories that we did not try within
390 * the last REND_HID_SERV_DIR_REQUERY_PERIOD seconds; on success, return 1,
391 * in the case that no hidden service directory is left to ask for the
392 * descriptor, return 0, and in case of a failure -1. <b>query</b> is only
393 * passed for pretty log statements. */
395 directory_get_from_hs_dir(const char *desc_id
, const rend_data_t
*rend_query
)
397 smartlist_t
*responsible_dirs
= smartlist_create();
398 routerstatus_t
*hs_dir
;
399 char desc_id_base32
[REND_DESC_ID_V2_LEN_BASE32
+ 1];
400 time_t now
= time(NULL
);
401 char descriptor_cookie_base64
[3*REND_DESC_COOKIE_LEN_BASE64
];
403 tor_assert(rend_query
);
404 /* Determine responsible dirs. Even if we can't get all we want,
405 * work with the ones we have. If it's empty, we'll notice below. */
406 (int) hid_serv_get_responsible_directories(responsible_dirs
, desc_id
);
408 base32_encode(desc_id_base32
, sizeof(desc_id_base32
),
409 desc_id
, DIGEST_LEN
);
411 /* Only select those hidden service directories to which we did not send
412 * a request recently and for which we have a router descriptor here. */
413 directory_clean_last_hid_serv_requests(); /* Clean request history first. */
415 SMARTLIST_FOREACH(responsible_dirs
, routerstatus_t
*, dir
, {
416 if (lookup_last_hid_serv_request(dir
, desc_id_base32
, 0, 0) +
417 REND_HID_SERV_DIR_REQUERY_PERIOD
>= now
||
418 !router_get_by_digest(dir
->identity_digest
))
419 SMARTLIST_DEL_CURRENT(responsible_dirs
, dir
);
422 hs_dir
= smartlist_choose(responsible_dirs
);
423 smartlist_free(responsible_dirs
);
425 log_info(LD_REND
, "Could not pick one of the responsible hidden "
426 "service directories, because we requested them all "
427 "recently without success.");
431 /* Remember, that we are requesting a descriptor from this hidden service
433 lookup_last_hid_serv_request(hs_dir
, desc_id_base32
, now
, 1);
435 /* Encode descriptor cookie for logging purposes. */
436 if (rend_query
->auth_type
!= REND_NO_AUTH
) {
437 if (base64_encode(descriptor_cookie_base64
,
438 sizeof(descriptor_cookie_base64
),
439 rend_query
->descriptor_cookie
, REND_DESC_COOKIE_LEN
)<0) {
440 log_warn(LD_BUG
, "Could not base64-encode descriptor cookie.");
443 /* Remove == signs and newline. */
444 descriptor_cookie_base64
[strlen(descriptor_cookie_base64
)-3] = '\0';
446 strlcpy(descriptor_cookie_base64
, "(none)",
447 sizeof(descriptor_cookie_base64
));
450 /* Send fetch request. (Pass query and possibly descriptor cookie so that
451 * they can be written to the directory connection and be referred to when
452 * the response arrives. */
453 directory_initiate_command_routerstatus_rend(hs_dir
,
454 DIR_PURPOSE_FETCH_RENDDESC_V2
,
455 ROUTER_PURPOSE_GENERAL
,
456 1, desc_id_base32
, NULL
, 0, 0,
458 log_info(LD_REND
, "Sending fetch request for v2 descriptor for "
459 "service '%s' with descriptor ID '%s', auth type %d, "
460 "and descriptor cookie '%s' to hidden service "
461 "directory '%s' on port %d.",
462 rend_query
->onion_address
, desc_id_base32
,
463 rend_query
->auth_type
,
464 (rend_query
->auth_type
== REND_NO_AUTH
? "[none]" :
465 escaped_safe_str(descriptor_cookie_base64
)),
466 hs_dir
->nickname
, hs_dir
->dir_port
);
470 /** If we are not currently fetching a rendezvous service descriptor
471 * for the service ID <b>query</b>, start a directory connection to fetch a
475 rend_client_refetch_renddesc(const char *query
)
477 if (!get_options()->FetchHidServDescriptors
)
479 log_info(LD_REND
, "Fetching rendezvous descriptor for service %s",
480 escaped_safe_str(query
));
481 if (connection_get_by_type_state_rendquery(CONN_TYPE_DIR
, 0, query
, 0)) {
482 log_info(LD_REND
,"Would fetch a new renddesc here (for %s), but one is "
483 "already in progress.", escaped_safe_str(query
));
485 /* not one already; initiate a dir rend desc lookup */
486 directory_get_from_dirserver(DIR_PURPOSE_FETCH_RENDDESC
,
487 ROUTER_PURPOSE_GENERAL
, query
,
488 PDS_RETRY_IF_NO_SERVERS
);
492 /** Start a connection to a hidden service directory to fetch a v2
493 * rendezvous service descriptor for the base32-encoded service ID
497 rend_client_refetch_v2_renddesc(const rend_data_t
*rend_query
)
499 char descriptor_id
[DIGEST_LEN
];
500 int replicas_left_to_try
[REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS
];
501 int i
, tries_left
, r
;
502 rend_cache_entry_t
*e
= NULL
;
503 time_t now
= time(NULL
);
504 tor_assert(rend_query
);
505 /* Are we configured to fetch descriptors? */
506 if (!get_options()->FetchHidServDescriptors
) {
507 log_warn(LD_REND
, "We received an onion address for a v2 rendezvous "
508 "service descriptor, but are not fetching service descriptors.");
511 /* Before fetching, check if we already have the descriptor here. */
512 r
= rend_cache_lookup_entry(rend_query
->onion_address
, -1, &e
);
513 if (r
> 0 && now
- e
->received
< NUM_SECONDS_BEFORE_HS_REFETCH
) {
514 log_info(LD_REND
, "We would fetch a v2 rendezvous descriptor, but we "
515 "already have a fresh copy of that descriptor here. "
519 log_debug(LD_REND
, "Fetching v2 rendezvous descriptor for service %s",
520 safe_str(rend_query
->onion_address
));
521 /* Randomly iterate over the replicas until a descriptor can be fetched
522 * from one of the consecutive nodes, or no options are left. */
523 tries_left
= REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS
;
524 for (i
= 0; i
< REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS
; i
++)
525 replicas_left_to_try
[i
] = i
;
526 while (tries_left
> 0) {
527 int rand
= crypto_rand_int(tries_left
);
528 int chosen_replica
= replicas_left_to_try
[rand
];
529 replicas_left_to_try
[rand
] = replicas_left_to_try
[--tries_left
];
531 if (rend_compute_v2_desc_id(descriptor_id
, rend_query
->onion_address
,
532 rend_query
->auth_type
== REND_STEALTH_AUTH
?
533 rend_query
->descriptor_cookie
: NULL
,
534 time(NULL
), chosen_replica
) < 0) {
535 log_warn(LD_REND
, "Internal error: Computing v2 rendezvous "
536 "descriptor ID did not succeed.");
539 if (directory_get_from_hs_dir(descriptor_id
, rend_query
) != 0)
540 return; /* either success or failure, but we're done */
542 /* If we come here, there are no hidden service directories left. */
543 log_info(LD_REND
, "Could not pick one of the responsible hidden "
544 "service directories to fetch descriptors, because "
545 "we already tried them all unsuccessfully.");
546 /* Close pending connections (unless a v0 request is still going on). */
547 rend_client_desc_trynow(rend_query
->onion_address
, 2);
551 /** Remove failed_intro from ent. If ent now has no intro points, or
552 * service is unrecognized, then launch a new renddesc fetch.
554 * Return -1 if error, 0 if no intro points remain or service
555 * unrecognized, 1 if recognized and some intro points remain.
558 rend_client_remove_intro_point(extend_info_t
*failed_intro
,
559 const rend_data_t
*rend_query
)
562 rend_cache_entry_t
*ent
;
565 r
= rend_cache_lookup_entry(rend_query
->onion_address
, -1, &ent
);
567 log_warn(LD_BUG
, "Malformed service ID %s.",
568 escaped_safe_str(rend_query
->onion_address
));
572 log_info(LD_REND
, "Unknown service %s. Re-fetching descriptor.",
573 escaped_safe_str(rend_query
->onion_address
));
574 /* Fetch both, v0 and v2 rend descriptors in parallel. Use whichever
575 * arrives first. Exception: When using client authorization, only
576 * fetch v2 descriptors.*/
577 rend_client_refetch_v2_renddesc(rend_query
);
578 if (rend_query
->auth_type
== REND_NO_AUTH
)
579 rend_client_refetch_renddesc(rend_query
->onion_address
);
583 for (i
= 0; i
< smartlist_len(ent
->parsed
->intro_nodes
); i
++) {
584 rend_intro_point_t
*intro
= smartlist_get(ent
->parsed
->intro_nodes
, i
);
585 if (!memcmp(failed_intro
->identity_digest
,
586 intro
->extend_info
->identity_digest
, DIGEST_LEN
)) {
587 rend_intro_point_free(intro
);
588 smartlist_del(ent
->parsed
->intro_nodes
, i
);
593 if (smartlist_len(ent
->parsed
->intro_nodes
) == 0) {
595 "No more intro points remain for %s. Re-fetching descriptor.",
596 escaped_safe_str(rend_query
->onion_address
));
597 /* Fetch both, v0 and v2 rend descriptors in parallel. Use whichever
598 * arrives first. Exception: When using client authorization, only
599 * fetch v2 descriptors.*/
600 rend_client_refetch_v2_renddesc(rend_query
);
601 if (rend_query
->auth_type
== REND_NO_AUTH
)
602 rend_client_refetch_renddesc(rend_query
->onion_address
);
604 /* move all pending streams back to renddesc_wait */
605 while ((conn
= connection_get_by_type_state_rendquery(CONN_TYPE_AP
,
606 AP_CONN_STATE_CIRCUIT_WAIT
,
607 rend_query
->onion_address
, -1))) {
608 conn
->state
= AP_CONN_STATE_RENDDESC_WAIT
;
613 log_info(LD_REND
,"%d options left for %s.",
614 smartlist_len(ent
->parsed
->intro_nodes
),
615 escaped_safe_str(rend_query
->onion_address
));
619 /** Called when we receive a RENDEZVOUS_ESTABLISHED cell; changes the state of
620 * the circuit to C_REND_READY.
623 rend_client_rendezvous_acked(origin_circuit_t
*circ
, const char *request
,
628 /* we just got an ack for our establish-rendezvous. switch purposes. */
629 if (circ
->_base
.purpose
!= CIRCUIT_PURPOSE_C_ESTABLISH_REND
) {
630 log_warn(LD_PROTOCOL
,"Got a rendezvous ack when we weren't expecting one. "
632 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_TORPROTOCOL
);
635 log_info(LD_REND
,"Got rendezvous ack. This circuit is now ready for "
637 circ
->_base
.purpose
= CIRCUIT_PURPOSE_C_REND_READY
;
638 /* XXXX022 This is a pretty brute-force approach. It'd be better to
639 * attach only the connections that are waiting on this circuit, rather
640 * than trying to attach them all. See comments bug 743. */
641 /* If we already have the introduction circuit built, make sure we send
642 * the INTRODUCE cell _now_ */
643 connection_ap_attach_pending();
647 /** Bob sent us a rendezvous cell; join the circuits. */
649 rend_client_receive_rendezvous(origin_circuit_t
*circ
, const char *request
,
653 char keys
[DIGEST_LEN
+CPATH_KEY_MATERIAL_LEN
];
655 if ((circ
->_base
.purpose
!= CIRCUIT_PURPOSE_C_REND_READY
&&
656 circ
->_base
.purpose
!= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
)
657 || !circ
->build_state
->pending_final_cpath
) {
658 log_warn(LD_PROTOCOL
,"Got rendezvous2 cell from hidden service, but not "
659 "expecting it. Closing.");
660 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_TORPROTOCOL
);
664 if (request_len
!= DH_KEY_LEN
+DIGEST_LEN
) {
665 log_warn(LD_PROTOCOL
,"Incorrect length (%d) on RENDEZVOUS2 cell.",
670 log_info(LD_REND
,"Got RENDEZVOUS2 cell from hidden service.");
672 /* first DH_KEY_LEN bytes are g^y from bob. Finish the dh handshake...*/
673 tor_assert(circ
->build_state
);
674 tor_assert(circ
->build_state
->pending_final_cpath
);
675 hop
= circ
->build_state
->pending_final_cpath
;
676 tor_assert(hop
->dh_handshake_state
);
677 if (crypto_dh_compute_secret(hop
->dh_handshake_state
, request
, DH_KEY_LEN
,
678 keys
, DIGEST_LEN
+CPATH_KEY_MATERIAL_LEN
)<0) {
679 log_warn(LD_GENERAL
, "Couldn't complete DH handshake.");
682 /* ... and set up cpath. */
683 if (circuit_init_cpath_crypto(hop
, keys
+DIGEST_LEN
, 0)<0)
686 /* Check whether the digest is right... */
687 if (memcmp(keys
, request
+DH_KEY_LEN
, DIGEST_LEN
)) {
688 log_warn(LD_PROTOCOL
, "Incorrect digest of key material.");
692 crypto_dh_free(hop
->dh_handshake_state
);
693 hop
->dh_handshake_state
= NULL
;
695 /* All is well. Extend the circuit. */
696 circ
->_base
.purpose
= CIRCUIT_PURPOSE_C_REND_JOINED
;
697 hop
->state
= CPATH_STATE_OPEN
;
698 /* set the windows to default. these are the windows
699 * that alice thinks bob has.
701 hop
->package_window
= CIRCWINDOW_START
;
702 hop
->deliver_window
= CIRCWINDOW_START
;
704 onion_append_to_cpath(&circ
->cpath
, hop
);
705 circ
->build_state
->pending_final_cpath
= NULL
; /* prevent double-free */
706 /* XXXX022 This is a pretty brute-force approach. It'd be better to
707 * attach only the connections that are waiting on this circuit, rather
708 * than trying to attach them all. See comments bug 743. */
709 connection_ap_attach_pending();
712 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_TORPROTOCOL
);
716 /** Find all the apconns in state AP_CONN_STATE_RENDDESC_WAIT that
717 * are waiting on query. If there's a working cache entry here
718 * with at least one intro point, move them to the next state. If
719 * <b>rend_version</b> is non-negative, fail connections that have
720 * requested <b>query</b> unless there are still descriptor fetch
721 * requests in progress for other descriptor versions than
722 * <b>rend_version</b>.
725 rend_client_desc_trynow(const char *query
, int rend_version
)
727 edge_connection_t
*conn
;
728 rend_cache_entry_t
*entry
;
729 time_t now
= time(NULL
);
731 smartlist_t
*conns
= get_connection_array();
732 SMARTLIST_FOREACH(conns
, connection_t
*, _conn
,
734 if (_conn
->type
!= CONN_TYPE_AP
||
735 _conn
->state
!= AP_CONN_STATE_RENDDESC_WAIT
||
736 _conn
->marked_for_close
)
738 conn
= TO_EDGE_CONN(_conn
);
739 if (!conn
->rend_data
)
741 if (rend_cmp_service_ids(query
, conn
->rend_data
->onion_address
))
743 assert_connection_ok(TO_CONN(conn
), now
);
744 if (rend_cache_lookup_entry(conn
->rend_data
->onion_address
, -1,
746 smartlist_len(entry
->parsed
->intro_nodes
) > 0) {
747 /* either this fetch worked, or it failed but there was a
748 * valid entry from before which we should reuse */
749 log_info(LD_REND
,"Rend desc is usable. Launching circuits.");
750 conn
->_base
.state
= AP_CONN_STATE_CIRCUIT_WAIT
;
752 /* restart their timeout values, so they get a fair shake at
753 * connecting to the hidden service. */
754 conn
->_base
.timestamp_created
= now
;
755 conn
->_base
.timestamp_lastread
= now
;
756 conn
->_base
.timestamp_lastwritten
= now
;
758 if (connection_ap_handshake_attach_circuit(conn
) < 0) {
759 /* it will never work */
760 log_warn(LD_REND
,"Rendezvous attempt failed. Closing.");
761 if (!conn
->_base
.marked_for_close
)
762 connection_mark_unattached_ap(conn
, END_STREAM_REASON_CANT_ATTACH
);
764 } else { /* 404, or fetch didn't get that far */
765 /* Unless there are requests for another descriptor version pending,
766 * close the connection. */
767 if (rend_version
>= 0 &&
768 !connection_get_by_type_state_rendquery(CONN_TYPE_DIR
, 0, query
,
769 rend_version
== 0 ? 2 : 0)) {
770 log_notice(LD_REND
,"Closing stream for '%s.onion': hidden service is "
771 "unavailable (try again later).", safe_str(query
));
772 connection_mark_unattached_ap(conn
, END_STREAM_REASON_RESOLVEFAILED
);
778 /** Return a newly allocated extend_info_t* for a randomly chosen introduction
779 * point for the named hidden service. Return NULL if all introduction points
780 * have been tried and failed.
783 rend_client_get_random_intro(const rend_data_t
*rend_query
)
786 rend_cache_entry_t
*entry
;
787 rend_intro_point_t
*intro
;
788 routerinfo_t
*router
;
790 if (rend_cache_lookup_entry(rend_query
->onion_address
, -1, &entry
) < 1) {
792 "Query '%s' didn't have valid rend desc in cache. Failing.",
793 safe_str(rend_query
->onion_address
));
798 if (smartlist_len(entry
->parsed
->intro_nodes
) == 0)
801 i
= crypto_rand_int(smartlist_len(entry
->parsed
->intro_nodes
));
802 intro
= smartlist_get(entry
->parsed
->intro_nodes
, i
);
803 /* Do we need to look up the router or is the extend info complete? */
804 if (!intro
->extend_info
->onion_key
) {
805 router
= router_get_by_nickname(intro
->extend_info
->nickname
, 0);
807 log_info(LD_REND
, "Unknown router with nickname '%s'; trying another.",
808 intro
->extend_info
->nickname
);
809 rend_intro_point_free(intro
);
810 smartlist_del(entry
->parsed
->intro_nodes
, i
);
813 extend_info_free(intro
->extend_info
);
814 intro
->extend_info
= extend_info_from_router(router
);
816 return extend_info_dup(intro
->extend_info
);
819 /** Client-side authorizations for hidden services; map of onion address to
820 * rend_service_authorization_t*. */
821 static strmap_t
*auth_hid_servs
= NULL
;
823 /** Look up the client-side authorization for the hidden service with
824 * <b>onion_address</b>. Return NULL if no authorization is available for
826 rend_service_authorization_t
*
827 rend_client_lookup_service_authorization(const char *onion_address
)
829 tor_assert(onion_address
);
830 if (!auth_hid_servs
) return NULL
;
831 return strmap_get(auth_hid_servs
, onion_address
);
834 /** Helper: Free storage held by rend_service_authorization_t. */
836 rend_service_authorization_free(rend_service_authorization_t
*auth
)
841 /** Helper for strmap_free. */
843 rend_service_authorization_strmap_item_free(void *service_auth
)
845 rend_service_authorization_free(service_auth
);
848 /** Release all the storage held in auth_hid_servs.
851 rend_service_authorization_free_all(void)
853 if (!auth_hid_servs
) {
856 strmap_free(auth_hid_servs
, rend_service_authorization_strmap_item_free
);
857 auth_hid_servs
= NULL
;
860 /** Parse <b>config_line</b> as a client-side authorization for a hidden
861 * service and add it to the local map of hidden service authorizations.
862 * Return 0 for success and -1 for failure. */
864 rend_parse_service_authorization(or_options_t
*options
, int validate_only
)
868 strmap_t
*parsed
= strmap_new();
869 smartlist_t
*sl
= smartlist_create();
870 rend_service_authorization_t
*auth
= NULL
;
872 for (line
= options
->HidServAuth
; line
; line
= line
->next
) {
873 char *onion_address
, *descriptor_cookie
;
874 char descriptor_cookie_tmp
[REND_DESC_COOKIE_LEN
+2];
875 char descriptor_cookie_base64ext
[REND_DESC_COOKIE_LEN_BASE64
+2+1];
876 int auth_type_val
= 0;
878 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
););
880 smartlist_split_string(sl
, line
->value
, " ",
881 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 3);
882 if (smartlist_len(sl
) < 2) {
883 log_warn(LD_CONFIG
, "Configuration line does not consist of "
884 "\"onion-address authorization-cookie [service-name]\": "
885 "'%s'", line
->value
);
888 auth
= tor_malloc_zero(sizeof(rend_service_authorization_t
));
889 /* Parse onion address. */
890 onion_address
= smartlist_get(sl
, 0);
891 if (strlen(onion_address
) != REND_SERVICE_ADDRESS_LEN
||
892 strcmpend(onion_address
, ".onion")) {
893 log_warn(LD_CONFIG
, "Onion address has wrong format: '%s'",
897 strlcpy(auth
->onion_address
, onion_address
, REND_SERVICE_ID_LEN_BASE32
+1);
898 if (!rend_valid_service_id(auth
->onion_address
)) {
899 log_warn(LD_CONFIG
, "Onion address has wrong format: '%s'",
903 /* Parse descriptor cookie. */
904 descriptor_cookie
= smartlist_get(sl
, 1);
905 if (strlen(descriptor_cookie
) != REND_DESC_COOKIE_LEN_BASE64
) {
906 log_warn(LD_CONFIG
, "Authorization cookie has wrong length: '%s'",
910 /* Add trailing zero bytes (AA) to make base64-decoding happy. */
911 tor_snprintf(descriptor_cookie_base64ext
,
912 REND_DESC_COOKIE_LEN_BASE64
+2+1,
913 "%sAA", descriptor_cookie
);
914 if (base64_decode(descriptor_cookie_tmp
, sizeof(descriptor_cookie_tmp
),
915 descriptor_cookie_base64ext
,
916 strlen(descriptor_cookie_base64ext
)) < 0) {
917 log_warn(LD_CONFIG
, "Decoding authorization cookie failed: '%s'",
921 auth_type_val
= (descriptor_cookie_tmp
[16] >> 4) + 1;
922 if (auth_type_val
< 1 || auth_type_val
> 2) {
923 log_warn(LD_CONFIG
, "Authorization cookie has unknown authorization "
927 auth
->auth_type
= auth_type_val
== 1 ? REND_BASIC_AUTH
: REND_STEALTH_AUTH
;
928 memcpy(auth
->descriptor_cookie
, descriptor_cookie_tmp
,
929 REND_DESC_COOKIE_LEN
);
930 if (strmap_get(parsed
, auth
->onion_address
)) {
931 log_warn(LD_CONFIG
, "Duplicate authorization for the same hidden "
935 strmap_set(parsed
, auth
->onion_address
, auth
);
944 rend_service_authorization_free(auth
);
945 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
););
947 if (!validate_only
&& res
== 0) {
948 rend_service_authorization_free_all();
949 auth_hid_servs
= parsed
;
951 strmap_free(parsed
, rend_service_authorization_strmap_item_free
);