hs: Encode flow control value in the descriptor
[tor.git] / src / feature / hs / hs_descriptor.c
blob80273c27b153b6f52b6a43a053ec2e276e6f728c
1 /* Copyright (c) 2016-2021, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
4 /**
5 * \file hs_descriptor.c
6 * \brief Handle hidden service descriptor encoding/decoding.
8 * \details
9 * Here is a graphical depiction of an HS descriptor and its layers:
11 * +------------------------------------------------------+
12 * |DESCRIPTOR HEADER: |
13 * | hs-descriptor 3 |
14 * | descriptor-lifetime 180 |
15 * | ... |
16 * | superencrypted |
17 * |+---------------------------------------------------+ |
18 * ||SUPERENCRYPTED LAYER (aka OUTER ENCRYPTED LAYER): | |
19 * || desc-auth-type x25519 | |
20 * || desc-auth-ephemeral-key | |
21 * || auth-client | |
22 * || auth-client | |
23 * || ... | |
24 * || encrypted | |
25 * ||+-------------------------------------------------+| |
26 * |||ENCRYPTED LAYER (aka INNER ENCRYPTED LAYER): || |
27 * ||| create2-formats || |
28 * ||| intro-auth-required || |
29 * ||| introduction-point || |
30 * ||| introduction-point || |
31 * ||| ... || |
32 * ||+-------------------------------------------------+| |
33 * |+---------------------------------------------------+ |
34 * +------------------------------------------------------+
36 * The DESCRIPTOR HEADER section is completely unencrypted and contains generic
37 * descriptor metadata.
39 * The SUPERENCRYPTED LAYER section is the first layer of encryption, and it's
40 * encrypted using the blinded public key of the hidden service to protect
41 * against entities who don't know its onion address. The clients of the hidden
42 * service know its onion address and blinded public key, whereas third-parties
43 * (like HSDirs) don't know it (except if it's a public hidden service).
45 * The ENCRYPTED LAYER section is the second layer of encryption, and it's
46 * encrypted using the client authorization key material (if those exist). When
47 * client authorization is enabled, this second layer of encryption protects
48 * the descriptor content from unauthorized entities. If client authorization
49 * is disabled, this second layer of encryption does not provide any extra
50 * security but is still present. The plaintext of this layer contains all the
51 * information required to connect to the hidden service like its list of
52 * introduction points.
53 **/
55 /* For unit tests.*/
56 #define HS_DESCRIPTOR_PRIVATE
58 #include <stdbool.h>
59 #include "core/or/or.h"
60 #include "app/config/config.h"
61 #include "trunnel/ed25519_cert.h" /* Trunnel interface. */
62 #include "feature/hs/hs_descriptor.h"
63 #include "core/or/circuitbuild.h"
64 #include "core/or/congestion_control_common.h"
65 #include "core/or/protover.h"
66 #include "lib/crypt_ops/crypto_rand.h"
67 #include "lib/crypt_ops/crypto_util.h"
68 #include "feature/dirparse/parsecommon.h"
69 #include "feature/hs/hs_cache.h"
70 #include "feature/hs/hs_config.h"
71 #include "feature/nodelist/torcert.h" /* tor_cert_encode_ed22519() */
72 #include "lib/memarea/memarea.h"
73 #include "lib/crypt_ops/crypto_format.h"
74 #include "core/or/versions.h"
76 #include "core/or/extend_info_st.h"
78 /* Constant string value used for the descriptor format. */
79 #define str_hs_desc "hs-descriptor"
80 #define str_desc_cert "descriptor-signing-key-cert"
81 #define str_rev_counter "revision-counter"
82 #define str_superencrypted "superencrypted"
83 #define str_encrypted "encrypted"
84 #define str_signature "signature"
85 #define str_lifetime "descriptor-lifetime"
86 /* Constant string value for the encrypted part of the descriptor. */
87 #define str_create2_formats "create2-formats"
88 #define str_intro_auth_required "intro-auth-required"
89 #define str_single_onion "single-onion-service"
90 #define str_intro_point "introduction-point"
91 #define str_ip_onion_key "onion-key"
92 #define str_ip_auth_key "auth-key"
93 #define str_ip_enc_key "enc-key"
94 #define str_ip_enc_key_cert "enc-key-cert"
95 #define str_ip_legacy_key "legacy-key"
96 #define str_ip_legacy_key_cert "legacy-key-cert"
97 #define str_intro_point_start "\n" str_intro_point " "
98 #define str_flow_control "flow-control"
99 /* Constant string value for the construction to encrypt the encrypted data
100 * section. */
101 #define str_enc_const_superencryption "hsdir-superencrypted-data"
102 #define str_enc_const_encryption "hsdir-encrypted-data"
103 /* Prefix required to compute/verify HS desc signatures */
104 #define str_desc_sig_prefix "Tor onion service descriptor sig v3"
105 #define str_desc_auth_type "desc-auth-type"
106 #define str_desc_auth_key "desc-auth-ephemeral-key"
107 #define str_desc_auth_client "auth-client"
108 #define str_encrypted "encrypted"
110 /** Authentication supported types. */
111 static const struct {
112 hs_desc_auth_type_t type;
113 const char *identifier;
114 } intro_auth_types[] = {
115 { HS_DESC_AUTH_ED25519, "ed25519" },
116 /* Indicate end of array. */
117 { 0, NULL }
120 /** Descriptor ruleset. */
121 static token_rule_t hs_desc_v3_token_table[] = {
122 T1_START(str_hs_desc, R_HS_DESCRIPTOR, EQ(1), NO_OBJ),
123 T1(str_lifetime, R3_DESC_LIFETIME, EQ(1), NO_OBJ),
124 T1(str_desc_cert, R3_DESC_SIGNING_CERT, NO_ARGS, NEED_OBJ),
125 T1(str_rev_counter, R3_REVISION_COUNTER, EQ(1), NO_OBJ),
126 T1(str_superencrypted, R3_SUPERENCRYPTED, NO_ARGS, NEED_OBJ),
127 T1_END(str_signature, R3_SIGNATURE, EQ(1), NO_OBJ),
128 END_OF_TABLE
131 /** Descriptor ruleset for the superencrypted section. */
132 static token_rule_t hs_desc_superencrypted_v3_token_table[] = {
133 T1_START(str_desc_auth_type, R3_DESC_AUTH_TYPE, GE(1), NO_OBJ),
134 T1(str_desc_auth_key, R3_DESC_AUTH_KEY, GE(1), NO_OBJ),
135 T1N(str_desc_auth_client, R3_DESC_AUTH_CLIENT, GE(3), NO_OBJ),
136 T1(str_encrypted, R3_ENCRYPTED, NO_ARGS, NEED_OBJ),
137 END_OF_TABLE
140 /** Descriptor ruleset for the encrypted section. */
141 static token_rule_t hs_desc_encrypted_v3_token_table[] = {
142 T1_START(str_create2_formats, R3_CREATE2_FORMATS, CONCAT_ARGS, NO_OBJ),
143 T01(str_intro_auth_required, R3_INTRO_AUTH_REQUIRED, GE(1), NO_OBJ),
144 T01(str_single_onion, R3_SINGLE_ONION_SERVICE, ARGS, NO_OBJ),
145 T01(str_flow_control, R3_FLOW_CONTROL, GE(2), NO_OBJ),
146 END_OF_TABLE
149 /** Descriptor ruleset for the introduction points section. */
150 static token_rule_t hs_desc_intro_point_v3_token_table[] = {
151 T1_START(str_intro_point, R3_INTRODUCTION_POINT, EQ(1), NO_OBJ),
152 T1N(str_ip_onion_key, R3_INTRO_ONION_KEY, GE(2), OBJ_OK),
153 T1(str_ip_auth_key, R3_INTRO_AUTH_KEY, NO_ARGS, NEED_OBJ),
154 T1(str_ip_enc_key, R3_INTRO_ENC_KEY, GE(2), OBJ_OK),
155 T1(str_ip_enc_key_cert, R3_INTRO_ENC_KEY_CERT, ARGS, OBJ_OK),
156 T01(str_ip_legacy_key, R3_INTRO_LEGACY_KEY, ARGS, NEED_KEY_1024),
157 T01(str_ip_legacy_key_cert, R3_INTRO_LEGACY_KEY_CERT, ARGS, OBJ_OK),
158 END_OF_TABLE
161 /** Using a key, salt and encrypted payload, build a MAC and put it in mac_out.
162 * We use SHA3-256 for the MAC computation.
163 * This function can't fail. */
164 static void
165 build_mac(const uint8_t *mac_key, size_t mac_key_len,
166 const uint8_t *salt, size_t salt_len,
167 const uint8_t *encrypted, size_t encrypted_len,
168 uint8_t *mac_out, size_t mac_len)
170 crypto_digest_t *digest;
172 const uint64_t mac_len_netorder = tor_htonll(mac_key_len);
173 const uint64_t salt_len_netorder = tor_htonll(salt_len);
175 tor_assert(mac_key);
176 tor_assert(salt);
177 tor_assert(encrypted);
178 tor_assert(mac_out);
180 digest = crypto_digest256_new(DIGEST_SHA3_256);
181 /* As specified in section 2.5 of proposal 224, first add the mac key
182 * then add the salt first and then the encrypted section. */
184 crypto_digest_add_bytes(digest, (const char *) &mac_len_netorder, 8);
185 crypto_digest_add_bytes(digest, (const char *) mac_key, mac_key_len);
186 crypto_digest_add_bytes(digest, (const char *) &salt_len_netorder, 8);
187 crypto_digest_add_bytes(digest, (const char *) salt, salt_len);
188 crypto_digest_add_bytes(digest, (const char *) encrypted, encrypted_len);
189 crypto_digest_get_digest(digest, (char *) mac_out, mac_len);
190 crypto_digest_free(digest);
193 /** Using a secret data and a given descriptor object, build the secret
194 * input needed for the KDF.
196 * secret_input = SECRET_DATA | subcredential | INT_8(revision_counter)
198 * Then, set the newly allocated buffer in secret_input_out and return the
199 * length of the buffer. */
200 static size_t
201 build_secret_input(const hs_descriptor_t *desc,
202 const uint8_t *secret_data,
203 size_t secret_data_len,
204 uint8_t **secret_input_out)
206 size_t offset = 0;
207 size_t secret_input_len = secret_data_len + DIGEST256_LEN + sizeof(uint64_t);
208 uint8_t *secret_input = NULL;
210 tor_assert(desc);
211 tor_assert(secret_data);
212 tor_assert(secret_input_out);
214 secret_input = tor_malloc_zero(secret_input_len);
216 /* Copy the secret data. */
217 memcpy(secret_input, secret_data, secret_data_len);
218 offset += secret_data_len;
219 /* Copy subcredential. */
220 memcpy(secret_input + offset, desc->subcredential.subcred, DIGEST256_LEN);
221 offset += DIGEST256_LEN;
222 /* Copy revision counter value. */
223 set_uint64(secret_input + offset,
224 tor_htonll(desc->plaintext_data.revision_counter));
225 offset += sizeof(uint64_t);
226 tor_assert(secret_input_len == offset);
228 *secret_input_out = secret_input;
230 return secret_input_len;
233 /** Do the KDF construction and put the resulting data in key_out which is of
234 * key_out_len length. It uses SHAKE-256 as specified in the spec. */
235 static void
236 build_kdf_key(const hs_descriptor_t *desc,
237 const uint8_t *secret_data,
238 size_t secret_data_len,
239 const uint8_t *salt, size_t salt_len,
240 uint8_t *key_out, size_t key_out_len,
241 int is_superencrypted_layer)
243 uint8_t *secret_input = NULL;
244 size_t secret_input_len;
245 crypto_xof_t *xof;
247 tor_assert(desc);
248 tor_assert(secret_data);
249 tor_assert(salt);
250 tor_assert(key_out);
252 /* Build the secret input for the KDF computation. */
253 secret_input_len = build_secret_input(desc, secret_data,
254 secret_data_len, &secret_input);
256 xof = crypto_xof_new();
257 /* Feed our KDF. [SHAKE it like a polaroid picture --Yawning]. */
258 crypto_xof_add_bytes(xof, secret_input, secret_input_len);
259 crypto_xof_add_bytes(xof, salt, salt_len);
261 /* Feed in the right string constant based on the desc layer */
262 if (is_superencrypted_layer) {
263 crypto_xof_add_bytes(xof, (const uint8_t *) str_enc_const_superencryption,
264 strlen(str_enc_const_superencryption));
265 } else {
266 crypto_xof_add_bytes(xof, (const uint8_t *) str_enc_const_encryption,
267 strlen(str_enc_const_encryption));
270 /* Eat from our KDF. */
271 crypto_xof_squeeze_bytes(xof, key_out, key_out_len);
272 crypto_xof_free(xof);
273 memwipe(secret_input, 0, secret_input_len);
275 tor_free(secret_input);
278 /** Using the given descriptor, secret data, and salt, run it through our
279 * KDF function and then extract a secret key in key_out, the IV in iv_out
280 * and MAC in mac_out. This function can't fail. */
281 static void
282 build_secret_key_iv_mac(const hs_descriptor_t *desc,
283 const uint8_t *secret_data,
284 size_t secret_data_len,
285 const uint8_t *salt, size_t salt_len,
286 uint8_t *key_out, size_t key_len,
287 uint8_t *iv_out, size_t iv_len,
288 uint8_t *mac_out, size_t mac_len,
289 int is_superencrypted_layer)
291 size_t offset = 0;
292 uint8_t kdf_key[HS_DESC_ENCRYPTED_KDF_OUTPUT_LEN];
294 tor_assert(desc);
295 tor_assert(secret_data);
296 tor_assert(salt);
297 tor_assert(key_out);
298 tor_assert(iv_out);
299 tor_assert(mac_out);
301 build_kdf_key(desc, secret_data, secret_data_len,
302 salt, salt_len, kdf_key, sizeof(kdf_key),
303 is_superencrypted_layer);
304 /* Copy the bytes we need for both the secret key and IV. */
305 memcpy(key_out, kdf_key, key_len);
306 offset += key_len;
307 memcpy(iv_out, kdf_key + offset, iv_len);
308 offset += iv_len;
309 memcpy(mac_out, kdf_key + offset, mac_len);
310 /* Extra precaution to make sure we are not out of bound. */
311 tor_assert((offset + mac_len) == sizeof(kdf_key));
312 memwipe(kdf_key, 0, sizeof(kdf_key));
315 /* === ENCODING === */
317 /** Encode the given link specifier objects into a newly allocated string.
318 * This can't fail so caller can always assume a valid string being
319 * returned. */
320 STATIC char *
321 encode_link_specifiers(const smartlist_t *specs)
323 char *encoded_b64 = NULL;
324 link_specifier_list_t *lslist = link_specifier_list_new();
326 tor_assert(specs);
327 /* No link specifiers is a code flow error, can't happen. */
328 tor_assert(smartlist_len(specs) > 0);
329 tor_assert(smartlist_len(specs) <= UINT8_MAX);
331 link_specifier_list_set_n_spec(lslist, smartlist_len(specs));
333 SMARTLIST_FOREACH_BEGIN(specs, const link_specifier_t *,
334 spec) {
335 link_specifier_t *ls = link_specifier_dup(spec);
336 tor_assert(ls);
337 link_specifier_list_add_spec(lslist, ls);
338 } SMARTLIST_FOREACH_END(spec);
341 uint8_t *encoded;
342 ssize_t encoded_len, encoded_b64_len, ret;
344 encoded_len = link_specifier_list_encoded_len(lslist);
345 tor_assert(encoded_len > 0);
346 encoded = tor_malloc_zero(encoded_len);
347 ret = link_specifier_list_encode(encoded, encoded_len, lslist);
348 tor_assert(ret == encoded_len);
350 /* Base64 encode our binary format. Add extra NUL byte for the base64
351 * encoded value. */
352 encoded_b64_len = base64_encode_size(encoded_len, 0) + 1;
353 encoded_b64 = tor_malloc_zero(encoded_b64_len);
354 ret = base64_encode(encoded_b64, encoded_b64_len, (const char *) encoded,
355 encoded_len, 0);
356 tor_assert(ret == (encoded_b64_len - 1));
357 tor_free(encoded);
360 link_specifier_list_free(lslist);
361 return encoded_b64;
364 /** Encode an introduction point legacy key and certificate. Return a newly
365 * allocated string with it. On failure, return NULL. */
366 static char *
367 encode_legacy_key(const hs_desc_intro_point_t *ip)
369 char *key_str, b64_cert[256], *encoded = NULL;
370 size_t key_str_len;
372 tor_assert(ip);
374 /* Encode cross cert. */
375 if (base64_encode(b64_cert, sizeof(b64_cert),
376 (const char *) ip->legacy.cert.encoded,
377 ip->legacy.cert.len, BASE64_ENCODE_MULTILINE) < 0) {
378 log_warn(LD_REND, "Unable to encode legacy crosscert.");
379 goto done;
381 /* Convert the encryption key to PEM format NUL terminated. */
382 if (crypto_pk_write_public_key_to_string(ip->legacy.key, &key_str,
383 &key_str_len) < 0) {
384 log_warn(LD_REND, "Unable to encode legacy encryption key.");
385 goto done;
387 tor_asprintf(&encoded,
388 "%s \n%s" /* Newline is added by the call above. */
389 "%s\n"
390 "-----BEGIN CROSSCERT-----\n"
391 "%s"
392 "-----END CROSSCERT-----",
393 str_ip_legacy_key, key_str,
394 str_ip_legacy_key_cert, b64_cert);
395 tor_free(key_str);
397 done:
398 return encoded;
401 /** Encode an introduction point encryption key and certificate. Return a newly
402 * allocated string with it. On failure, return NULL. */
403 static char *
404 encode_enc_key(const hs_desc_intro_point_t *ip)
406 char *encoded = NULL, *encoded_cert;
407 char key_b64[CURVE25519_BASE64_PADDED_LEN + 1];
409 tor_assert(ip);
411 /* Base64 encode the encryption key for the "enc-key" field. */
412 curve25519_public_to_base64(key_b64, &ip->enc_key, true);
413 if (tor_cert_encode_ed22519(ip->enc_key_cert, &encoded_cert) < 0) {
414 goto done;
416 tor_asprintf(&encoded,
417 "%s ntor %s\n"
418 "%s\n%s",
419 str_ip_enc_key, key_b64,
420 str_ip_enc_key_cert, encoded_cert);
421 tor_free(encoded_cert);
423 done:
424 return encoded;
427 /** Encode an introduction point onion key. Return a newly allocated string
428 * with it. Can not fail. */
429 static char *
430 encode_onion_key(const hs_desc_intro_point_t *ip)
432 char *encoded = NULL;
433 char key_b64[CURVE25519_BASE64_PADDED_LEN + 1];
435 tor_assert(ip);
437 /* Base64 encode the encryption key for the "onion-key" field. */
438 curve25519_public_to_base64(key_b64, &ip->onion_key, true);
439 tor_asprintf(&encoded, "%s ntor %s", str_ip_onion_key, key_b64);
441 return encoded;
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)
450 char *encoded_ip = NULL;
451 smartlist_t *lines = smartlist_new();
453 tor_assert(ip);
454 tor_assert(sig_key);
456 /* Encode link specifier. */
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);
463 /* Onion key encoding. */
465 char *encoded_onion_key = encode_onion_key(ip);
466 if (encoded_onion_key == NULL) {
467 goto err;
469 smartlist_add_asprintf(lines, "%s", encoded_onion_key);
470 tor_free(encoded_onion_key);
473 /* Authentication key encoding. */
475 char *encoded_cert;
476 if (tor_cert_encode_ed22519(ip->auth_key_cert, &encoded_cert) < 0) {
477 goto err;
479 smartlist_add_asprintf(lines, "%s\n%s", str_ip_auth_key, encoded_cert);
480 tor_free(encoded_cert);
483 /* Encryption key encoding. */
485 char *encoded_enc_key = encode_enc_key(ip);
486 if (encoded_enc_key == NULL) {
487 goto err;
489 smartlist_add_asprintf(lines, "%s", encoded_enc_key);
490 tor_free(encoded_enc_key);
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;
501 smartlist_add_asprintf(lines, "%s", encoded_legacy_key);
502 tor_free(encoded_legacy_key);
505 /* Join them all in one blob of text. */
506 encoded_ip = smartlist_join_strings(lines, "\n", 1, NULL);
508 err:
509 SMARTLIST_FOREACH(lines, char *, l, tor_free(l));
510 smartlist_free(lines);
511 return encoded_ip;
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)
519 size_t plaintext_padded_len;
520 const int padding_block_length = HS_DESC_SUPERENC_PLAINTEXT_PAD_MULTIPLE;
522 /* Make sure we won't overflow. */
523 tor_assert(plaintext_len <= (SIZE_T_CEILING - padding_block_length));
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;
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)
541 size_t padded_len;
542 uint8_t *padded;
544 tor_assert(plaintext);
545 tor_assert(padded_out);
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);
552 memcpy(padded, plaintext, plaintext_len);
553 *padded_out = padded;
554 return padded_len;
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)
565 size_t encrypted_len;
566 uint8_t *padded_plaintext, *encrypted;
567 crypto_cipher_t *cipher;
569 tor_assert(key);
570 tor_assert(iv);
571 tor_assert(plaintext);
572 tor_assert(encrypted_out);
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;
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;
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)
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];
620 tor_assert(desc);
621 tor_assert(secret_data);
622 tor_assert(plaintext);
623 tor_assert(encrypted_out);
625 /* Get our salt. The returned bytes are already hashed. */
626 crypto_strongest_rand(salt, sizeof(salt));
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);
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);
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));
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);
668 *encrypted_out = final_blob;
669 return final_blob_len;
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)
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];
686 #define ASSERT_AND_BASE64(field) STMT_BEGIN \
687 tor_assert(!fast_mem_is_zero((char *) client->field, \
688 sizeof(client->field))); \
689 ret = base64_encode_nopad(field##_b64, sizeof(field##_b64), \
690 client->field, sizeof(client->field)); \
691 tor_assert(ret > 0); \
692 STMT_END
694 ASSERT_AND_BASE64(client_id);
695 ASSERT_AND_BASE64(iv);
696 ASSERT_AND_BASE64(encrypted_cookie);
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);
702 #undef ASSERT_AND_BASE64
704 return auth_client_str;
707 /** Create the "client-auth" part of the descriptor and return a
708 * newly-allocated string with it. It's the responsibility of the caller to
709 * free the returned string. */
710 static char *
711 get_all_auth_client_lines(const hs_descriptor_t *desc)
713 smartlist_t *auth_client_lines = smartlist_new();
714 char *auth_client_lines_str = NULL;
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);
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;
727 auth_client_str = get_auth_client_str(client);
729 smartlist_add(auth_client_lines, auth_client_str);
730 } SMARTLIST_FOREACH_END(client);
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);
739 return auth_client_lines_str;
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)
749 char *encoded_str = NULL;
750 smartlist_t *lines = smartlist_new();
752 /* Build the start of the section prior to the introduction points. */
754 if (!desc->encrypted_data.create2_ntor) {
755 log_err(LD_BUG, "HS desc doesn't have recognized handshake type.");
756 goto err;
758 smartlist_add_asprintf(lines, "%s %d\n", str_create2_formats,
759 ONION_HANDSHAKE_TYPE_NTOR);
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);
770 if (desc->encrypted_data.single_onion_service) {
771 smartlist_add_asprintf(lines, "%s\n", str_single_onion);
774 if (congestion_control_enabled()) {
775 /* Add flow control line into the descriptor. */
776 smartlist_add_asprintf(lines, "%s %s %u\n", str_flow_control,
777 protover_get_supported(PRT_FLOWCTRL),
778 congestion_control_sendme_inc());
782 /* Build the introduction point(s) section. */
783 SMARTLIST_FOREACH_BEGIN(desc->encrypted_data.intro_points,
784 const hs_desc_intro_point_t *, ip) {
785 char *encoded_ip = encode_intro_point(&desc->plaintext_data.signing_pubkey,
786 ip);
787 if (encoded_ip == NULL) {
788 log_err(LD_BUG, "HS desc intro point is malformed.");
789 goto err;
791 smartlist_add(lines, encoded_ip);
792 } SMARTLIST_FOREACH_END(ip);
794 /* Build the entire encrypted data section into one encoded plaintext and
795 * then encrypt it. */
796 encoded_str = smartlist_join_strings(lines, "", 0, NULL);
798 err:
799 SMARTLIST_FOREACH(lines, char *, l, tor_free(l));
800 smartlist_free(lines);
802 return encoded_str;
805 /** Create the middle layer of the descriptor, which includes the client auth
806 * data and the encrypted inner layer (provided as a base64 string at
807 * <b>layer2_b64_ciphertext</b>). Return a newly-allocated string with the
808 * layer plaintext. It's the responsibility of the caller to free the returned
809 * string. Can not fail. */
810 static char *
811 get_outer_encrypted_layer_plaintext(const hs_descriptor_t *desc,
812 const char *layer2_b64_ciphertext)
814 char *layer1_str = NULL;
815 smartlist_t *lines = smartlist_new();
817 /* Specify auth type */
818 smartlist_add_asprintf(lines, "%s %s\n", str_desc_auth_type, "x25519");
820 { /* Print ephemeral x25519 key */
821 char ephemeral_key_base64[CURVE25519_BASE64_PADDED_LEN + 1];
822 const curve25519_public_key_t *ephemeral_pubkey;
824 ephemeral_pubkey = &desc->superencrypted_data.auth_ephemeral_pubkey;
825 tor_assert(!fast_mem_is_zero((char *) ephemeral_pubkey->public_key,
826 CURVE25519_PUBKEY_LEN));
828 curve25519_public_to_base64(ephemeral_key_base64, ephemeral_pubkey, true);
829 smartlist_add_asprintf(lines, "%s %s\n",
830 str_desc_auth_key, ephemeral_key_base64);
832 memwipe(ephemeral_key_base64, 0, sizeof(ephemeral_key_base64));
835 { /* Create auth-client lines. */
836 char *auth_client_lines = get_all_auth_client_lines(desc);
837 tor_assert(auth_client_lines);
838 smartlist_add(lines, auth_client_lines);
841 /* create encrypted section */
843 smartlist_add_asprintf(lines,
844 "%s\n"
845 "-----BEGIN MESSAGE-----\n"
846 "%s"
847 "-----END MESSAGE-----",
848 str_encrypted, layer2_b64_ciphertext);
851 layer1_str = smartlist_join_strings(lines, "", 0, NULL);
853 /* We need to memwipe all lines because it contains the ephemeral key */
854 SMARTLIST_FOREACH(lines, char *, a, memwipe(a, 0, strlen(a)));
855 SMARTLIST_FOREACH(lines, char *, a, tor_free(a));
856 smartlist_free(lines);
858 return layer1_str;
861 /** Encrypt <b>encoded_str</b> into an encrypted blob and then base64 it before
862 * returning it. <b>desc</b> is provided to derive the encryption
863 * keys. <b>secret_data</b> is also proved to derive the encryption keys.
864 * <b>is_superencrypted_layer</b> is set if <b>encoded_str</b> is the
865 * middle (superencrypted) layer of the descriptor. It's the responsibility of
866 * the caller to free the returned string. */
867 static char *
868 encrypt_desc_data_and_base64(const hs_descriptor_t *desc,
869 const uint8_t *secret_data,
870 size_t secret_data_len,
871 const char *encoded_str,
872 int is_superencrypted_layer)
874 char *enc_b64;
875 ssize_t enc_b64_len, ret_len, enc_len;
876 char *encrypted_blob = NULL;
878 enc_len = encrypt_descriptor_data(desc, secret_data, secret_data_len,
879 encoded_str, &encrypted_blob,
880 is_superencrypted_layer);
881 /* Get the encoded size plus a NUL terminating byte. */
882 enc_b64_len = base64_encode_size(enc_len, BASE64_ENCODE_MULTILINE) + 1;
883 enc_b64 = tor_malloc_zero(enc_b64_len);
884 /* Base64 the encrypted blob before returning it. */
885 ret_len = base64_encode(enc_b64, enc_b64_len, encrypted_blob, enc_len,
886 BASE64_ENCODE_MULTILINE);
887 /* Return length doesn't count the NUL byte. */
888 tor_assert(ret_len == (enc_b64_len - 1));
889 tor_free(encrypted_blob);
891 return enc_b64;
894 /** Generate the secret data which is used to encrypt/decrypt the descriptor.
896 * SECRET_DATA = blinded-public-key
897 * SECRET_DATA = blinded-public-key | descriptor_cookie
899 * The descriptor_cookie is optional but if it exists, it must be at least
900 * HS_DESC_DESCRIPTOR_COOKIE_LEN bytes long.
902 * A newly allocated secret data is put in secret_data_out. Return the
903 * length of the secret data. This function cannot fail. */
904 static size_t
905 build_secret_data(const ed25519_public_key_t *blinded_pubkey,
906 const uint8_t *descriptor_cookie,
907 uint8_t **secret_data_out)
909 size_t secret_data_len;
910 uint8_t *secret_data;
912 tor_assert(blinded_pubkey);
913 tor_assert(secret_data_out);
915 if (descriptor_cookie) {
916 /* If the descriptor cookie is present, we need both the blinded
917 * pubkey and the descriptor cookie as a secret data. */
918 secret_data_len = ED25519_PUBKEY_LEN + HS_DESC_DESCRIPTOR_COOKIE_LEN;
919 secret_data = tor_malloc(secret_data_len);
921 memcpy(secret_data,
922 blinded_pubkey->pubkey,
923 ED25519_PUBKEY_LEN);
924 memcpy(secret_data + ED25519_PUBKEY_LEN,
925 descriptor_cookie,
926 HS_DESC_DESCRIPTOR_COOKIE_LEN);
927 } else {
928 /* If the descriptor cookie is not present, we need only the blinded
929 * pubkey as a secret data. */
930 secret_data_len = ED25519_PUBKEY_LEN;
931 secret_data = tor_malloc(secret_data_len);
932 memcpy(secret_data,
933 blinded_pubkey->pubkey,
934 ED25519_PUBKEY_LEN);
937 *secret_data_out = secret_data;
938 return secret_data_len;
941 /** Generate and encode the superencrypted portion of <b>desc</b>. This also
942 * involves generating the encrypted portion of the descriptor, and performing
943 * the superencryption. A newly allocated NUL-terminated string pointer
944 * containing the encrypted encoded blob is put in encrypted_blob_out. Return 0
945 * on success else a negative value. */
946 static int
947 encode_superencrypted_data(const hs_descriptor_t *desc,
948 const uint8_t *descriptor_cookie,
949 char **encrypted_blob_out)
951 int ret = -1;
952 uint8_t *secret_data = NULL;
953 size_t secret_data_len = 0;
954 char *layer2_str = NULL;
955 char *layer2_b64_ciphertext = NULL;
956 char *layer1_str = NULL;
957 char *layer1_b64_ciphertext = NULL;
959 tor_assert(desc);
960 tor_assert(encrypted_blob_out);
962 /* Func logic: We first create the inner layer of the descriptor (layer2).
963 * We then encrypt it and use it to create the middle layer of the descriptor
964 * (layer1). Finally we superencrypt the middle layer and return it to our
965 * caller. */
967 /* Create inner descriptor layer */
968 layer2_str = get_inner_encrypted_layer_plaintext(desc);
969 if (!layer2_str) {
970 goto err;
973 secret_data_len = build_secret_data(&desc->plaintext_data.blinded_pubkey,
974 descriptor_cookie,
975 &secret_data);
977 /* Encrypt and b64 the inner layer */
978 layer2_b64_ciphertext =
979 encrypt_desc_data_and_base64(desc, secret_data, secret_data_len,
980 layer2_str, 0);
981 if (!layer2_b64_ciphertext) {
982 goto err;
985 /* Now create middle descriptor layer given the inner layer */
986 layer1_str = get_outer_encrypted_layer_plaintext(desc,layer2_b64_ciphertext);
987 if (!layer1_str) {
988 goto err;
991 /* Encrypt and base64 the middle layer */
992 layer1_b64_ciphertext =
993 encrypt_desc_data_and_base64(desc,
994 desc->plaintext_data.blinded_pubkey.pubkey,
995 ED25519_PUBKEY_LEN,
996 layer1_str, 1);
997 if (!layer1_b64_ciphertext) {
998 goto err;
1001 /* Success! */
1002 ret = 0;
1004 err:
1005 memwipe(secret_data, 0, secret_data_len);
1006 tor_free(secret_data);
1007 tor_free(layer1_str);
1008 tor_free(layer2_str);
1009 tor_free(layer2_b64_ciphertext);
1011 *encrypted_blob_out = layer1_b64_ciphertext;
1012 return ret;
1015 /** Encode a v3 HS descriptor. Return 0 on success and set encoded_out to the
1016 * newly allocated string of the encoded descriptor. On error, -1 is returned
1017 * and encoded_out is untouched. */
1018 static int
1019 desc_encode_v3(const hs_descriptor_t *desc,
1020 const ed25519_keypair_t *signing_kp,
1021 const uint8_t *descriptor_cookie,
1022 char **encoded_out)
1024 int ret = -1;
1025 char *encoded_str = NULL;
1026 size_t encoded_len;
1027 smartlist_t *lines = smartlist_new();
1029 tor_assert(desc);
1030 tor_assert(signing_kp);
1031 tor_assert(encoded_out);
1032 tor_assert(desc->plaintext_data.version == 3);
1034 /* Build the non-encrypted values. */
1036 char *encoded_cert;
1037 /* Encode certificate then create the first line of the descriptor. */
1038 if (desc->plaintext_data.signing_key_cert->cert_type
1039 != CERT_TYPE_SIGNING_HS_DESC) {
1040 log_err(LD_BUG, "HS descriptor signing key has an unexpected cert type "
1041 "(%d)", (int) desc->plaintext_data.signing_key_cert->cert_type);
1042 goto err;
1044 if (tor_cert_encode_ed22519(desc->plaintext_data.signing_key_cert,
1045 &encoded_cert) < 0) {
1046 /* The function will print error logs. */
1047 goto err;
1049 /* Create the hs descriptor line. */
1050 smartlist_add_asprintf(lines, "%s %" PRIu32, str_hs_desc,
1051 desc->plaintext_data.version);
1052 /* Add the descriptor lifetime line (in minutes). */
1053 smartlist_add_asprintf(lines, "%s %" PRIu32, str_lifetime,
1054 desc->plaintext_data.lifetime_sec / 60);
1055 /* Create the descriptor certificate line. */
1056 smartlist_add_asprintf(lines, "%s\n%s", str_desc_cert, encoded_cert);
1057 tor_free(encoded_cert);
1058 /* Create the revision counter line. */
1059 smartlist_add_asprintf(lines, "%s %" PRIu64, str_rev_counter,
1060 desc->plaintext_data.revision_counter);
1063 /* Build the superencrypted data section. */
1065 char *enc_b64_blob=NULL;
1066 if (encode_superencrypted_data(desc, descriptor_cookie,
1067 &enc_b64_blob) < 0) {
1068 goto err;
1070 smartlist_add_asprintf(lines,
1071 "%s\n"
1072 "-----BEGIN MESSAGE-----\n"
1073 "%s"
1074 "-----END MESSAGE-----",
1075 str_superencrypted, enc_b64_blob);
1076 tor_free(enc_b64_blob);
1079 /* Join all lines in one string so we can generate a signature and append
1080 * it to the descriptor. */
1081 encoded_str = smartlist_join_strings(lines, "\n", 1, &encoded_len);
1083 /* Sign all fields of the descriptor with our short term signing key. */
1085 ed25519_signature_t sig;
1086 char ed_sig_b64[ED25519_SIG_BASE64_LEN + 1];
1087 if (ed25519_sign_prefixed(&sig,
1088 (const uint8_t *) encoded_str, encoded_len,
1089 str_desc_sig_prefix, signing_kp) < 0) {
1090 log_warn(LD_BUG, "Can't sign encoded HS descriptor!");
1091 tor_free(encoded_str);
1092 goto err;
1094 ed25519_signature_to_base64(ed_sig_b64, &sig);
1095 /* Create the signature line. */
1096 smartlist_add_asprintf(lines, "%s %s", str_signature, ed_sig_b64);
1098 /* Free previous string that we used so compute the signature. */
1099 tor_free(encoded_str);
1100 encoded_str = smartlist_join_strings(lines, "\n", 1, NULL);
1101 *encoded_out = encoded_str;
1103 if (strlen(encoded_str) >= hs_cache_get_max_descriptor_size()) {
1104 log_warn(LD_GENERAL, "We just made an HS descriptor that's too big (%d)."
1105 "Failing.", (int)strlen(encoded_str));
1106 tor_free(encoded_str);
1107 goto err;
1110 /* XXX: Trigger a control port event. */
1112 /* Success! */
1113 ret = 0;
1115 err:
1116 SMARTLIST_FOREACH(lines, char *, l, tor_free(l));
1117 smartlist_free(lines);
1118 return ret;
1121 /* === DECODING === */
1123 /** Given the token tok for an auth client, decode it as
1124 * hs_desc_authorized_client_t. tok->args MUST contain at least 3 elements
1125 * Return 0 on success else -1 on failure. */
1126 static int
1127 decode_auth_client(const directory_token_t *tok,
1128 hs_desc_authorized_client_t *client)
1130 int ret = -1;
1132 tor_assert(tok);
1133 tor_assert(tok->n_args >= 3);
1134 tor_assert(client);
1136 if (base64_decode((char *) client->client_id, sizeof(client->client_id),
1137 tok->args[0], strlen(tok->args[0])) !=
1138 sizeof(client->client_id)) {
1139 goto done;
1141 if (base64_decode((char *) client->iv, sizeof(client->iv),
1142 tok->args[1], strlen(tok->args[1])) !=
1143 sizeof(client->iv)) {
1144 goto done;
1146 if (base64_decode((char *) client->encrypted_cookie,
1147 sizeof(client->encrypted_cookie),
1148 tok->args[2], strlen(tok->args[2])) !=
1149 sizeof(client->encrypted_cookie)) {
1150 goto done;
1153 /* Success. */
1154 ret = 0;
1155 done:
1156 return ret;
1159 /** Given an encoded string of the link specifiers, return a newly allocated
1160 * list of decoded link specifiers. Return NULL on error. */
1161 STATIC smartlist_t *
1162 decode_link_specifiers(const char *encoded)
1164 int decoded_len;
1165 size_t encoded_len, i;
1166 uint8_t *decoded;
1167 smartlist_t *results = NULL;
1168 link_specifier_list_t *specs = NULL;
1170 tor_assert(encoded);
1172 encoded_len = strlen(encoded);
1173 decoded = tor_malloc(encoded_len);
1174 decoded_len = base64_decode((char *) decoded, encoded_len, encoded,
1175 encoded_len);
1176 if (decoded_len < 0) {
1177 goto err;
1180 if (link_specifier_list_parse(&specs, decoded,
1181 (size_t) decoded_len) < decoded_len) {
1182 goto err;
1184 tor_assert(specs);
1185 results = smartlist_new();
1187 for (i = 0; i < link_specifier_list_getlen_spec(specs); i++) {
1188 link_specifier_t *ls = link_specifier_list_get_spec(specs, i);
1189 if (BUG(!ls)) {
1190 goto err;
1192 link_specifier_t *ls_dup = link_specifier_dup(ls);
1193 if (BUG(!ls_dup)) {
1194 goto err;
1196 smartlist_add(results, ls_dup);
1199 goto done;
1200 err:
1201 if (results) {
1202 SMARTLIST_FOREACH(results, link_specifier_t *, s,
1203 link_specifier_free(s));
1204 smartlist_free(results);
1205 results = NULL;
1207 done:
1208 link_specifier_list_free(specs);
1209 tor_free(decoded);
1210 return results;
1213 /** Given a list of authentication types, decode it and put it in the encrypted
1214 * data section. Return 1 if we at least know one of the type or 0 if we know
1215 * none of them. */
1216 static int
1217 decode_auth_type(hs_desc_encrypted_data_t *desc, const char *list)
1219 int match = 0;
1221 tor_assert(desc);
1222 tor_assert(list);
1224 desc->intro_auth_types = smartlist_new();
1225 smartlist_split_string(desc->intro_auth_types, list, " ", 0, 0);
1227 /* Validate the types that we at least know about one. */
1228 SMARTLIST_FOREACH_BEGIN(desc->intro_auth_types, const char *, auth) {
1229 for (int idx = 0; intro_auth_types[idx].identifier; idx++) {
1230 if (!strncmp(auth, intro_auth_types[idx].identifier,
1231 strlen(intro_auth_types[idx].identifier))) {
1232 match = 1;
1233 break;
1236 } SMARTLIST_FOREACH_END(auth);
1238 return match;
1241 /** Parse a space-delimited list of integers representing CREATE2 formats into
1242 * the bitfield in hs_desc_encrypted_data_t. Ignore unrecognized values. */
1243 static void
1244 decode_create2_list(hs_desc_encrypted_data_t *desc, const char *list)
1246 smartlist_t *tokens;
1248 tor_assert(desc);
1249 tor_assert(list);
1251 tokens = smartlist_new();
1252 smartlist_split_string(tokens, list, " ", 0, 0);
1254 SMARTLIST_FOREACH_BEGIN(tokens, char *, s) {
1255 int ok;
1256 unsigned long type = tor_parse_ulong(s, 10, 1, UINT16_MAX, &ok, NULL);
1257 if (!ok) {
1258 log_warn(LD_REND, "Unparseable value %s in create2 list", escaped(s));
1259 continue;
1261 switch (type) {
1262 case ONION_HANDSHAKE_TYPE_NTOR:
1263 desc->create2_ntor = 1;
1264 break;
1265 default:
1266 /* We deliberately ignore unsupported handshake types */
1267 continue;
1269 } SMARTLIST_FOREACH_END(s);
1271 SMARTLIST_FOREACH(tokens, char *, s, tor_free(s));
1272 smartlist_free(tokens);
1275 /** Given a certificate, validate the certificate for certain conditions which
1276 * are if the given type matches the cert's one, if the signing key is
1277 * included and if the that key was actually used to sign the certificate.
1279 * Return 1 iff if all conditions pass or 0 if one of them fails. */
1280 STATIC int
1281 cert_is_valid(tor_cert_t *cert, uint8_t type, const char *log_obj_type)
1283 tor_assert(log_obj_type);
1285 if (cert == NULL) {
1286 log_warn(LD_REND, "Certificate for %s couldn't be parsed.", log_obj_type);
1287 goto err;
1289 if (cert->cert_type != type) {
1290 log_warn(LD_REND, "Invalid cert type %02x for %s.", cert->cert_type,
1291 log_obj_type);
1292 goto err;
1294 /* All certificate must have its signing key included. */
1295 if (!cert->signing_key_included) {
1296 log_warn(LD_REND, "Signing key is NOT included for %s.", log_obj_type);
1297 goto err;
1300 /* The following will not only check if the signature matches but also the
1301 * expiration date and overall validity. */
1302 if (tor_cert_checksig(cert, &cert->signing_key, approx_time()) < 0) {
1303 if (cert->cert_expired) {
1304 char expiration_str[ISO_TIME_LEN+1];
1305 format_iso_time(expiration_str, cert->valid_until);
1306 log_fn(LOG_PROTOCOL_WARN, LD_REND, "Invalid signature for %s: %s (%s)",
1307 log_obj_type, tor_cert_describe_signature_status(cert),
1308 expiration_str);
1309 } else {
1310 log_warn(LD_REND, "Invalid signature for %s: %s",
1311 log_obj_type, tor_cert_describe_signature_status(cert));
1313 goto err;
1316 return 1;
1317 err:
1318 return 0;
1321 /** Given some binary data, try to parse it to get a certificate object. If we
1322 * have a valid cert, validate it using the given wanted type. On error, print
1323 * a log using the err_msg has the certificate identifier adding semantic to
1324 * the log and cert_out is set to NULL. On success, 0 is returned and cert_out
1325 * points to a newly allocated certificate object. */
1326 static int
1327 cert_parse_and_validate(tor_cert_t **cert_out, const char *data,
1328 size_t data_len, unsigned int cert_type_wanted,
1329 const char *err_msg)
1331 tor_cert_t *cert;
1333 tor_assert(cert_out);
1334 tor_assert(data);
1335 tor_assert(err_msg);
1337 /* Parse certificate. */
1338 cert = tor_cert_parse((const uint8_t *) data, data_len);
1339 if (!cert) {
1340 log_warn(LD_REND, "Certificate for %s couldn't be parsed.", err_msg);
1341 goto err;
1344 /* Validate certificate. */
1345 if (!cert_is_valid(cert, cert_type_wanted, err_msg)) {
1346 goto err;
1349 *cert_out = cert;
1350 return 0;
1352 err:
1353 tor_cert_free(cert);
1354 *cert_out = NULL;
1355 return -1;
1358 /** Return true iff the given length of the encrypted data of a descriptor
1359 * passes validation. */
1360 STATIC int
1361 encrypted_data_length_is_valid(size_t len)
1363 /* Make sure there is enough data for the salt and the mac. The equality is
1364 there to ensure that there is at least one byte of encrypted data. */
1365 if (len <= HS_DESC_ENCRYPTED_SALT_LEN + DIGEST256_LEN) {
1366 log_warn(LD_REND, "Length of descriptor's encrypted data is too small. "
1367 "Got %lu but minimum value is %d",
1368 (unsigned long)len, HS_DESC_ENCRYPTED_SALT_LEN + DIGEST256_LEN);
1369 goto err;
1372 return 1;
1373 err:
1374 return 0;
1377 /** Build the KEYS component for the authorized client computation. The format
1378 * of the construction is:
1380 * SECRET_SEED = x25519(sk, pk)
1381 * KEYS = KDF(subcredential | SECRET_SEED, 40)
1383 * Set the <b>keys_out</b> argument to point to the buffer containing the KEYS,
1384 * and return the buffer's length. The caller should wipe and free its content
1385 * once done with it. This function can't fail. */
1386 static size_t
1387 build_descriptor_cookie_keys(const hs_subcredential_t *subcredential,
1388 const curve25519_secret_key_t *sk,
1389 const curve25519_public_key_t *pk,
1390 uint8_t **keys_out)
1392 uint8_t secret_seed[CURVE25519_OUTPUT_LEN];
1393 uint8_t *keystream;
1394 size_t keystream_len = HS_DESC_CLIENT_ID_LEN + HS_DESC_COOKIE_KEY_LEN;
1395 crypto_xof_t *xof;
1397 tor_assert(subcredential);
1398 tor_assert(sk);
1399 tor_assert(pk);
1400 tor_assert(keys_out);
1402 keystream = tor_malloc_zero(keystream_len);
1404 /* Calculate x25519(sk, pk) to get the secret seed. */
1405 curve25519_handshake(secret_seed, sk, pk);
1407 /* Calculate KEYS = KDF(subcredential | SECRET_SEED, 40) */
1408 xof = crypto_xof_new();
1409 crypto_xof_add_bytes(xof, subcredential->subcred, SUBCRED_LEN);
1410 crypto_xof_add_bytes(xof, secret_seed, sizeof(secret_seed));
1411 crypto_xof_squeeze_bytes(xof, keystream, keystream_len);
1412 crypto_xof_free(xof);
1414 memwipe(secret_seed, 0, sizeof(secret_seed));
1416 *keys_out = keystream;
1417 return keystream_len;
1420 /** Decrypt the descriptor cookie given the descriptor, the auth client,
1421 * and the client secret key. On success, return 0 and a newly allocated
1422 * descriptor cookie descriptor_cookie_out. On error or if the client id
1423 * is invalid, return -1 and descriptor_cookie_out is set to
1424 * NULL. */
1425 static int
1426 decrypt_descriptor_cookie(const hs_descriptor_t *desc,
1427 const hs_desc_authorized_client_t *client,
1428 const curve25519_secret_key_t *client_auth_sk,
1429 uint8_t **descriptor_cookie_out)
1431 int ret = -1;
1432 uint8_t *keystream = NULL;
1433 size_t keystream_length = 0;
1434 uint8_t *descriptor_cookie = NULL;
1435 const uint8_t *cookie_key = NULL;
1436 crypto_cipher_t *cipher = NULL;
1438 tor_assert(desc);
1439 tor_assert(client);
1440 tor_assert(client_auth_sk);
1441 tor_assert(!fast_mem_is_zero(
1442 (char *) &desc->superencrypted_data.auth_ephemeral_pubkey,
1443 sizeof(desc->superencrypted_data.auth_ephemeral_pubkey)));
1444 tor_assert(!fast_mem_is_zero((char *) desc->subcredential.subcred,
1445 DIGEST256_LEN));
1447 /* Catch potential code-flow cases of an uninitialized private key sneaking
1448 * into this function. */
1449 if (BUG(fast_mem_is_zero((char *)client_auth_sk, sizeof(*client_auth_sk)))) {
1450 goto done;
1453 /* Get the KEYS component to derive the CLIENT-ID and COOKIE-KEY. */
1454 keystream_length =
1455 build_descriptor_cookie_keys(&desc->subcredential,
1456 client_auth_sk,
1457 &desc->superencrypted_data.auth_ephemeral_pubkey,
1458 &keystream);
1459 tor_assert(keystream_length > 0);
1461 /* If the client id of auth client is not the same as the calculcated
1462 * client id, it means that this auth client is invalid according to the
1463 * client secret key client_auth_sk. */
1464 if (tor_memneq(client->client_id, keystream, HS_DESC_CLIENT_ID_LEN)) {
1465 goto done;
1467 cookie_key = keystream + HS_DESC_CLIENT_ID_LEN;
1469 /* This creates a cipher for AES. It can't fail. */
1470 cipher = crypto_cipher_new_with_iv_and_bits(cookie_key, client->iv,
1471 HS_DESC_COOKIE_KEY_BIT_SIZE);
1472 descriptor_cookie = tor_malloc_zero(HS_DESC_DESCRIPTOR_COOKIE_LEN);
1473 /* This can't fail. */
1474 crypto_cipher_decrypt(cipher, (char *) descriptor_cookie,
1475 (const char *) client->encrypted_cookie,
1476 sizeof(client->encrypted_cookie));
1478 /* Success. */
1479 ret = 0;
1480 done:
1481 *descriptor_cookie_out = descriptor_cookie;
1482 if (cipher) {
1483 crypto_cipher_free(cipher);
1485 memwipe(keystream, 0, keystream_length);
1486 tor_free(keystream);
1487 return ret;
1490 /** Decrypt an encrypted descriptor layer at <b>encrypted_blob</b> of size
1491 * <b>encrypted_blob_size</b>. The descriptor cookie is optional. Use
1492 * the descriptor object <b>desc</b> and <b>descriptor_cookie</b>
1493 * to generate the right decryption keys; set <b>decrypted_out</b> to
1494 * the plaintext. If <b>is_superencrypted_layer</b> is set, this is
1495 * the outer encrypted layer of the descriptor.
1497 * On any error case, including an empty output, return 0 and set
1498 * *<b>decrypted_out</b> to NULL.
1500 MOCK_IMPL(STATIC size_t,
1501 decrypt_desc_layer,(const hs_descriptor_t *desc,
1502 const uint8_t *descriptor_cookie,
1503 bool is_superencrypted_layer,
1504 char **decrypted_out))
1506 uint8_t *decrypted = NULL;
1507 uint8_t secret_key[HS_DESC_ENCRYPTED_KEY_LEN], secret_iv[CIPHER_IV_LEN];
1508 uint8_t *secret_data = NULL;
1509 size_t secret_data_len = 0;
1510 uint8_t mac_key[DIGEST256_LEN], our_mac[DIGEST256_LEN];
1511 const uint8_t *salt, *encrypted, *desc_mac;
1512 size_t encrypted_len, result_len = 0;
1513 const uint8_t *encrypted_blob = (is_superencrypted_layer)
1514 ? desc->plaintext_data.superencrypted_blob
1515 : desc->superencrypted_data.encrypted_blob;
1516 size_t encrypted_blob_size = (is_superencrypted_layer)
1517 ? desc->plaintext_data.superencrypted_blob_size
1518 : desc->superencrypted_data.encrypted_blob_size;
1520 tor_assert(decrypted_out);
1521 tor_assert(desc);
1522 tor_assert(encrypted_blob);
1524 /* Construction is as follow: SALT | ENCRYPTED_DATA | MAC .
1525 * Make sure we have enough space for all these things. */
1526 if (!encrypted_data_length_is_valid(encrypted_blob_size)) {
1527 goto err;
1530 /* Start of the blob thus the salt. */
1531 salt = encrypted_blob;
1533 /* Next is the encrypted data. */
1534 encrypted = encrypted_blob + HS_DESC_ENCRYPTED_SALT_LEN;
1535 encrypted_len = encrypted_blob_size -
1536 (HS_DESC_ENCRYPTED_SALT_LEN + DIGEST256_LEN);
1537 tor_assert(encrypted_len > 0); /* guaranteed by the check above */
1539 /* And last comes the MAC. */
1540 desc_mac = encrypted_blob + encrypted_blob_size - DIGEST256_LEN;
1542 /* Build secret data to be used in the decryption. */
1543 secret_data_len = build_secret_data(&desc->plaintext_data.blinded_pubkey,
1544 descriptor_cookie,
1545 &secret_data);
1547 /* KDF construction resulting in a key from which the secret key, IV and MAC
1548 * key are extracted which is what we need for the decryption. */
1549 build_secret_key_iv_mac(desc, secret_data, secret_data_len,
1550 salt, HS_DESC_ENCRYPTED_SALT_LEN,
1551 secret_key, sizeof(secret_key),
1552 secret_iv, sizeof(secret_iv),
1553 mac_key, sizeof(mac_key),
1554 is_superencrypted_layer);
1556 /* Build MAC. */
1557 build_mac(mac_key, sizeof(mac_key), salt, HS_DESC_ENCRYPTED_SALT_LEN,
1558 encrypted, encrypted_len, our_mac, sizeof(our_mac));
1559 memwipe(mac_key, 0, sizeof(mac_key));
1560 /* Verify MAC; MAC is H(mac_key || salt || encrypted)
1562 * This is a critical check that is making sure the computed MAC matches the
1563 * one in the descriptor. */
1564 if (!tor_memeq(our_mac, desc_mac, sizeof(our_mac))) {
1565 log_info(LD_REND, "Encrypted service descriptor MAC check failed");
1566 goto err;
1570 /* Decrypt. Here we are assured that the encrypted length is valid for
1571 * decryption. */
1572 crypto_cipher_t *cipher;
1574 cipher = crypto_cipher_new_with_iv_and_bits(secret_key, secret_iv,
1575 HS_DESC_ENCRYPTED_BIT_SIZE);
1576 /* Extra byte for the NUL terminated byte. */
1577 decrypted = tor_malloc_zero(encrypted_len + 1);
1578 crypto_cipher_decrypt(cipher, (char *) decrypted,
1579 (const char *) encrypted, encrypted_len);
1580 crypto_cipher_free(cipher);
1584 /* Adjust length to remove NUL padding bytes */
1585 uint8_t *end = memchr(decrypted, 0, encrypted_len);
1586 result_len = encrypted_len;
1587 if (end) {
1588 result_len = end - decrypted;
1592 if (result_len == 0) {
1593 /* Treat this as an error, so that somebody will free the output. */
1594 goto err;
1597 /* Make sure to NUL terminate the string. */
1598 decrypted[encrypted_len] = '\0';
1599 *decrypted_out = (char *) decrypted;
1600 goto done;
1602 err:
1603 if (decrypted) {
1604 tor_free(decrypted);
1606 *decrypted_out = NULL;
1607 result_len = 0;
1609 done:
1610 memwipe(secret_data, 0, secret_data_len);
1611 memwipe(secret_key, 0, sizeof(secret_key));
1612 memwipe(secret_iv, 0, sizeof(secret_iv));
1613 tor_free(secret_data);
1614 return result_len;
1617 /** Decrypt the superencrypted section of the descriptor using the given
1618 * descriptor object <b>desc</b>. A newly allocated NUL terminated string is
1619 * put in decrypted_out which contains the superencrypted layer of the
1620 * descriptor. Return the length of decrypted_out on success else 0 is
1621 * returned and decrypted_out is set to NULL. */
1622 MOCK_IMPL(STATIC size_t,
1623 desc_decrypt_superencrypted,(const hs_descriptor_t *desc,char **decrypted_out))
1625 size_t superencrypted_len = 0;
1626 char *superencrypted_plaintext = NULL;
1628 tor_assert(desc);
1629 tor_assert(decrypted_out);
1631 superencrypted_len = decrypt_desc_layer(desc,
1632 NULL,
1633 true, &superencrypted_plaintext);
1635 if (!superencrypted_len) {
1636 log_warn(LD_REND, "Decrypting superencrypted desc failed.");
1637 goto done;
1639 tor_assert(superencrypted_plaintext);
1641 done:
1642 /* In case of error, superencrypted_plaintext is already NULL, so the
1643 * following line makes sense. */
1644 *decrypted_out = superencrypted_plaintext;
1645 /* This makes sense too, because, in case of error, this is zero. */
1646 return superencrypted_len;
1649 /** Decrypt the encrypted section of the descriptor using the given descriptor
1650 * object <b>desc</b>. A newly allocated NUL terminated string is put in
1651 * decrypted_out which contains the encrypted layer of the descriptor.
1652 * Return the length of decrypted_out on success else 0 is returned and
1653 * decrypted_out is set to NULL. */
1654 MOCK_IMPL(STATIC size_t,
1655 desc_decrypt_encrypted,(const hs_descriptor_t *desc,
1656 const curve25519_secret_key_t *client_auth_sk,
1657 char **decrypted_out))
1659 size_t encrypted_len = 0;
1660 char *encrypted_plaintext = NULL;
1661 uint8_t *descriptor_cookie = NULL;
1663 tor_assert(desc);
1664 tor_assert(desc->superencrypted_data.clients);
1665 tor_assert(decrypted_out);
1667 /* If the client secret key is provided, try to find a valid descriptor
1668 * cookie. Otherwise, leave it NULL. */
1669 if (client_auth_sk) {
1670 SMARTLIST_FOREACH_BEGIN(desc->superencrypted_data.clients,
1671 hs_desc_authorized_client_t *, client) {
1672 /* If we can decrypt the descriptor cookie successfully, we will use that
1673 * descriptor cookie and break from the loop. */
1674 if (!decrypt_descriptor_cookie(desc, client, client_auth_sk,
1675 &descriptor_cookie)) {
1676 break;
1678 } SMARTLIST_FOREACH_END(client);
1681 encrypted_len = decrypt_desc_layer(desc,
1682 descriptor_cookie,
1683 false, &encrypted_plaintext);
1685 if (!encrypted_len) {
1686 goto err;
1688 tor_assert(encrypted_plaintext);
1690 err:
1691 /* In case of error, encrypted_plaintext is already NULL, so the
1692 * following line makes sense. */
1693 *decrypted_out = encrypted_plaintext;
1694 if (descriptor_cookie) {
1695 memwipe(descriptor_cookie, 0, HS_DESC_DESCRIPTOR_COOKIE_LEN);
1697 tor_free(descriptor_cookie);
1698 /* This makes sense too, because, in case of error, this is zero. */
1699 return encrypted_len;
1702 /** Given the token tok for an intro point legacy key, the list of tokens, the
1703 * introduction point ip being decoded and the descriptor desc from which it
1704 * comes from, decode the legacy key and set the intro point object. Return 0
1705 * on success else -1 on failure. */
1706 static int
1707 decode_intro_legacy_key(const directory_token_t *tok,
1708 smartlist_t *tokens,
1709 hs_desc_intro_point_t *ip,
1710 const hs_descriptor_t *desc)
1712 tor_assert(tok);
1713 tor_assert(tokens);
1714 tor_assert(ip);
1715 tor_assert(desc);
1717 if (!crypto_pk_public_exponent_ok(tok->key)) {
1718 log_warn(LD_REND, "Introduction point legacy key is invalid");
1719 goto err;
1721 ip->legacy.key = crypto_pk_dup_key(tok->key);
1722 /* Extract the legacy cross certification cert which MUST be present if we
1723 * have a legacy key. */
1724 tok = find_opt_by_keyword(tokens, R3_INTRO_LEGACY_KEY_CERT);
1725 if (!tok) {
1726 log_warn(LD_REND, "Introduction point legacy key cert is missing");
1727 goto err;
1729 tor_assert(tok->object_body);
1730 if (strcmp(tok->object_type, "CROSSCERT")) {
1731 /* Info level because this might be an unknown field that we should
1732 * ignore. */
1733 log_info(LD_REND, "Introduction point legacy encryption key "
1734 "cross-certification has an unknown format.");
1735 goto err;
1737 /* Keep a copy of the certificate. */
1738 ip->legacy.cert.encoded = tor_memdup(tok->object_body, tok->object_size);
1739 ip->legacy.cert.len = tok->object_size;
1740 /* The check on the expiration date is for the entire lifetime of a
1741 * certificate which is 24 hours. However, a descriptor has a maximum
1742 * lifetime of 12 hours meaning we have a 12h difference between the two
1743 * which ultimately accommodate the clock skewed client. */
1744 if (rsa_ed25519_crosscert_check(ip->legacy.cert.encoded,
1745 ip->legacy.cert.len, ip->legacy.key,
1746 &desc->plaintext_data.signing_pubkey,
1747 approx_time() - HS_DESC_CERT_LIFETIME)) {
1748 log_warn(LD_REND, "Unable to check cross-certification on the "
1749 "introduction point legacy encryption key.");
1750 ip->cross_certified = 0;
1751 goto err;
1754 /* Success. */
1755 return 0;
1756 err:
1757 return -1;
1760 /** Dig into the descriptor <b>tokens</b> to find the onion key we should use
1761 * for this intro point, and set it into <b>onion_key_out</b>. Return 0 if it
1762 * was found and well-formed, otherwise return -1 in case of errors. */
1763 static int
1764 set_intro_point_onion_key(curve25519_public_key_t *onion_key_out,
1765 const smartlist_t *tokens)
1767 int retval = -1;
1768 smartlist_t *onion_keys = NULL;
1770 tor_assert(onion_key_out);
1772 onion_keys = find_all_by_keyword(tokens, R3_INTRO_ONION_KEY);
1773 if (!onion_keys) {
1774 log_warn(LD_REND, "Descriptor did not contain intro onion keys");
1775 goto err;
1778 SMARTLIST_FOREACH_BEGIN(onion_keys, directory_token_t *, tok) {
1779 /* This field is using GE(2) so for possible forward compatibility, we
1780 * accept more fields but must be at least 2. */
1781 tor_assert(tok->n_args >= 2);
1783 /* Try to find an ntor key, it's the only recognized type right now */
1784 if (!strcmp(tok->args[0], "ntor")) {
1785 if (curve25519_public_from_base64(onion_key_out, tok->args[1]) < 0) {
1786 log_warn(LD_REND, "Introduction point ntor onion-key is invalid");
1787 goto err;
1789 /* Got the onion key! Set the appropriate retval */
1790 retval = 0;
1792 } SMARTLIST_FOREACH_END(tok);
1794 /* Log an error if we didn't find it :( */
1795 if (retval < 0) {
1796 log_warn(LD_REND, "Descriptor did not contain ntor onion keys");
1799 err:
1800 smartlist_free(onion_keys);
1801 return retval;
1804 /** Given the start of a section and the end of it, decode a single
1805 * introduction point from that section. Return a newly allocated introduction
1806 * point object containing the decoded data. Return NULL if the section can't
1807 * be decoded. */
1808 STATIC hs_desc_intro_point_t *
1809 decode_introduction_point(const hs_descriptor_t *desc, const char *start)
1811 hs_desc_intro_point_t *ip = NULL;
1812 memarea_t *area = NULL;
1813 smartlist_t *tokens = NULL;
1814 const directory_token_t *tok;
1816 tor_assert(desc);
1817 tor_assert(start);
1819 area = memarea_new();
1820 tokens = smartlist_new();
1821 if (tokenize_string(area, start, start + strlen(start),
1822 tokens, hs_desc_intro_point_v3_token_table, 0) < 0) {
1823 log_warn(LD_REND, "Introduction point is not parseable");
1824 goto err;
1827 /* Ok we seem to have a well formed section containing enough tokens to
1828 * parse. Allocate our IP object and try to populate it. */
1829 ip = hs_desc_intro_point_new();
1831 /* "introduction-point" SP link-specifiers NL */
1832 tok = find_by_keyword(tokens, R3_INTRODUCTION_POINT);
1833 tor_assert(tok->n_args == 1);
1834 /* Our constructor creates this list by default so free it. */
1835 smartlist_free(ip->link_specifiers);
1836 ip->link_specifiers = decode_link_specifiers(tok->args[0]);
1837 if (!ip->link_specifiers) {
1838 log_warn(LD_REND, "Introduction point has invalid link specifiers");
1839 goto err;
1842 /* "onion-key" SP ntor SP key NL */
1843 if (set_intro_point_onion_key(&ip->onion_key, tokens) < 0) {
1844 goto err;
1847 /* "auth-key" NL certificate NL */
1848 tok = find_by_keyword(tokens, R3_INTRO_AUTH_KEY);
1849 tor_assert(tok->object_body);
1850 if (strcmp(tok->object_type, "ED25519 CERT")) {
1851 log_warn(LD_REND, "Unexpected object type for introduction auth key");
1852 goto err;
1854 /* Parse cert and do some validation. */
1855 if (cert_parse_and_validate(&ip->auth_key_cert, tok->object_body,
1856 tok->object_size, CERT_TYPE_AUTH_HS_IP_KEY,
1857 "introduction point auth-key") < 0) {
1858 goto err;
1860 /* Validate authentication certificate with descriptor signing key. */
1861 if (tor_cert_checksig(ip->auth_key_cert,
1862 &desc->plaintext_data.signing_pubkey, 0) < 0) {
1863 log_warn(LD_REND, "Invalid authentication key signature: %s",
1864 tor_cert_describe_signature_status(ip->auth_key_cert));
1865 goto err;
1868 /* Exactly one "enc-key" SP "ntor" SP key NL */
1869 tok = find_by_keyword(tokens, R3_INTRO_ENC_KEY);
1870 if (!strcmp(tok->args[0], "ntor")) {
1871 /* This field is using GE(2) so for possible forward compatibility, we
1872 * accept more fields but must be at least 2. */
1873 tor_assert(tok->n_args >= 2);
1875 if (curve25519_public_from_base64(&ip->enc_key, tok->args[1]) < 0) {
1876 log_warn(LD_REND, "Introduction point ntor enc-key is invalid");
1877 goto err;
1879 } else {
1880 /* Unknown key type so we can't use that introduction point. */
1881 log_warn(LD_REND, "Introduction point encryption key is unrecognized.");
1882 goto err;
1885 /* Exactly once "enc-key-cert" NL certificate NL */
1886 tok = find_by_keyword(tokens, R3_INTRO_ENC_KEY_CERT);
1887 tor_assert(tok->object_body);
1888 /* Do the cross certification. */
1889 if (strcmp(tok->object_type, "ED25519 CERT")) {
1890 log_warn(LD_REND, "Introduction point ntor encryption key "
1891 "cross-certification has an unknown format.");
1892 goto err;
1894 if (cert_parse_and_validate(&ip->enc_key_cert, tok->object_body,
1895 tok->object_size, CERT_TYPE_CROSS_HS_IP_KEYS,
1896 "introduction point enc-key-cert") < 0) {
1897 goto err;
1899 if (tor_cert_checksig(ip->enc_key_cert,
1900 &desc->plaintext_data.signing_pubkey, 0) < 0) {
1901 log_warn(LD_REND, "Invalid encryption key signature: %s",
1902 tor_cert_describe_signature_status(ip->enc_key_cert));
1903 goto err;
1905 /* It is successfully cross certified. Flag the object. */
1906 ip->cross_certified = 1;
1908 /* Do we have a "legacy-key" SP key NL ?*/
1909 tok = find_opt_by_keyword(tokens, R3_INTRO_LEGACY_KEY);
1910 if (tok) {
1911 if (decode_intro_legacy_key(tok, tokens, ip, desc) < 0) {
1912 goto err;
1916 /* Introduction point has been parsed successfully. */
1917 goto done;
1919 err:
1920 hs_desc_intro_point_free(ip);
1921 ip = NULL;
1923 done:
1924 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
1925 smartlist_free(tokens);
1926 if (area) {
1927 memarea_drop_all(area);
1930 return ip;
1933 /** Given a descriptor string at <b>data</b>, decode all possible introduction
1934 * points that we can find. Add the introduction point object to desc_enc as we
1935 * find them. This function can't fail and it is possible that zero
1936 * introduction points can be decoded. */
1937 static void
1938 decode_intro_points(const hs_descriptor_t *desc,
1939 hs_desc_encrypted_data_t *desc_enc,
1940 const char *data)
1942 smartlist_t *chunked_desc = smartlist_new();
1943 smartlist_t *intro_points = smartlist_new();
1945 tor_assert(desc);
1946 tor_assert(desc_enc);
1947 tor_assert(data);
1948 tor_assert(desc_enc->intro_points);
1950 /* Take the desc string, and extract the intro point substrings out of it */
1952 /* Split the descriptor string using the intro point header as delimiter */
1953 smartlist_split_string(chunked_desc, data, str_intro_point_start, 0, 0);
1955 /* Check if there are actually any intro points included. The first chunk
1956 * should be other descriptor fields (e.g. create2-formats), so it's not an
1957 * intro point. */
1958 if (smartlist_len(chunked_desc) < 2) {
1959 goto done;
1963 /* Take the intro point substrings, and prepare them for parsing */
1965 int i = 0;
1966 /* Prepend the introduction-point header to all the chunks, since
1967 smartlist_split_string() devoured it. */
1968 SMARTLIST_FOREACH_BEGIN(chunked_desc, char *, chunk) {
1969 /* Ignore first chunk. It's other descriptor fields. */
1970 if (i++ == 0) {
1971 continue;
1974 smartlist_add_asprintf(intro_points, "%s %s", str_intro_point, chunk);
1975 } SMARTLIST_FOREACH_END(chunk);
1978 /* Parse the intro points! */
1979 SMARTLIST_FOREACH_BEGIN(intro_points, const char *, intro_point) {
1980 hs_desc_intro_point_t *ip = decode_introduction_point(desc, intro_point);
1981 if (!ip) {
1982 /* Malformed introduction point section. We'll ignore this introduction
1983 * point and continue parsing. New or unknown fields are possible for
1984 * forward compatibility. */
1985 continue;
1987 smartlist_add(desc_enc->intro_points, ip);
1988 } SMARTLIST_FOREACH_END(intro_point);
1990 done:
1991 SMARTLIST_FOREACH(chunked_desc, char *, a, tor_free(a));
1992 smartlist_free(chunked_desc);
1993 SMARTLIST_FOREACH(intro_points, char *, a, tor_free(a));
1994 smartlist_free(intro_points);
1997 /** Return 1 iff the given base64 encoded signature in b64_sig from the encoded
1998 * descriptor in encoded_desc validates the descriptor content. */
1999 STATIC int
2000 desc_sig_is_valid(const char *b64_sig,
2001 const ed25519_public_key_t *signing_pubkey,
2002 const char *encoded_desc, size_t encoded_len)
2004 int ret = 0;
2005 ed25519_signature_t sig;
2006 const char *sig_start;
2008 tor_assert(b64_sig);
2009 tor_assert(signing_pubkey);
2010 tor_assert(encoded_desc);
2011 /* Verifying nothing won't end well :). */
2012 tor_assert(encoded_len > 0);
2014 /* Signature length check. */
2015 if (strlen(b64_sig) != ED25519_SIG_BASE64_LEN) {
2016 log_warn(LD_REND, "Service descriptor has an invalid signature length."
2017 "Expected %d but got %lu",
2018 ED25519_SIG_BASE64_LEN, (unsigned long) strlen(b64_sig));
2019 goto err;
2022 /* First, convert base64 blob to an ed25519 signature. */
2023 if (ed25519_signature_from_base64(&sig, b64_sig) != 0) {
2024 log_warn(LD_REND, "Service descriptor does not contain a valid "
2025 "signature");
2026 goto err;
2029 /* Find the start of signature. */
2030 sig_start = tor_memstr(encoded_desc, encoded_len, "\n" str_signature " ");
2031 /* Getting here means the token parsing worked for the signature so if we
2032 * can't find the start of the signature, we have a code flow issue. */
2033 if (!sig_start) {
2034 log_warn(LD_GENERAL, "Malformed signature line. Rejecting.");
2035 goto err;
2037 /* Skip newline, it has to go in the signature check. */
2038 sig_start++;
2040 /* Validate signature with the full body of the descriptor. */
2041 if (ed25519_checksig_prefixed(&sig,
2042 (const uint8_t *) encoded_desc,
2043 sig_start - encoded_desc,
2044 str_desc_sig_prefix,
2045 signing_pubkey) != 0) {
2046 log_warn(LD_REND, "Invalid signature on service descriptor");
2047 goto err;
2049 /* Valid signature! All is good. */
2050 ret = 1;
2052 err:
2053 return ret;
2056 /** Decode descriptor plaintext data for version 3. Given a list of tokens, an
2057 * allocated plaintext object that will be populated and the encoded
2058 * descriptor with its length. The last one is needed for signature
2059 * verification. Unknown tokens are simply ignored so this won't error on
2060 * unknowns but requires that all v3 token be present and valid.
2062 * Return 0 on success else a negative value. */
2063 static hs_desc_decode_status_t
2064 desc_decode_plaintext_v3(smartlist_t *tokens,
2065 hs_desc_plaintext_data_t *desc,
2066 const char *encoded_desc, size_t encoded_len)
2068 int ok;
2069 directory_token_t *tok;
2071 tor_assert(tokens);
2072 tor_assert(desc);
2073 /* Version higher could still use this function to decode most of the
2074 * descriptor and then they decode the extra part. */
2075 tor_assert(desc->version >= 3);
2077 /* Descriptor lifetime parsing. */
2078 tok = find_by_keyword(tokens, R3_DESC_LIFETIME);
2079 tor_assert(tok->n_args == 1);
2080 desc->lifetime_sec = (uint32_t) tor_parse_ulong(tok->args[0], 10, 0,
2081 UINT32_MAX, &ok, NULL);
2082 if (!ok) {
2083 log_warn(LD_REND, "Service descriptor lifetime value is invalid");
2084 goto err;
2086 /* Put it from minute to second. */
2087 desc->lifetime_sec *= 60;
2088 if (desc->lifetime_sec > HS_DESC_MAX_LIFETIME) {
2089 log_warn(LD_REND, "Service descriptor lifetime is too big. "
2090 "Got %" PRIu32 " but max is %d",
2091 desc->lifetime_sec, HS_DESC_MAX_LIFETIME);
2092 goto err;
2095 /* Descriptor signing certificate. */
2096 tok = find_by_keyword(tokens, R3_DESC_SIGNING_CERT);
2097 tor_assert(tok->object_body);
2098 /* Expecting a prop220 cert with the signing key extension, which contains
2099 * the blinded public key. */
2100 if (strcmp(tok->object_type, "ED25519 CERT") != 0) {
2101 log_warn(LD_REND, "Service descriptor signing cert wrong type (%s)",
2102 escaped(tok->object_type));
2103 goto err;
2105 if (cert_parse_and_validate(&desc->signing_key_cert, tok->object_body,
2106 tok->object_size, CERT_TYPE_SIGNING_HS_DESC,
2107 "service descriptor signing key") < 0) {
2108 goto err;
2111 /* Copy the public keys into signing_pubkey and blinded_pubkey */
2112 memcpy(&desc->signing_pubkey, &desc->signing_key_cert->signed_key,
2113 sizeof(ed25519_public_key_t));
2114 memcpy(&desc->blinded_pubkey, &desc->signing_key_cert->signing_key,
2115 sizeof(ed25519_public_key_t));
2117 /* Extract revision counter value. */
2118 tok = find_by_keyword(tokens, R3_REVISION_COUNTER);
2119 tor_assert(tok->n_args == 1);
2120 desc->revision_counter = tor_parse_uint64(tok->args[0], 10, 0,
2121 UINT64_MAX, &ok, NULL);
2122 if (!ok) {
2123 log_warn(LD_REND, "Service descriptor revision-counter is invalid");
2124 goto err;
2127 /* Extract the superencrypted data section. */
2128 tok = find_by_keyword(tokens, R3_SUPERENCRYPTED);
2129 tor_assert(tok->object_body);
2130 if (strcmp(tok->object_type, "MESSAGE") != 0) {
2131 log_warn(LD_REND, "Desc superencrypted data section is invalid");
2132 goto err;
2134 /* Make sure the length of the superencrypted blob is valid. */
2135 if (!encrypted_data_length_is_valid(tok->object_size)) {
2136 goto err;
2139 /* Copy the superencrypted blob to the descriptor object so we can handle it
2140 * latter if needed. */
2141 desc->superencrypted_blob = tor_memdup(tok->object_body, tok->object_size);
2142 desc->superencrypted_blob_size = tok->object_size;
2144 /* Extract signature and verify it. */
2145 tok = find_by_keyword(tokens, R3_SIGNATURE);
2146 tor_assert(tok->n_args == 1);
2147 /* First arg here is the actual encoded signature. */
2148 if (!desc_sig_is_valid(tok->args[0], &desc->signing_pubkey,
2149 encoded_desc, encoded_len)) {
2150 goto err;
2153 return HS_DESC_DECODE_OK;
2154 err:
2155 return HS_DESC_DECODE_PLAINTEXT_ERROR;
2158 /** Decode the version 3 superencrypted section of the given descriptor desc.
2159 * The desc_superencrypted_out will be populated with the decoded data. */
2160 STATIC hs_desc_decode_status_t
2161 desc_decode_superencrypted_v3(const hs_descriptor_t *desc,
2162 hs_desc_superencrypted_data_t *
2163 desc_superencrypted_out)
2165 int ret = HS_DESC_DECODE_SUPERENC_ERROR;
2166 char *message = NULL;
2167 size_t message_len;
2168 memarea_t *area = NULL;
2169 directory_token_t *tok;
2170 smartlist_t *tokens = NULL;
2171 /* Rename the parameter because it is too long. */
2172 hs_desc_superencrypted_data_t *superencrypted = desc_superencrypted_out;
2174 tor_assert(desc);
2175 tor_assert(desc_superencrypted_out);
2177 /* Decrypt the superencrypted data that is located in the plaintext section
2178 * in the descriptor as a blob of bytes. */
2179 message_len = desc_decrypt_superencrypted(desc, &message);
2180 if (!message_len) {
2181 log_warn(LD_REND, "Service descriptor decryption failed.");
2182 goto err;
2184 tor_assert(message);
2186 area = memarea_new();
2187 tokens = smartlist_new();
2188 if (tokenize_string(area, message, message + message_len,
2189 tokens, hs_desc_superencrypted_v3_token_table, 0) < 0) {
2190 log_warn(LD_REND, "Superencrypted service descriptor is not parseable.");
2191 goto err;
2194 /* Verify desc auth type */
2195 tok = find_by_keyword(tokens, R3_DESC_AUTH_TYPE);
2196 tor_assert(tok->n_args >= 1);
2197 if (strcmp(tok->args[0], "x25519")) {
2198 log_warn(LD_DIR, "Unrecognized desc auth type");
2199 goto err;
2202 /* Extract desc auth ephemeral key */
2203 tok = find_by_keyword(tokens, R3_DESC_AUTH_KEY);
2204 tor_assert(tok->n_args >= 1);
2205 if (curve25519_public_from_base64(&superencrypted->auth_ephemeral_pubkey,
2206 tok->args[0]) < 0) {
2207 log_warn(LD_DIR, "Bogus desc auth ephemeral key in HS desc");
2208 goto err;
2211 /* Extract desc auth client items */
2212 if (!superencrypted->clients) {
2213 superencrypted->clients = smartlist_new();
2215 SMARTLIST_FOREACH_BEGIN(tokens, const directory_token_t *, token) {
2216 if (token->tp == R3_DESC_AUTH_CLIENT) {
2217 tor_assert(token->n_args >= 3);
2219 hs_desc_authorized_client_t *client =
2220 tor_malloc_zero(sizeof(hs_desc_authorized_client_t));
2222 if (decode_auth_client(token, client) < 0) {
2223 log_warn(LD_REND, "Descriptor client authorization section can't "
2224 "be decoded.");
2225 tor_free(client);
2226 goto err;
2228 smartlist_add(superencrypted->clients, client);
2230 } SMARTLIST_FOREACH_END(token);
2232 /* Extract the encrypted data section. */
2233 tok = find_by_keyword(tokens, R3_ENCRYPTED);
2234 tor_assert(tok->object_body);
2235 if (strcmp(tok->object_type, "MESSAGE") != 0) {
2236 log_warn(LD_REND, "Desc encrypted data section is invalid");
2237 goto err;
2239 /* Make sure the length of the encrypted blob is valid. */
2240 if (!encrypted_data_length_is_valid(tok->object_size)) {
2241 goto err;
2244 /* Copy the encrypted blob to the descriptor object so we can handle it
2245 * latter if needed. */
2246 tor_assert(tok->object_size <= INT_MAX);
2247 superencrypted->encrypted_blob = tor_memdup(tok->object_body,
2248 tok->object_size);
2249 superencrypted->encrypted_blob_size = tok->object_size;
2251 ret = HS_DESC_DECODE_OK;
2252 goto done;
2254 err:
2255 tor_assert(ret < HS_DESC_DECODE_OK);
2256 hs_desc_superencrypted_data_free_contents(desc_superencrypted_out);
2258 done:
2259 if (tokens) {
2260 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
2261 smartlist_free(tokens);
2263 if (area) {
2264 memarea_drop_all(area);
2266 if (message) {
2267 tor_free(message);
2269 return ret;
2272 /** Decode the version 3 encrypted section of the given descriptor desc. The
2273 * desc_encrypted_out will be populated with the decoded data. */
2274 STATIC hs_desc_decode_status_t
2275 desc_decode_encrypted_v3(const hs_descriptor_t *desc,
2276 const curve25519_secret_key_t *client_auth_sk,
2277 hs_desc_encrypted_data_t *desc_encrypted_out)
2279 int ret = HS_DESC_DECODE_ENCRYPTED_ERROR;
2280 char *message = NULL;
2281 size_t message_len;
2282 memarea_t *area = NULL;
2283 directory_token_t *tok;
2284 smartlist_t *tokens = NULL;
2286 tor_assert(desc);
2287 tor_assert(desc_encrypted_out);
2289 /* Decrypt the encrypted data that is located in the superencrypted section
2290 * in the descriptor as a blob of bytes. */
2291 message_len = desc_decrypt_encrypted(desc, client_auth_sk, &message);
2292 if (!message_len) {
2293 /* Two possible situation here. Either we have a client authorization
2294 * configured that didn't work or we do not have any configured for this
2295 * onion address so likely the descriptor is for authorized client only,
2296 * we are not. */
2297 if (client_auth_sk) {
2298 /* At warning level so the client can notice that its client
2299 * authorization is failing. */
2300 log_warn(LD_REND, "Client authorization for requested onion address "
2301 "is invalid. Can't decrypt the descriptor.");
2302 ret = HS_DESC_DECODE_BAD_CLIENT_AUTH;
2303 } else {
2304 /* Inform at notice level that the onion address requested can't be
2305 * reached without client authorization most likely. */
2306 log_notice(LD_REND, "Fail to decrypt descriptor for requested onion "
2307 "address. It is likely requiring client "
2308 "authorization.");
2309 ret = HS_DESC_DECODE_NEED_CLIENT_AUTH;
2311 goto err;
2313 tor_assert(message);
2315 area = memarea_new();
2316 tokens = smartlist_new();
2317 if (tokenize_string(area, message, message + message_len,
2318 tokens, hs_desc_encrypted_v3_token_table, 0) < 0) {
2319 log_warn(LD_REND, "Encrypted service descriptor is not parseable.");
2320 goto err;
2323 /* CREATE2 supported cell format. It's mandatory. */
2324 tok = find_by_keyword(tokens, R3_CREATE2_FORMATS);
2325 tor_assert(tok);
2326 decode_create2_list(desc_encrypted_out, tok->args[0]);
2327 /* Must support ntor according to the specification */
2328 if (!desc_encrypted_out->create2_ntor) {
2329 log_warn(LD_REND, "Service create2-formats does not include ntor.");
2330 goto err;
2333 /* Authentication type. It's optional but only once. */
2334 tok = find_opt_by_keyword(tokens, R3_INTRO_AUTH_REQUIRED);
2335 if (tok) {
2336 tor_assert(tok->n_args >= 1);
2337 if (!decode_auth_type(desc_encrypted_out, tok->args[0])) {
2338 log_warn(LD_REND, "Service descriptor authentication type has "
2339 "invalid entry(ies).");
2340 goto err;
2344 /* Is this service a single onion service? */
2345 tok = find_opt_by_keyword(tokens, R3_SINGLE_ONION_SERVICE);
2346 if (tok) {
2347 desc_encrypted_out->single_onion_service = 1;
2350 /* Initialize the descriptor's introduction point list before we start
2351 * decoding. Having 0 intro point is valid. Then decode them all. */
2352 desc_encrypted_out->intro_points = smartlist_new();
2353 decode_intro_points(desc, desc_encrypted_out, message);
2355 /* Validation of maximum introduction points allowed. */
2356 if (smartlist_len(desc_encrypted_out->intro_points) >
2357 HS_CONFIG_V3_MAX_INTRO_POINTS) {
2358 log_warn(LD_REND, "Service descriptor contains too many introduction "
2359 "points. Maximum allowed is %d but we have %d",
2360 HS_CONFIG_V3_MAX_INTRO_POINTS,
2361 smartlist_len(desc_encrypted_out->intro_points));
2362 goto err;
2365 /* NOTE: Unknown fields are allowed because this function could be used to
2366 * decode other descriptor version. */
2368 ret = HS_DESC_DECODE_OK;
2369 goto done;
2371 err:
2372 tor_assert(ret < HS_DESC_DECODE_OK);
2373 hs_desc_encrypted_data_free_contents(desc_encrypted_out);
2375 done:
2376 if (tokens) {
2377 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
2378 smartlist_free(tokens);
2380 if (area) {
2381 memarea_drop_all(area);
2383 if (message) {
2384 tor_free(message);
2386 return ret;
2389 /** Table of encrypted decode function version specific. The function are
2390 * indexed by the version number so v3 callback is at index 3 in the array. */
2391 static hs_desc_decode_status_t
2392 (*decode_encrypted_handlers[])(
2393 const hs_descriptor_t *desc,
2394 const curve25519_secret_key_t *client_auth_sk,
2395 hs_desc_encrypted_data_t *desc_encrypted) =
2397 /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
2398 desc_decode_encrypted_v3,
2401 /** Decode the encrypted data section of the given descriptor and store the
2402 * data in the given encrypted data object. Return 0 on success else a
2403 * negative value on error. */
2404 hs_desc_decode_status_t
2405 hs_desc_decode_encrypted(const hs_descriptor_t *desc,
2406 const curve25519_secret_key_t *client_auth_sk,
2407 hs_desc_encrypted_data_t *desc_encrypted)
2409 int ret = HS_DESC_DECODE_ENCRYPTED_ERROR;
2410 uint32_t version;
2412 tor_assert(desc);
2413 /* Ease our life a bit. */
2414 version = desc->plaintext_data.version;
2415 tor_assert(desc_encrypted);
2416 /* Calling this function without an encrypted blob to parse is a code flow
2417 * error. The superencrypted parsing should never succeed in the first place
2418 * without an encrypted section. */
2419 tor_assert(desc->superencrypted_data.encrypted_blob);
2420 /* Let's make sure we have a supported version as well. By correctly parsing
2421 * the plaintext, this should not fail. */
2422 if (BUG(!hs_desc_is_supported_version(version))) {
2423 goto err;
2425 /* Extra precaution. Having no handler for the supported version should
2426 * never happened else we forgot to add it but we bumped the version. */
2427 tor_assert(ARRAY_LENGTH(decode_encrypted_handlers) >= version);
2428 tor_assert(decode_encrypted_handlers[version]);
2430 /* Run the version specific plaintext decoder. */
2431 ret = decode_encrypted_handlers[version](desc, client_auth_sk,
2432 desc_encrypted);
2433 if (ret < 0) {
2434 goto err;
2437 err:
2438 return ret;
2441 /** Table of superencrypted decode function version specific. The function are
2442 * indexed by the version number so v3 callback is at index 3 in the array. */
2443 static hs_desc_decode_status_t
2444 (*decode_superencrypted_handlers[])(
2445 const hs_descriptor_t *desc,
2446 hs_desc_superencrypted_data_t *desc_superencrypted) =
2448 /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
2449 desc_decode_superencrypted_v3,
2452 /** Decode the superencrypted data section of the given descriptor and store
2453 * the data in the given superencrypted data object. */
2454 hs_desc_decode_status_t
2455 hs_desc_decode_superencrypted(const hs_descriptor_t *desc,
2456 hs_desc_superencrypted_data_t *
2457 desc_superencrypted)
2459 int ret = HS_DESC_DECODE_SUPERENC_ERROR;
2460 uint32_t version;
2462 tor_assert(desc);
2463 /* Ease our life a bit. */
2464 version = desc->plaintext_data.version;
2465 tor_assert(desc_superencrypted);
2466 /* Calling this function without an superencrypted blob to parse is
2467 * a code flow error. The plaintext parsing should never succeed in
2468 * the first place without an superencrypted section. */
2469 tor_assert(desc->plaintext_data.superencrypted_blob);
2470 /* Let's make sure we have a supported version as well. By correctly parsing
2471 * the plaintext, this should not fail. */
2472 if (BUG(!hs_desc_is_supported_version(version))) {
2473 goto err;
2475 /* Extra precaution. Having no handler for the supported version should
2476 * never happened else we forgot to add it but we bumped the version. */
2477 tor_assert(ARRAY_LENGTH(decode_superencrypted_handlers) >= version);
2478 tor_assert(decode_superencrypted_handlers[version]);
2480 /* Run the version specific plaintext decoder. */
2481 ret = decode_superencrypted_handlers[version](desc, desc_superencrypted);
2482 if (ret < 0) {
2483 goto err;
2486 err:
2487 return ret;
2490 /** Table of plaintext decode function version specific. The function are
2491 * indexed by the version number so v3 callback is at index 3 in the array. */
2492 static hs_desc_decode_status_t
2493 (*decode_plaintext_handlers[])(
2494 smartlist_t *tokens,
2495 hs_desc_plaintext_data_t *desc,
2496 const char *encoded_desc,
2497 size_t encoded_len) =
2499 /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
2500 desc_decode_plaintext_v3,
2503 /** Fully decode the given descriptor plaintext and store the data in the
2504 * plaintext data object. */
2505 hs_desc_decode_status_t
2506 hs_desc_decode_plaintext(const char *encoded,
2507 hs_desc_plaintext_data_t *plaintext)
2509 int ok = 0, ret = HS_DESC_DECODE_PLAINTEXT_ERROR;
2510 memarea_t *area = NULL;
2511 smartlist_t *tokens = NULL;
2512 size_t encoded_len;
2513 directory_token_t *tok;
2515 tor_assert(encoded);
2516 tor_assert(plaintext);
2518 /* Check that descriptor is within size limits. */
2519 encoded_len = strlen(encoded);
2520 if (encoded_len >= hs_cache_get_max_descriptor_size()) {
2521 log_warn(LD_REND, "Service descriptor is too big (%lu bytes)",
2522 (unsigned long) encoded_len);
2523 goto err;
2526 area = memarea_new();
2527 tokens = smartlist_new();
2528 /* Tokenize the descriptor so we can start to parse it. */
2529 if (tokenize_string(area, encoded, encoded + encoded_len, tokens,
2530 hs_desc_v3_token_table, 0) < 0) {
2531 log_warn(LD_REND, "Service descriptor is not parseable");
2532 goto err;
2535 /* Get the version of the descriptor which is the first mandatory field of
2536 * the descriptor. From there, we'll decode the right descriptor version. */
2537 tok = find_by_keyword(tokens, R_HS_DESCRIPTOR);
2538 tor_assert(tok->n_args == 1);
2539 plaintext->version = (uint32_t) tor_parse_ulong(tok->args[0], 10, 0,
2540 UINT32_MAX, &ok, NULL);
2541 if (!ok) {
2542 log_warn(LD_REND, "Service descriptor has unparseable version %s",
2543 escaped(tok->args[0]));
2544 goto err;
2546 if (!hs_desc_is_supported_version(plaintext->version)) {
2547 log_warn(LD_REND, "Service descriptor has unsupported version %" PRIu32,
2548 plaintext->version);
2549 goto err;
2551 /* Extra precaution. Having no handler for the supported version should
2552 * never happened else we forgot to add it but we bumped the version. */
2553 tor_assert(ARRAY_LENGTH(decode_plaintext_handlers) >= plaintext->version);
2554 tor_assert(decode_plaintext_handlers[plaintext->version]);
2556 /* Run the version specific plaintext decoder. */
2557 ret = decode_plaintext_handlers[plaintext->version](tokens, plaintext,
2558 encoded, encoded_len);
2559 if (ret != HS_DESC_DECODE_OK) {
2560 goto err;
2562 /* Success. Descriptor has been populated with the data. */
2563 ret = HS_DESC_DECODE_OK;
2565 err:
2566 if (tokens) {
2567 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
2568 smartlist_free(tokens);
2570 if (area) {
2571 memarea_drop_all(area);
2573 return ret;
2576 /** Fully decode an encoded descriptor and set a newly allocated descriptor
2577 * object in desc_out. Client secret key is used to decrypt the "encrypted"
2578 * section if not NULL else it's ignored.
2580 * Return 0 on success. A negative value is returned on error and desc_out is
2581 * set to NULL. */
2582 hs_desc_decode_status_t
2583 hs_desc_decode_descriptor(const char *encoded,
2584 const hs_subcredential_t *subcredential,
2585 const curve25519_secret_key_t *client_auth_sk,
2586 hs_descriptor_t **desc_out)
2588 hs_desc_decode_status_t ret = HS_DESC_DECODE_GENERIC_ERROR;
2589 hs_descriptor_t *desc;
2591 tor_assert(encoded);
2593 desc = tor_malloc_zero(sizeof(hs_descriptor_t));
2595 /* Subcredentials are not optional. */
2596 if (BUG(!subcredential ||
2597 fast_mem_is_zero((char*)subcredential, DIGEST256_LEN))) {
2598 log_warn(LD_GENERAL, "Tried to decrypt without subcred. Impossible!");
2599 goto err;
2602 memcpy(&desc->subcredential, subcredential, sizeof(desc->subcredential));
2604 ret = hs_desc_decode_plaintext(encoded, &desc->plaintext_data);
2605 if (ret != HS_DESC_DECODE_OK) {
2606 goto err;
2609 ret = hs_desc_decode_superencrypted(desc, &desc->superencrypted_data);
2610 if (ret != HS_DESC_DECODE_OK) {
2611 goto err;
2614 ret = hs_desc_decode_encrypted(desc, client_auth_sk, &desc->encrypted_data);
2615 if (ret != HS_DESC_DECODE_OK) {
2616 goto err;
2619 if (desc_out) {
2620 *desc_out = desc;
2621 } else {
2622 hs_descriptor_free(desc);
2624 return ret;
2626 err:
2627 hs_descriptor_free(desc);
2628 if (desc_out) {
2629 *desc_out = NULL;
2632 tor_assert(ret < 0);
2633 return ret;
2636 /** Table of encode function version specific. The functions are indexed by the
2637 * version number so v3 callback is at index 3 in the array. */
2638 static int
2639 (*encode_handlers[])(
2640 const hs_descriptor_t *desc,
2641 const ed25519_keypair_t *signing_kp,
2642 const uint8_t *descriptor_cookie,
2643 char **encoded_out) =
2645 /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
2646 desc_encode_v3,
2649 /** Encode the given descriptor desc including signing with the given key pair
2650 * signing_kp and encrypting with the given descriptor cookie.
2652 * If the client authorization is enabled, descriptor_cookie must be the same
2653 * as the one used to build hs_desc_authorized_client_t in the descriptor.
2654 * Otherwise, it must be NULL. On success, encoded_out points to a newly
2655 * allocated NUL terminated string that contains the encoded descriptor as
2656 * a string.
2658 * Return 0 on success and encoded_out is a valid pointer. On error, -1 is
2659 * returned and encoded_out is set to NULL. */
2660 MOCK_IMPL(int,
2661 hs_desc_encode_descriptor,(const hs_descriptor_t *desc,
2662 const ed25519_keypair_t *signing_kp,
2663 const uint8_t *descriptor_cookie,
2664 char **encoded_out))
2666 int ret = -1;
2667 uint32_t version;
2669 tor_assert(desc);
2670 tor_assert(encoded_out);
2672 /* Make sure we support the version of the descriptor format. */
2673 version = desc->plaintext_data.version;
2674 if (!hs_desc_is_supported_version(version)) {
2675 goto err;
2677 /* Extra precaution. Having no handler for the supported version should
2678 * never happened else we forgot to add it but we bumped the version. */
2679 tor_assert(ARRAY_LENGTH(encode_handlers) >= version);
2680 tor_assert(encode_handlers[version]);
2682 ret = encode_handlers[version](desc, signing_kp,
2683 descriptor_cookie, encoded_out);
2684 if (ret < 0) {
2685 goto err;
2688 /* Try to decode what we just encoded. Symmetry is nice!, but it is
2689 * symmetric only if the client auth is disabled. That is, the descriptor
2690 * cookie will be NULL. */
2691 if (!descriptor_cookie) {
2692 ret = hs_desc_decode_descriptor(*encoded_out, &desc->subcredential,
2693 NULL, NULL);
2694 if (BUG(ret != HS_DESC_DECODE_OK)) {
2695 ret = -1;
2696 goto err;
2700 return 0;
2702 err:
2703 *encoded_out = NULL;
2704 return ret;
2707 /** Free the content of the plaintext section of a descriptor. */
2708 void
2709 hs_desc_plaintext_data_free_contents(hs_desc_plaintext_data_t *desc)
2711 if (!desc) {
2712 return;
2715 if (desc->superencrypted_blob) {
2716 tor_free(desc->superencrypted_blob);
2718 tor_cert_free(desc->signing_key_cert);
2720 memwipe(desc, 0, sizeof(*desc));
2723 /** Free the content of the superencrypted section of a descriptor. */
2724 void
2725 hs_desc_superencrypted_data_free_contents(hs_desc_superencrypted_data_t *desc)
2727 if (!desc) {
2728 return;
2731 if (desc->encrypted_blob) {
2732 tor_free(desc->encrypted_blob);
2734 if (desc->clients) {
2735 SMARTLIST_FOREACH(desc->clients, hs_desc_authorized_client_t *, client,
2736 hs_desc_authorized_client_free(client));
2737 smartlist_free(desc->clients);
2740 memwipe(desc, 0, sizeof(*desc));
2743 /** Free the content of the encrypted section of a descriptor. */
2744 void
2745 hs_desc_encrypted_data_free_contents(hs_desc_encrypted_data_t *desc)
2747 if (!desc) {
2748 return;
2751 if (desc->intro_auth_types) {
2752 SMARTLIST_FOREACH(desc->intro_auth_types, char *, a, tor_free(a));
2753 smartlist_free(desc->intro_auth_types);
2755 if (desc->intro_points) {
2756 SMARTLIST_FOREACH(desc->intro_points, hs_desc_intro_point_t *, ip,
2757 hs_desc_intro_point_free(ip));
2758 smartlist_free(desc->intro_points);
2760 memwipe(desc, 0, sizeof(*desc));
2763 /** Free the descriptor plaintext data object. */
2764 void
2765 hs_desc_plaintext_data_free_(hs_desc_plaintext_data_t *desc)
2767 hs_desc_plaintext_data_free_contents(desc);
2768 tor_free(desc);
2771 /** Free the descriptor plaintext data object. */
2772 void
2773 hs_desc_superencrypted_data_free_(hs_desc_superencrypted_data_t *desc)
2775 hs_desc_superencrypted_data_free_contents(desc);
2776 tor_free(desc);
2779 /** Free the descriptor encrypted data object. */
2780 void
2781 hs_desc_encrypted_data_free_(hs_desc_encrypted_data_t *desc)
2783 hs_desc_encrypted_data_free_contents(desc);
2784 tor_free(desc);
2787 /** Free the given descriptor object. */
2788 void
2789 hs_descriptor_free_(hs_descriptor_t *desc)
2791 if (!desc) {
2792 return;
2795 hs_desc_plaintext_data_free_contents(&desc->plaintext_data);
2796 hs_desc_superencrypted_data_free_contents(&desc->superencrypted_data);
2797 hs_desc_encrypted_data_free_contents(&desc->encrypted_data);
2798 tor_free(desc);
2801 /** Return the size in bytes of the given plaintext data object. A sizeof() is
2802 * not enough because the object contains pointers and the encrypted blob.
2803 * This is particularly useful for our OOM subsystem that tracks the HSDir
2804 * cache size for instance. */
2805 size_t
2806 hs_desc_plaintext_obj_size(const hs_desc_plaintext_data_t *data)
2808 tor_assert(data);
2809 return (sizeof(*data) + sizeof(*data->signing_key_cert) +
2810 data->superencrypted_blob_size);
2813 /** Return the size in bytes of the given encrypted data object. Used by OOM
2814 * subsystem. */
2815 static size_t
2816 hs_desc_encrypted_obj_size(const hs_desc_encrypted_data_t *data)
2818 tor_assert(data);
2819 size_t intro_size = 0;
2820 if (data->intro_auth_types) {
2821 intro_size +=
2822 smartlist_len(data->intro_auth_types) * sizeof(intro_auth_types);
2824 if (data->intro_points) {
2825 /* XXX could follow pointers here and get more accurate size */
2826 intro_size +=
2827 smartlist_len(data->intro_points) * sizeof(hs_desc_intro_point_t);
2830 return sizeof(*data) + intro_size;
2833 /** Return the size in bytes of the given descriptor object. Used by OOM
2834 * subsystem. */
2835 size_t
2836 hs_desc_obj_size(const hs_descriptor_t *data)
2838 if (data == NULL) {
2839 return 0;
2841 return (hs_desc_plaintext_obj_size(&data->plaintext_data) +
2842 hs_desc_encrypted_obj_size(&data->encrypted_data) +
2843 sizeof(data->subcredential));
2846 /** Return a newly allocated descriptor intro point. */
2847 hs_desc_intro_point_t *
2848 hs_desc_intro_point_new(void)
2850 hs_desc_intro_point_t *ip = tor_malloc_zero(sizeof(*ip));
2851 ip->link_specifiers = smartlist_new();
2852 return ip;
2855 /** Free a descriptor intro point object. */
2856 void
2857 hs_desc_intro_point_free_(hs_desc_intro_point_t *ip)
2859 if (ip == NULL) {
2860 return;
2862 if (ip->link_specifiers) {
2863 SMARTLIST_FOREACH(ip->link_specifiers, link_specifier_t *,
2864 ls, link_specifier_free(ls));
2865 smartlist_free(ip->link_specifiers);
2867 tor_cert_free(ip->auth_key_cert);
2868 tor_cert_free(ip->enc_key_cert);
2869 crypto_pk_free(ip->legacy.key);
2870 tor_free(ip->legacy.cert.encoded);
2871 tor_free(ip);
2874 /** Allocate and build a new fake client info for the descriptor. Return a
2875 * newly allocated object. This can't fail. */
2876 hs_desc_authorized_client_t *
2877 hs_desc_build_fake_authorized_client(void)
2879 hs_desc_authorized_client_t *client_auth =
2880 tor_malloc_zero(sizeof(*client_auth));
2882 crypto_rand((char *) client_auth->client_id,
2883 sizeof(client_auth->client_id));
2884 crypto_rand((char *) client_auth->iv,
2885 sizeof(client_auth->iv));
2886 crypto_rand((char *) client_auth->encrypted_cookie,
2887 sizeof(client_auth->encrypted_cookie));
2889 return client_auth;
2892 /** Using the service's subcredential, client public key, auth ephemeral secret
2893 * key, and descriptor cookie, build the auth client so we can then encode the
2894 * descriptor for publication. client_out must be already allocated. */
2895 void
2896 hs_desc_build_authorized_client(const hs_subcredential_t *subcredential,
2897 const curve25519_public_key_t *client_auth_pk,
2898 const curve25519_secret_key_t *
2899 auth_ephemeral_sk,
2900 const uint8_t *descriptor_cookie,
2901 hs_desc_authorized_client_t *client_out)
2903 uint8_t *keystream = NULL;
2904 size_t keystream_length = 0;
2905 const uint8_t *cookie_key;
2906 crypto_cipher_t *cipher;
2908 tor_assert(client_auth_pk);
2909 tor_assert(auth_ephemeral_sk);
2910 tor_assert(descriptor_cookie);
2911 tor_assert(client_out);
2912 tor_assert(subcredential);
2913 tor_assert(!fast_mem_is_zero((char *) auth_ephemeral_sk,
2914 sizeof(*auth_ephemeral_sk)));
2915 tor_assert(!fast_mem_is_zero((char *) client_auth_pk,
2916 sizeof(*client_auth_pk)));
2917 tor_assert(!fast_mem_is_zero((char *) descriptor_cookie,
2918 HS_DESC_DESCRIPTOR_COOKIE_LEN));
2919 tor_assert(!fast_mem_is_zero((char *) subcredential,
2920 DIGEST256_LEN));
2922 /* Get the KEYS part so we can derive the CLIENT-ID and COOKIE-KEY. */
2923 keystream_length =
2924 build_descriptor_cookie_keys(subcredential,
2925 auth_ephemeral_sk, client_auth_pk,
2926 &keystream);
2927 tor_assert(keystream_length > 0);
2929 /* Extract the CLIENT-ID and COOKIE-KEY from the KEYS. */
2930 memcpy(client_out->client_id, keystream, HS_DESC_CLIENT_ID_LEN);
2931 cookie_key = keystream + HS_DESC_CLIENT_ID_LEN;
2933 /* Random IV */
2934 crypto_strongest_rand(client_out->iv, sizeof(client_out->iv));
2936 /* This creates a cipher for AES. It can't fail. */
2937 cipher = crypto_cipher_new_with_iv_and_bits(cookie_key, client_out->iv,
2938 HS_DESC_COOKIE_KEY_BIT_SIZE);
2939 /* This can't fail. */
2940 crypto_cipher_encrypt(cipher, (char *) client_out->encrypted_cookie,
2941 (const char *) descriptor_cookie,
2942 HS_DESC_DESCRIPTOR_COOKIE_LEN);
2944 memwipe(keystream, 0, keystream_length);
2945 tor_free(keystream);
2947 crypto_cipher_free(cipher);
2950 /** Free an authoriezd client object. */
2951 void
2952 hs_desc_authorized_client_free_(hs_desc_authorized_client_t *client)
2954 tor_free(client);
2957 /** From the given descriptor, remove and free every introduction point. */
2958 void
2959 hs_descriptor_clear_intro_points(hs_descriptor_t *desc)
2961 smartlist_t *ips;
2963 tor_assert(desc);
2965 ips = desc->encrypted_data.intro_points;
2966 if (ips) {
2967 SMARTLIST_FOREACH(ips, hs_desc_intro_point_t *,
2968 ip, hs_desc_intro_point_free(ip));
2969 smartlist_clear(ips);