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