Implemented Traffic Flow Confidentiality padding in 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 #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 char text_said[SATOT_BUF];
784 bool ok = TRUE, routed = FALSE,
785 deleting = (op & ERO_MASK) == ERO_DELETE,
786 replacing = op & (SADB_X_SAFLAGS_REPLACEFLOW << ERO_FLAG_SHIFT);
787
788 set_text_said(text_said, that_host, spi, proto);
789
790 DBG(DBG_CONTROL | DBG_KERNEL,
791 {
792 int sport = ntohs(portof(&this_client->addr));
793 int dport = ntohs(portof(&that_client->addr));
794 char mybuf[SUBNETTOT_BUF];
795 char peerbuf[SUBNETTOT_BUF];
796
797 subnettot(this_client, 0, mybuf, sizeof(mybuf));
798 subnettot(that_client, 0, peerbuf, sizeof(peerbuf));
799 DBG_log("%s eroute %s:%d -> %s:%d => %s:%d"
800 , opname, mybuf, sport, peerbuf, dport
801 , text_said, transport_proto);
802 });
803
804 if (satype == SADB_X_SATYPE_INT)
805 {
806 switch (ntohl(spi))
807 {
808 case SPI_PASS:
809 type = POLICY_PASS;
810 break;
811 case SPI_DROP:
812 case SPI_REJECT:
813 type = POLICY_DROP;
814 break;
815 case SPI_TRAP:
816 case SPI_TRAPSUBNET:
817 case SPI_HOLD:
818 if (op & (SADB_X_SAFLAGS_INFLOW << ERO_FLAG_SHIFT))
819 {
820 return TRUE;
821 }
822 routed = TRUE;
823 break;
824 }
825 }
826
827 if (op & (SADB_X_SAFLAGS_INFLOW << ERO_FLAG_SHIFT))
828 {
829 dir = POLICY_IN;
830 }
831
832 host_src = host_create_from_sockaddr((sockaddr_t*)this_host);
833 host_dst = host_create_from_sockaddr((sockaddr_t*)that_host);
834 ts_src = traffic_selector_from_subnet(this_client, transport_proto);
835 ts_dst = traffic_selector_from_subnet(that_client, transport_proto);
836
837 if (deleting || replacing)
838 {
839 hydra->kernel_interface->del_policy(hydra->kernel_interface,
840 ts_src, ts_dst, dir, mark, routed);
841 }
842
843 if (!deleting)
844 {
845 ok = hydra->kernel_interface->add_policy(hydra->kernel_interface,
846 host_src, host_dst, ts_src, ts_dst, dir, type, sa,
847 mark, routed) == SUCCESS;
848 }
849
850 if (dir == POLICY_IN)
851 { /* handle forward policy */
852 dir = POLICY_FWD;
853 if (deleting || replacing)
854 {
855 hydra->kernel_interface->del_policy(hydra->kernel_interface,
856 ts_src, ts_dst, dir, mark, routed);
857 }
858
859 if (!deleting && ok &&
860 (sa->mode == MODE_TUNNEL || satype == SADB_X_SATYPE_INT))
861 {
862 ok = hydra->kernel_interface->add_policy(hydra->kernel_interface,
863 host_src, host_dst, ts_src, ts_dst, dir, type, sa,
864 mark, routed) == SUCCESS;
865 }
866 }
867
868 host_src->destroy(host_src);
869 host_dst->destroy(host_dst);
870 ts_src->destroy(ts_src);
871 ts_dst->destroy(ts_dst);
872
873 return ok;
874 }
875
876 static bool eroute_connection(struct spd_route *sr, ipsec_spi_t spi,
877 unsigned int proto, unsigned int satype,
878 ipsec_sa_cfg_t *sa, unsigned int op,
879 const char *opname)
880 {
881 const ip_address *peer = &sr->that.host_addr;
882 char buf2[256];
883 bool ok;
884
885 snprintf(buf2, sizeof(buf2)
886 , "eroute_connection %s", opname);
887
888 if (proto == SA_INT)
889 {
890 peer = aftoinfo(addrtypeof(peer))->any;
891 }
892 ok = raw_eroute(peer, &sr->that.client,
893 &sr->this.host_addr, &sr->this.client, sr->mark_in,
894 spi, proto, satype, sr->this.protocol,
895 sa, op | (SADB_X_SAFLAGS_INFLOW << ERO_FLAG_SHIFT), buf2);
896 return raw_eroute(&sr->this.host_addr, &sr->this.client, peer,
897 &sr->that.client, sr->mark_out, spi, proto, satype,
898 sr->this.protocol, sa, op, buf2) && ok;
899 }
900
901 /* assign a bare hold to a connection */
902
903 bool assign_hold(connection_t *c USED_BY_DEBUG, struct spd_route *sr,
904 int transport_proto,
905 const ip_address *src,
906 const ip_address *dst)
907 {
908 /* either the automatically installed %hold eroute is broad enough
909 * or we try to add a broader one and delete the automatic one.
910 * Beware: this %hold might be already handled, but still squeak
911 * through because of a race.
912 */
913 enum routing_t ro = sr->routing /* routing, old */
914 , rn = ro; /* routing, new */
915
916 passert(LHAS(LELEM(CK_PERMANENT) | LELEM(CK_INSTANCE), c->kind));
917 /* figure out what routing should become */
918 switch (ro)
919 {
920 case RT_UNROUTED:
921 rn = RT_UNROUTED_HOLD;
922 break;
923 case RT_ROUTED_PROSPECTIVE:
924 rn = RT_ROUTED_HOLD;
925 break;
926 default:
927 /* no change: this %hold is old news and should just be deleted */
928 break;
929 }
930
931 /* We need a broad %hold
932 * First we ensure that there is a broad %hold.
933 * There may already be one (race condition): no need to create one.
934 * There may already be a %trap: replace it.
935 * There may not be any broad eroute: add %hold.
936 */
937 if (rn != ro)
938 {
939 if (erouted(ro)
940 ? !eroute_connection(sr, htonl(SPI_HOLD), SA_INT, SADB_X_SATYPE_INT,
941 &null_ipsec_sa, ERO_REPLACE,
942 "replace %trap with broad %hold")
943 : !eroute_connection(sr, htonl(SPI_HOLD), SA_INT, SADB_X_SATYPE_INT,
944 &null_ipsec_sa, ERO_ADD, "add broad %hold"))
945 {
946 return FALSE;
947 }
948 }
949 sr->routing = rn;
950 return TRUE;
951 }
952
953 /* install or remove eroute for SA Group */
954 static bool sag_eroute(struct state *st, struct spd_route *sr,
955 unsigned op, const char *opname)
956 {
957 u_int inner_proto, inner_satype;
958 ipsec_spi_t inner_spi = 0;
959 ipsec_sa_cfg_t sa = {
960 .mode = MODE_TRANSPORT,
961 };
962 bool tunnel = FALSE;
963
964 if (st->st_ah.present)
965 {
966 inner_spi = st->st_ah.attrs.spi;
967 inner_proto = SA_AH;
968 inner_satype = SADB_SATYPE_AH;
969 sa.ah.use = TRUE;
970 sa.ah.spi = inner_spi;
971 tunnel |= st->st_ah.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL;
972 }
973
974 if (st->st_esp.present)
975 {
976 inner_spi = st->st_esp.attrs.spi;
977 inner_proto = SA_ESP;
978 inner_satype = SADB_SATYPE_ESP;
979 sa.esp.use = TRUE;
980 sa.esp.spi = inner_spi;
981 tunnel |= st->st_esp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL;
982 }
983
984 if (st->st_ipcomp.present)
985 {
986 inner_spi = st->st_ipcomp.attrs.spi;
987 inner_proto = SA_COMP;
988 inner_satype = SADB_X_SATYPE_COMP;
989 sa.ipcomp.transform = st->st_ipcomp.attrs.transid;
990 sa.ipcomp.cpi = htons(ntohl(inner_spi));
991 tunnel |= st->st_ipcomp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL;
992 }
993
994 if (!sa.ah.use && !sa.esp.use && !sa.ipcomp.transform)
995 {
996 impossible(); /* no transform at all! */
997 }
998
999 if (tunnel)
1000 {
1001 inner_spi = st->st_tunnel_out_spi;
1002 inner_proto = SA_IPIP;
1003 inner_satype = SADB_X_SATYPE_IPIP;
1004 sa.mode = MODE_TUNNEL;
1005 }
1006
1007 sa.reqid = sr->reqid;
1008
1009 return eroute_connection(sr, inner_spi, inner_proto, inner_satype,
1010 &sa, op, opname);
1011 }
1012
1013 /* compute a (host-order!) SPI to implement the policy in connection c */
1014 ipsec_spi_t
1015 shunt_policy_spi(connection_t *c, bool prospective)
1016 {
1017 /* note: these are in host order :-( */
1018 static const ipsec_spi_t shunt_spi[] =
1019 {
1020 SPI_TRAP, /* --initiateontraffic */
1021 SPI_PASS, /* --pass */
1022 SPI_DROP, /* --drop */
1023 SPI_REJECT, /* --reject */
1024 };
1025
1026 static const ipsec_spi_t fail_spi[] =
1027 {
1028 0, /* --none*/
1029 SPI_PASS, /* --failpass */
1030 SPI_DROP, /* --faildrop */
1031 SPI_REJECT, /* --failreject */
1032 };
1033
1034 return prospective
1035 ? shunt_spi[(c->policy & POLICY_SHUNT_MASK) >> POLICY_SHUNT_SHIFT]
1036 : fail_spi[(c->policy & POLICY_FAIL_MASK) >> POLICY_FAIL_SHIFT];
1037 }
1038
1039 /* Add/replace/delete a shunt eroute.
1040 * Such an eroute determines the fate of packets without the use
1041 * of any SAs. These are defaults, in effect.
1042 * If a negotiation has not been attempted, use %trap.
1043 * If negotiation has failed, the choice between %trap/%pass/%drop/%reject
1044 * is specified in the policy of connection c.
1045 */
1046 static bool shunt_eroute(connection_t *c, struct spd_route *sr,
1047 enum routing_t rt_kind,
1048 unsigned int op, const char *opname)
1049 {
1050 /* We are constructing a special SAID for the eroute.
1051 * The destination doesn't seem to matter, but the family does.
1052 * The protocol is SA_INT -- mark this as shunt.
1053 * The satype has no meaning, but is required for PF_KEY header!
1054 * The SPI signifies the kind of shunt.
1055 */
1056 ipsec_spi_t spi = shunt_policy_spi(c, rt_kind == RT_ROUTED_PROSPECTIVE);
1057
1058 if (spi == 0)
1059 {
1060 /* we're supposed to end up with no eroute: rejig op and opname */
1061 switch (op)
1062 {
1063 case ERO_REPLACE:
1064 /* replace with nothing == delete */
1065 op = ERO_DELETE;
1066 opname = "delete";
1067 break;
1068 case ERO_ADD:
1069 /* add nothing == do nothing */
1070 return TRUE;
1071 case ERO_DELETE:
1072 /* delete remains delete */
1073 break;
1074 default:
1075 bad_case(op);
1076 }
1077 }
1078 if (sr->routing == RT_ROUTED_ECLIPSED && c->kind == CK_TEMPLATE)
1079 {
1080 /* We think that we have an eroute, but we don't.
1081 * Adjust the request and account for eclipses.
1082 */
1083 passert(eclipsable(sr));
1084 switch (op)
1085 {
1086 case ERO_REPLACE:
1087 /* really an add */
1088 op = ERO_ADD;
1089 opname = "replace eclipsed";
1090 eclipse_count--;
1091 break;
1092 case ERO_DELETE:
1093 /* delete unnecessary: we don't actually have an eroute */
1094 eclipse_count--;
1095 return TRUE;
1096 case ERO_ADD:
1097 default:
1098 bad_case(op);
1099 }
1100 }
1101 else if (eclipse_count > 0 && op == ERO_DELETE && eclipsable(sr))
1102 {
1103 /* maybe we are uneclipsing something */
1104 struct spd_route *esr;
1105 connection_t *ue = eclipsed(c, &esr);
1106
1107 if (ue != NULL)
1108 {
1109 esr->routing = RT_ROUTED_PROSPECTIVE;
1110 return shunt_eroute(ue, esr
1111 , RT_ROUTED_PROSPECTIVE, ERO_REPLACE, "restoring eclipsed");
1112 }
1113 }
1114
1115 return eroute_connection(sr, htonl(spi), SA_INT, SADB_X_SATYPE_INT,
1116 &null_ipsec_sa, op, opname);
1117 }
1118
1119 static bool setup_half_ipsec_sa(struct state *st, bool inbound)
1120 {
1121 host_t *host_src, *host_dst;
1122 connection_t *c = st->st_connection;
1123 struct end *src, *dst;
1124 ipsec_mode_t mode = MODE_TRANSPORT;
1125 ipsec_sa_cfg_t sa = { .mode = 0 };
1126 lifetime_cfg_t lt_none = { .time = { .rekey = 0 } };
1127 mark_t mark;
1128 bool ok = TRUE;
1129 /* SPIs, saved for undoing, if necessary */
1130 struct kernel_sa said[EM_MAXRELSPIS], *said_next = said;
1131 if (inbound)
1132 {
1133 src = &c->spd.that;
1134 dst = &c->spd.this;
1135 mark = c->spd.mark_in;
1136 }
1137 else
1138 {
1139 src = &c->spd.this;
1140 dst = &c->spd.that;
1141 mark = c->spd.mark_out;
1142 }
1143
1144 host_src = host_create_from_sockaddr((sockaddr_t*)&src->host_addr);
1145 host_dst = host_create_from_sockaddr((sockaddr_t*)&dst->host_addr);
1146
1147 if (st->st_ah.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL
1148 || st->st_esp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL
1149 || st->st_ipcomp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1150 {
1151 mode = MODE_TUNNEL;
1152 }
1153
1154 sa.mode = mode;
1155 sa.reqid = c->spd.reqid;
1156
1157 memset(said, 0, sizeof(said));
1158
1159 /* set up IPCOMP SA, if any */
1160
1161 if (st->st_ipcomp.present)
1162 {
1163 ipsec_spi_t ipcomp_spi = inbound ? st->st_ipcomp.our_spi
1164 : st->st_ipcomp.attrs.spi;
1165
1166 switch (st->st_ipcomp.attrs.transid)
1167 {
1168 case IPCOMP_DEFLATE:
1169 break;
1170
1171 default:
1172 loglog(RC_LOG_SERIOUS, "IPCOMP transform %s not implemented",
1173 enum_name(&ipcomp_transformid_names,
1174 st->st_ipcomp.attrs.transid));
1175 goto fail;
1176 }
1177
1178 sa.ipcomp.cpi = htons(ntohl(ipcomp_spi));
1179 sa.ipcomp.transform = st->st_ipcomp.attrs.transid;
1180
1181 said_next->spi = ipcomp_spi;
1182 said_next->proto = IPPROTO_COMP;
1183
1184 if (hydra->kernel_interface->add_sa(hydra->kernel_interface, host_src,
1185 host_dst, ipcomp_spi, said_next->proto, c->spd.reqid,
1186 mark, 0, &lt_none, ENCR_UNDEFINED, chunk_empty,
1187 AUTH_UNDEFINED, chunk_empty, mode,
1188 st->st_ipcomp.attrs.transid, 0 /* cpi */, FALSE,
1189 inbound, NULL, NULL) != SUCCESS)
1190 {
1191 goto fail;
1192 }
1193 said_next++;
1194 mode = MODE_TRANSPORT;
1195 }
1196
1197 /* set up ESP SA, if any */
1198
1199 if (st->st_esp.present)
1200 {
1201 ipsec_spi_t esp_spi = inbound ? st->st_esp.our_spi
1202 : st->st_esp.attrs.spi;
1203 u_char *esp_dst_keymat = inbound ? st->st_esp.our_keymat
1204 : st->st_esp.peer_keymat;
1205 bool encap = st->nat_traversal & NAT_T_DETECTED;
1206 encryption_algorithm_t enc_alg;
1207 integrity_algorithm_t auth_alg;
1208 const struct esp_info *ei;
1209 chunk_t enc_key, auth_key;
1210 u_int16_t key_len;
1211
1212 if ((ei = kernel_alg_esp_info(st->st_esp.attrs.transid,
1213 st->st_esp.attrs.auth)) == NULL)
1214 {
1215 loglog(RC_LOG_SERIOUS, "ESP transform %s / auth %s"
1216 " not implemented yet",
1217 enum_name(&esp_transform_names, st->st_esp.attrs.transid),
1218 enum_name(&auth_alg_names, st->st_esp.attrs.auth));
1219 goto fail;
1220 }
1221
1222 key_len = st->st_esp.attrs.key_len / 8;
1223 if (key_len)
1224 {
1225 /* XXX: must change to check valid _range_ key_len */
1226 if (key_len > ei->enckeylen)
1227 {
1228 loglog(RC_LOG_SERIOUS, "ESP transform %s: key_len=%d > %d",
1229 enum_name(&esp_transform_names, st->st_esp.attrs.transid),
1230 (int)key_len, (int)ei->enckeylen);
1231 goto fail;
1232 }
1233 }
1234 else
1235 {
1236 key_len = ei->enckeylen;
1237 }
1238
1239 switch (ei->transid)
1240 {
1241 case ESP_3DES:
1242 /* 168 bits in kernel, need 192 bits for keymat_len */
1243 if (key_len == 21)
1244 {
1245 key_len = 24;
1246 }
1247 break;
1248 case ESP_DES:
1249 /* 56 bits in kernel, need 64 bits for keymat_len */
1250 if (key_len == 7)
1251 {
1252 key_len = 8;
1253 }
1254 break;
1255 case ESP_AES_CCM_8:
1256 case ESP_AES_CCM_12:
1257 case ESP_AES_CCM_16:
1258 key_len += 3;
1259 break;
1260 case ESP_AES_GCM_8:
1261 case ESP_AES_GCM_12:
1262 case ESP_AES_GCM_16:
1263 case ESP_AES_CTR:
1264 case ESP_AES_GMAC:
1265 key_len += 4;
1266 break;
1267 default:
1268 break;
1269 }
1270
1271 if (encap)
1272 {
1273 host_src->set_port(host_src, src->host_port);
1274 host_dst->set_port(host_dst, dst->host_port);
1275 // st->nat_oa is currently unused
1276 }
1277
1278 /* divide up keying material */
1279 enc_alg = encryption_algorithm_from_esp(st->st_esp.attrs.transid);
1280 enc_key.ptr = esp_dst_keymat;
1281 enc_key.len = key_len;
1282 auth_alg = integrity_algorithm_from_esp(st->st_esp.attrs.auth);
1283 auth_alg = auth_alg ? : AUTH_UNDEFINED;
1284 auth_key.ptr = esp_dst_keymat + key_len;
1285 auth_key.len = ei->authkeylen;
1286
1287 sa.esp.use = TRUE;
1288 sa.esp.spi = esp_spi;
1289
1290 said_next->spi = esp_spi;
1291 said_next->proto = IPPROTO_ESP;
1292
1293 if (hydra->kernel_interface->add_sa(hydra->kernel_interface, host_src,
1294 host_dst, esp_spi, said_next->proto, c->spd.reqid,
1295 mark, 0, &lt_none, enc_alg, enc_key,
1296 auth_alg, auth_key, mode, IPCOMP_NONE, 0 /* cpi */,
1297 encap, inbound, NULL, NULL) != SUCCESS)
1298 {
1299 goto fail;
1300 }
1301 said_next++;
1302 mode = MODE_TRANSPORT;
1303 }
1304
1305 /* set up AH SA, if any */
1306
1307 if (st->st_ah.present)
1308 {
1309 ipsec_spi_t ah_spi = inbound ? st->st_ah.our_spi
1310 : st->st_ah.attrs.spi;
1311 u_char *ah_dst_keymat = inbound ? st->st_ah.our_keymat
1312 : st->st_ah.peer_keymat;
1313 integrity_algorithm_t auth_alg;
1314 chunk_t auth_key;
1315
1316 auth_alg = integrity_algorithm_from_esp(st->st_ah.attrs.auth);
1317 auth_key.ptr = ah_dst_keymat;
1318 auth_key.len = st->st_ah.keymat_len;
1319
1320 sa.ah.use = TRUE;
1321 sa.ah.spi = ah_spi;
1322
1323 said_next->spi = ah_spi;
1324 said_next->proto = IPPROTO_AH;
1325
1326 if (hydra->kernel_interface->add_sa(hydra->kernel_interface, host_src,
1327 host_dst, ah_spi, said_next->proto, c->spd.reqid,
1328 mark, 0, &lt_none, ENCR_UNDEFINED, chunk_empty,
1329 auth_alg, auth_key, mode, IPCOMP_NONE, 0 /* cpi */,
1330 FALSE, inbound, NULL, NULL) != SUCCESS)
1331 {
1332 goto fail;
1333 }
1334 said_next++;
1335 mode = MODE_TRANSPORT;
1336 }
1337
1338 goto cleanup;
1339
1340 fail:
1341 /* undo the done SPIs */
1342 while (said_next-- != said)
1343 {
1344 hydra->kernel_interface->del_sa(hydra->kernel_interface, host_src,
1345 host_dst, said_next->spi,
1346 said_next->proto, 0 /* cpi */,
1347 mark);
1348 }
1349 ok = FALSE;
1350
1351 cleanup:
1352 host_src->destroy(host_src);
1353 host_dst->destroy(host_dst);
1354 return ok;
1355 }
1356
1357 static bool teardown_half_ipsec_sa(struct state *st, bool inbound)
1358 {
1359 connection_t *c = st->st_connection;
1360 const struct end *src, *dst;
1361 host_t *host_src, *host_dst;
1362 ipsec_spi_t spi;
1363 mark_t mark;
1364 bool result = TRUE;
1365
1366 if (inbound)
1367 {
1368 src = &c->spd.that;
1369 dst = &c->spd.this;
1370 mark = c->spd.mark_in;
1371 }
1372 else
1373 {
1374 src = &c->spd.this;
1375 dst = &c->spd.that;
1376 mark = c->spd.mark_out;
1377 }
1378
1379 host_src = host_create_from_sockaddr((sockaddr_t*)&src->host_addr);
1380 host_dst = host_create_from_sockaddr((sockaddr_t*)&dst->host_addr);
1381
1382 if (st->st_ah.present)
1383 {
1384 spi = inbound ? st->st_ah.our_spi : st->st_ah.attrs.spi;
1385 result &= hydra->kernel_interface->del_sa(hydra->kernel_interface,
1386 host_src, host_dst, spi, IPPROTO_AH,
1387 0 /* cpi */, mark) == SUCCESS;
1388 }
1389
1390 if (st->st_esp.present)
1391 {
1392 spi = inbound ? st->st_esp.our_spi : st->st_esp.attrs.spi;
1393 result &= hydra->kernel_interface->del_sa(hydra->kernel_interface,
1394 host_src, host_dst, spi, IPPROTO_ESP,
1395 0 /* cpi */, mark) == SUCCESS;
1396 }
1397
1398 if (st->st_ipcomp.present)
1399 {
1400 spi = inbound ? st->st_ipcomp.our_spi : st->st_ipcomp.attrs.spi;
1401 result &= hydra->kernel_interface->del_sa(hydra->kernel_interface,
1402 host_src, host_dst, spi, IPPROTO_COMP,
1403 0 /* cpi */, mark) == SUCCESS;
1404 }
1405
1406 host_src->destroy(host_src);
1407 host_dst->destroy(host_dst);
1408
1409 return result;
1410 }
1411
1412 /*
1413 * get information about a given sa
1414 */
1415 bool get_sa_info(struct state *st, bool inbound, u_int *bytes, time_t *use_time)
1416 {
1417 connection_t *c = st->st_connection;
1418 traffic_selector_t *ts_src = NULL, *ts_dst = NULL;
1419 host_t *host_src = NULL, *host_dst = NULL;
1420 const struct end *src, *dst;
1421 ipsec_spi_t spi;
1422 mark_t mark;
1423 u_int64_t bytes_kernel = 0;
1424 bool result = FALSE;
1425
1426 *use_time = UNDEFINED_TIME;
1427
1428 if (!st->st_esp.present)
1429 {
1430 goto failed;
1431 }
1432
1433 if (inbound)
1434 {
1435 src = &c->spd.that;
1436 dst = &c->spd.this;
1437 mark = c->spd.mark_in;
1438 spi = st->st_esp.our_spi;
1439 }
1440 else
1441 {
1442 src = &c->spd.this;
1443 dst = &c->spd.that;
1444 mark = c->spd.mark_out;
1445 spi = st->st_esp.attrs.spi;
1446 }
1447
1448 host_src = host_create_from_sockaddr((sockaddr_t*)&src->host_addr);
1449 host_dst = host_create_from_sockaddr((sockaddr_t*)&dst->host_addr);
1450
1451 switch(hydra->kernel_interface->query_sa(hydra->kernel_interface, host_src,
1452 host_dst, spi, IPPROTO_ESP,
1453 mark, &bytes_kernel))
1454 {
1455 case FAILED:
1456 goto failed;
1457 case SUCCESS:
1458 *bytes = bytes_kernel;
1459 break;
1460 case NOT_SUPPORTED:
1461 default:
1462 break;
1463 }
1464
1465 if (st->st_serialno == c->spd.eroute_owner)
1466 {
1467 u_int32_t time_kernel;
1468
1469 ts_src = traffic_selector_from_subnet(&src->client, src->protocol);
1470 ts_dst = traffic_selector_from_subnet(&dst->client, dst->protocol);
1471
1472 if (hydra->kernel_interface->query_policy(hydra->kernel_interface,
1473 ts_src, ts_dst, inbound ? POLICY_IN : POLICY_OUT,
1474 mark, &time_kernel) != SUCCESS)
1475 {
1476 goto failed;
1477 }
1478 *use_time = time_kernel;
1479
1480 if (inbound &&
1481 st->st_esp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1482 {
1483 if (hydra->kernel_interface->query_policy(hydra->kernel_interface,
1484 ts_src, ts_dst, POLICY_FWD, mark,
1485 &time_kernel) != SUCCESS)
1486 {
1487 goto failed;
1488 }
1489 *use_time = max(*use_time, time_kernel);
1490 }
1491 }
1492
1493 result = TRUE;
1494
1495 failed:
1496 DESTROY_IF(host_src);
1497 DESTROY_IF(host_dst);
1498 DESTROY_IF(ts_src);
1499 DESTROY_IF(ts_dst);
1500 return result;
1501 }
1502
1503 /**
1504 * Handler for kernel events (called by thread-pool thread)
1505 */
1506 kernel_listener_t *kernel_handler;
1507
1508 /**
1509 * Data for acquire events
1510 */
1511 typedef struct {
1512 /** Subnets */
1513 ip_subnet src, dst;
1514 /** Transport protocol */
1515 int proto;
1516 } acquire_data_t;
1517
1518 /**
1519 * Callback for acquire events (called by main thread)
1520 */
1521 void handle_acquire(acquire_data_t *this)
1522 {
1523 record_and_initiate_opportunistic(&this->src, &this->dst, this->proto,
1524 "%acquire");
1525 }
1526
1527 METHOD(kernel_listener_t, acquire, bool,
1528 kernel_listener_t *this, u_int32_t reqid,
1529 traffic_selector_t *src_ts, traffic_selector_t *dst_ts)
1530 {
1531 if (src_ts && dst_ts)
1532 {
1533 acquire_data_t *data;
1534 DBG(DBG_CONTROL,
1535 DBG_log("creating acquire event for policy %R === %R "
1536 "with reqid {%u}", src_ts, dst_ts, reqid));
1537 INIT(data,
1538 .src = subnet_from_traffic_selector(src_ts),
1539 .dst = subnet_from_traffic_selector(dst_ts),
1540 .proto = src_ts->get_protocol(src_ts),
1541 );
1542 pluto->events->queue(pluto->events, (void*)handle_acquire, data, free);
1543 }
1544 else
1545 {
1546 DBG(DBG_CONTROL,
1547 DBG_log("ignoring acquire without traffic selectors for policy "
1548 "with reqid {%u}", reqid));
1549 }
1550 DESTROY_IF(src_ts);
1551 DESTROY_IF(dst_ts);
1552 return TRUE;
1553 }
1554
1555 /**
1556 * Data for mapping events
1557 */
1558 typedef struct {
1559 /** reqid, spi of affected SA */
1560 u_int32_t reqid, spi;
1561 /** new endpont */
1562 ip_address new_end;
1563 } mapping_data_t;
1564
1565 /**
1566 * Callback for mapping events (called by main thread)
1567 */
1568 void handle_mapping(mapping_data_t *this)
1569 {
1570 process_nat_t_new_mapping(this->reqid, this->spi, &this->new_end);
1571 }
1572
1573
1574 METHOD(kernel_listener_t, mapping, bool,
1575 kernel_listener_t *this, u_int32_t reqid, u_int32_t spi, host_t *remote)
1576 {
1577 mapping_data_t *data;
1578 DBG(DBG_CONTROL,
1579 DBG_log("creating mapping event for SA with SPI %.8x and reqid {%u}",
1580 spi, reqid));
1581 INIT(data,
1582 .reqid = reqid,
1583 .spi = spi,
1584 .new_end = *(ip_address*)remote->get_sockaddr(remote),
1585 );
1586 pluto->events->queue(pluto->events, (void*)handle_mapping, data, free);
1587 return TRUE;
1588 }
1589
1590 void init_kernel(void)
1591 {
1592 /* register SA types that we can negotiate */
1593 can_do_IPcomp = FALSE; /* until we get a response from the kernel */
1594 pfkey_register();
1595
1596 INIT(kernel_handler,
1597 .acquire = _acquire,
1598 .mapping = _mapping,
1599 );
1600 hydra->kernel_interface->add_listener(hydra->kernel_interface,
1601 kernel_handler);
1602 }
1603
1604 void kernel_finalize()
1605 {
1606 hydra->kernel_interface->remove_listener(hydra->kernel_interface,
1607 kernel_handler);
1608 free(kernel_handler);
1609 }
1610
1611 /* Note: install_inbound_ipsec_sa is only used by the Responder.
1612 * The Responder will subsequently use install_ipsec_sa for the outbound.
1613 * The Initiator uses install_ipsec_sa to install both at once.
1614 */
1615 bool install_inbound_ipsec_sa(struct state *st)
1616 {
1617 connection_t *const c = st->st_connection;
1618
1619 /* If our peer has a fixed-address client, check if we already
1620 * have a route for that client that conflicts. We will take this
1621 * as proof that that route and the connections using it are
1622 * obsolete and should be eliminated. Interestingly, this is
1623 * the only case in which we can tell that a connection is obsolete.
1624 */
1625 passert(c->kind == CK_PERMANENT || c->kind == CK_INSTANCE);
1626 if (c->spd.that.has_client)
1627 {
1628 for (;;)
1629 {
1630 struct spd_route *esr;
1631 connection_t *o = route_owner(c, &esr, NULL, NULL);
1632
1633 if (o == NULL)
1634 {
1635 break; /* nobody has a route */
1636 }
1637
1638 /* note: we ignore the client addresses at this end */
1639 if (sameaddr(&o->spd.that.host_addr, &c->spd.that.host_addr) &&
1640 o->interface == c->interface)
1641 {
1642 break; /* existing route is compatible */
1643 }
1644
1645 if (o->kind == CK_TEMPLATE && streq(o->name, c->name))
1646 {
1647 break; /* ??? is this good enough?? */
1648 }
1649
1650 loglog(RC_LOG_SERIOUS, "route to peer's client conflicts with \"%s\" %s; releasing old connection to free the route"
1651 , o->name, ip_str(&o->spd.that.host_addr));
1652 release_connection(o, FALSE);
1653 }
1654 }
1655
1656 DBG(DBG_CONTROL, DBG_log("install_inbound_ipsec_sa() checking if we can route"));
1657 /* check that we will be able to route and eroute */
1658 switch (could_route(c))
1659 {
1660 case route_easy:
1661 case route_nearconflict:
1662 break;
1663 default:
1664 return FALSE;
1665 }
1666
1667 /* (attempt to) actually set up the SAs */
1668 return setup_half_ipsec_sa(st, TRUE);
1669 }
1670
1671 /* Install a route and then a prospective shunt eroute or an SA group eroute.
1672 * Assumption: could_route gave a go-ahead.
1673 * Any SA Group must have already been created.
1674 * On failure, steps will be unwound.
1675 */
1676 bool route_and_eroute(connection_t *c, struct spd_route *sr, struct state *st)
1677 {
1678 struct spd_route *esr;
1679 struct spd_route *rosr;
1680 connection_t *ero /* who, if anyone, owns our eroute? */
1681 , *ro = route_owner(c, &rosr, &ero, &esr);
1682 bool eroute_installed = FALSE
1683 , firewall_notified = FALSE
1684 , route_installed = FALSE;
1685
1686 connection_t *ero_top;
1687
1688 DBG(DBG_CONTROLMORE,
1689 DBG_log("route_and_eroute with c: %s (next: %s) ero:%s esr:{%p} ro:%s rosr:{%p} and state: %lu"
1690 , c->name
1691 , (c->policy_next ? c->policy_next->name : "none")
1692 , ero ? ero->name : "null"
1693 , esr
1694 , ro ? ro->name : "null"
1695 , rosr
1696 , st ? st->st_serialno : 0));
1697
1698 /* look along the chain of policies for one with the same name */
1699 ero_top = ero;
1700
1701 #if 0
1702 /* XXX - mcr this made sense before, and likely will make sense
1703 * again, so I'l leaving this to remind me what is up */
1704 if (ero!= NULL && ero->routing == RT_UNROUTED_KEYED)
1705 ero = NULL;
1706
1707 for (ero2 = ero; ero2 != NULL; ero2 = ero->policy_next)
1708 if ((ero2->kind == CK_TEMPLATE || ero2->kind==CK_SECONDARY)
1709 && streq(ero2->name, c->name))
1710 break;
1711 #endif
1712
1713 /* install the eroute */
1714
1715 if (ero != NULL)
1716 {
1717 /* We're replacing an eroute */
1718
1719 /* if no state provided, then install a shunt for later */
1720 if (st == NULL)
1721 {
1722 eroute_installed = shunt_eroute(c, sr, RT_ROUTED_PROSPECTIVE
1723 , ERO_REPLACE, "replace");
1724 }
1725 else
1726 {
1727 eroute_installed = sag_eroute(st, sr, ERO_REPLACE, "replace");
1728 }
1729 #if 0
1730 /* XXX - MCR. I previously felt that this was a bogus check */
1731 if (ero != NULL && ero != c && esr != sr)
1732 {
1733 /* By elimination, we must be eclipsing ero. Check. */
1734 passert(ero->kind == CK_TEMPLATE && streq(ero->name, c->name));
1735 passert(LHAS(LELEM(RT_ROUTED_PROSPECTIVE) | LELEM(RT_ROUTED_ECLIPSED)
1736 , esr->routing));
1737 passert(samesubnet(&esr->this.client, &sr->this.client)
1738 && samesubnet(&esr->that.client, &sr->that.client));
1739 }
1740 #endif
1741 }
1742 else
1743 {
1744 /* we're adding an eroute */
1745
1746 /* if no state provided, then install a shunt for later */
1747 if (st == NULL)
1748 {
1749 eroute_installed = shunt_eroute(c, sr, RT_ROUTED_PROSPECTIVE
1750 , ERO_ADD, "add");
1751 }
1752 else
1753 {
1754 eroute_installed = sag_eroute(st, sr, ERO_ADD, "add");
1755 }
1756 }
1757
1758 /* notify the firewall of a new tunnel */
1759
1760 if (eroute_installed)
1761 {
1762 /* do we have to notify the firewall? Yes, if we are installing
1763 * a tunnel eroute and the firewall wasn't notified
1764 * for a previous tunnel with the same clients. Any Previous
1765 * tunnel would have to be for our connection, so the actual
1766 * test is simple.
1767 */
1768 firewall_notified = st == NULL /* not a tunnel eroute */
1769 || sr->eroute_owner != SOS_NOBODY /* already notified */
1770 || do_command(c, sr, st, "up"); /* go ahead and notify */
1771 }
1772
1773 /* install the route */
1774
1775 DBG(DBG_CONTROL,
1776 DBG_log("route_and_eroute: firewall_notified: %s"
1777 , firewall_notified ? "true" : "false"));
1778 if (!firewall_notified)
1779 {
1780 /* we're in trouble -- don't do routing */
1781 }
1782 else if (ro == NULL)
1783 {
1784 /* a new route: no deletion required, but preparation is */
1785 (void) do_command(c, sr, st, "prepare"); /* just in case; ignore failure */
1786 route_installed = do_command(c, sr, st, "route");
1787 }
1788 else if (routed(sr->routing) || routes_agree(ro, c))
1789 {
1790 route_installed = TRUE; /* nothing to be done */
1791 }
1792 else
1793 {
1794 /* Some other connection must own the route
1795 * and the route must disagree. But since could_route
1796 * must have allowed our stealing it, we'll do so.
1797 *
1798 * A feature of LINUX allows us to install the new route
1799 * before deleting the old if the nexthops differ.
1800 * This reduces the "window of vulnerability" when packets
1801 * might flow in the clear.
1802 */
1803 if (sameaddr(&sr->this.host_nexthop, &esr->this.host_nexthop))
1804 {
1805 (void) do_command(ro, sr, st, "unroute");
1806 route_installed = do_command(c, sr, st, "route");
1807 }
1808 else
1809 {
1810 route_installed = do_command(c, sr, st, "route");
1811 (void) do_command(ro, sr, st, "unroute");
1812 }
1813
1814 /* record unrouting */
1815 if (route_installed)
1816 {
1817 do {
1818 passert(!erouted(rosr->routing));
1819 rosr->routing = RT_UNROUTED;
1820
1821 /* no need to keep old value */
1822 ro = route_owner(c, &rosr, NULL, NULL);
1823 } while (ro != NULL);
1824 }
1825 }
1826
1827 /* all done -- clean up */
1828 if (route_installed)
1829 {
1830 /* Success! */
1831
1832 if (ero != NULL && ero != c)
1833 {
1834 /* check if ero is an ancestor of c. */
1835 connection_t *ero2;
1836
1837 for (ero2 = c; ero2 != NULL && ero2 != c; ero2 = ero2->policy_next)
1838 ;
1839
1840 if (ero2 == NULL)
1841 {
1842 /* By elimination, we must be eclipsing ero. Checked above. */
1843 if (ero->spd.routing != RT_ROUTED_ECLIPSED)
1844 {
1845 ero->spd.routing = RT_ROUTED_ECLIPSED;
1846 eclipse_count++;
1847 }
1848 }
1849 }
1850
1851 if (st == NULL)
1852 {
1853 passert(sr->eroute_owner == SOS_NOBODY);
1854 sr->routing = RT_ROUTED_PROSPECTIVE;
1855 }
1856 else
1857 {
1858 char cib[CONN_INST_BUF];
1859 sr->routing = RT_ROUTED_TUNNEL;
1860
1861 DBG(DBG_CONTROL,
1862 DBG_log("route_and_eroute: instance \"%s\"%s, setting eroute_owner {spd=%p,sr=%p} to #%ld (was #%ld) (newest_ipsec_sa=#%ld)"
1863 , st->st_connection->name
1864 , (fmt_conn_instance(st->st_connection, cib), cib)
1865 , &st->st_connection->spd, sr
1866 , st->st_serialno
1867 , sr->eroute_owner
1868 , st->st_connection->newest_ipsec_sa));
1869 sr->eroute_owner = st->st_serialno;
1870 }
1871
1872 return TRUE;
1873 }
1874 else
1875 {
1876 /* Failure! Unwind our work. */
1877 if (firewall_notified && sr->eroute_owner == SOS_NOBODY)
1878 (void) do_command(c, sr, st, "down");
1879
1880 if (eroute_installed)
1881 {
1882 /* Restore original eroute, if we can.
1883 * Since there is nothing much to be done if the restoration
1884 * fails, ignore success or failure.
1885 */
1886 if (ero != NULL)
1887 {
1888 /* restore ero's former glory */
1889 if (esr->eroute_owner == SOS_NOBODY)
1890 {
1891 /* note: normal or eclipse case */
1892 (void) shunt_eroute(ero, esr
1893 , esr->routing, ERO_REPLACE, "restore");
1894 }
1895 else
1896 {
1897 /* Try to find state that owned eroute.
1898 * Don't do anything if it cannot be found.
1899 * This case isn't likely since we don't run
1900 * the updown script when replacing a SA group
1901 * with its successor (for the same conn).
1902 */
1903 struct state *ost = state_with_serialno(esr->eroute_owner);
1904
1905 if (ost != NULL)
1906 (void) sag_eroute(ost, esr, ERO_REPLACE, "restore");
1907 }
1908 }
1909 else
1910 {
1911 /* there was no previous eroute: delete whatever we installed */
1912 if (st == NULL)
1913 {
1914 (void) shunt_eroute(c, sr, sr->routing, ERO_DELETE, "delete");
1915 }
1916 else
1917 {
1918 (void) sag_eroute(st, sr, ERO_DELETE, "delete");
1919 }
1920 }
1921 }
1922
1923 return FALSE;
1924 }
1925 }
1926
1927 bool install_ipsec_sa(struct state *st, bool inbound_also)
1928 {
1929 struct spd_route *sr;
1930
1931 DBG(DBG_CONTROL, DBG_log("install_ipsec_sa() for #%ld: %s"
1932 , st->st_serialno
1933 , inbound_also?
1934 "inbound and outbound" : "outbound only"));
1935
1936 switch (could_route(st->st_connection))
1937 {
1938 case route_easy:
1939 case route_nearconflict:
1940 break;
1941 default:
1942 return FALSE;
1943 }
1944
1945 /* (attempt to) actually set up the SA group */
1946 if ((inbound_also && !setup_half_ipsec_sa(st, TRUE)) ||
1947 !setup_half_ipsec_sa(st, FALSE))
1948 {
1949 return FALSE;
1950 }
1951
1952 for (sr = &st->st_connection->spd; sr != NULL; sr = sr->next)
1953 {
1954 DBG(DBG_CONTROL, DBG_log("sr for #%ld: %s"
1955 , st->st_serialno
1956 , enum_name(&routing_story, sr->routing)));
1957
1958 /*
1959 * if the eroute owner is not us, then make it us.
1960 * See test co-terminal-02, pluto-rekey-01, pluto-unit-02/oppo-twice
1961 */
1962 pexpect(sr->eroute_owner == SOS_NOBODY
1963 || sr->routing >= RT_ROUTED_TUNNEL);
1964
1965 if (sr->eroute_owner != st->st_serialno
1966 && sr->routing != RT_UNROUTED_KEYED)
1967 {
1968 if (!route_and_eroute(st->st_connection, sr, st))
1969 {
1970 delete_ipsec_sa(st, FALSE);
1971 /* XXX go and unroute any SRs that were successfully
1972 * routed already.
1973 */
1974 return FALSE;
1975 }
1976 }
1977 }
1978
1979 return TRUE;
1980 }
1981
1982 /* delete an IPSEC SA.
1983 * we may not succeed, but we bull ahead anyway because
1984 * we cannot do anything better by recognizing failure
1985 */
1986 void delete_ipsec_sa(struct state *st, bool inbound_only)
1987 {
1988 if (!inbound_only)
1989 {
1990 /* If the state is the eroute owner, we must adjust
1991 * the routing for the connection.
1992 */
1993 connection_t *c = st->st_connection;
1994 struct spd_route *sr;
1995
1996 passert(st->st_connection);
1997
1998 for (sr = &c->spd; sr; sr = sr->next)
1999 {
2000 if (sr->eroute_owner == st->st_serialno
2001 && sr->routing == RT_ROUTED_TUNNEL)
2002 {
2003 sr->eroute_owner = SOS_NOBODY;
2004
2005 /* Routing should become RT_ROUTED_FAILURE,
2006 * but if POLICY_FAIL_NONE, then we just go
2007 * right back to RT_ROUTED_PROSPECTIVE as if no
2008 * failure happened.
2009 */
2010 sr->routing = (c->policy & POLICY_FAIL_MASK) == POLICY_FAIL_NONE
2011 ? RT_ROUTED_PROSPECTIVE : RT_ROUTED_FAILURE;
2012
2013 (void) do_command(c, sr, st, "down");
2014 if ((c->policy & POLICY_DONT_REKEY) && c->kind == CK_INSTANCE)
2015 {
2016 /* in this special case, even if the connection
2017 * is still alive (due to an ISAKMP SA),
2018 * we get rid of routing.
2019 * Even though there is still an eroute, the c->routing
2020 * setting will convince unroute_connection to delete it.
2021 * unroute_connection would be upset if c->routing == RT_ROUTED_TUNNEL
2022 */
2023 unroute_connection(c);
2024 }
2025 else
2026 {
2027 (void) shunt_eroute(c, sr, sr->routing, ERO_REPLACE, "replace with shunt");
2028 }
2029 }
2030 }
2031 (void) teardown_half_ipsec_sa(st, FALSE);
2032 }
2033 (void) teardown_half_ipsec_sa(st, TRUE);
2034 }
2035
2036 static bool update_nat_t_ipsec_esp_sa (struct state *st, bool inbound)
2037 {
2038 connection_t *c = st->st_connection;
2039 host_t *host_src, *host_dst, *new_src, *new_dst;
2040 ipsec_spi_t spi = inbound ? st->st_esp.our_spi : st->st_esp.attrs.spi;
2041 struct end *src = inbound ? &c->spd.that : &c->spd.this,
2042 *dst = inbound ? &c->spd.this : &c->spd.that;
2043 mark_t mark = inbound ? c->spd.mark_in : c->spd.mark_out;
2044 bool result;
2045
2046 host_src = host_create_from_sockaddr((sockaddr_t*)&src->host_addr);
2047 host_dst = host_create_from_sockaddr((sockaddr_t*)&dst->host_addr);
2048
2049 new_src = host_src->clone(host_src);
2050 new_dst = host_dst->clone(host_dst);
2051 new_src->set_port(new_src, src->host_port);
2052 new_dst->set_port(new_dst, dst->host_port);
2053
2054 result = hydra->kernel_interface->update_sa(hydra->kernel_interface,
2055 spi, IPPROTO_ESP, 0 /* cpi */, host_src, host_dst,
2056 new_src, new_dst, TRUE /* encap */, TRUE /* new_encap */,
2057 mark) == SUCCESS;
2058
2059 host_src->destroy(host_src);
2060 host_dst->destroy(host_dst);
2061 new_src->destroy(new_src);
2062 new_dst->destroy(new_dst);
2063
2064 return result;
2065 }
2066
2067 bool update_ipsec_sa (struct state *st)
2068 {
2069 if (IS_IPSEC_SA_ESTABLISHED(st->st_state))
2070 {
2071 if (st->st_esp.present && (
2072 (!update_nat_t_ipsec_esp_sa (st, TRUE)) ||
2073 (!update_nat_t_ipsec_esp_sa (st, FALSE))))
2074 {
2075 return FALSE;
2076 }
2077 }
2078 else if (IS_ONLY_INBOUND_IPSEC_SA_ESTABLISHED(st->st_state))
2079 {
2080 if (st->st_esp.present && !update_nat_t_ipsec_esp_sa (st, FALSE))
2081 {
2082 return FALSE;
2083 }
2084 }
2085 else
2086 {
2087 DBG_log("assert failed at %s:%d st_state=%d", __FILE__, __LINE__, st->st_state);
2088 return FALSE;
2089 }
2090 return TRUE;
2091 }
2092
2093 /* Check if there was traffic on given SA during the last idle_max
2094 * seconds. If TRUE, the SA was idle and DPD exchange should be performed.
2095 * If FALSE, DPD is not necessary. We also return TRUE for errors, as they
2096 * could mean that the SA is broken and needs to be replace anyway.
2097 */
2098 bool was_eroute_idle(struct state *st, time_t idle_max, time_t *idle_time)
2099 {
2100 time_t use_time;
2101 u_int bytes;
2102 int ret = TRUE;
2103
2104 passert(st != NULL);
2105
2106 if (get_sa_info(st, TRUE, &bytes, &use_time) && use_time != UNDEFINED_TIME)
2107 {
2108 *idle_time = time_monotonic(NULL) - use_time;
2109 ret = *idle_time >= idle_max;
2110 }
2111
2112 return ret;
2113 }