Merge commit 'karsten/fix-1073' into maint-0.2.1
[tor/rransom.git] / src / or / rendclient.c
blob13e43c87b7c0592dd95fce60b7f8a068fd150958
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2009, 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"
12 /** Called when we've established a circuit to an introduction point:
13 * send the introduction request. */
14 void
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.
27 static int
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);
37 return -1;
39 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
40 RELAY_COMMAND_ESTABLISH_RENDEZVOUS,
41 circ->rend_data->rend_cookie,
42 REND_COOKIE_LEN,
43 circ->cpath->prev)<0) {
44 /* circ is already marked for close */
45 log_warn(LD_GENERAL, "Couldn't send ESTABLISH_RENDEZVOUS cell");
46 return -1;
49 return 0;
52 /** Called when we're trying to connect an ap conn; sends an INTRODUCE1 cell
53 * down introcirc if possible.
55 int
56 rend_client_send_introduction(origin_circuit_t *introcirc,
57 origin_circuit_t *rendcirc)
59 size_t payload_len;
60 int r, v3_shift = 0;
61 char payload[RELAY_PAYLOAD_SIZE];
62 char tmp[RELAY_PAYLOAD_SIZE];
63 rend_cache_entry_t *entry;
64 crypt_path_t *cpath;
65 off_t dh_offset;
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,
76 &entry) < 1) {
77 log_warn(LD_REND,
78 "query %s didn't have valid rend desc in cache. Failing.",
79 escaped_safe_str(introcirc->rend_data->onion_address));
80 goto err;
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 */
87 intro_key = NULL;
88 SMARTLIST_FOREACH(entry->parsed->intro_nodes, rend_intro_point_t *,
89 intro, {
90 if (!memcmp(introcirc->build_state->chosen_exit->identity_digest,
91 intro->extend_info->identity_digest, DIGEST_LEN)) {
92 intro_key = intro->intro_key;
93 break;
95 });
96 if (!intro_key) {
97 /** XXX This case probably means that the intro point vanished while
98 * we were building a circuit to it. In the future, we should find
99 * out how that happened and whether we should kill the circuits to
100 * removed intro points immediately. See task 1073. */
101 int num_intro_points = smartlist_len(entry->parsed->intro_nodes);
102 if (rend_cache_lookup_entry(introcirc->rend_data->onion_address,
103 0, &entry) > 0) {
104 log_info(LD_REND, "We have both a v0 and a v2 rend desc for this "
105 "service. The v2 desc doesn't contain the introduction "
106 "point (and key) to send an INTRODUCE1/2 cell to this "
107 "introduction point. Assuming the introduction point "
108 "is for v0 rend clients and using the service key "
109 "from the v0 desc instead. (This is probably a bug, "
110 "because we shouldn't even have both a v0 and a v2 "
111 "descriptor for the same service.)");
112 /* See flyspray task 1024. */
113 intro_key = entry->parsed->pk;
114 } else {
115 log_info(LD_REND, "Internal error: could not find intro key; we "
116 "only have a v2 rend desc with %d intro points.",
117 num_intro_points);
118 goto err;
122 if (crypto_pk_get_digest(intro_key, payload)<0) {
123 log_warn(LD_BUG, "Internal error: couldn't hash public key.");
124 goto err;
127 /* Initialize the pending_final_cpath and start the DH handshake. */
128 cpath = rendcirc->build_state->pending_final_cpath;
129 if (!cpath) {
130 cpath = rendcirc->build_state->pending_final_cpath =
131 tor_malloc_zero(sizeof(crypt_path_t));
132 cpath->magic = CRYPT_PATH_MAGIC;
133 if (!(cpath->dh_handshake_state = crypto_dh_new())) {
134 log_warn(LD_BUG, "Internal error: couldn't allocate DH.");
135 goto err;
137 if (crypto_dh_generate_public(cpath->dh_handshake_state)<0) {
138 log_warn(LD_BUG, "Internal error: couldn't generate g^x.");
139 goto err;
143 /* If version is 3, write (optional) auth data and timestamp. */
144 if (entry->parsed->protocols & (1<<3)) {
145 tmp[0] = 3; /* version 3 of the cell format */
146 tmp[1] = (uint8_t)introcirc->rend_data->auth_type; /* auth type, if any */
147 v3_shift = 1;
148 if (introcirc->rend_data->auth_type != REND_NO_AUTH) {
149 set_uint16(tmp+2, htons(REND_DESC_COOKIE_LEN));
150 memcpy(tmp+4, introcirc->rend_data->descriptor_cookie,
151 REND_DESC_COOKIE_LEN);
152 v3_shift += 2+REND_DESC_COOKIE_LEN;
154 set_uint32(tmp+v3_shift+1, htonl((uint32_t)time(NULL)));
155 v3_shift += 4;
156 } /* if version 2 only write version number */
157 else if (entry->parsed->protocols & (1<<2)) {
158 tmp[0] = 2; /* version 2 of the cell format */
161 /* write the remaining items into tmp */
162 if (entry->parsed->protocols & (1<<3) || entry->parsed->protocols & (1<<2)) {
163 /* version 2 format */
164 extend_info_t *extend_info = rendcirc->build_state->chosen_exit;
165 int klen;
166 /* nul pads */
167 set_uint32(tmp+v3_shift+1, tor_addr_to_ipv4h(&extend_info->addr));
168 set_uint16(tmp+v3_shift+5, htons(extend_info->port));
169 memcpy(tmp+v3_shift+7, extend_info->identity_digest, DIGEST_LEN);
170 klen = crypto_pk_asn1_encode(extend_info->onion_key,
171 tmp+v3_shift+7+DIGEST_LEN+2,
172 sizeof(tmp)-(v3_shift+7+DIGEST_LEN+2));
173 set_uint16(tmp+v3_shift+7+DIGEST_LEN, htons(klen));
174 memcpy(tmp+v3_shift+7+DIGEST_LEN+2+klen, rendcirc->rend_data->rend_cookie,
175 REND_COOKIE_LEN);
176 dh_offset = v3_shift+7+DIGEST_LEN+2+klen+REND_COOKIE_LEN;
177 } else {
178 /* Version 0. */
179 strncpy(tmp, rendcirc->build_state->chosen_exit->nickname,
180 (MAX_NICKNAME_LEN+1)); /* nul pads */
181 memcpy(tmp+MAX_NICKNAME_LEN+1, rendcirc->rend_data->rend_cookie,
182 REND_COOKIE_LEN);
183 dh_offset = MAX_NICKNAME_LEN+1+REND_COOKIE_LEN;
186 if (crypto_dh_get_public(cpath->dh_handshake_state, tmp+dh_offset,
187 DH_KEY_LEN)<0) {
188 log_warn(LD_BUG, "Internal error: couldn't extract g^x.");
189 goto err;
192 note_crypto_pk_op(REND_CLIENT);
193 /*XXX maybe give crypto_pk_public_hybrid_encrypt a max_len arg,
194 * to avoid buffer overflows? */
195 r = crypto_pk_public_hybrid_encrypt(intro_key, payload+DIGEST_LEN,
196 tmp,
197 (int)(dh_offset+DH_KEY_LEN),
198 PK_PKCS1_OAEP_PADDING, 0);
199 if (r<0) {
200 log_warn(LD_BUG,"Internal error: hybrid pk encrypt failed.");
201 goto err;
204 payload_len = DIGEST_LEN + r;
205 tor_assert(payload_len <= RELAY_PAYLOAD_SIZE); /* we overran something */
207 log_info(LD_REND, "Sending an INTRODUCE1 cell");
208 if (relay_send_command_from_edge(0, TO_CIRCUIT(introcirc),
209 RELAY_COMMAND_INTRODUCE1,
210 payload, payload_len,
211 introcirc->cpath->prev)<0) {
212 /* introcirc is already marked for close. leave rendcirc alone. */
213 log_warn(LD_BUG, "Couldn't send INTRODUCE1 cell");
214 return -1;
217 /* Now, we wait for an ACK or NAK on this circuit. */
218 introcirc->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT;
220 return 0;
221 err:
222 circuit_mark_for_close(TO_CIRCUIT(introcirc), END_CIRC_REASON_INTERNAL);
223 circuit_mark_for_close(TO_CIRCUIT(rendcirc), END_CIRC_REASON_INTERNAL);
224 return -1;
227 /** Called when a rendezvous circuit is open; sends a establish
228 * rendezvous circuit as appropriate. */
229 void
230 rend_client_rendcirc_has_opened(origin_circuit_t *circ)
232 tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
234 log_info(LD_REND,"rendcirc is open");
236 /* generate a rendezvous cookie, store it in circ */
237 if (rend_client_send_establish_rendezvous(circ) < 0) {
238 return;
242 /** Called when get an ACK or a NAK for a REND_INTRODUCE1 cell.
245 rend_client_introduction_acked(origin_circuit_t *circ,
246 const char *request, size_t request_len)
248 origin_circuit_t *rendcirc;
249 (void) request; // XXXX Use this.
251 if (circ->_base.purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
252 log_warn(LD_PROTOCOL,
253 "Received REND_INTRODUCE_ACK on unexpected circuit %d.",
254 circ->_base.n_circ_id);
255 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
256 return -1;
259 tor_assert(circ->build_state->chosen_exit);
260 tor_assert(circ->rend_data);
262 if (request_len == 0) {
263 /* It's an ACK; the introduction point relayed our introduction request. */
264 /* Locate the rend circ which is waiting to hear about this ack,
265 * and tell it.
267 log_info(LD_REND,"Received ack. Telling rend circ...");
268 rendcirc = circuit_get_by_rend_query_and_purpose(
269 circ->rend_data->onion_address, CIRCUIT_PURPOSE_C_REND_READY);
270 if (rendcirc) { /* remember the ack */
271 rendcirc->_base.purpose = CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED;
272 } else {
273 log_info(LD_REND,"...Found no rend circ. Dropping on the floor.");
275 /* close the circuit: we won't need it anymore. */
276 circ->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCE_ACKED;
277 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
278 } else {
279 /* It's a NAK; the introduction point didn't relay our request. */
280 circ->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
281 /* Remove this intro point from the set of viable introduction
282 * points. If any remain, extend to a new one and try again.
283 * If none remain, refetch the service descriptor.
285 if (rend_client_remove_intro_point(circ->build_state->chosen_exit,
286 circ->rend_data) > 0) {
287 /* There are introduction points left. Re-extend the circuit to
288 * another intro point and try again. */
289 extend_info_t *extend_info;
290 int result;
291 extend_info = rend_client_get_random_intro(circ->rend_data);
292 if (!extend_info) {
293 log_warn(LD_REND, "No introduction points left for %s. Closing.",
294 escaped_safe_str(circ->rend_data->onion_address));
295 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
296 return -1;
298 if (circ->remaining_relay_early_cells) {
299 log_info(LD_REND,
300 "Got nack for %s from %s. Re-extending circ %d, "
301 "this time to %s.",
302 escaped_safe_str(circ->rend_data->onion_address),
303 circ->build_state->chosen_exit->nickname,
304 circ->_base.n_circ_id, extend_info->nickname);
305 result = circuit_extend_to_new_exit(circ, extend_info);
306 } else {
307 log_info(LD_REND,
308 "Got nack for %s from %s. Building a new introduction "
309 "circuit, this time to %s.",
310 escaped_safe_str(circ->rend_data->onion_address),
311 circ->build_state->chosen_exit->nickname,
312 extend_info->nickname);
313 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
314 if (!circuit_launch_by_extend_info(CIRCUIT_PURPOSE_C_INTRODUCING,
315 extend_info,
316 CIRCLAUNCH_IS_INTERNAL)) {
317 log_warn(LD_REND, "Building introduction circuit failed.");
318 result = -1;
319 } else {
320 result = 0;
323 extend_info_free(extend_info);
324 return result;
327 return 0;
330 /** The period for which a hidden service directory cannot be queried for
331 * the same descriptor ID again. */
332 #define REND_HID_SERV_DIR_REQUERY_PERIOD (15 * 60)
334 /** Contains the last request times to hidden service directories for
335 * certain queries; keys are strings consisting of base32-encoded
336 * hidden service directory identities and base32-encoded descriptor IDs;
337 * values are pointers to timestamps of the last requests. */
338 static strmap_t *last_hid_serv_requests = NULL;
340 /** Look up the last request time to hidden service directory <b>hs_dir</b>
341 * for descriptor ID <b>desc_id_base32</b>. If <b>set</b> is non-zero,
342 * assign the current time <b>now</b> and return that. Otherwise, return
343 * the most recent request time, or 0 if no such request has been sent
344 * before. */
345 static time_t
346 lookup_last_hid_serv_request(routerstatus_t *hs_dir,
347 const char *desc_id_base32, time_t now, int set)
349 char hsdir_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
350 char hsdir_desc_comb_id[2 * REND_DESC_ID_V2_LEN_BASE32 + 1];
351 time_t *last_request_ptr;
352 base32_encode(hsdir_id_base32, sizeof(hsdir_id_base32),
353 hs_dir->identity_digest, DIGEST_LEN);
354 tor_snprintf(hsdir_desc_comb_id, sizeof(hsdir_desc_comb_id), "%s%s",
355 hsdir_id_base32, desc_id_base32);
356 if (set) {
357 last_request_ptr = tor_malloc_zero(sizeof(time_t *));
358 *last_request_ptr = now;
359 strmap_set(last_hid_serv_requests, hsdir_desc_comb_id, last_request_ptr);
360 } else
361 last_request_ptr = strmap_get_lc(last_hid_serv_requests,
362 hsdir_desc_comb_id);
363 return (last_request_ptr) ? *last_request_ptr : 0;
366 /** Clean the history of request times to hidden service directories, so that
367 * it does not contain requests older than REND_HID_SERV_DIR_REQUERY_PERIOD
368 * seconds any more. */
369 static void
370 directory_clean_last_hid_serv_requests(void)
372 strmap_iter_t *iter;
373 time_t cutoff = time(NULL) - REND_HID_SERV_DIR_REQUERY_PERIOD;
374 if (!last_hid_serv_requests)
375 last_hid_serv_requests = strmap_new();
376 for (iter = strmap_iter_init(last_hid_serv_requests);
377 !strmap_iter_done(iter); ) {
378 const char *key;
379 void *val;
380 time_t *ent;
381 strmap_iter_get(iter, &key, &val);
382 ent = (time_t *) val;
383 if (*ent < cutoff) {
384 iter = strmap_iter_next_rmv(last_hid_serv_requests, iter);
385 tor_free(ent);
386 } else {
387 iter = strmap_iter_next(last_hid_serv_requests, iter);
392 /** Determine the responsible hidden service directories for <b>desc_id</b>
393 * and fetch the descriptor belonging to that ID from one of them. Only
394 * send a request to hidden service directories that we did not try within
395 * the last REND_HID_SERV_DIR_REQUERY_PERIOD seconds; on success, return 1,
396 * in the case that no hidden service directory is left to ask for the
397 * descriptor, return 0, and in case of a failure -1. <b>query</b> is only
398 * passed for pretty log statements. */
399 static int
400 directory_get_from_hs_dir(const char *desc_id, const rend_data_t *rend_query)
402 smartlist_t *responsible_dirs = smartlist_create();
403 routerstatus_t *hs_dir;
404 char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
405 time_t now = time(NULL);
406 char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
407 tor_assert(desc_id);
408 tor_assert(rend_query);
409 /* Determine responsible dirs. Even if we can't get all we want,
410 * work with the ones we have. If it's empty, we'll notice below. */
411 (int) hid_serv_get_responsible_directories(responsible_dirs, desc_id);
413 base32_encode(desc_id_base32, sizeof(desc_id_base32),
414 desc_id, DIGEST_LEN);
416 /* Only select those hidden service directories to which we did not send
417 * a request recently and for which we have a router descriptor here. */
418 directory_clean_last_hid_serv_requests(); /* Clean request history first. */
420 SMARTLIST_FOREACH(responsible_dirs, routerstatus_t *, dir, {
421 if (lookup_last_hid_serv_request(dir, desc_id_base32, 0, 0) +
422 REND_HID_SERV_DIR_REQUERY_PERIOD >= now ||
423 !router_get_by_digest(dir->identity_digest))
424 SMARTLIST_DEL_CURRENT(responsible_dirs, dir);
427 hs_dir = smartlist_choose(responsible_dirs);
428 smartlist_free(responsible_dirs);
429 if (!hs_dir) {
430 log_info(LD_REND, "Could not pick one of the responsible hidden "
431 "service directories, because we requested them all "
432 "recently without success.");
433 return 0;
436 /* Remember, that we are requesting a descriptor from this hidden service
437 * directory now. */
438 lookup_last_hid_serv_request(hs_dir, desc_id_base32, now, 1);
440 /* Encode descriptor cookie for logging purposes. */
441 if (rend_query->auth_type != REND_NO_AUTH) {
442 if (base64_encode(descriptor_cookie_base64,
443 sizeof(descriptor_cookie_base64),
444 rend_query->descriptor_cookie, REND_DESC_COOKIE_LEN)<0) {
445 log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
446 return 0;
448 /* Remove == signs and newline. */
449 descriptor_cookie_base64[strlen(descriptor_cookie_base64)-3] = '\0';
450 } else {
451 strlcpy(descriptor_cookie_base64, "(none)",
452 sizeof(descriptor_cookie_base64));
455 /* Send fetch request. (Pass query and possibly descriptor cookie so that
456 * they can be written to the directory connection and be referred to when
457 * the response arrives. */
458 directory_initiate_command_routerstatus_rend(hs_dir,
459 DIR_PURPOSE_FETCH_RENDDESC_V2,
460 ROUTER_PURPOSE_GENERAL,
461 1, desc_id_base32, NULL, 0, 0,
462 rend_query);
463 log_info(LD_REND, "Sending fetch request for v2 descriptor for "
464 "service '%s' with descriptor ID '%s', auth type %d, "
465 "and descriptor cookie '%s' to hidden service "
466 "directory '%s' on port %d.",
467 rend_query->onion_address, desc_id_base32,
468 rend_query->auth_type,
469 (rend_query->auth_type == REND_NO_AUTH ? "[none]" :
470 escaped_safe_str(descriptor_cookie_base64)),
471 hs_dir->nickname, hs_dir->dir_port);
472 return 1;
475 /** If we are not currently fetching a rendezvous service descriptor
476 * for the service ID <b>query</b>, start a directory connection to fetch a
477 * new one.
479 void
480 rend_client_refetch_renddesc(const char *query)
482 if (!get_options()->FetchHidServDescriptors)
483 return;
484 log_info(LD_REND, "Fetching rendezvous descriptor for service %s",
485 escaped_safe_str(query));
486 if (connection_get_by_type_state_rendquery(CONN_TYPE_DIR, 0, query, 0)) {
487 log_info(LD_REND,"Would fetch a new renddesc here (for %s), but one is "
488 "already in progress.", escaped_safe_str(query));
489 } else {
490 /* not one already; initiate a dir rend desc lookup */
491 directory_get_from_dirserver(DIR_PURPOSE_FETCH_RENDDESC,
492 ROUTER_PURPOSE_GENERAL, query,
493 PDS_RETRY_IF_NO_SERVERS);
497 /** Start a connection to a hidden service directory to fetch a v2
498 * rendezvous service descriptor for the base32-encoded service ID
499 * <b>query</b>.
501 void
502 rend_client_refetch_v2_renddesc(const rend_data_t *rend_query)
504 char descriptor_id[DIGEST_LEN];
505 int replicas_left_to_try[REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS];
506 int i, tries_left, r;
507 rend_cache_entry_t *e = NULL;
508 time_t now = time(NULL);
509 tor_assert(rend_query);
510 /* Are we configured to fetch descriptors? */
511 if (!get_options()->FetchHidServDescriptors) {
512 log_warn(LD_REND, "We received an onion address for a v2 rendezvous "
513 "service descriptor, but are not fetching service descriptors.");
514 return;
516 /* Before fetching, check if we already have the descriptor here. */
517 r = rend_cache_lookup_entry(rend_query->onion_address, -1, &e);
518 if (r > 0 && now - e->received < NUM_SECONDS_BEFORE_HS_REFETCH) {
519 log_info(LD_REND, "We would fetch a v2 rendezvous descriptor, but we "
520 "already have a fresh copy of that descriptor here. "
521 "Not fetching.");
522 return;
524 log_debug(LD_REND, "Fetching v2 rendezvous descriptor for service %s",
525 safe_str(rend_query->onion_address));
526 /* Randomly iterate over the replicas until a descriptor can be fetched
527 * from one of the consecutive nodes, or no options are left. */
528 tries_left = REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS;
529 for (i = 0; i < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; i++)
530 replicas_left_to_try[i] = i;
531 while (tries_left > 0) {
532 int rand = crypto_rand_int(tries_left);
533 int chosen_replica = replicas_left_to_try[rand];
534 replicas_left_to_try[rand] = replicas_left_to_try[--tries_left];
536 if (rend_compute_v2_desc_id(descriptor_id, rend_query->onion_address,
537 rend_query->auth_type == REND_STEALTH_AUTH ?
538 rend_query->descriptor_cookie : NULL,
539 time(NULL), chosen_replica) < 0) {
540 log_warn(LD_REND, "Internal error: Computing v2 rendezvous "
541 "descriptor ID did not succeed.");
542 return;
544 if (directory_get_from_hs_dir(descriptor_id, rend_query) != 0)
545 return; /* either success or failure, but we're done */
547 /* If we come here, there are no hidden service directories left. */
548 log_info(LD_REND, "Could not pick one of the responsible hidden "
549 "service directories to fetch descriptors, because "
550 "we already tried them all unsuccessfully.");
551 /* Close pending connections (unless a v0 request is still going on). */
552 rend_client_desc_trynow(rend_query->onion_address, 2);
553 return;
556 /** Remove failed_intro from ent. If ent now has no intro points, or
557 * service is unrecognized, then launch a new renddesc fetch.
559 * Return -1 if error, 0 if no intro points remain or service
560 * unrecognized, 1 if recognized and some intro points remain.
563 rend_client_remove_intro_point(extend_info_t *failed_intro,
564 const rend_data_t *rend_query)
566 int i, r;
567 rend_cache_entry_t *ent;
568 connection_t *conn;
570 r = rend_cache_lookup_entry(rend_query->onion_address, -1, &ent);
571 if (r<0) {
572 log_warn(LD_BUG, "Malformed service ID %s.",
573 escaped_safe_str(rend_query->onion_address));
574 return -1;
576 if (r==0) {
577 log_info(LD_REND, "Unknown service %s. Re-fetching descriptor.",
578 escaped_safe_str(rend_query->onion_address));
579 /* Fetch both, v0 and v2 rend descriptors in parallel. Use whichever
580 * arrives first. Exception: When using client authorization, only
581 * fetch v2 descriptors.*/
582 rend_client_refetch_v2_renddesc(rend_query);
583 if (rend_query->auth_type == REND_NO_AUTH)
584 rend_client_refetch_renddesc(rend_query->onion_address);
585 return 0;
588 for (i = 0; i < smartlist_len(ent->parsed->intro_nodes); i++) {
589 rend_intro_point_t *intro = smartlist_get(ent->parsed->intro_nodes, i);
590 if (!memcmp(failed_intro->identity_digest,
591 intro->extend_info->identity_digest, DIGEST_LEN)) {
592 rend_intro_point_free(intro);
593 smartlist_del(ent->parsed->intro_nodes, i);
594 break;
598 if (smartlist_len(ent->parsed->intro_nodes) == 0) {
599 log_info(LD_REND,
600 "No more intro points remain for %s. Re-fetching descriptor.",
601 escaped_safe_str(rend_query->onion_address));
602 /* Fetch both, v0 and v2 rend descriptors in parallel. Use whichever
603 * arrives first. Exception: When using client authorization, only
604 * fetch v2 descriptors.*/
605 rend_client_refetch_v2_renddesc(rend_query);
606 if (rend_query->auth_type == REND_NO_AUTH)
607 rend_client_refetch_renddesc(rend_query->onion_address);
609 /* move all pending streams back to renddesc_wait */
610 while ((conn = connection_get_by_type_state_rendquery(CONN_TYPE_AP,
611 AP_CONN_STATE_CIRCUIT_WAIT,
612 rend_query->onion_address, -1))) {
613 conn->state = AP_CONN_STATE_RENDDESC_WAIT;
616 return 0;
618 log_info(LD_REND,"%d options left for %s.",
619 smartlist_len(ent->parsed->intro_nodes),
620 escaped_safe_str(rend_query->onion_address));
621 return 1;
624 /** Called when we receive a RENDEZVOUS_ESTABLISHED cell; changes the state of
625 * the circuit to C_REND_READY.
628 rend_client_rendezvous_acked(origin_circuit_t *circ, const char *request,
629 size_t request_len)
631 (void) request;
632 (void) request_len;
633 /* we just got an ack for our establish-rendezvous. switch purposes. */
634 if (circ->_base.purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND) {
635 log_warn(LD_PROTOCOL,"Got a rendezvous ack when we weren't expecting one. "
636 "Closing circ.");
637 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
638 return -1;
640 log_info(LD_REND,"Got rendezvous ack. This circuit is now ready for "
641 "rendezvous.");
642 circ->_base.purpose = CIRCUIT_PURPOSE_C_REND_READY;
643 /* XXXX022 This is a pretty brute-force approach. It'd be better to
644 * attach only the connections that are waiting on this circuit, rather
645 * than trying to attach them all. See comments bug 743. */
646 /* If we already have the introduction circuit built, make sure we send
647 * the INTRODUCE cell _now_ */
648 connection_ap_attach_pending();
649 return 0;
652 /** Bob sent us a rendezvous cell; join the circuits. */
654 rend_client_receive_rendezvous(origin_circuit_t *circ, const char *request,
655 size_t request_len)
657 crypt_path_t *hop;
658 char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN];
660 if ((circ->_base.purpose != CIRCUIT_PURPOSE_C_REND_READY &&
661 circ->_base.purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)
662 || !circ->build_state->pending_final_cpath) {
663 log_warn(LD_PROTOCOL,"Got rendezvous2 cell from hidden service, but not "
664 "expecting it. Closing.");
665 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
666 return -1;
669 if (request_len != DH_KEY_LEN+DIGEST_LEN) {
670 log_warn(LD_PROTOCOL,"Incorrect length (%d) on RENDEZVOUS2 cell.",
671 (int)request_len);
672 goto err;
675 log_info(LD_REND,"Got RENDEZVOUS2 cell from hidden service.");
677 /* first DH_KEY_LEN bytes are g^y from bob. Finish the dh handshake...*/
678 tor_assert(circ->build_state);
679 tor_assert(circ->build_state->pending_final_cpath);
680 hop = circ->build_state->pending_final_cpath;
681 tor_assert(hop->dh_handshake_state);
682 if (crypto_dh_compute_secret(hop->dh_handshake_state, request, DH_KEY_LEN,
683 keys, DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
684 log_warn(LD_GENERAL, "Couldn't complete DH handshake.");
685 goto err;
687 /* ... and set up cpath. */
688 if (circuit_init_cpath_crypto(hop, keys+DIGEST_LEN, 0)<0)
689 goto err;
691 /* Check whether the digest is right... */
692 if (memcmp(keys, request+DH_KEY_LEN, DIGEST_LEN)) {
693 log_warn(LD_PROTOCOL, "Incorrect digest of key material.");
694 goto err;
697 crypto_dh_free(hop->dh_handshake_state);
698 hop->dh_handshake_state = NULL;
700 /* All is well. Extend the circuit. */
701 circ->_base.purpose = CIRCUIT_PURPOSE_C_REND_JOINED;
702 hop->state = CPATH_STATE_OPEN;
703 /* set the windows to default. these are the windows
704 * that alice thinks bob has.
706 hop->package_window = CIRCWINDOW_START;
707 hop->deliver_window = CIRCWINDOW_START;
709 onion_append_to_cpath(&circ->cpath, hop);
710 circ->build_state->pending_final_cpath = NULL; /* prevent double-free */
711 /* XXXX022 This is a pretty brute-force approach. It'd be better to
712 * attach only the connections that are waiting on this circuit, rather
713 * than trying to attach them all. See comments bug 743. */
714 connection_ap_attach_pending();
715 return 0;
716 err:
717 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
718 return -1;
721 /** Find all the apconns in state AP_CONN_STATE_RENDDESC_WAIT that
722 * are waiting on query. If there's a working cache entry here
723 * with at least one intro point, move them to the next state. If
724 * <b>rend_version</b> is non-negative, fail connections that have
725 * requested <b>query</b> unless there are still descriptor fetch
726 * requests in progress for other descriptor versions than
727 * <b>rend_version</b>.
729 void
730 rend_client_desc_trynow(const char *query, int rend_version)
732 edge_connection_t *conn;
733 rend_cache_entry_t *entry;
734 time_t now = time(NULL);
736 smartlist_t *conns = get_connection_array();
737 SMARTLIST_FOREACH(conns, connection_t *, _conn,
739 if (_conn->type != CONN_TYPE_AP ||
740 _conn->state != AP_CONN_STATE_RENDDESC_WAIT ||
741 _conn->marked_for_close)
742 continue;
743 conn = TO_EDGE_CONN(_conn);
744 if (!conn->rend_data)
745 continue;
746 if (rend_cmp_service_ids(query, conn->rend_data->onion_address))
747 continue;
748 assert_connection_ok(TO_CONN(conn), now);
749 if (rend_cache_lookup_entry(conn->rend_data->onion_address, -1,
750 &entry) == 1 &&
751 smartlist_len(entry->parsed->intro_nodes) > 0) {
752 /* either this fetch worked, or it failed but there was a
753 * valid entry from before which we should reuse */
754 log_info(LD_REND,"Rend desc is usable. Launching circuits.");
755 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
757 /* restart their timeout values, so they get a fair shake at
758 * connecting to the hidden service. */
759 conn->_base.timestamp_created = now;
760 conn->_base.timestamp_lastread = now;
761 conn->_base.timestamp_lastwritten = now;
763 if (connection_ap_handshake_attach_circuit(conn) < 0) {
764 /* it will never work */
765 log_warn(LD_REND,"Rendezvous attempt failed. Closing.");
766 if (!conn->_base.marked_for_close)
767 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
769 } else { /* 404, or fetch didn't get that far */
770 /* Unless there are requests for another descriptor version pending,
771 * close the connection. */
772 if (rend_version >= 0 &&
773 !connection_get_by_type_state_rendquery(CONN_TYPE_DIR, 0, query,
774 rend_version == 0 ? 2 : 0)) {
775 log_notice(LD_REND,"Closing stream for '%s.onion': hidden service is "
776 "unavailable (try again later).", safe_str(query));
777 connection_mark_unattached_ap(conn, END_STREAM_REASON_RESOLVEFAILED);
783 /** Return a newly allocated extend_info_t* for a randomly chosen introduction
784 * point for the named hidden service. Return NULL if all introduction points
785 * have been tried and failed.
787 extend_info_t *
788 rend_client_get_random_intro(const rend_data_t *rend_query)
790 int i;
791 rend_cache_entry_t *entry;
792 rend_intro_point_t *intro;
793 routerinfo_t *router;
795 if (rend_cache_lookup_entry(rend_query->onion_address, -1, &entry) < 1) {
796 log_warn(LD_REND,
797 "Query '%s' didn't have valid rend desc in cache. Failing.",
798 safe_str(rend_query->onion_address));
799 return NULL;
802 again:
803 if (smartlist_len(entry->parsed->intro_nodes) == 0)
804 return NULL;
806 i = crypto_rand_int(smartlist_len(entry->parsed->intro_nodes));
807 intro = smartlist_get(entry->parsed->intro_nodes, i);
808 /* Do we need to look up the router or is the extend info complete? */
809 if (!intro->extend_info->onion_key) {
810 router = router_get_by_nickname(intro->extend_info->nickname, 0);
811 if (!router) {
812 log_info(LD_REND, "Unknown router with nickname '%s'; trying another.",
813 intro->extend_info->nickname);
814 rend_intro_point_free(intro);
815 smartlist_del(entry->parsed->intro_nodes, i);
816 goto again;
818 extend_info_free(intro->extend_info);
819 intro->extend_info = extend_info_from_router(router);
821 return extend_info_dup(intro->extend_info);
824 /** Client-side authorizations for hidden services; map of onion address to
825 * rend_service_authorization_t*. */
826 static strmap_t *auth_hid_servs = NULL;
828 /** Look up the client-side authorization for the hidden service with
829 * <b>onion_address</b>. Return NULL if no authorization is available for
830 * that address. */
831 rend_service_authorization_t*
832 rend_client_lookup_service_authorization(const char *onion_address)
834 tor_assert(onion_address);
835 if (!auth_hid_servs) return NULL;
836 return strmap_get(auth_hid_servs, onion_address);
839 /** Helper: Free storage held by rend_service_authorization_t. */
840 static void
841 rend_service_authorization_free(rend_service_authorization_t *auth)
843 tor_free(auth);
846 /** Helper for strmap_free. */
847 static void
848 rend_service_authorization_strmap_item_free(void *service_auth)
850 rend_service_authorization_free(service_auth);
853 /** Release all the storage held in auth_hid_servs.
855 void
856 rend_service_authorization_free_all(void)
858 if (!auth_hid_servs) {
859 return;
861 strmap_free(auth_hid_servs, rend_service_authorization_strmap_item_free);
862 auth_hid_servs = NULL;
865 /** Parse <b>config_line</b> as a client-side authorization for a hidden
866 * service and add it to the local map of hidden service authorizations.
867 * Return 0 for success and -1 for failure. */
869 rend_parse_service_authorization(or_options_t *options, int validate_only)
871 config_line_t *line;
872 int res = -1;
873 strmap_t *parsed = strmap_new();
874 smartlist_t *sl = smartlist_create();
875 rend_service_authorization_t *auth = NULL;
877 for (line = options->HidServAuth; line; line = line->next) {
878 char *onion_address, *descriptor_cookie;
879 char descriptor_cookie_tmp[REND_DESC_COOKIE_LEN+2];
880 char descriptor_cookie_base64ext[REND_DESC_COOKIE_LEN_BASE64+2+1];
881 int auth_type_val = 0;
882 auth = NULL;
883 SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
884 smartlist_clear(sl);
885 smartlist_split_string(sl, line->value, " ",
886 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
887 if (smartlist_len(sl) < 2) {
888 log_warn(LD_CONFIG, "Configuration line does not consist of "
889 "\"onion-address authorization-cookie [service-name]\": "
890 "'%s'", line->value);
891 goto err;
893 auth = tor_malloc_zero(sizeof(rend_service_authorization_t));
894 /* Parse onion address. */
895 onion_address = smartlist_get(sl, 0);
896 if (strlen(onion_address) != REND_SERVICE_ADDRESS_LEN ||
897 strcmpend(onion_address, ".onion")) {
898 log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
899 onion_address);
900 goto err;
902 strlcpy(auth->onion_address, onion_address, REND_SERVICE_ID_LEN_BASE32+1);
903 if (!rend_valid_service_id(auth->onion_address)) {
904 log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
905 onion_address);
906 goto err;
908 /* Parse descriptor cookie. */
909 descriptor_cookie = smartlist_get(sl, 1);
910 if (strlen(descriptor_cookie) != REND_DESC_COOKIE_LEN_BASE64) {
911 log_warn(LD_CONFIG, "Authorization cookie has wrong length: '%s'",
912 descriptor_cookie);
913 goto err;
915 /* Add trailing zero bytes (AA) to make base64-decoding happy. */
916 tor_snprintf(descriptor_cookie_base64ext,
917 REND_DESC_COOKIE_LEN_BASE64+2+1,
918 "%sAA", descriptor_cookie);
919 if (base64_decode(descriptor_cookie_tmp, sizeof(descriptor_cookie_tmp),
920 descriptor_cookie_base64ext,
921 strlen(descriptor_cookie_base64ext)) < 0) {
922 log_warn(LD_CONFIG, "Decoding authorization cookie failed: '%s'",
923 descriptor_cookie);
924 goto err;
926 auth_type_val = (descriptor_cookie_tmp[16] >> 4) + 1;
927 if (auth_type_val < 1 || auth_type_val > 2) {
928 log_warn(LD_CONFIG, "Authorization cookie has unknown authorization "
929 "type encoded.");
930 goto err;
932 auth->auth_type = auth_type_val == 1 ? REND_BASIC_AUTH : REND_STEALTH_AUTH;
933 memcpy(auth->descriptor_cookie, descriptor_cookie_tmp,
934 REND_DESC_COOKIE_LEN);
935 if (strmap_get(parsed, auth->onion_address)) {
936 log_warn(LD_CONFIG, "Duplicate authorization for the same hidden "
937 "service.");
938 goto err;
940 strmap_set(parsed, auth->onion_address, auth);
941 auth = NULL;
943 res = 0;
944 goto done;
945 err:
946 res = -1;
947 done:
948 if (auth)
949 rend_service_authorization_free(auth);
950 SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
951 smartlist_free(sl);
952 if (!validate_only && res == 0) {
953 rend_service_authorization_free_all();
954 auth_hid_servs = parsed;
955 } else {
956 strmap_free(parsed, rend_service_authorization_strmap_item_free);
958 return res;