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