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