chiark / gitweb /
Exit nonzero if any unknown options are provided on the command line.
[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 3600000 /* One hour */
31 #define DEFAULT_KEY_RENEGOTIATE_GAP 300000 /* Five minutes */
32 #define DEFAULT_SETUP_RETRIES 5
33 #define DEFAULT_SETUP_TIMEOUT 2000
34 #define DEFAULT_WAIT_TIME 20000
35
36 /* Each site can be in one of several possible states. */
37
38 /* States:
39    SITE_STOP         - nothing is allowed to happen; tunnel is down;
40                        all session keys have been erased
41      -> SITE_RUN upon external instruction
42    SITE_RUN          - site up, maybe with valid key
43      -> SITE_RESOLVE upon outgoing packet and no valid key
44          we start name resolution for the other end of the tunnel
45      -> SITE_SENTMSG2 upon valid incoming message 1 and suitable time
46          we send an appropriate message 2
47    SITE_RESOLVE      - waiting for name resolution
48      -> SITE_SENTMSG1 upon successful resolution
49          we send an appropriate message 1
50      -> SITE_SENTMSG2 upon valid incoming message 1 (then abort resolution)
51          we abort resolution and 
52      -> SITE_WAIT on timeout or resolution failure
53    SITE_SENTMSG1
54      -> SITE_SENTMSG2 upon valid incoming message 1 from higher priority end
55      -> SITE_SENTMSG3 upon valid incoming message 2
56      -> SITE_WAIT on timeout
57    SITE_SENTMSG2
58      -> SITE_SENTMSG4 upon valid incoming message 3
59      -> SITE_WAIT on timeout
60    SITE_SENTMSG3
61      -> SITE_SENTMSG5 upon valid incoming message 4
62      -> SITE_WAIT on timeout
63    SITE_SENTMSG4
64      -> SITE_RUN upon valid incoming message 5
65      -> SITE_WAIT on timeout
66    SITE_SENTMSG5
67      -> SITE_RUN upon valid incoming message 6
68      -> SITE_WAIT on timeout
69    SITE_WAIT         - failed to establish key; do nothing for a while
70      -> SITE_RUN on timeout
71    */
72
73 #define SITE_STOP     0
74 #define SITE_RUN      1
75 #define SITE_RESOLVE  2
76 #define SITE_SENTMSG1 3
77 #define SITE_SENTMSG2 4
78 #define SITE_SENTMSG3 5
79 #define SITE_SENTMSG4 6
80 #define SITE_SENTMSG5 7
81 #define SITE_WAIT     8
82
83 static cstring_t state_name(uint32_t state)
84 {
85     switch (state) {
86     case 0: return "STOP";
87     case 1: return "RUN";
88     case 2: return "RESOLVE";
89     case 3: return "SENTMSG1";
90     case 4: return "SENTMSG2";
91     case 5: return "SENTMSG3";
92     case 6: return "SENTMSG4";
93     case 7: return "SENTMSG5";
94     case 8: return "WAIT";
95     default: return "*bad state*";
96     }
97 }
98
99 #define NONCELEN 8
100
101 #define LOG_UNEXPECTED    0x00000001
102 #define LOG_SETUP_INIT    0x00000002
103 #define LOG_SETUP_TIMEOUT 0x00000004
104 #define LOG_ACTIVATE_KEY  0x00000008
105 #define LOG_TIMEOUT_KEY   0x00000010
106 #define LOG_SEC           0x00000020
107 #define LOG_STATE         0x00000040
108 #define LOG_DROP          0x00000080
109 #define LOG_DUMP          0x00000100
110 #define LOG_ERROR         0x00000400
111
112 static struct flagstr log_event_table[]={
113     { "unexpected", LOG_UNEXPECTED },
114     { "setup-init", LOG_SETUP_INIT },
115     { "setup-timeout", LOG_SETUP_TIMEOUT },
116     { "activate-key", LOG_ACTIVATE_KEY },
117     { "timeout-key", LOG_TIMEOUT_KEY },
118     { "security", LOG_SEC },
119     { "state-change", LOG_STATE },
120     { "packet-drop", LOG_DROP },
121     { "dump-packets", LOG_DUMP },
122     { "errors", LOG_ERROR },
123     { "default", LOG_SETUP_INIT|LOG_SETUP_TIMEOUT|
124       LOG_ACTIVATE_KEY|LOG_TIMEOUT_KEY|LOG_SEC|LOG_ERROR },
125     { "all", 0xffffffff },
126     { NULL, 0 }
127 };
128
129 struct site {
130     closure_t cl;
131     struct site_if ops;
132 /* configuration information */
133     string_t localname;
134     string_t remotename;
135     string_t tunname; /* localname<->remotename by default, used in logs */
136     string_t address; /* DNS name for bootstrapping, optional */
137     int remoteport; /* Port for bootstrapping, optional */
138     struct netlink_if *netlink;
139     struct comm_if *comm;
140     struct resolver_if *resolver;
141     struct log_if *log;
142     struct random_if *random;
143     struct rsaprivkey_if *privkey;
144     struct rsapubkey_if *pubkey;
145     struct transform_if *transform;
146     struct dh_if *dh;
147     struct hash_if *hash;
148
149     uint32_t index; /* Index of this site */
150     int32_t setup_retries; /* How many times to send setup packets */
151     int32_t setup_timeout; /* Initial timeout for setup packets */
152     int32_t wait_timeout; /* How long to wait if setup unsuccessful */
153     int32_t key_lifetime; /* How long a key lasts once set up */
154     int32_t key_renegotiate_time; /* If we see traffic (or a keepalive)
155                                       after this time, initiate a new
156                                       key exchange */
157     bool_t keepalive; /* Send keepalives to detect peer failure (not yet
158                          implemented) */
159
160     uint8_t *setupsig; /* Expected signature of incoming MSG1 packets */
161     int32_t setupsiglen; /* Allows us to discard packets quickly if
162                             they are not for us */
163     bool_t setup_priority; /* Do we have precedence if both sites emit
164                               message 1 simultaneously? */
165     uint32_t log_events;
166
167 /* runtime information */
168     uint32_t state;
169     uint64_t now; /* Most recently seen time */
170
171     /* The currently established session */
172     uint32_t remote_session_id;
173     struct transform_inst_if *current_transform;
174     bool_t current_valid;
175     uint64_t current_key_timeout; /* End of life of current key */
176     uint64_t renegotiate_key_time; /* When we can negotiate a new key */
177     struct sockaddr_in peer; /* Current address of peer */
178     bool_t peer_valid; /* Peer address becomes invalid when key times out,
179                           but only if we have a DNS name for our peer */
180
181     /* The current key setup protocol exchange.  We can only be
182        involved in one of these at a time.  There's a potential for
183        denial of service here (the attacker keeps sending a setup
184        packet; we keep trying to continue the exchange, and have to
185        timeout before we can listen for another setup packet); perhaps
186        we should keep a list of 'bad' sources for setup packets. */
187     uint32_t setup_session_id;
188     struct sockaddr_in setup_peer;
189     uint8_t localN[NONCELEN]; /* Nonces for key exchange */
190     uint8_t remoteN[NONCELEN];
191     struct buffer_if buffer; /* Current outgoing key exchange packet */
192     int32_t retries; /* Number of retries remaining */
193     uint64_t timeout; /* Timeout for current state */
194     uint8_t *dhsecret;
195     uint8_t *sharedsecret;
196     struct transform_inst_if *new_transform; /* For key setup/verify */
197 };
198
199 static void slog(struct site *st, uint32_t event, cstring_t msg, ...)
200 {
201     va_list ap;
202     char buf[240];
203     uint32_t class;
204
205     va_start(ap,msg);
206
207     if (event&st->log_events) {
208         switch(event) {
209         case LOG_UNEXPECTED: class=M_INFO; break;
210         case LOG_SETUP_INIT: class=M_INFO; break;
211         case LOG_SETUP_TIMEOUT: class=M_NOTICE; break;
212         case LOG_ACTIVATE_KEY: class=M_INFO; break;
213         case LOG_TIMEOUT_KEY: class=M_INFO; break;
214         case LOG_SEC: class=M_SECURITY; break;
215         case LOG_STATE: class=M_DEBUG; break;
216         case LOG_DROP: class=M_DEBUG; break;
217         case LOG_DUMP: class=M_DEBUG; break;
218         case LOG_ERROR: class=M_ERR; break;
219         default: class=M_ERR; break;
220         }
221
222         vsnprintf(buf,sizeof(buf),msg,ap);
223         st->log->log(st->log->st,class,"%s: %s",st->tunname,buf);
224     }
225     va_end(ap);
226 }
227
228 static void set_link_quality(struct site *st);
229 static void delete_key(struct site *st, cstring_t reason, uint32_t loglevel);
230 static bool_t initiate_key_setup(struct site *st, cstring_t reason);
231 static void enter_state_run(struct site *st);
232 static bool_t enter_state_resolve(struct site *st);
233 static bool_t enter_new_state(struct site *st,uint32_t next);
234 static void enter_state_wait(struct site *st);
235
236 #define CHECK_AVAIL(b,l) do { if ((b)->size<(l)) return False; } while(0)
237 #define CHECK_EMPTY(b) do { if ((b)->size!=0) return False; } while(0)
238 #define CHECK_TYPE(b,t) do { uint32_t type; \
239     CHECK_AVAIL((b),4); \
240     type=buf_unprepend_uint32((b)); \
241     if (type!=(t)) return False; } while(0)
242
243 struct msg {
244     uint8_t *hashstart;
245     uint32_t dest;
246     uint32_t source;
247     int32_t remlen;
248     uint8_t *remote;
249     int32_t loclen;
250     uint8_t *local;
251     uint8_t *nR;
252     uint8_t *nL;
253     int32_t pklen;
254     char *pk;
255     int32_t hashlen;
256     int32_t siglen;
257     char *sig;
258 };
259
260 /* Build any of msg1 to msg4. msg5 and msg6 are built from the inside
261    out using a transform of config data supplied by netlink */
262 static bool_t generate_msg(struct site *st, uint32_t type, cstring_t what)
263 {
264     void *hst;
265     uint8_t *hash;
266     string_t dhpub, sig;
267
268     st->retries=st->setup_retries;
269     BUF_ALLOC(&st->buffer,what);
270     buffer_init(&st->buffer,0);
271     buf_append_uint32(&st->buffer,
272         (type==LABEL_MSG1?0:st->setup_session_id));
273     buf_append_uint32(&st->buffer,st->index);
274     buf_append_uint32(&st->buffer,type);
275     buf_append_string(&st->buffer,st->localname);
276     buf_append_string(&st->buffer,st->remotename);
277     memcpy(buf_append(&st->buffer,NONCELEN),st->localN,NONCELEN);
278     if (type==LABEL_MSG1) return True;
279     memcpy(buf_append(&st->buffer,NONCELEN),st->remoteN,NONCELEN);
280     if (type==LABEL_MSG2) return True;
281
282     if (hacky_par_mid_failnow()) return False;
283
284     dhpub=st->dh->makepublic(st->dh->st,st->dhsecret,st->dh->len);
285     buf_append_string(&st->buffer,dhpub);
286     free(dhpub);
287     hash=safe_malloc(st->hash->len, "generate_msg");
288     hst=st->hash->init();
289     st->hash->update(hst,st->buffer.start,st->buffer.size);
290     st->hash->final(hst,hash);
291     sig=st->privkey->sign(st->privkey->st,hash,st->hash->len);
292     buf_append_string(&st->buffer,sig);
293     free(sig);
294     free(hash);
295     return True;
296 }
297
298 static bool_t unpick_msg(struct site *st, uint32_t type,
299                          struct buffer_if *msg, struct msg *m)
300 {
301     m->hashstart=msg->start;
302     CHECK_AVAIL(msg,4);
303     m->dest=buf_unprepend_uint32(msg);
304     CHECK_AVAIL(msg,4);
305     m->source=buf_unprepend_uint32(msg);
306     CHECK_TYPE(msg,type);
307     CHECK_AVAIL(msg,2);
308     m->remlen=buf_unprepend_uint16(msg);
309     CHECK_AVAIL(msg,m->remlen);
310     m->remote=buf_unprepend(msg,m->remlen);
311     CHECK_AVAIL(msg,2);
312     m->loclen=buf_unprepend_uint16(msg);
313     CHECK_AVAIL(msg,m->loclen);
314     m->local=buf_unprepend(msg,m->loclen);
315     CHECK_AVAIL(msg,NONCELEN);
316     m->nR=buf_unprepend(msg,NONCELEN);
317     if (type==LABEL_MSG1) {
318         CHECK_EMPTY(msg);
319         return True;
320     }
321     CHECK_AVAIL(msg,NONCELEN);
322     m->nL=buf_unprepend(msg,NONCELEN);
323     if (type==LABEL_MSG2) {
324         CHECK_EMPTY(msg);
325         return True;
326     }
327     CHECK_AVAIL(msg,2);
328     m->pklen=buf_unprepend_uint16(msg);
329     CHECK_AVAIL(msg,m->pklen);
330     m->pk=buf_unprepend(msg,m->pklen);
331     m->hashlen=msg->start-m->hashstart;
332     CHECK_AVAIL(msg,2);
333     m->siglen=buf_unprepend_uint16(msg);
334     CHECK_AVAIL(msg,m->siglen);
335     m->sig=buf_unprepend(msg,m->siglen);
336     CHECK_EMPTY(msg);
337     return True;
338 }
339
340 static bool_t check_msg(struct site *st, uint32_t type, struct msg *m,
341                         cstring_t *error)
342 {
343     if (type==LABEL_MSG1) return True;
344
345     /* Check that the site names and our nonce have been sent
346        back correctly, and then store our peer's nonce. */ 
347     if (memcmp(m->remote,st->remotename,strlen(st->remotename)!=0)) {
348         *error="wrong remote site name";
349         return False;
350     }
351     if (memcmp(m->local,st->localname,strlen(st->localname)!=0)) {
352         *error="wrong local site name";
353         return False;
354     }
355     if (memcmp(m->nL,st->localN,NONCELEN)!=0) {
356         *error="wrong locally-generated nonce";
357         return False;
358     }
359     if (type==LABEL_MSG2) return True;
360     if (memcmp(m->nR,st->remoteN,NONCELEN)!=0) {
361         *error="wrong remotely-generated nonce";
362         return False;
363     }
364     if (type==LABEL_MSG3) return True;
365     if (type==LABEL_MSG4) return True;
366     *error="unknown message type";
367     return False;
368 }
369
370 static bool_t generate_msg1(struct site *st)
371 {
372     st->random->generate(st->random->st,NONCELEN,st->localN);
373     return generate_msg(st,LABEL_MSG1,"site:MSG1");
374 }
375
376 static bool_t process_msg1(struct site *st, struct buffer_if *msg1,
377                            struct sockaddr_in *src)
378 {
379     struct msg m;
380
381     /* We've already determined we're in an appropriate state to
382        process an incoming MSG1, and that the MSG1 has correct values
383        of A and B. */
384
385     if (!unpick_msg(st,LABEL_MSG1,msg1,&m)) return False;
386
387     st->setup_peer=*src;
388     st->setup_session_id=m.source;
389     memcpy(st->remoteN,m.nR,NONCELEN);
390     return True;
391 }
392
393 static bool_t generate_msg2(struct site *st)
394 {
395     st->random->generate(st->random->st,NONCELEN,st->localN);
396     return generate_msg(st,LABEL_MSG2,"site:MSG2");
397 }
398
399 static bool_t process_msg2(struct site *st, struct buffer_if *msg2,
400                            struct sockaddr_in *src)
401 {
402     struct msg m;
403     cstring_t err;
404
405     if (!unpick_msg(st,LABEL_MSG2,msg2,&m)) return False;
406     if (!check_msg(st,LABEL_MSG2,&m,&err)) {
407         slog(st,LOG_SEC,"msg2: %s",err);
408         return False;
409     }
410     st->setup_session_id=m.source;
411     memcpy(st->remoteN,m.nR,NONCELEN);
412     return True;
413 }
414
415 static bool_t generate_msg3(struct site *st)
416 {
417     /* Now we have our nonce and their nonce. Think of a secret key,
418        and create message number 3. */
419     st->random->generate(st->random->st,st->dh->len,st->dhsecret);
420     return generate_msg(st,LABEL_MSG3,"site:MSG3");
421 }
422
423 static bool_t process_msg3(struct site *st, struct buffer_if *msg3,
424                            struct sockaddr_in *src)
425 {
426     struct msg m;
427     uint8_t *hash;
428     void *hst;
429     cstring_t err;
430
431     if (!unpick_msg(st,LABEL_MSG3,msg3,&m)) return False;
432     if (!check_msg(st,LABEL_MSG3,&m,&err)) {
433         slog(st,LOG_SEC,"msg3: %s",err);
434         return False;
435     }
436
437     /* Check signature and store g^x mod m */
438     hash=safe_malloc(st->hash->len, "process_msg3");
439     hst=st->hash->init();
440     st->hash->update(hst,m.hashstart,m.hashlen);
441     st->hash->final(hst,hash);
442     /* Terminate signature with a '0' - cheating, but should be ok */
443     m.sig[m.siglen]=0;
444     if (!st->pubkey->check(st->pubkey->st,hash,st->hash->len,m.sig)) {
445         slog(st,LOG_SEC,"msg3 signature failed check!");
446         free(hash);
447         return False;
448     }
449     free(hash);
450
451     /* Terminate their DH public key with a '0' */
452     m.pk[m.pklen]=0;
453     /* Invent our DH secret key */
454     st->random->generate(st->random->st,st->dh->len,st->dhsecret);
455
456     /* Generate the shared key */
457     st->dh->makeshared(st->dh->st,st->dhsecret,st->dh->len,m.pk,
458                        st->sharedsecret,st->transform->keylen);
459
460     /* Set up the transform */
461     st->new_transform->setkey(st->new_transform->st,st->sharedsecret,
462                               st->transform->keylen);
463
464     return True;
465 }
466
467 static bool_t generate_msg4(struct site *st)
468 {
469     /* We have both nonces, their public key and our private key. Generate
470        our public key, sign it and send it to them. */
471     return generate_msg(st,LABEL_MSG4,"site:MSG4");
472 }
473
474 static bool_t process_msg4(struct site *st, struct buffer_if *msg4,
475                            struct sockaddr_in *src)
476 {
477     struct msg m;
478     uint8_t *hash;
479     void *hst;
480     cstring_t err;
481
482     if (!unpick_msg(st,LABEL_MSG4,msg4,&m)) return False;
483     if (!check_msg(st,LABEL_MSG4,&m,&err)) {
484         slog(st,LOG_SEC,"msg4: %s",err);
485         return False;
486     }
487     
488     /* Check signature and store g^x mod m */
489     hash=safe_malloc(st->hash->len, "process_msg4");
490     hst=st->hash->init();
491     st->hash->update(hst,m.hashstart,m.hashlen);
492     st->hash->final(hst,hash);
493     /* Terminate signature with a '0' - cheating, but should be ok */
494     m.sig[m.siglen]=0;
495     if (!st->pubkey->check(st->pubkey->st,hash,st->hash->len,m.sig)) {
496         slog(st,LOG_SEC,"msg4 signature failed check!");
497         free(hash);
498         return False;
499     }
500     free(hash);
501
502     /* Terminate their DH public key with a '0' */
503     m.pk[m.pklen]=0;
504     /* Generate the shared key */
505     st->dh->makeshared(st->dh->st,st->dhsecret,st->dh->len,m.pk,
506                        st->sharedsecret,st->transform->keylen);
507     /* Set up the transform */
508     st->new_transform->setkey(st->new_transform->st,st->sharedsecret,
509                               st->transform->keylen);
510
511     return True;
512 }
513
514 struct msg0 {
515     uint32_t dest;
516     uint32_t source;
517     uint32_t type;
518 };
519
520 static bool_t unpick_msg0(struct site *st, struct buffer_if *msg0,
521                           struct msg0 *m)
522 {
523     CHECK_AVAIL(msg0,4);
524     m->dest=buf_unprepend_uint32(msg0);
525     CHECK_AVAIL(msg0,4);
526     m->source=buf_unprepend_uint32(msg0);
527     CHECK_AVAIL(msg0,4);
528     m->type=buf_unprepend_uint32(msg0);
529     return True;
530     /* Leaves transformed part of buffer untouched */
531 }
532
533 static bool_t generate_msg5(struct site *st)
534 {
535     cstring_t transform_err;
536
537     BUF_ALLOC(&st->buffer,"site:MSG5");
538     /* We are going to add four words to the message */
539     buffer_init(&st->buffer,st->transform->max_start_pad+(4*4));
540     /* Give the netlink code an opportunity to put its own stuff in the
541        message (configuration information, etc.) */
542     st->netlink->output_config(st->netlink->st,&st->buffer);
543     buf_prepend_uint32(&st->buffer,LABEL_MSG5);
544     st->new_transform->forwards(st->new_transform->st,&st->buffer,
545                                 &transform_err);
546     buf_prepend_uint32(&st->buffer,LABEL_MSG5);
547     buf_prepend_uint32(&st->buffer,st->index);
548     buf_prepend_uint32(&st->buffer,st->setup_session_id);
549
550     st->retries=st->setup_retries;
551     return True;
552 }
553
554 static bool_t process_msg5(struct site *st, struct buffer_if *msg5,
555                            struct sockaddr_in *src)
556 {
557     struct msg0 m;
558     cstring_t transform_err;
559
560     if (!unpick_msg0(st,msg5,&m)) return False;
561
562     if (st->new_transform->reverse(st->new_transform->st,
563                                    msg5,&transform_err)) {
564         /* There's a problem */
565         slog(st,LOG_SEC,"process_msg5: transform: %s",transform_err);
566         return False;
567     }
568     /* Buffer should now contain untransformed PING packet data */
569     CHECK_AVAIL(msg5,4);
570     if (buf_unprepend_uint32(msg5)!=LABEL_MSG5) {
571         slog(st,LOG_SEC,"MSG5/PING packet contained wrong label");
572         return False;
573     }
574     if (!st->netlink->check_config(st->netlink->st,msg5)) {
575         slog(st,LOG_SEC,"MSG5/PING packet contained bad netlink config");
576         return False;
577     }
578     CHECK_EMPTY(msg5);
579     return True;
580 }
581
582 static bool_t generate_msg6(struct site *st)
583 {
584     cstring_t transform_err;
585
586     BUF_ALLOC(&st->buffer,"site:MSG6");
587     /* We are going to add four words to the message */
588     buffer_init(&st->buffer,st->transform->max_start_pad+(4*4));
589     /* Give the netlink code an opportunity to put its own stuff in the
590        message (configuration information, etc.) */
591     st->netlink->output_config(st->netlink->st,&st->buffer);
592     buf_prepend_uint32(&st->buffer,LABEL_MSG6);
593     st->new_transform->forwards(st->new_transform->st,&st->buffer,
594                                 &transform_err);
595     buf_prepend_uint32(&st->buffer,LABEL_MSG6);
596     buf_prepend_uint32(&st->buffer,st->index);
597     buf_prepend_uint32(&st->buffer,st->setup_session_id);
598
599     st->retries=1; /* Peer will retransmit MSG5 if this packet gets lost */
600     return True;
601 }
602
603 static bool_t process_msg6(struct site *st, struct buffer_if *msg6,
604                            struct sockaddr_in *src)
605 {
606     struct msg0 m;
607     cstring_t transform_err;
608
609     if (!unpick_msg0(st,msg6,&m)) return False;
610
611     if (st->new_transform->reverse(st->new_transform->st,
612                                    msg6,&transform_err)) {
613         /* There's a problem */
614         slog(st,LOG_SEC,"process_msg6: transform: %s",transform_err);
615         return False;
616     }
617     /* Buffer should now contain untransformed PING packet data */
618     CHECK_AVAIL(msg6,4);
619     if (buf_unprepend_uint32(msg6)!=LABEL_MSG6) {
620         slog(st,LOG_SEC,"MSG6/PONG packet contained invalid data");
621         return False;
622     }
623     if (!st->netlink->check_config(st->netlink->st,msg6)) {
624         slog(st,LOG_SEC,"MSG6/PONG packet contained bad netlink config");
625         return False;
626     }
627     CHECK_EMPTY(msg6);
628     return True;
629 }
630
631 static bool_t process_msg0(struct site *st, struct buffer_if *msg0,
632                            struct sockaddr_in *src)
633 {
634     struct msg0 m;
635     cstring_t transform_err;
636     uint32_t type;
637
638     if (!st->current_valid) {
639         slog(st,LOG_DROP,"incoming message but no current key -> dropping");
640         return initiate_key_setup(st,"incoming message but no current key");
641     }
642
643     if (!unpick_msg0(st,msg0,&m)) return False;
644
645     if (st->current_transform->reverse(st->current_transform->st,
646                                        msg0,&transform_err)) {
647         /* There's a problem */
648         slog(st,LOG_SEC,"transform: %s",transform_err);
649         return initiate_key_setup(st,"incoming message would not decrypt");
650     }
651     CHECK_AVAIL(msg0,4);
652     type=buf_unprepend_uint32(msg0);
653     switch(type) {
654     case LABEL_MSG7:
655         /* We must forget about the current session. */
656         delete_key(st,"request from peer",LOG_SEC);
657         return True;
658         break;
659     case LABEL_MSG9:
660         /* Deliver to netlink layer */
661         st->netlink->deliver(st->netlink->st,msg0);
662         return True;
663         break;
664     default:
665         slog(st,LOG_SEC,"incoming encrypted message of type %08x "
666              "(unknown)",type);
667         break;
668     }
669     return False;
670 }
671
672 static void dump_packet(struct site *st, struct buffer_if *buf,
673                         struct sockaddr_in *addr, bool_t incoming)
674 {
675     uint32_t dest=ntohl(*(uint32_t *)buf->start);
676     uint32_t source=ntohl(*(uint32_t *)(buf->start+4));
677     uint32_t msgtype=ntohl(*(uint32_t *)(buf->start+8));
678
679     if (st->log_events & LOG_DUMP)
680         slilog(st->log,M_DEBUG,"%s: %s: %08x<-%08x: %08x:",
681                st->tunname,incoming?"incoming":"outgoing",
682                dest,source,msgtype);
683 }
684
685 static uint32_t site_status(void *st)
686 {
687     return 0;
688 }
689
690 static bool_t send_msg(struct site *st)
691 {
692     if (st->retries>0) {
693         dump_packet(st,&st->buffer,&st->setup_peer,False);
694         st->comm->sendmsg(st->comm->st,&st->buffer,&st->setup_peer);
695         st->timeout=st->now+st->setup_timeout;
696         st->retries--;
697         return True;
698     } else {
699         slog(st,LOG_SETUP_TIMEOUT,"timed out sending key setup packet "
700             "(in state %s)",state_name(st->state));
701         enter_state_wait(st);
702         return False;
703     }
704 }
705
706 static void site_resolve_callback(void *sst, struct in_addr *address)
707 {
708     struct site *st=sst;
709
710     if (st->state!=SITE_RESOLVE) {
711         slog(st,LOG_UNEXPECTED,"site_resolve_callback called unexpectedly");
712         return;
713     }
714     if (address) {
715         memset(&st->setup_peer,0,sizeof(st->setup_peer));
716         st->setup_peer.sin_family=AF_INET;
717         st->setup_peer.sin_port=htons(st->remoteport);
718         st->setup_peer.sin_addr=*address;
719         enter_new_state(st,SITE_SENTMSG1);
720     } else {
721         /* Resolution failed */
722         slog(st,LOG_ERROR,"resolution of %s failed",st->address);
723         enter_state_run(st);
724     }
725 }
726
727 static bool_t initiate_key_setup(struct site *st, cstring_t reason)
728 {
729     if (st->state!=SITE_RUN) return False;
730     slog(st,LOG_SETUP_INIT,"initiating key exchange (%s)",reason);
731     if (st->address) {
732         slog(st,LOG_SETUP_INIT,"resolving peer address");
733         return enter_state_resolve(st);
734     } else if (st->peer_valid) {
735         slog(st,LOG_SETUP_INIT,"using old peer address");
736         st->setup_peer=st->peer;
737         return enter_new_state(st,SITE_SENTMSG1);
738     }
739     slog(st,LOG_SETUP_INIT,"key exchange failed: no address for peer");
740     return False;
741 }
742
743 static void activate_new_key(struct site *st)
744 {
745     struct transform_inst_if *t;
746
747     /* We have two transform instances, which we swap between active
748        and setup */
749     t=st->current_transform;
750     st->current_transform=st->new_transform;
751     st->new_transform=t;
752
753     t->delkey(t->st);
754     st->timeout=0;
755     st->current_valid=True;
756     st->current_key_timeout=st->now+st->key_lifetime;
757     st->renegotiate_key_time=st->now+st->key_renegotiate_time;
758     st->peer=st->setup_peer;
759     st->peer_valid=True;
760     st->remote_session_id=st->setup_session_id;
761
762     slog(st,LOG_ACTIVATE_KEY,"new key activated");
763     enter_state_run(st);
764 }
765
766 static void delete_key(struct site *st, cstring_t reason, uint32_t loglevel)
767 {
768     if (st->current_valid) {
769         slog(st,loglevel,"session closed (%s)",reason);
770
771         st->current_valid=False;
772         st->current_transform->delkey(st->current_transform->st);
773         st->current_key_timeout=0;
774         set_link_quality(st);
775     }
776 }
777
778 static void state_assert(struct site *st, bool_t ok)
779 {
780     if (!ok) fatal("site:state_assert");
781 }
782
783 static void enter_state_stop(struct site *st)
784 {
785     st->state=SITE_STOP;
786     st->timeout=0;
787     delete_key(st,"entering state STOP",LOG_TIMEOUT_KEY);
788     st->new_transform->delkey(st->new_transform->st);
789 }
790
791 static void set_link_quality(struct site *st)
792 {
793     uint32_t quality;
794     if (st->current_valid)
795         quality=LINK_QUALITY_UP;
796     else if (st->state==SITE_WAIT || st->state==SITE_STOP)
797         quality=LINK_QUALITY_DOWN;
798     else if (st->address)
799         quality=LINK_QUALITY_DOWN_CURRENT_ADDRESS;
800     else if (st->peer_valid)
801         quality=LINK_QUALITY_DOWN_STALE_ADDRESS;
802     else
803         quality=LINK_QUALITY_DOWN;
804
805     st->netlink->set_quality(st->netlink->st,quality);
806 }
807
808 static void enter_state_run(struct site *st)
809 {
810     slog(st,LOG_STATE,"entering state RUN");
811     st->state=SITE_RUN;
812     st->timeout=0;
813
814     st->setup_session_id=0;
815     memset(&st->setup_peer,0,sizeof(st->setup_peer));
816     memset(st->localN,0,NONCELEN);
817     memset(st->remoteN,0,NONCELEN);
818     st->new_transform->delkey(st->new_transform->st);
819     memset(st->dhsecret,0,st->dh->len);
820     memset(st->sharedsecret,0,st->transform->keylen);
821     set_link_quality(st);
822 }
823
824 static bool_t enter_state_resolve(struct site *st)
825 {
826     state_assert(st,st->state==SITE_RUN);
827     slog(st,LOG_STATE,"entering state RESOLVE");
828     st->state=SITE_RESOLVE;
829     st->resolver->request(st->resolver->st,st->address,
830                           site_resolve_callback,st);
831     return True;
832 }
833
834 static bool_t enter_new_state(struct site *st, uint32_t next)
835 {
836     bool_t (*gen)(struct site *st);
837     int r;
838
839     slog(st,LOG_STATE,"entering state %s",state_name(next));
840     switch(next) {
841     case SITE_SENTMSG1:
842         state_assert(st,st->state==SITE_RUN || st->state==SITE_RESOLVE);
843         gen=generate_msg1;
844         break;
845     case SITE_SENTMSG2:
846         state_assert(st,st->state==SITE_RUN || st->state==SITE_RESOLVE ||
847                      st->state==SITE_SENTMSG1 || st->state==SITE_WAIT);
848         gen=generate_msg2;
849         break;
850     case SITE_SENTMSG3:
851         state_assert(st,st->state==SITE_SENTMSG1);
852         BUF_FREE(&st->buffer);
853         gen=generate_msg3;
854         break;
855     case SITE_SENTMSG4:
856         state_assert(st,st->state==SITE_SENTMSG2);
857         BUF_FREE(&st->buffer);
858         gen=generate_msg4;
859         break;
860     case SITE_SENTMSG5:
861         state_assert(st,st->state==SITE_SENTMSG3);
862         BUF_FREE(&st->buffer);
863         gen=generate_msg5;
864         break;
865     case SITE_RUN:
866         state_assert(st,st->state==SITE_SENTMSG4);
867         BUF_FREE(&st->buffer);
868         gen=generate_msg6;
869         break;
870     default:
871         gen=NULL;
872         fatal("enter_new_state(%s): invalid new state",state_name(next));
873         break;
874     }
875
876     if (hacky_par_start_failnow()) return False;
877
878     r= gen(st) && send_msg(st);
879
880     hacky_par_end(&r,
881                   st->setup_retries, st->setup_timeout,
882                   send_msg, st);
883     
884     if (r) {
885         st->state=next;
886         if (next==SITE_RUN) {
887             BUF_FREE(&st->buffer); /* Never reused */
888             st->timeout=0; /* Never retransmit */
889             activate_new_key(st);
890         }
891         return True;
892     }
893     slog(st,LOG_ERROR,"error entering state %s",state_name(next));
894     st->buffer.free=False; /* Unconditionally use the buffer; it may be
895                               in either state, and enter_state_wait() will
896                               do a BUF_FREE() */
897     enter_state_wait(st);
898     return False;
899 }
900
901 /* msg7 tells our peer that we're about to forget our key */
902 static bool_t send_msg7(struct site *st, cstring_t reason)
903 {
904     cstring_t transform_err;
905
906     if (st->current_valid && st->peer_valid && st->buffer.free) {
907         BUF_ALLOC(&st->buffer,"site:MSG7");
908         buffer_init(&st->buffer,st->transform->max_start_pad+(4*3));
909         buf_append_uint32(&st->buffer,LABEL_MSG7);
910         buf_append_string(&st->buffer,reason);
911         st->current_transform->forwards(st->current_transform->st,
912                                         &st->buffer, &transform_err);
913         buf_prepend_uint32(&st->buffer,LABEL_MSG0);
914         buf_prepend_uint32(&st->buffer,st->index);
915         buf_prepend_uint32(&st->buffer,st->remote_session_id);
916         st->comm->sendmsg(st->comm->st,&st->buffer,&st->peer);
917         BUF_FREE(&st->buffer);
918         return True;
919     }
920     return False;
921 }
922
923 /* We go into this state if our peer becomes uncommunicative. Similar to
924    the "stop" state, we forget all session keys for a while, before
925    re-entering the "run" state. */
926 static void enter_state_wait(struct site *st)
927 {
928     slog(st,LOG_STATE,"entering state WAIT");
929     st->timeout=st->now+st->wait_timeout;
930     st->state=SITE_WAIT;
931     st->peer_valid=False;
932     set_link_quality(st);
933     BUF_FREE(&st->buffer); /* will have had an outgoing packet in it */
934     /* XXX Erase keys etc. */
935 }
936
937 static inline void site_settimeout(uint64_t timeout, int *timeout_io)
938 {
939     if (timeout) {
940         int64_t offset=timeout-*now;
941         if (offset<0) offset=0;
942         if (offset>INT_MAX) offset=INT_MAX;
943         if (*timeout_io<0 || offset<*timeout_io)
944             *timeout_io=offset;
945     }
946 }
947
948 static int site_beforepoll(void *sst, struct pollfd *fds, int *nfds_io,
949                            int *timeout_io)
950 {
951     struct site *st=sst;
952
953     *nfds_io=0; /* We don't use any file descriptors */
954     st->now=*now;
955
956     /* Work out when our next timeout is. The earlier of 'timeout' or
957        'current_key_timeout'. A stored value of '0' indicates no timeout
958        active. */
959     site_settimeout(st->timeout, timeout_io);
960     site_settimeout(st->current_key_timeout, timeout_io);
961
962     return 0; /* success */
963 }
964
965 /* NB site_afterpoll will be called before site_beforepoll is ever called */
966 static void site_afterpoll(void *sst, struct pollfd *fds, int nfds)
967 {
968     struct site *st=sst;
969
970     st->now=*now;
971     if (st->timeout && *now>st->timeout) {
972         st->timeout=0;
973         if (st->state>=SITE_SENTMSG1 && st->state<=SITE_SENTMSG5) {
974             if (!hacky_par_start_failnow())
975                 send_msg(st);
976         } else if (st->state==SITE_WAIT) {
977             enter_state_run(st);
978         } else {
979             slog(st,LOG_ERROR,"site_afterpoll: unexpected timeout, state=%d",
980                  st->state);
981         }
982     }
983     if (st->current_key_timeout && *now>st->current_key_timeout) {
984         delete_key(st,"maximum key life exceeded",LOG_TIMEOUT_KEY);
985     }
986 }
987
988 /* This function is called by the netlink device to deliver packets
989    intended for the remote network. The packet is in "raw" wire
990    format, but is guaranteed to be word-aligned. */
991 static void site_outgoing(void *sst, struct buffer_if *buf)
992 {
993     struct site *st=sst;
994     cstring_t transform_err;
995     
996     if (st->state==SITE_STOP) {
997         BUF_FREE(buf);
998         return;
999     }
1000
1001     /* In all other states we consider delivering the packet if we have
1002        a valid key and a valid address to send it to. */
1003     if (st->current_valid && st->peer_valid) {
1004         /* Transform it and send it */
1005         if (buf->size>0) {
1006             buf_prepend_uint32(buf,LABEL_MSG9);
1007             st->current_transform->forwards(st->current_transform->st,
1008                                             buf, &transform_err);
1009             buf_prepend_uint32(buf,LABEL_MSG0);
1010             buf_prepend_uint32(buf,st->index);
1011             buf_prepend_uint32(buf,st->remote_session_id);
1012             st->comm->sendmsg(st->comm->st,buf,&st->peer);
1013         }
1014         BUF_FREE(buf);
1015         /* See whether we should start negotiating a new key */
1016         if (st->now > st->renegotiate_key_time)
1017             initiate_key_setup(st,"outgoing packet in renegotiation window");
1018         return;
1019     }
1020
1021     slog(st,LOG_DROP,"discarding outgoing packet of size %d",buf->size);
1022     BUF_FREE(buf);
1023     initiate_key_setup(st,"outgoing packet");
1024 }
1025
1026 /* This function is called by the communication device to deliver
1027    packets from our peers. */
1028 static bool_t site_incoming(void *sst, struct buffer_if *buf,
1029                             struct sockaddr_in *source)
1030 {
1031     struct site *st=sst;
1032     uint32_t dest=ntohl(*(uint32_t *)buf->start);
1033
1034     if (dest==0) {
1035         /* It could be for any site - it should have LABEL_MSG1 and
1036            might have our name and our peer's name in it */
1037         if (buf->size<(st->setupsiglen+8+NONCELEN)) return False;
1038         if (memcmp(buf->start+8,st->setupsig,st->setupsiglen)==0) {
1039             /* It's addressed to us. Decide what to do about it. */
1040             dump_packet(st,buf,source,True);
1041             if (st->state==SITE_RUN || st->state==SITE_RESOLVE ||
1042                 st->state==SITE_WAIT) {
1043                 /* We should definitely process it */
1044                 if (process_msg1(st,buf,source)) {
1045                     slog(st,LOG_SETUP_INIT,"key setup initiated by peer");
1046                     enter_new_state(st,SITE_SENTMSG2);
1047                 } else {
1048                     slog(st,LOG_ERROR,"failed to process incoming msg1");
1049                 }
1050                 BUF_FREE(buf);
1051                 return True;
1052             } else if (st->state==SITE_SENTMSG1) {
1053                 /* We've just sent a message 1! They may have crossed on
1054                    the wire. If we have priority then we ignore the
1055                    incoming one, otherwise we process it as usual. */
1056                 if (st->setup_priority) {
1057                     BUF_FREE(buf);
1058                     slog(st,LOG_DUMP,"crossed msg1s; we are higher "
1059                          "priority => ignore incoming msg1");
1060                     return True;
1061                 } else {
1062                     slog(st,LOG_DUMP,"crossed msg1s; we are lower "
1063                          "priority => use incoming msg1");
1064                     if (process_msg1(st,buf,source)) {
1065                         BUF_FREE(&st->buffer); /* Free our old message 1 */
1066                         enter_new_state(st,SITE_SENTMSG2);
1067                     } else {
1068                         slog(st,LOG_ERROR,"failed to process an incoming "
1069                              "crossed msg1 (we have low priority)");
1070                     }
1071                     BUF_FREE(buf);
1072                     return True;
1073                 }
1074             }
1075             /* The message 1 was received at an unexpected stage of the
1076                key setup. XXX POLICY - what do we do? */
1077             slog(st,LOG_UNEXPECTED,"unexpected incoming message 1");
1078             BUF_FREE(buf);
1079             return True;
1080         }
1081         return False; /* Not for us. */
1082     }
1083     if (dest==st->index) {
1084         /* Explicitly addressed to us */
1085         uint32_t msgtype=ntohl(get_uint32(buf->start+8));
1086         if (msgtype!=LABEL_MSG0) dump_packet(st,buf,source,True);
1087         switch (msgtype) {
1088         case 0: /* NAK */
1089             /* If the source is our current peer then initiate a key setup,
1090                because our peer's forgotten the key */
1091             if (get_uint32(buf->start+4)==st->remote_session_id) {
1092                 initiate_key_setup(st,"received a NAK");
1093             } else {
1094                 slog(st,LOG_SEC,"bad incoming NAK");
1095             }
1096             break;
1097         case LABEL_MSG0:
1098             process_msg0(st,buf,source);
1099             break;
1100         case LABEL_MSG1:
1101             /* Setup packet: should not have been explicitly addressed
1102                to us */
1103             slog(st,LOG_SEC,"incoming explicitly addressed msg1");
1104             break;
1105         case LABEL_MSG2:
1106             /* Setup packet: expected only in state SENTMSG1 */
1107             if (st->state!=SITE_SENTMSG1) {
1108                 slog(st,LOG_UNEXPECTED,"unexpected MSG2");
1109             } else if (process_msg2(st,buf,source))
1110                 enter_new_state(st,SITE_SENTMSG3);
1111             else {
1112                 slog(st,LOG_SEC,"invalid MSG2");
1113             }
1114             break;
1115         case LABEL_MSG3:
1116             /* Setup packet: expected only in state SENTMSG2 */
1117             if (st->state!=SITE_SENTMSG2) {
1118                 slog(st,LOG_UNEXPECTED,"unexpected MSG3");
1119             } else if (process_msg3(st,buf,source))
1120                 enter_new_state(st,SITE_SENTMSG4);
1121             else {
1122                 slog(st,LOG_SEC,"invalid MSG3");
1123             }
1124             break;
1125         case LABEL_MSG4:
1126             /* Setup packet: expected only in state SENTMSG3 */
1127             if (st->state!=SITE_SENTMSG3) {
1128                 slog(st,LOG_UNEXPECTED,"unexpected MSG4");
1129             } else if (process_msg4(st,buf,source))
1130                 enter_new_state(st,SITE_SENTMSG5);
1131             else {
1132                 slog(st,LOG_SEC,"invalid MSG4");
1133             }
1134             break;
1135         case LABEL_MSG5:
1136             /* Setup packet: expected only in state SENTMSG4 */
1137             /* (may turn up in state RUN if our return MSG6 was lost
1138                and the new key has already been activated. In that
1139                case we should treat it as an ordinary PING packet. We
1140                can't pass it to process_msg5() because the
1141                new_transform will now be unkeyed. XXX) */
1142             if (st->state!=SITE_SENTMSG4) {
1143                 slog(st,LOG_UNEXPECTED,"unexpected MSG5");
1144             } else if (process_msg5(st,buf,source)) {
1145                 enter_new_state(st,SITE_RUN);
1146             } else {
1147                 slog(st,LOG_SEC,"invalid MSG5");
1148             }
1149             break;
1150         case LABEL_MSG6:
1151             /* Setup packet: expected only in state SENTMSG5 */
1152             if (st->state!=SITE_SENTMSG5) {
1153                 slog(st,LOG_UNEXPECTED,"unexpected MSG6");
1154             } else if (process_msg6(st,buf,source)) {
1155                 BUF_FREE(&st->buffer); /* Free message 5 */
1156                 activate_new_key(st);
1157             } else {
1158                 slog(st,LOG_SEC,"invalid MSG6");
1159             }
1160             break;
1161         default:
1162             slog(st,LOG_SEC,"received message of unknown type 0x%08x",
1163                  msgtype);
1164             break;
1165         }
1166         BUF_FREE(buf);
1167         return True;
1168     }
1169
1170     return False;
1171 }
1172
1173 static void site_control(void *vst, bool_t run)
1174 {
1175     struct site *st=vst;
1176     if (run) enter_state_run(st);
1177     else enter_state_stop(st);
1178 }
1179
1180 static void site_phase_hook(void *sst, uint32_t newphase)
1181 {
1182     struct site *st=sst;
1183
1184     /* The program is shutting down; tell our peer */
1185     send_msg7(st,"shutting down");
1186 }
1187
1188 static list_t *site_apply(closure_t *self, struct cloc loc, dict_t *context,
1189                           list_t *args)
1190 {
1191     static uint32_t index_sequence;
1192     struct site *st;
1193     item_t *item;
1194     dict_t *dict;
1195
1196     st=safe_malloc(sizeof(*st),"site_apply");
1197
1198     st->cl.description="site";
1199     st->cl.type=CL_SITE;
1200     st->cl.apply=NULL;
1201     st->cl.interface=&st->ops;
1202     st->ops.st=st;
1203     st->ops.control=site_control;
1204     st->ops.status=site_status;
1205
1206     /* First parameter must be a dict */
1207     item=list_elem(args,0);
1208     if (!item || item->type!=t_dict)
1209         cfgfatal(loc,"site","parameter must be a dictionary\n");
1210     
1211     dict=item->data.dict;
1212     st->localname=dict_read_string(dict, "local-name", True, "site", loc);
1213     st->remotename=dict_read_string(dict, "name", True, "site", loc);
1214     /* Sanity check (which also allows the 'sites' file to include
1215        site() closures for all sites including our own): refuse to
1216        talk to ourselves */
1217     if (strcmp(st->localname,st->remotename)==0) {
1218         Message(M_DEBUG,"site %s: local-name==name -> ignoring this site\n",
1219                 st->localname);
1220         free(st);
1221         return NULL;
1222     }
1223     assert(index_sequence < 0xffffffffUL);
1224     st->index = ++index_sequence;
1225     st->netlink=find_cl_if(dict,"link",CL_NETLINK,True,"site",loc);
1226     st->comm=find_cl_if(dict,"comm",CL_COMM,True,"site",loc);
1227     st->resolver=find_cl_if(dict,"resolver",CL_RESOLVER,True,"site",loc);
1228     st->log=find_cl_if(dict,"log",CL_LOG,True,"site",loc);
1229     st->random=find_cl_if(dict,"random",CL_RANDOMSRC,True,"site",loc);
1230
1231     st->privkey=find_cl_if(dict,"local-key",CL_RSAPRIVKEY,True,"site",loc);
1232     st->address=dict_read_string(dict, "address", False, "site", loc);
1233     if (st->address)
1234         st->remoteport=dict_read_number(dict,"port",True,"site",loc,0);
1235     else st->remoteport=0;
1236     st->pubkey=find_cl_if(dict,"key",CL_RSAPUBKEY,True,"site",loc);
1237
1238     st->transform=
1239         find_cl_if(dict,"transform",CL_TRANSFORM,True,"site",loc);
1240
1241     st->dh=find_cl_if(dict,"dh",CL_DH,True,"site",loc);
1242     st->hash=find_cl_if(dict,"hash",CL_HASH,True,"site",loc);
1243
1244     st->key_lifetime=dict_read_number(
1245         dict,"key-lifetime",False,"site",loc,DEFAULT_KEY_LIFETIME);
1246     st->setup_retries=dict_read_number(
1247         dict,"setup-retries",False,"site",loc,DEFAULT_SETUP_RETRIES);
1248     st->setup_timeout=dict_read_number(
1249         dict,"setup-timeout",False,"site",loc,DEFAULT_SETUP_TIMEOUT);
1250     st->wait_timeout=dict_read_number(
1251         dict,"wait-time",False,"site",loc,DEFAULT_WAIT_TIME);
1252
1253     if (st->key_lifetime < DEFAULT_KEY_RENEGOTIATE_GAP*2)
1254         st->key_renegotiate_time=st->key_lifetime/2;
1255     else
1256         st->key_renegotiate_time=st->key_lifetime-DEFAULT_KEY_RENEGOTIATE_GAP;
1257     st->key_renegotiate_time=dict_read_number(
1258         dict,"renegotiate-time",False,"site",loc,st->key_renegotiate_time);
1259     if (st->key_renegotiate_time > st->key_lifetime) {
1260         cfgfatal(loc,"site",
1261                  "renegotiate-time must be less than key-lifetime\n");
1262     }
1263     st->keepalive=dict_read_bool(dict,"keepalive",False,"site",loc,False);
1264
1265     st->log_events=string_list_to_word(dict_lookup(dict,"log-events"),
1266                                        log_event_table,"site");
1267
1268     st->tunname=safe_malloc(strlen(st->localname)+strlen(st->remotename)+5,
1269                             "site_apply");
1270     sprintf(st->tunname,"%s<->%s",st->localname,st->remotename);
1271
1272     /* The information we expect to see in incoming messages of type 1 */
1273     /* fixme: lots of unchecked overflows here, but the results are only
1274        corrupted packets rather than undefined behaviour */
1275     st->setupsiglen=strlen(st->remotename)+strlen(st->localname)+8;
1276     st->setupsig=safe_malloc(st->setupsiglen,"site_apply");
1277     put_uint32(st->setupsig+0,LABEL_MSG1);
1278     put_uint16(st->setupsig+4,strlen(st->remotename));
1279     memcpy(&st->setupsig[6],st->remotename,strlen(st->remotename));
1280     put_uint16(st->setupsig+(6+strlen(st->remotename)),strlen(st->localname));
1281     memcpy(&st->setupsig[8+strlen(st->remotename)],st->localname,
1282            strlen(st->localname));
1283     st->setup_priority=(strcmp(st->localname,st->remotename)>0);
1284
1285     buffer_new(&st->buffer,SETUP_BUFFER_LEN);
1286
1287     /* We are interested in poll(), but only for timeouts. We don't have
1288        any fds of our own. */
1289     register_for_poll(st, site_beforepoll, site_afterpoll, 0, "site");
1290     st->timeout=0;
1291
1292     st->current_valid=False;
1293     st->current_key_timeout=0;
1294     st->peer_valid=False;
1295     /* XXX mlock these */
1296     st->dhsecret=safe_malloc(st->dh->len,"site:dhsecret");
1297     st->sharedsecret=safe_malloc(st->transform->keylen,"site:sharedsecret");
1298
1299     /* We need to register the remote networks with the netlink device */
1300     st->netlink->reg(st->netlink->st, site_outgoing, st,
1301                      st->transform->max_start_pad+(4*4)+
1302                      st->comm->min_start_pad,
1303                      st->transform->max_end_pad+st->comm->min_end_pad);
1304     
1305     st->comm->request_notify(st->comm->st, st, site_incoming);
1306
1307     st->current_transform=st->transform->create(st->transform->st);
1308     st->new_transform=st->transform->create(st->transform->st);
1309
1310     enter_state_stop(st);
1311
1312     add_hook(PHASE_SHUTDOWN,site_phase_hook,st);
1313
1314     return new_closure(&st->cl);
1315 }
1316
1317 void site_module(dict_t *dict)
1318 {
1319     add_closure(dict,"site",site_apply);
1320 }