]> git.ipfire.org Git - people/ms/strongswan.git/blob - src/pluto/kernel.c
5d7c5f78aa546f0c5bf6105ffa43b4d6288e6aa9
[people/ms/strongswan.git] / src / pluto / kernel.c
1 /* routines that interface with the kernel's IPsec mechanism
2 * Copyright (C) 1997 Angelos D. Keromytis.
3 * Copyright (C) 1998-2002 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: kernel.c,v 1.25 2006/04/17 14:58:09 as Exp $
16 */
17
18 #include <stddef.h>
19 #include <string.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <errno.h>
23 #include <wait.h>
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <sys/queue.h>
27
28 #include <sys/stat.h>
29 #include <sys/socket.h>
30 #include <netinet/in.h>
31 #include <arpa/inet.h>
32
33 #include <freeswan.h>
34 #include <freeswan/ipsec_policy.h>
35
36 #ifdef KLIPS
37 #include <signal.h>
38 #include <sys/time.h> /* for select(2) */
39 #include <sys/types.h> /* for select(2) */
40 #include <pfkeyv2.h>
41 #include <pfkey.h>
42 #include "kameipsec.h"
43 #endif /* KLIPS */
44
45 #include "constants.h"
46 #include "defs.h"
47 #include "rnd.h"
48 #include "id.h"
49 #include "connections.h"
50 #include "state.h"
51 #include "timer.h"
52 #include "kernel.h"
53 #include "kernel_netlink.h"
54 #include "kernel_pfkey.h"
55 #include "kernel_noklips.h"
56 #include "log.h"
57 #include "ca.h"
58 #include "server.h"
59 #include "whack.h" /* for RC_LOG_SERIOUS */
60 #include "keys.h"
61
62 #ifdef NAT_TRAVERSAL
63 #include "packet.h" /* for pb_stream in nat_traversal.h */
64 #include "nat_traversal.h"
65 #endif
66
67 #include "alg_info.h"
68 #include "kernel_alg.h"
69
70
71 bool can_do_IPcomp = TRUE; /* can system actually perform IPCOMP? */
72
73 /* How far can IPsec messages arrive out of order before the anti-replay
74 * logic loses track and swats them? 64 is the best KLIPS can do.
75 * And 32 is the best XFRM can do...
76 */
77 #define REPLAY_WINDOW 64
78 #define REPLAY_WINDOW_XFRM 32
79
80 /* test if the routes required for two different connections agree
81 * It is assumed that the destination subnets agree; we are only
82 * testing that the interfaces and nexthops match.
83 */
84 #define routes_agree(c, d) ((c)->interface == (d)->interface \
85 && sameaddr(&(c)->spd.this.host_nexthop, &(d)->spd.this.host_nexthop))
86
87 #ifndef KLIPS
88
89 bool no_klips = TRUE; /* don't actually use KLIPS */
90
91 #else /* !KLIPS */
92
93 /* bare (connectionless) shunt (eroute) table
94 *
95 * Bare shunts are those that don't "belong" to a connection.
96 * This happens because some %trapped traffic hasn't yet or cannot be
97 * assigned to a connection. The usual reason is that we cannot discover
98 * the peer SG. Another is that even when the peer has been discovered,
99 * it may be that no connection matches all the particulars.
100 * We record them so that, with scanning, we can discover
101 * which %holds are news and which others should expire.
102 */
103
104 #define SHUNT_SCAN_INTERVAL (60 * 2) /* time between scans of eroutes */
105
106 /* SHUNT_PATIENCE only has resolution down to a multiple of the sample rate,
107 * SHUNT_SCAN_INTERVAL.
108 * By making SHUNT_PATIENCE an odd multiple of half of SHUNT_SCAN_INTERVAL,
109 * we minimize the effects of jitter.
110 */
111 #define SHUNT_PATIENCE (SHUNT_SCAN_INTERVAL * 15 / 2) /* inactivity timeout */
112
113 struct bare_shunt {
114 policy_prio_t policy_prio;
115 ip_subnet ours;
116 ip_subnet his;
117 ip_said said;
118 int transport_proto;
119 unsigned long count;
120 time_t last_activity;
121 char *why;
122 struct bare_shunt *next;
123 };
124
125 static struct bare_shunt *bare_shunts = NULL;
126
127 #ifdef DEBUG
128 static void
129 DBG_bare_shunt(const char *op, const struct bare_shunt *bs)
130 {
131 DBG(DBG_KLIPS,
132 {
133 int ourport = ntohs(portof(&(bs)->ours.addr));
134 int hisport = ntohs(portof(&(bs)->his.addr));
135 char ourst[SUBNETTOT_BUF];
136 char hist[SUBNETTOT_BUF];
137 char sat[SATOT_BUF];
138 char prio[POLICY_PRIO_BUF];
139
140 subnettot(&(bs)->ours, 0, ourst, sizeof(ourst));
141 subnettot(&(bs)->his, 0, hist, sizeof(hist));
142 satot(&(bs)->said, 0, sat, sizeof(sat));
143 fmt_policy_prio(bs->policy_prio, prio);
144 DBG_log("%s bare shunt %p %s:%d -> %s:%d => %s:%d %s %s"
145 , op, (const void *)(bs), ourst, ourport, hist, hisport
146 , sat, (bs)->transport_proto, prio, (bs)->why);
147 });
148 }
149 #else /* !DEBUG */
150 #define DBG_bare_shunt(op, bs) {}
151 #endif /* !DEBUG */
152
153 /* The orphaned_holds table records %holds for which we
154 * scan_proc_shunts found no representation of in any connection.
155 * The corresponding ACQUIRE message might have been lost.
156 */
157 struct eroute_info *orphaned_holds = NULL;
158
159 /* forward declaration */
160 static bool shunt_eroute(struct connection *c
161 , struct spd_route *sr
162 , enum routing_t rt_kind
163 , unsigned int op, const char *opname);
164 static void set_text_said(char *text_said
165 , const ip_address *dst
166 , ipsec_spi_t spi
167 , int proto);
168
169 bool no_klips = FALSE; /* don't actually use KLIPS */
170
171 static const struct pfkey_proto_info null_proto_info[2] = {
172 {
173 proto: IPPROTO_ESP,
174 encapsulation: ENCAPSULATION_MODE_TRANSPORT,
175 reqid: 0
176 },
177 {
178 proto: 0,
179 encapsulation: 0,
180 reqid: 0
181 }
182 };
183
184 void
185 record_and_initiate_opportunistic(const ip_subnet *ours
186 , const ip_subnet *his
187 , int transport_proto
188 , const char *why)
189 {
190 passert(samesubnettype(ours, his));
191
192 /* Add to bare shunt list.
193 * We need to do this because the shunt was installed by KLIPS
194 * which can't do this itself.
195 */
196 {
197 struct bare_shunt *bs = alloc_thing(struct bare_shunt, "bare shunt");
198
199 bs->why = clone_str(why, "story for bare shunt");
200 bs->ours = *ours;
201 bs->his = *his;
202 bs->transport_proto = transport_proto;
203 bs->policy_prio = BOTTOM_PRIO;
204
205 bs->said.proto = SA_INT;
206 bs->said.spi = htonl(SPI_HOLD);
207 bs->said.dst = *aftoinfo(subnettypeof(ours))->any;
208
209 bs->count = 0;
210 bs->last_activity = now();
211
212 bs->next = bare_shunts;
213 bare_shunts = bs;
214 DBG_bare_shunt("add", bs);
215 }
216
217 /* actually initiate opportunism */
218 {
219 ip_address src, dst;
220
221 networkof(ours, &src);
222 networkof(his, &dst);
223 initiate_opportunistic(&src, &dst, transport_proto, TRUE, NULL_FD);
224 }
225
226 /* if present, remove from orphaned_holds list.
227 * NOTE: we do this last in case ours or his is a pointer into a member.
228 */
229 {
230 struct eroute_info **pp, *p;
231
232 for (pp = &orphaned_holds; (p = *pp) != NULL; pp = &p->next)
233 {
234 if (samesubnet(ours, &p->ours)
235 && samesubnet(his, &p->his)
236 && transport_proto == p->transport_proto
237 && portof(&ours->addr) == portof(&p->ours.addr)
238 && portof(&his->addr) == portof(&p->his.addr))
239 {
240 *pp = p->next;
241 pfree(p);
242 break;
243 }
244 }
245 }
246 }
247
248 #endif /* KLIPS */
249
250 static unsigned get_proto_reqid(unsigned base, int proto)
251 {
252 switch (proto)
253 {
254 default:
255 case IPPROTO_COMP:
256 base++;
257 /* fall through */
258 case IPPROTO_ESP:
259 base++;
260 /* fall through */
261 case IPPROTO_AH:
262 break;
263 }
264
265 return base;
266 }
267
268 /* Generate Unique SPI numbers.
269 *
270 * The specs say that the number must not be less than IPSEC_DOI_SPI_MIN.
271 * Pluto generates numbers not less than IPSEC_DOI_SPI_OUR_MIN,
272 * reserving numbers in between for manual keying (but we cannot so
273 * restrict numbers generated by our peer).
274 * XXX This should be replaced by a call to the kernel when
275 * XXX we get an API.
276 * The returned SPI is in network byte order.
277 * We use a random number as the initial SPI so that there is
278 * a good chance that different Pluto instances will choose
279 * different SPIs. This is good for two reasons.
280 * - the keying material for the initiator and responder only
281 * differs if the SPIs differ.
282 * - if Pluto is restarted, it would otherwise recycle the SPI
283 * numbers and confuse everything. When the kernel generates
284 * SPIs, this will no longer matter.
285 * We then allocate numbers sequentially. Thus we don't have to
286 * check if the number was previously used (assuming that no
287 * SPI lives longer than 4G of its successors).
288 */
289 ipsec_spi_t
290 get_ipsec_spi(ipsec_spi_t avoid, int proto, struct spd_route *sr, bool tunnel)
291 {
292 static ipsec_spi_t spi = 0; /* host order, so not returned directly! */
293 char text_said[SATOT_BUF];
294
295 set_text_said(text_said, &sr->this.host_addr, 0, proto);
296
297 if (kernel_ops->get_spi)
298 return kernel_ops->get_spi(&sr->that.host_addr
299 , &sr->this.host_addr, proto, tunnel
300 , get_proto_reqid(sr->reqid, proto)
301 , IPSEC_DOI_SPI_OUR_MIN, 0xffffffff
302 , text_said);
303
304 spi++;
305 while (spi < IPSEC_DOI_SPI_OUR_MIN || spi == ntohl(avoid))
306 get_rnd_bytes((u_char *)&spi, sizeof(spi));
307
308 DBG(DBG_CONTROL,
309 {
310 ipsec_spi_t spi_net = htonl(spi);
311
312 DBG_dump("generate SPI:", (u_char *)&spi_net, sizeof(spi_net));
313 });
314
315 return htonl(spi);
316 }
317
318 /* Generate Unique CPI numbers.
319 * The result is returned as an SPI (4 bytes) in network order!
320 * The real bits are in the nework-low-order 2 bytes.
321 * Modelled on get_ipsec_spi, but range is more limited:
322 * 256-61439.
323 * If we can't find one easily, return 0 (a bad SPI,
324 * no matter what order) indicating failure.
325 */
326 ipsec_spi_t
327 get_my_cpi(struct spd_route *sr, bool tunnel)
328 {
329 static cpi_t
330 first_busy_cpi = 0,
331 latest_cpi;
332 char text_said[SATOT_BUF];
333
334 set_text_said(text_said, &sr->this.host_addr, 0, IPPROTO_COMP);
335
336 if (kernel_ops->get_spi)
337 return kernel_ops->get_spi(&sr->that.host_addr
338 , &sr->this.host_addr, IPPROTO_COMP, tunnel
339 , get_proto_reqid(sr->reqid, IPPROTO_COMP)
340 , IPCOMP_FIRST_NEGOTIATED, IPCOMP_LAST_NEGOTIATED
341 , text_said);
342
343 while (!(IPCOMP_FIRST_NEGOTIATED <= first_busy_cpi && first_busy_cpi < IPCOMP_LAST_NEGOTIATED))
344 {
345 get_rnd_bytes((u_char *)&first_busy_cpi, sizeof(first_busy_cpi));
346 latest_cpi = first_busy_cpi;
347 }
348
349 latest_cpi++;
350
351 if (latest_cpi == first_busy_cpi)
352 find_my_cpi_gap(&latest_cpi, &first_busy_cpi);
353
354 if (latest_cpi > IPCOMP_LAST_NEGOTIATED)
355 latest_cpi = IPCOMP_FIRST_NEGOTIATED;
356
357 return htonl((ipsec_spi_t)latest_cpi);
358 }
359
360 /* invoke the updown script to do the routing and firewall commands required
361 *
362 * The user-specified updown script is run. Parameters are fed to it in
363 * the form of environment variables. All such environment variables
364 * have names starting with "PLUTO_".
365 *
366 * The operation to be performed is specified by PLUTO_VERB. This
367 * verb has a suffix "-host" if the client on this end is just the
368 * host; otherwise the suffix is "-client". If the address family
369 * of the host is IPv6, an extra suffix of "-v6" is added.
370 *
371 * "prepare-host" and "prepare-client" are used to delete a route
372 * that may exist (due to forces outside of Pluto). It is used to
373 * prepare for pluto creating a route.
374 *
375 * "route-host" and "route-client" are used to install a route.
376 * Since routing is based only on destination, the PLUTO_MY_CLIENT_*
377 * values are probably of no use (using them may signify a bug).
378 *
379 * "unroute-host" and "unroute-client" are used to delete a route.
380 * Since routing is based only on destination, the PLUTO_MY_CLIENT_*
381 * values are probably of no use (using them may signify a bug).
382 *
383 * "up-host" and "up-client" are run when an eroute is added (not replaced).
384 * They are useful for adjusting a firewall: usually for adding a rule
385 * to let processed packets flow between clients. Note that only
386 * one eroute may exist for a pair of client subnets but inbound
387 * IPsec SAs may persist without an eroute.
388 *
389 * "down-host" and "down-client" are run when an eroute is deleted.
390 * They are useful for adjusting a firewall.
391 */
392
393 #ifndef DEFAULT_UPDOWN
394 # define DEFAULT_UPDOWN "ipsec _updown"
395 #endif
396
397 static bool
398 do_command(struct connection *c, struct spd_route *sr, const char *verb)
399 {
400 char cmd[1536]; /* arbitrary limit on shell command length */
401 const char *verb_suffix;
402
403 /* figure out which verb suffix applies */
404 {
405 const char *hs, *cs;
406
407 switch (addrtypeof(&sr->this.host_addr))
408 {
409 case AF_INET:
410 hs = "-host";
411 cs = "-client";
412 break;
413 case AF_INET6:
414 hs = "-host-v6";
415 cs = "-client-v6";
416 break;
417 default:
418 loglog(RC_LOG_SERIOUS, "unknown address family");
419 return FALSE;
420 }
421 verb_suffix = subnetisaddr(&sr->this.client, &sr->this.host_addr)
422 ? hs : cs;
423 }
424
425 /* form the command string */
426 {
427 char
428 nexthop_str[sizeof("PLUTO_NEXT_HOP='' ") +ADDRTOT_BUF] = "",
429 srcip_str[sizeof("PLUTO_MY_SOURCEIP='' ")+ADDRTOT_BUF] = "",
430 me_str[ADDRTOT_BUF],
431 myid_str[BUF_LEN],
432 myclient_str[SUBNETTOT_BUF],
433 myclientnet_str[ADDRTOT_BUF],
434 myclientmask_str[ADDRTOT_BUF],
435 peer_str[ADDRTOT_BUF],
436 peerid_str[BUF_LEN],
437 peerclient_str[SUBNETTOT_BUF],
438 peerclientnet_str[ADDRTOT_BUF],
439 peerclientmask_str[ADDRTOT_BUF],
440 peerca_str[BUF_LEN],
441 secure_myid_str[BUF_LEN] = "",
442 secure_peerid_str[BUF_LEN] = "",
443 secure_peerca_str[BUF_LEN] = "";
444 ip_address ta;
445 pubkey_list_t *p;
446
447 if (addrbytesptr(&sr->this.host_nexthop, NULL)
448 && !isanyaddr(&sr->this.host_nexthop))
449 {
450 char *n;
451
452 strcpy(nexthop_str, "PLUTO_NEXT_HOP='");
453 n = nexthop_str + strlen(nexthop_str);
454
455 addrtot(&sr->this.host_nexthop, 0
456 ,n , sizeof(nexthop_str)-strlen(nexthop_str));
457 strncat(nexthop_str, "' ", sizeof(nexthop_str));
458 }
459
460 if (addrbytesptr(&sr->this.host_srcip, NULL)
461 && !isanyaddr(&sr->this.host_srcip))
462 {
463 char *n;
464
465 strcpy(srcip_str, "PLUTO_MY_SOURCEIP='");
466 n = srcip_str + strlen(srcip_str);
467
468 addrtot(&sr->this.host_srcip, 0
469 ,n , sizeof(srcip_str)-strlen(srcip_str));
470 strncat(srcip_str, "' ", sizeof(srcip_str));
471 }
472
473 addrtot(&sr->this.host_addr, 0, me_str, sizeof(me_str));
474 idtoa(&sr->this.id, myid_str, sizeof(myid_str));
475 escape_metachar(myid_str, secure_myid_str, sizeof(secure_myid_str));
476 subnettot(&sr->this.client, 0, myclient_str, sizeof(myclientnet_str));
477 networkof(&sr->this.client, &ta);
478 addrtot(&ta, 0, myclientnet_str, sizeof(myclientnet_str));
479 maskof(&sr->this.client, &ta);
480 addrtot(&ta, 0, myclientmask_str, sizeof(myclientmask_str));
481
482 addrtot(&sr->that.host_addr, 0, peer_str, sizeof(peer_str));
483 idtoa(&sr->that.id, peerid_str, sizeof(peerid_str));
484 escape_metachar(peerid_str, secure_peerid_str, sizeof(secure_peerid_str));
485 subnettot(&sr->that.client, 0, peerclient_str, sizeof(peerclientnet_str));
486 networkof(&sr->that.client, &ta);
487 addrtot(&ta, 0, peerclientnet_str, sizeof(peerclientnet_str));
488 maskof(&sr->that.client, &ta);
489 addrtot(&ta, 0, peerclientmask_str, sizeof(peerclientmask_str));
490
491 for (p = pubkeys; p != NULL; p = p->next)
492 {
493 pubkey_t *key = p->key;
494 int pathlen;
495
496 if (key->alg == PUBKEY_ALG_RSA && same_id(&sr->that.id, &key->id)
497 && trusted_ca(key->issuer, sr->that.ca, &pathlen))
498 {
499 dntoa_or_null(peerca_str, BUF_LEN, key->issuer, "");
500 escape_metachar(peerca_str, secure_peerca_str, sizeof(secure_peerca_str));
501 break;
502 }
503 }
504
505 if (-1 == snprintf(cmd, sizeof(cmd)
506 , "2>&1 " /* capture stderr along with stdout */
507 "PLUTO_VERSION='1.1' " /* change VERSION when interface spec changes */
508 "PLUTO_VERB='%s%s' "
509 "PLUTO_CONNECTION='%s' "
510 "%s" /* optional PLUTO_NEXT_HOP */
511 "PLUTO_INTERFACE='%s' "
512 "%s" /* optional PLUTO_HOST_ACCESS */
513 "PLUTO_REQID='%u' "
514 "PLUTO_ME='%s' "
515 "PLUTO_MY_ID='%s' "
516 "PLUTO_MY_CLIENT='%s' "
517 "PLUTO_MY_CLIENT_NET='%s' "
518 "PLUTO_MY_CLIENT_MASK='%s' "
519 "PLUTO_MY_PORT='%u' "
520 "PLUTO_MY_PROTOCOL='%u' "
521 "PLUTO_PEER='%s' "
522 "PLUTO_PEER_ID='%s' "
523 "PLUTO_PEER_CLIENT='%s' "
524 "PLUTO_PEER_CLIENT_NET='%s' "
525 "PLUTO_PEER_CLIENT_MASK='%s' "
526 "PLUTO_PEER_PORT='%u' "
527 "PLUTO_PEER_PROTOCOL='%u' "
528 "PLUTO_PEER_CA='%s' "
529 "%s" /* optional PLUTO_MY_SRCIP */
530 "%s" /* actual script */
531 , verb, verb_suffix
532 , c->name
533 , nexthop_str
534 , c->interface->vname
535 , sr->this.hostaccess? "PLUTO_HOST_ACCESS='1' " : ""
536 , sr->reqid + 1 /* ESP requid */
537 , me_str
538 , secure_myid_str
539 , myclient_str
540 , myclientnet_str
541 , myclientmask_str
542 , sr->this.port
543 , sr->this.protocol
544 , peer_str
545 , secure_peerid_str
546 , peerclient_str
547 , peerclientnet_str
548 , peerclientmask_str
549 , sr->that.port
550 , sr->that.protocol
551 , secure_peerca_str
552 , srcip_str
553 , sr->this.updown == NULL? DEFAULT_UPDOWN : sr->this.updown))
554 {
555 loglog(RC_LOG_SERIOUS, "%s%s command too long!", verb, verb_suffix);
556 return FALSE;
557 }
558 }
559
560 DBG(DBG_CONTROL, DBG_log("executing %s%s: %s"
561 , verb, verb_suffix, cmd));
562
563 #ifdef KLIPS
564 if (!no_klips)
565 {
566 /* invoke the script, catching stderr and stdout
567 * It may be of concern that some file descriptors will
568 * be inherited. For the ones under our control, we
569 * have done fcntl(fd, F_SETFD, FD_CLOEXEC) to prevent this.
570 * Any used by library routines (perhaps the resolver or syslog)
571 * will remain.
572 */
573 FILE *f = popen(cmd, "r");
574
575 if (f == NULL)
576 {
577 loglog(RC_LOG_SERIOUS, "unable to popen %s%s command", verb, verb_suffix);
578 return FALSE;
579 }
580
581 /* log any output */
582 for (;;)
583 {
584 /* if response doesn't fit in this buffer, it will be folded */
585 char resp[256];
586
587 if (fgets(resp, sizeof(resp), f) == NULL)
588 {
589 if (ferror(f))
590 {
591 log_errno((e, "fgets failed on output of %s%s command"
592 , verb, verb_suffix));
593 return FALSE;
594 }
595 else
596 {
597 passert(feof(f));
598 break;
599 }
600 }
601 else
602 {
603 char *e = resp + strlen(resp);
604
605 if (e > resp && e[-1] == '\n')
606 e[-1] = '\0'; /* trim trailing '\n' */
607 plog("%s%s output: %s", verb, verb_suffix, resp);
608 }
609 }
610
611 /* report on and react to return code */
612 {
613 int r = pclose(f);
614
615 if (r == -1)
616 {
617 log_errno((e, "pclose failed for %s%s command"
618 , verb, verb_suffix));
619 return FALSE;
620 }
621 else if (WIFEXITED(r))
622 {
623 if (WEXITSTATUS(r) != 0)
624 {
625 loglog(RC_LOG_SERIOUS, "%s%s command exited with status %d"
626 , verb, verb_suffix, WEXITSTATUS(r));
627 return FALSE;
628 }
629 }
630 else if (WIFSIGNALED(r))
631 {
632 loglog(RC_LOG_SERIOUS, "%s%s command exited with signal %d"
633 , verb, verb_suffix, WTERMSIG(r));
634 return FALSE;
635 }
636 else
637 {
638 loglog(RC_LOG_SERIOUS, "%s%s command exited with unknown status %d"
639 , verb, verb_suffix, r);
640 return FALSE;
641 }
642 }
643 }
644 #endif /* KLIPS */
645 return TRUE;
646 }
647
648 /* Check that we can route (and eroute). Diagnose if we cannot. */
649
650 enum routability {
651 route_impossible = 0,
652 route_easy = 1,
653 route_nearconflict = 2,
654 route_farconflict = 3
655 };
656
657 static enum routability
658 could_route(struct connection *c)
659 {
660 struct spd_route *esr, *rosr;
661 struct connection *ero /* who, if anyone, owns our eroute? */
662 , *ro = route_owner(c, &rosr, &ero, &esr); /* who owns our route? */
663
664 /* it makes no sense to route a connection that is ISAKMP-only */
665 if (!NEVER_NEGOTIATE(c->policy) && !HAS_IPSEC_POLICY(c->policy))
666 {
667 loglog(RC_ROUTE, "cannot route an ISAKMP-only connection");
668 return route_impossible;
669 }
670
671 /* if this is a Road Warrior template, we cannot route.
672 * Opportunistic template is OK.
673 */
674 if (c->kind == CK_TEMPLATE && !(c->policy & POLICY_OPPO))
675 {
676 loglog(RC_ROUTE, "cannot route Road Warrior template");
677 return route_impossible;
678 }
679
680 /* if we don't know nexthop, we cannot route */
681 if (isanyaddr(&c->spd.this.host_nexthop))
682 {
683 loglog(RC_ROUTE, "cannot route connection without knowing our nexthop");
684 return route_impossible;
685 }
686
687 /* if routing would affect IKE messages, reject */
688 if (!no_klips
689 #ifdef NAT_TRAVERSAL
690 && c->spd.this.host_port != NAT_T_IKE_FLOAT_PORT
691 #endif
692 && c->spd.this.host_port != IKE_UDP_PORT
693 && addrinsubnet(&c->spd.that.host_addr, &c->spd.that.client))
694 {
695 loglog(RC_LOG_SERIOUS, "cannot install route: peer is within its client");
696 return route_impossible;
697 }
698
699 /* If there is already a route for peer's client subnet
700 * and it disagrees about interface or nexthop, we cannot steal it.
701 * Note: if this connection is already routed (perhaps for another
702 * state object), the route will agree.
703 * This is as it should be -- it will arise during rekeying.
704 */
705 if (ro != NULL && !routes_agree(ro, c))
706 {
707 loglog(RC_LOG_SERIOUS, "cannot route -- route already in use for \"%s\""
708 , ro->name);
709 return route_impossible; /* another connection already
710 using the eroute */
711 }
712
713 #ifdef KLIPS
714 /* if there is an eroute for another connection, there is a problem */
715 if (ero != NULL && ero != c)
716 {
717 struct connection *ero2, *ero_top;
718 struct connection *inside, *outside;
719
720 /*
721 * note, wavesec (PERMANENT) goes *outside* and
722 * OE goes *inside* (TEMPLATE)
723 */
724 inside = NULL;
725 outside= NULL;
726 if (ero->kind == CK_PERMANENT
727 && c->kind == CK_TEMPLATE)
728 {
729 outside = ero;
730 inside = c;
731 }
732 else if (c->kind == CK_PERMANENT
733 && ero->kind == CK_TEMPLATE)
734 {
735 outside = c;
736 inside = ero;
737 }
738
739 /* okay, check again, with correct order */
740 if (outside && outside->kind == CK_PERMANENT
741 && inside && inside->kind == CK_TEMPLATE)
742 {
743 char inst[CONN_INST_BUF];
744
745 /* this is a co-terminal attempt of the "near" kind. */
746 /* when chaining, we chain from inside to outside */
747
748 /* XXX permit multiple deep connections? */
749 passert(inside->policy_next == NULL);
750
751 inside->policy_next = outside;
752
753 /* since we are going to steal the eroute from the secondary
754 * policy, we need to make sure that it no longer thinks that
755 * it owns the eroute.
756 */
757 outside->spd.eroute_owner = SOS_NOBODY;
758 outside->spd.routing = RT_UNROUTED_KEYED;
759
760 /* set the priority of the new eroute owner to be higher
761 * than that of the current eroute owner
762 */
763 inside->prio = outside->prio + 1;
764
765 fmt_conn_instance(inside, inst);
766
767 loglog(RC_LOG_SERIOUS
768 , "conflict on eroute (%s), switching eroute to %s and linking %s"
769 , inst, inside->name, outside->name);
770
771 return route_nearconflict;
772 }
773
774 /* look along the chain of policies for one with the same name */
775 ero_top = ero;
776
777 for (ero2 = ero; ero2 != NULL; ero2 = ero->policy_next)
778 {
779 if (ero2->kind == CK_TEMPLATE
780 && streq(ero2->name, c->name))
781 break;
782 }
783
784 /* If we fell of the end of the list, then we found no TEMPLATE
785 * so there must be a conflict that we can't resolve.
786 * As the names are not equal, then we aren't replacing/rekeying.
787 */
788 if (ero2 == NULL)
789 {
790 char inst[CONN_INST_BUF];
791
792 fmt_conn_instance(ero, inst);
793
794 loglog(RC_LOG_SERIOUS
795 , "cannot install eroute -- it is in use for \"%s\"%s #%lu"
796 , ero->name, inst, esr->eroute_owner);
797 return FALSE; /* another connection already using the eroute */
798 }
799 }
800 #endif /* KLIPS */
801 return route_easy;
802 }
803
804 bool
805 trap_connection(struct connection *c)
806 {
807 switch (could_route(c))
808 {
809 case route_impossible:
810 return FALSE;
811
812 case route_nearconflict:
813 case route_easy:
814 /* RT_ROUTED_TUNNEL is treated specially: we don't override
815 * because we don't want to lose track of the IPSEC_SAs etc.
816 */
817 if (c->spd.routing < RT_ROUTED_TUNNEL)
818 {
819 return route_and_eroute(c, &c->spd, NULL);
820 }
821 return TRUE;
822
823 case route_farconflict:
824 return FALSE;
825 }
826
827 return FALSE;
828 }
829
830 /* delete any eroute for a connection and unroute it if route isn't shared */
831 void
832 unroute_connection(struct connection *c)
833 {
834 struct spd_route *sr;
835 enum routing_t cr;
836
837 for (sr = &c->spd; sr; sr = sr->next)
838 {
839 cr = sr->routing;
840
841 if (erouted(cr))
842 {
843 /* cannot handle a live one */
844 passert(sr->routing != RT_ROUTED_TUNNEL);
845 #ifdef KLIPS
846 shunt_eroute(c, sr, RT_UNROUTED, ERO_DELETE, "delete");
847 #endif
848 }
849
850 sr->routing = RT_UNROUTED; /* do now so route_owner won't find us */
851
852 /* only unroute if no other connection shares it */
853 if (routed(cr) && route_owner(c, NULL, NULL, NULL) == NULL)
854 (void) do_command(c, sr, "unroute");
855 }
856 }
857
858
859 #ifdef KLIPS
860
861 static void
862 set_text_said(char *text_said, const ip_address *dst, ipsec_spi_t spi, int proto)
863 {
864 ip_said said;
865
866 initsaid(dst, spi, proto, &said);
867 satot(&said, 0, text_said, SATOT_BUF);
868 }
869
870 /* find an entry in the bare_shunt table.
871 * Trick: return a pointer to the pointer to the entry;
872 * this allows the entry to be deleted.
873 */
874 static struct bare_shunt **
875 bare_shunt_ptr(const ip_subnet *ours, const ip_subnet *his, int transport_proto)
876 {
877 struct bare_shunt *p, **pp;
878
879 for (pp = &bare_shunts; (p = *pp) != NULL; pp = &p->next)
880 {
881 if (samesubnet(ours, &p->ours)
882 && samesubnet(his, &p->his)
883 && transport_proto == p->transport_proto
884 && portof(&ours->addr) == portof(&p->ours.addr)
885 && portof(&his->addr) == portof(&p->his.addr))
886 return pp;
887 }
888 return NULL;
889 }
890
891 /* free a bare_shunt entry, given a pointer to the pointer */
892 static void
893 free_bare_shunt(struct bare_shunt **pp)
894 {
895 if (pp == NULL)
896 {
897 DBG(DBG_CONTROL,
898 DBG_log("delete bare shunt: null pointer")
899 )
900 }
901 else
902 {
903 struct bare_shunt *p = *pp;
904
905 *pp = p->next;
906 DBG_bare_shunt("delete", p);
907 pfree(p->why);
908 pfree(p);
909 }
910 }
911
912 void
913 show_shunt_status(void)
914 {
915 struct bare_shunt *bs;
916
917 for (bs = bare_shunts; bs != NULL; bs = bs->next)
918 {
919 /* Print interesting fields. Ignore count and last_active. */
920
921 int ourport = ntohs(portof(&bs->ours.addr));
922 int hisport = ntohs(portof(&bs->his.addr));
923 char ourst[SUBNETTOT_BUF];
924 char hist[SUBNETTOT_BUF];
925 char sat[SATOT_BUF];
926 char prio[POLICY_PRIO_BUF];
927
928 subnettot(&(bs)->ours, 0, ourst, sizeof(ourst));
929 subnettot(&(bs)->his, 0, hist, sizeof(hist));
930 satot(&(bs)->said, 0, sat, sizeof(sat));
931 fmt_policy_prio(bs->policy_prio, prio);
932
933 whack_log(RC_COMMENT, "%s:%d -> %s:%d => %s:%d %s %s"
934 , ourst, ourport, hist, hisport, sat, bs->transport_proto
935 , prio, bs->why);
936 }
937 }
938
939 /* Setup an IPsec route entry.
940 * op is one of the ERO_* operators.
941 */
942
943 static bool
944 raw_eroute(const ip_address *this_host
945 , const ip_subnet *this_client
946 , const ip_address *that_host
947 , const ip_subnet *that_client
948 , ipsec_spi_t spi
949 , unsigned int proto
950 , unsigned int satype
951 , unsigned int transport_proto
952 , const struct pfkey_proto_info *proto_info
953 , time_t use_lifetime
954 , unsigned int op
955 , const char *opname USED_BY_DEBUG)
956 {
957 char text_said[SATOT_BUF];
958
959 set_text_said(text_said, that_host, spi, proto);
960
961 DBG(DBG_CONTROL | DBG_KLIPS,
962 {
963 int sport = ntohs(portof(&this_client->addr));
964 int dport = ntohs(portof(&that_client->addr));
965 char mybuf[SUBNETTOT_BUF];
966 char peerbuf[SUBNETTOT_BUF];
967
968 subnettot(this_client, 0, mybuf, sizeof(mybuf));
969 subnettot(that_client, 0, peerbuf, sizeof(peerbuf));
970 DBG_log("%s eroute %s:%d -> %s:%d => %s:%d"
971 , opname, mybuf, sport, peerbuf, dport
972 , text_said, transport_proto);
973 });
974
975 return kernel_ops->raw_eroute(this_host, this_client
976 , that_host, that_client, spi, satype, transport_proto, proto_info
977 , use_lifetime, op, text_said);
978 }
979
980 /* test to see if %hold remains */
981 bool
982 has_bare_hold(const ip_address *src, const ip_address *dst, int transport_proto)
983 {
984 ip_subnet this_client, that_client;
985 struct bare_shunt **bspp;
986
987 passert(addrtypeof(src) == addrtypeof(dst));
988 happy(addrtosubnet(src, &this_client));
989 happy(addrtosubnet(dst, &that_client));
990 bspp = bare_shunt_ptr(&this_client, &that_client, transport_proto);
991 return bspp != NULL
992 && (*bspp)->said.proto == SA_INT && (*bspp)->said.spi == htonl(SPI_HOLD);
993 }
994
995
996 /* Replace (or delete) a shunt that is in the bare_shunts table.
997 * Issues the PF_KEY commands and updates the bare_shunts table.
998 */
999 bool
1000 replace_bare_shunt(const ip_address *src, const ip_address *dst
1001 , policy_prio_t policy_prio
1002 , ipsec_spi_t shunt_spi /* in host order! */
1003 , bool repl /* if TRUE, replace; if FALSE, delete */
1004 , unsigned int transport_proto
1005 , const char *why)
1006 {
1007 ip_subnet this_client, that_client;
1008 ip_subnet this_broad_client, that_broad_client;
1009 const ip_address *null_host = aftoinfo(addrtypeof(src))->any;
1010
1011 passert(addrtypeof(src) == addrtypeof(dst));
1012 happy(addrtosubnet(src, &this_client));
1013 happy(addrtosubnet(dst, &that_client));
1014 this_broad_client = this_client;
1015 that_broad_client = that_client;
1016 setportof(0, &this_broad_client.addr);
1017 setportof(0, &that_broad_client.addr);
1018
1019 if (repl)
1020 {
1021 struct bare_shunt **bs_pp = bare_shunt_ptr(&this_broad_client
1022 , &that_broad_client, 0);
1023
1024 /* is there already a broad host-to-host bare shunt? */
1025 if (bs_pp == NULL)
1026 {
1027 if (raw_eroute(null_host, &this_broad_client, null_host, &that_broad_client
1028 , htonl(shunt_spi), SA_INT, SADB_X_SATYPE_INT
1029 , 0, null_proto_info
1030 , SHUNT_PATIENCE, ERO_ADD, why))
1031 {
1032 struct bare_shunt *bs = alloc_thing(struct bare_shunt, "bare shunt");
1033
1034 bs->ours = this_broad_client;
1035 bs->his = that_broad_client;
1036 bs->transport_proto = 0;
1037 bs->said.proto = SA_INT;
1038 bs->why = clone_str(why, "bare shunt story");
1039 bs->policy_prio = policy_prio;
1040 bs->said.spi = htonl(shunt_spi);
1041 bs->said.dst = *null_host;
1042 bs->count = 0;
1043 bs->last_activity = now();
1044 bs->next = bare_shunts;
1045 bare_shunts = bs;
1046 DBG_bare_shunt("add", bs);
1047 }
1048 }
1049 shunt_spi = SPI_HOLD;
1050 }
1051
1052 if (raw_eroute(null_host, &this_client, null_host, &that_client
1053 , htonl(shunt_spi), SA_INT, SADB_X_SATYPE_INT
1054 , transport_proto, null_proto_info
1055 , SHUNT_PATIENCE, ERO_DELETE, why))
1056 {
1057 struct bare_shunt **bs_pp = bare_shunt_ptr(&this_client, &that_client
1058 , transport_proto);
1059
1060 /* delete bare eroute */
1061 free_bare_shunt(bs_pp);
1062 return TRUE;
1063 }
1064 else
1065 {
1066 return FALSE;
1067 }
1068 }
1069
1070 static bool
1071 eroute_connection(struct spd_route *sr
1072 , ipsec_spi_t spi, unsigned int proto, unsigned int satype
1073 , const struct pfkey_proto_info *proto_info
1074 , unsigned int op, const char *opname)
1075 {
1076 const ip_address *peer = &sr->that.host_addr;
1077 char buf2[256];
1078
1079 snprintf(buf2, sizeof(buf2)
1080 , "eroute_connection %s", opname);
1081
1082 if (proto == SA_INT)
1083 peer = aftoinfo(addrtypeof(peer))->any;
1084
1085 return raw_eroute(&sr->this.host_addr, &sr->this.client
1086 , peer
1087 , &sr->that.client
1088 , spi, proto, satype
1089 , sr->this.protocol, proto_info, 0, op, buf2);
1090 }
1091
1092 /* assign a bare hold to a connection */
1093
1094 bool
1095 assign_hold(struct connection *c USED_BY_DEBUG
1096 , struct spd_route *sr
1097 , int transport_proto
1098 , const ip_address *src, const ip_address *dst)
1099 {
1100 /* either the automatically installed %hold eroute is broad enough
1101 * or we try to add a broader one and delete the automatic one.
1102 * Beware: this %hold might be already handled, but still squeak
1103 * through because of a race.
1104 */
1105 enum routing_t ro = sr->routing /* routing, old */
1106 , rn = ro; /* routing, new */
1107
1108 passert(LHAS(LELEM(CK_PERMANENT) | LELEM(CK_INSTANCE), c->kind));
1109 /* figure out what routing should become */
1110 switch (ro)
1111 {
1112 case RT_UNROUTED:
1113 rn = RT_UNROUTED_HOLD;
1114 break;
1115 case RT_ROUTED_PROSPECTIVE:
1116 rn = RT_ROUTED_HOLD;
1117 break;
1118 default:
1119 /* no change: this %hold is old news and should just be deleted */
1120 break;
1121 }
1122
1123 /* we need a broad %hold, not the narrow one.
1124 * First we ensure that there is a broad %hold.
1125 * There may already be one (race condition): no need to create one.
1126 * There may already be a %trap: replace it.
1127 * There may not be any broad eroute: add %hold.
1128 * Once the broad %hold is in place, delete the narrow one.
1129 */
1130 if (rn != ro)
1131 {
1132 if (erouted(ro)
1133 ? !eroute_connection(sr, htonl(SPI_HOLD), SA_INT, SADB_X_SATYPE_INT
1134 , null_proto_info
1135 , ERO_REPLACE, "replace %trap with broad %hold")
1136 : !eroute_connection(sr, htonl(SPI_HOLD), SA_INT, SADB_X_SATYPE_INT
1137 , null_proto_info
1138 , ERO_ADD, "add broad %hold"))
1139 {
1140 return FALSE;
1141 }
1142 }
1143 if (!replace_bare_shunt(src, dst, BOTTOM_PRIO, SPI_HOLD, FALSE
1144 , transport_proto, "delete narrow %hold"))
1145 {
1146 return FALSE;
1147 }
1148 sr->routing = rn;
1149 return TRUE;
1150 }
1151
1152 /* install or remove eroute for SA Group */
1153 static bool
1154 sag_eroute(struct state *st, struct spd_route *sr
1155 , unsigned op, const char *opname)
1156 {
1157 u_int inner_proto = 0;
1158 u_int inner_satype = 0;
1159 ipsec_spi_t inner_spi = 0;
1160 struct pfkey_proto_info proto_info[4];
1161 int i;
1162 bool tunnel;
1163
1164 /* figure out the SPI and protocol (in two forms)
1165 * for the innermost transformation.
1166 */
1167
1168 i = sizeof(proto_info) / sizeof(proto_info[0]) - 1;
1169 proto_info[i].proto = 0;
1170 tunnel = FALSE;
1171
1172 if (st->st_ah.present)
1173 {
1174 inner_spi = st->st_ah.attrs.spi;
1175 inner_proto = SA_AH;
1176 inner_satype = SADB_SATYPE_AH;
1177
1178 i--;
1179 proto_info[i].proto = IPPROTO_AH;
1180 proto_info[i].encapsulation = st->st_ah.attrs.encapsulation;
1181 tunnel |= proto_info[i].encapsulation == ENCAPSULATION_MODE_TUNNEL;
1182 proto_info[i].reqid = sr->reqid;
1183 }
1184
1185 if (st->st_esp.present)
1186 {
1187 inner_spi = st->st_esp.attrs.spi;
1188 inner_proto = SA_ESP;
1189 inner_satype = SADB_SATYPE_ESP;
1190
1191 i--;
1192 proto_info[i].proto = IPPROTO_ESP;
1193 proto_info[i].encapsulation = st->st_esp.attrs.encapsulation;
1194 tunnel |= proto_info[i].encapsulation == ENCAPSULATION_MODE_TUNNEL;
1195 proto_info[i].reqid = sr->reqid + 1;
1196 }
1197
1198 if (st->st_ipcomp.present)
1199 {
1200 inner_spi = st->st_ipcomp.attrs.spi;
1201 inner_proto = SA_COMP;
1202 inner_satype = SADB_X_SATYPE_COMP;
1203
1204 i--;
1205 proto_info[i].proto = IPPROTO_COMP;
1206 proto_info[i].encapsulation = st->st_ipcomp.attrs.encapsulation;
1207 tunnel |= proto_info[i].encapsulation == ENCAPSULATION_MODE_TUNNEL;
1208 proto_info[i].reqid = sr->reqid + 2;
1209 }
1210
1211 if (i == sizeof(proto_info) / sizeof(proto_info[0]) - 1)
1212 {
1213 impossible(); /* no transform at all! */
1214 }
1215
1216 if (tunnel)
1217 {
1218 int j;
1219
1220 inner_spi = st->st_tunnel_out_spi;
1221 inner_proto = SA_IPIP;
1222 inner_satype = SADB_X_SATYPE_IPIP;
1223
1224 proto_info[i].encapsulation = ENCAPSULATION_MODE_TUNNEL;
1225 for (j = i + 1; proto_info[j].proto; j++)
1226 {
1227 proto_info[j].encapsulation = ENCAPSULATION_MODE_TRANSPORT;
1228 }
1229 }
1230
1231 return eroute_connection(sr
1232 , inner_spi, inner_proto, inner_satype, proto_info + i
1233 , op, opname);
1234 }
1235
1236 /* compute a (host-order!) SPI to implement the policy in connection c */
1237 ipsec_spi_t
1238 shunt_policy_spi(struct connection *c, bool prospective)
1239 {
1240 /* note: these are in host order :-( */
1241 static const ipsec_spi_t shunt_spi[] =
1242 {
1243 SPI_TRAP, /* --initiateontraffic */
1244 SPI_PASS, /* --pass */
1245 SPI_DROP, /* --drop */
1246 SPI_REJECT, /* --reject */
1247 };
1248
1249 static const ipsec_spi_t fail_spi[] =
1250 {
1251 0, /* --none*/
1252 SPI_PASS, /* --failpass */
1253 SPI_DROP, /* --faildrop */
1254 SPI_REJECT, /* --failreject */
1255 };
1256
1257 return prospective
1258 ? shunt_spi[(c->policy & POLICY_SHUNT_MASK) >> POLICY_SHUNT_SHIFT]
1259 : fail_spi[(c->policy & POLICY_FAIL_MASK) >> POLICY_FAIL_SHIFT];
1260 }
1261
1262 /* Add/replace/delete a shunt eroute.
1263 * Such an eroute determines the fate of packets without the use
1264 * of any SAs. These are defaults, in effect.
1265 * If a negotiation has not been attempted, use %trap.
1266 * If negotiation has failed, the choice between %trap/%pass/%drop/%reject
1267 * is specified in the policy of connection c.
1268 */
1269 static bool
1270 shunt_eroute(struct connection *c
1271 , struct spd_route *sr
1272 , enum routing_t rt_kind
1273 , unsigned int op, const char *opname)
1274 {
1275 /* We are constructing a special SAID for the eroute.
1276 * The destination doesn't seem to matter, but the family does.
1277 * The protocol is SA_INT -- mark this as shunt.
1278 * The satype has no meaning, but is required for PF_KEY header!
1279 * The SPI signifies the kind of shunt.
1280 */
1281 ipsec_spi_t spi = shunt_policy_spi(c, rt_kind == RT_ROUTED_PROSPECTIVE);
1282 bool ok;
1283
1284 if (spi == 0)
1285 {
1286 /* we're supposed to end up with no eroute: rejig op and opname */
1287 switch (op)
1288 {
1289 case ERO_REPLACE:
1290 /* replace with nothing == delete */
1291 op = ERO_DELETE;
1292 opname = "delete";
1293 break;
1294 case ERO_ADD:
1295 /* add nothing == do nothing */
1296 return TRUE;
1297 case ERO_DELETE:
1298 /* delete remains delete */
1299 break;
1300 default:
1301 bad_case(op);
1302 }
1303 }
1304 if (sr->routing == RT_ROUTED_ECLIPSED && c->kind == CK_TEMPLATE)
1305 {
1306 /* We think that we have an eroute, but we don't.
1307 * Adjust the request and account for eclipses.
1308 */
1309 passert(eclipsable(sr));
1310 switch (op)
1311 {
1312 case ERO_REPLACE:
1313 /* really an add */
1314 op = ERO_ADD;
1315 opname = "replace eclipsed";
1316 eclipse_count--;
1317 break;
1318 case ERO_DELETE:
1319 /* delete unnecessary: we don't actually have an eroute */
1320 eclipse_count--;
1321 return TRUE;
1322 case ERO_ADD:
1323 default:
1324 bad_case(op);
1325 }
1326 }
1327 else if (eclipse_count > 0 && op == ERO_DELETE && eclipsable(sr))
1328 {
1329 /* maybe we are uneclipsing something */
1330 struct spd_route *esr;
1331 struct connection *ue = eclipsed(c, &esr);
1332
1333 if (ue != NULL)
1334 {
1335 esr->routing = RT_ROUTED_PROSPECTIVE;
1336 return shunt_eroute(ue, esr
1337 , RT_ROUTED_PROSPECTIVE, ERO_REPLACE, "restoring eclipsed");
1338 }
1339 }
1340
1341 ok = TRUE;
1342 if (kernel_ops->inbound_eroute)
1343 {
1344 ok = raw_eroute(&c->spd.that.host_addr, &c->spd.that.client
1345 , &c->spd.this.host_addr, &c->spd.this.client
1346 , htonl(spi), SA_INT, SADB_X_SATYPE_INT
1347 , 0, null_proto_info, 0
1348 , op | (SADB_X_SAFLAGS_INFLOW << ERO_FLAG_SHIFT), opname);
1349 }
1350 return eroute_connection(sr, htonl(spi), SA_INT, SADB_X_SATYPE_INT
1351 , null_proto_info, op, opname) && ok;
1352 }
1353
1354
1355 /*
1356 * This is only called when s is a likely SAID with trailing protocol i.e.
1357 * it has the form :-
1358 *
1359 * %<keyword>:p
1360 * <ip-proto><spi>@a.b.c.d:p
1361 *
1362 * The task here is to remove the ":p" part so that the rest can be read
1363 * by another routine.
1364 */
1365 static const char *
1366 read_proto(const char * s, size_t * len, int * transport_proto)
1367 {
1368 const char * p;
1369 const char * ugh;
1370 unsigned long proto;
1371 size_t l;
1372
1373 l = *len;
1374 p = memchr(s, ':', l);
1375 if (p == 0) {
1376 *transport_proto = 0;
1377 return 0;
1378 }
1379 ugh = ttoul(p+1, l-((p-s)+1), 10, &proto);
1380 if (ugh != 0)
1381 return ugh;
1382 if (proto > 65535)
1383 return "protocol number is too large, legal range is 0-65535";
1384 *len = p-s;
1385 *transport_proto = proto;
1386 return 0;
1387 }
1388
1389
1390 /* scan /proc/net/ipsec_eroute every once in a while, looking for:
1391 *
1392 * - %hold shunts of which Pluto isn't aware. This situation could
1393 * be caused by lost ACQUIRE messages. When found, they will
1394 * added to orphan_holds. This in turn will lead to Opportunistic
1395 * initiation.
1396 *
1397 * - other kinds of shunts that haven't been used recently. These will be
1398 * deleted. They represent OE failures.
1399 *
1400 * - recording recent uses of tunnel eroutes so that rekeying decisions
1401 * can be made for OE connections.
1402 *
1403 * Here are some sample lines:
1404 * 10 10.3.2.1.0/24 -> 0.0.0.0/0 => %trap
1405 * 259 10.3.2.1.115/32 -> 10.19.75.161/32 => tun0x1002@10.19.75.145
1406 * 71 10.44.73.97/32 -> 0.0.0.0/0 => %trap
1407 * 4119 10.44.73.97/32 -> 10.114.121.41/32 => %pass
1408 * Newer versions of KLIPS start each line with a 32-bit packet count.
1409 * If available, the count is used to detect whether a %pass shunt is in use.
1410 *
1411 * NOTE: execution time is quadratic in the number of eroutes since the
1412 * searching for each is sequential. If this becomes a problem, faster
1413 * searches could be implemented (hash or radix tree, for example).
1414 */
1415 void
1416 scan_proc_shunts(void)
1417 {
1418 static const char procname[] = "/proc/net/ipsec_eroute";
1419 FILE *f;
1420 time_t nw = now();
1421 int lino;
1422 struct eroute_info *expired = NULL;
1423
1424 event_schedule(EVENT_SHUNT_SCAN, SHUNT_SCAN_INTERVAL, NULL);
1425
1426 DBG(DBG_CONTROL,
1427 DBG_log("scanning for shunt eroutes")
1428 )
1429
1430 /* free any leftover entries: they will be refreshed if still current */
1431 while (orphaned_holds != NULL)
1432 {
1433 struct eroute_info *p = orphaned_holds;
1434
1435 orphaned_holds = p->next;
1436 pfree(orphaned_holds);
1437 }
1438
1439 /* decode the /proc file. Don't do anything strenuous to it
1440 * (certainly no PF_KEY stuff) to minimize the chance that it
1441 * might change underfoot.
1442 */
1443
1444 f = fopen(procname, "r");
1445 if (f == NULL)
1446 return;
1447
1448 /* for each line... */
1449 for (lino = 1; ; lino++)
1450 {
1451 unsigned char buf[1024]; /* should be big enough */
1452 chunk_t field[10]; /* 10 is loose upper bound */
1453 chunk_t *ff = NULL; /* fixed fields (excluding optional count) */
1454 int fi;
1455 struct eroute_info eri;
1456 char *cp;
1457 err_t context = ""
1458 , ugh = NULL;
1459
1460 cp = fgets(buf, sizeof(buf), f);
1461 if (cp == NULL)
1462 break;
1463
1464 /* break out each field
1465 * Note: if there are too many fields, just stop;
1466 * it will be diagnosed a little later.
1467 */
1468 for (fi = 0; fi < (int)elemsof(field); fi++)
1469 {
1470 static const char sep[] = " \t\n"; /* field-separating whitespace */
1471 size_t w;
1472
1473 cp += strspn(cp, sep); /* find start of field */
1474 w = strcspn(cp, sep); /* find width of field */
1475 setchunk(field[fi], cp, w);
1476 cp += w;
1477 if (w == 0)
1478 break;
1479 }
1480
1481 /* This odd do-hickey is to share error reporting code.
1482 * A break will get to that common code. The setting
1483 * of "ugh" and "context" parameterize it.
1484 */
1485 do {
1486 /* Old entries have no packet count; new ones do.
1487 * check if things are as they should be.
1488 */
1489 if (fi == 5)
1490 ff = &field[0]; /* old form, with no count */
1491 else if (fi == 6)
1492 ff = &field[1]; /* new form, with count */
1493 else
1494 {
1495 ugh = "has wrong number of fields";
1496 break;
1497 }
1498
1499 if (ff[1].len != 2
1500 || strncmp(ff[1].ptr, "->", 2) != 0
1501 || ff[3].len != 2
1502 || strncmp(ff[3].ptr, "=>", 2) != 0)
1503 {
1504 ugh = "is missing -> or =>";
1505 break;
1506 }
1507
1508 /* actually digest fields of interest */
1509
1510 /* packet count */
1511
1512 eri.count = 0;
1513 if (ff != field)
1514 {
1515 context = "count field is malformed: ";
1516 ugh = ttoul(field[0].ptr, field[0].len, 10, &eri.count);
1517 if (ugh != NULL)
1518 break;
1519 }
1520
1521 /* our client */
1522
1523 context = "source subnet field malformed: ";
1524 ugh = ttosubnet(ff[0].ptr, ff[0].len, AF_INET, &eri.ours);
1525 if (ugh != NULL)
1526 break;
1527
1528 /* his client */
1529
1530 context = "destination subnet field malformed: ";
1531 ugh = ttosubnet(ff[2].ptr, ff[2].len, AF_INET, &eri.his);
1532 if (ugh != NULL)
1533 break;
1534
1535 /* SAID */
1536
1537 context = "SA ID field malformed: ";
1538 ugh = read_proto(ff[4].ptr, &ff[4].len, &eri.transport_proto);
1539 if (ugh != NULL)
1540 break;
1541 ugh = ttosa(ff[4].ptr, ff[4].len, &eri.said);
1542 } while (FALSE);
1543
1544 if (ugh != NULL)
1545 {
1546 plog("INTERNAL ERROR: %s line %d %s%s"
1547 , procname, lino, context, ugh);
1548 continue; /* ignore rest of line */
1549 }
1550
1551 /* Now we have decoded eroute, let's consider it.
1552 * For shunt eroutes:
1553 *
1554 * %hold: if not known, add to orphaned_holds list for initiation
1555 * because ACQUIRE might have been lost.
1556 *
1557 * %pass, %drop, %reject: determine if idle; if so, blast it away.
1558 * Can occur bare (if DNS provided insufficient information)
1559 * or with a connection (failure context).
1560 * Could even be installed by ipsec manual.
1561 *
1562 * %trap: always welcome.
1563 *
1564 * For other eroutes: find state and record count change
1565 */
1566 if (eri.said.proto == SA_INT)
1567 {
1568 /* shunt eroute */
1569 switch (ntohl(eri.said.spi))
1570 {
1571 case SPI_HOLD:
1572 if (bare_shunt_ptr(&eri.ours, &eri.his, eri.transport_proto) == NULL
1573 && shunt_owner(&eri.ours, &eri.his) == NULL)
1574 {
1575 int ourport = ntohs(portof(&eri.ours.addr));
1576 int hisport = ntohs(portof(&eri.his.addr));
1577 char ourst[SUBNETTOT_BUF];
1578 char hist[SUBNETTOT_BUF];
1579 char sat[SATOT_BUF];
1580
1581 subnettot(&eri.ours, 0, ourst, sizeof(ourst));
1582 subnettot(&eri.his, 0, hist, sizeof(hist));
1583 satot(&eri.said, 0, sat, sizeof(sat));
1584
1585 DBG(DBG_CONTROL,
1586 DBG_log("add orphaned shunt %s:%d -> %s:%d => %s:%d"
1587 , ourst, ourport, hist, hisport, sat, eri.transport_proto)
1588 )
1589 eri.next = orphaned_holds;
1590 orphaned_holds = clone_thing(eri, "orphaned %hold");
1591 }
1592 break;
1593
1594 case SPI_PASS:
1595 case SPI_DROP:
1596 case SPI_REJECT:
1597 /* nothing sensible to do if we don't have counts */
1598 if (ff != field)
1599 {
1600 struct bare_shunt **bs_pp
1601 = bare_shunt_ptr(&eri.ours, &eri.his, eri.transport_proto);
1602
1603 if (bs_pp != NULL)
1604 {
1605 struct bare_shunt *bs = *bs_pp;
1606
1607 if (eri.count != bs->count)
1608 {
1609 bs->count = eri.count;
1610 bs->last_activity = nw;
1611 }
1612 else if (nw - bs->last_activity > SHUNT_PATIENCE)
1613 {
1614 eri.next = expired;
1615 expired = clone_thing(eri, "expired %pass");
1616 }
1617 }
1618 }
1619 break;
1620
1621 case SPI_TRAP:
1622 break;
1623
1624 default:
1625 bad_case(ntohl(eri.said.spi));
1626 }
1627 }
1628 else
1629 {
1630 /* regular (non-shunt) eroute */
1631 state_eroute_usage(&eri.ours, &eri.his, eri.count, nw);
1632 }
1633 } /* for each line */
1634 fclose(f);
1635
1636 /* Now that we've finished processing the /proc file,
1637 * it is safe to delete the expired %pass shunts.
1638 */
1639 while (expired != NULL)
1640 {
1641 struct eroute_info *p = expired;
1642 ip_address src, dst;
1643
1644 networkof(&p->ours, &src);
1645 networkof(&p->his, &dst);
1646 (void) replace_bare_shunt(&src, &dst
1647 , BOTTOM_PRIO /* not used because we are deleting. This value is a filler */
1648 , SPI_PASS /* not used because we are deleting. This value is a filler */
1649 , FALSE, p->transport_proto, "delete expired bare shunts");
1650 expired = p->next;
1651 pfree(p);
1652 }
1653 }
1654
1655 static bool
1656 del_spi(ipsec_spi_t spi, int proto
1657 , const ip_address *src, const ip_address *dest)
1658 {
1659 char text_said[SATOT_BUF];
1660 struct kernel_sa sa;
1661
1662 set_text_said(text_said, dest, spi, proto);
1663
1664 DBG(DBG_KLIPS, DBG_log("delete %s", text_said));
1665
1666 memset(&sa, 0, sizeof(sa));
1667 sa.spi = spi;
1668 sa.proto = proto;
1669 sa.src = src;
1670 sa.dst = dest;
1671 sa.text_said = text_said;
1672
1673 return kernel_ops->del_sa(&sa);
1674 }
1675
1676 /* Setup a pair of SAs. Code taken from setsa.c and spigrp.c, in
1677 * ipsec-0.5.
1678 */
1679
1680 static bool
1681 setup_half_ipsec_sa(struct state *st, bool inbound)
1682 {
1683 /* Build an inbound or outbound SA */
1684
1685 struct connection *c = st->st_connection;
1686 ip_subnet src, dst;
1687 ip_subnet src_client, dst_client;
1688 ipsec_spi_t inner_spi = 0;
1689 u_int proto = 0;
1690 u_int satype = SADB_SATYPE_UNSPEC;
1691 bool replace;
1692
1693 /* SPIs, saved for spigrouping or undoing, if necessary */
1694 struct kernel_sa
1695 said[EM_MAXRELSPIS],
1696 *said_next = said;
1697
1698 char text_said[SATOT_BUF];
1699 int encapsulation;
1700
1701 replace = inbound && (kernel_ops->get_spi != NULL);
1702
1703 src.maskbits = 0;
1704 dst.maskbits = 0;
1705
1706 if (inbound)
1707 {
1708 src.addr = c->spd.that.host_addr;
1709 dst.addr = c->spd.this.host_addr;
1710 src_client = c->spd.that.client;
1711 dst_client = c->spd.this.client;
1712 }
1713 else
1714 {
1715 src.addr = c->spd.this.host_addr,
1716 dst.addr = c->spd.that.host_addr;
1717 src_client = c->spd.this.client;
1718 dst_client = c->spd.that.client;
1719 }
1720
1721 encapsulation = ENCAPSULATION_MODE_TRANSPORT;
1722 if (st->st_ah.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL
1723 || st->st_esp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL
1724 || st->st_ipcomp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1725 {
1726 encapsulation = ENCAPSULATION_MODE_TUNNEL;
1727 }
1728
1729 memset(said, 0, sizeof(said));
1730
1731 /* If we are tunnelling, set up IP in IP pseudo SA */
1732
1733 if (kernel_ops->inbound_eroute)
1734 {
1735 inner_spi = 256;
1736 proto = SA_IPIP;
1737 satype = SADB_SATYPE_UNSPEC;
1738 }
1739 else if (encapsulation == ENCAPSULATION_MODE_TUNNEL)
1740 {
1741 /* XXX hack alert -- we SHOULD NOT HAVE TO HAVE A DIFFERENT SPI
1742 * XXX FOR IP-in-IP ENCAPSULATION!
1743 */
1744
1745 ipsec_spi_t ipip_spi;
1746
1747 /* Allocate an SPI for the tunnel.
1748 * Since our peer will never see this,
1749 * and it comes from its own number space,
1750 * it is purely a local implementation wart.
1751 */
1752 {
1753 static ipsec_spi_t last_tunnel_spi = IPSEC_DOI_SPI_OUR_MIN;
1754
1755 ipip_spi = htonl(++last_tunnel_spi);
1756 if (inbound)
1757 st->st_tunnel_in_spi = ipip_spi;
1758 else
1759 st->st_tunnel_out_spi = ipip_spi;
1760 }
1761
1762 set_text_said(text_said
1763 , &c->spd.that.host_addr, ipip_spi, SA_IPIP);
1764
1765 said_next->src = &src.addr;
1766 said_next->dst = &dst.addr;
1767 said_next->src_client = &src_client;
1768 said_next->dst_client = &dst_client;
1769 said_next->spi = ipip_spi;
1770 said_next->satype = SADB_X_SATYPE_IPIP;
1771 said_next->text_said = text_said;
1772
1773 if (!kernel_ops->add_sa(said_next, replace))
1774 goto fail;
1775
1776 said_next++;
1777
1778 inner_spi = ipip_spi;
1779 proto = SA_IPIP;
1780 satype = SADB_X_SATYPE_IPIP;
1781 }
1782
1783 /* set up IPCOMP SA, if any */
1784
1785 if (st->st_ipcomp.present)
1786 {
1787 ipsec_spi_t ipcomp_spi = inbound? st->st_ipcomp.our_spi : st->st_ipcomp.attrs.spi;
1788 unsigned compalg;
1789
1790 switch (st->st_ipcomp.attrs.transid)
1791 {
1792 case IPCOMP_DEFLATE:
1793 compalg = SADB_X_CALG_DEFLATE;
1794 break;
1795
1796 default:
1797 loglog(RC_LOG_SERIOUS, "IPCOMP transform %s not implemented"
1798 , enum_name(&ipcomp_transformid_names, st->st_ipcomp.attrs.transid));
1799 goto fail;
1800 }
1801
1802 set_text_said(text_said, &dst.addr, ipcomp_spi, SA_COMP);
1803
1804 said_next->src = &src.addr;
1805 said_next->dst = &dst.addr;
1806 said_next->src_client = &src_client;
1807 said_next->dst_client = &dst_client;
1808 said_next->spi = ipcomp_spi;
1809 said_next->satype = SADB_X_SATYPE_COMP;
1810 said_next->compalg = compalg;
1811 said_next->encapsulation = encapsulation;
1812 said_next->reqid = c->spd.reqid + 2;
1813 said_next->text_said = text_said;
1814
1815 if (!kernel_ops->add_sa(said_next, replace))
1816 goto fail;
1817
1818 said_next++;
1819
1820 encapsulation = ENCAPSULATION_MODE_TRANSPORT;
1821 }
1822
1823 /* set up ESP SA, if any */
1824
1825 if (st->st_esp.present)
1826 {
1827 ipsec_spi_t esp_spi = inbound? st->st_esp.our_spi : st->st_esp.attrs.spi;
1828 u_char *esp_dst_keymat = inbound? st->st_esp.our_keymat : st->st_esp.peer_keymat;
1829 const struct esp_info *ei;
1830 u_int16_t key_len;
1831
1832 static const struct esp_info esp_info[] = {
1833 { ESP_NULL, AUTH_ALGORITHM_HMAC_MD5,
1834 0, HMAC_MD5_KEY_LEN,
1835 SADB_EALG_NULL, SADB_AALG_MD5_HMAC },
1836 { ESP_NULL, AUTH_ALGORITHM_HMAC_SHA1,
1837 0, HMAC_SHA1_KEY_LEN,
1838 SADB_EALG_NULL, SADB_AALG_SHA1_HMAC },
1839
1840 { ESP_DES, AUTH_ALGORITHM_NONE,
1841 DES_CBC_BLOCK_SIZE, 0,
1842 SADB_EALG_DES_CBC, SADB_AALG_NONE },
1843 { ESP_DES, AUTH_ALGORITHM_HMAC_MD5,
1844 DES_CBC_BLOCK_SIZE, HMAC_MD5_KEY_LEN,
1845 SADB_EALG_DES_CBC, SADB_AALG_MD5_HMAC },
1846 { ESP_DES, AUTH_ALGORITHM_HMAC_SHA1,
1847 DES_CBC_BLOCK_SIZE,
1848 HMAC_SHA1_KEY_LEN, SADB_EALG_DES_CBC, SADB_AALG_SHA1_HMAC },
1849
1850 { ESP_3DES, AUTH_ALGORITHM_NONE,
1851 DES_CBC_BLOCK_SIZE * 3, 0,
1852 SADB_EALG_3DES_CBC, SADB_AALG_NONE },
1853 { ESP_3DES, AUTH_ALGORITHM_HMAC_MD5,
1854 DES_CBC_BLOCK_SIZE * 3, HMAC_MD5_KEY_LEN,
1855 SADB_EALG_3DES_CBC, SADB_AALG_MD5_HMAC },
1856 { ESP_3DES, AUTH_ALGORITHM_HMAC_SHA1,
1857 DES_CBC_BLOCK_SIZE * 3, HMAC_SHA1_KEY_LEN,
1858 SADB_EALG_3DES_CBC, SADB_AALG_SHA1_HMAC },
1859 };
1860
1861 #ifdef NAT_TRAVERSAL
1862 u_int8_t natt_type = 0;
1863 u_int16_t natt_sport = 0, natt_dport = 0;
1864 ip_address natt_oa;
1865
1866 if (st->nat_traversal & NAT_T_DETECTED) {
1867 natt_type = (st->nat_traversal & NAT_T_WITH_PORT_FLOATING) ?
1868 ESPINUDP_WITH_NON_ESP : ESPINUDP_WITH_NON_IKE;
1869 natt_sport = inbound? c->spd.that.host_port : c->spd.this.host_port;
1870 natt_dport = inbound? c->spd.this.host_port : c->spd.that.host_port;
1871 natt_oa = st->nat_oa;
1872 }
1873 #endif
1874
1875 for (ei = esp_info; ; ei++)
1876 {
1877 if (ei == &esp_info[elemsof(esp_info)])
1878 {
1879 /* Check for additional kernel alg */
1880 #ifndef NO_KERNEL_ALG
1881 if ((ei=kernel_alg_esp_info(st->st_esp.attrs.transid,
1882 st->st_esp.attrs.auth))!=NULL) {
1883 break;
1884 }
1885 #endif
1886
1887 /* note: enum_show may use a static buffer, so two
1888 * calls in one printf would be a mistake.
1889 * enum_name does the same job, without a static buffer,
1890 * assuming the name will be found.
1891 */
1892 loglog(RC_LOG_SERIOUS, "ESP transform %s / auth %s not implemented yet"
1893 , enum_name(&esp_transformid_names, st->st_esp.attrs.transid)
1894 , enum_name(&auth_alg_names, st->st_esp.attrs.auth));
1895 goto fail;
1896 }
1897
1898 if (st->st_esp.attrs.transid == ei->transid
1899 && st->st_esp.attrs.auth == ei->auth)
1900 break;
1901 }
1902
1903 key_len = st->st_esp.attrs.key_len/8;
1904 if (key_len) {
1905 /* XXX: must change to check valid _range_ key_len */
1906 if (key_len > ei->enckeylen) {
1907 loglog(RC_LOG_SERIOUS, "ESP transform %s passed key_len=%d > %d",
1908 enum_name(&esp_transformid_names, st->st_esp.attrs.transid),
1909 (int)key_len, (int)ei->enckeylen);
1910 goto fail;
1911 }
1912 } else {
1913 key_len = ei->enckeylen;
1914 }
1915 /* Grrrrr.... f*cking 7 bits jurassic algos */
1916
1917 /* 168 bits in kernel, need 192 bits for keymat_len */
1918 if (ei->transid == ESP_3DES && key_len == 21)
1919 key_len = 24;
1920
1921 /* 56 bits in kernel, need 64 bits for keymat_len */
1922 if (ei->transid == ESP_DES && key_len == 7)
1923 key_len = 8;
1924
1925 /* divide up keying material */
1926 /* passert(st->st_esp.keymat_len == ei->enckeylen + ei->authkeylen); */
1927 DBG(DBG_KLIPS|DBG_CONTROL|DBG_PARSING,
1928 if(st->st_esp.keymat_len != key_len + ei->authkeylen)
1929 DBG_log("keymat_len=%d key_len=%d authkeylen=%d",
1930 st->st_esp.keymat_len, (int)key_len, (int)ei->authkeylen);
1931 );
1932 passert(st->st_esp.keymat_len == key_len + ei->authkeylen);
1933
1934 set_text_said(text_said, &dst.addr, esp_spi, SA_ESP);
1935
1936 said_next->src = &src.addr;
1937 said_next->dst = &dst.addr;
1938 said_next->src_client = &src_client;
1939 said_next->dst_client = &dst_client;
1940 said_next->spi = esp_spi;
1941 said_next->satype = SADB_SATYPE_ESP;
1942 said_next->replay_window = (kernel_ops->type == KERNEL_TYPE_KLIPS) ? REPLAY_WINDOW : REPLAY_WINDOW_XFRM;
1943 said_next->authalg = ei->authalg;
1944 said_next->authkeylen = ei->authkeylen;
1945 /* said_next->authkey = esp_dst_keymat + ei->enckeylen; */
1946 said_next->authkey = esp_dst_keymat + key_len;
1947 said_next->encalg = ei->encryptalg;
1948 /* said_next->enckeylen = ei->enckeylen; */
1949 said_next->enckeylen = key_len;
1950 said_next->enckey = esp_dst_keymat;
1951 said_next->encapsulation = encapsulation;
1952 said_next->reqid = c->spd.reqid + 1;
1953 #ifdef NAT_TRAVERSAL
1954 said_next->natt_sport = natt_sport;
1955 said_next->natt_dport = natt_dport;
1956 said_next->transid = st->st_esp.attrs.transid;
1957 said_next->natt_type = natt_type;
1958 said_next->natt_oa = &natt_oa;
1959 #endif
1960 said_next->text_said = text_said;
1961
1962 if (!kernel_ops->add_sa(said_next, replace))
1963 goto fail;
1964
1965 said_next++;
1966
1967 encapsulation = ENCAPSULATION_MODE_TRANSPORT;
1968 }
1969
1970 /* set up AH SA, if any */
1971
1972 if (st->st_ah.present)
1973 {
1974 ipsec_spi_t ah_spi = inbound? st->st_ah.our_spi : st->st_ah.attrs.spi;
1975 u_char *ah_dst_keymat = inbound? st->st_ah.our_keymat : st->st_ah.peer_keymat;
1976
1977 unsigned char authalg;
1978
1979 switch (st->st_ah.attrs.auth)
1980 {
1981 case AUTH_ALGORITHM_HMAC_MD5:
1982 authalg = SADB_AALG_MD5_HMAC;
1983 break;
1984
1985 case AUTH_ALGORITHM_HMAC_SHA1:
1986 authalg = SADB_AALG_SHA1_HMAC;
1987 break;
1988
1989 default:
1990 loglog(RC_LOG_SERIOUS, "%s not implemented yet"
1991 , enum_show(&auth_alg_names, st->st_ah.attrs.auth));
1992 goto fail;
1993 }
1994
1995 set_text_said(text_said, &dst.addr, ah_spi, SA_AH);
1996
1997 said_next->src = &src.addr;
1998 said_next->dst = &dst.addr;
1999 said_next->src_client = &src_client;
2000 said_next->dst_client = &dst_client;
2001 said_next->spi = ah_spi;
2002 said_next->satype = SADB_SATYPE_AH;
2003 said_next->replay_window = (kernel_ops->type == KERNEL_TYPE_KLIPS) ? REPLAY_WINDOW : REPLAY_WINDOW_XFRM;
2004 said_next->authalg = authalg;
2005 said_next->authkeylen = st->st_ah.keymat_len;
2006 said_next->authkey = ah_dst_keymat;
2007 said_next->encapsulation = encapsulation;
2008 said_next->reqid = c->spd.reqid;
2009 said_next->text_said = text_said;
2010
2011 if (!kernel_ops->add_sa(said_next, replace))
2012 goto fail;
2013
2014 said_next++;
2015
2016 encapsulation = ENCAPSULATION_MODE_TRANSPORT;
2017 }
2018
2019 if (st->st_ah.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL
2020 || st->st_esp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL
2021 || st->st_ipcomp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
2022 {
2023 encapsulation = ENCAPSULATION_MODE_TUNNEL;
2024 }
2025
2026 if (kernel_ops->inbound_eroute ? c->spd.eroute_owner == SOS_NOBODY
2027 : encapsulation == ENCAPSULATION_MODE_TUNNEL)
2028 {
2029 /* If inbound, and policy does not specifie DISABLEARRIVALCHECK,
2030 * tell KLIPS to enforce the IP addresses appropriate for this tunnel.
2031 * Note reversed ends.
2032 * Not much to be done on failure.
2033 */
2034 if (inbound && (c->policy & POLICY_DISABLEARRIVALCHECK) == 0)
2035 {
2036 struct pfkey_proto_info proto_info[4];
2037 int i = 0;
2038
2039 if (st->st_ipcomp.present)
2040 {
2041 proto_info[i].proto = IPPROTO_COMP;
2042 proto_info[i].encapsulation = st->st_ipcomp.attrs.encapsulation;
2043 proto_info[i].reqid = c->spd.reqid + 2;
2044 i++;
2045 }
2046
2047 if (st->st_esp.present)
2048 {
2049 proto_info[i].proto = IPPROTO_ESP;
2050 proto_info[i].encapsulation = st->st_esp.attrs.encapsulation;
2051 proto_info[i].reqid = c->spd.reqid + 1;
2052 i++;
2053 }
2054
2055 if (st->st_ah.present)
2056 {
2057 proto_info[i].proto = IPPROTO_AH;
2058 proto_info[i].encapsulation = st->st_ah.attrs.encapsulation;
2059 proto_info[i].reqid = c->spd.reqid;
2060 i++;
2061 }
2062
2063 proto_info[i].proto = 0;
2064
2065 if (kernel_ops->inbound_eroute
2066 && encapsulation == ENCAPSULATION_MODE_TUNNEL)
2067 {
2068 proto_info[0].encapsulation = ENCAPSULATION_MODE_TUNNEL;
2069 for (i = 1; proto_info[i].proto; i++)
2070 {
2071 proto_info[i].encapsulation = ENCAPSULATION_MODE_TRANSPORT;
2072 }
2073 }
2074
2075 /* MCR - should be passed a spd_eroute structure here */
2076 (void) raw_eroute(&c->spd.that.host_addr, &c->spd.that.client
2077 , &c->spd.this.host_addr, &c->spd.this.client
2078 , inner_spi, proto, satype, c->spd.this.protocol
2079 , proto_info, 0
2080 , ERO_ADD_INBOUND, "add inbound");
2081 }
2082 }
2083
2084 /* If there are multiple SPIs, group them. */
2085
2086 if (kernel_ops->grp_sa && said_next > &said[1])
2087 {
2088 struct kernel_sa *s;
2089
2090 /* group SAs, two at a time, inner to outer (backwards in said[])
2091 * The grouping is by pairs. So if said[] contains ah esp ipip,
2092 * the grouping would be ipip:esp, esp:ah.
2093 */
2094 for (s = said; s < said_next-1; s++)
2095 {
2096 char
2097 text_said0[SATOT_BUF],
2098 text_said1[SATOT_BUF];
2099
2100 /* group s[1] and s[0], in that order */
2101
2102 set_text_said(text_said0, s[0].dst, s[0].spi, s[0].proto);
2103 set_text_said(text_said1, s[1].dst, s[1].spi, s[1].proto);
2104
2105 DBG(DBG_KLIPS, DBG_log("grouping %s and %s", text_said1, text_said0));
2106
2107 s[0].text_said = text_said0;
2108 s[1].text_said = text_said1;
2109
2110 if (!kernel_ops->grp_sa(s + 1, s))
2111 goto fail;
2112 }
2113 /* could update said, but it will not be used */
2114 }
2115
2116 return TRUE;
2117
2118 fail:
2119 {
2120 /* undo the done SPIs */
2121 while (said_next-- != said)
2122 (void) del_spi(said_next->spi, said_next->proto
2123 , &src.addr, said_next->dst);
2124 return FALSE;
2125 }
2126 }
2127
2128 /* teardown_ipsec_sa is a canibalized version of setup_ipsec_sa */
2129
2130 static bool
2131 teardown_half_ipsec_sa(struct state *st, bool inbound)
2132 {
2133 /* We need to delete AH, ESP, and IP in IP SPIs.
2134 * But if there is more than one, they have been grouped
2135 * so deleting any one will do. So we just delete the
2136 * first one found. It may or may not be the only one.
2137 */
2138 struct connection *c = st->st_connection;
2139 struct {
2140 unsigned proto;
2141 struct ipsec_proto_info *info;
2142 } protos[4];
2143 int i;
2144 bool result;
2145
2146 i = 0;
2147 if (kernel_ops->inbound_eroute && inbound
2148 && c->spd.eroute_owner == SOS_NOBODY)
2149 {
2150 (void) raw_eroute(&c->spd.that.host_addr, &c->spd.that.client
2151 , &c->spd.this.host_addr, &c->spd.this.client
2152 , 256, IPSEC_PROTO_ANY, SADB_SATYPE_UNSPEC, c->spd.this.protocol
2153 , null_proto_info, 0
2154 , ERO_DEL_INBOUND, "delete inbound");
2155 }
2156
2157 if (!kernel_ops->grp_sa)
2158 {
2159 if (st->st_ah.present)
2160 {
2161 protos[i].info = &st->st_ah;
2162 protos[i].proto = SA_AH;
2163 i++;
2164 }
2165
2166 if (st->st_esp.present)
2167 {
2168 protos[i].info = &st->st_esp;
2169 protos[i].proto = SA_ESP;
2170 i++;
2171 }
2172
2173 if (st->st_ipcomp.present)
2174 {
2175 protos[i].info = &st->st_ipcomp;
2176 protos[i].proto = SA_COMP;
2177 i++;
2178 }
2179 }
2180 else if (st->st_ah.present)
2181 {
2182 protos[i].info = &st->st_ah;
2183 protos[i].proto = SA_AH;
2184 i++;
2185 }
2186 else if (st->st_esp.present)
2187 {
2188 protos[i].info = &st->st_esp;
2189 protos[i].proto = SA_ESP;
2190 i++;
2191 }
2192 else
2193 {
2194 impossible(); /* neither AH nor ESP in outbound SA bundle! */
2195 }
2196 protos[i].proto = 0;
2197
2198 result = TRUE;
2199 for (i = 0; protos[i].proto; i++)
2200 {
2201 unsigned proto = protos[i].proto;
2202 ipsec_spi_t spi;
2203 const ip_address *src, *dst;
2204
2205 if (inbound)
2206 {
2207 spi = protos[i].info->our_spi;
2208 src = &c->spd.that.host_addr;
2209 dst = &c->spd.this.host_addr;
2210 }
2211 else
2212 {
2213 spi = protos[i].info->attrs.spi;
2214 src = &c->spd.this.host_addr;
2215 dst = &c->spd.that.host_addr;
2216 }
2217
2218 result &= del_spi(spi, proto, src, dst);
2219 }
2220 return result;
2221 }
2222
2223 /*
2224 * get information about a given sa
2225 */
2226 bool
2227 get_sa_info(struct state *st, bool inbound, u_int *bytes, time_t *use_time)
2228 {
2229 char text_said[SATOT_BUF];
2230 struct kernel_sa sa;
2231 struct connection *c = st->st_connection;
2232
2233 *use_time = UNDEFINED_TIME;
2234
2235 if (kernel_ops->get_sa == NULL || !st->st_esp.present)
2236 return FALSE;
2237
2238 memset(&sa, 0, sizeof(sa));
2239 sa.proto = SA_ESP;
2240
2241 if (inbound)
2242 {
2243 sa.src = &c->spd.that.host_addr;
2244 sa.dst = &c->spd.this.host_addr;
2245 sa.spi = st->st_esp.our_spi;
2246 }
2247 else
2248 {
2249 sa.src = &c->spd.this.host_addr;
2250 sa.dst = &c->spd.that.host_addr;
2251 sa.spi = st->st_esp.attrs.spi;
2252 }
2253 set_text_said(text_said, sa.dst, sa.spi, sa.proto);
2254
2255 sa.text_said = text_said;
2256
2257 DBG(DBG_KLIPS,
2258 DBG_log("get %s", text_said)
2259 )
2260 if (!kernel_ops->get_sa(&sa, bytes))
2261 return FALSE;
2262 DBG(DBG_KLIPS,
2263 DBG_log(" current: %d bytes", *bytes)
2264 )
2265
2266 if (st->st_serialno == c->spd.eroute_owner)
2267 {
2268 DBG(DBG_KLIPS,
2269 DBG_log("get %sbound policy with reqid %u"
2270 , inbound? "in":"out", (u_int)c->spd.reqid + 1)
2271 )
2272 sa.transport_proto = c->spd.this.protocol;
2273 sa.encapsulation = st->st_esp.attrs.encapsulation;
2274
2275 if (inbound)
2276 {
2277 sa.src_client = &c->spd.that.client;
2278 sa.dst_client = &c->spd.this.client;
2279 }
2280 else
2281 {
2282 sa.src_client = &c->spd.this.client;
2283 sa.dst_client = &c->spd.that.client;
2284 }
2285 if (!kernel_ops->get_policy(&sa, inbound, use_time))
2286 return FALSE;
2287 DBG(DBG_KLIPS,
2288 DBG_log(" use_time: %s", timetoa(use_time, FALSE))
2289 )
2290 }
2291 return TRUE;
2292 }
2293
2294 const struct kernel_ops *kernel_ops;
2295
2296 #endif /* KLIPS */
2297
2298 void
2299 init_kernel(void)
2300 {
2301 #ifdef KLIPS
2302
2303 if (no_klips)
2304 {
2305 kernel_ops = &noklips_kernel_ops;
2306 return;
2307 }
2308
2309 init_pfkey();
2310
2311 kernel_ops = &klips_kernel_ops;
2312
2313 #if defined(linux) && defined(KERNEL26_SUPPORT)
2314 {
2315 bool linux_ipsec = 0;
2316 struct stat buf;
2317
2318 linux_ipsec = (stat("/proc/net/pfkey", &buf) == 0);
2319 if (linux_ipsec)
2320 {
2321 plog("Using Linux 2.6 IPsec interface code");
2322 kernel_ops = &linux_kernel_ops;
2323 }
2324 else
2325 {
2326 plog("Using KLIPS IPsec interface code");
2327 }
2328 }
2329 #endif
2330
2331 if (kernel_ops->init)
2332 {
2333 kernel_ops->init();
2334 }
2335
2336 /* register SA types that we can negotiate */
2337 can_do_IPcomp = FALSE; /* until we get a response from KLIPS */
2338 kernel_ops->pfkey_register();
2339
2340 if (!kernel_ops->policy_lifetime)
2341 {
2342 event_schedule(EVENT_SHUNT_SCAN, SHUNT_SCAN_INTERVAL, NULL);
2343 }
2344 #endif
2345 }
2346
2347 /* Note: install_inbound_ipsec_sa is only used by the Responder.
2348 * The Responder will subsequently use install_ipsec_sa for the outbound.
2349 * The Initiator uses install_ipsec_sa to install both at once.
2350 */
2351 bool
2352 install_inbound_ipsec_sa(struct state *st)
2353 {
2354 struct connection *const c = st->st_connection;
2355
2356 /* If our peer has a fixed-address client, check if we already
2357 * have a route for that client that conflicts. We will take this
2358 * as proof that that route and the connections using it are
2359 * obsolete and should be eliminated. Interestingly, this is
2360 * the only case in which we can tell that a connection is obsolete.
2361 */
2362 passert(c->kind == CK_PERMANENT || c->kind == CK_INSTANCE);
2363 if (c->spd.that.has_client)
2364 {
2365 for (;;)
2366 {
2367 struct spd_route *esr;
2368 struct connection *o = route_owner(c, &esr, NULL, NULL);
2369
2370 if (o == NULL)
2371 break; /* nobody has a route */
2372
2373 /* note: we ignore the client addresses at this end */
2374 if (sameaddr(&o->spd.that.host_addr, &c->spd.that.host_addr)
2375 && o->interface == c->interface)
2376 break; /* existing route is compatible */
2377
2378 if (o->kind == CK_TEMPLATE && streq(o->name, c->name))
2379 break; /* ??? is this good enough?? */
2380
2381 loglog(RC_LOG_SERIOUS, "route to peer's client conflicts with \"%s\" %s; releasing old connection to free the route"
2382 , o->name, ip_str(&o->spd.that.host_addr));
2383 release_connection(o, FALSE);
2384 }
2385 }
2386
2387 DBG(DBG_CONTROL, DBG_log("install_inbound_ipsec_sa() checking if we can route"));
2388 /* check that we will be able to route and eroute */
2389 switch (could_route(c))
2390 {
2391 case route_easy:
2392 case route_nearconflict:
2393 break;
2394
2395 default:
2396 return FALSE;
2397 }
2398
2399 #ifdef KLIPS
2400 /* (attempt to) actually set up the SAs */
2401 return setup_half_ipsec_sa(st, TRUE);
2402 #else /* !KLIPS */
2403 DBG(DBG_CONTROL, DBG_log("install_inbound_ipsec_sa()"));
2404 return TRUE;
2405 #endif /* !KLIPS */
2406 }
2407
2408 /* Install a route and then a prospective shunt eroute or an SA group eroute.
2409 * Assumption: could_route gave a go-ahead.
2410 * Any SA Group must have already been created.
2411 * On failure, steps will be unwound.
2412 */
2413 bool
2414 route_and_eroute(struct connection *c USED_BY_KLIPS
2415 , struct spd_route *sr USED_BY_KLIPS
2416 , struct state *st USED_BY_KLIPS)
2417 {
2418 #ifdef KLIPS
2419 struct spd_route *esr;
2420 struct spd_route *rosr;
2421 struct connection *ero /* who, if anyone, owns our eroute? */
2422 , *ro = route_owner(c, &rosr, &ero, &esr);
2423 bool eroute_installed = FALSE
2424 , firewall_notified = FALSE
2425 , route_installed = FALSE;
2426
2427 struct connection *ero_top;
2428 struct bare_shunt **bspp;
2429
2430 DBG(DBG_CONTROLMORE,
2431 DBG_log("route_and_eroute with c: %s (next: %s) ero:%s esr:{%p} ro:%s rosr:{%p} and state: %lu"
2432 , c->name
2433 , (c->policy_next ? c->policy_next->name : "none")
2434 , ero ? ero->name : "null"
2435 , esr
2436 , ro ? ro->name : "null"
2437 , rosr
2438 , st ? st->st_serialno : 0));
2439
2440 /* look along the chain of policies for one with the same name */
2441 ero_top = ero;
2442
2443 #if 0
2444 /* XXX - mcr this made sense before, and likely will make sense
2445 * again, so I'l leaving this to remind me what is up */
2446 if (ero!= NULL && ero->routing == RT_UNROUTED_KEYED)
2447 ero = NULL;
2448
2449 for (ero2 = ero; ero2 != NULL; ero2 = ero->policy_next)
2450 if ((ero2->kind == CK_TEMPLATE || ero2->kind==CK_SECONDARY)
2451 && streq(ero2->name, c->name))
2452 break;
2453 #endif
2454
2455 bspp = (ero == NULL)
2456 ? bare_shunt_ptr(&sr->this.client, &sr->that.client, sr->this.protocol)
2457 : NULL;
2458
2459 /* install the eroute */
2460
2461 passert(bspp == NULL || ero == NULL); /* only one non-NULL */
2462
2463 if (bspp != NULL || ero != NULL)
2464 {
2465 /* We're replacing an eroute */
2466
2467 /* if no state provided, then install a shunt for later */
2468 if (st == NULL)
2469 eroute_installed = shunt_eroute(c, sr, RT_ROUTED_PROSPECTIVE
2470 , ERO_REPLACE, "replace");
2471 else
2472 eroute_installed = sag_eroute(st, sr, ERO_REPLACE, "replace");
2473
2474 #if 0
2475 /* XXX - MCR. I previously felt that this was a bogus check */
2476 if (ero != NULL && ero != c && esr != sr)
2477 {
2478 /* By elimination, we must be eclipsing ero. Check. */
2479 passert(ero->kind == CK_TEMPLATE && streq(ero->name, c->name));
2480 passert(LHAS(LELEM(RT_ROUTED_PROSPECTIVE) | LELEM(RT_ROUTED_ECLIPSED)
2481 , esr->routing));
2482 passert(samesubnet(&esr->this.client, &sr->this.client)
2483 && samesubnet(&esr->that.client, &sr->that.client));
2484 }
2485 #endif
2486 /* remember to free bspp iff we make it out of here alive */
2487 }
2488 else
2489 {
2490 /* we're adding an eroute */
2491
2492 /* if no state provided, then install a shunt for later */
2493 if (st == NULL)
2494 eroute_installed = shunt_eroute(c, sr, RT_ROUTED_PROSPECTIVE
2495 , ERO_ADD, "add");
2496 else
2497 eroute_installed = sag_eroute(st, sr, ERO_ADD, "add");
2498 }
2499
2500 /* notify the firewall of a new tunnel */
2501
2502 if (eroute_installed)
2503 {
2504 /* do we have to notify the firewall? Yes, if we are installing
2505 * a tunnel eroute and the firewall wasn't notified
2506 * for a previous tunnel with the same clients. Any Previous
2507 * tunnel would have to be for our connection, so the actual
2508 * test is simple.
2509 */
2510 firewall_notified = st == NULL /* not a tunnel eroute */
2511 || sr->eroute_owner != SOS_NOBODY /* already notified */
2512 || do_command(c, sr, "up"); /* go ahead and notify */
2513 }
2514
2515 /* install the route */
2516
2517 DBG(DBG_CONTROL,
2518 DBG_log("route_and_eroute: firewall_notified: %s"
2519 , firewall_notified ? "true" : "false"));
2520 if (!firewall_notified)
2521 {
2522 /* we're in trouble -- don't do routing */
2523 }
2524 else if (ro == NULL)
2525 {
2526 /* a new route: no deletion required, but preparation is */
2527 (void) do_command(c, sr, "prepare"); /* just in case; ignore failure */
2528 route_installed = do_command(c, sr, "route");
2529 }
2530 else if (routed(sr->routing)
2531 || routes_agree(ro, c))
2532 {
2533 route_installed = TRUE; /* nothing to be done */
2534 }
2535 else
2536 {
2537 /* Some other connection must own the route
2538 * and the route must disagree. But since could_route
2539 * must have allowed our stealing it, we'll do so.
2540 *
2541 * A feature of LINUX allows us to install the new route
2542 * before deleting the old if the nexthops differ.
2543 * This reduces the "window of vulnerability" when packets
2544 * might flow in the clear.
2545 */
2546 if (sameaddr(&sr->this.host_nexthop, &esr->this.host_nexthop))
2547 {
2548 (void) do_command(ro, sr, "unroute");
2549 route_installed = do_command(c, sr, "route");
2550 }
2551 else
2552 {
2553 route_installed = do_command(c, sr, "route");
2554 (void) do_command(ro, sr, "unroute");
2555 }
2556
2557 /* record unrouting */
2558 if (route_installed)
2559 {
2560 do {
2561 passert(!erouted(rosr->routing));
2562 rosr->routing = RT_UNROUTED;
2563
2564 /* no need to keep old value */
2565 ro = route_owner(c, &rosr, NULL, NULL);
2566 } while (ro != NULL);
2567 }
2568 }
2569
2570 /* all done -- clean up */
2571 if (route_installed)
2572 {
2573 /* Success! */
2574
2575 if (bspp != NULL)
2576 {
2577 free_bare_shunt(bspp);
2578 }
2579 else if (ero != NULL && ero != c)
2580 {
2581 /* check if ero is an ancestor of c. */
2582 struct connection *ero2;
2583
2584 for (ero2 = c; ero2 != NULL && ero2 != c; ero2 = ero2->policy_next)
2585 ;
2586
2587 if (ero2 == NULL)
2588 {
2589 /* By elimination, we must be eclipsing ero. Checked above. */
2590 if (ero->spd.routing != RT_ROUTED_ECLIPSED)
2591 {
2592 ero->spd.routing = RT_ROUTED_ECLIPSED;
2593 eclipse_count++;
2594 }
2595 }
2596 }
2597
2598 if (st == NULL)
2599 {
2600 passert(sr->eroute_owner == SOS_NOBODY);
2601 sr->routing = RT_ROUTED_PROSPECTIVE;
2602 }
2603 else
2604 {
2605 char cib[CONN_INST_BUF];
2606 sr->routing = RT_ROUTED_TUNNEL;
2607
2608 DBG(DBG_CONTROL,
2609 DBG_log("route_and_eroute: instance \"%s\"%s, setting eroute_owner {spd=%p,sr=%p} to #%ld (was #%ld) (newest_ipsec_sa=#%ld)"
2610 , st->st_connection->name
2611 , (fmt_conn_instance(st->st_connection, cib), cib)
2612 , &st->st_connection->spd, sr
2613 , st->st_serialno
2614 , sr->eroute_owner
2615 , st->st_connection->newest_ipsec_sa));
2616 sr->eroute_owner = st->st_serialno;
2617 }
2618
2619 return TRUE;
2620 }
2621 else
2622 {
2623 /* Failure! Unwind our work. */
2624 if (firewall_notified && sr->eroute_owner == SOS_NOBODY)
2625 (void) do_command(c, sr, "down");
2626
2627 if (eroute_installed)
2628 {
2629 /* Restore original eroute, if we can.
2630 * Since there is nothing much to be done if the restoration
2631 * fails, ignore success or failure.
2632 */
2633 if (bspp != NULL)
2634 {
2635 /* Restore old bare_shunt.
2636 * I don't think that this case is very likely.
2637 * Normally a bare shunt would have been assigned
2638 * to a connection before we've gotten this far.
2639 */
2640 struct bare_shunt *bs = *bspp;
2641
2642 (void) raw_eroute(&bs->said.dst /* should be useless */
2643 , &bs->ours
2644 , &bs->said.dst /* should be useless */
2645 , &bs->his
2646 , bs->said.spi /* network order */
2647 , SA_INT
2648 , SADB_X_SATYPE_INT
2649 , 0
2650 , null_proto_info
2651 , SHUNT_PATIENCE
2652 , ERO_REPLACE, "restore");
2653 }
2654 else if (ero != NULL)
2655 {
2656 /* restore ero's former glory */
2657 if (esr->eroute_owner == SOS_NOBODY)
2658 {
2659 /* note: normal or eclipse case */
2660 (void) shunt_eroute(ero, esr
2661 , esr->routing, ERO_REPLACE, "restore");
2662 }
2663 else
2664 {
2665 /* Try to find state that owned eroute.
2666 * Don't do anything if it cannot be found.
2667 * This case isn't likely since we don't run
2668 * the updown script when replacing a SA group
2669 * with its successor (for the same conn).
2670 */
2671 struct state *ost = state_with_serialno(esr->eroute_owner);
2672
2673 if (ost != NULL)
2674 (void) sag_eroute(ost, esr, ERO_REPLACE, "restore");
2675 }
2676 }
2677 else
2678 {
2679 /* there was no previous eroute: delete whatever we installed */
2680 if (st == NULL)
2681 (void) shunt_eroute(c, sr
2682 , sr->routing, ERO_DELETE, "delete");
2683 else
2684 (void) sag_eroute(st, sr
2685 , ERO_DELETE, "delete");
2686 }
2687 }
2688
2689 return FALSE;
2690 }
2691 #else /* !KLIPS */
2692 return TRUE;
2693 #endif /* !KLIPS */
2694 }
2695
2696 bool
2697 install_ipsec_sa(struct state *st, bool inbound_also USED_BY_KLIPS)
2698 {
2699 #ifdef KLIPS
2700 struct spd_route *sr;
2701
2702 DBG(DBG_CONTROL, DBG_log("install_ipsec_sa() for #%ld: %s"
2703 , st->st_serialno
2704 , inbound_also?
2705 "inbound and outbound" : "outbound only"));
2706
2707 switch (could_route(st->st_connection))
2708 {
2709 case route_easy:
2710 case route_nearconflict:
2711 break;
2712
2713 default:
2714 return FALSE;
2715 }
2716
2717 /* (attempt to) actually set up the SA group */
2718 if ((inbound_also && !setup_half_ipsec_sa(st, TRUE))
2719 || !setup_half_ipsec_sa(st, FALSE))
2720 return FALSE;
2721
2722 for (sr = &st->st_connection->spd; sr != NULL; sr = sr->next)
2723 {
2724 DBG(DBG_CONTROL, DBG_log("sr for #%ld: %s"
2725 , st->st_serialno
2726 , enum_name(&routing_story, sr->routing)));
2727
2728 /*
2729 * if the eroute owner is not us, then make it us.
2730 * See test co-terminal-02, pluto-rekey-01, pluto-unit-02/oppo-twice
2731 */
2732 pexpect(sr->eroute_owner == SOS_NOBODY
2733 || sr->routing >= RT_ROUTED_TUNNEL);
2734
2735 if (sr->eroute_owner != st->st_serialno
2736 && sr->routing != RT_UNROUTED_KEYED)
2737 {
2738 if (!route_and_eroute(st->st_connection, sr, st))
2739 {
2740 delete_ipsec_sa(st, FALSE);
2741 /* XXX go and unroute any SRs that were successfully
2742 * routed already.
2743 */
2744 return FALSE;
2745 }
2746 }
2747 }
2748 #else /* !KLIPS */
2749 DBG(DBG_CONTROL, DBG_log("install_ipsec_sa() %s"
2750 , inbound_also? "inbound and oubound" : "outbound only"));
2751
2752 switch (could_route(st->st_connection))
2753 {
2754 case route_easy:
2755 case route_nearconflict:
2756 break;
2757
2758 default:
2759 return FALSE;
2760 }
2761
2762
2763 #endif /* !KLIPS */
2764
2765 return TRUE;
2766 }
2767
2768 /* delete an IPSEC SA.
2769 * we may not succeed, but we bull ahead anyway because
2770 * we cannot do anything better by recognizing failure
2771 */
2772 void
2773 delete_ipsec_sa(struct state *st USED_BY_KLIPS, bool inbound_only USED_BY_KLIPS)
2774 {
2775 #ifdef KLIPS
2776 if (!inbound_only)
2777 {
2778 /* If the state is the eroute owner, we must adjust
2779 * the routing for the connection.
2780 */
2781 struct connection *c = st->st_connection;
2782 struct spd_route *sr;
2783
2784 passert(st->st_connection);
2785
2786 for (sr = &c->spd; sr; sr = sr->next)
2787 {
2788 if (sr->eroute_owner == st->st_serialno
2789 && sr->routing == RT_ROUTED_TUNNEL)
2790 {
2791 sr->eroute_owner = SOS_NOBODY;
2792
2793 /* Routing should become RT_ROUTED_FAILURE,
2794 * but if POLICY_FAIL_NONE, then we just go
2795 * right back to RT_ROUTED_PROSPECTIVE as if no
2796 * failure happened.
2797 */
2798 sr->routing = (c->policy & POLICY_FAIL_MASK) == POLICY_FAIL_NONE
2799 ? RT_ROUTED_PROSPECTIVE : RT_ROUTED_FAILURE;
2800
2801 (void) do_command(c, sr, "down");
2802 if ((c->policy & POLICY_DONT_REKEY)
2803 && c->kind == CK_INSTANCE)
2804 {
2805 /* in this special case, even if the connection
2806 * is still alive (due to an ISAKMP SA),
2807 * we get rid of routing.
2808 * Even though there is still an eroute, the c->routing
2809 * setting will convince unroute_connection to delete it.
2810 * unroute_connection would be upset if c->routing == RT_ROUTED_TUNNEL
2811 */
2812 unroute_connection(c);
2813 }
2814 else
2815 {
2816 (void) shunt_eroute(c, sr, sr->routing, ERO_REPLACE, "replace with shunt");
2817 }
2818 }
2819 }
2820 (void) teardown_half_ipsec_sa(st, FALSE);
2821 }
2822 (void) teardown_half_ipsec_sa(st, TRUE);
2823 #else /* !KLIPS */
2824 DBG(DBG_CONTROL, DBG_log("if I knew how, I'd eroute() and teardown_ipsec_sa()"));
2825 #endif /* !KLIPS */
2826 }
2827 #ifdef NAT_TRAVERSAL
2828 #ifdef KLIPS
2829 static bool update_nat_t_ipsec_esp_sa (struct state *st, bool inbound)
2830 {
2831 struct connection *c = st->st_connection;
2832 char text_said[SATOT_BUF];
2833 struct kernel_sa sa;
2834 ip_address
2835 src = inbound? c->spd.that.host_addr : c->spd.this.host_addr,
2836 dst = inbound? c->spd.this.host_addr : c->spd.that.host_addr;
2837
2838
2839 ipsec_spi_t esp_spi = inbound? st->st_esp.our_spi : st->st_esp.attrs.spi;
2840
2841 u_int16_t
2842 natt_sport = inbound? c->spd.that.host_port : c->spd.this.host_port,
2843 natt_dport = inbound? c->spd.this.host_port : c->spd.that.host_port;
2844
2845 set_text_said(text_said, &dst, esp_spi, SA_ESP);
2846
2847 memset(&sa, 0, sizeof(sa));
2848 sa.spi = esp_spi;
2849 sa.src = &src;
2850 sa.dst = &dst;
2851 sa.text_said = text_said;
2852 sa.authalg = alg_info_esp_aa2sadb(st->st_esp.attrs.auth);
2853 sa.natt_sport = natt_sport;
2854 sa.natt_dport = natt_dport;
2855 sa.transid = st->st_esp.attrs.transid;
2856
2857 return kernel_ops->add_sa(&sa, TRUE);
2858
2859 }
2860 #endif
2861
2862 bool update_ipsec_sa (struct state *st USED_BY_KLIPS)
2863 {
2864 #ifdef KLIPS
2865 if (IS_IPSEC_SA_ESTABLISHED(st->st_state)) {
2866 if ((st->st_esp.present) && (
2867 (!update_nat_t_ipsec_esp_sa (st, TRUE)) ||
2868 (!update_nat_t_ipsec_esp_sa (st, FALSE)))) {
2869 return FALSE;
2870 }
2871 }
2872 else if (IS_ONLY_INBOUND_IPSEC_SA_ESTABLISHED(st->st_state)) {
2873 if ((st->st_esp.present) && (!update_nat_t_ipsec_esp_sa (st, FALSE))) {
2874 return FALSE;
2875 }
2876 }
2877 else {
2878 DBG_log("assert failed at %s:%d st_state=%d", __FILE__, __LINE__,
2879 st->st_state);
2880 return FALSE;
2881 }
2882 return TRUE;
2883 #else /* !KLIPS */
2884 DBG(DBG_CONTROL, DBG_log("if I knew how, I'd update_ipsec_sa()"));
2885 return TRUE;
2886 #endif /* !KLIPS */
2887 }
2888 #endif
2889
2890 /* Check if there was traffic on given SA during the last idle_max
2891 * seconds. If TRUE, the SA was idle and DPD exchange should be performed.
2892 * If FALSE, DPD is not necessary. We also return TRUE for errors, as they
2893 * could mean that the SA is broken and needs to be replace anyway.
2894 */
2895 bool
2896 was_eroute_idle(struct state *st, time_t idle_max, time_t *idle_time)
2897 {
2898 static const char procname[] = "/proc/net/ipsec_spi";
2899 FILE *f;
2900 char buf[1024];
2901 u_int bytes;
2902 int ret = TRUE;
2903
2904 passert(st != NULL);
2905
2906 f = fopen(procname, "r");
2907 if (f == NULL)
2908 {
2909 /* Can't open the file, perhaps were are on 26sec? */
2910 time_t use_time;
2911
2912 if (get_sa_info(st, TRUE, &bytes, &use_time)
2913 && use_time != UNDEFINED_TIME)
2914 {
2915 *idle_time = time(NULL) - use_time;
2916 ret = *idle_time >= idle_max;
2917 }
2918 }
2919 else
2920 {
2921 while (f != NULL)
2922 {
2923 char *line;
2924 char text_said[SATOT_BUF];
2925 u_int8_t proto = 0;
2926 ip_address dst;
2927 ip_said said;
2928 ipsec_spi_t spi = 0;
2929 static const char idle[] = "idle=";
2930
2931 dst = st->st_connection->spd.this.host_addr; /* inbound SA */
2932 if (st->st_ah.present)
2933 {
2934 proto = SA_AH;
2935 spi = st->st_ah.our_spi;
2936 }
2937 if (st->st_esp.present)
2938 {
2939 proto = SA_ESP;
2940 spi = st->st_esp.our_spi;
2941 }
2942
2943 if (proto == 0 && spi == 0)
2944 {
2945 ret = TRUE;
2946 break;
2947 }
2948
2949 initsaid(&dst, spi, proto, &said);
2950 satot(&said, 'x', text_said, SATOT_BUF);
2951
2952 line = fgets(buf, sizeof(buf), f);
2953 if (line == NULL)
2954 {
2955 /* Reached end of list */
2956 ret = TRUE;
2957 break;
2958 }
2959
2960 if (strncmp(line, text_said, strlen(text_said)) == 0)
2961 {
2962 /* we found a match, now try to find idle= */
2963 char *p = strstr(line, idle);
2964
2965 if (p == NULL)
2966 {
2967 /* SAs which haven't been used yet don't have it */
2968 ret = TRUE; /* it didn't have traffic */
2969 break;
2970 }
2971 p += sizeof(idle)-1;
2972 if (*p == '\0')
2973 {
2974 ret = TRUE; /* be paranoid */
2975 break;
2976 }
2977 if (sscanf(p, "%d", (int *) idle_time) <= 0)
2978 {
2979 ret = TRUE;
2980 break;
2981 }
2982 if (*idle_time >= idle_max)
2983 {
2984 ret = TRUE;
2985 break;
2986 }
2987 else
2988 {
2989 ret = FALSE;
2990 break;
2991 }
2992 }
2993 }
2994 fclose(f);
2995 }
2996 return ret;
2997 }