chiark / gitweb /
crypto debugging, and several bugfixes
[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  * 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
47 #include "forwarder.h"
48
49 #define MAXMECHS 10
50
51 static size_t buffer_size;
52 static struct utsname uname_result;
53
54 static const char *opt_chars;
55 static int public_local_fd, private_in_fd, private_out_fd;
56 static int mtu2, keepalive, timeout;
57 static int public_remote_specd;
58 static struct sockaddr_in public_remote;
59 static int encdec_keys_fd, encdec_keys_write, crypto_debug;
60 static int n_mechs;
61 static const struct mechanism *mechs[MAXMECHS];
62
63 static struct mechdata *md_in[MAXMECHS], *md_out[MAXMECHS];
64 static size_t maxprefix, maxsuffix;
65
66 static struct buffer buf_in, buf_out;
67 static unsigned char *accum_buf;
68 static size_t accum_used, accum_avail;
69
70 static time_t nextsendka;
71
72 static void cdebug(int mechno /*or -1*/, const char *msg) {
73   if (!crypto_debug) return;
74   printf("%s: CRYPTO: %-20s %s\n",
75          programid,
76          mechno >= 0 ? mechs[mechno]->name : "",
77          msg);
78 }
79
80 static 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) {
83   const unsigned char *p;
84   size_t i;
85   unsigned j= dot_offset;
86   
87   if (!crypto_debug) return;
88   printf("%-8.8s: CRYPTO: %-20s %-10s",
89          uname_result.nodename,
90          mechno >= 0 ? mechs[mechno]->name : "",
91          msg);
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
97   fputc('\n',stdout);
98 }
99
100 static 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
106 void 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);
118   if (r != sz)
119     (ferror(randfile) ? sysfail : fail)("cannot read random number generator");
120
121   cdebughex(-1, "get_random", ptr, sz, 0,0,0);
122 }
123
124 void 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");
130   }
131 }
132
133
134 static 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
143 static const struct mechanism *find_mech(const char *name) {
144   const struct mechanism *mech, *const *mechlist;
145
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
156 static 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
163   buf_in.start= buf_in.base+1;
164   buf_in.size= buffer_size-2;
165   
166   setnonblock(public_local_fd,1);
167   this_saddrlen= sizeof(this_saddr);
168   r= recvfrom(public_local_fd, buf_in.start, buf_in.size, 0,
169               &this_saddr, &this_saddrlen);
170   if (!r) { diag("empty ciphertext"); return; }
171
172   if (r<0) {
173     if (errno != EAGAIN && errno != EINTR) { sysdiag("receive"); sleep(1); }
174     return;
175   }
176   if (this_saddr.sin_family != AF_INET) {
177     fprintf(stderr,"%s: received unknown AF %lu\n",
178             programid, (unsigned long)this_saddr.sin_family);
179     return;
180   }
181   assert(this_saddrlen == sizeof(this_saddr));
182
183   assert(r <= buf_in.size);
184   buf_in.size= r;
185   cdebugbuf(-1, "decode", &buf_in, 3,0);
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     }
192     cdebugbuf(i, "decode", &buf_in, 3,0);
193   }
194
195   alarm(timeout);
196
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);
200
201   if (different) {
202
203     if (public_remote_specd==2) {
204       fprintf(stderr, "%s: packet from unexpected sender %s:%lu\n",
205               programid, inet_ntoa(this_saddr.sin_addr),
206               (unsigned long)ntohs(this_saddr.sin_port));
207       return;
208     }
209
210     fprintf(stderr, "%s: tunnel open with peer %s:%lu\n",
211             programid, inet_ntoa(this_saddr.sin_addr),
212             (unsigned long)ntohs(this_saddr.sin_port));
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;
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   }
232
233   setnonblock(private_in_fd,0);
234   write_must(private_in_fd, buf_in.start, buf_in.size, "write down");
235 }
236
237 static 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
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   }
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
263 static 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;
283       if (this_packet) sendpacket(after_eaten, this_packet);
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
296 int main(int argc, const char *const *const argv_in) {
297   const char *arg;
298   const char *const *argv_save;
299   const char *const *argv_done;
300   struct pollfd pollfds[2];
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);
308
309   opt_chars= getarg_string();
310   encdec_keys_write= !!strchr(opt_chars,'w');
311   crypto_debug= !!strchr(opt_chars,'K');
312
313   public_local_fd= getarg_ulong();
314   private_in_fd= getarg_ulong();
315   private_out_fd= getarg_ulong();
316   encdec_keys_fd= getarg_ulong();
317
318   mtu2= getarg_ulong() * 2;
319   keepalive= getarg_ulong();
320   timeout= getarg_ulong();
321   
322   arg= getarg_string();
323   if (*arg) {
324     public_remote_specd= 1;
325     public_remote.sin_family= AF_INET;
326     arg_assert(inet_aton(arg,&public_remote.sin_addr));
327     public_remote.sin_port= htons(getarg_ulong());
328   }
329
330   if (crypto_debug) {
331     diag("crypto debugging enabled!");
332     setvbuf(stdout,0,_IOLBF,0);
333   }
334
335   maxprefix= 0;
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;
344     mechs[i]->encsetup(&md_in[i], &maxprefix, &maxsuffix);
345
346     argv_done= argv;
347     argv= argv_save;
348     cdebug(i,"decsetup");
349     mechs[i]->decsetup(&md_out[i]);
350
351     assert(argv == argv_done);
352     
353     i++;
354   }
355   n_mechs= i;
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();
377       if (tnow >= nextsendka && public_remote_specd) sendpacket("\300",1);
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
388     if (pollfds[0].revents & (POLLIN|POLLERR)) inbound();
389     if (pollfds[1].revents & (POLLIN|POLLERR)) outbound();
390   }
391 }