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