tor

The Tor anonymity network
git clone https://git.dasho.dev/tor.git
Log | Files | Refs | README | LICENSE

hs_descriptor.c (109142B)


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