rip out hid_serv_acting_as_directory()
[tor.git] / src / or / rendcommon.c
blob79aba806949bd478965634a386c22a75fed4184a
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2016, 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"
12 #include "circuitbuild.h"
13 #include "config.h"
14 #include "control.h"
15 #include "rendclient.h"
16 #include "rendcommon.h"
17 #include "rendmid.h"
18 #include "rendservice.h"
19 #include "rephist.h"
20 #include "router.h"
21 #include "routerlist.h"
22 #include "routerparse.h"
23 #include "networkstatus.h"
25 /** Return 0 if one and two are the same service ids, else -1 or 1 */
26 int
27 rend_cmp_service_ids(const char *one, const char *two)
29 return strcasecmp(one,two);
32 /** Free the storage held by the service descriptor <b>desc</b>.
34 void
35 rend_service_descriptor_free(rend_service_descriptor_t *desc)
37 if (!desc)
38 return;
39 if (desc->pk)
40 crypto_pk_free(desc->pk);
41 if (desc->intro_nodes) {
42 SMARTLIST_FOREACH(desc->intro_nodes, rend_intro_point_t *, intro,
43 rend_intro_point_free(intro););
44 smartlist_free(desc->intro_nodes);
46 if (desc->successful_uploads) {
47 SMARTLIST_FOREACH(desc->successful_uploads, char *, c, tor_free(c););
48 smartlist_free(desc->successful_uploads);
50 tor_free(desc);
53 /** Length of the descriptor cookie that is used for versioned hidden
54 * service descriptors. */
55 #define REND_DESC_COOKIE_LEN 16
57 /** Length of the replica number that is used to determine the secret ID
58 * part of versioned hidden service descriptors. */
59 #define REND_REPLICA_LEN 1
61 /** Compute the descriptor ID for <b>service_id</b> of length
62 * <b>REND_SERVICE_ID_LEN</b> and <b>secret_id_part</b> of length
63 * <b>DIGEST_LEN</b>, and write it to <b>descriptor_id_out</b> of length
64 * <b>DIGEST_LEN</b>. */
65 void
66 rend_get_descriptor_id_bytes(char *descriptor_id_out,
67 const char *service_id,
68 const char *secret_id_part)
70 crypto_digest_t *digest = crypto_digest_new();
71 crypto_digest_add_bytes(digest, service_id, REND_SERVICE_ID_LEN);
72 crypto_digest_add_bytes(digest, secret_id_part, DIGEST_LEN);
73 crypto_digest_get_digest(digest, descriptor_id_out, DIGEST_LEN);
74 crypto_digest_free(digest);
77 /** Compute the secret ID part for time_period,
78 * a <b>descriptor_cookie</b> of length
79 * <b>REND_DESC_COOKIE_LEN</b> which may also be <b>NULL</b> if no
80 * descriptor_cookie shall be used, and <b>replica</b>, and write it to
81 * <b>secret_id_part</b> of length DIGEST_LEN. */
82 static void
83 get_secret_id_part_bytes(char *secret_id_part, uint32_t time_period,
84 const char *descriptor_cookie, uint8_t replica)
86 crypto_digest_t *digest = crypto_digest_new();
87 time_period = htonl(time_period);
88 crypto_digest_add_bytes(digest, (char*)&time_period, sizeof(uint32_t));
89 if (descriptor_cookie) {
90 crypto_digest_add_bytes(digest, descriptor_cookie,
91 REND_DESC_COOKIE_LEN);
93 crypto_digest_add_bytes(digest, (const char *)&replica, REND_REPLICA_LEN);
94 crypto_digest_get_digest(digest, secret_id_part, DIGEST_LEN);
95 crypto_digest_free(digest);
98 /** Return the time period for time <b>now</b> plus a potentially
99 * intended <b>deviation</b> of one or more periods, based on the first byte
100 * of <b>service_id</b>. */
101 static uint32_t
102 get_time_period(time_t now, uint8_t deviation, const char *service_id)
104 /* The time period is the number of REND_TIME_PERIOD_V2_DESC_VALIDITY
105 * intervals that have passed since the epoch, offset slightly so that
106 * each service's time periods start and end at a fraction of that
107 * period based on their first byte. */
108 return (uint32_t)
109 (now + ((uint8_t) *service_id) * REND_TIME_PERIOD_V2_DESC_VALIDITY / 256)
110 / REND_TIME_PERIOD_V2_DESC_VALIDITY + deviation;
113 /** Compute the time in seconds that a descriptor that is generated
114 * <b>now</b> for <b>service_id</b> will be valid. */
115 static uint32_t
116 get_seconds_valid(time_t now, const char *service_id)
118 uint32_t result = REND_TIME_PERIOD_V2_DESC_VALIDITY -
119 ((uint32_t)
120 (now + ((uint8_t) *service_id) * REND_TIME_PERIOD_V2_DESC_VALIDITY / 256)
121 % REND_TIME_PERIOD_V2_DESC_VALIDITY);
122 return result;
125 /** Compute the binary <b>desc_id_out</b> (DIGEST_LEN bytes long) for a given
126 * base32-encoded <b>service_id</b> and optional unencoded
127 * <b>descriptor_cookie</b> of length REND_DESC_COOKIE_LEN,
128 * at time <b>now</b> for replica number
129 * <b>replica</b>. <b>desc_id</b> needs to have <b>DIGEST_LEN</b> bytes
130 * free. Return 0 for success, -1 otherwise. */
132 rend_compute_v2_desc_id(char *desc_id_out, const char *service_id,
133 const char *descriptor_cookie, time_t now,
134 uint8_t replica)
136 char service_id_binary[REND_SERVICE_ID_LEN];
137 char secret_id_part[DIGEST_LEN];
138 uint32_t time_period;
139 if (!service_id ||
140 strlen(service_id) != REND_SERVICE_ID_LEN_BASE32) {
141 log_warn(LD_REND, "Could not compute v2 descriptor ID: "
142 "Illegal service ID: %s",
143 safe_str(service_id));
144 return -1;
146 if (replica >= REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS) {
147 log_warn(LD_REND, "Could not compute v2 descriptor ID: "
148 "Replica number out of range: %d", replica);
149 return -1;
151 /* Convert service ID to binary. */
152 if (base32_decode(service_id_binary, REND_SERVICE_ID_LEN,
153 service_id, REND_SERVICE_ID_LEN_BASE32) < 0) {
154 log_warn(LD_REND, "Could not compute v2 descriptor ID: "
155 "Illegal characters in service ID: %s",
156 safe_str_client(service_id));
157 return -1;
159 /* Calculate current time-period. */
160 time_period = get_time_period(now, 0, service_id_binary);
161 /* Calculate secret-id-part = h(time-period | desc-cookie | replica). */
162 get_secret_id_part_bytes(secret_id_part, time_period, descriptor_cookie,
163 replica);
164 /* Calculate descriptor ID: H(permanent-id | secret-id-part) */
165 rend_get_descriptor_id_bytes(desc_id_out, service_id_binary, secret_id_part);
166 return 0;
169 /** Encode the introduction points in <b>desc</b> and write the result to a
170 * newly allocated string pointed to by <b>encoded</b>. Return 0 for
171 * success, -1 otherwise. */
172 static int
173 rend_encode_v2_intro_points(char **encoded, rend_service_descriptor_t *desc)
175 size_t unenc_len;
176 char *unenc = NULL;
177 size_t unenc_written = 0;
178 int i;
179 int r = -1;
180 /* Assemble unencrypted list of introduction points. */
181 unenc_len = smartlist_len(desc->intro_nodes) * 1000; /* too long, but ok. */
182 unenc = tor_malloc_zero(unenc_len);
183 for (i = 0; i < smartlist_len(desc->intro_nodes); i++) {
184 char id_base32[REND_INTRO_POINT_ID_LEN_BASE32 + 1];
185 char *onion_key = NULL;
186 size_t onion_key_len;
187 crypto_pk_t *intro_key;
188 char *service_key = NULL;
189 char *address = NULL;
190 size_t service_key_len;
191 int res;
192 rend_intro_point_t *intro = smartlist_get(desc->intro_nodes, i);
193 /* Obtain extend info with introduction point details. */
194 extend_info_t *info = intro->extend_info;
195 /* Encode introduction point ID. */
196 base32_encode(id_base32, sizeof(id_base32),
197 info->identity_digest, DIGEST_LEN);
198 /* Encode onion key. */
199 if (crypto_pk_write_public_key_to_string(info->onion_key, &onion_key,
200 &onion_key_len) < 0) {
201 log_warn(LD_REND, "Could not write onion key.");
202 goto done;
204 /* Encode intro key. */
205 intro_key = intro->intro_key;
206 if (!intro_key ||
207 crypto_pk_write_public_key_to_string(intro_key, &service_key,
208 &service_key_len) < 0) {
209 log_warn(LD_REND, "Could not write intro key.");
210 tor_free(onion_key);
211 goto done;
213 /* Assemble everything for this introduction point. */
214 address = tor_dup_addr(&info->addr);
215 res = tor_snprintf(unenc + unenc_written, unenc_len - unenc_written,
216 "introduction-point %s\n"
217 "ip-address %s\n"
218 "onion-port %d\n"
219 "onion-key\n%s"
220 "service-key\n%s",
221 id_base32,
222 address,
223 info->port,
224 onion_key,
225 service_key);
226 tor_free(address);
227 tor_free(onion_key);
228 tor_free(service_key);
229 if (res < 0) {
230 log_warn(LD_REND, "Not enough space for writing introduction point "
231 "string.");
232 goto done;
234 /* Update total number of written bytes for unencrypted intro points. */
235 unenc_written += res;
237 /* Finalize unencrypted introduction points. */
238 if (unenc_len < unenc_written + 2) {
239 log_warn(LD_REND, "Not enough space for finalizing introduction point "
240 "string.");
241 goto done;
243 unenc[unenc_written++] = '\n';
244 unenc[unenc_written++] = 0;
245 *encoded = unenc;
246 r = 0;
247 done:
248 if (r<0)
249 tor_free(unenc);
250 return r;
253 /** Encrypt the encoded introduction points in <b>encoded</b> using
254 * authorization type 'basic' with <b>client_cookies</b> and write the
255 * result to a newly allocated string pointed to by <b>encrypted_out</b> of
256 * length <b>encrypted_len_out</b>. Return 0 for success, -1 otherwise. */
257 static int
258 rend_encrypt_v2_intro_points_basic(char **encrypted_out,
259 size_t *encrypted_len_out,
260 const char *encoded,
261 smartlist_t *client_cookies)
263 int r = -1, i, pos, enclen, client_blocks;
264 size_t len, client_entries_len;
265 char *enc = NULL, iv[CIPHER_IV_LEN], *client_part = NULL,
266 session_key[CIPHER_KEY_LEN];
267 smartlist_t *encrypted_session_keys = NULL;
268 crypto_digest_t *digest;
269 crypto_cipher_t *cipher;
270 tor_assert(encoded);
271 tor_assert(client_cookies && smartlist_len(client_cookies) > 0);
273 /* Generate session key. */
274 crypto_rand(session_key, CIPHER_KEY_LEN);
276 /* Determine length of encrypted introduction points including session
277 * keys. */
278 client_blocks = 1 + ((smartlist_len(client_cookies) - 1) /
279 REND_BASIC_AUTH_CLIENT_MULTIPLE);
280 client_entries_len = client_blocks * REND_BASIC_AUTH_CLIENT_MULTIPLE *
281 REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
282 len = 2 + client_entries_len + CIPHER_IV_LEN + strlen(encoded);
283 if (client_blocks >= 256) {
284 log_warn(LD_REND, "Too many clients in introduction point string.");
285 goto done;
287 enc = tor_malloc_zero(len);
288 enc[0] = 0x01; /* type of authorization. */
289 enc[1] = (uint8_t)client_blocks;
291 /* Encrypt with random session key. */
292 enclen = crypto_cipher_encrypt_with_iv(session_key,
293 enc + 2 + client_entries_len,
294 CIPHER_IV_LEN + strlen(encoded), encoded, strlen(encoded));
296 if (enclen < 0) {
297 log_warn(LD_REND, "Could not encrypt introduction point string.");
298 goto done;
300 memcpy(iv, enc + 2 + client_entries_len, CIPHER_IV_LEN);
302 /* Encrypt session key for cookies, determine client IDs, and put both
303 * in a smartlist. */
304 encrypted_session_keys = smartlist_new();
305 SMARTLIST_FOREACH_BEGIN(client_cookies, const char *, cookie) {
306 client_part = tor_malloc_zero(REND_BASIC_AUTH_CLIENT_ENTRY_LEN);
307 /* Encrypt session key. */
308 cipher = crypto_cipher_new(cookie);
309 if (crypto_cipher_encrypt(cipher, client_part +
310 REND_BASIC_AUTH_CLIENT_ID_LEN,
311 session_key, CIPHER_KEY_LEN) < 0) {
312 log_warn(LD_REND, "Could not encrypt session key for client.");
313 crypto_cipher_free(cipher);
314 tor_free(client_part);
315 goto done;
317 crypto_cipher_free(cipher);
319 /* Determine client ID. */
320 digest = crypto_digest_new();
321 crypto_digest_add_bytes(digest, cookie, REND_DESC_COOKIE_LEN);
322 crypto_digest_add_bytes(digest, iv, CIPHER_IV_LEN);
323 crypto_digest_get_digest(digest, client_part,
324 REND_BASIC_AUTH_CLIENT_ID_LEN);
325 crypto_digest_free(digest);
327 /* Put both together. */
328 smartlist_add(encrypted_session_keys, client_part);
329 } SMARTLIST_FOREACH_END(cookie);
331 /* Add some fake client IDs and encrypted session keys. */
332 for (i = (smartlist_len(client_cookies) - 1) %
333 REND_BASIC_AUTH_CLIENT_MULTIPLE;
334 i < REND_BASIC_AUTH_CLIENT_MULTIPLE - 1; i++) {
335 client_part = tor_malloc_zero(REND_BASIC_AUTH_CLIENT_ENTRY_LEN);
336 crypto_rand(client_part, REND_BASIC_AUTH_CLIENT_ENTRY_LEN);
337 smartlist_add(encrypted_session_keys, client_part);
339 /* Sort smartlist and put elements in result in order. */
340 smartlist_sort_digests(encrypted_session_keys);
341 pos = 2;
342 SMARTLIST_FOREACH(encrypted_session_keys, const char *, entry, {
343 memcpy(enc + pos, entry, REND_BASIC_AUTH_CLIENT_ENTRY_LEN);
344 pos += REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
346 *encrypted_out = enc;
347 *encrypted_len_out = len;
348 enc = NULL; /* prevent free. */
349 r = 0;
350 done:
351 tor_free(enc);
352 if (encrypted_session_keys) {
353 SMARTLIST_FOREACH(encrypted_session_keys, char *, d, tor_free(d););
354 smartlist_free(encrypted_session_keys);
356 return r;
359 /** Encrypt the encoded introduction points in <b>encoded</b> using
360 * authorization type 'stealth' with <b>descriptor_cookie</b> of length
361 * REND_DESC_COOKIE_LEN and write the result to a newly allocated string
362 * pointed to by <b>encrypted_out</b> of length <b>encrypted_len_out</b>.
363 * Return 0 for success, -1 otherwise. */
364 static int
365 rend_encrypt_v2_intro_points_stealth(char **encrypted_out,
366 size_t *encrypted_len_out,
367 const char *encoded,
368 const char *descriptor_cookie)
370 int r = -1, enclen;
371 char *enc;
372 tor_assert(encoded);
373 tor_assert(descriptor_cookie);
375 enc = tor_malloc_zero(1 + CIPHER_IV_LEN + strlen(encoded));
376 enc[0] = 0x02; /* Auth type */
377 enclen = crypto_cipher_encrypt_with_iv(descriptor_cookie,
378 enc + 1,
379 CIPHER_IV_LEN+strlen(encoded),
380 encoded, strlen(encoded));
381 if (enclen < 0) {
382 log_warn(LD_REND, "Could not encrypt introduction point string.");
383 goto done;
385 *encrypted_out = enc;
386 *encrypted_len_out = enclen;
387 enc = NULL; /* prevent free */
388 r = 0;
389 done:
390 tor_free(enc);
391 return r;
394 /** Attempt to parse the given <b>desc_str</b> and return true if this
395 * succeeds, false otherwise. */
396 static int
397 rend_desc_v2_is_parsable(rend_encoded_v2_service_descriptor_t *desc)
399 rend_service_descriptor_t *test_parsed = NULL;
400 char test_desc_id[DIGEST_LEN];
401 char *test_intro_content = NULL;
402 size_t test_intro_size;
403 size_t test_encoded_size;
404 const char *test_next;
405 int res = rend_parse_v2_service_descriptor(&test_parsed, test_desc_id,
406 &test_intro_content,
407 &test_intro_size,
408 &test_encoded_size,
409 &test_next, desc->desc_str, 1);
410 rend_service_descriptor_free(test_parsed);
411 tor_free(test_intro_content);
412 return (res >= 0);
415 /** Free the storage held by an encoded v2 service descriptor. */
416 void
417 rend_encoded_v2_service_descriptor_free(
418 rend_encoded_v2_service_descriptor_t *desc)
420 if (!desc)
421 return;
422 tor_free(desc->desc_str);
423 tor_free(desc);
426 /** Free the storage held by an introduction point info. */
427 void
428 rend_intro_point_free(rend_intro_point_t *intro)
430 if (!intro)
431 return;
433 extend_info_free(intro->extend_info);
434 crypto_pk_free(intro->intro_key);
436 if (intro->accepted_intro_rsa_parts != NULL) {
437 replaycache_free(intro->accepted_intro_rsa_parts);
440 tor_free(intro);
443 /** Encode a set of rend_encoded_v2_service_descriptor_t's for <b>desc</b>
444 * at time <b>now</b> using <b>service_key</b>, depending on
445 * <b>auth_type</b> a <b>descriptor_cookie</b> and a list of
446 * <b>client_cookies</b> (which are both <b>NULL</b> if no client
447 * authorization is performed), and <b>period</b> (e.g. 0 for the current
448 * period, 1 for the next period, etc.) and add them to the existing list
449 * <b>descs_out</b>; return the number of seconds that the descriptors will
450 * be found by clients, or -1 if the encoding was not successful. */
452 rend_encode_v2_descriptors(smartlist_t *descs_out,
453 rend_service_descriptor_t *desc, time_t now,
454 uint8_t period, rend_auth_type_t auth_type,
455 crypto_pk_t *client_key,
456 smartlist_t *client_cookies)
458 char service_id[DIGEST_LEN];
459 char service_id_base32[REND_SERVICE_ID_LEN_BASE32+1];
460 uint32_t time_period;
461 char *ipos_base64 = NULL, *ipos = NULL, *ipos_encrypted = NULL,
462 *descriptor_cookie = NULL;
463 size_t ipos_len = 0, ipos_encrypted_len = 0;
464 int k;
465 uint32_t seconds_valid;
466 crypto_pk_t *service_key;
467 if (!desc) {
468 log_warn(LD_BUG, "Could not encode v2 descriptor: No desc given.");
469 return -1;
471 service_key = (auth_type == REND_STEALTH_AUTH) ? client_key : desc->pk;
472 tor_assert(service_key);
473 if (auth_type == REND_STEALTH_AUTH) {
474 descriptor_cookie = smartlist_get(client_cookies, 0);
475 tor_assert(descriptor_cookie);
477 /* Obtain service_id from public key. */
478 crypto_pk_get_digest(service_key, service_id);
479 /* Calculate current time-period. */
480 time_period = get_time_period(now, period, service_id);
481 /* Determine how many seconds the descriptor will be valid. */
482 seconds_valid = period * REND_TIME_PERIOD_V2_DESC_VALIDITY +
483 get_seconds_valid(now, service_id);
484 /* Assemble, possibly encrypt, and encode introduction points. */
485 if (smartlist_len(desc->intro_nodes) > 0) {
486 if (rend_encode_v2_intro_points(&ipos, desc) < 0) {
487 log_warn(LD_REND, "Encoding of introduction points did not succeed.");
488 return -1;
490 switch (auth_type) {
491 case REND_NO_AUTH:
492 ipos_len = strlen(ipos);
493 break;
494 case REND_BASIC_AUTH:
495 if (rend_encrypt_v2_intro_points_basic(&ipos_encrypted,
496 &ipos_encrypted_len, ipos,
497 client_cookies) < 0) {
498 log_warn(LD_REND, "Encrypting of introduction points did not "
499 "succeed.");
500 tor_free(ipos);
501 return -1;
503 tor_free(ipos);
504 ipos = ipos_encrypted;
505 ipos_len = ipos_encrypted_len;
506 break;
507 case REND_STEALTH_AUTH:
508 if (rend_encrypt_v2_intro_points_stealth(&ipos_encrypted,
509 &ipos_encrypted_len, ipos,
510 descriptor_cookie) < 0) {
511 log_warn(LD_REND, "Encrypting of introduction points did not "
512 "succeed.");
513 tor_free(ipos);
514 return -1;
516 tor_free(ipos);
517 ipos = ipos_encrypted;
518 ipos_len = ipos_encrypted_len;
519 break;
520 default:
521 log_warn(LD_REND|LD_BUG, "Unrecognized authorization type %d",
522 (int)auth_type);
523 tor_free(ipos);
524 return -1;
526 /* Base64-encode introduction points. */
527 ipos_base64 = tor_calloc(ipos_len, 2);
528 if (base64_encode(ipos_base64, ipos_len * 2, ipos, ipos_len,
529 BASE64_ENCODE_MULTILINE)<0) {
530 log_warn(LD_REND, "Could not encode introduction point string to "
531 "base64. length=%d", (int)ipos_len);
532 tor_free(ipos_base64);
533 tor_free(ipos);
534 return -1;
536 tor_free(ipos);
538 /* Encode REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS descriptors. */
539 for (k = 0; k < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; k++) {
540 char secret_id_part[DIGEST_LEN];
541 char secret_id_part_base32[REND_SECRET_ID_PART_LEN_BASE32 + 1];
542 char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
543 char *permanent_key = NULL;
544 size_t permanent_key_len;
545 char published[ISO_TIME_LEN+1];
546 int i;
547 char protocol_versions_string[16]; /* max len: "0,1,2,3,4,5,6,7\0" */
548 size_t protocol_versions_written;
549 size_t desc_len;
550 char *desc_str = NULL;
551 int result = 0;
552 size_t written = 0;
553 char desc_digest[DIGEST_LEN];
554 rend_encoded_v2_service_descriptor_t *enc =
555 tor_malloc_zero(sizeof(rend_encoded_v2_service_descriptor_t));
556 /* Calculate secret-id-part = h(time-period | cookie | replica). */
557 get_secret_id_part_bytes(secret_id_part, time_period, descriptor_cookie,
559 base32_encode(secret_id_part_base32, sizeof(secret_id_part_base32),
560 secret_id_part, DIGEST_LEN);
561 /* Calculate descriptor ID. */
562 rend_get_descriptor_id_bytes(enc->desc_id, service_id, secret_id_part);
563 base32_encode(desc_id_base32, sizeof(desc_id_base32),
564 enc->desc_id, DIGEST_LEN);
565 /* PEM-encode the public key */
566 if (crypto_pk_write_public_key_to_string(service_key, &permanent_key,
567 &permanent_key_len) < 0) {
568 log_warn(LD_BUG, "Could not write public key to string.");
569 rend_encoded_v2_service_descriptor_free(enc);
570 goto err;
572 /* Encode timestamp. */
573 format_iso_time(published, desc->timestamp);
574 /* Write protocol-versions bitmask to comma-separated value string. */
575 protocol_versions_written = 0;
576 for (i = 0; i < 8; i++) {
577 if (desc->protocols & 1 << i) {
578 tor_snprintf(protocol_versions_string + protocol_versions_written,
579 16 - protocol_versions_written, "%d,", i);
580 protocol_versions_written += 2;
583 if (protocol_versions_written)
584 protocol_versions_string[protocol_versions_written - 1] = '\0';
585 else
586 protocol_versions_string[0]= '\0';
587 /* Assemble complete descriptor. */
588 desc_len = 2000 + smartlist_len(desc->intro_nodes) * 1000; /* far too long,
589 but okay.*/
590 enc->desc_str = desc_str = tor_malloc_zero(desc_len);
591 result = tor_snprintf(desc_str, desc_len,
592 "rendezvous-service-descriptor %s\n"
593 "version 2\n"
594 "permanent-key\n%s"
595 "secret-id-part %s\n"
596 "publication-time %s\n"
597 "protocol-versions %s\n",
598 desc_id_base32,
599 permanent_key,
600 secret_id_part_base32,
601 published,
602 protocol_versions_string);
603 tor_free(permanent_key);
604 if (result < 0) {
605 log_warn(LD_BUG, "Descriptor ran out of room.");
606 rend_encoded_v2_service_descriptor_free(enc);
607 goto err;
609 written = result;
610 /* Add introduction points. */
611 if (ipos_base64) {
612 result = tor_snprintf(desc_str + written, desc_len - written,
613 "introduction-points\n"
614 "-----BEGIN MESSAGE-----\n%s"
615 "-----END MESSAGE-----\n",
616 ipos_base64);
617 if (result < 0) {
618 log_warn(LD_BUG, "could not write introduction points.");
619 rend_encoded_v2_service_descriptor_free(enc);
620 goto err;
622 written += result;
624 /* Add signature. */
625 strlcpy(desc_str + written, "signature\n", desc_len - written);
626 written += strlen(desc_str + written);
627 if (crypto_digest(desc_digest, desc_str, written) < 0) {
628 log_warn(LD_BUG, "could not create digest.");
629 rend_encoded_v2_service_descriptor_free(enc);
630 goto err;
632 if (router_append_dirobj_signature(desc_str + written,
633 desc_len - written,
634 desc_digest, DIGEST_LEN,
635 service_key) < 0) {
636 log_warn(LD_BUG, "Couldn't sign desc.");
637 rend_encoded_v2_service_descriptor_free(enc);
638 goto err;
640 written += strlen(desc_str+written);
641 if (written+2 > desc_len) {
642 log_warn(LD_BUG, "Could not finish desc.");
643 rend_encoded_v2_service_descriptor_free(enc);
644 goto err;
646 desc_str[written++] = 0;
647 /* Check if we can parse our own descriptor. */
648 if (!rend_desc_v2_is_parsable(enc)) {
649 log_warn(LD_BUG, "Could not parse my own descriptor: %s", desc_str);
650 rend_encoded_v2_service_descriptor_free(enc);
651 goto err;
653 smartlist_add(descs_out, enc);
654 /* Add the uploaded descriptor to the local service's descriptor cache */
655 rend_cache_store_v2_desc_as_service(enc->desc_str);
656 base32_encode(service_id_base32, sizeof(service_id_base32),
657 service_id, REND_SERVICE_ID_LEN);
658 control_event_hs_descriptor_created(service_id_base32, desc_id_base32, k);
661 log_info(LD_REND, "Successfully encoded a v2 descriptor and "
662 "confirmed that it is parsable.");
663 goto done;
665 err:
666 SMARTLIST_FOREACH(descs_out, rend_encoded_v2_service_descriptor_t *, d,
667 rend_encoded_v2_service_descriptor_free(d););
668 smartlist_clear(descs_out);
669 seconds_valid = -1;
671 done:
672 tor_free(ipos_base64);
673 return seconds_valid;
676 /** Sets <b>out</b> to the first 10 bytes of the digest of <b>pk</b>,
677 * base32 encoded. NUL-terminates out. (We use this string to
678 * identify services in directory requests and .onion URLs.)
681 rend_get_service_id(crypto_pk_t *pk, char *out)
683 char buf[DIGEST_LEN];
684 tor_assert(pk);
685 if (crypto_pk_get_digest(pk, buf) < 0)
686 return -1;
687 base32_encode(out, REND_SERVICE_ID_LEN_BASE32+1, buf, REND_SERVICE_ID_LEN);
688 return 0;
691 /** Determines whether <b>a</b> is in the interval of <b>b</b> (excluded) and
692 * <b>c</b> (included) in a circular digest ring; returns 1 if this is the
693 * case, and 0 otherwise.
696 rend_id_is_in_interval(const char *a, const char *b, const char *c)
698 int a_b, b_c, c_a;
699 tor_assert(a);
700 tor_assert(b);
701 tor_assert(c);
703 /* There are five cases in which a is outside the interval ]b,c]: */
704 a_b = tor_memcmp(a,b,DIGEST_LEN);
705 if (a_b == 0)
706 return 0; /* 1. a == b (b is excluded) */
707 b_c = tor_memcmp(b,c,DIGEST_LEN);
708 if (b_c == 0)
709 return 0; /* 2. b == c (interval is empty) */
710 else if (a_b <= 0 && b_c < 0)
711 return 0; /* 3. a b c */
712 c_a = tor_memcmp(c,a,DIGEST_LEN);
713 if (c_a < 0 && a_b <= 0)
714 return 0; /* 4. c a b */
715 else if (b_c < 0 && c_a < 0)
716 return 0; /* 5. b c a */
718 /* In the other cases (a c b; b a c; c b a), a is inside the interval. */
719 return 1;
722 /** Return true iff <b>query</b> is a syntactically valid service ID (as
723 * generated by rend_get_service_id). */
725 rend_valid_service_id(const char *query)
727 if (strlen(query) != REND_SERVICE_ID_LEN_BASE32)
728 return 0;
730 if (strspn(query, BASE32_CHARS) != REND_SERVICE_ID_LEN_BASE32)
731 return 0;
733 return 1;
736 /** Return true iff <b>query</b> is a syntactically valid descriptor ID.
737 * (as generated by rend_get_descriptor_id_bytes). */
739 rend_valid_descriptor_id(const char *query)
741 if (strlen(query) != REND_DESC_ID_V2_LEN_BASE32) {
742 goto invalid;
744 if (strspn(query, BASE32_CHARS) != REND_DESC_ID_V2_LEN_BASE32) {
745 goto invalid;
748 return 1;
750 invalid:
751 return 0;
754 /** Called when we get a rendezvous-related relay cell on circuit
755 * <b>circ</b>. Dispatch on rendezvous relay command. */
756 void
757 rend_process_relay_cell(circuit_t *circ, const crypt_path_t *layer_hint,
758 int command, size_t length,
759 const uint8_t *payload)
761 or_circuit_t *or_circ = NULL;
762 origin_circuit_t *origin_circ = NULL;
763 int r = -2;
764 if (CIRCUIT_IS_ORIGIN(circ)) {
765 origin_circ = TO_ORIGIN_CIRCUIT(circ);
766 if (!layer_hint || layer_hint != origin_circ->cpath->prev) {
767 log_fn(LOG_PROTOCOL_WARN, LD_APP,
768 "Relay cell (rend purpose %d) from wrong hop on origin circ",
769 command);
770 origin_circ = NULL;
772 } else {
773 or_circ = TO_OR_CIRCUIT(circ);
776 switch (command) {
777 case RELAY_COMMAND_ESTABLISH_INTRO:
778 if (or_circ)
779 r = rend_mid_establish_intro(or_circ,payload,length);
780 break;
781 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
782 if (or_circ)
783 r = rend_mid_establish_rendezvous(or_circ,payload,length);
784 break;
785 case RELAY_COMMAND_INTRODUCE1:
786 if (or_circ)
787 r = rend_mid_introduce(or_circ,payload,length);
788 break;
789 case RELAY_COMMAND_INTRODUCE2:
790 if (origin_circ)
791 r = rend_service_receive_introduction(origin_circ,payload,length);
792 break;
793 case RELAY_COMMAND_INTRODUCE_ACK:
794 if (origin_circ)
795 r = rend_client_introduction_acked(origin_circ,payload,length);
796 break;
797 case RELAY_COMMAND_RENDEZVOUS1:
798 if (or_circ)
799 r = rend_mid_rendezvous(or_circ,payload,length);
800 break;
801 case RELAY_COMMAND_RENDEZVOUS2:
802 if (origin_circ)
803 r = rend_client_receive_rendezvous(origin_circ,payload,length);
804 break;
805 case RELAY_COMMAND_INTRO_ESTABLISHED:
806 if (origin_circ)
807 r = rend_service_intro_established(origin_circ,payload,length);
808 break;
809 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
810 if (origin_circ)
811 r = rend_client_rendezvous_acked(origin_circ,payload,length);
812 break;
813 default:
814 tor_fragile_assert();
817 if (r == -2)
818 log_info(LD_PROTOCOL, "Dropping cell (type %d) for wrong circuit type.",
819 command);
822 /** Allocate and return a new rend_data_t with the same
823 * contents as <b>query</b>. */
824 rend_data_t *
825 rend_data_dup(const rend_data_t *data)
827 rend_data_t *data_dup;
828 tor_assert(data);
829 data_dup = tor_memdup(data, sizeof(rend_data_t));
830 data_dup->hsdirs_fp = smartlist_new();
831 SMARTLIST_FOREACH(data->hsdirs_fp, char *, fp,
832 smartlist_add(data_dup->hsdirs_fp,
833 tor_memdup(fp, DIGEST_LEN)));
834 return data_dup;
837 /** Compute descriptor ID for each replicas and save them. A valid onion
838 * address must be present in the <b>rend_data</b>.
840 * Return 0 on success else -1. */
841 static int
842 compute_desc_id(rend_data_t *rend_data)
844 int ret = 0;
845 unsigned replica;
846 time_t now = time(NULL);
848 tor_assert(rend_data);
850 /* Compute descriptor ID for each replicas. */
851 for (replica = 0; replica < ARRAY_LENGTH(rend_data->descriptor_id);
852 replica++) {
853 ret = rend_compute_v2_desc_id(rend_data->descriptor_id[replica],
854 rend_data->onion_address,
855 rend_data->descriptor_cookie,
856 now, replica);
857 if (ret < 0) {
858 goto end;
862 end:
863 return ret;
866 /** Allocate and initialize a rend_data_t object for a service using the
867 * given arguments. Only the <b>onion_address</b> is not optional.
869 * Return a valid rend_data_t pointer. */
870 rend_data_t *
871 rend_data_service_create(const char *onion_address, const char *pk_digest,
872 const uint8_t *cookie, rend_auth_type_t auth_type)
874 rend_data_t *rend_data = tor_malloc_zero(sizeof(*rend_data));
876 /* We need at least one else the call is wrong. */
877 tor_assert(onion_address != NULL);
879 if (pk_digest) {
880 memcpy(rend_data->rend_pk_digest, pk_digest,
881 sizeof(rend_data->rend_pk_digest));
883 if (cookie) {
884 memcpy(rend_data->rend_cookie, cookie,
885 sizeof(rend_data->rend_cookie));
888 strlcpy(rend_data->onion_address, onion_address,
889 sizeof(rend_data->onion_address));
890 rend_data->auth_type = auth_type;
891 /* Won't be used but still need to initialize it for rend_data dup and
892 * free. */
893 rend_data->hsdirs_fp = smartlist_new();
895 return rend_data;
898 /** Allocate and initialize a rend_data_t object for a client request using
899 * the given arguments. Either an onion address or a descriptor ID is
900 * needed. Both can be given but only the onion address will be used to make
901 * the descriptor fetch.
903 * Return a valid rend_data_t pointer or NULL on error meaning the
904 * descriptor IDs couldn't be computed from the given data. */
905 rend_data_t *
906 rend_data_client_create(const char *onion_address, const char *desc_id,
907 const char *cookie, rend_auth_type_t auth_type)
909 rend_data_t *rend_data = tor_malloc_zero(sizeof(*rend_data));
911 /* We need at least one else the call is wrong. */
912 tor_assert(onion_address != NULL || desc_id != NULL);
914 if (cookie) {
915 memcpy(rend_data->descriptor_cookie, cookie,
916 sizeof(rend_data->descriptor_cookie));
918 if (desc_id) {
919 memcpy(rend_data->desc_id_fetch, desc_id,
920 sizeof(rend_data->desc_id_fetch));
922 if (onion_address) {
923 strlcpy(rend_data->onion_address, onion_address,
924 sizeof(rend_data->onion_address));
925 if (compute_desc_id(rend_data) < 0) {
926 goto error;
930 rend_data->auth_type = auth_type;
931 rend_data->hsdirs_fp = smartlist_new();
933 return rend_data;
935 error:
936 rend_data_free(rend_data);
937 return NULL;
940 /** Determine the routers that are responsible for <b>id</b> (binary) and
941 * add pointers to those routers' routerstatus_t to <b>responsible_dirs</b>.
942 * Return -1 if we're returning an empty smartlist, else return 0.
945 hid_serv_get_responsible_directories(smartlist_t *responsible_dirs,
946 const char *id)
948 int start, found, n_added = 0, i;
949 networkstatus_t *c = networkstatus_get_latest_consensus();
950 if (!c || !smartlist_len(c->routerstatus_list)) {
951 log_warn(LD_REND, "We don't have a consensus, so we can't perform v2 "
952 "rendezvous operations.");
953 return -1;
955 tor_assert(id);
956 start = networkstatus_vote_find_entry_idx(c, id, &found);
957 if (start == smartlist_len(c->routerstatus_list)) start = 0;
958 i = start;
959 do {
960 routerstatus_t *r = smartlist_get(c->routerstatus_list, i);
961 if (r->is_hs_dir) {
962 smartlist_add(responsible_dirs, r);
963 if (++n_added == REND_NUMBER_OF_CONSECUTIVE_REPLICAS)
964 return 0;
966 if (++i == smartlist_len(c->routerstatus_list))
967 i = 0;
968 } while (i != start);
970 /* Even though we don't have the desired number of hidden service
971 * directories, be happy if we got any. */
972 return smartlist_len(responsible_dirs) ? 0 : -1;