1 /* Copyright (c) 2016-2021, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
5 * \file hs_descriptor.c
6 * \brief Handle hidden service descriptor encoding/decoding.
9 * Here is a graphical depiction of an HS descriptor and its layers:
11 * +------------------------------------------------------+
12 * |DESCRIPTOR HEADER: |
14 * | descriptor-lifetime 180 |
17 * |+---------------------------------------------------+ |
18 * ||SUPERENCRYPTED LAYER (aka OUTER ENCRYPTED LAYER): | |
19 * || desc-auth-type x25519 | |
20 * || desc-auth-ephemeral-key | |
25 * ||+-------------------------------------------------+| |
26 * |||ENCRYPTED LAYER (aka INNER ENCRYPTED LAYER): || |
27 * ||| create2-formats || |
28 * ||| intro-auth-required || |
29 * ||| introduction-point || |
30 * ||| introduction-point || |
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.
56 #define HS_DESCRIPTOR_PRIVATE
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/hs/hs_pow.h"
72 #include "feature/nodelist/torcert.h" /* tor_cert_encode_ed22519() */
73 #include "lib/memarea/memarea.h"
74 #include "lib/crypt_ops/crypto_format.h"
75 #include "core/or/versions.h"
77 #include "core/or/extend_info_st.h"
79 /* Constant string value used for the descriptor format. */
80 #define str_hs_desc "hs-descriptor"
81 #define str_desc_cert "descriptor-signing-key-cert"
82 #define str_rev_counter "revision-counter"
83 #define str_superencrypted "superencrypted"
84 #define str_encrypted "encrypted"
85 #define str_signature "signature"
86 #define str_lifetime "descriptor-lifetime"
87 /* Constant string value for the encrypted part of the descriptor. */
88 #define str_create2_formats "create2-formats"
89 #define str_intro_auth_required "intro-auth-required"
90 #define str_single_onion "single-onion-service"
91 #define str_intro_point "introduction-point"
92 #define str_ip_onion_key "onion-key"
93 #define str_ip_auth_key "auth-key"
94 #define str_ip_enc_key "enc-key"
95 #define str_ip_enc_key_cert "enc-key-cert"
96 #define str_ip_legacy_key "legacy-key"
97 #define str_ip_legacy_key_cert "legacy-key-cert"
98 #define str_intro_point_start "\n" str_intro_point " "
99 #define str_flow_control "flow-control"
100 #define str_pow_params "pow-params"
101 /* Constant string value for the construction to encrypt the encrypted data
103 #define str_enc_const_superencryption "hsdir-superencrypted-data"
104 #define str_enc_const_encryption "hsdir-encrypted-data"
105 /* Prefix required to compute/verify HS desc signatures */
106 #define str_desc_sig_prefix "Tor onion service descriptor sig v3"
107 #define str_desc_auth_type "desc-auth-type"
108 #define str_desc_auth_key "desc-auth-ephemeral-key"
109 #define str_desc_auth_client "auth-client"
110 #define str_encrypted "encrypted"
112 /** Authentication supported types. */
113 static const struct {
114 hs_desc_auth_type_t type
;
115 const char *identifier
;
116 } intro_auth_types
[] = {
117 { HS_DESC_AUTH_ED25519
, "ed25519" },
118 /* Indicate end of array. */
122 /** PoW supported types. */
123 static const struct {
124 hs_pow_desc_type_t type
;
125 const char *identifier
;
127 { HS_POW_DESC_V1
, "v1"},
128 /* Indicate end of array. */
132 /** Descriptor ruleset. */
133 static token_rule_t hs_desc_v3_token_table
[] = {
134 T1_START(str_hs_desc
, R_HS_DESCRIPTOR
, EQ(1), NO_OBJ
),
135 T1(str_lifetime
, R3_DESC_LIFETIME
, EQ(1), NO_OBJ
),
136 T1(str_desc_cert
, R3_DESC_SIGNING_CERT
, NO_ARGS
, NEED_OBJ
),
137 T1(str_rev_counter
, R3_REVISION_COUNTER
, EQ(1), NO_OBJ
),
138 T1(str_superencrypted
, R3_SUPERENCRYPTED
, NO_ARGS
, NEED_OBJ
),
139 T1_END(str_signature
, R3_SIGNATURE
, EQ(1), NO_OBJ
),
143 /** Descriptor ruleset for the superencrypted section. */
144 static token_rule_t hs_desc_superencrypted_v3_token_table
[] = {
145 T1_START(str_desc_auth_type
, R3_DESC_AUTH_TYPE
, GE(1), NO_OBJ
),
146 T1(str_desc_auth_key
, R3_DESC_AUTH_KEY
, GE(1), NO_OBJ
),
147 T1N(str_desc_auth_client
, R3_DESC_AUTH_CLIENT
, GE(3), NO_OBJ
),
148 T1(str_encrypted
, R3_ENCRYPTED
, NO_ARGS
, NEED_OBJ
),
152 /** Descriptor ruleset for the encrypted section. */
153 static token_rule_t hs_desc_encrypted_v3_token_table
[] = {
154 T1_START(str_create2_formats
, R3_CREATE2_FORMATS
, CONCAT_ARGS
, NO_OBJ
),
155 T01(str_intro_auth_required
, R3_INTRO_AUTH_REQUIRED
, GE(1), NO_OBJ
),
156 T01(str_single_onion
, R3_SINGLE_ONION_SERVICE
, ARGS
, NO_OBJ
),
157 T01(str_flow_control
, R3_FLOW_CONTROL
, GE(2), NO_OBJ
),
158 T01(str_pow_params
, R3_POW_PARAMS
, GE(4), NO_OBJ
),
162 /** Descriptor ruleset for the introduction points section. */
163 static token_rule_t hs_desc_intro_point_v3_token_table
[] = {
164 T1_START(str_intro_point
, R3_INTRODUCTION_POINT
, EQ(1), NO_OBJ
),
165 T1N(str_ip_onion_key
, R3_INTRO_ONION_KEY
, GE(2), OBJ_OK
),
166 T1(str_ip_auth_key
, R3_INTRO_AUTH_KEY
, NO_ARGS
, NEED_OBJ
),
167 T1(str_ip_enc_key
, R3_INTRO_ENC_KEY
, GE(2), OBJ_OK
),
168 T1(str_ip_enc_key_cert
, R3_INTRO_ENC_KEY_CERT
, ARGS
, OBJ_OK
),
169 T01(str_ip_legacy_key
, R3_INTRO_LEGACY_KEY
, ARGS
, NEED_KEY_1024
),
170 T01(str_ip_legacy_key_cert
, R3_INTRO_LEGACY_KEY_CERT
, ARGS
, OBJ_OK
),
174 /** Using a key, salt and encrypted payload, build a MAC and put it in mac_out.
175 * We use SHA3-256 for the MAC computation.
176 * This function can't fail. */
178 build_mac(const uint8_t *mac_key
, size_t mac_key_len
,
179 const uint8_t *salt
, size_t salt_len
,
180 const uint8_t *encrypted
, size_t encrypted_len
,
181 uint8_t *mac_out
, size_t mac_len
)
183 crypto_digest_t
*digest
;
185 const uint64_t mac_len_netorder
= tor_htonll(mac_key_len
);
186 const uint64_t salt_len_netorder
= tor_htonll(salt_len
);
190 tor_assert(encrypted
);
193 digest
= crypto_digest256_new(DIGEST_SHA3_256
);
194 /* As specified in section 2.5 of proposal 224, first add the mac key
195 * then add the salt first and then the encrypted section. */
197 crypto_digest_add_bytes(digest
, (const char *) &mac_len_netorder
, 8);
198 crypto_digest_add_bytes(digest
, (const char *) mac_key
, mac_key_len
);
199 crypto_digest_add_bytes(digest
, (const char *) &salt_len_netorder
, 8);
200 crypto_digest_add_bytes(digest
, (const char *) salt
, salt_len
);
201 crypto_digest_add_bytes(digest
, (const char *) encrypted
, encrypted_len
);
202 crypto_digest_get_digest(digest
, (char *) mac_out
, mac_len
);
203 crypto_digest_free(digest
);
206 /** Using a secret data and a given descriptor object, build the secret
207 * input needed for the KDF.
209 * secret_input = SECRET_DATA | subcredential | INT_8(revision_counter)
211 * Then, set the newly allocated buffer in secret_input_out and return the
212 * length of the buffer. */
214 build_secret_input(const hs_descriptor_t
*desc
,
215 const uint8_t *secret_data
,
216 size_t secret_data_len
,
217 uint8_t **secret_input_out
)
220 size_t secret_input_len
= secret_data_len
+ DIGEST256_LEN
+ sizeof(uint64_t);
221 uint8_t *secret_input
= NULL
;
224 tor_assert(secret_data
);
225 tor_assert(secret_input_out
);
227 secret_input
= tor_malloc_zero(secret_input_len
);
229 /* Copy the secret data. */
230 memcpy(secret_input
, secret_data
, secret_data_len
);
231 offset
+= secret_data_len
;
232 /* Copy subcredential. */
233 memcpy(secret_input
+ offset
, desc
->subcredential
.subcred
, DIGEST256_LEN
);
234 offset
+= DIGEST256_LEN
;
235 /* Copy revision counter value. */
236 set_uint64(secret_input
+ offset
,
237 tor_htonll(desc
->plaintext_data
.revision_counter
));
238 offset
+= sizeof(uint64_t);
239 tor_assert(secret_input_len
== offset
);
241 *secret_input_out
= secret_input
;
243 return secret_input_len
;
246 /** Do the KDF construction and put the resulting data in key_out which is of
247 * key_out_len length. It uses SHAKE-256 as specified in the spec. */
249 build_kdf_key(const hs_descriptor_t
*desc
,
250 const uint8_t *secret_data
,
251 size_t secret_data_len
,
252 const uint8_t *salt
, size_t salt_len
,
253 uint8_t *key_out
, size_t key_out_len
,
254 int is_superencrypted_layer
)
256 uint8_t *secret_input
= NULL
;
257 size_t secret_input_len
;
261 tor_assert(secret_data
);
265 /* Build the secret input for the KDF computation. */
266 secret_input_len
= build_secret_input(desc
, secret_data
,
267 secret_data_len
, &secret_input
);
269 xof
= crypto_xof_new();
270 /* Feed our KDF. [SHAKE it like a polaroid picture --Yawning]. */
271 crypto_xof_add_bytes(xof
, secret_input
, secret_input_len
);
272 crypto_xof_add_bytes(xof
, salt
, salt_len
);
274 /* Feed in the right string constant based on the desc layer */
275 if (is_superencrypted_layer
) {
276 crypto_xof_add_bytes(xof
, (const uint8_t *) str_enc_const_superencryption
,
277 strlen(str_enc_const_superencryption
));
279 crypto_xof_add_bytes(xof
, (const uint8_t *) str_enc_const_encryption
,
280 strlen(str_enc_const_encryption
));
283 /* Eat from our KDF. */
284 crypto_xof_squeeze_bytes(xof
, key_out
, key_out_len
);
285 crypto_xof_free(xof
);
286 memwipe(secret_input
, 0, secret_input_len
);
288 tor_free(secret_input
);
291 /** Using the given descriptor, secret data, and salt, run it through our
292 * KDF function and then extract a secret key in key_out, the IV in iv_out
293 * and MAC in mac_out. This function can't fail. */
295 build_secret_key_iv_mac(const hs_descriptor_t
*desc
,
296 const uint8_t *secret_data
,
297 size_t secret_data_len
,
298 const uint8_t *salt
, size_t salt_len
,
299 uint8_t *key_out
, size_t key_len
,
300 uint8_t *iv_out
, size_t iv_len
,
301 uint8_t *mac_out
, size_t mac_len
,
302 int is_superencrypted_layer
)
305 uint8_t kdf_key
[HS_DESC_ENCRYPTED_KDF_OUTPUT_LEN
];
308 tor_assert(secret_data
);
314 build_kdf_key(desc
, secret_data
, secret_data_len
,
315 salt
, salt_len
, kdf_key
, sizeof(kdf_key
),
316 is_superencrypted_layer
);
317 /* Copy the bytes we need for both the secret key and IV. */
318 memcpy(key_out
, kdf_key
, key_len
);
320 memcpy(iv_out
, kdf_key
+ offset
, iv_len
);
322 memcpy(mac_out
, kdf_key
+ offset
, mac_len
);
323 /* Extra precaution to make sure we are not out of bound. */
324 tor_assert((offset
+ mac_len
) == sizeof(kdf_key
));
325 memwipe(kdf_key
, 0, sizeof(kdf_key
));
328 /* === ENCODING === */
330 /** Encode the given link specifier objects into a newly allocated string.
331 * This can't fail so caller can always assume a valid string being
334 encode_link_specifiers(const smartlist_t
*specs
)
336 char *encoded_b64
= NULL
;
337 link_specifier_list_t
*lslist
= link_specifier_list_new();
340 /* No link specifiers is a code flow error, can't happen. */
341 tor_assert(smartlist_len(specs
) > 0);
342 tor_assert(smartlist_len(specs
) <= UINT8_MAX
);
344 link_specifier_list_set_n_spec(lslist
, smartlist_len(specs
));
346 SMARTLIST_FOREACH_BEGIN(specs
, const link_specifier_t
*,
348 link_specifier_t
*ls
= link_specifier_dup(spec
);
350 link_specifier_list_add_spec(lslist
, ls
);
351 } SMARTLIST_FOREACH_END(spec
);
355 ssize_t encoded_len
, encoded_b64_len
, ret
;
357 encoded_len
= link_specifier_list_encoded_len(lslist
);
358 tor_assert(encoded_len
> 0);
359 encoded
= tor_malloc_zero(encoded_len
);
360 ret
= link_specifier_list_encode(encoded
, encoded_len
, lslist
);
361 tor_assert(ret
== encoded_len
);
363 /* Base64 encode our binary format. Add extra NUL byte for the base64
365 encoded_b64_len
= base64_encode_size(encoded_len
, 0) + 1;
366 encoded_b64
= tor_malloc_zero(encoded_b64_len
);
367 ret
= base64_encode(encoded_b64
, encoded_b64_len
, (const char *) encoded
,
369 tor_assert(ret
== (encoded_b64_len
- 1));
373 link_specifier_list_free(lslist
);
377 /** Encode an introduction point legacy key and certificate. Return a newly
378 * allocated string with it. On failure, return NULL. */
380 encode_legacy_key(const hs_desc_intro_point_t
*ip
)
382 char *key_str
, b64_cert
[256], *encoded
= NULL
;
387 /* Encode cross cert. */
388 if (base64_encode(b64_cert
, sizeof(b64_cert
),
389 (const char *) ip
->legacy
.cert
.encoded
,
390 ip
->legacy
.cert
.len
, BASE64_ENCODE_MULTILINE
) < 0) {
391 log_warn(LD_REND
, "Unable to encode legacy crosscert.");
394 /* Convert the encryption key to PEM format NUL terminated. */
395 if (crypto_pk_write_public_key_to_string(ip
->legacy
.key
, &key_str
,
397 log_warn(LD_REND
, "Unable to encode legacy encryption key.");
400 tor_asprintf(&encoded
,
401 "%s \n%s" /* Newline is added by the call above. */
403 "-----BEGIN CROSSCERT-----\n"
405 "-----END CROSSCERT-----",
406 str_ip_legacy_key
, key_str
,
407 str_ip_legacy_key_cert
, b64_cert
);
414 /** Encode an introduction point encryption key and certificate. Return a newly
415 * allocated string with it. On failure, return NULL. */
417 encode_enc_key(const hs_desc_intro_point_t
*ip
)
419 char *encoded
= NULL
, *encoded_cert
;
420 char key_b64
[CURVE25519_BASE64_PADDED_LEN
+ 1];
424 /* Base64 encode the encryption key for the "enc-key" field. */
425 curve25519_public_to_base64(key_b64
, &ip
->enc_key
, true);
426 if (tor_cert_encode_ed22519(ip
->enc_key_cert
, &encoded_cert
) < 0) {
429 tor_asprintf(&encoded
,
432 str_ip_enc_key
, key_b64
,
433 str_ip_enc_key_cert
, encoded_cert
);
434 tor_free(encoded_cert
);
440 /** Encode an introduction point onion key. Return a newly allocated string
441 * with it. Can not fail. */
443 encode_onion_key(const hs_desc_intro_point_t
*ip
)
445 char *encoded
= NULL
;
446 char key_b64
[CURVE25519_BASE64_PADDED_LEN
+ 1];
450 /* Base64 encode the encryption key for the "onion-key" field. */
451 curve25519_public_to_base64(key_b64
, &ip
->onion_key
, true);
452 tor_asprintf(&encoded
, "%s ntor %s", str_ip_onion_key
, key_b64
);
457 /** Encode an introduction point object and return a newly allocated string
458 * with it. On failure, return NULL. */
460 encode_intro_point(const ed25519_public_key_t
*sig_key
,
461 const hs_desc_intro_point_t
*ip
)
463 char *encoded_ip
= NULL
;
464 smartlist_t
*lines
= smartlist_new();
469 /* Encode link specifier. */
471 char *ls_str
= encode_link_specifiers(ip
->link_specifiers
);
472 smartlist_add_asprintf(lines
, "%s %s", str_intro_point
, ls_str
);
476 /* Onion key encoding. */
478 char *encoded_onion_key
= encode_onion_key(ip
);
479 if (encoded_onion_key
== NULL
) {
482 smartlist_add_asprintf(lines
, "%s", encoded_onion_key
);
483 tor_free(encoded_onion_key
);
486 /* Authentication key encoding. */
489 if (tor_cert_encode_ed22519(ip
->auth_key_cert
, &encoded_cert
) < 0) {
492 smartlist_add_asprintf(lines
, "%s\n%s", str_ip_auth_key
, encoded_cert
);
493 tor_free(encoded_cert
);
496 /* Encryption key encoding. */
498 char *encoded_enc_key
= encode_enc_key(ip
);
499 if (encoded_enc_key
== NULL
) {
502 smartlist_add_asprintf(lines
, "%s", encoded_enc_key
);
503 tor_free(encoded_enc_key
);
506 /* Legacy key if any. */
507 if (ip
->legacy
.key
!= NULL
) {
508 /* Strong requirement else the IP creation was badly done. */
509 tor_assert(ip
->legacy
.cert
.encoded
);
510 char *encoded_legacy_key
= encode_legacy_key(ip
);
511 if (encoded_legacy_key
== NULL
) {
514 smartlist_add_asprintf(lines
, "%s", encoded_legacy_key
);
515 tor_free(encoded_legacy_key
);
518 /* Join them all in one blob of text. */
519 encoded_ip
= smartlist_join_strings(lines
, "\n", 1, NULL
);
522 SMARTLIST_FOREACH(lines
, char *, l
, tor_free(l
));
523 smartlist_free(lines
);
527 /** Given a source length, return the new size including padding for the
528 * plaintext encryption. */
530 compute_padded_plaintext_length(size_t plaintext_len
)
532 size_t plaintext_padded_len
;
533 const int padding_block_length
= HS_DESC_SUPERENC_PLAINTEXT_PAD_MULTIPLE
;
535 /* Make sure we won't overflow. */
536 tor_assert(plaintext_len
<= (SIZE_T_CEILING
- padding_block_length
));
538 /* Get the extra length we need to add. For example, if srclen is 10200
539 * bytes, this will expand to (2 * 10k) == 20k thus an extra 9800 bytes. */
540 plaintext_padded_len
= CEIL_DIV(plaintext_len
, padding_block_length
) *
541 padding_block_length
;
542 /* Can never be extra careful. Make sure we are _really_ padded. */
543 tor_assert(!(plaintext_padded_len
% padding_block_length
));
544 return plaintext_padded_len
;
547 /** Given a buffer, pad it up to the encrypted section padding requirement. Set
548 * the newly allocated string in padded_out and return the length of the
551 build_plaintext_padding(const char *plaintext
, size_t plaintext_len
,
552 uint8_t **padded_out
)
557 tor_assert(plaintext
);
558 tor_assert(padded_out
);
560 /* Allocate the final length including padding. */
561 padded_len
= compute_padded_plaintext_length(plaintext_len
);
562 tor_assert(padded_len
>= plaintext_len
);
563 padded
= tor_malloc_zero(padded_len
);
565 memcpy(padded
, plaintext
, plaintext_len
);
566 *padded_out
= padded
;
570 /** Using a key, IV and plaintext data of length plaintext_len, create the
571 * encrypted section by encrypting it and setting encrypted_out with the
572 * data. Return size of the encrypted data buffer. */
574 build_encrypted(const uint8_t *key
, const uint8_t *iv
, const char *plaintext
,
575 size_t plaintext_len
, uint8_t **encrypted_out
,
576 int is_superencrypted_layer
)
578 size_t encrypted_len
;
579 uint8_t *padded_plaintext
, *encrypted
;
580 crypto_cipher_t
*cipher
;
584 tor_assert(plaintext
);
585 tor_assert(encrypted_out
);
587 /* If we are encrypting the middle layer of the descriptor, we need to first
589 if (is_superencrypted_layer
) {
590 encrypted_len
= build_plaintext_padding(plaintext
, plaintext_len
,
592 /* Extra precautions that we have a valid padding length. */
593 tor_assert(!(encrypted_len
% HS_DESC_SUPERENC_PLAINTEXT_PAD_MULTIPLE
));
594 } else { /* No padding required for inner layers */
595 padded_plaintext
= tor_memdup(plaintext
, plaintext_len
);
596 encrypted_len
= plaintext_len
;
599 /* This creates a cipher for AES. It can't fail. */
600 cipher
= crypto_cipher_new_with_iv_and_bits(key
, iv
,
601 HS_DESC_ENCRYPTED_BIT_SIZE
);
602 /* We use a stream cipher so the encrypted length will be the same as the
603 * plaintext padded length. */
604 encrypted
= tor_malloc_zero(encrypted_len
);
605 /* This can't fail. */
606 crypto_cipher_encrypt(cipher
, (char *) encrypted
,
607 (const char *) padded_plaintext
, encrypted_len
);
608 *encrypted_out
= encrypted
;
610 crypto_cipher_free(cipher
);
611 tor_free(padded_plaintext
);
612 return encrypted_len
;
615 /** Encrypt the given <b>plaintext</b> buffer using <b>desc</b> and
616 * <b>secret_data</b> to get the keys. Set encrypted_out with the encrypted
617 * data and return the length of it. <b>is_superencrypted_layer</b> is set
618 * if this is the outer encrypted layer of the descriptor. */
620 encrypt_descriptor_data(const hs_descriptor_t
*desc
,
621 const uint8_t *secret_data
,
622 size_t secret_data_len
,
623 const char *plaintext
,
624 char **encrypted_out
, int is_superencrypted_layer
)
627 size_t encrypted_len
, final_blob_len
, offset
= 0;
629 uint8_t salt
[HS_DESC_ENCRYPTED_SALT_LEN
];
630 uint8_t secret_key
[HS_DESC_ENCRYPTED_KEY_LEN
], secret_iv
[CIPHER_IV_LEN
];
631 uint8_t mac_key
[DIGEST256_LEN
], mac
[DIGEST256_LEN
];
634 tor_assert(secret_data
);
635 tor_assert(plaintext
);
636 tor_assert(encrypted_out
);
638 /* Get our salt. The returned bytes are already hashed. */
639 crypto_strongest_rand(salt
, sizeof(salt
));
641 /* KDF construction resulting in a key from which the secret key, IV and MAC
642 * key are extracted which is what we need for the encryption. */
643 build_secret_key_iv_mac(desc
, secret_data
, secret_data_len
,
645 secret_key
, sizeof(secret_key
),
646 secret_iv
, sizeof(secret_iv
),
647 mac_key
, sizeof(mac_key
),
648 is_superencrypted_layer
);
650 /* Build the encrypted part that is do the actual encryption. */
651 encrypted_len
= build_encrypted(secret_key
, secret_iv
, plaintext
,
652 strlen(plaintext
), &encrypted
,
653 is_superencrypted_layer
);
654 memwipe(secret_key
, 0, sizeof(secret_key
));
655 memwipe(secret_iv
, 0, sizeof(secret_iv
));
656 /* This construction is specified in section 2.5 of proposal 224. */
657 final_blob_len
= sizeof(salt
) + encrypted_len
+ DIGEST256_LEN
;
658 final_blob
= tor_malloc_zero(final_blob_len
);
661 build_mac(mac_key
, sizeof(mac_key
), salt
, sizeof(salt
),
662 encrypted
, encrypted_len
, mac
, sizeof(mac
));
663 memwipe(mac_key
, 0, sizeof(mac_key
));
665 /* The salt is the first value. */
666 memcpy(final_blob
, salt
, sizeof(salt
));
667 offset
= sizeof(salt
);
668 /* Second value is the encrypted data. */
669 memcpy(final_blob
+ offset
, encrypted
, encrypted_len
);
670 offset
+= encrypted_len
;
671 /* Third value is the MAC. */
672 memcpy(final_blob
+ offset
, mac
, sizeof(mac
));
673 offset
+= sizeof(mac
);
674 /* Cleanup the buffers. */
675 memwipe(salt
, 0, sizeof(salt
));
676 memwipe(encrypted
, 0, encrypted_len
);
678 /* Extra precaution. */
679 tor_assert(offset
== final_blob_len
);
681 *encrypted_out
= final_blob
;
682 return final_blob_len
;
685 /** Create and return a string containing a client-auth entry. It's the
686 * responsibility of the caller to free the returned string. This function
687 * will never fail. */
689 get_auth_client_str(const hs_desc_authorized_client_t
*client
)
692 char *auth_client_str
= NULL
;
693 /* We are gonna fill these arrays with base64 data. They are all double
694 * the size of their binary representation to fit the base64 overhead. */
695 char client_id_b64
[HS_DESC_CLIENT_ID_LEN
* 2];
696 char iv_b64
[CIPHER_IV_LEN
* 2];
697 char encrypted_cookie_b64
[HS_DESC_ENCRYPED_COOKIE_LEN
* 2];
699 #define ASSERT_AND_BASE64(field) STMT_BEGIN \
700 tor_assert(!fast_mem_is_zero((char *) client->field, \
701 sizeof(client->field))); \
702 ret = base64_encode_nopad(field##_b64, sizeof(field##_b64), \
703 client->field, sizeof(client->field)); \
704 tor_assert(ret > 0); \
707 ASSERT_AND_BASE64(client_id
);
708 ASSERT_AND_BASE64(iv
);
709 ASSERT_AND_BASE64(encrypted_cookie
);
711 /* Build the final string */
712 tor_asprintf(&auth_client_str
, "%s %s %s %s", str_desc_auth_client
,
713 client_id_b64
, iv_b64
, encrypted_cookie_b64
);
715 #undef ASSERT_AND_BASE64
717 return auth_client_str
;
720 /** Create the "client-auth" part of the descriptor and return a
721 * newly-allocated string with it. It's the responsibility of the caller to
722 * free the returned string. */
724 get_all_auth_client_lines(const hs_descriptor_t
*desc
)
726 smartlist_t
*auth_client_lines
= smartlist_new();
727 char *auth_client_lines_str
= NULL
;
730 tor_assert(desc
->superencrypted_data
.clients
);
731 tor_assert(smartlist_len(desc
->superencrypted_data
.clients
) != 0);
732 tor_assert(smartlist_len(desc
->superencrypted_data
.clients
)
733 % HS_DESC_AUTH_CLIENT_MULTIPLE
== 0);
735 /* Make a line for each client */
736 SMARTLIST_FOREACH_BEGIN(desc
->superencrypted_data
.clients
,
737 const hs_desc_authorized_client_t
*, client
) {
738 char *auth_client_str
= NULL
;
740 auth_client_str
= get_auth_client_str(client
);
742 smartlist_add(auth_client_lines
, auth_client_str
);
743 } SMARTLIST_FOREACH_END(client
);
745 /* Join all lines together to form final string */
746 auth_client_lines_str
= smartlist_join_strings(auth_client_lines
,
748 /* Cleanup the mess */
749 SMARTLIST_FOREACH(auth_client_lines
, char *, a
, tor_free(a
));
750 smartlist_free(auth_client_lines
);
752 return auth_client_lines_str
;
755 /** Create the inner layer of the descriptor (which includes the intro points,
756 * etc.). Return a newly-allocated string with the layer plaintext, or NULL if
757 * an error occurred. It's the responsibility of the caller to free the
758 * returned string. */
760 get_inner_encrypted_layer_plaintext(const hs_descriptor_t
*desc
)
762 char *encoded_str
= NULL
;
763 smartlist_t
*lines
= smartlist_new();
765 /* Build the start of the section prior to the introduction points. */
767 if (!desc
->encrypted_data
.create2_ntor
) {
768 log_err(LD_BUG
, "HS desc doesn't have recognized handshake type.");
771 smartlist_add_asprintf(lines
, "%s %d\n", str_create2_formats
,
772 ONION_HANDSHAKE_TYPE_NTOR
);
774 #ifdef TOR_UNIT_TESTS
775 if (desc
->encrypted_data
.test_extra_plaintext
) {
777 tor_strdup(desc
->encrypted_data
.test_extra_plaintext
));
781 if (desc
->encrypted_data
.intro_auth_types
&&
782 smartlist_len(desc
->encrypted_data
.intro_auth_types
)) {
783 /* Put the authentication-required line. */
784 char *buf
= smartlist_join_strings(desc
->encrypted_data
.intro_auth_types
,
786 smartlist_add_asprintf(lines
, "%s %s\n", str_intro_auth_required
, buf
);
790 if (desc
->encrypted_data
.single_onion_service
) {
791 smartlist_add_asprintf(lines
, "%s\n", str_single_onion
);
794 if (congestion_control_enabled()) {
795 /* Add flow control line into the descriptor. */
796 smartlist_add_asprintf(lines
, "%s %s %u\n", str_flow_control
,
797 protover_get_supported(PRT_FLOWCTRL
),
798 congestion_control_sendme_inc());
801 /* Add PoW parameters if present. */
802 if (desc
->encrypted_data
.pow_params
) {
803 /* Base64 the seed */
804 size_t seed_b64_len
= base64_encode_size(HS_POW_SEED_LEN
, 0) + 1;
805 char *seed_b64
= tor_malloc_zero(seed_b64_len
);
806 int ret
= base64_encode(seed_b64
, seed_b64_len
,
807 (char *)desc
->encrypted_data
.pow_params
->seed
,
809 /* Return length doesn't count the NUL byte. */
810 tor_assert((size_t) ret
== (seed_b64_len
- 1));
812 /* Convert the expiration time to space-less ISO format. */
813 char time_buf
[ISO_TIME_LEN
+ 1];
814 format_iso_time_nospace(time_buf
,
815 desc
->encrypted_data
.pow_params
->expiration_time
);
817 /* Add "pow-params" line to descriptor encoding. */
818 smartlist_add_asprintf(lines
, "%s %s %s %u %s\n", str_pow_params
,
819 pow_types
[desc
->encrypted_data
.pow_params
->type
].identifier
,
821 desc
->encrypted_data
.pow_params
->suggested_effort
,
827 /* Build the introduction point(s) section. */
828 SMARTLIST_FOREACH_BEGIN(desc
->encrypted_data
.intro_points
,
829 const hs_desc_intro_point_t
*, ip
) {
830 char *encoded_ip
= encode_intro_point(&desc
->plaintext_data
.signing_pubkey
,
832 if (encoded_ip
== NULL
) {
833 log_err(LD_BUG
, "HS desc intro point is malformed.");
836 smartlist_add(lines
, encoded_ip
);
837 } SMARTLIST_FOREACH_END(ip
);
839 /* Build the entire encrypted data section into one encoded plaintext and
840 * then encrypt it. */
841 encoded_str
= smartlist_join_strings(lines
, "", 0, NULL
);
844 SMARTLIST_FOREACH(lines
, char *, l
, tor_free(l
));
845 smartlist_free(lines
);
850 /** Create the middle layer of the descriptor, which includes the client auth
851 * data and the encrypted inner layer (provided as a base64 string at
852 * <b>layer2_b64_ciphertext</b>). Return a newly-allocated string with the
853 * layer plaintext. It's the responsibility of the caller to free the returned
854 * string. Can not fail. */
856 get_outer_encrypted_layer_plaintext(const hs_descriptor_t
*desc
,
857 const char *layer2_b64_ciphertext
)
859 char *layer1_str
= NULL
;
860 smartlist_t
*lines
= smartlist_new();
862 /* Specify auth type */
863 smartlist_add_asprintf(lines
, "%s %s\n", str_desc_auth_type
, "x25519");
865 { /* Print ephemeral x25519 key */
866 char ephemeral_key_base64
[CURVE25519_BASE64_PADDED_LEN
+ 1];
867 const curve25519_public_key_t
*ephemeral_pubkey
;
869 ephemeral_pubkey
= &desc
->superencrypted_data
.auth_ephemeral_pubkey
;
870 tor_assert(!fast_mem_is_zero((char *) ephemeral_pubkey
->public_key
,
871 CURVE25519_PUBKEY_LEN
));
873 curve25519_public_to_base64(ephemeral_key_base64
, ephemeral_pubkey
, true);
874 smartlist_add_asprintf(lines
, "%s %s\n",
875 str_desc_auth_key
, ephemeral_key_base64
);
877 memwipe(ephemeral_key_base64
, 0, sizeof(ephemeral_key_base64
));
880 { /* Create auth-client lines. */
881 char *auth_client_lines
= get_all_auth_client_lines(desc
);
882 tor_assert(auth_client_lines
);
883 smartlist_add(lines
, auth_client_lines
);
886 /* create encrypted section */
888 smartlist_add_asprintf(lines
,
890 "-----BEGIN MESSAGE-----\n"
892 "-----END MESSAGE-----",
893 str_encrypted
, layer2_b64_ciphertext
);
896 layer1_str
= smartlist_join_strings(lines
, "", 0, NULL
);
898 /* We need to memwipe all lines because it contains the ephemeral key */
899 SMARTLIST_FOREACH(lines
, char *, a
, memwipe(a
, 0, strlen(a
)));
900 SMARTLIST_FOREACH(lines
, char *, a
, tor_free(a
));
901 smartlist_free(lines
);
906 /** Encrypt <b>encoded_str</b> into an encrypted blob and then base64 it before
907 * returning it. <b>desc</b> is provided to derive the encryption
908 * keys. <b>secret_data</b> is also proved to derive the encryption keys.
909 * <b>is_superencrypted_layer</b> is set if <b>encoded_str</b> is the
910 * middle (superencrypted) layer of the descriptor. It's the responsibility of
911 * the caller to free the returned string. */
913 encrypt_desc_data_and_base64(const hs_descriptor_t
*desc
,
914 const uint8_t *secret_data
,
915 size_t secret_data_len
,
916 const char *encoded_str
,
917 int is_superencrypted_layer
)
920 ssize_t enc_b64_len
, ret_len
, enc_len
;
921 char *encrypted_blob
= NULL
;
923 enc_len
= encrypt_descriptor_data(desc
, secret_data
, secret_data_len
,
924 encoded_str
, &encrypted_blob
,
925 is_superencrypted_layer
);
926 /* Get the encoded size plus a NUL terminating byte. */
927 enc_b64_len
= base64_encode_size(enc_len
, BASE64_ENCODE_MULTILINE
) + 1;
928 enc_b64
= tor_malloc_zero(enc_b64_len
);
929 /* Base64 the encrypted blob before returning it. */
930 ret_len
= base64_encode(enc_b64
, enc_b64_len
, encrypted_blob
, enc_len
,
931 BASE64_ENCODE_MULTILINE
);
932 /* Return length doesn't count the NUL byte. */
933 tor_assert(ret_len
== (enc_b64_len
- 1));
934 tor_free(encrypted_blob
);
939 /** Generate the secret data which is used to encrypt/decrypt the descriptor.
941 * SECRET_DATA = blinded-public-key
942 * SECRET_DATA = blinded-public-key | descriptor_cookie
944 * The descriptor_cookie is optional but if it exists, it must be at least
945 * HS_DESC_DESCRIPTOR_COOKIE_LEN bytes long.
947 * A newly allocated secret data is put in secret_data_out. Return the
948 * length of the secret data. This function cannot fail. */
950 build_secret_data(const ed25519_public_key_t
*blinded_pubkey
,
951 const uint8_t *descriptor_cookie
,
952 uint8_t **secret_data_out
)
954 size_t secret_data_len
;
955 uint8_t *secret_data
;
957 tor_assert(blinded_pubkey
);
958 tor_assert(secret_data_out
);
960 if (descriptor_cookie
) {
961 /* If the descriptor cookie is present, we need both the blinded
962 * pubkey and the descriptor cookie as a secret data. */
963 secret_data_len
= ED25519_PUBKEY_LEN
+ HS_DESC_DESCRIPTOR_COOKIE_LEN
;
964 secret_data
= tor_malloc(secret_data_len
);
967 blinded_pubkey
->pubkey
,
969 memcpy(secret_data
+ ED25519_PUBKEY_LEN
,
971 HS_DESC_DESCRIPTOR_COOKIE_LEN
);
973 /* If the descriptor cookie is not present, we need only the blinded
974 * pubkey as a secret data. */
975 secret_data_len
= ED25519_PUBKEY_LEN
;
976 secret_data
= tor_malloc(secret_data_len
);
978 blinded_pubkey
->pubkey
,
982 *secret_data_out
= secret_data
;
983 return secret_data_len
;
986 /** Generate and encode the superencrypted portion of <b>desc</b>. This also
987 * involves generating the encrypted portion of the descriptor, and performing
988 * the superencryption. A newly allocated NUL-terminated string pointer
989 * containing the encrypted encoded blob is put in encrypted_blob_out. Return 0
990 * on success else a negative value. */
992 encode_superencrypted_data(const hs_descriptor_t
*desc
,
993 const uint8_t *descriptor_cookie
,
994 char **encrypted_blob_out
)
997 uint8_t *secret_data
= NULL
;
998 size_t secret_data_len
= 0;
999 char *layer2_str
= NULL
;
1000 char *layer2_b64_ciphertext
= NULL
;
1001 char *layer1_str
= NULL
;
1002 char *layer1_b64_ciphertext
= NULL
;
1005 tor_assert(encrypted_blob_out
);
1007 /* Func logic: We first create the inner layer of the descriptor (layer2).
1008 * We then encrypt it and use it to create the middle layer of the descriptor
1009 * (layer1). Finally we superencrypt the middle layer and return it to our
1012 /* Create inner descriptor layer */
1013 layer2_str
= get_inner_encrypted_layer_plaintext(desc
);
1018 secret_data_len
= build_secret_data(&desc
->plaintext_data
.blinded_pubkey
,
1022 /* Encrypt and b64 the inner layer */
1023 layer2_b64_ciphertext
=
1024 encrypt_desc_data_and_base64(desc
, secret_data
, secret_data_len
,
1026 if (!layer2_b64_ciphertext
) {
1030 /* Now create middle descriptor layer given the inner layer */
1031 layer1_str
= get_outer_encrypted_layer_plaintext(desc
,layer2_b64_ciphertext
);
1036 /* Encrypt and base64 the middle layer */
1037 layer1_b64_ciphertext
=
1038 encrypt_desc_data_and_base64(desc
,
1039 desc
->plaintext_data
.blinded_pubkey
.pubkey
,
1042 if (!layer1_b64_ciphertext
) {
1050 memwipe(secret_data
, 0, secret_data_len
);
1051 tor_free(secret_data
);
1052 tor_free(layer1_str
);
1053 tor_free(layer2_str
);
1054 tor_free(layer2_b64_ciphertext
);
1056 *encrypted_blob_out
= layer1_b64_ciphertext
;
1060 /** Encode a v3 HS descriptor. Return 0 on success and set encoded_out to the
1061 * newly allocated string of the encoded descriptor. On error, -1 is returned
1062 * and encoded_out is untouched. */
1064 desc_encode_v3(const hs_descriptor_t
*desc
,
1065 const ed25519_keypair_t
*signing_kp
,
1066 const uint8_t *descriptor_cookie
,
1070 char *encoded_str
= NULL
;
1072 smartlist_t
*lines
= smartlist_new();
1075 tor_assert(signing_kp
);
1076 tor_assert(encoded_out
);
1077 tor_assert(desc
->plaintext_data
.version
== 3);
1079 /* Build the non-encrypted values. */
1082 /* Encode certificate then create the first line of the descriptor. */
1083 if (desc
->plaintext_data
.signing_key_cert
->cert_type
1084 != CERT_TYPE_SIGNING_HS_DESC
) {
1085 log_err(LD_BUG
, "HS descriptor signing key has an unexpected cert type "
1086 "(%d)", (int) desc
->plaintext_data
.signing_key_cert
->cert_type
);
1089 if (tor_cert_encode_ed22519(desc
->plaintext_data
.signing_key_cert
,
1090 &encoded_cert
) < 0) {
1091 /* The function will print error logs. */
1094 /* Create the hs descriptor line. */
1095 smartlist_add_asprintf(lines
, "%s %" PRIu32
, str_hs_desc
,
1096 desc
->plaintext_data
.version
);
1097 /* Add the descriptor lifetime line (in minutes). */
1098 smartlist_add_asprintf(lines
, "%s %" PRIu32
, str_lifetime
,
1099 desc
->plaintext_data
.lifetime_sec
/ 60);
1100 /* Create the descriptor certificate line. */
1101 smartlist_add_asprintf(lines
, "%s\n%s", str_desc_cert
, encoded_cert
);
1102 tor_free(encoded_cert
);
1103 /* Create the revision counter line. */
1104 smartlist_add_asprintf(lines
, "%s %" PRIu64
, str_rev_counter
,
1105 desc
->plaintext_data
.revision_counter
);
1108 /* Build the superencrypted data section. */
1110 char *enc_b64_blob
=NULL
;
1111 if (encode_superencrypted_data(desc
, descriptor_cookie
,
1112 &enc_b64_blob
) < 0) {
1115 smartlist_add_asprintf(lines
,
1117 "-----BEGIN MESSAGE-----\n"
1119 "-----END MESSAGE-----",
1120 str_superencrypted
, enc_b64_blob
);
1121 tor_free(enc_b64_blob
);
1124 /* Join all lines in one string so we can generate a signature and append
1125 * it to the descriptor. */
1126 encoded_str
= smartlist_join_strings(lines
, "\n", 1, &encoded_len
);
1128 /* Sign all fields of the descriptor with our short term signing key. */
1130 ed25519_signature_t sig
;
1131 char ed_sig_b64
[ED25519_SIG_BASE64_LEN
+ 1];
1132 if (ed25519_sign_prefixed(&sig
,
1133 (const uint8_t *) encoded_str
, encoded_len
,
1134 str_desc_sig_prefix
, signing_kp
) < 0) {
1135 log_warn(LD_BUG
, "Can't sign encoded HS descriptor!");
1136 tor_free(encoded_str
);
1139 ed25519_signature_to_base64(ed_sig_b64
, &sig
);
1140 /* Create the signature line. */
1141 smartlist_add_asprintf(lines
, "%s %s", str_signature
, ed_sig_b64
);
1143 /* Free previous string that we used so compute the signature. */
1144 tor_free(encoded_str
);
1145 encoded_str
= smartlist_join_strings(lines
, "\n", 1, NULL
);
1146 *encoded_out
= encoded_str
;
1148 if (strlen(encoded_str
) >= hs_cache_get_max_descriptor_size()) {
1149 log_warn(LD_GENERAL
, "We just made an HS descriptor that's too big (%d)."
1150 "Failing.", (int)strlen(encoded_str
));
1151 tor_free(encoded_str
);
1155 /* XXX: Trigger a control port event. */
1161 SMARTLIST_FOREACH(lines
, char *, l
, tor_free(l
));
1162 smartlist_free(lines
);
1166 /* === DECODING === */
1168 /** Given the token tok for an auth client, decode it as
1169 * hs_desc_authorized_client_t. tok->args MUST contain at least 3 elements
1170 * Return 0 on success else -1 on failure. */
1172 decode_auth_client(const directory_token_t
*tok
,
1173 hs_desc_authorized_client_t
*client
)
1178 tor_assert(tok
->n_args
>= 3);
1181 if (base64_decode((char *) client
->client_id
, sizeof(client
->client_id
),
1182 tok
->args
[0], strlen(tok
->args
[0])) !=
1183 sizeof(client
->client_id
)) {
1186 if (base64_decode((char *) client
->iv
, sizeof(client
->iv
),
1187 tok
->args
[1], strlen(tok
->args
[1])) !=
1188 sizeof(client
->iv
)) {
1191 if (base64_decode((char *) client
->encrypted_cookie
,
1192 sizeof(client
->encrypted_cookie
),
1193 tok
->args
[2], strlen(tok
->args
[2])) !=
1194 sizeof(client
->encrypted_cookie
)) {
1204 /** Given an encoded string of the link specifiers, return a newly allocated
1205 * list of decoded link specifiers. Return NULL on error. */
1206 STATIC smartlist_t
*
1207 decode_link_specifiers(const char *encoded
)
1210 size_t encoded_len
, i
;
1212 smartlist_t
*results
= NULL
;
1213 link_specifier_list_t
*specs
= NULL
;
1215 tor_assert(encoded
);
1217 encoded_len
= strlen(encoded
);
1218 decoded
= tor_malloc(encoded_len
);
1219 decoded_len
= base64_decode((char *) decoded
, encoded_len
, encoded
,
1221 if (decoded_len
< 0) {
1225 if (link_specifier_list_parse(&specs
, decoded
,
1226 (size_t) decoded_len
) < decoded_len
) {
1230 results
= smartlist_new();
1232 for (i
= 0; i
< link_specifier_list_getlen_spec(specs
); i
++) {
1233 link_specifier_t
*ls
= link_specifier_list_get_spec(specs
, i
);
1237 link_specifier_t
*ls_dup
= link_specifier_dup(ls
);
1241 smartlist_add(results
, ls_dup
);
1247 SMARTLIST_FOREACH(results
, link_specifier_t
*, s
,
1248 link_specifier_free(s
));
1249 smartlist_free(results
);
1253 link_specifier_list_free(specs
);
1258 /** Given a list of authentication types, decode it and put it in the encrypted
1259 * data section. Return 1 if we at least know one of the type or 0 if we know
1262 decode_auth_type(hs_desc_encrypted_data_t
*desc
, const char *list
)
1269 desc
->intro_auth_types
= smartlist_new();
1270 smartlist_split_string(desc
->intro_auth_types
, list
, " ", 0, 0);
1272 /* Validate the types that we at least know about one. */
1273 SMARTLIST_FOREACH_BEGIN(desc
->intro_auth_types
, const char *, auth
) {
1274 for (int idx
= 0; intro_auth_types
[idx
].identifier
; idx
++) {
1275 if (!strncmp(auth
, intro_auth_types
[idx
].identifier
,
1276 strlen(intro_auth_types
[idx
].identifier
))) {
1281 } SMARTLIST_FOREACH_END(auth
);
1286 /** Parse a space-delimited list of integers representing CREATE2 formats into
1287 * the bitfield in hs_desc_encrypted_data_t. Ignore unrecognized values. */
1289 decode_create2_list(hs_desc_encrypted_data_t
*desc
, const char *list
)
1291 smartlist_t
*tokens
;
1296 tokens
= smartlist_new();
1297 smartlist_split_string(tokens
, list
, " ", 0, 0);
1299 SMARTLIST_FOREACH_BEGIN(tokens
, char *, s
) {
1301 unsigned long type
= tor_parse_ulong(s
, 10, 1, UINT16_MAX
, &ok
, NULL
);
1303 log_warn(LD_REND
, "Unparseable value %s in create2 list", escaped(s
));
1307 case ONION_HANDSHAKE_TYPE_NTOR
:
1308 desc
->create2_ntor
= 1;
1311 /* We deliberately ignore unsupported handshake types */
1314 } SMARTLIST_FOREACH_END(s
);
1316 SMARTLIST_FOREACH(tokens
, char *, s
, tor_free(s
));
1317 smartlist_free(tokens
);
1320 /** Given a certificate, validate the certificate for certain conditions which
1321 * are if the given type matches the cert's one, if the signing key is
1322 * included and if the that key was actually used to sign the certificate.
1324 * Return 1 iff if all conditions pass or 0 if one of them fails. */
1326 cert_is_valid(tor_cert_t
*cert
, uint8_t type
, const char *log_obj_type
)
1328 tor_assert(log_obj_type
);
1331 log_warn(LD_REND
, "Certificate for %s couldn't be parsed.", log_obj_type
);
1334 if (cert
->cert_type
!= type
) {
1335 log_warn(LD_REND
, "Invalid cert type %02x for %s.", cert
->cert_type
,
1339 /* All certificate must have its signing key included. */
1340 if (!cert
->signing_key_included
) {
1341 log_warn(LD_REND
, "Signing key is NOT included for %s.", log_obj_type
);
1345 /* The following will not only check if the signature matches but also the
1346 * expiration date and overall validity. */
1347 if (tor_cert_checksig(cert
, &cert
->signing_key
, approx_time()) < 0) {
1348 if (cert
->cert_expired
) {
1349 char expiration_str
[ISO_TIME_LEN
+1];
1350 format_iso_time(expiration_str
, cert
->valid_until
);
1351 log_fn(LOG_PROTOCOL_WARN
, LD_REND
, "Invalid signature for %s: %s (%s)",
1352 log_obj_type
, tor_cert_describe_signature_status(cert
),
1355 log_warn(LD_REND
, "Invalid signature for %s: %s",
1356 log_obj_type
, tor_cert_describe_signature_status(cert
));
1366 /** Given some binary data, try to parse it to get a certificate object. If we
1367 * have a valid cert, validate it using the given wanted type. On error, print
1368 * a log using the err_msg has the certificate identifier adding semantic to
1369 * the log and cert_out is set to NULL. On success, 0 is returned and cert_out
1370 * points to a newly allocated certificate object. */
1372 cert_parse_and_validate(tor_cert_t
**cert_out
, const char *data
,
1373 size_t data_len
, unsigned int cert_type_wanted
,
1374 const char *err_msg
)
1378 tor_assert(cert_out
);
1380 tor_assert(err_msg
);
1382 /* Parse certificate. */
1383 cert
= tor_cert_parse((const uint8_t *) data
, data_len
);
1385 log_warn(LD_REND
, "Certificate for %s couldn't be parsed.", err_msg
);
1389 /* Validate certificate. */
1390 if (!cert_is_valid(cert
, cert_type_wanted
, err_msg
)) {
1398 tor_cert_free(cert
);
1403 /** Return true iff the given length of the encrypted data of a descriptor
1404 * passes validation. */
1406 encrypted_data_length_is_valid(size_t len
)
1408 /* Make sure there is enough data for the salt and the mac. The equality is
1409 there to ensure that there is at least one byte of encrypted data. */
1410 if (len
<= HS_DESC_ENCRYPTED_SALT_LEN
+ DIGEST256_LEN
) {
1411 log_warn(LD_REND
, "Length of descriptor's encrypted data is too small. "
1412 "Got %lu but minimum value is %d",
1413 (unsigned long)len
, HS_DESC_ENCRYPTED_SALT_LEN
+ DIGEST256_LEN
);
1422 /** Build the KEYS component for the authorized client computation. The format
1423 * of the construction is:
1425 * SECRET_SEED = x25519(sk, pk)
1426 * KEYS = KDF(subcredential | SECRET_SEED, 40)
1428 * Set the <b>keys_out</b> argument to point to the buffer containing the KEYS,
1429 * and return the buffer's length. The caller should wipe and free its content
1430 * once done with it. This function can't fail. */
1432 build_descriptor_cookie_keys(const hs_subcredential_t
*subcredential
,
1433 const curve25519_secret_key_t
*sk
,
1434 const curve25519_public_key_t
*pk
,
1437 uint8_t secret_seed
[CURVE25519_OUTPUT_LEN
];
1439 size_t keystream_len
= HS_DESC_CLIENT_ID_LEN
+ HS_DESC_COOKIE_KEY_LEN
;
1442 tor_assert(subcredential
);
1445 tor_assert(keys_out
);
1447 keystream
= tor_malloc_zero(keystream_len
);
1449 /* Calculate x25519(sk, pk) to get the secret seed. */
1450 curve25519_handshake(secret_seed
, sk
, pk
);
1452 /* Calculate KEYS = KDF(subcredential | SECRET_SEED, 40) */
1453 xof
= crypto_xof_new();
1454 crypto_xof_add_bytes(xof
, subcredential
->subcred
, SUBCRED_LEN
);
1455 crypto_xof_add_bytes(xof
, secret_seed
, sizeof(secret_seed
));
1456 crypto_xof_squeeze_bytes(xof
, keystream
, keystream_len
);
1457 crypto_xof_free(xof
);
1459 memwipe(secret_seed
, 0, sizeof(secret_seed
));
1461 *keys_out
= keystream
;
1462 return keystream_len
;
1465 /** Decrypt the descriptor cookie given the descriptor, the auth client,
1466 * and the client secret key. On success, return 0 and a newly allocated
1467 * descriptor cookie descriptor_cookie_out. On error or if the client id
1468 * is invalid, return -1 and descriptor_cookie_out is set to
1471 decrypt_descriptor_cookie(const hs_descriptor_t
*desc
,
1472 const hs_desc_authorized_client_t
*client
,
1473 const curve25519_secret_key_t
*client_auth_sk
,
1474 uint8_t **descriptor_cookie_out
)
1477 uint8_t *keystream
= NULL
;
1478 size_t keystream_length
= 0;
1479 uint8_t *descriptor_cookie
= NULL
;
1480 const uint8_t *cookie_key
= NULL
;
1481 crypto_cipher_t
*cipher
= NULL
;
1485 tor_assert(client_auth_sk
);
1486 tor_assert(!fast_mem_is_zero(
1487 (char *) &desc
->superencrypted_data
.auth_ephemeral_pubkey
,
1488 sizeof(desc
->superencrypted_data
.auth_ephemeral_pubkey
)));
1489 tor_assert(!fast_mem_is_zero((char *) desc
->subcredential
.subcred
,
1492 /* Catch potential code-flow cases of an uninitialized private key sneaking
1493 * into this function. */
1494 if (BUG(fast_mem_is_zero((char *)client_auth_sk
, sizeof(*client_auth_sk
)))) {
1498 /* Get the KEYS component to derive the CLIENT-ID and COOKIE-KEY. */
1500 build_descriptor_cookie_keys(&desc
->subcredential
,
1502 &desc
->superencrypted_data
.auth_ephemeral_pubkey
,
1504 tor_assert(keystream_length
> 0);
1506 /* If the client id of auth client is not the same as the calculcated
1507 * client id, it means that this auth client is invalid according to the
1508 * client secret key client_auth_sk. */
1509 if (tor_memneq(client
->client_id
, keystream
, HS_DESC_CLIENT_ID_LEN
)) {
1512 cookie_key
= keystream
+ HS_DESC_CLIENT_ID_LEN
;
1514 /* This creates a cipher for AES. It can't fail. */
1515 cipher
= crypto_cipher_new_with_iv_and_bits(cookie_key
, client
->iv
,
1516 HS_DESC_COOKIE_KEY_BIT_SIZE
);
1517 descriptor_cookie
= tor_malloc_zero(HS_DESC_DESCRIPTOR_COOKIE_LEN
);
1518 /* This can't fail. */
1519 crypto_cipher_decrypt(cipher
, (char *) descriptor_cookie
,
1520 (const char *) client
->encrypted_cookie
,
1521 sizeof(client
->encrypted_cookie
));
1526 *descriptor_cookie_out
= descriptor_cookie
;
1528 crypto_cipher_free(cipher
);
1530 memwipe(keystream
, 0, keystream_length
);
1531 tor_free(keystream
);
1535 /** Decrypt an encrypted descriptor layer at <b>encrypted_blob</b> of size
1536 * <b>encrypted_blob_size</b>. The descriptor cookie is optional. Use
1537 * the descriptor object <b>desc</b> and <b>descriptor_cookie</b>
1538 * to generate the right decryption keys; set <b>decrypted_out</b> to
1539 * the plaintext. If <b>is_superencrypted_layer</b> is set, this is
1540 * the outer encrypted layer of the descriptor.
1542 * On any error case, including an empty output, return 0 and set
1543 * *<b>decrypted_out</b> to NULL.
1545 MOCK_IMPL(STATIC
size_t,
1546 decrypt_desc_layer
,(const hs_descriptor_t
*desc
,
1547 const uint8_t *descriptor_cookie
,
1548 bool is_superencrypted_layer
,
1549 char **decrypted_out
))
1551 uint8_t *decrypted
= NULL
;
1552 uint8_t secret_key
[HS_DESC_ENCRYPTED_KEY_LEN
], secret_iv
[CIPHER_IV_LEN
];
1553 uint8_t *secret_data
= NULL
;
1554 size_t secret_data_len
= 0;
1555 uint8_t mac_key
[DIGEST256_LEN
], our_mac
[DIGEST256_LEN
];
1556 const uint8_t *salt
, *encrypted
, *desc_mac
;
1557 size_t encrypted_len
, result_len
= 0;
1558 const uint8_t *encrypted_blob
= (is_superencrypted_layer
)
1559 ? desc
->plaintext_data
.superencrypted_blob
1560 : desc
->superencrypted_data
.encrypted_blob
;
1561 size_t encrypted_blob_size
= (is_superencrypted_layer
)
1562 ? desc
->plaintext_data
.superencrypted_blob_size
1563 : desc
->superencrypted_data
.encrypted_blob_size
;
1565 tor_assert(decrypted_out
);
1567 tor_assert(encrypted_blob
);
1569 /* Construction is as follow: SALT | ENCRYPTED_DATA | MAC .
1570 * Make sure we have enough space for all these things. */
1571 if (!encrypted_data_length_is_valid(encrypted_blob_size
)) {
1575 /* Start of the blob thus the salt. */
1576 salt
= encrypted_blob
;
1578 /* Next is the encrypted data. */
1579 encrypted
= encrypted_blob
+ HS_DESC_ENCRYPTED_SALT_LEN
;
1580 encrypted_len
= encrypted_blob_size
-
1581 (HS_DESC_ENCRYPTED_SALT_LEN
+ DIGEST256_LEN
);
1582 tor_assert(encrypted_len
> 0); /* guaranteed by the check above */
1584 /* And last comes the MAC. */
1585 desc_mac
= encrypted_blob
+ encrypted_blob_size
- DIGEST256_LEN
;
1587 /* Build secret data to be used in the decryption. */
1588 secret_data_len
= build_secret_data(&desc
->plaintext_data
.blinded_pubkey
,
1592 /* KDF construction resulting in a key from which the secret key, IV and MAC
1593 * key are extracted which is what we need for the decryption. */
1594 build_secret_key_iv_mac(desc
, secret_data
, secret_data_len
,
1595 salt
, HS_DESC_ENCRYPTED_SALT_LEN
,
1596 secret_key
, sizeof(secret_key
),
1597 secret_iv
, sizeof(secret_iv
),
1598 mac_key
, sizeof(mac_key
),
1599 is_superencrypted_layer
);
1602 build_mac(mac_key
, sizeof(mac_key
), salt
, HS_DESC_ENCRYPTED_SALT_LEN
,
1603 encrypted
, encrypted_len
, our_mac
, sizeof(our_mac
));
1604 memwipe(mac_key
, 0, sizeof(mac_key
));
1605 /* Verify MAC; MAC is H(mac_key || salt || encrypted)
1607 * This is a critical check that is making sure the computed MAC matches the
1608 * one in the descriptor. */
1609 if (!tor_memeq(our_mac
, desc_mac
, sizeof(our_mac
))) {
1610 log_info(LD_REND
, "Encrypted service descriptor MAC check failed");
1615 /* Decrypt. Here we are assured that the encrypted length is valid for
1617 crypto_cipher_t
*cipher
;
1619 cipher
= crypto_cipher_new_with_iv_and_bits(secret_key
, secret_iv
,
1620 HS_DESC_ENCRYPTED_BIT_SIZE
);
1621 /* Extra byte for the NUL terminated byte. */
1622 decrypted
= tor_malloc_zero(encrypted_len
+ 1);
1623 crypto_cipher_decrypt(cipher
, (char *) decrypted
,
1624 (const char *) encrypted
, encrypted_len
);
1625 crypto_cipher_free(cipher
);
1629 /* Adjust length to remove NUL padding bytes */
1630 uint8_t *end
= memchr(decrypted
, 0, encrypted_len
);
1631 result_len
= encrypted_len
;
1633 result_len
= end
- decrypted
;
1637 if (result_len
== 0) {
1638 /* Treat this as an error, so that somebody will free the output. */
1642 /* Make sure to NUL terminate the string. */
1643 decrypted
[encrypted_len
] = '\0';
1644 *decrypted_out
= (char *) decrypted
;
1649 tor_free(decrypted
);
1651 *decrypted_out
= NULL
;
1655 memwipe(secret_data
, 0, secret_data_len
);
1656 memwipe(secret_key
, 0, sizeof(secret_key
));
1657 memwipe(secret_iv
, 0, sizeof(secret_iv
));
1658 tor_free(secret_data
);
1662 /** Decrypt the superencrypted section of the descriptor using the given
1663 * descriptor object <b>desc</b>. A newly allocated NUL terminated string is
1664 * put in decrypted_out which contains the superencrypted layer of the
1665 * descriptor. Return the length of decrypted_out on success else 0 is
1666 * returned and decrypted_out is set to NULL. */
1667 MOCK_IMPL(STATIC
size_t,
1668 desc_decrypt_superencrypted
,(const hs_descriptor_t
*desc
,char **decrypted_out
))
1670 size_t superencrypted_len
= 0;
1671 char *superencrypted_plaintext
= NULL
;
1674 tor_assert(decrypted_out
);
1676 superencrypted_len
= decrypt_desc_layer(desc
,
1678 true, &superencrypted_plaintext
);
1680 if (!superencrypted_len
) {
1681 log_warn(LD_REND
, "Decrypting superencrypted desc failed.");
1684 tor_assert(superencrypted_plaintext
);
1687 /* In case of error, superencrypted_plaintext is already NULL, so the
1688 * following line makes sense. */
1689 *decrypted_out
= superencrypted_plaintext
;
1690 /* This makes sense too, because, in case of error, this is zero. */
1691 return superencrypted_len
;
1694 /** Decrypt the encrypted section of the descriptor using the given descriptor
1695 * object <b>desc</b>. A newly allocated NUL terminated string is put in
1696 * decrypted_out which contains the encrypted layer of the descriptor.
1697 * Return the length of decrypted_out on success else 0 is returned and
1698 * decrypted_out is set to NULL. */
1699 MOCK_IMPL(STATIC
size_t,
1700 desc_decrypt_encrypted
,(const hs_descriptor_t
*desc
,
1701 const curve25519_secret_key_t
*client_auth_sk
,
1702 char **decrypted_out
))
1704 size_t encrypted_len
= 0;
1705 char *encrypted_plaintext
= NULL
;
1706 uint8_t *descriptor_cookie
= NULL
;
1709 tor_assert(desc
->superencrypted_data
.clients
);
1710 tor_assert(decrypted_out
);
1712 /* If the client secret key is provided, try to find a valid descriptor
1713 * cookie. Otherwise, leave it NULL. */
1714 if (client_auth_sk
) {
1715 SMARTLIST_FOREACH_BEGIN(desc
->superencrypted_data
.clients
,
1716 hs_desc_authorized_client_t
*, client
) {
1717 /* If we can decrypt the descriptor cookie successfully, we will use that
1718 * descriptor cookie and break from the loop. */
1719 if (!decrypt_descriptor_cookie(desc
, client
, client_auth_sk
,
1720 &descriptor_cookie
)) {
1723 } SMARTLIST_FOREACH_END(client
);
1726 encrypted_len
= decrypt_desc_layer(desc
,
1728 false, &encrypted_plaintext
);
1730 if (!encrypted_len
) {
1733 tor_assert(encrypted_plaintext
);
1736 /* In case of error, encrypted_plaintext is already NULL, so the
1737 * following line makes sense. */
1738 *decrypted_out
= encrypted_plaintext
;
1739 if (descriptor_cookie
) {
1740 memwipe(descriptor_cookie
, 0, HS_DESC_DESCRIPTOR_COOKIE_LEN
);
1742 tor_free(descriptor_cookie
);
1743 /* This makes sense too, because, in case of error, this is zero. */
1744 return encrypted_len
;
1747 /** Given the token tok for an intro point legacy key, the list of tokens, the
1748 * introduction point ip being decoded and the descriptor desc from which it
1749 * comes from, decode the legacy key and set the intro point object. Return 0
1750 * on success else -1 on failure. */
1752 decode_intro_legacy_key(const directory_token_t
*tok
,
1753 smartlist_t
*tokens
,
1754 hs_desc_intro_point_t
*ip
,
1755 const hs_descriptor_t
*desc
)
1762 if (!crypto_pk_public_exponent_ok(tok
->key
)) {
1763 log_warn(LD_REND
, "Introduction point legacy key is invalid");
1766 ip
->legacy
.key
= crypto_pk_dup_key(tok
->key
);
1767 /* Extract the legacy cross certification cert which MUST be present if we
1768 * have a legacy key. */
1769 tok
= find_opt_by_keyword(tokens
, R3_INTRO_LEGACY_KEY_CERT
);
1771 log_warn(LD_REND
, "Introduction point legacy key cert is missing");
1774 tor_assert(tok
->object_body
);
1775 if (strcmp(tok
->object_type
, "CROSSCERT")) {
1776 /* Info level because this might be an unknown field that we should
1778 log_info(LD_REND
, "Introduction point legacy encryption key "
1779 "cross-certification has an unknown format.");
1782 /* Keep a copy of the certificate. */
1783 ip
->legacy
.cert
.encoded
= tor_memdup(tok
->object_body
, tok
->object_size
);
1784 ip
->legacy
.cert
.len
= tok
->object_size
;
1785 /* The check on the expiration date is for the entire lifetime of a
1786 * certificate which is 24 hours. However, a descriptor has a maximum
1787 * lifetime of 12 hours meaning we have a 12h difference between the two
1788 * which ultimately accommodate the clock skewed client. */
1789 if (rsa_ed25519_crosscert_check(ip
->legacy
.cert
.encoded
,
1790 ip
->legacy
.cert
.len
, ip
->legacy
.key
,
1791 &desc
->plaintext_data
.signing_pubkey
,
1792 approx_time() - HS_DESC_CERT_LIFETIME
)) {
1793 log_warn(LD_REND
, "Unable to check cross-certification on the "
1794 "introduction point legacy encryption key.");
1795 ip
->cross_certified
= 0;
1805 /** Dig into the descriptor <b>tokens</b> to find the onion key we should use
1806 * for this intro point, and set it into <b>onion_key_out</b>. Return 0 if it
1807 * was found and well-formed, otherwise return -1 in case of errors. */
1809 set_intro_point_onion_key(curve25519_public_key_t
*onion_key_out
,
1810 const smartlist_t
*tokens
)
1813 smartlist_t
*onion_keys
= NULL
;
1815 tor_assert(onion_key_out
);
1817 onion_keys
= find_all_by_keyword(tokens
, R3_INTRO_ONION_KEY
);
1819 log_warn(LD_REND
, "Descriptor did not contain intro onion keys");
1823 SMARTLIST_FOREACH_BEGIN(onion_keys
, directory_token_t
*, tok
) {
1824 /* This field is using GE(2) so for possible forward compatibility, we
1825 * accept more fields but must be at least 2. */
1826 tor_assert(tok
->n_args
>= 2);
1828 /* Try to find an ntor key, it's the only recognized type right now */
1829 if (!strcmp(tok
->args
[0], "ntor")) {
1830 if (curve25519_public_from_base64(onion_key_out
, tok
->args
[1]) < 0) {
1831 log_warn(LD_REND
, "Introduction point ntor onion-key is invalid");
1834 /* Got the onion key! Set the appropriate retval */
1837 } SMARTLIST_FOREACH_END(tok
);
1839 /* Log an error if we didn't find it :( */
1841 log_warn(LD_REND
, "Descriptor did not contain ntor onion keys");
1845 smartlist_free(onion_keys
);
1849 /** Given the start of a section and the end of it, decode a single
1850 * introduction point from that section. Return a newly allocated introduction
1851 * point object containing the decoded data. Return NULL if the section can't
1853 STATIC hs_desc_intro_point_t
*
1854 decode_introduction_point(const hs_descriptor_t
*desc
, const char *start
)
1856 hs_desc_intro_point_t
*ip
= NULL
;
1857 memarea_t
*area
= NULL
;
1858 smartlist_t
*tokens
= NULL
;
1859 const directory_token_t
*tok
;
1864 area
= memarea_new();
1865 tokens
= smartlist_new();
1866 if (tokenize_string(area
, start
, start
+ strlen(start
),
1867 tokens
, hs_desc_intro_point_v3_token_table
, 0) < 0) {
1868 log_warn(LD_REND
, "Introduction point is not parseable");
1872 /* Ok we seem to have a well formed section containing enough tokens to
1873 * parse. Allocate our IP object and try to populate it. */
1874 ip
= hs_desc_intro_point_new();
1876 /* "introduction-point" SP link-specifiers NL */
1877 tok
= find_by_keyword(tokens
, R3_INTRODUCTION_POINT
);
1878 tor_assert(tok
->n_args
== 1);
1879 /* Our constructor creates this list by default so free it. */
1880 smartlist_free(ip
->link_specifiers
);
1881 ip
->link_specifiers
= decode_link_specifiers(tok
->args
[0]);
1882 if (!ip
->link_specifiers
) {
1883 log_warn(LD_REND
, "Introduction point has invalid link specifiers");
1887 /* "onion-key" SP ntor SP key NL */
1888 if (set_intro_point_onion_key(&ip
->onion_key
, tokens
) < 0) {
1892 /* "auth-key" NL certificate NL */
1893 tok
= find_by_keyword(tokens
, R3_INTRO_AUTH_KEY
);
1894 tor_assert(tok
->object_body
);
1895 if (strcmp(tok
->object_type
, "ED25519 CERT")) {
1896 log_warn(LD_REND
, "Unexpected object type for introduction auth key");
1899 /* Parse cert and do some validation. */
1900 if (cert_parse_and_validate(&ip
->auth_key_cert
, tok
->object_body
,
1901 tok
->object_size
, CERT_TYPE_AUTH_HS_IP_KEY
,
1902 "introduction point auth-key") < 0) {
1905 /* Validate authentication certificate with descriptor signing key. */
1906 if (tor_cert_checksig(ip
->auth_key_cert
,
1907 &desc
->plaintext_data
.signing_pubkey
, 0) < 0) {
1908 log_warn(LD_REND
, "Invalid authentication key signature: %s",
1909 tor_cert_describe_signature_status(ip
->auth_key_cert
));
1913 /* Exactly one "enc-key" SP "ntor" SP key NL */
1914 tok
= find_by_keyword(tokens
, R3_INTRO_ENC_KEY
);
1915 if (!strcmp(tok
->args
[0], "ntor")) {
1916 /* This field is using GE(2) so for possible forward compatibility, we
1917 * accept more fields but must be at least 2. */
1918 tor_assert(tok
->n_args
>= 2);
1920 if (curve25519_public_from_base64(&ip
->enc_key
, tok
->args
[1]) < 0) {
1921 log_warn(LD_REND
, "Introduction point ntor enc-key is invalid");
1925 /* Unknown key type so we can't use that introduction point. */
1926 log_warn(LD_REND
, "Introduction point encryption key is unrecognized.");
1930 /* Exactly once "enc-key-cert" NL certificate NL */
1931 tok
= find_by_keyword(tokens
, R3_INTRO_ENC_KEY_CERT
);
1932 tor_assert(tok
->object_body
);
1933 /* Do the cross certification. */
1934 if (strcmp(tok
->object_type
, "ED25519 CERT")) {
1935 log_warn(LD_REND
, "Introduction point ntor encryption key "
1936 "cross-certification has an unknown format.");
1939 if (cert_parse_and_validate(&ip
->enc_key_cert
, tok
->object_body
,
1940 tok
->object_size
, CERT_TYPE_CROSS_HS_IP_KEYS
,
1941 "introduction point enc-key-cert") < 0) {
1944 if (tor_cert_checksig(ip
->enc_key_cert
,
1945 &desc
->plaintext_data
.signing_pubkey
, 0) < 0) {
1946 log_warn(LD_REND
, "Invalid encryption key signature: %s",
1947 tor_cert_describe_signature_status(ip
->enc_key_cert
));
1950 /* It is successfully cross certified. Flag the object. */
1951 ip
->cross_certified
= 1;
1953 /* Do we have a "legacy-key" SP key NL ?*/
1954 tok
= find_opt_by_keyword(tokens
, R3_INTRO_LEGACY_KEY
);
1956 if (decode_intro_legacy_key(tok
, tokens
, ip
, desc
) < 0) {
1961 /* Introduction point has been parsed successfully. */
1965 hs_desc_intro_point_free(ip
);
1969 SMARTLIST_FOREACH(tokens
, directory_token_t
*, t
, token_clear(t
));
1970 smartlist_free(tokens
);
1972 memarea_drop_all(area
);
1978 /** Given a descriptor string at <b>data</b>, decode all possible introduction
1979 * points that we can find. Add the introduction point object to desc_enc as we
1980 * find them. This function can't fail and it is possible that zero
1981 * introduction points can be decoded. */
1983 decode_intro_points(const hs_descriptor_t
*desc
,
1984 hs_desc_encrypted_data_t
*desc_enc
,
1987 smartlist_t
*chunked_desc
= smartlist_new();
1988 smartlist_t
*intro_points
= smartlist_new();
1991 tor_assert(desc_enc
);
1993 tor_assert(desc_enc
->intro_points
);
1995 /* Take the desc string, and extract the intro point substrings out of it */
1997 /* Split the descriptor string using the intro point header as delimiter */
1998 smartlist_split_string(chunked_desc
, data
, str_intro_point_start
, 0, 0);
2000 /* Check if there are actually any intro points included. The first chunk
2001 * should be other descriptor fields (e.g. create2-formats), so it's not an
2003 if (smartlist_len(chunked_desc
) < 2) {
2008 /* Take the intro point substrings, and prepare them for parsing */
2011 /* Prepend the introduction-point header to all the chunks, since
2012 smartlist_split_string() devoured it. */
2013 SMARTLIST_FOREACH_BEGIN(chunked_desc
, char *, chunk
) {
2014 /* Ignore first chunk. It's other descriptor fields. */
2019 smartlist_add_asprintf(intro_points
, "%s %s", str_intro_point
, chunk
);
2020 } SMARTLIST_FOREACH_END(chunk
);
2023 /* Parse the intro points! */
2024 SMARTLIST_FOREACH_BEGIN(intro_points
, const char *, intro_point
) {
2025 hs_desc_intro_point_t
*ip
= decode_introduction_point(desc
, intro_point
);
2027 /* Malformed introduction point section. We'll ignore this introduction
2028 * point and continue parsing. New or unknown fields are possible for
2029 * forward compatibility. */
2032 smartlist_add(desc_enc
->intro_points
, ip
);
2033 } SMARTLIST_FOREACH_END(intro_point
);
2036 SMARTLIST_FOREACH(chunked_desc
, char *, a
, tor_free(a
));
2037 smartlist_free(chunked_desc
);
2038 SMARTLIST_FOREACH(intro_points
, char *, a
, tor_free(a
));
2039 smartlist_free(intro_points
);
2042 /** Return 1 iff the given base64 encoded signature in b64_sig from the encoded
2043 * descriptor in encoded_desc validates the descriptor content. */
2045 desc_sig_is_valid(const char *b64_sig
,
2046 const ed25519_public_key_t
*signing_pubkey
,
2047 const char *encoded_desc
, size_t encoded_len
)
2050 ed25519_signature_t sig
;
2051 const char *sig_start
;
2053 tor_assert(b64_sig
);
2054 tor_assert(signing_pubkey
);
2055 tor_assert(encoded_desc
);
2056 /* Verifying nothing won't end well :). */
2057 tor_assert(encoded_len
> 0);
2059 /* Signature length check. */
2060 if (strlen(b64_sig
) != ED25519_SIG_BASE64_LEN
) {
2061 log_warn(LD_REND
, "Service descriptor has an invalid signature length."
2062 "Expected %d but got %lu",
2063 ED25519_SIG_BASE64_LEN
, (unsigned long) strlen(b64_sig
));
2067 /* First, convert base64 blob to an ed25519 signature. */
2068 if (ed25519_signature_from_base64(&sig
, b64_sig
) != 0) {
2069 log_warn(LD_REND
, "Service descriptor does not contain a valid "
2074 /* Find the start of signature. */
2075 sig_start
= tor_memstr(encoded_desc
, encoded_len
, "\n" str_signature
" ");
2076 /* Getting here means the token parsing worked for the signature so if we
2077 * can't find the start of the signature, we have a code flow issue. */
2079 log_warn(LD_GENERAL
, "Malformed signature line. Rejecting.");
2082 /* Skip newline, it has to go in the signature check. */
2085 /* Validate signature with the full body of the descriptor. */
2086 if (ed25519_checksig_prefixed(&sig
,
2087 (const uint8_t *) encoded_desc
,
2088 sig_start
- encoded_desc
,
2089 str_desc_sig_prefix
,
2090 signing_pubkey
) != 0) {
2091 log_warn(LD_REND
, "Invalid signature on service descriptor");
2094 /* Valid signature! All is good. */
2101 /** Given the token tok for PoW params, decode it as hs_pow_desc_params_t.
2102 * tok->args MUST contain at least 4 elements Return 0 on success else -1 on
2105 decode_pow_params(const directory_token_t
*tok
,
2106 hs_pow_desc_params_t
*pow_params
)
2111 tor_assert(tok
->n_args
>= 4);
2112 tor_assert(pow_params
);
2114 /* Find the type of PoW system being used. */
2116 for (int idx
= 0; pow_types
[idx
].identifier
; idx
++) {
2117 if (!strncmp(tok
->args
[0], pow_types
[idx
].identifier
,
2118 strlen(pow_types
[idx
].identifier
))) {
2119 pow_params
->type
= pow_types
[idx
].type
;
2125 log_warn(LD_REND
, "Unknown PoW type from descriptor.");
2129 if (base64_decode((char *)pow_params
->seed
, sizeof(pow_params
->seed
),
2130 tok
->args
[1], strlen(tok
->args
[1])) !=
2131 sizeof(pow_params
->seed
)) {
2132 log_warn(LD_REND
, "Unparseable seed %s in PoW params",
2133 escaped(tok
->args
[1]));
2138 unsigned long effort
=
2139 tor_parse_ulong(tok
->args
[2], 10, 0, UINT32_MAX
, &ok
, NULL
);
2141 log_warn(LD_REND
, "Unparseable suggested effort %s in PoW params",
2142 escaped(tok
->args
[2]));
2145 pow_params
->suggested_effort
= (uint32_t)effort
;
2147 /* Parse the expiration time of the PoW params. */
2148 time_t expiration_time
= 0;
2149 if (parse_iso_time_nospace(tok
->args
[3], &expiration_time
)) {
2150 log_warn(LD_REND
, "Unparseable expiration time %s in PoW params",
2151 escaped(tok
->args
[3]));
2154 /* Validation of this time is done in client_desc_has_arrived() so we can
2155 * trigger a fetch if expired. */
2156 pow_params
->expiration_time
= expiration_time
;
2165 /** Decode descriptor plaintext data for version 3. Given a list of tokens, an
2166 * allocated plaintext object that will be populated and the encoded
2167 * descriptor with its length. The last one is needed for signature
2168 * verification. Unknown tokens are simply ignored so this won't error on
2169 * unknowns but requires that all v3 token be present and valid.
2171 * Return 0 on success else a negative value. */
2172 static hs_desc_decode_status_t
2173 desc_decode_plaintext_v3(smartlist_t
*tokens
,
2174 hs_desc_plaintext_data_t
*desc
,
2175 const char *encoded_desc
, size_t encoded_len
)
2178 directory_token_t
*tok
;
2182 /* Version higher could still use this function to decode most of the
2183 * descriptor and then they decode the extra part. */
2184 tor_assert(desc
->version
>= 3);
2186 /* Descriptor lifetime parsing. */
2187 tok
= find_by_keyword(tokens
, R3_DESC_LIFETIME
);
2188 tor_assert(tok
->n_args
== 1);
2189 desc
->lifetime_sec
= (uint32_t) tor_parse_ulong(tok
->args
[0], 10, 0,
2190 UINT32_MAX
, &ok
, NULL
);
2192 log_warn(LD_REND
, "Service descriptor lifetime value is invalid");
2195 /* Put it from minute to second. */
2196 desc
->lifetime_sec
*= 60;
2197 if (desc
->lifetime_sec
> HS_DESC_MAX_LIFETIME
) {
2198 log_warn(LD_REND
, "Service descriptor lifetime is too big. "
2199 "Got %" PRIu32
" but max is %d",
2200 desc
->lifetime_sec
, HS_DESC_MAX_LIFETIME
);
2204 /* Descriptor signing certificate. */
2205 tok
= find_by_keyword(tokens
, R3_DESC_SIGNING_CERT
);
2206 tor_assert(tok
->object_body
);
2207 /* Expecting a prop220 cert with the signing key extension, which contains
2208 * the blinded public key. */
2209 if (strcmp(tok
->object_type
, "ED25519 CERT") != 0) {
2210 log_warn(LD_REND
, "Service descriptor signing cert wrong type (%s)",
2211 escaped(tok
->object_type
));
2214 if (cert_parse_and_validate(&desc
->signing_key_cert
, tok
->object_body
,
2215 tok
->object_size
, CERT_TYPE_SIGNING_HS_DESC
,
2216 "service descriptor signing key") < 0) {
2220 /* Copy the public keys into signing_pubkey and blinded_pubkey */
2221 memcpy(&desc
->signing_pubkey
, &desc
->signing_key_cert
->signed_key
,
2222 sizeof(ed25519_public_key_t
));
2223 memcpy(&desc
->blinded_pubkey
, &desc
->signing_key_cert
->signing_key
,
2224 sizeof(ed25519_public_key_t
));
2226 /* Extract revision counter value. */
2227 tok
= find_by_keyword(tokens
, R3_REVISION_COUNTER
);
2228 tor_assert(tok
->n_args
== 1);
2229 desc
->revision_counter
= tor_parse_uint64(tok
->args
[0], 10, 0,
2230 UINT64_MAX
, &ok
, NULL
);
2232 log_warn(LD_REND
, "Service descriptor revision-counter is invalid");
2236 /* Extract the superencrypted data section. */
2237 tok
= find_by_keyword(tokens
, R3_SUPERENCRYPTED
);
2238 tor_assert(tok
->object_body
);
2239 if (strcmp(tok
->object_type
, "MESSAGE") != 0) {
2240 log_warn(LD_REND
, "Desc superencrypted data section is invalid");
2243 /* Make sure the length of the superencrypted blob is valid. */
2244 if (!encrypted_data_length_is_valid(tok
->object_size
)) {
2248 /* Copy the superencrypted blob to the descriptor object so we can handle it
2249 * latter if needed. */
2250 desc
->superencrypted_blob
= tor_memdup(tok
->object_body
, tok
->object_size
);
2251 desc
->superencrypted_blob_size
= tok
->object_size
;
2253 /* Extract signature and verify it. */
2254 tok
= find_by_keyword(tokens
, R3_SIGNATURE
);
2255 tor_assert(tok
->n_args
== 1);
2256 /* First arg here is the actual encoded signature. */
2257 if (!desc_sig_is_valid(tok
->args
[0], &desc
->signing_pubkey
,
2258 encoded_desc
, encoded_len
)) {
2262 return HS_DESC_DECODE_OK
;
2264 return HS_DESC_DECODE_PLAINTEXT_ERROR
;
2267 /** Decode the version 3 superencrypted section of the given descriptor desc.
2268 * The desc_superencrypted_out will be populated with the decoded data. */
2269 STATIC hs_desc_decode_status_t
2270 desc_decode_superencrypted_v3(const hs_descriptor_t
*desc
,
2271 hs_desc_superencrypted_data_t
*
2272 desc_superencrypted_out
)
2274 hs_desc_decode_status_t ret
= HS_DESC_DECODE_SUPERENC_ERROR
;
2275 char *message
= NULL
;
2277 memarea_t
*area
= NULL
;
2278 directory_token_t
*tok
;
2279 smartlist_t
*tokens
= NULL
;
2280 /* Rename the parameter because it is too long. */
2281 hs_desc_superencrypted_data_t
*superencrypted
= desc_superencrypted_out
;
2284 tor_assert(desc_superencrypted_out
);
2286 /* Decrypt the superencrypted data that is located in the plaintext section
2287 * in the descriptor as a blob of bytes. */
2288 message_len
= desc_decrypt_superencrypted(desc
, &message
);
2290 log_warn(LD_REND
, "Service descriptor decryption failed.");
2293 tor_assert(message
);
2295 area
= memarea_new();
2296 tokens
= smartlist_new();
2297 if (tokenize_string(area
, message
, message
+ message_len
,
2298 tokens
, hs_desc_superencrypted_v3_token_table
, 0) < 0) {
2299 log_warn(LD_REND
, "Superencrypted service descriptor is not parseable.");
2303 /* Verify desc auth type */
2304 tok
= find_by_keyword(tokens
, R3_DESC_AUTH_TYPE
);
2305 tor_assert(tok
->n_args
>= 1);
2306 if (strcmp(tok
->args
[0], "x25519")) {
2307 log_warn(LD_DIR
, "Unrecognized desc auth type");
2311 /* Extract desc auth ephemeral key */
2312 tok
= find_by_keyword(tokens
, R3_DESC_AUTH_KEY
);
2313 tor_assert(tok
->n_args
>= 1);
2314 if (curve25519_public_from_base64(&superencrypted
->auth_ephemeral_pubkey
,
2315 tok
->args
[0]) < 0) {
2316 log_warn(LD_DIR
, "Bogus desc auth ephemeral key in HS desc");
2320 /* Extract desc auth client items */
2321 if (!superencrypted
->clients
) {
2322 superencrypted
->clients
= smartlist_new();
2324 SMARTLIST_FOREACH_BEGIN(tokens
, const directory_token_t
*, token
) {
2325 if (token
->tp
== R3_DESC_AUTH_CLIENT
) {
2326 tor_assert(token
->n_args
>= 3);
2328 hs_desc_authorized_client_t
*client
=
2329 tor_malloc_zero(sizeof(hs_desc_authorized_client_t
));
2331 if (decode_auth_client(token
, client
) < 0) {
2332 log_warn(LD_REND
, "Descriptor client authorization section can't "
2337 smartlist_add(superencrypted
->clients
, client
);
2339 } SMARTLIST_FOREACH_END(token
);
2341 /* Extract the encrypted data section. */
2342 tok
= find_by_keyword(tokens
, R3_ENCRYPTED
);
2343 tor_assert(tok
->object_body
);
2344 if (strcmp(tok
->object_type
, "MESSAGE") != 0) {
2345 log_warn(LD_REND
, "Desc encrypted data section is invalid");
2348 /* Make sure the length of the encrypted blob is valid. */
2349 if (!encrypted_data_length_is_valid(tok
->object_size
)) {
2353 /* Copy the encrypted blob to the descriptor object so we can handle it
2354 * latter if needed. */
2355 tor_assert(tok
->object_size
<= INT_MAX
);
2356 superencrypted
->encrypted_blob
= tor_memdup(tok
->object_body
,
2358 superencrypted
->encrypted_blob_size
= tok
->object_size
;
2360 ret
= HS_DESC_DECODE_OK
;
2364 tor_assert(ret
< HS_DESC_DECODE_OK
);
2365 hs_desc_superencrypted_data_free_contents(desc_superencrypted_out
);
2369 SMARTLIST_FOREACH(tokens
, directory_token_t
*, t
, token_clear(t
));
2370 smartlist_free(tokens
);
2373 memarea_drop_all(area
);
2381 /** Decode the version 3 encrypted section of the given descriptor desc. The
2382 * desc_encrypted_out will be populated with the decoded data. */
2383 STATIC hs_desc_decode_status_t
2384 desc_decode_encrypted_v3(const hs_descriptor_t
*desc
,
2385 const curve25519_secret_key_t
*client_auth_sk
,
2386 hs_desc_encrypted_data_t
*desc_encrypted_out
)
2388 hs_desc_decode_status_t ret
= HS_DESC_DECODE_ENCRYPTED_ERROR
;
2389 char *message
= NULL
;
2391 memarea_t
*area
= NULL
;
2392 directory_token_t
*tok
;
2393 smartlist_t
*tokens
= NULL
;
2396 tor_assert(desc_encrypted_out
);
2398 /* Decrypt the encrypted data that is located in the superencrypted section
2399 * in the descriptor as a blob of bytes. */
2400 message_len
= desc_decrypt_encrypted(desc
, client_auth_sk
, &message
);
2402 /* Two possible situation here. Either we have a client authorization
2403 * configured that didn't work or we do not have any configured for this
2404 * onion address so likely the descriptor is for authorized client only,
2406 if (client_auth_sk
) {
2407 /* At warning level so the client can notice that its client
2408 * authorization is failing. */
2409 log_warn(LD_REND
, "Client authorization for requested onion address "
2410 "is invalid. Can't decrypt the descriptor.");
2411 ret
= HS_DESC_DECODE_BAD_CLIENT_AUTH
;
2413 /* Inform at notice level that the onion address requested can't be
2414 * reached without client authorization most likely. */
2415 log_notice(LD_REND
, "Fail to decrypt descriptor for requested onion "
2416 "address. It is likely requiring client "
2418 ret
= HS_DESC_DECODE_NEED_CLIENT_AUTH
;
2422 tor_assert(message
);
2424 area
= memarea_new();
2425 tokens
= smartlist_new();
2426 if (tokenize_string(area
, message
, message
+ message_len
,
2427 tokens
, hs_desc_encrypted_v3_token_table
, 0) < 0) {
2428 log_warn(LD_REND
, "Encrypted service descriptor is not parseable.");
2432 /* CREATE2 supported cell format. It's mandatory. */
2433 tok
= find_by_keyword(tokens
, R3_CREATE2_FORMATS
);
2435 decode_create2_list(desc_encrypted_out
, tok
->args
[0]);
2436 /* Must support ntor according to the specification */
2437 if (!desc_encrypted_out
->create2_ntor
) {
2438 log_warn(LD_REND
, "Service create2-formats does not include ntor.");
2442 /* Authentication type. It's optional but only once. */
2443 tok
= find_opt_by_keyword(tokens
, R3_INTRO_AUTH_REQUIRED
);
2445 tor_assert(tok
->n_args
>= 1);
2446 if (!decode_auth_type(desc_encrypted_out
, tok
->args
[0])) {
2447 log_warn(LD_REND
, "Service descriptor authentication type has "
2448 "invalid entry(ies).");
2453 /* Is this service a single onion service? */
2454 tok
= find_opt_by_keyword(tokens
, R3_SINGLE_ONION_SERVICE
);
2456 desc_encrypted_out
->single_onion_service
= 1;
2459 /* Get flow control if any. */
2460 tok
= find_opt_by_keyword(tokens
, R3_FLOW_CONTROL
);
2464 tor_asprintf(&desc_encrypted_out
->flow_control_pv
, "FlowCtrl=%s",
2466 uint8_t sendme_inc
=
2467 (uint8_t) tor_parse_uint64(tok
->args
[1], 10, 0, UINT8_MAX
, &ok
, NULL
);
2468 if (!ok
|| !congestion_control_validate_sendme_increment(sendme_inc
)) {
2469 log_warn(LD_REND
, "Service descriptor flow control sendme "
2470 "value is invalid");
2473 desc_encrypted_out
->sendme_inc
= sendme_inc
;
2476 /* Get PoW if any. */
2477 tok
= find_opt_by_keyword(tokens
, R3_POW_PARAMS
);
2479 hs_pow_desc_params_t
*pow_params
=
2480 tor_malloc_zero(sizeof(hs_pow_desc_params_t
));
2481 if (decode_pow_params(tok
, pow_params
)) {
2482 tor_free(pow_params
);
2485 desc_encrypted_out
->pow_params
= pow_params
;
2488 /* Initialize the descriptor's introduction point list before we start
2489 * decoding. Having 0 intro point is valid. Then decode them all. */
2490 desc_encrypted_out
->intro_points
= smartlist_new();
2491 decode_intro_points(desc
, desc_encrypted_out
, message
);
2493 /* Validation of maximum introduction points allowed. */
2494 if (smartlist_len(desc_encrypted_out
->intro_points
) >
2495 HS_CONFIG_V3_MAX_INTRO_POINTS
) {
2496 log_warn(LD_REND
, "Service descriptor contains too many introduction "
2497 "points. Maximum allowed is %d but we have %d",
2498 HS_CONFIG_V3_MAX_INTRO_POINTS
,
2499 smartlist_len(desc_encrypted_out
->intro_points
));
2503 /* NOTE: Unknown fields are allowed because this function could be used to
2504 * decode other descriptor version. */
2506 ret
= HS_DESC_DECODE_OK
;
2510 tor_assert(ret
< HS_DESC_DECODE_OK
);
2511 hs_desc_encrypted_data_free_contents(desc_encrypted_out
);
2515 SMARTLIST_FOREACH(tokens
, directory_token_t
*, t
, token_clear(t
));
2516 smartlist_free(tokens
);
2519 memarea_drop_all(area
);
2527 /** Table of encrypted decode function version specific. The function are
2528 * indexed by the version number so v3 callback is at index 3 in the array. */
2529 static hs_desc_decode_status_t
2530 (*decode_encrypted_handlers
[])(
2531 const hs_descriptor_t
*desc
,
2532 const curve25519_secret_key_t
*client_auth_sk
,
2533 hs_desc_encrypted_data_t
*desc_encrypted
) =
2535 /* v0 */ NULL
, /* v1 */ NULL
, /* v2 */ NULL
,
2536 desc_decode_encrypted_v3
,
2539 /** Decode the encrypted data section of the given descriptor and store the
2540 * data in the given encrypted data object. Return 0 on success else a
2541 * negative value on error. */
2542 hs_desc_decode_status_t
2543 hs_desc_decode_encrypted(const hs_descriptor_t
*desc
,
2544 const curve25519_secret_key_t
*client_auth_sk
,
2545 hs_desc_encrypted_data_t
*desc_encrypted
)
2547 hs_desc_decode_status_t ret
= HS_DESC_DECODE_ENCRYPTED_ERROR
;
2551 /* Ease our life a bit. */
2552 version
= desc
->plaintext_data
.version
;
2553 tor_assert(desc_encrypted
);
2554 /* Calling this function without an encrypted blob to parse is a code flow
2555 * error. The superencrypted parsing should never succeed in the first place
2556 * without an encrypted section. */
2557 tor_assert(desc
->superencrypted_data
.encrypted_blob
);
2558 /* Let's make sure we have a supported version as well. By correctly parsing
2559 * the plaintext, this should not fail. */
2560 if (BUG(!hs_desc_is_supported_version(version
))) {
2563 /* Extra precaution. Having no handler for the supported version should
2564 * never happened else we forgot to add it but we bumped the version. */
2565 tor_assert(ARRAY_LENGTH(decode_encrypted_handlers
) >= version
);
2566 tor_assert(decode_encrypted_handlers
[version
]);
2568 /* Run the version specific plaintext decoder. */
2569 ret
= decode_encrypted_handlers
[version
](desc
, client_auth_sk
,
2579 /** Table of superencrypted decode function version specific. The function are
2580 * indexed by the version number so v3 callback is at index 3 in the array. */
2581 static hs_desc_decode_status_t
2582 (*decode_superencrypted_handlers
[])(
2583 const hs_descriptor_t
*desc
,
2584 hs_desc_superencrypted_data_t
*desc_superencrypted
) =
2586 /* v0 */ NULL
, /* v1 */ NULL
, /* v2 */ NULL
,
2587 desc_decode_superencrypted_v3
,
2590 /** Decode the superencrypted data section of the given descriptor and store
2591 * the data in the given superencrypted data object. */
2592 hs_desc_decode_status_t
2593 hs_desc_decode_superencrypted(const hs_descriptor_t
*desc
,
2594 hs_desc_superencrypted_data_t
*
2595 desc_superencrypted
)
2597 hs_desc_decode_status_t ret
= HS_DESC_DECODE_SUPERENC_ERROR
;
2601 /* Ease our life a bit. */
2602 version
= desc
->plaintext_data
.version
;
2603 tor_assert(desc_superencrypted
);
2604 /* Calling this function without an superencrypted blob to parse is
2605 * a code flow error. The plaintext parsing should never succeed in
2606 * the first place without an superencrypted section. */
2607 tor_assert(desc
->plaintext_data
.superencrypted_blob
);
2608 /* Let's make sure we have a supported version as well. By correctly parsing
2609 * the plaintext, this should not fail. */
2610 if (BUG(!hs_desc_is_supported_version(version
))) {
2613 /* Extra precaution. Having no handler for the supported version should
2614 * never happened else we forgot to add it but we bumped the version. */
2615 tor_assert(ARRAY_LENGTH(decode_superencrypted_handlers
) >= version
);
2616 tor_assert(decode_superencrypted_handlers
[version
]);
2618 /* Run the version specific plaintext decoder. */
2619 ret
= decode_superencrypted_handlers
[version
](desc
, desc_superencrypted
);
2628 /** Table of plaintext decode function version specific. The function are
2629 * indexed by the version number so v3 callback is at index 3 in the array. */
2630 static hs_desc_decode_status_t
2631 (*decode_plaintext_handlers
[])(
2632 smartlist_t
*tokens
,
2633 hs_desc_plaintext_data_t
*desc
,
2634 const char *encoded_desc
,
2635 size_t encoded_len
) =
2637 /* v0 */ NULL
, /* v1 */ NULL
, /* v2 */ NULL
,
2638 desc_decode_plaintext_v3
,
2641 /** Fully decode the given descriptor plaintext and store the data in the
2642 * plaintext data object. */
2643 hs_desc_decode_status_t
2644 hs_desc_decode_plaintext(const char *encoded
,
2645 hs_desc_plaintext_data_t
*plaintext
)
2648 hs_desc_decode_status_t ret
= HS_DESC_DECODE_PLAINTEXT_ERROR
;
2649 memarea_t
*area
= NULL
;
2650 smartlist_t
*tokens
= NULL
;
2652 directory_token_t
*tok
;
2654 tor_assert(encoded
);
2655 tor_assert(plaintext
);
2657 /* Check that descriptor is within size limits. */
2658 encoded_len
= strlen(encoded
);
2659 if (encoded_len
>= hs_cache_get_max_descriptor_size()) {
2660 log_warn(LD_REND
, "Service descriptor is too big (%lu bytes)",
2661 (unsigned long) encoded_len
);
2665 area
= memarea_new();
2666 tokens
= smartlist_new();
2667 /* Tokenize the descriptor so we can start to parse it. */
2668 if (tokenize_string(area
, encoded
, encoded
+ encoded_len
, tokens
,
2669 hs_desc_v3_token_table
, 0) < 0) {
2670 log_warn(LD_REND
, "Service descriptor is not parseable");
2674 /* Get the version of the descriptor which is the first mandatory field of
2675 * the descriptor. From there, we'll decode the right descriptor version. */
2676 tok
= find_by_keyword(tokens
, R_HS_DESCRIPTOR
);
2677 tor_assert(tok
->n_args
== 1);
2678 plaintext
->version
= (uint32_t) tor_parse_ulong(tok
->args
[0], 10, 0,
2679 UINT32_MAX
, &ok
, NULL
);
2681 log_warn(LD_REND
, "Service descriptor has unparseable version %s",
2682 escaped(tok
->args
[0]));
2685 if (!hs_desc_is_supported_version(plaintext
->version
)) {
2686 log_warn(LD_REND
, "Service descriptor has unsupported version %" PRIu32
,
2687 plaintext
->version
);
2690 /* Extra precaution. Having no handler for the supported version should
2691 * never happened else we forgot to add it but we bumped the version. */
2692 tor_assert(ARRAY_LENGTH(decode_plaintext_handlers
) >= plaintext
->version
);
2693 tor_assert(decode_plaintext_handlers
[plaintext
->version
]);
2695 /* Run the version specific plaintext decoder. */
2696 ret
= decode_plaintext_handlers
[plaintext
->version
](tokens
, plaintext
,
2697 encoded
, encoded_len
);
2698 if (ret
!= HS_DESC_DECODE_OK
) {
2701 /* Success. Descriptor has been populated with the data. */
2702 ret
= HS_DESC_DECODE_OK
;
2706 SMARTLIST_FOREACH(tokens
, directory_token_t
*, t
, token_clear(t
));
2707 smartlist_free(tokens
);
2710 memarea_drop_all(area
);
2715 /** Fully decode an encoded descriptor and set a newly allocated descriptor
2716 * object in desc_out. Client secret key is used to decrypt the "encrypted"
2717 * section if not NULL else it's ignored.
2719 * Return 0 on success. A negative value is returned on error and desc_out is
2721 hs_desc_decode_status_t
2722 hs_desc_decode_descriptor(const char *encoded
,
2723 const hs_subcredential_t
*subcredential
,
2724 const curve25519_secret_key_t
*client_auth_sk
,
2725 hs_descriptor_t
**desc_out
)
2727 hs_desc_decode_status_t ret
= HS_DESC_DECODE_GENERIC_ERROR
;
2728 hs_descriptor_t
*desc
;
2730 tor_assert(encoded
);
2732 desc
= tor_malloc_zero(sizeof(hs_descriptor_t
));
2734 /* Subcredentials are not optional. */
2735 if (BUG(!subcredential
||
2736 fast_mem_is_zero((char*)subcredential
, DIGEST256_LEN
))) {
2737 log_warn(LD_GENERAL
, "Tried to decrypt without subcred. Impossible!");
2741 memcpy(&desc
->subcredential
, subcredential
, sizeof(desc
->subcredential
));
2743 ret
= hs_desc_decode_plaintext(encoded
, &desc
->plaintext_data
);
2744 if (ret
!= HS_DESC_DECODE_OK
) {
2748 ret
= hs_desc_decode_superencrypted(desc
, &desc
->superencrypted_data
);
2749 if (ret
!= HS_DESC_DECODE_OK
) {
2753 ret
= hs_desc_decode_encrypted(desc
, client_auth_sk
, &desc
->encrypted_data
);
2754 if (ret
!= HS_DESC_DECODE_OK
) {
2761 hs_descriptor_free(desc
);
2766 hs_descriptor_free(desc
);
2771 tor_assert(ret
< 0);
2775 /** Table of encode function version specific. The functions are indexed by the
2776 * version number so v3 callback is at index 3 in the array. */
2778 (*encode_handlers
[])(
2779 const hs_descriptor_t
*desc
,
2780 const ed25519_keypair_t
*signing_kp
,
2781 const uint8_t *descriptor_cookie
,
2782 char **encoded_out
) =
2784 /* v0 */ NULL
, /* v1 */ NULL
, /* v2 */ NULL
,
2788 /** Encode the given descriptor desc including signing with the given key pair
2789 * signing_kp and encrypting with the given descriptor cookie.
2791 * If the client authorization is enabled, descriptor_cookie must be the same
2792 * as the one used to build hs_desc_authorized_client_t in the descriptor.
2793 * Otherwise, it must be NULL. On success, encoded_out points to a newly
2794 * allocated NUL terminated string that contains the encoded descriptor as
2797 * Return 0 on success and encoded_out is a valid pointer. On error, -1 is
2798 * returned and encoded_out is set to NULL. */
2800 hs_desc_encode_descriptor
,(const hs_descriptor_t
*desc
,
2801 const ed25519_keypair_t
*signing_kp
,
2802 const uint8_t *descriptor_cookie
,
2803 char **encoded_out
))
2809 tor_assert(encoded_out
);
2811 /* Make sure we support the version of the descriptor format. */
2812 version
= desc
->plaintext_data
.version
;
2813 if (!hs_desc_is_supported_version(version
)) {
2816 /* Extra precaution. Having no handler for the supported version should
2817 * never happened else we forgot to add it but we bumped the version. */
2818 tor_assert(ARRAY_LENGTH(encode_handlers
) >= version
);
2819 tor_assert(encode_handlers
[version
]);
2821 ret
= encode_handlers
[version
](desc
, signing_kp
,
2822 descriptor_cookie
, encoded_out
);
2827 /* Try to decode what we just encoded. Symmetry is nice!, but it is
2828 * symmetric only if the client auth is disabled (That is, the descriptor
2829 * cookie will be NULL) and the test-only mock plaintext isn't in use. */
2830 bool do_round_trip_test
= !descriptor_cookie
;
2831 #ifdef TOR_UNIT_TESTS
2832 if (desc
->encrypted_data
.test_extra_plaintext
) {
2833 do_round_trip_test
= false;
2836 if (do_round_trip_test
) {
2837 ret
= hs_desc_decode_descriptor(*encoded_out
, &desc
->subcredential
,
2839 if (BUG(ret
!= HS_DESC_DECODE_OK
)) {
2848 *encoded_out
= NULL
;
2852 /** Free the content of the plaintext section of a descriptor. */
2854 hs_desc_plaintext_data_free_contents(hs_desc_plaintext_data_t
*desc
)
2860 if (desc
->superencrypted_blob
) {
2861 tor_free(desc
->superencrypted_blob
);
2863 tor_cert_free(desc
->signing_key_cert
);
2865 memwipe(desc
, 0, sizeof(*desc
));
2868 /** Free the content of the superencrypted section of a descriptor. */
2870 hs_desc_superencrypted_data_free_contents(hs_desc_superencrypted_data_t
*desc
)
2876 if (desc
->encrypted_blob
) {
2877 tor_free(desc
->encrypted_blob
);
2879 if (desc
->clients
) {
2880 SMARTLIST_FOREACH(desc
->clients
, hs_desc_authorized_client_t
*, client
,
2881 hs_desc_authorized_client_free(client
));
2882 smartlist_free(desc
->clients
);
2885 memwipe(desc
, 0, sizeof(*desc
));
2888 /** Free the content of the encrypted section of a descriptor. */
2890 hs_desc_encrypted_data_free_contents(hs_desc_encrypted_data_t
*desc
)
2896 if (desc
->intro_auth_types
) {
2897 SMARTLIST_FOREACH(desc
->intro_auth_types
, char *, a
, tor_free(a
));
2898 smartlist_free(desc
->intro_auth_types
);
2900 if (desc
->intro_points
) {
2901 SMARTLIST_FOREACH(desc
->intro_points
, hs_desc_intro_point_t
*, ip
,
2902 hs_desc_intro_point_free(ip
));
2903 smartlist_free(desc
->intro_points
);
2905 tor_free(desc
->flow_control_pv
);
2906 tor_free(desc
->pow_params
);
2907 memwipe(desc
, 0, sizeof(*desc
));
2910 /** Free the descriptor plaintext data object. */
2912 hs_desc_plaintext_data_free_(hs_desc_plaintext_data_t
*desc
)
2914 hs_desc_plaintext_data_free_contents(desc
);
2918 /** Free the descriptor plaintext data object. */
2920 hs_desc_superencrypted_data_free_(hs_desc_superencrypted_data_t
*desc
)
2922 hs_desc_superencrypted_data_free_contents(desc
);
2926 /** Free the descriptor encrypted data object. */
2928 hs_desc_encrypted_data_free_(hs_desc_encrypted_data_t
*desc
)
2930 hs_desc_encrypted_data_free_contents(desc
);
2934 /** Free the given descriptor object. */
2936 hs_descriptor_free_(hs_descriptor_t
*desc
)
2942 hs_desc_plaintext_data_free_contents(&desc
->plaintext_data
);
2943 hs_desc_superencrypted_data_free_contents(&desc
->superencrypted_data
);
2944 hs_desc_encrypted_data_free_contents(&desc
->encrypted_data
);
2948 /** Return the size in bytes of the given plaintext data object. A sizeof() is
2949 * not enough because the object contains pointers and the encrypted blob.
2950 * This is particularly useful for our OOM subsystem that tracks the HSDir
2951 * cache size for instance. */
2953 hs_desc_plaintext_obj_size(const hs_desc_plaintext_data_t
*data
)
2956 return (sizeof(*data
) + sizeof(*data
->signing_key_cert
) +
2957 data
->superencrypted_blob_size
);
2960 /** Return the size in bytes of the given encrypted data object. Used by OOM
2963 hs_desc_encrypted_obj_size(const hs_desc_encrypted_data_t
*data
)
2966 size_t intro_size
= 0;
2967 if (data
->intro_auth_types
) {
2969 smartlist_len(data
->intro_auth_types
) * sizeof(intro_auth_types
);
2971 if (data
->intro_points
) {
2972 /* XXX could follow pointers here and get more accurate size */
2974 smartlist_len(data
->intro_points
) * sizeof(hs_desc_intro_point_t
);
2977 return sizeof(*data
) + intro_size
;
2980 /** Return the size in bytes of the given descriptor object. Used by OOM
2983 hs_desc_obj_size(const hs_descriptor_t
*data
)
2988 return (hs_desc_plaintext_obj_size(&data
->plaintext_data
) +
2989 hs_desc_encrypted_obj_size(&data
->encrypted_data
) +
2990 sizeof(data
->subcredential
));
2993 /** Return a newly allocated descriptor intro point. */
2994 hs_desc_intro_point_t
*
2995 hs_desc_intro_point_new(void)
2997 hs_desc_intro_point_t
*ip
= tor_malloc_zero(sizeof(*ip
));
2998 ip
->link_specifiers
= smartlist_new();
3002 /** Free a descriptor intro point object. */
3004 hs_desc_intro_point_free_(hs_desc_intro_point_t
*ip
)
3009 if (ip
->link_specifiers
) {
3010 SMARTLIST_FOREACH(ip
->link_specifiers
, link_specifier_t
*,
3011 ls
, link_specifier_free(ls
));
3012 smartlist_free(ip
->link_specifiers
);
3014 tor_cert_free(ip
->auth_key_cert
);
3015 tor_cert_free(ip
->enc_key_cert
);
3016 crypto_pk_free(ip
->legacy
.key
);
3017 tor_free(ip
->legacy
.cert
.encoded
);
3021 /** Allocate and build a new fake client info for the descriptor. Return a
3022 * newly allocated object. This can't fail. */
3023 hs_desc_authorized_client_t
*
3024 hs_desc_build_fake_authorized_client(void)
3026 hs_desc_authorized_client_t
*client_auth
=
3027 tor_malloc_zero(sizeof(*client_auth
));
3029 crypto_rand((char *) client_auth
->client_id
,
3030 sizeof(client_auth
->client_id
));
3031 crypto_rand((char *) client_auth
->iv
,
3032 sizeof(client_auth
->iv
));
3033 crypto_rand((char *) client_auth
->encrypted_cookie
,
3034 sizeof(client_auth
->encrypted_cookie
));
3039 /** Using the service's subcredential, client public key, auth ephemeral secret
3040 * key, and descriptor cookie, build the auth client so we can then encode the
3041 * descriptor for publication. client_out must be already allocated. */
3043 hs_desc_build_authorized_client(const hs_subcredential_t
*subcredential
,
3044 const curve25519_public_key_t
*client_auth_pk
,
3045 const curve25519_secret_key_t
*
3047 const uint8_t *descriptor_cookie
,
3048 hs_desc_authorized_client_t
*client_out
)
3050 uint8_t *keystream
= NULL
;
3051 size_t keystream_length
= 0;
3052 const uint8_t *cookie_key
;
3053 crypto_cipher_t
*cipher
;
3055 tor_assert(client_auth_pk
);
3056 tor_assert(auth_ephemeral_sk
);
3057 tor_assert(descriptor_cookie
);
3058 tor_assert(client_out
);
3059 tor_assert(subcredential
);
3060 tor_assert(!fast_mem_is_zero((char *) auth_ephemeral_sk
,
3061 sizeof(*auth_ephemeral_sk
)));
3062 tor_assert(!fast_mem_is_zero((char *) client_auth_pk
,
3063 sizeof(*client_auth_pk
)));
3064 tor_assert(!fast_mem_is_zero((char *) descriptor_cookie
,
3065 HS_DESC_DESCRIPTOR_COOKIE_LEN
));
3066 tor_assert(!fast_mem_is_zero((char *) subcredential
,
3069 /* Get the KEYS part so we can derive the CLIENT-ID and COOKIE-KEY. */
3071 build_descriptor_cookie_keys(subcredential
,
3072 auth_ephemeral_sk
, client_auth_pk
,
3074 tor_assert(keystream_length
> 0);
3076 /* Extract the CLIENT-ID and COOKIE-KEY from the KEYS. */
3077 memcpy(client_out
->client_id
, keystream
, HS_DESC_CLIENT_ID_LEN
);
3078 cookie_key
= keystream
+ HS_DESC_CLIENT_ID_LEN
;
3081 crypto_strongest_rand(client_out
->iv
, sizeof(client_out
->iv
));
3083 /* This creates a cipher for AES. It can't fail. */
3084 cipher
= crypto_cipher_new_with_iv_and_bits(cookie_key
, client_out
->iv
,
3085 HS_DESC_COOKIE_KEY_BIT_SIZE
);
3086 /* This can't fail. */
3087 crypto_cipher_encrypt(cipher
, (char *) client_out
->encrypted_cookie
,
3088 (const char *) descriptor_cookie
,
3089 HS_DESC_DESCRIPTOR_COOKIE_LEN
);
3091 memwipe(keystream
, 0, keystream_length
);
3092 tor_free(keystream
);
3094 crypto_cipher_free(cipher
);
3097 /** Free an authoriezd client object. */
3099 hs_desc_authorized_client_free_(hs_desc_authorized_client_t
*client
)
3104 /** From the given descriptor, remove and free every introduction point. */
3106 hs_descriptor_clear_intro_points(hs_descriptor_t
*desc
)
3112 ips
= desc
->encrypted_data
.intro_points
;
3114 SMARTLIST_FOREACH(ips
, hs_desc_intro_point_t
*,
3115 ip
, hs_desc_intro_point_free(ip
));
3116 smartlist_clear(ips
);
3120 /** Return true iff we support the given descriptor congestion control
3123 hs_desc_supports_congestion_control(const hs_descriptor_t
*desc
)
3127 /* Validate that we support the protocol version in the descriptor. */
3128 return desc
->encrypted_data
.flow_control_pv
&&
3129 protocol_list_supports_protocol(desc
->encrypted_data
.flow_control_pv
,
3130 PRT_FLOWCTRL
, PROTOVER_FLOWCTRL_CC
);