kernel-pfkey: Use the same priority range for trap and regular 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 200000
146
147 #ifdef __APPLE__
148 /** from xnu/bsd/net/pfkeyv2.h */
149 #define SADB_X_EXT_NATT 0x002
150 struct sadb_sa_2 {
151 struct sadb_sa sa;
152 uint16_t sadb_sa_natt_port;
153 uint16_t sadb_reserved0;
154 uint32_t sadb_reserved1;
155 };
156 #endif
157
158 /** buffer size for PF_KEY messages */
159 #define PFKEY_BUFFER_SIZE 4096
160
161 /** PF_KEY messages are 64 bit aligned */
162 #define PFKEY_ALIGNMENT 8
163 /** aligns len to 64 bits */
164 #define PFKEY_ALIGN(len) (((len) + PFKEY_ALIGNMENT - 1) & ~(PFKEY_ALIGNMENT - 1))
165 /** calculates the properly padded length in 64 bit chunks */
166 #define PFKEY_LEN(len) ((PFKEY_ALIGN(len) / PFKEY_ALIGNMENT))
167 /** calculates user mode length i.e. in bytes */
168 #define PFKEY_USER_LEN(len) ((len) * PFKEY_ALIGNMENT)
169
170 /** given a PF_KEY message header and an extension this updates the length in the header */
171 #define PFKEY_EXT_ADD(msg, ext) ((msg)->sadb_msg_len += ((struct sadb_ext*)ext)->sadb_ext_len)
172 /** given a PF_KEY message header this returns a pointer to the next extension */
173 #define PFKEY_EXT_ADD_NEXT(msg) ((struct sadb_ext*)(((char*)(msg)) + PFKEY_USER_LEN((msg)->sadb_msg_len)))
174 /** copy an extension and append it to a PF_KEY message */
175 #define PFKEY_EXT_COPY(msg, ext) (PFKEY_EXT_ADD(msg, memcpy(PFKEY_EXT_ADD_NEXT(msg), ext, PFKEY_USER_LEN(((struct sadb_ext*)ext)->sadb_ext_len))))
176 /** given a PF_KEY extension this returns a pointer to the next extension */
177 #define PFKEY_EXT_NEXT(ext) ((struct sadb_ext*)(((char*)(ext)) + PFKEY_USER_LEN(((struct sadb_ext*)ext)->sadb_ext_len)))
178 /** given a PF_KEY extension this returns a pointer to the next extension also updates len (len in 64 bit words) */
179 #define PFKEY_EXT_NEXT_LEN(ext,len) ((len) -= (ext)->sadb_ext_len, PFKEY_EXT_NEXT(ext))
180 /** true if ext has a valid length and len is large enough to contain ext (assuming len in 64 bit words) */
181 #define PFKEY_EXT_OK(ext,len) ((len) >= PFKEY_LEN(sizeof(struct sadb_ext)) && \
182 (ext)->sadb_ext_len >= PFKEY_LEN(sizeof(struct sadb_ext)) && \
183 (ext)->sadb_ext_len <= (len))
184
185 typedef struct private_kernel_pfkey_ipsec_t private_kernel_pfkey_ipsec_t;
186
187 /**
188 * Private variables and functions of kernel_pfkey class.
189 */
190 struct private_kernel_pfkey_ipsec_t
191 {
192 /**
193 * Public part of the kernel_pfkey_t object.
194 */
195 kernel_pfkey_ipsec_t public;
196
197 /**
198 * mutex to lock access to various lists
199 */
200 mutex_t *mutex;
201
202 /**
203 * List of installed policies (policy_entry_t)
204 */
205 linked_list_t *policies;
206
207 /**
208 * List of exclude routes (exclude_route_t)
209 */
210 linked_list_t *excludes;
211
212 /**
213 * Hash table of IPsec SAs using policies (ipsec_sa_t)
214 */
215 hashtable_t *sas;
216
217 /**
218 * whether to install routes along policies
219 */
220 bool install_routes;
221
222 /**
223 * mutex to lock access to the PF_KEY socket
224 */
225 mutex_t *mutex_pfkey;
226
227 /**
228 * PF_KEY socket to communicate with the kernel
229 */
230 int socket;
231
232 /**
233 * PF_KEY socket to receive acquire and expire events
234 */
235 int socket_events;
236
237 /**
238 * sequence number for messages sent to the kernel
239 */
240 int seq;
241 };
242
243 typedef struct exclude_route_t exclude_route_t;
244
245 /**
246 * Exclude route definition
247 */
248 struct exclude_route_t {
249 /** destination address of exclude */
250 host_t *dst;
251 /** source address for route */
252 host_t *src;
253 /** nexthop exclude has been installed */
254 host_t *gtw;
255 /** references to this route */
256 int refs;
257 };
258
259 /**
260 * clean up a route exclude entry
261 */
262 static void exclude_route_destroy(exclude_route_t *this)
263 {
264 this->dst->destroy(this->dst);
265 this->src->destroy(this->src);
266 this->gtw->destroy(this->gtw);
267 free(this);
268 }
269
270 typedef struct route_entry_t route_entry_t;
271
272 /**
273 * installed routing entry
274 */
275 struct route_entry_t {
276 /** name of the interface the route is bound to */
277 char *if_name;
278
279 /** source ip of the route */
280 host_t *src_ip;
281
282 /** gateway for this route */
283 host_t *gateway;
284
285 /** destination net */
286 chunk_t dst_net;
287
288 /** destination net prefixlen */
289 uint8_t prefixlen;
290
291 /** reference to exclude route, if any */
292 exclude_route_t *exclude;
293 };
294
295 /**
296 * destroy an route_entry_t object
297 */
298 static void route_entry_destroy(route_entry_t *this)
299 {
300 free(this->if_name);
301 DESTROY_IF(this->src_ip);
302 DESTROY_IF(this->gateway);
303 chunk_free(&this->dst_net);
304 free(this);
305 }
306
307 /**
308 * compare two route_entry_t objects
309 */
310 static bool route_entry_equals(route_entry_t *a, route_entry_t *b)
311 {
312 return a->if_name && b->if_name && streq(a->if_name, b->if_name) &&
313 a->src_ip->ip_equals(a->src_ip, b->src_ip) &&
314 a->gateway && b->gateway &&
315 a->gateway->ip_equals(a->gateway, b->gateway) &&
316 chunk_equals(a->dst_net, b->dst_net) && a->prefixlen == b->prefixlen;
317 }
318
319 typedef struct ipsec_sa_t ipsec_sa_t;
320
321 /**
322 * IPsec SA assigned to a policy.
323 */
324 struct ipsec_sa_t {
325 /** Source address of this SA */
326 host_t *src;
327
328 /** Destination address of this SA */
329 host_t *dst;
330
331 /** Description of this SA */
332 ipsec_sa_cfg_t cfg;
333
334 /** Reference count for this SA */
335 refcount_t refcount;
336 };
337
338 /**
339 * Hash function for ipsec_sa_t objects
340 */
341 static u_int ipsec_sa_hash(ipsec_sa_t *sa)
342 {
343 return chunk_hash_inc(sa->src->get_address(sa->src),
344 chunk_hash_inc(sa->dst->get_address(sa->dst),
345 chunk_hash(chunk_from_thing(sa->cfg))));
346 }
347
348 /**
349 * Equality function for ipsec_sa_t objects
350 */
351 static bool ipsec_sa_equals(ipsec_sa_t *sa, ipsec_sa_t *other_sa)
352 {
353 return sa->src->ip_equals(sa->src, other_sa->src) &&
354 sa->dst->ip_equals(sa->dst, other_sa->dst) &&
355 ipsec_sa_cfg_equals(&sa->cfg, &other_sa->cfg);
356 }
357
358 /**
359 * Allocate or reference an IPsec SA object
360 */
361 static ipsec_sa_t *ipsec_sa_create(private_kernel_pfkey_ipsec_t *this,
362 host_t *src, host_t *dst,
363 ipsec_sa_cfg_t *cfg)
364 {
365 ipsec_sa_t *sa, *found;
366 INIT(sa,
367 .src = src,
368 .dst = dst,
369 .cfg = *cfg,
370 );
371 found = this->sas->get(this->sas, sa);
372 if (!found)
373 {
374 sa->src = src->clone(src);
375 sa->dst = dst->clone(dst);
376 this->sas->put(this->sas, sa, sa);
377 }
378 else
379 {
380 free(sa);
381 sa = found;
382 }
383 ref_get(&sa->refcount);
384 return sa;
385 }
386
387 /**
388 * Release and destroy an IPsec SA object
389 */
390 static void ipsec_sa_destroy(private_kernel_pfkey_ipsec_t *this,
391 ipsec_sa_t *sa)
392 {
393 if (ref_put(&sa->refcount))
394 {
395 this->sas->remove(this->sas, sa);
396 DESTROY_IF(sa->src);
397 DESTROY_IF(sa->dst);
398 free(sa);
399 }
400 }
401
402 typedef struct policy_sa_t policy_sa_t;
403 typedef struct policy_sa_out_t policy_sa_out_t;
404
405 /**
406 * Mapping between a policy and an IPsec SA.
407 */
408 struct policy_sa_t {
409 /** Priority assigned to the policy when installed with this SA */
410 uint32_t priority;
411
412 /** Base priority assigned to the policy when installed with this SA */
413 uint32_t auto_priority;
414
415 /** Type of the policy */
416 policy_type_t type;
417
418 /** Assigned SA */
419 ipsec_sa_t *sa;
420 };
421
422 /**
423 * For outbound policies we also cache the traffic selectors in order to install
424 * the route.
425 */
426 struct policy_sa_out_t {
427 /** Generic interface */
428 policy_sa_t generic;
429
430 /** Source traffic selector of this policy */
431 traffic_selector_t *src_ts;
432
433 /** Destination traffic selector of this policy */
434 traffic_selector_t *dst_ts;
435 };
436
437 /**
438 * Create a policy_sa(_in)_t object
439 */
440 static policy_sa_t *policy_sa_create(private_kernel_pfkey_ipsec_t *this,
441 policy_dir_t dir, policy_type_t type, host_t *src, host_t *dst,
442 traffic_selector_t *src_ts, traffic_selector_t *dst_ts, ipsec_sa_cfg_t *cfg)
443 {
444 policy_sa_t *policy;
445
446 if (dir == POLICY_OUT)
447 {
448 policy_sa_out_t *out;
449 INIT(out,
450 .src_ts = src_ts->clone(src_ts),
451 .dst_ts = dst_ts->clone(dst_ts),
452 );
453 policy = &out->generic;
454 }
455 else
456 {
457 INIT(policy, .priority = 0);
458 }
459 policy->type = type;
460 policy->sa = ipsec_sa_create(this, src, dst, cfg);
461 return policy;
462 }
463
464 /**
465 * Destroy a policy_sa(_in)_t object
466 */
467 static void policy_sa_destroy(policy_sa_t *policy, policy_dir_t *dir,
468 private_kernel_pfkey_ipsec_t *this)
469 {
470 if (*dir == POLICY_OUT)
471 {
472 policy_sa_out_t *out = (policy_sa_out_t*)policy;
473 out->src_ts->destroy(out->src_ts);
474 out->dst_ts->destroy(out->dst_ts);
475 }
476 ipsec_sa_destroy(this, policy->sa);
477 free(policy);
478 }
479
480 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: separate trap and regular policies (0..1) 1 bit
601 * bits 1-1: reserved for interface restriction (0..1) 1 bit
602 * bits 2-7: src + dst port mask bits (2 * 0..16) 6 bits
603 * bits 8-8: restriction to protocol (0..1) 1 bit
604 * bits 9-17: src + dst network mask bits (2 * 0..128) 9 bits
605 * 18 bits
606 *
607 * smallest value: 000000000 0 000000 0 0: 0, lowest priority = 100'000
608 * largest value : 100000000 1 100000 0 1: 131'457, highst priority = 68'543
609 */
610 static inline uint32_t get_priority(policy_entry_t *policy,
611 policy_priority_t prio)
612 {
613 uint32_t priority = PRIO_BASE;
614
615 switch (prio)
616 {
617 case POLICY_PRIORITY_FALLBACK:
618 priority += PRIO_BASE;
619 /* fall-through */
620 case POLICY_PRIORITY_ROUTED:
621 case POLICY_PRIORITY_DEFAULT:
622 priority += PRIO_BASE;
623 /* fall-through */
624 case POLICY_PRIORITY_PASS:
625 break;
626 }
627
628 /* calculate priority */
629 priority -= (policy->src.mask + policy->dst.mask) * 512;
630 priority -= policy->src.proto != IPSEC_PROTO_ANY ? 256 : 0;
631 priority -= policy->src.net->get_port(policy->src.net) ? 64 : 0;
632 priority -= policy->dst.net->get_port(policy->dst.net) ? 64 : 0;
633 priority -= (prio != POLICY_PRIORITY_ROUTED);
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 sa->sadb_sa_state = SADB_SASTATE_MATURE;
1721 if (id->proto == IPPROTO_COMP)
1722 {
1723 sa->sadb_sa_encrypt = lookup_algorithm(COMPRESSION_ALGORITHM,
1724 ipcomp);
1725 }
1726 else
1727 {
1728 /* Linux interprets sadb_sa_replay as number of packets/bits in the
1729 * replay window, whereas on BSD it's the size of the window in bytes.
1730 * Only set for the inbound SA as it's not relevant for the outbound
1731 * SA and might waste memory with large windows. */
1732 if (data->inbound)
1733 {
1734 #ifdef __linux__
1735 sa->sadb_sa_replay = min(data->replay_window, 32);
1736 #else
1737 sa->sadb_sa_replay = (data->replay_window + 7) / 8;
1738 #endif
1739 }
1740 sa->sadb_sa_auth = lookup_algorithm(INTEGRITY_ALGORITHM, data->int_alg);
1741 sa->sadb_sa_encrypt = lookup_algorithm(ENCRYPTION_ALGORITHM,
1742 data->enc_alg);
1743 }
1744 PFKEY_EXT_ADD(msg, sa);
1745
1746 sa2 = (struct sadb_x_sa2*)PFKEY_EXT_ADD_NEXT(msg);
1747 sa2->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
1748 sa2->sadb_x_sa2_len = PFKEY_LEN(sizeof(struct sadb_spirange));
1749 sa2->sadb_x_sa2_mode = mode2kernel(mode);
1750 sa2->sadb_x_sa2_reqid = data->reqid;
1751 PFKEY_EXT_ADD(msg, sa2);
1752
1753 add_addr_ext(msg, id->src, SADB_EXT_ADDRESS_SRC, 0, 0, FALSE);
1754 add_addr_ext(msg, id->dst, SADB_EXT_ADDRESS_DST, 0, 0, FALSE);
1755
1756 lft = (struct sadb_lifetime*)PFKEY_EXT_ADD_NEXT(msg);
1757 lft->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
1758 lft->sadb_lifetime_len = PFKEY_LEN(sizeof(struct sadb_lifetime));
1759 lft->sadb_lifetime_allocations = data->lifetime->packets.rekey;
1760 lft->sadb_lifetime_bytes = data->lifetime->bytes.rekey;
1761 lft->sadb_lifetime_addtime = data->lifetime->time.rekey;
1762 lft->sadb_lifetime_usetime = 0; /* we only use addtime */
1763 PFKEY_EXT_ADD(msg, lft);
1764
1765 lft = (struct sadb_lifetime*)PFKEY_EXT_ADD_NEXT(msg);
1766 lft->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
1767 lft->sadb_lifetime_len = PFKEY_LEN(sizeof(struct sadb_lifetime));
1768 lft->sadb_lifetime_allocations = data->lifetime->packets.life;
1769 lft->sadb_lifetime_bytes = data->lifetime->bytes.life;
1770 lft->sadb_lifetime_addtime = data->lifetime->time.life;
1771 lft->sadb_lifetime_usetime = 0; /* we only use addtime */
1772 PFKEY_EXT_ADD(msg, lft);
1773
1774 if (data->enc_alg != ENCR_UNDEFINED)
1775 {
1776 if (!sa->sadb_sa_encrypt)
1777 {
1778 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1779 encryption_algorithm_names, data->enc_alg);
1780 return FAILED;
1781 }
1782 DBG2(DBG_KNL, " using encryption algorithm %N with key size %d",
1783 encryption_algorithm_names, data->enc_alg, data->enc_key.len * 8);
1784
1785 key = (struct sadb_key*)PFKEY_EXT_ADD_NEXT(msg);
1786 key->sadb_key_exttype = SADB_EXT_KEY_ENCRYPT;
1787 key->sadb_key_bits = data->enc_key.len * 8;
1788 key->sadb_key_len = PFKEY_LEN(sizeof(struct sadb_key) + data->enc_key.len);
1789 memcpy(key + 1, data->enc_key.ptr, data->enc_key.len);
1790
1791 PFKEY_EXT_ADD(msg, key);
1792 }
1793
1794 if (data->int_alg != AUTH_UNDEFINED)
1795 {
1796 if (!sa->sadb_sa_auth)
1797 {
1798 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1799 integrity_algorithm_names, data->int_alg);
1800 return FAILED;
1801 }
1802 DBG2(DBG_KNL, " using integrity algorithm %N with key size %d",
1803 integrity_algorithm_names, data->int_alg, data->int_key.len * 8);
1804
1805 key = (struct sadb_key*)PFKEY_EXT_ADD_NEXT(msg);
1806 key->sadb_key_exttype = SADB_EXT_KEY_AUTH;
1807 key->sadb_key_bits = data->int_key.len * 8;
1808 key->sadb_key_len = PFKEY_LEN(sizeof(struct sadb_key) + data->int_key.len);
1809 memcpy(key + 1, data->int_key.ptr, data->int_key.len);
1810
1811 PFKEY_EXT_ADD(msg, key);
1812 }
1813
1814 #ifdef HAVE_NATT
1815 if (data->encap)
1816 {
1817 add_encap_ext(msg, id->src, id->dst);
1818 }
1819 #endif /*HAVE_NATT*/
1820
1821 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1822 {
1823 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x",
1824 ntohl(id->spi));
1825 return FAILED;
1826 }
1827 else if (out->sadb_msg_errno)
1828 {
1829 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x: %s (%d)",
1830 ntohl(id->spi), strerror(out->sadb_msg_errno),
1831 out->sadb_msg_errno);
1832 free(out);
1833 return FAILED;
1834 }
1835
1836 free(out);
1837 return SUCCESS;
1838 }
1839
1840 METHOD(kernel_ipsec_t, update_sa, status_t,
1841 private_kernel_pfkey_ipsec_t *this, kernel_ipsec_sa_id_t *id,
1842 kernel_ipsec_update_sa_t *data)
1843 {
1844 unsigned char request[PFKEY_BUFFER_SIZE];
1845 struct sadb_msg *msg, *out;
1846 struct sadb_sa *sa;
1847 pfkey_msg_t response;
1848 size_t len;
1849
1850 /* we can't update the SA if any of the ip addresses have changed.
1851 * that's because we can't use SADB_UPDATE and by deleting and readding the
1852 * SA the sequence numbers would get lost */
1853 if (!id->src->ip_equals(id->src, data->new_src) ||
1854 !id->dst->ip_equals(id->dst, data->new_dst))
1855 {
1856 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x: address "
1857 "changes are not supported", ntohl(id->spi));
1858 return NOT_SUPPORTED;
1859 }
1860
1861 /* if IPComp is used, we first update the IPComp SA */
1862 if (data->cpi)
1863 {
1864 kernel_ipsec_sa_id_t ipcomp_id = {
1865 .src = id->src,
1866 .dst = id->dst,
1867 .spi = htonl(ntohs(data->cpi)),
1868 .proto = IPPROTO_COMP,
1869 .mark = id->mark,
1870 };
1871 kernel_ipsec_update_sa_t ipcomp = {
1872 .new_src = data->new_src,
1873 .new_dst = data->new_dst,
1874 };
1875 update_sa(this, &ipcomp_id, &ipcomp);
1876 }
1877
1878 memset(&request, 0, sizeof(request));
1879
1880 DBG2(DBG_KNL, "querying SAD entry with SPI %.8x for update",
1881 ntohl(id->spi));
1882
1883 msg = (struct sadb_msg*)request;
1884 msg->sadb_msg_version = PF_KEY_V2;
1885 msg->sadb_msg_type = SADB_GET;
1886 msg->sadb_msg_satype = proto2satype(id->proto);
1887 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1888
1889 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1890 sa->sadb_sa_exttype = SADB_EXT_SA;
1891 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1892 sa->sadb_sa_spi = id->spi;
1893 sa->sadb_sa_state = SADB_SASTATE_MATURE;
1894 PFKEY_EXT_ADD(msg, sa);
1895
1896 /* the kernel wants a SADB_EXT_ADDRESS_SRC to be present even though
1897 * it is not used for anything. */
1898 add_anyaddr_ext(msg, id->dst->get_family(id->dst), SADB_EXT_ADDRESS_SRC);
1899 add_addr_ext(msg, id->dst, SADB_EXT_ADDRESS_DST, 0, 0, FALSE);
1900
1901 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1902 {
1903 DBG1(DBG_KNL, "unable to query SAD entry with SPI %.8x",
1904 ntohl(id->spi));
1905 return FAILED;
1906 }
1907 else if (out->sadb_msg_errno)
1908 {
1909 DBG1(DBG_KNL, "unable to query SAD entry with SPI %.8x: %s (%d)",
1910 ntohl(id->spi), strerror(out->sadb_msg_errno),
1911 out->sadb_msg_errno);
1912 free(out);
1913 return FAILED;
1914 }
1915 else if (parse_pfkey_message(out, &response) != SUCCESS)
1916 {
1917 DBG1(DBG_KNL, "unable to query SAD entry with SPI %.8x: parsing "
1918 "response from kernel failed", ntohl(id->spi));
1919 free(out);
1920 return FAILED;
1921 }
1922
1923 DBG2(DBG_KNL, "updating SAD entry with SPI %.8x from %#H..%#H to %#H..%#H",
1924 ntohl(id->spi), id->src, id->dst, data->new_src, data->new_dst);
1925
1926 memset(&request, 0, sizeof(request));
1927
1928 msg = (struct sadb_msg*)request;
1929 msg->sadb_msg_version = PF_KEY_V2;
1930 msg->sadb_msg_type = SADB_UPDATE;
1931 msg->sadb_msg_satype = proto2satype(id->proto);
1932 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1933
1934 #ifdef __APPLE__
1935 {
1936 struct sadb_sa_2 *sa_2;
1937 sa_2 = (struct sadb_sa_2*)PFKEY_EXT_ADD_NEXT(msg);
1938 sa_2->sa.sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa_2));
1939 memcpy(&sa_2->sa, response.sa, sizeof(struct sadb_sa));
1940 if (data->encap)
1941 {
1942 sa_2->sadb_sa_natt_port = data->new_dst->get_port(data->new_dst);
1943 sa_2->sa.sadb_sa_flags |= SADB_X_EXT_NATT;
1944 }
1945 }
1946 #else
1947 PFKEY_EXT_COPY(msg, response.sa);
1948 #endif
1949 PFKEY_EXT_COPY(msg, response.x_sa2);
1950
1951 PFKEY_EXT_COPY(msg, response.src);
1952 PFKEY_EXT_COPY(msg, response.dst);
1953
1954 PFKEY_EXT_COPY(msg, response.lft_soft);
1955 PFKEY_EXT_COPY(msg, response.lft_hard);
1956
1957 if (response.key_encr)
1958 {
1959 PFKEY_EXT_COPY(msg, response.key_encr);
1960 }
1961
1962 if (response.key_auth)
1963 {
1964 PFKEY_EXT_COPY(msg, response.key_auth);
1965 }
1966
1967 #ifdef HAVE_NATT
1968 if (data->new_encap)
1969 {
1970 add_encap_ext(msg, data->new_src, data->new_dst);
1971 }
1972 #endif /*HAVE_NATT*/
1973
1974 free(out);
1975
1976 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1977 {
1978 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x",
1979 ntohl(id->spi));
1980 return FAILED;
1981 }
1982 else if (out->sadb_msg_errno)
1983 {
1984 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x: %s (%d)",
1985 ntohl(id->spi), strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1986 free(out);
1987 return FAILED;
1988 }
1989 free(out);
1990
1991 return SUCCESS;
1992 }
1993
1994 METHOD(kernel_ipsec_t, query_sa, status_t,
1995 private_kernel_pfkey_ipsec_t *this, kernel_ipsec_sa_id_t *id,
1996 kernel_ipsec_query_sa_t *data, uint64_t *bytes, uint64_t *packets,
1997 time_t *time)
1998 {
1999 unsigned char request[PFKEY_BUFFER_SIZE];
2000 struct sadb_msg *msg, *out;
2001 struct sadb_sa *sa;
2002 pfkey_msg_t response;
2003 size_t len;
2004
2005 memset(&request, 0, sizeof(request));
2006
2007 DBG2(DBG_KNL, "querying SAD entry with SPI %.8x", ntohl(id->spi));
2008
2009 msg = (struct sadb_msg*)request;
2010 msg->sadb_msg_version = PF_KEY_V2;
2011 msg->sadb_msg_type = SADB_GET;
2012 msg->sadb_msg_satype = proto2satype(id->proto);
2013 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2014
2015 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
2016 sa->sadb_sa_exttype = SADB_EXT_SA;
2017 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
2018 sa->sadb_sa_spi = id->spi;
2019 PFKEY_EXT_ADD(msg, sa);
2020
2021 /* the Linux Kernel doesn't care for the src address, but other systems do
2022 * (e.g. FreeBSD)
2023 */
2024 add_addr_ext(msg, id->src, SADB_EXT_ADDRESS_SRC, 0, 0, FALSE);
2025 add_addr_ext(msg, id->dst, SADB_EXT_ADDRESS_DST, 0, 0, FALSE);
2026
2027 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2028 {
2029 DBG1(DBG_KNL, "unable to query SAD entry with SPI %.8x",
2030 ntohl(id->spi));
2031 return FAILED;
2032 }
2033 else if (out->sadb_msg_errno)
2034 {
2035 DBG1(DBG_KNL, "unable to query SAD entry with SPI %.8x: %s (%d)",
2036 ntohl(id->spi), strerror(out->sadb_msg_errno),
2037 out->sadb_msg_errno);
2038 free(out);
2039 return FAILED;
2040 }
2041 else if (parse_pfkey_message(out, &response) != SUCCESS)
2042 {
2043 DBG1(DBG_KNL, "unable to query SAD entry with SPI %.8x",
2044 ntohl(id->spi));
2045 free(out);
2046 return FAILED;
2047 }
2048 if (bytes)
2049 {
2050 *bytes = response.lft_current->sadb_lifetime_bytes;
2051 }
2052 if (packets)
2053 {
2054 /* at least on Linux and FreeBSD this contains the number of packets */
2055 *packets = response.lft_current->sadb_lifetime_allocations;
2056 }
2057 if (time)
2058 {
2059 #ifdef __APPLE__
2060 /* OS X uses the "last" time of use in usetime */
2061 *time = response.lft_current->sadb_lifetime_usetime;
2062 #else /* !__APPLE__ */
2063 /* on Linux, sadb_lifetime_usetime is set to the "first" time of use,
2064 * which is actually correct according to PF_KEY. We have to query
2065 * policies for the last usetime. */
2066 *time = 0;
2067 #endif /* !__APPLE__ */
2068 }
2069
2070 free(out);
2071 return SUCCESS;
2072 }
2073
2074 METHOD(kernel_ipsec_t, del_sa, status_t,
2075 private_kernel_pfkey_ipsec_t *this, kernel_ipsec_sa_id_t *id,
2076 kernel_ipsec_del_sa_t *data)
2077 {
2078 unsigned char request[PFKEY_BUFFER_SIZE];
2079 struct sadb_msg *msg, *out;
2080 struct sadb_sa *sa;
2081 size_t len;
2082
2083 /* if IPComp was used, we first delete the additional IPComp SA */
2084 if (data->cpi)
2085 {
2086 kernel_ipsec_sa_id_t ipcomp_id = {
2087 .src = id->src,
2088 .dst = id->dst,
2089 .spi = htonl(ntohs(data->cpi)),
2090 .proto = IPPROTO_COMP,
2091 .mark = id->mark,
2092 };
2093 kernel_ipsec_del_sa_t ipcomp = { 0 };
2094 del_sa(this, &ipcomp_id, &ipcomp);
2095 }
2096
2097 memset(&request, 0, sizeof(request));
2098
2099 DBG2(DBG_KNL, "deleting SAD entry with SPI %.8x", ntohl(id->spi));
2100
2101 msg = (struct sadb_msg*)request;
2102 msg->sadb_msg_version = PF_KEY_V2;
2103 msg->sadb_msg_type = SADB_DELETE;
2104 msg->sadb_msg_satype = proto2satype(id->proto);
2105 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2106
2107 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
2108 sa->sadb_sa_exttype = SADB_EXT_SA;
2109 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
2110 sa->sadb_sa_spi = id->spi;
2111 PFKEY_EXT_ADD(msg, sa);
2112
2113 /* the Linux Kernel doesn't care for the src address, but other systems do
2114 * (e.g. FreeBSD)
2115 */
2116 add_addr_ext(msg, id->src, SADB_EXT_ADDRESS_SRC, 0, 0, FALSE);
2117 add_addr_ext(msg, id->dst, SADB_EXT_ADDRESS_DST, 0, 0, FALSE);
2118
2119 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2120 {
2121 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x",
2122 ntohl(id->spi));
2123 return FAILED;
2124 }
2125 else if (out->sadb_msg_errno)
2126 {
2127 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x: %s (%d)",
2128 ntohl(id->spi), strerror(out->sadb_msg_errno),
2129 out->sadb_msg_errno);
2130 free(out);
2131 return FAILED;
2132 }
2133
2134 DBG2(DBG_KNL, "deleted SAD entry with SPI %.8x", ntohl(id->spi));
2135 free(out);
2136 return SUCCESS;
2137 }
2138
2139 METHOD(kernel_ipsec_t, flush_sas, status_t,
2140 private_kernel_pfkey_ipsec_t *this)
2141 {
2142 unsigned char request[PFKEY_BUFFER_SIZE];
2143 struct sadb_msg *msg, *out;
2144 struct {
2145 uint8_t proto;
2146 char *name;
2147 } protos[] = {
2148 { SADB_SATYPE_AH, "AH" },
2149 { SADB_SATYPE_ESP, "ESP" },
2150 { SADB_X_SATYPE_IPCOMP, "IPComp" },
2151 };
2152 size_t len;
2153 int i;
2154
2155 memset(&request, 0, sizeof(request));
2156
2157 msg = (struct sadb_msg*)request;
2158 msg->sadb_msg_version = PF_KEY_V2;
2159 msg->sadb_msg_type = SADB_FLUSH;
2160 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2161
2162 for (i = 0; i < countof(protos); i++)
2163 {
2164 DBG2(DBG_KNL, "flushing all %s SAD entries", protos[i].name);
2165
2166 msg->sadb_msg_satype = protos[i].proto;
2167 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2168 {
2169 DBG1(DBG_KNL, "unable to flush %s SAD entries", protos[i].name);
2170 return FAILED;
2171 }
2172 else if (out->sadb_msg_errno)
2173 {
2174 DBG1(DBG_KNL, "unable to flush %s SAD entries: %s (%d)",
2175 protos[i].name, strerror(out->sadb_msg_errno),
2176 out->sadb_msg_errno);
2177 free(out);
2178 return FAILED;
2179 }
2180 free(out);
2181 }
2182 return SUCCESS;
2183 }
2184
2185 /**
2186 * Add an explicit exclude route to a routing entry
2187 */
2188 static void add_exclude_route(private_kernel_pfkey_ipsec_t *this,
2189 route_entry_t *route, host_t *src, host_t *dst)
2190 {
2191 enumerator_t *enumerator;
2192 exclude_route_t *exclude;
2193 host_t *gtw;
2194
2195 enumerator = this->excludes->create_enumerator(this->excludes);
2196 while (enumerator->enumerate(enumerator, &exclude))
2197 {
2198 if (dst->ip_equals(dst, exclude->dst))
2199 {
2200 route->exclude = exclude;
2201 exclude->refs++;
2202 }
2203 }
2204 enumerator->destroy(enumerator);
2205
2206 if (!route->exclude)
2207 {
2208 DBG2(DBG_KNL, "installing new exclude route for %H src %H", dst, src);
2209 gtw = charon->kernel->get_nexthop(charon->kernel, dst, -1, NULL, NULL);
2210 if (gtw)
2211 {
2212 char *if_name = NULL;
2213
2214 if (charon->kernel->get_interface(charon->kernel, src, &if_name) &&
2215 charon->kernel->add_route(charon->kernel,
2216 dst->get_address(dst),
2217 dst->get_family(dst) == AF_INET ? 32 : 128,
2218 gtw, src, if_name) == SUCCESS)
2219 {
2220 INIT(exclude,
2221 .dst = dst->clone(dst),
2222 .src = src->clone(src),
2223 .gtw = gtw->clone(gtw),
2224 .refs = 1,
2225 );
2226 route->exclude = exclude;
2227 this->excludes->insert_last(this->excludes, exclude);
2228 }
2229 else
2230 {
2231 DBG1(DBG_KNL, "installing exclude route for %H failed", dst);
2232 }
2233 gtw->destroy(gtw);
2234 free(if_name);
2235 }
2236 else
2237 {
2238 DBG1(DBG_KNL, "gateway lookup for for %H failed", dst);
2239 }
2240 }
2241 }
2242
2243 /**
2244 * Remove an exclude route attached to a routing entry
2245 */
2246 static void remove_exclude_route(private_kernel_pfkey_ipsec_t *this,
2247 route_entry_t *route)
2248 {
2249 if (route->exclude)
2250 {
2251 enumerator_t *enumerator;
2252 exclude_route_t *exclude;
2253 bool removed = FALSE;
2254 host_t *dst;
2255
2256 enumerator = this->excludes->create_enumerator(this->excludes);
2257 while (enumerator->enumerate(enumerator, &exclude))
2258 {
2259 if (route->exclude == exclude)
2260 {
2261 if (--exclude->refs == 0)
2262 {
2263 this->excludes->remove_at(this->excludes, enumerator);
2264 removed = TRUE;
2265 break;
2266 }
2267 }
2268 }
2269 enumerator->destroy(enumerator);
2270
2271 if (removed)
2272 {
2273 char *if_name = NULL;
2274
2275 dst = route->exclude->dst;
2276 DBG2(DBG_KNL, "uninstalling exclude route for %H src %H",
2277 dst, route->exclude->src);
2278 if (charon->kernel->get_interface(
2279 charon->kernel,
2280 route->exclude->src, &if_name) &&
2281 charon->kernel->del_route(charon->kernel,
2282 dst->get_address(dst),
2283 dst->get_family(dst) == AF_INET ? 32 : 128,
2284 route->exclude->gtw, route->exclude->src,
2285 if_name) != SUCCESS)
2286 {
2287 DBG1(DBG_KNL, "uninstalling exclude route for %H failed", dst);
2288 }
2289 exclude_route_destroy(route->exclude);
2290 free(if_name);
2291 }
2292 route->exclude = NULL;
2293 }
2294 }
2295
2296 /**
2297 * Try to install a route to the given outbound policy
2298 */
2299 static bool install_route(private_kernel_pfkey_ipsec_t *this,
2300 policy_entry_t *policy, policy_sa_out_t *out)
2301 {
2302 route_entry_t *route, *old;
2303 host_t *host, *src, *dst;
2304 bool is_virtual;
2305
2306 if (charon->kernel->get_address_by_ts(charon->kernel, out->src_ts, &host,
2307 &is_virtual) != SUCCESS)
2308 {
2309 return FALSE;
2310 }
2311
2312 INIT(route,
2313 .prefixlen = policy->dst.mask,
2314 .src_ip = host,
2315 .dst_net = chunk_clone(policy->dst.net->get_address(policy->dst.net)),
2316 );
2317
2318 src = out->generic.sa->src;
2319 dst = out->generic.sa->dst;
2320
2321 if (!dst->is_anyaddr(dst))
2322 {
2323 route->gateway = charon->kernel->get_nexthop(charon->kernel, dst, -1,
2324 src, &route->if_name);
2325
2326 /* if the IP is virtual, we install the route over the interface it has
2327 * been installed on. Otherwise we use the interface we use for IKE, as
2328 * this is required for example on Linux. */
2329 if (is_virtual)
2330 {
2331 free(route->if_name);
2332 route->if_name = NULL;
2333 src = route->src_ip;
2334 }
2335 }
2336 else
2337 { /* for shunt policies */
2338 route->gateway = charon->kernel->get_nexthop(charon->kernel,
2339 policy->dst.net, policy->dst.mask,
2340 route->src_ip, &route->if_name);
2341
2342 /* we don't have a source address, use the address we found */
2343 src = route->src_ip;
2344 }
2345
2346 /* get interface for route, using source address */
2347 if (!route->if_name &&
2348 !charon->kernel->get_interface(charon->kernel, src, &route->if_name))
2349 {
2350 route_entry_destroy(route);
2351 return FALSE;
2352 }
2353
2354 if (policy->route)
2355 {
2356 old = policy->route;
2357
2358 if (route_entry_equals(old, route))
2359 { /* such a route already exists */
2360 route_entry_destroy(route);
2361 return TRUE;
2362 }
2363 /* uninstall previously installed route */
2364 if (charon->kernel->del_route(charon->kernel, old->dst_net,
2365 old->prefixlen, old->gateway,
2366 old->src_ip, old->if_name) != SUCCESS)
2367 {
2368 DBG1(DBG_KNL, "error uninstalling route installed with policy "
2369 "%R === %R %N", out->src_ts, out->dst_ts,
2370 policy_dir_names, policy->direction);
2371 }
2372 route_entry_destroy(old);
2373 policy->route = NULL;
2374 }
2375
2376 /* if remote traffic selector covers the IKE peer, add an exclude route */
2377 if (charon->kernel->get_features(charon->kernel) & KERNEL_REQUIRE_EXCLUDE_ROUTE)
2378 {
2379 if (out->dst_ts->is_host(out->dst_ts, dst))
2380 {
2381 DBG1(DBG_KNL, "can't install route for %R === %R %N, conflicts "
2382 "with IKE traffic", out->src_ts, out->dst_ts, policy_dir_names,
2383 policy->direction);
2384 route_entry_destroy(route);
2385 return FALSE;
2386 }
2387 if (out->dst_ts->includes(out->dst_ts, dst))
2388 {
2389 add_exclude_route(this, route, out->generic.sa->src, dst);
2390 }
2391 }
2392
2393 DBG2(DBG_KNL, "installing route: %R via %H src %H dev %s",
2394 out->dst_ts, route->gateway, route->src_ip, route->if_name);
2395
2396 switch (charon->kernel->add_route(charon->kernel, route->dst_net,
2397 route->prefixlen, route->gateway,
2398 route->src_ip, route->if_name))
2399 {
2400 case ALREADY_DONE:
2401 /* route exists, do not uninstall */
2402 remove_exclude_route(this, route);
2403 route_entry_destroy(route);
2404 return TRUE;
2405 case SUCCESS:
2406 /* cache the installed route */
2407 policy->route = route;
2408 return TRUE;
2409 default:
2410 DBG1(DBG_KNL, "installing route failed: %R via %H src %H dev %s",
2411 out->dst_ts, route->gateway, route->src_ip, route->if_name);
2412 remove_exclude_route(this, route);
2413 route_entry_destroy(route);
2414 return FALSE;
2415 }
2416 }
2417
2418 /**
2419 * Add or update a policy in the kernel.
2420 *
2421 * Note: The mutex has to be locked when entering this function.
2422 */
2423 static status_t add_policy_internal(private_kernel_pfkey_ipsec_t *this,
2424 policy_entry_t *policy, policy_sa_t *mapping, bool update)
2425 {
2426 unsigned char request[PFKEY_BUFFER_SIZE];
2427 struct sadb_msg *msg, *out;
2428 struct sadb_x_policy *pol;
2429 struct sadb_x_ipsecrequest *req;
2430 ipsec_sa_t *ipsec = mapping->sa;
2431 pfkey_msg_t response;
2432 size_t len;
2433 ipsec_mode_t proto_mode;
2434 status_t status;
2435
2436 memset(&request, 0, sizeof(request));
2437
2438 msg = (struct sadb_msg*)request;
2439 msg->sadb_msg_version = PF_KEY_V2;
2440 msg->sadb_msg_type = update ? SADB_X_SPDUPDATE : SADB_X_SPDADD;
2441 msg->sadb_msg_satype = 0;
2442 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2443
2444 pol = (struct sadb_x_policy*)PFKEY_EXT_ADD_NEXT(msg);
2445 pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2446 pol->sadb_x_policy_len = PFKEY_LEN(sizeof(struct sadb_x_policy));
2447 pol->sadb_x_policy_id = 0;
2448 pol->sadb_x_policy_dir = dir2kernel(policy->direction);
2449 pol->sadb_x_policy_type = type2kernel(mapping->type);
2450 #ifdef HAVE_STRUCT_SADB_X_POLICY_SADB_X_POLICY_PRIORITY
2451 pol->sadb_x_policy_priority = mapping->priority;
2452 #endif
2453
2454 if (mapping->type == POLICY_IPSEC && ipsec->cfg.reqid)
2455 {
2456 /* one or more sadb_x_ipsecrequest extensions are added to the
2457 * sadb_x_policy extension */
2458 proto_mode = ipsec->cfg.mode;
2459
2460 req = (struct sadb_x_ipsecrequest*)(pol + 1);
2461
2462 if (ipsec->cfg.ipcomp.transform != IPCOMP_NONE)
2463 {
2464 req->sadb_x_ipsecrequest_proto = IPPROTO_COMP;
2465
2466 /* !!! the length here MUST be in octets instead of 64 bit words */
2467 req->sadb_x_ipsecrequest_len = sizeof(struct sadb_x_ipsecrequest);
2468 req->sadb_x_ipsecrequest_mode = mode2kernel(ipsec->cfg.mode);
2469 req->sadb_x_ipsecrequest_reqid = ipsec->cfg.reqid;
2470 req->sadb_x_ipsecrequest_level = (policy->direction == POLICY_OUT) ?
2471 IPSEC_LEVEL_UNIQUE : IPSEC_LEVEL_USE;
2472 if (ipsec->cfg.mode == MODE_TUNNEL)
2473 {
2474 len = hostcpy(req + 1, ipsec->src, FALSE);
2475 req->sadb_x_ipsecrequest_len += len;
2476 len = hostcpy((char*)(req + 1) + len, ipsec->dst, FALSE);
2477 req->sadb_x_ipsecrequest_len += len;
2478 /* use transport mode for other SAs */
2479 proto_mode = MODE_TRANSPORT;
2480 }
2481
2482 pol->sadb_x_policy_len += PFKEY_LEN(req->sadb_x_ipsecrequest_len);
2483 req = (struct sadb_x_ipsecrequest*)((char*)(req) +
2484 req->sadb_x_ipsecrequest_len);
2485 }
2486
2487 req->sadb_x_ipsecrequest_proto = ipsec->cfg.esp.use ? IPPROTO_ESP
2488 : IPPROTO_AH;
2489 /* !!! the length here MUST be in octets instead of 64 bit words */
2490 req->sadb_x_ipsecrequest_len = sizeof(struct sadb_x_ipsecrequest);
2491 req->sadb_x_ipsecrequest_mode = mode2kernel(proto_mode);
2492 req->sadb_x_ipsecrequest_reqid = ipsec->cfg.reqid;
2493 req->sadb_x_ipsecrequest_level = IPSEC_LEVEL_UNIQUE;
2494 if (proto_mode == MODE_TUNNEL)
2495 {
2496 len = hostcpy(req + 1, ipsec->src, FALSE);
2497 req->sadb_x_ipsecrequest_len += len;
2498 len = hostcpy((char*)(req + 1) + len, ipsec->dst, FALSE);
2499 req->sadb_x_ipsecrequest_len += len;
2500 }
2501
2502 pol->sadb_x_policy_len += PFKEY_LEN(req->sadb_x_ipsecrequest_len);
2503 }
2504 PFKEY_EXT_ADD(msg, pol);
2505
2506 add_addr_ext(msg, policy->src.net, SADB_EXT_ADDRESS_SRC, policy->src.proto,
2507 policy->src.mask, TRUE);
2508 add_addr_ext(msg, policy->dst.net, SADB_EXT_ADDRESS_DST, policy->dst.proto,
2509 policy->dst.mask, TRUE);
2510
2511 #ifdef __FreeBSD__
2512 { /* on FreeBSD a lifetime has to be defined to be able to later query
2513 * the current use time. */
2514 struct sadb_lifetime *lft;
2515 lft = (struct sadb_lifetime*)PFKEY_EXT_ADD_NEXT(msg);
2516 lft->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2517 lft->sadb_lifetime_len = PFKEY_LEN(sizeof(struct sadb_lifetime));
2518 lft->sadb_lifetime_addtime = LONG_MAX;
2519 PFKEY_EXT_ADD(msg, lft);
2520 }
2521 #endif
2522
2523 this->mutex->unlock(this->mutex);
2524
2525 status = pfkey_send(this, msg, &out, &len);
2526 if (status == SUCCESS && !update && out->sadb_msg_errno == EEXIST)
2527 {
2528 DBG1(DBG_KNL, "policy already exists, try to update it");
2529 free(out);
2530 msg->sadb_msg_type = SADB_X_SPDUPDATE;
2531 status = pfkey_send(this, msg, &out, &len);
2532 }
2533 if (status != SUCCESS)
2534 {
2535 return FAILED;
2536 }
2537 else if (out->sadb_msg_errno)
2538 {
2539 DBG1(DBG_KNL, "unable to %s policy: %s (%d)",
2540 update ? "update" : "add", strerror(out->sadb_msg_errno),
2541 out->sadb_msg_errno);
2542 free(out);
2543 return FAILED;
2544 }
2545 else if (parse_pfkey_message(out, &response) != SUCCESS)
2546 {
2547 DBG1(DBG_KNL, "unable to %s policy: parsing response from kernel "
2548 "failed", update ? "update" : "add");
2549 free(out);
2550 return FAILED;
2551 }
2552
2553 /* we try to find the policy again and update the kernel index */
2554 this->mutex->lock(this->mutex);
2555 if (this->policies->find_first(this->policies, NULL,
2556 (void**)&policy) != SUCCESS)
2557 {
2558 DBG2(DBG_KNL, "unable to update index, the policy is already gone, "
2559 "ignoring");
2560 this->mutex->unlock(this->mutex);
2561 free(out);
2562 return SUCCESS;
2563 }
2564 policy->index = response.x_policy->sadb_x_policy_id;
2565 free(out);
2566
2567 /* install a route, if:
2568 * - this is an outbound policy (to just get one for each child)
2569 * - routing is not disabled via strongswan.conf
2570 * - the selector is not for a specific protocol/port
2571 * - we are in tunnel mode or install a bypass policy
2572 */
2573 if (policy->direction == POLICY_OUT && this->install_routes &&
2574 policy->src.proto == IPSEC_PROTO_ANY &&
2575 !policy->src.net->get_port(policy->src.net) &&
2576 !policy->dst.net->get_port(policy->dst.net))
2577 {
2578 if (mapping->type == POLICY_PASS ||
2579 (mapping->type == POLICY_IPSEC && ipsec->cfg.mode != MODE_TRANSPORT))
2580 {
2581 install_route(this, policy, (policy_sa_out_t*)mapping);
2582 }
2583 }
2584 this->mutex->unlock(this->mutex);
2585 return SUCCESS;
2586 }
2587
2588 METHOD(kernel_ipsec_t, add_policy, status_t,
2589 private_kernel_pfkey_ipsec_t *this, kernel_ipsec_policy_id_t *id,
2590 kernel_ipsec_manage_policy_t *data)
2591 {
2592 policy_entry_t *policy, *found = NULL;
2593 policy_sa_t *assigned_sa, *current_sa;
2594 enumerator_t *enumerator;
2595 bool update = TRUE;
2596
2597 if (dir2kernel(id->dir) == IPSEC_DIR_INVALID)
2598 { /* FWD policies are not supported on all platforms */
2599 return SUCCESS;
2600 }
2601
2602 /* create a policy */
2603 policy = create_policy_entry(id->src_ts, id->dst_ts, id->dir);
2604
2605 /* find a matching policy */
2606 this->mutex->lock(this->mutex);
2607 if (this->policies->find_first(this->policies,
2608 (linked_list_match_t)policy_entry_equals,
2609 (void**)&found, policy) == SUCCESS)
2610 { /* use existing policy */
2611 DBG2(DBG_KNL, "policy %R === %R %N already exists, increasing "
2612 "refcount", id->src_ts, id->dst_ts, policy_dir_names, id->dir);
2613 policy_entry_destroy(policy, this);
2614 policy = found;
2615 }
2616 else
2617 { /* use the new one, if we have no such policy */
2618 this->policies->insert_first(this->policies, policy);
2619 policy->used_by = linked_list_create();
2620 }
2621
2622 /* cache the assigned IPsec SA */
2623 assigned_sa = policy_sa_create(this, id->dir, data->type, data->src,
2624 data->dst, id->src_ts, id->dst_ts, data->sa);
2625 assigned_sa->auto_priority = get_priority(policy, data->prio);
2626 assigned_sa->priority = data->manual_prio ? data->manual_prio :
2627 assigned_sa->auto_priority;
2628
2629
2630 /* insert the SA according to its priority */
2631 enumerator = policy->used_by->create_enumerator(policy->used_by);
2632 while (enumerator->enumerate(enumerator, (void**)&current_sa))
2633 {
2634 if (current_sa->priority > assigned_sa->priority)
2635 {
2636 break;
2637 }
2638 if (current_sa->priority == assigned_sa->priority)
2639 {
2640 /* in case of equal manual prios order SAs by automatic priority */
2641 if (current_sa->auto_priority > assigned_sa->auto_priority)
2642 {
2643 break;
2644 }
2645 /* prefer SAs with a reqid over those without */
2646 if (current_sa->auto_priority == assigned_sa->auto_priority &&
2647 (!current_sa->sa->cfg.reqid || assigned_sa->sa->cfg.reqid))
2648 {
2649 break;
2650 }
2651 }
2652 update = FALSE;
2653 }
2654 policy->used_by->insert_before(policy->used_by, enumerator, assigned_sa);
2655 enumerator->destroy(enumerator);
2656
2657 if (!update)
2658 { /* we don't update the policy if the priority is lower than that of the
2659 * currently installed one */
2660 this->mutex->unlock(this->mutex);
2661 return SUCCESS;
2662 }
2663
2664 DBG2(DBG_KNL, "%s policy %R === %R %N",
2665 found ? "updating" : "adding", id->src_ts, id->dst_ts,
2666 policy_dir_names, id->dir);
2667
2668 if (add_policy_internal(this, policy, assigned_sa, found) != SUCCESS)
2669 {
2670 DBG1(DBG_KNL, "unable to %s policy %R === %R %N",
2671 found ? "update" : "add", id->src_ts, id->dst_ts,
2672 policy_dir_names, id->dir);
2673 return FAILED;
2674 }
2675 return SUCCESS;
2676 }
2677
2678 METHOD(kernel_ipsec_t, query_policy, status_t,
2679 private_kernel_pfkey_ipsec_t *this, kernel_ipsec_policy_id_t *id,
2680 kernel_ipsec_query_policy_t *data, time_t *use_time)
2681 {
2682 unsigned char request[PFKEY_BUFFER_SIZE];
2683 struct sadb_msg *msg, *out;
2684 struct sadb_x_policy *pol;
2685 policy_entry_t *policy, *found = NULL;
2686 pfkey_msg_t response;
2687 size_t len;
2688
2689 if (dir2kernel(id->dir) == IPSEC_DIR_INVALID)
2690 { /* FWD policies are not supported on all platforms */
2691 return NOT_FOUND;
2692 }
2693
2694 DBG2(DBG_KNL, "querying policy %R === %R %N", id->src_ts, id->dst_ts,
2695 policy_dir_names, id->dir);
2696
2697 /* create a policy */
2698 policy = create_policy_entry(id->src_ts, id->dst_ts, id->dir);
2699
2700 /* find a matching policy */
2701 this->mutex->lock(this->mutex);
2702 if (this->policies->find_first(this->policies,
2703 (linked_list_match_t)policy_entry_equals,
2704 (void**)&found, policy) != SUCCESS)
2705 {
2706 DBG1(DBG_KNL, "querying policy %R === %R %N failed, not found",
2707 id->src_ts, id->dst_ts, policy_dir_names, id->dir);
2708 policy_entry_destroy(policy, this);
2709 this->mutex->unlock(this->mutex);
2710 return NOT_FOUND;
2711 }
2712 policy_entry_destroy(policy, this);
2713 policy = found;
2714
2715 memset(&request, 0, sizeof(request));
2716
2717 msg = (struct sadb_msg*)request;
2718 msg->sadb_msg_version = PF_KEY_V2;
2719 msg->sadb_msg_type = SADB_X_SPDGET;
2720 msg->sadb_msg_satype = 0;
2721 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2722
2723 pol = (struct sadb_x_policy*)PFKEY_EXT_ADD_NEXT(msg);
2724 pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2725 pol->sadb_x_policy_id = policy->index;
2726 pol->sadb_x_policy_len = PFKEY_LEN(sizeof(struct sadb_x_policy));
2727 pol->sadb_x_policy_dir = dir2kernel(id->dir);
2728 pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC;
2729 PFKEY_EXT_ADD(msg, pol);
2730
2731 add_addr_ext(msg, policy->src.net, SADB_EXT_ADDRESS_SRC, policy->src.proto,
2732 policy->src.mask, TRUE);
2733 add_addr_ext(msg, policy->dst.net, SADB_EXT_ADDRESS_DST, policy->dst.proto,
2734 policy->dst.mask, TRUE);
2735
2736 this->mutex->unlock(this->mutex);
2737
2738 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2739 {
2740 DBG1(DBG_KNL, "unable to query policy %R === %R %N", id->src_ts,
2741 id->dst_ts, policy_dir_names, id->dir);
2742 return FAILED;
2743 }
2744 else if (out->sadb_msg_errno)
2745 {
2746 DBG1(DBG_KNL, "unable to query policy %R === %R %N: %s (%d)",
2747 id->src_ts, id->dst_ts, policy_dir_names, id->dir,
2748 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2749 free(out);
2750 return FAILED;
2751 }
2752 else if (parse_pfkey_message(out, &response) != SUCCESS)
2753 {
2754 DBG1(DBG_KNL, "unable to query policy %R === %R %N: parsing response "
2755 "from kernel failed", id->src_ts, id->dst_ts, policy_dir_names,
2756 id->dir);
2757 free(out);
2758 return FAILED;
2759 }
2760 else if (response.lft_current == NULL)
2761 {
2762 DBG2(DBG_KNL, "unable to query policy %R === %R %N: kernel reports no "
2763 "use time", id->src_ts, id->dst_ts, policy_dir_names,
2764 id->dir);
2765 free(out);
2766 return FAILED;
2767 }
2768
2769 /* we need the monotonic time, but the kernel returns system time. */
2770 if (response.lft_current->sadb_lifetime_usetime)
2771 {
2772 *use_time = time_monotonic(NULL) -
2773 (time(NULL) - response.lft_current->sadb_lifetime_usetime);
2774 }
2775 else
2776 {
2777 *use_time = 0;
2778 }
2779 free(out);
2780 return SUCCESS;
2781 }
2782
2783 METHOD(kernel_ipsec_t, del_policy, status_t,
2784 private_kernel_pfkey_ipsec_t *this, kernel_ipsec_policy_id_t *id,
2785 kernel_ipsec_manage_policy_t *data)
2786 {
2787 unsigned char request[PFKEY_BUFFER_SIZE];
2788 struct sadb_msg *msg, *out;
2789 struct sadb_x_policy *pol;
2790 policy_entry_t *policy, *found = NULL;
2791 policy_sa_t *mapping, *to_remove = NULL;
2792 enumerator_t *enumerator;
2793 bool first = TRUE, is_installed = TRUE;
2794 uint32_t priority, auto_priority;
2795 size_t len;
2796 ipsec_sa_t assigned_sa = {
2797 .src = data->src,
2798 .dst = data->dst,
2799 .cfg = *data->sa,
2800 };
2801
2802 if (dir2kernel(id->dir) == IPSEC_DIR_INVALID)
2803 { /* FWD policies are not supported on all platforms */
2804 return SUCCESS;
2805 }
2806
2807 DBG2(DBG_KNL, "deleting policy %R === %R %N", id->src_ts, id->dst_ts,
2808 policy_dir_names, id->dir);
2809
2810 /* create a policy */
2811 policy = create_policy_entry(id->src_ts, id->dst_ts, id->dir);
2812
2813 /* find a matching policy */
2814 this->mutex->lock(this->mutex);
2815 if (this->policies->find_first(this->policies,
2816 (linked_list_match_t)policy_entry_equals,
2817 (void**)&found, policy) != SUCCESS)
2818 {
2819 DBG1(DBG_KNL, "deleting policy %R === %R %N failed, not found",
2820 id->src_ts, id->dst_ts, policy_dir_names, id->dir);
2821 policy_entry_destroy(policy, this);
2822 this->mutex->unlock(this->mutex);
2823 return NOT_FOUND;
2824 }
2825 policy_entry_destroy(policy, this);
2826 policy = found;
2827
2828 /* remove mapping to SA by reqid and priority, if multiple match, which
2829 * could happen when rekeying due to an address change, remove the oldest */
2830 auto_priority = get_priority(policy, data->prio);
2831 priority = data->manual_prio ? data->manual_prio : auto_priority;
2832 enumerator = policy->used_by->create_enumerator(policy->used_by);
2833 while (enumerator->enumerate(enumerator, (void**)&mapping))
2834 {
2835 if (priority == mapping->priority &&
2836 auto_priority == mapping->auto_priority &&
2837 data->type == mapping->type &&
2838 ipsec_sa_equals(mapping->sa, &assigned_sa))
2839 {
2840 to_remove = mapping;
2841 is_installed = first;
2842 }
2843 else if (priority < mapping->priority)
2844 {
2845 break;
2846 }
2847 first = FALSE;
2848 }
2849 enumerator->destroy(enumerator);
2850 if (!to_remove)
2851 { /* sanity check */
2852 this->mutex->unlock(this->mutex);
2853 return SUCCESS;
2854 }
2855 policy->used_by->remove(policy->used_by, to_remove, NULL);
2856 mapping = to_remove;
2857
2858 if (policy->used_by->get_count(policy->used_by) > 0)
2859 { /* policy is used by more SAs, keep in kernel */
2860 DBG2(DBG_KNL, "policy still used by another CHILD_SA, not removed");
2861 policy_sa_destroy(mapping, &id->dir, this);
2862
2863 if (!is_installed)
2864 { /* no need to update as the policy was not installed for this SA */
2865 this->mutex->unlock(this->mutex);
2866 return SUCCESS;
2867 }
2868
2869 DBG2(DBG_KNL, "updating policy %R === %R %N", id->src_ts, id->dst_ts,
2870 policy_dir_names, id->dir);
2871 policy->used_by->get_first(policy->used_by, (void**)&mapping);
2872 if (add_policy_internal(this, policy, mapping, TRUE) != SUCCESS)
2873 {
2874 DBG1(DBG_KNL, "unable to update policy %R === %R %N",
2875 id->src_ts, id->dst_ts, policy_dir_names, id->dir);
2876 return FAILED;
2877 }
2878 return SUCCESS;
2879 }
2880
2881 memset(&request, 0, sizeof(request));
2882
2883 msg = (struct sadb_msg*)request;
2884 msg->sadb_msg_version = PF_KEY_V2;
2885 msg->sadb_msg_type = SADB_X_SPDDELETE;
2886 msg->sadb_msg_satype = 0;
2887 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2888
2889 pol = (struct sadb_x_policy*)PFKEY_EXT_ADD_NEXT(msg);
2890 pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2891 pol->sadb_x_policy_len = PFKEY_LEN(sizeof(struct sadb_x_policy));
2892 pol->sadb_x_policy_dir = dir2kernel(id->dir);
2893 pol->sadb_x_policy_type = type2kernel(mapping->type);
2894 PFKEY_EXT_ADD<