Merge remote branch 'public/bug1859_021' into maint-0.2.1
[tor/rransom.git] / src / or / rendclient.c
blobaf91099fcbb6ce5b46c54209b3e9cf64d0038a6d
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2011, 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(DH_TYPE_REND))) {
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 sizeof(payload)-DIGEST_LEN,
197 tmp,
198 (int)(dh_offset+DH_KEY_LEN),
199 PK_PKCS1_OAEP_PADDING, 0);
200 if (r<0) {
201 log_warn(LD_BUG,"Internal error: hybrid pk encrypt failed.");
202 goto err;
205 payload_len = DIGEST_LEN + r;
206 tor_assert(payload_len <= RELAY_PAYLOAD_SIZE); /* we overran something */
208 log_info(LD_REND, "Sending an INTRODUCE1 cell");
209 if (relay_send_command_from_edge(0, TO_CIRCUIT(introcirc),
210 RELAY_COMMAND_INTRODUCE1,
211 payload, payload_len,
212 introcirc->cpath->prev)<0) {
213 /* introcirc is already marked for close. leave rendcirc alone. */
214 log_warn(LD_BUG, "Couldn't send INTRODUCE1 cell");
215 return -1;
218 /* Now, we wait for an ACK or NAK on this circuit. */
219 introcirc->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT;
221 return 0;
222 err:
223 circuit_mark_for_close(TO_CIRCUIT(introcirc), END_CIRC_REASON_INTERNAL);
224 circuit_mark_for_close(TO_CIRCUIT(rendcirc), END_CIRC_REASON_INTERNAL);
225 return -1;
228 /** Called when a rendezvous circuit is open; sends a establish
229 * rendezvous circuit as appropriate. */
230 void
231 rend_client_rendcirc_has_opened(origin_circuit_t *circ)
233 tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
235 log_info(LD_REND,"rendcirc is open");
237 /* generate a rendezvous cookie, store it in circ */
238 if (rend_client_send_establish_rendezvous(circ) < 0) {
239 return;
243 /** Called when get an ACK or a NAK for a REND_INTRODUCE1 cell.
246 rend_client_introduction_acked(origin_circuit_t *circ,
247 const uint8_t *request, size_t request_len)
249 origin_circuit_t *rendcirc;
250 (void) request; // XXXX Use this.
252 if (circ->_base.purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
253 log_warn(LD_PROTOCOL,
254 "Received REND_INTRODUCE_ACK on unexpected circuit %d.",
255 circ->_base.n_circ_id);
256 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
257 return -1;
260 tor_assert(circ->build_state->chosen_exit);
261 tor_assert(circ->rend_data);
263 if (request_len == 0) {
264 /* It's an ACK; the introduction point relayed our introduction request. */
265 /* Locate the rend circ which is waiting to hear about this ack,
266 * and tell it.
268 log_info(LD_REND,"Received ack. Telling rend circ...");
269 rendcirc = circuit_get_by_rend_query_and_purpose(
270 circ->rend_data->onion_address, CIRCUIT_PURPOSE_C_REND_READY);
271 if (rendcirc) { /* remember the ack */
272 rendcirc->_base.purpose = CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED;
273 } else {
274 log_info(LD_REND,"...Found no rend circ. Dropping on the floor.");
276 /* close the circuit: we won't need it anymore. */
277 circ->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCE_ACKED;
278 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
279 } else {
280 /* It's a NAK; the introduction point didn't relay our request. */
281 circ->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
282 /* Remove this intro point from the set of viable introduction
283 * points. If any remain, extend to a new one and try again.
284 * If none remain, refetch the service descriptor.
286 if (rend_client_remove_intro_point(circ->build_state->chosen_exit,
287 circ->rend_data) > 0) {
288 /* There are introduction points left. Re-extend the circuit to
289 * another intro point and try again. */
290 extend_info_t *extend_info;
291 int result;
292 extend_info = rend_client_get_random_intro(circ->rend_data);
293 if (!extend_info) {
294 log_warn(LD_REND, "No introduction points left for %s. Closing.",
295 escaped_safe_str(circ->rend_data->onion_address));
296 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
297 return -1;
299 if (circ->remaining_relay_early_cells) {
300 log_info(LD_REND,
301 "Got nack for %s from %s. Re-extending circ %d, "
302 "this time to %s.",
303 escaped_safe_str(circ->rend_data->onion_address),
304 circ->build_state->chosen_exit->nickname,
305 circ->_base.n_circ_id, extend_info->nickname);
306 result = circuit_extend_to_new_exit(circ, extend_info);
307 } else {
308 log_info(LD_REND,
309 "Got nack for %s from %s. Building a new introduction "
310 "circuit, this time to %s.",
311 escaped_safe_str(circ->rend_data->onion_address),
312 circ->build_state->chosen_exit->nickname,
313 extend_info->nickname);
314 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
315 if (!circuit_launch_by_extend_info(CIRCUIT_PURPOSE_C_INTRODUCING,
316 extend_info,
317 CIRCLAUNCH_IS_INTERNAL)) {
318 log_warn(LD_REND, "Building introduction circuit failed.");
319 result = -1;
320 } else {
321 result = 0;
324 extend_info_free(extend_info);
325 return result;
328 return 0;
331 /** The period for which a hidden service directory cannot be queried for
332 * the same descriptor ID again. */
333 #define REND_HID_SERV_DIR_REQUERY_PERIOD (15 * 60)
335 /** Contains the last request times to hidden service directories for
336 * certain queries; keys are strings consisting of base32-encoded
337 * hidden service directory identities and base32-encoded descriptor IDs;
338 * values are pointers to timestamps of the last requests. */
339 static strmap_t *last_hid_serv_requests = NULL;
341 /** Look up the last request time to hidden service directory <b>hs_dir</b>
342 * for descriptor ID <b>desc_id_base32</b>. If <b>set</b> is non-zero,
343 * assign the current time <b>now</b> and return that. Otherwise, return
344 * the most recent request time, or 0 if no such request has been sent
345 * before. */
346 static time_t
347 lookup_last_hid_serv_request(routerstatus_t *hs_dir,
348 const char *desc_id_base32, time_t now, int set)
350 char hsdir_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
351 char hsdir_desc_comb_id[2 * REND_DESC_ID_V2_LEN_BASE32 + 1];
352 time_t *last_request_ptr;
353 base32_encode(hsdir_id_base32, sizeof(hsdir_id_base32),
354 hs_dir->identity_digest, DIGEST_LEN);
355 tor_snprintf(hsdir_desc_comb_id, sizeof(hsdir_desc_comb_id), "%s%s",
356 hsdir_id_base32, desc_id_base32);
357 if (set) {
358 time_t *oldptr;
359 last_request_ptr = tor_malloc_zero(sizeof(time_t));
360 *last_request_ptr = now;
361 oldptr = strmap_set(last_hid_serv_requests, hsdir_desc_comb_id,
362 last_request_ptr);
363 tor_free(oldptr);
364 } else
365 last_request_ptr = strmap_get_lc(last_hid_serv_requests,
366 hsdir_desc_comb_id);
367 return (last_request_ptr) ? *last_request_ptr : 0;
370 /** Clean the history of request times to hidden service directories, so that
371 * it does not contain requests older than REND_HID_SERV_DIR_REQUERY_PERIOD
372 * seconds any more. */
373 static void
374 directory_clean_last_hid_serv_requests(void)
376 strmap_iter_t *iter;
377 time_t cutoff = time(NULL) - REND_HID_SERV_DIR_REQUERY_PERIOD;
378 if (!last_hid_serv_requests)
379 last_hid_serv_requests = strmap_new();
380 for (iter = strmap_iter_init(last_hid_serv_requests);
381 !strmap_iter_done(iter); ) {
382 const char *key;
383 void *val;
384 time_t *ent;
385 strmap_iter_get(iter, &key, &val);
386 ent = (time_t *) val;
387 if (*ent < cutoff) {
388 iter = strmap_iter_next_rmv(last_hid_serv_requests, iter);
389 tor_free(ent);
390 } else {
391 iter = strmap_iter_next(last_hid_serv_requests, iter);
396 /** Determine the responsible hidden service directories for <b>desc_id</b>
397 * and fetch the descriptor belonging to that ID from one of them. Only
398 * send a request to hidden service directories that we did not try within
399 * the last REND_HID_SERV_DIR_REQUERY_PERIOD seconds; on success, return 1,
400 * in the case that no hidden service directory is left to ask for the
401 * descriptor, return 0, and in case of a failure -1. <b>query</b> is only
402 * passed for pretty log statements. */
403 static int
404 directory_get_from_hs_dir(const char *desc_id, const rend_data_t *rend_query)
406 smartlist_t *responsible_dirs = smartlist_create();
407 routerstatus_t *hs_dir;
408 char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
409 time_t now = time(NULL);
410 char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
411 tor_assert(desc_id);
412 tor_assert(rend_query);
413 /* Determine responsible dirs. Even if we can't get all we want,
414 * work with the ones we have. If it's empty, we'll notice below. */
415 (int) hid_serv_get_responsible_directories(responsible_dirs, desc_id);
417 base32_encode(desc_id_base32, sizeof(desc_id_base32),
418 desc_id, DIGEST_LEN);
420 /* Only select those hidden service directories to which we did not send
421 * a request recently and for which we have a router descriptor here. */
422 directory_clean_last_hid_serv_requests(); /* Clean request history first. */
424 SMARTLIST_FOREACH(responsible_dirs, routerstatus_t *, dir, {
425 if (lookup_last_hid_serv_request(dir, desc_id_base32, 0, 0) +
426 REND_HID_SERV_DIR_REQUERY_PERIOD >= now ||
427 !router_get_by_digest(dir->identity_digest))
428 SMARTLIST_DEL_CURRENT(responsible_dirs, dir);
431 hs_dir = smartlist_choose(responsible_dirs);
432 smartlist_free(responsible_dirs);
433 if (!hs_dir) {
434 log_info(LD_REND, "Could not pick one of the responsible hidden "
435 "service directories, because we requested them all "
436 "recently without success.");
437 return 0;
440 /* Remember, that we are requesting a descriptor from this hidden service
441 * directory now. */
442 lookup_last_hid_serv_request(hs_dir, desc_id_base32, now, 1);
444 /* Encode descriptor cookie for logging purposes. */
445 if (rend_query->auth_type != REND_NO_AUTH) {
446 if (base64_encode(descriptor_cookie_base64,
447 sizeof(descriptor_cookie_base64),
448 rend_query->descriptor_cookie, REND_DESC_COOKIE_LEN)<0) {
449 log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
450 return 0;
452 /* Remove == signs and newline. */
453 descriptor_cookie_base64[strlen(descriptor_cookie_base64)-3] = '\0';
454 } else {
455 strlcpy(descriptor_cookie_base64, "(none)",
456 sizeof(descriptor_cookie_base64));
459 /* Send fetch request. (Pass query and possibly descriptor cookie so that
460 * they can be written to the directory connection and be referred to when
461 * the response arrives. */
462 directory_initiate_command_routerstatus_rend(hs_dir,
463 DIR_PURPOSE_FETCH_RENDDESC_V2,
464 ROUTER_PURPOSE_GENERAL,
465 1, desc_id_base32, NULL, 0, 0,
466 rend_query);
467 log_info(LD_REND, "Sending fetch request for v2 descriptor for "
468 "service '%s' with descriptor ID '%s', auth type %d, "
469 "and descriptor cookie '%s' to hidden service "
470 "directory '%s' on port %d.",
471 rend_query->onion_address, desc_id_base32,
472 rend_query->auth_type,
473 (rend_query->auth_type == REND_NO_AUTH ? "[none]" :
474 escaped_safe_str(descriptor_cookie_base64)),
475 hs_dir->nickname, hs_dir->dir_port);
476 return 1;
479 /** If we are not currently fetching a rendezvous service descriptor
480 * for the service ID <b>query</b>, start a directory connection to fetch a
481 * new one.
483 void
484 rend_client_refetch_renddesc(const char *query)
486 if (!get_options()->FetchHidServDescriptors)
487 return;
488 log_info(LD_REND, "Fetching rendezvous descriptor for service %s",
489 escaped_safe_str(query));
490 if (connection_get_by_type_state_rendquery(CONN_TYPE_DIR, 0, query, 0)) {
491 log_info(LD_REND,"Would fetch a new renddesc here (for %s), but one is "
492 "already in progress.", escaped_safe_str(query));
493 } else {
494 /* not one already; initiate a dir rend desc lookup */
495 directory_get_from_dirserver(DIR_PURPOSE_FETCH_RENDDESC,
496 ROUTER_PURPOSE_GENERAL, query,
497 PDS_RETRY_IF_NO_SERVERS);
501 /** Start a connection to a hidden service directory to fetch a v2
502 * rendezvous service descriptor for the base32-encoded service ID
503 * <b>query</b>.
505 void
506 rend_client_refetch_v2_renddesc(const rend_data_t *rend_query)
508 char descriptor_id[DIGEST_LEN];
509 int replicas_left_to_try[REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS];
510 int i, tries_left, r;
511 rend_cache_entry_t *e = NULL;
512 time_t now = time(NULL);
513 tor_assert(rend_query);
514 /* Are we configured to fetch descriptors? */
515 if (!get_options()->FetchHidServDescriptors) {
516 log_warn(LD_REND, "We received an onion address for a v2 rendezvous "
517 "service descriptor, but are not fetching service descriptors.");
518 return;
520 /* Before fetching, check if we already have the descriptor here. */
521 r = rend_cache_lookup_entry(rend_query->onion_address, -1, &e);
522 if (r > 0 && now - e->received < NUM_SECONDS_BEFORE_HS_REFETCH) {
523 log_info(LD_REND, "We would fetch a v2 rendezvous descriptor, but we "
524 "already have a fresh copy of that descriptor here. "
525 "Not fetching.");
526 return;
528 log_debug(LD_REND, "Fetching v2 rendezvous descriptor for service %s",
529 safe_str(rend_query->onion_address));
530 /* Randomly iterate over the replicas until a descriptor can be fetched
531 * from one of the consecutive nodes, or no options are left. */
532 tries_left = REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS;
533 for (i = 0; i < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; i++)
534 replicas_left_to_try[i] = i;
535 while (tries_left > 0) {
536 int rand = crypto_rand_int(tries_left);
537 int chosen_replica = replicas_left_to_try[rand];
538 replicas_left_to_try[rand] = replicas_left_to_try[--tries_left];
540 if (rend_compute_v2_desc_id(descriptor_id, rend_query->onion_address,
541 rend_query->auth_type == REND_STEALTH_AUTH ?
542 rend_query->descriptor_cookie : NULL,
543 time(NULL), chosen_replica) < 0) {
544 log_warn(LD_REND, "Internal error: Computing v2 rendezvous "
545 "descriptor ID did not succeed.");
546 return;
548 if (directory_get_from_hs_dir(descriptor_id, rend_query) != 0)
549 return; /* either success or failure, but we're done */
551 /* If we come here, there are no hidden service directories left. */
552 log_info(LD_REND, "Could not pick one of the responsible hidden "
553 "service directories to fetch descriptors, because "
554 "we already tried them all unsuccessfully.");
555 /* Close pending connections (unless a v0 request is still going on). */
556 rend_client_desc_trynow(rend_query->onion_address, 2);
557 return;
560 /** Remove failed_intro from ent. If ent now has no intro points, or
561 * service is unrecognized, then launch a new renddesc fetch.
563 * Return -1 if error, 0 if no intro points remain or service
564 * unrecognized, 1 if recognized and some intro points remain.
567 rend_client_remove_intro_point(extend_info_t *failed_intro,
568 const rend_data_t *rend_query)
570 int i, r;
571 rend_cache_entry_t *ent;
572 connection_t *conn;
574 r = rend_cache_lookup_entry(rend_query->onion_address, -1, &ent);
575 if (r<0) {
576 log_warn(LD_BUG, "Malformed service ID %s.",
577 escaped_safe_str(rend_query->onion_address));
578 return -1;
580 if (r==0) {
581 log_info(LD_REND, "Unknown service %s. Re-fetching descriptor.",
582 escaped_safe_str(rend_query->onion_address));
583 /* Fetch both, v0 and v2 rend descriptors in parallel. Use whichever
584 * arrives first. Exception: When using client authorization, only
585 * fetch v2 descriptors.*/
586 rend_client_refetch_v2_renddesc(rend_query);
587 if (rend_query->auth_type == REND_NO_AUTH)
588 rend_client_refetch_renddesc(rend_query->onion_address);
589 return 0;
592 for (i = 0; i < smartlist_len(ent->parsed->intro_nodes); i++) {
593 rend_intro_point_t *intro = smartlist_get(ent->parsed->intro_nodes, i);
594 if (!memcmp(failed_intro->identity_digest,
595 intro->extend_info->identity_digest, DIGEST_LEN)) {
596 rend_intro_point_free(intro);
597 smartlist_del(ent->parsed->intro_nodes, i);
598 break;
602 if (smartlist_len(ent->parsed->intro_nodes) == 0) {
603 log_info(LD_REND,
604 "No more intro points remain for %s. Re-fetching descriptor.",
605 escaped_safe_str(rend_query->onion_address));
606 /* Fetch both, v0 and v2 rend descriptors in parallel. Use whichever
607 * arrives first. Exception: When using client authorization, only
608 * fetch v2 descriptors.*/
609 rend_client_refetch_v2_renddesc(rend_query);
610 if (rend_query->auth_type == REND_NO_AUTH)
611 rend_client_refetch_renddesc(rend_query->onion_address);
613 /* move all pending streams back to renddesc_wait */
614 while ((conn = connection_get_by_type_state_rendquery(CONN_TYPE_AP,
615 AP_CONN_STATE_CIRCUIT_WAIT,
616 rend_query->onion_address, -1))) {
617 conn->state = AP_CONN_STATE_RENDDESC_WAIT;
620 return 0;
622 log_info(LD_REND,"%d options left for %s.",
623 smartlist_len(ent->parsed->intro_nodes),
624 escaped_safe_str(rend_query->onion_address));
625 return 1;
628 /** Called when we receive a RENDEZVOUS_ESTABLISHED cell; changes the state of
629 * the circuit to C_REND_READY.
632 rend_client_rendezvous_acked(origin_circuit_t *circ, const uint8_t *request,
633 size_t request_len)
635 (void) request;
636 (void) request_len;
637 /* we just got an ack for our establish-rendezvous. switch purposes. */
638 if (circ->_base.purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND) {
639 log_warn(LD_PROTOCOL,"Got a rendezvous ack when we weren't expecting one. "
640 "Closing circ.");
641 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
642 return -1;
644 log_info(LD_REND,"Got rendezvous ack. This circuit is now ready for "
645 "rendezvous.");
646 circ->_base.purpose = CIRCUIT_PURPOSE_C_REND_READY;
647 /* XXXX022 This is a pretty brute-force approach. It'd be better to
648 * attach only the connections that are waiting on this circuit, rather
649 * than trying to attach them all. See comments bug 743. */
650 /* If we already have the introduction circuit built, make sure we send
651 * the INTRODUCE cell _now_ */
652 connection_ap_attach_pending();
653 return 0;
656 /** Bob sent us a rendezvous cell; join the circuits. */
658 rend_client_receive_rendezvous(origin_circuit_t *circ, const uint8_t *request,
659 size_t request_len)
661 crypt_path_t *hop;
662 char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN];
664 if ((circ->_base.purpose != CIRCUIT_PURPOSE_C_REND_READY &&
665 circ->_base.purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)
666 || !circ->build_state->pending_final_cpath) {
667 log_warn(LD_PROTOCOL,"Got rendezvous2 cell from hidden service, but not "
668 "expecting it. Closing.");
669 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
670 return -1;
673 if (request_len != DH_KEY_LEN+DIGEST_LEN) {
674 log_warn(LD_PROTOCOL,"Incorrect length (%d) on RENDEZVOUS2 cell.",
675 (int)request_len);
676 goto err;
679 log_info(LD_REND,"Got RENDEZVOUS2 cell from hidden service.");
681 /* first DH_KEY_LEN bytes are g^y from bob. Finish the dh handshake...*/
682 tor_assert(circ->build_state);
683 tor_assert(circ->build_state->pending_final_cpath);
684 hop = circ->build_state->pending_final_cpath;
685 tor_assert(hop->dh_handshake_state);
686 if (crypto_dh_compute_secret(hop->dh_handshake_state, (char*)request,
687 DH_KEY_LEN,
688 keys, DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
689 log_warn(LD_GENERAL, "Couldn't complete DH handshake.");
690 goto err;
692 /* ... and set up cpath. */
693 if (circuit_init_cpath_crypto(hop, keys+DIGEST_LEN, 0)<0)
694 goto err;
696 /* Check whether the digest is right... */
697 if (memcmp(keys, request+DH_KEY_LEN, DIGEST_LEN)) {
698 log_warn(LD_PROTOCOL, "Incorrect digest of key material.");
699 goto err;
702 crypto_dh_free(hop->dh_handshake_state);
703 hop->dh_handshake_state = NULL;
705 /* All is well. Extend the circuit. */
706 circ->_base.purpose = CIRCUIT_PURPOSE_C_REND_JOINED;
707 hop->state = CPATH_STATE_OPEN;
708 /* set the windows to default. these are the windows
709 * that alice thinks bob has.
711 hop->package_window = circuit_initial_package_window();
712 hop->deliver_window = CIRCWINDOW_START;
714 onion_append_to_cpath(&circ->cpath, hop);
715 circ->build_state->pending_final_cpath = NULL; /* prevent double-free */
716 /* XXXX022 This is a pretty brute-force approach. It'd be better to
717 * attach only the connections that are waiting on this circuit, rather
718 * than trying to attach them all. See comments bug 743. */
719 connection_ap_attach_pending();
720 memset(keys, 0, sizeof(keys));
721 return 0;
722 err:
723 memset(keys, 0, sizeof(keys));
724 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
725 return -1;
728 /** Find all the apconns in state AP_CONN_STATE_RENDDESC_WAIT that
729 * are waiting on query. If there's a working cache entry here
730 * with at least one intro point, move them to the next state. If
731 * <b>rend_version</b> is non-negative, fail connections that have
732 * requested <b>query</b> unless there are still descriptor fetch
733 * requests in progress for other descriptor versions than
734 * <b>rend_version</b>.
736 void
737 rend_client_desc_trynow(const char *query, int rend_version)
739 edge_connection_t *conn;
740 rend_cache_entry_t *entry;
741 time_t now = time(NULL);
743 smartlist_t *conns = get_connection_array();
744 SMARTLIST_FOREACH(conns, connection_t *, _conn,
746 if (_conn->type != CONN_TYPE_AP ||
747 _conn->state != AP_CONN_STATE_RENDDESC_WAIT ||
748 _conn->marked_for_close)
749 continue;
750 conn = TO_EDGE_CONN(_conn);
751 if (!conn->rend_data)
752 continue;
753 if (rend_cmp_service_ids(query, conn->rend_data->onion_address))
754 continue;
755 assert_connection_ok(TO_CONN(conn), now);
756 if (rend_cache_lookup_entry(conn->rend_data->onion_address, -1,
757 &entry) == 1 &&
758 smartlist_len(entry->parsed->intro_nodes) > 0) {
759 /* either this fetch worked, or it failed but there was a
760 * valid entry from before which we should reuse */
761 log_info(LD_REND,"Rend desc is usable. Launching circuits.");
762 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
764 /* restart their timeout values, so they get a fair shake at
765 * connecting to the hidden service. */
766 conn->_base.timestamp_created = now;
767 conn->_base.timestamp_lastread = now;
768 conn->_base.timestamp_lastwritten = now;
770 if (connection_ap_handshake_attach_circuit(conn) < 0) {
771 /* it will never work */
772 log_warn(LD_REND,"Rendezvous attempt failed. Closing.");
773 if (!conn->_base.marked_for_close)
774 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
776 } else { /* 404, or fetch didn't get that far */
777 /* Unless there are requests for another descriptor version pending,
778 * close the connection. */
779 if (rend_version >= 0 &&
780 !connection_get_by_type_state_rendquery(CONN_TYPE_DIR, 0, query,
781 rend_version == 0 ? 2 : 0)) {
782 log_notice(LD_REND,"Closing stream for '%s.onion': hidden service is "
783 "unavailable (try again later).", safe_str(query));
784 connection_mark_unattached_ap(conn, END_STREAM_REASON_RESOLVEFAILED);
790 /** Return a newly allocated extend_info_t* for a randomly chosen introduction
791 * point for the named hidden service. Return NULL if all introduction points
792 * have been tried and failed.
794 extend_info_t *
795 rend_client_get_random_intro(const rend_data_t *rend_query)
797 int i;
798 rend_cache_entry_t *entry;
799 rend_intro_point_t *intro;
800 routerinfo_t *router;
802 if (rend_cache_lookup_entry(rend_query->onion_address, -1, &entry) < 1) {
803 log_warn(LD_REND,
804 "Query '%s' didn't have valid rend desc in cache. Failing.",
805 safe_str(rend_query->onion_address));
806 return NULL;
809 again:
810 if (smartlist_len(entry->parsed->intro_nodes) == 0)
811 return NULL;
813 i = crypto_rand_int(smartlist_len(entry->parsed->intro_nodes));
814 intro = smartlist_get(entry->parsed->intro_nodes, i);
815 /* Do we need to look up the router or is the extend info complete? */
816 if (!intro->extend_info->onion_key) {
817 if (tor_digest_is_zero(intro->extend_info->identity_digest))
818 router = router_get_by_hexdigest(intro->extend_info->nickname);
819 else
820 router = router_get_by_digest(intro->extend_info->identity_digest);
821 if (!router) {
822 log_info(LD_REND, "Unknown router with nickname '%s'; trying another.",
823 intro->extend_info->nickname);
824 rend_intro_point_free(intro);
825 smartlist_del(entry->parsed->intro_nodes, i);
826 goto again;
828 extend_info_free(intro->extend_info);
829 intro->extend_info = extend_info_from_router(router);
831 return extend_info_dup(intro->extend_info);
834 /** Client-side authorizations for hidden services; map of onion address to
835 * rend_service_authorization_t*. */
836 static strmap_t *auth_hid_servs = NULL;
838 /** Look up the client-side authorization for the hidden service with
839 * <b>onion_address</b>. Return NULL if no authorization is available for
840 * that address. */
841 rend_service_authorization_t*
842 rend_client_lookup_service_authorization(const char *onion_address)
844 tor_assert(onion_address);
845 if (!auth_hid_servs) return NULL;
846 return strmap_get(auth_hid_servs, onion_address);
849 /** Helper: Free storage held by rend_service_authorization_t. */
850 static void
851 rend_service_authorization_free(rend_service_authorization_t *auth)
853 tor_free(auth);
856 /** Helper for strmap_free. */
857 static void
858 rend_service_authorization_strmap_item_free(void *service_auth)
860 rend_service_authorization_free(service_auth);
863 /** Release all the storage held in auth_hid_servs.
865 void
866 rend_service_authorization_free_all(void)
868 if (!auth_hid_servs) {
869 return;
871 strmap_free(auth_hid_servs, rend_service_authorization_strmap_item_free);
872 auth_hid_servs = NULL;
875 /** Parse <b>config_line</b> as a client-side authorization for a hidden
876 * service and add it to the local map of hidden service authorizations.
877 * Return 0 for success and -1 for failure. */
879 rend_parse_service_authorization(or_options_t *options, int validate_only)
881 config_line_t *line;
882 int res = -1;
883 strmap_t *parsed = strmap_new();
884 smartlist_t *sl = smartlist_create();
885 rend_service_authorization_t *auth = NULL;
887 for (line = options->HidServAuth; line; line = line->next) {
888 char *onion_address, *descriptor_cookie;
889 char descriptor_cookie_tmp[REND_DESC_COOKIE_LEN+2];
890 char descriptor_cookie_base64ext[REND_DESC_COOKIE_LEN_BASE64+2+1];
891 int auth_type_val = 0;
892 auth = NULL;
893 SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
894 smartlist_clear(sl);
895 smartlist_split_string(sl, line->value, " ",
896 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
897 if (smartlist_len(sl) < 2) {
898 log_warn(LD_CONFIG, "Configuration line does not consist of "
899 "\"onion-address authorization-cookie [service-name]\": "
900 "'%s'", line->value);
901 goto err;
903 auth = tor_malloc_zero(sizeof(rend_service_authorization_t));
904 /* Parse onion address. */
905 onion_address = smartlist_get(sl, 0);
906 if (strlen(onion_address) != REND_SERVICE_ADDRESS_LEN ||
907 strcmpend(onion_address, ".onion")) {
908 log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
909 onion_address);
910 goto err;
912 strlcpy(auth->onion_address, onion_address, REND_SERVICE_ID_LEN_BASE32+1);
913 if (!rend_valid_service_id(auth->onion_address)) {
914 log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
915 onion_address);
916 goto err;
918 /* Parse descriptor cookie. */
919 descriptor_cookie = smartlist_get(sl, 1);
920 if (strlen(descriptor_cookie) != REND_DESC_COOKIE_LEN_BASE64) {
921 log_warn(LD_CONFIG, "Authorization cookie has wrong length: '%s'",
922 descriptor_cookie);
923 goto err;
925 /* Add trailing zero bytes (AA) to make base64-decoding happy. */
926 tor_snprintf(descriptor_cookie_base64ext,
927 REND_DESC_COOKIE_LEN_BASE64+2+1,
928 "%sAA", descriptor_cookie);
929 if (base64_decode(descriptor_cookie_tmp, sizeof(descriptor_cookie_tmp),
930 descriptor_cookie_base64ext,
931 strlen(descriptor_cookie_base64ext)) < 0) {
932 log_warn(LD_CONFIG, "Decoding authorization cookie failed: '%s'",
933 descriptor_cookie);
934 goto err;
936 auth_type_val = (descriptor_cookie_tmp[16] >> 4) + 1;
937 if (auth_type_val < 1 || auth_type_val > 2) {
938 log_warn(LD_CONFIG, "Authorization cookie has unknown authorization "
939 "type encoded.");
940 goto err;
942 auth->auth_type = auth_type_val == 1 ? REND_BASIC_AUTH : REND_STEALTH_AUTH;
943 memcpy(auth->descriptor_cookie, descriptor_cookie_tmp,
944 REND_DESC_COOKIE_LEN);
945 if (strmap_get(parsed, auth->onion_address)) {
946 log_warn(LD_CONFIG, "Duplicate authorization for the same hidden "
947 "service.");
948 goto err;
950 strmap_set(parsed, auth->onion_address, auth);
951 auth = NULL;
953 res = 0;
954 goto done;
955 err:
956 res = -1;
957 done:
958 if (auth)
959 rend_service_authorization_free(auth);
960 SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
961 smartlist_free(sl);
962 if (!validate_only && res == 0) {
963 rend_service_authorization_free_all();
964 auth_hid_servs = parsed;
965 } else {
966 strmap_free(parsed, rend_service_authorization_strmap_item_free);
968 return res;