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