5d059cf2be4dd8d1115fcafeb1473873939fe371
[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
1927 if (hydra->kernel_interface->get_address_by_ts(hydra->kernel_interface,
1928 in->dst_ts, &host, NULL) != SUCCESS)
1929 {
1930 return FALSE;
1931 }
1932
1933 /* switch src/dst, as we handle an IN policy */
1934 src = in->generic.sa->dst;
1935 dst = in->generic.sa->src;
1936
1937 INIT(route,
1938 .prefixlen = policy->src.mask,
1939 .src_ip = host,
1940 .gateway = hydra->kernel_interface->get_nexthop(
1941 hydra->kernel_interface, dst, src),
1942 .dst_net = chunk_clone(policy->src.net->get_address(policy->src.net)),
1943 );
1944
1945 /* get interface for route, using source address */
1946 if (!hydra->kernel_interface->get_interface(hydra->kernel_interface,
1947 src, &route->if_name))
1948 {
1949 route_entry_destroy(route);
1950 return FALSE;
1951 }
1952
1953 if (policy->route)
1954 {
1955 old = policy->route;
1956
1957 if (route_entry_equals(old, route))
1958 { /* such a route already exists */
1959 route_entry_destroy(route);
1960 return TRUE;
1961 }
1962 /* uninstall previously installed route */
1963 if (hydra->kernel_interface->del_route(hydra->kernel_interface,
1964 old->dst_net, old->prefixlen, old->gateway,
1965 old->src_ip, old->if_name) != SUCCESS)
1966 {
1967 DBG1(DBG_KNL, "error uninstalling route installed with policy "
1968 "%R === %R %N", in->src_ts, in->dst_ts,
1969 policy_dir_names, policy->direction);
1970 }
1971 route_entry_destroy(old);
1972 policy->route = NULL;
1973 }
1974
1975 DBG2(DBG_KNL, "installing route: %R via %H src %H dev %s",
1976 in->src_ts, route->gateway, route->src_ip, route->if_name);
1977
1978 switch (hydra->kernel_interface->add_route(hydra->kernel_interface,
1979 route->dst_net, route->prefixlen, route->gateway,
1980 route->src_ip, route->if_name))
1981 {
1982 case ALREADY_DONE:
1983 /* route exists, do not uninstall */
1984 route_entry_destroy(route);
1985 return TRUE;
1986 case SUCCESS:
1987 /* cache the installed route */
1988 policy->route = route;
1989 return TRUE;
1990 default:
1991 DBG1(DBG_KNL, "installing route failed: %R via %H src %H dev %s",
1992 in->src_ts, route->gateway, route->src_ip, route->if_name);
1993 route_entry_destroy(route);
1994 return FALSE;
1995 }
1996 }
1997
1998 /**
1999 * Add or update a policy in the kernel.
2000 *
2001 * Note: The mutex has to be locked when entering this function.
2002 */
2003 static status_t add_policy_internal(private_kernel_pfkey_ipsec_t *this,
2004 policy_entry_t *policy, policy_sa_t *mapping, bool update)
2005 {
2006 unsigned char request[PFKEY_BUFFER_SIZE];
2007 struct sadb_msg *msg, *out;
2008 struct sadb_x_policy *pol;
2009 struct sadb_x_ipsecrequest *req;
2010 ipsec_sa_t *ipsec = mapping->sa;
2011 pfkey_msg_t response;
2012 size_t len;
2013
2014 memset(&request, 0, sizeof(request));
2015
2016 msg = (struct sadb_msg*)request;
2017 msg->sadb_msg_version = PF_KEY_V2;
2018 msg->sadb_msg_type = update ? SADB_X_SPDUPDATE : SADB_X_SPDADD;
2019 msg->sadb_msg_satype = 0;
2020 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2021
2022 pol = (struct sadb_x_policy*)PFKEY_EXT_ADD_NEXT(msg);
2023 pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2024 pol->sadb_x_policy_len = PFKEY_LEN(sizeof(struct sadb_x_policy));
2025 pol->sadb_x_policy_id = 0;
2026 pol->sadb_x_policy_dir = dir2kernel(policy->direction);
2027 pol->sadb_x_policy_type = type2kernel(mapping->type);
2028 #ifdef HAVE_STRUCT_SADB_X_POLICY_SADB_X_POLICY_PRIORITY
2029 pol->sadb_x_policy_priority = mapping->priority;
2030 #endif
2031
2032 /* one or more sadb_x_ipsecrequest extensions are added to the
2033 * sadb_x_policy extension */
2034 req = (struct sadb_x_ipsecrequest*)(pol + 1);
2035 req->sadb_x_ipsecrequest_proto = ipsec->cfg.esp.use ? IPPROTO_ESP
2036 : IPPROTO_AH;
2037 /* !!! the length here MUST be in octets instead of 64 bit words */
2038 req->sadb_x_ipsecrequest_len = sizeof(struct sadb_x_ipsecrequest);
2039 req->sadb_x_ipsecrequest_mode = mode2kernel(ipsec->cfg.mode);
2040 req->sadb_x_ipsecrequest_reqid = ipsec->cfg.reqid;
2041 req->sadb_x_ipsecrequest_level = IPSEC_LEVEL_UNIQUE;
2042 if (ipsec->cfg.mode == MODE_TUNNEL)
2043 {
2044 len = hostcpy(req + 1, ipsec->src, FALSE);
2045 req->sadb_x_ipsecrequest_len += len;
2046 len = hostcpy((char*)(req + 1) + len, ipsec->dst, FALSE);
2047 req->sadb_x_ipsecrequest_len += len;
2048 }
2049
2050 pol->sadb_x_policy_len += PFKEY_LEN(req->sadb_x_ipsecrequest_len);
2051 PFKEY_EXT_ADD(msg, pol);
2052
2053 add_addr_ext(msg, policy->src.net, SADB_EXT_ADDRESS_SRC, policy->src.proto,
2054 policy->src.mask, TRUE);
2055 add_addr_ext(msg, policy->dst.net, SADB_EXT_ADDRESS_DST, policy->dst.proto,
2056 policy->dst.mask, TRUE);
2057
2058 #ifdef __FreeBSD__
2059 { /* on FreeBSD a lifetime has to be defined to be able to later query
2060 * the current use time. */
2061 struct sadb_lifetime *lft;
2062 lft = (struct sadb_lifetime*)PFKEY_EXT_ADD_NEXT(msg);
2063 lft->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2064 lft->sadb_lifetime_len = PFKEY_LEN(sizeof(struct sadb_lifetime));
2065 lft->sadb_lifetime_addtime = LONG_MAX;
2066 PFKEY_EXT_ADD(msg, lft);
2067 }
2068 #endif
2069
2070 this->mutex->unlock(this->mutex);
2071
2072 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2073 {
2074 return FAILED;
2075 }
2076 else if (out->sadb_msg_errno)
2077 {
2078 DBG1(DBG_KNL, "unable to %s policy: %s (%d)",
2079 update ? "update" : "add", strerror(out->sadb_msg_errno),
2080 out->sadb_msg_errno);
2081 free(out);
2082 return FAILED;
2083 }
2084 else if (parse_pfkey_message(out, &response) != SUCCESS)
2085 {
2086 DBG1(DBG_KNL, "unable to %s policy: parsing response from kernel "
2087 "failed", update ? "update" : "add");
2088 free(out);
2089 return FAILED;
2090 }
2091
2092 /* we try to find the policy again and update the kernel index */
2093 this->mutex->lock(this->mutex);
2094 if (this->policies->find_last(this->policies, NULL,
2095 (void**)&policy) != SUCCESS)
2096 {
2097 DBG2(DBG_KNL, "unable to update index, the policy is already gone, "
2098 "ignoring");
2099 this->mutex->unlock(this->mutex);
2100 free(out);
2101 return SUCCESS;
2102 }
2103 policy->index = response.x_policy->sadb_x_policy_id;
2104 free(out);
2105
2106 /* install a route, if:
2107 * - this is a forward policy (to just get one for each child)
2108 * - we are in tunnel mode
2109 * - routing is not disabled via strongswan.conf
2110 */
2111 if (policy->direction == POLICY_IN &&
2112 ipsec->cfg.mode != MODE_TRANSPORT && this->install_routes)
2113 {
2114 install_route(this, policy, (policy_sa_in_t*)mapping);
2115 }
2116 this->mutex->unlock(this->mutex);
2117 return SUCCESS;
2118 }
2119
2120 METHOD(kernel_ipsec_t, add_policy, status_t,
2121 private_kernel_pfkey_ipsec_t *this, host_t *src, host_t *dst,
2122 traffic_selector_t *src_ts, traffic_selector_t *dst_ts,
2123 policy_dir_t direction, policy_type_t type, ipsec_sa_cfg_t *sa,
2124 mark_t mark, policy_priority_t priority)
2125 {
2126 policy_entry_t *policy, *found = NULL;
2127 policy_sa_t *assigned_sa, *current_sa;
2128 enumerator_t *enumerator;
2129 bool update = TRUE;
2130
2131 if (dir2kernel(direction) == IPSEC_DIR_INVALID)
2132 { /* FWD policies are not supported on all platforms */
2133 return SUCCESS;
2134 }
2135
2136 /* create a policy */
2137 policy = create_policy_entry(src_ts, dst_ts, direction);
2138
2139 /* find a matching policy */
2140 this->mutex->lock(this->mutex);
2141 if (this->policies->find_first(this->policies,
2142 (linked_list_match_t)policy_entry_equals,
2143 (void**)&found, policy) == SUCCESS)
2144 { /* use existing policy */
2145 DBG2(DBG_KNL, "policy %R === %R %N already exists, increasing "
2146 "refcount", src_ts, dst_ts, policy_dir_names, direction);
2147 policy_entry_destroy(policy, this);
2148 policy = found;
2149 }
2150 else
2151 { /* use the new one, if we have no such policy */
2152 this->policies->insert_last(this->policies, policy);
2153 policy->used_by = linked_list_create();
2154 }
2155
2156 /* cache the assigned IPsec SA */
2157 assigned_sa = policy_sa_create(this, direction, type, src, dst, src_ts,
2158 dst_ts, sa);
2159 assigned_sa->priority = get_priority(policy, priority);
2160
2161 /* insert the SA according to its priority */
2162 enumerator = policy->used_by->create_enumerator(policy->used_by);
2163 while (enumerator->enumerate(enumerator, (void**)&current_sa))
2164 {
2165 if (current_sa->priority >= assigned_sa->priority)
2166 {
2167 break;
2168 }
2169 update = FALSE;
2170 }
2171 policy->used_by->insert_before(policy->used_by, enumerator, assigned_sa);
2172 enumerator->destroy(enumerator);
2173
2174 if (!update)
2175 { /* we don't update the policy if the priority is lower than that of the
2176 * currently installed one */
2177 this->mutex->unlock(this->mutex);
2178 return SUCCESS;
2179 }
2180
2181 DBG2(DBG_KNL, "%s policy %R === %R %N",
2182 found ? "updating" : "adding", src_ts, dst_ts,
2183 policy_dir_names, direction);
2184
2185 if (add_policy_internal(this, policy, assigned_sa, found) != SUCCESS)
2186 {
2187 DBG1(DBG_KNL, "unable to %s policy %R === %R %N",
2188 found ? "update" : "add", src_ts, dst_ts,
2189 policy_dir_names, direction);
2190 return FAILED;
2191 }
2192 return SUCCESS;
2193 }
2194
2195 METHOD(kernel_ipsec_t, query_policy, status_t,
2196 private_kernel_pfkey_ipsec_t *this, traffic_selector_t *src_ts,
2197 traffic_selector_t *dst_ts, policy_dir_t direction, mark_t mark,
2198 u_int32_t *use_time)
2199 {
2200 unsigned char request[PFKEY_BUFFER_SIZE];
2201 struct sadb_msg *msg, *out;
2202 struct sadb_x_policy *pol;
2203 policy_entry_t *policy, *found = NULL;
2204 pfkey_msg_t response;
2205 size_t len;
2206
2207 if (dir2kernel(direction) == IPSEC_DIR_INVALID)
2208 { /* FWD policies are not supported on all platforms */
2209 return NOT_FOUND;
2210 }
2211
2212 DBG2(DBG_KNL, "querying policy %R === %R %N", src_ts, dst_ts,
2213 policy_dir_names, direction);
2214
2215 /* create a policy */
2216 policy = create_policy_entry(src_ts, dst_ts, direction);
2217
2218 /* find a matching policy */
2219 this->mutex->lock(this->mutex);
2220 if (this->policies->find_first(this->policies,
2221 (linked_list_match_t)policy_entry_equals,
2222 (void**)&found, policy) != SUCCESS)
2223 {
2224 DBG1(DBG_KNL, "querying policy %R === %R %N failed, not found", src_ts,
2225 dst_ts, policy_dir_names, direction);
2226 policy_entry_destroy(policy, this);
2227 this->mutex->unlock(this->mutex);
2228 return NOT_FOUND;
2229 }
2230 policy_entry_destroy(policy, this);
2231 policy = found;
2232
2233 memset(&request, 0, sizeof(request));
2234
2235 msg = (struct sadb_msg*)request;
2236 msg->sadb_msg_version = PF_KEY_V2;
2237 msg->sadb_msg_type = SADB_X_SPDGET;
2238 msg->sadb_msg_satype = 0;
2239 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2240
2241 pol = (struct sadb_x_policy*)PFKEY_EXT_ADD_NEXT(msg);
2242 pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2243 pol->sadb_x_policy_id = policy->index;
2244 pol->sadb_x_policy_len = PFKEY_LEN(sizeof(struct sadb_x_policy));
2245 pol->sadb_x_policy_dir = dir2kernel(direction);
2246 pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC;
2247 PFKEY_EXT_ADD(msg, pol);
2248
2249 add_addr_ext(msg, policy->src.net, SADB_EXT_ADDRESS_SRC, policy->src.proto,
2250 policy->src.mask, TRUE);
2251 add_addr_ext(msg, policy->dst.net, SADB_EXT_ADDRESS_DST, policy->dst.proto,
2252 policy->dst.mask, TRUE);
2253
2254 this->mutex->unlock(this->mutex);
2255
2256 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2257 {
2258 DBG1(DBG_KNL, "unable to query policy %R === %R %N", src_ts, dst_ts,
2259 policy_dir_names, direction);
2260 return FAILED;
2261 }
2262 else if (out->sadb_msg_errno)
2263 {
2264 DBG1(DBG_KNL, "unable to query policy %R === %R %N: %s (%d)", src_ts,
2265 dst_ts, policy_dir_names, direction,
2266 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2267 free(out);
2268 return FAILED;
2269 }
2270 else if (parse_pfkey_message(out, &response) != SUCCESS)
2271 {
2272 DBG1(DBG_KNL, "unable to query policy %R === %R %N: parsing response "
2273 "from kernel failed", src_ts, dst_ts, policy_dir_names,
2274 direction);
2275 free(out);
2276 return FAILED;
2277 }
2278 else if (response.lft_current == NULL)
2279 {
2280 DBG1(DBG_KNL, "unable to query policy %R === %R %N: kernel reports no "
2281 "use time", src_ts, dst_ts, policy_dir_names, direction);
2282 free(out);
2283 return FAILED;
2284 }
2285
2286 /* we need the monotonic time, but the kernel returns system time. */
2287 if (response.lft_current->sadb_lifetime_usetime)
2288 {
2289 *use_time = time_monotonic(NULL) -
2290 (time(NULL) - response.lft_current->sadb_lifetime_usetime);
2291 }
2292 else
2293 {
2294 *use_time = 0;
2295 }
2296 free(out);
2297 return SUCCESS;
2298 }
2299
2300 METHOD(kernel_ipsec_t, del_policy, status_t,
2301 private_kernel_pfkey_ipsec_t *this, traffic_selector_t *src_ts,
2302 traffic_selector_t *dst_ts, policy_dir_t direction, u_int32_t reqid,
2303 mark_t mark, policy_priority_t prio)
2304 {
2305 unsigned char request[PFKEY_BUFFER_SIZE];
2306 struct sadb_msg *msg, *out;
2307 struct sadb_x_policy *pol;
2308 policy_entry_t *policy, *found = NULL;
2309 policy_sa_t *mapping;
2310 enumerator_t *enumerator;
2311 bool is_installed = TRUE;
2312 u_int32_t priority;
2313 size_t len;
2314
2315 if (dir2kernel(direction) == IPSEC_DIR_INVALID)
2316 { /* FWD policies are not supported on all platforms */
2317 return SUCCESS;
2318 }
2319
2320 DBG2(DBG_KNL, "deleting policy %R === %R %N", src_ts, dst_ts,
2321 policy_dir_names, direction);
2322
2323 /* create a policy */
2324 policy = create_policy_entry(src_ts, dst_ts, direction);
2325
2326 /* find a matching policy */
2327 this->mutex->lock(this->mutex);
2328 if (this->policies->find_first(this->policies,
2329 (linked_list_match_t)policy_entry_equals,
2330 (void**)&found, policy) != SUCCESS)
2331 {
2332 DBG1(DBG_KNL, "deleting policy %R === %R %N failed, not found", src_ts,
2333 dst_ts, policy_dir_names, direction);
2334 policy_entry_destroy(policy, this);
2335 this->mutex->unlock(this->mutex);
2336 return NOT_FOUND;
2337 }
2338 policy_entry_destroy(policy, this);
2339 policy = found;
2340
2341 /* remove mapping to SA by reqid and priority */
2342 priority = get_priority(policy, prio);
2343 enumerator = policy->used_by->create_enumerator(policy->used_by);
2344 while (enumerator->enumerate(enumerator, (void**)&mapping))
2345 {
2346 if (reqid == mapping->sa->cfg.reqid && priority == mapping->priority)
2347 {
2348 policy->used_by->remove_at(policy->used_by, enumerator);
2349 break;
2350 }
2351 is_installed = FALSE;
2352 }
2353 enumerator->destroy(enumerator);
2354
2355 if (policy->used_by->get_count(policy->used_by) > 0)
2356 { /* policy is used by more SAs, keep in kernel */
2357 DBG2(DBG_KNL, "policy still used by another CHILD_SA, not removed");
2358 policy_sa_destroy(mapping, &direction, this);
2359
2360 if (!is_installed)
2361 { /* no need to update as the policy was not installed for this SA */
2362 this->mutex->unlock(this->mutex);
2363 return SUCCESS;
2364 }
2365
2366 DBG2(DBG_KNL, "updating policy %R === %R %N", src_ts, dst_ts,
2367 policy_dir_names, direction);
2368 policy->used_by->get_first(policy->used_by, (void**)&mapping);
2369 if (add_policy_internal(this, policy, mapping, TRUE) != SUCCESS)
2370 {
2371 DBG1(DBG_KNL, "unable to update policy %R === %R %N",
2372 src_ts, dst_ts, policy_dir_names, direction);
2373 return FAILED;
2374 }
2375 return SUCCESS;
2376 }
2377
2378 memset(&request, 0, sizeof(request));
2379
2380 msg = (struct sadb_msg*)request;
2381 msg->sadb_msg_version = PF_KEY_V2;
2382 msg->sadb_msg_type = SADB_X_SPDDELETE;
2383 msg->sadb_msg_satype = 0;
2384 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2385
2386 pol = (struct sadb_x_policy*)PFKEY_EXT_ADD_NEXT(msg);
2387 pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2388 pol->sadb_x_policy_len = PFKEY_LEN(sizeof(struct sadb_x_policy));
2389 pol->sadb_x_policy_dir = dir2kernel(direction);
2390 pol->sadb_x_policy_type = type2kernel(mapping->type);
2391 PFKEY_EXT_ADD(msg, pol);
2392
2393 add_addr_ext(msg, policy->src.net, SADB_EXT_ADDRESS_SRC, policy->src.proto,
2394 policy->src.mask, TRUE);
2395 add_addr_ext(msg, policy->dst.net, SADB_EXT_ADDRESS_DST, policy->dst.proto,
2396 policy->dst.mask, TRUE);
2397
2398 if (policy->route)
2399 {
2400 route_entry_t *route = policy->route;
2401 if (hydra->kernel_interface->del_route(hydra->kernel_interface,
2402 route->dst_net, route->prefixlen, route->gateway,
2403 route->src_ip, route->if_name) != SUCCESS)
2404 {
2405 DBG1(DBG_KNL, "error uninstalling route installed with "
2406 "policy %R === %R %N", src_ts, dst_ts,
2407 policy_dir_names, direction);
2408 }
2409 }
2410
2411 this->policies->remove(this->policies, found, NULL);
2412 policy_sa_destroy(mapping, &direction, this);
2413 policy_entry_destroy(policy, this);
2414 this->mutex->unlock(this->mutex);
2415
2416 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2417 {
2418 DBG1(DBG_KNL, "unable to delete policy %R === %R %N", src_ts, dst_ts,
2419 policy_dir_names, direction);
2420 return FAILED;
2421 }
2422 else if (out->sadb_msg_errno)
2423 {
2424 DBG1(DBG_KNL, "unable to delete policy %R === %R %N: %s (%d)", src_ts,
2425 dst_ts, policy_dir_names, direction,
2426 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2427 free(out);
2428 return FAILED;
2429 }
2430 free(out);
2431 return SUCCESS;
2432 }
2433
2434 METHOD(kernel_ipsec_t, flush_policies, status_t,
2435 private_kernel_pfkey_ipsec_t *this)
2436 {
2437 unsigned char request[PFKEY_BUFFER_SIZE];
2438 struct sadb_msg *msg, *out;
2439 size_t len;
2440
2441 memset(&request, 0, sizeof(request));
2442
2443 DBG2(DBG_KNL, "flushing all policies from SPD");
2444
2445 msg = (struct sadb_msg*)request;
2446 msg->sadb_msg_version = PF_KEY_V2;
2447 msg->sadb_msg_type = SADB_X_SPDFLUSH;
2448 msg->sadb_msg_satype = SADB_SATYPE_UNSPEC;
2449 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2450
2451 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2452 {
2453 DBG1(DBG_KNL, "unable to flush SPD entries");
2454 return FAILED;
2455 }
2456 else if (out->sadb_msg_errno)
2457 {
2458 DBG1(DBG_KNL, "unable to flush SPD entries: %s (%d)",
2459 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2460 free(out);
2461 return FAILED;
2462 }
2463 free(out);
2464 return SUCCESS;
2465 }
2466
2467 /**
2468 * Register a socket for ACQUIRE/EXPIRE messages
2469 */
2470 static status_t register_pfkey_socket(private_kernel_pfkey_ipsec_t *this,
2471 u_int8_t satype)
2472 {
2473 unsigned char request[PFKEY_BUFFER_SIZE];
2474 struct sadb_msg *msg, *out;
2475 size_t len;
2476
2477 memset(&request, 0, sizeof(request));
2478
2479 msg = (struct sadb_msg*)request;
2480 msg->sadb_msg_version = PF_KEY_V2;
2481 msg->sadb_msg_type = SADB_REGISTER;
2482 msg->sadb_msg_satype = satype;
2483 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2484
2485 if (pfkey_send_socket(this, this->socket_events, msg, &out, &len) != SUCCESS)
2486 {
2487 DBG1(DBG_KNL, "unable to register PF_KEY socket");
2488 return FAILED;
2489 }
2490 else if (out->sadb_msg_errno)
2491 {
2492 DBG1(DBG_KNL, "unable to register PF_KEY socket: %s (%d)",
2493 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2494 free(out);
2495 return FAILED;
2496 }
2497 free(out);
2498 return SUCCESS;
2499 }
2500
2501 METHOD(kernel_ipsec_t, bypass_socket, bool,
2502 private_kernel_pfkey_ipsec_t *this, int fd, int family)
2503 {
2504 struct sadb_x_policy policy;
2505 u_int sol, ipsec_policy;
2506
2507 switch (family)
2508 {
2509 case AF_INET:
2510 {
2511 sol = SOL_IP;
2512 ipsec_policy = IP_IPSEC_POLICY;
2513 break;
2514 }
2515 case AF_INET6:
2516 {
2517 sol = SOL_IPV6;
2518 ipsec_policy = IPV6_IPSEC_POLICY;
2519 break;
2520 }
2521 default:
2522 return FALSE;
2523 }
2524
2525 memset(&policy, 0, sizeof(policy));
2526 policy.sadb_x_policy_len = sizeof(policy) / sizeof(u_int64_t);
2527 policy.sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2528 policy.sadb_x_policy_type = IPSEC_POLICY_BYPASS;
2529
2530 policy.sadb_x_policy_dir = IPSEC_DIR_OUTBOUND;
2531 if (setsockopt(fd, sol, ipsec_policy, &policy, sizeof(policy)) < 0)
2532 {
2533 DBG1(DBG_KNL, "unable to set IPSEC_POLICY on socket: %s",
2534 strerror(errno));
2535 return FALSE;
2536 }
2537 policy.sadb_x_policy_dir = IPSEC_DIR_INBOUND;
2538 if (setsockopt(fd, sol, ipsec_policy, &policy, sizeof(policy)) < 0)
2539 {
2540 DBG1(DBG_KNL, "unable to set IPSEC_POLICY on socket: %s",
2541 strerror(errno));
2542 return FALSE;
2543 }
2544 return TRUE;
2545 }
2546
2547 METHOD(kernel_ipsec_t, enable_udp_decap, bool,
2548 private_kernel_pfkey_ipsec_t *this, int fd, int family, u_int16_t port)
2549 {
2550 #ifndef __APPLE__
2551 int type = UDP_ENCAP_ESPINUDP;
2552
2553 if (setsockopt(fd, SOL_UDP, UDP_ENCAP, &type, sizeof(type)) < 0)
2554 {
2555 DBG1(DBG_KNL, "unable to set UDP_ENCAP: %s", strerror(errno));
2556 return FALSE;
2557 }
2558 #else /* __APPLE__ */
2559 int intport = port;
2560
2561 if (sysctlbyname("net.inet.ipsec.esp_port", NULL, NULL, &intport,
2562 sizeof(intport)) != 0)
2563 {
2564 DBG1(DBG_KNL, "could not set net.inet.ipsec.esp_port to %d: %s",
2565 port, strerror(errno));
2566 return FALSE;
2567 }
2568 #endif /* __APPLE__ */
2569
2570 return TRUE;
2571 }
2572
2573 METHOD(kernel_ipsec_t, destroy, void,
2574 private_kernel_pfkey_ipsec_t *this)
2575 {
2576 if (this->socket > 0)
2577 {
2578 close(this->socket);
2579 }
2580 if (this->socket_events > 0)
2581 {
2582 close(this->socket_events);
2583 }
2584 this->policies->invoke_function(this->policies,
2585 (linked_list_invoke_t)policy_entry_destroy,
2586 this);
2587 this->policies->destroy(this->policies);
2588 this->sas->destroy(this->sas);
2589 this->mutex->destroy(this->mutex);
2590 this->mutex_pfkey->destroy(this->mutex_pfkey);
2591 free(this);
2592 }
2593
2594 /*
2595 * Described in header.
2596 */
2597 kernel_pfkey_ipsec_t *kernel_pfkey_ipsec_create()
2598 {
2599 private_kernel_pfkey_ipsec_t *this;
2600 bool register_for_events = TRUE;
2601
2602 INIT(this,
2603 .public = {
2604 .interface = {
2605 .get_spi = _get_spi,
2606 .get_cpi = _get_cpi,
2607 .add_sa = _add_sa,
2608 .update_sa = _update_sa,
2609 .query_sa = _query_sa,
2610 .del_sa = _del_sa,
2611 .flush_sas = _flush_sas,
2612 .add_policy = _add_policy,
2613 .query_policy = _query_policy,
2614 .del_policy = _del_policy,
2615 .flush_policies = _flush_policies,
2616 .bypass_socket = _bypass_socket,
2617 .enable_udp_decap = _enable_udp_decap,
2618 .destroy = _destroy,
2619 },
2620 },
2621 .policies = linked_list_create(),
2622 .sas = hashtable_create((hashtable_hash_t)ipsec_sa_hash,
2623 (hashtable_equals_t)ipsec_sa_equals, 32),
2624 .mutex = mutex_create(MUTEX_TYPE_DEFAULT),
2625 .mutex_pfkey = mutex_create(MUTEX_TYPE_DEFAULT),
2626 .install_routes = lib->settings->get_bool(lib->settings,
2627 "%s.install_routes", TRUE,
2628 hydra->daemon),
2629 );
2630
2631 if (streq(hydra->daemon, "starter"))
2632 { /* starter has no threads, so we do not register for kernel events */
2633 register_for_events = FALSE;
2634 }
2635
2636 /* create a PF_KEY socket to communicate with the kernel */
2637 this->socket = socket(PF_KEY, SOCK_RAW, PF_KEY_V2);
2638 if (this->socket <= 0)
2639 {
2640 DBG1(DBG_KNL, "unable to create PF_KEY socket");
2641 destroy(this);
2642 return NULL;
2643 }
2644
2645 if (register_for_events)
2646 {
2647 /* create a PF_KEY socket for ACQUIRE & EXPIRE */
2648 this->socket_events = socket(PF_KEY, SOCK_RAW, PF_KEY_V2);
2649 if (this->socket_events <= 0)
2650 {
2651 DBG1(DBG_KNL, "unable to create PF_KEY event socket");
2652 destroy(this);
2653 return NULL;
2654 }
2655
2656 /* register the event socket */
2657 if (register_pfkey_socket(this, SADB_SATYPE_ESP) != SUCCESS ||
2658 register_pfkey_socket(this, SADB_SATYPE_AH) != SUCCESS)
2659 {
2660 DBG1(DBG_KNL, "unable to register PF_KEY event socket");
2661 destroy(this);
2662 return NULL;
2663 }
2664
2665 lib->processor->queue_job(lib->processor,
2666 (job_t*)callback_job_create_with_prio(
2667 (callback_job_cb_t)receive_events, this, NULL,
2668 (callback_job_cancel_t)return_false, JOB_PRIO_CRITICAL));
2669 }
2670
2671 return &this->public;
2672 }