summaryrefslogtreecommitdiffstats
path: root/src/wireguard.c
blob: dd9082e31b37e95ef3cd54b1d87c027daade3f77 (plain) (blame)
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
#include <sys/types.h>
#include <sys/systm.h>
#include <sys/rwlock.h>
#include <sys/time.h>

#include <crypto/blake2s.h>
#include <crypto/curve25519.h>
#include <crypto/chachapoly.h>

#include <net/wireguard.h>

/* Constants for the wg protocol */
#define WG_CONSTRUCTION "Noise_IKpsk2_25519_ChaChaPoly_BLAKE2s"
#define WG_IDENTIFIER "WireGuard v1 zx2c4 Jason@zx2c4.com"
#define WG_MAC1 "mac1----"
#define WG_COOKIE "cookie--"

/* First byte indicating packet type on the wire */
#define WG_MSG_INITIATION htole32(1)
#define WG_MSG_RESPONSE htole32(2)
#define WG_MSG_COOKIE htole32(3)
#define WG_MSG_TRANSPORT htole32(4)

/* Temp defines */
#define offsetof(type, member)  ((size_t)(&((type *)0)->member))
#define	CTASSERT(x)	extern char  _ctassert[(x) ? 1 : -1 ]	\
			    __attribute__((__unused__))

/* Ensure struct sizes are correct at compile time. This allows us to overlay
 * the struct on the incoming network packet and access it as if it was a
 * struct. */
CTASSERT(sizeof(struct wg_msg_initiation) == 148);
CTASSERT(sizeof(struct wg_msg_response) == 92);
CTASSERT(sizeof(struct wg_msg_cookie) == 64);
CTASSERT(sizeof(struct wg_msg_transport) == 16);
//CTASSERT(sizeof(struct wg_timestamp) == 12);

CTASSERT(WG_KEY_SIZE == CHACHA20POLY1305_KEY_SIZE);
CTASSERT(WG_HASH_SIZE == BLAKE2S_HASH_SIZE);
CTASSERT(WG_KEY_SIZE == BLAKE2S_KEY_SIZE);
CTASSERT(WG_KEY_SIZE == WG_HASH_SIZE);
CTASSERT(WG_MSG_PADDING_SIZE == CHACHA20POLY1305_AUTHTAG_SIZE);
CTASSERT(WG_XNONCE_SIZE == XCHACHA20POLY1305_NONCE_SIZE);

#define ret_error(err) do { ret = err; goto leave; } while (0)

/* WireGuard crypto helper functions */
void
wg_kdf(uint8_t first[WG_HASH_SIZE], uint8_t second[WG_HASH_SIZE], uint8_t third[WG_HASH_SIZE], uint8_t key[WG_KEY_SIZE], uint8_t * input, size_t input_len)
{
	uint8_t 	buffer[WG_HASH_SIZE + 1];
	uint8_t 	secret[WG_HASH_SIZE];

	blake2s_hmac(secret, input, key, WG_HASH_SIZE, input_len, WG_KEY_SIZE);

	if (!first)
		return;

	buffer[0] = 1;
	blake2s_hmac(buffer, buffer, secret, WG_HASH_SIZE, 1, WG_KEY_SIZE);
	memcpy(first, buffer, WG_HASH_SIZE);

	if (!second)
		return;

	buffer[WG_HASH_SIZE] = 2;
	blake2s_hmac(buffer, buffer, secret, WG_HASH_SIZE, WG_HASH_SIZE + 1, WG_KEY_SIZE);
	memcpy(second, buffer, WG_HASH_SIZE);

	if (!third)
		return;

	buffer[WG_HASH_SIZE] = 3;
	blake2s_hmac(buffer, buffer, secret, WG_HASH_SIZE, WG_HASH_SIZE + 1, WG_KEY_SIZE);
	memcpy(third, buffer, WG_HASH_SIZE);
}

void
wg_hash2(uint8_t out[WG_HASH_SIZE], uint8_t * in1, size_t in1_len, uint8_t * in2, size_t in2_len)
{
	struct blake2s_state s;
	blake2s_init(&s, WG_HASH_SIZE);
	blake2s_update(&s, in1, in1_len);
	blake2s_update(&s, in2, in2_len);
	blake2s_final(&s, out, WG_HASH_SIZE);
}

