1 /* routines that interface with the kernel's IPsec mechanism
3 * Copyright (C) 2010 Tobias Brunner
4 * Copyright (C) 2009 Andreas Steffen
5 * Hochschule fuer Technik Rapperswil
7 * Copyright (C) 1998-2002 D. Hugh Redelmeier
8 * Copyright (C) 1997 Angelos D. Keromytis
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>.
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
29 #include <sys/queue.h>
32 #include <sys/socket.h>
33 #include <netinet/in.h>
34 #include <arpa/inet.h>
40 #include <crypto/rngs/rng.h>
41 #include <kernel/kernel_listener.h>
44 #include <sys/time.h> /* for select(2) */
45 #include <sys/types.h> /* for select(2) */
48 #include "kameipsec.h"
50 #include "constants.h"
52 #include "connections.h"
56 #include "kernel_pfkey.h"
60 #include "whack.h" /* for RC_LOG_SERIOUS */
63 #include "nat_traversal.h"
65 #include "kernel_alg.h"
69 bool can_do_IPcomp
= TRUE
; /* can system actually perform IPCOMP? */
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.
75 #define routes_agree(c, d) ((c)->interface == (d)->interface \
76 && sameaddr(&(c)->spd.this.host_nexthop, &(d)->spd.this.host_nexthop))
78 /* forward declaration */
79 static bool shunt_eroute(connection_t
*c
, struct spd_route
*sr
,
80 enum routing_t rt_kind
, unsigned int op
,
83 static void set_text_said(char *text_said
, const ip_address
*dst
,
84 ipsec_spi_t spi
, int proto
);
87 * Default IPsec SA config (e.g. to install trap policies).
89 static ipsec_sa_cfg_t null_ipsec_sa
= {
90 .mode
= MODE_TRANSPORT
,
97 * Helper function that converts an ip_subnet to a traffic_selector_t.
99 static traffic_selector_t
*traffic_selector_from_subnet(const ip_subnet
*client
,
100 const u_int8_t proto
)
102 traffic_selector_t
*ts
;
104 net
= host_create_from_sockaddr((sockaddr_t
*)&client
->addr
);
105 ts
= traffic_selector_create_from_subnet(net
, client
->maskbits
, proto
,
111 * Helper function that converts a traffic_selector_t to an ip_subnet.
113 static ip_subnet
subnet_from_traffic_selector(traffic_selector_t
*ts
)
118 ts
->to_subnet(ts
, &net
, &mask
);
119 subnet
.addr
= *(ip_address
*)net
->get_sockaddr(net
);
120 subnet
.maskbits
= mask
;
126 void record_and_initiate_opportunistic(const ip_subnet
*ours
,
127 const ip_subnet
*his
,
128 int transport_proto
, const char *why
)
131 passert(samesubnettype(ours
, his
));
133 /* actually initiate opportunism */
134 networkof(ours
, &src
);
135 networkof(his
, &dst
);
136 initiate_opportunistic(&src
, &dst
, transport_proto
, TRUE
, NULL_FD
);
139 /* Generate Unique SPI numbers.
141 * The returned SPI is in network byte order.
143 ipsec_spi_t
get_ipsec_spi(ipsec_spi_t avoid
, int proto
, struct spd_route
*sr
,
146 host_t
*host_src
, *host_dst
;
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
);
152 if (hydra
->kernel_interface
->get_spi(hydra
->kernel_interface
, host_src
,
153 host_dst
, proto
, sr
->reqid
, &spi
) != SUCCESS
)
158 host_src
->destroy(host_src
);
159 host_dst
->destroy(host_dst
);
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.
168 ipsec_spi_t
get_my_cpi(struct spd_route
*sr
, bool tunnel
)
170 host_t
*host_src
, *host_dst
;
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
);
176 if (hydra
->kernel_interface
->get_cpi(hydra
->kernel_interface
, host_src
,
177 host_dst
, sr
->reqid
, &cpi
) != SUCCESS
)
183 host_src
->destroy(host_src
);
184 host_dst
->destroy(host_dst
);
186 return htonl((u_int32_t
)ntohs(cpi
));
189 /* Replace the shell metacharacters ', \, ", `, and $ in a character string
190 * by escape sequences consisting of their octal values
192 static void escape_metachar(const char *src
, char *dst
, size_t dstlen
)
194 while (*src
!= '\0' && dstlen
> 4)
203 sprintf(dst
,"\\%s%o", (*src
< 64)?
"0":"", *src
);
216 /* invoke the updown script to do the routing and firewall commands required
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_".
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.
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.
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).
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).
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.
245 * "down-host" and "down-client" are run when an eroute is deleted.
246 * They are useful for adjusting a firewall.
249 #ifndef DEFAULT_UPDOWN
250 # define DEFAULT_UPDOWN "ipsec _updown"
253 static bool do_command(connection_t
*c
, struct spd_route
*sr
, struct state
*st
,
256 char cmd
[1536]; /* arbitrary limit on shell command length */
257 const char *verb_suffix
;
259 /* figure out which verb suffix applies */
263 switch (addrtypeof(&sr
->this.host_addr
))
274 loglog(RC_LOG_SERIOUS
, "unknown address family");
277 verb_suffix
= subnetisaddr(&sr
->this.client
, &sr
->this.host_addr
)
281 /* form the command string */
284 nexthop_str
[sizeof("PLUTO_NEXT_HOP='' ") +ADDRTOT_BUF
] = "",
285 srcip_str
[sizeof("PLUTO_MY_SOURCEIP='' ")+ADDRTOT_BUF
] = "",
288 myclient_str
[SUBNETTOT_BUF
],
289 myclientnet_str
[ADDRTOT_BUF
],
290 myclientmask_str
[ADDRTOT_BUF
],
291 peer_str
[ADDRTOT_BUF
],
293 peerclient_str
[SUBNETTOT_BUF
],
294 peerclientnet_str
[ADDRTOT_BUF
],
295 peerclientmask_str
[ADDRTOT_BUF
],
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
] = "";
308 if (addrbytesptr(&sr
->this.host_nexthop
, NULL
)
309 && !isanyaddr(&sr
->this.host_nexthop
))
313 strcpy(nexthop_str
, "PLUTO_NEXT_HOP='");
314 n
= nexthop_str
+ strlen(nexthop_str
);
316 addrtot(&sr
->this.host_nexthop
, 0
317 ,n
, sizeof(nexthop_str
)-strlen(nexthop_str
));
318 strncat(nexthop_str
, "' ", sizeof(nexthop_str
));
321 if (!sr
->this.host_srcip
->is_anyaddr(sr
->this.host_srcip
))
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
));
332 if (sr
->mark_in
.value
)
334 snprintf(mark_in
, sizeof(mark_in
), "PLUTO_MARK_IN='%u/0x%08x' ",
335 sr
->mark_in
.value
, sr
->mark_in
.mask
);
338 if (sr
->mark_out
.value
)
340 snprintf(mark_out
, sizeof(mark_out
), "PLUTO_MARK_OUT='%u/0x%08x' ",
341 sr
->mark_out
.value
, sr
->mark_out
.mask
);
344 if (st
&& (st
->nat_traversal
& NAT_T_DETECTED
))
346 snprintf(udp_encap
, sizeof(udp_encap
), "PLUTO_UDP_ENC='%u' ",
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
));
359 if (c
->xauth_identity
&&
360 c
->xauth_identity
->get_type(c
->xauth_identity
) != ID_ANY
)
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
);
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
));
378 for (p
= pubkeys
; p
!= NULL
; p
= p
->next
)
380 pubkey_t
*key
= p
->key
;
381 key_type_t type
= key
->public_key
->get_type(key
->public_key
);
384 if (type
== KEY_RSA
&&
385 sr
->that
.id
->equals(sr
->that
.id
, key
->id
) &&
386 trusted_ca(key
->issuer
, sr
->that
.ca
, &pathlen
))
390 snprintf(peerca_str
, BUF_LEN
, "%Y", key
->issuer
);
391 escape_metachar(peerca_str
, secure_peerca_str
, BUF_LEN
);
395 secure_peerca_str
[0] = '\0';
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 */
405 "PLUTO_CONNECTION='%s' "
406 "%s" /* optional PLUTO_NEXT_HOP */
407 "PLUTO_INTERFACE='%s' "
408 "%s" /* optional PLUTO_HOST_ACCESS */
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' "
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 */
434 , c
->interface
->vname
435 , sr
->this.hostaccess?
"PLUTO_HOST_ACCESS='1' " : ""
457 , sr
->this.updown
== NULL? DEFAULT_UPDOWN
: sr
->this.updown
))
459 loglog(RC_LOG_SERIOUS
, "%s%s command too long!", verb
, verb_suffix
);
464 DBG(DBG_CONTROL
, DBG_log("executing %s%s: %s"
465 , verb
, verb_suffix
, cmd
));
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)
474 FILE *f
= popen(cmd
, "r");
478 loglog(RC_LOG_SERIOUS
, "unable to popen %s%s command", verb
, verb_suffix
);
485 /* if response doesn't fit in this buffer, it will be folded */
488 if (fgets(resp
, sizeof(resp
), f
) == NULL
)
492 log_errno((e
, "fgets failed on output of %s%s command"
493 , verb
, verb_suffix
));
504 char *e
= resp
+ strlen(resp
);
506 if (e
> resp
&& e
[-1] == '\n')
507 e
[-1] = '\0'; /* trim trailing '\n' */
508 plog("%s%s output: %s", verb
, verb_suffix
, resp
);
512 /* report on and react to return code */
518 log_errno((e
, "pclose failed for %s%s command"
519 , verb
, verb_suffix
));
522 else if (WIFEXITED(r
))
524 if (WEXITSTATUS(r
) != 0)
526 loglog(RC_LOG_SERIOUS
, "%s%s command exited with status %d"
527 , verb
, verb_suffix
, WEXITSTATUS(r
));
531 else if (WIFSIGNALED(r
))
533 loglog(RC_LOG_SERIOUS
, "%s%s command exited with signal %d"
534 , verb
, verb_suffix
, WTERMSIG(r
));
539 loglog(RC_LOG_SERIOUS
, "%s%s command exited with unknown status %d"
540 , verb
, verb_suffix
, r
);
547 /* Check that we can route (and eroute). Diagnose if we cannot. */
550 route_impossible
= 0,
552 route_nearconflict
= 2,
553 route_farconflict
= 3
556 static enum routability
could_route(connection_t
*c
)
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? */
562 /* it makes no sense to route a connection that is ISAKMP-only */
563 if (!NEVER_NEGOTIATE(c
->policy
) && !HAS_IPSEC_POLICY(c
->policy
))
565 loglog(RC_ROUTE
, "cannot route an ISAKMP-only connection");
566 return route_impossible
;
569 /* if this is a Road Warrior template, we cannot route.
570 * Opportunistic template is OK.
572 if (c
->kind
== CK_TEMPLATE
&& !(c
->policy
& POLICY_OPPO
))
574 loglog(RC_ROUTE
, "cannot route Road Warrior template");
575 return route_impossible
;
578 /* if we don't know nexthop, we cannot route */
579 if (isanyaddr(&c
->spd
.this.host_nexthop
))
581 loglog(RC_ROUTE
, "cannot route connection without knowing our nexthop");
582 return route_impossible
;
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
))
590 loglog(RC_LOG_SERIOUS
, "cannot install route: peer is within its client");
591 return route_impossible
;
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.
600 if (ro
!= NULL
&& !routes_agree(ro
, c
))
602 loglog(RC_LOG_SERIOUS
, "cannot route -- route already in use for \"%s\""
604 return route_impossible
; /* another connection already
608 /* if there is an eroute for another connection, there is a problem */
609 if (ero
!= NULL
&& ero
!= c
)
611 connection_t
*ero2
, *ero_top
;
612 connection_t
*inside
, *outside
;
615 * note, wavesec (PERMANENT) goes *outside* and
616 * OE goes *inside* (TEMPLATE)
620 if (ero
->kind
== CK_PERMANENT
621 && c
->kind
== CK_TEMPLATE
)
626 else if (c
->kind
== CK_PERMANENT
627 && ero
->kind
== CK_TEMPLATE
)
633 /* okay, check again, with correct order */
634 if (outside
&& outside
->kind
== CK_PERMANENT
635 && inside
&& inside
->kind
== CK_TEMPLATE
)
637 char inst
[CONN_INST_BUF
];
639 /* this is a co-terminal attempt of the "near" kind. */
640 /* when chaining, we chain from inside to outside */
642 /* XXX permit multiple deep connections? */
643 passert(inside
->policy_next
== NULL
);
645 inside
->policy_next
= outside
;
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.
651 outside
->spd
.eroute_owner
= SOS_NOBODY
;
652 outside
->spd
.routing
= RT_UNROUTED_KEYED
;
654 /* set the priority of the new eroute owner to be higher
655 * than that of the current eroute owner
657 inside
->prio
= outside
->prio
+ 1;
659 fmt_conn_instance(inside
, inst
);
661 loglog(RC_LOG_SERIOUS
662 , "conflict on eroute (%s), switching eroute to %s and linking %s"
663 , inst
, inside
->name
, outside
->name
);
665 return route_nearconflict
;
668 /* look along the chain of policies for one with the same name */
671 for (ero2
= ero
; ero2
!= NULL
; ero2
= ero
->policy_next
)
673 if (ero2
->kind
== CK_TEMPLATE
674 && streq(ero2
->name
, c
->name
))
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.
684 char inst
[CONN_INST_BUF
];
686 fmt_conn_instance(ero
, inst
);
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
;
697 bool trap_connection(connection_t
*c
)
699 switch (could_route(c
))
701 case route_impossible
:
704 case route_nearconflict
:
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.
709 if (c
->spd
.routing
< RT_ROUTED_TUNNEL
)
711 return route_and_eroute(c
, &c
->spd
, NULL
);
715 case route_farconflict
:
723 * Delete any eroute for a connection and unroute it if route isn't shared
725 void unroute_connection(connection_t
*c
)
727 struct spd_route
*sr
;
730 for (sr
= &c
->spd
; sr
; sr
= sr
->next
)
736 /* cannot handle a live one */
737 passert(sr
->routing
!= RT_ROUTED_TUNNEL
);
738 shunt_eroute(c
, sr
, RT_UNROUTED
, ERO_DELETE
, "delete");
741 sr
->routing
= RT_UNROUTED
; /* do now so route_owner won't find us */
743 /* only unroute if no other connection shares it */
744 if (routed(cr
) && route_owner(c
, NULL
, NULL
, NULL
) == NULL
)
746 (void) do_command(c
, sr
, NULL
, "unroute");
752 static void set_text_said(char *text_said
, const ip_address
*dst
,
753 ipsec_spi_t spi
, int proto
)
757 initsaid(dst
, spi
, proto
, &said
);
758 satot(&said
, 0, text_said
, SATOT_BUF
);
763 * Setup an IPsec route entry.
764 * op is one of the ERO_* operators.
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
,
774 unsigned int transport_proto
,
777 const char *opname USED_BY_DEBUG
)
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 policy_priority_t priority
= POLICY_PRIORITY_DEFAULT
;
784 char text_said
[SATOT_BUF
];
786 deleting
= (op
& ERO_MASK
) == ERO_DELETE
,
787 replacing
= op
& (SADB_X_SAFLAGS_REPLACEFLOW
<< ERO_FLAG_SHIFT
);
789 set_text_said(text_said
, that_host
, spi
, proto
);
791 DBG(DBG_CONTROL
| DBG_KERNEL
,
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
];
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
);
805 if (satype
== SADB_X_SATYPE_INT
)
819 if (op
& (SADB_X_SAFLAGS_INFLOW
<< ERO_FLAG_SHIFT
))
823 priority
= POLICY_PRIORITY_ROUTED
;
828 if (op
& (SADB_X_SAFLAGS_INFLOW
<< ERO_FLAG_SHIFT
))
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
);
838 if (deleting
|| replacing
)
840 hydra
->kernel_interface
->del_policy(hydra
->kernel_interface
,
841 ts_src
, ts_dst
, dir
, sa
->reqid
, mark
, priority
);
846 ok
= hydra
->kernel_interface
->add_policy(hydra
->kernel_interface
,
847 host_src
, host_dst
, ts_src
, ts_dst
, dir
, type
, sa
,
848 mark
, priority
) == SUCCESS
;
851 if (dir
== POLICY_IN
)
852 { /* handle forward policy */
854 if (deleting
|| replacing
)
856 hydra
->kernel_interface
->del_policy(hydra
->kernel_interface
,
857 ts_src
, ts_dst
, dir
, sa
->reqid
, mark
, priority
);
860 if (!deleting
&& ok
&&
861 (sa
->mode
== MODE_TUNNEL
|| satype
== SADB_X_SATYPE_INT
))
863 ok
= hydra
->kernel_interface
->add_policy(hydra
->kernel_interface
,
864 host_src
, host_dst
, ts_src
, ts_dst
, dir
, type
, sa
,
865 mark
, priority
) == SUCCESS
;
869 host_src
->destroy(host_src
);
870 host_dst
->destroy(host_dst
);
871 ts_src
->destroy(ts_src
);
872 ts_dst
->destroy(ts_dst
);
877 static bool eroute_connection(struct spd_route
*sr
, ipsec_spi_t spi
,
878 unsigned int proto
, unsigned int satype
,
879 ipsec_sa_cfg_t
*sa
, unsigned int op
,
882 const ip_address
*peer
= &sr
->that
.host_addr
;
886 snprintf(buf2
, sizeof(buf2
)
887 , "eroute_connection %s", opname
);
891 peer
= aftoinfo(addrtypeof(peer
))->any
;
893 ok
= raw_eroute(peer
, &sr
->that
.client
,
894 &sr
->this.host_addr
, &sr
->this.client
, sr
->mark_in
,
895 spi
, proto
, satype
, sr
->this.protocol
,
896 sa
, op
| (SADB_X_SAFLAGS_INFLOW
<< ERO_FLAG_SHIFT
), buf2
);
897 return raw_eroute(&sr
->this.host_addr
, &sr
->this.client
, peer
,
898 &sr
->that
.client
, sr
->mark_out
, spi
, proto
, satype
,
899 sr
->this.protocol
, sa
, op
, buf2
) && ok
;
902 /* assign a bare hold to a connection */
904 bool assign_hold(connection_t
*c USED_BY_DEBUG
, struct spd_route
*sr
,
906 const ip_address
*src
,
907 const ip_address
*dst
)
909 /* either the automatically installed %hold eroute is broad enough
910 * or we try to add a broader one and delete the automatic one.
911 * Beware: this %hold might be already handled, but still squeak
912 * through because of a race.
914 enum routing_t ro
= sr
->routing
/* routing, old */
915 , rn
= ro
; /* routing, new */
917 passert(LHAS(LELEM(CK_PERMANENT
) | LELEM(CK_INSTANCE
), c
->kind
));
918 /* figure out what routing should become */
922 rn
= RT_UNROUTED_HOLD
;
924 case RT_ROUTED_PROSPECTIVE
:
928 /* no change: this %hold is old news and should just be deleted */
932 /* We need a broad %hold
933 * First we ensure that there is a broad %hold.
934 * There may already be one (race condition): no need to create one.
935 * There may already be a %trap: replace it.
936 * There may not be any broad eroute: add %hold.
941 ?
!eroute_connection(sr
, htonl(SPI_HOLD
), SA_INT
, SADB_X_SATYPE_INT
,
942 &null_ipsec_sa
, ERO_REPLACE
,
943 "replace %trap with broad %hold")
944 : !eroute_connection(sr
, htonl(SPI_HOLD
), SA_INT
, SADB_X_SATYPE_INT
,
945 &null_ipsec_sa
, ERO_ADD
, "add broad %hold"))
954 /* install or remove eroute for SA Group */
955 static bool sag_eroute(struct state
*st
, struct spd_route
*sr
,
956 unsigned op
, const char *opname
)
958 u_int inner_proto
, inner_satype
;
959 ipsec_spi_t inner_spi
= 0;
960 ipsec_sa_cfg_t sa
= {
961 .mode
= MODE_TRANSPORT
,
965 if (st
->st_ah
.present
)
967 inner_spi
= st
->st_ah
.attrs
.spi
;
969 inner_satype
= SADB_SATYPE_AH
;
971 sa
.ah
.spi
= inner_spi
;
972 tunnel
|= st
->st_ah
.attrs
.encapsulation
== ENCAPSULATION_MODE_TUNNEL
;
975 if (st
->st_esp
.present
)
977 inner_spi
= st
->st_esp
.attrs
.spi
;
978 inner_proto
= SA_ESP
;
979 inner_satype
= SADB_SATYPE_ESP
;
981 sa
.esp
.spi
= inner_spi
;
982 tunnel
|= st
->st_esp
.attrs
.encapsulation
== ENCAPSULATION_MODE_TUNNEL
;
985 if (st
->st_ipcomp
.present
)
987 inner_spi
= st
->st_ipcomp
.attrs
.spi
;
988 inner_proto
= SA_COMP
;
989 inner_satype
= SADB_X_SATYPE_COMP
;
990 sa
.ipcomp
.transform
= st
->st_ipcomp
.attrs
.transid
;
991 sa
.ipcomp
.cpi
= htons(ntohl(inner_spi
));
992 tunnel
|= st
->st_ipcomp
.attrs
.encapsulation
== ENCAPSULATION_MODE_TUNNEL
;
995 if (!sa
.ah
.use
&& !sa
.esp
.use
&& !sa
.ipcomp
.transform
)
997 impossible(); /* no transform at all! */
1002 inner_spi
= st
->st_tunnel_out_spi
;
1003 inner_proto
= SA_IPIP
;
1004 inner_satype
= SADB_X_SATYPE_IPIP
;
1005 sa
.mode
= MODE_TUNNEL
;
1008 sa
.reqid
= sr
->reqid
;
1010 return eroute_connection(sr
, inner_spi
, inner_proto
, inner_satype
,
1014 /* compute a (host-order!) SPI to implement the policy in connection c */
1016 shunt_policy_spi(connection_t
*c
, bool prospective
)
1018 /* note: these are in host order :-( */
1019 static const ipsec_spi_t shunt_spi
[] =
1021 SPI_TRAP
, /* --initiateontraffic */
1022 SPI_PASS
, /* --pass */
1023 SPI_DROP
, /* --drop */
1024 SPI_REJECT
, /* --reject */
1027 static const ipsec_spi_t fail_spi
[] =
1030 SPI_PASS
, /* --failpass */
1031 SPI_DROP
, /* --faildrop */
1032 SPI_REJECT
, /* --failreject */
1036 ? shunt_spi
[(c
->policy
& POLICY_SHUNT_MASK
) >> POLICY_SHUNT_SHIFT
]
1037 : fail_spi
[(c
->policy
& POLICY_FAIL_MASK
) >> POLICY_FAIL_SHIFT
];
1040 /* Add/replace/delete a shunt eroute.
1041 * Such an eroute determines the fate of packets without the use
1042 * of any SAs. These are defaults, in effect.
1043 * If a negotiation has not been attempted, use %trap.
1044 * If negotiation has failed, the choice between %trap/%pass/%drop/%reject
1045 * is specified in the policy of connection c.
1047 static bool shunt_eroute(connection_t
*c
, struct spd_route
*sr
,
1048 enum routing_t rt_kind
,
1049 unsigned int op
, const char *opname
)
1051 /* We are constructing a special SAID for the eroute.
1052 * The destination doesn't seem to matter, but the family does.
1053 * The protocol is SA_INT -- mark this as shunt.
1054 * The satype has no meaning, but is required for PF_KEY header!
1055 * The SPI signifies the kind of shunt.
1057 ipsec_spi_t spi
= shunt_policy_spi(c
, rt_kind
== RT_ROUTED_PROSPECTIVE
);
1061 /* we're supposed to end up with no eroute: rejig op and opname */
1065 /* replace with nothing == delete */
1070 /* add nothing == do nothing */
1073 /* delete remains delete */
1079 if (sr
->routing
== RT_ROUTED_ECLIPSED
&& c
->kind
== CK_TEMPLATE
)
1081 /* We think that we have an eroute, but we don't.
1082 * Adjust the request and account for eclipses.
1084 passert(eclipsable(sr
));
1090 opname
= "replace eclipsed";
1094 /* delete unnecessary: we don't actually have an eroute */
1102 else if (eclipse_count
> 0 && op
== ERO_DELETE
&& eclipsable(sr
))
1104 /* maybe we are uneclipsing something */
1105 struct spd_route
*esr
;
1106 connection_t
*ue
= eclipsed(c
, &esr
);
1110 esr
->routing
= RT_ROUTED_PROSPECTIVE
;
1111 return shunt_eroute(ue
, esr
1112 , RT_ROUTED_PROSPECTIVE
, ERO_REPLACE
, "restoring eclipsed");
1116 return eroute_connection(sr
, htonl(spi
), SA_INT
, SADB_X_SATYPE_INT
,
1117 &null_ipsec_sa
, op
, opname
);
1120 static bool setup_half_ipsec_sa(struct state
*st
, bool inbound
)
1122 host_t
*host_src
, *host_dst
;
1123 connection_t
*c
= st
->st_connection
;
1124 struct end
*src
, *dst
;
1125 ipsec_mode_t mode
= MODE_TRANSPORT
;
1126 ipsec_sa_cfg_t sa
= { .mode
= 0 };
1127 lifetime_cfg_t lt_none
= { .time
= { .rekey
= 0 } };
1130 /* SPIs, saved for undoing, if necessary */
1131 struct kernel_sa said
[EM_MAXRELSPIS
], *said_next
= said
;
1136 mark
= c
->spd
.mark_in
;
1142 mark
= c
->spd
.mark_out
;
1145 host_src
= host_create_from_sockaddr((sockaddr_t
*)&src
->host_addr
);
1146 host_dst
= host_create_from_sockaddr((sockaddr_t
*)&dst
->host_addr
);
1148 if (st
->st_ah
.attrs
.encapsulation
== ENCAPSULATION_MODE_TUNNEL
1149 || st
->st_esp
.attrs
.encapsulation
== ENCAPSULATION_MODE_TUNNEL
1150 || st
->st_ipcomp
.attrs
.encapsulation
== ENCAPSULATION_MODE_TUNNEL
)
1156 sa
.reqid
= c
->spd
.reqid
;
1158 memset(said
, 0, sizeof(said
));
1160 /* set up IPCOMP SA, if any */
1162 if (st
->st_ipcomp
.present
)
1164 ipsec_spi_t ipcomp_spi
= inbound ? st
->st_ipcomp
.our_spi
1165 : st
->st_ipcomp
.attrs
.spi
;
1167 switch (st
->st_ipcomp
.attrs
.transid
)
1169 case IPCOMP_DEFLATE
:
1173 loglog(RC_LOG_SERIOUS
, "IPCOMP transform %s not implemented",
1174 enum_name(&ipcomp_transformid_names
,
1175 st
->st_ipcomp
.attrs
.transid
));
1179 sa
.ipcomp
.cpi
= htons(ntohl(ipcomp_spi
));
1180 sa
.ipcomp
.transform
= st
->st_ipcomp
.attrs
.transid
;
1182 said_next
->spi
= ipcomp_spi
;
1183 said_next
->proto
= IPPROTO_COMP
;
1185 if (hydra
->kernel_interface
->add_sa(hydra
->kernel_interface
, host_src
,
1186 host_dst
, ipcomp_spi
, said_next
->proto
, c
->spd
.reqid
,
1187 mark
, 0, <_none
, ENCR_UNDEFINED
, chunk_empty
,
1188 AUTH_UNDEFINED
, chunk_empty
, mode
,
1189 st
->st_ipcomp
.attrs
.transid
, 0 /* cpi */, FALSE
, FALSE
,
1190 inbound
, NULL
, NULL
) != SUCCESS
)
1195 mode
= MODE_TRANSPORT
;
1198 /* set up ESP SA, if any */
1200 if (st
->st_esp
.present
)
1202 ipsec_spi_t esp_spi
= inbound ? st
->st_esp
.our_spi
1203 : st
->st_esp
.attrs
.spi
;
1204 u_char
*esp_dst_keymat
= inbound ? st
->st_esp
.our_keymat
1205 : st
->st_esp
.peer_keymat
;
1206 bool encap
= st
->nat_traversal
& NAT_T_DETECTED
;
1207 encryption_algorithm_t enc_alg
;
1208 integrity_algorithm_t auth_alg
;
1209 const struct esp_info
*ei
;
1210 chunk_t enc_key
, auth_key
;
1213 if ((ei
= kernel_alg_esp_info(st
->st_esp
.attrs
.transid
,
1214 st
->st_esp
.attrs
.auth
)) == NULL
)
1216 loglog(RC_LOG_SERIOUS
, "ESP transform %s / auth %s"
1217 " not implemented yet",
1218 enum_name(&esp_transform_names
, st
->st_esp
.attrs
.transid
),
1219 enum_name(&auth_alg_names
, st
->st_esp
.attrs
.auth
));
1223 key_len
= st
->st_esp
.attrs
.key_len
/ 8;
1226 /* XXX: must change to check valid _range_ key_len */
1227 if (key_len
> ei
->enckeylen
)
1229 loglog(RC_LOG_SERIOUS
, "ESP transform %s: key_len=%d > %d",
1230 enum_name(&esp_transform_names
, st
->st_esp
.attrs
.transid
),
1231 (int)key_len
, (int)ei
->enckeylen
);
1237 key_len
= ei
->enckeylen
;
1240 switch (ei
->transid
)
1243 /* 168 bits in kernel, need 192 bits for keymat_len */
1250 /* 56 bits in kernel, need 64 bits for keymat_len */
1257 case ESP_AES_CCM_12
:
1258 case ESP_AES_CCM_16
:
1262 case ESP_AES_GCM_12
:
1263 case ESP_AES_GCM_16
:
1274 host_src
->set_port(host_src
, src
->host_port
);
1275 host_dst
->set_port(host_dst
, dst
->host_port
);
1276 // st->nat_oa is currently unused
1279 /* divide up keying material */
1280 enc_alg
= encryption_algorithm_from_esp(st
->st_esp
.attrs
.transid
);
1281 enc_key
.ptr
= esp_dst_keymat
;
1282 enc_key
.len
= key_len
;
1283 auth_alg
= integrity_algorithm_from_esp(st
->st_esp
.attrs
.auth
);
1284 auth_alg
= auth_alg ?
: AUTH_UNDEFINED
;
1285 auth_key
.ptr
= esp_dst_keymat
+ key_len
;
1286 auth_key
.len
= ei
->authkeylen
;
1289 sa
.esp
.spi
= esp_spi
;
1291 said_next
->spi
= esp_spi
;
1292 said_next
->proto
= IPPROTO_ESP
;
1294 if (hydra
->kernel_interface
->add_sa(hydra
->kernel_interface
, host_src
,
1295 host_dst
, esp_spi
, said_next
->proto
, c
->spd
.reqid
,
1296 mark
, 0, <_none
, enc_alg
, enc_key
,
1297 auth_alg
, auth_key
, mode
, IPCOMP_NONE
, 0 /* cpi */,
1298 encap
, FALSE
, inbound
, NULL
, NULL
) != SUCCESS
)
1303 mode
= MODE_TRANSPORT
;
1306 /* set up AH SA, if any */
1308 if (st
->st_ah
.present
)
1310 ipsec_spi_t ah_spi
= inbound ? st
->st_ah
.our_spi
1311 : st
->st_ah
.attrs
.spi
;
1312 u_char
*ah_dst_keymat
= inbound ? st
->st_ah
.our_keymat
1313 : st
->st_ah
.peer_keymat
;
1314 integrity_algorithm_t auth_alg
;
1317 auth_alg
= integrity_algorithm_from_esp(st
->st_ah
.attrs
.auth
);
1318 auth_key
.ptr
= ah_dst_keymat
;
1319 auth_key
.len
= st
->st_ah
.keymat_len
;
1324 said_next
->spi
= ah_spi
;
1325 said_next
->proto
= IPPROTO_AH
;
1327 if (hydra
->kernel_interface
->add_sa(hydra
->kernel_interface
, host_src
,
1328 host_dst
, ah_spi
, said_next
->proto
, c
->spd
.reqid
,
1329 mark
, 0, <_none
, ENCR_UNDEFINED
, chunk_empty
,
1330 auth_alg
, auth_key
, mode
, IPCOMP_NONE
, 0 /* cpi */,
1331 FALSE
, FALSE
, inbound
, NULL
, NULL
) != SUCCESS
)
1336 mode
= MODE_TRANSPORT
;
1342 /* undo the done SPIs */
1343 while (said_next
-- != said
)
1345 hydra
->kernel_interface
->del_sa(hydra
->kernel_interface
, host_src
,
1346 host_dst
, said_next
->spi
,
1347 said_next
->proto
, 0 /* cpi */,
1353 host_src
->destroy(host_src
);
1354 host_dst
->destroy(host_dst
);
1358 static bool teardown_half_ipsec_sa(struct state
*st
, bool inbound
)
1360 connection_t
*c
= st
->st_connection
;
1361 const struct end
*src
, *dst
;
1362 host_t
*host_src
, *host_dst
;
1371 mark
= c
->spd
.mark_in
;
1377 mark
= c
->spd
.mark_out
;
1380 host_src
= host_create_from_sockaddr((sockaddr_t
*)&src
->host_addr
);
1381 host_dst
= host_create_from_sockaddr((sockaddr_t
*)&dst
->host_addr
);
1383 if (st
->st_ah
.present
)
1385 spi
= inbound ? st
->st_ah
.our_spi
: st
->st_ah
.attrs
.spi
;
1386 result
&= hydra
->kernel_interface
->del_sa(hydra
->kernel_interface
,
1387 host_src
, host_dst
, spi
, IPPROTO_AH
,
1388 0 /* cpi */, mark
) == SUCCESS
;
1391 if (st
->st_esp
.present
)
1393 spi
= inbound ? st
->st_esp
.our_spi
: st
->st_esp
.attrs
.spi
;
1394 result
&= hydra
->kernel_interface
->del_sa(hydra
->kernel_interface
,
1395 host_src
, host_dst
, spi
, IPPROTO_ESP
,
1396 0 /* cpi */, mark
) == SUCCESS
;
1399 if (st
->st_ipcomp
.present
)
1401 spi
= inbound ? st
->st_ipcomp
.our_spi
: st
->st_ipcomp
.attrs
.spi
;
1402 result
&= hydra
->kernel_interface
->del_sa(hydra
->kernel_interface
,
1403 host_src
, host_dst
, spi
, IPPROTO_COMP
,
1404 0 /* cpi */, mark
) == SUCCESS
;
1407 host_src
->destroy(host_src
);
1408 host_dst
->destroy(host_dst
);
1414 * get information about a given sa
1416 bool get_sa_info(struct state
*st
, bool inbound
, u_int
*bytes
, time_t *use_time
)
1418 connection_t
*c
= st
->st_connection
;
1419 traffic_selector_t
*ts_src
= NULL
, *ts_dst
= NULL
;
1420 host_t
*host_src
= NULL
, *host_dst
= NULL
;
1421 const struct end
*src
, *dst
;
1424 u_int64_t bytes_kernel
= 0;
1425 bool result
= FALSE
;
1427 *use_time
= UNDEFINED_TIME
;
1429 if (!st
->st_esp
.present
)
1438 mark
= c
->spd
.mark_in
;
1439 spi
= st
->st_esp
.our_spi
;
1445 mark
= c
->spd
.mark_out
;
1446 spi
= st
->st_esp
.attrs
.spi
;
1449 host_src
= host_create_from_sockaddr((sockaddr_t
*)&src
->host_addr
);
1450 host_dst
= host_create_from_sockaddr((sockaddr_t
*)&dst
->host_addr
);
1452 switch(hydra
->kernel_interface
->query_sa(hydra
->kernel_interface
, host_src
,
1453 host_dst
, spi
, IPPROTO_ESP
,
1454 mark
, &bytes_kernel
))
1459 *bytes
= bytes_kernel
;
1466 if (st
->st_serialno
== c
->spd
.eroute_owner
)
1468 u_int32_t time_kernel
;
1470 ts_src
= traffic_selector_from_subnet(&src
->client
, src
->protocol
);
1471 ts_dst
= traffic_selector_from_subnet(&dst
->client
, dst
->protocol
);
1473 if (hydra
->kernel_interface
->query_policy(hydra
->kernel_interface
,
1474 ts_src
, ts_dst
, inbound ? POLICY_IN
: POLICY_OUT
,
1475 mark
, &time_kernel
) != SUCCESS
)
1479 *use_time
= time_kernel
;
1482 st
->st_esp
.attrs
.encapsulation
== ENCAPSULATION_MODE_TUNNEL
)
1484 if (hydra
->kernel_interface
->query_policy(hydra
->kernel_interface
,
1485 ts_src
, ts_dst
, POLICY_FWD
, mark
,
1486 &time_kernel
) != SUCCESS
)
1490 *use_time
= max(*use_time
, time_kernel
);
1497 DESTROY_IF(host_src
);
1498 DESTROY_IF(host_dst
);
1505 * Handler for kernel events (called by thread-pool thread)
1507 kernel_listener_t
*kernel_handler
;
1510 * Data for acquire events
1515 /** Transport protocol */
1520 * Callback for acquire events (called by main thread)
1522 void handle_acquire(acquire_data_t
*this)
1524 record_and_initiate_opportunistic(&this->src
, &this->dst
, this->proto
,
1528 METHOD(kernel_listener_t
, acquire
, bool,
1529 kernel_listener_t
*this, u_int32_t reqid
,
1530 traffic_selector_t
*src_ts
, traffic_selector_t
*dst_ts
)
1532 if (src_ts
&& dst_ts
)
1534 acquire_data_t
*data
;
1536 DBG_log("creating acquire event for policy %R === %R "
1537 "with reqid {%u}", src_ts
, dst_ts
, reqid
));
1539 .src
= subnet_from_traffic_selector(src_ts
),
1540 .dst
= subnet_from_traffic_selector(dst_ts
),
1541 .proto
= src_ts
->get_protocol(src_ts
),
1543 pluto
->events
->queue(pluto
->events
, (void*)handle_acquire
, data
, free
);
1548 DBG_log("ignoring acquire without traffic selectors for policy "
1549 "with reqid {%u}", reqid
));
1557 * Data for mapping events
1560 /** reqid, spi of affected SA */
1561 u_int32_t reqid
, spi
;
1567 * Callback for mapping events (called by main thread)
1569 void handle_mapping(mapping_data_t
*this)
1571 process_nat_t_new_mapping(this->reqid
, this->spi
, &this->new_end
);
1575 METHOD(kernel_listener_t
, mapping
, bool,
1576 kernel_listener_t
*this, u_int32_t reqid
, u_int32_t spi
, host_t
*remote
)
1578 mapping_data_t
*data
;
1580 DBG_log("creating mapping event for SA with SPI %.8x and reqid {%u}",
1585 .new_end
= *(ip_address
*)remote
->get_sockaddr(remote
),
1587 pluto
->events
->queue(pluto
->events
, (void*)handle_mapping
, data
, free
);
1591 void init_kernel(void)
1593 /* register SA types that we can negotiate */
1594 can_do_IPcomp
= FALSE
; /* until we get a response from the kernel */
1597 INIT(kernel_handler
,
1598 .acquire
= _acquire
,
1599 .mapping
= _mapping
,
1601 hydra
->kernel_interface
->add_listener(hydra
->kernel_interface
,
1605 void kernel_finalize()
1607 hydra
->kernel_interface
->remove_listener(hydra
->kernel_interface
,
1609 free(kernel_handler
);
1612 /* Note: install_inbound_ipsec_sa is only used by the Responder.
1613 * The Responder will subsequently use install_ipsec_sa for the outbound.
1614 * The Initiator uses install_ipsec_sa to install both at once.
1616 bool install_inbound_ipsec_sa(struct state
*st
)
1618 connection_t
*const c
= st
->st_connection
;
1620 /* If our peer has a fixed-address client, check if we already
1621 * have a route for that client that conflicts. We will take this
1622 * as proof that that route and the connections using it are
1623 * obsolete and should be eliminated. Interestingly, this is
1624 * the only case in which we can tell that a connection is obsolete.
1626 passert(c
->kind
== CK_PERMANENT
|| c
->kind
== CK_INSTANCE
);
1627 if (c
->spd
.that
.has_client
)
1631 struct spd_route
*esr
;
1632 connection_t
*o
= route_owner(c
, &esr
, NULL
, NULL
);
1636 break; /* nobody has a route */
1639 /* note: we ignore the client addresses at this end */
1640 if (sameaddr(&o
->spd
.that
.host_addr
, &c
->spd
.that
.host_addr
) &&
1641 o
->interface
== c
->interface
)
1643 break; /* existing route is compatible */
1646 if (o
->kind
== CK_TEMPLATE
&& streq(o
->name
, c
->name
))
1648 break; /* ??? is this good enough?? */
1651 loglog(RC_LOG_SERIOUS
, "route to peer's client conflicts with \"%s\" %s; releasing old connection to free the route"
1652 , o
->name
, ip_str(&o
->spd
.that
.host_addr
));
1653 release_connection(o
, FALSE
);
1657 DBG(DBG_CONTROL
, DBG_log("install_inbound_ipsec_sa() checking if we can route"));
1658 /* check that we will be able to route and eroute */
1659 switch (could_route(c
))
1662 case route_nearconflict
:
1668 /* (attempt to) actually set up the SAs */
1669 return setup_half_ipsec_sa(st
, TRUE
);
1672 /* Install a route and then a prospective shunt eroute or an SA group eroute.
1673 * Assumption: could_route gave a go-ahead.
1674 * Any SA Group must have already been created.
1675 * On failure, steps will be unwound.
1677 bool route_and_eroute(connection_t
*c
, struct spd_route
*sr
, struct state
*st
)
1679 struct spd_route
*esr
;
1680 struct spd_route
*rosr
;
1681 connection_t
*ero
/* who, if anyone, owns our eroute? */
1682 , *ro
= route_owner(c
, &rosr
, &ero
, &esr
);
1683 bool eroute_installed
= FALSE
1684 , firewall_notified
= FALSE
1685 , route_installed
= FALSE
;
1687 connection_t
*ero_top
;
1689 DBG(DBG_CONTROLMORE
,
1690 DBG_log("route_and_eroute with c: %s (next: %s) ero:%s esr:{%p} ro:%s rosr:{%p} and state: %lu"
1692 , (c
->policy_next ? c
->policy_next
->name
: "none")
1693 , ero ? ero
->name
: "null"
1695 , ro ? ro
->name
: "null"
1697 , st ? st
->st_serialno
: 0));
1699 /* look along the chain of policies for one with the same name */
1703 /* XXX - mcr this made sense before, and likely will make sense
1704 * again, so I'l leaving this to remind me what is up */
1705 if (ero
!= NULL
&& ero
->routing
== RT_UNROUTED_KEYED
)
1708 for (ero2
= ero
; ero2
!= NULL
; ero2
= ero
->policy_next
)
1709 if ((ero2
->kind
== CK_TEMPLATE
|| ero2
->kind
==CK_SECONDARY
)
1710 && streq(ero2
->name
, c
->name
))
1714 /* install the eroute */
1718 /* We're replacing an eroute */
1720 /* if no state provided, then install a shunt for later */
1723 eroute_installed
= shunt_eroute(c
, sr
, RT_ROUTED_PROSPECTIVE
1724 , ERO_REPLACE
, "replace");
1728 eroute_installed
= sag_eroute(st
, sr
, ERO_REPLACE
, "replace");
1731 /* XXX - MCR. I previously felt that this was a bogus check */
1732 if (ero
!= NULL
&& ero
!= c
&& esr
!= sr
)
1734 /* By elimination, we must be eclipsing ero. Check. */
1735 passert(ero
->kind
== CK_TEMPLATE
&& streq(ero
->name
, c
->name
));
1736 passert(LHAS(LELEM(RT_ROUTED_PROSPECTIVE
) | LELEM(RT_ROUTED_ECLIPSED
)
1738 passert(samesubnet(&esr
->this.client
, &sr
->this.client
)
1739 && samesubnet(&esr
->that
.client
, &sr
->that
.client
));
1745 /* we're adding an eroute */
1747 /* if no state provided, then install a shunt for later */
1750 eroute_installed
= shunt_eroute(c
, sr
, RT_ROUTED_PROSPECTIVE
1755 eroute_installed
= sag_eroute(st
, sr
, ERO_ADD
, "add");
1759 /* notify the firewall of a new tunnel */
1761 if (eroute_installed
)
1763 /* do we have to notify the firewall? Yes, if we are installing
1764 * a tunnel eroute and the firewall wasn't notified
1765 * for a previous tunnel with the same clients. Any Previous
1766 * tunnel would have to be for our connection, so the actual
1769 firewall_notified
= st
== NULL
/* not a tunnel eroute */
1770 || sr
->eroute_owner
!= SOS_NOBODY
/* already notified */
1771 || do_command(c
, sr
, st
, "up"); /* go ahead and notify */
1774 /* install the route */
1777 DBG_log("route_and_eroute: firewall_notified: %s"
1778 , firewall_notified ?
"true" : "false"));
1779 if (!firewall_notified
)
1781 /* we're in trouble -- don't do routing */
1783 else if (ro
== NULL
)
1785 /* a new route: no deletion required, but preparation is */
1786 (void) do_command(c
, sr
, st
, "prepare"); /* just in case; ignore failure */
1787 route_installed
= do_command(c
, sr
, st
, "route");
1789 else if (routed(sr
->routing
) || routes_agree(ro
, c
))
1791 route_installed
= TRUE
; /* nothing to be done */
1795 /* Some other connection must own the route
1796 * and the route must disagree. But since could_route
1797 * must have allowed our stealing it, we'll do so.
1799 * A feature of LINUX allows us to install the new route
1800 * before deleting the old if the nexthops differ.
1801 * This reduces the "window of vulnerability" when packets
1802 * might flow in the clear.
1804 if (sameaddr(&sr
->this.host_nexthop
, &esr
->this.host_nexthop
))
1806 (void) do_command(ro
, sr
, st
, "unroute");
1807 route_installed
= do_command(c
, sr
, st
, "route");
1811 route_installed
= do_command(c
, sr
, st
, "route");
1812 (void) do_command(ro
, sr
, st
, "unroute");
1815 /* record unrouting */
1816 if (route_installed
)
1819 passert(!erouted(rosr
->routing
));
1820 rosr
->routing
= RT_UNROUTED
;
1822 /* no need to keep old value */
1823 ro
= route_owner(c
, &rosr
, NULL
, NULL
);
1824 } while (ro
!= NULL
);
1828 /* all done -- clean up */
1829 if (route_installed
)
1833 if (ero
!= NULL
&& ero
!= c
)
1835 /* check if ero is an ancestor of c. */
1838 for (ero2
= c
; ero2
!= NULL
&& ero2
!= c
; ero2
= ero2
->policy_next
)
1843 /* By elimination, we must be eclipsing ero. Checked above. */
1844 if (ero
->spd
.routing
!= RT_ROUTED_ECLIPSED
)
1846 ero
->spd
.routing
= RT_ROUTED_ECLIPSED
;
1854 passert(sr
->eroute_owner
== SOS_NOBODY
);
1855 sr
->routing
= RT_ROUTED_PROSPECTIVE
;
1859 char cib
[CONN_INST_BUF
];
1860 sr
->routing
= RT_ROUTED_TUNNEL
;
1863 DBG_log("route_and_eroute: instance \"%s\"%s, setting eroute_owner {spd=%p,sr=%p} to #%ld (was #%ld) (newest_ipsec_sa=#%ld)"
1864 , st
->st_connection
->name
1865 , (fmt_conn_instance(st
->st_connection
, cib
), cib
)
1866 , &st
->st_connection
->spd
, sr
1869 , st
->st_connection
->newest_ipsec_sa
));
1870 sr
->eroute_owner
= st
->st_serialno
;
1877 /* Failure! Unwind our work. */
1878 if (firewall_notified
&& sr
->eroute_owner
== SOS_NOBODY
)
1879 (void) do_command(c
, sr
, st
, "down");
1881 if (eroute_installed
)
1883 /* Restore original eroute, if we can.
1884 * Since there is nothing much to be done if the restoration
1885 * fails, ignore success or failure.
1889 /* restore ero's former glory */
1890 if (esr
->eroute_owner
== SOS_NOBODY
)
1892 /* note: normal or eclipse case */
1893 (void) shunt_eroute(ero
, esr
1894 , esr
->routing
, ERO_REPLACE
, "restore");
1898 /* Try to find state that owned eroute.
1899 * Don't do anything if it cannot be found.
1900 * This case isn't likely since we don't run
1901 * the updown script when replacing a SA group
1902 * with its successor (for the same conn).
1904 struct state
*ost
= state_with_serialno(esr
->eroute_owner
);
1907 (void) sag_eroute(ost
, esr
, ERO_REPLACE
, "restore");
1912 /* there was no previous eroute: delete whatever we installed */
1915 (void) shunt_eroute(c
, sr
, sr
->routing
, ERO_DELETE
, "delete");
1919 (void) sag_eroute(st
, sr
, ERO_DELETE
, "delete");
1928 bool install_ipsec_sa(struct state
*st
, bool inbound_also
)
1930 struct spd_route
*sr
;
1932 DBG(DBG_CONTROL
, DBG_log("install_ipsec_sa() for #%ld: %s"
1935 "inbound and outbound" : "outbound only"));
1937 switch (could_route(st
->st_connection
))
1940 case route_nearconflict
:
1946 /* (attempt to) actually set up the SA group */
1947 if ((inbound_also
&& !setup_half_ipsec_sa(st
, TRUE
)) ||
1948 !setup_half_ipsec_sa(st
, FALSE
))
1953 for (sr
= &st
->st_connection
->spd
; sr
!= NULL
; sr
= sr
->next
)
1955 DBG(DBG_CONTROL
, DBG_log("sr for #%ld: %s"
1957 , enum_name(&routing_story
, sr
->routing
)));
1960 * if the eroute owner is not us, then make it us.
1961 * See test co-terminal-02, pluto-rekey-01, pluto-unit-02/oppo-twice
1963 pexpect(sr
->eroute_owner
== SOS_NOBODY
1964 || sr
->routing
>= RT_ROUTED_TUNNEL
);
1966 if (sr
->eroute_owner
!= st
->st_serialno
1967 && sr
->routing
!= RT_UNROUTED_KEYED
)
1969 if (!route_and_eroute(st
->st_connection
, sr
, st
))
1971 delete_ipsec_sa(st
, FALSE
);
1972 /* XXX go and unroute any SRs that were successfully
1983 /* delete an IPSEC SA.
1984 * we may not succeed, but we bull ahead anyway because
1985 * we cannot do anything better by recognizing failure
1987 void delete_ipsec_sa(struct state
*st
, bool inbound_only
)
1991 /* If the state is the eroute owner, we must adjust
1992 * the routing for the connection.
1994 connection_t
*c
= st
->st_connection
;
1995 struct spd_route
*sr
;
1997 passert(st
->st_connection
);
1999 for (sr
= &c
->spd
; sr
; sr
= sr
->next
)
2001 if (sr
->eroute_owner
== st
->st_serialno
2002 && sr
->routing
== RT_ROUTED_TUNNEL
)
2004 sr
->eroute_owner
= SOS_NOBODY
;
2006 /* Routing should become RT_ROUTED_FAILURE,
2007 * but if POLICY_FAIL_NONE, then we just go
2008 * right back to RT_ROUTED_PROSPECTIVE as if no
2011 sr
->routing
= (c
->policy
& POLICY_FAIL_MASK
) == POLICY_FAIL_NONE
2012 ? RT_ROUTED_PROSPECTIVE
: RT_ROUTED_FAILURE
;
2014 (void) do_command(c
, sr
, st
, "down");
2015 if ((c
->policy
& POLICY_DONT_REKEY
) && c
->kind
== CK_INSTANCE
)
2017 /* in this special case, even if the connection
2018 * is still alive (due to an ISAKMP SA),
2019 * we get rid of routing.
2020 * Even though there is still an eroute, the c->routing
2021 * setting will convince unroute_connection to delete it.
2022 * unroute_connection would be upset if c->routing == RT_ROUTED_TUNNEL
2024 unroute_connection(c
);
2028 (void) shunt_eroute(c
, sr
, sr
->routing
, ERO_REPLACE
, "replace with shunt");
2032 (void) teardown_half_ipsec_sa(st
, FALSE
);
2034 (void) teardown_half_ipsec_sa(st
, TRUE
);
2037 static bool update_nat_t_ipsec_esp_sa (struct state
*st
, bool inbound
)
2039 connection_t
*c
= st
->st_connection
;
2040 host_t
*host_src
, *host_dst
, *new_src
, *new_dst
;
2041 ipsec_spi_t spi
= inbound ? st
->st_esp
.our_spi
: st
->st_esp
.attrs
.spi
;
2042 struct end
*src
= inbound ?
&c
->spd
.that
: &c
->spd
.this,
2043 *dst
= inbound ?
&c
->spd
.this : &c
->spd
.that
;
2044 mark_t mark
= inbound ? c
->spd
.mark_in
: c
->spd
.mark_out
;
2047 host_src
= host_create_from_sockaddr((sockaddr_t
*)&src
->host_addr
);
2048 host_dst
= host_create_from_sockaddr((sockaddr_t
*)&dst
->host_addr
);
2050 new_src
= host_src
->clone(host_src
);
2051 new_dst
= host_dst
->clone(host_dst
);
2052 new_src
->set_port(new_src
, src
->host_port
);
2053 new_dst
->set_port(new_dst
, dst
->host_port
);
2055 result
= hydra
->kernel_interface
->update_sa(hydra
->kernel_interface
,
2056 spi
, IPPROTO_ESP
, 0 /* cpi */, host_src
, host_dst
,
2057 new_src
, new_dst
, TRUE
/* encap */, TRUE
/* new_encap */,
2060 host_src
->destroy(host_src
);
2061 host_dst
->destroy(host_dst
);
2062 new_src
->destroy(new_src
);
2063 new_dst
->destroy(new_dst
);
2068 bool update_ipsec_sa (struct state
*st
)
2070 if (IS_IPSEC_SA_ESTABLISHED(st
->st_state
))
2072 if (st
->st_esp
.present
&& (
2073 (!update_nat_t_ipsec_esp_sa (st
, TRUE
)) ||
2074 (!update_nat_t_ipsec_esp_sa (st
, FALSE
))))
2079 else if (IS_ONLY_INBOUND_IPSEC_SA_ESTABLISHED(st
->st_state
))
2081 if (st
->st_esp
.present
&& !update_nat_t_ipsec_esp_sa (st
, FALSE
))
2088 DBG_log("assert failed at %s:%d st_state=%d", __FILE__
, __LINE__
, st
->st_state
);
2094 /* Check if there was traffic on given SA during the last idle_max
2095 * seconds. If TRUE, the SA was idle and DPD exchange should be performed.
2096 * If FALSE, DPD is not necessary. We also return TRUE for errors, as they
2097 * could mean that the SA is broken and needs to be replace anyway.
2099 bool was_eroute_idle(struct state
*st
, time_t idle_max
, time_t *idle_time
)
2105 passert(st
!= NULL
);
2107 if (get_sa_info(st
, TRUE
, &bytes
, &use_time
) && use_time
!= UNDEFINED_TIME
)
2109 *idle_time
= time_monotonic(NULL
) - use_time
;
2110 ret
= *idle_time
>= idle_max
;