chiark / gitweb /
site: interpret first 4 bytes of extrainfo as capabilities
[secnet.git] / secnet.h
1 /* Core interface of secnet, to be used by all modules */
2
3 #ifndef secnet_h
4 #define secnet_h
5
6 #include "config.h"
7 #include <stdlib.h>
8 #include <stdarg.h>
9 #include <stdio.h>
10 #include <string.h>
11 #include <assert.h>
12 #include <sys/poll.h>
13 #include <sys/types.h>
14 #include <sys/time.h>
15 #include <netinet/in.h>
16
17 typedef char *string_t;
18 typedef const char *cstring_t;
19 typedef enum {False,True} bool_t;
20
21 #define ASSERT(x) do { if (!(x)) { fatal("assertion failed line %d file " \
22                                          __FILE__,__LINE__); } } while(0)
23
24 /* from version.c */
25
26 extern char version[];
27
28 /* from logmsg.c */
29 extern uint32_t message_level;
30 extern bool_t secnet_is_daemon;
31 extern struct log_if *system_log;
32
33 /* from process.c */
34 extern void start_signal_handling(void);
35
36 /***** CONFIGURATION support *****/
37
38 extern bool_t just_check_config; /* If True then we're going to exit after
39                                     reading the configuration file */
40 extern bool_t background; /* If True then we'll eventually run as a daemon */
41
42 typedef struct dict dict_t;        /* Configuration dictionary */
43 typedef struct closure closure_t;
44 typedef struct item item_t;
45 typedef struct list list_t;        /* A list of items */
46
47 /* Configuration file location, for error-reporting */
48 struct cloc {
49     cstring_t file;
50     int line;
51 };
52
53 /* Modules export closures, which can be invoked from the configuration file.
54    "Invoking" a closure usually returns another closure (of a different
55    type), but can actually return any configuration object. */
56 typedef list_t *(apply_fn)(closure_t *self, struct cloc loc,
57                            dict_t *context, list_t *data);
58 struct closure {
59     cstring_t description; /* For debugging */
60     uint32_t type; /* Central registry... */
61     apply_fn *apply;
62     void *interface; /* Interface for use inside secnet; depends on type */
63 };
64
65 enum types { t_null, t_bool, t_string, t_number, t_dict, t_closure };
66 struct item {
67     enum types type;
68     union {
69         bool_t bool;
70         string_t string;
71         uint32_t number;
72         dict_t *dict;
73         closure_t *closure;
74     } data;
75     struct cloc loc;
76 };
77
78 /* Note that it is unwise to use this structure directly; use the list
79    manipulation functions instead. */
80 struct list {
81     item_t *item;
82     struct list *next;
83 };
84
85 /* In the following two lookup functions, NULL means 'not found' */
86 /* Lookup a value in the specified dictionary, or its parents */
87 extern list_t *dict_lookup(dict_t *dict, cstring_t key);
88 /* Lookup a value in just the specified dictionary */
89 extern list_t *dict_lookup_primitive(dict_t *dict, cstring_t key);
90 /* Add a value to the specified dictionary */
91 extern void dict_add(dict_t *dict, cstring_t key, list_t *val);
92 /* Obtain an array of keys in the dictionary. malloced; caller frees */
93 extern cstring_t *dict_keys(dict_t *dict);
94
95 /* List-manipulation functions */
96 extern list_t *list_new(void);
97 extern int32_t list_length(list_t *a);
98 extern list_t *list_append(list_t *a, item_t *i);
99 extern list_t *list_append_list(list_t *a, list_t *b);
100 /* Returns an item from the list (index starts at 0), or NULL */
101 extern item_t *list_elem(list_t *l, int32_t index);
102
103 /* Convenience functions */
104 extern list_t *new_closure(closure_t *cl);
105 extern void add_closure(dict_t *dict, cstring_t name, apply_fn apply);
106 extern void *find_cl_if(dict_t *dict, cstring_t name, uint32_t type,
107                         bool_t fail_if_invalid, cstring_t desc,
108                         struct cloc loc);
109 extern item_t *dict_find_item(dict_t *dict, cstring_t key, bool_t required,
110                               cstring_t desc, struct cloc loc);
111 extern string_t dict_read_string(dict_t *dict, cstring_t key, bool_t required,
112                                  cstring_t desc, struct cloc loc);
113 extern uint32_t dict_read_number(dict_t *dict, cstring_t key, bool_t required,
114                                  cstring_t desc, struct cloc loc,
115                                  uint32_t def);
116   /* return value can safely be assigned to int32_t */
117 extern bool_t dict_read_bool(dict_t *dict, cstring_t key, bool_t required,
118                              cstring_t desc, struct cloc loc, bool_t def);
119 struct flagstr {
120     cstring_t name;
121     uint32_t value;
122 };
123 extern uint32_t string_to_word(cstring_t s, struct cloc loc,
124                                struct flagstr *f, cstring_t desc);
125 extern uint32_t string_list_to_word(list_t *l, struct flagstr *f,
126                                     cstring_t desc);
127
128 /***** END of configuration support *****/
129
130 /***** UTILITY functions *****/
131
132 extern char *safe_strdup(const char *string, const char *message);
133 extern void *safe_malloc(size_t size, const char *message);
134 extern void *safe_malloc_ary(size_t size, size_t count, const char *message);
135
136 extern int sys_cmd(const char *file, const char *argc, ...);
137
138 extern uint64_t now_global;
139 extern struct timeval tv_now_global;
140
141 static const uint64_t       *const now    = &now_global;
142 static const struct timeval *const tv_now = &tv_now_global;
143
144 /* "now" is current program time, in milliseconds. It is derived
145    from tv_now. Both are provided by the event loop. */
146
147 /***** END of utility functions *****/
148
149 /***** SCHEDULING support */
150
151 /* If nfds_io is insufficient for your needs, set it to the required
152    number and return ERANGE. timeout is in milliseconds; if it is too
153    high then lower it. It starts at -1 (==infinite) */
154 typedef int beforepoll_fn(void *st, struct pollfd *fds, int *nfds_io,
155                           int *timeout_io);
156 typedef void afterpoll_fn(void *st, struct pollfd *fds, int nfds);
157
158 /* Register interest in the main loop of the program. Before a call
159    to poll() your supplied beforepoll function will be called. After
160    the call to poll() the supplied afterpoll function will be called.
161    max_nfds is a _hint_ about the maximum number of struct pollfd
162    structures you may require - you can always ask for more in
163    *nfds_io. */
164 extern void register_for_poll(void *st, beforepoll_fn *before,
165                               afterpoll_fn *after, int32_t max_nfds,
166                               cstring_t desc);
167
168 /***** END of scheduling support */
169
170 /***** PROGRAM LIFETIME support */
171
172 /* The secnet program goes through a number of phases in its lifetime.
173    Module code may arrange to be called just as various phases are
174    entered.
175  
176    Remember to update the table in util.c if changing the set of
177    phases. */
178
179 enum phase {
180     PHASE_INIT,
181     PHASE_GETOPTS,             /* Process command-line arguments */
182     PHASE_READCONFIG,          /* Parse and process configuration file */
183     PHASE_SETUP,               /* Process information in configuration */
184     PHASE_DAEMONIZE,           /* Become a daemon (if necessary) */
185     PHASE_GETRESOURCES,        /* Obtain all external resources */
186     PHASE_DROPPRIV,            /* Last chance for privileged operations */
187     PHASE_RUN,
188     PHASE_SHUTDOWN,            /* About to die; delete key material, etc. */
189     /* Keep this last: */
190     NR_PHASES,
191 };
192
193 typedef void hook_fn(void *self, uint32_t newphase);
194 bool_t add_hook(uint32_t phase, hook_fn *f, void *state);
195 bool_t remove_hook(uint32_t phase, hook_fn *f, void *state);
196
197 extern uint32_t current_phase;
198 extern void enter_phase(uint32_t new_phase);
199
200 /* Some features (like netlink 'soft' routes) require that secnet
201    retain root privileges.  They should indicate that here when
202    appropriate. */
203 extern bool_t require_root_privileges;
204 extern cstring_t require_root_privileges_explanation;
205
206 /***** END of program lifetime support *****/
207
208 /***** MODULE support *****/
209
210 /* Module initialisation function type - modules export one function of
211    this type which is called to initialise them. For dynamically loaded
212    modules it's called "secnet_module". */
213 typedef void init_module(dict_t *dict);
214
215 extern void init_builtin_modules(dict_t *dict);
216
217 extern init_module resolver_module;
218 extern init_module random_module;
219 extern init_module udp_module;
220 extern init_module util_module;
221 extern init_module site_module;
222 extern init_module transform_eax_module;
223 extern init_module transform_cbcmac_module;
224 extern init_module netlink_module;
225 extern init_module rsa_module;
226 extern init_module dh_module;
227 extern init_module md5_module;
228 extern init_module slip_module;
229 extern init_module tun_module;
230 extern init_module sha1_module;
231 extern init_module log_module;
232
233 /***** END of module support *****/
234
235 /***** CLOSURE TYPES and interface definitions *****/
236
237 #define CL_PURE         0
238 #define CL_RESOLVER     1
239 #define CL_RANDOMSRC    2
240 #define CL_RSAPUBKEY    3
241 #define CL_RSAPRIVKEY   4
242 #define CL_COMM         5
243 #define CL_IPIF         6
244 #define CL_LOG          7
245 #define CL_SITE         8
246 #define CL_TRANSFORM    9
247 #define CL_DH          11
248 #define CL_HASH        12
249 #define CL_BUFFER      13
250 #define CL_NETLINK     14
251
252 struct buffer_if;
253
254 /* PURE closure requires no interface */
255
256 /* RESOLVER interface */
257
258 /* Answers to queries are delivered to a function of this
259    type. 'address' will be NULL if there was a problem with the query. It
260    will be freed once resolve_answer_fn returns. It is in network byte
261    order. */
262 /* XXX extend to be able to provide multiple answers */
263 typedef void resolve_answer_fn(void *st, struct in_addr *addr);
264 typedef bool_t resolve_request_fn(void *st, cstring_t name,
265                                   resolve_answer_fn *cb, void *cst);
266 struct resolver_if {
267     void *st;
268     resolve_request_fn *request;
269 };
270
271 /* RANDOMSRC interface */
272
273 /* Return some random data. Returns TRUE for success. */
274 typedef bool_t random_fn(void *st, int32_t bytes, uint8_t *buff);
275
276 struct random_if {
277     void *st;
278     bool_t blocking;
279     random_fn *generate;
280 };
281
282 /* RSAPUBKEY interface */
283
284 typedef bool_t rsa_checksig_fn(void *st, uint8_t *data, int32_t datalen,
285                                cstring_t signature);
286 struct rsapubkey_if {
287     void *st;
288     rsa_checksig_fn *check;
289 };
290
291 /* RSAPRIVKEY interface */
292
293 typedef string_t rsa_makesig_fn(void *st, uint8_t *data, int32_t datalen);
294 struct rsaprivkey_if {
295     void *st;
296     rsa_makesig_fn *sign;
297 };
298
299 /* COMM interface */
300
301 struct comm_addr {
302     /* This struct is pure data; in particular comm's clients may
303        freely copy it. */
304     /* Everyone is also guaranteed that all padding is set to zero, ie
305        that comm_addrs referring to semantically identical peers will
306        compare equal with memcmp.  Anyone who constructs a comm_addr
307        must start by memsetting it with FILLZERO, or some
308        equivalent. */
309     struct comm_if *comm;
310     struct sockaddr_in sin;
311 };
312
313 /* Return True if the packet was processed, and shouldn't be passed to
314    any other potential receivers. */
315 typedef bool_t comm_notify_fn(void *state, struct buffer_if *buf,
316                               const struct comm_addr *source);
317 typedef void comm_request_notify_fn(void *commst, void *nst,
318                                     comm_notify_fn *fn);
319 typedef void comm_release_notify_fn(void *commst, void *nst,
320                                     comm_notify_fn *fn);
321 typedef bool_t comm_sendmsg_fn(void *commst, struct buffer_if *buf,
322                                const struct comm_addr *dest);
323 typedef const char *comm_addr_to_string_fn(void *commst,
324                                            const struct comm_addr *ca);
325         /* Returned string is in a static buffer. */
326 struct comm_if {
327     void *st;
328     int32_t min_start_pad;
329     int32_t min_end_pad;
330     comm_request_notify_fn *request_notify;
331     comm_release_notify_fn *release_notify;
332     comm_sendmsg_fn *sendmsg;
333     comm_addr_to_string_fn *addr_to_string;
334 };
335
336 /* LOG interface */
337
338 typedef void log_msg_fn(void *st, int class, const char *message, ...);
339 typedef void log_vmsg_fn(void *st, int class, const char *message,
340                          va_list args);
341 struct log_if {
342     void *st;
343     log_msg_fn *log;
344     log_vmsg_fn *vlog;
345 };
346 /* (convenience functions, defined in util.c) */
347 extern void slilog(struct log_if *lf, int class, const char *message, ...)
348 FORMAT(printf,3,4);
349 extern void vslilog(struct log_if *lf, int class, const char *message, va_list)
350 FORMAT(printf,3,0);
351
352 /* SITE interface */
353
354 /* Pretty much a placeholder; allows starting and stopping of processing,
355    key expiry, etc. */
356 typedef void site_control_fn(void *st, bool_t run);
357 typedef uint32_t site_status_fn(void *st);
358 struct site_if {
359     void *st;
360     site_control_fn *control;
361     site_status_fn *status;
362 };
363
364 /* TRANSFORM interface */
365
366 /* A reversable transformation. Transforms buffer in-place; may add
367    data to start or end. Maximum amount of data to be added specified
368    in max_start_pad and max_end_pad. (Reverse transformations decrease
369    length, of course.)  Transformations may be key-dependent, in which
370    case key material is passed in at initialisation time. They may
371    also depend on internal factors (eg. time) and keep internal
372    state. A struct transform_if only represents a particular type of
373    transformation; instances of the transformation (eg. with
374    particular key material) have a different C type. The same
375    secret key will be used in opposite directions between a pair of
376    secnets; one of these pairs will get direction==False, the other True. */
377
378 typedef struct transform_inst_if *transform_createinstance_fn(void *st);
379 typedef bool_t transform_setkey_fn(void *st, uint8_t *key, int32_t keylen,
380                                    bool_t direction);
381 typedef bool_t transform_valid_fn(void *st); /* 0: no key; 1: ok */
382 typedef void transform_delkey_fn(void *st);
383 typedef void transform_destroyinstance_fn(void *st);
384 /* Returns:
385  *   0: all is well
386  *   1: for any other problem
387  *   2: message decrypted but sequence number was out of range
388  */
389 typedef uint32_t transform_apply_fn(void *st, struct buffer_if *buf,
390                                     const char **errmsg);
391
392 struct transform_inst_if {
393     void *st;
394     transform_setkey_fn *setkey;
395     transform_valid_fn *valid;
396     transform_delkey_fn *delkey;
397     transform_apply_fn *forwards;
398     transform_apply_fn *reverse;
399     transform_destroyinstance_fn *destroy;
400 };
401
402 struct transform_if {
403     void *st;
404     int32_t max_start_pad; /* these three are all <<< INT_MAX */
405     int32_t max_end_pad;
406     int32_t keylen; /* 0 means give the transform exactly as much as there is */
407     transform_createinstance_fn *create;
408 };
409
410 /* NETLINK interface */
411
412 /* Used by netlink to deliver to site, and by site to deliver to
413    netlink.  cid is the client identifier returned by
414    netlink_regnets_fn.  If buf has size 0 then the function is just
415    being called for its site-effects (eg. making the site code attempt
416    to bring up a network link) */
417 typedef void netlink_deliver_fn(void *st, struct buffer_if *buf);
418 /* site code can tell netlink when outgoing packets will be dropped,
419    so netlink can generate appropriate ICMP and make routing decisions */
420 #define LINK_QUALITY_UNUSED 0   /* This link is unused, do not make this netlink */
421 #define LINK_QUALITY_DOWN 1   /* No chance of a packet being delivered right away*/
422 #define LINK_QUALITY_DOWN_STALE_ADDRESS 2 /* Link down, old address information */
423 #define LINK_QUALITY_DOWN_CURRENT_ADDRESS 3 /* Link down, current address information */
424 #define LINK_QUALITY_UP 4     /* Link active */
425 #define MAXIMUM_LINK_QUALITY 3
426 typedef void netlink_link_quality_fn(void *st, uint32_t quality);
427 typedef void netlink_register_fn(void *st, netlink_deliver_fn *deliver,
428                                  void *dst, int32_t max_start_pad,
429                                  int32_t max_end_pad);
430 typedef void netlink_output_config_fn(void *st, struct buffer_if *buf);
431 typedef bool_t netlink_check_config_fn(void *st, struct buffer_if *buf);
432 typedef void netlink_set_mtu_fn(void *st, int32_t new_mtu);
433 struct netlink_if {
434     void *st;
435     netlink_register_fn *reg;
436     netlink_deliver_fn *deliver;
437     netlink_link_quality_fn *set_quality;
438     netlink_set_mtu_fn *set_mtu;
439 };
440
441 /* DH interface */
442
443 /* Returns public key as a malloced hex string */
444 typedef string_t dh_makepublic_fn(void *st, uint8_t *secret,
445                                   int32_t secretlen);
446 /* Fills buffer (up to buflen) with shared secret */
447 typedef void dh_makeshared_fn(void *st, uint8_t *secret,
448                               int32_t secretlen, cstring_t rempublic,
449                               uint8_t *sharedsecret, int32_t buflen);
450 struct dh_if {
451     void *st;
452     int32_t len; /* Approximate size of modulus in bytes */
453     int32_t ceil_len; /* Number of bytes just sufficient to contain modulus */
454     dh_makepublic_fn *makepublic;
455     dh_makeshared_fn *makeshared;
456 };
457
458 /* HASH interface */
459
460 typedef void *hash_init_fn(void);
461 typedef void hash_update_fn(void *st, const void *buf, int32_t len);
462 typedef void hash_final_fn(void *st, uint8_t *digest);
463 struct hash_if {
464     int32_t len; /* Hash output length in bytes */
465     hash_init_fn *init;
466     hash_update_fn *update;
467     hash_final_fn *final;
468 };
469
470 /* BUFFER interface */
471
472 struct buffer_if {
473     bool_t free;
474     cstring_t owner; /* Set to constant string */
475     uint32_t flags; /* How paranoid should we be? */
476     struct cloc loc; /* Where we were defined */
477     uint8_t *base;
478     uint8_t *start;
479     int32_t size; /* Size of buffer contents */
480     int32_t len; /* Total length allocated at base */
481 };
482
483 /***** LOG functions *****/
484
485 #define M_DEBUG_CONFIG 0x001
486 #define M_DEBUG_PHASE  0x002
487 #define M_DEBUG        0x004
488 #define M_INFO         0x008
489 #define M_NOTICE       0x010
490 #define M_WARNING      0x020
491 #define M_ERR          0x040
492 #define M_SECURITY     0x080
493 #define M_FATAL        0x100
494
495 /* The fatal() family of functions require messages that do not end in '\n' */
496 extern NORETURN(fatal(const char *message, ...));
497 extern NORETURN(fatal_perror(const char *message, ...));
498 extern NORETURN(fatal_status(int status, const char *message, ...));
499 extern NORETURN(fatal_perror_status(int status, const char *message, ...));
500
501 /* The cfgfatal() family of functions require messages that end in '\n' */
502 extern NORETURN(cfgfatal(struct cloc loc, cstring_t facility,
503                          const char *message, ...));
504 extern void cfgfile_postreadcheck(struct cloc loc, FILE *f);
505 extern NORETURN(vcfgfatal_maybefile(FILE *maybe_f, struct cloc loc,
506                                     cstring_t facility, const char *message,
507                                     va_list));
508 extern NORETURN(cfgfatal_maybefile(FILE *maybe_f, struct cloc loc,
509                                    cstring_t facility,
510                                    const char *message, ...));
511
512 extern void Message(uint32_t class, const char *message, ...)
513     FORMAT(printf,2,3);
514 extern void log_from_fd(int fd, cstring_t prefix, struct log_if *log);
515
516 /***** END of log functions *****/
517
518 #define STRING2(x) #x
519 #define STRING(x) STRING2(x)
520
521 #define FILLZERO(obj) (memset(&(obj),0,sizeof((obj))))
522
523 #endif /* secnet_h */