void
wg_mix_hash(struct wg_handshake * hs, uint8_t * in, size_t in_len)
{
	wg_hash2(hs->hs_hash, hs->hs_hash, WG_HASH_SIZE, in, in_len);
}

void
wg_mix_dh(struct wg_handshake * hs, uint8_t priv[WG_KEY_SIZE], uint8_t pub[WG_KEY_SIZE])
{
	uint8_t 	DH    [WG_KEY_SIZE];
	crypto_scalarmult_curve25519(DH, priv, pub);
	wg_kdf(hs->hs_ck, hs->hs_k, NULL, hs->hs_ck, DH, WG_KEY_SIZE);
	explicit_bzero(DH, WG_KEY_SIZE);
}

void
wg_mix_psk(struct wg_handshake * hs, uint8_t psk[WG_KEY_SIZE])
{
	uint8_t 	t     [WG_HASH_SIZE];
	wg_kdf(hs->hs_ck, t, hs->hs_k, hs->hs_ck, psk, WG_KEY_SIZE);
	wg_mix_hash(hs, t, WG_HASH_SIZE);
	explicit_bzero(t, WG_HASH_SIZE);
}

void
wg_handshake_encrypt(struct wg_handshake *hs, uint8_t *dst, uint8_t *src, size_t srclen)
{
	return chacha20poly1305_encrypt(dst, src, srclen, hs->hs_hash, WG_HASH_SIZE, 0, hs->hs_k);
}

int
wg_handshake_decrypt(struct wg_handshake *hs, uint8_t *dst, uint8_t *src, size_t srclen)
{
	return chacha20poly1305_decrypt(dst, src, srclen, hs->hs_hash, WG_HASH_SIZE, 0, hs->hs_k);
}

void
wg_timestamp_get(uint8_t ts[WG_TIMESTAMP_SIZE])
{
	struct timespec tv;
	getnanotime(&tv);
	*(uint64_t *) (ts) = htobe64(tv.tv_sec);
	*(uint32_t *) (ts + 8) = htobe32(tv.tv_nsec);
}

/*
 * The following defines assist the wg_antireplay_check function. *
 * WG_ANTIREPLAY_INTEGER: the integer in the bitmap corresponding to num *
 * WG_ANTIREPLAY_INTEGERBIT: the integer with corresponding single bit set
 */
#define WG_ANTIREPLAY_INTEGER(ctx, num) (ctx->ar_bitmap[num % WG_ARB_BITS / WG_ARI_BITS])
#define WG_ANTIREPLAY_INTEGERBIT(num) (1llu << (num & (WG_ARI_BITS - 1)))

void
wg_antireplay_init(struct wg_antireplay * ctx)
{
	/* We just zero out the struct, expecting that then ctx->ar_head == 0 */
	explicit_bzero(ctx, sizeof(struct wg_antireplay));
}

int
wg_antireplay_check(struct wg_antireplay * ctx, uint64_t num)
{
	/* Bits after ctx->ar_head need to be zeroed. This is called when num is
	 * in front of ctx->ar_head, and those bits need to be set to 0 */
	for (; ctx->ar_head <= num; ctx->ar_head += WG_ARI_BITS) {
		WG_ANTIREPLAY_INTEGER(ctx, (ctx->ar_head + 1)) = 0;
	}

	if (ctx->ar_head > (num + WG_ARB_BITS - WG_ARI_BITS)) {
		/* Expired */
		return 1;
	} else if (WG_ANTIREPLAY_INTEGER(ctx, num) & WG_ANTIREPLAY_INTEGERBIT(num)) {
		/* Replayed */
		return 1;
	} else {
		/* Unseen */
		return 0;
	}
}

void
wg_handshake_init(struct wg_handshake *hs)
{
	bzero(hs, sizeof(*hs));
	rw_init(&hs->hs_lock, "wg_handshake");
}

void
wg_session_init(struct wg_session *s)
{
	bzero(s, sizeof(*s));
	rw_init(&s->s_lock, "wg_session");
}

