Merge remote branch 'origin/maint-0.2.1' into maint-0.2.2
[tor/rransom.git] / src / or / rendclient.c
blobb8526b676d0218caa3b8cbd7b939c98ad24fc54f
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"
11 #include "circuitbuild.h"
12 #include "circuitlist.h"
13 #include "circuituse.h"
14 #include "config.h"
15 #include "connection.h"
16 #include "connection_edge.h"
17 #include "directory.h"
18 #include "main.h"
19 #include "relay.h"
20 #include "rendclient.h"
21 #include "rendcommon.h"
22 #include "rephist.h"
23 #include "routerlist.h"
25 /** Called when we've established a circuit to an introduction point:
26 * send the introduction request. */
27 void
28 rend_client_introcirc_has_opened(origin_circuit_t *circ)
30 tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
31 tor_assert(circ->cpath);
33 log_info(LD_REND,"introcirc is open");
34 connection_ap_attach_pending();
37 /** Send the establish-rendezvous cell along a rendezvous circuit. if
38 * it fails, mark the circ for close and return -1. else return 0.
40 static int
41 rend_client_send_establish_rendezvous(origin_circuit_t *circ)
43 tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
44 tor_assert(circ->rend_data);
45 log_info(LD_REND, "Sending an ESTABLISH_RENDEZVOUS cell");
47 if (crypto_rand(circ->rend_data->rend_cookie, REND_COOKIE_LEN) < 0) {
48 log_warn(LD_BUG, "Internal error: Couldn't produce random cookie.");
49 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
50 return -1;
52 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
53 RELAY_COMMAND_ESTABLISH_RENDEZVOUS,
54 circ->rend_data->rend_cookie,
55 REND_COOKIE_LEN,
56 circ->cpath->prev)<0) {
57 /* circ is already marked for close */
58 log_warn(LD_GENERAL, "Couldn't send ESTABLISH_RENDEZVOUS cell");
59 return -1;
62 return 0;
65 /** Called when we're trying to connect an ap conn; sends an INTRODUCE1 cell
66 * down introcirc if possible.
68 int
69 rend_client_send_introduction(origin_circuit_t *introcirc,
70 origin_circuit_t *rendcirc)
72 size_t payload_len;
73 int r, v3_shift = 0;
74 char payload[RELAY_PAYLOAD_SIZE];
75 char tmp[RELAY_PAYLOAD_SIZE];
76 rend_cache_entry_t *entry;
77 crypt_path_t *cpath;
78 off_t dh_offset;
79 crypto_pk_env_t *intro_key = NULL;
81 tor_assert(introcirc->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
82 tor_assert(rendcirc->_base.purpose == CIRCUIT_PURPOSE_C_REND_READY);
83 tor_assert(introcirc->rend_data);
84 tor_assert(rendcirc->rend_data);
85 tor_assert(!rend_cmp_service_ids(introcirc->rend_data->onion_address,
86 rendcirc->rend_data->onion_address));
88 if (rend_cache_lookup_entry(introcirc->rend_data->onion_address, -1,
89 &entry) < 1) {
90 log_warn(LD_REND,
91 "query %s didn't have valid rend desc in cache. Failing.",
92 escaped_safe_str_client(introcirc->rend_data->onion_address));
93 goto err;
96 /* first 20 bytes of payload are the hash of the intro key */
97 intro_key = NULL;
98 SMARTLIST_FOREACH(entry->parsed->intro_nodes, rend_intro_point_t *,
99 intro, {
100 if (!memcmp(introcirc->build_state->chosen_exit->identity_digest,
101 intro->extend_info->identity_digest, DIGEST_LEN)) {
102 intro_key = intro->intro_key;
103 break;
106 if (!intro_key) {
107 log_info(LD_REND, "Our introduction point knowledge changed in "
108 "mid-connect! Could not find intro key; we only have a "
109 "v2 rend desc with %d intro points. Giving up.",
110 smartlist_len(entry->parsed->intro_nodes));
111 goto err;
113 if (crypto_pk_get_digest(intro_key, payload)<0) {
114 log_warn(LD_BUG, "Internal error: couldn't hash public key.");
115 goto err;
118 /* Initialize the pending_final_cpath and start the DH handshake. */
119 cpath = rendcirc->build_state->pending_final_cpath;
120 if (!cpath) {
121 cpath = rendcirc->build_state->pending_final_cpath =
122 tor_malloc_zero(sizeof(crypt_path_t));
123 cpath->magic = CRYPT_PATH_MAGIC;
124 if (!(cpath->dh_handshake_state = crypto_dh_new())) {
125 log_warn(LD_BUG, "Internal error: couldn't allocate DH.");
126 goto err;
128 if (crypto_dh_generate_public(cpath->dh_handshake_state)<0) {
129 log_warn(LD_BUG, "Internal error: couldn't generate g^x.");
130 goto err;
134 /* If version is 3, write (optional) auth data and timestamp. */
135 if (entry->parsed->protocols & (1<<3)) {
136 tmp[0] = 3; /* version 3 of the cell format */
137 tmp[1] = (uint8_t)introcirc->rend_data->auth_type; /* auth type, if any */
138 v3_shift = 1;
139 if (introcirc->rend_data->auth_type != REND_NO_AUTH) {
140 set_uint16(tmp+2, htons(REND_DESC_COOKIE_LEN));
141 memcpy(tmp+4, introcirc->rend_data->descriptor_cookie,
142 REND_DESC_COOKIE_LEN);
143 v3_shift += 2+REND_DESC_COOKIE_LEN;
145 set_uint32(tmp+v3_shift+1, htonl((uint32_t)time(NULL)));
146 v3_shift += 4;
147 } /* if version 2 only write version number */
148 else if (entry->parsed->protocols & (1<<2)) {
149 tmp[0] = 2; /* version 2 of the cell format */
152 /* write the remaining items into tmp */
153 if (entry->parsed->protocols & (1<<3) || entry->parsed->protocols & (1<<2)) {
154 /* version 2 format */
155 extend_info_t *extend_info = rendcirc->build_state->chosen_exit;
156 int klen;
157 /* nul pads */
158 set_uint32(tmp+v3_shift+1, tor_addr_to_ipv4h(&extend_info->addr));
159 set_uint16(tmp+v3_shift+5, htons(extend_info->port));
160 memcpy(tmp+v3_shift+7, extend_info->identity_digest, DIGEST_LEN);
161 klen = crypto_pk_asn1_encode(extend_info->onion_key,
162 tmp+v3_shift+7+DIGEST_LEN+2,
163 sizeof(tmp)-(v3_shift+7+DIGEST_LEN+2));
164 set_uint16(tmp+v3_shift+7+DIGEST_LEN, htons(klen));
165 memcpy(tmp+v3_shift+7+DIGEST_LEN+2+klen, rendcirc->rend_data->rend_cookie,
166 REND_COOKIE_LEN);
167 dh_offset = v3_shift+7+DIGEST_LEN+2+klen+REND_COOKIE_LEN;
168 } else {
169 /* Version 0. */
170 strncpy(tmp, rendcirc->build_state->chosen_exit->nickname,
171 (MAX_NICKNAME_LEN+1)); /* nul pads */
172 memcpy(tmp+MAX_NICKNAME_LEN+1, rendcirc->rend_data->rend_cookie,
173 REND_COOKIE_LEN);
174 dh_offset = MAX_NICKNAME_LEN+1+REND_COOKIE_LEN;
177 if (crypto_dh_get_public(cpath->dh_handshake_state, tmp+dh_offset,
178 DH_KEY_LEN)<0) {
179 log_warn(LD_BUG, "Internal error: couldn't extract g^x.");
180 goto err;
183 note_crypto_pk_op(REND_CLIENT);
184 /*XXX maybe give crypto_pk_public_hybrid_encrypt a max_len arg,
185 * to avoid buffer overflows? */
186 r = crypto_pk_public_hybrid_encrypt(intro_key, payload+DIGEST_LEN,
187 sizeof(payload)-DIGEST_LEN,
188 tmp,
189 (int)(dh_offset+DH_KEY_LEN),
190 PK_PKCS1_OAEP_PADDING, 0);
191 if (r<0) {
192 log_warn(LD_BUG,"Internal error: hybrid pk encrypt failed.");
193 goto err;
196 payload_len = DIGEST_LEN + r;
197 tor_assert(payload_len <= RELAY_PAYLOAD_SIZE); /* we overran something */
199 log_info(LD_REND, "Sending an INTRODUCE1 cell");
200 if (relay_send_command_from_edge(0, TO_CIRCUIT(introcirc),
201 RELAY_COMMAND_INTRODUCE1,
202 payload, payload_len,
203 introcirc->cpath->prev)<0) {
204 /* introcirc is already marked for close. leave rendcirc alone. */
205 log_warn(LD_BUG, "Couldn't send INTRODUCE1 cell");
206 return -1;
209 /* Now, we wait for an ACK or NAK on this circuit. */
210 introcirc->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT;
212 return 0;
213 err:
214 circuit_mark_for_close(TO_CIRCUIT(introcirc), END_CIRC_REASON_INTERNAL);
215 circuit_mark_for_close(TO_CIRCUIT(rendcirc), END_CIRC_REASON_INTERNAL);
216 return -1;
219 /** Called when a rendezvous circuit is open; sends a establish
220 * rendezvous circuit as appropriate. */
221 void
222 rend_client_rendcirc_has_opened(origin_circuit_t *circ)
224 tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
226 log_info(LD_REND,"rendcirc is open");
228 /* generate a rendezvous cookie, store it in circ */
229 if (rend_client_send_establish_rendezvous(circ) < 0) {
230 return;
234 /** Called when get an ACK or a NAK for a REND_INTRODUCE1 cell.
237 rend_client_introduction_acked(origin_circuit_t *circ,
238 const uint8_t *request, size_t request_len)
240 origin_circuit_t *rendcirc;
241 (void) request; // XXXX Use this.
243 if (circ->_base.purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
244 log_warn(LD_PROTOCOL,
245 "Received REND_INTRODUCE_ACK on unexpected circuit %d.",
246 circ->_base.n_circ_id);
247 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
248 return -1;
251 tor_assert(circ->build_state->chosen_exit);
252 tor_assert(circ->rend_data);
254 if (request_len == 0) {
255 /* It's an ACK; the introduction point relayed our introduction request. */
256 /* Locate the rend circ which is waiting to hear about this ack,
257 * and tell it.
259 log_info(LD_REND,"Received ack. Telling rend circ...");
260 rendcirc = circuit_get_by_rend_query_and_purpose(
261 circ->rend_data->onion_address, CIRCUIT_PURPOSE_C_REND_READY);
262 if (rendcirc) { /* remember the ack */
263 rendcirc->_base.purpose = CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED;
264 } else {
265 log_info(LD_REND,"...Found no rend circ. Dropping on the floor.");
267 /* close the circuit: we won't need it anymore. */
268 circ->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCE_ACKED;
269 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
270 } else {
271 /* It's a NAK; the introduction point didn't relay our request. */
272 circ->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
273 /* Remove this intro point from the set of viable introduction
274 * points. If any remain, extend to a new one and try again.
275 * If none remain, refetch the service descriptor.
277 if (rend_client_remove_intro_point(circ->build_state->chosen_exit,
278 circ->rend_data) > 0) {
279 /* There are introduction points left. Re-extend the circuit to
280 * another intro point and try again. */
281 extend_info_t *extend_info;
282 int result;
283 extend_info = rend_client_get_random_intro(circ->rend_data);
284 if (!extend_info) {
285 log_warn(LD_REND, "No introduction points left for %s. Closing.",
286 escaped_safe_str_client(circ->rend_data->onion_address));
287 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
288 return -1;
290 if (circ->remaining_relay_early_cells) {
291 log_info(LD_REND,
292 "Got nack for %s from %s. Re-extending circ %d, "
293 "this time to %s.",
294 escaped_safe_str_client(circ->rend_data->onion_address),
295 circ->build_state->chosen_exit->nickname,
296 circ->_base.n_circ_id, extend_info->nickname);
297 result = circuit_extend_to_new_exit(circ, extend_info);
298 } else {
299 log_info(LD_REND,
300 "Got nack for %s from %s. Building a new introduction "
301 "circuit, this time to %s.",
302 escaped_safe_str_client(circ->rend_data->onion_address),
303 circ->build_state->chosen_exit->nickname,
304 extend_info->nickname);
305 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
306 if (!circuit_launch_by_extend_info(CIRCUIT_PURPOSE_C_INTRODUCING,
307 extend_info,
308 CIRCLAUNCH_IS_INTERNAL)) {
309 log_warn(LD_REND, "Building introduction circuit failed.");
310 result = -1;
311 } else {
312 result = 0;
315 extend_info_free(extend_info);
316 return result;
319 return 0;
322 /** The period for which a hidden service directory cannot be queried for
323 * the same descriptor ID again. */
324 #define REND_HID_SERV_DIR_REQUERY_PERIOD (15 * 60)
326 /** Contains the last request times to hidden service directories for
327 * certain queries; keys are strings consisting of base32-encoded
328 * hidden service directory identities and base32-encoded descriptor IDs;
329 * values are pointers to timestamps of the last requests. */
330 static strmap_t *last_hid_serv_requests = NULL;
332 /** Look up the last request time to hidden service directory <b>hs_dir</b>
333 * for descriptor ID <b>desc_id_base32</b>. If <b>set</b> is non-zero,
334 * assign the current time <b>now</b> and return that. Otherwise, return
335 * the most recent request time, or 0 if no such request has been sent
336 * before. */
337 static time_t
338 lookup_last_hid_serv_request(routerstatus_t *hs_dir,
339 const char *desc_id_base32, time_t now, int set)
341 char hsdir_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
342 char hsdir_desc_comb_id[2 * REND_DESC_ID_V2_LEN_BASE32 + 1];
343 time_t *last_request_ptr;
344 base32_encode(hsdir_id_base32, sizeof(hsdir_id_base32),
345 hs_dir->identity_digest, DIGEST_LEN);
346 tor_snprintf(hsdir_desc_comb_id, sizeof(hsdir_desc_comb_id), "%s%s",
347 hsdir_id_base32, desc_id_base32);
348 if (set) {
349 time_t *oldptr;
350 last_request_ptr = tor_malloc_zero(sizeof(time_t));
351 *last_request_ptr = now;
352 oldptr = strmap_set(last_hid_serv_requests, hsdir_desc_comb_id,
353 last_request_ptr);
354 tor_free(oldptr);
355 } else
356 last_request_ptr = strmap_get_lc(last_hid_serv_requests,
357 hsdir_desc_comb_id);
358 return (last_request_ptr) ? *last_request_ptr : 0;
361 /** Clean the history of request times to hidden service directories, so that
362 * it does not contain requests older than REND_HID_SERV_DIR_REQUERY_PERIOD
363 * seconds any more. */
364 static void
365 directory_clean_last_hid_serv_requests(void)
367 strmap_iter_t *iter;
368 time_t cutoff = time(NULL) - REND_HID_SERV_DIR_REQUERY_PERIOD;
369 if (!last_hid_serv_requests)
370 last_hid_serv_requests = strmap_new();
371 for (iter = strmap_iter_init(last_hid_serv_requests);
372 !strmap_iter_done(iter); ) {
373 const char *key;
374 void *val;
375 time_t *ent;
376 strmap_iter_get(iter, &key, &val);
377 ent = (time_t *) val;
378 if (*ent < cutoff) {
379 iter = strmap_iter_next_rmv(last_hid_serv_requests, iter);
380 tor_free(ent);
381 } else {
382 iter = strmap_iter_next(last_hid_serv_requests, iter);
387 /** Determine the responsible hidden service directories for <b>desc_id</b>
388 * and fetch the descriptor belonging to that ID from one of them. Only
389 * send a request to hidden service directories that we did not try within
390 * the last REND_HID_SERV_DIR_REQUERY_PERIOD seconds; on success, return 1,
391 * in the case that no hidden service directory is left to ask for the
392 * descriptor, return 0, and in case of a failure -1. <b>query</b> is only
393 * passed for pretty log statements. */
394 static int
395 directory_get_from_hs_dir(const char *desc_id, const rend_data_t *rend_query)
397 smartlist_t *responsible_dirs = smartlist_create();
398 routerstatus_t *hs_dir;
399 char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
400 time_t now = time(NULL);
401 char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
402 tor_assert(desc_id);
403 tor_assert(rend_query);
404 /* Determine responsible dirs. Even if we can't get all we want,
405 * work with the ones we have. If it's empty, we'll notice below. */
406 (int) hid_serv_get_responsible_directories(responsible_dirs, desc_id);
408 base32_encode(desc_id_base32, sizeof(desc_id_base32),
409 desc_id, DIGEST_LEN);
411 /* Only select those hidden service directories to which we did not send
412 * a request recently and for which we have a router descriptor here. */
413 directory_clean_last_hid_serv_requests(); /* Clean request history first. */
415 SMARTLIST_FOREACH(responsible_dirs, routerstatus_t *, dir, {
416 if (lookup_last_hid_serv_request(dir, desc_id_base32, 0, 0) +
417 REND_HID_SERV_DIR_REQUERY_PERIOD >= now ||
418 !router_get_by_digest(dir->identity_digest))
419 SMARTLIST_DEL_CURRENT(responsible_dirs, dir);
422 hs_dir = smartlist_choose(responsible_dirs);
423 smartlist_free(responsible_dirs);
424 if (!hs_dir) {
425 log_info(LD_REND, "Could not pick one of the responsible hidden "
426 "service directories, because we requested them all "
427 "recently without success.");
428 return 0;
431 /* Remember, that we are requesting a descriptor from this hidden service
432 * directory now. */
433 lookup_last_hid_serv_request(hs_dir, desc_id_base32, now, 1);
435 /* Encode descriptor cookie for logging purposes. */
436 if (rend_query->auth_type != REND_NO_AUTH) {
437 if (base64_encode(descriptor_cookie_base64,
438 sizeof(descriptor_cookie_base64),
439 rend_query->descriptor_cookie, REND_DESC_COOKIE_LEN)<0) {
440 log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
441 return 0;
443 /* Remove == signs and newline. */
444 descriptor_cookie_base64[strlen(descriptor_cookie_base64)-3] = '\0';
445 } else {
446 strlcpy(descriptor_cookie_base64, "(none)",
447 sizeof(descriptor_cookie_base64));
450 /* Send fetch request. (Pass query and possibly descriptor cookie so that
451 * they can be written to the directory connection and be referred to when
452 * the response arrives. */
453 directory_initiate_command_routerstatus_rend(hs_dir,
454 DIR_PURPOSE_FETCH_RENDDESC_V2,
455 ROUTER_PURPOSE_GENERAL,
456 1, desc_id_base32, NULL, 0, 0,
457 rend_query);
458 log_info(LD_REND, "Sending fetch request for v2 descriptor for "
459 "service '%s' with descriptor ID '%s', auth type %d, "
460 "and descriptor cookie '%s' to hidden service "
461 "directory '%s' on port %d.",
462 rend_query->onion_address, desc_id_base32,
463 rend_query->auth_type,
464 (rend_query->auth_type == REND_NO_AUTH ? "[none]" :
465 escaped_safe_str_client(descriptor_cookie_base64)),
466 hs_dir->nickname, hs_dir->dir_port);
467 return 1;
470 /** Unless we already have a descriptor for <b>rend_query</b> with at least
471 * one (possibly) working introduction point in it, start a connection to a
472 * hidden service directory to fetch a v2 rendezvous service descriptor. */
473 void
474 rend_client_refetch_v2_renddesc(const rend_data_t *rend_query)
476 char descriptor_id[DIGEST_LEN];
477 int replicas_left_to_try[REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS];
478 int i, tries_left;
479 rend_cache_entry_t *e = NULL;
480 tor_assert(rend_query);
481 /* Are we configured to fetch descriptors? */
482 if (!get_options()->FetchHidServDescriptors) {
483 log_warn(LD_REND, "We received an onion address for a v2 rendezvous "
484 "service descriptor, but are not fetching service descriptors.");
485 return;
487 /* Before fetching, check if we already have the descriptor here. */
488 if (rend_cache_lookup_entry(rend_query->onion_address, -1, &e) > 0) {
489 log_info(LD_REND, "We would fetch a v2 rendezvous descriptor, but we "
490 "already have that descriptor here. Not fetching.");
491 return;
493 log_debug(LD_REND, "Fetching v2 rendezvous descriptor for service %s",
494 safe_str_client(rend_query->onion_address));
495 /* Randomly iterate over the replicas until a descriptor can be fetched
496 * from one of the consecutive nodes, or no options are left. */
497 tries_left = REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS;
498 for (i = 0; i < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; i++)
499 replicas_left_to_try[i] = i;
500 while (tries_left > 0) {
501 int rand = crypto_rand_int(tries_left);
502 int chosen_replica = replicas_left_to_try[rand];
503 replicas_left_to_try[rand] = replicas_left_to_try[--tries_left];
505 if (rend_compute_v2_desc_id(descriptor_id, rend_query->onion_address,
506 rend_query->auth_type == REND_STEALTH_AUTH ?
507 rend_query->descriptor_cookie : NULL,
508 time(NULL), chosen_replica) < 0) {
509 log_warn(LD_REND, "Internal error: Computing v2 rendezvous "
510 "descriptor ID did not succeed.");
511 return;
513 if (directory_get_from_hs_dir(descriptor_id, rend_query) != 0)
514 return; /* either success or failure, but we're done */
516 /* If we come here, there are no hidden service directories left. */
517 log_info(LD_REND, "Could not pick one of the responsible hidden "
518 "service directories to fetch descriptors, because "
519 "we already tried them all unsuccessfully.");
520 /* Close pending connections. */
521 rend_client_desc_trynow(rend_query->onion_address);
522 return;
525 /** Remove failed_intro from ent. If ent now has no intro points, or
526 * service is unrecognized, then launch a new renddesc fetch.
528 * Return -1 if error, 0 if no intro points remain or service
529 * unrecognized, 1 if recognized and some intro points remain.
532 rend_client_remove_intro_point(extend_info_t *failed_intro,
533 const rend_data_t *rend_query)
535 int i, r;
536 rend_cache_entry_t *ent;
537 connection_t *conn;
539 r = rend_cache_lookup_entry(rend_query->onion_address, -1, &ent);
540 if (r<0) {
541 log_warn(LD_BUG, "Malformed service ID %s.",
542 escaped_safe_str_client(rend_query->onion_address));
543 return -1;
545 if (r==0) {
546 log_info(LD_REND, "Unknown service %s. Re-fetching descriptor.",
547 escaped_safe_str_client(rend_query->onion_address));
548 rend_client_refetch_v2_renddesc(rend_query);
549 return 0;
552 for (i = 0; i < smartlist_len(ent->parsed->intro_nodes); i++) {
553 rend_intro_point_t *intro = smartlist_get(ent->parsed->intro_nodes, i);
554 if (!memcmp(failed_intro->identity_digest,
555 intro->extend_info->identity_digest, DIGEST_LEN)) {
556 rend_intro_point_free(intro);
557 smartlist_del(ent->parsed->intro_nodes, i);
558 break;
562 if (smartlist_len(ent->parsed->intro_nodes) == 0) {
563 log_info(LD_REND,
564 "No more intro points remain for %s. Re-fetching descriptor.",
565 escaped_safe_str_client(rend_query->onion_address));
566 rend_client_refetch_v2_renddesc(rend_query);
568 /* move all pending streams back to renddesc_wait */
569 while ((conn = connection_get_by_type_state_rendquery(CONN_TYPE_AP,
570 AP_CONN_STATE_CIRCUIT_WAIT,
571 rend_query->onion_address))) {
572 conn->state = AP_CONN_STATE_RENDDESC_WAIT;
575 return 0;
577 log_info(LD_REND,"%d options left for %s.",
578 smartlist_len(ent->parsed->intro_nodes),
579 escaped_safe_str_client(rend_query->onion_address));
580 return 1;
583 /** Called when we receive a RENDEZVOUS_ESTABLISHED cell; changes the state of
584 * the circuit to C_REND_READY.
587 rend_client_rendezvous_acked(origin_circuit_t *circ, const uint8_t *request,
588 size_t request_len)
590 (void) request;
591 (void) request_len;
592 /* we just got an ack for our establish-rendezvous. switch purposes. */
593 if (circ->_base.purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND) {
594 log_warn(LD_PROTOCOL,"Got a rendezvous ack when we weren't expecting one. "
595 "Closing circ.");
596 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
597 return -1;
599 log_info(LD_REND,"Got rendezvous ack. This circuit is now ready for "
600 "rendezvous.");
601 circ->_base.purpose = CIRCUIT_PURPOSE_C_REND_READY;
602 /* XXXX022 This is a pretty brute-force approach. It'd be better to
603 * attach only the connections that are waiting on this circuit, rather
604 * than trying to attach them all. See comments bug 743. */
605 /* If we already have the introduction circuit built, make sure we send
606 * the INTRODUCE cell _now_ */
607 connection_ap_attach_pending();
608 return 0;
611 /** Bob sent us a rendezvous cell; join the circuits. */
613 rend_client_receive_rendezvous(origin_circuit_t *circ, const uint8_t *request,
614 size_t request_len)
616 crypt_path_t *hop;
617 char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN];
619 if ((circ->_base.purpose != CIRCUIT_PURPOSE_C_REND_READY &&
620 circ->_base.purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)
621 || !circ->build_state->pending_final_cpath) {
622 log_warn(LD_PROTOCOL,"Got rendezvous2 cell from hidden service, but not "
623 "expecting it. Closing.");
624 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
625 return -1;
628 if (request_len != DH_KEY_LEN+DIGEST_LEN) {
629 log_warn(LD_PROTOCOL,"Incorrect length (%d) on RENDEZVOUS2 cell.",
630 (int)request_len);
631 goto err;
634 log_info(LD_REND,"Got RENDEZVOUS2 cell from hidden service.");
636 /* first DH_KEY_LEN bytes are g^y from bob. Finish the dh handshake...*/
637 tor_assert(circ->build_state);
638 tor_assert(circ->build_state->pending_final_cpath);
639 hop = circ->build_state->pending_final_cpath;
640 tor_assert(hop->dh_handshake_state);
641 if (crypto_dh_compute_secret(LOG_PROTOCOL_WARN,
642 hop->dh_handshake_state, (char*)request,
643 DH_KEY_LEN,
644 keys, DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
645 log_warn(LD_GENERAL, "Couldn't complete DH handshake.");
646 goto err;
648 /* ... and set up cpath. */
649 if (circuit_init_cpath_crypto(hop, keys+DIGEST_LEN, 0)<0)
650 goto err;
652 /* Check whether the digest is right... */
653 if (memcmp(keys, request+DH_KEY_LEN, DIGEST_LEN)) {
654 log_warn(LD_PROTOCOL, "Incorrect digest of key material.");
655 goto err;
658 crypto_dh_free(hop->dh_handshake_state);
659 hop->dh_handshake_state = NULL;
661 /* All is well. Extend the circuit. */
662 circ->_base.purpose = CIRCUIT_PURPOSE_C_REND_JOINED;
663 hop->state = CPATH_STATE_OPEN;
664 /* set the windows to default. these are the windows
665 * that alice thinks bob has.
667 hop->package_window = circuit_initial_package_window();
668 hop->deliver_window = CIRCWINDOW_START;
670 onion_append_to_cpath(&circ->cpath, hop);
671 circ->build_state->pending_final_cpath = NULL; /* prevent double-free */
672 /* XXXX022 This is a pretty brute-force approach. It'd be better to
673 * attach only the connections that are waiting on this circuit, rather
674 * than trying to attach them all. See comments bug 743. */
675 connection_ap_attach_pending();
676 return 0;
677 err:
678 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
679 return -1;
682 /** Find all the apconns in state AP_CONN_STATE_RENDDESC_WAIT that are
683 * waiting on <b>query</b>. If there's a working cache entry here with at
684 * least one intro point, move them to the next state. */
685 void
686 rend_client_desc_trynow(const char *query)
688 edge_connection_t *conn;
689 rend_cache_entry_t *entry;
690 time_t now = time(NULL);
692 smartlist_t *conns = get_connection_array();
693 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, _conn) {
694 if (_conn->type != CONN_TYPE_AP ||
695 _conn->state != AP_CONN_STATE_RENDDESC_WAIT ||
696 _conn->marked_for_close)
697 continue;
698 conn = TO_EDGE_CONN(_conn);
699 if (!conn->rend_data)
700 continue;
701 if (rend_cmp_service_ids(query, conn->rend_data->onion_address))
702 continue;
703 assert_connection_ok(TO_CONN(conn), now);
704 if (rend_cache_lookup_entry(conn->rend_data->onion_address, -1,
705 &entry) == 1 &&
706 smartlist_len(entry->parsed->intro_nodes) > 0) {
707 /* either this fetch worked, or it failed but there was a
708 * valid entry from before which we should reuse */
709 log_info(LD_REND,"Rend desc is usable. Launching circuits.");
710 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
712 /* restart their timeout values, so they get a fair shake at
713 * connecting to the hidden service. */
714 conn->_base.timestamp_created = now;
715 conn->_base.timestamp_lastread = now;
716 conn->_base.timestamp_lastwritten = now;
718 if (connection_ap_handshake_attach_circuit(conn) < 0) {
719 /* it will never work */
720 log_warn(LD_REND,"Rendezvous attempt failed. Closing.");
721 if (!conn->_base.marked_for_close)
722 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
724 } else { /* 404, or fetch didn't get that far */
725 log_notice(LD_REND,"Closing stream for '%s.onion': hidden service is "
726 "unavailable (try again later).",
727 safe_str_client(query));
728 connection_mark_unattached_ap(conn, END_STREAM_REASON_RESOLVEFAILED);
730 } SMARTLIST_FOREACH_END(_conn);
733 /** Return a newly allocated extend_info_t* for a randomly chosen introduction
734 * point for the named hidden service. Return NULL if all introduction points
735 * have been tried and failed.
737 extend_info_t *
738 rend_client_get_random_intro(const rend_data_t *rend_query)
740 int i;
741 rend_cache_entry_t *entry;
742 rend_intro_point_t *intro;
743 routerinfo_t *router;
745 if (rend_cache_lookup_entry(rend_query->onion_address, -1, &entry) < 1) {
746 log_warn(LD_REND,
747 "Query '%s' didn't have valid rend desc in cache. Failing.",
748 safe_str_client(rend_query->onion_address));
749 return NULL;
752 again:
753 if (smartlist_len(entry->parsed->intro_nodes) == 0)
754 return NULL;
756 i = crypto_rand_int(smartlist_len(entry->parsed->intro_nodes));
757 intro = smartlist_get(entry->parsed->intro_nodes, i);
758 /* Do we need to look up the router or is the extend info complete? */
759 if (!intro->extend_info->onion_key) {
760 if (tor_digest_is_zero(intro->extend_info->identity_digest))
761 router = router_get_by_hexdigest(intro->extend_info->nickname);
762 else
763 router = router_get_by_digest(intro->extend_info->identity_digest);
764 if (!router) {
765 log_info(LD_REND, "Unknown router with nickname '%s'; trying another.",
766 intro->extend_info->nickname);
767 rend_intro_point_free(intro);
768 smartlist_del(entry->parsed->intro_nodes, i);
769 goto again;
771 extend_info_free(intro->extend_info);
772 intro->extend_info = extend_info_from_router(router);
774 return extend_info_dup(intro->extend_info);
777 /** Client-side authorizations for hidden services; map of onion address to
778 * rend_service_authorization_t*. */
779 static strmap_t *auth_hid_servs = NULL;
781 /** Look up the client-side authorization for the hidden service with
782 * <b>onion_address</b>. Return NULL if no authorization is available for
783 * that address. */
784 rend_service_authorization_t*
785 rend_client_lookup_service_authorization(const char *onion_address)
787 tor_assert(onion_address);
788 if (!auth_hid_servs) return NULL;
789 return strmap_get(auth_hid_servs, onion_address);
792 /** Helper: Free storage held by rend_service_authorization_t. */
793 static void
794 rend_service_authorization_free(rend_service_authorization_t *auth)
796 tor_free(auth);
799 /** Helper for strmap_free. */
800 static void
801 rend_service_authorization_strmap_item_free(void *service_auth)
803 rend_service_authorization_free(service_auth);
806 /** Release all the storage held in auth_hid_servs.
808 void
809 rend_service_authorization_free_all(void)
811 if (!auth_hid_servs) {
812 return;
814 strmap_free(auth_hid_servs, rend_service_authorization_strmap_item_free);
815 auth_hid_servs = NULL;
818 /** Parse <b>config_line</b> as a client-side authorization for a hidden
819 * service and add it to the local map of hidden service authorizations.
820 * Return 0 for success and -1 for failure. */
822 rend_parse_service_authorization(or_options_t *options, int validate_only)
824 config_line_t *line;
825 int res = -1;
826 strmap_t *parsed = strmap_new();
827 smartlist_t *sl = smartlist_create();
828 rend_service_authorization_t *auth = NULL;
830 for (line = options->HidServAuth; line; line = line->next) {
831 char *onion_address, *descriptor_cookie;
832 char descriptor_cookie_tmp[REND_DESC_COOKIE_LEN+2];
833 char descriptor_cookie_base64ext[REND_DESC_COOKIE_LEN_BASE64+2+1];
834 int auth_type_val = 0;
835 auth = NULL;
836 SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
837 smartlist_clear(sl);
838 smartlist_split_string(sl, line->value, " ",
839 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
840 if (smartlist_len(sl) < 2) {
841 log_warn(LD_CONFIG, "Configuration line does not consist of "
842 "\"onion-address authorization-cookie [service-name]\": "
843 "'%s'", line->value);
844 goto err;
846 auth = tor_malloc_zero(sizeof(rend_service_authorization_t));
847 /* Parse onion address. */
848 onion_address = smartlist_get(sl, 0);
849 if (strlen(onion_address) != REND_SERVICE_ADDRESS_LEN ||
850 strcmpend(onion_address, ".onion")) {
851 log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
852 onion_address);
853 goto err;
855 strlcpy(auth->onion_address, onion_address, REND_SERVICE_ID_LEN_BASE32+1);
856 if (!rend_valid_service_id(auth->onion_address)) {
857 log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
858 onion_address);
859 goto err;
861 /* Parse descriptor cookie. */
862 descriptor_cookie = smartlist_get(sl, 1);
863 if (strlen(descriptor_cookie) != REND_DESC_COOKIE_LEN_BASE64) {
864 log_warn(LD_CONFIG, "Authorization cookie has wrong length: '%s'",
865 descriptor_cookie);
866 goto err;
868 /* Add trailing zero bytes (AA) to make base64-decoding happy. */
869 tor_snprintf(descriptor_cookie_base64ext,
870 REND_DESC_COOKIE_LEN_BASE64+2+1,
871 "%sAA", descriptor_cookie);
872 if (base64_decode(descriptor_cookie_tmp, sizeof(descriptor_cookie_tmp),
873 descriptor_cookie_base64ext,
874 strlen(descriptor_cookie_base64ext)) < 0) {
875 log_warn(LD_CONFIG, "Decoding authorization cookie failed: '%s'",
876 descriptor_cookie);
877 goto err;
879 auth_type_val = (descriptor_cookie_tmp[16] >> 4) + 1;
880 if (auth_type_val < 1 || auth_type_val > 2) {
881 log_warn(LD_CONFIG, "Authorization cookie has unknown authorization "
882 "type encoded.");
883 goto err;
885 auth->auth_type = auth_type_val == 1 ? REND_BASIC_AUTH : REND_STEALTH_AUTH;
886 memcpy(auth->descriptor_cookie, descriptor_cookie_tmp,
887 REND_DESC_COOKIE_LEN);
888 if (strmap_get(parsed, auth->onion_address)) {
889 log_warn(LD_CONFIG, "Duplicate authorization for the same hidden "
890 "service.");
891 goto err;
893 strmap_set(parsed, auth->onion_address, auth);
894 auth = NULL;
896 res = 0;
897 goto done;
898 err:
899 res = -1;
900 done:
901 rend_service_authorization_free(auth);
902 SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
903 smartlist_free(sl);
904 if (!validate_only && res == 0) {
905 rend_service_authorization_free_all();
906 auth_hid_servs = parsed;
907 } else {
908 strmap_free(parsed, rend_service_authorization_strmap_item_free);
910 return res;