Clean up (and mark for 0.2.2.) comments relating to non-beauty of current bug-743...
[tor/rransom.git] / src / or / rendclient.c
blob3568d50d8691cb70dee82119519bad0e5b332e6f
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2008, 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) { /* unversioned 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 log_warn(LD_BUG, "Internal error: could not find intro key.");
98 goto err;
101 if (crypto_pk_get_digest(intro_key, payload)<0) {
102 log_warn(LD_BUG, "Internal error: couldn't hash public key.");
103 goto err;
106 /* Initialize the pending_final_cpath and start the DH handshake. */
107 cpath = rendcirc->build_state->pending_final_cpath;
108 if (!cpath) {
109 cpath = rendcirc->build_state->pending_final_cpath =
110 tor_malloc_zero(sizeof(crypt_path_t));
111 cpath->magic = CRYPT_PATH_MAGIC;
112 if (!(cpath->dh_handshake_state = crypto_dh_new())) {
113 log_warn(LD_BUG, "Internal error: couldn't allocate DH.");
114 goto err;
116 if (crypto_dh_generate_public(cpath->dh_handshake_state)<0) {
117 log_warn(LD_BUG, "Internal error: couldn't generate g^x.");
118 goto err;
122 /* If version is 3, write (optional) auth data and timestamp. */
123 if (entry->parsed->protocols & (1<<3)) {
124 tmp[0] = 3; /* version 3 of the cell format */
125 tmp[1] = (uint8_t)introcirc->rend_data->auth_type; /* auth type, if any */
126 v3_shift = 1;
127 if (introcirc->rend_data->auth_type != REND_NO_AUTH) {
128 set_uint16(tmp+2, htons(REND_DESC_COOKIE_LEN));
129 memcpy(tmp+4, introcirc->rend_data->descriptor_cookie,
130 REND_DESC_COOKIE_LEN);
131 v3_shift += 2+REND_DESC_COOKIE_LEN;
133 set_uint32(tmp+v3_shift+1, htonl(time(NULL)));
134 v3_shift += 4;
135 } /* if version 2 only write version number */
136 else if (entry->parsed->protocols & (1<<2)) {
137 tmp[0] = 2; /* version 2 of the cell format */
140 /* write the remaining items into tmp */
141 if (entry->parsed->protocols & (1<<3) || entry->parsed->protocols & (1<<2)) {
142 /* version 2 format */
143 extend_info_t *extend_info = rendcirc->build_state->chosen_exit;
144 int klen;
145 /* nul pads */
146 set_uint32(tmp+v3_shift+1, tor_addr_to_ipv4h(&extend_info->addr));
147 set_uint16(tmp+v3_shift+5, htons(extend_info->port));
148 memcpy(tmp+v3_shift+7, extend_info->identity_digest, DIGEST_LEN);
149 klen = crypto_pk_asn1_encode(extend_info->onion_key,
150 tmp+v3_shift+7+DIGEST_LEN+2,
151 sizeof(tmp)-(v3_shift+7+DIGEST_LEN+2));
152 set_uint16(tmp+v3_shift+7+DIGEST_LEN, htons(klen));
153 memcpy(tmp+v3_shift+7+DIGEST_LEN+2+klen, rendcirc->rend_data->rend_cookie,
154 REND_COOKIE_LEN);
155 dh_offset = v3_shift+7+DIGEST_LEN+2+klen+REND_COOKIE_LEN;
156 } else {
157 /* Version 0. */
158 strncpy(tmp, rendcirc->build_state->chosen_exit->nickname,
159 (MAX_NICKNAME_LEN+1)); /* nul pads */
160 memcpy(tmp+MAX_NICKNAME_LEN+1, rendcirc->rend_data->rend_cookie,
161 REND_COOKIE_LEN);
162 dh_offset = MAX_NICKNAME_LEN+1+REND_COOKIE_LEN;
165 if (crypto_dh_get_public(cpath->dh_handshake_state, tmp+dh_offset,
166 DH_KEY_LEN)<0) {
167 log_warn(LD_BUG, "Internal error: couldn't extract g^x.");
168 goto err;
171 note_crypto_pk_op(REND_CLIENT);
172 /*XXX maybe give crypto_pk_public_hybrid_encrypt a max_len arg,
173 * to avoid buffer overflows? */
174 r = crypto_pk_public_hybrid_encrypt(intro_key, payload+DIGEST_LEN,
175 tmp,
176 (int)(dh_offset+DH_KEY_LEN),
177 PK_PKCS1_OAEP_PADDING, 0);
178 if (r<0) {
179 log_warn(LD_BUG,"Internal error: hybrid pk encrypt failed.");
180 goto err;
183 payload_len = DIGEST_LEN + r;
184 tor_assert(payload_len <= RELAY_PAYLOAD_SIZE); /* we overran something */
186 log_info(LD_REND, "Sending an INTRODUCE1 cell");
187 if (relay_send_command_from_edge(0, TO_CIRCUIT(introcirc),
188 RELAY_COMMAND_INTRODUCE1,
189 payload, payload_len,
190 introcirc->cpath->prev)<0) {
191 /* introcirc is already marked for close. leave rendcirc alone. */
192 log_warn(LD_BUG, "Couldn't send INTRODUCE1 cell");
193 return -1;
196 /* Now, we wait for an ACK or NAK on this circuit. */
197 introcirc->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT;
199 return 0;
200 err:
201 circuit_mark_for_close(TO_CIRCUIT(introcirc), END_CIRC_REASON_INTERNAL);
202 circuit_mark_for_close(TO_CIRCUIT(rendcirc), END_CIRC_REASON_INTERNAL);
203 return -1;
206 /** Called when a rendezvous circuit is open; sends a establish
207 * rendezvous circuit as appropriate. */
208 void
209 rend_client_rendcirc_has_opened(origin_circuit_t *circ)
211 tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
213 log_info(LD_REND,"rendcirc is open");
215 /* generate a rendezvous cookie, store it in circ */
216 if (rend_client_send_establish_rendezvous(circ) < 0) {
217 return;
221 /** Called when get an ACK or a NAK for a REND_INTRODUCE1 cell.
224 rend_client_introduction_acked(origin_circuit_t *circ,
225 const char *request, size_t request_len)
227 origin_circuit_t *rendcirc;
228 (void) request; // XXXX Use this.
230 if (circ->_base.purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
231 log_warn(LD_PROTOCOL,
232 "Received REND_INTRODUCE_ACK on unexpected circuit %d.",
233 circ->_base.n_circ_id);
234 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
235 return -1;
238 tor_assert(circ->build_state->chosen_exit);
239 tor_assert(circ->rend_data);
241 if (request_len == 0) {
242 /* It's an ACK; the introduction point relayed our introduction request. */
243 /* Locate the rend circ which is waiting to hear about this ack,
244 * and tell it.
246 log_info(LD_REND,"Received ack. Telling rend circ...");
247 rendcirc = circuit_get_by_rend_query_and_purpose(
248 circ->rend_data->onion_address, CIRCUIT_PURPOSE_C_REND_READY);
249 if (rendcirc) { /* remember the ack */
250 rendcirc->_base.purpose = CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED;
251 } else {
252 log_info(LD_REND,"...Found no rend circ. Dropping on the floor.");
254 /* close the circuit: we won't need it anymore. */
255 circ->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCE_ACKED;
256 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
257 } else {
258 /* It's a NAK; the introduction point didn't relay our request. */
259 circ->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
260 /* Remove this intro point from the set of viable introduction
261 * points. If any remain, extend to a new one and try again.
262 * If none remain, refetch the service descriptor.
264 if (rend_client_remove_intro_point(circ->build_state->chosen_exit,
265 circ->rend_data) > 0) {
266 /* There are introduction points left. Re-extend the circuit to
267 * another intro point and try again. */
268 extend_info_t *extend_info;
269 int result;
270 extend_info = rend_client_get_random_intro(circ->rend_data);
271 if (!extend_info) {
272 log_warn(LD_REND, "No introduction points left for %s. Closing.",
273 escaped_safe_str(circ->rend_data->onion_address));
274 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
275 return -1;
277 log_info(LD_REND,
278 "Got nack for %s from %s. Re-extending circ %d, "
279 "this time to %s.",
280 escaped_safe_str(circ->rend_data->onion_address),
281 circ->build_state->chosen_exit->nickname, circ->_base.n_circ_id,
282 extend_info->nickname);
283 result = circuit_extend_to_new_exit(circ, extend_info);
284 extend_info_free(extend_info);
285 return result;
288 return 0;
291 /** The period for which a hidden service directory cannot be queried for
292 * the same descriptor ID again. */
293 #define REND_HID_SERV_DIR_REQUERY_PERIOD (15 * 60)
295 /** Contains the last request times to hidden service directories for
296 * certain queries; keys are strings consisting of base32-encoded
297 * hidden service directory identities and base32-encoded descriptor IDs;
298 * values are pointers to timestamps of the last requests. */
299 static strmap_t *last_hid_serv_requests = NULL;
301 /** Look up the last request time to hidden service directory <b>hs_dir</b>
302 * for descriptor ID <b>desc_id_base32</b>. If <b>set</b> is non-zero,
303 * assign the current time <b>now</b> and return that. Otherwise, return
304 * the most recent request time, or 0 if no such request has been sent
305 * before. */
306 static time_t
307 lookup_last_hid_serv_request(routerstatus_t *hs_dir,
308 const char *desc_id_base32, time_t now, int set)
310 char hsdir_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
311 char hsdir_desc_comb_id[2 * REND_DESC_ID_V2_LEN_BASE32 + 1];
312 time_t *last_request_ptr;
313 base32_encode(hsdir_id_base32, sizeof(hsdir_id_base32),
314 hs_dir->identity_digest, DIGEST_LEN);
315 tor_snprintf(hsdir_desc_comb_id, sizeof(hsdir_desc_comb_id), "%s%s",
316 hsdir_id_base32, desc_id_base32);
317 if (set) {
318 last_request_ptr = tor_malloc_zero(sizeof(time_t *));
319 *last_request_ptr = now;
320 strmap_set(last_hid_serv_requests, hsdir_desc_comb_id, last_request_ptr);
321 } else
322 last_request_ptr = strmap_get_lc(last_hid_serv_requests,
323 hsdir_desc_comb_id);
324 return (last_request_ptr) ? *last_request_ptr : 0;
327 /** Clean the history of request times to hidden service directories, so that
328 * it does not contain requests older than REND_HID_SERV_DIR_REQUERY_PERIOD
329 * seconds any more. */
330 static void
331 directory_clean_last_hid_serv_requests(void)
333 strmap_iter_t *iter;
334 time_t cutoff = time(NULL) - REND_HID_SERV_DIR_REQUERY_PERIOD;
335 if (!last_hid_serv_requests)
336 last_hid_serv_requests = strmap_new();
337 for (iter = strmap_iter_init(last_hid_serv_requests);
338 !strmap_iter_done(iter); ) {
339 const char *key;
340 void *val;
341 time_t *ent;
342 strmap_iter_get(iter, &key, &val);
343 ent = (time_t *) val;
344 if (*ent < cutoff) {
345 iter = strmap_iter_next_rmv(last_hid_serv_requests, iter);
346 tor_free(ent);
347 } else {
348 iter = strmap_iter_next(last_hid_serv_requests, iter);
353 /** Determine the responsible hidden service directories for <b>desc_id</b>
354 * and fetch the descriptor belonging to that ID from one of them. Only
355 * send a request to hidden service directories that we did not try within
356 * the last REND_HID_SERV_DIR_REQUERY_PERIOD seconds; on success, return 1,
357 * in the case that no hidden service directory is left to ask for the
358 * descriptor, return 0, and in case of a failure -1. <b>query</b> is only
359 * passed for pretty log statements. */
360 static int
361 directory_get_from_hs_dir(const char *desc_id, const rend_data_t *rend_query)
363 smartlist_t *responsible_dirs = smartlist_create();
364 routerstatus_t *hs_dir;
365 char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
366 time_t now = time(NULL);
367 char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
368 tor_assert(desc_id);
369 tor_assert(rend_query);
370 /* Determine responsible dirs. Even if we can't get all we want,
371 * work with the ones we have. If it's empty, we'll notice below. */
372 (int) hid_serv_get_responsible_directories(responsible_dirs, desc_id);
374 base32_encode(desc_id_base32, sizeof(desc_id_base32),
375 desc_id, DIGEST_LEN);
377 /* Only select those hidden service directories to which we did not send
378 * a request recently and for which we have a router descriptor here. */
379 directory_clean_last_hid_serv_requests(); /* Clean request history first. */
381 SMARTLIST_FOREACH(responsible_dirs, routerstatus_t *, dir, {
382 if (lookup_last_hid_serv_request(dir, desc_id_base32, 0, 0) +
383 REND_HID_SERV_DIR_REQUERY_PERIOD >= now ||
384 !router_get_by_digest(dir->identity_digest))
385 SMARTLIST_DEL_CURRENT(responsible_dirs, dir);
388 hs_dir = smartlist_choose(responsible_dirs);
389 smartlist_free(responsible_dirs);
390 if (!hs_dir) {
391 log_info(LD_REND, "Could not pick one of the responsible hidden "
392 "service directories, because we requested them all "
393 "recently without success.");
394 return 0;
397 /* Remember, that we are requesting a descriptor from this hidden service
398 * directory now. */
399 lookup_last_hid_serv_request(hs_dir, desc_id_base32, now, 1);
401 /* Encode descriptor cookie for logging purposes. */
402 if (rend_query->auth_type != REND_NO_AUTH) {
403 if (base64_encode(descriptor_cookie_base64,
404 sizeof(descriptor_cookie_base64),
405 rend_query->descriptor_cookie, REND_DESC_COOKIE_LEN)<0) {
406 log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
407 return 0;
409 /* Remove == signs and newline. */
410 descriptor_cookie_base64[strlen(descriptor_cookie_base64)-3] = '\0';
411 } else {
412 strlcpy(descriptor_cookie_base64, "(none)",
413 sizeof(descriptor_cookie_base64));
416 /* Send fetch request. (Pass query and possibly descriptor cookie so that
417 * they can be written to the directory connection and be referred to when
418 * the response arrives. */
419 directory_initiate_command_routerstatus_rend(hs_dir,
420 DIR_PURPOSE_FETCH_RENDDESC_V2,
421 ROUTER_PURPOSE_GENERAL,
422 1, desc_id_base32, NULL, 0, 0,
423 rend_query);
424 log_info(LD_REND, "Sending fetch request for v2 descriptor for "
425 "service '%s' with descriptor ID '%s', auth type %d, "
426 "and descriptor cookie '%s' to hidden service "
427 "directory '%s' on port %d.",
428 rend_query->onion_address, desc_id_base32,
429 rend_query->auth_type,
430 (rend_query->auth_type == REND_NO_AUTH ? "[none]" :
431 escaped_safe_str(descriptor_cookie_base64)),
432 hs_dir->nickname, hs_dir->dir_port);
433 return 1;
436 /** If we are not currently fetching a rendezvous service descriptor
437 * for the service ID <b>query</b>, start a directory connection to fetch a
438 * new one.
440 void
441 rend_client_refetch_renddesc(const char *query)
443 if (!get_options()->FetchHidServDescriptors)
444 return;
445 log_info(LD_REND, "Fetching rendezvous descriptor for service %s",
446 escaped_safe_str(query));
447 if (connection_get_by_type_state_rendquery(CONN_TYPE_DIR, 0, query, 0)) {
448 log_info(LD_REND,"Would fetch a new renddesc here (for %s), but one is "
449 "already in progress.", escaped_safe_str(query));
450 } else {
451 /* not one already; initiate a dir rend desc lookup */
452 directory_get_from_dirserver(DIR_PURPOSE_FETCH_RENDDESC,
453 ROUTER_PURPOSE_GENERAL, query,
454 PDS_RETRY_IF_NO_SERVERS);
458 /** Start a connection to a hidden service directory to fetch a v2
459 * rendezvous service descriptor for the base32-encoded service ID
460 * <b>query</b>.
462 void
463 rend_client_refetch_v2_renddesc(const rend_data_t *rend_query)
465 char descriptor_id[DIGEST_LEN];
466 int replicas_left_to_try[REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS];
467 int i, tries_left;
468 rend_cache_entry_t *e = NULL;
469 tor_assert(rend_query);
470 /* Are we configured to fetch descriptors? */
471 if (!get_options()->FetchHidServDescriptors) {
472 log_warn(LD_REND, "We received an onion address for a v2 rendezvous "
473 "service descriptor, but are not fetching service descriptors.");
474 return;
476 /* Before fetching, check if we already have the descriptor here. */
477 if (rend_cache_lookup_entry(rend_query->onion_address, -1, &e) > 0) {
478 log_info(LD_REND, "We would fetch a v2 rendezvous descriptor, but we "
479 "already have that descriptor here. Not fetching.");
480 return;
482 log_debug(LD_REND, "Fetching v2 rendezvous descriptor for service %s",
483 safe_str(rend_query->onion_address));
484 /* Randomly iterate over the replicas until a descriptor can be fetched
485 * from one of the consecutive nodes, or no options are left. */
486 tries_left = REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS;
487 for (i = 0; i < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; i++)
488 replicas_left_to_try[i] = i;
489 while (tries_left > 0) {
490 int rand = crypto_rand_int(tries_left);
491 int chosen_replica = replicas_left_to_try[rand];
492 replicas_left_to_try[rand] = replicas_left_to_try[--tries_left];
494 if (rend_compute_v2_desc_id(descriptor_id, rend_query->onion_address,
495 rend_query->auth_type == REND_STEALTH_AUTH ?
496 rend_query->descriptor_cookie : NULL,
497 time(NULL), chosen_replica) < 0) {
498 log_warn(LD_REND, "Internal error: Computing v2 rendezvous "
499 "descriptor ID did not succeed.");
500 return;
502 if (directory_get_from_hs_dir(descriptor_id, rend_query) != 0)
503 return; /* either success or failure, but we're done */
505 /* If we come here, there are no hidden service directories left. */
506 log_info(LD_REND, "Could not pick one of the responsible hidden "
507 "service directories to fetch descriptors, because "
508 "we already tried them all unsuccessfully.");
509 /* Close pending connections (unless a v0 request is still going on). */
510 rend_client_desc_trynow(rend_query->onion_address, 2);
511 return;
514 /** Remove failed_intro from ent. If ent now has no intro points, or
515 * service is unrecognized, then launch a new renddesc fetch.
517 * Return -1 if error, 0 if no intro points remain or service
518 * unrecognized, 1 if recognized and some intro points remain.
521 rend_client_remove_intro_point(extend_info_t *failed_intro,
522 const rend_data_t *rend_query)
524 int i, r;
525 rend_cache_entry_t *ent;
526 connection_t *conn;
528 r = rend_cache_lookup_entry(rend_query->onion_address, -1, &ent);
529 if (r<0) {
530 log_warn(LD_BUG, "Malformed service ID %s.",
531 escaped_safe_str(rend_query->onion_address));
532 return -1;
534 if (r==0) {
535 log_info(LD_REND, "Unknown service %s. Re-fetching descriptor.",
536 escaped_safe_str(rend_query->onion_address));
537 /* Fetch both, v0 and v2 rend descriptors in parallel. Use whichever
538 * arrives first. Exception: When using client authorization, only
539 * fetch v2 descriptors.*/
540 rend_client_refetch_v2_renddesc(rend_query);
541 if (rend_query->auth_type == REND_NO_AUTH)
542 rend_client_refetch_renddesc(rend_query->onion_address);
543 return 0;
546 for (i = 0; i < smartlist_len(ent->parsed->intro_nodes); i++) {
547 rend_intro_point_t *intro = smartlist_get(ent->parsed->intro_nodes, i);
548 if (!memcmp(failed_intro->identity_digest,
549 intro->extend_info->identity_digest, DIGEST_LEN)) {
550 rend_intro_point_free(intro);
551 smartlist_del(ent->parsed->intro_nodes, i);
552 break;
556 if (smartlist_len(ent->parsed->intro_nodes) == 0) {
557 log_info(LD_REND,
558 "No more intro points remain for %s. Re-fetching descriptor.",
559 escaped_safe_str(rend_query->onion_address));
560 /* Fetch both, v0 and v2 rend descriptors in parallel. Use whichever
561 * arrives first. Exception: When using client authorization, only
562 * fetch v2 descriptors.*/
563 rend_client_refetch_v2_renddesc(rend_query);
564 if (rend_query->auth_type == REND_NO_AUTH)
565 rend_client_refetch_renddesc(rend_query->onion_address);
567 /* move all pending streams back to renddesc_wait */
568 while ((conn = connection_get_by_type_state_rendquery(CONN_TYPE_AP,
569 AP_CONN_STATE_CIRCUIT_WAIT,
570 rend_query->onion_address, -1))) {
571 conn->state = AP_CONN_STATE_RENDDESC_WAIT;
574 return 0;
576 log_info(LD_REND,"%d options left for %s.",
577 smartlist_len(ent->parsed->intro_nodes),
578 escaped_safe_str(rend_query->onion_address));
579 return 1;
582 /** Called when we receive a RENDEZVOUS_ESTABLISHED cell; changes the state of
583 * the circuit to C_REND_READY.
586 rend_client_rendezvous_acked(origin_circuit_t *circ, const char *request,
587 size_t request_len)
589 (void) request;
590 (void) request_len;
591 /* we just got an ack for our establish-rendezvous. switch purposes. */
592 if (circ->_base.purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND) {
593 log_warn(LD_PROTOCOL,"Got a rendezvous ack when we weren't expecting one. "
594 "Closing circ.");
595 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
596 return -1;
598 log_info(LD_REND,"Got rendezvous ack. This circuit is now ready for "
599 "rendezvous.");
600 circ->_base.purpose = CIRCUIT_PURPOSE_C_REND_READY;
601 /* XXXX022 This is a pretty brute-force approach. It'd be better to
602 * attach only the connections that are waiting on this circuit, rather
603 * than trying to attach them all. See comments bug 743. */
604 /* If we already have the introduction circuit built, make sure we send
605 * the INTRODUCE cell _now_ */
606 connection_ap_attach_pending();
607 return 0;
610 /** Bob sent us a rendezvous cell; join the circuits. */
612 rend_client_receive_rendezvous(origin_circuit_t *circ, const char *request,
613 size_t request_len)
615 crypt_path_t *hop;
616 char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN];
618 if ((circ->_base.purpose != CIRCUIT_PURPOSE_C_REND_READY &&
619 circ->_base.purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)
620 || !circ->build_state->pending_final_cpath) {
621 log_warn(LD_PROTOCOL,"Got rendezvous2 cell from hidden service, but not "
622 "expecting it. Closing.");
623 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
624 return -1;
627 if (request_len != DH_KEY_LEN+DIGEST_LEN) {
628 log_warn(LD_PROTOCOL,"Incorrect length (%d) on RENDEZVOUS2 cell.",
629 (int)request_len);
630 goto err;
633 log_info(LD_REND,"Got RENDEZVOUS2 cell from hidden service.");
635 /* first DH_KEY_LEN bytes are g^y from bob. Finish the dh handshake...*/
636 tor_assert(circ->build_state);
637 tor_assert(circ->build_state->pending_final_cpath);
638 hop = circ->build_state->pending_final_cpath;
639 tor_assert(hop->dh_handshake_state);
640 if (crypto_dh_compute_secret(hop->dh_handshake_state, request, DH_KEY_LEN,
641 keys, DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
642 log_warn(LD_GENERAL, "Couldn't complete DH handshake.");
643 goto err;
645 /* ... and set up cpath. */
646 if (circuit_init_cpath_crypto(hop, keys+DIGEST_LEN, 0)<0)
647 goto err;
649 /* Check whether the digest is right... */
650 if (memcmp(keys, request+DH_KEY_LEN, DIGEST_LEN)) {
651 log_warn(LD_PROTOCOL, "Incorrect digest of key material.");
652 goto err;
655 crypto_dh_free(hop->dh_handshake_state);
656 hop->dh_handshake_state = NULL;
658 /* All is well. Extend the circuit. */
659 circ->_base.purpose = CIRCUIT_PURPOSE_C_REND_JOINED;
660 hop->state = CPATH_STATE_OPEN;
661 /* set the windows to default. these are the windows
662 * that alice thinks bob has.
664 hop->package_window = CIRCWINDOW_START;
665 hop->deliver_window = CIRCWINDOW_START;
667 onion_append_to_cpath(&circ->cpath, hop);
668 circ->build_state->pending_final_cpath = NULL; /* prevent double-free */
669 /* XXXX022 This is a pretty brute-force approach. It'd be better to
670 * attach only the connections that are waiting on this circuit, rather
671 * than trying to attach them all. See comments bug 743. */
672 connection_ap_attach_pending();
673 return 0;
674 err:
675 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
676 return -1;
679 /** Find all the apconns in state AP_CONN_STATE_RENDDESC_WAIT that
680 * are waiting on query. If there's a working cache entry here
681 * with at least one intro point, move them to the next state. If
682 * <b>rend_version</b> is non-negative, fail connections that have
683 * requested <b>query</b> unless there are still descriptor fetch
684 * requests in progress for other descriptor versions than
685 * <b>rend_version</b>.
687 void
688 rend_client_desc_trynow(const char *query, int rend_version)
690 edge_connection_t *conn;
691 rend_cache_entry_t *entry;
692 time_t now = time(NULL);
694 smartlist_t *conns = get_connection_array();
695 SMARTLIST_FOREACH(conns, connection_t *, _conn,
697 if (_conn->type != CONN_TYPE_AP ||
698 _conn->state != AP_CONN_STATE_RENDDESC_WAIT ||
699 _conn->marked_for_close)
700 continue;
701 conn = TO_EDGE_CONN(_conn);
702 if (!conn->rend_data)
703 continue;
704 if (rend_cmp_service_ids(query, conn->rend_data->onion_address))
705 continue;
706 assert_connection_ok(TO_CONN(conn), now);
707 if (rend_cache_lookup_entry(conn->rend_data->onion_address, -1,
708 &entry) == 1 &&
709 smartlist_len(entry->parsed->intro_nodes) > 0) {
710 /* either this fetch worked, or it failed but there was a
711 * valid entry from before which we should reuse */
712 log_info(LD_REND,"Rend desc is usable. Launching circuits.");
713 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
715 /* restart their timeout values, so they get a fair shake at
716 * connecting to the hidden service. */
717 conn->_base.timestamp_created = now;
718 conn->_base.timestamp_lastread = now;
719 conn->_base.timestamp_lastwritten = now;
721 if (connection_ap_handshake_attach_circuit(conn) < 0) {
722 /* it will never work */
723 log_warn(LD_REND,"Rendezvous attempt failed. Closing.");
724 if (!conn->_base.marked_for_close)
725 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
727 } else { /* 404, or fetch didn't get that far */
728 /* Unless there are requests for another descriptor version pending,
729 * close the connection. */
730 if (rend_version >= 0 &&
731 !connection_get_by_type_state_rendquery(CONN_TYPE_DIR, 0, query,
732 rend_version == 0 ? 2 : 0)) {
733 log_notice(LD_REND,"Closing stream for '%s.onion': hidden service is "
734 "unavailable (try again later).", safe_str(query));
735 connection_mark_unattached_ap(conn, END_STREAM_REASON_RESOLVEFAILED);
741 /** Return a newly allocated extend_info_t* for a randomly chosen introduction
742 * point for the named hidden service. Return NULL if all introduction points
743 * have been tried and failed.
745 extend_info_t *
746 rend_client_get_random_intro(const rend_data_t *rend_query)
748 int i;
749 rend_cache_entry_t *entry;
750 rend_intro_point_t *intro;
751 routerinfo_t *router;
753 if (rend_cache_lookup_entry(rend_query->onion_address, -1, &entry) < 1) {
754 log_warn(LD_REND,
755 "Query '%s' didn't have valid rend desc in cache. Failing.",
756 safe_str(rend_query->onion_address));
757 return NULL;
760 again:
761 if (smartlist_len(entry->parsed->intro_nodes) == 0)
762 return NULL;
764 i = crypto_rand_int(smartlist_len(entry->parsed->intro_nodes));
765 intro = smartlist_get(entry->parsed->intro_nodes, i);
766 /* Do we need to look up the router or is the extend info complete? */
767 if (!intro->extend_info->onion_key) {
768 router = router_get_by_nickname(intro->extend_info->nickname, 0);
769 if (!router) {
770 log_info(LD_REND, "Unknown router with nickname '%s'; trying another.",
771 intro->extend_info->nickname);
772 rend_intro_point_free(intro);
773 smartlist_del(entry->parsed->intro_nodes, i);
774 goto again;
776 extend_info_free(intro->extend_info);
777 intro->extend_info = extend_info_from_router(router);
779 return extend_info_dup(intro->extend_info);
782 /** Client-side authorizations for hidden services; map of onion address to
783 * rend_service_authorization_t*. */
784 static strmap_t *auth_hid_servs = NULL;
786 /** Look up the client-side authorization for the hidden service with
787 * <b>onion_address</b>. Return NULL if no authorization is available for
788 * that address. */
789 rend_service_authorization_t*
790 rend_client_lookup_service_authorization(const char *onion_address)
792 tor_assert(onion_address);
793 if (!auth_hid_servs) return NULL;
794 return strmap_get(auth_hid_servs, onion_address);
797 /** Helper: Free storage held by rend_service_authorization_t. */
798 static void
799 rend_service_authorization_free(rend_service_authorization_t *auth)
801 tor_free(auth);
804 /** Helper for strmap_free. */
805 static void
806 rend_service_authorization_strmap_item_free(void *service_auth)
808 rend_service_authorization_free(service_auth);
811 /** Release all the storage held in auth_hid_servs.
813 void
814 rend_service_authorization_free_all(void)
816 if (!auth_hid_servs) {
817 return;
819 strmap_free(auth_hid_servs, rend_service_authorization_strmap_item_free);
820 auth_hid_servs = NULL;
823 /** Parse <b>config_line</b> as a client-side authorization for a hidden
824 * service and add it to the local map of hidden service authorizations.
825 * Return 0 for success and -1 for failure. */
827 rend_parse_service_authorization(or_options_t *options, int validate_only)
829 config_line_t *line;
830 int res = -1;
831 strmap_t *parsed = strmap_new();
832 smartlist_t *sl = smartlist_create();
833 rend_service_authorization_t *auth = NULL;
835 for (line = options->HidServAuth; line; line = line->next) {
836 char *onion_address, *descriptor_cookie;
837 char descriptor_cookie_tmp[REND_DESC_COOKIE_LEN+2];
838 char descriptor_cookie_base64ext[REND_DESC_COOKIE_LEN_BASE64+2+1];
839 int auth_type_val = 0;
840 auth = NULL;
841 SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
842 smartlist_clear(sl);
843 smartlist_split_string(sl, line->value, " ",
844 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
845 if (smartlist_len(sl) < 2) {
846 log_warn(LD_CONFIG, "Configuration line does not consist of "
847 "\"onion-address authorization-cookie [service-name]\": "
848 "'%s'", line->value);
849 goto err;
851 auth = tor_malloc_zero(sizeof(rend_service_authorization_t));
852 /* Parse onion address. */
853 onion_address = smartlist_get(sl, 0);
854 if (strlen(onion_address) != REND_SERVICE_ADDRESS_LEN ||
855 strcmpend(onion_address, ".onion")) {
856 log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
857 onion_address);
858 goto err;
860 strlcpy(auth->onion_address, onion_address, REND_SERVICE_ID_LEN_BASE32+1);
861 if (!rend_valid_service_id(auth->onion_address)) {
862 log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
863 onion_address);
864 goto err;
866 /* Parse descriptor cookie. */
867 descriptor_cookie = smartlist_get(sl, 1);
868 if (strlen(descriptor_cookie) != REND_DESC_COOKIE_LEN_BASE64) {
869 log_warn(LD_CONFIG, "Authorization cookie has wrong length: '%s'",
870 descriptor_cookie);
871 goto err;
873 /* Add trailing zero bytes (AA) to make base64-decoding happy. */
874 tor_snprintf(descriptor_cookie_base64ext,
875 REND_DESC_COOKIE_LEN_BASE64+2+1,
876 "%sAA", descriptor_cookie);
877 if (base64_decode(descriptor_cookie_tmp, sizeof(descriptor_cookie_tmp),
878 descriptor_cookie_base64ext,
879 strlen(descriptor_cookie_base64ext)) < 0) {
880 log_warn(LD_CONFIG, "Decoding authorization cookie failed: '%s'",
881 descriptor_cookie);
882 goto err;
884 auth_type_val = (descriptor_cookie_tmp[16] >> 4) + 1;
885 if (auth_type_val < 1 || auth_type_val > 2) {
886 log_warn(LD_CONFIG, "Authorization cookie has unknown authorization "
887 "type encoded.");
888 goto err;
890 auth->auth_type = auth_type_val == 1 ? REND_BASIC_AUTH : REND_STEALTH_AUTH;
891 memcpy(auth->descriptor_cookie, descriptor_cookie_tmp,
892 REND_DESC_COOKIE_LEN);
893 if (strmap_get(parsed, auth->onion_address)) {
894 log_warn(LD_CONFIG, "Duplicate authorization for the same hidden "
895 "service.");
896 goto err;
898 strmap_set(parsed, auth->onion_address, auth);
899 auth = NULL;
901 res = 0;
902 goto done;
903 err:
904 res = -1;
905 done:
906 if (auth)
907 rend_service_authorization_free(auth);
908 SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
909 smartlist_free(sl);
910 if (!validate_only && res == 0) {
911 rend_service_authorization_free_all();
912 auth_hid_servs = parsed;
913 } else {
914 strmap_free(parsed, rend_service_authorization_strmap_item_free);
916 return res;