enum wg_error
wg_handshake_merge(struct wg_handshake *dst, struct wg_handshake *src)
{
	enum wg_error ret = WG_OK;
	rw_enter_write(&dst->hs_lock);
	if (dst->hs_state != WG_STATE_CLEAN)
		ret_error(WG_STATE);

	if (dst->hs_skey != dst->hs_skey)
		ret_error(WG_STATE);

	if (memcmp(dst->hs_skey, src->hs_skey, WG_KEY_SIZE))
		ret_error(WG_STATE);

	if (memcmp(dst->hs_timestamp, src->hs_timestamp, WG_TIMESTAMP_SIZE) >= 0) 
		ret_error(WG_TIMESTAMP);

#define HS_COPY(elem) memcpy(&dst->elem, &src->elem, sizeof(dst->elem))
	HS_COPY(hs_state);
	HS_COPY(hs_local_id);
	HS_COPY(hs_remote_id);
	HS_COPY(hs_mac);
	HS_COPY(hs_hash);
	HS_COPY(hs_ck);
	HS_COPY(hs_k);
	HS_COPY(hs_timestamp);
	//HS_COPY(hs_cookie);
	//HS_COPY(hs_shared);
	//HS_COPY(hs_spub);
	//HS_COPY(hs_skey);
	HS_COPY(hs_epub);
	HS_COPY(hs_ekey);
#undef HS_COPY

leave:
	rw_exit_write(&dst->hs_lock);
	explicit_bzero(src, sizeof(struct wg_handshake));
	return ret;
}

uint32_t
wg_handshake_clean_nolock(struct wg_handshake *hs)
{
	uint32_t id = hs->hs_local_id;
	rw_assert_wrlock(&hs->hs_lock);
#define HS_CLEAN(elem) explicit_bzero(&hs->elem, sizeof(hs->elem))
	HS_CLEAN(hs_state);
	HS_CLEAN(hs_local_id);
	HS_CLEAN(hs_remote_id);
	HS_CLEAN(hs_mac);
	HS_CLEAN(hs_hash);
	HS_CLEAN(hs_ck);
	HS_CLEAN(hs_k);
	HS_CLEAN(hs_timestamp);
	HS_CLEAN(hs_cookie);
	//HS_CLEAN(hs_shared);
	//HS_CLEAN(hs_spub);
	//HS_CLEAN(hs_skey);
	HS_CLEAN(hs_epub);
	HS_CLEAN(hs_ekey);
#undef HS_CLEAN
	return id;
}

uint32_t
wg_handshake_clean(struct wg_handshake *hs)
{
	uint32_t ret;
	rw_enter_write(&hs->hs_lock);
	ret = wg_handshake_clean_nolock(hs);
	rw_exit_write(&hs->hs_lock);
	return ret;
}

uint32_t
wg_session_clean(struct wg_session *s)
{
#define S_CLEAN(elem) explicit_bzero(&s->elem, sizeof(s->elem))
	rw_enter_write(&s->s_lock);
	uint32_t id = s->s_local_id;
	S_CLEAN(s_state);
	S_CLEAN(s_txcounter);
	S_CLEAN(s_rxcounter);
	S_CLEAN(s_local_id);
	S_CLEAN(s_remote_id);
	S_CLEAN(s_created);
	S_CLEAN(s_txkey);
	S_CLEAN(s_rxkey);
	S_CLEAN(s_ar);
	rw_exit_write(&s->s_lock);
#undef S_CLEAN
	return id;
}

enum wg_error
wg_session_from_handshake(struct wg_session *s, struct wg_handshake *hs)
{
	enum wg_error ret = WG_OK;

	rw_enter_write(&s->s_lock);
	rw_enter_write(&hs->hs_lock);
	s->s_txcounter = s->s_rxcounter = 0;
	s->s_local_id = hs->hs_local_id;
	s->s_remote_id = hs->hs_remote_id;

	getnanotime(&s->s_created);

	if (hs->hs_state == WG_STATE_RECV_RESPONSE) {
		s->s_state = WG_STATE_INITIATOR;
		wg_kdf(s->s_txkey, s->s_rxkey, NULL, hs->hs_ck, NULL, 0);
	} else if (hs->hs_state == WG_STATE_MADE_RESPONSE) {
		s->s_state = WG_STATE_RESPONDER;
		wg_kdf(s->s_rxkey, s->s_txkey, NULL, hs->hs_ck, NULL, 0);
	} else {
		ret_error(WG_STATE);
	}

	wg_antireplay_init(&s->s_ar);
	wg_handshake_clean_nolock(hs);

leave:
	rw_exit_write(&hs->hs_lock);
	rw_exit_write(&s->s_lock);
	return ret;
}

