b937a769ec57d9678e03d803c43d858641b2b934
[strongswan.git] / src / libcharon / plugins / kernel_pfkey / kernel_pfkey_ipsec.c
1 /*
2 * Copyright (C) 2008-2017 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 #endif
894 #ifdef SADB_X_EALG_CAMELLIACBC
895 {ENCR_CAMELLIA_CBC, SADB_X_EALG_CAMELLIACBC },
896 #endif
897 {END_OF_LIST, 0 },
898 };
899
900 /**
901 * Algorithms for integrity protection
902 */
903 static kernel_algorithm_t integrity_algs[] = {
904 {AUTH_HMAC_MD5_96, SADB_AALG_MD5HMAC },
905 {AUTH_HMAC_SHA1_96, SADB_AALG_SHA1HMAC },
906 {AUTH_HMAC_SHA2_256_128, SADB_X_AALG_SHA2_256HMAC },
907 {AUTH_HMAC_SHA2_384_192, SADB_X_AALG_SHA2_384HMAC },
908 {AUTH_HMAC_SHA2_512_256, SADB_X_AALG_SHA2_512HMAC },
909 /* {AUTH_DES_MAC, 0, }, */
910 /* {AUTH_KPDK_MD5, 0, }, */
911 #ifdef SADB_X_AALG_AES_XCBC_MAC
912 {AUTH_AES_XCBC_96, SADB_X_AALG_AES_XCBC_MAC, },
913 #endif
914 {END_OF_LIST, 0, },
915 };
916
917 /**
918 * Algorithms for IPComp, unused yet
919 */
920 static kernel_algorithm_t compression_algs[] = {
921 /* {IPCOMP_OUI, 0 }, */
922 {IPCOMP_DEFLATE, SADB_X_CALG_DEFLATE },
923 #ifdef SADB_X_CALG_LZS
924 {IPCOMP_LZS, SADB_X_CALG_LZS },
925 #endif
926 #ifdef SADB_X_CALG_LZJH
927 {IPCOMP_LZJH, SADB_X_CALG_LZJH },
928 #endif
929 {END_OF_LIST, 0 },
930 };
931
932 /**
933 * Look up a kernel algorithm ID and its key size
934 */
935 static int lookup_algorithm(transform_type_t type, int ikev2)
936 {
937 kernel_algorithm_t *list;
938 uint16_t alg = 0;
939
940 switch (type)
941 {
942 case ENCRYPTION_ALGORITHM:
943 list = encryption_algs;
944 break;
945 case INTEGRITY_ALGORITHM:
946 list = integrity_algs;
947 break;
948 case COMPRESSION_ALGORITHM:
949 list = compression_algs;
950 break;
951 default:
952 return 0;
953 }
954 while (list->ikev2 != END_OF_LIST)
955 {
956 if (ikev2 == list->ikev2)
957 {
958 return list->kernel;
959 }
960 list++;
961 }
962 charon->kernel->lookup_algorithm(charon->kernel, ikev2, type, &alg, NULL);
963 return alg;
964 }
965
966 /**
967 * Helper to set a port in a sockaddr_t, the port has to be in host order
968 */
969 static void set_port(sockaddr_t *addr, uint16_t port)
970 {
971 switch (addr->sa_family)
972 {
973 case AF_INET:
974 {
975 struct sockaddr_in *sin = (struct sockaddr_in*)addr;
976 sin->sin_port = htons(port);
977 break;
978 }
979 case AF_INET6:
980 {
981 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)addr;
982 sin6->sin6_port = htons(port);
983 break;
984 }
985 }
986 }
987
988 /**
989 * Copy a host_t as sockaddr_t to the given memory location.
990 * @return the number of bytes copied
991 */
992 static size_t hostcpy(void *dest, host_t *host, bool include_port)
993 {
994 sockaddr_t *addr = host->get_sockaddr(host), *dest_addr = dest;
995 socklen_t *len = host->get_sockaddr_len(host);
996
997 memcpy(dest, addr, *len);
998 #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
999 dest_addr->sa_len = *len;
1000 #endif
1001 if (!include_port)
1002 {
1003 set_port(dest_addr, 0);
1004 }
1005 return *len;
1006 }
1007
1008 /**
1009 * add a host to the given sadb_msg
1010 */
1011 static void add_addr_ext(struct sadb_msg *msg, host_t *host, uint16_t type,
1012 uint8_t proto, uint8_t prefixlen, bool include_port)
1013 {
1014 struct sadb_address *addr = (struct sadb_address*)PFKEY_EXT_ADD_NEXT(msg);
1015 size_t len;
1016
1017 addr->sadb_address_exttype = type;
1018 addr->sadb_address_proto = proto;
1019 addr->sadb_address_prefixlen = prefixlen;
1020 len = hostcpy(addr + 1, host, include_port);
1021 addr->sadb_address_len = PFKEY_LEN(sizeof(*addr) + len);
1022 PFKEY_EXT_ADD(msg, addr);
1023 }
1024
1025 #ifdef HAVE_NATT
1026 /**
1027 * add udp encap extensions to a sadb_msg
1028 */
1029 static void add_encap_ext(struct sadb_msg *msg, host_t *src, host_t *dst)
1030 {
1031 struct sadb_x_nat_t_type* nat_type;
1032 struct sadb_x_nat_t_port* nat_port;
1033
1034 nat_type = (struct sadb_x_nat_t_type*)PFKEY_EXT_ADD_NEXT(msg);
1035 nat_type->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
1036 nat_type->sadb_x_nat_t_type_len = PFKEY_LEN(sizeof(*nat_type));
1037 nat_type->sadb_x_nat_t_type_type = UDP_ENCAP_ESPINUDP;
1038 PFKEY_EXT_ADD(msg, nat_type);
1039
1040 nat_port = (struct sadb_x_nat_t_port*)PFKEY_EXT_ADD_NEXT(msg);
1041 nat_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_SPORT;
1042 nat_port->sadb_x_nat_t_port_len = PFKEY_LEN(sizeof(*nat_port));
1043 nat_port->sadb_x_nat_t_port_port = htons(src->get_port(src));
1044 PFKEY_EXT_ADD(msg, nat_port);
1045
1046 nat_port = (struct sadb_x_nat_t_port*)PFKEY_EXT_ADD_NEXT(msg);
1047 nat_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_DPORT;
1048 nat_port->sadb_x_nat_t_port_len = PFKEY_LEN(sizeof(*nat_port));
1049 nat_port->sadb_x_nat_t_port_port = htons(dst->get_port(dst));
1050 PFKEY_EXT_ADD(msg, nat_port);
1051 }
1052 #endif /*HAVE_NATT*/
1053
1054 /**
1055 * Convert a sadb_address to a traffic_selector
1056 */
1057 static traffic_selector_t* sadb_address2ts(struct sadb_address *address)
1058 {
1059 traffic_selector_t *ts;
1060 host_t *host;
1061 uint8_t proto;
1062
1063 proto = address->sadb_address_proto;
1064 proto = proto == IPSEC_PROTO_ANY ? 0 : proto;
1065
1066 /* The Linux 2.6 kernel does not set the protocol and port information
1067 * in the src and dst sadb_address extensions of the SADB_ACQUIRE message.
1068 */
1069 host = host_create_from_sockaddr((sockaddr_t*)&address[1]);
1070 ts = traffic_selector_create_from_subnet(host,
1071 address->sadb_address_prefixlen,
1072 proto, host->get_port(host),
1073 host->get_port(host) ?: 65535);
1074 return ts;
1075 }
1076
1077 /**
1078 * Parses a pfkey message received from the kernel
1079 */
1080 static status_t parse_pfkey_message(struct sadb_msg *msg, pfkey_msg_t *out)
1081 {
1082 struct sadb_ext* ext;
1083 size_t len;
1084
1085 memset(out, 0, sizeof(pfkey_msg_t));
1086 out->msg = msg;
1087
1088 len = msg->sadb_msg_len;
1089 len -= PFKEY_LEN(sizeof(struct sadb_msg));
1090
1091 ext = (struct sadb_ext*)(((char*)msg) + sizeof(struct sadb_msg));
1092
1093 while (len >= PFKEY_LEN(sizeof(struct sadb_ext)))
1094 {
1095 DBG3(DBG_KNL, " %N", sadb_ext_type_names, ext->sadb_ext_type);
1096 if (ext->sadb_ext_len < PFKEY_LEN(sizeof(struct sadb_ext)) ||
1097 ext->sadb_ext_len > len)
1098 {
1099 DBG1(DBG_KNL, "length of %N extension is invalid",
1100 sadb_ext_type_names, ext->sadb_ext_type);
1101 break;
1102 }
1103
1104 if ((ext->sadb_ext_type > SADB_EXT_MAX) || (!ext->sadb_ext_type))
1105 {
1106 DBG1(DBG_KNL, "type of PF_KEY extension (%d) is invalid",
1107 ext->sadb_ext_type);
1108 break;
1109 }
1110
1111 if (out->ext[ext->sadb_ext_type])
1112 {
1113 DBG1(DBG_KNL, "duplicate %N extension",
1114 sadb_ext_type_names, ext->sadb_ext_type);
1115 break;
1116 }
1117
1118 out->ext[ext->sadb_ext_type] = ext;
1119 ext = PFKEY_EXT_NEXT_LEN(ext, len);
1120 }
1121
1122 if (len)
1123 {
1124 DBG1(DBG_KNL, "PF_KEY message length is invalid");
1125 return FAILED;
1126 }
1127
1128 return SUCCESS;
1129 }
1130
1131 /**
1132 * Send a message to a specific PF_KEY socket and handle the response.
1133 */
1134 static status_t pfkey_send_socket(private_kernel_pfkey_ipsec_t *this, int socket,
1135 struct sadb_msg *in, struct sadb_msg **out, size_t *out_len)
1136 {
1137 unsigned char buf[PFKEY_BUFFER_SIZE];
1138 struct sadb_msg *msg;
1139 int in_len, len;
1140
1141 this->mutex_pfkey->lock(this->mutex_pfkey);
1142
1143 /* FIXME: our usage of sequence numbers is probably wrong. check RFC 2367,
1144 * in particular the behavior in response to an SADB_ACQUIRE. */
1145 in->sadb_msg_seq = ++this->seq;
1146 in->sadb_msg_pid = getpid();
1147
1148 in_len = PFKEY_USER_LEN(in->sadb_msg_len);
1149
1150 while (TRUE)
1151 {
1152 len = send(socket, in, in_len, 0);
1153
1154 if (len != in_len)
1155 {
1156 if (errno == EINTR)
1157 {
1158 /* interrupted, try again */
1159 continue;
1160 }
1161 this->mutex_pfkey->unlock(this->mutex_pfkey);
1162 DBG1(DBG_KNL, "error sending to PF_KEY socket: %s",
1163 strerror(errno));
1164 return FAILED;
1165 }
1166 break;
1167 }
1168
1169 while (TRUE)
1170 {
1171 msg = (struct sadb_msg*)buf;
1172
1173 len = recv(socket, buf, sizeof(buf), 0);
1174
1175 if (len < 0)
1176 {
1177 if (errno == EINTR)
1178 {
1179 DBG1(DBG_KNL, "got interrupted");
1180 /* interrupted, try again */
1181 continue;
1182 }
1183 DBG1(DBG_KNL, "error reading from PF_KEY socket: %s",
1184 strerror(errno));
1185 this->mutex_pfkey->unlock(this->mutex_pfkey);
1186 return FAILED;
1187 }
1188 if (len < sizeof(struct sadb_msg) ||
1189 msg->sadb_msg_len < PFKEY_LEN(sizeof(struct sadb_msg)))
1190 {
1191 DBG1(DBG_KNL, "received corrupted PF_KEY message");
1192 this->mutex_pfkey->unlock(this->mutex_pfkey);
1193 return FAILED;
1194 }
1195 if (msg->sadb_msg_len > len / PFKEY_ALIGNMENT)
1196 {
1197 DBG1(DBG_KNL, "buffer was too small to receive the complete PF_KEY "
1198 "message");
1199 this->mutex_pfkey->unlock(this->mutex_pfkey);
1200 return FAILED;
1201 }
1202 if (msg->sadb_msg_pid != in->sadb_msg_pid)
1203 {
1204 DBG2(DBG_KNL, "received PF_KEY message is not intended for us");
1205 continue;
1206 }
1207 if (msg->sadb_msg_seq != this->seq)
1208 {
1209 DBG2(DBG_KNL, "received PF_KEY message with unexpected sequence "
1210 "number, was %d expected %d", msg->sadb_msg_seq,
1211 this->seq);
1212 if (msg->sadb_msg_seq == 0)
1213 {
1214 /* FreeBSD and Mac OS X do this for the response to
1215 * SADB_X_SPDGET (but not for the response to SADB_GET).
1216 * FreeBSD: 'key_spdget' in /usr/src/sys/netipsec/key.c. */
1217 }
1218 else if (msg->sadb_msg_seq < this->seq)
1219 {
1220 continue;
1221 }
1222 else
1223 {
1224 this->mutex_pfkey->unlock(this->mutex_pfkey);
1225 return FAILED;
1226 }
1227 }
1228 if (msg->sadb_msg_type != in->sadb_msg_type)
1229 {
1230 DBG2(DBG_KNL, "received PF_KEY message of wrong type, "
1231 "was %d expected %d, ignoring", msg->sadb_msg_type,
1232 in->sadb_msg_type);
1233 }
1234 break;
1235 }
1236
1237 *out_len = len;
1238 *out = (struct sadb_msg*)malloc(len);
1239 memcpy(*out, buf, len);
1240
1241 this->mutex_pfkey->unlock(this->mutex_pfkey);
1242 return SUCCESS;
1243 }
1244
1245 /**
1246 * Send a message to the default PF_KEY socket and handle the response.
1247 */
1248 static status_t pfkey_send(private_kernel_pfkey_ipsec_t *this,
1249 struct sadb_msg *in, struct sadb_msg **out,
1250 size_t *out_len)
1251 {
1252 return pfkey_send_socket(this, this->socket, in, out, out_len);
1253 }
1254
1255 /**
1256 * Process a SADB_ACQUIRE message from the kernel
1257 */
1258 static void process_acquire(private_kernel_pfkey_ipsec_t *this,
1259 struct sadb_msg* msg)
1260 {
1261 pfkey_msg_t response;
1262 uint32_t index, reqid = 0;
1263 traffic_selector_t *src_ts, *dst_ts;
1264 policy_entry_t *policy;
1265 policy_sa_t *sa;
1266
1267 switch (msg->sadb_msg_satype)
1268 {
1269 case SADB_SATYPE_UNSPEC:
1270 case SADB_SATYPE_ESP:
1271 case SADB_SATYPE_AH:
1272 break;
1273 default:
1274 /* acquire for AH/ESP only */
1275 return;
1276 }
1277 DBG2(DBG_KNL, "received an SADB_ACQUIRE");
1278
1279 if (parse_pfkey_message(msg, &response) != SUCCESS)
1280 {
1281 DBG1(DBG_KNL, "parsing SADB_ACQUIRE from kernel failed");
1282 return;
1283 }
1284
1285 index = response.x_policy->sadb_x_policy_id;
1286 this->mutex->lock(this->mutex);
1287 if (this->policies->find_first(this->policies, policy_entry_match_byindex,
1288 (void**)&policy, index) &&
1289 policy->used_by->get_first(policy->used_by, (void**)&sa) == SUCCESS)
1290 {
1291 reqid = sa->sa->cfg.reqid;
1292 }
1293 else
1294 {
1295 DBG1(DBG_KNL, "received an SADB_ACQUIRE with policy id %d but no "
1296 "matching policy found", index);
1297 }
1298 this->mutex->unlock(this->mutex);
1299
1300 src_ts = sadb_address2ts(response.src);
1301 dst_ts = sadb_address2ts(response.dst);
1302
1303 charon->kernel->acquire(charon->kernel, reqid, src_ts, dst_ts);
1304 }
1305
1306 /**
1307 * Process a SADB_EXPIRE message from the kernel
1308 */
1309 static void process_expire(private_kernel_pfkey_ipsec_t *this,
1310 struct sadb_msg* msg)
1311 {
1312 pfkey_msg_t response;
1313 uint8_t protocol;
1314 uint32_t spi;
1315 host_t *dst;
1316 bool hard;
1317
1318 DBG2(DBG_KNL, "received an SADB_EXPIRE");
1319
1320 if (parse_pfkey_message(msg, &response) != SUCCESS)
1321 {
1322 DBG1(DBG_KNL, "parsing SADB_EXPIRE from kernel failed");
1323 return;
1324 }
1325
1326 protocol = satype2proto(msg->sadb_msg_satype);
1327 spi = response.sa->sadb_sa_spi;
1328 hard = response.lft_hard != NULL;
1329
1330 if (protocol == IPPROTO_ESP || protocol == IPPROTO_AH)
1331 {
1332 dst = host_create_from_sockaddr((sockaddr_t*)(response.dst + 1));
1333 if (dst)
1334 {
1335 charon->kernel->expire(charon->kernel, protocol, spi, dst, hard);
1336 dst->destroy(dst);
1337 }
1338 }
1339 }
1340
1341 #ifdef SADB_X_MIGRATE
1342 /**
1343 * Process a SADB_X_MIGRATE message from the kernel
1344 */
1345 static void process_migrate(private_kernel_pfkey_ipsec_t *this,
1346 struct sadb_msg* msg)
1347 {
1348 pfkey_msg_t response;
1349 traffic_selector_t *src_ts, *dst_ts;
1350 policy_dir_t dir;
1351 uint32_t reqid = 0;
1352 host_t *local = NULL, *remote = NULL;
1353
1354 DBG2(DBG_KNL, "received an SADB_X_MIGRATE");
1355
1356 if (parse_pfkey_message(msg, &response) != SUCCESS)
1357 {
1358 DBG1(DBG_KNL, "parsing SADB_X_MIGRATE from kernel failed");
1359 return;
1360 }
1361 src_ts = sadb_address2ts(response.src);
1362 dst_ts = sadb_address2ts(response.dst);
1363 dir = kernel2dir(response.x_policy->sadb_x_policy_dir);
1364 DBG2(DBG_KNL, " policy %R === %R %N, id %u", src_ts, dst_ts,
1365 policy_dir_names, dir);
1366
1367 /* SADB_X_EXT_KMADDRESS is not present in unpatched kernels < 2.6.28 */
1368 if (response.x_kmaddress)
1369 {
1370 sockaddr_t *local_addr, *remote_addr;
1371 uint32_t local_len;
1372
1373 local_addr = (sockaddr_t*)&response.x_kmaddress[1];
1374 local = host_create_from_sockaddr(local_addr);
1375 local_len = (local_addr->sa_family == AF_INET6)?
1376 sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in);
1377 remote_addr = (sockaddr_t*)((uint8_t*)local_addr + local_len);
1378 remote = host_create_from_sockaddr(remote_addr);
1379 DBG2(DBG_KNL, " kmaddress: %H...%H", local, remote);
1380 }
1381
1382 if (src_ts && dst_ts && local && remote)
1383 {
1384 charon->kernel->migrate(charon->kernel, reqid, src_ts, dst_ts, dir,
1385 local, remote);
1386 }
1387 else
1388 {
1389 DESTROY_IF(src_ts);
1390 DESTROY_IF(dst_ts);
1391 DESTROY_IF(local);
1392 DESTROY_IF(remote);
1393 }
1394 }
1395 #endif /*SADB_X_MIGRATE*/
1396
1397 #ifdef SADB_X_NAT_T_NEW_MAPPING
1398 /**
1399 * Process a SADB_X_NAT_T_NEW_MAPPING message from the kernel
1400 */
1401 static void process_mapping(private_kernel_pfkey_ipsec_t *this,
1402 struct sadb_msg* msg)
1403 {
1404 pfkey_msg_t response;
1405 uint32_t spi;
1406 sockaddr_t *sa;
1407 host_t *dst, *new;
1408
1409 DBG2(DBG_KNL, "received an SADB_X_NAT_T_NEW_MAPPING");
1410
1411 if (parse_pfkey_message(msg, &response) != SUCCESS)
1412 {
1413 DBG1(DBG_KNL, "parsing SADB_X_NAT_T_NEW_MAPPING from kernel failed");
1414 return;
1415 }
1416
1417 if (!response.x_sa2)
1418 {
1419 DBG1(DBG_KNL, "received SADB_X_NAT_T_NEW_MAPPING is missing required "
1420 "information");
1421 return;
1422 }
1423
1424 spi = response.sa->sadb_sa_spi;
1425
1426 if (satype2proto(msg->sadb_msg_satype) != IPPROTO_ESP)
1427 {
1428 return;
1429 }
1430
1431 sa = (sockaddr_t*)(response.dst + 1);
1432 dst = host_create_from_sockaddr(sa);
1433 switch (sa->sa_family)
1434 {
1435 case AF_INET:
1436 {
1437 struct sockaddr_in *sin = (struct sockaddr_in*)sa;
1438 sin->sin_port = htons(response.x_natt_dport->sadb_x_nat_t_port_port);
1439 break;
1440 }
1441 case AF_INET6:
1442 {
1443 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)sa;
1444 sin6->sin6_port = htons(response.x_natt_dport->sadb_x_nat_t_port_port);
1445 break;
1446 }
1447 default:
1448 break;
1449 }
1450 if (dst)
1451 {
1452 new = host_create_from_sockaddr(sa);
1453 if (new)
1454 {
1455 charon->kernel->mapping(charon->kernel, IPPROTO_ESP, spi, dst, new);
1456 new->destroy(new);
1457 }
1458 dst->destroy(dst);
1459 }
1460 }
1461 #endif /*SADB_X_NAT_T_NEW_MAPPING*/
1462
1463 /**
1464 * Receives events from kernel
1465 */
1466 static bool receive_events(private_kernel_pfkey_ipsec_t *this, int fd,
1467 watcher_event_t event)
1468 {
1469 unsigned char buf[PFKEY_BUFFER_SIZE];
1470 struct sadb_msg *msg = (struct sadb_msg*)buf;
1471 int len;
1472
1473 len = recvfrom(this->socket_events, buf, sizeof(buf), MSG_DONTWAIT, NULL, 0);
1474 if (len < 0)
1475 {
1476 switch (errno)
1477 {
1478 case EINTR:
1479 /* interrupted, try again */
1480 return TRUE;
1481 case EAGAIN:
1482 /* no data ready, select again */
1483 return TRUE;
1484 default:
1485 DBG1(DBG_KNL, "unable to receive from PF_KEY event socket");
1486 sleep(1);
1487 return TRUE;
1488 }
1489 }
1490
1491 if (len < sizeof(struct sadb_msg) ||
1492 msg->sadb_msg_len < PFKEY_LEN(sizeof(struct sadb_msg)))
1493 {
1494 DBG2(DBG_KNL, "received corrupted PF_KEY message");
1495 return TRUE;
1496 }
1497 if (msg->sadb_msg_pid != 0)
1498 { /* not from kernel. not interested, try another one */
1499 return TRUE;
1500 }
1501 if (msg->sadb_msg_len > len / PFKEY_ALIGNMENT)
1502 {
1503 DBG1(DBG_KNL, "buffer was too small to receive the complete "
1504 "PF_KEY message");
1505 return TRUE;
1506 }
1507
1508 switch (msg->sadb_msg_type)
1509 {
1510 case SADB_ACQUIRE:
1511 process_acquire(this, msg);
1512 break;
1513 case SADB_EXPIRE:
1514 process_expire(this, msg);
1515 break;
1516 #ifdef SADB_X_MIGRATE
1517 case SADB_X_MIGRATE:
1518 process_migrate(this, msg);
1519 break;
1520 #endif /*SADB_X_MIGRATE*/
1521 #ifdef SADB_X_NAT_T_NEW_MAPPING
1522 case SADB_X_NAT_T_NEW_MAPPING:
1523 process_mapping(this, msg);
1524 break;
1525 #endif /*SADB_X_NAT_T_NEW_MAPPING*/
1526 default:
1527 break;
1528 }
1529
1530 return TRUE;
1531 }
1532
1533 /**
1534 * Get an SPI for a specific protocol from the kernel.
1535 */
1536
1537 static status_t get_spi_internal(private_kernel_pfkey_ipsec_t *this,
1538 host_t *src, host_t *dst, uint8_t proto, uint32_t min, uint32_t max,
1539 uint32_t *spi)
1540 {
1541 unsigned char request[PFKEY_BUFFER_SIZE];
1542 struct sadb_msg *msg, *out;
1543 struct sadb_spirange *range;
1544 pfkey_msg_t response;
1545 uint32_t received_spi = 0;
1546 size_t len;
1547
1548 memset(&request, 0, sizeof(request));
1549
1550 msg = (struct sadb_msg*)request;
1551 msg->sadb_msg_version = PF_KEY_V2;
1552 msg->sadb_msg_type = SADB_GETSPI;
1553 msg->sadb_msg_satype = proto2satype(proto);
1554 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1555
1556 add_addr_ext(msg, src, SADB_EXT_ADDRESS_SRC, 0, 0, FALSE);
1557 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST, 0, 0, FALSE);
1558
1559 range = (struct sadb_spirange*)PFKEY_EXT_ADD_NEXT(msg);
1560 range->sadb_spirange_exttype = SADB_EXT_SPIRANGE;
1561 range->sadb_spirange_len = PFKEY_LEN(sizeof(struct sadb_spirange));
1562 range->sadb_spirange_min = min;
1563 range->sadb_spirange_max = max;
1564 PFKEY_EXT_ADD(msg, range);
1565
1566 if (pfkey_send(this, msg, &out, &len) == SUCCESS)
1567 {
1568 if (out->sadb_msg_errno)
1569 {
1570 DBG1(DBG_KNL, "allocating SPI failed: %s (%d)",
1571 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1572 }
1573 else if (parse_pfkey_message(out, &response) == SUCCESS)
1574 {
1575 received_spi = response.sa->sadb_sa_spi;
1576 }
1577 free(out);
1578 }
1579
1580 if (received_spi == 0)
1581 {
1582 return FAILED;
1583 }
1584
1585 *spi = received_spi;
1586 return SUCCESS;
1587 }
1588
1589 METHOD(kernel_ipsec_t, get_spi, status_t,
1590 private_kernel_pfkey_ipsec_t *this, host_t *src, host_t *dst,
1591 uint8_t protocol, uint32_t *spi)
1592 {
1593 uint32_t spi_min, spi_max;
1594
1595 spi_min = lib->settings->get_int(lib->settings, "%s.spi_min",
1596 KERNEL_SPI_MIN, lib->ns);
1597 spi_max = lib->settings->get_int(lib->settings, "%s.spi_max",
1598 KERNEL_SPI_MAX, lib->ns);
1599
1600 if (get_spi_internal(this, src, dst, protocol, min(spi_min, spi_max),
1601 max(spi_min, spi_max), spi) != SUCCESS)
1602 {
1603 DBG1(DBG_KNL, "unable to get SPI");
1604 return FAILED;
1605 }
1606
1607 DBG2(DBG_KNL, "got SPI %.8x", ntohl(*spi));
1608 return SUCCESS;
1609 }
1610
1611 METHOD(kernel_ipsec_t, get_cpi, status_t,
1612 private_kernel_pfkey_ipsec_t *this, host_t *src, host_t *dst,
1613 uint16_t *cpi)
1614 {
1615 uint32_t received_spi = 0;
1616
1617 DBG2(DBG_KNL, "getting CPI");
1618
1619 if (get_spi_internal(this, src, dst, IPPROTO_COMP,
1620 0x100, 0xEFFF, &received_spi) != SUCCESS)
1621 {
1622 DBG1(DBG_KNL, "unable to get CPI");
1623 return FAILED;
1624 }
1625
1626 *cpi = htons((uint16_t)ntohl(received_spi));
1627
1628 DBG2(DBG_KNL, "got CPI %.4x", ntohs(*cpi));
1629 return SUCCESS;
1630 }
1631
1632 METHOD(kernel_ipsec_t, add_sa, status_t,
1633 private_kernel_pfkey_ipsec_t *this, kernel_ipsec_sa_id_t *id,
1634 kernel_ipsec_add_sa_t *data)
1635 {
1636 unsigned char request[PFKEY_BUFFER_SIZE];
1637 struct sadb_msg *msg, *out;
1638 struct sadb_sa *sa;
1639 struct sadb_x_sa2 *sa2;
1640 struct sadb_lifetime *lft;
1641 struct sadb_key *key;
1642 size_t len;
1643 uint16_t ipcomp = data->ipcomp;
1644 ipsec_mode_t mode = data->mode;
1645
1646 /* if IPComp is used, we install an additional IPComp SA. if the cpi is 0
1647 * we are in the recursive call below */
1648 if (ipcomp != IPCOMP_NONE && data->cpi != 0)
1649 {
1650 lifetime_cfg_t lft = {{0,0,0},{0,0,0},{0,0,0}};
1651 kernel_ipsec_sa_id_t ipcomp_id = {
1652 .src = id->src,
1653 .dst = id->dst,
1654 .spi = htonl(ntohs(data->cpi)),
1655 .proto = IPPROTO_COMP,
1656 .mark = id->mark,
1657 };
1658 kernel_ipsec_add_sa_t ipcomp_sa = {
1659 .reqid = data->reqid,
1660 .mode = data->mode,
1661 .src_ts = data->src_ts,
1662 .dst_ts = data->dst_ts,
1663 .lifetime = &lft,
1664 .enc_alg = ENCR_UNDEFINED,
1665 .int_alg = AUTH_UNDEFINED,
1666 .tfc = data->tfc,
1667 .ipcomp = data->ipcomp,
1668 .initiator = data->initiator,
1669 .inbound = data->inbound,
1670 .update = data->update,
1671 };
1672 add_sa(this, &ipcomp_id, &ipcomp_sa);
1673 ipcomp = IPCOMP_NONE;
1674 /* use transport mode ESP SA, IPComp uses tunnel mode */
1675 mode = MODE_TRANSPORT;
1676 }
1677
1678 if (data->update)
1679 {
1680 /* As we didn't know the reqid during SPI allocation, we used reqid
1681 * zero. Unfortunately we can't SADB_UPDATE to the new reqid, hence we
1682 * have to delete the SPI allocation state manually. The reqid
1683 * selector does not count for that, therefore we have to delete
1684 * that state before installing the new SA to avoid deleting the
1685 * the new state after installing it. */
1686 kernel_ipsec_sa_id_t del_id = {
1687 .src = id->src,
1688 .dst = id->dst,
1689 .spi = id->spi,
1690 .proto = id->proto,
1691 };
1692 kernel_ipsec_del_sa_t del = { 0 };
1693
1694 if (this->public.interface.del_sa(&this->public.interface, &del_id,
1695 &del) != SUCCESS)
1696 {
1697 DBG1(DBG_KNL, "deleting SPI allocation SA failed");
1698 }
1699 }
1700
1701 memset(&request, 0, sizeof(request));
1702
1703 DBG2(DBG_KNL, "adding SAD entry with SPI %.8x and reqid {%u}",
1704 ntohl(id->spi), data->reqid);
1705
1706 msg = (struct sadb_msg*)request;
1707 msg->sadb_msg_version = PF_KEY_V2;
1708 msg->sadb_msg_type = SADB_ADD;
1709 msg->sadb_msg_satype = proto2satype(id->proto);
1710 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1711
1712 #ifdef __APPLE__
1713 if (data->encap)
1714 {
1715 struct sadb_sa_2 *sa_2;
1716 sa_2 = (struct sadb_sa_2*)PFKEY_EXT_ADD_NEXT(msg);
1717 sa_2->sadb_sa_natt_port = id->dst->get_port(id->dst);
1718 sa = &sa_2->sa;
1719 sa->sadb_sa_flags |= SADB_X_EXT_NATT;
1720 len = sizeof(struct sadb_sa_2);
1721 }
1722 else
1723 #endif
1724 {
1725 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1726 len = sizeof(struct sadb_sa);
1727 }
1728 sa->sadb_sa_exttype = SADB_EXT_SA;
1729 sa->sadb_sa_len = PFKEY_LEN(len);
1730 sa->sadb_sa_spi = id->spi;
1731 sa->sadb_sa_state = SADB_SASTATE_MATURE;
1732 if (id->proto == IPPROTO_COMP)
1733 {
1734 sa->sadb_sa_encrypt = lookup_algorithm(COMPRESSION_ALGORITHM,
1735 ipcomp);
1736 }
1737 else
1738 {
1739 /* Linux interprets sadb_sa_replay as number of packets/bits in the
1740 * replay window, whereas on BSD it's the size of the window in bytes.
1741 * Only set for the inbound SA as it's not relevant for the outbound
1742 * SA and might waste memory with large windows. */
1743 if (data->inbound)
1744 {
1745 #ifdef __linux__
1746 sa->sadb_sa_replay = min(data->replay_window, 32);
1747 #else
1748 sa->sadb_sa_replay = min((data->replay_window + 7) / 8, UINT8_MAX);
1749 #endif
1750 }
1751 sa->sadb_sa_auth = lookup_algorithm(INTEGRITY_ALGORITHM, data->int_alg);
1752 sa->sadb_sa_encrypt = lookup_algorithm(ENCRYPTION_ALGORITHM,
1753 data->enc_alg);
1754 }
1755 PFKEY_EXT_ADD(msg, sa);
1756
1757 #ifdef SADB_X_EXT_SA_REPLAY
1758 if (data->inbound)
1759 {
1760 struct sadb_x_sa_replay *repl;
1761
1762 repl = (struct sadb_x_sa_replay*)PFKEY_EXT_ADD_NEXT(msg);
1763 repl->sadb_x_sa_replay_exttype = SADB_X_EXT_SA_REPLAY;
1764 repl->sadb_x_sa_replay_len = PFKEY_LEN(sizeof(struct sadb_x_sa_replay));
1765 repl->sadb_x_sa_replay_replay = min(data->replay_window, UINT32_MAX-32);
1766 PFKEY_EXT_ADD(msg, repl);
1767 }
1768 #endif
1769
1770 sa2 = (struct sadb_x_sa2*)PFKEY_EXT_ADD_NEXT(msg);
1771 sa2->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
1772 sa2->sadb_x_sa2_len = PFKEY_LEN(sizeof(struct sadb_spirange));
1773 sa2->sadb_x_sa2_mode = mode2kernel(mode);
1774 sa2->sadb_x_sa2_reqid = data->reqid;
1775 PFKEY_EXT_ADD(msg, sa2);
1776
1777 add_addr_ext(msg, id->src, SADB_EXT_ADDRESS_SRC, 0, 0, FALSE);
1778 add_addr_ext(msg, id->dst, SADB_EXT_ADDRESS_DST, 0, 0, FALSE);
1779
1780 lft = (struct sadb_lifetime*)PFKEY_EXT_ADD_NEXT(msg);
1781 lft->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
1782 lft->sadb_lifetime_len = PFKEY_LEN(sizeof(struct sadb_lifetime));
1783 lft->sadb_lifetime_allocations = data->lifetime->packets.rekey;
1784 lft->sadb_lifetime_bytes = data->lifetime->bytes.rekey;
1785 lft->sadb_lifetime_addtime = data->lifetime->time.rekey;
1786 lft->sadb_lifetime_usetime = 0; /* we only use addtime */
1787 PFKEY_EXT_ADD(msg, lft);
1788
1789 lft = (struct sadb_lifetime*)PFKEY_EXT_ADD_NEXT(msg);
1790 lft->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
1791 lft->sadb_lifetime_len = PFKEY_LEN(sizeof(struct sadb_lifetime));
1792 lft->sadb_lifetime_allocations = data->lifetime->packets.life;
1793 lft->sadb_lifetime_bytes = data->lifetime->bytes.life;
1794 lft->sadb_lifetime_addtime = data->lifetime->time.life;
1795 lft->sadb_lifetime_usetime = 0; /* we only use addtime */
1796 PFKEY_EXT_ADD(msg, lft);
1797
1798 if (data->enc_alg != ENCR_UNDEFINED)
1799 {
1800 if (!sa->sadb_sa_encrypt)
1801 {
1802 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1803 encryption_algorithm_names, data->enc_alg);
1804 return FAILED;
1805 }
1806 DBG2(DBG_KNL, " using encryption algorithm %N with key size %d",
1807 encryption_algorithm_names, data->enc_alg, data->enc_key.len * 8);
1808
1809 key = (struct sadb_key*)PFKEY_EXT_ADD_NEXT(msg);
1810 key->sadb_key_exttype = SADB_EXT_KEY_ENCRYPT;
1811 key->sadb_key_bits = data->enc_key.len * 8;
1812 key->sadb_key_len = PFKEY_LEN(sizeof(struct sadb_key) + data->enc_key.len);
1813 memcpy(key + 1, data->enc_key.ptr, data->enc_key.len);
1814
1815 PFKEY_EXT_ADD(msg, key);
1816 }
1817
1818 if (data->int_alg != AUTH_UNDEFINED)
1819 {
1820 if (!sa->sadb_sa_auth)
1821 {
1822 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1823 integrity_algorithm_names, data->int_alg);
1824 return FAILED;
1825 }
1826 DBG2(DBG_KNL, " using integrity algorithm %N with key size %d",
1827 integrity_algorithm_names, data->int_alg, data->int_key.len * 8);
1828
1829 key = (struct sadb_key*)PFKEY_EXT_ADD_NEXT(msg);
1830 key->sadb_key_exttype = SADB_EXT_KEY_AUTH;
1831 key->sadb_key_bits = data->int_key.len * 8;
1832 key->sadb_key_len = PFKEY_LEN(sizeof(struct sadb_key) + data->int_key.len);
1833 memcpy(key + 1, data->int_key.ptr, data->int_key.len);
1834
1835 PFKEY_EXT_ADD(msg, key);
1836 }
1837
1838 #ifdef HAVE_NATT
1839 if (data->encap)
1840 {
1841 add_encap_ext(msg, id->src, id->dst);
1842 }
1843 #endif /*HAVE_NATT*/
1844
1845 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1846 {
1847 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x",
1848 ntohl(id->spi));
1849 return FAILED;
1850 }
1851 else if (out->sadb_msg_errno)
1852 {
1853 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x: %s (%d)",
1854 ntohl(id->spi), strerror(out->sadb_msg_errno),
1855 out->sadb_msg_errno);
1856 free(out);
1857 return FAILED;
1858 }
1859
1860 free(out);
1861 return SUCCESS;
1862 }
1863
1864 METHOD(kernel_ipsec_t, update_sa, status_t,
1865 private_kernel_pfkey_ipsec_t *this, kernel_ipsec_sa_id_t *id,
1866 kernel_ipsec_update_sa_t *data)
1867 {
1868 unsigned char request[PFKEY_BUFFER_SIZE];
1869 struct sadb_msg *msg, *out;
1870 struct sadb_sa *sa;
1871 pfkey_msg_t response;
1872 size_t len;
1873
1874 #ifndef SADB_X_EXT_NEW_ADDRESS_SRC
1875 /* we can't update the SA if any of the ip addresses have changed.
1876 * that's because we can't use SADB_UPDATE and by deleting and readding the
1877 * SA the sequence numbers would get lost */
1878 if (!id->src->ip_equals(id->src, data->new_src) ||
1879 !id->dst->ip_equals(id->dst, data->new_dst))
1880 {
1881 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x: address "
1882 "changes are not supported", ntohl(id->spi));
1883 return NOT_SUPPORTED;
1884 }
1885 #endif /*SADB_X_EXT_NEW_ADDRESS_SRC*/
1886
1887 /* if IPComp is used, we first update the IPComp SA */
1888 if (data->cpi)
1889 {
1890 kernel_ipsec_sa_id_t ipcomp_id = {
1891 .src = id->src,
1892 .dst = id->dst,
1893 .spi = htonl(ntohs(data->cpi)),
1894 .proto = IPPROTO_COMP,
1895 .mark = id->mark,
1896 };
1897 kernel_ipsec_update_sa_t ipcomp = {
1898 .new_src = data->new_src,
1899 .new_dst = data->new_dst,
1900 };
1901 update_sa(this, &ipcomp_id, &ipcomp);
1902 }
1903
1904 memset(&request, 0, sizeof(request));
1905
1906 DBG2(DBG_KNL, "querying SAD entry with SPI %.8x for update",
1907 ntohl(id->spi));
1908
1909 msg = (struct sadb_msg*)request;
1910 msg->sadb_msg_version = PF_KEY_V2;
1911 msg->sadb_msg_type = SADB_GET;
1912 msg->sadb_msg_satype = proto2satype(id->proto);
1913 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1914
1915 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1916 sa->sadb_sa_exttype = SADB_EXT_SA;
1917 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1918 sa->sadb_sa_spi = id->spi;
1919 sa->sadb_sa_state = SADB_SASTATE_MATURE;
1920 PFKEY_EXT_ADD(msg, sa);
1921
1922 add_addr_ext(msg, id->src, SADB_EXT_ADDRESS_SRC, 0, 0, FALSE);
1923 add_addr_ext(msg, id->dst, SADB_EXT_ADDRESS_DST, 0, 0, FALSE);
1924
1925 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1926 {
1927 DBG1(DBG_KNL, "unable to query SAD entry with SPI %.8x",
1928 ntohl(id->spi));
1929 return FAILED;
1930 }
1931 else if (out->sadb_msg_errno)
1932 {
1933 DBG1(DBG_KNL, "unable to query SAD entry with SPI %.8x: %s (%d)",
1934 ntohl(id->spi), strerror(out->sadb_msg_errno),
1935 out->sadb_msg_errno);
1936 free(out);
1937 return FAILED;
1938 }
1939 else if (parse_pfkey_message(out, &response) != SUCCESS)
1940 {
1941 DBG1(DBG_KNL, "unable to query SAD entry with SPI %.8x: parsing "
1942 "response from kernel failed", ntohl(id->spi));
1943 free(out);
1944 return FAILED;
1945 }
1946
1947 DBG2(DBG_KNL, "updating SAD entry with SPI %.8x from %#H..%#H to %#H..%#H",
1948 ntohl(id->spi), id->src, id->dst, data->new_src, data->new_dst);
1949
1950 memset(&request, 0, sizeof(request));
1951
1952 msg = (struct sadb_msg*)request;
1953 msg->sadb_msg_version = PF_KEY_V2;
1954 msg->sadb_msg_type = SADB_UPDATE;
1955 msg->sadb_msg_satype = proto2satype(id->proto);
1956 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1957
1958 #ifdef __APPLE__
1959 {
1960 struct sadb_sa_2 *sa_2;
1961 sa_2 = (struct sadb_sa_2*)PFKEY_EXT_ADD_NEXT(msg);
1962 sa_2->sa.sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa_2));
1963 memcpy(&sa_2->sa, response.sa, sizeof(struct sadb_sa));
1964 if (data->new_encap)
1965 {
1966 sa_2->sadb_sa_natt_port = data->new_dst->get_port(data->new_dst);
1967 sa_2->sa.sadb_sa_flags |= SADB_X_EXT_NATT;
1968 }
1969 }
1970 #else
1971 PFKEY_EXT_COPY(msg, response.sa);
1972 #endif
1973 PFKEY_EXT_COPY(msg, response.x_sa2);
1974
1975 PFKEY_EXT_COPY(msg, response.src);
1976 PFKEY_EXT_COPY(msg, response.dst);
1977
1978 PFKEY_EXT_COPY(msg, response.lft_soft);
1979 PFKEY_EXT_COPY(msg, response.lft_hard);
1980
1981 #ifndef __FreeBSD__
1982 /* FreeBSD 11.1 does not allow key updates via SADB_UPDATE for mature SAs */
1983 if (response.key_encr)
1984 {
1985 PFKEY_EXT_COPY(msg, response.key_encr);
1986 }
1987
1988 if (response.key_auth)
1989 {
1990 PFKEY_EXT_COPY(msg, response.key_auth);
1991 }
1992 #endif
1993
1994 #ifdef HAVE_NATT
1995 if (data->new_encap)
1996 {
1997 add_encap_ext(msg, data->new_src, data->new_dst);
1998 }
1999 #endif /*HAVE_NATT*/
2000
2001 #ifdef SADB_X_EXT_NEW_ADDRESS_SRC
2002 if (!id->src->ip_equals(id->src, data->new_src))
2003 {
2004 add_addr_ext(msg, data->new_src, SADB_X_EXT_NEW_ADDRESS_SRC, 0, 0,
2005 FALSE);
2006 }
2007 if (!id->dst->ip_equals(id->dst, data->new_dst))
2008 {
2009 add_addr_ext(msg, data->new_dst, SADB_X_EXT_NEW_ADDRESS_DST, 0, 0,
2010 FALSE);
2011 }
2012 #endif /*SADB_X_EXT_NEW_ADDRESS_SRC*/
2013
2014 free(out);
2015
2016 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2017 {
2018 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x",
2019 ntohl(id->spi));
2020 return FAILED;
2021 }
2022 else if (out->sadb_msg_errno)
2023 {
2024 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x: %s (%d)",
2025 ntohl(id->spi), strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2026 free(out);
2027 return FAILED;
2028 }
2029 free(out);
2030
2031 return SUCCESS;
2032 }
2033
2034 METHOD(kernel_ipsec_t, query_sa, status_t,
2035 private_kernel_pfkey_ipsec_t *this, kernel_ipsec_sa_id_t *id,
2036 kernel_ipsec_query_sa_t *data, uint64_t *bytes, uint64_t *packets,
2037 time_t *time)
2038 {
2039 unsigned char request[PFKEY_BUFFER_SIZE];
2040 struct sadb_msg *msg, *out;
2041 struct sadb_sa *sa;
2042 pfkey_msg_t response;
2043 size_t len;
2044
2045 memset(&request, 0, sizeof(request));
2046
2047 DBG2(DBG_KNL, "querying SAD entry with SPI %.8x", ntohl(id->spi));
2048
2049 msg = (struct sadb_msg*)request;
2050 msg->sadb_msg_version = PF_KEY_V2;
2051 msg->sadb_msg_type = SADB_GET;
2052 msg->sadb_msg_satype = proto2satype(id->proto);
2053 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2054
2055 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
2056 sa->sadb_sa_exttype = SADB_EXT_SA;
2057 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
2058 sa->sadb_sa_spi = id->spi;
2059 PFKEY_EXT_ADD(msg, sa);
2060
2061 /* the Linux Kernel doesn't care for the src address, but other systems do
2062 * (e.g. FreeBSD)
2063 */
2064 add_addr_ext(msg, id->src, SADB_EXT_ADDRESS_SRC, 0, 0, FALSE);
2065 add_addr_ext(msg, id->dst, SADB_EXT_ADDRESS_DST, 0, 0, FALSE);
2066
2067 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2068 {
2069 DBG1(DBG_KNL, "unable to query SAD entry with SPI %.8x",
2070 ntohl(id->spi));
2071 return FAILED;
2072 }
2073 else if (out->sadb_msg_errno)
2074 {
2075 DBG1(DBG_KNL, "unable to query SAD entry with SPI %.8x: %s (%d)",
2076 ntohl(id->spi), strerror(out->sadb_msg_errno),
2077 out->sadb_msg_errno);
2078 free(out);
2079 return FAILED;
2080 }
2081 else if (parse_pfkey_message(out, &response) != SUCCESS)
2082 {
2083 DBG1(DBG_KNL, "unable to query SAD entry with SPI %.8x",
2084 ntohl(id->spi));
2085 free(out);
2086 return FAILED;
2087 }
2088 if (bytes)
2089 {
2090 *bytes = response.lft_current->sadb_lifetime_bytes;
2091 }
2092 if (packets)
2093 {
2094 /* at least on Linux and FreeBSD this contains the number of packets */
2095 *packets = response.lft_current->sadb_lifetime_allocations;
2096 }
2097 if (time)
2098 {
2099 #ifdef __APPLE__
2100 /* OS X uses the "last" time of use in usetime */
2101 *time = response.lft_current->sadb_lifetime_usetime;
2102 #else /* !__APPLE__ */
2103 /* on Linux, sadb_lifetime_usetime is set to the "first" time of use,
2104 * which is actually correct according to PF_KEY. We have to query
2105 * policies for the last usetime. */
2106 *time = 0;
2107 #endif /* !__APPLE__ */
2108 }
2109
2110 free(out);
2111 return SUCCESS;
2112 }
2113
2114 METHOD(kernel_ipsec_t, del_sa, status_t,
2115 private_kernel_pfkey_ipsec_t *this, kernel_ipsec_sa_id_t *id,
2116 kernel_ipsec_del_sa_t *data)
2117 {
2118 unsigned char request[PFKEY_BUFFER_SIZE];
2119 struct sadb_msg *msg, *out;
2120 struct sadb_sa *sa;
2121 size_t len;
2122
2123 /* if IPComp was used, we first delete the additional IPComp SA */
2124 if (data->cpi)
2125 {
2126 kernel_ipsec_sa_id_t ipcomp_id = {
2127 .src = id->src,
2128 .dst = id->dst,
2129 .spi = htonl(ntohs(data->cpi)),
2130 .proto = IPPROTO_COMP,
2131 .mark = id->mark,
2132 };
2133 kernel_ipsec_del_sa_t ipcomp = { 0 };
2134 del_sa(this, &ipcomp_id, &ipcomp);
2135 }
2136
2137 memset(&request, 0, sizeof(request));
2138
2139 DBG2(DBG_KNL, "deleting SAD entry with SPI %.8x", ntohl(id->spi));
2140
2141 msg = (struct sadb_msg*)request;
2142 msg->sadb_msg_version = PF_KEY_V2;
2143 msg->sadb_msg_type = SADB_DELETE;
2144 msg->sadb_msg_satype = proto2satype(id->proto);
2145 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2146
2147 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
2148 sa->sadb_sa_exttype = SADB_EXT_SA;
2149 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
2150 sa->sadb_sa_spi = id->spi;
2151 PFKEY_EXT_ADD(msg, sa);
2152
2153 /* the Linux Kernel doesn't care for the src address, but other systems do
2154 * (e.g. FreeBSD)
2155 */
2156 add_addr_ext(msg, id->src, SADB_EXT_ADDRESS_SRC, 0, 0, FALSE);
2157 add_addr_ext(msg, id->dst, SADB_EXT_ADDRESS_DST, 0, 0, FALSE);
2158
2159 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2160 {
2161 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x",
2162 ntohl(id->spi));
2163 return FAILED;
2164 }
2165 else if (out->sadb_msg_errno)
2166 {
2167 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x: %s (%d)",
2168 ntohl(id->spi), strerror(out->sadb_msg_errno),
2169 out->sadb_msg_errno);
2170 free(out);
2171 return FAILED;
2172 }
2173
2174 DBG2(DBG_KNL, "deleted SAD entry with SPI %.8x", ntohl(id->spi));
2175 free(out);
2176 return SUCCESS;
2177 }
2178
2179 METHOD(kernel_ipsec_t, flush_sas, status_t,
2180 private_kernel_pfkey_ipsec_t *this)
2181 {
2182 unsigned char request[PFKEY_BUFFER_SIZE];
2183 struct sadb_msg *msg, *out;
2184 struct {
2185 uint8_t proto;
2186 char *name;
2187 } protos[] = {
2188 { SADB_SATYPE_AH, "AH" },
2189 { SADB_SATYPE_ESP, "ESP" },
2190 { SADB_X_SATYPE_IPCOMP, "IPComp" },
2191 };
2192 size_t len;
2193 int i;
2194
2195 memset(&request, 0, sizeof(request));
2196
2197 msg = (struct sadb_msg*)request;
2198 msg->sadb_msg_version = PF_KEY_V2;
2199 msg->sadb_msg_type = SADB_FLUSH;
2200 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2201
2202 for (i = 0; i < countof(protos); i++)
2203 {
2204 DBG2(DBG_KNL, "flushing all %s SAD entries", protos[i].name);
2205
2206 msg->sadb_msg_satype = protos[i].proto;
2207 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2208 {
2209 DBG1(DBG_KNL, "unable to flush %s SAD entries", protos[i].name);
2210 return FAILED;
2211 }
2212 else if (out->sadb_msg_errno)
2213 {
2214 DBG1(DBG_KNL, "unable to flush %s SAD entries: %s (%d)",
2215 protos[i].name, strerror(out->sadb_msg_errno),
2216 out->sadb_msg_errno);
2217 free(out);
2218 return FAILED;
2219 }
2220 free(out);
2221 }
2222 return SUCCESS;
2223 }
2224
2225 /**
2226 * Add an explicit exclude route to a routing entry
2227 */
2228 static void add_exclude_route(private_kernel_pfkey_ipsec_t *this,
2229 route_entry_t *route, host_t *src, host_t *dst)
2230 {
2231 enumerator_t *enumerator;
2232 exclude_route_t *exclude;
2233 host_t *gtw;
2234
2235 enumerator = this->excludes->create_enumerator(this->excludes);
2236 while (enumerator->enumerate(enumerator, &exclude))
2237 {
2238 if (dst->ip_equals(dst, exclude->dst))
2239 {
2240 route->exclude = exclude;
2241 exclude->refs++;
2242 }
2243 }
2244 enumerator->destroy(enumerator);
2245
2246 if (!route->exclude)
2247 {
2248 DBG2(DBG_KNL, "installing new exclude route for %H src %H", dst, src);
2249 gtw = charon->kernel->get_nexthop(charon->kernel, dst, -1, NULL, NULL);
2250 if (gtw)
2251 {
2252 char *if_name = NULL;
2253
2254 if (charon->kernel->get_interface(charon->kernel, src, &if_name) &&
2255 charon->kernel->add_route(charon->kernel,
2256 dst->get_address(dst),
2257 dst->get_family(dst) == AF_INET ? 32 : 128,
2258 gtw, src, if_name) == SUCCESS)
2259 {
2260 INIT(exclude,
2261 .dst = dst->clone(dst),
2262 .src = src->clone(src),
2263 .gtw = gtw->clone(gtw),
2264 .refs = 1,
2265 );
2266 route->exclude = exclude;
2267 this->excludes->insert_last(this->excludes, exclude);
2268 }
2269 else
2270 {
2271 DBG1(DBG_KNL, "installing exclude route for %H failed", dst);
2272 }
2273 gtw->destroy(gtw);
2274 free(if_name);
2275 }
2276 else
2277 {
2278 DBG1(DBG_KNL, "gateway lookup for for %H failed", dst);
2279 }
2280 }
2281 }
2282
2283 /**
2284 * Remove an exclude route attached to a routing entry
2285 */
2286 static void remove_exclude_route(private_kernel_pfkey_ipsec_t *this,
2287 route_entry_t *route)
2288 {
2289 if (route->exclude)
2290 {
2291 enumerator_t *enumerator;
2292 exclude_route_t *exclude;
2293 bool removed = FALSE;
2294 host_t *dst;
2295
2296 enumerator = this->excludes->create_enumerator(this->excludes);
2297 while (enumerator->enumerate(enumerator, &exclude))
2298 {
2299 if (route->exclude == exclude)
2300 {
2301 if (--exclude->refs == 0)
2302 {
2303 this->excludes->remove_at(this->excludes, enumerator);
2304 removed = TRUE;
2305 break;
2306 }
2307 }
2308 }
2309 enumerator->destroy(enumerator);
2310
2311 if (removed)
2312 {
2313 char *if_name = NULL;
2314
2315 dst = route->exclude->dst;
2316 DBG2(DBG_KNL, "uninstalling exclude route for %H src %H",
2317 dst, route->exclude->src);
2318 if (charon->kernel->get_interface(
2319 charon->kernel,
2320 route->exclude->src, &if_name) &&
2321 charon->kernel->del_route(charon->kernel,
2322 dst->get_address(dst),
2323 dst->get_family(dst) == AF_INET ? 32 : 128,
2324 route->exclude->gtw, route->exclude->src,
2325 if_name) != SUCCESS)
2326 {
2327 DBG1(DBG_KNL, "uninstalling exclude route for %H failed", dst);
2328 }
2329 exclude_route_destroy(route->exclude);
2330 free(if_name);
2331 }
2332 route->exclude = NULL;
2333 }
2334 }
2335
2336 /**
2337 * Try to install a route to the given outbound policy
2338 */
2339 static bool install_route(private_kernel_pfkey_ipsec_t *this,
2340 policy_entry_t *policy, policy_sa_out_t *out)
2341 {
2342 route_entry_t *route, *old;
2343 host_t *host, *src, *dst;
2344 bool is_virtual;
2345
2346 if (charon->kernel->get_address_by_ts(charon->kernel, out->src_ts, &host,
2347 &is_virtual) != SUCCESS)
2348 {
2349 return FALSE;
2350 }
2351
2352 INIT(route,
2353 .prefixlen = policy->dst.mask,
2354 .src_ip = host,
2355 .dst_net = chunk_clone(policy->dst.net->get_address(policy->dst.net)),
2356 );
2357
2358 src = out->generic.sa->src;
2359 dst = out->generic.sa->dst;
2360
2361 if (!dst->is_anyaddr(dst))
2362 {
2363 route->gateway = charon->kernel->get_nexthop(charon->kernel, dst, -1,
2364 src, &route->if_name);
2365
2366 /* if the IP is virtual, we install the route over the interface it has
2367 * been installed on. Otherwise we use the interface we use for IKE, as
2368 * this is required for example on Linux. */
2369 if (is_virtual || this->route_via_internal)
2370 {
2371 free(route->if_name);
2372 route->if_name = NULL;
2373 src = route->src_ip;
2374 }
2375 }
2376 else
2377 { /* for shunt policies */
2378 route->gateway = charon->kernel->get_nexthop(charon->kernel,
2379 policy->dst.net, policy->dst.mask,
2380 route->src_ip, &route->if_name);
2381
2382 /* we don't have a source address, use the address we found */
2383 src = route->src_ip;
2384 }
2385
2386 /* get interface for route, using source address */
2387 if (!route->if_name &&
2388 !charon->kernel->get_interface(charon->kernel, src, &route->if_name))
2389 {
2390 route_entry_destroy(route);
2391 return FALSE;
2392 }
2393
2394 if (policy->route)
2395 {
2396 old = policy->route;
2397
2398 if (route_entry_equals(old, route))
2399 { /* such a route already exists */
2400 route_entry_destroy(route);
2401 return TRUE;
2402 }
2403 /* uninstall previously installed route */
2404 if (charon->kernel->del_route(charon->kernel, old->dst_net,
2405 old->prefixlen, old->gateway,
2406 old->src_ip, old->if_name) != SUCCESS)
2407 {
2408 DBG1(DBG_KNL, "error uninstalling route installed with policy "
2409 "%R === %R %N", out->src_ts, out->dst_ts,
2410 policy_dir_names, policy->direction);
2411 }
2412 route_entry_destroy(old);
2413 policy->route = NULL;
2414 }
2415
2416 /* if remote traffic selector covers the IKE peer, add an exclude route */
2417 if (charon->kernel->get_features(charon->kernel) & KERNEL_REQUIRE_EXCLUDE_ROUTE)
2418 {
2419 if (out->dst_ts->is_host(out->dst_ts, dst))
2420 {
2421 DBG1(DBG_KNL, "can't install route for %R === %R %N, conflicts "
2422 "with IKE traffic", out->src_ts, out->dst_ts, policy_dir_names,
2423 policy->direction);
2424 route_entry_destroy(route);
2425 return FALSE;
2426 }
2427 if (out->dst_ts->includes(out->dst_ts, dst))
2428 {
2429 add_exclude_route(this, route, out->generic.sa->src, dst);
2430 }
2431 }
2432
2433 DBG2(DBG_KNL, "installing route: %R via %H src %H dev %s",
2434 out->dst_ts, route->gateway, route->src_ip, route->if_name);
2435
2436 switch (charon->kernel->add_route(charon->kernel, route->dst_net,
2437 route->prefixlen, route->gateway,
2438 route->src_ip, route->if_name))
2439 {
2440 case ALREADY_DONE:
2441 /* route exists, do not uninstall */
2442 remove_exclude_route(this, route);
2443 route_entry_destroy(route);
2444 return TRUE;
2445 case SUCCESS:
2446 /* cache the installed route */
2447 policy->route = route;
2448 return TRUE;
2449 default:
2450 DBG1(DBG_KNL, "installing route failed: %R via %H src %H dev %s",
2451 out->dst_ts, route->gateway, route->src_ip, route->if_name);
2452 remove_exclude_route(this, route);
2453 route_entry_destroy(route);
2454 return FALSE;
2455 }
2456 }
2457
2458 /**
2459 * Check if any significant data has changed to warrant sending an update to
2460 * the kernel.
2461 */
2462 static bool policy_update_required(policy_sa_t *current, policy_sa_t *updated)
2463 {
2464 if (current->type != updated->type
2465 #ifdef HAVE_STRUCT_SADB_X_POLICY_SADB_X_POLICY_PRIORITY
2466 || current->priority != updated->priority
2467 #endif
2468 )
2469 {
2470 return TRUE;
2471 }
2472 if (current->type == POLICY_IPSEC)
2473 {
2474 ipsec_sa_cfg_t *cur = &current->sa->cfg, *upd = &updated->sa->cfg;
2475
2476 /* we don't use ipsec_sa_cfg_equals() here as e.g. SPIs are not
2477 * relevant for this kernel interface, so we don't have to update the
2478 * policy during a rekeying */
2479 if (cur->mode != upd->mode ||
2480 cur->reqid != upd->reqid ||
2481 cur->esp.use != upd->esp.use ||
2482 cur->ah.use != upd->ah.use ||
2483 cur->ipcomp.transform != upd->ipcomp.transform)
2484 {
2485 return TRUE;
2486 }
2487 if (cur->mode == MODE_TUNNEL &&
2488 (!current->sa->src->ip_equals(current->sa->src, updated->sa->src) ||
2489 !current->sa->dst->ip_equals(current->sa->dst, updated->sa->dst)))
2490 {
2491 return TRUE;
2492 }
2493 }
2494 return FALSE;
2495 }
2496
2497 /**
2498 * Add or update a policy in the kernel.
2499 *
2500 * Note: The mutex has to be locked when entering this function.
2501 */
2502 static status_t add_policy_internal(private_kernel_pfkey_ipsec_t *this,
2503 policy_entry_t *policy, policy_sa_t *mapping, bool update)
2504 {
2505 unsigned char request[PFKEY_BUFFER_SIZE];
2506 struct sadb_msg *msg, *out;
2507 struct sadb_x_policy *pol;
2508 struct sadb_x_ipsecrequest *req;
2509 ipsec_sa_t *ipsec = mapping->sa;
2510 pfkey_msg_t response;
2511 size_t len;
2512 ipsec_mode_t proto_mode;
2513 status_t status;
2514
2515 memset(&request, 0, sizeof(request));
2516
2517 msg = (struct sadb_msg*)request;
2518 msg->sadb_msg_version = PF_KEY_V2;
2519 msg->sadb_msg_type = update ? SADB_X_SPDUPDATE : SADB_X_SPDADD;
2520 msg->sadb_msg_satype = 0;
2521 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2522
2523 pol = (struct sadb_x_policy*)PFKEY_EXT_ADD_NEXT(msg);
2524 pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2525 pol->sadb_x_policy_len = PFKEY_LEN(sizeof(struct sadb_x_policy));
2526 pol->sadb_x_policy_id = 0;
2527 pol->sadb_x_policy_dir = dir2kernel(policy->direction);
2528 pol->sadb_x_policy_type = type2kernel(mapping->type);
2529 #ifdef HAVE_STRUCT_SADB_X_POLICY_SADB_X_POLICY_PRIORITY
2530 pol->sadb_x_policy_priority = mapping->priority;
2531 #endif
2532
2533 if (mapping->type == POLICY_IPSEC && ipsec->cfg.reqid)
2534 {
2535 /* one or more sadb_x_ipsecrequest extensions are added to the
2536 * sadb_x_policy extension */
2537 proto_mode = ipsec->cfg.mode;
2538
2539 req = (struct sadb_x_ipsecrequest*)(pol + 1);
2540
2541 if (ipsec->cfg.ipcomp.transform != IPCOMP_NONE)
2542 {
2543 req->sadb_x_ipsecrequest_proto = IPPROTO_COMP;
2544
2545 /* !!! the length here MUST be in octets instead of 64 bit words */
2546 req->sadb_x_ipsecrequest_len = sizeof(struct sadb_x_ipsecrequest);
2547 req->sadb_x_ipsecrequest_mode = mode2kernel(ipsec->cfg.mode);
2548 req->sadb_x_ipsecrequest_reqid = ipsec->cfg.reqid;
2549 req->sadb_x_ipsecrequest_level = (policy->direction == POLICY_OUT) ?
2550 IPSEC_LEVEL_UNIQUE : IPSEC_LEVEL_USE;
2551 if (ipsec->cfg.mode == MODE_TUNNEL)
2552 {
2553 len = hostcpy(req + 1, ipsec->src, FALSE);
2554 req->sadb_x_ipsecrequest_len += len;
2555 len = hostcpy((char*)(req + 1) + len, ipsec->dst, FALSE);
2556 req->sadb_x_ipsecrequest_len += len;
2557 /* use transport mode for other SAs */
2558 proto_mode = MODE_TRANSPORT;
2559 }
2560
2561 pol->sadb_x_policy_len += PFKEY_LEN(req->sadb_x_ipsecrequest_len);
2562 req = (struct sadb_x_ipsecrequest*)((char*)(req) +
2563 req->sadb_x_ipsecrequest_len);
2564 }
2565
2566 req->sadb_x_ipsecrequest_proto = ipsec->cfg.esp.use ? IPPROTO_ESP
2567 : IPPROTO_AH;
2568 /* !!! the length here MUST be in octets instead of 64 bit words */
2569 req->sadb_x_ipsecrequest_len = sizeof(struct sadb_x_ipsecrequest);
2570 req->sadb_x_ipsecrequest_mode = mode2kernel(proto_mode);
2571 req->sadb_x_ipsecrequest_reqid = ipsec->cfg.reqid;
2572 req->sadb_x_ipsecrequest_level = IPSEC_LEVEL_UNIQUE;
2573 if (proto_mode == MODE_TUNNEL)
2574 {
2575 len = hostcpy(req + 1, ipsec->src, FALSE);
2576 req->sadb_x_ipsecrequest_len += len;
2577 len = hostcpy((char*)(req + 1) + len, ipsec->dst, FALSE);
2578 req->sadb_x_ipsecrequest_len += len;
2579 }
2580
2581 pol->sadb_x_policy_len += PFKEY_LEN(req->sadb_x_ipsecrequest_len);
2582 }
2583 PFKEY_EXT_ADD(msg, pol);
2584
2585 add_addr_ext(msg, policy->src.net, SADB_EXT_ADDRESS_SRC, policy->src.proto,
2586 policy->src.mask, TRUE);
2587 add_addr_ext(msg, policy->dst.net, SADB_EXT_ADDRESS_DST, policy->dst.proto,
2588 policy->dst.mask, TRUE);
2589
2590 #ifdef __FreeBSD__
2591 { /* on FreeBSD a lifetime has to be defined to be able to later query
2592 * the current use time. */
2593 struct sadb_lifetime *lft;
2594 lft = (struct sadb_lifetime*)PFKEY_EXT_ADD_NEXT(msg);
2595 lft->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2596 lft->sadb_lifetime_len = PFKEY_LEN(sizeof(struct sadb_lifetime));
2597 lft->sadb_lifetime_addtime = LONG_MAX;
2598 PFKEY_EXT_ADD(msg, lft);
2599 }
2600 #endif
2601
2602 this->mutex->unlock(this->mutex);
2603
2604 status = pfkey_send(this, msg, &out, &len);
2605 if (status == SUCCESS && !update && out->sadb_msg_errno == EEXIST)
2606 {
2607 DBG1(DBG_KNL, "policy already exists, try to update it");
2608 free(out);
2609 msg->sadb_msg_type = SADB_X_SPDUPDATE;
2610 status = pfkey_send(this, msg, &out, &len);
2611 }
2612 if (status != SUCCESS)
2613 {
2614 return FAILED;
2615 }
2616 else if (out->sadb_msg_errno)
2617 {
2618 DBG1(DBG_KNL, "unable to %s policy: %s (%d)",
2619 update ? "update" : "add", strerror(out->sadb_msg_errno),
2620 out->sadb_msg_errno);
2621 free(out);
2622 return FAILED;
2623 }
2624 else if (parse_pfkey_message(out, &response) != SUCCESS)
2625 {
2626 DBG1(DBG_KNL, "unable to %s policy: parsing response from kernel "
2627 "failed", update ? "update" : "add");
2628 free(out);
2629 return FAILED;
2630 }
2631
2632 /* we try to find the policy again and update the kernel index */
2633 this->mutex->lock(this->mutex);
2634 if (!this->policies->find_first(this->policies, NULL, (void**)&policy))
2635 {
2636 DBG2(DBG_KNL, "unable to update index, the policy is already gone, "
2637 "ignoring");
2638 this->mutex->unlock(this->mutex);
2639 free(out);
2640 return SUCCESS;
2641 }
2642 policy->index = response.x_policy->sadb_x_policy_id;
2643 free(out);
2644
2645 /* install a route, if:
2646 * - this is an outbound policy (to just get one for each child)
2647 * - routing is not disabled via strongswan.conf
2648 * - the selector is not for a specific protocol/port
2649 * - we are in tunnel mode or install a bypass policy
2650 */
2651 if (policy->direction == POLICY_OUT && this->install_routes &&
2652 policy->src.proto == IPSEC_PROTO_ANY &&
2653 !policy->src.net->get_port(policy->src.net) &&
2654 !policy->dst.net->get_port(policy->dst.net))
2655 {
2656 if (mapping->type == POLICY_PASS ||
2657 (mapping->type == POLICY_IPSEC && ipsec->cfg.mode != MODE_TRANSPORT))
2658 {
2659 install_route(this, policy, (policy_sa_out_t*)mapping);
2660 }
2661 }
2662 this->mutex->unlock(this->mutex);
2663 return SUCCESS;
2664 }
2665
2666 METHOD(kernel_ipsec_t, add_policy, status_t,
2667 private_kernel_pfkey_ipsec_t *this, kernel_ipsec_policy_id_t *id,
2668 kernel_ipsec_manage_policy_t *data)
2669 {
2670 policy_entry_t *policy, *found = NULL;
2671 policy_sa_t *assigned_sa, *current_sa = NULL;
2672 enumerator_t *enumerator;
2673 bool update = TRUE;
2674
2675 if (dir2kernel(id->dir) == IPSEC_DIR_INVALID)
2676 { /* FWD policies are not supported on all platforms */
2677 return SUCCESS;
2678 }
2679
2680 /* create a policy */
2681 policy = create_policy_entry(id->src_ts, id->dst_ts, id->dir);
2682
2683 /* find a matching policy */
2684 this->mutex->lock(this->mutex);
2685 if (this->policies->find_first(this->policies, policy_entry_equals,
2686 (void**)&found, policy))
2687 { /* use existing policy */
2688 DBG2(DBG_KNL, "policy %R === %R %N already exists, increasing "
2689 "refcount", id->src_ts, id->dst_ts, policy_dir_names, id->dir);
2690 policy_entry_destroy(policy, this);
2691 policy = found;
2692 }
2693 else
2694 { /* use the new one, if we have no such policy */
2695 this->policies->insert_first(this->policies, policy);
2696 policy->used_by = linked_list_create();
2697 }
2698
2699 /* cache the assigned IPsec SA */
2700 assigned_sa = policy_sa_create(this, id->dir, data->type, data->src,
2701 data->dst, id->src_ts, id->dst_ts, data->sa);
2702 assigned_sa->auto_priority = get_priority(policy, data->prio);
2703 assigned_sa->priority = data->manual_prio ? data->manual_prio :
2704 assigned_sa->auto_priority;
2705
2706
2707 /* insert the SA according to its priority */
2708 enumerator = policy->used_by->create_enumerator(policy->used_by);
2709 while (enumerator->enumerate(enumerator, (void**)&current_sa))
2710 {
2711 if (current_sa->priority > assigned_sa->priority)
2712 {
2713 break;
2714 }
2715 if (current_sa->priority == assigned_sa->priority)
2716 {
2717 /* in case of equal manual prios order SAs by automatic priority */
2718 if (current_sa->auto_priority > assigned_sa->auto_priority)
2719 {
2720 break;
2721 }
2722 /* prefer SAs with a reqid over those without */
2723 if (current_sa->auto_priority == assigned_sa->auto_priority &&
2724 (!current_sa->sa->cfg.reqid || assigned_sa->sa->cfg.reqid))
2725 {
2726 break;
2727 }
2728 }
2729 update = FALSE;
2730 }
2731 policy->used_by->insert_before(policy->used_by, enumerator, assigned_sa);
2732 enumerator->destroy(enumerator);
2733
2734 if (update && current_sa)
2735 { /* check if there are actually any relevant changes, if not, we don't
2736 * send an update to the kernel as e.g. FreeBSD doesn't do that
2737 * atomically, causing unecessary traffic loss during rekeyings */
2738 update = policy_update_required(current_sa, assigned_sa);
2739 }
2740
2741 if (!update)
2742 { /* we don't update the policy if the priority is lower than that of the
2743 * currently installed one */
2744 this->mutex->unlock(this->mutex);
2745 return SUCCESS;
2746 }
2747
2748 DBG2(DBG_KNL, "%s policy %R === %R %N",
2749 found ? "updating" : "adding", id->src_ts, id->dst_ts,
2750 policy_dir_names, id->dir);
2751
2752 if (add_policy_internal(this, policy, assigned_sa, found) != SUCCESS)
2753 {
2754 DBG1(DBG_KNL, "unable to %s policy %R === %R %N",
2755 found ? "update" : "add", id->src_ts, id->dst_ts,
2756 policy_dir_names, id->dir);
2757 return FAILED;
2758 }
2759 return SUCCESS;
2760 }
2761
2762 METHOD(kernel_ipsec_t, query_policy, status_t,
2763 private_kernel_pfkey_ipsec_t *this, kernel_ipsec_policy_id_t *id,
2764 kernel_ipsec_query_policy_t *data, time_t *use_time)
2765 {
2766 unsigned char request[PFKEY_BUFFER_SIZE];
2767 struct sadb_msg *msg, *out;
2768 struct sadb_x_policy *pol;
2769 policy_entry_t *policy, *found = NULL;
2770 pfkey_msg_t response;
2771 size_t len;
2772
2773 if (dir2kernel(id->dir) == IPSEC_DIR_INVALID)
2774 { /* FWD policies are not supported on all platforms */
2775 return NOT_FOUND;
2776 }
2777
2778 DBG2(DBG_KNL, "querying policy %R === %R %N", id->src_ts, id->dst_ts,
2779 policy_dir_names, id->dir);
2780
2781 /* create a policy */
2782 policy = create_policy_entry(id->src_ts, id->dst_ts, id->dir);
2783
2784 /* find a matching policy */
2785 this->mutex->lock(this->mutex);
2786 if (!this->policies->find_first(this->policies, policy_entry_equals,
2787 (void**)&found, policy))
2788 {
2789 DBG1(DBG_KNL, "querying policy %R === %R %N failed, not found",
2790 id->src_ts, id->dst_ts, policy_dir_names, id->dir);
2791 policy_entry_destroy(policy, this);
2792 this->mutex->unlock(this->mutex);
2793 return NOT_FOUND;
2794 }
2795 policy_entry_destroy(policy, this);
2796 policy = found;
2797
2798 memset(&request, 0, sizeof(request));
2799
2800 msg = (struct sadb_msg*)request;
2801 msg->sadb_msg_version = PF_KEY_V2;
2802 msg->sadb_msg_type = SADB_X_SPDGET;
2803 msg->sadb_msg_satype = 0;
2804 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2805
2806 pol = (struct sadb_x_policy*)PFKEY_EXT_ADD_NEXT(msg);
2807 pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2808 pol->sadb_x_policy_id = policy->index;
2809 pol->sadb_x_policy_len = PFKEY_LEN(sizeof(struct sadb_x_policy));
2810 pol->sadb_x_policy_dir = dir2kernel(id->dir);
2811 pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC;
2812 PFKEY_EXT_ADD(msg, pol);
2813
2814 add_addr_ext(msg, policy->src.net, SADB_EXT_ADDRESS_SRC, policy->src.proto,
2815 policy->src.mask, TRUE);
2816 add_addr_ext(msg, policy->dst.net, SADB_EXT_ADDRESS_DST, policy->dst.proto,
2817 policy->dst.mask, TRUE);
2818
2819 this->mutex->unlock(this->mutex);
2820
2821 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2822 {
2823 DBG1(DBG_KNL, "unable to query policy %R === %R %N", id->src_ts,
2824 id->dst_ts, policy_dir_names, id->dir);
2825 return FAILED;
2826 }
2827 else if (out->sadb_msg_errno)
2828 {
2829 DBG1(DBG_KNL, "unable to query policy %R === %R %N: %s (%d)",
2830 id->src_ts, id->dst_ts, policy_dir_names, id->dir,
2831 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2832 free(out);
2833 return FAILED;
2834 }
2835 else if (parse_pfkey_message(out, &response) != SUCCESS)
2836 {
2837 DBG1(DBG_KNL, "unable to query policy %R === %R %N: parsing response "
2838 "from kernel failed", id->src_ts, id->dst_ts, policy_dir_names,
2839 id->dir);
2840 free(out);
2841 return FAILED;
2842 }
2843 else if (response.lft_current == NULL)
2844 {
2845 DBG2(DBG_KNL, "unable to query policy %R === %R %N: kernel reports no "
2846 "use time", id->src_ts, id->dst_ts, policy_dir_names,
2847 id->dir);
2848 free(out);
2849 return FAILED;
2850 }
2851
2852 /* we need the monotonic time, but the kernel returns system time. */
2853 if (response.lft_current->sadb_lifetime_usetime)
2854 {
2855 *use_time = time_monotonic(NULL) -
2856 (time(NULL) - response.lft_current->sadb_lifetime_usetime);
2857 }
2858 else
2859 {
2860 *use_time = 0;
2861 }
2862 free(out);
2863 return SUCCESS;
2864 }
2865
2866 METHOD(kernel_ipsec_t, del_policy, status_t,
2867 private_kernel_pfkey_ipsec_t *this, kernel_ipsec_policy_id_t *id,
2868 kernel_ipsec_manage_policy_t *data)
2869 {
2870 unsigned char request[PFKEY_BUFFER_SIZE];
2871 struct sadb_msg *msg, *out;
2872 struct sadb_x_policy *pol;
2873 policy_entry_t *policy, *found = NULL;
2874 policy_sa_t *mapping, *to_remove = NULL;
2875 enumerator_t *enumerator;
2876 bool first = TRUE, is_installed = TRUE;
2877 uint32_t priority, auto_priority;
2878 size_t len;
2879 ipsec_sa_t assigned_sa = {
2880 .src = data->src,
2881 .dst = data->dst,
2882 .cfg = *data->sa,
2883 };
2884
2885 if (dir2kernel(id->dir) == IPSEC_DIR_INVALID)
2886 { /* FWD policies are not supported on all platforms */
2887 return SUCCESS;
2888 }
2889
2890 DBG2(DBG_KNL, "deleting policy %R === %R %N", id->src_ts, id->dst_ts,
2891 policy_dir_names, id->dir);
2892
2893 /* create a policy */
2894 policy = create_policy_entry(id->src_ts, id->dst_ts, id->dir);
2895
2896 /* find a matching policy */
2897 this->mutex->lock(this->mutex);
2898 if (!this->policies->find_first(this->policies, policy_entry_equals,
2899 (void**)&found, policy))
2900 {
2901 DBG1(DBG_KNL, "deleting policy %R === %R %N failed, not found",
2902 id->src_ts, id->dst_ts, policy_dir_names, id->dir);
2903 policy_entry_destroy(policy, this);
2904 this->mutex->unlock(this->mutex);
2905 return NOT_FOUND;
2906 }
2907 policy_entry_destroy(policy, this);
2908 policy = found;
2909
2910 /* remove mapping to SA by reqid and priority, if multiple match, which
2911 * could happen when rekeying due to an address change, remove the oldest */
2912 auto_priority = get_priority(policy, data->prio);
2913 priority = data->manual_prio ? data->manual_prio : auto_priority;
2914 enumerator = policy->used_by->create_enumerator(policy->used_by);
2915 while (enumerator->enumerate(enumerator, (void**)&mapping))
2916 {
2917 if (priority == mapping->priority &&
2918 auto_priority == mapping->auto_priority &&
2919 data->type == mapping->type &&
2920 ipsec_sa_equals(mapping->sa, &assigned_sa))
2921 {
2922 to_remove = mapping;
2923 is_installed = first;
2924 }
2925 else if (priority < mapping->priority)
2926 {
2927 break;
2928 }
2929 first = FALSE;
2930 }
2931 enumerator->destroy(enumerator);
2932 if (!to_remove)
2933 { /* sanity check */
2934 this->mutex->unlock(this->mutex);
2935 return SUCCESS;
2936 }
2937 policy->used_by->remove(policy->used_by, to_remove, NULL);
2938
2939 if (policy->used_by->get_count(policy->used_by) > 0)
2940 { /* policy is used by more SAs, keep in kernel */
2941 DBG2(DBG_KNL, "policy still used by another CHILD_SA, not removed");
2942
2943 if (is_installed)
2944 { /* check if there are actually any relevant changes, if not, we do
2945 * not send an update to the kernel as e.g. FreeBSD doesn't do that
2946 * atomically, causing unecessary traffic loss during rekeyings */
2947 policy->used_by->get_first(policy->used_by, (void**)&mapping);
2948 is_installed = policy_update_required(mapping, to_remove);
2949 }
2950 policy_sa_destroy(to_remove, id->dir, this);
2951
2952 if (!is_installed)
2953 { /* no need to update as the policy */
2954 this->mutex->unlock(this->mutex);
2955 return SUCCESS;
2956 }
2957
2958 DBG2(DBG_KNL, "updating policy %R === %R %N", id->src_ts, id->dst_ts,
2959 policy_dir_names, id->dir);
2960 if (add_policy_internal(this, policy, mapping, TRUE) != SUCCESS)
2961 {
2962 DBG1(DBG_KNL, "unable to update policy %R === %R %N",
2963 id->src_ts, id->dst_ts, policy_dir_names, id->dir);
2964 return FAILED;
2965 }
2966 return SUCCESS;
2967 }
2968
2969 memset(&request, 0, sizeof(request));
2970
2971 msg = (struct sadb_msg*)request;
2972 msg->sadb_msg_version = PF_KEY_V2;
2973 msg->sadb_msg_type = SADB_X_SPDDELETE;
2974 msg->sadb_msg_satype = 0;
2975 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2976
2977 pol = (struct sadb_x_policy*)PFKEY_EXT_ADD_NEXT(msg);
2978 pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2979 pol->sadb_x_policy_len = PFKEY_LEN(sizeof(struct sadb_x_policy));
2980 pol->sadb_x_policy_dir = dir2kernel(id->dir);
2981 pol->sadb_x_policy_type = type2kernel(to_remove->type);
2982 PFKEY_EXT_ADD(msg, pol);
2983
2984 add_addr_ext(msg, policy->src.net, SADB_EXT_ADDRESS_SRC, policy->src.proto,
2985 policy->src.mask, TRUE);
2986 add_addr_ext(msg, policy->dst.net, SADB_EXT_ADDRESS_DST, policy->dst.proto,
2987 policy->dst.mask, TRUE);
2988
2989 if (policy->route)
2990 {
2991 route_entry_t *route = policy->route;
2992 if (charon->kernel->del_route(charon->kernel, route->dst_net,
2993 route->prefixlen, route->gateway,
2994 route->src_ip, route->if_name) != SUCCESS)
2995 {
2996 DBG1(DBG_KNL, "error uninstalling route installed with "
2997 "policy %R === %R %N", id->src_ts, id->dst_ts,
2998 policy_dir_names, id->dir);
2999 }
3000 remove_exclude_route(this, route);
3001 }
3002
3003 this->policies->remove(this->policies, found, NULL);
3004 policy_sa_destroy(to_remove, id->dir, this);
3005 policy_entry_destroy(policy, this);
3006 this->mutex->unlock(this->mutex);
3007
3008 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
3009 {
3010 DBG1(DBG_KNL, "unable to delete policy %R === %R %N", id->src_ts,
3011 id->dst_ts, policy_dir_names, id->dir);
3012 return FAILED;
3013 }
3014 else if (out->sadb_msg_errno)
3015 {
3016 DBG1(DBG_KNL, "unable to delete policy %R === %R %N: %s (%d)",
3017 id->src_ts, id->dst_ts, policy_dir_names, id->dir,
3018 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
3019 free(out);
3020 return FAILED;
3021 }
3022 free(out);
3023 return SUCCESS;
3024 }
3025
3026 METHOD(kernel_ipsec_t, flush_policies, status_t,
3027 private_kernel_pfkey_ipsec_t *this)
3028 {
3029 unsigned char request[PFKEY_BUFFER_SIZE];
3030 struct sadb_msg *msg, *out;
3031 size_t len;
3032
3033 memset(&request, 0, sizeof(request));
3034
3035 DBG2(DBG_KNL, "flushing all policies from SPD");
3036
3037 msg = (struct sadb_msg*)request;
3038 msg->sadb_msg_version = PF_KEY_V2;
3039 msg->sadb_msg_type = SADB_X_SPDFLUSH;
3040 msg->sadb_msg_satype = SADB_SATYPE_UNSPEC;
3041 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
3042
3043 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
3044 {
3045 DBG1(DBG_KNL, "unable to flush SPD entries");
3046 return FAILED;
3047 }
3048 else if (out->sadb_msg_errno)
3049 {
3050 DBG1(DBG_KNL, "unable to flush SPD entries: %s (%d)",
3051 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
3052 free(out);
3053 return FAILED;
3054 }
3055 free(out);
3056 return SUCCESS;
3057 }
3058
3059 /**
3060 * Register a socket for ACQUIRE/EXPIRE messages
3061 */
3062 static status_t register_pfkey_socket(private_kernel_pfkey_ipsec_t *this,
3063 uint8_t satype)
3064 {
3065 unsigned char request[PFKEY_BUFFER_SIZE];
3066 struct sadb_msg *msg, *out;
3067 size_t len;
3068
3069 memset(&request, 0, sizeof(request));
3070
3071 msg = (struct sadb_msg*)request;
3072 msg->sadb_msg_version = PF_KEY_V2;
3073 msg->sadb_msg_type = SADB_REGISTER;
3074 msg->sadb_msg_satype = satype;
3075 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
3076
3077 if (pfkey_send_socket(this, this->socket_events, msg, &out, &len) != SUCCESS)
3078 {
3079 DBG1(DBG_KNL, "unable to register PF_KEY socket");
3080 return FAILED;
3081 }
3082 else if (out->sadb_msg_errno)
3083 {
3084 DBG1(DBG_KNL, "unable to register PF_KEY socket: %s (%d)",
3085 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
3086 free(out);
3087 return FAILED;
3088 }
3089 free(out);
3090 return SUCCESS;
3091 }
3092
3093 METHOD(kernel_ipsec_t, bypass_socket, bool,
3094 private_kernel_pfkey_ipsec_t *this, int fd, int family)
3095 {
3096 struct sadb_x_policy policy;
3097 u_int sol, ipsec_policy;
3098
3099 switch (family)
3100 {
3101 case AF_INET:
3102 {
3103 sol = SOL_IP;
3104 ipsec_policy = IP_IPSEC_POLICY;
3105 break;
3106 }
3107 case AF_INET6:
3108 {
3109 sol = SOL_IPV6;
3110 ipsec_policy = IPV6_IPSEC_POLICY;
3111 break;
3112 }
3113 default:
3114 return FALSE;
3115 }
3116
3117 memset(&policy, 0, sizeof(policy));
3118 policy.sadb_x_policy_len = sizeof(policy) / sizeof(uint64_t);
3119 policy.sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3120 policy.sadb_x_policy_type = IPSEC_POLICY_BYPASS;
3121
3122 policy.sadb_x_policy_dir = IPSEC_DIR_OUTBOUND;
3123 if (setsockopt(fd, sol, ipsec_policy, &policy, sizeof(policy)) < 0)
3124 {
3125 DBG1(DBG_KNL, "unable to set IPSEC_POLICY on socket: %s",
3126 strerror(errno));
3127 return FALSE;
3128 }
3129 policy.sadb_x_policy_dir = IPSEC_DIR_INBOUND;
3130 if (setsockopt(fd, sol, ipsec_policy, &policy, sizeof(policy)) < 0)
3131 {
3132 DBG1(DBG_KNL, "unable to set IPSEC_POLICY on socket: %s",
3133 strerror(errno));
3134 return FALSE;
3135 }
3136 return TRUE;
3137 }
3138
3139 METHOD(kernel_ipsec_t, enable_udp_decap, bool,
3140 private_kernel_pfkey_ipsec_t *this, int fd, int family, uint16_t port)
3141 {
3142 #ifndef __APPLE__
3143 int type = UDP_ENCAP_ESPINUDP;
3144
3145 if (setsockopt(fd, SOL_UDP, UDP_ENCAP, &type, sizeof(type)) < 0)
3146 {
3147 DBG1(DBG_KNL, "unable to set UDP_ENCAP: %s", strerror(errno));
3148 return FALSE;
3149 }
3150 #else /* __APPLE__ */
3151 int intport = port;
3152
3153 if (sysctlbyname("net.inet.ipsec.esp_port", NULL, NULL, &intport,
3154 sizeof(intport)) != 0)
3155 {
3156 DBG1(DBG_KNL, "could not set net.inet.ipsec.esp_port to %d: %s",
3157 port, strerror(errno));
3158 return FALSE;
3159 }
3160 #endif /* __APPLE__ */
3161
3162 return TRUE;
3163 }
3164
3165 METHOD(kernel_ipsec_t, destroy, void,
3166 private_kernel_pfkey_ipsec_t *this)
3167 {
3168 if (this->socket > 0)
3169 {
3170 close(this->socket);
3171 }
3172 if (this->socket_events > 0)
3173 {
3174 lib->watcher->remove(lib->watcher, this->socket_events);
3175 close(this->socket_events);
3176 }
3177 this->policies->invoke_function(this->policies, policy_entry_destroy_cb,
3178 this);
3179 this->policies->destroy(this->policies);
3180 this->excludes->destroy(this->excludes);
3181 this->sas->destroy(this->sas);
3182 this->mutex->destroy(this->mutex);
3183 this->mutex_pfkey->destroy(this->mutex_pfkey);
3184 free(this);
3185 }
3186
3187 /*
3188 * Described in header.
3189 */
3190 kernel_pfkey_ipsec_t *kernel_pfkey_ipsec_create()
3191 {
3192 private_kernel_pfkey_ipsec_t *this;
3193 bool register_for_events = TRUE;
3194 int rcv_buffer;
3195
3196 INIT(this,
3197 .public = {
3198 .interface = {
3199 .get_spi = _get_spi,
3200 .get_cpi = _get_cpi,
3201 .add_sa = _add_sa,
3202 .update_sa = _update_sa,
3203 .query_sa = _query_sa,
3204 .del_sa = _del_sa,
3205 .flush_sas = _flush_sas,
3206 .add_policy = _add_policy,
3207 .query_policy = _query_policy,
3208 .del_policy = _del_policy,
3209 .flush_policies = _flush_policies,
3210 .bypass_socket = _bypass_socket,
3211 .enable_udp_decap = _enable_udp_decap,
3212 .destroy = _destroy,
3213 },
3214 },
3215 .policies = linked_list_create(),
3216 .excludes = linked_list_create(),
3217 .sas = hashtable_create((hashtable_hash_t)ipsec_sa_hash,
3218 (hashtable_equals_t)ipsec_sa_equals, 32),
3219 .mutex = mutex_create(MUTEX_TYPE_DEFAULT),
3220 .mutex_pfkey = mutex_create(MUTEX_TYPE_DEFAULT),
3221 .install_routes = lib->settings->get_bool(lib->settings,
3222 "%s.install_routes", TRUE,
3223 lib->ns),
3224 .route_via_internal = lib->settings->get_bool(lib->settings,
3225 "%s.plugins.kernel-pfkey.route_via_internal",
3226 FALSE, lib->ns),
3227 );
3228
3229 if (streq(lib->ns, "starter"))
3230 { /* starter has no threads, so we do not register for kernel events */
3231 register_for_events = FALSE;
3232 }
3233
3234 /* create a PF_KEY socket to communicate with the kernel */
3235 this->socket = socket(PF_KEY, SOCK_RAW, PF_KEY_V2);
3236 if (this->socket <= 0)
3237 {
3238 DBG1(DBG_KNL, "unable to create PF_KEY socket");
3239 destroy(this);
3240 return NULL;
3241 }
3242
3243 if (register_for_events)
3244 {
3245 /* create a PF_KEY socket for ACQUIRE & EXPIRE */
3246 this->socket_events = socket(PF_KEY, SOCK_RAW, PF_KEY_V2);
3247 if (this->socket_events <= 0)
3248 {
3249 DBG1(DBG_KNL, "unable to create PF_KEY event socket");
3250 destroy(this);
3251 return NULL;
3252 }
3253
3254 rcv_buffer = lib->settings->get_int(lib->settings,
3255 "%s.plugins.kernel-pfkey.events_buffer_size", 0, lib->ns);
3256 if (rcv_buffer > 0)
3257 {
3258 if (setsockopt(this->socket_events, SOL_SOCKET, SO_RCVBUF,
3259 &rcv_buffer, sizeof(rcv_buffer)) == -1)
3260 {
3261 DBG1(DBG_KNL, "unable to set receive buffer size on PF_KEY "
3262 "event socket: %s", strerror(errno));
3263 }
3264 }
3265
3266 /* register the event socket */
3267 if (register_pfkey_socket(this, SADB_SATYPE_ESP) != SUCCESS ||
3268 register_pfkey_socket(this, SADB_SATYPE_AH) != SUCCESS)
3269 {
3270 DBG1(DBG_KNL, "unable to register PF_KEY event socket");
3271 destroy(this);
3272 return NULL;
3273 }
3274
3275 lib->watcher->add(lib->watcher, this->socket_events, WATCHER_READ,
3276 (watcher_cb_t)receive_events, this);
3277 }
3278
3279 return &this->public;
3280 }