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