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