kernel-pfkey: Provide interface name when installing exclude route
[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 u_int8_t proto;
985
986 proto = address->sadb_address_proto;
987 proto = proto == IPSEC_PROTO_ANY ? 0 : proto;
988
989 /* The Linux 2.6 kernel does not set the protocol and port information
990 * in the src and dst sadb_address extensions of the SADB_ACQUIRE message.
991 */
992 host = host_create_from_sockaddr((sockaddr_t*)&address[1]);
993 ts = traffic_selector_create_from_subnet(host,
994 address->sadb_address_prefixlen,
995 proto, host->get_port(host),
996 host->get_port(host) ?: 65535);
997 return ts;
998 }
999
1000 /**
1001 * Parses a pfkey message received from the kernel
1002 */
1003 static status_t parse_pfkey_message(struct sadb_msg *msg, pfkey_msg_t *out)
1004 {
1005 struct sadb_ext* ext;
1006 size_t len;
1007
1008 memset(out, 0, sizeof(pfkey_msg_t));
1009 out->msg = msg;
1010
1011 len = msg->sadb_msg_len;
1012 len -= PFKEY_LEN(sizeof(struct sadb_msg));
1013
1014 ext = (struct sadb_ext*)(((char*)msg) + sizeof(struct sadb_msg));
1015
1016 while (len >= PFKEY_LEN(sizeof(struct sadb_ext)))
1017 {
1018 DBG3(DBG_KNL, " %N", sadb_ext_type_names, ext->sadb_ext_type);
1019 if (ext->sadb_ext_len < PFKEY_LEN(sizeof(struct sadb_ext)) ||
1020 ext->sadb_ext_len > len)
1021 {
1022 DBG1(DBG_KNL, "length of %N extension is invalid",
1023 sadb_ext_type_names, ext->sadb_ext_type);
1024 break;
1025 }
1026
1027 if ((ext->sadb_ext_type > SADB_EXT_MAX) || (!ext->sadb_ext_type))
1028 {
1029 DBG1(DBG_KNL, "type of PF_KEY extension (%d) is invalid",
1030 ext->sadb_ext_type);
1031 break;
1032 }
1033
1034 if (out->ext[ext->sadb_ext_type])
1035 {
1036 DBG1(DBG_KNL, "duplicate %N extension",
1037 sadb_ext_type_names, ext->sadb_ext_type);
1038 break;
1039 }
1040
1041 out->ext[ext->sadb_ext_type] = ext;
1042 ext = PFKEY_EXT_NEXT_LEN(ext, len);
1043 }
1044
1045 if (len)
1046 {
1047 DBG1(DBG_KNL, "PF_KEY message length is invalid");
1048 return FAILED;
1049 }
1050
1051 return SUCCESS;
1052 }
1053
1054 /**
1055 * Send a message to a specific PF_KEY socket and handle the response.
1056 */
1057 static status_t pfkey_send_socket(private_kernel_pfkey_ipsec_t *this, int socket,
1058 struct sadb_msg *in, struct sadb_msg **out, size_t *out_len)
1059 {
1060 unsigned char buf[PFKEY_BUFFER_SIZE];
1061 struct sadb_msg *msg;
1062 int in_len, len;
1063
1064 this->mutex_pfkey->lock(this->mutex_pfkey);
1065
1066 /* FIXME: our usage of sequence numbers is probably wrong. check RFC 2367,
1067 * in particular the behavior in response to an SADB_ACQUIRE. */
1068 in->sadb_msg_seq = ++this->seq;
1069 in->sadb_msg_pid = getpid();
1070
1071 in_len = PFKEY_USER_LEN(in->sadb_msg_len);
1072
1073 while (TRUE)
1074 {
1075 len = send(socket, in, in_len, 0);
1076
1077 if (len != in_len)
1078 {
1079 if (errno == EINTR)
1080 {
1081 /* interrupted, try again */
1082 continue;
1083 }
1084 this->mutex_pfkey->unlock(this->mutex_pfkey);
1085 DBG1(DBG_KNL, "error sending to PF_KEY socket: %s",
1086 strerror(errno));
1087 return FAILED;
1088 }
1089 break;
1090 }
1091
1092 while (TRUE)
1093 {
1094 msg = (struct sadb_msg*)buf;
1095
1096 len = recv(socket, buf, sizeof(buf), 0);
1097
1098 if (len < 0)
1099 {
1100 if (errno == EINTR)
1101 {
1102 DBG1(DBG_KNL, "got interrupted");
1103 /* interrupted, try again */
1104 continue;
1105 }
1106 DBG1(DBG_KNL, "error reading from PF_KEY socket: %s",
1107 strerror(errno));
1108 this->mutex_pfkey->unlock(this->mutex_pfkey);
1109 return FAILED;
1110 }
1111 if (len < sizeof(struct sadb_msg) ||
1112 msg->sadb_msg_len < PFKEY_LEN(sizeof(struct sadb_msg)))
1113 {
1114 DBG1(DBG_KNL, "received corrupted PF_KEY message");
1115 this->mutex_pfkey->unlock(this->mutex_pfkey);
1116 return FAILED;
1117 }
1118 if (msg->sadb_msg_len > len / PFKEY_ALIGNMENT)
1119 {
1120 DBG1(DBG_KNL, "buffer was too small to receive the complete PF_KEY "
1121 "message");
1122 this->mutex_pfkey->unlock(this->mutex_pfkey);
1123 return FAILED;
1124 }
1125 if (msg->sadb_msg_pid != in->sadb_msg_pid)
1126 {
1127 DBG2(DBG_KNL, "received PF_KEY message is not intended for us");
1128 continue;
1129 }
1130 if (msg->sadb_msg_seq != this->seq)
1131 {
1132 DBG2(DBG_KNL, "received PF_KEY message with unexpected sequence "
1133 "number, was %d expected %d", msg->sadb_msg_seq,
1134 this->seq);
1135 if (msg->sadb_msg_seq == 0)
1136 {
1137 /* FreeBSD and Mac OS X do this for the response to
1138 * SADB_X_SPDGET (but not for the response to SADB_GET).
1139 * FreeBSD: 'key_spdget' in /usr/src/sys/netipsec/key.c. */
1140 }
1141 else if (msg->sadb_msg_seq < this->seq)
1142 {
1143 continue;
1144 }
1145 else
1146 {
1147 this->mutex_pfkey->unlock(this->mutex_pfkey);
1148 return FAILED;
1149 }
1150 }
1151 if (msg->sadb_msg_type != in->sadb_msg_type)
1152 {
1153 DBG2(DBG_KNL, "received PF_KEY message of wrong type, "
1154 "was %d expected %d, ignoring", msg->sadb_msg_type,
1155 in->sadb_msg_type);
1156 }
1157 break;
1158 }
1159
1160 *out_len = len;
1161 *out = (struct sadb_msg*)malloc(len);
1162 memcpy(*out, buf, len);
1163
1164 this->mutex_pfkey->unlock(this->mutex_pfkey);
1165 return SUCCESS;
1166 }
1167
1168 /**
1169 * Send a message to the default PF_KEY socket and handle the response.
1170 */
1171 static status_t pfkey_send(private_kernel_pfkey_ipsec_t *this,
1172 struct sadb_msg *in, struct sadb_msg **out,
1173 size_t *out_len)
1174 {
1175 return pfkey_send_socket(this, this->socket, in, out, out_len);
1176 }
1177
1178 /**
1179 * Process a SADB_ACQUIRE message from the kernel
1180 */
1181 static void process_acquire(private_kernel_pfkey_ipsec_t *this,
1182 struct sadb_msg* msg)
1183 {
1184 pfkey_msg_t response;
1185 u_int32_t index, reqid = 0;
1186 traffic_selector_t *src_ts, *dst_ts;
1187 policy_entry_t *policy;
1188 policy_sa_t *sa;
1189
1190 switch (msg->sadb_msg_satype)
1191 {
1192 case SADB_SATYPE_UNSPEC:
1193 case SADB_SATYPE_ESP:
1194 case SADB_SATYPE_AH:
1195 break;
1196 default:
1197 /* acquire for AH/ESP only */
1198 return;
1199 }
1200 DBG2(DBG_KNL, "received an SADB_ACQUIRE");
1201
1202 if (parse_pfkey_message(msg, &response) != SUCCESS)
1203 {
1204 DBG1(DBG_KNL, "parsing SADB_ACQUIRE from kernel failed");
1205 return;
1206 }
1207
1208 index = response.x_policy->sadb_x_policy_id;
1209 this->mutex->lock(this->mutex);
1210 if (this->policies->find_first(this->policies,
1211 (linked_list_match_t)policy_entry_match_byindex,
1212 (void**)&policy, &index) == SUCCESS &&
1213 policy->used_by->get_first(policy->used_by, (void**)&sa) == SUCCESS)
1214 {
1215 reqid = sa->sa->cfg.reqid;
1216 }
1217 else
1218 {
1219 DBG1(DBG_KNL, "received an SADB_ACQUIRE with policy id %d but no "
1220 "matching policy found", index);
1221 }
1222 this->mutex->unlock(this->mutex);
1223
1224 src_ts = sadb_address2ts(response.src);
1225 dst_ts = sadb_address2ts(response.dst);
1226
1227 hydra->kernel_interface->acquire(hydra->kernel_interface, reqid, src_ts,
1228 dst_ts);
1229 }
1230
1231 /**
1232 * Process a SADB_EXPIRE message from the kernel
1233 */
1234 static void process_expire(private_kernel_pfkey_ipsec_t *this,
1235 struct sadb_msg* msg)
1236 {
1237 pfkey_msg_t response;
1238 u_int8_t protocol;
1239 u_int32_t spi, reqid;
1240 bool hard;
1241
1242 DBG2(DBG_KNL, "received an SADB_EXPIRE");
1243
1244 if (parse_pfkey_message(msg, &response) != SUCCESS)
1245 {
1246 DBG1(DBG_KNL, "parsing SADB_EXPIRE from kernel failed");
1247 return;
1248 }
1249
1250 protocol = satype2proto(msg->sadb_msg_satype);
1251 spi = response.sa->sadb_sa_spi;
1252 reqid = response.x_sa2->sadb_x_sa2_reqid;
1253 hard = response.lft_hard != NULL;
1254
1255 if (protocol != IPPROTO_ESP && protocol != IPPROTO_AH)
1256 {
1257 DBG2(DBG_KNL, "ignoring SADB_EXPIRE for SA with SPI %.8x and "
1258 "reqid {%u} which is not a CHILD_SA", ntohl(spi), reqid);
1259 return;
1260 }
1261
1262 hydra->kernel_interface->expire(hydra->kernel_interface, reqid, protocol,
1263 spi, hard);
1264 }
1265
1266 #ifdef SADB_X_MIGRATE
1267 /**
1268 * Process a SADB_X_MIGRATE message from the kernel
1269 */
1270 static void process_migrate(private_kernel_pfkey_ipsec_t *this,
1271 struct sadb_msg* msg)
1272 {
1273 pfkey_msg_t response;
1274 traffic_selector_t *src_ts, *dst_ts;
1275 policy_dir_t dir;
1276 u_int32_t reqid = 0;
1277 host_t *local = NULL, *remote = NULL;
1278
1279 DBG2(DBG_KNL, "received an SADB_X_MIGRATE");
1280
1281 if (parse_pfkey_message(msg, &response) != SUCCESS)
1282 {
1283 DBG1(DBG_KNL, "parsing SADB_X_MIGRATE from kernel failed");
1284 return;
1285 }
1286 src_ts = sadb_address2ts(response.src);
1287 dst_ts = sadb_address2ts(response.dst);
1288 dir = kernel2dir(response.x_policy->sadb_x_policy_dir);
1289 DBG2(DBG_KNL, " policy %R === %R %N, id %u", src_ts, dst_ts,
1290 policy_dir_names, dir);
1291
1292 /* SADB_X_EXT_KMADDRESS is not present in unpatched kernels < 2.6.28 */
1293 if (response.x_kmaddress)
1294 {
1295 sockaddr_t *local_addr, *remote_addr;
1296 u_int32_t local_len;
1297
1298 local_addr = (sockaddr_t*)&response.x_kmaddress[1];
1299 local = host_create_from_sockaddr(local_addr);
1300 local_len = (local_addr->sa_family == AF_INET6)?
1301 sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in);
1302 remote_addr = (sockaddr_t*)((u_int8_t*)local_addr + local_len);
1303 remote = host_create_from_sockaddr(remote_addr);
1304 DBG2(DBG_KNL, " kmaddress: %H...%H", local, remote);
1305 }
1306
1307 if (src_ts && dst_ts && local && remote)
1308 {
1309 hydra->kernel_interface->migrate(hydra->kernel_interface, reqid,
1310 src_ts, dst_ts, dir, local, remote);
1311 }
1312 else
1313 {
1314 DESTROY_IF(src_ts);
1315 DESTROY_IF(dst_ts);
1316 DESTROY_IF(local);
1317 DESTROY_IF(remote);
1318 }
1319 }
1320 #endif /*SADB_X_MIGRATE*/
1321
1322 #ifdef SADB_X_NAT_T_NEW_MAPPING
1323 /**
1324 * Process a SADB_X_NAT_T_NEW_MAPPING message from the kernel
1325 */
1326 static void process_mapping(private_kernel_pfkey_ipsec_t *this,
1327 struct sadb_msg* msg)
1328 {
1329 pfkey_msg_t response;
1330 u_int32_t spi, reqid;
1331 sockaddr_t *sa;
1332 host_t *host;
1333
1334 DBG2(DBG_KNL, "received an SADB_X_NAT_T_NEW_MAPPING");
1335
1336 if (parse_pfkey_message(msg, &response) != SUCCESS)
1337 {
1338 DBG1(DBG_KNL, "parsing SADB_X_NAT_T_NEW_MAPPING from kernel failed");
1339 return;
1340 }
1341
1342 if (!response.x_sa2)
1343 {
1344 DBG1(DBG_KNL, "received SADB_X_NAT_T_NEW_MAPPING is missing required "
1345 "information");
1346 return;
1347 }
1348
1349 spi = response.sa->sadb_sa_spi;
1350 reqid = response.x_sa2->sadb_x_sa2_reqid;
1351
1352 if (satype2proto(msg->sadb_msg_satype) != IPPROTO_ESP)
1353 {
1354 return;
1355 }
1356
1357 sa = (sockaddr_t*)(response.dst + 1);
1358 switch (sa->sa_family)
1359 {
1360 case AF_INET:
1361 {
1362 struct sockaddr_in *sin = (struct sockaddr_in*)sa;
1363 sin->sin_port = htons(response.x_natt_dport->sadb_x_nat_t_port_port);
1364 break;
1365 }
1366 case AF_INET6:
1367 {
1368 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)sa;
1369 sin6->sin6_port = htons(response.x_natt_dport->sadb_x_nat_t_port_port);
1370 break;
1371 }
1372 default:
1373 break;
1374 }
1375
1376 host = host_create_from_sockaddr(sa);
1377 if (host)
1378 {
1379 hydra->kernel_interface->mapping(hydra->kernel_interface, reqid,
1380 spi, host);
1381 }
1382 }
1383 #endif /*SADB_X_NAT_T_NEW_MAPPING*/
1384
1385 /**
1386 * Receives events from kernel
1387 */
1388 static job_requeue_t receive_events(private_kernel_pfkey_ipsec_t *this)
1389 {
1390 unsigned char buf[PFKEY_BUFFER_SIZE];
1391 struct sadb_msg *msg = (struct sadb_msg*)buf;
1392 bool oldstate;
1393 int len;
1394
1395 oldstate = thread_cancelability(TRUE);
1396 len = recvfrom(this->socket_events, buf, sizeof(buf), 0, NULL, 0);
1397 thread_cancelability(oldstate);
1398
1399 if (len < 0)
1400 {
1401 switch (errno)
1402 {
1403 case EINTR:
1404 /* interrupted, try again */
1405 return JOB_REQUEUE_DIRECT;
1406 case EAGAIN:
1407 /* no data ready, select again */
1408 return JOB_REQUEUE_DIRECT;
1409 default:
1410 DBG1(DBG_KNL, "unable to receive from PF_KEY event socket");
1411 sleep(1);
1412 return JOB_REQUEUE_FAIR;
1413 }
1414 }
1415
1416 if (len < sizeof(struct sadb_msg) ||
1417 msg->sadb_msg_len < PFKEY_LEN(sizeof(struct sadb_msg)))
1418 {
1419 DBG2(DBG_KNL, "received corrupted PF_KEY message");
1420 return JOB_REQUEUE_DIRECT;
1421 }
1422 if (msg->sadb_msg_pid != 0)
1423 { /* not from kernel. not interested, try another one */
1424 return JOB_REQUEUE_DIRECT;
1425 }
1426 if (msg->sadb_msg_len > len / PFKEY_ALIGNMENT)
1427 {
1428 DBG1(DBG_KNL, "buffer was too small to receive the complete "
1429 "PF_KEY message");
1430 return JOB_REQUEUE_DIRECT;
1431 }
1432
1433 switch (msg->sadb_msg_type)
1434 {
1435 case SADB_ACQUIRE:
1436 process_acquire(this, msg);
1437 break;
1438 case SADB_EXPIRE:
1439 process_expire(this, msg);
1440 break;
1441 #ifdef SADB_X_MIGRATE
1442 case SADB_X_MIGRATE:
1443 process_migrate(this, msg);
1444 break;
1445 #endif /*SADB_X_MIGRATE*/
1446 #ifdef SADB_X_NAT_T_NEW_MAPPING
1447 case SADB_X_NAT_T_NEW_MAPPING:
1448 process_mapping(this, msg);
1449 break;
1450 #endif /*SADB_X_NAT_T_NEW_MAPPING*/
1451 default:
1452 break;
1453 }
1454
1455 return JOB_REQUEUE_DIRECT;
1456 }
1457
1458 METHOD(kernel_ipsec_t, get_spi, status_t,
1459 private_kernel_pfkey_ipsec_t *this, host_t *src, host_t *dst,
1460 u_int8_t protocol, u_int32_t reqid, u_int32_t *spi)
1461 {
1462 unsigned char request[PFKEY_BUFFER_SIZE];
1463 struct sadb_msg *msg, *out;
1464 struct sadb_x_sa2 *sa2;
1465 struct sadb_spirange *range;
1466 pfkey_msg_t response;
1467 u_int32_t received_spi = 0;
1468 size_t len;
1469
1470 memset(&request, 0, sizeof(request));
1471
1472 msg = (struct sadb_msg*)request;
1473 msg->sadb_msg_version = PF_KEY_V2;
1474 msg->sadb_msg_type = SADB_GETSPI;
1475 msg->sadb_msg_satype = proto2satype(protocol);
1476 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1477
1478 sa2 = (struct sadb_x_sa2*)PFKEY_EXT_ADD_NEXT(msg);
1479 sa2->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
1480 sa2->sadb_x_sa2_len = PFKEY_LEN(sizeof(struct sadb_spirange));
1481 sa2->sadb_x_sa2_reqid = reqid;
1482 PFKEY_EXT_ADD(msg, sa2);
1483
1484 add_addr_ext(msg, src, SADB_EXT_ADDRESS_SRC, 0, 0, FALSE);
1485 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST, 0, 0, FALSE);
1486
1487 range = (struct sadb_spirange*)PFKEY_EXT_ADD_NEXT(msg);
1488 range->sadb_spirange_exttype = SADB_EXT_SPIRANGE;
1489 range->sadb_spirange_len = PFKEY_LEN(sizeof(struct sadb_spirange));
1490 range->sadb_spirange_min = 0xc0000000;
1491 range->sadb_spirange_max = 0xcFFFFFFF;
1492 PFKEY_EXT_ADD(msg, range);
1493
1494 if (pfkey_send(this, msg, &out, &len) == SUCCESS)
1495 {
1496 if (out->sadb_msg_errno)
1497 {
1498 DBG1(DBG_KNL, "allocating SPI failed: %s (%d)",
1499 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1500 }
1501 else if (parse_pfkey_message(out, &response) == SUCCESS)
1502 {
1503 received_spi = response.sa->sadb_sa_spi;
1504 }
1505 free(out);
1506 }
1507
1508 if (received_spi == 0)
1509 {
1510 return FAILED;
1511 }
1512
1513 *spi = received_spi;
1514 return SUCCESS;
1515 }
1516
1517 METHOD(kernel_ipsec_t, get_cpi, status_t,
1518 private_kernel_pfkey_ipsec_t *this, host_t *src, host_t *dst,
1519 u_int32_t reqid, u_int16_t *cpi)
1520 {
1521 return FAILED;
1522 }
1523
1524 METHOD(kernel_ipsec_t, add_sa, status_t,
1525 private_kernel_pfkey_ipsec_t *this, host_t *src, host_t *dst, u_int32_t spi,
1526 u_int8_t protocol, u_int32_t reqid, mark_t mark, u_int32_t tfc,
1527 lifetime_cfg_t *lifetime, u_int16_t enc_alg, chunk_t enc_key,
1528 u_int16_t int_alg, chunk_t int_key, ipsec_mode_t mode,
1529 u_int16_t ipcomp, u_int16_t cpi, bool initiator, bool encap, bool esn,
1530 bool inbound, traffic_selector_t *src_ts, traffic_selector_t *dst_ts)
1531 {
1532 unsigned char request[PFKEY_BUFFER_SIZE];
1533 struct sadb_msg *msg, *out;
1534 struct sadb_sa *sa;
1535 struct sadb_x_sa2 *sa2;
1536 struct sadb_lifetime *lft;
1537 struct sadb_key *key;
1538 size_t len;
1539
1540 memset(&request, 0, sizeof(request));
1541
1542 DBG2(DBG_KNL, "adding SAD entry with SPI %.8x and reqid {%u}",
1543 ntohl(spi), reqid);
1544
1545 msg = (struct sadb_msg*)request;
1546 msg->sadb_msg_version = PF_KEY_V2;
1547 msg->sadb_msg_type = inbound ? SADB_UPDATE : SADB_ADD;
1548 msg->sadb_msg_satype = proto2satype(protocol);
1549 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1550
1551 #ifdef __APPLE__
1552 if (encap)
1553 {
1554 struct sadb_sa_2 *sa_2;
1555 sa_2 = (struct sadb_sa_2*)PFKEY_EXT_ADD_NEXT(msg);
1556 sa_2->sadb_sa_natt_port = dst->get_port(dst);
1557 sa = &sa_2->sa;
1558 sa->sadb_sa_flags |= SADB_X_EXT_NATT;
1559 len = sizeof(struct sadb_sa_2);
1560 }
1561 else
1562 #endif
1563 {
1564 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1565 len = sizeof(struct sadb_sa);
1566 }
1567 sa->sadb_sa_exttype = SADB_EXT_SA;
1568 sa->sadb_sa_len = PFKEY_LEN(len);
1569 sa->sadb_sa_spi = spi;
1570 sa->sadb_sa_replay = (protocol == IPPROTO_COMP) ? 0 : 32;
1571 sa->sadb_sa_auth = lookup_algorithm(INTEGRITY_ALGORITHM, int_alg);
1572 sa->sadb_sa_encrypt = lookup_algorithm(ENCRYPTION_ALGORITHM, enc_alg);
1573 PFKEY_EXT_ADD(msg, sa);
1574
1575 sa2 = (struct sadb_x_sa2*)PFKEY_EXT_ADD_NEXT(msg);
1576 sa2->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
1577 sa2->sadb_x_sa2_len = PFKEY_LEN(sizeof(struct sadb_spirange));
1578 sa2->sadb_x_sa2_mode = mode2kernel(mode);
1579 sa2->sadb_x_sa2_reqid = reqid;
1580 PFKEY_EXT_ADD(msg, sa2);
1581
1582 add_addr_ext(msg, src, SADB_EXT_ADDRESS_SRC, 0, 0, FALSE);
1583 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST, 0, 0, FALSE);
1584
1585 lft = (struct sadb_lifetime*)PFKEY_EXT_ADD_NEXT(msg);
1586 lft->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
1587 lft->sadb_lifetime_len = PFKEY_LEN(sizeof(struct sadb_lifetime));
1588 lft->sadb_lifetime_allocations = lifetime->packets.rekey;
1589 lft->sadb_lifetime_bytes = lifetime->bytes.rekey;
1590 lft->sadb_lifetime_addtime = lifetime->time.rekey;
1591 lft->sadb_lifetime_usetime = 0; /* we only use addtime */
1592 PFKEY_EXT_ADD(msg, lft);
1593
1594 lft = (struct sadb_lifetime*)PFKEY_EXT_ADD_NEXT(msg);
1595 lft->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
1596 lft->sadb_lifetime_len = PFKEY_LEN(sizeof(struct sadb_lifetime));
1597 lft->sadb_lifetime_allocations = lifetime->packets.life;
1598 lft->sadb_lifetime_bytes = lifetime->bytes.life;
1599 lft->sadb_lifetime_addtime = lifetime->time.life;
1600 lft->sadb_lifetime_usetime = 0; /* we only use addtime */
1601 PFKEY_EXT_ADD(msg, lft);
1602
1603 if (enc_alg != ENCR_UNDEFINED)
1604 {
1605 if (!sa->sadb_sa_encrypt)
1606 {
1607 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1608 encryption_algorithm_names, enc_alg);
1609 return FAILED;
1610 }
1611 DBG2(DBG_KNL, " using encryption algorithm %N with key size %d",
1612 encryption_algorithm_names, enc_alg, enc_key.len * 8);
1613
1614 key = (struct sadb_key*)PFKEY_EXT_ADD_NEXT(msg);
1615 key->sadb_key_exttype = SADB_EXT_KEY_ENCRYPT;
1616 key->sadb_key_bits = enc_key.len * 8;
1617 key->sadb_key_len = PFKEY_LEN(sizeof(struct sadb_key) + enc_key.len);
1618 memcpy(key + 1, enc_key.ptr, enc_key.len);
1619
1620 PFKEY_EXT_ADD(msg, key);
1621 }
1622
1623 if (int_alg != AUTH_UNDEFINED)
1624 {
1625 if (!sa->sadb_sa_auth)
1626 {
1627 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1628 integrity_algorithm_names, int_alg);
1629 return FAILED;
1630 }
1631 DBG2(DBG_KNL, " using integrity algorithm %N with key size %d",
1632 integrity_algorithm_names, int_alg, int_key.len * 8);
1633
1634 key = (struct sadb_key*)PFKEY_EXT_ADD_NEXT(msg);
1635 key->sadb_key_exttype = SADB_EXT_KEY_AUTH;
1636 key->sadb_key_bits = int_key.len * 8;
1637 key->sadb_key_len = PFKEY_LEN(sizeof(struct sadb_key) + int_key.len);
1638 memcpy(key + 1, int_key.ptr, int_key.len);
1639
1640 PFKEY_EXT_ADD(msg, key);
1641 }
1642
1643 if (ipcomp != IPCOMP_NONE)
1644 {
1645 /*TODO*/
1646 }
1647
1648 #ifdef HAVE_NATT
1649 if (encap)
1650 {
1651 add_encap_ext(msg, src, dst);
1652 }
1653 #endif /*HAVE_NATT*/
1654
1655 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1656 {
1657 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x", ntohl(spi));
1658 return FAILED;
1659 }
1660 else if (out->sadb_msg_errno)
1661 {
1662 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x: %s (%d)",
1663 ntohl(spi), strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1664 free(out);
1665 return FAILED;
1666 }
1667
1668 free(out);
1669 return SUCCESS;
1670 }
1671
1672 METHOD(kernel_ipsec_t, update_sa, status_t,
1673 private_kernel_pfkey_ipsec_t *this, u_int32_t spi, u_int8_t protocol,
1674 u_int16_t cpi, host_t *src, host_t *dst, host_t *new_src, host_t *new_dst,
1675 bool encap, bool new_encap, mark_t mark)
1676 {
1677 unsigned char request[PFKEY_BUFFER_SIZE];
1678 struct sadb_msg *msg, *out;
1679 struct sadb_sa *sa;
1680 pfkey_msg_t response;
1681 size_t len;
1682
1683 /* we can't update the SA if any of the ip addresses have changed.
1684 * that's because we can't use SADB_UPDATE and by deleting and readding the
1685 * SA the sequence numbers would get lost */
1686 if (!src->ip_equals(src, new_src) ||
1687 !dst->ip_equals(dst, new_dst))
1688 {
1689 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x: address "
1690 "changes are not supported", ntohl(spi));
1691 return NOT_SUPPORTED;
1692 }
1693
1694 memset(&request, 0, sizeof(request));
1695
1696 DBG2(DBG_KNL, "querying SAD entry with SPI %.8x", ntohl(spi));
1697
1698 msg = (struct sadb_msg*)request;
1699 msg->sadb_msg_version = PF_KEY_V2;
1700 msg->sadb_msg_type = SADB_GET;
1701 msg->sadb_msg_satype = proto2satype(protocol);
1702 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1703
1704 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1705 sa->sadb_sa_exttype = SADB_EXT_SA;
1706 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1707 sa->sadb_sa_spi = spi;
1708 PFKEY_EXT_ADD(msg, sa);
1709
1710 /* the kernel wants a SADB_EXT_ADDRESS_SRC to be present even though
1711 * it is not used for anything. */
1712 add_anyaddr_ext(msg, dst->get_family(dst), SADB_EXT_ADDRESS_SRC);
1713 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST, 0, 0, FALSE);
1714
1715 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1716 {
1717 DBG1(DBG_KNL, "unable to query SAD entry with SPI %.8x", ntohl(spi));
1718 return FAILED;
1719 }
1720 else if (out->sadb_msg_errno)
1721 {
1722 DBG1(DBG_KNL, "unable to query SAD entry with SPI %.8x: %s (%d)",
1723 ntohl(spi), strerror(out->sadb_msg_errno),
1724 out->sadb_msg_errno);
1725 free(out);
1726 return FAILED;
1727 }
1728 else if (parse_pfkey_message(out, &response) != SUCCESS)
1729 {
1730 DBG1(DBG_KNL, "unable to query SAD entry with SPI %.8x: parsing "
1731 "response from kernel failed", ntohl(spi));
1732 free(out);
1733 return FAILED;
1734 }
1735
1736 DBG2(DBG_KNL, "updating SAD entry with SPI %.8x from %#H..%#H to %#H..%#H",
1737 ntohl(spi), src, dst, new_src, new_dst);
1738
1739 memset(&request, 0, sizeof(request));
1740
1741 msg = (struct sadb_msg*)request;
1742 msg->sadb_msg_version = PF_KEY_V2;
1743 msg->sadb_msg_type = SADB_UPDATE;
1744 msg->sadb_msg_satype = proto2satype(protocol);
1745 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1746
1747 #ifdef __APPLE__
1748 {
1749 struct sadb_sa_2 *sa_2;
1750 sa_2 = (struct sadb_sa_2*)PFKEY_EXT_ADD_NEXT(msg);
1751 sa_2->sa.sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa_2));
1752 memcpy(&sa_2->sa, response.sa, sizeof(struct sadb_sa));
1753 if (encap)
1754 {
1755 sa_2->sadb_sa_natt_port = new_dst->get_port(new_dst);
1756 sa_2->sa.sadb_sa_flags |= SADB_X_EXT_NATT;
1757 }
1758 }
1759 #else
1760 PFKEY_EXT_COPY(msg, response.sa);
1761 #endif
1762 PFKEY_EXT_COPY(msg, response.x_sa2);
1763
1764 PFKEY_EXT_COPY(msg, response.src);
1765 PFKEY_EXT_COPY(msg, response.dst);
1766
1767 PFKEY_EXT_COPY(msg, response.lft_soft);
1768 PFKEY_EXT_COPY(msg, response.lft_hard);
1769
1770 if (response.key_encr)
1771 {
1772 PFKEY_EXT_COPY(msg, response.key_encr);
1773 }
1774
1775 if (response.key_auth)
1776 {
1777 PFKEY_EXT_COPY(msg, response.key_auth);
1778 }
1779
1780 #ifdef HAVE_NATT
1781 if (new_encap)
1782 {
1783 add_encap_ext(msg, new_src, new_dst);
1784 }
1785 #endif /*HAVE_NATT*/
1786
1787 free(out);
1788
1789 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1790 {
1791 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x", ntohl(spi));
1792 return FAILED;
1793 }
1794 else if (out->sadb_msg_errno)
1795 {
1796 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x: %s (%d)",
1797 ntohl(spi), strerror(out->sadb_msg_errno),
1798 out->sadb_msg_errno);
1799 free(out);
1800 return FAILED;
1801 }
1802 free(out);
1803
1804 return SUCCESS;
1805 }
1806
1807 METHOD(kernel_ipsec_t, query_sa, status_t,
1808 private_kernel_pfkey_ipsec_t *this, host_t *src, host_t *dst,
1809 u_int32_t spi, u_int8_t protocol, mark_t mark,
1810 u_int64_t *bytes, u_int64_t *packets, u_int32_t *time)
1811 {
1812 unsigned char request[PFKEY_BUFFER_SIZE];
1813 struct sadb_msg *msg, *out;
1814 struct sadb_sa *sa;
1815 pfkey_msg_t response;
1816 size_t len;
1817
1818 memset(&request, 0, sizeof(request));
1819
1820 DBG2(DBG_KNL, "querying SAD entry with SPI %.8x", ntohl(spi));
1821
1822 msg = (struct sadb_msg*)request;
1823 msg->sadb_msg_version = PF_KEY_V2;
1824 msg->sadb_msg_type = SADB_GET;
1825 msg->sadb_msg_satype = proto2satype(protocol);
1826 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1827
1828 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1829 sa->sadb_sa_exttype = SADB_EXT_SA;
1830 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1831 sa->sadb_sa_spi = spi;
1832 PFKEY_EXT_ADD(msg, sa);
1833
1834 /* the Linux Kernel doesn't care for the src address, but other systems do
1835 * (e.g. FreeBSD)
1836 */
1837 add_addr_ext(msg, src, SADB_EXT_ADDRESS_SRC, 0, 0, FALSE);
1838 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST, 0, 0, FALSE);
1839
1840 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1841 {
1842 DBG1(DBG_KNL, "unable to query SAD entry with SPI %.8x", ntohl(spi));
1843 return FAILED;
1844 }
1845 else if (out->sadb_msg_errno)
1846 {
1847 DBG1(DBG_KNL, "unable to query SAD entry with SPI %.8x: %s (%d)",
1848 ntohl(spi), strerror(out->sadb_msg_errno),
1849 out->sadb_msg_errno);
1850 free(out);
1851 return FAILED;
1852 }
1853 else if (parse_pfkey_message(out, &response) != SUCCESS)
1854 {
1855 DBG1(DBG_KNL, "unable to query SAD entry with SPI %.8x", ntohl(spi));
1856 free(out);
1857 return FAILED;
1858 }
1859 if (bytes)
1860 {
1861 *bytes = response.lft_current->sadb_lifetime_bytes;
1862 }
1863 if (packets)
1864 {
1865 /* not supported by PF_KEY */
1866 *packets = 0;
1867 }
1868 if (time)
1869 {
1870 #ifdef __APPLE__
1871 /* OS X uses the "last" time of use in usetime */
1872 *time = response.lft_current->sadb_lifetime_usetime;
1873 #else /* !__APPLE__ */
1874 /* on Linux, sadb_lifetime_usetime is set to the "first" time of use,
1875 * which is actually correct according to PF_KEY. We have to query
1876 * policies for the last usetime. */
1877 *time = 0;
1878 #endif /* !__APPLE__ */
1879 }
1880
1881 free(out);
1882 return SUCCESS;
1883 }
1884
1885 METHOD(kernel_ipsec_t, del_sa, status_t,
1886 private_kernel_pfkey_ipsec_t *this, host_t *src, host_t *dst,
1887 u_int32_t spi, u_int8_t protocol, u_int16_t cpi, mark_t mark)
1888 {
1889 unsigned char request[PFKEY_BUFFER_SIZE];
1890 struct sadb_msg *msg, *out;
1891 struct sadb_sa *sa;
1892 size_t len;
1893
1894 memset(&request, 0, sizeof(request));
1895
1896 DBG2(DBG_KNL, "deleting SAD entry with SPI %.8x", ntohl(spi));
1897
1898 msg = (struct sadb_msg*)request;
1899 msg->sadb_msg_version = PF_KEY_V2;
1900 msg->sadb_msg_type = SADB_DELETE;
1901 msg->sadb_msg_satype = proto2satype(protocol);
1902 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1903
1904 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1905 sa->sadb_sa_exttype = SADB_EXT_SA;
1906 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1907 sa->sadb_sa_spi = spi;
1908 PFKEY_EXT_ADD(msg, sa);
1909
1910 /* the Linux Kernel doesn't care for the src address, but other systems do
1911 * (e.g. FreeBSD)
1912 */
1913 add_addr_ext(msg, src, SADB_EXT_ADDRESS_SRC, 0, 0, FALSE);
1914 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST, 0, 0, FALSE);
1915
1916 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1917 {
1918 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x", ntohl(spi));
1919 return FAILED;
1920 }
1921 else if (out->sadb_msg_errno)
1922 {
1923 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x: %s (%d)",
1924 ntohl(spi), strerror(out->sadb_msg_errno),
1925 out->sadb_msg_errno);
1926 free(out);
1927 return FAILED;
1928 }
1929
1930 DBG2(DBG_KNL, "deleted SAD entry with SPI %.8x", ntohl(spi));
1931 free(out);
1932 return SUCCESS;
1933 }
1934
1935 METHOD(kernel_ipsec_t, flush_sas, status_t,
1936 private_kernel_pfkey_ipsec_t *this)
1937 {
1938 unsigned char request[PFKEY_BUFFER_SIZE];
1939 struct sadb_msg *msg, *out;
1940 size_t len;
1941
1942 memset(&request, 0, sizeof(request));
1943
1944 DBG2(DBG_KNL, "flushing all SAD entries");
1945
1946 msg = (struct sadb_msg*)request;
1947 msg->sadb_msg_version = PF_KEY_V2;
1948 msg->sadb_msg_type = SADB_FLUSH;
1949 msg->sadb_msg_satype = SADB_SATYPE_UNSPEC;
1950 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1951
1952 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1953 {
1954 DBG1(DBG_KNL, "unable to flush SAD entries");
1955 return FAILED;
1956 }
1957 else if (out->sadb_msg_errno)
1958 {
1959 DBG1(DBG_KNL, "unable to flush SAD entries: %s (%d)",
1960 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1961 free(out);
1962 return FAILED;
1963 }
1964 free(out);
1965 return SUCCESS;
1966 }
1967
1968 /**
1969 * Add an explicit exclude route to a routing entry
1970 */
1971 static void add_exclude_route(private_kernel_pfkey_ipsec_t *this,
1972 route_entry_t *route, host_t *src, host_t *dst)
1973 {
1974 enumerator_t *enumerator;
1975 exclude_route_t *exclude;
1976 host_t *gtw;
1977
1978 enumerator = this->excludes->create_enumerator(this->excludes);
1979 while (enumerator->enumerate(enumerator, &exclude))
1980 {
1981 if (dst->ip_equals(dst, exclude->dst))
1982 {
1983 route->exclude = exclude;
1984 exclude->refs++;
1985 }
1986 }
1987 enumerator->destroy(enumerator);
1988
1989 if (!route->exclude)
1990 {
1991 DBG2(DBG_KNL, "installing new exclude route for %H src %H", dst, src);
1992 gtw = hydra->kernel_interface->get_nexthop(hydra->kernel_interface,
1993 dst, NULL);
1994 if (gtw)
1995 {
1996 char *if_name = NULL;
1997
1998 if (hydra->kernel_interface->get_interface(
1999 hydra->kernel_interface, src, &if_name) &&
2000 hydra->kernel_interface->add_route(hydra->kernel_interface,
2001 dst->get_address(dst),
2002 dst->get_family(dst) == AF_INET ? 32 : 128,
2003 gtw, src, if_name) == SUCCESS)
2004 {
2005 INIT(exclude,
2006 .dst = dst->clone(dst),
2007 .src = src->clone(src),
2008 .gtw = gtw->clone(gtw),
2009 .refs = 1,
2010 );
2011 route->exclude = exclude;
2012 this->excludes->insert_last(this->excludes, exclude);
2013 }
2014 else
2015 {
2016 DBG1(DBG_KNL, "installing exclude route for %H failed", dst);
2017 }
2018 gtw->destroy(gtw);
2019 free(if_name);
2020 }
2021 else
2022 {
2023 DBG1(DBG_KNL, "gateway lookup for for %H failed", dst);
2024 }
2025 }
2026 }
2027
2028 /**
2029 * Remove an exclude route attached to a routing entry
2030 */
2031 static void remove_exclude_route(private_kernel_pfkey_ipsec_t *this,
2032 route_entry_t *route)
2033 {
2034 if (route->exclude)
2035 {
2036 enumerator_t *enumerator;
2037 exclude_route_t *exclude;
2038 bool removed = FALSE;
2039 host_t *dst;
2040
2041 enumerator = this->excludes->create_enumerator(this->excludes);
2042 while (enumerator->enumerate(enumerator, &exclude))
2043 {
2044 if (route->exclude == exclude)
2045 {
2046 if (--exclude->refs == 0)
2047 {
2048 this->excludes->remove_at(this->excludes, enumerator);
2049 removed = TRUE;
2050 break;
2051 }
2052 }
2053 }
2054 enumerator->destroy(enumerator);
2055
2056 if (removed)
2057 {
2058 char *if_name = NULL;
2059
2060 dst = route->exclude->dst;
2061 DBG2(DBG_KNL, "uninstalling exclude route for %H src %H",
2062 dst, route->exclude->src);
2063 if (hydra->kernel_interface->get_interface(
2064 hydra->kernel_interface,
2065 route->exclude->src, &if_name) &&
2066 hydra->kernel_interface->del_route(hydra->kernel_interface,
2067 dst->get_address(dst),
2068 dst->get_family(dst) == AF_INET ? 32 : 128,
2069 route->exclude->gtw, route->exclude->src,
2070 if_name) != SUCCESS)
2071 {
2072 DBG1(DBG_KNL, "uninstalling exclude route for %H failed", dst);
2073 }
2074 exclude_route_destroy(route->exclude);
2075 free(if_name);
2076 }
2077 route->exclude = NULL;
2078 }
2079 }
2080
2081 /**
2082 * Try to install a route to the given inbound policy
2083 */
2084 static bool install_route(private_kernel_pfkey_ipsec_t *this,
2085 policy_entry_t *policy, policy_sa_in_t *in)
2086 {
2087 route_entry_t *route, *old;
2088 host_t *host, *src, *dst;
2089 bool is_virtual;
2090
2091 if (hydra->kernel_interface->get_address_by_ts(hydra->kernel_interface,
2092 in->dst_ts, &host, &is_virtual) != SUCCESS)
2093 {
2094 return FALSE;
2095 }
2096
2097 /* switch src/dst, as we handle an IN policy */
2098 src = in->generic.sa->dst;
2099 dst = in->generic.sa->src;
2100
2101 INIT(route,
2102 .prefixlen = policy->src.mask,
2103 .src_ip = host,
2104 .gateway = hydra->kernel_interface->get_nexthop(
2105 hydra->kernel_interface, dst, src),
2106 .dst_net = chunk_clone(policy->src.net->get_address(policy->src.net)),
2107 );
2108
2109 /* if the IP is virtual, we install the route over the interface it has
2110 * been installed on. Otherwise we use the interface we use for IKE, as
2111 * this is required for example on Linux. */
2112 if (is_virtual)
2113 {
2114 src = route->src_ip;
2115 }
2116
2117 /* get interface for route, using source address */
2118 if (!hydra->kernel_interface->get_interface(hydra->kernel_interface,
2119 src, &route->if_name))
2120 {
2121 route_entry_destroy(route);
2122 return FALSE;
2123 }
2124
2125 if (policy->route)
2126 {
2127 old = policy->route;
2128
2129 if (route_entry_equals(old, route))
2130 { /* such a route already exists */
2131 route_entry_destroy(route);
2132 return TRUE;
2133 }
2134 /* uninstall previously installed route */
2135 if (hydra->kernel_interface->del_route(hydra->kernel_interface,
2136 old->dst_net, old->prefixlen, old->gateway,
2137 old->src_ip, old->if_name) != SUCCESS)
2138 {
2139 DBG1(DBG_KNL, "error uninstalling route installed with policy "
2140 "%R === %R %N", in->src_ts, in->dst_ts,
2141 policy_dir_names, policy->direction);
2142 }
2143 route_entry_destroy(old);
2144 policy->route = NULL;
2145 }
2146
2147 /* if remote traffic selector covers the IKE peer, add an exclude route */
2148 if (hydra->kernel_interface->get_features(
2149 hydra->kernel_interface) & KERNEL_REQUIRE_EXCLUDE_ROUTE)
2150 {
2151 if (in->src_ts->includes(in->src_ts, dst))
2152 {
2153 add_exclude_route(this, route, in->generic.sa->dst, dst);
2154 }
2155 }
2156
2157 DBG2(DBG_KNL, "installing route: %R via %H src %H dev %s",
2158 in->src_ts, route->gateway, route->src_ip, route->if_name);
2159
2160 switch (hydra->kernel_interface->add_route(hydra->kernel_interface,
2161 route->dst_net, route->prefixlen, route->gateway,
2162 route->src_ip, route->if_name))
2163 {
2164 case ALREADY_DONE:
2165 /* route exists, do not uninstall */
2166 remove_exclude_route(this, route);
2167 route_entry_destroy(route);
2168 return TRUE;
2169 case SUCCESS:
2170 /* cache the installed route */
2171 policy->route = route;
2172 return TRUE;
2173 default:
2174 DBG1(DBG_KNL, "installing route failed: %R via %H src %H dev %s",
2175 in->src_ts, route->gateway, route->src_ip, route->if_name);
2176 remove_exclude_route(this, route);
2177 route_entry_destroy(route);
2178 return FALSE;
2179 }
2180 }
2181
2182 /**
2183 * Add or update a policy in the kernel.
2184 *
2185 * Note: The mutex has to be locked when entering this function.
2186 */
2187 static status_t add_policy_internal(private_kernel_pfkey_ipsec_t *this,
2188 policy_entry_t *policy, policy_sa_t *mapping, bool update)
2189 {
2190 unsigned char request[PFKEY_BUFFER_SIZE];
2191 struct sadb_msg *msg, *out;
2192 struct sadb_x_policy *pol;
2193 struct sadb_x_ipsecrequest *req;
2194 ipsec_sa_t *ipsec = mapping->sa;
2195 pfkey_msg_t response;
2196 size_t len;
2197
2198 memset(&request, 0, sizeof(request));
2199
2200 msg = (struct sadb_msg*)request;
2201 msg->sadb_msg_version = PF_KEY_V2;
2202 msg->sadb_msg_type = update ? SADB_X_SPDUPDATE : SADB_X_SPDADD;
2203 msg->sadb_msg_satype = 0;
2204 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2205
2206 pol = (struct sadb_x_policy*)PFKEY_EXT_ADD_NEXT(msg);
2207 pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2208 pol->sadb_x_policy_len = PFKEY_LEN(sizeof(struct sadb_x_policy));
2209 pol->sadb_x_policy_id = 0;
2210 pol->sadb_x_policy_dir = dir2kernel(policy->direction);
2211 pol->sadb_x_policy_type = type2kernel(mapping->type);
2212 #ifdef HAVE_STRUCT_SADB_X_POLICY_SADB_X_POLICY_PRIORITY
2213 pol->sadb_x_policy_priority = mapping->priority;
2214 #endif
2215
2216 /* one or more sadb_x_ipsecrequest extensions are added to the
2217 * sadb_x_policy extension */
2218 req = (struct sadb_x_ipsecrequest*)(pol + 1);
2219 req->sadb_x_ipsecrequest_proto = ipsec->cfg.esp.use ? IPPROTO_ESP
2220 : IPPROTO_AH;
2221 /* !!! the length here MUST be in octets instead of 64 bit words */
2222 req->sadb_x_ipsecrequest_len = sizeof(struct sadb_x_ipsecrequest);
2223 req->sadb_x_ipsecrequest_mode = mode2kernel(ipsec->cfg.mode);
2224 req->sadb_x_ipsecrequest_reqid = ipsec->cfg.reqid;
2225 req->sadb_x_ipsecrequest_level = IPSEC_LEVEL_UNIQUE;
2226 if (ipsec->cfg.mode == MODE_TUNNEL)
2227 {
2228 len = hostcpy(req + 1, ipsec->src, FALSE);
2229 req->sadb_x_ipsecrequest_len += len;
2230 len = hostcpy((char*)(req + 1) + len, ipsec->dst, FALSE);
2231 req->sadb_x_ipsecrequest_len += len;
2232 }
2233
2234 pol->sadb_x_policy_len += PFKEY_LEN(req->sadb_x_ipsecrequest_len);
2235 PFKEY_EXT_ADD(msg, pol);
2236
2237 add_addr_ext(msg, policy->src.net, SADB_EXT_ADDRESS_SRC, policy->src.proto,
2238 policy->src.mask, TRUE);
2239 add_addr_ext(msg, policy->dst.net, SADB_EXT_ADDRESS_DST, policy->dst.proto,
2240 policy->dst.mask, TRUE);
2241
2242 #ifdef __FreeBSD__
2243 { /* on FreeBSD a lifetime has to be defined to be able to later query
2244 * the current use time. */
2245 struct sadb_lifetime *lft;
2246 lft = (struct sadb_lifetime*)PFKEY_EXT_ADD_NEXT(msg);
2247 lft->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2248 lft->sadb_lifetime_len = PFKEY_LEN(sizeof(struct sadb_lifetime));
2249 lft->sadb_lifetime_addtime = LONG_MAX;
2250 PFKEY_EXT_ADD(msg, lft);
2251 }
2252 #endif
2253
2254 this->mutex->unlock(this->mutex);
2255
2256 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2257 {
2258 return FAILED;
2259 }
2260 else if (out->sadb_msg_errno)
2261 {
2262 DBG1(DBG_KNL, "unable to %s policy: %s (%d)",
2263 update ? "update" : "add", strerror(out->sadb_msg_errno),
2264 out->sadb_msg_errno);
2265 free(out);
2266 return FAILED;
2267 }
2268 else if (parse_pfkey_message(out, &response) != SUCCESS)
2269 {
2270 DBG1(DBG_KNL, "unable to %s policy: parsing response from kernel "
2271 "failed", update ? "update" : "add");
2272 free(out);
2273 return FAILED;
2274 }
2275
2276 /* we try to find the policy again and update the kernel index */
2277 this->mutex->lock(this->mutex);
2278 if (this->policies->find_first(this->policies, NULL,
2279 (void**)&policy) != SUCCESS)
2280 {
2281 DBG2(DBG_KNL, "unable to update index, the policy is already gone, "
2282 "ignoring");
2283 this->mutex->unlock(this->mutex);
2284 free(out);
2285 return SUCCESS;
2286 }
2287 policy->index = response.x_policy->sadb_x_policy_id;
2288 free(out);
2289
2290 /* install a route, if:
2291 * - this is a forward policy (to just get one for each child)
2292 * - we are in tunnel mode
2293 * - routing is not disabled via strongswan.conf
2294 */
2295 if (policy->direction == POLICY_IN &&
2296 ipsec->cfg.mode != MODE_TRANSPORT && this->install_routes)
2297 {
2298 install_route(this, policy, (policy_sa_in_t*)mapping);
2299 }
2300 this->mutex->unlock(this->mutex);
2301 return SUCCESS;
2302 }
2303
2304 METHOD(kernel_ipsec_t, add_policy, status_t,
2305 private_kernel_pfkey_ipsec_t *this, host_t *src, host_t *dst,
2306 traffic_selector_t *src_ts, traffic_selector_t *dst_ts,
2307 policy_dir_t direction, policy_type_t type, ipsec_sa_cfg_t *sa,
2308 mark_t mark, policy_priority_t priority)
2309 {
2310 policy_entry_t *policy, *found = NULL;
2311 policy_sa_t *assigned_sa, *current_sa;
2312 enumerator_t *enumerator;
2313 bool update = TRUE;
2314
2315 if (dir2kernel(direction) == IPSEC_DIR_INVALID)
2316 { /* FWD policies are not supported on all platforms */
2317 return SUCCESS;
2318 }
2319
2320 /* create a policy */
2321 policy = create_policy_entry(src_ts, dst_ts, direction);
2322
2323 /* find a matching policy */
2324 this->mutex->lock(this->mutex);
2325 if (this->policies->find_first(this->policies,
2326 (linked_list_match_t)policy_entry_equals,
2327 (void**)&found, policy) == SUCCESS)
2328 { /* use existing policy */
2329 DBG2(DBG_KNL, "policy %R === %R %N already exists, increasing "
2330 "refcount", src_ts, dst_ts, policy_dir_names, direction);
2331 policy_entry_destroy(policy, this);
2332 policy = found;
2333 }
2334 else
2335 { /* use the new one, if we have no such policy */
2336 this->policies->insert_first(this->policies, policy);
2337 policy->used_by = linked_list_create();
2338 }
2339
2340 /* cache the assigned IPsec SA */
2341 assigned_sa = policy_sa_create(this, direction, type, src, dst, src_ts,
2342 dst_ts, sa);
2343 assigned_sa->priority = get_priority(policy, priority);
2344
2345 /* insert the SA according to its priority */
2346 enumerator = policy->used_by->create_enumerator(policy->used_by);
2347 while (enumerator->enumerate(enumerator, (void**)&current_sa))
2348 {
2349 if (current_sa->priority >= assigned_sa->priority)
2350 {
2351 break;
2352 }
2353 update = FALSE;
2354 }
2355 policy->used_by->insert_before(policy->used_by, enumerator, assigned_sa);
2356 enumerator->destroy(enumerator);
2357
2358 if (!update)
2359 { /* we don't update the policy if the priority is lower than that of the
2360 * currently installed one */
2361 this->mutex->unlock(this->mutex);
2362 return SUCCESS;
2363 }
2364
2365 DBG2(DBG_KNL, "%s policy %R === %R %N",
2366 found ? "updating" : "adding", src_ts, dst_ts,
2367 policy_dir_names, direction);
2368
2369 if (add_policy_internal(this, policy, assigned_sa, found) != SUCCESS)
2370 {
2371 DBG1(DBG_KNL, "unable to %s policy %R === %R %N",
2372 found ? "update" : "add", src_ts, dst_ts,
2373 policy_dir_names, direction);
2374 return FAILED;
2375 }
2376 return SUCCESS;
2377 }
2378
2379 METHOD(kernel_ipsec_t, query_policy, status_t,
2380 private_kernel_pfkey_ipsec_t *this, traffic_selector_t *src_ts,
2381 traffic_selector_t *dst_ts, policy_dir_t direction, mark_t mark,
2382 u_int32_t *use_time)
2383 {
2384 unsigned char request[PFKEY_BUFFER_SIZE];
2385 struct sadb_msg *msg, *out;
2386 struct sadb_x_policy *pol;
2387 policy_entry_t *policy, *found = NULL;
2388 pfkey_msg_t response;
2389 size_t len;
2390
2391 if (dir2kernel(direction) == IPSEC_DIR_INVALID)
2392 { /* FWD policies are not supported on all platforms */
2393 return NOT_FOUND;
2394 }
2395
2396 DBG2(DBG_KNL, "querying policy %R === %R %N", src_ts, dst_ts,
2397 policy_dir_names, direction);
2398
2399 /* create a policy */
2400 policy = create_policy_entry(src_ts, dst_ts, direction);
2401
2402 /* find a matching policy */
2403 this->mutex->lock(this->mutex);
2404 if (this->policies->find_first(this->policies,
2405 (linked_list_match_t)policy_entry_equals,
2406 (void**)&found, policy) != SUCCESS)
2407 {
2408 DBG1(DBG_KNL, "querying policy %R === %R %N failed, not found", src_ts,
2409 dst_ts, policy_dir_names, direction);
2410 policy_entry_destroy(policy, this);
2411 this->mutex->unlock(this->mutex);
2412 return NOT_FOUND;
2413 }
2414 policy_entry_destroy(policy, this);
2415 policy = found;
2416
2417 memset(&request, 0, sizeof(request));
2418
2419 msg = (struct sadb_msg*)request;
2420 msg->sadb_msg_version = PF_KEY_V2;
2421 msg->sadb_msg_type = SADB_X_SPDGET;
2422 msg->sadb_msg_satype = 0;
2423 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2424
2425 pol = (struct sadb_x_policy*)PFKEY_EXT_ADD_NEXT(msg);
2426 pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2427 pol->sadb_x_policy_id = policy->index;
2428 pol->sadb_x_policy_len = PFKEY_LEN(sizeof(struct sadb_x_policy));
2429 pol->sadb_x_policy_dir = dir2kernel(direction);
2430 pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC;
2431 PFKEY_EXT_ADD(msg, pol);
2432
2433 add_addr_ext(msg, policy->src.net, SADB_EXT_ADDRESS_SRC, policy->src.proto,
2434 policy->src.mask, TRUE);
2435 add_addr_ext(msg, policy->dst.net, SADB_EXT_ADDRESS_DST, policy->dst.proto,
2436 policy->dst.mask, TRUE);
2437
2438 this->mutex->unlock(this->mutex);
2439
2440 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2441 {
2442 DBG1(DBG_KNL, "unable to query policy %R === %R %N", src_ts, dst_ts,
2443 policy_dir_names, direction);
2444 return FAILED;
2445 }
2446 else if (out->sadb_msg_errno)
2447 {
2448 DBG1(DBG_KNL, "unable to query policy %R === %R %N: %s (%d)", src_ts,
2449 dst_ts, policy_dir_names, direction,
2450 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2451 free(out);
2452 return FAILED;
2453 }
2454 else if (parse_pfkey_message(out, &response) != SUCCESS)
2455 {
2456 DBG1(DBG_KNL, "unable to query policy %R === %R %N: parsing response "
2457 "from kernel failed", src_ts, dst_ts, policy_dir_names,
2458 direction);
2459 free(out);
2460 return FAILED;
2461 }
2462 else if (response.lft_current == NULL)
2463 {
2464 DBG2(DBG_KNL, "unable to query policy %R === %R %N: kernel reports no "
2465 "use time", src_ts, dst_ts, policy_dir_names, direction);
2466 free(out);
2467 return FAILED;
2468 }
2469
2470 /* we need the monotonic time, but the kernel returns system time. */
2471 if (response.lft_current->sadb_lifetime_usetime)
2472 {
2473 *use_time = time_monotonic(NULL) -
2474 (time(NULL) - response.lft_current->sadb_lifetime_usetime);
2475 }
2476 else
2477 {
2478 *use_time = 0;
2479 }
2480 free(out);
2481 return SUCCESS;
2482 }
2483
2484 METHOD(kernel_ipsec_t, del_policy, status_t,
2485 private_kernel_pfkey_ipsec_t *this, traffic_selector_t *src_ts,
2486 traffic_selector_t *dst_ts, policy_dir_t direction, u_int32_t reqid,
2487 mark_t mark, policy_priority_t prio)
2488 {
2489 unsigned char request[PFKEY_BUFFER_SIZE];
2490 struct sadb_msg *msg, *out;
2491 struct sadb_x_policy *pol;
2492 policy_entry_t *policy, *found = NULL;
2493 policy_sa_t *mapping, *to_remove = NULL;
2494 enumerator_t *enumerator;
2495 bool first = TRUE, is_installed = TRUE;
2496 u_int32_t priority;
2497 size_t len;
2498
2499 if (dir2kernel(direction) == IPSEC_DIR_INVALID)
2500 { /* FWD policies are not supported on all platforms */
2501 return SUCCESS;
2502 }
2503
2504 DBG2(DBG_KNL, "deleting policy %R === %R %N", src_ts, dst_ts,
2505 policy_dir_names, direction);
2506
2507 /* create a policy */
2508 policy = create_policy_entry(src_ts, dst_ts, direction);
2509
2510 /* find a matching policy */
2511 this->mutex->lock(this->mutex);
2512 if (this->policies->find_first(this->policies,
2513 (linked_list_match_t)policy_entry_equals,
2514 (void**)&found, policy) != SUCCESS)
2515 {
2516 DBG1(DBG_KNL, "deleting policy %R === %R %N failed, not found", src_ts,
2517 dst_ts, policy_dir_names, direction);
2518 policy_entry_destroy(policy, this);
2519 this->mutex->unlock(this->mutex);
2520 return NOT_FOUND;
2521 }
2522 policy_entry_destroy(policy, this);
2523 policy = found;
2524
2525 /* remove mapping to SA by reqid and priority, if multiple match, which
2526 * could happen when rekeying due to an address change, remove the oldest */
2527 priority = get_priority(policy, prio);
2528 enumerator = policy->used_by->create_enumerator(policy->used_by);
2529 while (enumerator->enumerate(enumerator, (void**)&mapping))
2530 {
2531 if (reqid == mapping->sa->cfg.reqid && priority == mapping->priority)
2532 {
2533 to_remove = mapping;
2534 is_installed = first;
2535 }
2536 else if (priority < mapping->priority)
2537 {
2538 break;
2539 }
2540 first = FALSE;
2541 }
2542 enumerator->destroy(enumerator);
2543 policy->used_by->remove(policy->used_by, to_remove, NULL);
2544 mapping = to_remove;
2545
2546 if (policy->used_by->get_count(policy->used_by) > 0)
2547 { /* policy is used by more SAs, keep in kernel */
2548 DBG2(DBG_KNL, "policy still used by another CHILD_SA, not removed");
2549 policy_sa_destroy(mapping, &direction, this);
2550
2551 if (!is_installed)
2552 { /* no need to update as the policy was not installed for this SA */
2553 this->mutex->unlock(this->mutex);
2554 return SUCCESS;
2555 }
2556
2557 DBG2(DBG_KNL, "updating policy %R === %R %N", src_ts, dst_ts,
2558 policy_dir_names, direction);
2559 policy->used_by->get_first(policy->used_by, (void**)&mapping);
2560 if (add_policy_internal(this, policy, mapping, TRUE) != SUCCESS)
2561 {
2562 DBG1(DBG_KNL, "unable to update policy %R === %R %N",
2563 src_ts, dst_ts, policy_dir_names, direction);
2564 return FAILED;
2565 }
2566 return SUCCESS;
2567 }
2568
2569 memset(&request, 0, sizeof(request));
2570
2571 msg = (struct sadb_msg*)request;
2572 msg->sadb_msg_version = PF_KEY_V2;
2573 msg->sadb_msg_type = SADB_X_SPDDELETE;
2574 msg->sadb_msg_satype = 0;
2575 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2576
2577 pol = (struct sadb_x_policy*)PFKEY_EXT_ADD_NEXT(msg);
2578 pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2579 pol->sadb_x_policy_len = PFKEY_LEN(sizeof(struct sadb_x_policy));
2580 pol->sadb_x_policy_dir = dir2kernel(direction);
2581 pol->sadb_x_policy_type = type2kernel(mapping->type);
2582 PFKEY_EXT_ADD(msg, pol);
2583
2584 add_addr_ext(msg, policy->src.net, SADB_EXT_ADDRESS_SRC, policy->src.proto,
2585 policy->src.mask, TRUE);
2586 add_addr_ext(msg, policy->dst.net, SADB_EXT_ADDRESS_DST, policy->dst.proto,
2587 policy->dst.mask, TRUE);
2588
2589 if (policy->route)
2590 {
2591 route_entry_t *route = policy->route;
2592 if (hydra->kernel_interface->del_route(hydra->kernel_interface,
2593 route->dst_net, route->prefixlen, route->gateway,
2594 route->src_ip, route->if_name) != SUCCESS)
2595 {
2596 DBG1(DBG_KNL, "error uninstalling route installed with "
2597 "policy %R === %R %N", src_ts, dst_ts,
2598 policy_dir_names, direction);
2599 }
2600 remove_exclude_route(this, route);
2601 }
2602
2603 this->policies->remove(this->policies, found, NULL);
2604 policy_sa_destroy(mapping, &direction, this);
2605 policy_entry_destroy(policy, this);
2606 this->mutex->unlock(this->mutex);
2607
2608 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2609 {
2610 DBG1(DBG_KNL, "unable to delete policy %R === %R %N", src_ts, dst_ts,
2611 policy_dir_names, direction);
2612 return FAILED;
2613 }
2614 else if (out->sadb_msg_errno)
2615 {
2616 DBG1(DBG_KNL, "unable to delete policy %R === %R %N: %s (%d)", src_ts,
2617 dst_ts, policy_dir_names, direction,
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 METHOD(kernel_ipsec_t, flush_policies, status_t,
2627 private_kernel_pfkey_ipsec_t *this)
2628 {
2629 unsigned char request[PFKEY_BUFFER_SIZE];
2630 struct sadb_msg *msg, *out;
2631 size_t len;
2632
2633 memset(&request, 0, sizeof(request));
2634
2635 DBG2(DBG_KNL, "flushing all policies from SPD");
2636
2637 msg = (struct sadb_msg*)request;
2638 msg->sadb_msg_version = PF_KEY_V2;
2639 msg->sadb_msg_type = SADB_X_SPDFLUSH;
2640 msg->sadb_msg_satype = SADB_SATYPE_UNSPEC;
2641 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2642
2643 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2644 {
2645 DBG1(DBG_KNL, "unable to flush SPD entries");
2646 return FAILED;
2647 }
2648 else if (out->sadb_msg_errno)
2649 {
2650 DBG1(DBG_KNL, "unable to flush SPD entries: %s (%d)",
2651 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2652 free(out);
2653 return FAILED;
2654 }
2655 free(out);
2656 return SUCCESS;
2657 }
2658
2659 /**
2660 * Register a socket for ACQUIRE/EXPIRE messages
2661 */
2662 static status_t register_pfkey_socket(private_kernel_pfkey_ipsec_t *this,
2663 u_int8_t satype)
2664 {
2665 unsigned char request[PFKEY_BUFFER_SIZE];
2666 struct sadb_msg *msg, *out;
2667 size_t len;
2668
2669 memset(&request, 0, sizeof(request));
2670
2671 msg = (struct sadb_msg*)request;
2672 msg->sadb_msg_version = PF_KEY_V2;
2673 msg->sadb_msg_type = SADB_REGISTER;
2674 msg->sadb_msg_satype = satype;
2675 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2676
2677 if (pfkey_send_socket(this, this->socket_events, msg, &out, &len) != SUCCESS)
2678 {
2679 DBG1(DBG_KNL, "unable to register PF_KEY socket");
2680 return FAILED;
2681 }
2682 else if (out->sadb_msg_errno)
2683 {
2684 DBG1(DBG_KNL, "unable to register PF_KEY socket: %s (%d)",
2685 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2686 free(out);
2687 return FAILED;
2688 }
2689 free(out);
2690 return SUCCESS;
2691 }
2692
2693 METHOD(kernel_ipsec_t, bypass_socket, bool,
2694 private_kernel_pfkey_ipsec_t *this, int fd, int family)
2695 {
2696 struct sadb_x_policy policy;
2697 u_int sol, ipsec_policy;
2698
2699 switch (family)
2700 {
2701 case AF_INET:
2702 {
2703 sol = SOL_IP;
2704 ipsec_policy = IP_IPSEC_POLICY;
2705 break;
2706 }
2707 case AF_INET6:
2708 {
2709 sol = SOL_IPV6;
2710 ipsec_policy = IPV6_IPSEC_POLICY;
2711 break;
2712 }
2713 default:
2714 return FALSE;
2715 }
2716
2717 memset(&policy, 0, sizeof(policy));
2718 policy.sadb_x_policy_len = sizeof(policy) / sizeof(u_int64_t);
2719 policy.sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2720 policy.sadb_x_policy_type = IPSEC_POLICY_BYPASS;
2721
2722 policy.sadb_x_policy_dir = IPSEC_DIR_OUTBOUND;
2723 if (setsockopt(fd, sol, ipsec_policy, &policy, sizeof(policy)) < 0)
2724 {
2725 DBG1(DBG_KNL, "unable to set IPSEC_POLICY on socket: %s",
2726 strerror(errno));
2727 return FALSE;
2728 }
2729 policy.sadb_x_policy_dir = IPSEC_DIR_INBOUND;
2730 if (setsockopt(fd, sol, ipsec_policy, &policy, sizeof(policy)) < 0)
2731 {
2732 DBG1(DBG_KNL, "unable to set IPSEC_POLICY on socket: %s",
2733 strerror(errno));
2734 return FALSE;
2735 }
2736 return TRUE;
2737 }
2738
2739 METHOD(kernel_ipsec_t, enable_udp_decap, bool,
2740 private_kernel_pfkey_ipsec_t *this, int fd, int family, u_int16_t port)
2741 {
2742 #ifndef __APPLE__
2743 int type = UDP_ENCAP_ESPINUDP;
2744
2745 if (setsockopt(fd, SOL_UDP, UDP_ENCAP, &type, sizeof(type)) < 0)
2746 {
2747 DBG1(DBG_KNL, "unable to set UDP_ENCAP: %s", strerror(errno));
2748 return FALSE;
2749 }
2750 #else /* __APPLE__ */
2751 int intport = port;
2752
2753 if (sysctlbyname("net.inet.ipsec.esp_port", NULL, NULL, &intport,
2754 sizeof(intport)) != 0)
2755 {
2756 DBG1(DBG_KNL, "could not set net.inet.ipsec.esp_port to %d: %s",
2757 port, strerror(errno));
2758 return FALSE;
2759 }
2760 #endif /* __APPLE__ */
2761
2762 return TRUE;
2763 }
2764
2765 METHOD(kernel_ipsec_t, destroy, void,
2766 private_kernel_pfkey_ipsec_t *this)
2767 {
2768 if (this->socket > 0)
2769 {
2770 close(this->socket);
2771 }
2772 if (this->socket_events > 0)
2773 {
2774 close(this->socket_events);
2775 }
2776 this->policies->invoke_function(this->policies,
2777 (linked_list_invoke_t)policy_entry_destroy,
2778 this);
2779 this->policies->destroy(this->policies);
2780 this->excludes->destroy(this->excludes);
2781 this->sas->destroy(this->sas);
2782 this->mutex->destroy(this->mutex);
2783 this->mutex_pfkey->destroy(this->mutex_pfkey);
2784 free(this);
2785 }
2786
2787 /*
2788 * Described in header.
2789 */
2790 kernel_pfkey_ipsec_t *kernel_pfkey_ipsec_create()
2791 {
2792 private_kernel_pfkey_ipsec_t *this;
2793 bool register_for_events = TRUE;
2794
2795 INIT(this,
2796 .public = {
2797 .interface = {
2798 .get_spi = _get_spi,
2799 .get_cpi = _get_cpi,
2800 .add_sa = _add_sa,
2801 .update_sa = _update_sa,
2802 .query_sa = _query_sa,
2803 .del_sa = _del_sa,
2804 .flush_sas = _flush_sas,
2805 .add_policy = _add_policy,
2806 .query_policy = _query_policy,
2807 .del_policy = _del_policy,
2808 .flush_policies = _flush_policies,
2809 .bypass_socket = _bypass_socket,
2810 .enable_udp_decap = _enable_udp_decap,
2811 .destroy = _destroy,
2812 },
2813 },
2814 .policies = linked_list_create(),
2815 .excludes = linked_list_create(),
2816 .sas = hashtable_create((hashtable_hash_t)ipsec_sa_hash,
2817 (hashtable_equals_t)ipsec_sa_equals, 32),
2818 .mutex = mutex_create(MUTEX_TYPE_DEFAULT),
2819 .mutex_pfkey = mutex_create(MUTEX_TYPE_DEFAULT),
2820 .install_routes = lib->settings->get_bool(lib->settings,
2821 "%s.install_routes", TRUE,
2822 hydra->daemon),
2823 );
2824
2825 if (streq(hydra->daemon, "starter"))
2826 { /* starter has no threads, so we do not register for kernel events */
2827 register_for_events = FALSE;
2828 }
2829
2830 /* create a PF_KEY socket to communicate with the kernel */
2831 this->socket = socket(PF_KEY, SOCK_RAW, PF_KEY_V2);
2832 if (this->socket <= 0)
2833 {
2834 DBG1(DBG_KNL, "unable to create PF_KEY socket");
2835 destroy(this);
2836 return NULL;
2837 }
2838
2839 if (register_for_events)
2840 {
2841 /* create a PF_KEY socket for ACQUIRE & EXPIRE */
2842 this->socket_events = socket(PF_KEY, SOCK_RAW, PF_KEY_V2);
2843 if (this->socket_events <= 0)
2844 {
2845 DBG1(DBG_KNL, "unable to create PF_KEY event socket");
2846 destroy(this);
2847 return NULL;
2848 }
2849
2850 /* register the event socket */
2851 if (register_pfkey_socket(this, SADB_SATYPE_ESP) != SUCCESS ||
2852 register_pfkey_socket(this, SADB_SATYPE_AH) != SUCCESS)
2853 {
2854 DBG1(DBG_KNL, "unable to register PF_KEY event socket");
2855 destroy(this);
2856 return NULL;
2857 }
2858
2859 lib->processor->queue_job(lib->processor,
2860 (job_t*)callback_job_create_with_prio(
2861 (callback_job_cb_t)receive_events, this, NULL,
2862 (callback_job_cancel_t)return_false, JOB_PRIO_CRITICAL));
2863 }
2864
2865 return &this->public;
2866 }