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