0ae3314248c7eec49432a86e5b79c8cfff67fe7b
[strongswan.git] / src / libcharon / plugins / kernel_pfkey / kernel_pfkey_ipsec.c
1 /*
2 * Copyright (C) 2008-2018 Tobias Brunner
3 * Copyright (C) 2008 Andreas Steffen
4 * HSR 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 * Copyright (C) 2014 Nanoteq Pty Ltd
18 *
19 * Permission is hereby granted, free of charge, to any person obtaining a copy
20 * of this software and associated documentation files (the "Software"), to deal
21 * in the Software without restriction, including without limitation the rights
22 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
23 * copies of the Software, and to permit persons to whom the Software is
24 * furnished to do so, subject to the following conditions:
25 *
26 * The above copyright notice and this permission notice shall be included in
27 * all copies or substantial portions of the Software.
28 *
29 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
31 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
32 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
33 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
34 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
35 * THE SOFTWARE.
36 */
37
38 #include <stdint.h>
39 #include <sys/types.h>
40 #include <sys/socket.h>
41
42 #ifdef __FreeBSD__
43 #include <limits.h> /* for LONG_MAX */
44 #endif
45
46 #ifdef HAVE_NET_PFKEYV2_H
47 #include <net/pfkeyv2.h>
48 #else
49 #include <linux/pfkeyv2.h>
50 #endif
51
52 #ifdef SADB_X_EXT_NAT_T_TYPE
53 #define HAVE_NATT
54 #endif
55
56 #ifdef HAVE_NETIPSEC_IPSEC_H
57 #include <netipsec/ipsec.h>
58 #elif defined(HAVE_NETINET6_IPSEC_H)
59 #include <netinet6/ipsec.h>
60 #else
61 #include <linux/ipsec.h>
62 #endif
63
64 #ifdef HAVE_NATT
65 #ifdef HAVE_LINUX_UDP_H
66 #include <linux/udp.h>
67 #else
68 #include <netinet/udp.h>
69 #endif /*HAVE_LINUX_UDP_H*/
70 #endif /*HAVE_NATT*/
71
72 #include <unistd.h>
73 #include <time.h>
74 #include <errno.h>
75 #ifdef __APPLE__
76 #include <sys/sysctl.h>
77 #endif
78
79 #include "kernel_pfkey_ipsec.h"
80
81 #include <daemon.h>
82 #include <utils/debug.h>
83 #include <networking/host.h>
84 #include <collections/linked_list.h>
85 #include <collections/hashtable.h>
86 #include <threading/mutex.h>
87
88 /** non linux specific */
89 #ifndef IPPROTO_COMP
90 #ifdef IPPROTO_IPCOMP
91 #define IPPROTO_COMP IPPROTO_IPCOMP
92 #endif
93 #endif
94
95 #ifndef SADB_X_AALG_SHA2_256HMAC
96 #define SADB_X_AALG_SHA2_256HMAC SADB_X_AALG_SHA2_256
97 #define SADB_X_AALG_SHA2_384HMAC SADB_X_AALG_SHA2_384
98 #define SADB_X_AALG_SHA2_512HMAC SADB_X_AALG_SHA2_512
99 #endif
100
101 #ifndef SADB_X_EALG_AESCBC
102 #define SADB_X_EALG_AESCBC SADB_X_EALG_AES
103 #endif
104
105 #ifndef SADB_X_EALG_CASTCBC
106 #define SADB_X_EALG_CASTCBC SADB_X_EALG_CAST128CBC
107 #endif
108
109 #if !defined(SADB_X_EALG_AES_GCM_ICV8) && defined(SADB_X_EALG_AESGCM8)
110 #define SADB_X_EALG_AES_GCM_ICV8 SADB_X_EALG_AESGCM8
111 #define SADB_X_EALG_AES_GCM_ICV12 SADB_X_EALG_AESGCM12
112 #define SADB_X_EALG_AES_GCM_ICV16 SADB_X_EALG_AESGCM16
113 #endif
114
115 #ifndef SOL_IP
116 #define SOL_IP IPPROTO_IP
117 #define SOL_IPV6 IPPROTO_IPV6
118 #endif
119
120 /** from linux/in.h */
121 #ifndef IP_IPSEC_POLICY
122 #define IP_IPSEC_POLICY 16
123 #endif
124
125 /** missing on uclibc */
126 #ifndef IPV6_IPSEC_POLICY
127 #define IPV6_IPSEC_POLICY 34
128 #endif
129
130 /* from linux/udp.h */
131 #ifndef UDP_ENCAP
132 #define UDP_ENCAP 100
133 #endif
134
135 #ifndef UDP_ENCAP_ESPINUDP
136 #define UDP_ENCAP_ESPINUDP 2
137 #endif
138
139 /* this is not defined on some platforms */
140 #ifndef SOL_UDP
141 #define SOL_UDP IPPROTO_UDP
142 #endif
143
144 /** Base priority for installed policies */
145 #define PRIO_BASE 200000
146
147 #ifdef __APPLE__
148 /** from xnu/bsd/net/pfkeyv2.h */
149 #define SADB_X_EXT_NATT 0x002
150 struct sadb_sa_2 {
151 struct sadb_sa sa;
152 uint16_t sadb_sa_natt_port;
153 uint16_t sadb_reserved0;
154 uint32_t sadb_reserved1;
155 };
156 #endif
157
158 /** buffer size for PF_KEY messages */
159 #define PFKEY_BUFFER_SIZE 4096
160
161 /** PF_KEY messages are 64 bit aligned */
162 #define PFKEY_ALIGNMENT 8
163 /** aligns len to 64 bits */
164 #define PFKEY_ALIGN(len) (((len) + PFKEY_ALIGNMENT - 1) & ~(PFKEY_ALIGNMENT - 1))
165 /** calculates the properly padded length in 64 bit chunks */
166 #define PFKEY_LEN(len) ((PFKEY_ALIGN(len) / PFKEY_ALIGNMENT))
167 /** calculates user mode length i.e. in bytes */
168 #define PFKEY_USER_LEN(len) ((len) * PFKEY_ALIGNMENT)
169
170 /** given a PF_KEY message header and an extension this updates the length in the header */
171 #define PFKEY_EXT_ADD(msg, ext) ((msg)->sadb_msg_len += ((struct sadb_ext*)ext)->sadb_ext_len)
172 /** given a PF_KEY message header this returns a pointer to the next extension */
173 #define PFKEY_EXT_ADD_NEXT(msg) ((struct sadb_ext*)(((char*)(msg)) + PFKEY_USER_LEN((msg)->sadb_msg_len)))
174 /** copy an extension and append it to a PF_KEY message */
175 #define PFKEY_EXT_COPY(msg, ext) (PFKEY_EXT_ADD(msg, memcpy(PFKEY_EXT_ADD_NEXT(msg), ext, PFKEY_USER_LEN(((struct sadb_ext*)ext)->sadb_ext_len))))
176 /** given a PF_KEY extension this returns a pointer to the next extension */
177 #define PFKEY_EXT_NEXT(ext) ((struct sadb_ext*)(((char*)(ext)) + PFKEY_USER_LEN(((struct sadb_ext*)ext)->sadb_ext_len)))
178 /** given a PF_KEY extension this returns a pointer to the next extension also updates len (len in 64 bit words) */
179 #define PFKEY_EXT_NEXT_LEN(ext,len) ((len) -= (ext)->sadb_ext_len, PFKEY_EXT_NEXT(ext))
180 /** true if ext has a valid length and len is large enough to contain ext (assuming len in 64 bit words) */
181 #define PFKEY_EXT_OK(ext,len) ((len) >= PFKEY_LEN(sizeof(struct sadb_ext)) && \
182 (ext)->sadb_ext_len >= PFKEY_LEN(sizeof(struct sadb_ext)) && \
183 (ext)->sadb_ext_len <= (len))
184
185 typedef struct private_kernel_pfkey_ipsec_t private_kernel_pfkey_ipsec_t;
186
187 /**
188 * Private variables and functions of kernel_pfkey class.
189 */
190 struct private_kernel_pfkey_ipsec_t
191 {
192 /**
193 * Public part of the kernel_pfkey_t object.
194 */
195 kernel_pfkey_ipsec_t public;
196
197 /**
198 * mutex to lock access to various lists
199 */
200 mutex_t *mutex;
201
202 /**
203 * List of installed policies (policy_entry_t)
204 */
205 linked_list_t *policies;
206
207 /**
208 * List of exclude routes (exclude_route_t)
209 */
210 linked_list_t *excludes;
211
212 /**
213 * Hash table of IPsec SAs using policies (ipsec_sa_t)
214 */
215 hashtable_t *sas;
216
217 /**
218 * whether to install routes along policies
219 */
220 bool install_routes;
221
222 /**
223 * whether to install the route via internal interface
224 */
225 bool route_via_internal;
226
227 /**
228 * mutex to lock access to the PF_KEY socket
229 */
230 mutex_t *mutex_pfkey;
231
232 /**
233 * PF_KEY socket to communicate with the kernel
234 */
235 int socket;
236
237 /**
238 * PF_KEY socket to receive acquire and expire events
239 */
240 int socket_events;
241
242 /**
243 * sequence number for messages sent to the kernel
244 */
245 int seq;
246 };
247
248 typedef struct exclude_route_t exclude_route_t;
249
250 /**
251 * Exclude route definition
252 */
253 struct exclude_route_t {
254 /** destination address of exclude */
255 host_t *dst;
256 /** source address for route */
257 host_t *src;
258 /** nexthop exclude has been installed */
259 host_t *gtw;
260 /** references to this route */
261 int refs;
262 };
263
264 /**
265 * clean up a route exclude entry
266 */
267 static void exclude_route_destroy(exclude_route_t *this)
268 {
269 this->dst->destroy(this->dst);
270 this->src->destroy(this->src);
271 this->gtw->destroy(this->gtw);
272 free(this);
273 }
274
275 typedef struct route_entry_t route_entry_t;
276
277 /**
278 * installed routing entry
279 */
280 struct route_entry_t {
281 /** name of the interface the route is bound to */
282 char *if_name;
283
284 /** source ip of the route */
285 host_t *src_ip;
286
287 /** gateway for this route */
288 host_t *gateway;
289
290 /** destination net */
291 chunk_t dst_net;
292
293 /** destination net prefixlen */
294 uint8_t prefixlen;
295
296 /** reference to exclude route, if any */
297 exclude_route_t *exclude;
298 };
299
300 /**
301 * destroy an route_entry_t object
302 */
303 static void route_entry_destroy(route_entry_t *this)
304 {
305 free(this->if_name);
306 DESTROY_IF(this->src_ip);
307 DESTROY_IF(this->gateway);
308 chunk_free(&this->dst_net);
309 free(this);
310 }
311
312 /**
313 * compare two route_entry_t objects
314 */
315 static bool route_entry_equals(route_entry_t *a, route_entry_t *b)
316 {
317 return a->if_name && b->if_name && streq(a->if_name, b->if_name) &&
318 a->src_ip->ip_equals(a->src_ip, b->src_ip) &&
319 a->gateway && b->gateway &&
320 a->gateway->ip_equals(a->gateway, b->gateway) &&
321 chunk_equals(a->dst_net, b->dst_net) && a->prefixlen == b->prefixlen;
322 }
323
324 typedef struct ipsec_sa_t ipsec_sa_t;
325
326 /**
327 * IPsec SA assigned to a policy.
328 */
329 struct ipsec_sa_t {
330 /** Source address of this SA */
331 host_t *src;
332
333 /** Destination address of this SA */
334 host_t *dst;
335
336 /** Description of this SA */
337 ipsec_sa_cfg_t cfg;
338
339 /** Reference count for this SA */
340 refcount_t refcount;
341 };
342
343 /**
344 * Hash function for ipsec_sa_t objects
345 */
346 static u_int ipsec_sa_hash(ipsec_sa_t *sa)
347 {
348 return chunk_hash_inc(sa->src->get_address(sa->src),
349 chunk_hash_inc(sa->dst->get_address(sa->dst),
350 chunk_hash(chunk_from_thing(sa->cfg))));
351 }
352
353 /**
354 * Equality function for ipsec_sa_t objects
355 */
356 static bool ipsec_sa_equals(ipsec_sa_t *sa, ipsec_sa_t *other_sa)
357 {
358 return sa->src->ip_equals(sa->src, other_sa->src) &&
359 sa->dst->ip_equals(sa->dst, other_sa->dst) &&
360 ipsec_sa_cfg_equals(&sa->cfg, &other_sa->cfg);
361 }
362
363 /**
364 * Allocate or reference an IPsec SA object
365 */
366 static ipsec_sa_t *ipsec_sa_create(private_kernel_pfkey_ipsec_t *this,
367 host_t *src, host_t *dst,
368 ipsec_sa_cfg_t *cfg)
369 {
370 ipsec_sa_t *sa, *found;
371 INIT(sa,
372 .src = src,
373 .dst = dst,
374 .cfg = *cfg,
375 );
376 found = this->sas->get(this->sas, sa);
377 if (!found)
378 {
379 sa->src = src->clone(src);
380 sa->dst = dst->clone(dst);
381 this->sas->put(this->sas, sa, sa);
382 }
383 else
384 {
385 free(sa);
386 sa = found;
387 }
388 ref_get(&sa->refcount);
389 return sa;
390 }
391
392 /**
393 * Release and destroy an IPsec SA object
394 */
395 static void ipsec_sa_destroy(private_kernel_pfkey_ipsec_t *this,
396 ipsec_sa_t *sa)
397 {
398 if (ref_put(&sa->refcount))
399 {
400 this->sas->remove(this->sas, sa);
401 DESTROY_IF(sa->src);
402 DESTROY_IF(sa->dst);
403 free(sa);
404 }
405 }
406
407 typedef struct policy_sa_t policy_sa_t;
408 typedef struct policy_sa_out_t policy_sa_out_t;
409
410 /**
411 * Mapping between a policy and an IPsec SA.
412 */
413 struct policy_sa_t {
414 /** Priority assigned to the policy when installed with this SA */
415 uint32_t priority;
416
417 /** Base priority assigned to the policy when installed with this SA */
418 uint32_t auto_priority;
419
420 /** Type of the policy */
421 policy_type_t type;
422
423 /** Assigned SA */
424 ipsec_sa_t *sa;
425 };
426
427 /**
428 * For outbound policies we also cache the traffic selectors in order to install
429 * the route.
430 */
431 struct policy_sa_out_t {
432 /** Generic interface */
433 policy_sa_t generic;
434
435 /** Source traffic selector of this policy */
436 traffic_selector_t *src_ts;
437
438 /** Destination traffic selector of this policy */
439 traffic_selector_t *dst_ts;
440 };
441
442 /**
443 * Create a policy_sa(_in)_t object
444 */
445 static policy_sa_t *policy_sa_create(private_kernel_pfkey_ipsec_t *this,
446 policy_dir_t dir, policy_type_t type, host_t *src, host_t *dst,
447 traffic_selector_t *src_ts, traffic_selector_t *dst_ts, ipsec_sa_cfg_t *cfg)
448 {
449 policy_sa_t *policy;
450
451 if (dir == POLICY_OUT)
452 {
453 policy_sa_out_t *out;
454 INIT(out,
455 .src_ts = src_ts->clone(src_ts),
456 .dst_ts = dst_ts->clone(dst_ts),
457 );
458 policy = &out->generic;
459 }
460 else
461 {
462 INIT(policy, .priority = 0);
463 }
464 policy->type = type;
465 policy->sa = ipsec_sa_create(this, src, dst, cfg);
466 return policy;
467 }
468
469 /**
470 * Destroy a policy_sa(_in)_t object
471 */
472 static void policy_sa_destroy(policy_sa_t *policy, policy_dir_t dir,
473 private_kernel_pfkey_ipsec_t *this)
474 {
475 if (dir == POLICY_OUT)
476 {
477 policy_sa_out_t *out = (policy_sa_out_t*)policy;
478 out->src_ts->destroy(out->src_ts);
479 out->dst_ts->destroy(out->dst_ts);
480 }
481 ipsec_sa_destroy(this, policy->sa);
482 free(policy);
483 }
484
485 CALLBACK(policy_sa_destroy_cb, void,
486 policy_sa_t *policy, va_list args)
487 {
488 private_kernel_pfkey_ipsec_t *this;
489 policy_dir_t dir;
490
491 VA_ARGS_VGET(args, dir, this);
492 policy_sa_destroy(policy, dir, this);
493 }
494
495 typedef struct policy_entry_t policy_entry_t;
496
497 /**
498 * installed kernel policy.
499 */
500 struct policy_entry_t {
501 /** Index assigned by the kernel */
502 uint32_t index;
503
504 /** Direction of this policy: in, out, forward */
505 uint8_t direction;
506
507 /** Parameters of installed policy */
508 struct {
509 /** Subnet and port */
510 host_t *net;
511 /** Subnet mask */
512 uint8_t mask;
513 /** Protocol */
514 uint8_t proto;
515 } src, dst;
516
517 /** Associated route installed for this policy */
518 route_entry_t *route;
519
520 /** List of SAs this policy is used by, ordered by priority */
521 linked_list_t *used_by;
522 };
523
524 /**
525 * Create a policy_entry_t object
526 */
527 static policy_entry_t *create_policy_entry(traffic_selector_t *src_ts,
528 traffic_selector_t *dst_ts,
529 policy_dir_t dir)
530 {
531 policy_entry_t *policy;
532 INIT(policy,
533 .direction = dir,
534 );
535 uint16_t port;
536 uint8_t proto;
537
538 src_ts->to_subnet(src_ts, &policy->src.net, &policy->src.mask);
539 dst_ts->to_subnet(dst_ts, &policy->dst.net, &policy->dst.mask);
540
541 /* src or dest proto may be "any" (0), use more restrictive one */
542 proto = max(src_ts->get_protocol(src_ts), dst_ts->get_protocol(dst_ts));
543 /* map the ports to ICMP type/code how the Linux kernel expects them, that
544 * is, type in src, code in dst */
545 if (proto == IPPROTO_ICMP || proto == IPPROTO_ICMPV6)
546 {
547 port = max(policy->src.net->get_port(policy->src.net),
548 policy->dst.net->get_port(policy->dst.net));
549 policy->src.net->set_port(policy->src.net,
550 traffic_selector_icmp_type(port));
551 policy->dst.net->set_port(policy->dst.net,
552 traffic_selector_icmp_code(port));
553 }
554 else if (!proto)
555 {
556 proto = IPSEC_PROTO_ANY;
557 }
558 policy->src.proto = policy->dst.proto = proto;
559
560 return policy;
561 }
562
563 /**
564 * Destroy a policy_entry_t object
565 */
566 static void policy_entry_destroy(policy_entry_t *policy,
567 private_kernel_pfkey_ipsec_t *this)
568 {
569 if (policy->route)
570 {
571 route_entry_destroy(policy->route);
572 }
573 if (policy->used_by)
574 {
575 policy->used_by->invoke_function(policy->used_by, policy_sa_destroy_cb,
576 policy->direction, this);
577 policy->used_by->destroy(policy->used_by);
578 }
579 DESTROY_IF(policy->src.net);
580 DESTROY_IF(policy->dst.net);
581 free(policy);
582 }
583
584 CALLBACK(policy_entry_destroy_cb, void,
585 policy_entry_t *policy, va_list args)
586 {
587 private_kernel_pfkey_ipsec_t *this;
588
589 VA_ARGS_VGET(args, this);
590 policy_entry_destroy(policy, this);
591 }
592
593 CALLBACK(policy_entry_equals, bool,
594 policy_entry_t *current, va_list args)
595 {
596 policy_entry_t *policy;
597
598 VA_ARGS_VGET(args, policy);
599 return current->direction == policy->direction &&
600 current->src.proto == policy->src.proto &&
601 current->dst.proto == policy->dst.proto &&
602 current->src.mask == policy->src.mask &&
603 current->dst.mask == policy->dst.mask &&
604 current->src.net->equals(current->src.net, policy->src.net) &&
605 current->dst.net->equals(current->dst.net, policy->dst.net);
606 }
607
608 CALLBACK(policy_entry_match_byindex, bool,
609 policy_entry_t *current, va_list args)
610 {
611 uint32_t index;
612
613 VA_ARGS_VGET(args, index);
614 return current->index == index;
615 }
616
617 /**
618 * Calculate the priority of a policy
619 *
620 * This is the same formula we use in the kernel-netlink interface, but some
621 * features are currently not or only partially supported by PF_KEY.
622 *
623 * bits 0-0: separate trap and regular policies (0..1) 1 bit
624 * bits 1-1: reserved for interface restriction (0..1) 1 bit
625 * bits 2-7: src + dst port mask bits (2 * 0..16) 6 bits
626 * bits 8-8: restriction to protocol (0..1) 1 bit
627 * bits 9-17: src + dst network mask bits (2 * 0..128) 9 bits
628 * 18 bits
629 *
630 * smallest value: 000000000 0 000000 0 0: 0, lowest priority = 100'000
631 * largest value : 100000000 1 100000 0 1: 131'457, highst priority = 68'543
632 */
633 static inline uint32_t get_priority(policy_entry_t *policy,
634 policy_priority_t prio)
635 {
636 uint32_t priority = PRIO_BASE;
637
638 switch (prio)
639 {
640 case POLICY_PRIORITY_FALLBACK:
641 priority += PRIO_BASE;
642 /* fall-through */
643 case POLICY_PRIORITY_ROUTED:
644 case POLICY_PRIORITY_DEFAULT:
645 priority += PRIO_BASE;
646 /* fall-through */
647 case POLICY_PRIORITY_PASS:
648 break;
649 }
650
651 /* calculate priority */
652 priority -= (policy->src.mask + policy->dst.mask) * 512;
653 priority -= policy->src.proto != IPSEC_PROTO_ANY ? 256 : 0;
654 priority -= policy->src.net->get_port(policy->src.net) ? 64 : 0;
655 priority -= policy->dst.net->get_port(policy->dst.net) ? 64 : 0;
656 priority -= (prio != POLICY_PRIORITY_ROUTED);
657 return priority;
658 }
659
660 typedef struct pfkey_msg_t pfkey_msg_t;
661
662 struct pfkey_msg_t
663 {
664 /**
665 * PF_KEY message base
666 */
667 struct sadb_msg *msg;
668
669 /**
670 * PF_KEY message extensions
671 */
672 union {
673 struct sadb_ext *ext[SADB_EXT_MAX + 1];
674 struct {
675 struct sadb_ext *reserved; /* SADB_EXT_RESERVED */
676 struct sadb_sa *sa; /* SADB_EXT_SA */
677 struct sadb_lifetime *lft_current; /* SADB_EXT_LIFETIME_CURRENT */
678 struct sadb_lifetime *lft_hard; /* SADB_EXT_LIFETIME_HARD */
679 struct sadb_lifetime *lft_soft; /* SADB_EXT_LIFETIME_SOFT */
680 struct sadb_address *src; /* SADB_EXT_ADDRESS_SRC */
681 struct sadb_address *dst; /* SADB_EXT_ADDRESS_DST */
682 struct sadb_address *proxy; /* SADB_EXT_ADDRESS_PROXY */
683 struct sadb_key *key_auth; /* SADB_EXT_KEY_AUTH */
684 struct sadb_key *key_encr; /* SADB_EXT_KEY_ENCRYPT */
685 struct sadb_ident *id_src; /* SADB_EXT_IDENTITY_SRC */
686 struct sadb_ident *id_dst; /* SADB_EXT_IDENTITY_DST */
687 struct sadb_sens *sensitivity; /* SADB_EXT_SENSITIVITY */
688 struct sadb_prop *proposal; /* SADB_EXT_PROPOSAL */
689 struct sadb_supported *supported_auth; /* SADB_EXT_SUPPORTED_AUTH */
690 struct sadb_supported *supported_encr; /* SADB_EXT_SUPPORTED_ENCRYPT */
691 struct sadb_spirange *spirange; /* SADB_EXT_SPIRANGE */
692 struct sadb_x_kmprivate *x_kmprivate; /* SADB_X_EXT_KMPRIVATE */
693 struct sadb_x_policy *x_policy; /* SADB_X_EXT_POLICY */
694 struct sadb_x_sa2 *x_sa2; /* SADB_X_EXT_SA2 */
695 struct sadb_x_nat_t_type *x_natt_type; /* SADB_X_EXT_NAT_T_TYPE */
696 struct sadb_x_nat_t_port *x_natt_sport; /* SADB_X_EXT_NAT_T_SPORT */
697 struct sadb_x_nat_t_port *x_natt_dport; /* SADB_X_EXT_NAT_T_DPORT */
698 struct sadb_address *x_natt_oa; /* SADB_X_EXT_NAT_T_OA */
699 struct sadb_x_sec_ctx *x_sec_ctx; /* SADB_X_EXT_SEC_CTX */
700 struct sadb_x_kmaddress *x_kmaddress; /* SADB_X_EXT_KMADDRESS */
701 } __attribute__((__packed__));
702 };
703 };
704
705 ENUM(sadb_ext_type_names, SADB_EXT_RESERVED, SADB_EXT_MAX,
706 "SADB_EXT_RESERVED",
707 "SADB_EXT_SA",
708 "SADB_EXT_LIFETIME_CURRENT",
709 "SADB_EXT_LIFETIME_HARD",
710 "SADB_EXT_LIFETIME_SOFT",
711 "SADB_EXT_ADDRESS_SRC",
712 "SADB_EXT_ADDRESS_DST",
713 "SADB_EXT_ADDRESS_PROXY",
714 "SADB_EXT_KEY_AUTH",
715 "SADB_EXT_KEY_ENCRYPT",
716 "SADB_EXT_IDENTITY_SRC",
717 "SADB_EXT_IDENTITY_DST",
718 "SADB_EXT_SENSITIVITY",
719 "SADB_EXT_PROPOSAL",
720 "SADB_EXT_SUPPORTED_AUTH",
721 "SADB_EXT_SUPPORTED_ENCRYPT",
722 "SADB_EXT_SPIRANGE",
723 "SADB_X_EXT_KMPRIVATE",
724 "SADB_X_EXT_POLICY",
725 "SADB_X_EXT_SA2",
726 "SADB_X_EXT_NAT_T_TYPE",
727 "SADB_X_EXT_NAT_T_SPORT",
728 "SADB_X_EXT_NAT_T_DPORT",
729 "SADB_X_EXT_NAT_T_OA",
730 "SADB_X_EXT_SEC_CTX",
731 "SADB_X_EXT_KMADDRESS"
732 );
733
734 /**
735 * convert a protocol identifier to the PF_KEY sa type
736 */
737 static uint8_t proto2satype(uint8_t proto)
738 {
739 switch (proto)
740 {
741 case IPPROTO_ESP:
742 return SADB_SATYPE_ESP;
743 case IPPROTO_AH:
744 return SADB_SATYPE_AH;
745 case IPPROTO_COMP:
746 return SADB_X_SATYPE_IPCOMP;
747 default:
748 return proto;
749 }
750 }
751
752 /**
753 * convert a PF_KEY sa type to a protocol identifier
754 */
755 static uint8_t satype2proto(uint8_t satype)
756 {
757 switch (satype)
758 {
759 case SADB_SATYPE_ESP:
760 return IPPROTO_ESP;
761 case SADB_SATYPE_AH:
762 return IPPROTO_AH;
763 case SADB_X_SATYPE_IPCOMP:
764 return IPPROTO_COMP;
765 default:
766 return satype;
767 }
768 }
769
770 /**
771 * convert the general ipsec mode to the one defined in ipsec.h
772 */
773 static uint8_t mode2kernel(ipsec_mode_t mode)
774 {
775 switch (mode)
776 {
777 case MODE_TRANSPORT:
778 return IPSEC_MODE_TRANSPORT;
779 case MODE_TUNNEL:
780 return IPSEC_MODE_TUNNEL;
781 #ifdef HAVE_IPSEC_MODE_BEET
782 case MODE_BEET:
783 return IPSEC_MODE_BEET;
784 #endif
785 default:
786 return mode;
787 }
788 }
789
790 /**
791 * convert the general policy direction to the one defined in ipsec.h
792 */
793 static uint8_t dir2kernel(policy_dir_t dir)
794 {
795 switch (dir)
796 {
797 case POLICY_IN:
798 return IPSEC_DIR_INBOUND;
799 case POLICY_OUT:
800 return IPSEC_DIR_OUTBOUND;
801 #ifdef HAVE_IPSEC_DIR_FWD
802 case POLICY_FWD:
803 return IPSEC_DIR_FWD;
804 #endif
805 default:
806 return IPSEC_DIR_INVALID;
807 }
808 }
809
810 /**
811 * convert the policy type to the one defined in ipsec.h
812 */
813 static inline uint16_t type2kernel(policy_type_t type)
814 {
815 switch (type)
816 {
817 case POLICY_IPSEC:
818 return IPSEC_POLICY_IPSEC;
819 case POLICY_PASS:
820 return IPSEC_POLICY_NONE;
821 case POLICY_DROP:
822 return IPSEC_POLICY_DISCARD;
823 }
824 return type;
825 }
826
827 #ifdef SADB_X_MIGRATE
828 /**
829 * convert the policy direction in ipsec.h to the general one.
830 */
831 static policy_dir_t kernel2dir(uint8_t dir)
832 {
833 switch (dir)
834 {
835 case IPSEC_DIR_INBOUND:
836 return POLICY_IN;
837 case IPSEC_DIR_OUTBOUND:
838 return POLICY_OUT;
839 #ifdef HAVE_IPSEC_DIR_FWD
840 case IPSEC_DIR_FWD:
841 return POLICY_FWD;
842 #endif
843 default:
844 return dir;
845 }
846 }
847 #endif /*SADB_X_MIGRATE*/
848
849 typedef struct kernel_algorithm_t kernel_algorithm_t;
850
851 /**
852 * Mapping of IKEv2 algorithms to PF_KEY algorithms
853 */
854 struct kernel_algorithm_t {
855 /**
856 * Identifier specified in IKEv2
857 */
858 int ikev2;
859
860 /**
861 * Identifier as defined in pfkeyv2.h
862 */
863 int kernel;
864 };
865
866 #define END_OF_LIST -1
867
868 /**
869 * Algorithms for encryption
870 */
871 static kernel_algorithm_t encryption_algs[] = {
872 /* {ENCR_DES_IV64, 0 }, */
873 {ENCR_DES, SADB_EALG_DESCBC },
874 {ENCR_3DES, SADB_EALG_3DESCBC },
875 /* {ENCR_RC5, 0 }, */
876 /* {ENCR_IDEA, 0 }, */
877 {ENCR_CAST, SADB_X_EALG_CASTCBC },
878 {ENCR_BLOWFISH, SADB_X_EALG_BLOWFISHCBC },
879 /* {ENCR_3IDEA, 0 }, */
880 /* {ENCR_DES_IV32, 0 }, */
881 {ENCR_NULL, SADB_EALG_NULL },
882 {ENCR_AES_CBC, SADB_X_EALG_AESCBC },
883 #ifdef SADB_X_EALG_AESCTR
884 {ENCR_AES_CTR, SADB_X_EALG_AESCTR },
885 #endif
886 /* {ENCR_AES_CCM_ICV8, SADB_X_EALG_AES_CCM_ICV8 }, */
887 /* {ENCR_AES_CCM_ICV12, SADB_X_EALG_AES_CCM_ICV12 }, */
888 /* {ENCR_AES_CCM_ICV16, SADB_X_EALG_AES_CCM_ICV16 }, */
889 #ifdef SADB_X_EALG_AES_GCM_ICV8 /* assume the others are defined too */
890 {ENCR_AES_GCM_ICV8, SADB_X_EALG_AES_GCM_ICV8 },
891 {ENCR_AES_GCM_ICV12, SADB_X_EALG_AES_GCM_ICV12 },
892 {ENCR_AES_GCM_ICV16, SADB_X_EALG_AES_GCM_ICV16 },
893 #elif defined(SADB_X_EALG_AES_GCM) /* macOS */
894 {ENCR_AES_GCM_ICV16, SADB_X_EALG_AES_GCM },
895 #endif
896 #ifdef SADB_X_EALG_CAMELLIACBC
897 {ENCR_CAMELLIA_CBC, SADB_X_EALG_CAMELLIACBC },
898 #endif
899 #ifdef SADB_X_EALG_CHACHA20POLY1305
900 {ENCR_CHACHA20_POLY1305, SADB_X_EALG_CHACHA20POLY1305},
901 #endif
902 {END_OF_LIST, 0 },
903 };
904
905 /**
906 * Algorithms for integrity protection
907 */
908 static kernel_algorithm_t integrity_algs[] = {
909 {AUTH_HMAC_MD5_96, SADB_AALG_MD5HMAC },
910 {AUTH_HMAC_SHA1_96, SADB_AALG_SHA1HMAC },
911 {AUTH_HMAC_SHA2_256_128, SADB_X_AALG_SHA2_256HMAC },
912 {AUTH_HMAC_SHA2_384_192, SADB_X_AALG_SHA2_384HMAC },
913 {AUTH_HMAC_SHA2_512_256, SADB_X_AALG_SHA2_512HMAC },
914 /* {AUTH_DES_MAC, 0, }, */
915 /* {AUTH_KPDK_MD5, 0, }, */
916 #ifdef SADB_X_AALG_AES_XCBC_MAC
917 {AUTH_AES_XCBC_96, SADB_X_AALG_AES_XCBC_MAC, },
918 #endif
919 {END_OF_LIST, 0, },
920 };
921
922 /**
923 * Algorithms for IPComp, unused yet
924 */
925 static kernel_algorithm_t compression_algs[] = {
926 /* {IPCOMP_OUI, 0 }, */
927 {IPCOMP_DEFLATE, SADB_X_CALG_DEFLATE },
928 #ifdef SADB_X_CALG_LZS
929 {IPCOMP_LZS, SADB_X_CALG_LZS },
930 #endif
931 #ifdef SADB_X_CALG_LZJH
932 {IPCOMP_LZJH, SADB_X_CALG_LZJH },
933 #endif
934 {END_OF_LIST, 0 },
935 };
936
937 /**
938 * Look up a kernel algorithm ID and its key size
939 */
940 static int lookup_algorithm(transform_type_t type, int ikev2)
941 {
942 kernel_algorithm_t *list;
943 uint16_t alg = 0;
944
945 switch (type)
946 {
947 case ENCRYPTION_ALGORITHM:
948 list = encryption_algs;
949 break;
950 case INTEGRITY_ALGORITHM:
951 list = integrity_algs;
952 break;
953 case COMPRESSION_ALGORITHM:
954 list = compression_algs;
955 break;
956 default:
957 return 0;
958 }
959 while (list->ikev2 != END_OF_LIST)
960 {
961 if (ikev2 == list->ikev2)
962 {
963 return list->kernel;
964 }
965 list++;
966 }
967 charon->kernel->lookup_algorithm(charon->kernel, ikev2, type, &alg, NULL);
968 return alg;
969 }
970
971 /**
972 * Helper to set a port in a sockaddr_t, the port has to be in host order
973 */
974 static void set_port(sockaddr_t *addr, uint16_t port)
975 {
976 switch (addr->sa_family)
977 {
978 case AF_INET:
979 {
980 struct sockaddr_in *sin = (struct sockaddr_in*)addr;
981 sin->sin_port = htons(port);
982 break;
983 }
984 case AF_INET6:
985 {
986 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)addr;
987 sin6->sin6_port = htons(port);
988 break;
989 }
990 }
991 }
992
993 /**
994 * Copy a host_t as sockaddr_t to the given memory location.
995 * @return the number of bytes copied
996 */
997 static size_t hostcpy(void *dest, host_t *host, bool include_port)
998 {
999 sockaddr_t *addr = host->get_sockaddr(host), *dest_addr = dest;
1000 socklen_t *len = host->get_sockaddr_len(host);
1001
1002 memcpy(dest, addr, *len);
1003 #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
1004 dest_addr->sa_len = *len;
1005 #endif
1006 if (!include_port)
1007 {
1008 set_port(dest_addr, 0);
1009 }
1010 return *len;
1011 }
1012
1013 /**
1014 * add a host to the given sadb_msg
1015 */
1016 static void add_addr_ext(struct sadb_msg *msg, host_t *host, uint16_t type,
1017 uint8_t proto, uint8_t prefixlen, bool include_port)
1018 {
1019 struct sadb_address *addr = (struct sadb_address*)PFKEY_EXT_ADD_NEXT(msg);
1020 size_t len;
1021
1022 addr->sadb_address_exttype = type;
1023 addr->sadb_address_proto = proto;
1024 addr->sadb_address_prefixlen = prefixlen;
1025 len = hostcpy(addr + 1, host, include_port);
1026 addr->sadb_address_len = PFKEY_LEN(sizeof(*addr) + len);
1027 PFKEY_EXT_ADD(msg, addr);
1028 }
1029
1030 #ifdef HAVE_NATT
1031 /**
1032 * add udp encap extensions to a sadb_msg
1033 */
1034 static void add_encap_ext(struct sadb_msg *msg, host_t *src, host_t *dst)
1035 {
1036 struct sadb_x_nat_t_type* nat_type;
1037 struct sadb_x_nat_t_port* nat_port;
1038
1039 nat_type = (struct sadb_x_nat_t_type*)PFKEY_EXT_ADD_NEXT(msg);
1040 nat_type->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
1041 nat_type->sadb_x_nat_t_type_len = PFKEY_LEN(sizeof(*nat_type));
1042 nat_type->sadb_x_nat_t_type_type = UDP_ENCAP_ESPINUDP;
1043 PFKEY_EXT_ADD(msg, nat_type);
1044
1045 nat_port = (struct sadb_x_nat_t_port*)PFKEY_EXT_ADD_NEXT(msg);
1046 nat_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_SPORT;
1047 nat_port->sadb_x_nat_t_port_len = PFKEY_LEN(sizeof(*nat_port));
1048 nat_port->sadb_x_nat_t_port_port = htons(src->get_port(src));
1049 PFKEY_EXT_ADD(msg, nat_port);
1050
1051 nat_port = (struct sadb_x_nat_t_port*)PFKEY_EXT_ADD_NEXT(msg);
1052 nat_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_DPORT;
1053 nat_port->sadb_x_nat_t_port_len = PFKEY_LEN(sizeof(*nat_port));
1054 nat_port->sadb_x_nat_t_port_port = htons(dst->get_port(dst));
1055 PFKEY_EXT_ADD(msg, nat_port);
1056 }
1057 #endif /*HAVE_NATT*/
1058
1059 /**
1060 * Convert a sadb_address to a traffic_selector
1061 */
1062 static traffic_selector_t* sadb_address2ts(struct sadb_address *address)
1063 {
1064 traffic_selector_t *ts;
1065 host_t *host;
1066 uint8_t proto;
1067
1068 proto = address->sadb_address_proto;
1069 proto = proto == IPSEC_PROTO_ANY ? 0 : proto;
1070
1071 /* The Linux 2.6 kernel does not set the protocol and port information
1072 * in the src and dst sadb_address extensions of the SADB_ACQUIRE message.
1073 */
1074 host = host_create_from_sockaddr((sockaddr_t*)&address[1]);
1075 ts = traffic_selector_create_from_subnet(host,
1076 address->sadb_address_prefixlen,
1077 proto, host->get_port(host),
1078 host->get_port(host) ?: 65535);
1079 return ts;
1080 }
1081
1082 /**
1083 * Parses a pfkey message received from the kernel
1084 */
1085 static status_t parse_pfkey_message(struct sadb_msg *msg, pfkey_msg_t *out)
1086 {
1087 struct sadb_ext* ext;
1088 size_t len;
1089
1090 memset(out, 0, sizeof(pfkey_msg_t));
1091 out->msg = msg;
1092
1093 len = msg->sadb_msg_len;
1094 len -= PFKEY_LEN(sizeof(struct sadb_msg));
1095
1096 ext = (struct sadb_ext*)(((char*)msg) + sizeof(struct sadb_msg));
1097
1098 while (len >= PFKEY_LEN(sizeof(struct sadb_ext)))
1099 {
1100 DBG3(DBG_KNL, " %N", sadb_ext_type_names, ext->sadb_ext_type);
1101 if (ext->sadb_ext_len < PFKEY_LEN(sizeof(struct sadb_ext)) ||
1102 ext->sadb_ext_len > len)
1103 {
1104 DBG1(DBG_KNL, "length of %N extension is invalid",
1105 sadb_ext_type_names, ext->sadb_ext_type);
1106 break;
1107 }
1108
1109 if ((ext->sadb_ext_type > SADB_EXT_MAX) || (!ext->sadb_ext_type))
1110 {
1111 DBG1(DBG_KNL, "type of PF_KEY extension (%d) is invalid",
1112 ext->sadb_ext_type);
1113 break;
1114 }
1115
1116 if (out->ext[ext->sadb_ext_type])
1117 {
1118 DBG1(DBG_KNL, "duplicate %N extension",
1119 sadb_ext_type_names, ext->sadb_ext_type);
1120 break;
1121 }
1122
1123 out->ext[ext->sadb_ext_type] = ext;
1124 ext = PFKEY_EXT_NEXT_LEN(ext, len);
1125 }
1126
1127 if (len)
1128 {
1129 DBG1(DBG_KNL, "PF_KEY message length is invalid");
1130 return FAILED;
1131 }
1132
1133 return SUCCESS;
1134 }
1135
1136 /**
1137 * Send a message to a specific PF_KEY socket and handle the response.
1138 */
1139 static status_t pfkey_send_socket(private_kernel_pfkey_ipsec_t *this, int socket,
1140 struct sadb_msg *in, struct sadb_msg **out, size_t *out_len)
1141 {
1142 unsigned char buf[PFKEY_BUFFER_SIZE];
1143 struct sadb_msg *msg;
1144 int in_len, len;
1145
1146 this->mutex_pfkey->lock(this->mutex_pfkey);
1147
1148 /* the kernel may broadcast messages not related to our requests (e.g. when
1149 * managing SAs and policies via an external tool), so let's clear the
1150 * receive buffer so there is room for our request and its reply. */
1151 while (TRUE)
1152 {
1153 len = recv(socket, buf, sizeof(buf), MSG_DONTWAIT);
1154
1155 if (len < 0)
1156 {
1157 if (errno == EINTR)
1158 { /* interrupted, try again */
1159 continue;
1160 }
1161 break;
1162 }
1163 }
1164
1165 /* FIXME: our usage of sequence numbers is probably wrong. check RFC 2367,
1166 * in particular the behavior in response to an SADB_ACQUIRE. */
1167 in->sadb_msg_seq = ++this->seq;
1168 in->sadb_msg_pid = getpid();
1169
1170 in_len = PFKEY_USER_LEN(in->sadb_msg_len);
1171
1172 while (TRUE)
1173 {
1174 len = send(socket, in, in_len, 0);
1175
1176 if (len != in_len)
1177 {
1178 if (errno == EINTR)
1179 {
1180 /* interrupted, try again */
1181 continue;
1182 }
1183 this->mutex_pfkey->unlock(this->mutex_pfkey);
1184 DBG1(DBG_KNL, "error sending to PF_KEY socket: %s",
1185 strerror(errno));
1186 return FAILED;
1187 }
1188 break;
1189 }
1190
1191 while (TRUE)
1192 {
1193 msg = (struct sadb_msg*)buf;
1194
1195 len = recv(socket, buf, sizeof(buf), 0);
1196
1197 if (len < 0)
1198 {
1199 if (errno == EINTR)
1200 {
1201 DBG1(DBG_KNL, "got interrupted");
1202 /* interrupted, try again */
1203 continue;
1204 }
1205 DBG1(DBG_KNL, "error reading from PF_KEY socket: %s",
1206 strerror(errno));
1207 this->mutex_pfkey->unlock(this->mutex_pfkey);
1208 return FAILED;
1209 }
1210 if (len < sizeof(struct sadb_msg) ||
1211 msg->sadb_msg_len < PFKEY_LEN(sizeof(struct sadb_msg)))
1212 {
1213 DBG1(DBG_KNL, "received corrupted PF_KEY message");
1214 this->mutex_pfkey->unlock(this->mutex_pfkey);
1215 return FAILED;
1216 }
1217 if (msg->sadb_msg_len > len / PFKEY_ALIGNMENT)
1218 {
1219 DBG1(DBG_KNL, "buffer was too small to receive the complete PF_KEY "
1220 "message");
1221 this->mutex_pfkey->unlock(this->mutex_pfkey);
1222 return FAILED;
1223 }
1224 if (msg->sadb_msg_pid != in->sadb_msg_pid)
1225 {
1226 DBG2(DBG_KNL, "received PF_KEY message is not intended for us");
1227 continue;
1228 }
1229 if (msg->sadb_msg_seq != this->seq)
1230 {
1231 DBG2(DBG_KNL, "received PF_KEY message with unexpected sequence "
1232 "number, was %d expected %d", msg->sadb_msg_seq,
1233 this->seq);
1234 if (msg->sadb_msg_seq == 0)
1235 {
1236 /* FreeBSD and Mac OS X do this for the response to
1237 * SADB_X_SPDGET (but not for the response to SADB_GET).
1238 * FreeBSD: 'key_spdget' in /usr/src/sys/netipsec/key.c. */
1239 }
1240 else if (msg->sadb_msg_seq < this->seq)
1241 {
1242 continue;
1243 }
1244 else
1245 {
1246 this->mutex_pfkey->unlock(this->mutex_pfkey);
1247 return FAILED;
1248 }
1249 }
1250 if (msg->sadb_msg_type != in->sadb_msg_type)
1251 {
1252 DBG2(DBG_KNL, "received PF_KEY message of wrong type, "
1253 "was %d expected %d, ignoring", msg->sadb_msg_type,
1254 in->sadb_msg_type);
1255 }
1256 break;
1257 }
1258
1259 *out_len = len;
1260 *out = (struct sadb_msg*)malloc(len);
1261 memcpy(*out, buf, len);
1262
1263 this->mutex_pfkey->unlock(this->mutex_pfkey);
1264 return SUCCESS;
1265 }
1266
1267 /**
1268 * Send a message to the default PF_KEY socket and handle the response.
1269 */
1270 static status_t pfkey_send(private_kernel_pfkey_ipsec_t *this,
1271 struct sadb_msg *in, struct sadb_msg **out,
1272 size_t *out_len)
1273 {
1274 return pfkey_send_socket(this, this->socket, in, out, out_len);
1275 }
1276
1277 /**
1278 * Process a SADB_ACQUIRE message from the kernel
1279 */
1280 static void process_acquire(private_kernel_pfkey_ipsec_t *this,
1281 struct sadb_msg* msg)
1282 {
1283 pfkey_msg_t response;
1284 uint32_t index, reqid = 0;
1285 traffic_selector_t *src_ts, *dst_ts;
1286 policy_entry_t *policy;
1287 policy_sa_t *sa;
1288
1289 switch (msg->sadb_msg_satype)
1290 {
1291 case SADB_SATYPE_UNSPEC:
1292 case SADB_SATYPE_ESP:
1293 case SADB_SATYPE_AH:
1294 break;
1295 default:
1296 /* acquire for AH/ESP only */
1297 return;
1298 }
1299 DBG2(DBG_KNL, "received an SADB_ACQUIRE");
1300
1301 if (parse_pfkey_message(msg, &response) != SUCCESS)
1302 {
1303 DBG1(DBG_KNL, "parsing SADB_ACQUIRE from kernel failed");
1304 return;
1305 }
1306
1307 if (response.x_sa2)
1308 {
1309 reqid = response.x_sa2->sadb_x_sa2_reqid;
1310 }
1311 else
1312 {
1313 index = response.x_policy->sadb_x_policy_id;
1314 this->mutex->lock(this->mutex);
1315 if (this->policies->find_first(this->policies, policy_entry_match_byindex,
1316 (void**)&policy, index) &&
1317 policy->used_by->get_first(policy->used_by, (void**)&sa) == SUCCESS)
1318 {
1319 reqid = sa->sa->cfg.reqid;
1320 }
1321 else
1322 {
1323 DBG1(DBG_KNL, "received an SADB_ACQUIRE with policy id %d but no "
1324 "matching policy found", index);
1325 }
1326 this->mutex->unlock(this->mutex);
1327 }
1328
1329 src_ts = sadb_address2ts(response.src);
1330 dst_ts = sadb_address2ts(response.dst);
1331
1332 charon->kernel->acquire(charon->kernel, reqid, src_ts, dst_ts);
1333 }
1334
1335 /**
1336 * Process a SADB_EXPIRE message from the kernel
1337 */
1338 static void process_expire(private_kernel_pfkey_ipsec_t *this,
1339 struct sadb_msg* msg)
1340 {
1341 pfkey_msg_t response;
1342 uint8_t protocol;
1343 uint32_t spi;
1344 host_t *dst;
1345 bool hard;
1346
1347 DBG2(DBG_KNL, "received an SADB_EXPIRE");
1348
1349 if (parse_pfkey_message(msg, &response) != SUCCESS)
1350 {
1351 DBG1(DBG_KNL, "parsing SADB_EXPIRE from kernel failed");
1352 return;
1353 }
1354
1355 protocol = satype2proto(msg->sadb_msg_satype);
1356 spi = response.sa->sadb_sa_spi;
1357 hard = response.lft_hard != NULL;
1358
1359 if (protocol == IPPROTO_ESP || protocol == IPPROTO_AH)
1360 {
1361 dst = host_create_from_sockaddr((sockaddr_t*)(response.dst + 1));
1362 if (dst)
1363 {
1364 charon->kernel->expire(charon->kernel, protocol, spi, dst, hard);
1365 dst->destroy(dst);
1366 }
1367 }
1368 }
1369
1370 #ifdef SADB_X_MIGRATE
1371 /**
1372 * Process a SADB_X_MIGRATE message from the kernel
1373 */
1374 static void process_migrate(private_kernel_pfkey_ipsec_t *this,
1375 struct sadb_msg* msg)
1376 {
1377 pfkey_msg_t response;
1378 traffic_selector_t *src_ts, *dst_ts;
1379 policy_dir_t dir;
1380 uint32_t reqid = 0;
1381 host_t *local = NULL, *remote = NULL;
1382
1383 DBG2(DBG_KNL, "received an SADB_X_MIGRATE");
1384
1385 if (parse_pfkey_message(msg, &response) != SUCCESS)
1386 {
1387 DBG1(DBG_KNL, "parsing SADB_X_MIGRATE from kernel failed");
1388 return;
1389 }
1390 src_ts = sadb_address2ts(response.src);
1391 dst_ts = sadb_address2ts(response.dst);
1392 dir = kernel2dir(response.x_policy->sadb_x_policy_dir);
1393 DBG2(DBG_KNL, " policy %R === %R %N, id %u", src_ts, dst_ts,
1394 policy_dir_names, dir);
1395
1396 /* SADB_X_EXT_KMADDRESS is not present in unpatched kernels < 2.6.28 */
1397 if (response.x_kmaddress)
1398 {
1399 sockaddr_t *local_addr, *remote_addr;
1400 uint32_t local_len;
1401
1402 local_addr = (sockaddr_t*)&response.x_kmaddress[1];
1403 local = host_create_from_sockaddr(local_addr);
1404 local_len = (local_addr->sa_family == AF_INET6)?
1405 sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in);
1406 remote_addr = (sockaddr_t*)((uint8_t*)local_addr + local_len);
1407 remote = host_create_from_sockaddr(remote_addr);
1408 DBG2(DBG_KNL, " kmaddress: %H...%H", local, remote);
1409 }
1410
1411 if (src_ts && dst_ts && local && remote)
1412 {
1413 charon->kernel->migrate(charon->kernel, reqid, src_ts, dst_ts, dir,
1414 local, remote);
1415 }
1416 else
1417 {
1418 DESTROY_IF(src_ts);
1419 DESTROY_IF(dst_ts);
1420 DESTROY_IF(local);
1421 DESTROY_IF(remote);
1422 }
1423 }
1424 #endif /*SADB_X_MIGRATE*/
1425
1426 #ifdef SADB_X_NAT_T_NEW_MAPPING
1427 /**
1428 * Process a SADB_X_NAT_T_NEW_MAPPING message from the kernel
1429 */
1430 static void process_mapping(private_kernel_pfkey_ipsec_t *this,
1431 struct sadb_msg* msg)
1432 {
1433 pfkey_msg_t response;
1434 uint32_t spi;
1435 sockaddr_t *sa;
1436 host_t *dst, *new;
1437
1438 DBG2(DBG_KNL, "received an SADB_X_NAT_T_NEW_MAPPING");
1439
1440 if (parse_pfkey_message(msg, &response) != SUCCESS)
1441 {
1442 DBG1(DBG_KNL, "parsing SADB_X_NAT_T_NEW_MAPPING from kernel failed");
1443 return;
1444 }
1445
1446 if (!response.x_sa2)
1447 {
1448 DBG1(DBG_KNL, "received SADB_X_NAT_T_NEW_MAPPING is missing required "
1449 "information");
1450 return;
1451 }
1452
1453 spi = response.sa->sadb_sa_spi;
1454
1455 if (satype2proto(msg->sadb_msg_satype) != IPPROTO_ESP)
1456 {
1457 return;
1458 }
1459
1460 sa = (sockaddr_t*)(response.dst + 1);
1461 dst = host_create_from_sockaddr(sa);
1462 switch (sa->sa_family)
1463 {
1464 case AF_INET:
1465 {
1466 struct sockaddr_in *sin = (struct sockaddr_in*)sa;
1467 sin->sin_port = htons(response.x_natt_dport->sadb_x_nat_t_port_port);
1468 break;
1469 }
1470 case AF_INET6:
1471 {
1472 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)sa;
1473 sin6->sin6_port = htons(response.x_natt_dport->sadb_x_nat_t_port_port);
1474 break;
1475 }
1476 default:
1477 break;
1478 }
1479 if (dst)
1480 {
1481 new = host_create_from_sockaddr(sa);
1482 if (new)
1483 {
1484 charon->kernel->mapping(charon->kernel, IPPROTO_ESP, spi, dst, new);
1485 new->destroy(new);
1486 }
1487 dst->destroy(dst);
1488 }
1489 }
1490 #endif /*SADB_X_NAT_T_NEW_MAPPING*/
1491
1492 /**
1493 * Receives events from kernel
1494 */
1495 static bool receive_events(private_kernel_pfkey_ipsec_t *this, int fd,
1496 watcher_event_t event)
1497 {
1498 unsigned char buf[PFKEY_BUFFER_SIZE];
1499 struct sadb_msg *msg = (struct sadb_msg*)buf;
1500 int len;
1501
1502 len = recvfrom(this->socket_events, buf, sizeof(buf), MSG_DONTWAIT, NULL, 0);
1503 if (len < 0)
1504 {
1505 switch (errno)
1506 {
1507 case EINTR:
1508 /* interrupted, try again */
1509 return TRUE;
1510 case EAGAIN:
1511 /* no data ready, select again */
1512 return TRUE;
1513 default:
1514 DBG1(DBG_KNL, "unable to receive from PF_KEY event socket");
1515 sleep(1);
1516 return TRUE;
1517 }
1518 }
1519
1520 if (len < sizeof(struct sadb_msg) ||
1521 msg->sadb_msg_len < PFKEY_LEN(sizeof(struct sadb_msg)))
1522 {
1523 DBG2(DBG_KNL, "received corrupted PF_KEY message");
1524 return TRUE;
1525 }
1526 if (msg->sadb_msg_pid != 0)
1527 { /* not from kernel. not interested, try another one */
1528 return TRUE;
1529 }
1530 if (msg->sadb_msg_len > len / PFKEY_ALIGNMENT)
1531 {
1532 DBG1(DBG_KNL, "buffer was too small to receive the complete "
1533 "PF_KEY message");
1534 return TRUE;
1535 }
1536
1537 switch (msg->sadb_msg_type)
1538 {
1539 case SADB_ACQUIRE:
1540 process_acquire(this, msg);
1541 break;
1542 case SADB_EXPIRE:
1543 process_expire(this, msg);
1544 break;
1545 #ifdef SADB_X_MIGRATE
1546 case SADB_X_MIGRATE:
1547 process_migrate(this, msg);
1548 break;
1549 #endif /*SADB_X_MIGRATE*/
1550 #ifdef SADB_X_NAT_T_NEW_MAPPING
1551 case SADB_X_NAT_T_NEW_MAPPING:
1552 process_mapping(this, msg);
1553 break;
1554 #endif /*SADB_X_NAT_T_NEW_MAPPING*/
1555 default:
1556 break;
1557 }
1558
1559 return TRUE;
1560 }
1561
1562 /**
1563 * Get an SPI for a specific protocol from the kernel.
1564 */
1565
1566 static status_t get_spi_internal(private_kernel_pfkey_ipsec_t *this,
1567 host_t *src, host_t *dst, uint8_t proto, uint32_t min, uint32_t max,
1568 uint32_t *spi)
1569 {
1570 unsigned char request[PFKEY_BUFFER_SIZE];
1571 struct sadb_msg *msg, *out;
1572 struct sadb_spirange *range;
1573 pfkey_msg_t response;
1574 uint32_t received_spi = 0;
1575 size_t len;
1576
1577 memset(&request, 0, sizeof(request));
1578
1579 msg = (struct sadb_msg*)request;
1580 msg->sadb_msg_version = PF_KEY_V2;
1581 msg->sadb_msg_type = SADB_GETSPI;
1582 msg->sadb_msg_satype = proto2satype(proto);
1583 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1584
1585 add_addr_ext(msg, src, SADB_EXT_ADDRESS_SRC, 0, 0, FALSE);
1586 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST, 0, 0, FALSE);
1587
1588 range = (struct sadb_spirange*)PFKEY_EXT_ADD_NEXT(msg);
1589 range->sadb_spirange_exttype = SADB_EXT_SPIRANGE;
1590 range->sadb_spirange_len = PFKEY_LEN(sizeof(struct sadb_spirange));
1591 range->sadb_spirange_min = min;
1592 range->sadb_spirange_max = max;
1593 PFKEY_EXT_ADD(msg, range);
1594
1595 if (pfkey_send(this, msg, &out, &len) == SUCCESS)
1596 {
1597 if (out->sadb_msg_errno)
1598 {
1599 DBG1(DBG_KNL, "allocating SPI failed: %s (%d)",
1600 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1601 }
1602 else if (parse_pfkey_message(out, &response) == SUCCESS)
1603 {
1604 received_spi = response.sa->sadb_sa_spi;
1605 }
1606 free(out);
1607 }
1608
1609 if (received_spi == 0)
1610 {
1611 return FAILED;
1612 }
1613
1614 *spi = received_spi;
1615 return SUCCESS;
1616 }
1617
1618 METHOD(kernel_ipsec_t, get_spi, status_t,
1619 private_kernel_pfkey_ipsec_t *this, host_t *src, host_t *dst,
1620 uint8_t protocol, uint32_t *spi)
1621 {
1622 uint32_t spi_min, spi_max;
1623
1624 spi_min = lib->settings->get_int(lib->settings, "%s.spi_min",
1625 KERNEL_SPI_MIN, lib->ns);
1626 spi_max = lib->settings->get_int(lib->settings, "%s.spi_max",
1627 KERNEL_SPI_MAX, lib->ns);
1628
1629 if (get_spi_internal(this, src, dst, protocol, min(spi_min, spi_max),
1630 max(spi_min, spi_max), spi) != SUCCESS)
1631 {
1632 DBG1(DBG_KNL, "unable to get SPI");
1633 return FAILED;
1634 }
1635
1636 DBG2(DBG_KNL, "got SPI %.8x", ntohl(*spi));
1637 return SUCCESS;
1638 }
1639
1640 METHOD(kernel_ipsec_t, get_cpi, status_t,
1641 private_kernel_pfkey_ipsec_t *this, host_t *src, host_t *dst,
1642 uint16_t *cpi)
1643 {
1644 uint32_t received_spi = 0;
1645
1646 DBG2(DBG_KNL, "getting CPI");
1647
1648 if (get_spi_internal(this, src, dst, IPPROTO_COMP,
1649 0x100, 0xEFFF, &received_spi) != SUCCESS)
1650 {
1651 DBG1(DBG_KNL, "unable to get CPI");
1652 return FAILED;
1653 }
1654
1655 *cpi = htons((uint16_t)ntohl(received_spi));
1656
1657 DBG2(DBG_KNL, "got CPI %.4x", ntohs(*cpi));
1658 return SUCCESS;
1659 }
1660
1661 METHOD(kernel_ipsec_t, add_sa, status_t,
1662 private_kernel_pfkey_ipsec_t *this, kernel_ipsec_sa_id_t *id,
1663 kernel_ipsec_add_sa_t *data)
1664 {
1665 unsigned char request[PFKEY_BUFFER_SIZE];
1666 struct sadb_msg *msg, *out;
1667 struct sadb_sa *sa;
1668 struct sadb_x_sa2 *sa2;
1669 struct sadb_lifetime *lft;
1670 struct sadb_key *key;
1671 size_t len;
1672 uint16_t ipcomp = data->ipcomp;
1673 ipsec_mode_t mode = data->mode;
1674
1675 /* if IPComp is used, we install an additional IPComp SA. if the cpi is 0
1676 * we are in the recursive call below */
1677 if (ipcomp != IPCOMP_NONE && data->cpi != 0)
1678 {
1679 lifetime_cfg_t lft = {{0,0,0},{0,0,0},{0,0,0}};
1680 kernel_ipsec_sa_id_t ipcomp_id = {
1681 .src = id->src,
1682 .dst = id->dst,
1683 .spi = htonl(ntohs(data->cpi)),
1684 .proto = IPPROTO_COMP,
1685 .mark = id->mark,
1686 };
1687 kernel_ipsec_add_sa_t ipcomp_sa = {
1688 .reqid = data->reqid,
1689 .mode = data->mode,
1690 .src_ts = data->src_ts,
1691 .dst_ts = data->dst_ts,
1692 .lifetime = &lft,
1693 .enc_alg = ENCR_UNDEFINED,
1694 .int_alg = AUTH_UNDEFINED,
1695 .tfc = data->tfc,
1696 .ipcomp = data->ipcomp,
1697 .initiator = data->initiator,
1698 .inbound = data->inbound,
1699 .update = data->update,
1700 };
1701 add_sa(this, &ipcomp_id, &ipcomp_sa);
1702 ipcomp = IPCOMP_NONE;
1703 /* use transport mode ESP SA, IPComp uses tunnel mode */
1704 mode = MODE_TRANSPORT;
1705 }
1706
1707 if (data->update)
1708 {
1709 /* As we didn't know the reqid during SPI allocation, we used reqid
1710 * zero. Unfortunately we can't SADB_UPDATE to the new reqid, hence we
1711 * have to delete the SPI allocation state manually. The reqid
1712 * selector does not count for that, therefore we have to delete
1713 * that state before installing the new SA to avoid deleting the
1714 * the new state after installing it. */
1715 kernel_ipsec_sa_id_t del_id = {
1716 .src = id->src,
1717 .dst = id->dst,
1718 .spi = id->spi,
1719 .proto = id->proto,
1720 };
1721 kernel_ipsec_del_sa_t del = { 0 };
1722
1723 if (this->public.interface.del_sa(&this->public.interface, &del_id,
1724 &del) != SUCCESS)
1725 {
1726 DBG1(DBG_KNL, "deleting SPI allocation SA failed");
1727 }
1728 }
1729
1730 memset(&request, 0, sizeof(request));
1731
1732 DBG2(DBG_KNL, "adding SAD entry with SPI %.8x and reqid {%u}",
1733 ntohl(id->spi), data->reqid);
1734
1735 msg = (struct sadb_msg*)request;
1736 msg->sadb_msg_version = PF_KEY_V2;
1737 msg->sadb_msg_type = SADB_ADD;
1738 msg->sadb_msg_satype = proto2satype(id->proto);
1739 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1740
1741 #ifdef __APPLE__
1742 if (data->encap)
1743 {
1744 struct sadb_sa_2 *sa_2;
1745 sa_2 = (struct sadb_sa_2*)PFKEY_EXT_ADD_NEXT(msg);
1746 sa_2->sadb_sa_natt_port = id->dst->get_port(id->dst);
1747 sa = &sa_2->sa;
1748 sa->sadb_sa_flags |= SADB_X_EXT_NATT;
1749 len = sizeof(struct sadb_sa_2);
1750 }
1751 else
1752 #endif
1753 {
1754 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1755 len = sizeof(struct sadb_sa);
1756 }
1757 sa->sadb_sa_exttype = SADB_EXT_SA;
1758 sa->sadb_sa_len = PFKEY_LEN(len);
1759 sa->sadb_sa_spi = id->spi;
1760 sa->sadb_sa_state = SADB_SASTATE_MATURE;
1761 if (id->proto == IPPROTO_COMP)
1762 {
1763 sa->sadb_sa_encrypt = lookup_algorithm(COMPRESSION_ALGORITHM,
1764 ipcomp);
1765 }
1766 else
1767 {
1768 /* Linux interprets sadb_sa_replay as number of packets/bits in the
1769 * replay window, whereas on BSD it's the size of the window in bytes.
1770 * Only set for the inbound SA as it's not relevant for the outbound
1771 * SA and might waste memory with large windows. */
1772 if (data->inbound)
1773 {
1774 #ifdef __linux__
1775 sa->sadb_sa_replay = min(data->replay_window, 32);
1776 #else
1777 sa->sadb_sa_replay = min((data->replay_window + 7) / 8, UINT8_MAX);
1778 #endif
1779 }
1780 if (data->esn)
1781 {
1782 #ifdef SADB_X_SAFLAGS_ESN
1783 DBG2(DBG_KNL, " using extended sequence numbers (ESN)");
1784 sa->sadb_sa_flags |= SADB_X_SAFLAGS_ESN;
1785 #else
1786 DBG1(DBG_KNL, "extended sequence numbers (ESN) not supported by "
1787 "kernel!");
1788 return FAILED;
1789 #endif
1790 }
1791 sa->sadb_sa_auth = lookup_algorithm(INTEGRITY_ALGORITHM, data->int_alg);
1792 sa->sadb_sa_encrypt = lookup_algorithm(ENCRYPTION_ALGORITHM,
1793 data->enc_alg);
1794 }
1795 PFKEY_EXT_ADD(msg, sa);
1796
1797 #ifdef SADB_X_EXT_SA_REPLAY
1798 if (data->inbound)
1799 {
1800 struct sadb_x_sa_replay *repl;
1801
1802 repl = (struct sadb_x_sa_replay*)PFKEY_EXT_ADD_NEXT(msg);
1803 repl->sadb_x_sa_replay_exttype = SADB_X_EXT_SA_REPLAY;
1804 repl->sadb_x_sa_replay_len = PFKEY_LEN(sizeof(struct sadb_x_sa_replay));
1805 repl->sadb_x_sa_replay_replay = min(data->replay_window, UINT32_MAX-32);
1806 PFKEY_EXT_ADD(msg, repl);
1807 }
1808 #endif
1809
1810 sa2 = (struct sadb_x_sa2*)PFKEY_EXT_ADD_NEXT(msg);
1811 sa2->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
1812 sa2->sadb_x_sa2_len = PFKEY_LEN(sizeof(struct sadb_spirange));
1813 sa2->sadb_x_sa2_mode = mode2kernel(mode);
1814 sa2->sadb_x_sa2_reqid = data->reqid;
1815 PFKEY_EXT_ADD(msg, sa2);
1816
1817 add_addr_ext(msg, id->src, SADB_EXT_ADDRESS_SRC, 0, 0, FALSE);
1818 add_addr_ext(msg, id->dst, SADB_EXT_ADDRESS_DST, 0, 0, FALSE);
1819
1820 lft = (struct sadb_lifetime*)PFKEY_EXT_ADD_NEXT(msg);
1821 lft->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
1822 lft->sadb_lifetime_len = PFKEY_LEN(sizeof(struct sadb_lifetime));
1823 lft->sadb_lifetime_allocations = data->lifetime->packets.rekey;
1824 lft->sadb_lifetime_bytes = data->lifetime->bytes.rekey;
1825 lft->sadb_lifetime_addtime = data->lifetime->time.rekey;
1826 lft->sadb_lifetime_usetime = 0; /* we only use addtime */
1827 PFKEY_EXT_ADD(msg, lft);
1828
1829 lft = (struct sadb_lifetime*)PFKEY_EXT_ADD_NEXT(msg);
1830 lft->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
1831 lft->sadb_lifetime_len = PFKEY_LEN(sizeof(struct sadb_lifetime));
1832 lft->sadb_lifetime_allocations = data->lifetime->packets.life;
1833 lft->sadb_lifetime_bytes = data->lifetime->bytes.life;
1834 lft->sadb_lifetime_addtime = data->lifetime->time.life;
1835 lft->sadb_lifetime_usetime = 0; /* we only use addtime */
1836 PFKEY_EXT_ADD(msg, lft);
1837
1838 if (data->enc_alg != ENCR_UNDEFINED)
1839 {
1840 if (!sa->sadb_sa_encrypt)
1841 {
1842 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1843 encryption_algorithm_names, data->enc_alg);
1844 return FAILED;
1845 }
1846 DBG2(DBG_KNL, " using encryption algorithm %N with key size %d",
1847 encryption_algorithm_names, data->enc_alg, data->enc_key.len * 8);
1848
1849 key = (struct sadb_key*)PFKEY_EXT_ADD_NEXT(msg);
1850 key->sadb_key_exttype = SADB_EXT_KEY_ENCRYPT;
1851 key->sadb_key_bits = data->enc_key.len * 8;
1852 key->sadb_key_len = PFKEY_LEN(sizeof(struct sadb_key) + data->enc_key.len);
1853 memcpy(key + 1, data->enc_key.ptr, data->enc_key.len);
1854
1855 PFKEY_EXT_ADD(msg, key);
1856 }
1857
1858 if (data->int_alg != AUTH_UNDEFINED)
1859 {
1860 if (!sa->sadb_sa_auth)
1861 {
1862 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1863 integrity_algorithm_names, data->int_alg);
1864 return FAILED;
1865 }
1866 DBG2(DBG_KNL, " using integrity algorithm %N with key size %d",
1867 integrity_algorithm_names, data->int_alg, data->int_key.len * 8);
1868
1869 key = (struct sadb_key*)PFKEY_EXT_ADD_NEXT(msg);
1870 key->sadb_key_exttype = SADB_EXT_KEY_AUTH;
1871 key->sadb_key_bits = data->int_key.len * 8;
1872 key->sadb_key_len = PFKEY_LEN(sizeof(struct sadb_key) + data->int_key.len);
1873 memcpy(key + 1, data->int_key.ptr, data->int_key.len);
1874
1875 PFKEY_EXT_ADD(msg, key);
1876 }
1877
1878 #ifdef HAVE_NATT
1879 if (data->encap)
1880 {
1881 add_encap_ext(msg, id->src, id->dst);
1882 }
1883 #endif /*HAVE_NATT*/
1884
1885 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1886 {
1887 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x",
1888 ntohl(id->spi));
1889 return FAILED;
1890 }
1891 else if (out->sadb_msg_errno)
1892 {
1893 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x: %s (%d)",
1894 ntohl(id->spi), strerror(out->sadb_msg_errno),
1895 out->sadb_msg_errno);
1896 free(out);
1897 return FAILED;
1898 }
1899
1900 free(out);
1901 return SUCCESS;
1902 }
1903
1904 METHOD(kernel_ipsec_t, update_sa, status_t,
1905 private_kernel_pfkey_ipsec_t *this, kernel_ipsec_sa_id_t *id,
1906 kernel_ipsec_update_sa_t *data)
1907 {
1908 unsigned char request[PFKEY_BUFFER_SIZE];
1909 struct sadb_msg *msg, *out;
1910 struct sadb_sa *sa;
1911 pfkey_msg_t response;
1912 size_t len;
1913
1914 #ifndef SADB_X_EXT_NEW_ADDRESS_SRC
1915 /* we can't update the SA if any of the ip addresses have changed.
1916 * that's because we can't use SADB_UPDATE and by deleting and readding the
1917 * SA the sequence numbers would get lost */
1918 if (!id->src->ip_equals(id->src, data->new_src) ||
1919 !id->dst->ip_equals(id->dst, data->new_dst))
1920 {
1921 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x: address "
1922 "changes are not supported", ntohl(id->spi));
1923 return NOT_SUPPORTED;
1924 }
1925 #endif /*SADB_X_EXT_NEW_ADDRESS_SRC*/
1926
1927 /* if IPComp is used, we first update the IPComp SA */
1928 if (data->cpi)
1929 {
1930 kernel_ipsec_sa_id_t ipcomp_id = {
1931 .src = id->src,
1932 .dst = id->dst,
1933 .spi = htonl(ntohs(data->cpi)),
1934 .proto = IPPROTO_COMP,
1935 .mark = id->mark,
1936 };
1937 kernel_ipsec_update_sa_t ipcomp = {
1938 .new_src = data->new_src,
1939 .new_dst = data->new_dst,
1940 };
1941 update_sa(this, &ipcomp_id, &ipcomp);
1942 }
1943
1944 memset(&request, 0, sizeof(request));
1945
1946 DBG2(DBG_KNL, "querying SAD entry with SPI %.8x for update",
1947 ntohl(id->spi));
1948
1949 msg = (struct sadb_msg*)request;
1950 msg->sadb_msg_version = PF_KEY_V2;
1951 msg->sadb_msg_type = SADB_GET;
1952 msg->sadb_msg_satype = proto2satype(id->proto);
1953 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1954
1955 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1956 sa->sadb_sa_exttype = SADB_EXT_SA;
1957 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1958 sa->sadb_sa_spi = id->spi;
1959 sa->sadb_sa_state = SADB_SASTATE_MATURE;
1960 PFKEY_EXT_ADD(msg, sa);
1961
1962 add_addr_ext(msg, id->src, SADB_EXT_ADDRESS_SRC, 0, 0, FALSE);
1963 add_addr_ext(msg, id->dst, SADB_EXT_ADDRESS_DST, 0, 0, FALSE);
1964
1965 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1966 {
1967 DBG1(DBG_KNL, "unable to query SAD entry with SPI %.8x",
1968 ntohl(id->spi));
1969 return FAILED;
1970 }
1971 else if (out->sadb_msg_errno)
1972 {
1973 DBG1(DBG_KNL, "unable to query SAD entry with SPI %.8x: %s (%d)",
1974 ntohl(id->spi), strerror(out->sadb_msg_errno),
1975 out->sadb_msg_errno);
1976 free(out);
1977 return FAILED;
1978 }
1979 else if (parse_pfkey_message(out, &response) != SUCCESS)
1980 {
1981 DBG1(DBG_KNL, "unable to query SAD entry with SPI %.8x: parsing "
1982 "response from kernel failed", ntohl(id->spi));
1983 free(out);
1984 return FAILED;
1985 }
1986
1987 DBG2(DBG_KNL, "updating SAD entry with SPI %.8x from %#H..%#H to %#H..%#H",
1988 ntohl(id->spi), id->src, id->dst, data->new_src, data->new_dst);
1989
1990 memset(&request, 0, sizeof(request));
1991
1992 msg = (struct sadb_msg*)request;
1993 msg->sadb_msg_version = PF_KEY_V2;
1994 msg->sadb_msg_type = SADB_UPDATE;
1995 msg->sadb_msg_satype = proto2satype(id->proto);
1996 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1997
1998 #ifdef __APPLE__
1999 {
2000 struct sadb_sa_2 *sa_2;
2001 sa_2 = (struct sadb_sa_2*)PFKEY_EXT_ADD_NEXT(msg);
2002 sa_2->sa.sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa_2));
2003 memcpy(&sa_2->sa, response.sa, sizeof(struct sadb_sa));
2004 if (data->new_encap)
2005 {
2006 sa_2->sadb_sa_natt_port = data->new_dst->get_port(data->new_dst);
2007 sa_2->sa.sadb_sa_flags |= SADB_X_EXT_NATT;
2008 }
2009 }
2010 #else
2011 PFKEY_EXT_COPY(msg, response.sa);
2012 #endif
2013 PFKEY_EXT_COPY(msg, response.x_sa2);
2014
2015 PFKEY_EXT_COPY(msg, response.src);
2016 PFKEY_EXT_COPY(msg, response.dst);
2017
2018 PFKEY_EXT_COPY(msg, response.lft_soft);
2019 PFKEY_EXT_COPY(msg, response.lft_hard);
2020
2021 #ifndef __FreeBSD__
2022 /* FreeBSD 11.1 does not allow key updates via SADB_UPDATE for mature SAs */
2023 if (response.key_encr)
2024 {
2025 PFKEY_EXT_COPY(msg, response.key_encr);
2026 }
2027
2028 if (response.key_auth)
2029 {
2030 PFKEY_EXT_COPY(msg, response.key_auth);
2031 }
2032 #endif
2033
2034 #ifdef HAVE_NATT
2035 if (data->new_encap)
2036 {
2037 add_encap_ext(msg, data->new_src, data->new_dst);
2038 }
2039 #endif /*HAVE_NATT*/
2040
2041 #ifdef SADB_X_EXT_NEW_ADDRESS_SRC
2042 if (!id->src->ip_equals(id->src, data->new_src))
2043 {
2044 add_addr_ext(msg, data->new_src, SADB_X_EXT_NEW_ADDRESS_SRC, 0, 0,
2045 FALSE);
2046 }
2047 if (!id->dst->ip_equals(id->dst, data->new_dst))
2048 {
2049 add_addr_ext(msg, data->new_dst, SADB_X_EXT_NEW_ADDRESS_DST, 0, 0,
2050 FALSE);
2051 }
2052 #endif /*SADB_X_EXT_NEW_ADDRESS_SRC*/
2053
2054 free(out);
2055
2056 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2057 {
2058 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x",
2059 ntohl(id->spi));
2060 return FAILED;
2061 }
2062 else if (out->sadb_msg_errno)
2063 {
2064 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x: %s (%d)",
2065 ntohl(id->spi), strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2066 free(out);
2067 return FAILED;
2068 }
2069 free(out);
2070
2071 return SUCCESS;
2072 }
2073
2074 METHOD(kernel_ipsec_t, query_sa, status_t,
2075 private_kernel_pfkey_ipsec_t *this, kernel_ipsec_sa_id_t *id,
2076 kernel_ipsec_query_sa_t *data, uint64_t *bytes, uint64_t *packets,
2077 time_t *time)
2078 {
2079 unsigned char request[PFKEY_BUFFER_SIZE];
2080 struct sadb_msg *msg, *out;
2081 struct sadb_sa *sa;
2082 pfkey_msg_t response;
2083 size_t len;
2084
2085 memset(&request, 0, sizeof(request));
2086
2087 DBG2(DBG_KNL, "querying SAD entry with SPI %.8x", ntohl(id->spi));
2088
2089 msg = (struct sadb_msg*)request;
2090 msg->sadb_msg_version = PF_KEY_V2;
2091 msg->sadb_msg_type = SADB_GET;
2092 msg->sadb_msg_satype = proto2satype(id->proto);
2093 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2094
2095 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
2096 sa->sadb_sa_exttype = SADB_EXT_SA;
2097 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
2098 sa->sadb_sa_spi = id->spi;
2099 PFKEY_EXT_ADD(msg, sa);
2100
2101 /* the Linux Kernel doesn't care for the src address, but other systems do
2102 * (e.g. FreeBSD)
2103 */
2104 add_addr_ext(msg, id->src, SADB_EXT_ADDRESS_SRC, 0, 0, FALSE);
2105 add_addr_ext(msg, id->dst, SADB_EXT_ADDRESS_DST, 0, 0, FALSE);
2106
2107 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2108 {
2109 DBG1(DBG_KNL, "unable to query SAD entry with SPI %.8x",
2110 ntohl(id->spi));
2111 return FAILED;
2112 }
2113 else if (out->sadb_msg_errno)
2114 {
2115 DBG1(DBG_KNL, "unable to query SAD entry with SPI %.8x: %s (%d)",
2116 ntohl(id->spi), strerror(out->sadb_msg_errno),
2117 out->sadb_msg_errno);
2118 free(out);
2119 return FAILED;
2120 }
2121 else if (parse_pfkey_message(out, &response) != SUCCESS)
2122 {
2123 DBG1(DBG_KNL, "unable to query SAD entry with SPI %.8x",
2124 ntohl(id->spi));
2125 free(out);
2126 return FAILED;
2127 }
2128 if (bytes)
2129 {
2130 *bytes = response.lft_current->sadb_lifetime_bytes;
2131 }
2132 if (packets)
2133 {
2134 /* at least on Linux and FreeBSD this contains the number of packets */
2135 *packets = response.lft_current->sadb_lifetime_allocations;
2136 }
2137 if (time)
2138 {
2139 #ifdef __APPLE__
2140 /* OS X uses the "last" time of use in usetime */
2141 *time = response.lft_current->sadb_lifetime_usetime;
2142 #else /* !__APPLE__ */
2143 /* on Linux, sadb_lifetime_usetime is set to the "first" time of use,
2144 * which is actually correct according to PF_KEY. We have to query
2145 * policies for the last usetime. */
2146 *time = 0;
2147 #endif /* !__APPLE__ */
2148 }
2149
2150 free(out);
2151 return SUCCESS;
2152 }
2153
2154 METHOD(kernel_ipsec_t, del_sa, status_t,
2155 private_kernel_pfkey_ipsec_t *this, kernel_ipsec_sa_id_t *id,
2156 kernel_ipsec_del_sa_t *data)
2157 {
2158 unsigned char request[PFKEY_BUFFER_SIZE];
2159 struct sadb_msg *msg, *out;
2160 struct sadb_sa *sa;
2161 size_t len;
2162
2163 /* if IPComp was used, we first delete the additional IPComp SA */
2164 if (data->cpi)
2165 {
2166 kernel_ipsec_sa_id_t ipcomp_id = {
2167 .src = id->src,
2168 .dst = id->dst,
2169 .spi = htonl(ntohs(data->cpi)),
2170 .proto = IPPROTO_COMP,
2171 .mark = id->mark,
2172 };
2173 kernel_ipsec_del_sa_t ipcomp = { 0 };
2174 del_sa(this, &ipcomp_id, &ipcomp);
2175 }
2176
2177 memset(&request, 0, sizeof(request));
2178
2179 DBG2(DBG_KNL, "deleting SAD entry with SPI %.8x", ntohl(id->spi));
2180
2181 msg = (struct sadb_msg*)request;
2182 msg->sadb_msg_version = PF_KEY_V2;
2183 msg->sadb_msg_type = SADB_DELETE;
2184 msg->sadb_msg_satype = proto2satype(id->proto);
2185 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2186
2187 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
2188 sa->sadb_sa_exttype = SADB_EXT_SA;
2189 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
2190 sa->sadb_sa_spi = id->spi;
2191 PFKEY_EXT_ADD(msg, sa);
2192
2193 /* the Linux Kernel doesn't care for the src address, but other systems do
2194 * (e.g. FreeBSD)
2195 */
2196 add_addr_ext(msg, id->src, SADB_EXT_ADDRESS_SRC, 0, 0, FALSE);
2197 add_addr_ext(msg, id->dst, SADB_EXT_ADDRESS_DST, 0, 0, FALSE);
2198
2199 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2200 {
2201 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x",
2202 ntohl(id->spi));
2203 return FAILED;
2204 }
2205 else if (out->sadb_msg_errno)
2206 {
2207 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x: %s (%d)",
2208 ntohl(id->spi), strerror(out->sadb_msg_errno),
2209 out->sadb_msg_errno);
2210 free(out);
2211 return FAILED;
2212 }
2213
2214 DBG2(DBG_KNL, "deleted SAD entry with SPI %.8x", ntohl(id->spi));
2215 free(out);
2216 return SUCCESS;
2217 }
2218
2219 METHOD(kernel_ipsec_t, flush_sas, status_t,
2220 private_kernel_pfkey_ipsec_t *this)
2221 {
2222 unsigned char request[PFKEY_BUFFER_SIZE];
2223 struct sadb_msg *msg, *out;
2224 struct {
2225 uint8_t proto;
2226 char *name;
2227 } protos[] = {
2228 { SADB_SATYPE_AH, "AH" },
2229 { SADB_SATYPE_ESP, "ESP" },
2230 { SADB_X_SATYPE_IPCOMP, "IPComp" },
2231 };
2232 size_t len;
2233 int i;
2234
2235 memset(&request, 0, sizeof(request));
2236
2237 msg = (struct sadb_msg*)request;
2238 msg->sadb_msg_version = PF_KEY_V2;
2239 msg->sadb_msg_type = SADB_FLUSH;
2240 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2241
2242 for (i = 0; i < countof(protos); i++)
2243 {
2244 DBG2(DBG_KNL, "flushing all %s SAD entries", protos[i].name);
2245
2246 msg->sadb_msg_satype = protos[i].proto;
2247 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2248 {
2249 DBG1(DBG_KNL, "unable to flush %s SAD entries", protos[i].name);
2250 return FAILED;
2251 }
2252 else if (out->sadb_msg_errno)
2253 {
2254 DBG1(DBG_KNL, "unable to flush %s SAD entries: %s (%d)",
2255 protos[i].name, strerror(out->sadb_msg_errno),
2256 out->sadb_msg_errno);
2257 free(out);
2258 return FAILED;
2259 }
2260 free(out);
2261 }
2262 return SUCCESS;
2263 }
2264
2265 /**
2266 * Add an explicit exclude route to a routing entry
2267 */
2268 static void add_exclude_route(private_kernel_pfkey_ipsec_t *this,
2269 route_entry_t *route, host_t *src, host_t *dst)
2270 {
2271 enumerator_t *enumerator;
2272 exclude_route_t *exclude;
2273 host_t *gtw;
2274
2275 enumerator = this->excludes->create_enumerator(this->excludes);
2276 while (enumerator->enumerate(enumerator, &exclude))
2277 {
2278 if (dst->ip_equals(dst, exclude->dst))
2279 {
2280 route->exclude = exclude;
2281 exclude->refs++;
2282 }
2283 }
2284 enumerator->destroy(enumerator);
2285
2286 if (!route->exclude)
2287 {
2288 DBG2(DBG_KNL, "installing new exclude route for %H src %H", dst, src);
2289 gtw = charon->kernel->get_nexthop(charon->kernel, dst, -1, NULL, NULL);
2290 if (gtw)
2291 {
2292 char *if_name = NULL;
2293
2294 if (charon->kernel->get_interface(charon->kernel, src, &if_name) &&
2295 charon->kernel->add_route(charon->kernel,
2296 dst->get_address(dst),
2297 dst->get_family(dst) == AF_INET ? 32 : 128,
2298 gtw, src, if_name) == SUCCESS)
2299 {
2300 INIT(exclude,
2301 .dst = dst->clone(dst),
2302 .src = src->clone(src),
2303 .gtw = gtw->clone(gtw),
2304 .refs = 1,
2305 );
2306 route->exclude = exclude;
2307 this->excludes->insert_last(this->excludes, exclude);
2308 }
2309 else
2310 {
2311 DBG1(DBG_KNL, "installing exclude route for %H failed", dst);
2312 }
2313 gtw->destroy(gtw);
2314 free(if_name);
2315 }
2316 else
2317 {
2318 DBG1(DBG_KNL, "gateway lookup for for %H failed", dst);
2319 }
2320 }
2321 }
2322
2323 /**
2324 * Remove an exclude route attached to a routing entry
2325 */
2326 static void remove_exclude_route(private_kernel_pfkey_ipsec_t *this,
2327 route_entry_t *route)
2328 {
2329 if (route->exclude)
2330 {
2331 enumerator_t *enumerator;
2332 exclude_route_t *exclude;
2333 bool removed = FALSE;
2334 host_t *dst;
2335
2336 enumerator = this->excludes->create_enumerator(this->excludes);
2337 while (enumerator->enumerate(enumerator, &exclude))
2338 {
2339 if (route->exclude == exclude)
2340 {
2341 if (--exclude->refs == 0)
2342 {
2343 this->excludes->remove_at(this->excludes, enumerator);
2344 removed = TRUE;
2345 break;
2346 }
2347 }
2348 }
2349 enumerator->destroy(enumerator);
2350
2351 if (removed)
2352 {
2353 char *if_name = NULL;
2354
2355 dst = route->exclude->dst;
2356 DBG2(DBG_KNL, "uninstalling exclude route for %H src %H",
2357 dst, route->exclude->src);
2358 if (charon->kernel->get_interface(
2359 charon->kernel,
2360 route->exclude->src, &if_name) &&
2361 charon->kernel->del_route(charon->kernel,
2362 dst->get_address(dst),
2363 dst->get_family(dst) == AF_INET ? 32 : 128,
2364 route->exclude->gtw, route->exclude->src,
2365 if_name) != SUCCESS)
2366 {
2367 DBG1(DBG_KNL, "uninstalling exclude route for %H failed", dst);
2368 }
2369 exclude_route_destroy(route->exclude);
2370 free(if_name);
2371 }
2372 route->exclude = NULL;
2373 }
2374 }
2375
2376 /**
2377 * Try to install a route to the given outbound policy
2378 */
2379 static bool install_route(private_kernel_pfkey_ipsec_t *this,
2380 policy_entry_t *policy, policy_sa_out_t *out)
2381 {
2382 route_entry_t *route, *old;
2383 host_t *host, *src, *dst;
2384 bool is_virtual;
2385
2386 if (charon->kernel->get_address_by_ts(charon->kernel, out->src_ts, &host,
2387 &is_virtual) != SUCCESS)
2388 {
2389 return FALSE;
2390 }
2391
2392 INIT(route,
2393 .prefixlen = policy->dst.mask,
2394 .src_ip = host,
2395 .dst_net = chunk_clone(policy->dst.net->get_address(policy->dst.net)),
2396 );
2397
2398 src = out->generic.sa->src;
2399 dst = out->generic.sa->dst;
2400
2401 if (!dst->is_anyaddr(dst))
2402 {
2403 route->gateway = charon->kernel->get_nexthop(charon->kernel, dst, -1,
2404 src, &route->if_name);
2405
2406 /* if the IP is virtual, we install the route over the interface it has
2407 * been installed on. Otherwise we use the interface we use for IKE, as
2408 * this is required for example on Linux. */
2409 if (is_virtual || this->route_via_internal)
2410 {
2411 free(route->if_name);
2412 route->if_name = NULL;
2413 src = route->src_ip;
2414 }
2415 }
2416 else
2417 { /* for shunt policies */
2418 route->gateway = charon->kernel->get_nexthop(charon->kernel,
2419 policy->dst.net, policy->dst.mask,
2420 route->src_ip, &route->if_name);
2421
2422 /* we don't have a source address, use the address we found */
2423 src = route->src_ip;
2424 }
2425
2426 /* get interface for route, using source address */
2427 if (!route->if_name &&
2428 !charon->kernel->get_interface(charon->kernel, src, &route->if_name))
2429 {
2430 route_entry_destroy(route);
2431 return FALSE;
2432 }
2433
2434 if (policy->route)
2435 {
2436 old = policy->route;
2437
2438 if (route_entry_equals(old, route))
2439 { /* such a route already exists */
2440 route_entry_destroy(route);
2441 return TRUE;
2442 }
2443 /* uninstall previously installed route */
2444 if (charon->kernel->del_route(charon->kernel, old->dst_net,
2445 old->prefixlen, old->gateway,
2446 old->src_ip, old->if_name) != SUCCESS)
2447 {
2448 DBG1(DBG_KNL, "error uninstalling route installed with policy "
2449 "%R === %R %N", out->src_ts, out->dst_ts,
2450 policy_dir_names, policy->direction);
2451 }
2452 route_entry_destroy(old);
2453 policy->route = NULL;
2454 }
2455
2456 /* if remote traffic selector covers the IKE peer, add an exclude route */
2457 if (charon->kernel->get_features(charon->kernel) & KERNEL_REQUIRE_EXCLUDE_ROUTE)
2458 {
2459 if (out->dst_ts->is_host(out->dst_ts, dst))
2460 {
2461 DBG1(DBG_KNL, "can't install route for %R === %R %N, conflicts "
2462 "with IKE traffic", out->src_ts, out->dst_ts, policy_dir_names,
2463 policy->direction);
2464 route_entry_destroy(route);
2465 return FALSE;
2466 }
2467 if (out->dst_ts->includes(out->dst_ts, dst))
2468 {
2469 add_exclude_route(this, route, out->generic.sa->src, dst);
2470 }
2471 }
2472
2473 DBG2(DBG_KNL, "installing route: %R via %H src %H dev %s",
2474 out->dst_ts, route->gateway, route->src_ip, route->if_name);
2475
2476 switch (charon->kernel->add_route(charon->kernel, route->dst_net,
2477 route->prefixlen, route->gateway,
2478 route->src_ip, route->if_name))
2479 {
2480 case ALREADY_DONE:
2481 /* route exists, do not uninstall */
2482 remove_exclude_route(this, route);
2483 route_entry_destroy(route);
2484 return TRUE;
2485 case SUCCESS:
2486 /* cache the installed route */
2487 policy->route = route;
2488 return TRUE;
2489 default:
2490 DBG1(DBG_KNL, "installing route failed: %R via %H src %H dev %s",
2491 out->dst_ts, route->gateway, route->src_ip, route->if_name);
2492 remove_exclude_route(this, route);
2493 route_entry_destroy(route);
2494 return FALSE;
2495 }
2496 }
2497
2498 /**
2499 * Check if any significant data has changed to warrant sending an update to
2500 * the kernel.
2501 */
2502 static bool policy_update_required(policy_sa_t *current, policy_sa_t *updated)
2503 {
2504 if (current->type != updated->type
2505 #ifdef HAVE_STRUCT_SADB_X_POLICY_SADB_X_POLICY_PRIORITY
2506 || current->priority != updated->priority
2507 #endif
2508 )
2509 {
2510 return TRUE;
2511 }
2512 if (current->type == POLICY_IPSEC)
2513 {
2514 ipsec_sa_cfg_t *cur = &current->sa->cfg, *upd = &updated->sa->cfg;
2515
2516 /* we don't use ipsec_sa_cfg_equals() here as e.g. SPIs are not
2517 * relevant for this kernel interface, so we don't have to update the
2518 * policy during a rekeying */
2519 if (cur->mode != upd->mode ||
2520 cur->reqid != upd->reqid ||
2521 cur->esp.use != upd->esp.use ||
2522 cur->ah.use != upd->ah.use ||
2523 cur->ipcomp.transform != upd->ipcomp.transform)
2524 {
2525 return TRUE;
2526 }
2527 if (cur->mode == MODE_TUNNEL &&
2528 (!current->sa->src->ip_equals(current->sa->src, updated->sa->src) ||
2529 !current->sa->dst->ip_equals(current->sa->dst, updated->sa->dst)))
2530 {
2531 return TRUE;
2532 }
2533 }
2534 return FALSE;
2535 }
2536
2537 /**
2538 * Add or update a policy in the kernel.
2539 *
2540 * Note: The mutex has to be locked when entering this function.
2541 */
2542 static status_t add_policy_internal(private_kernel_pfkey_ipsec_t *this,
2543 policy_entry_t *policy, policy_sa_t *mapping, bool update)
2544 {
2545 unsigned char request[PFKEY_BUFFER_SIZE];
2546 struct sadb_msg *msg, *out;
2547 struct sadb_x_policy *pol;
2548 struct sadb_x_ipsecrequest *req;
2549 ipsec_sa_t *ipsec = mapping->sa;
2550 pfkey_msg_t response;
2551 size_t len;
2552 ipsec_mode_t proto_mode;
2553 status_t status;
2554
2555 memset(&request, 0, sizeof(request));
2556
2557 msg = (struct sadb_msg*)request;
2558 msg->sadb_msg_version = PF_KEY_V2;
2559 msg->sadb_msg_type = update ? SADB_X_SPDUPDATE : SADB_X_SPDADD;
2560 msg->sadb_msg_satype = 0;
2561 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2562
2563 pol = (struct sadb_x_policy*)PFKEY_EXT_ADD_NEXT(msg);
2564 pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2565 pol->sadb_x_policy_len = PFKEY_LEN(sizeof(struct sadb_x_policy));
2566 pol->sadb_x_policy_id = 0;
2567 pol->sadb_x_policy_dir = dir2kernel(policy->direction);
2568 pol->sadb_x_policy_type = type2kernel(mapping->type);
2569 #ifdef HAVE_STRUCT_SADB_X_POLICY_SADB_X_POLICY_PRIORITY
2570 pol->sadb_x_policy_priority = mapping->priority;
2571 #endif
2572
2573 if (mapping->type == POLICY_IPSEC && ipsec->cfg.reqid)
2574 {
2575 /* one or more sadb_x_ipsecrequest extensions are added to the
2576 * sadb_x_policy extension */
2577 proto_mode = ipsec->cfg.mode;
2578
2579 req = (struct sadb_x_ipsecrequest*)(pol + 1);
2580
2581 if (ipsec->cfg.ipcomp.transform != IPCOMP_NONE)
2582 {
2583 req->sadb_x_ipsecrequest_proto = IPPROTO_COMP;
2584
2585 /* !!! the length here MUST be in octets instead of 64 bit words */
2586 req->sadb_x_ipsecrequest_len = sizeof(struct sadb_x_ipsecrequest);
2587 req->sadb_x_ipsecrequest_mode = mode2kernel(ipsec->cfg.mode);
2588 req->sadb_x_ipsecrequest_reqid = ipsec->cfg.reqid;
2589 req->sadb_x_ipsecrequest_level = (policy->direction == POLICY_OUT) ?
2590 IPSEC_LEVEL_UNIQUE : IPSEC_LEVEL_USE;
2591 if (ipsec->cfg.mode == MODE_TUNNEL)
2592 {
2593 len = hostcpy(req + 1, ipsec->src, FALSE);
2594 req->sadb_x_ipsecrequest_len += len;
2595 len = hostcpy((char*)(req + 1) + len, ipsec->dst, FALSE);
2596 req->sadb_x_ipsecrequest_len += len;
2597 /* use transport mode for other SAs */
2598 proto_mode = MODE_TRANSPORT;
2599 }
2600
2601 pol->sadb_x_policy_len += PFKEY_LEN(req->sadb_x_ipsecrequest_len);
2602 req = (struct sadb_x_ipsecrequest*)((char*)(req) +
2603 req->sadb_x_ipsecrequest_len);
2604 }
2605
2606 req->sadb_x_ipsecrequest_proto = ipsec->cfg.esp.use ? IPPROTO_ESP
2607 : IPPROTO_AH;
2608 /* !!! the length here MUST be in octets instead of 64 bit words */
2609 req->sadb_x_ipsecrequest_len = sizeof(struct sadb_x_ipsecrequest);
2610 req->sadb_x_ipsecrequest_mode = mode2kernel(proto_mode);
2611 req->sadb_x_ipsecrequest_reqid = ipsec->cfg.reqid;
2612 req->sadb_x_ipsecrequest_level = IPSEC_LEVEL_UNIQUE;
2613 if (proto_mode == MODE_TUNNEL)
2614 {
2615 len = hostcpy(req + 1, ipsec->src, FALSE);
2616 req->sadb_x_ipsecrequest_len += len;
2617 len = hostcpy((char*)(req + 1) + len, ipsec->dst, FALSE);
2618 req->sadb_x_ipsecrequest_len += len;
2619 }
2620
2621 pol->sadb_x_policy_len += PFKEY_LEN(req->sadb_x_ipsecrequest_len);
2622 }
2623 PFKEY_EXT_ADD(msg, pol);
2624
2625 add_addr_ext(msg, policy->src.net, SADB_EXT_ADDRESS_SRC, policy->src.proto,
2626 policy->src.mask, TRUE);
2627 add_addr_ext(msg, policy->dst.net, SADB_EXT_ADDRESS_DST, policy->dst.proto,
2628 policy->dst.mask, TRUE);
2629
2630 #ifdef __FreeBSD__
2631 { /* on FreeBSD a lifetime has to be defined to be able to later query
2632 * the current use time. */
2633 struct sadb_lifetime *lft;
2634 lft = (struct sadb_lifetime*)PFKEY_EXT_ADD_NEXT(msg);
2635 lft->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2636 lft->sadb_lifetime_len = PFKEY_LEN(sizeof(struct sadb_lifetime));
2637 lft->sadb_lifetime_addtime = LONG_MAX;
2638 PFKEY_EXT_ADD(msg, lft);
2639 }
2640 #endif
2641
2642 this->mutex->unlock(this->mutex);
2643
2644 status = pfkey_send(this, msg, &out, &len);
2645 if (status == SUCCESS && !update && out->sadb_msg_errno == EEXIST)
2646 {
2647 DBG1(DBG_KNL, "policy already exists, try to update it");
2648 free(out);
2649 msg->sadb_msg_type = SADB_X_SPDUPDATE;
2650 status = pfkey_send(this, msg, &out, &len);
2651 }
2652 if (status != SUCCESS)
2653 {
2654 return FAILED;
2655 }
2656 else if (out->sadb_msg_errno)
2657 {
2658 DBG1(DBG_KNL, "unable to %s policy: %s (%d)",
2659 update ? "update" : "add", strerror(out->sadb_msg_errno),
2660 out->sadb_msg_errno);
2661 free(out);
2662 return FAILED;
2663 }
2664 else if (parse_pfkey_message(out, &response) != SUCCESS)
2665 {
2666 DBG1(DBG_KNL, "unable to %s policy: parsing response from kernel "
2667 "failed", update ? "update" : "add");
2668 free(out);
2669 return FAILED;
2670 }
2671
2672 /* we try to find the policy again and update the kernel index */
2673 this->mutex->lock(this->mutex);
2674 if (!this->policies->find_first(this->policies, NULL, (void**)&policy))
2675 {
2676 DBG2(DBG_KNL, "unable to update index, the policy is already gone, "
2677 "ignoring");
2678 this->mutex->unlock(this->mutex);
2679 free(out);
2680 return SUCCESS;
2681 }
2682 policy->index = response.x_policy->sadb_x_policy_id;
2683 free(out);
2684
2685 /* install a route, if:
2686 * - this is an outbound policy (to just get one for each child)
2687 * - routing is not disabled via strongswan.conf
2688 * - the selector is not for a specific protocol/port
2689 * - we are in tunnel mode or install a bypass policy
2690 */
2691 if (policy->direction == POLICY_OUT && this->install_routes &&
2692 policy->src.proto == IPSEC_PROTO_ANY &&
2693 !policy->src.net->get_port(policy->src.net) &&
2694 !policy->dst.net->get_port(policy->dst.net))
2695 {
2696 if (mapping->type == POLICY_PASS ||
2697 (mapping->type == POLICY_IPSEC && ipsec->cfg.mode != MODE_TRANSPORT))
2698 {
2699 install_route(this, policy, (policy_sa_out_t*)mapping);
2700 }
2701 }
2702 this->mutex->unlock(this->mutex);
2703 return SUCCESS;
2704 }
2705
2706 METHOD(kernel_ipsec_t, add_policy, status_t,
2707 private_kernel_pfkey_ipsec_t *this, kernel_ipsec_policy_id_t *id,
2708 kernel_ipsec_manage_policy_t *data)
2709 {
2710 policy_entry_t *policy, *found = NULL;
2711 policy_sa_t *assigned_sa, *current_sa = NULL;
2712 enumerator_t *enumerator;
2713 bool update = TRUE;
2714
2715 if (dir2kernel(id->dir) == IPSEC_DIR_INVALID)
2716 { /* FWD policies are not supported on all platforms */
2717 return SUCCESS;
2718 }
2719
2720 /* create a policy */
2721 policy = create_policy_entry(id->src_ts, id->dst_ts, id->dir);
2722
2723 /* find a matching policy */
2724 this->mutex->lock(this->mutex);
2725 if (this->policies->find_first(this->policies, policy_entry_equals,
2726 (void**)&found, policy))
2727 { /* use existing policy */
2728 DBG2(DBG_KNL, "policy %R === %R %N already exists, increasing "
2729 "refcount", id->src_ts, id->dst_ts, policy_dir_names, id->dir);
2730 policy_entry_destroy(policy, this);
2731 policy = found;
2732 }
2733 else
2734 { /* use the new one, if we have no such policy */
2735 this->policies->insert_first(this->policies, policy);
2736 policy->used_by = linked_list_create();
2737 }
2738
2739 /* cache the assigned IPsec SA */
2740 assigned_sa = policy_sa_create(this, id->dir, data->type, data->src,
2741 data->dst, id->src_ts, id->dst_ts, data->sa);
2742 assigned_sa->auto_priority = get_priority(policy, data->prio);
2743 assigned_sa->priority = data->manual_prio ? data->manual_prio :
2744 assigned_sa->auto_priority;
2745
2746
2747 /* insert the SA according to its priority */
2748 enumerator = policy->used_by->create_enumerator(policy->used_by);
2749 while (enumerator->enumerate(enumerator, (void**)&current_sa))
2750 {
2751 if (current_sa->priority > assigned_sa->priority)
2752 {
2753 break;
2754 }
2755 if (current_sa->priority == assigned_sa->priority)
2756 {
2757 /* in case of equal manual prios order SAs by automatic priority */
2758 if (current_sa->auto_priority > assigned_sa->auto_priority)
2759 {
2760 break;
2761 }
2762 /* prefer SAs with a reqid over those without */
2763 if (current_sa->auto_priority == assigned_sa->auto_priority &&
2764 (!current_sa->sa->cfg.reqid || assigned_sa->sa->cfg.reqid))
2765 {
2766 break;
2767 }
2768 }
2769 update = FALSE;
2770 }
2771 policy->used_by->insert_before(policy->used_by, enumerator, assigned_sa);
2772 enumerator->destroy(enumerator);
2773
2774 if (update && current_sa)
2775 { /* check if there are actually any relevant changes, if not, we don't
2776 * send an update to the kernel as e.g. FreeBSD doesn't do that
2777 * atomically, causing unnecessary traffic loss during rekeyings */
2778 update = policy_update_required(current_sa, assigned_sa);
2779 }
2780
2781 if (!update)
2782 { /* we don't update the policy if the priority is lower than that of the
2783 * currently installed one */
2784 this->mutex->unlock(this->mutex);
2785 return SUCCESS;
2786 }
2787
2788 DBG2(DBG_KNL, "%s policy %R === %R %N",
2789 found ? "updating" : "adding", id->src_ts, id->dst_ts,
2790 policy_dir_names, id->dir);
2791
2792 if (add_policy_internal(this, policy, assigned_sa, found) != SUCCESS)
2793 {
2794 DBG1(DBG_KNL, "unable to %s policy %R === %R %N",
2795 found ? "update" : "add", id->src_ts, id->dst_ts,
2796 policy_dir_names, id->dir);
2797 return FAILED;
2798 }
2799 return SUCCESS;
2800 }
2801
2802 METHOD(kernel_ipsec_t, query_policy, status_t,
2803 private_kernel_pfkey_ipsec_t *this, kernel_ipsec_policy_id_t *id,
2804 kernel_ipsec_query_policy_t *data, time_t *use_time)
2805 {
2806 unsigned char request[PFKEY_BUFFER_SIZE];
2807 struct sadb_msg *msg, *out;
2808 struct sadb_x_policy *pol;
2809 policy_entry_t *policy, *found = NULL;
2810 pfkey_msg_t response;
2811 size_t len;
2812
2813 if (dir2kernel(id->dir) == IPSEC_DIR_INVALID)
2814 { /* FWD policies are not supported on all platforms */
2815 return NOT_FOUND;
2816 }
2817
2818 DBG2(DBG_KNL, "querying policy %R === %R %N", id->src_ts, id->dst_ts,
2819 policy_dir_names, id->dir);
2820
2821 /* create a policy */
2822 policy = create_policy_entry(id->src_ts, id->dst_ts, id->dir);
2823
2824 /* find a matching policy */
2825 this->mutex->lock(this->mutex);
2826 if (!this->policies->find_first(this->policies, policy_entry_equals,
2827 (void**)&found, policy))
2828 {
2829 DBG1(DBG_KNL, "querying policy %R === %R %N failed, not found",
2830 id->src_ts, id->dst_ts, policy_dir_names, id->dir);
2831 policy_entry_destroy(policy, this);
2832 this->mutex->unlock(this->mutex);
2833 return NOT_FOUND;
2834 }
2835 policy_entry_destroy(policy, this);
2836 policy = found;
2837
2838 memset(&request, 0, sizeof(request));
2839
2840 msg = (struct sadb_msg*)request;
2841 msg->sadb_msg_version = PF_KEY_V2;
2842 msg->sadb_msg_type = SADB_X_SPDGET;
2843 msg->sadb_msg_satype = 0;
2844 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2845
2846 pol = (struct sadb_x_policy*)PFKEY_EXT_ADD_NEXT(msg);
2847 pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2848 pol->sadb_x_policy_id = policy->index;
2849 pol->sadb_x_policy_len = PFKEY_LEN(sizeof(struct sadb_x_policy));
2850 pol->sadb_x_policy_dir = dir2kernel(id->dir);
2851 pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC;
2852 PFKEY_EXT_ADD(msg, pol);
2853
2854 add_addr_ext(msg, policy->src.net, SADB_EXT_ADDRESS_SRC, policy->src.proto,
2855 policy->src.mask, TRUE);
2856 add_addr_ext(msg, policy->dst.net, SADB_EXT_ADDRESS_DST, policy->dst.proto,
2857 policy->dst.mask, TRUE);
2858
2859 this->mutex->unlock(this->mutex);
2860
2861 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2862 {
2863 DBG1(DBG_KNL, "unable to query policy %R === %R %N", id->src_ts,
2864 id->dst_ts, policy_dir_names, id->dir);
2865 return FAILED;
2866 }
2867 else if (out->sadb_msg_errno)
2868 {
2869 DBG1(DBG_KNL, "unable to query policy %R === %R %N: %s (%d)",
2870 id->src_ts, id->dst_ts, policy_dir_names, id->dir,
2871 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2872 free(out);
2873 return FAILED;
2874 }
2875 else if (parse_pfkey_message(out, &response) != SUCCESS)
2876 {
2877 DBG1(DBG_KNL, "unable to query policy %R === %R %N: parsing response "
2878 "from kernel failed", id->src_ts, id->dst_ts, policy_dir_names,
2879 id->dir);
2880 free(out);
2881 return FAILED;
2882 }
2883 else if (response.lft_current == NULL)
2884 {
2885 DBG2(DBG_KNL, "unable to query policy %R === %R %N: kernel reports no "
2886 "use time", id->src_ts, id->dst_ts, policy_dir_names,
2887 id->dir);
2888 free(out);
2889 return FAILED;
2890 }
2891
2892 /* we need the monotonic time, but the kernel returns system time. */
2893 if (response.lft_current->sadb_lifetime_usetime)
2894 {
2895 *use_time = time_monotonic(NULL) -
2896 (time(NULL) - response.lft_current->sadb_lifetime_usetime);
2897 }
2898 else
2899 {
2900 *use_time = 0;
2901 }
2902 free(out);
2903 return SUCCESS;
2904 }
2905
2906 METHOD(kernel_ipsec_t, del_policy, status_t,
2907 private_kernel_pfkey_ipsec_t *this, kernel_ipsec_policy_id_t *id,