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