summaryrefslogtreecommitdiff
path: root/ipif/forwarder.c
blob: d92fdd9294dc34842a0d4257895384937e996975 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
/*
 * Encrypting tunnel for userv-ipif tunnels, actual core implementation
 */
/*
 * usage:
 *  udptunnel-forwarder <optchars>
 *                      <public-local-fd> <private-in-fd> <private-out-fd>
 *                      <encdec-keys-fd>
 *                      <mtu> <keepalive> <timeout> <reannounce>
 *                      <public-remote-addr> [<public-remote-port>]
 *                      |<mech1> [<mech1-params> ...]
 *                      |<mech2> [<mech2-params> ...]
 *                      ''
 *
 * Remote addr may '' to mean wait to receive a packet and reply to
 * whereever we get a good packet from first, in which case port
 * should not be specified.
 *
 * <optchars> is zero or more of
 *    w   means generate and write encdec keys, rather than reading them
 *    K   means do crypto debug (use with care!)
 *
 * encdec keys datastream has keys for packets from key datastream
 * writer to reader first, then keys for packets from reader to
 * writer.
 *
 * Every addr or port must be numeric.  There is very little argument checking.
 *
 * Exit status:
 *  SIGALARM   timed out
 *       0     terminated due to outbound packet stream EOF
 *       4     other error
 *       8     system problem
 *      12     usage error
 *      16     bad trouble
 */
/*
 * This file is part of ipif, part of userv-utils
 *
 * Copyright 1996-2013 Ian Jackson <ijackson@chiark.greenend.org.uk>
 * Copyright 1998 David Damerell <damerell@chiark.greenend.org.uk>
 * Copyright 1999,2003
 *    Chancellor Masters and Scholars of the University of Cambridge
 * Copyright 2010 Tony Finch <fanf@dotat.at>
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with userv-utils; if not, see http://www.gnu.org/licenses/.
 */

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/utsname.h>
#include <sys/poll.h>

#include <string.h>
#include <errno.h>
#include <assert.h>
#include <stdlib.h>

#include <unistd.h>
#include <fcntl.h>

#include "forwarder.h"

#define MAXMECHS 10

static size_t buffer_size;
static struct utsname uname_result;

static const char *opt_chars;
static int public_local_fd, private_in_fd, private_out_fd;
static int mtu2, keepalive, timeout, reannounce;
static int public_remote_specd;
static struct sockaddr_in public_remote;
static int encdec_keys_fd, encdec_keys_write, crypto_debug;
static int n_mechs;
static const struct mechanism *mechs[MAXMECHS];

static struct mechdata *md_in[MAXMECHS], *md_out[MAXMECHS];
static int maxprefix, maxsuffix;

static struct buffer buf_in, buf_out;
static unsigned char *accum_buf;
static size_t accum_used, accum_avail;

static time_t nextsendka;

static void cdebug(int mechno /*or -1*/, const char *msg) {
  if (!crypto_debug) return;
  printf("%-8.8s: CRYPTO: %-20s %s\n",
	 uname_result.nodename,
	 mechno >= 0 ? mechs[mechno]->name : "",
	 msg);
}

static void cdebughex(int mechno /*or -1*/, const char *msg, const void *ptr,
		      size_t sz, size_t skipbefore,
		      int spc_offset, int dot_offset) {
  const unsigned char *p;
  size_t i;
  unsigned j= dot_offset;
  
  if (!crypto_debug) return;
  printf("%-8.8s: CRYPTO: %-20s %-10s",
	 uname_result.nodename,
	 mechno >= 0 ? mechs[mechno]->name : "",
	 msg);

  for (i=0; i<spc_offset; i++, j++) fputs(j&3 ? "  " : "   ",stdout);
  for (i=0; i<skipbefore; i++, j++) fputs(j&3 ? ".." : " ..",stdout);
  for (i=0, p=ptr; i<sz; i++, j++, p++) printf(j&3 ? "%02x" : " %02x",*p);

  fputc('\n',stdout);
}

static void cdebugbuf(int mechno /*or -1*/, const char *msg,
		      const struct buffer *buf, int spc_offset, int dot_offset) {
  cdebughex(mechno, msg, buf->start, buf->size, buf->start - buf->base,
	    spc_offset, dot_offset);
}

void get_random(void *ptr, size_t sz) {
  static FILE *randfile;

  size_t r;

  if (!randfile) {
    randfile= fopen("/dev/urandom","rb");
    if (!randfile && errno==ENOENT) randfile= fopen("/dev/random","rb");
    if (!randfile) sysfail("open random number generator");
  }

  r= fread(ptr,1,sz,randfile);
  if (r != sz)
    (ferror(randfile) ? sysfail : fail)("cannot read random number generator");

  cdebughex(-1, "get_random", ptr, sz, 0,0,0);
}

