summaryrefslogtreecommitdiffstats
path: root/src/protocols/ec25519_fhmqvc/handshake.c
blob: c29b7b178aacad65de80449e4a5936816e8ecfb6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
/*
  Copyright (c) 2012-2014, Matthias Schiffer <mschiffer@universe-factory.net>
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice,
       this list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright notice,
       this list of conditions and the following disclaimer in the documentation
       and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


#include "handshake.h"
#include "../../handshake.h"
#include "../../hkdf_sha256.h"
#include "../../verify.h"


#define HASHBYTES FASTD_SHA256_HASH_BYTES


#if HASHBYTES != FASTD_HMACSHA256_KEY_BYTES
#error bug: HASHBYTES != FASTD_HMACSHA256_KEY_BYTES
#endif

#if HASHBYTES != SECRETKEYBYTES
#error bug: HASHBYTES != SECRETKEYBYTES
#endif


#define RECORD_SENDER_KEY RECORD_PROTOCOL1
#define RECORD_RECEIPIENT_KEY RECORD_PROTOCOL2
#define RECORD_SENDER_HANDSHAKE_KEY RECORD_PROTOCOL3
#define RECORD_RECEIPIENT_HANDSHAKE_KEY RECORD_PROTOCOL4
#define RECORD_T RECORD_PROTOCOL5


static void derive_key(fastd_sha256_t *out, size_t blocks, const uint32_t *salt, const char *method_name,
		       const aligned_int256_t *A, const aligned_int256_t *B, const aligned_int256_t *X, const aligned_int256_t *Y,
		       const aligned_int256_t *sigma) {
	size_t methodlen = strlen(method_name);
	uint8_t info[4*PUBLICKEYBYTES + methodlen] __attribute__((aligned(8)));

	memcpy(info, A, PUBLICKEYBYTES);
	memcpy(info+PUBLICKEYBYTES, B, PUBLICKEYBYTES);
	memcpy(info+2*PUBLICKEYBYTES, X, PUBLICKEYBYTES);
	memcpy(info+3*PUBLICKEYBYTES, Y, PUBLICKEYBYTES);
	memcpy(info+4*PUBLICKEYBYTES, method_name, methodlen);

	fastd_sha256_t prk;
	fastd_hkdf_sha256_extract(&prk, salt, sigma->u32, PUBLICKEYBYTES);

	fastd_hkdf_sha256_expand(out, blocks, &prk, info, sizeof(info));
}

static inline void supersede_session(fastd_peer_t *peer, const fastd_method_info_t *method) {
	if (is_session_valid(&peer->protocol_state->session) && !is_session_valid(&peer->protocol_state->old_session)) {
		if (peer->protocol_state->old_session.method)
			peer->protocol_state->old_session.method->provider->session_free(peer->protocol_state->old_session.method_state);
		peer->protocol_state->old_session = peer->protocol_state->session;
	}
	else {
		if (peer->protocol_state->session.method)
			peer->protocol_state->session.method->provider->session_free(peer->protocol_state->session.method_state);
	}

	if (peer->protocol_state->old_session.method) {
		if (peer->protocol_state->old_session.method != method) {
			pr_debug("method of %P has changed, terminating old session", peer);
			peer->protocol_state->old_session.method->provider->session_free(peer->protocol_state->old_session.method_state);
			peer->protocol_state->old_session = (protocol_session_t){};
		}
		else {
			peer->protocol_state->old_session.method->provider->session_superseded(peer->protocol_state->old_session.method_state);
		}
	}
}

static inline bool new_session(fastd_peer_t *peer, const fastd_method_info_t *method, bool initiator,
			       const aligned_int256_t *A, const aligned_int256_t *B, const aligned_int256_t *X, const aligned_int256_t *Y,
			       const aligned_int256_t *sigma, const uint32_t *salt, uint64_t serial) {

	supersede_session(peer, method);

	if (salt) {
		size_t blocks = block_count(method->provider->key_length(method->method), sizeof(fastd_sha256_t));
		fastd_sha256_t secret[blocks];
		derive_key(secret, blocks, salt, method->name, A, B, X, Y, sigma);

		peer->protocol_state->session.method_state = method->provider->session_init(method->method, (const uint8_t*)secret, initiator);
	}
	else {
		fastd_sha256_t hash;
		fastd_sha256_blocks(&hash, X->u32, Y->u32, A->u32, B->u32, sigma->u32, NULL);
		peer->protocol_state->session.method_state = method->provider->session_init_compat(method->method, hash.b, HASHBYTES, initiator);
	}

	if (!peer->protocol_state->session.method_state)
		return false;

	peer->protocol_state->session.handshakes_cleaned = false;
	peer->protocol_state->session.refreshing = false;
	peer->protocol_state->session.method = method;
	peer->protocol_state->last_serial = serial;

	return true;
}

static bool establish(fastd_peer_t *peer, const fastd_method_info_t *method, fastd_socket_t *sock,
		      const fastd_peer_address_t *local_addr, const fastd_peer_address_t *remote_addr, bool initiator,
		      const aligned_int256_t *A, const aligned_int256_t *B, const aligned_int256_t *X, const aligned_int256_t *Y,
		      const aligned_int256_t *sigma, const uint32_t *salt, uint64_t serial) {
	if (serial <= peer->protocol_state->last_serial) {
		pr_debug("ignoring handshake from %P[%I] because of handshake key reuse", peer, remote_addr);
		return false;
	}

	if (!salt && !method->provider->session_init_compat) {
		pr_warn("can't establish compat session with %P[%I] (method without compat support)", peer, remote_addr);
		return false;
	}

	pr_verbose("%I authorized as %P", remote_addr, peer);

	if (!fastd_peer_claim_address(peer, sock, local_addr, remote_addr, true)) {
		pr_warn("can't establish session with %P[%I] as the address is used by another peer", peer, remote_addr);
		fastd_peer_reset(peer);
		return false;
	}

	if (!new_session(peer, method, initiator, A, B, X, Y, sigma, salt, serial)) {
		pr_error("failed to initialize method session for %P (method `%s'%s)", peer, method->name, salt ? "" : " (compat mode)");
		fastd_peer_reset(peer);
		return false;
	}

	peer->establish_handshake_timeout = fastd_in_seconds(MIN_HANDSHAKE_INTERVAL);
	fastd_peer_seen(peer);
	fastd_peer_set_established(peer);

	pr_verbose("new session with %P established using method `%s'%s.", peer, method->name, salt ? "" : " (compat mode)");

	if (initiator)
		fastd_peer_schedule_handshake_default(peer);
	else
		fastd_protocol_ec25519_fhmqvc_send_empty(peer, &peer->protocol_state->session);

	return true;
}


static inline bool has_field(const fastd_handshake_t *handshake, uint8_t type, size_t length) {
	return (handshake->records[type].length == length);
}

static inline bool secure_handshake(const fastd_handshake_t *handshake) {
	return has_field(handshake, RECORD_TLV_MAC, HASHBYTES);
}


static bool make_shared_handshake_key(const ecc_int256_t *handshake_key, bool initiator,
				      const aligned_int256_t *A, const aligned_int256_t *B,
				      const aligned_int256_t *X, const aligned_int256_t *Y,
				      aligned_int256_t *sigma,
				      fastd_sha256_t *shared_handshake_key,
				      fastd_sha256_t *shared_handshake_key_compat) {
	static const uint32_t zero_salt[FASTD_HMACSHA256_KEY_WORDS] = {};

	ecc_25519_work_t work, workXY;

	if (!ecc_25519_load_packed(&workXY, initiator ? &Y->int256 : &X->int256))
		return false;

	ecc_25519_scalarmult(&work, &ecc_25519_gf_order, &workXY);
	if (!ecc_25519_is_identity(&work))
		return false;

	if (!ecc_25519_load_packed(&work, initiator ? &B->int256 : &A->int256))
		return false;

	fastd_sha256_t hashbuf;
	fastd_sha256_blocks(&hashbuf, Y->u32, X->u32, B->u32, A->u32, NULL);

	ecc_int256_t d = {{0}}, e = {{0}}, s;

	memcpy(d.p, hashbuf.b, HASHBYTES/2);
	memcpy(e.p, hashbuf.b+HASHBYTES/2, HASHBYTES/2);

	d.p[15] |= 0x80;
	e.p[15] |= 0x80;

	if (initiator) {
		ecc_int256_t da;
		ecc_25519_gf_mult(&da, &d, &conf.protocol_config->key.secret);
		ecc_25519_gf_add(&s, &da, handshake_key);

		ecc_25519_scalarmult(&work, &e, &work);
	}
	else {
		ecc_int256_t eb;
		ecc_25519_gf_mult(&eb, &e, &conf.protocol_config->key.secret);
		ecc_25519_gf_add(&s, &eb, handshake_key);

		ecc_25519_scalarmult(&work, &d, &work);
	}

	ecc_25519_add(&work, &workXY, &work);
	ecc_25519_scalarmult(&work, &s, &work);

	if (ecc_25519_is_identity(&work))
		return false;

	ecc_25519_store_packed(&sigma->int256, &work);

	if (shared_handshake_key)
		derive_key(shared_handshake_key, 1, zero_salt, "", A, B, X, Y, sigma);

	if (shared_handshake_key_compat)
		fastd_sha256_blocks(shared_handshake_key_compat, Y->u32, X->u32, B->u32, A->u32, sigma->u32, NULL);

	return true;
}

static bool update_shared_handshake_key(const fastd_peer_t *peer, const handshake_key_t *handshake_key, const aligned_int256_t *peer_handshake_key) {
	if (peer->protocol_state->last_handshake_serial == handshake_key->serial) {
		if (memcmp(&peer->protocol_state->peer_handshake_key, peer_handshake_key, PUBLICKEYBYTES) == 0)
			return true;
	}

	bool compat = !conf.secure_handshakes;

	if (!make_shared_handshake_key(&handshake_key->key.secret, false,
				       &peer->protocol_config->public_key,
				       &conf.protocol_config->key.public,
				       peer_handshake_key,
				       &handshake_key->key.public,
				       &peer->protocol_state->sigma,
				       &peer->protocol_state->shared_handshake_key,
				       compat ? &peer->protocol_state->shared_handshake_key_compat : NULL))
		return false;

	peer->protocol_state->last_handshake_serial = handshake_key->serial;
	peer->protocol_state->peer_handshake_key = *peer_handshake_key;

	return true;
}

static void clear_shared_handshake_key(const fastd_peer_t *peer) {
	memset(&peer->protocol_state->sigma, 0, sizeof(peer->protocol_state->sigma));
	memset(&peer->protocol_state->shared_handshake_key, 0, sizeof(peer->protocol_state->shared_handshake_key));
	memset(&peer->protocol_state->shared_handshake_key_compat, 0, sizeof(peer->protocol_state->shared_handshake_key_compat));

	peer->protocol_state->last_handshake_serial = 0;
	memset(&peer->protocol_state->peer_handshake_key, 0, sizeof(peer->protocol_state->peer_handshake_key));
}

static void respond_handshake(const fastd_socket_t *sock, const fastd_peer_address_t *local_addr, const fastd_peer_address_t *remote_addr, fastd_peer_t *peer,
			      const aligned_int256_t *peer_handshake_key, const fastd_method_info_t *method) {
	pr_debug("responding handshake with %P[%I]...", peer, remote_addr);

	const handshake_key_t *handshake_key = &ctx.protocol_state->handshake_key;

	if (!update_shared_handshake_key(peer, handshake_key, peer_handshake_key))
		return;

	fastd_buffer_t buffer = fastd_handshake_new_reply(2, method, true, 4*(4+PUBLICKEYBYTES) + 2*(4+HASHBYTES));

	fastd_handshake_add(&buffer, RECORD_SENDER_KEY, PUBLICKEYBYTES, &conf.protocol_config->key.public);
	fastd_handshake_add(&buffer, RECORD_RECEIPIENT_KEY, PUBLICKEYBYTES, &peer->protocol_config->public_key);
	fastd_handshake_add(&buffer, RECORD_SENDER_HANDSHAKE_KEY, PUBLICKEYBYTES, &handshake_key->key.public);
	fastd_handshake_add(&buffer, RECORD_RECEIPIENT_HANDSHAKE_KEY, PUBLICKEYBYTES, peer_handshake_key);

	fastd_sha256_t hmacbuf;

	if (!conf.secure_handshakes) {
		fastd_hmacsha256_blocks(&hmacbuf, peer->protocol_state->shared_handshake_key_compat.w, conf.protocol_config->key.public.u32, handshake_key->key.public.u32, NULL);
		fastd_handshake_add(&buffer, RECORD_T, HASHBYTES, hmacbuf.b);
	}

	uint8_t *mac = fastd_handshake_add_zero(&buffer, RECORD_TLV_MAC, HASHBYTES);
	fastd_hmacsha256(&hmacbuf, peer->protocol_state->shared_handshake_key.w, fastd_handshake_tlv_data(&buffer), fastd_handshake_tlv_len(&buffer));
	memcpy(mac, hmacbuf.b, HASHBYTES);

	fastd_send_handshake(sock, local_addr, remote_addr, peer, buffer);
}

static void finish_handshake(fastd_socket_t *sock, const fastd_peer_address_t *local_addr, const fastd_peer_address_t *remote_addr, fastd_peer_t *peer, const handshake_key_t *handshake_key, const aligned_int256_t *peer_handshake_key,
			     const fastd_handshake_t *handshake, const fastd_method_info_t *method) {
	pr_debug("finishing handshake with %P[%I]...", peer, remote_addr);

	bool compat = !secure_handshake(handshake);

	aligned_int256_t sigma;
	fastd_sha256_t shared_handshake_key, shared_handshake_key_compat;
	if (!make_shared_handshake_key(&handshake_key->key.secret, true,
				       &conf.protocol_config->key.public,
				       &peer->protocol_config->public_key,
				       &handshake_key->key.public,
				       peer_handshake_key,
				       &sigma,
				       compat ? NULL : &shared_handshake_key,
				       compat ? &shared_handshake_key_compat : NULL))
		return;

	bool valid;
	if (!compat) {
		uint8_t mac[HASHBYTES] __attribute__((aligned(8)));
		memcpy(mac, handshake->records[RECORD_TLV_MAC].data, HASHBYTES);
		memset(handshake->records[RECORD_TLV_MAC].data, 0, HASHBYTES);

		valid = fastd_hmacsha256_verify(mac, shared_handshake_key.w, handshake->tlv_data, handshake->tlv_len);
	}
	else {
		valid = fastd_hmacsha256_blocks_verify(handshake->records[RECORD_T].data, shared_handshake_key_compat.w, peer->protocol_config->public_key.u32, peer_handshake_key->u32, NULL);
	}

	if (!valid) {
		pr_warn("received invalid protocol handshake response from %P[%I]", peer, remote_addr);
		return;
	}

	if (!establish(peer, method, sock, local_addr, remote_addr, true, &handshake_key->key.public, peer_handshake_key, &conf.protocol_config->key.public,
		       &peer->protocol_config->public_key, &sigma, compat ? NULL : shared_handshake_key.w, handshake_key->serial))
		return;

	fastd_buffer_t buffer = fastd_handshake_new_reply(3, method, false, 4*(4+PUBLICKEYBYTES) + 2*(4+HASHBYTES));

	fastd_handshake_add(&buffer, RECORD_SENDER_KEY, PUBLICKEYBYTES, &conf.protocol_config->key.public);
	fastd_handshake_add(&buffer, RECORD_RECEIPIENT_KEY, PUBLICKEYBYTES, &peer->protocol_config->public_key);
	fastd_handshake_add(&buffer, RECORD_SENDER_HANDSHAKE_KEY, PUBLICKEYBYTES, &handshake_key->key.public);
	fastd_handshake_add(&buffer, RECORD_RECEIPIENT_HANDSHAKE_KEY, PUBLICKEYBYTES, peer_handshake_key);

	if (!compat) {
		fastd_sha256_t hmacbuf;
		uint8_t *mac = fastd_handshake_add_zero(&buffer, RECORD_TLV_MAC, HASHBYTES);
		fastd_hmacsha256(&hmacbuf, shared_handshake_key.w, fastd_handshake_tlv_data(&buffer), fastd_handshake_tlv_len(&buffer));
		memcpy(mac, hmacbuf.b, HASHBYTES);
	}
	else {
		fastd_sha256_t hmacbuf;
		fastd_hmacsha256_blocks(&hmacbuf, shared_handshake_key_compat.w, conf.protocol_config->key.public.u32, handshake_key->key.public.u32, NULL);
		fastd_handshake_add(&buffer, RECORD_T, HASHBYTES, hmacbuf.b);
	}

	fastd_send_handshake(sock, local_addr, remote_addr, peer, buffer);
}

static void handle_finish_handshake(fastd_socket_t *sock, const fastd_peer_address_t *local_addr, const fastd_peer_address_t *remote_addr,
				    fastd_peer_t *peer, const handshake_key_t *handshake_key, const aligned_int256_t *peer_handshake_key,
				    const fastd_handshake_t *handshake, const fastd_method_info_t *method) {
	pr_debug("handling handshake finish with %P[%I]...", peer, remote_addr);

	bool compat = !secure_handshake(handshake);

	if (!update_shared_handshake_key(peer, handshake_key, peer_handshake_key))
		return;

	bool valid;
	if (!compat) {
		uint8_t mac[HASHBYTES];
		memcpy(mac, handshake->records[RECORD_TLV_MAC].data, HASHBYTES);
		memset(handshake->records[RECORD_TLV_MAC].data, 0, HASHBYTES);

		valid = fastd_hmacsha256_verify(mac, peer->protocol_state->shared_handshake_key.w, handshake->tlv_data, handshake->tlv_len);
	}
	else {
		valid = fastd_hmacsha256_blocks_verify(handshake->records[RECORD_T].data, peer->protocol_state->shared_handshake_key_compat.w, peer->protocol_config->public_key.u32, peer_handshake_key->u32, NULL);
	}

	if (!valid) {
		pr_warn("received invalid protocol handshake finish from %P[%I]", peer, remote_addr);
		return;
	}

	establish(peer, method, sock, local_addr, remote_addr, false, peer_handshake_key, &handshake_key->key.public, &peer->protocol_config->public_key,
		  &conf.protocol_config->key.public, &peer->protocol_state->sigma, compat ? NULL : peer->protocol_state->shared_handshake_key.w, handshake_key->serial);

	clear_shared_handshake_key(peer);
}

static fastd_peer_t* find_sender_key(const fastd_peer_address_t *address, const unsigned char key[PUBLICKEYBYTES]) {
	errno = 0;

	fastd_peer_t *ret = NULL;
	size_t i;

	for (i = 0; i < VECTOR_LEN(ctx.peers); i++) {
		fastd_peer_t *peer = VECTOR_INDEX(ctx.peers, i);

		if (memcmp(&peer->protocol_config->public_key, key, PUBLICKEYBYTES) == 0) {
			if (!fastd_peer_matches_address(peer, address)) {
				errno = EPERM;
				return NULL;
			}

			ret = peer;
			continue;
		}

		if (fastd_peer_owns_address(peer, address)) {
			errno = EPERM;
			return NULL;
		}
	}

	if (!ret)
		errno = ENOENT;

	return ret;
}

static fastd_peer_t* match_sender_key(const fastd_socket_t *sock, const fastd_peer_address_t *address, fastd_peer_t *peer, const unsigned char key[PUBLICKEYBYTES]) {
	errno = 0;

	if (sock->peer && peer != sock->peer)
		exit_bug("packet without correct peer set on dynamic socket");

	if (peer) {
		if (memcmp(&peer->protocol_config->public_key, key, PUBLICKEYBYTES) == 0)
			return peer;

		if (fastd_peer_owns_address(peer, address)) {
			errno = EPERM;
			return NULL;
		}
	}

	return find_sender_key(address, key);
}

static size_t key_count(const unsigned char key[PUBLICKEYBYTES]) {
	size_t ret = 0;

	fastd_peer_config_t *p;
	for (p = conf.peers; p; p = p->next) {
		if (!p->protocol_config)
			continue;

		if (memcmp(&p->protocol_config->public_key, key, PUBLICKEYBYTES) == 0)
			ret++;
	}

	return ret;
}

bool fastd_protocol_ec25519_fhmqvc_peer_check(fastd_peer_config_t *peer_conf) {
	if (!peer_conf->protocol_config)
		return false;

	if (memcmp(&peer_conf->protocol_config->public_key, &conf.protocol_config->key.public, PUBLICKEYBYTES) == 0)
		return false;

	if (key_count(peer_conf->protocol_config->public_key.u8) > 1) {
		char buf[65];
		hexdump(buf, peer_conf->protocol_config->public_key.u8);
		pr_warn("more than one peer is configured with key %s, disabling %s", buf, peer_conf->name);
		return false;
	}

	return true;
}

void fastd_protocol_ec25519_fhmqvc_handshake_init(fastd_socket_t *sock, const fastd_peer_address_t *local_addr, const fastd_peer_address_t *remote_addr, fastd_peer_t *peer) {
	fastd_protocol_ec25519_fhmqvc_maintenance();

	fastd_buffer_t buffer = fastd_handshake_new_init(3*(4+PUBLICKEYBYTES) /* sender key, receipient key, handshake key */);

	fastd_handshake_add(&buffer, RECORD_SENDER_KEY, PUBLICKEYBYTES, &conf.protocol_config->key.public);

	if (peer)
		fastd_handshake_add(&buffer, RECORD_RECEIPIENT_KEY, PUBLICKEYBYTES, &peer->protocol_config->public_key);
	else
		pr_debug("sending handshake to unknown peer %I", remote_addr);

	fastd_handshake_add(&buffer, RECORD_SENDER_HANDSHAKE_KEY, PUBLICKEYBYTES, &ctx.protocol_state->handshake_key.key.public);

	if (!peer || !fastd_peer_is_established(peer))
		fastd_peer_exec_shell_command(&conf.on_connect, peer, (local_addr && local_addr->sa.sa_family) ? local_addr : sock->bound_addr, remote_addr);

	fastd_send_handshake(sock, local_addr, remote_addr, peer, buffer);
}

