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