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