int
wg_timespec_timedout(struct timespec * start, time_t timeout)
{
	struct timespec now;

	getnanotime(&now);

	return now.tv_sec == start->tv_sec + timeout ?
		now.tv_nsec > start->tv_nsec :
		now.tv_sec > start->tv_sec + timeout;
}

int
wg_handshake_need_cookie(struct wg_handshake *hs)
{
	return !wg_timespec_timedout(&hs->hs_cookie.time, WG_COOKIE_VALID_TIME);
}

int
wg_session_reject_tx(struct wg_session *s)
{
	return wg_timespec_timedout(&s->s_created, WG_REJECT_AFTER_TIME) ||
		s->s_txcounter > WG_REJECT_AFTER_MESSAGES;
}

int
wg_session_reject_rx(struct wg_session *s)
{
	return wg_timespec_timedout(&s->s_created, WG_REJECT_AFTER_TIME) ||
		s->s_rxcounter > WG_REJECT_AFTER_MESSAGES;
}

int
wg_session_rekey_tx(struct wg_session *s)
{
	if (s->s_state == WG_STATE_INITIATOR &&
	    wg_timespec_timedout(&s->s_created, WG_REKEY_AFTER_TIME))
		return 1;
	if (s->s_txcounter > WG_REKEY_AFTER_MESSAGES)
		return 1;
	return 0;
}

int
wg_session_rekey_rx(struct wg_session *s)
{
	if (s->s_state == WG_STATE_RESPONDER &&
	    wg_timespec_timedout(&s->s_created, WG_REKEY_AFTER_TIME_RECV))
		return 1;
	return 0;
}

enum wg_error
wg_handshake_make_initiation(struct wg_handshake *hs, uint32_t id, struct wg_msg_initiation *m)
{
	enum wg_error ret = WG_OK;

	rw_enter_write(&hs->hs_lock);

	if (hs->hs_state != WG_STATE_CLEAN)
		ret_error(WG_STATE);

	wg_keypair_generate(&hs->hs_ekey);

	m->type = WG_MSG_INITIATION;
	m->sender = hs->hs_local_id = id;
	memcpy(m->ephemeral, hs->hs_ekey.pub, WG_KEY_SIZE);

	wg_hash2(hs->hs_ck, WG_CONSTRUCTION, strlen(WG_CONSTRUCTION), NULL, 0);
	memcpy(hs->hs_hash, hs->hs_ck, WG_HASH_SIZE);
	wg_mix_hash(hs, WG_IDENTIFIER, strlen(WG_IDENTIFIER));

	wg_mix_hash(hs, hs->hs_spub, WG_KEY_SIZE);
	wg_kdf(hs->hs_ck, NULL, NULL, hs->hs_ck, hs->hs_ekey.pub, WG_KEY_SIZE);
	wg_mix_hash(hs, hs->hs_ekey.pub, WG_KEY_SIZE);
	wg_mix_dh(hs, hs->hs_ekey.priv, hs->hs_spub);

	wg_handshake_encrypt(hs, m->static_pub, hs->hs_skey->pub, WG_KEY_SIZE);

	wg_mix_hash(hs, m->static_pub, WG_ENCRYPTED_SIZE(WG_KEY_SIZE));
	wg_mix_dh(hs, hs->hs_skey->priv, hs->hs_spub);

	wg_timestamp_get(m->timestamp);

	wg_handshake_encrypt(hs, m->timestamp, m->timestamp, WG_TIMESTAMP_SIZE);
	wg_mix_hash(hs, m->timestamp, WG_ENCRYPTED_SIZE(WG_TIMESTAMP_SIZE));
	wg_hash2(hs->hs_k, WG_MAC1, strlen(WG_MAC1), hs->hs_spub, WG_KEY_SIZE);

	blake2s(m->mac1, (void *) m, hs->hs_k, sizeof(m->mac1), offsetof(struct wg_msg_initiation, mac1), sizeof(hs->hs_k));
	memcpy(hs->hs_mac, m->mac1, sizeof(hs->hs_mac));
	
	if (wg_handshake_need_cookie(hs))
		blake2s(m->mac2, (void *)m, hs->hs_cookie.cookie, sizeof(m->mac2), offsetof(struct wg_msg_initiation, mac2), sizeof(hs->hs_cookie.cookie));
	else
		bzero(m->mac2, WG_MAC_SIZE);

	hs->hs_state = WG_STATE_MADE_INITIATION;
	hs->hs_remote_id = 0;

leave:
	rw_exit_write(&hs->hs_lock);
	return ret;
}

