1 #include "config.h"
2 #include <assert.h>
3 #include <bitcoin/pubkey.h>
4 #include <ccan/crypto/hkdf_sha256/hkdf_sha256.h>
5 #include <ccan/endian/endian.h>
6 #include <ccan/io/io.h>
7 #include <ccan/mem/mem.h>
8 #include <common/crypto_state.h>
9 #include <common/ecdh.h>
10 #include <common/status.h>
11 #include <common/type_to_string.h>
12 #include <common/utils.h>
13 #include <common/wireaddr.h>
14 #include <connectd/handshake.h>
15 #include <errno.h>
16 #include <secp256k1_ecdh.h>
17 #include <sodium/crypto_aead_chacha20poly1305.h>
18 #include <sodium/randombytes.h>
19 
20 #ifndef SUPERVERBOSE
21 #define SUPERVERBOSE(...)
22 #endif
23 
24 enum bolt8_side {
25 	INITIATOR,
26 	RESPONDER
27 };
28 
29 /* BOLT #8:
30  *
31  * Act One is sent from initiator to responder. During Act One, the
32  * initiator attempts to satisfy an implicit challenge by the responder. To
33  * complete this challenge, the initiator must know the static public key of
34  * the responder.
35  */
36 struct act_one {
37 	u8 v;
38 	u8 pubkey[PUBKEY_CMPR_LEN];
39 	u8 tag[crypto_aead_chacha20poly1305_ietf_ABYTES];
40 };
41 
42 /* BOLT #8: The handshake message is _exactly_ 50 bytes */
43 #define ACT_ONE_SIZE 50 /* ARM's stupid ABI adds padding. */
44 
check_act_one(const struct act_one * act1)45 static inline void check_act_one(const struct act_one *act1)
46 {
47 	/* BOLT #8:
48 	 *
49 	 * : 1 byte for the handshake version, 33 bytes for the compressed
50 	 * ephemeral public key of the initiator, and 16 bytes for the
51 	 * `poly1305` tag.
52 	 */
53 	BUILD_ASSERT(sizeof(act1->v) == 1);
54 	BUILD_ASSERT(sizeof(act1->pubkey) == 33);
55 	BUILD_ASSERT(sizeof(act1->tag) == 16);
56 }
57 
58 /* BOLT #8:
59  *
60  * Act Two is sent from the responder to the initiator. Act Two will
61  * _only_ take place if Act One was successful. Act One was successful if
62  * the responder was able to properly decrypt and check the MAC of the tag
63  * sent at the end of Act One.
64  */
65 struct act_two {
66 	u8 v;
67 	u8 pubkey[PUBKEY_CMPR_LEN];
68 	u8 tag[crypto_aead_chacha20poly1305_ietf_ABYTES];
69 };
70 
71 /* BOLT #8: The handshake is _exactly_ 50 bytes: */
72 #define ACT_TWO_SIZE 50 /* ARM's stupid ABI adds padding. */
73 
check_act_two(const struct act_two * act2)74 static inline void check_act_two(const struct act_two *act2)
75 {
76 	/* BOLT #8:
77 	 * 1 byte for the handshake version,
78 	 * 33 bytes for the compressed ephemeral public key of the initiator, and
79 	 * 16 bytes for the `poly1305` tag.
80 	 */
81 	BUILD_ASSERT(sizeof(act2->v) == 1);
82 	BUILD_ASSERT(sizeof(act2->pubkey) == 33);
83 	BUILD_ASSERT(sizeof(act2->tag) == 16);
84 }
85 
86 /* BOLT #8:
87  *
88  * Act Three is the final phase in the authenticated key agreement described
89  * in this section. This act is sent from the initiator to the responder as a
90  * concluding step. Act Three is executed  _if and only if_  Act Two was
91  * successful.  During Act Three, the initiator transports its static public
92  * key to the responder encrypted with _strong_ forward secrecy, using the
93  * accumulated `HKDF` derived secret key at this point of the handshake.
94  */
95 struct act_three {
96 	u8 v;
97 	u8 ciphertext[PUBKEY_CMPR_LEN + crypto_aead_chacha20poly1305_ietf_ABYTES];
98 	u8 tag[crypto_aead_chacha20poly1305_ietf_ABYTES];
99 };
100 
101 /* BOLT #8: The handshake is _exactly_ 66 bytes */
102 #define ACT_THREE_SIZE 66 /* ARM's stupid ABI adds padding. */
103 
check_act_three(const struct act_three * act3)104 static inline void check_act_three(const struct act_three *act3)
105 {
106 	/* BOLT #8:
107 	 *
108 	 * 1 byte for the handshake version, 33 bytes for the
109 	 * compressed ephemeral public key of the initiator, and 16
110 	 * bytes for the `poly1305` tag.
111 	 */
112 	BUILD_ASSERT(sizeof(act3->v) == 1);
113 	BUILD_ASSERT(sizeof(act3->ciphertext) == 33 + 16);
114 	BUILD_ASSERT(sizeof(act3->tag) == 16);
115 }
116 
117 /* BOLT #8:
118  *
119  *  * `generateKey()`: generates and returns a fresh `secp256k1` keypair
120  *      * Where the object returned by `generateKey` has two attributes:
121  *          * `.pub`, which returns an abstract object representing the
122  *            public key
123  *          * `.priv`, which represents the private key used to generate the
124  *            public key
125  */
126 struct keypair {
127 	struct pubkey pub;
128 	struct privkey priv;
129 };
130 
131 /* BOLT #8:
132  *
133  * Throughout the handshake process, each side maintains these variables:
134  *
135  *  * `ck`: the **chaining key**. This value is the accumulated hash of all
136  *    previous ECDH outputs. At the end of the handshake, `ck` is used to derive
137  *    the encryption keys for Lightning messages.
138  *
139  *  * `h`: the **handshake hash**. This value is the accumulated hash of _all_
140  *    handshake data that has been sent and received so far during the handshake
141  *    process.
142  *
143  *  * `temp_k1`, `temp_k2`, `temp_k3`: the **intermediate keys**. These are used to
144  *    encrypt and decrypt the zero-length AEAD payloads at the end of each handshake
145  *    message.
146  *
147  *  * `e`: a party's **ephemeral keypair**. For each session, a node MUST generate a
148  *    new ephemeral key with strong cryptographic randomness.
149  *
150  *  * `s`: a party's **static keypair** (`ls` for local, `rs` for remote)
151  */
152 struct handshake {
153 	struct secret ck;
154 	struct secret temp_k;
155 	struct sha256 h;
156 	struct keypair e;
157 	struct secret *ss;
158 
159 	/* Used between the Acts */
160 	struct pubkey re;
161 	struct act_one act1;
162 	struct act_two act2;
163 	struct act_three act3;
164 
165 	/* Where is connection from/to */
166 	struct wireaddr_internal addr;
167 
168 	/* Who we are */
169 	struct pubkey my_id;
170 	/* Who they are: set already if we're initiator. */
171 	struct pubkey their_id;
172 
173 	/* Are we initiator or responder. */
174 	enum bolt8_side side;
175 
176 	/* Function to call once handshake complete. */
177 	struct io_plan *(*cb)(struct io_conn *conn,
178 			      const struct pubkey *their_id,
179 			      const struct wireaddr_internal *wireaddr,
180 			      struct crypto_state *cs,
181 			      void *cbarg);
182 	void *cbarg;
183 };
184 
generate_key(void)185 static struct keypair generate_key(void)
186 {
187 	struct keypair k;
188 
189 	do {
190 		randombytes_buf(k.priv.secret.data, sizeof(k.priv.secret.data));
191 	} while (!secp256k1_ec_pubkey_create(secp256k1_ctx,
192 					     &k.pub.pubkey, k.priv.secret.data));
193 	return k;
194 }
195 
196 /* h = SHA-256(h || data) */
sha_mix_in(struct sha256 * h,const void * data,size_t len)197 static void sha_mix_in(struct sha256 *h, const void *data, size_t len)
198 {
199 	struct sha256_ctx shactx;
200 
201 	sha256_init(&shactx);
202 	sha256_update(&shactx, h, sizeof(*h));
203 	sha256_update(&shactx, data, len);
204 	sha256_done(&shactx, h);
205 }
206 
207 /* h = SHA-256(h || pub.serializeCompressed()) */
sha_mix_in_key(struct sha256 * h,const struct pubkey * key)208 static void sha_mix_in_key(struct sha256 *h, const struct pubkey *key)
209 {
210 	u8 der[PUBKEY_CMPR_LEN];
211 	size_t len = sizeof(der);
212 
213 	secp256k1_ec_pubkey_serialize(secp256k1_ctx, der, &len, &key->pubkey,
214 				      SECP256K1_EC_COMPRESSED);
215 	assert(len == sizeof(der));
216 	sha_mix_in(h, der, sizeof(der));
217 }
218 
219 /* out1, out2 = HKDF(in1, in2)` */
hkdf_two_keys(struct secret * out1,struct secret * out2,const struct secret * in1,const void * in2,size_t in2_size)220 static void hkdf_two_keys(struct secret *out1, struct secret *out2,
221 			  const struct secret *in1,
222 			  const void *in2, size_t in2_size)
223 {
224 	/* BOLT #8:
225 	 *
226 	 *   * `HKDF(salt,ikm)`: a function defined in `RFC 5869`<sup>[3](#reference-3)</sup>,
227 	 *      evaluated with a zero-length `info` field
228 	 *      * All invocations of `HKDF` implicitly return 64 bytes
229 	 *        of cryptographic randomness using the extract-and-expand
230 	 *        component of the `HKDF`.
231 	 */
232 	struct secret okm[2];
233 
234 	SUPERVERBOSE("# HKDF(0x%s,%s%s)",
235 		     tal_hexstr(tmpctx, in1, sizeof(*in1)),
236 		     in2_size ? "0x" : "zero",
237 		     tal_hexstr(tmpctx, in2, in2_size));
238 	BUILD_ASSERT(sizeof(okm) == 64);
239 	hkdf_sha256(okm, sizeof(okm), in1, sizeof(*in1), in2, in2_size,
240 		    NULL, 0);
241 	*out1 = okm[0];
242 	*out2 = okm[1];
243 }
244 
le64_nonce(unsigned char * npub,u64 nonce)245 static void le64_nonce(unsigned char *npub, u64 nonce)
246 {
247 	/* BOLT #8:
248 	 *
249 	 * ...with nonce `n` encoded as 32 zero bits, followed by a
250 	 * *little-endian* 64-bit value. Note: this follows the Noise
251 	 * Protocol convention, rather than our normal endian
252 	 */
253 	le64 le_nonce = cpu_to_le64(nonce);
254 	const size_t zerolen = crypto_aead_chacha20poly1305_ietf_NPUBBYTES - sizeof(le_nonce);
255 
256 	BUILD_ASSERT(crypto_aead_chacha20poly1305_ietf_NPUBBYTES >= sizeof(le_nonce));
257 	/* First part is 0, followed by nonce. */
258 	memset(npub, 0, zerolen);
259 	memcpy(npub + zerolen, &le_nonce, sizeof(le_nonce));
260 }
261 
262 /* BOLT #8:
263  *   * `encryptWithAD(k, n, ad, plaintext)`: outputs `encrypt(k, n, ad,
264  *      plaintext)`
265  *      * Where `encrypt` is an evaluation of `ChaCha20-Poly1305` (IETF
266  *	  variant) with the passed arguments, with nonce `n`
267  */
encrypt_ad(const struct secret * k,u64 nonce,const void * additional_data,size_t additional_data_len,const void * plaintext,size_t plaintext_len,void * output,size_t outputlen)268 static void encrypt_ad(const struct secret *k, u64 nonce,
269 		       const void *additional_data, size_t additional_data_len,
270 		       const void *plaintext, size_t plaintext_len,
271 		       void *output, size_t outputlen)
272 {
273 	unsigned char npub[crypto_aead_chacha20poly1305_ietf_NPUBBYTES];
274 	unsigned long long clen;
275 	int ret;
276 
277 	assert(outputlen == plaintext_len + crypto_aead_chacha20poly1305_ietf_ABYTES);
278 	le64_nonce(npub, nonce);
279 	BUILD_ASSERT(sizeof(*k) == crypto_aead_chacha20poly1305_ietf_KEYBYTES);
280 	SUPERVERBOSE("# encryptWithAD(0x%s, 0x%s, 0x%s, %s%s)",
281 		     tal_hexstr(tmpctx, k, sizeof(*k)),
282 		     tal_hexstr(tmpctx, npub, sizeof(npub)),
283 		     tal_hexstr(tmpctx, additional_data, additional_data_len),
284 		     plaintext_len ? "0x" : "<empty>",
285 		     tal_hexstr(tmpctx, plaintext, plaintext_len));
286 
287 	ret = crypto_aead_chacha20poly1305_ietf_encrypt(output, &clen,
288 						   memcheck(plaintext, plaintext_len),
289 						   plaintext_len,
290 						   additional_data, additional_data_len,
291 							NULL, npub, k->data);
292 	assert(ret == 0);
293 	assert(clen == plaintext_len + crypto_aead_chacha20poly1305_ietf_ABYTES);
294 }
295 
296 /* BOLT #8:
297  *    * `decryptWithAD(k, n, ad, ciphertext)`: outputs `decrypt(k, n, ad,
298  *       ciphertext)`
299  *      * Where `decrypt` is an evaluation of `ChaCha20-Poly1305` (IETF
300  *        variant) with the passed arguments, with nonce `n`
301  */
decrypt(const struct secret * k,u64 nonce,const void * additional_data,size_t additional_data_len,const void * ciphertext,size_t ciphertext_len,void * output,size_t outputlen)302 static bool decrypt(const struct secret *k, u64 nonce,
303 		    const void *additional_data, size_t additional_data_len,
304 		    const void *ciphertext, size_t ciphertext_len,
305 		    void *output, size_t outputlen)
306 {
307 	unsigned char npub[crypto_aead_chacha20poly1305_ietf_NPUBBYTES];
308 	unsigned long long mlen;
309 
310 	assert(outputlen == ciphertext_len - crypto_aead_chacha20poly1305_ietf_ABYTES);
311 
312 	le64_nonce(npub, nonce);
313 	BUILD_ASSERT(sizeof(*k) == crypto_aead_chacha20poly1305_ietf_KEYBYTES);
314 	SUPERVERBOSE("# decryptWithAD(0x%s, 0x%s, 0x%s, 0x%s)",
315 		     tal_hexstr(tmpctx, k, sizeof(*k)),
316 		     tal_hexstr(tmpctx, npub, sizeof(npub)),
317 		     tal_hexstr(tmpctx, additional_data, additional_data_len),
318 		     tal_hexstr(tmpctx, ciphertext, ciphertext_len));
319 	if (crypto_aead_chacha20poly1305_ietf_decrypt(output, &mlen, NULL,
320 						 memcheck(ciphertext, ciphertext_len),
321 						 ciphertext_len,
322 						 additional_data, additional_data_len,
323 						 npub, k->data) != 0)
324 		return false;
325 
326 	assert(mlen == ciphertext_len - crypto_aead_chacha20poly1305_ietf_ABYTES);
327 	return true;
328 }
329 
handshake_failed_(struct io_conn * conn,struct handshake * h,const char * function,int line)330 static struct io_plan *handshake_failed_(struct io_conn *conn,
331 					 struct handshake *h,
332 					 const char *function, int line)
333 {
334 	status_debug("%s: handshake failed %s:%u",
335 		     h->side == RESPONDER ? "Responder" : "Initiator",
336 		     function, line);
337 	errno = EPROTO;
338 	return io_close(conn);
339 }
340 #define handshake_failed(conn, h) \
341 	handshake_failed_((conn), (h), __func__, __LINE__)
342 
handshake_succeeded(struct io_conn * conn,struct handshake * h)343 static struct io_plan *handshake_succeeded(struct io_conn *conn,
344 					   struct handshake *h)
345 {
346 	struct crypto_state cs;
347 	struct io_plan *(*cb)(struct io_conn *conn,
348 			      const struct pubkey *their_id,
349 			      const struct wireaddr_internal *addr,
350 			      struct crypto_state *cs,
351 			      void *cbarg);
352 	void *cbarg;
353 	struct pubkey their_id;
354 	struct wireaddr_internal addr;
355 
356 	/* BOLT #8:
357 	 *
358 	 * 9. `rk, sk = HKDF(ck, zero)`
359 	 *      * where `zero` is a zero-length plaintext, `rk` is the key to
360 	 *        be used by the responder to decrypt the messages sent by the
361 	 *        initiator, and `sk` is the key to be used by the responder
362 	 *        to encrypt messages to the initiator
363 	 *
364 	 *      * The final encryption keys, to be used for sending and
365 	 *        receiving messages for the duration of the session, are
366 	 *        generated.
367 	 */
368 	if (h->side == RESPONDER)
369 		hkdf_two_keys(&cs.rk, &cs.sk, &h->ck, NULL, 0);
370 	else
371 		hkdf_two_keys(&cs.sk, &cs.rk, &h->ck, NULL, 0);
372 
373 	cs.rn = cs.sn = 0;
374 	cs.r_ck = cs.s_ck = h->ck;
375 
376 	cb = h->cb;
377 	cbarg = h->cbarg;
378 	their_id = h->their_id;
379 	addr = h->addr;
380 
381 	tal_free(h);
382 	return cb(conn, &their_id, &addr, &cs, cbarg);
383 }
384 
new_handshake(const tal_t * ctx,const struct pubkey * responder_id)385 static struct handshake *new_handshake(const tal_t *ctx,
386 				       const struct pubkey *responder_id)
387 {
388 	struct handshake *handshake = tal(ctx, struct handshake);
389 
390 	/* BOLT #8:
391 	 *
392 	 * Before the start of Act One, both sides initialize their
393 	 * per-sessions state as follows:
394 	 *
395 	 *  1. `h = SHA-256(protocolName)`
396 	 *   *  where `protocolName = "Noise_XK_secp256k1_ChaChaPoly_SHA256"`
397 	 *      encoded as an ASCII string
398 	 */
399 	sha256(&handshake->h, "Noise_XK_secp256k1_ChaChaPoly_SHA256",
400 	       strlen("Noise_XK_secp256k1_ChaChaPoly_SHA256"));
401 
402 	/* BOLT #8:
403 	 *
404 	 * 2. `ck = h`
405 	 */
406 	BUILD_ASSERT(sizeof(handshake->h) == sizeof(handshake->ck));
407 	memcpy(&handshake->ck, &handshake->h, sizeof(handshake->ck));
408 	SUPERVERBOSE("# ck=%s",
409 		     tal_hexstr(tmpctx, &handshake->ck, sizeof(handshake->ck)));
410 
411 	/* BOLT #8:
412 	 *
413 	 * 3. `h = SHA-256(h || prologue)`
414 	 *    *  where `prologue` is the ASCII string: `lightning`
415 	 */
416 	sha_mix_in(&handshake->h, "lightning", strlen("lightning"));
417 
418 	/* BOLT #8:
419 	 *
420 	 * As a concluding step, both sides mix the responder's public key
421 	 * into the handshake digest:
422 	 *
423 	 * * The initiating node mixes in the responding node's static public
424 	 *    key serialized in Bitcoin's compressed format:
425 	 *    * `h = SHA-256(h || rs.pub.serializeCompressed())`
426 	 *
427 	 * * The responding node mixes in their local static public key
428 	 *   serialized in Bitcoin's compressed format:
429 	 *    * `h = SHA-256(h || ls.pub.serializeCompressed())`
430 	 */
431 	sha_mix_in_key(&handshake->h, responder_id);
432 	SUPERVERBOSE("# h=%s",
433 		     tal_hexstr(tmpctx, &handshake->h, sizeof(handshake->h)));
434 
435 	return handshake;
436 }
437 
act_three_initiator(struct io_conn * conn,struct handshake * h)438 static struct io_plan *act_three_initiator(struct io_conn *conn,
439 					   struct handshake *h)
440 {
441 	u8 spub[PUBKEY_CMPR_LEN];
442 	size_t len = sizeof(spub);
443 
444 	SUPERVERBOSE("Initiator: Act 3");
445 
446 	/* BOLT #8:
447 	 * 1. `c = encryptWithAD(temp_k2, 1, h, s.pub.serializeCompressed())`
448 	 *     * where `s` is the static public key of the initiator
449 	 */
450 	secp256k1_ec_pubkey_serialize(secp256k1_ctx, spub, &len,
451 				      &h->my_id.pubkey,
452 				      SECP256K1_EC_COMPRESSED);
453 	encrypt_ad(&h->temp_k, 1, &h->h, sizeof(h->h), spub, sizeof(spub),
454 		   h->act3.ciphertext, sizeof(h->act3.ciphertext));
455 	SUPERVERBOSE("# c=0x%s",
456 		     tal_hexstr(tmpctx,
457 				h->act3.ciphertext, sizeof(h->act3.ciphertext)));
458 
459 	/* BOLT #8:
460 	 * 2. `h = SHA-256(h || c)`
461 	 */
462 	sha_mix_in(&h->h, h->act3.ciphertext, sizeof(h->act3.ciphertext));
463 	SUPERVERBOSE("# h=0x%s", tal_hexstr(tmpctx, &h->h, sizeof(h->h)));
464 
465 	/* BOLT #8:
466 	 *
467 	 * 3. `se = ECDH(s.priv, re)`
468 	 *     * where `re` is the ephemeral public key of the responder
469 	 */
470 	h->ss = tal(h, struct secret);
471 	ecdh(&h->re, h->ss);
472 	SUPERVERBOSE("# ss=0x%s", tal_hexstr(tmpctx, h->ss, sizeof(*h->ss)));
473 
474 	/* BOLT #8:
475 	 *
476 	 * 4. `ck, temp_k3 = HKDF(ck, se)`
477 	 *     * The final intermediate shared secret is mixed into the running chaining key.
478 	 */
479 	hkdf_two_keys(&h->ck, &h->temp_k, &h->ck, h->ss, sizeof(*h->ss));
480 	SUPERVERBOSE("# ck,temp_k3=0x%s,0x%s",
481 		     tal_hexstr(tmpctx, &h->ck, sizeof(h->ck)),
482 		     tal_hexstr(tmpctx, &h->temp_k, sizeof(h->temp_k)));
483 
484 	/* BOLT #8:
485 	 *
486 	 * 5. `t = encryptWithAD(temp_k3, 0, h, zero)`
487 	 *      * where `zero` is a zero-length plaintext
488 	 *
489 	 */
490 	encrypt_ad(&h->temp_k, 0, &h->h, sizeof(h->h), NULL, 0,
491 		   h->act3.tag, sizeof(h->act3.tag));
492 	SUPERVERBOSE("# t=0x%s",
493 		     tal_hexstr(tmpctx, h->act3.tag, sizeof(h->act3.tag)));
494 
495 	/* BOLT #8:
496 	 *
497 	 * 8.  Send `m = 0 || c || t` over the network buffer.
498 	 *
499 	 */
500 	h->act3.v = 0;
501 
502 	SUPERVERBOSE("output: 0x%s", tal_hexstr(tmpctx, &h->act3, ACT_THREE_SIZE));
503 	return io_write(conn, &h->act3, ACT_THREE_SIZE, handshake_succeeded, h);
504 }
505 
act_two_initiator2(struct io_conn * conn,struct handshake * h)506 static struct io_plan *act_two_initiator2(struct io_conn *conn,
507 					 struct handshake *h)
508 {
509 	SUPERVERBOSE("input: 0x%s", tal_hexstr(tmpctx, &h->act2, ACT_TWO_SIZE));
510 
511 	/* BOLT #8:
512 	 *
513 	 * 3. If `v` is an unrecognized handshake version, then the responder
514 	 *     MUST abort the connection attempt.
515 	 */
516 	if (h->act2.v != 0)
517 		return handshake_failed(conn, h);
518 
519 	/* BOLT #8:
520 	 *
521 	 *     * The raw bytes of the remote party's ephemeral public key
522 	 *       (`re`) are to be deserialized into a point on the curve using
523 	 *       affine coordinates as encoded by the key's serialized
524 	 *       composed format.
525 	 */
526 	if (secp256k1_ec_pubkey_parse(secp256k1_ctx, &h->re.pubkey,
527 				      h->act2.pubkey, sizeof(h->act2.pubkey)) != 1)
528 		return handshake_failed(conn, h);
529 
530 	SUPERVERBOSE("# re=0x%s", type_to_string(tmpctx, struct pubkey, &h->re));
531 
532 	/* BOLT #8:
533 	 *
534 	 * 4. `h = SHA-256(h || re.serializeCompressed())`
535 	 */
536 	sha_mix_in_key(&h->h, &h->re);
537 	SUPERVERBOSE("# h=0x%s", tal_hexstr(tmpctx, &h->h, sizeof(h->h)));
538 
539 	/* BOLT #8:
540 	 *
541 	 * 5. `es = ECDH(s.priv, re)`
542 	 */
543 	if (!secp256k1_ecdh(secp256k1_ctx, h->ss->data, &h->re.pubkey,
544 			    h->e.priv.secret.data, NULL, NULL))
545 		return handshake_failed(conn, h);
546 
547 	SUPERVERBOSE("# ss=0x%s", tal_hexstr(tmpctx, h->ss, sizeof(*h->ss)));
548 
549 	/* BOLT #8:
550 	 *
551 	 * 6. `ck, temp_k2 = HKDF(ck, ee)`
552 	 *      * A new temporary encryption key is generated, which is
553 	 *        used to generate the authenticating MAC.
554 	 */
555 	hkdf_two_keys(&h->ck, &h->temp_k, &h->ck, h->ss, sizeof(*h->ss));
556 	SUPERVERBOSE("# ck,temp_k2=0x%s,0x%s",
557 		     tal_hexstr(tmpctx, &h->ck, sizeof(h->ck)),
558 		     tal_hexstr(tmpctx, &h->temp_k, sizeof(h->temp_k)));
559 
560 	/* BOLT #8:
561 	 *
562 	 * 7. `p = decryptWithAD(temp_k2, 0, h, c)`
563 	 *     * If the MAC check in this operation fails, then the initiator
564 	 *       MUST terminate the connection without any further messages.
565 	 */
566 	if (!decrypt(&h->temp_k, 0, &h->h, sizeof(h->h),
567 		     h->act2.tag, sizeof(h->act2.tag), NULL, 0))
568 		return handshake_failed(conn, h);
569 
570 	/* BOLT #8:
571 	 *
572 	 * 8. `h = SHA-256(h || c)`
573 	 *     * The received ciphertext is mixed into the handshake digest.
574 	 *       This step serves to ensure the payload wasn't modified by a
575 	 *       MITM.
576 	 */
577 	sha_mix_in(&h->h, h->act2.tag, sizeof(h->act2.tag));
578 	SUPERVERBOSE("# h=0x%s", tal_hexstr(tmpctx, &h->h, sizeof(h->h)));
579 
580 	return act_three_initiator(conn, h);
581 }
582 
act_two_initiator(struct io_conn * conn,struct handshake * h)583 static struct io_plan *act_two_initiator(struct io_conn *conn,
584 					 struct handshake *h)
585 {
586 	SUPERVERBOSE("Initiator: Act 2");
587 
588 	/* BOLT #8:
589 	 *
590 	 * 1. Read _exactly_ 50 bytes from the network buffer.
591 	 *
592 	 * 2. Parse the read message (`m`) into `v`, `re`, and `c`:
593 	 *    * where `v` is the _first_ byte of `m`, `re` is the next 33
594 	 *      bytes of `m`, and `c` is the last 16 bytes of `m`.
595 	 */
596 	return io_read(conn, &h->act2, ACT_TWO_SIZE, act_two_initiator2, h);
597 }
598 
act_one_initiator(struct io_conn * conn,struct handshake * h)599 static struct io_plan *act_one_initiator(struct io_conn *conn,
600 					 struct handshake *h)
601 {
602 	size_t len;
603 
604 	SUPERVERBOSE("Initiator: Act 1");
605 
606 	/* BOLT #8:
607 	 *
608 	 * **Sender Actions:**
609 	 *
610 	 * 1. `e = generateKey()`
611 	 */
612 	h->e = generate_key();
613 	SUPERVERBOSE("e.priv: 0x%s",
614 		     tal_hexstr(tmpctx, &h->e.priv, sizeof(h->e.priv)));
615 	SUPERVERBOSE("e.pub: 0x%s",
616 		     type_to_string(tmpctx, struct pubkey, &h->e.pub));
617 
618 	/* BOLT #8:
619 	 *
620 	 * 2. `h = SHA-256(h || e.pub.serializeCompressed())`
621 	 *     * The newly generated ephemeral key is accumulated into the
622 	 *       running handshake digest.
623 	 */
624 	sha_mix_in_key(&h->h, &h->e.pub);
625 	SUPERVERBOSE("# h=0x%s", tal_hexstr(tmpctx, &h->h, sizeof(h->h)));
626 
627 	/* BOLT #8:
628 	 *
629 	 * 3. `es = ECDH(e.priv, rs)`
630 	 *      * The initiator performs an ECDH between its newly generated ephemeral
631 	 *        key and the remote node's static public key.
632 	 */
633 	h->ss = tal(h, struct secret);
634 	if (!secp256k1_ecdh(secp256k1_ctx, h->ss->data,
635 			    &h->their_id.pubkey, h->e.priv.secret.data,
636 			    NULL, NULL))
637 		return handshake_failed(conn, h);
638 
639 	SUPERVERBOSE("# ss=0x%s", tal_hexstr(tmpctx, h->ss->data, sizeof(h->ss->data)));
640 
641 	/* BOLT #8:
642 	 *
643 	 * 4. `ck, temp_k1 = HKDF(ck, es)`
644 	 *      * A new temporary encryption key is generated, which is
645 	 *        used to generate the authenticating MAC.
646 	 */
647 	hkdf_two_keys(&h->ck, &h->temp_k, &h->ck, h->ss, sizeof(*h->ss));
648 	SUPERVERBOSE("# ck,temp_k1=0x%s,0x%s",
649 		     tal_hexstr(tmpctx, &h->ck, sizeof(h->ck)),
650 		     tal_hexstr(tmpctx, &h->temp_k, sizeof(h->temp_k)));
651 
652 	/* BOLT #8:
653 	 * 5. `c = encryptWithAD(temp_k1, 0, h, zero)`
654 	 *     * where `zero` is a zero-length plaintext
655 	 */
656 	encrypt_ad(&h->temp_k, 0, &h->h, sizeof(h->h), NULL, 0,
657 		   h->act1.tag, sizeof(h->act1.tag));
658 	SUPERVERBOSE("# c=%s",
659 		     tal_hexstr(tmpctx, h->act1.tag, sizeof(h->act1.tag)));
660 
661 	/* BOLT #8:
662 	 * 6. `h = SHA-256(h || c)`
663 	 *     * Finally, the generated ciphertext is accumulated into the
664 	 *       authenticating handshake digest.
665 	 */
666 	sha_mix_in(&h->h, h->act1.tag, sizeof(h->act1.tag));
667 	SUPERVERBOSE("# h=0x%s", tal_hexstr(tmpctx, &h->h, sizeof(h->h)));
668 
669 	/* BOLT #8:
670 	 *
671 	 * 7. Send `m = 0 || e.pub.serializeCompressed() || c` to the responder over the network buffer.
672 	 */
673 	h->act1.v = 0;
674 	len = sizeof(h->act1.pubkey);
675 	secp256k1_ec_pubkey_serialize(secp256k1_ctx, h->act1.pubkey, &len,
676 				      &h->e.pub.pubkey,
677 				      SECP256K1_EC_COMPRESSED);
678 	SUPERVERBOSE("output: 0x%s", tal_hexstr(tmpctx, &h->act1, ACT_ONE_SIZE));
679 
680 	check_act_one(&h->act1);
681 	return io_write(conn, &h->act1, ACT_ONE_SIZE, act_two_initiator, h);
682 }
683 
act_three_responder2(struct io_conn * conn,struct handshake * h)684 static struct io_plan *act_three_responder2(struct io_conn *conn,
685 					    struct handshake *h)
686 {
687 	u8 der[PUBKEY_CMPR_LEN];
688 
689 	SUPERVERBOSE("input: 0x%s", tal_hexstr(tmpctx, &h->act3, ACT_THREE_SIZE));
690 
691 	/* BOLT #8:
692 	 *
693 	 * 2. Parse the read message (`m`) into `v`, `c`, and `t`:
694 	 *    * where `v` is the _first_ byte of `m`, `c` is the next 49
695 	 *      bytes of `m`, and `t` is the last 16 bytes of `m`
696 	 */
697 
698 	/* BOLT #8:
699 	 *
700 	 * 3. If `v` is an unrecognized handshake version, then the responder
701 	 *    MUST abort the connection attempt.
702 	 */
703 	if (h->act3.v != 0)
704 		return handshake_failed(conn, h);
705 
706 	/* BOLT #8:
707 	 *
708 	 * 4. `rs = decryptWithAD(temp_k2, 1, h, c)`
709 	 *      * At this point, the responder has recovered the static public
710 	 *        key of the initiator.
711 	 */
712 	if (!decrypt(&h->temp_k, 1, &h->h, sizeof(h->h),
713 		     h->act3.ciphertext, sizeof(h->act3.ciphertext),
714 		     der, sizeof(der)))
715 		return handshake_failed(conn, h);
716 
717 	SUPERVERBOSE("# rs=0x%s", tal_hexstr(tmpctx, der, sizeof(der)));
718 
719 	if (secp256k1_ec_pubkey_parse(secp256k1_ctx, &h->their_id.pubkey,
720 				      der, sizeof(der)) != 1)
721 		return handshake_failed(conn, h);
722 
723 	/* BOLT #8:
724 	 *
725 	 * 5. `h = SHA-256(h || c)`
726 	 *
727 	 */
728 	sha_mix_in(&h->h, h->act3.ciphertext, sizeof(h->act3.ciphertext));
729 	SUPERVERBOSE("# h=0x%s", tal_hexstr(tmpctx, &h->h, sizeof(h->h)));
730 
731 	/* BOLT #8:
732 	 *
733 	 * 6. `se = ECDH(e.priv, rs)`
734 	 *      * where `e` is the responder's original ephemeral key
735 	 */
736 	if (!secp256k1_ecdh(secp256k1_ctx, h->ss->data, &h->their_id.pubkey,
737 			    h->e.priv.secret.data, NULL, NULL))
738 		return handshake_failed(conn, h);
739 
740 	SUPERVERBOSE("# ss=0x%s", tal_hexstr(tmpctx, h->ss, sizeof(*h->ss)));
741 
742 	/* BOLT #8:
743 	 * 7. `ck, temp_k3 = HKDF(ck, se)`
744 	 */
745 	hkdf_two_keys(&h->ck, &h->temp_k, &h->ck, h->ss, sizeof(*h->ss));
746 	SUPERVERBOSE("# ck,temp_k3=0x%s,0x%s",
747 		     tal_hexstr(tmpctx, &h->ck, sizeof(h->ck)),
748 		     tal_hexstr(tmpctx, &h->temp_k, sizeof(h->temp_k)));
749 
750 	/* BOLT #8:
751 	 * 8. `p = decryptWithAD(temp_k3, 0, h, t)`
752 	 *      * If the MAC check in this operation fails, then the responder
753 	 *        MUST terminate the connection without any further messages.
754 	 *
755 	 */
756 	if (!decrypt(&h->temp_k, 0, &h->h, sizeof(h->h),
757 		     h->act3.tag, sizeof(h->act3.tag), NULL, 0))
758 		return handshake_failed(conn, h);
759 
760 	check_act_three(&h->act3);
761 	return handshake_succeeded(conn, h);
762 }
763 
act_three_responder(struct io_conn * conn,struct handshake * h)764 static struct io_plan *act_three_responder(struct io_conn *conn,
765 					   struct handshake *h)
766 {
767 	SUPERVERBOSE("Responder: Act 3");
768 
769 	/* BOLT #8:
770 	 *
771 	 * **Receiver Actions:**
772 	 *
773 	 * 1. Read _exactly_ 66 bytes from the network buffer.
774 	 */
775 	return io_read(conn, &h->act3, ACT_THREE_SIZE, act_three_responder2, h);
776 }
777 
act_two_responder(struct io_conn * conn,struct handshake * h)778 static struct io_plan *act_two_responder(struct io_conn *conn,
779 					 struct handshake *h)
780 {
781 	size_t len;
782 
783 	SUPERVERBOSE("Responder: Act 2");
784 
785 	/* BOLT #8:
786 	 *
787 	 * **Sender Actions:**
788 	 *
789 	 * 1. `e = generateKey()`
790 	 */
791 	h->e = generate_key();
792 	SUPERVERBOSE("# e.pub=0x%s e.priv=0x%s",
793 		     type_to_string(tmpctx, struct pubkey, &h->e.pub),
794 		     tal_hexstr(tmpctx, &h->e.priv, sizeof(h->e.priv)));
795 
796 	/* BOLT #8:
797 	 *
798 	 * 2. `h = SHA-256(h || e.pub.serializeCompressed())`
799 	 *      * The newly generated ephemeral key is accumulated into the
800 	 *        running handshake digest.
801 	 */
802 	sha_mix_in_key(&h->h, &h->e.pub);
803 	SUPERVERBOSE("# h=0x%s", tal_hexstr(tmpctx, &h->h, sizeof(h->h)));
804 
805 	/* BOLT #8:
806 	 *
807 	 * 3. `ee = ECDH(e.priv, re)`
808 	 *      * where `re` is the ephemeral key of the initiator, which was received
809 	 *        during Act One
810 	 */
811 	if (!secp256k1_ecdh(secp256k1_ctx, h->ss->data, &h->re.pubkey,
812 			    h->e.priv.secret.data, NULL, NULL))
813 		return handshake_failed(conn, h);
814 	SUPERVERBOSE("# ss=0x%s", tal_hexstr(tmpctx, h->ss, sizeof(*h->ss)));
815 
816 	/* BOLT #8:
817 	 *
818 	 * 4. `ck, temp_k2 = HKDF(ck, ee)`
819 	 *      * A new temporary encryption key is generated, which is
820 	 *       used to generate the authenticating MAC.
821 	 */
822 	hkdf_two_keys(&h->ck, &h->temp_k, &h->ck, h->ss, sizeof(*h->ss));
823 	SUPERVERBOSE("# ck,temp_k2=0x%s,0x%s",
824 		     tal_hexstr(tmpctx, &h->ck, sizeof(h->ck)),
825 		     tal_hexstr(tmpctx, &h->temp_k, sizeof(h->temp_k)));
826 
827 	/* BOLT #8:
828 	 *
829 	 * 5. `c = encryptWithAD(temp_k2, 0, h, zero)`
830 	 *      * where `zero` is a zero-length plaintext
831 	 */
832 	encrypt_ad(&h->temp_k, 0, &h->h, sizeof(h->h), NULL, 0,
833 		   h->act2.tag, sizeof(h->act2.tag));
834 	SUPERVERBOSE("# c=0x%s", tal_hexstr(tmpctx, h->act2.tag, sizeof(h->act2.tag)));
835 
836 	/* BOLT #8:
837 	 *
838 	 * 6. `h = SHA-256(h || c)`
839 	 *      * Finally, the generated ciphertext is accumulated into the
840 	 *        authenticating handshake digest.
841 	 */
842 	sha_mix_in(&h->h, h->act2.tag, sizeof(h->act2.tag));
843 	SUPERVERBOSE("# h=0x%s", tal_hexstr(tmpctx, &h->h, sizeof(h->h)));
844 
845 	/* BOLT #8:
846 	 *
847 	 * 7. Send `m = 0 || e.pub.serializeCompressed() || c` to the initiator over the network buffer.
848 	 */
849 	h->act2.v = 0;
850 	len = sizeof(h->act2.pubkey);
851 	secp256k1_ec_pubkey_serialize(secp256k1_ctx, h->act2.pubkey, &len,
852 				      &h->e.pub.pubkey,
853 				      SECP256K1_EC_COMPRESSED);
854 	SUPERVERBOSE("output: 0x%s", tal_hexstr(tmpctx, &h->act2, ACT_TWO_SIZE));
855 
856 	check_act_two(&h->act2);
857 	return io_write(conn, &h->act2, ACT_TWO_SIZE, act_three_responder, h);
858 }
859 
act_one_responder2(struct io_conn * conn,struct handshake * h)860 static struct io_plan *act_one_responder2(struct io_conn *conn,
861 					 struct handshake *h)
862 {
863 	/* BOLT #8:
864 	 *
865 	 * 3. If `v` is an unrecognized handshake version, then the responder
866 	 *     MUST abort the connection attempt.
867 	 */
868 	if (h->act1.v != 0)
869 		return handshake_failed(conn, h);
870 
871 	/* BOLT #8:
872 	 *
873 	 *     * The raw bytes of the remote party's ephemeral public key
874 	 *       (`re`) are to be deserialized into a point on the curve using
875 	 *       affine coordinates as encoded by the key's serialized
876 	 *       composed format.
877 	 */
878 	if (secp256k1_ec_pubkey_parse(secp256k1_ctx, &h->re.pubkey,
879 				      h->act1.pubkey, sizeof(h->act1.pubkey)) != 1)
880 		return handshake_failed(conn, h);
881 
882 	SUPERVERBOSE("# re=0x%s", type_to_string(tmpctx, struct pubkey, &h->re));
883 
884 	/* BOLT #8:
885 	 *
886 	 * 4. `h = SHA-256(h || re.serializeCompressed())`
887 	 *    * The responder accumulates the initiator's ephemeral key into the
888 	 *      authenticating handshake digest.
889 	 */
890 	sha_mix_in_key(&h->h, &h->re);
891 	SUPERVERBOSE("# h=0x%s", tal_hexstr(tmpctx, &h->h, sizeof(h->h)));
892 
893 	/* BOLT #8:
894 	 *
895 	 * 5. `es = ECDH(s.priv, re)`
896 	 *    * The responder performs an ECDH between its static private key and
897 	 *      the initiator's ephemeral public key.
898 	 */
899 	h->ss = tal(h, struct secret);
900 	ecdh(&h->re, h->ss);
901 	SUPERVERBOSE("# ss=0x%s", tal_hexstr(tmpctx, h->ss, sizeof(*h->ss)));
902 
903 	/* BOLT #8:
904 	 *
905 	 * 6. `ck, temp_k1 = HKDF(ck, es)`
906 	 *     * A new temporary encryption key is generated, which will
907 	 *       shortly be used to check the authenticating MAC.
908 	 */
909 	hkdf_two_keys(&h->ck, &h->temp_k, &h->ck, h->ss, sizeof(*h->ss));
910 	SUPERVERBOSE("# ck,temp_k1=0x%s,0x%s",
911 		     tal_hexstr(tmpctx, &h->ck, sizeof(h->ck)),
912 		     tal_hexstr(tmpctx, &h->temp_k, sizeof(h->temp_k)));
913 
914 	/* BOLT #8:
915 	 *
916 	 * 7. `p = decryptWithAD(temp_k1, 0, h, c)`
917 	 *     * If the MAC check in this operation fails, then the initiator
918 	 *       does _not_ know the responder's static public key. If this
919 	 *       is the case, then the responder MUST terminate the connection
920 	 *       without any further messages.
921 	 */
922 	if (!decrypt(&h->temp_k, 0, &h->h, sizeof(h->h),
923 		     h->act1.tag, sizeof(h->act1.tag), NULL, 0))
924 		return handshake_failed(conn, h);
925 
926 	/* BOLT #8:
927 	 *
928 	 * 8. `h = SHA-256(h || c)`
929 	 *     * The received ciphertext is mixed into the handshake digest.
930 	 *       This step serves to ensure the payload wasn't modified by a
931 	 *       MITM.
932 	 */
933 	sha_mix_in(&h->h, h->act1.tag, sizeof(h->act1.tag));
934 	SUPERVERBOSE("# h=0x%s", tal_hexstr(tmpctx, &h->h, sizeof(h->h)));
935 
936 	return act_two_responder(conn, h);
937 }
938 
act_one_responder(struct io_conn * conn,struct handshake * h)939 static struct io_plan *act_one_responder(struct io_conn *conn,
940 					 struct handshake *h)
941 {
942 
943 	SUPERVERBOSE("Responder: Act 1");
944 
945 	/* BOLT #8:
946 	 *
947 	 * 1. Read _exactly_ 50 bytes from the network buffer.
948 	 *
949 	 * 2. Parse the read message (`m`) into `v`, `re`, and `c`:
950 	 *     * where `v` is the _first_ byte of `m`, `re` is the next 33
951 	 *       bytes of `m`, and `c` is the last 16 bytes of `m`.
952 	 */
953 	return io_read(conn, &h->act1, ACT_ONE_SIZE, act_one_responder2, h);
954 }
955 
responder_handshake_(struct io_conn * conn,const struct pubkey * my_id,const struct wireaddr_internal * addr,struct io_plan * (* cb)(struct io_conn *,const struct pubkey *,const struct wireaddr_internal *,struct crypto_state *,void * cbarg),void * cbarg)956 struct io_plan *responder_handshake_(struct io_conn *conn,
957 				     const struct pubkey *my_id,
958 				     const struct wireaddr_internal *addr,
959 				     struct io_plan *(*cb)(struct io_conn *,
960 							   const struct pubkey *,
961 							   const struct wireaddr_internal *,
962 							   struct crypto_state *,
963 							   void *cbarg),
964 				     void *cbarg)
965 {
966 	struct handshake *h = new_handshake(conn, my_id);
967 
968 	h->side = RESPONDER;
969 	h->my_id = *my_id;
970 	h->addr = *addr;
971 	h->cbarg = cbarg;
972 	h->cb = cb;
973 
974 	return act_one_responder(conn, h);
975 }
976 
initiator_handshake_(struct io_conn * conn,const struct pubkey * my_id,const struct pubkey * their_id,const struct wireaddr_internal * addr,struct io_plan * (* cb)(struct io_conn *,const struct pubkey *,const struct wireaddr_internal *,struct crypto_state *,void * cbarg),void * cbarg)977 struct io_plan *initiator_handshake_(struct io_conn *conn,
978 				     const struct pubkey *my_id,
979 				     const struct pubkey *their_id,
980 				     const struct wireaddr_internal *addr,
981 				     struct io_plan *(*cb)(struct io_conn *,
982 							   const struct pubkey *,
983 							   const struct wireaddr_internal *,
984 							   struct crypto_state *,
985 							   void *cbarg),
986 				     void *cbarg)
987 {
988 	struct handshake *h = new_handshake(conn, their_id);
989 
990 	h->side = INITIATOR;
991 	h->my_id = *my_id;
992 	h->their_id = *their_id;
993 	h->addr = *addr;
994 	h->cbarg = cbarg;
995 	h->cb = cb;
996 
997 	return act_one_initiator(conn, h);
998 }
999