fix wide lines
[tor.git] / src / or / rendcommon.c
blobd9d39b1f1975db945a3a45f9a13c56841715a263
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_addr_to_str_dup(&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 /** Return true iff <b>query</b> is a syntactically valid service ID (as
692 * generated by rend_get_service_id). */
694 rend_valid_service_id(const char *query)
696 if (strlen(query) != REND_SERVICE_ID_LEN_BASE32)
697 return 0;
699 if (strspn(query, BASE32_CHARS) != REND_SERVICE_ID_LEN_BASE32)
700 return 0;
702 return 1;
705 /** Return true iff <b>query</b> is a syntactically valid descriptor ID.
706 * (as generated by rend_get_descriptor_id_bytes). */
708 rend_valid_descriptor_id(const char *query)
710 if (strlen(query) != REND_DESC_ID_V2_LEN_BASE32) {
711 goto invalid;
713 if (strspn(query, BASE32_CHARS) != REND_DESC_ID_V2_LEN_BASE32) {
714 goto invalid;
717 return 1;
719 invalid:
720 return 0;
723 /** Return true iff <b>client_name</b> is a syntactically valid name
724 * for rendezvous client authentication. */
726 rend_valid_client_name(const char *client_name)
728 size_t len = strlen(client_name);
729 if (len < 1 || len > REND_CLIENTNAME_MAX_LEN) {
730 return 0;
732 if (strspn(client_name, REND_LEGAL_CLIENTNAME_CHARACTERS) != len) {
733 return 0;
736 return 1;
739 /** Called when we get a rendezvous-related relay cell on circuit
740 * <b>circ</b>. Dispatch on rendezvous relay command. */
741 void
742 rend_process_relay_cell(circuit_t *circ, const crypt_path_t *layer_hint,
743 int command, size_t length,
744 const uint8_t *payload)
746 or_circuit_t *or_circ = NULL;
747 origin_circuit_t *origin_circ = NULL;
748 int r = -2;
749 if (CIRCUIT_IS_ORIGIN(circ)) {
750 origin_circ = TO_ORIGIN_CIRCUIT(circ);
751 if (!layer_hint || layer_hint != origin_circ->cpath->prev) {
752 log_fn(LOG_PROTOCOL_WARN, LD_APP,
753 "Relay cell (rend purpose %d) from wrong hop on origin circ",
754 command);
755 origin_circ = NULL;
757 } else {
758 or_circ = TO_OR_CIRCUIT(circ);
761 switch (command) {
762 case RELAY_COMMAND_ESTABLISH_INTRO:
763 if (or_circ)
764 r = rend_mid_establish_intro(or_circ,payload,length);
765 break;
766 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
767 if (or_circ)
768 r = rend_mid_establish_rendezvous(or_circ,payload,length);
769 break;
770 case RELAY_COMMAND_INTRODUCE1:
771 if (or_circ)
772 r = rend_mid_introduce(or_circ,payload,length);
773 break;
774 case RELAY_COMMAND_INTRODUCE2:
775 if (origin_circ)
776 r = rend_service_receive_introduction(origin_circ,payload,length);
777 break;
778 case RELAY_COMMAND_INTRODUCE_ACK:
779 if (origin_circ)
780 r = rend_client_introduction_acked(origin_circ,payload,length);
781 break;
782 case RELAY_COMMAND_RENDEZVOUS1:
783 if (or_circ)
784 r = rend_mid_rendezvous(or_circ,payload,length);
785 break;
786 case RELAY_COMMAND_RENDEZVOUS2:
787 if (origin_circ)
788 r = rend_client_receive_rendezvous(origin_circ,payload,length);
789 break;
790 case RELAY_COMMAND_INTRO_ESTABLISHED:
791 if (origin_circ)
792 r = rend_service_intro_established(origin_circ,payload,length);
793 break;
794 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
795 if (origin_circ)
796 r = rend_client_rendezvous_acked(origin_circ,payload,length);
797 break;
798 default:
799 tor_fragile_assert();
802 if (r == -2)
803 log_info(LD_PROTOCOL, "Dropping cell (type %d) for wrong circuit type.",
804 command);
807 /** Allocate and return a new rend_data_t with the same
808 * contents as <b>query</b>. */
809 rend_data_t *
810 rend_data_dup(const rend_data_t *data)
812 rend_data_t *data_dup;
813 tor_assert(data);
814 data_dup = tor_memdup(data, sizeof(rend_data_t));
815 data_dup->hsdirs_fp = smartlist_new();
816 SMARTLIST_FOREACH(data->hsdirs_fp, char *, fp,
817 smartlist_add(data_dup->hsdirs_fp,
818 tor_memdup(fp, DIGEST_LEN)));
819 return data_dup;
822 /** Compute descriptor ID for each replicas and save them. A valid onion
823 * address must be present in the <b>rend_data</b>.
825 * Return 0 on success else -1. */
826 static int
827 compute_desc_id(rend_data_t *rend_data)
829 int ret = 0;
830 unsigned replica;
831 time_t now = time(NULL);
833 tor_assert(rend_data);
835 /* Compute descriptor ID for each replicas. */
836 for (replica = 0; replica < ARRAY_LENGTH(rend_data->descriptor_id);
837 replica++) {
838 ret = rend_compute_v2_desc_id(rend_data->descriptor_id[replica],
839 rend_data->onion_address,
840 rend_data->descriptor_cookie,
841 now, replica);
842 if (ret < 0) {
843 goto end;
847 end:
848 return ret;
851 /** Allocate and initialize a rend_data_t object for a service using the
852 * given arguments. Only the <b>onion_address</b> is not optional.
854 * Return a valid rend_data_t pointer. */
855 rend_data_t *
856 rend_data_service_create(const char *onion_address, const char *pk_digest,
857 const uint8_t *cookie, rend_auth_type_t auth_type)
859 rend_data_t *rend_data = tor_malloc_zero(sizeof(*rend_data));
861 /* We need at least one else the call is wrong. */
862 tor_assert(onion_address != NULL);
864 if (pk_digest) {
865 memcpy(rend_data->rend_pk_digest, pk_digest,
866 sizeof(rend_data->rend_pk_digest));
868 if (cookie) {
869 memcpy(rend_data->rend_cookie, cookie,
870 sizeof(rend_data->rend_cookie));
873 strlcpy(rend_data->onion_address, onion_address,
874 sizeof(rend_data->onion_address));
875 rend_data->auth_type = auth_type;
876 /* Won't be used but still need to initialize it for rend_data dup and
877 * free. */
878 rend_data->hsdirs_fp = smartlist_new();
880 return rend_data;
883 /** Allocate and initialize a rend_data_t object for a client request using
884 * the given arguments. Either an onion address or a descriptor ID is
885 * needed. Both can be given but only the onion address will be used to make
886 * the descriptor fetch.
888 * Return a valid rend_data_t pointer or NULL on error meaning the
889 * descriptor IDs couldn't be computed from the given data. */
890 rend_data_t *
891 rend_data_client_create(const char *onion_address, const char *desc_id,
892 const char *cookie, rend_auth_type_t auth_type)
894 rend_data_t *rend_data = tor_malloc_zero(sizeof(*rend_data));
896 /* We need at least one else the call is wrong. */
897 tor_assert(onion_address != NULL || desc_id != NULL);
899 if (cookie) {
900 memcpy(rend_data->descriptor_cookie, cookie,
901 sizeof(rend_data->descriptor_cookie));
903 if (desc_id) {
904 memcpy(rend_data->desc_id_fetch, desc_id,
905 sizeof(rend_data->desc_id_fetch));
907 if (onion_address) {
908 strlcpy(rend_data->onion_address, onion_address,
909 sizeof(rend_data->onion_address));
910 if (compute_desc_id(rend_data) < 0) {
911 goto error;
915 rend_data->auth_type = auth_type;
916 rend_data->hsdirs_fp = smartlist_new();
918 return rend_data;
920 error:
921 rend_data_free(rend_data);
922 return NULL;
925 /** Determine the routers that are responsible for <b>id</b> (binary) and
926 * add pointers to those routers' routerstatus_t to <b>responsible_dirs</b>.
927 * Return -1 if we're returning an empty smartlist, else return 0.
930 hid_serv_get_responsible_directories(smartlist_t *responsible_dirs,
931 const char *id)
933 int start, found, n_added = 0, i;
934 networkstatus_t *c = networkstatus_get_latest_consensus();
935 if (!c || !smartlist_len(c->routerstatus_list)) {
936 log_warn(LD_REND, "We don't have a consensus, so we can't perform v2 "
937 "rendezvous operations.");
938 return -1;
940 tor_assert(id);
941 start = networkstatus_vote_find_entry_idx(c, id, &found);
942 if (start == smartlist_len(c->routerstatus_list)) start = 0;
943 i = start;
944 do {
945 routerstatus_t *r = smartlist_get(c->routerstatus_list, i);
946 if (r->is_hs_dir) {
947 smartlist_add(responsible_dirs, r);
948 if (++n_added == REND_NUMBER_OF_CONSECUTIVE_REPLICAS)
949 return 0;
951 if (++i == smartlist_len(c->routerstatus_list))
952 i = 0;
953 } while (i != start);
955 /* Even though we don't have the desired number of hidden service
956 * directories, be happy if we got any. */
957 return smartlist_len(responsible_dirs) ? 0 : -1;
960 /* Length of the 'extended' auth cookie used to encode auth type before
961 * base64 encoding. */
962 #define REND_DESC_COOKIE_LEN_EXT (REND_DESC_COOKIE_LEN + 1)
963 /* Length of the zero-padded auth cookie when base64 encoded. These two
964 * padding bytes always (A=) are stripped off of the returned cookie. */
965 #define REND_DESC_COOKIE_LEN_EXT_BASE64 (REND_DESC_COOKIE_LEN_BASE64 + 2)
967 /** Encode a client authorization descriptor cookie.
968 * The result of this function is suitable for use in the HidServAuth
969 * option. The trailing padding characters are removed, and the
970 * auth type is encoded into the cookie.
972 * Returns a new base64-encoded cookie. This function cannot fail.
973 * The caller is responsible for freeing the returned value.
975 char *
976 rend_auth_encode_cookie(const uint8_t *cookie_in, rend_auth_type_t auth_type)
978 uint8_t extended_cookie[REND_DESC_COOKIE_LEN_EXT];
979 char *cookie_out = tor_malloc_zero(REND_DESC_COOKIE_LEN_EXT_BASE64 + 1);
980 int re;
982 tor_assert(cookie_in);
984 memcpy(extended_cookie, cookie_in, REND_DESC_COOKIE_LEN);
985 extended_cookie[REND_DESC_COOKIE_LEN] = ((int)auth_type - 1) << 4;
986 re = base64_encode(cookie_out, REND_DESC_COOKIE_LEN_EXT_BASE64 + 1,
987 (const char *) extended_cookie, REND_DESC_COOKIE_LEN_EXT,
989 tor_assert(re == REND_DESC_COOKIE_LEN_EXT_BASE64);
991 /* Remove the trailing 'A='. Auth type is encoded in the high bits
992 * of the last byte, so the last base64 character will always be zero
993 * (A). This is subtly different behavior from base64_encode_nopad. */
994 cookie_out[REND_DESC_COOKIE_LEN_BASE64] = '\0';
995 memwipe(extended_cookie, 0, sizeof(extended_cookie));
996 return cookie_out;
999 /** Decode a base64-encoded client authorization descriptor cookie.
1000 * The descriptor_cookie can be truncated to REND_DESC_COOKIE_LEN_BASE64
1001 * characters (as given to clients), or may include the two padding
1002 * characters (as stored by the service).
1004 * The result is stored in REND_DESC_COOKIE_LEN bytes of cookie_out.
1005 * The rend_auth_type_t decoded from the cookie is stored in the
1006 * optional auth_type_out parameter.
1008 * Return 0 on success, or -1 on error. The caller is responsible for
1009 * freeing the returned err_msg.
1012 rend_auth_decode_cookie(const char *cookie_in, uint8_t *cookie_out,
1013 rend_auth_type_t *auth_type_out, char **err_msg_out)
1015 uint8_t descriptor_cookie_decoded[REND_DESC_COOKIE_LEN_EXT + 1] = { 0 };
1016 char descriptor_cookie_base64ext[REND_DESC_COOKIE_LEN_EXT_BASE64 + 1];
1017 const char *descriptor_cookie = cookie_in;
1018 char *err_msg = NULL;
1019 int auth_type_val = 0;
1020 int res = -1;
1021 int decoded_len;
1023 size_t len = strlen(descriptor_cookie);
1024 if (len == REND_DESC_COOKIE_LEN_BASE64) {
1025 /* Add a trailing zero byte to make base64-decoding happy. */
1026 tor_snprintf(descriptor_cookie_base64ext,
1027 sizeof(descriptor_cookie_base64ext),
1028 "%sA=", descriptor_cookie);
1029 descriptor_cookie = descriptor_cookie_base64ext;
1030 } else if (len != REND_DESC_COOKIE_LEN_EXT_BASE64) {
1031 tor_asprintf(&err_msg, "Authorization cookie has wrong length: %s",
1032 escaped(cookie_in));
1033 goto err;
1036 decoded_len = base64_decode((char *) descriptor_cookie_decoded,
1037 sizeof(descriptor_cookie_decoded),
1038 descriptor_cookie,
1039 REND_DESC_COOKIE_LEN_EXT_BASE64);
1040 if (decoded_len != REND_DESC_COOKIE_LEN &&
1041 decoded_len != REND_DESC_COOKIE_LEN_EXT) {
1042 tor_asprintf(&err_msg, "Authorization cookie has invalid characters: %s",
1043 escaped(cookie_in));
1044 goto err;
1047 if (auth_type_out) {
1048 auth_type_val = (descriptor_cookie_decoded[REND_DESC_COOKIE_LEN] >> 4) + 1;
1049 if (auth_type_val < 1 || auth_type_val > 2) {
1050 tor_asprintf(&err_msg, "Authorization cookie type is unknown: %s",
1051 escaped(cookie_in));
1052 goto err;
1054 *auth_type_out = auth_type_val == 1 ? REND_BASIC_AUTH : REND_STEALTH_AUTH;
1057 memcpy(cookie_out, descriptor_cookie_decoded, REND_DESC_COOKIE_LEN);
1058 res = 0;
1059 err:
1060 if (err_msg_out) {
1061 *err_msg_out = err_msg;
1062 } else {
1063 tor_free(err_msg);
1065 memwipe(descriptor_cookie_decoded, 0, sizeof(descriptor_cookie_decoded));
1066 memwipe(descriptor_cookie_base64ext, 0, sizeof(descriptor_cookie_base64ext));
1067 return res;
1070 /* Is this a rend client or server that allows direct (non-anonymous)
1071 * connections?
1072 * Clients must be specifically compiled and configured in this mode.
1073 * Onion services can be configured to start in this mode.
1074 * Prefer rend_client_allow_non_anonymous_connection() or
1075 * rend_service_allow_non_anonymous_connection() whenever possible, so that
1076 * checks are specific to Single Onion Services or Tor2web. */
1078 rend_allow_non_anonymous_connection(const or_options_t* options)
1080 return (rend_client_allow_non_anonymous_connection(options)
1081 || rend_service_allow_non_anonymous_connection(options));
1084 /* Is this a rend client or server in non-anonymous mode?
1085 * Clients must be specifically compiled in this mode.
1086 * Onion services can be configured to start in this mode.
1087 * Prefer rend_client_non_anonymous_mode_enabled() or
1088 * rend_service_non_anonymous_mode_enabled() whenever possible, so that checks
1089 * are specific to Single Onion Services or Tor2web. */
1091 rend_non_anonymous_mode_enabled(const or_options_t *options)
1093 return (rend_client_non_anonymous_mode_enabled(options)
1094 || rend_service_non_anonymous_mode_enabled(options));
1097 /* Make sure that tor only builds one-hop circuits when they would not
1098 * compromise user anonymity.
1100 * One-hop circuits are permitted in Tor2web or Single Onion modes.
1102 * Tor2web or Single Onion modes are also allowed to make multi-hop circuits.
1103 * For example, single onion HSDir circuits are 3-hop to prevent denial of
1104 * service.
1106 void
1107 assert_circ_anonymity_ok(origin_circuit_t *circ,
1108 const or_options_t *options)
1110 tor_assert(options);
1111 tor_assert(circ);
1112 tor_assert(circ->build_state);
1114 if (circ->build_state->onehop_tunnel) {
1115 tor_assert(rend_allow_non_anonymous_connection(options));