enum wg_error
wg_handshake_make_response(struct wg_handshake *hs, uint32_t id, struct wg_msg_response *m)
{
	enum wg_error ret = WG_OK;

	rw_enter_write(&hs->hs_lock);

	if (hs->hs_state != WG_STATE_RECV_INITIATION)
		ret_error(WG_STATE);

	m->type = WG_MSG_RESPONSE;
	m->sender = id;
	m->receiver = hs->hs_remote_id;

	wg_kdf(hs->hs_ck, NULL, NULL, hs->hs_ck, hs->hs_ekey.pub, WG_KEY_SIZE);
	wg_mix_hash(hs, hs->hs_ekey.pub, WG_KEY_SIZE);

	memcpy(m->ephemeral, hs->hs_ekey.pub, WG_KEY_SIZE);

	wg_mix_dh(hs, hs->hs_ekey.priv, hs->hs_epub);
	wg_mix_dh(hs, hs->hs_ekey.priv, hs->hs_spub);

	wg_mix_psk(hs, hs->hs_shared);

	wg_handshake_encrypt(hs, m->empty, NULL, 0);

	wg_mix_hash(hs, m->empty, WG_ENCRYPTED_SIZE(0));

	wg_hash2(hs->hs_k, WG_MAC1, strlen(WG_MAC1), hs->hs_spub, WG_KEY_SIZE);
	blake2s(m->mac1, (void *)m, hs->hs_k, sizeof(m->mac1), offsetof(struct wg_msg_response, mac1), sizeof(hs->hs_k));
	memcpy(hs->hs_mac, m->mac1, sizeof(hs->hs_mac));

	if (wg_handshake_need_cookie(hs))
		blake2s(m->mac2, (void *)m, hs->hs_cookie.cookie, sizeof(m->mac2), offsetof(struct wg_msg_response, mac2), sizeof(hs->hs_cookie.cookie));
	else
		bzero(m->mac2, WG_MAC_SIZE);

	hs->hs_state = WG_STATE_MADE_RESPONSE;
leave:
	rw_exit_write(&hs->hs_lock);
	return ret;
}

enum wg_error
wg_handshake_make_cookie(struct wg_keypair *kp, struct wg_cookie *c, uint32_t id, uint8_t *ip, uint8_t ip_len, uint8_t mac[WG_MAC_SIZE], struct wg_msg_cookie *m)
{
	uint8_t val[WG_MAC_SIZE];
	uint8_t key[WG_KEY_SIZE]; // Same as WG_HASH_SIZE

	m->type = WG_MSG_COOKIE;
	m->receiver = id;
	arc4random_buf(m->nonce, sizeof(m->nonce));

	if (wg_timespec_timedout(&c->time, WG_COOKIE_VALID_TIME)) {
		getnanotime(&c->time);
		arc4random_buf(c->cookie, sizeof(c->cookie));
	}

	blake2s(val, ip, c->cookie, WG_MAC_SIZE, ip_len, WG_COOKIE_SIZE);

	wg_hash2(key, WG_COOKIE, strlen(WG_COOKIE), kp->pub, WG_KEY_SIZE);

	xchacha20poly1305_encrypt(m->cookie, val, WG_MAC_SIZE, mac, WG_MAC_SIZE, m->nonce, key);

	return WG_OK;
}

enum wg_error
wg_handshake_valid_mac2(struct wg_cookie *c, uint8_t *m, uint8_t mlen)
{
	uint8_t mac[WG_MAC_SIZE];
	blake2s(mac, m, c->cookie, WG_MAC_SIZE, mlen - WG_MAC_SIZE, WG_COOKIE_SIZE);
	return timingsafe_bcmp(mac, m + WG_MAC_SIZE, WG_MAC_SIZE) ?
		WG_MAC : WG_OK;
}

