chiark / gitweb /
404bad0f10e29ecb7a45f124488207a233a02740
[tripe] / server / tripe.h
1 /* -*-c-*-
2  *
3  * Main header file 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
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * TrIPE is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with TrIPE; if not, write to the Free Software Foundation,
24  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25  */
26
27 #ifndef TRIPE_H
28 #define TRIPE_H
29
30 #ifdef __cplusplus
31   extern "C" {
32 #endif
33
34 /*----- Header files ------------------------------------------------------*/
35
36 #include "config.h"
37
38 #include <assert.h>
39 #include <ctype.h>
40 #include <errno.h>
41 #include <limits.h>
42 #include <signal.h>
43 #include <stdarg.h>
44 #include <stddef.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <time.h>
49
50 #include <sys/types.h>
51 #include <sys/time.h>
52 #include <unistd.h>
53 #include <fcntl.h>
54 #include <sys/stat.h>
55
56 #include <sys/socket.h>
57 #include <sys/un.h>
58 #include <netinet/in.h>
59 #include <arpa/inet.h>
60 #include <netdb.h>
61
62 #include <pwd.h>
63 #include <grp.h>
64
65 #include <mLib/alloc.h>
66 #include <mLib/arena.h>
67 #include <mLib/base64.h>
68 #include <mLib/bres.h>
69 #include <mLib/daemonize.h>
70 #include <mLib/dstr.h>
71 #include <mLib/env.h>
72 #include <mLib/fdflags.h>
73 #include <mLib/fwatch.h>
74 #include <mLib/hash.h>
75 #include <mLib/macros.h>
76 #include <mLib/mdwopt.h>
77 #include <mLib/quis.h>
78 #include <mLib/report.h>
79 #include <mLib/sel.h>
80 #include <mLib/selbuf.h>
81 #include <mLib/sig.h>
82 #include <mLib/str.h>
83 #include <mLib/sub.h>
84 #include <mLib/trace.h>
85 #include <mLib/tv.h>
86 #include <mLib/versioncmp.h>
87
88 #include <catacomb/buf.h>
89
90 #include <catacomb/gcipher.h>
91 #include <catacomb/gmac.h>
92 #include <catacomb/grand.h>
93 #include <catacomb/key.h>
94 #include <catacomb/paranoia.h>
95
96 #include <catacomb/noise.h>
97 #include <catacomb/rand.h>
98
99 #include <catacomb/mp.h>
100 #include <catacomb/mprand.h>
101 #include <catacomb/dh.h>
102 #include <catacomb/ec.h>
103 #include <catacomb/ec-keys.h>
104 #include <catacomb/group.h>
105
106 #include "protocol.h"
107 #include "slip.h"
108 #include "util.h"
109
110 #undef sun
111
112 /*----- Magic numbers -----------------------------------------------------*/
113
114 /* --- Trace flags --- */
115
116 #define T_TUNNEL 1u
117 #define T_PEER 2u
118 #define T_PACKET 4u
119 #define T_ADMIN 8u
120 #define T_CRYPTO 16u
121 #define T_KEYSET 32u
122 #define T_KEYEXCH 64u
123 #define T_KEYMGMT 128u
124 #define T_CHAL 256u
125
126 #define T_ALL 511u
127
128 /* --- Units --- */
129
130 #define SEC(n) (n##u)
131 #define MIN(n) (n##u * 60u)
132 #define MEG(n) (n##ul * 1024ul * 1024ul)
133
134 /* --- Other things --- */
135
136 #define PKBUFSZ 65536
137
138 /*----- Cipher selections -------------------------------------------------*/
139
140 typedef struct algswitch {
141   const gccipher *c;                    /* Symmetric encryption scheme */
142   const gccipher *mgf;                  /* Mask-generation function */
143   const gchash *h;                      /* Hash function */
144   const gcmac *m;                       /* Message authentication code */
145   size_t hashsz;                        /* Hash output size */
146   size_t tagsz;                         /* Length to truncate MAC tags */
147   size_t expsz;                         /* Size of data to process */
148   size_t cksz, mksz;                    /* Key lengths for @c@ and @m@ */
149 } algswitch;
150
151 extern algswitch algs;
152
153 #define MAXHASHSZ 64                    /* Largest possible hash size */
154
155 #define HASH_STRING(h, s) GH_HASH((h), (s), sizeof(s))
156
157 /*----- Data structures ---------------------------------------------------*/
158
159 /* --- Socket addresses --- *
160  *
161  * A magic union of supported socket addresses.
162  */
163
164 typedef union addr {
165   struct sockaddr sa;
166   struct sockaddr_in sin;
167 } addr;
168
169 /* --- Mapping keyed on addresses --- */
170
171 typedef struct addrmap {
172   hash_table t;
173   size_t load;
174 } addrmap;
175
176 typedef struct addrmap_base {
177   hash_base b;
178   addr a;
179 } addrmap_base;
180
181 /* --- Sequence number checking --- */
182
183 typedef struct seqwin {
184   uint32 seq;                           /* First acceptable input sequence */
185   uint32 win;                           /* Window of acceptable numbers */
186 } seqwin;
187
188 #define SEQ_WINSZ 32                    /* Bits in sequence number window */
189
190 /* --- A symmetric keyset --- *
191  *
192  * A keyset contains a set of symmetric keys for encrypting and decrypting
193  * packets.  Keysets are stored in a list, sorted in reverse order of
194  * creation, so that the most recent keyset (the one most likely to be used)
195  * is first.
196  *
197  * Each keyset has a time limit and a data limit.  The keyset is destroyed
198  * when either it has existed for too long, or it has been used to encrypt
199  * too much data.  New key exchanges are triggered when keys are close to
200  * expiry.
201  */
202
203 typedef struct keyset {
204   struct keyset *next;                  /* Next active keyset in the list */
205   unsigned ref;                         /* Reference count for keyset */
206   struct peer *p;                       /* Pointer to peer structure */
207   time_t t_exp;                         /* Expiry time for this keyset */
208   unsigned long sz_exp, sz_regen;       /* Data limits for the keyset */
209   T( unsigned seq; )                    /* Sequence number for tracing */
210   unsigned f;                           /* Various useful flags */
211   gcipher *cin, *cout;                  /* Keyset ciphers for encryption */
212   size_t tagsz;                         /* Length to truncate MAC tags */
213   gmac *min, *mout;                     /* Keyset MACs for integrity */
214   uint32 oseq;                          /* Outbound sequence number */
215   seqwin iseq;                          /* Inbound sequence number */
216 } keyset;
217
218 #define KSF_LISTEN 1u                   /* Don't encrypt packets yet */
219 #define KSF_LINK 2u                     /* Key is in a linked list */
220
221 #define KSERR_REGEN -1                  /* Regenerate keys */
222 #define KSERR_NOKEYS -2                 /* No keys left */
223 #define KSERR_DECRYPT -3                /* Unable to decrypt message */
224
225 /* --- Key exchange --- *
226  *
227  * TrIPE uses the Wrestlers Protocol for its key exchange.  The Wrestlers
228  * Protocol has a number of desirable features (e.g., perfect forward
229  * secrecy, and zero-knowledge authentication) which make it attractive for
230  * use in TrIPE.  The Wrestlers Protocol was designed by Mark Wooding and
231  * Clive Jones.
232  */
233
234 #define KX_NCHAL 16u
235
236 typedef struct kxchal {
237   struct keyexch *kx;                   /* Pointer back to key exchange */
238   ge *c;                                /* Responder's challenge */
239   ge *r;                                /* My reply to the challenge */
240   keyset *ks;                           /* Pointer to temporary keyset */
241   unsigned f;                           /* Various useful flags */
242   sel_timer t;                          /* Response timer for challenge */
243   octet hc[MAXHASHSZ];                  /* Hash of his challenge */
244   octet ck[MAXHASHSZ];                  /* His magical check value */
245   octet hswrq_in[MAXHASHSZ];            /* Inbound switch request message */
246   octet hswok_in[MAXHASHSZ];            /* Inbound switch confirmation */
247   octet hswrq_out[MAXHASHSZ];           /* Outbound switch request message */
248   octet hswok_out[MAXHASHSZ];           /* Outbound switch confirmation */
249 } kxchal;
250
251 typedef struct keyexch {
252   struct peer *p;                       /* Pointer back to the peer */
253   keyset **ks;                          /* Peer's list of keysets */
254   unsigned f;                           /* Various useful flags */
255   unsigned s;                           /* Current state in exchange */
256   sel_timer t;                          /* Timer for next exchange */
257   ge *kpub;                             /* Peer's public key */
258   time_t texp_kpub;                     /* Expiry time for public key */
259   mp *alpha;                            /* My temporary secret */
260   ge *c;                                /* My challenge */
261   ge *rx;                               /* The expected response */
262   unsigned nr;                          /* Number of extant responses */
263   time_t t_valid;                       /* When this exchange goes bad */
264   octet hc[MAXHASHSZ];                  /* Hash of my challenge */
265   kxchal *r[KX_NCHAL];                  /* Array of challenges */
266 } keyexch;
267
268 #define KXF_TIMER 1u                    /* Waiting for a timer to go off */
269 #define KXF_DEAD 2u                     /* The key-exchanger isn't up */
270 #define KXF_PUBKEY 4u                   /* Key exchanger has a public key */
271 #define KXF_CORK 8u                     /* Don't send anything yet */
272
273 enum {
274   KXS_DEAD,                             /* Uninitialized state (magical) */
275   KXS_CHAL,                             /* Main answer-challenges state */
276   KXS_COMMIT,                           /* Committed: send switch request */
277   KXS_SWITCH                            /* Switched: send confirmation */
278 };
279
280 /* --- Tunnel structure --- *
281  *
282  * Used to maintain system-specific information about the tunnel interface.
283  */
284
285 typedef struct tunnel tunnel;
286 struct peer;
287
288 typedef struct tunnel_ops {
289   const char *name;                     /* Name of this tunnel driver */
290   void (*init)(void);                   /* Initializes the system */
291   int (*open)(char **/*ifn*/);          /* Open tunnel and report ifname */
292   tunnel *(*create)(struct peer */*p*/, int /*fd*/, char **/*ifn*/);
293                                         /* Initializes a new tunnel */
294   void (*setifname)(tunnel */*t*/, const char */*ifn*/);
295                                         /*  Notifies ifname change */
296   void (*inject)(tunnel */*t*/, buf */*b*/); /* Sends packet through if */
297   void (*destroy)(tunnel */*t*/);       /* Destroys a tunnel */
298 } tunnel_ops;
299
300 #ifndef TUN_INTERNALS
301 struct tunnel { const tunnel_ops *ops; };
302 #endif
303
304 /* --- Peer statistics --- *
305  *
306  * Contains various interesting and not-so-interesting statistics about a
307  * peer.  This is updated by various parts of the code.  The format of the
308  * structure isn't considered private, and @p_stats@ returns a pointer to the
309  * statistics block for a given peer.
310  */
311
312 typedef struct stats {
313   unsigned long sz_in, sz_out;          /* Size of all data in and out */
314   unsigned long sz_kxin, sz_kxout;      /* Size of key exchange messages */
315   unsigned long sz_ipin, sz_ipout;      /* Size of encapsulated IP packets */
316   time_t t_start, t_last, t_kx;         /* Time peer created, last pk, kx */
317   unsigned long n_reject;               /* Number of rejected packets */
318   unsigned long n_in, n_out;            /* Number of packets in and out */
319   unsigned long n_kxin, n_kxout;        /* Number of key exchange packets */
320   unsigned long n_ipin, n_ipout;        /* Number of encrypted packets */
321 } stats;
322
323 /* --- Peer structure --- *
324  *
325  * The main structure which glues everything else together.
326  */
327
328 typedef struct peerspec {
329   char *name;                           /* Peer's name */
330   const tunnel_ops *tops;               /* Tunnel operations */
331   unsigned long t_ka;                   /* Keep alive interval */
332   addr sa;                              /* Socket address to speak to */
333   size_t sasz;                          /* Socket address size */
334   unsigned kxf;                         /* Key exchange flags to set */
335 } peerspec;
336
337 typedef struct peer_byname {
338   sym_base _b;
339   struct peer *p;
340 } peer_byname;
341
342 typedef struct peer_byaddr {
343   addrmap_base _b;
344   struct peer *p;
345 } peer_byaddr;
346
347 typedef struct peer {
348   peer_byname *byname;                  /* Lookup-by-name block */
349   peer_byaddr *byaddr;                  /* Lookup-by-address block */
350   struct ping *pings;                   /* Pings we're waiting for */
351   peerspec spec;                        /* Specifications for this peer */
352   tunnel *t;                            /* Tunnel for local packets */
353   char *ifname;                         /* Interface name for tunnel */
354   keyset *ks;                           /* List head for keysets */
355   buf b;                                /* Buffer for sending packets */
356   stats st;                             /* Statistics */
357   keyexch kx;                           /* Key exchange protocol block */
358   sel_timer tka;                        /* Timer for keepalives */
359 } peer;
360
361 typedef struct peer_iter { sym_iter i; } peer_iter;
362
363 typedef struct ping {
364   struct ping *next, *prev;             /* Links to next and previous */
365   peer *p;                              /* Peer so we can free it */
366   unsigned msg;                         /* Kind of response expected */
367   uint32 id;                            /* Id so we can recognize response */
368   octet magic[32];                      /* Some random data */
369   sel_timer t;                          /* Timeout for ping */
370   void (*func)(int /*rc*/, void */*arg*/); /* Function to call when done */
371   void *arg;                            /* Argument for callback */
372 } ping;
373
374 enum {
375   PING_NONOTIFY = -1,
376   PING_OK = 0,
377   PING_TIMEOUT,
378   PING_PEERDIED,
379   PING_MAX
380 };
381
382 /* --- Admin structure --- */
383
384 #define OBUFSZ 16384u
385
386 typedef struct obuf {
387   struct obuf *next;                    /* Next buffer in list */
388   char *p_in, *p_out;                   /* Pointers into the buffer */
389   char buf[OBUFSZ];                     /* The actual buffer */
390 } obuf;
391
392 typedef struct oqueue {
393   obuf *hd, *tl;                        /* Head and tail pointers */
394 } oqueue;
395
396 struct admin;
397
398 typedef struct admin_bgop {
399   struct admin_bgop *next, *prev;       /* Links to next and previous */
400   struct admin *a;                      /* Owner job */
401   char *tag;                            /* Tag string for messages */
402   void (*cancel)(struct admin_bgop *);  /* Destructor function */
403 } admin_bgop;
404
405 typedef struct admin_resop {
406   admin_bgop bg;                        /* Background operation header */
407   char *addr;                           /* Hostname to be resolved */
408   bres_client r;                        /* Background resolver task */
409   sel_timer t;                          /* Timer for resolver */
410   addr sa;                              /* Socket address */
411   size_t sasz;                          /* Socket address size */
412   void (*func)(struct admin_resop *, int); /* Handler */
413 } admin_resop;
414
415 enum { ARES_OK, ARES_FAIL };
416
417 typedef struct admin_addop {
418   admin_resop r;                        /* Name resolution header */
419   peerspec peer;                        /* Peer pending creation */
420 } admin_addop;
421
422 typedef struct admin_greetop {
423   admin_resop r;                        /* Name resolution header */
424   void *c;                              /* Challenge block */
425   size_t sz;                            /* Length of challenge */
426 } admin_greetop;
427
428 typedef struct admin_pingop {
429   admin_bgop bg;                        /* Background operation header */
430   ping ping;                            /* Ping pending response */
431   struct timeval pingtime;              /* Time last ping was sent */
432 } admin_pingop;
433
434 typedef struct admin_service {
435   sym_base _b;                          /* Hash table base structure */
436   char *version;                        /* The provided version */
437   struct admin *prov;                   /* Which client provides me */
438   struct admin_service *next, *prev;    /* Client's list of services */
439 } admin_service;
440
441 typedef struct admin_svcop {
442   admin_bgop bg;                        /* Background operation header */
443   struct admin *prov;                   /* Client servicing this job */
444   unsigned index;                       /* This job's index */
445   struct admin_svcop *next, *prev;      /* Links for provider's jobs */
446 } admin_svcop;
447
448 typedef struct admin_jobentry {
449   unsigned short seq;                   /* Zero if unused */
450   union {
451     admin_svcop *op;                    /* Operation, if slot in use, ... */
452     uint32 next;                        /* ... or index of next free slot */
453   } u;
454 } admin_jobentry;
455
456 typedef struct admin_jobtable {
457   uint32 n, sz;                         /* Used slots and table size */
458   admin_svcop *active;                  /* List of active jobs */
459   uint32 free;                          /* Index of first free slot */
460   admin_jobentry *v;                    /* And the big array of entries */
461 } admin_jobtable;
462
463 typedef struct admin {
464   struct admin *next, *prev;            /* Links to next and previous */
465   unsigned f;                           /* Various useful flags */
466   unsigned ref;                         /* Reference counter */
467 #ifndef NTRACE
468   unsigned seq;                         /* Sequence number for tracing */
469 #endif
470   oqueue out;                           /* Output buffer list */
471   oqueue delay;                         /* Delayed output buffer list */
472   admin_bgop *bg;                       /* Backgrounded operations */
473   admin_service *svcs;                  /* Which services I provide */
474   admin_jobtable j;                     /* Table of outstanding jobs */
475   selbuf b;                             /* Line buffer for commands */
476   sel_file w;                           /* Selector for write buffering */
477 } admin;
478
479 #define AF_DEAD 1u                      /* Destroy this admin block */
480 #define AF_CLOSE 2u                     /* Client closed connection */
481 #define AF_NOTE 4u                      /* Catch notifications */
482 #define AF_WARN 8u                      /* Catch warning messages */
483 #ifndef NTRACE
484   #define AF_TRACE 16u                  /* Catch tracing */
485 #endif
486 #define AF_FOREGROUND 32u               /* Quit server when client closes */
487
488 #ifndef NTRACE
489 #  define AF_ALLMSGS (AF_NOTE | AF_TRACE | AF_WARN)
490 #else
491 #  define AF_ALLMSGS (AF_NOTE | AF_WARN)
492 #endif
493
494 /*----- Global variables --------------------------------------------------*/
495
496 extern sel_state sel;                   /* Global I/O event state */
497 extern group *gg;                       /* The group we work in */
498 extern size_t indexsz;                  /* Size of exponent for the group */
499 extern mp *kpriv;                       /* Our private key */
500 extern ge *kpub;                        /* Our public key */
501 extern octet buf_i[PKBUFSZ], buf_o[PKBUFSZ], buf_t[PKBUFSZ], buf_u[PKBUFSZ];
502 extern const tunnel_ops *tunnels[];     /* Table of tunnels (0-term) */
503 extern const tunnel_ops *tun_default;   /* Default tunnel to use */
504
505 #ifndef NTRACE
506 extern const trace_opt tr_opts[];       /* Trace options array */
507 extern unsigned tr_flags;               /* Trace options flags */
508 #endif
509
510 /*----- Other macros ------------------------------------------------------*/
511
512 #define TIMER noise_timer(RAND_GLOBAL)
513
514 /*----- Key management ----------------------------------------------------*/
515
516 /* --- @km_reload@ --- *
517  *
518  * Arguments:   ---
519  *
520  * Returns:     Zero if OK, nonzero to force reloading of keys.
521  *
522  * Use:         Checks the keyrings to see if they need reloading.
523  */
524
525 extern int km_reload(void);
526
527 /* --- @km_init@ --- *
528  *
529  * Arguments:   @const char *kr_priv@ = private keyring file
530  *              @const char *kr_pub@ = public keyring file
531  *              @const char *tag@ = tag to load
532  *
533  * Returns:     ---
534  *
535  * Use:         Initializes, and loads the private key.
536  */
537
538 extern void km_init(const char */*kr_priv*/, const char */*kr_pub*/,
539                     const char */*tag*/);
540
541 /* --- @km_getpubkey@ --- *
542  *
543  * Arguments:   @const char *tag@ = public key tag to load
544  *              @ge *kpub@ = where to put the public key
545  *              @time_t *t_exp@ = where to put the expiry time
546  *
547  * Returns:     Zero if OK, nonzero if it failed.
548  *
549  * Use:         Fetches a public key from the keyring.
550  */
551
552 extern int km_getpubkey(const char */*tag*/, ge */*kpub*/,
553                         time_t */*t_exp*/);
554
555 /*----- Key exchange ------------------------------------------------------*/
556
557 /* --- @kx_start@ --- *
558  *
559  * Arguments:   @keyexch *kx@ = pointer to key exchange context
560  *              @int forcep@ = nonzero to ignore the quiet timer
561  *
562  * Returns:     ---
563  *
564  * Use:         Stimulates a key exchange.  If a key exchage is in progress,
565  *              a new challenge is sent (unless the quiet timer forbids
566  *              this); if no exchange is in progress, one is commenced.
567  */
568
569 extern void kx_start(keyexch */*kx*/, int /*forcep*/);
570
571 /* --- @kx_message@ --- *
572  *
573  * Arguments:   @keyexch *kx@ = pointer to key exchange context
574  *              @unsigned msg@ = the message code
575  *              @buf *b@ = pointer to buffer containing the packet
576  *
577  * Returns:     ---
578  *
579  * Use:         Reads a packet containing key exchange messages and handles
580  *              it.
581  */
582
583 extern void kx_message(keyexch */*kx*/, unsigned /*msg*/, buf */*b*/);
584
585 /* --- @kx_free@ --- *
586  *
587  * Arguments:   @keyexch *kx@ = pointer to key exchange context
588  *
589  * Returns:     ---
590  *
591  * Use:         Frees everything in a key exchange context.
592  */
593
594 extern void kx_free(keyexch */*kx*/);
595
596 /* --- @kx_newkeys@ --- *
597  *
598  * Arguments:   @keyexch *kx@ = pointer to key exchange context
599  *
600  * Returns:     ---
601  *
602  * Use:         Informs the key exchange module that its keys may have
603  *              changed.  If fetching the new keys fails, the peer will be
604  *              destroyed, we log messages and struggle along with the old
605  *              keys.
606  */
607
608 extern void kx_newkeys(keyexch */*kx*/);
609
610 /* --- @kx_init@ --- *
611  *
612  * Arguments:   @keyexch *kx@ = pointer to key exchange context
613  *              @peer *p@ = pointer to peer context
614  *              @keyset **ks@ = pointer to keyset list
615  *              @unsigned f@ = various useful flags
616  *
617  * Returns:     Zero if OK, nonzero if it failed.
618  *
619  * Use:         Initializes a key exchange module.  The module currently
620  *              contains no keys, and will attempt to initiate a key
621  *              exchange.
622  */
623
624 extern int kx_init(keyexch */*kx*/, peer */*p*/,
625                    keyset **/*ks*/, unsigned /*f*/);
626
627 /*----- Keysets and symmetric cryptography --------------------------------*/
628
629 /* --- @ks_drop@ --- *
630  *
631  * Arguments:   @keyset *ks@ = pointer to a keyset
632  *
633  * Returns:     ---
634  *
635  * Use:         Decrements a keyset's reference counter.  If the counter hits
636  *              zero, the keyset is freed.
637  */
638
639 extern void ks_drop(keyset */*ks*/);
640
641 /* --- @ks_gen@ --- *
642  *
643  * Arguments:   @const void *k@ = pointer to key material
644  *              @size_t x, y, z@ = offsets into key material (see below)
645  *              @peer *p@ = pointer to peer information
646  *
647  * Returns:     A pointer to the new keyset.
648  *
649  * Use:         Derives a new keyset from the given key material.  The
650  *              offsets @x@, @y@ and @z@ separate the key material into three
651  *              parts.  Between the @k@ and @k + x@ is `my' contribution to
652  *              the key material; between @k + x@ and @k + y@ is `your'
653  *              contribution; and between @k + y@ and @k + z@ is a shared
654  *              value we made together.  These are used to construct two
655  *              pairs of symmetric keys.  Each pair consists of an encryption
656  *              key and a message authentication key.  One pair is used for
657  *              outgoing messages, the other for incoming messages.
658  *
659  *              The new key is marked so that it won't be selected for output
660  *              by @ksl_encrypt@.  You can still encrypt data with it by
661  *              calling @ks_encrypt@ directly.
662  */
663
664 extern keyset *ks_gen(const void */*k*/,
665                       size_t /*x*/, size_t /*y*/, size_t /*z*/,
666                       peer */*p*/);
667
668 /* --- @ks_tregen@ --- *
669  *
670  * Arguments:   @keyset *ks@ = pointer to a keyset
671  *
672  * Returns:     The time at which moves ought to be made to replace this key.
673  */
674
675 extern time_t ks_tregen(keyset */*ks*/);
676
677 /* --- @ks_activate@ --- *
678  *
679  * Arguments:   @keyset *ks@ = pointer to a keyset
680  *
681  * Returns:     ---
682  *
683  * Use:         Activates a keyset, so that it can be used for encrypting
684  *              outgoing messages.
685  */
686
687 extern void ks_activate(keyset */*ks*/);
688
689 /* --- @ks_encrypt@ --- *
690  *
691  * Arguments:   @keyset *ks@ = pointer to a keyset
692  *              @unsigned ty@ = message type
693  *              @buf *b@ = pointer to input buffer
694  *              @buf *bb@ = pointer to output buffer
695  *
696  * Returns:     Zero if successful; @KSERR_REGEN@ if we should negotiate a
697  *              new key; @KSERR_NOKEYS@ if the key is not usable.  Also
698  *              returns zero if there was insufficient buffer (but the output
699  *              buffer is broken in this case).
700  *
701  * Use:         Encrypts a block of data using the key.  Note that the `key
702  *              ought to be replaced' notification is only ever given once
703  *              for each key.  Also note that this call forces a keyset to be
704  *              used even if it's marked as not for data output.
705  */
706
707 extern int ks_encrypt(keyset */*ks*/, unsigned /*ty*/,
708                       buf */*b*/, buf */*bb*/);
709
710 /* --- @ks_decrypt@ --- *
711  *
712  * Arguments:   @keyset *ks@ = pointer to a keyset
713  *              @unsigned ty@ = expected type code
714  *              @buf *b@ = pointer to an input buffer
715  *              @buf *bb@ = pointer to an output buffer
716  *
717  * Returns:     Zero on success; @KSERR_DECRYPT@ on failure.  Also returns
718  *              zero if there was insufficient buffer (but the output buffer
719  *              is broken in this case).
720  *
721  * Use:         Attempts to decrypt a message using a given key.  Note that
722  *              requesting decryption with a key directly won't clear a
723  *              marking that it's not for encryption.
724  */
725
726 extern int ks_decrypt(keyset */*ks*/, unsigned /*ty*/,
727                       buf */*b*/, buf */*bb*/);
728
729 /* --- @ksl_free@ --- *
730  *
731  * Arguments:   @keyset **ksroot@ = pointer to keyset list head
732  *
733  * Returns:     ---
734  *
735  * Use:         Frees (releases references to) all of the keys in a keyset.
736  */
737
738 extern void ksl_free(keyset **/*ksroot*/);
739
740 /* --- @ksl_link@ --- *
741  *
742  * Arguments:   @keyset **ksroot@ = pointer to keyset list head
743  *              @keyset *ks@ = pointer to a keyset
744  *
745  * Returns:     ---
746  *
747  * Use:         Links a keyset into a list.  A keyset can only be on one list
748  *              at a time.  Bad things happen otherwise.
749  */
750
751 extern void ksl_link(keyset **/*ksroot*/, keyset */*ks*/);
752
753 /* --- @ksl_prune@ --- *
754  *
755  * Arguments:   @keyset **ksroot@ = pointer to keyset list head
756  *
757  * Returns:     ---
758  *
759  * Use:         Prunes the keyset list by removing keys which mustn't be used
760  *              any more.
761  */
762
763 extern void ksl_prune(keyset **/*ksroot*/);
764
765 /* --- @ksl_encrypt@ --- *
766  *
767  * Arguments:   @keyset **ksroot@ = pointer to keyset list head
768  *              @unsigned ty@ = message type
769  *              @buf *b@ = pointer to input buffer
770  *              @buf *bb@ = pointer to output buffer
771  *
772  * Returns:     Zero if successful; @KSERR_REGEN@ if it's time to negotiate a
773  *              new key; @KSERR_NOKEYS@ if there are no suitable keys
774  *              available.  Also returns zero if there was insufficient
775  *              buffer space (but the output buffer is broken in this case).
776  *
777  * Use:         Encrypts a packet.
778  */
779
780 extern int ksl_encrypt(keyset **/*ksroot*/, unsigned /*ty*/,
781                        buf */*b*/, buf */*bb*/);
782
783 /* --- @ksl_decrypt@ --- *
784  *
785  * Arguments:   @keyset **ksroot@ = pointer to keyset list head
786  *              @unsigned ty@ = expected type code
787  *              @buf *b@ = pointer to input buffer
788  *              @buf *bb@ = pointer to output buffer
789  *
790  * Returns:     Zero on success; @KSERR_DECRYPT@ on failure.  Also returns
791  *              zero if there was insufficient buffer (but the output buffer
792  *              is broken in this case).
793  *
794  * Use:         Decrypts a packet.
795  */
796
797 extern int ksl_decrypt(keyset **/*ksroot*/, unsigned /*ty*/,
798                        buf */*b*/, buf */*bb*/);
799
800 /*----- Challenges --------------------------------------------------------*/
801
802 /* --- @c_new@ --- *
803  *
804  * Arguments:   @buf *b@ = where to put the challenge
805  *
806  * Returns:     Zero if OK, nonzero on error.
807  *
808  * Use:         Issues a new challenge.
809  */
810
811 extern int c_new(buf */*b*/);
812
813 /* --- @c_check@ --- *
814  *
815  * Arguments:   @buf *b@ = where to find the challenge
816  *
817  * Returns:     Zero if OK, nonzero if it didn't work.
818  *
819  * Use:         Checks a challenge.  On failure, the buffer is broken.
820  */
821
822 extern int c_check(buf */*b*/);
823
824 /*----- Administration interface ------------------------------------------*/
825
826 #define A_END ((char *)0)
827
828 /* --- @a_vformat@ --- *
829  *
830  * Arguments:   @dstr *d@ = where to leave the formatted message
831  *              @const char *fmt@ = pointer to format string
832  *              @va_list ap@ = arguments in list
833  *
834  * Returns:     ---
835  *
836  * Use:         Main message token formatting driver.  The arguments are
837  *              interleaved formatting tokens and their parameters, finally
838  *              terminated by an entry @A_END@.
839  *
840  *              Tokens recognized:
841  *
842  *                * "*..." ... -- pretokenized @dstr_putf@-like string
843  *
844  *                * "?ADDR" SOCKADDR -- a socket address, to be converted
845  *
846  *                * "?B64" BUFFER SIZE -- binary data to be base64-encoded
847  *
848  *                * "?TOKENS" VECTOR -- null-terminated vector of tokens
849  *
850  *                * "?PEER" PEER -- peer's name
851  *
852  *                * "?ERRNO" ERRNO -- system error code
853  *
854  *                * "[!]..." ... -- @dstr_putf@-like string as single token
855  */
856
857 extern void a_vformat(dstr */*d*/, const char */*fmt*/, va_list /*ap*/);
858
859 /* --- @a_warn@ --- *
860  *
861  * Arguments:   @const char *fmt@ = pointer to format string
862  *              @...@ = other arguments
863  *
864  * Returns:     ---
865  *
866  * Use:         Informs all admin connections of a warning.
867  */
868
869 extern void a_warn(const char */*fmt*/, ...);
870
871 /* --- @a_notify@ --- *
872  *
873  * Arguments:   @const char *fmt@ = pointer to format string
874  *              @...@ = other arguments
875  *
876  * Returns:     ---
877  *
878  * Use:         Sends a notification to interested admin connections.
879  */
880
881 extern void a_notify(const char */*fmt*/, ...);
882
883 /* --- @a_create@ --- *
884  *
885  * Arguments:   @int fd_in, fd_out@ = file descriptors to use
886  *              @unsigned f@ = initial flags to set
887  *
888  * Returns:     ---
889  *
890  * Use:         Creates a new admin connection.
891  */
892
893 extern void a_create(int /*fd_in*/, int /*fd_out*/, unsigned /*f*/);
894
895 /* --- @a_quit@ --- *
896  *
897  * Arguments:   ---
898  *
899  * Returns:     ---
900  *
901  * Use:         Shuts things down nicely.
902  */
903
904 extern void a_quit(void);
905
906 /* --- @a_preselect@ --- *
907  *
908  * Arguments:   ---
909  *
910  * Returns:     ---
911  *
912  * Use:         Informs the admin module that we're about to select again,
913  *              and that it should do cleanup things it has delayed until a
914  *              `safe' time.
915  */
916
917 extern void a_preselect(void);
918
919 /* --- @a_daemon@ --- *
920  *
921  * Arguments:   ---
922  *
923  * Returns:     ---
924  *
925  * Use:         Informs the admin module that it's a daemon.
926  */
927
928 extern void a_daemon(void);
929
930 /* --- @a_init@ --- *
931  *
932  * Arguments:   @const char *sock@ = socket name to create
933  *              @uid_t u@ = user to own the socket
934  *              @gid_t g@ = group to own the socket
935  *
936  * Returns:     ---
937  *
938  * Use:         Creates the admin listening socket.
939  */
940
941 extern void a_init(const char */*sock*/, uid_t /*u*/, gid_t /*g*/);
942
943 /*----- Mapping with addresses as keys ------------------------------------*/
944
945 /* --- @am_create@ --- *
946  *
947  * Arguments:   @addrmap *m@ = pointer to map
948  *
949  * Returns:     ---
950  *
951  * Use:         Create an address map, properly set up.
952  */
953
954 extern void am_create(addrmap */*m*/);
955
956 /* --- @am_destroy@ --- *
957  *
958  * Arguments:   @addrmap *m@ = pointer to map
959  *
960  * Returns:     ---
961  *
962  * Use:         Destroy an address map, throwing away all the entries.
963  */
964
965 extern void am_destroy(addrmap */*m*/);
966
967 /* --- @am_find@ --- *
968  *
969  * Arguments:   @addrmap *m@ = pointer to map
970  *              @const addr *a@ = address to look up
971  *              @size_t sz@ = size of block to allocate
972  *              @unsigned *f@ = where to store flags
973  *
974  * Returns:     Pointer to found item, or null.
975  *
976  * Use:         Finds a record with the given IP address, set @*f@ nonzero
977  *              and returns it.  If @sz@ is zero, and no match was found,
978  *              return null; otherwise allocate a new block of @sz@ bytes,
979  *              clear @*f@ to zero and return the block pointer.
980  */
981
982 extern void *am_find(addrmap */*m*/, const addr */*a*/,
983                      size_t /*sz*/, unsigned */*f*/);
984
985 /* --- @am_remove@ --- *
986  *
987  * Arguments:   @addrmap *m@ = pointer to map
988  *              @void *i@ = pointer to the item
989  *
990  * Returns:     ---
991  *
992  * Use:         Removes an item from the map.
993  */
994
995 extern void am_remove(addrmap */*m*/, void */*i*/);
996
997 /*----- Peer management ---------------------------------------------------*/
998
999 /* --- @p_txstart@ --- *
1000  *
1001  * Arguments:   @peer *p@ = pointer to peer block
1002  *              @unsigned msg@ = message type code
1003  *
1004  * Returns:     A pointer to a buffer to write to.
1005  *
1006  * Use:         Starts sending to a peer.  Only one send can happen at a
1007  *              time.
1008  */
1009
1010 extern buf *p_txstart(peer */*p*/, unsigned /*msg*/);
1011
1012 /* --- @p_txend@ --- *
1013  *
1014  * Arguments:   @peer *p@ = pointer to peer block
1015  *
1016  * Returns:     ---
1017  *
1018  * Use:         Sends a packet to the peer.
1019  */
1020
1021 extern void p_txend(peer */*p*/);
1022
1023 /* --- @p_pingsend@ --- *
1024  *
1025  * Arguments:   @peer *p@ = destination peer
1026  *              @ping *pg@ = structure to fill in
1027  *              @unsigned type@ = message type
1028  *              @unsigned long timeout@ = how long to wait before giving up
1029  *              @void (*func)(int, void *)@ = callback function
1030  *              @void *arg@ = argument for callback
1031  *
1032  * Returns:     Zero if successful, nonzero if it failed.
1033  *
1034  * Use:         Sends a ping to a peer.  Call @func@ with a nonzero argument
1035  *              if we get an answer within the timeout, or zero if no answer.
1036  */
1037
1038 extern int p_pingsend(peer */*p*/, ping */*pg*/, unsigned /*type*/,
1039                       unsigned long /*timeout*/,
1040                       void (*/*func*/)(int, void *), void */*arg*/);
1041
1042 /* --- @p_pingdone@ --- *
1043  *
1044  * Arguments:   @ping *p@ = ping structure
1045  *              @int rc@ = return code to pass on
1046  *
1047  * Returns:     ---
1048  *
1049  * Use:         Disposes of a ping structure, maybe sending a notification.
1050  */
1051
1052 extern void p_pingdone(ping */*p*/, int /*rc*/);
1053
1054 /* --- @p_greet@ --- *
1055  *
1056  * Arguments:   @peer *p@ = peer to send to
1057  *              @const void *c@ = pointer to challenge
1058  *              @size_t sz@ = size of challenge
1059  *
1060  * Returns:     ---
1061  *
1062  * Use:         Sends a greeting packet.
1063  */
1064
1065 extern void p_greet(peer */*p*/, const void */*c*/, size_t /*sz*/);
1066
1067 /* --- @p_tun@ --- *
1068  *
1069  * Arguments:   @peer *p@ = pointer to peer block
1070  *              @buf *b@ = buffer containing incoming packet
1071  *
1072  * Returns:     ---
1073  *
1074  * Use:         Handles a packet which needs to be sent to a peer.
1075  */
1076
1077 extern void p_tun(peer */*p*/, buf */*b*/);
1078
1079 /* --- @p_keyreload@ --- *
1080  *
1081  * Arguments:   ---
1082  *
1083  * Returns:     ---
1084  *
1085  * Use:         Forces a check of the daemon's keyring files.
1086  */
1087
1088 extern void p_keyreload(void);
1089
1090 /* --- @p_interval@ --- *
1091  *
1092  * Arguments:   ---
1093  *
1094  * Returns:     ---
1095  *
1096  * Use:         Called periodically to do tidying.
1097  */
1098
1099 extern void p_interval(void);
1100
1101 /* --- @p_stats@ --- *
1102  *
1103  * Arguments:   @peer *p@ = pointer to a peer block
1104  *
1105  * Returns:     A pointer to the peer's statistics.
1106  */
1107
1108 extern stats *p_stats(peer */*p*/);
1109
1110 /* --- @p_ifname@ --- *
1111  *
1112  * Arguments:   @peer *p@ = pointer to a peer block
1113  *
1114  * Returns:     A pointer to the peer's interface name.
1115  */
1116
1117 extern const char *p_ifname(peer */*p*/);
1118
1119 /* --- @p_setifname@ --- *
1120  *
1121  * Arguments:   @peer *p@ = pointer to a peer block
1122  *              @const char *name@ = pointer to the new name
1123  *
1124  * Returns:     ---
1125  *
1126  * Use:         Changes the name held for a peer's interface.
1127  */
1128
1129 extern void p_setifname(peer */*p*/, const char */*name*/);
1130
1131 /* --- @p_addr@ --- *
1132  *
1133  * Arguments:   @peer *p@ = pointer to a peer block
1134  *
1135  * Returns:     A pointer to the peer's address.
1136  */
1137
1138 extern const addr *p_addr(peer */*p*/);
1139
1140 /* --- @p_init@ --- *
1141  *
1142  * Arguments:   @struct in_addr addr@ = address to bind to
1143  *              @unsigned port@ = port number to listen to
1144  *
1145  * Returns:     ---
1146  *
1147  * Use:         Initializes the peer system; creates the socket.
1148  */
1149
1150 extern void p_init(struct in_addr /*addr*/, unsigned /*port*/);
1151
1152 /* --- @p_port@ --- *
1153  *
1154  * Arguments:   ---
1155  *
1156  * Returns:     Port number used for socket.
1157  */
1158
1159 unsigned p_port(void);
1160
1161 /* --- @p_create@ --- *
1162  *
1163  * Arguments:   @peerspec *spec@ = information about this peer
1164  *
1165  * Returns:     Pointer to the peer block, or null if it failed.
1166  *
1167  * Use:         Creates a new named peer block.  No peer is actually attached
1168  *              by this point.
1169  */
1170
1171 extern peer *p_create(peerspec */*spec*/);
1172
1173 /* --- @p_name@ --- *
1174  *
1175  * Arguments:   @peer *p@ = pointer to a peer block
1176  *
1177  * Returns:     A pointer to the peer's name.
1178  *
1179  * Use:         Equivalent to @p_spec(p)->name@.
1180  */
1181
1182 extern const char *p_name(peer */*p*/);
1183
1184 /* --- @p_spec@ --- *
1185  *
1186  * Arguments:   @peer *p@ = pointer to a peer block
1187  *
1188  * Returns:     Pointer to the peer's specification
1189  */
1190
1191 extern const peerspec *p_spec(peer */*p*/);
1192
1193 /* --- @p_findbyaddr@ --- *
1194  *
1195  * Arguments:   @const addr *a@ = address to look up
1196  *
1197  * Returns:     Pointer to the peer block, or null if not found.
1198  *
1199  * Use:         Finds a peer by address.
1200  */
1201
1202 extern peer *p_findbyaddr(const addr */*a*/);
1203
1204 /* --- @p_find@ --- *
1205  *
1206  * Arguments:   @const char *name@ = name to look up
1207  *
1208  * Returns:     Pointer to the peer block, or null if not found.
1209  *
1210  * Use:         Finds a peer by name.
1211  */
1212
1213 extern peer *p_find(const char */*name*/);
1214
1215 /* --- @p_destroy@ --- *
1216  *
1217  * Arguments:   @peer *p@ = pointer to a peer
1218  *
1219  * Returns:     ---
1220  *
1221  * Use:         Destroys a peer.
1222  */
1223
1224 extern void p_destroy(peer */*p*/);
1225
1226 /* --- @FOREACH_PEER@ --- *
1227  *
1228  * Arguments:   @p@ = name to bind to each peer
1229  *              @stuff@ = thing to do for each item
1230  *
1231  * Use:         Does something for each current peer.
1232  */
1233
1234 #define FOREACH_PEER(p, stuff) do {                                     \
1235   peer_iter i_;                                                         \
1236   peer *p;                                                              \
1237   for (p_mkiter(&i_); (p = p_next(&i_)) != 0; ) do stuff while (0);     \
1238 } while (0)
1239
1240 /* --- @p_mkiter@ --- *
1241  *
1242  * Arguments:   @peer_iter *i@ = pointer to an iterator
1243  *
1244  * Returns:     ---
1245  *
1246  * Use:         Initializes the iterator.
1247  */
1248
1249 extern void p_mkiter(peer_iter */*i*/);
1250
1251 /* --- @p_next@ --- *
1252  *
1253  * Arguments:   @peer_iter *i@ = pointer to an iterator
1254  *
1255  * Returns:     Next peer, or null if at the end.
1256  *
1257  * Use:         Returns the next peer.
1258  */
1259
1260 extern peer *p_next(peer_iter */*i*/);
1261
1262 /*----- Tunnel drivers ----------------------------------------------------*/
1263
1264 #ifdef TUN_LINUX
1265   extern const tunnel_ops tun_linux;
1266 #endif
1267
1268 #ifdef TUN_UNET
1269   extern const tunnel_ops tun_unet;
1270 #endif
1271
1272 #ifdef TUN_BSD
1273   extern const tunnel_ops tun_bsd;
1274 #endif
1275
1276 extern const tunnel_ops tun_slip;
1277
1278 /*----- Other handy utilities ---------------------------------------------*/
1279
1280 /* --- @mpstr@ --- *
1281  *
1282  * Arguments:   @mp *m@ = a multiprecision integer
1283  *
1284  * Returns:     A pointer to the integer's textual representation.
1285  *
1286  * Use:         Converts a multiprecision integer to a string.  Corrupts
1287  *              @buf_u@.
1288  */
1289
1290 extern const char *mpstr(mp */*m*/);
1291
1292 /* --- @gestr@ --- *
1293  *
1294  * Arguments:   @group *g@ = a group
1295  *              @ge *x@ = a group element
1296  *
1297  * Returns:     A pointer to the element's textual representation.
1298  *
1299  * Use:         Converts a group element to a string.  Corrupts
1300  *              @buf_u@.
1301  */
1302
1303 extern const char *gestr(group */*g*/, ge */*x*/);
1304
1305 /* --- @timestr@ --- *
1306  *
1307  * Arguments:   @time_t t@ = a time to convert
1308  *
1309  * Returns:     A pointer to a textual representation of the time.
1310  *
1311  * Use:         Converts a time to a textual representation.  Corrupts
1312  *              @buf_u@.
1313  */
1314
1315 extern const char *timestr(time_t /*t*/);
1316
1317 /* --- @mystrieq@ --- *
1318  *
1319  * Arguments:   @const char *x, *y@ = two strings
1320  *
1321  * Returns:     True if @x@ and @y are equal, up to case.
1322  */
1323
1324 extern int mystrieq(const char */*x*/, const char */*y*/);
1325
1326 /* --- @seq_reset@ --- *
1327  *
1328  * Arguments:   @seqwin *s@ = sequence-checking window
1329  *
1330  * Returns:     ---
1331  *
1332  * Use:         Resets a sequence number window.
1333  */
1334
1335 extern void seq_reset(seqwin */*s*/);
1336
1337 /* --- @seq_check@ --- *
1338  *
1339  * Arguments:   @seqwin *s@ = sequence-checking window
1340  *              @uint32 q@ = sequence number to check
1341  *              @const char *service@ = service to report message from
1342  *
1343  * Returns:     A @SEQ_@ code.
1344  *
1345  * Use:         Checks a sequence number against the window, updating things
1346  *              as necessary.
1347  */
1348
1349 extern int seq_check(seqwin */*s*/, uint32 /*q*/, const char */*service*/);
1350
1351 /*----- That's all, folks -------------------------------------------------*/
1352
1353 #ifdef __cplusplus
1354   }
1355 #endif
1356
1357 #endif