chiark / gitweb /
8fa4c113ffb33be343c3359e7a1254c29b44e708
[secnet.git] / site.c
1 /* site.c - manage communication with a remote network site */
2
3 /* The 'site' code doesn't know anything about the structure of the
4    packets it's transmitting.  In fact, under the new netlink
5    configuration scheme it doesn't need to know anything at all about
6    IP addresses, except how to contact its peer.  This means it could
7    potentially be used to tunnel other protocols too (IPv6, IPX, plain
8    old Ethernet frames) if appropriate netlink code can be written
9    (and that ought not to be too hard, eg. using the TUN/TAP device to
10    pretend to be an Ethernet interface).  */
11
12 /* At some point in the future the netlink code will be asked for
13    configuration information to go in the PING/PONG packets at the end
14    of the key exchange. */
15
16 #include "secnet.h"
17 #include <stdio.h>
18 #include <string.h>
19 #include <limits.h>
20 #include <assert.h>
21 #include <sys/socket.h>
22
23 #include <sys/mman.h>
24 #include "util.h"
25 #include "unaligned.h"
26 #include "magic.h"
27
28 #define SETUP_BUFFER_LEN 2048
29
30 #define DEFAULT_KEY_LIFETIME                  (3600*1000) /* [ms] */
31 #define DEFAULT_KEY_RENEGOTIATE_GAP           (5*60*1000) /* [ms] */
32 #define DEFAULT_SETUP_RETRIES 5
33 #define DEFAULT_SETUP_RETRY_INTERVAL             (2*1000) /* [ms] */
34 #define DEFAULT_WAIT_TIME                       (20*1000) /* [ms] */
35
36 #define DEFAULT_MOBILE_KEY_LIFETIME      (2*24*3600*1000) /* [ms] */
37 #define DEFAULT_MOBILE_KEY_RENEGOTIATE_GAP (12*3600*1000) /* [ms] */
38 #define DEFAULT_MOBILE_SETUP_RETRIES 30
39 #define DEFAULT_MOBILE_SETUP_RETRY_INTERVAL      (1*1000) /* [ms] */
40 #define DEFAULT_MOBILE_WAIT_TIME                (10*1000) /* [ms] */
41
42 #define DEFAULT_MOBILE_PEER_EXPIRY            (2*60)      /* [s] */
43 #define DEFAULT_MOBILE_PEERS_MAX 3 /* send at most this many copies (default) */
44
45 /* Each site can be in one of several possible states. */
46
47 /* States:
48    SITE_STOP         - nothing is allowed to happen; tunnel is down;
49                        all session keys have been erased
50      -> SITE_RUN upon external instruction
51    SITE_RUN          - site up, maybe with valid key
52      -> SITE_RESOLVE upon outgoing packet and no valid key
53          we start name resolution for the other end of the tunnel
54      -> SITE_SENTMSG2 upon valid incoming message 1 and suitable time
55          we send an appropriate message 2
56    SITE_RESOLVE      - waiting for name resolution
57      -> SITE_SENTMSG1 upon successful resolution
58          we send an appropriate message 1
59      -> SITE_SENTMSG2 upon valid incoming message 1 (then abort resolution)
60          we abort resolution and 
61      -> SITE_WAIT on timeout or resolution failure
62    SITE_SENTMSG1
63      -> SITE_SENTMSG2 upon valid incoming message 1 from higher priority end
64      -> SITE_SENTMSG3 upon valid incoming message 2
65      -> SITE_WAIT on timeout
66    SITE_SENTMSG2
67      -> SITE_SENTMSG4 upon valid incoming message 3
68      -> SITE_WAIT on timeout
69    SITE_SENTMSG3
70      -> SITE_SENTMSG5 upon valid incoming message 4
71      -> SITE_WAIT on timeout
72    SITE_SENTMSG4
73      -> SITE_RUN upon valid incoming message 5
74      -> SITE_WAIT on timeout
75    SITE_SENTMSG5
76      -> SITE_RUN upon valid incoming message 6
77      -> SITE_WAIT on timeout
78    SITE_WAIT         - failed to establish key; do nothing for a while
79      -> SITE_RUN on timeout
80    */
81
82 #define SITE_STOP     0
83 #define SITE_RUN      1
84 #define SITE_RESOLVE  2
85 #define SITE_SENTMSG1 3
86 #define SITE_SENTMSG2 4
87 #define SITE_SENTMSG3 5
88 #define SITE_SENTMSG4 6
89 #define SITE_SENTMSG5 7
90 #define SITE_WAIT     8
91
92 static cstring_t state_name(uint32_t state)
93 {
94     switch (state) {
95     case 0: return "STOP";
96     case 1: return "RUN";
97     case 2: return "RESOLVE";
98     case 3: return "SENTMSG1";
99     case 4: return "SENTMSG2";
100     case 5: return "SENTMSG3";
101     case 6: return "SENTMSG4";
102     case 7: return "SENTMSG5";
103     case 8: return "WAIT";
104     default: return "*bad state*";
105     }
106 }
107
108 #define NONCELEN 8
109
110 #define LOG_UNEXPECTED    0x00000001
111 #define LOG_SETUP_INIT    0x00000002
112 #define LOG_SETUP_TIMEOUT 0x00000004
113 #define LOG_ACTIVATE_KEY  0x00000008
114 #define LOG_TIMEOUT_KEY   0x00000010
115 #define LOG_SEC           0x00000020
116 #define LOG_STATE         0x00000040
117 #define LOG_DROP          0x00000080
118 #define LOG_DUMP          0x00000100
119 #define LOG_ERROR         0x00000400
120 #define LOG_PEER_ADDRS    0x00000800
121
122 static struct flagstr log_event_table[]={
123     { "unexpected", LOG_UNEXPECTED },
124     { "setup-init", LOG_SETUP_INIT },
125     { "setup-timeout", LOG_SETUP_TIMEOUT },
126     { "activate-key", LOG_ACTIVATE_KEY },
127     { "timeout-key", LOG_TIMEOUT_KEY },
128     { "security", LOG_SEC },
129     { "state-change", LOG_STATE },
130     { "packet-drop", LOG_DROP },
131     { "dump-packets", LOG_DUMP },
132     { "errors", LOG_ERROR },
133     { "peer-addrs", LOG_PEER_ADDRS },
134     { "default", LOG_SETUP_INIT|LOG_SETUP_TIMEOUT|
135       LOG_ACTIVATE_KEY|LOG_TIMEOUT_KEY|LOG_SEC|LOG_ERROR },
136     { "all", 0xffffffff },
137     { NULL, 0 }
138 };
139
140
141 /***** TRANSPORT PEERS declarations *****/
142
143 /* Details of "mobile peer" semantics:
144    
145    - We record mobile_peers_max peer address/port numbers ("peers")
146      for key setup, and separately mobile_peers_max for data
147      transfer.  If these lists fill up, we retain the newest peers.
148      (For non-mobile peers we only record one of each.)
149
150    - Outgoing packets are sent to every recorded peer in the
151      applicable list.
152
153    - Data transfer peers are straightforward: whenever we successfully
154      process a data packet, we record the peer.  Also, whenever we
155      successfully complete a key setup, we merge the key setup
156      peers into the data transfer peers.
157
158      (For "non-mobile" peers we simply copy the peer used for
159      successful key setup, and don't change the peer otherwise.)
160
161    - Key setup peers are slightly more complicated.
162
163      Whenever we receive and successfully process a key exchange
164      packet, we record the peer.
165
166      Whenever we try to initiate a key setup, we copy the list of data
167      transfer peers and use it for key setup.  But we also look to see
168      if the config supplies an address and port number and if so we
169      add that as a key setup peer (possibly evicting one of the data
170      transfer peers we just copied).
171
172      (For "non-mobile" peers, if we if we have a configured peer
173      address and port, we always use that; otherwise if we have a
174      current data peer address we use that; otherwise we do not
175      attempt to initiate a key setup for lack of a peer address.)
176
177    "Record the peer" means
178     1. expire any peers last seen >120s ("mobile-peer-expiry") ago
179     2. add the peer of the just received packet to the applicable list
180        (possibly evicting older entries)
181    NB that we do not expire peers until an incoming packet arrives.
182
183    */
184
185 #define MAX_MOBILE_PEERS_MAX 5 /* send at most this many copies, compiled max */
186
187 typedef struct {
188     struct timeval last;
189     struct comm_addr addr;
190 } transport_peer;
191
192 typedef struct {
193 /* configuration information */
194 /* runtime information */
195     int npeers;
196     transport_peer peers[MAX_MOBILE_PEERS_MAX];
197 } transport_peers;
198
199 static void transport_peers_clear(struct site *st, transport_peers *peers);
200 static int transport_peers_valid(transport_peers *peers);
201 static void transport_peers_copy(struct site *st, transport_peers *dst,
202                                  const transport_peers *src);
203
204 static void transport_setup_msgok(struct site *st, const struct comm_addr *a);
205 static void transport_data_msgok(struct site *st, const struct comm_addr *a);
206 static bool_t transport_compute_setupinit_peers(struct site *st,
207         const struct comm_addr *configured_addr /* 0 if none or not found */);
208 static void transport_record_peer(struct site *st, transport_peers *peers,
209                                   const struct comm_addr *addr, const char *m);
210
211 static void transport_xmit(struct site *st, transport_peers *peers,
212                            struct buffer_if *buf, bool_t candebug);
213
214  /***** END of transport peers declarations *****/
215
216
217 struct data_key {
218     struct transform_inst_if *transform;
219     uint64_t key_timeout; /* End of life of current key */
220     uint32_t remote_session_id;
221 };
222
223 struct site {
224     closure_t cl;
225     struct site_if ops;
226 /* configuration information */
227     string_t localname;
228     string_t remotename;
229     bool_t peer_mobile; /* Mobile client support */
230     int32_t transport_peers_max;
231     string_t tunname; /* localname<->remotename by default, used in logs */
232     string_t address; /* DNS name for bootstrapping, optional */
233     int remoteport; /* Port for bootstrapping, optional */
234     struct netlink_if *netlink;
235     struct comm_if **comms;
236     int ncomms;
237     struct resolver_if *resolver;
238     struct log_if *log;
239     struct random_if *random;
240     struct rsaprivkey_if *privkey;
241     struct rsapubkey_if *pubkey;
242     struct transform_if *transform;
243     struct dh_if *dh;
244     struct hash_if *hash;
245
246     uint32_t index; /* Index of this site */
247     int32_t setup_retries; /* How many times to send setup packets */
248     int32_t setup_retry_interval; /* Initial timeout for setup packets */
249     int32_t wait_timeout; /* How long to wait if setup unsuccessful */
250     int32_t mobile_peer_expiry; /* How long to remember 2ary addresses */
251     int32_t key_lifetime; /* How long a key lasts once set up */
252     int32_t key_renegotiate_time; /* If we see traffic (or a keepalive)
253                                       after this time, initiate a new
254                                       key exchange */
255
256     uint8_t *setupsig; /* Expected signature of incoming MSG1 packets */
257     int32_t setupsiglen; /* Allows us to discard packets quickly if
258                             they are not for us */
259     bool_t setup_priority; /* Do we have precedence if both sites emit
260                               message 1 simultaneously? */
261     uint32_t log_events;
262
263 /* runtime information */
264     uint32_t state;
265     uint64_t now; /* Most recently seen time */
266
267     /* The currently established session */
268     struct data_key current;
269     struct data_key auxiliary_key;
270     bool_t auxiliary_is_new;
271     uint64_t renegotiate_key_time; /* When we can negotiate a new key */
272     uint64_t auxiliary_renegotiate_key_time;
273     transport_peers peers; /* Current address(es) of peer for data traffic */
274
275     /* The current key setup protocol exchange.  We can only be
276        involved in one of these at a time.  There's a potential for
277        denial of service here (the attacker keeps sending a setup
278        packet; we keep trying to continue the exchange, and have to
279        timeout before we can listen for another setup packet); perhaps
280        we should keep a list of 'bad' sources for setup packets. */
281     uint32_t setup_session_id;
282     transport_peers setup_peers;
283     uint8_t localN[NONCELEN]; /* Nonces for key exchange */
284     uint8_t remoteN[NONCELEN];
285     struct buffer_if buffer; /* Current outgoing key exchange packet */
286     struct buffer_if scratch;
287     int32_t retries; /* Number of retries remaining */
288     uint64_t timeout; /* Timeout for current state */
289     uint8_t *dhsecret;
290     uint8_t *sharedsecret;
291     uint32_t sharedsecretlen;
292     struct transform_inst_if *new_transform; /* For key setup/verify */
293 };
294
295 static void slog(struct site *st, uint32_t event, cstring_t msg, ...)
296 {
297     va_list ap;
298     char buf[240];
299     uint32_t class;
300
301     va_start(ap,msg);
302
303     if (event&st->log_events) {
304         switch(event) {
305         case LOG_UNEXPECTED: class=M_INFO; break;
306         case LOG_SETUP_INIT: class=M_INFO; break;
307         case LOG_SETUP_TIMEOUT: class=M_NOTICE; break;
308         case LOG_ACTIVATE_KEY: class=M_INFO; break;
309         case LOG_TIMEOUT_KEY: class=M_INFO; break;
310         case LOG_SEC: class=M_SECURITY; break;
311         case LOG_STATE: class=M_DEBUG; break;
312         case LOG_DROP: class=M_DEBUG; break;
313         case LOG_DUMP: class=M_DEBUG; break;
314         case LOG_ERROR: class=M_ERR; break;
315         case LOG_PEER_ADDRS: class=M_DEBUG; break;
316         default: class=M_ERR; break;
317         }
318
319         vsnprintf(buf,sizeof(buf),msg,ap);
320         st->log->log(st->log->st,class,"%s: %s",st->tunname,buf);
321     }
322     va_end(ap);
323 }
324
325 static void set_link_quality(struct site *st);
326 static void delete_keys(struct site *st, cstring_t reason, uint32_t loglevel);
327 static void delete_one_key(struct site *st, struct data_key *key,
328                            const char *reason /* may be 0 meaning don't log*/,
329                            const char *which /* ignored if !reasonn */,
330                            uint32_t loglevel /* ignored if !reasonn */);
331 static bool_t initiate_key_setup(struct site *st, cstring_t reason);
332 static void enter_state_run(struct site *st);
333 static bool_t enter_state_resolve(struct site *st);
334 static bool_t enter_new_state(struct site *st,uint32_t next);
335 static void enter_state_wait(struct site *st);
336 static void activate_new_key(struct site *st);
337
338 static bool_t current_valid(struct site *st)
339 {
340     return st->current.transform->valid(st->current.transform->st);
341 }
342
343 #define CHECK_AVAIL(b,l) do { if ((b)->size<(l)) return False; } while(0)
344 #define CHECK_EMPTY(b) do { if ((b)->size!=0) return False; } while(0)
345 #define CHECK_TYPE(b,t) do { uint32_t type; \
346     CHECK_AVAIL((b),4); \
347     type=buf_unprepend_uint32((b)); \
348     if (type!=(t)) return False; } while(0)
349
350 struct msg {
351     uint8_t *hashstart;
352     uint32_t dest;
353     uint32_t source;
354     int32_t remlen;
355     uint8_t *remote;
356     int32_t loclen;
357     uint8_t *local;
358     uint8_t *nR;
359     uint8_t *nL;
360     int32_t pklen;
361     char *pk;
362     int32_t hashlen;
363     int32_t siglen;
364     char *sig;
365 };
366
367 /* Build any of msg1 to msg4. msg5 and msg6 are built from the inside
368    out using a transform of config data supplied by netlink */
369 static bool_t generate_msg(struct site *st, uint32_t type, cstring_t what)
370 {
371     void *hst;
372     uint8_t *hash;
373     string_t dhpub, sig;
374
375     st->retries=st->setup_retries;
376     BUF_ALLOC(&st->buffer,what);
377     buffer_init(&st->buffer,0);
378     buf_append_uint32(&st->buffer,
379         (type==LABEL_MSG1?0:st->setup_session_id));
380     buf_append_uint32(&st->buffer,st->index);
381     buf_append_uint32(&st->buffer,type);
382     buf_append_string(&st->buffer,st->localname);
383     buf_append_string(&st->buffer,st->remotename);
384     memcpy(buf_append(&st->buffer,NONCELEN),st->localN,NONCELEN);
385     if (type==LABEL_MSG1) return True;
386     memcpy(buf_append(&st->buffer,NONCELEN),st->remoteN,NONCELEN);
387     if (type==LABEL_MSG2) return True;
388
389     if (hacky_par_mid_failnow()) return False;
390
391     dhpub=st->dh->makepublic(st->dh->st,st->dhsecret,st->dh->len);
392     buf_append_string(&st->buffer,dhpub);
393     free(dhpub);
394     hash=safe_malloc(st->hash->len, "generate_msg");
395     hst=st->hash->init();
396     st->hash->update(hst,st->buffer.start,st->buffer.size);
397     st->hash->final(hst,hash);
398     sig=st->privkey->sign(st->privkey->st,hash,st->hash->len);
399     buf_append_string(&st->buffer,sig);
400     free(sig);
401     free(hash);
402     return True;
403 }
404
405 static bool_t unpick_msg(struct site *st, uint32_t type,
406                          struct buffer_if *msg, struct msg *m)
407 {
408     m->hashstart=msg->start;
409     CHECK_AVAIL(msg,4);
410     m->dest=buf_unprepend_uint32(msg);
411     CHECK_AVAIL(msg,4);
412     m->source=buf_unprepend_uint32(msg);
413     CHECK_TYPE(msg,type);
414     CHECK_AVAIL(msg,2);
415     m->remlen=buf_unprepend_uint16(msg);
416     CHECK_AVAIL(msg,m->remlen);
417     m->remote=buf_unprepend(msg,m->remlen);
418     CHECK_AVAIL(msg,2);
419     m->loclen=buf_unprepend_uint16(msg);
420     CHECK_AVAIL(msg,m->loclen);
421     m->local=buf_unprepend(msg,m->loclen);
422     CHECK_AVAIL(msg,NONCELEN);
423     m->nR=buf_unprepend(msg,NONCELEN);
424     if (type==LABEL_MSG1) {
425         CHECK_EMPTY(msg);
426         return True;
427     }
428     CHECK_AVAIL(msg,NONCELEN);
429     m->nL=buf_unprepend(msg,NONCELEN);
430     if (type==LABEL_MSG2) {
431         CHECK_EMPTY(msg);
432         return True;
433     }
434     CHECK_AVAIL(msg,2);
435     m->pklen=buf_unprepend_uint16(msg);
436     CHECK_AVAIL(msg,m->pklen);
437     m->pk=buf_unprepend(msg,m->pklen);
438     m->hashlen=msg->start-m->hashstart;
439     CHECK_AVAIL(msg,2);
440     m->siglen=buf_unprepend_uint16(msg);
441     CHECK_AVAIL(msg,m->siglen);
442     m->sig=buf_unprepend(msg,m->siglen);
443     CHECK_EMPTY(msg);
444     return True;
445 }
446
447 static bool_t check_msg(struct site *st, uint32_t type, struct msg *m,
448                         cstring_t *error)
449 {
450     if (type==LABEL_MSG1) return True;
451
452     /* Check that the site names and our nonce have been sent
453        back correctly, and then store our peer's nonce. */ 
454     if (memcmp(m->remote,st->remotename,strlen(st->remotename)!=0)) {
455         *error="wrong remote site name";
456         return False;
457     }
458     if (memcmp(m->local,st->localname,strlen(st->localname)!=0)) {
459         *error="wrong local site name";
460         return False;
461     }
462     if (memcmp(m->nL,st->localN,NONCELEN)!=0) {
463         *error="wrong locally-generated nonce";
464         return False;
465     }
466     if (type==LABEL_MSG2) return True;
467     if (!consttime_memeq(m->nR,st->remoteN,NONCELEN)!=0) {
468         *error="wrong remotely-generated nonce";
469         return False;
470     }
471     if (type==LABEL_MSG3) return True;
472     if (type==LABEL_MSG4) return True;
473     *error="unknown message type";
474     return False;
475 }
476
477 static bool_t generate_msg1(struct site *st)
478 {
479     st->random->generate(st->random->st,NONCELEN,st->localN);
480     return generate_msg(st,LABEL_MSG1,"site:MSG1");
481 }
482
483 static bool_t process_msg1(struct site *st, struct buffer_if *msg1,
484                            const struct comm_addr *src)
485 {
486     struct msg m;
487
488     /* We've already determined we're in an appropriate state to
489        process an incoming MSG1, and that the MSG1 has correct values
490        of A and B. */
491
492     if (!unpick_msg(st,LABEL_MSG1,msg1,&m)) return False;
493
494     transport_record_peer(st,&st->setup_peers,src,"msg1");
495     st->setup_session_id=m.source;
496     memcpy(st->remoteN,m.nR,NONCELEN);
497     return True;
498 }
499
500 static bool_t generate_msg2(struct site *st)
501 {
502     st->random->generate(st->random->st,NONCELEN,st->localN);
503     return generate_msg(st,LABEL_MSG2,"site:MSG2");
504 }
505
506 static bool_t process_msg2(struct site *st, struct buffer_if *msg2,
507                            const struct comm_addr *src)
508 {
509     struct msg m;
510     cstring_t err;
511
512     if (!unpick_msg(st,LABEL_MSG2,msg2,&m)) return False;
513     if (!check_msg(st,LABEL_MSG2,&m,&err)) {
514         slog(st,LOG_SEC,"msg2: %s",err);
515         return False;
516     }
517     st->setup_session_id=m.source;
518     memcpy(st->remoteN,m.nR,NONCELEN);
519     return True;
520 }
521
522 static bool_t generate_msg3(struct site *st)
523 {
524     /* Now we have our nonce and their nonce. Think of a secret key,
525        and create message number 3. */
526     st->random->generate(st->random->st,st->dh->len,st->dhsecret);
527     return generate_msg(st,LABEL_MSG3,"site:MSG3");
528 }
529
530 static bool_t process_msg3(struct site *st, struct buffer_if *msg3,
531                            const struct comm_addr *src)
532 {
533     struct msg m;
534     uint8_t *hash;
535     void *hst;
536     cstring_t err;
537
538     if (!unpick_msg(st,LABEL_MSG3,msg3,&m)) return False;
539     if (!check_msg(st,LABEL_MSG3,&m,&err)) {
540         slog(st,LOG_SEC,"msg3: %s",err);
541         return False;
542     }
543
544     /* Check signature and store g^x mod m */
545     hash=safe_malloc(st->hash->len, "process_msg3");
546     hst=st->hash->init();
547     st->hash->update(hst,m.hashstart,m.hashlen);
548     st->hash->final(hst,hash);
549     /* Terminate signature with a '0' - cheating, but should be ok */
550     m.sig[m.siglen]=0;
551     if (!st->pubkey->check(st->pubkey->st,hash,st->hash->len,m.sig)) {
552         slog(st,LOG_SEC,"msg3 signature failed check!");
553         free(hash);
554         return False;
555     }
556     free(hash);
557
558     /* Terminate their DH public key with a '0' */
559     m.pk[m.pklen]=0;
560     /* Invent our DH secret key */
561     st->random->generate(st->random->st,st->dh->len,st->dhsecret);
562
563     /* Generate the shared key */
564     st->dh->makeshared(st->dh->st,st->dhsecret,st->dh->len,m.pk,
565                        st->sharedsecret,st->sharedsecretlen);
566
567     /* Set up the transform */
568     st->new_transform->setkey(st->new_transform->st,st->sharedsecret,
569                               st->sharedsecretlen,st->setup_priority);
570
571     return True;
572 }
573
574 static bool_t generate_msg4(struct site *st)
575 {
576     /* We have both nonces, their public key and our private key. Generate
577        our public key, sign it and send it to them. */
578     return generate_msg(st,LABEL_MSG4,"site:MSG4");
579 }
580
581 static bool_t process_msg4(struct site *st, struct buffer_if *msg4,
582                            const struct comm_addr *src)
583 {
584     struct msg m;
585     uint8_t *hash;
586     void *hst;
587     cstring_t err;
588
589     if (!unpick_msg(st,LABEL_MSG4,msg4,&m)) return False;
590     if (!check_msg(st,LABEL_MSG4,&m,&err)) {
591         slog(st,LOG_SEC,"msg4: %s",err);
592         return False;
593     }
594     
595     /* Check signature and store g^x mod m */
596     hash=safe_malloc(st->hash->len, "process_msg4");
597     hst=st->hash->init();
598     st->hash->update(hst,m.hashstart,m.hashlen);
599     st->hash->final(hst,hash);
600     /* Terminate signature with a '0' - cheating, but should be ok */
601     m.sig[m.siglen]=0;
602     if (!st->pubkey->check(st->pubkey->st,hash,st->hash->len,m.sig)) {
603         slog(st,LOG_SEC,"msg4 signature failed check!");
604         free(hash);
605         return False;
606     }
607     free(hash);
608
609     /* Terminate their DH public key with a '0' */
610     m.pk[m.pklen]=0;
611     /* Generate the shared key */
612     st->dh->makeshared(st->dh->st,st->dhsecret,st->dh->len,m.pk,
613                        st->sharedsecret,st->sharedsecretlen);
614     /* Set up the transform */
615     st->new_transform->setkey(st->new_transform->st,st->sharedsecret,
616                               st->sharedsecretlen,st->setup_priority);
617
618     return True;
619 }
620
621 struct msg0 {
622     uint32_t dest;
623     uint32_t source;
624     uint32_t type;
625 };
626
627 static bool_t unpick_msg0(struct site *st, struct buffer_if *msg0,
628                           struct msg0 *m)
629 {
630     CHECK_AVAIL(msg0,4);
631     m->dest=buf_unprepend_uint32(msg0);
632     CHECK_AVAIL(msg0,4);
633     m->source=buf_unprepend_uint32(msg0);
634     CHECK_AVAIL(msg0,4);
635     m->type=buf_unprepend_uint32(msg0);
636     return True;
637     /* Leaves transformed part of buffer untouched */
638 }
639
640 static bool_t generate_msg5(struct site *st)
641 {
642     cstring_t transform_err;
643
644     BUF_ALLOC(&st->buffer,"site:MSG5");
645     /* We are going to add four words to the message */
646     buffer_init(&st->buffer,st->transform->max_start_pad+(4*4));
647     /* Give the netlink code an opportunity to put its own stuff in the
648        message (configuration information, etc.) */
649     buf_prepend_uint32(&st->buffer,LABEL_MSG5);
650     st->new_transform->forwards(st->new_transform->st,&st->buffer,
651                                 &transform_err);
652     buf_prepend_uint32(&st->buffer,LABEL_MSG5);
653     buf_prepend_uint32(&st->buffer,st->index);
654     buf_prepend_uint32(&st->buffer,st->setup_session_id);
655
656     st->retries=st->setup_retries;
657     return True;
658 }
659
660 static bool_t process_msg5(struct site *st, struct buffer_if *msg5,
661                            const struct comm_addr *src,
662                            struct transform_inst_if *transform)
663 {
664     struct msg0 m;
665     cstring_t transform_err;
666
667     if (!unpick_msg0(st,msg5,&m)) return False;
668
669     if (transform->reverse(transform->st,msg5,&transform_err)) {
670         /* There's a problem */
671         slog(st,LOG_SEC,"process_msg5: transform: %s",transform_err);
672         return False;
673     }
674     /* Buffer should now contain untransformed PING packet data */
675     CHECK_AVAIL(msg5,4);
676     if (buf_unprepend_uint32(msg5)!=LABEL_MSG5) {
677         slog(st,LOG_SEC,"MSG5/PING packet contained wrong label");
678         return False;
679     }
680     /* Older versions of secnet used to write some config data here
681      * which we ignore.  So we don't CHECK_EMPTY */
682     return True;
683 }
684
685 static void create_msg6(struct site *st, struct transform_inst_if *transform,
686                         uint32_t session_id)
687 {
688     cstring_t transform_err;
689
690     BUF_ALLOC(&st->buffer,"site:MSG6");
691     /* We are going to add four words to the message */
692     buffer_init(&st->buffer,st->transform->max_start_pad+(4*4));
693     /* Give the netlink code an opportunity to put its own stuff in the
694        message (configuration information, etc.) */
695     buf_prepend_uint32(&st->buffer,LABEL_MSG6);
696     transform->forwards(transform->st,&st->buffer,&transform_err);
697     buf_prepend_uint32(&st->buffer,LABEL_MSG6);
698     buf_prepend_uint32(&st->buffer,st->index);
699     buf_prepend_uint32(&st->buffer,session_id);
700 }
701
702 static bool_t generate_msg6(struct site *st)
703 {
704     create_msg6(st,st->new_transform,st->setup_session_id);
705     st->retries=1; /* Peer will retransmit MSG5 if this packet gets lost */
706     return True;
707 }
708
709 static bool_t process_msg6(struct site *st, struct buffer_if *msg6,
710                            const struct comm_addr *src)
711 {
712     struct msg0 m;
713     cstring_t transform_err;
714
715     if (!unpick_msg0(st,msg6,&m)) return False;
716
717     if (st->new_transform->reverse(st->new_transform->st,
718                                    msg6,&transform_err)) {
719         /* There's a problem */
720         slog(st,LOG_SEC,"process_msg6: transform: %s",transform_err);
721         return False;
722     }
723     /* Buffer should now contain untransformed PING packet data */
724     CHECK_AVAIL(msg6,4);
725     if (buf_unprepend_uint32(msg6)!=LABEL_MSG6) {
726         slog(st,LOG_SEC,"MSG6/PONG packet contained invalid data");
727         return False;
728     }
729     /* Older versions of secnet used to write some config data here
730      * which we ignore.  So we don't CHECK_EMPTY */
731     return True;
732 }
733
734 static bool_t decrypt_msg0(struct site *st, struct buffer_if *msg0,
735                            const struct comm_addr *src)
736 {
737     cstring_t transform_err, auxkey_err, newkey_err="n/a";
738     struct msg0 m;
739     uint32_t problem;
740
741     if (!unpick_msg0(st,msg0,&m)) return False;
742
743     /* Keep a copy so we can try decrypting it with multiple keys */
744     buffer_copy(&st->scratch, msg0);
745
746     problem = st->current.transform->reverse(st->current.transform->st,
747                                              msg0,&transform_err);
748     if (!problem) {
749         if (!st->auxiliary_is_new)
750             delete_one_key(st,&st->auxiliary_key,
751                            "peer has used new key","auxiliary key",LOG_SEC);
752         return True;
753     }
754     if (problem==2)
755         goto skew;
756
757     buffer_copy(msg0, &st->scratch);
758     problem = st->auxiliary_key.transform->reverse
759         (st->auxiliary_key.transform->st,msg0,&auxkey_err);
760     if (problem==0) {
761         slog(st,LOG_DROP,"processing packet which uses auxiliary key");
762         if (st->auxiliary_is_new) {
763             /* We previously timed out in state SENTMSG5 but it turns
764              * out that our peer did in fact get our MSG5 and is
765              * using the new key.  So we should switch to it too. */
766             /* This is a bit like activate_new_key. */
767             struct data_key t;
768             t=st->current;
769             st->current=st->auxiliary_key;
770             st->auxiliary_key=t;
771
772             delete_one_key(st,&st->auxiliary_key,"peer has used new key",
773                            "previous key",LOG_SEC);
774             st->auxiliary_is_new=0;
775             st->renegotiate_key_time=st->auxiliary_renegotiate_key_time;
776         }
777         return True;
778     }
779     if (problem==2)
780         goto skew;
781
782     if (st->state==SITE_SENTMSG5) {
783         buffer_copy(msg0, &st->scratch);
784         problem = st->new_transform->reverse(st->new_transform->st,
785                                              msg0,&newkey_err);
786         if (!problem) {
787             /* It looks like we didn't get the peer's MSG6 */
788             /* This is like a cut-down enter_new_state(SITE_RUN) */
789             slog(st,LOG_STATE,"will enter state RUN (MSG0 with new key)");
790             BUF_FREE(&st->buffer);
791             st->timeout=0;
792             activate_new_key(st);
793             return True; /* do process the data in this packet */
794         }
795         if (problem==2)
796             goto skew;
797     }
798
799     slog(st,LOG_SEC,"transform: %s (aux: %s, new: %s)",
800          transform_err,auxkey_err,newkey_err);
801     initiate_key_setup(st,"incoming message would not decrypt");
802     send_nak(src,m.dest,m.source,m.type,msg0,"message would not decrypt");
803     return False;
804
805  skew:
806     slog(st,LOG_DROP,"transform: %s (merely skew)",transform_err);
807     return False;
808 }
809
810 static bool_t process_msg0(struct site *st, struct buffer_if *msg0,
811                            const struct comm_addr *src)
812 {
813     uint32_t type;
814
815     if (!decrypt_msg0(st,msg0,src))
816         return False;
817
818     CHECK_AVAIL(msg0,4);
819     type=buf_unprepend_uint32(msg0);
820     switch(type) {
821     case LABEL_MSG7:
822         /* We must forget about the current session. */
823         delete_keys(st,"request from peer",LOG_SEC);
824         return True;
825     case LABEL_MSG9:
826         /* Deliver to netlink layer */
827         st->netlink->deliver(st->netlink->st,msg0);
828         transport_data_msgok(st,src);
829         /* See whether we should start negotiating a new key */
830         if (st->now > st->renegotiate_key_time)
831             initiate_key_setup(st,"incoming packet in renegotiation window");
832         return True;
833     default:
834         slog(st,LOG_SEC,"incoming encrypted message of type %08x "
835              "(unknown)",type);
836         break;
837     }
838     return False;
839 }
840
841 static void dump_packet(struct site *st, struct buffer_if *buf,
842                         const struct comm_addr *addr, bool_t incoming)
843 {
844     uint32_t dest=ntohl(*(uint32_t *)buf->start);
845     uint32_t source=ntohl(*(uint32_t *)(buf->start+4));
846     uint32_t msgtype=ntohl(*(uint32_t *)(buf->start+8));
847
848     if (st->log_events & LOG_DUMP)
849         slilog(st->log,M_DEBUG,"%s: %s: %08x<-%08x: %08x:",
850                st->tunname,incoming?"incoming":"outgoing",
851                dest,source,msgtype);
852 }
853
854 static uint32_t site_status(void *st)
855 {
856     return 0;
857 }
858
859 static bool_t send_msg(struct site *st)
860 {
861     if (st->retries>0) {
862         transport_xmit(st, &st->setup_peers, &st->buffer, True);
863         st->timeout=st->now+st->setup_retry_interval;
864         st->retries--;
865         return True;
866     } else if (st->state==SITE_SENTMSG5) {
867         slog(st,LOG_SETUP_TIMEOUT,"timed out sending MSG5, stashing new key");
868         /* We stash the key we have produced, in case it turns out that
869          * our peer did see our MSG5 after all and starts using it. */
870         /* This is a bit like some of activate_new_key */
871         struct transform_inst_if *t;
872         t=st->auxiliary_key.transform;
873         st->auxiliary_key.transform=st->new_transform;
874         st->new_transform=t;
875
876         t->delkey(t->st);
877         st->auxiliary_is_new=1;
878         st->auxiliary_key.key_timeout=st->now+st->key_lifetime;
879         st->auxiliary_renegotiate_key_time=st->now+st->key_renegotiate_time;
880         st->auxiliary_key.remote_session_id=st->setup_session_id;
881
882         enter_state_wait(st);
883         return False;
884     } else {
885         slog(st,LOG_SETUP_TIMEOUT,"timed out sending key setup packet "
886             "(in state %s)",state_name(st->state));
887         enter_state_wait(st);
888         return False;
889     }
890 }
891
892 static void site_resolve_callback(void *sst, struct in_addr *address)
893 {
894     struct site *st=sst;
895     struct comm_addr ca_buf, *ca_use;
896
897     if (st->state!=SITE_RESOLVE) {
898         slog(st,LOG_UNEXPECTED,"site_resolve_callback called unexpectedly");
899         return;
900     }
901     if (address) {
902         FILLZERO(ca_buf);
903         ca_buf.comm=st->comms[0];
904         ca_buf.sin.sin_family=AF_INET;
905         ca_buf.sin.sin_port=htons(st->remoteport);
906         ca_buf.sin.sin_addr=*address;
907         ca_use=&ca_buf;
908     } else {
909         slog(st,LOG_ERROR,"resolution of %s failed",st->address);
910         ca_use=0;
911     }
912     if (transport_compute_setupinit_peers(st,ca_use)) {
913         enter_new_state(st,SITE_SENTMSG1);
914     } else {
915         /* Can't figure out who to try to to talk to */
916         slog(st,LOG_SETUP_INIT,"key exchange failed: cannot find peer address");
917         enter_state_run(st);
918     }
919 }
920
921 static bool_t initiate_key_setup(struct site *st, cstring_t reason)
922 {
923     if (st->state!=SITE_RUN) return False;
924     slog(st,LOG_SETUP_INIT,"initiating key exchange (%s)",reason);
925     if (st->address) {
926         slog(st,LOG_SETUP_INIT,"resolving peer address");
927         return enter_state_resolve(st);
928     } else if (transport_compute_setupinit_peers(st,0)) {
929         return enter_new_state(st,SITE_SENTMSG1);
930     }
931     slog(st,LOG_SETUP_INIT,"key exchange failed: no address for peer");
932     return False;
933 }
934
935 static void activate_new_key(struct site *st)
936 {
937     struct transform_inst_if *t;
938
939     /* We have three transform instances, which we swap between old,
940        active and setup */
941     t=st->auxiliary_key.transform;
942     st->auxiliary_key.transform=st->current.transform;
943     st->current.transform=st->new_transform;
944     st->new_transform=t;
945
946     t->delkey(t->st);
947     st->timeout=0;
948     st->auxiliary_is_new=0;
949     st->auxiliary_key.key_timeout=st->current.key_timeout;
950     st->current.key_timeout=st->now+st->key_lifetime;
951     st->renegotiate_key_time=st->now+st->key_renegotiate_time;
952     transport_peers_copy(st,&st->peers,&st->setup_peers);
953     st->current.remote_session_id=st->setup_session_id;
954
955     slog(st,LOG_ACTIVATE_KEY,"new key activated");
956     enter_state_run(st);
957 }
958
959 static void delete_one_key(struct site *st, struct data_key *key,
960                            cstring_t reason, cstring_t which, uint32_t loglevel)
961 {
962     if (!key->transform->valid(key->transform->st)) return;
963     if (reason) slog(st,loglevel,"%s deleted (%s)",which,reason);
964     key->transform->delkey(key->transform->st);
965     key->key_timeout=0;
966 }
967
968 static void delete_keys(struct site *st, cstring_t reason, uint32_t loglevel)
969 {
970     if (current_valid(st)) {
971         slog(st,loglevel,"session closed (%s)",reason);
972
973         delete_one_key(st,&st->current,0,0,0);
974         set_link_quality(st);
975     }
976     delete_one_key(st,&st->auxiliary_key,0,0,0);
977 }
978
979 static void state_assert(struct site *st, bool_t ok)
980 {
981     if (!ok) fatal("site:state_assert");
982 }
983
984 static void enter_state_stop(struct site *st)
985 {
986     st->state=SITE_STOP;
987     st->timeout=0;
988     delete_keys(st,"entering state STOP",LOG_TIMEOUT_KEY);
989     st->new_transform->delkey(st->new_transform->st);
990 }
991
992 static void set_link_quality(struct site *st)
993 {
994     uint32_t quality;
995     if (current_valid(st))
996         quality=LINK_QUALITY_UP;
997     else if (st->state==SITE_WAIT || st->state==SITE_STOP)
998         quality=LINK_QUALITY_DOWN;
999     else if (st->address)
1000         quality=LINK_QUALITY_DOWN_CURRENT_ADDRESS;
1001     else if (transport_peers_valid(&st->peers))
1002         quality=LINK_QUALITY_DOWN_STALE_ADDRESS;
1003     else
1004         quality=LINK_QUALITY_DOWN;
1005
1006     st->netlink->set_quality(st->netlink->st,quality);
1007 }
1008
1009 static void enter_state_run(struct site *st)
1010 {
1011     slog(st,LOG_STATE,"entering state RUN");
1012     st->state=SITE_RUN;
1013     st->timeout=0;
1014
1015     st->setup_session_id=0;
1016     transport_peers_clear(st,&st->setup_peers);
1017     memset(st->localN,0,NONCELEN);
1018     memset(st->remoteN,0,NONCELEN);
1019     st->new_transform->delkey(st->new_transform->st);
1020     memset(st->dhsecret,0,st->dh->len);
1021     memset(st->sharedsecret,0,st->sharedsecretlen);
1022     set_link_quality(st);
1023 }
1024
1025 static bool_t enter_state_resolve(struct site *st)
1026 {
1027     state_assert(st,st->state==SITE_RUN);
1028     slog(st,LOG_STATE,"entering state RESOLVE");
1029     st->state=SITE_RESOLVE;
1030     st->resolver->request(st->resolver->st,st->address,
1031                           site_resolve_callback,st);
1032     return True;
1033 }
1034
1035 static bool_t enter_new_state(struct site *st, uint32_t next)
1036 {
1037     bool_t (*gen)(struct site *st);
1038     int r;
1039
1040     slog(st,LOG_STATE,"entering state %s",state_name(next));
1041     switch(next) {
1042     case SITE_SENTMSG1:
1043         state_assert(st,st->state==SITE_RUN || st->state==SITE_RESOLVE);
1044         gen=generate_msg1;
1045         break;
1046     case SITE_SENTMSG2:
1047         state_assert(st,st->state==SITE_RUN || st->state==SITE_RESOLVE ||
1048                      st->state==SITE_SENTMSG1 || st->state==SITE_WAIT);
1049         gen=generate_msg2;
1050         break;
1051     case SITE_SENTMSG3:
1052         state_assert(st,st->state==SITE_SENTMSG1);
1053         BUF_FREE(&st->buffer);
1054         gen=generate_msg3;
1055         break;
1056     case SITE_SENTMSG4:
1057         state_assert(st,st->state==SITE_SENTMSG2);
1058         BUF_FREE(&st->buffer);
1059         gen=generate_msg4;
1060         break;
1061     case SITE_SENTMSG5:
1062         state_assert(st,st->state==SITE_SENTMSG3);
1063         BUF_FREE(&st->buffer);
1064         gen=generate_msg5;
1065         break;
1066     case SITE_RUN:
1067         state_assert(st,st->state==SITE_SENTMSG4);
1068         BUF_FREE(&st->buffer);
1069         gen=generate_msg6;
1070         break;
1071     default:
1072         gen=NULL;
1073         fatal("enter_new_state(%s): invalid new state",state_name(next));
1074         break;
1075     }
1076
1077     if (hacky_par_start_failnow()) return False;
1078
1079     r= gen(st) && send_msg(st);
1080
1081     hacky_par_end(&r,
1082                   st->setup_retries, st->setup_retry_interval,
1083                   send_msg, st);
1084     
1085     if (r) {
1086         st->state=next;
1087         if (next==SITE_RUN) {
1088             BUF_FREE(&st->buffer); /* Never reused */
1089             st->timeout=0; /* Never retransmit */
1090             activate_new_key(st);
1091         }
1092         return True;
1093     }
1094     slog(st,LOG_ERROR,"error entering state %s",state_name(next));
1095     st->buffer.free=False; /* Unconditionally use the buffer; it may be
1096                               in either state, and enter_state_wait() will
1097                               do a BUF_FREE() */
1098     enter_state_wait(st);
1099     return False;
1100 }
1101
1102 /* msg7 tells our peer that we're about to forget our key */
1103 static bool_t send_msg7(struct site *st, cstring_t reason)
1104 {
1105     cstring_t transform_err;
1106
1107     if (current_valid(st) && st->buffer.free
1108         && transport_peers_valid(&st->peers)) {
1109         BUF_ALLOC(&st->buffer,"site:MSG7");
1110         buffer_init(&st->buffer,st->transform->max_start_pad+(4*3));
1111         buf_append_uint32(&st->buffer,LABEL_MSG7);
1112         buf_append_string(&st->buffer,reason);
1113         st->current.transform->forwards(st->current.transform->st,
1114                                         &st->buffer, &transform_err);
1115         buf_prepend_uint32(&st->buffer,LABEL_MSG0);
1116         buf_prepend_uint32(&st->buffer,st->index);
1117         buf_prepend_uint32(&st->buffer,st->current.remote_session_id);
1118         transport_xmit(st,&st->peers,&st->buffer,True);
1119         BUF_FREE(&st->buffer);
1120         return True;
1121     }
1122     return False;
1123 }
1124
1125 /* We go into this state if our peer becomes uncommunicative. Similar to
1126    the "stop" state, we forget all session keys for a while, before
1127    re-entering the "run" state. */
1128 static void enter_state_wait(struct site *st)
1129 {
1130     slog(st,LOG_STATE,"entering state WAIT");
1131     st->timeout=st->now+st->wait_timeout;
1132     st->state=SITE_WAIT;
1133     set_link_quality(st);
1134     BUF_FREE(&st->buffer); /* will have had an outgoing packet in it */
1135     /* XXX Erase keys etc. */
1136 }
1137
1138 static inline void site_settimeout(uint64_t timeout, int *timeout_io)
1139 {
1140     if (timeout) {
1141         int64_t offset=timeout-*now;
1142         if (offset<0) offset=0;
1143         if (offset>INT_MAX) offset=INT_MAX;
1144         if (*timeout_io<0 || offset<*timeout_io)
1145             *timeout_io=offset;
1146     }
1147 }
1148
1149 static int site_beforepoll(void *sst, struct pollfd *fds, int *nfds_io,
1150                            int *timeout_io)
1151 {
1152     struct site *st=sst;
1153
1154     *nfds_io=0; /* We don't use any file descriptors */
1155     st->now=*now;
1156
1157     /* Work out when our next timeout is. The earlier of 'timeout' or
1158        'current.key_timeout'. A stored value of '0' indicates no timeout
1159        active. */
1160     site_settimeout(st->timeout, timeout_io);
1161     site_settimeout(st->current.key_timeout, timeout_io);
1162     site_settimeout(st->auxiliary_key.key_timeout, timeout_io);
1163
1164     return 0; /* success */
1165 }
1166
1167 static void check_expiry(struct site *st, struct data_key *key,
1168                          const char *which)
1169 {
1170     if (key->key_timeout && *now>key->key_timeout) {
1171         delete_one_key(st,key,"maximum life exceeded",which,LOG_TIMEOUT_KEY);
1172     }
1173 }
1174
1175 /* NB site_afterpoll will be called before site_beforepoll is ever called */
1176 static void site_afterpoll(void *sst, struct pollfd *fds, int nfds)
1177 {
1178     struct site *st=sst;
1179
1180     st->now=*now;
1181     if (st->timeout && *now>st->timeout) {
1182         st->timeout=0;
1183         if (st->state>=SITE_SENTMSG1 && st->state<=SITE_SENTMSG5) {
1184             if (!hacky_par_start_failnow())
1185                 send_msg(st);
1186         } else if (st->state==SITE_WAIT) {
1187             enter_state_run(st);
1188         } else {
1189             slog(st,LOG_ERROR,"site_afterpoll: unexpected timeout, state=%d",
1190                  st->state);
1191         }
1192     }
1193     check_expiry(st,&st->current,"current key");
1194     check_expiry(st,&st->auxiliary_key,"auxiliary key");
1195 }
1196
1197 /* This function is called by the netlink device to deliver packets
1198    intended for the remote network. The packet is in "raw" wire
1199    format, but is guaranteed to be word-aligned. */
1200 static void site_outgoing(void *sst, struct buffer_if *buf)
1201 {
1202     struct site *st=sst;
1203     cstring_t transform_err;
1204     
1205     if (st->state==SITE_STOP) {
1206         BUF_FREE(buf);
1207         return;
1208     }
1209
1210     /* In all other states we consider delivering the packet if we have
1211        a valid key and a valid address to send it to. */
1212     if (current_valid(st) && transport_peers_valid(&st->peers)) {
1213         /* Transform it and send it */
1214         if (buf->size>0) {
1215             buf_prepend_uint32(buf,LABEL_MSG9);
1216             st->current.transform->forwards(st->current.transform->st,
1217                                             buf, &transform_err);
1218             buf_prepend_uint32(buf,LABEL_MSG0);
1219             buf_prepend_uint32(buf,st->index);
1220             buf_prepend_uint32(buf,st->current.remote_session_id);
1221             transport_xmit(st,&st->peers,buf,False);
1222         }
1223         BUF_FREE(buf);
1224         return;
1225     }
1226
1227     slog(st,LOG_DROP,"discarding outgoing packet of size %d",buf->size);
1228     BUF_FREE(buf);
1229     initiate_key_setup(st,"outgoing packet");
1230 }
1231
1232 /* This function is called by the communication device to deliver
1233    packets from our peers. */
1234 static bool_t site_incoming(void *sst, struct buffer_if *buf,
1235                             const struct comm_addr *source)
1236 {
1237     struct site *st=sst;
1238
1239     if (buf->size < 12) return False;
1240
1241     uint32_t dest=ntohl(*(uint32_t *)buf->start);
1242
1243     if (dest==0) {
1244         /* It could be for any site - it should have LABEL_MSG1 and
1245            might have our name and our peer's name in it */
1246         if (buf->size<(st->setupsiglen+8+NONCELEN)) return False;
1247         if (memcmp(buf->start+8,st->setupsig,st->setupsiglen)==0) {
1248             /* It's addressed to us. Decide what to do about it. */
1249             dump_packet(st,buf,source,True);
1250             if (st->state==SITE_RUN || st->state==SITE_RESOLVE ||
1251                 st->state==SITE_WAIT) {
1252                 /* We should definitely process it */
1253                 if (process_msg1(st,buf,source)) {
1254                     slog(st,LOG_SETUP_INIT,"key setup initiated by peer");
1255                     enter_new_state(st,SITE_SENTMSG2);
1256                 } else {
1257                     slog(st,LOG_ERROR,"failed to process incoming msg1");
1258                 }
1259                 BUF_FREE(buf);
1260                 return True;
1261             } else if (st->state==SITE_SENTMSG1) {
1262                 /* We've just sent a message 1! They may have crossed on
1263                    the wire. If we have priority then we ignore the
1264                    incoming one, otherwise we process it as usual. */
1265                 if (st->setup_priority) {
1266                     BUF_FREE(buf);
1267                     slog(st,LOG_DUMP,"crossed msg1s; we are higher "
1268                          "priority => ignore incoming msg1");
1269                     return True;
1270                 } else {
1271                     slog(st,LOG_DUMP,"crossed msg1s; we are lower "
1272                          "priority => use incoming msg1");
1273                     if (process_msg1(st,buf,source)) {
1274                         BUF_FREE(&st->buffer); /* Free our old message 1 */
1275                         enter_new_state(st,SITE_SENTMSG2);
1276                     } else {
1277                         slog(st,LOG_ERROR,"failed to process an incoming "
1278                              "crossed msg1 (we have low priority)");
1279                     }
1280                     BUF_FREE(buf);
1281                     return True;
1282                 }
1283             }
1284             /* The message 1 was received at an unexpected stage of the
1285                key setup. XXX POLICY - what do we do? */
1286             slog(st,LOG_UNEXPECTED,"unexpected incoming message 1");
1287             BUF_FREE(buf);
1288             return True;
1289         }
1290         return False; /* Not for us. */
1291     }
1292     if (dest==st->index) {
1293         /* Explicitly addressed to us */
1294         uint32_t msgtype=ntohl(get_uint32(buf->start+8));
1295         if (msgtype!=LABEL_MSG0) dump_packet(st,buf,source,True);
1296         switch (msgtype) {
1297         case LABEL_NAK:
1298             /* If the source is our current peer then initiate a key setup,
1299                because our peer's forgotten the key */
1300             if (get_uint32(buf->start+4)==st->current.remote_session_id) {
1301                 initiate_key_setup(st,"received a NAK");
1302             } else {
1303                 slog(st,LOG_SEC,"bad incoming NAK");
1304             }
1305             break;
1306         case LABEL_MSG0:
1307             process_msg0(st,buf,source);
1308             break;
1309         case LABEL_MSG1:
1310             /* Setup packet: should not have been explicitly addressed
1311                to us */
1312             slog(st,LOG_SEC,"incoming explicitly addressed msg1");
1313             break;
1314         case LABEL_MSG2:
1315             /* Setup packet: expected only in state SENTMSG1 */
1316             if (st->state!=SITE_SENTMSG1) {
1317                 slog(st,LOG_UNEXPECTED,"unexpected MSG2");
1318             } else if (process_msg2(st,buf,source)) {
1319                 transport_setup_msgok(st,source);
1320                 enter_new_state(st,SITE_SENTMSG3);
1321             } else {
1322                 slog(st,LOG_SEC,"invalid MSG2");
1323             }
1324             break;
1325         case LABEL_MSG3:
1326             /* Setup packet: expected only in state SENTMSG2 */
1327             if (st->state!=SITE_SENTMSG2) {
1328                 slog(st,LOG_UNEXPECTED,"unexpected MSG3");
1329             } else if (process_msg3(st,buf,source)) {
1330                 transport_setup_msgok(st,source);
1331                 enter_new_state(st,SITE_SENTMSG4);
1332             } else {
1333                 slog(st,LOG_SEC,"invalid MSG3");
1334             }
1335             break;
1336         case LABEL_MSG4:
1337             /* Setup packet: expected only in state SENTMSG3 */
1338             if (st->state!=SITE_SENTMSG3) {
1339                 slog(st,LOG_UNEXPECTED,"unexpected MSG4");
1340             } else if (process_msg4(st,buf,source)) {
1341                 transport_setup_msgok(st,source);
1342                 enter_new_state(st,SITE_SENTMSG5);
1343             } else {
1344                 slog(st,LOG_SEC,"invalid MSG4");
1345             }
1346             break;
1347         case LABEL_MSG5:
1348             /* Setup packet: expected only in state SENTMSG4 */
1349             /* (may turn up in state RUN if our return MSG6 was lost
1350                and the new key has already been activated. In that
1351                case we discard it. The peer will realise that we
1352                are using the new key when they see our data packets.
1353                Until then the peer's data packets to us get discarded. */
1354             if (st->state==SITE_SENTMSG4) {
1355                 if (process_msg5(st,buf,source,st->new_transform)) {
1356                     transport_setup_msgok(st,source);
1357                     enter_new_state(st,SITE_RUN);
1358                 } else {
1359                     slog(st,LOG_SEC,"invalid MSG5");
1360                 }
1361             } else if (st->state==SITE_RUN) {
1362                 if (process_msg5(st,buf,source,st->current.transform)) {
1363                     slog(st,LOG_DROP,"got MSG5, retransmitting MSG6");
1364                     transport_setup_msgok(st,source);
1365                     create_msg6(st,st->current.transform,
1366                                 st->current.remote_session_id);
1367                     transport_xmit(st,&st->peers,&st->buffer,True);
1368                     BUF_FREE(&st->buffer);
1369                 } else {
1370                     slog(st,LOG_SEC,"invalid MSG5 (in state RUN)");
1371                 }
1372             } else {
1373                 slog(st,LOG_UNEXPECTED,"unexpected MSG5");
1374             }
1375             break;
1376         case LABEL_MSG6:
1377             /* Setup packet: expected only in state SENTMSG5 */
1378             if (st->state!=SITE_SENTMSG5) {
1379                 slog(st,LOG_UNEXPECTED,"unexpected MSG6");
1380             } else if (process_msg6(st,buf,source)) {
1381                 BUF_FREE(&st->buffer); /* Free message 5 */
1382                 transport_setup_msgok(st,source);
1383                 activate_new_key(st);
1384             } else {
1385                 slog(st,LOG_SEC,"invalid MSG6");
1386             }
1387             break;
1388         default:
1389             slog(st,LOG_SEC,"received message of unknown type 0x%08x",
1390                  msgtype);
1391             break;
1392         }
1393         BUF_FREE(buf);
1394         return True;
1395     }
1396
1397     return False;
1398 }
1399
1400 static void site_control(void *vst, bool_t run)
1401 {
1402     struct site *st=vst;
1403     if (run) enter_state_run(st);
1404     else enter_state_stop(st);
1405 }
1406
1407 static void site_phase_hook(void *sst, uint32_t newphase)
1408 {
1409     struct site *st=sst;
1410
1411     /* The program is shutting down; tell our peer */
1412     send_msg7(st,"shutting down");
1413 }
1414
1415 static list_t *site_apply(closure_t *self, struct cloc loc, dict_t *context,
1416                           list_t *args)
1417 {
1418     static uint32_t index_sequence;
1419     struct site *st;
1420     item_t *item;
1421     dict_t *dict;
1422     int i;
1423
1424     st=safe_malloc(sizeof(*st),"site_apply");
1425
1426     st->cl.description="site";
1427     st->cl.type=CL_SITE;
1428     st->cl.apply=NULL;
1429     st->cl.interface=&st->ops;
1430     st->ops.st=st;
1431     st->ops.control=site_control;
1432     st->ops.status=site_status;
1433
1434     /* First parameter must be a dict */
1435     item=list_elem(args,0);
1436     if (!item || item->type!=t_dict)
1437         cfgfatal(loc,"site","parameter must be a dictionary\n");
1438     
1439     dict=item->data.dict;
1440     st->localname=dict_read_string(dict, "local-name", True, "site", loc);
1441     st->remotename=dict_read_string(dict, "name", True, "site", loc);
1442
1443     st->peer_mobile=dict_read_bool(dict,"mobile",False,"site",loc,False);
1444     bool_t local_mobile=
1445         dict_read_bool(dict,"local-mobile",False,"site",loc,False);
1446
1447     /* Sanity check (which also allows the 'sites' file to include
1448        site() closures for all sites including our own): refuse to
1449        talk to ourselves */
1450     if (strcmp(st->localname,st->remotename)==0) {
1451         Message(M_DEBUG,"site %s: local-name==name -> ignoring this site\n",
1452                 st->localname);
1453         if (st->peer_mobile != local_mobile)
1454             cfgfatal(loc,"site","site %s's peer-mobile=%d"
1455                     " but our local-mobile=%d\n",
1456                     st->localname, st->peer_mobile, local_mobile);
1457         free(st);
1458         return NULL;
1459     }
1460     if (st->peer_mobile && local_mobile) {
1461         Message(M_WARNING,"site %s: site is mobile but so are we"
1462                 " -> ignoring this site\n", st->remotename);
1463         free(st);
1464         return NULL;
1465     }
1466
1467     assert(index_sequence < 0xffffffffUL);
1468     st->index = ++index_sequence;
1469     st->netlink=find_cl_if(dict,"link",CL_NETLINK,True,"site",loc);
1470
1471     list_t *comms_cfg=dict_lookup(dict,"comm");
1472     if (!comms_cfg) cfgfatal(loc,"site","closure list \"comm\" not found\n");
1473     st->ncomms=list_length(comms_cfg);
1474     st->comms=safe_malloc_ary(sizeof(*st->comms),st->ncomms,"comms");
1475     assert(st->ncomms);
1476     for (i=0; i<st->ncomms; i++) {
1477         item_t *item=list_elem(comms_cfg,i);
1478         if (item->type!=t_closure)
1479             cfgfatal(loc,"site","comm is not a closure\n");
1480         closure_t *cl=item->data.closure;
1481         if (cl->type!=CL_COMM) cfgfatal(loc,"site","comm closure wrong type\n");
1482         st->comms[i]=cl->interface;
1483     }
1484
1485     st->resolver=find_cl_if(dict,"resolver",CL_RESOLVER,True,"site",loc);
1486     st->log=find_cl_if(dict,"log",CL_LOG,True,"site",loc);
1487     st->random=find_cl_if(dict,"random",CL_RANDOMSRC,True,"site",loc);
1488
1489     st->privkey=find_cl_if(dict,"local-key",CL_RSAPRIVKEY,True,"site",loc);
1490     st->address=dict_read_string(dict, "address", False, "site", loc);
1491     if (st->address)
1492         st->remoteport=dict_read_number(dict,"port",True,"site",loc,0);
1493     else st->remoteport=0;
1494     st->pubkey=find_cl_if(dict,"key",CL_RSAPUBKEY,True,"site",loc);
1495
1496     st->transform=
1497         find_cl_if(dict,"transform",CL_TRANSFORM,True,"site",loc);
1498
1499     st->dh=find_cl_if(dict,"dh",CL_DH,True,"site",loc);
1500     st->hash=find_cl_if(dict,"hash",CL_HASH,True,"site",loc);
1501
1502 #define DEFAULT(D) (st->peer_mobile || local_mobile     \
1503                     ? DEFAULT_MOBILE_##D : DEFAULT_##D)
1504 #define CFG_NUMBER(k,D) dict_read_number(dict,(k),False,"site",loc,DEFAULT(D));
1505
1506     st->key_lifetime=         CFG_NUMBER("key-lifetime",  KEY_LIFETIME);
1507     st->setup_retries=        CFG_NUMBER("setup-retries", SETUP_RETRIES);
1508     st->setup_retry_interval= CFG_NUMBER("setup-timeout", SETUP_RETRY_INTERVAL);
1509     st->wait_timeout=         CFG_NUMBER("wait-time",     WAIT_TIME);
1510
1511     st->mobile_peer_expiry= dict_read_number(
1512        dict,"mobile-peer-expiry",False,"site",loc,DEFAULT_MOBILE_PEER_EXPIRY);
1513
1514     st->transport_peers_max= !st->peer_mobile ? 1 : dict_read_number(
1515         dict,"mobile-peers-max",False,"site",loc,DEFAULT_MOBILE_PEERS_MAX);
1516     if (st->transport_peers_max<1 ||
1517         st->transport_peers_max>=MAX_MOBILE_PEERS_MAX) {
1518         cfgfatal(loc,"site","mobile-peers-max must be in range 1.."
1519                  STRING(MAX_MOBILE_PEERS_MAX) "\n");
1520     }
1521
1522     if (st->key_lifetime < DEFAULT(KEY_RENEGOTIATE_GAP)*2)
1523         st->key_renegotiate_time=st->key_lifetime/2;
1524     else
1525         st->key_renegotiate_time=st->key_lifetime-DEFAULT(KEY_RENEGOTIATE_GAP);
1526     st->key_renegotiate_time=dict_read_number(
1527         dict,"renegotiate-time",False,"site",loc,st->key_renegotiate_time);
1528     if (st->key_renegotiate_time > st->key_lifetime) {
1529         cfgfatal(loc,"site",
1530                  "renegotiate-time must be less than key-lifetime\n");
1531     }
1532
1533     st->log_events=string_list_to_word(dict_lookup(dict,"log-events"),
1534                                        log_event_table,"site");
1535
1536     st->tunname=safe_malloc(strlen(st->localname)+strlen(st->remotename)+5,
1537                             "site_apply");
1538     sprintf(st->tunname,"%s<->%s",st->localname,st->remotename);
1539
1540     /* The information we expect to see in incoming messages of type 1 */
1541     /* fixme: lots of unchecked overflows here, but the results are only
1542        corrupted packets rather than undefined behaviour */
1543     st->setupsiglen=strlen(st->remotename)+strlen(st->localname)+8;
1544     st->setupsig=safe_malloc(st->setupsiglen,"site_apply");
1545     put_uint32(st->setupsig+0,LABEL_MSG1);
1546     put_uint16(st->setupsig+4,strlen(st->remotename));
1547     memcpy(&st->setupsig[6],st->remotename,strlen(st->remotename));
1548     put_uint16(st->setupsig+(6+strlen(st->remotename)),strlen(st->localname));
1549     memcpy(&st->setupsig[8+strlen(st->remotename)],st->localname,
1550            strlen(st->localname));
1551     st->setup_priority=(strcmp(st->localname,st->remotename)>0);
1552
1553     buffer_new(&st->buffer,SETUP_BUFFER_LEN);
1554
1555     buffer_new(&st->scratch,0);
1556     BUF_ALLOC(&st->scratch,"site:scratch");
1557
1558     /* We are interested in poll(), but only for timeouts. We don't have
1559        any fds of our own. */
1560     register_for_poll(st, site_beforepoll, site_afterpoll, 0, "site");
1561     st->timeout=0;
1562
1563     st->current.key_timeout=0;
1564     st->auxiliary_key.key_timeout=0;
1565     transport_peers_clear(st,&st->peers);
1566     transport_peers_clear(st,&st->setup_peers);
1567     /* XXX mlock these */
1568     st->dhsecret=safe_malloc(st->dh->len,"site:dhsecret");
1569     st->sharedsecretlen=st->transform->keylen?:st->dh->ceil_len;
1570     st->sharedsecret=safe_malloc(st->sharedsecretlen,"site:sharedsecret");
1571
1572     /* We need to compute some properties of our comms */
1573 #define COMPUTE_WORST(pad)                      \
1574     int worst_##pad=0;                          \
1575     for (i=0; i<st->ncomms; i++) {              \
1576         int thispad=st->comms[i]->pad;          \
1577         if (thispad > worst_##pad)              \
1578             worst_##pad=thispad;                \
1579     }
1580     COMPUTE_WORST(min_start_pad)
1581     COMPUTE_WORST(min_end_pad)
1582
1583     /* We need to register the remote networks with the netlink device */
1584     st->netlink->reg(st->netlink->st, site_outgoing, st,
1585                      st->transform->max_start_pad+(4*4)+
1586                      worst_min_start_pad,
1587                      st->transform->max_end_pad+worst_min_end_pad);
1588     
1589     for (i=0; i<st->ncomms; i++)
1590         st->comms[i]->request_notify(st->comms[i]->st, st, site_incoming);
1591
1592     st->current.transform=st->transform->create(st->transform->st);
1593     st->auxiliary_key.transform=st->transform->create(st->transform->st);
1594     st->new_transform=st->transform->create(st->transform->st);
1595     st->auxiliary_is_new=0;
1596
1597     enter_state_stop(st);
1598
1599     add_hook(PHASE_SHUTDOWN,site_phase_hook,st);
1600
1601     return new_closure(&st->cl);
1602 }
1603
1604 void site_module(dict_t *dict)
1605 {
1606     add_closure(dict,"site",site_apply);
1607 }
1608
1609
1610 /***** TRANSPORT PEERS definitions *****/
1611
1612 static void transport_peers_debug(struct site *st, transport_peers *dst,
1613                                   const char *didwhat,
1614                                   int nargs, const struct comm_addr *args,
1615                                   size_t stride) {
1616     int i;
1617     char *argp;
1618
1619     if (!(st->log_events & LOG_PEER_ADDRS))
1620         return; /* an optimisation */
1621
1622     slog(st, LOG_PEER_ADDRS, "peers (%s) %s nargs=%d => npeers=%d",
1623          (dst==&st->peers ? "data" :
1624           dst==&st->setup_peers ? "setup" : "UNKNOWN"),
1625          didwhat, nargs, dst->npeers);
1626
1627     for (i=0, argp=(void*)args;
1628          i<nargs;
1629          i++, (argp+=stride?stride:sizeof(*args))) {
1630         const struct comm_addr *ca=(void*)argp;
1631         slog(st, LOG_PEER_ADDRS, " args: addrs[%d]=%s",
1632              i, ca->comm->addr_to_string(ca->comm->st,ca));
1633     }
1634     for (i=0; i<dst->npeers; i++) {
1635         struct timeval diff;
1636         timersub(tv_now,&dst->peers[i].last,&diff);
1637         const struct comm_addr *ca=&dst->peers[i].addr;
1638         slog(st, LOG_PEER_ADDRS, " peers: addrs[%d]=%s T-%ld.%06ld",
1639              i, ca->comm->addr_to_string(ca->comm->st,ca),
1640              (unsigned long)diff.tv_sec, (unsigned long)diff.tv_usec);
1641     }
1642 }
1643
1644 static int transport_peer_compar(const void *av, const void *bv) {
1645     const transport_peer *a=av;
1646     const transport_peer *b=bv;
1647     /* put most recent first in the array */
1648     if (timercmp(&a->last, &b->last, <)) return +1;
1649     if (timercmp(&a->last, &b->last, >)) return -11;
1650     return 0;
1651 }
1652
1653 static void transport_peers_expire(struct site *st, transport_peers *peers) {
1654     /* peers must be sorted first */
1655     int previous_peers=peers->npeers;
1656     struct timeval oldest;
1657     oldest.tv_sec  = tv_now->tv_sec - st->mobile_peer_expiry;
1658     oldest.tv_usec = tv_now->tv_usec;
1659     while (peers->npeers>1 &&
1660            timercmp(&peers->peers[peers->npeers-1].last, &oldest, <))
1661         peers->npeers--;
1662     if (peers->npeers != previous_peers)
1663         transport_peers_debug(st,peers,"expire", 0,0,0);
1664 }
1665
1666 static void transport_record_peer(struct site *st, transport_peers *peers,
1667                                   const struct comm_addr *addr, const char *m) {
1668     int slot, changed=0;
1669
1670     for (slot=0; slot<peers->npeers; slot++)
1671         if (!memcmp(&peers->peers[slot].addr, addr, sizeof(*addr)))
1672             goto found;
1673
1674     changed=1;
1675     if (peers->npeers==st->transport_peers_max)
1676         slot=st->transport_peers_max;
1677     else
1678         slot=peers->npeers++;
1679
1680  found:
1681     peers->peers[slot].addr=*addr;
1682     peers->peers[slot].last=*tv_now;
1683
1684     if (peers->npeers>1)
1685         qsort(peers->peers, peers->npeers,
1686               sizeof(*peers->peers), transport_peer_compar);
1687
1688     if (changed || peers->npeers!=1)
1689         transport_peers_debug(st,peers,m, 1,addr,0);
1690     transport_peers_expire(st, peers);
1691 }
1692
1693 static bool_t transport_compute_setupinit_peers(struct site *st,
1694         const struct comm_addr *configured_addr /* 0 if none or not found */) {
1695
1696     if (!configured_addr && !transport_peers_valid(&st->peers))
1697         return False;
1698
1699     slog(st,LOG_SETUP_INIT,
1700          (!configured_addr ? "using only %d old peer address(es)"
1701           : "using configured address, and/or perhaps %d old peer address(es)"),
1702          st->peers);
1703
1704     /* Non-mobile peers havve st->peers.npeers==0 or ==1, since they
1705      * have transport_peers_max==1.  The effect is that this code
1706      * always uses the configured address if supplied, or otherwise
1707      * the existing data peer if one exists; this is as desired. */
1708
1709     transport_peers_copy(st,&st->setup_peers,&st->peers);
1710
1711     if (configured_addr)
1712         transport_record_peer(st,&st->setup_peers,configured_addr,"setupinit");
1713
1714     assert(transport_peers_valid(&st->setup_peers));
1715     return True;
1716 }
1717
1718 static void transport_setup_msgok(struct site *st, const struct comm_addr *a) {
1719     if (st->peer_mobile)
1720         transport_record_peer(st,&st->setup_peers,a,"setupmsg");
1721 }
1722 static void transport_data_msgok(struct site *st, const struct comm_addr *a) {
1723     if (st->peer_mobile)
1724         transport_record_peer(st,&st->peers,a,"datamsg");
1725 }
1726
1727 static int transport_peers_valid(transport_peers *peers) {
1728     return peers->npeers;
1729 }
1730 static void transport_peers_clear(struct site *st, transport_peers *peers) {
1731     peers->npeers= 0;
1732     transport_peers_debug(st,peers,"clear",0,0,0);
1733 }
1734 static void transport_peers_copy(struct site *st, transport_peers *dst,
1735                                  const transport_peers *src) {
1736     dst->npeers=src->npeers;
1737     memcpy(dst->peers, src->peers, sizeof(*dst->peers) * dst->npeers);
1738     transport_peers_debug(st,dst,"copy",
1739                           src->npeers, &src->peers->addr, sizeof(*src->peers));
1740 }
1741
1742 void transport_xmit(struct site *st, transport_peers *peers,
1743                     struct buffer_if *buf, bool_t candebug) {
1744     int slot;
1745     transport_peers_expire(st, peers);
1746     for (slot=0; slot<peers->npeers; slot++) {
1747         transport_peer *peer=&peers->peers[slot];
1748         if (candebug)
1749             dump_packet(st, buf, &peer->addr, False);
1750         peer->addr.comm->sendmsg(peer->addr.comm->st, buf, &peer->addr);
1751     }
1752 }
1753
1754 /***** END of transport peers declarations *****/