pluto: Store xfrm marks on connection and use them when installing SAs and policies.
[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 mark_t mark,
753 ipsec_spi_t spi,
754 unsigned int proto,
755 unsigned int satype,
756 unsigned int transport_proto,
757 ipsec_sa_cfg_t *sa,
758 time_t use_lifetime,
759 unsigned int op,
760 const char *opname USED_BY_DEBUG)
761 {
762 traffic_selector_t *ts_src, *ts_dst;
763 host_t *host_src, *host_dst;
764 policy_type_t type = POLICY_IPSEC;
765 policy_dir_t dir = POLICY_OUT;
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, 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, 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, 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, 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, sr->mark_out, spi, proto, satype,
878 sr->this.protocol, 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(&sr->that.host_addr, &sr->that.client,
1097 &sr->this.host_addr, &sr->this.client, sr->mark_in,
1098 htonl(spi), 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;
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 mark = c->spd.mark_in;
1123 }
1124 else
1125 {
1126 src = &c->spd.this;
1127 dst = &c->spd.that;
1128 mark = c->spd.mark_out;
1129 }
1130
1131 host_src = host_create_from_sockaddr((sockaddr_t*)&src->host_addr);
1132 host_dst = host_create_from_sockaddr((sockaddr_t*)&dst->host_addr);
1133
1134 if (st->st_ah.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL
1135 || st->st_esp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL
1136 || st->st_ipcomp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1137 {
1138 mode = MODE_TUNNEL;
1139 }
1140
1141 sa.mode = mode;
1142 sa.reqid = c->spd.reqid;
1143
1144 memset(said, 0, sizeof(said));
1145
1146 /* set up IPCOMP SA, if any */
1147
1148 if (st->st_ipcomp.present)
1149 {
1150 ipsec_spi_t ipcomp_spi = inbound ? st->st_ipcomp.our_spi
1151 : st->st_ipcomp.attrs.spi;
1152
1153 switch (st->st_ipcomp.attrs.transid)
1154 {
1155 case IPCOMP_DEFLATE:
1156 break;
1157
1158 default:
1159 loglog(RC_LOG_SERIOUS, "IPCOMP transform %s not implemented",
1160 enum_name(&ipcomp_transformid_names,
1161 st->st_ipcomp.attrs.transid));
1162 goto fail;
1163 }
1164
1165 sa.ipcomp.cpi = htons(ntohl(ipcomp_spi));
1166 sa.ipcomp.transform = st->st_ipcomp.attrs.transid;
1167
1168 said_next->spi = ipcomp_spi;
1169 said_next->proto = IPPROTO_COMP;
1170
1171 if (hydra->kernel_interface->add_sa(hydra->kernel_interface, host_src,
1172 host_dst, ipcomp_spi, said_next->proto, c->spd.reqid,
1173 mark, &lt_none, ENCR_UNDEFINED, chunk_empty,
1174 AUTH_UNDEFINED, chunk_empty, mode,
1175 st->st_ipcomp.attrs.transid, 0 /* cpi */, FALSE,
1176 inbound, NULL, NULL) != SUCCESS)
1177 {
1178 goto fail;
1179 }
1180 said_next++;
1181 mode = MODE_TRANSPORT;
1182 }
1183
1184 /* set up ESP SA, if any */
1185
1186 if (st->st_esp.present)
1187 {
1188 ipsec_spi_t esp_spi = inbound ? st->st_esp.our_spi
1189 : st->st_esp.attrs.spi;
1190 u_char *esp_dst_keymat = inbound ? st->st_esp.our_keymat
1191 : st->st_esp.peer_keymat;
1192 bool encap = st->nat_traversal & NAT_T_DETECTED;
1193 encryption_algorithm_t enc_alg;
1194 integrity_algorithm_t auth_alg;
1195 const struct esp_info *ei;
1196 chunk_t enc_key, auth_key;
1197 u_int16_t key_len;
1198
1199 if ((ei = kernel_alg_esp_info(st->st_esp.attrs.transid,
1200 st->st_esp.attrs.auth)) == NULL)
1201 {
1202 loglog(RC_LOG_SERIOUS, "ESP transform %s / auth %s"
1203 " not implemented yet",
1204 enum_name(&esp_transform_names, st->st_esp.attrs.transid),
1205 enum_name(&auth_alg_names, st->st_esp.attrs.auth));
1206 goto fail;
1207 }
1208
1209 key_len = st->st_esp.attrs.key_len / 8;
1210 if (key_len)
1211 {
1212 /* XXX: must change to check valid _range_ key_len */
1213 if (key_len > ei->enckeylen)
1214 {
1215 loglog(RC_LOG_SERIOUS, "ESP transform %s: key_len=%d > %d",
1216 enum_name(&esp_transform_names, st->st_esp.attrs.transid),
1217 (int)key_len, (int)ei->enckeylen);
1218 goto fail;
1219 }
1220 }
1221 else
1222 {
1223 key_len = ei->enckeylen;
1224 }
1225
1226 switch (ei->transid)
1227 {
1228 case ESP_3DES:
1229 /* 168 bits in kernel, need 192 bits for keymat_len */
1230 if (key_len == 21)
1231 {
1232 key_len = 24;
1233 }
1234 break;
1235 case ESP_DES:
1236 /* 56 bits in kernel, need 64 bits for keymat_len */
1237 if (key_len == 7)
1238 {
1239 key_len = 8;
1240 }
1241 break;
1242 case ESP_AES_CCM_8:
1243 case ESP_AES_CCM_12:
1244 case ESP_AES_CCM_16:
1245 key_len += 3;
1246 break;
1247 case ESP_AES_GCM_8:
1248 case ESP_AES_GCM_12:
1249 case ESP_AES_GCM_16:
1250 case ESP_AES_CTR:
1251 case ESP_AES_GMAC:
1252 key_len += 4;
1253 break;
1254 default:
1255 break;
1256 }
1257
1258 if (encap)
1259 {
1260 host_src->set_port(host_src, src->host_port);
1261 host_dst->set_port(host_dst, dst->host_port);
1262 // st->nat_oa is currently unused
1263 }
1264
1265 /* divide up keying material */
1266 enc_alg = encryption_algorithm_from_esp(st->st_esp.attrs.transid);
1267 enc_key.ptr = esp_dst_keymat;
1268 enc_key.len = key_len;
1269 auth_alg = integrity_algorithm_from_esp(st->st_esp.attrs.auth);
1270 auth_alg = auth_alg ? : AUTH_UNDEFINED;
1271 auth_key.ptr = esp_dst_keymat + key_len;
1272 auth_key.len = ei->authkeylen;
1273
1274 sa.esp.use = TRUE;
1275 sa.esp.spi = esp_spi;
1276
1277 said_next->spi = esp_spi;
1278 said_next->proto = IPPROTO_ESP;
1279
1280 if (hydra->kernel_interface->add_sa(hydra->kernel_interface, host_src,
1281 host_dst, esp_spi, said_next->proto, c->spd.reqid,
1282 mark, &lt_none, enc_alg, enc_key,
1283 auth_alg, auth_key, mode, IPCOMP_NONE, 0 /* cpi */,
1284 encap, inbound, NULL, NULL) != SUCCESS)
1285 {
1286 goto fail;
1287 }
1288 said_next++;
1289 mode = MODE_TRANSPORT;
1290 }
1291
1292 /* set up AH SA, if any */
1293
1294 if (st->st_ah.present)
1295 {
1296 ipsec_spi_t ah_spi = inbound ? st->st_ah.our_spi
1297 : st->st_ah.attrs.spi;
1298 u_char *ah_dst_keymat = inbound ? st->st_ah.our_keymat
1299 : st->st_ah.peer_keymat;
1300 integrity_algorithm_t auth_alg;
1301 chunk_t auth_key;
1302
1303 auth_alg = integrity_algorithm_from_esp(st->st_ah.attrs.auth);
1304 auth_key.ptr = ah_dst_keymat;
1305 auth_key.len = st->st_ah.keymat_len;
1306
1307 sa.ah.use = TRUE;
1308 sa.ah.spi = ah_spi;
1309
1310 said_next->spi = ah_spi;
1311 said_next->proto = IPPROTO_AH;
1312
1313 if (hydra->kernel_interface->add_sa(hydra->kernel_interface, host_src,
1314 host_dst, ah_spi, said_next->proto, c->spd.reqid,
1315 mark, &lt_none, ENCR_UNDEFINED, chunk_empty,
1316 auth_alg, auth_key, mode, IPCOMP_NONE, 0 /* cpi */,
1317 FALSE, inbound, NULL, NULL) != SUCCESS)
1318 {
1319 goto fail;
1320 }
1321 said_next++;
1322 mode = MODE_TRANSPORT;
1323 }
1324
1325 if (inbound && c->spd.eroute_owner == SOS_NOBODY)
1326 {
1327 (void) raw_eroute(&src->host_addr, &src->client, &dst->host_addr,
1328 &dst->client, mark, 256, SA_IPIP, SADB_SATYPE_UNSPEC,
1329 c->spd.this.protocol, &sa, 0, ERO_ADD_INBOUND,
1330 "add inbound");
1331 }
1332
1333 goto cleanup;
1334
1335 fail:
1336 /* undo the done SPIs */
1337 while (said_next-- != said)
1338 {
1339 hydra->kernel_interface->del_sa(hydra->kernel_interface, host_src,
1340 host_dst, said_next->spi,
1341 said_next->proto, 0 /* cpi */,
1342 mark);
1343 }
1344 ok = FALSE;
1345
1346 cleanup:
1347 host_src->destroy(host_src);
1348 host_dst->destroy(host_dst);
1349 return ok;
1350 }
1351
1352 static bool teardown_half_ipsec_sa(struct state *st, bool inbound)
1353 {
1354 connection_t *c = st->st_connection;
1355 const struct end *src, *dst;
1356 host_t *host_src, *host_dst;
1357 ipsec_spi_t spi;
1358 mark_t mark;
1359 bool result = TRUE;
1360
1361 if (inbound)
1362 {
1363 src = &c->spd.that;
1364 dst = &c->spd.this;
1365 mark = c->spd.mark_in;
1366
1367 if (c->spd.eroute_owner == SOS_NOBODY)
1368 {
1369 (void) raw_eroute(&src->host_addr, &src->client, &dst->host_addr,
1370 &dst->client, mark, 256, IPSEC_PROTO_ANY,
1371 SADB_SATYPE_UNSPEC, c->spd.this.protocol,
1372 &null_ipsec_sa, 0, ERO_DEL_INBOUND,
1373 "delete inbound");
1374 }
1375 }
1376 else
1377 {
1378 src = &c->spd.this;
1379 dst = &c->spd.that;
1380 mark = c->spd.mark_out;
1381 }
1382
1383 host_src = host_create_from_sockaddr((sockaddr_t*)&src->host_addr);
1384 host_dst = host_create_from_sockaddr((sockaddr_t*)&dst->host_addr);
1385
1386 if (st->st_ah.present)
1387 {
1388 spi = inbound ? st->st_ah.our_spi : st->st_ah.attrs.spi;
1389 result &= hydra->kernel_interface->del_sa(hydra->kernel_interface,
1390 host_src, host_dst, spi, IPPROTO_AH,
1391 0 /* cpi */, mark) == SUCCESS;
1392 }
1393
1394 if (st->st_esp.present)
1395 {
1396 spi = inbound ? st->st_esp.our_spi : st->st_esp.attrs.spi;
1397 result &= hydra->kernel_interface->del_sa(hydra->kernel_interface,
1398 host_src, host_dst, spi, IPPROTO_ESP,
1399 0 /* cpi */, mark) == SUCCESS;
1400 }
1401
1402 if (st->st_ipcomp.present)
1403 {
1404 spi = inbound ? st->st_ipcomp.our_spi : st->st_ipcomp.attrs.spi;
1405 result &= hydra->kernel_interface->del_sa(hydra->kernel_interface,
1406 host_src, host_dst, spi, IPPROTO_COMP,
1407 0 /* cpi */, mark) == SUCCESS;
1408 }
1409
1410 host_src->destroy(host_src);
1411 host_dst->destroy(host_dst);
1412
1413 return result;
1414 }
1415
1416 /*
1417 * get information about a given sa
1418 */
1419 bool get_sa_info(struct state *st, bool inbound, u_int *bytes, time_t *use_time)
1420 {
1421 connection_t *c = st->st_connection;
1422 traffic_selector_t *ts_src = NULL, *ts_dst = NULL;
1423 host_t *host_src = NULL, *host_dst = NULL;
1424 const struct end *src, *dst;
1425 ipsec_spi_t spi;
1426 mark_t mark;
1427 u_int64_t bytes_kernel = 0;
1428 bool result = FALSE;
1429
1430 *use_time = UNDEFINED_TIME;
1431
1432 if (!st->st_esp.present)
1433 {
1434 goto failed;
1435 }
1436
1437 if (inbound)
1438 {
1439 src = &c->spd.that;
1440 dst = &c->spd.this;
1441 mark = c->spd.mark_in;
1442 spi = st->st_esp.our_spi;
1443 }
1444 else
1445 {
1446 src = &c->spd.this;
1447 dst = &c->spd.that;
1448 mark = c->spd.mark_out;
1449 spi = st->st_esp.attrs.spi;
1450 }
1451
1452 host_src = host_create_from_sockaddr((sockaddr_t*)&src->host_addr);
1453 host_dst = host_create_from_sockaddr((sockaddr_t*)&dst->host_addr);
1454
1455 switch(hydra->kernel_interface->query_sa(hydra->kernel_interface, host_src,
1456 host_dst, spi, IPPROTO_ESP,
1457 mark, &bytes_kernel))
1458 {
1459 case FAILED:
1460 goto failed;
1461 case SUCCESS:
1462 *bytes = bytes_kernel;
1463 break;
1464 case NOT_SUPPORTED:
1465 default:
1466 break;
1467 }
1468
1469 if (st->st_serialno == c->spd.eroute_owner)
1470 {
1471 u_int32_t time_kernel;
1472
1473 ts_src = traffic_selector_from_subnet(&src->client, src->protocol);
1474 ts_dst = traffic_selector_from_subnet(&dst->client, dst->protocol);
1475
1476 if (hydra->kernel_interface->query_policy(hydra->kernel_interface,
1477 ts_src, ts_dst, inbound ? POLICY_IN : POLICY_OUT,
1478 mark, &time_kernel) != SUCCESS)
1479 {
1480 goto failed;
1481 }
1482 *use_time = time_kernel;
1483
1484 if (inbound &&
1485 st->st_esp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1486 {
1487 if (hydra->kernel_interface->query_policy(hydra->kernel_interface,
1488 ts_src, ts_dst, POLICY_FWD, mark,
1489 &time_kernel) != SUCCESS)
1490 {
1491 goto failed;
1492 }
1493 *use_time = max(*use_time, time_kernel);
1494 }
1495 }
1496
1497 result = TRUE;
1498
1499 failed:
1500 DESTROY_IF(host_src);
1501 DESTROY_IF(host_dst);
1502 DESTROY_IF(ts_src);
1503 DESTROY_IF(ts_dst);
1504 return result;
1505 }
1506
1507 /**
1508 * Handler for kernel events (called by thread-pool thread)
1509 */
1510 kernel_listener_t *kernel_handler;
1511
1512 /**
1513 * Data for acquire events
1514 */
1515 typedef struct {
1516 /** Subnets */
1517 ip_subnet src, dst;
1518 /** Transport protocol */
1519 int proto;
1520 } acquire_data_t;
1521
1522 /**
1523 * Callback for acquire events (called by main thread)
1524 */
1525 void handle_acquire(acquire_data_t *this)
1526 {
1527 record_and_initiate_opportunistic(&this->src, &this->dst, this->proto,
1528 "%acquire");
1529 }
1530
1531 METHOD(kernel_listener_t, acquire, bool,
1532 kernel_listener_t *this, u_int32_t reqid,
1533 traffic_selector_t *src_ts, traffic_selector_t *dst_ts)
1534 {
1535 if (src_ts && dst_ts)
1536 {
1537 acquire_data_t *data;
1538 DBG(DBG_CONTROL,
1539 DBG_log("creating acquire event for policy %R === %R "
1540 "with reqid {%u}", src_ts, dst_ts, reqid));
1541 INIT(data,
1542 .src = subnet_from_traffic_selector(src_ts),
1543 .dst = subnet_from_traffic_selector(dst_ts),
1544 .proto = src_ts->get_protocol(src_ts),
1545 );
1546 pluto->events->queue(pluto->events, (void*)handle_acquire, data, free);
1547 }
1548 else
1549 {
1550 DBG(DBG_CONTROL,
1551 DBG_log("ignoring acquire without traffic selectors for policy "
1552 "with reqid {%u}", reqid));
1553 }
1554 DESTROY_IF(src_ts);
1555 DESTROY_IF(dst_ts);
1556 return TRUE;
1557 }
1558
1559 /**
1560 * Data for mapping events
1561 */
1562 typedef struct {
1563 /** reqid, spi of affected SA */
1564 u_int32_t reqid, spi;
1565 /** new endpont */
1566 ip_address new_end;
1567 } mapping_data_t;
1568
1569 /**
1570 * Callback for mapping events (called by main thread)
1571 */
1572 void handle_mapping(mapping_data_t *this)
1573 {
1574 process_nat_t_new_mapping(this->reqid, this->spi, &this->new_end);
1575 }
1576
1577
1578 METHOD(kernel_listener_t, mapping, bool,
1579 kernel_listener_t *this, u_int32_t reqid, u_int32_t spi, host_t *remote)
1580 {
1581 mapping_data_t *data;
1582 DBG(DBG_CONTROL,
1583 DBG_log("creating mapping event for SA with SPI %.8x and reqid {%u}",
1584 spi, reqid));
1585 INIT(data,
1586 .reqid = reqid,
1587 .spi = spi,
1588 .new_end = *(ip_address*)remote->get_sockaddr(remote),
1589 );
1590 pluto->events->queue(pluto->events, (void*)handle_mapping, data, free);
1591 return TRUE;
1592 }
1593
1594 void init_kernel(void)
1595 {
1596 /* register SA types that we can negotiate */
1597 can_do_IPcomp = FALSE; /* until we get a response from the kernel */
1598 pfkey_register();
1599
1600 INIT(kernel_handler,
1601 .acquire = _acquire,
1602 .mapping = _mapping,
1603 );
1604 hydra->kernel_interface->add_listener(hydra->kernel_interface,
1605 kernel_handler);
1606 }
1607
1608 void kernel_finalize()
1609 {
1610 hydra->kernel_interface->remove_listener(hydra->kernel_interface,
1611 kernel_handler);
1612 }
1613
1614 /* Note: install_inbound_ipsec_sa is only used by the Responder.
1615 * The Responder will subsequently use install_ipsec_sa for the outbound.
1616 * The Initiator uses install_ipsec_sa to install both at once.
1617 */
1618 bool install_inbound_ipsec_sa(struct state *st)
1619 {
1620 connection_t *const c = st->st_connection;
1621
1622 /* If our peer has a fixed-address client, check if we already
1623 * have a route for that client that conflicts. We will take this
1624 * as proof that that route and the connections using it are
1625 * obsolete and should be eliminated. Interestingly, this is
1626 * the only case in which we can tell that a connection is obsolete.
1627 */
1628 passert(c->kind == CK_PERMANENT || c->kind == CK_INSTANCE);
1629 if (c->spd.that.has_client)
1630 {
1631 for (;;)
1632 {
1633 struct spd_route *esr;
1634 connection_t *o = route_owner(c, &esr, NULL, NULL);
1635
1636 if (o == NULL)
1637 {
1638 break; /* nobody has a route */
1639 }
1640
1641 /* note: we ignore the client addresses at this end */
1642 if (sameaddr(&o->spd.that.host_addr, &c->spd.that.host_addr) &&
1643 o->interface == c->interface)
1644 {
1645 break; /* existing route is compatible */
1646 }
1647
1648 if (o->kind == CK_TEMPLATE && streq(o->name, c->name))
1649 {
1650 break; /* ??? is this good enough?? */
1651 }
1652
1653 loglog(RC_LOG_SERIOUS, "route to peer's client conflicts with \"%s\" %s; releasing old connection to free the route"
1654 , o->name, ip_str(&o->spd.that.host_addr));
1655 release_connection(o, FALSE);
1656 }
1657 }
1658
1659 DBG(DBG_CONTROL, DBG_log("install_inbound_ipsec_sa() checking if we can route"));
1660 /* check that we will be able to route and eroute */
1661 switch (could_route(c))
1662 {
1663 case route_easy:
1664 case route_nearconflict:
1665 break;
1666 default:
1667 return FALSE;
1668 }
1669
1670 /* (attempt to) actually set up the SAs */
1671 return setup_half_ipsec_sa(st, TRUE);
1672 }
1673
1674 /* Install a route and then a prospective shunt eroute or an SA group eroute.
1675 * Assumption: could_route gave a go-ahead.
1676 * Any SA Group must have already been created.
1677 * On failure, steps will be unwound.
1678 */
1679 bool route_and_eroute(connection_t *c, struct spd_route *sr, struct state *st)
1680 {
1681 struct spd_route *esr;
1682 struct spd_route *rosr;
1683 connection_t *ero /* who, if anyone, owns our eroute? */
1684 , *ro = route_owner(c, &rosr, &ero, &esr);
1685 bool eroute_installed = FALSE
1686 , firewall_notified = FALSE
1687 , route_installed = FALSE;
1688
1689 connection_t *ero_top;
1690
1691 DBG(DBG_CONTROLMORE,
1692 DBG_log("route_and_eroute with c: %s (next: %s) ero:%s esr:{%p} ro:%s rosr:{%p} and state: %lu"
1693 , c->name
1694 , (c->policy_next ? c->policy_next->name : "none")
1695 , ero ? ero->name : "null"
1696 , esr
1697 , ro ? ro->name : "null"
1698 , rosr
1699 , st ? st->st_serialno : 0));
1700
1701 /* look along the chain of policies for one with the same name */
1702 ero_top = ero;
1703
1704 #if 0
1705 /* XXX - mcr this made sense before, and likely will make sense
1706 * again, so I'l leaving this to remind me what is up */
1707 if (ero!= NULL && ero->routing == RT_UNROUTED_KEYED)
1708 ero = NULL;
1709
1710 for (ero2 = ero; ero2 != NULL; ero2 = ero->policy_next)
1711 if ((ero2->kind == CK_TEMPLATE || ero2->kind==CK_SECONDARY)
1712 && streq(ero2->name, c->name))
1713 break;
1714 #endif
1715
1716 /* install the eroute */
1717
1718 if (ero != NULL)
1719 {
1720 /* We're replacing an eroute */
1721
1722 /* if no state provided, then install a shunt for later */
1723 if (st == NULL)
1724 {
1725 eroute_installed = shunt_eroute(c, sr, RT_ROUTED_PROSPECTIVE
1726 , ERO_REPLACE, "replace");
1727 }
1728 else
1729 {
1730 eroute_installed = sag_eroute(st, sr, ERO_REPLACE, "replace");
1731 }
1732 #if 0
1733 /* XXX - MCR. I previously felt that this was a bogus check */
1734 if (ero != NULL && ero != c && esr != sr)
1735 {
1736 /* By elimination, we must be eclipsing ero. Check. */
1737 passert(ero->kind == CK_TEMPLATE && streq(ero->name, c->name));
1738 passert(LHAS(LELEM(RT_ROUTED_PROSPECTIVE) | LELEM(RT_ROUTED_ECLIPSED)
1739 , esr->routing));
1740 passert(samesubnet(&esr->this.client, &sr->this.client)
1741 && samesubnet(&esr->that.client, &sr->that.client));
1742 }
1743 #endif
1744 }
1745 else
1746 {
1747 /* we're adding an eroute */
1748
1749 /* if no state provided, then install a shunt for later */
1750 if (st == NULL)
1751 {
1752 eroute_installed = shunt_eroute(c, sr, RT_ROUTED_PROSPECTIVE
1753 , ERO_ADD, "add");
1754 }
1755 else
1756 {
1757 eroute_installed = sag_eroute(st, sr, ERO_ADD, "add");
1758 }
1759 }
1760
1761 /* notify the firewall of a new tunnel */
1762
1763 if (eroute_installed)
1764 {
1765 /* do we have to notify the firewall? Yes, if we are installing
1766 * a tunnel eroute and the firewall wasn't notified
1767 * for a previous tunnel with the same clients. Any Previous
1768 * tunnel would have to be for our connection, so the actual
1769 * test is simple.
1770 */
1771 firewall_notified = st == NULL /* not a tunnel eroute */
1772 || sr->eroute_owner != SOS_NOBODY /* already notified */
1773 || do_command(c, sr, st, "up"); /* go ahead and notify */
1774 }
1775
1776 /* install the route */
1777
1778 DBG(DBG_CONTROL,
1779 DBG_log("route_and_eroute: firewall_notified: %s"
1780 , firewall_notified ? "true" : "false"));
1781 if (!firewall_notified)
1782 {
1783 /* we're in trouble -- don't do routing */
1784 }
1785 else if (ro == NULL)
1786 {
1787 /* a new route: no deletion required, but preparation is */
1788 (void) do_command(c, sr, st, "prepare"); /* just in case; ignore failure */
1789 route_installed = do_command(c, sr, st, "route");
1790 }
1791 else if (routed(sr->routing) || routes_agree(ro, c))
1792 {
1793 route_installed = TRUE; /* nothing to be done */
1794 }
1795 else
1796 {
1797 /* Some other connection must own the route
1798 * and the route must disagree. But since could_route
1799 * must have allowed our stealing it, we'll do so.
1800 *
1801 * A feature of LINUX allows us to install the new route
1802 * before deleting the old if the nexthops differ.
1803 * This reduces the "window of vulnerability" when packets
1804 * might flow in the clear.
1805 */
1806 if (sameaddr(&sr->this.host_nexthop, &esr->this.host_nexthop))
1807 {
1808 (void) do_command(ro, sr, st, "unroute");
1809 route_installed = do_command(c, sr, st, "route");
1810 }
1811 else
1812 {
1813 route_installed = do_command(c, sr, st, "route");
1814 (void) do_command(ro, sr, st, "unroute");
1815 }
1816
1817 /* record unrouting */
1818 if (route_installed)
1819 {
1820 do {
1821 passert(!erouted(rosr->routing));
1822 rosr->routing = RT_UNROUTED;
1823
1824 /* no need to keep old value */
1825 ro = route_owner(c, &rosr, NULL, NULL);
1826 } while (ro != NULL);
1827 }
1828 }
1829
1830 /* all done -- clean up */
1831 if (route_installed)
1832 {
1833 /* Success! */
1834
1835 if (ero != NULL && ero != c)
1836 {
1837 /* check if ero is an ancestor of c. */
1838 connection_t *ero2;
1839
1840 for (ero2 = c; ero2 != NULL && ero2 != c; ero2 = ero2->policy_next)
1841 ;
1842
1843 if (ero2 == NULL)
1844 {
1845 /* By elimination, we must be eclipsing ero. Checked above. */
1846 if (ero->spd.routing != RT_ROUTED_ECLIPSED)
1847 {
1848 ero->spd.routing = RT_ROUTED_ECLIPSED;
1849 eclipse_count++;
1850 }
1851 }
1852 }
1853
1854 if (st == NULL)
1855 {
1856 passert(sr->eroute_owner == SOS_NOBODY);
1857 sr->routing = RT_ROUTED_PROSPECTIVE;
1858 }
1859 else
1860 {
1861 char cib[CONN_INST_BUF];
1862 sr->routing = RT_ROUTED_TUNNEL;
1863
1864 DBG(DBG_CONTROL,
1865 DBG_log("route_and_eroute: instance \"%s\"%s, setting eroute_owner {spd=%p,sr=%p} to #%ld (was #%ld) (newest_ipsec_sa=#%ld)"
1866 , st->st_connection->name
1867 , (fmt_conn_instance(st->st_connection, cib), cib)
1868 , &st->st_connection->spd, sr
1869 , st->st_serialno
1870 , sr->eroute_owner
1871 , st->st_connection->newest_ipsec_sa));
1872 sr->eroute_owner = st->st_serialno;
1873 }
1874
1875 return TRUE;
1876 }
1877 else
1878 {
1879 /* Failure! Unwind our work. */
1880 if (firewall_notified && sr->eroute_owner == SOS_NOBODY)
1881 (void) do_command(c, sr, st, "down");
1882
1883 if (eroute_installed)
1884 {
1885 /* Restore original eroute, if we can.
1886 * Since there is nothing much to be done if the restoration
1887 * fails, ignore success or failure.
1888 */
1889 if (ero != NULL)
1890 {
1891 /* restore ero's former glory */
1892 if (esr->eroute_owner == SOS_NOBODY)
1893 {
1894 /* note: normal or eclipse case */
1895 (void) shunt_eroute(ero, esr
1896 , esr->routing, ERO_REPLACE, "restore");
1897 }
1898 else
1899 {
1900 /* Try to find state that owned eroute.
1901 * Don't do anything if it cannot be found.
1902 * This case isn't likely since we don't run
1903 * the updown script when replacing a SA group
1904 * with its successor (for the same conn).
1905 */
1906 struct state *ost = state_with_serialno(esr->eroute_owner);
1907
1908 if (ost != NULL)
1909 (void) sag_eroute(ost, esr, ERO_REPLACE, "restore");
1910 }
1911 }
1912 else
1913 {
1914 /* there was no previous eroute: delete whatever we installed */
1915 if (st == NULL)
1916 {
1917 (void) shunt_eroute(c, sr, sr->routing, ERO_DELETE, "delete");
1918 }
1919 else
1920 {
1921 (void) sag_eroute(st, sr, ERO_DELETE, "delete");
1922 }
1923 }
1924 }
1925
1926 return FALSE;
1927 }
1928 }
1929
1930 bool install_ipsec_sa(struct state *st, bool inbound_also)
1931 {
1932 struct spd_route *sr;
1933
1934 DBG(DBG_CONTROL, DBG_log("install_ipsec_sa() for #%ld: %s"
1935 , st->st_serialno
1936 , inbound_also?
1937 "inbound and outbound" : "outbound only"));
1938
1939 switch (could_route(st->st_connection))
1940 {
1941 case route_easy:
1942 case route_nearconflict:
1943 break;
1944 default:
1945 return FALSE;
1946 }
1947
1948 /* (attempt to) actually set up the SA group */
1949 if ((inbound_also && !setup_half_ipsec_sa(st, TRUE)) ||
1950 !setup_half_ipsec_sa(st, FALSE))
1951 {
1952 return FALSE;
1953 }
1954
1955 for (sr = &st->st_connection->spd; sr != NULL; sr = sr->next)
1956 {
1957 DBG(DBG_CONTROL, DBG_log("sr for #%ld: %s"
1958 , st->st_serialno
1959 , enum_name(&routing_story, sr->routing)));
1960
1961 /*
1962 * if the eroute owner is not us, then make it us.
1963 * See test co-terminal-02, pluto-rekey-01, pluto-unit-02/oppo-twice
1964 */
1965 pexpect(sr->eroute_owner == SOS_NOBODY
1966 || sr->routing >= RT_ROUTED_TUNNEL);
1967
1968 if (sr->eroute_owner != st->st_serialno
1969 && sr->routing != RT_UNROUTED_KEYED)
1970 {
1971 if (!route_and_eroute(st->st_connection, sr, st))
1972 {
1973 delete_ipsec_sa(st, FALSE);
1974 /* XXX go and unroute any SRs that were successfully
1975 * routed already.
1976 */
1977 return FALSE;
1978 }
1979 }
1980 }
1981
1982 return TRUE;
1983 }
1984
1985 /* delete an IPSEC SA.
1986 * we may not succeed, but we bull ahead anyway because
1987 * we cannot do anything better by recognizing failure
1988 */
1989 void delete_ipsec_sa(struct state *st, bool inbound_only)
1990 {
1991 if (!inbound_only)
1992 {
1993 /* If the state is the eroute owner, we must adjust
1994 * the routing for the connection.
1995 */
1996 connection_t *c = st->st_connection;
1997 struct spd_route *sr;
1998
1999 passert(st->st_connection);
2000
2001 for (sr = &c->spd; sr; sr = sr->next)
2002 {
2003 if (sr->eroute_owner == st->st_serialno
2004 && sr->routing == RT_ROUTED_TUNNEL)
2005 {
2006 sr->eroute_owner = SOS_NOBODY;
2007
2008 /* Routing should become RT_ROUTED_FAILURE,
2009 * but if POLICY_FAIL_NONE, then we just go
2010 * right back to RT_ROUTED_PROSPECTIVE as if no
2011 * failure happened.
2012 */
2013 sr->routing = (c->policy & POLICY_FAIL_MASK) == POLICY_FAIL_NONE
2014 ? RT_ROUTED_PROSPECTIVE : RT_ROUTED_FAILURE;
2015
2016 (void) do_command(c, sr, st, "down");
2017 if ((c->policy & POLICY_DONT_REKEY) && c->kind == CK_INSTANCE)
2018 {
2019 /* in this special case, even if the connection
2020 * is still alive (due to an ISAKMP SA),
2021 * we get rid of routing.
2022 * Even though there is still an eroute, the c->routing
2023 * setting will convince unroute_connection to delete it.
2024 * unroute_connection would be upset if c->routing == RT_ROUTED_TUNNEL
2025 */
2026 unroute_connection(c);
2027 }
2028 else
2029 {
2030 (void) shunt_eroute(c, sr, sr->routing, ERO_REPLACE, "replace with shunt");
2031 }
2032 }
2033 }
2034 (void) teardown_half_ipsec_sa(st, FALSE);
2035 }
2036 (void) teardown_half_ipsec_sa(st, TRUE);
2037 }
2038
2039 static bool update_nat_t_ipsec_esp_sa (struct state *st, bool inbound)
2040 {
2041 connection_t *c = st->st_connection;
2042 host_t *host_src, *host_dst, *new_src, *new_dst;
2043 ipsec_spi_t spi = inbound ? st->st_esp.our_spi : st->st_esp.attrs.spi;
2044 struct end *src = inbound ? &c->spd.that : &c->spd.this,
2045 *dst = inbound ? &c->spd.this : &c->spd.that;
2046 mark_t mark = inbound ? c->spd.mark_in : c->spd.mark_out;
2047 bool result;
2048
2049 host_src = host_create_from_sockaddr((sockaddr_t*)&src->host_addr);
2050 host_dst = host_create_from_sockaddr((sockaddr_t*)&dst->host_addr);
2051
2052 new_src = host_src->clone(host_src);
2053 new_dst = host_dst->clone(host_dst);
2054 new_src->set_port(new_src, src->host_port);
2055 new_dst->set_port(new_dst, dst->host_port);
2056
2057 result = hydra->kernel_interface->update_sa(hydra->kernel_interface,
2058 spi, IPPROTO_ESP, 0 /* cpi */, host_src, host_dst,
2059 new_src, new_dst, TRUE /* encap */, TRUE /* new_encap */,
2060 mark) == SUCCESS;
2061
2062 host_src->destroy(host_src);
2063 host_dst->destroy(host_dst);
2064 new_src->destroy(new_src);
2065 new_dst->destroy(new_dst);
2066
2067 return result;
2068 }
2069
2070 bool update_ipsec_sa (struct state *st)
2071 {
2072 if (IS_IPSEC_SA_ESTABLISHED(st->st_state))
2073 {
2074 if (st->st_esp.present && (
2075 (!update_nat_t_ipsec_esp_sa (st, TRUE)) ||
2076 (!update_nat_t_ipsec_esp_sa (st, FALSE))))
2077 {
2078 return FALSE;
2079 }
2080 }
2081 else if (IS_ONLY_INBOUND_IPSEC_SA_ESTABLISHED(st->st_state))
2082 {
2083 if (st->st_esp.present && !update_nat_t_ipsec_esp_sa (st, FALSE))
2084 {
2085 return FALSE;
2086 }
2087 }
2088 else
2089 {
2090 DBG_log("assert failed at %s:%d st_state=%d", __FILE__, __LINE__, st->st_state);
2091 return FALSE;
2092 }
2093 return TRUE;
2094 }
2095
2096 /* Check if there was traffic on given SA during the last idle_max
2097 * seconds. If TRUE, the SA was idle and DPD exchange should be performed.
2098 * If FALSE, DPD is not necessary. We also return TRUE for errors, as they
2099 * could mean that the SA is broken and needs to be replace anyway.
2100 */
2101 bool was_eroute_idle(struct state *st, time_t idle_max, time_t *idle_time)
2102 {
2103 time_t use_time;
2104 u_int bytes;
2105 int ret = TRUE;
2106
2107 passert(st != NULL);
2108
2109 if (get_sa_info(st, TRUE, &bytes, &use_time) && use_time != UNDEFINED_TIME)
2110 {
2111 *idle_time = time_monotonic(NULL) - use_time;
2112 ret = *idle_time >= idle_max;
2113 }
2114
2115 return ret;
2116 }