diff options
Diffstat (limited to 'receiver.c')
-rw-r--r-- | receiver.c | 298 |
1 files changed, 298 insertions, 0 deletions
diff --git a/receiver.c b/receiver.c new file mode 100644 index 0000000..b7171d9 --- /dev/null +++ b/receiver.c | |||
@@ -0,0 +1,298 @@ | |||
1 | #include <regex.h> | ||
2 | #include <string.h> | ||
3 | #include <dirent.h> | ||
4 | #include <err.h> | ||
5 | #include <stdio.h> | ||
6 | #include <inttypes.h> | ||
7 | #include <fcntl.h> | ||
8 | #include <unistd.h> | ||
9 | #include <sys/socket.h> | ||
10 | #include <netinet/in.h> | ||
11 | |||
12 | #include <mbedtls/pk.h> | ||
13 | #include <mbedtls/entropy.h> | ||
14 | #include "mbedtls/ctr_drbg.h" | ||
15 | #include "mbedtls/gcm.h" | ||
16 | |||
17 | const unsigned short PORT = 58132; | ||
18 | |||
19 | static const unsigned char privkey[] = | ||
20 | "-----BEGIN RSA PRIVATE KEY-----\n" | ||
21 | "MIIEpAIBAAKCAQEAwWlNmLHOOzZpdrfp+EAANwqab0FhQwCyZ/u+ySBW5XxPf6mo\n" | ||
22 | "bySvtJrLdsWzdwnup/UfwZiEhJk/4wpD4Qf/2+syuJi3Rf7L+Jfh//Qf9uXAS80+\n" | ||
23 | "LYad7dW0c1r5nt+F9Can5fBn7futnd8n672T+y8QpHRwX9GtaILvYQe5GQac8cfq\n" | ||
24 | "2rGUd5iYj5KSdcaIZnJ4YgnjLHg2PMbtEJwqcV+2oAkcOPzTAJoNE7XjLZTwXmLl\n" | ||
25 | "FgL/2cN4uJZBDnwv3RZSAhpdYF4KOJmE2GFs2jdvRUrYO7WSl8fM16vRH4vz5MNN\n" | ||
26 | "caprg2MlXheVTPQa+WMdcz7dyQx8s9kRVPPUSwIDAQABAoIBAH1KD8A4flYRO2Ry\n" | ||
27 | "YxgzrW/6aGxlt/HFg8ykYcS8NE5Yps8WQkwtQb0HAYKhM06LmpQm0DmC6WVUOPSE\n" | ||
28 | "c9BUdEQsKiE2nJK1KcCR8w7xP7uavWTdQcgQCkJFS63mYwmt1oKAgAcOIuUhQiig\n" | ||
29 | "pKWrmy7+IBPIcftAQssO9q6uaBNy+ONu6KU/FYd4UAoEt07MzuIAl5rybROOWCrA\n" | ||
30 | "cjuOKK830Q2Mi2ESwwlO0+3Vyz9VhSha5wW2WwFv9zx8YQblaVXxfXC6O5XcXb0j\n" | ||
31 | "O2rTpgHMmOVik3Zrg3XoRXsNZCvFQqbIevwGhRNEFQTnzakh/5g0VDa54RAK/APC\n" | ||
32 | "t3ABEAECgYEA+rnqDqmXQc/xMCLOhJduxRFvZbT6EbUVJG5+l6XtATTa4LWzqx1B\n" | ||
33 | "QDXS/Dixxc9FA1vSH2rAW//6wbr8KXihSeI7YxgIfWyrSIxbS3Dd1qwddvniYIpx\n" | ||
34 | "ms9vYpQKAewv2p310nf7fyuURES8YikhpSuff3DhzXBEi7s3Y7gIIEsCgYEAxXrD\n" | ||
35 | "6xjgLSgbbdyqxKeNk8ADMifbj8ZoiNIHkJ6sShFaTEbyHweOJ4RY7OmTBUDhgzUY\n" | ||
36 | "1oynztilADFaq8KhsiMqzI3DgZ3/2OElGYReEAbXljvgudL3tmiBWc5j9S7XNLBe\n" | ||
37 | "u9f3WYAYDu7/BVqmQWa/QtD9JquoZ1xgV2D6nAECgYEA29w9t9/VSJvM9xX+nNyi\n" | ||
38 | "AON6GOjrRK3TPWA7WEXjH+S2bshHJi0ANAs+2Xfpw/kunnRdPLmCtuowfMO4LbGf\n" | ||
39 | "VcexpgLEJyAszvBteikeDwpcyCD19wxP9J4kIYCJiggQKpfLoWUfP/P6DydrPnSt\n" | ||
40 | "EUbAlaNqDpl9Mj7YonQVhCMCgYEAv0c9M5+hrDuX7d76zYaZvI4UymUO54E/yZ7e\n" | ||
41 | "UvdOXGPYed+SL/oKeD5aQAeyLzl79bHdgBs3g0QW9kvXzly0cC5eC0oZH5hhs7nI\n" | ||
42 | "TKII1i86bLtM3dD5vQYWnF0sNtWK/+8Bo6L5ZAiNxRE7lP0L4ndaNKbnPaixcoRo\n" | ||
43 | "kNpPhAECgYAg7jmNlw+7VVurzR36LKKE+d6veraF5ltpJiboDb3j38RGe3982LLq\n" | ||
44 | "WaBKm1gkHfXgBjkNzS4r2kyRijw0GQ9JgmWooR7BXFH30HkPNl4gFTSsrOG5zGLi\n" | ||
45 | "0aexkDpXQuKsgBzqU0Wn94GZMM+RhuOYec/56JFT+8U5Tcntb26wwA==\n" | ||
46 | "-----END RSA PRIVATE KEY-----\n"; | ||
47 | |||
48 | static const unsigned char pp[] = "IJUHZGFDXTZKHJKHGFDHZLUÖDRTFGHHJGHH"; | ||
49 | |||
50 | /* | ||
51 | 1 byte type: 0 allocate session, 1 log to session, rest: discard | ||
52 | 8 bytes session id | ||
53 | type 0: | ||
54 | 256 bytes rsa 2048 data yielding 32 byte AES session key | ||
55 | type 1: | ||
56 | 16 bytes iv | ||
57 | 16 bytes tag | ||
58 | rest cipher text | ||
59 | |||
60 | File name format: 2020-10-13-23-42-05-SSSSSSSSSSSSSSSS-KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK.log | ||
61 | |||
62 | */ | ||
63 | |||
64 | enum { SESSION_ID_LENGTH = 8, AES_KEY_LENGTH = 16, GCM_IV_LENGTH = 16, GCM_TAG_LENGTH = 16 }; | ||
65 | typedef struct { | ||
66 | uint8_t session_id[SESSION_ID_LENGTH]; | ||
67 | uint8_t key[AES_KEY_LENGTH]; | ||
68 | int fd; // or -1 if not existing | ||
69 | time_t last_access; | ||
70 | char file_name[80]; | ||
71 | } SESSION; | ||
72 | static SESSION *g_sessions = 0; | ||
73 | static size_t g_session_count = 0; | ||
74 | |||
75 | int session_compare(const void *a, const void *b) { return memcmp(a, b, 8); } | ||
76 | |||
77 | enum { SIDOFFS = 20, KEYOFFS = 37, }; | ||
78 | |||
79 | static uint8_t hex2nyble(char c) | ||
80 | { | ||
81 | return (c>='0'&&c<='9') ? (uint8_t)(c-'0') | ||
82 | : (c>='a'&&c<='f') ? (uint8_t)(c-'a'+10) | ||
83 | : (c>='A'&&c<='F') ? (uint8_t)(c-'A'+10) | ||
84 | : 0; | ||
85 | } | ||
86 | |||
87 | static void import_sessions(const char *dirname) { | ||
88 | DIR * dirp = opendir(dirname); | ||
89 | if (!dirp) | ||
90 | errx(-1, "Fatal: Can't open dir %s\n", dirname); | ||
91 | |||
92 | free(g_sessions); | ||
93 | g_session_count = 0; | ||
94 | |||
95 | size_t allocated = 1024; | ||
96 | g_sessions = malloc(allocated * sizeof(SESSION)); | ||
97 | if (!g_sessions) | ||
98 | errx(-1, "Fatal: Out of memory"); | ||
99 | |||
100 | regex_t regex; | ||
101 | if (regcomp(®ex, "^[[:digit:]]{4}-[[:digit:]][[:digit:]]-[[:digit:]][[:digit:]]-[[:digit:]][[:digit:]]-[[:digit:]][[:digit:]]-" | ||
102 | "[[:digit:]][[:digit:]]-[[:xdigit:]]{16}-[[:xdigit:]]{32}.log$", REG_EXTENDED)) | ||
103 | errx(-1, "Fatal: Can't compile re"); | ||
104 | |||
105 | struct dirent * entry; | ||
106 | while ((entry = readdir(dirp)) != NULL) { | ||
107 | // We expect a very specific format | ||
108 | if (entry->d_type != DT_REG || entry->d_namlen != 73) { | ||
109 | fprintf(stderr, "Skipping wrong length file: %*s\n", entry->d_namlen, entry->d_name); | ||
110 | continue; | ||
111 | } | ||
112 | |||
113 | SESSION *ns = g_sessions + g_session_count; | ||
114 | |||
115 | memcpy(ns->file_name, entry->d_name, entry->d_namlen); | ||
116 | ns->file_name[entry->d_namlen] = 0; | ||
117 | ns->fd = -1; | ||
118 | ns->last_access = 0; | ||
119 | |||
120 | if (regexec(®ex, ns->file_name, (size_t) 0, NULL, 0)) { | ||
121 | fprintf(stderr, "Skipping non-re-matching file: %s\n", ns->file_name); | ||
122 | continue; | ||
123 | } | ||
124 | |||
125 | if (sscanf(ns->file_name + SIDOFFS, "%" SCNx64, (uint64_t*)&ns->session_id) != 1) { | ||
126 | fprintf(stderr, "Skipping non-parsable file: %s\n", ns->file_name); | ||
127 | continue; | ||
128 | } | ||
129 | const char * hexkey = ns->file_name + KEYOFFS; | ||
130 | for (int i=0; i<16; ++i) | ||
131 | ns->key[i] = (hex2nyble(hexkey[2*i]) << 4 ) | hex2nyble(hexkey[2*i+1]); | ||
132 | |||
133 | // Need more memory? | ||
134 | if (++g_session_count > allocated) { | ||
135 | allocated += 1024; | ||
136 | g_sessions = realloc(g_sessions, allocated * sizeof(SESSION)); | ||
137 | if (!g_sessions) | ||
138 | errx(-1, "Fatal: Out of memory"); | ||
139 | } | ||
140 | } | ||
141 | closedir(dirp); | ||
142 | regfree(®ex); | ||
143 | |||
144 | qsort(g_sessions, g_session_count, sizeof(SESSION), session_compare); | ||
145 | } | ||
146 | |||
147 | static void add_session(uint8_t *session_id, uint8_t aes_key[AES_KEY_LENGTH]) { | ||
148 | // We don't overwrite existing sessions | ||
149 | if (bsearch(session_id, g_sessions, g_session_count, sizeof(SESSION), session_compare)) | ||
150 | return; | ||
151 | |||
152 | SESSION * sessions_realloc = realloc(g_sessions, sizeof(SESSION) * (1 + g_session_count)); | ||
153 | |||
154 | if (!sessions_realloc) | ||
155 | errx(-1, "Fatal: Out of memory"); | ||
156 | |||
157 | g_sessions = sessions_realloc; | ||
158 | SESSION * new_session = &g_sessions[g_session_count]; | ||
159 | g_session_count++; | ||
160 | |||
161 | memcpy(new_session->session_id, session_id, SESSION_ID_LENGTH); | ||
162 | memcpy(new_session->key, aes_key, AES_KEY_LENGTH); | ||
163 | new_session->fd = -1; | ||
164 | new_session->last_access = 0; | ||
165 | |||
166 | time_t t = time(NULL); | ||
167 | struct tm * jetzt = localtime(&t); | ||
168 | char tprefix[32], hexkey[2*AES_KEY_LENGTH + 1]; | ||
169 | size_t nlen = strftime(tprefix, sizeof(tprefix), "%F-%H-%M-%S", jetzt); | ||
170 | for (int i=0; i<AES_KEY_LENGTH; ++i) | ||
171 | sprintf(hexkey + 2 * i, "%02x", aes_key[i]); | ||
172 | int off = snprintf(new_session->file_name, sizeof(new_session->file_name), | ||
173 | "%s-%" PRIx64 "-%s.log", tprefix, *(uint64_t*)session_id, hexkey); | ||
174 | int fd = open("new_session->file_name", O_RDWR|O_CREAT, 0755); | ||
175 | close(fd); | ||
176 | |||
177 | mergesort(g_sessions, g_session_count, sizeof(SESSION), session_compare); | ||
178 | } | ||
179 | |||
180 | static time_t now() { | ||
181 | struct timespec tp; | ||
182 | clock_gettime(CLOCK_MONOTONIC, &tp); | ||
183 | return tp.tv_sec; | ||
184 | } | ||
185 | |||
186 | static void log_to_session(const uint8_t *packet, size_t len) { | ||
187 | // First check if the packet holds enough space for session id, iv and at least one gcm block | ||
188 | if (len < SESSION_ID_LENGTH + GCM_IV_LENGTH + GCM_TAG_LENGTH) { | ||
189 | fprintf(stderr, "Error: Short packet, size %zd\n", len); | ||
190 | return; | ||
191 | } | ||
192 | |||
193 | const uint8_t *session_id = packet; | ||
194 | const uint8_t *iv = packet + SESSION_ID_LENGTH; | ||
195 | const uint8_t *tag = packet + SESSION_ID_LENGTH + GCM_IV_LENGTH; | ||
196 | packet += SESSION_ID_LENGTH + GCM_IV_LENGTH + GCM_TAG_LENGTH; | ||
197 | len -= SESSION_ID_LENGTH + GCM_IV_LENGTH + GCM_TAG_LENGTH; | ||
198 | |||
199 | SESSION * s = bsearch(session_id, g_sessions, g_session_count, sizeof(SESSION), session_compare); | ||
200 | if (!s) { | ||
201 | fprintf(stderr, "Error: Can't log to unknown session 0x%" PRIx64 "\n", *(uint64_t*)session_id); | ||
202 | return; | ||
203 | } | ||
204 | |||
205 | // Create output file if it doesn't exist | ||
206 | if (s->fd < 0) | ||
207 | s->fd = open(s->file_name, O_WRONLY | O_APPEND | O_CREAT, 0755); | ||
208 | if (s->fd < 0) { | ||
209 | fprintf(stderr, "Error: Can't create file %s for session 0x%" PRIx64 "\n", s->file_name, *(uint64_t*)packet); | ||
210 | return; | ||
211 | } | ||
212 | |||
213 | // Now decrypt | ||
214 | mbedtls_gcm_context ctx; | ||
215 | mbedtls_gcm_init(&ctx); | ||
216 | mbedtls_gcm_setkey(&ctx, MBEDTLS_CIPHER_ID_AES, s->key, 8 * AES_KEY_LENGTH); | ||
217 | |||
218 | // Prepare output scratch space | ||
219 | uint8_t *output = alloca(len); | ||
220 | |||
221 | // This should fail on invalid input sizes | ||
222 | switch(mbedtls_gcm_auth_decrypt(&ctx, len, iv, GCM_IV_LENGTH, session_id, SESSION_ID_LENGTH, tag, GCM_TAG_LENGTH, packet, output)) | ||
223 | { | ||
224 | case 0: | ||
225 | write(s->fd, output, len); | ||
226 | s->last_access = now(); | ||
227 | break; | ||
228 | case MBEDTLS_ERR_GCM_BAD_INPUT: | ||
229 | fprintf(stderr, "Error: Invalid log data\n"); | ||
230 | break; | ||
231 | case MBEDTLS_ERR_GCM_AUTH_FAILED : | ||
232 | fprintf(stderr, "Error: Can't decrypt\n"); | ||
233 | break; | ||
234 | default: | ||
235 | fprintf(stderr, "Error: Unknown gcm error\n"); | ||
236 | } | ||
237 | |||
238 | mbedtls_gcm_free(&ctx); | ||
239 | } | ||
240 | |||
241 | int main() { | ||
242 | mbedtls_ctr_drbg_context ctr_drbg; | ||
243 | mbedtls_entropy_context entropy; | ||
244 | mbedtls_pk_context pk; | ||
245 | int ret = 0; | ||
246 | unsigned char result[256]; | ||
247 | unsigned char input[256]; | ||
248 | size_t inputlen = 0; | ||
249 | |||
250 | chdir("sessions"); | ||
251 | |||
252 | mbedtls_pk_init( &pk ); | ||
253 | mbedtls_entropy_init( &entropy ); | ||
254 | mbedtls_ctr_drbg_init( &ctr_drbg ); | ||
255 | mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, pp, sizeof(pp)); | ||
256 | |||
257 | if ((ret = mbedtls_pk_parse_key(&pk, privkey, sizeof(privkey), NULL, 0) ) != 0 ) | ||
258 | errx(-1, "Fatal: mbedtls_pk_parse_key returned -0x%04x\n", -ret ); | ||
259 | |||
260 | int sock = socket(AF_INET, SOCK_DGRAM, 0); | ||
261 | if (sock < 0) | ||
262 | errx(-1, "Fatal: Can not make socket\n"); | ||
263 | |||
264 | struct sockaddr_in servaddr, peer; | ||
265 | servaddr.sin_family = AF_INET; | ||
266 | servaddr.sin_addr.s_addr = INADDR_ANY; | ||
267 | servaddr.sin_port = htons(PORT); | ||
268 | if (bind(sock, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) | ||
269 | errx(-1, "Fatal: Can't bind to port %d\n", PORT); | ||
270 | |||
271 | import_sessions("."); | ||
272 | |||
273 | while(1) { | ||
274 | uint8_t packet[16*1024]; | ||
275 | uint8_t rsa_plain_text[AES_KEY_LENGTH]; | ||
276 | size_t olen; | ||
277 | socklen_t peer_len = sizeof(peer); | ||
278 | |||
279 | ssize_t len = recvfrom(sock, packet, sizeof(packet), MSG_WAITALL, (struct sockaddr *) &peer, &peer_len); | ||
280 | if (len <= 0) | ||
281 | errx(-1, "Fatal: recvfrom yields %zd\n", len); | ||
282 | switch(packet[0]) { | ||
283 | case 0: // Session setup | ||
284 | ret = mbedtls_pk_decrypt(&pk, packet + 1 + SESSION_ID_LENGTH, len - 1 - SESSION_ID_LENGTH, | ||
285 | rsa_plain_text, &olen, sizeof(rsa_plain_text), mbedtls_ctr_drbg_random, &ctr_drbg); | ||
286 | if (ret < 0) | ||
287 | fprintf(stderr, "Error: Failed to decrypt key (error %d) for session 0x%" PRIx64 "\n", -ret, *(uint64_t *)(packet + 1)); | ||
288 | else | ||
289 | add_session(packet + 1, rsa_plain_text); | ||
290 | break; | ||
291 | case 1: | ||
292 | log_to_session(packet + 1, len - 1); | ||
293 | break; | ||
294 | default: | ||
295 | break; | ||
296 | } | ||
297 | } | ||
298 | } | ||