minor updates on upcoming changelog
[tor.git] / src / or / hs_descriptor.c
blob1708866944e47f2b65816ee60a07c18ffe63714f
1 /* Copyright (c) 2016-2017, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
4 /**
5 * \file hs_descriptor.c
6 * \brief Handle hidden service descriptor encoding/decoding.
8 * \details
9 * Here is a graphical depiction of an HS descriptor and its layers:
11 * +------------------------------------------------------+
12 * |DESCRIPTOR HEADER: |
13 * | hs-descriptor 3 |
14 * | descriptor-lifetime 180 |
15 * | ... |
16 * | superencrypted |
17 * |+---------------------------------------------------+ |
18 * ||SUPERENCRYPTED LAYER (aka OUTER ENCRYPTED LAYER): | |
19 * || desc-auth-type x25519 | |
20 * || desc-auth-ephemeral-key | |
21 * || auth-client | |
22 * || auth-client | |
23 * || ... | |
24 * || encrypted | |
25 * ||+-------------------------------------------------+| |
26 * |||ENCRYPTED LAYER (aka INNER ENCRYPTED LAYER): || |
27 * ||| create2-formats || |
28 * ||| intro-auth-required || |
29 * ||| introduction-point || |
30 * ||| introduction-point || |
31 * ||| ... || |
32 * ||+-------------------------------------------------+| |
33 * |+---------------------------------------------------+ |
34 * +------------------------------------------------------+
36 * The DESCRIPTOR HEADER section is completely unencrypted and contains generic
37 * descriptor metadata.
39 * The SUPERENCRYPTED LAYER section is the first layer of encryption, and it's
40 * encrypted using the blinded public key of the hidden service to protect
41 * against entities who don't know its onion address. The clients of the hidden
42 * service know its onion address and blinded public key, whereas third-parties
43 * (like HSDirs) don't know it (except if it's a public hidden service).
45 * The ENCRYPTED LAYER section is the second layer of encryption, and it's
46 * encrypted using the client authorization key material (if those exist). When
47 * client authorization is enabled, this second layer of encryption protects
48 * the descriptor content from unauthorized entities. If client authorization
49 * is disabled, this second layer of encryption does not provide any extra
50 * security but is still present. The plaintext of this layer contains all the
51 * information required to connect to the hidden service like its list of
52 * introduction points.
53 **/
55 /* For unit tests.*/
56 #define HS_DESCRIPTOR_PRIVATE
58 #include "or.h"
59 #include "ed25519_cert.h" /* Trunnel interface. */
60 #include "hs_descriptor.h"
61 #include "circuitbuild.h"
62 #include "parsecommon.h"
63 #include "rendcache.h"
64 #include "hs_cache.h"
65 #include "hs_config.h"
66 #include "torcert.h" /* tor_cert_encode_ed22519() */
68 /* Constant string value used for the descriptor format. */
69 #define str_hs_desc "hs-descriptor"
70 #define str_desc_cert "descriptor-signing-key-cert"
71 #define str_rev_counter "revision-counter"
72 #define str_superencrypted "superencrypted"
73 #define str_encrypted "encrypted"
74 #define str_signature "signature"
75 #define str_lifetime "descriptor-lifetime"
76 /* Constant string value for the encrypted part of the descriptor. */
77 #define str_create2_formats "create2-formats"
78 #define str_intro_auth_required "intro-auth-required"
79 #define str_single_onion "single-onion-service"
80 #define str_intro_point "introduction-point"
81 #define str_ip_onion_key "onion-key"
82 #define str_ip_auth_key "auth-key"
83 #define str_ip_enc_key "enc-key"
84 #define str_ip_enc_key_cert "enc-key-cert"
85 #define str_ip_legacy_key "legacy-key"
86 #define str_ip_legacy_key_cert "legacy-key-cert"
87 #define str_intro_point_start "\n" str_intro_point " "
88 /* Constant string value for the construction to encrypt the encrypted data
89 * section. */
90 #define str_enc_const_superencryption "hsdir-superencrypted-data"
91 #define str_enc_const_encryption "hsdir-encrypted-data"
92 /* Prefix required to compute/verify HS desc signatures */
93 #define str_desc_sig_prefix "Tor onion service descriptor sig v3"
94 #define str_desc_auth_type "desc-auth-type"
95 #define str_desc_auth_key "desc-auth-ephemeral-key"
96 #define str_desc_auth_client "auth-client"
97 #define str_encrypted "encrypted"
99 /* Authentication supported types. */
100 static const struct {
101 hs_desc_auth_type_t type;
102 const char *identifier;
103 } intro_auth_types[] = {
104 { HS_DESC_AUTH_ED25519, "ed25519" },
105 /* Indicate end of array. */
106 { 0, NULL }
109 /* Descriptor ruleset. */
110 static token_rule_t hs_desc_v3_token_table[] = {
111 T1_START(str_hs_desc, R_HS_DESCRIPTOR, EQ(1), NO_OBJ),
112 T1(str_lifetime, R3_DESC_LIFETIME, EQ(1), NO_OBJ),
113 T1(str_desc_cert, R3_DESC_SIGNING_CERT, NO_ARGS, NEED_OBJ),
114 T1(str_rev_counter, R3_REVISION_COUNTER, EQ(1), NO_OBJ),
115 T1(str_superencrypted, R3_SUPERENCRYPTED, NO_ARGS, NEED_OBJ),
116 T1_END(str_signature, R3_SIGNATURE, EQ(1), NO_OBJ),
117 END_OF_TABLE
120 /* Descriptor ruleset for the superencrypted section. */
121 static token_rule_t hs_desc_superencrypted_v3_token_table[] = {
122 T1_START(str_desc_auth_type, R3_DESC_AUTH_TYPE, GE(1), NO_OBJ),
123 T1(str_desc_auth_key, R3_DESC_AUTH_KEY, GE(1), NO_OBJ),
124 T1N(str_desc_auth_client, R3_DESC_AUTH_CLIENT, GE(3), NO_OBJ),
125 T1(str_encrypted, R3_ENCRYPTED, NO_ARGS, NEED_OBJ),
126 END_OF_TABLE
129 /* Descriptor ruleset for the encrypted section. */
130 static token_rule_t hs_desc_encrypted_v3_token_table[] = {
131 T1_START(str_create2_formats, R3_CREATE2_FORMATS, CONCAT_ARGS, NO_OBJ),
132 T01(str_intro_auth_required, R3_INTRO_AUTH_REQUIRED, ARGS, NO_OBJ),
133 T01(str_single_onion, R3_SINGLE_ONION_SERVICE, ARGS, NO_OBJ),
134 END_OF_TABLE
137 /* Descriptor ruleset for the introduction points section. */
138 static token_rule_t hs_desc_intro_point_v3_token_table[] = {
139 T1_START(str_intro_point, R3_INTRODUCTION_POINT, EQ(1), NO_OBJ),
140 T1N(str_ip_onion_key, R3_INTRO_ONION_KEY, GE(2), OBJ_OK),
141 T1(str_ip_auth_key, R3_INTRO_AUTH_KEY, NO_ARGS, NEED_OBJ),
142 T1(str_ip_enc_key, R3_INTRO_ENC_KEY, GE(2), OBJ_OK),
143 T1(str_ip_enc_key_cert, R3_INTRO_ENC_KEY_CERT, ARGS, OBJ_OK),
144 T01(str_ip_legacy_key, R3_INTRO_LEGACY_KEY, ARGS, NEED_KEY_1024),
145 T01(str_ip_legacy_key_cert, R3_INTRO_LEGACY_KEY_CERT, ARGS, OBJ_OK),
146 END_OF_TABLE
149 /* Free the content of the plaintext section of a descriptor. */
150 STATIC void
151 desc_plaintext_data_free_contents(hs_desc_plaintext_data_t *desc)
153 if (!desc) {
154 return;
157 if (desc->superencrypted_blob) {
158 tor_free(desc->superencrypted_blob);
160 tor_cert_free(desc->signing_key_cert);
162 memwipe(desc, 0, sizeof(*desc));
165 /* Free the content of the encrypted section of a descriptor. */
166 static void
167 desc_encrypted_data_free_contents(hs_desc_encrypted_data_t *desc)
169 if (!desc) {
170 return;
173 if (desc->intro_auth_types) {
174 SMARTLIST_FOREACH(desc->intro_auth_types, char *, a, tor_free(a));
175 smartlist_free(desc->intro_auth_types);
177 if (desc->intro_points) {
178 SMARTLIST_FOREACH(desc->intro_points, hs_desc_intro_point_t *, ip,
179 hs_desc_intro_point_free(ip));
180 smartlist_free(desc->intro_points);
182 memwipe(desc, 0, sizeof(*desc));
185 /* Using a key, salt and encrypted payload, build a MAC and put it in mac_out.
186 * We use SHA3-256 for the MAC computation.
187 * This function can't fail. */
188 static void
189 build_mac(const uint8_t *mac_key, size_t mac_key_len,
190 const uint8_t *salt, size_t salt_len,
191 const uint8_t *encrypted, size_t encrypted_len,
192 uint8_t *mac_out, size_t mac_len)
194 crypto_digest_t *digest;
196 const uint64_t mac_len_netorder = tor_htonll(mac_key_len);
197 const uint64_t salt_len_netorder = tor_htonll(salt_len);
199 tor_assert(mac_key);
200 tor_assert(salt);
201 tor_assert(encrypted);
202 tor_assert(mac_out);
204 digest = crypto_digest256_new(DIGEST_SHA3_256);
205 /* As specified in section 2.5 of proposal 224, first add the mac key
206 * then add the salt first and then the encrypted section. */
208 crypto_digest_add_bytes(digest, (const char *) &mac_len_netorder, 8);
209 crypto_digest_add_bytes(digest, (const char *) mac_key, mac_key_len);
210 crypto_digest_add_bytes(digest, (const char *) &salt_len_netorder, 8);
211 crypto_digest_add_bytes(digest, (const char *) salt, salt_len);
212 crypto_digest_add_bytes(digest, (const char *) encrypted, encrypted_len);
213 crypto_digest_get_digest(digest, (char *) mac_out, mac_len);
214 crypto_digest_free(digest);
217 /* Using a given decriptor object, build the secret input needed for the
218 * KDF and put it in the dst pointer which is an already allocated buffer
219 * of size dstlen. */
220 static void
221 build_secret_input(const hs_descriptor_t *desc, uint8_t *dst, size_t dstlen)
223 size_t offset = 0;
225 tor_assert(desc);
226 tor_assert(dst);
227 tor_assert(HS_DESC_ENCRYPTED_SECRET_INPUT_LEN <= dstlen);
229 /* XXX use the destination length as the memcpy length */
230 /* Copy blinded public key. */
231 memcpy(dst, desc->plaintext_data.blinded_pubkey.pubkey,
232 sizeof(desc->plaintext_data.blinded_pubkey.pubkey));
233 offset += sizeof(desc->plaintext_data.blinded_pubkey.pubkey);
234 /* Copy subcredential. */
235 memcpy(dst + offset, desc->subcredential, sizeof(desc->subcredential));
236 offset += sizeof(desc->subcredential);
237 /* Copy revision counter value. */
238 set_uint64(dst + offset, tor_htonll(desc->plaintext_data.revision_counter));
239 offset += sizeof(uint64_t);
240 tor_assert(HS_DESC_ENCRYPTED_SECRET_INPUT_LEN == offset);
243 /* Do the KDF construction and put the resulting data in key_out which is of
244 * key_out_len length. It uses SHAKE-256 as specified in the spec. */
245 static void
246 build_kdf_key(const hs_descriptor_t *desc,
247 const uint8_t *salt, size_t salt_len,
248 uint8_t *key_out, size_t key_out_len,
249 int is_superencrypted_layer)
251 uint8_t secret_input[HS_DESC_ENCRYPTED_SECRET_INPUT_LEN];
252 crypto_xof_t *xof;
254 tor_assert(desc);
255 tor_assert(salt);
256 tor_assert(key_out);
258 /* Build the secret input for the KDF computation. */
259 build_secret_input(desc, secret_input, sizeof(secret_input));
261 xof = crypto_xof_new();
262 /* Feed our KDF. [SHAKE it like a polaroid picture --Yawning]. */
263 crypto_xof_add_bytes(xof, secret_input, sizeof(secret_input));
264 crypto_xof_add_bytes(xof, salt, salt_len);
266 /* Feed in the right string constant based on the desc layer */
267 if (is_superencrypted_layer) {
268 crypto_xof_add_bytes(xof, (const uint8_t *) str_enc_const_superencryption,
269 strlen(str_enc_const_superencryption));
270 } else {
271 crypto_xof_add_bytes(xof, (const uint8_t *) str_enc_const_encryption,
272 strlen(str_enc_const_encryption));
275 /* Eat from our KDF. */
276 crypto_xof_squeeze_bytes(xof, key_out, key_out_len);
277 crypto_xof_free(xof);
278 memwipe(secret_input, 0, sizeof(secret_input));
281 /* Using the given descriptor and salt, run it through our KDF function and
282 * then extract a secret key in key_out, the IV in iv_out and MAC in mac_out.
283 * This function can't fail. */
284 static void
285 build_secret_key_iv_mac(const hs_descriptor_t *desc,
286 const uint8_t *salt, size_t salt_len,
287 uint8_t *key_out, size_t key_len,
288 uint8_t *iv_out, size_t iv_len,
289 uint8_t *mac_out, size_t mac_len,
290 int is_superencrypted_layer)
292 size_t offset = 0;
293 uint8_t kdf_key[HS_DESC_ENCRYPTED_KDF_OUTPUT_LEN];
295 tor_assert(desc);
296 tor_assert(salt);
297 tor_assert(key_out);
298 tor_assert(iv_out);
299 tor_assert(mac_out);
301 build_kdf_key(desc, salt, salt_len, kdf_key, sizeof(kdf_key),
302 is_superencrypted_layer);
303 /* Copy the bytes we need for both the secret key and IV. */
304 memcpy(key_out, kdf_key, key_len);
305 offset += key_len;
306 memcpy(iv_out, kdf_key + offset, iv_len);
307 offset += iv_len;
308 memcpy(mac_out, kdf_key + offset, mac_len);
309 /* Extra precaution to make sure we are not out of bound. */
310 tor_assert((offset + mac_len) == sizeof(kdf_key));
311 memwipe(kdf_key, 0, sizeof(kdf_key));
314 /* === ENCODING === */
316 /* Encode the given link specifier objects into a newly allocated string.
317 * This can't fail so caller can always assume a valid string being
318 * returned. */
319 STATIC char *
320 encode_link_specifiers(const smartlist_t *specs)
322 char *encoded_b64 = NULL;
323 link_specifier_list_t *lslist = link_specifier_list_new();
325 tor_assert(specs);
326 /* No link specifiers is a code flow error, can't happen. */
327 tor_assert(smartlist_len(specs) > 0);
328 tor_assert(smartlist_len(specs) <= UINT8_MAX);
330 link_specifier_list_set_n_spec(lslist, smartlist_len(specs));
332 SMARTLIST_FOREACH_BEGIN(specs, const hs_desc_link_specifier_t *,
333 spec) {
334 link_specifier_t *ls = hs_desc_lspec_to_trunnel(spec);
335 if (ls) {
336 link_specifier_list_add_spec(lslist, ls);
338 } SMARTLIST_FOREACH_END(spec);
341 uint8_t *encoded;
342 ssize_t encoded_len, encoded_b64_len, ret;
344 encoded_len = link_specifier_list_encoded_len(lslist);
345 tor_assert(encoded_len > 0);
346 encoded = tor_malloc_zero(encoded_len);
347 ret = link_specifier_list_encode(encoded, encoded_len, lslist);
348 tor_assert(ret == encoded_len);
350 /* Base64 encode our binary format. Add extra NUL byte for the base64
351 * encoded value. */
352 encoded_b64_len = base64_encode_size(encoded_len, 0) + 1;
353 encoded_b64 = tor_malloc_zero(encoded_b64_len);
354 ret = base64_encode(encoded_b64, encoded_b64_len, (const char *) encoded,
355 encoded_len, 0);
356 tor_assert(ret == (encoded_b64_len - 1));
357 tor_free(encoded);
360 link_specifier_list_free(lslist);
361 return encoded_b64;
364 /* Encode an introduction point legacy key and certificate. Return a newly
365 * allocated string with it. On failure, return NULL. */
366 static char *
367 encode_legacy_key(const hs_desc_intro_point_t *ip)
369 char *key_str, b64_cert[256], *encoded = NULL;
370 size_t key_str_len;
372 tor_assert(ip);
374 /* Encode cross cert. */
375 if (base64_encode(b64_cert, sizeof(b64_cert),
376 (const char *) ip->legacy.cert.encoded,
377 ip->legacy.cert.len, BASE64_ENCODE_MULTILINE) < 0) {
378 log_warn(LD_REND, "Unable to encode legacy crosscert.");
379 goto done;
381 /* Convert the encryption key to PEM format NUL terminated. */
382 if (crypto_pk_write_public_key_to_string(ip->legacy.key, &key_str,
383 &key_str_len) < 0) {
384 log_warn(LD_REND, "Unable to encode legacy encryption key.");
385 goto done;
387 tor_asprintf(&encoded,
388 "%s \n%s" /* Newline is added by the call above. */
389 "%s\n"
390 "-----BEGIN CROSSCERT-----\n"
391 "%s"
392 "-----END CROSSCERT-----",
393 str_ip_legacy_key, key_str,
394 str_ip_legacy_key_cert, b64_cert);
395 tor_free(key_str);
397 done:
398 return encoded;
401 /* Encode an introduction point encryption key and certificate. Return a newly
402 * allocated string with it. On failure, return NULL. */
403 static char *
404 encode_enc_key(const hs_desc_intro_point_t *ip)
406 char *encoded = NULL, *encoded_cert;
407 char key_b64[CURVE25519_BASE64_PADDED_LEN + 1];
409 tor_assert(ip);
411 /* Base64 encode the encryption key for the "enc-key" field. */
412 if (curve25519_public_to_base64(key_b64, &ip->enc_key) < 0) {
413 goto done;
415 if (tor_cert_encode_ed22519(ip->enc_key_cert, &encoded_cert) < 0) {
416 goto done;
418 tor_asprintf(&encoded,
419 "%s ntor %s\n"
420 "%s\n%s",
421 str_ip_enc_key, key_b64,
422 str_ip_enc_key_cert, encoded_cert);
423 tor_free(encoded_cert);
425 done:
426 return encoded;
429 /* Encode an introduction point onion key. Return a newly allocated string
430 * with it. On failure, return NULL. */
431 static char *
432 encode_onion_key(const hs_desc_intro_point_t *ip)
434 char *encoded = NULL;
435 char key_b64[CURVE25519_BASE64_PADDED_LEN + 1];
437 tor_assert(ip);
439 /* Base64 encode the encryption key for the "onion-key" field. */
440 if (curve25519_public_to_base64(key_b64, &ip->onion_key) < 0) {
441 goto done;
443 tor_asprintf(&encoded, "%s ntor %s", str_ip_onion_key, key_b64);
445 done:
446 return encoded;
449 /* Encode an introduction point object and return a newly allocated string
450 * with it. On failure, return NULL. */
451 static char *
452 encode_intro_point(const ed25519_public_key_t *sig_key,
453 const hs_desc_intro_point_t *ip)
455 char *encoded_ip = NULL;
456 smartlist_t *lines = smartlist_new();
458 tor_assert(ip);
459 tor_assert(sig_key);
461 /* Encode link specifier. */
463 char *ls_str = encode_link_specifiers(ip->link_specifiers);
464 smartlist_add_asprintf(lines, "%s %s", str_intro_point, ls_str);
465 tor_free(ls_str);
468 /* Onion key encoding. */
470 char *encoded_onion_key = encode_onion_key(ip);
471 if (encoded_onion_key == NULL) {
472 goto err;
474 smartlist_add_asprintf(lines, "%s", encoded_onion_key);
475 tor_free(encoded_onion_key);
478 /* Authentication key encoding. */
480 char *encoded_cert;
481 if (tor_cert_encode_ed22519(ip->auth_key_cert, &encoded_cert) < 0) {
482 goto err;
484 smartlist_add_asprintf(lines, "%s\n%s", str_ip_auth_key, encoded_cert);
485 tor_free(encoded_cert);
488 /* Encryption key encoding. */
490 char *encoded_enc_key = encode_enc_key(ip);
491 if (encoded_enc_key == NULL) {
492 goto err;
494 smartlist_add_asprintf(lines, "%s", encoded_enc_key);
495 tor_free(encoded_enc_key);
498 /* Legacy key if any. */
499 if (ip->legacy.key != NULL) {
500 /* Strong requirement else the IP creation was badly done. */
501 tor_assert(ip->legacy.cert.encoded);
502 char *encoded_legacy_key = encode_legacy_key(ip);
503 if (encoded_legacy_key == NULL) {
504 goto err;
506 smartlist_add_asprintf(lines, "%s", encoded_legacy_key);
507 tor_free(encoded_legacy_key);
510 /* Join them all in one blob of text. */
511 encoded_ip = smartlist_join_strings(lines, "\n", 1, NULL);
513 err:
514 SMARTLIST_FOREACH(lines, char *, l, tor_free(l));
515 smartlist_free(lines);
516 return encoded_ip;
519 /* Given a source length, return the new size including padding for the
520 * plaintext encryption. */
521 static size_t
522 compute_padded_plaintext_length(size_t plaintext_len)
524 size_t plaintext_padded_len;
525 const int padding_block_length = HS_DESC_SUPERENC_PLAINTEXT_PAD_MULTIPLE;
527 /* Make sure we won't overflow. */
528 tor_assert(plaintext_len <= (SIZE_T_CEILING - padding_block_length));
530 /* Get the extra length we need to add. For example, if srclen is 10200
531 * bytes, this will expand to (2 * 10k) == 20k thus an extra 9800 bytes. */
532 plaintext_padded_len = CEIL_DIV(plaintext_len, padding_block_length) *
533 padding_block_length;
534 /* Can never be extra careful. Make sure we are _really_ padded. */
535 tor_assert(!(plaintext_padded_len % padding_block_length));
536 return plaintext_padded_len;
539 /* Given a buffer, pad it up to the encrypted section padding requirement. Set
540 * the newly allocated string in padded_out and return the length of the
541 * padded buffer. */
542 STATIC size_t
543 build_plaintext_padding(const char *plaintext, size_t plaintext_len,
544 uint8_t **padded_out)
546 size_t padded_len;
547 uint8_t *padded;
549 tor_assert(plaintext);
550 tor_assert(padded_out);
552 /* Allocate the final length including padding. */
553 padded_len = compute_padded_plaintext_length(plaintext_len);
554 tor_assert(padded_len >= plaintext_len);
555 padded = tor_malloc_zero(padded_len);
557 memcpy(padded, plaintext, plaintext_len);
558 *padded_out = padded;
559 return padded_len;
562 /* Using a key, IV and plaintext data of length plaintext_len, create the
563 * encrypted section by encrypting it and setting encrypted_out with the
564 * data. Return size of the encrypted data buffer. */
565 static size_t
566 build_encrypted(const uint8_t *key, const uint8_t *iv, const char *plaintext,
567 size_t plaintext_len, uint8_t **encrypted_out,
568 int is_superencrypted_layer)
570 size_t encrypted_len;
571 uint8_t *padded_plaintext, *encrypted;
572 crypto_cipher_t *cipher;
574 tor_assert(key);
575 tor_assert(iv);
576 tor_assert(plaintext);
577 tor_assert(encrypted_out);
579 /* If we are encrypting the middle layer of the descriptor, we need to first
580 pad the plaintext */
581 if (is_superencrypted_layer) {
582 encrypted_len = build_plaintext_padding(plaintext, plaintext_len,
583 &padded_plaintext);
584 /* Extra precautions that we have a valid padding length. */
585 tor_assert(!(encrypted_len % HS_DESC_SUPERENC_PLAINTEXT_PAD_MULTIPLE));
586 } else { /* No padding required for inner layers */
587 padded_plaintext = tor_memdup(plaintext, plaintext_len);
588 encrypted_len = plaintext_len;
591 /* This creates a cipher for AES. It can't fail. */
592 cipher = crypto_cipher_new_with_iv_and_bits(key, iv,
593 HS_DESC_ENCRYPTED_BIT_SIZE);
594 /* We use a stream cipher so the encrypted length will be the same as the
595 * plaintext padded length. */
596 encrypted = tor_malloc_zero(encrypted_len);
597 /* This can't fail. */
598 crypto_cipher_encrypt(cipher, (char *) encrypted,
599 (const char *) padded_plaintext, encrypted_len);
600 *encrypted_out = encrypted;
601 /* Cleanup. */
602 crypto_cipher_free(cipher);
603 tor_free(padded_plaintext);
604 return encrypted_len;
607 /* Encrypt the given <b>plaintext</b> buffer using <b>desc</b> to get the
608 * keys. Set encrypted_out with the encrypted data and return the length of
609 * it. <b>is_superencrypted_layer</b> is set if this is the outer encrypted
610 * layer of the descriptor. */
611 static size_t
612 encrypt_descriptor_data(const hs_descriptor_t *desc, const char *plaintext,
613 char **encrypted_out, int is_superencrypted_layer)
615 char *final_blob;
616 size_t encrypted_len, final_blob_len, offset = 0;
617 uint8_t *encrypted;
618 uint8_t salt[HS_DESC_ENCRYPTED_SALT_LEN];
619 uint8_t secret_key[HS_DESC_ENCRYPTED_KEY_LEN], secret_iv[CIPHER_IV_LEN];
620 uint8_t mac_key[DIGEST256_LEN], mac[DIGEST256_LEN];
622 tor_assert(desc);
623 tor_assert(plaintext);
624 tor_assert(encrypted_out);
626 /* Get our salt. The returned bytes are already hashed. */
627 crypto_strongest_rand(salt, sizeof(salt));
629 /* KDF construction resulting in a key from which the secret key, IV and MAC
630 * key are extracted which is what we need for the encryption. */
631 build_secret_key_iv_mac(desc, salt, sizeof(salt),
632 secret_key, sizeof(secret_key),
633 secret_iv, sizeof(secret_iv),
634 mac_key, sizeof(mac_key),
635 is_superencrypted_layer);
637 /* Build the encrypted part that is do the actual encryption. */
638 encrypted_len = build_encrypted(secret_key, secret_iv, plaintext,
639 strlen(plaintext), &encrypted,
640 is_superencrypted_layer);
641 memwipe(secret_key, 0, sizeof(secret_key));
642 memwipe(secret_iv, 0, sizeof(secret_iv));
643 /* This construction is specified in section 2.5 of proposal 224. */
644 final_blob_len = sizeof(salt) + encrypted_len + DIGEST256_LEN;
645 final_blob = tor_malloc_zero(final_blob_len);
647 /* Build the MAC. */
648 build_mac(mac_key, sizeof(mac_key), salt, sizeof(salt),
649 encrypted, encrypted_len, mac, sizeof(mac));
650 memwipe(mac_key, 0, sizeof(mac_key));
652 /* The salt is the first value. */
653 memcpy(final_blob, salt, sizeof(salt));
654 offset = sizeof(salt);
655 /* Second value is the encrypted data. */
656 memcpy(final_blob + offset, encrypted, encrypted_len);
657 offset += encrypted_len;
658 /* Third value is the MAC. */
659 memcpy(final_blob + offset, mac, sizeof(mac));
660 offset += sizeof(mac);
661 /* Cleanup the buffers. */
662 memwipe(salt, 0, sizeof(salt));
663 memwipe(encrypted, 0, encrypted_len);
664 tor_free(encrypted);
665 /* Extra precaution. */
666 tor_assert(offset == final_blob_len);
668 *encrypted_out = final_blob;
669 return final_blob_len;
672 /* Create and return a string containing a fake client-auth entry. It's the
673 * responsibility of the caller to free the returned string. This function will
674 * never fail. */
675 static char *
676 get_fake_auth_client_str(void)
678 char *auth_client_str = NULL;
679 /* We are gonna fill these arrays with fake base64 data. They are all double
680 * the size of their binary representation to fit the base64 overhead. */
681 char client_id_b64[8*2];
682 char iv_b64[16*2];
683 char encrypted_cookie_b64[16*2];
684 int retval;
686 /* This is a macro to fill a field with random data and then base64 it. */
687 #define FILL_WITH_FAKE_DATA_AND_BASE64(field) STMT_BEGIN \
688 crypto_rand((char *)field, sizeof(field)); \
689 retval = base64_encode_nopad(field##_b64, sizeof(field##_b64), \
690 field, sizeof(field)); \
691 tor_assert(retval > 0); \
692 STMT_END
694 { /* Get those fakes! */
695 uint8_t client_id[8]; /* fake client-id */
696 uint8_t iv[16]; /* fake IV (initialization vector) */
697 uint8_t encrypted_cookie[16]; /* fake encrypted cookie */
699 FILL_WITH_FAKE_DATA_AND_BASE64(client_id);
700 FILL_WITH_FAKE_DATA_AND_BASE64(iv);
701 FILL_WITH_FAKE_DATA_AND_BASE64(encrypted_cookie);
704 /* Build the final string */
705 tor_asprintf(&auth_client_str, "%s %s %s %s", str_desc_auth_client,
706 client_id_b64, iv_b64, encrypted_cookie_b64);
708 #undef FILL_WITH_FAKE_DATA_AND_BASE64
710 return auth_client_str;
713 /** How many lines of "client-auth" we want in our descriptors; fake or not. */
714 #define CLIENT_AUTH_ENTRIES_BLOCK_SIZE 16
716 /** Create the "client-auth" part of the descriptor and return a
717 * newly-allocated string with it. It's the responsibility of the caller to
718 * free the returned string. */
719 static char *
720 get_fake_auth_client_lines(void)
722 /* XXX: Client authorization is still not implemented, so all this function
723 does is make fake clients */
724 int i = 0;
725 smartlist_t *auth_client_lines = smartlist_new();
726 char *auth_client_lines_str = NULL;
728 /* Make a line for each fake client */
729 const int num_fake_clients = CLIENT_AUTH_ENTRIES_BLOCK_SIZE;
730 for (i = 0; i < num_fake_clients; i++) {
731 char *auth_client_str = get_fake_auth_client_str();
732 tor_assert(auth_client_str);
733 smartlist_add(auth_client_lines, auth_client_str);
736 /* Join all lines together to form final string */
737 auth_client_lines_str = smartlist_join_strings(auth_client_lines,
738 "\n", 1, NULL);
739 /* Cleanup the mess */
740 SMARTLIST_FOREACH(auth_client_lines, char *, a, tor_free(a));
741 smartlist_free(auth_client_lines);
743 return auth_client_lines_str;
746 /* Create the inner layer of the descriptor (which includes the intro points,
747 * etc.). Return a newly-allocated string with the layer plaintext, or NULL if
748 * an error occured. It's the responsibility of the caller to free the returned
749 * string. */
750 static char *
751 get_inner_encrypted_layer_plaintext(const hs_descriptor_t *desc)
753 char *encoded_str = NULL;
754 smartlist_t *lines = smartlist_new();
756 /* Build the start of the section prior to the introduction points. */
758 if (!desc->encrypted_data.create2_ntor) {
759 log_err(LD_BUG, "HS desc doesn't have recognized handshake type.");
760 goto err;
762 smartlist_add_asprintf(lines, "%s %d\n", str_create2_formats,
763 ONION_HANDSHAKE_TYPE_NTOR);
765 if (desc->encrypted_data.intro_auth_types &&
766 smartlist_len(desc->encrypted_data.intro_auth_types)) {
767 /* Put the authentication-required line. */
768 char *buf = smartlist_join_strings(desc->encrypted_data.intro_auth_types,
769 " ", 0, NULL);
770 smartlist_add_asprintf(lines, "%s %s\n", str_intro_auth_required, buf);
771 tor_free(buf);
774 if (desc->encrypted_data.single_onion_service) {
775 smartlist_add_asprintf(lines, "%s\n", str_single_onion);
779 /* Build the introduction point(s) section. */
780 SMARTLIST_FOREACH_BEGIN(desc->encrypted_data.intro_points,
781 const hs_desc_intro_point_t *, ip) {
782 char *encoded_ip = encode_intro_point(&desc->plaintext_data.signing_pubkey,
783 ip);
784 if (encoded_ip == NULL) {
785 log_err(LD_BUG, "HS desc intro point is malformed.");
786 goto err;
788 smartlist_add(lines, encoded_ip);
789 } SMARTLIST_FOREACH_END(ip);
791 /* Build the entire encrypted data section into one encoded plaintext and
792 * then encrypt it. */
793 encoded_str = smartlist_join_strings(lines, "", 0, NULL);
795 err:
796 SMARTLIST_FOREACH(lines, char *, l, tor_free(l));
797 smartlist_free(lines);
799 return encoded_str;
802 /* Create the middle layer of the descriptor, which includes the client auth
803 * data and the encrypted inner layer (provided as a base64 string at
804 * <b>layer2_b64_ciphertext</b>). Return a newly-allocated string with the
805 * layer plaintext, or NULL if an error occured. It's the responsibility of the
806 * caller to free the returned string. */
807 static char *
808 get_outer_encrypted_layer_plaintext(const hs_descriptor_t *desc,
809 const char *layer2_b64_ciphertext)
811 char *layer1_str = NULL;
812 smartlist_t *lines = smartlist_new();
814 /* XXX: Disclaimer: This function generates only _fake_ client auth
815 * data. Real client auth is not yet implemented, but client auth data MUST
816 * always be present in descriptors. In the future this function will be
817 * refactored to use real client auth data if they exist (#20700). */
818 (void) *desc;
820 /* Specify auth type */
821 smartlist_add_asprintf(lines, "%s %s\n", str_desc_auth_type, "x25519");
823 { /* Create fake ephemeral x25519 key */
824 char fake_key_base64[CURVE25519_BASE64_PADDED_LEN + 1];
825 curve25519_keypair_t fake_x25519_keypair;
826 if (curve25519_keypair_generate(&fake_x25519_keypair, 0) < 0) {
827 goto done;
829 if (curve25519_public_to_base64(fake_key_base64,
830 &fake_x25519_keypair.pubkey) < 0) {
831 goto done;
833 smartlist_add_asprintf(lines, "%s %s\n",
834 str_desc_auth_key, fake_key_base64);
835 /* No need to memwipe any of these fake keys. They will go unused. */
838 { /* Create fake auth-client lines. */
839 char *auth_client_lines = get_fake_auth_client_lines();
840 tor_assert(auth_client_lines);
841 smartlist_add(lines, auth_client_lines);
844 /* create encrypted section */
846 smartlist_add_asprintf(lines,
847 "%s\n"
848 "-----BEGIN MESSAGE-----\n"
849 "%s"
850 "-----END MESSAGE-----",
851 str_encrypted, layer2_b64_ciphertext);
854 layer1_str = smartlist_join_strings(lines, "", 0, NULL);
856 done:
857 SMARTLIST_FOREACH(lines, char *, a, tor_free(a));
858 smartlist_free(lines);
860 return layer1_str;
863 /* Encrypt <b>encoded_str</b> into an encrypted blob and then base64 it before
864 * returning it. <b>desc</b> is provided to derive the encryption
865 * keys. <b>is_superencrypted_layer</b> is set if <b>encoded_str</b> is the
866 * middle (superencrypted) layer of the descriptor. It's the responsibility of
867 * the caller to free the returned string. */
868 static char *
869 encrypt_desc_data_and_base64(const hs_descriptor_t *desc,
870 const char *encoded_str,
871 int is_superencrypted_layer)
873 char *enc_b64;
874 ssize_t enc_b64_len, ret_len, enc_len;
875 char *encrypted_blob = NULL;
877 enc_len = encrypt_descriptor_data(desc, encoded_str, &encrypted_blob,
878 is_superencrypted_layer);
879 /* Get the encoded size plus a NUL terminating byte. */
880 enc_b64_len = base64_encode_size(enc_len, BASE64_ENCODE_MULTILINE) + 1;
881 enc_b64 = tor_malloc_zero(enc_b64_len);
882 /* Base64 the encrypted blob before returning it. */
883 ret_len = base64_encode(enc_b64, enc_b64_len, encrypted_blob, enc_len,
884 BASE64_ENCODE_MULTILINE);
885 /* Return length doesn't count the NUL byte. */
886 tor_assert(ret_len == (enc_b64_len - 1));
887 tor_free(encrypted_blob);
889 return enc_b64;
892 /* Generate and encode the superencrypted portion of <b>desc</b>. This also
893 * involves generating the encrypted portion of the descriptor, and performing
894 * the superencryption. A newly allocated NUL-terminated string pointer
895 * containing the encrypted encoded blob is put in encrypted_blob_out. Return 0
896 * on success else a negative value. */
897 static int
898 encode_superencrypted_data(const hs_descriptor_t *desc,
899 char **encrypted_blob_out)
901 int ret = -1;
902 char *layer2_str = NULL;
903 char *layer2_b64_ciphertext = NULL;
904 char *layer1_str = NULL;
905 char *layer1_b64_ciphertext = NULL;
907 tor_assert(desc);
908 tor_assert(encrypted_blob_out);
910 /* Func logic: We first create the inner layer of the descriptor (layer2).
911 * We then encrypt it and use it to create the middle layer of the descriptor
912 * (layer1). Finally we superencrypt the middle layer and return it to our
913 * caller. */
915 /* Create inner descriptor layer */
916 layer2_str = get_inner_encrypted_layer_plaintext(desc);
917 if (!layer2_str) {
918 goto err;
921 /* Encrypt and b64 the inner layer */
922 layer2_b64_ciphertext = encrypt_desc_data_and_base64(desc, layer2_str, 0);
923 if (!layer2_b64_ciphertext) {
924 goto err;
927 /* Now create middle descriptor layer given the inner layer */
928 layer1_str = get_outer_encrypted_layer_plaintext(desc,layer2_b64_ciphertext);
929 if (!layer1_str) {
930 goto err;
933 /* Encrypt and base64 the middle layer */
934 layer1_b64_ciphertext = encrypt_desc_data_and_base64(desc, layer1_str, 1);
935 if (!layer1_b64_ciphertext) {
936 goto err;
939 /* Success! */
940 ret = 0;
942 err:
943 tor_free(layer1_str);
944 tor_free(layer2_str);
945 tor_free(layer2_b64_ciphertext);
947 *encrypted_blob_out = layer1_b64_ciphertext;
948 return ret;
951 /* Encode a v3 HS descriptor. Return 0 on success and set encoded_out to the
952 * newly allocated string of the encoded descriptor. On error, -1 is returned
953 * and encoded_out is untouched. */
954 static int
955 desc_encode_v3(const hs_descriptor_t *desc,
956 const ed25519_keypair_t *signing_kp, char **encoded_out)
958 int ret = -1;
959 char *encoded_str = NULL;
960 size_t encoded_len;
961 smartlist_t *lines = smartlist_new();
963 tor_assert(desc);
964 tor_assert(signing_kp);
965 tor_assert(encoded_out);
966 tor_assert(desc->plaintext_data.version == 3);
968 if (BUG(desc->subcredential == NULL)) {
969 goto err;
972 /* Build the non-encrypted values. */
974 char *encoded_cert;
975 /* Encode certificate then create the first line of the descriptor. */
976 if (desc->plaintext_data.signing_key_cert->cert_type
977 != CERT_TYPE_SIGNING_HS_DESC) {
978 log_err(LD_BUG, "HS descriptor signing key has an unexpected cert type "
979 "(%d)", (int) desc->plaintext_data.signing_key_cert->cert_type);
980 goto err;
982 if (tor_cert_encode_ed22519(desc->plaintext_data.signing_key_cert,
983 &encoded_cert) < 0) {
984 /* The function will print error logs. */
985 goto err;
987 /* Create the hs descriptor line. */
988 smartlist_add_asprintf(lines, "%s %" PRIu32, str_hs_desc,
989 desc->plaintext_data.version);
990 /* Add the descriptor lifetime line (in minutes). */
991 smartlist_add_asprintf(lines, "%s %" PRIu32, str_lifetime,
992 desc->plaintext_data.lifetime_sec / 60);
993 /* Create the descriptor certificate line. */
994 smartlist_add_asprintf(lines, "%s\n%s", str_desc_cert, encoded_cert);
995 tor_free(encoded_cert);
996 /* Create the revision counter line. */
997 smartlist_add_asprintf(lines, "%s %" PRIu64, str_rev_counter,
998 desc->plaintext_data.revision_counter);
1001 /* Build the superencrypted data section. */
1003 char *enc_b64_blob=NULL;
1004 if (encode_superencrypted_data(desc, &enc_b64_blob) < 0) {
1005 goto err;
1007 smartlist_add_asprintf(lines,
1008 "%s\n"
1009 "-----BEGIN MESSAGE-----\n"
1010 "%s"
1011 "-----END MESSAGE-----",
1012 str_superencrypted, enc_b64_blob);
1013 tor_free(enc_b64_blob);
1016 /* Join all lines in one string so we can generate a signature and append
1017 * it to the descriptor. */
1018 encoded_str = smartlist_join_strings(lines, "\n", 1, &encoded_len);
1020 /* Sign all fields of the descriptor with our short term signing key. */
1022 ed25519_signature_t sig;
1023 char ed_sig_b64[ED25519_SIG_BASE64_LEN + 1];
1024 if (ed25519_sign_prefixed(&sig,
1025 (const uint8_t *) encoded_str, encoded_len,
1026 str_desc_sig_prefix, signing_kp) < 0) {
1027 log_warn(LD_BUG, "Can't sign encoded HS descriptor!");
1028 tor_free(encoded_str);
1029 goto err;
1031 if (ed25519_signature_to_base64(ed_sig_b64, &sig) < 0) {
1032 log_warn(LD_BUG, "Can't base64 encode descriptor signature!");
1033 tor_free(encoded_str);
1034 goto err;
1036 /* Create the signature line. */
1037 smartlist_add_asprintf(lines, "%s %s", str_signature, ed_sig_b64);
1039 /* Free previous string that we used so compute the signature. */
1040 tor_free(encoded_str);
1041 encoded_str = smartlist_join_strings(lines, "\n", 1, NULL);
1042 *encoded_out = encoded_str;
1044 if (strlen(encoded_str) >= hs_cache_get_max_descriptor_size()) {
1045 log_warn(LD_GENERAL, "We just made an HS descriptor that's too big (%d)."
1046 "Failing.", (int)strlen(encoded_str));
1047 tor_free(encoded_str);
1048 goto err;
1051 /* XXX: Trigger a control port event. */
1053 /* Success! */
1054 ret = 0;
1056 err:
1057 SMARTLIST_FOREACH(lines, char *, l, tor_free(l));
1058 smartlist_free(lines);
1059 return ret;
1062 /* === DECODING === */
1064 /* Given an encoded string of the link specifiers, return a newly allocated
1065 * list of decoded link specifiers. Return NULL on error. */
1066 STATIC smartlist_t *
1067 decode_link_specifiers(const char *encoded)
1069 int decoded_len;
1070 size_t encoded_len, i;
1071 uint8_t *decoded;
1072 smartlist_t *results = NULL;
1073 link_specifier_list_t *specs = NULL;
1075 tor_assert(encoded);
1077 encoded_len = strlen(encoded);
1078 decoded = tor_malloc(encoded_len);
1079 decoded_len = base64_decode((char *) decoded, encoded_len, encoded,
1080 encoded_len);
1081 if (decoded_len < 0) {
1082 goto err;
1085 if (link_specifier_list_parse(&specs, decoded,
1086 (size_t) decoded_len) < decoded_len) {
1087 goto err;
1089 tor_assert(specs);
1090 results = smartlist_new();
1092 for (i = 0; i < link_specifier_list_getlen_spec(specs); i++) {
1093 hs_desc_link_specifier_t *hs_spec;
1094 link_specifier_t *ls = link_specifier_list_get_spec(specs, i);
1095 tor_assert(ls);
1097 hs_spec = tor_malloc_zero(sizeof(*hs_spec));
1098 hs_spec->type = link_specifier_get_ls_type(ls);
1099 switch (hs_spec->type) {
1100 case LS_IPV4:
1101 tor_addr_from_ipv4h(&hs_spec->u.ap.addr,
1102 link_specifier_get_un_ipv4_addr(ls));
1103 hs_spec->u.ap.port = link_specifier_get_un_ipv4_port(ls);
1104 break;
1105 case LS_IPV6:
1106 tor_addr_from_ipv6_bytes(&hs_spec->u.ap.addr, (const char *)
1107 link_specifier_getarray_un_ipv6_addr(ls));
1108 hs_spec->u.ap.port = link_specifier_get_un_ipv6_port(ls);
1109 break;
1110 case LS_LEGACY_ID:
1111 /* Both are known at compile time so let's make sure they are the same
1112 * else we can copy memory out of bound. */
1113 tor_assert(link_specifier_getlen_un_legacy_id(ls) ==
1114 sizeof(hs_spec->u.legacy_id));
1115 memcpy(hs_spec->u.legacy_id, link_specifier_getarray_un_legacy_id(ls),
1116 sizeof(hs_spec->u.legacy_id));
1117 break;
1118 case LS_ED25519_ID:
1119 /* Both are known at compile time so let's make sure they are the same
1120 * else we can copy memory out of bound. */
1121 tor_assert(link_specifier_getlen_un_ed25519_id(ls) ==
1122 sizeof(hs_spec->u.ed25519_id));
1123 memcpy(hs_spec->u.ed25519_id,
1124 link_specifier_getconstarray_un_ed25519_id(ls),
1125 sizeof(hs_spec->u.ed25519_id));
1126 break;
1127 default:
1128 goto err;
1131 smartlist_add(results, hs_spec);
1134 goto done;
1135 err:
1136 if (results) {
1137 SMARTLIST_FOREACH(results, hs_desc_link_specifier_t *, s, tor_free(s));
1138 smartlist_free(results);
1139 results = NULL;
1141 done:
1142 link_specifier_list_free(specs);
1143 tor_free(decoded);
1144 return results;
1147 /* Given a list of authentication types, decode it and put it in the encrypted
1148 * data section. Return 1 if we at least know one of the type or 0 if we know
1149 * none of them. */
1150 static int
1151 decode_auth_type(hs_desc_encrypted_data_t *desc, const char *list)
1153 int match = 0;
1155 tor_assert(desc);
1156 tor_assert(list);
1158 desc->intro_auth_types = smartlist_new();
1159 smartlist_split_string(desc->intro_auth_types, list, " ", 0, 0);
1161 /* Validate the types that we at least know about one. */
1162 SMARTLIST_FOREACH_BEGIN(desc->intro_auth_types, const char *, auth) {
1163 for (int idx = 0; intro_auth_types[idx].identifier; idx++) {
1164 if (!strncmp(auth, intro_auth_types[idx].identifier,
1165 strlen(intro_auth_types[idx].identifier))) {
1166 match = 1;
1167 break;
1170 } SMARTLIST_FOREACH_END(auth);
1172 return match;
1175 /* Parse a space-delimited list of integers representing CREATE2 formats into
1176 * the bitfield in hs_desc_encrypted_data_t. Ignore unrecognized values. */
1177 static void
1178 decode_create2_list(hs_desc_encrypted_data_t *desc, const char *list)
1180 smartlist_t *tokens;
1182 tor_assert(desc);
1183 tor_assert(list);
1185 tokens = smartlist_new();
1186 smartlist_split_string(tokens, list, " ", 0, 0);
1188 SMARTLIST_FOREACH_BEGIN(tokens, char *, s) {
1189 int ok;
1190 unsigned long type = tor_parse_ulong(s, 10, 1, UINT16_MAX, &ok, NULL);
1191 if (!ok) {
1192 log_warn(LD_REND, "Unparseable value %s in create2 list", escaped(s));
1193 continue;
1195 switch (type) {
1196 case ONION_HANDSHAKE_TYPE_NTOR:
1197 desc->create2_ntor = 1;
1198 break;
1199 default:
1200 /* We deliberately ignore unsupported handshake types */
1201 continue;
1203 } SMARTLIST_FOREACH_END(s);
1205 SMARTLIST_FOREACH(tokens, char *, s, tor_free(s));
1206 smartlist_free(tokens);
1209 /* Given a certificate, validate the certificate for certain conditions which
1210 * are if the given type matches the cert's one, if the signing key is
1211 * included and if the that key was actually used to sign the certificate.
1213 * Return 1 iff if all conditions pass or 0 if one of them fails. */
1214 STATIC int
1215 cert_is_valid(tor_cert_t *cert, uint8_t type, const char *log_obj_type)
1217 tor_assert(log_obj_type);
1219 if (cert == NULL) {
1220 log_warn(LD_REND, "Certificate for %s couldn't be parsed.", log_obj_type);
1221 goto err;
1223 if (cert->cert_type != type) {
1224 log_warn(LD_REND, "Invalid cert type %02x for %s.", cert->cert_type,
1225 log_obj_type);
1226 goto err;
1228 /* All certificate must have its signing key included. */
1229 if (!cert->signing_key_included) {
1230 log_warn(LD_REND, "Signing key is NOT included for %s.", log_obj_type);
1231 goto err;
1233 /* The following will not only check if the signature matches but also the
1234 * expiration date and overall validity. */
1235 if (tor_cert_checksig(cert, &cert->signing_key, approx_time()) < 0) {
1236 log_warn(LD_REND, "Invalid signature for %s.", log_obj_type);
1237 goto err;
1240 return 1;
1241 err:
1242 return 0;
1245 /* Given some binary data, try to parse it to get a certificate object. If we
1246 * have a valid cert, validate it using the given wanted type. On error, print
1247 * a log using the err_msg has the certificate identifier adding semantic to
1248 * the log and cert_out is set to NULL. On success, 0 is returned and cert_out
1249 * points to a newly allocated certificate object. */
1250 static int
1251 cert_parse_and_validate(tor_cert_t **cert_out, const char *data,
1252 size_t data_len, unsigned int cert_type_wanted,
1253 const char *err_msg)
1255 tor_cert_t *cert;
1257 tor_assert(cert_out);
1258 tor_assert(data);
1259 tor_assert(err_msg);
1261 /* Parse certificate. */
1262 cert = tor_cert_parse((const uint8_t *) data, data_len);
1263 if (!cert) {
1264 log_warn(LD_REND, "Certificate for %s couldn't be parsed.", err_msg);
1265 goto err;
1268 /* Validate certificate. */
1269 if (!cert_is_valid(cert, cert_type_wanted, err_msg)) {
1270 goto err;
1273 *cert_out = cert;
1274 return 0;
1276 err:
1277 tor_cert_free(cert);
1278 *cert_out = NULL;
1279 return -1;
1282 /* Return true iff the given length of the encrypted data of a descriptor
1283 * passes validation. */
1284 STATIC int
1285 encrypted_data_length_is_valid(size_t len)
1287 /* Make sure there is enough data for the salt and the mac. The equality is
1288 there to ensure that there is at least one byte of encrypted data. */
1289 if (len <= HS_DESC_ENCRYPTED_SALT_LEN + DIGEST256_LEN) {
1290 log_warn(LD_REND, "Length of descriptor's encrypted data is too small. "
1291 "Got %lu but minimum value is %d",
1292 (unsigned long)len, HS_DESC_ENCRYPTED_SALT_LEN + DIGEST256_LEN);
1293 goto err;
1296 return 1;
1297 err:
1298 return 0;
1301 /** Decrypt an encrypted descriptor layer at <b>encrypted_blob</b> of size
1302 * <b>encrypted_blob_size</b>. Use the descriptor object <b>desc</b> to
1303 * generate the right decryption keys; set <b>decrypted_out</b> to the
1304 * plaintext. If <b>is_superencrypted_layer</b> is set, this is the outter
1305 * encrypted layer of the descriptor.
1307 * On any error case, including an empty output, return 0 and set
1308 * *<b>decrypted_out</b> to NULL.
1310 MOCK_IMPL(STATIC size_t,
1311 decrypt_desc_layer,(const hs_descriptor_t *desc,
1312 const uint8_t *encrypted_blob,
1313 size_t encrypted_blob_size,
1314 int is_superencrypted_layer,
1315 char **decrypted_out))
1317 uint8_t *decrypted = NULL;
1318 uint8_t secret_key[HS_DESC_ENCRYPTED_KEY_LEN], secret_iv[CIPHER_IV_LEN];
1319 uint8_t mac_key[DIGEST256_LEN], our_mac[DIGEST256_LEN];
1320 const uint8_t *salt, *encrypted, *desc_mac;
1321 size_t encrypted_len, result_len = 0;
1323 tor_assert(decrypted_out);
1324 tor_assert(desc);
1325 tor_assert(encrypted_blob);
1327 /* Construction is as follow: SALT | ENCRYPTED_DATA | MAC .
1328 * Make sure we have enough space for all these things. */
1329 if (!encrypted_data_length_is_valid(encrypted_blob_size)) {
1330 goto err;
1333 /* Start of the blob thus the salt. */
1334 salt = encrypted_blob;
1336 /* Next is the encrypted data. */
1337 encrypted = encrypted_blob + HS_DESC_ENCRYPTED_SALT_LEN;
1338 encrypted_len = encrypted_blob_size -
1339 (HS_DESC_ENCRYPTED_SALT_LEN + DIGEST256_LEN);
1340 tor_assert(encrypted_len > 0); /* guaranteed by the check above */
1342 /* And last comes the MAC. */
1343 desc_mac = encrypted_blob + encrypted_blob_size - DIGEST256_LEN;
1345 /* KDF construction resulting in a key from which the secret key, IV and MAC
1346 * key are extracted which is what we need for the decryption. */
1347 build_secret_key_iv_mac(desc, salt, HS_DESC_ENCRYPTED_SALT_LEN,
1348 secret_key, sizeof(secret_key),
1349 secret_iv, sizeof(secret_iv),
1350 mac_key, sizeof(mac_key),
1351 is_superencrypted_layer);
1353 /* Build MAC. */
1354 build_mac(mac_key, sizeof(mac_key), salt, HS_DESC_ENCRYPTED_SALT_LEN,
1355 encrypted, encrypted_len, our_mac, sizeof(our_mac));
1356 memwipe(mac_key, 0, sizeof(mac_key));
1357 /* Verify MAC; MAC is H(mac_key || salt || encrypted)
1359 * This is a critical check that is making sure the computed MAC matches the
1360 * one in the descriptor. */
1361 if (!tor_memeq(our_mac, desc_mac, sizeof(our_mac))) {
1362 log_warn(LD_REND, "Encrypted service descriptor MAC check failed");
1363 goto err;
1367 /* Decrypt. Here we are assured that the encrypted length is valid for
1368 * decryption. */
1369 crypto_cipher_t *cipher;
1371 cipher = crypto_cipher_new_with_iv_and_bits(secret_key, secret_iv,
1372 HS_DESC_ENCRYPTED_BIT_SIZE);
1373 /* Extra byte for the NUL terminated byte. */
1374 decrypted = tor_malloc_zero(encrypted_len + 1);
1375 crypto_cipher_decrypt(cipher, (char *) decrypted,
1376 (const char *) encrypted, encrypted_len);
1377 crypto_cipher_free(cipher);
1381 /* Adjust length to remove NUL padding bytes */
1382 uint8_t *end = memchr(decrypted, 0, encrypted_len);
1383 result_len = encrypted_len;
1384 if (end) {
1385 result_len = end - decrypted;
1389 if (result_len == 0) {
1390 /* Treat this as an error, so that somebody will free the output. */
1391 goto err;
1394 /* Make sure to NUL terminate the string. */
1395 decrypted[encrypted_len] = '\0';
1396 *decrypted_out = (char *) decrypted;
1397 goto done;
1399 err:
1400 if (decrypted) {
1401 tor_free(decrypted);
1403 *decrypted_out = NULL;
1404 result_len = 0;
1406 done:
1407 memwipe(secret_key, 0, sizeof(secret_key));
1408 memwipe(secret_iv, 0, sizeof(secret_iv));
1409 return result_len;
1412 /* Basic validation that the superencrypted client auth portion of the
1413 * descriptor is well-formed and recognized. Return True if so, otherwise
1414 * return False. */
1415 static int
1416 superencrypted_auth_data_is_valid(smartlist_t *tokens)
1418 /* XXX: This is just basic validation for now. When we implement client auth,
1419 we can refactor this function so that it actually parses and saves the
1420 data. */
1422 { /* verify desc auth type */
1423 const directory_token_t *tok;
1424 tok = find_by_keyword(tokens, R3_DESC_AUTH_TYPE);
1425 tor_assert(tok->n_args >= 1);
1426 if (strcmp(tok->args[0], "x25519")) {
1427 log_warn(LD_DIR, "Unrecognized desc auth type");
1428 return 0;
1432 { /* verify desc auth key */
1433 const directory_token_t *tok;
1434 curve25519_public_key_t k;
1435 tok = find_by_keyword(tokens, R3_DESC_AUTH_KEY);
1436 tor_assert(tok->n_args >= 1);
1437 if (curve25519_public_from_base64(&k, tok->args[0]) < 0) {
1438 log_warn(LD_DIR, "Bogus desc auth key in HS desc");
1439 return 0;
1443 /* verify desc auth client items */
1444 SMARTLIST_FOREACH_BEGIN(tokens, const directory_token_t *, tok) {
1445 if (tok->tp == R3_DESC_AUTH_CLIENT) {
1446 tor_assert(tok->n_args >= 3);
1448 } SMARTLIST_FOREACH_END(tok);
1450 return 1;
1453 /* Parse <b>message</b>, the plaintext of the superencrypted portion of an HS
1454 * descriptor. Set <b>encrypted_out</b> to the encrypted blob, and return its
1455 * size */
1456 STATIC size_t
1457 decode_superencrypted(const char *message, size_t message_len,
1458 uint8_t **encrypted_out)
1460 int retval = 0;
1461 memarea_t *area = NULL;
1462 smartlist_t *tokens = NULL;
1464 area = memarea_new();
1465 tokens = smartlist_new();
1466 if (tokenize_string(area, message, message + message_len, tokens,
1467 hs_desc_superencrypted_v3_token_table, 0) < 0) {
1468 log_warn(LD_REND, "Superencrypted portion is not parseable");
1469 goto err;
1472 /* Do some rudimentary validation of the authentication data */
1473 if (!superencrypted_auth_data_is_valid(tokens)) {
1474 log_warn(LD_REND, "Invalid auth data");
1475 goto err;
1478 /* Extract the encrypted data section. */
1480 const directory_token_t *tok;
1481 tok = find_by_keyword(tokens, R3_ENCRYPTED);
1482 tor_assert(tok->object_body);
1483 if (strcmp(tok->object_type, "MESSAGE") != 0) {
1484 log_warn(LD_REND, "Desc superencrypted data section is invalid");
1485 goto err;
1487 /* Make sure the length of the encrypted blob is valid. */
1488 if (!encrypted_data_length_is_valid(tok->object_size)) {
1489 goto err;
1492 /* Copy the encrypted blob to the descriptor object so we can handle it
1493 * latter if needed. */
1494 tor_assert(tok->object_size <= INT_MAX);
1495 *encrypted_out = tor_memdup(tok->object_body, tok->object_size);
1496 retval = (int) tok->object_size;
1499 err:
1500 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
1501 smartlist_free(tokens);
1502 if (area) {
1503 memarea_drop_all(area);
1506 return retval;
1509 /* Decrypt both the superencrypted and the encrypted section of the descriptor
1510 * using the given descriptor object <b>desc</b>. A newly allocated NUL
1511 * terminated string is put in decrypted_out which contains the inner encrypted
1512 * layer of the descriptor. Return the length of decrypted_out on success else
1513 * 0 is returned and decrypted_out is set to NULL. */
1514 static size_t
1515 desc_decrypt_all(const hs_descriptor_t *desc, char **decrypted_out)
1517 size_t decrypted_len = 0;
1518 size_t encrypted_len = 0;
1519 size_t superencrypted_len = 0;
1520 char *superencrypted_plaintext = NULL;
1521 uint8_t *encrypted_blob = NULL;
1523 /** Function logic: This function takes us from the descriptor header to the
1524 * inner encrypted layer, by decrypting and decoding the middle descriptor
1525 * layer. In the end we return the contents of the inner encrypted layer to
1526 * our caller. */
1528 /* 1. Decrypt middle layer of descriptor */
1529 superencrypted_len = decrypt_desc_layer(desc,
1530 desc->plaintext_data.superencrypted_blob,
1531 desc->plaintext_data.superencrypted_blob_size,
1533 &superencrypted_plaintext);
1534 if (!superencrypted_len) {
1535 log_warn(LD_REND, "Decrypting superencrypted desc failed.");
1536 goto err;
1538 tor_assert(superencrypted_plaintext);
1540 /* 2. Parse "superencrypted" */
1541 encrypted_len = decode_superencrypted(superencrypted_plaintext,
1542 superencrypted_len,
1543 &encrypted_blob);
1544 if (!encrypted_len) {
1545 log_warn(LD_REND, "Decrypting encrypted desc failed.");
1546 goto err;
1548 tor_assert(encrypted_blob);
1550 /* 3. Decrypt "encrypted" and set decrypted_out */
1551 char *decrypted_desc;
1552 decrypted_len = decrypt_desc_layer(desc,
1553 encrypted_blob, encrypted_len,
1554 0, &decrypted_desc);
1555 if (!decrypted_len) {
1556 log_warn(LD_REND, "Decrypting encrypted desc failed.");
1557 goto err;
1559 tor_assert(decrypted_desc);
1561 *decrypted_out = decrypted_desc;
1563 err:
1564 tor_free(superencrypted_plaintext);
1565 tor_free(encrypted_blob);
1567 return decrypted_len;
1570 /* Given the token tok for an intro point legacy key, the list of tokens, the
1571 * introduction point ip being decoded and the descriptor desc from which it
1572 * comes from, decode the legacy key and set the intro point object. Return 0
1573 * on success else -1 on failure. */
1574 static int
1575 decode_intro_legacy_key(const directory_token_t *tok,
1576 smartlist_t *tokens,
1577 hs_desc_intro_point_t *ip,
1578 const hs_descriptor_t *desc)
1580 tor_assert(tok);
1581 tor_assert(tokens);
1582 tor_assert(ip);
1583 tor_assert(desc);
1585 if (!crypto_pk_public_exponent_ok(tok->key)) {
1586 log_warn(LD_REND, "Introduction point legacy key is invalid");
1587 goto err;
1589 ip->legacy.key = crypto_pk_dup_key(tok->key);
1590 /* Extract the legacy cross certification cert which MUST be present if we
1591 * have a legacy key. */
1592 tok = find_opt_by_keyword(tokens, R3_INTRO_LEGACY_KEY_CERT);
1593 if (!tok) {
1594 log_warn(LD_REND, "Introduction point legacy key cert is missing");
1595 goto err;
1597 tor_assert(tok->object_body);
1598 if (strcmp(tok->object_type, "CROSSCERT")) {
1599 /* Info level because this might be an unknown field that we should
1600 * ignore. */
1601 log_info(LD_REND, "Introduction point legacy encryption key "
1602 "cross-certification has an unknown format.");
1603 goto err;
1605 /* Keep a copy of the certificate. */
1606 ip->legacy.cert.encoded = tor_memdup(tok->object_body, tok->object_size);
1607 ip->legacy.cert.len = tok->object_size;
1608 /* The check on the expiration date is for the entire lifetime of a
1609 * certificate which is 24 hours. However, a descriptor has a maximum
1610 * lifetime of 12 hours meaning we have a 12h difference between the two
1611 * which ultimately accomodate the clock skewed client. */
1612 if (rsa_ed25519_crosscert_check(ip->legacy.cert.encoded,
1613 ip->legacy.cert.len, ip->legacy.key,
1614 &desc->plaintext_data.signing_pubkey,
1615 approx_time() - HS_DESC_CERT_LIFETIME)) {
1616 log_warn(LD_REND, "Unable to check cross-certification on the "
1617 "introduction point legacy encryption key.");
1618 ip->cross_certified = 0;
1619 goto err;
1622 /* Success. */
1623 return 0;
1624 err:
1625 return -1;
1628 /* Dig into the descriptor <b>tokens</b> to find the onion key we should use
1629 * for this intro point, and set it into <b>onion_key_out</b>. Return 0 if it
1630 * was found and well-formed, otherwise return -1 in case of errors. */
1631 static int
1632 set_intro_point_onion_key(curve25519_public_key_t *onion_key_out,
1633 const smartlist_t *tokens)
1635 int retval = -1;
1636 smartlist_t *onion_keys = NULL;
1638 tor_assert(onion_key_out);
1640 onion_keys = find_all_by_keyword(tokens, R3_INTRO_ONION_KEY);
1641 if (!onion_keys) {
1642 log_warn(LD_REND, "Descriptor did not contain intro onion keys");
1643 goto err;
1646 SMARTLIST_FOREACH_BEGIN(onion_keys, directory_token_t *, tok) {
1647 /* This field is using GE(2) so for possible forward compatibility, we
1648 * accept more fields but must be at least 2. */
1649 tor_assert(tok->n_args >= 2);
1651 /* Try to find an ntor key, it's the only recognized type right now */
1652 if (!strcmp(tok->args[0], "ntor")) {
1653 if (curve25519_public_from_base64(onion_key_out, tok->args[1]) < 0) {
1654 log_warn(LD_REND, "Introduction point ntor onion-key is invalid");
1655 goto err;
1657 /* Got the onion key! Set the appropriate retval */
1658 retval = 0;
1660 } SMARTLIST_FOREACH_END(tok);
1662 /* Log an error if we didn't find it :( */
1663 if (retval < 0) {
1664 log_warn(LD_REND, "Descriptor did not contain ntor onion keys");
1667 err:
1668 smartlist_free(onion_keys);
1669 return retval;
1672 /* Given the start of a section and the end of it, decode a single
1673 * introduction point from that section. Return a newly allocated introduction
1674 * point object containing the decoded data. Return NULL if the section can't
1675 * be decoded. */
1676 STATIC hs_desc_intro_point_t *
1677 decode_introduction_point(const hs_descriptor_t *desc, const char *start)
1679 hs_desc_intro_point_t *ip = NULL;
1680 memarea_t *area = NULL;
1681 smartlist_t *tokens = NULL;
1682 const directory_token_t *tok;
1684 tor_assert(desc);
1685 tor_assert(start);
1687 area = memarea_new();
1688 tokens = smartlist_new();
1689 if (tokenize_string(area, start, start + strlen(start),
1690 tokens, hs_desc_intro_point_v3_token_table, 0) < 0) {
1691 log_warn(LD_REND, "Introduction point is not parseable");
1692 goto err;
1695 /* Ok we seem to have a well formed section containing enough tokens to
1696 * parse. Allocate our IP object and try to populate it. */
1697 ip = hs_desc_intro_point_new();
1699 /* "introduction-point" SP link-specifiers NL */
1700 tok = find_by_keyword(tokens, R3_INTRODUCTION_POINT);
1701 tor_assert(tok->n_args == 1);
1702 /* Our constructor creates this list by default so free it. */
1703 smartlist_free(ip->link_specifiers);
1704 ip->link_specifiers = decode_link_specifiers(tok->args[0]);
1705 if (!ip->link_specifiers) {
1706 log_warn(LD_REND, "Introduction point has invalid link specifiers");
1707 goto err;
1710 /* "onion-key" SP ntor SP key NL */
1711 if (set_intro_point_onion_key(&ip->onion_key, tokens) < 0) {
1712 goto err;
1715 /* "auth-key" NL certificate NL */
1716 tok = find_by_keyword(tokens, R3_INTRO_AUTH_KEY);
1717 tor_assert(tok->object_body);
1718 if (strcmp(tok->object_type, "ED25519 CERT")) {
1719 log_warn(LD_REND, "Unexpected object type for introduction auth key");
1720 goto err;
1722 /* Parse cert and do some validation. */
1723 if (cert_parse_and_validate(&ip->auth_key_cert, tok->object_body,
1724 tok->object_size, CERT_TYPE_AUTH_HS_IP_KEY,
1725 "introduction point auth-key") < 0) {
1726 goto err;
1728 /* Validate authentication certificate with descriptor signing key. */
1729 if (tor_cert_checksig(ip->auth_key_cert,
1730 &desc->plaintext_data.signing_pubkey, 0) < 0) {
1731 log_warn(LD_REND, "Invalid authentication key signature");
1732 goto err;
1735 /* Exactly one "enc-key" SP "ntor" SP key NL */
1736 tok = find_by_keyword(tokens, R3_INTRO_ENC_KEY);
1737 if (!strcmp(tok->args[0], "ntor")) {
1738 /* This field is using GE(2) so for possible forward compatibility, we
1739 * accept more fields but must be at least 2. */
1740 tor_assert(tok->n_args >= 2);
1742 if (curve25519_public_from_base64(&ip->enc_key, tok->args[1]) < 0) {
1743 log_warn(LD_REND, "Introduction point ntor enc-key is invalid");
1744 goto err;
1746 } else {
1747 /* Unknown key type so we can't use that introduction point. */
1748 log_warn(LD_REND, "Introduction point encryption key is unrecognized.");
1749 goto err;
1752 /* Exactly once "enc-key-cert" NL certificate NL */
1753 tok = find_by_keyword(tokens, R3_INTRO_ENC_KEY_CERT);
1754 tor_assert(tok->object_body);
1755 /* Do the cross certification. */
1756 if (strcmp(tok->object_type, "ED25519 CERT")) {
1757 log_warn(LD_REND, "Introduction point ntor encryption key "
1758 "cross-certification has an unknown format.");
1759 goto err;
1761 if (cert_parse_and_validate(&ip->enc_key_cert, tok->object_body,
1762 tok->object_size, CERT_TYPE_CROSS_HS_IP_KEYS,
1763 "introduction point enc-key-cert") < 0) {
1764 goto err;
1766 if (tor_cert_checksig(ip->enc_key_cert,
1767 &desc->plaintext_data.signing_pubkey, 0) < 0) {
1768 log_warn(LD_REND, "Invalid encryption key signature");
1769 goto err;
1771 /* It is successfully cross certified. Flag the object. */
1772 ip->cross_certified = 1;
1774 /* Do we have a "legacy-key" SP key NL ?*/
1775 tok = find_opt_by_keyword(tokens, R3_INTRO_LEGACY_KEY);
1776 if (tok) {
1777 if (decode_intro_legacy_key(tok, tokens, ip, desc) < 0) {
1778 goto err;
1782 /* Introduction point has been parsed successfully. */
1783 goto done;
1785 err:
1786 hs_desc_intro_point_free(ip);
1787 ip = NULL;
1789 done:
1790 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
1791 smartlist_free(tokens);
1792 if (area) {
1793 memarea_drop_all(area);
1796 return ip;
1799 /* Given a descriptor string at <b>data</b>, decode all possible introduction
1800 * points that we can find. Add the introduction point object to desc_enc as we
1801 * find them. This function can't fail and it is possible that zero
1802 * introduction points can be decoded. */
1803 static void
1804 decode_intro_points(const hs_descriptor_t *desc,
1805 hs_desc_encrypted_data_t *desc_enc,
1806 const char *data)
1808 smartlist_t *chunked_desc = smartlist_new();
1809 smartlist_t *intro_points = smartlist_new();
1811 tor_assert(desc);
1812 tor_assert(desc_enc);
1813 tor_assert(data);
1814 tor_assert(desc_enc->intro_points);
1816 /* Take the desc string, and extract the intro point substrings out of it */
1818 /* Split the descriptor string using the intro point header as delimiter */
1819 smartlist_split_string(chunked_desc, data, str_intro_point_start, 0, 0);
1821 /* Check if there are actually any intro points included. The first chunk
1822 * should be other descriptor fields (e.g. create2-formats), so it's not an
1823 * intro point. */
1824 if (smartlist_len(chunked_desc) < 2) {
1825 goto done;
1829 /* Take the intro point substrings, and prepare them for parsing */
1831 int i = 0;
1832 /* Prepend the introduction-point header to all the chunks, since
1833 smartlist_split_string() devoured it. */
1834 SMARTLIST_FOREACH_BEGIN(chunked_desc, char *, chunk) {
1835 /* Ignore first chunk. It's other descriptor fields. */
1836 if (i++ == 0) {
1837 continue;
1840 smartlist_add_asprintf(intro_points, "%s %s", str_intro_point, chunk);
1841 } SMARTLIST_FOREACH_END(chunk);
1844 /* Parse the intro points! */
1845 SMARTLIST_FOREACH_BEGIN(intro_points, const char *, intro_point) {
1846 hs_desc_intro_point_t *ip = decode_introduction_point(desc, intro_point);
1847 if (!ip) {
1848 /* Malformed introduction point section. We'll ignore this introduction
1849 * point and continue parsing. New or unknown fields are possible for
1850 * forward compatibility. */
1851 continue;
1853 smartlist_add(desc_enc->intro_points, ip);
1854 } SMARTLIST_FOREACH_END(intro_point);
1856 done:
1857 SMARTLIST_FOREACH(chunked_desc, char *, a, tor_free(a));
1858 smartlist_free(chunked_desc);
1859 SMARTLIST_FOREACH(intro_points, char *, a, tor_free(a));
1860 smartlist_free(intro_points);
1862 /* Return 1 iff the given base64 encoded signature in b64_sig from the encoded
1863 * descriptor in encoded_desc validates the descriptor content. */
1864 STATIC int
1865 desc_sig_is_valid(const char *b64_sig,
1866 const ed25519_public_key_t *signing_pubkey,
1867 const char *encoded_desc, size_t encoded_len)
1869 int ret = 0;
1870 ed25519_signature_t sig;
1871 const char *sig_start;
1873 tor_assert(b64_sig);
1874 tor_assert(signing_pubkey);
1875 tor_assert(encoded_desc);
1876 /* Verifying nothing won't end well :). */
1877 tor_assert(encoded_len > 0);
1879 /* Signature length check. */
1880 if (strlen(b64_sig) != ED25519_SIG_BASE64_LEN) {
1881 log_warn(LD_REND, "Service descriptor has an invalid signature length."
1882 "Exptected %d but got %lu",
1883 ED25519_SIG_BASE64_LEN, (unsigned long) strlen(b64_sig));
1884 goto err;
1887 /* First, convert base64 blob to an ed25519 signature. */
1888 if (ed25519_signature_from_base64(&sig, b64_sig) != 0) {
1889 log_warn(LD_REND, "Service descriptor does not contain a valid "
1890 "signature");
1891 goto err;
1894 /* Find the start of signature. */
1895 sig_start = tor_memstr(encoded_desc, encoded_len, "\n" str_signature);
1896 /* Getting here means the token parsing worked for the signature so if we
1897 * can't find the start of the signature, we have a code flow issue. */
1898 if (!sig_start) {
1899 log_warn(LD_GENERAL, "Malformed signature line. Rejecting.");
1900 goto err;
1902 /* Skip newline, it has to go in the signature check. */
1903 sig_start++;
1905 /* Validate signature with the full body of the descriptor. */
1906 if (ed25519_checksig_prefixed(&sig,
1907 (const uint8_t *) encoded_desc,
1908 sig_start - encoded_desc,
1909 str_desc_sig_prefix,
1910 signing_pubkey) != 0) {
1911 log_warn(LD_REND, "Invalid signature on service descriptor");
1912 goto err;
1914 /* Valid signature! All is good. */
1915 ret = 1;
1917 err:
1918 return ret;
1921 /* Decode descriptor plaintext data for version 3. Given a list of tokens, an
1922 * allocated plaintext object that will be populated and the encoded
1923 * descriptor with its length. The last one is needed for signature
1924 * verification. Unknown tokens are simply ignored so this won't error on
1925 * unknowns but requires that all v3 token be present and valid.
1927 * Return 0 on success else a negative value. */
1928 static int
1929 desc_decode_plaintext_v3(smartlist_t *tokens,
1930 hs_desc_plaintext_data_t *desc,
1931 const char *encoded_desc, size_t encoded_len)
1933 int ok;
1934 directory_token_t *tok;
1936 tor_assert(tokens);
1937 tor_assert(desc);
1938 /* Version higher could still use this function to decode most of the
1939 * descriptor and then they decode the extra part. */
1940 tor_assert(desc->version >= 3);
1942 /* Descriptor lifetime parsing. */
1943 tok = find_by_keyword(tokens, R3_DESC_LIFETIME);
1944 tor_assert(tok->n_args == 1);
1945 desc->lifetime_sec = (uint32_t) tor_parse_ulong(tok->args[0], 10, 0,
1946 UINT32_MAX, &ok, NULL);
1947 if (!ok) {
1948 log_warn(LD_REND, "Service descriptor lifetime value is invalid");
1949 goto err;
1951 /* Put it from minute to second. */
1952 desc->lifetime_sec *= 60;
1953 if (desc->lifetime_sec > HS_DESC_MAX_LIFETIME) {
1954 log_warn(LD_REND, "Service descriptor lifetime is too big. "
1955 "Got %" PRIu32 " but max is %d",
1956 desc->lifetime_sec, HS_DESC_MAX_LIFETIME);
1957 goto err;
1960 /* Descriptor signing certificate. */
1961 tok = find_by_keyword(tokens, R3_DESC_SIGNING_CERT);
1962 tor_assert(tok->object_body);
1963 /* Expecting a prop220 cert with the signing key extension, which contains
1964 * the blinded public key. */
1965 if (strcmp(tok->object_type, "ED25519 CERT") != 0) {
1966 log_warn(LD_REND, "Service descriptor signing cert wrong type (%s)",
1967 escaped(tok->object_type));
1968 goto err;
1970 if (cert_parse_and_validate(&desc->signing_key_cert, tok->object_body,
1971 tok->object_size, CERT_TYPE_SIGNING_HS_DESC,
1972 "service descriptor signing key") < 0) {
1973 goto err;
1976 /* Copy the public keys into signing_pubkey and blinded_pubkey */
1977 memcpy(&desc->signing_pubkey, &desc->signing_key_cert->signed_key,
1978 sizeof(ed25519_public_key_t));
1979 memcpy(&desc->blinded_pubkey, &desc->signing_key_cert->signing_key,
1980 sizeof(ed25519_public_key_t));
1982 /* Extract revision counter value. */
1983 tok = find_by_keyword(tokens, R3_REVISION_COUNTER);
1984 tor_assert(tok->n_args == 1);
1985 desc->revision_counter = tor_parse_uint64(tok->args[0], 10, 0,
1986 UINT64_MAX, &ok, NULL);
1987 if (!ok) {
1988 log_warn(LD_REND, "Service descriptor revision-counter is invalid");
1989 goto err;
1992 /* Extract the encrypted data section. */
1993 tok = find_by_keyword(tokens, R3_SUPERENCRYPTED);
1994 tor_assert(tok->object_body);
1995 if (strcmp(tok->object_type, "MESSAGE") != 0) {
1996 log_warn(LD_REND, "Service descriptor encrypted data section is invalid");
1997 goto err;
1999 /* Make sure the length of the encrypted blob is valid. */
2000 if (!encrypted_data_length_is_valid(tok->object_size)) {
2001 goto err;
2004 /* Copy the encrypted blob to the descriptor object so we can handle it
2005 * latter if needed. */
2006 desc->superencrypted_blob = tor_memdup(tok->object_body, tok->object_size);
2007 desc->superencrypted_blob_size = tok->object_size;
2009 /* Extract signature and verify it. */
2010 tok = find_by_keyword(tokens, R3_SIGNATURE);
2011 tor_assert(tok->n_args == 1);
2012 /* First arg here is the actual encoded signature. */
2013 if (!desc_sig_is_valid(tok->args[0], &desc->signing_pubkey,
2014 encoded_desc, encoded_len)) {
2015 goto err;
2018 return 0;
2020 err:
2021 return -1;
2024 /* Decode the version 3 encrypted section of the given descriptor desc. The
2025 * desc_encrypted_out will be populated with the decoded data. Return 0 on
2026 * success else -1. */
2027 static int
2028 desc_decode_encrypted_v3(const hs_descriptor_t *desc,
2029 hs_desc_encrypted_data_t *desc_encrypted_out)
2031 int result = -1;
2032 char *message = NULL;
2033 size_t message_len;
2034 memarea_t *area = NULL;
2035 directory_token_t *tok;
2036 smartlist_t *tokens = NULL;
2038 tor_assert(desc);
2039 tor_assert(desc_encrypted_out);
2041 /* Decrypt the superencrypted data that is located in the plaintext section
2042 * in the descriptor as a blob of bytes. */
2043 message_len = desc_decrypt_all(desc, &message);
2044 if (!message_len) {
2045 log_warn(LD_REND, "Service descriptor decryption failed.");
2046 goto err;
2048 tor_assert(message);
2050 area = memarea_new();
2051 tokens = smartlist_new();
2052 if (tokenize_string(area, message, message + message_len,
2053 tokens, hs_desc_encrypted_v3_token_table, 0) < 0) {
2054 log_warn(LD_REND, "Encrypted service descriptor is not parseable.");
2055 goto err;
2058 /* CREATE2 supported cell format. It's mandatory. */
2059 tok = find_by_keyword(tokens, R3_CREATE2_FORMATS);
2060 tor_assert(tok);
2061 decode_create2_list(desc_encrypted_out, tok->args[0]);
2062 /* Must support ntor according to the specification */
2063 if (!desc_encrypted_out->create2_ntor) {
2064 log_warn(LD_REND, "Service create2-formats does not include ntor.");
2065 goto err;
2068 /* Authentication type. It's optional but only once. */
2069 tok = find_opt_by_keyword(tokens, R3_INTRO_AUTH_REQUIRED);
2070 if (tok) {
2071 if (!decode_auth_type(desc_encrypted_out, tok->args[0])) {
2072 log_warn(LD_REND, "Service descriptor authentication type has "
2073 "invalid entry(ies).");
2074 goto err;
2078 /* Is this service a single onion service? */
2079 tok = find_opt_by_keyword(tokens, R3_SINGLE_ONION_SERVICE);
2080 if (tok) {
2081 desc_encrypted_out->single_onion_service = 1;
2084 /* Initialize the descriptor's introduction point list before we start
2085 * decoding. Having 0 intro point is valid. Then decode them all. */
2086 desc_encrypted_out->intro_points = smartlist_new();
2087 decode_intro_points(desc, desc_encrypted_out, message);
2089 /* Validation of maximum introduction points allowed. */
2090 if (smartlist_len(desc_encrypted_out->intro_points) >
2091 HS_CONFIG_V3_MAX_INTRO_POINTS) {
2092 log_warn(LD_REND, "Service descriptor contains too many introduction "
2093 "points. Maximum allowed is %d but we have %d",
2094 HS_CONFIG_V3_MAX_INTRO_POINTS,
2095 smartlist_len(desc_encrypted_out->intro_points));
2096 goto err;
2099 /* NOTE: Unknown fields are allowed because this function could be used to
2100 * decode other descriptor version. */
2102 result = 0;
2103 goto done;
2105 err:
2106 tor_assert(result < 0);
2107 desc_encrypted_data_free_contents(desc_encrypted_out);
2109 done:
2110 if (tokens) {
2111 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
2112 smartlist_free(tokens);
2114 if (area) {
2115 memarea_drop_all(area);
2117 if (message) {
2118 tor_free(message);
2120 return result;
2123 /* Table of encrypted decode function version specific. The function are
2124 * indexed by the version number so v3 callback is at index 3 in the array. */
2125 static int
2126 (*decode_encrypted_handlers[])(
2127 const hs_descriptor_t *desc,
2128 hs_desc_encrypted_data_t *desc_encrypted) =
2130 /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
2131 desc_decode_encrypted_v3,
2134 /* Decode the encrypted data section of the given descriptor and store the
2135 * data in the given encrypted data object. Return 0 on success else a
2136 * negative value on error. */
2138 hs_desc_decode_encrypted(const hs_descriptor_t *desc,
2139 hs_desc_encrypted_data_t *desc_encrypted)
2141 int ret;
2142 uint32_t version;
2144 tor_assert(desc);
2145 /* Ease our life a bit. */
2146 version = desc->plaintext_data.version;
2147 tor_assert(desc_encrypted);
2148 /* Calling this function without an encrypted blob to parse is a code flow
2149 * error. The plaintext parsing should never succeed in the first place
2150 * without an encrypted section. */
2151 tor_assert(desc->plaintext_data.superencrypted_blob);
2152 /* Let's make sure we have a supported version as well. By correctly parsing
2153 * the plaintext, this should not fail. */
2154 if (BUG(!hs_desc_is_supported_version(version))) {
2155 ret = -1;
2156 goto err;
2158 /* Extra precaution. Having no handler for the supported version should
2159 * never happened else we forgot to add it but we bumped the version. */
2160 tor_assert(ARRAY_LENGTH(decode_encrypted_handlers) >= version);
2161 tor_assert(decode_encrypted_handlers[version]);
2163 /* Run the version specific plaintext decoder. */
2164 ret = decode_encrypted_handlers[version](desc, desc_encrypted);
2165 if (ret < 0) {
2166 goto err;
2169 err:
2170 return ret;
2173 /* Table of plaintext decode function version specific. The function are
2174 * indexed by the version number so v3 callback is at index 3 in the array. */
2175 static int
2176 (*decode_plaintext_handlers[])(
2177 smartlist_t *tokens,
2178 hs_desc_plaintext_data_t *desc,
2179 const char *encoded_desc,
2180 size_t encoded_len) =
2182 /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
2183 desc_decode_plaintext_v3,
2186 /* Fully decode the given descriptor plaintext and store the data in the
2187 * plaintext data object. Returns 0 on success else a negative value. */
2189 hs_desc_decode_plaintext(const char *encoded,
2190 hs_desc_plaintext_data_t *plaintext)
2192 int ok = 0, ret = -1;
2193 memarea_t *area = NULL;
2194 smartlist_t *tokens = NULL;
2195 size_t encoded_len;
2196 directory_token_t *tok;
2198 tor_assert(encoded);
2199 tor_assert(plaintext);
2201 /* Check that descriptor is within size limits. */
2202 encoded_len = strlen(encoded);
2203 if (encoded_len >= hs_cache_get_max_descriptor_size()) {
2204 log_warn(LD_REND, "Service descriptor is too big (%lu bytes)",
2205 (unsigned long) encoded_len);
2206 goto err;
2209 area = memarea_new();
2210 tokens = smartlist_new();
2211 /* Tokenize the descriptor so we can start to parse it. */
2212 if (tokenize_string(area, encoded, encoded + encoded_len, tokens,
2213 hs_desc_v3_token_table, 0) < 0) {
2214 log_warn(LD_REND, "Service descriptor is not parseable");
2215 goto err;
2218 /* Get the version of the descriptor which is the first mandatory field of
2219 * the descriptor. From there, we'll decode the right descriptor version. */
2220 tok = find_by_keyword(tokens, R_HS_DESCRIPTOR);
2221 tor_assert(tok->n_args == 1);
2222 plaintext->version = (uint32_t) tor_parse_ulong(tok->args[0], 10, 0,
2223 UINT32_MAX, &ok, NULL);
2224 if (!ok) {
2225 log_warn(LD_REND, "Service descriptor has unparseable version %s",
2226 escaped(tok->args[0]));
2227 goto err;
2229 if (!hs_desc_is_supported_version(plaintext->version)) {
2230 log_warn(LD_REND, "Service descriptor has unsupported version %" PRIu32,
2231 plaintext->version);
2232 goto err;
2234 /* Extra precaution. Having no handler for the supported version should
2235 * never happened else we forgot to add it but we bumped the version. */
2236 tor_assert(ARRAY_LENGTH(decode_plaintext_handlers) >= plaintext->version);
2237 tor_assert(decode_plaintext_handlers[plaintext->version]);
2239 /* Run the version specific plaintext decoder. */
2240 ret = decode_plaintext_handlers[plaintext->version](tokens, plaintext,
2241 encoded, encoded_len);
2242 if (ret < 0) {
2243 goto err;
2245 /* Success. Descriptor has been populated with the data. */
2246 ret = 0;
2248 err:
2249 if (tokens) {
2250 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
2251 smartlist_free(tokens);
2253 if (area) {
2254 memarea_drop_all(area);
2256 return ret;
2259 /* Fully decode an encoded descriptor and set a newly allocated descriptor
2260 * object in desc_out. Subcredentials are used if not NULL else it's ignored.
2262 * Return 0 on success. A negative value is returned on error and desc_out is
2263 * set to NULL. */
2265 hs_desc_decode_descriptor(const char *encoded,
2266 const uint8_t *subcredential,
2267 hs_descriptor_t **desc_out)
2269 int ret = -1;
2270 hs_descriptor_t *desc;
2272 tor_assert(encoded);
2274 desc = tor_malloc_zero(sizeof(hs_descriptor_t));
2276 /* Subcredentials are optional. */
2277 if (BUG(!subcredential)) {
2278 log_warn(LD_GENERAL, "Tried to decrypt without subcred. Impossible!");
2279 goto err;
2282 memcpy(desc->subcredential, subcredential, sizeof(desc->subcredential));
2284 ret = hs_desc_decode_plaintext(encoded, &desc->plaintext_data);
2285 if (ret < 0) {
2286 goto err;
2289 ret = hs_desc_decode_encrypted(desc, &desc->encrypted_data);
2290 if (ret < 0) {
2291 goto err;
2294 if (desc_out) {
2295 *desc_out = desc;
2296 } else {
2297 hs_descriptor_free(desc);
2299 return ret;
2301 err:
2302 hs_descriptor_free(desc);
2303 if (desc_out) {
2304 *desc_out = NULL;
2307 tor_assert(ret < 0);
2308 return ret;
2311 /* Table of encode function version specific. The functions are indexed by the
2312 * version number so v3 callback is at index 3 in the array. */
2313 static int
2314 (*encode_handlers[])(
2315 const hs_descriptor_t *desc,
2316 const ed25519_keypair_t *signing_kp,
2317 char **encoded_out) =
2319 /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
2320 desc_encode_v3,
2323 /* Encode the given descriptor desc including signing with the given key pair
2324 * signing_kp. On success, encoded_out points to a newly allocated NUL
2325 * terminated string that contains the encoded descriptor as a string.
2327 * Return 0 on success and encoded_out is a valid pointer. On error, -1 is
2328 * returned and encoded_out is set to NULL. */
2329 MOCK_IMPL(int,
2330 hs_desc_encode_descriptor,(const hs_descriptor_t *desc,
2331 const ed25519_keypair_t *signing_kp,
2332 char **encoded_out))
2334 int ret = -1;
2335 uint32_t version;
2337 tor_assert(desc);
2338 tor_assert(encoded_out);
2340 /* Make sure we support the version of the descriptor format. */
2341 version = desc->plaintext_data.version;
2342 if (!hs_desc_is_supported_version(version)) {
2343 goto err;
2345 /* Extra precaution. Having no handler for the supported version should
2346 * never happened else we forgot to add it but we bumped the version. */
2347 tor_assert(ARRAY_LENGTH(encode_handlers) >= version);
2348 tor_assert(encode_handlers[version]);
2350 ret = encode_handlers[version](desc, signing_kp, encoded_out);
2351 if (ret < 0) {
2352 goto err;
2355 /* Try to decode what we just encoded. Symmetry is nice! */
2356 ret = hs_desc_decode_descriptor(*encoded_out, desc->subcredential, NULL);
2357 if (BUG(ret < 0)) {
2358 goto err;
2361 return 0;
2363 err:
2364 *encoded_out = NULL;
2365 return ret;
2368 /* Free the descriptor plaintext data object. */
2369 void
2370 hs_desc_plaintext_data_free(hs_desc_plaintext_data_t *desc)
2372 desc_plaintext_data_free_contents(desc);
2373 tor_free(desc);
2376 /* Free the descriptor encrypted data object. */
2377 void
2378 hs_desc_encrypted_data_free(hs_desc_encrypted_data_t *desc)
2380 desc_encrypted_data_free_contents(desc);
2381 tor_free(desc);
2384 /* Free the given descriptor object. */
2385 void
2386 hs_descriptor_free(hs_descriptor_t *desc)
2388 if (!desc) {
2389 return;
2392 desc_plaintext_data_free_contents(&desc->plaintext_data);
2393 desc_encrypted_data_free_contents(&desc->encrypted_data);
2394 tor_free(desc);
2397 /* Return the size in bytes of the given plaintext data object. A sizeof() is
2398 * not enough because the object contains pointers and the encrypted blob.
2399 * This is particularly useful for our OOM subsystem that tracks the HSDir
2400 * cache size for instance. */
2401 size_t
2402 hs_desc_plaintext_obj_size(const hs_desc_plaintext_data_t *data)
2404 tor_assert(data);
2405 return (sizeof(*data) + sizeof(*data->signing_key_cert) +
2406 data->superencrypted_blob_size);
2409 /* Return the size in bytes of the given encrypted data object. Used by OOM
2410 * subsystem. */
2411 static size_t
2412 hs_desc_encrypted_obj_size(const hs_desc_encrypted_data_t *data)
2414 tor_assert(data);
2415 size_t intro_size = 0;
2416 if (data->intro_auth_types) {
2417 intro_size +=
2418 smartlist_len(data->intro_auth_types) * sizeof(intro_auth_types);
2420 if (data->intro_points) {
2421 /* XXX could follow pointers here and get more accurate size */
2422 intro_size +=
2423 smartlist_len(data->intro_points) * sizeof(hs_desc_intro_point_t);
2426 return sizeof(*data) + intro_size;
2429 /* Return the size in bytes of the given descriptor object. Used by OOM
2430 * subsystem. */
2431 size_t
2432 hs_desc_obj_size(const hs_descriptor_t *data)
2434 tor_assert(data);
2435 return (hs_desc_plaintext_obj_size(&data->plaintext_data) +
2436 hs_desc_encrypted_obj_size(&data->encrypted_data) +
2437 sizeof(data->subcredential));
2440 /* Return a newly allocated descriptor intro point. */
2441 hs_desc_intro_point_t *
2442 hs_desc_intro_point_new(void)
2444 hs_desc_intro_point_t *ip = tor_malloc_zero(sizeof(*ip));
2445 ip->link_specifiers = smartlist_new();
2446 return ip;
2449 /* Free a descriptor intro point object. */
2450 void
2451 hs_desc_intro_point_free(hs_desc_intro_point_t *ip)
2453 if (ip == NULL) {
2454 return;
2456 if (ip->link_specifiers) {
2457 SMARTLIST_FOREACH(ip->link_specifiers, hs_desc_link_specifier_t *,
2458 ls, hs_desc_link_specifier_free(ls));
2459 smartlist_free(ip->link_specifiers);
2461 tor_cert_free(ip->auth_key_cert);
2462 tor_cert_free(ip->enc_key_cert);
2463 crypto_pk_free(ip->legacy.key);
2464 tor_free(ip->legacy.cert.encoded);
2465 tor_free(ip);
2468 /* Free the given descriptor link specifier. */
2469 void
2470 hs_desc_link_specifier_free(hs_desc_link_specifier_t *ls)
2472 if (ls == NULL) {
2473 return;
2475 tor_free(ls);
2478 /* Return a newly allocated descriptor link specifier using the given extend
2479 * info and requested type. Return NULL on error. */
2480 hs_desc_link_specifier_t *
2481 hs_desc_link_specifier_new(const extend_info_t *info, uint8_t type)
2483 hs_desc_link_specifier_t *ls = NULL;
2485 tor_assert(info);
2487 ls = tor_malloc_zero(sizeof(*ls));
2488 ls->type = type;
2489 switch (ls->type) {
2490 case LS_IPV4:
2491 if (info->addr.family != AF_INET) {
2492 goto err;
2494 tor_addr_copy(&ls->u.ap.addr, &info->addr);
2495 ls->u.ap.port = info->port;
2496 break;
2497 case LS_IPV6:
2498 if (info->addr.family != AF_INET6) {
2499 goto err;
2501 tor_addr_copy(&ls->u.ap.addr, &info->addr);
2502 ls->u.ap.port = info->port;
2503 break;
2504 case LS_LEGACY_ID:
2505 /* Bug out if the identity digest is not set */
2506 if (BUG(tor_mem_is_zero(info->identity_digest,
2507 sizeof(info->identity_digest)))) {
2508 goto err;
2510 memcpy(ls->u.legacy_id, info->identity_digest, sizeof(ls->u.legacy_id));
2511 break;
2512 case LS_ED25519_ID:
2513 /* ed25519 keys are optional for intro points */
2514 if (ed25519_public_key_is_zero(&info->ed_identity)) {
2515 goto err;
2517 memcpy(ls->u.ed25519_id, info->ed_identity.pubkey,
2518 sizeof(ls->u.ed25519_id));
2519 break;
2520 default:
2521 /* Unknown type is code flow error. */
2522 tor_assert(0);
2525 return ls;
2526 err:
2527 tor_free(ls);
2528 return NULL;
2531 /* From the given descriptor, remove and free every introduction point. */
2532 void
2533 hs_descriptor_clear_intro_points(hs_descriptor_t *desc)
2535 smartlist_t *ips;
2537 tor_assert(desc);
2539 ips = desc->encrypted_data.intro_points;
2540 if (ips) {
2541 SMARTLIST_FOREACH(ips, hs_desc_intro_point_t *,
2542 ip, hs_desc_intro_point_free(ip));
2543 smartlist_clear(ips);
2547 /* From a descriptor link specifier object spec, returned a newly allocated
2548 * link specifier object that is the encoded representation of spec. Return
2549 * NULL on error. */
2550 link_specifier_t *
2551 hs_desc_lspec_to_trunnel(const hs_desc_link_specifier_t *spec)
2553 tor_assert(spec);
2555 link_specifier_t *ls = link_specifier_new();
2556 link_specifier_set_ls_type(ls, spec->type);
2558 switch (spec->type) {
2559 case LS_IPV4:
2560 link_specifier_set_un_ipv4_addr(ls,
2561 tor_addr_to_ipv4h(&spec->u.ap.addr));
2562 link_specifier_set_un_ipv4_port(ls, spec->u.ap.port);
2563 /* Four bytes IPv4 and two bytes port. */
2564 link_specifier_set_ls_len(ls, sizeof(spec->u.ap.addr.addr.in_addr) +
2565 sizeof(spec->u.ap.port));
2566 break;
2567 case LS_IPV6:
2569 size_t addr_len = link_specifier_getlen_un_ipv6_addr(ls);
2570 const uint8_t *in6_addr = tor_addr_to_in6_addr8(&spec->u.ap.addr);
2571 uint8_t *ipv6_array = link_specifier_getarray_un_ipv6_addr(ls);
2572 memcpy(ipv6_array, in6_addr, addr_len);
2573 link_specifier_set_un_ipv6_port(ls, spec->u.ap.port);
2574 /* Sixteen bytes IPv6 and two bytes port. */
2575 link_specifier_set_ls_len(ls, addr_len + sizeof(spec->u.ap.port));
2576 break;
2578 case LS_LEGACY_ID:
2580 size_t legacy_id_len = link_specifier_getlen_un_legacy_id(ls);
2581 uint8_t *legacy_id_array = link_specifier_getarray_un_legacy_id(ls);
2582 memcpy(legacy_id_array, spec->u.legacy_id, legacy_id_len);
2583 link_specifier_set_ls_len(ls, legacy_id_len);
2584 break;
2586 case LS_ED25519_ID:
2588 size_t ed25519_id_len = link_specifier_getlen_un_ed25519_id(ls);
2589 uint8_t *ed25519_id_array = link_specifier_getarray_un_ed25519_id(ls);
2590 memcpy(ed25519_id_array, spec->u.ed25519_id, ed25519_id_len);
2591 link_specifier_set_ls_len(ls, ed25519_id_len);
2592 break;
2594 default:
2595 tor_assert_nonfatal_unreached();
2596 link_specifier_free(ls);
2597 ls = NULL;
2600 return ls;