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