bool fastd_protocol_ec25519_fhmqvc_peer_check_temporary(fastd_peer_t *peer) {
	if (key_count(peer->protocol_config->public_key.u8)) {
		char buf[65];
		hexdump(buf, peer->protocol_config->public_key.u8);
		pr_info("key %s is configured now, deleting temporary peer.", buf);
		return false;
	}

	return true;
}


#ifdef WITH_VERIFY

typedef struct verify_data {
	aligned_int256_t peer_handshake_key;
} verify_data_t;

static fastd_peer_t * add_temporary(fastd_socket_t *sock, const fastd_peer_address_t *addr, const unsigned char key[PUBLICKEYBYTES]) {
	if (!fastd_allow_verify()) {
		pr_debug("ignoring handshake from %I (unknown key)", addr);
		return NULL;
	}

	if (sock->peer) {
		/* WTF? */
		pr_debug("ignoring handshake from %I (received on another peer's socket)", addr);
		return NULL;
	}

	if (key_count(key)) {
		pr_debug("ignoring handshake from %I (disabled key)", addr);
		return NULL;
	}

	fastd_peer_t *peer = fastd_peer_add(NULL);

	peer->protocol_config = malloc(sizeof(fastd_protocol_peer_config_t));
	memcpy(&peer->protocol_config->public_key, key, PUBLICKEYBYTES);

	/* Ugly hack */
	peer->protocol_state->last_serial--;

	return peer;
}

