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/gcipher.h>
103 #include <catacomb/gmac.h>
104 #include <catacomb/grand.h>
105 #include <catacomb/key.h>
106 #include <catacomb/paranoia.h>
107 #include <catacomb/poly1305.h>
108 #include <catacomb/salsa20.h>
110 #include <catacomb/noise.h>
111 #include <catacomb/rand.h>
113 #include <catacomb/mp.h>
114 #include <catacomb/mpmont.h>
115 #include <catacomb/mprand.h>
116 #include <catacomb/dh.h>
117 #include <catacomb/ec.h>
118 #include <catacomb/ec-raw.h>
119 #include <catacomb/ec-keys.h>
120 #include <catacomb/x25519.h>
121 #include <catacomb/x448.h>
124 #include "protocol.h"
130 /*----- Magic numbers -----------------------------------------------------*/
132 /* --- Trace flags --- */
140 #define T_KEYEXCH 64u
141 #define T_KEYMGMT 128u
143 /* T_PRIVSEP in priv.h */
149 #define SEC(n) (n##u)
150 #define MIN(n) (n##u * 60u)
151 #define F_2P32 (65536.0*65536.0)
152 #define MEG(n) (n##ul * 1024ul * 1024ul)
154 /* --- Timing parameters --- */
156 #define T_EXP MIN(60) /* Expiry time for a key */
157 #define T_REGEN MIN(40) /* Regeneration time for a key */
159 #define T_VALID SEC(20) /* Challenge validity period */
160 #define T_RETRYMIN SEC(2) /* Minimum retry interval */
161 #define T_RETRYMAX MIN(5) /* Maximum retry interval */
162 #define T_RETRYGROW (5.0/4.0) /* Retry interval growth factor */
164 #define T_WOBBLE (1.0/3.0) /* Relative timer randomness */
166 /* --- Other things --- */
168 #define PKBUFSZ 65536
170 /*----- Cipher selections -------------------------------------------------*/
172 typedef struct keyset keyset;
173 typedef struct algswitch algswitch;
174 typedef struct kdata kdata;
175 typedef struct admin admin;
177 typedef struct dhgrp {
178 const struct dhops *ops;
182 typedef struct dhsc dhsc;
183 typedef struct dhge dhge;
186 DHFMT_STD, /* Fixed-width format, suitable for encryption */
187 DHFMT_HASH, /* Deterministic format, suitable for hashing */
188 DHFMT_VAR /* Variable-width-format, mostly a bad idea */
191 typedef struct deriveargs {
192 const char *what; /* Operation name (hashed) */
193 unsigned f; /* Flags */
194 #define DF_IN 1u /* Make incoming key */
195 #define DF_OUT 2u /* Make outgoing key */
196 const gchash *hc; /* Hash class */
197 const octet *k; /* Pointer to contributions */
198 size_t x, y, z; /* Markers in contributions */
201 typedef struct bulkalgs {
202 const struct bulkops *ops;
205 typedef struct bulkctx {
206 const struct bulkops *ops;
209 typedef struct bulkchal {
210 const struct bulkops *ops;
214 typedef struct dhops {
217 int (*ldpriv)(key_file */*kf*/, key */*k*/, key_data */*d*/,
218 kdata */*kd*/, dstr */*t*/, dstr */*e*/);
219 /* Load a private key from @d@, storing the data in @kd@. The key's
220 * file and key object are in @kf@ and @k@, mostly in case its
221 * attributes are interesting; the key tag is in @t@; errors are
222 * reported by writing tokens to @e@ and returning nonzero.
225 int (*ldpub)(key_file */*kf*/, key */*k*/, key_data */*d*/,
226 kdata */*kd*/, dstr */*t*/, dstr */*e*/);
227 /* Load a public key from @d@, storing the data in @kd@. The key's
228 * file and key object are in @kf@ and @k@, mostly in case its
229 * attributes are interesting; the key tag is in @t@; errors are
230 * reported by writing tokens to @e@ and returning nonzero.
233 const char *(*checkgrp)(const dhgrp */*g*/);
234 /* Check that the group is valid; return null on success, or an error
238 void (*grpinfo)(const dhgrp */*g*/, admin */*a*/);
239 /* Report on the group to an admin client. */
241 T( void (*tracegrp)(const dhgrp */*g*/); )
242 /* Trace a description of the group. */
244 int (*samegrpp)(const dhgrp */*g*/, const dhgrp */*gg*/);
245 /* Return nonzero if the two group objects represent the same
249 void (*freegrp)(dhgrp */*g*/);
250 /* Free a group and the resources it holds. */
252 dhsc *(*ldsc)(const dhgrp */*g*/, const void */*p*/, size_t /*sz*/);
253 /* Load a scalar from @p@, @sz@ and return it. Return null on
257 int (*stsc)(const dhgrp */*g*/,
258 void */*p*/, size_t /*sz*/, const dhsc */*x*/);
259 /* Store a scalar at @p@, @sz@. Return nonzero on error. */
261 dhsc *(*randsc)(const dhgrp */*g*/);
262 /* Return a random scalar. */
264 T( const char *(*scstr)(const dhgrp */*g*/, const dhsc */*x*/); )
265 /* Return a human-readable representation of @x@; @buf_t@ may be used
269 void (*freesc)(const dhgrp */*g*/, dhsc */*x*/);
270 /* Free a scalar and the resources it holds. */
272 dhge *(*ldge)(const dhgrp */*g*/, buf */*b*/, int /*fmt*/);
273 /* Load a group element from @b@, encoded using format @fmt@. Return
277 int (*stge)(const dhgrp */*g*/, buf */*b*/,
278 const dhge */*Y*/, int /*fmt*/);
279 /* Store a group element in @b@, encoded using format @fmt@. Return
283 int (*checkge)(const dhgrp */*h*/, const dhge */*Y*/);
284 /* Check a group element for validity. Return zero if everything
285 * checks out; nonzero on failure.
288 int (*eq)(const dhgrp */*g*/, const dhge */*Y*/, const dhge */*Z*/);
289 /* Return nonzero if @Y@ and @Z@ are equal. */
291 dhge *(*mul)(const dhgrp */*g*/, const dhsc */*x*/, const dhge */*Y*/);
292 /* Multiply a group element by a scalar, resulting in a shared-secret
293 * group element. If @y@ is null, then multiply the well-known
297 T( const char *(*gestr)(const dhgrp */*g*/, const dhge */*Y*/); )
298 /* Return a human-readable representation of @Y@; @buf_t@ may be used
302 void (*freege)(const dhgrp */*g*/, dhge */*Y*/);
303 /* Free a group element and the resources it holds. */
307 typedef struct bulkops {
310 bulkalgs *(*getalgs)(const algswitch */*asw*/, dstr */*e*/,
311 key_file */*kf*/, key */*k*/);
312 /* Determine algorithms to use and return a @bulkalgs@ object
313 * representing the decision. On error, write tokens to @e@ and
317 T( void (*tracealgs)(const bulkalgs */*a*/); )
318 /* Write trace information about the algorithm selection. */
320 int (*checkalgs)(bulkalgs */*a*/, const algswitch */*asw*/, dstr */*e*/);
321 /* Check that the algorithms in @a@ and @asw@ are acceptable. On
322 * error, write tokens to @e@ and return @-1@; otherwise return zero.
325 int (*samealgsp)(const bulkalgs */*a*/, const bulkalgs */*aa*/);
326 /* If @a@ and @aa@ represent the same algorithm selection, return
327 * nonzero; if not, return zero.
330 void (*alginfo)(const bulkalgs */*a*/, admin */*adm*/);
331 /* Report on the algorithm selection to an admin client: call
332 * @a_info@ with appropriate key-value pairs.
335 size_t (*overhead)(const bulkalgs */*a*/);
336 /* Return the per-packet overhead of the bulk transform, in bytes. */
338 size_t (*expsz)(const bulkalgs */*a*/);
339 /* Return the total size limit for the bulk transform, in bytes,
340 * after which the keys must no longer be used.
343 bulkctx *(*genkeys)(const bulkalgs */*a*/, const deriveargs */*a*/);
344 /* Generate session keys and construct and return an appropriate
345 * context for using them. The offsets @a->x@, @a->y@ and @a->z@
346 * separate the key material into three parts. Between @a->k@ and
347 * @a->k + a->x@ is `my' contribution to the key material; between
348 * @a->k + a->x@ and @a->k + a->y@ is `your' contribution; and
349 * between @a->k + a->y@ and @a->k + a->z@ is a shared value we made
350 * together. These are used to construct (up to) two collections of
351 * symmetric keys: one for outgoing messages, the other for incoming
352 * messages. If @a->x == 0@ (or @a->y == a->x@) then my (or your)
353 * contribution is omitted.
356 bulkchal *(*genchal)(const bulkalgs */*a*/);
357 /* Construct and return a challenge issuing and verification
358 * context with a fresh random key.
361 void (*freealgs)(bulkalgs */*a*/);
362 /* Release an algorithm selection object. (Associated bulk
363 * encryption contexts and challenge contexts may still exist and
364 * must remain valid.)
367 int (*encrypt)(bulkctx */*bc*/, unsigned /*ty*/,
368 buf */*b*/, buf */*bb*/, uint32 /*seq*/);
369 /* Encrypt the packet in @b@, with type @ty@ (which doesn't need
370 * encoding separately) and sequence number @seq@ (which must be
371 * recoverable by @decrypt@), and write the result to @bb@. On
372 * error, return a @KSERR_...@ code and/or break the output buffer.
375 int (*decrypt)(bulkctx */*bc*/, unsigned /*ty*/,
376 buf */*b*/, buf */*bb*/, uint32 */*seq*/);
377 /* Decrypt the packet in @b@, with type @ty@, writing the result to
378 * @bb@ and storing the incoming (claimed) sequence number in @seq@.
379 * On error, return a @KSERR_...@ code.
382 void (*freectx)(bulkctx */*a*/);
383 /* Release a bulk encryption context and the resources it holds. */
385 int (*chaltag)(bulkchal */*bc*/, const void */*m*/, size_t /*msz*/,
386 uint32 /*seq*/, void */*t*/);
387 /* Calculate a tag for the challenge in @m@, @msz@, with the sequence
388 * number @seq@, and write it to @t@. Return @-1@ on error, zero on
392 int (*chalvrf)(bulkchal */*bc*/, const void */*m*/, size_t /*msz*/,
393 uint32 /*seq*/, const void */*t*/);
394 /* Check the tag @t@ on @m@, @msz@ and @seq@: return zero if the tag
395 * is OK, nonzero if it's bad.
398 void (*freechal)(bulkchal */*bc*/);
399 /* Release a challenge context and the resources it holds. */
404 const gchash *h; size_t hashsz; /* Hash function */
405 const gccipher *mgf; /* Mask-generation function */
406 bulkalgs *bulk; /* Bulk crypto algorithms */
410 unsigned ref; /* Reference counter */
411 struct knode *kn; /* Pointer to cache entry */
412 uint32 id; /* The underlying key's id */
413 char *tag; /* Full tag name of the key */
414 dhgrp *grp; /* The group we work in */
415 dhsc *k; /* The private key (or null) */
416 dhge *K; /* The public key */
417 time_t t_exp; /* Expiry time of the key */
418 algswitch algs; /* Collection of algorithms */
421 typedef struct knode {
422 sym_base _b; /* Symbol table intrusion */
423 unsigned f; /* Various flags */
424 #define KNF_BROKEN 1u /* Don't use this key any more */
425 struct keyhalf *kh; /* Pointer to the home keyhalf */
426 kdata *kd; /* Pointer to the key data */
429 #define MAXHASHSZ 64 /* Largest possible hash size */
431 #define HASH_STRING(h, s) GH_HASH((h), (s), sizeof(s))
433 extern const dhops dhtab[];
434 extern const bulkops bulktab[];
436 /*----- Data structures ---------------------------------------------------*/
438 /* --- The address-family table --- */
445 #define ENUM(af, qf) AFIX_##af,
451 extern const struct addrfam {
459 /* --- Socket addresses --- *
461 * A magic union of supported socket addresses.
466 struct sockaddr_in sin;
467 struct sockaddr_in6 sin6;
470 /* --- Mapping keyed on addresses --- */
472 typedef struct addrmap {
477 typedef struct addrmap_base {
482 /* --- Sequence number checking --- */
484 typedef struct seqwin {
485 uint32 seq; /* First acceptable input sequence */
486 uint32 win; /* Window of acceptable numbers */
489 #define SEQ_WINSZ 32 /* Bits in sequence number window */
491 /* --- A symmetric keyset --- *
493 * A keyset contains a set of symmetric keys for encrypting and decrypting
494 * packets. Keysets are stored in a list, sorted in reverse order of
495 * creation, so that the most recent keyset (the one most likely to be used)
498 * Each keyset has a time limit and a data limit. The keyset is destroyed
499 * when either it has existed for too long, or it has been used to encrypt
500 * too much data. New key exchanges are triggered when keys are close to
504 enum { DIR_IN, DIR_OUT, NDIR };
507 struct keyset *next; /* Next active keyset in the list */
508 unsigned ref; /* Reference count for keyset */
509 struct peer *p; /* Pointer to peer structure */
510 time_t t_exp; /* Expiry time for this keyset */
511 unsigned long sz_exp, sz_regen; /* Data limits for the keyset */
512 T( unsigned seq; ) /* Sequence number for tracing */
513 unsigned f; /* Various useful flags */
514 bulkctx *bulk; /* Bulk crypto transform */
515 uint32 oseq; /* Outbound sequence number */
516 seqwin iseq; /* Inbound sequence number */
519 #define KSF_LISTEN 1u /* Don't encrypt packets yet */
520 #define KSF_LINK 2u /* Key is in a linked list */
522 #define KSERR_REGEN -1 /* Regenerate keys */
523 #define KSERR_NOKEYS -2 /* No keys left */
524 #define KSERR_DECRYPT -3 /* Unable to decrypt message */
525 #define KSERR_SEQ -4 /* Incorrect sequence number */
526 #define KSERR_MALFORMED -5 /* Input ciphertext is broken */
528 /* --- Key exchange --- *
530 * TrIPE uses the Wrestlers Protocol for its key exchange. The Wrestlers
531 * Protocol has a number of desirable features (e.g., perfect forward
532 * secrecy, and zero-knowledge authentication) which make it attractive for
533 * use in TrIPE. The Wrestlers Protocol was designed by Mark Wooding and
537 typedef struct retry {
538 double t; /* Current retry time */
543 typedef struct kxchal {
544 struct keyexch *kx; /* Pointer back to key exchange */
545 dhge *C; /* Responder's challenge */
546 dhge *R; /* My reply to the challenge */
547 keyset *ks; /* Pointer to temporary keyset */
548 unsigned f; /* Various useful flags */
549 sel_timer t; /* Response timer for challenge */
550 retry rs; /* Retry state */
551 octet hc[MAXHASHSZ]; /* Hash of his challenge */
552 octet ck[MAXHASHSZ]; /* His magical check value */
553 octet hswrq_in[MAXHASHSZ]; /* Inbound switch request message */
554 octet hswok_in[MAXHASHSZ]; /* Inbound switch confirmation */
555 octet hswrq_out[MAXHASHSZ]; /* Outbound switch request message */
556 octet hswok_out[MAXHASHSZ]; /* Outbound switch confirmation */
559 typedef struct keyexch {
560 struct peer *p; /* Pointer back to the peer */
561 kdata *kpriv; /* Private key and related info */
562 kdata *kpub; /* Peer's public key */
563 keyset **ks; /* Peer's list of keysets */
564 unsigned f; /* Various useful flags */
565 unsigned s; /* Current state in exchange */
566 sel_timer t; /* Timer for next exchange */
567 retry rs; /* Retry state */
568 dhsc *a; /* My temporary secret */
569 dhge *C; /* My challenge */
570 dhge *RX; /* The expected response */
571 unsigned nr; /* Number of extant responses */
572 time_t t_valid; /* When this exchange goes bad */
573 octet hc[MAXHASHSZ]; /* Hash of my challenge */
574 kxchal *r[KX_NCHAL]; /* Array of challenges */
577 #define KXF_TIMER 1u /* Waiting for a timer to go off */
578 #define KXF_DEAD 2u /* The key-exchanger isn't up */
579 #define KXF_PUBKEY 4u /* Key exchanger has a public key */
580 #define KXF_CORK 8u /* Don't send anything yet */
583 KXS_DEAD, /* Uninitialized state (magical) */
584 KXS_CHAL, /* Main answer-challenges state */
585 KXS_COMMIT, /* Committed: send switch request */
586 KXS_SWITCH /* Switched: send confirmation */
589 /* --- Tunnel structure --- *
591 * Used to maintain system-specific information about the tunnel interface.
594 typedef struct tunnel tunnel;
597 typedef struct tunnel_ops {
598 const char *name; /* Name of this tunnel driver */
599 unsigned flags; /* Various interesting flags */
600 #define TUNF_PRIVOPEN 1u /* Need helper to open file */
601 void (*init)(void); /* Initializes the system */
602 tunnel *(*create)(struct peer */*p*/, int /*fd*/, char **/*ifn*/);
603 /* Initializes a new tunnel */
604 void (*setifname)(tunnel */*t*/, const char */*ifn*/);
605 /* Notifies ifname change */
606 void (*inject)(tunnel */*t*/, buf */*b*/); /* Sends packet through if */
607 void (*destroy)(tunnel */*t*/); /* Destroys a tunnel */
610 #ifndef TUN_INTERNALS
611 struct tunnel { const tunnel_ops *ops; };
614 /* --- Peer statistics --- *
616 * Contains various interesting and not-so-interesting statistics about a
617 * peer. This is updated by various parts of the code. The format of the
618 * structure isn't considered private, and @p_stats@ returns a pointer to the
619 * statistics block for a given peer.
622 typedef struct stats {
623 unsigned long sz_in, sz_out; /* Size of all data in and out */
624 unsigned long sz_kxin, sz_kxout; /* Size of key exchange messages */
625 unsigned long sz_ipin, sz_ipout; /* Size of encapsulated IP packets */
626 time_t t_start, t_last, t_kx; /* Time peer created, last pk, kx */
627 unsigned long n_reject; /* Number of rejected packets */
628 unsigned long n_in, n_out; /* Number of packets in and out */
629 unsigned long n_kxin, n_kxout; /* Number of key exchange packets */
630 unsigned long n_ipin, n_ipout; /* Number of encrypted packets */
633 /* --- Peer structure --- *
635 * The main structure which glues everything else together.
638 typedef struct peerspec {
639 char *name; /* Peer's name */
640 char *privtag; /* Private key tag */
641 char *tag; /* Public key tag */
642 char *knock; /* Knock string, or null */
643 const tunnel_ops *tops; /* Tunnel operations */
644 unsigned long t_ka; /* Keep alive interval */
645 addr sa; /* Socket address to speak to */
646 unsigned f; /* Flags for the peer */
647 #define PSF_KXMASK 255u /* Key-exchange flags to set */
648 #define PSF_MOBILE 256u /* Address may change rapidly */
649 #define PSF_EPHEM 512u /* Association is ephemeral */
652 typedef struct peer_byname {
657 typedef struct peer_byaddr {
662 typedef struct peer {
663 peer_byname *byname; /* Lookup-by-name block */
664 peer_byaddr *byaddr; /* Lookup-by-address block */
665 struct ping *pings; /* Pings we're waiting for */
666 peerspec spec; /* Specifications for this peer */
667 int afix; /* Index of address family */
668 tunnel *t; /* Tunnel for local packets */
669 char *ifname; /* Interface name for tunnel */
670 keyset *ks; /* List head for keysets */
671 buf b; /* Buffer for sending packets */
672 stats st; /* Statistics */
673 keyexch kx; /* Key exchange protocol block */
674 sel_timer tka; /* Timer for keepalives */
677 typedef struct peer_iter { sym_iter i; } peer_iter;
679 typedef struct udpsocket {
680 sel_file sf; /* Selector for the socket */
683 typedef struct ping {
684 struct ping *next, *prev; /* Links to next and previous */
685 peer *p; /* Peer so we can free it */
686 unsigned msg; /* Kind of response expected */
687 uint32 id; /* Id so we can recognize response */
688 octet magic[32]; /* Some random data */
689 sel_timer t; /* Timeout for ping */
690 void (*func)(int /*rc*/, void */*arg*/); /* Function to call when done */
691 void *arg; /* Argument for callback */
702 /* --- Admin structure --- */
704 #define OBUFSZ 16384u
706 typedef struct obuf {
707 struct obuf *next; /* Next buffer in list */
708 char *p_in, *p_out; /* Pointers into the buffer */
709 char buf[OBUFSZ]; /* The actual buffer */
712 typedef struct oqueue {
713 obuf *hd, *tl; /* Head and tail pointers */
718 typedef struct admin_bgop {
719 struct admin_bgop *next, *prev; /* Links to next and previous */
720 struct admin *a; /* Owner job */
721 char *tag; /* Tag string for messages */
722 void (*cancel)(struct admin_bgop *); /* Destructor function */
725 typedef struct admin_resop {
726 admin_bgop bg; /* Background operation header */
727 char *addr; /* Hostname to be resolved */
731 bres_client r; /* Background resolver task */
733 sel_timer t; /* Timer for resolver */
734 addr sa; /* Socket address */
735 unsigned port; /* Port number chosen */
736 size_t sasz; /* Socket address size */
737 void (*func)(struct admin_resop *, int); /* Handler */
740 enum { ARES_OK, ARES_FAIL };
742 typedef struct admin_addop {
743 admin_resop r; /* Name resolution header */
744 peerspec peer; /* Peer pending creation */
747 typedef struct admin_pingop {
748 admin_bgop bg; /* Background operation header */
749 ping ping; /* Ping pending response */
750 struct timeval pingtime; /* Time last ping was sent */
753 typedef struct admin_service {
754 sym_base _b; /* Hash table base structure */
755 char *version; /* The provided version */
756 struct admin *prov; /* Which client provides me */
757 struct admin_service *next, *prev; /* Client's list of services */
760 typedef struct admin_svcop {
761 admin_bgop bg; /* Background operation header */
762 struct admin *prov; /* Client servicing this job */
763 unsigned index; /* This job's index */
764 struct admin_svcop *next, *prev; /* Links for provider's jobs */
767 typedef struct admin_jobentry {
768 unsigned short seq; /* Zero if unused */
770 admin_svcop *op; /* Operation, if slot in use, ... */
771 uint32 next; /* ... or index of next free slot */
775 typedef struct admin_jobtable {
776 uint32 n, sz; /* Used slots and table size */
777 admin_svcop *active; /* List of active jobs */
778 uint32 free; /* Index of first free slot */
779 admin_jobentry *v; /* And the big array of entries */
783 struct admin *next, *prev; /* Links to next and previous */
784 unsigned f; /* Various useful flags */
785 unsigned ref; /* Reference counter */
787 unsigned seq; /* Sequence number for tracing */
789 oqueue out; /* Output buffer list */
790 oqueue delay; /* Delayed output buffer list */
791 admin_bgop *bg; /* Backgrounded operations */
792 admin_service *svcs; /* Which services I provide */
793 admin_jobtable j; /* Table of outstanding jobs */
794 selbuf b; /* Line buffer for commands */
795 sel_file w; /* Selector for write buffering */
798 #define AF_DEAD 1u /* Destroy this admin block */
799 #define AF_CLOSE 2u /* Client closed connection */
800 #define AF_NOTE 4u /* Catch notifications */
801 #define AF_WARN 8u /* Catch warning messages */
803 # define AF_TRACE 16u /* Catch tracing */
805 #define AF_FOREGROUND 32u /* Quit server when client closes */
808 # define AF_ALLMSGS (AF_NOTE | AF_TRACE | AF_WARN)
810 # define AF_ALLMSGS (AF_NOTE | AF_WARN)
813 /*----- Global variables --------------------------------------------------*/
815 extern sel_state sel; /* Global I/O event state */
816 extern octet buf_i[PKBUFSZ], buf_o[PKBUFSZ], buf_t[PKBUFSZ], buf_u[PKBUFSZ];
817 extern const tunnel_ops *tunnels[]; /* Table of tunnels (0-term) */
818 extern const tunnel_ops *tun_default; /* Default tunnel to use */
819 extern udpsocket udpsock[NADDRFAM]; /* The master UDP sockets */
820 extern kdata *master; /* Default private key */
821 extern const char *tag_priv; /* Default private key tag */
824 extern const trace_opt tr_opts[]; /* Trace options array */
825 extern unsigned tr_flags; /* Trace options flags */
828 /*----- Other macros ------------------------------------------------------*/
831 do { rand_quick(RAND_GLOBAL); noise_timer(RAND_GLOBAL); } while (0)
833 /*----- Key management ----------------------------------------------------*/
835 /* --- @km_init@ --- *
837 * Arguments: @const char *privkr@ = private keyring file
838 * @const char *pubkr@ = public keyring file
839 * @const char *ptag@ = default private-key tag
843 * Use: Initializes the key-management machinery, loading the
844 * keyrings and so on.
847 extern void km_init(const char */*privkr*/, const char */*pubkr*/,
848 const char */*ptag*/);
850 /* --- @km_reload@ --- *
854 * Returns: Zero if OK, nonzero to force reloading of keys.
856 * Use: Checks the keyrings to see if they need reloading.
859 extern int km_reload(void);
861 /* --- @km_findpub@, @km_findpriv@ --- *
863 * Arguments: @const char *tag@ = key tag to load
865 * Returns: Pointer to the kdata object if successful, or null on error.
867 * Use: Fetches a public or private key from the keyring.
870 extern kdata *km_findpub(const char */*tag*/);
871 extern kdata *km_findpriv(const char */*tag*/);
873 /* --- @km_findpubbyid@, @km_findprivbyid@ --- *
875 * Arguments: @uint32 id@ = key id to load
877 * Returns: Pointer to the kdata object if successful, or null on error.
879 * Use: Fetches a public or private key from the keyring given its
883 extern kdata *km_findpubbyid(uint32 /*id*/);
884 extern kdata *km_findprivbyid(uint32 /*id*/);
886 /* --- @km_samealgsp@ --- *
888 * Arguments: @const kdata *kdx, *kdy@ = two key data objects
890 * Returns: Nonzero if their two algorithm selections are the same.
892 * Use: Checks sameness of algorithm selections: used to ensure that
893 * peers are using sensible algorithms.
896 extern int km_samealgsp(const kdata */*kdx*/, const kdata */*kdy*/);
898 /* --- @km_ref@ --- *
900 * Arguments: @kdata *kd@ = pointer to the kdata object
904 * Use: Claim a new reference to a kdata object.
907 extern void km_ref(kdata */*kd*/);
909 /* --- @km_unref@ --- *
911 * Arguments: @kdata *kd@ = pointer to the kdata object
915 * Use: Releases a reference to a kdata object.
918 extern void km_unref(kdata */*kd*/);
920 /* --- @km_tag@ --- *
922 * Arguments: @kdata *kd@ - pointer to the kdata object
924 * Returns: A pointer to the short tag by which the kdata was loaded.
927 extern const char *km_tag(kdata */*kd*/);
929 /*----- Key exchange ------------------------------------------------------*/
931 /* --- @kx_start@ --- *
933 * Arguments: @keyexch *kx@ = pointer to key exchange context
934 * @int forcep@ = nonzero to ignore the quiet timer
938 * Use: Stimulates a key exchange. If a key exchage is in progress,
939 * a new challenge is sent (unless the quiet timer forbids
940 * this); if no exchange is in progress, one is commenced.
943 extern void kx_start(keyexch */*kx*/, int /*forcep*/);
945 /* --- @kx_message@ --- *
947 * Arguments: @keyexch *kx@ = pointer to key exchange context
948 * @const addr *a@ = sender's IP address and port
949 * @unsigned msg@ = the message code
950 * @buf *b@ = pointer to buffer containing the packet
952 * Returns: Nonzero if the sender's address was unknown.
954 * Use: Reads a packet containing key exchange messages and handles
958 extern int kx_message(keyexch */*kx*/, const addr */*a*/,
959 unsigned /*msg*/, buf */*b*/);
961 /* --- @kx_free@ --- *
963 * Arguments: @keyexch *kx@ = pointer to key exchange context
967 * Use: Frees everything in a key exchange context.
970 extern void kx_free(keyexch */*kx*/);
972 /* --- @kx_newkeys@ --- *
974 * Arguments: @keyexch *kx@ = pointer to key exchange context
978 * Use: Informs the key exchange module that its keys may have
979 * changed. If fetching the new keys fails, the peer will be
980 * destroyed, we log messages and struggle along with the old
984 extern void kx_newkeys(keyexch */*kx*/);
986 /* --- @kx_setup@ --- *
988 * Arguments: @keyexch *kx@ = pointer to key exchange context
989 * @peer *p@ = pointer to peer context
990 * @keyset **ks@ = pointer to keyset list
991 * @unsigned f@ = various useful flags
993 * Returns: Zero if OK, nonzero if it failed.
995 * Use: Initializes a key exchange module. The module currently
996 * contains no keys, and will attempt to initiate a key
1000 extern int kx_setup(keyexch */*kx*/, peer */*p*/,
1001 keyset **/*ks*/, unsigned /*f*/);
1003 /* --- @kx_init@ --- *
1009 * Use: Initializes the key-exchange logic.
1012 extern void kx_init(void);
1014 /*----- Keysets and symmetric cryptography --------------------------------*/
1016 /* --- @ks_drop@ --- *
1018 * Arguments: @keyset *ks@ = pointer to a keyset
1022 * Use: Decrements a keyset's reference counter. If the counter hits
1023 * zero, the keyset is freed.
1026 extern void ks_drop(keyset */*ks*/);
1028 /* --- @ks_gen@ --- *
1030 * Arguments: @deriveargs *a@ = key derivation parameters (modified)
1031 * @peer *p@ = pointer to peer information
1033 * Returns: A pointer to the new keyset.
1035 * Use: Derives a new keyset from the given key material. This will
1036 * set the @what@, @f@, and @hc@ members in @*a@; other members
1037 * must be filled in by the caller.
1039 * The new key is marked so that it won't be selected for output
1040 * by @ksl_encrypt@. You can still encrypt data with it by
1041 * calling @ks_encrypt@ directly.
1044 extern keyset *ks_gen(deriveargs */*a*/, peer */*p*/);
1046 /* --- @ks_activate@ --- *
1048 * Arguments: @keyset *ks@ = pointer to a keyset
1052 * Use: Activates a keyset, so that it can be used for encrypting
1053 * outgoing messages.
1056 extern void ks_activate(keyset */*ks*/);
1058 /* --- @ks_encrypt@ --- *
1060 * Arguments: @keyset *ks@ = pointer to a keyset
1061 * @unsigned ty@ = message type
1062 * @buf *b@ = pointer to input buffer
1063 * @buf *bb@ = pointer to output buffer
1065 * Returns: Zero if successful; @KSERR_REGEN@ if we should negotiate a
1066 * new key; @KSERR_NOKEYS@ if the key is not usable. Also
1067 * returns zero if there was insufficient buffer (but the output
1068 * buffer is broken in this case).
1070 * Use: Encrypts a block of data using the key. Note that the `key
1071 * ought to be replaced' notification is only ever given once
1072 * for each key. Also note that this call forces a keyset to be
1073 * used even if it's marked as not for data output.
1075 * The encryption transform is permitted to corrupt @buf_u@ for
1076 * its own purposes. Neither the source nor destination should
1077 * be within @buf_u@; and callers mustn't expect anything stored
1078 * in @buf_u@ to still
1081 extern int ks_encrypt(keyset */*ks*/, unsigned /*ty*/,
1082 buf */*b*/, buf */*bb*/);
1084 /* --- @ks_decrypt@ --- *
1086 * Arguments: @keyset *ks@ = pointer to a keyset
1087 * @unsigned ty@ = expected type code
1088 * @buf *b@ = pointer to an input buffer
1089 * @buf *bb@ = pointer to an output buffer
1091 * Returns: Zero on success; @KSERR_DECRYPT@ on failure. Also returns
1092 * zero if there was insufficient buffer (but the output buffer
1093 * is broken in this case).
1095 * Use: Attempts to decrypt a message using a given key. Note that
1096 * requesting decryption with a key directly won't clear a
1097 * marking that it's not for encryption.
1099 * The decryption transform is permitted to corrupt @buf_u@ for
1100 * its own purposes. Neither the source nor destination should
1101 * be within @buf_u@; and callers mustn't expect anything stored
1102 * in @buf_u@ to still
1105 extern int ks_decrypt(keyset */*ks*/, unsigned /*ty*/,
1106 buf */*b*/, buf */*bb*/);
1108 /* --- @ksl_free@ --- *
1110 * Arguments: @keyset **ksroot@ = pointer to keyset list head
1114 * Use: Frees (releases references to) all of the keys in a keyset.
1117 extern void ksl_free(keyset **/*ksroot*/);
1119 /* --- @ksl_link@ --- *
1121 * Arguments: @keyset **ksroot@ = pointer to keyset list head
1122 * @keyset *ks@ = pointer to a keyset
1126 * Use: Links a keyset into a list. A keyset can only be on one list
1127 * at a time. Bad things happen otherwise.
1130 extern void ksl_link(keyset **/*ksroot*/, keyset */*ks*/);
1132 /* --- @ksl_prune@ --- *
1134 * Arguments: @keyset **ksroot@ = pointer to keyset list head
1138 * Use: Prunes the keyset list by removing keys which mustn't be used
1142 extern void ksl_prune(keyset **/*ksroot*/);
1144 /* --- @ksl_encrypt@ --- *
1146 * Arguments: @keyset **ksroot@ = pointer to keyset list head
1147 * @unsigned ty@ = message type
1148 * @buf *b@ = pointer to input buffer
1149 * @buf *bb@ = pointer to output buffer
1151 * Returns: Zero if successful; @KSERR_REGEN@ if it's time to negotiate a
1152 * new key; @KSERR_NOKEYS@ if there are no suitable keys
1153 * available. Also returns zero if there was insufficient
1154 * buffer space (but the output buffer is broken in this case).
1156 * Use: Encrypts a packet.
1159 extern int ksl_encrypt(keyset **/*ksroot*/, unsigned /*ty*/,
1160 buf */*b*/, buf */*bb*/);
1162 /* --- @ksl_decrypt@ --- *
1164 * Arguments: @keyset **ksroot@ = pointer to keyset list head
1165 * @unsigned ty@ = expected type code
1166 * @buf *b@ = pointer to input buffer
1167 * @buf *bb@ = pointer to output buffer
1169 * Returns: Zero on success; @KSERR_DECRYPT@ on failure. Also returns
1170 * zero if there was insufficient buffer (but the output buffer
1171 * is broken in this case).
1173 * Use: Decrypts a packet.
1176 extern int ksl_decrypt(keyset **/*ksroot*/, unsigned /*ty*/,
1177 buf */*b*/, buf */*bb*/);
1179 /*----- Challenges --------------------------------------------------------*/
1181 /* --- @c_new@ --- *
1183 * Arguments: @const void *m@ = pointer to associated message, or null
1184 * @size_t msz@ = length of associated message
1185 * @buf *b@ = where to put the challenge
1187 * Returns: Zero if OK, nonzero on error.
1189 * Use: Issues a new challenge.
1192 extern int c_new(const void */*m*/, size_t /*msz*/, buf */*b*/);
1194 /* --- @c_check@ --- *
1196 * Arguments: @const void *m@ = pointer to associated message, or null
1197 * @size_t msz@ = length of associated message
1198 * @buf *b@ = where to find the challenge
1200 * Returns: Zero if OK, nonzero if it didn't work.
1202 * Use: Checks a challenge. On failure, the buffer is broken.
1205 extern int c_check(const void */*m*/, size_t /*msz*/, buf */*b*/);
1207 /*----- Administration interface ------------------------------------------*/
1209 #define A_END ((char *)0)
1211 /* --- @a_vformat@ --- *
1213 * Arguments: @dstr *d@ = where to leave the formatted message
1214 * @const char *fmt@ = pointer to format string
1215 * @va_list *ap@ = arguments in list
1219 * Use: Main message token formatting driver. The arguments are
1220 * interleaved formatting tokens and their parameters, finally
1221 * terminated by an entry @A_END@.
1223 * Tokens recognized:
1225 * * "*..." ... -- pretokenized @dstr_putf@-like string
1227 * * "?ADDR" SOCKADDR -- a socket address, to be converted
1229 * * "?B64" BUFFER SIZE -- binary data to be base64-encoded
1231 * * "?TOKENS" VECTOR -- null-terminated vector of tokens
1233 * * "?PEER" PEER -- peer's name
1235 * * "?ERRNO" ERRNO -- system error code
1237 * * "[!]..." ... -- @dstr_putf@-like string as single token
1240 extern void a_vformat(dstr */*d*/, const char */*fmt*/, va_list */*ap*/);
1242 /* --- @a_format@ --- *
1244 * Arguments: @dstr *d@ = where to leave the formatted message
1245 * @const char *fmt@ = pointer to format string
1249 * Use: Writes a tokenized message into a string, for later
1253 extern void EXECL_LIKE(0) a_format(dstr */*d*/, const char */*fmt*/, ...);
1255 /* --- @a_info@ --- *
1257 * Arguments: @admin *a@ = connection
1258 * @const char *fmt@ = format string
1259 * @...@ = other arguments
1263 * Use: Report information to an admin client.
1266 extern void EXECL_LIKE(0) a_info(admin */*a*/, const char */*fmt*/, ...);
1268 /* --- @a_warn@ --- *
1270 * Arguments: @const char *fmt@ = pointer to format string
1271 * @...@ = other arguments
1275 * Use: Informs all admin connections of a warning.
1278 extern void EXECL_LIKE(0) a_warn(const char */*fmt*/, ...);
1280 /* --- @a_notify@ --- *
1282 * Arguments: @const char *fmt@ = pointer to format string
1283 * @...@ = other arguments
1287 * Use: Sends a notification to interested admin connections.
1290 extern void EXECL_LIKE(0) a_notify(const char */*fmt*/, ...);
1292 /* --- @a_create@ --- *
1294 * Arguments: @int fd_in, fd_out@ = file descriptors to use
1295 * @unsigned f@ = initial flags to set
1299 * Use: Creates a new admin connection.
1302 extern void a_create(int /*fd_in*/, int /*fd_out*/, unsigned /*f*/);
1304 /* --- @a_quit@ --- *
1310 * Use: Shuts things down nicely.
1313 extern void a_quit(void);
1315 /* --- @a_preselect@ --- *
1321 * Use: Informs the admin module that we're about to select again,
1322 * and that it should do cleanup things it has delayed until a
1326 extern void a_preselect(void);
1328 /* --- @a_daemon@ --- *
1334 * Use: Informs the admin module that it's a daemon.
1337 extern void a_daemon(void);
1339 /* --- @a_init@ --- *
1341 * Arguments: @const char *sock@ = socket name to create
1342 * @uid_t u@ = user to own the socket
1343 * @gid_t g@ = group to own the socket
1344 * @mode_t m@ = permissions to set on the socket
1348 * Use: Creates the admin listening socket.
1351 extern void a_init(const char */*sock*/,
1352 uid_t /*u*/, gid_t /*g*/, mode_t /*m*/);
1354 /*----- Mapping with addresses as keys ------------------------------------*/
1356 /* --- @am_create@ --- *
1358 * Arguments: @addrmap *m@ = pointer to map
1362 * Use: Create an address map, properly set up.
1365 extern void am_create(addrmap */*m*/);
1367 /* --- @am_destroy@ --- *
1369 * Arguments: @addrmap *m@ = pointer to map
1373 * Use: Destroy an address map, throwing away all the entries.
1376 extern void am_destroy(addrmap */*m*/);
1378 /* --- @am_find@ --- *
1380 * Arguments: @addrmap *m@ = pointer to map
1381 * @const addr *a@ = address to look up
1382 * @size_t sz@ = size of block to allocate
1383 * @unsigned *f@ = where to store flags
1385 * Returns: Pointer to found item, or null.
1387 * Use: Finds a record with the given IP address, set @*f@ nonzero
1388 * and returns it. If @sz@ is zero, and no match was found,
1389 * return null; otherwise allocate a new block of @sz@ bytes,
1390 * clear @*f@ to zero and return the block pointer.
1393 extern void *am_find(addrmap */*m*/, const addr */*a*/,
1394 size_t /*sz*/, unsigned */*f*/);
1396 /* --- @am_remove@ --- *
1398 * Arguments: @addrmap *m@ = pointer to map
1399 * @void *i@ = pointer to the item
1403 * Use: Removes an item from the map.
1406 extern void am_remove(addrmap */*m*/, void */*i*/);
1408 /*----- Privilege separation ----------------------------------------------*/
1410 /* --- @ps_trace@ --- *
1412 * Arguments: @unsigned mask@ = trace mask to check
1413 * @const char *fmt@ = message format
1414 * @...@ = values for placeholders
1418 * Use: Writes a trace message.
1421 T( extern void PRINTF_LIKE(2, 3)
1422 ps_trace(unsigned /*mask*/, const char */*fmt*/, ...); )
1424 /* --- @ps_warn@ --- *
1426 * Arguments: @const char *fmt@ = message format
1427 * @...@ = values for placeholders
1431 * Use: Writes a warning message.
1434 extern void PRINTF_LIKE(1, 2) ps_warn(const char */*fmt*/, ...);
1436 /* --- @ps_tunfd@ --- *
1438 * Arguments: @const tunnel_ops *tops@ = pointer to tunnel operations
1439 * @char **ifn@ = where to put the interface name
1441 * Returns: The file descriptor, or @-1@ on error.
1443 * Use: Fetches a file descriptor for a tunnel driver.
1446 extern int ps_tunfd(const tunnel_ops */*tops*/, char **/*ifn*/);
1448 /* --- @ps_split@ --- *
1450 * Arguments: @int detachp@ = whether to detach the child from its terminal
1454 * Use: Separates off the privileged tunnel-opening service from the
1455 * rest of the server.
1458 extern void ps_split(int /*detachp*/);
1460 /* --- @ps_quit@ --- *
1466 * Use: Detaches from the helper process.
1469 extern void ps_quit(void);
1471 /*----- Peer management ---------------------------------------------------*/
1473 /* --- @p_updateaddr@ --- *
1475 * Arguments: @peer *p@ = pointer to peer block
1476 * @const addr *a@ = address to associate with this peer
1478 * Returns: Zero if the address was changed; @+1@ if it was already
1481 * Use: Updates our idea of @p@'s address.
1484 extern int p_updateaddr(peer */*p*/, const addr */*a*/);
1486 /* --- @p_txstart@ --- *
1488 * Arguments: @peer *p@ = pointer to peer block
1489 * @unsigned msg@ = message type code
1491 * Returns: A pointer to a buffer to write to.
1493 * Use: Starts sending to a peer. Only one send can happen at a
1497 extern buf *p_txstart(peer */*p*/, unsigned /*msg*/);
1499 /* --- @p_txaddr@ --- *
1501 * Arguments: @const addr *a@ = recipient address
1502 * @const void *p@ = pointer to packet to send
1503 * @size_t sz@ = length of packet
1505 * Returns: Zero if successful, nonzero on error.
1507 * Use: Sends a packet to an address which (possibly) isn't a current
1511 extern int p_txaddr(const addr */*a*/, const void */*p*/, size_t /*sz*/);
1513 /* --- @p_txend@ --- *
1515 * Arguments: @peer *p@ = pointer to peer block
1519 * Use: Sends a packet to the peer.
1522 extern void p_txend(peer */*p*/);
1524 /* --- @p_pingsend@ --- *
1526 * Arguments: @peer *p@ = destination peer
1527 * @ping *pg@ = structure to fill in
1528 * @unsigned type@ = message type
1529 * @unsigned long timeout@ = how long to wait before giving up
1530 * @void (*func)(int, void *)@ = callback function
1531 * @void *arg@ = argument for callback
1533 * Returns: Zero if successful, nonzero if it failed.
1535 * Use: Sends a ping to a peer. Call @func@ with a nonzero argument
1536 * if we get an answer within the timeout, or zero if no answer.
1539 extern int p_pingsend(peer */*p*/, ping */*pg*/, unsigned /*type*/,
1540 unsigned long /*timeout*/,
1541 void (*/*func*/)(int, void *), void */*arg*/);
1543 /* --- @p_pingdone@ --- *
1545 * Arguments: @ping *p@ = ping structure
1546 * @int rc@ = return code to pass on
1550 * Use: Disposes of a ping structure, maybe sending a notification.
1553 extern void p_pingdone(ping */*p*/, int /*rc*/);
1555 /* --- @p_greet@ --- *
1557 * Arguments: @peer *p@ = peer to send to
1558 * @const void *c@ = pointer to challenge
1559 * @size_t sz@ = size of challenge
1563 * Use: Sends a greeting packet.
1566 extern void p_greet(peer */*p*/, const void */*c*/, size_t /*sz*/);
1568 /* --- @p_tun@ --- *
1570 * Arguments: @peer *p@ = pointer to peer block
1571 * @buf *b@ = buffer containing incoming packet
1575 * Use: Handles a packet which needs to be sent to a peer.
1578 extern void p_tun(peer */*p*/, buf */*b*/);
1580 /* --- @p_keyreload@ --- *
1586 * Use: Forces a check of the daemon's keyring files.
1589 extern void p_keyreload(void);
1591 /* --- @p_interval@ --- *
1597 * Use: Called periodically to do tidying.
1600 extern void p_interval(void);
1602 /* --- @p_stats@ --- *
1604 * Arguments: @peer *p@ = pointer to a peer block
1606 * Returns: A pointer to the peer's statistics.
1609 extern stats *p_stats(peer */*p*/);
1611 /* --- @p_ifname@ --- *
1613 * Arguments: @peer *p@ = pointer to a peer block
1615 * Returns: A pointer to the peer's interface name.
1618 extern const char *p_ifname(peer */*p*/);
1620 /* --- @p_setifname@ --- *
1622 * Arguments: @peer *p@ = pointer to a peer block
1623 * @const char *name@ = pointer to the new name
1627 * Use: Changes the name held for a peer's interface.
1630 extern void p_setifname(peer */*p*/, const char */*name*/);
1632 /* --- @p_addr@ --- *
1634 * Arguments: @peer *p@ = pointer to a peer block
1636 * Returns: A pointer to the peer's address.
1639 extern const addr *p_addr(peer */*p*/);
1641 /* --- @p_init@ --- *
1643 * Arguments: @struct addrinfo *ailist@ = addresses to bind to
1647 * Use: Initializes the peer system; creates the socket.
1650 extern void p_init(struct addrinfo */*ailist*/);
1652 /* --- @p_port@ --- *
1654 * Arguments: @int i@ = address family index to retrieve
1656 * Returns: Port number used for socket.
1659 extern unsigned p_port(int /*i*/);
1661 /* --- @p_create@ --- *
1663 * Arguments: @peerspec *spec@ = information about this peer
1665 * Returns: Pointer to the peer block, or null if it failed.
1667 * Use: Creates a new named peer block. No peer is actually attached
1671 extern peer *p_create(peerspec */*spec*/);
1673 /* --- @p_name@ --- *
1675 * Arguments: @peer *p@ = pointer to a peer block
1677 * Returns: A pointer to the peer's name.
1679 * Use: Equivalent to @p_spec(p)->name@.
1682 extern const char *p_name(peer */*p*/);
1684 /* --- @p_tag@ --- *
1686 * Arguments: @peer *p@ = pointer to a peer block
1688 * Returns: A pointer to the peer's public key tag.
1691 extern const char *p_tag(peer */*p*/);
1693 /* --- @p_privtag@ --- *
1695 * Arguments: @peer *p@ = pointer to a peer block
1697 * Returns: A pointer to the peer's private key tag.
1700 extern const char *p_privtag(peer */*p*/);
1702 /* --- @p_spec@ --- *
1704 * Arguments: @peer *p@ = pointer to a peer block
1706 * Returns: Pointer to the peer's specification
1709 extern const peerspec *p_spec(peer */*p*/);
1711 /* --- @p_findbyaddr@ --- *
1713 * Arguments: @const addr *a@ = address to look up
1715 * Returns: Pointer to the peer block, or null if not found.
1717 * Use: Finds a peer by address.
1720 extern peer *p_findbyaddr(const addr */*a*/);
1722 /* --- @p_find@ --- *
1724 * Arguments: @const char *name@ = name to look up
1726 * Returns: Pointer to the peer block, or null if not found.
1728 * Use: Finds a peer by name.
1731 extern peer *p_find(const char */*name*/);
1733 /* --- @p_destroy@ --- *
1735 * Arguments: @peer *p@ = pointer to a peer
1736 * @int bye@ = say goodbye to the peer?
1740 * Use: Destroys a peer.
1743 extern void p_destroy(peer */*p*/, int /*bye*/);
1745 /* --- @FOREACH_PEER@ --- *
1747 * Arguments: @p@ = name to bind to each peer
1748 * @stuff@ = thing to do for each item
1750 * Use: Does something for each current peer.
1753 #define FOREACH_PEER(p, stuff) do { \
1756 for (p_mkiter(&i_); (p = p_next(&i_)) != 0; ) stuff \
1759 /* --- @p_mkiter@ --- *
1761 * Arguments: @peer_iter *i@ = pointer to an iterator
1765 * Use: Initializes the iterator.
1768 extern void p_mkiter(peer_iter */*i*/);
1770 /* --- @p_next@ --- *
1772 * Arguments: @peer_iter *i@ = pointer to an iterator
1774 * Returns: Next peer, or null if at the end.
1776 * Use: Returns the next peer.
1779 extern peer *p_next(peer_iter */*i*/);
1781 /*----- Tunnel drivers ----------------------------------------------------*/
1784 extern const tunnel_ops tun_linux;
1788 extern const tunnel_ops tun_unet;
1792 extern const tunnel_ops tun_bsd;
1795 extern const tunnel_ops tun_slip;
1797 /*----- Other handy utilities ---------------------------------------------*/
1799 /* --- @timestr@ --- *
1801 * Arguments: @time_t t@ = a time to convert
1803 * Returns: A pointer to a textual representation of the time.
1805 * Use: Converts a time to a textual representation. Corrupts
1809 extern const char *timestr(time_t /*t*/);
1811 /* --- @mystrieq@ --- *
1813 * Arguments: @const char *x, *y@ = two strings
1815 * Returns: True if @x@ and @y are equal, up to case.
1818 extern int mystrieq(const char */*x*/, const char */*y*/);
1822 * Arguments: @int af@ = an address family code
1824 * Returns: The index of the address family's record in @aftab@, or @-1@.
1827 extern int afix(int af);
1829 /* --- @addrsz@ --- *
1831 * Arguments: @const addr *a@ = a network address
1833 * Returns: The size of the address, for passing into the sockets API.
1836 extern socklen_t addrsz(const addr */*a*/);
1838 /* --- @getport@, @setport@ --- *
1840 * Arguments: @addr *a@ = a network address
1841 * @unsigned port@ = port number to set
1845 * Use: Retrieves or sets the port number in an address structure.
1848 extern unsigned getport(addr */*a*/);
1849 extern void setport(addr */*a*/, unsigned /*port*/);
1851 /* --- @seq_reset@ --- *
1853 * Arguments: @seqwin *s@ = sequence-checking window
1857 * Use: Resets a sequence number window.
1860 extern void seq_reset(seqwin */*s*/);
1862 /* --- @seq_check@ --- *
1864 * Arguments: @seqwin *s@ = sequence-checking window
1865 * @uint32 q@ = sequence number to check
1866 * @const char *service@ = service to report message from
1868 * Returns: A @SEQ_@ code.
1870 * Use: Checks a sequence number against the window, updating things
1874 extern int seq_check(seqwin */*s*/, uint32 /*q*/, const char */*service*/);
1876 typedef struct ratelim {
1877 unsigned n, max, persec;
1878 struct timeval when;
1881 /* --- @ratelim_init@ --- *
1883 * Arguments: @ratelim *r@ = rate-limiting state to fill in
1884 * @unsigned persec@ = credit to accumulate per second
1885 * @unsigned max@ = maximum credit to retain
1889 * Use: Initialize a rate-limiting state.
1892 extern void ratelim_init(ratelim */*r*/,
1893 unsigned /*persec*/, unsigned /*max*/);
1895 /* --- @ratelim_withdraw@ --- *
1897 * Arguments: @ratelim *r@ = rate-limiting state
1898 * @unsigned n@ = credit to withdraw
1900 * Returns: Zero if successful; @-1@ if there is unsufficient credit
1902 * Use: Updates the state with any accumulated credit. Then, if
1903 * there there are more than @n@ credits available, withdraw @n@
1904 * and return successfully; otherwise, report failure.
1907 extern int ratelim_withdraw(ratelim */*r*/, unsigned /*n*/);
1909 /* --- @ies_encrypt@ --- *
1911 * Arguments: @kdata *kpub@ = recipient's public key
1912 * @unsigned ty@ = message type octet
1913 * @buf *b@ = input message buffer
1914 * @buf *bb@ = output buffer for the ciphertext
1916 * Returns: On error, returns a @KSERR_...@ code or breaks the buffer;
1917 * on success, returns zero and the buffer is good.
1919 * Use: Encrypts a message for a recipient, given their public key.
1920 * This does not (by itself) provide forward secrecy or sender
1921 * authenticity. The ciphertext is self-delimiting (unlike
1925 extern int ies_encrypt(kdata */*kpub*/, unsigned /*ty*/,
1926 buf */*b*/, buf */*bb*/);
1928 /* --- @ies_decrypt@ --- *
1930 * Arguments: @kdata *kpub@ = private key key
1931 * @unsigned ty@ = message type octet
1932 * @buf *b@ = input ciphertext buffer
1933 * @buf *bb@ = output buffer for the message
1935 * Returns: On error, returns a @KSERR_...@ code; on success, returns
1936 * zero and the buffer is good.
1938 * Use: Decrypts a message encrypted using @ies_encrypt@, given our
1942 extern int ies_decrypt(kdata */*kpriv*/, unsigned /*ty*/,
1943 buf */*b*/, buf */*bb*/);
1945 /*----- That's all, folks -------------------------------------------------*/