tor  0.4.0.1-alpha
hs_descriptor.c
Go to the documentation of this file.
1 /* Copyright (c) 2016-2019, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
3 
55 /* For unit tests.*/
56 #define HS_DESCRIPTOR_PRIVATE
57 
58 #include "core/or/or.h"
59 #include "trunnel/ed25519_cert.h" /* Trunnel interface. */
61 #include "core/or/circuitbuild.h"
65 #include "feature/rend/rendcache.h"
66 #include "feature/hs/hs_cache.h"
67 #include "feature/hs/hs_config.h"
68 #include "feature/nodelist/torcert.h" /* tor_cert_encode_ed22519() */
69 #include "lib/memarea/memarea.h"
71 
72 #include "core/or/extend_info_st.h"
73 
74 /* Constant string value used for the descriptor format. */
75 #define str_hs_desc "hs-descriptor"
76 #define str_desc_cert "descriptor-signing-key-cert"
77 #define str_rev_counter "revision-counter"
78 #define str_superencrypted "superencrypted"
79 #define str_encrypted "encrypted"
80 #define str_signature "signature"
81 #define str_lifetime "descriptor-lifetime"
82 /* Constant string value for the encrypted part of the descriptor. */
83 #define str_create2_formats "create2-formats"
84 #define str_intro_auth_required "intro-auth-required"
85 #define str_single_onion "single-onion-service"
86 #define str_intro_point "introduction-point"
87 #define str_ip_onion_key "onion-key"
88 #define str_ip_auth_key "auth-key"
89 #define str_ip_enc_key "enc-key"
90 #define str_ip_enc_key_cert "enc-key-cert"
91 #define str_ip_legacy_key "legacy-key"
92 #define str_ip_legacy_key_cert "legacy-key-cert"
93 #define str_intro_point_start "\n" str_intro_point " "
94 /* Constant string value for the construction to encrypt the encrypted data
95  * section. */
96 #define str_enc_const_superencryption "hsdir-superencrypted-data"
97 #define str_enc_const_encryption "hsdir-encrypted-data"
98 /* Prefix required to compute/verify HS desc signatures */
99 #define str_desc_sig_prefix "Tor onion service descriptor sig v3"
100 #define str_desc_auth_type "desc-auth-type"
101 #define str_desc_auth_key "desc-auth-ephemeral-key"
102 #define str_desc_auth_client "auth-client"
103 #define str_encrypted "encrypted"
104 
105 /* Authentication supported types. */
106 static const struct {
107  hs_desc_auth_type_t type;
108  const char *identifier;
109 } intro_auth_types[] = {
110  { HS_DESC_AUTH_ED25519, "ed25519" },
111  /* Indicate end of array. */
112  { 0, NULL }
113 };
114 
115 /* Descriptor ruleset. */
116 static token_rule_t hs_desc_v3_token_table[] = {
117  T1_START(str_hs_desc, R_HS_DESCRIPTOR, EQ(1), NO_OBJ),
118  T1(str_lifetime, R3_DESC_LIFETIME, EQ(1), NO_OBJ),
119  T1(str_desc_cert, R3_DESC_SIGNING_CERT, NO_ARGS, NEED_OBJ),
120  T1(str_rev_counter, R3_REVISION_COUNTER, EQ(1), NO_OBJ),
121  T1(str_superencrypted, R3_SUPERENCRYPTED, NO_ARGS, NEED_OBJ),
122  T1_END(str_signature, R3_SIGNATURE, EQ(1), NO_OBJ),
124 };
125 
126 /* Descriptor ruleset for the superencrypted section. */
127 static token_rule_t hs_desc_superencrypted_v3_token_table[] = {
128  T1_START(str_desc_auth_type, R3_DESC_AUTH_TYPE, GE(1), NO_OBJ),
129  T1(str_desc_auth_key, R3_DESC_AUTH_KEY, GE(1), NO_OBJ),
130  T1N(str_desc_auth_client, R3_DESC_AUTH_CLIENT, GE(3), NO_OBJ),
131  T1(str_encrypted, R3_ENCRYPTED, NO_ARGS, NEED_OBJ),
133 };
134 
135 /* Descriptor ruleset for the encrypted section. */
136 static token_rule_t hs_desc_encrypted_v3_token_table[] = {
137  T1_START(str_create2_formats, R3_CREATE2_FORMATS, CONCAT_ARGS, NO_OBJ),
138  T01(str_intro_auth_required, R3_INTRO_AUTH_REQUIRED, ARGS, NO_OBJ),
139  T01(str_single_onion, R3_SINGLE_ONION_SERVICE, ARGS, NO_OBJ),
141 };
142 
143 /* Descriptor ruleset for the introduction points section. */
144 static token_rule_t hs_desc_intro_point_v3_token_table[] = {
145  T1_START(str_intro_point, R3_INTRODUCTION_POINT, EQ(1), NO_OBJ),
146  T1N(str_ip_onion_key, R3_INTRO_ONION_KEY, GE(2), OBJ_OK),
147  T1(str_ip_auth_key, R3_INTRO_AUTH_KEY, NO_ARGS, NEED_OBJ),
148  T1(str_ip_enc_key, R3_INTRO_ENC_KEY, GE(2), OBJ_OK),
149  T1(str_ip_enc_key_cert, R3_INTRO_ENC_KEY_CERT, ARGS, OBJ_OK),
150  T01(str_ip_legacy_key, R3_INTRO_LEGACY_KEY, ARGS, NEED_KEY_1024),
151  T01(str_ip_legacy_key_cert, R3_INTRO_LEGACY_KEY_CERT, ARGS, OBJ_OK),
153 };
154 
155 /* Using a key, salt and encrypted payload, build a MAC and put it in mac_out.
156  * We use SHA3-256 for the MAC computation.
157  * This function can't fail. */
158 static void
159 build_mac(const uint8_t *mac_key, size_t mac_key_len,
160  const uint8_t *salt, size_t salt_len,
161  const uint8_t *encrypted, size_t encrypted_len,
162  uint8_t *mac_out, size_t mac_len)
163 {
164  crypto_digest_t *digest;
165 
166  const uint64_t mac_len_netorder = tor_htonll(mac_key_len);
167  const uint64_t salt_len_netorder = tor_htonll(salt_len);
168 
169  tor_assert(mac_key);
170  tor_assert(salt);
171  tor_assert(encrypted);
172  tor_assert(mac_out);
173 
174  digest = crypto_digest256_new(DIGEST_SHA3_256);
175  /* As specified in section 2.5 of proposal 224, first add the mac key
176  * then add the salt first and then the encrypted section. */
177 
178  crypto_digest_add_bytes(digest, (const char *) &mac_len_netorder, 8);
179  crypto_digest_add_bytes(digest, (const char *) mac_key, mac_key_len);
180  crypto_digest_add_bytes(digest, (const char *) &salt_len_netorder, 8);
181  crypto_digest_add_bytes(digest, (const char *) salt, salt_len);
182  crypto_digest_add_bytes(digest, (const char *) encrypted, encrypted_len);
183  crypto_digest_get_digest(digest, (char *) mac_out, mac_len);
184  crypto_digest_free(digest);
185 }
186 
187 /* Using a secret data and a given decriptor object, build the secret
188  * input needed for the KDF.
189  *
190  * secret_input = SECRET_DATA | subcredential | INT_8(revision_counter)
191  *
192  * Then, set the newly allocated buffer in secret_input_out and return the
193  * length of the buffer. */
194 static size_t
195 build_secret_input(const hs_descriptor_t *desc,
196  const uint8_t *secret_data,
197  size_t secret_data_len,
198  uint8_t **secret_input_out)
199 {
200  size_t offset = 0;
201  size_t secret_input_len = secret_data_len + DIGEST256_LEN + sizeof(uint64_t);
202  uint8_t *secret_input = NULL;
203 
204  tor_assert(desc);
205  tor_assert(secret_data);
206  tor_assert(secret_input_out);
207 
208  secret_input = tor_malloc_zero(secret_input_len);
209 
210  /* Copy the secret data. */
211  memcpy(secret_input, secret_data, secret_data_len);
212  offset += secret_data_len;
213  /* Copy subcredential. */
214  memcpy(secret_input + offset, desc->subcredential, DIGEST256_LEN);
215  offset += DIGEST256_LEN;
216  /* Copy revision counter value. */
217  set_uint64(secret_input + offset,
218  tor_htonll(desc->plaintext_data.revision_counter));
219  offset += sizeof(uint64_t);
220  tor_assert(secret_input_len == offset);
221 
222  *secret_input_out = secret_input;
223 
224  return secret_input_len;
225 }
226 
227 /* Do the KDF construction and put the resulting data in key_out which is of
228  * key_out_len length. It uses SHAKE-256 as specified in the spec. */
229 static void
230 build_kdf_key(const hs_descriptor_t *desc,
231  const uint8_t *secret_data,
232  size_t secret_data_len,
233  const uint8_t *salt, size_t salt_len,
234  uint8_t *key_out, size_t key_out_len,
235  int is_superencrypted_layer)
236 {
237  uint8_t *secret_input = NULL;
238  size_t secret_input_len;
239  crypto_xof_t *xof;
240 
241  tor_assert(desc);
242  tor_assert(secret_data);
243  tor_assert(salt);
244  tor_assert(key_out);
245 
246  /* Build the secret input for the KDF computation. */
247  secret_input_len = build_secret_input(desc, secret_data,
248  secret_data_len, &secret_input);
249 
250  xof = crypto_xof_new();
251  /* Feed our KDF. [SHAKE it like a polaroid picture --Yawning]. */
252  crypto_xof_add_bytes(xof, secret_input, secret_input_len);
253  crypto_xof_add_bytes(xof, salt, salt_len);
254 
255  /* Feed in the right string constant based on the desc layer */
256  if (is_superencrypted_layer) {
257  crypto_xof_add_bytes(xof, (const uint8_t *) str_enc_const_superencryption,
258  strlen(str_enc_const_superencryption));
259  } else {
260  crypto_xof_add_bytes(xof, (const uint8_t *) str_enc_const_encryption,
261  strlen(str_enc_const_encryption));
262  }
263 
264  /* Eat from our KDF. */
265  crypto_xof_squeeze_bytes(xof, key_out, key_out_len);
266  crypto_xof_free(xof);
267  memwipe(secret_input, 0, secret_input_len);
268 
269  tor_free(secret_input);
270 }
271 
272 /* Using the given descriptor, secret data, and salt, run it through our
273  * KDF function and then extract a secret key in key_out, the IV in iv_out
274  * and MAC in mac_out. This function can't fail. */
275 static void
276 build_secret_key_iv_mac(const hs_descriptor_t *desc,
277  const uint8_t *secret_data,
278  size_t secret_data_len,
279  const uint8_t *salt, size_t salt_len,
280  uint8_t *key_out, size_t key_len,
281  uint8_t *iv_out, size_t iv_len,
282  uint8_t *mac_out, size_t mac_len,
283  int is_superencrypted_layer)
284 {
285  size_t offset = 0;
286  uint8_t kdf_key[HS_DESC_ENCRYPTED_KDF_OUTPUT_LEN];
287 
288  tor_assert(desc);
289  tor_assert(secret_data);
290  tor_assert(salt);
291  tor_assert(key_out);
292  tor_assert(iv_out);
293  tor_assert(mac_out);
294 
295  build_kdf_key(desc, secret_data, secret_data_len,
296  salt, salt_len, kdf_key, sizeof(kdf_key),
297  is_superencrypted_layer);
298  /* Copy the bytes we need for both the secret key and IV. */
299  memcpy(key_out, kdf_key, key_len);
300  offset += key_len;
301  memcpy(iv_out, kdf_key + offset, iv_len);
302  offset += iv_len;
303  memcpy(mac_out, kdf_key + offset, mac_len);
304  /* Extra precaution to make sure we are not out of bound. */
305  tor_assert((offset + mac_len) == sizeof(kdf_key));
306  memwipe(kdf_key, 0, sizeof(kdf_key));
307 }
308 
309 /* === ENCODING === */
310 
311 /* Encode the given link specifier objects into a newly allocated string.
312  * This can't fail so caller can always assume a valid string being
313  * returned. */
314 STATIC char *
315 encode_link_specifiers(const smartlist_t *specs)
316 {
317  char *encoded_b64 = NULL;
318  link_specifier_list_t *lslist = link_specifier_list_new();
319 
320  tor_assert(specs);
321  /* No link specifiers is a code flow error, can't happen. */
322  tor_assert(smartlist_len(specs) > 0);
323  tor_assert(smartlist_len(specs) <= UINT8_MAX);
324 
325  link_specifier_list_set_n_spec(lslist, smartlist_len(specs));
326 
328  spec) {
329  link_specifier_t *ls = hs_desc_lspec_to_trunnel(spec);
330  if (ls) {
331  link_specifier_list_add_spec(lslist, ls);
332  }
333  } SMARTLIST_FOREACH_END(spec);
334 
335  {
336  uint8_t *encoded;
337  ssize_t encoded_len, encoded_b64_len, ret;
338 
339  encoded_len = link_specifier_list_encoded_len(lslist);
340  tor_assert(encoded_len > 0);
341  encoded = tor_malloc_zero(encoded_len);
342  ret = link_specifier_list_encode(encoded, encoded_len, lslist);
343  tor_assert(ret == encoded_len);
344 
345  /* Base64 encode our binary format. Add extra NUL byte for the base64
346  * encoded value. */
347  encoded_b64_len = base64_encode_size(encoded_len, 0) + 1;
348  encoded_b64 = tor_malloc_zero(encoded_b64_len);
349  ret = base64_encode(encoded_b64, encoded_b64_len, (const char *) encoded,
350  encoded_len, 0);
351  tor_assert(ret == (encoded_b64_len - 1));
352  tor_free(encoded);
353  }
354 
355  link_specifier_list_free(lslist);
356  return encoded_b64;
357 }
358 
359 /* Encode an introduction point legacy key and certificate. Return a newly
360  * allocated string with it. On failure, return NULL. */
361 static char *
362 encode_legacy_key(const hs_desc_intro_point_t *ip)
363 {
364  char *key_str, b64_cert[256], *encoded = NULL;
365  size_t key_str_len;
366 
367  tor_assert(ip);
368 
369  /* Encode cross cert. */
370  if (base64_encode(b64_cert, sizeof(b64_cert),
371  (const char *) ip->legacy.cert.encoded,
372  ip->legacy.cert.len, BASE64_ENCODE_MULTILINE) < 0) {
373  log_warn(LD_REND, "Unable to encode legacy crosscert.");
374  goto done;
375  }
376  /* Convert the encryption key to PEM format NUL terminated. */
377  if (crypto_pk_write_public_key_to_string(ip->legacy.key, &key_str,
378  &key_str_len) < 0) {
379  log_warn(LD_REND, "Unable to encode legacy encryption key.");
380  goto done;
381  }
382  tor_asprintf(&encoded,
383  "%s \n%s" /* Newline is added by the call above. */
384  "%s\n"
385  "-----BEGIN CROSSCERT-----\n"
386  "%s"
387  "-----END CROSSCERT-----",
388  str_ip_legacy_key, key_str,
389  str_ip_legacy_key_cert, b64_cert);
390  tor_free(key_str);
391 
392  done:
393  return encoded;
394 }
395 
396 /* Encode an introduction point encryption key and certificate. Return a newly
397  * allocated string with it. On failure, return NULL. */
398 static char *
399 encode_enc_key(const hs_desc_intro_point_t *ip)
400 {
401  char *encoded = NULL, *encoded_cert;
402  char key_b64[CURVE25519_BASE64_PADDED_LEN + 1];
403 
404  tor_assert(ip);
405 
406  /* Base64 encode the encryption key for the "enc-key" field. */
407  if (curve25519_public_to_base64(key_b64, &ip->enc_key) < 0) {
408  goto done;
409  }
410  if (tor_cert_encode_ed22519(ip->enc_key_cert, &encoded_cert) < 0) {
411  goto done;
412  }
413  tor_asprintf(&encoded,
414  "%s ntor %s\n"
415  "%s\n%s",
416  str_ip_enc_key, key_b64,
417  str_ip_enc_key_cert, encoded_cert);
418  tor_free(encoded_cert);
419 
420  done:
421  return encoded;
422 }
423 
424 /* Encode an introduction point onion key. Return a newly allocated string
425  * with it. On failure, return NULL. */
426 static char *
427 encode_onion_key(const hs_desc_intro_point_t *ip)
428 {
429  char *encoded = NULL;
430  char key_b64[CURVE25519_BASE64_PADDED_LEN + 1];
431 
432  tor_assert(ip);
433 
434  /* Base64 encode the encryption key for the "onion-key" field. */
435  if (curve25519_public_to_base64(key_b64, &ip->onion_key) < 0) {
436  goto done;
437  }
438  tor_asprintf(&encoded, "%s ntor %s", str_ip_onion_key, key_b64);
439 
440  done:
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 *
447 encode_intro_point(const ed25519_public_key_t *sig_key,
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. */
580  tor_assert(!(encrypted_len % HS_DESC_SUPERENC_PLAINTEXT_PAD_MULTIPLE));
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
607 encrypt_descriptor_data(const hs_descriptor_t *desc,
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 *
676 get_auth_client_str(const hs_desc_authorized_client_t *client)
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(!tor_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 
710 static char *
712 {
713  smartlist_t *auth_client_lines = smartlist_new();
714  char *auth_client_lines_str = NULL;
715 
716  tor_assert(desc);
717  tor_assert(desc->superencrypted_data.clients);
718  tor_assert(smartlist_len(desc->superencrypted_data.clients) != 0);
719  tor_assert(smartlist_len(desc->superencrypted_data.clients)
720  % HS_DESC_AUTH_CLIENT_MULTIPLE == 0);
721 
722  /* Make a line for each client */
723  SMARTLIST_FOREACH_BEGIN(desc->superencrypted_data.clients,
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 *
747 get_inner_encrypted_layer_plaintext(const hs_descriptor_t *desc)
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. */
764  char *buf = smartlist_join_strings(desc->encrypted_data.intro_auth_types,
765  " ", 0, NULL);
766  smartlist_add_asprintf(lines, "%s %s\n", str_intro_auth_required, buf);
767  tor_free(buf);
768  }
769 
770  if (desc->encrypted_data.single_onion_service) {
771  smartlist_add_asprintf(lines, "%s\n", str_single_onion);
772  }
773  }
774 
775  /* Build the introduction point(s) section. */
776  SMARTLIST_FOREACH_BEGIN(desc->encrypted_data.intro_points,
777  const hs_desc_intro_point_t *, ip) {
778  char *encoded_ip = encode_intro_point(&desc->plaintext_data.signing_pubkey,
779  ip);
780  if (encoded_ip == NULL) {
781  log_err(LD_BUG, "HS desc intro point is malformed.");
782  goto err;
783  }
784  smartlist_add(lines, encoded_ip);
785  } SMARTLIST_FOREACH_END(ip);
786 
787  /* Build the entire encrypted data section into one encoded plaintext and
788  * then encrypt it. */
789  encoded_str = smartlist_join_strings(lines, "", 0, NULL);
790 
791  err:
792  SMARTLIST_FOREACH(lines, char *, l, tor_free(l));
793  smartlist_free(lines);
794 
795  return encoded_str;
796 }
797 
798 /* Create the middle layer of the descriptor, which includes the client auth
799  * data and the encrypted inner layer (provided as a base64 string at
800  * <b>layer2_b64_ciphertext</b>). Return a newly-allocated string with the
801  * layer plaintext, or NULL if an error occurred. It's the responsibility of
802  * the caller to free the returned string. */
803 static char *
804 get_outer_encrypted_layer_plaintext(const hs_descriptor_t *desc,
805  const char *layer2_b64_ciphertext)
806 {
807  char *layer1_str = NULL;
808  smartlist_t *lines = smartlist_new();
809 
810  /* Specify auth type */
811  smartlist_add_asprintf(lines, "%s %s\n", str_desc_auth_type, "x25519");
812 
813  { /* Print ephemeral x25519 key */
814  char ephemeral_key_base64[CURVE25519_BASE64_PADDED_LEN + 1];
815  const curve25519_public_key_t *ephemeral_pubkey;
816 
817  ephemeral_pubkey = &desc->superencrypted_data.auth_ephemeral_pubkey;
818  tor_assert(!tor_mem_is_zero((char *) ephemeral_pubkey->public_key,
820 
821  if (curve25519_public_to_base64(ephemeral_key_base64,
822  ephemeral_pubkey) < 0) {
823  goto done;
824  }
825  smartlist_add_asprintf(lines, "%s %s\n",
826  str_desc_auth_key, ephemeral_key_base64);
827 
828  memwipe(ephemeral_key_base64, 0, sizeof(ephemeral_key_base64));
829  }
830 
831  { /* Create auth-client lines. */
832  char *auth_client_lines = get_all_auth_client_lines(desc);
833  tor_assert(auth_client_lines);
834  smartlist_add(lines, auth_client_lines);
835  }
836 
837  /* create encrypted section */
838  {
840  "%s\n"
841  "-----BEGIN MESSAGE-----\n"
842  "%s"
843  "-----END MESSAGE-----",
844  str_encrypted, layer2_b64_ciphertext);
845  }
846 
847  layer1_str = smartlist_join_strings(lines, "", 0, NULL);
848 
849  done:
850  /* We need to memwipe all lines because it contains the ephemeral key */
851  SMARTLIST_FOREACH(lines, char *, a, memwipe(a, 0, strlen(a)));
852  SMARTLIST_FOREACH(lines, char *, a, tor_free(a));
853  smartlist_free(lines);
854 
855  return layer1_str;
856 }
857 
858 /* Encrypt <b>encoded_str</b> into an encrypted blob and then base64 it before
859  * returning it. <b>desc</b> is provided to derive the encryption
860  * keys. <b>secret_data</b> is also proved to derive the encryption keys.
861  * <b>is_superencrypted_layer</b> is set if <b>encoded_str</b> is the
862  * middle (superencrypted) layer of the descriptor. It's the responsibility of
863  * the caller to free the returned string. */
864 static char *
865 encrypt_desc_data_and_base64(const hs_descriptor_t *desc,
866  const uint8_t *secret_data,
867  size_t secret_data_len,
868  const char *encoded_str,
869  int is_superencrypted_layer)
870 {
871  char *enc_b64;
872  ssize_t enc_b64_len, ret_len, enc_len;
873  char *encrypted_blob = NULL;
874 
875  enc_len = encrypt_descriptor_data(desc, secret_data, secret_data_len,
876  encoded_str, &encrypted_blob,
877  is_superencrypted_layer);
878  /* Get the encoded size plus a NUL terminating byte. */
879  enc_b64_len = base64_encode_size(enc_len, BASE64_ENCODE_MULTILINE) + 1;
880  enc_b64 = tor_malloc_zero(enc_b64_len);
881  /* Base64 the encrypted blob before returning it. */
882  ret_len = base64_encode(enc_b64, enc_b64_len, encrypted_blob, enc_len,
883  BASE64_ENCODE_MULTILINE);
884  /* Return length doesn't count the NUL byte. */
885  tor_assert(ret_len == (enc_b64_len - 1));
886  tor_free(encrypted_blob);
887 
888  return enc_b64;
889 }
890 
891 /* Generate the secret data which is used to encrypt/decrypt the descriptor.
892  *
893  * SECRET_DATA = blinded-public-key
894  * SECRET_DATA = blinded-public-key | descriptor_cookie
895  *
896  * The descriptor_cookie is optional but if it exists, it must be at least
897  * HS_DESC_DESCRIPTOR_COOKIE_LEN bytes long.
898  *
899  * A newly allocated secret data is put in secret_data_out. Return the
900  * length of the secret data. This function cannot fail. */
901 static size_t
902 build_secret_data(const ed25519_public_key_t *blinded_pubkey,
903  const uint8_t *descriptor_cookie,
904  uint8_t **secret_data_out)
905 {
906  size_t secret_data_len;
907  uint8_t *secret_data;
908 
909  tor_assert(blinded_pubkey);
910  tor_assert(secret_data_out);
911 
912  if (descriptor_cookie) {
913  /* If the descriptor cookie is present, we need both the blinded
914  * pubkey and the descriptor cookie as a secret data. */
915  secret_data_len = ED25519_PUBKEY_LEN + HS_DESC_DESCRIPTOR_COOKIE_LEN;
916  secret_data = tor_malloc(secret_data_len);
917 
918  memcpy(secret_data,
919  blinded_pubkey->pubkey,
920  ED25519_PUBKEY_LEN);
921  memcpy(secret_data + ED25519_PUBKEY_LEN,
922  descriptor_cookie,
923  HS_DESC_DESCRIPTOR_COOKIE_LEN);
924  } else {
925  /* If the descriptor cookie is not present, we need only the blinded
926  * pubkey as a secret data. */
927  secret_data_len = ED25519_PUBKEY_LEN;
928  secret_data = tor_malloc(secret_data_len);
929  memcpy(secret_data,
930  blinded_pubkey->pubkey,
931  ED25519_PUBKEY_LEN);
932  }
933 
934  *secret_data_out = secret_data;
935  return secret_data_len;
936 }
937 
938 /* Generate and encode the superencrypted portion of <b>desc</b>. This also
939  * involves generating the encrypted portion of the descriptor, and performing
940  * the superencryption. A newly allocated NUL-terminated string pointer
941  * containing the encrypted encoded blob is put in encrypted_blob_out. Return 0
942  * on success else a negative value. */
943 static int
944 encode_superencrypted_data(const hs_descriptor_t *desc,
945  const uint8_t *descriptor_cookie,
946  char **encrypted_blob_out)
947 {
948  int ret = -1;
949  uint8_t *secret_data = NULL;
950  size_t secret_data_len = 0;
951  char *layer2_str = NULL;
952  char *layer2_b64_ciphertext = NULL;
953  char *layer1_str = NULL;
954  char *layer1_b64_ciphertext = NULL;
955 
956  tor_assert(desc);
957  tor_assert(encrypted_blob_out);
958 
959  /* Func logic: We first create the inner layer of the descriptor (layer2).
960  * We then encrypt it and use it to create the middle layer of the descriptor
961  * (layer1). Finally we superencrypt the middle layer and return it to our
962  * caller. */
963 
964  /* Create inner descriptor layer */
965  layer2_str = get_inner_encrypted_layer_plaintext(desc);
966  if (!layer2_str) {
967  goto err;
968  }
969 
970  secret_data_len = build_secret_data(&desc->plaintext_data.blinded_pubkey,
971  descriptor_cookie,
972  &secret_data);
973 
974  /* Encrypt and b64 the inner layer */
975  layer2_b64_ciphertext =
976  encrypt_desc_data_and_base64(desc, secret_data, secret_data_len,
977  layer2_str, 0);
978  if (!layer2_b64_ciphertext) {
979  goto err;
980  }
981 
982  /* Now create middle descriptor layer given the inner layer */
983  layer1_str = get_outer_encrypted_layer_plaintext(desc,layer2_b64_ciphertext);
984  if (!layer1_str) {
985  goto err;
986  }
987 
988  /* Encrypt and base64 the middle layer */
989  layer1_b64_ciphertext =
990  encrypt_desc_data_and_base64(desc,
991  desc->plaintext_data.blinded_pubkey.pubkey,
992  ED25519_PUBKEY_LEN,
993  layer1_str, 1);
994  if (!layer1_b64_ciphertext) {
995  goto err;
996  }
997 
998  /* Success! */
999  ret = 0;
1000 
1001  err:
1002  memwipe(secret_data, 0, secret_data_len);
1003  tor_free(secret_data);
1004  tor_free(layer1_str);
1005  tor_free(layer2_str);
1006  tor_free(layer2_b64_ciphertext);
1007 
1008  *encrypted_blob_out = layer1_b64_ciphertext;
1009  return ret;
1010 }
1011 
1012 /* Encode a v3 HS descriptor. Return 0 on success and set encoded_out to the
1013  * newly allocated string of the encoded descriptor. On error, -1 is returned
1014  * and encoded_out is untouched. */
1015 static int
1016 desc_encode_v3(const hs_descriptor_t *desc,
1017  const ed25519_keypair_t *signing_kp,
1018  const uint8_t *descriptor_cookie,
1019  char **encoded_out)
1020 {
1021  int ret = -1;
1022  char *encoded_str = NULL;
1023  size_t encoded_len;
1024  smartlist_t *lines = smartlist_new();
1025 
1026  tor_assert(desc);
1027  tor_assert(signing_kp);
1028  tor_assert(encoded_out);
1029  tor_assert(desc->plaintext_data.version == 3);
1030 
1031  if (BUG(desc->subcredential == NULL)) {
1032  goto err;
1033  }
1034 
1035  /* Build the non-encrypted values. */
1036  {
1037  char *encoded_cert;
1038  /* Encode certificate then create the first line of the descriptor. */
1039  if (desc->plaintext_data.signing_key_cert->cert_type
1040  != CERT_TYPE_SIGNING_HS_DESC) {
1041  log_err(LD_BUG, "HS descriptor signing key has an unexpected cert type "
1042  "(%d)", (int) desc->plaintext_data.signing_key_cert->cert_type);
1043  goto err;
1044  }
1045  if (tor_cert_encode_ed22519(desc->plaintext_data.signing_key_cert,
1046  &encoded_cert) < 0) {
1047  /* The function will print error logs. */
1048  goto err;
1049  }
1050  /* Create the hs descriptor line. */
1051  smartlist_add_asprintf(lines, "%s %" PRIu32, str_hs_desc,
1052  desc->plaintext_data.version);
1053  /* Add the descriptor lifetime line (in minutes). */
1054  smartlist_add_asprintf(lines, "%s %" PRIu32, str_lifetime,
1055  desc->plaintext_data.lifetime_sec / 60);
1056  /* Create the descriptor certificate line. */
1057  smartlist_add_asprintf(lines, "%s\n%s", str_desc_cert, encoded_cert);
1058  tor_free(encoded_cert);
1059  /* Create the revision counter line. */
1060  smartlist_add_asprintf(lines, "%s %" PRIu64, str_rev_counter,
1061  desc->plaintext_data.revision_counter);
1062  }
1063 
1064  /* Build the superencrypted data section. */
1065  {
1066  char *enc_b64_blob=NULL;
1067  if (encode_superencrypted_data(desc, descriptor_cookie,
1068  &enc_b64_blob) < 0) {
1069  goto err;
1070  }
1071  smartlist_add_asprintf(lines,
1072  "%s\n"
1073  "-----BEGIN MESSAGE-----\n"
1074  "%s"
1075  "-----END MESSAGE-----",
1076  str_superencrypted, enc_b64_blob);
1077  tor_free(enc_b64_blob);
1078  }
1079 
1080  /* Join all lines in one string so we can generate a signature and append
1081  * it to the descriptor. */
1082  encoded_str = smartlist_join_strings(lines, "\n", 1, &encoded_len);
1083 
1084  /* Sign all fields of the descriptor with our short term signing key. */
1085  {
1086  ed25519_signature_t sig;
1087  char ed_sig_b64[ED25519_SIG_BASE64_LEN + 1];
1088  if (ed25519_sign_prefixed(&sig,
1089  (const uint8_t *) encoded_str, encoded_len,
1090  str_desc_sig_prefix, signing_kp) < 0) {
1091  log_warn(LD_BUG, "Can't sign encoded HS descriptor!");
1092  tor_free(encoded_str);
1093  goto err;
1094  }
1095  if (ed25519_signature_to_base64(ed_sig_b64, &sig) < 0) {
1096  log_warn(LD_BUG, "Can't base64 encode descriptor signature!");
1097  tor_free(encoded_str);
1098  goto err;
1099  }
1100  /* Create the signature line. */
1101  smartlist_add_asprintf(lines, "%s %s", str_signature, ed_sig_b64);
1102  }
1103  /* Free previous string that we used so compute the signature. */
1104  tor_free(encoded_str);
1105  encoded_str = smartlist_join_strings(lines, "\n", 1, NULL);
1106  *encoded_out = encoded_str;
1107 
1108  if (strlen(encoded_str) >= hs_cache_get_max_descriptor_size()) {
1109  log_warn(LD_GENERAL, "We just made an HS descriptor that's too big (%d)."
1110  "Failing.", (int)strlen(encoded_str));
1111  tor_free(encoded_str);
1112  goto err;
1113  }
1114 
1115  /* XXX: Trigger a control port event. */
1116 
1117  /* Success! */
1118  ret = 0;
1119 
1120  err:
1121  SMARTLIST_FOREACH(lines, char *, l, tor_free(l));
1122  smartlist_free(lines);
1123  return ret;
1124 }
1125 
1126 /* === DECODING === */
1127 
1128 /* Given the token tok for an auth client, decode it as
1129  * hs_desc_authorized_client_t. tok->args MUST contain at least 3 elements
1130  * Return 0 on success else -1 on failure. */
1131 static int
1132 decode_auth_client(const directory_token_t *tok,
1134 {
1135  int ret = -1;
1136 
1137  tor_assert(tok);
1138  tor_assert(tok->n_args >= 3);
1139  tor_assert(client);
1140 
1141  if (base64_decode((char *) client->client_id, sizeof(client->client_id),
1142  tok->args[0], strlen(tok->args[0])) !=
1143  sizeof(client->client_id)) {
1144  goto done;
1145  }
1146  if (base64_decode((char *) client->iv, sizeof(client->iv),
1147  tok->args[1], strlen(tok->args[1])) !=
1148  sizeof(client->iv)) {
1149  goto done;
1150  }
1151  if (base64_decode((char *) client->encrypted_cookie,
1152  sizeof(client->encrypted_cookie),
1153  tok->args[2], strlen(tok->args[2])) !=
1154  sizeof(client->encrypted_cookie)) {
1155  goto done;
1156  }
1157 
1158  /* Success. */
1159  ret = 0;
1160  done:
1161  return ret;
1162 }
1163 
1164 /* Given an encoded string of the link specifiers, return a newly allocated
1165  * list of decoded link specifiers. Return NULL on error. */
1166 STATIC smartlist_t *
1167 decode_link_specifiers(const char *encoded)
1168 {
1169  int decoded_len;
1170  size_t encoded_len, i;
1171  uint8_t *decoded;
1172  smartlist_t *results = NULL;
1173  link_specifier_list_t *specs = NULL;
1174 
1175  tor_assert(encoded);
1176 
1177  encoded_len = strlen(encoded);
1178  decoded = tor_malloc(encoded_len);
1179  decoded_len = base64_decode((char *) decoded, encoded_len, encoded,
1180  encoded_len);
1181  if (decoded_len < 0) {
1182  goto err;
1183  }
1184 
1185  if (link_specifier_list_parse(&specs, decoded,
1186  (size_t) decoded_len) < decoded_len) {
1187  goto err;
1188  }
1189  tor_assert(specs);
1190  results = smartlist_new();
1191 
1192  for (i = 0; i < link_specifier_list_getlen_spec(specs); i++) {
1193  hs_desc_link_specifier_t *hs_spec;
1194  link_specifier_t *ls = link_specifier_list_get_spec(specs, i);
1195  tor_assert(ls);
1196 
1197  hs_spec = tor_malloc_zero(sizeof(*hs_spec));
1198  hs_spec->type = link_specifier_get_ls_type(ls);
1199  switch (hs_spec->type) {
1200  case LS_IPV4:
1201  tor_addr_from_ipv4h(&hs_spec->u.ap.addr,
1202  link_specifier_get_un_ipv4_addr(ls));
1203  hs_spec->u.ap.port = link_specifier_get_un_ipv4_port(ls);
1204  break;
1205  case LS_IPV6:
1206  tor_addr_from_ipv6_bytes(&hs_spec->u.ap.addr, (const char *)
1207  link_specifier_getarray_un_ipv6_addr(ls));
1208  hs_spec->u.ap.port = link_specifier_get_un_ipv6_port(ls);
1209  break;
1210  case LS_LEGACY_ID:
1211  /* Both are known at compile time so let's make sure they are the same
1212  * else we can copy memory out of bound. */
1213  tor_assert(link_specifier_getlen_un_legacy_id(ls) ==
1214  sizeof(hs_spec->u.legacy_id));
1215  memcpy(hs_spec->u.legacy_id, link_specifier_getarray_un_legacy_id(ls),
1216  sizeof(hs_spec->u.legacy_id));
1217  break;
1218  case LS_ED25519_ID:
1219  /* Both are known at compile time so let's make sure they are the same
1220  * else we can copy memory out of bound. */
1221  tor_assert(link_specifier_getlen_un_ed25519_id(ls) ==
1222  sizeof(hs_spec->u.ed25519_id));
1223  memcpy(hs_spec->u.ed25519_id,
1224  link_specifier_getconstarray_un_ed25519_id(ls),
1225  sizeof(hs_spec->u.ed25519_id));
1226  break;
1227  default:
1228  tor_free(hs_spec);
1229  goto err;
1230  }
1231 
1232  smartlist_add(results, hs_spec);
1233  }
1234 
1235  goto done;
1236  err:
1237  if (results) {
1239  smartlist_free(results);
1240  results = NULL;
1241  }
1242  done:
1243  link_specifier_list_free(specs);
1244  tor_free(decoded);
1245  return results;
1246 }
1247 
1248 /* Given a list of authentication types, decode it and put it in the encrypted
1249  * data section. Return 1 if we at least know one of the type or 0 if we know
1250  * none of them. */
1251 static int
1252 decode_auth_type(hs_desc_encrypted_data_t *desc, const char *list)
1253 {
1254  int match = 0;
1255 
1256  tor_assert(desc);
1257  tor_assert(list);
1258 
1259  desc->intro_auth_types = smartlist_new();
1260  smartlist_split_string(desc->intro_auth_types, list, " ", 0, 0);
1261 
1262  /* Validate the types that we at least know about one. */
1263  SMARTLIST_FOREACH_BEGIN(desc->intro_auth_types, const char *, auth) {
1264  for (int idx = 0; intro_auth_types[idx].identifier; idx++) {
1265  if (!strncmp(auth, intro_auth_types[idx].identifier,
1266  strlen(intro_auth_types[idx].identifier))) {
1267  match = 1;
1268  break;
1269  }
1270  }
1271  } SMARTLIST_FOREACH_END(auth);
1272 
1273  return match;
1274 }
1275 
1276 /* Parse a space-delimited list of integers representing CREATE2 formats into
1277  * the bitfield in hs_desc_encrypted_data_t. Ignore unrecognized values. */
1278 static void
1279 decode_create2_list(hs_desc_encrypted_data_t *desc, const char *list)
1280 {
1281  smartlist_t *tokens;
1282 
1283  tor_assert(desc);
1284  tor_assert(list);
1285 
1286  tokens = smartlist_new();
1287  smartlist_split_string(tokens, list, " ", 0, 0);
1288 
1289  SMARTLIST_FOREACH_BEGIN(tokens, char *, s) {
1290  int ok;
1291  unsigned long type = tor_parse_ulong(s, 10, 1, UINT16_MAX, &ok, NULL);
1292  if (!ok) {
1293  log_warn(LD_REND, "Unparseable value %s in create2 list", escaped(s));
1294  continue;
1295  }
1296  switch (type) {
1297  case ONION_HANDSHAKE_TYPE_NTOR:
1298  desc->create2_ntor = 1;
1299  break;
1300  default:
1301  /* We deliberately ignore unsupported handshake types */
1302  continue;
1303  }
1304  } SMARTLIST_FOREACH_END(s);
1305 
1306  SMARTLIST_FOREACH(tokens, char *, s, tor_free(s));
1307  smartlist_free(tokens);
1308 }
1309 
1310 /* Given a certificate, validate the certificate for certain conditions which
1311  * are if the given type matches the cert's one, if the signing key is
1312  * included and if the that key was actually used to sign the certificate.
1313  *
1314  * Return 1 iff if all conditions pass or 0 if one of them fails. */
1315 STATIC int
1316 cert_is_valid(tor_cert_t *cert, uint8_t type, const char *log_obj_type)
1317 {
1318  tor_assert(log_obj_type);
1319 
1320  if (cert == NULL) {
1321  log_warn(LD_REND, "Certificate for %s couldn't be parsed.", log_obj_type);
1322  goto err;
1323  }
1324  if (cert->cert_type != type) {
1325  log_warn(LD_REND, "Invalid cert type %02x for %s.", cert->cert_type,
1326  log_obj_type);
1327  goto err;
1328  }
1329  /* All certificate must have its signing key included. */
1330  if (!cert->signing_key_included) {
1331  log_warn(LD_REND, "Signing key is NOT included for %s.", log_obj_type);
1332  goto err;
1333  }
1334  /* The following will not only check if the signature matches but also the
1335  * expiration date and overall validity. */
1336  if (tor_cert_checksig(cert, &cert->signing_key, approx_time()) < 0) {
1337  log_warn(LD_REND, "Invalid signature for %s: %s", log_obj_type,
1339  goto err;
1340  }
1341 
1342  return 1;
1343  err:
1344  return 0;
1345 }
1346 
1347 /* Given some binary data, try to parse it to get a certificate object. If we
1348  * have a valid cert, validate it using the given wanted type. On error, print
1349  * a log using the err_msg has the certificate identifier adding semantic to
1350  * the log and cert_out is set to NULL. On success, 0 is returned and cert_out
1351  * points to a newly allocated certificate object. */
1352 static int
1353 cert_parse_and_validate(tor_cert_t **cert_out, const char *data,
1354  size_t data_len, unsigned int cert_type_wanted,
1355  const char *err_msg)
1356 {
1357  tor_cert_t *cert;
1358 
1359  tor_assert(cert_out);
1360  tor_assert(data);
1361  tor_assert(err_msg);
1362 
1363  /* Parse certificate. */
1364  cert = tor_cert_parse((const uint8_t *) data, data_len);
1365  if (!cert) {
1366  log_warn(LD_REND, "Certificate for %s couldn't be parsed.", err_msg);
1367  goto err;
1368  }
1369 
1370  /* Validate certificate. */
1371  if (!cert_is_valid(cert, cert_type_wanted, err_msg)) {
1372  goto err;
1373  }
1374 
1375  *cert_out = cert;
1376  return 0;
1377 
1378  err:
1379  tor_cert_free(cert);
1380  *cert_out = NULL;
1381  return -1;
1382 }
1383 
1384 /* Return true iff the given length of the encrypted data of a descriptor
1385  * passes validation. */
1386 STATIC int
1387 encrypted_data_length_is_valid(size_t len)
1388 {
1389  /* Make sure there is enough data for the salt and the mac. The equality is
1390  there to ensure that there is at least one byte of encrypted data. */
1391  if (len <= HS_DESC_ENCRYPTED_SALT_LEN + DIGEST256_LEN) {
1392  log_warn(LD_REND, "Length of descriptor's encrypted data is too small. "
1393  "Got %lu but minimum value is %d",
1394  (unsigned long)len, HS_DESC_ENCRYPTED_SALT_LEN + DIGEST256_LEN);
1395  goto err;
1396  }
1397 
1398  return 1;
1399  err:
1400  return 0;
1401 }
1402 
1403 /* Build the KEYS component for the authorized client computation. The format
1404  * of the construction is:
1405  *
1406  * SECRET_SEED = x25519(sk, pk)
1407  * KEYS = KDF(subcredential | SECRET_SEED, 40)
1408  *
1409  * Set the <b>keys_out</b> argument to point to the buffer containing the KEYS,
1410  * and return the buffer's length. The caller should wipe and free its content
1411  * once done with it. This function can't fail. */
1412 static size_t
1413 build_descriptor_cookie_keys(const uint8_t *subcredential,
1414  size_t subcredential_len,
1415  const curve25519_secret_key_t *sk,
1416  const curve25519_public_key_t *pk,
1417  uint8_t **keys_out)
1418 {
1419  uint8_t secret_seed[CURVE25519_OUTPUT_LEN];
1420  uint8_t *keystream;
1421  size_t keystream_len = HS_DESC_CLIENT_ID_LEN + HS_DESC_COOKIE_KEY_LEN;
1422  crypto_xof_t *xof;
1423 
1424  tor_assert(subcredential);
1425  tor_assert(sk);
1426  tor_assert(pk);
1427  tor_assert(keys_out);
1428 
1429  keystream = tor_malloc_zero(keystream_len);
1430 
1431  /* Calculate x25519(sk, pk) to get the secret seed. */
1432  curve25519_handshake(secret_seed, sk, pk);
1433 
1434  /* Calculate KEYS = KDF(subcredential | SECRET_SEED, 40) */
1435  xof = crypto_xof_new();
1436  crypto_xof_add_bytes(xof, subcredential, subcredential_len);
1437  crypto_xof_add_bytes(xof, secret_seed, sizeof(secret_seed));
1438  crypto_xof_squeeze_bytes(xof, keystream, keystream_len);
1439  crypto_xof_free(xof);
1440 
1441  memwipe(secret_seed, 0, sizeof(secret_seed));
1442 
1443  *keys_out = keystream;
1444  return keystream_len;
1445 }
1446 
1447 /* Decrypt the descriptor cookie given the descriptor, the auth client,
1448  * and the client secret key. On sucess, return 0 and a newly allocated
1449  * descriptor cookie descriptor_cookie_out. On error or if the client id
1450  * is invalid, return -1 and descriptor_cookie_out is set to
1451  * NULL. */
1452 static int
1453 decrypt_descriptor_cookie(const hs_descriptor_t *desc,
1454  const hs_desc_authorized_client_t *client,
1455  const curve25519_secret_key_t *client_auth_sk,
1456  uint8_t **descriptor_cookie_out)
1457 {
1458  int ret = -1;
1459  uint8_t *keystream = NULL;
1460  size_t keystream_length = 0;
1461  uint8_t *descriptor_cookie = NULL;
1462  const uint8_t *cookie_key = NULL;
1463  crypto_cipher_t *cipher = NULL;
1464 
1465  tor_assert(desc);
1466  tor_assert(client);
1467  tor_assert(client_auth_sk);
1469  (char *) &desc->superencrypted_data.auth_ephemeral_pubkey,
1470  sizeof(desc->superencrypted_data.auth_ephemeral_pubkey)));
1471  tor_assert(!tor_mem_is_zero((char *) client_auth_sk,
1472  sizeof(*client_auth_sk)));
1473  tor_assert(!tor_mem_is_zero((char *) desc->subcredential, DIGEST256_LEN));
1474 
1475  /* Get the KEYS component to derive the CLIENT-ID and COOKIE-KEY. */
1476  keystream_length =
1477  build_descriptor_cookie_keys(desc->subcredential, DIGEST256_LEN,
1478  client_auth_sk,
1479  &desc->superencrypted_data.auth_ephemeral_pubkey,
1480  &keystream);
1481  tor_assert(keystream_length > 0);
1482 
1483  /* If the client id of auth client is not the same as the calculcated
1484  * client id, it means that this auth client is invaild according to the
1485  * client secret key client_auth_sk. */
1486  if (tor_memneq(client->client_id, keystream, HS_DESC_CLIENT_ID_LEN)) {
1487  goto done;
1488  }
1489  cookie_key = keystream + HS_DESC_CLIENT_ID_LEN;
1490 
1491  /* This creates a cipher for AES. It can't fail. */
1492  cipher = crypto_cipher_new_with_iv_and_bits(cookie_key, client->iv,
1493  HS_DESC_COOKIE_KEY_BIT_SIZE);
1494  descriptor_cookie = tor_malloc_zero(HS_DESC_DESCRIPTOR_COOKIE_LEN);
1495  /* This can't fail. */
1496  crypto_cipher_decrypt(cipher, (char *) descriptor_cookie,
1497  (const char *) client->encrypted_cookie,
1498  sizeof(client->encrypted_cookie));
1499 
1500  /* Success. */
1501  ret = 0;
1502  done:
1503  *descriptor_cookie_out = descriptor_cookie;
1504  if (cipher) {
1505  crypto_cipher_free(cipher);
1506  }
1507  memwipe(keystream, 0, keystream_length);
1508  tor_free(keystream);
1509  return ret;
1510 }
1511 
1522 MOCK_IMPL(STATIC size_t,
1523 decrypt_desc_layer,(const hs_descriptor_t *desc,
1524  const uint8_t *encrypted_blob,
1525  size_t encrypted_blob_size,
1526  const uint8_t *descriptor_cookie,
1527  int is_superencrypted_layer,
1528  char **decrypted_out))
1529 {
1530  uint8_t *decrypted = NULL;
1531  uint8_t secret_key[HS_DESC_ENCRYPTED_KEY_LEN], secret_iv[CIPHER_IV_LEN];
1532  uint8_t *secret_data = NULL;
1533  size_t secret_data_len = 0;
1534  uint8_t mac_key[DIGEST256_LEN], our_mac[DIGEST256_LEN];
1535  const uint8_t *salt, *encrypted, *desc_mac;
1536  size_t encrypted_len, result_len = 0;
1537 
1538  tor_assert(decrypted_out);
1539  tor_assert(desc);
1540  tor_assert(encrypted_blob);
1541 
1542  /* Construction is as follow: SALT | ENCRYPTED_DATA | MAC .
1543  * Make sure we have enough space for all these things. */
1544  if (!encrypted_data_length_is_valid(encrypted_blob_size)) {
1545  goto err;
1546  }
1547 
1548  /* Start of the blob thus the salt. */
1549  salt = encrypted_blob;
1550 
1551  /* Next is the encrypted data. */
1552  encrypted = encrypted_blob + HS_DESC_ENCRYPTED_SALT_LEN;
1553  encrypted_len = encrypted_blob_size -
1554  (HS_DESC_ENCRYPTED_SALT_LEN + DIGEST256_LEN);
1555  tor_assert(encrypted_len > 0); /* guaranteed by the check above */
1556 
1557  /* And last comes the MAC. */
1558  desc_mac = encrypted_blob + encrypted_blob_size - DIGEST256_LEN;
1559 
1560  /* Build secret data to be used in the decryption. */
1561  secret_data_len = build_secret_data(&desc->plaintext_data.blinded_pubkey,
1562  descriptor_cookie,
1563  &secret_data);
1564 
1565  /* KDF construction resulting in a key from which the secret key, IV and MAC
1566  * key are extracted which is what we need for the decryption. */
1567  build_secret_key_iv_mac(desc, secret_data, secret_data_len,
1568  salt, HS_DESC_ENCRYPTED_SALT_LEN,
1569  secret_key, sizeof(secret_key),
1570  secret_iv, sizeof(secret_iv),
1571  mac_key, sizeof(mac_key),
1572  is_superencrypted_layer);
1573 
1574  /* Build MAC. */
1575  build_mac(mac_key, sizeof(mac_key), salt, HS_DESC_ENCRYPTED_SALT_LEN,
1576  encrypted, encrypted_len, our_mac, sizeof(our_mac));
1577  memwipe(mac_key, 0, sizeof(mac_key));
1578  /* Verify MAC; MAC is H(mac_key || salt || encrypted)
1579  *
1580  * This is a critical check that is making sure the computed MAC matches the
1581  * one in the descriptor. */
1582  if (!tor_memeq(our_mac, desc_mac, sizeof(our_mac))) {
1583  log_info(LD_REND, "Encrypted service descriptor MAC check failed");
1584  goto err;
1585  }
1586 
1587  {
1588  /* Decrypt. Here we are assured that the encrypted length is valid for
1589  * decryption. */
1590  crypto_cipher_t *cipher;
1591 
1592  cipher = crypto_cipher_new_with_iv_and_bits(secret_key, secret_iv,
1593  HS_DESC_ENCRYPTED_BIT_SIZE);
1594  /* Extra byte for the NUL terminated byte. */
1595  decrypted = tor_malloc_zero(encrypted_len + 1);
1596  crypto_cipher_decrypt(cipher, (char *) decrypted,
1597  (const char *) encrypted, encrypted_len);
1598  crypto_cipher_free(cipher);
1599  }
1600 
1601  {
1602  /* Adjust length to remove NUL padding bytes */
1603  uint8_t *end = memchr(decrypted, 0, encrypted_len);
1604  result_len = encrypted_len;
1605  if (end) {
1606  result_len = end - decrypted;
1607  }
1608  }
1609 
1610  if (result_len == 0) {
1611  /* Treat this as an error, so that somebody will free the output. */
1612  goto err;
1613  }
1614 
1615  /* Make sure to NUL terminate the string. */
1616  decrypted[encrypted_len] = '\0';
1617  *decrypted_out = (char *) decrypted;
1618  goto done;
1619 
1620  err:
1621  if (decrypted) {
1622  tor_free(decrypted);
1623  }
1624  *decrypted_out = NULL;
1625  result_len = 0;
1626 
1627  done:
1628  memwipe(secret_data, 0, secret_data_len);
1629  memwipe(secret_key, 0, sizeof(secret_key));
1630  memwipe(secret_iv, 0, sizeof(secret_iv));
1631  tor_free(secret_data);
1632  return result_len;
1633 }
1634 
1635 /* Decrypt the superencrypted section of the descriptor using the given
1636  * descriptor object <b>desc</b>. A newly allocated NUL terminated string is
1637  * put in decrypted_out which contains the superencrypted layer of the
1638  * descriptor. Return the length of decrypted_out on success else 0 is
1639  * returned and decrypted_out is set to NULL. */
1640 static size_t
1641 desc_decrypt_superencrypted(const hs_descriptor_t *desc, char **decrypted_out)
1642 {
1643  size_t superencrypted_len = 0;
1644  char *superencrypted_plaintext = NULL;
1645 
1646  tor_assert(desc);
1647  tor_assert(decrypted_out);
1648 
1649  superencrypted_len = decrypt_desc_layer(desc,
1650  desc->plaintext_data.superencrypted_blob,
1651  desc->plaintext_data.superencrypted_blob_size,
1652  NULL, 1, &superencrypted_plaintext);
1653 
1654  if (!superencrypted_len) {
1655  log_warn(LD_REND, "Decrypting superencrypted desc failed.");
1656  goto done;
1657  }
1658  tor_assert(superencrypted_plaintext);
1659 
1660  done:
1661  /* In case of error, superencrypted_plaintext is already NULL, so the
1662  * following line makes sense. */
1663  *decrypted_out = superencrypted_plaintext;
1664  /* This makes sense too, because, in case of error, this is zero. */
1665  return superencrypted_len;
1666 }
1667 
1668 /* Decrypt the encrypted section of the descriptor using the given descriptor
1669  * object <b>desc</b>. A newly allocated NUL terminated string is put in
1670  * decrypted_out which contains the encrypted layer of the descriptor.
1671  * Return the length of decrypted_out on success else 0 is returned and
1672  * decrypted_out is set to NULL. */
1673 static size_t
1674 desc_decrypt_encrypted(const hs_descriptor_t *desc,
1675  const curve25519_secret_key_t *client_auth_sk,
1676  char **decrypted_out)
1677 {
1678  size_t encrypted_len = 0;
1679  char *encrypted_plaintext = NULL;
1680  uint8_t *descriptor_cookie = NULL;
1681 
1682  tor_assert(desc);
1683  tor_assert(desc->superencrypted_data.clients);
1684  tor_assert(decrypted_out);
1685 
1686  /* If the client secret key is provided, try to find a valid descriptor
1687  * cookie. Otherwise, leave it NULL. */
1688  if (client_auth_sk) {
1689  SMARTLIST_FOREACH_BEGIN(desc->superencrypted_data.clients,
1690  hs_desc_authorized_client_t *, client) {
1691  /* If we can decrypt the descriptor cookie successfully, we will use that
1692  * descriptor cookie and break from the loop. */
1693  if (!decrypt_descriptor_cookie(desc, client, client_auth_sk,
1694  &descriptor_cookie)) {
1695  break;
1696  }
1697  } SMARTLIST_FOREACH_END(client);
1698  }
1699 
1700  encrypted_len = decrypt_desc_layer(desc,
1701  desc->superencrypted_data.encrypted_blob,
1702  desc->superencrypted_data.encrypted_blob_size,
1703  descriptor_cookie, 0, &encrypted_plaintext);
1704  if (!encrypted_len) {
1705  goto err;
1706  }
1707  tor_assert(encrypted_plaintext);
1708 
1709  err:
1710  /* In case of error, encrypted_plaintext is already NULL, so the
1711  * following line makes sense. */
1712  *decrypted_out = encrypted_plaintext;
1713  if (descriptor_cookie) {
1714  memwipe(descriptor_cookie, 0, HS_DESC_DESCRIPTOR_COOKIE_LEN);
1715  }
1716  tor_free(descriptor_cookie);
1717  /* This makes sense too, because, in case of error, this is zero. */
1718  return encrypted_len;
1719 }
1720 
1721 /* Given the token tok for an intro point legacy key, the list of tokens, the
1722  * introduction point ip being decoded and the descriptor desc from which it
1723  * comes from, decode the legacy key and set the intro point object. Return 0
1724  * on success else -1 on failure. */
1725 static int
1726 decode_intro_legacy_key(const directory_token_t *tok,
1727  smartlist_t *tokens,
1729  const hs_descriptor_t *desc)
1730 {
1731  tor_assert(tok);
1732  tor_assert(tokens);
1733  tor_assert(ip);
1734  tor_assert(desc);
1735 
1736  if (!crypto_pk_public_exponent_ok(tok->key)) {
1737  log_warn(LD_REND, "Introduction point legacy key is invalid");
1738  goto err;
1739  }
1740  ip->legacy.key = crypto_pk_dup_key(tok->key);
1741  /* Extract the legacy cross certification cert which MUST be present if we
1742  * have a legacy key. */
1743  tok = find_opt_by_keyword(tokens, R3_INTRO_LEGACY_KEY_CERT);
1744  if (!tok) {
1745  log_warn(LD_REND, "Introduction point legacy key cert is missing");
1746  goto err;
1747  }
1748  tor_assert(tok->object_body);
1749  if (strcmp(tok->object_type, "CROSSCERT")) {
1750  /* Info level because this might be an unknown field that we should
1751  * ignore. */
1752  log_info(LD_REND, "Introduction point legacy encryption key "
1753  "cross-certification has an unknown format.");
1754  goto err;
1755  }
1756  /* Keep a copy of the certificate. */
1757  ip->legacy.cert.encoded = tor_memdup(tok->object_body, tok->object_size);
1758  ip->legacy.cert.len = tok->object_size;
1759  /* The check on the expiration date is for the entire lifetime of a
1760  * certificate which is 24 hours. However, a descriptor has a maximum
1761  * lifetime of 12 hours meaning we have a 12h difference between the two
1762  * which ultimately accommodate the clock skewed client. */
1763  if (rsa_ed25519_crosscert_check(ip->legacy.cert.encoded,
1764  ip->legacy.cert.len, ip->legacy.key,
1765  &desc->plaintext_data.signing_pubkey,
1766  approx_time() - HS_DESC_CERT_LIFETIME)) {
1767  log_warn(LD_REND, "Unable to check cross-certification on the "
1768  "introduction point legacy encryption key.");
1769  ip->cross_certified = 0;
1770  goto err;
1771  }
1772 
1773  /* Success. */
1774  return 0;
1775  err:
1776  return -1;
1777 }
1778 
1779 /* Dig into the descriptor <b>tokens</b> to find the onion key we should use
1780  * for this intro point, and set it into <b>onion_key_out</b>. Return 0 if it
1781  * was found and well-formed, otherwise return -1 in case of errors. */
1782 static int
1783 set_intro_point_onion_key(curve25519_public_key_t *onion_key_out,
1784  const smartlist_t *tokens)
1785 {
1786  int retval = -1;
1787  smartlist_t *onion_keys = NULL;
1788 
1789  tor_assert(onion_key_out);
1790 
1791  onion_keys = find_all_by_keyword(tokens, R3_INTRO_ONION_KEY);
1792  if (!onion_keys) {
1793  log_warn(LD_REND, "Descriptor did not contain intro onion keys");
1794  goto err;
1795  }
1796 
1797  SMARTLIST_FOREACH_BEGIN(onion_keys, directory_token_t *, tok) {
1798  /* This field is using GE(2) so for possible forward compatibility, we
1799  * accept more fields but must be at least 2. */
1800  tor_assert(tok->n_args >= 2);
1801 
1802  /* Try to find an ntor key, it's the only recognized type right now */
1803  if (!strcmp(tok->args[0], "ntor")) {
1804  if (curve25519_public_from_base64(onion_key_out, tok->args[1]) < 0) {
1805  log_warn(LD_REND, "Introduction point ntor onion-key is invalid");
1806  goto err;
1807  }
1808  /* Got the onion key! Set the appropriate retval */
1809  retval = 0;
1810  }
1811  } SMARTLIST_FOREACH_END(tok);
1812 
1813  /* Log an error if we didn't find it :( */
1814  if (retval < 0) {
1815  log_warn(LD_REND, "Descriptor did not contain ntor onion keys");
1816  }
1817 
1818  err:
1819  smartlist_free(onion_keys);
1820  return retval;
1821 }
1822 
1823 /* Given the start of a section and the end of it, decode a single
1824  * introduction point from that section. Return a newly allocated introduction
1825  * point object containing the decoded data. Return NULL if the section can't
1826  * be decoded. */
1827 STATIC hs_desc_intro_point_t *
1828 decode_introduction_point(const hs_descriptor_t *desc, const char *start)
1829 {
1830  hs_desc_intro_point_t *ip = NULL;
1831  memarea_t *area = NULL;
1832  smartlist_t *tokens = NULL;
1833  const directory_token_t *tok;
1834 
1835  tor_assert(desc);
1836  tor_assert(start);
1837 
1838  area = memarea_new();
1839  tokens = smartlist_new();
1840  if (tokenize_string(area, start, start + strlen(start),
1841  tokens, hs_desc_intro_point_v3_token_table, 0) < 0) {
1842  log_warn(LD_REND, "Introduction point is not parseable");
1843  goto err;
1844  }
1845 
1846  /* Ok we seem to have a well formed section containing enough tokens to
1847  * parse. Allocate our IP object and try to populate it. */
1848  ip = hs_desc_intro_point_new();
1849 
1850  /* "introduction-point" SP link-specifiers NL */
1851  tok = find_by_keyword(tokens, R3_INTRODUCTION_POINT);
1852  tor_assert(tok->n_args == 1);
1853  /* Our constructor creates this list by default so free it. */
1854  smartlist_free(ip->link_specifiers);
1855  ip->link_specifiers = decode_link_specifiers(tok->args[0]);
1856  if (!ip->link_specifiers) {
1857  log_warn(LD_REND, "Introduction point has invalid link specifiers");
1858  goto err;
1859  }
1860 
1861  /* "onion-key" SP ntor SP key NL */
1862  if (set_intro_point_onion_key(&ip->onion_key, tokens) < 0) {
1863  goto err;
1864  }
1865 
1866  /* "auth-key" NL certificate NL */
1867  tok = find_by_keyword(tokens, R3_INTRO_AUTH_KEY);
1868  tor_assert(tok->object_body);
1869  if (strcmp(tok->object_type, "ED25519 CERT")) {
1870  log_warn(LD_REND, "Unexpected object type for introduction auth key");
1871  goto err;
1872  }
1873  /* Parse cert and do some validation. */
1874  if (cert_parse_and_validate(&ip->auth_key_cert, tok->object_body,
1875  tok->object_size, CERT_TYPE_AUTH_HS_IP_KEY,
1876  "introduction point auth-key") < 0) {
1877  goto err;
1878  }
1879  /* Validate authentication certificate with descriptor signing key. */
1880  if (tor_cert_checksig(ip->auth_key_cert,
1881  &desc->plaintext_data.signing_pubkey, 0) < 0) {
1882  log_warn(LD_REND, "Invalid authentication key signature: %s",
1883  tor_cert_describe_signature_status(ip->auth_key_cert));
1884  goto err;
1885  }
1886 
1887  /* Exactly one "enc-key" SP "ntor" SP key NL */
1888  tok = find_by_keyword(tokens, R3_INTRO_ENC_KEY);
1889  if (!strcmp(tok->args[0], "ntor")) {
1890  /* This field is using GE(2) so for possible forward compatibility, we
1891  * accept more fields but must be at least 2. */
1892  tor_assert(tok->n_args >= 2);
1893 
1894  if (curve25519_public_from_base64(&ip->enc_key, tok->args[1]) < 0) {
1895  log_warn(LD_REND, "Introduction point ntor enc-key is invalid");
1896  goto err;
1897  }
1898  } else {
1899  /* Unknown key type so we can't use that introduction point. */
1900  log_warn(LD_REND, "Introduction point encryption key is unrecognized.");
1901  goto err;
1902  }
1903 
1904  /* Exactly once "enc-key-cert" NL certificate NL */
1905  tok = find_by_keyword(tokens, R3_INTRO_ENC_KEY_CERT);
1906  tor_assert(tok->object_body);
1907  /* Do the cross certification. */
1908  if (strcmp(tok->object_type, "ED25519 CERT")) {
1909  log_warn(LD_REND, "Introduction point ntor encryption key "
1910  "cross-certification has an unknown format.");
1911  goto err;
1912  }
1913  if (cert_parse_and_validate(&ip->enc_key_cert, tok->object_body,
1914  tok->object_size, CERT_TYPE_CROSS_HS_IP_KEYS,
1915  "introduction point enc-key-cert") < 0) {
1916  goto err;
1917  }
1918  if (tor_cert_checksig(ip->enc_key_cert,
1919  &desc->plaintext_data.signing_pubkey, 0) < 0) {
1920  log_warn(LD_REND, "Invalid encryption key signature: %s",
1921  tor_cert_describe_signature_status(ip->enc_key_cert));
1922  goto err;
1923  }
1924  /* It is successfully cross certified. Flag the object. */
1925  ip->cross_certified = 1;
1926 
1927  /* Do we have a "legacy-key" SP key NL ?*/
1928  tok = find_opt_by_keyword(tokens, R3_INTRO_LEGACY_KEY);
1929  if (tok) {
1930  if (decode_intro_legacy_key(tok, tokens, ip, desc) < 0) {
1931  goto err;
1932  }
1933  }
1934 
1935  /* Introduction point has been parsed successfully. */
1936  goto done;
1937 
1938  err:
1939  hs_desc_intro_point_free(ip);
1940  ip = NULL;
1941 
1942  done:
1944  smartlist_free(tokens);
1945  if (area) {
1946  memarea_drop_all(area);
1947  }
1948 
1949  return ip;
1950 }
1951 
1952 /* Given a descriptor string at <b>data</b>, decode all possible introduction
1953  * points that we can find. Add the introduction point object to desc_enc as we
1954  * find them. This function can't fail and it is possible that zero
1955  * introduction points can be decoded. */
1956 static void
1957 decode_intro_points(const hs_descriptor_t *desc,
1958  hs_desc_encrypted_data_t *desc_enc,
1959  const char *data)
1960 {
1961  smartlist_t *chunked_desc = smartlist_new();
1962  smartlist_t *intro_points = smartlist_new();
1963 
1964  tor_assert(desc);
1965  tor_assert(desc_enc);
1966  tor_assert(data);
1967  tor_assert(desc_enc->intro_points);
1968 
1969  /* Take the desc string, and extract the intro point substrings out of it */
1970  {
1971  /* Split the descriptor string using the intro point header as delimiter */
1972  smartlist_split_string(chunked_desc, data, str_intro_point_start, 0, 0);
1973 
1974  /* Check if there are actually any intro points included. The first chunk
1975  * should be other descriptor fields (e.g. create2-formats), so it's not an
1976  * intro point. */
1977  if (smartlist_len(chunked_desc) < 2) {
1978  goto done;
1979  }
1980  }
1981 
1982  /* Take the intro point substrings, and prepare them for parsing */
1983  {
1984  int i = 0;
1985  /* Prepend the introduction-point header to all the chunks, since
1986  smartlist_split_string() devoured it. */
1987  SMARTLIST_FOREACH_BEGIN(chunked_desc, char *, chunk) {
1988  /* Ignore first chunk. It's other descriptor fields. */
1989  if (i++ == 0) {
1990  continue;
1991  }
1992 
1993  smartlist_add_asprintf(intro_points, "%s %s", str_intro_point, chunk);
1994  } SMARTLIST_FOREACH_END(chunk);
1995  }
1996 
1997  /* Parse the intro points! */
1998  SMARTLIST_FOREACH_BEGIN(intro_points, const char *, intro_point) {
1999  hs_desc_intro_point_t *ip = decode_introduction_point(desc, intro_point);
2000  if (!ip) {
2001  /* Malformed introduction point section. We'll ignore this introduction
2002  * point and continue parsing. New or unknown fields are possible for
2003  * forward compatibility. */
2004  continue;
2005  }
2006  smartlist_add(desc_enc->intro_points, ip);
2007  } SMARTLIST_FOREACH_END(intro_point);
2008 
2009  done:
2010  SMARTLIST_FOREACH(chunked_desc, char *, a, tor_free(a));
2011  smartlist_free(chunked_desc);
2012  SMARTLIST_FOREACH(intro_points, char *, a, tor_free(a));
2013  smartlist_free(intro_points);
2014 }
2015 /* Return 1 iff the given base64 encoded signature in b64_sig from the encoded
2016  * descriptor in encoded_desc validates the descriptor content. */
2017 STATIC int
2018 desc_sig_is_valid(const char *b64_sig,
2019  const ed25519_public_key_t *signing_pubkey,
2020  const char *encoded_desc, size_t encoded_len)
2021 {
2022  int ret = 0;
2023  ed25519_signature_t sig;
2024  const char *sig_start;
2025 
2026  tor_assert(b64_sig);
2027  tor_assert(signing_pubkey);
2028  tor_assert(encoded_desc);
2029  /* Verifying nothing won't end well :). */
2030  tor_assert(encoded_len > 0);
2031 
2032  /* Signature length check. */
2033  if (strlen(b64_sig) != ED25519_SIG_BASE64_LEN) {
2034  log_warn(LD_REND, "Service descriptor has an invalid signature length."
2035  "Exptected %d but got %lu",
2036  ED25519_SIG_BASE64_LEN, (unsigned long) strlen(b64_sig));
2037  goto err;
2038  }
2039 
2040  /* First, convert base64 blob to an ed25519 signature. */
2041  if (ed25519_signature_from_base64(&sig, b64_sig) != 0) {
2042  log_warn(LD_REND, "Service descriptor does not contain a valid "
2043  "signature");
2044  goto err;
2045  }
2046 
2047  /* Find the start of signature. */
2048  sig_start = tor_memstr(encoded_desc, encoded_len, "\n" str_signature " ");
2049  /* Getting here means the token parsing worked for the signature so if we
2050  * can't find the start of the signature, we have a code flow issue. */
2051  if (!sig_start) {
2052  log_warn(LD_GENERAL, "Malformed signature line. Rejecting.");
2053  goto err;
2054  }
2055  /* Skip newline, it has to go in the signature check. */
2056  sig_start++;
2057 
2058  /* Validate signature with the full body of the descriptor. */
2059  if (ed25519_checksig_prefixed(&sig,
2060  (const uint8_t *) encoded_desc,
2061  sig_start - encoded_desc,
2062  str_desc_sig_prefix,
2063  signing_pubkey) != 0) {
2064  log_warn(LD_REND, "Invalid signature on service descriptor");
2065  goto err;
2066  }
2067  /* Valid signature! All is good. */
2068  ret = 1;
2069 
2070  err:
2071  return ret;
2072 }
2073 
2074 /* Decode descriptor plaintext data for version 3. Given a list of tokens, an
2075  * allocated plaintext object that will be populated and the encoded
2076  * descriptor with its length. The last one is needed for signature
2077  * verification. Unknown tokens are simply ignored so this won't error on
2078  * unknowns but requires that all v3 token be present and valid.
2079  *
2080  * Return 0 on success else a negative value. */
2081 static int
2082 desc_decode_plaintext_v3(smartlist_t *tokens,
2084  const char *encoded_desc, size_t encoded_len)
2085 {
2086  int ok;
2087  directory_token_t *tok;
2088 
2089  tor_assert(tokens);
2090  tor_assert(desc);
2091  /* Version higher could still use this function to decode most of the
2092  * descriptor and then they decode the extra part. */
2093  tor_assert(desc->version >= 3);
2094 
2095  /* Descriptor lifetime parsing. */
2096  tok = find_by_keyword(tokens, R3_DESC_LIFETIME);
2097  tor_assert(tok->n_args == 1);
2098  desc->lifetime_sec = (uint32_t) tor_parse_ulong(tok->args[0], 10, 0,
2099  UINT32_MAX, &ok, NULL);
2100  if (!ok) {
2101  log_warn(LD_REND, "Service descriptor lifetime value is invalid");
2102  goto err;
2103  }
2104  /* Put it from minute to second. */
2105  desc->lifetime_sec *= 60;
2106  if (desc->lifetime_sec > HS_DESC_MAX_LIFETIME) {
2107  log_warn(LD_REND, "Service descriptor lifetime is too big. "
2108  "Got %" PRIu32 " but max is %d",
2109  desc->lifetime_sec, HS_DESC_MAX_LIFETIME);
2110  goto err;
2111  }
2112 
2113  /* Descriptor signing certificate. */
2114  tok = find_by_keyword(tokens, R3_DESC_SIGNING_CERT);
2115  tor_assert(tok->object_body);
2116  /* Expecting a prop220 cert with the signing key extension, which contains
2117  * the blinded public key. */
2118  if (strcmp(tok->object_type, "ED25519 CERT") != 0) {
2119  log_warn(LD_REND, "Service descriptor signing cert wrong type (%s)",
2120  escaped(tok->object_type));
2121  goto err;
2122  }
2123  if (cert_parse_and_validate(&desc->signing_key_cert, tok->object_body,
2124  tok->object_size, CERT_TYPE_SIGNING_HS_DESC,
2125  "service descriptor signing key") < 0) {
2126  goto err;
2127  }
2128 
2129  /* Copy the public keys into signing_pubkey and blinded_pubkey */
2130  memcpy(&desc->signing_pubkey, &desc->signing_key_cert->signed_key,
2131  sizeof(ed25519_public_key_t));
2132  memcpy(&desc->blinded_pubkey, &desc->signing_key_cert->signing_key,
2133  sizeof(ed25519_public_key_t));
2134 
2135  /* Extract revision counter value. */
2136  tok = find_by_keyword(tokens, R3_REVISION_COUNTER);
2137  tor_assert(tok->n_args == 1);
2138  desc->revision_counter = tor_parse_uint64(tok->args[0], 10, 0,
2139  UINT64_MAX, &ok, NULL);
2140  if (!ok) {
2141  log_warn(LD_REND, "Service descriptor revision-counter is invalid");
2142  goto err;
2143  }
2144 
2145  /* Extract the superencrypted data section. */
2146  tok = find_by_keyword(tokens, R3_SUPERENCRYPTED);
2147  tor_assert(tok->object_body);
2148  if (strcmp(tok->object_type, "MESSAGE") != 0) {
2149  log_warn(LD_REND, "Desc superencrypted data section is invalid");
2150  goto err;
2151  }
2152  /* Make sure the length of the superencrypted blob is valid. */
2153  if (!encrypted_data_length_is_valid(tok->object_size)) {
2154  goto err;
2155  }
2156 
2157  /* Copy the superencrypted blob to the descriptor object so we can handle it
2158  * latter if needed. */
2159  desc->superencrypted_blob = tor_memdup(tok->object_body, tok->object_size);
2160  desc->superencrypted_blob_size = tok->object_size;
2161 
2162  /* Extract signature and verify it. */
2163  tok = find_by_keyword(tokens, R3_SIGNATURE);
2164  tor_assert(tok->n_args == 1);
2165  /* First arg here is the actual encoded signature. */
2166  if (!desc_sig_is_valid(tok->args[0], &desc->signing_pubkey,
2167  encoded_desc, encoded_len)) {
2168  goto err;
2169  }
2170 
2171  return 0;
2172 
2173  err:
2174  return -1;
2175 }
2176 
2177 /* Decode the version 3 superencrypted section of the given descriptor desc.
2178  * The desc_superencrypted_out will be populated with the decoded data.
2179  * Return 0 on success else -1. */
2180 static int
2181 desc_decode_superencrypted_v3(const hs_descriptor_t *desc,
2183  desc_superencrypted_out)
2184 {
2185  int ret = -1;
2186  char *message = NULL;
2187  size_t message_len;
2188  memarea_t *area = NULL;
2189  directory_token_t *tok;
2190  smartlist_t *tokens = NULL;
2191  /* Rename the parameter because it is too long. */
2192  hs_desc_superencrypted_data_t *superencrypted = desc_superencrypted_out;
2193 
2194  tor_assert(desc);
2195  tor_assert(desc_superencrypted_out);
2196 
2197  /* Decrypt the superencrypted data that is located in the plaintext section
2198  * in the descriptor as a blob of bytes. */
2199  message_len = desc_decrypt_superencrypted(desc, &message);
2200  if (!message_len) {
2201  log_warn(LD_REND, "Service descriptor decryption failed.");
2202  goto err;
2203  }
2204  tor_assert(message);
2205 
2206  area = memarea_new();
2207  tokens = smartlist_new();
2208  if (tokenize_string(area, message, message + message_len,
2209  tokens, hs_desc_superencrypted_v3_token_table, 0) < 0) {
2210  log_warn(LD_REND, "Superencrypted service descriptor is not parseable.");
2211  goto err;
2212  }
2213 
2214  /* Verify desc auth type */
2215  tok = find_by_keyword(tokens, R3_DESC_AUTH_TYPE);
2216  tor_assert(tok->n_args >= 1);
2217  if (strcmp(tok->args[0], "x25519")) {
2218  log_warn(LD_DIR, "Unrecognized desc auth type");
2219  goto err;
2220  }
2221 
2222  /* Extract desc auth ephemeral key */
2223  tok = find_by_keyword(tokens, R3_DESC_AUTH_KEY);
2224  tor_assert(tok->n_args >= 1);
2225  if (curve25519_public_from_base64(&superencrypted->auth_ephemeral_pubkey,
2226  tok->args[0]) < 0) {
2227  log_warn(LD_DIR, "Bogus desc auth ephemeral key in HS desc");
2228  goto err;
2229  }
2230 
2231  /* Extract desc auth client items */
2232  if (!superencrypted->clients) {
2233  superencrypted->clients = smartlist_new();
2234  }
2235  SMARTLIST_FOREACH_BEGIN(tokens, const directory_token_t *, token) {
2236  if (token->tp == R3_DESC_AUTH_CLIENT) {
2237  tor_assert(token->n_args >= 3);
2238 
2239  hs_desc_authorized_client_t *client =
2240  tor_malloc_zero(sizeof(hs_desc_authorized_client_t));
2241 
2242  if (decode_auth_client(token, client) < 0) {
2243  log_warn(LD_REND, "Descriptor client authorization section can't "
2244  "be decoded.");
2245  tor_free(client);
2246  goto err;
2247  }
2248  smartlist_add(superencrypted->clients, client);
2249  }
2250  } SMARTLIST_FOREACH_END(token);
2251 
2252  /* Extract the encrypted data section. */
2253  tok = find_by_keyword(tokens, R3_ENCRYPTED);
2254  tor_assert(tok->object_body);
2255  if (strcmp(tok->object_type, "MESSAGE") != 0) {
2256  log_warn(LD_REND, "Desc encrypted data section is invalid");
2257  goto err;
2258  }
2259  /* Make sure the length of the encrypted blob is valid. */
2260  if (!encrypted_data_length_is_valid(tok->object_size)) {
2261  goto err;
2262  }
2263 
2264  /* Copy the encrypted blob to the descriptor object so we can handle it
2265  * latter if needed. */
2266  tor_assert(tok->object_size <= INT_MAX);
2267  superencrypted->encrypted_blob = tor_memdup(tok->object_body,
2268  tok->object_size);
2269  superencrypted->encrypted_blob_size = tok->object_size;
2270 
2271  ret = 0;
2272  goto done;
2273 
2274  err:
2275  tor_assert(ret < 0);
2276  hs_desc_superencrypted_data_free_contents(desc_superencrypted_out);
2277 
2278  done:
2279  if (tokens) {
2281  smartlist_free(tokens);
2282  }
2283  if (area) {
2284  memarea_drop_all(area);
2285  }
2286  if (message) {
2287  tor_free(message);
2288  }
2289  return ret;
2290 }
2291 
2292 /* Decode the version 3 encrypted section of the given descriptor desc. The
2293  * desc_encrypted_out will be populated with the decoded data. Return 0 on
2294  * success else -1. */
2295 static int
2296 desc_decode_encrypted_v3(const hs_descriptor_t *desc,
2297  const curve25519_secret_key_t *client_auth_sk,
2298  hs_desc_encrypted_data_t *desc_encrypted_out)
2299 {
2300  int ret = -1;
2301  char *message = NULL;
2302  size_t message_len;
2303  memarea_t *area = NULL;
2304  directory_token_t *tok;
2305  smartlist_t *tokens = NULL;
2306 
2307  tor_assert(desc);
2308  tor_assert(desc_encrypted_out);
2309 
2310  /* Decrypt the encrypted data that is located in the superencrypted section
2311  * in the descriptor as a blob of bytes. */
2312  message_len = desc_decrypt_encrypted(desc, client_auth_sk, &message);
2313  if (!message_len) {
2314  /* Two possible situation here. Either we have a client authorization
2315  * configured that didn't work or we do not have any configured for this
2316  * onion address so likely the descriptor is for authorized client only,
2317  * we are not. */
2318  if (client_auth_sk) {
2319  /* At warning level so the client can notice that its client
2320  * authorization is failing. */
2321  log_warn(LD_REND, "Client authorization for requested onion address "
2322  "is invalid. Can't decrypt the descriptor.");
2323  } else {
2324  /* Inform at notice level that the onion address requested can't be
2325  * reached without client authorization most likely. */
2326  log_notice(LD_REND, "Fail to decrypt descriptor for requested onion "
2327  "address. It is likely requiring client "
2328  "authorization.");
2329  }
2330  goto err;
2331  }
2332  tor_assert(message);
2333 
2334  area = memarea_new();
2335  tokens = smartlist_new();
2336  if (tokenize_string(area, message, message + message_len,
2337  tokens, hs_desc_encrypted_v3_token_table, 0) < 0) {
2338  log_warn(LD_REND, "Encrypted service descriptor is not parseable.");
2339  goto err;
2340  }
2341 
2342  /* CREATE2 supported cell format. It's mandatory. */
2343  tok = find_by_keyword(tokens, R3_CREATE2_FORMATS);
2344  tor_assert(tok);
2345  decode_create2_list(desc_encrypted_out, tok->args[0]);
2346  /* Must support ntor according to the specification */
2347  if (!desc_encrypted_out->create2_ntor) {
2348  log_warn(LD_REND, "Service create2-formats does not include ntor.");
2349  goto err;
2350  }
2351 
2352  /* Authentication type. It's optional but only once. */
2353  tok = find_opt_by_keyword(tokens, R3_INTRO_AUTH_REQUIRED);
2354  if (tok) {
2355  if (!decode_auth_type(desc_encrypted_out, tok->args[0])) {
2356  log_warn(LD_REND, "Service descriptor authentication type has "
2357  "invalid entry(ies).");
2358  goto err;
2359  }
2360  }
2361 
2362  /* Is this service a single onion service? */
2363  tok = find_opt_by_keyword(tokens, R3_SINGLE_ONION_SERVICE);
2364  if (tok) {
2365  desc_encrypted_out->single_onion_service = 1;
2366  }
2367 
2368  /* Initialize the descriptor's introduction point list before we start
2369  * decoding. Having 0 intro point is valid. Then decode them all. */
2370  desc_encrypted_out->intro_points = smartlist_new();
2371  decode_intro_points(desc, desc_encrypted_out, message);
2372 
2373  /* Validation of maximum introduction points allowed. */
2374  if (smartlist_len(desc_encrypted_out->intro_points) >
2375  HS_CONFIG_V3_MAX_INTRO_POINTS) {
2376  log_warn(LD_REND, "Service descriptor contains too many introduction "
2377  "points. Maximum allowed is %d but we have %d",
2378  HS_CONFIG_V3_MAX_INTRO_POINTS,
2379  smartlist_len(desc_encrypted_out->intro_points));
2380  goto err;
2381  }
2382 
2383  /* NOTE: Unknown fields are allowed because this function could be used to
2384  * decode other descriptor version. */
2385 
2386  ret = 0;
2387  goto done;
2388 
2389  err:
2390  tor_assert(ret < 0);
2391  hs_desc_encrypted_data_free_contents(desc_encrypted_out);
2392 
2393  done:
2394  if (tokens) {
2396  smartlist_free(tokens);
2397  }
2398  if (area) {
2399  memarea_drop_all(area);
2400  }
2401  if (message) {
2402  tor_free(message);
2403  }
2404  return ret;
2405 }
2406 
2407 /* Table of encrypted decode function version specific. The function are
2408  * indexed by the version number so v3 callback is at index 3 in the array. */
2409 static int
2410  (*decode_encrypted_handlers[])(
2411  const hs_descriptor_t *desc,
2412  const curve25519_secret_key_t *client_auth_sk,
2413  hs_desc_encrypted_data_t *desc_encrypted) =
2414 {
2415  /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
2416  desc_decode_encrypted_v3,
2417 };
2418 
2419 /* Decode the encrypted data section of the given descriptor and store the
2420  * data in the given encrypted data object. Return 0 on success else a
2421  * negative value on error. */
2422 int
2423 hs_desc_decode_encrypted(const hs_descriptor_t *desc,
2424  const curve25519_secret_key_t *client_auth_sk,
2425  hs_desc_encrypted_data_t *desc_encrypted)
2426 {
2427  int ret;
2428  uint32_t version;
2429 
2430  tor_assert(desc);
2431  /* Ease our life a bit. */
2432  version = desc->plaintext_data.version;
2433  tor_assert(desc_encrypted);
2434  /* Calling this function without an encrypted blob to parse is a code flow
2435  * error. The superencrypted parsing should never succeed in the first place
2436  * without an encrypted section. */
2437  tor_assert(desc->superencrypted_data.encrypted_blob);
2438  /* Let's make sure we have a supported version as well. By correctly parsing
2439  * the plaintext, this should not fail. */
2440  if (BUG(!hs_desc_is_supported_version(version))) {
2441  ret = -1;
2442  goto err;
2443  }
2444  /* Extra precaution. Having no handler for the supported version should
2445  * never happened else we forgot to add it but we bumped the version. */
2446  tor_assert(ARRAY_LENGTH(decode_encrypted_handlers) >= version);
2447  tor_assert(decode_encrypted_handlers[version]);
2448 
2449  /* Run the version specific plaintext decoder. */
2450  ret = decode_encrypted_handlers[version](desc, client_auth_sk,
2451  desc_encrypted);
2452  if (ret < 0) {
2453  goto err;
2454  }
2455 
2456  err:
2457  return ret;
2458 }
2459 
2460 /* Table of superencrypted decode function version specific. The function are
2461  * indexed by the version number so v3 callback is at index 3 in the array. */
2462 static int
2463  (*decode_superencrypted_handlers[])(
2464  const hs_descriptor_t *desc,
2465  hs_desc_superencrypted_data_t *desc_superencrypted) =
2466 {
2467  /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
2468  desc_decode_superencrypted_v3,
2469 };
2470 
2471 /* Decode the superencrypted data section of the given descriptor and store the
2472  * data in the given superencrypted data object. Return 0 on success else a
2473  * negative value on error. */
2474 int
2475 hs_desc_decode_superencrypted(const hs_descriptor_t *desc,
2477  desc_superencrypted)
2478 {
2479  int ret;
2480  uint32_t version;
2481 
2482  tor_assert(desc);
2483  /* Ease our life a bit. */
2484  version = desc->plaintext_data.version;
2485  tor_assert(desc_superencrypted);
2486  /* Calling this function without an superencrypted blob to parse is
2487  * a code flow error. The plaintext parsing should never succeed in
2488  * the first place without an superencrypted section. */
2489  tor_assert(desc->plaintext_data.superencrypted_blob);
2490  /* Let's make sure we have a supported version as well. By correctly parsing
2491  * the plaintext, this should not fail. */
2492  if (BUG(!hs_desc_is_supported_version(version))) {
2493  ret = -1;
2494  goto err;
2495  }
2496  /* Extra precaution. Having no handler for the supported version should
2497  * never happened else we forgot to add it but we bumped the version. */
2498  tor_assert(ARRAY_LENGTH(decode_superencrypted_handlers) >= version);
2499  tor_assert(decode_superencrypted_handlers[version]);
2500 
2501  /* Run the version specific plaintext decoder. */
2502  ret = decode_superencrypted_handlers[version](desc, desc_superencrypted);
2503  if (ret < 0) {
2504  goto err;
2505  }
2506 
2507  err:
2508  return ret;
2509 }
2510 
2511 /* Table of plaintext decode function version specific. The function are
2512  * indexed by the version number so v3 callback is at index 3 in the array. */
2513 static int
2514  (*decode_plaintext_handlers[])(
2515  smartlist_t *tokens,
2517  const char *encoded_desc,
2518  size_t encoded_len) =
2519 {
2520  /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
2521  desc_decode_plaintext_v3,
2522 };
2523 
2524 /* Fully decode the given descriptor plaintext and store the data in the
2525  * plaintext data object. Returns 0 on success else a negative value. */
2526 int
2527 hs_desc_decode_plaintext(const char *encoded,
2528  hs_desc_plaintext_data_t *plaintext)
2529 {
2530  int ok = 0, ret = -1;
2531  memarea_t *area = NULL;
2532  smartlist_t *tokens = NULL;
2533  size_t encoded_len;
2534  directory_token_t *tok;
2535 
2536  tor_assert(encoded);
2537  tor_assert(plaintext);
2538 
2539  /* Check that descriptor is within size limits. */
2540  encoded_len = strlen(encoded);
2541  if (encoded_len >= hs_cache_get_max_descriptor_size()) {
2542  log_warn(LD_REND, "Service descriptor is too big (%lu bytes)",
2543  (unsigned long) encoded_len);
2544  goto err;
2545  }
2546 
2547  area = memarea_new();
2548  tokens = smartlist_new();
2549  /* Tokenize the descriptor so we can start to parse it. */
2550  if (tokenize_string(area, encoded, encoded + encoded_len, tokens,
2551  hs_desc_v3_token_table, 0) < 0) {
2552  log_warn(LD_REND, "Service descriptor is not parseable");
2553  goto err;
2554  }
2555 
2556  /* Get the version of the descriptor which is the first mandatory field of
2557  * the descriptor. From there, we'll decode the right descriptor version. */
2558  tok = find_by_keyword(tokens, R_HS_DESCRIPTOR);
2559  tor_assert(tok->n_args == 1);
2560  plaintext->version = (uint32_t) tor_parse_ulong(tok->args[0], 10, 0,
2561  UINT32_MAX, &ok, NULL);
2562  if (!ok) {
2563  log_warn(LD_REND, "Service descriptor has unparseable version %s",
2564  escaped(tok->args[0]));
2565  goto err;
2566  }
2567  if (!hs_desc_is_supported_version(plaintext->version)) {
2568  log_warn(LD_REND, "Service descriptor has unsupported version %" PRIu32,
2569  plaintext->version);
2570  goto err;
2571  }
2572  /* Extra precaution. Having no handler for the supported version should
2573  * never happened else we forgot to add it but we bumped the version. */
2574  tor_assert(ARRAY_LENGTH(decode_plaintext_handlers) >= plaintext->version);
2575  tor_assert(decode_plaintext_handlers[plaintext->version]);
2576 
2577  /* Run the version specific plaintext decoder. */
2578  ret = decode_plaintext_handlers[plaintext->version](tokens, plaintext,
2579  encoded, encoded_len);
2580  if (ret < 0) {
2581  goto err;
2582  }
2583  /* Success. Descriptor has been populated with the data. */
2584  ret = 0;
2585 
2586  err:
2587  if (tokens) {
2589  smartlist_free(tokens);
2590  }
2591  if (area) {
2592  memarea_drop_all(area);
2593  }
2594  return ret;
2595 }
2596 
2597 /* Fully decode an encoded descriptor and set a newly allocated descriptor
2598  * object in desc_out. Client secret key is used to decrypt the "encrypted"
2599  * section if not NULL else it's ignored.
2600  *
2601  * Return 0 on success. A negative value is returned on error and desc_out is
2602  * set to NULL. */
2603 int
2604 hs_desc_decode_descriptor(const char *encoded,
2605  const uint8_t *subcredential,
2606  const curve25519_secret_key_t *client_auth_sk,
2607  hs_descriptor_t **desc_out)
2608 {
2609  int ret = -1;
2610  hs_descriptor_t *desc;
2611 
2612  tor_assert(encoded);
2613 
2614  desc = tor_malloc_zero(sizeof(hs_descriptor_t));
2615 
2616  /* Subcredentials are not optional. */
2617  if (BUG(!subcredential ||
2618  tor_mem_is_zero((char*)subcredential, DIGEST256_LEN))) {
2619  log_warn(LD_GENERAL, "Tried to decrypt without subcred. Impossible!");
2620  goto err;
2621  }
2622 
2623  memcpy(desc->subcredential, subcredential, sizeof(desc->subcredential));
2624 
2625  ret = hs_desc_decode_plaintext(encoded, &desc->plaintext_data);
2626  if (ret < 0) {
2627  goto err;
2628  }
2629 
2630  ret = hs_desc_decode_superencrypted(desc, &desc->superencrypted_data);
2631  if (ret < 0) {
2632  goto err;
2633  }
2634 
2635  ret = hs_desc_decode_encrypted(desc, client_auth_sk, &desc->encrypted_data);
2636  if (ret < 0) {
2637  goto err;
2638  }
2639 
2640  if (desc_out) {
2641  *desc_out = desc;
2642  } else {
2643  hs_descriptor_free(desc);
2644  }
2645  return ret;
2646 
2647  err:
2648  hs_descriptor_free(desc);
2649  if (desc_out) {
2650  *desc_out = NULL;
2651  }
2652 
2653  tor_assert(ret < 0);
2654  return ret;
2655 }
2656 
2657 /* Table of encode function version specific. The functions are indexed by the
2658  * version number so v3 callback is at index 3 in the array. */
2659 static int
2660  (*encode_handlers[])(
2661  const hs_descriptor_t *desc,
2662  const ed25519_keypair_t *signing_kp,
2663  const uint8_t *descriptor_cookie,
2664  char **encoded_out) =
2665 {
2666  /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
2667  desc_encode_v3,
2668 };
2669 
2670 /* Encode the given descriptor desc including signing with the given key pair
2671  * signing_kp and encrypting with the given descriptor cookie.
2672  *
2673  * If the client authorization is enabled, descriptor_cookie must be the same
2674  * as the one used to build hs_desc_authorized_client_t in the descriptor.
2675  * Otherwise, it must be NULL. On success, encoded_out points to a newly
2676  * allocated NUL terminated string that contains the encoded descriptor as
2677  * a string.
2678  *
2679  * Return 0 on success and encoded_out is a valid pointer. On error, -1 is
2680  * returned and encoded_out is set to NULL. */
2681 MOCK_IMPL(int,
2682 hs_desc_encode_descriptor,(const hs_descriptor_t *desc,
2683  const ed25519_keypair_t *signing_kp,
2684  const uint8_t *descriptor_cookie,
2685  char **encoded_out))
2686 {
2687  int ret = -1;
2688  uint32_t version;
2689 
2690  tor_assert(desc);
2691  tor_assert(encoded_out);
2692 
2693  /* Make sure we support the version of the descriptor format. */
2694  version = desc->plaintext_data.version;
2695  if (!hs_desc_is_supported_version(version)) {
2696  goto err;
2697  }
2698  /* Extra precaution. Having no handler for the supported version should
2699  * never happened else we forgot to add it but we bumped the version. */
2700  tor_assert(ARRAY_LENGTH(encode_handlers) >= version);
2701  tor_assert(encode_handlers[version]);
2702 
2703  ret = encode_handlers[version](desc, signing_kp,
2704  descriptor_cookie, encoded_out);
2705  if (ret < 0) {
2706  goto err;
2707  }
2708 
2709  /* Try to decode what we just encoded. Symmetry is nice!, but it is
2710  * symmetric only if the client auth is disabled. That is, the descriptor
2711  * cookie will be NULL. */
2712  if (!descriptor_cookie) {
2713  ret = hs_desc_decode_descriptor(*encoded_out, desc->subcredential,
2714  NULL, NULL);
2715  if (BUG(ret < 0)) {
2716  goto err;
2717  }
2718  }
2719 
2720  return 0;
2721 
2722  err:
2723  *encoded_out = NULL;
2724  return ret;
2725 }
2726 
2727 /* Free the content of the plaintext section of a descriptor. */
2728 void
2729 hs_desc_plaintext_data_free_contents(hs_desc_plaintext_data_t *desc)
2730 {
2731  if (!desc) {
2732  return;
2733  }
2734 
2735  if (desc->superencrypted_blob) {
2736  tor_free(desc->superencrypted_blob);
2737  }
2738  tor_cert_free(desc->signing_key_cert);
2739 
2740  memwipe(desc, 0, sizeof(*desc));
2741 }
2742 
2743 /* Free the content of the superencrypted section of a descriptor. */
2744 void
2745 hs_desc_superencrypted_data_free_contents(hs_desc_superencrypted_data_t *desc)
2746 {
2747  if (!desc) {
2748  return;
2749  }
2750 
2751  if (desc->encrypted_blob) {
2752  tor_free(desc->encrypted_blob);
2753  }
2754  if (desc->clients) {
2755  SMARTLIST_FOREACH(desc->clients, hs_desc_authorized_client_t *, client,
2756  hs_desc_authorized_client_free(client));
2757  smartlist_free(desc->clients);
2758  }
2759 
2760  memwipe(desc, 0, sizeof(*desc));
2761 }
2762 
2763 /* Free the content of the encrypted section of a descriptor. */
2764 void
2765 hs_desc_encrypted_data_free_contents(hs_desc_encrypted_data_t *desc)
2766 {
2767  if (!desc) {
2768  return;
2769  }
2770 
2771  if (desc->intro_auth_types) {
2772  SMARTLIST_FOREACH(desc->intro_auth_types, char *, a, tor_free(a));
2773  smartlist_free(desc->intro_auth_types);
2774  }
2775  if (desc->intro_points) {
2776  SMARTLIST_FOREACH(desc->intro_points, hs_desc_intro_point_t *, ip,
2777  hs_desc_intro_point_free(ip));
2778  smartlist_free(desc->intro_points);
2779  }
2780  memwipe(desc, 0, sizeof(*desc));
2781 }
2782 
2783 /* Free the descriptor plaintext data object. */
2784 void
2785 hs_desc_plaintext_data_free_(hs_desc_plaintext_data_t *desc)
2786 {
2787  hs_desc_plaintext_data_free_contents(desc);
2788  tor_free(desc);
2789 }
2790 
2791 /* Free the descriptor plaintext data object. */
2792 void
2793 hs_desc_superencrypted_data_free_(hs_desc_superencrypted_data_t *desc)
2794 {
2795  hs_desc_superencrypted_data_free_contents(desc);
2796  tor_free(desc);
2797 }
2798 
2799 /* Free the descriptor encrypted data object. */
2800 void
2801 hs_desc_encrypted_data_free_(hs_desc_encrypted_data_t *desc)
2802 {
2803  hs_desc_encrypted_data_free_contents(desc);
2804  tor_free(desc);
2805 }
2806 
2807 /* Free the given descriptor object. */
2808 void
2809 hs_descriptor_free_(hs_descriptor_t *desc)
2810 {
2811  if (!desc) {
2812  return;
2813  }
2814 
2815  hs_desc_plaintext_data_free_contents(&desc->plaintext_data);
2816  hs_desc_superencrypted_data_free_contents(&desc->superencrypted_data);
2817  hs_desc_encrypted_data_free_contents(&desc->encrypted_data);
2818  tor_free(desc);
2819 }
2820 
2821 /* Return the size in bytes of the given plaintext data object. A sizeof() is
2822  * not enough because the object contains pointers and the encrypted blob.
2823  * This is particularly useful for our OOM subsystem that tracks the HSDir
2824  * cache size for instance. */
2825 size_t
2826 hs_desc_plaintext_obj_size(const hs_desc_plaintext_data_t *data)
2827 {
2828  tor_assert(data);
2829  return (sizeof(*data) + sizeof(*data->signing_key_cert) +
2830  data->superencrypted_blob_size);
2831 }
2832 
2833 /* Return the size in bytes of the given encrypted data object. Used by OOM
2834  * subsystem. */
2835 static size_t
2836 hs_desc_encrypted_obj_size(const hs_desc_encrypted_data_t *data)
2837 {
2838  tor_assert(data);
2839  size_t intro_size = 0;
2840  if (data->intro_auth_types) {
2841  intro_size +=
2842  smartlist_len(data->intro_auth_types) * sizeof(intro_auth_types);
2843  }
2844  if (data->intro_points) {
2845  /* XXX could follow pointers here and get more accurate size */
2846  intro_size +=
2847  smartlist_len(data->intro_points) * sizeof(hs_desc_intro_point_t);
2848  }
2849 
2850  return sizeof(*data) + intro_size;
2851 }
2852 
2853 /* Return the size in bytes of the given descriptor object. Used by OOM
2854  * subsystem. */
2855  size_t
2856 hs_desc_obj_size(const hs_descriptor_t *data)
2857 {
2858  tor_assert(data);
2859  return (hs_desc_plaintext_obj_size(&data->plaintext_data) +
2860  hs_desc_encrypted_obj_size(&data->encrypted_data) +
2861  sizeof(data->subcredential));
2862 }
2863 
2864 /* Return a newly allocated descriptor intro point. */
2866 hs_desc_intro_point_new(void)
2867 {
2868  hs_desc_intro_point_t *ip = tor_malloc_zero(sizeof(*ip));
2869  ip->link_specifiers = smartlist_new();
2870  return ip;
2871 }
2872 
2873 /* Free a descriptor intro point object. */
2874 void
2875 hs_desc_intro_point_free_(hs_desc_intro_point_t *ip)
2876 {
2877  if (ip == NULL) {
2878  return;
2879  }
2880  if (ip->link_specifiers) {
2881  SMARTLIST_FOREACH(ip->link_specifiers, hs_desc_link_specifier_t *,
2882  ls, hs_desc_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. */
2895 hs_desc_build_fake_authorized_client(void)
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
2914 hs_desc_build_authorized_client(const uint8_t *subcredential,
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(!tor_mem_is_zero((char *) auth_ephemeral_sk,
2932  sizeof(*auth_ephemeral_sk)));
2933  tor_assert(!tor_mem_is_zero((char *) client_auth_pk,
2934  sizeof(*client_auth_pk)));
2935  tor_assert(!tor_mem_is_zero((char *) descriptor_cookie,
2936  HS_DESC_DESCRIPTOR_COOKIE_LEN));
2937  tor_assert(!tor_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, DIGEST256_LEN,
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
2970 hs_desc_authorized_client_free_(hs_desc_authorized_client_t *client)
2971 {
2972  tor_free(client);
2973 }
2974 
2975 /* Free the given descriptor link specifier. */
2976 void
2977 hs_desc_link_specifier_free_(hs_desc_link_specifier_t *ls)
2978 {
2979  if (ls == NULL) {
2980  return;
2981  }
2982  tor_free(ls);
2983 }
2984 
2985 /* Return a newly allocated descriptor link specifier using the given extend
2986  * info and requested type. Return NULL on error. */
2988 hs_desc_link_specifier_new(const extend_info_t *info, uint8_t type)
2989 {
2990  hs_desc_link_specifier_t *ls = NULL;
2991 
2992  tor_assert(info);
2993 
2994  ls = tor_malloc_zero(sizeof(*ls));
2995  ls->type = type;
2996  switch (ls->type) {
2997  case LS_IPV4:
2998  if (info->addr.family != AF_INET) {
2999  goto err;
3000  }
3001  tor_addr_copy(&ls->u.ap.addr, &info->addr);
3002  ls->u.ap.port = info->port;
3003  break;
3004  case LS_IPV6:
3005  if (info->addr.family != AF_INET6) {
3006  goto err;
3007  }
3008  tor_addr_copy(&ls->u.ap.addr, &info->addr);
3009  ls->u.ap.port = info->port;
3010  break;
3011  case LS_LEGACY_ID:
3012  /* Bug out if the identity digest is not set */
3013  if (BUG(tor_mem_is_zero(info->identity_digest,
3014  sizeof(info->identity_digest)))) {
3015  goto err;
3016  }
3017  memcpy(ls->u.legacy_id, info->identity_digest, sizeof(ls->u.legacy_id));
3018  break;
3019  case LS_ED25519_ID:
3020  /* ed25519 keys are optional for intro points */
3022  goto err;
3023  }
3024  memcpy(ls->u.ed25519_id, info->ed_identity.pubkey,
3025  sizeof(ls->u.ed25519_id));
3026  break;
3027  default:
3028  /* Unknown type is code flow error. */
3029  tor_assert(0);
3030  }
3031 
3032  return ls;
3033  err:
3034  tor_free(ls);
3035  return NULL;
3036 }
3037 
3038 /* From the given descriptor, remove and free every introduction point. */
3039 void
3040 hs_descriptor_clear_intro_points(hs_descriptor_t *desc)
3041 {
3042  smartlist_t *ips;
3043 
3044  tor_assert(desc);
3045 
3046  ips = desc->encrypted_data.intro_points;
3047  if (ips) {
3049  ip, hs_desc_intro_point_free(ip));
3050  smartlist_clear(ips);
3051  }
3052 }
3053 
3054 /* From a descriptor link specifier object spec, returned a newly allocated
3055  * link specifier object that is the encoded representation of spec. Return
3056  * NULL on error. */
3057 link_specifier_t *
3058 hs_desc_lspec_to_trunnel(const hs_desc_link_specifier_t *spec)
3059 {
3060  tor_assert(spec);
3061 
3062  link_specifier_t *ls = link_specifier_new();
3063  link_specifier_set_ls_type(ls, spec->type);
3064 
3065  switch (spec->type) {
3066  case LS_IPV4:
3067  link_specifier_set_un_ipv4_addr(ls,
3068  tor_addr_to_ipv4h(&spec->u.ap.addr));
3069  link_specifier_set_un_ipv4_port(ls, spec->u.ap.port);
3070  /* Four bytes IPv4 and two bytes port. */
3071  link_specifier_set_ls_len(ls, sizeof(spec->u.ap.addr.addr.in_addr) +
3072  sizeof(spec->u.ap.port));
3073  break;
3074  case LS_IPV6:
3075  {
3076  size_t addr_len = link_specifier_getlen_un_ipv6_addr(ls);
3077  const uint8_t *in6_addr = tor_addr_to_in6_addr8(&spec->u.ap.addr);
3078  uint8_t *ipv6_array = link_specifier_getarray_un_ipv6_addr(ls);
3079  memcpy(ipv6_array, in6_addr, addr_len);
3080  link_specifier_set_un_ipv6_port(ls, spec->u.ap.port);
3081  /* Sixteen bytes IPv6 and two bytes port. */
3082  link_specifier_set_ls_len(ls, addr_len + sizeof(spec->u.ap.port));
3083  break;
3084  }
3085  case LS_LEGACY_ID:
3086  {
3087  size_t legacy_id_len = link_specifier_getlen_un_legacy_id(ls);
3088  uint8_t *legacy_id_array = link_specifier_getarray_un_legacy_id(ls);
3089  memcpy(legacy_id_array, spec->u.legacy_id, legacy_id_len);
3090  link_specifier_set_ls_len(ls, legacy_id_len);
3091  break;
3092  }
3093  case LS_ED25519_ID:
3094  {
3095  size_t ed25519_id_len = link_specifier_getlen_un_ed25519_id(ls);
3096  uint8_t *ed25519_id_array = link_specifier_getarray_un_ed25519_id(ls);
3097  memcpy(ed25519_id_array, spec->u.ed25519_id, ed25519_id_len);
3098  link_specifier_set_ls_len(ls, ed25519_id_len);
3099  break;
3100  }
3101  default:
3102  tor_assert_nonfatal_unreached();
3103  link_specifier_free(ls);
3104  ls = NULL;
3105  }
3106 
3107  return ls;
3108 }
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)
struct crypto_pk_t * key
Definition: parsecommon.h:210
void crypto_digest_add_bytes(crypto_digest_t *digest, const char *data, size_t len)
ed25519_public_key_t signed_key
Definition: torcert.h:25
Header file containing configuration ABI/API for the HS subsytem.
smartlist_t * find_all_by_keyword(const smartlist_t *s, directory_keyword k)
Definition: parsecommon.c:461
Common functions for using (pseudo-)random number generators.
#define END_OF_TABLE
Definition: parsecommon.h:244
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
uint64_t tor_parse_uint64(const char *s, int base, uint64_t min, uint64_t max, int *ok, char **next)
Definition: parse_int.c:107
int tor_cert_checksig(tor_cert_t *cert, const ed25519_public_key_t *pubkey, time_t now)
Definition: torcert.c:244
int tor_mem_is_zero(const char *mem, size_t len)
Definition: util_string.c:74
#define LD_GENERAL
Definition: log.h:58
unsigned long tor_parse_ulong(const char *s, int base, unsigned long min, unsigned long max, int *ok, char **next)
Definition: parse_int.c:75
int curve25519_public_from_base64(curve25519_public_key_t *pkey, const char *input)
int ed25519_signature_to_base64(char *output, const ed25519_signature_t *sig)
int crypto_cipher_encrypt(crypto_cipher_t *env, char *to, const char *from, size_t fromlen)
Definition: crypto_cipher.c:88
void crypto_xof_add_bytes(crypto_xof_t *xof, const uint8_t *data, size_t len)
void smartlist_add(smartlist_t *sl, void *element)
uint8_t cert_type
Definition: torcert.h:38
size_t base64_encode_size(size_t srclen, int flags)
Definition: binascii.c:166
int crypto_pk_write_public_key_to_string(crypto_pk_t *env, char **dest, size_t *len)
Definition: crypto_rsa.c:461
ed25519_public_key_t signing_key
Definition: torcert.h:28
static uint32_t tor_addr_to_ipv4h(const tor_addr_t *a)
Definition: address.h:152
void crypto_xof_squeeze_bytes(crypto_xof_t *xof, uint8_t *out, size_t len)
#define tor_free(p)
Definition: malloc.h:52
#define T1_START(s, t, a, o)
Definition: parsecommon.h:252
#define T1N(s, t, a, o)
Definition: parsecommon.h:256
void memwipe(void *mem, uint8_t byte, size_t sz)
Definition: crypto_util.c:57
void curve25519_handshake(uint8_t *output, const curve25519_secret_key_t *skey, const curve25519_public_key_t *pkey)
memarea_t * memarea_new(void)
Definition: memarea.c:153
unsigned signing_key_included
Definition: torcert.h:40
int base64_encode(char *dest, size_t destlen, const char *src, size_t srclen, int flags)
Definition: binascii.c:215
#define CIPHER_IV_LEN
Definition: crypto_cipher.h:24
#define DIGEST256_LEN
Definition: digest_sizes.h:23
#define NO_ARGS
Definition: parsecommon.h:265
Common functions for cryptographic routines.
tor_assert(buffer)
tor_cert_t * tor_cert_parse(const uint8_t *encoded, const size_t len)
Definition: torcert.c:159
#define tor_addr_from_ipv4h(dest, v4addr)
Definition: address.h:287
Header for crypto_format.c.
int tor_memeq(const void *a, const void *b, size_t sz)
Definition: di_ops.c:107
int tor_asprintf(char **strp, const char *fmt,...)
Definition: printf.c:75
static void set_uint64(void *cp, uint64_t v)
Definition: bytes.h:91
#define SIZE_T_CEILING
Definition: torint.h:126
void tor_addr_from_ipv6_bytes(tor_addr_t *dest, const char *ipv6_bytes)
Definition: address.c:873
void smartlist_add_asprintf(struct smartlist_t *sl, const char *pattern,...)
Definition: smartlist.c:36
int ed25519_public_key_is_zero(const ed25519_public_key_t *pubkey)
Header file for rendcache.c.
#define GE(n)
Definition: parsecommon.h:269
void crypto_digest_get_digest(crypto_digest_t *digest, char *out, size_t out_len)
Master header file for Tor-specific functionality.
Header file for circuitbuild.c.
#define ARGS
Definition: parsecommon.h:263
Header for memarea.c.
#define EQ(n)
Definition: parsecommon.h:271
int crypto_cipher_decrypt(crypto_cipher_t *env, char *to, const char *from, size_t fromlen)
Header file for hs_descriptor.c.
#define CONCAT_ARGS
Definition: parsecommon.h:267
static uint64_t tor_htonll(uint64_t a)
Definition: bytes.h:167
#define LD_REND
Definition: log.h:80
crypto_pk_t * crypto_pk_dup_key(crypto_pk_t *orig)
directory_token_t * find_opt_by_keyword(const smartlist_t *s, directory_keyword keyword)
Definition: parsecommon.c:450
const char * tor_cert_describe_signature_status(const tor_cert_t *cert)
Definition: torcert.c:279
int crypto_pk_public_exponent_ok(const crypto_pk_t *env)
#define CURVE25519_OUTPUT_LEN
Definition: x25519_sizes.h:24
#define T1_END(s, t, a, o)
Definition: parsecommon.h:254
#define LD_DIR
Definition: log.h:84
Header file for parsecommon.c.
char * smartlist_join_strings(smartlist_t *sl, const char *join, int terminate, size_t *len_out)
Definition: smartlist.c:279
int base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:394
char identity_digest[DIGEST_LEN]
#define SMARTLIST_FOREACH(sl, type, var, cmd)
const char * escaped(const char *s)
Definition: escape.c:126
static char * get_all_auth_client_lines(const hs_descriptor_t *desc)
#define ARRAY_LENGTH(x)
void crypto_strongest_rand(uint8_t *out, size_t out_len)
Definition: crypto_rand.c:339
time_t approx_time(void)
Definition: approx_time.c:32
#define T1(s, t, a, o)
Definition: parsecommon.h:250
void token_clear(directory_token_t *tok)
Definition: parsecommon.c:41
Header file for hs_cache.c.
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
#define tor_addr_to_in6_addr8(x)
Definition: address.h:129
int ed25519_signature_from_base64(ed25519_signature_t *sig, const char *input)
MOCK_IMPL(STATIC size_t, decrypt_desc_layer,(const hs_descriptor_t *desc, const uint8_t *encrypted_blob, size_t encrypted_blob_size, const uint8_t *descriptor_cookie, int is_superencrypted_layer, char **decrypted_out))
tor_addr_t addr
void tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
Definition: address.c:892
crypto_xof_t * crypto_xof_new(void)
ed25519_public_key_t ed_identity
void smartlist_clear(smartlist_t *sl)
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
#define T01(s, t, a, o)
Definition: parsecommon.h:258
int curve25519_public_to_base64(char *output, const curve25519_public_key_t *pkey)
#define LD_BUG
Definition: log.h:82
#define CURVE25519_PUBKEY_LEN
Definition: x25519_sizes.h:20
int smartlist_split_string(smartlist_t *sl, const char *str, const char *sep, int flags, int max)
crypto_digest_t * crypto_digest256_new(digest_algorithm_t algorithm)