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