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