void random_key(void *ptr, size_t sz) {
  if (encdec_keys_write) {
    get_random(ptr,sz);
    write_must(encdec_keys_fd,ptr,sz,"write keys datastream");
  } else {
    read_must(encdec_keys_fd,ptr,sz,"read keys datastream");
    cdebughex(-1, "random_key", ptr, sz, 0,0,0);
  }
}


static void setnonblock(int fd, int nonblock) {
  int r;
  
  r= fcntl(fd,F_GETFL);
  if (r==-1) sysfail("fcntl F_GETFL");
  r= fcntl(fd,F_SETFL, nonblock ? r|O_NONBLOCK : r&~O_NONBLOCK);
  if (r==-1) sysfail("fcntl F_SETFL");
}

static const struct mechanism *find_mech(const char *name) {
  const struct mechanism *mech, *const *mechlist;

  for (mechlist= mechanismlists;
       *mechlist;
       mechlist++)
    for (mech= *mechlist; mech->name; mech++)
      if (!strcmp(mech->name,name)) return mech;

  fprintf(stderr,"%s: unknown mechanism: %s\n",programid,name);
  exit(4);
}

static void inbound(void) {
  static int any_recvd;
  static time_t nextreann;
  static unsigned long npackets, nbytes;
  
  struct sockaddr_in this_saddr;
  size_t this_saddrlen;
  int r, i, different;
  const char *emsg;

  buf_in.start= buf_in.base+1;
  buf_in.size= buffer_size-2;
  
  setnonblock(public_local_fd,1);
  this_saddrlen= sizeof(this_saddr);
  r= recvfrom(public_local_fd, buf_in.start, buf_in.size, 0,
	      &this_saddr, &this_saddrlen);
  if (!r) { diag("empty ciphertext"); return; }

  if (r<0) {
    if (errno != EAGAIN && errno != EINTR) { sysdiag("receive"); sleep(1); }
    return;
  }
  if (this_saddr.sin_family != AF_INET) {
    fprintf(stderr,"%s: received unknown AF %lu\n",
	    programid, (unsigned long)this_saddr.sin_family);
    return;
  }
  assert(this_saddrlen == sizeof(this_saddr));

  assert(r <= buf_in.size);
  buf_in.size= r;
  cdebugbuf(-1, "decode", &buf_in, 3,0);
  for (i=n_mechs-1; i>=0; i--) {
    emsg= mechs[i]->decode(md_in[i],&buf_in);
    if (emsg) {
      if (*emsg)
	fprintf(stderr, "%s: bad packet: %s: %s\n",
		programid, mechs[i]->name, emsg);
      else
	cdebug(i,"silently discarded");
      return;
    }
    cdebugbuf(i, "decode", &buf_in, 3,0);
  }

  npackets++;
  nbytes += buf_in.size;
  alarm(timeout);

  different= (!public_remote_specd ||
	      public_remote.sin_addr.s_addr != this_saddr.sin_addr.s_addr ||
	      public_remote.sin_port != this_saddr.sin_port);

  if (different) {

    if (public_remote_specd==2) {
      fprintf(stderr, "%s: packet from unexpected sender %s:%lu\n",
	      programid, inet_ntoa(this_saddr.sin_addr),
	      (unsigned long)ntohs(this_saddr.sin_port));
      return;
    }

    fprintf(stderr, "%s: tunnel open with peer %s:%lu\n",
	    programid, inet_ntoa(this_saddr.sin_addr),
	    (unsigned long)ntohs(this_saddr.sin_port));
    nextsendka= now();
    public_remote_specd= 1;
    memcpy(&public_remote,&this_saddr,sizeof(public_remote));

  } else if (!any_recvd) {

    diag("tunnel open");

  } else if (reannounce && now() >= nextreann) {

    fprintf(stderr, "%s: tunnel still open: received %lu packets, %lu bytes\n",
	    programid, npackets, nbytes);

  } else {

    goto no_set_reann; /* only reset this if we don't print a message. */

  }

  if (reannounce)
    nextreann= now() + reannounce;
  
no_set_reann:

  any_recvd= 1;

  if (!buf_in.size || *buf_in.start != 0300) {
    *--buf_in.start= 0300;
    buf_in.size++;
  }
  if (buf_in.start[buf_in.size-1] != 0300) {
    buf_in.start[buf_in.size++]= 0300;
  }

  setnonblock(private_in_fd,0);
  write_must(private_in_fd, buf_in.start, buf_in.size, "write down");
}

static void sendpacket(const unsigned char *message, size_t size) {
  int i, r;
  
  buf_out.start= buf_out.base+maxprefix;
  buf_out.size= size;
  memcpy(buf_out.start, message, size);

  nextsendka= now() + keepalive;

  cdebugbuf(-1, "encode", &buf_out, 4,0);
  for (i=0; i<n_mechs; i++) {
    mechs[i]->encode(md_out[i],&buf_out);
    cdebugbuf(i, "encode", &buf_out, 4,0);
  }
  assert(public_remote_specd);
  
  setnonblock(public_local_fd,1);
  for (;;) {
    r= sendto(public_local_fd, buf_out.start, buf_out.size, 0,
	      &public_remote, sizeof(public_remote));
    if (r == buf_out.size) break;
    if (r >= 0) { diag("unexpected short send"); return; }
    if (errno != EINTR) { sysdiag("send"); return; }
  }
}