enum wg_error
wg_handshake_recv_initiation(struct wg_handshake *ths, struct wg_keypair *kp, struct wg_msg_initiation *m)
{
	enum wg_error ret = WG_OK;

	/* Setup */
	ths->hs_state = WG_STATE_RECV_INITIATION;
	ths->hs_skey = kp;
	ths->hs_local_id = 0;
	ths->hs_remote_id = m->sender;
	memcpy(ths->hs_epub, m->ephemeral, WG_KEY_SIZE);

	wg_keypair_generate(&ths->hs_ekey);

	/* Initialise hash */
	wg_hash2(ths->hs_ck, WG_CONSTRUCTION, strlen(WG_CONSTRUCTION), NULL, 0);
	memcpy(ths->hs_hash, ths->hs_ck, WG_HASH_SIZE);
	wg_mix_hash(ths, WG_IDENTIFIER, strlen(WG_IDENTIFIER));

	/* KDF and mix */
	wg_mix_hash(ths, ths->hs_skey->pub, WG_KEY_SIZE);
	wg_kdf(ths->hs_ck, NULL, NULL, ths->hs_ck, ths->hs_epub, WG_KEY_SIZE);
	wg_mix_hash(ths, ths->hs_epub, WG_KEY_SIZE);
	wg_mix_dh(ths, ths->hs_skey->priv, ths->hs_epub);

	if (!wg_handshake_decrypt(ths, ths->hs_spub, m->static_pub, WG_ENCRYPTED_SIZE(WG_KEY_SIZE)))
		ret_error(WG_DECRYPT);

	wg_mix_hash(ths, m->static_pub, WG_ENCRYPTED_SIZE(WG_KEY_SIZE));
	wg_mix_dh(ths, ths->hs_skey->priv, ths->hs_spub);

	if (!wg_handshake_decrypt(ths, ths->hs_timestamp, m->timestamp, WG_ENCRYPTED_SIZE(WG_TIMESTAMP_SIZE)))
		ret_error(WG_DECRYPT);

	wg_mix_hash(ths, m->timestamp, WG_ENCRYPTED_SIZE(WG_TIMESTAMP_SIZE));
	wg_hash2(ths->hs_k, WG_MAC1, strlen(WG_MAC1), ths->hs_skey->pub, WG_KEY_SIZE);

	blake2s(ths->hs_mac, (void *)m, ths->hs_k, sizeof(ths->hs_mac), offsetof(struct wg_msg_initiation, mac1), sizeof(ths->hs_k));

	if (timingsafe_bcmp(ths->hs_mac, m->mac1, WG_MAC_SIZE))
		ret_error(WG_MAC);

leave:
	return ret;
}


enum wg_error
wg_handshake_recv_response(struct wg_handshake *hs, struct wg_msg_response *m)
{
	enum wg_error ret = WG_OK;
	uint8_t	mac1[WG_MAC_SIZE];
	struct wg_handshake tmp_hs;

	rw_enter_write(&hs->hs_lock);

	if (hs->hs_state != WG_STATE_MADE_INITIATION)
		ret_error(WG_STATE);

	tmp_hs = *hs;

	tmp_hs.hs_remote_id = m->sender;
	memcpy(tmp_hs.hs_epub, m->ephemeral, WG_KEY_SIZE);

	wg_kdf(tmp_hs.hs_ck, NULL, NULL, tmp_hs.hs_ck, tmp_hs.hs_epub, WG_KEY_SIZE);
	wg_mix_hash(&tmp_hs, tmp_hs.hs_epub, WG_KEY_SIZE);

	wg_mix_dh(&tmp_hs, tmp_hs.hs_ekey.priv, tmp_hs.hs_epub);
	wg_mix_dh(&tmp_hs, tmp_hs.hs_skey->priv, tmp_hs.hs_epub);

	wg_mix_psk(&tmp_hs, tmp_hs.hs_shared);

	if (!wg_handshake_decrypt(&tmp_hs, NULL, m->empty, WG_MAC_SIZE))
		ret_error(WG_DECRYPT);

	wg_mix_hash(&tmp_hs, m->empty, WG_ENCRYPTED_SIZE(0));

	wg_hash2(tmp_hs.hs_k, WG_MAC1, strlen(WG_MAC1), tmp_hs.hs_skey->pub, WG_KEY_SIZE);
	blake2s(mac1, (void *)m, tmp_hs.hs_k, sizeof(mac1), offsetof(struct wg_msg_response, mac1), sizeof(tmp_hs.hs_k));

	if (timingsafe_bcmp(mac1, m->mac1, WG_MAC_SIZE))
		ret_error(WG_MAC);

	*hs = tmp_hs;
	hs->hs_state = WG_STATE_RECV_RESPONSE;
leave:
	rw_exit_write(&hs->hs_lock);
	explicit_bzero(&tmp_hs, sizeof(tmp_hs));
	return ret;
}

