Update Tor Project copyright years
[tor/rransom.git] / src / or / rendcommon.c
blob1f9596de2eb65f791ed9654a396c28be2781b5f9
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2010, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
5 /**
6 * \file rendcommon.c
7 * \brief Rendezvous implementation: shared code between
8 * introducers, services, clients, and rendezvous points.
9 **/
11 #include "or.h"
13 /** Return 0 if one and two are the same service ids, else -1 or 1 */
14 int
15 rend_cmp_service_ids(const char *one, const char *two)
17 return strcasecmp(one,two);
20 /** Free the storage held by the service descriptor <b>desc</b>.
22 void
23 rend_service_descriptor_free(rend_service_descriptor_t *desc)
25 if (desc->pk)
26 crypto_free_pk_env(desc->pk);
27 if (desc->intro_nodes) {
28 SMARTLIST_FOREACH(desc->intro_nodes, rend_intro_point_t *, intro,
29 rend_intro_point_free(intro););
30 smartlist_free(desc->intro_nodes);
32 if (desc->successful_uploads) {
33 SMARTLIST_FOREACH(desc->successful_uploads, char *, c, tor_free(c););
34 smartlist_free(desc->successful_uploads);
36 tor_free(desc);
39 /** Length of the descriptor cookie that is used for versioned hidden
40 * service descriptors. */
41 #define REND_DESC_COOKIE_LEN 16
43 /** Length of the replica number that is used to determine the secret ID
44 * part of versioned hidden service descriptors. */
45 #define REND_REPLICA_LEN 1
47 /** Compute the descriptor ID for <b>service_id</b> of length
48 * <b>REND_SERVICE_ID_LEN</b> and <b>secret_id_part</b> of length
49 * <b>DIGEST_LEN</b>, and write it to <b>descriptor_id_out</b> of length
50 * <b>DIGEST_LEN</b>. */
51 void
52 rend_get_descriptor_id_bytes(char *descriptor_id_out,
53 const char *service_id,
54 const char *secret_id_part)
56 crypto_digest_env_t *digest = crypto_new_digest_env();
57 crypto_digest_add_bytes(digest, service_id, REND_SERVICE_ID_LEN);
58 crypto_digest_add_bytes(digest, secret_id_part, DIGEST_LEN);
59 crypto_digest_get_digest(digest, descriptor_id_out, DIGEST_LEN);
60 crypto_free_digest_env(digest);
63 /** Compute the secret ID part for time_period,
64 * a <b>descriptor_cookie</b> of length
65 * <b>REND_DESC_COOKIE_LEN</b> which may also be <b>NULL</b> if no
66 * descriptor_cookie shall be used, and <b>replica</b>, and write it to
67 * <b>secret_id_part</b> of length DIGEST_LEN. */
68 static void
69 get_secret_id_part_bytes(char *secret_id_part, uint32_t time_period,
70 const char *descriptor_cookie, uint8_t replica)
72 crypto_digest_env_t *digest = crypto_new_digest_env();
73 time_period = htonl(time_period);
74 crypto_digest_add_bytes(digest, (char*)&time_period, sizeof(uint32_t));
75 if (descriptor_cookie) {
76 crypto_digest_add_bytes(digest, descriptor_cookie,
77 REND_DESC_COOKIE_LEN);
79 crypto_digest_add_bytes(digest, (const char *)&replica, REND_REPLICA_LEN);
80 crypto_digest_get_digest(digest, secret_id_part, DIGEST_LEN);
81 crypto_free_digest_env(digest);
84 /** Return the time period for time <b>now</b> plus a potentially
85 * intended <b>deviation</b> of one or more periods, based on the first byte
86 * of <b>service_id</b>. */
87 static uint32_t
88 get_time_period(time_t now, uint8_t deviation, const char *service_id)
90 /* The time period is the number of REND_TIME_PERIOD_V2_DESC_VALIDITY
91 * intervals that have passed since the epoch, offset slightly so that
92 * each service's time periods start and end at a fraction of that
93 * period based on their first byte. */
94 return (uint32_t)
95 (now + ((uint8_t) *service_id) * REND_TIME_PERIOD_V2_DESC_VALIDITY / 256)
96 / REND_TIME_PERIOD_V2_DESC_VALIDITY + deviation;
99 /** Compute the time in seconds that a descriptor that is generated
100 * <b>now</b> for <b>service_id</b> will be valid. */
101 static uint32_t
102 get_seconds_valid(time_t now, const char *service_id)
104 uint32_t result = REND_TIME_PERIOD_V2_DESC_VALIDITY -
105 ((uint32_t)
106 (now + ((uint8_t) *service_id) * REND_TIME_PERIOD_V2_DESC_VALIDITY / 256)
107 % REND_TIME_PERIOD_V2_DESC_VALIDITY);
108 return result;
111 /** Compute the binary <b>desc_id_out</b> (DIGEST_LEN bytes long) for a given
112 * base32-encoded <b>service_id</b> and optional unencoded
113 * <b>descriptor_cookie</b> of length REND_DESC_COOKIE_LEN,
114 * at time <b>now</b> for replica number
115 * <b>replica</b>. <b>desc_id</b> needs to have <b>DIGEST_LEN</b> bytes
116 * free. Return 0 for success, -1 otherwise. */
118 rend_compute_v2_desc_id(char *desc_id_out, const char *service_id,
119 const char *descriptor_cookie, time_t now,
120 uint8_t replica)
122 char service_id_binary[REND_SERVICE_ID_LEN];
123 char secret_id_part[DIGEST_LEN];
124 uint32_t time_period;
125 if (!service_id ||
126 strlen(service_id) != REND_SERVICE_ID_LEN_BASE32) {
127 log_warn(LD_REND, "Could not compute v2 descriptor ID: "
128 "Illegal service ID: %s", safe_str(service_id));
129 return -1;
131 if (replica >= REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS) {
132 log_warn(LD_REND, "Could not compute v2 descriptor ID: "
133 "Replica number out of range: %d", replica);
134 return -1;
136 /* Convert service ID to binary. */
137 if (base32_decode(service_id_binary, REND_SERVICE_ID_LEN,
138 service_id, REND_SERVICE_ID_LEN_BASE32) < 0) {
139 log_warn(LD_REND, "Could not compute v2 descriptor ID: "
140 "Illegal characters in service ID: %s",
141 safe_str(service_id));
142 return -1;
144 /* Calculate current time-period. */
145 time_period = get_time_period(now, 0, service_id_binary);
146 /* Calculate secret-id-part = h(time-period + replica). */
147 get_secret_id_part_bytes(secret_id_part, time_period, descriptor_cookie,
148 replica);
149 /* Calculate descriptor ID. */
150 rend_get_descriptor_id_bytes(desc_id_out, service_id_binary, secret_id_part);
151 return 0;
154 /** Encode the introduction points in <b>desc</b> and write the result to a
155 * newly allocated string pointed to by <b>encoded</b>. Return 0 for
156 * success, -1 otherwise. */
157 static int
158 rend_encode_v2_intro_points(char **encoded, rend_service_descriptor_t *desc)
160 size_t unenc_len;
161 char *unenc = NULL;
162 size_t unenc_written = 0;
163 int i;
164 int r = -1;
165 /* Assemble unencrypted list of introduction points. */
166 unenc_len = smartlist_len(desc->intro_nodes) * 1000; /* too long, but ok. */
167 unenc = tor_malloc_zero(unenc_len);
168 for (i = 0; i < smartlist_len(desc->intro_nodes); i++) {
169 char id_base32[REND_INTRO_POINT_ID_LEN_BASE32 + 1];
170 char *onion_key = NULL;
171 size_t onion_key_len;
172 crypto_pk_env_t *intro_key;
173 char *service_key = NULL;
174 char *address = NULL;
175 size_t service_key_len;
176 int res;
177 rend_intro_point_t *intro = smartlist_get(desc->intro_nodes, i);
178 /* Obtain extend info with introduction point details. */
179 extend_info_t *info = intro->extend_info;
180 /* Encode introduction point ID. */
181 base32_encode(id_base32, sizeof(id_base32),
182 info->identity_digest, DIGEST_LEN);
183 /* Encode onion key. */
184 if (crypto_pk_write_public_key_to_string(info->onion_key, &onion_key,
185 &onion_key_len) < 0) {
186 log_warn(LD_REND, "Could not write onion key.");
187 goto done;
189 /* Encode intro key. */
190 intro_key = intro->intro_key;
191 if (!intro_key ||
192 crypto_pk_write_public_key_to_string(intro_key, &service_key,
193 &service_key_len) < 0) {
194 log_warn(LD_REND, "Could not write intro key.");
195 tor_free(onion_key);
196 goto done;
198 /* Assemble everything for this introduction point. */
199 address = tor_dup_addr(&info->addr);
200 res = tor_snprintf(unenc + unenc_written, unenc_len - unenc_written,
201 "introduction-point %s\n"
202 "ip-address %s\n"
203 "onion-port %d\n"
204 "onion-key\n%s"
205 "service-key\n%s",
206 id_base32,
207 address,
208 info->port,
209 onion_key,
210 service_key);
211 tor_free(address);
212 tor_free(onion_key);
213 tor_free(service_key);
214 if (res < 0) {
215 log_warn(LD_REND, "Not enough space for writing introduction point "
216 "string.");
217 goto done;
219 /* Update total number of written bytes for unencrypted intro points. */
220 unenc_written += res;
222 /* Finalize unencrypted introduction points. */
223 if (unenc_len < unenc_written + 2) {
224 log_warn(LD_REND, "Not enough space for finalizing introduction point "
225 "string.");
226 goto done;
228 unenc[unenc_written++] = '\n';
229 unenc[unenc_written++] = 0;
230 *encoded = unenc;
231 r = 0;
232 done:
233 if (r<0)
234 tor_free(unenc);
235 return r;
238 /** Encrypt the encoded introduction points in <b>encoded</b> using
239 * authorization type 'basic' with <b>client_cookies</b> and write the
240 * result to a newly allocated string pointed to by <b>encrypted_out</b> of
241 * length <b>encrypted_len_out</b>. Return 0 for success, -1 otherwise. */
242 static int
243 rend_encrypt_v2_intro_points_basic(char **encrypted_out,
244 size_t *encrypted_len_out,
245 const char *encoded,
246 smartlist_t *client_cookies)
248 int r = -1, i, pos, enclen, client_blocks;
249 size_t len, client_entries_len;
250 char *enc = NULL, iv[CIPHER_IV_LEN], *client_part = NULL,
251 session_key[CIPHER_KEY_LEN];
252 smartlist_t *encrypted_session_keys = NULL;
253 crypto_digest_env_t *digest;
254 crypto_cipher_env_t *cipher;
255 tor_assert(encoded);
256 tor_assert(client_cookies && smartlist_len(client_cookies) > 0);
258 /* Generate session key. */
259 if (crypto_rand(session_key, CIPHER_KEY_LEN) < 0) {
260 log_warn(LD_REND, "Unable to generate random session key to encrypt "
261 "introduction point string.");
262 goto done;
265 /* Determine length of encrypted introduction points including session
266 * keys. */
267 client_blocks = 1 + ((smartlist_len(client_cookies) - 1) /
268 REND_BASIC_AUTH_CLIENT_MULTIPLE);
269 client_entries_len = client_blocks * REND_BASIC_AUTH_CLIENT_MULTIPLE *
270 REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
271 len = 2 + client_entries_len + CIPHER_IV_LEN + strlen(encoded);
272 if (client_blocks >= 256) {
273 log_warn(LD_REND, "Too many clients in introduction point string.");
274 goto done;
276 enc = tor_malloc_zero(len);
277 enc[0] = 0x01; /* type of authorization. */
278 enc[1] = (uint8_t)client_blocks;
280 /* Encrypt with random session key. */
281 cipher = crypto_create_init_cipher(session_key, 1);
282 enclen = crypto_cipher_encrypt_with_iv(cipher,
283 enc + 2 + client_entries_len,
284 CIPHER_IV_LEN + strlen(encoded), encoded, strlen(encoded));
285 crypto_free_cipher_env(cipher);
286 if (enclen < 0) {
287 log_warn(LD_REND, "Could not encrypt introduction point string.");
288 goto done;
290 memcpy(iv, enc + 2 + client_entries_len, CIPHER_IV_LEN);
292 /* Encrypt session key for cookies, determine client IDs, and put both
293 * in a smartlist. */
294 encrypted_session_keys = smartlist_create();
295 SMARTLIST_FOREACH_BEGIN(client_cookies, const char *, cookie) {
296 client_part = tor_malloc_zero(REND_BASIC_AUTH_CLIENT_ENTRY_LEN);
297 /* Encrypt session key. */
298 cipher = crypto_create_init_cipher(cookie, 1);
299 if (crypto_cipher_encrypt(cipher, client_part +
300 REND_BASIC_AUTH_CLIENT_ID_LEN,
301 session_key, CIPHER_KEY_LEN) < 0) {
302 log_warn(LD_REND, "Could not encrypt session key for client.");
303 crypto_free_cipher_env(cipher);
304 tor_free(client_part);
305 goto done;
307 crypto_free_cipher_env(cipher);
309 /* Determine client ID. */
310 digest = crypto_new_digest_env();
311 crypto_digest_add_bytes(digest, cookie, REND_DESC_COOKIE_LEN);
312 crypto_digest_add_bytes(digest, iv, CIPHER_IV_LEN);
313 crypto_digest_get_digest(digest, client_part,
314 REND_BASIC_AUTH_CLIENT_ID_LEN);
315 crypto_free_digest_env(digest);
317 /* Put both together. */
318 smartlist_add(encrypted_session_keys, client_part);
319 } SMARTLIST_FOREACH_END(cookie);
321 /* Add some fake client IDs and encrypted session keys. */
322 for (i = (smartlist_len(client_cookies) - 1) %
323 REND_BASIC_AUTH_CLIENT_MULTIPLE;
324 i < REND_BASIC_AUTH_CLIENT_MULTIPLE - 1; i++) {
325 client_part = tor_malloc_zero(REND_BASIC_AUTH_CLIENT_ENTRY_LEN);
326 if (crypto_rand(client_part, REND_BASIC_AUTH_CLIENT_ENTRY_LEN) < 0) {
327 log_warn(LD_REND, "Unable to generate fake client entry.");
328 tor_free(client_part);
329 goto done;
331 smartlist_add(encrypted_session_keys, client_part);
333 /* Sort smartlist and put elements in result in order. */
334 smartlist_sort_digests(encrypted_session_keys);
335 pos = 2;
336 SMARTLIST_FOREACH(encrypted_session_keys, const char *, entry, {
337 memcpy(enc + pos, entry, REND_BASIC_AUTH_CLIENT_ENTRY_LEN);
338 pos += REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
340 *encrypted_out = enc;
341 *encrypted_len_out = len;
342 enc = NULL; /* prevent free. */
343 r = 0;
344 done:
345 tor_free(enc);
346 if (encrypted_session_keys) {
347 SMARTLIST_FOREACH(encrypted_session_keys, char *, d, tor_free(d););
348 smartlist_free(encrypted_session_keys);
350 return r;
353 /** Encrypt the encoded introduction points in <b>encoded</b> using
354 * authorization type 'stealth' with <b>descriptor_cookie</b> of length
355 * REND_DESC_COOKIE_LEN and write the result to a newly allocated string
356 * pointed to by <b>encrypted_out</b> of length <b>encrypted_len_out</b>.
357 * Return 0 for success, -1 otherwise. */
358 static int
359 rend_encrypt_v2_intro_points_stealth(char **encrypted_out,
360 size_t *encrypted_len_out,
361 const char *encoded,
362 const char *descriptor_cookie)
364 int r = -1, enclen;
365 crypto_cipher_env_t *cipher;
366 char *enc;
367 tor_assert(encoded);
368 tor_assert(descriptor_cookie);
370 enc = tor_malloc_zero(1 + CIPHER_IV_LEN + strlen(encoded));
371 enc[0] = 0x02; /* Auth type */
372 cipher = crypto_create_init_cipher(descriptor_cookie, 1);
373 enclen = crypto_cipher_encrypt_with_iv(cipher, enc + 1,
374 CIPHER_IV_LEN+strlen(encoded),
375 encoded, strlen(encoded));
376 crypto_free_cipher_env(cipher);
377 if (enclen < 0) {
378 log_warn(LD_REND, "Could not encrypt introduction point string.");
379 goto done;
381 *encrypted_out = enc;
382 *encrypted_len_out = enclen;
383 enc = NULL; /* prevent free */
384 r = 0;
385 done:
386 tor_free(enc);
387 return r;
390 /** Attempt to parse the given <b>desc_str</b> and return true if this
391 * succeeds, false otherwise. */
392 static int
393 rend_desc_v2_is_parsable(rend_encoded_v2_service_descriptor_t *desc)
395 rend_service_descriptor_t *test_parsed = NULL;
396 char test_desc_id[DIGEST_LEN];
397 char *test_intro_content = NULL;
398 size_t test_intro_size;
399 size_t test_encoded_size;
400 const char *test_next;
401 int res = rend_parse_v2_service_descriptor(&test_parsed, test_desc_id,
402 &test_intro_content,
403 &test_intro_size,
404 &test_encoded_size,
405 &test_next, desc->desc_str);
406 if (test_parsed)
407 rend_service_descriptor_free(test_parsed);
408 tor_free(test_intro_content);
409 return (res >= 0);
412 /** Free the storage held by an encoded v2 service descriptor. */
413 void
414 rend_encoded_v2_service_descriptor_free(
415 rend_encoded_v2_service_descriptor_t *desc)
417 tor_free(desc->desc_str);
418 tor_free(desc);
421 /** Free the storage held by an introduction point info. */
422 void
423 rend_intro_point_free(rend_intro_point_t *intro)
425 if (intro->extend_info)
426 extend_info_free(intro->extend_info);
427 if (intro->intro_key)
428 crypto_free_pk_env(intro->intro_key);
429 tor_free(intro);
432 /** Encode a set of rend_encoded_v2_service_descriptor_t's for <b>desc</b>
433 * at time <b>now</b> using <b>service_key</b>, depending on
434 * <b>auth_type</b> a <b>descriptor_cookie</b> and a list of
435 * <b>client_cookies</b> (which are both <b>NULL</b> if no client
436 * authorization is performed), and <b>period</b> (e.g. 0 for the current
437 * period, 1 for the next period, etc.) and add them to the existing list
438 * <b>descs_out</b>; return the number of seconds that the descriptors will
439 * be found by clients, or -1 if the encoding was not successful. */
441 rend_encode_v2_descriptors(smartlist_t *descs_out,
442 rend_service_descriptor_t *desc, time_t now,
443 uint8_t period, rend_auth_type_t auth_type,
444 crypto_pk_env_t *client_key,
445 smartlist_t *client_cookies)
447 char service_id[DIGEST_LEN];
448 uint32_t time_period;
449 char *ipos_base64 = NULL, *ipos = NULL, *ipos_encrypted = NULL,
450 *descriptor_cookie = NULL;
451 size_t ipos_len = 0, ipos_encrypted_len = 0;
452 int k;
453 uint32_t seconds_valid;
454 crypto_pk_env_t *service_key;
455 if (!desc) {
456 log_warn(LD_BUG, "Could not encode v2 descriptor: No desc given.");
457 return -1;
459 service_key = (auth_type == REND_STEALTH_AUTH) ? client_key : desc->pk;
460 tor_assert(service_key);
461 if (auth_type == REND_STEALTH_AUTH) {
462 descriptor_cookie = smartlist_get(client_cookies, 0);
463 tor_assert(descriptor_cookie);
465 /* Obtain service_id from public key. */
466 crypto_pk_get_digest(service_key, service_id);
467 /* Calculate current time-period. */
468 time_period = get_time_period(now, period, service_id);
469 /* Determine how many seconds the descriptor will be valid. */
470 seconds_valid = period * REND_TIME_PERIOD_V2_DESC_VALIDITY +
471 get_seconds_valid(now, service_id);
472 /* Assemble, possibly encrypt, and encode introduction points. */
473 if (smartlist_len(desc->intro_nodes) > 0) {
474 if (rend_encode_v2_intro_points(&ipos, desc) < 0) {
475 log_warn(LD_REND, "Encoding of introduction points did not succeed.");
476 return -1;
478 switch (auth_type) {
479 case REND_NO_AUTH:
480 ipos_len = strlen(ipos);
481 break;
482 case REND_BASIC_AUTH:
483 if (rend_encrypt_v2_intro_points_basic(&ipos_encrypted,
484 &ipos_encrypted_len, ipos,
485 client_cookies) < 0) {
486 log_warn(LD_REND, "Encrypting of introduction points did not "
487 "succeed.");
488 tor_free(ipos);
489 return -1;
491 tor_free(ipos);
492 ipos = ipos_encrypted;
493 ipos_len = ipos_encrypted_len;
494 break;
495 case REND_STEALTH_AUTH:
496 if (rend_encrypt_v2_intro_points_stealth(&ipos_encrypted,
497 &ipos_encrypted_len, ipos,
498 descriptor_cookie) < 0) {
499 log_warn(LD_REND, "Encrypting of introduction points did not "
500 "succeed.");
501 tor_free(ipos);
502 return -1;
504 tor_free(ipos);
505 ipos = ipos_encrypted;
506 ipos_len = ipos_encrypted_len;
507 break;
508 default:
509 log_warn(LD_REND|LD_BUG, "Unrecognized authorization type %d",
510 (int)auth_type);
511 tor_free(ipos);
512 return -1;
514 /* Base64-encode introduction points. */
515 ipos_base64 = tor_malloc_zero(ipos_len * 2);
516 if (base64_encode(ipos_base64, ipos_len * 2, ipos, ipos_len)<0) {
517 log_warn(LD_REND, "Could not encode introduction point string to "
518 "base64. length=%d", (int)ipos_len);
519 tor_free(ipos_base64);
520 tor_free(ipos);
521 return -1;
523 tor_free(ipos);
525 /* Encode REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS descriptors. */
526 for (k = 0; k < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; k++) {
527 char secret_id_part[DIGEST_LEN];
528 char secret_id_part_base32[REND_SECRET_ID_PART_LEN_BASE32 + 1];
529 char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
530 char *permanent_key = NULL;
531 size_t permanent_key_len;
532 char published[ISO_TIME_LEN+1];
533 int i;
534 char protocol_versions_string[16]; /* max len: "0,1,2,3,4,5,6,7\0" */
535 size_t protocol_versions_written;
536 size_t desc_len;
537 char *desc_str = NULL;
538 int result = 0;
539 size_t written = 0;
540 char desc_digest[DIGEST_LEN];
541 rend_encoded_v2_service_descriptor_t *enc =
542 tor_malloc_zero(sizeof(rend_encoded_v2_service_descriptor_t));
543 /* Calculate secret-id-part = h(time-period + cookie + replica). */
544 get_secret_id_part_bytes(secret_id_part, time_period, descriptor_cookie,
546 base32_encode(secret_id_part_base32, sizeof(secret_id_part_base32),
547 secret_id_part, DIGEST_LEN);
548 /* Calculate descriptor ID. */
549 rend_get_descriptor_id_bytes(enc->desc_id, service_id, secret_id_part);
550 base32_encode(desc_id_base32, sizeof(desc_id_base32),
551 enc->desc_id, DIGEST_LEN);
552 /* PEM-encode the public key */
553 if (crypto_pk_write_public_key_to_string(service_key, &permanent_key,
554 &permanent_key_len) < 0) {
555 log_warn(LD_BUG, "Could not write public key to string.");
556 rend_encoded_v2_service_descriptor_free(enc);
557 goto err;
559 /* Encode timestamp. */
560 format_iso_time(published, desc->timestamp);
561 /* Write protocol-versions bitmask to comma-separated value string. */
562 protocol_versions_written = 0;
563 for (i = 0; i < 8; i++) {
564 if (desc->protocols & 1 << i) {
565 tor_snprintf(protocol_versions_string + protocol_versions_written,
566 16 - protocol_versions_written, "%d,", i);
567 protocol_versions_written += 2;
570 if (protocol_versions_written)
571 protocol_versions_string[protocol_versions_written - 1] = '\0';
572 else
573 protocol_versions_string[0]= '\0';
574 /* Assemble complete descriptor. */
575 desc_len = 2000 + smartlist_len(desc->intro_nodes) * 1000; /* far too long,
576 but okay.*/
577 enc->desc_str = desc_str = tor_malloc_zero(desc_len);
578 result = tor_snprintf(desc_str, desc_len,
579 "rendezvous-service-descriptor %s\n"
580 "version 2\n"
581 "permanent-key\n%s"
582 "secret-id-part %s\n"
583 "publication-time %s\n"
584 "protocol-versions %s\n",
585 desc_id_base32,
586 permanent_key,
587 secret_id_part_base32,
588 published,
589 protocol_versions_string);
590 tor_free(permanent_key);
591 if (result < 0) {
592 log_warn(LD_BUG, "Descriptor ran out of room.");
593 rend_encoded_v2_service_descriptor_free(enc);
594 goto err;
596 written = result;
597 /* Add introduction points. */
598 if (ipos_base64) {
599 result = tor_snprintf(desc_str + written, desc_len - written,
600 "introduction-points\n"
601 "-----BEGIN MESSAGE-----\n%s"
602 "-----END MESSAGE-----\n",
603 ipos_base64);
604 if (result < 0) {
605 log_warn(LD_BUG, "could not write introduction points.");
606 rend_encoded_v2_service_descriptor_free(enc);
607 goto err;
609 written += result;
611 /* Add signature. */
612 strlcpy(desc_str + written, "signature\n", desc_len - written);
613 written += strlen(desc_str + written);
614 if (crypto_digest(desc_digest, desc_str, written) < 0) {
615 log_warn(LD_BUG, "could not create digest.");
616 rend_encoded_v2_service_descriptor_free(enc);
617 goto err;
619 if (router_append_dirobj_signature(desc_str + written,
620 desc_len - written,
621 desc_digest, service_key) < 0) {
622 log_warn(LD_BUG, "Couldn't sign desc.");
623 rend_encoded_v2_service_descriptor_free(enc);
624 goto err;
626 written += strlen(desc_str+written);
627 if (written+2 > desc_len) {
628 log_warn(LD_BUG, "Could not finish desc.");
629 rend_encoded_v2_service_descriptor_free(enc);
630 goto err;
632 desc_str[written++] = '\n';
633 desc_str[written++] = 0;
634 /* Check if we can parse our own descriptor. */
635 if (!rend_desc_v2_is_parsable(enc)) {
636 log_warn(LD_BUG, "Could not parse my own descriptor: %s", desc_str);
637 rend_encoded_v2_service_descriptor_free(enc);
638 goto err;
640 smartlist_add(descs_out, enc);
643 log_info(LD_REND, "Successfully encoded a v2 descriptor and "
644 "confirmed that it is parsable.");
645 goto done;
647 err:
648 SMARTLIST_FOREACH(descs_out, rend_encoded_v2_service_descriptor_t *, d,
649 rend_encoded_v2_service_descriptor_free(d););
650 smartlist_clear(descs_out);
651 seconds_valid = -1;
653 done:
654 tor_free(ipos_base64);
655 return seconds_valid;
658 /** Encode a service descriptor for <b>desc</b>, and sign it with
659 * <b>key</b>. Store the descriptor in *<b>str_out</b>, and set
660 * *<b>len_out</b> to its length.
663 rend_encode_service_descriptor(rend_service_descriptor_t *desc,
664 crypto_pk_env_t *key,
665 char **str_out, size_t *len_out)
667 char *cp;
668 char *end;
669 int i, r;
670 size_t asn1len;
671 size_t buflen =
672 PK_BYTES*2*(smartlist_len(desc->intro_nodes)+2);/*Too long, but ok*/
673 cp = *str_out = tor_malloc(buflen);
674 end = cp + PK_BYTES*2*(smartlist_len(desc->intro_nodes)+1);
675 r = crypto_pk_asn1_encode(desc->pk, cp+2, end-(cp+2));
676 if (r < 0) {
677 tor_free(*str_out);
678 return -1;
680 asn1len = r;
681 set_uint16(cp, htons((uint16_t)asn1len));
682 cp += 2+asn1len;
683 set_uint32(cp, htonl((uint32_t)desc->timestamp));
684 cp += 4;
685 set_uint16(cp, htons((uint16_t)smartlist_len(desc->intro_nodes)));
686 cp += 2;
687 for (i=0; i < smartlist_len(desc->intro_nodes); ++i) {
688 rend_intro_point_t *intro = smartlist_get(desc->intro_nodes, i);
689 char ipoint[HEX_DIGEST_LEN+2];
690 const size_t ipoint_len = HEX_DIGEST_LEN+1;
691 ipoint[0] = '$';
692 base16_encode(ipoint+1, HEX_DIGEST_LEN+1,
693 intro->extend_info->identity_digest,
694 DIGEST_LEN);
695 tor_assert(strlen(ipoint) == ipoint_len);
696 /* Assert that appending ipoint and its NUL won't over overrun the
697 * buffer. */
698 tor_assert(cp + ipoint_len+1 < *str_out + buflen);
699 memcpy(cp, ipoint, ipoint_len+1);
700 cp += ipoint_len+1;
702 note_crypto_pk_op(REND_SERVER);
703 r = crypto_pk_private_sign_digest(key, cp, *str_out, cp-*str_out);
704 if (r<0) {
705 tor_free(*str_out);
706 return -1;
708 cp += r;
709 *len_out = (size_t)(cp-*str_out);
710 return 0;
713 /** Parse a service descriptor at <b>str</b> (<b>len</b> bytes). On
714 * success, return a newly alloced service_descriptor_t. On failure,
715 * return NULL.
717 rend_service_descriptor_t *
718 rend_parse_service_descriptor(const char *str, size_t len)
720 rend_service_descriptor_t *result = NULL;
721 int i, n_intro_points;
722 size_t keylen, asn1len;
723 const char *end, *cp, *eos;
724 rend_intro_point_t *intro;
726 result = tor_malloc_zero(sizeof(rend_service_descriptor_t));
727 cp = str;
728 end = str+len;
729 if (end-cp<2) goto truncated;
730 result->version = 0;
731 if (end-cp < 2) goto truncated;
732 asn1len = ntohs(get_uint16(cp));
733 cp += 2;
734 if ((size_t)(end-cp) < asn1len) goto truncated;
735 result->pk = crypto_pk_asn1_decode(cp, asn1len);
736 if (!result->pk) goto truncated;
737 cp += asn1len;
738 if (end-cp < 4) goto truncated;
739 result->timestamp = (time_t) ntohl(get_uint32(cp));
740 cp += 4;
741 result->protocols = 1<<2; /* always use intro format 2 */
742 if (end-cp < 2) goto truncated;
743 n_intro_points = ntohs(get_uint16(cp));
744 cp += 2;
746 result->intro_nodes = smartlist_create();
747 for (i=0;i<n_intro_points;++i) {
748 if (end-cp < 2) goto truncated;
749 eos = (const char *)memchr(cp,'\0',end-cp);
750 if (!eos) goto truncated;
751 /* Write nickname to extend info, but postpone the lookup whether
752 * we know that router. It's not part of the parsing process. */
753 intro = tor_malloc_zero(sizeof(rend_intro_point_t));
754 intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
755 strlcpy(intro->extend_info->nickname, cp,
756 sizeof(intro->extend_info->nickname));
757 smartlist_add(result->intro_nodes, intro);
758 cp = eos+1;
760 keylen = crypto_pk_keysize(result->pk);
761 tor_assert(end-cp >= 0);
762 if ((size_t)(end-cp) < keylen) goto truncated;
763 if ((size_t)(end-cp) > keylen) {
764 log_warn(LD_PROTOCOL,
765 "Signature is %d bytes too long on service descriptor.",
766 (int)((size_t)(end-cp) - keylen));
767 goto error;
769 note_crypto_pk_op(REND_CLIENT);
770 if (crypto_pk_public_checksig_digest(result->pk,
771 (char*)str,cp-str, /* data */
772 (char*)cp,end-cp /* signature*/
773 )<0) {
774 log_warn(LD_PROTOCOL, "Bad signature on service descriptor.");
775 goto error;
778 return result;
779 truncated:
780 log_warn(LD_PROTOCOL, "Truncated service descriptor.");
781 error:
782 rend_service_descriptor_free(result);
783 return NULL;
786 /** Sets <b>out</b> to the first 10 bytes of the digest of <b>pk</b>,
787 * base32 encoded. NUL-terminates out. (We use this string to
788 * identify services in directory requests and .onion URLs.)
791 rend_get_service_id(crypto_pk_env_t *pk, char *out)
793 char buf[DIGEST_LEN];
794 tor_assert(pk);
795 if (crypto_pk_get_digest(pk, buf) < 0)
796 return -1;
797 base32_encode(out, REND_SERVICE_ID_LEN_BASE32+1, buf, REND_SERVICE_ID_LEN);
798 return 0;
801 /* ==== Rendezvous service descriptor cache. */
803 /** How old do we let hidden service descriptors get before discarding
804 * them as too old? */
805 #define REND_CACHE_MAX_AGE (2*24*60*60)
806 /** How wrong do we assume our clock may be when checking whether hidden
807 * services are too old or too new? */
808 #define REND_CACHE_MAX_SKEW (24*60*60)
810 /** Map from service id (as generated by rend_get_service_id) to
811 * rend_cache_entry_t. */
812 static strmap_t *rend_cache = NULL;
814 /** Map from descriptor id to rend_cache_entry_t; only for hidden service
815 * directories. */
816 static digestmap_t *rend_cache_v2_dir = NULL;
818 /** Initializes the service descriptor cache.
820 void
821 rend_cache_init(void)
823 rend_cache = strmap_new();
824 rend_cache_v2_dir = digestmap_new();
827 /** Helper: free storage held by a single service descriptor cache entry. */
828 static void
829 _rend_cache_entry_free(void *p)
831 rend_cache_entry_t *e = p;
832 rend_service_descriptor_free(e->parsed);
833 tor_free(e->desc);
834 tor_free(e);
837 /** Free all storage held by the service descriptor cache. */
838 void
839 rend_cache_free_all(void)
841 if (rend_cache)
842 strmap_free(rend_cache, _rend_cache_entry_free);
843 if (rend_cache_v2_dir)
844 digestmap_free(rend_cache_v2_dir, _rend_cache_entry_free);
845 rend_cache = NULL;
846 rend_cache_v2_dir = NULL;
849 /** Removes all old entries from the service descriptor cache.
851 void
852 rend_cache_clean(void)
854 strmap_iter_t *iter;
855 const char *key;
856 void *val;
857 rend_cache_entry_t *ent;
858 time_t cutoff;
859 cutoff = time(NULL) - REND_CACHE_MAX_AGE - REND_CACHE_MAX_SKEW;
860 for (iter = strmap_iter_init(rend_cache); !strmap_iter_done(iter); ) {
861 strmap_iter_get(iter, &key, &val);
862 ent = (rend_cache_entry_t*)val;
863 if (ent->parsed->timestamp < cutoff) {
864 iter = strmap_iter_next_rmv(rend_cache, iter);
865 _rend_cache_entry_free(ent);
866 } else {
867 iter = strmap_iter_next(rend_cache, iter);
872 /** Remove all old v2 descriptors and those for which this hidden service
873 * directory is not responsible for any more. */
874 void
875 rend_cache_clean_v2_descs_as_dir(void)
877 digestmap_iter_t *iter;
878 time_t cutoff = time(NULL) - REND_CACHE_MAX_AGE - REND_CACHE_MAX_SKEW;
879 for (iter = digestmap_iter_init(rend_cache_v2_dir);
880 !digestmap_iter_done(iter); ) {
881 const char *key;
882 void *val;
883 rend_cache_entry_t *ent;
884 digestmap_iter_get(iter, &key, &val);
885 ent = val;
886 if (ent->parsed->timestamp < cutoff ||
887 !hid_serv_responsible_for_desc_id(key)) {
888 char key_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
889 base32_encode(key_base32, sizeof(key_base32), key, DIGEST_LEN);
890 log_info(LD_REND, "Removing descriptor with ID '%s' from cache",
891 safe_str(key_base32));
892 iter = digestmap_iter_next_rmv(rend_cache_v2_dir, iter);
893 _rend_cache_entry_free(ent);
894 } else {
895 iter = digestmap_iter_next(rend_cache_v2_dir, iter);
900 /** Determines whether <b>a</b> is in the interval of <b>b</b> (excluded) and
901 * <b>c</b> (included) in a circular digest ring; returns 1 if this is the
902 * case, and 0 otherwise.
905 rend_id_is_in_interval(const char *a, const char *b, const char *c)
907 int a_b, b_c, c_a;
908 tor_assert(a);
909 tor_assert(b);
910 tor_assert(c);
912 /* There are five cases in which a is outside the interval ]b,c]: */
913 a_b = memcmp(a,b,DIGEST_LEN);
914 if (a_b == 0)
915 return 0; /* 1. a == b (b is excluded) */
916 b_c = memcmp(b,c,DIGEST_LEN);
917 if (b_c == 0)
918 return 0; /* 2. b == c (interval is empty) */
919 else if (a_b <= 0 && b_c < 0)
920 return 0; /* 3. a b c */
921 c_a = memcmp(c,a,DIGEST_LEN);
922 if (c_a < 0 && a_b <= 0)
923 return 0; /* 4. c a b */
924 else if (b_c < 0 && c_a < 0)
925 return 0; /* 5. b c a */
927 /* In the other cases (a c b; b a c; c b a), a is inside the interval. */
928 return 1;
931 /** Return true iff <b>query</b> is a syntactically valid service ID (as
932 * generated by rend_get_service_id). */
934 rend_valid_service_id(const char *query)
936 if (strlen(query) != REND_SERVICE_ID_LEN_BASE32)
937 return 0;
939 if (strspn(query, BASE32_CHARS) != REND_SERVICE_ID_LEN_BASE32)
940 return 0;
942 return 1;
945 /** If we have a cached rend_cache_entry_t for the service ID <b>query</b>
946 * with <b>version</b>, set *<b>e</b> to that entry and return 1.
947 * Else return 0. If <b>version</b> is nonnegative, only return an entry
948 * in that descriptor format version. Otherwise (if <b>version</b> is
949 * negative), return the most recent format we have.
952 rend_cache_lookup_entry(const char *query, int version, rend_cache_entry_t **e)
954 char key[REND_SERVICE_ID_LEN_BASE32+2]; /* <version><query>\0 */
955 tor_assert(rend_cache);
956 if (!rend_valid_service_id(query))
957 return -1;
958 *e = NULL;
959 if (version != 0) {
960 tor_snprintf(key, sizeof(key), "2%s", query);
961 *e = strmap_get_lc(rend_cache, key);
963 if (!*e && version != 2) {
964 tor_snprintf(key, sizeof(key), "0%s", query);
965 *e = strmap_get_lc(rend_cache, key);
967 if (!*e)
968 return 0;
969 return 1;
972 /** <b>query</b> is a base-32'ed service id. If it's malformed, return -1.
973 * Else look it up.
974 * - If it is found, point *desc to it, and write its length into
975 * *desc_len, and return 1.
976 * - If it is not found, return 0.
977 * Note: calls to rend_cache_clean or rend_cache_store may invalidate
978 * *desc.
981 rend_cache_lookup_desc(const char *query, int version, const char **desc,
982 size_t *desc_len)
984 rend_cache_entry_t *e;
985 int r;
986 r = rend_cache_lookup_entry(query,version,&e);
987 if (r <= 0) return r;
988 *desc = e->desc;
989 *desc_len = e->len;
990 return 1;
993 /** Lookup the v2 service descriptor with base32-encoded <b>desc_id</b> and
994 * copy the pointer to it to *<b>desc</b>. Return 1 on success, 0 on
995 * well-formed-but-not-found, and -1 on failure.
998 rend_cache_lookup_v2_desc_as_dir(const char *desc_id, const char **desc)
1000 rend_cache_entry_t *e;
1001 char desc_id_digest[DIGEST_LEN];
1002 tor_assert(rend_cache_v2_dir);
1003 if (base32_decode(desc_id_digest, DIGEST_LEN,
1004 desc_id, REND_DESC_ID_V2_LEN_BASE32) < 0) {
1005 log_warn(LD_REND, "Descriptor ID contains illegal characters: %s",
1006 safe_str(desc_id));
1007 return -1;
1009 /* Determine if we are responsible. */
1010 if (hid_serv_responsible_for_desc_id(desc_id_digest) < 0) {
1011 log_info(LD_REND, "Could not answer fetch request for v2 descriptor; "
1012 "either we are no hidden service directory, or we are "
1013 "not responsible for the requested ID.");
1014 return -1;
1016 /* Lookup descriptor and return. */
1017 e = digestmap_get(rend_cache_v2_dir, desc_id_digest);
1018 if (e) {
1019 *desc = e->desc;
1020 return 1;
1022 return 0;
1025 /** Parse *desc, calculate its service id, and store it in the cache.
1026 * If we have a newer v0 descriptor with the same ID, ignore this one.
1027 * If we have an older descriptor with the same ID, replace it.
1028 * If we are acting as client due to the published flag and have any v2
1029 * descriptor with the same ID, reject this one in order to not get
1030 * confused with having both versions for the same service.
1032 * Return -2 if it's malformed or otherwise rejected; return -1 if we
1033 * already have a v2 descriptor here; return 0 if it's the same or older
1034 * than one we've already got; return 1 if it's novel.
1036 * The published flag tells us if we store the descriptor
1037 * in our role as directory (1) or if we cache it as client (0).
1040 rend_cache_store(const char *desc, size_t desc_len, int published)
1042 rend_cache_entry_t *e;
1043 rend_service_descriptor_t *parsed;
1044 char query[REND_SERVICE_ID_LEN_BASE32+1];
1045 char key[REND_SERVICE_ID_LEN_BASE32+2]; /* 0<query>\0 */
1046 time_t now;
1047 or_options_t *options = get_options();
1048 tor_assert(rend_cache);
1049 parsed = rend_parse_service_descriptor(desc,desc_len);
1050 if (!parsed) {
1051 log_warn(LD_PROTOCOL,"Couldn't parse service descriptor.");
1052 return -2;
1054 if (rend_get_service_id(parsed->pk, query)<0) {
1055 log_warn(LD_BUG,"Couldn't compute service ID.");
1056 rend_service_descriptor_free(parsed);
1057 return -2;
1059 now = time(NULL);
1060 if (parsed->timestamp < now-REND_CACHE_MAX_AGE-REND_CACHE_MAX_SKEW) {
1061 log_fn(LOG_PROTOCOL_WARN, LD_REND,
1062 "Service descriptor %s is too old.", safe_str(query));
1063 rend_service_descriptor_free(parsed);
1064 return -2;
1066 if (parsed->timestamp > now+REND_CACHE_MAX_SKEW) {
1067 log_fn(LOG_PROTOCOL_WARN, LD_REND,
1068 "Service descriptor %s is too far in the future.", safe_str(query));
1069 rend_service_descriptor_free(parsed);
1070 return -2;
1072 /* Do we have a v2 descriptor and fetched this descriptor as a client? */
1073 tor_snprintf(key, sizeof(key), "2%s", query);
1074 if (!published && strmap_get_lc(rend_cache, key)) {
1075 log_info(LD_REND, "We already have a v2 descriptor for service %s.",
1076 safe_str(query));
1077 rend_service_descriptor_free(parsed);
1078 return -1;
1080 /* report novel publication to statistics */
1081 if (published && options->HSAuthorityRecordStats) {
1082 hs_usage_note_publish_total(query, now);
1084 tor_snprintf(key, sizeof(key), "0%s", query);
1085 e = (rend_cache_entry_t*) strmap_get_lc(rend_cache, key);
1086 if (e && e->parsed->timestamp > parsed->timestamp) {
1087 log_info(LD_REND,"We already have a newer service descriptor %s with the "
1088 "same ID and version.", safe_str(query));
1089 rend_service_descriptor_free(parsed);
1090 return 0;
1092 if (e && e->len == desc_len && !memcmp(desc,e->desc,desc_len)) {
1093 log_info(LD_REND,"We already have this service descriptor %s.",
1094 safe_str(query));
1095 e->received = time(NULL);
1096 rend_service_descriptor_free(parsed);
1097 return 0;
1099 if (!e) {
1100 e = tor_malloc_zero(sizeof(rend_cache_entry_t));
1101 strmap_set_lc(rend_cache, key, e);
1102 /* report novel publication to statistics */
1103 if (published && options->HSAuthorityRecordStats) {
1104 hs_usage_note_publish_novel(query, now);
1106 } else {
1107 rend_service_descriptor_free(e->parsed);
1108 tor_free(e->desc);
1110 e->received = time(NULL);
1111 e->parsed = parsed;
1112 e->len = desc_len;
1113 e->desc = tor_malloc(desc_len);
1114 memcpy(e->desc, desc, desc_len);
1116 log_debug(LD_REND,"Successfully stored rend desc '%s', len %d.",
1117 safe_str(query), (int)desc_len);
1118 return 1;
1121 /** Parse the v2 service descriptor(s) in <b>desc</b> and store it/them to the
1122 * local rend cache. Don't attempt to decrypt the included list of introduction
1123 * points (as we don't have a descriptor cookie for it).
1125 * If we have a newer descriptor with the same ID, ignore this one.
1126 * If we have an older descriptor with the same ID, replace it.
1127 * Return -2 if we are not acting as hidden service directory;
1128 * return -1 if the descriptor(s) were not parsable; return 0 if all
1129 * descriptors are the same or older than those we've already got;
1130 * return a positive number for the number of novel stored descriptors.
1133 rend_cache_store_v2_desc_as_dir(const char *desc)
1135 rend_service_descriptor_t *parsed;
1136 char desc_id[DIGEST_LEN];
1137 char *intro_content;
1138 size_t intro_size;
1139 size_t encoded_size;
1140 char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
1141 int number_parsed = 0, number_stored = 0;
1142 const char *current_desc = desc;
1143 const char *next_desc;
1144 rend_cache_entry_t *e;
1145 time_t now = time(NULL);
1146 tor_assert(rend_cache_v2_dir);
1147 tor_assert(desc);
1148 if (!hid_serv_acting_as_directory()) {
1149 /* Cannot store descs, because we are (currently) not acting as
1150 * hidden service directory. */
1151 log_info(LD_REND, "Cannot store descs: Not acting as hs dir");
1152 return -2;
1154 while (rend_parse_v2_service_descriptor(&parsed, desc_id, &intro_content,
1155 &intro_size, &encoded_size,
1156 &next_desc, current_desc) >= 0) {
1157 number_parsed++;
1158 /* We don't care about the introduction points. */
1159 tor_free(intro_content);
1160 /* For pretty log statements. */
1161 base32_encode(desc_id_base32, sizeof(desc_id_base32),
1162 desc_id, DIGEST_LEN);
1163 /* Is desc ID in the range that we are (directly or indirectly) responsible
1164 * for? */
1165 if (!hid_serv_responsible_for_desc_id(desc_id)) {
1166 log_info(LD_REND, "Service descriptor with desc ID %s is not in "
1167 "interval that we are responsible for.",
1168 safe_str(desc_id_base32));
1169 goto skip;
1171 /* Is descriptor too old? */
1172 if (parsed->timestamp < now - REND_CACHE_MAX_AGE-REND_CACHE_MAX_SKEW) {
1173 log_info(LD_REND, "Service descriptor with desc ID %s is too old.",
1174 safe_str(desc_id_base32));
1175 goto skip;
1177 /* Is descriptor too far in the future? */
1178 if (parsed->timestamp > now + REND_CACHE_MAX_SKEW) {
1179 log_info(LD_REND, "Service descriptor with desc ID %s is too far in the "
1180 "future.",
1181 safe_str(desc_id_base32));
1182 goto skip;
1184 /* Do we already have a newer descriptor? */
1185 e = digestmap_get(rend_cache_v2_dir, desc_id);
1186 if (e && e->parsed->timestamp > parsed->timestamp) {
1187 log_info(LD_REND, "We already have a newer service descriptor with the "
1188 "same desc ID %s and version.",
1189 safe_str(desc_id_base32));
1190 goto skip;
1192 /* Do we already have this descriptor? */
1193 if (e && !strcmp(desc, e->desc)) {
1194 log_info(LD_REND, "We already have this service descriptor with desc "
1195 "ID %s.", safe_str(desc_id_base32));
1196 e->received = time(NULL);
1197 goto skip;
1199 /* Store received descriptor. */
1200 if (!e) {
1201 e = tor_malloc_zero(sizeof(rend_cache_entry_t));
1202 digestmap_set(rend_cache_v2_dir, desc_id, e);
1203 } else {
1204 rend_service_descriptor_free(e->parsed);
1205 tor_free(e->desc);
1207 e->received = time(NULL);
1208 e->parsed = parsed;
1209 e->desc = tor_strndup(current_desc, encoded_size);
1210 e->len = encoded_size;
1211 log_info(LD_REND, "Successfully stored service descriptor with desc ID "
1212 "'%s' and len %d.",
1213 safe_str(desc_id_base32), (int)encoded_size);
1214 number_stored++;
1215 goto advance;
1216 skip:
1217 rend_service_descriptor_free(parsed);
1218 advance:
1219 /* advance to next descriptor, if available. */
1220 current_desc = next_desc;
1221 /* check if there is a next descriptor. */
1222 if (!current_desc ||
1223 strcmpstart(current_desc, "rendezvous-service-descriptor "))
1224 break;
1226 if (!number_parsed) {
1227 log_info(LD_REND, "Could not parse any descriptor.");
1228 return -1;
1230 log_info(LD_REND, "Parsed %d and added %d descriptor%s.",
1231 number_parsed, number_stored, number_stored != 1 ? "s" : "");
1232 return number_stored;
1235 /** Parse the v2 service descriptor in <b>desc</b>, decrypt the included list
1236 * of introduction points with <b>descriptor_cookie</b> (which may also be
1237 * <b>NULL</b> if decryption is not necessary), and store the descriptor to
1238 * the local cache under its version and service id.
1240 * If we have a newer v2 descriptor with the same ID, ignore this one.
1241 * If we have an older descriptor with the same ID, replace it.
1242 * If we have any v0 descriptor with the same ID, reject this one in order
1243 * to not get confused with having both versions for the same service.
1244 * Return -2 if it's malformed or otherwise rejected; return -1 if we
1245 * already have a v0 descriptor here; return 0 if it's the same or older
1246 * than one we've already got; return 1 if it's novel.
1249 rend_cache_store_v2_desc_as_client(const char *desc,
1250 const rend_data_t *rend_query)
1252 /*XXXX this seems to have a bit of duplicate code with
1253 * rend_cache_store_v2_desc_as_dir(). Fix that. */
1254 /* Though having similar elements, both functions were separated on
1255 * purpose:
1256 * - dirs don't care about encoded/encrypted introduction points, clients
1257 * do.
1258 * - dirs store descriptors in a separate cache by descriptor ID, whereas
1259 * clients store them by service ID; both caches are different data
1260 * structures and have different access methods.
1261 * - dirs store a descriptor only if they are responsible for its ID,
1262 * clients do so in every way (because they have requested it before).
1263 * - dirs can process multiple concatenated descriptors which is required
1264 * for replication, whereas clients only accept a single descriptor.
1265 * Thus, combining both methods would result in a lot of if statements
1266 * which probably would not improve, but worsen code readability. -KL */
1267 rend_service_descriptor_t *parsed = NULL;
1268 char desc_id[DIGEST_LEN];
1269 char *intro_content = NULL;
1270 size_t intro_size;
1271 size_t encoded_size;
1272 const char *next_desc;
1273 time_t now = time(NULL);
1274 char key[REND_SERVICE_ID_LEN_BASE32+2];
1275 char service_id[REND_SERVICE_ID_LEN_BASE32+1];
1276 rend_cache_entry_t *e;
1277 int retval;
1278 tor_assert(rend_cache);
1279 tor_assert(desc);
1280 /* Parse the descriptor. */
1281 if (rend_parse_v2_service_descriptor(&parsed, desc_id, &intro_content,
1282 &intro_size, &encoded_size,
1283 &next_desc, desc) < 0) {
1284 log_warn(LD_REND, "Could not parse descriptor.");
1285 retval = -2;
1286 goto err;
1288 /* Compute service ID from public key. */
1289 if (rend_get_service_id(parsed->pk, service_id)<0) {
1290 log_warn(LD_REND, "Couldn't compute service ID.");
1291 retval = -2;
1292 goto err;
1294 /* Decode/decrypt introduction points. */
1295 if (intro_content) {
1296 if (rend_query->auth_type != REND_NO_AUTH &&
1297 rend_query->descriptor_cookie) {
1298 char *ipos_decrypted = NULL;
1299 size_t ipos_decrypted_size;
1300 if (rend_decrypt_introduction_points(&ipos_decrypted,
1301 &ipos_decrypted_size,
1302 rend_query->descriptor_cookie,
1303 intro_content,
1304 intro_size) < 0) {
1305 log_warn(LD_REND, "Failed to decrypt introduction points. We are "
1306 "probably unable to parse the encoded introduction points.");
1307 } else {
1308 /* Replace encrypted with decrypted introduction points. */
1309 log_info(LD_REND, "Successfully decrypted introduction points.");
1310 tor_free(intro_content);
1311 intro_content = ipos_decrypted;
1312 intro_size = ipos_decrypted_size;
1315 if (rend_parse_introduction_points(parsed, intro_content,
1316 intro_size) <= 0) {
1317 log_warn(LD_REND, "Failed to parse introduction points. Either the "
1318 "service has published a corrupt descriptor or you have "
1319 "provided invalid authorization data.");
1320 retval = -2;
1321 goto err;
1323 } else {
1324 log_info(LD_REND, "Descriptor does not contain any introduction points.");
1325 parsed->intro_nodes = smartlist_create();
1327 /* We don't need the encoded/encrypted introduction points any longer. */
1328 tor_free(intro_content);
1329 /* Is descriptor too old? */
1330 if (parsed->timestamp < now - REND_CACHE_MAX_AGE-REND_CACHE_MAX_SKEW) {
1331 log_warn(LD_REND, "Service descriptor with service ID %s is too old.",
1332 safe_str(service_id));
1333 retval = -2;
1334 goto err;
1336 /* Is descriptor too far in the future? */
1337 if (parsed->timestamp > now + REND_CACHE_MAX_SKEW) {
1338 log_warn(LD_REND, "Service descriptor with service ID %s is too far in "
1339 "the future.", safe_str(service_id));
1340 retval = -2;
1341 goto err;
1343 /* Do we have a v0 descriptor? */
1344 tor_snprintf(key, sizeof(key), "0%s", service_id);
1345 if (strmap_get_lc(rend_cache, key)) {
1346 log_info(LD_REND, "We already have a v0 descriptor for service ID %s.",
1347 safe_str(service_id));
1348 retval = -1;
1349 goto err;
1351 /* Do we already have a newer descriptor? */
1352 tor_snprintf(key, sizeof(key), "2%s", service_id);
1353 e = (rend_cache_entry_t*) strmap_get_lc(rend_cache, key);
1354 if (e && e->parsed->timestamp > parsed->timestamp) {
1355 log_info(LD_REND, "We already have a newer service descriptor for "
1356 "service ID %s with the same desc ID and version.",
1357 safe_str(service_id));
1358 retval = 0;
1359 goto err;
1361 /* Do we already have this descriptor? */
1362 if (e && !strcmp(desc, e->desc)) {
1363 log_info(LD_REND,"We already have this service descriptor %s.",
1364 safe_str(service_id));
1365 e->received = time(NULL);
1366 retval = 0;
1367 goto err;
1369 if (!e) {
1370 e = tor_malloc_zero(sizeof(rend_cache_entry_t));
1371 strmap_set_lc(rend_cache, key, e);
1372 } else {
1373 rend_service_descriptor_free(e->parsed);
1374 tor_free(e->desc);
1376 e->received = time(NULL);
1377 e->parsed = parsed;
1378 e->desc = tor_malloc_zero(encoded_size + 1);
1379 strlcpy(e->desc, desc, encoded_size + 1);
1380 e->len = encoded_size;
1381 log_debug(LD_REND,"Successfully stored rend desc '%s', len %d.",
1382 safe_str(service_id), (int)encoded_size);
1383 return 1;
1385 err:
1386 if (parsed)
1387 rend_service_descriptor_free(parsed);
1388 tor_free(intro_content);
1389 return retval;
1392 /** Called when we get a rendezvous-related relay cell on circuit
1393 * <b>circ</b>. Dispatch on rendezvous relay command. */
1394 void
1395 rend_process_relay_cell(circuit_t *circ, const crypt_path_t *layer_hint,
1396 int command, size_t length,
1397 const char *payload)
1399 or_circuit_t *or_circ = NULL;
1400 origin_circuit_t *origin_circ = NULL;
1401 int r = -2;
1402 if (CIRCUIT_IS_ORIGIN(circ)) {
1403 origin_circ = TO_ORIGIN_CIRCUIT(circ);
1404 if (!layer_hint || layer_hint != origin_circ->cpath->prev) {
1405 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1406 "Relay cell (rend purpose %d) from wrong hop on origin circ",
1407 command);
1408 origin_circ = NULL;
1410 } else {
1411 or_circ = TO_OR_CIRCUIT(circ);
1414 switch (command) {
1415 case RELAY_COMMAND_ESTABLISH_INTRO:
1416 if (or_circ)
1417 r = rend_mid_establish_intro(or_circ,payload,length);
1418 break;
1419 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
1420 if (or_circ)
1421 r = rend_mid_establish_rendezvous(or_circ,payload,length);
1422 break;
1423 case RELAY_COMMAND_INTRODUCE1:
1424 if (or_circ)
1425 r = rend_mid_introduce(or_circ,payload,length);
1426 break;
1427 case RELAY_COMMAND_INTRODUCE2:
1428 if (origin_circ)
1429 r = rend_service_introduce(origin_circ,payload,length);
1430 break;
1431 case RELAY_COMMAND_INTRODUCE_ACK:
1432 if (origin_circ)
1433 r = rend_client_introduction_acked(origin_circ,payload,length);
1434 break;
1435 case RELAY_COMMAND_RENDEZVOUS1:
1436 if (or_circ)
1437 r = rend_mid_rendezvous(or_circ,payload,length);
1438 break;
1439 case RELAY_COMMAND_RENDEZVOUS2:
1440 if (origin_circ)
1441 r = rend_client_receive_rendezvous(origin_circ,payload,length);
1442 break;
1443 case RELAY_COMMAND_INTRO_ESTABLISHED:
1444 if (origin_circ)
1445 r = rend_service_intro_established(origin_circ,payload,length);
1446 break;
1447 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
1448 if (origin_circ)
1449 r = rend_client_rendezvous_acked(origin_circ,payload,length);
1450 break;
1451 default:
1452 tor_fragile_assert();
1455 if (r == -2)
1456 log_info(LD_PROTOCOL, "Dropping cell (type %d) for wrong circuit type.",
1457 command);
1460 /** Return the number of entries in our rendezvous descriptor cache. */
1462 rend_cache_size(void)
1464 return strmap_size(rend_cache);
1467 /** Allocate and return a new rend_data_t with the same
1468 * contents as <b>query</b>. */
1469 rend_data_t *
1470 rend_data_dup(const rend_data_t *data)
1472 tor_assert(data);
1473 return tor_memdup(data, sizeof(rend_data_t));