tor

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

onion_ntor_v3.c (27624B)


      1 /* Copyright (c) 2001 Matej Pfajfar.
      2 * Copyright (c) 2001-2004, Roger Dingledine.
      3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
      4 * Copyright (c) 2007-2021, The Tor Project, Inc. */
      5 /* See LICENSE for licensing information */
      6 
      7 /**
      8 * @file onion_ntor_v3.c
      9 * @brief Implements the version 3 ntor handshake as first specified in
     10 * proposal 332.
     11 *
     12 * The v3 ntor handshake differs from the earlier versions (ntor and hs-ntor)
     13 * primarily in that it allows the client to send an authenticated encrypted
     14 * message as part of its onion skin, and allows the relay to send and
     15 * encrypted authenticated reply as part of its response.
     16 *
     17 * It also takes a "verification string" -- the handshake cannot succeed
     18 * unless both parties use the same value for their verification stream.
     19 **/
     20 
     21 #define ONION_NTOR_V3_PRIVATE
     22 
     23 #include "orconfig.h"
     24 #include "core/crypto/onion_ntor_v3.h"
     25 
     26 #include "lib/arch/bytes.h"
     27 #include "lib/crypt_ops/crypto_digest.h"
     28 #include "lib/crypt_ops/crypto_rand.h"
     29 #include "lib/crypt_ops/crypto_util.h"
     30 #include "lib/ctime/di_ops.h"
     31 #include "lib/log/util_bug.h"
     32 
     33 #include <string.h>
     34 
     35 /* Parameters used to keep the outputs of this handshake from colliding with
     36 * others.  These are defined in the specification. */
     37 #define PROTOID "ntor3-curve25519-sha3_256-1"
     38 #define TWEAK(A) (PROTOID ":" A)
     39 
     40 #define T_MSGKDF TWEAK("kdf_phase1")
     41 #define T_MSGMAC TWEAK("msg_mac")
     42 #define T_KEY_SEED TWEAK("key_seed")
     43 #define T_VERIFY TWEAK("verify")
     44 #define T_FINAL TWEAK("kdf_final")
     45 #define T_AUTH TWEAK("auth_final")
     46 
     47 /**
     48 * Add @a len bytes of @a data as input to the provided @a xof.
     49 *
     50 * (This is provided just for abbreviation).
     51 **/
     52 #define xof_add(xof, data, len) crypto_xof_add_bytes((xof), (data), (len))
     53 /**
     54 * Add @a len bytes of @a data as input to the provided @a xof,
     55 * prefixed with an encoding of the length.
     56 *
     57 * This is equivalent to ENCAP(data) in the spec.
     58 **/
     59 static void
     60 xof_add_encap(crypto_xof_t *xof, const uint8_t *data, size_t len)
     61 {
     62  uint64_t len64 = tor_htonll(len);
     63  xof_add(xof, (uint8_t *)(&len64), 8);
     64  xof_add(xof, data, len);
     65 }
     66 /**
     67 * Add an encapsulated tweak to the provided xof.
     68 **/
     69 #define xof_add_tweak(d, s) xof_add_encap((d), (const uint8_t *)(s), strlen(s))
     70 
     71 /**
     72 * Add @a len bytes of @a data to the provided @a digest.
     73 *
     74 * This is provided as an abbreviation, and to get the types right.
     75 **/
     76 static void
     77 d_add(crypto_digest_t *digest, const uint8_t *data, size_t len)
     78 {
     79  crypto_digest_add_bytes(digest, (const char *)data, len);
     80 }
     81 /**
     82 * Add @a len bytes of @a data to the provided @a digest, prefixed
     83 * with the encoded length.
     84 *
     85 * This is equivalent to ENCAP(data) from the spec.
     86 **/
     87 static void
     88 d_add_encap(crypto_digest_t *digest, const uint8_t *data, size_t len)
     89 {
     90  uint64_t len64 = tor_htonll(len);
     91  d_add(digest, (const uint8_t *)(&len64), 8);
     92  d_add(digest, data, len);
     93 }
     94 /**
     95 * Add an encapsulated tweak to the provided digest.
     96 **/
     97 #define d_add_tweak(d, s) d_add_encap((d), (const uint8_t *)(s), strlen(s))
     98 
     99 /**
    100 * Helper: copy @a len bytes of @a data onto *@a ptr, and advance @a ptr
    101 * forward by @a len bytes.
    102 *
    103 * Asserts that @a ptr will not be advanced beyond @a endptr.
    104 **/
    105 static void
    106 push(uint8_t **ptr, const uint8_t *endptr, const uint8_t *data, size_t len)
    107 {
    108  size_t remaining = endptr - *ptr;
    109  tor_assert(len <= remaining);
    110  memcpy(*ptr, data, len);
    111  *ptr += len;
    112 }
    113 
    114 /**
    115 * Helper: Drop storage held by @a state, after wiping it.
    116 **/
    117 void
    118 ntor3_handshake_state_free_(ntor3_handshake_state_t *state)
    119 {
    120  if (!state)
    121    return;
    122 
    123  memwipe(state, 0, sizeof(*state));
    124  tor_free(state);
    125 }
    126 
    127 /**
    128 * Perform a client-side v3 ntor handshake with a given relay.
    129 *
    130 * As inputs this function takes the relay's Ed25519 identity (@a relay_id),
    131 * the relay's current ntor onion key (@a relay_key), a verification string
    132 * (@a verification_len bytes at @a verification), and a message to send
    133 * as part of the handshake (@a message_len bytes at @a message).
    134 *
    135 * The message will be encrypted and authenticated to the relay, but will not
    136 * receive the same forward secrecy as the rest of the handshake.  We should
    137 * not put any super-confidential data in it.
    138 *
    139 * The handshake will only succeed if the relay uses the same verification
    140 * string as we are using.
    141 *
    142 * As outputs, this function returns 0 on success and -1 on failure.  On
    143 * success, it sets @a onion_skin_out and @a onion_skin_len_out to a newly
    144 * allocated handshake message that the client can send as part of its CREATE2
    145 * or EXTEND2 cell.  It also sets it sets @a handshake_state_out to a newly
    146 * allocated handshake state object; the client needs to use this object to
    147 * process the relay's eventual reply.
    148 **/
    149 int
    150 onion_skin_ntor3_create(const ed25519_public_key_t *relay_id,
    151                        const curve25519_public_key_t *relay_key,
    152                        const uint8_t *verification,
    153                        const size_t verification_len,
    154                        const uint8_t *message,
    155                        const size_t message_len,
    156                        ntor3_handshake_state_t **handshake_state_out,
    157                        uint8_t **onion_skin_out,
    158                        size_t *onion_skin_len_out)
    159 {
    160  curve25519_keypair_t client_keypair;
    161  if (curve25519_keypair_generate(&client_keypair, 0) < 0) {
    162    return -1;
    163  }
    164  int r = onion_skin_ntor3_create_nokeygen(
    165                                   &client_keypair,
    166                                   relay_id,
    167                                   relay_key,
    168                                   verification,
    169                                   verification_len,
    170                                   message,
    171                                   message_len,
    172                                   handshake_state_out,
    173                                   onion_skin_out,
    174                                   onion_skin_len_out);
    175  memwipe(&client_keypair, 0, sizeof(client_keypair));
    176  return r;
    177 }
    178 
    179 /**
    180 * Like onion_skin_ntor3_create, but do not generate a new ephemeral keypair.
    181 * Instead, take the ephemeral keypair (x,X) from @a client_keypair.
    182 *
    183 * (Having a separate function for this lets us test the code for correct
    184 * behavior.)
    185 **/
    186 STATIC int
    187 onion_skin_ntor3_create_nokeygen(
    188                        const curve25519_keypair_t *client_keypair,
    189                        const ed25519_public_key_t *relay_id,
    190                        const curve25519_public_key_t *relay_key,
    191                        const uint8_t *verification,
    192                        const size_t verification_len,
    193                        const uint8_t *message,
    194                        const size_t message_len,
    195                        ntor3_handshake_state_t **handshake_state_out,
    196                        uint8_t **onion_skin_out,
    197                        size_t *onion_skin_len_out)
    198 {
    199  *handshake_state_out = NULL;
    200  *onion_skin_out = NULL;
    201  *onion_skin_len_out = 0;
    202 
    203  // Set up the handshake state object.
    204  *handshake_state_out = tor_malloc_zero(sizeof(ntor3_handshake_state_t));
    205  memcpy(&(*handshake_state_out)->client_keypair, client_keypair,
    206         sizeof(*client_keypair));
    207  memcpy(&(*handshake_state_out)->relay_id, relay_id, sizeof(*relay_id));
    208  memcpy(&(*handshake_state_out)->relay_key, relay_key, sizeof(*relay_key));
    209 
    210  // Perform the first DH handshake.
    211  curve25519_handshake((*handshake_state_out)->bx,
    212                       &client_keypair->seckey, relay_key);
    213  if (safe_mem_is_zero((*handshake_state_out)->bx, CURVE25519_OUTPUT_LEN)) {
    214    // Okay to return early here, since our behavior here doesn't
    215    // cause a visible timing sidechannel.
    216    return -1;
    217  }
    218 
    219  // Compute phase1_keys.
    220  uint8_t enc_key[CIPHER256_KEY_LEN];
    221  uint8_t mac_key[DIGEST256_LEN];
    222  {
    223    crypto_xof_t *xof = crypto_xof_new();
    224    // secret_input_phase1 = Bx | ID | X | B | PROTOID | ENCAP(VER)
    225    xof_add_tweak(xof, T_MSGKDF);
    226    xof_add(xof, (*handshake_state_out)->bx, CURVE25519_OUTPUT_LEN);
    227    xof_add(xof, relay_id->pubkey, ED25519_PUBKEY_LEN);
    228    xof_add(xof, client_keypair->pubkey.public_key, CURVE25519_PUBKEY_LEN);
    229    xof_add(xof, relay_key->public_key, CURVE25519_PUBKEY_LEN);
    230    xof_add(xof, (const uint8_t *)PROTOID, strlen(PROTOID));
    231    xof_add_encap(xof, verification, verification_len);
    232    crypto_xof_squeeze_bytes(xof, enc_key, sizeof(enc_key));
    233    crypto_xof_squeeze_bytes(xof, mac_key, sizeof(mac_key));
    234    crypto_xof_free(xof);
    235  }
    236 
    237  // Compute encrypted message.
    238  uint8_t *encrypted_message = tor_memdup(message, message_len);
    239  {
    240    crypto_cipher_t *c =
    241      crypto_cipher_new_with_bits((const char *)enc_key, 256);
    242    crypto_cipher_crypt_inplace(c, (char *)encrypted_message, message_len);
    243    crypto_cipher_free(c);
    244  }
    245 
    246  // Compute the MAC value.
    247  {
    248    crypto_digest_t *m = crypto_digest256_new(DIGEST_SHA3_256);
    249    d_add_tweak(m, T_MSGMAC);
    250    d_add_encap(m, mac_key, sizeof(mac_key));
    251    d_add(m, relay_id->pubkey, ED25519_PUBKEY_LEN);
    252    d_add(m, relay_key->public_key, CURVE25519_PUBKEY_LEN);
    253    d_add(m, client_keypair->pubkey.public_key, CURVE25519_PUBKEY_LEN);
    254    d_add(m, encrypted_message, message_len);
    255    crypto_digest_get_digest(m,
    256                             (char *)(*handshake_state_out)->msg_mac,
    257                             DIGEST256_LEN);
    258    crypto_digest_free(m);
    259  }
    260 
    261  // Build the onionskin.
    262  *onion_skin_len_out = (ED25519_PUBKEY_LEN + CURVE25519_PUBKEY_LEN*2 +
    263                          DIGEST256_LEN + message_len);
    264  *onion_skin_out = tor_malloc(*onion_skin_len_out);
    265  {
    266    uint8_t *ptr = *onion_skin_out, *end = ptr + *onion_skin_len_out;
    267 
    268    push(&ptr, end, relay_id->pubkey, ED25519_PUBKEY_LEN);
    269    push(&ptr, end, relay_key->public_key, CURVE25519_PUBKEY_LEN);
    270    push(&ptr, end, client_keypair->pubkey.public_key, CURVE25519_PUBKEY_LEN);
    271    push(&ptr, end, encrypted_message, message_len);
    272    push(&ptr, end, (*handshake_state_out)->msg_mac, DIGEST256_LEN);
    273    tor_assert(ptr == end);
    274  }
    275 
    276  memwipe(&enc_key, 0, sizeof(enc_key));
    277  memwipe(&mac_key, 0, sizeof(mac_key));
    278  memwipe(encrypted_message, 0, message_len);
    279  tor_free(encrypted_message);
    280 
    281  return 0;
    282 }
    283 
    284 /**
    285 * Complete a client-side v3 ntor handshake.
    286 *
    287 * Takes a @a handshake_state returned earlier by `onion_skin_ntor3_create()`,
    288 * and the relay's reply to that handshake (@a reply_len bytes at @a
    289 * handshake_reply).  Also takes a verification string (@a verification_len
    290 * bytes at @a verification).
    291 *
    292 * Returns 0 on success and -1 on failure. On success, generates @a key_len
    293 * bytes of key material into the provided @a keys_out buffer, and sets @a
    294 * message_out to the message that the relay sent in reply to our message (and
    295 * sets @a message_out_len to that message's length).
    296 **/
    297 int
    298 onion_ntor3_client_handshake(const ntor3_handshake_state_t *handshake_state,
    299                             const uint8_t *handshake_reply,
    300                             size_t reply_len,
    301                             const uint8_t *verification,
    302                             size_t verification_len,
    303                             uint8_t *keys_out,
    304                             size_t keys_out_len,
    305                             uint8_t **message_out,
    306                             size_t *message_len_out)
    307 {
    308  *message_out = NULL;
    309  *message_len_out = 0;
    310 
    311  int problems = 0;
    312 
    313  // Parse the relay's message.
    314  curve25519_public_key_t relay_Y;
    315  uint8_t relay_auth[DIGEST256_LEN];
    316  size_t encrypted_msg_len;
    317  const uint8_t *encrypted_msg;
    318  {
    319    if (reply_len < CURVE25519_PUBKEY_LEN + DIGEST256_LEN) {
    320      // Okay to return early here, since the message is completely
    321      // ill-formed, so we can't leak anything.
    322      ++problems;
    323      goto done;
    324    }
    325    encrypted_msg_len = reply_len - (CURVE25519_PUBKEY_LEN + DIGEST256_LEN);
    326 
    327    memcpy(&relay_Y.public_key, handshake_reply, CURVE25519_PUBKEY_LEN);
    328    handshake_reply += CURVE25519_PUBKEY_LEN;
    329    memcpy(&relay_auth, handshake_reply, DIGEST256_LEN);
    330    handshake_reply += DIGEST256_LEN;
    331    encrypted_msg = handshake_reply;
    332  }
    333 
    334  // Finish the second diffie hellman handshake.
    335  uint8_t yx[CURVE25519_OUTPUT_LEN];
    336  curve25519_handshake(yx, &handshake_state->client_keypair.seckey, &relay_Y);
    337  problems |= safe_mem_is_zero(yx, sizeof(yx));
    338 
    339  // Compute two tweaked hashes of secret_input.
    340  uint8_t key_seed[DIGEST256_LEN], verify[DIGEST256_LEN];
    341  {
    342    crypto_digest_t *ks = crypto_digest256_new(DIGEST_SHA3_256);
    343    crypto_digest_t *v = crypto_digest256_new(DIGEST_SHA3_256);
    344    d_add_tweak(ks, T_KEY_SEED);
    345    d_add_tweak(v, T_VERIFY);
    346 #define ADD2(s,len) STMT_BEGIN { \
    347      d_add(ks, (s),(len)); d_add(v, (s), (len));       \
    348    } STMT_END
    349 #define ADD2_ENCAP(s,len) STMT_BEGIN { \
    350        d_add_encap(ks, (s),(len)); d_add_encap(v, (s), (len)); \
    351      } STMT_END
    352 
    353    ADD2(yx, sizeof(yx));
    354    ADD2(handshake_state->bx, sizeof(handshake_state->bx));
    355    ADD2(handshake_state->relay_id.pubkey, ED25519_PUBKEY_LEN);
    356    ADD2(handshake_state->relay_key.public_key, CURVE25519_PUBKEY_LEN);
    357    ADD2(handshake_state->client_keypair.pubkey.public_key,
    358         CURVE25519_PUBKEY_LEN);
    359    ADD2(relay_Y.public_key, CURVE25519_PUBKEY_LEN);
    360    ADD2((const uint8_t *)PROTOID, strlen(PROTOID));
    361    ADD2_ENCAP(verification, verification_len);
    362 
    363    crypto_digest_get_digest(ks, (char*) key_seed, DIGEST256_LEN);
    364    crypto_digest_get_digest(v, (char*) verify, DIGEST256_LEN);
    365    crypto_digest_free(ks);
    366    crypto_digest_free(v);
    367  }
    368 
    369  // compute expected auth value.
    370  uint8_t auth_computed[DIGEST256_LEN];
    371  {
    372    crypto_digest_t *d = crypto_digest256_new(DIGEST_SHA3_256);
    373    d_add_tweak(d, T_AUTH);
    374    d_add(d, verify, sizeof(verify));
    375    d_add(d, handshake_state->relay_id.pubkey, ED25519_PUBKEY_LEN);
    376    d_add(d, handshake_state->relay_key.public_key, CURVE25519_PUBKEY_LEN);
    377    d_add(d, relay_Y.public_key, CURVE25519_PUBKEY_LEN);
    378    d_add(d, handshake_state->client_keypair.pubkey.public_key,
    379          CURVE25519_PUBKEY_LEN);
    380    d_add(d, handshake_state->msg_mac, DIGEST256_LEN);
    381    d_add_encap(d, encrypted_msg, encrypted_msg_len);
    382    d_add(d, (const uint8_t*)PROTOID, strlen(PROTOID));
    383    d_add(d, (const uint8_t*)"Server", strlen("Server"));
    384    crypto_digest_get_digest(d, (char *)auth_computed, DIGEST256_LEN);
    385    crypto_digest_free(d);
    386  }
    387 
    388  // Check authentication value.
    389  problems |= tor_memneq(auth_computed, relay_auth, DIGEST256_LEN);
    390 
    391  // Compute keystream, decrypt message, and return.
    392  *message_out = tor_malloc(encrypted_msg_len);
    393  *message_len_out = encrypted_msg_len;
    394  uint8_t enc_key[CIPHER256_KEY_LEN];
    395  {
    396    crypto_xof_t *xof = crypto_xof_new();
    397    xof_add_tweak(xof, T_FINAL);
    398    xof_add(xof, key_seed, sizeof(key_seed));
    399    crypto_xof_squeeze_bytes(xof, enc_key, sizeof(enc_key));
    400    crypto_xof_squeeze_bytes(xof, (uint8_t *)keys_out, keys_out_len);
    401    crypto_xof_free(xof);
    402 
    403    crypto_cipher_t *c =
    404      crypto_cipher_new_with_bits((const char *)enc_key, 256);
    405    crypto_cipher_decrypt(c, (char *)*message_out,
    406                          (const char *)encrypted_msg, encrypted_msg_len);
    407    crypto_cipher_free(c);
    408  }
    409 
    410 done:
    411  memwipe(&relay_Y, 0, sizeof(relay_Y));
    412  memwipe(&relay_auth, 0, sizeof(relay_auth));
    413  memwipe(&yx, 0, sizeof(yx));
    414  memwipe(key_seed, 0, sizeof(key_seed));
    415  memwipe(verify, 0, sizeof(verify));
    416  memwipe(enc_key, 0, sizeof(enc_key));
    417  if (problems) {
    418    if (*message_out) {
    419      memwipe(*message_out, 0, *message_len_out);
    420      tor_free(*message_out); // Sets it to NULL.
    421    }
    422    *message_len_out = 0;
    423    crypto_rand((char*)keys_out, keys_out_len); // In case bad code uses it.
    424    return -1;
    425  }
    426 
    427  return 0;
    428 }
    429 
    430 /**
    431 * Wipe a server handshake state, and release the storage it holds.
    432 **/
    433 void
    434 ntor3_server_handshake_state_free_(ntor3_server_handshake_state_t *state)
    435 {
    436  if (state == NULL)
    437    return;
    438 
    439  memwipe(state, 0, sizeof(ntor3_server_handshake_state_t));
    440  tor_free(state);
    441 }
    442 
    443 /**
    444 * As a relay, start handling a client's v3 ntor handshake.
    445 *
    446 * This function performs the _first half_ of the handshake, up to the point
    447 * where the client's message is decoded.  After calling it, the relay should
    448 * decide how and whether to reply to the client's message, compose its reply,
    449 * and call `onion_skin_ntor3_server_handshake_part2`.
    450 *
    451 * It takes as input a map of the relay's known onion keys in @a private_keys,
    452 * along with a fake @a junk_key to use if there is a complete mismatch.  It
    453 * takes the relay's ed25519 identity in @a my_id, along with the client's
    454 * handshake message (@a client_handshake_len bytes in @a client_handshake),
    455 * and a verification string (@a verification_len bytes in @a verification).
    456 *
    457 * Return 0 on success, and -1 on failure.  On success, sets @a
    458 * client_message_out to a newly allocated string holding the plaintext of the
    459 * message that the client sent as part of its handshake, and @a
    460 * client_message_out_len to its length. Also sets @a state_out to a newly
    461 * allocated state object holding the intermediate computation for this
    462 * handshake.
    463 **/
    464 int
    465 onion_skin_ntor3_server_handshake_part1(
    466                const di_digest256_map_t *private_keys,
    467                const curve25519_keypair_t *junk_key,
    468                const ed25519_public_key_t *my_id,
    469                const uint8_t *client_handshake,
    470                size_t client_handshake_len,
    471                const uint8_t *verification,
    472                size_t verification_len,
    473                uint8_t **client_message_out,
    474                size_t *client_message_len_out,
    475                ntor3_server_handshake_state_t **state_out)
    476 {
    477  *client_message_out = NULL;
    478  *client_message_len_out = 0;
    479  *state_out = NULL;
    480 
    481  int problems = 0;
    482 
    483  // Initialize state.
    484  (*state_out) = tor_malloc_zero(sizeof(ntor3_server_handshake_state_t));
    485  memcpy(&(*state_out)->my_id, my_id, sizeof(*my_id));
    486 
    487  const uint8_t *wanted_id; // [ED25519_PUBKEY_LEN]
    488  const uint8_t *wanted_key; // [CURVE25519_PUBKEY_LEN]
    489  const uint8_t *encrypted_message;
    490  size_t encrypted_message_len;
    491  // Unpack the client handshake.
    492  {
    493    const uint8_t *ptr = client_handshake;
    494    const uint8_t *end = ptr + client_handshake_len;
    495 
    496    if (client_handshake_len <
    497        ED25519_PUBKEY_LEN + CURVE25519_PUBKEY_LEN * 2 + DIGEST256_LEN) {
    498      // Okay to end early; the client knows this is unparseable already.
    499      ++problems;
    500      goto done;
    501    }
    502    wanted_id = ptr;
    503    ptr += ED25519_PUBKEY_LEN;
    504    wanted_key = ptr;
    505    ptr += CURVE25519_PUBKEY_LEN;
    506    memcpy((*state_out)->client_key.public_key, ptr, CURVE25519_PUBKEY_LEN);
    507    ptr += CURVE25519_PUBKEY_LEN;
    508    size_t remaining = (end-ptr);
    509    if (BUG(remaining < DIGEST256_LEN)) {
    510      // Okay to end early; this is a bug.
    511      ++problems;
    512      goto done;
    513    }
    514    encrypted_message = ptr;
    515    encrypted_message_len = remaining - DIGEST256_LEN;
    516    ptr += encrypted_message_len;
    517    remaining = (end-ptr);
    518    tor_assert(remaining == DIGEST256_LEN);
    519    memcpy((*state_out)->msg_mac, ptr, DIGEST256_LEN);
    520  }
    521 
    522  // Check the identity.
    523  problems |= tor_memneq(my_id->pubkey, wanted_id, ED25519_PUBKEY_LEN);
    524 
    525  // Find the correct keypair.
    526  const curve25519_keypair_t *keypair =
    527    dimap_search(private_keys, wanted_key, (void *)junk_key);
    528  tor_assert(keypair);
    529  memcpy(&(*state_out)->my_key, &keypair->pubkey,
    530         sizeof(curve25519_public_key_t));
    531 
    532  // Do the first diffie hellman handshake.
    533  curve25519_handshake((*state_out)->xb,
    534                       &keypair->seckey, &(*state_out)->client_key);
    535  problems |= safe_mem_is_zero((*state_out)->xb, CURVE25519_OUTPUT_LEN);
    536 
    537  // Derive the encryption and mac keys
    538  uint8_t enc_key[CIPHER256_KEY_LEN], mac_key[DIGEST256_LEN];
    539  {
    540    crypto_xof_t *xof = crypto_xof_new();
    541    xof_add_tweak(xof, T_MSGKDF);
    542    xof_add(xof, (*state_out)->xb, CURVE25519_OUTPUT_LEN);
    543    xof_add(xof, wanted_id, ED25519_PUBKEY_LEN);
    544    xof_add(xof, (*state_out)->client_key.public_key, CURVE25519_PUBKEY_LEN);
    545    xof_add(xof, keypair->pubkey.public_key, CURVE25519_PUBKEY_LEN);
    546    xof_add(xof, (const uint8_t *)PROTOID, strlen(PROTOID));
    547    xof_add_encap(xof, verification, verification_len);
    548    crypto_xof_squeeze_bytes(xof, enc_key, sizeof(enc_key));
    549    crypto_xof_squeeze_bytes(xof, mac_key, sizeof(mac_key));
    550    crypto_xof_free(xof);
    551  }
    552 
    553  // Check the MAC.
    554  uint8_t computed_mac[DIGEST256_LEN];
    555  {
    556    crypto_digest_t *d = crypto_digest256_new(DIGEST_SHA3_256);
    557    d_add_tweak(d, T_MSGMAC);
    558    d_add_encap(d, mac_key, sizeof(mac_key));
    559    d_add(d, my_id->pubkey, ED25519_PUBKEY_LEN);
    560    d_add(d, keypair->pubkey.public_key, CURVE25519_PUBKEY_LEN);
    561    d_add(d, (*state_out)->client_key.public_key, CURVE25519_PUBKEY_LEN);
    562    d_add(d, encrypted_message, encrypted_message_len);
    563    crypto_digest_get_digest(d, (char *)computed_mac, DIGEST256_LEN);
    564    crypto_digest_free(d);
    565  }
    566 
    567  problems |= tor_memneq((*state_out)->msg_mac, computed_mac, DIGEST256_LEN);
    568 
    569  // Decrypt the message.
    570  *client_message_out = tor_malloc(encrypted_message_len);
    571  *client_message_len_out = encrypted_message_len;
    572  {
    573    crypto_cipher_t *c =
    574      crypto_cipher_new_with_bits((const char *)enc_key, 256);
    575    crypto_cipher_decrypt(c, (char *)*client_message_out,
    576                          (const char *)encrypted_message,
    577                          encrypted_message_len);
    578    crypto_cipher_free(c);
    579  }
    580 
    581 done:
    582  memwipe(enc_key, 0, sizeof(enc_key));
    583  memwipe(mac_key, 0, sizeof(mac_key));
    584  memwipe(computed_mac, 0, sizeof(computed_mac));
    585  if (problems) {
    586    if (*client_message_out) {
    587      memwipe(*client_message_out, 0, *client_message_len_out);
    588      tor_free(*client_message_out); // Sets it to NULL.
    589    }
    590    *client_message_len_out = 0;
    591    ntor3_server_handshake_state_free(*state_out);
    592    return -1;
    593  }
    594 
    595  return 0;
    596 }
    597 
    598 /**
    599 * Finish the relay side of an ntor v3 handshake.
    600 *
    601 * The relay calls this function after it has decided to respond to the
    602 * client's original encrypted message.  This function receives the relay's
    603 * message in @a server_message and its length in @a server_message_len, and
    604 * completes the handshake.
    605 *
    606 * Returns 0 on success and -1 on failure. On success, stores the newly
    607 * allocated handshake for the relay to send in @a handshake_out, and its
    608 * length in @a handshake_len_out.  Stores @a keys_out_len bytes of generated
    609 * keys in the provided buffer at @a keys_out.
    610 **/
    611 int
    612 onion_skin_ntor3_server_handshake_part2(
    613                const ntor3_server_handshake_state_t *state,
    614                const uint8_t *verification,
    615                size_t verification_len,
    616                const uint8_t *server_message,
    617                size_t server_message_len,
    618                uint8_t **handshake_out,
    619                size_t *handshake_len_out,
    620                uint8_t *keys_out,
    621                size_t keys_out_len)
    622 {
    623  curve25519_keypair_t relay_keypair;
    624  if (curve25519_keypair_generate(&relay_keypair, 0) < 0) {
    625    return -1;
    626  }
    627  int r = onion_skin_ntor3_server_handshake_part2_nokeygen(
    628              &relay_keypair,
    629              state,
    630              verification,
    631              verification_len,
    632              server_message,
    633              server_message_len,
    634              handshake_out,
    635              handshake_len_out,
    636              keys_out,
    637              keys_out_len);
    638  memwipe(&relay_keypair, 0, sizeof(relay_keypair));
    639  return r;
    640 }
    641 
    642 /**
    643 * Like `onion_skin_ntor3_server_handshake_part2`, but do not generate
    644 * an ephemeral (y,Y) keypair.
    645 *
    646 * Instead, this function takes that keypair as @a relay_keypair_y.
    647 *
    648 * (Having a separate function for this lets us test the code for correct
    649 * behavior.)
    650 **/
    651 STATIC int
    652 onion_skin_ntor3_server_handshake_part2_nokeygen(
    653                const curve25519_keypair_t *relay_keypair_y,
    654                const ntor3_server_handshake_state_t *state,
    655                const uint8_t *verification,
    656                size_t verification_len,
    657                const uint8_t *server_message,
    658                size_t server_message_len,
    659                uint8_t **handshake_out,
    660                size_t *handshake_len_out,
    661                uint8_t *keys_out,
    662                size_t keys_out_len)
    663 {
    664  *handshake_out = NULL;
    665  *handshake_len_out = 0;
    666 
    667  int problems = 0;
    668 
    669  // Second diffie-hellman handshake.
    670  uint8_t xy[CURVE25519_OUTPUT_LEN];
    671  curve25519_handshake(xy, &relay_keypair_y->seckey, &state->client_key);
    672  problems |= safe_mem_is_zero(xy, sizeof(xy));
    673 
    674  // Compute two tweaked hashes of secret_input.
    675  uint8_t key_seed[DIGEST256_LEN], verify[DIGEST256_LEN];
    676  {
    677    crypto_digest_t *ks = crypto_digest256_new(DIGEST_SHA3_256);
    678    crypto_digest_t *v = crypto_digest256_new(DIGEST_SHA3_256);
    679    d_add_tweak(ks, T_KEY_SEED);
    680    d_add_tweak(v, T_VERIFY);
    681    ADD2(xy, sizeof(xy));
    682    ADD2(state->xb, sizeof(state->xb));
    683    ADD2(state->my_id.pubkey, ED25519_PUBKEY_LEN);
    684    ADD2(state->my_key.public_key, CURVE25519_PUBKEY_LEN);
    685    ADD2(state->client_key.public_key, CURVE25519_PUBKEY_LEN);
    686    ADD2(relay_keypair_y->pubkey.public_key, CURVE25519_PUBKEY_LEN);
    687    ADD2((const uint8_t *)PROTOID, strlen(PROTOID));
    688    ADD2_ENCAP(verification, verification_len);
    689    crypto_digest_get_digest(ks, (char*) key_seed, DIGEST256_LEN);
    690    crypto_digest_get_digest(v, (char*) verify, DIGEST256_LEN);
    691    crypto_digest_free(ks);
    692    crypto_digest_free(v);
    693  }
    694 
    695  // Compute enc_key and keystream.
    696  uint8_t enc_key[CIPHER256_KEY_LEN];
    697  {
    698    crypto_xof_t *xof = crypto_xof_new();
    699    xof_add_tweak(xof, T_FINAL);
    700    xof_add(xof, key_seed, sizeof(key_seed));
    701    crypto_xof_squeeze_bytes(xof, enc_key, sizeof(enc_key));
    702    crypto_xof_squeeze_bytes(xof, keys_out, keys_out_len);
    703    crypto_xof_free(xof);
    704  }
    705 
    706  // Encrypt message.
    707  uint8_t *encrypted_message = tor_memdup(server_message, server_message_len);
    708  {
    709    crypto_cipher_t *c =
    710      crypto_cipher_new_with_bits((const char *)enc_key, 256);
    711    crypto_cipher_crypt_inplace(
    712                c, (char *)encrypted_message, server_message_len);
    713    crypto_cipher_free(c);
    714  }
    715 
    716  // Compute AUTH digest.
    717  uint8_t auth[DIGEST256_LEN];
    718  {
    719    crypto_digest_t *d = crypto_digest256_new(DIGEST_SHA3_256);
    720    d_add_tweak(d, T_AUTH);
    721    d_add(d, verify, sizeof(verify));
    722    d_add(d, state->my_id.pubkey, ED25519_PUBKEY_LEN);
    723    d_add(d, state->my_key.public_key, CURVE25519_PUBKEY_LEN);
    724    d_add(d, relay_keypair_y->pubkey.public_key, CURVE25519_PUBKEY_LEN);
    725    d_add(d, state->client_key.public_key, CURVE25519_PUBKEY_LEN);
    726    d_add(d, state->msg_mac, DIGEST256_LEN);
    727    d_add_encap(d, encrypted_message, server_message_len);
    728    d_add(d, (const uint8_t*)PROTOID, strlen(PROTOID));
    729    d_add(d, (const uint8_t*)"Server", strlen("Server"));
    730    crypto_digest_get_digest(d, (char *)auth, DIGEST256_LEN);
    731    crypto_digest_free(d);
    732  }
    733 
    734  // Compose the reply.
    735  *handshake_len_out = CURVE25519_PUBKEY_LEN + DIGEST256_LEN +
    736    server_message_len;
    737  *handshake_out = tor_malloc(*handshake_len_out);
    738  uint8_t *ptr = *handshake_out, *end = ptr + *handshake_len_out;
    739  push(&ptr, end, relay_keypair_y->pubkey.public_key, CURVE25519_PUBKEY_LEN);
    740  push(&ptr, end, auth, sizeof(auth));
    741  push(&ptr, end, encrypted_message, server_message_len);
    742  tor_assert(ptr == end);
    743 
    744  // Clean up and return.
    745  memwipe(xy, 0, sizeof(xy));
    746  memwipe(key_seed, 0, sizeof(key_seed));
    747  memwipe(verify, 0, sizeof(verify));
    748  memwipe(enc_key, 0, sizeof(enc_key));
    749  memwipe(encrypted_message, 0, server_message_len);
    750  tor_free(encrypted_message);
    751 
    752  if (problems) {
    753    memwipe(*handshake_out, 0, *handshake_len_out);
    754    tor_free(*handshake_out); // Sets it to NULL.
    755    *handshake_len_out = 0;
    756    crypto_rand((char*)keys_out, keys_out_len); // In case bad code uses it.
    757    return -1;
    758  }
    759  return 0;
    760 }