server/keymgmt.c, server/tripe.c: Add `km_clear' to shut down keyrings.
[tripe] / server / tripe.h
1 /* -*-c-*-
2 *
3 * Main header file for TrIPE
4 *
5 * (c) 2001 Straylight/Edgeware
6 */
7
8 /*----- Licensing notice --------------------------------------------------*
9 *
10 * This file is part of Trivial IP Encryption (TrIPE).
11 *
12 * TrIPE is free software: you can redistribute it and/or modify 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.
16 *
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
20 * for more details.
21 *
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/>.
24 */
25
26 #ifndef TRIPE_H
27 #define TRIPE_H
28
29 #ifdef __cplusplus
30 extern "C" {
31 #endif
32
33 /*----- Header files ------------------------------------------------------*/
34
35 #include "config.h"
36
37 #include <assert.h>
38 #include <ctype.h>
39 #include <errno.h>
40 #include <limits.h>
41 #include <signal.h>
42 #include <stdarg.h>
43 #include <stddef.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <time.h>
48
49 #include <sys/types.h>
50 #include <sys/time.h>
51 #include <unistd.h>
52 #include <fcntl.h>
53 #include <sys/stat.h>
54 #include <sys/wait.h>
55
56 #include <sys/socket.h>
57 #include <sys/un.h>
58 #include <netinet/in.h>
59 #include <arpa/inet.h>
60 #include <netdb.h>
61
62 #include <pwd.h>
63 #include <grp.h>
64
65 #ifdef HAVE_LIBADNS
66 # define ADNS_FEATURE_MANYAF
67 # include <adns.h>
68 #endif
69
70 #include <mLib/alloc.h>
71 #include <mLib/arena.h>
72 #include <mLib/base64.h>
73 #ifndef HAVE_LIBADNS
74 # include <mLib/bres.h>
75 #endif
76 #include <mLib/codec.h>
77 #include <mLib/daemonize.h>
78 #include <mLib/dstr.h>
79 #include <mLib/env.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>
89 #include <mLib/sel.h>
90 #include <mLib/selbuf.h>
91 #include <mLib/sig.h>
92 #include <mLib/str.h>
93 #include <mLib/sub.h>
94 #include <mLib/trace.h>
95 #include <mLib/tv.h>
96 #include <mLib/versioncmp.h>
97
98 #include <catacomb/buf.h>
99 #include <catacomb/ct.h>
100
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>
109
110 #include <catacomb/noise.h>
111 #include <catacomb/rand.h>
112
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>
122
123 #include "priv.h"
124 #include "protocol.h"
125 #include "slip.h"
126 #include "util.h"
127
128 #undef sun
129
130 /*----- Magic numbers -----------------------------------------------------*/
131
132 /* --- Trace flags --- */
133
134 #define T_TUNNEL 1u
135 #define T_PEER 2u
136 #define T_PACKET 4u
137 #define T_ADMIN 8u
138 #define T_CRYPTO 16u
139 #define T_KEYSET 32u
140 #define T_KEYEXCH 64u
141 #define T_KEYMGMT 128u
142 #define T_CHAL 256u
143 /* T_PRIVSEP in priv.h */
144
145 #define T_ALL 1023u
146
147 /* --- Units --- */
148
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)
153
154 /* --- Timing parameters --- */
155
156 #define T_EXP MIN(60) /* Expiry time for a key */
157 #define T_REGEN MIN(40) /* Regeneration time for a key */
158
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 */
163
164 #define T_WOBBLE (1.0/3.0) /* Relative timer randomness */
165
166 /* --- Other things --- */
167
168 #define PKBUFSZ 65536
169
170 /*----- Cipher selections -------------------------------------------------*/
171
172 typedef struct keyset keyset;
173 typedef struct algswitch algswitch;
174 typedef struct kdata kdata;
175 typedef struct admin admin;
176
177 typedef struct dhgrp {
178 const struct dhops *ops;
179 size_t scsz;
180 } dhgrp;
181
182 typedef struct dhsc dhsc;
183 typedef struct dhge dhge;
184
185 enum {
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 */
189 };
190
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 */
199 } deriveargs;
200
201 typedef struct bulkalgs {
202 const struct bulkops *ops;
203 } bulkalgs;
204
205 typedef struct bulkctx {
206 const struct bulkops *ops;
207 } bulkctx;
208
209 typedef struct bulkchal {
210 const struct bulkops *ops;
211 size_t tagsz;
212 } bulkchal;
213
214 typedef struct dhops {
215 const char *name;
216
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.
223 */
224
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.
231 */
232
233 const char *(*checkgrp)(const dhgrp */*g*/);
234 /* Check that the group is valid; return null on success, or an error
235 * string.
236 */
237
238 void (*grpinfo)(const dhgrp */*g*/, admin */*a*/);
239 /* Report on the group to an admin client. */
240
241 T( void (*tracegrp)(const dhgrp */*g*/); )
242 /* Trace a description of the group. */
243
244 int (*samegrpp)(const dhgrp */*g*/, const dhgrp */*gg*/);
245 /* Return nonzero if the two group objects represent the same
246 * group.
247 */
248
249 void (*freegrp)(dhgrp */*g*/);
250 /* Free a group and the resources it holds. */
251
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
254 * error.
255 */
256
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. */
260
261 dhsc *(*randsc)(const dhgrp */*g*/);
262 /* Return a random scalar. */
263
264 T( const char *(*scstr)(const dhgrp */*g*/, const dhsc */*x*/); )
265 /* Return a human-readable representation of @x@; @buf_t@ may be used
266 * to hold it.
267 */
268
269 void (*freesc)(const dhgrp */*g*/, dhsc */*x*/);
270 /* Free a scalar and the resources it holds. */
271
272 dhge *(*ldge)(const dhgrp */*g*/, buf */*b*/, int /*fmt*/);
273 /* Load a group element from @b@, encoded using format @fmt@. Return
274 * null on error.
275 */
276
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
280 * nonzero on error.
281 */
282
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.
286 */
287
288 int (*eq)(const dhgrp */*g*/, const dhge */*Y*/, const dhge */*Z*/);
289 /* Return nonzero if @Y@ and @Z@ are equal. */
290
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
294 * generator.
295 */
296
297 T( const char *(*gestr)(const dhgrp */*g*/, const dhge */*Y*/); )
298 /* Return a human-readable representation of @Y@; @buf_t@ may be used
299 * to hold it.
300 */
301
302 void (*freege)(const dhgrp */*g*/, dhge */*Y*/);
303 /* Free a group element and the resources it holds. */
304
305 } dhops;
306
307 typedef struct bulkops {
308 const char *name;
309
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
314 * return null.
315 */
316
317 T( void (*tracealgs)(const bulkalgs */*a*/); )
318 /* Write trace information about the algorithm selection. */
319
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.
323 */
324
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.
328 */
329
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.
333 */
334
335 size_t (*overhead)(const bulkalgs */*a*/);
336 /* Return the per-packet overhead of the bulk transform, in bytes. */
337
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.
341 */
342
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.
354 */
355
356 bulkchal *(*genchal)(const bulkalgs */*a*/);
357 /* Construct and return a challenge issuing and verification
358 * context with a fresh random key.
359 */
360
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.)
365 */
366
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.
373 */
374
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.
380 */
381
382 void (*freectx)(bulkctx */*a*/);
383 /* Release a bulk encryption context and the resources it holds. */
384
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
389 * success.
390 */
391
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.
396 */
397
398 void (*freechal)(bulkchal */*bc*/);
399 /* Release a challenge context and the resources it holds. */
400
401 } bulkops;
402
403 struct algswitch {
404 const gchash *h; size_t hashsz; /* Hash function */
405 const gccipher *mgf; /* Mask-generation function */
406 bulkalgs *bulk; /* Bulk crypto algorithms */
407 };
408
409 struct kdata {
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 */
419 };
420
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 */
427 } knode;
428
429 #define MAXHASHSZ 64 /* Largest possible hash size */
430
431 #define HASH_STRING(h, s) GH_HASH((h), (s), sizeof(s))
432
433 extern const dhops dhtab[];
434 extern const bulkops bulktab[];
435
436 /*----- Data structures ---------------------------------------------------*/
437
438 /* --- The address-family table --- */
439
440 #define ADDRFAM(_) \
441 _(INET, want_ipv4) \
442 _(INET6, want_ipv6)
443
444 enum {
445 #define ENUM(af, qf) AFIX_##af,
446 ADDRFAM(ENUM)
447 #undef ENUM
448 NADDRFAM
449 };
450
451 extern const struct addrfam {
452 int af;
453 const char *name;
454 #ifdef HAVE_LIBADNS
455 adns_queryflags qf;
456 #endif
457 } aftab[NADDRFAM];
458
459 /* --- Socket addresses --- *
460 *
461 * A magic union of supported socket addresses.
462 */
463
464 typedef union addr {
465 struct sockaddr sa;
466 struct sockaddr_in sin;
467 struct sockaddr_in6 sin6;
468 } addr;
469
470 /* --- Mapping keyed on addresses --- */
471
472 typedef struct addrmap {
473 hash_table t;
474 size_t load;
475 } addrmap;
476
477 typedef struct addrmap_base {
478 hash_base b;
479 addr a;
480 } addrmap_base;
481
482 /* --- Sequence number checking --- */
483
484 typedef struct seqwin {
485 uint32 seq; /* First acceptable input sequence */
486 uint32 win; /* Window of acceptable numbers */
487 } seqwin;
488
489 #define SEQ_WINSZ 32 /* Bits in sequence number window */
490
491 /* --- A symmetric keyset --- *
492 *
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)
496 * is first.
497 *
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
501 * expiry.
502 */
503
504 enum { DIR_IN, DIR_OUT, NDIR };
505
506 struct keyset {
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 */
517 };
518
519 #define KSF_LISTEN 1u /* Don't encrypt packets yet */
520 #define KSF_LINK 2u /* Key is in a linked list */
521
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 */
527
528 /* --- Key exchange --- *
529 *
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
534 * Clive Jones.
535 */
536
537 typedef struct retry {
538 double t; /* Current retry time */
539 } retry;
540
541 #define KX_NCHAL 16u
542
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 */
557 } kxchal;
558
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 */
575 } keyexch;
576
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 */
581
582 enum {
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 */
587 };
588
589 /* --- Tunnel structure --- *
590 *
591 * Used to maintain system-specific information about the tunnel interface.
592 */
593
594 typedef struct tunnel tunnel;
595 struct peer;
596
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 */
608 } tunnel_ops;
609
610 #ifndef TUN_INTERNALS
611 struct tunnel { const tunnel_ops *ops; };
612 #endif
613
614 /* --- Peer statistics --- *
615 *
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.
620 */
621
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 */
631 } stats;
632
633 /* --- Peer structure --- *
634 *
635 * The main structure which glues everything else together.
636 */
637
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 */
650 } peerspec;
651
652 typedef struct peer_byname {
653 sym_base _b;
654 struct peer *p;
655 } peer_byname;
656
657 typedef struct peer_byaddr {
658 addrmap_base _b;
659 struct peer *p;
660 } peer_byaddr;
661
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 */
675 } peer;
676
677 typedef struct peer_iter { sym_iter i; } peer_iter;
678
679 typedef struct udpsocket {
680 sel_file sf; /* Selector for the socket */
681 unsigned port; /* Chosen port number */
682 } udpsocket;
683
684 typedef struct ping {
685 struct ping *next, *prev; /* Links to next and previous */
686 peer *p; /* Peer so we can free it */
687 unsigned msg; /* Kind of response expected */
688 uint32 id; /* Id so we can recognize response */
689 octet magic[32]; /* Some random data */
690 sel_timer t; /* Timeout for ping */
691 void (*func)(int /*rc*/, void */*arg*/); /* Function to call when done */
692 void *arg; /* Argument for callback */
693 } ping;
694
695 enum {
696 PING_NONOTIFY = -1,
697 PING_OK = 0,
698 PING_TIMEOUT,
699 PING_PEERDIED,
700 PING_MAX
701 };
702
703 /* --- Admin structure --- */
704
705 #define OBUFSZ 16384u
706
707 typedef struct obuf {
708 struct obuf *next; /* Next buffer in list */
709 char *p_in, *p_out; /* Pointers into the buffer */
710 char buf[OBUFSZ]; /* The actual buffer */
711 } obuf;
712
713 typedef struct oqueue {
714 obuf *hd, *tl; /* Head and tail pointers */
715 } oqueue;
716
717 struct admin;
718
719 typedef struct admin_bgop {
720 struct admin_bgop *next, *prev; /* Links to next and previous */
721 struct admin *a; /* Owner job */
722 char *tag; /* Tag string for messages */
723 void (*cancel)(struct admin_bgop *); /* Destructor function */
724 } admin_bgop;
725
726 typedef struct admin_resop {
727 admin_bgop bg; /* Background operation header */
728 char *addr; /* Hostname to be resolved */
729 #ifdef HAVE_LIBADNS
730 adns_query q;
731 #else
732 bres_client r; /* Background resolver task */
733 #endif
734 sel_timer t; /* Timer for resolver */
735 addr sa; /* Socket address */
736 unsigned port; /* Port number chosen */
737 size_t sasz; /* Socket address size */
738 void (*func)(struct admin_resop *, int); /* Handler */
739 } admin_resop;
740
741 enum { ARES_OK, ARES_FAIL };
742
743 typedef struct admin_addop {
744 admin_resop r; /* Name resolution header */
745 peerspec peer; /* Peer pending creation */
746 } admin_addop;
747
748 typedef struct admin_pingop {
749 admin_bgop bg; /* Background operation header */
750 ping ping; /* Ping pending response */
751 struct timeval pingtime; /* Time last ping was sent */
752 } admin_pingop;
753
754 typedef struct admin_service {
755 sym_base _b; /* Hash table base structure */
756 char *version; /* The provided version */
757 struct admin *prov; /* Which client provides me */
758 struct admin_service *next, *prev; /* Client's list of services */
759 } admin_service;
760
761 typedef struct admin_svcop {
762 admin_bgop bg; /* Background operation header */
763 struct admin *prov; /* Client servicing this job */
764 unsigned index; /* This job's index */
765 struct admin_svcop *next, *prev; /* Links for provider's jobs */
766 } admin_svcop;
767
768 typedef struct admin_jobentry {
769 unsigned short seq; /* Zero if unused */
770 union {
771 admin_svcop *op; /* Operation, if slot in use, ... */
772 uint32 next; /* ... or index of next free slot */
773 } u;
774 } admin_jobentry;
775
776 typedef struct admin_jobtable {
777 uint32 n, sz; /* Used slots and table size */
778 admin_svcop *active; /* List of active jobs */
779 uint32 free; /* Index of first free slot */
780 admin_jobentry *v; /* And the big array of entries */
781 } admin_jobtable;
782
783 struct admin {
784 struct admin *next, *prev; /* Links to next and previous */
785 unsigned f; /* Various useful flags */
786 unsigned ref; /* Reference counter */
787 #ifndef NTRACE
788 unsigned seq; /* Sequence number for tracing */
789 #endif
790 oqueue out; /* Output buffer list */
791 oqueue delay; /* Delayed output buffer list */
792 admin_bgop *bg; /* Backgrounded operations */
793 admin_service *svcs; /* Which services I provide */
794 admin_jobtable j; /* Table of outstanding jobs */
795 selbuf b; /* Line buffer for commands */
796 sel_file w; /* Selector for write buffering */
797 };
798
799 #define AF_DEAD 1u /* Destroy this admin block */
800 #define AF_CLOSE 2u /* Client closed connection */
801 #define AF_NOTE 4u /* Catch notifications */
802 #define AF_WARN 8u /* Catch warning messages */
803 #ifndef NTRACE
804 # define AF_TRACE 16u /* Catch tracing */
805 #endif
806 #define AF_FOREGROUND 32u /* Quit server when client closes */
807
808 #ifndef NTRACE
809 # define AF_ALLMSGS (AF_NOTE | AF_TRACE | AF_WARN)
810 #else
811 # define AF_ALLMSGS (AF_NOTE | AF_WARN)
812 #endif
813
814 /*----- Global variables --------------------------------------------------*/
815
816 extern sel_state sel; /* Global I/O event state */
817 extern octet buf_i[PKBUFSZ], buf_o[PKBUFSZ], buf_t[PKBUFSZ], buf_u[PKBUFSZ];
818 extern const tunnel_ops *tunnels[]; /* Table of tunnels (0-term) */
819 extern const tunnel_ops *tun_default; /* Default tunnel to use */
820 extern udpsocket udpsock[NADDRFAM]; /* The master UDP sockets */
821 extern kdata *master; /* Default private key */
822 extern const char *tag_priv; /* Default private key tag */
823
824 #ifndef NTRACE
825 extern const trace_opt tr_opts[]; /* Trace options array */
826 extern unsigned tr_flags; /* Trace options flags */
827 #endif
828
829 /*----- Other macros ------------------------------------------------------*/
830
831 #define QUICKRAND \
832 do { rand_quick(RAND_GLOBAL); noise_timer(RAND_GLOBAL); } while (0)
833
834 /*----- Key management ----------------------------------------------------*/
835
836 /* --- @km_init@ --- *
837 *
838 * Arguments: @const char *privkr@ = private keyring file
839 * @const char *pubkr@ = public keyring file
840 * @const char *ptag@ = default private-key tag
841 *
842 * Returns: ---
843 *
844 * Use: Initializes the key-management machinery, loading the
845 * keyrings and so on.
846 */
847
848 extern void km_init(const char */*privkr*/, const char */*pubkr*/,
849 const char */*ptag*/);
850
851 /* --- @km_reload@ --- *
852 *
853 * Arguments: ---
854 *
855 * Returns: Zero if OK, nonzero to force reloading of keys.
856 *
857 * Use: Checks the keyrings to see if they need reloading.
858 */
859
860 extern int km_reload(void);
861
862 /* --- @km_clear@ --- *
863 *
864 * Arguments: ---
865 *
866 * Returns: ---
867 *
868 * Use: Forget the currently loaded keyrings. The @master@ key will
869 * be cleared, but other keys already loaded will continue to
870 * exist until their reference count drops to zero. Call
871 * @km_init@ to make everything work again.
872 */
873
874 extern void km_clear(void);
875
876 /* --- @km_findpub@, @km_findpriv@ --- *
877 *
878 * Arguments: @const char *tag@ = key tag to load
879 *
880 * Returns: Pointer to the kdata object if successful, or null on error.
881 *
882 * Use: Fetches a public or private key from the keyring.
883 */
884
885 extern kdata *km_findpub(const char */*tag*/);
886 extern kdata *km_findpriv(const char */*tag*/);
887
888 /* --- @km_findpubbyid@, @km_findprivbyid@ --- *
889 *
890 * Arguments: @uint32 id@ = key id to load
891 *
892 * Returns: Pointer to the kdata object if successful, or null on error.
893 *
894 * Use: Fetches a public or private key from the keyring given its
895 * numeric id.
896 */
897
898 extern kdata *km_findpubbyid(uint32 /*id*/);
899 extern kdata *km_findprivbyid(uint32 /*id*/);
900
901 /* --- @km_samealgsp@ --- *
902 *
903 * Arguments: @const kdata *kdx, *kdy@ = two key data objects
904 *
905 * Returns: Nonzero if their two algorithm selections are the same.
906 *
907 * Use: Checks sameness of algorithm selections: used to ensure that
908 * peers are using sensible algorithms.
909 */
910
911 extern int km_samealgsp(const kdata */*kdx*/, const kdata */*kdy*/);
912
913 /* --- @km_ref@ --- *
914 *
915 * Arguments: @kdata *kd@ = pointer to the kdata object
916 *
917 * Returns: ---
918 *
919 * Use: Claim a new reference to a kdata object.
920 */
921
922 extern void km_ref(kdata */*kd*/);
923
924 /* --- @km_unref@ --- *
925 *
926 * Arguments: @kdata *kd@ = pointer to the kdata object
927 *
928 * Returns: ---
929 *
930 * Use: Releases a reference to a kdata object.
931 */
932
933 extern void km_unref(kdata */*kd*/);
934
935 /* --- @km_tag@ --- *
936 *
937 * Arguments: @kdata *kd@ - pointer to the kdata object
938 *
939 * Returns: A pointer to the short tag by which the kdata was loaded.
940 */
941
942 extern const char *km_tag(kdata */*kd*/);
943
944 /*----- Key exchange ------------------------------------------------------*/
945
946 /* --- @kx_start@ --- *
947 *
948 * Arguments: @keyexch *kx@ = pointer to key exchange context
949 * @int forcep@ = nonzero to ignore the quiet timer
950 *
951 * Returns: ---
952 *
953 * Use: Stimulates a key exchange. If a key exchage is in progress,
954 * a new challenge is sent (unless the quiet timer forbids
955 * this); if no exchange is in progress, one is commenced.
956 */
957
958 extern void kx_start(keyexch */*kx*/, int /*forcep*/);
959
960 /* --- @kx_message@ --- *
961 *
962 * Arguments: @keyexch *kx@ = pointer to key exchange context
963 * @const addr *a@ = sender's IP address and port
964 * @unsigned msg@ = the message code
965 * @buf *b@ = pointer to buffer containing the packet
966 *
967 * Returns: Nonzero if the sender's address was unknown.
968 *
969 * Use: Reads a packet containing key exchange messages and handles
970 * it.
971 */
972
973 extern int kx_message(keyexch */*kx*/, const addr */*a*/,
974 unsigned /*msg*/, buf */*b*/);
975
976 /* --- @kx_free@ --- *
977 *
978 * Arguments: @keyexch *kx@ = pointer to key exchange context
979 *
980 * Returns: ---
981 *
982 * Use: Frees everything in a key exchange context.
983 */
984
985 extern void kx_free(keyexch */*kx*/);
986
987 /* --- @kx_newkeys@ --- *
988 *
989 * Arguments: @keyexch *kx@ = pointer to key exchange context
990 *
991 * Returns: ---
992 *
993 * Use: Informs the key exchange module that its keys may have
994 * changed. If fetching the new keys fails, the peer will be
995 * destroyed, we log messages and struggle along with the old
996 * keys.
997 */
998
999 extern void kx_newkeys(keyexch */*kx*/);
1000
1001 /* --- @kx_setup@ --- *
1002 *
1003 * Arguments: @keyexch *kx@ = pointer to key exchange context
1004 * @peer *p@ = pointer to peer context
1005 * @keyset **ks@ = pointer to keyset list
1006 * @unsigned f@ = various useful flags
1007 *
1008 * Returns: Zero if OK, nonzero if it failed.
1009 *
1010 * Use: Initializes a key exchange module. The module currently
1011 * contains no keys, and will attempt to initiate a key
1012 * exchange.
1013 */
1014
1015 extern int kx_setup(keyexch */*kx*/, peer */*p*/,
1016 keyset **/*ks*/, unsigned /*f*/);
1017
1018 /* --- @kx_init@ --- *
1019 *
1020 * Arguments: ---
1021 *
1022 * Returns: ---
1023 *
1024 * Use: Initializes the key-exchange logic.
1025 */
1026
1027 extern void kx_init(void);
1028
1029 /*----- Keysets and symmetric cryptography --------------------------------*/
1030
1031 /* --- @ks_drop@ --- *
1032 *
1033 * Arguments: @keyset *ks@ = pointer to a keyset
1034 *
1035 * Returns: ---
1036 *
1037 * Use: Decrements a keyset's reference counter. If the counter hits
1038 * zero, the keyset is freed.
1039 */
1040
1041 extern void ks_drop(keyset */*ks*/);
1042
1043 /* --- @ks_gen@ --- *
1044 *
1045 * Arguments: @deriveargs *a@ = key derivation parameters (modified)
1046 * @peer *p@ = pointer to peer information
1047 *
1048 * Returns: A pointer to the new keyset.
1049 *
1050 * Use: Derives a new keyset from the given key material. This will
1051 * set the @what@, @f@, and @hc@ members in @*a@; other members
1052 * must be filled in by the caller.
1053 *
1054 * The new key is marked so that it won't be selected for output
1055 * by @ksl_encrypt@. You can still encrypt data with it by
1056 * calling @ks_encrypt@ directly.
1057 */
1058
1059 extern keyset *ks_gen(deriveargs */*a*/, peer */*p*/);
1060
1061 /* --- @ks_activate@ --- *
1062 *
1063 * Arguments: @keyset *ks@ = pointer to a keyset
1064 *
1065 * Returns: ---
1066 *
1067 * Use: Activates a keyset, so that it can be used for encrypting
1068 * outgoing messages.
1069 */
1070
1071 extern void ks_activate(keyset */*ks*/);
1072
1073 /* --- @ks_encrypt@ --- *
1074 *
1075 * Arguments: @keyset *ks@ = pointer to a keyset
1076 * @unsigned ty@ = message type
1077 * @buf *b@ = pointer to input buffer
1078 * @buf *bb@ = pointer to output buffer
1079 *
1080 * Returns: Zero if successful; @KSERR_REGEN@ if we should negotiate a
1081 * new key; @KSERR_NOKEYS@ if the key is not usable. Also
1082 * returns zero if there was insufficient buffer (but the output
1083 * buffer is broken in this case).
1084 *
1085 * Use: Encrypts a block of data using the key. Note that the `key
1086 * ought to be replaced' notification is only ever given once
1087 * for each key. Also note that this call forces a keyset to be
1088 * used even if it's marked as not for data output.
1089 *
1090 * The encryption transform is permitted to corrupt @buf_u@ for
1091 * its own purposes. Neither the source nor destination should
1092 * be within @buf_u@; and callers mustn't expect anything stored
1093 * in @buf_u@ to still
1094 */
1095
1096 extern int ks_encrypt(keyset */*ks*/, unsigned /*ty*/,
1097 buf */*b*/, buf */*bb*/);
1098
1099 /* --- @ks_decrypt@ --- *
1100 *
1101 * Arguments: @keyset *ks@ = pointer to a keyset
1102 * @unsigned ty@ = expected type code
1103 * @buf *b@ = pointer to an input buffer
1104 * @buf *bb@ = pointer to an output buffer
1105 *
1106 * Returns: Zero on success; @KSERR_DECRYPT@ on failure. Also returns
1107 * zero if there was insufficient buffer (but the output buffer
1108 * is broken in this case).
1109 *
1110 * Use: Attempts to decrypt a message using a given key. Note that
1111 * requesting decryption with a key directly won't clear a
1112 * marking that it's not for encryption.
1113 *
1114 * The decryption transform is permitted to corrupt @buf_u@ for
1115 * its own purposes. Neither the source nor destination should
1116 * be within @buf_u@; and callers mustn't expect anything stored
1117 * in @buf_u@ to still
1118 */
1119
1120 extern int ks_decrypt(keyset */*ks*/, unsigned /*ty*/,
1121 buf */*b*/, buf */*bb*/);
1122
1123 /* --- @ksl_free@ --- *
1124 *
1125 * Arguments: @keyset **ksroot@ = pointer to keyset list head
1126 *
1127 * Returns: ---
1128 *
1129 * Use: Frees (releases references to) all of the keys in a keyset.
1130 */
1131
1132 extern void ksl_free(keyset **/*ksroot*/);
1133
1134 /* --- @ksl_link@ --- *
1135 *
1136 * Arguments: @keyset **ksroot@ = pointer to keyset list head
1137 * @keyset *ks@ = pointer to a keyset
1138 *
1139 * Returns: ---
1140 *
1141 * Use: Links a keyset into a list. A keyset can only be on one list
1142 * at a time. Bad things happen otherwise.
1143 */
1144
1145 extern void ksl_link(keyset **/*ksroot*/, keyset */*ks*/);
1146
1147 /* --- @ksl_prune@ --- *
1148 *
1149 * Arguments: @keyset **ksroot@ = pointer to keyset list head
1150 *
1151 * Returns: ---
1152 *
1153 * Use: Prunes the keyset list by removing keys which mustn't be used
1154 * any more.
1155 */
1156
1157 extern void ksl_prune(keyset **/*ksroot*/);
1158
1159 /* --- @ksl_encrypt@ --- *
1160 *
1161 * Arguments: @keyset **ksroot@ = pointer to keyset list head
1162 * @unsigned ty@ = message type
1163 * @buf *b@ = pointer to input buffer
1164 * @buf *bb@ = pointer to output buffer
1165 *
1166 * Returns: Zero if successful; @KSERR_REGEN@ if it's time to negotiate a
1167 * new key; @KSERR_NOKEYS@ if there are no suitable keys
1168 * available. Also returns zero if there was insufficient
1169 * buffer space (but the output buffer is broken in this case).
1170 *
1171 * Use: Encrypts a packet.
1172 */
1173
1174 extern int ksl_encrypt(keyset **/*ksroot*/, unsigned /*ty*/,
1175 buf */*b*/, buf */*bb*/);
1176
1177 /* --- @ksl_decrypt@ --- *
1178 *
1179 * Arguments: @keyset **ksroot@ = pointer to keyset list head
1180 * @unsigned ty@ = expected type code
1181 * @buf *b@ = pointer to input buffer
1182 * @buf *bb@ = pointer to output buffer
1183 *
1184 * Returns: Zero on success; @KSERR_DECRYPT@ on failure. Also returns
1185 * zero if there was insufficient buffer (but the output buffer
1186 * is broken in this case).
1187 *
1188 * Use: Decrypts a packet.
1189 */
1190
1191 extern int ksl_decrypt(keyset **/*ksroot*/, unsigned /*ty*/,
1192 buf */*b*/, buf */*bb*/);
1193
1194 /*----- Challenges --------------------------------------------------------*/
1195
1196 /* --- @c_new@ --- *
1197 *
1198 * Arguments: @const void *m@ = pointer to associated message, or null
1199 * @size_t msz@ = length of associated message
1200 * @buf *b@ = where to put the challenge
1201 *
1202 * Returns: Zero if OK, nonzero on error.
1203 *
1204 * Use: Issues a new challenge.
1205 */
1206
1207 extern int c_new(const void */*m*/, size_t /*msz*/, buf */*b*/);
1208
1209 /* --- @c_check@ --- *
1210 *
1211 * Arguments: @const void *m@ = pointer to associated message, or null
1212 * @size_t msz@ = length of associated message
1213 * @buf *b@ = where to find the challenge
1214 *
1215 * Returns: Zero if OK, nonzero if it didn't work.
1216 *
1217 * Use: Checks a challenge. On failure, the buffer is broken.
1218 */
1219
1220 extern int c_check(const void */*m*/, size_t /*msz*/, buf */*b*/);
1221
1222 /*----- Administration interface ------------------------------------------*/
1223
1224 #define A_END ((char *)0)
1225
1226 /* --- @a_vformat@ --- *
1227 *
1228 * Arguments: @dstr *d@ = where to leave the formatted message
1229 * @const char *fmt@ = pointer to format string
1230 * @va_list *ap@ = arguments in list
1231 *
1232 * Returns: ---
1233 *
1234 * Use: Main message token formatting driver. The arguments are
1235 * interleaved formatting tokens and their parameters, finally
1236 * terminated by an entry @A_END@.
1237 *
1238 * Tokens recognized:
1239 *
1240 * * "*..." ... -- pretokenized @dstr_putf@-like string
1241 *
1242 * * "?ADDR" SOCKADDR -- a socket address, to be converted
1243 *
1244 * * "?B64" BUFFER SIZE -- binary data to be base64-encoded
1245 *
1246 * * "?TOKENS" VECTOR -- null-terminated vector of tokens
1247 *
1248 * * "?PEER" PEER -- peer's name
1249 *
1250 * * "?ERR" CODE -- system error code
1251 *
1252 * * "?ERRNO" -- system error code from @errno@
1253 *
1254 * * "[!]..." ... -- @dstr_putf@-like string as single token
1255 */
1256
1257 extern void a_vformat(dstr */*d*/, const char */*fmt*/, va_list */*ap*/);
1258
1259 /* --- @a_format@ --- *
1260 *
1261 * Arguments: @dstr *d@ = where to leave the formatted message
1262 * @const char *fmt@ = pointer to format string
1263 *
1264 * Returns: ---
1265 *
1266 * Use: Writes a tokenized message into a string, for later
1267 * presentation.
1268 */
1269
1270 extern void EXECL_LIKE(0) a_format(dstr */*d*/, const char */*fmt*/, ...);
1271
1272 /* --- @a_info@ --- *
1273 *
1274 * Arguments: @admin *a@ = connection
1275 * @const char *fmt@ = format string
1276 * @...@ = other arguments
1277 *
1278 * Returns: ---
1279 *
1280 * Use: Report information to an admin client.
1281 */
1282
1283 extern void EXECL_LIKE(0) a_info(admin */*a*/, const char */*fmt*/, ...);
1284
1285 /* --- @a_warn@ --- *
1286 *
1287 * Arguments: @const char *fmt@ = pointer to format string
1288 * @...@ = other arguments
1289 *
1290 * Returns: ---
1291 *
1292 * Use: Informs all admin connections of a warning.
1293 */
1294
1295 extern void EXECL_LIKE(0) a_warn(const char */*fmt*/, ...);
1296
1297 /* --- @a_notify@ --- *
1298 *
1299 * Arguments: @const char *fmt@ = pointer to format string
1300 * @...@ = other arguments
1301 *
1302 * Returns: ---
1303 *
1304 * Use: Sends a notification to interested admin connections.
1305 */
1306
1307 extern void EXECL_LIKE(0) a_notify(const char */*fmt*/, ...);
1308
1309 /* --- @a_create@ --- *
1310 *
1311 * Arguments: @int fd_in, fd_out@ = file descriptors to use
1312 * @unsigned f@ = initial flags to set
1313 *
1314 * Returns: ---
1315 *
1316 * Use: Creates a new admin connection. It's safe to call this
1317 * before @a_init@ -- and, indeed, this makes sense if you also
1318 * call @a_switcherr@ to report initialization errors through
1319 * the administration machinery.
1320 */
1321
1322 extern void a_create(int /*fd_in*/, int /*fd_out*/, unsigned /*f*/);
1323
1324 /* --- @a_preselect@ --- *
1325 *
1326 * Arguments: ---
1327 *
1328 * Returns: ---
1329 *
1330 * Use: Informs the admin module that we're about to select again,
1331 * and that it should do cleanup things it has delayed until a
1332 * `safe' time.
1333 */
1334
1335 extern void a_preselect(void);
1336
1337 /* --- @a_daemon@ --- *
1338 *
1339 * Arguments: ---
1340 *
1341 * Returns: ---
1342 *
1343 * Use: Informs the admin module that it's a daemon.
1344 */
1345
1346 extern void a_daemon(void);
1347
1348 /* --- @a_listen@ --- *
1349 *
1350 * Arguments: @const char *name@ = socket name to create
1351 * @uid_t u@ = user to own the socket
1352 * @gid_t g@ = group to own the socket
1353 * @mode_t m@ = permissions to set on the socket
1354 *
1355 * Returns: ---
1356 *
1357 * Use: Creates the admin listening socket.
1358 */
1359
1360 extern void a_listen(const char */*sock*/,
1361 uid_t /*u*/, gid_t /*g*/, mode_t /*m*/);
1362
1363 /* --- @a_unlisten@ --- *
1364 *
1365 * Arguments: ---
1366 *
1367 * Returns: ---
1368 *
1369 * Use: Stops listening to the administration socket and removes it.
1370 */
1371
1372 extern void a_unlisten(void);
1373
1374 /* --- @a_switcherr@ --- *
1375 *
1376 * Arguments: ---
1377 *
1378 * Returns: ---
1379 *
1380 * Use: Arrange to report warnings, trace messages, etc. to
1381 * administration clients rather than the standard-error stream.
1382 *
1383 * Obviously this makes no sense unless there is at least one
1384 * client established. Calling @a_listen@ won't help with this,
1385 * because the earliest a new client can connect is during the
1386 * first select-loop iteration, which is too late: some initial
1387 * client must have been added manually using @a_create@.
1388 */
1389
1390 extern void a_switcherr(void);
1391
1392 /* --- @a_signals@ --- *
1393 *
1394 * Arguments: ---
1395 *
1396 * Returns: ---
1397 *
1398 * Use: Establishes handlers for the obvious signals.
1399 */
1400
1401 extern void a_signals(void);
1402
1403 /* --- @a_init@ --- *
1404 *
1405 * Arguments: @const char *sock@ = socket name to create
1406 * @uid_t u@ = user to own the socket
1407 * @gid_t g@ = group to own the socket
1408 * @mode_t m@ = permissions to set on the socket
1409 *
1410 * Returns: ---
1411 *
1412 * Use: Creates the admin listening socket.
1413 */
1414
1415 extern void a_init(void);
1416
1417 /*----- Mapping with addresses as keys ------------------------------------*/
1418
1419 /* --- @am_create@ --- *
1420 *
1421 * Arguments: @addrmap *m@ = pointer to map
1422 *
1423 * Returns: ---
1424 *
1425 * Use: Create an address map, properly set up.
1426 */
1427
1428 extern void am_create(addrmap */*m*/);
1429
1430 /* --- @am_destroy@ --- *
1431 *
1432 * Arguments: @addrmap *m@ = pointer to map
1433 *
1434 * Returns: ---
1435 *
1436 * Use: Destroy an address map, throwing away all the entries.
1437 */
1438
1439 extern void am_destroy(addrmap */*m*/);
1440
1441 /* --- @am_find@ --- *
1442 *
1443 * Arguments: @addrmap *m@ = pointer to map
1444 * @const addr *a@ = address to look up
1445 * @size_t sz@ = size of block to allocate
1446 * @unsigned *f@ = where to store flags
1447 *
1448 * Returns: Pointer to found item, or null.
1449 *
1450 * Use: Finds a record with the given IP address, set @*f@ nonzero
1451 * and returns it. If @sz@ is zero, and no match was found,
1452 * return null; otherwise allocate a new block of @sz@ bytes,
1453 * clear @*f@ to zero and return the block pointer.
1454 */
1455
1456 extern void *am_find(addrmap */*m*/, const addr */*a*/,
1457 size_t /*sz*/, unsigned */*f*/);
1458
1459 /* --- @am_remove@ --- *
1460 *
1461 * Arguments: @addrmap *m@ = pointer to map
1462 * @void *i@ = pointer to the item
1463 *
1464 * Returns: ---
1465 *
1466 * Use: Removes an item from the map.
1467 */
1468
1469 extern void am_remove(addrmap */*m*/, void */*i*/);
1470
1471 /*----- Privilege separation ----------------------------------------------*/
1472
1473 /* --- @ps_trace@ --- *
1474 *
1475 * Arguments: @unsigned mask@ = trace mask to check
1476 * @const char *fmt@ = message format
1477 * @...@ = values for placeholders
1478 *
1479 * Returns: ---
1480 *
1481 * Use: Writes a trace message.
1482 */
1483
1484 T( extern void PRINTF_LIKE(2, 3)
1485 ps_trace(unsigned /*mask*/, const char */*fmt*/, ...); )
1486
1487 /* --- @ps_warn@ --- *
1488 *
1489 * Arguments: @const char *fmt@ = message format
1490 * @...@ = values for placeholders
1491 *
1492 * Returns: ---
1493 *
1494 * Use: Writes a warning message.
1495 */
1496
1497 extern void PRINTF_LIKE(1, 2) ps_warn(const char */*fmt*/, ...);
1498
1499 /* --- @ps_tunfd@ --- *
1500 *
1501 * Arguments: @const tunnel_ops *tops@ = pointer to tunnel operations
1502 * @char **ifn@ = where to put the interface name
1503 *
1504 * Returns: The file descriptor, or @-1@ on error.
1505 *
1506 * Use: Fetches a file descriptor for a tunnel driver.
1507 */
1508
1509 extern int ps_tunfd(const tunnel_ops */*tops*/, char **/*ifn*/);
1510
1511 /* --- @ps_split@ --- *
1512 *
1513 * Arguments: @int detachp@ = whether to detach the child from its terminal
1514 *
1515 * Returns: ---
1516 *
1517 * Use: Separates off the privileged tunnel-opening service from the
1518 * rest of the server.
1519 */
1520
1521 extern void ps_split(int /*detachp*/);
1522
1523 /* --- @ps_quit@ --- *
1524 *
1525 * Arguments: ---
1526 *
1527 * Returns: ---
1528 *
1529 * Use: Detaches from the helper process.
1530 */
1531
1532 extern void ps_quit(void);
1533
1534 /*----- Peer management ---------------------------------------------------*/
1535
1536 /* --- @p_updateaddr@ --- *
1537 *
1538 * Arguments: @peer *p@ = pointer to peer block
1539 * @const addr *a@ = address to associate with this peer
1540 *
1541 * Returns: Zero if the address was changed; @+1@ if it was already
1542 * right.
1543 *
1544 * Use: Updates our idea of @p@'s address.
1545 */
1546
1547 extern int p_updateaddr(peer */*p*/, const addr */*a*/);
1548
1549 /* --- @p_txstart@ --- *
1550 *
1551 * Arguments: @peer *p@ = pointer to peer block
1552 * @unsigned msg@ = message type code
1553 *
1554 * Returns: A pointer to a buffer to write to.
1555 *
1556 * Use: Starts sending to a peer. Only one send can happen at a
1557 * time.
1558 */
1559
1560 extern buf *p_txstart(peer */*p*/, unsigned /*msg*/);
1561
1562 /* --- @p_txaddr@ --- *
1563 *
1564 * Arguments: @const addr *a@ = recipient address
1565 * @const void *p@ = pointer to packet to send
1566 * @size_t sz@ = length of packet
1567 *
1568 * Returns: Zero if successful, nonzero on error.
1569 *
1570 * Use: Sends a packet to an address which (possibly) isn't a current
1571 * peer.
1572 */
1573
1574 extern int p_txaddr(const addr */*a*/, const void */*p*/, size_t /*sz*/);
1575
1576 /* --- @p_txend@ --- *
1577 *
1578 * Arguments: @peer *p@ = pointer to peer block
1579 *
1580 * Returns: ---
1581 *
1582 * Use: Sends a packet to the peer.
1583 */
1584
1585 extern void p_txend(peer */*p*/);
1586
1587 /* --- @p_pingsend@ --- *
1588 *
1589 * Arguments: @peer *p@ = destination peer
1590 * @ping *pg@ = structure to fill in
1591 * @unsigned type@ = message type
1592 * @unsigned long timeout@ = how long to wait before giving up
1593 * @void (*func)(int, void *)@ = callback function
1594 * @void *arg@ = argument for callback
1595 *
1596 * Returns: Zero if successful, nonzero if it failed.
1597 *
1598 * Use: Sends a ping to a peer. Call @func@ with a nonzero argument
1599 * if we get an answer within the timeout, or zero if no answer.
1600 */
1601
1602 extern int p_pingsend(peer */*p*/, ping */*pg*/, unsigned /*type*/,
1603 unsigned long /*timeout*/,
1604 void (*/*func*/)(int, void *), void */*arg*/);
1605
1606 /* --- @p_pingdone@ --- *
1607 *
1608 * Arguments: @ping *p@ = ping structure
1609 * @int rc@ = return code to pass on
1610 *
1611 * Returns: ---
1612 *
1613 * Use: Disposes of a ping structure, maybe sending a notification.
1614 */
1615
1616 extern void p_pingdone(ping */*p*/, int /*rc*/);
1617
1618 /* --- @p_greet@ --- *
1619 *
1620 * Arguments: @peer *p@ = peer to send to
1621 * @const void *c@ = pointer to challenge
1622 * @size_t sz@ = size of challenge
1623 *
1624 * Returns: ---
1625 *
1626 * Use: Sends a greeting packet.
1627 */
1628
1629 extern void p_greet(peer */*p*/, const void */*c*/, size_t /*sz*/);
1630
1631 /* --- @p_tun@ --- *
1632 *
1633 * Arguments: @peer *p@ = pointer to peer block
1634 * @buf *b@ = buffer containing incoming packet
1635 *
1636 * Returns: ---
1637 *
1638 * Use: Handles a packet which needs to be sent to a peer.
1639 */
1640
1641 extern void p_tun(peer */*p*/, buf */*b*/);
1642
1643 /* --- @p_keyreload@ --- *
1644 *
1645 * Arguments: ---
1646 *
1647 * Returns: ---
1648 *
1649 * Use: Forces a check of the daemon's keyring files.
1650 */
1651
1652 extern void p_keyreload(void);
1653
1654 /* --- @p_interval@ --- *
1655 *
1656 * Arguments: ---
1657 *
1658 * Returns: ---
1659 *
1660 * Use: Called periodically to do tidying.
1661 */
1662
1663 extern void p_interval(void);
1664
1665 /* --- @p_stats@ --- *
1666 *
1667 * Arguments: @peer *p@ = pointer to a peer block
1668 *
1669 * Returns: A pointer to the peer's statistics.
1670 */
1671
1672 extern stats *p_stats(peer */*p*/);
1673
1674 /* --- @p_ifname@ --- *
1675 *
1676 * Arguments: @peer *p@ = pointer to a peer block
1677 *
1678 * Returns: A pointer to the peer's interface name.
1679 */
1680
1681 extern const char *p_ifname(peer */*p*/);
1682
1683 /* --- @p_setifname@ --- *
1684 *
1685 * Arguments: @peer *p@ = pointer to a peer block
1686 * @const char *name@ = pointer to the new name
1687 *
1688 * Returns: ---
1689 *
1690 * Use: Changes the name held for a peer's interface.
1691 */
1692
1693 extern void p_setifname(peer */*p*/, const char */*name*/);
1694
1695 /* --- @p_addr@ --- *
1696 *
1697 * Arguments: @peer *p@ = pointer to a peer block
1698 *
1699 * Returns: A pointer to the peer's address.
1700 */
1701
1702 extern const addr *p_addr(peer */*p*/);
1703
1704 /* --- @p_bind@ --- *
1705 *
1706 * Arguments: @struct addrinfo *ailist@ = addresses to bind to
1707 *
1708 * Returns: ---
1709 *
1710 * Use: Binds to the main UDP sockets.
1711 */
1712
1713 extern void p_bind(struct addrinfo */*ailist*/);
1714
1715 /* --- @p_unbind@ --- *
1716 *
1717 * Arguments: ---
1718 *
1719 * Returns: ---
1720 *
1721 * Use: Unbinds the UDP sockets. There must not be any active peers,
1722 * and none can be created until the sockets are rebound.
1723 */
1724
1725 extern void p_unbind(void);
1726
1727 /* --- @p_init@ --- *
1728 *
1729 * Arguments: ---
1730 *
1731 * Returns: ---
1732 *
1733 * Use: Initializes the peer system.
1734 */
1735
1736 extern void p_init(void);
1737
1738 /* --- @p_create@ --- *
1739 *
1740 * Arguments: @peerspec *spec@ = information about this peer
1741 *
1742 * Returns: Pointer to the peer block, or null if it failed.
1743 *
1744 * Use: Creates a new named peer block. No peer is actually attached
1745 * by this point.
1746 */
1747
1748 extern peer *p_create(peerspec */*spec*/);
1749
1750 /* --- @p_name@ --- *
1751 *
1752 * Arguments: @peer *p@ = pointer to a peer block
1753 *
1754 * Returns: A pointer to the peer's name.
1755 *
1756 * Use: Equivalent to @p_spec(p)->name@.
1757 */
1758
1759 extern const char *p_name(peer */*p*/);
1760
1761 /* --- @p_tag@ --- *
1762 *
1763 * Arguments: @peer *p@ = pointer to a peer block
1764 *
1765 * Returns: A pointer to the peer's public key tag.
1766 */
1767
1768 extern const char *p_tag(peer */*p*/);
1769
1770 /* --- @p_privtag@ --- *
1771 *
1772 * Arguments: @peer *p@ = pointer to a peer block
1773 *
1774 * Returns: A pointer to the peer's private key tag.
1775 */
1776
1777 extern const char *p_privtag(peer */*p*/);
1778
1779 /* --- @p_spec@ --- *
1780 *
1781 * Arguments: @peer *p@ = pointer to a peer block
1782 *
1783 * Returns: Pointer to the peer's specification
1784 */
1785
1786 extern const peerspec *p_spec(peer */*p*/);
1787
1788 /* --- @p_findbyaddr@ --- *
1789 *
1790 * Arguments: @const addr *a@ = address to look up
1791 *
1792 * Returns: Pointer to the peer block, or null if not found.
1793 *
1794 * Use: Finds a peer by address.
1795 */
1796
1797 extern peer *p_findbyaddr(const addr */*a*/);
1798
1799 /* --- @p_find@ --- *
1800 *
1801 * Arguments: @const char *name@ = name to look up
1802 *
1803 * Returns: Pointer to the peer block, or null if not found.
1804 *
1805 * Use: Finds a peer by name.
1806 */
1807
1808 extern peer *p_find(const char */*name*/);
1809
1810 /* --- @p_destroy@ --- *
1811 *
1812 * Arguments: @peer *p@ = pointer to a peer
1813 * @int bye@ = say goodbye to the peer?
1814 *
1815 * Returns: ---
1816 *
1817 * Use: Destroys a peer.
1818 */
1819
1820 extern void p_destroy(peer */*p*/, int /*bye*/);
1821
1822 /* --- @p_destroyall@ --- *
1823 *
1824 * Arguments: ---
1825 *
1826 * Returns: ---
1827 *
1828 * Use: Destroys all of the peers, saying goodbye.
1829 */
1830
1831 extern void p_destroyall(void);
1832
1833 /* --- @FOREACH_PEER@ --- *
1834 *
1835 * Arguments: @p@ = name to bind to each peer
1836 * @stuff@ = thing to do for each item
1837 *
1838 * Use: Does something for each current peer.
1839 */
1840
1841 #define FOREACH_PEER(p, stuff) do { \
1842 peer_iter i_; \
1843 peer *p; \
1844 for (p_mkiter(&i_); (p = p_next(&i_)) != 0; ) stuff \
1845 } while (0)
1846
1847 /* --- @p_mkiter@ --- *
1848 *
1849 * Arguments: @peer_iter *i@ = pointer to an iterator
1850 *
1851 * Returns: ---
1852 *
1853 * Use: Initializes the iterator.
1854 */
1855
1856 extern void p_mkiter(peer_iter */*i*/);
1857
1858 /* --- @p_next@ --- *
1859 *
1860 * Arguments: @peer_iter *i@ = pointer to an iterator
1861 *
1862 * Returns: Next peer, or null if at the end.
1863 *
1864 * Use: Returns the next peer.
1865 */
1866
1867 extern peer *p_next(peer_iter */*i*/);
1868
1869 /*----- The interval timer ------------------------------------------------*/
1870
1871 /* --- @iv_addreason@ --- *
1872 *
1873 * Arguments: ---
1874 *
1875 * Returns: ---
1876 *
1877 * Use: Adds an `interval timer reason'; if there are no others, the
1878 * interval timer is engaged.
1879 */
1880
1881 extern void iv_addreason(void);
1882
1883 /* --- @iv_rmreason@ --- *
1884 *
1885 * Arguments: ---
1886 *
1887 * Returns: ---
1888 *
1889 * Use: Removes an interval timer reason; if there are none left, the
1890 * interval timer is disengaged.
1891 */
1892
1893 extern void iv_rmreason(void);
1894
1895 /*----- The main loop -----------------------------------------------------*/
1896
1897 /* --- @lp_init@ --- *
1898 *
1899 * Arguments: ---
1900 *
1901 * Returns: ---
1902 *
1903 * Use: Initializes the main loop. Most importantly, this sets up
1904 * the select multiplexor that everything else hooks onto.
1905 */
1906
1907 extern void lp_init(void);
1908
1909 /* --- @lp_end@ --- *
1910 *
1911 * Arguments: ---
1912 *
1913 * Returns: ---
1914 *
1915 * Use: Requests an exit from the main loop.
1916 */
1917
1918 extern void lp_end(void);
1919
1920 /* --- @lp_run@ --- *
1921 *
1922 * Arguments: ---
1923 *
1924 * Returns: Zero on successful termination; @-1@ if things went wrong.
1925 *
1926 * Use: Cranks the main loop until it should be cranked no more.
1927 */
1928
1929 extern int lp_run(void);
1930
1931 /*----- Tunnel drivers ----------------------------------------------------*/
1932
1933 #ifdef TUN_LINUX
1934 extern const tunnel_ops tun_linux;
1935 #endif
1936
1937 #ifdef TUN_UNET
1938 extern const tunnel_ops tun_unet;
1939 #endif
1940
1941 #ifdef TUN_BSD
1942 extern const tunnel_ops tun_bsd;
1943 #endif
1944
1945 extern const tunnel_ops tun_slip;
1946
1947 /*----- Other handy utilities ---------------------------------------------*/
1948
1949 /* --- @timestr@ --- *
1950 *
1951 * Arguments: @time_t t@ = a time to convert
1952 *
1953 * Returns: A pointer to a textual representation of the time.
1954 *
1955 * Use: Converts a time to a textual representation. Corrupts
1956 * @buf_u@.
1957 */
1958
1959 extern const char *timestr(time_t /*t*/);
1960
1961 /* --- @mystrieq@ --- *
1962 *
1963 * Arguments: @const char *x, *y@ = two strings
1964 *
1965 * Returns: True if @x@ and @y are equal, up to case.
1966 */
1967
1968 extern int mystrieq(const char */*x*/, const char */*y*/);
1969
1970 /* --- @afix@ --- *
1971 *
1972 * Arguments: @int af@ = an address family code
1973 *
1974 * Returns: The index of the address family's record in @aftab@, or @-1@.
1975 */
1976
1977 extern int afix(int af);
1978
1979 /* --- @addrsz@ --- *
1980 *
1981 * Arguments: @const addr *a@ = a network address
1982 *
1983 * Returns: The size of the address, for passing into the sockets API.
1984 */
1985
1986 extern socklen_t addrsz(const addr */*a*/);
1987
1988 /* --- @getport@, @setport@ --- *
1989 *
1990 * Arguments: @addr *a@ = a network address
1991 * @unsigned port@ = port number to set
1992 *
1993 * Returns: ---
1994 *
1995 * Use: Retrieves or sets the port number in an address structure.
1996 */
1997
1998 extern unsigned getport(addr */*a*/);
1999 extern void setport(addr */*a*/, unsigned /*port*/);
2000
2001 /* --- @seq_reset@ --- *
2002 *
2003 * Arguments: @seqwin *s@ = sequence-checking window
2004 *
2005 * Returns: ---
2006 *
2007 * Use: Resets a sequence number window.
2008 */
2009
2010 extern void seq_reset(seqwin */*s*/);
2011
2012 /* --- @seq_check@ --- *
2013 *
2014 * Arguments: @seqwin *s@ = sequence-checking window
2015 * @uint32 q@ = sequence number to check
2016 * @const char *service@ = service to report message from
2017 *
2018 * Returns: A @SEQ_@ code.
2019 *
2020 * Use: Checks a sequence number against the window, updating things
2021 * as necessary.
2022 */
2023
2024 extern int seq_check(seqwin */*s*/, uint32 /*q*/, const char */*service*/);
2025
2026 typedef struct ratelim {
2027 unsigned n, max, persec;
2028 struct timeval when;
2029 } ratelim;
2030
2031 /* --- @ratelim_init@ --- *
2032 *
2033 * Arguments: @ratelim *r@ = rate-limiting state to fill in
2034 * @unsigned persec@ = credit to accumulate per second
2035 * @unsigned max@ = maximum credit to retain
2036 *
2037 * Returns: ---
2038 *
2039 * Use: Initialize a rate-limiting state.
2040 */
2041
2042 extern void ratelim_init(ratelim */*r*/,
2043 unsigned /*persec*/, unsigned /*max*/);
2044
2045 /* --- @ratelim_withdraw@ --- *
2046 *
2047 * Arguments: @ratelim *r@ = rate-limiting state
2048 * @unsigned n@ = credit to withdraw
2049 *
2050 * Returns: Zero if successful; @-1@ if there is unsufficient credit
2051 *
2052 * Use: Updates the state with any accumulated credit. Then, if
2053 * there there are more than @n@ credits available, withdraw @n@
2054 * and return successfully; otherwise, report failure.
2055 */
2056
2057 extern int ratelim_withdraw(ratelim */*r*/, unsigned /*n*/);
2058
2059 /* --- @ies_encrypt@ --- *
2060 *
2061 * Arguments: @kdata *kpub@ = recipient's public key
2062 * @unsigned ty@ = message type octet
2063 * @buf *b@ = input message buffer
2064 * @buf *bb@ = output buffer for the ciphertext
2065 *
2066 * Returns: On error, returns a @KSERR_...@ code or breaks the buffer;
2067 * on success, returns zero and the buffer is good.
2068 *
2069 * Use: Encrypts a message for a recipient, given their public key.
2070 * This does not (by itself) provide forward secrecy or sender
2071 * authenticity. The ciphertext is self-delimiting (unlike
2072 * @ks_encrypt@).
2073 */
2074
2075 extern int ies_encrypt(kdata */*kpub*/, unsigned /*ty*/,
2076 buf */*b*/, buf */*bb*/);
2077
2078 /* --- @ies_decrypt@ --- *
2079 *
2080 * Arguments: @kdata *kpub@ = private key key
2081 * @unsigned ty@ = message type octet
2082 * @buf *b@ = input ciphertext buffer
2083 * @buf *bb@ = output buffer for the message
2084 *
2085 * Returns: On error, returns a @KSERR_...@ code; on success, returns
2086 * zero and the buffer is good.
2087 *
2088 * Use: Decrypts a message encrypted using @ies_encrypt@, given our
2089 * private key.
2090 */
2091
2092 extern int ies_decrypt(kdata */*kpriv*/, unsigned /*ty*/,
2093 buf */*b*/, buf */*bb*/);
2094
2095 /*----- That's all, folks -------------------------------------------------*/
2096
2097 #ifdef __cplusplus
2098 }
2099 #endif
2100
2101 #endif