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
15 #define DEFAULT_SETUP_RETRIES 5
16 #define DEFAULT_SETUP_TIMEOUT 1000
17 #define DEFAULT_WAIT_TIME 10000
19 /* Each site can be in one of several possible states. */
22 SITE_STOP - nothing is allowed to happen; tunnel is down;
23 all session keys have been erased
24 -> SITE_RUN upon external instruction
25 SITE_RUN - site up, maybe with valid key
26 -> SITE_RESOLVE upon outgoing packet and no valid key
27 we start name resolution for the other end of the tunnel
28 -> SITE_SENTMSG2 upon valid incoming message 1 and suitable time
29 we send an appropriate message 2
30 SITE_RESOLVE - waiting for name resolution
31 -> SITE_SENTMSG1 upon successful resolution
32 we send an appropriate message 1
33 -> SITE_SENTMSG2 upon valid incoming message 1 (then abort resolution)
34 we abort resolution and
35 -> SITE_WAIT on timeout or resolution failure
37 -> SITE_SENTMSG2 upon valid incoming message 1 from higher priority end
38 -> SITE_SENTMSG3 upon valid incoming message 2
39 -> SITE_WAIT on timeout
41 -> SITE_SENTMSG4 upon valid incoming message 3
42 -> SITE_WAIT on timeout
44 -> SITE_SENTMSG5 upon valid incoming message 4
45 -> SITE_WAIT on timeout
47 -> SITE_RUN upon valid incoming message 5
48 -> SITE_WAIT on timeout
50 -> SITE_RUN upon valid incoming message 6
51 -> SITE_WAIT on timeout
52 SITE_WAIT - failed to establish key; do nothing for a while
53 -> SITE_RUN on timeout
58 #define SITE_RESOLVE 2
59 #define SITE_SENTMSG1 3
60 #define SITE_SENTMSG2 4
61 #define SITE_SENTMSG3 5
62 #define SITE_SENTMSG4 6
63 #define SITE_SENTMSG5 7
67 static string_t state_name(uint32_t state)
70 case 0: return "SITE_STOP";
71 case 1: return "SITE_RUN";
72 case 2: return "SITE_RESOLVE";
73 case 3: return "SITE_SENTMSG1";
74 case 4: return "SITE_SENTMSG2";
75 case 5: return "SITE_SENTMSG3";
76 case 6: return "SITE_SENTMSG4";
77 case 7: return "SITE_SENTMSG5";
78 case 8: return "SITE_WAIT";
79 default: return "*bad state*";
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
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
111 /* configuration information */
114 string_t tunname; /* localname<->remotename by default */
115 string_t address; /* DNS name for bootstrapping, optional */
117 struct netlink_if *netlink;
118 struct comm_if *comm;
119 struct resolver_if *resolver;
121 struct random_if *random;
122 struct rsaprivkey_if *privkey;
123 struct subnet_list remotenets;
124 struct rsapubkey_if *pubkey;
125 struct transform_if *transform;
127 struct hash_if *hash;
130 uint32_t setup_retries; /* How many times to send setup packets */
131 uint32_t setup_timeout; /* Initial timeout for setup packets */
132 uint32_t wait_timeout; /* How long to wait if setup unsuccessful */
133 uint32_t key_lifetime; /* How long a key lasts once set up */
135 uint8_t *setupsig; /* Expected signature of incoming MSG1 packets */
136 uint32_t setupsiglen; /* Allows us to discard packets quickly if
137 they are not for us */
138 bool_t setup_priority; /* Do we have precedence if both sites emit
139 message 1 simultaneously? */
142 /* runtime information */
144 uint64_t now; /* Most recently seen time */
146 uint32_t remote_session_id;
147 struct transform_inst_if *current_transform;
148 bool_t current_valid;
149 uint64_t current_key_timeout; /* End of life of current key */
150 struct sockaddr_in peer; /* Current address of peer */
151 bool_t peer_valid; /* Peer address becomes invalid when key times out,
152 but only if we have a DNS name for our peer */
154 uint32_t setup_session_id;
155 struct sockaddr_in setup_peer;
156 uint8_t localN[NONCELEN]; /* Nonces for key exchange */
157 uint8_t remoteN[NONCELEN];
158 struct buffer_if buffer; /* Current outgoing key exchange packet */
159 uint32_t retries; /* Number of retries remaining */
160 uint64_t timeout; /* Timeout for current state */
162 uint8_t *sharedsecret;
164 struct transform_inst_if *new_transform; /* For key setup/verify */
167 static void slog(struct site *st, uint32_t event, string_t msg, ...)
174 if (event&st->log_events) {
175 vsnprintf(buf,240,msg,ap);
176 st->log->log(st->log->st,0,"%s: %s",st->tunname,buf);
181 static void enter_state_run(struct site *st);
182 static bool_t enter_state_resolve(struct site *st);
183 static bool_t enter_state_sentmsg1(struct site *st);
184 static bool_t enter_state_sentmsg2(struct site *st);
185 static bool_t enter_state_sentmsg3(struct site *st);
186 static bool_t enter_state_sentmsg4(struct site *st);
187 static bool_t enter_state_sentmsg5(struct site *st);
188 static void enter_state_wait(struct site *st);
190 #define CHECK_AVAIL(b,l) do { if ((b)->size<(l)) return False; } while(0)
191 #define CHECK_EMPTY(b) do { if ((b)->size!=0) return False; } while(0)
192 #define CHECK_TYPE(b,t) do { uint32_t type; \
193 CHECK_AVAIL((b),4); \
194 type=buf_unprepend_uint32((b)); \
195 if (type!=(t)) return False; } while(0)
214 /* Build any of msg1 to msg4. msg5 and msg6 are built from the inside out
215 using a transform. */
216 static bool_t generate_msg(struct site *st, uint32_t type, string_t what)
219 uint8_t *hash=alloca(st->hash->len);
222 st->retries=st->setup_retries;
223 BUF_ALLOC(&st->buffer,what);
224 buffer_init(&st->buffer,0);
225 buf_append_uint32(&st->buffer,
226 (type==LABEL_MSG1?0:st->setup_session_id));
227 buf_append_uint32(&st->buffer,(uint32_t)st);
228 buf_append_uint32(&st->buffer,type);
229 buf_append_string(&st->buffer,st->localname);
230 buf_append_string(&st->buffer,st->remotename);
231 memcpy(buf_append(&st->buffer,NONCELEN),st->localN,NONCELEN);
232 if (type==LABEL_MSG1) return True;
233 memcpy(buf_append(&st->buffer,NONCELEN),st->remoteN,NONCELEN);
234 if (type==LABEL_MSG2) return True;
235 dhpub=st->dh->makepublic(st->dh->st,st->dhsecret,st->dh->len);
236 buf_append_string(&st->buffer,dhpub);
238 hst=st->hash->init();
239 st->hash->update(hst,st->buffer.start,st->buffer.size);
240 st->hash->final(hst,hash);
241 sig=st->privkey->sign(st->privkey->st,hash,st->hash->len);
242 buf_append_string(&st->buffer,sig);
247 static bool_t unpick_msg(struct site *st, uint32_t type,
248 struct buffer_if *msg, struct msg *m)
250 m->hashstart=msg->start;
252 m->dest=buf_unprepend_uint32(msg);
254 m->source=buf_unprepend_uint32(msg);
255 CHECK_TYPE(msg,type);
257 m->remlen=buf_unprepend_uint16(msg);
258 CHECK_AVAIL(msg,m->remlen);
259 m->remote=buf_unprepend(msg,m->remlen);
261 m->loclen=buf_unprepend_uint16(msg);
262 CHECK_AVAIL(msg,m->loclen);
263 m->local=buf_unprepend(msg,m->loclen);
264 CHECK_AVAIL(msg,NONCELEN);
265 m->nR=buf_unprepend(msg,NONCELEN);
266 if (type==LABEL_MSG1) {
270 CHECK_AVAIL(msg,NONCELEN);
271 m->nL=buf_unprepend(msg,NONCELEN);
272 if (type==LABEL_MSG2) {
277 m->pklen=buf_unprepend_uint16(msg);
278 CHECK_AVAIL(msg,m->pklen);
279 m->pk=buf_unprepend(msg,m->pklen);
280 m->hashlen=msg->start-m->hashstart;
282 m->siglen=buf_unprepend_uint16(msg);
283 CHECK_AVAIL(msg,m->siglen);
284 m->sig=buf_unprepend(msg,m->siglen);
289 static bool_t generate_msg1(struct site *st)
291 st->random->generate(st->random->st,NONCELEN,st->localN);
292 return generate_msg(st,LABEL_MSG1,"site:MSG1");
295 static bool_t process_msg1(struct site *st, struct buffer_if *msg1,
296 struct sockaddr_in *src)
300 /* We've already determined we're in an appropriate state to
301 process an incoming MSG1, and that the MSG1 has correct values
304 if (!unpick_msg(st,LABEL_MSG1,msg1,&m)) return False;
306 /* XXX save src as our peer address here? */
309 st->setup_session_id=m.source;
310 memcpy(st->remoteN,m.nR,NONCELEN);
314 static bool_t generate_msg2(struct site *st)
316 st->random->generate(st->random->st,NONCELEN,st->localN);
317 return generate_msg(st,LABEL_MSG2,"site:MSG2");
320 static bool_t process_msg2(struct site *st, struct buffer_if *msg2,
321 struct sockaddr_in *src)
325 if (!unpick_msg(st,LABEL_MSG2,msg2,&m)) return False;
327 /* Check that the site names and our nonce have been sent
328 back correctly, and then store our peer's nonce. */
329 if (memcmp(m.remote,st->remotename,strlen(st->remotename)!=0)) {
330 slog(st,LOG_SEC,"msg2: bad B (remote site name)");
333 if (memcmp(m.local,st->localname,strlen(st->localname)!=0)) {
334 slog(st,LOG_SEC,"msg2: bad A (local site name)");
337 if (memcmp(m.nL,st->localN,NONCELEN)!=0) {
338 slog(st,LOG_SEC,"msg2: bad nA (locally generated nonce)");
341 st->setup_session_id=m.source;
342 memcpy(st->remoteN,m.nR,NONCELEN);
346 static bool_t generate_msg3(struct site *st)
348 /* Now we have our nonce and their nonce. Think of a secret key,
349 and create message number 3. */
350 st->random->generate(st->random->st,st->dh->len,st->dhsecret);
351 return generate_msg(st,LABEL_MSG3,"site:MSG3");
354 static bool_t process_msg3(struct site *st, struct buffer_if *msg3,
355 struct sockaddr_in *src)
358 uint8_t *hash=alloca(st->hash->len);
361 if (!unpick_msg(st,LABEL_MSG3,msg3,&m)) return False;
363 /* Check that the site names and nonces have been sent back
365 if (memcmp(m.remote,st->remotename,strlen(st->remotename)!=0)) {
366 slog(st,LOG_SEC,"msg3: bad A (remote site name)");
369 if (memcmp(m.local,st->localname,strlen(st->localname)!=0)) {
370 slog(st,LOG_SEC,"msg3: bad B (local site name)");
373 if (memcmp(m.nR,st->remoteN,NONCELEN)!=0) {
374 slog(st,LOG_SEC,"msg3: bad nA (remotely generated nonce)");
377 if (memcmp(m.nL,st->localN,NONCELEN)!=0) {
378 slog(st,LOG_SEC,"msg3: bad nB (locally generated nonce)");
382 /* Check signature and store g^x mod m */
383 hst=st->hash->init();
384 st->hash->update(hst,m.hashstart,m.hashlen);
385 st->hash->final(hst,hash);
386 /* Terminate signature with a '0' - cheating, but should be ok */
388 if (!st->pubkey->check(st->pubkey->st,hash,st->hash->len,m.sig)) {
389 slog(st,LOG_SEC,"msg3 signature failed check!");
393 /* Terminate their DH public key with a '0' */
395 /* Invent our DH secret key */
396 st->random->generate(st->random->st,st->dh->len,st->dhsecret);
398 /* Generate the shared key */
399 st->dh->makeshared(st->dh->st,st->dhsecret,st->dh->len,m.pk,
400 st->sharedsecret,st->transform->keylen);
402 /* Set up the transform */
403 st->new_transform->setkey(st->new_transform->st,st->sharedsecret,
404 st->transform->keylen);
409 static bool_t generate_msg4(struct site *st)
411 /* We have both nonces, their public key and our private key. Generate
412 our public key, sign it and send it to them. */
413 return generate_msg(st,LABEL_MSG4,"site:MSG4");
416 static bool_t process_msg4(struct site *st, struct buffer_if *msg4,
417 struct sockaddr_in *src)
420 uint8_t *hash=alloca(st->hash->len);
423 if (!unpick_msg(st,LABEL_MSG4,msg4,&m)) return False;
425 /* Check that the site names and nonces have been sent back
427 if (memcmp(m.remote,st->remotename,strlen(st->remotename)!=0)) {
428 slog(st,LOG_SEC,"msg4: bad B (remote site name)");
431 if (memcmp(m.local,st->localname,strlen(st->localname)!=0)) {
432 slog(st,LOG_SEC,"msg4: bad A (local site name)");
435 if (memcmp(m.nR,st->remoteN,NONCELEN)!=0) {
436 slog(st,LOG_SEC,"msg4: bad nB (remotely generated nonce)");
439 if (memcmp(m.nL,st->localN,NONCELEN)!=0) {
440 slog(st,LOG_SEC,"msg4: bad nA (locally generated nonce)");
444 /* Check signature and store g^x mod m */
445 hst=st->hash->init();
446 st->hash->update(hst,m.hashstart,m.hashlen);
447 st->hash->final(hst,hash);
448 /* Terminate signature with a '0' - cheating, but should be ok */
450 if (!st->pubkey->check(st->pubkey->st,hash,st->hash->len,m.sig)) {
451 slog(st,LOG_SEC,"msg4 signature failed check!");
455 /* Terminate their DH public key with a '0' */
457 /* Generate the shared key */
458 st->dh->makeshared(st->dh->st,st->dhsecret,st->dh->len,m.pk,
459 st->sharedsecret,st->transform->keylen);
460 /* Set up the transform */
461 st->new_transform->setkey(st->new_transform->st,st->sharedsecret,
462 st->transform->keylen);
467 static bool_t generate_msg5(struct site *st)
469 string_t transform_err;
471 BUF_ALLOC(&st->buffer,"site:MSG5");
472 /* We are going to add three words to the transformed message */
473 buffer_init(&st->buffer,st->transform->max_start_pad+(4*3));
474 buf_append_uint32(&st->buffer,LABEL_MSG5);
475 st->new_transform->forwards(st->new_transform->st,&st->buffer,
477 buf_prepend_uint32(&st->buffer,LABEL_MSG5);
478 buf_prepend_uint32(&st->buffer,(uint32_t)st);
479 buf_prepend_uint32(&st->buffer,st->setup_session_id);
481 st->retries=st->setup_retries;
491 static bool_t unpick_msg0(struct site *st, struct buffer_if *msg0,
495 m->dest=buf_unprepend_uint32(msg0);
497 m->source=buf_unprepend_uint32(msg0);
499 m->type=buf_unprepend_uint32(msg0);
501 /* Leaves transformed part of buffer untouched */
504 static bool_t process_msg5(struct site *st, struct buffer_if *msg5,
505 struct sockaddr_in *src)
508 string_t transform_err;
510 if (!unpick_msg0(st,msg5,&m)) return False;
512 if (st->new_transform->reverse(st->new_transform->st,
513 msg5,&transform_err)) {
514 /* There's a problem */
515 slog(st,LOG_SEC,"process_msg5: transform: %s",transform_err);
518 /* Buffer should now contain untransformed PING packet data */
520 if (buf_unprepend_uint32(msg5)!=LABEL_MSG5) {
521 slog(st,LOG_SEC,"MSG5/PING packet contained invalid data");
528 static bool_t generate_msg6(struct site *st)
530 string_t transform_err;
532 BUF_ALLOC(&st->buffer,"site:MSG6");
533 /* We are going to add three words to the transformed message */
534 buffer_init(&st->buffer,st->transform->max_start_pad+(4*3));
535 buf_append_uint32(&st->buffer,LABEL_MSG6);
536 st->new_transform->forwards(st->new_transform->st,&st->buffer,
538 buf_prepend_uint32(&st->buffer,LABEL_MSG6);
539 buf_prepend_uint32(&st->buffer,(uint32_t)st);
540 buf_prepend_uint32(&st->buffer,st->setup_session_id);
542 st->retries=1; /* Peer will retransmit MSG5 if necessary */
546 static bool_t process_msg6(struct site *st, struct buffer_if *msg6,
547 struct sockaddr_in *src)
550 string_t transform_err;
552 if (!unpick_msg0(st,msg6,&m)) return False;
554 if (st->new_transform->reverse(st->new_transform->st,
555 msg6,&transform_err)) {
556 /* There's a problem */
557 slog(st,LOG_SEC,"process_msg6: transform: %s",transform_err);
560 /* Buffer should now contain untransformed PING packet data */
562 if (buf_unprepend_uint32(msg6)!=LABEL_MSG6) {
563 slog(st,LOG_SEC,"MSG6/PONG packet contained invalid data");
570 static bool_t process_msg0(struct site *st, struct buffer_if *msg0,
571 struct sockaddr_in *src)
574 string_t transform_err;
577 if (!st->current_valid) {
578 slog(st,LOG_DROP,"incoming message but no current key -> dropping");
579 if (st->state==SITE_RUN) {
580 slog(st,LOG_SETUP_INIT|LOG_STATE,
581 "now initiating setup of new key");
582 return enter_state_resolve(st);
587 if (!unpick_msg0(st,msg0,&m)) return False;
589 if (st->current_transform->reverse(st->current_transform->st,
590 msg0,&transform_err)) {
591 /* There's a problem */
592 slog(st,LOG_SEC,"transform: %s",transform_err);
596 type=buf_unprepend_uint32(msg0);
599 /* Deliver to netlink layer */
600 st->netlink->deliver(st->netlink->st,st->netlink_cid,msg0);
604 slog(st,LOG_SEC,"incoming message of type %08x (unknown)",type);
610 static void dump_packet(struct site *st, struct buffer_if *buf,
611 struct sockaddr_in *addr, bool_t incoming)
613 uint32_t dest=ntohl(*(uint32_t *)buf->start);
614 uint32_t source=ntohl(*(uint32_t *)(buf->start+4));
615 uint32_t msgtype=ntohl(*(uint32_t *)(buf->start+8));
617 if (st->log_events & LOG_DUMP)
618 log(st->log,0,"(%s,%s): %s: %08x<-%08x: %08x:",
619 st->localname,st->remotename,incoming?"incoming":"outgoing",
620 dest,source,msgtype);
623 static uint32_t site_status(void *st)
628 static bool_t send_msg(struct site *st)
631 dump_packet(st,&st->buffer,&st->setup_peer,False);
632 st->comm->sendmsg(st->comm->st,&st->buffer,&st->setup_peer);
633 st->timeout=st->now+st->setup_timeout;
637 slog(st,LOG_SETUP_TIMEOUT,"timed out sending key setup packet");
638 enter_state_wait(st);
643 static void site_resolve_callback(void *sst, struct in_addr *address)
647 if (st->state!=SITE_RESOLVE) {
648 slog(st,LOG_UNEXPECTED,"site_resolve_callback called unexpectedly");
652 memset(&st->setup_peer,0,sizeof(st->setup_peer));
653 st->setup_peer.sin_family=AF_INET;
654 st->setup_peer.sin_port=htons(st->remoteport);
655 st->setup_peer.sin_addr=*address;
656 enter_state_sentmsg1(st);
658 /* Resolution failed */
659 slog(st,LOG_ERROR,"resolution of %s failed",st->address);
664 static void activate_new_key(struct site *st)
666 struct transform_inst_if *t;
668 t=st->current_transform;
669 st->current_transform=st->new_transform;
675 st->current_valid=True;
676 st->current_key_timeout=st->now+st->key_lifetime;
677 st->peer=st->setup_peer;
679 st->remote_session_id=st->setup_session_id;
681 slog(st,LOG_ACTIVATE_KEY,"new key activated");
684 static void state_assert(struct site *st, bool_t ok)
686 if (!ok) fatal("state_assert\n");
689 static void enter_state_stop(struct site *st)
693 st->current_transform->delkey(st->current_transform->st);
694 st->current_valid=False;
695 st->current_key_timeout=0;
697 st->peer_valid=False;
699 st->new_transform->delkey(st->new_transform->st);
702 static void enter_state_run(struct site *st)
704 slog(st,LOG_STATE,"entering state RUN");
707 st->netlink->set_delivery(st->netlink->st,st->netlink_cid,True);
708 /* XXX get rid of key setup data */
711 static bool_t enter_state_resolve(struct site *st)
713 state_assert(st,st->state==SITE_RUN);
714 slog(st,LOG_STATE,"entering state RESOLVE");
715 st->state=SITE_RESOLVE;
716 st->resolver->request(st->resolver->st,st->address,
717 site_resolve_callback,st);
721 static bool_t enter_state_sentmsg1(struct site *st)
723 state_assert(st,st->state==SITE_RUN || st->state==SITE_RESOLVE);
724 slog(st,LOG_STATE,"entering state SENTMSG1");
725 if (generate_msg1(st) && send_msg(st)) {
726 st->state=SITE_SENTMSG1;
729 slog(st,LOG_ERROR,"error entering state SENTMSG1");
730 st->buffer.free=False; /* Can't tell which it was, but enter_state_wait()
731 will do a BUF_FREE() */
732 enter_state_wait(st);
736 static bool_t enter_state_sentmsg2(struct site *st)
738 state_assert(st,st->state==SITE_RUN || st->state==SITE_RESOLVE ||
739 st->state==SITE_SENTMSG1 || st->state==SITE_WAIT);
740 slog(st,LOG_STATE,"entering state SENTMSG2");
741 if (generate_msg2(st) && send_msg(st)) {
742 st->state=SITE_SENTMSG2;
745 slog(st,LOG_ERROR,"error entering state SENTMSG2");
746 st->buffer.free=False;
747 enter_state_wait(st);
751 static bool_t enter_state_sentmsg3(struct site *st)
753 state_assert(st,st->state==SITE_SENTMSG1);
754 slog(st,LOG_STATE,"entering state SENTMSG3");
755 BUF_FREE(&st->buffer); /* Free message 1 */
756 if (generate_msg3(st) && send_msg(st)) {
757 st->state=SITE_SENTMSG3;
760 slog(st,LOG_ERROR,"error entering state SENTMSG3");
761 st->buffer.free=False;
762 enter_state_wait(st);
766 static bool_t enter_state_sentmsg4(struct site *st)
768 state_assert(st,st->state==SITE_SENTMSG2);
769 slog(st,LOG_STATE,"entering state SENTMSG4");
770 BUF_FREE(&st->buffer); /* Free message 2 */
771 if (generate_msg4(st) && send_msg(st)) {
772 st->state=SITE_SENTMSG4;
775 slog(st,LOG_ERROR,"error entering state SENTMSG4");
776 st->buffer.free=False;
777 enter_state_wait(st);
781 static bool_t enter_state_sentmsg5(struct site *st)
783 state_assert(st,st->state==SITE_SENTMSG3);
784 slog(st,LOG_STATE,"entering state SENTMSG5");
785 BUF_FREE(&st->buffer); /* Free message 3 */
787 if (generate_msg5(st) && send_msg(st)) {
788 st->state=SITE_SENTMSG5;
791 slog(st,LOG_ERROR,"error entering state SENTMSG5");
792 st->buffer.free=False;
793 enter_state_wait(st);
798 static bool_t send_msg6(struct site *st)
800 state_assert(st,st->state==SITE_SENTMSG4);
801 slog(st,LOG_STATE,"entering state RUN after sending msg6");
802 BUF_FREE(&st->buffer); /* Free message 4 */
803 if (generate_msg6(st) && send_msg(st)) {
804 BUF_FREE(&st->buffer); /* Never reused */
805 st->timeout=0; /* Never retransmit */
806 activate_new_key(st);
809 slog(st,LOG_ERROR,"error entering state RUN after sending msg6");
810 st->buffer.free=False;
811 enter_state_wait(st);
815 /* We go into this state if our peer becomes uncommunicative. Similar to
816 the "stop" state, we forget all session keys for a while, before
817 re-entering the "run" state. */
818 static void enter_state_wait(struct site *st)
820 slog(st,LOG_STATE,"entering state WAIT");
821 st->timeout=st->now+st->wait_timeout;
823 st->peer_valid=False;
824 st->netlink->set_delivery(st->netlink->st,st->netlink_cid,False);
825 BUF_FREE(&st->buffer); /* will have had an outgoing packet in it */
826 /* XXX Erase keys etc. */
829 static int site_beforepoll(void *sst, struct pollfd *fds, int *nfds_io,
830 int *timeout_io, const struct timeval *tv_now,
835 *nfds_io=0; /* We don't use any file descriptors */
838 /* Work out when our next timeout is. The earlier of 'timeout' or
839 'current_key_timeout'. A stored value of '0' indicates no timeout
841 if (st->timeout && st->timeout-*now < *timeout_io) {
842 *timeout_io=st->timeout-*now;
845 if (st->current_key_timeout && st->current_key_timeout-*now < *timeout_io)
846 *timeout_io=st->current_key_timeout-*now;
848 return 0; /* success */
851 /* NB site_afterpoll will be called before site_beforepoll is ever called */
852 static void site_afterpoll(void *sst, struct pollfd *fds, int nfds,
853 const struct timeval *tv_now, uint64_t *now)
858 if (st->timeout && *now>st->timeout) {
861 if (st->state>=SITE_SENTMSG1 && st->state<=SITE_SENTMSG5)
863 else if (st->state==SITE_WAIT) {
866 slog(st,LOG_ERROR,"site_afterpoll: unexpected timeout, state=%d",
870 if (st->current_key_timeout && *now>st->current_key_timeout) {
871 slog(st,LOG_TIMEOUT_KEY,"maximum key life exceeded; session closed");
872 st->current_valid=False;
873 st->current_transform->delkey(st->current_transform->st);
874 st->current_key_timeout=0;
878 /* This function is called by the netlink device to deliver packets
879 intended for the remote network. The packet is in "raw" wire
880 format, but is guaranteed to be word-aligned. */
881 static void site_outgoing(void *sst, void *cid, struct buffer_if *buf)
884 string_t transform_err;
886 if (st->state==SITE_STOP) {
891 /* In all other states we consider delivering the packet if we have
892 a valid key and a valid address to send it to. */
893 if (st->current_valid && st->peer_valid) {
894 /* Transform it and send it */
895 buf_prepend_uint32(buf,LABEL_MSG9);
896 st->current_transform->forwards(st->current_transform->st,
897 buf, &transform_err);
898 buf_prepend_uint32(buf,LABEL_MSG0);
899 buf_prepend_uint32(buf,(uint32_t)st);
900 buf_prepend_uint32(buf,st->remote_session_id);
901 st->comm->sendmsg(st->comm->st,buf,&st->peer);
906 if (st->state==SITE_RUN) {
907 BUF_FREE(buf); /* We throw the outgoing packet away */
908 slog(st,LOG_SETUP_INIT,"initiating key exchange");
909 enter_state_resolve(st);
913 /* Otherwise we're in the middle of key setup or a wait - just
914 throw the outgoing packet away */
915 slog(st,LOG_DROP,"discarding outgoing packet");
920 /* This function is called by the communication device to deliver
921 packets from our peers. */
922 static bool_t site_incoming(void *sst, struct buffer_if *buf,
923 struct sockaddr_in *source)
926 uint32_t dest=ntohl(*(uint32_t *)buf->start);
929 if (buf->size<(st->setupsiglen+8+NONCELEN)) return False;
930 /* It could be for any site - it should have LABEL_MSG1 and
931 might have our name and our peer's name in it */
932 if (memcmp(buf->start+8,st->setupsig,st->setupsiglen)==0) {
933 dump_packet(st,buf,source,True);
934 /* It's addressed to us. Decide what to do about it. */
935 if (st->state==SITE_RUN || st->state==SITE_RESOLVE ||
936 st->state==SITE_WAIT) {
937 /* We should definitely process it */
938 if (process_msg1(st,buf,source)) {
939 slog(st,LOG_SETUP_INIT,"key setup initiated by peer");
940 enter_state_sentmsg2(st);
942 slog(st,LOG_ERROR,"failed to process incoming msg1");
947 if (st->state==SITE_SENTMSG1) {
948 /* We've just sent a message 1! They may have crossed on
949 the wire. If we have priority then we ignore the
950 incoming one, otherwise we process it as usual. */
951 if (st->setup_priority) {
953 slog(st,LOG_DUMP,"crossed msg1s; we are higher "
954 "priority => ignore incoming msg1");
957 slog(st,LOG_DUMP,"crossed msg1s; we are lower "
958 "priority => use incoming msg1");
959 if (process_msg1(st,buf,source)) {
960 BUF_FREE(&st->buffer); /* Free our old message 1 */
961 enter_state_sentmsg2(st);
963 slog(st,LOG_ERROR,"failed to process an incoming "
964 "crossed msg1 (we have low priority)");
970 /* The message 1 was received at an unexpected stage of the
971 key setup. XXX POLICY - what do we do? */
972 slog(st,LOG_UNEXPECTED,"unexpected incoming message 1");
976 return False; /* Not for us. */
978 if (dest==(uint32_t)st) {
979 uint32_t msgtype=ntohl(*(uint32_t *)(buf->start+8));
980 /* Explicitly addressed to us */
981 if (msgtype!=LABEL_MSG0) dump_packet(st,buf,source,True);
984 process_msg0(st,buf,source);
987 /* Setup packet: should not have been explicitly addressed
989 slog(st,LOG_SEC,"incoming explicitly addressed msg1");
992 /* Setup packet: expected only in state SENTMSG1 */
993 if (st->state!=SITE_SENTMSG1) {
994 slog(st,LOG_UNEXPECTED,"unexpected MSG2");
995 } else if (process_msg2(st,buf,source))
996 enter_state_sentmsg3(st);
998 slog(st,LOG_SEC,"invalid MSG2");
1002 /* Setup packet: expected only in state SENTMSG2 */
1003 if (st->state!=SITE_SENTMSG2) {
1004 slog(st,LOG_UNEXPECTED,"unexpected MSG3");
1005 } else if (process_msg3(st,buf,source))
1006 enter_state_sentmsg4(st);
1008 slog(st,LOG_SEC,"invalid MSG3");
1012 /* Setup packet: expected only in state SENTMSG3 */
1013 if (st->state!=SITE_SENTMSG3) {
1014 slog(st,LOG_UNEXPECTED,"unexpected MSG4");
1015 } else if (process_msg4(st,buf,source))
1016 enter_state_sentmsg5(st);
1018 slog(st,LOG_SEC,"invalid MSG4");
1022 /* Setup packet: expected only in state SENTMSG4 */
1023 /* (may turn up in state RUN if our return MSG6 was lost
1024 and the new key has already been activated. In that
1025 case we should treat it as an ordinary PING packet. We
1026 can't pass it to process_msg5() because the
1027 new_transform will now be null. XXX) */
1028 if (st->state!=SITE_SENTMSG4) {
1029 slog(st,LOG_UNEXPECTED,"unexpected MSG5");
1030 } else if (process_msg5(st,buf,source)) {
1033 slog(st,LOG_SEC,"invalid MSG5");
1037 /* Setup packet: expected only in state SENTMSG5 */
1038 if (st->state!=SITE_SENTMSG5) {
1039 slog(st,LOG_UNEXPECTED,"unexpected MSG6");
1040 } else if (process_msg6(st,buf,source)) {
1041 BUF_FREE(&st->buffer); /* Free message 5 */
1042 activate_new_key(st);
1044 slog(st,LOG_SEC,"invalid MSG6");
1048 /* NAK packet: enter state where we ping and check for response */
1049 slog(st,LOG_ERROR,"received a NAK");
1052 slog(st,LOG_SEC,"received message of unknown type 0x%08x",
1063 static void site_control(void *vst, bool_t run)
1065 struct site *st=vst;
1066 if (run) enter_state_run(st);
1067 else enter_state_stop(st);
1070 static list_t *site_apply(closure_t *self, struct cloc loc, dict_t *context,
1077 st=safe_malloc(sizeof(*st),"site_apply");
1079 st->cl.description="site";
1080 st->cl.type=CL_SITE;
1082 st->cl.interface=&st->ops;
1084 st->ops.control=site_control;
1085 st->ops.status=site_status;
1087 /* First parameter must be a dict */
1088 item=list_elem(args,0);
1089 if (!item || item->type!=t_dict)
1090 cfgfatal(loc,"site","parameter must be a dictionary\n");
1092 dict=item->data.dict;
1093 st->localname=dict_read_string(dict, "local-name", True, "site", loc);
1094 st->remotename=dict_read_string(dict, "name", True, "site", loc);
1095 /* Sanity check (which also allows the 'sites' file to include
1096 site() closures for all sites including our own): refuse to
1097 talk to ourselves */
1098 if (strcmp(st->localname,st->remotename)==0) {
1099 Message(M_INFO,"site %s: local-name==name -> ignoring this site\n",
1104 st->netlink=find_cl_if(dict,"netlink",CL_NETLINK,True,"site",loc);
1105 st->comm=find_cl_if(dict,"comm",CL_COMM,True,"site",loc);
1106 st->resolver=find_cl_if(dict,"resolver",CL_RESOLVER,True,"site",loc);
1107 st->log=find_cl_if(dict,"log",CL_LOG,True,"site",loc);
1108 st->random=find_cl_if(dict,"random",CL_RANDOMSRC,True,"site",loc);
1110 st->privkey=find_cl_if(dict,"local-key",CL_RSAPRIVKEY,True,"site",loc);
1111 st->remoteport=dict_read_number(dict,"port",True,"site",loc,0);
1113 st->address=dict_read_string(dict, "address", False, "site", loc);
1114 dict_read_subnet_list(dict, "networks", True, "site", loc,
1116 st->pubkey=find_cl_if(dict,"key",CL_RSAPUBKEY,True,"site",loc);
1119 find_cl_if(dict,"transform",CL_TRANSFORM,True,"site",loc);
1121 st->dh=find_cl_if(dict,"dh",CL_DH,True,"site",loc);
1122 st->hash=find_cl_if(dict,"hash",CL_HASH,True,"site",loc);
1124 st->key_lifetime=dict_read_number(dict,"key-lifetime",
1125 False,"site",loc,DEFAULT_KEY_LIFETIME);
1126 st->setup_retries=dict_read_number(dict,"setup-retries",
1127 False,"site",loc,DEFAULT_SETUP_RETRIES);
1128 st->setup_timeout=dict_read_number(dict,"setup-timeout",
1129 False,"site",loc,DEFAULT_SETUP_TIMEOUT);
1130 st->wait_timeout=dict_read_number(dict,"wait-time",
1131 False,"site",loc,DEFAULT_WAIT_TIME);
1132 /* XXX should be configurable */
1133 st->log_events=LOG_SEC|LOG_ERROR|
1134 LOG_ACTIVATE_KEY|LOG_TIMEOUT_KEY|LOG_SETUP_INIT|LOG_SETUP_TIMEOUT;
1136 st->tunname=safe_malloc(strlen(st->localname)+strlen(st->remotename)+5,
1138 sprintf(st->tunname,"%s<->%s",st->localname,st->remotename);
1140 /* The information we expect to see in incoming messages of type 1 */
1141 /* XXX fix this bit for unaligned access */
1142 st->setupsiglen=strlen(st->remotename)+strlen(st->localname)+8;
1143 st->setupsig=safe_malloc(st->setupsiglen,"site_apply");
1144 put_uint32(st->setupsig+0,LABEL_MSG1);
1145 put_uint16(st->setupsig+4,strlen(st->remotename));
1146 memcpy(&st->setupsig[6],st->remotename,strlen(st->remotename));
1147 put_uint16(st->setupsig+(6+strlen(st->remotename)),strlen(st->localname));
1148 memcpy(&st->setupsig[8+strlen(st->remotename)],st->localname,
1149 strlen(st->localname));
1150 st->setup_priority=(strcmp(st->localname,st->remotename)>0);
1152 buffer_new(&st->buffer,SETUP_BUFFER_LEN);
1154 /* We are interested in poll(), but only for timeouts. We don't have
1155 any fds of our own. */
1156 register_for_poll(st, site_beforepoll, site_afterpoll, 0, "site");
1159 st->current_valid=False;
1160 st->current_key_timeout=0;
1161 st->peer_valid=False;
1162 /* XXX mlock these */
1163 st->dhsecret=safe_malloc(st->dh->len,"site:dhsecret");
1164 st->sharedsecret=safe_malloc(st->transform->keylen,"site:sharedsecret");
1166 /* We need to register the remote networks with the netlink device */
1167 st->netlink_cid=st->netlink->regnets(st->netlink->st, &st->remotenets,
1169 st->transform->max_start_pad+(4*4),
1170 st->transform->max_end_pad,
1173 st->comm->request_notify(st->comm->st, st, site_incoming);
1175 st->current_transform=st->transform->create(st->transform->st);
1176 st->new_transform=st->transform->create(st->transform->st);
1178 enter_state_stop(st);
1180 return new_closure(&st->cl);
1183 init_module site_module;
1184 void site_module(dict_t *dict)
1186 add_closure(dict,"site",site_apply);