Simplify the math to round up to the next multiple of some value.
[tor/rransom.git] / src / or / rendcommon.c
blobdf7195e3ea8c64ccf8275991717351469105b70a
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 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 = auth_type == REND_STEALTH_AUTH ?
455 client_key : desc->pk;
456 tor_assert(service_key);
457 if (auth_type == REND_STEALTH_AUTH) {
458 descriptor_cookie = smartlist_get(client_cookies, 0);
459 tor_assert(descriptor_cookie);
461 if (!desc) {
462 log_warn(LD_REND, "Could not encode v2 descriptor: No desc given.");
463 return -1;
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 /** Parse a service descriptor at <b>str</b> (<b>len</b> bytes). On
659 * success, return a newly alloced service_descriptor_t. On failure,
660 * return NULL.
662 rend_service_descriptor_t *
663 rend_parse_service_descriptor(const char *str, size_t len)
665 rend_service_descriptor_t *result = NULL;
666 int i, n_intro_points;
667 size_t keylen, asn1len;
668 const char *end, *cp, *eos;
669 rend_intro_point_t *intro;
671 result = tor_malloc_zero(sizeof(rend_service_descriptor_t));
672 cp = str;
673 end = str+len;
674 if (end-cp<2) goto truncated;
675 result->version = 0;
676 if (end-cp < 2) goto truncated;
677 asn1len = ntohs(get_uint16(cp));
678 cp += 2;
679 if ((size_t)(end-cp) < asn1len) goto truncated;
680 result->pk = crypto_pk_asn1_decode(cp, asn1len);
681 if (!result->pk) goto truncated;
682 cp += asn1len;
683 if (end-cp < 4) goto truncated;
684 result->timestamp = (time_t) ntohl(get_uint32(cp));
685 cp += 4;
686 result->protocols = 1<<2; /* always use intro format 2 */
687 if (end-cp < 2) goto truncated;
688 n_intro_points = ntohs(get_uint16(cp));
689 cp += 2;
691 result->intro_nodes = smartlist_create();
692 for (i=0;i<n_intro_points;++i) {
693 if (end-cp < 2) goto truncated;
694 eos = (const char *)memchr(cp,'\0',end-cp);
695 if (!eos) goto truncated;
696 /* Write nickname to extend info, but postpone the lookup whether
697 * we know that router. It's not part of the parsing process. */
698 intro = tor_malloc_zero(sizeof(rend_intro_point_t));
699 intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
700 strlcpy(intro->extend_info->nickname, cp,
701 sizeof(intro->extend_info->nickname));
702 smartlist_add(result->intro_nodes, intro);
703 cp = eos+1;
705 keylen = crypto_pk_keysize(result->pk);
706 tor_assert(end-cp >= 0);
707 if ((size_t)(end-cp) < keylen) goto truncated;
708 if ((size_t)(end-cp) > keylen) {
709 log_warn(LD_PROTOCOL,
710 "Signature is %d bytes too long on service descriptor.",
711 (int)((size_t)(end-cp) - keylen));
712 goto error;
714 note_crypto_pk_op(REND_CLIENT);
715 if (crypto_pk_public_checksig_digest(result->pk,
716 (char*)str,cp-str, /* data */
717 (char*)cp,end-cp /* signature*/
718 )<0) {
719 log_warn(LD_PROTOCOL, "Bad signature on service descriptor.");
720 goto error;
723 return result;
724 truncated:
725 log_warn(LD_PROTOCOL, "Truncated service descriptor.");
726 error:
727 rend_service_descriptor_free(result);
728 return NULL;
731 /** Sets <b>out</b> to the first 10 bytes of the digest of <b>pk</b>,
732 * base32 encoded. NUL-terminates out. (We use this string to
733 * identify services in directory requests and .onion URLs.)
736 rend_get_service_id(crypto_pk_env_t *pk, char *out)
738 char buf[DIGEST_LEN];
739 tor_assert(pk);
740 if (crypto_pk_get_digest(pk, buf) < 0)
741 return -1;
742 base32_encode(out, REND_SERVICE_ID_LEN_BASE32+1, buf, REND_SERVICE_ID_LEN);
743 return 0;
746 /* ==== Rendezvous service descriptor cache. */
748 /** How old do we let hidden service descriptors get before discarding
749 * them as too old? */
750 #define REND_CACHE_MAX_AGE (2*24*60*60)
751 /** How wrong do we assume our clock may be when checking whether hidden
752 * services are too old or too new? */
753 #define REND_CACHE_MAX_SKEW (24*60*60)
755 /** Map from service id (as generated by rend_get_service_id) to
756 * rend_cache_entry_t. */
757 static strmap_t *rend_cache = NULL;
759 /** Map from descriptor id to rend_cache_entry_t; only for hidden service
760 * directories. */
761 static digestmap_t *rend_cache_v2_dir = NULL;
763 /** Initializes the service descriptor cache.
765 void
766 rend_cache_init(void)
768 rend_cache = strmap_new();
769 rend_cache_v2_dir = digestmap_new();
772 /** Helper: free storage held by a single service descriptor cache entry. */
773 static void
774 _rend_cache_entry_free(void *p)
776 rend_cache_entry_t *e = p;
777 rend_service_descriptor_free(e->parsed);
778 tor_free(e->desc);
779 tor_free(e);
782 /** Free all storage held by the service descriptor cache. */
783 void
784 rend_cache_free_all(void)
786 if (rend_cache)
787 strmap_free(rend_cache, _rend_cache_entry_free);
788 if (rend_cache_v2_dir)
789 digestmap_free(rend_cache_v2_dir, _rend_cache_entry_free);
790 rend_cache = NULL;
791 rend_cache_v2_dir = NULL;
794 /** Removes all old entries from the service descriptor cache.
796 void
797 rend_cache_clean(void)
799 strmap_iter_t *iter;
800 const char *key;
801 void *val;
802 rend_cache_entry_t *ent;
803 time_t cutoff;
804 cutoff = time(NULL) - REND_CACHE_MAX_AGE - REND_CACHE_MAX_SKEW;
805 for (iter = strmap_iter_init(rend_cache); !strmap_iter_done(iter); ) {
806 strmap_iter_get(iter, &key, &val);
807 ent = (rend_cache_entry_t*)val;
808 if (ent->parsed->timestamp < cutoff) {
809 iter = strmap_iter_next_rmv(rend_cache, iter);
810 _rend_cache_entry_free(ent);
811 } else {
812 iter = strmap_iter_next(rend_cache, iter);
817 /** Remove all old v2 descriptors and those for which this hidden service
818 * directory is not responsible for any more. */
819 void
820 rend_cache_clean_v2_descs_as_dir(void)
822 digestmap_iter_t *iter;
823 time_t cutoff = time(NULL) - REND_CACHE_MAX_AGE - REND_CACHE_MAX_SKEW;
824 for (iter = digestmap_iter_init(rend_cache_v2_dir);
825 !digestmap_iter_done(iter); ) {
826 const char *key;
827 void *val;
828 rend_cache_entry_t *ent;
829 digestmap_iter_get(iter, &key, &val);
830 ent = val;
831 if (ent->parsed->timestamp < cutoff ||
832 !hid_serv_responsible_for_desc_id(key)) {
833 char key_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
834 base32_encode(key_base32, sizeof(key_base32), key, DIGEST_LEN);
835 log_info(LD_REND, "Removing descriptor with ID '%s' from cache",
836 safe_str(key_base32));
837 iter = digestmap_iter_next_rmv(rend_cache_v2_dir, iter);
838 _rend_cache_entry_free(ent);
839 } else {
840 iter = digestmap_iter_next(rend_cache_v2_dir, iter);
845 /** Determines whether <b>a</b> is in the interval of <b>b</b> (excluded) and
846 * <b>c</b> (included) in a circular digest ring; returns 1 if this is the
847 * case, and 0 otherwise.
850 rend_id_is_in_interval(const char *a, const char *b, const char *c)
852 int a_b, b_c, c_a;
853 tor_assert(a);
854 tor_assert(b);
855 tor_assert(c);
857 /* There are five cases in which a is outside the interval ]b,c]: */
858 a_b = memcmp(a,b,DIGEST_LEN);
859 if (a_b == 0)
860 return 0; /* 1. a == b (b is excluded) */
861 b_c = memcmp(b,c,DIGEST_LEN);
862 if (b_c == 0)
863 return 0; /* 2. b == c (interval is empty) */
864 else if (a_b <= 0 && b_c < 0)
865 return 0; /* 3. a b c */
866 c_a = memcmp(c,a,DIGEST_LEN);
867 if (c_a < 0 && a_b <= 0)
868 return 0; /* 4. c a b */
869 else if (b_c < 0 && c_a < 0)
870 return 0; /* 5. b c a */
872 /* In the other cases (a c b; b a c; c b a), a is inside the interval. */
873 return 1;
876 /** Return true iff <b>query</b> is a syntactically valid service ID (as
877 * generated by rend_get_service_id). */
879 rend_valid_service_id(const char *query)
881 if (strlen(query) != REND_SERVICE_ID_LEN_BASE32)
882 return 0;
884 if (strspn(query, BASE32_CHARS) != REND_SERVICE_ID_LEN_BASE32)
885 return 0;
887 return 1;
890 /** If we have a cached rend_cache_entry_t for the service ID <b>query</b>
891 * with <b>version</b>, set *<b>e</b> to that entry and return 1.
892 * Else return 0. If <b>version</b> is nonnegative, only return an entry
893 * in that descriptor format version. Otherwise (if <b>version</b> is
894 * negative), return the most recent format we have.
897 rend_cache_lookup_entry(const char *query, int version, rend_cache_entry_t **e)
899 char key[REND_SERVICE_ID_LEN_BASE32+2]; /* <version><query>\0 */
900 tor_assert(rend_cache);
901 if (!rend_valid_service_id(query))
902 return -1;
903 *e = NULL;
904 if (version != 0) {
905 tor_snprintf(key, sizeof(key), "2%s", query);
906 *e = strmap_get_lc(rend_cache, key);
908 if (!*e && version != 2) {
909 tor_snprintf(key, sizeof(key), "0%s", query);
910 *e = strmap_get_lc(rend_cache, key);
912 if (!*e)
913 return 0;
914 tor_assert((*e)->parsed && (*e)->parsed->intro_nodes);
915 /* XXX022 hack for now, to return "not found" if there are no intro
916 * points remaining. See bug 997. */
917 if (smartlist_len((*e)->parsed->intro_nodes) == 0)
918 return 0;
919 return 1;
922 /** <b>query</b> is a base-32'ed service id. If it's malformed, return -1.
923 * Else look it up.
924 * - If it is found, point *desc to it, and write its length into
925 * *desc_len, and return 1.
926 * - If it is not found, return 0.
927 * Note: calls to rend_cache_clean or rend_cache_store may invalidate
928 * *desc.
931 rend_cache_lookup_desc(const char *query, int version, const char **desc,
932 size_t *desc_len)
934 rend_cache_entry_t *e;
935 int r;
936 r = rend_cache_lookup_entry(query,version,&e);
937 if (r <= 0) return r;
938 *desc = e->desc;
939 *desc_len = e->len;
940 return 1;
943 /** Lookup the v2 service descriptor with base32-encoded <b>desc_id</b> and
944 * copy the pointer to it to *<b>desc</b>. Return 1 on success, 0 on
945 * well-formed-but-not-found, and -1 on failure.
948 rend_cache_lookup_v2_desc_as_dir(const char *desc_id, const char **desc)
950 rend_cache_entry_t *e;
951 char desc_id_digest[DIGEST_LEN];
952 tor_assert(rend_cache_v2_dir);
953 if (base32_decode(desc_id_digest, DIGEST_LEN,
954 desc_id, REND_DESC_ID_V2_LEN_BASE32) < 0) {
955 log_warn(LD_REND, "Descriptor ID contains illegal characters: %s",
956 safe_str(desc_id));
957 return -1;
959 /* Determine if we are responsible. */
960 if (hid_serv_responsible_for_desc_id(desc_id_digest) < 0) {
961 log_info(LD_REND, "Could not answer fetch request for v2 descriptor; "
962 "either we are no hidden service directory, or we are "
963 "not responsible for the requested ID.");
964 return -1;
966 /* Lookup descriptor and return. */
967 e = digestmap_get(rend_cache_v2_dir, desc_id_digest);
968 if (e) {
969 *desc = e->desc;
970 return 1;
972 return 0;
975 /** Parse *desc, calculate its service id, and store it in the cache.
976 * If we have a newer v0 descriptor with the same ID, ignore this one.
977 * If we have an older descriptor with the same ID, replace it.
978 * If we are acting as client due to the published flag and have any v2
979 * descriptor with the same ID, reject this one in order to not get
980 * confused with having both versions for the same service.
982 * Return -2 if it's malformed or otherwise rejected; return -1 if we
983 * already have a v2 descriptor here; return 0 if it's the same or older
984 * than one we've already got; return 1 if it's novel.
986 * The published flag tells us if we store the descriptor
987 * in our role as directory (1) or if we cache it as client (0).
990 rend_cache_store(const char *desc, size_t desc_len, int published)
992 rend_cache_entry_t *e;
993 rend_service_descriptor_t *parsed;
994 char query[REND_SERVICE_ID_LEN_BASE32+1];
995 char key[REND_SERVICE_ID_LEN_BASE32+2]; /* 0<query>\0 */
996 time_t now;
997 or_options_t *options = get_options();
998 tor_assert(rend_cache);
999 parsed = rend_parse_service_descriptor(desc,desc_len);
1000 if (!parsed) {
1001 log_warn(LD_PROTOCOL,"Couldn't parse service descriptor.");
1002 return -2;
1004 if (rend_get_service_id(parsed->pk, query)<0) {
1005 log_warn(LD_BUG,"Couldn't compute service ID.");
1006 rend_service_descriptor_free(parsed);
1007 return -2;
1009 now = time(NULL);
1010 if (parsed->timestamp < now-REND_CACHE_MAX_AGE-REND_CACHE_MAX_SKEW) {
1011 log_fn(LOG_PROTOCOL_WARN, LD_REND,
1012 "Service descriptor %s is too old.", safe_str(query));
1013 rend_service_descriptor_free(parsed);
1014 return -2;
1016 if (parsed->timestamp > now+REND_CACHE_MAX_SKEW) {
1017 log_fn(LOG_PROTOCOL_WARN, LD_REND,
1018 "Service descriptor %s is too far in the future.", safe_str(query));
1019 rend_service_descriptor_free(parsed);
1020 return -2;
1022 /* Do we have a v2 descriptor and fetched this descriptor as a client? */
1023 tor_snprintf(key, sizeof(key), "2%s", query);
1024 if (!published && strmap_get_lc(rend_cache, key)) {
1025 log_info(LD_REND, "We already have a v2 descriptor for service %s.",
1026 safe_str(query));
1027 rend_service_descriptor_free(parsed);
1028 return -1;
1030 /* report novel publication to statistics */
1031 if (published && options->HSAuthorityRecordStats) {
1032 hs_usage_note_publish_total(query, now);
1034 tor_snprintf(key, sizeof(key), "0%s", query);
1035 e = (rend_cache_entry_t*) strmap_get_lc(rend_cache, key);
1036 if (e && e->parsed->timestamp > parsed->timestamp) {
1037 log_info(LD_REND,"We already have a newer service descriptor %s with the "
1038 "same ID and version.", safe_str(query));
1039 rend_service_descriptor_free(parsed);
1040 return 0;
1042 if (e && e->len == desc_len && !memcmp(desc,e->desc,desc_len)) {
1043 log_info(LD_REND,"We already have this service descriptor %s.",
1044 safe_str(query));
1045 e->received = time(NULL);
1046 rend_service_descriptor_free(parsed);
1047 return 0;
1049 if (!e) {
1050 e = tor_malloc_zero(sizeof(rend_cache_entry_t));
1051 strmap_set_lc(rend_cache, key, e);
1052 /* report novel publication to statistics */
1053 if (published && options->HSAuthorityRecordStats) {
1054 hs_usage_note_publish_novel(query, now);
1056 } else {
1057 rend_service_descriptor_free(e->parsed);
1058 tor_free(e->desc);
1060 e->received = time(NULL);
1061 e->parsed = parsed;
1062 e->len = desc_len;
1063 e->desc = tor_malloc(desc_len);
1064 memcpy(e->desc, desc, desc_len);
1066 log_debug(LD_REND,"Successfully stored rend desc '%s', len %d.",
1067 safe_str(query), (int)desc_len);
1068 return 1;
1071 /** Parse the v2 service descriptor(s) in <b>desc</b> and store it/them to the
1072 * local rend cache. Don't attempt to decrypt the included list of introduction
1073 * points (as we don't have a descriptor cookie for it).
1075 * If we have a newer descriptor with the same ID, ignore this one.
1076 * If we have an older descriptor with the same ID, replace it.
1077 * Return -2 if we are not acting as hidden service directory;
1078 * return -1 if the descriptor(s) were not parsable; return 0 if all
1079 * descriptors are the same or older than those we've already got;
1080 * return a positive number for the number of novel stored descriptors.
1083 rend_cache_store_v2_desc_as_dir(const char *desc)
1085 rend_service_descriptor_t *parsed;
1086 char desc_id[DIGEST_LEN];
1087 char *intro_content;
1088 size_t intro_size;
1089 size_t encoded_size;
1090 char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
1091 int number_parsed = 0, number_stored = 0;
1092 const char *current_desc = desc;
1093 const char *next_desc;
1094 rend_cache_entry_t *e;
1095 time_t now = time(NULL);
1096 tor_assert(rend_cache_v2_dir);
1097 tor_assert(desc);
1098 if (!hid_serv_acting_as_directory()) {
1099 /* Cannot store descs, because we are (currently) not acting as
1100 * hidden service directory. */
1101 log_info(LD_REND, "Cannot store descs: Not acting as hs dir");
1102 return -2;
1104 while (rend_parse_v2_service_descriptor(&parsed, desc_id, &intro_content,
1105 &intro_size, &encoded_size,
1106 &next_desc, current_desc) >= 0) {
1107 number_parsed++;
1108 /* We don't care about the introduction points. */
1109 tor_free(intro_content);
1110 /* For pretty log statements. */
1111 base32_encode(desc_id_base32, sizeof(desc_id_base32),
1112 desc_id, DIGEST_LEN);
1113 /* Is desc ID in the range that we are (directly or indirectly) responsible
1114 * for? */
1115 if (!hid_serv_responsible_for_desc_id(desc_id)) {
1116 log_info(LD_REND, "Service descriptor with desc ID %s is not in "
1117 "interval that we are responsible for.",
1118 safe_str(desc_id_base32));
1119 goto skip;
1121 /* Is descriptor too old? */
1122 if (parsed->timestamp < now - REND_CACHE_MAX_AGE-REND_CACHE_MAX_SKEW) {
1123 log_info(LD_REND, "Service descriptor with desc ID %s is too old.",
1124 safe_str(desc_id_base32));
1125 goto skip;
1127 /* Is descriptor too far in the future? */
1128 if (parsed->timestamp > now + REND_CACHE_MAX_SKEW) {
1129 log_info(LD_REND, "Service descriptor with desc ID %s is too far in the "
1130 "future.",
1131 safe_str(desc_id_base32));
1132 goto skip;
1134 /* Do we already have a newer descriptor? */
1135 e = digestmap_get(rend_cache_v2_dir, desc_id);
1136 if (e && e->parsed->timestamp > parsed->timestamp) {
1137 log_info(LD_REND, "We already have a newer service descriptor with the "
1138 "same desc ID %s and version.",
1139 safe_str(desc_id_base32));
1140 goto skip;
1142 /* Do we already have this descriptor? */
1143 if (e && !strcmp(desc, e->desc)) {
1144 log_info(LD_REND, "We already have this service descriptor with desc "
1145 "ID %s.", safe_str(desc_id_base32));
1146 e->received = time(NULL);
1147 goto skip;
1149 /* Store received descriptor. */
1150 if (!e) {
1151 e = tor_malloc_zero(sizeof(rend_cache_entry_t));
1152 digestmap_set(rend_cache_v2_dir, desc_id, e);
1153 } else {
1154 rend_service_descriptor_free(e->parsed);
1155 tor_free(e->desc);
1157 e->received = time(NULL);
1158 e->parsed = parsed;
1159 e->desc = tor_strndup(current_desc, encoded_size);
1160 e->len = encoded_size;
1161 log_info(LD_REND, "Successfully stored service descriptor with desc ID "
1162 "'%s' and len %d.",
1163 safe_str(desc_id_base32), (int)encoded_size);
1164 number_stored++;
1165 goto advance;
1166 skip:
1167 rend_service_descriptor_free(parsed);
1168 advance:
1169 /* advance to next descriptor, if available. */
1170 current_desc = next_desc;
1171 /* check if there is a next descriptor. */
1172 if (!current_desc ||
1173 strcmpstart(current_desc, "rendezvous-service-descriptor "))
1174 break;
1176 if (!number_parsed) {
1177 log_info(LD_REND, "Could not parse any descriptor.");
1178 return -1;
1180 log_info(LD_REND, "Parsed %d and added %d descriptor%s.",
1181 number_parsed, number_stored, number_stored != 1 ? "s" : "");
1182 return number_stored;
1185 /** Parse the v2 service descriptor in <b>desc</b>, decrypt the included list
1186 * of introduction points with <b>descriptor_cookie</b> (which may also be
1187 * <b>NULL</b> if decryption is not necessary), and store the descriptor to
1188 * the local cache under its version and service id.
1190 * If we have a newer v2 descriptor with the same ID, ignore this one.
1191 * If we have an older descriptor with the same ID, replace it.
1192 * If we have any v0 descriptor with the same ID, reject this one in order
1193 * to not get confused with having both versions for the same service.
1194 * Return -2 if it's malformed or otherwise rejected; return -1 if we
1195 * already have a v0 descriptor here; return 0 if it's the same or older
1196 * than one we've already got; return 1 if it's novel.
1199 rend_cache_store_v2_desc_as_client(const char *desc,
1200 const rend_data_t *rend_query)
1202 /*XXXX this seems to have a bit of duplicate code with
1203 * rend_cache_store_v2_desc_as_dir(). Fix that. */
1204 /* Though having similar elements, both functions were separated on
1205 * purpose:
1206 * - dirs don't care about encoded/encrypted introduction points, clients
1207 * do.
1208 * - dirs store descriptors in a separate cache by descriptor ID, whereas
1209 * clients store them by service ID; both caches are different data
1210 * structures and have different access methods.
1211 * - dirs store a descriptor only if they are responsible for its ID,
1212 * clients do so in every way (because they have requested it before).
1213 * - dirs can process multiple concatenated descriptors which is required
1214 * for replication, whereas clients only accept a single descriptor.
1215 * Thus, combining both methods would result in a lot of if statements
1216 * which probably would not improve, but worsen code readability. -KL */
1217 rend_service_descriptor_t *parsed = NULL;
1218 char desc_id[DIGEST_LEN];
1219 char *intro_content = NULL;
1220 size_t intro_size;
1221 size_t encoded_size;
1222 const char *next_desc;
1223 time_t now = time(NULL);
1224 char key[REND_SERVICE_ID_LEN_BASE32+2];
1225 char service_id[REND_SERVICE_ID_LEN_BASE32+1];
1226 rend_cache_entry_t *e;
1227 int retval;
1228 tor_assert(rend_cache);
1229 tor_assert(desc);
1230 /* Parse the descriptor. */
1231 if (rend_parse_v2_service_descriptor(&parsed, desc_id, &intro_content,
1232 &intro_size, &encoded_size,
1233 &next_desc, desc) < 0) {
1234 log_warn(LD_REND, "Could not parse descriptor.");
1235 retval = -2;
1236 goto err;
1238 /* Compute service ID from public key. */
1239 if (rend_get_service_id(parsed->pk, service_id)<0) {
1240 log_warn(LD_REND, "Couldn't compute service ID.");
1241 retval = -2;
1242 goto err;
1244 /* Decode/decrypt introduction points. */
1245 if (intro_content) {
1246 if (rend_query->auth_type != REND_NO_AUTH &&
1247 rend_query->descriptor_cookie) {
1248 char *ipos_decrypted = NULL;
1249 size_t ipos_decrypted_size;
1250 if (rend_decrypt_introduction_points(&ipos_decrypted,
1251 &ipos_decrypted_size,
1252 rend_query->descriptor_cookie,
1253 intro_content,
1254 intro_size) < 0) {
1255 log_warn(LD_REND, "Failed to decrypt introduction points. We are "
1256 "probably unable to parse the encoded introduction points.");
1257 } else {
1258 /* Replace encrypted with decrypted introduction points. */
1259 log_info(LD_REND, "Successfully decrypted introduction points.");
1260 tor_free(intro_content);
1261 intro_content = ipos_decrypted;
1262 intro_size = ipos_decrypted_size;
1265 if (rend_parse_introduction_points(parsed, intro_content,
1266 intro_size) <= 0) {
1267 log_warn(LD_REND, "Failed to parse introduction points. Either the "
1268 "service has published a corrupt descriptor or you have "
1269 "provided invalid authorization data.");
1270 retval = -2;
1271 goto err;
1273 } else {
1274 log_info(LD_REND, "Descriptor does not contain any introduction points.");
1275 parsed->intro_nodes = smartlist_create();
1277 /* We don't need the encoded/encrypted introduction points any longer. */
1278 tor_free(intro_content);
1279 /* Is descriptor too old? */
1280 if (parsed->timestamp < now - REND_CACHE_MAX_AGE-REND_CACHE_MAX_SKEW) {
1281 log_warn(LD_REND, "Service descriptor with service ID %s is too old.",
1282 safe_str(service_id));
1283 retval = -2;
1284 goto err;
1286 /* Is descriptor too far in the future? */
1287 if (parsed->timestamp > now + REND_CACHE_MAX_SKEW) {
1288 log_warn(LD_REND, "Service descriptor with service ID %s is too far in "
1289 "the future.", safe_str(service_id));
1290 retval = -2;
1291 goto err;
1293 /* Do we have a v0 descriptor? */
1294 tor_snprintf(key, sizeof(key), "0%s", service_id);
1295 if (strmap_get_lc(rend_cache, key)) {
1296 log_info(LD_REND, "We already have a v0 descriptor for service ID %s.",
1297 safe_str(service_id));
1298 retval = -1;
1299 goto err;
1301 /* Do we already have a newer descriptor? */
1302 tor_snprintf(key, sizeof(key), "2%s", service_id);
1303 e = (rend_cache_entry_t*) strmap_get_lc(rend_cache, key);
1304 if (e && e->parsed->timestamp > parsed->timestamp) {
1305 log_info(LD_REND, "We already have a newer service descriptor for "
1306 "service ID %s with the same desc ID and version.",
1307 safe_str(service_id));
1308 retval = 0;
1309 goto err;
1311 /* Do we already have this descriptor? */
1312 if (e && !strcmp(desc, e->desc)) {
1313 log_info(LD_REND,"We already have this service descriptor %s.",
1314 safe_str(service_id));
1315 e->received = time(NULL);
1316 retval = 0;
1317 goto err;
1319 if (!e) {
1320 e = tor_malloc_zero(sizeof(rend_cache_entry_t));
1321 strmap_set_lc(rend_cache, key, e);
1322 } else {
1323 rend_service_descriptor_free(e->parsed);
1324 tor_free(e->desc);
1326 e->received = time(NULL);
1327 e->parsed = parsed;
1328 e->desc = tor_malloc_zero(encoded_size + 1);
1329 strlcpy(e->desc, desc, encoded_size + 1);
1330 e->len = encoded_size;
1331 log_debug(LD_REND,"Successfully stored rend desc '%s', len %d.",
1332 safe_str(service_id), (int)encoded_size);
1333 return 1;
1335 err:
1336 if (parsed)
1337 rend_service_descriptor_free(parsed);
1338 tor_free(intro_content);
1339 return retval;
1342 /** Called when we get a rendezvous-related relay cell on circuit
1343 * <b>circ</b>. Dispatch on rendezvous relay command. */
1344 void
1345 rend_process_relay_cell(circuit_t *circ, const crypt_path_t *layer_hint,
1346 int command, size_t length,
1347 const char *payload)
1349 or_circuit_t *or_circ = NULL;
1350 origin_circuit_t *origin_circ = NULL;
1351 int r = -2;
1352 if (CIRCUIT_IS_ORIGIN(circ)) {
1353 origin_circ = TO_ORIGIN_CIRCUIT(circ);
1354 if (!layer_hint || layer_hint != origin_circ->cpath->prev) {
1355 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1356 "Relay cell (rend purpose %d) from wrong hop on origin circ",
1357 command);
1358 origin_circ = NULL;
1360 } else {
1361 or_circ = TO_OR_CIRCUIT(circ);
1364 switch (command) {
1365 case RELAY_COMMAND_ESTABLISH_INTRO:
1366 if (or_circ)
1367 r = rend_mid_establish_intro(or_circ,payload,length);
1368 break;
1369 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
1370 if (or_circ)
1371 r = rend_mid_establish_rendezvous(or_circ,payload,length);
1372 break;
1373 case RELAY_COMMAND_INTRODUCE1:
1374 if (or_circ)
1375 r = rend_mid_introduce(or_circ,payload,length);
1376 break;
1377 case RELAY_COMMAND_INTRODUCE2:
1378 if (origin_circ)
1379 r = rend_service_introduce(origin_circ,payload,length);
1380 break;
1381 case RELAY_COMMAND_INTRODUCE_ACK:
1382 if (origin_circ)
1383 r = rend_client_introduction_acked(origin_circ,payload,length);
1384 break;
1385 case RELAY_COMMAND_RENDEZVOUS1:
1386 if (or_circ)
1387 r = rend_mid_rendezvous(or_circ,payload,length);
1388 break;
1389 case RELAY_COMMAND_RENDEZVOUS2:
1390 if (origin_circ)
1391 r = rend_client_receive_rendezvous(origin_circ,payload,length);
1392 break;
1393 case RELAY_COMMAND_INTRO_ESTABLISHED:
1394 if (origin_circ)
1395 r = rend_service_intro_established(origin_circ,payload,length);
1396 break;
1397 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
1398 if (origin_circ)
1399 r = rend_client_rendezvous_acked(origin_circ,payload,length);
1400 break;
1401 default:
1402 tor_fragile_assert();
1405 if (r == -2)
1406 log_info(LD_PROTOCOL, "Dropping cell (type %d) for wrong circuit type.",
1407 command);
1410 /** Return the number of entries in our rendezvous descriptor cache. */
1412 rend_cache_size(void)
1414 return strmap_size(rend_cache);
1417 /** Allocate and return a new rend_data_t with the same
1418 * contents as <b>query</b>. */
1419 rend_data_t *
1420 rend_data_dup(const rend_data_t *data)
1422 tor_assert(data);
1423 return tor_memdup(data, sizeof(rend_data_t));