fixed a use-after-free bug in dpd_timeout()
[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$
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 c->kind = ck;
468 }
469
470 /* Walk through the state table, and delete each state whose phase 1 (IKE)
471 * peer is among those given.
472 */
473 void
474 delete_states_by_peer(ip_address *peer)
475 {
476 char peerstr[ADDRTOT_BUF];
477 int i;
478
479 addrtot(peer, 0, peerstr, sizeof(peerstr));
480
481 /* For each hash chain... */
482 for (i = 0; i < STATE_TABLE_SIZE; i++)
483 {
484 struct state *st;
485
486 /* For each state in the hash chain... */
487 for (st = statetable[i]; st != NULL; )
488 {
489 struct state *this = st;
490 struct spd_route *sr;
491 struct connection *c = this->st_connection;
492
493 st = st->st_hashchain_next; /* before this is deleted */
494
495 /* ??? Is it not the case that the peer is the same for all spds? */
496 for (sr = &c->spd; sr != NULL; sr = sr->next)
497 {
498 if (sameaddr(&sr->that.host_addr, peer))
499 {
500 plog("peer %s for connection %s deleting - claimed to have crashed"
501 , peerstr
502 , c->name);
503 delete_states_by_connection(c, TRUE);
504 if (c->kind == CK_INSTANCE)
505 delete_connection(c, TRUE);
506 break; /* can only delete it once */
507 }
508 }
509 }
510 }
511 }
512
513 /* Duplicate a Phase 1 state object, to create a Phase 2 object.
514 * Caller must schedule an event for this object so that it doesn't leak.
515 * Caller must insert_state().
516 */
517 struct state *
518 duplicate_state(struct state *st)
519 {
520 struct state *nst;
521
522 DBG(DBG_CONTROL, DBG_log("duplicating state object #%lu",
523 st->st_serialno));
524
525 /* record use of the Phase 1 state */
526 st->st_outbound_count++;
527 st->st_outbound_time = now();
528
529 nst = new_state();
530
531 memcpy(nst->st_icookie, st->st_icookie, COOKIE_SIZE);
532 memcpy(nst->st_rcookie, st->st_rcookie, COOKIE_SIZE);
533
534 nst->st_connection = st->st_connection;
535 nst->st_doi = st->st_doi;
536 nst->st_situation = st->st_situation;
537 nst->st_clonedfrom = st->st_serialno;
538 nst->st_oakley = st->st_oakley;
539 nst->st_modecfg = st->st_modecfg;
540
541 # define clone_chunk(ch, name) \
542 clonetochunk(nst->ch, st->ch.ptr, st->ch.len, name)
543
544 clone_chunk(st_skeyid_d, "st_skeyid_d in duplicate_state");
545 clone_chunk(st_skeyid_a, "st_skeyid_a in duplicate_state");
546 clone_chunk(st_skeyid_e, "st_skeyid_e in duplicate_state");
547 clone_chunk(st_enc_key, "st_enc_key in duplicate_state");
548
549 # undef clone_chunk
550
551 return nst;
552 }
553
554 #if 1
555 void for_each_state(void *(f)(struct state *, void *data), void *data)
556 {
557 struct state *st, *ocs = cur_state;
558 int i;
559 for (i=0; i<STATE_TABLE_SIZE; i++) {
560 for (st = statetable[i]; st != NULL; st = st->st_hashchain_next) {
561 set_cur_state(st);
562 f(st, data);
563 }
564 }
565 cur_state = ocs;
566 }
567 #endif
568
569 /*
570 * Find a state object.
571 */
572 struct state *
573 find_state(const u_char *icookie
574 , const u_char *rcookie
575 , const ip_address *peer
576 , msgid_t /*network order*/ msgid)
577 {
578 struct state *st = *state_hash(icookie, rcookie, peer);
579
580 while (st != (struct state *) NULL)
581 if (sameaddr(peer, &st->st_connection->spd.that.host_addr)
582 && memcmp(icookie, st->st_icookie, COOKIE_SIZE) == 0
583 && memcmp(rcookie, st->st_rcookie, COOKIE_SIZE) == 0
584 && msgid == st->st_msgid)
585 break;
586 else
587 st = st->st_hashchain_next;
588
589 DBG(DBG_CONTROL,
590 if (st == NULL)
591 DBG_log("state object not found");
592 else
593 DBG_log("state object #%lu found, in %s"
594 , st->st_serialno
595 , enum_show(&state_names, st->st_state)));
596
597 return st;
598 }
599
600 /* Find the state that sent a packet
601 * ??? this could be expensive -- it should be rate-limited to avoid DoS
602 */
603 struct state *
604 find_sender(size_t packet_len, u_char *packet)
605 {
606 int i;
607 struct state *st;
608
609 if (packet_len >= sizeof(struct isakmp_hdr))
610 for (i = 0; i < STATE_TABLE_SIZE; i++)
611 for (st = statetable[i]; st != NULL; st = st->st_hashchain_next)
612 if (st->st_tpacket.ptr != NULL
613 && st->st_tpacket.len == packet_len
614 && memcmp(st->st_tpacket.ptr, packet, packet_len) == 0)
615 return st;
616
617 return NULL;
618 }
619
620 struct state *
621 find_phase2_state_to_delete(const struct state *p1st
622 , u_int8_t protoid
623 , ipsec_spi_t spi
624 , bool *bogus)
625 {
626 struct state *st;
627 int i;
628
629 *bogus = FALSE;
630 for (i = 0; i < STATE_TABLE_SIZE; i++)
631 {
632 for (st = statetable[i]; st != NULL; st = st->st_hashchain_next)
633 {
634 if (IS_IPSEC_SA_ESTABLISHED(st->st_state)
635 && p1st->st_connection->host_pair == st->st_connection->host_pair
636 && same_peer_ids(p1st->st_connection, st->st_connection, NULL))
637 {
638 struct ipsec_proto_info *pr = protoid == PROTO_IPSEC_AH
639 ? &st->st_ah : &st->st_esp;
640
641 if (pr->present)
642 {
643 if (pr->attrs.spi == spi)
644 return st;
645 if (pr->our_spi == spi)
646 *bogus = TRUE;
647 }
648 }
649 }
650 }
651 return NULL;
652 }
653
654 /* Find newest Phase 1 negotiation state object for suitable for connection c
655 */
656 struct state *
657 find_phase1_state(const struct connection *c, lset_t ok_states)
658 {
659 struct state
660 *st,
661 *best = NULL;
662 int i;
663
664 for (i = 0; i < STATE_TABLE_SIZE; i++)
665 for (st = statetable[i]; st != NULL; st = st->st_hashchain_next)
666 if (LHAS(ok_states, st->st_state)
667 && c->host_pair == st->st_connection->host_pair
668 && same_peer_ids(c, st->st_connection, NULL)
669 && (best == NULL || best->st_serialno < st->st_serialno))
670 best = st;
671
672 return best;
673 }
674
675 void
676 state_eroute_usage(ip_subnet *ours, ip_subnet *his
677 , unsigned long count, time_t nw)
678 {
679 struct state *st;
680 int i;
681
682 for (i = 0; i < STATE_TABLE_SIZE; i++)
683 {
684 for (st = statetable[i]; st != NULL; st = st->st_hashchain_next)
685 {
686 struct connection *c = st->st_connection;
687
688 /* XXX spd-enum */
689 if (IS_IPSEC_SA_ESTABLISHED(st->st_state)
690 && c->spd.eroute_owner == st->st_serialno
691 && c->spd.routing == RT_ROUTED_TUNNEL
692 && samesubnet(&c->spd.this.client, ours)
693 && samesubnet(&c->spd.that.client, his))
694 {
695 if (st->st_outbound_count != count)
696 {
697 st->st_outbound_count = count;
698 st->st_outbound_time = nw;
699 }
700 return;
701 }
702 }
703 }
704 DBG(DBG_CONTROL,
705 {
706 char ourst[SUBNETTOT_BUF];
707 char hist[SUBNETTOT_BUF];
708
709 subnettot(ours, 0, ourst, sizeof(ourst));
710 subnettot(his, 0, hist, sizeof(hist));
711 DBG_log("unknown tunnel eroute %s -> %s found in scan"
712 , ourst, hist);
713 });
714 }
715
716 void fmt_state(bool all, struct state *st, time_t n
717 , char *state_buf, size_t state_buf_len
718 , char *state_buf2, size_t state_buf2_len)
719 {
720 /* what the heck is interesting about a state? */
721 const struct connection *c = st->st_connection;
722
723 long delta = st->st_event->ev_time >= n
724 ? (long)(st->st_event->ev_time - n)
725 : -(long)(n - st->st_event->ev_time);
726
727 char inst[CONN_INST_BUF];
728 const char *np1 = c->newest_isakmp_sa == st->st_serialno
729 ? "; newest ISAKMP" : "";
730 const char *np2 = c->newest_ipsec_sa == st->st_serialno
731 ? "; newest IPSEC" : "";
732 /* XXX spd-enum */
733 const char *eo = c->spd.eroute_owner == st->st_serialno
734 ? "; eroute owner" : "";
735 const char *dpd = (all && st->st_dpd && c->dpd_action != DPD_ACTION_NONE)
736 ? "; DPD active" : "";
737
738 passert(st->st_event != 0);
739
740 fmt_conn_instance(c, inst);
741
742 snprintf(state_buf, state_buf_len
743 , "#%lu: \"%s\"%s %s (%s); %s in %lds%s%s%s%s"
744 , st->st_serialno
745 , c->name, inst
746 , enum_name(&state_names, st->st_state)
747 , state_story[st->st_state - STATE_MAIN_R0]
748 , enum_name(&timer_event_names, st->st_event->ev_type)
749 , delta
750 , np1, np2, eo, dpd);
751
752 /* print out SPIs if SAs are established */
753 if (state_buf2_len != 0)
754 state_buf2[0] = '\0'; /* default to empty */
755 if (IS_IPSEC_SA_ESTABLISHED(st->st_state))
756 {
757
758 bool tunnel;
759 char buf[SATOT_BUF*6 + 2*20 + 1];
760 const char *p_end = buf + sizeof(buf);
761 char *p = buf;
762
763 # define add_said(adst, aspi, aproto) { \
764 ip_said s; \
765 \
766 initsaid(adst, aspi, aproto, &s); \
767 if (p < p_end - 1) \
768 { \
769 *p++ = ' '; \
770 p += satot(&s, 0, p, p_end - p) - 1; \
771 } \
772 }
773
774 # define add_sa_info(st, inbound) { \
775 u_int bytes; \
776 time_t use_time; \
777 \
778 if (get_sa_info(st, inbound, &bytes, &use_time)) \
779 { \
780 p += snprintf(p, p_end - p, " (%'u bytes", bytes); \
781 if (bytes > 0 && use_time != UNDEFINED_TIME) \
782 p += snprintf(p, p_end - p, ", %ds ago", (int)(now - use_time)); \
783 p += snprintf(p, p_end - p, ")"); \
784 } \
785 }
786
787 *p = '\0';
788 if (st->st_ah.present)
789 {
790 add_said(&c->spd.that.host_addr, st->st_ah.attrs.spi, SA_AH);
791 add_said(&c->spd.this.host_addr, st->st_ah.our_spi, SA_AH);
792 }
793 if (st->st_esp.present)
794 {
795 time_t now = time(NULL);
796
797 add_said(&c->spd.that.host_addr, st->st_esp.attrs.spi, SA_ESP);
798 add_sa_info(st, FALSE);
799 add_said(&c->spd.this.host_addr, st->st_esp.our_spi, SA_ESP);
800 add_sa_info(st, TRUE);
801 }
802 if (st->st_ipcomp.present)
803 {
804 add_said(&c->spd.that.host_addr, st->st_ipcomp.attrs.spi, SA_COMP);
805 add_said(&c->spd.this.host_addr, st->st_ipcomp.our_spi, SA_COMP);
806 }
807 #ifdef KLIPS
808 tunnel = st->st_ah.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL
809 || st->st_esp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL
810 || st->st_ipcomp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL;
811 p += snprintf(p, p_end - p, "; %s", tunnel? "tunnel":"transport");
812 #endif
813
814 snprintf(state_buf2, state_buf2_len
815 , "#%lu: \"%s\"%s%s"
816 , st->st_serialno
817 , c->name, inst
818 , buf);
819
820 # undef add_said
821 # undef add_sa_info
822 }
823 }
824
825 /*
826 * sorting logic is:
827 *
828 * name
829 * type
830 * instance#
831 * isakmp_sa (XXX probably wrong)
832 *
833 */
834 static int
835 state_compare(const void *a, const void *b)
836 {
837 const struct state *sap = *(const struct state *const *)a;
838 struct connection *ca = sap->st_connection;
839 const struct state *sbp = *(const struct state *const *)b;
840 struct connection *cb = sbp->st_connection;
841
842 /* DBG_log("comparing %s to %s", ca->name, cb->name); */
843
844 return connection_compare(ca, cb);
845 }
846
847 void
848 show_states_status(bool all, const char *name)
849 {
850 time_t n = now();
851 int i;
852 char state_buf[LOG_WIDTH];
853 char state_buf2[LOG_WIDTH];
854 int count;
855 struct state **array;
856
857 /* make count of states */
858 count = 0;
859 for (i = 0; i < STATE_TABLE_SIZE; i++)
860 {
861 struct state *st;
862
863 for (st = statetable[i]; st != NULL; st = st->st_hashchain_next)
864 {
865 if (name == NULL || streq(name, st->st_connection->name))
866 count++;
867 }
868 }
869
870 /* build the array */
871 array = alloc_bytes(sizeof(struct state *)*count, "state array");
872 count = 0;
873 for (i = 0; i < STATE_TABLE_SIZE; i++)
874 {
875 struct state *st;
876
877 for (st = statetable[i]; st != NULL; st = st->st_hashchain_next)
878 {
879 if (name == NULL || streq(name, st->st_connection->name))
880 array[count++]=st;
881 }
882 }
883
884 /* sort it! */
885 qsort(array, count, sizeof(struct state *), state_compare);
886
887 /* now print sorted results */
888 for (i = 0; i < count; i++)
889 {
890 struct state *st;
891
892 st = array[i];
893
894 fmt_state(all, st, n
895 , state_buf, sizeof(state_buf)
896 , state_buf2, sizeof(state_buf2));
897 whack_log(RC_COMMENT, state_buf);
898 if (state_buf2[0] != '\0')
899 whack_log(RC_COMMENT, state_buf2);
900
901 /* show any associated pending Phase 2s */
902 if (IS_PHASE1(st->st_state))
903 show_pending_phase2(st->st_connection->host_pair, st);
904 }
905 if (count > 0)
906 whack_log(RC_COMMENT, BLANK_FORMAT); /* spacer */
907
908 /* free the array */
909 pfree(array);
910 }
911
912 /* Given that we've used up a range of unused CPI's,
913 * search for a new range of currently unused ones.
914 * Note: this is very expensive when not trivial!
915 * If we can't find one easily, choose 0 (a bad SPI,
916 * no matter what order) indicating failure.
917 */
918 void
919 find_my_cpi_gap(cpi_t *latest_cpi, cpi_t *first_busy_cpi)
920 {
921 int tries = 0;
922 cpi_t base = *latest_cpi;
923 cpi_t closest;
924 int i;
925
926 startover:
927 closest = ~0; /* not close at all */
928 for (i = 0; i < STATE_TABLE_SIZE; i++)
929 {
930 struct state *st;
931
932 for (st = statetable[i]; st != NULL; st = st->st_hashchain_next)
933 {
934 if (st->st_ipcomp.present)
935 {
936 cpi_t c = ntohl(st->st_ipcomp.our_spi) - base;
937
938 if (c < closest)
939 {
940 if (c == 0)
941 {
942 /* oops: next spot is occupied; start over */
943 if (++tries == 20)
944 {
945 /* FAILURE */
946 *latest_cpi = *first_busy_cpi = 0;
947 return;
948 }
949 base++;
950 if (base > IPCOMP_LAST_NEGOTIATED)
951 base = IPCOMP_FIRST_NEGOTIATED;
952 goto startover; /* really a tail call */
953 }
954 closest = c;
955 }
956 }
957 }
958 }
959 *latest_cpi = base; /* base is first in next free range */
960 *first_busy_cpi = closest + base; /* and this is the roof */
961 }
962
963 /* Muck with high-order 16 bits of this SPI in order to make
964 * the corresponding SAID unique.
965 * Its low-order 16 bits hold a well-known IPCOMP CPI.
966 * Oh, and remember that SPIs are stored in network order.
967 * Kludge!!! So I name it with the non-English word "uniquify".
968 * If we can't find one easily, return 0 (a bad SPI,
969 * no matter what order) indicating failure.
970 */
971 ipsec_spi_t
972 uniquify_his_cpi(ipsec_spi_t cpi, struct state *st)
973 {
974 int tries = 0;
975 int i;
976
977 startover:
978
979 /* network order makes first two bytes our target */
980 get_rnd_bytes((u_char *)&cpi, 2);
981
982 /* Make sure that the result is unique.
983 * Hard work. If there is no unique value, we'll loop forever!
984 */
985 for (i = 0; i < STATE_TABLE_SIZE; i++)
986 {
987 struct state *s;
988
989 for (s = statetable[i]; s != NULL; s = s->st_hashchain_next)
990 {
991 if (s->st_ipcomp.present
992 && sameaddr(&s->st_connection->spd.that.host_addr
993 , &st->st_connection->spd.that.host_addr)
994 && cpi == s->st_ipcomp.attrs.spi)
995 {
996 if (++tries == 20)
997 return 0; /* FAILURE */
998 goto startover;
999 }
1000 }
1001 }
1002 return cpi;
1003 }
1004
1005 /*
1006 * Local Variables:
1007 * c-basic-offset:4
1008 * End:
1009 */