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 it under
13 * the terms of the GNU General Public License as published by the Free
14 * Software Foundation; either version 3 of the License, or (at your
15 * option) any later version.
17 * TrIPE is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
22 * You should have received a copy of the GNU General Public License
23 * along with TrIPE. If not, see <https://www.gnu.org/licenses/>.
33 /*----- Header files ------------------------------------------------------*/
49 #include <sys/types.h>
56 #include <sys/socket.h>
58 #include <netinet/in.h>
59 #include <arpa/inet.h>
66 # define ADNS_FEATURE_MANYAF
70 #include <mLib/alloc.h>
71 #include <mLib/arena.h>
72 #include <mLib/base64.h>
74 # include <mLib/bres.h>
76 #include <mLib/codec.h>
77 #include <mLib/daemonize.h>
78 #include <mLib/dstr.h>
80 #include <mLib/fdflags.h>
81 #include <mLib/fdpass.h>
82 #include <mLib/fwatch.h>
83 #include <mLib/hash.h>
84 #include <mLib/macros.h>
85 #include <mLib/mdup.h>
86 #include <mLib/mdwopt.h>
87 #include <mLib/quis.h>
88 #include <mLib/report.h>
90 #include <mLib/selbuf.h>
94 #include <mLib/trace.h>
96 #include <mLib/versioncmp.h>
98 #include <catacomb/buf.h>
99 #include <catacomb/ct.h>
101 #include <catacomb/chacha.h>
102 #include <catacomb/gaead.h>
103 #include <catacomb/gcipher.h>
104 #include <catacomb/gmac.h>
105 #include <catacomb/grand.h>
106 #include <catacomb/latinpoly.h>
107 #include <catacomb/key.h>
108 #include <catacomb/paranoia.h>
109 #include <catacomb/poly1305.h>
110 #include <catacomb/salsa20.h>
112 #include <catacomb/noise.h>
113 #include <catacomb/rand.h>
115 #include <catacomb/mp.h>
116 #include <catacomb/mpmont.h>
117 #include <catacomb/mprand.h>
118 #include <catacomb/dh.h>
119 #include <catacomb/ec.h>
120 #include <catacomb/ec-raw.h>
121 #include <catacomb/ec-keys.h>
122 #include <catacomb/x25519.h>
123 #include <catacomb/x448.h>
126 #include "protocol.h"
132 /*----- Magic numbers -----------------------------------------------------*/
134 /* --- Trace flags --- */
142 #define T_KEYEXCH 64u
143 #define T_KEYMGMT 128u
145 /* T_PRIVSEP in priv.h */
151 #define SEC(n) (n##u)
152 #define MIN(n) (n##u * 60u)
153 #define F_2P32 (65536.0*65536.0)
154 #define MEG(n) (n##ul * 1024ul * 1024ul)
156 /* --- Timing parameters --- */
158 #define T_EXP MIN(60) /* Expiry time for a key */
159 #define T_REGEN MIN(40) /* Regeneration time for a key */
161 #define T_VALID SEC(20) /* Challenge validity period */
162 #define T_RETRYMIN SEC(2) /* Minimum retry interval */
163 #define T_RETRYMAX MIN(5) /* Maximum retry interval */
164 #define T_RETRYGROW (5.0/4.0) /* Retry interval growth factor */
166 #define T_WOBBLE (1.0/3.0) /* Relative timer randomness */
168 /* --- Other things --- */
170 #define PKBUFSZ 65536
172 /*----- Cipher selections -------------------------------------------------*/
174 typedef struct keyset keyset;
175 typedef struct algswitch algswitch;
176 typedef struct kdata kdata;
177 typedef struct admin admin;
179 typedef struct dhgrp {
180 const struct dhops *ops;
184 typedef struct dhsc dhsc;
185 typedef struct dhge dhge;
188 DHFMT_STD, /* Fixed-width format, suitable for encryption */
189 DHFMT_HASH, /* Deterministic format, suitable for hashing */
190 DHFMT_VAR /* Variable-width-format, mostly a bad idea */
193 typedef struct deriveargs {
194 const char *what; /* Operation name (hashed) */
195 unsigned f; /* Flags */
196 #define DF_IN 1u /* Make incoming key */
197 #define DF_OUT 2u /* Make outgoing key */
198 const gchash *hc; /* Hash class */
199 const octet *k; /* Pointer to contributions */
200 size_t x, y, z; /* Markers in contributions */
203 typedef struct bulkalgs {
204 const struct bulkops *ops;
207 typedef struct bulkctx {
208 const struct bulkops *ops;
211 typedef struct bulkchal {
212 const struct bulkops *ops;
216 typedef struct dhops {
219 int (*ldpriv)(key_file */*kf*/, key */*k*/, key_data */*d*/,
220 kdata */*kd*/, dstr */*t*/, dstr */*e*/);
221 /* Load a private key from @d@, storing the data in @kd@. The key's
222 * file and key object are in @kf@ and @k@, mostly in case its
223 * attributes are interesting; the key tag is in @t@; errors are
224 * reported by writing tokens to @e@ and returning nonzero.
227 int (*ldpub)(key_file */*kf*/, key */*k*/, key_data */*d*/,
228 kdata */*kd*/, dstr */*t*/, dstr */*e*/);
229 /* Load a public key from @d@, storing the data in @kd@. The key's
230 * file and key object are in @kf@ and @k@, mostly in case its
231 * attributes are interesting; the key tag is in @t@; errors are
232 * reported by writing tokens to @e@ and returning nonzero.
235 const char *(*checkgrp)(const dhgrp */*g*/);
236 /* Check that the group is valid; return null on success, or an error
240 void (*grpinfo)(const dhgrp */*g*/, admin */*a*/);
241 /* Report on the group to an admin client. */
243 T( void (*tracegrp)(const dhgrp */*g*/); )
244 /* Trace a description of the group. */
246 int (*samegrpp)(const dhgrp */*g*/, const dhgrp */*gg*/);
247 /* Return nonzero if the two group objects represent the same
251 void (*freegrp)(dhgrp */*g*/);
252 /* Free a group and the resources it holds. */
254 dhsc *(*ldsc)(const dhgrp */*g*/, const void */*p*/, size_t /*sz*/);
255 /* Load a scalar from @p@, @sz@ and return it. Return null on
259 int (*stsc)(const dhgrp */*g*/,
260 void */*p*/, size_t /*sz*/, const dhsc */*x*/);
261 /* Store a scalar at @p@, @sz@. Return nonzero on error. */
263 dhsc *(*randsc)(const dhgrp */*g*/);
264 /* Return a random scalar. */
266 T( const char *(*scstr)(const dhgrp */*g*/, const dhsc */*x*/); )
267 /* Return a human-readable representation of @x@; @buf_t@ may be used
271 void (*freesc)(const dhgrp */*g*/, dhsc */*x*/);
272 /* Free a scalar and the resources it holds. */
274 dhge *(*ldge)(const dhgrp */*g*/, buf */*b*/, int /*fmt*/);
275 /* Load a group element from @b@, encoded using format @fmt@. Return
279 int (*stge)(const dhgrp */*g*/, buf */*b*/,
280 const dhge */*Y*/, int /*fmt*/);
281 /* Store a group element in @b@, encoded using format @fmt@. Return
285 int (*checkge)(const dhgrp */*h*/, const dhge */*Y*/);
286 /* Check a group element for validity. Return zero if everything
287 * checks out; nonzero on failure.
290 int (*eq)(const dhgrp */*g*/, const dhge */*Y*/, const dhge */*Z*/);
291 /* Return nonzero if @Y@ and @Z@ are equal. */
293 dhge *(*mul)(const dhgrp */*g*/, const dhsc */*x*/, const dhge */*Y*/);
294 /* Multiply a group element by a scalar, resulting in a shared-secret
295 * group element. If @y@ is null, then multiply the well-known
299 T( const char *(*gestr)(const dhgrp */*g*/, const dhge */*Y*/); )
300 /* Return a human-readable representation of @Y@; @buf_t@ may be used
304 void (*freege)(const dhgrp */*g*/, dhge */*Y*/);
305 /* Free a group element and the resources it holds. */
309 typedef struct bulkops {
312 bulkalgs *(*getalgs)(const algswitch */*asw*/, dstr */*e*/,
313 key_file */*kf*/, key */*k*/);
314 /* Determine algorithms to use and return a @bulkalgs@ object
315 * representing the decision. On error, write tokens to @e@ and
319 T( void (*tracealgs)(const bulkalgs */*a*/); )
320 /* Write trace information about the algorithm selection. */
322 int (*checkalgs)(bulkalgs */*a*/, const algswitch */*asw*/, dstr */*e*/);
323 /* Check that the algorithms in @a@ and @asw@ are acceptable. On
324 * error, write tokens to @e@ and return @-1@; otherwise return zero.
327 int (*samealgsp)(const bulkalgs */*a*/, const bulkalgs */*aa*/);
328 /* If @a@ and @aa@ represent the same algorithm selection, return
329 * nonzero; if not, return zero.
332 void (*alginfo)(const bulkalgs */*a*/, admin */*adm*/);
333 /* Report on the algorithm selection to an admin client: call
334 * @a_info@ with appropriate key-value pairs.
337 size_t (*overhead)(const bulkalgs */*a*/);
338 /* Return the per-packet overhead of the bulk transform, in bytes. */
340 size_t (*expsz)(const bulkalgs */*a*/);
341 /* Return the total size limit for the bulk transform, in bytes,
342 * after which the keys must no longer be used.
345 bulkctx *(*genkeys)(const bulkalgs */*a*/, const deriveargs */*a*/);
346 /* Generate session keys and construct and return an appropriate
347 * context for using them. The offsets @a->x@, @a->y@ and @a->z@
348 * separate the key material into three parts. Between @a->k@ and
349 * @a->k + a->x@ is `my' contribution to the key material; between
350 * @a->k + a->x@ and @a->k + a->y@ is `your' contribution; and
351 * between @a->k + a->y@ and @a->k + a->z@ is a shared value we made
352 * together. These are used to construct (up to) two collections of
353 * symmetric keys: one for outgoing messages, the other for incoming
354 * messages. If @a->x == 0@ (or @a->y == a->x@) then my (or your)
355 * contribution is omitted.
358 bulkchal *(*genchal)(const bulkalgs */*a*/);
359 /* Construct and return a challenge issuing and verification
360 * context with a fresh random key.
363 void (*freealgs)(bulkalgs */*a*/);
364 /* Release an algorithm selection object. (Associated bulk
365 * encryption contexts and challenge contexts may still exist and
366 * must remain valid.)
369 int (*encrypt)(bulkctx */*bc*/, unsigned /*ty*/,
370 buf */*b*/, buf */*bb*/, uint32 /*seq*/);
371 /* Encrypt the packet in @b@, with type @ty@ (which doesn't need
372 * encoding separately) and sequence number @seq@ (which must be
373 * recoverable by @decrypt@), and write the result to @bb@. On
374 * error, return a @KSERR_...@ code and/or break the output buffer.
377 int (*decrypt)(bulkctx */*bc*/, unsigned /*ty*/,
378 buf */*b*/, buf */*bb*/, uint32 */*seq*/);
379 /* Decrypt the packet in @b@, with type @ty@, writing the result to
380 * @bb@ and storing the incoming (claimed) sequence number in @seq@.
381 * On error, return a @KSERR_...@ code.
384 void (*freectx)(bulkctx */*a*/);
385 /* Release a bulk encryption context and the resources it holds. */
387 int (*chaltag)(bulkchal */*bc*/, const void */*m*/, size_t /*msz*/,
388 uint32 /*seq*/, void */*t*/);
389 /* Calculate a tag for the challenge in @m@, @msz@, with the sequence
390 * number @seq@, and write it to @t@. Return @-1@ on error, zero on
394 int (*chalvrf)(bulkchal */*bc*/, const void */*m*/, size_t /*msz*/,
395 uint32 /*seq*/, const void */*t*/);
396 /* Check the tag @t@ on @m@, @msz@ and @seq@: return zero if the tag
397 * is OK, nonzero if it's bad.
400 void (*freechal)(bulkchal */*bc*/);
401 /* Release a challenge context and the resources it holds. */
406 const gchash *h; size_t hashsz; /* Hash function */
407 const gccipher *mgf; /* Mask-generation function */
408 bulkalgs *bulk; /* Bulk crypto algorithms */
412 unsigned ref; /* Reference counter */
413 struct knode *kn; /* Pointer to cache entry */
414 uint32 id; /* The underlying key's id */
415 char *tag; /* Full tag name of the key */
416 dhgrp *grp; /* The group we work in */
417 dhsc *k; /* The private key (or null) */
418 dhge *K; /* The public key */
419 time_t t_exp; /* Expiry time of the key */
420 algswitch algs; /* Collection of algorithms */
423 typedef struct knode {
424 sym_base _b; /* Symbol table intrusion */
425 unsigned f; /* Various flags */
426 #define KNF_BROKEN 1u /* Don't use this key any more */
427 struct keyhalf *kh; /* Pointer to the home keyhalf */
428 kdata *kd; /* Pointer to the key data */
431 #define MAXHASHSZ 64 /* Largest possible hash size */
433 #define HASH_STRING(h, s) GH_HASH((h), (s), sizeof(s))
435 extern const dhops dhtab[];
436 extern const bulkops bulktab[];
438 /*----- Data structures ---------------------------------------------------*/
440 /* --- The address-family table --- */
447 #define ENUM(af, qf) AFIX_##af,
453 extern const struct addrfam {
461 /* --- Socket addresses --- *
463 * A magic union of supported socket addresses.
468 struct sockaddr_in sin;
469 struct sockaddr_in6 sin6;
472 /* --- Mapping keyed on addresses --- */
474 typedef struct addrmap {
479 typedef struct addrmap_base {
484 /* --- Sequence number checking --- */
486 typedef struct seqwin {
487 uint32 seq; /* First acceptable input sequence */
488 uint32 win; /* Window of acceptable numbers */
491 #define SEQ_WINSZ 32 /* Bits in sequence number window */
493 /* --- A symmetric keyset --- *
495 * A keyset contains a set of symmetric keys for encrypting and decrypting
496 * packets. Keysets are stored in a list, sorted in reverse order of
497 * creation, so that the most recent keyset (the one most likely to be used)
500 * Each keyset has a time limit and a data limit. The keyset is destroyed
501 * when either it has existed for too long, or it has been used to encrypt
502 * too much data. New key exchanges are triggered when keys are close to
506 enum { DIR_IN, DIR_OUT, NDIR };
509 struct keyset *next; /* Next active keyset in the list */
510 unsigned ref; /* Reference count for keyset */
511 struct peer *p; /* Pointer to peer structure */
512 time_t t_exp; /* Expiry time for this keyset */
513 unsigned long sz_exp, sz_regen; /* Data limits for the keyset */
514 T( unsigned seq; ) /* Sequence number for tracing */
515 unsigned f; /* Various useful flags */
516 bulkctx *bulk; /* Bulk crypto transform */
517 uint32 oseq; /* Outbound sequence number */
518 seqwin iseq; /* Inbound sequence number */
521 #define KSF_LISTEN 1u /* Don't encrypt packets yet */
522 #define KSF_LINK 2u /* Key is in a linked list */
524 #define KSERR_REGEN -1 /* Regenerate keys */
525 #define KSERR_NOKEYS -2 /* No keys left */
526 #define KSERR_DECRYPT -3 /* Unable to decrypt message */
527 #define KSERR_SEQ -4 /* Incorrect sequence number */
528 #define KSERR_MALFORMED -5 /* Input ciphertext is broken */
530 /* --- Key exchange --- *
532 * TrIPE uses the Wrestlers Protocol for its key exchange. The Wrestlers
533 * Protocol has a number of desirable features (e.g., perfect forward
534 * secrecy, and zero-knowledge authentication) which make it attractive for
535 * use in TrIPE. The Wrestlers Protocol was designed by Mark Wooding and
539 typedef struct retry {
540 double t; /* Current retry time */
545 typedef struct kxchal {
546 struct keyexch *kx; /* Pointer back to key exchange */
547 dhge *C; /* Responder's challenge */
548 dhge *R; /* My reply to the challenge */
549 keyset *ks; /* Pointer to temporary keyset */
550 unsigned f; /* Various useful flags */
551 sel_timer t; /* Response timer for challenge */
552 retry rs; /* Retry state */
553 octet hc[MAXHASHSZ]; /* Hash of his challenge */
554 octet ck[MAXHASHSZ]; /* His magical check value */
555 octet hswrq_in[MAXHASHSZ]; /* Inbound switch request message */
556 octet hswok_in[MAXHASHSZ]; /* Inbound switch confirmation */
557 octet hswrq_out[MAXHASHSZ]; /* Outbound switch request message */
558 octet hswok_out[MAXHASHSZ]; /* Outbound switch confirmation */
561 typedef struct keyexch {
562 struct peer *p; /* Pointer back to the peer */
563 kdata *kpriv; /* Private key and related info */
564 kdata *kpub; /* Peer's public key */
565 keyset **ks; /* Peer's list of keysets */
566 unsigned f; /* Various useful flags */
567 unsigned s; /* Current state in exchange */
568 sel_timer t; /* Timer for next exchange */
569 retry rs; /* Retry state */
570 dhsc *a; /* My temporary secret */
571 dhge *C; /* My challenge */
572 dhge *RX; /* The expected response */
573 unsigned nr; /* Number of extant responses */
574 time_t t_valid; /* When this exchange goes bad */
575 octet hc[MAXHASHSZ]; /* Hash of my challenge */
576 kxchal *r[KX_NCHAL]; /* Array of challenges */
579 #define KXF_TIMER 1u /* Waiting for a timer to go off */
580 #define KXF_DEAD 2u /* The key-exchanger isn't up */
581 #define KXF_PUBKEY 4u /* Key exchanger has a public key */
582 #define KXF_CORK 8u /* Don't send anything yet */
585 KXS_DEAD, /* Uninitialized state (magical) */
586 KXS_CHAL, /* Main answer-challenges state */
587 KXS_COMMIT, /* Committed: send switch request */
588 KXS_SWITCH /* Switched: send confirmation */
591 /* --- Tunnel structure --- *
593 * Used to maintain system-specific information about the tunnel interface.
596 typedef struct tunnel tunnel;
599 typedef struct tunnel_ops {
600 const char *name; /* Name of this tunnel driver */
601 unsigned flags; /* Various interesting flags */
602 #define TUNF_PRIVOPEN 1u /* Need helper to open file */
603 int (*init)(void); /* Initializes the system */
604 tunnel *(*create)(struct peer */*p*/, int /*fd*/, char **/*ifn*/);
605 /* Initializes a new tunnel */
606 void (*setifname)(tunnel */*t*/, const char */*ifn*/);
607 /* Notifies ifname change */
608 void (*inject)(tunnel */*t*/, buf */*b*/); /* Sends packet through if */
609 void (*destroy)(tunnel */*t*/); /* Destroys a tunnel */
612 #ifndef TUN_INTERNALS
613 struct tunnel { const tunnel_ops *ops; };
616 typedef struct tun_iter {
617 const struct tunnel_node *next;
620 /* --- Peer statistics --- *
622 * Contains various interesting and not-so-interesting statistics about a
623 * peer. This is updated by various parts of the code. The format of the
624 * structure isn't considered private, and @p_stats@ returns a pointer to the
625 * statistics block for a given peer.
628 typedef struct stats {
629 unsigned long sz_in, sz_out; /* Size of all data in and out */
630 unsigned long sz_kxin, sz_kxout; /* Size of key exchange messages */
631 unsigned long sz_ipin, sz_ipout; /* Size of encapsulated IP packets */
632 time_t t_start, t_last, t_kx; /* Time peer created, last pk, kx */
633 unsigned long n_reject; /* Number of rejected packets */
634 unsigned long n_in, n_out; /* Number of packets in and out */
635 unsigned long n_kxin, n_kxout; /* Number of key exchange packets */
636 unsigned long n_ipin, n_ipout; /* Number of encrypted packets */
639 /* --- Peer structure --- *
641 * The main structure which glues everything else together.
644 typedef struct peerspec {
645 char *name; /* Peer's name */
646 char *privtag; /* Private key tag */
647 char *tag; /* Public key tag */
648 char *knock; /* Knock string, or null */
649 const tunnel_ops *tops; /* Tunnel operations */
650 unsigned long t_ka; /* Keep alive interval */
651 addr sa; /* Socket address to speak to */
652 unsigned f; /* Flags for the peer */
653 #define PSF_KXMASK 255u /* Key-exchange flags to set */
654 #define PSF_MOBILE 256u /* Address may change rapidly */
655 #define PSF_EPHEM 512u /* Association is ephemeral */
658 typedef struct peer_byname {
663 typedef struct peer_byaddr {
668 typedef struct peer {
669 peer_byname *byname; /* Lookup-by-name block */
670 peer_byaddr *byaddr; /* Lookup-by-address block */
671 struct ping *pings; /* Pings we're waiting for */
672 peerspec spec; /* Specifications for this peer */
673 int afix; /* Index of address family */
674 tunnel *t; /* Tunnel for local packets */
675 char *ifname; /* Interface name for tunnel */
676 keyset *ks; /* List head for keysets */
677 buf b; /* Buffer for sending packets */
678 stats st; /* Statistics */
679 keyexch kx; /* Key exchange protocol block */
680 sel_timer tka; /* Timer for keepalives */
683 typedef struct peer_iter { sym_iter i; } peer_iter;
685 typedef struct udpsocket {
686 sel_file sf; /* Selector for the socket */
687 unsigned port; /* Chosen port number */
690 typedef struct ping {
691 struct ping *next, *prev; /* Links to next and previous */
692 peer *p; /* Peer so we can free it */
693 unsigned msg; /* Kind of response expected */
694 uint32 id; /* Id so we can recognize response */
695 octet magic[32]; /* Some random data */
696 sel_timer t; /* Timeout for ping */
697 void (*func)(int /*rc*/, void */*arg*/); /* Function to call when done */
698 void *arg; /* Argument for callback */
709 /* --- Admin structure --- */
711 #define OBUFSZ 16384u
713 typedef struct obuf {
714 struct obuf *next; /* Next buffer in list */
715 char *p_in, *p_out; /* Pointers into the buffer */
716 char buf[OBUFSZ]; /* The actual buffer */
719 typedef struct oqueue {
720 obuf *hd, *tl; /* Head and tail pointers */
725 typedef struct admin_bgop {
726 struct admin_bgop *next, *prev; /* Links to next and previous */
727 struct admin *a; /* Owner job */
728 char *tag; /* Tag string for messages */
729 void (*cancel)(struct admin_bgop *); /* Destructor function */
732 typedef struct admin_resop {
733 admin_bgop bg; /* Background operation header */
734 char *addr; /* Hostname to be resolved */
738 bres_client r; /* Background resolver task */
740 sel_timer t; /* Timer for resolver */
741 addr sa; /* Socket address */
742 unsigned port; /* Port number chosen */
743 size_t sasz; /* Socket address size */
744 void (*func)(struct admin_resop *, int); /* Handler */
747 enum { ARES_OK, ARES_FAIL };
749 typedef struct admin_addop {
750 admin_resop r; /* Name resolution header */
751 peerspec peer; /* Peer pending creation */
754 typedef struct admin_pingop {
755 admin_bgop bg; /* Background operation header */
756 ping ping; /* Ping pending response */
757 struct timeval pingtime; /* Time last ping was sent */
760 typedef struct admin_service {
761 sym_base _b; /* Hash table base structure */
762 char *version; /* The provided version */
763 struct admin *prov; /* Which client provides me */
764 struct admin_service *next, *prev; /* Client's list of services */
767 typedef struct admin_svcop {
768 admin_bgop bg; /* Background operation header */
769 struct admin *prov; /* Client servicing this job */
770 unsigned index; /* This job's index */
771 struct admin_svcop *next, *prev; /* Links for provider's jobs */
774 typedef struct admin_jobentry {
775 unsigned short seq; /* Zero if unused */
777 admin_svcop *op; /* Operation, if slot in use, ... */
778 uint32 next; /* ... or index of next free slot */
782 typedef struct admin_jobtable {
783 uint32 n, sz; /* Used slots and table size */
784 admin_svcop *active; /* List of active jobs */
785 uint32 free; /* Index of first free slot */
786 admin_jobentry *v; /* And the big array of entries */
790 struct admin *next, *prev; /* Links to next and previous */
791 unsigned f; /* Various useful flags */
792 unsigned ref; /* Reference counter */
794 unsigned seq; /* Sequence number for tracing */
796 oqueue out; /* Output buffer list */
797 oqueue delay; /* Delayed output buffer list */
798 admin_bgop *bg; /* Backgrounded operations */
799 admin_service *svcs; /* Which services I provide */
800 admin_jobtable j; /* Table of outstanding jobs */
801 selbuf b; /* Line buffer for commands */
802 sel_file w; /* Selector for write buffering */
805 #define AF_DEAD 1u /* Destroy this admin block */
806 #define AF_CLOSE 2u /* Client closed connection */
807 #define AF_NOTE 4u /* Catch notifications */
808 #define AF_WARN 8u /* Catch warning messages */
810 # define AF_TRACE 16u /* Catch tracing */
812 #define AF_FOREGROUND 32u /* Quit server when client closes */
815 # define AF_ALLMSGS (AF_NOTE | AF_TRACE | AF_WARN)
817 # define AF_ALLMSGS (AF_NOTE | AF_WARN)
820 /*----- Global variables --------------------------------------------------*/
822 extern sel_state sel; /* Global I/O event state */
823 extern octet buf_i[PKBUFSZ], buf_o[PKBUFSZ], buf_t[PKBUFSZ], buf_u[PKBUFSZ];
824 extern udpsocket udpsock[NADDRFAM]; /* The master UDP sockets */
825 extern kdata *master; /* Default private key */
826 extern char *tag_priv; /* Default private key tag */
829 extern const trace_opt tr_opts[]; /* Trace options array */
830 extern unsigned tr_flags; /* Trace options flags */
833 /*----- Other macros ------------------------------------------------------*/
836 do { rand_quick(RAND_GLOBAL); noise_timer(RAND_GLOBAL); } while (0)
838 /*----- Key management ----------------------------------------------------*/
840 /* --- @km_init@ --- *
842 * Arguments: @const char *privkr@ = private keyring file
843 * @const char *pubkr@ = public keyring file
844 * @const char *ptag@ = default private-key tag
846 * Returns: Zero on success, @-1@ on failure.
848 * Use: Initializes the key-management machinery, loading the
849 * keyrings and so on.
852 extern int km_init(const char */*privkr*/, const char */*pubkr*/,
853 const char */*ptag*/);
855 /* --- @km_reload@ --- *
859 * Returns: Zero if OK, nonzero to force reloading of keys.
861 * Use: Checks the keyrings to see if they need reloading.
864 extern int km_reload(void);
866 /* --- @km_clear@ --- *
872 * Use: Forget the currently loaded keyrings. The @master@ key will
873 * be cleared, but other keys already loaded will continue to
874 * exist until their reference count drops to zero. Call
875 * @km_init@ to make everything work again.
878 extern void km_clear(void);
880 /* --- @km_findpub@, @km_findpriv@ --- *
882 * Arguments: @const char *tag@ = key tag to load
884 * Returns: Pointer to the kdata object if successful, or null on error.
886 * Use: Fetches a public or private key from the keyring.
889 extern kdata *km_findpub(const char */*tag*/);
890 extern kdata *km_findpriv(const char */*tag*/);
892 /* --- @km_findpubbyid@, @km_findprivbyid@ --- *
894 * Arguments: @uint32 id@ = key id to load
896 * Returns: Pointer to the kdata object if successful, or null on error.
898 * Use: Fetches a public or private key from the keyring given its
902 extern kdata *km_findpubbyid(uint32 /*id*/);
903 extern kdata *km_findprivbyid(uint32 /*id*/);
905 /* --- @km_samealgsp@ --- *
907 * Arguments: @const kdata *kdx, *kdy@ = two key data objects
909 * Returns: Nonzero if their two algorithm selections are the same.
911 * Use: Checks sameness of algorithm selections: used to ensure that
912 * peers are using sensible algorithms.
915 extern int km_samealgsp(const kdata */*kdx*/, const kdata */*kdy*/);
917 /* --- @km_ref@ --- *
919 * Arguments: @kdata *kd@ = pointer to the kdata object
923 * Use: Claim a new reference to a kdata object.
926 extern void km_ref(kdata */*kd*/);
928 /* --- @km_unref@ --- *
930 * Arguments: @kdata *kd@ = pointer to the kdata object
934 * Use: Releases a reference to a kdata object.
937 extern void km_unref(kdata */*kd*/);
939 /* --- @km_tag@ --- *
941 * Arguments: @kdata *kd@ - pointer to the kdata object
943 * Returns: A pointer to the short tag by which the kdata was loaded.
946 extern const char *km_tag(kdata */*kd*/);
948 /*----- Key exchange ------------------------------------------------------*/
950 /* --- @kx_start@ --- *
952 * Arguments: @keyexch *kx@ = pointer to key exchange context
953 * @int forcep@ = nonzero to ignore the quiet timer
957 * Use: Stimulates a key exchange. If a key exchage is in progress,
958 * a new challenge is sent (unless the quiet timer forbids
959 * this); if no exchange is in progress, one is commenced.
962 extern void kx_start(keyexch */*kx*/, int /*forcep*/);
964 /* --- @kx_message@ --- *
966 * Arguments: @keyexch *kx@ = pointer to key exchange context
967 * @const addr *a@ = sender's IP address and port
968 * @unsigned msg@ = the message code
969 * @buf *b@ = pointer to buffer containing the packet
971 * Returns: Nonzero if the sender's address was unknown.
973 * Use: Reads a packet containing key exchange messages and handles
977 extern int kx_message(keyexch */*kx*/, const addr */*a*/,
978 unsigned /*msg*/, buf */*b*/);
980 /* --- @kx_free@ --- *
982 * Arguments: @keyexch *kx@ = pointer to key exchange context
986 * Use: Frees everything in a key exchange context.
989 extern void kx_free(keyexch */*kx*/);
991 /* --- @kx_newkeys@ --- *
993 * Arguments: @keyexch *kx@ = pointer to key exchange context
997 * Use: Informs the key exchange module that its keys may have
998 * changed. If fetching the new keys fails, the peer will be
999 * destroyed, we log messages and struggle along with the old
1003 extern void kx_newkeys(keyexch */*kx*/);
1005 /* --- @kx_setup@ --- *
1007 * Arguments: @keyexch *kx@ = pointer to key exchange context
1008 * @peer *p@ = pointer to peer context
1009 * @keyset **ks@ = pointer to keyset list
1010 * @unsigned f@ = various useful flags
1012 * Returns: Zero if OK, nonzero if it failed.
1014 * Use: Initializes a key exchange module. The module currently
1015 * contains no keys, and will attempt to initiate a key
1019 extern int kx_setup(keyexch */*kx*/, peer */*p*/,
1020 keyset **/*ks*/, unsigned /*f*/);
1022 /* --- @kx_init@ --- *
1028 * Use: Initializes the key-exchange logic.
1031 extern void kx_init(void);
1033 /*----- Keysets and symmetric cryptography --------------------------------*/
1035 /* --- @ks_drop@ --- *
1037 * Arguments: @keyset *ks@ = pointer to a keyset
1041 * Use: Decrements a keyset's reference counter. If the counter hits
1042 * zero, the keyset is freed.
1045 extern void ks_drop(keyset */*ks*/);
1047 /* --- @ks_gen@ --- *
1049 * Arguments: @deriveargs *a@ = key derivation parameters (modified)
1050 * @peer *p@ = pointer to peer information
1052 * Returns: A pointer to the new keyset.
1054 * Use: Derives a new keyset from the given key material. This will
1055 * set the @what@, @f@, and @hc@ members in @*a@; other members
1056 * must be filled in by the caller.
1058 * The new key is marked so that it won't be selected for output
1059 * by @ksl_encrypt@. You can still encrypt data with it by
1060 * calling @ks_encrypt@ directly.
1063 extern keyset *ks_gen(deriveargs */*a*/, peer */*p*/);
1065 /* --- @ks_activate@ --- *
1067 * Arguments: @keyset *ks@ = pointer to a keyset
1071 * Use: Activates a keyset, so that it can be used for encrypting
1072 * outgoing messages.
1075 extern void ks_activate(keyset */*ks*/);
1077 /* --- @ks_encrypt@ --- *
1079 * Arguments: @keyset *ks@ = pointer to a keyset
1080 * @unsigned ty@ = message type
1081 * @buf *b@ = pointer to input buffer
1082 * @buf *bb@ = pointer to output buffer
1084 * Returns: Zero if successful; @KSERR_REGEN@ if we should negotiate a
1085 * new key; @KSERR_NOKEYS@ if the key is not usable. Also
1086 * returns zero if there was insufficient buffer (but the output
1087 * buffer is broken in this case).
1089 * Use: Encrypts a block of data using the key. Note that the `key
1090 * ought to be replaced' notification is only ever given once
1091 * for each key. Also note that this call forces a keyset to be
1092 * used even if it's marked as not for data output.
1094 * The encryption transform is permitted to corrupt @buf_u@ for
1095 * its own purposes. Neither the source nor destination should
1096 * be within @buf_u@; and callers mustn't expect anything stored
1097 * in @buf_u@ to still
1100 extern int ks_encrypt(keyset */*ks*/, unsigned /*ty*/,
1101 buf */*b*/, buf */*bb*/);
1103 /* --- @ks_decrypt@ --- *
1105 * Arguments: @keyset *ks@ = pointer to a keyset
1106 * @unsigned ty@ = expected type code
1107 * @buf *b@ = pointer to an input buffer
1108 * @buf *bb@ = pointer to an output buffer
1110 * Returns: Zero on success; @KSERR_DECRYPT@ on failure. Also returns
1111 * zero if there was insufficient buffer (but the output buffer
1112 * is broken in this case).
1114 * Use: Attempts to decrypt a message using a given key. Note that
1115 * requesting decryption with a key directly won't clear a
1116 * marking that it's not for encryption.
1118 * The decryption transform is permitted to corrupt @buf_u@ for
1119 * its own purposes. Neither the source nor destination should
1120 * be within @buf_u@; and callers mustn't expect anything stored
1121 * in @buf_u@ to still
1124 extern int ks_decrypt(keyset */*ks*/, unsigned /*ty*/,
1125 buf */*b*/, buf */*bb*/);
1127 /* --- @ksl_free@ --- *
1129 * Arguments: @keyset **ksroot@ = pointer to keyset list head
1133 * Use: Frees (releases references to) all of the keys in a keyset.
1136 extern void ksl_free(keyset **/*ksroot*/);
1138 /* --- @ksl_link@ --- *
1140 * Arguments: @keyset **ksroot@ = pointer to keyset list head
1141 * @keyset *ks@ = pointer to a keyset
1145 * Use: Links a keyset into a list. A keyset can only be on one list
1146 * at a time. Bad things happen otherwise.
1149 extern void ksl_link(keyset **/*ksroot*/, keyset */*ks*/);
1151 /* --- @ksl_prune@ --- *
1153 * Arguments: @keyset **ksroot@ = pointer to keyset list head
1157 * Use: Prunes the keyset list by removing keys which mustn't be used
1161 extern void ksl_prune(keyset **/*ksroot*/);
1163 /* --- @ksl_encrypt@ --- *
1165 * Arguments: @keyset **ksroot@ = pointer to keyset list head
1166 * @unsigned ty@ = message type
1167 * @buf *b@ = pointer to input buffer
1168 * @buf *bb@ = pointer to output buffer
1170 * Returns: Zero if successful; @KSERR_REGEN@ if it's time to negotiate a
1171 * new key; @KSERR_NOKEYS@ if there are no suitable keys
1172 * available. Also returns zero if there was insufficient
1173 * buffer space (but the output buffer is broken in this case).
1175 * Use: Encrypts a packet.
1178 extern int ksl_encrypt(keyset **/*ksroot*/, unsigned /*ty*/,
1179 buf */*b*/, buf */*bb*/);
1181 /* --- @ksl_decrypt@ --- *
1183 * Arguments: @keyset **ksroot@ = pointer to keyset list head
1184 * @unsigned ty@ = expected type code
1185 * @buf *b@ = pointer to input buffer
1186 * @buf *bb@ = pointer to output buffer
1188 * Returns: Zero on success; @KSERR_DECRYPT@ on failure. Also returns
1189 * zero if there was insufficient buffer (but the output buffer
1190 * is broken in this case).
1192 * Use: Decrypts a packet.
1195 extern int ksl_decrypt(keyset **/*ksroot*/, unsigned /*ty*/,
1196 buf */*b*/, buf */*bb*/);
1198 /*----- Challenges --------------------------------------------------------*/
1200 /* --- @c_new@ --- *
1202 * Arguments: @const void *m@ = pointer to associated message, or null
1203 * @size_t msz@ = length of associated message
1204 * @buf *b@ = where to put the challenge
1206 * Returns: Zero if OK, nonzero on error.
1208 * Use: Issues a new challenge.
1211 extern int c_new(const void */*m*/, size_t /*msz*/, buf */*b*/);
1213 /* --- @c_check@ --- *
1215 * Arguments: @const void *m@ = pointer to associated message, or null
1216 * @size_t msz@ = length of associated message
1217 * @buf *b@ = where to find the challenge
1219 * Returns: Zero if OK, nonzero if it didn't work.
1221 * Use: Checks a challenge. On failure, the buffer is broken.
1224 extern int c_check(const void */*m*/, size_t /*msz*/, buf */*b*/);
1226 /*----- Administration interface ------------------------------------------*/
1228 #define A_END ((char *)0)
1230 /* --- @a_vformat@ --- *
1232 * Arguments: @dstr *d@ = where to leave the formatted message
1233 * @const char *fmt@ = pointer to format string
1234 * @va_list *ap@ = arguments in list
1238 * Use: Main message token formatting driver. The arguments are
1239 * interleaved formatting tokens and their parameters, finally
1240 * terminated by an entry @A_END@.
1242 * Tokens recognized:
1244 * * "*..." ... -- pretokenized @dstr_putf@-like string
1246 * * "?ADDR" SOCKADDR -- a socket address, to be converted
1248 * * "?B64" BUFFER SIZE -- binary data to be base64-encoded
1250 * * "?TOKENS" VECTOR -- null-terminated vector of tokens
1252 * * "?PEER" PEER -- peer's name
1254 * * "?ERR" CODE -- system error code
1256 * * "?ERRNO" -- system error code from @errno@
1258 * * "[!]..." ... -- @dstr_putf@-like string as single token
1261 extern void a_vformat(dstr */*d*/, const char */*fmt*/, va_list */*ap*/);
1263 /* --- @a_format@ --- *
1265 * Arguments: @dstr *d@ = where to leave the formatted message
1266 * @const char *fmt@ = pointer to format string
1270 * Use: Writes a tokenized message into a string, for later
1274 extern void EXECL_LIKE(0) a_format(dstr */*d*/, const char */*fmt*/, ...);
1276 /* --- @a_info@ --- *
1278 * Arguments: @admin *a@ = connection
1279 * @const char *fmt@ = format string
1280 * @...@ = other arguments
1284 * Use: Report information to an admin client.
1287 extern void EXECL_LIKE(0) a_info(admin */*a*/, const char */*fmt*/, ...);
1289 /* --- @a_warn@ --- *
1291 * Arguments: @const char *fmt@ = pointer to format string
1292 * @...@ = other arguments
1296 * Use: Informs all admin connections of a warning.
1299 extern void EXECL_LIKE(0) a_warn(const char */*fmt*/, ...);
1301 /* --- @a_notify@ --- *
1303 * Arguments: @const char *fmt@ = pointer to format string
1304 * @...@ = other arguments
1308 * Use: Sends a notification to interested admin connections.
1311 extern void EXECL_LIKE(0) a_notify(const char */*fmt*/, ...);
1313 /* --- @a_create@ --- *
1315 * Arguments: @int fd_in, fd_out@ = file descriptors to use
1316 * @unsigned f@ = initial flags to set
1320 * Use: Creates a new admin connection. It's safe to call this
1321 * before @a_init@ -- and, indeed, this makes sense if you also
1322 * call @a_switcherr@ to report initialization errors through
1323 * the administration machinery.
1326 extern void a_create(int /*fd_in*/, int /*fd_out*/, unsigned /*f*/);
1328 /* --- @a_preselect@ --- *
1334 * Use: Informs the admin module that we're about to select again,
1335 * and that it should do cleanup things it has delayed until a
1339 extern void a_preselect(void);
1341 /* --- @a_daemon@ --- *
1347 * Use: Informs the admin module that it's a daemon.
1350 extern void a_daemon(void);
1352 /* --- @a_listen@ --- *
1354 * Arguments: @const char *name@ = socket name to create
1355 * @uid_t u@ = user to own the socket
1356 * @gid_t g@ = group to own the socket
1357 * @mode_t m@ = permissions to set on the socket
1359 * Returns: Zero on success, @-1@ on failure.
1361 * Use: Creates the admin listening socket.
1364 extern int a_listen(const char */*sock*/,
1365 uid_t /*u*/, gid_t /*g*/, mode_t /*m*/);
1367 /* --- @a_unlisten@ --- *
1373 * Use: Stops listening to the administration socket and removes it.
1376 extern void a_unlisten(void);
1378 /* --- @a_switcherr@ --- *
1384 * Use: Arrange to report warnings, trace messages, etc. to
1385 * administration clients rather than the standard-error stream.
1387 * Obviously this makes no sense unless there is at least one
1388 * client established. Calling @a_listen@ won't help with this,
1389 * because the earliest a new client can connect is during the
1390 * first select-loop iteration, which is too late: some initial
1391 * client must have been added manually using @a_create@.
1394 extern void a_switcherr(void);
1396 /* --- @a_signals@ --- *
1402 * Use: Establishes handlers for the obvious signals.
1405 extern void a_signals(void);
1407 /* --- @a_init@ --- *
1409 * Arguments: @const char *sock@ = socket name to create
1410 * @uid_t u@ = user to own the socket
1411 * @gid_t g@ = group to own the socket
1412 * @mode_t m@ = permissions to set on the socket
1414 * Returns: Zero on success, @-1@ on failure.
1416 * Use: Creates the admin listening socket.
1419 extern int a_init(void);
1421 /*----- Mapping with addresses as keys ------------------------------------*/
1423 /* --- @am_create@ --- *
1425 * Arguments: @addrmap *m@ = pointer to map
1429 * Use: Create an address map, properly set up.
1432 extern void am_create(addrmap */*m*/);
1434 /* --- @am_destroy@ --- *
1436 * Arguments: @addrmap *m@ = pointer to map
1440 * Use: Destroy an address map, throwing away all the entries.
1443 extern void am_destroy(addrmap */*m*/);
1445 /* --- @am_find@ --- *
1447 * Arguments: @addrmap *m@ = pointer to map
1448 * @const addr *a@ = address to look up
1449 * @size_t sz@ = size of block to allocate
1450 * @unsigned *f@ = where to store flags
1452 * Returns: Pointer to found item, or null.
1454 * Use: Finds a record with the given IP address, set @*f@ nonzero
1455 * and returns it. If @sz@ is zero, and no match was found,
1456 * return null; otherwise allocate a new block of @sz@ bytes,
1457 * clear @*f@ to zero and return the block pointer.
1460 extern void *am_find(addrmap */*m*/, const addr */*a*/,
1461 size_t /*sz*/, unsigned */*f*/);
1463 /* --- @am_remove@ --- *
1465 * Arguments: @addrmap *m@ = pointer to map
1466 * @void *i@ = pointer to the item
1470 * Use: Removes an item from the map.
1473 extern void am_remove(addrmap */*m*/, void */*i*/);
1475 /*----- Privilege separation ----------------------------------------------*/
1477 /* --- @ps_trace@ --- *
1479 * Arguments: @unsigned mask@ = trace mask to check
1480 * @const char *fmt@ = message format
1481 * @...@ = values for placeholders
1485 * Use: Writes a trace message.
1488 T( extern void PRINTF_LIKE(2, 3)
1489 ps_trace(unsigned /*mask*/, const char */*fmt*/, ...); )
1491 /* --- @ps_warn@ --- *
1493 * Arguments: @const char *fmt@ = message format
1494 * @...@ = values for placeholders
1498 * Use: Writes a warning message.
1501 extern void PRINTF_LIKE(1, 2) ps_warn(const char */*fmt*/, ...);
1503 /* --- @ps_tunfd@ --- *
1505 * Arguments: @const tunnel_ops *tops@ = pointer to tunnel operations
1506 * @char **ifn@ = where to put the interface name
1508 * Returns: The file descriptor, or @-1@ on error.
1510 * Use: Fetches a file descriptor for a tunnel driver.
1513 extern int ps_tunfd(const tunnel_ops */*tops*/, char **/*ifn*/);
1515 /* --- @ps_split@ --- *
1517 * Arguments: @int detachp@ = whether to detach the child from its terminal
1519 * Returns: Zero on success, @-1@ on failure.
1521 * Use: Separates off the privileged tunnel-opening service from the
1522 * rest of the server.
1525 extern int ps_split(int /*detachp*/);
1527 /* --- @ps_quit@ --- *
1533 * Use: Detaches from the helper process.
1536 extern void ps_quit(void);
1538 /*----- Peer management ---------------------------------------------------*/
1540 /* --- @p_updateaddr@ --- *
1542 * Arguments: @peer *p@ = pointer to peer block
1543 * @const addr *a@ = address to associate with this peer
1545 * Returns: Zero if the address was changed; @+1@ if it was already
1548 * Use: Updates our idea of @p@'s address.
1551 extern int p_updateaddr(peer */*p*/, const addr */*a*/);
1553 /* --- @p_txstart@ --- *
1555 * Arguments: @peer *p@ = pointer to peer block
1556 * @unsigned msg@ = message type code
1558 * Returns: A pointer to a buffer to write to.
1560 * Use: Starts sending to a peer. Only one send can happen at a
1564 extern buf *p_txstart(peer */*p*/, unsigned /*msg*/);
1566 /* --- @p_txaddr@ --- *
1568 * Arguments: @const addr *a@ = recipient address
1569 * @const void *p@ = pointer to packet to send
1570 * @size_t sz@ = length of packet
1572 * Returns: Zero if successful, nonzero on error.
1574 * Use: Sends a packet to an address which (possibly) isn't a current
1578 extern int p_txaddr(const addr */*a*/, const void */*p*/, size_t /*sz*/);
1580 /* --- @p_txend@ --- *
1582 * Arguments: @peer *p@ = pointer to peer block
1583 * @unsigned f@ = flags
1587 * Use: Sends a packet to the peer.
1590 extern void p_txend(peer */*p*/, unsigned /*f*/);
1592 /* --- @p_pingsend@ --- *
1594 * Arguments: @peer *p@ = destination peer
1595 * @ping *pg@ = structure to fill in
1596 * @unsigned type@ = message type
1597 * @unsigned long timeout@ = how long to wait before giving up
1598 * @void (*func)(int, void *)@ = callback function
1599 * @void *arg@ = argument for callback
1601 * Returns: Zero if successful, nonzero if it failed.
1603 * Use: Sends a ping to a peer. Call @func@ with a nonzero argument
1604 * if we get an answer within the timeout, or zero if no answer.
1607 extern int p_pingsend(peer */*p*/, ping */*pg*/, unsigned /*type*/,
1608 unsigned long /*timeout*/,
1609 void (*/*func*/)(int, void *), void */*arg*/);
1611 /* --- @p_pingdone@ --- *
1613 * Arguments: @ping *p@ = ping structure
1614 * @int rc@ = return code to pass on
1618 * Use: Disposes of a ping structure, maybe sending a notification.
1621 extern void p_pingdone(ping */*p*/, int /*rc*/);
1623 /* --- @p_greet@ --- *
1625 * Arguments: @peer *p@ = peer to send to
1626 * @const void *c@ = pointer to challenge
1627 * @size_t sz@ = size of challenge
1631 * Use: Sends a greeting packet.
1634 extern void p_greet(peer */*p*/, const void */*c*/, size_t /*sz*/);
1636 /* --- @p_tun@ --- *
1638 * Arguments: @peer *p@ = pointer to peer block
1639 * @buf *b@ = buffer containing incoming packet
1643 * Use: Handles a packet which needs to be sent to a peer.
1646 extern void p_tun(peer */*p*/, buf */*b*/);
1648 /* --- @p_keyreload@ --- *
1654 * Use: Forces a check of the daemon's keyring files.
1657 extern void p_keyreload(void);
1659 /* --- @p_interval@ --- *
1665 * Use: Called periodically to do tidying.
1668 extern void p_interval(void);
1670 /* --- @p_stats@ --- *
1672 * Arguments: @peer *p@ = pointer to a peer block
1674 * Returns: A pointer to the peer's statistics.
1677 extern stats *p_stats(peer */*p*/);
1679 /* --- @p_ifname@ --- *
1681 * Arguments: @peer *p@ = pointer to a peer block
1683 * Returns: A pointer to the peer's interface name.
1686 extern const char *p_ifname(peer */*p*/);
1688 /* --- @p_setifname@ --- *
1690 * Arguments: @peer *p@ = pointer to a peer block
1691 * @const char *name@ = pointer to the new name
1695 * Use: Changes the name held for a peer's interface.
1698 extern void p_setifname(peer */*p*/, const char */*name*/);
1700 /* --- @p_addr@ --- *
1702 * Arguments: @peer *p@ = pointer to a peer block
1704 * Returns: A pointer to the peer's address.
1707 extern const addr *p_addr(peer */*p*/);
1709 /* --- @p_bind@ --- *
1711 * Arguments: @struct addrinfo *ailist@ = addresses to bind to
1713 * Returns: Zero on success, @-1@ on failure.
1715 * Use: Binds to the main UDP sockets.
1718 extern int p_bind(struct addrinfo */*ailist*/);
1720 /* --- @p_unbind@ --- *
1726 * Use: Unbinds the UDP sockets. There must not be any active peers,
1727 * and none can be created until the sockets are rebound.
1730 extern void p_unbind(void);
1732 /* --- @p_init@ --- *
1738 * Use: Initializes the peer system.
1741 extern void p_init(void);
1743 /* --- @p_addtun@ --- *
1745 * Arguments: @const tunnel_ops *tops@ = tunnel ops to add
1747 * Returns: Zero on success, @-1@ on failure.
1749 * Use: Adds a tunnel class to the list of known classes, if it
1750 * initializes properly. If there is no current default tunnel,
1751 * then this one is made the default.
1753 * Does nothing if the tunnel class is already known. So adding
1754 * a bunch of tunnels takes quadratic time, but there will be
1755 * too few to care about.
1758 extern int p_addtun(const tunnel_ops */*tops*/);
1760 /* --- @p_setdflttun@ --- *
1762 * Arguments: @const tunnel_ops *tops@ = tunnel ops to set
1766 * Use: Sets the default tunnel. It must already be registered. The
1767 * old default is forgotten.
1770 extern void p_setdflttun(const tunnel_ops */*tops*/);
1772 /* --- @p_dflttun@ --- *
1776 * Returns: A pointer to the current default tunnel operations, or null
1777 * if no tunnels are defined.
1780 extern const tunnel_ops *p_dflttun(void);
1782 /* --- @p_findtun@ --- *
1784 * Arguments: @const char *name@ = tunnel name
1786 * Returns: Pointer to the tunnel operations, or null.
1788 * Use: Finds the operations for a named tunnel class.
1791 extern const tunnel_ops *p_findtun(const char */*name*/);
1793 /* --- @p_mktuniter@ --- *
1795 * Arguments: @tuniter *i@ = pointer to iterator to initialize
1799 * Use: Initializes a tunnel iterator.
1802 extern void p_mktuniter(tun_iter */*i*/);
1804 /* --- @p_nexttun@ --- *
1806 * Arguments: @tuniter *i@ = pointer to iterator
1808 * Returns: Pointer to the next tunnel's operations, or null.
1811 extern const tunnel_ops *p_nexttun(tun_iter */*i*/);
1813 /* --- @FOREACH_TUN@ --- *
1815 * Arguments: @tops@ = name to bind to each tunnel
1816 * @stuff@ = thing to do for each item
1818 * Use: Does something for each known tunnel class.
1821 #define FOREACH_TUN(tops, stuff) do { \
1823 const tunnel_ops *tops; \
1824 for (p_mktuniter(&i_); (tops = p_nexttun(&i_)) != 0; ) stuff; \
1827 /* --- @p_create@ --- *
1829 * Arguments: @peerspec *spec@ = information about this peer
1831 * Returns: Pointer to the peer block, or null if it failed.
1833 * Use: Creates a new named peer block. No peer is actually attached
1837 extern peer *p_create(peerspec */*spec*/);
1839 /* --- @p_name@ --- *
1841 * Arguments: @peer *p@ = pointer to a peer block
1843 * Returns: A pointer to the peer's name.
1845 * Use: Equivalent to @p_spec(p)->name@.
1848 extern const char *p_name(peer */*p*/);
1850 /* --- @p_tag@ --- *
1852 * Arguments: @peer *p@ = pointer to a peer block
1854 * Returns: A pointer to the peer's public key tag.
1857 extern const char *p_tag(peer */*p*/);
1859 /* --- @p_privtag@ --- *
1861 * Arguments: @peer *p@ = pointer to a peer block
1863 * Returns: A pointer to the peer's private key tag.
1866 extern const char *p_privtag(peer */*p*/);
1868 /* --- @p_spec@ --- *
1870 * Arguments: @peer *p@ = pointer to a peer block
1872 * Returns: Pointer to the peer's specification
1875 extern const peerspec *p_spec(peer */*p*/);
1877 /* --- @p_findbyaddr@ --- *
1879 * Arguments: @const addr *a@ = address to look up
1881 * Returns: Pointer to the peer block, or null if not found.
1883 * Use: Finds a peer by address.
1886 extern peer *p_findbyaddr(const addr */*a*/);
1888 /* --- @p_find@ --- *
1890 * Arguments: @const char *name@ = name to look up
1892 * Returns: Pointer to the peer block, or null if not found.
1894 * Use: Finds a peer by name.
1897 extern peer *p_find(const char */*name*/);
1899 /* --- @p_destroy@ --- *
1901 * Arguments: @peer *p@ = pointer to a peer
1902 * @int bye@ = say goodbye to the peer?
1906 * Use: Destroys a peer.
1909 extern void p_destroy(peer */*p*/, int /*bye*/);
1911 /* --- @p_destroyall@ --- *
1917 * Use: Destroys all of the peers, saying goodbye.
1920 extern void p_destroyall(void);
1922 /* --- @FOREACH_PEER@ --- *
1924 * Arguments: @p@ = name to bind to each peer
1925 * @stuff@ = thing to do for each item
1927 * Use: Does something for each current peer.
1930 #define FOREACH_PEER(p, stuff) do { \
1933 for (p_mkiter(&i_); (p = p_next(&i_)) != 0; ) stuff \
1936 /* --- @p_mkiter@ --- *
1938 * Arguments: @peer_iter *i@ = pointer to an iterator
1942 * Use: Initializes the iterator.
1945 extern void p_mkiter(peer_iter */*i*/);
1947 /* --- @p_next@ --- *
1949 * Arguments: @peer_iter *i@ = pointer to an iterator
1951 * Returns: Next peer, or null if at the end.
1953 * Use: Returns the next peer.
1956 extern peer *p_next(peer_iter */*i*/);
1958 /*----- The interval timer ------------------------------------------------*/
1960 /* --- @iv_addreason@ --- *
1966 * Use: Adds an `interval timer reason'; if there are no others, the
1967 * interval timer is engaged.
1970 extern void iv_addreason(void);
1972 /* --- @iv_rmreason@ --- *
1978 * Use: Removes an interval timer reason; if there are none left, the
1979 * interval timer is disengaged.
1982 extern void iv_rmreason(void);
1984 /*----- The main loop -----------------------------------------------------*/
1986 /* --- @lp_init@ --- *
1992 * Use: Initializes the main loop. Most importantly, this sets up
1993 * the select multiplexor that everything else hooks onto.
1996 extern void lp_init(void);
1998 /* --- @lp_end@ --- *
2004 * Use: Requests an exit from the main loop.
2007 extern void lp_end(void);
2009 /* --- @lp_run@ --- *
2013 * Returns: Zero on successful termination; @-1@ if things went wrong.
2015 * Use: Cranks the main loop until it should be cranked no more.
2018 extern int lp_run(void);
2020 /*----- Tunnel drivers ----------------------------------------------------*/
2023 extern const tunnel_ops tun_linux;
2027 extern const tunnel_ops tun_unet;
2031 extern const tunnel_ops tun_bsd;
2034 extern const tunnel_ops tun_slip;
2036 /*----- Other handy utilities ---------------------------------------------*/
2038 /* --- @timestr@ --- *
2040 * Arguments: @time_t t@ = a time to convert
2042 * Returns: A pointer to a textual representation of the time.
2044 * Use: Converts a time to a textual representation. Corrupts
2048 extern const char *timestr(time_t /*t*/);
2050 /* --- @mystrieq@ --- *
2052 * Arguments: @const char *x, *y@ = two strings
2054 * Returns: True if @x@ and @y are equal, up to case.
2057 extern int mystrieq(const char */*x*/, const char */*y*/);
2061 * Arguments: @int af@ = an address family code
2063 * Returns: The index of the address family's record in @aftab@, or @-1@.
2066 extern int afix(int af);
2068 /* --- @addrsz@ --- *
2070 * Arguments: @const addr *a@ = a network address
2072 * Returns: The size of the address, for passing into the sockets API.
2075 extern socklen_t addrsz(const addr */*a*/);
2077 /* --- @getport@, @setport@ --- *
2079 * Arguments: @addr *a@ = a network address
2080 * @unsigned port@ = port number to set
2084 * Use: Retrieves or sets the port number in an address structure.
2087 extern unsigned getport(addr */*a*/);
2088 extern void setport(addr */*a*/, unsigned /*port*/);
2090 /* --- @seq_reset@ --- *
2092 * Arguments: @seqwin *s@ = sequence-checking window
2096 * Use: Resets a sequence number window.
2099 extern void seq_reset(seqwin */*s*/);
2101 /* --- @seq_check@ --- *
2103 * Arguments: @seqwin *s@ = sequence-checking window
2104 * @uint32 q@ = sequence number to check
2105 * @const char *service@ = service to report message from
2107 * Returns: A @SEQ_@ code.
2109 * Use: Checks a sequence number against the window, updating things
2113 extern int seq_check(seqwin */*s*/, uint32 /*q*/, const char */*service*/);
2115 typedef struct ratelim {
2116 unsigned n, max, persec;
2117 struct timeval when;
2120 /* --- @ratelim_init@ --- *
2122 * Arguments: @ratelim *r@ = rate-limiting state to fill in
2123 * @unsigned persec@ = credit to accumulate per second
2124 * @unsigned max@ = maximum credit to retain
2128 * Use: Initialize a rate-limiting state.
2131 extern void ratelim_init(ratelim */*r*/,
2132 unsigned /*persec*/, unsigned /*max*/);
2134 /* --- @ratelim_withdraw@ --- *
2136 * Arguments: @ratelim *r@ = rate-limiting state
2137 * @unsigned n@ = credit to withdraw
2139 * Returns: Zero if successful; @-1@ if there is unsufficient credit
2141 * Use: Updates the state with any accumulated credit. Then, if
2142 * there there are more than @n@ credits available, withdraw @n@
2143 * and return successfully; otherwise, report failure.
2146 extern int ratelim_withdraw(ratelim */*r*/, unsigned /*n*/);
2148 /* --- @ies_encrypt@ --- *
2150 * Arguments: @kdata *kpub@ = recipient's public key
2151 * @unsigned ty@ = message type octet
2152 * @buf *b@ = input message buffer
2153 * @buf *bb@ = output buffer for the ciphertext
2155 * Returns: On error, returns a @KSERR_...@ code or breaks the buffer;
2156 * on success, returns zero and the buffer is good.
2158 * Use: Encrypts a message for a recipient, given their public key.
2159 * This does not (by itself) provide forward secrecy or sender
2160 * authenticity. The ciphertext is self-delimiting (unlike
2164 extern int ies_encrypt(kdata */*kpub*/, unsigned /*ty*/,
2165 buf */*b*/, buf */*bb*/);
2167 /* --- @ies_decrypt@ --- *
2169 * Arguments: @kdata *kpub@ = private key key
2170 * @unsigned ty@ = message type octet
2171 * @buf *b@ = input ciphertext buffer
2172 * @buf *bb@ = output buffer for the message
2174 * Returns: On error, returns a @KSERR_...@ code; on success, returns
2175 * zero and the buffer is good.
2177 * Use: Decrypts a message encrypted using @ies_encrypt@, given our
2181 extern int ies_decrypt(kdata */*kpriv*/, unsigned /*ty*/,
2182 buf */*b*/, buf */*bb*/);
2184 /*----- That's all, folks -------------------------------------------------*/