enum wg_error
wg_handshake_recv_cookie(struct wg_handshake *hs, struct wg_msg_cookie *m)
{
	uint8_t key[WG_KEY_SIZE];
	uint8_t value[WG_COOKIE_SIZE];
	enum wg_error ret = WG_OK;

	rw_enter_write(&hs->hs_lock);

	wg_hash2(key, WG_COOKIE, strlen(WG_COOKIE), hs->hs_spub, WG_KEY_SIZE);

	if(!xchacha20poly1305_decrypt(value, m->cookie, sizeof(m->cookie),
				hs->hs_mac, WG_MAC_SIZE, m->nonce, key))
		ret_error(WG_DECRYPT);

	memcpy(hs->hs_cookie.cookie, value, sizeof(hs->hs_cookie.cookie));
	getnanotime(&hs->hs_cookie.time);

leave:
	rw_exit_write(&hs->hs_lock);
	return ret;
}

enum wg_error
wg_session_encrypt(struct wg_session *s, struct wg_msg_transport *m, size_t len)
{
	enum wg_error ret = WG_OK;

	rw_enter_read(&s->s_lock);

	if (wg_session_reject_tx(s))
		ret_error(WG_REJECT);

	m->type = WG_MSG_TRANSPORT;
	m->receiver = s->s_remote_id;
	m->counter = s->s_txcounter++; /* TODO make atomic */

	chacha20poly1305_encrypt(m->data, m->data, len, NULL, 0, m->counter, s->s_txkey);

	/* Packet OK, but we do want a rekey */
	if (wg_session_rekey_tx(s))
		ret = WG_REKEY;
leave:
	rw_exit_read(&s->s_lock);
	return ret;
}

enum wg_error
wg_session_decrypt(struct wg_session *s, struct wg_msg_transport *m, size_t len)
{
	enum wg_error ret = WG_OK;
	size_t data_len = len - offsetof(struct wg_msg_transport, data);

	rw_enter_read(&s->s_lock);

	/* Check session is valid */
	if (wg_session_reject_rx(s))
		ret_error(WG_REJECT);

	/* Decrypt session */
	if (!chacha20poly1305_decrypt(m->data, m->data, data_len, NULL, 0, m->counter, s->s_rxkey))
		ret_error(WG_DECRYPT);

	/* Check for replay */
	if (wg_antireplay_check(&s->s_ar, m->counter))
		ret_error(WG_REPLAY);

	s->s_rxcounter = m->counter;

	/* Packet OK, but we do want a rekey */
	if (wg_session_rekey_tx(s))
		ret = WG_REKEY;
leave:
	rw_exit_read(&s->s_lock);
	return ret;
}

void
wg_keypair_from_bytes(struct wg_keypair *kp, const uint8_t key[WG_KEY_SIZE])
{
	const uint8_t basepoint[WG_KEY_SIZE] = {9};
	memcpy(kp->priv, key, WG_KEY_SIZE);
	crypto_scalarmult_curve25519(kp->pub, kp->priv, basepoint);
}

void
wg_keypair_generate(struct wg_keypair *kp)
{
	arc4random_buf(kp->priv, WG_KEY_SIZE);

	kp->priv[0] &= 248;
	kp->priv[31] = (kp->priv[31] & 127) | 64;

	wg_keypair_from_bytes(kp, kp->priv);
}


enum wg_pkt_type
wg_pkt_type(uint8_t *buf, size_t len)
{
	struct wg_msg_unknown *msg;

	if (len < sizeof(*msg))
		return WG_PKT_UNKNOWN;
	else
		msg = (struct wg_msg_unknown *)buf;

	if (msg->type == WG_MSG_INITIATION && len == sizeof(struct wg_msg_initiation))
		return WG_PKT_INITIATION;
	else if (msg->type == WG_MSG_RESPONSE && len == sizeof(struct wg_msg_response))
		return WG_PKT_RESPONSE;
	else if (msg->type == WG_MSG_COOKIE && len == sizeof(struct wg_msg_cookie))
		return WG_PKT_COOKIE;
	else if (msg->type == WG_MSG_TRANSPORT && 
			len >= WG_ENCRYPTED_SIZE(sizeof(struct wg_msg_transport)))
		return WG_PKT_TRANSPORT;
	else 
		return WG_PKT_UNKNOWN;
}