2024627a10abde931bc1dabc15137fb89875ae35
[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 #include <mLib/alloc.h>
66 #include <mLib/arena.h>
67 #include <mLib/base64.h>
68 #include <mLib/bres.h>
69 #include <mLib/codec.h>
70 #include <mLib/daemonize.h>
71 #include <mLib/dstr.h>
72 #include <mLib/env.h>
73 #include <mLib/fdflags.h>
74 #include <mLib/fdpass.h>
75 #include <mLib/fwatch.h>
76 #include <mLib/hash.h>
77 #include <mLib/macros.h>
78 #include <mLib/mdup.h>
79 #include <mLib/mdwopt.h>
80 #include <mLib/quis.h>
81 #include <mLib/report.h>
82 #include <mLib/sel.h>
83 #include <mLib/selbuf.h>
84 #include <mLib/sig.h>
85 #include <mLib/str.h>
86 #include <mLib/sub.h>
87 #include <mLib/trace.h>
88 #include <mLib/tv.h>
89 #include <mLib/versioncmp.h>
90
91 #include <catacomb/buf.h>
92 #include <catacomb/ct.h>
93
94 #include <catacomb/chacha.h>
95 #include <catacomb/gcipher.h>
96 #include <catacomb/gmac.h>
97 #include <catacomb/grand.h>
98 #include <catacomb/key.h>
99 #include <catacomb/paranoia.h>
100 #include <catacomb/poly1305.h>
101 #include <catacomb/salsa20.h>
102
103 #include <catacomb/noise.h>
104 #include <catacomb/rand.h>
105
106 #include <catacomb/mp.h>
107 #include <catacomb/mpmont.h>
108 #include <catacomb/mprand.h>
109 #include <catacomb/dh.h>
110 #include <catacomb/ec.h>
111 #include <catacomb/ec-raw.h>
112 #include <catacomb/ec-keys.h>
113 #include <catacomb/x25519.h>
114 #include <catacomb/x448.h>
115
116 #include "priv.h"
117 #include "protocol.h"
118 #include "slip.h"
119 #include "util.h"
120
121 #undef sun
122
123 /*----- Magic numbers -----------------------------------------------------*/
124
125 /* --- Trace flags --- */
126
127 #define T_TUNNEL 1u
128 #define T_PEER 2u
129 #define T_PACKET 4u
130 #define T_ADMIN 8u
131 #define T_CRYPTO 16u
132 #define T_KEYSET 32u
133 #define T_KEYEXCH 64u
134 #define T_KEYMGMT 128u
135 #define T_CHAL 256u
136 /* T_PRIVSEP in priv.h */
137
138 #define T_ALL 1023u
139
140 /* --- Units --- */
141
142 #define SEC(n) (n##u)
143 #define MIN(n) (n##u * 60u)
144 #define F_2P32 (65536.0*65536.0)
145 #define MEG(n) (n##ul * 1024ul * 1024ul)
146
147 /* --- Timing parameters --- */
148
149 #define T_EXP MIN(60) /* Expiry time for a key */
150 #define T_REGEN MIN(40) /* Regeneration time for a key */
151
152 #define T_VALID SEC(20) /* Challenge validity period */
153 #define T_RETRYMIN SEC(2) /* Minimum retry interval */
154 #define T_RETRYMAX MIN(5) /* Maximum retry interval */
155 #define T_RETRYGROW (5.0/4.0) /* Retry interval growth factor */
156
157 #define T_WOBBLE (1.0/3.0) /* Relative timer randomness */
158
159 /* --- Other things --- */
160
161 #define PKBUFSZ 65536
162
163 /*----- Cipher selections -------------------------------------------------*/
164
165 typedef struct keyset keyset;
166 typedef struct algswitch algswitch;
167 typedef struct kdata kdata;
168 typedef struct admin admin;
169
170 typedef struct dhgrp {
171 const struct dhops *ops;
172 size_t scsz;
173 } dhgrp;
174
175 typedef struct dhsc dhsc;
176 typedef struct dhge dhge;
177
178 enum {
179 DHFMT_STD, /* Fixed-width format, suitable for encryption */
180 DHFMT_HASH, /* Deterministic format, suitable for hashing */
181 DHFMT_VAR /* Variable-width-format, mostly a bad idea */
182 };
183
184 typedef struct deriveargs {
185 const char *what; /* Operation name (hashed) */
186 unsigned f; /* Flags */
187 #define DF_IN 1u /* Make incoming key */
188 #define DF_OUT 2u /* Make outgoing key */
189 const gchash *hc; /* Hash class */
190 const octet *k; /* Pointer to contributions */
191 size_t x, y, z; /* Markers in contributions */
192 } deriveargs;
193
194 typedef struct bulkalgs {
195 const struct bulkops *ops;
196 } bulkalgs;
197
198 typedef struct bulkctx {
199 const struct bulkops *ops;
200 } bulkctx;
201
202 typedef struct bulkchal {
203 const struct bulkops *ops;
204 size_t tagsz;
205 } bulkchal;
206
207 typedef struct dhops {
208 const char *name;
209
210 int (*ldpriv)(key_file */*kf*/, key */*k*/, key_data */*d*/,
211 kdata */*kd*/, dstr */*t*/, dstr */*e*/);
212 /* Load a private key from @d@, storing the data in @kd@. The key's
213 * file and key object are in @kf@ and @k@, mostly in case its
214 * attributes are interesting; the key tag is in @t@; errors are
215 * reported by writing tokens to @e@ and returning nonzero.
216 */
217
218 int (*ldpub)(key_file */*kf*/, key */*k*/, key_data */*d*/,
219 kdata */*kd*/, dstr */*t*/, dstr */*e*/);
220 /* Load a public key from @d@, storing the data in @kd@. The key's
221 * file and key object are in @kf@ and @k@, mostly in case its
222 * attributes are interesting; the key tag is in @t@; errors are
223 * reported by writing tokens to @e@ and returning nonzero.
224 */
225
226 const char *(*checkgrp)(const dhgrp */*g*/);
227 /* Check that the group is valid; return null on success, or an error
228 * string.
229 */
230
231 void (*grpinfo)(const dhgrp */*g*/, admin */*a*/);
232 /* Report on the group to an admin client. */
233
234 T( void (*tracegrp)(const dhgrp */*g*/); )
235 /* Trace a description of the group. */
236
237 int (*samegrpp)(const dhgrp */*g*/, const dhgrp */*gg*/);
238 /* Return nonzero if the two group objects represent the same
239 * group.
240 */
241
242 void (*freegrp)(dhgrp */*g*/);
243 /* Free a group and the resources it holds. */
244
245 dhsc *(*ldsc)(const dhgrp */*g*/, const void */*p*/, size_t /*sz*/);
246 /* Load a scalar from @p@, @sz@ and return it. Return null on
247 * error.
248 */
249
250 int (*stsc)(const dhgrp */*g*/,
251 void */*p*/, size_t /*sz*/, const dhsc */*x*/);
252 /* Store a scalar at @p@, @sz@. Return nonzero on error. */
253
254 dhsc *(*randsc)(const dhgrp */*g*/);
255 /* Return a random scalar. */
256
257 T( const char *(*scstr)(const dhgrp */*g*/, const dhsc */*x*/); )
258 /* Return a human-readable representation of @x@; @buf_t@ may be used
259 * to hold it.
260 */
261
262 void (*freesc)(const dhgrp */*g*/, dhsc */*x*/);
263 /* Free a scalar and the resources it holds. */
264
265 dhge *(*ldge)(const dhgrp */*g*/, buf */*b*/, int /*fmt*/);
266 /* Load a group element from @b@, encoded using format @fmt@. Return
267 * null on error.
268 */
269
270 int (*stge)(const dhgrp */*g*/, buf */*b*/,
271 const dhge */*Y*/, int /*fmt*/);
272 /* Store a group element in @b@, encoded using format @fmt@. Return
273 * nonzero on error.
274 */
275
276 int (*checkge)(const dhgrp */*h*/, const dhge */*Y*/);
277 /* Check a group element for validity. Return zero if everything
278 * checks out; nonzero on failure.
279 */
280
281 int (*eq)(const dhgrp */*g*/, const dhge */*Y*/, const dhge */*Z*/);
282 /* Return nonzero if @Y@ and @Z@ are equal. */
283
284 dhge *(*mul)(const dhgrp */*g*/, const dhsc */*x*/, const dhge */*Y*/);
285 /* Multiply a group element by a scalar, resulting in a shared-secret
286 * group element. If @y@ is null, then multiply the well-known
287 * generator.
288 */
289
290 T( const char *(*gestr)(const dhgrp */*g*/, const dhge */*Y*/); )
291 /* Return a human-readable representation of @Y@; @buf_t@ may be used
292 * to hold it.
293 */
294
295 void (*freege)(const dhgrp */*g*/, dhge */*Y*/);
296 /* Free a group element and the resources it holds. */
297
298 } dhops;
299
300 typedef struct bulkops {
301 const char *name;
302
303 bulkalgs *(*getalgs)(const algswitch */*asw*/, dstr */*e*/,
304 key_file */*kf*/, key */*k*/);
305 /* Determine algorithms to use and return a @bulkalgs@ object
306 * representing the decision. On error, write tokens to @e@ and
307 * return null.
308 */
309
310 T( void (*tracealgs)(const bulkalgs */*a*/); )
311 /* Write trace information about the algorithm selection. */
312
313 int (*checkalgs)(bulkalgs */*a*/, const algswitch */*asw*/, dstr */*e*/);
314 /* Check that the algorithms in @a@ and @asw@ are acceptable. On
315 * error, write tokens to @e@ and return @-1@; otherwise return zero.
316 */
317
318 int (*samealgsp)(const bulkalgs */*a*/, const bulkalgs */*aa*/);
319 /* If @a@ and @aa@ represent the same algorithm selection, return
320 * nonzero; if not, return zero.
321 */
322
323 void (*alginfo)(const bulkalgs */*a*/, admin */*adm*/);
324 /* Report on the algorithm selection to an admin client: call
325 * @a_info@ with appropriate key-value pairs.
326 */
327
328 size_t (*overhead)(const bulkalgs */*a*/);
329 /* Return the per-packet overhead of the bulk transform, in bytes. */
330
331 size_t (*expsz)(const bulkalgs */*a*/);
332 /* Return the total size limit for the bulk transform, in bytes,
333 * after which the keys must no longer be used.
334 */
335
336 bulkctx *(*genkeys)(const bulkalgs */*a*/, const deriveargs */*a*/);
337 /* Generate session keys and construct and return an appropriate
338 * context for using them. The offsets @a->x@, @a->y@ and @a->z@
339 * separate the key material into three parts. Between @a->k@ and
340 * @a->k + a->x@ is `my' contribution to the key material; between
341 * @a->k + a->x@ and @a->k + a->y@ is `your' contribution; and
342 * between @a->k + a->y@ and @a->k + a->z@ is a shared value we made
343 * together. These are used to construct (up to) two collections of
344 * symmetric keys: one for outgoing messages, the other for incoming
345 * messages. If @a->x == 0@ (or @a->y == a->x@) then my (or your)
346 * contribution is omitted.
347 */
348
349 bulkchal *(*genchal)(const bulkalgs */*a*/);
350 /* Construct and return a challenge issuing and verification
351 * context with a fresh random key.
352 */
353
354 void (*freealgs)(bulkalgs */*a*/);
355 /* Release an algorithm selection object. (Associated bulk
356 * encryption contexts and challenge contexts may still exist and
357 * must remain valid.)
358 */
359
360 int (*encrypt)(bulkctx */*bc*/, unsigned /*ty*/,
361 buf */*b*/, buf */*bb*/, uint32 /*seq*/);
362 /* Encrypt the packet in @b@, with type @ty@ (which doesn't need
363 * encoding separately) and sequence number @seq@ (which must be
364 * recoverable by @decrypt@), and write the result to @bb@. On
365 * error, return a @KSERR_...@ code and/or break the output buffer.
366 */
367
368 int (*decrypt)(bulkctx */*bc*/, unsigned /*ty*/,
369 buf */*b*/, buf */*bb*/, uint32 */*seq*/);
370 /* Decrypt the packet in @b@, with type @ty@, writing the result to
371 * @bb@ and storing the incoming (claimed) sequence number in @seq@.
372 * On error, return a @KSERR_...@ code.
373 */
374
375 void (*freectx)(bulkctx */*a*/);
376 /* Release a bulk encryption context and the resources it holds. */
377
378 int (*chaltag)(bulkchal */*bc*/, const void */*m*/, size_t /*msz*/,
379 uint32 /*seq*/, void */*t*/);
380 /* Calculate a tag for the challenge in @m@, @msz@, with the sequence
381 * number @seq@, and write it to @t@. Return @-1@ on error, zero on
382 * success.
383 */
384
385 int (*chalvrf)(bulkchal */*bc*/, const void */*m*/, size_t /*msz*/,
386 uint32 /*seq*/, const void */*t*/);
387 /* Check the tag @t@ on @m@, @msz@ and @seq@: return zero if the tag
388 * is OK, nonzero if it's bad.
389 */
390
391 void (*freechal)(bulkchal */*bc*/);
392 /* Release a challenge context and the resources it holds. */
393
394 } bulkops;
395
396 struct algswitch {
397 const gchash *h; size_t hashsz; /* Hash function */
398 const gccipher *mgf; /* Mask-generation function */
399 bulkalgs *bulk; /* Bulk crypto algorithms */
400 };
401
402 struct kdata {
403 unsigned ref; /* Reference counter */
404 struct knode *kn; /* Pointer to cache entry */
405 uint32 id; /* The underlying key's id */
406 char *tag; /* Full tag name of the key */
407 dhgrp *grp; /* The group we work in */
408 dhsc *k; /* The private key (or null) */
409 dhge *K; /* The public key */
410 time_t t_exp; /* Expiry time of the key */
411 algswitch algs; /* Collection of algorithms */
412 };
413
414 typedef struct knode {
415 sym_base _b; /* Symbol table intrusion */
416 unsigned f; /* Various flags */
417 #define KNF_BROKEN 1u /* Don't use this key any more */
418 struct keyhalf *kh; /* Pointer to the home keyhalf */
419 kdata *kd; /* Pointer to the key data */
420 } knode;
421
422 #define MAXHASHSZ 64 /* Largest possible hash size */
423
424 #define HASH_STRING(h, s) GH_HASH((h), (s), sizeof(s))
425
426 extern const dhops dhtab[];
427 extern const bulkops bulktab[];
428
429 /*----- Data structures ---------------------------------------------------*/
430
431 /* --- Socket addresses --- *
432 *
433 * A magic union of supported socket addresses.
434 */
435
436 typedef union addr {
437 struct sockaddr sa;
438 struct sockaddr_in sin;
439 } addr;
440
441 /* --- Mapping keyed on addresses --- */
442
443 typedef struct addrmap {
444 hash_table t;
445 size_t load;
446 } addrmap;
447
448 typedef struct addrmap_base {
449 hash_base b;
450 addr a;
451 } addrmap_base;
452
453 /* --- Sequence number checking --- */
454
455 typedef struct seqwin {
456 uint32 seq; /* First acceptable input sequence */
457 uint32 win; /* Window of acceptable numbers */
458 } seqwin;
459
460 #define SEQ_WINSZ 32 /* Bits in sequence number window */
461
462 /* --- A symmetric keyset --- *
463 *
464 * A keyset contains a set of symmetric keys for encrypting and decrypting
465 * packets. Keysets are stored in a list, sorted in reverse order of
466 * creation, so that the most recent keyset (the one most likely to be used)
467 * is first.
468 *
469 * Each keyset has a time limit and a data limit. The keyset is destroyed
470 * when either it has existed for too long, or it has been used to encrypt
471 * too much data. New key exchanges are triggered when keys are close to
472 * expiry.
473 */
474
475 enum { DIR_IN, DIR_OUT, NDIR };
476
477 struct keyset {
478 struct keyset *next; /* Next active keyset in the list */
479 unsigned ref; /* Reference count for keyset */
480 struct peer *p; /* Pointer to peer structure */
481 time_t t_exp; /* Expiry time for this keyset */
482 unsigned long sz_exp, sz_regen; /* Data limits for the keyset */
483 T( unsigned seq; ) /* Sequence number for tracing */
484 unsigned f; /* Various useful flags */
485 bulkctx *bulk; /* Bulk crypto transform */
486 uint32 oseq; /* Outbound sequence number */
487 seqwin iseq; /* Inbound sequence number */
488 };
489
490 #define KSF_LISTEN 1u /* Don't encrypt packets yet */
491 #define KSF_LINK 2u /* Key is in a linked list */
492
493 #define KSERR_REGEN -1 /* Regenerate keys */
494 #define KSERR_NOKEYS -2 /* No keys left */
495 #define KSERR_DECRYPT -3 /* Unable to decrypt message */
496 #define KSERR_SEQ -4 /* Incorrect sequence number */
497 #define KSERR_MALFORMED -5 /* Input ciphertext is broken */
498
499 /* --- Key exchange --- *
500 *
501 * TrIPE uses the Wrestlers Protocol for its key exchange. The Wrestlers
502 * Protocol has a number of desirable features (e.g., perfect forward
503 * secrecy, and zero-knowledge authentication) which make it attractive for
504 * use in TrIPE. The Wrestlers Protocol was designed by Mark Wooding and
505 * Clive Jones.
506 */
507
508 typedef struct retry {
509 double t; /* Current retry time */
510 } retry;
511
512 #define KX_NCHAL 16u
513
514 typedef struct kxchal {
515 struct keyexch *kx; /* Pointer back to key exchange */
516 dhge *C; /* Responder's challenge */
517 dhge *R; /* My reply to the challenge */
518 keyset *ks; /* Pointer to temporary keyset */
519 unsigned f; /* Various useful flags */
520 sel_timer t; /* Response timer for challenge */
521 retry rs; /* Retry state */
522 octet hc[MAXHASHSZ]; /* Hash of his challenge */
523 octet ck[MAXHASHSZ]; /* His magical check value */
524 octet hswrq_in[MAXHASHSZ]; /* Inbound switch request message */
525 octet hswok_in[MAXHASHSZ]; /* Inbound switch confirmation */
526 octet hswrq_out[MAXHASHSZ]; /* Outbound switch request message */
527 octet hswok_out[MAXHASHSZ]; /* Outbound switch confirmation */
528 } kxchal;
529
530 typedef struct keyexch {
531 struct peer *p; /* Pointer back to the peer */
532 kdata *kpriv; /* Private key and related info */
533 kdata *kpub; /* Peer's public key */
534 keyset **ks; /* Peer's list of keysets */
535 unsigned f; /* Various useful flags */
536 unsigned s; /* Current state in exchange */
537 sel_timer t; /* Timer for next exchange */
538 retry rs; /* Retry state */
539 dhsc *a; /* My temporary secret */
540 dhge *C; /* My challenge */
541 dhge *RX; /* The expected response */
542 unsigned nr; /* Number of extant responses */
543 time_t t_valid; /* When this exchange goes bad */
544 octet hc[MAXHASHSZ]; /* Hash of my challenge */
545 kxchal *r[KX_NCHAL]; /* Array of challenges */
546 } keyexch;
547
548 #define KXF_TIMER 1u /* Waiting for a timer to go off */
549 #define KXF_DEAD 2u /* The key-exchanger isn't up */
550 #define KXF_PUBKEY 4u /* Key exchanger has a public key */
551 #define KXF_CORK 8u /* Don't send anything yet */
552
553 enum {
554 KXS_DEAD, /* Uninitialized state (magical) */
555 KXS_CHAL, /* Main answer-challenges state */
556 KXS_COMMIT, /* Committed: send switch request */
557 KXS_SWITCH /* Switched: send confirmation */
558 };
559
560 /* --- Tunnel structure --- *
561 *
562 * Used to maintain system-specific information about the tunnel interface.
563 */
564
565 typedef struct tunnel tunnel;
566 struct peer;
567
568 typedef struct tunnel_ops {
569 const char *name; /* Name of this tunnel driver */
570 unsigned flags; /* Various interesting flags */
571 #define TUNF_PRIVOPEN 1u /* Need helper to open file */
572 void (*init)(void); /* Initializes the system */
573 tunnel *(*create)(struct peer */*p*/, int /*fd*/, char **/*ifn*/);
574 /* Initializes a new tunnel */
575 void (*setifname)(tunnel */*t*/, const char */*ifn*/);
576 /* Notifies ifname change */
577 void (*inject)(tunnel */*t*/, buf */*b*/); /* Sends packet through if */
578 void (*destroy)(tunnel */*t*/); /* Destroys a tunnel */
579 } tunnel_ops;
580
581 #ifndef TUN_INTERNALS
582 struct tunnel { const tunnel_ops *ops; };
583 #endif
584
585 /* --- Peer statistics --- *
586 *
587 * Contains various interesting and not-so-interesting statistics about a
588 * peer. This is updated by various parts of the code. The format of the
589 * structure isn't considered private, and @p_stats@ returns a pointer to the
590 * statistics block for a given peer.
591 */
592
593 typedef struct stats {
594 unsigned long sz_in, sz_out; /* Size of all data in and out */
595 unsigned long sz_kxin, sz_kxout; /* Size of key exchange messages */
596 unsigned long sz_ipin, sz_ipout; /* Size of encapsulated IP packets */
597 time_t t_start, t_last, t_kx; /* Time peer created, last pk, kx */
598 unsigned long n_reject; /* Number of rejected packets */
599 unsigned long n_in, n_out; /* Number of packets in and out */
600 unsigned long n_kxin, n_kxout; /* Number of key exchange packets */
601 unsigned long n_ipin, n_ipout; /* Number of encrypted packets */
602 } stats;
603
604 /* --- Peer structure --- *
605 *
606 * The main structure which glues everything else together.
607 */
608
609 typedef struct peerspec {
610 char *name; /* Peer's name */
611 char *privtag; /* Private key tag */
612 char *tag; /* Public key tag */
613 char *knock; /* Knock string, or null */
614 const tunnel_ops *tops; /* Tunnel operations */
615 unsigned long t_ka; /* Keep alive interval */
616 addr sa; /* Socket address to speak to */
617 unsigned f; /* Flags for the peer */
618 #define PSF_KXMASK 255u /* Key-exchange flags to set */
619 #define PSF_MOBILE 256u /* Address may change rapidly */
620 } peerspec;
621
622 typedef struct peer_byname {
623 sym_base _b;
624 struct peer *p;
625 } peer_byname;
626
627 typedef struct peer_byaddr {
628 addrmap_base _b;
629 struct peer *p;
630 } peer_byaddr;
631
632 typedef struct peer {
633 peer_byname *byname; /* Lookup-by-name block */
634 peer_byaddr *byaddr; /* Lookup-by-address block */
635 struct ping *pings; /* Pings we're waiting for */
636 peerspec spec; /* Specifications for this peer */
637 tunnel *t; /* Tunnel for local packets */
638 char *ifname; /* Interface name for tunnel */
639 keyset *ks; /* List head for keysets */
640 buf b; /* Buffer for sending packets */
641 stats st; /* Statistics */
642 keyexch kx; /* Key exchange protocol block */
643 sel_timer tka; /* Timer for keepalives */
644 } peer;
645
646 typedef struct peer_iter { sym_iter i; } peer_iter;
647
648 typedef struct ping {
649 struct ping *next, *prev; /* Links to next and previous */
650 peer *p; /* Peer so we can free it */
651 unsigned msg; /* Kind of response expected */
652 uint32 id; /* Id so we can recognize response */
653 octet magic[32]; /* Some random data */
654 sel_timer t; /* Timeout for ping */
655 void (*func)(int /*rc*/, void */*arg*/); /* Function to call when done */
656 void *arg; /* Argument for callback */
657 } ping;
658
659 enum {
660 PING_NONOTIFY = -1,
661 PING_OK = 0,
662 PING_TIMEOUT,
663 PING_PEERDIED,
664 PING_MAX
665 };
666
667 /* --- Admin structure --- */
668
669 #define OBUFSZ 16384u
670
671 typedef struct obuf {
672 struct obuf *next; /* Next buffer in list */
673 char *p_in, *p_out; /* Pointers into the buffer */
674 char buf[OBUFSZ]; /* The actual buffer */
675 } obuf;
676
677 typedef struct oqueue {
678 obuf *hd, *tl; /* Head and tail pointers */
679 } oqueue;
680
681 struct admin;
682
683 typedef struct admin_bgop {
684 struct admin_bgop *next, *prev; /* Links to next and previous */
685 struct admin *a; /* Owner job */
686 char *tag; /* Tag string for messages */
687 void (*cancel)(struct admin_bgop *); /* Destructor function */
688 } admin_bgop;
689
690 typedef struct admin_resop {
691 admin_bgop bg; /* Background operation header */
692 char *addr; /* Hostname to be resolved */
693 bres_client r; /* Background resolver task */
694 sel_timer t; /* Timer for resolver */
695 addr sa; /* Socket address */
696 size_t sasz; /* Socket address size */
697 void (*func)(struct admin_resop *, int); /* Handler */
698 } admin_resop;
699
700 enum { ARES_OK, ARES_FAIL };
701
702 typedef struct admin_addop {
703 admin_resop r; /* Name resolution header */
704 peerspec peer; /* Peer pending creation */
705 } admin_addop;
706
707 typedef struct admin_pingop {
708 admin_bgop bg; /* Background operation header */
709 ping ping; /* Ping pending response */
710 struct timeval pingtime; /* Time last ping was sent */
711 } admin_pingop;
712
713 typedef struct admin_service {
714 sym_base _b; /* Hash table base structure */
715 char *version; /* The provided version */
716 struct admin *prov; /* Which client provides me */
717 struct admin_service *next, *prev; /* Client's list of services */
718 } admin_service;
719
720 typedef struct admin_svcop {
721 admin_bgop bg; /* Background operation header */
722 struct admin *prov; /* Client servicing this job */
723 unsigned index; /* This job's index */
724 struct admin_svcop *next, *prev; /* Links for provider's jobs */
725 } admin_svcop;
726
727 typedef struct admin_jobentry {
728 unsigned short seq; /* Zero if unused */
729 union {
730 admin_svcop *op; /* Operation, if slot in use, ... */
731 uint32 next; /* ... or index of next free slot */
732 } u;
733 } admin_jobentry;
734
735 typedef struct admin_jobtable {
736 uint32 n, sz; /* Used slots and table size */
737 admin_svcop *active; /* List of active jobs */
738 uint32 free; /* Index of first free slot */
739 admin_jobentry *v; /* And the big array of entries */
740 } admin_jobtable;
741
742 struct admin {
743 struct admin *next, *prev; /* Links to next and previous */
744 unsigned f; /* Various useful flags */
745 unsigned ref; /* Reference counter */
746 #ifndef NTRACE
747 unsigned seq; /* Sequence number for tracing */
748 #endif
749 oqueue out; /* Output buffer list */
750 oqueue delay; /* Delayed output buffer list */
751 admin_bgop *bg; /* Backgrounded operations */
752 admin_service *svcs; /* Which services I provide */
753 admin_jobtable j; /* Table of outstanding jobs */
754 selbuf b; /* Line buffer for commands */
755 sel_file w; /* Selector for write buffering */
756 };
757
758 #define AF_DEAD 1u /* Destroy this admin block */
759 #define AF_CLOSE 2u /* Client closed connection */
760 #define AF_NOTE 4u /* Catch notifications */
761 #define AF_WARN 8u /* Catch warning messages */
762 #ifndef NTRACE
763 # define AF_TRACE 16u /* Catch tracing */
764 #endif
765 #define AF_FOREGROUND 32u /* Quit server when client closes */
766
767 #ifndef NTRACE
768 # define AF_ALLMSGS (AF_NOTE | AF_TRACE | AF_WARN)
769 #else
770 # define AF_ALLMSGS (AF_NOTE | AF_WARN)
771 #endif
772
773 /*----- Global variables --------------------------------------------------*/
774
775 extern sel_state sel; /* Global I/O event state */
776 extern octet buf_i[PKBUFSZ], buf_o[PKBUFSZ], buf_t[PKBUFSZ], buf_u[PKBUFSZ];
777 extern const tunnel_ops *tunnels[]; /* Table of tunnels (0-term) */
778 extern const tunnel_ops *tun_default; /* Default tunnel to use */
779 extern kdata *master; /* Default private key */
780 extern const char *tag_priv; /* Default private key tag */
781
782 #ifndef NTRACE
783 extern const trace_opt tr_opts[]; /* Trace options array */
784 extern unsigned tr_flags; /* Trace options flags */
785 #endif
786
787 /*----- Other macros ------------------------------------------------------*/
788
789 #define QUICKRAND \
790 do { rand_quick(RAND_GLOBAL); noise_timer(RAND_GLOBAL); } while (0)
791
792 /*----- Key management ----------------------------------------------------*/
793
794 /* --- @km_init@ --- *
795 *
796 * Arguments: @const char *privkr@ = private keyring file
797 * @const char *pubkr@ = public keyring file
798 * @const char *ptag@ = default private-key tag
799 *
800 * Returns: ---
801 *
802 * Use: Initializes the key-management machinery, loading the
803 * keyrings and so on.
804 */
805
806 extern void km_init(const char */*privkr*/, const char */*pubkr*/,
807 const char */*ptag*/);
808
809 /* --- @km_reload@ --- *
810 *
811 * Arguments: ---
812 *
813 * Returns: Zero if OK, nonzero to force reloading of keys.
814 *
815 * Use: Checks the keyrings to see if they need reloading.
816 */
817
818 extern int km_reload(void);
819
820 /* --- @km_findpub@, @km_findpriv@ --- *
821 *
822 * Arguments: @const char *tag@ = key tag to load
823 *
824 * Returns: Pointer to the kdata object if successful, or null on error.
825 *
826 * Use: Fetches a public or private key from the keyring.
827 */
828
829 extern kdata *km_findpub(const char */*tag*/);
830 extern kdata *km_findpriv(const char */*tag*/);
831
832 /* --- @km_findpubbyid@, @km_findprivbyid@ --- *
833 *
834 * Arguments: @uint32 id@ = key id to load
835 *
836 * Returns: Pointer to the kdata object if successful, or null on error.
837 *
838 * Use: Fetches a public or private key from the keyring given its
839 * numeric id.
840 */
841
842 extern kdata *km_findpubbyid(uint32 /*id*/);
843 extern kdata *km_findprivbyid(uint32 /*id*/);
844
845 /* --- @km_samealgsp@ --- *
846 *
847 * Arguments: @const kdata *kdx, *kdy@ = two key data objects
848 *
849 * Returns: Nonzero if their two algorithm selections are the same.
850 *
851 * Use: Checks sameness of algorithm selections: used to ensure that
852 * peers are using sensible algorithms.
853 */
854
855 extern int km_samealgsp(const kdata */*kdx*/, const kdata */*kdy*/);
856
857 /* --- @km_ref@ --- *
858 *
859 * Arguments: @kdata *kd@ = pointer to the kdata object
860 *
861 * Returns: ---
862 *
863 * Use: Claim a new reference to a kdata object.
864 */
865
866 extern void km_ref(kdata */*kd*/);
867
868 /* --- @km_unref@ --- *
869 *
870 * Arguments: @kdata *kd@ = pointer to the kdata object
871 *
872 * Returns: ---
873 *
874 * Use: Releases a reference to a kdata object.
875 */
876
877 extern void km_unref(kdata */*kd*/);
878
879 /* --- @km_tag@ --- *
880 *
881 * Arguments: @kdata *kd@ - pointer to the kdata object
882 *
883 * Returns: A pointer to the short tag by which the kdata was loaded.
884 */
885
886 extern const char *km_tag(kdata */*kd*/);
887
888 /*----- Key exchange ------------------------------------------------------*/
889
890 /* --- @kx_start@ --- *
891 *
892 * Arguments: @keyexch *kx@ = pointer to key exchange context
893 * @int forcep@ = nonzero to ignore the quiet timer
894 *
895 * Returns: ---
896 *
897 * Use: Stimulates a key exchange. If a key exchage is in progress,
898 * a new challenge is sent (unless the quiet timer forbids
899 * this); if no exchange is in progress, one is commenced.
900 */
901
902 extern void kx_start(keyexch */*kx*/, int /*forcep*/);
903
904 /* --- @kx_message@ --- *
905 *
906 * Arguments: @keyexch *kx@ = pointer to key exchange context
907 * @const addr *a@ = sender's IP address and port
908 * @unsigned msg@ = the message code
909 * @buf *b@ = pointer to buffer containing the packet
910 *
911 * Returns: Nonzero if the sender's address was unknown.
912 *
913 * Use: Reads a packet containing key exchange messages and handles
914 * it.
915 */
916
917 extern int kx_message(keyexch */*kx*/, const addr */*a*/,
918 unsigned /*msg*/, buf */*b*/);
919
920 /* --- @kx_free@ --- *
921 *
922 * Arguments: @keyexch *kx@ = pointer to key exchange context
923 *
924 * Returns: ---
925 *
926 * Use: Frees everything in a key exchange context.
927 */
928
929 extern void kx_free(keyexch */*kx*/);
930
931 /* --- @kx_newkeys@ --- *
932 *
933 * Arguments: @keyexch *kx@ = pointer to key exchange context
934 *
935 * Returns: ---
936 *
937 * Use: Informs the key exchange module that its keys may have
938 * changed. If fetching the new keys fails, the peer will be
939 * destroyed, we log messages and struggle along with the old
940 * keys.
941 */
942
943 extern void kx_newkeys(keyexch */*kx*/);
944
945 /* --- @kx_setup@ --- *
946 *
947 * Arguments: @keyexch *kx@ = pointer to key exchange context
948 * @peer *p@ = pointer to peer context
949 * @keyset **ks@ = pointer to keyset list
950 * @unsigned f@ = various useful flags
951 *
952 * Returns: Zero if OK, nonzero if it failed.
953 *
954 * Use: Initializes a key exchange module. The module currently
955 * contains no keys, and will attempt to initiate a key
956 * exchange.
957 */
958
959 extern int kx_setup(keyexch */*kx*/, peer */*p*/,
960 keyset **/*ks*/, unsigned /*f*/);
961
962 /* --- @kx_init@ --- *
963 *
964 * Arguments: ---
965 *
966 * Returns: ---
967 *
968 * Use: Initializes the key-exchange logic.
969 */
970
971 extern void kx_init(void);
972
973 /*----- Keysets and symmetric cryptography --------------------------------*/
974
975 /* --- @ks_drop@ --- *
976 *
977 * Arguments: @keyset *ks@ = pointer to a keyset
978 *
979 * Returns: ---
980 *
981 * Use: Decrements a keyset's reference counter. If the counter hits
982 * zero, the keyset is freed.
983 */
984
985 extern void ks_drop(keyset */*ks*/);
986
987 /* --- @ks_gen@ --- *
988 *
989 * Arguments: @deriveargs *a@ = key derivation parameters (modified)
990 * @peer *p@ = pointer to peer information
991 *
992 * Returns: A pointer to the new keyset.
993 *
994 * Use: Derives a new keyset from the given key material. This will
995 * set the @what@, @f@, and @hc@ members in @*a@; other members
996 * must be filled in by the caller.
997 *
998 * The new key is marked so that it won't be selected for output
999 * by @ksl_encrypt@. You can still encrypt data with it by
1000 * calling @ks_encrypt@ directly.
1001 */
1002
1003 extern keyset *ks_gen(deriveargs */*a*/, peer */*p*/);
1004
1005 /* --- @ks_activate@ --- *
1006 *
1007 * Arguments: @keyset *ks@ = pointer to a keyset
1008 *
1009 * Returns: ---
1010 *
1011 * Use: Activates a keyset, so that it can be used for encrypting
1012 * outgoing messages.
1013 */
1014
1015 extern void ks_activate(keyset */*ks*/);
1016
1017 /* --- @ks_encrypt@ --- *
1018 *
1019 * Arguments: @keyset *ks@ = pointer to a keyset
1020 * @unsigned ty@ = message type
1021 * @buf *b@ = pointer to input buffer
1022 * @buf *bb@ = pointer to output buffer
1023 *
1024 * Returns: Zero if successful; @KSERR_REGEN@ if we should negotiate a
1025 * new key; @KSERR_NOKEYS@ if the key is not usable. Also
1026 * returns zero if there was insufficient buffer (but the output
1027 * buffer is broken in this case).
1028 *
1029 * Use: Encrypts a block of data using the key. Note that the `key
1030 * ought to be replaced' notification is only ever given once
1031 * for each key. Also note that this call forces a keyset to be
1032 * used even if it's marked as not for data output.
1033 *
1034 * The encryption transform is permitted to corrupt @buf_u@ for
1035 * its own purposes. Neither the source nor destination should
1036 * be within @buf_u@; and callers mustn't expect anything stored
1037 * in @buf_u@ to still
1038 */
1039
1040 extern int ks_encrypt(keyset */*ks*/, unsigned /*ty*/,
1041 buf */*b*/, buf */*bb*/);
1042
1043 /* --- @ks_decrypt@ --- *
1044 *
1045 * Arguments: @keyset *ks@ = pointer to a keyset
1046 * @unsigned ty@ = expected type code
1047 * @buf *b@ = pointer to an input buffer
1048 * @buf *bb@ = pointer to an output buffer
1049 *
1050 * Returns: Zero on success; @KSERR_DECRYPT@ on failure. Also returns
1051 * zero if there was insufficient buffer (but the output buffer
1052 * is broken in this case).
1053 *
1054 * Use: Attempts to decrypt a message using a given key. Note that
1055 * requesting decryption with a key directly won't clear a
1056 * marking that it's not for encryption.
1057 *
1058 * The decryption transform is permitted to corrupt @buf_u@ for
1059 * its own purposes. Neither the source nor destination should
1060 * be within @buf_u@; and callers mustn't expect anything stored
1061 * in @buf_u@ to still
1062 */
1063
1064 extern int ks_decrypt(keyset */*ks*/, unsigned /*ty*/,
1065 buf */*b*/, buf */*bb*/);
1066
1067 /* --- @ksl_free@ --- *
1068 *
1069 * Arguments: @keyset **ksroot@ = pointer to keyset list head
1070 *
1071 * Returns: ---
1072 *
1073 * Use: Frees (releases references to) all of the keys in a keyset.
1074 */
1075
1076 extern void ksl_free(keyset **/*ksroot*/);
1077
1078 /* --- @ksl_link@ --- *
1079 *
1080 * Arguments: @keyset **ksroot@ = pointer to keyset list head
1081 * @keyset *ks@ = pointer to a keyset
1082 *
1083 * Returns: ---
1084 *
1085 * Use: Links a keyset into a list. A keyset can only be on one list
1086 * at a time. Bad things happen otherwise.
1087 */
1088
1089 extern void ksl_link(keyset **/*ksroot*/, keyset */*ks*/);
1090
1091 /* --- @ksl_prune@ --- *
1092 *
1093 * Arguments: @keyset **ksroot@ = pointer to keyset list head
1094 *
1095 * Returns: ---
1096 *
1097 * Use: Prunes the keyset list by removing keys which mustn't be used
1098 * any more.
1099 */
1100
1101 extern void ksl_prune(keyset **/*ksroot*/);
1102
1103 /* --- @ksl_encrypt@ --- *
1104 *
1105 * Arguments: @keyset **ksroot@ = pointer to keyset list head
1106 * @unsigned ty@ = message type
1107 * @buf *b@ = pointer to input buffer
1108 * @buf *bb@ = pointer to output buffer
1109 *
1110 * Returns: Zero if successful; @KSERR_REGEN@ if it's time to negotiate a
1111 * new key; @KSERR_NOKEYS@ if there are no suitable keys
1112 * available. Also returns zero if there was insufficient
1113 * buffer space (but the output buffer is broken in this case).
1114 *
1115 * Use: Encrypts a packet.
1116 */
1117
1118 extern int ksl_encrypt(keyset **/*ksroot*/, unsigned /*ty*/,
1119 buf */*b*/, buf */*bb*/);
1120
1121 /* --- @ksl_decrypt@ --- *
1122 *
1123 * Arguments: @keyset **ksroot@ = pointer to keyset list head
1124 * @unsigned ty@ = expected type code
1125 * @buf *b@ = pointer to input buffer
1126 * @buf *bb@ = pointer to output buffer
1127 *
1128 * Returns: Zero on success; @KSERR_DECRYPT@ on failure. Also returns
1129 * zero if there was insufficient buffer (but the output buffer
1130 * is broken in this case).
1131 *
1132 * Use: Decrypts a packet.
1133 */
1134
1135 extern int ksl_decrypt(keyset **/*ksroot*/, unsigned /*ty*/,
1136 buf */*b*/, buf */*bb*/);
1137
1138 /*----- Challenges --------------------------------------------------------*/
1139
1140 /* --- @c_new@ --- *
1141 *
1142 * Arguments: @const void *m@ = pointer to associated message, or null
1143 * @size_t msz@ = length of associated message
1144 * @buf *b@ = where to put the challenge
1145 *
1146 * Returns: Zero if OK, nonzero on error.
1147 *
1148 * Use: Issues a new challenge.
1149 */
1150
1151 extern int c_new(const void */*m*/, size_t /*msz*/, buf */*b*/);
1152
1153 /* --- @c_check@ --- *
1154 *
1155 * Arguments: @const void *m@ = pointer to associated message, or null
1156 * @size_t msz@ = length of associated message
1157 * @buf *b@ = where to find the challenge
1158 *
1159 * Returns: Zero if OK, nonzero if it didn't work.
1160 *
1161 * Use: Checks a challenge. On failure, the buffer is broken.
1162 */
1163
1164 extern int c_check(const void */*m*/, size_t /*msz*/, buf */*b*/);
1165
1166 /*----- Administration interface ------------------------------------------*/
1167
1168 #define A_END ((char *)0)
1169
1170 /* --- @a_vformat@ --- *
1171 *
1172 * Arguments: @dstr *d@ = where to leave the formatted message
1173 * @const char *fmt@ = pointer to format string
1174 * @va_list *ap@ = arguments in list
1175 *
1176 * Returns: ---
1177 *
1178 * Use: Main message token formatting driver. The arguments are
1179 * interleaved formatting tokens and their parameters, finally
1180 * terminated by an entry @A_END@.
1181 *
1182 * Tokens recognized:
1183 *
1184 * * "*..." ... -- pretokenized @dstr_putf@-like string
1185 *
1186 * * "?ADDR" SOCKADDR -- a socket address, to be converted
1187 *
1188 * * "?B64" BUFFER SIZE -- binary data to be base64-encoded
1189 *
1190 * * "?TOKENS" VECTOR -- null-terminated vector of tokens
1191 *
1192 * * "?PEER" PEER -- peer's name
1193 *
1194 * * "?ERRNO" ERRNO -- system error code
1195 *
1196 * * "[!]..." ... -- @dstr_putf@-like string as single token
1197 */
1198
1199 extern void a_vformat(dstr */*d*/, const char */*fmt*/, va_list */*ap*/);
1200
1201 /* --- @a_format@ --- *
1202 *
1203 * Arguments: @dstr *d@ = where to leave the formatted message
1204 * @const char *fmt@ = pointer to format string
1205 *
1206 * Returns: ---
1207 *
1208 * Use: Writes a tokenized message into a string, for later
1209 * presentation.
1210 */
1211
1212 extern void EXECL_LIKE(0) a_format(dstr */*d*/, const char */*fmt*/, ...);
1213
1214 /* --- @a_info@ --- *
1215 *
1216 * Arguments: @admin *a@ = connection
1217 * @const char *fmt@ = format string
1218 * @...@ = other arguments
1219 *
1220 * Returns: ---
1221 *
1222 * Use: Report information to an admin client.
1223 */
1224
1225 extern void EXECL_LIKE(0) a_info(admin */*a*/, const char */*fmt*/, ...);
1226
1227 /* --- @a_warn@ --- *
1228 *
1229 * Arguments: @const char *fmt@ = pointer to format string
1230 * @...@ = other arguments
1231 *
1232 * Returns: ---
1233 *
1234 * Use: Informs all admin connections of a warning.
1235 */
1236
1237 extern void EXECL_LIKE(0) a_warn(const char */*fmt*/, ...);
1238
1239 /* --- @a_notify@ --- *
1240 *
1241 * Arguments: @const char *fmt@ = pointer to format string
1242 * @...@ = other arguments
1243 *
1244 * Returns: ---
1245 *
1246 * Use: Sends a notification to interested admin connections.
1247 */
1248
1249 extern void EXECL_LIKE(0) a_notify(const char */*fmt*/, ...);
1250
1251 /* --- @a_create@ --- *
1252 *
1253 * Arguments: @int fd_in, fd_out@ = file descriptors to use
1254 * @unsigned f@ = initial flags to set
1255 *
1256 * Returns: ---
1257 *
1258 * Use: Creates a new admin connection.
1259 */
1260
1261 extern void a_create(int /*fd_in*/, int /*fd_out*/, unsigned /*f*/);
1262
1263 /* --- @a_quit@ --- *
1264 *
1265 * Arguments: ---
1266 *
1267 * Returns: ---
1268 *
1269 * Use: Shuts things down nicely.
1270 */
1271
1272 extern void a_quit(void);
1273
1274 /* --- @a_preselect@ --- *
1275 *
1276 * Arguments: ---
1277 *
1278 * Returns: ---
1279 *
1280 * Use: Informs the admin module that we're about to select again,
1281 * and that it should do cleanup things it has delayed until a
1282 * `safe' time.
1283 */
1284
1285 extern void a_preselect(void);
1286
1287 /* --- @a_daemon@ --- *
1288 *
1289 * Arguments: ---
1290 *
1291 * Returns: ---
1292 *
1293 * Use: Informs the admin module that it's a daemon.
1294 */
1295
1296 extern void a_daemon(void);
1297
1298 /* --- @a_init@ --- *
1299 *
1300 * Arguments: @const char *sock@ = socket name to create
1301 * @uid_t u@ = user to own the socket
1302 * @gid_t g@ = group to own the socket
1303 * @mode_t m@ = permissions to set on the socket
1304 *
1305 * Returns: ---
1306 *
1307 * Use: Creates the admin listening socket.
1308 */
1309
1310 extern void a_init(const char */*sock*/,
1311 uid_t /*u*/, gid_t /*g*/, mode_t /*m*/);
1312
1313 /*----- Mapping with addresses as keys ------------------------------------*/
1314
1315 /* --- @am_create@ --- *
1316 *
1317 * Arguments: @addrmap *m@ = pointer to map
1318 *
1319 * Returns: ---
1320 *
1321 * Use: Create an address map, properly set up.
1322 */
1323
1324 extern void am_create(addrmap */*m*/);
1325
1326 /* --- @am_destroy@ --- *
1327 *
1328 * Arguments: @addrmap *m@ = pointer to map
1329 *
1330 * Returns: ---
1331 *
1332 * Use: Destroy an address map, throwing away all the entries.
1333 */
1334
1335 extern void am_destroy(addrmap */*m*/);
1336
1337 /* --- @am_find@ --- *
1338 *
1339 * Arguments: @addrmap *m@ = pointer to map
1340 * @const addr *a@ = address to look up
1341 * @size_t sz@ = size of block to allocate
1342 * @unsigned *f@ = where to store flags
1343 *
1344 * Returns: Pointer to found item, or null.
1345 *
1346 * Use: Finds a record with the given IP address, set @*f@ nonzero
1347 * and returns it. If @sz@ is zero, and no match was found,
1348 * return null; otherwise allocate a new block of @sz@ bytes,
1349 * clear @*f@ to zero and return the block pointer.
1350 */
1351
1352 extern void *am_find(addrmap */*m*/, const addr */*a*/,
1353 size_t /*sz*/, unsigned */*f*/);
1354
1355 /* --- @am_remove@ --- *
1356 *
1357 * Arguments: @addrmap *m@ = pointer to map
1358 * @void *i@ = pointer to the item
1359 *
1360 * Returns: ---
1361 *
1362 * Use: Removes an item from the map.
1363 */
1364
1365 extern void am_remove(addrmap */*m*/, void */*i*/);
1366
1367 /*----- Privilege separation ----------------------------------------------*/
1368
1369 /* --- @ps_trace@ --- *
1370 *
1371 * Arguments: @unsigned mask@ = trace mask to check
1372 * @const char *fmt@ = message format
1373 * @...@ = values for placeholders
1374 *
1375 * Returns: ---
1376 *
1377 * Use: Writes a trace message.
1378 */
1379
1380 T( extern void PRINTF_LIKE(2, 3)
1381 ps_trace(unsigned /*mask*/, const char */*fmt*/, ...); )
1382
1383 /* --- @ps_warn@ --- *
1384 *
1385 * Arguments: @const char *fmt@ = message format
1386 * @...@ = values for placeholders
1387 *
1388 * Returns: ---
1389 *
1390 * Use: Writes a warning message.
1391 */
1392
1393 extern void PRINTF_LIKE(1, 2) ps_warn(const char */*fmt*/, ...);
1394
1395 /* --- @ps_tunfd@ --- *
1396 *
1397 * Arguments: @const tunnel_ops *tops@ = pointer to tunnel operations
1398 * @char **ifn@ = where to put the interface name
1399 *
1400 * Returns: The file descriptor, or @-1@ on error.
1401 *
1402 * Use: Fetches a file descriptor for a tunnel driver.
1403 */
1404
1405 extern int ps_tunfd(const tunnel_ops */*tops*/, char **/*ifn*/);
1406
1407 /* --- @ps_split@ --- *
1408 *
1409 * Arguments: @int detachp@ = whether to detach the child from its terminal
1410 *
1411 * Returns: ---
1412 *
1413 * Use: Separates off the privileged tunnel-opening service from the
1414 * rest of the server.
1415 */
1416
1417 extern void ps_split(int /*detachp*/);
1418
1419 /* --- @ps_quit@ --- *
1420 *
1421 * Arguments: ---
1422 *
1423 * Returns: ---
1424 *
1425 * Use: Detaches from the helper process.
1426 */
1427
1428 extern void ps_quit(void);
1429
1430 /*----- Peer management ---------------------------------------------------*/
1431
1432 /* --- @p_updateaddr@ --- *
1433 *
1434 * Arguments: @peer *p@ = pointer to peer block
1435 * @const addr *a@ = address to associate with this peer
1436 *
1437 * Returns: Zero if the address was changed; @+1@ if it was already
1438 * right.
1439 *
1440 * Use: Updates our idea of @p@'s address.
1441 */
1442
1443 extern int p_updateaddr(peer */*p*/, const addr */*a*/);
1444
1445 /* --- @p_txstart@ --- *
1446 *
1447 * Arguments: @peer *p@ = pointer to peer block
1448 * @unsigned msg@ = message type code
1449 *
1450 * Returns: A pointer to a buffer to write to.
1451 *
1452 * Use: Starts sending to a peer. Only one send can happen at a
1453 * time.
1454 */
1455
1456 extern buf *p_txstart(peer */*p*/, unsigned /*msg*/);
1457
1458 /* --- @p_txaddr@ --- *
1459 *
1460 * Arguments: @const addr *a@ = recipient address
1461 * @const void *p@ = pointer to packet to send
1462 * @size_t sz@ = length of packet
1463 *
1464 * Returns: Zero if successful, nonzero on error.
1465 *
1466 * Use: Sends a packet to an address which (possibly) isn't a current
1467 * peer.
1468 */
1469
1470 extern int p_txaddr(const addr */*a*/, const void */*p*/, size_t /*sz*/);
1471
1472 /* --- @p_txend@ --- *
1473 *
1474 * Arguments: @peer *p@ = pointer to peer block
1475 *
1476 * Returns: ---
1477 *
1478 * Use: Sends a packet to the peer.
1479 */
1480
1481 extern void p_txend(peer */*p*/);
1482
1483 /* --- @p_pingsend@ --- *
1484 *
1485 * Arguments: @peer *p@ = destination peer
1486 * @ping *pg@ = structure to fill in
1487 * @unsigned type@ = message type
1488 * @unsigned long timeout@ = how long to wait before giving up
1489 * @void (*func)(int, void *)@ = callback function
1490 * @void *arg@ = argument for callback
1491 *
1492 * Returns: Zero if successful, nonzero if it failed.
1493 *
1494 * Use: Sends a ping to a peer. Call @func@ with a nonzero argument
1495 * if we get an answer within the timeout, or zero if no answer.
1496 */
1497
1498 extern int p_pingsend(peer */*p*/, ping */*pg*/, unsigned /*type*/,
1499 unsigned long /*timeout*/,
1500 void (*/*func*/)(int, void *), void */*arg*/);
1501
1502 /* --- @p_pingdone@ --- *
1503 *
1504 * Arguments: @ping *p@ = ping structure
1505 * @int rc@ = return code to pass on
1506 *
1507 * Returns: ---
1508 *
1509 * Use: Disposes of a ping structure, maybe sending a notification.
1510 */
1511
1512 extern void p_pingdone(ping */*p*/, int /*rc*/);
1513
1514 /* --- @p_greet@ --- *
1515 *
1516 * Arguments: @peer *p@ = peer to send to
1517 * @const void *c@ = pointer to challenge
1518 * @size_t sz@ = size of challenge
1519 *
1520 * Returns: ---
1521 *
1522 * Use: Sends a greeting packet.
1523 */
1524
1525 extern void p_greet(peer */*p*/, const void */*c*/, size_t /*sz*/);
1526
1527 /* --- @p_tun@ --- *
1528 *
1529 * Arguments: @peer *p@ = pointer to peer block
1530 * @buf *b@ = buffer containing incoming packet
1531 *
1532 * Returns: ---
1533 *
1534 * Use: Handles a packet which needs to be sent to a peer.
1535 */
1536
1537 extern void p_tun(peer */*p*/, buf */*b*/);
1538
1539 /* --- @p_keyreload@ --- *
1540 *
1541 * Arguments: ---
1542 *
1543 * Returns: ---
1544 *
1545 * Use: Forces a check of the daemon's keyring files.
1546 */
1547
1548 extern void p_keyreload(void);
1549
1550 /* --- @p_interval@ --- *
1551 *
1552 * Arguments: ---
1553 *
1554 * Returns: ---
1555 *
1556 * Use: Called periodically to do tidying.
1557 */
1558
1559 extern void p_interval(void);
1560
1561 /* --- @p_stats@ --- *
1562 *
1563 * Arguments: @peer *p@ = pointer to a peer block
1564 *
1565 * Returns: A pointer to the peer's statistics.
1566 */
1567
1568 extern stats *p_stats(peer */*p*/);
1569
1570 /* --- @p_ifname@ --- *
1571 *
1572 * Arguments: @peer *p@ = pointer to a peer block
1573 *
1574 * Returns: A pointer to the peer's interface name.
1575 */
1576
1577 extern const char *p_ifname(peer */*p*/);
1578
1579 /* --- @p_setifname@ --- *
1580 *
1581 * Arguments: @peer *p@ = pointer to a peer block
1582 * @const char *name@ = pointer to the new name
1583 *
1584 * Returns: ---
1585 *
1586 * Use: Changes the name held for a peer's interface.
1587 */
1588
1589 extern void p_setifname(peer */*p*/, const char */*name*/);
1590
1591 /* --- @p_addr@ --- *
1592 *
1593 * Arguments: @peer *p@ = pointer to a peer block
1594 *
1595 * Returns: A pointer to the peer's address.
1596 */
1597
1598 extern const addr *p_addr(peer */*p*/);
1599
1600 /* --- @p_init@ --- *
1601 *
1602 * Arguments: @struct in_addr addr@ = address to bind to
1603 * @unsigned port@ = port number to listen to
1604 *
1605 * Returns: ---
1606 *
1607 * Use: Initializes the peer system; creates the socket.
1608 */
1609
1610 extern void p_init(struct in_addr /*addr*/, unsigned /*port*/);
1611
1612 /* --- @p_port@ --- *
1613 *
1614 * Arguments: ---
1615 *
1616 * Returns: Port number used for socket.
1617 */
1618
1619 unsigned p_port(void);
1620
1621 /* --- @p_create@ --- *
1622 *
1623 * Arguments: @peerspec *spec@ = information about this peer
1624 *
1625 * Returns: Pointer to the peer block, or null if it failed.
1626 *
1627 * Use: Creates a new named peer block. No peer is actually attached
1628 * by this point.
1629 */
1630
1631 extern peer *p_create(peerspec */*spec*/);
1632
1633 /* --- @p_name@ --- *
1634 *
1635 * Arguments: @peer *p@ = pointer to a peer block
1636 *
1637 * Returns: A pointer to the peer's name.
1638 *
1639 * Use: Equivalent to @p_spec(p)->name@.
1640 */
1641
1642 extern const char *p_name(peer */*p*/);
1643
1644 /* --- @p_tag@ --- *
1645 *
1646 * Arguments: @peer *p@ = pointer to a peer block
1647 *
1648 * Returns: A pointer to the peer's public key tag.
1649 */
1650
1651 extern const char *p_tag(peer */*p*/);
1652
1653 /* --- @p_privtag@ --- *
1654 *
1655 * Arguments: @peer *p@ = pointer to a peer block
1656 *
1657 * Returns: A pointer to the peer's private key tag.
1658 */
1659
1660 extern const char *p_privtag(peer */*p*/);
1661
1662 /* --- @p_spec@ --- *
1663 *
1664 * Arguments: @peer *p@ = pointer to a peer block
1665 *
1666 * Returns: Pointer to the peer's specification
1667 */
1668
1669 extern const peerspec *p_spec(peer */*p*/);
1670
1671 /* --- @p_findbyaddr@ --- *
1672 *
1673 * Arguments: @const addr *a@ = address to look up
1674 *
1675 * Returns: Pointer to the peer block, or null if not found.
1676 *
1677 * Use: Finds a peer by address.
1678 */
1679
1680 extern peer *p_findbyaddr(const addr */*a*/);
1681
1682 /* --- @p_find@ --- *
1683 *
1684 * Arguments: @const char *name@ = name to look up
1685 *
1686 * Returns: Pointer to the peer block, or null if not found.
1687 *
1688 * Use: Finds a peer by name.
1689 */
1690
1691 extern peer *p_find(const char */*name*/);
1692
1693 /* --- @p_destroy@ --- *
1694 *
1695 * Arguments: @peer *p@ = pointer to a peer
1696 *
1697 * Returns: ---
1698 *
1699 * Use: Destroys a peer.
1700 */
1701
1702 extern void p_destroy(peer */*p*/);
1703
1704 /* --- @FOREACH_PEER@ --- *
1705 *
1706 * Arguments: @p@ = name to bind to each peer
1707 * @stuff@ = thing to do for each item
1708 *
1709 * Use: Does something for each current peer.
1710 */
1711
1712 #define FOREACH_PEER(p, stuff) do { \
1713 peer_iter i_; \
1714 peer *p; \
1715 for (p_mkiter(&i_); (p = p_next(&i_)) != 0; ) stuff \
1716 } while (0)
1717
1718 /* --- @p_mkiter@ --- *
1719 *
1720 * Arguments: @peer_iter *i@ = pointer to an iterator
1721 *
1722 * Returns: ---
1723 *
1724 * Use: Initializes the iterator.
1725 */
1726
1727 extern void p_mkiter(peer_iter */*i*/);
1728
1729 /* --- @p_next@ --- *
1730 *
1731 * Arguments: @peer_iter *i@ = pointer to an iterator
1732 *
1733 * Returns: Next peer, or null if at the end.
1734 *
1735 * Use: Returns the next peer.
1736 */
1737
1738 extern peer *p_next(peer_iter */*i*/);
1739
1740 /*----- Tunnel drivers ----------------------------------------------------*/
1741
1742 #ifdef TUN_LINUX
1743 extern const tunnel_ops tun_linux;
1744 #endif
1745
1746 #ifdef TUN_UNET
1747 extern const tunnel_ops tun_unet;
1748 #endif
1749
1750 #ifdef TUN_BSD
1751 extern const tunnel_ops tun_bsd;
1752 #endif
1753
1754 extern const tunnel_ops tun_slip;
1755
1756 /*----- Other handy utilities ---------------------------------------------*/
1757
1758 /* --- @timestr@ --- *
1759 *
1760 * Arguments: @time_t t@ = a time to convert
1761 *
1762 * Returns: A pointer to a textual representation of the time.
1763 *
1764 * Use: Converts a time to a textual representation. Corrupts
1765 * @buf_u@.
1766 */
1767
1768 extern const char *timestr(time_t /*t*/);
1769
1770 /* --- @mystrieq@ --- *
1771 *
1772 * Arguments: @const char *x, *y@ = two strings
1773 *
1774 * Returns: True if @x@ and @y are equal, up to case.
1775 */
1776
1777 extern int mystrieq(const char */*x*/, const char */*y*/);
1778
1779 /* --- @addrsz@ --- *
1780 *
1781 * Arguments: @const addr *a@ = a network address
1782 *
1783 * Returns: The size of the address, for passing into the sockets API.
1784 */
1785
1786 extern socklen_t addrsz(const addr */*a*/);
1787
1788 /* --- @seq_reset@ --- *
1789 *
1790 * Arguments: @seqwin *s@ = sequence-checking window
1791 *
1792 * Returns: ---
1793 *
1794 * Use: Resets a sequence number window.
1795 */
1796
1797 extern void seq_reset(seqwin */*s*/);
1798
1799 /* --- @seq_check@ --- *
1800 *
1801 * Arguments: @seqwin *s@ = sequence-checking window
1802 * @uint32 q@ = sequence number to check
1803 * @const char *service@ = service to report message from
1804 *
1805 * Returns: A @SEQ_@ code.
1806 *
1807 * Use: Checks a sequence number against the window, updating things
1808 * as necessary.
1809 */
1810
1811 extern int seq_check(seqwin */*s*/, uint32 /*q*/, const char */*service*/);
1812
1813 typedef struct ratelim {
1814 unsigned n, max, persec;
1815 struct timeval when;
1816 } ratelim;
1817
1818 /* --- @ratelim_init@ --- *
1819 *
1820 * Arguments: @ratelim *r@ = rate-limiting state to fill in
1821 * @unsigned persec@ = credit to accumulate per second
1822 * @unsigned max@ = maximum credit to retain
1823 *
1824 * Returns: ---
1825 *
1826 * Use: Initialize a rate-limiting state.
1827 */
1828
1829 extern void ratelim_init(ratelim */*r*/,
1830 unsigned /*persec*/, unsigned /*max*/);
1831
1832 /* --- @ratelim_withdraw@ --- *
1833 *
1834 * Arguments: @ratelim *r@ = rate-limiting state
1835 * @unsigned n@ = credit to withdraw
1836 *
1837 * Returns: Zero if successful; @-1@ if there is unsufficient credit
1838 *
1839 * Use: Updates the state with any accumulated credit. Then, if
1840 * there there are more than @n@ credits available, withdraw @n@
1841 * and return successfully; otherwise, report failure.
1842 */
1843
1844 extern int ratelim_withdraw(ratelim */*r*/, unsigned /*n*/);
1845
1846 /* --- @ies_encrypt@ --- *
1847 *
1848 * Arguments: @kdata *kpub@ = recipient's public key
1849 * @unsigned ty@ = message type octet
1850 * @buf *b@ = input message buffer
1851 * @buf *bb@ = output buffer for the ciphertext
1852 *
1853 * Returns: On error, returns a @KSERR_...@ code or breaks the buffer;
1854 * on success, returns zero and the buffer is good.
1855 *
1856 * Use: Encrypts a message for a recipient, given their public key.
1857 * This does not (by itself) provide forward secrecy or sender
1858 * authenticity. The ciphertext is self-delimiting (unlike
1859 * @ks_encrypt@).
1860 */
1861
1862 extern int ies_encrypt(kdata */*kpub*/, unsigned /*ty*/,
1863 buf */*b*/, buf */*bb*/);
1864
1865 /* --- @ies_decrypt@ --- *
1866 *
1867 * Arguments: @kdata *kpub@ = private key key
1868 * @unsigned ty@ = message type octet
1869 * @buf *b@ = input ciphertext buffer
1870 * @buf *bb@ = output buffer for the message
1871 *
1872 * Returns: On error, returns a @KSERR_...@ code; on success, returns
1873 * zero and the buffer is good.
1874 *
1875 * Use: Decrypts a message encrypted using @ies_encrypt@, given our
1876 * private key.
1877 */
1878
1879 extern int ies_decrypt(kdata */*kpriv*/, unsigned /*ty*/,
1880 buf */*b*/, buf */*bb*/);
1881
1882 /*----- That's all, folks -------------------------------------------------*/
1883
1884 #ifdef __cplusplus
1885 }
1886 #endif
1887
1888 #endif