updated copyright statement
[strongswan.git] / src / pluto / state.c
1 /* routines for state objects
2 * Copyright (C) 1997 Angelos D. Keromytis.
3 * Copyright (C) 1998-2001 D. Hugh Redelmeier.
4 * Copyright (C) 2009 Andreas Steffen - Hochschule fuer Technik Rapperswil
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; either version 2 of the License, or (at your
9 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * for more details.
15 */
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <unistd.h>
21 #include <sys/types.h>
22 #include <sys/socket.h>
23 #include <netinet/in.h>
24 #include <arpa/inet.h>
25 #include <fcntl.h>
26 #include <sys/queue.h>
27
28 #include <freeswan.h>
29
30 #include <library.h>
31 #include <crypto/rngs/rng.h>
32
33 #include "constants.h"
34 #include "defs.h"
35 #include "connections.h"
36 #include "state.h"
37 #include "kernel.h"
38 #include "log.h"
39 #include "packet.h" /* so we can calculate sizeof(struct isakmp_hdr) */
40 #include "keys.h" /* for free_public_key */
41 #include "timer.h"
42 #include "whack.h"
43 #include "demux.h" /* needs packet.h */
44 #include "ipsec_doi.h" /* needs demux.h and state.h */
45 #include "crypto.h"
46
47 /*
48 * Global variables: had to go somewhere, might as well be this file.
49 */
50
51 u_int16_t pluto_port = IKE_UDP_PORT; /* Pluto's port */
52
53 /*
54 * This file has the functions that handle the
55 * state hash table and the Message ID list.
56 */
57
58 /* Message-IDs
59 *
60 * A Message ID is contained in each IKE message header.
61 * For Phase 1 exchanges (Main and Aggressive), it will be zero.
62 * For other exchanges, which must be under the protection of an
63 * ISAKMP SA, the Message ID must be unique within that ISAKMP SA.
64 * Effectively, this labels the message as belonging to a particular
65 * exchange.
66 * BTW, we feel this uniqueness allows rekeying to be somewhat simpler
67 * than specified by draft-jenkins-ipsec-rekeying-06.txt.
68 *
69 * A MessageID is a 32 bit unsigned number. We represent the value
70 * internally in network order -- they are just blobs to us.
71 * They are unsigned numbers to make hashing and comparing easy.
72 *
73 * The following mechanism is used to allocate message IDs. This
74 * requires that we keep track of which numbers have already been used
75 * so that we don't allocate one in use.
76 */
77
78 struct msgid_list
79 {
80 msgid_t msgid; /* network order */
81 struct msgid_list *next;
82 };
83
84 bool reserve_msgid(struct state *isakmp_sa, msgid_t msgid)
85 {
86 struct msgid_list *p;
87
88 passert(msgid != MAINMODE_MSGID);
89 passert(IS_ISAKMP_ENCRYPTED(isakmp_sa->st_state));
90
91 for (p = isakmp_sa->st_used_msgids; p != NULL; p = p->next)
92 if (p->msgid == msgid)
93 return FALSE;
94
95 p = malloc_thing(struct msgid_list);
96 p->msgid = msgid;
97 p->next = isakmp_sa->st_used_msgids;
98 isakmp_sa->st_used_msgids = p;
99 return TRUE;
100 }
101
102 msgid_t generate_msgid(struct state *isakmp_sa)
103 {
104 int timeout = 100; /* only try so hard for unique msgid */
105 msgid_t msgid;
106 rng_t *rng;
107
108 passert(IS_ISAKMP_ENCRYPTED(isakmp_sa->st_state));
109 rng = lib->crypto->create_rng(lib->crypto, RNG_WEAK);
110
111 for (;;)
112 {
113 rng->get_bytes(rng, sizeof(msgid), (void *) &msgid);
114 if (msgid != 0 && reserve_msgid(isakmp_sa, msgid))
115 {
116 break;
117 }
118 if (--timeout == 0)
119 {
120 plog("gave up looking for unique msgid; using 0x%08lx"
121 , (unsigned long) msgid);
122 break;
123 }
124 }
125 rng->destroy(rng);
126 return msgid;
127 }
128
129
130 /* state table functions */
131
132 #define STATE_TABLE_SIZE 32
133
134 static struct state *statetable[STATE_TABLE_SIZE];
135
136 static struct state **state_hash(const u_char *icookie, const u_char *rcookie,
137 const ip_address *peer)
138 {
139 u_int i = 0, j;
140 const unsigned char *byte_ptr;
141 size_t length = addrbytesptr(peer, &byte_ptr);
142
143 DBG(DBG_RAW | DBG_CONTROL,
144 DBG_dump("ICOOKIE:", icookie, COOKIE_SIZE);
145 DBG_dump("RCOOKIE:", rcookie, COOKIE_SIZE);
146 DBG_dump("peer:", byte_ptr, length));
147
148 /* XXX the following hash is pretty pathetic */
149
150 for (j = 0; j < COOKIE_SIZE; j++)
151 i = i * 407 + icookie[j] + rcookie[j];
152
153 for (j = 0; j < length; j++)
154 i = i * 613 + byte_ptr[j];
155
156 i = i % STATE_TABLE_SIZE;
157
158 DBG(DBG_CONTROL, DBG_log("state hash entry %d", i));
159
160 return &statetable[i];
161 }
162
163 /* Get a state object.
164 * Caller must schedule an event for this object so that it doesn't leak.
165 * Caller must insert_state().
166 */
167 struct state *new_state(void)
168 {
169 static const struct state blank_state; /* initialized all to zero & NULL */
170 static so_serial_t next_so = SOS_FIRST;
171 struct state *st;
172
173 st = clone_thing(blank_state);
174 st->st_serialno = next_so++;
175 passert(next_so > SOS_FIRST); /* overflow can't happen! */
176 st->st_whack_sock = NULL_FD;
177 DBG(DBG_CONTROL, DBG_log("creating state object #%lu at %p",
178 st->st_serialno, (void *) st));
179 return st;
180 }
181
182 /*
183 * Initialize the state table (and mask*).
184 */
185 void init_states(void)
186 {
187 int i;
188
189 for (i = 0; i < STATE_TABLE_SIZE; i++)
190 statetable[i] = (struct state *) NULL;
191 }
192
193 /* Find the state object with this serial number.
194 * This allows state object references that don't turn into dangerous
195 * dangling pointers: reference a state by its serial number.
196 * Returns NULL if there is no such state.
197 * If this turns out to be a significant CPU hog, it could be
198 * improved to use a hash table rather than sequential seartch.
199 */
200 struct state *state_with_serialno(so_serial_t sn)
201 {
202 if (sn >= SOS_FIRST)
203 {
204 struct state *st;
205 int i;
206
207 for (i = 0; i < STATE_TABLE_SIZE; i++)
208 for (st = statetable[i]; st != NULL; st = st->st_hashchain_next)
209 if (st->st_serialno == sn)
210 return st;
211 }
212 return NULL;
213 }
214
215 /* Insert a state object in the hash table. The object is inserted
216 * at the begining of list.
217 * Needs cookies, connection, and msgid.
218 */
219 void insert_state(struct state *st)
220 {
221 struct state **p = state_hash(st->st_icookie, st->st_rcookie
222 , &st->st_connection->spd.that.host_addr);
223
224 passert(st->st_hashchain_prev == NULL && st->st_hashchain_next == NULL);
225
226 if (*p != NULL)
227 {
228 passert((*p)->st_hashchain_prev == NULL);
229 (*p)->st_hashchain_prev = st;
230 }
231 st->st_hashchain_next = *p;
232 *p = st;
233
234 /* Ensure that somebody is in charge of killing this state:
235 * if no event is scheduled for it, schedule one to discard the state.
236 * If nothing goes wrong, this event will be replaced by
237 * a more appropriate one.
238 */
239 if (st->st_event == NULL)
240 event_schedule(EVENT_SO_DISCARD, 0, st);
241 }
242
243 /* unlink a state object from the hash table, but don't free it
244 */
245 void unhash_state(struct state *st)
246 {
247 /* unlink from forward chain */
248 struct state **p = st->st_hashchain_prev == NULL
249 ? state_hash(st->st_icookie, st->st_rcookie
250 , &st->st_connection->spd.that.host_addr)
251 : &st->st_hashchain_prev->st_hashchain_next;
252
253 /* unlink from forward chain */
254 passert(*p == st);
255 *p = st->st_hashchain_next;
256
257 /* unlink from backward chain */
258 if (st->st_hashchain_next != NULL)
259 {
260 passert(st->st_hashchain_next->st_hashchain_prev == st);
261 st->st_hashchain_next->st_hashchain_prev = st->st_hashchain_prev;
262 }
263
264 st->st_hashchain_next = st->st_hashchain_prev = NULL;
265 }
266
267 /* Free the Whack socket file descriptor.
268 * This has the side effect of telling Whack that we're done.
269 */
270 void release_whack(struct state *st)
271 {
272 close_any(st->st_whack_sock);
273 }
274
275 /**
276 * Delete a state object
277 */
278 void delete_state(struct state *st)
279 {
280 struct connection *const c = st->st_connection;
281 struct state *old_cur_state = cur_state == st? NULL : cur_state;
282
283 set_cur_state(st);
284
285 /* If DPD is enabled on this state object, clear any pending events */
286 if(st->st_dpd_event != NULL)
287 delete_dpd_event(st);
288
289 /* if there is a suspended state transition, disconnect us */
290 if (st->st_suspended_md != NULL)
291 {
292 passert(st->st_suspended_md->st == st);
293 st->st_suspended_md->st = NULL;
294 }
295
296 /* tell the other side of any IPSEC SAs that are going down */
297 if (IS_IPSEC_SA_ESTABLISHED(st->st_state)
298 || IS_ISAKMP_SA_ESTABLISHED(st->st_state))
299 send_delete(st);
300
301 delete_event(st); /* delete any pending timer event */
302
303 /* Ditch anything pending on ISAKMP SA being established.
304 * Note: this must be done before the unhash_state to prevent
305 * flush_pending_by_state inadvertently and prematurely
306 * deleting our connection.
307 */
308 flush_pending_by_state(st);
309
310 /* effectively, this deletes any ISAKMP SA that this state represents */
311 unhash_state(st);
312
313 /* tell kernel to delete any IPSEC SA
314 * ??? we ought to tell peer to delete IPSEC SAs
315 */
316 if (IS_IPSEC_SA_ESTABLISHED(st->st_state))
317 delete_ipsec_sa(st, FALSE);
318 else if (IS_ONLY_INBOUND_IPSEC_SA_ESTABLISHED(st->st_state))
319 delete_ipsec_sa(st, TRUE);
320
321 if (c->newest_ipsec_sa == st->st_serialno)
322 c->newest_ipsec_sa = SOS_NOBODY;
323
324 if (c->newest_isakmp_sa == st->st_serialno)
325 c->newest_isakmp_sa = SOS_NOBODY;
326
327 st->st_connection = NULL; /* we might be about to free it */
328 cur_state = old_cur_state; /* without st_connection, st isn't complete */
329 connection_discard(c);
330
331 release_whack(st);
332
333 /* from here on we are just freeing RAM */
334
335 {
336 struct msgid_list *p = st->st_used_msgids;
337
338 while (p != NULL)
339 {
340 struct msgid_list *q = p;
341 p = p->next;
342 free(q);
343 }
344 }
345
346 unreference_key(&st->st_peer_pubkey);
347
348 DESTROY_IF(st->st_dh);
349
350 free(st->st_tpacket.ptr);
351 free(st->st_rpacket.ptr);
352 free(st->st_p1isa.ptr);
353 free(st->st_gi.ptr);
354 free(st->st_gr.ptr);
355 free(st->st_shared.ptr);
356 free(st->st_ni.ptr);
357 free(st->st_nr.ptr);
358 free(st->st_skeyid.ptr);
359 free(st->st_skeyid_d.ptr);
360 free(st->st_skeyid_a.ptr);
361 free(st->st_skeyid_e.ptr);
362 free(st->st_enc_key.ptr);
363 free(st->st_ah.our_keymat);
364 free(st->st_ah.peer_keymat);
365 free(st->st_esp.our_keymat);
366 free(st->st_esp.peer_keymat);
367
368 free(st);
369 }
370
371 /**
372 * Is a connection in use by some state?
373 */
374 bool states_use_connection(struct connection *c)
375 {
376 /* are there any states still using it? */
377 struct state *st = NULL;
378 int i;
379
380 for (i = 0; st == NULL && i < STATE_TABLE_SIZE; i++)
381 for (st = statetable[i]; st != NULL; st = st->st_hashchain_next)
382 if (st->st_connection == c)
383 return TRUE;
384
385 return FALSE;
386 }
387
388 /**
389 * Delete all states that were created for a given connection.
390 * if relations == TRUE, then also delete states that share
391 * the same phase 1 SA.
392 */
393 void delete_states_by_connection(struct connection *c, bool relations)
394 {
395 int pass;
396 /* this kludge avoids an n^2 algorithm */
397 enum connection_kind ck = c->kind;
398 struct spd_route *sr;
399
400 /* save this connection's isakmp SA, since it will get set to later SOS_NOBODY */
401 so_serial_t parent_sa = c->newest_isakmp_sa;
402
403 if (ck == CK_INSTANCE)
404 c->kind = CK_GOING_AWAY;
405
406 /* We take two passes so that we delete any ISAKMP SAs last.
407 * This allows Delete Notifications to be sent.
408 * ?? We could probably double the performance by caching any
409 * ISAKMP SA states found in the first pass, avoiding a second.
410 */
411 for (pass = 0; pass != 2; pass++)
412 {
413 int i;
414
415 /* For each hash chain... */
416 for (i = 0; i < STATE_TABLE_SIZE; i++)
417 {
418 struct state *st;
419
420 /* For each state in the hash chain... */
421 for (st = statetable[i]; st != NULL; )
422 {
423 struct state *this = st;
424
425 st = st->st_hashchain_next; /* before this is deleted */
426
427
428 if ((this->st_connection == c
429 || (relations && parent_sa != SOS_NOBODY
430 && this->st_clonedfrom == parent_sa))
431 && (pass == 1 || !IS_ISAKMP_SA_ESTABLISHED(this->st_state)))
432 {
433 struct state *old_cur_state
434 = cur_state == this? NULL : cur_state;
435 #ifdef DEBUG
436 lset_t old_cur_debugging = cur_debugging;
437 #endif
438
439 set_cur_state(this);
440 plog("deleting state (%s)"
441 , enum_show(&state_names, this->st_state));
442 delete_state(this);
443 cur_state = old_cur_state;
444 #ifdef DEBUG
445 cur_debugging = old_cur_debugging;
446 #endif
447 }
448 }
449 }
450 }
451
452 sr = &c->spd;
453 while (sr != NULL)
454 {
455 passert(sr->eroute_owner == SOS_NOBODY);
456 passert(sr->routing != RT_ROUTED_TUNNEL);
457 sr = sr->next;
458 }
459 c->kind = ck;
460 }
461
462 /**
463 * Walk through the state table, and delete each state whose phase 1 (IKE)
464 * peer is among those given.
465 */
466 void delete_states_by_peer(ip_address *peer)
467 {
468 char peerstr[ADDRTOT_BUF];
469 int i;
470
471 addrtot(peer, 0, peerstr, sizeof(peerstr));
472
473 /* For each hash chain... */
474 for (i = 0; i < STATE_TABLE_SIZE; i++)
475 {
476 struct state *st;
477
478 /* For each state in the hash chain... */
479 for (st = statetable[i]; st != NULL; )
480 {
481 struct state *this = st;
482 struct spd_route *sr;
483 struct connection *c = this->st_connection;
484
485 st = st->st_hashchain_next; /* before this is deleted */
486
487 /* ??? Is it not the case that the peer is the same for all spds? */
488 for (sr = &c->spd; sr != NULL; sr = sr->next)
489 {
490 if (sameaddr(&sr->that.host_addr, peer))
491 {
492 plog("peer %s for connection %s deleting - claimed to have crashed"
493 , peerstr
494 , c->name);
495 delete_states_by_connection(c, TRUE);
496 if (c->kind == CK_INSTANCE)
497 delete_connection(c, TRUE);
498 break; /* can only delete it once */
499 }
500 }
501 }
502 }
503 }
504
505 /* Duplicate a Phase 1 state object, to create a Phase 2 object.
506 * Caller must schedule an event for this object so that it doesn't leak.
507 * Caller must insert_state().
508 */
509 struct state *duplicate_state(struct state *st)
510 {
511 struct state *nst;
512
513 DBG(DBG_CONTROL, DBG_log("duplicating state object #%lu",
514 st->st_serialno));
515
516 /* record use of the Phase 1 state */
517 st->st_outbound_count++;
518 st->st_outbound_time = now();
519
520 nst = new_state();
521
522 memcpy(nst->st_icookie, st->st_icookie, COOKIE_SIZE);
523 memcpy(nst->st_rcookie, st->st_rcookie, COOKIE_SIZE);
524
525 nst->st_connection = st->st_connection;
526 nst->st_doi = st->st_doi;
527 nst->st_situation = st->st_situation;
528 nst->st_clonedfrom = st->st_serialno;
529 nst->st_oakley = st->st_oakley;
530 nst->st_modecfg = st->st_modecfg;
531 nst->st_skeyid_d = chunk_clone(st->st_skeyid_d);
532 nst->st_skeyid_a = chunk_clone(st->st_skeyid_a);
533 nst->st_skeyid_e = chunk_clone(st->st_skeyid_e);
534 nst->st_enc_key = chunk_clone(st->st_enc_key);
535
536 return nst;
537 }
538
539 #if 1
540 void for_each_state(void *(f)(struct state *, void *data), void *data)
541 {
542 struct state *st, *ocs = cur_state;
543 int i;
544 for (i=0; i<STATE_TABLE_SIZE; i++) {
545 for (st = statetable[i]; st != NULL; st = st->st_hashchain_next) {
546 set_cur_state(st);
547 f(st, data);
548 }
549 }
550 cur_state = ocs;
551 }
552 #endif
553
554 /**
555 * Find a state object.
556 */
557 struct state *find_state(const u_char *icookie, const u_char *rcookie,
558 const ip_address *peer, msgid_t msgid)
559 {
560 struct state *st = *state_hash(icookie, rcookie, peer);
561
562 while (st != (struct state *) NULL)
563 {
564 if (sameaddr(peer, &st->st_connection->spd.that.host_addr)
565 && memeq(icookie, st->st_icookie, COOKIE_SIZE)
566 && memeq(rcookie, st->st_rcookie, COOKIE_SIZE)
567 && msgid == st->st_msgid)
568 {
569 break;
570 }
571 else
572 {
573 st = st->st_hashchain_next;
574 }
575 }
576 DBG(DBG_CONTROL,
577 if (st == NULL)
578 DBG_log("state object not found");
579 else
580 DBG_log("state object #%lu found, in %s"
581 , st->st_serialno
582 , enum_show(&state_names, st->st_state)));
583
584 return st;
585 }
586
587 /**
588 * Find the state that sent a packet
589 * ??? this could be expensive -- it should be rate-limited to avoid DoS
590 */
591 struct state *find_sender(size_t packet_len, u_char *packet)
592 {
593 int i;
594 struct state *st;
595
596 if (packet_len >= sizeof(struct isakmp_hdr))
597 {
598 for (i = 0; i < STATE_TABLE_SIZE; i++)
599 {
600 for (st = statetable[i]; st != NULL; st = st->st_hashchain_next)
601 {
602 if (st->st_tpacket.ptr != NULL
603 && st->st_tpacket.len == packet_len
604 && memeq(st->st_tpacket.ptr, packet, packet_len))
605 {
606 return st;
607 }
608 }
609 }
610 }
611 return NULL;
612 }
613
614 struct state *find_phase2_state_to_delete(const struct state *p1st,
615 u_int8_t protoid, ipsec_spi_t spi,
616 bool *bogus)
617 {
618 struct state *st;
619 int i;
620
621 *bogus = FALSE;
622 for (i = 0; i < STATE_TABLE_SIZE; i++)
623 {
624 for (st = statetable[i]; st != NULL; st = st->st_hashchain_next)
625 {
626 if (IS_IPSEC_SA_ESTABLISHED(st->st_state)
627 && p1st->st_connection->host_pair == st->st_connection->host_pair
628 && same_peer_ids(p1st->st_connection, st->st_connection, NULL))
629 {
630 struct ipsec_proto_info *pr = protoid == PROTO_IPSEC_AH
631 ? &st->st_ah : &st->st_esp;
632
633 if (pr->present)
634 {
635 if (pr->attrs.spi == spi)
636 return st;
637 if (pr->our_spi == spi)
638 *bogus = TRUE;
639 }
640 }
641 }
642 }
643 return NULL;
644 }
645
646 /**
647 * Find newest Phase 1 negotiation state object for suitable for connection c
648 */
649 struct state *find_phase1_state(const struct connection *c, lset_t ok_states)
650 {
651 struct state
652 *st,
653 *best = NULL;
654 int i;
655
656 for (i = 0; i < STATE_TABLE_SIZE; i++)
657 for (st = statetable[i]; st != NULL; st = st->st_hashchain_next)
658 if (LHAS(ok_states, st->st_state)
659 && c->host_pair == st->st_connection->host_pair
660 && same_peer_ids(c, st->st_connection, NULL)
661 && (best == NULL || best->st_serialno < st->st_serialno))
662 best = st;
663
664 return best;
665 }
666
667 void state_eroute_usage(ip_subnet *ours, ip_subnet *his, unsigned long count,
668 time_t nw)
669 {
670 struct state *st;
671 int i;
672
673 for (i = 0; i < STATE_TABLE_SIZE; i++)
674 {
675 for (st = statetable[i]; st != NULL; st = st->st_hashchain_next)
676 {
677 struct connection *c = st->st_connection;
678
679 /* XXX spd-enum */
680 if (IS_IPSEC_SA_ESTABLISHED(st->st_state)
681 && c->spd.eroute_owner == st->st_serialno
682 && c->spd.routing == RT_ROUTED_TUNNEL
683 && samesubnet(&c->spd.this.client, ours)
684 && samesubnet(&c->spd.that.client, his))
685 {
686 if (st->st_outbound_count != count)
687 {
688 st->st_outbound_count = count;
689 st->st_outbound_time = nw;
690 }
691 return;
692 }
693 }
694 }
695 DBG(DBG_CONTROL,
696 {
697 char ourst[SUBNETTOT_BUF];
698 char hist[SUBNETTOT_BUF];
699
700 subnettot(ours, 0, ourst, sizeof(ourst));
701 subnettot(his, 0, hist, sizeof(hist));
702 DBG_log("unknown tunnel eroute %s -> %s found in scan"
703 , ourst, hist);
704 });
705 }
706
707 void fmt_state(bool all, struct state *st, time_t n, char *state_buf,
708 size_t state_buf_len, char *state_buf2, size_t state_buf2_len)
709 {
710 /* what the heck is interesting about a state? */
711 const struct connection *c = st->st_connection;
712
713 long delta = st->st_event->ev_time >= n
714 ? (long)(st->st_event->ev_time - n)
715 : -(long)(n - st->st_event->ev_time);
716
717 char inst[CONN_INST_BUF];
718 const char *np1 = c->newest_isakmp_sa == st->st_serialno
719 ? "; newest ISAKMP" : "";
720 const char *np2 = c->newest_ipsec_sa == st->st_serialno
721 ? "; newest IPSEC" : "";
722 /* XXX spd-enum */
723 const char *eo = c->spd.eroute_owner == st->st_serialno
724 ? "; eroute owner" : "";
725 const char *dpd = (all && st->st_dpd && c->dpd_action != DPD_ACTION_NONE)
726 ? "; DPD active" : "";
727
728 passert(st->st_event != 0);
729
730 fmt_conn_instance(c, inst);
731
732 snprintf(state_buf, state_buf_len
733 , "#%lu: \"%s\"%s %s (%s); %N in %lds%s%s%s%s"
734 , st->st_serialno
735 , c->name, inst
736 , enum_name(&state_names, st->st_state)
737 , state_story[st->st_state - STATE_MAIN_R0]
738 , timer_event_names, st->st_event->ev_type
739 , delta
740 , np1, np2, eo, dpd);
741
742 /* print out SPIs if SAs are established */
743 if (state_buf2_len != 0)
744 state_buf2[0] = '\0'; /* default to empty */
745 if (IS_IPSEC_SA_ESTABLISHED(st->st_state))
746 {
747
748 bool tunnel;
749 char buf[SATOT_BUF*6 + 2*20 + 1];
750 const char *p_end = buf + sizeof(buf);
751 char *p = buf;
752
753 # define add_said(adst, aspi, aproto) { \
754 ip_said s; \
755 \
756 initsaid(adst, aspi, aproto, &s); \
757 if (p < p_end - 1) \
758 { \
759 *p++ = ' '; \
760 p += satot(&s, 0, p, p_end - p) - 1; \
761 } \
762 }
763
764 # define add_sa_info(st, inbound) { \
765 u_int bytes; \
766 time_t use_time; \
767 \
768 if (get_sa_info(st, inbound, &bytes, &use_time)) \
769 { \
770 p += snprintf(p, p_end - p, " (%'u bytes", bytes); \
771 if (bytes > 0 && use_time != UNDEFINED_TIME) \
772 p += snprintf(p, p_end - p, ", %ds ago", (int)(now - use_time)); \
773 p += snprintf(p, p_end - p, ")"); \
774 } \
775 }
776
777 *p = '\0';
778 if (st->st_ah.present)
779 {
780 add_said(&c->spd.that.host_addr, st->st_ah.attrs.spi, SA_AH);
781 add_said(&c->spd.this.host_addr, st->st_ah.our_spi, SA_AH);
782 }
783 if (st->st_esp.present)
784 {
785 time_t now = time(NULL);
786
787 add_said(&c->spd.that.host_addr, st->st_esp.attrs.spi, SA_ESP);
788 add_sa_info(st, FALSE);
789 add_said(&c->spd.this.host_addr, st->st_esp.our_spi, SA_ESP);
790 add_sa_info(st, TRUE);
791 }
792 if (st->st_ipcomp.present)
793 {
794 add_said(&c->spd.that.host_addr, st->st_ipcomp.attrs.spi, SA_COMP);
795 add_said(&c->spd.this.host_addr, st->st_ipcomp.our_spi, SA_COMP);
796 }
797 #ifdef KLIPS
798 tunnel = st->st_ah.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL
799 || st->st_esp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL
800 || st->st_ipcomp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL;
801 p += snprintf(p, p_end - p, "; %s", tunnel? "tunnel":"transport");
802 #endif
803
804 snprintf(state_buf2, state_buf2_len
805 , "#%lu: \"%s\"%s%s"
806 , st->st_serialno
807 , c->name, inst
808 , buf);
809
810 # undef add_said
811 # undef add_sa_info
812 }
813 }
814
815 /*
816 * sorting logic is:
817 *
818 * name
819 * type
820 * instance#
821 * isakmp_sa (XXX probably wrong)
822 *
823 */
824 static int state_compare(const void *a, const void *b)
825 {
826 const struct state *sap = *(const struct state *const *)a;
827 struct connection *ca = sap->st_connection;
828 const struct state *sbp = *(const struct state *const *)b;
829 struct connection *cb = sbp->st_connection;
830
831 /* DBG_log("comparing %s to %s", ca->name, cb->name); */
832
833 return connection_compare(ca, cb);
834 }
835
836 void show_states_status(bool all, const char *name)
837 {
838 time_t n = now();
839 int i;
840 char state_buf[LOG_WIDTH];
841 char state_buf2[LOG_WIDTH];
842 int count;
843 struct state **array;
844
845 /* make count of states */
846 count = 0;
847 for (i = 0; i < STATE_TABLE_SIZE; i++)
848 {
849 struct state *st;
850
851 for (st = statetable[i]; st != NULL; st = st->st_hashchain_next)
852 {
853 if (name == NULL || streq(name, st->st_connection->name))
854 count++;
855 }
856 }
857
858 /* build the array */
859 array = malloc(sizeof(struct state *)*count);
860 count = 0;
861 for (i = 0; i < STATE_TABLE_SIZE; i++)
862 {
863 struct state *st;
864
865 for (st = statetable[i]; st != NULL; st = st->st_hashchain_next)
866 {
867 if (name == NULL || streq(name, st->st_connection->name))
868 array[count++]=st;
869 }
870 }
871
872 /* sort it! */
873 qsort(array, count, sizeof(struct state *), state_compare);
874
875 /* now print sorted results */
876 for (i = 0; i < count; i++)
877 {
878 struct state *st;
879
880 st = array[i];
881
882 fmt_state(all, st, n
883 , state_buf, sizeof(state_buf)
884 , state_buf2, sizeof(state_buf2));
885 whack_log(RC_COMMENT, state_buf);
886 if (state_buf2[0] != '\0')
887 whack_log(RC_COMMENT, state_buf2);
888
889 /* show any associated pending Phase 2s */
890 if (IS_PHASE1(st->st_state))
891 show_pending_phase2(st->st_connection->host_pair, st);
892 }
893 if (count > 0)
894 whack_log(RC_COMMENT, BLANK_FORMAT); /* spacer */
895
896 /* free the array */
897 free(array);
898 }
899
900 /* Given that we've used up a range of unused CPI's,
901 * search for a new range of currently unused ones.
902 * Note: this is very expensive when not trivial!
903 * If we can't find one easily, choose 0 (a bad SPI,
904 * no matter what order) indicating failure.
905 */
906 void find_my_cpi_gap(cpi_t *latest_cpi, cpi_t *first_busy_cpi)
907 {
908 int tries = 0;
909 cpi_t base = *latest_cpi;
910 cpi_t closest;
911 int i;
912
913 startover:
914 closest = ~0; /* not close at all */
915 for (i = 0; i < STATE_TABLE_SIZE; i++)
916 {
917 struct state *st;
918
919 for (st = statetable[i]; st != NULL; st = st->st_hashchain_next)
920 {
921 if (st->st_ipcomp.present)
922 {
923 cpi_t c = ntohl(st->st_ipcomp.our_spi) - base;
924
925 if (c < closest)
926 {
927 if (c == 0)
928 {
929 /* oops: next spot is occupied; start over */
930 if (++tries == 20)
931 {
932 /* FAILURE */
933 *latest_cpi = *first_busy_cpi = 0;
934 return;
935 }
936 base++;
937 if (base > IPCOMP_LAST_NEGOTIATED)
938 base = IPCOMP_FIRST_NEGOTIATED;
939 goto startover; /* really a tail call */
940 }
941 closest = c;
942 }
943 }
944 }
945 }
946 *latest_cpi = base; /* base is first in next free range */
947 *first_busy_cpi = closest + base; /* and this is the roof */
948 }
949
950 /* Muck with high-order 16 bits of this SPI in order to make
951 * the corresponding SAID unique.
952 * Its low-order 16 bits hold a well-known IPCOMP CPI.
953 * Oh, and remember that SPIs are stored in network order.
954 * Kludge!!! So I name it with the non-English word "uniquify".
955 * If we can't find one easily, return 0 (a bad SPI,
956 * no matter what order) indicating failure.
957 */
958 ipsec_spi_t uniquify_his_cpi(ipsec_spi_t cpi, struct state *st)
959 {
960 int tries = 0;
961 int i;
962 rng_t *rng = lib->crypto->create_rng(lib->crypto, RNG_WEAK);
963
964 startover:
965
966 /* network order makes first two bytes our target */
967 rng->get_bytes(rng, 2, (u_char *)&cpi);
968
969 /* Make sure that the result is unique.
970 * Hard work. If there is no unique value, we'll loop forever!
971 */
972 for (i = 0; i < STATE_TABLE_SIZE; i++)
973 {
974 struct state *s;
975
976 for (s = statetable[i]; s != NULL; s = s->st_hashchain_next)
977 {
978 if (s->st_ipcomp.present
979 && sameaddr(&s->st_connection->spd.that.host_addr
980 , &st->st_connection->spd.that.host_addr)
981 && cpi == s->st_ipcomp.attrs.spi)
982 {
983 if (++tries == 20)
984 {
985 rng->destroy(rng);
986 return 0; /* FAILURE */
987 }
988 goto startover;
989 }
990 }
991 }
992 rng->destroy(rng);
993 return cpi;
994 }
995
996 /*
997 * Local Variables:
998 * c-basic-offset:4
999 * End:
1000 */