Fix compile warnings on Snow Leopard
[tor/rransom.git] / src / or / rendclient.c
blob38383e8abbf8f8f87612a91a5ddd5573244e6cd1
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 if (rend_cache_lookup_entry(introcirc->rend_data->onion_address,
98 0, &entry) > 0) {
99 log_warn(LD_BUG, "We have both a v0 and a v2 rend desc for this "
100 "service. The v2 desc doesn't contain the introduction "
101 "point (and key) to send an INTRODUCE1/2 cell to this "
102 "introduction point. Assuming the introduction point "
103 "is for v0 rend clients and using the service key "
104 "from the v0 desc instead. (This is probably a bug, "
105 "because we shouldn't even have both a v0 and a v2 "
106 "descriptor for the same service.)");
107 /* See flyspray task 1024. */
108 intro_key = entry->parsed->pk;
109 } else {
110 log_warn(LD_BUG, "Internal error: could not find intro key; we "
111 "only have a v2 rend desc with %d intro points.",
112 smartlist_len(entry->parsed->intro_nodes));
113 goto err;
117 if (crypto_pk_get_digest(intro_key, payload)<0) {
118 log_warn(LD_BUG, "Internal error: couldn't hash public key.");
119 goto err;
122 /* Initialize the pending_final_cpath and start the DH handshake. */
123 cpath = rendcirc->build_state->pending_final_cpath;
124 if (!cpath) {
125 cpath = rendcirc->build_state->pending_final_cpath =
126 tor_malloc_zero(sizeof(crypt_path_t));
127 cpath->magic = CRYPT_PATH_MAGIC;
128 if (!(cpath->dh_handshake_state = crypto_dh_new())) {
129 log_warn(LD_BUG, "Internal error: couldn't allocate DH.");
130 goto err;
132 if (crypto_dh_generate_public(cpath->dh_handshake_state)<0) {
133 log_warn(LD_BUG, "Internal error: couldn't generate g^x.");
134 goto err;
138 /* If version is 3, write (optional) auth data and timestamp. */
139 if (entry->parsed->protocols & (1<<3)) {
140 tmp[0] = 3; /* version 3 of the cell format */
141 tmp[1] = (uint8_t)introcirc->rend_data->auth_type; /* auth type, if any */
142 v3_shift = 1;
143 if (introcirc->rend_data->auth_type != REND_NO_AUTH) {
144 set_uint16(tmp+2, htons(REND_DESC_COOKIE_LEN));
145 memcpy(tmp+4, introcirc->rend_data->descriptor_cookie,
146 REND_DESC_COOKIE_LEN);
147 v3_shift += 2+REND_DESC_COOKIE_LEN;
149 set_uint32(tmp+v3_shift+1, htonl((uint32_t)time(NULL)));
150 v3_shift += 4;
151 } /* if version 2 only write version number */
152 else if (entry->parsed->protocols & (1<<2)) {
153 tmp[0] = 2; /* version 2 of the cell format */
156 /* write the remaining items into tmp */
157 if (entry->parsed->protocols & (1<<3) || entry->parsed->protocols & (1<<2)) {
158 /* version 2 format */
159 extend_info_t *extend_info = rendcirc->build_state->chosen_exit;
160 int klen;
161 /* nul pads */
162 set_uint32(tmp+v3_shift+1, tor_addr_to_ipv4h(&extend_info->addr));
163 set_uint16(tmp+v3_shift+5, htons(extend_info->port));
164 memcpy(tmp+v3_shift+7, extend_info->identity_digest, DIGEST_LEN);
165 klen = crypto_pk_asn1_encode(extend_info->onion_key,
166 tmp+v3_shift+7+DIGEST_LEN+2,
167 sizeof(tmp)-(v3_shift+7+DIGEST_LEN+2));
168 set_uint16(tmp+v3_shift+7+DIGEST_LEN, htons(klen));
169 memcpy(tmp+v3_shift+7+DIGEST_LEN+2+klen, rendcirc->rend_data->rend_cookie,
170 REND_COOKIE_LEN);
171 dh_offset = v3_shift+7+DIGEST_LEN+2+klen+REND_COOKIE_LEN;
172 } else {
173 /* Version 0. */
174 strncpy(tmp, rendcirc->build_state->chosen_exit->nickname,
175 (MAX_NICKNAME_LEN+1)); /* nul pads */
176 memcpy(tmp+MAX_NICKNAME_LEN+1, rendcirc->rend_data->rend_cookie,
177 REND_COOKIE_LEN);
178 dh_offset = MAX_NICKNAME_LEN+1+REND_COOKIE_LEN;
181 if (crypto_dh_get_public(cpath->dh_handshake_state, tmp+dh_offset,
182 DH_KEY_LEN)<0) {
183 log_warn(LD_BUG, "Internal error: couldn't extract g^x.");
184 goto err;
187 note_crypto_pk_op(REND_CLIENT);
188 /*XXX maybe give crypto_pk_public_hybrid_encrypt a max_len arg,
189 * to avoid buffer overflows? */
190 r = crypto_pk_public_hybrid_encrypt(intro_key, payload+DIGEST_LEN,
191 tmp,
192 (int)(dh_offset+DH_KEY_LEN),
193 PK_PKCS1_OAEP_PADDING, 0);
194 if (r<0) {
195 log_warn(LD_BUG,"Internal error: hybrid pk encrypt failed.");
196 goto err;
199 payload_len = DIGEST_LEN + r;
200 tor_assert(payload_len <= RELAY_PAYLOAD_SIZE); /* we overran something */
202 log_info(LD_REND, "Sending an INTRODUCE1 cell");
203 if (relay_send_command_from_edge(0, TO_CIRCUIT(introcirc),
204 RELAY_COMMAND_INTRODUCE1,
205 payload, payload_len,
206 introcirc->cpath->prev)<0) {
207 /* introcirc is already marked for close. leave rendcirc alone. */
208 log_warn(LD_BUG, "Couldn't send INTRODUCE1 cell");
209 return -1;
212 /* Now, we wait for an ACK or NAK on this circuit. */
213 introcirc->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT;
215 return 0;
216 err:
217 circuit_mark_for_close(TO_CIRCUIT(introcirc), END_CIRC_REASON_INTERNAL);
218 circuit_mark_for_close(TO_CIRCUIT(rendcirc), END_CIRC_REASON_INTERNAL);
219 return -1;
222 /** Called when a rendezvous circuit is open; sends a establish
223 * rendezvous circuit as appropriate. */
224 void
225 rend_client_rendcirc_has_opened(origin_circuit_t *circ)
227 tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
229 log_info(LD_REND,"rendcirc is open");
231 /* generate a rendezvous cookie, store it in circ */
232 if (rend_client_send_establish_rendezvous(circ) < 0) {
233 return;
237 /** Called when get an ACK or a NAK for a REND_INTRODUCE1 cell.
240 rend_client_introduction_acked(origin_circuit_t *circ,
241 const char *request, size_t request_len)
243 origin_circuit_t *rendcirc;
244 (void) request; // XXXX Use this.
246 if (circ->_base.purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
247 log_warn(LD_PROTOCOL,
248 "Received REND_INTRODUCE_ACK on unexpected circuit %d.",
249 circ->_base.n_circ_id);
250 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
251 return -1;
254 tor_assert(circ->build_state->chosen_exit);
255 tor_assert(circ->rend_data);
257 if (request_len == 0) {
258 /* It's an ACK; the introduction point relayed our introduction request. */
259 /* Locate the rend circ which is waiting to hear about this ack,
260 * and tell it.
262 log_info(LD_REND,"Received ack. Telling rend circ...");
263 rendcirc = circuit_get_by_rend_query_and_purpose(
264 circ->rend_data->onion_address, CIRCUIT_PURPOSE_C_REND_READY);
265 if (rendcirc) { /* remember the ack */
266 rendcirc->_base.purpose = CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED;
267 } else {
268 log_info(LD_REND,"...Found no rend circ. Dropping on the floor.");
270 /* close the circuit: we won't need it anymore. */
271 circ->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCE_ACKED;
272 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
273 } else {
274 /* It's a NAK; the introduction point didn't relay our request. */
275 circ->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
276 /* Remove this intro point from the set of viable introduction
277 * points. If any remain, extend to a new one and try again.
278 * If none remain, refetch the service descriptor.
280 if (rend_client_remove_intro_point(circ->build_state->chosen_exit,
281 circ->rend_data) > 0) {
282 /* There are introduction points left. Re-extend the circuit to
283 * another intro point and try again. */
284 extend_info_t *extend_info;
285 int result;
286 extend_info = rend_client_get_random_intro(circ->rend_data);
287 if (!extend_info) {
288 log_warn(LD_REND, "No introduction points left for %s. Closing.",
289 escaped_safe_str(circ->rend_data->onion_address));
290 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
291 return -1;
293 if (circ->remaining_relay_early_cells) {
294 log_info(LD_REND,
295 "Got nack for %s from %s. Re-extending circ %d, "
296 "this time to %s.",
297 escaped_safe_str(circ->rend_data->onion_address),
298 circ->build_state->chosen_exit->nickname,
299 circ->_base.n_circ_id, extend_info->nickname);
300 result = circuit_extend_to_new_exit(circ, extend_info);
301 } else {
302 log_info(LD_REND,
303 "Got nack for %s from %s. Building a new introduction "
304 "circuit, this time to %s.",
305 escaped_safe_str(circ->rend_data->onion_address),
306 circ->build_state->chosen_exit->nickname,
307 extend_info->nickname);
308 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
309 if (!circuit_launch_by_extend_info(CIRCUIT_PURPOSE_C_INTRODUCING,
310 extend_info,
311 CIRCLAUNCH_IS_INTERNAL)) {
312 log_warn(LD_REND, "Building introduction circuit failed.");
313 result = -1;
314 } else {
315 result = 0;
318 extend_info_free(extend_info);
319 return result;
322 return 0;
325 /** The period for which a hidden service directory cannot be queried for
326 * the same descriptor ID again. */
327 #define REND_HID_SERV_DIR_REQUERY_PERIOD (15 * 60)
329 /** Contains the last request times to hidden service directories for
330 * certain queries; keys are strings consisting of base32-encoded
331 * hidden service directory identities and base32-encoded descriptor IDs;
332 * values are pointers to timestamps of the last requests. */
333 static strmap_t *last_hid_serv_requests = NULL;
335 /** Look up the last request time to hidden service directory <b>hs_dir</b>
336 * for descriptor ID <b>desc_id_base32</b>. If <b>set</b> is non-zero,
337 * assign the current time <b>now</b> and return that. Otherwise, return
338 * the most recent request time, or 0 if no such request has been sent
339 * before. */
340 static time_t
341 lookup_last_hid_serv_request(routerstatus_t *hs_dir,
342 const char *desc_id_base32, time_t now, int set)
344 char hsdir_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
345 char hsdir_desc_comb_id[2 * REND_DESC_ID_V2_LEN_BASE32 + 1];
346 time_t *last_request_ptr;
347 base32_encode(hsdir_id_base32, sizeof(hsdir_id_base32),
348 hs_dir->identity_digest, DIGEST_LEN);
349 tor_snprintf(hsdir_desc_comb_id, sizeof(hsdir_desc_comb_id), "%s%s",
350 hsdir_id_base32, desc_id_base32);
351 if (set) {
352 last_request_ptr = tor_malloc_zero(sizeof(time_t *));
353 *last_request_ptr = now;
354 strmap_set(last_hid_serv_requests, hsdir_desc_comb_id, last_request_ptr);
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(descriptor_cookie_base64)),
466 hs_dir->nickname, hs_dir->dir_port);
467 return 1;
470 /** If we are not currently fetching a rendezvous service descriptor
471 * for the service ID <b>query</b>, start a directory connection to fetch a
472 * new one.
474 void
475 rend_client_refetch_renddesc(const char *query)
477 if (!get_options()->FetchHidServDescriptors)
478 return;
479 log_info(LD_REND, "Fetching rendezvous descriptor for service %s",
480 escaped_safe_str(query));
481 if (connection_get_by_type_state_rendquery(CONN_TYPE_DIR, 0, query, 0)) {
482 log_info(LD_REND,"Would fetch a new renddesc here (for %s), but one is "
483 "already in progress.", escaped_safe_str(query));
484 } else {
485 /* not one already; initiate a dir rend desc lookup */
486 directory_get_from_dirserver(DIR_PURPOSE_FETCH_RENDDESC,
487 ROUTER_PURPOSE_GENERAL, query,
488 PDS_RETRY_IF_NO_SERVERS);
492 /** Start a connection to a hidden service directory to fetch a v2
493 * rendezvous service descriptor for the base32-encoded service ID
494 * <b>query</b>.
496 void
497 rend_client_refetch_v2_renddesc(const rend_data_t *rend_query)
499 char descriptor_id[DIGEST_LEN];
500 int replicas_left_to_try[REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS];
501 int i, tries_left, r;
502 rend_cache_entry_t *e = NULL;
503 time_t now = time(NULL);
504 tor_assert(rend_query);
505 /* Are we configured to fetch descriptors? */
506 if (!get_options()->FetchHidServDescriptors) {
507 log_warn(LD_REND, "We received an onion address for a v2 rendezvous "
508 "service descriptor, but are not fetching service descriptors.");
509 return;
511 /* Before fetching, check if we already have the descriptor here. */
512 r = rend_cache_lookup_entry(rend_query->onion_address, -1, &e);
513 if (r > 0 && now - e->received < NUM_SECONDS_BEFORE_HS_REFETCH) {
514 log_info(LD_REND, "We would fetch a v2 rendezvous descriptor, but we "
515 "already have a fresh copy of that descriptor here. "
516 "Not fetching.");
517 return;
519 log_debug(LD_REND, "Fetching v2 rendezvous descriptor for service %s",
520 safe_str(rend_query->onion_address));
521 /* Randomly iterate over the replicas until a descriptor can be fetched
522 * from one of the consecutive nodes, or no options are left. */
523 tries_left = REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS;
524 for (i = 0; i < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; i++)
525 replicas_left_to_try[i] = i;
526 while (tries_left > 0) {
527 int rand = crypto_rand_int(tries_left);
528 int chosen_replica = replicas_left_to_try[rand];
529 replicas_left_to_try[rand] = replicas_left_to_try[--tries_left];
531 if (rend_compute_v2_desc_id(descriptor_id, rend_query->onion_address,
532 rend_query->auth_type == REND_STEALTH_AUTH ?
533 rend_query->descriptor_cookie : NULL,
534 time(NULL), chosen_replica) < 0) {
535 log_warn(LD_REND, "Internal error: Computing v2 rendezvous "
536 "descriptor ID did not succeed.");
537 return;
539 if (directory_get_from_hs_dir(descriptor_id, rend_query) != 0)
540 return; /* either success or failure, but we're done */
542 /* If we come here, there are no hidden service directories left. */
543 log_info(LD_REND, "Could not pick one of the responsible hidden "
544 "service directories to fetch descriptors, because "
545 "we already tried them all unsuccessfully.");
546 /* Close pending connections (unless a v0 request is still going on). */
547 rend_client_desc_trynow(rend_query->onion_address, 2);
548 return;
551 /** Remove failed_intro from ent. If ent now has no intro points, or
552 * service is unrecognized, then launch a new renddesc fetch.
554 * Return -1 if error, 0 if no intro points remain or service
555 * unrecognized, 1 if recognized and some intro points remain.
558 rend_client_remove_intro_point(extend_info_t *failed_intro,
559 const rend_data_t *rend_query)
561 int i, r;
562 rend_cache_entry_t *ent;
563 connection_t *conn;
565 r = rend_cache_lookup_entry(rend_query->onion_address, -1, &ent);
566 if (r<0) {
567 log_warn(LD_BUG, "Malformed service ID %s.",
568 escaped_safe_str(rend_query->onion_address));
569 return -1;
571 if (r==0) {
572 log_info(LD_REND, "Unknown service %s. Re-fetching descriptor.",
573 escaped_safe_str(rend_query->onion_address));
574 /* Fetch both, v0 and v2 rend descriptors in parallel. Use whichever
575 * arrives first. Exception: When using client authorization, only
576 * fetch v2 descriptors.*/
577 rend_client_refetch_v2_renddesc(rend_query);
578 if (rend_query->auth_type == REND_NO_AUTH)
579 rend_client_refetch_renddesc(rend_query->onion_address);
580 return 0;
583 for (i = 0; i < smartlist_len(ent->parsed->intro_nodes); i++) {
584 rend_intro_point_t *intro = smartlist_get(ent->parsed->intro_nodes, i);
585 if (!memcmp(failed_intro->identity_digest,
586 intro->extend_info->identity_digest, DIGEST_LEN)) {
587 rend_intro_point_free(intro);
588 smartlist_del(ent->parsed->intro_nodes, i);
589 break;
593 if (smartlist_len(ent->parsed->intro_nodes) == 0) {
594 log_info(LD_REND,
595 "No more intro points remain for %s. Re-fetching descriptor.",
596 escaped_safe_str(rend_query->onion_address));
597 /* Fetch both, v0 and v2 rend descriptors in parallel. Use whichever
598 * arrives first. Exception: When using client authorization, only
599 * fetch v2 descriptors.*/
600 rend_client_refetch_v2_renddesc(rend_query);
601 if (rend_query->auth_type == REND_NO_AUTH)
602 rend_client_refetch_renddesc(rend_query->onion_address);
604 /* move all pending streams back to renddesc_wait */
605 while ((conn = connection_get_by_type_state_rendquery(CONN_TYPE_AP,
606 AP_CONN_STATE_CIRCUIT_WAIT,
607 rend_query->onion_address, -1))) {
608 conn->state = AP_CONN_STATE_RENDDESC_WAIT;
611 return 0;
613 log_info(LD_REND,"%d options left for %s.",
614 smartlist_len(ent->parsed->intro_nodes),
615 escaped_safe_str(rend_query->onion_address));
616 return 1;
619 /** Called when we receive a RENDEZVOUS_ESTABLISHED cell; changes the state of
620 * the circuit to C_REND_READY.
623 rend_client_rendezvous_acked(origin_circuit_t *circ, const char *request,
624 size_t request_len)
626 (void) request;
627 (void) request_len;
628 /* we just got an ack for our establish-rendezvous. switch purposes. */
629 if (circ->_base.purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND) {
630 log_warn(LD_PROTOCOL,"Got a rendezvous ack when we weren't expecting one. "
631 "Closing circ.");
632 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
633 return -1;
635 log_info(LD_REND,"Got rendezvous ack. This circuit is now ready for "
636 "rendezvous.");
637 circ->_base.purpose = CIRCUIT_PURPOSE_C_REND_READY;
638 /* XXXX022 This is a pretty brute-force approach. It'd be better to
639 * attach only the connections that are waiting on this circuit, rather
640 * than trying to attach them all. See comments bug 743. */
641 /* If we already have the introduction circuit built, make sure we send
642 * the INTRODUCE cell _now_ */
643 connection_ap_attach_pending();
644 return 0;
647 /** Bob sent us a rendezvous cell; join the circuits. */
649 rend_client_receive_rendezvous(origin_circuit_t *circ, const char *request,
650 size_t request_len)
652 crypt_path_t *hop;
653 char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN];
655 if ((circ->_base.purpose != CIRCUIT_PURPOSE_C_REND_READY &&
656 circ->_base.purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)
657 || !circ->build_state->pending_final_cpath) {
658 log_warn(LD_PROTOCOL,"Got rendezvous2 cell from hidden service, but not "
659 "expecting it. Closing.");
660 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
661 return -1;
664 if (request_len != DH_KEY_LEN+DIGEST_LEN) {
665 log_warn(LD_PROTOCOL,"Incorrect length (%d) on RENDEZVOUS2 cell.",
666 (int)request_len);
667 goto err;
670 log_info(LD_REND,"Got RENDEZVOUS2 cell from hidden service.");
672 /* first DH_KEY_LEN bytes are g^y from bob. Finish the dh handshake...*/
673 tor_assert(circ->build_state);
674 tor_assert(circ->build_state->pending_final_cpath);
675 hop = circ->build_state->pending_final_cpath;
676 tor_assert(hop->dh_handshake_state);
677 if (crypto_dh_compute_secret(hop->dh_handshake_state, request, DH_KEY_LEN,
678 keys, DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
679 log_warn(LD_GENERAL, "Couldn't complete DH handshake.");
680 goto err;
682 /* ... and set up cpath. */
683 if (circuit_init_cpath_crypto(hop, keys+DIGEST_LEN, 0)<0)
684 goto err;
686 /* Check whether the digest is right... */
687 if (memcmp(keys, request+DH_KEY_LEN, DIGEST_LEN)) {
688 log_warn(LD_PROTOCOL, "Incorrect digest of key material.");
689 goto err;
692 crypto_dh_free(hop->dh_handshake_state);
693 hop->dh_handshake_state = NULL;
695 /* All is well. Extend the circuit. */
696 circ->_base.purpose = CIRCUIT_PURPOSE_C_REND_JOINED;
697 hop->state = CPATH_STATE_OPEN;
698 /* set the windows to default. these are the windows
699 * that alice thinks bob has.
701 hop->package_window = CIRCWINDOW_START;
702 hop->deliver_window = CIRCWINDOW_START;
704 onion_append_to_cpath(&circ->cpath, hop);
705 circ->build_state->pending_final_cpath = NULL; /* prevent double-free */
706 /* XXXX022 This is a pretty brute-force approach. It'd be better to
707 * attach only the connections that are waiting on this circuit, rather
708 * than trying to attach them all. See comments bug 743. */
709 connection_ap_attach_pending();
710 return 0;
711 err:
712 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
713 return -1;
716 /** Find all the apconns in state AP_CONN_STATE_RENDDESC_WAIT that
717 * are waiting on query. If there's a working cache entry here
718 * with at least one intro point, move them to the next state. If
719 * <b>rend_version</b> is non-negative, fail connections that have
720 * requested <b>query</b> unless there are still descriptor fetch
721 * requests in progress for other descriptor versions than
722 * <b>rend_version</b>.
724 void
725 rend_client_desc_trynow(const char *query, int rend_version)
727 edge_connection_t *conn;
728 rend_cache_entry_t *entry;
729 time_t now = time(NULL);
731 smartlist_t *conns = get_connection_array();
732 SMARTLIST_FOREACH(conns, connection_t *, _conn,
734 if (_conn->type != CONN_TYPE_AP ||
735 _conn->state != AP_CONN_STATE_RENDDESC_WAIT ||
736 _conn->marked_for_close)
737 continue;
738 conn = TO_EDGE_CONN(_conn);
739 if (!conn->rend_data)
740 continue;
741 if (rend_cmp_service_ids(query, conn->rend_data->onion_address))
742 continue;
743 assert_connection_ok(TO_CONN(conn), now);
744 if (rend_cache_lookup_entry(conn->rend_data->onion_address, -1,
745 &entry) == 1 &&
746 smartlist_len(entry->parsed->intro_nodes) > 0) {
747 /* either this fetch worked, or it failed but there was a
748 * valid entry from before which we should reuse */
749 log_info(LD_REND,"Rend desc is usable. Launching circuits.");
750 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
752 /* restart their timeout values, so they get a fair shake at
753 * connecting to the hidden service. */
754 conn->_base.timestamp_created = now;
755 conn->_base.timestamp_lastread = now;
756 conn->_base.timestamp_lastwritten = now;
758 if (connection_ap_handshake_attach_circuit(conn) < 0) {
759 /* it will never work */
760 log_warn(LD_REND,"Rendezvous attempt failed. Closing.");
761 if (!conn->_base.marked_for_close)
762 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
764 } else { /* 404, or fetch didn't get that far */
765 /* Unless there are requests for another descriptor version pending,
766 * close the connection. */
767 if (rend_version >= 0 &&
768 !connection_get_by_type_state_rendquery(CONN_TYPE_DIR, 0, query,
769 rend_version == 0 ? 2 : 0)) {
770 log_notice(LD_REND,"Closing stream for '%s.onion': hidden service is "
771 "unavailable (try again later).", safe_str(query));
772 connection_mark_unattached_ap(conn, END_STREAM_REASON_RESOLVEFAILED);
778 /** Return a newly allocated extend_info_t* for a randomly chosen introduction
779 * point for the named hidden service. Return NULL if all introduction points
780 * have been tried and failed.
782 extend_info_t *
783 rend_client_get_random_intro(const rend_data_t *rend_query)
785 int i;
786 rend_cache_entry_t *entry;
787 rend_intro_point_t *intro;
788 routerinfo_t *router;
790 if (rend_cache_lookup_entry(rend_query->onion_address, -1, &entry) < 1) {
791 log_warn(LD_REND,
792 "Query '%s' didn't have valid rend desc in cache. Failing.",
793 safe_str(rend_query->onion_address));
794 return NULL;
797 again:
798 if (smartlist_len(entry->parsed->intro_nodes) == 0)
799 return NULL;
801 i = crypto_rand_int(smartlist_len(entry->parsed->intro_nodes));
802 intro = smartlist_get(entry->parsed->intro_nodes, i);
803 /* Do we need to look up the router or is the extend info complete? */
804 if (!intro->extend_info->onion_key) {
805 router = router_get_by_nickname(intro->extend_info->nickname, 0);
806 if (!router) {
807 log_info(LD_REND, "Unknown router with nickname '%s'; trying another.",
808 intro->extend_info->nickname);
809 rend_intro_point_free(intro);
810 smartlist_del(entry->parsed->intro_nodes, i);
811 goto again;
813 extend_info_free(intro->extend_info);
814 intro->extend_info = extend_info_from_router(router);
816 return extend_info_dup(intro->extend_info);
819 /** Client-side authorizations for hidden services; map of onion address to
820 * rend_service_authorization_t*. */
821 static strmap_t *auth_hid_servs = NULL;
823 /** Look up the client-side authorization for the hidden service with
824 * <b>onion_address</b>. Return NULL if no authorization is available for
825 * that address. */
826 rend_service_authorization_t*
827 rend_client_lookup_service_authorization(const char *onion_address)
829 tor_assert(onion_address);
830 if (!auth_hid_servs) return NULL;
831 return strmap_get(auth_hid_servs, onion_address);
834 /** Helper: Free storage held by rend_service_authorization_t. */
835 static void
836 rend_service_authorization_free(rend_service_authorization_t *auth)
838 tor_free(auth);
841 /** Helper for strmap_free. */
842 static void
843 rend_service_authorization_strmap_item_free(void *service_auth)
845 rend_service_authorization_free(service_auth);
848 /** Release all the storage held in auth_hid_servs.
850 void
851 rend_service_authorization_free_all(void)
853 if (!auth_hid_servs) {
854 return;
856 strmap_free(auth_hid_servs, rend_service_authorization_strmap_item_free);
857 auth_hid_servs = NULL;
860 /** Parse <b>config_line</b> as a client-side authorization for a hidden
861 * service and add it to the local map of hidden service authorizations.
862 * Return 0 for success and -1 for failure. */
864 rend_parse_service_authorization(or_options_t *options, int validate_only)
866 config_line_t *line;
867 int res = -1;
868 strmap_t *parsed = strmap_new();
869 smartlist_t *sl = smartlist_create();
870 rend_service_authorization_t *auth = NULL;
872 for (line = options->HidServAuth; line; line = line->next) {
873 char *onion_address, *descriptor_cookie;
874 char descriptor_cookie_tmp[REND_DESC_COOKIE_LEN+2];
875 char descriptor_cookie_base64ext[REND_DESC_COOKIE_LEN_BASE64+2+1];
876 int auth_type_val = 0;
877 auth = NULL;
878 SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
879 smartlist_clear(sl);
880 smartlist_split_string(sl, line->value, " ",
881 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
882 if (smartlist_len(sl) < 2) {
883 log_warn(LD_CONFIG, "Configuration line does not consist of "
884 "\"onion-address authorization-cookie [service-name]\": "
885 "'%s'", line->value);
886 goto err;
888 auth = tor_malloc_zero(sizeof(rend_service_authorization_t));
889 /* Parse onion address. */
890 onion_address = smartlist_get(sl, 0);
891 if (strlen(onion_address) != REND_SERVICE_ADDRESS_LEN ||
892 strcmpend(onion_address, ".onion")) {
893 log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
894 onion_address);
895 goto err;
897 strlcpy(auth->onion_address, onion_address, REND_SERVICE_ID_LEN_BASE32+1);
898 if (!rend_valid_service_id(auth->onion_address)) {
899 log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
900 onion_address);
901 goto err;
903 /* Parse descriptor cookie. */
904 descriptor_cookie = smartlist_get(sl, 1);
905 if (strlen(descriptor_cookie) != REND_DESC_COOKIE_LEN_BASE64) {
906 log_warn(LD_CONFIG, "Authorization cookie has wrong length: '%s'",
907 descriptor_cookie);
908 goto err;
910 /* Add trailing zero bytes (AA) to make base64-decoding happy. */
911 tor_snprintf(descriptor_cookie_base64ext,
912 REND_DESC_COOKIE_LEN_BASE64+2+1,
913 "%sAA", descriptor_cookie);
914 if (base64_decode(descriptor_cookie_tmp, sizeof(descriptor_cookie_tmp),
915 descriptor_cookie_base64ext,
916 strlen(descriptor_cookie_base64ext)) < 0) {
917 log_warn(LD_CONFIG, "Decoding authorization cookie failed: '%s'",
918 descriptor_cookie);
919 goto err;
921 auth_type_val = (descriptor_cookie_tmp[16] >> 4) + 1;
922 if (auth_type_val < 1 || auth_type_val > 2) {
923 log_warn(LD_CONFIG, "Authorization cookie has unknown authorization "
924 "type encoded.");
925 goto err;
927 auth->auth_type = auth_type_val == 1 ? REND_BASIC_AUTH : REND_STEALTH_AUTH;
928 memcpy(auth->descriptor_cookie, descriptor_cookie_tmp,
929 REND_DESC_COOKIE_LEN);
930 if (strmap_get(parsed, auth->onion_address)) {
931 log_warn(LD_CONFIG, "Duplicate authorization for the same hidden "
932 "service.");
933 goto err;
935 strmap_set(parsed, auth->onion_address, auth);
936 auth = NULL;
938 res = 0;
939 goto done;
940 err:
941 res = -1;
942 done:
943 if (auth)
944 rend_service_authorization_free(auth);
945 SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
946 smartlist_free(sl);
947 if (!validate_only && res == 0) {
948 rend_service_authorization_free_all();
949 auth_hid_servs = parsed;
950 } else {
951 strmap_free(parsed, rend_service_authorization_strmap_item_free);
953 return res;