3 * Main header file for TrIPE
5 * (c) 2001 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of Trivial IP Encryption (TrIPE).
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.
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.
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.
34 /*----- Header files ------------------------------------------------------*/
50 #include <sys/types.h>
57 #include <sys/socket.h>
59 #include <netinet/in.h>
60 #include <arpa/inet.h>
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>
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>
83 #include <mLib/selbuf.h>
87 #include <mLib/trace.h>
89 #include <mLib/versioncmp.h>
91 #include <catacomb/buf.h>
92 #include <catacomb/ct.h>
94 #include <catacomb/gcipher.h>
95 #include <catacomb/gmac.h>
96 #include <catacomb/grand.h>
97 #include <catacomb/key.h>
98 #include <catacomb/paranoia.h>
100 #include <catacomb/noise.h>
101 #include <catacomb/rand.h>
103 #include <catacomb/mp.h>
104 #include <catacomb/mprand.h>
105 #include <catacomb/dh.h>
106 #include <catacomb/ec.h>
107 #include <catacomb/ec-keys.h>
108 #include <catacomb/group.h>
111 #include "protocol.h"
117 /*----- Magic numbers -----------------------------------------------------*/
119 /* --- Trace flags --- */
127 #define T_KEYEXCH 64u
128 #define T_KEYMGMT 128u
130 /* T_PRIVSEP in priv.h */
136 #define SEC(n) (n##u)
137 #define MIN(n) (n##u * 60u)
138 #define F_2P32 (65536.0*65536.0)
139 #define MEG(n) (n##ul * 1024ul * 1024ul)
141 /* --- Timing parameters --- */
143 #define T_EXP MIN(60) /* Expiry time for a key */
144 #define T_REGEN MIN(40) /* Regeneration time for a key */
146 #define T_VALID SEC(20) /* Challenge validity period */
147 #define T_RETRYMIN SEC(2) /* Minimum retry interval */
148 #define T_RETRYMAX MIN(5) /* Maximum retry interval */
149 #define T_RETRYGROW (5.0/4.0) /* Retry interval growth factor */
151 #define T_WOBBLE (1.0/3.0) /* Relative timer randomness */
153 /* --- Other things --- */
155 #define PKBUFSZ 65536
157 /*----- Cipher selections -------------------------------------------------*/
159 typedef struct keyset keyset;
160 typedef struct algswitch algswitch;
161 typedef struct admin admin;
163 typedef struct bulkalgs {
164 const struct bulkops *ops;
167 typedef struct bulkctx {
168 const struct bulkops *ops;
171 typedef struct bulkchal {
172 const struct bulkops *ops;
178 typedef struct bulkops {
181 bulkalgs *(*getalgs)(const algswitch */*asw*/, dstr */*e*/,
182 key_file */*kf*/, key */*k*/);
183 /* Determine algorithms to use and return a @bulkalgs@ object
184 * representing the decision. On error, write tokens to @e@ and
188 T( void (*tracealgs)(const bulkalgs */*a*/); )
189 /* Write trace information about the algorithm selection. */
191 int (*checkalgs)(bulkalgs */*a*/, const algswitch */*asw*/, dstr */*e*/);
192 /* Check that the algorithms in @a@ and @asw@ are acceptable. On
193 * error, write tokens to @e@ and return @-1@; otherwise return zero.
196 int (*samealgsp)(const bulkalgs */*a*/, const bulkalgs */*aa*/);
197 /* If @a@ and @aa@ represent the same algorithm selection, return
198 * nonzero; if not, return zero.
201 void (*alginfo)(const bulkalgs */*a*/, admin */*adm*/);
202 /* Report on the algorithm selection to an admin client: call
203 * @a_info@ with appropriate key-value pairs.
206 size_t (*overhead)(const bulkalgs */*a*/);
207 /* Return the per-packet overhead of the bulk transform, in bytes. */
209 size_t (*expsz)(const bulkalgs */*a*/);
210 /* Return the total size limit for the bulk transform, in bytes,
211 * after which the keys must no longer be used.
214 bulkctx *(*genkeys)(const bulkalgs */*a*/, const struct rawkey */*rk*/);
215 /* Generate session keys and construct and return an appropriate
216 * context for using them, by calling @ks_derive@.
219 bulkchal *(*genchal)(const bulkalgs */*a*/);
220 /* Construct and return a challenge issuing and verification
221 * context with a fresh random key.
224 void (*freealgs)(bulkalgs */*a*/);
225 /* Release an algorithm selection object. (Associated bulk
226 * encryption contexts and challenge contexts may still exist and
227 * must remain valid.)
230 int (*encrypt)(bulkctx */*bc*/, unsigned /*ty*/,
231 buf */*b*/, buf */*bb*/, uint32 /*seq*/);
232 /* Encrypt the packet in @b@, with type @ty@ (which doesn't need
233 * encoding separately) and sequence number @seq@ (which must be
234 * recoverable by @decrypt@), and write the result to @bb@. On
235 * error, return a @KSERR_...@ code and/or break the output buffer.
238 int (*decrypt)(bulkctx */*bc*/, unsigned /*ty*/,
239 buf */*b*/, buf */*bb*/, uint32 */*seq*/);
240 /* Decrypt the packet in @b@, with type @ty@, writing the result to
241 * @bb@ and storing the incoming (claimed) sequence number in @seq@.
242 * On error, return a @KSERR_...@ code.
245 void (*freectx)(bulkctx */*a*/);
246 /* Release a bulk encryption context and the resources it holds. */
248 int (*chaltag)(bulkchal */*bc*/, const void */*m*/, size_t /*msz*/,
250 /* Calculate a tag for the challenge in @m@, @msz@, and write it to
251 * @t@. Return @-1@ on error, zero on success.
254 int (*chalvrf)(bulkchal */*bc*/, const void */*m*/, size_t /*msz*/,
256 /* Check the tag @t@ on @m@, @msz@: return zero if the tag is OK,
257 * nonzero if it's bad.
260 void (*freechal)(bulkchal */*bc*/);
261 /* Release a challenge context and the resources it holds. */
266 const gchash *h; size_t hashsz; /* Hash function */
267 const gccipher *mgf; /* Mask-generation function */
268 bulkalgs *bulk; /* Bulk crypto algorithms */
271 typedef struct kdata {
272 unsigned ref; /* Reference counter */
273 struct knode *kn; /* Pointer to cache entry */
274 char *tag; /* Full tag name of the key */
275 group *g; /* The group we work in */
276 size_t indexsz; /* Size of exponent for the group */
277 mp *kpriv; /* The private key (or null) */
278 ge *kpub; /* The public key */
279 time_t t_exp; /* Expiry time of the key */
280 algswitch algs; /* Collection of algorithms */
283 typedef struct knode {
284 sym_base _b; /* Symbol table intrusion */
285 unsigned f; /* Various flags */
286 #define KNF_BROKEN 1u /* Don't use this key any more */
287 struct keyhalf *kh; /* Pointer to the home keyhalf */
288 kdata *kd; /* Pointer to the key data */
291 #define MAXHASHSZ 64 /* Largest possible hash size */
293 #define HASH_STRING(h, s) GH_HASH((h), (s), sizeof(s))
295 extern const bulkops bulktab[];
297 /*----- Data structures ---------------------------------------------------*/
299 /* --- Socket addresses --- *
301 * A magic union of supported socket addresses.
306 struct sockaddr_in sin;
309 /* --- Mapping keyed on addresses --- */
311 typedef struct addrmap {
316 typedef struct addrmap_base {
321 /* --- Sequence number checking --- */
323 typedef struct seqwin {
324 uint32 seq; /* First acceptable input sequence */
325 uint32 win; /* Window of acceptable numbers */
328 #define SEQ_WINSZ 32 /* Bits in sequence number window */
330 /* --- A symmetric keyset --- *
332 * A keyset contains a set of symmetric keys for encrypting and decrypting
333 * packets. Keysets are stored in a list, sorted in reverse order of
334 * creation, so that the most recent keyset (the one most likely to be used)
337 * Each keyset has a time limit and a data limit. The keyset is destroyed
338 * when either it has existed for too long, or it has been used to encrypt
339 * too much data. New key exchanges are triggered when keys are close to
343 enum { DIR_IN, DIR_OUT, NDIR };
346 struct keyset *next; /* Next active keyset in the list */
347 unsigned ref; /* Reference count for keyset */
348 struct peer *p; /* Pointer to peer structure */
349 time_t t_exp; /* Expiry time for this keyset */
350 unsigned long sz_exp, sz_regen; /* Data limits for the keyset */
351 T( unsigned seq; ) /* Sequence number for tracing */
352 unsigned f; /* Various useful flags */
353 bulkctx *bulk; /* Bulk crypto transform */
354 uint32 oseq; /* Outbound sequence number */
355 seqwin iseq; /* Inbound sequence number */
358 #define KSF_LISTEN 1u /* Don't encrypt packets yet */
359 #define KSF_LINK 2u /* Key is in a linked list */
361 #define KSERR_REGEN -1 /* Regenerate keys */
362 #define KSERR_NOKEYS -2 /* No keys left */
363 #define KSERR_DECRYPT -3 /* Unable to decrypt message */
364 #define KSERR_SEQ -4 /* Incorrect sequence number */
365 #define KSERR_MALFORMED -5 /* Input ciphertext is broken */
367 /* --- Key exchange --- *
369 * TrIPE uses the Wrestlers Protocol for its key exchange. The Wrestlers
370 * Protocol has a number of desirable features (e.g., perfect forward
371 * secrecy, and zero-knowledge authentication) which make it attractive for
372 * use in TrIPE. The Wrestlers Protocol was designed by Mark Wooding and
376 typedef struct retry {
377 double t; /* Current retry time */
382 typedef struct kxchal {
383 struct keyexch *kx; /* Pointer back to key exchange */
384 ge *c; /* Responder's challenge */
385 ge *r; /* My reply to the challenge */
386 keyset *ks; /* Pointer to temporary keyset */
387 unsigned f; /* Various useful flags */
388 sel_timer t; /* Response timer for challenge */
389 retry rs; /* Retry state */
390 octet hc[MAXHASHSZ]; /* Hash of his challenge */
391 octet ck[MAXHASHSZ]; /* His magical check value */
392 octet hswrq_in[MAXHASHSZ]; /* Inbound switch request message */
393 octet hswok_in[MAXHASHSZ]; /* Inbound switch confirmation */
394 octet hswrq_out[MAXHASHSZ]; /* Outbound switch request message */
395 octet hswok_out[MAXHASHSZ]; /* Outbound switch confirmation */
398 typedef struct keyexch {
399 struct peer *p; /* Pointer back to the peer */
400 kdata *kpriv; /* Private key and related info */
401 kdata *kpub; /* Peer's public key */
402 keyset **ks; /* Peer's list of keysets */
403 unsigned f; /* Various useful flags */
404 unsigned s; /* Current state in exchange */
405 sel_timer t; /* Timer for next exchange */
406 retry rs; /* Retry state */
407 mp *alpha; /* My temporary secret */
408 ge *c; /* My challenge */
409 ge *rx; /* The expected response */
410 unsigned nr; /* Number of extant responses */
411 time_t t_valid; /* When this exchange goes bad */
412 octet hc[MAXHASHSZ]; /* Hash of my challenge */
413 kxchal *r[KX_NCHAL]; /* Array of challenges */
416 #define KXF_TIMER 1u /* Waiting for a timer to go off */
417 #define KXF_DEAD 2u /* The key-exchanger isn't up */
418 #define KXF_PUBKEY 4u /* Key exchanger has a public key */
419 #define KXF_CORK 8u /* Don't send anything yet */
422 KXS_DEAD, /* Uninitialized state (magical) */
423 KXS_CHAL, /* Main answer-challenges state */
424 KXS_COMMIT, /* Committed: send switch request */
425 KXS_SWITCH /* Switched: send confirmation */
428 /* --- Tunnel structure --- *
430 * Used to maintain system-specific information about the tunnel interface.
433 typedef struct tunnel tunnel;
436 typedef struct tunnel_ops {
437 const char *name; /* Name of this tunnel driver */
438 unsigned flags; /* Various interesting flags */
439 #define TUNF_PRIVOPEN 1u /* Need helper to open file */
440 void (*init)(void); /* Initializes the system */
441 tunnel *(*create)(struct peer */*p*/, int /*fd*/, char **/*ifn*/);
442 /* Initializes a new tunnel */
443 void (*setifname)(tunnel */*t*/, const char */*ifn*/);
444 /* Notifies ifname change */
445 void (*inject)(tunnel */*t*/, buf */*b*/); /* Sends packet through if */
446 void (*destroy)(tunnel */*t*/); /* Destroys a tunnel */
449 #ifndef TUN_INTERNALS
450 struct tunnel { const tunnel_ops *ops; };
453 /* --- Peer statistics --- *
455 * Contains various interesting and not-so-interesting statistics about a
456 * peer. This is updated by various parts of the code. The format of the
457 * structure isn't considered private, and @p_stats@ returns a pointer to the
458 * statistics block for a given peer.
461 typedef struct stats {
462 unsigned long sz_in, sz_out; /* Size of all data in and out */
463 unsigned long sz_kxin, sz_kxout; /* Size of key exchange messages */
464 unsigned long sz_ipin, sz_ipout; /* Size of encapsulated IP packets */
465 time_t t_start, t_last, t_kx; /* Time peer created, last pk, kx */
466 unsigned long n_reject; /* Number of rejected packets */
467 unsigned long n_in, n_out; /* Number of packets in and out */
468 unsigned long n_kxin, n_kxout; /* Number of key exchange packets */
469 unsigned long n_ipin, n_ipout; /* Number of encrypted packets */
472 /* --- Peer structure --- *
474 * The main structure which glues everything else together.
477 typedef struct peerspec {
478 char *name; /* Peer's name */
479 char *privtag; /* Private key tag */
480 char *tag; /* Public key tag */
481 const tunnel_ops *tops; /* Tunnel operations */
482 unsigned long t_ka; /* Keep alive interval */
483 addr sa; /* Socket address to speak to */
484 size_t sasz; /* Socket address size */
485 unsigned f; /* Flags for the peer */
486 #define PSF_KXMASK 255u /* Key-exchange flags to set */
487 #define PSF_MOBILE 256u /* Address may change rapidly */
490 typedef struct peer_byname {
495 typedef struct peer_byaddr {
500 typedef struct peer {
501 peer_byname *byname; /* Lookup-by-name block */
502 peer_byaddr *byaddr; /* Lookup-by-address block */
503 struct ping *pings; /* Pings we're waiting for */
504 peerspec spec; /* Specifications for this peer */
505 tunnel *t; /* Tunnel for local packets */
506 char *ifname; /* Interface name for tunnel */
507 keyset *ks; /* List head for keysets */
508 buf b; /* Buffer for sending packets */
509 stats st; /* Statistics */
510 keyexch kx; /* Key exchange protocol block */
511 sel_timer tka; /* Timer for keepalives */
514 typedef struct peer_iter { sym_iter i; } peer_iter;
516 typedef struct ping {
517 struct ping *next, *prev; /* Links to next and previous */
518 peer *p; /* Peer so we can free it */
519 unsigned msg; /* Kind of response expected */
520 uint32 id; /* Id so we can recognize response */
521 octet magic[32]; /* Some random data */
522 sel_timer t; /* Timeout for ping */
523 void (*func)(int /*rc*/, void */*arg*/); /* Function to call when done */
524 void *arg; /* Argument for callback */
535 /* --- Admin structure --- */
537 #define OBUFSZ 16384u
539 typedef struct obuf {
540 struct obuf *next; /* Next buffer in list */
541 char *p_in, *p_out; /* Pointers into the buffer */
542 char buf[OBUFSZ]; /* The actual buffer */
545 typedef struct oqueue {
546 obuf *hd, *tl; /* Head and tail pointers */
551 typedef struct admin_bgop {
552 struct admin_bgop *next, *prev; /* Links to next and previous */
553 struct admin *a; /* Owner job */
554 char *tag; /* Tag string for messages */
555 void (*cancel)(struct admin_bgop *); /* Destructor function */
558 typedef struct admin_resop {
559 admin_bgop bg; /* Background operation header */
560 char *addr; /* Hostname to be resolved */
561 bres_client r; /* Background resolver task */
562 sel_timer t; /* Timer for resolver */
563 addr sa; /* Socket address */
564 size_t sasz; /* Socket address size */
565 void (*func)(struct admin_resop *, int); /* Handler */
568 enum { ARES_OK, ARES_FAIL };
570 typedef struct admin_addop {
571 admin_resop r; /* Name resolution header */
572 peerspec peer; /* Peer pending creation */
575 typedef struct admin_pingop {
576 admin_bgop bg; /* Background operation header */
577 ping ping; /* Ping pending response */
578 struct timeval pingtime; /* Time last ping was sent */
581 typedef struct admin_service {
582 sym_base _b; /* Hash table base structure */
583 char *version; /* The provided version */
584 struct admin *prov; /* Which client provides me */
585 struct admin_service *next, *prev; /* Client's list of services */
588 typedef struct admin_svcop {
589 admin_bgop bg; /* Background operation header */
590 struct admin *prov; /* Client servicing this job */
591 unsigned index; /* This job's index */
592 struct admin_svcop *next, *prev; /* Links for provider's jobs */
595 typedef struct admin_jobentry {
596 unsigned short seq; /* Zero if unused */
598 admin_svcop *op; /* Operation, if slot in use, ... */
599 uint32 next; /* ... or index of next free slot */
603 typedef struct admin_jobtable {
604 uint32 n, sz; /* Used slots and table size */
605 admin_svcop *active; /* List of active jobs */
606 uint32 free; /* Index of first free slot */
607 admin_jobentry *v; /* And the big array of entries */
611 struct admin *next, *prev; /* Links to next and previous */
612 unsigned f; /* Various useful flags */
613 unsigned ref; /* Reference counter */
615 unsigned seq; /* Sequence number for tracing */
617 oqueue out; /* Output buffer list */
618 oqueue delay; /* Delayed output buffer list */
619 admin_bgop *bg; /* Backgrounded operations */
620 admin_service *svcs; /* Which services I provide */
621 admin_jobtable j; /* Table of outstanding jobs */
622 selbuf b; /* Line buffer for commands */
623 sel_file w; /* Selector for write buffering */
626 #define AF_DEAD 1u /* Destroy this admin block */
627 #define AF_CLOSE 2u /* Client closed connection */
628 #define AF_NOTE 4u /* Catch notifications */
629 #define AF_WARN 8u /* Catch warning messages */
631 #define AF_TRACE 16u /* Catch tracing */
633 #define AF_FOREGROUND 32u /* Quit server when client closes */
636 # define AF_ALLMSGS (AF_NOTE | AF_TRACE | AF_WARN)
638 # define AF_ALLMSGS (AF_NOTE | AF_WARN)
641 /*----- Global variables --------------------------------------------------*/
643 extern sel_state sel; /* Global I/O event state */
644 extern octet buf_i[PKBUFSZ], buf_o[PKBUFSZ], buf_t[PKBUFSZ], buf_u[PKBUFSZ];
645 extern const tunnel_ops *tunnels[]; /* Table of tunnels (0-term) */
646 extern const tunnel_ops *tun_default; /* Default tunnel to use */
647 extern kdata *master; /* Default private key */
648 extern const char *tag_priv; /* Default private key tag */
651 extern const trace_opt tr_opts[]; /* Trace options array */
652 extern unsigned tr_flags; /* Trace options flags */
655 /*----- Other macros ------------------------------------------------------*/
658 do { rand_quick(RAND_GLOBAL); noise_timer(RAND_GLOBAL); } while (0)
660 /*----- Key management ----------------------------------------------------*/
662 /* --- @km_init@ --- *
664 * Arguments: @const char *privkr@ = private keyring file
665 * @const char *pubkr@ = public keyring file
666 * @const char *ptag@ = default private-key tag
670 * Use: Initializes the key-management machinery, loading the
671 * keyrings and so on.
674 extern void km_init(const char */*privkr*/, const char */*pubkr*/,
675 const char */*ptag*/);
677 /* --- @km_reload@ --- *
681 * Returns: Zero if OK, nonzero to force reloading of keys.
683 * Use: Checks the keyrings to see if they need reloading.
686 extern int km_reload(void);
688 /* --- @km_findpub@, @km_findpriv@ --- *
690 * Arguments: @const char *tag@ = key tag to load
692 * Returns: Pointer to the kdata object if successful, or null on error.
694 * Use: Fetches a public or private key from the keyring.
697 extern kdata *km_findpub(const char */*tag*/);
698 extern kdata *km_findpriv(const char */*tag*/);
700 /* --- @km_samealgsp@ --- *
702 * Arguments: @const kdata *kdx, *kdy@ = two key data objects
704 * Returns: Nonzero if their two algorithm selections are the same.
706 * Use: Checks sameness of algorithm selections: used to ensure that
707 * peers are using sensible algorithms.
710 extern int km_samealgsp(const kdata */*kdx*/, const kdata */*kdy*/);
712 /* --- @km_ref@ --- *
714 * Arguments: @kdata *kd@ = pointer to the kdata object
718 * Use: Claim a new reference to a kdata object.
721 extern void km_ref(kdata */*kd*/);
723 /* --- @km_unref@ --- *
725 * Arguments: @kdata *kd@ = pointer to the kdata object
729 * Use: Releases a reference to a kdata object.
732 extern void km_unref(kdata */*kd*/);
734 /* --- @km_tag@ --- *
736 * Arguments: @kdata *kd@ - pointer to the kdata object
738 * Returns: A pointer to the short tag by which the kdata was loaded.
741 extern const char *km_tag(kdata */*kd*/);
743 /*----- Key exchange ------------------------------------------------------*/
745 /* --- @kx_start@ --- *
747 * Arguments: @keyexch *kx@ = pointer to key exchange context
748 * @int forcep@ = nonzero to ignore the quiet timer
752 * Use: Stimulates a key exchange. If a key exchage is in progress,
753 * a new challenge is sent (unless the quiet timer forbids
754 * this); if no exchange is in progress, one is commenced.
757 extern void kx_start(keyexch */*kx*/, int /*forcep*/);
759 /* --- @kx_message@ --- *
761 * Arguments: @keyexch *kx@ = pointer to key exchange context
762 * @unsigned msg@ = the message code
763 * @buf *b@ = pointer to buffer containing the packet
767 * Use: Reads a packet containing key exchange messages and handles
771 extern void kx_message(keyexch */*kx*/, unsigned /*msg*/, buf */*b*/);
773 /* --- @kx_free@ --- *
775 * Arguments: @keyexch *kx@ = pointer to key exchange context
779 * Use: Frees everything in a key exchange context.
782 extern void kx_free(keyexch */*kx*/);
784 /* --- @kx_newkeys@ --- *
786 * Arguments: @keyexch *kx@ = pointer to key exchange context
790 * Use: Informs the key exchange module that its keys may have
791 * changed. If fetching the new keys fails, the peer will be
792 * destroyed, we log messages and struggle along with the old
796 extern void kx_newkeys(keyexch */*kx*/);
798 /* --- @kx_init@ --- *
800 * Arguments: @keyexch *kx@ = pointer to key exchange context
801 * @peer *p@ = pointer to peer context
802 * @keyset **ks@ = pointer to keyset list
803 * @unsigned f@ = various useful flags
805 * Returns: Zero if OK, nonzero if it failed.
807 * Use: Initializes a key exchange module. The module currently
808 * contains no keys, and will attempt to initiate a key
812 extern int kx_init(keyexch */*kx*/, peer */*p*/,
813 keyset **/*ks*/, unsigned /*f*/);
815 /*----- Keysets and symmetric cryptography --------------------------------*/
817 /* --- @ks_drop@ --- *
819 * Arguments: @keyset *ks@ = pointer to a keyset
823 * Use: Decrements a keyset's reference counter. If the counter hits
824 * zero, the keyset is freed.
827 extern void ks_drop(keyset */*ks*/);
829 /* --- @ks_derivekey@ --- *
831 * Arguments: @octet *k@ = pointer to an output buffer of at least
833 * @size_t ksz@ = actual size wanted (for tracing)
834 * @const struct rawkey *rk@ = a raw key, as passed into
836 * @int dir@ = direction for the key (@DIR_IN@ or @DIR_OUT@)
837 * @const char *what@ = label for the key (input to derivation)
841 * Use: Derives a session key, for use on incoming or outgoing data.
842 * This function is part of a private protocol between @ks_gen@
843 * and the bulk crypto transform @genkeys@ operation.
846 extern void ks_derivekey(octet */*k*/, size_t /*ksz*/,
847 const struct rawkey */*rk*/,
848 int /*dir*/, const char */*what*/);
850 /* --- @ks_gen@ --- *
852 * Arguments: @const void *k@ = pointer to key material
853 * @size_t x, y, z@ = offsets into key material (see below)
854 * @peer *p@ = pointer to peer information
856 * Returns: A pointer to the new keyset.
858 * Use: Derives a new keyset from the given key material. The
859 * offsets @x@, @y@ and @z@ separate the key material into three
860 * parts. Between the @k@ and @k + x@ is `my' contribution to
861 * the key material; between @k + x@ and @k + y@ is `your'
862 * contribution; and between @k + y@ and @k + z@ is a shared
863 * value we made together. These are used to construct two
864 * pairs of symmetric keys. Each pair consists of an encryption
865 * key and a message authentication key. One pair is used for
866 * outgoing messages, the other for incoming messages.
868 * The new key is marked so that it won't be selected for output
869 * by @ksl_encrypt@. You can still encrypt data with it by
870 * calling @ks_encrypt@ directly.
873 extern keyset *ks_gen(const void */*k*/,
874 size_t /*x*/, size_t /*y*/, size_t /*z*/,
877 /* --- @ks_activate@ --- *
879 * Arguments: @keyset *ks@ = pointer to a keyset
883 * Use: Activates a keyset, so that it can be used for encrypting
887 extern void ks_activate(keyset */*ks*/);
889 /* --- @ks_encrypt@ --- *
891 * Arguments: @keyset *ks@ = pointer to a keyset
892 * @unsigned ty@ = message type
893 * @buf *b@ = pointer to input buffer
894 * @buf *bb@ = pointer to output buffer
896 * Returns: Zero if successful; @KSERR_REGEN@ if we should negotiate a
897 * new key; @KSERR_NOKEYS@ if the key is not usable. Also
898 * returns zero if there was insufficient buffer (but the output
899 * buffer is broken in this case).
901 * Use: Encrypts a block of data using the key. Note that the `key
902 * ought to be replaced' notification is only ever given once
903 * for each key. Also note that this call forces a keyset to be
904 * used even if it's marked as not for data output.
906 * The encryption transform is permitted to corrupt @buf_u@ for
907 * its own purposes. Neither the source nor destination should
908 * be within @buf_u@; and callers mustn't expect anything stored
909 * in @buf_u@ to still
912 extern int ks_encrypt(keyset */*ks*/, unsigned /*ty*/,
913 buf */*b*/, buf */*bb*/);
915 /* --- @ks_decrypt@ --- *
917 * Arguments: @keyset *ks@ = pointer to a keyset
918 * @unsigned ty@ = expected type code
919 * @buf *b@ = pointer to an input buffer
920 * @buf *bb@ = pointer to an output buffer
922 * Returns: Zero on success; @KSERR_DECRYPT@ on failure. Also returns
923 * zero if there was insufficient buffer (but the output buffer
924 * is broken in this case).
926 * Use: Attempts to decrypt a message using a given key. Note that
927 * requesting decryption with a key directly won't clear a
928 * marking that it's not for encryption.
930 * The decryption transform is permitted to corrupt @buf_u@ for
931 * its own purposes. Neither the source nor destination should
932 * be within @buf_u@; and callers mustn't expect anything stored
933 * in @buf_u@ to still
936 extern int ks_decrypt(keyset */*ks*/, unsigned /*ty*/,
937 buf */*b*/, buf */*bb*/);
939 /* --- @ksl_free@ --- *
941 * Arguments: @keyset **ksroot@ = pointer to keyset list head
945 * Use: Frees (releases references to) all of the keys in a keyset.
948 extern void ksl_free(keyset **/*ksroot*/);
950 /* --- @ksl_link@ --- *
952 * Arguments: @keyset **ksroot@ = pointer to keyset list head
953 * @keyset *ks@ = pointer to a keyset
957 * Use: Links a keyset into a list. A keyset can only be on one list
958 * at a time. Bad things happen otherwise.
961 extern void ksl_link(keyset **/*ksroot*/, keyset */*ks*/);
963 /* --- @ksl_prune@ --- *
965 * Arguments: @keyset **ksroot@ = pointer to keyset list head
969 * Use: Prunes the keyset list by removing keys which mustn't be used
973 extern void ksl_prune(keyset **/*ksroot*/);
975 /* --- @ksl_encrypt@ --- *
977 * Arguments: @keyset **ksroot@ = pointer to keyset list head
978 * @unsigned ty@ = message type
979 * @buf *b@ = pointer to input buffer
980 * @buf *bb@ = pointer to output buffer
982 * Returns: Zero if successful; @KSERR_REGEN@ if it's time to negotiate a
983 * new key; @KSERR_NOKEYS@ if there are no suitable keys
984 * available. Also returns zero if there was insufficient
985 * buffer space (but the output buffer is broken in this case).
987 * Use: Encrypts a packet.
990 extern int ksl_encrypt(keyset **/*ksroot*/, unsigned /*ty*/,
991 buf */*b*/, buf */*bb*/);
993 /* --- @ksl_decrypt@ --- *
995 * Arguments: @keyset **ksroot@ = pointer to keyset list head
996 * @unsigned ty@ = expected type code
997 * @buf *b@ = pointer to input buffer
998 * @buf *bb@ = pointer to output buffer
1000 * Returns: Zero on success; @KSERR_DECRYPT@ on failure. Also returns
1001 * zero if there was insufficient buffer (but the output buffer
1002 * is broken in this case).
1004 * Use: Decrypts a packet.
1007 extern int ksl_decrypt(keyset **/*ksroot*/, unsigned /*ty*/,
1008 buf */*b*/, buf */*bb*/);
1010 /*----- Challenges --------------------------------------------------------*/
1012 /* --- @c_new@ --- *
1014 * Arguments: @buf *b@ = where to put the challenge
1016 * Returns: Zero if OK, nonzero on error.
1018 * Use: Issues a new challenge.
1021 extern int c_new(buf */*b*/);
1023 /* --- @c_check@ --- *
1025 * Arguments: @buf *b@ = where to find the challenge
1027 * Returns: Zero if OK, nonzero if it didn't work.
1029 * Use: Checks a challenge. On failure, the buffer is broken.
1032 extern int c_check(buf */*b*/);
1034 /*----- Administration interface ------------------------------------------*/
1036 #define A_END ((char *)0)
1038 /* --- @a_vformat@ --- *
1040 * Arguments: @dstr *d@ = where to leave the formatted message
1041 * @const char *fmt@ = pointer to format string
1042 * @va_list *ap@ = arguments in list
1046 * Use: Main message token formatting driver. The arguments are
1047 * interleaved formatting tokens and their parameters, finally
1048 * terminated by an entry @A_END@.
1050 * Tokens recognized:
1052 * * "*..." ... -- pretokenized @dstr_putf@-like string
1054 * * "?ADDR" SOCKADDR -- a socket address, to be converted
1056 * * "?B64" BUFFER SIZE -- binary data to be base64-encoded
1058 * * "?TOKENS" VECTOR -- null-terminated vector of tokens
1060 * * "?PEER" PEER -- peer's name
1062 * * "?ERRNO" ERRNO -- system error code
1064 * * "[!]..." ... -- @dstr_putf@-like string as single token
1067 extern void a_vformat(dstr */*d*/, const char */*fmt*/, va_list */*ap*/);
1069 /* --- @a_format@ --- *
1071 * Arguments: @dstr *d@ = where to leave the formatted message
1072 * @const char *fmt@ = pointer to format string
1076 * Use: Writes a tokenized message into a string, for later
1080 extern void EXECL_LIKE(0) a_format(dstr */*d*/, const char */*fmt*/, ...);
1082 /* --- @a_info@ --- *
1084 * Arguments: @admin *a@ = connection
1085 * @const char *fmt@ = format string
1086 * @...@ = other arguments
1090 * Use: Report information to an admin client.
1093 extern void EXECL_LIKE(0) a_info(admin */*a*/, const char */*fmt*/, ...);
1095 /* --- @a_warn@ --- *
1097 * Arguments: @const char *fmt@ = pointer to format string
1098 * @...@ = other arguments
1102 * Use: Informs all admin connections of a warning.
1105 extern void EXECL_LIKE(0) a_warn(const char */*fmt*/, ...);
1107 /* --- @a_notify@ --- *
1109 * Arguments: @const char *fmt@ = pointer to format string
1110 * @...@ = other arguments
1114 * Use: Sends a notification to interested admin connections.
1117 extern void EXECL_LIKE(0) a_notify(const char */*fmt*/, ...);
1119 /* --- @a_create@ --- *
1121 * Arguments: @int fd_in, fd_out@ = file descriptors to use
1122 * @unsigned f@ = initial flags to set
1126 * Use: Creates a new admin connection.
1129 extern void a_create(int /*fd_in*/, int /*fd_out*/, unsigned /*f*/);
1131 /* --- @a_quit@ --- *
1137 * Use: Shuts things down nicely.
1140 extern void a_quit(void);
1142 /* --- @a_preselect@ --- *
1148 * Use: Informs the admin module that we're about to select again,
1149 * and that it should do cleanup things it has delayed until a
1153 extern void a_preselect(void);
1155 /* --- @a_daemon@ --- *
1161 * Use: Informs the admin module that it's a daemon.
1164 extern void a_daemon(void);
1166 /* --- @a_init@ --- *
1168 * Arguments: @const char *sock@ = socket name to create
1169 * @uid_t u@ = user to own the socket
1170 * @gid_t g@ = group to own the socket
1171 * @mode_t m@ = permissions to set on the socket
1175 * Use: Creates the admin listening socket.
1178 extern void a_init(const char */*sock*/,
1179 uid_t /*u*/, gid_t /*g*/, mode_t /*m*/);
1181 /*----- Mapping with addresses as keys ------------------------------------*/
1183 /* --- @am_create@ --- *
1185 * Arguments: @addrmap *m@ = pointer to map
1189 * Use: Create an address map, properly set up.
1192 extern void am_create(addrmap */*m*/);
1194 /* --- @am_destroy@ --- *
1196 * Arguments: @addrmap *m@ = pointer to map
1200 * Use: Destroy an address map, throwing away all the entries.
1203 extern void am_destroy(addrmap */*m*/);
1205 /* --- @am_find@ --- *
1207 * Arguments: @addrmap *m@ = pointer to map
1208 * @const addr *a@ = address to look up
1209 * @size_t sz@ = size of block to allocate
1210 * @unsigned *f@ = where to store flags
1212 * Returns: Pointer to found item, or null.
1214 * Use: Finds a record with the given IP address, set @*f@ nonzero
1215 * and returns it. If @sz@ is zero, and no match was found,
1216 * return null; otherwise allocate a new block of @sz@ bytes,
1217 * clear @*f@ to zero and return the block pointer.
1220 extern void *am_find(addrmap */*m*/, const addr */*a*/,
1221 size_t /*sz*/, unsigned */*f*/);
1223 /* --- @am_remove@ --- *
1225 * Arguments: @addrmap *m@ = pointer to map
1226 * @void *i@ = pointer to the item
1230 * Use: Removes an item from the map.
1233 extern void am_remove(addrmap */*m*/, void */*i*/);
1235 /*----- Privilege separation ----------------------------------------------*/
1237 /* --- @ps_trace@ --- *
1239 * Arguments: @unsigned mask@ = trace mask to check
1240 * @const char *fmt@ = message format
1241 * @...@ = values for placeholders
1245 * Use: Writes a trace message.
1248 T( extern void PRINTF_LIKE(2, 3)
1249 ps_trace(unsigned /*mask*/, const char */*fmt*/, ...); )
1251 /* --- @ps_warn@ --- *
1253 * Arguments: @const char *fmt@ = message format
1254 * @...@ = values for placeholders
1258 * Use: Writes a warning message.
1261 extern void PRINTF_LIKE(1, 2) ps_warn(const char */*fmt*/, ...);
1263 /* --- @ps_tunfd@ --- *
1265 * Arguments: @const tunnel_ops *tops@ = pointer to tunnel operations
1266 * @char **ifn@ = where to put the interface name
1268 * Returns: The file descriptor, or @-1@ on error.
1270 * Use: Fetches a file descriptor for a tunnel driver.
1273 extern int ps_tunfd(const tunnel_ops */*tops*/, char **/*ifn*/);
1275 /* --- @ps_split@ --- *
1277 * Arguments: @int detachp@ = whether to detach the child from its terminal
1281 * Use: Separates off the privileged tunnel-opening service from the
1282 * rest of the server.
1285 extern void ps_split(int /*detachp*/);
1287 /* --- @ps_quit@ --- *
1293 * Use: Detaches from the helper process.
1296 extern void ps_quit(void);
1298 /*----- Peer management ---------------------------------------------------*/
1300 /* --- @p_txstart@ --- *
1302 * Arguments: @peer *p@ = pointer to peer block
1303 * @unsigned msg@ = message type code
1305 * Returns: A pointer to a buffer to write to.
1307 * Use: Starts sending to a peer. Only one send can happen at a
1311 extern buf *p_txstart(peer */*p*/, unsigned /*msg*/);
1313 /* --- @p_txend@ --- *
1315 * Arguments: @peer *p@ = pointer to peer block
1319 * Use: Sends a packet to the peer.
1322 extern void p_txend(peer */*p*/);
1324 /* --- @p_pingsend@ --- *
1326 * Arguments: @peer *p@ = destination peer
1327 * @ping *pg@ = structure to fill in
1328 * @unsigned type@ = message type
1329 * @unsigned long timeout@ = how long to wait before giving up
1330 * @void (*func)(int, void *)@ = callback function
1331 * @void *arg@ = argument for callback
1333 * Returns: Zero if successful, nonzero if it failed.
1335 * Use: Sends a ping to a peer. Call @func@ with a nonzero argument
1336 * if we get an answer within the timeout, or zero if no answer.
1339 extern int p_pingsend(peer */*p*/, ping */*pg*/, unsigned /*type*/,
1340 unsigned long /*timeout*/,
1341 void (*/*func*/)(int, void *), void */*arg*/);
1343 /* --- @p_pingdone@ --- *
1345 * Arguments: @ping *p@ = ping structure
1346 * @int rc@ = return code to pass on
1350 * Use: Disposes of a ping structure, maybe sending a notification.
1353 extern void p_pingdone(ping */*p*/, int /*rc*/);
1355 /* --- @p_greet@ --- *
1357 * Arguments: @peer *p@ = peer to send to
1358 * @const void *c@ = pointer to challenge
1359 * @size_t sz@ = size of challenge
1363 * Use: Sends a greeting packet.
1366 extern void p_greet(peer */*p*/, const void */*c*/, size_t /*sz*/);
1368 /* --- @p_tun@ --- *
1370 * Arguments: @peer *p@ = pointer to peer block
1371 * @buf *b@ = buffer containing incoming packet
1375 * Use: Handles a packet which needs to be sent to a peer.
1378 extern void p_tun(peer */*p*/, buf */*b*/);
1380 /* --- @p_keyreload@ --- *
1386 * Use: Forces a check of the daemon's keyring files.
1389 extern void p_keyreload(void);
1391 /* --- @p_interval@ --- *
1397 * Use: Called periodically to do tidying.
1400 extern void p_interval(void);
1402 /* --- @p_stats@ --- *
1404 * Arguments: @peer *p@ = pointer to a peer block
1406 * Returns: A pointer to the peer's statistics.
1409 extern stats *p_stats(peer */*p*/);
1411 /* --- @p_ifname@ --- *
1413 * Arguments: @peer *p@ = pointer to a peer block
1415 * Returns: A pointer to the peer's interface name.
1418 extern const char *p_ifname(peer */*p*/);
1420 /* --- @p_setifname@ --- *
1422 * Arguments: @peer *p@ = pointer to a peer block
1423 * @const char *name@ = pointer to the new name
1427 * Use: Changes the name held for a peer's interface.
1430 extern void p_setifname(peer */*p*/, const char */*name*/);
1432 /* --- @p_addr@ --- *
1434 * Arguments: @peer *p@ = pointer to a peer block
1436 * Returns: A pointer to the peer's address.
1439 extern const addr *p_addr(peer */*p*/);
1441 /* --- @p_init@ --- *
1443 * Arguments: @struct in_addr addr@ = address to bind to
1444 * @unsigned port@ = port number to listen to
1448 * Use: Initializes the peer system; creates the socket.
1451 extern void p_init(struct in_addr /*addr*/, unsigned /*port*/);
1453 /* --- @p_port@ --- *
1457 * Returns: Port number used for socket.
1460 unsigned p_port(void);
1462 /* --- @p_create@ --- *
1464 * Arguments: @peerspec *spec@ = information about this peer
1466 * Returns: Pointer to the peer block, or null if it failed.
1468 * Use: Creates a new named peer block. No peer is actually attached
1472 extern peer *p_create(peerspec */*spec*/);
1474 /* --- @p_name@ --- *
1476 * Arguments: @peer *p@ = pointer to a peer block
1478 * Returns: A pointer to the peer's name.
1480 * Use: Equivalent to @p_spec(p)->name@.
1483 extern const char *p_name(peer */*p*/);
1485 /* --- @p_tag@ --- *
1487 * Arguments: @peer *p@ = pointer to a peer block
1489 * Returns: A pointer to the peer's public key tag.
1492 extern const char *p_tag(peer */*p*/);
1494 /* --- @p_privtag@ --- *
1496 * Arguments: @peer *p@ = pointer to a peer block
1498 * Returns: A pointer to the peer's private key tag.
1501 extern const char *p_privtag(peer */*p*/);
1503 /* --- @p_spec@ --- *
1505 * Arguments: @peer *p@ = pointer to a peer block
1507 * Returns: Pointer to the peer's specification
1510 extern const peerspec *p_spec(peer */*p*/);
1512 /* --- @p_findbyaddr@ --- *
1514 * Arguments: @const addr *a@ = address to look up
1516 * Returns: Pointer to the peer block, or null if not found.
1518 * Use: Finds a peer by address.
1521 extern peer *p_findbyaddr(const addr */*a*/);
1523 /* --- @p_find@ --- *
1525 * Arguments: @const char *name@ = name to look up
1527 * Returns: Pointer to the peer block, or null if not found.
1529 * Use: Finds a peer by name.
1532 extern peer *p_find(const char */*name*/);
1534 /* --- @p_destroy@ --- *
1536 * Arguments: @peer *p@ = pointer to a peer
1540 * Use: Destroys a peer.
1543 extern void p_destroy(peer */*p*/);
1545 /* --- @FOREACH_PEER@ --- *
1547 * Arguments: @p@ = name to bind to each peer
1548 * @stuff@ = thing to do for each item
1550 * Use: Does something for each current peer.
1553 #define FOREACH_PEER(p, stuff) do { \
1556 for (p_mkiter(&i_); (p = p_next(&i_)) != 0; ) stuff \
1559 /* --- @p_mkiter@ --- *
1561 * Arguments: @peer_iter *i@ = pointer to an iterator
1565 * Use: Initializes the iterator.
1568 extern void p_mkiter(peer_iter */*i*/);
1570 /* --- @p_next@ --- *
1572 * Arguments: @peer_iter *i@ = pointer to an iterator
1574 * Returns: Next peer, or null if at the end.
1576 * Use: Returns the next peer.
1579 extern peer *p_next(peer_iter */*i*/);
1581 /*----- Tunnel drivers ----------------------------------------------------*/
1584 extern const tunnel_ops tun_linux;
1588 extern const tunnel_ops tun_unet;
1592 extern const tunnel_ops tun_bsd;
1595 extern const tunnel_ops tun_slip;
1597 /*----- Other handy utilities ---------------------------------------------*/
1599 /* --- @mpstr@ --- *
1601 * Arguments: @mp *m@ = a multiprecision integer
1603 * Returns: A pointer to the integer's textual representation.
1605 * Use: Converts a multiprecision integer to a string. Corrupts
1609 extern const char *mpstr(mp */*m*/);
1611 /* --- @gestr@ --- *
1613 * Arguments: @group *g@ = a group
1614 * @ge *x@ = a group element
1616 * Returns: A pointer to the element's textual representation.
1618 * Use: Converts a group element to a string. Corrupts
1622 extern const char *gestr(group */*g*/, ge */*x*/);
1624 /* --- @timestr@ --- *
1626 * Arguments: @time_t t@ = a time to convert
1628 * Returns: A pointer to a textual representation of the time.
1630 * Use: Converts a time to a textual representation. Corrupts
1634 extern const char *timestr(time_t /*t*/);
1636 /* --- @mystrieq@ --- *
1638 * Arguments: @const char *x, *y@ = two strings
1640 * Returns: True if @x@ and @y are equal, up to case.
1643 extern int mystrieq(const char */*x*/, const char */*y*/);
1645 /* --- @seq_reset@ --- *
1647 * Arguments: @seqwin *s@ = sequence-checking window
1651 * Use: Resets a sequence number window.
1654 extern void seq_reset(seqwin */*s*/);
1656 /* --- @seq_check@ --- *
1658 * Arguments: @seqwin *s@ = sequence-checking window
1659 * @uint32 q@ = sequence number to check
1660 * @const char *service@ = service to report message from
1662 * Returns: A @SEQ_@ code.
1664 * Use: Checks a sequence number against the window, updating things
1668 extern int seq_check(seqwin */*s*/, uint32 /*q*/, const char */*service*/);
1670 /*----- That's all, folks -------------------------------------------------*/