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