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