Tor  0.4.5.0-alpha-dev
hs_descriptor.c
Go to the documentation of this file.
1 /* Copyright (c) 2016-2020, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
3 
4 /**
5  * \file hs_descriptor.c
6  * \brief Handle hidden service descriptor encoding/decoding.
7  *
8  * \details
9  * Here is a graphical depiction of an HS descriptor and its layers:
10  *
11  * +------------------------------------------------------+
12  * |DESCRIPTOR HEADER: |
13  * | hs-descriptor 3 |
14  * | descriptor-lifetime 180 |
15  * | ... |
16  * | superencrypted |
17  * |+---------------------------------------------------+ |
18  * ||SUPERENCRYPTED LAYER (aka OUTER ENCRYPTED LAYER): | |
19  * || desc-auth-type x25519 | |
20  * || desc-auth-ephemeral-key | |
21  * || auth-client | |
22  * || auth-client | |
23  * || ... | |
24  * || encrypted | |
25  * ||+-------------------------------------------------+| |
26  * |||ENCRYPTED LAYER (aka INNER ENCRYPTED LAYER): || |
27  * ||| create2-formats || |
28  * ||| intro-auth-required || |
29  * ||| introduction-point || |
30  * ||| introduction-point || |
31  * ||| ... || |
32  * ||+-------------------------------------------------+| |
33  * |+---------------------------------------------------+ |
34  * +------------------------------------------------------+
35  *
36  * The DESCRIPTOR HEADER section is completely unencrypted and contains generic
37  * descriptor metadata.
38  *
39  * The SUPERENCRYPTED LAYER section is the first layer of encryption, and it's
40  * encrypted using the blinded public key of the hidden service to protect
41  * against entities who don't know its onion address. The clients of the hidden
42  * service know its onion address and blinded public key, whereas third-parties
43  * (like HSDirs) don't know it (except if it's a public hidden service).
44  *
45  * The ENCRYPTED LAYER section is the second layer of encryption, and it's
46  * encrypted using the client authorization key material (if those exist). When
47  * client authorization is enabled, this second layer of encryption protects
48  * the descriptor content from unauthorized entities. If client authorization
49  * is disabled, this second layer of encryption does not provide any extra
50  * security but is still present. The plaintext of this layer contains all the
51  * information required to connect to the hidden service like its list of
52  * introduction points.
53  **/
54 
55 /* For unit tests.*/
56 #define HS_DESCRIPTOR_PRIVATE
57 
58 #include <stdbool.h>
59 #include "core/or/or.h"
60 #include "app/config/config.h"
61 #include "trunnel/ed25519_cert.h" /* Trunnel interface. */
63 #include "core/or/circuitbuild.h"
67 #include "feature/rend/rendcache.h"
68 #include "feature/hs/hs_cache.h"
69 #include "feature/hs/hs_config.h"
70 #include "feature/nodelist/torcert.h" /* tor_cert_encode_ed22519() */
71 #include "lib/memarea/memarea.h"
73 
74 #include "core/or/extend_info_st.h"
75 
76 /* Constant string value used for the descriptor format. */
77 #define str_hs_desc "hs-descriptor"
78 #define str_desc_cert "descriptor-signing-key-cert"
79 #define str_rev_counter "revision-counter"
80 #define str_superencrypted "superencrypted"
81 #define str_encrypted "encrypted"
82 #define str_signature "signature"
83 #define str_lifetime "descriptor-lifetime"
84 /* Constant string value for the encrypted part of the descriptor. */
85 #define str_create2_formats "create2-formats"
86 #define str_intro_auth_required "intro-auth-required"
87 #define str_single_onion "single-onion-service"
88 #define str_intro_point "introduction-point"
89 #define str_ip_onion_key "onion-key"
90 #define str_ip_auth_key "auth-key"
91 #define str_ip_enc_key "enc-key"
92 #define str_ip_enc_key_cert "enc-key-cert"
93 #define str_ip_legacy_key "legacy-key"
94 #define str_ip_legacy_key_cert "legacy-key-cert"
95 #define str_intro_point_start "\n" str_intro_point " "
96 /* Constant string value for the construction to encrypt the encrypted data
97  * section. */
98 #define str_enc_const_superencryption "hsdir-superencrypted-data"
99 #define str_enc_const_encryption "hsdir-encrypted-data"
100 /* Prefix required to compute/verify HS desc signatures */
101 #define str_desc_sig_prefix "Tor onion service descriptor sig v3"
102 #define str_desc_auth_type "desc-auth-type"
103 #define str_desc_auth_key "desc-auth-ephemeral-key"
104 #define str_desc_auth_client "auth-client"
105 #define str_encrypted "encrypted"
106 
107 /** Authentication supported types. */
108 static const struct {
109  hs_desc_auth_type_t type;
110  const char *identifier;
111 } intro_auth_types[] = {
112  { HS_DESC_AUTH_ED25519, "ed25519" },
113  /* Indicate end of array. */
114  { 0, NULL }
115 };
116 
117 /** Descriptor ruleset. */
119  T1_START(str_hs_desc, R_HS_DESCRIPTOR, EQ(1), NO_OBJ),
120  T1(str_lifetime, R3_DESC_LIFETIME, EQ(1), NO_OBJ),
121  T1(str_desc_cert, R3_DESC_SIGNING_CERT, NO_ARGS, NEED_OBJ),
122  T1(str_rev_counter, R3_REVISION_COUNTER, EQ(1), NO_OBJ),
123  T1(str_superencrypted, R3_SUPERENCRYPTED, NO_ARGS, NEED_OBJ),
124  T1_END(str_signature, R3_SIGNATURE, EQ(1), NO_OBJ),
126 };
127 
128 /** Descriptor ruleset for the superencrypted section. */
130  T1_START(str_desc_auth_type, R3_DESC_AUTH_TYPE, GE(1), NO_OBJ),
131  T1(str_desc_auth_key, R3_DESC_AUTH_KEY, GE(1), NO_OBJ),
132  T1N(str_desc_auth_client, R3_DESC_AUTH_CLIENT, GE(3), NO_OBJ),
133  T1(str_encrypted, R3_ENCRYPTED, NO_ARGS, NEED_OBJ),
135 };
136 
137 /** Descriptor ruleset for the encrypted section. */
139  T1_START(str_create2_formats, R3_CREATE2_FORMATS, CONCAT_ARGS, NO_OBJ),
140  T01(str_intro_auth_required, R3_INTRO_AUTH_REQUIRED, ARGS, NO_OBJ),
141  T01(str_single_onion, R3_SINGLE_ONION_SERVICE, ARGS, NO_OBJ),
143 };
144 
145 /** Descriptor ruleset for the introduction points section. */
147  T1_START(str_intro_point, R3_INTRODUCTION_POINT, EQ(1), NO_OBJ),
148  T1N(str_ip_onion_key, R3_INTRO_ONION_KEY, GE(2), OBJ_OK),
149  T1(str_ip_auth_key, R3_INTRO_AUTH_KEY, NO_ARGS, NEED_OBJ),
150  T1(str_ip_enc_key, R3_INTRO_ENC_KEY, GE(2), OBJ_OK),
151  T1(str_ip_enc_key_cert, R3_INTRO_ENC_KEY_CERT, ARGS, OBJ_OK),
152  T01(str_ip_legacy_key, R3_INTRO_LEGACY_KEY, ARGS, NEED_KEY_1024),
153  T01(str_ip_legacy_key_cert, R3_INTRO_LEGACY_KEY_CERT, ARGS, OBJ_OK),
155 };
156 
157 /** Using a key, salt and encrypted payload, build a MAC and put it in mac_out.
158  * We use SHA3-256 for the MAC computation.
159  * This function can't fail. */
160 static void
161 build_mac(const uint8_t *mac_key, size_t mac_key_len,
162  const uint8_t *salt, size_t salt_len,
163  const uint8_t *encrypted, size_t encrypted_len,
164  uint8_t *mac_out, size_t mac_len)
165 {
166  crypto_digest_t *digest;
167 
168  const uint64_t mac_len_netorder = tor_htonll(mac_key_len);
169  const uint64_t salt_len_netorder = tor_htonll(salt_len);
170 
171  tor_assert(mac_key);
172  tor_assert(salt);
173  tor_assert(encrypted);
174  tor_assert(mac_out);
175 
176  digest = crypto_digest256_new(DIGEST_SHA3_256);
177  /* As specified in section 2.5 of proposal 224, first add the mac key
178  * then add the salt first and then the encrypted section. */
179 
180  crypto_digest_add_bytes(digest, (const char *) &mac_len_netorder, 8);
181  crypto_digest_add_bytes(digest, (const char *) mac_key, mac_key_len);
182  crypto_digest_add_bytes(digest, (const char *) &salt_len_netorder, 8);
183  crypto_digest_add_bytes(digest, (const char *) salt, salt_len);
184  crypto_digest_add_bytes(digest, (const char *) encrypted, encrypted_len);
185  crypto_digest_get_digest(digest, (char *) mac_out, mac_len);
186  crypto_digest_free(digest);
187 }
188 
189 /** Using a secret data and a given decriptor object, build the secret
190  * input needed for the KDF.
191  *
192  * secret_input = SECRET_DATA | subcredential | INT_8(revision_counter)
193  *
194  * Then, set the newly allocated buffer in secret_input_out and return the
195  * length of the buffer. */
196 static size_t
198  const uint8_t *secret_data,
199  size_t secret_data_len,
200  uint8_t **secret_input_out)
201 {
202  size_t offset = 0;
203  size_t secret_input_len = secret_data_len + DIGEST256_LEN + sizeof(uint64_t);
204  uint8_t *secret_input = NULL;
205 
206  tor_assert(desc);
207  tor_assert(secret_data);
208  tor_assert(secret_input_out);
209 
210  secret_input = tor_malloc_zero(secret_input_len);
211 
212  /* Copy the secret data. */
213  memcpy(secret_input, secret_data, secret_data_len);
214  offset += secret_data_len;
215  /* Copy subcredential. */
216  memcpy(secret_input + offset, desc->subcredential.subcred, DIGEST256_LEN);
217  offset += DIGEST256_LEN;
218  /* Copy revision counter value. */
219  set_uint64(secret_input + offset,
221  offset += sizeof(uint64_t);
222  tor_assert(secret_input_len == offset);
223 
224  *secret_input_out = secret_input;
225 
226  return secret_input_len;
227 }
228 
229 /** Do the KDF construction and put the resulting data in key_out which is of
230  * key_out_len length. It uses SHAKE-256 as specified in the spec. */
231 static void
233  const uint8_t *secret_data,
234  size_t secret_data_len,
235  const uint8_t *salt, size_t salt_len,
236  uint8_t *key_out, size_t key_out_len,
237  int is_superencrypted_layer)
238 {
239  uint8_t *secret_input = NULL;
240  size_t secret_input_len;
241  crypto_xof_t *xof;
242 
243  tor_assert(desc);
244  tor_assert(secret_data);
245  tor_assert(salt);
246  tor_assert(key_out);
247 
248  /* Build the secret input for the KDF computation. */
249  secret_input_len = build_secret_input(desc, secret_data,
250  secret_data_len, &secret_input);
251 
252  xof = crypto_xof_new();
253  /* Feed our KDF. [SHAKE it like a polaroid picture --Yawning]. */
254  crypto_xof_add_bytes(xof, secret_input, secret_input_len);
255  crypto_xof_add_bytes(xof, salt, salt_len);
256 
257  /* Feed in the right string constant based on the desc layer */
258  if (is_superencrypted_layer) {
259  crypto_xof_add_bytes(xof, (const uint8_t *) str_enc_const_superencryption,
260  strlen(str_enc_const_superencryption));
261  } else {
262  crypto_xof_add_bytes(xof, (const uint8_t *) str_enc_const_encryption,
263  strlen(str_enc_const_encryption));
264  }
265 
266  /* Eat from our KDF. */
267  crypto_xof_squeeze_bytes(xof, key_out, key_out_len);
268  crypto_xof_free(xof);
269  memwipe(secret_input, 0, secret_input_len);
270 
271  tor_free(secret_input);
272 }
273 
274 /** Using the given descriptor, secret data, and salt, run it through our
275  * KDF function and then extract a secret key in key_out, the IV in iv_out
276  * and MAC in mac_out. This function can't fail. */
277 static void
279  const uint8_t *secret_data,
280  size_t secret_data_len,
281  const uint8_t *salt, size_t salt_len,
282  uint8_t *key_out, size_t key_len,
283  uint8_t *iv_out, size_t iv_len,
284  uint8_t *mac_out, size_t mac_len,
285  int is_superencrypted_layer)
286 {
287  size_t offset = 0;
288  uint8_t kdf_key[HS_DESC_ENCRYPTED_KDF_OUTPUT_LEN];
289 
290  tor_assert(desc);
291  tor_assert(secret_data);
292  tor_assert(salt);
293  tor_assert(key_out);
294  tor_assert(iv_out);
295  tor_assert(mac_out);
296 
297  build_kdf_key(desc, secret_data, secret_data_len,
298  salt, salt_len, kdf_key, sizeof(kdf_key),
299  is_superencrypted_layer);
300  /* Copy the bytes we need for both the secret key and IV. */
301  memcpy(key_out, kdf_key, key_len);
302  offset += key_len;
303  memcpy(iv_out, kdf_key + offset, iv_len);
304  offset += iv_len;
305  memcpy(mac_out, kdf_key + offset, mac_len);
306  /* Extra precaution to make sure we are not out of bound. */
307  tor_assert((offset + mac_len) == sizeof(kdf_key));
308  memwipe(kdf_key, 0, sizeof(kdf_key));
309 }
310 
311 /* === ENCODING === */
312 
313 /** Encode the given link specifier objects into a newly allocated string.
314  * This can't fail so caller can always assume a valid string being
315  * returned. */
316 STATIC char *
318 {
319  char *encoded_b64 = NULL;
320  link_specifier_list_t *lslist = link_specifier_list_new();
321 
322  tor_assert(specs);
323  /* No link specifiers is a code flow error, can't happen. */
324  tor_assert(smartlist_len(specs) > 0);
325  tor_assert(smartlist_len(specs) <= UINT8_MAX);
326 
327  link_specifier_list_set_n_spec(lslist, smartlist_len(specs));
328 
329  SMARTLIST_FOREACH_BEGIN(specs, const link_specifier_t *,
330  spec) {
331  link_specifier_t *ls = link_specifier_dup(spec);
332  tor_assert(ls);
333  link_specifier_list_add_spec(lslist, ls);
334  } SMARTLIST_FOREACH_END(spec);
335 
336  {
337  uint8_t *encoded;
338  ssize_t encoded_len, encoded_b64_len, ret;
339 
340  encoded_len = link_specifier_list_encoded_len(lslist);
341  tor_assert(encoded_len > 0);
342  encoded = tor_malloc_zero(encoded_len);
343  ret = link_specifier_list_encode(encoded, encoded_len, lslist);
344  tor_assert(ret == encoded_len);
345 
346  /* Base64 encode our binary format. Add extra NUL byte for the base64
347  * encoded value. */
348  encoded_b64_len = base64_encode_size(encoded_len, 0) + 1;
349  encoded_b64 = tor_malloc_zero(encoded_b64_len);
350  ret = base64_encode(encoded_b64, encoded_b64_len, (const char *) encoded,
351  encoded_len, 0);
352  tor_assert(ret == (encoded_b64_len - 1));
353  tor_free(encoded);
354  }
355 
356  link_specifier_list_free(lslist);
357  return encoded_b64;
358 }
359 
360 /** Encode an introduction point legacy key and certificate. Return a newly
361  * allocated string with it. On failure, return NULL. */
362 static char *
364 {
365  char *key_str, b64_cert[256], *encoded = NULL;
366  size_t key_str_len;
367 
368  tor_assert(ip);
369 
370  /* Encode cross cert. */
371  if (base64_encode(b64_cert, sizeof(b64_cert),
372  (const char *) ip->legacy.cert.encoded,
373  ip->legacy.cert.len, BASE64_ENCODE_MULTILINE) < 0) {
374  log_warn(LD_REND, "Unable to encode legacy crosscert.");
375  goto done;
376  }
377  /* Convert the encryption key to PEM format NUL terminated. */
379  &key_str_len) < 0) {
380  log_warn(LD_REND, "Unable to encode legacy encryption key.");
381  goto done;
382  }
383  tor_asprintf(&encoded,
384  "%s \n%s" /* Newline is added by the call above. */
385  "%s\n"
386  "-----BEGIN CROSSCERT-----\n"
387  "%s"
388  "-----END CROSSCERT-----",
389  str_ip_legacy_key, key_str,
390  str_ip_legacy_key_cert, b64_cert);
391  tor_free(key_str);
392 
393  done:
394  return encoded;
395 }
396 
397 /** Encode an introduction point encryption key and certificate. Return a newly
398  * allocated string with it. On failure, return NULL. */
399 static char *
401 {
402  char *encoded = NULL, *encoded_cert;
403  char key_b64[CURVE25519_BASE64_PADDED_LEN + 1];
404 
405  tor_assert(ip);
406 
407  /* Base64 encode the encryption key for the "enc-key" field. */
408  curve25519_public_to_base64(key_b64, &ip->enc_key, true);
409  if (tor_cert_encode_ed22519(ip->enc_key_cert, &encoded_cert) < 0) {
410  goto done;
411  }
412  tor_asprintf(&encoded,
413  "%s ntor %s\n"
414  "%s\n%s",
415  str_ip_enc_key, key_b64,
416  str_ip_enc_key_cert, encoded_cert);
417  tor_free(encoded_cert);
418 
419  done:
420  return encoded;
421 }
422 
423 /** Encode an introduction point onion key. Return a newly allocated string
424  * with it. Can not fail. */
425 static char *
427 {
428  char *encoded = NULL;
429  char key_b64[CURVE25519_BASE64_PADDED_LEN + 1];
430 
431  tor_assert(ip);
432 
433  /* Base64 encode the encryption key for the "onion-key" field. */
434  curve25519_public_to_base64(key_b64, &ip->onion_key, true);
435  tor_asprintf(&encoded, "%s ntor %s", str_ip_onion_key, key_b64);
436 
437  return encoded;
438 }
439 
440 /** Encode an introduction point object and return a newly allocated string
441  * with it. On failure, return NULL. */
442 static char *
444  const hs_desc_intro_point_t *ip)
445 {
446  char *encoded_ip = NULL;
447  smartlist_t *lines = smartlist_new();
448 
449  tor_assert(ip);
450  tor_assert(sig_key);
451 
452  /* Encode link specifier. */
453  {
454  char *ls_str = encode_link_specifiers(ip->link_specifiers);
455  smartlist_add_asprintf(lines, "%s %s", str_intro_point, ls_str);
456  tor_free(ls_str);
457  }
458 
459  /* Onion key encoding. */
460  {
461  char *encoded_onion_key = encode_onion_key(ip);
462  if (encoded_onion_key == NULL) {
463  goto err;
464  }
465  smartlist_add_asprintf(lines, "%s", encoded_onion_key);
466  tor_free(encoded_onion_key);
467  }
468 
469  /* Authentication key encoding. */
470  {
471  char *encoded_cert;
472  if (tor_cert_encode_ed22519(ip->auth_key_cert, &encoded_cert) < 0) {
473  goto err;
474  }
475  smartlist_add_asprintf(lines, "%s\n%s", str_ip_auth_key, encoded_cert);
476  tor_free(encoded_cert);
477  }
478 
479  /* Encryption key encoding. */
480  {
481  char *encoded_enc_key = encode_enc_key(ip);
482  if (encoded_enc_key == NULL) {
483  goto err;
484  }
485  smartlist_add_asprintf(lines, "%s", encoded_enc_key);
486  tor_free(encoded_enc_key);
487  }
488 
489  /* Legacy key if any. */
490  if (ip->legacy.key != NULL) {
491  /* Strong requirement else the IP creation was badly done. */
492  tor_assert(ip->legacy.cert.encoded);
493  char *encoded_legacy_key = encode_legacy_key(ip);
494  if (encoded_legacy_key == NULL) {
495  goto err;
496  }
497  smartlist_add_asprintf(lines, "%s", encoded_legacy_key);
498  tor_free(encoded_legacy_key);
499  }
500 
501  /* Join them all in one blob of text. */
502  encoded_ip = smartlist_join_strings(lines, "\n", 1, NULL);
503 
504  err:
505  SMARTLIST_FOREACH(lines, char *, l, tor_free(l));
506  smartlist_free(lines);
507  return encoded_ip;
508 }
509 
510 /** Given a source length, return the new size including padding for the
511  * plaintext encryption. */
512 static size_t
513 compute_padded_plaintext_length(size_t plaintext_len)
514 {
515  size_t plaintext_padded_len;
516  const int padding_block_length = HS_DESC_SUPERENC_PLAINTEXT_PAD_MULTIPLE;
517 
518  /* Make sure we won't overflow. */
519  tor_assert(plaintext_len <= (SIZE_T_CEILING - padding_block_length));
520 
521  /* Get the extra length we need to add. For example, if srclen is 10200
522  * bytes, this will expand to (2 * 10k) == 20k thus an extra 9800 bytes. */
523  plaintext_padded_len = CEIL_DIV(plaintext_len, padding_block_length) *
524  padding_block_length;
525  /* Can never be extra careful. Make sure we are _really_ padded. */
526  tor_assert(!(plaintext_padded_len % padding_block_length));
527  return plaintext_padded_len;
528 }
529 
530 /** Given a buffer, pad it up to the encrypted section padding requirement. Set
531  * the newly allocated string in padded_out and return the length of the
532  * padded buffer. */
533 STATIC size_t
534 build_plaintext_padding(const char *plaintext, size_t plaintext_len,
535  uint8_t **padded_out)
536 {
537  size_t padded_len;
538  uint8_t *padded;
539 
540  tor_assert(plaintext);
541  tor_assert(padded_out);
542 
543  /* Allocate the final length including padding. */
544  padded_len = compute_padded_plaintext_length(plaintext_len);
545  tor_assert(padded_len >= plaintext_len);
546  padded = tor_malloc_zero(padded_len);
547 
548  memcpy(padded, plaintext, plaintext_len);
549  *padded_out = padded;
550  return padded_len;
551 }
552 
553 /** Using a key, IV and plaintext data of length plaintext_len, create the
554  * encrypted section by encrypting it and setting encrypted_out with the
555  * data. Return size of the encrypted data buffer. */
556 static size_t
557 build_encrypted(const uint8_t *key, const uint8_t *iv, const char *plaintext,
558  size_t plaintext_len, uint8_t **encrypted_out,
559  int is_superencrypted_layer)
560 {
561  size_t encrypted_len;
562  uint8_t *padded_plaintext, *encrypted;
563  crypto_cipher_t *cipher;
564 
565  tor_assert(key);
566  tor_assert(iv);
567  tor_assert(plaintext);
568  tor_assert(encrypted_out);
569 
570  /* If we are encrypting the middle layer of the descriptor, we need to first
571  pad the plaintext */
572  if (is_superencrypted_layer) {
573  encrypted_len = build_plaintext_padding(plaintext, plaintext_len,
574  &padded_plaintext);
575  /* Extra precautions that we have a valid padding length. */
577  } else { /* No padding required for inner layers */
578  padded_plaintext = tor_memdup(plaintext, plaintext_len);
579  encrypted_len = plaintext_len;
580  }
581 
582  /* This creates a cipher for AES. It can't fail. */
583  cipher = crypto_cipher_new_with_iv_and_bits(key, iv,
584  HS_DESC_ENCRYPTED_BIT_SIZE);
585  /* We use a stream cipher so the encrypted length will be the same as the
586  * plaintext padded length. */
587  encrypted = tor_malloc_zero(encrypted_len);
588  /* This can't fail. */
589  crypto_cipher_encrypt(cipher, (char *) encrypted,
590  (const char *) padded_plaintext, encrypted_len);
591  *encrypted_out = encrypted;
592  /* Cleanup. */
593  crypto_cipher_free(cipher);
594  tor_free(padded_plaintext);
595  return encrypted_len;
596 }
597 
598 /** Encrypt the given <b>plaintext</b> buffer using <b>desc</b> and
599  * <b>secret_data</b> to get the keys. Set encrypted_out with the encrypted
600  * data and return the length of it. <b>is_superencrypted_layer</b> is set
601  * if this is the outer encrypted layer of the descriptor. */
602 static size_t
604  const uint8_t *secret_data,
605  size_t secret_data_len,
606  const char *plaintext,
607  char **encrypted_out, int is_superencrypted_layer)
608 {
609  char *final_blob;
610  size_t encrypted_len, final_blob_len, offset = 0;
611  uint8_t *encrypted;
612  uint8_t salt[HS_DESC_ENCRYPTED_SALT_LEN];
613  uint8_t secret_key[HS_DESC_ENCRYPTED_KEY_LEN], secret_iv[CIPHER_IV_LEN];
614  uint8_t mac_key[DIGEST256_LEN], mac[DIGEST256_LEN];
615 
616  tor_assert(desc);
617  tor_assert(secret_data);
618  tor_assert(plaintext);
619  tor_assert(encrypted_out);
620 
621  /* Get our salt. The returned bytes are already hashed. */
622  crypto_strongest_rand(salt, sizeof(salt));
623 
624  /* KDF construction resulting in a key from which the secret key, IV and MAC
625  * key are extracted which is what we need for the encryption. */
626  build_secret_key_iv_mac(desc, secret_data, secret_data_len,
627  salt, sizeof(salt),
628  secret_key, sizeof(secret_key),
629  secret_iv, sizeof(secret_iv),
630  mac_key, sizeof(mac_key),
631  is_superencrypted_layer);
632 
633  /* Build the encrypted part that is do the actual encryption. */
634  encrypted_len = build_encrypted(secret_key, secret_iv, plaintext,
635  strlen(plaintext), &encrypted,
636  is_superencrypted_layer);
637  memwipe(secret_key, 0, sizeof(secret_key));
638  memwipe(secret_iv, 0, sizeof(secret_iv));
639  /* This construction is specified in section 2.5 of proposal 224. */
640  final_blob_len = sizeof(salt) + encrypted_len + DIGEST256_LEN;
641  final_blob = tor_malloc_zero(final_blob_len);
642 
643  /* Build the MAC. */
644  build_mac(mac_key, sizeof(mac_key), salt, sizeof(salt),
645  encrypted, encrypted_len, mac, sizeof(mac));
646  memwipe(mac_key, 0, sizeof(mac_key));
647 
648  /* The salt is the first value. */
649  memcpy(final_blob, salt, sizeof(salt));
650  offset = sizeof(salt);
651  /* Second value is the encrypted data. */
652  memcpy(final_blob + offset, encrypted, encrypted_len);
653  offset += encrypted_len;
654  /* Third value is the MAC. */
655  memcpy(final_blob + offset, mac, sizeof(mac));
656  offset += sizeof(mac);
657  /* Cleanup the buffers. */
658  memwipe(salt, 0, sizeof(salt));
659  memwipe(encrypted, 0, encrypted_len);
660  tor_free(encrypted);
661  /* Extra precaution. */
662  tor_assert(offset == final_blob_len);
663 
664  *encrypted_out = final_blob;
665  return final_blob_len;
666 }
667 
668 /** Create and return a string containing a client-auth entry. It's the
669  * responsibility of the caller to free the returned string. This function
670  * will never fail. */
671 static char *
673 {
674  int ret;
675  char *auth_client_str = NULL;
676  /* We are gonna fill these arrays with base64 data. They are all double
677  * the size of their binary representation to fit the base64 overhead. */
678  char client_id_b64[HS_DESC_CLIENT_ID_LEN * 2];
679  char iv_b64[CIPHER_IV_LEN * 2];
680  char encrypted_cookie_b64[HS_DESC_ENCRYPED_COOKIE_LEN * 2];
681 
682 #define ASSERT_AND_BASE64(field) STMT_BEGIN \
683  tor_assert(!fast_mem_is_zero((char *) client->field, \
684  sizeof(client->field))); \
685  ret = base64_encode_nopad(field##_b64, sizeof(field##_b64), \
686  client->field, sizeof(client->field)); \
687  tor_assert(ret > 0); \
688  STMT_END
689 
690  ASSERT_AND_BASE64(client_id);
691  ASSERT_AND_BASE64(iv);
692  ASSERT_AND_BASE64(encrypted_cookie);
693 
694  /* Build the final string */
695  tor_asprintf(&auth_client_str, "%s %s %s %s", str_desc_auth_client,
696  client_id_b64, iv_b64, encrypted_cookie_b64);
697 
698 #undef ASSERT_AND_BASE64
699 
700  return auth_client_str;
701 }
702 
703 /** Create the "client-auth" part of the descriptor and return a
704  * newly-allocated string with it. It's the responsibility of the caller to
705  * free the returned string. */
706 static char *
708 {
709  smartlist_t *auth_client_lines = smartlist_new();
710  char *auth_client_lines_str = NULL;
711 
712  tor_assert(desc);
714  tor_assert(smartlist_len(desc->superencrypted_data.clients) != 0);
715  tor_assert(smartlist_len(desc->superencrypted_data.clients)
717 
718  /* Make a line for each client */
720  const hs_desc_authorized_client_t *, client) {
721  char *auth_client_str = NULL;
722 
723  auth_client_str = get_auth_client_str(client);
724 
725  smartlist_add(auth_client_lines, auth_client_str);
726  } SMARTLIST_FOREACH_END(client);
727 
728  /* Join all lines together to form final string */
729  auth_client_lines_str = smartlist_join_strings(auth_client_lines,
730  "\n", 1, NULL);
731  /* Cleanup the mess */
732  SMARTLIST_FOREACH(auth_client_lines, char *, a, tor_free(a));
733  smartlist_free(auth_client_lines);
734 
735  return auth_client_lines_str;
736 }
737 
738 /** Create the inner layer of the descriptor (which includes the intro points,
739  * etc.). Return a newly-allocated string with the layer plaintext, or NULL if
740  * an error occurred. It's the responsibility of the caller to free the
741  * returned string. */
742 static char *
744 {
745  char *encoded_str = NULL;
746  smartlist_t *lines = smartlist_new();
747 
748  /* Build the start of the section prior to the introduction points. */
749  {
750  if (!desc->encrypted_data.create2_ntor) {
751  log_err(LD_BUG, "HS desc doesn't have recognized handshake type.");
752  goto err;
753  }
754  smartlist_add_asprintf(lines, "%s %d\n", str_create2_formats,
755  ONION_HANDSHAKE_TYPE_NTOR);
756 
757  if (desc->encrypted_data.intro_auth_types &&
758  smartlist_len(desc->encrypted_data.intro_auth_types)) {
759  /* Put the authentication-required line. */
761  " ", 0, NULL);
762  smartlist_add_asprintf(lines, "%s %s\n", str_intro_auth_required, buf);
763  tor_free(buf);
764  }
765 
767  smartlist_add_asprintf(lines, "%s\n", str_single_onion);
768  }
769  }
770 
771  /* Build the introduction point(s) section. */
773  const hs_desc_intro_point_t *, ip) {
774  char *encoded_ip = encode_intro_point(&desc->plaintext_data.signing_pubkey,
775  ip);
776  if (encoded_ip == NULL) {
777  log_err(LD_BUG, "HS desc intro point is malformed.");
778  goto err;
779  }
780  smartlist_add(lines, encoded_ip);
781  } SMARTLIST_FOREACH_END(ip);
782 
783  /* Build the entire encrypted data section into one encoded plaintext and
784  * then encrypt it. */
785  encoded_str = smartlist_join_strings(lines, "", 0, NULL);
786 
787  err:
788  SMARTLIST_FOREACH(lines, char *, l, tor_free(l));
789  smartlist_free(lines);
790 
791  return encoded_str;
792 }
793 
794 /** Create the middle layer of the descriptor, which includes the client auth
795  * data and the encrypted inner layer (provided as a base64 string at
796  * <b>layer2_b64_ciphertext</b>). Return a newly-allocated string with the
797  * layer plaintext. It's the responsibility of the caller to free the returned
798  * string. Can not fail. */
799 static char *
801  const char *layer2_b64_ciphertext)
802 {
803  char *layer1_str = NULL;
804  smartlist_t *lines = smartlist_new();
805 
806  /* Specify auth type */
807  smartlist_add_asprintf(lines, "%s %s\n", str_desc_auth_type, "x25519");
808 
809  { /* Print ephemeral x25519 key */
810  char ephemeral_key_base64[CURVE25519_BASE64_PADDED_LEN + 1];
811  const curve25519_public_key_t *ephemeral_pubkey;
812 
813  ephemeral_pubkey = &desc->superencrypted_data.auth_ephemeral_pubkey;
814  tor_assert(!fast_mem_is_zero((char *) ephemeral_pubkey->public_key,
816 
817  curve25519_public_to_base64(ephemeral_key_base64, ephemeral_pubkey, true);
818  smartlist_add_asprintf(lines, "%s %s\n",
819  str_desc_auth_key, ephemeral_key_base64);
820 
821  memwipe(ephemeral_key_base64, 0, sizeof(ephemeral_key_base64));
822  }
823 
824  { /* Create auth-client lines. */
825  char *auth_client_lines = get_all_auth_client_lines(desc);
826  tor_assert(auth_client_lines);
827  smartlist_add(lines, auth_client_lines);
828  }
829 
830  /* create encrypted section */
831  {
833  "%s\n"
834  "-----BEGIN MESSAGE-----\n"
835  "%s"
836  "-----END MESSAGE-----",
837  str_encrypted, layer2_b64_ciphertext);
838  }
839 
840  layer1_str = smartlist_join_strings(lines, "", 0, NULL);
841 
842  /* We need to memwipe all lines because it contains the ephemeral key */
843  SMARTLIST_FOREACH(lines, char *, a, memwipe(a, 0, strlen(a)));
844  SMARTLIST_FOREACH(lines, char *, a, tor_free(a));
845  smartlist_free(lines);
846 
847  return layer1_str;
848 }
849 
850 /** Encrypt <b>encoded_str</b> into an encrypted blob and then base64 it before
851  * returning it. <b>desc</b> is provided to derive the encryption
852  * keys. <b>secret_data</b> is also proved to derive the encryption keys.
853  * <b>is_superencrypted_layer</b> is set if <b>encoded_str</b> is the
854  * middle (superencrypted) layer of the descriptor. It's the responsibility of
855  * the caller to free the returned string. */
856 static char *
858  const uint8_t *secret_data,
859  size_t secret_data_len,
860  const char *encoded_str,
861  int is_superencrypted_layer)
862 {
863  char *enc_b64;
864  ssize_t enc_b64_len, ret_len, enc_len;
865  char *encrypted_blob = NULL;
866 
867  enc_len = encrypt_descriptor_data(desc, secret_data, secret_data_len,
868  encoded_str, &encrypted_blob,
869  is_superencrypted_layer);
870  /* Get the encoded size plus a NUL terminating byte. */
871  enc_b64_len = base64_encode_size(enc_len, BASE64_ENCODE_MULTILINE) + 1;
872  enc_b64 = tor_malloc_zero(enc_b64_len);
873  /* Base64 the encrypted blob before returning it. */
874  ret_len = base64_encode(enc_b64, enc_b64_len, encrypted_blob, enc_len,
875  BASE64_ENCODE_MULTILINE);
876  /* Return length doesn't count the NUL byte. */
877  tor_assert(ret_len == (enc_b64_len - 1));
878  tor_free(encrypted_blob);
879 
880  return enc_b64;
881 }
882 
883 /** Generate the secret data which is used to encrypt/decrypt the descriptor.
884  *
885  * SECRET_DATA = blinded-public-key
886  * SECRET_DATA = blinded-public-key | descriptor_cookie
887  *
888  * The descriptor_cookie is optional but if it exists, it must be at least
889  * HS_DESC_DESCRIPTOR_COOKIE_LEN bytes long.
890  *
891  * A newly allocated secret data is put in secret_data_out. Return the
892  * length of the secret data. This function cannot fail. */
893 static size_t
895  const uint8_t *descriptor_cookie,
896  uint8_t **secret_data_out)
897 {
898  size_t secret_data_len;
899  uint8_t *secret_data;
900 
901  tor_assert(blinded_pubkey);
902  tor_assert(secret_data_out);
903 
904  if (descriptor_cookie) {
905  /* If the descriptor cookie is present, we need both the blinded
906  * pubkey and the descriptor cookie as a secret data. */
907  secret_data_len = ED25519_PUBKEY_LEN + HS_DESC_DESCRIPTOR_COOKIE_LEN;
908  secret_data = tor_malloc(secret_data_len);
909 
910  memcpy(secret_data,
911  blinded_pubkey->pubkey,
913  memcpy(secret_data + ED25519_PUBKEY_LEN,
914  descriptor_cookie,
915  HS_DESC_DESCRIPTOR_COOKIE_LEN);
916  } else {
917  /* If the descriptor cookie is not present, we need only the blinded
918  * pubkey as a secret data. */
919  secret_data_len = ED25519_PUBKEY_LEN;
920  secret_data = tor_malloc(secret_data_len);
921  memcpy(secret_data,
922  blinded_pubkey->pubkey,
924  }
925 
926  *secret_data_out = secret_data;
927  return secret_data_len;
928 }
929 
930 /** Generate and encode the superencrypted portion of <b>desc</b>. This also
931  * involves generating the encrypted portion of the descriptor, and performing
932  * the superencryption. A newly allocated NUL-terminated string pointer
933  * containing the encrypted encoded blob is put in encrypted_blob_out. Return 0
934  * on success else a negative value. */
935 static int
937  const uint8_t *descriptor_cookie,
938  char **encrypted_blob_out)
939 {
940  int ret = -1;
941  uint8_t *secret_data = NULL;
942  size_t secret_data_len = 0;
943  char *layer2_str = NULL;
944  char *layer2_b64_ciphertext = NULL;
945  char *layer1_str = NULL;
946  char *layer1_b64_ciphertext = NULL;
947 
948  tor_assert(desc);
949  tor_assert(encrypted_blob_out);
950 
951  /* Func logic: We first create the inner layer of the descriptor (layer2).
952  * We then encrypt it and use it to create the middle layer of the descriptor
953  * (layer1). Finally we superencrypt the middle layer and return it to our
954  * caller. */
955 
956  /* Create inner descriptor layer */
957  layer2_str = get_inner_encrypted_layer_plaintext(desc);
958  if (!layer2_str) {
959  goto err;
960  }
961 
962  secret_data_len = build_secret_data(&desc->plaintext_data.blinded_pubkey,
963  descriptor_cookie,
964  &secret_data);
965 
966  /* Encrypt and b64 the inner layer */
967  layer2_b64_ciphertext =
968  encrypt_desc_data_and_base64(desc, secret_data, secret_data_len,
969  layer2_str, 0);
970  if (!layer2_b64_ciphertext) {
971  goto err;
972  }
973 
974  /* Now create middle descriptor layer given the inner layer */
975  layer1_str = get_outer_encrypted_layer_plaintext(desc,layer2_b64_ciphertext);
976  if (!layer1_str) {
977  goto err;
978  }
979 
980  /* Encrypt and base64 the middle layer */
981  layer1_b64_ciphertext =
983  desc->plaintext_data.blinded_pubkey.pubkey,
985  layer1_str, 1);
986  if (!layer1_b64_ciphertext) {
987  goto err;
988  }
989 
990  /* Success! */
991  ret = 0;
992 
993  err:
994  memwipe(secret_data, 0, secret_data_len);
995  tor_free(secret_data);
996  tor_free(layer1_str);
997  tor_free(layer2_str);
998  tor_free(layer2_b64_ciphertext);
999 
1000  *encrypted_blob_out = layer1_b64_ciphertext;
1001  return ret;
1002 }
1003 
1004 /** Encode a v3 HS descriptor. Return 0 on success and set encoded_out to the
1005  * newly allocated string of the encoded descriptor. On error, -1 is returned
1006  * and encoded_out is untouched. */
1007 static int
1009  const ed25519_keypair_t *signing_kp,
1010  const uint8_t *descriptor_cookie,
1011  char **encoded_out)
1012 {
1013  int ret = -1;
1014  char *encoded_str = NULL;
1015  size_t encoded_len;
1016  smartlist_t *lines = smartlist_new();
1017 
1018  tor_assert(desc);
1019  tor_assert(signing_kp);
1020  tor_assert(encoded_out);
1021  tor_assert(desc->plaintext_data.version == 3);
1022 
1023  /* Build the non-encrypted values. */
1024  {
1025  char *encoded_cert;
1026  /* Encode certificate then create the first line of the descriptor. */
1028  != CERT_TYPE_SIGNING_HS_DESC) {
1029  log_err(LD_BUG, "HS descriptor signing key has an unexpected cert type "
1030  "(%d)", (int) desc->plaintext_data.signing_key_cert->cert_type);
1031  goto err;
1032  }
1033  if (tor_cert_encode_ed22519(desc->plaintext_data.signing_key_cert,
1034  &encoded_cert) < 0) {
1035  /* The function will print error logs. */
1036  goto err;
1037  }
1038  /* Create the hs descriptor line. */
1039  smartlist_add_asprintf(lines, "%s %" PRIu32, str_hs_desc,
1040  desc->plaintext_data.version);
1041  /* Add the descriptor lifetime line (in minutes). */
1042  smartlist_add_asprintf(lines, "%s %" PRIu32, str_lifetime,
1043  desc->plaintext_data.lifetime_sec / 60);
1044  /* Create the descriptor certificate line. */
1045  smartlist_add_asprintf(lines, "%s\n%s", str_desc_cert, encoded_cert);
1046  tor_free(encoded_cert);
1047  /* Create the revision counter line. */
1048  smartlist_add_asprintf(lines, "%s %" PRIu64, str_rev_counter,
1050  }
1051 
1052  /* Build the superencrypted data section. */
1053  {
1054  char *enc_b64_blob=NULL;
1055  if (encode_superencrypted_data(desc, descriptor_cookie,
1056  &enc_b64_blob) < 0) {
1057  goto err;
1058  }
1059  smartlist_add_asprintf(lines,
1060  "%s\n"
1061  "-----BEGIN MESSAGE-----\n"
1062  "%s"
1063  "-----END MESSAGE-----",
1064  str_superencrypted, enc_b64_blob);
1065  tor_free(enc_b64_blob);
1066  }
1067 
1068  /* Join all lines in one string so we can generate a signature and append
1069  * it to the descriptor. */
1070  encoded_str = smartlist_join_strings(lines, "\n", 1, &encoded_len);
1071 
1072  /* Sign all fields of the descriptor with our short term signing key. */
1073  {
1074  ed25519_signature_t sig;
1075  char ed_sig_b64[ED25519_SIG_BASE64_LEN + 1];
1076  if (ed25519_sign_prefixed(&sig,
1077  (const uint8_t *) encoded_str, encoded_len,
1078  str_desc_sig_prefix, signing_kp) < 0) {
1079  log_warn(LD_BUG, "Can't sign encoded HS descriptor!");
1080  tor_free(encoded_str);
1081  goto err;
1082  }
1083  ed25519_signature_to_base64(ed_sig_b64, &sig);
1084  /* Create the signature line. */
1085  smartlist_add_asprintf(lines, "%s %s", str_signature, ed_sig_b64);
1086  }
1087  /* Free previous string that we used so compute the signature. */
1088  tor_free(encoded_str);
1089  encoded_str = smartlist_join_strings(lines, "\n", 1, NULL);
1090  *encoded_out = encoded_str;
1091 
1092  if (strlen(encoded_str) >= hs_cache_get_max_descriptor_size()) {
1093  log_warn(LD_GENERAL, "We just made an HS descriptor that's too big (%d)."
1094  "Failing.", (int)strlen(encoded_str));
1095  tor_free(encoded_str);
1096  goto err;
1097  }
1098 
1099  /* XXX: Trigger a control port event. */
1100 
1101  /* Success! */
1102  ret = 0;
1103 
1104  err:
1105  SMARTLIST_FOREACH(lines, char *, l, tor_free(l));
1106  smartlist_free(lines);
1107  return ret;
1108 }
1109 
1110 /* === DECODING === */
1111 
1112 /** Given the token tok for an auth client, decode it as
1113  * hs_desc_authorized_client_t. tok->args MUST contain at least 3 elements
1114  * Return 0 on success else -1 on failure. */
1115 static int
1118 {
1119  int ret = -1;
1120 
1121  tor_assert(tok);
1122  tor_assert(tok->n_args >= 3);
1123  tor_assert(client);
1124 
1125  if (base64_decode((char *) client->client_id, sizeof(client->client_id),
1126  tok->args[0], strlen(tok->args[0])) !=
1127  sizeof(client->client_id)) {
1128  goto done;
1129  }
1130  if (base64_decode((char *) client->iv, sizeof(client->iv),
1131  tok->args[1], strlen(tok->args[1])) !=
1132  sizeof(client->iv)) {
1133  goto done;
1134  }
1135  if (base64_decode((char *) client->encrypted_cookie,
1136  sizeof(client->encrypted_cookie),
1137  tok->args[2], strlen(tok->args[2])) !=
1138  sizeof(client->encrypted_cookie)) {
1139  goto done;
1140  }
1141 
1142  /* Success. */
1143  ret = 0;
1144  done:
1145  return ret;
1146 }
1147 
1148 /** Given an encoded string of the link specifiers, return a newly allocated
1149  * list of decoded link specifiers. Return NULL on error. */
1151 decode_link_specifiers(const char *encoded)
1152 {
1153  int decoded_len;
1154  size_t encoded_len, i;
1155  uint8_t *decoded;
1156  smartlist_t *results = NULL;
1157  link_specifier_list_t *specs = NULL;
1158 
1159  tor_assert(encoded);
1160 
1161  encoded_len = strlen(encoded);
1162  decoded = tor_malloc(encoded_len);
1163  decoded_len = base64_decode((char *) decoded, encoded_len, encoded,
1164  encoded_len);
1165  if (decoded_len < 0) {
1166  goto err;
1167  }
1168 
1169  if (link_specifier_list_parse(&specs, decoded,
1170  (size_t) decoded_len) < decoded_len) {
1171  goto err;
1172  }
1173  tor_assert(specs);
1174  results = smartlist_new();
1175 
1176  for (i = 0; i < link_specifier_list_getlen_spec(specs); i++) {
1177  link_specifier_t *ls = link_specifier_list_get_spec(specs, i);
1178  if (BUG(!ls)) {
1179  goto err;
1180  }
1181  link_specifier_t *ls_dup = link_specifier_dup(ls);
1182  if (BUG(!ls_dup)) {
1183  goto err;
1184  }
1185  smartlist_add(results, ls_dup);
1186  }
1187 
1188  goto done;
1189  err:
1190  if (results) {
1191  SMARTLIST_FOREACH(results, link_specifier_t *, s,
1192  link_specifier_free(s));
1193  smartlist_free(results);
1194  results = NULL;
1195  }
1196  done:
1197  link_specifier_list_free(specs);
1198  tor_free(decoded);
1199  return results;
1200 }
1201 
1202 /** Given a list of authentication types, decode it and put it in the encrypted
1203  * data section. Return 1 if we at least know one of the type or 0 if we know
1204  * none of them. */
1205 static int
1207 {
1208  int match = 0;
1209 
1210  tor_assert(desc);
1211  tor_assert(list);
1212 
1213  desc->intro_auth_types = smartlist_new();
1214  smartlist_split_string(desc->intro_auth_types, list, " ", 0, 0);
1215 
1216  /* Validate the types that we at least know about one. */
1217  SMARTLIST_FOREACH_BEGIN(desc->intro_auth_types, const char *, auth) {
1218  for (int idx = 0; intro_auth_types[idx].identifier; idx++) {
1219  if (!strncmp(auth, intro_auth_types[idx].identifier,
1220  strlen(intro_auth_types[idx].identifier))) {
1221  match = 1;
1222  break;
1223  }
1224  }
1225  } SMARTLIST_FOREACH_END(auth);
1226 
1227  return match;
1228 }
1229 
1230 /** Parse a space-delimited list of integers representing CREATE2 formats into
1231  * the bitfield in hs_desc_encrypted_data_t. Ignore unrecognized values. */
1232 static void
1234 {
1235  smartlist_t *tokens;
1236 
1237  tor_assert(desc);
1238  tor_assert(list);
1239 
1240  tokens = smartlist_new();
1241  smartlist_split_string(tokens, list, " ", 0, 0);
1242 
1243  SMARTLIST_FOREACH_BEGIN(tokens, char *, s) {
1244  int ok;
1245  unsigned long type = tor_parse_ulong(s, 10, 1, UINT16_MAX, &ok, NULL);
1246  if (!ok) {
1247  log_warn(LD_REND, "Unparseable value %s in create2 list", escaped(s));
1248  continue;
1249  }
1250  switch (type) {
1251  case ONION_HANDSHAKE_TYPE_NTOR:
1252  desc->create2_ntor = 1;
1253  break;
1254  default:
1255  /* We deliberately ignore unsupported handshake types */
1256  continue;
1257  }
1258  } SMARTLIST_FOREACH_END(s);
1259 
1260  SMARTLIST_FOREACH(tokens, char *, s, tor_free(s));
1261  smartlist_free(tokens);
1262 }
1263 
1264 /** Given a certificate, validate the certificate for certain conditions which
1265  * are if the given type matches the cert's one, if the signing key is
1266  * included and if the that key was actually used to sign the certificate.
1267  *
1268  * Return 1 iff if all conditions pass or 0 if one of them fails. */
1269 STATIC int
1270 cert_is_valid(tor_cert_t *cert, uint8_t type, const char *log_obj_type)
1271 {
1272  tor_assert(log_obj_type);
1273 
1274  if (cert == NULL) {
1275  log_warn(LD_REND, "Certificate for %s couldn't be parsed.", log_obj_type);
1276  goto err;
1277  }
1278  if (cert->cert_type != type) {
1279  log_warn(LD_REND, "Invalid cert type %02x for %s.", cert->cert_type,
1280  log_obj_type);
1281  goto err;
1282  }
1283  /* All certificate must have its signing key included. */
1284  if (!cert->signing_key_included) {
1285  log_warn(LD_REND, "Signing key is NOT included for %s.", log_obj_type);
1286  goto err;
1287  }
1288 
1289  /* The following will not only check if the signature matches but also the
1290  * expiration date and overall validity. */
1291  if (tor_cert_checksig(cert, &cert->signing_key, approx_time()) < 0) {
1292  if (cert->cert_expired) {
1293  char expiration_str[ISO_TIME_LEN+1];
1294  format_iso_time(expiration_str, cert->valid_until);
1295  log_fn(LOG_PROTOCOL_WARN, LD_REND, "Invalid signature for %s: %s (%s)",
1296  log_obj_type, tor_cert_describe_signature_status(cert),
1297  expiration_str);
1298  } else {
1299  log_warn(LD_REND, "Invalid signature for %s: %s",
1300  log_obj_type, tor_cert_describe_signature_status(cert));
1301  }
1302  goto err;
1303  }
1304 
1305  return 1;
1306  err:
1307  return 0;
1308 }
1309 
1310 /** Given some binary data, try to parse it to get a certificate object. If we
1311  * have a valid cert, validate it using the given wanted type. On error, print
1312  * a log using the err_msg has the certificate identifier adding semantic to
1313  * the log and cert_out is set to NULL. On success, 0 is returned and cert_out
1314  * points to a newly allocated certificate object. */
1315 static int
1316 cert_parse_and_validate(tor_cert_t **cert_out, const char *data,
1317  size_t data_len, unsigned int cert_type_wanted,
1318  const char *err_msg)
1319 {
1320  tor_cert_t *cert;
1321 
1322  tor_assert(cert_out);
1323  tor_assert(data);
1324  tor_assert(err_msg);
1325 
1326  /* Parse certificate. */
1327  cert = tor_cert_parse((const uint8_t *) data, data_len);
1328  if (!cert) {
1329  log_warn(LD_REND, "Certificate for %s couldn't be parsed.", err_msg);
1330  goto err;
1331  }
1332 
1333  /* Validate certificate. */
1334  if (!cert_is_valid(cert, cert_type_wanted, err_msg)) {
1335  goto err;
1336  }
1337 
1338  *cert_out = cert;
1339  return 0;
1340 
1341  err:
1342  tor_cert_free(cert);
1343  *cert_out = NULL;
1344  return -1;
1345 }
1346 
1347 /** Return true iff the given length of the encrypted data of a descriptor
1348  * passes validation. */
1349 STATIC int
1351 {
1352  /* Make sure there is enough data for the salt and the mac. The equality is
1353  there to ensure that there is at least one byte of encrypted data. */
1355  log_warn(LD_REND, "Length of descriptor's encrypted data is too small. "
1356  "Got %lu but minimum value is %d",
1357  (unsigned long)len, HS_DESC_ENCRYPTED_SALT_LEN + DIGEST256_LEN);
1358  goto err;
1359  }
1360 
1361  return 1;
1362  err:
1363  return 0;
1364 }
1365 
1366 /** Build the KEYS component for the authorized client computation. The format
1367  * of the construction is:
1368  *
1369  * SECRET_SEED = x25519(sk, pk)
1370  * KEYS = KDF(subcredential | SECRET_SEED, 40)
1371  *
1372  * Set the <b>keys_out</b> argument to point to the buffer containing the KEYS,
1373  * and return the buffer's length. The caller should wipe and free its content
1374  * once done with it. This function can't fail. */
1375 static size_t
1377  const curve25519_secret_key_t *sk,
1378  const curve25519_public_key_t *pk,
1379  uint8_t **keys_out)
1380 {
1381  uint8_t secret_seed[CURVE25519_OUTPUT_LEN];
1382  uint8_t *keystream;
1383  size_t keystream_len = HS_DESC_CLIENT_ID_LEN + HS_DESC_COOKIE_KEY_LEN;
1384  crypto_xof_t *xof;
1385 
1386  tor_assert(subcredential);
1387  tor_assert(sk);
1388  tor_assert(pk);
1389  tor_assert(keys_out);
1390 
1391  keystream = tor_malloc_zero(keystream_len);
1392 
1393  /* Calculate x25519(sk, pk) to get the secret seed. */
1394  curve25519_handshake(secret_seed, sk, pk);
1395 
1396  /* Calculate KEYS = KDF(subcredential | SECRET_SEED, 40) */
1397  xof = crypto_xof_new();
1398  crypto_xof_add_bytes(xof, subcredential->subcred, SUBCRED_LEN);
1399  crypto_xof_add_bytes(xof, secret_seed, sizeof(secret_seed));
1400  crypto_xof_squeeze_bytes(xof, keystream, keystream_len);
1401  crypto_xof_free(xof);
1402 
1403  memwipe(secret_seed, 0, sizeof(secret_seed));
1404 
1405  *keys_out = keystream;
1406  return keystream_len;
1407 }
1408 
1409 /** Decrypt the descriptor cookie given the descriptor, the auth client,
1410  * and the client secret key. On sucess, return 0 and a newly allocated
1411  * descriptor cookie descriptor_cookie_out. On error or if the client id
1412  * is invalid, return -1 and descriptor_cookie_out is set to
1413  * NULL. */
1414 static int
1416  const hs_desc_authorized_client_t *client,
1417  const curve25519_secret_key_t *client_auth_sk,
1418  uint8_t **descriptor_cookie_out)
1419 {
1420  int ret = -1;
1421  uint8_t *keystream = NULL;
1422  size_t keystream_length = 0;
1423  uint8_t *descriptor_cookie = NULL;
1424  const uint8_t *cookie_key = NULL;
1425  crypto_cipher_t *cipher = NULL;
1426 
1427  tor_assert(desc);
1428  tor_assert(client);
1429  tor_assert(client_auth_sk);
1433  tor_assert(!fast_mem_is_zero((char *) desc->subcredential.subcred,
1434  DIGEST256_LEN));
1435 
1436  /* Catch potential code-flow cases of an unitialized private key sneaking
1437  * into this function. */
1438  if (BUG(fast_mem_is_zero((char *)client_auth_sk, sizeof(*client_auth_sk)))) {
1439  goto done;
1440  }
1441 
1442  /* Get the KEYS component to derive the CLIENT-ID and COOKIE-KEY. */
1443  keystream_length =
1445  client_auth_sk,
1447  &keystream);
1448  tor_assert(keystream_length > 0);
1449 
1450  /* If the client id of auth client is not the same as the calculcated
1451  * client id, it means that this auth client is invaild according to the
1452  * client secret key client_auth_sk. */
1453  if (tor_memneq(client->client_id, keystream, HS_DESC_CLIENT_ID_LEN)) {
1454  goto done;
1455  }
1456  cookie_key = keystream + HS_DESC_CLIENT_ID_LEN;
1457 
1458  /* This creates a cipher for AES. It can't fail. */
1459  cipher = crypto_cipher_new_with_iv_and_bits(cookie_key, client->iv,
1460  HS_DESC_COOKIE_KEY_BIT_SIZE);
1461  descriptor_cookie = tor_malloc_zero(HS_DESC_DESCRIPTOR_COOKIE_LEN);
1462  /* This can't fail. */
1463  crypto_cipher_decrypt(cipher, (char *) descriptor_cookie,
1464  (const char *) client->encrypted_cookie,
1465  sizeof(client->encrypted_cookie));
1466 
1467  /* Success. */
1468  ret = 0;
1469  done:
1470  *descriptor_cookie_out = descriptor_cookie;
1471  if (cipher) {
1472  crypto_cipher_free(cipher);
1473  }
1474  memwipe(keystream, 0, keystream_length);
1475  tor_free(keystream);
1476  return ret;
1477 }
1478 
1479 /** Decrypt an encrypted descriptor layer at <b>encrypted_blob</b> of size
1480  * <b>encrypted_blob_size</b>. The descriptor cookie is optional. Use
1481  * the descriptor object <b>desc</b> and <b>descriptor_cookie</b>
1482  * to generate the right decryption keys; set <b>decrypted_out</b> to
1483  * the plaintext. If <b>is_superencrypted_layer</b> is set, this is
1484  * the outter encrypted layer of the descriptor.
1485  *
1486  * On any error case, including an empty output, return 0 and set
1487  * *<b>decrypted_out</b> to NULL.
1488  */
1489 MOCK_IMPL(STATIC size_t,
1490 decrypt_desc_layer,(const hs_descriptor_t *desc,
1491  const uint8_t *descriptor_cookie,
1492  bool is_superencrypted_layer,
1493  char **decrypted_out))
1494 {
1495  uint8_t *decrypted = NULL;
1496  uint8_t secret_key[HS_DESC_ENCRYPTED_KEY_LEN], secret_iv[CIPHER_IV_LEN];
1497  uint8_t *secret_data = NULL;
1498  size_t secret_data_len = 0;
1499  uint8_t mac_key[DIGEST256_LEN], our_mac[DIGEST256_LEN];
1500  const uint8_t *salt, *encrypted, *desc_mac;
1501  size_t encrypted_len, result_len = 0;
1502  const uint8_t *encrypted_blob = (is_superencrypted_layer)
1505  size_t encrypted_blob_size = (is_superencrypted_layer)
1508 
1509  tor_assert(decrypted_out);
1510  tor_assert(desc);
1511  tor_assert(encrypted_blob);
1512 
1513  /* Construction is as follow: SALT | ENCRYPTED_DATA | MAC .
1514  * Make sure we have enough space for all these things. */
1515  if (!encrypted_data_length_is_valid(encrypted_blob_size)) {
1516  goto err;
1517  }
1518 
1519  /* Start of the blob thus the salt. */
1520  salt = encrypted_blob;
1521 
1522  /* Next is the encrypted data. */
1523  encrypted = encrypted_blob + HS_DESC_ENCRYPTED_SALT_LEN;
1524  encrypted_len = encrypted_blob_size -
1526  tor_assert(encrypted_len > 0); /* guaranteed by the check above */
1527 
1528  /* And last comes the MAC. */
1529  desc_mac = encrypted_blob + encrypted_blob_size - DIGEST256_LEN;
1530 
1531  /* Build secret data to be used in the decryption. */
1532  secret_data_len = build_secret_data(&desc->plaintext_data.blinded_pubkey,
1533  descriptor_cookie,
1534  &secret_data);
1535 
1536  /* KDF construction resulting in a key from which the secret key, IV and MAC
1537  * key are extracted which is what we need for the decryption. */
1538  build_secret_key_iv_mac(desc, secret_data, secret_data_len,
1540  secret_key, sizeof(secret_key),
1541  secret_iv, sizeof(secret_iv),
1542  mac_key, sizeof(mac_key),
1543  is_superencrypted_layer);
1544 
1545  /* Build MAC. */
1546  build_mac(mac_key, sizeof(mac_key), salt, HS_DESC_ENCRYPTED_SALT_LEN,
1547  encrypted, encrypted_len, our_mac, sizeof(our_mac));
1548  memwipe(mac_key, 0, sizeof(mac_key));
1549  /* Verify MAC; MAC is H(mac_key || salt || encrypted)
1550  *
1551  * This is a critical check that is making sure the computed MAC matches the
1552  * one in the descriptor. */
1553  if (!tor_memeq(our_mac, desc_mac, sizeof(our_mac))) {
1554  log_info(LD_REND, "Encrypted service descriptor MAC check failed");
1555  goto err;
1556  }
1557 
1558  {
1559  /* Decrypt. Here we are assured that the encrypted length is valid for
1560  * decryption. */
1561  crypto_cipher_t *cipher;
1562 
1563  cipher = crypto_cipher_new_with_iv_and_bits(secret_key, secret_iv,
1564  HS_DESC_ENCRYPTED_BIT_SIZE);
1565  /* Extra byte for the NUL terminated byte. */
1566  decrypted = tor_malloc_zero(encrypted_len + 1);
1567  crypto_cipher_decrypt(cipher, (char *) decrypted,
1568  (const char *) encrypted, encrypted_len);
1569  crypto_cipher_free(cipher);
1570  }
1571 
1572  {
1573  /* Adjust length to remove NUL padding bytes */
1574  uint8_t *end = memchr(decrypted, 0, encrypted_len);
1575  result_len = encrypted_len;
1576  if (end) {
1577  result_len = end - decrypted;
1578  }
1579  }
1580 
1581  if (result_len == 0) {
1582  /* Treat this as an error, so that somebody will free the output. */
1583  goto err;
1584  }
1585 
1586  /* Make sure to NUL terminate the string. */
1587  decrypted[encrypted_len] = '\0';
1588  *decrypted_out = (char *) decrypted;
1589  goto done;
1590 
1591  err:
1592  if (decrypted) {
1593  tor_free(decrypted);
1594  }
1595  *decrypted_out = NULL;
1596  result_len = 0;
1597 
1598  done:
1599  memwipe(secret_data, 0, secret_data_len);
1600  memwipe(secret_key, 0, sizeof(secret_key));
1601  memwipe(secret_iv, 0, sizeof(secret_iv));
1602  tor_free(secret_data);
1603  return result_len;
1604 }
1605 
1606 /** Decrypt the superencrypted section of the descriptor using the given
1607  * descriptor object <b>desc</b>. A newly allocated NUL terminated string is
1608  * put in decrypted_out which contains the superencrypted layer of the
1609  * descriptor. Return the length of decrypted_out on success else 0 is
1610  * returned and decrypted_out is set to NULL. */
1611 static size_t
1612 desc_decrypt_superencrypted(const hs_descriptor_t *desc, char **decrypted_out)
1613 {
1614  size_t superencrypted_len = 0;
1615  char *superencrypted_plaintext = NULL;
1616 
1617  tor_assert(desc);
1618  tor_assert(decrypted_out);
1619 
1620  superencrypted_len = decrypt_desc_layer(desc,
1621  NULL,
1622  true, &superencrypted_plaintext);
1623 
1624  if (!superencrypted_len) {
1625  log_warn(LD_REND, "Decrypting superencrypted desc failed.");
1626  goto done;
1627  }
1628  tor_assert(superencrypted_plaintext);
1629 
1630  done:
1631  /* In case of error, superencrypted_plaintext is already NULL, so the
1632  * following line makes sense. */
1633  *decrypted_out = superencrypted_plaintext;
1634  /* This makes sense too, because, in case of error, this is zero. */
1635  return superencrypted_len;
1636 }
1637 
1638 /** Decrypt the encrypted section of the descriptor using the given descriptor
1639  * object <b>desc</b>. A newly allocated NUL terminated string is put in
1640  * decrypted_out which contains the encrypted layer of the descriptor.
1641  * Return the length of decrypted_out on success else 0 is returned and
1642  * decrypted_out is set to NULL. */
1643 static size_t
1645  const curve25519_secret_key_t *client_auth_sk,
1646  char **decrypted_out)
1647 {
1648  size_t encrypted_len = 0;
1649  char *encrypted_plaintext = NULL;
1650  uint8_t *descriptor_cookie = NULL;
1651 
1652  tor_assert(desc);
1654  tor_assert(decrypted_out);
1655 
1656  /* If the client secret key is provided, try to find a valid descriptor
1657  * cookie. Otherwise, leave it NULL. */
1658  if (client_auth_sk) {
1660  hs_desc_authorized_client_t *, client) {
1661  /* If we can decrypt the descriptor cookie successfully, we will use that
1662  * descriptor cookie and break from the loop. */
1663  if (!decrypt_descriptor_cookie(desc, client, client_auth_sk,
1664  &descriptor_cookie)) {
1665  break;
1666  }
1667  } SMARTLIST_FOREACH_END(client);
1668  }
1669 
1670  encrypted_len = decrypt_desc_layer(desc,
1671  descriptor_cookie,
1672  false, &encrypted_plaintext);
1673 
1674  if (!encrypted_len) {
1675  goto err;
1676  }
1677  tor_assert(encrypted_plaintext);
1678 
1679  err:
1680  /* In case of error, encrypted_plaintext is already NULL, so the
1681  * following line makes sense. */
1682  *decrypted_out = encrypted_plaintext;
1683  if (descriptor_cookie) {
1684  memwipe(descriptor_cookie, 0, HS_DESC_DESCRIPTOR_COOKIE_LEN);
1685  }
1686  tor_free(descriptor_cookie);
1687  /* This makes sense too, because, in case of error, this is zero. */
1688  return encrypted_len;
1689 }
1690 
1691 /** Given the token tok for an intro point legacy key, the list of tokens, the
1692  * introduction point ip being decoded and the descriptor desc from which it
1693  * comes from, decode the legacy key and set the intro point object. Return 0
1694  * on success else -1 on failure. */
1695 static int
1697  smartlist_t *tokens,
1699  const hs_descriptor_t *desc)
1700 {
1701  tor_assert(tok);
1702  tor_assert(tokens);
1703  tor_assert(ip);
1704  tor_assert(desc);
1705 
1706  if (!crypto_pk_public_exponent_ok(tok->key)) {
1707  log_warn(LD_REND, "Introduction point legacy key is invalid");
1708  goto err;
1709  }
1710  ip->legacy.key = crypto_pk_dup_key(tok->key);
1711  /* Extract the legacy cross certification cert which MUST be present if we
1712  * have a legacy key. */
1713  tok = find_opt_by_keyword(tokens, R3_INTRO_LEGACY_KEY_CERT);
1714  if (!tok) {
1715  log_warn(LD_REND, "Introduction point legacy key cert is missing");
1716  goto err;
1717  }
1718  tor_assert(tok->object_body);
1719  if (strcmp(tok->object_type, "CROSSCERT")) {
1720  /* Info level because this might be an unknown field that we should
1721  * ignore. */
1722  log_info(LD_REND, "Introduction point legacy encryption key "
1723  "cross-certification has an unknown format.");
1724  goto err;
1725  }
1726  /* Keep a copy of the certificate. */
1727  ip->legacy.cert.encoded = tor_memdup(tok->object_body, tok->object_size);
1728  ip->legacy.cert.len = tok->object_size;
1729  /* The check on the expiration date is for the entire lifetime of a
1730  * certificate which is 24 hours. However, a descriptor has a maximum
1731  * lifetime of 12 hours meaning we have a 12h difference between the two
1732  * which ultimately accommodate the clock skewed client. */
1733  if (rsa_ed25519_crosscert_check(ip->legacy.cert.encoded,
1734  ip->legacy.cert.len, ip->legacy.key,
1737  log_warn(LD_REND, "Unable to check cross-certification on the "
1738  "introduction point legacy encryption key.");
1739  ip->cross_certified = 0;
1740  goto err;
1741  }
1742 
1743  /* Success. */
1744  return 0;
1745  err:
1746  return -1;
1747 }
1748 
1749 /** Dig into the descriptor <b>tokens</b> to find the onion key we should use
1750  * for this intro point, and set it into <b>onion_key_out</b>. Return 0 if it
1751  * was found and well-formed, otherwise return -1 in case of errors. */
1752 static int
1754  const smartlist_t *tokens)
1755 {
1756  int retval = -1;
1757  smartlist_t *onion_keys = NULL;
1758 
1759  tor_assert(onion_key_out);
1760 
1761  onion_keys = find_all_by_keyword(tokens, R3_INTRO_ONION_KEY);
1762  if (!onion_keys) {
1763  log_warn(LD_REND, "Descriptor did not contain intro onion keys");
1764  goto err;
1765  }
1766 
1767  SMARTLIST_FOREACH_BEGIN(onion_keys, directory_token_t *, tok) {
1768  /* This field is using GE(2) so for possible forward compatibility, we
1769  * accept more fields but must be at least 2. */
1770  tor_assert(tok->n_args >= 2);
1771 
1772  /* Try to find an ntor key, it's the only recognized type right now */
1773  if (!strcmp(tok->args[0], "ntor")) {
1774  if (curve25519_public_from_base64(onion_key_out, tok->args[1]) < 0) {
1775  log_warn(LD_REND, "Introduction point ntor onion-key is invalid");
1776  goto err;
1777  }
1778  /* Got the onion key! Set the appropriate retval */
1779  retval = 0;
1780  }
1781  } SMARTLIST_FOREACH_END(tok);
1782 
1783  /* Log an error if we didn't find it :( */
1784  if (retval < 0) {
1785  log_warn(LD_REND, "Descriptor did not contain ntor onion keys");
1786  }
1787 
1788  err:
1789  smartlist_free(onion_keys);
1790  return retval;
1791 }
1792 
1793 /** Given the start of a section and the end of it, decode a single
1794  * introduction point from that section. Return a newly allocated introduction
1795  * point object containing the decoded data. Return NULL if the section can't
1796  * be decoded. */
1798 decode_introduction_point(const hs_descriptor_t *desc, const char *start)
1799 {
1800  hs_desc_intro_point_t *ip = NULL;
1801  memarea_t *area = NULL;
1802  smartlist_t *tokens = NULL;
1803  const directory_token_t *tok;
1804 
1805  tor_assert(desc);
1806  tor_assert(start);
1807 
1808  area = memarea_new();
1809  tokens = smartlist_new();
1810  if (tokenize_string(area, start, start + strlen(start),
1811  tokens, hs_desc_intro_point_v3_token_table, 0) < 0) {
1812  log_warn(LD_REND, "Introduction point is not parseable");
1813  goto err;
1814  }
1815 
1816  /* Ok we seem to have a well formed section containing enough tokens to
1817  * parse. Allocate our IP object and try to populate it. */
1818  ip = hs_desc_intro_point_new();
1819 
1820  /* "introduction-point" SP link-specifiers NL */
1821  tok = find_by_keyword(tokens, R3_INTRODUCTION_POINT);
1822  tor_assert(tok->n_args == 1);
1823  /* Our constructor creates this list by default so free it. */
1824  smartlist_free(ip->link_specifiers);
1826  if (!ip->link_specifiers) {
1827  log_warn(LD_REND, "Introduction point has invalid link specifiers");
1828  goto err;
1829  }
1830 
1831  /* "onion-key" SP ntor SP key NL */
1832  if (set_intro_point_onion_key(&ip->onion_key, tokens) < 0) {
1833  goto err;
1834  }
1835 
1836  /* "auth-key" NL certificate NL */
1837  tok = find_by_keyword(tokens, R3_INTRO_AUTH_KEY);
1838  tor_assert(tok->object_body);
1839  if (strcmp(tok->object_type, "ED25519 CERT")) {
1840  log_warn(LD_REND, "Unexpected object type for introduction auth key");
1841  goto err;
1842  }
1843  /* Parse cert and do some validation. */
1845  tok->object_size, CERT_TYPE_AUTH_HS_IP_KEY,
1846  "introduction point auth-key") < 0) {
1847  goto err;
1848  }
1849  /* Validate authentication certificate with descriptor signing key. */
1851  &desc->plaintext_data.signing_pubkey, 0) < 0) {
1852  log_warn(LD_REND, "Invalid authentication key signature: %s",
1854  goto err;
1855  }
1856 
1857  /* Exactly one "enc-key" SP "ntor" SP key NL */
1858  tok = find_by_keyword(tokens, R3_INTRO_ENC_KEY);
1859  if (!strcmp(tok->args[0], "ntor")) {
1860  /* This field is using GE(2) so for possible forward compatibility, we
1861  * accept more fields but must be at least 2. */
1862  tor_assert(tok->n_args >= 2);
1863 
1864  if (curve25519_public_from_base64(&ip->enc_key, tok->args[1]) < 0) {
1865  log_warn(LD_REND, "Introduction point ntor enc-key is invalid");
1866  goto err;
1867  }
1868  } else {
1869  /* Unknown key type so we can't use that introduction point. */
1870  log_warn(LD_REND, "Introduction point encryption key is unrecognized.");
1871  goto err;
1872  }
1873 
1874  /* Exactly once "enc-key-cert" NL certificate NL */
1875  tok = find_by_keyword(tokens, R3_INTRO_ENC_KEY_CERT);
1876  tor_assert(tok->object_body);
1877  /* Do the cross certification. */
1878  if (strcmp(tok->object_type, "ED25519 CERT")) {
1879  log_warn(LD_REND, "Introduction point ntor encryption key "
1880  "cross-certification has an unknown format.");
1881  goto err;
1882  }
1884  tok->object_size, CERT_TYPE_CROSS_HS_IP_KEYS,
1885  "introduction point enc-key-cert") < 0) {
1886  goto err;
1887  }
1889  &desc->plaintext_data.signing_pubkey, 0) < 0) {
1890  log_warn(LD_REND, "Invalid encryption key signature: %s",
1892  goto err;
1893  }
1894  /* It is successfully cross certified. Flag the object. */
1895  ip->cross_certified = 1;
1896 
1897  /* Do we have a "legacy-key" SP key NL ?*/
1898  tok = find_opt_by_keyword(tokens, R3_INTRO_LEGACY_KEY);
1899  if (tok) {
1900  if (decode_intro_legacy_key(tok, tokens, ip, desc) < 0) {
1901  goto err;
1902  }
1903  }
1904 
1905  /* Introduction point has been parsed successfully. */
1906  goto done;
1907 
1908  err:
1909  hs_desc_intro_point_free(ip);
1910  ip = NULL;
1911 
1912  done:
1914  smartlist_free(tokens);
1915  if (area) {
1916  memarea_drop_all(area);
1917  }
1918 
1919  return ip;
1920 }
1921 
1922 /** Given a descriptor string at <b>data</b>, decode all possible introduction
1923  * points that we can find. Add the introduction point object to desc_enc as we
1924  * find them. This function can't fail and it is possible that zero
1925  * introduction points can be decoded. */
1926 static void
1928  hs_desc_encrypted_data_t *desc_enc,
1929  const char *data)
1930 {
1931  smartlist_t *chunked_desc = smartlist_new();
1932  smartlist_t *intro_points = smartlist_new();
1933 
1934  tor_assert(desc);
1935  tor_assert(desc_enc);
1936  tor_assert(data);
1937  tor_assert(desc_enc->intro_points);
1938 
1939  /* Take the desc string, and extract the intro point substrings out of it */
1940  {
1941  /* Split the descriptor string using the intro point header as delimiter */
1942  smartlist_split_string(chunked_desc, data, str_intro_point_start, 0, 0);
1943 
1944  /* Check if there are actually any intro points included. The first chunk
1945  * should be other descriptor fields (e.g. create2-formats), so it's not an
1946  * intro point. */
1947  if (smartlist_len(chunked_desc) < 2) {
1948  goto done;
1949  }
1950  }
1951 
1952  /* Take the intro point substrings, and prepare them for parsing */
1953  {
1954  int i = 0;
1955  /* Prepend the introduction-point header to all the chunks, since
1956  smartlist_split_string() devoured it. */
1957  SMARTLIST_FOREACH_BEGIN(chunked_desc, char *, chunk) {
1958  /* Ignore first chunk. It's other descriptor fields. */
1959  if (i++ == 0) {
1960  continue;
1961  }
1962 
1963  smartlist_add_asprintf(intro_points, "%s %s", str_intro_point, chunk);
1964  } SMARTLIST_FOREACH_END(chunk);
1965  }
1966 
1967  /* Parse the intro points! */
1968  SMARTLIST_FOREACH_BEGIN(intro_points, const char *, intro_point) {
1969  hs_desc_intro_point_t *ip = decode_introduction_point(desc, intro_point);
1970  if (!ip) {
1971  /* Malformed introduction point section. We'll ignore this introduction
1972  * point and continue parsing. New or unknown fields are possible for
1973  * forward compatibility. */
1974  continue;
1975  }
1976  smartlist_add(desc_enc->intro_points, ip);
1977  } SMARTLIST_FOREACH_END(intro_point);
1978 
1979  done:
1980  SMARTLIST_FOREACH(chunked_desc, char *, a, tor_free(a));
1981  smartlist_free(chunked_desc);
1982  SMARTLIST_FOREACH(intro_points, char *, a, tor_free(a));
1983  smartlist_free(intro_points);
1984 }
1985 
1986 /** Return 1 iff the given base64 encoded signature in b64_sig from the encoded
1987  * descriptor in encoded_desc validates the descriptor content. */
1988 STATIC int
1989 desc_sig_is_valid(const char *b64_sig,
1990  const ed25519_public_key_t *signing_pubkey,
1991  const char *encoded_desc, size_t encoded_len)
1992 {
1993  int ret = 0;
1994  ed25519_signature_t sig;
1995  const char *sig_start;
1996 
1997  tor_assert(b64_sig);
1998  tor_assert(signing_pubkey);
1999  tor_assert(encoded_desc);
2000  /* Verifying nothing won't end well :). */
2001  tor_assert(encoded_len > 0);
2002 
2003  /* Signature length check. */
2004  if (strlen(b64_sig) != ED25519_SIG_BASE64_LEN) {
2005  log_warn(LD_REND, "Service descriptor has an invalid signature length."
2006  "Exptected %d but got %lu",
2007  ED25519_SIG_BASE64_LEN, (unsigned long) strlen(b64_sig));
2008  goto err;
2009  }
2010 
2011  /* First, convert base64 blob to an ed25519 signature. */
2012  if (ed25519_signature_from_base64(&sig, b64_sig) != 0) {
2013  log_warn(LD_REND, "Service descriptor does not contain a valid "
2014  "signature");
2015  goto err;
2016  }
2017 
2018  /* Find the start of signature. */
2019  sig_start = tor_memstr(encoded_desc, encoded_len, "\n" str_signature " ");
2020  /* Getting here means the token parsing worked for the signature so if we
2021  * can't find the start of the signature, we have a code flow issue. */
2022  if (!sig_start) {
2023  log_warn(LD_GENERAL, "Malformed signature line. Rejecting.");
2024  goto err;
2025  }
2026  /* Skip newline, it has to go in the signature check. */
2027  sig_start++;
2028 
2029  /* Validate signature with the full body of the descriptor. */
2030  if (ed25519_checksig_prefixed(&sig,
2031  (const uint8_t *) encoded_desc,
2032  sig_start - encoded_desc,
2033  str_desc_sig_prefix,
2034  signing_pubkey) != 0) {
2035  log_warn(LD_REND, "Invalid signature on service descriptor");
2036  goto err;
2037  }
2038  /* Valid signature! All is good. */
2039  ret = 1;
2040 
2041  err:
2042  return ret;
2043 }
2044 
2045 /** Decode descriptor plaintext data for version 3. Given a list of tokens, an
2046  * allocated plaintext object that will be populated and the encoded
2047  * descriptor with its length. The last one is needed for signature
2048  * verification. Unknown tokens are simply ignored so this won't error on
2049  * unknowns but requires that all v3 token be present and valid.
2050  *
2051  * Return 0 on success else a negative value. */
2055  const char *encoded_desc, size_t encoded_len)
2056 {
2057  int ok;
2058  directory_token_t *tok;
2059 
2060  tor_assert(tokens);
2061  tor_assert(desc);
2062  /* Version higher could still use this function to decode most of the
2063  * descriptor and then they decode the extra part. */
2064  tor_assert(desc->version >= 3);
2065 
2066  /* Descriptor lifetime parsing. */
2067  tok = find_by_keyword(tokens, R3_DESC_LIFETIME);
2068  tor_assert(tok->n_args == 1);
2069  desc->lifetime_sec = (uint32_t) tor_parse_ulong(tok->args[0], 10, 0,
2070  UINT32_MAX, &ok, NULL);
2071  if (!ok) {
2072  log_warn(LD_REND, "Service descriptor lifetime value is invalid");
2073  goto err;
2074  }
2075  /* Put it from minute to second. */
2076  desc->lifetime_sec *= 60;
2077  if (desc->lifetime_sec > HS_DESC_MAX_LIFETIME) {
2078  log_warn(LD_REND, "Service descriptor lifetime is too big. "
2079  "Got %" PRIu32 " but max is %d",
2081  goto err;
2082  }
2083 
2084  /* Descriptor signing certificate. */
2085  tok = find_by_keyword(tokens, R3_DESC_SIGNING_CERT);
2086  tor_assert(tok->object_body);
2087  /* Expecting a prop220 cert with the signing key extension, which contains
2088  * the blinded public key. */
2089  if (strcmp(tok->object_type, "ED25519 CERT") != 0) {
2090  log_warn(LD_REND, "Service descriptor signing cert wrong type (%s)",
2091  escaped(tok->object_type));
2092  goto err;
2093  }
2095  tok->object_size, CERT_TYPE_SIGNING_HS_DESC,
2096  "service descriptor signing key") < 0) {
2097  goto err;
2098  }
2099 
2100  /* Copy the public keys into signing_pubkey and blinded_pubkey */
2101  memcpy(&desc->signing_pubkey, &desc->signing_key_cert->signed_key,
2102  sizeof(ed25519_public_key_t));
2103  memcpy(&desc->blinded_pubkey, &desc->signing_key_cert->signing_key,
2104  sizeof(ed25519_public_key_t));
2105 
2106  /* Extract revision counter value. */
2107  tok = find_by_keyword(tokens, R3_REVISION_COUNTER);
2108  tor_assert(tok->n_args == 1);
2109  desc->revision_counter = tor_parse_uint64(tok->args[0], 10, 0,
2110  UINT64_MAX, &ok, NULL);
2111  if (!ok) {
2112  log_warn(LD_REND, "Service descriptor revision-counter is invalid");
2113  goto err;
2114  }
2115 
2116  /* Extract the superencrypted data section. */
2117  tok = find_by_keyword(tokens, R3_SUPERENCRYPTED);
2118  tor_assert(tok->object_body);
2119  if (strcmp(tok->object_type, "MESSAGE") != 0) {
2120  log_warn(LD_REND, "Desc superencrypted data section is invalid");
2121  goto err;
2122  }
2123  /* Make sure the length of the superencrypted blob is valid. */
2125  goto err;
2126  }
2127 
2128  /* Copy the superencrypted blob to the descriptor object so we can handle it
2129  * latter if needed. */
2130  desc->superencrypted_blob = tor_memdup(tok->object_body, tok->object_size);
2132 
2133  /* Extract signature and verify it. */
2134  tok = find_by_keyword(tokens, R3_SIGNATURE);
2135  tor_assert(tok->n_args == 1);
2136  /* First arg here is the actual encoded signature. */
2137  if (!desc_sig_is_valid(tok->args[0], &desc->signing_pubkey,
2138  encoded_desc, encoded_len)) {
2139  goto err;
2140  }
2141 
2142  return HS_DESC_DECODE_OK;
2143  err:
2144  return HS_DESC_DECODE_PLAINTEXT_ERROR;
2145 }
2146 
2147 /** Decode the version 3 superencrypted section of the given descriptor desc.
2148  * The desc_superencrypted_out will be populated with the decoded data. */
2152  desc_superencrypted_out)
2153 {
2154  int ret = HS_DESC_DECODE_SUPERENC_ERROR;
2155  char *message = NULL;
2156  size_t message_len;
2157  memarea_t *area = NULL;
2158  directory_token_t *tok;
2159  smartlist_t *tokens = NULL;
2160  /* Rename the parameter because it is too long. */
2161  hs_desc_superencrypted_data_t *superencrypted = desc_superencrypted_out;
2162 
2163  tor_assert(desc);
2164  tor_assert(desc_superencrypted_out);
2165 
2166  /* Decrypt the superencrypted data that is located in the plaintext section
2167  * in the descriptor as a blob of bytes. */
2168  message_len = desc_decrypt_superencrypted(desc, &message);
2169  if (!message_len) {
2170  log_warn(LD_REND, "Service descriptor decryption failed.");
2171  goto err;
2172  }
2173  tor_assert(message);
2174 
2175  area = memarea_new();
2176  tokens = smartlist_new();
2177  if (tokenize_string(area, message, message + message_len,
2178  tokens, hs_desc_superencrypted_v3_token_table, 0) < 0) {
2179  log_warn(LD_REND, "Superencrypted service descriptor is not parseable.");
2180  goto err;
2181  }
2182 
2183  /* Verify desc auth type */
2184  tok = find_by_keyword(tokens, R3_DESC_AUTH_TYPE);
2185  tor_assert(tok->n_args >= 1);
2186  if (strcmp(tok->args[0], "x25519")) {
2187  log_warn(LD_DIR, "Unrecognized desc auth type");
2188  goto err;
2189  }
2190 
2191  /* Extract desc auth ephemeral key */
2192  tok = find_by_keyword(tokens, R3_DESC_AUTH_KEY);
2193  tor_assert(tok->n_args >= 1);
2195  tok->args[0]) < 0) {
2196  log_warn(LD_DIR, "Bogus desc auth ephemeral key in HS desc");
2197  goto err;
2198  }
2199 
2200  /* Extract desc auth client items */
2201  if (!superencrypted->clients) {
2202  superencrypted->clients = smartlist_new();
2203  }
2204  SMARTLIST_FOREACH_BEGIN(tokens, const directory_token_t *, token) {
2205  if (token->tp == R3_DESC_AUTH_CLIENT) {
2206  tor_assert(token->n_args >= 3);
2207 
2208  hs_desc_authorized_client_t *client =
2209  tor_malloc_zero(sizeof(hs_desc_authorized_client_t));
2210 
2211  if (decode_auth_client(token, client) < 0) {
2212  log_warn(LD_REND, "Descriptor client authorization section can't "
2213  "be decoded.");
2214  tor_free(client);
2215  goto err;
2216  }
2217  smartlist_add(superencrypted->clients, client);
2218  }
2219  } SMARTLIST_FOREACH_END(token);
2220 
2221  /* Extract the encrypted data section. */
2222  tok = find_by_keyword(tokens, R3_ENCRYPTED);
2223  tor_assert(tok->object_body);
2224  if (strcmp(tok->object_type, "MESSAGE") != 0) {
2225  log_warn(LD_REND, "Desc encrypted data section is invalid");
2226  goto err;
2227  }
2228  /* Make sure the length of the encrypted blob is valid. */
2230  goto err;
2231  }
2232 
2233  /* Copy the encrypted blob to the descriptor object so we can handle it
2234  * latter if needed. */
2235  tor_assert(tok->object_size <= INT_MAX);
2236  superencrypted->encrypted_blob = tor_memdup(tok->object_body,
2237  tok->object_size);
2238  superencrypted->encrypted_blob_size = tok->object_size;
2239 
2240  ret = HS_DESC_DECODE_OK;
2241  goto done;
2242 
2243  err:
2244  tor_assert(ret < HS_DESC_DECODE_OK);
2245  hs_desc_superencrypted_data_free_contents(desc_superencrypted_out);
2246 
2247  done:
2248  if (tokens) {
2250  smartlist_free(tokens);
2251  }
2252  if (area) {
2253  memarea_drop_all(area);
2254  }
2255  if (message) {
2256  tor_free(message);
2257  }
2258  return ret;
2259 }
2260 
2261 /** Decode the version 3 encrypted section of the given descriptor desc. The
2262  * desc_encrypted_out will be populated with the decoded data. */
2265  const curve25519_secret_key_t *client_auth_sk,
2266  hs_desc_encrypted_data_t *desc_encrypted_out)
2267 {
2268  int ret = HS_DESC_DECODE_ENCRYPTED_ERROR;
2269  char *message = NULL;
2270  size_t message_len;
2271  memarea_t *area = NULL;
2272  directory_token_t *tok;
2273  smartlist_t *tokens = NULL;
2274 
2275  tor_assert(desc);
2276  tor_assert(desc_encrypted_out);
2277 
2278  /* Decrypt the encrypted data that is located in the superencrypted section
2279  * in the descriptor as a blob of bytes. */
2280  message_len = desc_decrypt_encrypted(desc, client_auth_sk, &message);
2281  if (!message_len) {
2282  /* Two possible situation here. Either we have a client authorization
2283  * configured that didn't work or we do not have any configured for this
2284  * onion address so likely the descriptor is for authorized client only,
2285  * we are not. */
2286  if (client_auth_sk) {
2287  /* At warning level so the client can notice that its client
2288  * authorization is failing. */
2289  log_warn(LD_REND, "Client authorization for requested onion address "
2290  "is invalid. Can't decrypt the descriptor.");
2291  ret = HS_DESC_DECODE_BAD_CLIENT_AUTH;
2292  } else {
2293  /* Inform at notice level that the onion address requested can't be
2294  * reached without client authorization most likely. */
2295  log_notice(LD_REND, "Fail to decrypt descriptor for requested onion "
2296  "address. It is likely requiring client "
2297  "authorization.");
2298  ret = HS_DESC_DECODE_NEED_CLIENT_AUTH;
2299  }
2300  goto err;
2301  }
2302  tor_assert(message);
2303 
2304  area = memarea_new();
2305  tokens = smartlist_new();
2306  if (tokenize_string(area, message, message + message_len,
2307  tokens, hs_desc_encrypted_v3_token_table, 0) < 0) {
2308  log_warn(LD_REND, "Encrypted service descriptor is not parseable.");
2309  goto err;
2310  }
2311 
2312  /* CREATE2 supported cell format. It's mandatory. */
2313  tok = find_by_keyword(tokens, R3_CREATE2_FORMATS);
2314  tor_assert(tok);
2315  decode_create2_list(desc_encrypted_out, tok->args[0]);
2316  /* Must support ntor according to the specification */
2317  if (!desc_encrypted_out->create2_ntor) {
2318  log_warn(LD_REND, "Service create2-formats does not include ntor.");
2319  goto err;
2320  }
2321 
2322  /* Authentication type. It's optional but only once. */
2323  tok = find_opt_by_keyword(tokens, R3_INTRO_AUTH_REQUIRED);
2324  if (tok) {
2325  if (!decode_auth_type(desc_encrypted_out, tok->args[0])) {
2326  log_warn(LD_REND, "Service descriptor authentication type has "
2327  "invalid entry(ies).");
2328  goto err;
2329  }
2330  }
2331 
2332  /* Is this service a single onion service? */
2333  tok = find_opt_by_keyword(tokens, R3_SINGLE_ONION_SERVICE);
2334  if (tok) {
2335  desc_encrypted_out->single_onion_service = 1;
2336  }
2337 
2338  /* Initialize the descriptor's introduction point list before we start
2339  * decoding. Having 0 intro point is valid. Then decode them all. */
2340  desc_encrypted_out->intro_points = smartlist_new();
2341  decode_intro_points(desc, desc_encrypted_out, message);
2342 
2343  /* Validation of maximum introduction points allowed. */
2344  if (smartlist_len(desc_encrypted_out->intro_points) >
2345  HS_CONFIG_V3_MAX_INTRO_POINTS) {
2346  log_warn(LD_REND, "Service descriptor contains too many introduction "
2347  "points. Maximum allowed is %d but we have %d",
2348  HS_CONFIG_V3_MAX_INTRO_POINTS,
2349  smartlist_len(desc_encrypted_out->intro_points));
2350  goto err;
2351  }
2352 
2353  /* NOTE: Unknown fields are allowed because this function could be used to
2354  * decode other descriptor version. */
2355 
2356  ret = HS_DESC_DECODE_OK;
2357  goto done;
2358 
2359  err:
2360  tor_assert(ret < HS_DESC_DECODE_OK);
2361  hs_desc_encrypted_data_free_contents(desc_encrypted_out);
2362 
2363  done:
2364  if (tokens) {
2366  smartlist_free(tokens);
2367  }
2368  if (area) {
2369  memarea_drop_all(area);
2370  }
2371  if (message) {
2372  tor_free(message);
2373  }
2374  return ret;
2375 }
2376 
2377 /** Table of encrypted decode function version specific. The function are
2378  * indexed by the version number so v3 callback is at index 3 in the array. */
2381  const hs_descriptor_t *desc,
2382  const curve25519_secret_key_t *client_auth_sk,
2383  hs_desc_encrypted_data_t *desc_encrypted) =
2384 {
2385  /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
2387 };
2388 
2389 /** Decode the encrypted data section of the given descriptor and store the
2390  * data in the given encrypted data object. Return 0 on success else a
2391  * negative value on error. */
2394  const curve25519_secret_key_t *client_auth_sk,
2395  hs_desc_encrypted_data_t *desc_encrypted)
2396 {
2397  int ret = HS_DESC_DECODE_ENCRYPTED_ERROR;
2398  uint32_t version;
2399 
2400  tor_assert(desc);
2401  /* Ease our life a bit. */
2402  version = desc->plaintext_data.version;
2403  tor_assert(desc_encrypted);
2404  /* Calling this function without an encrypted blob to parse is a code flow
2405  * error. The superencrypted parsing should never succeed in the first place
2406  * without an encrypted section. */
2408  /* Let's make sure we have a supported version as well. By correctly parsing
2409  * the plaintext, this should not fail. */
2410  if (BUG(!hs_desc_is_supported_version(version))) {
2411  goto err;
2412  }
2413  /* Extra precaution. Having no handler for the supported version should
2414  * never happened else we forgot to add it but we bumped the version. */
2417 
2418  /* Run the version specific plaintext decoder. */
2419  ret = decode_encrypted_handlers[version](desc, client_auth_sk,
2420  desc_encrypted);
2421  if (ret < 0) {
2422  goto err;
2423  }
2424 
2425  err:
2426  return ret;
2427 }
2428 
2429 /** Table of superencrypted decode function version specific. The function are
2430  * indexed by the version number so v3 callback is at index 3 in the array. */
2433  const hs_descriptor_t *desc,
2434  hs_desc_superencrypted_data_t *desc_superencrypted) =
2435 {
2436  /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
2438 };
2439 
2440 /** Decode the superencrypted data section of the given descriptor and store
2441  * the data in the given superencrypted data object. */
2445  desc_superencrypted)
2446 {
2447  int ret = HS_DESC_DECODE_SUPERENC_ERROR;
2448  uint32_t version;
2449 
2450  tor_assert(desc);
2451  /* Ease our life a bit. */
2452  version = desc->plaintext_data.version;
2453  tor_assert(desc_superencrypted);
2454  /* Calling this function without an superencrypted blob to parse is
2455  * a code flow error. The plaintext parsing should never succeed in
2456  * the first place without an superencrypted section. */
2458  /* Let's make sure we have a supported version as well. By correctly parsing
2459  * the plaintext, this should not fail. */
2460  if (BUG(!hs_desc_is_supported_version(version))) {
2461  goto err;
2462  }
2463  /* Extra precaution. Having no handler for the supported version should
2464  * never happened else we forgot to add it but we bumped the version. */
2467 
2468  /* Run the version specific plaintext decoder. */
2469  ret = decode_superencrypted_handlers[version](desc, desc_superencrypted);
2470  if (ret < 0) {
2471  goto err;
2472  }
2473 
2474  err:
2475  return ret;
2476 }
2477 
2478 /** Table of plaintext decode function version specific. The function are
2479  * indexed by the version number so v3 callback is at index 3 in the array. */
2482  smartlist_t *tokens,
2484  const char *encoded_desc,
2485  size_t encoded_len) =
2486 {
2487  /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
2489 };
2490 
2491 /** Fully decode the given descriptor plaintext and store the data in the
2492  * plaintext data object. */
2494 hs_desc_decode_plaintext(const char *encoded,
2495  hs_desc_plaintext_data_t *plaintext)
2496 {
2497  int ok = 0, ret = HS_DESC_DECODE_PLAINTEXT_ERROR;
2498  memarea_t *area = NULL;
2499  smartlist_t *tokens = NULL;
2500  size_t encoded_len;
2501  directory_token_t *tok;
2502 
2503  tor_assert(encoded);
2504  tor_assert(plaintext);
2505 
2506  /* Check that descriptor is within size limits. */
2507  encoded_len = strlen(encoded);
2508  if (encoded_len >= hs_cache_get_max_descriptor_size()) {
2509  log_warn(LD_REND, "Service descriptor is too big (%lu bytes)",
2510  (unsigned long) encoded_len);
2511  goto err;
2512  }
2513 
2514  area = memarea_new();
2515  tokens = smartlist_new();
2516  /* Tokenize the descriptor so we can start to parse it. */
2517  if (tokenize_string(area, encoded, encoded + encoded_len, tokens,
2518  hs_desc_v3_token_table, 0) < 0) {
2519  log_warn(LD_REND, "Service descriptor is not parseable");
2520  goto err;
2521  }
2522 
2523  /* Get the version of the descriptor which is the first mandatory field of
2524  * the descriptor. From there, we'll decode the right descriptor version. */
2525  tok = find_by_keyword(tokens, R_HS_DESCRIPTOR);
2526  tor_assert(tok->n_args == 1);
2527  plaintext->version = (uint32_t) tor_parse_ulong(tok->args[0], 10, 0,
2528  UINT32_MAX, &ok, NULL);
2529  if (!ok) {
2530  log_warn(LD_REND, "Service descriptor has unparseable version %s",
2531  escaped(tok->args[0]));
2532  goto err;
2533  }
2534  if (!hs_desc_is_supported_version(plaintext->version)) {
2535  log_warn(LD_REND, "Service descriptor has unsupported version %" PRIu32,
2536  plaintext->version);
2537  goto err;
2538  }
2539  /* Extra precaution. Having no handler for the supported version should
2540  * never happened else we forgot to add it but we bumped the version. */
2543 
2544  /* Run the version specific plaintext decoder. */
2545  ret = decode_plaintext_handlers[plaintext->version](tokens, plaintext,
2546  encoded, encoded_len);
2547  if (ret != HS_DESC_DECODE_OK) {
2548  goto err;
2549  }
2550  /* Success. Descriptor has been populated with the data. */
2551  ret = HS_DESC_DECODE_OK;
2552 
2553  err:
2554  if (tokens) {
2556  smartlist_free(tokens);
2557  }
2558  if (area) {
2559  memarea_drop_all(area);
2560  }
2561  return ret;
2562 }
2563 
2564 /** Fully decode an encoded descriptor and set a newly allocated descriptor
2565  * object in desc_out. Client secret key is used to decrypt the "encrypted"
2566  * section if not NULL else it's ignored.
2567  *
2568  * Return 0 on success. A negative value is returned on error and desc_out is
2569  * set to NULL. */
2571 hs_desc_decode_descriptor(const char *encoded,
2572  const hs_subcredential_t *subcredential,
2573  const curve25519_secret_key_t *client_auth_sk,
2574  hs_descriptor_t **desc_out)
2575 {
2576  hs_desc_decode_status_t ret = HS_DESC_DECODE_GENERIC_ERROR;
2577  hs_descriptor_t *desc;
2578 
2579  tor_assert(encoded);
2580 
2581  desc = tor_malloc_zero(sizeof(hs_descriptor_t));
2582 
2583  /* Subcredentials are not optional. */
2584  if (BUG(!subcredential ||
2585  fast_mem_is_zero((char*)subcredential, DIGEST256_LEN))) {
2586  log_warn(LD_GENERAL, "Tried to decrypt without subcred. Impossible!");
2587  goto err;
2588  }
2589 
2590  memcpy(&desc->subcredential, subcredential, sizeof(desc->subcredential));
2591 
2592  ret = hs_desc_decode_plaintext(encoded, &desc->plaintext_data);
2593  if (ret != HS_DESC_DECODE_OK) {
2594  goto err;
2595  }
2596 
2598  if (ret != HS_DESC_DECODE_OK) {
2599  goto err;
2600  }
2601 
2602  ret = hs_desc_decode_encrypted(desc, client_auth_sk, &desc->encrypted_data);
2603  if (ret != HS_DESC_DECODE_OK) {
2604  goto err;
2605  }
2606 
2607  if (desc_out) {
2608  *desc_out = desc;
2609  } else {
2610  hs_descriptor_free(desc);
2611  }
2612  return ret;
2613 
2614  err:
2615  hs_descriptor_free(desc);
2616  if (desc_out) {
2617  *desc_out = NULL;
2618  }
2619 
2620  tor_assert(ret < 0);
2621  return ret;
2622 }
2623 
2624 /** Table of encode function version specific. The functions are indexed by the
2625  * version number so v3 callback is at index 3 in the array. */
2626 static int
2627  (*encode_handlers[])(
2628  const hs_descriptor_t *desc,
2629  const ed25519_keypair_t *signing_kp,
2630  const uint8_t *descriptor_cookie,
2631  char **encoded_out) =
2632 {
2633  /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
2635 };
2636 
2637 /** Encode the given descriptor desc including signing with the given key pair
2638  * signing_kp and encrypting with the given descriptor cookie.
2639  *
2640  * If the client authorization is enabled, descriptor_cookie must be the same
2641  * as the one used to build hs_desc_authorized_client_t in the descriptor.
2642  * Otherwise, it must be NULL. On success, encoded_out points to a newly
2643  * allocated NUL terminated string that contains the encoded descriptor as
2644  * a string.
2645  *
2646  * Return 0 on success and encoded_out is a valid pointer. On error, -1 is
2647  * returned and encoded_out is set to NULL. */
2648 MOCK_IMPL(int,
2650  const ed25519_keypair_t *signing_kp,
2651  const uint8_t *descriptor_cookie,
2652  char **encoded_out))
2653 {
2654  int ret = -1;
2655  uint32_t version;
2656 
2657  tor_assert(desc);
2658  tor_assert(encoded_out);
2659 
2660  /* Make sure we support the version of the descriptor format. */
2661  version = desc->plaintext_data.version;
2662  if (!hs_desc_is_supported_version(version)) {
2663  goto err;
2664  }
2665  /* Extra precaution. Having no handler for the supported version should
2666  * never happened else we forgot to add it but we bumped the version. */
2668  tor_assert(encode_handlers[version]);
2669 
2670  ret = encode_handlers[version](desc, signing_kp,
2671  descriptor_cookie, encoded_out);
2672  if (ret < 0) {
2673  goto err;
2674  }
2675 
2676  /* Try to decode what we just encoded. Symmetry is nice!, but it is
2677  * symmetric only if the client auth is disabled. That is, the descriptor
2678  * cookie will be NULL. */
2679  if (!descriptor_cookie) {
2680  ret = hs_desc_decode_descriptor(*encoded_out, &desc->subcredential,
2681  NULL, NULL);
2682  if (BUG(ret != HS_DESC_DECODE_OK)) {
2683  ret = -1;
2684  goto err;
2685  }
2686  }
2687 
2688  return 0;
2689 
2690  err:
2691  *encoded_out = NULL;
2692  return ret;
2693 }
2694 
2695 /** Free the content of the plaintext section of a descriptor. */
2696 void
2698 {
2699  if (!desc) {
2700  return;
2701  }
2702 
2703  if (desc->superencrypted_blob) {
2705  }
2706  tor_cert_free(desc->signing_key_cert);
2707 
2708  memwipe(desc, 0, sizeof(*desc));
2709 }
2710 
2711 /** Free the content of the superencrypted section of a descriptor. */
2712 void
2714 {
2715  if (!desc) {
2716  return;
2717  }
2718 
2719  if (desc->encrypted_blob) {
2720  tor_free(desc->encrypted_blob);
2721  }
2722  if (desc->clients) {
2724  hs_desc_authorized_client_free(client));
2725  smartlist_free(desc->clients);
2726  }
2727 
2728  memwipe(desc, 0, sizeof(*desc));
2729 }
2730 
2731 /** Free the content of the encrypted section of a descriptor. */
2732 void
2734 {
2735  if (!desc) {
2736  return;
2737  }
2738 
2739  if (desc->intro_auth_types) {
2740  SMARTLIST_FOREACH(desc->intro_auth_types, char *, a, tor_free(a));
2741  smartlist_free(desc->intro_auth_types);
2742  }
2743  if (desc->intro_points) {
2745  hs_desc_intro_point_free(ip));
2746  smartlist_free(desc->intro_points);
2747  }
2748  memwipe(desc, 0, sizeof(*desc));
2749 }
2750 
2751 /** Free the descriptor plaintext data object. */
2752 void
2754 {
2756  tor_free(desc);
2757 }
2758 
2759 /** Free the descriptor plaintext data object. */
2760 void
2762 {
2764  tor_free(desc);
2765 }
2766 
2767 /** Free the descriptor encrypted data object. */
2768 void
2770 {
2772  tor_free(desc);
2773 }
2774 
2775 /** Free the given descriptor object. */
2776 void
2778 {
2779  if (!desc) {
2780  return;
2781  }
2782 
2786  tor_free(desc);
2787 }
2788 
2789 /** Return the size in bytes of the given plaintext data object. A sizeof() is
2790  * not enough because the object contains pointers and the encrypted blob.
2791  * This is particularly useful for our OOM subsystem that tracks the HSDir
2792  * cache size for instance. */
2793 size_t
2795 {
2796  tor_assert(data);
2797  return (sizeof(*data) + sizeof(*data->signing_key_cert) +
2798  data->superencrypted_blob_size);
2799 }
2800 
2801 /** Return the size in bytes of the given encrypted data object. Used by OOM
2802  * subsystem. */
2803 static size_t
2805 {
2806  tor_assert(data);
2807  size_t intro_size = 0;
2808  if (data->intro_auth_types) {
2809  intro_size +=
2810  smartlist_len(data->intro_auth_types) * sizeof(intro_auth_types);
2811  }
2812  if (data->intro_points) {
2813  /* XXX could follow pointers here and get more accurate size */
2814  intro_size +=
2815  smartlist_len(data->intro_points) * sizeof(hs_desc_intro_point_t);
2816  }
2817 
2818  return sizeof(*data) + intro_size;
2819 }
2820 
2821 /** Return the size in bytes of the given descriptor object. Used by OOM
2822  * subsystem. */
2823  size_t
2825 {
2826  if (data == NULL) {
2827  return 0;
2828  }
2829  return (hs_desc_plaintext_obj_size(&data->plaintext_data) +
2831  sizeof(data->subcredential));
2832 }
2833 
2834 /** Return a newly allocated descriptor intro point. */
2837 {
2838  hs_desc_intro_point_t *ip = tor_malloc_zero(sizeof(*ip));
2840  return ip;
2841 }
2842 
2843 /** Free a descriptor intro point object. */
2844 void
2846 {
2847  if (ip == NULL) {
2848  return;
2849  }
2850  if (ip->link_specifiers) {
2851  SMARTLIST_FOREACH(ip->link_specifiers, link_specifier_t *,
2852  ls, link_specifier_free(ls));
2853  smartlist_free(ip->link_specifiers);
2854  }
2855  tor_cert_free(ip->auth_key_cert);
2856  tor_cert_free(ip->enc_key_cert);
2857  crypto_pk_free(ip->legacy.key);
2858  tor_free(ip->legacy.cert.encoded);
2859  tor_free(ip);
2860 }
2861 
2862 /** Allocate and build a new fake client info for the descriptor. Return a
2863  * newly allocated object. This can't fail. */
2866 {
2867  hs_desc_authorized_client_t *client_auth =
2868  tor_malloc_zero(sizeof(*client_auth));
2869 
2870  crypto_rand((char *) client_auth->client_id,
2871  sizeof(client_auth->client_id));
2872  crypto_rand((char *) client_auth->iv,
2873  sizeof(client_auth->iv));
2874  crypto_rand((char *) client_auth->encrypted_cookie,
2875  sizeof(client_auth->encrypted_cookie));
2876 
2877  return client_auth;
2878 }
2879 
2880 /** Using the service's subcredential, client public key, auth ephemeral secret
2881  * key, and descriptor cookie, build the auth client so we can then encode the
2882  * descriptor for publication. client_out must be already allocated. */
2883 void
2885  const curve25519_public_key_t *client_auth_pk,
2886  const curve25519_secret_key_t *
2887  auth_ephemeral_sk,
2888  const uint8_t *descriptor_cookie,
2889  hs_desc_authorized_client_t *client_out)
2890 {
2891  uint8_t *keystream = NULL;
2892  size_t keystream_length = 0;
2893  const uint8_t *cookie_key;
2894  crypto_cipher_t *cipher;
2895 
2896  tor_assert(client_auth_pk);
2897  tor_assert(auth_ephemeral_sk);
2898  tor_assert(descriptor_cookie);
2899  tor_assert(client_out);
2900  tor_assert(subcredential);
2901  tor_assert(!fast_mem_is_zero((char *) auth_ephemeral_sk,
2902  sizeof(*auth_ephemeral_sk)));
2903  tor_assert(!fast_mem_is_zero((char *) client_auth_pk,
2904  sizeof(*client_auth_pk)));
2905  tor_assert(!fast_mem_is_zero((char *) descriptor_cookie,
2906  HS_DESC_DESCRIPTOR_COOKIE_LEN));
2907  tor_assert(!fast_mem_is_zero((char *) subcredential,
2908  DIGEST256_LEN));
2909 
2910  /* Get the KEYS part so we can derive the CLIENT-ID and COOKIE-KEY. */
2911  keystream_length =
2912  build_descriptor_cookie_keys(subcredential,
2913  auth_ephemeral_sk, client_auth_pk,
2914  &keystream);
2915  tor_assert(keystream_length > 0);
2916 
2917  /* Extract the CLIENT-ID and COOKIE-KEY from the KEYS. */
2918  memcpy(client_out->client_id, keystream, HS_DESC_CLIENT_ID_LEN);
2919  cookie_key = keystream + HS_DESC_CLIENT_ID_LEN;
2920 
2921  /* Random IV */
2922  crypto_strongest_rand(client_out->iv, sizeof(client_out->iv));
2923 
2924  /* This creates a cipher for AES. It can't fail. */
2925  cipher = crypto_cipher_new_with_iv_and_bits(cookie_key, client_out->iv,
2926  HS_DESC_COOKIE_KEY_BIT_SIZE);
2927  /* This can't fail. */
2928  crypto_cipher_encrypt(cipher, (char *) client_out->encrypted_cookie,
2929  (const char *) descriptor_cookie,
2930  HS_DESC_DESCRIPTOR_COOKIE_LEN);
2931 
2932  memwipe(keystream, 0, keystream_length);
2933  tor_free(keystream);
2934 
2935  crypto_cipher_free(cipher);
2936 }
2937 
2938 /** Free an authoriezd client object. */
2939 void
2941 {
2942  tor_free(client);
2943 }
2944 
2945 /** From the given descriptor, remove and free every introduction point. */
2946 void
2948 {
2949  smartlist_t *ips;
2950 
2951  tor_assert(desc);
2952 
2953  ips = desc->encrypted_data.intro_points;
2954  if (ips) {
2956  ip, hs_desc_intro_point_free(ip));
2957  smartlist_clear(ips);
2958  }
2959 }
log_fn
#define log_fn(severity, domain, args,...)
Definition: log.h:283
tor_free
#define tor_free(p)
Definition: malloc.h:52
hs_desc_authorized_client_free_
void hs_desc_authorized_client_free_(hs_desc_authorized_client_t *client)
Definition: hs_descriptor.c:2940
decode_encrypted_handlers
static hs_desc_decode_status_t(* decode_encrypted_handlers[])(const hs_descriptor_t *desc, const curve25519_secret_key_t *client_auth_sk, hs_desc_encrypted_data_t *desc_encrypted)
Definition: hs_descriptor.c:2380
build_descriptor_cookie_keys
static size_t build_descriptor_cookie_keys(const hs_subcredential_t *subcredential, const curve25519_secret_key_t *sk, const curve25519_public_key_t *pk, uint8_t **keys_out)
Definition: hs_descriptor.c:1376
CURVE25519_PUBKEY_LEN
#define CURVE25519_PUBKEY_LEN
Definition: x25519_sizes.h:20
hs_desc_encrypted_data_free_contents
void hs_desc_encrypted_data_free_contents(hs_desc_encrypted_data_t *desc)
Definition: hs_descriptor.c:2733
crypto_xof_free
#define crypto_xof_free(xof)
Definition: crypto_digest.h:158
T1_START
#define T1_START(s, t, a, o)
Definition: parsecommon.h:252
smartlist_split_string
int smartlist_split_string(smartlist_t *sl, const char *str, const char *sep, int flags, int max)
Definition: smartlist_split.c:37
hs_desc_superencrypted_data_free_
void hs_desc_superencrypted_data_free_(hs_desc_superencrypted_data_t *desc)
Definition: hs_descriptor.c:2761
tor_cert_t::cert_expired
unsigned cert_expired
Definition: torcert.h:54
HS_DESC_CERT_LIFETIME
#define HS_DESC_CERT_LIFETIME
Definition: hs_descriptor.h:38
hs_desc_decode_status_t
hs_desc_decode_status_t
Definition: hs_descriptor.h:74
tor_cert_t
Definition: torcert.h:30
memwipe
void memwipe(void *mem, uint8_t byte, size_t sz)
Definition: crypto_util.c:55
encode_link_specifiers
STATIC char * encode_link_specifiers(const smartlist_t *specs)
Definition: hs_descriptor.c:317
approx_time
time_t approx_time(void)
Definition: approx_time.c:32
MOCK_IMPL
#define MOCK_IMPL(rv, funcname, arglist)
Definition: testsupport.h:133
ed25519_sign_prefixed
int ed25519_sign_prefixed(ed25519_signature_t *signature_out, const uint8_t *msg, size_t msg_len, const char *prefix_str, const ed25519_keypair_t *keypair)
Definition: crypto_ed25519.c:292
NEED_KEY_1024
@ NEED_KEY_1024
Definition: parsecommon.h:222
END_OF_TABLE
#define END_OF_TABLE
Definition: parsecommon.h:244
hs_desc_plaintext_data_free_
void hs_desc_plaintext_data_free_(hs_desc_plaintext_data_t *desc)
Definition: hs_descriptor.c:2753
hs_desc_encrypted_data_t
Definition: hs_descriptor.h:158
tokenize_string
int tokenize_string(memarea_t *area, const char *start, const char *end, smartlist_t *out, const token_rule_t *table, int flags)
Definition: parsecommon.c:53
tor_assert
#define tor_assert(expr)
Definition: util_bug.h:102
hs_desc_intro_point_t::link_specifiers
smartlist_t * link_specifiers
Definition: hs_descriptor.h:102
hs_desc_superencrypted_data_t::encrypted_blob_size
size_t encrypted_blob_size
Definition: hs_descriptor.h:189
LD_BUG
#define LD_BUG
Definition: log.h:86
format_iso_time
void format_iso_time(char *buf, time_t t)
Definition: time_fmt.c:295
fast_mem_is_zero
int fast_mem_is_zero(const char *mem, size_t len)
Definition: util_string.c:74
tor_cert_t::valid_until
time_t valid_until
Definition: torcert.h:37
memarea.h
Header for memarea.c.
CURVE25519_BASE64_PADDED_LEN
#define CURVE25519_BASE64_PADDED_LEN
Definition: x25519_sizes.h:37
hs_cache_get_max_descriptor_size
unsigned int hs_cache_get_max_descriptor_size(void)
Definition: hs_cache.c:1111
LD_GENERAL
#define LD_GENERAL
Definition: log.h:62
crypto_pk_dup_key
crypto_pk_t * crypto_pk_dup_key(crypto_pk_t *orig)
Definition: crypto_rsa_nss.c:351
decode_intro_legacy_key
static int decode_intro_legacy_key(const directory_token_t *tok, smartlist_t *tokens, hs_desc_intro_point_t *ip, const hs_descriptor_t *desc)
Definition: hs_descriptor.c:1696
directory_token_t
Definition: parsecommon.h:201
T1N
#define T1N(s, t, a, o)
Definition: parsecommon.h:256
NO_OBJ
@ NO_OBJ
Definition: parsecommon.h:219
memarea_drop_all
#define memarea_drop_all(area)
Definition: memarea.h:22
hs_desc_build_fake_authorized_client
hs_desc_authorized_client_t * hs_desc_build_fake_authorized_client(void)
Definition: hs_descriptor.c:2865
decode_plaintext_handlers
static hs_desc_decode_status_t(* decode_plaintext_handlers[])(smartlist_t *tokens, hs_desc_plaintext_data_t *desc, const char *encoded_desc, size_t encoded_len)
Definition: hs_descriptor.c:2481
build_kdf_key
static void build_kdf_key(const hs_descriptor_t *desc, const uint8_t *secret_data, size_t secret_data_len, const uint8_t *salt, size_t salt_len, uint8_t *key_out, size_t key_out_len, int is_superencrypted_layer)
Definition: hs_descriptor.c:232
tor_parse_uint64
uint64_t tor_parse_uint64(const char *s, int base, uint64_t min, uint64_t max, int *ok, char **next)
Definition: parse_int.c:110
smartlist_add
void smartlist_add(smartlist_t *sl, void *element)
Definition: smartlist_core.c:117
crypto_cipher_new_with_iv_and_bits
crypto_cipher_t * crypto_cipher_new_with_iv_and_bits(const uint8_t *key, const uint8_t *iv, int bits)
Definition: crypto_cipher.c:29
hs_descriptor_t::plaintext_data
hs_desc_plaintext_data_t plaintext_data
Definition: hs_descriptor.h:228
hs_desc_v3_token_table
static token_rule_t hs_desc_v3_token_table[]
Definition: hs_descriptor.c:118
hs_desc_plaintext_data_t::version
uint32_t version
Definition: hs_descriptor.h:196
hs_desc_plaintext_data_t::signing_pubkey
ed25519_public_key_t signing_pubkey
Definition: hs_descriptor.h:207
desc_decode_plaintext_v3
static hs_desc_decode_status_t desc_decode_plaintext_v3(smartlist_t *tokens, hs_desc_plaintext_data_t *desc, const char *encoded_desc, size_t encoded_len)
Definition: hs_descriptor.c:2053
hs_desc_decode_encrypted
hs_desc_decode_status_t hs_desc_decode_encrypted(const hs_descriptor_t *desc, const curve25519_secret_key_t *client_auth_sk, hs_desc_encrypted_data_t *desc_encrypted)
Definition: hs_descriptor.c:2393
token_clear
void token_clear(directory_token_t *tok)
Definition: parsecommon.c:41
HS_DESC_ENCRYPTED_SALT_LEN
#define HS_DESC_ENCRYPTED_SALT_LEN
Definition: hs_descriptor.h:40
tor_cert_t::signing_key_included
unsigned signing_key_included
Definition: torcert.h:47
hs_desc_authorized_client_t::iv
uint8_t iv[CIPHER_IV_LEN]
Definition: hs_descriptor.h:149
crypto_cipher_encrypt
int crypto_cipher_encrypt(crypto_cipher_t *env, char *to, const char *from, size_t fromlen)
Definition: crypto_cipher.c:88
directory_token_t::args
char ** args
Definition: parsecommon.h:204
hs_desc_obj_size
size_t hs_desc_obj_size(const hs_descriptor_t *data)
Definition: hs_descriptor.c:2824
ED25519_PUBKEY_LEN
#define ED25519_PUBKEY_LEN
Definition: x25519_sizes.h:27
get_all_auth_client_lines
static char * get_all_auth_client_lines(const hs_descriptor_t *desc)
Definition: hs_descriptor.c:707
hs_desc_plaintext_obj_size
size_t hs_desc_plaintext_obj_size(const hs_desc_plaintext_data_t *data)
Definition: hs_descriptor.c:2794
NEED_OBJ
@ NEED_OBJ
Definition: parsecommon.h:220
crypto_digest_add_bytes
void crypto_digest_add_bytes(crypto_digest_t *digest, const char *data, size_t len)
Definition: crypto_digest_nss.c:308
tor_cert_checksig
int tor_cert_checksig(tor_cert_t *cert, const ed25519_public_key_t *pubkey, time_t now)
Definition: torcert.c:244
encode_onion_key
static char * encode_onion_key(const hs_desc_intro_point_t *ip)
Definition: hs_descriptor.c:426
smartlist_new
smartlist_t * smartlist_new(void)
Definition: smartlist_core.c:26
hs_desc_intro_point_t::auth_key_cert
tor_cert_t * auth_key_cert
Definition: hs_descriptor.h:111
ed25519_signature_from_base64
int ed25519_signature_from_base64(ed25519_signature_t *sig, const char *input)
Definition: crypto_format.c:255
base64_encode
int base64_encode(char *dest, size_t destlen, const char *src, size_t srclen, int flags)
Definition: binascii.c:215
crypto_digest_t
Definition: crypto_digest_nss.c:166
hs_desc_superencrypted_data_t::clients
smartlist_t * clients
Definition: hs_descriptor.h:183
decrypt_descriptor_cookie
static int decrypt_descriptor_cookie(const hs_descriptor_t *desc, const hs_desc_authorized_client_t *client, const curve25519_secret_key_t *client_auth_sk, uint8_t **descriptor_cookie_out)
Definition: hs_descriptor.c:1415
encode_intro_point
static char * encode_intro_point(const ed25519_public_key_t *sig_key, const hs_desc_intro_point_t *ip)
Definition: hs_descriptor.c:443
hs_desc_encrypted_data_t::single_onion_service
unsigned int single_onion_service
Definition: hs_descriptor.h:168
SMARTLIST_FOREACH
#define SMARTLIST_FOREACH(sl, type, var, cmd)
Definition: smartlist_foreach.h:112
encrypt_desc_data_and_base64
static char * encrypt_desc_data_and_base64(const hs_descriptor_t *desc, const uint8_t *secret_data, size_t secret_data_len, const char *encoded_str, int is_superencrypted_layer)
Definition: hs_descriptor.c:857
hs_desc_intro_point_t::legacy
struct hs_desc_intro_point_t::@16 legacy
hs_desc_encrypted_data_t::intro_auth_types
smartlist_t * intro_auth_types
Definition: hs_descriptor.h:165
compute_padded_plaintext_length
static size_t compute_padded_plaintext_length(size_t plaintext_len)
Definition: hs_descriptor.c:513
hs_desc_is_supported_version
static int hs_desc_is_supported_version(uint32_t version)
Definition: hs_descriptor.h:247
crypto_xof_new
crypto_xof_t * crypto_xof_new(void)
Definition: crypto_digest.c:166
build_encrypted
static size_t build_encrypted(const uint8_t *key, const uint8_t *iv, const char *plaintext, size_t plaintext_len, uint8_t **encrypted_out, int is_superencrypted_layer)
Definition: hs_descriptor.c:557
build_secret_input
static size_t build_secret_input(const hs_descriptor_t *desc, const uint8_t *secret_data, size_t secret_data_len, uint8_t **secret_input_out)
Definition: hs_descriptor.c:197
hs_desc_intro_point_v3_token_table
static token_rule_t hs_desc_intro_point_v3_token_table[]
Definition: hs_descriptor.c:146
build_secret_data
static size_t build_secret_data(const ed25519_public_key_t *blinded_pubkey, const uint8_t *descriptor_cookie, uint8_t **secret_data_out)
Definition: hs_descriptor.c:894
tor_memeq
int tor_memeq(const void *a, const void *b, size_t sz)
Definition: di_ops.c:107
hs_desc_decode_plaintext
hs_desc_decode_status_t hs_desc_decode_plaintext(const char *encoded, hs_desc_plaintext_data_t *plaintext)
Definition: hs_descriptor.c:2494
hs_desc_auth_type_t
hs_desc_auth_type_t
Definition: hs_descriptor.h:69
encrypt_descriptor_data
static size_t encrypt_descriptor_data(const hs_descriptor_t *desc, const uint8_t *secret_data, size_t secret_data_len, const char *plaintext, char **encrypted_out, int is_superencrypted_layer)
Definition: hs_descriptor.c:603
crypto_util.h
Common functions for cryptographic routines.
hs_cache.h
Header file for hs_cache.c.
decode_auth_type
static int decode_auth_type(hs_desc_encrypted_data_t *desc, const char *list)
Definition: hs_descriptor.c:1206
base64_encode_size
size_t base64_encode_size(size_t srclen, int flags)
Definition: binascii.c:166
hs_desc_intro_point_free_
void hs_desc_intro_point_free_(hs_desc_intro_point_t *ip)
Definition: hs_descriptor.c:2845
find_all_by_keyword
smartlist_t * find_all_by_keyword(const smartlist_t *s, directory_keyword k)
Definition: parsecommon.c:468
decrypt_desc_layer
STATIC size_t decrypt_desc_layer(const hs_descriptor_t *desc, const uint8_t *descriptor_cookie, bool is_superencrypted_layer, char **decrypted_out)
Definition: hs_descriptor.c:1493
hs_desc_intro_point_t::enc_key
curve25519_public_key_t enc_key
Definition: hs_descriptor.h:114
T01
#define T01(s, t, a, o)
Definition: parsecommon.h:258
encrypted_data_length_is_valid
STATIC int encrypted_data_length_is_valid(size_t len)
Definition: hs_descriptor.c:1350
HS_DESC_CLIENT_ID_LEN
#define HS_DESC_CLIENT_ID_LEN
Definition: hs_descriptor.h:58
SIZE_T_CEILING
#define SIZE_T_CEILING
Definition: torint.h:126
directory_token_t::n_args
int n_args
Definition: parsecommon.h:203
hs_desc_superencrypted_data_t::auth_ephemeral_pubkey
curve25519_public_key_t auth_ephemeral_pubkey
Definition: hs_descriptor.h:179
hs_desc_plaintext_data_t::revision_counter
uint64_t revision_counter
Definition: hs_descriptor.h:216
ARGS
#define ARGS
Definition: parsecommon.h:263
EQ
#define EQ(n)
Definition: parsecommon.h:271
HS_DESC_ENCRYPTED_KDF_OUTPUT_LEN
#define HS_DESC_ENCRYPTED_KDF_OUTPUT_LEN
Definition: hs_descriptor.h:43
HS_DESC_AUTH_CLIENT_MULTIPLE
#define HS_DESC_AUTH_CLIENT_MULTIPLE
Definition: hs_descriptor.h:66
hs_desc_authorized_client_t::encrypted_cookie
uint8_t encrypted_cookie[HS_DESC_ENCRYPED_COOKIE_LEN]
Definition: hs_descriptor.h:153
crypto_format.h
Header for crypto_format.c.
NO_ARGS
#define NO_ARGS
Definition: parsecommon.h:265
crypto_xof_add_bytes
void crypto_xof_add_bytes(crypto_xof_t *xof, const uint8_t *data, size_t len)
Definition: crypto_digest.c:186
hs_descriptor_clear_intro_points
void hs_descriptor_clear_intro_points(hs_descriptor_t *desc)
Definition: hs_descriptor.c:2947
decode_link_specifiers
STATIC smartlist_t * decode_link_specifiers(const char *encoded)
Definition: hs_descriptor.c:1151
decode_auth_client
static int decode_auth_client(const directory_token_t *tok, hs_desc_authorized_client_t *client)
Definition: hs_descriptor.c:1116
hs_desc_superencrypted_v3_token_table
static token_rule_t hs_desc_superencrypted_v3_token_table[]
Definition: hs_descriptor.c:129
tor_memneq
#define tor_memneq(a, b, sz)
Definition: di_ops.h:21
curve25519_public_from_base64
int curve25519_public_from_base64(curve25519_public_key_t *pkey, const char *input)
Definition: crypto_format.c:170
T1
#define T1(s, t, a, o)
Definition: parsecommon.h:250
memarea_new
memarea_t * memarea_new(void)
Definition: memarea.c:153
hs_descriptor_t::superencrypted_data
hs_desc_superencrypted_data_t superencrypted_data
Definition: hs_descriptor.h:233
hs_desc_intro_point_t::key
crypto_pk_t * key
Definition: hs_descriptor.h:126
torcert.h
Header for torcert.c.
crypto_strongest_rand
void crypto_strongest_rand(uint8_t *out, size_t out_len)
Definition: crypto_rand.c:340
hs_desc_authorized_client_t::client_id
uint8_t client_id[HS_DESC_CLIENT_ID_LEN]
Definition: hs_descriptor.h:146
hs_desc_decode_descriptor
hs_desc_decode_status_t hs_desc_decode_descriptor(const char *encoded, const hs_subcredential_t *subcredential, const curve25519_secret_key_t *client_auth_sk, hs_descriptor_t **desc_out)
Definition: hs_descriptor.c:2571
hs_desc_authorized_client_t
Definition: hs_descriptor.h:143
hs_desc_decode_superencrypted
hs_desc_decode_status_t hs_desc_decode_superencrypted(const hs_descriptor_t *desc, hs_desc_superencrypted_data_t *desc_superencrypted)
Definition: hs_descriptor.c:2443
ed25519_public_key_t
Definition: crypto_ed25519.h:23
build_secret_key_iv_mac
static void build_secret_key_iv_mac(const hs_descriptor_t *desc, const uint8_t *secret_data, size_t secret_data_len, const uint8_t *salt, size_t salt_len, uint8_t *key_out, size_t key_len, uint8_t *iv_out, size_t iv_len, uint8_t *mac_out, size_t mac_len, int is_superencrypted_layer)
Definition: hs_descriptor.c:278
LD_REND
#define LD_REND
Definition: log.h:84
escaped
const char * escaped(const char *s)
Definition: escape.c:126
tor_cert_t::signing_key
ed25519_public_key_t signing_key
Definition: torcert.h:35
hs_desc_intro_point_t::enc_key_cert
tor_cert_t * enc_key_cert
Definition: hs_descriptor.h:119
hs_desc_plaintext_data_t::blinded_pubkey
ed25519_public_key_t blinded_pubkey
Definition: hs_descriptor.h:211
tor_cert_parse
tor_cert_t * tor_cert_parse(const uint8_t *encoded, const size_t len)
Definition: torcert.c:159
memarea_t
Definition: memarea.c:119
hs_desc_plaintext_data_t
Definition: hs_descriptor.h:193
ed25519_signature_to_base64
void ed25519_signature_to_base64(char *output, const ed25519_signature_t *sig)
Definition: crypto_format.c:239
set_intro_point_onion_key
static int set_intro_point_onion_key(curve25519_public_key_t *onion_key_out, const smartlist_t *tokens)
Definition: hs_descriptor.c:1753
desc_sig_is_valid
STATIC int desc_sig_is_valid(const char *b64_sig, const ed25519_public_key_t *signing_pubkey, const char *encoded_desc, size_t encoded_len)
Definition: hs_descriptor.c:1989
hs_descriptor_t
Definition: hs_descriptor.h:226
hs_desc_intro_point_t::cert
struct hs_desc_intro_point_t::@16::@17 cert
hs_desc_superencrypted_data_free_contents
void hs_desc_superencrypted_data_free_contents(hs_desc_superencrypted_data_t *desc)
Definition: hs_descriptor.c:2713
directory_token_t::object_body
char * object_body
Definition: parsecommon.h:208
desc_decode_superencrypted_v3
static hs_desc_decode_status_t desc_decode_superencrypted_v3(const hs_descriptor_t *desc, hs_desc_superencrypted_data_t *desc_superencrypted_out)
Definition: hs_descriptor.c:2150
hs_desc_plaintext_data_free_contents
void hs_desc_plaintext_data_free_contents(hs_desc_plaintext_data_t *desc)
Definition: hs_descriptor.c:2697
hs_desc_build_authorized_client
void hs_desc_build_authorized_client(const hs_subcredential_t *subcredential, const curve25519_public_key_t *client_auth_pk, const curve25519_secret_key_t *auth_ephemeral_sk, const uint8_t *descriptor_cookie, hs_desc_authorized_client_t *client_out)
Definition: hs_descriptor.c:2884
DIGEST256_LEN
#define DIGEST256_LEN
Definition: digest_sizes.h:23
CONCAT_ARGS
#define CONCAT_ARGS
Definition: parsecommon.h:267
tor_cert_describe_signature_status
const char * tor_cert_describe_signature_status(const tor_cert_t *cert)
Definition: torcert.c:279
hs_desc_intro_point_t::onion_key
curve25519_public_key_t onion_key
Definition: hs_descriptor.h:106
intro_auth_types
static const struct @15 intro_auth_types[]
desc_decrypt_encrypted
static size_t desc_decrypt_encrypted(const hs_descriptor_t *desc, const curve25519_secret_key_t *client_auth_sk, char **decrypted_out)
Definition: hs_descriptor.c:1644
OBJ_OK
@ OBJ_OK
Definition: parsecommon.h:224
crypto_digest256_new
crypto_digest_t * crypto_digest256_new(digest_algorithm_t algorithm)
Definition: crypto_digest_nss.c:272
get_inner_encrypted_layer_plaintext
static char * get_inner_encrypted_layer_plaintext(const hs_descriptor_t *desc)
Definition: hs_descriptor.c:743
rendcache.h
Header file for rendcache.c.
ARRAY_LENGTH
#define ARRAY_LENGTH(x)
Definition: compat_compiler.h:222
hs_descriptor_free_
void hs_descriptor_free_(hs_descriptor_t *desc)
Definition: hs_descriptor.c:2777
crypto_rand.h
Common functions for using (pseudo-)random number generators.
hs_desc_plaintext_data_t::superencrypted_blob_size
size_t superencrypted_blob_size
Definition: hs_descriptor.h:222
CURVE25519_OUTPUT_LEN
#define CURVE25519_OUTPUT_LEN
Definition: x25519_sizes.h:24
build_mac
static void build_mac(const uint8_t *mac_key, size_t mac_key_len, const uint8_t *salt, size_t salt_len, const uint8_t *encrypted, size_t encrypted_len, uint8_t *mac_out, size_t mac_len)
Definition: hs_descriptor.c:161
link_specifier_dup
link_specifier_t * link_specifier_dup(const link_specifier_t *src)
Definition: hs_common.c:1873
circuitbuild.h
Header file for circuitbuild.c.
smartlist_clear
void smartlist_clear(smartlist_t *sl)
Definition: smartlist_core.c:50
HS_DESC_MAX_LIFETIME
#define HS_DESC_MAX_LIFETIME
Definition: hs_descriptor.h:32
crypto_xof_t
Definition: crypto_digest.c:137
hs_desc_encrypted_obj_size
static size_t hs_desc_encrypted_obj_size(const hs_desc_encrypted_data_t *data)
Definition: hs_descriptor.c:2804
crypto_digest_free
#define crypto_digest_free(d)
Definition: crypto_digest.h:130
extend_info_st.h
Extend-info structure.
directory_token_t::object_size
size_t object_size
Definition: parsecommon.h:207
curve25519_public_key_t
Definition: crypto_curve25519.h:24
decode_superencrypted_handlers
static hs_desc_decode_status_t(* decode_superencrypted_handlers[])(const hs_descriptor_t *desc, hs_desc_superencrypted_data_t *desc_superencrypted)
Definition: hs_descriptor.c:2432
desc_encode_v3
static int desc_encode_v3(const hs_descriptor_t *desc, const ed25519_keypair_t *signing_kp, const uint8_t *descriptor_cookie, char **encoded_out)
Definition: hs_descriptor.c:1008
rsa_ed25519_crosscert_check
int rsa_ed25519_crosscert_check(const uint8_t *crosscert, const size_t crosscert_len, const crypto_pk_t *rsa_id_key, const ed25519_public_key_t *master_key, const time_t reject_if_expired_before)
Definition: torcert.c:395
crypto_pk_public_exponent_ok
int crypto_pk_public_exponent_ok(const crypto_pk_t *env)
Definition: crypto_rsa_nss.c:261
hs_desc_intro_point_new
hs_desc_intro_point_t * hs_desc_intro_point_new(void)
Definition: hs_descriptor.c:2836
T1_END
#define T1_END(s, t, a, o)
Definition: parsecommon.h:254
hs_desc_plaintext_data_t::signing_key_cert
tor_cert_t * signing_key_cert
Definition: hs_descriptor.h:203
ed25519_signature_t
Definition: crypto_ed25519.h:18
hs_desc_encrypted_data_free_
void hs_desc_encrypted_data_free_(hs_desc_encrypted_data_t *desc)
Definition: hs_descriptor.c:2769
cert_is_valid
STATIC int cert_is_valid(tor_cert_t *cert, uint8_t type, const char *log_obj_type)
Definition: hs_descriptor.c:1270
encode_handlers
static int(* encode_handlers[])(const hs_descriptor_t *desc, const ed25519_keypair_t *signing_kp, const uint8_t *descriptor_cookie, char **encoded_out)
Definition: hs_descriptor.c:2627
hs_desc_encrypted_data_t::create2_ntor
unsigned int create2_ntor
Definition: hs_descriptor.h:161
hs_subcredential_t
Definition: hs_ntor.h:43
decode_introduction_point
STATIC hs_desc_intro_point_t * decode_introduction_point(const hs_descriptor_t *desc, const char *start)
Definition: hs_descriptor.c:1798
parsecommon.h
Header file for parsecommon.c.
hs_config.h
Header file containing configuration ABI/API for the HS subsytem.
curve25519_secret_key_t
Definition: crypto_curve25519.h:33
tor_htonll
static uint64_t tor_htonll(uint64_t a)
Definition: bytes.h:184
build_plaintext_padding
STATIC size_t build_plaintext_padding(const char *plaintext, size_t plaintext_len, uint8_t **padded_out)
Definition: hs_descriptor.c:534
desc_decode_encrypted_v3
static hs_desc_decode_status_t desc_decode_encrypted_v3(const hs_descriptor_t *desc, const curve25519_secret_key_t *client_auth_sk, hs_desc_encrypted_data_t *desc_encrypted_out)
Definition: hs_descriptor.c:2264
tor_asprintf
int tor_asprintf(char **strp, const char *fmt,...)
Definition: printf.c:75
HS_DESC_ENCRYPTED_KEY_LEN
#define HS_DESC_ENCRYPTED_KEY_LEN
Definition: hs_descriptor.h:54
SMARTLIST_FOREACH_BEGIN
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
Definition: smartlist_foreach.h:78
ED25519_SIG_BASE64_LEN
#define ED25519_SIG_BASE64_LEN
Definition: x25519_sizes.h:45
cert_parse_and_validate
static int cert_parse_and_validate(tor_cert_t **cert_out, const char *data, size_t data_len, unsigned int cert_type_wanted, const char *err_msg)
Definition: hs_descriptor.c:1316
hs_desc_encrypted_data_t::intro_points
smartlist_t * intro_points
Definition: hs_descriptor.h:171
hs_descriptor_t::encrypted_data
hs_desc_encrypted_data_t encrypted_data
Definition: hs_descriptor.h:238
base64_decode
int base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:396
crypto_pk_write_public_key_to_string
int crypto_pk_write_public_key_to_string(crypto_pk_t *env, char **dest, size_t *len)
Definition: crypto_rsa.c:466
find_opt_by_keyword
directory_token_t * find_opt_by_keyword(const smartlist_t *s, directory_keyword keyword)
Definition: parsecommon.c:457
hs_desc_superencrypted_data_t::encrypted_blob
uint8_t * encrypted_blob
Definition: hs_descriptor.h:186
tor_parse_ulong
unsigned long tor_parse_ulong(const char *s, int base, unsigned long min, unsigned long max, int *ok, char **next)
Definition: parse_int.c:78
tor_cert_t::cert_type
uint8_t cert_type
Definition: torcert.h:45
config.h
Header file for config.c.
desc_decrypt_superencrypted
static size_t desc_decrypt_superencrypted(const hs_descriptor_t *desc, char **decrypted_out)
Definition: hs_descriptor.c:1612
encode_enc_key
static char * encode_enc_key(const hs_desc_intro_point_t *ip)
Definition: hs_descriptor.c:400
crypto_cipher_decrypt
int crypto_cipher_decrypt(crypto_cipher_t *env, char *to, const char *from, size_t fromlen)
Definition: crypto_cipher.c:108
hs_descriptor_t::subcredential
hs_subcredential_t subcredential
Definition: hs_descriptor.h:242
smartlist_add_asprintf
void smartlist_add_asprintf(struct smartlist_t *sl, const char *pattern,...)
Definition: smartlist.c:36
decode_create2_list
static void decode_create2_list(hs_desc_encrypted_data_t *desc, const char *list)
Definition: hs_descriptor.c:1233
token_rule_t
Definition: parsecommon.h:275
encode_superencrypted_data
static int encode_superencrypted_data(const hs_descriptor_t *desc, const uint8_t *descriptor_cookie, char **encrypted_blob_out)
Definition: hs_descriptor.c:936
crypto_rand
void crypto_rand(char *to, size_t n)
Definition: crypto_rand.c:477
tor_cert_t::signed_key
ed25519_public_key_t signed_key
Definition: torcert.h:32
hs_desc_encode_descriptor
int hs_desc_encode_descriptor(const hs_descriptor_t *desc, const ed25519_keypair_t *signing_kp, const uint8_t *descriptor_cookie, char **encoded_out)
Definition: hs_descriptor.c:2652
decode_intro_points
static void decode_intro_points(const hs_descriptor_t *desc, hs_desc_encrypted_data_t *desc_enc, const char *data)
Definition: hs_descriptor.c:1927
STATIC
#define STATIC
Definition: testsupport.h:32
hs_desc_superencrypted_data_t
Definition: hs_descriptor.h:176
set_uint64
static void set_uint64(void *cp, uint64_t v)
Definition: bytes.h:96
get_outer_encrypted_layer_plaintext
static char * get_outer_encrypted_layer_plaintext(const hs_descriptor_t *desc, const char *layer2_b64_ciphertext)
Definition: hs_descriptor.c:800
GE
#define GE(n)
Definition: parsecommon.h:269
curve25519_handshake
void curve25519_handshake(uint8_t *output, const curve25519_secret_key_t *skey, const curve25519_public_key_t *pkey)
Definition: crypto_curve25519.c:268
LD_DIR
#define LD_DIR
Definition: log.h:88
crypto_xof_squeeze_bytes
void crypto_xof_squeeze_bytes(crypto_xof_t *xof, uint8_t *out, size_t len)
Definition: crypto_digest.c:201
ed25519_checksig_prefixed
int ed25519_checksig_prefixed(const ed25519_signature_t *signature, const uint8_t *msg, size_t msg_len, const char *prefix_str, const ed25519_public_key_t *pubkey)
Definition: crypto_ed25519.c:339
get_auth_client_str
static char * get_auth_client_str(const hs_desc_authorized_client_t *client)
Definition: hs_descriptor.c:672
hs_desc_intro_point_t
Definition: hs_descriptor.h:99
curve25519_public_to_base64
void curve25519_public_to_base64(char *output, const curve25519_public_key_t *pkey, bool pad)
Definition: crypto_format.c:144
hs_descriptor.h
Header file for hs_descriptor.c.
encode_legacy_key
static char * encode_legacy_key(const hs_desc_intro_point_t *ip)
Definition: hs_descriptor.c:363
smartlist_t
Definition: smartlist_core.h:26
hs_desc_plaintext_data_t::superencrypted_blob
uint8_t * superencrypted_blob
Definition: hs_descriptor.h:219
smartlist_join_strings
char * smartlist_join_strings(smartlist_t *sl, const char *join, int terminate, size_t *len_out)
Definition: smartlist.c:279
crypto_digest_get_digest
void crypto_digest_get_digest(crypto_digest_t *digest, char *out, size_t out_len)
Definition: crypto_digest_nss.c:348
directory_token_t::key
struct crypto_pk_t * key
Definition: parsecommon.h:210
directory_token_t::object_type
char * object_type
Definition: parsecommon.h:206
CIPHER_IV_LEN
#define CIPHER_IV_LEN
Definition: crypto_cipher.h:24
hs_desc_encrypted_v3_token_table
static token_rule_t hs_desc_encrypted_v3_token_table[]
Definition: hs_descriptor.c:138
HS_DESC_SUPERENC_PLAINTEXT_PAD_MULTIPLE
#define HS_DESC_SUPERENC_PLAINTEXT_PAD_MULTIPLE
Definition: hs_descriptor.h:47
or.h
Master header file for Tor-specific functionality.
ed25519_keypair_t
Definition: crypto_ed25519.h:39
hs_desc_intro_point_t::cross_certified
unsigned int cross_certified
Definition: hs_descriptor.h:139
hs_desc_plaintext_data_t::lifetime_sec
uint32_t lifetime_sec
Definition: hs_descriptor.h:199