minor updates on upcoming changelog
[tor.git] / src / or / rendcommon.c
blob458a90058f923c3b01e3295a4e8c8128c3524f70
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2017, 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 #define RENDCOMMON_PRIVATE
13 #include "or.h"
14 #include "circuitbuild.h"
15 #include "config.h"
16 #include "control.h"
17 #include "hs_common.h"
18 #include "rendclient.h"
19 #include "rendcommon.h"
20 #include "rendmid.h"
21 #include "hs_intropoint.h"
22 #include "hs_client.h"
23 #include "rendservice.h"
24 #include "rephist.h"
25 #include "router.h"
26 #include "routerlist.h"
27 #include "routerparse.h"
28 #include "networkstatus.h"
30 /** Return 0 if one and two are the same service ids, else -1 or 1 */
31 int
32 rend_cmp_service_ids(const char *one, const char *two)
34 return strcasecmp(one,two);
37 /** Free the storage held by the service descriptor <b>desc</b>.
39 void
40 rend_service_descriptor_free(rend_service_descriptor_t *desc)
42 if (!desc)
43 return;
44 if (desc->pk)
45 crypto_pk_free(desc->pk);
46 if (desc->intro_nodes) {
47 SMARTLIST_FOREACH(desc->intro_nodes, rend_intro_point_t *, intro,
48 rend_intro_point_free(intro););
49 smartlist_free(desc->intro_nodes);
51 if (desc->successful_uploads) {
52 SMARTLIST_FOREACH(desc->successful_uploads, char *, c, tor_free(c););
53 smartlist_free(desc->successful_uploads);
55 tor_free(desc);
58 /** Length of the descriptor cookie that is used for versioned hidden
59 * service descriptors. */
60 #define REND_DESC_COOKIE_LEN 16
62 /** Length of the replica number that is used to determine the secret ID
63 * part of versioned hidden service descriptors. */
64 #define REND_REPLICA_LEN 1
66 /** Compute the descriptor ID for <b>service_id</b> of length
67 * <b>REND_SERVICE_ID_LEN</b> and <b>secret_id_part</b> of length
68 * <b>DIGEST_LEN</b>, and write it to <b>descriptor_id_out</b> of length
69 * <b>DIGEST_LEN</b>. */
70 void
71 rend_get_descriptor_id_bytes(char *descriptor_id_out,
72 const char *service_id,
73 const char *secret_id_part)
75 crypto_digest_t *digest = crypto_digest_new();
76 crypto_digest_add_bytes(digest, service_id, REND_SERVICE_ID_LEN);
77 crypto_digest_add_bytes(digest, secret_id_part, DIGEST_LEN);
78 crypto_digest_get_digest(digest, descriptor_id_out, DIGEST_LEN);
79 crypto_digest_free(digest);
82 /** Compute the secret ID part for time_period,
83 * a <b>descriptor_cookie</b> of length
84 * <b>REND_DESC_COOKIE_LEN</b> which may also be <b>NULL</b> if no
85 * descriptor_cookie shall be used, and <b>replica</b>, and write it to
86 * <b>secret_id_part</b> of length DIGEST_LEN. */
87 static void
88 get_secret_id_part_bytes(char *secret_id_part, uint32_t time_period,
89 const char *descriptor_cookie, uint8_t replica)
91 crypto_digest_t *digest = crypto_digest_new();
92 time_period = htonl(time_period);
93 crypto_digest_add_bytes(digest, (char*)&time_period, sizeof(uint32_t));
94 if (descriptor_cookie) {
95 crypto_digest_add_bytes(digest, descriptor_cookie,
96 REND_DESC_COOKIE_LEN);
98 crypto_digest_add_bytes(digest, (const char *)&replica, REND_REPLICA_LEN);
99 crypto_digest_get_digest(digest, secret_id_part, DIGEST_LEN);
100 crypto_digest_free(digest);
103 /** Return the time period for time <b>now</b> plus a potentially
104 * intended <b>deviation</b> of one or more periods, based on the first byte
105 * of <b>service_id</b>. */
106 static uint32_t
107 get_time_period(time_t now, uint8_t deviation, const char *service_id)
109 /* The time period is the number of REND_TIME_PERIOD_V2_DESC_VALIDITY
110 * intervals that have passed since the epoch, offset slightly so that
111 * each service's time periods start and end at a fraction of that
112 * period based on their first byte. */
113 return (uint32_t)
114 (now + ((uint8_t) *service_id) * REND_TIME_PERIOD_V2_DESC_VALIDITY / 256)
115 / REND_TIME_PERIOD_V2_DESC_VALIDITY + deviation;
118 /** Compute the time in seconds that a descriptor that is generated
119 * <b>now</b> for <b>service_id</b> will be valid. */
120 static uint32_t
121 get_seconds_valid(time_t now, const char *service_id)
123 uint32_t result = REND_TIME_PERIOD_V2_DESC_VALIDITY -
124 ((uint32_t)
125 (now + ((uint8_t) *service_id) * REND_TIME_PERIOD_V2_DESC_VALIDITY / 256)
126 % REND_TIME_PERIOD_V2_DESC_VALIDITY);
127 return result;
130 /** Compute the binary <b>desc_id_out</b> (DIGEST_LEN bytes long) for a given
131 * base32-encoded <b>service_id</b> and optional unencoded
132 * <b>descriptor_cookie</b> of length REND_DESC_COOKIE_LEN,
133 * at time <b>now</b> for replica number
134 * <b>replica</b>. <b>desc_id</b> needs to have <b>DIGEST_LEN</b> bytes
135 * free. Return 0 for success, -1 otherwise. */
137 rend_compute_v2_desc_id(char *desc_id_out, const char *service_id,
138 const char *descriptor_cookie, time_t now,
139 uint8_t replica)
141 char service_id_binary[REND_SERVICE_ID_LEN];
142 char secret_id_part[DIGEST_LEN];
143 uint32_t time_period;
144 if (!service_id ||
145 strlen(service_id) != REND_SERVICE_ID_LEN_BASE32) {
146 log_warn(LD_REND, "Could not compute v2 descriptor ID: "
147 "Illegal service ID: %s",
148 safe_str(service_id));
149 return -1;
151 if (replica >= REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS) {
152 log_warn(LD_REND, "Could not compute v2 descriptor ID: "
153 "Replica number out of range: %d", replica);
154 return -1;
156 /* Convert service ID to binary. */
157 if (base32_decode(service_id_binary, REND_SERVICE_ID_LEN,
158 service_id, REND_SERVICE_ID_LEN_BASE32) < 0) {
159 log_warn(LD_REND, "Could not compute v2 descriptor ID: "
160 "Illegal characters in service ID: %s",
161 safe_str_client(service_id));
162 return -1;
164 /* Calculate current time-period. */
165 time_period = get_time_period(now, 0, service_id_binary);
166 /* Calculate secret-id-part = h(time-period | desc-cookie | replica). */
167 get_secret_id_part_bytes(secret_id_part, time_period, descriptor_cookie,
168 replica);
169 /* Calculate descriptor ID: H(permanent-id | secret-id-part) */
170 rend_get_descriptor_id_bytes(desc_id_out, service_id_binary, secret_id_part);
171 return 0;
174 /** Encode the introduction points in <b>desc</b> and write the result to a
175 * newly allocated string pointed to by <b>encoded</b>. Return 0 for
176 * success, -1 otherwise. */
177 static int
178 rend_encode_v2_intro_points(char **encoded, rend_service_descriptor_t *desc)
180 size_t unenc_len;
181 char *unenc = NULL;
182 size_t unenc_written = 0;
183 int i;
184 int r = -1;
185 /* Assemble unencrypted list of introduction points. */
186 unenc_len = smartlist_len(desc->intro_nodes) * 1000; /* too long, but ok. */
187 unenc = tor_malloc_zero(unenc_len);
188 for (i = 0; i < smartlist_len(desc->intro_nodes); i++) {
189 char id_base32[REND_INTRO_POINT_ID_LEN_BASE32 + 1];
190 char *onion_key = NULL;
191 size_t onion_key_len;
192 crypto_pk_t *intro_key;
193 char *service_key = NULL;
194 char *address = NULL;
195 size_t service_key_len;
196 int res;
197 rend_intro_point_t *intro = smartlist_get(desc->intro_nodes, i);
198 /* Obtain extend info with introduction point details. */
199 extend_info_t *info = intro->extend_info;
200 /* Encode introduction point ID. */
201 base32_encode(id_base32, sizeof(id_base32),
202 info->identity_digest, DIGEST_LEN);
203 /* Encode onion key. */
204 if (crypto_pk_write_public_key_to_string(info->onion_key, &onion_key,
205 &onion_key_len) < 0) {
206 log_warn(LD_REND, "Could not write onion key.");
207 goto done;
209 /* Encode intro key. */
210 intro_key = intro->intro_key;
211 if (!intro_key ||
212 crypto_pk_write_public_key_to_string(intro_key, &service_key,
213 &service_key_len) < 0) {
214 log_warn(LD_REND, "Could not write intro key.");
215 tor_free(onion_key);
216 goto done;
218 /* Assemble everything for this introduction point. */
219 address = tor_addr_to_str_dup(&info->addr);
220 res = tor_snprintf(unenc + unenc_written, unenc_len - unenc_written,
221 "introduction-point %s\n"
222 "ip-address %s\n"
223 "onion-port %d\n"
224 "onion-key\n%s"
225 "service-key\n%s",
226 id_base32,
227 address,
228 info->port,
229 onion_key,
230 service_key);
231 tor_free(address);
232 tor_free(onion_key);
233 tor_free(service_key);
234 if (res < 0) {
235 log_warn(LD_REND, "Not enough space for writing introduction point "
236 "string.");
237 goto done;
239 /* Update total number of written bytes for unencrypted intro points. */
240 unenc_written += res;
242 /* Finalize unencrypted introduction points. */
243 if (unenc_len < unenc_written + 2) {
244 log_warn(LD_REND, "Not enough space for finalizing introduction point "
245 "string.");
246 goto done;
248 unenc[unenc_written++] = '\n';
249 unenc[unenc_written++] = 0;
250 *encoded = unenc;
251 r = 0;
252 done:
253 if (r<0)
254 tor_free(unenc);
255 return r;
258 /** Encrypt the encoded introduction points in <b>encoded</b> using
259 * authorization type 'basic' with <b>client_cookies</b> and write the
260 * result to a newly allocated string pointed to by <b>encrypted_out</b> of
261 * length <b>encrypted_len_out</b>. Return 0 for success, -1 otherwise. */
262 static int
263 rend_encrypt_v2_intro_points_basic(char **encrypted_out,
264 size_t *encrypted_len_out,
265 const char *encoded,
266 smartlist_t *client_cookies)
268 int r = -1, i, pos, enclen, client_blocks;
269 size_t len, client_entries_len;
270 char *enc = NULL, iv[CIPHER_IV_LEN], *client_part = NULL,
271 session_key[CIPHER_KEY_LEN];
272 smartlist_t *encrypted_session_keys = NULL;
273 crypto_digest_t *digest;
274 crypto_cipher_t *cipher;
275 tor_assert(encoded);
276 tor_assert(client_cookies && smartlist_len(client_cookies) > 0);
278 /* Generate session key. */
279 crypto_rand(session_key, CIPHER_KEY_LEN);
281 /* Determine length of encrypted introduction points including session
282 * keys. */
283 client_blocks = 1 + ((smartlist_len(client_cookies) - 1) /
284 REND_BASIC_AUTH_CLIENT_MULTIPLE);
285 client_entries_len = client_blocks * REND_BASIC_AUTH_CLIENT_MULTIPLE *
286 REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
287 len = 2 + client_entries_len + CIPHER_IV_LEN + strlen(encoded);
288 if (client_blocks >= 256) {
289 log_warn(LD_REND, "Too many clients in introduction point string.");
290 goto done;
292 enc = tor_malloc_zero(len);
293 enc[0] = 0x01; /* type of authorization. */
294 enc[1] = (uint8_t)client_blocks;
296 /* Encrypt with random session key. */
297 enclen = crypto_cipher_encrypt_with_iv(session_key,
298 enc + 2 + client_entries_len,
299 CIPHER_IV_LEN + strlen(encoded), encoded, strlen(encoded));
301 if (enclen < 0) {
302 log_warn(LD_REND, "Could not encrypt introduction point string.");
303 goto done;
305 memcpy(iv, enc + 2 + client_entries_len, CIPHER_IV_LEN);
307 /* Encrypt session key for cookies, determine client IDs, and put both
308 * in a smartlist. */
309 encrypted_session_keys = smartlist_new();
310 SMARTLIST_FOREACH_BEGIN(client_cookies, const char *, cookie) {
311 client_part = tor_malloc_zero(REND_BASIC_AUTH_CLIENT_ENTRY_LEN);
312 /* Encrypt session key. */
313 cipher = crypto_cipher_new(cookie);
314 if (crypto_cipher_encrypt(cipher, client_part +
315 REND_BASIC_AUTH_CLIENT_ID_LEN,
316 session_key, CIPHER_KEY_LEN) < 0) {
317 log_warn(LD_REND, "Could not encrypt session key for client.");
318 crypto_cipher_free(cipher);
319 tor_free(client_part);
320 goto done;
322 crypto_cipher_free(cipher);
324 /* Determine client ID. */
325 digest = crypto_digest_new();
326 crypto_digest_add_bytes(digest, cookie, REND_DESC_COOKIE_LEN);
327 crypto_digest_add_bytes(digest, iv, CIPHER_IV_LEN);
328 crypto_digest_get_digest(digest, client_part,
329 REND_BASIC_AUTH_CLIENT_ID_LEN);
330 crypto_digest_free(digest);
332 /* Put both together. */
333 smartlist_add(encrypted_session_keys, client_part);
334 } SMARTLIST_FOREACH_END(cookie);
336 /* Add some fake client IDs and encrypted session keys. */
337 for (i = (smartlist_len(client_cookies) - 1) %
338 REND_BASIC_AUTH_CLIENT_MULTIPLE;
339 i < REND_BASIC_AUTH_CLIENT_MULTIPLE - 1; i++) {
340 client_part = tor_malloc_zero(REND_BASIC_AUTH_CLIENT_ENTRY_LEN);
341 crypto_rand(client_part, REND_BASIC_AUTH_CLIENT_ENTRY_LEN);
342 smartlist_add(encrypted_session_keys, client_part);
344 /* Sort smartlist and put elements in result in order. */
345 smartlist_sort_digests(encrypted_session_keys);
346 pos = 2;
347 SMARTLIST_FOREACH(encrypted_session_keys, const char *, entry, {
348 memcpy(enc + pos, entry, REND_BASIC_AUTH_CLIENT_ENTRY_LEN);
349 pos += REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
351 *encrypted_out = enc;
352 *encrypted_len_out = len;
353 enc = NULL; /* prevent free. */
354 r = 0;
355 done:
356 tor_free(enc);
357 if (encrypted_session_keys) {
358 SMARTLIST_FOREACH(encrypted_session_keys, char *, d, tor_free(d););
359 smartlist_free(encrypted_session_keys);
361 return r;
364 /** Encrypt the encoded introduction points in <b>encoded</b> using
365 * authorization type 'stealth' with <b>descriptor_cookie</b> of length
366 * REND_DESC_COOKIE_LEN and write the result to a newly allocated string
367 * pointed to by <b>encrypted_out</b> of length <b>encrypted_len_out</b>.
368 * Return 0 for success, -1 otherwise. */
369 static int
370 rend_encrypt_v2_intro_points_stealth(char **encrypted_out,
371 size_t *encrypted_len_out,
372 const char *encoded,
373 const char *descriptor_cookie)
375 int r = -1, enclen;
376 char *enc;
377 tor_assert(encoded);
378 tor_assert(descriptor_cookie);
380 enc = tor_malloc_zero(1 + CIPHER_IV_LEN + strlen(encoded));
381 enc[0] = 0x02; /* Auth type */
382 enclen = crypto_cipher_encrypt_with_iv(descriptor_cookie,
383 enc + 1,
384 CIPHER_IV_LEN+strlen(encoded),
385 encoded, strlen(encoded));
386 if (enclen < 0) {
387 log_warn(LD_REND, "Could not encrypt introduction point string.");
388 goto done;
390 *encrypted_out = enc;
391 *encrypted_len_out = enclen;
392 enc = NULL; /* prevent free */
393 r = 0;
394 done:
395 tor_free(enc);
396 return r;
399 /** Attempt to parse the given <b>desc_str</b> and return true if this
400 * succeeds, false otherwise. */
401 STATIC int
402 rend_desc_v2_is_parsable(rend_encoded_v2_service_descriptor_t *desc)
404 rend_service_descriptor_t *test_parsed = NULL;
405 char test_desc_id[DIGEST_LEN];
406 char *test_intro_content = NULL;
407 size_t test_intro_size;
408 size_t test_encoded_size;
409 const char *test_next;
410 int res = rend_parse_v2_service_descriptor(&test_parsed, test_desc_id,
411 &test_intro_content,
412 &test_intro_size,
413 &test_encoded_size,
414 &test_next, desc->desc_str, 1);
415 rend_service_descriptor_free(test_parsed);
416 tor_free(test_intro_content);
417 return (res >= 0);
420 /** Free the storage held by an encoded v2 service descriptor. */
421 void
422 rend_encoded_v2_service_descriptor_free(
423 rend_encoded_v2_service_descriptor_t *desc)
425 if (!desc)
426 return;
427 tor_free(desc->desc_str);
428 tor_free(desc);
431 /** Free the storage held by an introduction point info. */
432 void
433 rend_intro_point_free(rend_intro_point_t *intro)
435 if (!intro)
436 return;
438 extend_info_free(intro->extend_info);
439 crypto_pk_free(intro->intro_key);
441 if (intro->accepted_intro_rsa_parts != NULL) {
442 replaycache_free(intro->accepted_intro_rsa_parts);
445 tor_free(intro);
448 /** Encode a set of rend_encoded_v2_service_descriptor_t's for <b>desc</b>
449 * at time <b>now</b> using <b>service_key</b>, depending on
450 * <b>auth_type</b> a <b>descriptor_cookie</b> and a list of
451 * <b>client_cookies</b> (which are both <b>NULL</b> if no client
452 * authorization is performed), and <b>period</b> (e.g. 0 for the current
453 * period, 1 for the next period, etc.) and add them to the existing list
454 * <b>descs_out</b>; return the number of seconds that the descriptors will
455 * be found by clients, or -1 if the encoding was not successful. */
457 rend_encode_v2_descriptors(smartlist_t *descs_out,
458 rend_service_descriptor_t *desc, time_t now,
459 uint8_t period, rend_auth_type_t auth_type,
460 crypto_pk_t *client_key,
461 smartlist_t *client_cookies)
463 char service_id[DIGEST_LEN];
464 char service_id_base32[REND_SERVICE_ID_LEN_BASE32+1];
465 uint32_t time_period;
466 char *ipos_base64 = NULL, *ipos = NULL, *ipos_encrypted = NULL,
467 *descriptor_cookie = NULL;
468 size_t ipos_len = 0, ipos_encrypted_len = 0;
469 int k;
470 uint32_t seconds_valid;
471 crypto_pk_t *service_key;
472 if (!desc) {
473 log_warn(LD_BUG, "Could not encode v2 descriptor: No desc given.");
474 return -1;
476 service_key = (auth_type == REND_STEALTH_AUTH) ? client_key : desc->pk;
477 tor_assert(service_key);
478 if (auth_type == REND_STEALTH_AUTH) {
479 descriptor_cookie = smartlist_get(client_cookies, 0);
480 tor_assert(descriptor_cookie);
482 /* Obtain service_id from public key. */
483 if (crypto_pk_get_digest(service_key, service_id) < 0) {
484 log_warn(LD_BUG, "Couldn't compute service key digest.");
485 return -1;
487 /* Calculate current time-period. */
488 time_period = get_time_period(now, period, service_id);
489 /* Determine how many seconds the descriptor will be valid. */
490 seconds_valid = period * REND_TIME_PERIOD_V2_DESC_VALIDITY +
491 get_seconds_valid(now, service_id);
492 /* Assemble, possibly encrypt, and encode introduction points. */
493 if (smartlist_len(desc->intro_nodes) > 0) {
494 if (rend_encode_v2_intro_points(&ipos, desc) < 0) {
495 log_warn(LD_REND, "Encoding of introduction points did not succeed.");
496 return -1;
498 switch (auth_type) {
499 case REND_NO_AUTH:
500 ipos_len = strlen(ipos);
501 break;
502 case REND_BASIC_AUTH:
503 if (rend_encrypt_v2_intro_points_basic(&ipos_encrypted,
504 &ipos_encrypted_len, ipos,
505 client_cookies) < 0) {
506 log_warn(LD_REND, "Encrypting of introduction points did not "
507 "succeed.");
508 tor_free(ipos);
509 return -1;
511 tor_free(ipos);
512 ipos = ipos_encrypted;
513 ipos_len = ipos_encrypted_len;
514 break;
515 case REND_STEALTH_AUTH:
516 if (rend_encrypt_v2_intro_points_stealth(&ipos_encrypted,
517 &ipos_encrypted_len, ipos,
518 descriptor_cookie) < 0) {
519 log_warn(LD_REND, "Encrypting of introduction points did not "
520 "succeed.");
521 tor_free(ipos);
522 return -1;
524 tor_free(ipos);
525 ipos = ipos_encrypted;
526 ipos_len = ipos_encrypted_len;
527 break;
528 default:
529 log_warn(LD_REND|LD_BUG, "Unrecognized authorization type %d",
530 (int)auth_type);
531 tor_free(ipos);
532 return -1;
534 /* Base64-encode introduction points. */
535 ipos_base64 = tor_calloc(ipos_len, 2);
536 if (base64_encode(ipos_base64, ipos_len * 2, ipos, ipos_len,
537 BASE64_ENCODE_MULTILINE)<0) {
538 log_warn(LD_REND, "Could not encode introduction point string to "
539 "base64. length=%d", (int)ipos_len);
540 tor_free(ipos_base64);
541 tor_free(ipos);
542 return -1;
544 tor_free(ipos);
546 /* Encode REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS descriptors. */
547 for (k = 0; k < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; k++) {
548 char secret_id_part[DIGEST_LEN];
549 char secret_id_part_base32[REND_SECRET_ID_PART_LEN_BASE32 + 1];
550 char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
551 char *permanent_key = NULL;
552 size_t permanent_key_len;
553 char published[ISO_TIME_LEN+1];
554 int i;
555 char protocol_versions_string[16]; /* max len: "0,1,2,3,4,5,6,7\0" */
556 size_t protocol_versions_written;
557 size_t desc_len;
558 char *desc_str = NULL;
559 int result = 0;
560 size_t written = 0;
561 char desc_digest[DIGEST_LEN];
562 rend_encoded_v2_service_descriptor_t *enc =
563 tor_malloc_zero(sizeof(rend_encoded_v2_service_descriptor_t));
564 /* Calculate secret-id-part = h(time-period | cookie | replica). */
565 get_secret_id_part_bytes(secret_id_part, time_period, descriptor_cookie,
567 base32_encode(secret_id_part_base32, sizeof(secret_id_part_base32),
568 secret_id_part, DIGEST_LEN);
569 /* Calculate descriptor ID. */
570 rend_get_descriptor_id_bytes(enc->desc_id, service_id, secret_id_part);
571 base32_encode(desc_id_base32, sizeof(desc_id_base32),
572 enc->desc_id, DIGEST_LEN);
573 /* PEM-encode the public key */
574 if (crypto_pk_write_public_key_to_string(service_key, &permanent_key,
575 &permanent_key_len) < 0) {
576 log_warn(LD_BUG, "Could not write public key to string.");
577 rend_encoded_v2_service_descriptor_free(enc);
578 goto err;
580 /* Encode timestamp. */
581 format_iso_time(published, desc->timestamp);
582 /* Write protocol-versions bitmask to comma-separated value string. */
583 protocol_versions_written = 0;
584 for (i = 0; i < 8; i++) {
585 if (desc->protocols & 1 << i) {
586 tor_snprintf(protocol_versions_string + protocol_versions_written,
587 16 - protocol_versions_written, "%d,", i);
588 protocol_versions_written += 2;
591 if (protocol_versions_written)
592 protocol_versions_string[protocol_versions_written - 1] = '\0';
593 else
594 protocol_versions_string[0]= '\0';
595 /* Assemble complete descriptor. */
596 desc_len = 2000 + smartlist_len(desc->intro_nodes) * 1000; /* far too long,
597 but okay.*/
598 enc->desc_str = desc_str = tor_malloc_zero(desc_len);
599 result = tor_snprintf(desc_str, desc_len,
600 "rendezvous-service-descriptor %s\n"
601 "version 2\n"
602 "permanent-key\n%s"
603 "secret-id-part %s\n"
604 "publication-time %s\n"
605 "protocol-versions %s\n",
606 desc_id_base32,
607 permanent_key,
608 secret_id_part_base32,
609 published,
610 protocol_versions_string);
611 tor_free(permanent_key);
612 if (result < 0) {
613 log_warn(LD_BUG, "Descriptor ran out of room.");
614 rend_encoded_v2_service_descriptor_free(enc);
615 goto err;
617 written = result;
618 /* Add introduction points. */
619 if (ipos_base64) {
620 result = tor_snprintf(desc_str + written, desc_len - written,
621 "introduction-points\n"
622 "-----BEGIN MESSAGE-----\n%s"
623 "-----END MESSAGE-----\n",
624 ipos_base64);
625 if (result < 0) {
626 log_warn(LD_BUG, "could not write introduction points.");
627 rend_encoded_v2_service_descriptor_free(enc);
628 goto err;
630 written += result;
632 /* Add signature. */
633 strlcpy(desc_str + written, "signature\n", desc_len - written);
634 written += strlen(desc_str + written);
635 if (crypto_digest(desc_digest, desc_str, written) < 0) {
636 log_warn(LD_BUG, "could not create digest.");
637 rend_encoded_v2_service_descriptor_free(enc);
638 goto err;
640 if (router_append_dirobj_signature(desc_str + written,
641 desc_len - written,
642 desc_digest, DIGEST_LEN,
643 service_key) < 0) {
644 log_warn(LD_BUG, "Couldn't sign desc.");
645 rend_encoded_v2_service_descriptor_free(enc);
646 goto err;
648 written += strlen(desc_str+written);
649 if (written+2 > desc_len) {
650 log_warn(LD_BUG, "Could not finish desc.");
651 rend_encoded_v2_service_descriptor_free(enc);
652 goto err;
654 desc_str[written++] = 0;
655 /* Check if we can parse our own descriptor. */
656 if (!rend_desc_v2_is_parsable(enc)) {
657 log_warn(LD_BUG, "Could not parse my own descriptor: %s", desc_str);
658 rend_encoded_v2_service_descriptor_free(enc);
659 goto err;
661 smartlist_add(descs_out, enc);
662 /* Add the uploaded descriptor to the local service's descriptor cache */
663 rend_cache_store_v2_desc_as_service(enc->desc_str);
664 base32_encode(service_id_base32, sizeof(service_id_base32),
665 service_id, REND_SERVICE_ID_LEN);
666 control_event_hs_descriptor_created(service_id_base32, desc_id_base32, k);
669 log_info(LD_REND, "Successfully encoded a v2 descriptor and "
670 "confirmed that it is parsable.");
671 goto done;
673 err:
674 SMARTLIST_FOREACH(descs_out, rend_encoded_v2_service_descriptor_t *, d,
675 rend_encoded_v2_service_descriptor_free(d););
676 smartlist_clear(descs_out);
677 seconds_valid = -1;
679 done:
680 tor_free(ipos_base64);
681 return seconds_valid;
684 /** Sets <b>out</b> to the first 10 bytes of the digest of <b>pk</b>,
685 * base32 encoded. NUL-terminates out. (We use this string to
686 * identify services in directory requests and .onion URLs.)
689 rend_get_service_id(crypto_pk_t *pk, char *out)
691 char buf[DIGEST_LEN];
692 tor_assert(pk);
693 if (crypto_pk_get_digest(pk, buf) < 0)
694 return -1;
695 base32_encode(out, REND_SERVICE_ID_LEN_BASE32+1, buf, REND_SERVICE_ID_LEN);
696 return 0;
699 /** Return true iff <b>query</b> is a syntactically valid service ID (as
700 * generated by rend_get_service_id). */
702 rend_valid_v2_service_id(const char *query)
704 if (strlen(query) != REND_SERVICE_ID_LEN_BASE32)
705 return 0;
707 if (strspn(query, BASE32_CHARS) != REND_SERVICE_ID_LEN_BASE32)
708 return 0;
710 return 1;
713 /** Return true iff <b>query</b> is a syntactically valid descriptor ID.
714 * (as generated by rend_get_descriptor_id_bytes). */
716 rend_valid_descriptor_id(const char *query)
718 if (strlen(query) != REND_DESC_ID_V2_LEN_BASE32) {
719 goto invalid;
721 if (strspn(query, BASE32_CHARS) != REND_DESC_ID_V2_LEN_BASE32) {
722 goto invalid;
725 return 1;
727 invalid:
728 return 0;
731 /** Return true iff <b>client_name</b> is a syntactically valid name
732 * for rendezvous client authentication. */
734 rend_valid_client_name(const char *client_name)
736 size_t len = strlen(client_name);
737 if (len < 1 || len > REND_CLIENTNAME_MAX_LEN) {
738 return 0;
740 if (strspn(client_name, REND_LEGAL_CLIENTNAME_CHARACTERS) != len) {
741 return 0;
744 return 1;
747 /** Called when we get a rendezvous-related relay cell on circuit
748 * <b>circ</b>. Dispatch on rendezvous relay command. */
749 void
750 rend_process_relay_cell(circuit_t *circ, const crypt_path_t *layer_hint,
751 int command, size_t length,
752 const uint8_t *payload)
754 or_circuit_t *or_circ = NULL;
755 origin_circuit_t *origin_circ = NULL;
756 int r = -2;
757 if (CIRCUIT_IS_ORIGIN(circ)) {
758 origin_circ = TO_ORIGIN_CIRCUIT(circ);
759 if (!layer_hint || layer_hint != origin_circ->cpath->prev) {
760 log_fn(LOG_PROTOCOL_WARN, LD_APP,
761 "Relay cell (rend purpose %d) from wrong hop on origin circ",
762 command);
763 origin_circ = NULL;
765 } else {
766 or_circ = TO_OR_CIRCUIT(circ);
769 switch (command) {
770 case RELAY_COMMAND_ESTABLISH_INTRO:
771 if (or_circ)
772 r = hs_intro_received_establish_intro(or_circ,payload,length);
773 break;
774 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
775 if (or_circ)
776 r = rend_mid_establish_rendezvous(or_circ,payload,length);
777 break;
778 case RELAY_COMMAND_INTRODUCE1:
779 if (or_circ)
780 r = hs_intro_received_introduce1(or_circ,payload,length);
781 break;
782 case RELAY_COMMAND_INTRODUCE2:
783 if (origin_circ)
784 r = hs_service_receive_introduce2(origin_circ,payload,length);
785 break;
786 case RELAY_COMMAND_INTRODUCE_ACK:
787 if (origin_circ)
788 r = hs_client_receive_introduce_ack(origin_circ,payload,length);
789 break;
790 case RELAY_COMMAND_RENDEZVOUS1:
791 if (or_circ)
792 r = rend_mid_rendezvous(or_circ,payload,length);
793 break;
794 case RELAY_COMMAND_RENDEZVOUS2:
795 if (origin_circ)
796 r = hs_client_receive_rendezvous2(origin_circ,payload,length);
797 break;
798 case RELAY_COMMAND_INTRO_ESTABLISHED:
799 if (origin_circ)
800 r = hs_service_receive_intro_established(origin_circ,payload,length);
801 break;
802 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
803 if (origin_circ)
804 r = hs_client_receive_rendezvous_acked(origin_circ,payload,length);
805 break;
806 default:
807 tor_fragile_assert();
810 if (r == -2)
811 log_info(LD_PROTOCOL, "Dropping cell (type %d) for wrong circuit type.",
812 command);
815 /** Determine the routers that are responsible for <b>id</b> (binary) and
816 * add pointers to those routers' routerstatus_t to <b>responsible_dirs</b>.
817 * Return -1 if we're returning an empty smartlist, else return 0.
820 hid_serv_get_responsible_directories(smartlist_t *responsible_dirs,
821 const char *id)
823 int start, found, n_added = 0, i;
824 networkstatus_t *c = networkstatus_get_latest_consensus();
825 if (!c || !smartlist_len(c->routerstatus_list)) {
826 log_warn(LD_REND, "We don't have a consensus, so we can't perform v2 "
827 "rendezvous operations.");
828 return -1;
830 tor_assert(id);
831 start = networkstatus_vote_find_entry_idx(c, id, &found);
832 if (start == smartlist_len(c->routerstatus_list)) start = 0;
833 i = start;
834 do {
835 routerstatus_t *r = smartlist_get(c->routerstatus_list, i);
836 if (r->is_hs_dir) {
837 smartlist_add(responsible_dirs, r);
838 if (++n_added == REND_NUMBER_OF_CONSECUTIVE_REPLICAS)
839 return 0;
841 if (++i == smartlist_len(c->routerstatus_list))
842 i = 0;
843 } while (i != start);
845 /* Even though we don't have the desired number of hidden service
846 * directories, be happy if we got any. */
847 return smartlist_len(responsible_dirs) ? 0 : -1;
850 /* Length of the 'extended' auth cookie used to encode auth type before
851 * base64 encoding. */
852 #define REND_DESC_COOKIE_LEN_EXT (REND_DESC_COOKIE_LEN + 1)
853 /* Length of the zero-padded auth cookie when base64 encoded. These two
854 * padding bytes always (A=) are stripped off of the returned cookie. */
855 #define REND_DESC_COOKIE_LEN_EXT_BASE64 (REND_DESC_COOKIE_LEN_BASE64 + 2)
857 /** Encode a client authorization descriptor cookie.
858 * The result of this function is suitable for use in the HidServAuth
859 * option. The trailing padding characters are removed, and the
860 * auth type is encoded into the cookie.
862 * Returns a new base64-encoded cookie. This function cannot fail.
863 * The caller is responsible for freeing the returned value.
865 char *
866 rend_auth_encode_cookie(const uint8_t *cookie_in, rend_auth_type_t auth_type)
868 uint8_t extended_cookie[REND_DESC_COOKIE_LEN_EXT];
869 char *cookie_out = tor_malloc_zero(REND_DESC_COOKIE_LEN_EXT_BASE64 + 1);
870 int re;
872 tor_assert(cookie_in);
874 memcpy(extended_cookie, cookie_in, REND_DESC_COOKIE_LEN);
875 extended_cookie[REND_DESC_COOKIE_LEN] = ((int)auth_type - 1) << 4;
876 re = base64_encode(cookie_out, REND_DESC_COOKIE_LEN_EXT_BASE64 + 1,
877 (const char *) extended_cookie, REND_DESC_COOKIE_LEN_EXT,
879 tor_assert(re == REND_DESC_COOKIE_LEN_EXT_BASE64);
881 /* Remove the trailing 'A='. Auth type is encoded in the high bits
882 * of the last byte, so the last base64 character will always be zero
883 * (A). This is subtly different behavior from base64_encode_nopad. */
884 cookie_out[REND_DESC_COOKIE_LEN_BASE64] = '\0';
885 memwipe(extended_cookie, 0, sizeof(extended_cookie));
886 return cookie_out;
889 /** Decode a base64-encoded client authorization descriptor cookie.
890 * The descriptor_cookie can be truncated to REND_DESC_COOKIE_LEN_BASE64
891 * characters (as given to clients), or may include the two padding
892 * characters (as stored by the service).
894 * The result is stored in REND_DESC_COOKIE_LEN bytes of cookie_out.
895 * The rend_auth_type_t decoded from the cookie is stored in the
896 * optional auth_type_out parameter.
898 * Return 0 on success, or -1 on error. The caller is responsible for
899 * freeing the returned err_msg.
902 rend_auth_decode_cookie(const char *cookie_in, uint8_t *cookie_out,
903 rend_auth_type_t *auth_type_out, char **err_msg_out)
905 uint8_t descriptor_cookie_decoded[REND_DESC_COOKIE_LEN_EXT + 1] = { 0 };
906 char descriptor_cookie_base64ext[REND_DESC_COOKIE_LEN_EXT_BASE64 + 1];
907 const char *descriptor_cookie = cookie_in;
908 char *err_msg = NULL;
909 int auth_type_val = 0;
910 int res = -1;
911 int decoded_len;
913 size_t len = strlen(descriptor_cookie);
914 if (len == REND_DESC_COOKIE_LEN_BASE64) {
915 /* Add a trailing zero byte to make base64-decoding happy. */
916 tor_snprintf(descriptor_cookie_base64ext,
917 sizeof(descriptor_cookie_base64ext),
918 "%sA=", descriptor_cookie);
919 descriptor_cookie = descriptor_cookie_base64ext;
920 } else if (len != REND_DESC_COOKIE_LEN_EXT_BASE64) {
921 tor_asprintf(&err_msg, "Authorization cookie has wrong length: %s",
922 escaped(cookie_in));
923 goto err;
926 decoded_len = base64_decode((char *) descriptor_cookie_decoded,
927 sizeof(descriptor_cookie_decoded),
928 descriptor_cookie,
929 REND_DESC_COOKIE_LEN_EXT_BASE64);
930 if (decoded_len != REND_DESC_COOKIE_LEN &&
931 decoded_len != REND_DESC_COOKIE_LEN_EXT) {
932 tor_asprintf(&err_msg, "Authorization cookie has invalid characters: %s",
933 escaped(cookie_in));
934 goto err;
937 if (auth_type_out) {
938 auth_type_val = (descriptor_cookie_decoded[REND_DESC_COOKIE_LEN] >> 4) + 1;
939 if (auth_type_val < 1 || auth_type_val > 2) {
940 tor_asprintf(&err_msg, "Authorization cookie type is unknown: %s",
941 escaped(cookie_in));
942 goto err;
944 *auth_type_out = auth_type_val == 1 ? REND_BASIC_AUTH : REND_STEALTH_AUTH;
947 memcpy(cookie_out, descriptor_cookie_decoded, REND_DESC_COOKIE_LEN);
948 res = 0;
949 err:
950 if (err_msg_out) {
951 *err_msg_out = err_msg;
952 } else {
953 tor_free(err_msg);
955 memwipe(descriptor_cookie_decoded, 0, sizeof(descriptor_cookie_decoded));
956 memwipe(descriptor_cookie_base64ext, 0, sizeof(descriptor_cookie_base64ext));
957 return res;
960 /* Is this a rend client or server that allows direct (non-anonymous)
961 * connections?
962 * Clients must be specifically compiled and configured in this mode.
963 * Onion services can be configured to start in this mode.
964 * Prefer rend_client_allow_non_anonymous_connection() or
965 * rend_service_allow_non_anonymous_connection() whenever possible, so that
966 * checks are specific to Single Onion Services or Tor2web. */
968 rend_allow_non_anonymous_connection(const or_options_t* options)
970 return (rend_client_allow_non_anonymous_connection(options)
971 || rend_service_allow_non_anonymous_connection(options));
974 /* Is this a rend client or server in non-anonymous mode?
975 * Clients must be specifically compiled in this mode.
976 * Onion services can be configured to start in this mode.
977 * Prefer rend_client_non_anonymous_mode_enabled() or
978 * rend_service_non_anonymous_mode_enabled() whenever possible, so that checks
979 * are specific to Single Onion Services or Tor2web. */
981 rend_non_anonymous_mode_enabled(const or_options_t *options)
983 return (rend_client_non_anonymous_mode_enabled(options)
984 || rend_service_non_anonymous_mode_enabled(options));
987 /* Make sure that tor only builds one-hop circuits when they would not
988 * compromise user anonymity.
990 * One-hop circuits are permitted in Tor2web or Single Onion modes.
992 * Tor2web or Single Onion modes are also allowed to make multi-hop circuits.
993 * For example, single onion HSDir circuits are 3-hop to prevent denial of
994 * service.
996 void
997 assert_circ_anonymity_ok(const origin_circuit_t *circ,
998 const or_options_t *options)
1000 tor_assert(options);
1001 tor_assert(circ);
1002 tor_assert(circ->build_state);
1004 if (circ->build_state->onehop_tunnel) {
1005 tor_assert(rend_allow_non_anonymous_connection(options));
1009 /* Return 1 iff the given <b>digest</b> of a permenanent hidden service key is
1010 * equal to the digest in the origin circuit <b>ocirc</b> of its rend data .
1011 * If the rend data doesn't exist, 0 is returned. This function is agnostic to
1012 * the rend data version. */
1014 rend_circuit_pk_digest_eq(const origin_circuit_t *ocirc,
1015 const uint8_t *digest)
1017 size_t rend_pk_digest_len;
1018 const uint8_t *rend_pk_digest;
1020 tor_assert(ocirc);
1021 tor_assert(digest);
1023 if (ocirc->rend_data == NULL) {
1024 goto no_match;
1027 rend_pk_digest = rend_data_get_pk_digest(ocirc->rend_data,
1028 &rend_pk_digest_len);
1029 if (tor_memeq(rend_pk_digest, digest, rend_pk_digest_len)) {
1030 goto match;
1032 no_match:
1033 return 0;
1034 match:
1035 return 1;