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