lnsocket

A minimal C library for connecting to the lightning network
git clone git://jb55.com/lnsocket
Log | Files | Refs | Submodules | README | LICENSE

handshake.c (13850B)


      1 /* Copyright Rusty Russell (Blockstream) 2015.
      2              William Casarin 2022
      3 
      4 Permission is hereby granted, free of charge, to any person obtaining a copy
      5 of this software and associated documentation files (the "Software"), to deal
      6 in the Software without restriction, including without limitation the rights
      7 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      8 copies of the Software, and to permit persons to whom the Software is
      9 furnished to do so, subject to the following conditions:
     10 
     11 The above copyright notice and this permission notice shall be included in
     12 all copies or substantial portions of the Software.
     13 
     14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
     17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
     19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
     20 THE SOFTWARE.
     21 */
     22 
     23 #include "compiler.h"
     24 #include "endian.h"
     25 #include "error.h"
     26 #include "handshake.h"
     27 #include "hkdf.h"
     28 #include "lnsocket_internal.h"
     29 #include "sha256.h"
     30 #include <errno.h>
     31 #include <secp256k1_ecdh.h>
     32 #include <unistd.h>
     33 #include <sodium/randombytes.h>
     34 #include "export.h"
     35 
     36 struct keypair generate_key(secp256k1_context *ctx)
     37 {
     38 	struct keypair k;
     39 
     40 	do {
     41 		randombytes_buf(k.priv.secret.data, sizeof(k.priv.secret.data));
     42 	} while (!secp256k1_ec_pubkey_create(ctx, &k.pub.pubkey,
     43 				k.priv.secret.data));
     44 	return k;
     45 }
     46 
     47 
     48 /* h = SHA-256(h || data) */
     49 static void sha_mix_in(struct sha256 *h, const void *data, size_t len)
     50 {
     51 	struct sha256_ctx shactx;
     52 
     53 	sha256_init(&shactx);
     54 	sha256_update(&shactx, h->u.u8, sizeof(*h));
     55 	sha256_update(&shactx, data, len);
     56 	sha256_done(&shactx, h);
     57 }
     58 
     59 /* h = SHA-256(h || pub.serializeCompressed()) */
     60 static void sha_mix_in_key(secp256k1_context *ctx, struct sha256 *h,
     61 		const struct pubkey *key)
     62 {
     63 	u8 der[PUBKEY_CMPR_LEN];
     64 	size_t len = sizeof(der);
     65 
     66 	secp256k1_ec_pubkey_serialize(ctx, der, &len, &key->pubkey,
     67 				      SECP256K1_EC_COMPRESSED);
     68 	assert(len == sizeof(der));
     69 	sha_mix_in(h, der, sizeof(der));
     70 }
     71 
     72 
     73 /* BOLT #8:
     74  *   * `encryptWithAD(k, n, ad, plaintext)`: outputs `encrypt(k, n, ad,
     75  *      plaintext)`
     76  *      * Where `encrypt` is an evaluation of `ChaCha20-Poly1305` (IETF
     77  *	  variant) with the passed arguments, with nonce `n`
     78  */
     79 static void encrypt_ad(const struct secret *k, u64 nonce,
     80 		       const void *additional_data, size_t additional_data_len,
     81 		       const void *plaintext, size_t plaintext_len,
     82 		       void *output, size_t outputlen)
     83 {
     84 	unsigned char npub[crypto_aead_chacha20poly1305_ietf_NPUBBYTES];
     85 	unsigned long long clen;
     86 	int ret;
     87 
     88 	assert(outputlen == plaintext_len + crypto_aead_chacha20poly1305_ietf_ABYTES);
     89 	le64_nonce(npub, nonce);
     90 	BUILD_ASSERT(sizeof(*k) == crypto_aead_chacha20poly1305_ietf_KEYBYTES);
     91 
     92 	ret = crypto_aead_chacha20poly1305_ietf_encrypt(
     93 			output, &clen, memcheck(plaintext, plaintext_len),
     94 			plaintext_len, additional_data, additional_data_len,
     95 			NULL, npub, k->data);
     96 
     97 	assert(ret == 0);
     98 	assert(clen == plaintext_len + crypto_aead_chacha20poly1305_ietf_ABYTES);
     99 }
    100 
    101 static inline void check_act_one(const struct act_one *act1)
    102 {
    103 	/* BOLT #8:
    104 	 *
    105 	 * : 1 byte for the handshake version, 33 bytes for the compressed
    106 	 * ephemeral public key of the initiator, and 16 bytes for the
    107 	 * `poly1305` tag.
    108 	 */
    109 	BUILD_ASSERT(sizeof(act1->v) == 1);
    110 	BUILD_ASSERT(sizeof(act1->pubkey) == 33);
    111 	BUILD_ASSERT(sizeof(act1->tag) == 16);
    112 }
    113 
    114 /*
    115 static void print_hex(u8 *bytes, int len) {
    116 	int i;
    117 	for (i = 0; i < len; ++i) {
    118 		printf("%02x", bytes[i]);
    119 	}
    120 }
    121 */
    122 
    123 void new_handshake(secp256k1_context *secp, struct handshake *handshake,
    124 		const struct pubkey *responder_id)
    125 {
    126 	/* BOLT #8:
    127 	 *
    128 	 * Before the start of Act One, both sides initialize their
    129 	 * per-sessions state as follows:
    130 	 *
    131 	 *  1. `h = SHA-256(protocolName)`
    132 	 *   *  where `protocolName = "Noise_XK_secp256k1_ChaChaPoly_SHA256"`
    133 	 *      encoded as an ASCII string
    134 	 */
    135 	sha256(&handshake->h, "Noise_XK_secp256k1_ChaChaPoly_SHA256",
    136 	       strlen("Noise_XK_secp256k1_ChaChaPoly_SHA256"));
    137 
    138 	/* BOLT #8:
    139 	 *
    140 	 * 2. `ck = h`
    141 	 */
    142 	BUILD_ASSERT(sizeof(handshake->h) == sizeof(handshake->ck));
    143 	memcpy(&handshake->ck, &handshake->h, sizeof(handshake->ck));
    144 
    145 	/* BOLT #8:
    146 	 *
    147 	 * 3. `h = SHA-256(h || prologue)`
    148 	 *    *  where `prologue` is the ASCII string: `lightning`
    149 	 */
    150 	sha_mix_in(&handshake->h, "lightning", strlen("lightning"));
    151 
    152 	/* BOLT #8:
    153 	 *
    154 	 * As a concluding step, both sides mix the responder's public key
    155 	 * into the handshake digest:
    156 	 *
    157 	 * * The initiating node mixes in the responding node's static public
    158 	 *    key serialized in Bitcoin's compressed format:
    159 	 *    * `h = SHA-256(h || rs.pub.serializeCompressed())`
    160 	 *
    161 	 * * The responding node mixes in their local static public key
    162 	 *   serialized in Bitcoin's compressed format:
    163 	 *    * `h = SHA-256(h || ls.pub.serializeCompressed())`
    164 	 */
    165 	sha_mix_in_key(secp, &handshake->h, responder_id);
    166 }
    167 
    168 /*
    169 static void print_act_two(struct act_two *two)
    170 {
    171 	printf("ACT2 v %d pubkey ", two->v);
    172 	print_hex(two->pubkey, sizeof(two->pubkey));
    173 	printf(" tag ");
    174 	print_hex(two->tag, sizeof(two->tag));
    175 	printf("\n");
    176 }
    177 */
    178 
    179 /* BOLT #8:
    180  *    * `decryptWithAD(k, n, ad, ciphertext)`: outputs `decrypt(k, n, ad,
    181  *       ciphertext)`
    182  *      * Where `decrypt` is an evaluation of `ChaCha20-Poly1305` (IETF
    183  *        variant) with the passed arguments, with nonce `n`
    184  */
    185 static int decrypt(const struct secret *k, u64 nonce,
    186 		const void *additional_data, size_t additional_data_len,
    187 		const void *ciphertext, size_t ciphertext_len,
    188 		void *output, size_t outputlen)
    189 {
    190 	unsigned char npub[crypto_aead_chacha20poly1305_ietf_NPUBBYTES];
    191 	unsigned long long mlen;
    192 
    193 	assert(outputlen == ciphertext_len - crypto_aead_chacha20poly1305_ietf_ABYTES);
    194 
    195 	le64_nonce(npub, nonce);
    196 	BUILD_ASSERT(sizeof(*k) == crypto_aead_chacha20poly1305_ietf_KEYBYTES);
    197 	if (crypto_aead_chacha20poly1305_ietf_decrypt(output, &mlen, NULL,
    198 						 memcheck(ciphertext, ciphertext_len),
    199 						 ciphertext_len,
    200 						 additional_data, additional_data_len,
    201 						 npub, k->data) != 0) {
    202 		return 0;
    203 	}
    204 
    205 	assert(mlen == ciphertext_len - crypto_aead_chacha20poly1305_ietf_ABYTES);
    206 	return 1;
    207 }
    208 
    209 static int handshake_success(struct lnsocket *ln, struct handshake *h)
    210 {
    211 	struct crypto_state *cs = &ln->crypto_state;
    212 
    213 	/* BOLT #8:
    214 	 *
    215 	 * 9. `rk, sk = HKDF(ck, zero)`
    216 	 *      * where `zero` is a zero-length plaintext, `rk` is the key to
    217 	 *        be used by the responder to decrypt the messages sent by the
    218 	 *        initiator, and `sk` is the key to be used by the responder
    219 	 *        to encrypt messages to the initiator
    220 	 *
    221 	 *      * The final encryption keys, to be used for sending and
    222 	 *        receiving messages for the duration of the session, are
    223 	 *        generated.
    224 	 */
    225 	if (h->side == RESPONDER)
    226 		hkdf_two_keys(&cs->rk, &cs->sk, &h->ck, NULL);
    227 	else
    228 		hkdf_two_keys(&cs->sk, &cs->rk, &h->ck, NULL);
    229 
    230 	cs->rn = cs->sn = 0;
    231 	cs->r_ck = cs->s_ck = h->ck;
    232 
    233 	return 1;
    234 }
    235 
    236 static struct act_three *build_act_three(struct lnsocket *ln)
    237 {
    238 	u8 spub[PUBKEY_CMPR_LEN];
    239 	size_t len = sizeof(spub);
    240 	struct handshake *h = &ln->handshake;
    241 
    242 	/* BOLT #8:
    243 	 * 1. `c = encryptWithAD(temp_k2, 1, h, s.pub.serializeCompressed())`
    244 	 *     * where `s` is the static public key of the initiator
    245 	 */
    246 	secp256k1_ec_pubkey_serialize(ln->secp, spub, &len,
    247 				      &ln->key.pub.pubkey,
    248 				      SECP256K1_EC_COMPRESSED);
    249 	encrypt_ad(&h->temp_k, 1, &h->h, sizeof(h->h), spub, sizeof(spub),
    250 		   h->act3.ciphertext, sizeof(h->act3.ciphertext));
    251 
    252 	/* BOLT #8:
    253 	 * 2. `h = SHA-256(h || c)`
    254 	 */
    255 	sha_mix_in(&h->h, h->act3.ciphertext, sizeof(h->act3.ciphertext));
    256 
    257 	/* BOLT #8:
    258 	 *
    259 	 * 3. `se = ECDH(s.priv, re)`
    260 	 *     * where `re` is the ephemeral public key of the responder
    261 	 */
    262 	if (!secp256k1_ecdh(ln->secp, h->ss.data, &h->re.pubkey,
    263 			    ln->key.priv.secret.data, NULL, NULL)) {
    264 		note_error(&ln->errs, "act3 ecdh handshake failed");
    265 		return NULL;
    266 	}
    267 
    268 	/* BOLT #8:
    269 	 *
    270 	 * 4. `ck, temp_k3 = HKDF(ck, se)`
    271 	 *     * The final intermediate shared secret is mixed into the running chaining key.
    272 	 */
    273 	hkdf_two_keys(&h->ck, &h->temp_k, &h->ck, &h->ss);
    274 
    275 	/* BOLT #8:
    276 	 *
    277 	 * 5. `t = encryptWithAD(temp_k3, 0, h, zero)`
    278 	 *      * where `zero` is a zero-length plaintext
    279 	 *
    280 	 */
    281 	encrypt_ad(&h->temp_k, 0, &h->h, sizeof(h->h), NULL, 0,
    282 		   h->act3.tag, sizeof(h->act3.tag));
    283 
    284 	/* BOLT #8:
    285 	 *
    286 	 * 8.  Send `m = 0 || c || t` over the network buffer.
    287 	 *
    288 	 */
    289 	h->act3.v = 0;
    290 
    291         handshake_success(ln, &ln->handshake);
    292 
    293 	return &h->act3;
    294 }
    295 
    296 
    297 // act2: handle the response to the message sent in act1
    298 struct act_three* EXPORT lnsocket_act_two(struct lnsocket *ln, struct act_two *act2)
    299 {
    300 	struct handshake *h = &ln->handshake;
    301 
    302 	//print_act_two(act2);
    303 
    304 	/* BOLT #8:
    305 	 *
    306 	 * 3. If `v` is an unrecognized handshake version, then the responder
    307 	 *     MUST abort the connection attempt.
    308 	 */
    309 	if (act2->v != 0) {
    310 		note_error(&ln->errs, "unrecognized handshake version");
    311 		return NULL;
    312 	}
    313 
    314 	//print_hex()
    315 
    316 	/* BOLT #8:
    317 	 *
    318 	 *     * The raw bytes of the remote party's ephemeral public key
    319 	 *       (`re`) are to be deserialized into a point on the curve using
    320 	 *       affine coordinates as encoded by the key's serialized
    321 	 *       composed format.
    322 	 */
    323 	if (secp256k1_ec_pubkey_parse(ln->secp, &h->re.pubkey, act2->pubkey,
    324 				sizeof(act2->pubkey)) != 1) {
    325 		note_error(&ln->errs, "failed to parse remote pubkey");
    326 		return NULL;
    327 	}
    328 
    329 	/* BOLT #8:
    330 	 *
    331 	 * 4. `h = SHA-256(h || re.serializeCompressed())`
    332 	 */
    333 	sha_mix_in_key(ln->secp, &h->h, &h->re);
    334 
    335 	/* BOLT #8:
    336 	 *
    337 	 * 5. `es = ECDH(s.priv, re)`
    338 	 */
    339 	if (!secp256k1_ecdh(ln->secp, h->ss.data, &h->re.pubkey,
    340 			    h->e.priv.secret.data, NULL, NULL)) {
    341 		note_error(&ln->errs, "act2 ecdh failed");
    342 		return NULL;
    343 	}
    344 
    345 	/* BOLT #8:
    346 	 *
    347 	 * 6. `ck, temp_k2 = HKDF(ck, ee)`
    348 	 *      * A new temporary encryption key is generated, which is
    349 	 *        used to generate the authenticating MAC.
    350 	 */
    351 	hkdf_two_keys(&h->ck, &h->temp_k, &h->ck, &h->ss);
    352 
    353 	/* BOLT #8:
    354 	 *
    355 	 * 7. `p = decryptWithAD(temp_k2, 0, h, c)`
    356 	 *     * If the MAC check in this operation fails, then the initiator
    357 	 *       MUST terminate the connection without any further messages.
    358 	 */
    359 	if (!decrypt(&h->temp_k, 0, &h->h, sizeof(h->h),
    360 		     act2->tag, sizeof(act2->tag), NULL, 0)) {
    361 		note_error(&ln->errs, "handshake decrypt failed");
    362 		return NULL;
    363 	}
    364 
    365 	/* BOLT #8:
    366 	 *
    367 	 * 8. `h = SHA-256(h || c)`
    368 	 *     * The received ciphertext is mixed into the handshake digest.
    369 	 *       This step serves to ensure the payload wasn't modified by a
    370 	 *       MITM.
    371 	 */
    372 	sha_mix_in(&h->h, act2->tag, sizeof(act2->tag));
    373 
    374 	return build_act_three(ln);
    375 }
    376 
    377 // Prepare the very first message and send it the connected node
    378 // Wait for a response in act2
    379 int act_one_initiator_prep(struct lnsocket *ln)
    380 {
    381 	struct handshake *h = &ln->handshake;
    382 
    383 	h->e = generate_key(ln->secp);
    384 
    385 	/* BOLT #8:
    386 	 *
    387 	 * 2. `h = SHA-256(h || e.pub.serializeCompressed())`
    388 	 *     * The newly generated ephemeral key is accumulated into the
    389 	 *       running handshake digest.
    390 	 */
    391 	sha_mix_in_key(ln->secp, &h->h, &h->e.pub);
    392 
    393 	/* BOLT #8:
    394 	 *
    395 	 * 3. `es = ECDH(e.priv, rs)`
    396 	 *      * The initiator performs an ECDH between its newly generated ephemeral
    397 	 *        key and the remote node's static public key.
    398 	 */
    399 	if (!secp256k1_ecdh(ln->secp, h->ss.data,
    400 			    &h->their_id.pubkey, h->e.priv.secret.data,
    401 			    NULL, NULL)) {
    402 		return note_error(&ln->errs, "handshake failed, secp256k1_ecdh error");
    403 	}
    404 
    405 	/* BOLT #8:
    406 	 *
    407 	 * 4. `ck, temp_k1 = HKDF(ck, es)`
    408 	 *      * A new temporary encryption key is generated, which is
    409 	 *        used to generate the authenticating MAC.
    410 	 */
    411 	hkdf_two_keys(&h->ck, &h->temp_k, &h->ck, &h->ss);
    412 
    413 	/* BOLT #8:
    414 	 * 5. `c = encryptWithAD(temp_k1, 0, h, zero)`
    415 	 *     * where `zero` is a zero-length plaintext
    416 	 */
    417 	encrypt_ad(&h->temp_k, 0, &h->h, sizeof(h->h), NULL, 0,
    418 		   h->act1.tag, sizeof(h->act1.tag));
    419 
    420 	/* BOLT #8:
    421 	 * 6. `h = SHA-256(h || c)`
    422 	 *     * Finally, the generated ciphertext is accumulated into the
    423 	 *       authenticating handshake digest.
    424 	 */
    425 	sha_mix_in(&h->h, h->act1.tag, sizeof(h->act1.tag));
    426 
    427 	/* BOLT #8:
    428 	 *
    429 	 * 7. Send `m = 0 || e.pub.serializeCompressed() || c` to the responder over the network buffer.
    430 	 */
    431 	h->act1.v = 0;
    432 	size_t len = sizeof(h->act1.pubkey);
    433 	secp256k1_ec_pubkey_serialize(ln->secp, h->act1.pubkey, &len,
    434 				      &h->e.pub.pubkey,
    435 				      SECP256K1_EC_COMPRESSED);
    436 
    437 	check_act_one(&h->act1);
    438 
    439 	return 1;
    440 }
    441 
    442 // act2: read the response to the message sent in act1
    443 static int act_two_initiator(struct lnsocket *ln, struct handshake *h)
    444 {
    445 	/* BOLT #8:
    446 	 *
    447 	 * 1. Read _exactly_ 50 bytes from the network buffer.
    448 	 *
    449 	 * 2. Parse the read message (`m`) into `v`, `re`, and `c`:
    450 	 *    * where `v` is the _first_ byte of `m`, `re` is the next 33
    451 	 *      bytes of `m`, and `c` is the last 16 bytes of `m`.
    452 	 */
    453 	ssize_t size;
    454 
    455 	if ((size = read(ln->socket, &h->act2, ACT_TWO_SIZE)) != ACT_TWO_SIZE) {
    456 		fprintf(stderr, "read %ld bytes, expected %d\n", size, ACT_TWO_SIZE);
    457 		return note_error(&ln->errs, "%s", strerror(errno));
    458 	}
    459 
    460 	struct act_three *act3 = lnsocket_act_two(ln, &h->act2);
    461 	if (act3 == NULL)
    462 		return 0;
    463 
    464 	if (write(ln->socket, act3, ACT_THREE_SIZE) != ACT_THREE_SIZE) {
    465 		return note_error(&ln->errs, "handshake failed on initial send");
    466 	}
    467 
    468 	return 1;
    469 }
    470 
    471 int act_one_initiator(struct lnsocket *ln)
    472 {
    473 	if (!act_one_initiator_prep(ln))
    474 		return 0;
    475 
    476 	if (write(ln->socket, &ln->handshake.act1, ACT_ONE_SIZE) != ACT_ONE_SIZE) {
    477 		return note_error(&ln->errs, "handshake failed on initial send");
    478 	}
    479 
    480 	return act_two_initiator(ln, &ln->handshake);
    481 }