1 /* site.c - manage communication with a remote network site */
4 * This file is part of secnet.
5 * See README for full list of copyright holders.
7 * secnet is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * secnet is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * version 3 along with secnet; if not, see
19 * https://www.gnu.org/licenses/gpl.html.
22 /* The 'site' code doesn't know anything about the structure of the
23 packets it's transmitting. In fact, under the new netlink
24 configuration scheme it doesn't need to know anything at all about
25 IP addresses, except how to contact its peer. This means it could
26 potentially be used to tunnel other protocols too (IPv6, IPX, plain
27 old Ethernet frames) if appropriate netlink code can be written
28 (and that ought not to be too hard, eg. using the TUN/TAP device to
29 pretend to be an Ethernet interface). */
31 /* At some point in the future the netlink code will be asked for
32 configuration information to go in the PING/PONG packets at the end
33 of the key exchange. */
40 #include <sys/socket.h>
44 #include "unaligned.h"
48 #define SETUP_BUFFER_LEN 2048
50 #define DEFAULT_KEY_LIFETIME (3600*1000) /* [ms] */
51 #define DEFAULT_KEY_RENEGOTIATE_GAP (5*60*1000) /* [ms] */
52 #define DEFAULT_SETUP_RETRIES 5
53 #define DEFAULT_SETUP_RETRY_INTERVAL (2*1000) /* [ms] */
54 #define DEFAULT_WAIT_TIME (20*1000) /* [ms] */
56 #define DEFAULT_MOBILE_KEY_LIFETIME (2*24*3600*1000) /* [ms] */
57 #define DEFAULT_MOBILE_KEY_RENEGOTIATE_GAP (12*3600*1000) /* [ms] */
58 #define DEFAULT_MOBILE_SETUP_RETRIES 30
59 #define DEFAULT_MOBILE_SETUP_RETRY_INTERVAL (1*1000) /* [ms] */
60 #define DEFAULT_MOBILE_WAIT_TIME (10*1000) /* [ms] */
62 #define DEFAULT_MOBILE_PEER_EXPIRY (2*60) /* [s] */
64 /* Each site can be in one of several possible states. */
67 SITE_STOP - nothing is allowed to happen; tunnel is down;
68 all session keys have been erased
69 -> SITE_RUN upon external instruction
70 SITE_RUN - site up, maybe with valid key
71 -> SITE_RESOLVE upon outgoing packet and no valid key
72 we start name resolution for the other end of the tunnel
73 -> SITE_SENTMSG2 upon valid incoming message 1 and suitable time
74 we send an appropriate message 2
75 SITE_RESOLVE - waiting for name resolution
76 -> SITE_SENTMSG1 upon successful resolution
77 we send an appropriate message 1
78 -> SITE_SENTMSG2 upon valid incoming message 1 (then abort resolution)
79 we abort resolution and
80 -> SITE_WAIT on timeout or resolution failure
82 -> SITE_SENTMSG2 upon valid incoming message 1 from higher priority end
83 -> SITE_SENTMSG3 upon valid incoming message 2
84 -> SITE_WAIT on timeout
86 -> SITE_SENTMSG4 upon valid incoming message 3
87 -> SITE_WAIT on timeout
89 -> SITE_SENTMSG5 upon valid incoming message 4
90 -> SITE_WAIT on timeout
92 -> SITE_RUN upon valid incoming message 5
93 -> SITE_WAIT on timeout
95 -> SITE_RUN upon valid incoming message 6
96 -> SITE_WAIT on timeout
97 SITE_WAIT - failed to establish key; do nothing for a while
98 -> SITE_RUN on timeout
103 #define SITE_RESOLVE 2
104 #define SITE_SENTMSG1 3
105 #define SITE_SENTMSG2 4
106 #define SITE_SENTMSG3 5
107 #define SITE_SENTMSG4 6
108 #define SITE_SENTMSG5 7
111 #define CASES_MSG3_KNOWN LABEL_MSG3: case LABEL_MSG3BIS
115 int32_t site_max_start_pad = 4*4;
117 static cstring_t state_name(uint32_t state)
120 case 0: return "STOP";
121 case 1: return "RUN";
122 case 2: return "RESOLVE";
123 case 3: return "SENTMSG1";
124 case 4: return "SENTMSG2";
125 case 5: return "SENTMSG3";
126 case 6: return "SENTMSG4";
127 case 7: return "SENTMSG5";
128 case 8: return "WAIT";
129 default: return "*bad state*";
135 #define LOG_UNEXPECTED 0x00000001
136 #define LOG_SETUP_INIT 0x00000002
137 #define LOG_SETUP_TIMEOUT 0x00000004
138 #define LOG_ACTIVATE_KEY 0x00000008
139 #define LOG_TIMEOUT_KEY 0x00000010
140 #define LOG_SEC 0x00000020
141 #define LOG_STATE 0x00000040
142 #define LOG_DROP 0x00000080
143 #define LOG_DUMP 0x00000100
144 #define LOG_ERROR 0x00000400
145 #define LOG_PEER_ADDRS 0x00000800
146 #define LOG_SIGKEYS 0x00001000
148 static struct flagstr log_event_table[]={
149 { "unexpected", LOG_UNEXPECTED },
150 { "setup-init", LOG_SETUP_INIT },
151 { "setup-timeout", LOG_SETUP_TIMEOUT },
152 { "activate-key", LOG_ACTIVATE_KEY },
153 { "timeout-key", LOG_TIMEOUT_KEY },
154 { "security", LOG_SEC },
155 { "state-change", LOG_STATE },
156 { "packet-drop", LOG_DROP },
157 { "dump-packets", LOG_DUMP },
158 { "errors", LOG_ERROR },
159 { "peer-addrs", LOG_PEER_ADDRS },
160 { "sigkeys", LOG_SIGKEYS },
161 { "default", LOG_SETUP_INIT|LOG_SETUP_TIMEOUT|
162 LOG_ACTIVATE_KEY|LOG_TIMEOUT_KEY|LOG_SEC|LOG_ERROR|LOG_SIGKEYS },
163 { "all", 0xffffffff },
168 /***** TRANSPORT PEERS declarations *****/
170 /* Details of "mobile peer" semantics:
172 - We use the same data structure for the different configurations,
173 but manage it with different algorithms.
175 - We record up to mobile_peers_max peer address/port numbers
176 ("peers") for key setup, and separately up to mobile_peers_max
179 - In general, we make a new set of addrs (see below) when we start
180 a new key exchange; the key setup addrs become the data transport
181 addrs when key setup complets.
183 If our peer is mobile:
185 - We send to all recent addresses of incoming packets, plus
186 initially all configured addresses (which we also expire).
188 - So, we record addrs of good incoming packets, as follows:
189 1. expire any peers last seen >120s ("mobile-peer-expiry") ago
190 2. add the peer of the just received packet to the applicable list
191 (possibly evicting the oldest entries to make room)
192 NB that we do not expire peers until an incoming packet arrives.
194 - If the peer has a configured address or name, we record them the
195 same way, but only as a result of our own initiation of key
196 setup. (We might evict some incoming packet addrs to make room.)
198 - The default number of addrs to keep is 3, or 4 if we have a
199 configured name or address. That's space for two configured
200 addresses (one IPv6 and one IPv4), plus two received addresses.
202 - Outgoing packets are sent to every recorded address in the
203 applicable list. Any unsupported[1] addresses are deleted from
204 the list right away. (This should only happen to configured
205 addresses, of course, but there is no need to check that.)
207 - When we successfully complete a key setup, we merge the key setup
208 peers into the data transfer peers.
210 [1] An unsupported address is one for whose AF we don't have a
211 socket (perhaps because we got EAFNOSUPPORT or some such) or for
212 which sendto gives ENETUNREACH.
214 If neither end is mobile:
216 - When peer initiated the key exchange, we use the incoming packet
219 - When we initiate the key exchange, we try configured addresses
220 until we get one which isn't unsupported then fixate on that.
222 - When we complete a key setup, we replace the data transport peers
223 with those from the key setup.
227 - We can't tell when local network setup changes so we can't cache
228 the unsupported addrs and completely remove the spurious calls to
229 sendto, but we can optimise things a bit by deprioritising addrs
230 which seem to be unsupported.
232 - Use only configured addresses. (Except, that if our peer
233 initiated a key exchange we use the incoming packet address until
234 our name resolution completes.)
236 - When we send a packet, try each address in turn; if addr
237 supported, put that address to the end of the list for future
238 packets, and go onto the next address.
240 - When we complete a key setup, we replace the data transport peers
241 with those from the key setup.
247 struct comm_addr addr;
251 /* configuration information */
252 /* runtime information */
254 transport_peer peers[MAX_PEER_ADDRS];
257 /* Basic operations on transport peer address sets */
258 static void transport_peers_clear(struct site *st, transport_peers *peers);
259 static int transport_peers_valid(transport_peers *peers);
260 static void transport_peers_copy(struct site *st, transport_peers *dst,
261 const transport_peers *src);
263 /* Record address of incoming setup packet; resp. data packet. */
264 static void transport_setup_msgok(struct site *st, const struct comm_addr *a);
265 static void transport_data_msgok(struct site *st, const struct comm_addr *a);
267 /* Initialise the setup addresses. Called before we send the first
268 * packet in a key exchange. If we are the initiator, as a result of
269 * resolve completing (or being determined not to be relevant) or an
270 * incoming PROD; if we are the responder, as a result of the MSG1. */
271 static bool_t transport_compute_setupinit_peers(struct site *st,
272 const struct comm_addr *configured_addrs /* 0 if none or not found */,
273 int n_configured_addrs /* 0 if none or not found */,
274 const struct comm_addr *incoming_packet_addr /* 0 if none */);
276 /* Called if we are the responder in a key setup, when the resolve
277 * completes. transport_compute_setupinit_peers will hvae been called
278 * earlier. If _complete is called, we are still doing the key setup
279 * (and we should use the new values for both the rest of the key
280 * setup and the ongoing data exchange); if _tardy is called, the key
281 * setup is done (either completed or not) and only the data peers are
283 static void transport_resolve_complete(struct site *st,
284 const struct comm_addr *addrs, int naddrs);
285 static void transport_resolve_complete_tardy(struct site *st,
286 const struct comm_addr *addrs, int naddrs);
288 static void transport_xmit(struct site *st, transport_peers *peers,
289 struct buffer_if *buf, bool_t candebug);
291 /***** END of transport peers declarations *****/
295 struct transform_inst_if *transform;
296 uint64_t key_timeout; /* End of life of current key */
297 uint32_t remote_session_id;
303 /* configuration information */
307 bool_t local_mobile, peer_mobile; /* Mobile client support */
308 int32_t transport_peers_max;
309 string_t tunname; /* localname<->remotename by default, used in logs */
310 cstring_t *addresses; /* DNS name or address(es) for bootstrapping, optional */
311 int remoteport; /* Port for bootstrapping, optional */
313 struct netlink_if *netlink;
314 struct comm_if **comms;
315 struct comm_clientinfo **commclientinfos;
317 struct resolver_if *resolver;
319 struct random_if *random;
320 struct privcache_if *privkeys;
321 struct sigprivkey_if *privkey_fixed;
322 struct transform_if **transforms;
326 uint32_t index; /* Index of this site */
327 uint32_t early_capabilities;
328 uint32_t local_capabilities;
329 int32_t setup_retries; /* How many times to send setup packets */
330 int32_t setup_retry_interval; /* Initial timeout for setup packets */
331 int32_t wait_timeout_mean; /* How long to wait if setup unsuccessful */
332 int32_t mobile_peer_expiry; /* How long to remember 2ary addresses */
333 int32_t key_lifetime; /* How long a key lasts once set up */
334 int32_t key_renegotiate_time; /* If we see traffic (or a keepalive)
335 after this time, initiate a new
338 bool_t our_name_later; /* our name > peer name */
341 /* runtime information */
343 uint64_t now; /* Most recently seen time */
344 bool_t allow_send_prod;
345 bool_t msg1_crossed_logged;
347 int resolving_n_results_all;
348 int resolving_n_results_stored;
349 struct comm_addr resolving_results[MAX_PEER_ADDRS];
350 const char *peerkeys_path;
351 struct peer_keyset *peerkeys_current, *peerkeys_kex;
353 /* The currently established session */
354 struct data_key current;
355 struct data_key auxiliary_key;
356 bool_t auxiliary_is_new;
357 uint64_t renegotiate_key_time; /* When we can negotiate a new key */
358 uint64_t auxiliary_renegotiate_key_time;
359 transport_peers peers; /* Current address(es) of peer for data traffic */
361 /* The current key setup protocol exchange. We can only be
362 involved in one of these at a time. There's a potential for
363 denial of service here (the attacker keeps sending a setup
364 packet; we keep trying to continue the exchange, and have to
365 timeout before we can listen for another setup packet); perhaps
366 we should keep a list of 'bad' sources for setup packets. */
367 uint32_t remote_capabilities;
368 uint16_t remote_adv_mtu;
369 struct transform_if *chosen_transform;
370 uint32_t setup_session_id;
371 transport_peers setup_peers;
372 uint8_t localN[NONCELEN]; /* Nonces for key exchange */
373 uint8_t remoteN[NONCELEN];
374 struct buffer_if buffer; /* Current outgoing key exchange packet */
375 struct buffer_if scratch;
376 int32_t retries; /* Number of retries remaining */
377 uint64_t timeout; /* Timeout for current state */
379 uint8_t *sharedsecret;
380 uint32_t sharedsecretlen, sharedsecretallocd;
381 struct transform_inst_if *new_transform; /* For key setup/verify */
384 static uint32_t event_log_priority(struct site *st, uint32_t event)
386 if (!(event&st->log_events))
389 case LOG_UNEXPECTED: return M_INFO;
390 case LOG_SETUP_INIT: return M_INFO;
391 case LOG_SETUP_TIMEOUT: return M_NOTICE;
392 case LOG_ACTIVATE_KEY: return M_INFO;
393 case LOG_TIMEOUT_KEY: return M_INFO;
394 case LOG_SEC: return M_SECURITY;
395 case LOG_STATE: return M_DEBUG;
396 case LOG_DROP: return M_DEBUG;
397 case LOG_DUMP: return M_DEBUG;
398 case LOG_ERROR: return M_ERR;
399 case LOG_PEER_ADDRS: return M_DEBUG;
400 case LOG_SIGKEYS: return M_INFO;
401 default: return M_ERR;
405 static uint32_t slog_start(struct site *st, uint32_t event)
407 uint32_t class=event_log_priority(st, event);
409 slilog_part(st->log,class,"%s: ",st->tunname);
414 static void vslog(struct site *st, uint32_t event, cstring_t msg, va_list ap)
416 static void vslog(struct site *st, uint32_t event, cstring_t msg, va_list ap)
420 class=slog_start(st,event);
422 vslilog_part(st->log,class,msg,ap);
423 slilog_part(st->log,class,"\n");
427 static void slog(struct site *st, uint32_t event, cstring_t msg, ...)
429 static void slog(struct site *st, uint32_t event, cstring_t msg, ...)
433 vslog(st,event,msg,ap);
437 static void logtimeout(struct site *st, const char *fmt, ...)
439 static void logtimeout(struct site *st, const char *fmt, ...)
441 uint32_t class=event_log_priority(st,LOG_SETUP_TIMEOUT);
448 slilog_part(st->log,class,"%s: ",st->tunname);
449 vslilog_part(st->log,class,fmt,ap);
453 for (i=0, delim=" (tried ";
454 i<st->setup_peers.npeers;
456 transport_peer *peer=&st->setup_peers.peers[i];
457 const char *s=comm_addr_to_string(&peer->addr);
458 slilog_part(st->log,class,"%s%s",delim,s);
461 slilog_part(st->log,class,")\n");
465 static void set_link_quality(struct site *st);
466 static void delete_keys(struct site *st, cstring_t reason, uint32_t loglevel);
467 static void delete_one_key(struct site *st, struct data_key *key,
468 const char *reason /* may be 0 meaning don't log*/,
469 const char *which /* ignored if !reasonn */,
470 uint32_t loglevel /* ignored if !reasonn */);
471 static bool_t initiate_key_setup(struct site *st, cstring_t reason,
472 const struct comm_addr *prod_hint);
473 static void enter_state_run(struct site *st);
474 static bool_t enter_state_resolve(struct site *st);
475 static void decrement_resolving_count(struct site *st, int by);
476 static bool_t enter_new_state(struct site *st,uint32_t next,
477 const struct msg *prompt
478 /* may be 0 for SENTMSG1 */);
479 static void enter_state_wait(struct site *st);
480 static void activate_new_key(struct site *st);
482 static bool_t is_transform_valid(struct transform_inst_if *transform)
484 return transform && transform->valid(transform->st);
487 static bool_t current_valid(struct site *st)
489 return is_transform_valid(st->current.transform);
492 #define DEFINE_CALL_TRANSFORM(fwdrev) \
493 static transform_apply_return \
494 call_transform_##fwdrev(struct site *st, \
495 struct transform_inst_if *transform, \
496 struct buffer_if *buf, \
497 const char **errmsg) \
499 if (!is_transform_valid(transform)) { \
500 *errmsg="transform not set up"; \
501 return transform_apply_err; \
503 return transform->fwdrev(transform->st,buf,errmsg); \
506 DEFINE_CALL_TRANSFORM(forwards)
507 DEFINE_CALL_TRANSFORM(reverse)
509 static void dispose_transform(struct transform_inst_if **transform_var)
511 struct transform_inst_if *transform=*transform_var;
513 transform->delkey(transform->st);
514 transform->destroy(transform->st);
519 #define CHECK_AVAIL(b,l) do { if ((b)->size<(l)) return False; } while(0)
520 #define CHECK_EMPTY(b) do { if ((b)->size!=0) return False; } while(0)
521 #define CHECK_TYPE(b,t) do { uint32_t type; \
522 CHECK_AVAIL((b),4); \
523 type=buf_unprepend_uint32((b)); \
524 if (type!=(t)) return False; } while(0)
526 static _Bool type_is_msg23(uint32_t type)
529 case LABEL_MSG2: case CASES_MSG3_KNOWN: return True;
530 default: return False;
533 static _Bool type_is_msg34(uint32_t type)
536 case CASES_MSG3_KNOWN: case LABEL_MSG4: return True;
537 default: return False;
544 struct buffer_if extrainfo;
551 struct parsedname remote;
552 struct parsedname local;
553 uint32_t remote_capabilities;
555 int capab_transformnum;
561 struct alg_msg_data sig;
562 int n_pubkeys_accepted_nom; /* may be > MAX_SIG_KEYS ! */
563 const struct sigkeyid *pubkeys_accepted[MAX_SIG_KEYS];
564 int signing_key_index;
567 static const struct sigkeyid keyid_zero;
569 static int32_t wait_timeout(struct site *st) {
570 int32_t t = st->wait_timeout_mean;
573 st->random->generate(st->random->st,sizeof(factor),&factor);
574 t += (t / 256) * factor;
579 static _Bool set_new_transform(struct site *st, char *pk)
583 /* Make room for the shared key */
584 st->sharedsecretlen=st->chosen_transform->keylen?:st->dh->ceil_len;
585 assert(st->sharedsecretlen);
586 if (st->sharedsecretlen > st->sharedsecretallocd) {
587 st->sharedsecretallocd=st->sharedsecretlen;
588 st->sharedsecret=safe_realloc_ary(st->sharedsecret,1,
589 st->sharedsecretallocd,
590 "site:sharedsecret");
593 /* Generate the shared key */
594 st->dh->makeshared(st->dh->st,st->dhsecret,st->dh->len,pk,
595 st->sharedsecret,st->sharedsecretlen);
597 /* Set up the transform */
598 struct transform_if *generator=st->chosen_transform;
599 struct transform_inst_if *generated=generator->create(generator->st);
600 ok = generated->setkey(generated->st,st->sharedsecret,
601 st->sharedsecretlen,st->our_name_later);
603 dispose_transform(&st->new_transform);
604 if (!ok) return False;
605 st->new_transform=generated;
607 slog(st,LOG_SETUP_INIT,"key exchange negotiated transform"
608 " %d (capabilities ours=%#"PRIx32" theirs=%#"PRIx32")",
609 st->chosen_transform->capab_bit,
610 st->local_capabilities, st->remote_capabilities);
615 int32_t lenpos, afternul;
617 static void append_string_xinfo_start(struct buffer_if *buf,
618 struct xinfoadd *xia,
620 /* Helps construct one of the names with additional info as found
621 * in MSG1..4. Call this function first, then append all the
622 * desired extra info (not including the nul byte) to the buffer,
623 * then call append_string_xinfo_done. */
625 xia->lenpos = buf->size;
626 buf_append_string(buf,str);
627 buf_append_uint8(buf,0);
628 xia->afternul = buf->size;
630 static void append_string_xinfo_done(struct buffer_if *buf,
631 struct xinfoadd *xia)
633 /* we just need to adjust the string length */
634 if (buf->size == xia->afternul) {
635 /* no extra info, strip the nul too */
636 buf_unappend_uint8(buf);
638 put_uint16(buf->start+xia->lenpos, buf->size-(xia->lenpos+2));
642 /* Build any of msg1 to msg4. msg5 and msg6 are built from the inside
643 out using a transform of config data supplied by netlink */
644 static bool_t generate_msg(struct site *st, uint32_t type, cstring_t what,
645 const struct msg *prompt
646 /* may be 0 for MSG1 */)
652 st->retries=st->setup_retries;
653 BUF_ALLOC(&st->buffer,what);
654 buffer_init(&st->buffer,0);
655 buf_append_uint32(&st->buffer,
656 (type==LABEL_MSG1?0:st->setup_session_id));
657 buf_append_uint32(&st->buffer,st->index);
658 buf_append_uint32(&st->buffer,type);
661 append_string_xinfo_start(&st->buffer,&xia,st->localname);
662 if ((st->local_capabilities & st->early_capabilities) ||
663 (type != LABEL_MSG1)) {
664 buf_append_uint32(&st->buffer,st->local_capabilities);
666 if (type_is_msg34(type)) {
667 buf_append_uint16(&st->buffer,st->mtu_target);
669 if (type_is_msg23(type)) {
670 buf_append_uint8(&st->buffer,st->peerkeys_kex->nkeys);
671 for (ki=0; ki<st->peerkeys_kex->nkeys; ki++) {
672 struct peer_pubkey *pk = &st->peerkeys_kex->keys[ki];
673 BUF_ADD_OBJ(append,&st->buffer,pk->id);
676 struct sigprivkey_if *privkey=0;
677 if (type_is_msg34(type)) {
678 assert(prompt->n_pubkeys_accepted_nom>0);
680 ki<prompt->n_pubkeys_accepted_nom && ki<MAX_SIG_KEYS;
682 const struct sigkeyid *kid=prompt->pubkeys_accepted[ki];
684 privkey=st->privkeys->lookup(st->privkeys->st,kid,st->log);
685 if (privkey) goto privkey_found;
687 if (sigkeyid_equal(&keyid_zero,kid)) {
688 privkey=st->privkey_fixed;
693 uint32_t class = slog_start(st,LOG_ERROR);
695 slilog_part(st->log,class,"no suitable private key, peer wanted");
697 ki<prompt->n_pubkeys_accepted_nom && ki<MAX_SIG_KEYS;
699 slilog_part(st->log,class, " " SIGKEYID_PR_FMT,
700 SIGKEYID_PR_VAL(prompt->pubkeys_accepted[ki]));
702 if (prompt->n_pubkeys_accepted_nom > MAX_SIG_KEYS)
703 slilog_part(st->log,class," +%d",
704 prompt->n_pubkeys_accepted_nom - MAX_SIG_KEYS);
705 slilog_part(st->log,class,"\n");
710 buf_append_uint8(&st->buffer,ki);
713 append_string_xinfo_done(&st->buffer,&xia);
715 buf_append_string(&st->buffer,st->remotename);
716 BUF_ADD_OBJ(append,&st->buffer,st->localN);
717 if (type==LABEL_MSG1) return True;
718 BUF_ADD_OBJ(append,&st->buffer,st->remoteN);
719 if (type==LABEL_MSG2) return True;
721 if (hacky_par_mid_failnow()) return False;
723 if (MSGMAJOR(type) == 3) do {
724 minor = MSGMINOR(type);
725 if (minor < 1) break;
726 buf_append_uint8(&st->buffer,st->chosen_transform->capab_bit);
729 dhpub=st->dh->makepublic(st->dh->st,st->dhsecret,st->dh->len);
730 buf_append_string(&st->buffer,dhpub);
733 bool_t ok=privkey->sign(privkey->st,
744 static bool_t unpick_name(struct buffer_if *msg, struct parsedname *nm)
747 nm->len=buf_unprepend_uint16(msg);
748 CHECK_AVAIL(msg,nm->len);
749 nm->name=buf_unprepend(msg,nm->len);
750 uint8_t *nul=memchr(nm->name,0,nm->len);
752 buffer_readonly_view(&nm->extrainfo,0,0);
754 buffer_readonly_view(&nm->extrainfo, nul+1, msg->start-(nul+1));
755 nm->len=nul-nm->name;
760 static bool_t unpick_msg(struct site *st, uint32_t type,
761 struct buffer_if *msg, struct msg *m)
765 m->n_pubkeys_accepted_nom=-1;
766 m->capab_transformnum=-1;
767 m->signing_key_index=-1;
768 m->hashstart=msg->start;
770 m->dest=buf_unprepend_uint32(msg);
772 m->source=buf_unprepend_uint32(msg);
773 CHECK_TYPE(msg,type);
774 if (!unpick_name(msg,&m->remote)) return False;
775 m->remote_capabilities=0;
777 if (m->remote.extrainfo.size) {
778 CHECK_AVAIL(&m->remote.extrainfo,4);
779 m->remote_capabilities=buf_unprepend_uint32(&m->remote.extrainfo);
781 if (type_is_msg34(type) && m->remote.extrainfo.size) {
782 CHECK_AVAIL(&m->remote.extrainfo,2);
783 m->remote_mtu=buf_unprepend_uint16(&m->remote.extrainfo);
785 if (type_is_msg23(type) && m->remote.extrainfo.size) {
786 m->n_pubkeys_accepted_nom = buf_unprepend_uint8(&m->remote.extrainfo);
787 if (!m->n_pubkeys_accepted_nom) return False;
788 for (int ki_nom=0; ki_nom<m->n_pubkeys_accepted_nom; ki_nom++) {
789 CHECK_AVAIL(&m->remote.extrainfo,KEYIDSZ);
790 struct sigkeyid *kid = buf_unprepend(&m->remote.extrainfo,KEYIDSZ);
791 if (ki_nom<MAX_SIG_KEYS) m->pubkeys_accepted[ki_nom] = kid;
794 m->n_pubkeys_accepted_nom = 1;
795 m->pubkeys_accepted[0] = &keyid_zero;
797 if (type_is_msg34(type) && m->remote.extrainfo.size) {
798 m->signing_key_index=buf_unprepend_uint8(&m->remote.extrainfo);
800 m->signing_key_index=0;
802 if (!unpick_name(msg,&m->local)) return False;
803 if (type==LABEL_PROD) {
807 CHECK_AVAIL(msg,NONCELEN);
808 m->nR=buf_unprepend(msg,NONCELEN);
809 if (type==LABEL_MSG1) {
813 CHECK_AVAIL(msg,NONCELEN);
814 m->nL=buf_unprepend(msg,NONCELEN);
815 if (type==LABEL_MSG2) {
819 if (MSGMAJOR(type) == 3) do {
820 minor = MSGMINOR(type);
821 #define MAYBE_READ_CAP(minminor, kind, dflt) do { \
822 if (minor < (minminor)) \
823 m->capab_##kind##num = (dflt); \
825 CHECK_AVAIL(msg, 1); \
826 m->capab_##kind##num = buf_unprepend_uint8(msg); \
829 MAYBE_READ_CAP(1, transform, CAPAB_BIT_ANCIENTTRANSFORM);
830 #undef MAYBE_READ_CAP
833 m->pklen=buf_unprepend_uint16(msg);
834 CHECK_AVAIL(msg,m->pklen);
835 m->pk=buf_unprepend(msg,m->pklen);
836 m->hashlen=msg->start-m->hashstart;
838 if (m->signing_key_index < 0 ||
839 m->signing_key_index >= st->peerkeys_kex->nkeys) {
842 struct sigpubkey_if *pubkey=
843 st->peerkeys_kex->keys[m->signing_key_index].pubkey;
844 if (!pubkey->unpick(pubkey->st,msg,&m->sig)) {
853 static bool_t name_matches(const struct parsedname *nm, const char *expected)
855 int expected_len=strlen(expected);
857 nm->len == expected_len &&
858 !memcmp(nm->name, expected, expected_len);
861 static bool_t check_msg(struct site *st, uint32_t type, struct msg *m,
864 if (type==LABEL_MSG1) return True;
866 /* Check that the site names and our nonce have been sent
867 back correctly, and then store our peer's nonce. */
868 if (!name_matches(&m->remote,st->remotename)) {
869 *error="wrong remote site name";
872 if (!name_matches(&m->local,st->localname)) {
873 *error="wrong local site name";
876 if (memcmp(m->nL,st->localN,NONCELEN)!=0) {
877 *error="wrong locally-generated nonce";
880 if (type==LABEL_MSG2) return True;
881 if (!consttime_memeq(m->nR,st->remoteN,NONCELEN)) {
882 *error="wrong remotely-generated nonce";
885 /* MSG3 has complicated rules about capabilities, which are
886 * handled in process_msg3. */
887 if (MSGMAJOR(type) == 3) return True;
888 if (m->remote_capabilities!=st->remote_capabilities) {
889 *error="remote capabilities changed";
892 if (type==LABEL_MSG4) return True;
893 *error="unknown message type";
897 static bool_t kex_init(struct site *st)
899 keyset_dispose(&st->peerkeys_kex);
900 if (!st->peerkeys_current) {
901 slog(st,LOG_SETUP_INIT,"no peer public keys, abandoning key setup");
904 st->peerkeys_kex = keyset_dup(st->peerkeys_current);
905 st->random->generate(st->random->st,NONCELEN,st->localN);
909 static bool_t generate_msg1(struct site *st, const struct msg *prompt_maybe_0)
912 generate_msg(st,LABEL_MSG1,"site:MSG1",prompt_maybe_0);
915 static bool_t process_msg1(struct site *st, struct buffer_if *msg1,
916 const struct comm_addr *src,
919 /* We've already determined we're in an appropriate state to
920 process an incoming MSG1, and that the MSG1 has correct values
923 st->setup_session_id=m->source;
924 st->remote_capabilities=m->remote_capabilities;
925 memcpy(st->remoteN,m->nR,NONCELEN);
929 static bool_t generate_msg2(struct site *st,
930 const struct msg *prompt_may_be_null)
933 generate_msg(st,LABEL_MSG2,"site:MSG2",prompt_may_be_null);
936 static bool_t process_msg2(struct site *st, struct buffer_if *msg2,
937 const struct comm_addr *src,
938 struct msg *m /* returned */)
942 if (!unpick_msg(st,LABEL_MSG2,msg2,m)) return False;
943 if (!check_msg(st,LABEL_MSG2,m,&err)) {
944 slog(st,LOG_SEC,"msg2: %s",err);
947 st->setup_session_id=m->source;
948 st->remote_capabilities=m->remote_capabilities;
950 /* Select the transform to use */
952 uint32_t remote_crypto_caps = st->remote_capabilities & CAPAB_TRANSFORM_MASK;
953 if (!remote_crypto_caps)
954 /* old secnets only had this one transform */
955 remote_crypto_caps = 1UL << CAPAB_BIT_ANCIENTTRANSFORM;
957 #define CHOOSE_CRYPTO(kind, whats) do { \
958 struct kind##_if *iface; \
959 uint32_t bit, ours = 0; \
961 for (i= 0; i < st->n##kind##s; i++) { \
962 iface=st->kind##s[i]; \
963 bit = 1UL << iface->capab_bit; \
964 if (bit & remote_crypto_caps) goto kind##_found; \
967 slog(st,LOG_ERROR,"no " whats " in common" \
968 " (us %#"PRIx32"; them: %#"PRIx32")", \
969 st->local_capabilities & ours, remote_crypto_caps); \
972 st->chosen_##kind = iface; \
975 CHOOSE_CRYPTO(transform, "transforms");
979 memcpy(st->remoteN,m->nR,NONCELEN);
983 static bool_t generate_msg3(struct site *st, const struct msg *prompt)
985 /* Now we have our nonce and their nonce. Think of a secret key,
986 and create message number 3. */
987 st->random->generate(st->random->st,st->dh->len,st->dhsecret);
988 return generate_msg(st,
989 (st->remote_capabilities & CAPAB_TRANSFORM_MASK)
995 static bool_t process_msg3_msg4(struct site *st, struct msg *m)
997 /* Check signature and store g^x mod m */
1000 if (m->signing_key_index >= 0) {
1001 if (m->signing_key_index >= st->peerkeys_kex->nkeys)
1003 ki=m->signing_key_index;
1005 for (ki=0; ki<st->peerkeys_kex->nkeys; ki++)
1006 if (sigkeyid_equal(&keyid_zero,&st->peerkeys_kex->keys[ki].id))
1010 "peer signed with keyid zero, which we do not accept");
1014 struct sigpubkey_if *pubkey=st->peerkeys_kex->keys[ki].pubkey;
1016 if (!pubkey->check(pubkey->st,
1017 m->hashstart,m->hashlen,
1019 slog(st,LOG_SEC,"msg3/msg4 signature failed check!");
1023 st->remote_adv_mtu=m->remote_mtu;
1028 static bool_t process_msg3(struct site *st, struct buffer_if *msg3,
1029 const struct comm_addr *src, uint32_t msgtype,
1030 struct msg *m /* returned */)
1035 case CASES_MSG3_KNOWN: break;
1039 if (!unpick_msg(st,msgtype,msg3,m)) return False;
1040 if (!check_msg(st,msgtype,m,&err)) {
1041 slog(st,LOG_SEC,"msg3: %s",err);
1044 uint32_t capab_adv_late = m->remote_capabilities
1045 & ~st->remote_capabilities & st->early_capabilities;
1046 if (capab_adv_late) {
1047 slog(st,LOG_SEC,"msg3 impermissibly adds early capability flag(s)"
1048 " %#"PRIx32" (was %#"PRIx32", now %#"PRIx32")",
1049 capab_adv_late, st->remote_capabilities, m->remote_capabilities);
1053 #define CHOSE_CRYPTO(kind, what) do { \
1054 struct kind##_if *iface; \
1056 for (i=0; i<st->n##kind##s; i++) { \
1057 iface=st->kind##s[i]; \
1058 if (iface->capab_bit == m->capab_##kind##num) \
1059 goto kind##_found; \
1061 slog(st,LOG_SEC,"peer chose unknown-to-us " what " %d!", \
1062 m->capab_##kind##num); \
1065 st->chosen_##kind=iface; \
1068 CHOSE_CRYPTO(transform, "transform");
1072 if (!process_msg3_msg4(st,m))
1075 /* Update our idea of the remote site's capabilities, now that we've
1076 * verified that its message was authentic.
1078 * Our previous idea of the remote site's capabilities came from the
1079 * unauthenticated MSG1. We've already checked that this new message
1080 * doesn't change any of the bits we relied upon in the past, but it may
1081 * also have set additional capability bits. We simply throw those away
1082 * now, and use the authentic capabilities from this MSG3. */
1083 st->remote_capabilities=m->remote_capabilities;
1085 /* Terminate their DH public key with a '0' */
1087 /* Invent our DH secret key */
1088 st->random->generate(st->random->st,st->dh->len,st->dhsecret);
1090 /* Generate the shared key and set up the transform */
1091 if (!set_new_transform(st,m->pk)) return False;
1096 static bool_t generate_msg4(struct site *st, const struct msg *prompt)
1098 /* We have both nonces, their public key and our private key. Generate
1099 our public key, sign it and send it to them. */
1100 return generate_msg(st,LABEL_MSG4,"site:MSG4",prompt);
1103 static bool_t process_msg4(struct site *st, struct buffer_if *msg4,
1104 const struct comm_addr *src,
1105 struct msg *m /* returned */)
1109 if (!unpick_msg(st,LABEL_MSG4,msg4,m)) return False;
1110 if (!check_msg(st,LABEL_MSG4,m,&err)) {
1111 slog(st,LOG_SEC,"msg4: %s",err);
1115 if (!process_msg3_msg4(st,m))
1118 /* Terminate their DH public key with a '0' */
1121 /* Generate the shared key and set up the transform */
1122 if (!set_new_transform(st,m->pk)) return False;
1133 static bool_t unpick_msg0(struct site *st, struct buffer_if *msg0,
1136 CHECK_AVAIL(msg0,4);
1137 m->dest=buf_unprepend_uint32(msg0);
1138 CHECK_AVAIL(msg0,4);
1139 m->source=buf_unprepend_uint32(msg0);
1140 CHECK_AVAIL(msg0,4);
1141 m->type=buf_unprepend_uint32(msg0);
1143 /* Leaves transformed part of buffer untouched */
1146 static bool_t generate_msg5(struct site *st, const struct msg *prompt)
1148 cstring_t transform_err;
1150 BUF_ALLOC(&st->buffer,"site:MSG5");
1151 /* We are going to add four words to the message */
1152 buffer_init(&st->buffer,calculate_max_start_pad());
1153 /* Give the netlink code an opportunity to put its own stuff in the
1154 message (configuration information, etc.) */
1155 buf_prepend_uint32(&st->buffer,LABEL_MSG5);
1156 if (call_transform_forwards(st,st->new_transform,
1157 &st->buffer,&transform_err))
1159 buf_prepend_uint32(&st->buffer,LABEL_MSG5);
1160 buf_prepend_uint32(&st->buffer,st->index);
1161 buf_prepend_uint32(&st->buffer,st->setup_session_id);
1163 st->retries=st->setup_retries;
1167 static bool_t process_msg5(struct site *st, struct buffer_if *msg5,
1168 const struct comm_addr *src,
1169 struct transform_inst_if *transform)
1172 cstring_t transform_err;
1174 if (!unpick_msg0(st,msg5,&m)) return False;
1176 if (call_transform_reverse(st,transform,msg5,&transform_err)) {
1177 /* There's a problem */
1178 slog(st,LOG_SEC,"process_msg5: transform: %s",transform_err);
1181 /* Buffer should now contain untransformed PING packet data */
1182 CHECK_AVAIL(msg5,4);
1183 if (buf_unprepend_uint32(msg5)!=LABEL_MSG5) {
1184 slog(st,LOG_SEC,"MSG5/PING packet contained wrong label");
1187 /* Older versions of secnet used to write some config data here
1188 * which we ignore. So we don't CHECK_EMPTY */
1192 static void create_msg6(struct site *st, struct transform_inst_if *transform,
1193 uint32_t session_id)
1195 cstring_t transform_err;
1197 BUF_ALLOC(&st->buffer,"site:MSG6");
1198 /* We are going to add four words to the message */
1199 buffer_init(&st->buffer,calculate_max_start_pad());
1200 /* Give the netlink code an opportunity to put its own stuff in the
1201 message (configuration information, etc.) */
1202 buf_prepend_uint32(&st->buffer,LABEL_MSG6);
1203 transform_apply_return problem =
1204 call_transform_forwards(st,transform,
1205 &st->buffer,&transform_err);
1207 buf_prepend_uint32(&st->buffer,LABEL_MSG6);
1208 buf_prepend_uint32(&st->buffer,st->index);
1209 buf_prepend_uint32(&st->buffer,session_id);
1212 static bool_t generate_msg6(struct site *st, const struct msg *prompt)
1214 if (!is_transform_valid(st->new_transform))
1216 create_msg6(st,st->new_transform,st->setup_session_id);
1217 st->retries=1; /* Peer will retransmit MSG5 if this packet gets lost */
1221 static bool_t process_msg6(struct site *st, struct buffer_if *msg6,
1222 const struct comm_addr *src)
1225 cstring_t transform_err;
1227 if (!unpick_msg0(st,msg6,&m)) return False;
1229 if (call_transform_reverse(st,st->new_transform,msg6,&transform_err)) {
1230 /* There's a problem */
1231 slog(st,LOG_SEC,"process_msg6: transform: %s",transform_err);
1234 /* Buffer should now contain untransformed PING packet data */
1235 CHECK_AVAIL(msg6,4);
1236 if (buf_unprepend_uint32(msg6)!=LABEL_MSG6) {
1237 slog(st,LOG_SEC,"MSG6/PONG packet contained invalid data");
1240 /* Older versions of secnet used to write some config data here
1241 * which we ignore. So we don't CHECK_EMPTY */
1245 static transform_apply_return
1246 decrypt_msg0(struct site *st, struct buffer_if *msg0,
1247 const struct comm_addr *src)
1249 cstring_t transform_err, auxkey_err, newkey_err="n/a";
1251 transform_apply_return problem;
1253 if (!unpick_msg0(st,msg0,&m)) return False;
1255 /* Keep a copy so we can try decrypting it with multiple keys */
1256 buffer_copy(&st->scratch, msg0);
1258 problem = call_transform_reverse(st,st->current.transform,
1259 msg0,&transform_err);
1261 if (!st->auxiliary_is_new)
1262 delete_one_key(st,&st->auxiliary_key,
1263 "peer has used new key","auxiliary key",LOG_SEC);
1266 if (transform_apply_return_badseq(problem))
1269 buffer_copy(msg0, &st->scratch);
1270 problem = call_transform_reverse(st,st->auxiliary_key.transform,
1273 slog(st,LOG_DROP,"processing packet which uses auxiliary key");
1274 if (st->auxiliary_is_new) {
1275 /* We previously timed out in state SENTMSG5 but it turns
1276 * out that our peer did in fact get our MSG5 and is
1277 * using the new key. So we should switch to it too. */
1278 /* This is a bit like activate_new_key. */
1281 st->current=st->auxiliary_key;
1282 st->auxiliary_key=t;
1284 delete_one_key(st,&st->auxiliary_key,"peer has used new key",
1285 "previous key",LOG_SEC);
1286 st->auxiliary_is_new=0;
1287 st->renegotiate_key_time=st->auxiliary_renegotiate_key_time;
1291 if (transform_apply_return_badseq(problem))
1294 if (st->state==SITE_SENTMSG5) {
1295 buffer_copy(msg0, &st->scratch);
1296 problem = call_transform_reverse(st,st->new_transform,
1299 /* It looks like we didn't get the peer's MSG6 */
1300 /* This is like a cut-down enter_new_state(SITE_RUN) */
1301 slog(st,LOG_STATE,"will enter state RUN (MSG0 with new key)");
1302 BUF_FREE(&st->buffer);
1304 activate_new_key(st);
1305 return 0; /* do process the data in this packet */
1307 if (transform_apply_return_badseq(problem))
1311 slog(st,LOG_SEC,"transform: %s (aux: %s, new: %s)",
1312 transform_err,auxkey_err,newkey_err);
1313 initiate_key_setup(st,"incoming message would not decrypt",0);
1314 send_nak(src,m.dest,m.source,m.type,msg0,"message would not decrypt");
1319 slog(st,LOG_DROP,"transform: %s (bad seq.)",transform_err);
1324 static bool_t process_msg0(struct site *st, struct buffer_if *msg0,
1325 const struct comm_addr *src)
1328 transform_apply_return problem;
1330 problem = decrypt_msg0(st,msg0,src);
1331 if (problem==transform_apply_seqdupe) {
1332 /* We recently received another copy of this packet, maybe due
1333 * to polypath. That's not a problem; indeed, for the
1334 * purposes of transport address management it is a success.
1335 * But we don't want to process the packet. */
1336 transport_data_msgok(st,src);
1342 CHECK_AVAIL(msg0,4);
1343 type=buf_unprepend_uint32(msg0);
1346 /* We must forget about the current session. */
1347 delete_keys(st,"request from peer",LOG_SEC);
1348 /* probably, the peer is shutting down, and this is going to fail,
1349 * but we need to be trying to bring the link up again */
1351 initiate_key_setup(st,"peer requested key teardown",0);
1354 /* Deliver to netlink layer */
1355 st->netlink->deliver(st->netlink->st,msg0);
1356 transport_data_msgok(st,src);
1357 /* See whether we should start negotiating a new key */
1358 if (st->now > st->renegotiate_key_time)
1359 initiate_key_setup(st,"incoming packet in renegotiation window",0);
1362 slog(st,LOG_SEC,"incoming encrypted message of type %08x "
1369 static void dump_packet(struct site *st, struct buffer_if *buf,
1370 const struct comm_addr *addr, bool_t incoming,
1373 uint32_t dest=get_uint32(buf->start);
1374 uint32_t source=get_uint32(buf->start+4);
1375 uint32_t msgtype=get_uint32(buf->start+8);
1377 if (st->log_events & LOG_DUMP)
1378 slilog(st->log,M_DEBUG,"%s: %s: %08x<-%08x: %08x: %s%s",
1379 st->tunname,incoming?"incoming":"outgoing",
1380 dest,source,msgtype,comm_addr_to_string(addr),
1384 static bool_t comm_addr_sendmsg(struct site *st,
1385 const struct comm_addr *dest,
1386 struct buffer_if *buf)
1389 struct comm_clientinfo *commclientinfo = 0;
1391 for (i=0; i < st->ncomms; i++) {
1392 if (st->comms[i] == dest->comm) {
1393 commclientinfo = st->commclientinfos[i];
1397 return dest->comm->sendmsg(dest->comm->st, buf, dest, commclientinfo);
1400 static uint32_t site_status(void *st)
1405 static bool_t send_msg(struct site *st)
1407 if (st->retries>0) {
1408 transport_xmit(st, &st->setup_peers, &st->buffer, True);
1409 st->timeout=st->now+st->setup_retry_interval;
1412 } else if (st->state==SITE_SENTMSG5) {
1413 logtimeout(st,"timed out sending MSG5, stashing new key");
1414 /* We stash the key we have produced, in case it turns out that
1415 * our peer did see our MSG5 after all and starts using it. */
1416 /* This is a bit like some of activate_new_key */
1417 struct transform_inst_if *t;
1418 t=st->auxiliary_key.transform;
1419 st->auxiliary_key.transform=st->new_transform;
1420 st->new_transform=t;
1421 dispose_transform(&st->new_transform);
1423 st->auxiliary_is_new=1;
1424 st->auxiliary_key.key_timeout=st->now+st->key_lifetime;
1425 st->auxiliary_renegotiate_key_time=st->now+st->key_renegotiate_time;
1426 st->auxiliary_key.remote_session_id=st->setup_session_id;
1428 enter_state_wait(st);
1431 logtimeout(st,"timed out sending key setup packet "
1432 "(in state %s)",state_name(st->state));
1433 enter_state_wait(st);
1438 static void site_resolve_callback(void *sst, const struct comm_addr *addrs,
1439 int stored_naddrs, int all_naddrs,
1440 const char *address, const char *failwhy)
1442 struct site *st=sst;
1444 if (!stored_naddrs) {
1445 slog(st,LOG_ERROR,"resolution of %s failed: %s",address,failwhy);
1447 slog(st,LOG_PEER_ADDRS,"resolution of %s completed, %d addrs, eg: %s",
1448 address, all_naddrs, comm_addr_to_string(&addrs[0]));;
1450 int space=st->transport_peers_max-st->resolving_n_results_stored;
1451 int n_tocopy=MIN(stored_naddrs,space);
1452 COPY_ARRAY(st->resolving_results + st->resolving_n_results_stored,
1455 st->resolving_n_results_stored += n_tocopy;
1456 st->resolving_n_results_all += all_naddrs;
1459 decrement_resolving_count(st,1);
1462 static void decrement_resolving_count(struct site *st, int by)
1464 assert(st->resolving_count>0);
1465 st->resolving_count-=by;
1467 if (st->resolving_count)
1470 /* OK, we are done with them all. Handle combined results. */
1472 const struct comm_addr *addrs=st->resolving_results;
1473 int naddrs=st->resolving_n_results_stored;
1474 assert(naddrs<=st->transport_peers_max);
1477 if (naddrs != st->resolving_n_results_all) {
1478 slog(st,LOG_SETUP_INIT,"resolution of supplied addresses/names"
1479 " yielded too many results (%d > %d), some ignored",
1480 st->resolving_n_results_all, naddrs);
1482 slog(st,LOG_STATE,"resolution completed, %d addrs, eg: %s",
1483 naddrs, iaddr_to_string(&addrs[0].ia));;
1486 switch (st->state) {
1488 if (transport_compute_setupinit_peers(st,addrs,naddrs,0)) {
1489 enter_new_state(st,SITE_SENTMSG1,0);
1491 /* Can't figure out who to try to to talk to */
1492 slog(st,LOG_SETUP_INIT,
1493 "key exchange failed: cannot find peer address");
1494 enter_state_run(st);
1497 case SITE_SENTMSG1: case SITE_SENTMSG2:
1498 case SITE_SENTMSG3: case SITE_SENTMSG4:
1501 /* We start using the address immediately for data too.
1502 * It's best to store it in st->peers now because we might
1503 * go via SENTMSG5, WAIT, and a MSG0, straight into using
1504 * the new key (without updating the data peer addrs). */
1505 transport_resolve_complete(st,addrs,naddrs);
1506 } else if (st->local_mobile) {
1507 /* We can't let this rest because we may have a peer
1508 * address which will break in the future. */
1509 slog(st,LOG_SETUP_INIT,"resolution failed: "
1510 "abandoning key exchange");
1511 enter_state_wait(st);
1513 slog(st,LOG_SETUP_INIT,"resolution failed: "
1514 " continuing to use source address of peer's packets"
1515 " for key exchange and ultimately data");
1520 slog(st,LOG_SETUP_INIT,"resolution completed tardily,"
1521 " updating peer address(es)");
1522 transport_resolve_complete_tardy(st,addrs,naddrs);
1523 } else if (st->local_mobile) {
1524 /* Not very good. We should queue (another) renegotiation
1525 * so that we can update the peer address. */
1526 st->key_renegotiate_time=st->now+wait_timeout(st);
1528 slog(st,LOG_SETUP_INIT,"resolution failed: "
1529 " continuing to use source address of peer's packets");
1539 static bool_t initiate_key_setup(struct site *st, cstring_t reason,
1540 const struct comm_addr *prod_hint)
1542 /* Reentrancy hazard: can call enter_new_state/enter_state_* */
1543 if (st->state!=SITE_RUN) return False;
1544 slog(st,LOG_SETUP_INIT,"initiating key exchange (%s)",reason);
1545 if (st->addresses) {
1546 slog(st,LOG_SETUP_INIT,"resolving peer address(es)");
1547 return enter_state_resolve(st);
1548 } else if (transport_compute_setupinit_peers(st,0,0,prod_hint)) {
1549 return enter_new_state(st,SITE_SENTMSG1,0);
1551 slog(st,LOG_SETUP_INIT,"key exchange failed: no address for peer");
1555 static void activate_new_key(struct site *st)
1557 struct transform_inst_if *t;
1559 /* We have three transform instances, which we swap between old,
1561 t=st->auxiliary_key.transform;
1562 st->auxiliary_key.transform=st->current.transform;
1563 st->current.transform=st->new_transform;
1564 st->new_transform=t;
1565 dispose_transform(&st->new_transform);
1568 st->auxiliary_is_new=0;
1569 st->auxiliary_key.key_timeout=st->current.key_timeout;
1570 st->current.key_timeout=st->now+st->key_lifetime;
1571 st->renegotiate_key_time=st->now+st->key_renegotiate_time;
1572 transport_peers_copy(st,&st->peers,&st->setup_peers);
1573 st->current.remote_session_id=st->setup_session_id;
1575 /* Compute the inter-site MTU. This is min( our_mtu, their_mtu ).
1576 * But their mtu be unspecified, in which case we just use ours. */
1577 uint32_t intersite_mtu=
1578 MIN(st->mtu_target, st->remote_adv_mtu ?: ~(uint32_t)0);
1579 st->netlink->set_mtu(st->netlink->st,intersite_mtu);
1581 slog(st,LOG_ACTIVATE_KEY,"new key activated"
1582 " (mtu ours=%"PRId32" theirs=%"PRId32" intersite=%"PRId32")",
1583 st->mtu_target, st->remote_adv_mtu, intersite_mtu);
1584 enter_state_run(st);
1587 static void delete_one_key(struct site *st, struct data_key *key,
1588 cstring_t reason, cstring_t which, uint32_t loglevel)
1590 if (!is_transform_valid(key->transform)) return;
1591 if (reason) slog(st,loglevel,"%s deleted (%s)",which,reason);
1592 dispose_transform(&key->transform);
1596 static void delete_keys(struct site *st, cstring_t reason, uint32_t loglevel)
1598 if (current_valid(st)) {
1599 slog(st,loglevel,"session closed (%s)",reason);
1601 delete_one_key(st,&st->current,0,0,0);
1602 set_link_quality(st);
1604 delete_one_key(st,&st->auxiliary_key,0,0,0);
1607 static void state_assert(struct site *st, bool_t ok)
1609 if (!ok) fatal("site:state_assert");
1612 static void enter_state_stop(struct site *st)
1614 st->state=SITE_STOP;
1616 delete_keys(st,"entering state STOP",LOG_TIMEOUT_KEY);
1617 dispose_transform(&st->new_transform);
1620 static void set_link_quality(struct site *st)
1623 if (current_valid(st))
1624 quality=LINK_QUALITY_UP;
1625 else if (st->state==SITE_WAIT || st->state==SITE_STOP)
1626 quality=LINK_QUALITY_DOWN;
1627 else if (st->addresses)
1628 quality=LINK_QUALITY_DOWN_CURRENT_ADDRESS;
1629 else if (transport_peers_valid(&st->peers))
1630 quality=LINK_QUALITY_DOWN_STALE_ADDRESS;
1632 quality=LINK_QUALITY_DOWN;
1634 st->netlink->set_quality(st->netlink->st,quality);
1637 static void enter_state_run(struct site *st)
1639 slog(st,LOG_STATE,"entering state RUN%s",
1640 current_valid(st) ? " (keyed)" : " (unkeyed)");
1644 st->setup_session_id=0;
1645 transport_peers_clear(st,&st->setup_peers);
1646 keyset_dispose(&st->peerkeys_kex);
1647 FILLZERO(st->localN);
1648 FILLZERO(st->remoteN);
1649 dispose_transform(&st->new_transform);
1650 memset(st->dhsecret,0,st->dh->len);
1651 if (st->sharedsecret) memset(st->sharedsecret,0,st->sharedsecretlen);
1652 set_link_quality(st);
1654 if (st->keepalive && !current_valid(st))
1655 initiate_key_setup(st, "keepalive", 0);
1658 static bool_t ensure_resolving(struct site *st)
1660 /* Reentrancy hazard: may call site_resolve_callback and hence
1661 * enter_new_state, enter_state_* and generate_msg*. */
1662 if (st->resolving_count)
1665 assert(st->addresses);
1667 /* resolver->request might reentrantly call site_resolve_callback
1668 * which will decrement st->resolving, so we need to increment it
1669 * twice beforehand to prevent decrement from thinking we're
1670 * finished, and decrement it ourselves. Alternatively if
1671 * everything fails then there are no callbacks due and we simply
1672 * set it to 0 and return false.. */
1673 st->resolving_n_results_stored=0;
1674 st->resolving_n_results_all=0;
1675 st->resolving_count+=2;
1676 const char **addrp=st->addresses;
1677 const char *address;
1679 for (; (address=*addrp++); ) {
1680 bool_t ok = st->resolver->request(st->resolver->st,address,
1681 st->remoteport,st->comms[0],
1682 site_resolve_callback,st);
1684 st->resolving_count++;
1688 st->resolving_count=0;
1691 decrement_resolving_count(st,2);
1695 static bool_t enter_state_resolve(struct site *st)
1697 /* Reentrancy hazard! See ensure_resolving. */
1698 state_assert(st,st->state==SITE_RUN);
1699 slog(st,LOG_STATE,"entering state RESOLVE");
1700 st->state=SITE_RESOLVE;
1701 return ensure_resolving(st);
1704 static bool_t enter_new_state(struct site *st, uint32_t next,
1705 const struct msg *prompt
1706 /* may be 0 for SENTMSG1 */)
1708 bool_t (*gen)(struct site *st, const struct msg *prompt);
1711 slog(st,LOG_STATE,"entering state %s",state_name(next));
1714 state_assert(st,st->state==SITE_RUN || st->state==SITE_RESOLVE);
1715 if (!kex_init(st)) return False;
1717 st->msg1_crossed_logged = False;
1720 state_assert(st,st->state==SITE_RUN || st->state==SITE_RESOLVE ||
1721 st->state==SITE_SENTMSG1 || st->state==SITE_WAIT);
1722 if (!kex_init(st)) return False;
1726 state_assert(st,st->state==SITE_SENTMSG1);
1727 BUF_FREE(&st->buffer);
1731 state_assert(st,st->state==SITE_SENTMSG2);
1732 BUF_FREE(&st->buffer);
1736 state_assert(st,st->state==SITE_SENTMSG3);
1737 BUF_FREE(&st->buffer);
1741 state_assert(st,st->state==SITE_SENTMSG4);
1742 BUF_FREE(&st->buffer);
1747 fatal("enter_new_state(%s): invalid new state",state_name(next));
1751 if (hacky_par_start_failnow()) return False;
1753 r= gen(st,prompt) && send_msg(st);
1756 st->setup_retries, st->setup_retry_interval,
1761 if (next==SITE_RUN) {
1762 BUF_FREE(&st->buffer); /* Never reused */
1763 st->timeout=0; /* Never retransmit */
1764 activate_new_key(st);
1768 slog(st,LOG_ERROR,"error entering state %s",state_name(next));
1769 st->buffer.free=False; /* Unconditionally use the buffer; it may be
1770 in either state, and enter_state_wait() will
1772 enter_state_wait(st);
1776 /* msg7 tells our peer that we're about to forget our key */
1777 static bool_t send_msg7(struct site *st, cstring_t reason)
1779 cstring_t transform_err;
1781 if (current_valid(st) && st->buffer.free
1782 && transport_peers_valid(&st->peers)) {
1783 BUF_ALLOC(&st->buffer,"site:MSG7");
1784 buffer_init(&st->buffer,calculate_max_start_pad());
1785 buf_append_uint32(&st->buffer,LABEL_MSG7);
1786 buf_append_string(&st->buffer,reason);
1787 if (call_transform_forwards(st, st->current.transform,
1788 &st->buffer, &transform_err))
1790 buf_prepend_uint32(&st->buffer,LABEL_MSG0);
1791 buf_prepend_uint32(&st->buffer,st->index);
1792 buf_prepend_uint32(&st->buffer,st->current.remote_session_id);
1793 transport_xmit(st,&st->peers,&st->buffer,True);
1794 BUF_FREE(&st->buffer);
1801 /* We go into this state if our peer becomes uncommunicative. Similar to
1802 the "stop" state, we forget all session keys for a while, before
1803 re-entering the "run" state. */
1804 static void enter_state_wait(struct site *st)
1806 slog(st,LOG_STATE,"entering state WAIT");
1807 st->timeout=st->now+wait_timeout(st);
1808 st->state=SITE_WAIT;
1809 set_link_quality(st);
1810 BUF_FREE(&st->buffer); /* will have had an outgoing packet in it */
1811 /* XXX Erase keys etc. */
1814 static void generate_prod(struct site *st, struct buffer_if *buf)
1817 buf_append_uint32(buf,0);
1818 buf_append_uint32(buf,0);
1819 buf_append_uint32(buf,LABEL_PROD);
1820 buf_append_string(buf,st->localname);
1821 buf_append_string(buf,st->remotename);
1824 static void generate_send_prod(struct site *st,
1825 const struct comm_addr *source)
1827 if (!st->allow_send_prod) return; /* too soon */
1828 if (!(st->state==SITE_RUN || st->state==SITE_RESOLVE ||
1829 st->state==SITE_WAIT)) return; /* we'd ignore peer's MSG1 */
1831 slog(st,LOG_SETUP_INIT,"prodding peer for key exchange");
1832 st->allow_send_prod=0;
1833 generate_prod(st,&st->scratch);
1834 bool_t ok = comm_addr_sendmsg(st, source, &st->scratch);
1835 dump_packet(st,&st->scratch,source,False,ok);
1838 static inline void site_settimeout(uint64_t timeout, int *timeout_io)
1841 int64_t offset=timeout-*now;
1842 if (offset<0) offset=0;
1843 if (offset>INT_MAX) offset=INT_MAX;
1844 if (*timeout_io<0 || offset<*timeout_io)
1849 static int site_beforepoll(void *sst, struct pollfd *fds, int *nfds_io,
1852 struct site *st=sst;
1854 BEFOREPOLL_WANT_FDS(0); /* We don't use any file descriptors */
1857 /* Work out when our next timeout is. The earlier of 'timeout' or
1858 'current.key_timeout'. A stored value of '0' indicates no timeout
1860 site_settimeout(st->timeout, timeout_io);
1861 site_settimeout(st->current.key_timeout, timeout_io);
1862 site_settimeout(st->auxiliary_key.key_timeout, timeout_io);
1864 return 0; /* success */
1867 static void check_expiry(struct site *st, struct data_key *key,
1870 if (key->key_timeout && *now>key->key_timeout) {
1871 delete_one_key(st,key,"maximum life exceeded",which,LOG_TIMEOUT_KEY);
1875 /* NB site_afterpoll will be called before site_beforepoll is ever called */
1876 static void site_afterpoll(void *sst, struct pollfd *fds, int nfds)
1878 struct site *st=sst;
1881 if (st->timeout && *now>st->timeout) {
1883 if (st->state>=SITE_SENTMSG1 && st->state<=SITE_SENTMSG5) {
1884 if (!hacky_par_start_failnow())
1886 } else if (st->state==SITE_WAIT) {
1887 enter_state_run(st);
1889 slog(st,LOG_ERROR,"site_afterpoll: unexpected timeout, state=%d",
1893 check_expiry(st,&st->current,"current key");
1894 check_expiry(st,&st->auxiliary_key,"auxiliary key");
1897 /* This function is called by the netlink device to deliver packets
1898 intended for the remote network. The packet is in "raw" wire
1899 format, but is guaranteed to be word-aligned. */
1900 static void site_outgoing(void *sst, struct buffer_if *buf)
1902 struct site *st=sst;
1903 cstring_t transform_err;
1905 if (st->state==SITE_STOP) {
1910 st->allow_send_prod=1;
1912 /* In all other states we consider delivering the packet if we have
1913 a valid key and a valid address to send it to. */
1914 if (current_valid(st) && transport_peers_valid(&st->peers)) {
1915 /* Transform it and send it */
1917 buf_prepend_uint32(buf,LABEL_MSG9);
1918 if (call_transform_forwards(st, st->current.transform,
1919 buf, &transform_err))
1921 buf_prepend_uint32(buf,LABEL_MSG0);
1922 buf_prepend_uint32(buf,st->index);
1923 buf_prepend_uint32(buf,st->current.remote_session_id);
1924 transport_xmit(st,&st->peers,buf,False);
1931 slog(st,LOG_DROP,"discarding outgoing packet of size %d",buf->size);
1933 initiate_key_setup(st,"outgoing packet",0);
1936 static bool_t named_for_us(struct site *st, const struct buffer_if *buf_in,
1937 uint32_t type, struct msg *m,
1938 struct priomsg *whynot)
1939 /* For packets which are identified by the local and remote names.
1940 * If it has our name and our peer's name in it it's for us. */
1942 struct buffer_if buf[1];
1943 buffer_readonly_clone(buf,buf_in);
1945 if (!unpick_msg(st,type,buf,m)) {
1946 priomsg_update_fixed(whynot, comm_notify_whynot_unpick, "malformed");
1949 #define NAME_MATCHES(lr) \
1950 if (!name_matches(&m->lr, st->lr##name)) { \
1951 if (priomsg_update_fixed(whynot, comm_notify_whynot_name_##lr, \
1952 "unknown " #lr " name: ")) { \
1953 truncmsg_add_packet_string(&whynot->m, m->lr.len, m->lr.name); \
1957 NAME_MATCHES(remote);
1958 NAME_MATCHES(local );
1964 static bool_t we_have_priority(struct site *st, const struct msg *m) {
1965 if (st->local_capabilities & m->remote_capabilities &
1966 CAPAB_PRIORITY_MOBILE) {
1967 if (st->local_mobile) return True;
1968 if (st-> peer_mobile) return False;
1970 return st->our_name_later;
1973 static bool_t setup_late_msg_ok(struct site *st,
1974 const struct buffer_if *buf_in,
1976 const struct comm_addr *source,
1977 struct msg *m /* returned */) {
1978 /* For setup packets which seem from their type like they are
1979 * late. Maybe they came via a different path. All we do is make
1980 * a note of the sending address, iff they look like they are part
1981 * of the current key setup attempt. */
1982 if (!named_for_us(st,buf_in,msgtype,m,0))
1983 /* named_for_us calls unpick_msg which gets the nonces */
1985 if (!consttime_memeq(m->nR,st->remoteN,NONCELEN) ||
1986 !consttime_memeq(m->nL,st->localN, NONCELEN))
1987 /* spoof ? from stale run ? who knows */
1989 transport_setup_msgok(st,source);
1993 /* This function is called by the communication device to deliver
1994 packets from our peers.
1995 It should return True if the packet is recognised as being for
1996 this current site instance (and should therefore not be processed
1997 by other sites), even if the packet was otherwise ignored. */
1998 static bool_t site_incoming(void *sst, struct buffer_if *buf,
1999 const struct comm_addr *source,
2000 struct priomsg *whynot)
2002 struct site *st=sst;
2004 if (buf->size < 12) return False;
2006 uint32_t dest=get_uint32(buf->start);
2007 uint32_t msgtype=get_uint32(buf->start+8);
2009 /* initialised by named_for_us, or process_msgN for N!=1 */
2011 if (msgtype==LABEL_MSG1) {
2012 if (!named_for_us(st,buf,msgtype,&msg,whynot))
2014 /* It's a MSG1 addressed to us. Decide what to do about it. */
2015 dump_packet(st,buf,source,True,True);
2016 if (st->state==SITE_RUN || st->state==SITE_RESOLVE ||
2017 st->state==SITE_WAIT) {
2018 /* We should definitely process it */
2019 transport_compute_setupinit_peers(st,0,0,source);
2020 if (process_msg1(st,buf,source,&msg)) {
2021 slog(st,LOG_SETUP_INIT,"key setup initiated by peer");
2022 bool_t entered=enter_new_state(st,SITE_SENTMSG2,&msg);
2023 if (entered && st->addresses && st->local_mobile)
2024 /* We must do this as the very last thing, because
2025 the resolver callback might reenter us. */
2026 ensure_resolving(st);
2028 slog(st,LOG_ERROR,"failed to process incoming msg1");
2032 } else if (st->state==SITE_SENTMSG1) {
2033 /* We've just sent a message 1! They may have crossed on
2034 the wire. If we have priority then we ignore the
2035 incoming one, otherwise we process it as usual. */
2036 if (we_have_priority(st,&msg)) {
2038 if (!st->msg1_crossed_logged++)
2039 slog(st,LOG_SETUP_INIT,"crossed msg1s; we are higher "
2040 "priority => ignore incoming msg1");
2043 slog(st,LOG_SETUP_INIT,"crossed msg1s; we are lower "
2044 "priority => use incoming msg1");
2045 if (process_msg1(st,buf,source,&msg)) {
2046 BUF_FREE(&st->buffer); /* Free our old message 1 */
2047 transport_setup_msgok(st,source);
2048 enter_new_state(st,SITE_SENTMSG2,&msg);
2050 slog(st,LOG_ERROR,"failed to process an incoming "
2051 "crossed msg1 (we have low priority)");
2056 } else if (st->state==SITE_SENTMSG2 ||
2057 st->state==SITE_SENTMSG4) {
2058 if (consttime_memeq(msg.nR,st->remoteN,NONCELEN)) {
2059 /* We are ahead in the protocol, but that msg1 had the
2060 * peer's nonce so presumably it is from this key
2061 * exchange run, via a slower route */
2062 transport_setup_msgok(st,source);
2064 slog(st,LOG_UNEXPECTED,"competing incoming message 1");
2069 /* The message 1 was received at an unexpected stage of the
2070 key setup. Well, they lost the race. */
2071 slog(st,LOG_UNEXPECTED,"unexpected incoming message 1");
2075 if (msgtype==LABEL_PROD) {
2076 if (!named_for_us(st,buf,msgtype,&msg,whynot))
2078 dump_packet(st,buf,source,True,True);
2079 if (st->state!=SITE_RUN) {
2080 slog(st,LOG_DROP,"ignoring PROD when not in state RUN");
2081 } else if (current_valid(st)) {
2082 slog(st,LOG_DROP,"ignoring PROD when we think we have a key");
2084 initiate_key_setup(st,"peer sent PROD packet",source);
2089 if (dest==st->index) {
2090 /* Explicitly addressed to us */
2091 if (msgtype!=LABEL_MSG0) dump_packet(st,buf,source,True,True);
2094 /* If the source is our current peer then initiate a key setup,
2095 because our peer's forgotten the key */
2096 if (get_uint32(buf->start+4)==st->current.remote_session_id) {
2098 initiated = initiate_key_setup(st,"received a NAK",source);
2099 if (!initiated) generate_send_prod(st,source);
2101 slog(st,LOG_SEC,"bad incoming NAK");
2105 process_msg0(st,buf,source);
2108 /* Setup packet: should not have been explicitly addressed
2110 slog(st,LOG_SEC,"incoming explicitly addressed msg1");
2113 /* Setup packet: expected only in state SENTMSG1 */
2114 if (st->state!=SITE_SENTMSG1) {
2115 if ((st->state==SITE_SENTMSG3 ||
2116 st->state==SITE_SENTMSG5) &&
2117 setup_late_msg_ok(st,buf,msgtype,source,&msg))
2119 slog(st,LOG_UNEXPECTED,"unexpected MSG2");
2120 } else if (process_msg2(st,buf,source,&msg)) {
2121 transport_setup_msgok(st,source);
2122 enter_new_state(st,SITE_SENTMSG3,&msg);
2124 slog(st,LOG_SEC,"invalid MSG2");
2127 case CASES_MSG3_KNOWN:
2128 /* Setup packet: expected only in state SENTMSG2 */
2129 if (st->state!=SITE_SENTMSG2) {
2130 if ((st->state==SITE_SENTMSG4) &&
2131 setup_late_msg_ok(st,buf,msgtype,source,&msg))
2133 slog(st,LOG_UNEXPECTED,"unexpected MSG3");
2134 } else if (process_msg3(st,buf,source,msgtype,&msg)) {
2135 transport_setup_msgok(st,source);
2136 enter_new_state(st,SITE_SENTMSG4,&msg);
2138 slog(st,LOG_SEC,"invalid MSG3");
2142 /* Setup packet: expected only in state SENTMSG3 */
2143 if (st->state!=SITE_SENTMSG3) {
2144 if ((st->state==SITE_SENTMSG5) &&
2145 setup_late_msg_ok(st,buf,msgtype,source,&msg))
2147 slog(st,LOG_UNEXPECTED,"unexpected MSG4");
2148 } else if (process_msg4(st,buf,source,&msg)) {
2149 transport_setup_msgok(st,source);
2150 enter_new_state(st,SITE_SENTMSG5,&msg);
2152 slog(st,LOG_SEC,"invalid MSG4");
2156 /* Setup packet: expected only in state SENTMSG4 */
2157 /* (may turn up in state RUN if our return MSG6 was lost
2158 and the new key has already been activated. In that
2159 case we discard it. The peer will realise that we
2160 are using the new key when they see our data packets.
2161 Until then the peer's data packets to us get discarded. */
2162 if (st->state==SITE_SENTMSG4) {
2163 if (process_msg5(st,buf,source,st->new_transform)) {
2164 transport_setup_msgok(st,source);
2165 enter_new_state(st,SITE_RUN,&msg);
2167 slog(st,LOG_SEC,"invalid MSG5");
2169 } else if (st->state==SITE_RUN) {
2170 if (process_msg5(st,buf,source,st->current.transform)) {
2171 slog(st,LOG_DROP,"got MSG5, retransmitting MSG6");
2172 transport_setup_msgok(st,source);
2173 create_msg6(st,st->current.transform,
2174 st->current.remote_session_id);
2175 transport_xmit(st,&st->peers,&st->buffer,True);
2176 BUF_FREE(&st->buffer);
2178 slog(st,LOG_SEC,"invalid MSG5 (in state RUN)");
2181 slog(st,LOG_UNEXPECTED,"unexpected MSG5");
2185 /* Setup packet: expected only in state SENTMSG5 */
2186 if (st->state!=SITE_SENTMSG5) {
2187 slog(st,LOG_UNEXPECTED,"unexpected MSG6");
2188 } else if (process_msg6(st,buf,source)) {
2189 BUF_FREE(&st->buffer); /* Free message 5 */
2190 transport_setup_msgok(st,source);
2191 activate_new_key(st);
2193 slog(st,LOG_SEC,"invalid MSG6");
2197 slog(st,LOG_SEC,"received message of unknown type 0x%08x",
2205 priomsg_update_fixed(whynot, comm_notify_whynot_general,
2206 "not MSG1 or PROD; unknown dest index");
2210 static void site_control(void *vst, bool_t run)
2212 struct site *st=vst;
2213 if (run) enter_state_run(st);
2214 else enter_state_stop(st);
2217 static void site_phase_hook(void *sst, uint32_t newphase)
2219 struct site *st=sst;
2221 /* The program is shutting down; tell our peer */
2222 send_msg7(st,"shutting down");
2225 static void site_childpersist_clearkeys(void *sst, uint32_t newphase)
2227 struct site *st=sst;
2228 dispose_transform(&st->current.transform);
2229 dispose_transform(&st->auxiliary_key.transform);
2230 dispose_transform(&st->new_transform);
2231 /* Not much point overwiting the signing key, since we loaded it
2232 from disk, and it is only valid prospectively if at all,
2234 /* XXX it would be best to overwrite the DH state, because that
2235 _is_ relevant to forward secrecy. However we have no
2236 convenient interface for doing that and in practice gmp has
2237 probably dribbled droppings all over the malloc arena. A good
2238 way to fix this would be to have a privsep child for asymmetric
2239 crypto operations, but that's a task for another day. */
2242 static void setup_sethash(struct site *st, dict_t *dict,
2243 struct hash_if **hash, struct cloc loc,
2244 sig_sethash_fn *sethash, void *sigkey_st) {
2245 if (!*hash) *hash=find_cl_if(dict,"hash",CL_HASH,True,"site",loc);
2246 sethash(sigkey_st,*hash);
2248 #define SETUP_SETHASH(k) do{ \
2250 setup_sethash(st,dict, &hash,loc, (k)->sethash,(k)->st); \
2253 static list_t *site_apply(closure_t *self, struct cloc loc, dict_t *context,
2256 static uint32_t index_sequence;
2264 st->cl.description="site";
2265 st->cl.type=CL_SITE;
2267 st->cl.interface=&st->ops;
2269 st->ops.control=site_control;
2270 st->ops.status=site_status;
2271 st->peerkeys_path=0;
2272 st->peerkeys_current=st->peerkeys_kex=0;
2274 /* First parameter must be a dict */
2275 item=list_elem(args,0);
2276 if (!item || item->type!=t_dict)
2277 cfgfatal(loc,"site","parameter must be a dictionary\n");
2279 dict=item->data.dict;
2280 st->localname=dict_read_string(dict, "local-name", True, "site", loc);
2281 st->remotename=dict_read_string(dict, "name", True, "site", loc);
2283 st->keepalive=dict_read_bool(dict,"keepalive",False,"site",loc,False);
2285 st->peer_mobile=dict_read_bool(dict,"mobile",False,"site",loc,False);
2287 dict_read_bool(dict,"local-mobile",False,"site",loc,False);
2289 /* Sanity check (which also allows the 'sites' file to include
2290 site() closures for all sites including our own): refuse to
2291 talk to ourselves */
2292 if (strcmp(st->localname,st->remotename)==0) {
2293 Message(M_DEBUG,"site %s: local-name==name -> ignoring this site\n",
2295 if (st->peer_mobile != st->local_mobile)
2296 cfgfatal(loc,"site","site %s's peer-mobile=%d"
2297 " but our local-mobile=%d\n",
2298 st->localname, st->peer_mobile, st->local_mobile);
2302 if (st->peer_mobile && st->local_mobile) {
2303 Message(M_WARNING,"site %s: site is mobile but so are we"
2304 " -> ignoring this site\n", st->remotename);
2309 assert(index_sequence < 0xffffffffUL);
2310 st->index = ++index_sequence;
2311 st->local_capabilities = 0;
2312 st->early_capabilities = CAPAB_PRIORITY_MOBILE;
2313 st->netlink=find_cl_if(dict,"link",CL_NETLINK,True,"site",loc);
2315 #define GET_CLOSURE_LIST(dictkey,things,nthings,CL_TYPE) do{ \
2316 list_t *things##_cfg=dict_lookup(dict,dictkey); \
2317 if (!things##_cfg) \
2318 cfgfatal(loc,"site","closure list \"%s\" not found\n",dictkey); \
2319 st->nthings=list_length(things##_cfg); \
2320 NEW_ARY(st->things,st->nthings); \
2321 assert(st->nthings); \
2322 for (i=0; i<st->nthings; i++) { \
2323 item_t *item=list_elem(things##_cfg,i); \
2324 if (item->type!=t_closure) \
2325 cfgfatal(loc,"site","%s is not a closure\n",dictkey); \
2326 closure_t *cl=item->data.closure; \
2327 if (cl->type!=CL_TYPE) \
2328 cfgfatal(loc,"site","%s closure wrong type\n",dictkey); \
2329 st->things[i]=cl->interface; \
2333 GET_CLOSURE_LIST("comm",comms,ncomms,CL_COMM);
2335 NEW_ARY(st->commclientinfos, st->ncomms);
2336 dict_t *comminfo = dict_read_dict(dict,"comm-info",False,"site",loc);
2337 for (i=0; i<st->ncomms; i++) {
2338 st->commclientinfos[i] =
2340 st->comms[i]->clientinfo(st->comms[i],comminfo,loc);
2343 st->resolver=find_cl_if(dict,"resolver",CL_RESOLVER,True,"site",loc);
2344 st->log=find_cl_if(dict,"log",CL_LOG,True,"site",loc);
2345 st->random=find_cl_if(dict,"random",CL_RANDOMSRC,True,"site",loc);
2347 struct hash_if *hash=0;
2349 st->privkeys=find_cl_if(dict,"key-cache",CL_PRIVCACHE,False,"site",loc);
2350 if (!st->privkeys) {
2352 find_cl_if(dict,"local-key",CL_SIGPRIVKEY,True,"site",loc);
2353 SETUP_SETHASH(st->privkey_fixed);
2356 struct sigpubkey_if *fixed_pubkey
2357 =find_cl_if(dict,"key",CL_SIGPUBKEY,False,"site",loc);
2358 st->peerkeys_path=dict_read_string(dict,"peer-keys",fixed_pubkey==0,
2360 if (st->peerkeys_path) {
2361 st->peerkeys_current=keyset_load(st->peerkeys_path,
2362 &st->scratch,st->log,M_ERR);
2364 fixed_pubkey->dispose(fixed_pubkey->st);
2367 assert(fixed_pubkey);
2368 SETUP_SETHASH(fixed_pubkey);
2369 NEW(st->peerkeys_current);
2370 st->peerkeys_current->refcount=1;
2371 st->peerkeys_current->nkeys=1;
2372 st->peerkeys_current->keys[0].id=keyid_zero;
2373 st->peerkeys_current->keys[0].pubkey=fixed_pubkey;
2374 slog(st,LOG_SIGKEYS,
2375 "using old-style fixed peer public key (no `peer-keys')");
2378 st->addresses=dict_read_string_array(dict,"address",False,"site",loc,0);
2380 st->remoteport=dict_read_number(dict,"port",True,"site",loc,0);
2381 else st->remoteport=0;
2383 GET_CLOSURE_LIST("transform",transforms,ntransforms,CL_TRANSFORM);
2385 st->dh=find_cl_if(dict,"dh",CL_DH,True,"site",loc);
2387 #define DEFAULT(D) (st->peer_mobile || st->local_mobile \
2388 ? DEFAULT_MOBILE_##D : DEFAULT_##D)
2389 #define CFG_NUMBER(k,D) dict_read_number(dict,(k),False,"site",loc,DEFAULT(D));
2391 st->key_lifetime= CFG_NUMBER("key-lifetime", KEY_LIFETIME);
2392 st->setup_retries= CFG_NUMBER("setup-retries", SETUP_RETRIES);
2393 st->setup_retry_interval= CFG_NUMBER("setup-timeout", SETUP_RETRY_INTERVAL);
2394 st->wait_timeout_mean= CFG_NUMBER("wait-time", WAIT_TIME);
2395 st->mtu_target= dict_read_number(dict,"mtu-target",False,"site",loc,0);
2397 st->mobile_peer_expiry= dict_read_number(
2398 dict,"mobile-peer-expiry",False,"site",loc,DEFAULT_MOBILE_PEER_EXPIRY);
2400 const char *peerskey= st->peer_mobile
2401 ? "mobile-peers-max" : "static-peers-max";
2402 st->transport_peers_max= dict_read_number(
2403 dict,peerskey,False,"site",loc, st->addresses ? 4 : 3);
2404 if (st->transport_peers_max<1 ||
2405 st->transport_peers_max>MAX_PEER_ADDRS) {
2406 cfgfatal(loc,"site", "%s must be in range 1.."
2407 STRING(MAX_PEER_ADDRS) "\n", peerskey);
2410 if (st->key_lifetime < DEFAULT(KEY_RENEGOTIATE_GAP)*2)
2411 st->key_renegotiate_time=st->key_lifetime/2;
2413 st->key_renegotiate_time=st->key_lifetime-DEFAULT(KEY_RENEGOTIATE_GAP);
2414 st->key_renegotiate_time=dict_read_number(
2415 dict,"renegotiate-time",False,"site",loc,st->key_renegotiate_time);
2416 if (st->key_renegotiate_time > st->key_lifetime) {
2417 cfgfatal(loc,"site",
2418 "renegotiate-time must be less than key-lifetime\n");
2421 st->log_events=string_list_to_word(dict_lookup(dict,"log-events"),
2422 log_event_table,"site");
2424 st->resolving_count=0;
2425 st->allow_send_prod=0;
2427 st->tunname=safe_malloc(strlen(st->localname)+strlen(st->remotename)+5,
2429 sprintf(st->tunname,"%s<->%s",st->localname,st->remotename);
2431 /* The information we expect to see in incoming messages of type 1 */
2432 /* fixme: lots of unchecked overflows here, but the results are only
2433 corrupted packets rather than undefined behaviour */
2434 st->our_name_later=(strcmp(st->localname,st->remotename)>0);
2436 buffer_new(&st->buffer,SETUP_BUFFER_LEN);
2438 buffer_new(&st->scratch,SETUP_BUFFER_LEN);
2439 BUF_ALLOC(&st->scratch,"site:scratch");
2441 /* We are interested in poll(), but only for timeouts. We don't have
2442 any fds of our own. */
2443 register_for_poll(st, site_beforepoll, site_afterpoll, "site");
2446 st->remote_capabilities=0;
2447 st->chosen_transform=0;
2448 st->current.key_timeout=0;
2449 st->auxiliary_key.key_timeout=0;
2450 transport_peers_clear(st,&st->peers);
2451 transport_peers_clear(st,&st->setup_peers);
2452 /* XXX mlock these */
2453 st->dhsecret=safe_malloc(st->dh->len,"site:dhsecret");
2454 st->sharedsecretlen=st->sharedsecretallocd=0;
2457 #define SET_CAPBIT(bit) do { \
2458 uint32_t capflag = 1UL << (bit); \
2459 if (st->local_capabilities & capflag) \
2460 slog(st,LOG_ERROR,"capability bit" \
2461 " %d (%#"PRIx32") reused", (bit), capflag); \
2462 st->local_capabilities |= capflag; \
2465 for (i=0; i<st->ntransforms; i++)
2466 SET_CAPBIT(st->transforms[i]->capab_bit);
2470 if (st->local_mobile || st->peer_mobile)
2471 st->local_capabilities |= CAPAB_PRIORITY_MOBILE;
2473 /* We need to register the remote networks with the netlink device */
2474 uint32_t netlink_mtu; /* local virtual interface mtu */
2475 st->netlink->reg(st->netlink->st, site_outgoing, st, &netlink_mtu);
2476 if (!st->mtu_target)
2477 st->mtu_target=netlink_mtu;
2479 for (i=0; i<st->ncomms; i++)
2480 st->comms[i]->request_notify(st->comms[i]->st, st, site_incoming);
2482 st->current.transform=0;
2483 st->auxiliary_key.transform=0;
2484 st->new_transform=0;
2485 st->auxiliary_is_new=0;
2487 enter_state_stop(st);
2489 add_hook(PHASE_SHUTDOWN,site_phase_hook,st);
2490 add_hook(PHASE_CHILDPERSIST,site_childpersist_clearkeys,st);
2492 return new_closure(&st->cl);
2495 void site_module(dict_t *dict)
2497 add_closure(dict,"site",site_apply);
2501 /***** TRANSPORT PEERS definitions *****/
2503 static void transport_peers_debug(struct site *st, transport_peers *dst,
2504 const char *didwhat,
2505 int nargs, const struct comm_addr *args,
2510 if (!(st->log_events & LOG_PEER_ADDRS))
2511 return; /* an optimisation */
2513 slog(st, LOG_PEER_ADDRS, "peers (%s) %s nargs=%d => npeers=%d",
2514 (dst==&st->peers ? "data" :
2515 dst==&st->setup_peers ? "setup" : "UNKNOWN"),
2516 didwhat, nargs, dst->npeers);
2518 for (i=0, argp=(void*)args;
2520 i++, (argp+=stride?stride:sizeof(*args))) {
2521 const struct comm_addr *ca=(void*)argp;
2522 slog(st, LOG_PEER_ADDRS, " args: addrs[%d]=%s",
2523 i, comm_addr_to_string(ca));
2525 for (i=0; i<dst->npeers; i++) {
2526 struct timeval diff;
2527 timersub(tv_now,&dst->peers[i].last,&diff);
2528 const struct comm_addr *ca=&dst->peers[i].addr;
2529 slog(st, LOG_PEER_ADDRS, " peers: addrs[%d]=%s T-%ld.%06ld",
2530 i, comm_addr_to_string(ca),
2531 (unsigned long)diff.tv_sec, (unsigned long)diff.tv_usec);
2535 static void transport_peers_expire(struct site *st, transport_peers *peers) {
2536 /* peers must be sorted first */
2537 int previous_peers=peers->npeers;
2538 struct timeval oldest;
2539 oldest.tv_sec = tv_now->tv_sec - st->mobile_peer_expiry;
2540 oldest.tv_usec = tv_now->tv_usec;
2541 while (peers->npeers>1 &&
2542 timercmp(&peers->peers[peers->npeers-1].last, &oldest, <))
2544 if (peers->npeers != previous_peers)
2545 transport_peers_debug(st,peers,"expire", 0,0,0);
2548 static bool_t transport_peer_record_one(struct site *st, transport_peers *peers,
2549 const struct comm_addr *ca,
2550 const struct timeval *tv) {
2551 /* returns false if output is full */
2554 if (peers->npeers >= st->transport_peers_max)
2557 for (search=0; search<peers->npeers; search++)
2558 if (comm_addr_equal(&peers->peers[search].addr, ca))
2561 peers->peers[peers->npeers].addr = *ca;
2562 peers->peers[peers->npeers].last = *tv;
2567 static void transport_record_peers(struct site *st, transport_peers *peers,
2568 const struct comm_addr *addrs, int naddrs,
2570 /* We add addrs into peers. The new entries end up at the front
2571 * and displace entries towards the end (perhaps even off the
2572 * end). Any existing matching entries are moved up to the front.
2574 * Caller must first call transport_peers_expire. */
2577 /* avoids debug for uninteresting updates */
2579 for (i=0; i<peers->npeers; i++) {
2580 if (comm_addr_equal(&addrs[0], &peers->peers[i].addr)) {
2581 memmove(peers->peers+1, peers->peers,
2582 sizeof(peers->peers[0]) * i);
2583 peers->peers[0].addr = addrs[0];
2584 peers->peers[0].last = *tv_now;
2590 int old_npeers=peers->npeers;
2591 transport_peer old_peers[old_npeers];
2592 COPY_ARRAY(old_peers,peers->peers,old_npeers);
2596 for (i=0; i<naddrs; i++) {
2597 if (!transport_peer_record_one(st,peers, &addrs[i], tv_now))
2600 for (i=0; i<old_npeers; i++) {
2601 const transport_peer *old=&old_peers[i];
2602 if (!transport_peer_record_one(st,peers, &old->addr, &old->last))
2606 transport_peers_debug(st,peers,m, naddrs,addrs,0);
2609 static void transport_expire_record_peers(struct site *st,
2610 transport_peers *peers,
2611 const struct comm_addr *addrs,
2612 int naddrs, const char *m) {
2613 /* Convenience function */
2614 transport_peers_expire(st,peers);
2615 transport_record_peers(st,peers,addrs,naddrs,m);
2618 static bool_t transport_compute_setupinit_peers(struct site *st,
2619 const struct comm_addr *configured_addrs /* 0 if none or not found */,
2620 int n_configured_addrs /* 0 if none or not found */,
2621 const struct comm_addr *incoming_packet_addr /* 0 if none */) {
2622 if (!n_configured_addrs && !incoming_packet_addr &&
2623 !transport_peers_valid(&st->peers))
2626 slog(st,LOG_SETUP_INIT,
2627 "using: %d configured addr(s);%s %d old peer addrs(es)",
2629 incoming_packet_addr ? " incoming packet address;" : "",
2632 /* Non-mobile peers try addresses until one is plausible. The
2633 * effect is that this code always tries first the configured
2634 * address if supplied, or otherwise the address of the incoming
2635 * PROD, or finally the existing data peer if one exists; this is
2638 transport_peers_copy(st,&st->setup_peers,&st->peers);
2639 transport_peers_expire(st,&st->setup_peers);
2641 if (incoming_packet_addr)
2642 transport_record_peers(st,&st->setup_peers,
2643 incoming_packet_addr,1, "incoming");
2645 if (n_configured_addrs)
2646 transport_record_peers(st,&st->setup_peers,
2647 configured_addrs,n_configured_addrs, "setupinit");
2649 assert(transport_peers_valid(&st->setup_peers));
2653 static void transport_setup_msgok(struct site *st, const struct comm_addr *a) {
2654 if (st->peer_mobile)
2655 transport_expire_record_peers(st,&st->setup_peers,a,1,"setupmsg");
2657 static void transport_data_msgok(struct site *st, const struct comm_addr *a) {
2658 if (st->peer_mobile)
2659 transport_expire_record_peers(st,&st->peers,a,1,"datamsg");
2662 static int transport_peers_valid(transport_peers *peers) {
2663 return peers->npeers;
2665 static void transport_peers_clear(struct site *st, transport_peers *peers) {
2667 transport_peers_debug(st,peers,"clear",0,0,0);
2669 static void transport_peers_copy(struct site *st, transport_peers *dst,
2670 const transport_peers *src) {
2671 dst->npeers=src->npeers;
2672 COPY_ARRAY(dst->peers, src->peers, dst->npeers);
2673 transport_peers_debug(st,dst,"copy",
2674 src->npeers, &src->peers->addr, sizeof(*src->peers));
2677 static void transport_resolve_complete(struct site *st,
2678 const struct comm_addr *addrs,
2680 transport_expire_record_peers(st,&st->peers,addrs,naddrs,
2682 transport_expire_record_peers(st,&st->setup_peers,addrs,naddrs,
2686 static void transport_resolve_complete_tardy(struct site *st,
2687 const struct comm_addr *addrs,
2689 transport_expire_record_peers(st,&st->peers,addrs,naddrs,
2690 "resolved tardily");
2693 static void transport_peers__copy_by_mask(transport_peer *out, int *nout_io,
2695 const transport_peers *inp) {
2696 /* out and in->peers may be the same region, or nonoverlapping */
2697 const transport_peer *in=inp->peers;
2699 for (slot=0; slot<inp->npeers; slot++) {
2700 if (!(mask & (1U << slot)))
2702 if (!(out==in && slot==*nout_io))
2703 COPY_OBJ(out[*nout_io], in[slot]);
2708 void transport_xmit(struct site *st, transport_peers *peers,
2709 struct buffer_if *buf, bool_t candebug) {
2711 transport_peers_expire(st, peers);
2712 unsigned failed=0; /* bitmask */
2713 assert(MAX_PEER_ADDRS < sizeof(unsigned)*CHAR_BIT);
2716 for (slot=0; slot<peers->npeers; slot++) {
2717 transport_peer *peer=&peers->peers[slot];
2718 bool_t ok = comm_addr_sendmsg(st, &peer->addr, buf);
2720 dump_packet(st, buf, &peer->addr, False, ok);
2722 failed |= 1U << slot;
2725 if (ok && !st->peer_mobile)
2728 /* Now we need to demote/delete failing addrs: if we are mobile we
2729 * merely demote them; otherwise we delete them. */
2730 if (st->local_mobile) {
2731 unsigned expected = ((1U << nfailed)-1) << (peers->npeers-nfailed);
2732 /* `expected' has all the failures at the end already */
2733 if (failed != expected) {
2735 transport_peer failedpeers[nfailed];
2736 transport_peers__copy_by_mask(failedpeers, &fslot, failed,peers);
2737 assert(fslot == nfailed);
2739 transport_peers__copy_by_mask(peers->peers,&wslot,~failed,peers);
2740 assert(wslot+nfailed == peers->npeers);
2741 COPY_ARRAY(peers->peers+wslot, failedpeers, nfailed);
2742 transport_peers_debug(st,peers,"mobile failure reorder",0,0,0);
2745 if (failed && peers->npeers > 1) {
2747 transport_peers__copy_by_mask(peers->peers,&wslot,~failed,peers);
2748 peers->npeers=wslot;
2749 transport_peers_debug(st,peers,"non-mobile failure cleanup",0,0,0);
2754 /***** END of transport peers declarations *****/