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