SKEYID derivation based on libstrongswan
[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
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <string.h>
19 #include <unistd.h>
20 #include <sys/types.h>
21 #include <sys/socket.h>
22 #include <netinet/in.h>
23 #include <arpa/inet.h>
24 #include <fcntl.h>
25 #include <sys/queue.h>
26
27 #include <freeswan.h>
28
29 #include <library.h>
30 #include <crypto/rngs/rng.h>
31
32 #include "constants.h"
33 #include "defs.h"
34 #include "connections.h"
35 #include "state.h"
36 #include "kernel.h"
37 #include "log.h"
38 #include "packet.h" /* so we can calculate sizeof(struct isakmp_hdr) */
39 #include "keys.h" /* for free_public_key */
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 #include "crypto.h"
45
46 /*
47 * Global variables: had to go somewhere, might as well be this file.
48 */
49
50 u_int16_t pluto_port = IKE_UDP_PORT; /* Pluto's port */
51
52 /*
53 * This file has the functions that handle the
54 * state hash table and the Message ID list.
55 */
56
57 /* Message-IDs
58 *
59 * A Message ID is contained in each IKE message header.
60 * For Phase 1 exchanges (Main and Aggressive), it will be zero.
61 * For other exchanges, which must be under the protection of an
62 * ISAKMP SA, the Message ID must be unique within that ISAKMP SA.
63 * Effectively, this labels the message as belonging to a particular
64 * exchange.
65 * BTW, we feel this uniqueness allows rekeying to be somewhat simpler
66 * than specified by draft-jenkins-ipsec-rekeying-06.txt.
67 *
68 * A MessageID is a 32 bit unsigned number. We represent the value
69 * internally in network order -- they are just blobs to us.
70 * They are unsigned numbers to make hashing and comparing easy.
71 *
72 * The following mechanism is used to allocate message IDs. This
73 * requires that we keep track of which numbers have already been used
74 * so that we don't allocate one in use.
75 */
76
77 struct msgid_list
78 {
79 msgid_t msgid; /* network order */
80 struct msgid_list *next;
81 };
82
83 bool reserve_msgid(struct state *isakmp_sa, msgid_t msgid)
84 {
85 struct msgid_list *p;
86
87 passert(msgid != MAINMODE_MSGID);
88 passert(IS_ISAKMP_ENCRYPTED(isakmp_sa->st_state));
89
90 for (p = isakmp_sa->st_used_msgids; p != NULL; p = p->next)
91 if (p->msgid == msgid)
92 return FALSE;
93
94 p = malloc_thing(struct msgid_list);
95 p->msgid = msgid;
96 p->next = isakmp_sa->st_used_msgids;
97 isakmp_sa->st_used_msgids = p;
98 return TRUE;
99 }
100
101 msgid_t generate_msgid(struct state *isakmp_sa)
102 {
103 int timeout = 100; /* only try so hard for unique msgid */
104 msgid_t msgid;
105 rng_t *rng;
106
107 passert(IS_ISAKMP_ENCRYPTED(isakmp_sa->st_state));
108 rng = lib->crypto->create_rng(lib->crypto, RNG_WEAK);
109
110 for (;;)
111 {
112 rng->get_bytes(rng, sizeof(msgid), (void *) &msgid);
113 if (msgid != 0 && reserve_msgid(isakmp_sa, msgid))
114 {
115 break;
116 }
117 if (--timeout == 0)
118 {
119 plog("gave up looking for unique msgid; using 0x%08lx"
120 , (unsigned long) msgid);
121 break;
122 }
123 }
124 rng->destroy(rng);
125 return msgid;
126 }
127
128
129 /* state table functions */
130
131 #define STATE_TABLE_SIZE 32
132
133 static struct state *statetable[STATE_TABLE_SIZE];
134
135 static struct state **state_hash(const u_char *icookie, const u_char *rcookie,
136 const ip_address *peer)
137 {
138 u_int i = 0, j;
139 const unsigned char *byte_ptr;
140 size_t length = addrbytesptr(peer, &byte_ptr);
141
142 DBG(DBG_RAW | DBG_CONTROL,
143 DBG_dump("ICOOKIE:", icookie, COOKIE_SIZE);
144 DBG_dump("RCOOKIE:", rcookie, COOKIE_SIZE);
145 DBG_dump("peer:", byte_ptr, length));
146
147 /* XXX the following hash is pretty pathetic */
148
149 for (j = 0; j < COOKIE_SIZE; j++)
150 i = i * 407 + icookie[j] + rcookie[j];
151
152 for (j = 0; j < length; j++)
153 i = i * 613 + byte_ptr[j];
154
155 i = i % STATE_TABLE_SIZE;
156
157 DBG(DBG_CONTROL, DBG_log("state hash entry %d", i));
158
159 return &statetable[i];
160 }
161
162 /* Get a state object.
163 * Caller must schedule an event for this object so that it doesn't leak.
164 * Caller must insert_state().
165 */
166 struct state *new_state(void)
167 {
168 static const struct state blank_state; /* initialized all to zero & NULL */
169 static so_serial_t next_so = SOS_FIRST;
170 struct state *st;
171
172 st = clone_thing(blank_state);
173 st->st_serialno = next_so++;
174 passert(next_so > SOS_FIRST); /* overflow can't happen! */
175 st->st_whack_sock = NULL_FD;
176 DBG(DBG_CONTROL, DBG_log("creating state object #%lu at %p",
177 st->st_serialno, (void *) st));
178 return st;
179 }
180
181 /*
182 * Initialize the state table (and mask*).
183 */
184 void init_states(void)
185 {
186 int i;
187
188 for (i = 0; i < STATE_TABLE_SIZE; i++)
189 statetable[i] = (struct state *) NULL;
190 }
191
192 /* Find the state object with this serial number.
193 * This allows state object references that don't turn into dangerous
194 * dangling pointers: reference a state by its serial number.
195 * Returns NULL if there is no such state.
196 * If this turns out to be a significant CPU hog, it could be
197 * improved to use a hash table rather than sequential seartch.
198 */
199 struct state *state_with_serialno(so_serial_t sn)
200 {
201 if (sn >= SOS_FIRST)
202 {
203 struct state *st;
204 int i;
205
206 for (i = 0; i < STATE_TABLE_SIZE; i++)
207 for (st = statetable[i]; st != NULL; st = st->st_hashchain_next)
208 if (st->st_serialno == sn)
209 return st;
210 }
211 return NULL;
212 }
213
214 /* Insert a state object in the hash table. The object is inserted
215 * at the begining of list.
216 * Needs cookies, connection, and msgid.
217 */
218 void insert_state(struct state *st)
219 {
220 struct state **p = state_hash(st->st_icookie, st->st_rcookie
221 , &st->st_connection->spd.that.host_addr);
222
223 passert(st->st_hashchain_prev == NULL && st->st_hashchain_next == NULL);
224
225 if (*p != NULL)
226 {
227 passert((*p)->st_hashchain_prev == NULL);
228 (*p)->st_hashchain_prev = st;
229 }
230 st->st_hashchain_next = *p;
231 *p = st;
232
233 /* Ensure that somebody is in charge of killing this state:
234 * if no event is scheduled for it, schedule one to discard the state.
235 * If nothing goes wrong, this event will be replaced by
236 * a more appropriate one.
237 */
238 if (st->st_event == NULL)
239 event_schedule(EVENT_SO_DISCARD, 0, st);
240 }
241
242 /* unlink a state object from the hash table, but don't free it
243 */
244 void unhash_state(struct state *st)
245 {
246 /* unlink from forward chain */
247 struct state **p = st->st_hashchain_prev == NULL
248 ? state_hash(st->st_icookie, st->st_rcookie
249 , &st->st_connection->spd.that.host_addr)
250 : &st->st_hashchain_prev->st_hashchain_next;
251
252 /* unlink from forward chain */
253 passert(*p == st);
254 *p = st->st_hashchain_next;
255
256 /* unlink from backward chain */
257 if (st->st_hashchain_next != NULL)
258 {
259 passert(st->st_hashchain_next->st_hashchain_prev == st);
260 st->st_hashchain_next->st_hashchain_prev = st->st_hashchain_prev;
261 }
262
263 st->st_hashchain_next = st->st_hashchain_prev = NULL;
264 }
265
266 /* Free the Whack socket file descriptor.
267 * This has the side effect of telling Whack that we're done.
268 */
269 void release_whack(struct state *st)
270 {
271 close_any(st->st_whack_sock);
272 }
273
274 /**
275 * Delete a state object
276 */
277 void delete_state(struct state *st)
278 {
279 struct connection *const c = st->st_connection;
280 struct state *old_cur_state = cur_state == st? NULL : cur_state;
281
282 set_cur_state(st);
283
284 /* If DPD is enabled on this state object, clear any pending events */
285 if(st->st_dpd_event != NULL)
286 delete_dpd_event(st);
287
288 /* if there is a suspended state transition, disconnect us */
289 if (st->st_suspended_md != NULL)
290 {
291 passert(st->st_suspended_md->st == st);
292 st->st_suspended_md->st = NULL;
293 }
294
295 /* tell the other side of any IPSEC SAs that are going down */
296 if (IS_IPSEC_SA_ESTABLISHED(st->st_state)
297 || IS_ISAKMP_SA_ESTABLISHED(st->st_state))
298 send_delete(st);
299
300 delete_event(st); /* delete any pending timer event */
301
302 /* Ditch anything pending on ISAKMP SA being established.
303 * Note: this must be done before the unhash_state to prevent
304 * flush_pending_by_state inadvertently and prematurely
305 * deleting our connection.
306 */
307 flush_pending_by_state(st);
308
309 /* effectively, this deletes any ISAKMP SA that this state represents */
310 unhash_state(st);
311
312 /* tell kernel to delete any IPSEC SA
313 * ??? we ought to tell peer to delete IPSEC SAs
314 */
315 if (IS_IPSEC_SA_ESTABLISHED(st->st_state))
316 delete_ipsec_sa(st, FALSE);
317 else if (IS_ONLY_INBOUND_IPSEC_SA_ESTABLISHED(st->st_state))
318 delete_ipsec_sa(st, TRUE);
319
320 if (c->newest_ipsec_sa == st->st_serialno)
321 c->newest_ipsec_sa = SOS_NOBODY;
322
323 if (c->newest_isakmp_sa == st->st_serialno)
324 c->newest_isakmp_sa = SOS_NOBODY;
325
326 st->st_connection = NULL; /* we might be about to free it */
327 cur_state = old_cur_state; /* without st_connection, st isn't complete */
328 connection_discard(c);
329
330 release_whack(st);
331
332 /* from here on we are just freeing RAM */
333
334 {
335 struct msgid_list *p = st->st_used_msgids;
336
337 while (p != NULL)
338 {
339 struct msgid_list *q = p;
340 p = p->next;
341 free(q);
342 }
343 }
344
345 unreference_key(&st->st_peer_pubkey);
346
347 if (st->st_sec_in_use)
348 mpz_clear(&(st->st_sec));
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 */