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