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