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