1 /* site.c - manage communication with a remote network site */
5 /* MBM asserts the next one is needed for compilation under BSD. */
6 #include <sys/socket.h>
10 #include "unaligned.h"
12 #define SETUP_BUFFER_LEN 2048
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
20 /* Each site can be in one of several possible 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
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
42 -> SITE_SENTMSG4 upon valid incoming message 3
43 -> SITE_WAIT on timeout
45 -> SITE_SENTMSG5 upon valid incoming message 4
46 -> SITE_WAIT on timeout
48 -> SITE_RUN upon valid incoming message 5
49 -> SITE_WAIT on timeout
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
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
67 static string_t state_name(uint32_t state)
70 case 0: return "STOP";
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*";
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
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
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 },
122 static struct flagstr netlink_option_table[]={
123 { "soft", NETLINK_OPTION_SOFTROUTE },
124 { "allow-route", NETLINK_OPTION_ALLOW_ROUTE },
131 /* configuration information */
134 string_t tunname; /* localname<->remotename by default */
135 string_t address; /* DNS name for bootstrapping, optional */
137 struct netlink_if *netlink;
138 struct comm_if *comm;
139 struct resolver_if *resolver;
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;
147 struct hash_if *hash;
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
157 bool_t keepalive; /* Always keep the tunnel up */
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? */
166 /* runtime information */
168 uint64_t now; /* Most recently seen time */
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 */
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 */
188 uint8_t *sharedsecret;
190 struct transform_inst_if *new_transform; /* For key setup/verify */
193 static void slog(struct site *st, uint32_t event, string_t msg, ...)
201 if (event&st->log_events) {
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;
216 vsnprintf(buf,240,msg,ap);
217 st->log->log(st->log->st,class,"%s: %s",st->tunname,buf);
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);
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)
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)
262 uint8_t *hash=alloca(st->hash->len);
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);
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);
290 static bool_t unpick_msg(struct site *st, uint32_t type,
291 struct buffer_if *msg, struct msg *m)
293 m->hashstart=msg->start;
295 m->dest=buf_unprepend_uint32(msg);
297 m->source=buf_unprepend_uint32(msg);
298 CHECK_TYPE(msg,type);
300 m->remlen=buf_unprepend_uint16(msg);
301 CHECK_AVAIL(msg,m->remlen);
302 m->remote=buf_unprepend(msg,m->remlen);
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) {
313 CHECK_AVAIL(msg,NONCELEN);
314 m->nL=buf_unprepend(msg,NONCELEN);
315 if (type==LABEL_MSG2) {
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;
325 m->siglen=buf_unprepend_uint16(msg);
326 CHECK_AVAIL(msg,m->siglen);
327 m->sig=buf_unprepend(msg,m->siglen);
332 static bool_t generate_msg1(struct site *st)
334 st->random->generate(st->random->st,NONCELEN,st->localN);
335 return generate_msg(st,LABEL_MSG1,"site:MSG1");
338 static bool_t process_msg1(struct site *st, struct buffer_if *msg1,
339 struct sockaddr_in *src)
343 /* We've already determined we're in an appropriate state to
344 process an incoming MSG1, and that the MSG1 has correct values
347 if (!unpick_msg(st,LABEL_MSG1,msg1,&m)) return False;
349 /* XXX save src as our peer address here? */
352 st->setup_session_id=m.source;
353 memcpy(st->remoteN,m.nR,NONCELEN);
357 static bool_t generate_msg2(struct site *st)
359 st->random->generate(st->random->st,NONCELEN,st->localN);
360 return generate_msg(st,LABEL_MSG2,"site:MSG2");
363 static bool_t process_msg2(struct site *st, struct buffer_if *msg2,
364 struct sockaddr_in *src)
368 if (!unpick_msg(st,LABEL_MSG2,msg2,&m)) return False;
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)");
376 if (memcmp(m.local,st->localname,strlen(st->localname)!=0)) {
377 slog(st,LOG_SEC,"msg2: bad A (local site name)");
380 if (memcmp(m.nL,st->localN,NONCELEN)!=0) {
381 slog(st,LOG_SEC,"msg2: bad nA (locally generated nonce)");
384 st->setup_session_id=m.source;
385 memcpy(st->remoteN,m.nR,NONCELEN);
389 static bool_t generate_msg3(struct site *st)
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");
397 static bool_t process_msg3(struct site *st, struct buffer_if *msg3,
398 struct sockaddr_in *src)
401 uint8_t *hash=alloca(st->hash->len);
404 if (!unpick_msg(st,LABEL_MSG3,msg3,&m)) return False;
406 /* Check that the site names and nonces have been sent back
408 if (memcmp(m.remote,st->remotename,strlen(st->remotename)!=0)) {
409 slog(st,LOG_SEC,"msg3: bad A (remote site name)");
412 if (memcmp(m.local,st->localname,strlen(st->localname)!=0)) {
413 slog(st,LOG_SEC,"msg3: bad B (local site name)");
416 if (memcmp(m.nR,st->remoteN,NONCELEN)!=0) {
417 slog(st,LOG_SEC,"msg3: bad nA (remotely generated nonce)");
420 if (memcmp(m.nL,st->localN,NONCELEN)!=0) {
421 slog(st,LOG_SEC,"msg3: bad nB (locally generated nonce)");
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 */
431 if (!st->pubkey->check(st->pubkey->st,hash,st->hash->len,m.sig)) {
432 slog(st,LOG_SEC,"msg3 signature failed check!");
436 /* Terminate their DH public key with a '0' */
438 /* Invent our DH secret key */
439 st->random->generate(st->random->st,st->dh->len,st->dhsecret);
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);
445 /* Set up the transform */
446 st->new_transform->setkey(st->new_transform->st,st->sharedsecret,
447 st->transform->keylen);
452 static bool_t generate_msg4(struct site *st)
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");
459 static bool_t process_msg4(struct site *st, struct buffer_if *msg4,
460 struct sockaddr_in *src)
463 uint8_t *hash=alloca(st->hash->len);
466 if (!unpick_msg(st,LABEL_MSG4,msg4,&m)) return False;
468 /* Check that the site names and nonces have been sent back
470 if (memcmp(m.remote,st->remotename,strlen(st->remotename)!=0)) {
471 slog(st,LOG_SEC,"msg4: bad B (remote site name)");
474 if (memcmp(m.local,st->localname,strlen(st->localname)!=0)) {
475 slog(st,LOG_SEC,"msg4: bad A (local site name)");
478 if (memcmp(m.nR,st->remoteN,NONCELEN)!=0) {
479 slog(st,LOG_SEC,"msg4: bad nB (remotely generated nonce)");
482 if (memcmp(m.nL,st->localN,NONCELEN)!=0) {
483 slog(st,LOG_SEC,"msg4: bad nA (locally generated nonce)");
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 */
493 if (!st->pubkey->check(st->pubkey->st,hash,st->hash->len,m.sig)) {
494 slog(st,LOG_SEC,"msg4 signature failed check!");
498 /* Terminate their DH public key with a '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);
510 static bool_t generate_msg5(struct site *st)
512 string_t transform_err;
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,
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);
524 st->retries=st->setup_retries;
534 static bool_t unpick_msg0(struct site *st, struct buffer_if *msg0,
538 m->dest=buf_unprepend_uint32(msg0);
540 m->source=buf_unprepend_uint32(msg0);
542 m->type=buf_unprepend_uint32(msg0);
544 /* Leaves transformed part of buffer untouched */
547 static bool_t process_msg5(struct site *st, struct buffer_if *msg5,
548 struct sockaddr_in *src)
551 string_t transform_err;
553 if (!unpick_msg0(st,msg5,&m)) return False;
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);
561 /* Buffer should now contain untransformed PING packet data */
563 if (buf_unprepend_uint32(msg5)!=LABEL_MSG5) {
564 slog(st,LOG_SEC,"MSG5/PING packet contained invalid data");
571 static bool_t generate_msg6(struct site *st)
573 string_t transform_err;
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,
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);
585 st->retries=1; /* Peer will retransmit MSG5 if necessary */
589 static bool_t process_msg6(struct site *st, struct buffer_if *msg6,
590 struct sockaddr_in *src)
593 string_t transform_err;
595 if (!unpick_msg0(st,msg6,&m)) return False;
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);
603 /* Buffer should now contain untransformed PING packet data */
605 if (buf_unprepend_uint32(msg6)!=LABEL_MSG6) {
606 slog(st,LOG_SEC,"MSG6/PONG packet contained invalid data");
613 static bool_t process_msg0(struct site *st, struct buffer_if *msg0,
614 struct sockaddr_in *src)
617 string_t transform_err;
620 if (!st->current_valid) {
621 slog(st,LOG_DROP,"incoming message but no current key -> dropping");
622 return initiate_key_setup(st);
625 if (!unpick_msg0(st,msg0,&m)) return False;
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);
634 type=buf_unprepend_uint32(msg0);
637 /* Deliver to netlink layer */
638 st->netlink->deliver(st->netlink->st,st->netlink_cid,msg0);
642 slog(st,LOG_SEC,"incoming message of type %08x (unknown)",type);
648 static void dump_packet(struct site *st, struct buffer_if *buf,
649 struct sockaddr_in *addr, bool_t incoming)
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));
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);
661 static uint32_t site_status(void *st)
666 static bool_t send_msg(struct site *st)
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;
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);
682 static void site_resolve_callback(void *sst, struct in_addr *address)
686 if (st->state!=SITE_RESOLVE) {
687 slog(st,LOG_UNEXPECTED,"site_resolve_callback called unexpectedly");
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);
697 /* Resolution failed */
698 slog(st,LOG_ERROR,"resolution of %s failed",st->address);
703 static bool_t initiate_key_setup(struct site *st)
705 if (st->state!=SITE_RUN) return False;
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 "
712 st->setup_peer=st->peer;
713 return enter_state_sentmsg1(st);
718 static void activate_new_key(struct site *st)
720 struct transform_inst_if *t;
722 t=st->current_transform;
723 st->current_transform=st->new_transform;
728 st->current_valid=True;
729 st->current_key_timeout=st->now+st->key_lifetime;
730 st->peer=st->setup_peer;
732 st->remote_session_id=st->setup_session_id;
734 slog(st,LOG_ACTIVATE_KEY,"new key activated");
738 static void state_assert(struct site *st, bool_t ok)
740 if (!ok) fatal("state_assert\n");
743 static void enter_state_stop(struct site *st)
747 st->current_transform->delkey(st->current_transform->st);
748 st->current_valid=False;
749 st->current_key_timeout=0;
751 st->peer_valid=False;
753 set_link_quality(st);
755 st->new_transform->delkey(st->new_transform->st);
758 static void set_link_quality(struct site *st)
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;
770 quality=LINK_QUALITY_DOWN;
772 st->netlink->set_quality(st->netlink->st,st->netlink_cid,quality);
775 static void enter_state_run(struct site *st)
777 slog(st,LOG_STATE,"entering state RUN");
781 set_link_quality(st);
782 /* XXX get rid of key setup data */
785 static bool_t enter_state_resolve(struct site *st)
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);
795 static bool_t enter_state_sentmsg1(struct site *st)
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;
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);
810 static bool_t enter_state_sentmsg2(struct site *st)
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;
819 slog(st,LOG_ERROR,"error entering state SENTMSG2");
820 st->buffer.free=False;
821 enter_state_wait(st);
825 static bool_t enter_state_sentmsg3(struct site *st)
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;
834 slog(st,LOG_ERROR,"error entering state SENTMSG3");
835 st->buffer.free=False;
836 enter_state_wait(st);
840 static bool_t enter_state_sentmsg4(struct site *st)
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;
849 slog(st,LOG_ERROR,"error entering state SENTMSG4");
850 st->buffer.free=False;
851 enter_state_wait(st);
855 static bool_t enter_state_sentmsg5(struct site *st)
857 state_assert(st,st->state==SITE_SENTMSG3);
858 slog(st,LOG_STATE,"entering state SENTMSG5");
859 BUF_FREE(&st->buffer); /* Free message 3 */
861 if (generate_msg5(st) && send_msg(st)) {
862 st->state=SITE_SENTMSG5;
865 slog(st,LOG_ERROR,"error entering state SENTMSG5");
866 st->buffer.free=False;
867 enter_state_wait(st);
872 static bool_t send_msg6(struct site *st)
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);
883 slog(st,LOG_ERROR,"error entering state RUN after sending msg6");
884 st->buffer.free=False;
885 enter_state_wait(st);
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)
894 slog(st,LOG_STATE,"entering state WAIT");
895 st->timeout=st->now+st->wait_timeout;
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. */
903 static int site_beforepoll(void *sst, struct pollfd *fds, int *nfds_io,
904 int *timeout_io, const struct timeval *tv_now,
909 *nfds_io=0; /* We don't use any file descriptors */
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
915 if (st->timeout && st->timeout-*now < *timeout_io) {
916 *timeout_io=st->timeout-*now;
919 if (st->current_key_timeout && st->current_key_timeout-*now < *timeout_io)
920 *timeout_io=st->current_key_timeout-*now;
922 return 0; /* success */
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)
932 if (st->timeout && *now>st->timeout) {
935 if (st->state>=SITE_SENTMSG1 && st->state<=SITE_SENTMSG5)
937 else if (st->state==SITE_WAIT) {
940 slog(st,LOG_ERROR,"site_afterpoll: unexpected timeout, state=%d",
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);
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)
959 string_t transform_err;
961 if (st->state==SITE_STOP) {
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 */
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);
983 slog(st,LOG_DROP,"discarding outgoing packet of size %d",buf->size);
985 initiate_key_setup(st);
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)
994 uint32_t dest=ntohl(*(uint32_t *)buf->start);
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);
1010 slog(st,LOG_ERROR,"failed to process incoming msg1");
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) {
1021 slog(st,LOG_DUMP,"crossed msg1s; we are higher "
1022 "priority => ignore incoming msg1");
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);
1031 slog(st,LOG_ERROR,"failed to process an incoming "
1032 "crossed msg1 (we have low priority)");
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");
1044 return False; /* Not for us. */
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);
1052 process_msg0(st,buf,source);
1055 /* Setup packet: should not have been explicitly addressed
1057 slog(st,LOG_SEC,"incoming explicitly addressed msg1");
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);
1066 slog(st,LOG_SEC,"invalid MSG2");
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);
1076 slog(st,LOG_SEC,"invalid MSG3");
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);
1086 slog(st,LOG_SEC,"invalid MSG4");
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)) {
1101 slog(st,LOG_SEC,"invalid MSG5");
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);
1112 slog(st,LOG_SEC,"invalid MSG6");
1116 /* NAK packet: enter state where we ping and check for response */
1117 slog(st,LOG_ERROR,"received a NAK");
1120 slog(st,LOG_SEC,"received message of unknown type 0x%08x",
1131 static void site_control(void *vst, bool_t run)
1133 struct site *st=vst;
1134 if (run) enter_state_run(st);
1135 else enter_state_stop(st);
1138 static list_t *site_apply(closure_t *self, struct cloc loc, dict_t *context,
1144 uint32_t netlink_options;
1146 st=safe_malloc(sizeof(*st),"site_apply");
1148 st->cl.description="site";
1149 st->cl.type=CL_SITE;
1151 st->cl.interface=&st->ops;
1153 st->ops.control=site_control;
1154 st->ops.status=site_status;
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");
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",
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);
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);
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,
1186 st->pubkey=find_cl_if(dict,"key",CL_RSAPUBKEY,True,"site",loc);
1189 find_cl_if(dict,"transform",CL_TRANSFORM,True,"site",loc);
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);
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;
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");
1212 /* XXX keepalive will eventually default to True */
1213 st->keepalive=dict_read_bool(dict,"keepalive",False,"site",loc,False);
1215 st->log_events=string_list_to_word(dict_lookup(dict,"log-events"),
1216 log_event_table,"site");
1218 netlink_options=string_list_to_word(dict_lookup(dict,"netlink-options"),
1219 netlink_option_table,"site");
1221 st->tunname=safe_malloc(strlen(st->localname)+strlen(st->remotename)+5,
1223 sprintf(st->tunname,"%s<->%s",st->localname,st->remotename);
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);
1236 buffer_new(&st->buffer,SETUP_BUFFER_LEN);
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");
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");
1250 /* We need to register the remote networks with the netlink device */
1251 st->netlink_cid=st->netlink->regnets(st->netlink->st, &st->remotenets,
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",
1260 return NULL; /* XXX should free site first */
1263 st->comm->request_notify(st->comm->st, st, site_incoming);
1265 st->current_transform=st->transform->create(st->transform->st);
1266 st->new_transform=st->transform->create(st->transform->st);
1268 enter_state_stop(st);
1270 return new_closure(&st->cl);
1273 init_module site_module;
1274 void site_module(dict_t *dict)
1276 add_closure(dict,"site",site_apply);