crypto debugging, and several bugfixes
[userv-utils] / ipif / forwarder.c
CommitLineData
1fb3cba0 1/*
2 * Encrypting tunnel for userv-ipif tunnels, actual implementation
3 *
4 * usage:
09966b49 5 * udptunnel-forwarder <optchars>
6 * <public-local-fd> <private-in-fd> <private-out-fd>
7 * <encdec-keys-fd>
1fb3cba0 8 * <mtu> <keepalive> <timeout>
9 * <public-remote-addr> [<public-remote-port>]
0f4b558c 10 * !<mech1> [<mech1-params> ...]
11 * !<mech2> [<mech2-params> ...]
1fb3cba0 12 * ''
13 *
14 * Remote addr may '' to mean wait to receive a packet and reply to
15 * whereever we get a good packet from first, in which case port
16 * should not be specified.
17 *
09966b49 18 * <optchars> is zero or more of
19 * w means generate and write encdec keys, rather than reading them
0f4b558c 20 * K means do crypto debug (use with care!)
1fb3cba0 21 *
22 * Every must be numeric. There is very little argument checking.
23 *
24 * Exit status:
25 * SIGALARM timed out
26 * 0 terminated due to outbound packet stream EOF
27 * 4 other error
28 * 8 system problem
29 * 12 usage error
30 * 16 bad trouble
31 */
32
33#include <sys/socket.h>
34#include <netinet/in.h>
35#include <arpa/inet.h>
36#include <sys/utsname.h>
37#include <sys/poll.h>
38
39#include <string.h>
40#include <errno.h>
41#include <assert.h>
42#include <stdlib.h>
43
44#include <unistd.h>
45#include <fcntl.h>
46
f9e59051 47#include "forwarder.h"
1fb3cba0 48
49#define MAXMECHS 10
1fb3cba0 50
1fb3cba0 51static size_t buffer_size;
0f4b558c 52static struct utsname uname_result;
1fb3cba0 53
09966b49 54static const char *opt_chars;
1fb3cba0 55static int public_local_fd, private_in_fd, private_out_fd;
56static int mtu2, keepalive, timeout;
57static int public_remote_specd;
58static struct sockaddr_in public_remote;
09966b49 59static int encdec_keys_fd, encdec_keys_write, crypto_debug;
1fb3cba0 60static int n_mechs;
61static const struct mechanism *mechs[MAXMECHS];
62
63static struct mechdata *md_in[MAXMECHS], *md_out[MAXMECHS];
64static size_t maxprefix, maxsuffix;
65
66static struct buffer buf_in, buf_out;
67static unsigned char *accum_buf;
68static size_t accum_used, accum_avail;
69
70static time_t nextsendka;
71
09966b49 72static void cdebug(int mechno /*or -1*/, const char *msg) {
73 if (!crypto_debug) return;
0f4b558c 74 printf("%s: CRYPTO: %-20s %s\n",
09966b49 75 programid,
0f4b558c 76 mechno >= 0 ? mechs[mechno]->name : "",
09966b49 77 msg);
78}
79
0f4b558c 80static void cdebughex(int mechno /*or -1*/, const char *msg, const void *ptr,
81 size_t sz, size_t skipbefore,
82 int spc_offset, int dot_offset) {
09966b49 83 const unsigned char *p;
0f4b558c 84 size_t i;
85 unsigned j= dot_offset;
09966b49 86
87 if (!crypto_debug) return;
0f4b558c 88 printf("%-8.8s: CRYPTO: %-20s %-10s",
89 uname_result.nodename,
90 mechno >= 0 ? mechs[mechno]->name : "",
09966b49 91 msg);
0f4b558c 92
93 for (i=0; i<spc_offset; i++, j++) fputs(j&3 ? " " : " ",stdout);
94 for (i=0; i<skipbefore; i++, j++) fputs(j&3 ? ".." : " ..",stdout);
95 for (i=0, p=ptr; i<sz; i++, j++, p++) printf(j&3 ? "%02x" : " %02x",*p);
96
09966b49 97 fputc('\n',stdout);
98}
99
0f4b558c 100static void cdebugbuf(int mechno /*or -1*/, const char *msg,
101 const struct buffer *buf, int spc_offset, int dot_offset) {
102 cdebughex(mechno, msg, buf->start, buf->size, buf->start - buf->base,
103 spc_offset, dot_offset);
104}
105
09966b49 106void get_random(void *ptr, size_t sz) {
107 static FILE *randfile;
108
109 size_t r;
110
111 if (!randfile) {
112 randfile= fopen("/dev/urandom","rb");
113 if (!randfile && errno==ENOENT) randfile= fopen("/dev/random","rb");
114 if (!randfile) sysfail("open random number generator");
115 }
116
117 r= fread(ptr,1,sz,randfile);
0f4b558c 118 if (r != sz)
119 (ferror(randfile) ? sysfail : fail)("cannot read random number generator");
09966b49 120
0f4b558c 121 cdebughex(-1, "get_random", ptr, sz, 0,0,0);
09966b49 122}
1fb3cba0 123
f9e59051 124void random_key(void *ptr, size_t sz) {
125 if (encdec_keys_write) {
126 get_random(ptr,sz);
127 write_must(encdec_keys_fd,ptr,sz,"write keys datastream");
128 } else {
129 read_must(encdec_keys_fd,ptr,sz,"read keys datastream");
1fb3cba0 130 }
1fb3cba0 131}
132
1fb3cba0 133
134static void setnonblock(int fd, int nonblock) {
135 int r;
136
137 r= fcntl(fd,F_GETFL);
138 if (r==-1) sysfail("fcntl F_GETFL");
139 r= fcntl(fd,F_SETFL, nonblock ? r|O_NONBLOCK : r&~O_NONBLOCK);
140 if (r==-1) sysfail("fcntl F_SETFL");
141}
142
0f4b558c 143static const struct mechanism *find_mech(const char *name) {
1fb3cba0 144 const struct mechanism *mech, *const *mechlist;
145
1fb3cba0 146 for (mechlist= mechanismlists;
147 *mechlist;
148 mechlist++)
149 for (mech= *mechlist; mech->name; mech++)
150 if (!strcmp(mech->name,name)) return mech;
151
152 fprintf(stderr,"%s: unknown mechanism: %s\n",programid,name);
153 exit(4);
154}
155
156static void inbound(void) {
157 static int any_recvd;
158
159 struct sockaddr_in this_saddr;
160 int r, i, different, this_saddrlen;
161 const char *emsg;
162
9d4e63db 163 buf_in.start= buf_in.base+1;
164 buf_in.size= buffer_size-2;
165
1fb3cba0 166 setnonblock(public_local_fd,1);
167 this_saddrlen= sizeof(this_saddr);
9d4e63db 168 r= recvfrom(public_local_fd, buf_in.start, buf_in.size, 0,
1fb3cba0 169 &this_saddr, &this_saddrlen);
170 if (!r) { diag("empty ciphertext"); return; }
171
172 if (r<0) {
f9e59051 173 if (errno != EAGAIN && errno != EINTR) { sysdiag("receive"); sleep(1); }
1fb3cba0 174 return;
175 }
176 if (this_saddr.sin_family != AF_INET) {
9d4e63db 177 fprintf(stderr,"%s: received unknown AF %lu\n",
1fb3cba0 178 programid, (unsigned long)this_saddr.sin_family);
179 return;
180 }
181 assert(this_saddrlen == sizeof(this_saddr));
182
9d4e63db 183 assert(r <= buf_in.size);
184 buf_in.size= r;
0f4b558c 185 cdebugbuf(-1, "decode", &buf_in, 3,0);
1fb3cba0 186 for (i=n_mechs-1; i>=0; i--) {
187 emsg= mechs[i]->decode(md_in[i],&buf_in);
188 if (emsg) {
189 fprintf(stderr, "%s: bad packet: %s: %s\n", programid, mechs[i]->name, emsg);
190 return;
191 }
0f4b558c 192 cdebugbuf(i, "decode", &buf_in, 3,0);
1fb3cba0 193 }
194
f9e59051 195 alarm(timeout);
196
9d4e63db 197 different= (!public_remote_specd ||
198 public_remote.sin_addr.s_addr != this_saddr.sin_addr.s_addr ||
199 public_remote.sin_port != this_saddr.sin_port);
1fb3cba0 200
201 if (different) {
202
203 if (public_remote_specd==2) {
9d4e63db 204 fprintf(stderr, "%s: packet from unexpected sender %s:%lu\n",
1fb3cba0 205 programid, inet_ntoa(this_saddr.sin_addr),
9d4e63db 206 (unsigned long)ntohs(this_saddr.sin_port));
1fb3cba0 207 return;
208 }
209
9d4e63db 210 fprintf(stderr, "%s: tunnel open with peer %s:%lu\n",
1fb3cba0 211 programid, inet_ntoa(this_saddr.sin_addr),
9d4e63db 212 (unsigned long)ntohs(this_saddr.sin_port));
1fb3cba0 213 nextsendka= now();
214 public_remote_specd= 1;
215 memcpy(&public_remote,&this_saddr,sizeof(public_remote));
216
217 } else if (!any_recvd) {
218
219 diag("tunnel open");
220
221 }
222
223 any_recvd= 1;
9d4e63db 224
225 if (!buf_in.size || *buf_in.start != 0300) {
226 *--buf_in.start= 0300;
227 buf_in.size++;
228 }
229 if (buf_in.start[buf_in.size-1] != 0300) {
230 buf_in.start[buf_in.size++]= 0300;
231 }
1fb3cba0 232
233 setnonblock(private_in_fd,0);
f9e59051 234 write_must(private_in_fd, buf_in.start, buf_in.size, "write down");
1fb3cba0 235}
236
237static void sendpacket(const unsigned char *message, size_t size) {
238 int i, r;
239
240 buf_out.start= buf_out.base+maxprefix;
241 buf_out.size= size;
242 memcpy(buf_out.start, message, size);
243
244 nextsendka= now() + keepalive;
245
0f4b558c 246 cdebugbuf(-1, "encode", &buf_out, 4,0);
247 for (i=0; i<n_mechs; i++) {
248 mechs[i]->encode(md_out[i],&buf_out);
249 cdebugbuf(i, "encode", &buf_out, 4,0);
250 }
1fb3cba0 251 assert(public_remote_specd);
252
253 setnonblock(public_local_fd,1);
254 for (;;) {
255 r= sendto(public_local_fd, buf_out.start, buf_out.size, 0,
256 &public_remote, sizeof(public_remote));
257 if (r == buf_out.size) break;
258 if (r >= 0) { diag("unexpected short send"); return; }
259 if (errno != EINTR) { sysdiag("send"); return; }
260 }
261}
262
263static void outbound(void) {
264 int r;
265 unsigned char *after_eaten, *delim;
266 size_t this_packet;
267
268 setnonblock(private_out_fd,1);
269
270 for (;;) {
271 r= read(private_out_fd, accum_buf + accum_used, accum_avail - accum_used);
272 if (!r) { diag("outbound datastream closed, quitting"); exit(0); }
273 if (r<0) {
274 if (errno == EAGAIN) return;
275 if (errno == EINTR) continue;
276 }
277 accum_used += r;
278 assert(accum_used<=accum_avail);
279
280 after_eaten= accum_buf;
281 while ((delim= memchr(after_eaten, 0300, accum_used))) {
282 this_packet= delim - after_eaten;
9d4e63db 283 if (this_packet) sendpacket(after_eaten, this_packet);
1fb3cba0 284 accum_used -= this_packet+1;
285 after_eaten = delim+1;
286 }
287 memmove(accum_buf, after_eaten, accum_used);
288
289 if (accum_used == accum_avail) {
290 diag("missing interpacket delimiter in output datastream");
291 accum_used= 0;
292 }
293 }
294}
295
296int main(int argc, const char *const *const argv_in) {
297 const char *arg;
0f4b558c 298 const char *const *argv_save;
299 const char *const *argv_done;
1fb3cba0 300 struct pollfd pollfds[2];
1fb3cba0 301 int i, polltimeout, r;
302 time_t tnow;
303
304 argv= argv_in;
305
306 if (uname(&uname_result)) { perror(PROGRAM ": uname failed"); exit(16); }
307 sprintf(programid, PROGRAM ": %.*s", SYS_NMLN, uname_result.nodename);
09966b49 308
309 opt_chars= getarg_string();
0f4b558c 310 encdec_keys_write= !!strchr(opt_chars,'w');
311 crypto_debug= !!strchr(opt_chars,'K');
09966b49 312
1fb3cba0 313 public_local_fd= getarg_ulong();
f9e59051 314 private_in_fd= getarg_ulong();
315 private_out_fd= getarg_ulong();
09966b49 316 encdec_keys_fd= getarg_ulong();
317
1fb3cba0 318 mtu2= getarg_ulong() * 2;
319 keepalive= getarg_ulong();
320 timeout= getarg_ulong();
1fb3cba0 321
322 arg= getarg_string();
323 if (*arg) {
324 public_remote_specd= 1;
9d4e63db 325 public_remote.sin_family= AF_INET;
1fb3cba0 326 arg_assert(inet_aton(arg,&public_remote.sin_addr));
9d4e63db 327 public_remote.sin_port= htons(getarg_ulong());
1fb3cba0 328 }
329
09966b49 330 if (crypto_debug) {
331 diag("crypto debugging enabled!");
332 setvbuf(stdout,0,_IOLBF,0);
333 }
1fb3cba0 334
335 maxprefix= 0;
0f4b558c 336 i= 0;
337 while ((arg= *++argv)) {
338 arg_assert(*arg++ == '!');
339 arg_assert(i <= MAXMECHS);
340 mechs[i]= find_mech(arg);
341 cdebug(i,"encsetup");
342
343 argv_save= argv;
b18a1d7b 344 mechs[i]->encsetup(&md_out[i], &maxprefix, &maxsuffix);
0f4b558c 345
346 argv_done= argv;
347 argv= argv_save;
348 cdebug(i,"decsetup");
b18a1d7b 349 mechs[i]->decsetup(&md_in[i]);
0f4b558c 350
351 assert(argv == argv_done);
352
353 i++;
09966b49 354 }
0f4b558c 355 n_mechs= i;
1fb3cba0 356
357 if (maxprefix<1) maxprefix= 1;
358 if (maxsuffix<1) maxsuffix= 1;
359 buffer_size= mtu2 + maxprefix + maxsuffix;
360 buf_in.base= xmalloc(buffer_size);
361 buf_out.base= xmalloc(buffer_size);
362 accum_avail= mtu2 + 1;
363 accum_buf= xmalloc(accum_avail);
364
365 alarm(timeout);
366
367 pollfds[0].fd= public_local_fd;
368 pollfds[0].events= POLLIN;
369 pollfds[1].fd= private_out_fd;
370 for (;;) {
371 pollfds[1].events= public_remote_specd ? POLLIN : 0;
372 pollfds[0].revents= 0;
373 pollfds[1].revents= 0;
374
375 if (keepalive) {
376 tnow= now();
9d4e63db 377 if (tnow >= nextsendka && public_remote_specd) sendpacket("\300",1);
1fb3cba0 378 polltimeout= (nextsendka - tnow)*1000;
379 } else {
380 polltimeout= -1;
381 }
382
383 r= poll(pollfds,2,polltimeout);
384 if (!r) continue;
385 if (r==-1 && errno==EINTR) continue;
386 if (r==-1) sysfail("poll");
387
9d4e63db 388 if (pollfds[0].revents & (POLLIN|POLLERR)) inbound();
389 if (pollfds[1].revents & (POLLIN|POLLERR)) outbound();
1fb3cba0 390 }
391}