summary refs log tree commit diff
path: root/common.h
blob: 2059d816938749b6006d34bdcacb478a250a9f2e (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
/* common (not config, need code patch after change) */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <time.h>

#include "shorttypes.h"
#include "crypto-sponge.h"

#define ERRDIE(a, b) if ((a) == -1) perror((b)), exit(1)

#define NONCE_SZ 16
#define HMAC_SZ  16

#define MIN_PKT_SZ NONCE_SZ + HMAC_SZ + 4 + 4 + 8 + 1
#if MAX_PKT_SZ < MIN_PKT_SZ
#error "MAX_PKT_SZ < MIN_PKT_SZ"
#endif

#define CONNECT (u16)32
#define PING    (u16)4
#define SSTATE  (u16)8

u8  key[32];
u8  password[PASSWORD_BUF_SZ];
u32 prng_state[14];


static void send_pkt
(s32 skt, void *buf, u16 sz, struct sockaddr_storage *addr){
	ssize_t res;
	u8 *nonce, *tag;

	/* nonce, tag */
	nonce = (u8*)buf + sz;
	tag = nonce + NONCE_SZ;
	duplex257_prng_rand16(prng_state, nonce);

	/* encrypt */
	duplex257_ae_encrypt(key, nonce, tag, buf, sz);
	sz += NONCE_SZ + HMAC_SZ;

	/* send */
	res = sendto(skt, buf, sz, 0,(struct sockaddr*)addr, sizeof(*addr));
	ERRDIE(res, "sendto");
	return;
}

static s32 recv_pkt
(s32 skt, void *buf, u16 sz, struct sockaddr_storage *addr){
	socklen_t skl;
	s32 res;
	u8 *nonce, *rtag;
	u8 tag[HMAC_SZ];

	/* recv */
	skl = sizeof(*addr);
	res = recvfrom(skt, buf, sz, 0, (struct sockaddr*)addr, &skl);
	ERRDIE(res, "recvfrom");

	/* drop packet if it too small */
	if (res < 4 + NONCE_SZ + HMAC_SZ) return -1;

	/* nonce, recieved tag */
	rtag = buf + res - HMAC_SZ;
	nonce  = rtag - NONCE_SZ;

	/* decrypt */
	res -= NONCE_SZ + HMAC_SZ;
	duplex257_ae_decrypt(key, nonce, tag, buf, res);
	if (0 != memcmp(tag, rtag, HMAC_SZ)) return -1;

	return res;
}