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