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>
11 #include "unaligned.h"
13 #define SETUP_BUFFER_LEN 2048
15 #define DEFAULT_KEY_LIFETIME 3600000 /* One hour */
16 #define DEFAULT_KEY_RENEGOTIATE_GAP 300000 /* Five minutes */
17 #define DEFAULT_SETUP_RETRIES 5
18 #define DEFAULT_SETUP_TIMEOUT 1000
19 #define DEFAULT_WAIT_TIME 20000
21 /* Each site can be in one of several possible states. */
24 SITE_STOP - nothing is allowed to happen; tunnel is down;
25 all session keys have been erased
26 -> SITE_RUN upon external instruction
27 SITE_RUN - site up, maybe with valid key
28 -> SITE_RESOLVE upon outgoing packet and no valid key
29 we start name resolution for the other end of the tunnel
30 -> SITE_SENTMSG2 upon valid incoming message 1 and suitable time
31 we send an appropriate message 2
32 SITE_RESOLVE - waiting for name resolution
33 -> SITE_SENTMSG1 upon successful resolution
34 we send an appropriate message 1
35 -> SITE_SENTMSG2 upon valid incoming message 1 (then abort resolution)
36 we abort resolution and
37 -> SITE_WAIT on timeout or resolution failure
39 -> SITE_SENTMSG2 upon valid incoming message 1 from higher priority end
40 -> SITE_SENTMSG3 upon valid incoming message 2
41 -> SITE_WAIT on timeout
43 -> SITE_SENTMSG4 upon valid incoming message 3
44 -> SITE_WAIT on timeout
46 -> SITE_SENTMSG5 upon valid incoming message 4
47 -> SITE_WAIT on timeout
49 -> SITE_RUN upon valid incoming message 5
50 -> SITE_WAIT on timeout
52 -> SITE_RUN upon valid incoming message 6
53 -> SITE_WAIT on timeout
54 SITE_WAIT - failed to establish key; do nothing for a while
55 -> SITE_RUN on timeout
60 #define SITE_RESOLVE 2
61 #define SITE_SENTMSG1 3
62 #define SITE_SENTMSG2 4
63 #define SITE_SENTMSG3 5
64 #define SITE_SENTMSG4 6
65 #define SITE_SENTMSG5 7
68 static string_t state_name(uint32_t state)
71 case 0: return "STOP";
73 case 2: return "RESOLVE";
74 case 3: return "SENTMSG1";
75 case 4: return "SENTMSG2";
76 case 5: return "SENTMSG3";
77 case 6: return "SENTMSG4";
78 case 7: return "SENTMSG5";
79 case 8: return "WAIT";
80 default: return "*bad state*";
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
108 static struct flagstr log_event_table[]={
109 { "unexpected", LOG_UNEXPECTED },
110 { "setup-init", LOG_SETUP_INIT },
111 { "setup-timeout", LOG_SETUP_TIMEOUT },
112 { "activate-key", LOG_ACTIVATE_KEY },
113 { "timeout-key", LOG_TIMEOUT_KEY },
114 { "security", LOG_SEC },
115 { "state-change", LOG_STATE },
116 { "packet-drop", LOG_DROP },
117 { "dump-packets", LOG_DUMP },
118 { "errors", LOG_ERROR },
119 { "all", 0xffffffff },
123 static struct flagstr netlink_option_table[]={
124 { "soft", NETLINK_OPTION_SOFTROUTE },
125 { "allow-route", NETLINK_OPTION_ALLOW_ROUTE },
132 /* configuration information */
135 string_t tunname; /* localname<->remotename by default */
136 string_t address; /* DNS name for bootstrapping, optional */
138 struct netlink_if *netlink;
139 struct comm_if *comm;
140 struct resolver_if *resolver;
142 struct random_if *random;
143 struct rsaprivkey_if *privkey;
144 struct subnet_list remotenets;
145 struct rsapubkey_if *pubkey;
146 struct transform_if *transform;
148 struct hash_if *hash;
150 uint32_t setup_retries; /* How many times to send setup packets */
151 uint32_t setup_timeout; /* Initial timeout for setup packets */
152 uint32_t wait_timeout; /* How long to wait if setup unsuccessful */
153 uint32_t key_lifetime; /* How long a key lasts once set up */
154 uint32_t key_renegotiate_time; /* If we see traffic (or a keepalive)
155 after this time, initiate a new
158 bool_t keepalive; /* Always keep the tunnel up */
160 uint8_t *setupsig; /* Expected signature of incoming MSG1 packets */
161 uint32_t setupsiglen; /* Allows us to discard packets quickly if
162 they are not for us */
163 bool_t setup_priority; /* Do we have precedence if both sites emit
164 message 1 simultaneously? */
167 /* runtime information */
169 uint64_t now; /* Most recently seen time */
173 uint32_t remote_session_id;
174 struct transform_inst_if *current_transform;
175 bool_t current_valid;
176 uint64_t current_key_timeout; /* End of life of current key */
177 struct sockaddr_in peer; /* Current address of peer */
178 bool_t peer_valid; /* Peer address becomes invalid when key times out,
179 but only if we have a DNS name for our peer */
181 uint32_t setup_session_id;
182 struct sockaddr_in setup_peer;
183 uint8_t localN[NONCELEN]; /* Nonces for key exchange */
184 uint8_t remoteN[NONCELEN];
185 struct buffer_if buffer; /* Current outgoing key exchange packet */
186 uint32_t retries; /* Number of retries remaining */
187 uint64_t timeout; /* Timeout for current state */
189 uint8_t *sharedsecret;
191 struct transform_inst_if *new_transform; /* For key setup/verify */
194 static void slog(struct site *st, uint32_t event, string_t msg, ...)
202 if (event&st->log_events) {
204 case LOG_UNEXPECTED: class=M_INFO; break;
205 case LOG_SETUP_INIT: class=M_INFO; break;
206 case LOG_SETUP_TIMEOUT: class=M_NOTICE; break;
207 case LOG_ACTIVATE_KEY: class=M_INFO; break;
208 case LOG_TIMEOUT_KEY: class=M_INFO; break;
209 case LOG_SEC: class=M_SECURITY; break;
210 case LOG_STATE: class=M_DEBUG; break;
211 case LOG_DROP: class=M_DEBUG; break;
212 case LOG_DUMP: class=M_DEBUG; break;
213 case LOG_ERROR: class=M_ERROR; break;
214 default: class=M_ERROR; break;
217 vsnprintf(buf,240,msg,ap);
218 st->log->log(st->log->st,class,"%s: %s",st->tunname,buf);
223 static void set_link_quality(struct site *st);
224 static bool_t initiate_key_setup(struct site *st);
225 static void enter_state_run(struct site *st);
226 static bool_t enter_state_resolve(struct site *st);
227 static bool_t enter_state_sentmsg1(struct site *st);
228 static bool_t enter_state_sentmsg2(struct site *st);
229 static bool_t enter_state_sentmsg3(struct site *st);
230 static bool_t enter_state_sentmsg4(struct site *st);
231 static bool_t enter_state_sentmsg5(struct site *st);
232 static void enter_state_wait(struct site *st);
234 #define CHECK_AVAIL(b,l) do { if ((b)->size<(l)) return False; } while(0)
235 #define CHECK_EMPTY(b) do { if ((b)->size!=0) return False; } while(0)
236 #define CHECK_TYPE(b,t) do { uint32_t type; \
237 CHECK_AVAIL((b),4); \
238 type=buf_unprepend_uint32((b)); \
239 if (type!=(t)) return False; } while(0)
258 /* Build any of msg1 to msg4. msg5 and msg6 are built from the inside out
259 using a transform. */
260 static bool_t generate_msg(struct site *st, uint32_t type, string_t what)
263 uint8_t *hash=alloca(st->hash->len);
266 st->retries=st->setup_retries;
267 BUF_ALLOC(&st->buffer,what);
268 buffer_init(&st->buffer,0);
269 buf_append_uint32(&st->buffer,
270 (type==LABEL_MSG1?0:st->setup_session_id));
271 buf_append_uint32(&st->buffer,(uint32_t)st);
272 buf_append_uint32(&st->buffer,type);
273 buf_append_string(&st->buffer,st->localname);
274 buf_append_string(&st->buffer,st->remotename);
275 memcpy(buf_append(&st->buffer,NONCELEN),st->localN,NONCELEN);
276 if (type==LABEL_MSG1) return True;
277 memcpy(buf_append(&st->buffer,NONCELEN),st->remoteN,NONCELEN);
278 if (type==LABEL_MSG2) return True;
279 dhpub=st->dh->makepublic(st->dh->st,st->dhsecret,st->dh->len);
280 buf_append_string(&st->buffer,dhpub);
282 hst=st->hash->init();
283 st->hash->update(hst,st->buffer.start,st->buffer.size);
284 st->hash->final(hst,hash);
285 sig=st->privkey->sign(st->privkey->st,hash,st->hash->len);
286 buf_append_string(&st->buffer,sig);
291 static bool_t unpick_msg(struct site *st, uint32_t type,
292 struct buffer_if *msg, struct msg *m)
294 m->hashstart=msg->start;
296 m->dest=buf_unprepend_uint32(msg);
298 m->source=buf_unprepend_uint32(msg);
299 CHECK_TYPE(msg,type);
301 m->remlen=buf_unprepend_uint16(msg);
302 CHECK_AVAIL(msg,m->remlen);
303 m->remote=buf_unprepend(msg,m->remlen);
305 m->loclen=buf_unprepend_uint16(msg);
306 CHECK_AVAIL(msg,m->loclen);
307 m->local=buf_unprepend(msg,m->loclen);
308 CHECK_AVAIL(msg,NONCELEN);
309 m->nR=buf_unprepend(msg,NONCELEN);
310 if (type==LABEL_MSG1) {
314 CHECK_AVAIL(msg,NONCELEN);
315 m->nL=buf_unprepend(msg,NONCELEN);
316 if (type==LABEL_MSG2) {
321 m->pklen=buf_unprepend_uint16(msg);
322 CHECK_AVAIL(msg,m->pklen);
323 m->pk=buf_unprepend(msg,m->pklen);
324 m->hashlen=msg->start-m->hashstart;
326 m->siglen=buf_unprepend_uint16(msg);
327 CHECK_AVAIL(msg,m->siglen);
328 m->sig=buf_unprepend(msg,m->siglen);
333 static bool_t generate_msg1(struct site *st)
335 st->random->generate(st->random->st,NONCELEN,st->localN);
336 return generate_msg(st,LABEL_MSG1,"site:MSG1");
339 static bool_t process_msg1(struct site *st, struct buffer_if *msg1,
340 struct sockaddr_in *src)
344 /* We've already determined we're in an appropriate state to
345 process an incoming MSG1, and that the MSG1 has correct values
348 if (!unpick_msg(st,LABEL_MSG1,msg1,&m)) return False;
350 /* XXX save src as our peer address here? */
353 st->setup_session_id=m.source;
354 memcpy(st->remoteN,m.nR,NONCELEN);
358 static bool_t generate_msg2(struct site *st)
360 st->random->generate(st->random->st,NONCELEN,st->localN);
361 return generate_msg(st,LABEL_MSG2,"site:MSG2");
364 static bool_t process_msg2(struct site *st, struct buffer_if *msg2,
365 struct sockaddr_in *src)
369 if (!unpick_msg(st,LABEL_MSG2,msg2,&m)) return False;
371 /* Check that the site names and our nonce have been sent
372 back correctly, and then store our peer's nonce. */
373 if (memcmp(m.remote,st->remotename,strlen(st->remotename)!=0)) {
374 slog(st,LOG_SEC,"msg2: bad B (remote site name)");
377 if (memcmp(m.local,st->localname,strlen(st->localname)!=0)) {
378 slog(st,LOG_SEC,"msg2: bad A (local site name)");
381 if (memcmp(m.nL,st->localN,NONCELEN)!=0) {
382 slog(st,LOG_SEC,"msg2: bad nA (locally generated nonce)");
385 st->setup_session_id=m.source;
386 memcpy(st->remoteN,m.nR,NONCELEN);
390 static bool_t generate_msg3(struct site *st)
392 /* Now we have our nonce and their nonce. Think of a secret key,
393 and create message number 3. */
394 st->random->generate(st->random->st,st->dh->len,st->dhsecret);
395 return generate_msg(st,LABEL_MSG3,"site:MSG3");
398 static bool_t process_msg3(struct site *st, struct buffer_if *msg3,
399 struct sockaddr_in *src)
402 uint8_t *hash=alloca(st->hash->len);
405 if (!unpick_msg(st,LABEL_MSG3,msg3,&m)) return False;
407 /* Check that the site names and nonces have been sent back
409 if (memcmp(m.remote,st->remotename,strlen(st->remotename)!=0)) {
410 slog(st,LOG_SEC,"msg3: bad A (remote site name)");
413 if (memcmp(m.local,st->localname,strlen(st->localname)!=0)) {
414 slog(st,LOG_SEC,"msg3: bad B (local site name)");
417 if (memcmp(m.nR,st->remoteN,NONCELEN)!=0) {
418 slog(st,LOG_SEC,"msg3: bad nA (remotely generated nonce)");
421 if (memcmp(m.nL,st->localN,NONCELEN)!=0) {
422 slog(st,LOG_SEC,"msg3: bad nB (locally generated nonce)");
426 /* Check signature and store g^x mod m */
427 hst=st->hash->init();
428 st->hash->update(hst,m.hashstart,m.hashlen);
429 st->hash->final(hst,hash);
430 /* Terminate signature with a '0' - cheating, but should be ok */
432 if (!st->pubkey->check(st->pubkey->st,hash,st->hash->len,m.sig)) {
433 slog(st,LOG_SEC,"msg3 signature failed check!");
437 /* Terminate their DH public key with a '0' */
439 /* Invent our DH secret key */
440 st->random->generate(st->random->st,st->dh->len,st->dhsecret);
442 /* Generate the shared key */
443 st->dh->makeshared(st->dh->st,st->dhsecret,st->dh->len,m.pk,
444 st->sharedsecret,st->transform->keylen);
446 /* Set up the transform */
447 st->new_transform->setkey(st->new_transform->st,st->sharedsecret,
448 st->transform->keylen);
453 static bool_t generate_msg4(struct site *st)
455 /* We have both nonces, their public key and our private key. Generate
456 our public key, sign it and send it to them. */
457 return generate_msg(st,LABEL_MSG4,"site:MSG4");
460 static bool_t process_msg4(struct site *st, struct buffer_if *msg4,
461 struct sockaddr_in *src)
464 uint8_t *hash=alloca(st->hash->len);
467 if (!unpick_msg(st,LABEL_MSG4,msg4,&m)) return False;
469 /* Check that the site names and nonces have been sent back
471 if (memcmp(m.remote,st->remotename,strlen(st->remotename)!=0)) {
472 slog(st,LOG_SEC,"msg4: bad B (remote site name)");
475 if (memcmp(m.local,st->localname,strlen(st->localname)!=0)) {
476 slog(st,LOG_SEC,"msg4: bad A (local site name)");
479 if (memcmp(m.nR,st->remoteN,NONCELEN)!=0) {
480 slog(st,LOG_SEC,"msg4: bad nB (remotely generated nonce)");
483 if (memcmp(m.nL,st->localN,NONCELEN)!=0) {
484 slog(st,LOG_SEC,"msg4: bad nA (locally generated nonce)");
488 /* Check signature and store g^x mod m */
489 hst=st->hash->init();
490 st->hash->update(hst,m.hashstart,m.hashlen);
491 st->hash->final(hst,hash);
492 /* Terminate signature with a '0' - cheating, but should be ok */
494 if (!st->pubkey->check(st->pubkey->st,hash,st->hash->len,m.sig)) {
495 slog(st,LOG_SEC,"msg4 signature failed check!");
499 /* Terminate their DH public key with a '0' */
501 /* Generate the shared key */
502 st->dh->makeshared(st->dh->st,st->dhsecret,st->dh->len,m.pk,
503 st->sharedsecret,st->transform->keylen);
504 /* Set up the transform */
505 st->new_transform->setkey(st->new_transform->st,st->sharedsecret,
506 st->transform->keylen);
511 static bool_t generate_msg5(struct site *st)
513 string_t transform_err;
515 BUF_ALLOC(&st->buffer,"site:MSG5");
516 /* We are going to add three words to the transformed message */
517 buffer_init(&st->buffer,st->transform->max_start_pad+(4*3));
518 buf_append_uint32(&st->buffer,LABEL_MSG5);
519 st->new_transform->forwards(st->new_transform->st,&st->buffer,
521 buf_prepend_uint32(&st->buffer,LABEL_MSG5);
522 buf_prepend_uint32(&st->buffer,(uint32_t)st);
523 buf_prepend_uint32(&st->buffer,st->setup_session_id);
525 st->retries=st->setup_retries;
535 static bool_t unpick_msg0(struct site *st, struct buffer_if *msg0,
539 m->dest=buf_unprepend_uint32(msg0);
541 m->source=buf_unprepend_uint32(msg0);
543 m->type=buf_unprepend_uint32(msg0);
545 /* Leaves transformed part of buffer untouched */
548 static bool_t process_msg5(struct site *st, struct buffer_if *msg5,
549 struct sockaddr_in *src)
552 string_t transform_err;
554 if (!unpick_msg0(st,msg5,&m)) return False;
556 if (st->new_transform->reverse(st->new_transform->st,
557 msg5,&transform_err)) {
558 /* There's a problem */
559 slog(st,LOG_SEC,"process_msg5: transform: %s",transform_err);
562 /* Buffer should now contain untransformed PING packet data */
564 if (buf_unprepend_uint32(msg5)!=LABEL_MSG5) {
565 slog(st,LOG_SEC,"MSG5/PING packet contained invalid data");
572 static bool_t generate_msg6(struct site *st)
574 string_t transform_err;
576 BUF_ALLOC(&st->buffer,"site:MSG6");
577 /* We are going to add three words to the transformed message */
578 buffer_init(&st->buffer,st->transform->max_start_pad+(4*3));
579 buf_append_uint32(&st->buffer,LABEL_MSG6);
580 st->new_transform->forwards(st->new_transform->st,&st->buffer,
582 buf_prepend_uint32(&st->buffer,LABEL_MSG6);
583 buf_prepend_uint32(&st->buffer,(uint32_t)st);
584 buf_prepend_uint32(&st->buffer,st->setup_session_id);
586 st->retries=1; /* Peer will retransmit MSG5 if necessary */
590 static bool_t process_msg6(struct site *st, struct buffer_if *msg6,
591 struct sockaddr_in *src)
594 string_t transform_err;
596 if (!unpick_msg0(st,msg6,&m)) return False;
598 if (st->new_transform->reverse(st->new_transform->st,
599 msg6,&transform_err)) {
600 /* There's a problem */
601 slog(st,LOG_SEC,"process_msg6: transform: %s",transform_err);
604 /* Buffer should now contain untransformed PING packet data */
606 if (buf_unprepend_uint32(msg6)!=LABEL_MSG6) {
607 slog(st,LOG_SEC,"MSG6/PONG packet contained invalid data");
614 static bool_t process_msg0(struct site *st, struct buffer_if *msg0,
615 struct sockaddr_in *src)
618 string_t transform_err;
621 if (!st->current_valid) {
622 slog(st,LOG_DROP,"incoming message but no current key -> dropping");
623 return initiate_key_setup(st);
626 if (!unpick_msg0(st,msg0,&m)) return False;
628 if (st->current_transform->reverse(st->current_transform->st,
629 msg0,&transform_err)) {
630 /* There's a problem */
631 slog(st,LOG_SEC,"transform: %s",transform_err);
635 type=buf_unprepend_uint32(msg0);
638 /* Deliver to netlink layer */
639 st->netlink->deliver(st->netlink->st,st->netlink_cid,msg0);
643 slog(st,LOG_SEC,"incoming message of type %08x (unknown)",type);
649 static void dump_packet(struct site *st, struct buffer_if *buf,
650 struct sockaddr_in *addr, bool_t incoming)
652 uint32_t dest=ntohl(*(uint32_t *)buf->start);
653 uint32_t source=ntohl(*(uint32_t *)(buf->start+4));
654 uint32_t msgtype=ntohl(*(uint32_t *)(buf->start+8));
656 if (st->log_events & LOG_DUMP)
657 log(st->log,M_DEBUG,"%s: %s: %08x<-%08x: %08x:",
658 st->tunname,incoming?"incoming":"outgoing",
659 dest,source,msgtype);
662 static uint32_t site_status(void *st)
667 static bool_t send_msg(struct site *st)
670 dump_packet(st,&st->buffer,&st->setup_peer,False);
671 st->comm->sendmsg(st->comm->st,&st->buffer,&st->setup_peer);
672 st->timeout=st->now+st->setup_timeout;
676 slog(st,LOG_SETUP_TIMEOUT,"timed out sending key setup packet "
677 "(in state %s)",state_name(st->state));
678 enter_state_wait(st);
683 static void site_resolve_callback(void *sst, struct in_addr *address)
687 if (st->state!=SITE_RESOLVE) {
688 slog(st,LOG_UNEXPECTED,"site_resolve_callback called unexpectedly");
692 memset(&st->setup_peer,0,sizeof(st->setup_peer));
693 st->setup_peer.sin_family=AF_INET;
694 st->setup_peer.sin_port=htons(st->remoteport);
695 st->setup_peer.sin_addr=*address;
696 enter_state_sentmsg1(st);
698 /* Resolution failed */
699 slog(st,LOG_ERROR,"resolution of %s failed",st->address);
704 static bool_t initiate_key_setup(struct site *st)
706 if (st->state!=SITE_RUN) return False;
708 slog(st,LOG_SETUP_INIT,"initiating key exchange; resolving address");
709 return enter_state_resolve(st);
710 } else if (st->peer_valid) {
711 slog(st,LOG_SETUP_INIT,"initiating key exchange using old "
713 st->setup_peer=st->peer;
714 return enter_state_sentmsg1(st);
719 static void activate_new_key(struct site *st)
721 struct transform_inst_if *t;
723 t=st->current_transform;
724 st->current_transform=st->new_transform;
729 st->current_valid=True;
730 st->current_key_timeout=st->now+st->key_lifetime;
731 st->peer=st->setup_peer;
733 st->remote_session_id=st->setup_session_id;
735 slog(st,LOG_ACTIVATE_KEY,"new key activated");
739 static void state_assert(struct site *st, bool_t ok)
741 if (!ok) fatal("state_assert\n");
744 static void enter_state_stop(struct site *st)
748 st->current_transform->delkey(st->current_transform->st);
749 st->current_valid=False;
750 st->current_key_timeout=0;
752 st->peer_valid=False;
754 set_link_quality(st);
756 st->new_transform->delkey(st->new_transform->st);
759 static void set_link_quality(struct site *st)
762 if (st->current_valid)
763 quality=LINK_QUALITY_UP;
764 else if (st->state==SITE_WAIT || st->state==SITE_STOP)
765 quality=LINK_QUALITY_DOWN;
766 else if (st->address)
767 quality=LINK_QUALITY_DOWN_CURRENT_ADDRESS;
768 else if (st->peer_valid)
769 quality=LINK_QUALITY_DOWN_STALE_ADDRESS;
771 quality=LINK_QUALITY_DOWN;
773 st->netlink->set_quality(st->netlink->st,st->netlink_cid,quality);
776 static void enter_state_run(struct site *st)
778 slog(st,LOG_STATE,"entering state RUN");
782 set_link_quality(st);
783 /* XXX get rid of key setup data */
786 static bool_t enter_state_resolve(struct site *st)
788 state_assert(st,st->state==SITE_RUN);
789 slog(st,LOG_STATE,"entering state RESOLVE");
790 st->state=SITE_RESOLVE;
791 st->resolver->request(st->resolver->st,st->address,
792 site_resolve_callback,st);
796 static bool_t enter_state_sentmsg1(struct site *st)
798 state_assert(st,st->state==SITE_RUN || st->state==SITE_RESOLVE);
799 slog(st,LOG_STATE,"entering state SENTMSG1");
800 if (generate_msg1(st) && send_msg(st)) {
801 st->state=SITE_SENTMSG1;
804 slog(st,LOG_ERROR,"error entering state SENTMSG1");
805 st->buffer.free=False; /* Can't tell which it was, but enter_state_wait()
806 will do a BUF_FREE() */
807 enter_state_wait(st);
811 static bool_t enter_state_sentmsg2(struct site *st)
813 state_assert(st,st->state==SITE_RUN || st->state==SITE_RESOLVE ||
814 st->state==SITE_SENTMSG1 || st->state==SITE_WAIT);
815 slog(st,LOG_STATE,"entering state SENTMSG2");
816 if (generate_msg2(st) && send_msg(st)) {
817 st->state=SITE_SENTMSG2;
820 slog(st,LOG_ERROR,"error entering state SENTMSG2");
821 st->buffer.free=False;
822 enter_state_wait(st);
826 static bool_t enter_state_sentmsg3(struct site *st)
828 state_assert(st,st->state==SITE_SENTMSG1);
829 slog(st,LOG_STATE,"entering state SENTMSG3");
830 BUF_FREE(&st->buffer); /* Free message 1 */
831 if (generate_msg3(st) && send_msg(st)) {
832 st->state=SITE_SENTMSG3;
835 slog(st,LOG_ERROR,"error entering state SENTMSG3");
836 st->buffer.free=False;
837 enter_state_wait(st);
841 static bool_t enter_state_sentmsg4(struct site *st)
843 state_assert(st,st->state==SITE_SENTMSG2);
844 slog(st,LOG_STATE,"entering state SENTMSG4");
845 BUF_FREE(&st->buffer); /* Free message 2 */
846 if (generate_msg4(st) && send_msg(st)) {
847 st->state=SITE_SENTMSG4;
850 slog(st,LOG_ERROR,"error entering state SENTMSG4");
851 st->buffer.free=False;
852 enter_state_wait(st);
856 static bool_t enter_state_sentmsg5(struct site *st)
858 state_assert(st,st->state==SITE_SENTMSG3);
859 slog(st,LOG_STATE,"entering state SENTMSG5");
860 BUF_FREE(&st->buffer); /* Free message 3 */
862 if (generate_msg5(st) && send_msg(st)) {
863 st->state=SITE_SENTMSG5;
866 slog(st,LOG_ERROR,"error entering state SENTMSG5");
867 st->buffer.free=False;
868 enter_state_wait(st);
873 static bool_t send_msg6(struct site *st)
875 state_assert(st,st->state==SITE_SENTMSG4);
876 slog(st,LOG_STATE,"entering state RUN after sending msg6");
877 BUF_FREE(&st->buffer); /* Free message 4 */
878 if (generate_msg6(st) && send_msg(st)) {
879 BUF_FREE(&st->buffer); /* Never reused */
880 st->timeout=0; /* Never retransmit */
881 activate_new_key(st);
884 slog(st,LOG_ERROR,"error entering state RUN after sending msg6");
885 st->buffer.free=False;
886 enter_state_wait(st);
890 /* We go into this state if our peer becomes uncommunicative. Similar to
891 the "stop" state, we forget all session keys for a while, before
892 re-entering the "run" state. */
893 static void enter_state_wait(struct site *st)
895 slog(st,LOG_STATE,"entering state WAIT");
896 st->timeout=st->now+st->wait_timeout;
898 st->peer_valid=False;
899 set_link_quality(st);
900 BUF_FREE(&st->buffer); /* will have had an outgoing packet in it */
901 /* XXX Erase keys etc. */
904 static int site_beforepoll(void *sst, struct pollfd *fds, int *nfds_io,
905 int *timeout_io, const struct timeval *tv_now,
910 *nfds_io=0; /* We don't use any file descriptors */
913 /* Work out when our next timeout is. The earlier of 'timeout' or
914 'current_key_timeout'. A stored value of '0' indicates no timeout
916 if (st->timeout && st->timeout-*now < *timeout_io) {
917 *timeout_io=st->timeout-*now;
920 if (st->current_key_timeout && st->current_key_timeout-*now < *timeout_io)
921 *timeout_io=st->current_key_timeout-*now;
923 return 0; /* success */
926 /* NB site_afterpoll will be called before site_beforepoll is ever called */
927 static void site_afterpoll(void *sst, struct pollfd *fds, int nfds,
928 const struct timeval *tv_now, uint64_t *now)
933 if (st->timeout && *now>st->timeout) {
936 if (st->state>=SITE_SENTMSG1 && st->state<=SITE_SENTMSG5)
938 else if (st->state==SITE_WAIT) {
941 slog(st,LOG_ERROR,"site_afterpoll: unexpected timeout, state=%d",
945 if (st->current_key_timeout && *now>st->current_key_timeout) {
946 slog(st,LOG_TIMEOUT_KEY,"maximum key life exceeded; session closed");
947 st->current_valid=False;
948 st->current_transform->delkey(st->current_transform->st);
949 st->current_key_timeout=0;
950 set_link_quality(st);
954 /* This function is called by the netlink device to deliver packets
955 intended for the remote network. The packet is in "raw" wire
956 format, but is guaranteed to be word-aligned. */
957 static void site_outgoing(void *sst, void *cid, struct buffer_if *buf)
960 string_t transform_err;
962 if (st->state==SITE_STOP) {
967 /* In all other states we consider delivering the packet if we have
968 a valid key and a valid address to send it to. */
969 if (st->current_valid && st->peer_valid) {
970 /* Transform it and send it */
972 buf_prepend_uint32(buf,LABEL_MSG9);
973 st->current_transform->forwards(st->current_transform->st,
974 buf, &transform_err);
975 buf_prepend_uint32(buf,LABEL_MSG0);
976 buf_prepend_uint32(buf,(uint32_t)st);
977 buf_prepend_uint32(buf,st->remote_session_id);
978 st->comm->sendmsg(st->comm->st,buf,&st->peer);
984 slog(st,LOG_DROP,"discarding outgoing packet of size %d",buf->size);
986 initiate_key_setup(st);
989 /* This function is called by the communication device to deliver
990 packets from our peers. */
991 static bool_t site_incoming(void *sst, struct buffer_if *buf,
992 struct sockaddr_in *source)
995 uint32_t dest=ntohl(*(uint32_t *)buf->start);
998 if (buf->size<(st->setupsiglen+8+NONCELEN)) return False;
999 /* It could be for any site - it should have LABEL_MSG1 and
1000 might have our name and our peer's name in it */
1001 if (memcmp(buf->start+8,st->setupsig,st->setupsiglen)==0) {
1002 dump_packet(st,buf,source,True);
1003 /* It's addressed to us. Decide what to do about it. */
1004 if (st->state==SITE_RUN || st->state==SITE_RESOLVE ||
1005 st->state==SITE_WAIT) {
1006 /* We should definitely process it */
1007 if (process_msg1(st,buf,source)) {
1008 slog(st,LOG_SETUP_INIT,"key setup initiated by peer");
1009 enter_state_sentmsg2(st);
1011 slog(st,LOG_ERROR,"failed to process incoming msg1");
1016 if (st->state==SITE_SENTMSG1) {
1017 /* We've just sent a message 1! They may have crossed on
1018 the wire. If we have priority then we ignore the
1019 incoming one, otherwise we process it as usual. */
1020 if (st->setup_priority) {
1022 slog(st,LOG_DUMP,"crossed msg1s; we are higher "
1023 "priority => ignore incoming msg1");
1026 slog(st,LOG_DUMP,"crossed msg1s; we are lower "
1027 "priority => use incoming msg1");
1028 if (process_msg1(st,buf,source)) {
1029 BUF_FREE(&st->buffer); /* Free our old message 1 */
1030 enter_state_sentmsg2(st);
1032 slog(st,LOG_ERROR,"failed to process an incoming "
1033 "crossed msg1 (we have low priority)");
1039 /* The message 1 was received at an unexpected stage of the
1040 key setup. XXX POLICY - what do we do? */
1041 slog(st,LOG_UNEXPECTED,"unexpected incoming message 1");
1045 return False; /* Not for us. */
1047 if (dest==(uint32_t)st) {
1048 uint32_t msgtype=ntohl(*(uint32_t *)(buf->start+8));
1049 /* Explicitly addressed to us */
1050 if (msgtype!=LABEL_MSG0) dump_packet(st,buf,source,True);
1053 process_msg0(st,buf,source);
1056 /* Setup packet: should not have been explicitly addressed
1058 slog(st,LOG_SEC,"incoming explicitly addressed msg1");
1061 /* Setup packet: expected only in state SENTMSG1 */
1062 if (st->state!=SITE_SENTMSG1) {
1063 slog(st,LOG_UNEXPECTED,"unexpected MSG2");
1064 } else if (process_msg2(st,buf,source))
1065 enter_state_sentmsg3(st);
1067 slog(st,LOG_SEC,"invalid MSG2");
1071 /* Setup packet: expected only in state SENTMSG2 */
1072 if (st->state!=SITE_SENTMSG2) {
1073 slog(st,LOG_UNEXPECTED,"unexpected MSG3");
1074 } else if (process_msg3(st,buf,source))
1075 enter_state_sentmsg4(st);
1077 slog(st,LOG_SEC,"invalid MSG3");
1081 /* Setup packet: expected only in state SENTMSG3 */
1082 if (st->state!=SITE_SENTMSG3) {
1083 slog(st,LOG_UNEXPECTED,"unexpected MSG4");
1084 } else if (process_msg4(st,buf,source))
1085 enter_state_sentmsg5(st);
1087 slog(st,LOG_SEC,"invalid MSG4");
1091 /* Setup packet: expected only in state SENTMSG4 */
1092 /* (may turn up in state RUN if our return MSG6 was lost
1093 and the new key has already been activated. In that
1094 case we should treat it as an ordinary PING packet. We
1095 can't pass it to process_msg5() because the
1096 new_transform will now be null. XXX) */
1097 if (st->state!=SITE_SENTMSG4) {
1098 slog(st,LOG_UNEXPECTED,"unexpected MSG5");
1099 } else if (process_msg5(st,buf,source)) {
1102 slog(st,LOG_SEC,"invalid MSG5");
1106 /* Setup packet: expected only in state SENTMSG5 */
1107 if (st->state!=SITE_SENTMSG5) {
1108 slog(st,LOG_UNEXPECTED,"unexpected MSG6");
1109 } else if (process_msg6(st,buf,source)) {
1110 BUF_FREE(&st->buffer); /* Free message 5 */
1111 activate_new_key(st);
1113 slog(st,LOG_SEC,"invalid MSG6");
1117 /* NAK packet: enter state where we ping and check for response */
1118 slog(st,LOG_ERROR,"received a NAK");
1121 slog(st,LOG_SEC,"received message of unknown type 0x%08x",
1132 static void site_control(void *vst, bool_t run)
1134 struct site *st=vst;
1135 if (run) enter_state_run(st);
1136 else enter_state_stop(st);
1139 static list_t *site_apply(closure_t *self, struct cloc loc, dict_t *context,
1145 uint32_t netlink_options;
1147 st=safe_malloc(sizeof(*st),"site_apply");
1149 st->cl.description="site";
1150 st->cl.type=CL_SITE;
1152 st->cl.interface=&st->ops;
1154 st->ops.control=site_control;
1155 st->ops.status=site_status;
1157 /* First parameter must be a dict */
1158 item=list_elem(args,0);
1159 if (!item || item->type!=t_dict)
1160 cfgfatal(loc,"site","parameter must be a dictionary\n");
1162 dict=item->data.dict;
1163 st->localname=dict_read_string(dict, "local-name", True, "site", loc);
1164 st->remotename=dict_read_string(dict, "name", True, "site", loc);
1165 /* Sanity check (which also allows the 'sites' file to include
1166 site() closures for all sites including our own): refuse to
1167 talk to ourselves */
1168 if (strcmp(st->localname,st->remotename)==0) {
1169 Message(M_DEBUG,"site %s: local-name==name -> ignoring this site\n",
1174 st->netlink=find_cl_if(dict,"netlink",CL_NETLINK,True,"site",loc);
1175 st->comm=find_cl_if(dict,"comm",CL_COMM,True,"site",loc);
1176 st->resolver=find_cl_if(dict,"resolver",CL_RESOLVER,True,"site",loc);
1177 st->log=find_cl_if(dict,"log",CL_LOG,True,"site",loc);
1178 st->random=find_cl_if(dict,"random",CL_RANDOMSRC,True,"site",loc);
1180 st->privkey=find_cl_if(dict,"local-key",CL_RSAPRIVKEY,True,"site",loc);
1181 st->address=dict_read_string(dict, "address", False, "site", loc);
1183 st->remoteport=dict_read_number(dict,"port",True,"site",loc,0);
1184 else st->remoteport=0;
1185 dict_read_subnet_list(dict, "networks", True, "site", loc,
1187 st->pubkey=find_cl_if(dict,"key",CL_RSAPUBKEY,True,"site",loc);
1190 find_cl_if(dict,"transform",CL_TRANSFORM,True,"site",loc);
1192 st->dh=find_cl_if(dict,"dh",CL_DH,True,"site",loc);
1193 st->hash=find_cl_if(dict,"hash",CL_HASH,True,"site",loc);
1195 st->key_lifetime=dict_read_number(
1196 dict,"key-lifetime",False,"site",loc,DEFAULT_KEY_LIFETIME);
1197 if (st->key_lifetime < DEFAULT_KEY_RENEGOTIATE_GAP)
1198 st->key_renegotiate_time=st->key_lifetime/2;
1200 st->key_renegotiate_time=st->key_lifetime-DEFAULT_KEY_RENEGOTIATE_GAP;
1201 st->setup_retries=dict_read_number(
1202 dict,"setup-retries",False,"site",loc,DEFAULT_SETUP_RETRIES);
1203 st->setup_timeout=dict_read_number(
1204 dict,"setup-timeout",False,"site",loc,DEFAULT_SETUP_TIMEOUT);
1205 st->wait_timeout=dict_read_number(
1206 dict,"wait-time",False,"site",loc,DEFAULT_WAIT_TIME);
1207 st->key_renegotiate_time=dict_read_number(
1208 dict,"renegotiate-time",False,"site",loc,st->key_lifetime);
1209 if (st->key_renegotiate_time > st->key_lifetime) {
1210 cfgfatal(loc,"site",
1211 "renegotiate-time must be less than key-lifetime\n");
1213 /* XXX keepalive will eventually default to True */
1214 st->keepalive=dict_read_bool(dict,"keepalive",False,"site",loc,False);
1216 st->log_events=string_list_to_word(dict_lookup(dict,"log-events"),
1217 log_event_table,"site");
1219 netlink_options=string_list_to_word(dict_lookup(dict,"netlink-options"),
1220 netlink_option_table,"site");
1222 st->tunname=safe_malloc(strlen(st->localname)+strlen(st->remotename)+5,
1224 sprintf(st->tunname,"%s<->%s",st->localname,st->remotename);
1226 /* The information we expect to see in incoming messages of type 1 */
1227 st->setupsiglen=strlen(st->remotename)+strlen(st->localname)+8;
1228 st->setupsig=safe_malloc(st->setupsiglen,"site_apply");
1229 put_uint32(st->setupsig+0,LABEL_MSG1);
1230 put_uint16(st->setupsig+4,strlen(st->remotename));
1231 memcpy(&st->setupsig[6],st->remotename,strlen(st->remotename));
1232 put_uint16(st->setupsig+(6+strlen(st->remotename)),strlen(st->localname));
1233 memcpy(&st->setupsig[8+strlen(st->remotename)],st->localname,
1234 strlen(st->localname));
1235 st->setup_priority=(strcmp(st->localname,st->remotename)>0);
1237 buffer_new(&st->buffer,SETUP_BUFFER_LEN);
1239 /* We are interested in poll(), but only for timeouts. We don't have
1240 any fds of our own. */
1241 register_for_poll(st, site_beforepoll, site_afterpoll, 0, "site");
1244 st->current_valid=False;
1245 st->current_key_timeout=0;
1246 st->peer_valid=False;
1247 /* XXX mlock these */
1248 st->dhsecret=safe_malloc(st->dh->len,"site:dhsecret");
1249 st->sharedsecret=safe_malloc(st->transform->keylen,"site:sharedsecret");
1251 /* We need to register the remote networks with the netlink device */
1252 st->netlink_cid=st->netlink->regnets(st->netlink->st, &st->remotenets,
1254 st->transform->max_start_pad+(4*4),
1255 st->transform->max_end_pad,
1256 netlink_options, st->tunname);
1257 if (!st->netlink_cid) {
1258 Message(M_WARNING,"%s: netlink device did not let us register "
1259 "our remote networks. This site will not start.\n",
1261 return NULL; /* XXX should free site first */
1264 st->comm->request_notify(st->comm->st, st, site_incoming);
1266 st->current_transform=st->transform->create(st->transform->st);
1267 st->new_transform=st->transform->create(st->transform->st);
1269 enter_state_stop(st);
1271 return new_closure(&st->cl);
1274 init_module site_module;
1275 void site_module(dict_t *dict)
1277 add_closure(dict,"site",site_apply);