static void outbound(void) {
  int r;
  unsigned char *after_eaten, *delim;
  size_t this_packet;
  
  setnonblock(private_out_fd,1);

  for (;;) {
    r= read(private_out_fd, accum_buf + accum_used, accum_avail - accum_used);
    if (!r) { diag("outbound datastream closed, quitting"); exit(0); }
    if (r<0) {
      if (errno == EAGAIN) return;
      if (errno == EINTR) continue;
    }
    accum_used += r;
    assert(accum_used<=accum_avail);

    after_eaten= accum_buf;
    while ((delim= memchr(after_eaten, 0300, accum_used))) {
      this_packet= delim - after_eaten;
      if (this_packet) sendpacket(after_eaten, this_packet);
      accum_used -= this_packet+1;
      after_eaten = delim+1;
    }
    memmove(accum_buf, after_eaten, accum_used);
    
    if (accum_used == accum_avail) {
      diag("missing interpacket delimiter in output datastream");
      accum_used= 0;
    }
  }
}

int main(int argc, const char *const *const argv_in) {
  const char *arg;
  const char *const *argv_save;
  const char *const *argv_done;
  struct pollfd pollfds[2];
  int i, polltimeout, r;
  time_t tnow;

  argv= argv_in;

  if (uname(&uname_result)) { perror(PROGRAM ": uname failed"); exit(16); }
  sprintf(programid, PROGRAM ": %.*s", SYS_NMLN, uname_result.nodename);

  opt_chars= getarg_string();
  encdec_keys_write= !!strchr(opt_chars,'w');
  crypto_debug= !!strchr(opt_chars,'K');

  public_local_fd= getarg_ulong();
  private_in_fd= getarg_ulong();
  private_out_fd= getarg_ulong();
  encdec_keys_fd= getarg_ulong();

  mtu2= getarg_ulong() * 2;
  keepalive= getarg_ulong();
  timeout= getarg_ulong();
  reannounce= getarg_ulong();
  
  arg= getarg_string();
  if (*arg) {
    public_remote_specd= 1;
    public_remote.sin_family= AF_INET;
    arg_assert(inet_aton(arg,&public_remote.sin_addr));
    public_remote.sin_port= htons(getarg_ulong());
  }

  if (crypto_debug) {
    diag("crypto debugging enabled!");
    setvbuf(stdout,0,_IOLBF,0);
  }

  maxprefix= 0;
  i= 0;
  while ((arg= *++argv)) {
    arg_assert(*arg++ == '|');
    arg_assert(i <= MAXMECHS);
    mechs[i]= find_mech(arg);

    cdebug(i,"writer->reader setup");
    argv_save= argv;

    if (encdec_keys_write)
      mechs[i]->encsetup(&md_out[i], &maxprefix, &maxsuffix);
    else
      mechs[i]->decsetup(&md_in[i]);

    argv_done= argv;
    argv= argv_save;
    cdebug(i,"reader->writer setup");

    if (encdec_keys_write)
      mechs[i]->decsetup(&md_in[i]);
    else
      mechs[i]->encsetup(&md_out[i], &maxprefix, &maxsuffix);

    assert(argv == argv_done);
    
    i++;
  }
  n_mechs= i;

  if (maxprefix<1) maxprefix= 1;
  if (maxsuffix<1) maxsuffix= 1;
  buffer_size= mtu2 + maxprefix + maxsuffix;
  buf_in.base= xmalloc(buffer_size);
  buf_out.base= xmalloc(buffer_size);
  accum_avail= mtu2 + 1;
  accum_buf= xmalloc(accum_avail);

  alarm(timeout);

  pollfds[0].fd= public_local_fd;
  pollfds[0].events= POLLIN;
  pollfds[1].fd= private_out_fd;
  for (;;) {
    pollfds[1].events= public_remote_specd ? POLLIN : 0;
    pollfds[0].revents= 0;
    pollfds[1].revents= 0;

    if (keepalive) {
      tnow= now();
      if (tnow >= nextsendka && public_remote_specd)
	sendpacket((unsigned char*)"\300",1);
      polltimeout= (nextsendka - tnow)*1000;
    } else {
      polltimeout= -1;
    }
    
    r= poll(pollfds,2,polltimeout);
    if (!r) continue;
    if (r==-1 && errno==EINTR) continue;
    if (r==-1) sysfail("poll");

    if (pollfds[0].revents & (POLLIN|POLLERR)) inbound();
    if (pollfds[1].revents & (POLLIN|POLLERR)) outbound();
  }
}