1 /* Core interface of secnet, to be used by all modules */
6 #define ADNS_FEATURE_MANYAF
19 #include <sys/types.h>
22 #include <netinet/in.h>
23 #include <arpa/inet.h>
25 #include <bsd/sys/queue.h>
27 #define MAX_PEER_ADDRS 5
28 /* send at most this many copies; honour at most that many addresses */
33 typedef char *string_t;
34 typedef const char *cstring_t;
36 #define False (_Bool)0
42 struct sockaddr_in sin;
44 struct sockaddr_in6 sin6;
48 #define ASSERT(x) do { if (!(x)) { fatal("assertion failed line %d file " \
49 __FILE__,__LINE__); } } while(0)
53 extern char version[];
56 extern uint32_t message_level;
57 extern bool_t secnet_is_daemon;
58 extern struct log_if *system_log;
61 extern void start_signal_handling(void);
64 /* Must be called before exec in every child made after
65 start_signal_handling. Safe to call in earlier children too. */
67 void childpersist_closefd_hook(void *fd_p, uint32_t newphase);
68 /* Convenience hook function for use with add_hook PHASE_CHILDPERSIST.
69 With `int fd' in your state struct, pass fd_p=&fd. The hook checks
70 whether fd>=0, so you can use it for an fd which is only sometimes
71 open. This function will set fd to -1, so it is idempotent. */
73 /***** CONFIGURATION support *****/
75 extern bool_t just_check_config; /* If True then we're going to exit after
76 reading the configuration file */
77 extern bool_t background; /* If True then we'll eventually run as a daemon */
79 typedef struct dict dict_t; /* Configuration dictionary */
80 typedef struct closure closure_t;
81 typedef struct item item_t;
82 typedef struct list list_t; /* A list of items */
84 /* Configuration file location, for error-reporting */
90 /* Modules export closures, which can be invoked from the configuration file.
91 "Invoking" a closure usually returns another closure (of a different
92 type), but can actually return any configuration object. */
93 typedef list_t *(apply_fn)(closure_t *self, struct cloc loc,
94 dict_t *context, list_t *data);
96 cstring_t description; /* For debugging */
97 uint32_t type; /* Central registry... */
99 void *interface; /* Interface for use inside secnet; depends on type */
102 enum types { t_null, t_bool, t_string, t_number, t_dict, t_closure };
115 /* Note that it is unwise to use this structure directly; use the list
116 manipulation functions instead. */
122 /* In the following two lookup functions, NULL means 'not found' */
123 /* Lookup a value in the specified dictionary, or its parents */
124 extern list_t *dict_lookup(dict_t *dict, cstring_t key);
125 /* Lookup a value in just the specified dictionary */
126 extern list_t *dict_lookup_primitive(dict_t *dict, cstring_t key);
127 /* Add a value to the specified dictionary */
128 extern void dict_add(dict_t *dict, cstring_t key, list_t *val);
129 /* Obtain an array of keys in the dictionary. malloced; caller frees */
130 extern cstring_t *dict_keys(dict_t *dict);
132 /* List-manipulation functions */
133 extern list_t *list_new(void);
134 extern int32_t list_length(const list_t *a);
135 extern list_t *list_append(list_t *a, item_t *i);
136 extern list_t *list_append_list(list_t *a, list_t *b);
137 /* Returns an item from the list (index starts at 0), or NULL */
138 extern item_t *list_elem(list_t *l, int32_t index);
140 /* Convenience functions */
141 extern list_t *new_closure(closure_t *cl);
142 extern void add_closure(dict_t *dict, cstring_t name, apply_fn apply);
143 extern void *find_cl_if(dict_t *dict, cstring_t name, uint32_t type,
144 bool_t fail_if_invalid, cstring_t desc,
146 extern item_t *dict_find_item(dict_t *dict, cstring_t key, bool_t required,
147 cstring_t desc, struct cloc loc);
148 extern string_t dict_read_string(dict_t *dict, cstring_t key, bool_t required,
149 cstring_t desc, struct cloc loc);
150 extern uint32_t dict_read_number(dict_t *dict, cstring_t key, bool_t required,
151 cstring_t desc, struct cloc loc,
153 /* return value can safely be assigned to int32_t */
154 extern bool_t dict_read_bool(dict_t *dict, cstring_t key, bool_t required,
155 cstring_t desc, struct cloc loc, bool_t def);
156 const char **dict_read_string_array(dict_t *dict, cstring_t key,
157 bool_t required, cstring_t desc,
158 struct cloc loc, const char *const *def);
159 /* Return value is a NULL-terminated array obtained from malloc;
160 * Individual string values are still owned by config file machinery
161 * and must not be modified or freed. Returns NULL if key not
168 extern uint32_t string_to_word(cstring_t s, struct cloc loc,
169 struct flagstr *f, cstring_t desc);
170 extern uint32_t string_list_to_word(list_t *l, struct flagstr *f,
173 /***** END of configuration support *****/
175 /***** UTILITY functions *****/
177 extern char *safe_strdup(const char *string, const char *message);
178 extern void *safe_malloc(size_t size, const char *message);
179 extern void *safe_malloc_ary(size_t size, size_t count, const char *message);
180 extern void *safe_realloc_ary(void *p, size_t size, size_t count,
181 const char *message);
184 ((p)=safe_malloc(sizeof(*(p)), \
186 #define NEW_ARY(p,count) \
187 ((p)=safe_malloc_ary(sizeof(*(p)),(count), \
188 __FILE__ ":" #p "[" #count "]"))
189 #define REALLOC_ARY(p,count) \
190 ((p)=safe_realloc_ary((p),sizeof(*(p)),(count), \
191 __FILE__ ":" #p "[" #count "]"))
193 void setcloexec(int fd); /* cannot fail */
194 void setnonblock(int fd); /* cannot fail */
195 void pipe_cloexec(int fd[2]); /* pipe(), setcloexec() twice; cannot fail */
197 extern int sys_cmd(const char *file, const char *argc, ...);
199 extern uint64_t now_global;
200 extern struct timeval tv_now_global;
202 static const uint64_t *const now = &now_global;
203 static const struct timeval *const tv_now = &tv_now_global;
205 /* "now" is current program time, in milliseconds. It is derived
206 from tv_now. Both are provided by the event loop. */
208 /***** END of utility functions *****/
210 /***** START of max_start_pad handling *****/
212 extern int32_t site_max_start_pad, transform_max_start_pad,
215 void update_max_start_pad(int32_t *our_module_global, int32_t our_instance);
216 int32_t calculate_max_start_pad(void);
218 /***** END of max_start_pad handling *****/
220 /***** SCHEDULING support */
222 /* If nfds_io is insufficient for your needs, set it to the required
223 number and return ERANGE. timeout is in milliseconds; if it is too
224 high then lower it. It starts at -1 (==infinite). */
225 /* Note that beforepoll_fn may NOT do anything which might change the
226 fds or timeouts wanted by other registered poll loop loopers.
227 Callers should make sure of this by not making any calls into other
228 modules from the beforepoll_fn; the easiest way to ensure this is
229 for beforepoll_fn to only retreive information and not take any
232 typedef int beforepoll_fn(void *st, struct pollfd *fds, int *nfds_io,
234 typedef void afterpoll_fn(void *st, struct pollfd *fds, int nfds);
235 /* If beforepoll_fn returned ERANGE, afterpoll_fn gets nfds==0.
236 afterpoll_fn never gets !!(fds[].revents & POLLNVAL) - such
237 a report is detected as a fatal error by the event loop. */
239 /* void BEFOREPOLL_WANT_FDS(int want);
240 * Expects: int *nfds_io;
241 * Can perform non-local exit.
242 * Checks whether there is space for want fds. If so, sets *nfds_io.
243 * If not, sets *nfds_io and returns. */
244 #define BEFOREPOLL_WANT_FDS(want) do{ \
245 if (*nfds_io<(want)) { *nfds_io=(want); return ERANGE; } \
249 /* Register interest in the main loop of the program. Before a call
250 to poll() your supplied beforepoll function will be called. After
251 the call to poll() the supplied afterpoll function will be called. */
252 struct poll_interest *register_for_poll(void *st, beforepoll_fn *before,
253 afterpoll_fn *after, cstring_t desc);
254 void deregister_for_poll(struct poll_interest *i);
256 /***** END of scheduling support */
258 /***** PROGRAM LIFETIME support */
260 /* The secnet program goes through a number of phases in its lifetime.
261 Module code may arrange to be called just as various phases are
264 Remember to update the table in util.c if changing the set of
269 PHASE_GETOPTS, /* Process command-line arguments */
270 PHASE_READCONFIG, /* Parse and process configuration file */
271 PHASE_SETUP, /* Process information in configuration */
272 PHASE_DAEMONIZE, /* Become a daemon (if necessary) */
273 PHASE_GETRESOURCES, /* Obtain all external resources */
274 PHASE_DROPPRIV, /* Last chance for privileged operations */
276 PHASE_SHUTDOWN, /* About to die; delete key material, etc. */
277 PHASE_CHILDPERSIST, /* Forked long-term child: close fds, etc. */
278 /* Keep this last: */
282 /* Each module should, in its CHILDPERSIST hooks, close all fds which
283 constitute ownership of important operating system resources, or
284 which are used for IPC with other processes who want to get the
285 usual disconnection effects if the main secnet process dies.
286 CHILDPERSIST hooks are not run if the child is going to exec;
287 so fds such as described above should be CLOEXEC too. */
289 typedef void hook_fn(void *self, uint32_t newphase);
290 bool_t add_hook(uint32_t phase, hook_fn *f, void *state);
291 bool_t remove_hook(uint32_t phase, hook_fn *f, void *state);
293 extern uint32_t current_phase;
294 extern void enter_phase(uint32_t new_phase);
296 void phase_hooks_init(void); /* for main() only */
297 void clear_phase_hooks(uint32_t phase); /* for afterfork() */
299 /* Some features (like netlink 'soft' routes) require that secnet
300 retain root privileges. They should indicate that here when
302 extern bool_t require_root_privileges;
303 extern cstring_t require_root_privileges_explanation;
305 /* Some modules may want to know whether secnet is going to drop
306 privilege, so that they know whether to do privsep. Call only
307 in phases SETUP and later. */
308 bool_t will_droppriv(void);
310 /***** END of program lifetime support *****/
312 /***** MODULE support *****/
314 /* Module initialisation function type - modules export one function of
315 this type which is called to initialise them. For dynamically loaded
316 modules it's called "secnet_module". */
317 typedef void init_module(dict_t *dict);
319 extern void init_builtin_modules(dict_t *dict);
321 extern init_module resolver_module;
322 extern init_module random_module;
323 extern init_module udp_module;
324 extern init_module polypath_module;
325 extern init_module util_module;
326 extern init_module site_module;
327 extern init_module transform_eax_module;
328 extern init_module transform_cbcmac_module;
329 extern init_module netlink_module;
330 extern init_module rsa_module;
331 extern init_module dh_module;
332 extern init_module md5_module;
333 extern init_module slip_module;
334 extern init_module tun_module;
335 extern init_module sha1_module;
336 extern init_module log_module;
338 /***** END of module support *****/
340 /***** CLOSURE TYPES and interface definitions *****/
343 #define CL_RESOLVER 1
344 #define CL_RANDOMSRC 2
345 #define CL_RSAPUBKEY 3
346 #define CL_RSAPRIVKEY 4
351 #define CL_TRANSFORM 9
355 #define CL_NETLINK 14
359 /* PURE closure requires no interface */
361 /* RESOLVER interface */
363 /* Answers to queries are delivered to a function of this
364 type. 'address' will be NULL if there was a problem with the query. It
365 will be freed once resolve_answer_fn returns. naddrs is the actual
366 size of the array at addrs; was_naddrs is the number of addresses
367 actually found in the DNS, which may be bigger if addrs is equal
368 to MAX_PEER_ADDRS (ie there were too many). */
369 typedef void resolve_answer_fn(void *st, const struct comm_addr *addrs,
370 int naddrs, int was_naddrs,
371 const char *name, const char *failwhy);
372 /* name is the same ptr as passed to request, so its lifetime must
374 typedef bool_t resolve_request_fn(void *st, cstring_t name,
375 int remoteport, struct comm_if *comm,
376 resolve_answer_fn *cb, void *cst);
379 resolve_request_fn *request;
382 /* RANDOMSRC interface */
384 /* Return some random data. Returns TRUE for success. */
385 typedef bool_t random_fn(void *st, int32_t bytes, uint8_t *buff);
393 /* RSAPUBKEY interface */
395 typedef bool_t rsa_checksig_fn(void *st, uint8_t *data, int32_t datalen,
396 cstring_t signature);
397 struct rsapubkey_if {
399 rsa_checksig_fn *check;
402 /* RSAPRIVKEY interface */
404 typedef string_t rsa_makesig_fn(void *st, uint8_t *data, int32_t datalen);
405 struct rsaprivkey_if {
407 rsa_makesig_fn *sign;
413 /* This struct is pure data; in particular comm's clients may
415 struct comm_if *comm;
417 int ix; /* see comment `Re comm_addr.ix' in udp.c */
420 /* Return True if the packet was processed, and shouldn't be passed to
421 any other potential receivers. (buf is freed iff True returned.) */
422 typedef bool_t comm_notify_fn(void *state, struct buffer_if *buf,
423 const struct comm_addr *source);
424 typedef void comm_request_notify_fn(void *commst, void *nst,
426 typedef void comm_release_notify_fn(void *commst, void *nst,
428 typedef bool_t comm_sendmsg_fn(void *commst, struct buffer_if *buf,
429 const struct comm_addr *dest);
430 /* Only returns false if (we know that) the local network
431 * environment is such that this address cannot work; transient
432 * or unknown/unexpected failures return true. */
433 typedef const char *comm_addr_to_string_fn(void *commst,
434 const struct comm_addr *ca);
435 /* Returned string is in a static buffer. */
438 comm_request_notify_fn *request_notify;
439 comm_release_notify_fn *release_notify;
440 comm_sendmsg_fn *sendmsg;
441 comm_addr_to_string_fn *addr_to_string;
444 bool_t iaddr_equal(const union iaddr *ia, const union iaddr *ib,
447 static inline const char *comm_addr_to_string(const struct comm_addr *ca)
449 return ca->comm->addr_to_string(ca->comm->st, ca);
452 static inline bool_t comm_addr_equal(const struct comm_addr *a,
453 const struct comm_addr *b)
455 return a->comm==b->comm && iaddr_equal(&a->ia,&b->ia,False);
460 #define LOG_MESSAGE_BUFLEN 1023
462 typedef void log_msg_fn(void *st, int class, const char *message, ...);
463 typedef void log_vmsg_fn(void *st, int class, const char *message,
467 log_vmsg_fn *vlogfn; /* printf format checking. Use [v]slilog instead */
468 char buff[LOG_MESSAGE_BUFLEN+1];
470 /* (convenience functions, defined in util.c) */
471 extern void slilog(struct log_if *lf, int class, const char *message, ...)
473 extern void vslilog(struct log_if *lf, int class, const char *message, va_list)
476 /* Versions which take (parts of) (multiple) messages, using \n to
477 * distinguish one message from another. */
478 extern void slilog_part(struct log_if *lf, int class, const char *message, ...)
480 extern void vslilog_part(struct log_if *lf, int class, const char *message,
481 va_list) FORMAT(printf,3,0);
485 /* Pretty much a placeholder; allows starting and stopping of processing,
487 typedef void site_control_fn(void *st, bool_t run);
488 typedef uint32_t site_status_fn(void *st);
491 site_control_fn *control;
492 site_status_fn *status;
495 /* TRANSFORM interface */
497 /* A reversable transformation. Transforms buffer in-place; may add
498 data to start or end. (Reverse transformations decrease
499 length, of course.) Transformations may be key-dependent, in which
500 case key material is passed in at initialisation time. They may
501 also depend on internal factors (eg. time) and keep internal
502 state. A struct transform_if only represents a particular type of
503 transformation; instances of the transformation (eg. with
504 particular key material) have a different C type. The same
505 secret key will be used in opposite directions between a pair of
506 secnets; one of these pairs will get direction==False, the other True. */
508 typedef struct transform_inst_if *transform_createinstance_fn(void *st);
509 typedef bool_t transform_setkey_fn(void *st, uint8_t *key, int32_t keylen,
511 typedef bool_t transform_valid_fn(void *st); /* 0: no key; 1: ok */
512 typedef void transform_delkey_fn(void *st);
513 typedef void transform_destroyinstance_fn(void *st);
516 * 1: for any other problem
517 * 2: message decrypted but sequence number was out of range
519 typedef uint32_t transform_apply_fn(void *st, struct buffer_if *buf,
520 const char **errmsg);
522 struct transform_inst_if {
524 transform_setkey_fn *setkey;
525 transform_valid_fn *valid;
526 transform_delkey_fn *delkey;
527 transform_apply_fn *forwards;
528 transform_apply_fn *reverse;
529 transform_destroyinstance_fn *destroy;
532 struct transform_if {
534 int capab_transformnum;
535 int32_t keylen; /* <<< INT_MAX */
536 transform_createinstance_fn *create;
539 /* NETLINK interface */
541 /* Used by netlink to deliver to site, and by site to deliver to
542 netlink. cid is the client identifier returned by
543 netlink_regnets_fn. If buf has size 0 then the function is just
544 being called for its site-effects (eg. making the site code attempt
545 to bring up a network link) */
546 typedef void netlink_deliver_fn(void *st, struct buffer_if *buf);
547 /* site code can tell netlink when outgoing packets will be dropped,
548 so netlink can generate appropriate ICMP and make routing decisions */
549 #define LINK_QUALITY_UNUSED 0 /* This link is unused, do not make this netlink */
550 #define LINK_QUALITY_DOWN 1 /* No chance of a packet being delivered right away*/
551 #define LINK_QUALITY_DOWN_STALE_ADDRESS 2 /* Link down, old address information */
552 #define LINK_QUALITY_DOWN_CURRENT_ADDRESS 3 /* Link down, current address information */
553 #define LINK_QUALITY_UP 4 /* Link active */
554 #define MAXIMUM_LINK_QUALITY 3
555 typedef void netlink_link_quality_fn(void *st, uint32_t quality);
556 typedef void netlink_register_fn(void *st, netlink_deliver_fn *deliver,
557 void *dst, uint32_t *localmtu_r /* NULL ok */);
558 typedef void netlink_output_config_fn(void *st, struct buffer_if *buf);
559 typedef bool_t netlink_check_config_fn(void *st, struct buffer_if *buf);
560 typedef void netlink_set_mtu_fn(void *st, int32_t new_mtu);
563 netlink_register_fn *reg;
564 netlink_deliver_fn *deliver;
565 netlink_link_quality_fn *set_quality;
566 netlink_set_mtu_fn *set_mtu;
571 /* Returns public key as a malloced hex string */
572 typedef string_t dh_makepublic_fn(void *st, uint8_t *secret,
574 /* Fills buffer (up to buflen) with shared secret */
575 typedef void dh_makeshared_fn(void *st, uint8_t *secret,
576 int32_t secretlen, cstring_t rempublic,
577 uint8_t *sharedsecret, int32_t buflen);
580 int32_t len; /* Approximate size of modulus in bytes */
581 int32_t ceil_len; /* Number of bytes just sufficient to contain modulus */
582 dh_makepublic_fn *makepublic;
583 dh_makeshared_fn *makeshared;
588 typedef void *hash_init_fn(void);
589 typedef void hash_update_fn(void *st, const void *buf, int32_t len);
590 typedef void hash_final_fn(void *st, uint8_t *digest);
592 int32_t len; /* Hash output length in bytes */
594 hash_update_fn *update;
595 hash_final_fn *final;
598 /* BUFFER interface */
602 cstring_t owner; /* Set to constant string */
603 uint32_t flags; /* How paranoid should we be? */
604 struct cloc loc; /* Where we were defined */
607 int32_t size; /* Size of buffer contents */
608 int32_t alloclen; /* Total length allocated at base */
611 /***** LOG functions *****/
613 #define M_DEBUG_CONFIG 0x001
614 #define M_DEBUG_PHASE 0x002
615 #define M_DEBUG 0x004
617 #define M_NOTICE 0x010
618 #define M_WARNING 0x020
620 #define M_SECURITY 0x080
621 #define M_FATAL 0x100
623 /* The fatal() family of functions require messages that do not end in '\n' */
624 extern NORETURN(fatal(const char *message, ...)) FORMAT(printf,1,2);
625 extern NORETURN(fatal_perror(const char *message, ...)) FORMAT(printf,1,2);
626 extern NORETURN(fatal_status(int status, const char *message, ...))
628 extern NORETURN(fatal_perror_status(int status, const char *message, ...))
631 /* Convenient nonfatal logging. Requires message that does not end in '\n'.
632 * If class contains M_FATAL, exits (after entering PHASE_SHUTDOWN).
633 * lg, errnoval and loc may sensibly be 0. desc must NOT be 0.
634 * lg_[v]perror save and restore errno. */
635 void lg_vperror(struct log_if *lg, const char *desc, struct cloc *loc,
636 int class, int errnoval, const char *fmt, va_list al)
638 void lg_perror(struct log_if *lg, const char *desc, struct cloc *loc,
639 int class, int errnoval, const char *fmt, ...)
641 void lg_exitstatus(struct log_if *lg, const char *desc, struct cloc *loc,
642 int class, int status, const char *progname);
644 /* The cfgfatal() family of functions require messages that end in '\n' */
645 extern NORETURN(cfgfatal(struct cloc loc, cstring_t facility,
646 const char *message, ...)) FORMAT(printf,3,4);
647 extern void cfgfile_postreadcheck(struct cloc loc, FILE *f);
648 extern NORETURN(vcfgfatal_maybefile(FILE *maybe_f, struct cloc loc,
649 cstring_t facility, const char *message,
652 extern NORETURN(cfgfatal_maybefile(FILE *maybe_f, struct cloc loc,
654 const char *message, ...))
657 extern void Message(uint32_t class, const char *message, ...)
659 extern void log_from_fd(int fd, cstring_t prefix, struct log_if *log);
661 /***** END of log functions *****/
663 #define STRING2(x) #x
664 #define STRING(x) STRING2(x)
666 #define FILLZERO(obj) (memset(&(obj),0,sizeof((obj))))
667 #define ARRAY_SIZE(ary) (sizeof((ary))/sizeof((ary)[0]))
670 * void COPY_OBJ( OBJECT& dst, const OBJECT& src);
671 * void COPY_ARRAY(OBJECT *dst, const OBJECT *src, INTEGER count);
672 * // Typesafe: we check that the type OBJECT is the same in both cases.
673 * // It is OK to use COPY_OBJ on an array object, provided it's
674 * // _actually_ the whole array object and not decayed into a
675 * // pointer (e.g. a formal parameter).
677 #define COPY_OBJ(dst,src) \
678 (&(dst)==&(src), memcpy(&(dst),&(src),sizeof((dst))))
679 #define COPY_ARRAY(dst,src,count) \
680 (&(dst)[0]==&(src)[0], memcpy((dst),(src),sizeof((dst)[0])*(count)))
682 #endif /* secnet_h */