chiark / gitweb /
server/keyset.c, server/keymgmt.c: Variable data limits.
[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   tunnel *(*create)(struct peer */*p*/, char **/*ifn*/);
292                                         /* Initializes a new tunnel */
293   void (*setifname)(tunnel */*t*/, const char */*ifn*/);
294                                         /*  Notifies ifname change */
295   void (*inject)(tunnel */*t*/, buf */*b*/); /* Sends packet through if */
296   void (*destroy)(tunnel */*t*/);       /* Destroys a tunnel */
297 } tunnel_ops;
298
299 #ifndef TUN_INTERNALS
300 struct tunnel { const tunnel_ops *ops; };
301 #endif
302
303 /* --- Peer statistics --- *
304  *
305  * Contains various interesting and not-so-interesting statistics about a
306  * peer.  This is updated by various parts of the code.  The format of the
307  * structure isn't considered private, and @p_stats@ returns a pointer to the
308  * statistics block for a given peer.
309  */
310
311 typedef struct stats {
312   unsigned long sz_in, sz_out;          /* Size of all data in and out */
313   unsigned long sz_kxin, sz_kxout;      /* Size of key exchange messages */
314   unsigned long sz_ipin, sz_ipout;      /* Size of encapsulated IP packets */
315   time_t t_start, t_last, t_kx;         /* Time peer created, last pk, kx */
316   unsigned long n_reject;               /* Number of rejected packets */
317   unsigned long n_in, n_out;            /* Number of packets in and out */
318   unsigned long n_kxin, n_kxout;        /* Number of key exchange packets */
319   unsigned long n_ipin, n_ipout;        /* Number of encrypted packets */
320 } stats;
321
322 /* --- Peer structure --- *
323  *
324  * The main structure which glues everything else together.
325  */
326
327 typedef struct peerspec {
328   char *name;                           /* Peer's name */
329   const tunnel_ops *tops;               /* Tunnel operations */
330   unsigned long t_ka;                   /* Keep alive interval */
331   addr sa;                              /* Socket address to speak to */
332   size_t sasz;                          /* Socket address size */
333   unsigned kxf;                         /* Key exchange flags to set */
334 } peerspec;
335
336 typedef struct peer_byname {
337   sym_base _b;
338   struct peer *p;
339 } peer_byname;
340
341 typedef struct peer_byaddr {
342   addrmap_base _b;
343   struct peer *p;
344 } peer_byaddr;
345
346 typedef struct peer {
347   peer_byname *byname;                  /* Lookup-by-name block */
348   peer_byaddr *byaddr;                  /* Lookup-by-address block */
349   struct ping *pings;                   /* Pings we're waiting for */
350   peerspec spec;                        /* Specifications for this peer */
351   tunnel *t;                            /* Tunnel for local packets */
352   char *ifname;                         /* Interface name for tunnel */
353   keyset *ks;                           /* List head for keysets */
354   buf b;                                /* Buffer for sending packets */
355   stats st;                             /* Statistics */
356   keyexch kx;                           /* Key exchange protocol block */
357   sel_timer tka;                        /* Timer for keepalives */
358 } peer;
359
360 typedef struct peer_iter { sym_iter i; } peer_iter;
361
362 typedef struct ping {
363   struct ping *next, *prev;             /* Links to next and previous */
364   peer *p;                              /* Peer so we can free it */
365   unsigned msg;                         /* Kind of response expected */
366   uint32 id;                            /* Id so we can recognize response */
367   octet magic[32];                      /* Some random data */
368   sel_timer t;                          /* Timeout for ping */
369   void (*func)(int /*rc*/, void */*arg*/); /* Function to call when done */
370   void *arg;                            /* Argument for callback */
371 } ping;
372
373 enum {
374   PING_NONOTIFY = -1,
375   PING_OK = 0,
376   PING_TIMEOUT,
377   PING_PEERDIED,
378   PING_MAX
379 };
380
381 /* --- Admin structure --- */
382
383 #define OBUFSZ 16384u
384
385 typedef struct obuf {
386   struct obuf *next;                    /* Next buffer in list */
387   char *p_in, *p_out;                   /* Pointers into the buffer */
388   char buf[OBUFSZ];                     /* The actual buffer */
389 } obuf;
390
391 typedef struct oqueue {
392   obuf *hd, *tl;                        /* Head and tail pointers */
393 } oqueue;
394
395 struct admin;
396
397 typedef struct admin_bgop {
398   struct admin_bgop *next, *prev;       /* Links to next and previous */
399   struct admin *a;                      /* Owner job */
400   char *tag;                            /* Tag string for messages */
401   void (*cancel)(struct admin_bgop *);  /* Destructor function */
402 } admin_bgop;
403
404 typedef struct admin_resop {
405   admin_bgop bg;                        /* Background operation header */
406   char *addr;                           /* Hostname to be resolved */
407   bres_client r;                        /* Background resolver task */
408   sel_timer t;                          /* Timer for resolver */
409   addr sa;                              /* Socket address */
410   size_t sasz;                          /* Socket address size */
411   void (*func)(struct admin_resop *, int); /* Handler */
412 } admin_resop;
413
414 enum { ARES_OK, ARES_FAIL };
415
416 typedef struct admin_addop {
417   admin_resop r;                        /* Name resolution header */
418   peerspec peer;                        /* Peer pending creation */
419 } admin_addop;
420
421 typedef struct admin_greetop {
422   admin_resop r;                        /* Name resolution header */
423   void *c;                              /* Challenge block */
424   size_t sz;                            /* Length of challenge */
425 } admin_greetop;
426
427 typedef struct admin_pingop {
428   admin_bgop bg;                        /* Background operation header */
429   ping ping;                            /* Ping pending response */
430   struct timeval pingtime;              /* Time last ping was sent */
431 } admin_pingop;
432
433 typedef struct admin_service {
434   sym_base _b;                          /* Hash table base structure */
435   char *version;                        /* The provided version */
436   struct admin *prov;                   /* Which client provides me */
437   struct admin_service *next, *prev;    /* Client's list of services */
438 } admin_service;
439
440 typedef struct admin_svcop {
441   admin_bgop bg;                        /* Background operation header */
442   struct admin *prov;                   /* Client servicing this job */
443   unsigned index;                       /* This job's index */
444   struct admin_svcop *next, *prev;      /* Links for provider's jobs */
445 } admin_svcop;
446
447 typedef struct admin_jobentry {
448   unsigned short seq;                   /* Zero if unused */
449   union {
450     admin_svcop *op;                    /* Operation, if slot in use, ... */
451     uint32 next;                        /* ... or index of next free slot */
452   } u;
453 } admin_jobentry;
454
455 typedef struct admin_jobtable {
456   uint32 n, sz;                         /* Used slots and table size */
457   admin_svcop *active;                  /* List of active jobs */
458   uint32 free;                          /* Index of first free slot */
459   admin_jobentry *v;                    /* And the big array of entries */
460 } admin_jobtable;
461
462 typedef struct admin {
463   struct admin *next, *prev;            /* Links to next and previous */
464   unsigned f;                           /* Various useful flags */
465   unsigned ref;                         /* Reference counter */
466 #ifndef NTRACE
467   unsigned seq;                         /* Sequence number for tracing */
468 #endif
469   oqueue out;                           /* Output buffer list */
470   oqueue delay;                         /* Delayed output buffer list */
471   admin_bgop *bg;                       /* Backgrounded operations */
472   admin_service *svcs;                  /* Which services I provide */
473   admin_jobtable j;                     /* Table of outstanding jobs */
474   selbuf b;                             /* Line buffer for commands */
475   sel_file w;                           /* Selector for write buffering */
476 } admin;
477
478 #define AF_DEAD 1u                      /* Destroy this admin block */
479 #define AF_CLOSE 2u                     /* Client closed connection */
480 #define AF_NOTE 4u                      /* Catch notifications */
481 #define AF_WARN 8u                      /* Catch warning messages */
482 #ifndef NTRACE
483   #define AF_TRACE 16u                  /* Catch tracing */
484 #endif
485 #define AF_FOREGROUND 32u               /* Quit server when client closes */
486
487 #ifndef NTRACE
488 #  define AF_ALLMSGS (AF_NOTE | AF_TRACE | AF_WARN)
489 #else
490 #  define AF_ALLMSGS (AF_NOTE | AF_WARN)
491 #endif
492
493 /*----- Global variables --------------------------------------------------*/
494
495 extern sel_state sel;                   /* Global I/O event state */
496 extern group *gg;                       /* The group we work in */
497 extern size_t indexsz;                  /* Size of exponent for the group */
498 extern mp *kpriv;                       /* Our private key */
499 extern ge *kpub;                        /* Our public key */
500 extern octet buf_i[PKBUFSZ], buf_o[PKBUFSZ], buf_t[PKBUFSZ], buf_u[PKBUFSZ];
501 extern const tunnel_ops *tunnels[];     /* Table of tunnels (0-term) */
502 extern const tunnel_ops *tun_default;   /* Default tunnel to use */
503
504 #ifndef NTRACE
505 extern const trace_opt tr_opts[];       /* Trace options array */
506 extern unsigned tr_flags;               /* Trace options flags */
507 #endif
508
509 /*----- Other macros ------------------------------------------------------*/
510
511 #define TIMER noise_timer(RAND_GLOBAL)
512
513 /*----- Key management ----------------------------------------------------*/
514
515 /* --- @km_reload@ --- *
516  *
517  * Arguments:   ---
518  *
519  * Returns:     Zero if OK, nonzero to force reloading of keys.
520  *
521  * Use:         Checks the keyrings to see if they need reloading.
522  */
523
524 extern int km_reload(void);
525
526 /* --- @km_init@ --- *
527  *
528  * Arguments:   @const char *kr_priv@ = private keyring file
529  *              @const char *kr_pub@ = public keyring file
530  *              @const char *tag@ = tag to load
531  *
532  * Returns:     ---
533  *
534  * Use:         Initializes, and loads the private key.
535  */
536
537 extern void km_init(const char */*kr_priv*/, const char */*kr_pub*/,
538                     const char */*tag*/);
539
540 /* --- @km_getpubkey@ --- *
541  *
542  * Arguments:   @const char *tag@ = public key tag to load
543  *              @ge *kpub@ = where to put the public key
544  *              @time_t *t_exp@ = where to put the expiry time
545  *
546  * Returns:     Zero if OK, nonzero if it failed.
547  *
548  * Use:         Fetches a public key from the keyring.
549  */
550
551 extern int km_getpubkey(const char */*tag*/, ge */*kpub*/,
552                         time_t */*t_exp*/);
553
554 /*----- Key exchange ------------------------------------------------------*/
555
556 /* --- @kx_start@ --- *
557  *
558  * Arguments:   @keyexch *kx@ = pointer to key exchange context
559  *              @int forcep@ = nonzero to ignore the quiet timer
560  *
561  * Returns:     ---
562  *
563  * Use:         Stimulates a key exchange.  If a key exchage is in progress,
564  *              a new challenge is sent (unless the quiet timer forbids
565  *              this); if no exchange is in progress, one is commenced.
566  */
567
568 extern void kx_start(keyexch */*kx*/, int /*forcep*/);
569
570 /* --- @kx_message@ --- *
571  *
572  * Arguments:   @keyexch *kx@ = pointer to key exchange context
573  *              @unsigned msg@ = the message code
574  *              @buf *b@ = pointer to buffer containing the packet
575  *
576  * Returns:     ---
577  *
578  * Use:         Reads a packet containing key exchange messages and handles
579  *              it.
580  */
581
582 extern void kx_message(keyexch */*kx*/, unsigned /*msg*/, buf */*b*/);
583
584 /* --- @kx_free@ --- *
585  *
586  * Arguments:   @keyexch *kx@ = pointer to key exchange context
587  *
588  * Returns:     ---
589  *
590  * Use:         Frees everything in a key exchange context.
591  */
592
593 extern void kx_free(keyexch */*kx*/);
594
595 /* --- @kx_newkeys@ --- *
596  *
597  * Arguments:   @keyexch *kx@ = pointer to key exchange context
598  *
599  * Returns:     ---
600  *
601  * Use:         Informs the key exchange module that its keys may have
602  *              changed.  If fetching the new keys fails, the peer will be
603  *              destroyed, we log messages and struggle along with the old
604  *              keys.
605  */
606
607 extern void kx_newkeys(keyexch */*kx*/);
608
609 /* --- @kx_init@ --- *
610  *
611  * Arguments:   @keyexch *kx@ = pointer to key exchange context
612  *              @peer *p@ = pointer to peer context
613  *              @keyset **ks@ = pointer to keyset list
614  *              @unsigned f@ = various useful flags
615  *
616  * Returns:     Zero if OK, nonzero if it failed.
617  *
618  * Use:         Initializes a key exchange module.  The module currently
619  *              contains no keys, and will attempt to initiate a key
620  *              exchange.
621  */
622
623 extern int kx_init(keyexch */*kx*/, peer */*p*/,
624                    keyset **/*ks*/, unsigned /*f*/);
625
626 /*----- Keysets and symmetric cryptography --------------------------------*/
627
628 /* --- @ks_drop@ --- *
629  *
630  * Arguments:   @keyset *ks@ = pointer to a keyset
631  *
632  * Returns:     ---
633  *
634  * Use:         Decrements a keyset's reference counter.  If the counter hits
635  *              zero, the keyset is freed.
636  */
637
638 extern void ks_drop(keyset */*ks*/);
639
640 /* --- @ks_gen@ --- *
641  *
642  * Arguments:   @const void *k@ = pointer to key material
643  *              @size_t x, y, z@ = offsets into key material (see below)
644  *              @peer *p@ = pointer to peer information
645  *
646  * Returns:     A pointer to the new keyset.
647  *
648  * Use:         Derives a new keyset from the given key material.  The
649  *              offsets @x@, @y@ and @z@ separate the key material into three
650  *              parts.  Between the @k@ and @k + x@ is `my' contribution to
651  *              the key material; between @k + x@ and @k + y@ is `your'
652  *              contribution; and between @k + y@ and @k + z@ is a shared
653  *              value we made together.  These are used to construct two
654  *              pairs of symmetric keys.  Each pair consists of an encryption
655  *              key and a message authentication key.  One pair is used for
656  *              outgoing messages, the other for incoming messages.
657  *
658  *              The new key is marked so that it won't be selected for output
659  *              by @ksl_encrypt@.  You can still encrypt data with it by
660  *              calling @ks_encrypt@ directly.
661  */
662
663 extern keyset *ks_gen(const void */*k*/,
664                       size_t /*x*/, size_t /*y*/, size_t /*z*/,
665                       peer */*p*/);
666
667 /* --- @ks_tregen@ --- *
668  *
669  * Arguments:   @keyset *ks@ = pointer to a keyset
670  *
671  * Returns:     The time at which moves ought to be made to replace this key.
672  */
673
674 extern time_t ks_tregen(keyset */*ks*/);
675
676 /* --- @ks_activate@ --- *
677  *
678  * Arguments:   @keyset *ks@ = pointer to a keyset
679  *
680  * Returns:     ---
681  *
682  * Use:         Activates a keyset, so that it can be used for encrypting
683  *              outgoing messages.
684  */
685
686 extern void ks_activate(keyset */*ks*/);
687
688 /* --- @ks_encrypt@ --- *
689  *
690  * Arguments:   @keyset *ks@ = pointer to a keyset
691  *              @unsigned ty@ = message type
692  *              @buf *b@ = pointer to input buffer
693  *              @buf *bb@ = pointer to output buffer
694  *
695  * Returns:     Zero if successful; @KSERR_REGEN@ if we should negotiate a
696  *              new key; @KSERR_NOKEYS@ if the key is not usable.  Also
697  *              returns zero if there was insufficient buffer (but the output
698  *              buffer is broken in this case).
699  *
700  * Use:         Encrypts a block of data using the key.  Note that the `key
701  *              ought to be replaced' notification is only ever given once
702  *              for each key.  Also note that this call forces a keyset to be
703  *              used even if it's marked as not for data output.
704  */
705
706 extern int ks_encrypt(keyset */*ks*/, unsigned /*ty*/,
707                       buf */*b*/, buf */*bb*/);
708
709 /* --- @ks_decrypt@ --- *
710  *
711  * Arguments:   @keyset *ks@ = pointer to a keyset
712  *              @unsigned ty@ = expected type code
713  *              @buf *b@ = pointer to an input buffer
714  *              @buf *bb@ = pointer to an output buffer
715  *
716  * Returns:     Zero on success; @KSERR_DECRYPT@ on failure.  Also returns
717  *              zero if there was insufficient buffer (but the output buffer
718  *              is broken in this case).
719  *
720  * Use:         Attempts to decrypt a message using a given key.  Note that
721  *              requesting decryption with a key directly won't clear a
722  *              marking that it's not for encryption.
723  */
724
725 extern int ks_decrypt(keyset */*ks*/, unsigned /*ty*/,
726                       buf */*b*/, buf */*bb*/);
727
728 /* --- @ksl_free@ --- *
729  *
730  * Arguments:   @keyset **ksroot@ = pointer to keyset list head
731  *
732  * Returns:     ---
733  *
734  * Use:         Frees (releases references to) all of the keys in a keyset.
735  */
736
737 extern void ksl_free(keyset **/*ksroot*/);
738
739 /* --- @ksl_link@ --- *
740  *
741  * Arguments:   @keyset **ksroot@ = pointer to keyset list head
742  *              @keyset *ks@ = pointer to a keyset
743  *
744  * Returns:     ---
745  *
746  * Use:         Links a keyset into a list.  A keyset can only be on one list
747  *              at a time.  Bad things happen otherwise.
748  */
749
750 extern void ksl_link(keyset **/*ksroot*/, keyset */*ks*/);
751
752 /* --- @ksl_prune@ --- *
753  *
754  * Arguments:   @keyset **ksroot@ = pointer to keyset list head
755  *
756  * Returns:     ---
757  *
758  * Use:         Prunes the keyset list by removing keys which mustn't be used
759  *              any more.
760  */
761
762 extern void ksl_prune(keyset **/*ksroot*/);
763
764 /* --- @ksl_encrypt@ --- *
765  *
766  * Arguments:   @keyset **ksroot@ = pointer to keyset list head
767  *              @unsigned ty@ = message type
768  *              @buf *b@ = pointer to input buffer
769  *              @buf *bb@ = pointer to output buffer
770  *
771  * Returns:     Zero if successful; @KSERR_REGEN@ if it's time to negotiate a
772  *              new key; @KSERR_NOKEYS@ if there are no suitable keys
773  *              available.  Also returns zero if there was insufficient
774  *              buffer space (but the output buffer is broken in this case).
775  *
776  * Use:         Encrypts a packet.
777  */
778
779 extern int ksl_encrypt(keyset **/*ksroot*/, unsigned /*ty*/,
780                        buf */*b*/, buf */*bb*/);
781
782 /* --- @ksl_decrypt@ --- *
783  *
784  * Arguments:   @keyset **ksroot@ = pointer to keyset list head
785  *              @unsigned ty@ = expected type code
786  *              @buf *b@ = pointer to input buffer
787  *              @buf *bb@ = pointer to output buffer
788  *
789  * Returns:     Zero on success; @KSERR_DECRYPT@ on failure.  Also returns
790  *              zero if there was insufficient buffer (but the output buffer
791  *              is broken in this case).
792  *
793  * Use:         Decrypts a packet.
794  */
795
796 extern int ksl_decrypt(keyset **/*ksroot*/, unsigned /*ty*/,
797                        buf */*b*/, buf */*bb*/);
798
799 /*----- Challenges --------------------------------------------------------*/
800
801 /* --- @c_new@ --- *
802  *
803  * Arguments:   @buf *b@ = where to put the challenge
804  *
805  * Returns:     Zero if OK, nonzero on error.
806  *
807  * Use:         Issues a new challenge.
808  */
809
810 extern int c_new(buf */*b*/);
811
812 /* --- @c_check@ --- *
813  *
814  * Arguments:   @buf *b@ = where to find the challenge
815  *
816  * Returns:     Zero if OK, nonzero if it didn't work.
817  *
818  * Use:         Checks a challenge.  On failure, the buffer is broken.
819  */
820
821 extern int c_check(buf */*b*/);
822
823 /*----- Administration interface ------------------------------------------*/
824
825 #define A_END ((char *)0)
826
827 /* --- @a_warn@ --- *
828  *
829  * Arguments:   @const char *fmt@ = pointer to format string
830  *              @...@ = other arguments
831  *
832  * Returns:     ---
833  *
834  * Use:         Informs all admin connections of a warning.
835  */
836
837 extern void a_warn(const char */*fmt*/, ...);
838
839 /* --- @a_notify@ --- *
840  *
841  * Arguments:   @const char *fmt@ = pointer to format string
842  *              @...@ = other arguments
843  *
844  * Returns:     ---
845  *
846  * Use:         Sends a notification to interested admin connections.
847  */
848
849 extern void a_notify(const char */*fmt*/, ...);
850
851 /* --- @a_create@ --- *
852  *
853  * Arguments:   @int fd_in, fd_out@ = file descriptors to use
854  *              @unsigned f@ = initial flags to set
855  *
856  * Returns:     ---
857  *
858  * Use:         Creates a new admin connection.
859  */
860
861 extern void a_create(int /*fd_in*/, int /*fd_out*/, unsigned /*f*/);
862
863 /* --- @a_quit@ --- *
864  *
865  * Arguments:   ---
866  *
867  * Returns:     ---
868  *
869  * Use:         Shuts things down nicely.
870  */
871
872 extern void a_quit(void);
873
874 /* --- @a_preselect@ --- *
875  *
876  * Arguments:   ---
877  *
878  * Returns:     ---
879  *
880  * Use:         Informs the admin module that we're about to select again,
881  *              and that it should do cleanup things it has delayed until a
882  *              `safe' time.
883  */
884
885 extern void a_preselect(void);
886
887 /* --- @a_daemon@ --- *
888  *
889  * Arguments:   ---
890  *
891  * Returns:     ---
892  *
893  * Use:         Informs the admin module that it's a daemon.
894  */
895
896 extern void a_daemon(void);
897
898 /* --- @a_init@ --- *
899  *
900  * Arguments:   @const char *sock@ = socket name to create
901  *
902  * Returns:     ---
903  *
904  * Use:         Creates the admin listening socket.
905  */
906
907 extern void a_init(const char */*sock*/);
908
909 /*----- Mapping with addresses as keys ------------------------------------*/
910
911 /* --- @am_create@ --- *
912  *
913  * Arguments:   @addrmap *m@ = pointer to map
914  *
915  * Returns:     ---
916  *
917  * Use:         Create an address map, properly set up.
918  */
919
920 extern void am_create(addrmap */*m*/);
921
922 /* --- @am_destroy@ --- *
923  *
924  * Arguments:   @addrmap *m@ = pointer to map
925  *
926  * Returns:     ---
927  *
928  * Use:         Destroy an address map, throwing away all the entries.
929  */
930
931 extern void am_destroy(addrmap */*m*/);
932
933 /* --- @am_find@ --- *
934  *
935  * Arguments:   @addrmap *m@ = pointer to map
936  *              @const addr *a@ = address to look up
937  *              @size_t sz@ = size of block to allocate
938  *              @unsigned *f@ = where to store flags
939  *
940  * Returns:     Pointer to found item, or null.
941  *
942  * Use:         Finds a record with the given IP address, set @*f@ nonzero
943  *              and returns it.  If @sz@ is zero, and no match was found,
944  *              return null; otherwise allocate a new block of @sz@ bytes,
945  *              clear @*f@ to zero and return the block pointer.
946  */
947
948 extern void *am_find(addrmap */*m*/, const addr */*a*/,
949                      size_t /*sz*/, unsigned */*f*/);
950
951 /* --- @am_remove@ --- *
952  *
953  * Arguments:   @addrmap *m@ = pointer to map
954  *              @void *i@ = pointer to the item
955  *
956  * Returns:     ---
957  *
958  * Use:         Removes an item from the map.
959  */
960
961 extern void am_remove(addrmap */*m*/, void */*i*/);
962
963 /*----- Peer management ---------------------------------------------------*/
964
965 /* --- @p_txstart@ --- *
966  *
967  * Arguments:   @peer *p@ = pointer to peer block
968  *              @unsigned msg@ = message type code
969  *
970  * Returns:     A pointer to a buffer to write to.
971  *
972  * Use:         Starts sending to a peer.  Only one send can happen at a
973  *              time.
974  */
975
976 extern buf *p_txstart(peer */*p*/, unsigned /*msg*/);
977
978 /* --- @p_txend@ --- *
979  *
980  * Arguments:   @peer *p@ = pointer to peer block
981  *
982  * Returns:     ---
983  *
984  * Use:         Sends a packet to the peer.
985  */
986
987 extern void p_txend(peer */*p*/);
988
989 /* --- @p_pingsend@ --- *
990  *
991  * Arguments:   @peer *p@ = destination peer
992  *              @ping *pg@ = structure to fill in
993  *              @unsigned type@ = message type
994  *              @unsigned long timeout@ = how long to wait before giving up
995  *              @void (*func)(int, void *)@ = callback function
996  *              @void *arg@ = argument for callback
997  *
998  * Returns:     Zero if successful, nonzero if it failed.
999  *
1000  * Use:         Sends a ping to a peer.  Call @func@ with a nonzero argument
1001  *              if we get an answer within the timeout, or zero if no answer.
1002  */
1003
1004 extern int p_pingsend(peer */*p*/, ping */*pg*/, unsigned /*type*/,
1005                       unsigned long /*timeout*/,
1006                       void (*/*func*/)(int, void *), void */*arg*/);
1007
1008 /* --- @p_pingdone@ --- *
1009  *
1010  * Arguments:   @ping *p@ = ping structure
1011  *              @int rc@ = return code to pass on
1012  *
1013  * Returns:     ---
1014  *
1015  * Use:         Disposes of a ping structure, maybe sending a notification.
1016  */
1017
1018 extern void p_pingdone(ping */*p*/, int /*rc*/);
1019
1020 /* --- @p_greet@ --- *
1021  *
1022  * Arguments:   @peer *p@ = peer to send to
1023  *              @const void *c@ = pointer to challenge
1024  *              @size_t sz@ = size of challenge
1025  *
1026  * Returns:     ---
1027  *
1028  * Use:         Sends a greeting packet.
1029  */
1030
1031 extern void p_greet(peer */*p*/, const void */*c*/, size_t /*sz*/);
1032
1033 /* --- @p_tun@ --- *
1034  *
1035  * Arguments:   @peer *p@ = pointer to peer block
1036  *              @buf *b@ = buffer containing incoming packet
1037  *
1038  * Returns:     ---
1039  *
1040  * Use:         Handles a packet which needs to be sent to a peer.
1041  */
1042
1043 extern void p_tun(peer */*p*/, buf */*b*/);
1044
1045 /* --- @p_keyreload@ --- *
1046  *
1047  * Arguments:   ---
1048  *
1049  * Returns:     ---
1050  *
1051  * Use:         Forces a check of the daemon's keyring files.
1052  */
1053
1054 extern void p_keyreload(void);
1055
1056 /* --- @p_interval@ --- *
1057  *
1058  * Arguments:   ---
1059  *
1060  * Returns:     ---
1061  *
1062  * Use:         Called periodically to do tidying.
1063  */
1064
1065 extern void p_interval(void);
1066
1067 /* --- @p_stats@ --- *
1068  *
1069  * Arguments:   @peer *p@ = pointer to a peer block
1070  *
1071  * Returns:     A pointer to the peer's statistics.
1072  */
1073
1074 extern stats *p_stats(peer */*p*/);
1075
1076 /* --- @p_ifname@ --- *
1077  *
1078  * Arguments:   @peer *p@ = pointer to a peer block
1079  *
1080  * Returns:     A pointer to the peer's interface name.
1081  */
1082
1083 extern const char *p_ifname(peer */*p*/);
1084
1085 /* --- @p_setifname@ --- *
1086  *
1087  * Arguments:   @peer *p@ = pointer to a peer block
1088  *              @const char *name@ = pointer to the new name
1089  *
1090  * Returns:     ---
1091  *
1092  * Use:         Changes the name held for a peer's interface.
1093  */
1094
1095 extern void p_setifname(peer */*p*/, const char */*name*/);
1096
1097 /* --- @p_addr@ --- *
1098  *
1099  * Arguments:   @peer *p@ = pointer to a peer block
1100  *
1101  * Returns:     A pointer to the peer's address.
1102  */
1103
1104 extern const addr *p_addr(peer */*p*/);
1105
1106 /* --- @p_init@ --- *
1107  *
1108  * Arguments:   @struct in_addr addr@ = address to bind to
1109  *              @unsigned port@ = port number to listen to
1110  *
1111  * Returns:     ---
1112  *
1113  * Use:         Initializes the peer system; creates the socket.
1114  */
1115
1116 extern void p_init(struct in_addr /*addr*/, unsigned /*port*/);
1117
1118 /* --- @p_port@ --- *
1119  *
1120  * Arguments:   ---
1121  *
1122  * Returns:     Port number used for socket.
1123  */
1124
1125 unsigned p_port(void);
1126
1127 /* --- @p_create@ --- *
1128  *
1129  * Arguments:   @peerspec *spec@ = information about this peer
1130  *
1131  * Returns:     Pointer to the peer block, or null if it failed.
1132  *
1133  * Use:         Creates a new named peer block.  No peer is actually attached
1134  *              by this point.
1135  */
1136
1137 extern peer *p_create(peerspec */*spec*/);
1138
1139 /* --- @p_name@ --- *
1140  *
1141  * Arguments:   @peer *p@ = pointer to a peer block
1142  *
1143  * Returns:     A pointer to the peer's name.
1144  *
1145  * Use:         Equivalent to @p_spec(p)->name@.
1146  */
1147
1148 extern const char *p_name(peer */*p*/);
1149
1150 /* --- @p_spec@ --- *
1151  *
1152  * Arguments:   @peer *p@ = pointer to a peer block
1153  *
1154  * Returns:     Pointer to the peer's specification
1155  */
1156
1157 extern const peerspec *p_spec(peer */*p*/);
1158
1159 /* --- @p_findbyaddr@ --- *
1160  *
1161  * Arguments:   @const addr *a@ = address to look up
1162  *
1163  * Returns:     Pointer to the peer block, or null if not found.
1164  *
1165  * Use:         Finds a peer by address.
1166  */
1167
1168 extern peer *p_findbyaddr(const addr */*a*/);
1169
1170 /* --- @p_find@ --- *
1171  *
1172  * Arguments:   @const char *name@ = name to look up
1173  *
1174  * Returns:     Pointer to the peer block, or null if not found.
1175  *
1176  * Use:         Finds a peer by name.
1177  */
1178
1179 extern peer *p_find(const char */*name*/);
1180
1181 /* --- @p_destroy@ --- *
1182  *
1183  * Arguments:   @peer *p@ = pointer to a peer
1184  *
1185  * Returns:     ---
1186  *
1187  * Use:         Destroys a peer.
1188  */
1189
1190 extern void p_destroy(peer */*p*/);
1191
1192 /* --- @FOREACH_PEER@ --- *
1193  *
1194  * Arguments:   @p@ = name to bind to each peer
1195  *              @stuff@ = thing to do for each item
1196  *
1197  * Use:         Does something for each current peer.
1198  */
1199
1200 #define FOREACH_PEER(p, stuff) do {                                     \
1201   peer_iter i_;                                                         \
1202   peer *p;                                                              \
1203   for (p_mkiter(&i_); (p = p_next(&i_)) != 0; ) do stuff while (0);     \
1204 } while (0)
1205
1206 /* --- @p_mkiter@ --- *
1207  *
1208  * Arguments:   @peer_iter *i@ = pointer to an iterator
1209  *
1210  * Returns:     ---
1211  *
1212  * Use:         Initializes the iterator.
1213  */
1214
1215 extern void p_mkiter(peer_iter */*i*/);
1216
1217 /* --- @p_next@ --- *
1218  *
1219  * Arguments:   @peer_iter *i@ = pointer to an iterator
1220  *
1221  * Returns:     Next peer, or null if at the end.
1222  *
1223  * Use:         Returns the next peer.
1224  */
1225
1226 extern peer *p_next(peer_iter */*i*/);
1227
1228 /*----- Tunnel drivers ----------------------------------------------------*/
1229
1230 #ifdef TUN_LINUX
1231   extern const tunnel_ops tun_linux;
1232 #endif
1233
1234 #ifdef TUN_UNET
1235   extern const tunnel_ops tun_unet;
1236 #endif
1237
1238 #ifdef TUN_BSD
1239   extern const tunnel_ops tun_bsd;
1240 #endif
1241
1242 extern const tunnel_ops tun_slip;
1243
1244 /*----- Other handy utilities ---------------------------------------------*/
1245
1246 /* --- @mpstr@ --- *
1247  *
1248  * Arguments:   @mp *m@ = a multiprecision integer
1249  *
1250  * Returns:     A pointer to the integer's textual representation.
1251  *
1252  * Use:         Converts a multiprecision integer to a string.  Corrupts
1253  *              @buf_u@.
1254  */
1255
1256 extern const char *mpstr(mp */*m*/);
1257
1258 /* --- @gestr@ --- *
1259  *
1260  * Arguments:   @group *g@ = a group
1261  *              @ge *x@ = a group element
1262  *
1263  * Returns:     A pointer to the element's textual representation.
1264  *
1265  * Use:         Converts a group element to a string.  Corrupts
1266  *              @buf_u@.
1267  */
1268
1269 extern const char *gestr(group */*g*/, ge */*x*/);
1270
1271 /* --- @timestr@ --- *
1272  *
1273  * Arguments:   @time_t t@ = a time to convert
1274  *
1275  * Returns:     A pointer to a textual representation of the time.
1276  *
1277  * Use:         Converts a time to a textual representation.  Corrupts
1278  *              @buf_u@.
1279  */
1280
1281 extern const char *timestr(time_t /*t*/);
1282
1283 /* --- @mystrieq@ --- *
1284  *
1285  * Arguments:   @const char *x, *y@ = two strings
1286  *
1287  * Returns:     True if @x@ and @y are equal, up to case.
1288  */
1289
1290 extern int mystrieq(const char */*x*/, const char */*y*/);
1291
1292 /* --- @seq_reset@ --- *
1293  *
1294  * Arguments:   @seqwin *s@ = sequence-checking window
1295  *
1296  * Returns:     ---
1297  *
1298  * Use:         Resets a sequence number window.
1299  */
1300
1301 extern void seq_reset(seqwin */*s*/);
1302
1303 /* --- @seq_check@ --- *
1304  *
1305  * Arguments:   @seqwin *s@ = sequence-checking window
1306  *              @uint32 q@ = sequence number to check
1307  *              @const char *service@ = service to report message from
1308  *
1309  * Returns:     A @SEQ_@ code.
1310  *
1311  * Use:         Checks a sequence number against the window, updating things
1312  *              as necessary.
1313  */
1314
1315 extern int seq_check(seqwin */*s*/, uint32 /*q*/, const char */*service*/);
1316
1317 /*----- That's all, folks -------------------------------------------------*/
1318
1319 #ifdef __cplusplus
1320   }
1321 #endif
1322
1323 #endif