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