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