static bool handle_temporary(fastd_socket_t *sock, const fastd_peer_address_t *local_addr, const fastd_peer_address_t *remote_addr,
			     fastd_peer_t *peer, const fastd_handshake_t *handshake, const fastd_method_info_t *method) {
	if (handshake->type != 1 || !fastd_timed_out(&peer->verify_timeout))
		return !fastd_timed_out(&peer->verify_valid_timeout);

	verify_data_t verify_data;
	memset(&verify_data, 0, sizeof(verify_data));
	memcpy(&verify_data.peer_handshake_key, handshake->records[RECORD_SENDER_HANDSHAKE_KEY].data, PUBLICKEYBYTES);

	fastd_tristate_t verified = fastd_verify_peer(peer, sock, local_addr, remote_addr, method, &verify_data, sizeof(verify_data));

	if (!verified.set)
		/* async verify */
		return false;

	if (!verified.state) {
		pr_debug("ignoring handshake from %P[%I] (verification failed)", peer, remote_addr);
		fastd_peer_delete(peer);
		return false;
	}

	return true;
}

void fastd_protocol_ec25519_fhmqvc_handle_verify_return(fastd_peer_t *peer, fastd_socket_t *sock, const fastd_peer_address_t *local_addr, const fastd_peer_address_t *remote_addr,
							const fastd_method_info_t *method, const void *protocol_data, bool ok) {
	if (!ok)
		return;

	const verify_data_t *data = protocol_data;

	peer->last_handshake_response_timeout = fastd_in_seconds(MIN_HANDSHAKE_INTERVAL);
	peer->last_handshake_response_address = *remote_addr;
	respond_handshake(sock, local_addr, remote_addr, peer, &data->peer_handshake_key, method);
}

