linked-list: Remove barely used find_last() method
[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 initiator, bool encap, bool esn,
1527 bool inbound, 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, u_int32_t *time)
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 if (time)
1866 {
1867 #ifdef __APPLE__
1868 /* OS X uses the "last" time of use in usetime */
1869 *time = response.lft_current->sadb_lifetime_usetime;
1870 #else /* !__APPLE__ */
1871 /* on Linux, sadb_lifetime_usetime is set to the "first" time of use,
1872 * which is actually correct according to PF_KEY. We have to query
1873 * policies for the last usetime. */
1874 *time = 0;
1875 #endif /* !__APPLE__ */
1876 }
1877
1878 free(out);
1879 return SUCCESS;
1880 }
1881
1882 METHOD(kernel_ipsec_t, del_sa, status_t,
1883 private_kernel_pfkey_ipsec_t *this, host_t *src, host_t *dst,
1884 u_int32_t spi, u_int8_t protocol, u_int16_t cpi, mark_t mark)
1885 {
1886 unsigned char request[PFKEY_BUFFER_SIZE];
1887 struct sadb_msg *msg, *out;
1888 struct sadb_sa *sa;
1889 size_t len;
1890
1891 memset(&request, 0, sizeof(request));
1892
1893 DBG2(DBG_KNL, "deleting SAD entry with SPI %.8x", ntohl(spi));
1894
1895 msg = (struct sadb_msg*)request;
1896 msg->sadb_msg_version = PF_KEY_V2;
1897 msg->sadb_msg_type = SADB_DELETE;
1898 msg->sadb_msg_satype = proto2satype(protocol);
1899 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1900
1901 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1902 sa->sadb_sa_exttype = SADB_EXT_SA;
1903 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1904 sa->sadb_sa_spi = spi;
1905 PFKEY_EXT_ADD(msg, sa);
1906
1907 /* the Linux Kernel doesn't care for the src address, but other systems do
1908 * (e.g. FreeBSD)
1909 */
1910 add_addr_ext(msg, src, SADB_EXT_ADDRESS_SRC, 0, 0, FALSE);
1911 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST, 0, 0, FALSE);
1912
1913 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1914 {
1915 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x", ntohl(spi));
1916 return FAILED;
1917 }
1918 else if (out->sadb_msg_errno)
1919 {
1920 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x: %s (%d)",
1921 ntohl(spi), strerror(out->sadb_msg_errno),
1922 out->sadb_msg_errno);
1923 free(out);
1924 return FAILED;
1925 }
1926
1927 DBG2(DBG_KNL, "deleted SAD entry with SPI %.8x", ntohl(spi));
1928 free(out);
1929 return SUCCESS;
1930 }
1931
1932 METHOD(kernel_ipsec_t, flush_sas, status_t,
1933 private_kernel_pfkey_ipsec_t *this)
1934 {
1935 unsigned char request[PFKEY_BUFFER_SIZE];
1936 struct sadb_msg *msg, *out;
1937 size_t len;
1938
1939 memset(&request, 0, sizeof(request));
1940
1941 DBG2(DBG_KNL, "flushing all SAD entries");
1942
1943 msg = (struct sadb_msg*)request;
1944 msg->sadb_msg_version = PF_KEY_V2;
1945 msg->sadb_msg_type = SADB_FLUSH;
1946 msg->sadb_msg_satype = SADB_SATYPE_UNSPEC;
1947 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1948
1949 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1950 {
1951 DBG1(DBG_KNL, "unable to flush SAD entries");
1952 return FAILED;
1953 }
1954 else if (out->sadb_msg_errno)
1955 {
1956 DBG1(DBG_KNL, "unable to flush SAD entries: %s (%d)",
1957 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1958 free(out);
1959 return FAILED;
1960 }
1961 free(out);
1962 return SUCCESS;
1963 }
1964
1965 /**
1966 * Add an explicit exclude route to a routing entry
1967 */
1968 static void add_exclude_route(private_kernel_pfkey_ipsec_t *this,
1969 route_entry_t *route, host_t *src, host_t *dst)
1970 {
1971 enumerator_t *enumerator;
1972 exclude_route_t *exclude;
1973 host_t *gtw;
1974
1975 enumerator = this->excludes->create_enumerator(this->excludes);
1976 while (enumerator->enumerate(enumerator, &exclude))
1977 {
1978 if (dst->ip_equals(dst, exclude->dst))
1979 {
1980 route->exclude = exclude;
1981 exclude->refs++;
1982 }
1983 }
1984 enumerator->destroy(enumerator);
1985
1986 if (!route->exclude)
1987 {
1988 DBG2(DBG_KNL, "installing new exclude route for %H src %H", dst, src);
1989 gtw = hydra->kernel_interface->get_nexthop(hydra->kernel_interface,
1990 dst, NULL);
1991 if (gtw)
1992 {
1993 if (hydra->kernel_interface->add_route(hydra->kernel_interface,
1994 dst->get_address(dst),
1995 dst->get_family(dst) == AF_INET ? 32 : 128,
1996 gtw, src, NULL) == SUCCESS)
1997 {
1998 INIT(exclude,
1999 .dst = dst->clone(dst),
2000 .src = src->clone(src),
2001 .gtw = gtw->clone(gtw),
2002 .refs = 1,
2003 );
2004 route->exclude = exclude;
2005 this->excludes->insert_last(this->excludes, exclude);
2006 }
2007 else
2008 {
2009 DBG1(DBG_KNL, "installing exclude route for %H failed", dst);
2010 }
2011 gtw->destroy(gtw);
2012 }
2013 else
2014 {
2015 DBG1(DBG_KNL, "gateway lookup for for %H failed", dst);
2016 }
2017 }
2018 }
2019
2020 /**
2021 * Remove an exclude route attached to a routing entry
2022 */
2023 static void remove_exclude_route(private_kernel_pfkey_ipsec_t *this,
2024 route_entry_t *route)
2025 {
2026 if (route->exclude)
2027 {
2028 enumerator_t *enumerator;
2029 exclude_route_t *exclude;
2030 bool removed = FALSE;
2031 host_t *dst;
2032
2033 enumerator = this->excludes->create_enumerator(this->excludes);
2034 while (enumerator->enumerate(enumerator, &exclude))
2035 {
2036 if (route->exclude == exclude)
2037 {
2038 if (--exclude->refs == 0)
2039 {
2040 this->excludes->remove_at(this->excludes, enumerator);
2041 removed = TRUE;
2042 break;
2043 }
2044 }
2045 }
2046 enumerator->destroy(enumerator);
2047
2048 if (removed)
2049 {
2050 dst = route->exclude->dst;
2051 DBG2(DBG_KNL, "uninstalling exclude route for %H src %H",
2052 dst, route->exclude->src);
2053 if (hydra->kernel_interface->del_route(hydra->kernel_interface,
2054 dst->get_address(dst),
2055 dst->get_family(dst) == AF_INET ? 32 : 128,
2056 route->exclude->gtw, route->exclude->src,
2057 NULL) != SUCCESS)
2058 {
2059 DBG1(DBG_KNL, "uninstalling exclude route for %H failed", dst);
2060 }
2061 exclude_route_destroy(route->exclude);
2062 }
2063 route->exclude = NULL;
2064 }
2065 }
2066
2067 /**
2068 * Try to install a route to the given inbound policy
2069 */
2070 static bool install_route(private_kernel_pfkey_ipsec_t *this,
2071 policy_entry_t *policy, policy_sa_in_t *in)
2072 {
2073 route_entry_t *route, *old;
2074 host_t *host, *src, *dst;
2075 bool is_virtual;
2076
2077 if (hydra->kernel_interface->get_address_by_ts(hydra->kernel_interface,
2078 in->dst_ts, &host, &is_virtual) != SUCCESS)
2079 {
2080 return FALSE;
2081 }
2082
2083 /* switch src/dst, as we handle an IN policy */
2084 src = in->generic.sa->dst;
2085 dst = in->generic.sa->src;
2086
2087 INIT(route,
2088 .prefixlen = policy->src.mask,
2089 .src_ip = host,
2090 .gateway = hydra->kernel_interface->get_nexthop(
2091 hydra->kernel_interface, dst, src),
2092 .dst_net = chunk_clone(policy->src.net->get_address(policy->src.net)),
2093 );
2094
2095 /* if the IP is virtual, we install the route over the interface it has
2096 * been installed on. Otherwise we use the interface we use for IKE, as
2097 * this is required for example on Linux. */
2098 if (is_virtual)
2099 {
2100 src = route->src_ip;
2101 }
2102
2103 /* get interface for route, using source address */
2104 if (!hydra->kernel_interface->get_interface(hydra->kernel_interface,
2105 src, &route->if_name))
2106 {
2107 route_entry_destroy(route);
2108 return FALSE;
2109 }
2110
2111 if (policy->route)
2112 {
2113 old = policy->route;
2114
2115 if (route_entry_equals(old, route))
2116 { /* such a route already exists */
2117 route_entry_destroy(route);
2118 return TRUE;
2119 }
2120 /* uninstall previously installed route */
2121 if (hydra->kernel_interface->del_route(hydra->kernel_interface,
2122 old->dst_net, old->prefixlen, old->gateway,
2123 old->src_ip, old->if_name) != SUCCESS)
2124 {
2125 DBG1(DBG_KNL, "error uninstalling route installed with policy "
2126 "%R === %R %N", in->src_ts, in->dst_ts,
2127 policy_dir_names, policy->direction);
2128 }
2129 route_entry_destroy(old);
2130 policy->route = NULL;
2131 }
2132
2133 /* if remote traffic selector covers the IKE peer, add an exclude route */
2134 if (hydra->kernel_interface->get_features(
2135 hydra->kernel_interface) & KERNEL_REQUIRE_EXCLUDE_ROUTE)
2136 {
2137 if (in->src_ts->includes(in->src_ts, dst))
2138 {
2139 add_exclude_route(this, route, in->generic.sa->dst, dst);
2140 }
2141 }
2142
2143 DBG2(DBG_KNL, "installing route: %R via %H src %H dev %s",
2144 in->src_ts, route->gateway, route->src_ip, route->if_name);
2145
2146 switch (hydra->kernel_interface->add_route(hydra->kernel_interface,
2147 route->dst_net, route->prefixlen, route->gateway,
2148 route->src_ip, route->if_name))
2149 {
2150 case ALREADY_DONE:
2151 /* route exists, do not uninstall */
2152 remove_exclude_route(this, route);
2153 route_entry_destroy(route);
2154 return TRUE;
2155 case SUCCESS:
2156 /* cache the installed route */
2157 policy->route = route;
2158 return TRUE;
2159 default:
2160 DBG1(DBG_KNL, "installing route failed: %R via %H src %H dev %s",
2161 in->src_ts, route->gateway, route->src_ip, route->if_name);
2162 remove_exclude_route(this, route);
2163 route_entry_destroy(route);
2164 return FALSE;
2165 }
2166 }
2167
2168 /**
2169 * Add or update a policy in the kernel.
2170 *
2171 * Note: The mutex has to be locked when entering this function.
2172 */
2173 static status_t add_policy_internal(private_kernel_pfkey_ipsec_t *this,
2174 policy_entry_t *policy, policy_sa_t *mapping, bool update)
2175 {
2176 unsigned char request[PFKEY_BUFFER_SIZE];
2177 struct sadb_msg *msg, *out;
2178 struct sadb_x_policy *pol;
2179 struct sadb_x_ipsecrequest *req;
2180 ipsec_sa_t *ipsec = mapping->sa;
2181 pfkey_msg_t response;
2182 size_t len;
2183
2184 memset(&request, 0, sizeof(request));
2185
2186 msg = (struct sadb_msg*)request;
2187 msg->sadb_msg_version = PF_KEY_V2;
2188 msg->sadb_msg_type = update ? SADB_X_SPDUPDATE : SADB_X_SPDADD;
2189 msg->sadb_msg_satype = 0;
2190 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2191
2192 pol = (struct sadb_x_policy*)PFKEY_EXT_ADD_NEXT(msg);
2193 pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2194 pol->sadb_x_policy_len = PFKEY_LEN(sizeof(struct sadb_x_policy));
2195 pol->sadb_x_policy_id = 0;
2196 pol->sadb_x_policy_dir = dir2kernel(policy->direction);
2197 pol->sadb_x_policy_type = type2kernel(mapping->type);
2198 #ifdef HAVE_STRUCT_SADB_X_POLICY_SADB_X_POLICY_PRIORITY
2199 pol->sadb_x_policy_priority = mapping->priority;
2200 #endif
2201
2202 /* one or more sadb_x_ipsecrequest extensions are added to the
2203 * sadb_x_policy extension */
2204 req = (struct sadb_x_ipsecrequest*)(pol + 1);
2205 req->sadb_x_ipsecrequest_proto = ipsec->cfg.esp.use ? IPPROTO_ESP
2206 : IPPROTO_AH;
2207 /* !!! the length here MUST be in octets instead of 64 bit words */
2208 req->sadb_x_ipsecrequest_len = sizeof(struct sadb_x_ipsecrequest);
2209 req->sadb_x_ipsecrequest_mode = mode2kernel(ipsec->cfg.mode);
2210 req->sadb_x_ipsecrequest_reqid = ipsec->cfg.reqid;
2211 req->sadb_x_ipsecrequest_level = IPSEC_LEVEL_UNIQUE;
2212 if (ipsec->cfg.mode == MODE_TUNNEL)
2213 {
2214 len = hostcpy(req + 1, ipsec->src, FALSE);
2215 req->sadb_x_ipsecrequest_len += len;
2216 len = hostcpy((char*)(req + 1) + len, ipsec->dst, FALSE);
2217 req->sadb_x_ipsecrequest_len += len;
2218 }
2219
2220 pol->sadb_x_policy_len += PFKEY_LEN(req->sadb_x_ipsecrequest_len);
2221 PFKEY_EXT_ADD(msg, pol);
2222
2223 add_addr_ext(msg, policy->src.net, SADB_EXT_ADDRESS_SRC, policy->src.proto,
2224 policy->src.mask, TRUE);
2225 add_addr_ext(msg, policy->dst.net, SADB_EXT_ADDRESS_DST, policy->dst.proto,
2226 policy->dst.mask, TRUE);
2227
2228 #ifdef __FreeBSD__
2229 { /* on FreeBSD a lifetime has to be defined to be able to later query
2230 * the current use time. */
2231 struct sadb_lifetime *lft;
2232 lft = (struct sadb_lifetime*)PFKEY_EXT_ADD_NEXT(msg);
2233 lft->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2234 lft->sadb_lifetime_len = PFKEY_LEN(sizeof(struct sadb_lifetime));
2235 lft->sadb_lifetime_addtime = LONG_MAX;
2236 PFKEY_EXT_ADD(msg, lft);
2237 }
2238 #endif
2239
2240 this->mutex->unlock(this->mutex);
2241
2242 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2243 {
2244 return FAILED;
2245 }
2246 else if (out->sadb_msg_errno)
2247 {
2248 DBG1(DBG_KNL, "unable to %s policy: %s (%d)",
2249 update ? "update" : "add", strerror(out->sadb_msg_errno),
2250 out->sadb_msg_errno);
2251 free(out);
2252 return FAILED;
2253 }
2254 else if (parse_pfkey_message(out, &response) != SUCCESS)
2255 {
2256 DBG1(DBG_KNL, "unable to %s policy: parsing response from kernel "
2257 "failed", update ? "update" : "add");
2258 free(out);
2259 return FAILED;
2260 }
2261
2262 /* we try to find the policy again and update the kernel index */
2263 this->mutex->lock(this->mutex);
2264 if (this->policies->find_first(this->policies, NULL,
2265 (void**)&policy) != SUCCESS)
2266 {
2267 DBG2(DBG_KNL, "unable to update index, the policy is already gone, "
2268 "ignoring");
2269 this->mutex->unlock(this->mutex);
2270 free(out);
2271 return SUCCESS;
2272 }
2273 policy->index = response.x_policy->sadb_x_policy_id;
2274 free(out);
2275
2276 /* install a route, if:
2277 * - this is a forward policy (to just get one for each child)
2278 * - we are in tunnel mode
2279 * - routing is not disabled via strongswan.conf
2280 */
2281 if (policy->direction == POLICY_IN &&
2282 ipsec->cfg.mode != MODE_TRANSPORT && this->install_routes)
2283 {
2284 install_route(this, policy, (policy_sa_in_t*)mapping);
2285 }
2286 this->mutex->unlock(this->mutex);
2287 return SUCCESS;
2288 }
2289
2290 METHOD(kernel_ipsec_t, add_policy, status_t,
2291 private_kernel_pfkey_ipsec_t *this, host_t *src, host_t *dst,
2292 traffic_selector_t *src_ts, traffic_selector_t *dst_ts,
2293 policy_dir_t direction, policy_type_t type, ipsec_sa_cfg_t *sa,
2294 mark_t mark, policy_priority_t priority)
2295 {
2296 policy_entry_t *policy, *found = NULL;
2297 policy_sa_t *assigned_sa, *current_sa;
2298 enumerator_t *enumerator;
2299 bool update = TRUE;
2300
2301 if (dir2kernel(direction) == IPSEC_DIR_INVALID)
2302 { /* FWD policies are not supported on all platforms */
2303 return SUCCESS;
2304 }
2305
2306 /* create a policy */
2307 policy = create_policy_entry(src_ts, dst_ts, direction);
2308
2309 /* find a matching policy */
2310 this->mutex->lock(this->mutex);
2311 if (this->policies->find_first(this->policies,
2312 (linked_list_match_t)policy_entry_equals,
2313 (void**)&found, policy) == SUCCESS)
2314 { /* use existing policy */
2315 DBG2(DBG_KNL, "policy %R === %R %N already exists, increasing "
2316 "refcount", src_ts, dst_ts, policy_dir_names, direction);
2317 policy_entry_destroy(policy, this);
2318 policy = found;
2319 }
2320 else
2321 { /* use the new one, if we have no such policy */
2322 this->policies->insert_first(this->policies, policy);
2323 policy->used_by = linked_list_create();
2324 }
2325
2326 /* cache the assigned IPsec SA */
2327 assigned_sa = policy_sa_create(this, direction, type, src, dst, src_ts,
2328 dst_ts, sa);
2329 assigned_sa->priority = get_priority(policy, priority);
2330
2331 /* insert the SA according to its priority */
2332 enumerator = policy->used_by->create_enumerator(policy->used_by);
2333 while (enumerator->enumerate(enumerator, (void**)&current_sa))
2334 {
2335 if (current_sa->priority >= assigned_sa->priority)
2336 {
2337 break;
2338 }
2339 update = FALSE;
2340 }
2341 policy->used_by->insert_before(policy->used_by, enumerator, assigned_sa);
2342 enumerator->destroy(enumerator);
2343
2344 if (!update)
2345 { /* we don't update the policy if the priority is lower than that of the
2346 * currently installed one */
2347 this->mutex->unlock(this->mutex);
2348 return SUCCESS;
2349 }
2350
2351 DBG2(DBG_KNL, "%s policy %R === %R %N",
2352 found ? "updating" : "adding", src_ts, dst_ts,
2353 policy_dir_names, direction);
2354
2355 if (add_policy_internal(this, policy, assigned_sa, found) != SUCCESS)
2356 {
2357 DBG1(DBG_KNL, "unable to %s policy %R === %R %N",
2358 found ? "update" : "add", src_ts, dst_ts,
2359 policy_dir_names, direction);
2360 return FAILED;
2361 }
2362 return SUCCESS;
2363 }
2364
2365 METHOD(kernel_ipsec_t, query_policy, status_t,
2366 private_kernel_pfkey_ipsec_t *this, traffic_selector_t *src_ts,
2367 traffic_selector_t *dst_ts, policy_dir_t direction, mark_t mark,
2368 u_int32_t *use_time)
2369 {
2370 unsigned char request[PFKEY_BUFFER_SIZE];
2371 struct sadb_msg *msg, *out;
2372 struct sadb_x_policy *pol;
2373 policy_entry_t *policy, *found = NULL;
2374 pfkey_msg_t response;
2375 size_t len;
2376
2377 if (dir2kernel(direction) == IPSEC_DIR_INVALID)
2378 { /* FWD policies are not supported on all platforms */
2379 return NOT_FOUND;
2380 }
2381
2382 DBG2(DBG_KNL, "querying policy %R === %R %N", src_ts, dst_ts,
2383 policy_dir_names, direction);
2384
2385 /* create a policy */
2386 policy = create_policy_entry(src_ts, dst_ts, direction);
2387
2388 /* find a matching policy */
2389 this->mutex->lock(this->mutex);
2390 if (this->policies->find_first(this->policies,
2391 (linked_list_match_t)policy_entry_equals,
2392 (void**)&found, policy) != SUCCESS)
2393 {
2394 DBG1(DBG_KNL, "querying policy %R === %R %N failed, not found", src_ts,
2395 dst_ts, policy_dir_names, direction);
2396 policy_entry_destroy(policy, this);
2397 this->mutex->unlock(this->mutex);
2398 return NOT_FOUND;
2399 }
2400 policy_entry_destroy(policy, this);
2401 policy = found;
2402
2403 memset(&request, 0, sizeof(request));
2404
2405 msg = (struct sadb_msg*)request;
2406 msg->sadb_msg_version = PF_KEY_V2;
2407 msg->sadb_msg_type = SADB_X_SPDGET;
2408 msg->sadb_msg_satype = 0;
2409 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2410
2411 pol = (struct sadb_x_policy*)PFKEY_EXT_ADD_NEXT(msg);
2412 pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2413 pol->sadb_x_policy_id = policy->index;
2414 pol->sadb_x_policy_len = PFKEY_LEN(sizeof(struct sadb_x_policy));
2415 pol->sadb_x_policy_dir = dir2kernel(direction);
2416 pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC;
2417 PFKEY_EXT_ADD(msg, pol);
2418
2419 add_addr_ext(msg, policy->src.net, SADB_EXT_ADDRESS_SRC, policy->src.proto,
2420 policy->src.mask, TRUE);
2421 add_addr_ext(msg, policy->dst.net, SADB_EXT_ADDRESS_DST, policy->dst.proto,
2422 policy->dst.mask, TRUE);
2423
2424 this->mutex->unlock(this->mutex);
2425
2426 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2427 {
2428 DBG1(DBG_KNL, "unable to query policy %R === %R %N", src_ts, dst_ts,
2429 policy_dir_names, direction);
2430 return FAILED;
2431 }
2432 else if (out->sadb_msg_errno)
2433 {
2434 DBG1(DBG_KNL, "unable to query policy %R === %R %N: %s (%d)", src_ts,
2435 dst_ts, policy_dir_names, direction,
2436 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2437 free(out);
2438 return FAILED;
2439 }
2440 else if (parse_pfkey_message(out, &response) != SUCCESS)
2441 {
2442 DBG1(DBG_KNL, "unable to query policy %R === %R %N: parsing response "
2443 "from kernel failed", src_ts, dst_ts, policy_dir_names,
2444 direction);
2445 free(out);
2446 return FAILED;
2447 }
2448 else if (response.lft_current == NULL)
2449 {
2450 DBG2(DBG_KNL, "unable to query policy %R === %R %N: kernel reports no "
2451 "use time", src_ts, dst_ts, policy_dir_names, direction);
2452 free(out);
2453 return FAILED;
2454 }
2455
2456 /* we need the monotonic time, but the kernel returns system time. */
2457 if (response.lft_current->sadb_lifetime_usetime)
2458 {
2459 *use_time = time_monotonic(NULL) -
2460 (time(NULL) - response.lft_current->sadb_lifetime_usetime);
2461 }
2462 else
2463 {
2464 *use_time = 0;
2465 }
2466 free(out);
2467 return SUCCESS;
2468 }
2469
2470 METHOD(kernel_ipsec_t, del_policy, status_t,
2471 private_kernel_pfkey_ipsec_t *this, traffic_selector_t *src_ts,
2472 traffic_selector_t *dst_ts, policy_dir_t direction, u_int32_t reqid,
2473 mark_t mark, policy_priority_t prio)
2474 {
2475 unsigned char request[PFKEY_BUFFER_SIZE];
2476 struct sadb_msg *msg, *out;
2477 struct sadb_x_policy *pol;
2478 policy_entry_t *policy, *found = NULL;
2479 policy_sa_t *mapping;
2480 enumerator_t *enumerator;
2481 bool is_installed = TRUE;
2482 u_int32_t priority;
2483 size_t len;
2484
2485 if (dir2kernel(direction) == IPSEC_DIR_INVALID)
2486 { /* FWD policies are not supported on all platforms */
2487 return SUCCESS;
2488 }
2489
2490 DBG2(DBG_KNL, "deleting policy %R === %R %N", src_ts, dst_ts,
2491 policy_dir_names, direction);
2492
2493 /* create a policy */
2494 policy = create_policy_entry(src_ts, dst_ts, direction);
2495
2496 /* find a matching policy */
2497 this->mutex->lock(this->mutex);
2498 if (this->policies->find_first(this->policies,
2499 (linked_list_match_t)policy_entry_equals,
2500 (void**)&found, policy) != SUCCESS)
2501 {
2502 DBG1(DBG_KNL, "deleting policy %R === %R %N failed, not found", src_ts,
2503 dst_ts, policy_dir_names, direction);
2504 policy_entry_destroy(policy, this);
2505 this->mutex->unlock(this->mutex);
2506 return NOT_FOUND;
2507 }
2508 policy_entry_destroy(policy, this);
2509 policy = found;
2510
2511 /* remove mapping to SA by reqid and priority */
2512 priority = get_priority(policy, prio);
2513 enumerator = policy->used_by->create_enumerator(policy->used_by);
2514 while (enumerator->enumerate(enumerator, (void**)&mapping))
2515 {
2516 if (reqid == mapping->sa->cfg.reqid && priority == mapping->priority)
2517 {
2518 policy->used_by->remove_at(policy->used_by, enumerator);
2519 break;
2520 }
2521 is_installed = FALSE;
2522 }
2523 enumerator->destroy(enumerator);
2524
2525 if (policy->used_by->get_count(policy->used_by) > 0)
2526 { /* policy is used by more SAs, keep in kernel */
2527 DBG2(DBG_KNL, "policy still used by another CHILD_SA, not removed");
2528 policy_sa_destroy(mapping, &direction, this);
2529
2530 if (!is_installed)
2531 { /* no need to update as the policy was not installed for this SA */
2532 this->mutex->unlock(this->mutex);
2533 return SUCCESS;
2534 }
2535
2536 DBG2(DBG_KNL, "updating policy %R === %R %N", src_ts, dst_ts,
2537 policy_dir_names, direction);
2538 policy->used_by->get_first(policy->used_by, (void**)&mapping);
2539 if (add_policy_internal(this, policy, mapping, TRUE) != SUCCESS)
2540 {
2541 DBG1(DBG_KNL, "unable to update policy %R === %R %N",
2542 src_ts, dst_ts, policy_dir_names, direction);
2543 return FAILED;
2544 }
2545 return SUCCESS;
2546 }
2547
2548 memset(&request, 0, sizeof(request));
2549
2550 msg = (struct sadb_msg*)request;
2551 msg->sadb_msg_version = PF_KEY_V2;
2552 msg->sadb_msg_type = SADB_X_SPDDELETE;
2553 msg->sadb_msg_satype = 0;
2554 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2555
2556 pol = (struct sadb_x_policy*)PFKEY_EXT_ADD_NEXT(msg);
2557 pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2558 pol->sadb_x_policy_len = PFKEY_LEN(sizeof(struct sadb_x_policy));
2559 pol->sadb_x_policy_dir = dir2kernel(direction);
2560 pol->sadb_x_policy_type = type2kernel(mapping->type);
2561 PFKEY_EXT_ADD(msg, pol);
2562
2563 add_addr_ext(msg, policy->src.net, SADB_EXT_ADDRESS_SRC, policy->src.proto,
2564 policy->src.mask, TRUE);
2565 add_addr_ext(msg, policy->dst.net, SADB_EXT_ADDRESS_DST, policy->dst.proto,
2566 policy->dst.mask, TRUE);
2567
2568 if (policy->route)
2569 {
2570 route_entry_t *route = policy->route;
2571 if (hydra->kernel_interface->del_route(hydra->kernel_interface,
2572 route->dst_net, route->prefixlen, route->gateway,
2573 route->src_ip, route->if_name) != SUCCESS)
2574 {
2575 DBG1(DBG_KNL, "error uninstalling route installed with "
2576 "policy %R === %R %N", src_ts, dst_ts,
2577 policy_dir_names, direction);
2578 }
2579 remove_exclude_route(this, route);
2580 }
2581
2582 this->policies->remove(this->policies, found, NULL);
2583 policy_sa_destroy(mapping, &direction, this);
2584 policy_entry_destroy(policy, this);
2585 this->mutex->unlock(this->mutex);
2586
2587 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2588 {
2589 DBG1(DBG_KNL, "unable to delete policy %R === %R %N", src_ts, dst_ts,
2590 policy_dir_names, direction);
2591 return FAILED;
2592 }
2593 else if (out->sadb_msg_errno)
2594 {
2595 DBG1(DBG_KNL, "unable to delete policy %R === %R %N: %s (%d)", src_ts,
2596 dst_ts, policy_dir_names, direction,
2597 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2598 free(out);
2599 return FAILED;
2600 }
2601 free(out);
2602 return SUCCESS;
2603 }
2604
2605 METHOD(kernel_ipsec_t, flush_policies, status_t,
2606 private_kernel_pfkey_ipsec_t *this)
2607 {
2608 unsigned char request[PFKEY_BUFFER_SIZE];
2609 struct sadb_msg *msg, *out;
2610 size_t len;
2611
2612 memset(&request, 0, sizeof(request));
2613
2614 DBG2(DBG_KNL, "flushing all policies from SPD");
2615
2616 msg = (struct sadb_msg*)request;
2617 msg->sadb_msg_version = PF_KEY_V2;
2618 msg->sadb_msg_type = SADB_X_SPDFLUSH;
2619 msg->sadb_msg_satype = SADB_SATYPE_UNSPEC;
2620 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2621
2622 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2623 {
2624 DBG1(DBG_KNL, "unable to flush SPD entries");
2625 return FAILED;
2626 }
2627 else if (out->sadb_msg_errno)
2628 {
2629 DBG1(DBG_KNL, "unable to flush SPD entries: %s (%d)",
2630 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2631 free(out);
2632 return FAILED;
2633 }
2634 free(out);
2635 return SUCCESS;
2636 }
2637
2638 /**
2639 * Register a socket for ACQUIRE/EXPIRE messages
2640 */
2641 static status_t register_pfkey_socket(private_kernel_pfkey_ipsec_t *this,
2642 u_int8_t satype)
2643 {
2644 unsigned char request[PFKEY_BUFFER_SIZE];
2645 struct sadb_msg *msg, *out;
2646 size_t len;
2647
2648 memset(&request, 0, sizeof(request));
2649
2650 msg = (struct sadb_msg*)request;
2651 msg->sadb_msg_version = PF_KEY_V2;
2652 msg->sadb_msg_type = SADB_REGISTER;
2653 msg->sadb_msg_satype = satype;
2654 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2655
2656 if (pfkey_send_socket(this, this->socket_events, msg, &out, &len) != SUCCESS)
2657 {
2658 DBG1(DBG_KNL, "unable to register PF_KEY socket");
2659 return FAILED;
2660 }
2661 else if (out->sadb_msg_errno)
2662 {
2663 DBG1(DBG_KNL, "unable to register PF_KEY socket: %s (%d)",
2664 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2665 free(out);
2666 return FAILED;
2667 }
2668 free(out);
2669 return SUCCESS;
2670 }
2671
2672 METHOD(kernel_ipsec_t, bypass_socket, bool,
2673 private_kernel_pfkey_ipsec_t *this, int fd, int family)
2674 {
2675 struct sadb_x_policy policy;
2676 u_int sol, ipsec_policy;
2677
2678 switch (family)
2679 {
2680 case AF_INET:
2681 {
2682 sol = SOL_IP;
2683 ipsec_policy = IP_IPSEC_POLICY;
2684 break;
2685 }
2686 case AF_INET6:
2687 {
2688 sol = SOL_IPV6;
2689 ipsec_policy = IPV6_IPSEC_POLICY;
2690 break;
2691 }
2692 default:
2693 return FALSE;
2694 }
2695
2696 memset(&policy, 0, sizeof(policy));
2697 policy.sadb_x_policy_len = sizeof(policy) / sizeof(u_int64_t);
2698 policy.sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2699 policy.sadb_x_policy_type = IPSEC_POLICY_BYPASS;
2700
2701 policy.sadb_x_policy_dir = IPSEC_DIR_OUTBOUND;
2702 if (setsockopt(fd, sol, ipsec_policy, &policy, sizeof(policy)) < 0)
2703 {
2704 DBG1(DBG_KNL, "unable to set IPSEC_POLICY on socket: %s",
2705 strerror(errno));
2706 return FALSE;
2707 }
2708 policy.sadb_x_policy_dir = IPSEC_DIR_INBOUND;
2709 if (setsockopt(fd, sol, ipsec_policy, &policy, sizeof(policy)) < 0)
2710 {
2711 DBG1(DBG_KNL, "unable to set IPSEC_POLICY on socket: %s",
2712 strerror(errno));
2713 return FALSE;
2714 }
2715 return TRUE;
2716 }
2717
2718 METHOD(kernel_ipsec_t, enable_udp_decap, bool,
2719 private_kernel_pfkey_ipsec_t *this, int fd, int family, u_int16_t port)
2720 {
2721 #ifndef __APPLE__
2722 int type = UDP_ENCAP_ESPINUDP;
2723
2724 if (setsockopt(fd, SOL_UDP, UDP_ENCAP, &type, sizeof(type)) < 0)
2725 {
2726 DBG1(DBG_KNL, "unable to set UDP_ENCAP: %s", strerror(errno));
2727 return FALSE;
2728 }
2729 #else /* __APPLE__ */
2730 int intport = port;
2731
2732 if (sysctlbyname("net.inet.ipsec.esp_port", NULL, NULL, &intport,
2733 sizeof(intport)) != 0)
2734 {
2735 DBG1(DBG_KNL, "could not set net.inet.ipsec.esp_port to %d: %s",
2736 port, strerror(errno));
2737 return FALSE;
2738 }
2739 #endif /* __APPLE__ */
2740
2741 return TRUE;
2742 }
2743
2744 METHOD(kernel_ipsec_t, destroy, void,
2745 private_kernel_pfkey_ipsec_t *this)
2746 {
2747 if (this->socket > 0)
2748 {
2749 close(this->socket);
2750 }
2751 if (this->socket_events > 0)
2752 {
2753 close(this->socket_events);
2754 }
2755 this->policies->invoke_function(this->policies,
2756 (linked_list_invoke_t)policy_entry_destroy,
2757 this);
2758 this->policies->destroy(this->policies);
2759 this->excludes->destroy(this->excludes);
2760 this->sas->destroy(this->sas);
2761 this->mutex->destroy(this->mutex);
2762 this->mutex_pfkey->destroy(this->mutex_pfkey);
2763 free(this);
2764 }
2765
2766 /*
2767 * Described in header.
2768 */
2769 kernel_pfkey_ipsec_t *kernel_pfkey_ipsec_create()
2770 {
2771 private_kernel_pfkey_ipsec_t *this;
2772 bool register_for_events = TRUE;
2773
2774 INIT(this,
2775 .public = {
2776 .interface = {
2777 .get_spi = _get_spi,
2778 .get_cpi = _get_cpi,
2779 .add_sa = _add_sa,
2780 .update_sa = _update_sa,
2781 .query_sa = _query_sa,
2782 .del_sa = _del_sa,
2783 .flush_sas = _flush_sas,
2784 .add_policy = _add_policy,
2785 .query_policy = _query_policy,
2786 .del_policy = _del_policy,
2787 .flush_policies = _flush_policies,
2788 .bypass_socket = _bypass_socket,
2789 .enable_udp_decap = _enable_udp_decap,
2790 .destroy = _destroy,
2791 },
2792 },
2793 .policies = linked_list_create(),
2794 .excludes = linked_list_create(),
2795 .sas = hashtable_create((hashtable_hash_t)ipsec_sa_hash,
2796 (hashtable_equals_t)ipsec_sa_equals, 32),
2797 .mutex = mutex_create(MUTEX_TYPE_DEFAULT),
2798 .mutex_pfkey = mutex_create(MUTEX_TYPE_DEFAULT),
2799 .install_routes = lib->settings->get_bool(lib->settings,
2800 "%s.install_routes", TRUE,
2801 hydra->daemon),
2802 );
2803
2804 if (streq(hydra->daemon, "starter"))
2805 { /* starter has no threads, so we do not register for kernel events */
2806 register_for_events = FALSE;
2807 }
2808
2809 /* create a PF_KEY socket to communicate with the kernel */
2810 this->socket = socket(PF_KEY, SOCK_RAW, PF_KEY_V2);
2811 if (this->socket <= 0)
2812 {
2813 DBG1(DBG_KNL, "unable to create PF_KEY socket");
2814 destroy(this);
2815 return NULL;
2816 }
2817
2818 if (register_for_events)
2819 {
2820 /* create a PF_KEY socket for ACQUIRE & EXPIRE */
2821 this->socket_events = socket(PF_KEY, SOCK_RAW, PF_KEY_V2);
2822 if (this->socket_events <= 0)
2823 {
2824 DBG1(DBG_KNL, "unable to create PF_KEY event socket");
2825 destroy(this);
2826 return NULL;
2827 }
2828
2829 /* register the event socket */
2830 if (register_pfkey_socket(this, SADB_SATYPE_ESP) != SUCCESS ||
2831 register_pfkey_socket(this, SADB_SATYPE_AH) != SUCCESS)
2832 {
2833 DBG1(DBG_KNL, "unable to register PF_KEY event socket");
2834 destroy(this);
2835 return NULL;
2836 }
2837
2838 lib->processor->queue_job(lib->processor,
2839 (job_t*)callback_job_create_with_prio(
2840 (callback_job_cb_t)receive_events, this, NULL,
2841 (callback_job_cancel_t)return_false, JOB_PRIO_CRITICAL));
2842 }
2843
2844 return &this->public;
2845 }