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