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