In routerlist_assert_ok(), check r2 before taking &(r2->cache_info)
[tor.git] / src / or / rendclient.c
blobd42024010d22a728476ed83bb95fb42047720fff
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2013, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
5 /**
6 * \file rendclient.c
7 * \brief Client code to access location-hidden services.
8 **/
10 #include "or.h"
11 #include "circpathbias.h"
12 #include "circuitbuild.h"
13 #include "circuitlist.h"
14 #include "circuituse.h"
15 #include "config.h"
16 #include "connection.h"
17 #include "connection_edge.h"
18 #include "directory.h"
19 #include "main.h"
20 #include "networkstatus.h"
21 #include "nodelist.h"
22 #include "relay.h"
23 #include "rendclient.h"
24 #include "rendcommon.h"
25 #include "rephist.h"
26 #include "router.h"
27 #include "routerlist.h"
28 #include "routerset.h"
29 #include "control.h"
31 static extend_info_t *rend_client_get_random_intro_impl(
32 const rend_cache_entry_t *rend_query,
33 const int strict, const int warnings);
35 /** Purge all potentially remotely-detectable state held in the hidden
36 * service client code. Called on SIGNAL NEWNYM. */
37 void
38 rend_client_purge_state(void)
40 rend_cache_purge();
41 rend_client_cancel_descriptor_fetches();
42 rend_client_purge_last_hid_serv_requests();
45 /** Called when we've established a circuit to an introduction point:
46 * send the introduction request. */
47 void
48 rend_client_introcirc_has_opened(origin_circuit_t *circ)
50 tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
51 tor_assert(circ->cpath);
53 log_info(LD_REND,"introcirc is open");
54 connection_ap_attach_pending();
57 /** Send the establish-rendezvous cell along a rendezvous circuit. if
58 * it fails, mark the circ for close and return -1. else return 0.
60 static int
61 rend_client_send_establish_rendezvous(origin_circuit_t *circ)
63 tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
64 tor_assert(circ->rend_data);
65 log_info(LD_REND, "Sending an ESTABLISH_RENDEZVOUS cell");
67 if (crypto_rand(circ->rend_data->rend_cookie, REND_COOKIE_LEN) < 0) {
68 log_warn(LD_BUG, "Internal error: Couldn't produce random cookie.");
69 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
70 return -1;
73 /* Set timestamp_dirty, because circuit_expire_building expects it,
74 * and the rend cookie also means we've used the circ. */
75 circ->base_.timestamp_dirty = time(NULL);
77 /* We've attempted to use this circuit. Probe it if we fail */
78 pathbias_count_use_attempt(circ);
80 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
81 RELAY_COMMAND_ESTABLISH_RENDEZVOUS,
82 circ->rend_data->rend_cookie,
83 REND_COOKIE_LEN,
84 circ->cpath->prev)<0) {
85 /* circ is already marked for close */
86 log_warn(LD_GENERAL, "Couldn't send ESTABLISH_RENDEZVOUS cell");
87 return -1;
90 return 0;
93 /** Extend the introduction circuit <b>circ</b> to another valid
94 * introduction point for the hidden service it is trying to connect
95 * to, or mark it and launch a new circuit if we can't extend it.
96 * Return 0 on success or possible success. Return -1 and mark the
97 * introduction circuit for close on permanent failure.
99 * On failure, the caller is responsible for marking the associated
100 * rendezvous circuit for close. */
101 static int
102 rend_client_reextend_intro_circuit(origin_circuit_t *circ)
104 extend_info_t *extend_info;
105 int result;
106 extend_info = rend_client_get_random_intro(circ->rend_data);
107 if (!extend_info) {
108 log_warn(LD_REND,
109 "No usable introduction points left for %s. Closing.",
110 safe_str_client(circ->rend_data->onion_address));
111 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
112 return -1;
114 // XXX: should we not re-extend if hs_circ_has_timed_out?
115 if (circ->remaining_relay_early_cells) {
116 log_info(LD_REND,
117 "Re-extending circ %u, this time to %s.",
118 (unsigned)circ->base_.n_circ_id,
119 safe_str_client(extend_info_describe(extend_info)));
120 result = circuit_extend_to_new_exit(circ, extend_info);
121 } else {
122 log_info(LD_REND,
123 "Closing intro circ %u (out of RELAY_EARLY cells).",
124 (unsigned)circ->base_.n_circ_id);
125 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
126 /* connection_ap_handshake_attach_circuit will launch a new intro circ. */
127 result = 0;
129 extend_info_free(extend_info);
130 return result;
133 /** Return true iff we should send timestamps in our INTRODUCE1 cells */
134 static int
135 rend_client_should_send_timestamp(void)
137 if (get_options()->Support022HiddenServices >= 0)
138 return get_options()->Support022HiddenServices;
140 return networkstatus_get_param(NULL, "Support022HiddenServices", 1, 0, 1);
143 /** Called when we're trying to connect an ap conn; sends an INTRODUCE1 cell
144 * down introcirc if possible.
147 rend_client_send_introduction(origin_circuit_t *introcirc,
148 origin_circuit_t *rendcirc)
150 size_t payload_len;
151 int r, v3_shift = 0;
152 char payload[RELAY_PAYLOAD_SIZE];
153 char tmp[RELAY_PAYLOAD_SIZE];
154 rend_cache_entry_t *entry;
155 crypt_path_t *cpath;
156 off_t dh_offset;
157 crypto_pk_t *intro_key = NULL;
158 int status = 0;
160 tor_assert(introcirc->base_.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
161 tor_assert(rendcirc->base_.purpose == CIRCUIT_PURPOSE_C_REND_READY);
162 tor_assert(introcirc->rend_data);
163 tor_assert(rendcirc->rend_data);
164 tor_assert(!rend_cmp_service_ids(introcirc->rend_data->onion_address,
165 rendcirc->rend_data->onion_address));
166 #ifndef NON_ANONYMOUS_MODE_ENABLED
167 tor_assert(!(introcirc->build_state->onehop_tunnel));
168 tor_assert(!(rendcirc->build_state->onehop_tunnel));
169 #endif
171 if (rend_cache_lookup_entry(introcirc->rend_data->onion_address, -1,
172 &entry) < 1) {
173 log_info(LD_REND,
174 "query %s didn't have valid rend desc in cache. "
175 "Refetching descriptor.",
176 safe_str_client(introcirc->rend_data->onion_address));
177 rend_client_refetch_v2_renddesc(introcirc->rend_data);
179 connection_t *conn;
181 while ((conn = connection_get_by_type_state_rendquery(CONN_TYPE_AP,
182 AP_CONN_STATE_CIRCUIT_WAIT,
183 introcirc->rend_data->onion_address))) {
184 conn->state = AP_CONN_STATE_RENDDESC_WAIT;
188 status = -1;
189 goto cleanup;
192 /* first 20 bytes of payload are the hash of Bob's pk */
193 intro_key = NULL;
194 SMARTLIST_FOREACH(entry->parsed->intro_nodes, rend_intro_point_t *,
195 intro, {
196 if (tor_memeq(introcirc->build_state->chosen_exit->identity_digest,
197 intro->extend_info->identity_digest, DIGEST_LEN)) {
198 intro_key = intro->intro_key;
199 break;
202 if (!intro_key) {
203 log_info(LD_REND, "Could not find intro key for %s at %s; we "
204 "have a v2 rend desc with %d intro points. "
205 "Trying a different intro point...",
206 safe_str_client(introcirc->rend_data->onion_address),
207 safe_str_client(extend_info_describe(
208 introcirc->build_state->chosen_exit)),
209 smartlist_len(entry->parsed->intro_nodes));
211 if (rend_client_reextend_intro_circuit(introcirc)) {
212 status = -2;
213 goto perm_err;
214 } else {
215 status = -1;
216 goto cleanup;
219 if (crypto_pk_get_digest(intro_key, payload)<0) {
220 log_warn(LD_BUG, "Internal error: couldn't hash public key.");
221 status = -2;
222 goto perm_err;
225 /* Initialize the pending_final_cpath and start the DH handshake. */
226 cpath = rendcirc->build_state->pending_final_cpath;
227 if (!cpath) {
228 cpath = rendcirc->build_state->pending_final_cpath =
229 tor_malloc_zero(sizeof(crypt_path_t));
230 cpath->magic = CRYPT_PATH_MAGIC;
231 if (!(cpath->rend_dh_handshake_state = crypto_dh_new(DH_TYPE_REND))) {
232 log_warn(LD_BUG, "Internal error: couldn't allocate DH.");
233 status = -2;
234 goto perm_err;
236 if (crypto_dh_generate_public(cpath->rend_dh_handshake_state)<0) {
237 log_warn(LD_BUG, "Internal error: couldn't generate g^x.");
238 status = -2;
239 goto perm_err;
243 /* If version is 3, write (optional) auth data and timestamp. */
244 if (entry->parsed->protocols & (1<<3)) {
245 tmp[0] = 3; /* version 3 of the cell format */
246 tmp[1] = (uint8_t)introcirc->rend_data->auth_type; /* auth type, if any */
247 v3_shift = 1;
248 if (introcirc->rend_data->auth_type != REND_NO_AUTH) {
249 set_uint16(tmp+2, htons(REND_DESC_COOKIE_LEN));
250 memcpy(tmp+4, introcirc->rend_data->descriptor_cookie,
251 REND_DESC_COOKIE_LEN);
252 v3_shift += 2+REND_DESC_COOKIE_LEN;
254 if (rend_client_should_send_timestamp()) {
255 uint32_t now = (uint32_t)time(NULL);
256 now += 300;
257 now -= now % 600;
258 set_uint32(tmp+v3_shift+1, htonl(now));
259 } else {
260 set_uint32(tmp+v3_shift+1, 0);
262 v3_shift += 4;
263 } /* if version 2 only write version number */
264 else if (entry->parsed->protocols & (1<<2)) {
265 tmp[0] = 2; /* version 2 of the cell format */
268 /* write the remaining items into tmp */
269 if (entry->parsed->protocols & (1<<3) || entry->parsed->protocols & (1<<2)) {
270 /* version 2 format */
271 extend_info_t *extend_info = rendcirc->build_state->chosen_exit;
272 int klen;
273 /* nul pads */
274 set_uint32(tmp+v3_shift+1, tor_addr_to_ipv4h(&extend_info->addr));
275 set_uint16(tmp+v3_shift+5, htons(extend_info->port));
276 memcpy(tmp+v3_shift+7, extend_info->identity_digest, DIGEST_LEN);
277 klen = crypto_pk_asn1_encode(extend_info->onion_key,
278 tmp+v3_shift+7+DIGEST_LEN+2,
279 sizeof(tmp)-(v3_shift+7+DIGEST_LEN+2));
280 set_uint16(tmp+v3_shift+7+DIGEST_LEN, htons(klen));
281 memcpy(tmp+v3_shift+7+DIGEST_LEN+2+klen, rendcirc->rend_data->rend_cookie,
282 REND_COOKIE_LEN);
283 dh_offset = v3_shift+7+DIGEST_LEN+2+klen+REND_COOKIE_LEN;
284 } else {
285 /* Version 0. */
286 strncpy(tmp, rendcirc->build_state->chosen_exit->nickname,
287 (MAX_NICKNAME_LEN+1)); /* nul pads */
288 memcpy(tmp+MAX_NICKNAME_LEN+1, rendcirc->rend_data->rend_cookie,
289 REND_COOKIE_LEN);
290 dh_offset = MAX_NICKNAME_LEN+1+REND_COOKIE_LEN;
293 if (crypto_dh_get_public(cpath->rend_dh_handshake_state, tmp+dh_offset,
294 DH_KEY_LEN)<0) {
295 log_warn(LD_BUG, "Internal error: couldn't extract g^x.");
296 status = -2;
297 goto perm_err;
300 note_crypto_pk_op(REND_CLIENT);
301 /*XXX maybe give crypto_pk_public_hybrid_encrypt a max_len arg,
302 * to avoid buffer overflows? */
303 r = crypto_pk_public_hybrid_encrypt(intro_key, payload+DIGEST_LEN,
304 sizeof(payload)-DIGEST_LEN,
305 tmp,
306 (int)(dh_offset+DH_KEY_LEN),
307 PK_PKCS1_OAEP_PADDING, 0);
308 if (r<0) {
309 log_warn(LD_BUG,"Internal error: hybrid pk encrypt failed.");
310 status = -2;
311 goto perm_err;
314 payload_len = DIGEST_LEN + r;
315 tor_assert(payload_len <= RELAY_PAYLOAD_SIZE); /* we overran something */
317 /* Copy the rendezvous cookie from rendcirc to introcirc, so that
318 * when introcirc gets an ack, we can change the state of the right
319 * rendezvous circuit. */
320 memcpy(introcirc->rend_data->rend_cookie, rendcirc->rend_data->rend_cookie,
321 REND_COOKIE_LEN);
323 log_info(LD_REND, "Sending an INTRODUCE1 cell");
324 if (relay_send_command_from_edge(0, TO_CIRCUIT(introcirc),
325 RELAY_COMMAND_INTRODUCE1,
326 payload, payload_len,
327 introcirc->cpath->prev)<0) {
328 /* introcirc is already marked for close. leave rendcirc alone. */
329 log_warn(LD_BUG, "Couldn't send INTRODUCE1 cell");
330 status = -2;
331 goto cleanup;
334 /* Now, we wait for an ACK or NAK on this circuit. */
335 circuit_change_purpose(TO_CIRCUIT(introcirc),
336 CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT);
337 /* Set timestamp_dirty, because circuit_expire_building expects it
338 * to specify when a circuit entered the _C_INTRODUCE_ACK_WAIT
339 * state. */
340 introcirc->base_.timestamp_dirty = time(NULL);
342 pathbias_count_use_attempt(introcirc);
344 goto cleanup;
346 perm_err:
347 if (!introcirc->base_.marked_for_close)
348 circuit_mark_for_close(TO_CIRCUIT(introcirc), END_CIRC_REASON_INTERNAL);
349 circuit_mark_for_close(TO_CIRCUIT(rendcirc), END_CIRC_REASON_INTERNAL);
350 cleanup:
351 memwipe(payload, 0, sizeof(payload));
352 memwipe(tmp, 0, sizeof(tmp));
354 return status;
357 /** Called when a rendezvous circuit is open; sends a establish
358 * rendezvous circuit as appropriate. */
359 void
360 rend_client_rendcirc_has_opened(origin_circuit_t *circ)
362 tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
364 log_info(LD_REND,"rendcirc is open");
366 /* generate a rendezvous cookie, store it in circ */
367 if (rend_client_send_establish_rendezvous(circ) < 0) {
368 return;
373 * Called to close other intro circuits we launched in parallel
374 * due to timeout.
376 static void
377 rend_client_close_other_intros(const char *onion_address)
379 circuit_t *c;
380 /* abort parallel intro circs, if any */
381 TOR_LIST_FOREACH(c, circuit_get_global_list(), head) {
382 if ((c->purpose == CIRCUIT_PURPOSE_C_INTRODUCING ||
383 c->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) &&
384 !c->marked_for_close && CIRCUIT_IS_ORIGIN(c)) {
385 origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(c);
386 if (oc->rend_data &&
387 !rend_cmp_service_ids(onion_address,
388 oc->rend_data->onion_address)) {
389 log_info(LD_REND|LD_CIRC, "Closing introduction circuit %d that we "
390 "built in parallel (Purpose %d).", oc->global_identifier,
391 c->purpose);
392 circuit_mark_for_close(c, END_CIRC_REASON_TIMEOUT);
398 /** Called when get an ACK or a NAK for a REND_INTRODUCE1 cell.
401 rend_client_introduction_acked(origin_circuit_t *circ,
402 const uint8_t *request, size_t request_len)
404 origin_circuit_t *rendcirc;
405 (void) request; // XXXX Use this.
407 if (circ->base_.purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
408 log_warn(LD_PROTOCOL,
409 "Received REND_INTRODUCE_ACK on unexpected circuit %u.",
410 (unsigned)circ->base_.n_circ_id);
411 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
412 return -1;
415 tor_assert(circ->build_state->chosen_exit);
416 #ifndef NON_ANONYMOUS_MODE_ENABLED
417 tor_assert(!(circ->build_state->onehop_tunnel));
418 #endif
419 tor_assert(circ->rend_data);
421 /* For path bias: This circuit was used successfully. Valid
422 * nacks and acks count. */
423 pathbias_mark_use_success(circ);
425 if (request_len == 0) {
426 /* It's an ACK; the introduction point relayed our introduction request. */
427 /* Locate the rend circ which is waiting to hear about this ack,
428 * and tell it.
430 log_info(LD_REND,"Received ack. Telling rend circ...");
431 rendcirc = circuit_get_ready_rend_circ_by_rend_data(circ->rend_data);
432 if (rendcirc) { /* remember the ack */
433 #ifndef NON_ANONYMOUS_MODE_ENABLED
434 tor_assert(!(rendcirc->build_state->onehop_tunnel));
435 #endif
436 circuit_change_purpose(TO_CIRCUIT(rendcirc),
437 CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED);
438 /* Set timestamp_dirty, because circuit_expire_building expects
439 * it to specify when a circuit entered the
440 * _C_REND_READY_INTRO_ACKED state. */
441 rendcirc->base_.timestamp_dirty = time(NULL);
442 } else {
443 log_info(LD_REND,"...Found no rend circ. Dropping on the floor.");
445 /* close the circuit: we won't need it anymore. */
446 circuit_change_purpose(TO_CIRCUIT(circ),
447 CIRCUIT_PURPOSE_C_INTRODUCE_ACKED);
448 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
450 /* close any other intros launched in parallel */
451 rend_client_close_other_intros(circ->rend_data->onion_address);
452 } else {
453 /* It's a NAK; the introduction point didn't relay our request. */
454 circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_C_INTRODUCING);
455 /* Remove this intro point from the set of viable introduction
456 * points. If any remain, extend to a new one and try again.
457 * If none remain, refetch the service descriptor.
459 log_info(LD_REND, "Got nack for %s from %s...",
460 safe_str_client(circ->rend_data->onion_address),
461 safe_str_client(extend_info_describe(circ->build_state->chosen_exit)));
462 if (rend_client_report_intro_point_failure(circ->build_state->chosen_exit,
463 circ->rend_data,
464 INTRO_POINT_FAILURE_GENERIC)>0) {
465 /* There are introduction points left. Re-extend the circuit to
466 * another intro point and try again. */
467 int result = rend_client_reextend_intro_circuit(circ);
468 /* XXXX If that call failed, should we close the rend circuit,
469 * too? */
470 return result;
473 return 0;
476 /** The period for which a hidden service directory cannot be queried for
477 * the same descriptor ID again. */
478 #define REND_HID_SERV_DIR_REQUERY_PERIOD (15 * 60)
480 /** Contains the last request times to hidden service directories for
481 * certain queries; each key is a string consisting of the
482 * concatenation of a base32-encoded HS directory identity digest, a
483 * base32-encoded HS descriptor ID, and a hidden service address
484 * (without the ".onion" part); each value is a pointer to a time_t
485 * holding the time of the last request for that descriptor ID to that
486 * HS directory. */
487 static strmap_t *last_hid_serv_requests_ = NULL;
489 /** Returns last_hid_serv_requests_, initializing it to a new strmap if
490 * necessary. */
491 static strmap_t *
492 get_last_hid_serv_requests(void)
494 if (!last_hid_serv_requests_)
495 last_hid_serv_requests_ = strmap_new();
496 return last_hid_serv_requests_;
499 #define LAST_HID_SERV_REQUEST_KEY_LEN (REND_DESC_ID_V2_LEN_BASE32 + \
500 REND_DESC_ID_V2_LEN_BASE32 + \
501 REND_SERVICE_ID_LEN_BASE32)
503 /** Look up the last request time to hidden service directory <b>hs_dir</b>
504 * for descriptor ID <b>desc_id_base32</b> for the service specified in
505 * <b>rend_query</b>. If <b>set</b> is non-zero,
506 * assign the current time <b>now</b> and return that. Otherwise, return
507 * the most recent request time, or 0 if no such request has been sent
508 * before. */
509 static time_t
510 lookup_last_hid_serv_request(routerstatus_t *hs_dir,
511 const char *desc_id_base32,
512 const rend_data_t *rend_query,
513 time_t now, int set)
515 char hsdir_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
516 char hsdir_desc_comb_id[LAST_HID_SERV_REQUEST_KEY_LEN + 1];
517 time_t *last_request_ptr;
518 strmap_t *last_hid_serv_requests = get_last_hid_serv_requests();
519 base32_encode(hsdir_id_base32, sizeof(hsdir_id_base32),
520 hs_dir->identity_digest, DIGEST_LEN);
521 tor_snprintf(hsdir_desc_comb_id, sizeof(hsdir_desc_comb_id), "%s%s%s",
522 hsdir_id_base32,
523 desc_id_base32,
524 rend_query->onion_address);
525 /* XXX023 tor_assert(strlen(hsdir_desc_comb_id) ==
526 LAST_HID_SERV_REQUEST_KEY_LEN); */
527 if (set) {
528 time_t *oldptr;
529 last_request_ptr = tor_malloc_zero(sizeof(time_t));
530 *last_request_ptr = now;
531 oldptr = strmap_set(last_hid_serv_requests, hsdir_desc_comb_id,
532 last_request_ptr);
533 tor_free(oldptr);
534 } else
535 last_request_ptr = strmap_get_lc(last_hid_serv_requests,
536 hsdir_desc_comb_id);
537 return (last_request_ptr) ? *last_request_ptr : 0;
540 /** Clean the history of request times to hidden service directories, so that
541 * it does not contain requests older than REND_HID_SERV_DIR_REQUERY_PERIOD
542 * seconds any more. */
543 static void
544 directory_clean_last_hid_serv_requests(time_t now)
546 strmap_iter_t *iter;
547 time_t cutoff = now - REND_HID_SERV_DIR_REQUERY_PERIOD;
548 strmap_t *last_hid_serv_requests = get_last_hid_serv_requests();
549 for (iter = strmap_iter_init(last_hid_serv_requests);
550 !strmap_iter_done(iter); ) {
551 const char *key;
552 void *val;
553 time_t *ent;
554 strmap_iter_get(iter, &key, &val);
555 ent = (time_t *) val;
556 if (*ent < cutoff) {
557 iter = strmap_iter_next_rmv(last_hid_serv_requests, iter);
558 tor_free(ent);
559 } else {
560 iter = strmap_iter_next(last_hid_serv_requests, iter);
565 /** Remove all requests related to the hidden service named
566 * <b>onion_address</b> from the history of times of requests to
567 * hidden service directories. */
568 static void
569 purge_hid_serv_from_last_hid_serv_requests(const char *onion_address)
571 strmap_iter_t *iter;
572 strmap_t *last_hid_serv_requests = get_last_hid_serv_requests();
573 /* XXX023 tor_assert(strlen(onion_address) == REND_SERVICE_ID_LEN_BASE32); */
574 for (iter = strmap_iter_init(last_hid_serv_requests);
575 !strmap_iter_done(iter); ) {
576 const char *key;
577 void *val;
578 strmap_iter_get(iter, &key, &val);
579 /* XXX023 tor_assert(strlen(key) == LAST_HID_SERV_REQUEST_KEY_LEN); */
580 if (tor_memeq(key + LAST_HID_SERV_REQUEST_KEY_LEN -
581 REND_SERVICE_ID_LEN_BASE32,
582 onion_address,
583 REND_SERVICE_ID_LEN_BASE32)) {
584 iter = strmap_iter_next_rmv(last_hid_serv_requests, iter);
585 tor_free(val);
586 } else {
587 iter = strmap_iter_next(last_hid_serv_requests, iter);
592 /** Purge the history of request times to hidden service directories,
593 * so that future lookups of an HS descriptor will not fail because we
594 * accessed all of the HSDir relays responsible for the descriptor
595 * recently. */
596 void
597 rend_client_purge_last_hid_serv_requests(void)
599 /* Don't create the table if it doesn't exist yet (and it may very
600 * well not exist if the user hasn't accessed any HSes)... */
601 strmap_t *old_last_hid_serv_requests = last_hid_serv_requests_;
602 /* ... and let get_last_hid_serv_requests re-create it for us if
603 * necessary. */
604 last_hid_serv_requests_ = NULL;
606 if (old_last_hid_serv_requests != NULL) {
607 log_info(LD_REND, "Purging client last-HS-desc-request-time table");
608 strmap_free(old_last_hid_serv_requests, tor_free_);
612 /** Determine the responsible hidden service directories for <b>desc_id</b>
613 * and fetch the descriptor with that ID from one of them. Only
614 * send a request to a hidden service directory that we have not yet tried
615 * during this attempt to connect to this hidden service; on success, return 1,
616 * in the case that no hidden service directory is left to ask for the
617 * descriptor, return 0, and in case of a failure -1. */
618 static int
619 directory_get_from_hs_dir(const char *desc_id, const rend_data_t *rend_query)
621 smartlist_t *responsible_dirs = smartlist_new();
622 smartlist_t *usable_responsible_dirs = smartlist_new();
623 const or_options_t *options = get_options();
624 routerstatus_t *hs_dir;
625 char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
626 time_t now = time(NULL);
627 char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
628 const int tor2web_mode = options->Tor2webMode;
629 int excluded_some;
630 tor_assert(desc_id);
631 tor_assert(rend_query);
632 /* Determine responsible dirs. Even if we can't get all we want,
633 * work with the ones we have. If it's empty, we'll notice below. */
634 hid_serv_get_responsible_directories(responsible_dirs, desc_id);
636 base32_encode(desc_id_base32, sizeof(desc_id_base32),
637 desc_id, DIGEST_LEN);
639 /* Only select those hidden service directories to which we did not send
640 * a request recently and for which we have a router descriptor here. */
642 /* Clean request history first. */
643 directory_clean_last_hid_serv_requests(now);
645 SMARTLIST_FOREACH(responsible_dirs, routerstatus_t *, dir, {
646 time_t last = lookup_last_hid_serv_request(
647 dir, desc_id_base32, rend_query, 0, 0);
648 const node_t *node = node_get_by_id(dir->identity_digest);
649 if (last + REND_HID_SERV_DIR_REQUERY_PERIOD >= now ||
650 !node || !node_has_descriptor(node)) {
651 SMARTLIST_DEL_CURRENT(responsible_dirs, dir);
652 continue;
654 if (! routerset_contains_node(options->ExcludeNodes, node)) {
655 smartlist_add(usable_responsible_dirs, dir);
659 excluded_some =
660 smartlist_len(usable_responsible_dirs) < smartlist_len(responsible_dirs);
662 hs_dir = smartlist_choose(usable_responsible_dirs);
663 if (! hs_dir && ! options->StrictNodes)
664 hs_dir = smartlist_choose(responsible_dirs);
666 smartlist_free(responsible_dirs);
667 smartlist_free(usable_responsible_dirs);
668 if (!hs_dir) {
669 log_info(LD_REND, "Could not pick one of the responsible hidden "
670 "service directories, because we requested them all "
671 "recently without success.");
672 if (options->StrictNodes && excluded_some) {
673 log_warn(LD_REND, "Could not pick a hidden service directory for the "
674 "requested hidden service: they are all either down or "
675 "excluded, and StrictNodes is set.");
677 return 0;
680 /* Remember that we are requesting a descriptor from this hidden service
681 * directory now. */
682 lookup_last_hid_serv_request(hs_dir, desc_id_base32, rend_query, now, 1);
684 /* Encode descriptor cookie for logging purposes. */
685 if (rend_query->auth_type != REND_NO_AUTH) {
686 if (base64_encode(descriptor_cookie_base64,
687 sizeof(descriptor_cookie_base64),
688 rend_query->descriptor_cookie, REND_DESC_COOKIE_LEN)<0) {
689 log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
690 return 0;
692 /* Remove == signs and newline. */
693 descriptor_cookie_base64[strlen(descriptor_cookie_base64)-3] = '\0';
694 } else {
695 strlcpy(descriptor_cookie_base64, "(none)",
696 sizeof(descriptor_cookie_base64));
699 /* Send fetch request. (Pass query and possibly descriptor cookie so that
700 * they can be written to the directory connection and be referred to when
701 * the response arrives. */
702 directory_initiate_command_routerstatus_rend(hs_dir,
703 DIR_PURPOSE_FETCH_RENDDESC_V2,
704 ROUTER_PURPOSE_GENERAL,
705 tor2web_mode?DIRIND_ONEHOP:DIRIND_ANONYMOUS,
706 desc_id_base32,
707 NULL, 0, 0,
708 rend_query);
709 log_info(LD_REND, "Sending fetch request for v2 descriptor for "
710 "service '%s' with descriptor ID '%s', auth type %d, "
711 "and descriptor cookie '%s' to hidden service "
712 "directory %s",
713 rend_query->onion_address, desc_id_base32,
714 rend_query->auth_type,
715 (rend_query->auth_type == REND_NO_AUTH ? "[none]" :
716 escaped_safe_str_client(descriptor_cookie_base64)),
717 routerstatus_describe(hs_dir));
718 control_event_hs_descriptor_requested(rend_query,
719 hs_dir->identity_digest,
720 desc_id_base32);
721 return 1;
724 /** Unless we already have a descriptor for <b>rend_query</b> with at least
725 * one (possibly) working introduction point in it, start a connection to a
726 * hidden service directory to fetch a v2 rendezvous service descriptor. */
727 void
728 rend_client_refetch_v2_renddesc(const rend_data_t *rend_query)
730 char descriptor_id[DIGEST_LEN];
731 int replicas_left_to_try[REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS];
732 int i, tries_left;
733 rend_cache_entry_t *e = NULL;
734 tor_assert(rend_query);
735 /* Are we configured to fetch descriptors? */
736 if (!get_options()->FetchHidServDescriptors) {
737 log_warn(LD_REND, "We received an onion address for a v2 rendezvous "
738 "service descriptor, but are not fetching service descriptors.");
739 return;
741 /* Before fetching, check if we already have a usable descriptor here. */
742 if (rend_cache_lookup_entry(rend_query->onion_address, -1, &e) > 0 &&
743 rend_client_any_intro_points_usable(e)) {
744 log_info(LD_REND, "We would fetch a v2 rendezvous descriptor, but we "
745 "already have a usable descriptor here. Not fetching.");
746 return;
748 log_debug(LD_REND, "Fetching v2 rendezvous descriptor for service %s",
749 safe_str_client(rend_query->onion_address));
750 /* Randomly iterate over the replicas until a descriptor can be fetched
751 * from one of the consecutive nodes, or no options are left. */
752 tries_left = REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS;
753 for (i = 0; i < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; i++)
754 replicas_left_to_try[i] = i;
755 while (tries_left > 0) {
756 int rand = crypto_rand_int(tries_left);
757 int chosen_replica = replicas_left_to_try[rand];
758 replicas_left_to_try[rand] = replicas_left_to_try[--tries_left];
760 if (rend_compute_v2_desc_id(descriptor_id, rend_query->onion_address,
761 rend_query->auth_type == REND_STEALTH_AUTH ?
762 rend_query->descriptor_cookie : NULL,
763 time(NULL), chosen_replica) < 0) {
764 log_warn(LD_REND, "Internal error: Computing v2 rendezvous "
765 "descriptor ID did not succeed.");
767 * Hmm, can this write anything to descriptor_id and still fail?
768 * Let's clear it just to be safe.
770 * From here on, any returns should goto done which clears
771 * descriptor_id so we don't leave key-derived material on the stack.
773 goto done;
775 if (directory_get_from_hs_dir(descriptor_id, rend_query) != 0)
776 goto done; /* either success or failure, but we're done */
778 /* If we come here, there are no hidden service directories left. */
779 log_info(LD_REND, "Could not pick one of the responsible hidden "
780 "service directories to fetch descriptors, because "
781 "we already tried them all unsuccessfully.");
782 /* Close pending connections. */
783 rend_client_desc_trynow(rend_query->onion_address);
785 done:
786 memwipe(descriptor_id, 0, sizeof(descriptor_id));
788 return;
791 /** Cancel all rendezvous descriptor fetches currently in progress.
793 void
794 rend_client_cancel_descriptor_fetches(void)
796 smartlist_t *connection_array = get_connection_array();
798 SMARTLIST_FOREACH_BEGIN(connection_array, connection_t *, conn) {
799 if (conn->type == CONN_TYPE_DIR &&
800 conn->purpose == DIR_PURPOSE_FETCH_RENDDESC_V2) {
801 /* It's a rendezvous descriptor fetch in progress -- cancel it
802 * by marking the connection for close.
804 * Even if this connection has already reached EOF, this is
805 * enough to make sure that if the descriptor hasn't been
806 * processed yet, it won't be. See the end of
807 * connection_handle_read; connection_reached_eof (indirectly)
808 * processes whatever response the connection received. */
810 const rend_data_t *rd = (TO_DIR_CONN(conn))->rend_data;
811 if (!rd) {
812 log_warn(LD_BUG | LD_REND,
813 "Marking for close dir conn fetching rendezvous "
814 "descriptor for unknown service!");
815 } else {
816 log_debug(LD_REND, "Marking for close dir conn fetching "
817 "rendezvous descriptor for service %s",
818 safe_str(rd->onion_address));
820 connection_mark_for_close(conn);
822 } SMARTLIST_FOREACH_END(conn);
825 /** Mark <b>failed_intro</b> as a failed introduction point for the
826 * hidden service specified by <b>rend_query</b>. If the HS now has no
827 * usable intro points, or we do not have an HS descriptor for it,
828 * then launch a new renddesc fetch.
830 * If <b>failure_type</b> is INTRO_POINT_FAILURE_GENERIC, remove the
831 * intro point from (our parsed copy of) the HS descriptor.
833 * If <b>failure_type</b> is INTRO_POINT_FAILURE_TIMEOUT, mark the
834 * intro point as 'timed out'; it will not be retried until the
835 * current hidden service connection attempt has ended or it has
836 * appeared in a newly fetched rendezvous descriptor.
838 * If <b>failure_type</b> is INTRO_POINT_FAILURE_UNREACHABLE,
839 * increment the intro point's reachability-failure count; if it has
840 * now failed MAX_INTRO_POINT_REACHABILITY_FAILURES or more times,
841 * remove the intro point from (our parsed copy of) the HS descriptor.
843 * Return -1 if error, 0 if no usable intro points remain or service
844 * unrecognized, 1 if recognized and some intro points remain.
847 rend_client_report_intro_point_failure(extend_info_t *failed_intro,
848 const rend_data_t *rend_query,
849 unsigned int failure_type)
851 int i, r;
852 rend_cache_entry_t *ent;
853 connection_t *conn;
855 r = rend_cache_lookup_entry(rend_query->onion_address, -1, &ent);
856 if (r<0) {
857 log_warn(LD_BUG, "Malformed service ID %s.",
858 escaped_safe_str_client(rend_query->onion_address));
859 return -1;
861 if (r==0) {
862 log_info(LD_REND, "Unknown service %s. Re-fetching descriptor.",
863 escaped_safe_str_client(rend_query->onion_address));
864 rend_client_refetch_v2_renddesc(rend_query);
865 return 0;
868 for (i = 0; i < smartlist_len(ent->parsed->intro_nodes); i++) {
869 rend_intro_point_t *intro = smartlist_get(ent->parsed->intro_nodes, i);
870 if (tor_memeq(failed_intro->identity_digest,
871 intro->extend_info->identity_digest, DIGEST_LEN)) {
872 switch (failure_type) {
873 default:
874 log_warn(LD_BUG, "Unknown failure type %u. Removing intro point.",
875 failure_type);
876 tor_fragile_assert();
877 /* fall through */
878 case INTRO_POINT_FAILURE_GENERIC:
879 rend_intro_point_free(intro);
880 smartlist_del(ent->parsed->intro_nodes, i);
881 break;
882 case INTRO_POINT_FAILURE_TIMEOUT:
883 intro->timed_out = 1;
884 break;
885 case INTRO_POINT_FAILURE_UNREACHABLE:
886 ++(intro->unreachable_count);
888 int zap_intro_point =
889 intro->unreachable_count >= MAX_INTRO_POINT_REACHABILITY_FAILURES;
890 log_info(LD_REND, "Failed to reach this intro point %u times.%s",
891 intro->unreachable_count,
892 zap_intro_point ? " Removing from descriptor.": "");
893 if (zap_intro_point) {
894 rend_intro_point_free(intro);
895 smartlist_del(ent->parsed->intro_nodes, i);
898 break;
900 break;
904 if (! rend_client_any_intro_points_usable(ent)) {
905 log_info(LD_REND,
906 "No more intro points remain for %s. Re-fetching descriptor.",
907 escaped_safe_str_client(rend_query->onion_address));
908 rend_client_refetch_v2_renddesc(rend_query);
910 /* move all pending streams back to renddesc_wait */
911 while ((conn = connection_get_by_type_state_rendquery(CONN_TYPE_AP,
912 AP_CONN_STATE_CIRCUIT_WAIT,
913 rend_query->onion_address))) {
914 conn->state = AP_CONN_STATE_RENDDESC_WAIT;
917 return 0;
919 log_info(LD_REND,"%d options left for %s.",
920 smartlist_len(ent->parsed->intro_nodes),
921 escaped_safe_str_client(rend_query->onion_address));
922 return 1;
925 /** Called when we receive a RENDEZVOUS_ESTABLISHED cell; changes the state of
926 * the circuit to C_REND_READY.
929 rend_client_rendezvous_acked(origin_circuit_t *circ, const uint8_t *request,
930 size_t request_len)
932 (void) request;
933 (void) request_len;
934 /* we just got an ack for our establish-rendezvous. switch purposes. */
935 if (circ->base_.purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND) {
936 log_warn(LD_PROTOCOL,"Got a rendezvous ack when we weren't expecting one. "
937 "Closing circ.");
938 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
939 return -1;
941 log_info(LD_REND,"Got rendezvous ack. This circuit is now ready for "
942 "rendezvous.");
943 circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_C_REND_READY);
944 /* Set timestamp_dirty, because circuit_expire_building expects it
945 * to specify when a circuit entered the _C_REND_READY state. */
946 circ->base_.timestamp_dirty = time(NULL);
948 /* From a path bias point of view, this circuit is now successfully used.
949 * Waiting any longer opens us up to attacks from Bob. He could induce
950 * Alice to attempt to connect to his hidden service and never reply
951 * to her rend requests */
952 pathbias_mark_use_success(circ);
954 /* XXXX This is a pretty brute-force approach. It'd be better to
955 * attach only the connections that are waiting on this circuit, rather
956 * than trying to attach them all. See comments bug 743. */
957 /* If we already have the introduction circuit built, make sure we send
958 * the INTRODUCE cell _now_ */
959 connection_ap_attach_pending();
960 return 0;
963 /** Bob sent us a rendezvous cell; join the circuits. */
965 rend_client_receive_rendezvous(origin_circuit_t *circ, const uint8_t *request,
966 size_t request_len)
968 crypt_path_t *hop;
969 char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN];
971 if ((circ->base_.purpose != CIRCUIT_PURPOSE_C_REND_READY &&
972 circ->base_.purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)
973 || !circ->build_state->pending_final_cpath) {
974 log_warn(LD_PROTOCOL,"Got rendezvous2 cell from hidden service, but not "
975 "expecting it. Closing.");
976 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
977 return -1;
980 if (request_len != DH_KEY_LEN+DIGEST_LEN) {
981 log_warn(LD_PROTOCOL,"Incorrect length (%d) on RENDEZVOUS2 cell.",
982 (int)request_len);
983 goto err;
986 log_info(LD_REND,"Got RENDEZVOUS2 cell from hidden service.");
988 /* first DH_KEY_LEN bytes are g^y from bob. Finish the dh handshake...*/
989 tor_assert(circ->build_state);
990 tor_assert(circ->build_state->pending_final_cpath);
991 hop = circ->build_state->pending_final_cpath;
992 tor_assert(hop->rend_dh_handshake_state);
993 if (crypto_dh_compute_secret(LOG_PROTOCOL_WARN,
994 hop->rend_dh_handshake_state, (char*)request,
995 DH_KEY_LEN,
996 keys, DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
997 log_warn(LD_GENERAL, "Couldn't complete DH handshake.");
998 goto err;
1000 /* ... and set up cpath. */
1001 if (circuit_init_cpath_crypto(hop, keys+DIGEST_LEN, 0)<0)
1002 goto err;
1004 /* Check whether the digest is right... */
1005 if (tor_memneq(keys, request+DH_KEY_LEN, DIGEST_LEN)) {
1006 log_warn(LD_PROTOCOL, "Incorrect digest of key material.");
1007 goto err;
1010 crypto_dh_free(hop->rend_dh_handshake_state);
1011 hop->rend_dh_handshake_state = NULL;
1013 /* All is well. Extend the circuit. */
1014 circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_C_REND_JOINED);
1015 hop->state = CPATH_STATE_OPEN;
1016 /* set the windows to default. these are the windows
1017 * that alice thinks bob has.
1019 hop->package_window = circuit_initial_package_window();
1020 hop->deliver_window = CIRCWINDOW_START;
1022 /* Now that this circuit has finished connecting to its destination,
1023 * make sure circuit_get_open_circ_or_launch is willing to return it
1024 * so we can actually use it. */
1025 circ->hs_circ_has_timed_out = 0;
1027 onion_append_to_cpath(&circ->cpath, hop);
1028 circ->build_state->pending_final_cpath = NULL; /* prevent double-free */
1030 circuit_try_attaching_streams(circ);
1032 memwipe(keys, 0, sizeof(keys));
1033 return 0;
1034 err:
1035 memwipe(keys, 0, sizeof(keys));
1036 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
1037 return -1;
1040 /** Find all the apconns in state AP_CONN_STATE_RENDDESC_WAIT that are
1041 * waiting on <b>query</b>. If there's a working cache entry here with at
1042 * least one intro point, move them to the next state. */
1043 void
1044 rend_client_desc_trynow(const char *query)
1046 entry_connection_t *conn;
1047 rend_cache_entry_t *entry;
1048 const rend_data_t *rend_data;
1049 time_t now = time(NULL);
1051 smartlist_t *conns = get_connection_array();
1052 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
1053 if (base_conn->type != CONN_TYPE_AP ||
1054 base_conn->state != AP_CONN_STATE_RENDDESC_WAIT ||
1055 base_conn->marked_for_close)
1056 continue;
1057 conn = TO_ENTRY_CONN(base_conn);
1058 rend_data = ENTRY_TO_EDGE_CONN(conn)->rend_data;
1059 if (!rend_data)
1060 continue;
1061 if (rend_cmp_service_ids(query, rend_data->onion_address))
1062 continue;
1063 assert_connection_ok(base_conn, now);
1064 if (rend_cache_lookup_entry(rend_data->onion_address, -1,
1065 &entry) == 1 &&
1066 rend_client_any_intro_points_usable(entry)) {
1067 /* either this fetch worked, or it failed but there was a
1068 * valid entry from before which we should reuse */
1069 log_info(LD_REND,"Rend desc is usable. Launching circuits.");
1070 base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
1072 /* restart their timeout values, so they get a fair shake at
1073 * connecting to the hidden service. */
1074 base_conn->timestamp_created = now;
1075 base_conn->timestamp_lastread = now;
1076 base_conn->timestamp_lastwritten = now;
1078 if (connection_ap_handshake_attach_circuit(conn) < 0) {
1079 /* it will never work */
1080 log_warn(LD_REND,"Rendezvous attempt failed. Closing.");
1081 if (!base_conn->marked_for_close)
1082 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1084 } else { /* 404, or fetch didn't get that far */
1085 log_notice(LD_REND,"Closing stream for '%s.onion': hidden service is "
1086 "unavailable (try again later).",
1087 safe_str_client(query));
1088 connection_mark_unattached_ap(conn, END_STREAM_REASON_RESOLVEFAILED);
1089 rend_client_note_connection_attempt_ended(query);
1091 } SMARTLIST_FOREACH_END(base_conn);
1094 /** Clear temporary state used only during an attempt to connect to
1095 * the hidden service named <b>onion_address</b>. Called when a
1096 * connection attempt has ended; may be called occasionally at other
1097 * times, and should be reasonably harmless. */
1098 void
1099 rend_client_note_connection_attempt_ended(const char *onion_address)
1101 rend_cache_entry_t *cache_entry = NULL;
1102 rend_cache_lookup_entry(onion_address, -1, &cache_entry);
1104 log_info(LD_REND, "Connection attempt for %s has ended; "
1105 "cleaning up temporary state.",
1106 safe_str_client(onion_address));
1108 /* Clear the timed_out flag on all remaining intro points for this HS. */
1109 if (cache_entry != NULL) {
1110 SMARTLIST_FOREACH(cache_entry->parsed->intro_nodes,
1111 rend_intro_point_t *, ip,
1112 ip->timed_out = 0; );
1115 /* Remove the HS's entries in last_hid_serv_requests. */
1116 purge_hid_serv_from_last_hid_serv_requests(onion_address);
1119 /** Return a newly allocated extend_info_t* for a randomly chosen introduction
1120 * point for the named hidden service. Return NULL if all introduction points
1121 * have been tried and failed.
1123 extend_info_t *
1124 rend_client_get_random_intro(const rend_data_t *rend_query)
1126 extend_info_t *result;
1127 rend_cache_entry_t *entry;
1129 if (rend_cache_lookup_entry(rend_query->onion_address, -1, &entry) < 1) {
1130 log_warn(LD_REND,
1131 "Query '%s' didn't have valid rend desc in cache. Failing.",
1132 safe_str_client(rend_query->onion_address));
1133 return NULL;
1136 /* See if we can get a node that complies with ExcludeNodes */
1137 if ((result = rend_client_get_random_intro_impl(entry, 1, 1)))
1138 return result;
1139 /* If not, and StrictNodes is not set, see if we can return any old node
1141 if (!get_options()->StrictNodes)
1142 return rend_client_get_random_intro_impl(entry, 0, 1);
1143 return NULL;
1146 /** As rend_client_get_random_intro, except assume that StrictNodes is set
1147 * iff <b>strict</b> is true. If <b>warnings</b> is false, don't complain
1148 * to the user when we're out of nodes, even if StrictNodes is true.
1150 static extend_info_t *
1151 rend_client_get_random_intro_impl(const rend_cache_entry_t *entry,
1152 const int strict,
1153 const int warnings)
1155 int i;
1157 rend_intro_point_t *intro;
1158 const or_options_t *options = get_options();
1159 smartlist_t *usable_nodes;
1160 int n_excluded = 0;
1162 /* We'll keep a separate list of the usable nodes. If this becomes empty,
1163 * no nodes are usable. */
1164 usable_nodes = smartlist_new();
1165 smartlist_add_all(usable_nodes, entry->parsed->intro_nodes);
1167 /* Remove the intro points that have timed out during this HS
1168 * connection attempt from our list of usable nodes. */
1169 SMARTLIST_FOREACH(usable_nodes, rend_intro_point_t *, ip,
1170 if (ip->timed_out) {
1171 SMARTLIST_DEL_CURRENT(usable_nodes, ip);
1174 again:
1175 if (smartlist_len(usable_nodes) == 0) {
1176 if (n_excluded && get_options()->StrictNodes && warnings) {
1177 /* We only want to warn if StrictNodes is really set. Otherwise
1178 * we're just about to retry anyways.
1180 log_warn(LD_REND, "All introduction points for hidden service are "
1181 "at excluded relays, and StrictNodes is set. Skipping.");
1183 smartlist_free(usable_nodes);
1184 return NULL;
1187 i = crypto_rand_int(smartlist_len(usable_nodes));
1188 intro = smartlist_get(usable_nodes, i);
1189 /* Do we need to look up the router or is the extend info complete? */
1190 if (!intro->extend_info->onion_key) {
1191 const node_t *node;
1192 extend_info_t *new_extend_info;
1193 if (tor_digest_is_zero(intro->extend_info->identity_digest))
1194 node = node_get_by_hex_id(intro->extend_info->nickname);
1195 else
1196 node = node_get_by_id(intro->extend_info->identity_digest);
1197 if (!node) {
1198 log_info(LD_REND, "Unknown router with nickname '%s'; trying another.",
1199 intro->extend_info->nickname);
1200 smartlist_del(usable_nodes, i);
1201 goto again;
1203 new_extend_info = extend_info_from_node(node, 0);
1204 if (!new_extend_info) {
1205 log_info(LD_REND, "We don't have a descriptor for the intro-point relay "
1206 "'%s'; trying another.",
1207 extend_info_describe(intro->extend_info));
1208 smartlist_del(usable_nodes, i);
1209 goto again;
1210 } else {
1211 extend_info_free(intro->extend_info);
1212 intro->extend_info = new_extend_info;
1214 tor_assert(intro->extend_info != NULL);
1216 /* Check if we should refuse to talk to this router. */
1217 if (strict &&
1218 routerset_contains_extendinfo(options->ExcludeNodes,
1219 intro->extend_info)) {
1220 n_excluded++;
1221 smartlist_del(usable_nodes, i);
1222 goto again;
1225 smartlist_free(usable_nodes);
1226 return extend_info_dup(intro->extend_info);
1229 /** Return true iff any introduction points still listed in <b>entry</b> are
1230 * usable. */
1232 rend_client_any_intro_points_usable(const rend_cache_entry_t *entry)
1234 extend_info_t *extend_info =
1235 rend_client_get_random_intro_impl(entry, get_options()->StrictNodes, 0);
1237 int rv = (extend_info != NULL);
1239 extend_info_free(extend_info);
1240 return rv;
1243 /** Client-side authorizations for hidden services; map of onion address to
1244 * rend_service_authorization_t*. */
1245 static strmap_t *auth_hid_servs = NULL;
1247 /** Look up the client-side authorization for the hidden service with
1248 * <b>onion_address</b>. Return NULL if no authorization is available for
1249 * that address. */
1250 rend_service_authorization_t*
1251 rend_client_lookup_service_authorization(const char *onion_address)
1253 tor_assert(onion_address);
1254 if (!auth_hid_servs) return NULL;
1255 return strmap_get(auth_hid_servs, onion_address);
1258 /** Helper: Free storage held by rend_service_authorization_t. */
1259 static void
1260 rend_service_authorization_free(rend_service_authorization_t *auth)
1262 tor_free(auth);
1265 /** Helper for strmap_free. */
1266 static void
1267 rend_service_authorization_strmap_item_free(void *service_auth)
1269 rend_service_authorization_free(service_auth);
1272 /** Release all the storage held in auth_hid_servs.
1274 void
1275 rend_service_authorization_free_all(void)
1277 if (!auth_hid_servs) {
1278 return;
1280 strmap_free(auth_hid_servs, rend_service_authorization_strmap_item_free);
1281 auth_hid_servs = NULL;
1284 /** Parse <b>config_line</b> as a client-side authorization for a hidden
1285 * service and add it to the local map of hidden service authorizations.
1286 * Return 0 for success and -1 for failure. */
1288 rend_parse_service_authorization(const or_options_t *options,
1289 int validate_only)
1291 config_line_t *line;
1292 int res = -1;
1293 strmap_t *parsed = strmap_new();
1294 smartlist_t *sl = smartlist_new();
1295 rend_service_authorization_t *auth = NULL;
1296 char descriptor_cookie_tmp[REND_DESC_COOKIE_LEN+2];
1297 char descriptor_cookie_base64ext[REND_DESC_COOKIE_LEN_BASE64+2+1];
1299 for (line = options->HidServAuth; line; line = line->next) {
1300 char *onion_address, *descriptor_cookie;
1301 int auth_type_val = 0;
1302 auth = NULL;
1303 SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
1304 smartlist_clear(sl);
1305 smartlist_split_string(sl, line->value, " ",
1306 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
1307 if (smartlist_len(sl) < 2) {
1308 log_warn(LD_CONFIG, "Configuration line does not consist of "
1309 "\"onion-address authorization-cookie [service-name]\": "
1310 "'%s'", line->value);
1311 goto err;
1313 auth = tor_malloc_zero(sizeof(rend_service_authorization_t));
1314 /* Parse onion address. */
1315 onion_address = smartlist_get(sl, 0);
1316 if (strlen(onion_address) != REND_SERVICE_ADDRESS_LEN ||
1317 strcmpend(onion_address, ".onion")) {
1318 log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
1319 onion_address);
1320 goto err;
1322 strlcpy(auth->onion_address, onion_address, REND_SERVICE_ID_LEN_BASE32+1);
1323 if (!rend_valid_service_id(auth->onion_address)) {
1324 log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
1325 onion_address);
1326 goto err;
1328 /* Parse descriptor cookie. */
1329 descriptor_cookie = smartlist_get(sl, 1);
1330 if (strlen(descriptor_cookie) != REND_DESC_COOKIE_LEN_BASE64) {
1331 log_warn(LD_CONFIG, "Authorization cookie has wrong length: '%s'",
1332 descriptor_cookie);
1333 goto err;
1335 /* Add trailing zero bytes (AA) to make base64-decoding happy. */
1336 tor_snprintf(descriptor_cookie_base64ext,
1337 REND_DESC_COOKIE_LEN_BASE64+2+1,
1338 "%sAA", descriptor_cookie);
1339 if (base64_decode(descriptor_cookie_tmp, sizeof(descriptor_cookie_tmp),
1340 descriptor_cookie_base64ext,
1341 strlen(descriptor_cookie_base64ext)) < 0) {
1342 log_warn(LD_CONFIG, "Decoding authorization cookie failed: '%s'",
1343 descriptor_cookie);
1344 goto err;
1346 auth_type_val = (((uint8_t)descriptor_cookie_tmp[16]) >> 4) + 1;
1347 if (auth_type_val < 1 || auth_type_val > 2) {
1348 log_warn(LD_CONFIG, "Authorization cookie has unknown authorization "
1349 "type encoded.");
1350 goto err;
1352 auth->auth_type = auth_type_val == 1 ? REND_BASIC_AUTH : REND_STEALTH_AUTH;
1353 memcpy(auth->descriptor_cookie, descriptor_cookie_tmp,
1354 REND_DESC_COOKIE_LEN);
1355 if (strmap_get(parsed, auth->onion_address)) {
1356 log_warn(LD_CONFIG, "Duplicate authorization for the same hidden "
1357 "service.");
1358 goto err;
1360 strmap_set(parsed, auth->onion_address, auth);
1361 auth = NULL;
1363 res = 0;
1364 goto done;
1365 err:
1366 res = -1;
1367 done:
1368 rend_service_authorization_free(auth);
1369 SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
1370 smartlist_free(sl);
1371 if (!validate_only && res == 0) {
1372 rend_service_authorization_free_all();
1373 auth_hid_servs = parsed;
1374 } else {
1375 strmap_free(parsed, rend_service_authorization_strmap_item_free);
1377 memwipe(descriptor_cookie_tmp, 0, sizeof(descriptor_cookie_tmp));
1378 memwipe(descriptor_cookie_base64ext, 0, sizeof(descriptor_cookie_base64ext));
1379 return res;