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