chiark / gitweb /
server/admin.h: Consolidate address construction during resolution.
[tripe] / proxy / tripe-mitm.c
1 /* -*-c-*-
2  *
3  * An evil proxy for TrIPE
4  *
5  * (c) 2001 Straylight/Edgeware
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of Trivial IP Encryption (TrIPE).
11  *
12  * TrIPE is free software: you can redistribute it and/or modify it under
13  * the terms of the GNU General Public License as published by the Free
14  * Software Foundation; either version 3 of the License, or (at your
15  * option) any later version.
16  *
17  * TrIPE is distributed in the hope that it will be useful, but WITHOUT
18  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
20  * for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with TrIPE.  If not, see <https://www.gnu.org/licenses/>.
24  */
25
26 /*----- Header files ------------------------------------------------------*/
27
28 #include "config.h"
29
30 #include <assert.h>
31 #include <errno.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <time.h>
36
37 #include <sys/types.h>
38 #include <sys/time.h>
39 #include <unistd.h>
40 #include <fcntl.h>
41
42 #include <sys/socket.h>
43 #include <netinet/in.h>
44 #include <arpa/inet.h>
45 #include <netdb.h>
46
47 #include <mLib/alloc.h>
48 #include <mLib/dstr.h>
49 #include <mLib/fdflags.h>
50 #include <mLib/mdwopt.h>
51 #include <mLib/quis.h>
52 #include <mLib/report.h>
53 #include <mLib/sel.h>
54 #include <mLib/sub.h>
55 #include <mLib/tv.h>
56
57 #include <catacomb/buf.h>
58
59 #include <catacomb/key.h>
60
61 #include <catacomb/mp.h>
62 #include <catacomb/mprand.h>
63 #include <catacomb/dh.h>
64
65 #include <catacomb/chacha20.h>
66 #include <catacomb/noise.h>
67 #include <catacomb/rand.h>
68
69 #include "util.h"
70
71 /*----- Data structures ---------------------------------------------------*/
72
73 typedef struct peer {
74   sel_file sf;
75   const char *name;
76   struct filter *f;
77 } peer;
78
79 typedef struct filter {
80   struct filter *next;
81   peer *p_from, *p_to;
82   void (*func)(struct filter */*f*/, const octet */*buf*/, size_t /*sz*/);
83   void *state;
84 } filter;
85
86 typedef struct qnode {
87   octet *buf;
88   size_t sz;
89 } qnode;
90
91 /*----- Static variables --------------------------------------------------*/
92
93 #define PKBUFSZ 65536
94
95 static sel_state sel;
96 static peer peers[2];
97 static unsigned npeer = 0;
98 static key_file keys;
99 static grand *rng;
100 static const char *delim = ":";
101
102 #define PASS(f, buf, sz) ((f) ? (f)->func((f), (buf), (sz)) : (void)0)
103 #define RND(i) (rng->ops->range(rng, (i)))
104
105 /*----- Peer management ---------------------------------------------------*/
106
107 static void dopacket(int fd, unsigned mode, void *vv)
108 {
109   octet buf[PKBUFSZ];
110   peer *p = vv;
111   int r = read(fd, buf, sizeof(buf));
112   if (r >= 0) {
113     printf("recv from `%s'\n", p->name);
114     PASS(p->f, buf, r);
115   }
116 }
117
118 static void addpeer_common(const char *cmd, int af, unsigned ac, char **av)
119 {
120   struct addrinfo aihint = { 0 }, *ai0, *ai1;
121   int len = PKBUFSZ, yes = 1;
122   int err;
123   peer *p;
124   int fd;
125
126   if (ac != 4) die(1, "syntax: %s:NAME:PORT:ADDR:PORT", cmd);
127   if (!key_bytag(&keys, av[0])) die(1, "no key named `%s'", av[0]);
128   p = &peers[npeer++];
129   p->name = xstrdup(av[0]);
130   aihint.ai_family = af;
131   aihint.ai_socktype = SOCK_DGRAM;
132   aihint.ai_flags = AI_ADDRCONFIG;
133   if ((err = getaddrinfo(av[2], av[3], &aihint, &ai1)) != 0)
134     die(1, "getaddrinfo(`%s', `%s'): %s", av[2], av[3], gai_strerror(err));
135   aihint.ai_family = ai1->ai_family;
136   aihint.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
137   if ((err = getaddrinfo(0, av[1], &aihint, &ai0)) != 0)
138     die(1, "getaddrinfo(passive, `%s'): %s", av[1], gai_strerror(err));
139   if ((fd = socket(ai1->ai_family, SOCK_DGRAM, ai1->ai_protocol)) < 0)
140     die(1, "socket: %s", strerror(errno));
141   if (ai1->ai_family == AF_INET6) {
142     if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &yes, sizeof(yes)))
143       die(1, "setsockopt: %s", strerror(errno));
144   }
145   if (bind(fd, ai0->ai_addr, ai0->ai_addrlen))
146     die(1, "bind: %s", strerror(errno));
147   if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len)) ||
148       setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &len, sizeof(len)))
149     die(1, "setsockopt: %s", strerror(errno));
150   if (connect(fd, ai1->ai_addr, ai1->ai_addrlen))
151     die(1, "connect: %s", strerror(errno));
152   sel_initfile(&sel, &p->sf, fd, SEL_READ, dopacket, p);
153   sel_addfile(&p->sf);
154   freeaddrinfo(ai0); freeaddrinfo(ai1);
155 }
156
157 static void addpeer(unsigned ac, char **av)
158   { addpeer_common("peer", AF_UNSPEC, ac, av); }
159 static void addpeer4(unsigned ac, char **av)
160   { addpeer_common("peer4", AF_INET, ac, av); }
161 static void addpeer6(unsigned ac, char **av)
162   { addpeer_common("peer6", AF_INET6, ac, av); }
163
164 /*----- Fork filter -------------------------------------------------------*/
165
166 typedef struct forknode {
167   struct forknode *next;
168   filter *f;
169 } forknode;
170
171 typedef struct forkfilt {
172   const char *name;
173   forknode *fn;
174 } forkfilt;
175
176 static void dofork(filter *f, const octet *buf, size_t sz)
177 {
178   forkfilt *ff = f->state;
179   forknode *fn;
180   unsigned i = 0;
181
182   ff = f->state;
183   for (fn = ff->fn; fn; fn = fn->next) {
184     printf("fork branch %u of fork `%s'\n", i++, ff->name);
185     PASS(fn->f, buf, sz);
186   }
187   printf("fork branch %u of fork `%s'\n", i++, ff->name);
188   PASS(f->next, buf, sz);
189 }
190
191 static void addfork(filter *f, unsigned ac, char **av)
192 {
193   forkfilt *ff;
194   if (ac != 1) die(1, "syntax: filt:fork:NAME");
195   ff = CREATE(forkfilt);
196   ff->name = xstrdup(av[0]);
197   ff->fn = 0;
198   f->func = dofork;
199   f->state = ff;
200 }
201
202 static void nextfork(unsigned ac, char **av)
203 {
204   unsigned i, j;
205   filter *f;
206   forkfilt *ff;
207   forknode *fn, **ffn;
208   peer *p;
209
210   if (ac < 1) die(1, "syntax: next:NAME:...");
211   for (i = 0; i < 2; i++) {
212     p = &peers[i];
213     for (f = p->f; f; f = f->next) {
214       if (f->func != dofork) continue;
215       ff = f->state;
216       for (j = 0; j < ac; j++)
217         if (strcmp(av[j], ff->name) == 0) goto match;
218       continue;
219     match:
220       fn = CREATE(forknode);
221       for (ffn = &ff->fn; *ffn; ffn = &(*ffn)->next);
222       fn->f = f->next;
223       f->next = 0;
224       fn->next = 0;
225       *ffn = fn;
226     }
227   }
228 }
229
230 /*----- Corrupt filter ----------------------------------------------------*/
231
232 typedef struct corrupt {
233   unsigned p_corrupt;
234 } corrupt;
235
236 static void docorrupt(filter *f, const octet *buf, size_t sz)
237 {
238   corrupt *c = f->state;
239   octet b[PKBUFSZ];
240   memcpy(b, buf, sz);
241
242   while (!RND(c->p_corrupt)) {
243     puts("corrupt packet");
244     b[RND(sz)] ^= RND(256);
245   }
246   PASS(f->next, b, sz);
247 }
248
249 static void addcorrupt(filter *f, unsigned ac, char **av)
250 {
251   corrupt *c;
252   if (ac > 1) die(1, "syntax: filt:corrupt[:P-CORRUPT]");
253   c = CREATE(corrupt);
254   if (ac > 0) c->p_corrupt = atoi(av[0]);
255   else c->p_corrupt = 5;
256   f->state = c;
257   f->func = docorrupt;
258 }
259
260 /*----- Drop filter -------------------------------------------------------*/
261
262 typedef struct drop {
263   unsigned p_drop;
264 } drop;
265
266 static void dodrop(filter *f, const octet *buf, size_t sz)
267 {
268   drop *d = f->state;
269
270   if (!RND(d->p_drop)) puts("drop packet");
271   else PASS(f->next, buf, sz);
272 }
273
274 static void adddrop(filter *f, unsigned ac, char **av)
275 {
276   drop *d;
277   if (ac > 1) die(1, "syntax: filt:drop[:P-DROP]");
278   d = CREATE(drop);
279   if (ac > 0) d->p_drop = atoi(av[0]);
280   else d->p_drop = 5;
281   f->state = d;
282   f->func = dodrop;
283 }
284
285 /*----- Delay filter ------------------------------------------------------*/
286
287 typedef struct delaynode {
288   unsigned flag;
289   sel_timer tm;
290   unsigned i;
291   struct delay *d;
292   octet *buf;
293   size_t sz;
294   unsigned seq;
295 } delaynode;
296
297 typedef struct delay {
298   unsigned max, n;
299   unsigned long t;
300   unsigned p_replay;
301   filter *f;
302   delaynode *q;
303 } delay;
304
305 static void dtimer(struct timeval *tv, void *vv);
306
307 static void dinsert(delaynode *dn)
308 {
309   struct timeval tv;
310   sel_timer *ta, *tb;
311   unsigned long tdelta = RND(dn->d->t);
312   gettimeofday(&tv, 0);
313   TV_ADDL(&tv, &tv, 0, tdelta);
314   assert(!dn->flag);
315   sel_addtimer(&sel, &dn->tm, &tv, dtimer, dn);
316   dn->flag = 1;
317   for (ta = tb = sel.timers; ta; ta = ta->next) {
318     ta = ta->next; if (!ta) break; assert(ta != tb);
319     ta = ta->next; if (!ta) break; assert(ta != tb);
320     tb = tb->next;
321   }
322   printf(" delay %lu usecs", tdelta);
323 }
324
325 static void dsend(delaynode *dn, unsigned force)
326 {
327   delay *d = dn->d;
328   delaynode *ddn;
329   unsigned i;
330
331   fputs(" send...\n", stdout);
332   assert(dn->buf);
333   PASS(d->f->next, dn->buf, dn->sz);
334   fputs("delay ...", stdout);
335   if (!force)
336     dinsert(dn);
337   else {
338     xfree(dn->buf);
339     dn->buf = 0;
340     d->n--;
341     if (dn->i < d->n) {
342       ddn = &d->q[d->n];
343       sel_rmtimer(&ddn->tm);
344       sel_addtimer(&sel, &dn->tm, &ddn->tm.tv, dtimer, dn);
345       dn->flag = 1;
346       dn->buf = ddn->buf;
347       dn->sz = ddn->sz;
348       dn->seq = ddn->seq;
349       ddn->buf = 0;
350       ddn->flag = 0;
351       printf(" move id %u from slot %u to slot %u", ddn->seq, ddn->i, dn->i);
352     }
353     for (i = 0; i < d->n; i++) assert(d->q[i].buf);
354     fputs(" remove", stdout);
355   }
356 }
357
358 static void dtimer(struct timeval *tv, void *vv)
359 {
360   delaynode *dn = vv;
361   printf("delay timer peer `%s' id %u slot %u",
362          dn->d->f->p_from->name, dn->seq, dn->i);
363   dn->flag = 0;
364   dsend(dn, RND(dn->d->p_replay));
365   fputc('\n', stdout);
366 }
367
368 static void dodelay(filter *f, const octet *buf, size_t sz)
369 {
370   delay *d = f->state;
371   delaynode *dn;
372   static unsigned seq = 0;
373
374   fputs("delay", stdout);
375   if (d->n == d->max) {
376     dn = &d->q[RND(d->n)];
377     printf(" force uid %u", dn->seq);
378     sel_rmtimer(&dn->tm);
379     dn->flag = 0;
380     dsend(dn, 1);
381     fputc(';', stdout);
382   }
383   dn = &d->q[d->n++];
384   dn->seq = seq++;
385   printf(" new id %u in slot %u", dn->seq, dn->i);
386   dn->buf = xmalloc(sz);
387   dn->sz = sz;
388   memcpy(dn->buf, buf, sz);
389   dinsert(dn);
390   fputc('\n', stdout);
391 }
392
393 static void adddelay(filter *f, unsigned ac, char **av)
394 {
395   delay *d;
396   unsigned i;
397
398   if (ac < 1 || ac > 3) die(1, "syntax: filt:delay:QLEN[:MILLIS:P-REPLAY]");
399   d = CREATE(delay);
400   d->max = atoi(av[0]);
401   if (ac > 1) d->t = strtoul(av[1], 0, 10);
402   else d->t = 100;
403   d->t *= 1000;
404   if (ac > 2) d->p_replay = atoi(av[2]);
405   else d->p_replay = 20;
406   d->n = 0;
407   d->q = xmalloc(d->max * sizeof(delaynode));
408   d->f = f;
409   f->state = d;
410   f->func = dodelay;
411   for (i = 0; i < d->max; i++) {
412     d->q[i].d = d;
413     d->q[i].i = i;
414     d->q[i].buf = 0;
415     d->q[i].flag = 0;
416   }
417 }
418
419 /*----- Filters -----------------------------------------------------------*/
420
421 static void dosend(filter *f, const octet *buf, size_t sz)
422 {
423   printf("send to `%s'\n", f->p_to->name);
424   DISCARD(write(f->p_to->sf.fd, buf, sz));
425 }
426
427 static void addsend(filter *f, unsigned ac, char **av)
428 {
429   if (ac) die(1, "syntax: filt:send");
430   f->func = dosend;
431 }
432
433 const struct filtab {
434   const char *name;
435   void (*func)(filter */*f*/, unsigned /*ac*/, char **/*av*/);
436 } filtab[] = {
437   { "send",     addsend },
438   { "fork",     addfork },
439   { "delay",    adddelay },
440   { "drop",     adddrop },
441   { "corrupt",  addcorrupt },
442   { 0,          0 }
443 };
444
445 static void dofilter(peer *from, peer *to, unsigned ac, char **av)
446 {
447   filter **ff, *f = CREATE(filter);
448   const struct filtab *ft;
449   if (ac < 1) die(1, "syntax: {l,r,}filt:NAME:...");
450   f->next = 0;
451   f->p_from = from;
452   f->p_to = to;
453   f->state = 0;
454   for (ff = &from->f; *ff; ff = &(*ff)->next);
455   *ff = f;
456   for (ft = filtab; ft->name; ft++)
457     if (strcmp(av[0], ft->name) == 0)
458       { ft->func(f, ac - 1, av + 1); return; }
459   die(1, "unknown filter `%s'", av[0]);
460 }
461
462 /*----- Flooding ----------------------------------------------------------*/
463
464 typedef struct flood {
465   peer *p;
466   unsigned type;
467   size_t sz;
468   unsigned long t;
469   sel_timer tm;
470 } flood;
471
472 static void setflood(flood *f);
473
474 static void floodtimer(struct timeval *tv, void *vv)
475 {
476   flood *f = vv;
477   octet buf[PKBUFSZ];
478   size_t sz;
479
480   sz = RND(f->sz);
481   sz += RND(f->sz);
482   sz += RND(f->sz);
483   sz += RND(f->sz);
484   sz /= 2;
485
486   rng->ops->fill(rng, buf, sz);
487   if (f->type < 0x100) buf[0] = f->type;
488   puts("flood packet");
489   PASS(f->p->f, buf, sz);
490   setflood(f);
491 }
492
493 static void setflood(flood *f)
494 {
495   struct timeval tv;
496   gettimeofday(&tv, 0);
497   TV_ADDL(&tv, &tv, 0, RND(f->t));
498   sel_addtimer(&sel, &f->tm, &tv, floodtimer, f);
499 }
500
501 static void doflood(peer *p, unsigned ac, char **av)
502 {
503   flood *f;
504   if (ac > 3) die(1, "syntax: flood[:TYPE:MILLIS:SIZE]");
505   f = CREATE(flood);
506   f->p = p;
507   if (ac > 0) f->type = strtoul(av[0], 0, 16);
508   else f->type = 0x100;
509   if (ac > 1) f->t = atoi(av[1]);
510   else f->t = 10;
511   if (ac > 2) f->sz = atoi(av[2]);
512   else f->sz = 128;
513   f->t *= 1000;
514   setflood(f);
515 }
516
517 /*----- Configuration commands --------------------------------------------*/
518
519 static void parse(char *p);
520
521 static void addflood(unsigned ac, char **av) {
522   doflood(&peers[0], ac, av);
523   doflood(&peers[1], ac, av);
524 }
525 static void addlflood(unsigned ac, char **av) {
526   doflood(&peers[0], ac, av);
527 }
528 static void addrflood(unsigned ac, char **av) {
529   doflood(&peers[1], ac, av);
530 }
531
532 static void addfilter(unsigned ac, char **av) {
533   dofilter(&peers[0], &peers[1], ac, av);
534   dofilter(&peers[1], &peers[0], ac, av);
535 }
536 static void addlfilter(unsigned ac, char **av) {
537   dofilter(&peers[0], &peers[1], ac, av);
538 }
539 static void addrfilter(unsigned ac, char **av) {
540   dofilter(&peers[1], &peers[0], ac, av);
541 }
542
543 static void include(unsigned ac, char **av)
544 {
545   FILE *fp;
546   dstr d = DSTR_INIT;
547   if (!ac) die(1, "syntax: include:FILE:...");
548   while (*av) {
549     if ((fp = fopen(*av, "r")) == 0)
550       die(1, "fopen `%s': %s", *av, strerror(errno));
551     while (dstr_putline(&d, fp) != EOF) { parse(d.buf); DRESET(&d); }
552     fclose(fp);
553     av++;
554   }
555 }
556
557 const struct cmdtab {
558   const char *name;
559   void (*func)(unsigned /*ac*/, char **/*av*/);
560 } cmdtab[] = {
561   { "peer",     addpeer },
562   { "peer4",    addpeer4 },
563   { "peer6",    addpeer6 },
564   { "include",  include },
565   { "filt",     addfilter },
566   { "lfilt",    addlfilter },
567   { "rfilt",    addrfilter },
568   { "next",     nextfork },
569   { "flood",    addflood },
570   { "lflood",   addlflood },
571   { "rflood",   addrflood },
572   { 0,          0 }
573 };
574
575 #define AVMAX 16
576
577 static void parse(char *p)
578 {
579   char *v[AVMAX];
580   unsigned c = 0;
581   const struct cmdtab *ct;
582
583   p = strtok(p, delim);
584   if (!p || *p == '#') return;
585   do {
586     v[c++] = p;
587     p = strtok(0, delim);
588   } while (p && c < AVMAX - 1);
589   v[c] = 0;
590   for (ct = cmdtab; ct->name; ct++) {
591     if (strcmp(ct->name, v[0]) == 0) {
592       ct->func(c - 1, v + 1);
593       return;
594     }
595   }
596   die(1, "unknown command `%s'", v[0]);
597 }
598
599 /*----- Main driver -------------------------------------------------------*/
600
601 static void version(FILE *fp)
602   { pquis(fp, "$, TrIPE version " VERSION "\n"); }
603
604 static void usage(FILE *fp)
605   { pquis(fp, "Usage: $ [-d CHAR] [-k KEYRING] DIRECTIVE...\n"); }
606
607 static void help(FILE *fp)
608 {
609   version(fp);
610   putc('\n', fp);
611   usage(fp);
612   fputs("\n\
613 Options:\n\
614 \n\
615 -h, --help              Show this help text.\n\
616 -v, --version           Show the version number.\n\
617 -u, --usage             Show terse usage summary.\n\
618 \n\
619 -d, --delimiter=CHAR    Use CHAR rather than `:' as delimiter.\n\
620 -k, --keyring=FILE      Fetch keys from FILE.\n\
621 \n\
622 Directives:\n\
623   peer{,4,6}:NAME:LOCAL-PORT:REMOTE-ADDR:REMOTE-PORT\n\
624   include:FILE\n\
625   {,l,r}filt:FILTER:ARGS:...\n\
626   next:TAG\n\
627   {,l,r}flood:TYPE:MILLIS:SIZE\n\
628 \n\
629 Filters:\n\
630   send\n\
631   fork:TAG\n\
632   delay:QLEN[:MILLIS:P-REPLAY]\n\
633   drop[:P-DROP]\n\
634   corrupt[:P-CORRUPT]\n",
635         fp);
636 }
637
638 int main(int argc, char *argv[])
639 {
640   const char *kfname = "keyring.pub";
641   int i;
642   unsigned f = 0;
643   char buf[32];
644   static octet zero[CHACHA_NONCESZ];
645
646 #define f_bogus 1u
647
648   ego(argv[0]);
649   for (;;) {
650     static const struct option opt[] = {
651       { "help",         0,              0,      'h' },
652       { "version",      0,              0,      'v' },
653       { "usage",        0,              0,      'u' },
654       { "delimiter",    OPTF_ARGREQ,    0,      'd' },
655       { "keyring",      OPTF_ARGREQ,    0,      'k' },
656       { 0,              0,              0,      0 }
657     };
658     if ((i = mdwopt(argc, argv, "hvud:k:", opt, 0, 0, 0)) < 0) break;
659     switch (i) {
660       case 'h': help(stdout); exit(0);
661       case 'v': version(stdout); exit(0);
662       case 'u': usage(stdout); exit(0);
663       case 'd':
664         if (!optarg[0] || optarg[1])
665           die(1, "delimiter must be a single character");
666         delim = optarg;
667         break;
668       case 'k': kfname = optarg; break;
669       default: f |= f_bogus; break;
670     }
671   }
672   if (f & f_bogus) { usage(stderr); exit(1); }
673
674   rand_noisesrc(RAND_GLOBAL, &noise_source);
675   rand_seed(RAND_GLOBAL, 256);
676   rand_get(RAND_GLOBAL, buf, sizeof(buf));
677   rng = chacha20_rand(buf, sizeof(buf), zero);
678   sel_init(&sel);
679   if (key_open(&keys, kfname, KOPEN_READ, key_moan, 0))
680     die(1, "couldn't open `%s': %s", kfname, strerror(errno));
681   for (i = optind; i < argc; i++) parse(argv[i]);
682   if (npeer != 2) die(1, "need two peers");
683   for (;;) {
684     if (sel_select(&sel) && errno != EINTR)
685       die(1, "select failed: %s", strerror(errno));
686   }
687
688 #undef f_bogus
689 }
690
691 /*----- That's all, folks -------------------------------------------------*/