updated copyright statement
[strongswan.git] / src / pluto / kernel.c
1 /* routines that interface with the kernel's IPsec mechanism
2 * Copyright (C) 1997 Angelos D. Keromytis.
3 * Copyright (C) 1998-2002 D. Hugh Redelmeier.
4 * Copyright (C) 2009 Andreas Steffen - Hochschule fuer Technik Rapperswil
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; either version 2 of the License, or (at your
9 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * for more details.
15 */
16
17 #include <stddef.h>
18 #include <string.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <errno.h>
22 #include <wait.h>
23 #include <unistd.h>
24 #include <fcntl.h>
25 #include <sys/queue.h>
26
27 #include <sys/stat.h>
28 #include <sys/socket.h>
29 #include <netinet/in.h>
30 #include <arpa/inet.h>
31
32 #include <freeswan.h>
33
34 #include <library.h>
35 #include <crypto/rngs/rng.h>
36
37 #ifdef KLIPS
38 #include <signal.h>
39 #include <sys/time.h> /* for select(2) */
40 #include <sys/types.h> /* for select(2) */
41 #include <pfkeyv2.h>
42 #include <pfkey.h>
43 #include "kameipsec.h"
44 #endif /* KLIPS */
45
46 #include "constants.h"
47 #include "defs.h"
48 #include "id.h"
49 #include "connections.h"
50 #include "state.h"
51 #include "timer.h"
52 #include "kernel.h"
53 #include "kernel_netlink.h"
54 #include "kernel_pfkey.h"
55 #include "kernel_noklips.h"
56 #include "log.h"
57 #include "ca.h"
58 #include "server.h"
59 #include "whack.h" /* for RC_LOG_SERIOUS */
60 #include "keys.h"
61 #include "nat_traversal.h"
62 #include "alg_info.h"
63 #include "kernel_alg.h"
64
65
66 bool can_do_IPcomp = TRUE; /* can system actually perform IPCOMP? */
67
68 /* How far can IPsec messages arrive out of order before the anti-replay
69 * logic loses track and swats them? 64 is the best KLIPS can do.
70 * And 32 is the best XFRM can do...
71 */
72 #define REPLAY_WINDOW 64
73 #define REPLAY_WINDOW_XFRM 32
74
75 /* test if the routes required for two different connections agree
76 * It is assumed that the destination subnets agree; we are only
77 * testing that the interfaces and nexthops match.
78 */
79 #define routes_agree(c, d) ((c)->interface == (d)->interface \
80 && sameaddr(&(c)->spd.this.host_nexthop, &(d)->spd.this.host_nexthop))
81
82 #ifndef KLIPS
83
84 bool no_klips = TRUE; /* don't actually use KLIPS */
85
86 #else /* !KLIPS */
87
88 /* bare (connectionless) shunt (eroute) table
89 *
90 * Bare shunts are those that don't "belong" to a connection.
91 * This happens because some %trapped traffic hasn't yet or cannot be
92 * assigned to a connection. The usual reason is that we cannot discover
93 * the peer SG. Another is that even when the peer has been discovered,
94 * it may be that no connection matches all the particulars.
95 * We record them so that, with scanning, we can discover
96 * which %holds are news and which others should expire.
97 */
98
99 #define SHUNT_SCAN_INTERVAL (60 * 2) /* time between scans of eroutes */
100
101 /* SHUNT_PATIENCE only has resolution down to a multiple of the sample rate,
102 * SHUNT_SCAN_INTERVAL.
103 * By making SHUNT_PATIENCE an odd multiple of half of SHUNT_SCAN_INTERVAL,
104 * we minimize the effects of jitter.
105 */
106 #define SHUNT_PATIENCE (SHUNT_SCAN_INTERVAL * 15 / 2) /* inactivity timeout */
107
108 struct bare_shunt {
109 policy_prio_t policy_prio;
110 ip_subnet ours;
111 ip_subnet his;
112 ip_said said;
113 int transport_proto;
114 unsigned long count;
115 time_t last_activity;
116 char *why;
117 struct bare_shunt *next;
118 };
119
120 static struct bare_shunt *bare_shunts = NULL;
121
122 #ifdef DEBUG
123 static void DBG_bare_shunt(const char *op, const struct bare_shunt *bs)
124 {
125 DBG(DBG_KLIPS,
126 {
127 int ourport = ntohs(portof(&(bs)->ours.addr));
128 int hisport = ntohs(portof(&(bs)->his.addr));
129 char ourst[SUBNETTOT_BUF];
130 char hist[SUBNETTOT_BUF];
131 char sat[SATOT_BUF];
132 char prio[POLICY_PRIO_BUF];
133
134 subnettot(&(bs)->ours, 0, ourst, sizeof(ourst));
135 subnettot(&(bs)->his, 0, hist, sizeof(hist));
136 satot(&(bs)->said, 0, sat, sizeof(sat));
137 fmt_policy_prio(bs->policy_prio, prio);
138 DBG_log("%s bare shunt %p %s:%d -> %s:%d => %s:%d %s %s"
139 , op, (const void *)(bs), ourst, ourport, hist, hisport
140 , sat, (bs)->transport_proto, prio, (bs)->why);
141 });
142 }
143 #else /* !DEBUG */
144 #define DBG_bare_shunt(op, bs) {}
145 #endif /* !DEBUG */
146
147 /* The orphaned_holds table records %holds for which we
148 * scan_proc_shunts found no representation of in any connection.
149 * The corresponding ACQUIRE message might have been lost.
150 */
151 struct eroute_info *orphaned_holds = NULL;
152
153 /* forward declaration */
154 static bool shunt_eroute(struct connection *c, struct spd_route *sr,
155 enum routing_t rt_kind, unsigned int op,
156 const char *opname);
157
158 static void set_text_said(char *text_said, const ip_address *dst,
159 ipsec_spi_t spi, int proto);
160
161 bool no_klips = FALSE; /* don't actually use KLIPS */
162
163 static const struct pfkey_proto_info null_proto_info[2] = {
164 {
165 proto: IPPROTO_ESP,
166 encapsulation: ENCAPSULATION_MODE_TRANSPORT,
167 reqid: 0
168 },
169 {
170 proto: 0,
171 encapsulation: 0,
172 reqid: 0
173 }
174 };
175
176 void record_and_initiate_opportunistic(const ip_subnet *ours,
177 const ip_subnet *his,
178 int transport_proto, const char *why)
179 {
180 passert(samesubnettype(ours, his));
181
182 /* Add to bare shunt list.
183 * We need to do this because the shunt was installed by KLIPS
184 * which can't do this itself.
185 */
186 {
187 struct bare_shunt *bs = malloc_thing(struct bare_shunt);
188
189 bs->why = clone_str(why);
190 bs->ours = *ours;
191 bs->his = *his;
192 bs->transport_proto = transport_proto;
193 bs->policy_prio = BOTTOM_PRIO;
194
195 bs->said.proto = SA_INT;
196 bs->said.spi = htonl(SPI_HOLD);
197 bs->said.dst = *aftoinfo(subnettypeof(ours))->any;
198
199 bs->count = 0;
200 bs->last_activity = now();
201
202 bs->next = bare_shunts;
203 bare_shunts = bs;
204 DBG_bare_shunt("add", bs);
205 }
206
207 /* actually initiate opportunism */
208 {
209 ip_address src, dst;
210
211 networkof(ours, &src);
212 networkof(his, &dst);
213 initiate_opportunistic(&src, &dst, transport_proto, TRUE, NULL_FD);
214 }
215
216 /* if present, remove from orphaned_holds list.
217 * NOTE: we do this last in case ours or his is a pointer into a member.
218 */
219 {
220 struct eroute_info **pp, *p;
221
222 for (pp = &orphaned_holds; (p = *pp) != NULL; pp = &p->next)
223 {
224 if (samesubnet(ours, &p->ours)
225 && samesubnet(his, &p->his)
226 && transport_proto == p->transport_proto
227 && portof(&ours->addr) == portof(&p->ours.addr)
228 && portof(&his->addr) == portof(&p->his.addr))
229 {
230 *pp = p->next;
231 free(p);
232 break;
233 }
234 }
235 }
236 }
237
238 #endif /* KLIPS */
239
240 static unsigned get_proto_reqid(unsigned base, int proto)
241 {
242 switch (proto)
243 {
244 default:
245 case IPPROTO_COMP:
246 base++;
247 /* fall through */
248 case IPPROTO_ESP:
249 base++;
250 /* fall through */
251 case IPPROTO_AH:
252 break;
253 }
254
255 return base;
256 }
257
258 /* Generate Unique SPI numbers.
259 *
260 * The specs say that the number must not be less than IPSEC_DOI_SPI_MIN.
261 * Pluto generates numbers not less than IPSEC_DOI_SPI_OUR_MIN,
262 * reserving numbers in between for manual keying (but we cannot so
263 * restrict numbers generated by our peer).
264 * XXX This should be replaced by a call to the kernel when
265 * XXX we get an API.
266 * The returned SPI is in network byte order.
267 * We use a random number as the initial SPI so that there is
268 * a good chance that different Pluto instances will choose
269 * different SPIs. This is good for two reasons.
270 * - the keying material for the initiator and responder only
271 * differs if the SPIs differ.
272 * - if Pluto is restarted, it would otherwise recycle the SPI
273 * numbers and confuse everything. When the kernel generates
274 * SPIs, this will no longer matter.
275 * We then allocate numbers sequentially. Thus we don't have to
276 * check if the number was previously used (assuming that no
277 * SPI lives longer than 4G of its successors).
278 */
279 ipsec_spi_t get_ipsec_spi(ipsec_spi_t avoid, int proto, struct spd_route *sr,
280 bool tunnel)
281 {
282 static ipsec_spi_t spi = 0; /* host order, so not returned directly! */
283 char text_said[SATOT_BUF];
284 rng_t *rng;
285
286 set_text_said(text_said, &sr->this.host_addr, 0, proto);
287
288 if (kernel_ops->get_spi)
289 {
290 return kernel_ops->get_spi(&sr->that.host_addr
291 , &sr->this.host_addr, proto, tunnel
292 , get_proto_reqid(sr->reqid, proto)
293 , IPSEC_DOI_SPI_OUR_MIN, 0xffffffff
294 , text_said);
295 }
296
297 spi++;
298 rng = lib->crypto->create_rng(lib->crypto, RNG_WEAK);
299 while (spi < IPSEC_DOI_SPI_OUR_MIN || spi == ntohl(avoid))
300 {
301 rng->get_bytes(rng, sizeof(spi), (u_char *)&spi);
302 }
303 rng->destroy(rng);
304 DBG(DBG_CONTROL,
305 {
306 ipsec_spi_t spi_net = htonl(spi);
307
308 DBG_dump("generate SPI:", (u_char *)&spi_net, sizeof(spi_net));
309 });
310
311 return htonl(spi);
312 }
313
314 /* Generate Unique CPI numbers.
315 * The result is returned as an SPI (4 bytes) in network order!
316 * The real bits are in the nework-low-order 2 bytes.
317 * Modelled on get_ipsec_spi, but range is more limited:
318 * 256-61439.
319 * If we can't find one easily, return 0 (a bad SPI,
320 * no matter what order) indicating failure.
321 */
322 ipsec_spi_t get_my_cpi(struct spd_route *sr, bool tunnel)
323 {
324 static cpi_t first_busy_cpi = 0, latest_cpi;
325 char text_said[SATOT_BUF];
326 rng_t *rng;
327
328 set_text_said(text_said, &sr->this.host_addr, 0, IPPROTO_COMP);
329
330 if (kernel_ops->get_spi)
331 {
332 return kernel_ops->get_spi(&sr->that.host_addr
333 , &sr->this.host_addr, IPPROTO_COMP, tunnel
334 , get_proto_reqid(sr->reqid, IPPROTO_COMP)
335 , IPCOMP_FIRST_NEGOTIATED, IPCOMP_LAST_NEGOTIATED
336 , text_said);
337 }
338
339 rng = lib->crypto->create_rng(lib->crypto, RNG_WEAK);
340 while (!(IPCOMP_FIRST_NEGOTIATED <= first_busy_cpi && first_busy_cpi < IPCOMP_LAST_NEGOTIATED))
341 {
342 rng->get_bytes(rng, sizeof(first_busy_cpi), (u_char *)&first_busy_cpi);
343 latest_cpi = first_busy_cpi;
344 }
345 rng->destroy(rng);
346
347 latest_cpi++;
348
349 if (latest_cpi == first_busy_cpi)
350 find_my_cpi_gap(&latest_cpi, &first_busy_cpi);
351
352 if (latest_cpi > IPCOMP_LAST_NEGOTIATED)
353 latest_cpi = IPCOMP_FIRST_NEGOTIATED;
354
355 return htonl((ipsec_spi_t)latest_cpi);
356 }
357
358 /* invoke the updown script to do the routing and firewall commands required
359 *
360 * The user-specified updown script is run. Parameters are fed to it in
361 * the form of environment variables. All such environment variables
362 * have names starting with "PLUTO_".
363 *
364 * The operation to be performed is specified by PLUTO_VERB. This
365 * verb has a suffix "-host" if the client on this end is just the
366 * host; otherwise the suffix is "-client". If the address family
367 * of the host is IPv6, an extra suffix of "-v6" is added.
368 *
369 * "prepare-host" and "prepare-client" are used to delete a route
370 * that may exist (due to forces outside of Pluto). It is used to
371 * prepare for pluto creating a route.
372 *
373 * "route-host" and "route-client" are used to install a route.
374 * Since routing is based only on destination, the PLUTO_MY_CLIENT_*
375 * values are probably of no use (using them may signify a bug).
376 *
377 * "unroute-host" and "unroute-client" are used to delete a route.
378 * Since routing is based only on destination, the PLUTO_MY_CLIENT_*
379 * values are probably of no use (using them may signify a bug).
380 *
381 * "up-host" and "up-client" are run when an eroute is added (not replaced).
382 * They are useful for adjusting a firewall: usually for adding a rule
383 * to let processed packets flow between clients. Note that only
384 * one eroute may exist for a pair of client subnets but inbound
385 * IPsec SAs may persist without an eroute.
386 *
387 * "down-host" and "down-client" are run when an eroute is deleted.
388 * They are useful for adjusting a firewall.
389 */
390
391 #ifndef DEFAULT_UPDOWN
392 # define DEFAULT_UPDOWN "ipsec _updown"
393 #endif
394
395 static bool do_command(struct connection *c, struct spd_route *sr,
396 const char *verb)
397 {
398 char cmd[1536]; /* arbitrary limit on shell command length */
399 const char *verb_suffix;
400
401 /* figure out which verb suffix applies */
402 {
403 const char *hs, *cs;
404
405 switch (addrtypeof(&sr->this.host_addr))
406 {
407 case AF_INET:
408 hs = "-host";
409 cs = "-client";
410 break;
411 case AF_INET6:
412 hs = "-host-v6";
413 cs = "-client-v6";
414 break;
415 default:
416 loglog(RC_LOG_SERIOUS, "unknown address family");
417 return FALSE;
418 }
419 verb_suffix = subnetisaddr(&sr->this.client, &sr->this.host_addr)
420 ? hs : cs;
421 }
422
423 /* form the command string */
424 {
425 char
426 nexthop_str[sizeof("PLUTO_NEXT_HOP='' ") +ADDRTOT_BUF] = "",
427 srcip_str[sizeof("PLUTO_MY_SOURCEIP='' ")+ADDRTOT_BUF] = "",
428 me_str[ADDRTOT_BUF],
429 myid_str[BUF_LEN],
430 myclient_str[SUBNETTOT_BUF],
431 myclientnet_str[ADDRTOT_BUF],
432 myclientmask_str[ADDRTOT_BUF],
433 peer_str[ADDRTOT_BUF],
434 peerid_str[BUF_LEN],
435 peerclient_str[SUBNETTOT_BUF],
436 peerclientnet_str[ADDRTOT_BUF],
437 peerclientmask_str[ADDRTOT_BUF],
438 peerca_str[BUF_LEN],
439 secure_myid_str[BUF_LEN] = "",
440 secure_peerid_str[BUF_LEN] = "",
441 secure_peerca_str[BUF_LEN] = "";
442 ip_address ta;
443 pubkey_list_t *p;
444
445 if (addrbytesptr(&sr->this.host_nexthop, NULL)
446 && !isanyaddr(&sr->this.host_nexthop))
447 {
448 char *n;
449
450 strcpy(nexthop_str, "PLUTO_NEXT_HOP='");
451 n = nexthop_str + strlen(nexthop_str);
452
453 addrtot(&sr->this.host_nexthop, 0
454 ,n , sizeof(nexthop_str)-strlen(nexthop_str));
455 strncat(nexthop_str, "' ", sizeof(nexthop_str));
456 }
457
458 if (addrbytesptr(&sr->this.host_srcip, NULL)
459 && !isanyaddr(&sr->this.host_srcip))
460 {
461 char *n;
462
463 strcpy(srcip_str, "PLUTO_MY_SOURCEIP='");
464 n = srcip_str + strlen(srcip_str);
465
466 addrtot(&sr->this.host_srcip, 0
467 ,n , sizeof(srcip_str)-strlen(srcip_str));
468 strncat(srcip_str, "' ", sizeof(srcip_str));
469 }
470
471 addrtot(&sr->this.host_addr, 0, me_str, sizeof(me_str));
472 idtoa(&sr->this.id, myid_str, sizeof(myid_str));
473 escape_metachar(myid_str, secure_myid_str, sizeof(secure_myid_str));
474 subnettot(&sr->this.client, 0, myclient_str, sizeof(myclientnet_str));
475 networkof(&sr->this.client, &ta);
476 addrtot(&ta, 0, myclientnet_str, sizeof(myclientnet_str));
477 maskof(&sr->this.client, &ta);
478 addrtot(&ta, 0, myclientmask_str, sizeof(myclientmask_str));
479
480 addrtot(&sr->that.host_addr, 0, peer_str, sizeof(peer_str));
481 idtoa(&sr->that.id, peerid_str, sizeof(peerid_str));
482 escape_metachar(peerid_str, secure_peerid_str, sizeof(secure_peerid_str));
483 subnettot(&sr->that.client, 0, peerclient_str, sizeof(peerclientnet_str));
484 networkof(&sr->that.client, &ta);
485 addrtot(&ta, 0, peerclientnet_str, sizeof(peerclientnet_str));
486 maskof(&sr->that.client, &ta);
487 addrtot(&ta, 0, peerclientmask_str, sizeof(peerclientmask_str));
488
489 for (p = pubkeys; p != NULL; p = p->next)
490 {
491 pubkey_t *key = p->key;
492 key_type_t type = key->public_key->get_type(key->public_key);
493 int pathlen;
494
495 if (type == KEY_RSA && same_id(&sr->that.id, &key->id) &&
496 trusted_ca(key->issuer, sr->that.ca, &pathlen))
497 {
498 dntoa_or_null(peerca_str, BUF_LEN, key->issuer, "");
499 escape_metachar(peerca_str, secure_peerca_str, sizeof(secure_peerca_str));
500 break;
501 }
502 }
503
504 if (-1 == snprintf(cmd, sizeof(cmd)
505 , "2>&1 " /* capture stderr along with stdout */
506 "PLUTO_VERSION='1.1' " /* change VERSION when interface spec changes */
507 "PLUTO_VERB='%s%s' "
508 "PLUTO_CONNECTION='%s' "
509 "%s" /* optional PLUTO_NEXT_HOP */
510 "PLUTO_INTERFACE='%s' "
511 "%s" /* optional PLUTO_HOST_ACCESS */
512 "PLUTO_REQID='%u' "
513 "PLUTO_ME='%s' "
514 "PLUTO_MY_ID='%s' "
515 "PLUTO_MY_CLIENT='%s' "
516 "PLUTO_MY_CLIENT_NET='%s' "
517 "PLUTO_MY_CLIENT_MASK='%s' "
518 "PLUTO_MY_PORT='%u' "
519 "PLUTO_MY_PROTOCOL='%u' "
520 "PLUTO_PEER='%s' "
521 "PLUTO_PEER_ID='%s' "
522 "PLUTO_PEER_CLIENT='%s' "
523 "PLUTO_PEER_CLIENT_NET='%s' "
524 "PLUTO_PEER_CLIENT_MASK='%s' "
525 "PLUTO_PEER_PORT='%u' "
526 "PLUTO_PEER_PROTOCOL='%u' "
527 "PLUTO_PEER_CA='%s' "
528 "%s" /* optional PLUTO_MY_SRCIP */
529 "%s" /* actual script */
530 , verb, verb_suffix
531 , c->name
532 , nexthop_str
533 , c->interface->vname
534 , sr->this.hostaccess? "PLUTO_HOST_ACCESS='1' " : ""
535 , sr->reqid + 1 /* ESP requid */
536 , me_str
537 , secure_myid_str
538 , myclient_str
539 , myclientnet_str
540 , myclientmask_str
541 , sr->this.port
542 , sr->this.protocol
543 , peer_str
544 , secure_peerid_str
545 , peerclient_str
546 , peerclientnet_str
547 , peerclientmask_str
548 , sr->that.port
549 , sr->that.protocol
550 , secure_peerca_str
551 , srcip_str
552 , sr->this.updown == NULL? DEFAULT_UPDOWN : sr->this.updown))
553 {
554 loglog(RC_LOG_SERIOUS, "%s%s command too long!", verb, verb_suffix);
555 return FALSE;
556 }
557 }
558
559 DBG(DBG_CONTROL, DBG_log("executing %s%s: %s"
560 , verb, verb_suffix, cmd));
561
562 #ifdef KLIPS
563 if (!no_klips)
564 {
565 /* invoke the script, catching stderr and stdout
566 * It may be of concern that some file descriptors will
567 * be inherited. For the ones under our control, we
568 * have done fcntl(fd, F_SETFD, FD_CLOEXEC) to prevent this.
569 * Any used by library routines (perhaps the resolver or syslog)
570 * will remain.
571 */
572 FILE *f = popen(cmd, "r");
573
574 if (f == NULL)
575 {
576 loglog(RC_LOG_SERIOUS, "unable to popen %s%s command", verb, verb_suffix);
577 return FALSE;
578 }
579
580 /* log any output */
581 for (;;)
582 {
583 /* if response doesn't fit in this buffer, it will be folded */
584 char resp[256];
585
586 if (fgets(resp, sizeof(resp), f) == NULL)
587 {
588 if (ferror(f))
589 {
590 log_errno((e, "fgets failed on output of %s%s command"
591 , verb, verb_suffix));
592 return FALSE;
593 }
594 else
595 {
596 passert(feof(f));
597 break;
598 }
599 }
600 else
601 {
602 char *e = resp + strlen(resp);
603
604 if (e > resp && e[-1] == '\n')
605 e[-1] = '\0'; /* trim trailing '\n' */
606 plog("%s%s output: %s", verb, verb_suffix, resp);
607 }
608 }
609
610 /* report on and react to return code */
611 {
612 int r = pclose(f);
613
614 if (r == -1)
615 {
616 log_errno((e, "pclose failed for %s%s command"
617 , verb, verb_suffix));
618 return FALSE;
619 }
620 else if (WIFEXITED(r))
621 {
622 if (WEXITSTATUS(r) != 0)
623 {
624 loglog(RC_LOG_SERIOUS, "%s%s command exited with status %d"
625 , verb, verb_suffix, WEXITSTATUS(r));
626 return FALSE;
627 }
628 }
629 else if (WIFSIGNALED(r))
630 {
631 loglog(RC_LOG_SERIOUS, "%s%s command exited with signal %d"
632 , verb, verb_suffix, WTERMSIG(r));
633 return FALSE;
634 }
635 else
636 {
637 loglog(RC_LOG_SERIOUS, "%s%s command exited with unknown status %d"
638 , verb, verb_suffix, r);
639 return FALSE;
640 }
641 }
642 }
643 #endif /* KLIPS */
644 return TRUE;
645 }
646
647 /* Check that we can route (and eroute). Diagnose if we cannot. */
648
649 enum routability {
650 route_impossible = 0,
651 route_easy = 1,
652 route_nearconflict = 2,
653 route_farconflict = 3
654 };
655
656 static enum routability could_route(struct connection *c)
657 {
658 struct spd_route *esr, *rosr;
659 struct connection *ero /* who, if anyone, owns our eroute? */
660 , *ro = route_owner(c, &rosr, &ero, &esr); /* who owns our route? */
661
662 /* it makes no sense to route a connection that is ISAKMP-only */
663 if (!NEVER_NEGOTIATE(c->policy) && !HAS_IPSEC_POLICY(c->policy))
664 {
665 loglog(RC_ROUTE, "cannot route an ISAKMP-only connection");
666 return route_impossible;
667 }
668
669 /* if this is a Road Warrior template, we cannot route.
670 * Opportunistic template is OK.
671 */
672 if (c->kind == CK_TEMPLATE && !(c->policy & POLICY_OPPO))
673 {
674 loglog(RC_ROUTE, "cannot route Road Warrior template");
675 return route_impossible;
676 }
677
678 /* if we don't know nexthop, we cannot route */
679 if (isanyaddr(&c->spd.this.host_nexthop))
680 {
681 loglog(RC_ROUTE, "cannot route connection without knowing our nexthop");
682 return route_impossible;
683 }
684
685 /* if routing would affect IKE messages, reject */
686 if (!no_klips
687 && c->spd.this.host_port != NAT_T_IKE_FLOAT_PORT
688 && c->spd.this.host_port != IKE_UDP_PORT
689 && addrinsubnet(&c->spd.that.host_addr, &c->spd.that.client))
690 {
691 loglog(RC_LOG_SERIOUS, "cannot install route: peer is within its client");
692 return route_impossible;
693 }
694
695 /* If there is already a route for peer's client subnet
696 * and it disagrees about interface or nexthop, we cannot steal it.
697 * Note: if this connection is already routed (perhaps for another
698 * state object), the route will agree.
699 * This is as it should be -- it will arise during rekeying.
700 */
701 if (ro != NULL && !routes_agree(ro, c))
702 {
703 loglog(RC_LOG_SERIOUS, "cannot route -- route already in use for \"%s\""
704 , ro->name);
705 return route_impossible; /* another connection already
706 using the eroute */
707 }
708
709 #ifdef KLIPS
710 /* if there is an eroute for another connection, there is a problem */
711 if (ero != NULL && ero != c)
712 {
713 struct connection *ero2, *ero_top;
714 struct connection *inside, *outside;
715
716 /*
717 * note, wavesec (PERMANENT) goes *outside* and
718 * OE goes *inside* (TEMPLATE)
719 */
720 inside = NULL;
721 outside= NULL;
722 if (ero->kind == CK_PERMANENT
723 && c->kind == CK_TEMPLATE)
724 {
725 outside = ero;
726 inside = c;
727 }
728 else if (c->kind == CK_PERMANENT
729 && ero->kind == CK_TEMPLATE)
730 {
731 outside = c;
732 inside = ero;
733 }
734
735 /* okay, check again, with correct order */
736 if (outside && outside->kind == CK_PERMANENT
737 && inside && inside->kind == CK_TEMPLATE)
738 {
739 char inst[CONN_INST_BUF];
740
741 /* this is a co-terminal attempt of the "near" kind. */
742 /* when chaining, we chain from inside to outside */
743
744 /* XXX permit multiple deep connections? */
745 passert(inside->policy_next == NULL);
746
747 inside->policy_next = outside;
748
749 /* since we are going to steal the eroute from the secondary
750 * policy, we need to make sure that it no longer thinks that
751 * it owns the eroute.
752 */
753 outside->spd.eroute_owner = SOS_NOBODY;
754 outside->spd.routing = RT_UNROUTED_KEYED;
755
756 /* set the priority of the new eroute owner to be higher
757 * than that of the current eroute owner
758 */
759 inside->prio = outside->prio + 1;
760
761 fmt_conn_instance(inside, inst);
762
763 loglog(RC_LOG_SERIOUS
764 , "conflict on eroute (%s), switching eroute to %s and linking %s"
765 , inst, inside->name, outside->name);
766
767 return route_nearconflict;
768 }
769
770 /* look along the chain of policies for one with the same name */
771 ero_top = ero;
772
773 for (ero2 = ero; ero2 != NULL; ero2 = ero->policy_next)
774 {
775 if (ero2->kind == CK_TEMPLATE
776 && streq(ero2->name, c->name))
777 break;
778 }
779
780 /* If we fell of the end of the list, then we found no TEMPLATE
781 * so there must be a conflict that we can't resolve.
782 * As the names are not equal, then we aren't replacing/rekeying.
783 */
784 if (ero2 == NULL)
785 {
786 char inst[CONN_INST_BUF];
787
788 fmt_conn_instance(ero, inst);
789
790 loglog(RC_LOG_SERIOUS
791 , "cannot install eroute -- it is in use for \"%s\"%s #%lu"
792 , ero->name, inst, esr->eroute_owner);
793 return FALSE; /* another connection already using the eroute */
794 }
795 }
796 #endif /* KLIPS */
797 return route_easy;
798 }
799
800 bool trap_connection(struct connection *c)
801 {
802 switch (could_route(c))
803 {
804 case route_impossible:
805 return FALSE;
806
807 case route_nearconflict:
808 case route_easy:
809 /* RT_ROUTED_TUNNEL is treated specially: we don't override
810 * because we don't want to lose track of the IPSEC_SAs etc.
811 */
812 if (c->spd.routing < RT_ROUTED_TUNNEL)
813 {
814 return route_and_eroute(c, &c->spd, NULL);
815 }
816 return TRUE;
817
818 case route_farconflict:
819 return FALSE;
820 }
821
822 return FALSE;
823 }
824
825 /**
826 * Delete any eroute for a connection and unroute it if route isn't shared
827 */
828 void unroute_connection(struct connection *c)
829 {
830 struct spd_route *sr;
831 enum routing_t cr;
832
833 for (sr = &c->spd; sr; sr = sr->next)
834 {
835 cr = sr->routing;
836
837 if (erouted(cr))
838 {
839 /* cannot handle a live one */
840 passert(sr->routing != RT_ROUTED_TUNNEL);
841 #ifdef KLIPS
842 shunt_eroute(c, sr, RT_UNROUTED, ERO_DELETE, "delete");
843 #endif
844 }
845
846 sr->routing = RT_UNROUTED; /* do now so route_owner won't find us */
847
848 /* only unroute if no other connection shares it */
849 if (routed(cr) && route_owner(c, NULL, NULL, NULL) == NULL)
850 (void) do_command(c, sr, "unroute");
851 }
852 }
853
854
855 #ifdef KLIPS
856
857 static void set_text_said(char *text_said, const ip_address *dst,
858 ipsec_spi_t spi, int proto)
859 {
860 ip_said said;
861
862 initsaid(dst, spi, proto, &said);
863 satot(&said, 0, text_said, SATOT_BUF);
864 }
865
866 /* find an entry in the bare_shunt table.
867 * Trick: return a pointer to the pointer to the entry;
868 * this allows the entry to be deleted.
869 */
870 static struct bare_shunt** bare_shunt_ptr(const ip_subnet *ours,
871 const ip_subnet *his,
872 int transport_proto)
873 {
874 struct bare_shunt *p, **pp;
875
876 for (pp = &bare_shunts; (p = *pp) != NULL; pp = &p->next)
877 {
878 if (samesubnet(ours, &p->ours)
879 && samesubnet(his, &p->his)
880 && transport_proto == p->transport_proto
881 && portof(&ours->addr) == portof(&p->ours.addr)
882 && portof(&his->addr) == portof(&p->his.addr))
883 return pp;
884 }
885 return NULL;
886 }
887
888 /* free a bare_shunt entry, given a pointer to the pointer */
889 static void free_bare_shunt(struct bare_shunt **pp)
890 {
891 if (pp == NULL)
892 {
893 DBG(DBG_CONTROL,
894 DBG_log("delete bare shunt: null pointer")
895 )
896 }
897 else
898 {
899 struct bare_shunt *p = *pp;
900
901 *pp = p->next;
902 DBG_bare_shunt("delete", p);
903 free(p->why);
904 free(p);
905 }
906 }
907
908 void
909 show_shunt_status(void)
910 {
911 struct bare_shunt *bs;
912
913 for (bs = bare_shunts; bs != NULL; bs = bs->next)
914 {
915 /* Print interesting fields. Ignore count and last_active. */
916
917 int ourport = ntohs(portof(&bs->ours.addr));
918 int hisport = ntohs(portof(&bs->his.addr));
919 char ourst[SUBNETTOT_BUF];
920 char hist[SUBNETTOT_BUF];
921 char sat[SATOT_BUF];
922 char prio[POLICY_PRIO_BUF];
923
924 subnettot(&(bs)->ours, 0, ourst, sizeof(ourst));
925 subnettot(&(bs)->his, 0, hist, sizeof(hist));
926 satot(&(bs)->said, 0, sat, sizeof(sat));
927 fmt_policy_prio(bs->policy_prio, prio);
928
929 whack_log(RC_COMMENT, "%s:%d -> %s:%d => %s:%d %s %s"
930 , ourst, ourport, hist, hisport, sat, bs->transport_proto
931 , prio, bs->why);
932 }
933 if (bare_shunts != NULL)
934 whack_log(RC_COMMENT, BLANK_FORMAT); /* spacer */
935 }
936
937 /* Setup an IPsec route entry.
938 * op is one of the ERO_* operators.
939 */
940
941 static bool raw_eroute(const ip_address *this_host,
942 const ip_subnet *this_client,
943 const ip_address *that_host,
944 const ip_subnet *that_client,
945 ipsec_spi_t spi,
946 unsigned int proto,
947 unsigned int satype,
948 unsigned int transport_proto,
949 const struct pfkey_proto_info *proto_info,
950 time_t use_lifetime,
951 unsigned int op,
952 const char *opname USED_BY_DEBUG)
953 {
954 char text_said[SATOT_BUF];
955
956 set_text_said(text_said, that_host, spi, proto);
957
958 DBG(DBG_CONTROL | DBG_KLIPS,
959 {
960 int sport = ntohs(portof(&this_client->addr));
961 int dport = ntohs(portof(&that_client->addr));
962 char mybuf[SUBNETTOT_BUF];
963 char peerbuf[SUBNETTOT_BUF];
964
965 subnettot(this_client, 0, mybuf, sizeof(mybuf));
966 subnettot(that_client, 0, peerbuf, sizeof(peerbuf));
967 DBG_log("%s eroute %s:%d -> %s:%d => %s:%d"
968 , opname, mybuf, sport, peerbuf, dport
969 , text_said, transport_proto);
970 });
971
972 return kernel_ops->raw_eroute(this_host, this_client
973 , that_host, that_client, spi, satype, transport_proto, proto_info
974 , use_lifetime, op, text_said);
975 }
976
977 /* test to see if %hold remains */
978 bool has_bare_hold(const ip_address *src, const ip_address *dst,
979 int transport_proto)
980 {
981 ip_subnet this_client, that_client;
982 struct bare_shunt **bspp;
983
984 passert(addrtypeof(src) == addrtypeof(dst));
985 happy(addrtosubnet(src, &this_client));
986 happy(addrtosubnet(dst, &that_client));
987 bspp = bare_shunt_ptr(&this_client, &that_client, transport_proto);
988 return bspp != NULL
989 && (*bspp)->said.proto == SA_INT && (*bspp)->said.spi == htonl(SPI_HOLD);
990 }
991
992
993 /* Replace (or delete) a shunt that is in the bare_shunts table.
994 * Issues the PF_KEY commands and updates the bare_shunts table.
995 */
996 bool replace_bare_shunt(const ip_address *src, const ip_address *dst,
997 policy_prio_t policy_prio, ipsec_spi_t shunt_spi,
998 bool repl, unsigned int transport_proto, const char *why)
999 {
1000 ip_subnet this_client, that_client;
1001 ip_subnet this_broad_client, that_broad_client;
1002 const ip_address *null_host = aftoinfo(addrtypeof(src))->any;
1003
1004 passert(addrtypeof(src) == addrtypeof(dst));
1005 happy(addrtosubnet(src, &this_client));
1006 happy(addrtosubnet(dst, &that_client));
1007 this_broad_client = this_client;
1008 that_broad_client = that_client;
1009 setportof(0, &this_broad_client.addr);
1010 setportof(0, &that_broad_client.addr);
1011
1012 if (repl)
1013 {
1014 struct bare_shunt **bs_pp = bare_shunt_ptr(&this_broad_client
1015 , &that_broad_client, 0);
1016
1017 /* is there already a broad host-to-host bare shunt? */
1018 if (bs_pp == NULL)
1019 {
1020 if (raw_eroute(null_host, &this_broad_client, null_host, &that_broad_client
1021 , htonl(shunt_spi), SA_INT, SADB_X_SATYPE_INT
1022 , 0, null_proto_info
1023 , SHUNT_PATIENCE, ERO_ADD, why))
1024 {
1025 struct bare_shunt *bs = malloc_thing(struct bare_shunt);
1026
1027 bs->ours = this_broad_client;
1028 bs->his = that_broad_client;
1029 bs->transport_proto = 0;
1030 bs->said.proto = SA_INT;
1031 bs->why = clone_str(why);
1032 bs->policy_prio = policy_prio;
1033 bs->said.spi = htonl(shunt_spi);
1034 bs->said.dst = *null_host;
1035 bs->count = 0;
1036 bs->last_activity = now();
1037 bs->next = bare_shunts;
1038 bare_shunts = bs;
1039 DBG_bare_shunt("add", bs);
1040 }
1041 }
1042 shunt_spi = SPI_HOLD;
1043 }
1044
1045 if (raw_eroute(null_host, &this_client, null_host, &that_client
1046 , htonl(shunt_spi), SA_INT, SADB_X_SATYPE_INT
1047 , transport_proto, null_proto_info
1048 , SHUNT_PATIENCE, ERO_DELETE, why))
1049 {
1050 struct bare_shunt **bs_pp = bare_shunt_ptr(&this_client, &that_client
1051 , transport_proto);
1052
1053 /* delete bare eroute */
1054 free_bare_shunt(bs_pp);
1055 return TRUE;
1056 }
1057 else
1058 {
1059 return FALSE;
1060 }
1061 }
1062
1063 static bool eroute_connection(struct spd_route *sr, ipsec_spi_t spi,
1064 unsigned int proto, unsigned int satype,
1065 const struct pfkey_proto_info *proto_info,
1066 unsigned int op, const char *opname)
1067 {
1068 const ip_address *peer = &sr->that.host_addr;
1069 char buf2[256];
1070
1071 snprintf(buf2, sizeof(buf2)
1072 , "eroute_connection %s", opname);
1073
1074 if (proto == SA_INT)
1075 peer = aftoinfo(addrtypeof(peer))->any;
1076
1077 return raw_eroute(&sr->this.host_addr, &sr->this.client
1078 , peer
1079 , &sr->that.client
1080 , spi, proto, satype
1081 , sr->this.protocol, proto_info, 0, op, buf2);
1082 }
1083
1084 /* assign a bare hold to a connection */
1085
1086 bool assign_hold(struct connection *c USED_BY_DEBUG, struct spd_route *sr,
1087 int transport_proto,
1088 const ip_address *src,
1089 const ip_address *dst)
1090 {
1091 /* either the automatically installed %hold eroute is broad enough
1092 * or we try to add a broader one and delete the automatic one.
1093 * Beware: this %hold might be already handled, but still squeak
1094 * through because of a race.
1095 */
1096 enum routing_t ro = sr->routing /* routing, old */
1097 , rn = ro; /* routing, new */
1098
1099 passert(LHAS(LELEM(CK_PERMANENT) | LELEM(CK_INSTANCE), c->kind));
1100 /* figure out what routing should become */
1101 switch (ro)
1102 {
1103 case RT_UNROUTED:
1104 rn = RT_UNROUTED_HOLD;
1105 break;
1106 case RT_ROUTED_PROSPECTIVE:
1107 rn = RT_ROUTED_HOLD;
1108 break;
1109 default:
1110 /* no change: this %hold is old news and should just be deleted */
1111 break;
1112 }
1113
1114 /* we need a broad %hold, not the narrow one.
1115 * First we ensure that there is a broad %hold.
1116 * There may already be one (race condition): no need to create one.
1117 * There may already be a %trap: replace it.
1118 * There may not be any broad eroute: add %hold.
1119 * Once the broad %hold is in place, delete the narrow one.
1120 */
1121 if (rn != ro)
1122 {
1123 if (erouted(ro)
1124 ? !eroute_connection(sr, htonl(SPI_HOLD), SA_INT, SADB_X_SATYPE_INT
1125 , null_proto_info
1126 , ERO_REPLACE, "replace %trap with broad %hold")
1127 : !eroute_connection(sr, htonl(SPI_HOLD), SA_INT, SADB_X_SATYPE_INT
1128 , null_proto_info
1129 , ERO_ADD, "add broad %hold"))
1130 {
1131 return FALSE;
1132 }
1133 }
1134 if (!replace_bare_shunt(src, dst, BOTTOM_PRIO, SPI_HOLD, FALSE
1135 , transport_proto, "delete narrow %hold"))
1136 {
1137 return FALSE;
1138 }
1139 sr->routing = rn;
1140 return TRUE;
1141 }
1142
1143 /* install or remove eroute for SA Group */
1144 static bool sag_eroute(struct state *st, struct spd_route *sr,
1145 unsigned op, const char *opname)
1146 {
1147 u_int inner_proto = 0;
1148 u_int inner_satype = 0;
1149 ipsec_spi_t inner_spi = 0;
1150 struct pfkey_proto_info proto_info[4];
1151 int i;
1152 bool tunnel;
1153
1154 /* figure out the SPI and protocol (in two forms)
1155 * for the innermost transformation.
1156 */
1157
1158 i = sizeof(proto_info) / sizeof(proto_info[0]) - 1;
1159 proto_info[i].proto = 0;
1160 tunnel = FALSE;
1161
1162 if (st->st_ah.present)
1163 {
1164 inner_spi = st->st_ah.attrs.spi;
1165 inner_proto = SA_AH;
1166 inner_satype = SADB_SATYPE_AH;
1167
1168 i--;
1169 proto_info[i].proto = IPPROTO_AH;
1170 proto_info[i].encapsulation = st->st_ah.attrs.encapsulation;
1171 tunnel |= proto_info[i].encapsulation == ENCAPSULATION_MODE_TUNNEL;
1172 proto_info[i].reqid = sr->reqid;
1173 }
1174
1175 if (st->st_esp.present)
1176 {
1177 inner_spi = st->st_esp.attrs.spi;
1178 inner_proto = SA_ESP;
1179 inner_satype = SADB_SATYPE_ESP;
1180
1181 i--;
1182 proto_info[i].proto = IPPROTO_ESP;
1183 proto_info[i].encapsulation = st->st_esp.attrs.encapsulation;
1184 tunnel |= proto_info[i].encapsulation == ENCAPSULATION_MODE_TUNNEL;
1185 proto_info[i].reqid = sr->reqid + 1;
1186 }
1187
1188 if (st->st_ipcomp.present)
1189 {
1190 inner_spi = st->st_ipcomp.attrs.spi;
1191 inner_proto = SA_COMP;
1192 inner_satype = SADB_X_SATYPE_COMP;
1193
1194 i--;
1195 proto_info[i].proto = IPPROTO_COMP;
1196 proto_info[i].encapsulation = st->st_ipcomp.attrs.encapsulation;
1197 tunnel |= proto_info[i].encapsulation == ENCAPSULATION_MODE_TUNNEL;
1198 proto_info[i].reqid = sr->reqid + 2;
1199 }
1200
1201 if (i == sizeof(proto_info) / sizeof(proto_info[0]) - 1)
1202 {
1203 impossible(); /* no transform at all! */
1204 }
1205
1206 if (tunnel)
1207 {
1208 int j;
1209
1210 inner_spi = st->st_tunnel_out_spi;
1211 inner_proto = SA_IPIP;
1212 inner_satype = SADB_X_SATYPE_IPIP;
1213
1214 proto_info[i].encapsulation = ENCAPSULATION_MODE_TUNNEL;
1215 for (j = i + 1; proto_info[j].proto; j++)
1216 {
1217 proto_info[j].encapsulation = ENCAPSULATION_MODE_TRANSPORT;
1218 }
1219 }
1220
1221 return eroute_connection(sr
1222 , inner_spi, inner_proto, inner_satype, proto_info + i
1223 , op, opname);
1224 }
1225
1226 /* compute a (host-order!) SPI to implement the policy in connection c */
1227 ipsec_spi_t
1228 shunt_policy_spi(struct connection *c, bool prospective)
1229 {
1230 /* note: these are in host order :-( */
1231 static const ipsec_spi_t shunt_spi[] =
1232 {
1233 SPI_TRAP, /* --initiateontraffic */
1234 SPI_PASS, /* --pass */
1235 SPI_DROP, /* --drop */
1236 SPI_REJECT, /* --reject */
1237 };
1238
1239 static const ipsec_spi_t fail_spi[] =
1240 {
1241 0, /* --none*/
1242 SPI_PASS, /* --failpass */
1243 SPI_DROP, /* --faildrop */
1244 SPI_REJECT, /* --failreject */
1245 };
1246
1247 return prospective
1248 ? shunt_spi[(c->policy & POLICY_SHUNT_MASK) >> POLICY_SHUNT_SHIFT]
1249 : fail_spi[(c->policy & POLICY_FAIL_MASK) >> POLICY_FAIL_SHIFT];
1250 }
1251
1252 /* Add/replace/delete a shunt eroute.
1253 * Such an eroute determines the fate of packets without the use
1254 * of any SAs. These are defaults, in effect.
1255 * If a negotiation has not been attempted, use %trap.
1256 * If negotiation has failed, the choice between %trap/%pass/%drop/%reject
1257 * is specified in the policy of connection c.
1258 */
1259 static bool shunt_eroute(struct connection *c, struct spd_route *sr,
1260 enum routing_t rt_kind,
1261 unsigned int op, const char *opname)
1262 {
1263 /* We are constructing a special SAID for the eroute.
1264 * The destination doesn't seem to matter, but the family does.
1265 * The protocol is SA_INT -- mark this as shunt.
1266 * The satype has no meaning, but is required for PF_KEY header!
1267 * The SPI signifies the kind of shunt.
1268 */
1269 ipsec_spi_t spi = shunt_policy_spi(c, rt_kind == RT_ROUTED_PROSPECTIVE);
1270 bool ok;
1271
1272 if (spi == 0)
1273 {
1274 /* we're supposed to end up with no eroute: rejig op and opname */
1275 switch (op)
1276 {
1277 case ERO_REPLACE:
1278 /* replace with nothing == delete */
1279 op = ERO_DELETE;
1280 opname = "delete";
1281 break;
1282 case ERO_ADD:
1283 /* add nothing == do nothing */
1284 return TRUE;
1285 case ERO_DELETE:
1286 /* delete remains delete */
1287 break;
1288 default:
1289 bad_case(op);
1290 }
1291 }
1292 if (sr->routing == RT_ROUTED_ECLIPSED && c->kind == CK_TEMPLATE)
1293 {
1294 /* We think that we have an eroute, but we don't.
1295 * Adjust the request and account for eclipses.
1296 */
1297 passert(eclipsable(sr));
1298 switch (op)
1299 {
1300 case ERO_REPLACE:
1301 /* really an add */
1302 op = ERO_ADD;
1303 opname = "replace eclipsed";
1304 eclipse_count--;
1305 break;
1306 case ERO_DELETE:
1307 /* delete unnecessary: we don't actually have an eroute */
1308 eclipse_count--;
1309 return TRUE;
1310 case ERO_ADD:
1311 default:
1312 bad_case(op);
1313 }
1314 }
1315 else if (eclipse_count > 0 && op == ERO_DELETE && eclipsable(sr))
1316 {
1317 /* maybe we are uneclipsing something */
1318 struct spd_route *esr;
1319 struct connection *ue = eclipsed(c, &esr);
1320
1321 if (ue != NULL)
1322 {
1323 esr->routing = RT_ROUTED_PROSPECTIVE;
1324 return shunt_eroute(ue, esr
1325 , RT_ROUTED_PROSPECTIVE, ERO_REPLACE, "restoring eclipsed");
1326 }
1327 }
1328
1329 ok = TRUE;
1330 if (kernel_ops->inbound_eroute)
1331 {
1332 ok = raw_eroute(&c->spd.that.host_addr, &c->spd.that.client
1333 , &c->spd.this.host_addr, &c->spd.this.client
1334 , htonl(spi), SA_INT, SADB_X_SATYPE_INT
1335 , 0, null_proto_info, 0
1336 , op | (SADB_X_SAFLAGS_INFLOW << ERO_FLAG_SHIFT), opname);
1337 }
1338 return eroute_connection(sr, htonl(spi), SA_INT, SADB_X_SATYPE_INT
1339 , null_proto_info, op, opname) && ok;
1340 }
1341
1342
1343 /*
1344 * This is only called when s is a likely SAID with trailing protocol i.e.
1345 * it has the form :-
1346 *
1347 * %<keyword>:p
1348 * <ip-proto><spi>@a.b.c.d:p
1349 *
1350 * The task here is to remove the ":p" part so that the rest can be read
1351 * by another routine.
1352 */
1353 static const char *read_proto(const char * s, size_t * len, int * transport_proto)
1354 {
1355 const char * p;
1356 const char * ugh;
1357 unsigned long proto;
1358 size_t l;
1359
1360 l = *len;
1361 p = memchr(s, ':', l);
1362 if (p == 0) {
1363 *transport_proto = 0;
1364 return 0;
1365 }
1366 ugh = ttoul(p+1, l-((p-s)+1), 10, &proto);
1367 if (ugh != 0)
1368 return ugh;
1369 if (proto > 65535)
1370 return "protocol number is too large, legal range is 0-65535";
1371 *len = p-s;
1372 *transport_proto = proto;
1373 return 0;
1374 }
1375
1376
1377 /* scan /proc/net/ipsec_eroute every once in a while, looking for:
1378 *
1379 * - %hold shunts of which Pluto isn't aware. This situation could
1380 * be caused by lost ACQUIRE messages. When found, they will
1381 * added to orphan_holds. This in turn will lead to Opportunistic
1382 * initiation.
1383 *
1384 * - other kinds of shunts that haven't been used recently. These will be
1385 * deleted. They represent OE failures.
1386 *
1387 * - recording recent uses of tunnel eroutes so that rekeying decisions
1388 * can be made for OE connections.
1389 *
1390 * Here are some sample lines:
1391 * 10 10.3.2.1.0/24 -> 0.0.0.0/0 => %trap
1392 * 259 10.3.2.1.115/32 -> 10.19.75.161/32 => tun0x1002@10.19.75.145
1393 * 71 10.44.73.97/32 -> 0.0.0.0/0 => %trap
1394 * 4119 10.44.73.97/32 -> 10.114.121.41/32 => %pass
1395 * Newer versions of KLIPS start each line with a 32-bit packet count.
1396 * If available, the count is used to detect whether a %pass shunt is in use.
1397 *
1398 * NOTE: execution time is quadratic in the number of eroutes since the
1399 * searching for each is sequential. If this becomes a problem, faster
1400 * searches could be implemented (hash or radix tree, for example).
1401 */
1402 void scan_proc_shunts(void)
1403 {
1404 static const char procname[] = "/proc/net/ipsec_eroute";
1405 FILE *f;
1406 time_t nw = now();
1407 int lino;
1408 struct eroute_info *expired = NULL;
1409
1410 event_schedule(EVENT_SHUNT_SCAN, SHUNT_SCAN_INTERVAL, NULL);
1411
1412 DBG(DBG_CONTROL,
1413 DBG_log("scanning for shunt eroutes")
1414 )
1415
1416 /* free any leftover entries: they will be refreshed if still current */
1417 while (orphaned_holds != NULL)
1418 {
1419 struct eroute_info *p = orphaned_holds;
1420
1421 orphaned_holds = p->next;
1422 free(orphaned_holds);
1423 }
1424
1425 /* decode the /proc file. Don't do anything strenuous to it
1426 * (certainly no PF_KEY stuff) to minimize the chance that it
1427 * might change underfoot.
1428 */
1429
1430 f = fopen(procname, "r");
1431 if (f == NULL)
1432 return;
1433
1434 /* for each line... */
1435 for (lino = 1; ; lino++)
1436 {
1437 unsigned char buf[1024]; /* should be big enough */
1438 chunk_t field[10]; /* 10 is loose upper bound */
1439 chunk_t *ff = NULL; /* fixed fields (excluding optional count) */
1440 int fi;
1441 struct eroute_info eri;
1442 char *cp;
1443 err_t context = ""
1444 , ugh = NULL;
1445
1446 cp = fgets(buf, sizeof(buf), f);
1447 if (cp == NULL)
1448 break;
1449
1450 /* break out each field
1451 * Note: if there are too many fields, just stop;
1452 * it will be diagnosed a little later.
1453 */
1454 for (fi = 0; fi < (int)countof(field); fi++)
1455 {
1456 static const char sep[] = " \t\n"; /* field-separating whitespace */
1457 size_t w;
1458
1459 cp += strspn(cp, sep); /* find start of field */
1460 w = strcspn(cp, sep); /* find width of field */
1461 field[fi] = chunk_create(cp, w);
1462 cp += w;
1463 if (w == 0)
1464 break;
1465 }
1466
1467 /* This odd do-hickey is to share error reporting code.
1468 * A break will get to that common code. The setting
1469 * of "ugh" and "context" parameterize it.
1470 */
1471 do {
1472 /* Old entries have no packet count; new ones do.
1473 * check if things are as they should be.
1474 */
1475 if (fi == 5)
1476 ff = &field[0]; /* old form, with no count */
1477 else if (fi == 6)
1478 ff = &field[1]; /* new form, with count */
1479 else
1480 {
1481 ugh = "has wrong number of fields";
1482 break;
1483 }
1484
1485 if (ff[1].len != 2
1486 || strncmp(ff[1].ptr, "->", 2) != 0
1487 || ff[3].len != 2
1488 || strncmp(ff[3].ptr, "=>", 2) != 0)
1489 {
1490 ugh = "is missing -> or =>";
1491 break;
1492 }
1493
1494 /* actually digest fields of interest */
1495
1496 /* packet count */
1497
1498 eri.count = 0;
1499 if (ff != field)
1500 {
1501 context = "count field is malformed: ";
1502 ugh = ttoul(field[0].ptr, field[0].len, 10, &eri.count);
1503 if (ugh != NULL)
1504 break;
1505 }
1506
1507 /* our client */
1508
1509 context = "source subnet field malformed: ";
1510 ugh = ttosubnet(ff[0].ptr, ff[0].len, AF_INET, &eri.ours);
1511 if (ugh != NULL)
1512 break;
1513
1514 /* his client */
1515
1516 context = "destination subnet field malformed: ";
1517 ugh = ttosubnet(ff[2].ptr, ff[2].len, AF_INET, &eri.his);
1518 if (ugh != NULL)
1519 break;
1520
1521 /* SAID */
1522
1523 context = "SA ID field malformed: ";
1524 ugh = read_proto(ff[4].ptr, &ff[4].len, &eri.transport_proto);
1525 if (ugh != NULL)
1526 break;
1527 ugh = ttosa(ff[4].ptr, ff[4].len, &eri.said);
1528 } while (FALSE);
1529
1530 if (ugh != NULL)
1531 {
1532 plog("INTERNAL ERROR: %s line %d %s%s"
1533 , procname, lino, context, ugh);
1534 continue; /* ignore rest of line */
1535 }
1536
1537 /* Now we have decoded eroute, let's consider it.
1538 * For shunt eroutes:
1539 *
1540 * %hold: if not known, add to orphaned_holds list for initiation
1541 * because ACQUIRE might have been lost.
1542 *
1543 * %pass, %drop, %reject: determine if idle; if so, blast it away.
1544 * Can occur bare (if DNS provided insufficient information)
1545 * or with a connection (failure context).
1546 * Could even be installed by ipsec manual.
1547 *
1548 * %trap: always welcome.
1549 *
1550 * For other eroutes: find state and record count change
1551 */
1552 if (eri.said.proto == SA_INT)
1553 {
1554 /* shunt eroute */
1555 switch (ntohl(eri.said.spi))
1556 {
1557 case SPI_HOLD:
1558 if (bare_shunt_ptr(&eri.ours, &eri.his, eri.transport_proto) == NULL
1559 && shunt_owner(&eri.ours, &eri.his) == NULL)
1560 {
1561 int ourport = ntohs(portof(&eri.ours.addr));
1562 int hisport = ntohs(portof(&eri.his.addr));
1563 char ourst[SUBNETTOT_BUF];
1564 char hist[SUBNETTOT_BUF];
1565 char sat[SATOT_BUF];
1566
1567 subnettot(&eri.ours, 0, ourst, sizeof(ourst));
1568 subnettot(&eri.his, 0, hist, sizeof(hist));
1569 satot(&eri.said, 0, sat, sizeof(sat));
1570
1571 DBG(DBG_CONTROL,
1572 DBG_log("add orphaned shunt %s:%d -> %s:%d => %s:%d"
1573 , ourst, ourport, hist, hisport, sat, eri.transport_proto)
1574 )
1575 eri.next = orphaned_holds;
1576 orphaned_holds = clone_thing(eri);
1577 }
1578 break;
1579
1580 case SPI_PASS:
1581 case SPI_DROP:
1582 case SPI_REJECT:
1583 /* nothing sensible to do if we don't have counts */
1584 if (ff != field)
1585 {
1586 struct bare_shunt **bs_pp
1587 = bare_shunt_ptr(&eri.ours, &eri.his, eri.transport_proto);
1588
1589 if (bs_pp != NULL)
1590 {
1591 struct bare_shunt *bs = *bs_pp;
1592
1593 if (eri.count != bs->count)
1594 {
1595 bs->count = eri.count;
1596 bs->last_activity = nw;
1597 }
1598 else if (nw - bs->last_activity > SHUNT_PATIENCE)
1599 {
1600 eri.next = expired;
1601 expired = clone_thing(eri);
1602 }
1603 }
1604 }
1605 break;
1606
1607 case SPI_TRAP:
1608 break;
1609
1610 default:
1611 bad_case(ntohl(eri.said.spi));
1612 }
1613 }
1614 else
1615 {
1616 /* regular (non-shunt) eroute */
1617 state_eroute_usage(&eri.ours, &eri.his, eri.count, nw);
1618 }
1619 } /* for each line */
1620 fclose(f);
1621
1622 /* Now that we've finished processing the /proc file,
1623 * it is safe to delete the expired %pass shunts.
1624 */
1625 while (expired != NULL)
1626 {
1627 struct eroute_info *p = expired;
1628 ip_address src, dst;
1629
1630 networkof(&p->ours, &src);
1631 networkof(&p->his, &dst);
1632 (void) replace_bare_shunt(&src, &dst
1633 , BOTTOM_PRIO /* not used because we are deleting. This value is a filler */
1634 , SPI_PASS /* not used because we are deleting. This value is a filler */
1635 , FALSE, p->transport_proto, "delete expired bare shunts");
1636 expired = p->next;
1637 free(p);
1638 }
1639 }
1640
1641 static bool del_spi(ipsec_spi_t spi, int proto,
1642 const ip_address *src, const ip_address *dest)
1643 {
1644 char text_said[SATOT_BUF];
1645 struct kernel_sa sa;
1646
1647 set_text_said(text_said, dest, spi, proto);
1648
1649 DBG(DBG_KLIPS, DBG_log("delete %s", text_said));
1650
1651 memset(&sa, 0, sizeof(sa));
1652 sa.spi = spi;
1653 sa.proto = proto;
1654 sa.src = src;
1655 sa.dst = dest;
1656 sa.text_said = text_said;
1657
1658 return kernel_ops->del_sa(&sa);
1659 }
1660
1661 /* Setup a pair of SAs. Code taken from setsa.c and spigrp.c, in
1662 * ipsec-0.5.
1663 */
1664
1665 static bool setup_half_ipsec_sa(struct state *st, bool inbound)
1666 {
1667 /* Build an inbound or outbound SA */
1668
1669 struct connection *c = st->st_connection;
1670 ip_subnet src, dst;
1671 ip_subnet src_client, dst_client;
1672 ipsec_spi_t inner_spi = 0;
1673 u_int proto = 0;
1674 u_int satype = SADB_SATYPE_UNSPEC;
1675 bool replace;
1676
1677 /* SPIs, saved for spigrouping or undoing, if necessary */
1678 struct kernel_sa
1679 said[EM_MAXRELSPIS],
1680 *said_next = said;
1681
1682 char text_said[SATOT_BUF];
1683 int encapsulation;
1684
1685 replace = inbound && (kernel_ops->get_spi != NULL);
1686
1687 src.maskbits = 0;
1688 dst.maskbits = 0;
1689
1690 if (inbound)
1691 {
1692 src.addr = c->spd.that.host_addr;
1693 dst.addr = c->spd.this.host_addr;
1694 src_client = c->spd.that.client;
1695 dst_client = c->spd.this.client;
1696 }
1697 else
1698 {
1699 src.addr = c->spd.this.host_addr,
1700 dst.addr = c->spd.that.host_addr;
1701 src_client = c->spd.this.client;
1702 dst_client = c->spd.that.client;
1703 }
1704
1705 encapsulation = ENCAPSULATION_MODE_TRANSPORT;
1706 if (st->st_ah.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL
1707 || st->st_esp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL
1708 || st->st_ipcomp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1709 {
1710 encapsulation = ENCAPSULATION_MODE_TUNNEL;
1711 }
1712
1713 memset(said, 0, sizeof(said));
1714
1715 /* If we are tunnelling, set up IP in IP pseudo SA */
1716
1717 if (kernel_ops->inbound_eroute)
1718 {
1719 inner_spi = 256;
1720 proto = SA_IPIP;
1721 satype = SADB_SATYPE_UNSPEC;
1722 }
1723 else if (encapsulation == ENCAPSULATION_MODE_TUNNEL)
1724 {
1725 /* XXX hack alert -- we SHOULD NOT HAVE TO HAVE A DIFFERENT SPI
1726 * XXX FOR IP-in-IP ENCAPSULATION!
1727 */
1728
1729 ipsec_spi_t ipip_spi;
1730
1731 /* Allocate an SPI for the tunnel.
1732 * Since our peer will never see this,
1733 * and it comes from its own number space,
1734 * it is purely a local implementation wart.
1735 */
1736 {
1737 static ipsec_spi_t last_tunnel_spi = IPSEC_DOI_SPI_OUR_MIN;
1738
1739 ipip_spi = htonl(++last_tunnel_spi);
1740 if (inbound)
1741 st->st_tunnel_in_spi = ipip_spi;
1742 else
1743 st->st_tunnel_out_spi = ipip_spi;
1744 }
1745
1746 set_text_said(text_said
1747 , &c->spd.that.host_addr, ipip_spi, SA_IPIP);
1748
1749 said_next->src = &src.addr;
1750 said_next->dst = &dst.addr;
1751 said_next->src_client = &src_client;
1752 said_next->dst_client = &dst_client;
1753 said_next->spi = ipip_spi;
1754 said_next->satype = SADB_X_SATYPE_IPIP;
1755 said_next->text_said = text_said;
1756
1757 if (!kernel_ops->add_sa(said_next, replace))
1758 goto fail;
1759
1760 said_next++;
1761
1762 inner_spi = ipip_spi;
1763 proto = SA_IPIP;
1764 satype = SADB_X_SATYPE_IPIP;
1765 }
1766
1767 /* set up IPCOMP SA, if any */
1768
1769 if (st->st_ipcomp.present)
1770 {
1771 ipsec_spi_t ipcomp_spi = inbound? st->st_ipcomp.our_spi : st->st_ipcomp.attrs.spi;
1772 unsigned compalg;
1773
1774 switch (st->st_ipcomp.attrs.transid)
1775 {
1776 case IPCOMP_DEFLATE:
1777 compalg = SADB_X_CALG_DEFLATE;
1778 break;
1779
1780 default:
1781 loglog(RC_LOG_SERIOUS, "IPCOMP transform %s not implemented"
1782 , enum_name(&ipcomp_transformid_names, st->st_ipcomp.attrs.transid));
1783 goto fail;
1784 }
1785
1786 set_text_said(text_said, &dst.addr, ipcomp_spi, SA_COMP);
1787
1788 said_next->src = &src.addr;
1789 said_next->dst = &dst.addr;
1790 said_next->src_client = &src_client;
1791 said_next->dst_client = &dst_client;
1792 said_next->spi = ipcomp_spi;
1793 said_next->satype = SADB_X_SATYPE_COMP;
1794 said_next->compalg = compalg;
1795 said_next->encapsulation = encapsulation;
1796 said_next->reqid = c->spd.reqid + 2;
1797 said_next->text_said = text_said;
1798
1799 if (!kernel_ops->add_sa(said_next, replace))
1800 goto fail;
1801
1802 said_next++;
1803
1804 encapsulation = ENCAPSULATION_MODE_TRANSPORT;
1805 }
1806
1807 /* set up ESP SA, if any */
1808
1809 if (st->st_esp.present)
1810 {
1811 ipsec_spi_t esp_spi = inbound? st->st_esp.our_spi : st->st_esp.attrs.spi;
1812 u_char *esp_dst_keymat = inbound? st->st_esp.our_keymat : st->st_esp.peer_keymat;
1813 const struct esp_info *ei;
1814 u_int16_t key_len;
1815
1816 static const struct esp_info esp_info[] = {
1817 { ESP_NULL, AUTH_ALGORITHM_HMAC_MD5,
1818 0, HMAC_MD5_KEY_LEN,
1819 SADB_EALG_NULL, SADB_AALG_MD5HMAC },
1820 { ESP_NULL, AUTH_ALGORITHM_HMAC_SHA1,
1821 0, HMAC_SHA1_KEY_LEN,
1822 SADB_EALG_NULL, SADB_AALG_SHA1HMAC },
1823
1824 { ESP_DES, AUTH_ALGORITHM_NONE,
1825 DES_CBC_BLOCK_SIZE, 0,
1826 SADB_EALG_DESCBC, SADB_AALG_NONE },
1827 { ESP_DES, AUTH_ALGORITHM_HMAC_MD5,
1828 DES_CBC_BLOCK_SIZE, HMAC_MD5_KEY_LEN,
1829 SADB_EALG_DESCBC, SADB_AALG_MD5HMAC },
1830 { ESP_DES, AUTH_ALGORITHM_HMAC_SHA1,
1831 DES_CBC_BLOCK_SIZE,
1832 HMAC_SHA1_KEY_LEN, SADB_EALG_DESCBC, SADB_AALG_SHA1HMAC },
1833
1834 { ESP_3DES, AUTH_ALGORITHM_NONE,
1835 DES_CBC_BLOCK_SIZE * 3, 0,
1836 SADB_EALG_3DESCBC, SADB_AALG_NONE },
1837 { ESP_3DES, AUTH_ALGORITHM_HMAC_MD5,
1838 DES_CBC_BLOCK_SIZE * 3, HMAC_MD5_KEY_LEN,
1839 SADB_EALG_3DESCBC, SADB_AALG_MD5HMAC },
1840 { ESP_3DES, AUTH_ALGORITHM_HMAC_SHA1,
1841 DES_CBC_BLOCK_SIZE * 3, HMAC_SHA1_KEY_LEN,
1842 SADB_EALG_3DESCBC, SADB_AALG_SHA1HMAC },
1843 };
1844
1845 u_int8_t natt_type = 0;
1846 u_int16_t natt_sport = 0;
1847 u_int16_t natt_dport = 0;
1848 ip_address natt_oa;
1849
1850 if (st->nat_traversal & NAT_T_DETECTED)
1851 {
1852 natt_type = (st->nat_traversal & NAT_T_WITH_PORT_FLOATING) ?
1853 ESPINUDP_WITH_NON_ESP : ESPINUDP_WITH_NON_IKE;
1854 natt_sport = inbound? c->spd.that.host_port : c->spd.this.host_port;
1855 natt_dport = inbound? c->spd.this.host_port : c->spd.that.host_port;
1856 natt_oa = st->nat_oa;
1857 }
1858
1859 for (ei = esp_info; ; ei++)
1860 {
1861 if (ei == &esp_info[countof(esp_info)])
1862 {
1863 /* Check for additional kernel alg */
1864 #ifndef NO_KERNEL_ALG
1865 if ((ei=kernel_alg_esp_info(st->st_esp.attrs.transid,
1866 st->st_esp.attrs.auth))!=NULL) {
1867 break;
1868 }
1869 #endif
1870
1871 /* note: enum_show may use a static buffer, so two
1872 * calls in one printf would be a mistake.
1873 * enum_name does the same job, without a static buffer,
1874 * assuming the name will be found.
1875 */
1876 loglog(RC_LOG_SERIOUS, "ESP transform %s / auth %s not implemented yet"
1877 , enum_name(&esp_transformid_names, st->st_esp.attrs.transid)
1878 , enum_name(&auth_alg_names, st->st_esp.attrs.auth));
1879 goto fail;
1880 }
1881
1882 if (st->st_esp.attrs.transid == ei->transid
1883 && st->st_esp.attrs.auth == ei->auth)
1884 break;
1885 }
1886
1887 key_len = st->st_esp.attrs.key_len/8;
1888 if (key_len)
1889 {
1890 /* XXX: must change to check valid _range_ key_len */
1891 if (key_len > ei->enckeylen)
1892 {
1893 loglog(RC_LOG_SERIOUS, "ESP transform %s passed key_len=%d > %d",
1894 enum_name(&esp_transformid_names, st->st_esp.attrs.transid),
1895 (int)key_len, (int)ei->enckeylen);
1896 goto fail;
1897 }
1898 }
1899 else
1900 {
1901 key_len = ei->enckeylen;
1902 }
1903 /* Grrrrr.... f*cking 7 bits jurassic algos */
1904
1905 /* 168 bits in kernel, need 192 bits for keymat_len */
1906 if (ei->transid == ESP_3DES && key_len == 21)
1907 key_len = 24;
1908
1909 /* 56 bits in kernel, need 64 bits for keymat_len */
1910 if (ei->transid == ESP_DES && key_len == 7)
1911 key_len = 8;
1912
1913 /* divide up keying material */
1914 /* passert(st->st_esp.keymat_len == ei->enckeylen + ei->authkeylen); */
1915 DBG(DBG_KLIPS|DBG_CONTROL|DBG_PARSING,
1916 if(st->st_esp.keymat_len != key_len + ei->authkeylen)
1917 DBG_log("keymat_len=%d key_len=%d authkeylen=%d",
1918 st->st_esp.keymat_len, (int)key_len, (int)ei->authkeylen);
1919 )
1920 passert(st->st_esp.keymat_len == key_len + ei->authkeylen);
1921
1922 set_text_said(text_said, &dst.addr, esp_spi, SA_ESP);
1923
1924 said_next->src = &src.addr;
1925 said_next->dst = &dst.addr;
1926 said_next->src_client = &src_client;
1927 said_next->dst_client = &dst_client;
1928 said_next->spi = esp_spi;
1929 said_next->satype = SADB_SATYPE_ESP;
1930 said_next->replay_window = (kernel_ops->type == KERNEL_TYPE_KLIPS) ? REPLAY_WINDOW : REPLAY_WINDOW_XFRM;
1931 said_next->authalg = ei->authalg;
1932 said_next->authkeylen = ei->authkeylen;
1933 /* said_next->authkey = esp_dst_keymat + ei->enckeylen; */
1934 said_next->authkey = esp_dst_keymat + key_len;
1935 said_next->encalg = ei->encryptalg;
1936 /* said_next->enckeylen = ei->enckeylen; */
1937 said_next->enckeylen = key_len;
1938 said_next->enckey = esp_dst_keymat;
1939 said_next->encapsulation = encapsulation;
1940 said_next->reqid = c->spd.reqid + 1;
1941 said_next->natt_sport = natt_sport;
1942 said_next->natt_dport = natt_dport;
1943 said_next->transid = st->st_esp.attrs.transid;
1944 said_next->natt_type = natt_type;
1945 said_next->natt_oa = &natt_oa;
1946 said_next->text_said = text_said;
1947
1948 if (!kernel_ops->add_sa(said_next, replace))
1949 goto fail;
1950
1951 said_next++;
1952
1953 encapsulation = ENCAPSULATION_MODE_TRANSPORT;
1954 }
1955
1956 /* set up AH SA, if any */
1957
1958 if (st->st_ah.present)
1959 {
1960 ipsec_spi_t ah_spi = inbound? st->st_ah.our_spi : st->st_ah.attrs.spi;
1961 u_char *ah_dst_keymat = inbound? st->st_ah.our_keymat : st->st_ah.peer_keymat;
1962
1963 unsigned char authalg;
1964
1965 switch (st->st_ah.attrs.auth)
1966 {
1967 case AUTH_ALGORITHM_HMAC_MD5:
1968 authalg = SADB_AALG_MD5HMAC;
1969 break;
1970
1971 case AUTH_ALGORITHM_HMAC_SHA1:
1972 authalg = SADB_AALG_SHA1HMAC;
1973 break;
1974
1975 default:
1976 loglog(RC_LOG_SERIOUS, "%s not implemented yet"
1977 , enum_show(&auth_alg_names, st->st_ah.attrs.auth));
1978 goto fail;
1979 }
1980
1981 set_text_said(text_said, &dst.addr, ah_spi, SA_AH);
1982
1983 said_next->src = &src.addr;
1984 said_next->dst = &dst.addr;
1985 said_next->src_client = &src_client;
1986 said_next->dst_client = &dst_client;
1987 said_next->spi = ah_spi;
1988 said_next->satype = SADB_SATYPE_AH;
1989 said_next->replay_window = (kernel_ops->type == KERNEL_TYPE_KLIPS) ? REPLAY_WINDOW : REPLAY_WINDOW_XFRM;
1990 said_next->authalg = authalg;
1991 said_next->authkeylen = st->st_ah.keymat_len;
1992 said_next->authkey = ah_dst_keymat;
1993 said_next->encapsulation = encapsulation;
1994 said_next->reqid = c->spd.reqid;
1995 said_next->text_said = text_said;
1996
1997 if (!kernel_ops->add_sa(said_next, replace))
1998 goto fail;
1999
2000 said_next++;
2001
2002 encapsulation = ENCAPSULATION_MODE_TRANSPORT;
2003 }
2004
2005 if (st->st_ah.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL
2006 || st->st_esp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL
2007 || st->st_ipcomp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
2008 {
2009 encapsulation = ENCAPSULATION_MODE_TUNNEL;
2010 }
2011
2012 if (kernel_ops->inbound_eroute ? c->spd.eroute_owner == SOS_NOBODY
2013 : encapsulation == ENCAPSULATION_MODE_TUNNEL)
2014 {
2015 /* If inbound, and policy does not specifie DISABLEARRIVALCHECK,
2016 * tell KLIPS to enforce the IP addresses appropriate for this tunnel.
2017 * Note reversed ends.
2018 * Not much to be done on failure.
2019 */
2020 if (inbound && (c->policy & POLICY_DISABLEARRIVALCHECK) == 0)
2021 {
2022 struct pfkey_proto_info proto_info[4];
2023 int i = 0;
2024
2025 if (st->st_ipcomp.present)
2026 {
2027 proto_info[i].proto = IPPROTO_COMP;
2028 proto_info[i].encapsulation = st->st_ipcomp.attrs.encapsulation;
2029 proto_info[i].reqid = c->spd.reqid + 2;
2030 i++;
2031 }
2032
2033 if (st->st_esp.present)
2034 {
2035 proto_info[i].proto = IPPROTO_ESP;
2036 proto_info[i].encapsulation = st->st_esp.attrs.encapsulation;
2037 proto_info[i].reqid = c->spd.reqid + 1;
2038 i++;
2039 }
2040
2041 if (st->st_ah.present)
2042 {
2043 proto_info[i].proto = IPPROTO_AH;
2044 proto_info[i].encapsulation = st->st_ah.attrs.encapsulation;
2045 proto_info[i].reqid = c->spd.reqid;
2046 i++;
2047 }
2048
2049 proto_info[i].proto = 0;
2050
2051 if (kernel_ops->inbound_eroute
2052 && encapsulation == ENCAPSULATION_MODE_TUNNEL)
2053 {
2054 proto_info[0].encapsulation = ENCAPSULATION_MODE_TUNNEL;
2055 for (i = 1; proto_info[i].proto; i++)
2056 {
2057 proto_info[i].encapsulation = ENCAPSULATION_MODE_TRANSPORT;
2058 }
2059 }
2060
2061 /* MCR - should be passed a spd_eroute structure here */
2062 (void) raw_eroute(&c->spd.that.host_addr, &c->spd.that.client
2063 , &c->spd.this.host_addr, &c->spd.this.client
2064 , inner_spi, proto, satype, c->spd.this.protocol
2065 , proto_info, 0
2066 , ERO_ADD_INBOUND, "add inbound");
2067 }
2068 }
2069
2070 /* If there are multiple SPIs, group them. */
2071
2072 if (kernel_ops->grp_sa && said_next > &said[1])
2073 {
2074 struct kernel_sa *s;
2075
2076 /* group SAs, two at a time, inner to outer (backwards in said[])
2077 * The grouping is by pairs. So if said[] contains ah esp ipip,
2078 * the grouping would be ipip:esp, esp:ah.
2079 */
2080 for (s = said; s < said_next-1; s++)
2081 {
2082 char
2083 text_said0[SATOT_BUF],
2084 text_said1[SATOT_BUF];
2085
2086 /* group s[1] and s[0], in that order */
2087
2088 set_text_said(text_said0, s[0].dst, s[0].spi, s[0].proto);
2089 set_text_said(text_said1, s[1].dst, s[1].spi, s[1].proto);
2090
2091 DBG(DBG_KLIPS, DBG_log("grouping %s and %s", text_said1, text_said0));
2092
2093 s[0].text_said = text_said0;
2094 s[1].text_said = text_said1;
2095
2096 if (!kernel_ops->grp_sa(s + 1, s))
2097 goto fail;
2098 }
2099 /* could update said, but it will not be used */
2100 }
2101
2102 return TRUE;
2103
2104 fail:
2105 {
2106 /* undo the done SPIs */
2107 while (said_next-- != said)
2108 (void) del_spi(said_next->spi, said_next->proto
2109 , &src.addr, said_next->dst);
2110 return FALSE;
2111 }
2112 }
2113
2114 /* teardown_ipsec_sa is a canibalized version of setup_ipsec_sa */
2115
2116 static bool teardown_half_ipsec_sa(struct state *st, bool inbound)
2117 {
2118 /* We need to delete AH, ESP, and IP in IP SPIs.
2119 * But if there is more than one, they have been grouped
2120 * so deleting any one will do. So we just delete the
2121 * first one found. It may or may not be the only one.
2122 */
2123 struct connection *c = st->st_connection;
2124 struct {
2125 unsigned proto;
2126 struct ipsec_proto_info *info;
2127 } protos[4];
2128 int i;
2129 bool result;
2130
2131 i = 0;
2132 if (kernel_ops->inbound_eroute && inbound
2133 && c->spd.eroute_owner == SOS_NOBODY)
2134 {
2135 (void) raw_eroute(&c->spd.that.host_addr, &c->spd.that.client
2136 , &c->spd.this.host_addr, &c->spd.this.client
2137 , 256, IPSEC_PROTO_ANY, SADB_SATYPE_UNSPEC, c->spd.this.protocol
2138 , null_proto_info, 0
2139 , ERO_DEL_INBOUND, "delete inbound");
2140 }
2141
2142 if (!kernel_ops->grp_sa)
2143 {
2144 if (st->st_ah.present)
2145 {
2146 protos[i].info = &st->st_ah;
2147 protos[i].proto = SA_AH;
2148 i++;
2149 }
2150
2151 if (st->st_esp.present)
2152 {
2153 protos[i].info = &st->st_esp;
2154 protos[i].proto = SA_ESP;
2155 i++;
2156 }
2157
2158 if (st->st_ipcomp.present)
2159 {
2160 protos[i].info = &st->st_ipcomp;
2161 protos[i].proto = SA_COMP;
2162 i++;
2163 }
2164 }
2165 else if (st->st_ah.present)
2166 {
2167 protos[i].info = &st->st_ah;
2168 protos[i].proto = SA_AH;
2169 i++;
2170 }
2171 else if (st->st_esp.present)
2172 {
2173 protos[i].info = &st->st_esp;
2174 protos[i].proto = SA_ESP;
2175 i++;
2176 }
2177 else
2178 {
2179 impossible(); /* neither AH nor ESP in outbound SA bundle! */
2180 }
2181 protos[i].proto = 0;
2182
2183 result = TRUE;
2184 for (i = 0; protos[i].proto; i++)
2185 {
2186 unsigned proto = protos[i].proto;
2187 ipsec_spi_t spi;
2188 const ip_address *src, *dst;
2189
2190 if (inbound)
2191 {
2192 spi = protos[i].info->our_spi;
2193 src = &c->spd.that.host_addr;
2194 dst = &c->spd.this.host_addr;
2195 }
2196 else
2197 {
2198 spi = protos[i].info->attrs.spi;
2199 src = &c->spd.this.host_addr;
2200 dst = &c->spd.that.host_addr;
2201 }
2202
2203 result &= del_spi(spi, proto, src, dst);
2204 }
2205 return result;
2206 }
2207
2208 /*
2209 * get information about a given sa
2210 */
2211 bool get_sa_info(struct state *st, bool inbound, u_int *bytes, time_t *use_time)
2212 {
2213 char text_said[SATOT_BUF];
2214 struct kernel_sa sa;
2215 struct connection *c = st->st_connection;
2216
2217 *use_time = UNDEFINED_TIME;
2218
2219 if (kernel_ops->get_sa == NULL || !st->st_esp.present)
2220 return FALSE;
2221
2222 memset(&sa, 0, sizeof(sa));
2223 sa.proto = SA_ESP;
2224
2225 if (inbound)
2226 {
2227 sa.src = &c->spd.that.host_addr;
2228 sa.dst = &c->spd.this.host_addr;
2229 sa.spi = st->st_esp.our_spi;
2230 }
2231 else
2232 {
2233 sa.src = &c->spd.this.host_addr;
2234 sa.dst = &c->spd.that.host_addr;
2235 sa.spi = st->st_esp.attrs.spi;
2236 }
2237 set_text_said(text_said, sa.dst, sa.spi, sa.proto);
2238
2239 sa.text_said = text_said;
2240
2241 DBG(DBG_KLIPS,
2242 DBG_log("get %s", text_said)
2243 )
2244 if (!kernel_ops->get_sa(&sa, bytes))
2245 return FALSE;
2246 DBG(DBG_KLIPS,
2247 DBG_log(" current: %d bytes", *bytes)
2248 )
2249
2250 if (st->st_serialno == c->spd.eroute_owner)
2251 {
2252 DBG(DBG_KLIPS,
2253 DBG_log("get %sbound policy with reqid %u"
2254 , inbound? "in":"out", (u_int)c->spd.reqid + 1)
2255 )
2256 sa.transport_proto = c->spd.this.protocol;
2257 sa.encapsulation = st->st_esp.attrs.encapsulation;
2258
2259 if (inbound)
2260 {
2261 sa.src_client = &c->spd.that.client;
2262 sa.dst_client = &c->spd.this.client;
2263 }
2264 else
2265 {
2266 sa.src_client = &c->spd.this.client;
2267 sa.dst_client = &c->spd.that.client;
2268 }
2269 if (!kernel_ops->get_policy(&sa, inbound, use_time))
2270 return FALSE;
2271 DBG(DBG_KLIPS,
2272 DBG_log(" use_time: %T", use_time, FALSE)
2273 )
2274 }
2275 return TRUE;
2276 }
2277
2278 const struct kernel_ops *kernel_ops;
2279
2280 #endif /* KLIPS */
2281
2282 void init_kernel(void)
2283 {
2284 #ifdef KLIPS
2285
2286 if (no_klips)
2287 {
2288 kernel_ops = &noklips_kernel_ops;
2289 return;
2290 }
2291
2292 init_pfkey();
2293
2294 kernel_ops = &klips_kernel_ops;
2295
2296 #if defined(linux) && defined(KERNEL26_SUPPORT)
2297 {
2298 bool linux_ipsec = 0;
2299 struct stat buf;
2300
2301 linux_ipsec = (stat("/proc/net/pfkey", &buf) == 0);
2302 if (linux_ipsec)
2303 {
2304 plog("Using Linux 2.6 IPsec interface code");
2305 kernel_ops = &linux_kernel_ops;
2306 }
2307 else
2308 {
2309 plog("Using KLIPS IPsec interface code");
2310 }
2311 }
2312 #endif
2313
2314 if (kernel_ops->init)
2315 {
2316 kernel_ops->init();
2317 }
2318
2319 /* register SA types that we can negotiate */
2320 can_do_IPcomp = FALSE; /* until we get a response from KLIPS */
2321 kernel_ops->pfkey_register();
2322
2323 if (!kernel_ops->policy_lifetime)
2324 {
2325 event_schedule(EVENT_SHUNT_SCAN, SHUNT_SCAN_INTERVAL, NULL);
2326 }
2327 #endif
2328 }
2329
2330 /* Note: install_inbound_ipsec_sa is only used by the Responder.
2331 * The Responder will subsequently use install_ipsec_sa for the outbound.
2332 * The Initiator uses install_ipsec_sa to install both at once.
2333 */
2334 bool install_inbound_ipsec_sa(struct state *st)
2335 {
2336 struct connection *const c = st->st_connection;
2337
2338 /* If our peer has a fixed-address client, check if we already
2339 * have a route for that client that conflicts. We will take this
2340 * as proof that that route and the connections using it are
2341 * obsolete and should be eliminated. Interestingly, this is
2342 * the only case in which we can tell that a connection is obsolete.
2343 */
2344 passert(c->kind == CK_PERMANENT || c->kind == CK_INSTANCE);
2345 if (c->spd.that.has_client)
2346 {
2347 for (;;)
2348 {
2349 struct spd_route *esr;
2350 struct connection *o = route_owner(c, &esr, NULL, NULL);
2351
2352 if (o == NULL)
2353 break; /* nobody has a route */
2354
2355 /* note: we ignore the client addresses at this end */
2356 if (sameaddr(&o->spd.that.host_addr, &c->spd.that.host_addr)
2357 && o->interface == c->interface)
2358 break; /* existing route is compatible */
2359
2360 if (o->kind == CK_TEMPLATE && streq(o->name, c->name))
2361 break; /* ??? is this good enough?? */
2362
2363 loglog(RC_LOG_SERIOUS, "route to peer's client conflicts with \"%s\" %s; releasing old connection to free the route"
2364 , o->name, ip_str(&o->spd.that.host_addr));
2365 release_connection(o, FALSE);
2366 }
2367 }
2368
2369 DBG(DBG_CONTROL, DBG_log("install_inbound_ipsec_sa() checking if we can route"));
2370 /* check that we will be able to route and eroute */
2371 switch (could_route(c))
2372 {
2373 case route_easy:
2374 case route_nearconflict:
2375 break;
2376
2377 default:
2378 return FALSE;
2379 }
2380
2381 #ifdef KLIPS
2382 /* (attempt to) actually set up the SAs */
2383 return setup_half_ipsec_sa(st, TRUE);
2384 #else /* !KLIPS */
2385 DBG(DBG_CONTROL, DBG_log("install_inbound_ipsec_sa()"));
2386 return TRUE;
2387 #endif /* !KLIPS */
2388 }
2389
2390 /* Install a route and then a prospective shunt eroute or an SA group eroute.
2391 * Assumption: could_route gave a go-ahead.
2392 * Any SA Group must have already been created.
2393 * On failure, steps will be unwound.
2394 */
2395 bool route_and_eroute(struct connection *c USED_BY_KLIPS,
2396 struct spd_route *sr USED_BY_KLIPS,
2397 struct state *st USED_BY_KLIPS)
2398 {
2399 #ifdef KLIPS
2400 struct spd_route *esr;
2401 struct spd_route *rosr;
2402 struct connection *ero /* who, if anyone, owns our eroute? */
2403 , *ro = route_owner(c, &rosr, &ero, &esr);
2404 bool eroute_installed = FALSE
2405 , firewall_notified = FALSE
2406 , route_installed = FALSE;
2407
2408 struct connection *ero_top;
2409 struct bare_shunt **bspp;
2410
2411 DBG(DBG_CONTROLMORE,
2412 DBG_log("route_and_eroute with c: %s (next: %s) ero:%s esr:{%p} ro:%s rosr:{%p} and state: %lu"
2413 , c->name
2414 , (c->policy_next ? c->policy_next->name : "none")
2415 , ero ? ero->name : "null"
2416 , esr
2417 , ro ? ro->name : "null"
2418 , rosr
2419 , st ? st->st_serialno : 0));
2420
2421 /* look along the chain of policies for one with the same name */
2422 ero_top = ero;
2423
2424 #if 0
2425 /* XXX - mcr this made sense before, and likely will make sense
2426 * again, so I'l leaving this to remind me what is up */
2427 if (ero!= NULL && ero->routing == RT_UNROUTED_KEYED)
2428 ero = NULL;
2429
2430 for (ero2 = ero; ero2 != NULL; ero2 = ero->policy_next)
2431 if ((ero2->kind == CK_TEMPLATE || ero2->kind==CK_SECONDARY)
2432 && streq(ero2->name, c->name))
2433 break;
2434 #endif
2435
2436 bspp = (ero == NULL)
2437 ? bare_shunt_ptr(&sr->this.client, &sr->that.client, sr->this.protocol)
2438 : NULL;
2439
2440 /* install the eroute */
2441
2442 passert(bspp == NULL || ero == NULL); /* only one non-NULL */
2443
2444 if (bspp != NULL || ero != NULL)
2445 {
2446 /* We're replacing an eroute */
2447
2448 /* if no state provided, then install a shunt for later */
2449 if (st == NULL)
2450 eroute_installed = shunt_eroute(c, sr, RT_ROUTED_PROSPECTIVE
2451 , ERO_REPLACE, "replace");
2452 else
2453 eroute_installed = sag_eroute(st, sr, ERO_REPLACE, "replace");
2454
2455 #if 0
2456 /* XXX - MCR. I previously felt that this was a bogus check */
2457 if (ero != NULL && ero != c && esr != sr)
2458 {
2459 /* By elimination, we must be eclipsing ero. Check. */
2460 passert(ero->kind == CK_TEMPLATE && streq(ero->name, c->name));
2461 passert(LHAS(LELEM(RT_ROUTED_PROSPECTIVE) | LELEM(RT_ROUTED_ECLIPSED)
2462 , esr->routing));
2463 passert(samesubnet(&esr->this.client, &sr->this.client)
2464 && samesubnet(&esr->that.client, &sr->that.client));
2465 }
2466 #endif
2467 /* remember to free bspp iff we make it out of here alive */
2468 }
2469 else
2470 {
2471 /* we're adding an eroute */
2472
2473 /* if no state provided, then install a shunt for later */
2474 if (st == NULL)
2475 eroute_installed = shunt_eroute(c, sr, RT_ROUTED_PROSPECTIVE
2476 , ERO_ADD, "add");
2477 else
2478 eroute_installed = sag_eroute(st, sr, ERO_ADD, "add");
2479 }
2480
2481 /* notify the firewall of a new tunnel */
2482
2483 if (eroute_installed)
2484 {
2485 /* do we have to notify the firewall? Yes, if we are installing
2486 * a tunnel eroute and the firewall wasn't notified
2487 * for a previous tunnel with the same clients. Any Previous
2488 * tunnel would have to be for our connection, so the actual
2489 * test is simple.
2490 */
2491 firewall_notified = st == NULL /* not a tunnel eroute */
2492 || sr->eroute_owner != SOS_NOBODY /* already notified */
2493 || do_command(c, sr, "up"); /* go ahead and notify */
2494 }
2495
2496 /* install the route */
2497
2498 DBG(DBG_CONTROL,
2499 DBG_log("route_and_eroute: firewall_notified: %s"
2500 , firewall_notified ? "true" : "false"));
2501 if (!firewall_notified)
2502 {
2503 /* we're in trouble -- don't do routing */
2504 }
2505 else if (ro == NULL)
2506 {
2507 /* a new route: no deletion required, but preparation is */
2508 (void) do_command(c, sr, "prepare"); /* just in case; ignore failure */
2509 route_installed = do_command(c, sr, "route");
2510 }
2511 else if (routed(sr->routing)
2512 || routes_agree(ro, c))
2513 {
2514 route_installed = TRUE; /* nothing to be done */
2515 }
2516 else
2517 {
2518 /* Some other connection must own the route
2519 * and the route must disagree. But since could_route
2520 * must have allowed our stealing it, we'll do so.
2521 *
2522 * A feature of LINUX allows us to install the new route
2523 * before deleting the old if the nexthops differ.
2524 * This reduces the "window of vulnerability" when packets
2525 * might flow in the clear.
2526 */
2527 if (sameaddr(&sr->this.host_nexthop, &esr->this.host_nexthop))
2528 {
2529 (void) do_command(ro, sr, "unroute");
2530 route_installed = do_command(c, sr, "route");
2531 }
2532 else
2533 {
2534 route_installed = do_command(c, sr, "route");
2535 (void) do_command(ro, sr, "unroute");
2536 }
2537
2538 /* record unrouting */
2539 if (route_installed)
2540 {
2541 do {
2542 passert(!erouted(rosr->routing));
2543 rosr->routing = RT_UNROUTED;
2544
2545 /* no need to keep old value */
2546 ro = route_owner(c, &rosr, NULL, NULL);
2547 } while (ro != NULL);
2548 }
2549 }
2550
2551 /* all done -- clean up */
2552 if (route_installed)
2553 {
2554 /* Success! */
2555
2556 if (bspp != NULL)
2557 {
2558 free_bare_shunt(bspp);
2559 }
2560 else if (ero != NULL && ero != c)
2561 {
2562 /* check if ero is an ancestor of c. */
2563 struct connection *ero2;
2564
2565 for (ero2 = c; ero2 != NULL && ero2 != c; ero2 = ero2->policy_next)
2566 ;
2567
2568 if (ero2 == NULL)
2569 {
2570 /* By elimination, we must be eclipsing ero. Checked above. */
2571 if (ero->spd.routing != RT_ROUTED_ECLIPSED)
2572 {
2573 ero->spd.routing = RT_ROUTED_ECLIPSED;
2574 eclipse_count++;
2575 }
2576 }
2577 }
2578
2579 if (st == NULL)
2580 {
2581 passert(sr->eroute_owner == SOS_NOBODY);
2582 sr->routing = RT_ROUTED_PROSPECTIVE;
2583 }
2584 else
2585 {
2586 char cib[CONN_INST_BUF];
2587 sr->routing = RT_ROUTED_TUNNEL;
2588
2589 DBG(DBG_CONTROL,
2590 DBG_log("route_and_eroute: instance \"%s\"%s, setting eroute_owner {spd=%p,sr=%p} to #%ld (was #%ld) (newest_ipsec_sa=#%ld)"
2591 , st->st_connection->name
2592 , (fmt_conn_instance(st->st_connection, cib), cib)
2593 , &st->st_connection->spd, sr
2594 , st->st_serialno
2595 , sr->eroute_owner
2596 , st->st_connection->newest_ipsec_sa));
2597 sr->eroute_owner = st->st_serialno;
2598 }
2599
2600 return TRUE;
2601 }
2602 else
2603 {
2604 /* Failure! Unwind our work. */
2605 if (firewall_notified && sr->eroute_owner == SOS_NOBODY)
2606 (void) do_command(c, sr, "down");
2607
2608 if (eroute_installed)
2609 {
2610 /* Restore original eroute, if we can.
2611 * Since there is nothing much to be done if the restoration
2612 * fails, ignore success or failure.
2613 */
2614 if (bspp != NULL)
2615 {
2616 /* Restore old bare_shunt.
2617 * I don't think that this case is very likely.
2618 * Normally a bare shunt would have been assigned
2619 * to a connection before we've gotten this far.
2620 */
2621 struct bare_shunt *bs = *bspp;
2622
2623 (void) raw_eroute(&bs->said.dst /* should be useless */
2624 , &bs->ours
2625 , &bs->said.dst /* should be useless */
2626 , &bs->his
2627 , bs->said.spi /* network order */
2628 , SA_INT
2629 , SADB_X_SATYPE_INT
2630 , 0
2631 , null_proto_info
2632 , SHUNT_PATIENCE
2633 , ERO_REPLACE, "restore");
2634 }
2635 else if (ero != NULL)
2636 {
2637 /* restore ero's former glory */
2638 if (esr->eroute_owner == SOS_NOBODY)
2639 {
2640 /* note: normal or eclipse case */
2641 (void) shunt_eroute(ero, esr
2642 , esr->routing, ERO_REPLACE, "restore");
2643 }
2644 else
2645 {
2646 /* Try to find state that owned eroute.
2647 * Don't do anything if it cannot be found.
2648 * This case isn't likely since we don't run
2649 * the updown script when replacing a SA group
2650 * with its successor (for the same conn).
2651 */
2652 struct state *ost = state_with_serialno(esr->eroute_owner);
2653
2654 if (ost != NULL)
2655 (void) sag_eroute(ost, esr, ERO_REPLACE, "restore");
2656 }
2657 }
2658 else
2659 {
2660 /* there was no previous eroute: delete whatever we installed */
2661 if (st == NULL)
2662 (void) shunt_eroute(c, sr
2663 , sr->routing, ERO_DELETE, "delete");
2664 else
2665 (void) sag_eroute(st, sr
2666 , ERO_DELETE, "delete");
2667 }
2668 }
2669
2670 return FALSE;
2671 }
2672 #else /* !KLIPS */
2673 return TRUE;
2674 #endif /* !KLIPS */
2675 }
2676
2677 bool install_ipsec_sa(struct state *st, bool inbound_also USED_BY_KLIPS)
2678 {
2679 #ifdef KLIPS
2680 struct spd_route *sr;
2681
2682 DBG(DBG_CONTROL, DBG_log("install_ipsec_sa() for #%ld: %s"
2683 , st->st_serialno
2684 , inbound_also?
2685 "inbound and outbound" : "outbound only"));
2686
2687 switch (could_route(st->st_connection))
2688 {
2689 case route_easy:
2690 case route_nearconflict:
2691 break;
2692
2693 default:
2694 return FALSE;
2695 }
2696
2697 /* (attempt to) actually set up the SA group */
2698 if ((inbound_also && !setup_half_ipsec_sa(st, TRUE))
2699 || !setup_half_ipsec_sa(st, FALSE))
2700 return FALSE;
2701
2702 for (sr = &st->st_connection->spd; sr != NULL; sr = sr->next)
2703 {
2704 DBG(DBG_CONTROL, DBG_log("sr for #%ld: %s"
2705 , st->st_serialno
2706 , enum_name(&routing_story, sr->routing)));
2707
2708 /*
2709 * if the eroute owner is not us, then make it us.
2710 * See test co-terminal-02, pluto-rekey-01, pluto-unit-02/oppo-twice
2711 */
2712 pexpect(sr->eroute_owner == SOS_NOBODY
2713 || sr->routing >= RT_ROUTED_TUNNEL);
2714
2715 if (sr->eroute_owner != st->st_serialno
2716 && sr->routing != RT_UNROUTED_KEYED)
2717 {
2718 if (!route_and_eroute(st->st_connection, sr, st))
2719 {
2720 delete_ipsec_sa(st, FALSE);
2721 /* XXX go and unroute any SRs that were successfully
2722 * routed already.
2723 */
2724 return FALSE;
2725 }
2726 }
2727 }
2728 #else /* !KLIPS */
2729 DBG(DBG_CONTROL, DBG_log("install_ipsec_sa() %s"
2730 , inbound_also? "inbound and oubound" : "outbound only"));
2731
2732 switch (could_route(st->st_connection))
2733 {
2734 case route_easy:
2735 case route_nearconflict:
2736 break;
2737
2738 default:
2739 return FALSE;
2740 }
2741
2742
2743 #endif /* !KLIPS */
2744
2745 return TRUE;
2746 }
2747
2748 /* delete an IPSEC SA.
2749 * we may not succeed, but we bull ahead anyway because
2750 * we cannot do anything better by recognizing failure
2751 */
2752 void delete_ipsec_sa(struct state *st USED_BY_KLIPS,
2753 bool inbound_only USED_BY_KLIPS)
2754 {
2755 #ifdef KLIPS
2756 if (!inbound_only)
2757 {
2758 /* If the state is the eroute owner, we must adjust
2759 * the routing for the connection.
2760 */
2761 struct connection *c = st->st_connection;
2762 struct spd_route *sr;
2763
2764 passert(st->st_connection);
2765
2766 for (sr = &c->spd; sr; sr = sr->next)
2767 {
2768 if (sr->eroute_owner == st->st_serialno
2769 && sr->routing == RT_ROUTED_TUNNEL)
2770 {
2771 sr->eroute_owner = SOS_NOBODY;
2772
2773 /* Routing should become RT_ROUTED_FAILURE,
2774 * but if POLICY_FAIL_NONE, then we just go
2775 * right back to RT_ROUTED_PROSPECTIVE as if no
2776 * failure happened.
2777 */
2778 sr->routing = (c->policy & POLICY_FAIL_MASK) == POLICY_FAIL_NONE
2779 ? RT_ROUTED_PROSPECTIVE : RT_ROUTED_FAILURE;
2780
2781 (void) do_command(c, sr, "down");
2782 if ((c->policy & POLICY_DONT_REKEY)
2783 && c->kind == CK_INSTANCE)
2784 {
2785 /* in this special case, even if the connection
2786 * is still alive (due to an ISAKMP SA),
2787 * we get rid of routing.
2788 * Even though there is still an eroute, the c->routing
2789 * setting will convince unroute_connection to delete it.
2790 * unroute_connection would be upset if c->routing == RT_ROUTED_TUNNEL
2791 */
2792 unroute_connection(c);
2793 }
2794 else
2795 {
2796 (void) shunt_eroute(c, sr, sr->routing, ERO_REPLACE, "replace with shunt");
2797 }
2798 }
2799 }
2800 (void) teardown_half_ipsec_sa(st, FALSE);
2801 }
2802 (void) teardown_half_ipsec_sa(st, TRUE);
2803 #else /* !KLIPS */
2804 DBG(DBG_CONTROL, DBG_log("if I knew how, I'd eroute() and teardown_ipsec_sa()"));
2805 #endif /* !KLIPS */
2806 }
2807
2808 #ifdef KLIPS
2809 static bool update_nat_t_ipsec_esp_sa (struct state *st, bool inbound)
2810 {
2811 struct connection *c = st->st_connection;
2812 char text_said[SATOT_BUF];
2813 struct kernel_sa sa;
2814 ip_address
2815 src = inbound? c->spd.that.host_addr : c->spd.this.host_addr,
2816 dst = inbound? c->spd.this.host_addr : c->spd.that.host_addr;
2817
2818 ipsec_spi_t esp_spi = inbound? st->st_esp.our_spi : st->st_esp.attrs.spi;
2819
2820 u_int16_t
2821 natt_sport = inbound? c->spd.that.host_port : c->spd.this.host_port,
2822 natt_dport = inbound? c->spd.this.host_port : c->spd.that.host_port;
2823
2824 set_text_said(text_said, &dst, esp_spi, SA_ESP);
2825
2826 memset(&sa, 0, sizeof(sa));
2827 sa.spi = esp_spi;
2828 sa.src = &src;
2829 sa.dst = &dst;
2830 sa.text_said = text_said;
2831 sa.authalg = alg_info_esp_aa2sadb(st->st_esp.attrs.auth);
2832 sa.natt_sport = natt_sport;
2833 sa.natt_dport = natt_dport;
2834 sa.transid = st->st_esp.attrs.transid;
2835
2836 return kernel_ops->add_sa(&sa, TRUE);
2837 }
2838 #endif
2839
2840 bool update_ipsec_sa (struct state *st USED_BY_KLIPS)
2841 {
2842 #ifdef KLIPS
2843 if (IS_IPSEC_SA_ESTABLISHED(st->st_state))
2844 {
2845 if (st->st_esp.present && (
2846 (!update_nat_t_ipsec_esp_sa (st, TRUE)) ||
2847 (!update_nat_t_ipsec_esp_sa (st, FALSE))))
2848 {
2849 return FALSE;
2850 }
2851 }
2852 else if (IS_ONLY_INBOUND_IPSEC_SA_ESTABLISHED(st->st_state))
2853 {
2854 if (st->st_esp.present && !update_nat_t_ipsec_esp_sa (st, FALSE))
2855 {
2856 return FALSE;
2857 }
2858 }
2859 else
2860 {
2861 DBG_log("assert failed at %s:%d st_state=%d", __FILE__, __LINE__, st->st_state);
2862 return FALSE;
2863 }
2864 return TRUE;
2865 #else /* !KLIPS */
2866 DBG(DBG_CONTROL, DBG_log("if I knew how, I'd update_ipsec_sa()"));
2867 return TRUE;
2868 #endif /* !KLIPS */
2869 }
2870
2871 /* Check if there was traffic on given SA during the last idle_max
2872 * seconds. If TRUE, the SA was idle and DPD exchange should be performed.
2873 * If FALSE, DPD is not necessary. We also return TRUE for errors, as they
2874 * could mean that the SA is broken and needs to be replace anyway.
2875 */
2876 bool was_eroute_idle(struct state *st, time_t idle_max, time_t *idle_time)
2877 {
2878 static const char procname[] = "/proc/net/ipsec_spi";
2879 FILE *f;
2880 char buf[1024];
2881 u_int bytes;
2882 int ret = TRUE;
2883
2884 passert(st != NULL);
2885
2886 f = fopen(procname, "r");
2887 if (f == NULL)
2888 {
2889 /* Can't open the file, perhaps were are on 26sec? */
2890 time_t use_time;
2891
2892 if (get_sa_info(st, TRUE, &bytes, &use_time)
2893 && use_time != UNDEFINED_TIME)
2894 {
2895 *idle_time = time(NULL) - use_time;
2896 ret = *idle_time >= idle_max;
2897 }
2898 }
2899 else
2900 {
2901 while (f != NULL)
2902 {
2903 char *line;
2904 char text_said[SATOT_BUF];
2905 u_int8_t proto = 0;
2906 ip_address dst;
2907 ip_said said;
2908 ipsec_spi_t spi = 0;
2909 static const char idle[] = "idle=";
2910
2911 dst = st->st_connection->spd.this.host_addr; /* inbound SA */
2912 if (st->st_ah.present)
2913 {
2914 proto = SA_AH;
2915 spi = st->st_ah.our_spi;
2916 }
2917 if (st->st_esp.present)
2918 {
2919 proto = SA_ESP;
2920 spi = st->st_esp.our_spi;
2921 }
2922
2923 if (proto == 0 && spi == 0)
2924 {
2925 ret = TRUE;
2926 break;
2927 }
2928
2929 initsaid(&dst, spi, proto, &said);
2930 satot(&said, 'x', text_said, SATOT_BUF);
2931
2932 line = fgets(buf, sizeof(buf), f);
2933 if (line == NULL)
2934 {
2935 /* Reached end of list */
2936 ret = TRUE;
2937 break;
2938 }
2939
2940 if (strneq(line, text_said, strlen(text_said)))
2941 {
2942 /* we found a match, now try to find idle= */
2943 char *p = strstr(line, idle);
2944
2945 if (p == NULL)
2946 {
2947 /* SAs which haven't been used yet don't have it */
2948 ret = TRUE; /* it didn't have traffic */
2949 break;
2950 }
2951 p += sizeof(idle)-1;
2952 if (*p == '\0')
2953 {
2954 ret = TRUE; /* be paranoid */
2955 break;
2956 }
2957 if (sscanf(p, "%d", (int *) idle_time) <= 0)
2958 {
2959 ret = TRUE;
2960 break;
2961 }
2962 if (*idle_time >= idle_max)
2963 {
2964 ret = TRUE;
2965 break;
2966 }
2967 else
2968 {
2969 ret = FALSE;
2970 break;
2971 }
2972 }
2973 }
2974 fclose(f);
2975 }
2976 return ret;
2977 }