#else

static inline fastd_peer_t * add_temporary(fastd_socket_t *sock UNUSED, const fastd_peer_address_t *addr, const unsigned char key[PUBLICKEYBYTES] UNUSED) {
	pr_debug("ignoring handshake from %I (unknown key)", addr);
	return NULL;
}

#endif /* WITH_VERIFY */


void fastd_protocol_ec25519_fhmqvc_handshake_handle(fastd_socket_t *sock, const fastd_peer_address_t *local_addr, const fastd_peer_address_t *remote_addr,
						    fastd_peer_t *peer, const fastd_handshake_t *handshake, const fastd_method_info_t *method) {
	fastd_protocol_ec25519_fhmqvc_maintenance();

	if (!has_field(handshake, RECORD_SENDER_KEY, PUBLICKEYBYTES)) {
		pr_debug("received handshake without sender key from %I", remote_addr);
		return;
	}

	peer = match_sender_key(sock, remote_addr, peer, handshake->records[RECORD_SENDER_KEY].data);
	if (!peer) {
		switch (errno) {
		case EPERM:
			pr_debug("ignoring handshake from %I (incorrect source address)", remote_addr);
			return;

		case ENOENT:
			peer = add_temporary(sock, remote_addr, handshake->records[RECORD_SENDER_KEY].data);
			if (peer)
				break;

			return;

		default:
			exit_bug("match_sender_key: unknown error");
		}
	}

	if (!has_field(handshake, RECORD_SENDER_HANDSHAKE_KEY, PUBLICKEYBYTES)) {
		pr_debug("received handshake without sender handshake key from %P[%I]", peer, remote_addr);
		return;
	}

	if (!fastd_peer_may_connect(peer)) {
		pr_debug("ignoring handshake from %P[%I] because of local constraints", peer, remote_addr);
		return;
	}

	if (!fastd_timed_out(&peer->establish_handshake_timeout)) {
		pr_debug("received repeated handshakes from %P[%I], ignoring", peer, remote_addr);
		return;
	}

	if (has_field(handshake, RECORD_RECEIPIENT_KEY, PUBLICKEYBYTES)) {
		if (memcmp(&conf.protocol_config->key.public, handshake->records[RECORD_RECEIPIENT_KEY].data, PUBLICKEYBYTES) != 0) {
			pr_debug("received protocol handshake with wrong receipient key from %P[%I]", peer, remote_addr);
			return;
		}
	}

#ifdef WITH_VERIFY
	if (fastd_peer_is_temporary(peer)) {
		if (!handle_temporary(sock, local_addr, remote_addr, peer, handshake, method))
			return;
	}
#endif

	aligned_int256_t peer_handshake_key;
	memcpy(&peer_handshake_key, handshake->records[RECORD_SENDER_HANDSHAKE_KEY].data, PUBLICKEYBYTES);

	if (handshake->type == 1) {
		if (!fastd_timed_out(&peer->last_handshake_response_timeout)
		    && fastd_peer_address_equal(remote_addr, &peer->last_handshake_response_address)) {
			pr_debug("not responding to repeated handshake from %P[%I]", peer, remote_addr);
			return;
		}

		pr_verbose("received handshake from %P[%I]%s%s", peer, remote_addr, handshake->peer_version ? " using fastd " : "", handshake->peer_version ?: "");

		peer->last_handshake_response_timeout = fastd_in_seconds(MIN_HANDSHAKE_INTERVAL);
		peer->last_handshake_response_address = *remote_addr;
		respond_handshake(sock, local_addr, remote_addr, peer, &peer_handshake_key, method);
		return;
	}

	if (!has_field(handshake, RECORD_RECEIPIENT_KEY, PUBLICKEYBYTES)) {
		pr_debug("received handshake reply without receipient key from %P[%I]", peer, remote_addr);
		return;
	}

	if (!has_field(handshake, RECORD_RECEIPIENT_HANDSHAKE_KEY, PUBLICKEYBYTES)) {
		pr_debug("received handshake reply without receipient handshake key from %P[%I]", peer, remote_addr);
		return;
	}

	if (!secure_handshake(handshake)) {
		if (conf.secure_handshakes || !has_field(handshake, RECORD_T, HASHBYTES)) {
			pr_debug("received handshake reply without HMAC from %P[%I]", peer, remote_addr);
			return;
		}
	}

	handshake_key_t *handshake_key;
	if (is_handshake_key_valid(&ctx.protocol_state->handshake_key) &&
	    memcmp(&ctx.protocol_state->handshake_key.key.public, handshake->records[RECORD_RECEIPIENT_HANDSHAKE_KEY].data, PUBLICKEYBYTES) == 0) {
		handshake_key = &ctx.protocol_state->handshake_key;
	}
	else if (is_handshake_key_valid(&ctx.protocol_state->prev_handshake_key) &&
		 memcmp(&ctx.protocol_state->prev_handshake_key.key.public, handshake->records[RECORD_RECEIPIENT_HANDSHAKE_KEY].data, PUBLICKEYBYTES) == 0) {
		handshake_key = &ctx.protocol_state->prev_handshake_key;
	}
	else {
		pr_debug("received handshake reply with unexpected receipient handshake key from %P[%I]", peer, remote_addr);
		return;
	}

	switch (handshake->type) {
	case 2:
		pr_verbose("received handshake response from %P[%I]%s%s", peer, remote_addr, handshake->peer_version ? " using fastd " : "", handshake->peer_version ?: "");

		finish_handshake(sock, local_addr, remote_addr, peer, handshake_key, &peer_handshake_key, handshake, method);
		break;

	case 3:
		pr_debug("received handshake finish from %P[%I]%s%s", peer, remote_addr, handshake->peer_version ? " using fastd " : "", handshake->peer_version ?: "");

		handle_finish_handshake(sock, local_addr, remote_addr, peer, handshake_key, &peer_handshake_key, handshake, method);
		break;

	default:
		pr_debug("received handshake reply with unknown type %u from %P[%I]", handshake->type, peer, remote_addr);
	}
}