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