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