pluto: Adapted kernel.c to changed kernel interface.
[strongswan.git] / src / pluto / kernel.c
1 /* routines that interface with the kernel's IPsec mechanism
2 *
3 * Copyright (C) 2010 Tobias Brunner
4 * Copyright (C) 2009 Andreas Steffen
5 * Hochschule fuer Technik Rapperswil
6 *
7 * Copyright (C) 1998-2002 D. Hugh Redelmeier
8 * Copyright (C) 1997 Angelos D. Keromytis
9 *
10 * This program is free software; you can redistribute it and/or modify it
11 * under the terms of the GNU General Public License as published by the
12 * Free Software Foundation; either version 2 of the License, or (at your
13 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
14 *
15 * This program is distributed in the hope that it will be useful, but
16 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
18 * for more details.
19 */
20
21 #include <stddef.h>
22 #include <string.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <errno.h>
26 #include <wait.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29 #include <sys/queue.h>
30
31 #include <sys/stat.h>
32 #include <sys/socket.h>
33 #include <netinet/in.h>
34 #include <arpa/inet.h>
35
36 #include <freeswan.h>
37
38 #include <library.h>
39 #include <hydra.h>
40 #include <crypto/rngs/rng.h>
41
42 #ifdef KLIPS
43 #include <signal.h>
44 #include <sys/time.h> /* for select(2) */
45 #include <sys/types.h> /* for select(2) */
46 #include <pfkeyv2.h>
47 #include <pfkey.h>
48 #include "kameipsec.h"
49 #endif /* KLIPS */
50
51 #include "constants.h"
52 #include "defs.h"
53 #include "connections.h"
54 #include "state.h"
55 #include "timer.h"
56 #include "kernel.h"
57 #include "kernel_netlink.h"
58 #include "kernel_pfkey.h"
59 #include "kernel_noklips.h"
60 #include "log.h"
61 #include "ca.h"
62 #include "server.h"
63 #include "whack.h" /* for RC_LOG_SERIOUS */
64 #include "keys.h"
65 #include "crypto.h"
66 #include "nat_traversal.h"
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 /* test if the routes required for two different connections agree
74 * It is assumed that the destination subnets agree; we are only
75 * testing that the interfaces and nexthops match.
76 */
77 #define routes_agree(c, d) ((c)->interface == (d)->interface \
78 && sameaddr(&(c)->spd.this.host_nexthop, &(d)->spd.this.host_nexthop))
79
80 #ifndef KLIPS
81
82 bool no_klips = TRUE; /* don't actually use KLIPS */
83
84 #else /* !KLIPS */
85
86 /* bare (connectionless) shunt (eroute) table
87 *
88 * Bare shunts are those that don't "belong" to a connection.
89 * This happens because some %trapped traffic hasn't yet or cannot be
90 * assigned to a connection. The usual reason is that we cannot discover
91 * the peer SG. Another is that even when the peer has been discovered,
92 * it may be that no connection matches all the particulars.
93 * We record them so that, with scanning, we can discover
94 * which %holds are news and which others should expire.
95 */
96
97 #define SHUNT_SCAN_INTERVAL (60 * 2) /* time between scans of eroutes */
98
99 /* SHUNT_PATIENCE only has resolution down to a multiple of the sample rate,
100 * SHUNT_SCAN_INTERVAL.
101 * By making SHUNT_PATIENCE an odd multiple of half of SHUNT_SCAN_INTERVAL,
102 * we minimize the effects of jitter.
103 */
104 #define SHUNT_PATIENCE (SHUNT_SCAN_INTERVAL * 15 / 2) /* inactivity timeout */
105
106 struct bare_shunt {
107 policy_prio_t policy_prio;
108 ip_subnet ours;
109 ip_subnet his;
110 ip_said said;
111 int transport_proto;
112 unsigned long count;
113 time_t last_activity;
114 char *why;
115 struct bare_shunt *next;
116 };
117
118 static struct bare_shunt *bare_shunts = NULL;
119
120 #ifdef DEBUG
121 static void DBG_bare_shunt(const char *op, const struct bare_shunt *bs)
122 {
123 DBG(DBG_KLIPS,
124 {
125 int ourport = ntohs(portof(&(bs)->ours.addr));
126 int hisport = ntohs(portof(&(bs)->his.addr));
127 char ourst[SUBNETTOT_BUF];
128 char hist[SUBNETTOT_BUF];
129 char sat[SATOT_BUF];
130 char prio[POLICY_PRIO_BUF];
131
132 subnettot(&(bs)->ours, 0, ourst, sizeof(ourst));
133 subnettot(&(bs)->his, 0, hist, sizeof(hist));
134 satot(&(bs)->said, 0, sat, sizeof(sat));
135 fmt_policy_prio(bs->policy_prio, prio);
136 DBG_log("%s bare shunt %p %s:%d -> %s:%d => %s:%d %s %s"
137 , op, (const void *)(bs), ourst, ourport, hist, hisport
138 , sat, (bs)->transport_proto, prio, (bs)->why);
139 });
140 }
141 #else /* !DEBUG */
142 #define DBG_bare_shunt(op, bs) {}
143 #endif /* !DEBUG */
144
145 /* The orphaned_holds table records %holds for which we
146 * scan_proc_shunts found no representation of in any connection.
147 * The corresponding ACQUIRE message might have been lost.
148 */
149 struct eroute_info *orphaned_holds = NULL;
150
151 /* forward declaration */
152 static bool shunt_eroute(connection_t *c, struct spd_route *sr,
153 enum routing_t rt_kind, unsigned int op,
154 const char *opname);
155
156 static void set_text_said(char *text_said, const ip_address *dst,
157 ipsec_spi_t spi, int proto);
158
159 bool no_klips = FALSE; /* don't actually use KLIPS */
160
161 /**
162 * Default IPsec SA config (e.g. to install trap policies).
163 */
164 static ipsec_sa_cfg_t null_ipsec_sa = {
165 .mode = MODE_TRANSPORT,
166 .esp = {
167 .use = TRUE,
168 },
169 };
170
171 /**
172 * Helper function that converts an ip_subnet to a traffic_selector_t.
173 */
174 static traffic_selector_t *traffic_selector_from_subnet(const ip_subnet *client,
175 const u_int8_t proto)
176 {
177 traffic_selector_t *ts;
178 host_t *net;
179 net = host_create_from_sockaddr((sockaddr_t*)&client->addr);
180 ts = traffic_selector_create_from_subnet(net, client->maskbits, proto,
181 portof(&client->addr));
182 return ts;
183 }
184
185 void record_and_initiate_opportunistic(const ip_subnet *ours,
186 const ip_subnet *his,
187 int transport_proto, const char *why)
188 {
189 passert(samesubnettype(ours, his));
190
191 /* Add to bare shunt list.
192 * We need to do this because the shunt was installed by KLIPS
193 * which can't do this itself.
194 */
195 {
196 struct bare_shunt *bs = malloc_thing(struct bare_shunt);
197
198 bs->why = clone_str(why);
199 bs->ours = *ours;
200 bs->his = *his;
201 bs->transport_proto = transport_proto;
202 bs->policy_prio = BOTTOM_PRIO;
203
204 bs->said.proto = SA_INT;
205 bs->said.spi = htonl(SPI_HOLD);
206 bs->said.dst = *aftoinfo(subnettypeof(ours))->any;
207
208 bs->count = 0;
209 bs->last_activity = now();
210
211 bs->next = bare_shunts;
212 bare_shunts = bs;
213 DBG_bare_shunt("add", bs);
214 }
215
216 /* actually initiate opportunism */
217 {
218 ip_address src, dst;
219
220 networkof(ours, &src);
221 networkof(his, &dst);
222 initiate_opportunistic(&src, &dst, transport_proto, TRUE, NULL_FD);
223 }
224
225 /* if present, remove from orphaned_holds list.
226 * NOTE: we do this last in case ours or his is a pointer into a member.
227 */
228 {
229 struct eroute_info **pp, *p;
230
231 for (pp = &orphaned_holds; (p = *pp) != NULL; pp = &p->next)
232 {
233 if (samesubnet(ours, &p->ours)
234 && samesubnet(his, &p->his)
235 && transport_proto == p->transport_proto
236 && portof(&ours->addr) == portof(&p->ours.addr)
237 && portof(&his->addr) == portof(&p->his.addr))
238 {
239 *pp = p->next;
240 free(p);
241 break;
242 }
243 }
244 }
245 }
246
247 #endif /* KLIPS */
248
249 /* Generate Unique SPI numbers.
250 *
251 * The returned SPI is in network byte order.
252 */
253 ipsec_spi_t get_ipsec_spi(ipsec_spi_t avoid, int proto, struct spd_route *sr,
254 bool tunnel)
255 {
256 host_t *host_src, *host_dst;
257 u_int32_t spi;
258
259 host_src = host_create_from_sockaddr((sockaddr_t*)&sr->that.host_addr);
260 host_dst = host_create_from_sockaddr((sockaddr_t*)&sr->this.host_addr);
261
262 if (hydra->kernel_interface->get_spi(hydra->kernel_interface, host_src,
263 host_dst, proto, sr->reqid, &spi) != SUCCESS)
264 {
265 spi = 0;
266 }
267
268 host_src->destroy(host_src);
269 host_dst->destroy(host_dst);
270
271 return spi;
272 }
273
274 /* Generate Unique CPI numbers.
275 * The result is returned as an SPI (4 bytes) in network order!
276 * The real bits are in the nework-low-order 2 bytes.
277 */
278 ipsec_spi_t get_my_cpi(struct spd_route *sr, bool tunnel)
279 {
280 host_t *host_src, *host_dst;
281 u_int16_t cpi;
282
283 host_src = host_create_from_sockaddr((sockaddr_t*)&sr->that.host_addr);
284 host_dst = host_create_from_sockaddr((sockaddr_t*)&sr->this.host_addr);
285
286 if (hydra->kernel_interface->get_cpi(hydra->kernel_interface, host_src,
287 host_dst, sr->reqid, &cpi) != SUCCESS)
288
289 {
290 cpi = 0;
291 }
292
293 host_src->destroy(host_src);
294 host_dst->destroy(host_dst);
295
296 return htonl((u_int32_t)ntohs(cpi));
297 }
298
299 /* Replace the shell metacharacters ', \, ", `, and $ in a character string
300 * by escape sequences consisting of their octal values
301 */
302 static void escape_metachar(const char *src, char *dst, size_t dstlen)
303 {
304 while (*src != '\0' && dstlen > 4)
305 {
306 switch (*src)
307 {
308 case '\'':
309 case '\\':
310 case '"':
311 case '`':
312 case '$':
313 sprintf(dst,"\\%s%o", (*src < 64)?"0":"", *src);
314 dst += 4;
315 dstlen -= 4;
316 break;
317 default:
318 *dst++ = *src;
319 dstlen--;
320 }
321 src++;
322 }
323 *dst = '\0';
324 }
325
326 /* invoke the updown script to do the routing and firewall commands required
327 *
328 * The user-specified updown script is run. Parameters are fed to it in
329 * the form of environment variables. All such environment variables
330 * have names starting with "PLUTO_".
331 *
332 * The operation to be performed is specified by PLUTO_VERB. This
333 * verb has a suffix "-host" if the client on this end is just the
334 * host; otherwise the suffix is "-client". If the address family
335 * of the host is IPv6, an extra suffix of "-v6" is added.
336 *
337 * "prepare-host" and "prepare-client" are used to delete a route
338 * that may exist (due to forces outside of Pluto). It is used to
339 * prepare for pluto creating a route.
340 *
341 * "route-host" and "route-client" are used to install a route.
342 * Since routing is based only on destination, the PLUTO_MY_CLIENT_*
343 * values are probably of no use (using them may signify a bug).
344 *
345 * "unroute-host" and "unroute-client" are used to delete a route.
346 * Since routing is based only on destination, the PLUTO_MY_CLIENT_*
347 * values are probably of no use (using them may signify a bug).
348 *
349 * "up-host" and "up-client" are run when an eroute is added (not replaced).
350 * They are useful for adjusting a firewall: usually for adding a rule
351 * to let processed packets flow between clients. Note that only
352 * one eroute may exist for a pair of client subnets but inbound
353 * IPsec SAs may persist without an eroute.
354 *
355 * "down-host" and "down-client" are run when an eroute is deleted.
356 * They are useful for adjusting a firewall.
357 */
358
359 #ifndef DEFAULT_UPDOWN
360 # define DEFAULT_UPDOWN "ipsec _updown"
361 #endif
362
363 static bool do_command(connection_t *c, struct spd_route *sr,
364 const char *verb)
365 {
366 char cmd[1536]; /* arbitrary limit on shell command length */
367 const char *verb_suffix;
368
369 /* figure out which verb suffix applies */
370 {
371 const char *hs, *cs;
372
373 switch (addrtypeof(&sr->this.host_addr))
374 {
375 case AF_INET:
376 hs = "-host";
377 cs = "-client";
378 break;
379 case AF_INET6:
380 hs = "-host-v6";
381 cs = "-client-v6";
382 break;
383 default:
384 loglog(RC_LOG_SERIOUS, "unknown address family");
385 return FALSE;
386 }
387 verb_suffix = subnetisaddr(&sr->this.client, &sr->this.host_addr)
388 ? hs : cs;
389 }
390
391 /* form the command string */
392 {
393 char
394 nexthop_str[sizeof("PLUTO_NEXT_HOP='' ") +ADDRTOT_BUF] = "",
395 srcip_str[sizeof("PLUTO_MY_SOURCEIP='' ")+ADDRTOT_BUF] = "",
396 me_str[ADDRTOT_BUF],
397 myid_str[BUF_LEN],
398 myclient_str[SUBNETTOT_BUF],
399 myclientnet_str[ADDRTOT_BUF],
400 myclientmask_str[ADDRTOT_BUF],
401 peer_str[ADDRTOT_BUF],
402 peerid_str[BUF_LEN],
403 peerclient_str[SUBNETTOT_BUF],
404 peerclientnet_str[ADDRTOT_BUF],
405 peerclientmask_str[ADDRTOT_BUF],
406 peerca_str[BUF_LEN],
407 xauth_id_str[BUF_LEN] = "",
408 secure_myid_str[BUF_LEN] = "",
409 secure_peerid_str[BUF_LEN] = "",
410 secure_peerca_str[BUF_LEN] = "",
411 secure_xauth_id_str[BUF_LEN] = "";
412 ip_address ta;
413 pubkey_list_t *p;
414
415 if (addrbytesptr(&sr->this.host_nexthop, NULL)
416 && !isanyaddr(&sr->this.host_nexthop))
417 {
418 char *n;
419
420 strcpy(nexthop_str, "PLUTO_NEXT_HOP='");
421 n = nexthop_str + strlen(nexthop_str);
422
423 addrtot(&sr->this.host_nexthop, 0
424 ,n , sizeof(nexthop_str)-strlen(nexthop_str));
425 strncat(nexthop_str, "' ", sizeof(nexthop_str));
426 }
427
428 if (!sr->this.host_srcip->is_anyaddr(sr->this.host_srcip))
429 {
430 char *n;
431
432 strcpy(srcip_str, "PLUTO_MY_SOURCEIP='");
433 n = srcip_str + strlen(srcip_str);
434 snprintf(n, sizeof(srcip_str)-strlen(srcip_str), "%H",
435 sr->this.host_srcip);
436 strncat(srcip_str, "' ", sizeof(srcip_str));
437 }
438
439 addrtot(&sr->this.host_addr, 0, me_str, sizeof(me_str));
440 snprintf(myid_str, sizeof(myid_str), "%Y", sr->this.id);
441 escape_metachar(myid_str, secure_myid_str, sizeof(secure_myid_str));
442 subnettot(&sr->this.client, 0, myclient_str, sizeof(myclientnet_str));
443 networkof(&sr->this.client, &ta);
444 addrtot(&ta, 0, myclientnet_str, sizeof(myclientnet_str));
445 maskof(&sr->this.client, &ta);
446 addrtot(&ta, 0, myclientmask_str, sizeof(myclientmask_str));
447
448 if (c->xauth_identity &&
449 c->xauth_identity->get_type(c->xauth_identity) != ID_ANY)
450 {
451 snprintf(xauth_id_str, sizeof(xauth_id_str), "%Y", c->xauth_identity);
452 escape_metachar(xauth_id_str, secure_xauth_id_str,
453 sizeof(secure_xauth_id_str));
454 snprintf(xauth_id_str, sizeof(xauth_id_str), "PLUTO_XAUTH_ID='%s' ",
455 secure_xauth_id_str);
456 }
457
458 addrtot(&sr->that.host_addr, 0, peer_str, sizeof(peer_str));
459 snprintf(peerid_str, sizeof(peerid_str), "%Y", sr->that.id);
460 escape_metachar(peerid_str, secure_peerid_str, sizeof(secure_peerid_str));
461 subnettot(&sr->that.client, 0, peerclient_str, sizeof(peerclientnet_str));
462 networkof(&sr->that.client, &ta);
463 addrtot(&ta, 0, peerclientnet_str, sizeof(peerclientnet_str));
464 maskof(&sr->that.client, &ta);
465 addrtot(&ta, 0, peerclientmask_str, sizeof(peerclientmask_str));
466
467 for (p = pubkeys; p != NULL; p = p->next)
468 {
469 pubkey_t *key = p->key;
470 key_type_t type = key->public_key->get_type(key->public_key);
471 int pathlen;
472
473 if (type == KEY_RSA &&
474 sr->that.id->equals(sr->that.id, key->id) &&
475 trusted_ca(key->issuer, sr->that.ca, &pathlen))
476 {
477 if (key->issuer)
478 {
479 snprintf(peerca_str, BUF_LEN, "%Y", key->issuer);
480 escape_metachar(peerca_str, secure_peerca_str, BUF_LEN);
481 }
482 else
483 {
484 secure_peerca_str[0] = '\0';
485 }
486 break;
487 }
488 }
489
490 if (-1 == snprintf(cmd, sizeof(cmd)
491 , "2>&1 " /* capture stderr along with stdout */
492 "PLUTO_VERSION='1.1' " /* change VERSION when interface spec changes */
493 "PLUTO_VERB='%s%s' "
494 "PLUTO_CONNECTION='%s' "
495 "%s" /* optional PLUTO_NEXT_HOP */
496 "PLUTO_INTERFACE='%s' "
497 "%s" /* optional PLUTO_HOST_ACCESS */
498 "PLUTO_REQID='%u' "
499 "PLUTO_ME='%s' "
500 "PLUTO_MY_ID='%s' "
501 "PLUTO_MY_CLIENT='%s' "
502 "PLUTO_MY_CLIENT_NET='%s' "
503 "PLUTO_MY_CLIENT_MASK='%s' "
504 "PLUTO_MY_PORT='%u' "
505 "PLUTO_MY_PROTOCOL='%u' "
506 "PLUTO_PEER='%s' "
507 "PLUTO_PEER_ID='%s' "
508 "PLUTO_PEER_CLIENT='%s' "
509 "PLUTO_PEER_CLIENT_NET='%s' "
510 "PLUTO_PEER_CLIENT_MASK='%s' "
511 "PLUTO_PEER_PORT='%u' "
512 "PLUTO_PEER_PROTOCOL='%u' "
513 "PLUTO_PEER_CA='%s' "
514 "%s" /* optional PLUTO_MY_SRCIP */
515 "%s" /* optional PLUTO_XAUTH_ID */
516 "%s" /* actual script */
517 , verb, verb_suffix
518 , c->name
519 , nexthop_str
520 , c->interface->vname
521 , sr->this.hostaccess? "PLUTO_HOST_ACCESS='1' " : ""
522 , sr->reqid
523 , me_str
524 , secure_myid_str
525 , myclient_str
526 , myclientnet_str
527 , myclientmask_str
528 , sr->this.port
529 , sr->this.protocol
530 , peer_str
531 , secure_peerid_str
532 , peerclient_str
533 , peerclientnet_str
534 , peerclientmask_str
535 , sr->that.port
536 , sr->that.protocol
537 , secure_peerca_str
538 , srcip_str
539 , xauth_id_str
540 , sr->this.updown == NULL? DEFAULT_UPDOWN : sr->this.updown))
541 {
542 loglog(RC_LOG_SERIOUS, "%s%s command too long!", verb, verb_suffix);
543 return FALSE;
544 }
545 }
546
547 DBG(DBG_CONTROL, DBG_log("executing %s%s: %s"
548 , verb, verb_suffix, cmd));
549
550 #ifdef KLIPS
551 if (!no_klips)
552 {
553 /* invoke the script, catching stderr and stdout
554 * It may be of concern that some file descriptors will
555 * be inherited. For the ones under our control, we
556 * have done fcntl(fd, F_SETFD, FD_CLOEXEC) to prevent this.
557 * Any used by library routines (perhaps the resolver or syslog)
558 * will remain.
559 */
560 FILE *f = popen(cmd, "r");
561
562 if (f == NULL)
563 {
564 loglog(RC_LOG_SERIOUS, "unable to popen %s%s command", verb, verb_suffix);
565 return FALSE;
566 }
567
568 /* log any output */
569 for (;;)
570 {
571 /* if response doesn't fit in this buffer, it will be folded */
572 char resp[256];
573
574 if (fgets(resp, sizeof(resp), f) == NULL)
575 {
576 if (ferror(f))
577 {
578 log_errno((e, "fgets failed on output of %s%s command"
579 , verb, verb_suffix));
580 return FALSE;
581 }
582 else
583 {
584 passert(feof(f));
585 break;
586 }
587 }
588 else
589 {
590 char *e = resp + strlen(resp);
591
592 if (e > resp && e[-1] == '\n')
593 e[-1] = '\0'; /* trim trailing '\n' */
594 plog("%s%s output: %s", verb, verb_suffix, resp);
595 }
596 }
597
598 /* report on and react to return code */
599 {
600 int r = pclose(f);
601
602 if (r == -1)
603 {
604 log_errno((e, "pclose failed for %s%s command"
605 , verb, verb_suffix));
606 return FALSE;
607 }
608 else if (WIFEXITED(r))
609 {
610 if (WEXITSTATUS(r) != 0)
611 {
612 loglog(RC_LOG_SERIOUS, "%s%s command exited with status %d"
613 , verb, verb_suffix, WEXITSTATUS(r));
614 return FALSE;
615 }
616 }
617 else if (WIFSIGNALED(r))
618 {
619 loglog(RC_LOG_SERIOUS, "%s%s command exited with signal %d"
620 , verb, verb_suffix, WTERMSIG(r));
621 return FALSE;
622 }
623 else
624 {
625 loglog(RC_LOG_SERIOUS, "%s%s command exited with unknown status %d"
626 , verb, verb_suffix, r);
627 return FALSE;
628 }
629 }
630 }
631 #endif /* KLIPS */
632 return TRUE;
633 }
634
635 /* Check that we can route (and eroute). Diagnose if we cannot. */
636
637 enum routability {
638 route_impossible = 0,
639 route_easy = 1,
640 route_nearconflict = 2,
641 route_farconflict = 3
642 };
643
644 static enum routability could_route(connection_t *c)
645 {
646 struct spd_route *esr, *rosr;
647 connection_t *ero /* who, if anyone, owns our eroute? */
648 , *ro = route_owner(c, &rosr, &ero, &esr); /* who owns our route? */
649
650 /* it makes no sense to route a connection that is ISAKMP-only */
651 if (!NEVER_NEGOTIATE(c->policy) && !HAS_IPSEC_POLICY(c->policy))
652 {
653 loglog(RC_ROUTE, "cannot route an ISAKMP-only connection");
654 return route_impossible;
655 }
656
657 /* if this is a Road Warrior template, we cannot route.
658 * Opportunistic template is OK.
659 */
660 if (c->kind == CK_TEMPLATE && !(c->policy & POLICY_OPPO))
661 {
662 loglog(RC_ROUTE, "cannot route Road Warrior template");
663 return route_impossible;
664 }
665
666 /* if we don't know nexthop, we cannot route */
667 if (isanyaddr(&c->spd.this.host_nexthop))
668 {
669 loglog(RC_ROUTE, "cannot route connection without knowing our nexthop");
670 return route_impossible;
671 }
672
673 /* if routing would affect IKE messages, reject */
674 if (!no_klips
675 && c->spd.this.host_port != NAT_T_IKE_FLOAT_PORT
676 && c->spd.this.host_port != IKE_UDP_PORT
677 && addrinsubnet(&c->spd.that.host_addr, &c->spd.that.client))
678 {
679 loglog(RC_LOG_SERIOUS, "cannot install route: peer is within its client");
680 return route_impossible;
681 }
682
683 /* If there is already a route for peer's client subnet
684 * and it disagrees about interface or nexthop, we cannot steal it.
685 * Note: if this connection is already routed (perhaps for another
686 * state object), the route will agree.
687 * This is as it should be -- it will arise during rekeying.
688 */
689 if (ro != NULL && !routes_agree(ro, c))
690 {
691 loglog(RC_LOG_SERIOUS, "cannot route -- route already in use for \"%s\""
692 , ro->name);
693 return route_impossible; /* another connection already
694 using the eroute */
695 }
696
697 #ifdef KLIPS
698 /* if there is an eroute for another connection, there is a problem */
699 if (ero != NULL && ero != c)
700 {
701 connection_t *ero2, *ero_top;
702 connection_t *inside, *outside;
703
704 /*
705 * note, wavesec (PERMANENT) goes *outside* and
706 * OE goes *inside* (TEMPLATE)
707 */
708 inside = NULL;
709 outside= NULL;
710 if (ero->kind == CK_PERMANENT
711 && c->kind == CK_TEMPLATE)
712 {
713 outside = ero;
714 inside = c;
715 }
716 else if (c->kind == CK_PERMANENT
717 && ero->kind == CK_TEMPLATE)
718 {
719 outside = c;
720 inside = ero;
721 }
722
723 /* okay, check again, with correct order */
724 if (outside && outside->kind == CK_PERMANENT
725 && inside && inside->kind == CK_TEMPLATE)
726 {
727 char inst[CONN_INST_BUF];
728
729 /* this is a co-terminal attempt of the "near" kind. */
730 /* when chaining, we chain from inside to outside */
731
732 /* XXX permit multiple deep connections? */
733 passert(inside->policy_next == NULL);
734
735 inside->policy_next = outside;
736
737 /* since we are going to steal the eroute from the secondary
738 * policy, we need to make sure that it no longer thinks that
739 * it owns the eroute.
740 */
741 outside->spd.eroute_owner = SOS_NOBODY;
742 outside->spd.routing = RT_UNROUTED_KEYED;
743
744 /* set the priority of the new eroute owner to be higher
745 * than that of the current eroute owner
746 */
747 inside->prio = outside->prio + 1;
748
749 fmt_conn_instance(inside, inst);
750
751 loglog(RC_LOG_SERIOUS
752 , "conflict on eroute (%s), switching eroute to %s and linking %s"
753 , inst, inside->name, outside->name);
754
755 return route_nearconflict;
756 }
757
758 /* look along the chain of policies for one with the same name */
759 ero_top = ero;
760
761 for (ero2 = ero; ero2 != NULL; ero2 = ero->policy_next)
762 {
763 if (ero2->kind == CK_TEMPLATE
764 && streq(ero2->name, c->name))
765 break;
766 }
767
768 /* If we fell of the end of the list, then we found no TEMPLATE
769 * so there must be a conflict that we can't resolve.
770 * As the names are not equal, then we aren't replacing/rekeying.
771 */
772 if (ero2 == NULL)
773 {
774 char inst[CONN_INST_BUF];
775
776 fmt_conn_instance(ero, inst);
777
778 loglog(RC_LOG_SERIOUS
779 , "cannot install eroute -- it is in use for \"%s\"%s #%lu"
780 , ero->name, inst, esr->eroute_owner);
781 return FALSE; /* another connection already using the eroute */
782 }
783 }
784 #endif /* KLIPS */
785 return route_easy;
786 }
787
788 bool trap_connection(connection_t *c)
789 {
790 switch (could_route(c))
791 {
792 case route_impossible:
793 return FALSE;
794
795 case route_nearconflict:
796 case route_easy:
797 /* RT_ROUTED_TUNNEL is treated specially: we don't override
798 * because we don't want to lose track of the IPSEC_SAs etc.
799 */
800 if (c->spd.routing < RT_ROUTED_TUNNEL)
801 {
802 return route_and_eroute(c, &c->spd, NULL);
803 }
804 return TRUE;
805
806 case route_farconflict:
807 return FALSE;
808 }
809
810 return FALSE;
811 }
812
813 /**
814 * Delete any eroute for a connection and unroute it if route isn't shared
815 */
816 void unroute_connection(connection_t *c)
817 {
818 struct spd_route *sr;
819 enum routing_t cr;
820
821 for (sr = &c->spd; sr; sr = sr->next)
822 {
823 cr = sr->routing;
824
825 if (erouted(cr))
826 {
827 /* cannot handle a live one */
828 passert(sr->routing != RT_ROUTED_TUNNEL);
829 #ifdef KLIPS
830 shunt_eroute(c, sr, RT_UNROUTED, ERO_DELETE, "delete");
831 #endif
832 }
833
834 sr->routing = RT_UNROUTED; /* do now so route_owner won't find us */
835
836 /* only unroute if no other connection shares it */
837 if (routed(cr) && route_owner(c, NULL, NULL, NULL) == NULL)
838 {
839 (void) do_command(c, sr, "unroute");
840 }
841 }
842 }
843
844
845 #ifdef KLIPS
846
847 static void set_text_said(char *text_said, const ip_address *dst,
848 ipsec_spi_t spi, int proto)
849 {
850 ip_said said;
851
852 initsaid(dst, spi, proto, &said);
853 satot(&said, 0, text_said, SATOT_BUF);
854 }
855
856 /* find an entry in the bare_shunt table.
857 * Trick: return a pointer to the pointer to the entry;
858 * this allows the entry to be deleted.
859 */
860 static struct bare_shunt** bare_shunt_ptr(const ip_subnet *ours,
861 const ip_subnet *his,
862 int transport_proto)
863 {
864 struct bare_shunt *p, **pp;
865
866 for (pp = &bare_shunts; (p = *pp) != NULL; pp = &p->next)
867 {
868 if (samesubnet(ours, &p->ours)
869 && samesubnet(his, &p->his)
870 && transport_proto == p->transport_proto
871 && portof(&ours->addr) == portof(&p->ours.addr)
872 && portof(&his->addr) == portof(&p->his.addr))
873 return pp;
874 }
875 return NULL;
876 }
877
878 /* free a bare_shunt entry, given a pointer to the pointer */
879 static void free_bare_shunt(struct bare_shunt **pp)
880 {
881 if (pp == NULL)
882 {
883 DBG(DBG_CONTROL,
884 DBG_log("delete bare shunt: null pointer")
885 )
886 }
887 else
888 {
889 struct bare_shunt *p = *pp;
890
891 *pp = p->next;
892 DBG_bare_shunt("delete", p);
893 free(p->why);
894 free(p);
895 }
896 }
897
898 void
899 show_shunt_status(void)
900 {
901 struct bare_shunt *bs;
902
903 for (bs = bare_shunts; bs != NULL; bs = bs->next)
904 {
905 /* Print interesting fields. Ignore count and last_active. */
906
907 int ourport = ntohs(portof(&bs->ours.addr));
908 int hisport = ntohs(portof(&bs->his.addr));
909 char ourst[SUBNETTOT_BUF];
910 char hist[SUBNETTOT_BUF];
911 char sat[SATOT_BUF];
912 char prio[POLICY_PRIO_BUF];
913
914 subnettot(&(bs)->ours, 0, ourst, sizeof(ourst));
915 subnettot(&(bs)->his, 0, hist, sizeof(hist));
916 satot(&(bs)->said, 0, sat, sizeof(sat));
917 fmt_policy_prio(bs->policy_prio, prio);
918
919 whack_log(RC_COMMENT, "%s:%d -> %s:%d => %s:%d %s %s"
920 , ourst, ourport, hist, hisport, sat, bs->transport_proto
921 , prio, bs->why);
922 }
923 if (bare_shunts != NULL)
924 whack_log(RC_COMMENT, BLANK_FORMAT); /* spacer */
925 }
926
927 /**
928 * Setup an IPsec route entry.
929 * op is one of the ERO_* operators.
930 */
931 static bool raw_eroute(const ip_address *this_host,
932 const ip_subnet *this_client,
933 const ip_address *that_host,
934 const ip_subnet *that_client,
935 ipsec_spi_t spi,
936 unsigned int proto,
937 unsigned int satype,
938 unsigned int transport_proto,
939 ipsec_sa_cfg_t *sa,
940 time_t use_lifetime,
941 unsigned int op,
942 const char *opname USED_BY_DEBUG)
943 {
944 traffic_selector_t *ts_src, *ts_dst;
945 host_t *host_src, *host_dst;
946 policy_type_t type = POLICY_IPSEC;
947 policy_dir_t dir = POLICY_OUT;
948 mark_t mark_none = { 0, 0 };
949 char text_said[SATOT_BUF];
950 bool ok = TRUE, routed = FALSE,
951 deleting = (op & ERO_MASK) == ERO_DELETE,
952 replacing = op & (SADB_X_SAFLAGS_REPLACEFLOW << ERO_FLAG_SHIFT);
953
954 set_text_said(text_said, that_host, spi, proto);
955
956 DBG(DBG_CONTROL | DBG_KLIPS,
957 {
958 int sport = ntohs(portof(&this_client->addr));
959 int dport = ntohs(portof(&that_client->addr));
960 char mybuf[SUBNETTOT_BUF];
961 char peerbuf[SUBNETTOT_BUF];
962
963 subnettot(this_client, 0, mybuf, sizeof(mybuf));
964 subnettot(that_client, 0, peerbuf, sizeof(peerbuf));
965 DBG_log("%s eroute %s:%d -> %s:%d => %s:%d"
966 , opname, mybuf, sport, peerbuf, dport
967 , text_said, transport_proto);
968 });
969
970 if (satype == SADB_X_SATYPE_INT)
971 {
972 switch (ntohl(spi))
973 {
974 case SPI_PASS:
975 type = POLICY_PASS;
976 break;
977 case SPI_DROP:
978 case SPI_REJECT:
979 type = POLICY_DROP;
980 break;
981 case SPI_TRAP:
982 case SPI_TRAPSUBNET:
983 case SPI_HOLD:
984 if (op & (SADB_X_SAFLAGS_INFLOW << ERO_FLAG_SHIFT))
985 {
986 return TRUE;
987 }
988 routed = TRUE;
989 break;
990 }
991 }
992
993 if (op & (SADB_X_SAFLAGS_INFLOW << ERO_FLAG_SHIFT))
994 {
995 dir = POLICY_IN;
996 }
997
998 host_src = host_create_from_sockaddr((sockaddr_t*)this_host);
999 host_dst = host_create_from_sockaddr((sockaddr_t*)that_host);
1000 ts_src = traffic_selector_from_subnet(this_client, transport_proto);
1001 ts_dst = traffic_selector_from_subnet(that_client, transport_proto);
1002
1003 if (deleting || replacing)
1004 {
1005 hydra->kernel_interface->del_policy(hydra->kernel_interface,
1006 ts_src, ts_dst, dir, mark_none, routed);
1007 }
1008
1009 if (!deleting)
1010 {
1011 /* FIXME: use_lifetime? */
1012 ok = hydra->kernel_interface->add_policy(hydra->kernel_interface,
1013 host_src, host_dst, ts_src, ts_dst, dir, type, sa,
1014 mark_none, routed) == SUCCESS;
1015 }
1016
1017 if (dir == POLICY_IN)
1018 { /* handle forward policy */
1019 dir = POLICY_FWD;
1020 if (deleting || replacing)
1021 {
1022 hydra->kernel_interface->del_policy(hydra->kernel_interface,
1023 ts_src, ts_dst, dir, mark_none, routed);
1024 }
1025
1026 if (!deleting && ok &&
1027 (sa->mode == MODE_TUNNEL || satype == SADB_X_SATYPE_INT))
1028 {
1029 /* FIXME: use_lifetime? */
1030 ok = hydra->kernel_interface->add_policy(hydra->kernel_interface,
1031 host_src, host_dst, ts_src, ts_dst, dir, type, sa,
1032 mark_none, routed) == SUCCESS;
1033 }
1034 }
1035
1036 host_src->destroy(host_src);
1037 host_dst->destroy(host_dst);
1038 ts_src->destroy(ts_src);
1039 ts_dst->destroy(ts_dst);
1040
1041 return ok;
1042 }
1043
1044 /* test to see if %hold remains */
1045 bool has_bare_hold(const ip_address *src, const ip_address *dst,
1046 int transport_proto)
1047 {
1048 ip_subnet this_client, that_client;
1049 struct bare_shunt **bspp;
1050
1051 passert(addrtypeof(src) == addrtypeof(dst));
1052 happy(addrtosubnet(src, &this_client));
1053 happy(addrtosubnet(dst, &that_client));
1054 bspp = bare_shunt_ptr(&this_client, &that_client, transport_proto);
1055 return bspp != NULL
1056 && (*bspp)->said.proto == SA_INT && (*bspp)->said.spi == htonl(SPI_HOLD);
1057 }
1058
1059
1060 /* Replace (or delete) a shunt that is in the bare_shunts table.
1061 * Issues the PF_KEY commands and updates the bare_shunts table.
1062 */
1063 bool replace_bare_shunt(const ip_address *src, const ip_address *dst,
1064 policy_prio_t policy_prio, ipsec_spi_t shunt_spi,
1065 bool repl, unsigned int transport_proto, const char *why)
1066 {
1067 ip_subnet this_client, that_client;
1068 ip_subnet this_broad_client, that_broad_client;
1069 const ip_address *null_host = aftoinfo(addrtypeof(src))->any;
1070
1071 passert(addrtypeof(src) == addrtypeof(dst));
1072 happy(addrtosubnet(src, &this_client));
1073 happy(addrtosubnet(dst, &that_client));
1074 this_broad_client = this_client;
1075 that_broad_client = that_client;
1076 setportof(0, &this_broad_client.addr);
1077 setportof(0, &that_broad_client.addr);
1078
1079 if (repl)
1080 {
1081 struct bare_shunt **bs_pp = bare_shunt_ptr(&this_broad_client
1082 , &that_broad_client, 0);
1083
1084 /* is there already a broad host-to-host bare shunt? */
1085 if (bs_pp == NULL)
1086 {
1087 if (raw_eroute(null_host, &this_broad_client, null_host,
1088 &that_broad_client, htonl(shunt_spi), SA_INT,
1089 SADB_X_SATYPE_INT, 0, &null_ipsec_sa,
1090 SHUNT_PATIENCE, ERO_ADD, why))
1091 {
1092 struct bare_shunt *bs = malloc_thing(struct bare_shunt);
1093
1094 bs->ours = this_broad_client;
1095 bs->his = that_broad_client;
1096 bs->transport_proto = 0;
1097 bs->said.proto = SA_INT;
1098 bs->why = clone_str(why);
1099 bs->policy_prio = policy_prio;
1100 bs->said.spi = htonl(shunt_spi);
1101 bs->said.dst = *null_host;
1102 bs->count = 0;
1103 bs->last_activity = now();
1104 bs->next = bare_shunts;
1105 bare_shunts = bs;
1106 DBG_bare_shunt("add", bs);
1107 }
1108 }
1109 shunt_spi = SPI_HOLD;
1110 }
1111
1112 if (raw_eroute(null_host, &this_client, null_host, &that_client,
1113 htonl(shunt_spi), SA_INT, SADB_X_SATYPE_INT, transport_proto,
1114 &null_ipsec_sa, SHUNT_PATIENCE, ERO_DELETE, why))
1115 {
1116 struct bare_shunt **bs_pp = bare_shunt_ptr(&this_client, &that_client
1117 , transport_proto);
1118
1119 /* delete bare eroute */
1120 free_bare_shunt(bs_pp);
1121 return TRUE;
1122 }
1123 else
1124 {
1125 return FALSE;
1126 }
1127 }
1128
1129 static bool eroute_connection(struct spd_route *sr, ipsec_spi_t spi,
1130 unsigned int proto, unsigned int satype,
1131 ipsec_sa_cfg_t *sa, unsigned int op,
1132 const char *opname)
1133 {
1134 const ip_address *peer = &sr->that.host_addr;
1135 char buf2[256];
1136
1137 snprintf(buf2, sizeof(buf2)
1138 , "eroute_connection %s", opname);
1139
1140 if (proto == SA_INT)
1141 {
1142 peer = aftoinfo(addrtypeof(peer))->any;
1143 }
1144 return raw_eroute(&sr->this.host_addr, &sr->this.client, peer,
1145 &sr->that.client, spi, proto, satype, sr->this.protocol,
1146 sa, 0, op, buf2);
1147 }
1148
1149 /* assign a bare hold to a connection */
1150
1151 bool assign_hold(connection_t *c USED_BY_DEBUG, struct spd_route *sr,
1152 int transport_proto,
1153 const ip_address *src,
1154 const ip_address *dst)
1155 {
1156 /* either the automatically installed %hold eroute is broad enough
1157 * or we try to add a broader one and delete the automatic one.
1158 * Beware: this %hold might be already handled, but still squeak
1159 * through because of a race.
1160 */
1161 enum routing_t ro = sr->routing /* routing, old */
1162 , rn = ro; /* routing, new */
1163
1164 passert(LHAS(LELEM(CK_PERMANENT) | LELEM(CK_INSTANCE), c->kind));
1165 /* figure out what routing should become */
1166 switch (ro)
1167 {
1168 case RT_UNROUTED:
1169 rn = RT_UNROUTED_HOLD;
1170 break;
1171 case RT_ROUTED_PROSPECTIVE:
1172 rn = RT_ROUTED_HOLD;
1173 break;
1174 default:
1175 /* no change: this %hold is old news and should just be deleted */
1176 break;
1177 }
1178
1179 /* we need a broad %hold, not the narrow one.
1180 * First we ensure that there is a broad %hold.
1181 * There may already be one (race condition): no need to create one.
1182 * There may already be a %trap: replace it.
1183 * There may not be any broad eroute: add %hold.
1184 * Once the broad %hold is in place, delete the narrow one.
1185 */
1186 if (rn != ro)
1187 {
1188 if (erouted(ro)
1189 ? !eroute_connection(sr, htonl(SPI_HOLD), SA_INT, SADB_X_SATYPE_INT,
1190 &null_ipsec_sa, ERO_REPLACE,
1191 "replace %trap with broad %hold")
1192 : !eroute_connection(sr, htonl(SPI_HOLD), SA_INT, SADB_X_SATYPE_INT,
1193 &null_ipsec_sa, ERO_ADD, "add broad %hold"))
1194 {
1195 return FALSE;
1196 }
1197 }
1198 if (!replace_bare_shunt(src, dst, BOTTOM_PRIO, SPI_HOLD, FALSE,
1199 transport_proto, "delete narrow %hold"))
1200 {
1201 return FALSE;
1202 }
1203 sr->routing = rn;
1204 return TRUE;
1205 }
1206
1207 /* install or remove eroute for SA Group */
1208 static bool sag_eroute(struct state *st, struct spd_route *sr,
1209 unsigned op, const char *opname)
1210 {
1211 u_int inner_proto, inner_satype;
1212 ipsec_spi_t inner_spi = 0;
1213 ipsec_sa_cfg_t sa = {
1214 .mode = MODE_TRANSPORT,
1215 };
1216 bool tunnel = FALSE;
1217
1218 if (st->st_ah.present)
1219 {
1220 inner_spi = st->st_ah.attrs.spi;
1221 inner_proto = SA_AH;
1222 inner_satype = SADB_SATYPE_AH;
1223 sa.ah.use = TRUE;
1224 sa.ah.spi = inner_spi;
1225 tunnel |= st->st_ah.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL;
1226 }
1227
1228 if (st->st_esp.present)
1229 {
1230 inner_spi = st->st_esp.attrs.spi;
1231 inner_proto = SA_ESP;
1232 inner_satype = SADB_SATYPE_ESP;
1233 sa.esp.use = TRUE;
1234 sa.esp.spi = inner_spi;
1235 tunnel |= st->st_esp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL;
1236 }
1237
1238 if (st->st_ipcomp.present)
1239 {
1240 inner_spi = st->st_ipcomp.attrs.spi;
1241 inner_proto = SA_COMP;
1242 inner_satype = SADB_X_SATYPE_COMP;
1243 sa.ipcomp.transform = st->st_ipcomp.attrs.transid;
1244 sa.ipcomp.cpi = htons(ntohl(inner_spi));
1245 tunnel |= st->st_ipcomp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL;
1246 }
1247
1248 if (!sa.ah.use && !sa.esp.use && !sa.ipcomp.transform)
1249 {
1250 impossible(); /* no transform at all! */
1251 }
1252
1253 if (tunnel)
1254 {
1255 inner_spi = st->st_tunnel_out_spi;
1256 inner_proto = SA_IPIP;
1257 inner_satype = SADB_X_SATYPE_IPIP;
1258 sa.mode = MODE_TUNNEL;
1259 }
1260
1261 sa.reqid = sr->reqid;
1262
1263 return eroute_connection(sr, inner_spi, inner_proto, inner_satype,
1264 &sa, op, opname);
1265 }
1266
1267 /* compute a (host-order!) SPI to implement the policy in connection c */
1268 ipsec_spi_t
1269 shunt_policy_spi(connection_t *c, bool prospective)
1270 {
1271 /* note: these are in host order :-( */
1272 static const ipsec_spi_t shunt_spi[] =
1273 {
1274 SPI_TRAP, /* --initiateontraffic */
1275 SPI_PASS, /* --pass */
1276 SPI_DROP, /* --drop */
1277 SPI_REJECT, /* --reject */
1278 };
1279
1280 static const ipsec_spi_t fail_spi[] =
1281 {
1282 0, /* --none*/
1283 SPI_PASS, /* --failpass */
1284 SPI_DROP, /* --faildrop */
1285 SPI_REJECT, /* --failreject */
1286 };
1287
1288 return prospective
1289 ? shunt_spi[(c->policy & POLICY_SHUNT_MASK) >> POLICY_SHUNT_SHIFT]
1290 : fail_spi[(c->policy & POLICY_FAIL_MASK) >> POLICY_FAIL_SHIFT];
1291 }
1292
1293 /* Add/replace/delete a shunt eroute.
1294 * Such an eroute determines the fate of packets without the use
1295 * of any SAs. These are defaults, in effect.
1296 * If a negotiation has not been attempted, use %trap.
1297 * If negotiation has failed, the choice between %trap/%pass/%drop/%reject
1298 * is specified in the policy of connection c.
1299 */
1300 static bool shunt_eroute(connection_t *c, struct spd_route *sr,
1301 enum routing_t rt_kind,
1302 unsigned int op, const char *opname)
1303 {
1304 /* We are constructing a special SAID for the eroute.
1305 * The destination doesn't seem to matter, but the family does.
1306 * The protocol is SA_INT -- mark this as shunt.
1307 * The satype has no meaning, but is required for PF_KEY header!
1308 * The SPI signifies the kind of shunt.
1309 */
1310 ipsec_spi_t spi = shunt_policy_spi(c, rt_kind == RT_ROUTED_PROSPECTIVE);
1311 bool ok;
1312
1313 if (spi == 0)
1314 {
1315 /* we're supposed to end up with no eroute: rejig op and opname */
1316 switch (op)
1317 {
1318 case ERO_REPLACE:
1319 /* replace with nothing == delete */
1320 op = ERO_DELETE;
1321 opname = "delete";
1322 break;
1323 case ERO_ADD:
1324 /* add nothing == do nothing */
1325 return TRUE;
1326 case ERO_DELETE:
1327 /* delete remains delete */
1328 break;
1329 default:
1330 bad_case(op);
1331 }
1332 }
1333 if (sr->routing == RT_ROUTED_ECLIPSED && c->kind == CK_TEMPLATE)
1334 {
1335 /* We think that we have an eroute, but we don't.
1336 * Adjust the request and account for eclipses.
1337 */
1338 passert(eclipsable(sr));
1339 switch (op)
1340 {
1341 case ERO_REPLACE:
1342 /* really an add */
1343 op = ERO_ADD;
1344 opname = "replace eclipsed";
1345 eclipse_count--;
1346 break;
1347 case ERO_DELETE:
1348 /* delete unnecessary: we don't actually have an eroute */
1349 eclipse_count--;
1350 return TRUE;
1351 case ERO_ADD:
1352 default:
1353 bad_case(op);
1354 }
1355 }
1356 else if (eclipse_count > 0 && op == ERO_DELETE && eclipsable(sr))
1357 {
1358 /* maybe we are uneclipsing something */
1359 struct spd_route *esr;
1360 connection_t *ue = eclipsed(c, &esr);
1361
1362 if (ue != NULL)
1363 {
1364 esr->routing = RT_ROUTED_PROSPECTIVE;
1365 return shunt_eroute(ue, esr
1366 , RT_ROUTED_PROSPECTIVE, ERO_REPLACE, "restoring eclipsed");
1367 }
1368 }
1369
1370 ok = raw_eroute(&c->spd.that.host_addr, &c->spd.that.client,
1371 &c->spd.this.host_addr, &c->spd.this.client, htonl(spi),
1372 SA_INT, SADB_X_SATYPE_INT, 0, &null_ipsec_sa, 0,
1373 op | (SADB_X_SAFLAGS_INFLOW << ERO_FLAG_SHIFT), opname);
1374
1375 return eroute_connection(sr, htonl(spi), SA_INT, SADB_X_SATYPE_INT,
1376 &null_ipsec_sa, op, opname) && ok;
1377 }
1378
1379 static bool setup_half_ipsec_sa(struct state *st, bool inbound)
1380 {
1381 host_t *host_src, *host_dst;
1382 connection_t *c = st->st_connection;
1383 struct end *src, *dst;
1384 ipsec_mode_t mode = MODE_TRANSPORT;
1385 ipsec_sa_cfg_t sa = { .mode = 0 };
1386 lifetime_cfg_t lt_none = { .time = { .rekey = 0 } };
1387 mark_t mark_none = { 0, 0 };
1388 bool ok = TRUE;
1389 /* SPIs, saved for undoing, if necessary */
1390 struct kernel_sa said[EM_MAXRELSPIS], *said_next = said;
1391 if (inbound)
1392 {
1393 src = &c->spd.that;
1394 dst = &c->spd.this;
1395 }
1396 else
1397 {
1398 src = &c->spd.this;
1399 dst = &c->spd.that;
1400 }
1401
1402 host_src = host_create_from_sockaddr((sockaddr_t*)&src->host_addr);
1403 host_dst = host_create_from_sockaddr((sockaddr_t*)&dst->host_addr);
1404
1405 if (st->st_ah.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL
1406 || st->st_esp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL
1407 || st->st_ipcomp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1408 {
1409 mode = MODE_TUNNEL;
1410 }
1411
1412 sa.mode = mode;
1413 sa.reqid = c->spd.reqid;
1414
1415 memset(said, 0, sizeof(said));
1416
1417 /* set up IPCOMP SA, if any */
1418
1419 if (st->st_ipcomp.present)
1420 {
1421 ipsec_spi_t ipcomp_spi = inbound ? st->st_ipcomp.our_spi
1422 : st->st_ipcomp.attrs.spi;
1423
1424 switch (st->st_ipcomp.attrs.transid)
1425 {
1426 case IPCOMP_DEFLATE:
1427 break;
1428
1429 default:
1430 loglog(RC_LOG_SERIOUS, "IPCOMP transform %s not implemented",
1431 enum_name(&ipcomp_transformid_names,
1432 st->st_ipcomp.attrs.transid));
1433 goto fail;
1434 }
1435
1436 sa.ipcomp.cpi = htons(ntohl(ipcomp_spi));
1437 sa.ipcomp.transform = st->st_ipcomp.attrs.transid;
1438
1439 said_next->spi = ipcomp_spi;
1440 said_next->proto = IPPROTO_COMP;
1441
1442 if (hydra->kernel_interface->add_sa(hydra->kernel_interface, host_src,
1443 host_dst, ipcomp_spi, said_next->proto, c->spd.reqid,
1444 mark_none, &lt_none, ENCR_UNDEFINED, chunk_empty,
1445 AUTH_UNDEFINED, chunk_empty, mode,
1446 st->st_ipcomp.attrs.transid, 0 /* cpi */, FALSE,
1447 inbound, NULL, NULL) != SUCCESS)
1448 {
1449 goto fail;
1450 }
1451 said_next++;
1452 mode = MODE_TRANSPORT;
1453 }
1454
1455 /* set up ESP SA, if any */
1456
1457 if (st->st_esp.present)
1458 {
1459 ipsec_spi_t esp_spi = inbound ? st->st_esp.our_spi
1460 : st->st_esp.attrs.spi;
1461 u_char *esp_dst_keymat = inbound ? st->st_esp.our_keymat
1462 : st->st_esp.peer_keymat;
1463 bool encap = st->nat_traversal & NAT_T_DETECTED;
1464 encryption_algorithm_t enc_alg;
1465 integrity_algorithm_t auth_alg;
1466 const struct esp_info *ei;
1467 chunk_t enc_key, auth_key;
1468 u_int16_t key_len;
1469
1470 if ((ei = kernel_alg_esp_info(st->st_esp.attrs.transid,
1471 st->st_esp.attrs.auth)) == NULL)
1472 {
1473 loglog(RC_LOG_SERIOUS, "ESP transform %s / auth %s"
1474 " not implemented yet",
1475 enum_name(&esp_transform_names, st->st_esp.attrs.transid),
1476 enum_name(&auth_alg_names, st->st_esp.attrs.auth));
1477 goto fail;
1478 }
1479
1480 key_len = st->st_esp.attrs.key_len / 8;
1481 if (key_len)
1482 {
1483 /* XXX: must change to check valid _range_ key_len */
1484 if (key_len > ei->enckeylen)
1485 {
1486 loglog(RC_LOG_SERIOUS, "ESP transform %s: key_len=%d > %d",
1487 enum_name(&esp_transform_names, st->st_esp.attrs.transid),
1488 (int)key_len, (int)ei->enckeylen);
1489 goto fail;
1490 }
1491 }
1492 else
1493 {
1494 key_len = ei->enckeylen;
1495 }
1496
1497 switch (ei->transid)
1498 {
1499 case ESP_3DES:
1500 /* 168 bits in kernel, need 192 bits for keymat_len */
1501 if (key_len == 21)
1502 {
1503 key_len = 24;
1504 }
1505 break;
1506 case ESP_DES:
1507 /* 56 bits in kernel, need 64 bits for keymat_len */
1508 if (key_len == 7)
1509 {
1510 key_len = 8;
1511 }
1512 break;
1513 case ESP_AES_CCM_8:
1514 case ESP_AES_CCM_12:
1515 case ESP_AES_CCM_16:
1516 key_len += 3;
1517 break;
1518 case ESP_AES_GCM_8:
1519 case ESP_AES_GCM_12:
1520 case ESP_AES_GCM_16:
1521 case ESP_AES_CTR:
1522 case ESP_AES_GMAC:
1523 key_len += 4;
1524 break;
1525 default:
1526 break;
1527 }
1528
1529 if (encap)
1530 {
1531 host_src->set_port(host_src, src->host_port);
1532 host_dst->set_port(host_dst, dst->host_port);
1533 // st->nat_oa is currently unused
1534 }
1535
1536 /* divide up keying material */
1537 enc_alg = encryption_algorithm_from_esp(st->st_esp.attrs.transid);
1538 enc_key.ptr = esp_dst_keymat;
1539 enc_key.len = key_len;
1540 auth_alg = integrity_algorithm_from_esp(st->st_esp.attrs.auth);
1541 auth_alg = auth_alg ? : AUTH_UNDEFINED;
1542 auth_key.ptr = esp_dst_keymat + key_len;
1543 auth_key.len = ei->authkeylen;
1544
1545 sa.esp.use = TRUE;
1546 sa.esp.spi = esp_spi;
1547
1548 said_next->spi = esp_spi;
1549 said_next->proto = IPPROTO_ESP;
1550
1551 if (hydra->kernel_interface->add_sa(hydra->kernel_interface, host_src,
1552 host_dst, esp_spi, said_next->proto, c->spd.reqid,
1553 mark_none, &lt_none, enc_alg, enc_key,
1554 auth_alg, auth_key, mode, IPCOMP_NONE, 0 /* cpi */,
1555 encap, inbound, NULL, NULL) != SUCCESS)
1556 {
1557 goto fail;
1558 }
1559 said_next++;
1560 mode = MODE_TRANSPORT;
1561 }
1562
1563 /* set up AH SA, if any */
1564
1565 if (st->st_ah.present)
1566 {
1567 ipsec_spi_t ah_spi = inbound ? st->st_ah.our_spi
1568 : st->st_ah.attrs.spi;
1569 u_char *ah_dst_keymat = inbound ? st->st_ah.our_keymat
1570 : st->st_ah.peer_keymat;
1571 integrity_algorithm_t auth_alg;
1572 chunk_t auth_key;
1573
1574 auth_alg = integrity_algorithm_from_esp(st->st_ah.attrs.auth);
1575 auth_key.ptr = ah_dst_keymat;
1576 auth_key.len = st->st_ah.keymat_len;
1577
1578 sa.ah.use = TRUE;
1579 sa.ah.spi = ah_spi;
1580
1581 said_next->spi = ah_spi;
1582 said_next->proto = IPPROTO_AH;
1583
1584 if (hydra->kernel_interface->add_sa(hydra->kernel_interface, host_src,
1585 host_dst, ah_spi, said_next->proto, c->spd.reqid,
1586 mark_none, &lt_none, ENCR_UNDEFINED, chunk_empty,
1587 auth_alg, auth_key, mode, IPCOMP_NONE, 0 /* cpi */,
1588 FALSE, inbound, NULL, NULL) != SUCCESS)
1589 {
1590 goto fail;
1591 }
1592 said_next++;
1593 mode = MODE_TRANSPORT;
1594 }
1595
1596 if (inbound && c->spd.eroute_owner == SOS_NOBODY)
1597 {
1598 (void) raw_eroute(&src->host_addr, &src->client, &dst->host_addr,
1599 &dst->client, 256, SA_IPIP, SADB_SATYPE_UNSPEC,
1600 c->spd.this.protocol, &sa, 0, ERO_ADD_INBOUND,
1601 "add inbound");
1602 }
1603
1604 goto cleanup;
1605
1606 fail:
1607 /* undo the done SPIs */
1608 while (said_next-- != said)
1609 {
1610 hydra->kernel_interface->del_sa(hydra->kernel_interface, host_src,
1611 host_dst, said_next->spi,
1612 said_next->proto, 0 /* cpi */,
1613 mark_none);
1614 }
1615 ok = FALSE;
1616
1617 cleanup:
1618 host_src->destroy(host_src);
1619 host_dst->destroy(host_dst);
1620 return ok;
1621 }
1622
1623 static bool teardown_half_ipsec_sa(struct state *st, bool inbound)
1624 {
1625 connection_t *c = st->st_connection;
1626 const struct end *src, *dst;
1627 host_t *host_src, *host_dst;
1628 ipsec_spi_t spi;
1629 mark_t mark_none = { 0, 0 };
1630 bool result = TRUE;
1631
1632 if (inbound)
1633 {
1634 src = &c->spd.that;
1635 dst = &c->spd.this;
1636
1637 if (c->spd.eroute_owner == SOS_NOBODY)
1638 {
1639 (void) raw_eroute(&src->host_addr, &src->client, &dst->host_addr,
1640 &dst->client, 256, IPSEC_PROTO_ANY,
1641 SADB_SATYPE_UNSPEC, c->spd.this.protocol,
1642 &null_ipsec_sa, 0, ERO_DEL_INBOUND,
1643 "delete inbound");
1644 }
1645 }
1646 else
1647 {
1648 src = &c->spd.this;
1649 dst = &c->spd.that;
1650 }
1651
1652 host_src = host_create_from_sockaddr((sockaddr_t*)&src->host_addr);
1653 host_dst = host_create_from_sockaddr((sockaddr_t*)&dst->host_addr);
1654
1655 if (st->st_ah.present)
1656 {
1657 spi = inbound ? st->st_ah.our_spi : st->st_ah.attrs.spi;
1658 result &= hydra->kernel_interface->del_sa(hydra->kernel_interface,
1659 host_src, host_dst, spi, IPPROTO_AH,
1660 0 /* cpi */, mark_none) == SUCCESS;
1661 }
1662
1663 if (st->st_esp.present)
1664 {
1665 spi = inbound ? st->st_esp.our_spi : st->st_esp.attrs.spi;
1666 result &= hydra->kernel_interface->del_sa(hydra->kernel_interface,
1667 host_src, host_dst, spi, IPPROTO_ESP,
1668 0 /* cpi */, mark_none) == SUCCESS;
1669 }
1670
1671 if (st->st_ipcomp.present)
1672 {
1673 spi = inbound ? st->st_ipcomp.our_spi : st->st_ipcomp.attrs.spi;
1674 result &= hydra->kernel_interface->del_sa(hydra->kernel_interface,
1675 host_src, host_dst, spi, IPPROTO_COMP,
1676 0 /* cpi */, mark_none) == SUCCESS;
1677 }
1678
1679 host_src->destroy(host_src);
1680 host_dst->destroy(host_dst);
1681
1682 return result;
1683 }
1684
1685 /*
1686 * get information about a given sa
1687 */
1688 bool get_sa_info(struct state *st, bool inbound, u_int *bytes, time_t *use_time)
1689 {
1690 connection_t *c = st->st_connection;
1691 traffic_selector_t *ts_src = NULL, *ts_dst = NULL;
1692 host_t *host_src = NULL, *host_dst = NULL;
1693 const struct end *src, *dst;
1694 ipsec_spi_t spi;
1695 mark_t mark_none = { 0, 0 };
1696 u_int64_t bytes_kernel = 0;
1697 bool result = FALSE;
1698
1699 *use_time = UNDEFINED_TIME;
1700
1701 if (!st->st_esp.present)
1702 {
1703 goto failed;
1704 }
1705
1706 if (inbound)
1707 {
1708 src = &c->spd.that;
1709 dst = &c->spd.this;
1710 spi = st->st_esp.our_spi;
1711 }
1712 else
1713 {
1714 src = &c->spd.this;
1715 dst = &c->spd.that;
1716 spi = st->st_esp.attrs.spi;
1717 }
1718
1719 host_src = host_create_from_sockaddr((sockaddr_t*)&src->host_addr);
1720 host_dst = host_create_from_sockaddr((sockaddr_t*)&dst->host_addr);
1721
1722 switch(hydra->kernel_interface->query_sa(hydra->kernel_interface, host_src,
1723 host_dst, spi, IPPROTO_ESP,
1724 mark_none, &bytes_kernel))
1725 {
1726 case FAILED:
1727 goto failed;
1728 case SUCCESS:
1729 *bytes = bytes_kernel;
1730 break;
1731 case NOT_SUPPORTED:
1732 default:
1733 break;
1734 }
1735
1736 if (st->st_serialno == c->spd.eroute_owner)
1737 {
1738 u_int32_t time_kernel;
1739
1740 ts_src = traffic_selector_from_subnet(&src->client, src->protocol);
1741 ts_dst = traffic_selector_from_subnet(&dst->client, dst->protocol);
1742
1743 if (hydra->kernel_interface->query_policy(hydra->kernel_interface,
1744 ts_src, ts_dst, inbound ? POLICY_IN : POLICY_OUT,
1745 mark_none, &time_kernel) != SUCCESS)
1746 {
1747 goto failed;
1748 }
1749 *use_time = time_kernel;
1750
1751 if (inbound &&
1752 st->st_esp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1753 {
1754 if (hydra->kernel_interface->query_policy(hydra->kernel_interface,
1755 ts_src, ts_dst, POLICY_FWD, mark_none,
1756 &time_kernel) != SUCCESS)
1757 {
1758 goto failed;
1759 }
1760 *use_time = max(*use_time, time_kernel);
1761 }
1762 }
1763
1764 result = TRUE;
1765
1766 failed:
1767 DESTROY_IF(host_src);
1768 DESTROY_IF(host_dst);
1769 DESTROY_IF(ts_src);
1770 DESTROY_IF(ts_dst);
1771 return result;
1772 }
1773
1774 const struct kernel_ops *kernel_ops;
1775
1776 #endif /* KLIPS */
1777
1778 void init_kernel(void)
1779 {
1780 #ifdef KLIPS
1781
1782 if (no_klips)
1783 {
1784 kernel_ops = &noklips_kernel_ops;
1785 return;
1786 }
1787
1788 init_pfkey();
1789
1790 kernel_ops = &klips_kernel_ops;
1791
1792 #if defined(linux) && defined(KERNEL26_SUPPORT)
1793 {
1794 bool linux_ipsec = 0;
1795 struct stat buf;
1796
1797 linux_ipsec = (stat("/proc/net/pfkey", &buf) == 0);
1798 if (linux_ipsec)
1799 {
1800 plog("Using Linux 2.6 IPsec interface code");
1801 kernel_ops = &linux_kernel_ops;
1802 }
1803 else
1804 {
1805 plog("Using KLIPS IPsec interface code");
1806 }
1807 }
1808 #endif
1809
1810 if (kernel_ops->init)
1811 {
1812 kernel_ops->init();
1813 }
1814
1815 /* register SA types that we can negotiate */
1816 can_do_IPcomp = FALSE; /* until we get a response from KLIPS */
1817 kernel_ops->pfkey_register();
1818 #endif
1819 }
1820
1821 /* Note: install_inbound_ipsec_sa is only used by the Responder.
1822 * The Responder will subsequently use install_ipsec_sa for the outbound.
1823 * The Initiator uses install_ipsec_sa to install both at once.
1824 */
1825 bool install_inbound_ipsec_sa(struct state *st)
1826 {
1827 connection_t *const c = st->st_connection;
1828
1829 /* If our peer has a fixed-address client, check if we already
1830 * have a route for that client that conflicts. We will take this
1831 * as proof that that route and the connections using it are
1832 * obsolete and should be eliminated. Interestingly, this is
1833 * the only case in which we can tell that a connection is obsolete.
1834 */
1835 passert(c->kind == CK_PERMANENT || c->kind == CK_INSTANCE);
1836 if (c->spd.that.has_client)
1837 {
1838 for (;;)
1839 {
1840 struct spd_route *esr;
1841 connection_t *o = route_owner(c, &esr, NULL, NULL);
1842
1843 if (o == NULL)
1844 {
1845 break; /* nobody has a route */
1846 }
1847
1848 /* note: we ignore the client addresses at this end */
1849 if (sameaddr(&o->spd.that.host_addr, &c->spd.that.host_addr) &&
1850 o->interface == c->interface)
1851 {
1852 break; /* existing route is compatible */
1853 }
1854
1855 if (o->kind == CK_TEMPLATE && streq(o->name, c->name))
1856 {
1857 break; /* ??? is this good enough?? */
1858 }
1859
1860 loglog(RC_LOG_SERIOUS, "route to peer's client conflicts with \"%s\" %s; releasing old connection to free the route"
1861 , o->name, ip_str(&o->spd.that.host_addr));
1862 release_connection(o, FALSE);
1863 }
1864 }
1865
1866 DBG(DBG_CONTROL, DBG_log("install_inbound_ipsec_sa() checking if we can route"));
1867 /* check that we will be able to route and eroute */
1868 switch (could_route(c))
1869 {
1870 case route_easy:
1871 case route_nearconflict:
1872 break;
1873 default:
1874 return FALSE;
1875 }
1876
1877 #ifdef KLIPS
1878 /* (attempt to) actually set up the SAs */
1879 return setup_half_ipsec_sa(st, TRUE);
1880 #else /* !KLIPS */
1881 DBG(DBG_CONTROL, DBG_log("install_inbound_ipsec_sa()"));
1882 return TRUE;
1883 #endif /* !KLIPS */
1884 }
1885
1886 /* Install a route and then a prospective shunt eroute or an SA group eroute.
1887 * Assumption: could_route gave a go-ahead.
1888 * Any SA Group must have already been created.
1889 * On failure, steps will be unwound.
1890 */
1891 bool route_and_eroute(connection_t *c USED_BY_KLIPS,
1892 struct spd_route *sr USED_BY_KLIPS,
1893 struct state *st USED_BY_KLIPS)
1894 {
1895 #ifdef KLIPS
1896 struct spd_route *esr;
1897 struct spd_route *rosr;
1898 connection_t *ero /* who, if anyone, owns our eroute? */
1899 , *ro = route_owner(c, &rosr, &ero, &esr);
1900 bool eroute_installed = FALSE
1901 , firewall_notified = FALSE
1902 , route_installed = FALSE;
1903
1904 connection_t *ero_top;
1905 struct bare_shunt **bspp;
1906
1907 DBG(DBG_CONTROLMORE,
1908 DBG_log("route_and_eroute with c: %s (next: %s) ero:%s esr:{%p} ro:%s rosr:{%p} and state: %lu"
1909 , c->name
1910 , (c->policy_next ? c->policy_next->name : "none")
1911 , ero ? ero->name : "null"
1912 , esr
1913 , ro ? ro->name : "null"
1914 , rosr
1915 , st ? st->st_serialno : 0));
1916
1917 /* look along the chain of policies for one with the same name */
1918 ero_top = ero;
1919
1920 #if 0
1921 /* XXX - mcr this made sense before, and likely will make sense
1922 * again, so I'l leaving this to remind me what is up */
1923 if (ero!= NULL && ero->routing == RT_UNROUTED_KEYED)
1924 ero = NULL;
1925
1926 for (ero2 = ero; ero2 != NULL; ero2 = ero->policy_next)
1927 if ((ero2->kind == CK_TEMPLATE || ero2->kind==CK_SECONDARY)
1928 && streq(ero2->name, c->name))
1929 break;
1930 #endif
1931
1932 bspp = (ero == NULL)
1933 ? bare_shunt_ptr(&sr->this.client, &sr->that.client, sr->this.protocol)
1934 : NULL;
1935
1936 /* install the eroute */
1937
1938 passert(bspp == NULL || ero == NULL); /* only one non-NULL */
1939
1940 if (bspp != NULL || ero != NULL)
1941 {
1942 /* We're replacing an eroute */
1943
1944 /* if no state provided, then install a shunt for later */
1945 if (st == NULL)
1946 {
1947 eroute_installed = shunt_eroute(c, sr, RT_ROUTED_PROSPECTIVE
1948 , ERO_REPLACE, "replace");
1949 }
1950 else
1951 {
1952 eroute_installed = sag_eroute(st, sr, ERO_REPLACE, "replace");
1953 }
1954 #if 0
1955 /* XXX - MCR. I previously felt that this was a bogus check */
1956 if (ero != NULL && ero != c && esr != sr)
1957 {
1958 /* By elimination, we must be eclipsing ero. Check. */
1959 passert(ero->kind == CK_TEMPLATE && streq(ero->name, c->name));
1960 passert(LHAS(LELEM(RT_ROUTED_PROSPECTIVE) | LELEM(RT_ROUTED_ECLIPSED)
1961 , esr->routing));
1962 passert(samesubnet(&esr->this.client, &sr->this.client)
1963 && samesubnet(&esr->that.client, &sr->that.client));
1964 }
1965 #endif
1966 /* remember to free bspp iff we make it out of here alive */
1967 }
1968 else
1969 {
1970 /* we're adding an eroute */
1971
1972 /* if no state provided, then install a shunt for later */
1973 if (st == NULL)
1974 {
1975 eroute_installed = shunt_eroute(c, sr, RT_ROUTED_PROSPECTIVE
1976 , ERO_ADD, "add");
1977 }
1978 else
1979 {
1980 eroute_installed = sag_eroute(st, sr, ERO_ADD, "add");
1981 }
1982 }
1983
1984 /* notify the firewall of a new tunnel */
1985
1986 if (eroute_installed)
1987 {
1988 /* do we have to notify the firewall? Yes, if we are installing
1989 * a tunnel eroute and the firewall wasn't notified
1990 * for a previous tunnel with the same clients. Any Previous
1991 * tunnel would have to be for our connection, so the actual
1992 * test is simple.
1993 */
1994 firewall_notified = st == NULL /* not a tunnel eroute */
1995 || sr->eroute_owner != SOS_NOBODY /* already notified */
1996 || do_command(c, sr, "up"); /* go ahead and notify */
1997 }
1998
1999 /* install the route */
2000
2001 DBG(DBG_CONTROL,
2002 DBG_log("route_and_eroute: firewall_notified: %s"
2003 , firewall_notified ? "true" : "false"));
2004 if (!firewall_notified)
2005 {
2006 /* we're in trouble -- don't do routing */
2007 }
2008 else if (ro == NULL)
2009 {
2010 /* a new route: no deletion required, but preparation is */
2011 (void) do_command(c, sr, "prepare"); /* just in case; ignore failure */
2012 route_installed = do_command(c, sr, "route");
2013 }
2014 else if (routed(sr->routing) || routes_agree(ro, c))
2015 {
2016 route_installed = TRUE; /* nothing to be done */
2017 }
2018 else
2019 {
2020 /* Some other connection must own the route
2021 * and the route must disagree. But since could_route
2022 * must have allowed our stealing it, we'll do so.
2023 *
2024 * A feature of LINUX allows us to install the new route
2025 * before deleting the old if the nexthops differ.
2026 * This reduces the "window of vulnerability" when packets
2027 * might flow in the clear.
2028 */
2029 if (sameaddr(&sr->this.host_nexthop, &esr->this.host_nexthop))
2030 {
2031 (void) do_command(ro, sr, "unroute");
2032 route_installed = do_command(c, sr, "route");
2033 }
2034 else
2035 {
2036 route_installed = do_command(c, sr, "route");
2037 (void) do_command(ro, sr, "unroute");
2038 }
2039
2040 /* record unrouting */
2041 if (route_installed)
2042 {
2043 do {
2044 passert(!erouted(rosr->routing));
2045 rosr->routing = RT_UNROUTED;
2046
2047 /* no need to keep old value */
2048 ro = route_owner(c, &rosr, NULL, NULL);
2049 } while (ro != NULL);
2050 }
2051 }
2052
2053 /* all done -- clean up */
2054 if (route_installed)
2055 {
2056 /* Success! */
2057
2058 if (bspp != NULL)
2059 {
2060 free_bare_shunt(bspp);
2061 }
2062 else if (ero != NULL && ero != c)
2063 {
2064 /* check if ero is an ancestor of c. */
2065 connection_t *ero2;
2066
2067 for (ero2 = c; ero2 != NULL && ero2 != c; ero2 = ero2->policy_next)
2068 ;
2069
2070 if (ero2 == NULL)
2071 {
2072 /* By elimination, we must be eclipsing ero. Checked above. */
2073 if (ero->spd.routing != RT_ROUTED_ECLIPSED)
2074 {
2075 ero->spd.routing = RT_ROUTED_ECLIPSED;
2076 eclipse_count++;
2077 }
2078 }
2079 }
2080
2081 if (st == NULL)
2082 {
2083 passert(sr->eroute_owner == SOS_NOBODY);
2084 sr->routing = RT_ROUTED_PROSPECTIVE;
2085 }
2086 else
2087 {
2088 char cib[CONN_INST_BUF];
2089 sr->routing = RT_ROUTED_TUNNEL;
2090
2091 DBG(DBG_CONTROL,
2092 DBG_log("route_and_eroute: instance \"%s\"%s, setting eroute_owner {spd=%p,sr=%p} to #%ld (was #%ld) (newest_ipsec_sa=#%ld)"
2093 , st->st_connection->name
2094 , (fmt_conn_instance(st->st_connection, cib), cib)
2095 , &st->st_connection->spd, sr
2096 , st->st_serialno
2097 , sr->eroute_owner
2098 , st->st_connection->newest_ipsec_sa));
2099 sr->eroute_owner = st->st_serialno;
2100 }
2101
2102 return TRUE;
2103 }
2104 else
2105 {
2106 /* Failure! Unwind our work. */
2107 if (firewall_notified && sr->eroute_owner == SOS_NOBODY)
2108 (void) do_command(c, sr, "down");
2109
2110 if (eroute_installed)
2111 {
2112 /* Restore original eroute, if we can.
2113 * Since there is nothing much to be done if the restoration
2114 * fails, ignore success or failure.
2115 */
2116 if (bspp != NULL)
2117 {
2118 /* Restore old bare_shunt.
2119 * I don't think that this case is very likely.
2120 * Normally a bare shunt would have been assigned
2121 * to a connection before we've gotten this far.
2122 */
2123 struct bare_shunt *bs = *bspp;
2124
2125 (void) raw_eroute(&bs->said.dst, /* should be useless */
2126 &bs->ours,
2127 &bs->said.dst, /* should be useless */
2128 &bs->his,
2129 bs->said.spi, /* network order */
2130 SA_INT, SADB_X_SATYPE_INT, 0,
2131 &null_ipsec_sa, SHUNT_PATIENCE,
2132 ERO_REPLACE, "restore");
2133 }
2134 else if (ero != NULL)
2135 {
2136 /* restore ero's former glory */
2137 if (esr->eroute_owner == SOS_NOBODY)
2138 {
2139 /* note: normal or eclipse case */
2140 (void) shunt_eroute(ero, esr
2141 , esr->routing, ERO_REPLACE, "restore");
2142 }
2143 else
2144 {
2145 /* Try to find state that owned eroute.
2146 * Don't do anything if it cannot be found.
2147 * This case isn't likely since we don't run
2148 * the updown script when replacing a SA group
2149 * with its successor (for the same conn).
2150 */
2151 struct state *ost = state_with_serialno(esr->eroute_owner);
2152
2153 if (ost != NULL)
2154 (void) sag_eroute(ost, esr, ERO_REPLACE, "restore");
2155 }
2156 }
2157 else
2158 {
2159 /* there was no previous eroute: delete whatever we installed */
2160 if (st == NULL)
2161 {
2162 (void) shunt_eroute(c, sr, sr->routing, ERO_DELETE, "delete");
2163 }
2164 else
2165 {
2166 (void) sag_eroute(st, sr, ERO_DELETE, "delete");
2167 }
2168 }
2169 }
2170
2171 return FALSE;
2172 }
2173 #else /* !KLIPS */
2174 return TRUE;
2175 #endif /* !KLIPS */
2176 }
2177
2178 bool install_ipsec_sa(struct state *st, bool inbound_also USED_BY_KLIPS)
2179 {
2180 #ifdef KLIPS
2181 struct spd_route *sr;
2182
2183 DBG(DBG_CONTROL, DBG_log("install_ipsec_sa() for #%ld: %s"
2184 , st->st_serialno
2185 , inbound_also?
2186 "inbound and outbound" : "outbound only"));
2187
2188 switch (could_route(st->st_connection))
2189 {
2190 case route_easy:
2191 case route_nearconflict:
2192 break;
2193 default:
2194 return FALSE;
2195 }
2196
2197 /* (attempt to) actually set up the SA group */
2198 if ((inbound_also && !setup_half_ipsec_sa(st, TRUE)) ||
2199 !setup_half_ipsec_sa(st, FALSE))
2200 {
2201 return FALSE;
2202 }
2203
2204 for (sr = &st->st_connection->spd; sr != NULL; sr = sr->next)
2205 {
2206 DBG(DBG_CONTROL, DBG_log("sr for #%ld: %s"
2207 , st->st_serialno
2208 , enum_name(&routing_story, sr->routing)));
2209
2210 /*
2211 * if the eroute owner is not us, then make it us.
2212 * See test co-terminal-02, pluto-rekey-01, pluto-unit-02/oppo-twice
2213 */
2214 pexpect(sr->eroute_owner == SOS_NOBODY
2215 || sr->routing >= RT_ROUTED_TUNNEL);
2216
2217 if (sr->eroute_owner != st->st_serialno
2218 && sr->routing != RT_UNROUTED_KEYED)
2219 {
2220 if (!route_and_eroute(st->st_connection, sr, st))
2221 {
2222 delete_ipsec_sa(st, FALSE);
2223 /* XXX go and unroute any SRs that were successfully
2224 * routed already.
2225 */
2226 return FALSE;
2227 }
2228 }
2229 }
2230 #else /* !KLIPS */
2231 DBG(DBG_CONTROL, DBG_log("install_ipsec_sa() %s"
2232 , inbound_also? "inbound and oubound" : "outbound only"));
2233
2234 switch (could_route(st->st_connection))
2235 {
2236 case route_easy:
2237 case route_nearconflict:
2238 break;
2239 default:
2240 return FALSE;
2241 }
2242
2243
2244 #endif /* !KLIPS */
2245
2246 return TRUE;
2247 }
2248
2249 /* delete an IPSEC SA.
2250 * we may not succeed, but we bull ahead anyway because
2251 * we cannot do anything better by recognizing failure
2252 */
2253 void delete_ipsec_sa(struct state *st USED_BY_KLIPS,
2254 bool inbound_only USED_BY_KLIPS)
2255 {
2256 #ifdef KLIPS
2257 if (!inbound_only)
2258 {
2259 /* If the state is the eroute owner, we must adjust
2260 * the routing for the connection.
2261 */
2262 connection_t *c = st->st_connection;
2263 struct spd_route *sr;
2264
2265 passert(st->st_connection);
2266
2267 for (sr = &c->spd; sr; sr = sr->next)
2268 {
2269 if (sr->eroute_owner == st->st_serialno
2270 && sr->routing == RT_ROUTED_TUNNEL)
2271 {
2272 sr->eroute_owner = SOS_NOBODY;
2273
2274 /* Routing should become RT_ROUTED_FAILURE,
2275 * but if POLICY_FAIL_NONE, then we just go
2276 * right back to RT_ROUTED_PROSPECTIVE as if no
2277 * failure happened.
2278 */
2279 sr->routing = (c->policy & POLICY_FAIL_MASK) == POLICY_FAIL_NONE
2280 ? RT_ROUTED_PROSPECTIVE : RT_ROUTED_FAILURE;
2281
2282 (void) do_command(c, sr, "down");
2283 if ((c->policy & POLICY_DONT_REKEY) && c->kind == CK_INSTANCE)
2284 {
2285 /* in this special case, even if the connection
2286 * is still alive (due to an ISAKMP SA),
2287 * we get rid of routing.
2288 * Even though there is still an eroute, the c->routing
2289 * setting will convince unroute_connection to delete it.
2290 * unroute_connection would be upset if c->routing == RT_ROUTED_TUNNEL
2291 */
2292 unroute_connection(c);
2293 }
2294 else
2295 {
2296 (void) shunt_eroute(c, sr, sr->routing, ERO_REPLACE, "replace with shunt");
2297 }
2298 }
2299 }
2300 (void) teardown_half_ipsec_sa(st, FALSE);
2301 }
2302 (void) teardown_half_ipsec_sa(st, TRUE);
2303 #else /* !KLIPS */
2304 DBG(DBG_CONTROL, DBG_log("if I knew how, I'd eroute() and teardown_ipsec_sa()"));
2305 #endif /* !KLIPS */
2306 }
2307
2308 #ifdef KLIPS
2309 static bool update_nat_t_ipsec_esp_sa (struct state *st, bool inbound)
2310 {
2311 connection_t *c = st->st_connection;
2312 host_t *host_src, *host_dst, *new_src, *new_dst;
2313 mark_t mark_none = { 0, 0 };
2314 bool result;
2315 ipsec_spi_t spi = inbound ? st->st_esp.our_spi : st->st_esp.attrs.spi;
2316 struct end *src = inbound ? &c->spd.that : &c->spd.this,
2317 *dst = inbound ? &c->spd.this : &c->spd.that;
2318
2319 host_src = host_create_from_sockaddr((sockaddr_t*)&src->host_addr);
2320 host_dst = host_create_from_sockaddr((sockaddr_t*)&dst->host_addr);
2321
2322 new_src = host_src->clone(host_src);
2323 new_dst = host_dst->clone(host_dst);
2324 new_src->set_port(new_src, src->host_port);
2325 new_dst->set_port(new_dst, dst->host_port);
2326
2327 result = hydra->kernel_interface->update_sa(hydra->kernel_interface,
2328 spi, IPPROTO_ESP, 0 /* cpi */, host_src, host_dst,
2329 new_src, new_dst, TRUE /* encap */, TRUE /* new_encap */,
2330 mark_none) == SUCCESS;
2331
2332 host_src->destroy(host_src);
2333 host_dst->destroy(host_dst);
2334 new_src->destroy(new_src);
2335 new_dst->destroy(new_dst);
2336
2337 return result;
2338 }
2339 #endif
2340
2341 bool update_ipsec_sa (struct state *st USED_BY_KLIPS)
2342 {
2343 #ifdef KLIPS
2344 if (IS_IPSEC_SA_ESTABLISHED(st->st_state))
2345 {
2346 if (st->st_esp.present && (
2347 (!update_nat_t_ipsec_esp_sa (st, TRUE)) ||
2348 (!update_nat_t_ipsec_esp_sa (st, FALSE))))
2349 {
2350 return FALSE;
2351 }
2352 }
2353 else if (IS_ONLY_INBOUND_IPSEC_SA_ESTABLISHED(st->st_state))
2354 {
2355 if (st->st_esp.present && !update_nat_t_ipsec_esp_sa (st, FALSE))
2356 {
2357 return FALSE;
2358 }
2359 }
2360 else
2361 {
2362 DBG_log("assert failed at %s:%d st_state=%d", __FILE__, __LINE__, st->st_state);
2363 return FALSE;
2364 }
2365 return TRUE;
2366 #else /* !KLIPS */
2367 DBG(DBG_CONTROL, DBG_log("if I knew how, I'd update_ipsec_sa()"));
2368 return TRUE;
2369 #endif /* !KLIPS */
2370 }
2371
2372 /* Check if there was traffic on given SA during the last idle_max
2373 * seconds. If TRUE, the SA was idle and DPD exchange should be performed.
2374 * If FALSE, DPD is not necessary. We also return TRUE for errors, as they
2375 * could mean that the SA is broken and needs to be replace anyway.
2376 */
2377 bool was_eroute_idle(struct state *st, time_t idle_max, time_t *idle_time)
2378 {
2379 time_t use_time;
2380 u_int bytes;
2381 int ret = TRUE;
2382
2383 passert(st != NULL);
2384
2385 if (get_sa_info(st, TRUE, &bytes, &use_time) && use_time != UNDEFINED_TIME)
2386 {
2387 *idle_time = time_monotonic(NULL) - use_time;
2388 ret = *idle_time >= idle_max;
2389 }
2390
2391 return ret;
2392 }