child-rekey: Uninstall old outbound SA earlier on initiator/winner
[strongswan.git] / src / libhydra / plugins / kernel_netlink / kernel_netlink_ipsec.c
1 /*
2 * Copyright (C) 2006-2012 Tobias Brunner
3 * Copyright (C) 2005-2009 Martin Willi
4 * Copyright (C) 2008 Andreas Steffen
5 * Copyright (C) 2006-2007 Fabian Hartmann, Noah Heusser
6 * Copyright (C) 2006 Daniel Roethlisberger
7 * Copyright (C) 2005 Jan Hutter
8 * Hochschule fuer Technik Rapperswil
9 *
10 * This program is free software; you can redistribute it and/or modify it
11 * under the terms of the GNU General Public License as published by the
12 * Free Software Foundation; either version 2 of the License, or (at your
13 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
14 *
15 * This program is distributed in the hope that it will be useful, but
16 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
18 * for more details.
19 */
20
21 #include <sys/types.h>
22 #include <sys/socket.h>
23 #include <stdint.h>
24 #include <linux/ipsec.h>
25 #include <linux/netlink.h>
26 #include <linux/rtnetlink.h>
27 #include <linux/xfrm.h>
28 #include <linux/udp.h>
29 #include <unistd.h>
30 #include <time.h>
31 #include <errno.h>
32 #include <string.h>
33 #include <fcntl.h>
34
35 #include "kernel_netlink_ipsec.h"
36 #include "kernel_netlink_shared.h"
37
38 #include <hydra.h>
39 #include <utils/debug.h>
40 #include <threading/mutex.h>
41 #include <collections/hashtable.h>
42 #include <collections/linked_list.h>
43
44 /** Required for Linux 2.6.26 kernel and later */
45 #ifndef XFRM_STATE_AF_UNSPEC
46 #define XFRM_STATE_AF_UNSPEC 32
47 #endif
48
49 /** From linux/in.h */
50 #ifndef IP_XFRM_POLICY
51 #define IP_XFRM_POLICY 17
52 #endif
53
54 /** Missing on uclibc */
55 #ifndef IPV6_XFRM_POLICY
56 #define IPV6_XFRM_POLICY 34
57 #endif /*IPV6_XFRM_POLICY*/
58
59 /* from linux/udp.h */
60 #ifndef UDP_ENCAP
61 #define UDP_ENCAP 100
62 #endif
63
64 #ifndef UDP_ENCAP_ESPINUDP
65 #define UDP_ENCAP_ESPINUDP 2
66 #endif
67
68 /* this is not defined on some platforms */
69 #ifndef SOL_UDP
70 #define SOL_UDP IPPROTO_UDP
71 #endif
72
73 /** Default priority of installed policies */
74 #define PRIO_BASE 512
75
76 /** Default replay window size, if not set using charon.replay_window */
77 #define DEFAULT_REPLAY_WINDOW 32
78
79 /**
80 * Map the limit for bytes and packets to XFRM_INF by default
81 */
82 #define XFRM_LIMIT(x) ((x) == 0 ? XFRM_INF : (x))
83
84 /**
85 * Create ORable bitfield of XFRM NL groups
86 */
87 #define XFRMNLGRP(x) (1<<(XFRMNLGRP_##x-1))
88
89 /**
90 * Returns a pointer to the first rtattr following the nlmsghdr *nlh and the
91 * 'usual' netlink data x like 'struct xfrm_usersa_info'
92 */
93 #define XFRM_RTA(nlh, x) ((struct rtattr*)(NLMSG_DATA(nlh) + \
94 NLMSG_ALIGN(sizeof(x))))
95 /**
96 * Returns the total size of attached rta data
97 * (after 'usual' netlink data x like 'struct xfrm_usersa_info')
98 */
99 #define XFRM_PAYLOAD(nlh, x) NLMSG_PAYLOAD(nlh, sizeof(x))
100
101 typedef struct kernel_algorithm_t kernel_algorithm_t;
102
103 /**
104 * Mapping of IKEv2 kernel identifier to linux crypto API names
105 */
106 struct kernel_algorithm_t {
107 /**
108 * Identifier specified in IKEv2
109 */
110 int ikev2;
111
112 /**
113 * Name of the algorithm in linux crypto API
114 */
115 char *name;
116 };
117
118 ENUM(xfrm_msg_names, XFRM_MSG_NEWSA, XFRM_MSG_MAPPING,
119 "XFRM_MSG_NEWSA",
120 "XFRM_MSG_DELSA",
121 "XFRM_MSG_GETSA",
122 "XFRM_MSG_NEWPOLICY",
123 "XFRM_MSG_DELPOLICY",
124 "XFRM_MSG_GETPOLICY",
125 "XFRM_MSG_ALLOCSPI",
126 "XFRM_MSG_ACQUIRE",
127 "XFRM_MSG_EXPIRE",
128 "XFRM_MSG_UPDPOLICY",
129 "XFRM_MSG_UPDSA",
130 "XFRM_MSG_POLEXPIRE",
131 "XFRM_MSG_FLUSHSA",
132 "XFRM_MSG_FLUSHPOLICY",
133 "XFRM_MSG_NEWAE",
134 "XFRM_MSG_GETAE",
135 "XFRM_MSG_REPORT",
136 "XFRM_MSG_MIGRATE",
137 "XFRM_MSG_NEWSADINFO",
138 "XFRM_MSG_GETSADINFO",
139 "XFRM_MSG_NEWSPDINFO",
140 "XFRM_MSG_GETSPDINFO",
141 "XFRM_MSG_MAPPING"
142 );
143
144 ENUM(xfrm_attr_type_names, XFRMA_UNSPEC, XFRMA_REPLAY_ESN_VAL,
145 "XFRMA_UNSPEC",
146 "XFRMA_ALG_AUTH",
147 "XFRMA_ALG_CRYPT",
148 "XFRMA_ALG_COMP",
149 "XFRMA_ENCAP",
150 "XFRMA_TMPL",
151 "XFRMA_SA",
152 "XFRMA_POLICY",
153 "XFRMA_SEC_CTX",
154 "XFRMA_LTIME_VAL",
155 "XFRMA_REPLAY_VAL",
156 "XFRMA_REPLAY_THRESH",
157 "XFRMA_ETIMER_THRESH",
158 "XFRMA_SRCADDR",
159 "XFRMA_COADDR",
160 "XFRMA_LASTUSED",
161 "XFRMA_POLICY_TYPE",
162 "XFRMA_MIGRATE",
163 "XFRMA_ALG_AEAD",
164 "XFRMA_KMADDRESS",
165 "XFRMA_ALG_AUTH_TRUNC",
166 "XFRMA_MARK",
167 "XFRMA_TFCPAD",
168 "XFRMA_REPLAY_ESN_VAL",
169 );
170
171 /**
172 * Algorithms for encryption
173 */
174 static kernel_algorithm_t encryption_algs[] = {
175 /* {ENCR_DES_IV64, "***" }, */
176 {ENCR_DES, "des" },
177 {ENCR_3DES, "des3_ede" },
178 /* {ENCR_RC5, "***" }, */
179 /* {ENCR_IDEA, "***" }, */
180 {ENCR_CAST, "cast128" },
181 {ENCR_BLOWFISH, "blowfish" },
182 /* {ENCR_3IDEA, "***" }, */
183 /* {ENCR_DES_IV32, "***" }, */
184 {ENCR_NULL, "cipher_null" },
185 {ENCR_AES_CBC, "aes" },
186 {ENCR_AES_CTR, "rfc3686(ctr(aes))" },
187 {ENCR_AES_CCM_ICV8, "rfc4309(ccm(aes))" },
188 {ENCR_AES_CCM_ICV12, "rfc4309(ccm(aes))" },
189 {ENCR_AES_CCM_ICV16, "rfc4309(ccm(aes))" },
190 {ENCR_AES_GCM_ICV8, "rfc4106(gcm(aes))" },
191 {ENCR_AES_GCM_ICV12, "rfc4106(gcm(aes))" },
192 {ENCR_AES_GCM_ICV16, "rfc4106(gcm(aes))" },
193 {ENCR_NULL_AUTH_AES_GMAC, "rfc4543(gcm(aes))" },
194 {ENCR_CAMELLIA_CBC, "cbc(camellia)" },
195 /* {ENCR_CAMELLIA_CTR, "***" }, */
196 /* {ENCR_CAMELLIA_CCM_ICV8, "***" }, */
197 /* {ENCR_CAMELLIA_CCM_ICV12, "***" }, */
198 /* {ENCR_CAMELLIA_CCM_ICV16, "***" }, */
199 {ENCR_SERPENT_CBC, "serpent" },
200 {ENCR_TWOFISH_CBC, "twofish" },
201 };
202
203 /**
204 * Algorithms for integrity protection
205 */
206 static kernel_algorithm_t integrity_algs[] = {
207 {AUTH_HMAC_MD5_96, "md5" },
208 {AUTH_HMAC_MD5_128, "hmac(md5)" },
209 {AUTH_HMAC_SHA1_96, "sha1" },
210 {AUTH_HMAC_SHA1_160, "hmac(sha1)" },
211 {AUTH_HMAC_SHA2_256_96, "sha256" },
212 {AUTH_HMAC_SHA2_256_128, "hmac(sha256)" },
213 {AUTH_HMAC_SHA2_384_192, "hmac(sha384)" },
214 {AUTH_HMAC_SHA2_512_256, "hmac(sha512)" },
215 /* {AUTH_DES_MAC, "***" }, */
216 /* {AUTH_KPDK_MD5, "***" }, */
217 {AUTH_AES_XCBC_96, "xcbc(aes)" },
218 };
219
220 /**
221 * Algorithms for IPComp
222 */
223 static kernel_algorithm_t compression_algs[] = {
224 /* {IPCOMP_OUI, "***" }, */
225 {IPCOMP_DEFLATE, "deflate" },
226 {IPCOMP_LZS, "lzs" },
227 {IPCOMP_LZJH, "lzjh" },
228 };
229
230 /**
231 * Look up a kernel algorithm name and its key size
232 */
233 static char* lookup_algorithm(transform_type_t type, int ikev2)
234 {
235 kernel_algorithm_t *list;
236 int i, count;
237 char *name;
238
239 switch (type)
240 {
241 case ENCRYPTION_ALGORITHM:
242 list = encryption_algs;
243 count = countof(encryption_algs);
244 break;
245 case INTEGRITY_ALGORITHM:
246 list = integrity_algs;
247 count = countof(integrity_algs);
248 break;
249 case COMPRESSION_ALGORITHM:
250 list = compression_algs;
251 count = countof(compression_algs);
252 break;
253 default:
254 return NULL;
255 }
256 for (i = 0; i < count; i++)
257 {
258 if (list[i].ikev2 == ikev2)
259 {
260 return list[i].name;
261 }
262 }
263 if (hydra->kernel_interface->lookup_algorithm(hydra->kernel_interface,
264 ikev2, type, NULL, &name))
265 {
266 return name;
267 }
268 return NULL;
269 }
270
271 typedef struct private_kernel_netlink_ipsec_t private_kernel_netlink_ipsec_t;
272
273 /**
274 * Private variables and functions of kernel_netlink class.
275 */
276 struct private_kernel_netlink_ipsec_t {
277 /**
278 * Public part of the kernel_netlink_t object
279 */
280 kernel_netlink_ipsec_t public;
281
282 /**
283 * Mutex to lock access to installed policies
284 */
285 mutex_t *mutex;
286
287 /**
288 * Hash table of installed policies (policy_entry_t)
289 */
290 hashtable_t *policies;
291
292 /**
293 * Hash table of IPsec SAs using policies (ipsec_sa_t)
294 */
295 hashtable_t *sas;
296
297 /**
298 * Netlink xfrm socket (IPsec)
299 */
300 netlink_socket_t *socket_xfrm;
301
302 /**
303 * Netlink xfrm socket to receive acquire and expire events
304 */
305 int socket_xfrm_events;
306
307 /**
308 * Whether to install routes along policies
309 */
310 bool install_routes;
311
312 /**
313 * Whether to track the history of a policy
314 */
315 bool policy_history;
316
317 /**
318 * Size of the replay window, in packets (= bits)
319 */
320 u_int32_t replay_window;
321
322 /**
323 * Size of the replay window bitmap, in number of __u32 blocks
324 */
325 u_int32_t replay_bmp;
326 };
327
328 typedef struct route_entry_t route_entry_t;
329
330 /**
331 * Installed routing entry
332 */
333 struct route_entry_t {
334 /** Name of the interface the route is bound to */
335 char *if_name;
336
337 /** Source ip of the route */
338 host_t *src_ip;
339
340 /** Gateway for this route */
341 host_t *gateway;
342
343 /** Destination net */
344 chunk_t dst_net;
345
346 /** Destination net prefixlen */
347 u_int8_t prefixlen;
348 };
349
350 /**
351 * Destroy a route_entry_t object
352 */
353 static void route_entry_destroy(route_entry_t *this)
354 {
355 free(this->if_name);
356 this->src_ip->destroy(this->src_ip);
357 DESTROY_IF(this->gateway);
358 chunk_free(&this->dst_net);
359 free(this);
360 }
361
362 /**
363 * Compare two route_entry_t objects
364 */
365 static bool route_entry_equals(route_entry_t *a, route_entry_t *b)
366 {
367 return a->if_name && b->if_name && streq(a->if_name, b->if_name) &&
368 a->src_ip->ip_equals(a->src_ip, b->src_ip) &&
369 a->gateway->ip_equals(a->gateway, b->gateway) &&
370 chunk_equals(a->dst_net, b->dst_net) && a->prefixlen == b->prefixlen;
371 }
372
373 typedef struct ipsec_sa_t ipsec_sa_t;
374
375 /**
376 * IPsec SA assigned to a policy.
377 */
378 struct ipsec_sa_t {
379 /** Source address of this SA */
380 host_t *src;
381
382 /** Destination address of this SA */
383 host_t *dst;
384
385 /** Optional mark */
386 mark_t mark;
387
388 /** Description of this SA */
389 ipsec_sa_cfg_t cfg;
390
391 /** Reference count for this SA */
392 refcount_t refcount;
393 };
394
395 /**
396 * Hash function for ipsec_sa_t objects
397 */
398 static u_int ipsec_sa_hash(ipsec_sa_t *sa)
399 {
400 return chunk_hash_inc(sa->src->get_address(sa->src),
401 chunk_hash_inc(sa->dst->get_address(sa->dst),
402 chunk_hash_inc(chunk_from_thing(sa->mark),
403 chunk_hash(chunk_from_thing(sa->cfg)))));
404 }
405
406 /**
407 * Equality function for ipsec_sa_t objects
408 */
409 static bool ipsec_sa_equals(ipsec_sa_t *sa, ipsec_sa_t *other_sa)
410 {
411 return sa->src->ip_equals(sa->src, other_sa->src) &&
412 sa->dst->ip_equals(sa->dst, other_sa->dst) &&
413 memeq(&sa->mark, &other_sa->mark, sizeof(mark_t)) &&
414 memeq(&sa->cfg, &other_sa->cfg, sizeof(ipsec_sa_cfg_t));
415 }
416
417 /**
418 * Allocate or reference an IPsec SA object
419 */
420 static ipsec_sa_t *ipsec_sa_create(private_kernel_netlink_ipsec_t *this,
421 host_t *src, host_t *dst, mark_t mark,
422 ipsec_sa_cfg_t *cfg)
423 {
424 ipsec_sa_t *sa, *found;
425 INIT(sa,
426 .src = src,
427 .dst = dst,
428 .mark = mark,
429 .cfg = *cfg,
430 );
431 found = this->sas->get(this->sas, sa);
432 if (!found)
433 {
434 sa->src = src->clone(src);
435 sa->dst = dst->clone(dst);
436 this->sas->put(this->sas, sa, sa);
437 }
438 else
439 {
440 free(sa);
441 sa = found;
442 }
443 ref_get(&sa->refcount);
444 return sa;
445 }
446
447 /**
448 * Release and destroy an IPsec SA object
449 */
450 static void ipsec_sa_destroy(private_kernel_netlink_ipsec_t *this,
451 ipsec_sa_t *sa)
452 {
453 if (ref_put(&sa->refcount))
454 {
455 this->sas->remove(this->sas, sa);
456 DESTROY_IF(sa->src);
457 DESTROY_IF(sa->dst);
458 free(sa);
459 }
460 }
461
462 typedef struct policy_sa_t policy_sa_t;
463 typedef struct policy_sa_fwd_t policy_sa_fwd_t;
464
465 /**
466 * Mapping between a policy and an IPsec SA.
467 */
468 struct policy_sa_t {
469 /** Priority assigned to the policy when installed with this SA */
470 u_int32_t priority;
471
472 /** Type of the policy */
473 policy_type_t type;
474
475 /** Assigned SA */
476 ipsec_sa_t *sa;
477 };
478
479 /**
480 * For forward policies we also cache the traffic selectors in order to install
481 * the route.
482 */
483 struct policy_sa_fwd_t {
484 /** Generic interface */
485 policy_sa_t generic;
486
487 /** Source traffic selector of this policy */
488 traffic_selector_t *src_ts;
489
490 /** Destination traffic selector of this policy */
491 traffic_selector_t *dst_ts;
492 };
493
494 /**
495 * Create a policy_sa(_fwd)_t object
496 */
497 static policy_sa_t *policy_sa_create(private_kernel_netlink_ipsec_t *this,
498 policy_dir_t dir, policy_type_t type, host_t *src, host_t *dst,
499 traffic_selector_t *src_ts, traffic_selector_t *dst_ts, mark_t mark,
500 ipsec_sa_cfg_t *cfg)
501 {
502 policy_sa_t *policy;
503
504 if (dir == POLICY_FWD)
505 {
506 policy_sa_fwd_t *fwd;
507 INIT(fwd,
508 .src_ts = src_ts->clone(src_ts),
509 .dst_ts = dst_ts->clone(dst_ts),
510 );
511 policy = &fwd->generic;
512 }
513 else
514 {
515 INIT(policy, .priority = 0);
516 }
517 policy->type = type;
518 policy->sa = ipsec_sa_create(this, src, dst, mark, cfg);
519 return policy;
520 }
521
522 /**
523 * Destroy a policy_sa(_fwd)_t object
524 */
525 static void policy_sa_destroy(policy_sa_t *policy, policy_dir_t *dir,
526 private_kernel_netlink_ipsec_t *this)
527 {
528 if (*dir == POLICY_FWD)
529 {
530 policy_sa_fwd_t *fwd = (policy_sa_fwd_t*)policy;
531 fwd->src_ts->destroy(fwd->src_ts);
532 fwd->dst_ts->destroy(fwd->dst_ts);
533 }
534 ipsec_sa_destroy(this, policy->sa);
535 free(policy);
536 }
537
538 typedef struct policy_entry_t policy_entry_t;
539
540 /**
541 * Installed kernel policy.
542 */
543 struct policy_entry_t {
544
545 /** Direction of this policy: in, out, forward */
546 u_int8_t direction;
547
548 /** Parameters of installed policy */
549 struct xfrm_selector sel;
550
551 /** Optional mark */
552 u_int32_t mark;
553
554 /** Associated route installed for this policy */
555 route_entry_t *route;
556
557 /** List of SAs this policy is used by, ordered by priority */
558 linked_list_t *used_by;
559
560 /** reqid for this policy */
561 u_int32_t reqid;
562 };
563
564 /**
565 * Destroy a policy_entry_t object
566 */
567 static void policy_entry_destroy(private_kernel_netlink_ipsec_t *this,
568 policy_entry_t *policy)
569 {
570 if (policy->route)
571 {
572 route_entry_destroy(policy->route);
573 }
574 if (policy->used_by)
575 {
576 policy->used_by->invoke_function(policy->used_by,
577 (linked_list_invoke_t)policy_sa_destroy,
578 &policy->direction, this);
579 policy->used_by->destroy(policy->used_by);
580 }
581 free(policy);
582 }
583
584 /**
585 * Hash function for policy_entry_t objects
586 */
587 static u_int policy_hash(policy_entry_t *key)
588 {
589 chunk_t chunk = chunk_from_thing(key->sel);
590 return chunk_hash_inc(chunk, chunk_hash(chunk_from_thing(key->mark)));
591 }
592
593 /**
594 * Equality function for policy_entry_t objects
595 */
596 static bool policy_equals(policy_entry_t *key, policy_entry_t *other_key)
597 {
598 return memeq(&key->sel, &other_key->sel, sizeof(struct xfrm_selector)) &&
599 key->mark == other_key->mark &&
600 key->direction == other_key->direction;
601 }
602
603 /**
604 * Calculate the priority of a policy
605 */
606 static inline u_int32_t get_priority(policy_entry_t *policy,
607 policy_priority_t prio)
608 {
609 u_int32_t priority = PRIO_BASE;
610 switch (prio)
611 {
612 case POLICY_PRIORITY_FALLBACK:
613 priority <<= 1;
614 /* fall-through */
615 case POLICY_PRIORITY_ROUTED:
616 priority <<= 1;
617 /* fall-through */
618 case POLICY_PRIORITY_DEFAULT:
619 break;
620 }
621 /* calculate priority based on selector size, small size = high prio */
622 priority -= policy->sel.prefixlen_s;
623 priority -= policy->sel.prefixlen_d;
624 priority <<= 2; /* make some room for the two flags */
625 priority += policy->sel.sport_mask || policy->sel.dport_mask ? 0 : 2;
626 priority += policy->sel.proto ? 0 : 1;
627 return priority;
628 }
629
630 /**
631 * Convert the general ipsec mode to the one defined in xfrm.h
632 */
633 static u_int8_t mode2kernel(ipsec_mode_t mode)
634 {
635 switch (mode)
636 {
637 case MODE_TRANSPORT:
638 return XFRM_MODE_TRANSPORT;
639 case MODE_TUNNEL:
640 return XFRM_MODE_TUNNEL;
641 case MODE_BEET:
642 return XFRM_MODE_BEET;
643 default:
644 return mode;
645 }
646 }
647
648 /**
649 * Convert a host_t to a struct xfrm_address
650 */
651 static void host2xfrm(host_t *host, xfrm_address_t *xfrm)
652 {
653 chunk_t chunk = host->get_address(host);
654 memcpy(xfrm, chunk.ptr, min(chunk.len, sizeof(xfrm_address_t)));
655 }
656
657 /**
658 * Convert a struct xfrm_address to a host_t
659 */
660 static host_t* xfrm2host(int family, xfrm_address_t *xfrm, u_int16_t port)
661 {
662 chunk_t chunk;
663
664 switch (family)
665 {
666 case AF_INET:
667 chunk = chunk_create((u_char*)&xfrm->a4, sizeof(xfrm->a4));
668 break;
669 case AF_INET6:
670 chunk = chunk_create((u_char*)&xfrm->a6, sizeof(xfrm->a6));
671 break;
672 default:
673 return NULL;
674 }
675 return host_create_from_chunk(family, chunk, ntohs(port));
676 }
677
678 /**
679 * Convert a traffic selector address range to subnet and its mask.
680 */
681 static void ts2subnet(traffic_selector_t* ts,
682 xfrm_address_t *net, u_int8_t *mask)
683 {
684 host_t *net_host;
685 chunk_t net_chunk;
686
687 ts->to_subnet(ts, &net_host, mask);
688 net_chunk = net_host->get_address(net_host);
689 memcpy(net, net_chunk.ptr, net_chunk.len);
690 net_host->destroy(net_host);
691 }
692
693 /**
694 * Convert a traffic selector port range to port/portmask
695 */
696 static void ts2ports(traffic_selector_t* ts,
697 u_int16_t *port, u_int16_t *mask)
698 {
699 /* Linux does not seem to accept complex portmasks. Only
700 * any or a specific port is allowed. We set to any, if we have
701 * a port range, or to a specific, if we have one port only.
702 */
703 u_int16_t from, to;
704
705 from = ts->get_from_port(ts);
706 to = ts->get_to_port(ts);
707
708 if (from == to)
709 {
710 *port = htons(from);
711 *mask = ~0;
712 }
713 else
714 {
715 *port = 0;
716 *mask = 0;
717 }
718 }
719
720 /**
721 * Convert a pair of traffic_selectors to an xfrm_selector
722 */
723 static struct xfrm_selector ts2selector(traffic_selector_t *src,
724 traffic_selector_t *dst)
725 {
726 struct xfrm_selector sel;
727
728 memset(&sel, 0, sizeof(sel));
729 sel.family = (src->get_type(src) == TS_IPV4_ADDR_RANGE) ? AF_INET : AF_INET6;
730 /* src or dest proto may be "any" (0), use more restrictive one */
731 sel.proto = max(src->get_protocol(src), dst->get_protocol(dst));
732 ts2subnet(dst, &sel.daddr, &sel.prefixlen_d);
733 ts2subnet(src, &sel.saddr, &sel.prefixlen_s);
734 ts2ports(dst, &sel.dport, &sel.dport_mask);
735 ts2ports(src, &sel.sport, &sel.sport_mask);
736 sel.ifindex = 0;
737 sel.user = 0;
738
739 return sel;
740 }
741
742 /**
743 * Convert an xfrm_selector to a src|dst traffic_selector
744 */
745 static traffic_selector_t* selector2ts(struct xfrm_selector *sel, bool src)
746 {
747 u_char *addr;
748 u_int8_t prefixlen;
749 u_int16_t port = 0;
750 host_t *host = NULL;
751
752 if (src)
753 {
754 addr = (u_char*)&sel->saddr;
755 prefixlen = sel->prefixlen_s;
756 if (sel->sport_mask)
757 {
758 port = htons(sel->sport);
759 }
760 }
761 else
762 {
763 addr = (u_char*)&sel->daddr;
764 prefixlen = sel->prefixlen_d;
765 if (sel->dport_mask)
766 {
767 port = htons(sel->dport);
768 }
769 }
770
771 /* The Linux 2.6 kernel does not set the selector's family field,
772 * so as a kludge we additionally test the prefix length.
773 */
774 if (sel->family == AF_INET || sel->prefixlen_s == 32)
775 {
776 host = host_create_from_chunk(AF_INET, chunk_create(addr, 4), 0);
777 }
778 else if (sel->family == AF_INET6 || sel->prefixlen_s == 128)
779 {
780 host = host_create_from_chunk(AF_INET6, chunk_create(addr, 16), 0);
781 }
782
783 if (host)
784 {
785 return traffic_selector_create_from_subnet(host, prefixlen,
786 sel->proto, port, port ?: 65535);
787 }
788 return NULL;
789 }
790
791 /**
792 * Process a XFRM_MSG_ACQUIRE from kernel
793 */
794 static void process_acquire(private_kernel_netlink_ipsec_t *this,
795 struct nlmsghdr *hdr)
796 {
797 struct xfrm_user_acquire *acquire;
798 struct rtattr *rta;
799 size_t rtasize;
800 traffic_selector_t *src_ts, *dst_ts;
801 u_int32_t reqid = 0;
802 int proto = 0;
803
804 acquire = (struct xfrm_user_acquire*)NLMSG_DATA(hdr);
805 rta = XFRM_RTA(hdr, struct xfrm_user_acquire);
806 rtasize = XFRM_PAYLOAD(hdr, struct xfrm_user_acquire);
807
808 DBG2(DBG_KNL, "received a XFRM_MSG_ACQUIRE");
809
810 while (RTA_OK(rta, rtasize))
811 {
812 DBG2(DBG_KNL, " %N", xfrm_attr_type_names, rta->rta_type);
813
814 if (rta->rta_type == XFRMA_TMPL)
815 {
816 struct xfrm_user_tmpl* tmpl;
817 tmpl = (struct xfrm_user_tmpl*)RTA_DATA(rta);
818 reqid = tmpl->reqid;
819 proto = tmpl->id.proto;
820 }
821 rta = RTA_NEXT(rta, rtasize);
822 }
823 switch (proto)
824 {
825 case 0:
826 case IPPROTO_ESP:
827 case IPPROTO_AH:
828 break;
829 default:
830 /* acquire for AH/ESP only, not for IPCOMP */
831 return;
832 }
833 src_ts = selector2ts(&acquire->sel, TRUE);
834 dst_ts = selector2ts(&acquire->sel, FALSE);
835
836 hydra->kernel_interface->acquire(hydra->kernel_interface, reqid, src_ts,
837 dst_ts);
838 }
839
840 /**
841 * Process a XFRM_MSG_EXPIRE from kernel
842 */
843 static void process_expire(private_kernel_netlink_ipsec_t *this,
844 struct nlmsghdr *hdr)
845 {
846 struct xfrm_user_expire *expire;
847 u_int32_t spi, reqid;
848 u_int8_t protocol;
849
850 expire = (struct xfrm_user_expire*)NLMSG_DATA(hdr);
851 protocol = expire->state.id.proto;
852 spi = expire->state.id.spi;
853 reqid = expire->state.reqid;
854
855 DBG2(DBG_KNL, "received a XFRM_MSG_EXPIRE");
856
857 if (protocol != IPPROTO_ESP && protocol != IPPROTO_AH)
858 {
859 DBG2(DBG_KNL, "ignoring XFRM_MSG_EXPIRE for SA with SPI %.8x and "
860 "reqid {%u} which is not a CHILD_SA", ntohl(spi), reqid);
861 return;
862 }
863
864 hydra->kernel_interface->expire(hydra->kernel_interface, reqid, protocol,
865 spi, expire->hard != 0);
866 }
867
868 /**
869 * Process a XFRM_MSG_MIGRATE from kernel
870 */
871 static void process_migrate(private_kernel_netlink_ipsec_t *this,
872 struct nlmsghdr *hdr)
873 {
874 struct xfrm_userpolicy_id *policy_id;
875 struct rtattr *rta;
876 size_t rtasize;
877 traffic_selector_t *src_ts, *dst_ts;
878 host_t *local = NULL, *remote = NULL;
879 host_t *old_src = NULL, *old_dst = NULL;
880 host_t *new_src = NULL, *new_dst = NULL;
881 u_int32_t reqid = 0;
882 policy_dir_t dir;
883
884 policy_id = (struct xfrm_userpolicy_id*)NLMSG_DATA(hdr);
885 rta = XFRM_RTA(hdr, struct xfrm_userpolicy_id);
886 rtasize = XFRM_PAYLOAD(hdr, struct xfrm_userpolicy_id);
887
888 DBG2(DBG_KNL, "received a XFRM_MSG_MIGRATE");
889
890 src_ts = selector2ts(&policy_id->sel, TRUE);
891 dst_ts = selector2ts(&policy_id->sel, FALSE);
892 dir = (policy_dir_t)policy_id->dir;
893
894 DBG2(DBG_KNL, " policy: %R === %R %N", src_ts, dst_ts, policy_dir_names);
895
896 while (RTA_OK(rta, rtasize))
897 {
898 DBG2(DBG_KNL, " %N", xfrm_attr_type_names, rta->rta_type);
899 if (rta->rta_type == XFRMA_KMADDRESS)
900 {
901 struct xfrm_user_kmaddress *kmaddress;
902
903 kmaddress = (struct xfrm_user_kmaddress*)RTA_DATA(rta);
904 local = xfrm2host(kmaddress->family, &kmaddress->local, 0);
905 remote = xfrm2host(kmaddress->family, &kmaddress->remote, 0);
906 DBG2(DBG_KNL, " kmaddress: %H...%H", local, remote);
907 }
908 else if (rta->rta_type == XFRMA_MIGRATE)
909 {
910 struct xfrm_user_migrate *migrate;
911
912 migrate = (struct xfrm_user_migrate*)RTA_DATA(rta);
913 old_src = xfrm2host(migrate->old_family, &migrate->old_saddr, 0);
914 old_dst = xfrm2host(migrate->old_family, &migrate->old_daddr, 0);
915 new_src = xfrm2host(migrate->new_family, &migrate->new_saddr, 0);
916 new_dst = xfrm2host(migrate->new_family, &migrate->new_daddr, 0);
917 reqid = migrate->reqid;
918 DBG2(DBG_KNL, " migrate %H...%H to %H...%H, reqid {%u}",
919 old_src, old_dst, new_src, new_dst, reqid);
920 DESTROY_IF(old_src);
921 DESTROY_IF(old_dst);
922 DESTROY_IF(new_src);
923 DESTROY_IF(new_dst);
924 }
925 rta = RTA_NEXT(rta, rtasize);
926 }
927
928 if (src_ts && dst_ts && local && remote)
929 {
930 hydra->kernel_interface->migrate(hydra->kernel_interface, reqid,
931 src_ts, dst_ts, dir, local, remote);
932 }
933 else
934 {
935 DESTROY_IF(src_ts);
936 DESTROY_IF(dst_ts);
937 DESTROY_IF(local);
938 DESTROY_IF(remote);
939 }
940 }
941
942 /**
943 * Process a XFRM_MSG_MAPPING from kernel
944 */
945 static void process_mapping(private_kernel_netlink_ipsec_t *this,
946 struct nlmsghdr *hdr)
947 {
948 struct xfrm_user_mapping *mapping;
949 u_int32_t spi, reqid;
950
951 mapping = (struct xfrm_user_mapping*)NLMSG_DATA(hdr);
952 spi = mapping->id.spi;
953 reqid = mapping->reqid;
954
955 DBG2(DBG_KNL, "received a XFRM_MSG_MAPPING");
956
957 if (mapping->id.proto == IPPROTO_ESP)
958 {
959 host_t *host;
960 host = xfrm2host(mapping->id.family, &mapping->new_saddr,
961 mapping->new_sport);
962 if (host)
963 {
964 hydra->kernel_interface->mapping(hydra->kernel_interface, reqid,
965 spi, host);
966 }
967 }
968 }
969
970 /**
971 * Receives events from kernel
972 */
973 static bool receive_events(private_kernel_netlink_ipsec_t *this, int fd,
974 watcher_event_t event)
975 {
976 char response[1024];
977 struct nlmsghdr *hdr = (struct nlmsghdr*)response;
978 struct sockaddr_nl addr;
979 socklen_t addr_len = sizeof(addr);
980 int len;
981
982 len = recvfrom(this->socket_xfrm_events, response, sizeof(response),
983 MSG_DONTWAIT, (struct sockaddr*)&addr, &addr_len);
984 if (len < 0)
985 {
986 switch (errno)
987 {
988 case EINTR:
989 /* interrupted, try again */
990 return TRUE;
991 case EAGAIN:
992 /* no data ready, select again */
993 return TRUE;
994 default:
995 DBG1(DBG_KNL, "unable to receive from xfrm event socket");
996 sleep(1);
997 return TRUE;
998 }
999 }
1000
1001 if (addr.nl_pid != 0)
1002 { /* not from kernel. not interested, try another one */
1003 return TRUE;
1004 }
1005
1006 while (NLMSG_OK(hdr, len))
1007 {
1008 switch (hdr->nlmsg_type)
1009 {
1010 case XFRM_MSG_ACQUIRE:
1011 process_acquire(this, hdr);
1012 break;
1013 case XFRM_MSG_EXPIRE:
1014 process_expire(this, hdr);
1015 break;
1016 case XFRM_MSG_MIGRATE:
1017 process_migrate(this, hdr);
1018 break;
1019 case XFRM_MSG_MAPPING:
1020 process_mapping(this, hdr);
1021 break;
1022 default:
1023 DBG1(DBG_KNL, "received unknown event from xfrm event "
1024 "socket: %d", hdr->nlmsg_type);
1025 break;
1026 }
1027 hdr = NLMSG_NEXT(hdr, len);
1028 }
1029 return TRUE;
1030 }
1031
1032 METHOD(kernel_ipsec_t, get_features, kernel_feature_t,
1033 private_kernel_netlink_ipsec_t *this)
1034 {
1035 return KERNEL_ESP_V3_TFC;
1036 }
1037
1038 /**
1039 * Get an SPI for a specific protocol from the kernel.
1040 */
1041 static status_t get_spi_internal(private_kernel_netlink_ipsec_t *this,
1042 host_t *src, host_t *dst, u_int8_t proto, u_int32_t min, u_int32_t max,
1043 u_int32_t reqid, u_int32_t *spi)
1044 {
1045 netlink_buf_t request;
1046 struct nlmsghdr *hdr, *out;
1047 struct xfrm_userspi_info *userspi;
1048 u_int32_t received_spi = 0;
1049 size_t len;
1050
1051 memset(&request, 0, sizeof(request));
1052
1053 hdr = (struct nlmsghdr*)request;
1054 hdr->nlmsg_flags = NLM_F_REQUEST;
1055 hdr->nlmsg_type = XFRM_MSG_ALLOCSPI;
1056 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userspi_info));
1057
1058 userspi = (struct xfrm_userspi_info*)NLMSG_DATA(hdr);
1059 host2xfrm(src, &userspi->info.saddr);
1060 host2xfrm(dst, &userspi->info.id.daddr);
1061 userspi->info.id.proto = proto;
1062 userspi->info.mode = XFRM_MODE_TUNNEL;
1063 userspi->info.reqid = reqid;
1064 userspi->info.family = src->get_family(src);
1065 userspi->min = min;
1066 userspi->max = max;
1067
1068 if (this->socket_xfrm->send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
1069 {
1070 hdr = out;
1071 while (NLMSG_OK(hdr, len))
1072 {
1073 switch (hdr->nlmsg_type)
1074 {
1075 case XFRM_MSG_NEWSA:
1076 {
1077 struct xfrm_usersa_info* usersa = NLMSG_DATA(hdr);
1078 received_spi = usersa->id.spi;
1079 break;
1080 }
1081 case NLMSG_ERROR:
1082 {
1083 struct nlmsgerr *err = NLMSG_DATA(hdr);
1084 DBG1(DBG_KNL, "allocating SPI failed: %s (%d)",
1085 strerror(-err->error), -err->error);
1086 break;
1087 }
1088 default:
1089 hdr = NLMSG_NEXT(hdr, len);
1090 continue;
1091 case NLMSG_DONE:
1092 break;
1093 }
1094 break;
1095 }
1096 free(out);
1097 }
1098
1099 if (received_spi == 0)
1100 {
1101 return FAILED;
1102 }
1103
1104 *spi = received_spi;
1105 return SUCCESS;
1106 }
1107
1108 METHOD(kernel_ipsec_t, get_spi, status_t,
1109 private_kernel_netlink_ipsec_t *this, host_t *src, host_t *dst,
1110 u_int8_t protocol, u_int32_t reqid, u_int32_t *spi)
1111 {
1112 DBG2(DBG_KNL, "getting SPI for reqid {%u}", reqid);
1113
1114 if (get_spi_internal(this, src, dst, protocol,
1115 0xc0000000, 0xcFFFFFFF, reqid, spi) != SUCCESS)
1116 {
1117 DBG1(DBG_KNL, "unable to get SPI for reqid {%u}", reqid);
1118 return FAILED;
1119 }
1120
1121 DBG2(DBG_KNL, "got SPI %.8x for reqid {%u}", ntohl(*spi), reqid);
1122 return SUCCESS;
1123 }
1124
1125 METHOD(kernel_ipsec_t, get_cpi, status_t,
1126 private_kernel_netlink_ipsec_t *this, host_t *src, host_t *dst,
1127 u_int32_t reqid, u_int16_t *cpi)
1128 {
1129 u_int32_t received_spi = 0;
1130
1131 DBG2(DBG_KNL, "getting CPI for reqid {%u}", reqid);
1132
1133 if (get_spi_internal(this, src, dst, IPPROTO_COMP,
1134 0x100, 0xEFFF, reqid, &received_spi) != SUCCESS)
1135 {
1136 DBG1(DBG_KNL, "unable to get CPI for reqid {%u}", reqid);
1137 return FAILED;
1138 }
1139
1140 *cpi = htons((u_int16_t)ntohl(received_spi));
1141
1142 DBG2(DBG_KNL, "got CPI %.4x for reqid {%u}", ntohs(*cpi), reqid);
1143 return SUCCESS;
1144 }
1145
1146 /**
1147 * Add a XFRM mark to message if required
1148 */
1149 static bool add_mark(struct nlmsghdr *hdr, int buflen, mark_t mark)
1150 {
1151 if (mark.value)
1152 {
1153 struct xfrm_mark *xmrk;
1154
1155 xmrk = netlink_reserve(hdr, buflen, XFRMA_MARK, sizeof(*xmrk));
1156 if (!xmrk)
1157 {
1158 return FALSE;
1159 }
1160 xmrk->v = mark.value;
1161 xmrk->m = mark.mask;
1162 }
1163 return TRUE;
1164 }
1165
1166 METHOD(kernel_ipsec_t, add_sa, status_t,
1167 private_kernel_netlink_ipsec_t *this, host_t *src, host_t *dst,
1168 u_int32_t spi, u_int8_t protocol, u_int32_t reqid, mark_t mark,
1169 u_int32_t tfc, lifetime_cfg_t *lifetime, u_int16_t enc_alg, chunk_t enc_key,
1170 u_int16_t int_alg, chunk_t int_key, ipsec_mode_t mode, u_int16_t ipcomp,
1171 u_int16_t cpi, bool initiator, bool encap, bool esn, bool inbound,
1172 traffic_selector_t* src_ts, traffic_selector_t* dst_ts)
1173 {
1174 netlink_buf_t request;
1175 char *alg_name;
1176 struct nlmsghdr *hdr;
1177 struct xfrm_usersa_info *sa;
1178 u_int16_t icv_size = 64;
1179 status_t status = FAILED;
1180
1181 /* if IPComp is used, we install an additional IPComp SA. if the cpi is 0
1182 * we are in the recursive call below */
1183 if (ipcomp != IPCOMP_NONE && cpi != 0)
1184 {
1185 lifetime_cfg_t lft = {{0,0,0},{0,0,0},{0,0,0}};
1186 add_sa(this, src, dst, htonl(ntohs(cpi)), IPPROTO_COMP, reqid, mark,
1187 tfc, &lft, ENCR_UNDEFINED, chunk_empty, AUTH_UNDEFINED,
1188 chunk_empty, mode, ipcomp, 0, initiator, FALSE, FALSE, inbound,
1189 NULL, NULL);
1190 ipcomp = IPCOMP_NONE;
1191 /* use transport mode ESP SA, IPComp uses tunnel mode */
1192 mode = MODE_TRANSPORT;
1193 }
1194
1195 memset(&request, 0, sizeof(request));
1196
1197 DBG2(DBG_KNL, "adding SAD entry with SPI %.8x and reqid {%u} (mark "
1198 "%u/0x%08x)", ntohl(spi), reqid, mark.value, mark.mask);
1199
1200 hdr = (struct nlmsghdr*)request;
1201 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
1202 hdr->nlmsg_type = inbound ? XFRM_MSG_UPDSA : XFRM_MSG_NEWSA;
1203 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_info));
1204
1205 sa = (struct xfrm_usersa_info*)NLMSG_DATA(hdr);
1206 host2xfrm(src, &sa->saddr);
1207 host2xfrm(dst, &sa->id.daddr);
1208 sa->id.spi = spi;
1209 sa->id.proto = protocol;
1210 sa->family = src->get_family(src);
1211 sa->mode = mode2kernel(mode);
1212 switch (mode)
1213 {
1214 case MODE_TUNNEL:
1215 sa->flags |= XFRM_STATE_AF_UNSPEC;
1216 break;
1217 case MODE_BEET:
1218 case MODE_TRANSPORT:
1219 if(src_ts && dst_ts)
1220 {
1221 sa->sel = ts2selector(src_ts, dst_ts);
1222 /* don't install proto/port on SA. This would break
1223 * potential secondary SAs for the same address using a
1224 * different prot/port. */
1225 sa->sel.proto = 0;
1226 sa->sel.dport = sa->sel.dport_mask = 0;
1227 sa->sel.sport = sa->sel.sport_mask = 0;
1228 }
1229 break;
1230 default:
1231 break;
1232 }
1233
1234 sa->reqid = reqid;
1235 sa->lft.soft_byte_limit = XFRM_LIMIT(lifetime->bytes.rekey);
1236 sa->lft.hard_byte_limit = XFRM_LIMIT(lifetime->bytes.life);
1237 sa->lft.soft_packet_limit = XFRM_LIMIT(lifetime->packets.rekey);
1238 sa->lft.hard_packet_limit = XFRM_LIMIT(lifetime->packets.life);
1239 /* we use lifetimes since added, not since used */
1240 sa->lft.soft_add_expires_seconds = lifetime->time.rekey;
1241 sa->lft.hard_add_expires_seconds = lifetime->time.life;
1242 sa->lft.soft_use_expires_seconds = 0;
1243 sa->lft.hard_use_expires_seconds = 0;
1244
1245 switch (enc_alg)
1246 {
1247 case ENCR_UNDEFINED:
1248 /* no encryption */
1249 break;
1250 case ENCR_AES_CCM_ICV16:
1251 case ENCR_AES_GCM_ICV16:
1252 case ENCR_NULL_AUTH_AES_GMAC:
1253 case ENCR_CAMELLIA_CCM_ICV16:
1254 icv_size += 32;
1255 /* FALL */
1256 case ENCR_AES_CCM_ICV12:
1257 case ENCR_AES_GCM_ICV12:
1258 case ENCR_CAMELLIA_CCM_ICV12:
1259 icv_size += 32;
1260 /* FALL */
1261 case ENCR_AES_CCM_ICV8:
1262 case ENCR_AES_GCM_ICV8:
1263 case ENCR_CAMELLIA_CCM_ICV8:
1264 {
1265 struct xfrm_algo_aead *algo;
1266
1267 alg_name = lookup_algorithm(ENCRYPTION_ALGORITHM, enc_alg);
1268 if (alg_name == NULL)
1269 {
1270 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1271 encryption_algorithm_names, enc_alg);
1272 goto failed;
1273 }
1274 DBG2(DBG_KNL, " using encryption algorithm %N with key size %d",
1275 encryption_algorithm_names, enc_alg, enc_key.len * 8);
1276
1277 algo = netlink_reserve(hdr, sizeof(request), XFRMA_ALG_AEAD,
1278 sizeof(*algo) + enc_key.len);
1279 if (!algo)
1280 {
1281 goto failed;
1282 }
1283 algo->alg_key_len = enc_key.len * 8;
1284 algo->alg_icv_len = icv_size;
1285 strncpy(algo->alg_name, alg_name, sizeof(algo->alg_name));
1286 algo->alg_name[sizeof(algo->alg_name) - 1] = '\0';
1287 memcpy(algo->alg_key, enc_key.ptr, enc_key.len);
1288 break;
1289 }
1290 default:
1291 {
1292 struct xfrm_algo *algo;
1293
1294 alg_name = lookup_algorithm(ENCRYPTION_ALGORITHM, enc_alg);
1295 if (alg_name == NULL)
1296 {
1297 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1298 encryption_algorithm_names, enc_alg);
1299 goto failed;
1300 }
1301 DBG2(DBG_KNL, " using encryption algorithm %N with key size %d",
1302 encryption_algorithm_names, enc_alg, enc_key.len * 8);
1303
1304 algo = netlink_reserve(hdr, sizeof(request), XFRMA_ALG_CRYPT,
1305 sizeof(*algo) + enc_key.len);
1306 if (!algo)
1307 {
1308 goto failed;
1309 }
1310 algo->alg_key_len = enc_key.len * 8;
1311 strncpy(algo->alg_name, alg_name, sizeof(algo->alg_name));
1312 algo->alg_name[sizeof(algo->alg_name) - 1] = '\0';
1313 memcpy(algo->alg_key, enc_key.ptr, enc_key.len);
1314 }
1315 }
1316
1317 if (int_alg != AUTH_UNDEFINED)
1318 {
1319 u_int trunc_len = 0;
1320
1321 alg_name = lookup_algorithm(INTEGRITY_ALGORITHM, int_alg);
1322 if (alg_name == NULL)
1323 {
1324 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1325 integrity_algorithm_names, int_alg);
1326 goto failed;
1327 }
1328 DBG2(DBG_KNL, " using integrity algorithm %N with key size %d",
1329 integrity_algorithm_names, int_alg, int_key.len * 8);
1330
1331 switch (int_alg)
1332 {
1333 case AUTH_HMAC_MD5_128:
1334 case AUTH_HMAC_SHA2_256_128:
1335 trunc_len = 128;
1336 break;
1337 case AUTH_HMAC_SHA1_160:
1338 trunc_len = 160;
1339 break;
1340 default:
1341 break;
1342 }
1343
1344 if (trunc_len)
1345 {
1346 struct xfrm_algo_auth* algo;
1347
1348 /* the kernel uses SHA256 with 96 bit truncation by default,
1349 * use specified truncation size supported by newer kernels.
1350 * also use this for untruncated MD5 and SHA1. */
1351 algo = netlink_reserve(hdr, sizeof(request), XFRMA_ALG_AUTH_TRUNC,
1352 sizeof(*algo) + int_key.len);
1353 if (!algo)
1354 {
1355 goto failed;
1356 }
1357 algo->alg_key_len = int_key.len * 8;
1358 algo->alg_trunc_len = trunc_len;
1359 strncpy(algo->alg_name, alg_name, sizeof(algo->alg_name));
1360 algo->alg_name[sizeof(algo->alg_name) - 1] = '\0';
1361 memcpy(algo->alg_key, int_key.ptr, int_key.len);
1362 }
1363 else
1364 {
1365 struct xfrm_algo* algo;
1366
1367 algo = netlink_reserve(hdr, sizeof(request), XFRMA_ALG_AUTH,
1368 sizeof(*algo) + int_key.len);
1369 if (!algo)
1370 {
1371 goto failed;
1372 }
1373 algo->alg_key_len = int_key.len * 8;
1374 strncpy(algo->alg_name, alg_name, sizeof(algo->alg_name));
1375 algo->alg_name[sizeof(algo->alg_name) - 1] = '\0';
1376 memcpy(algo->alg_key, int_key.ptr, int_key.len);
1377 }
1378 }
1379
1380 if (ipcomp != IPCOMP_NONE)
1381 {
1382 struct xfrm_algo* algo;
1383
1384 alg_name = lookup_algorithm(COMPRESSION_ALGORITHM, ipcomp);
1385 if (alg_name == NULL)
1386 {
1387 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1388 ipcomp_transform_names, ipcomp);
1389 goto failed;
1390 }
1391 DBG2(DBG_KNL, " using compression algorithm %N",
1392 ipcomp_transform_names, ipcomp);
1393
1394 algo = netlink_reserve(hdr, sizeof(request), XFRMA_ALG_COMP,
1395 sizeof(*algo));
1396 if (!algo)
1397 {
1398 goto failed;
1399 }
1400 algo->alg_key_len = 0;
1401 strncpy(algo->alg_name, alg_name, sizeof(algo->alg_name));
1402 algo->alg_name[sizeof(algo->alg_name) - 1] = '\0';
1403 }
1404
1405 if (encap)
1406 {
1407 struct xfrm_encap_tmpl *tmpl;
1408
1409 tmpl = netlink_reserve(hdr, sizeof(request), XFRMA_ENCAP, sizeof(*tmpl));
1410 if (!tmpl)
1411 {
1412 goto failed;
1413 }
1414 tmpl->encap_type = UDP_ENCAP_ESPINUDP;
1415 tmpl->encap_sport = htons(src->get_port(src));
1416 tmpl->encap_dport = htons(dst->get_port(dst));
1417 memset(&tmpl->encap_oa, 0, sizeof (xfrm_address_t));
1418 /* encap_oa could probably be derived from the
1419 * traffic selectors [rfc4306, p39]. In the netlink kernel
1420 * implementation pluto does the same as we do here but it uses
1421 * encap_oa in the pfkey implementation.
1422 * BUT as /usr/src/linux/net/key/af_key.c indicates the kernel ignores
1423 * it anyway
1424 * -> does that mean that NAT-T encap doesn't work in transport mode?
1425 * No. The reason the kernel ignores NAT-OA is that it recomputes
1426 * (or, rather, just ignores) the checksum. If packets pass the IPsec
1427 * checks it marks them "checksum ok" so OA isn't needed. */
1428 }
1429
1430 if (!add_mark(hdr, sizeof(request), mark))
1431 {
1432 goto failed;
1433 }
1434
1435 if (tfc)
1436 {
1437 u_int32_t *tfcpad;
1438
1439 tfcpad = netlink_reserve(hdr, sizeof(request), XFRMA_TFCPAD,
1440 sizeof(*tfcpad));
1441 if (!tfcpad)
1442 {
1443 goto failed;
1444 }
1445 *tfcpad = tfc;
1446 }
1447
1448 if (protocol != IPPROTO_COMP)
1449 {
1450 if (esn || this->replay_window > DEFAULT_REPLAY_WINDOW)
1451 {
1452 /* for ESN or larger replay windows we need the new
1453 * XFRMA_REPLAY_ESN_VAL attribute to configure a bitmap */
1454 struct xfrm_replay_state_esn *replay;
1455
1456 replay = netlink_reserve(hdr, sizeof(request), XFRMA_REPLAY_ESN_VAL,
1457 sizeof(*replay) + (this->replay_window + 7) / 8);
1458 if (!replay)
1459 {
1460 goto failed;
1461 }
1462 /* bmp_len contains number uf __u32's */
1463 replay->bmp_len = this->replay_bmp;
1464 replay->replay_window = this->replay_window;
1465 DBG2(DBG_KNL, " using replay window of %u packets",
1466 this->replay_window);
1467
1468 if (esn)
1469 {
1470 DBG2(DBG_KNL, " using extended sequence numbers (ESN)");
1471 sa->flags |= XFRM_STATE_ESN;
1472 }
1473 }
1474 else
1475 {
1476 DBG2(DBG_KNL, " using replay window of %u packets",
1477 this->replay_window);
1478 sa->replay_window = this->replay_window;
1479 }
1480 }
1481
1482 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
1483 {
1484 if (mark.value)
1485 {
1486 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x "
1487 "(mark %u/0x%08x)", ntohl(spi), mark.value, mark.mask);
1488 }
1489 else
1490 {
1491 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x", ntohl(spi));
1492 }
1493 goto failed;
1494 }
1495
1496 status = SUCCESS;
1497
1498 failed:
1499 memwipe(request, sizeof(request));
1500 return status;
1501 }
1502
1503 /**
1504 * Get the ESN replay state (i.e. sequence numbers) of an SA.
1505 *
1506 * Allocates into one the replay state structure we get from the kernel.
1507 */
1508 static void get_replay_state(private_kernel_netlink_ipsec_t *this,
1509 u_int32_t spi, u_int8_t protocol,
1510 host_t *dst, mark_t mark,
1511 struct xfrm_replay_state_esn **replay_esn,
1512 struct xfrm_replay_state **replay)
1513 {
1514 netlink_buf_t request;
1515 struct nlmsghdr *hdr, *out = NULL;
1516 struct xfrm_aevent_id *out_aevent = NULL, *aevent_id;
1517 size_t len;
1518 struct rtattr *rta;
1519 size_t rtasize;
1520
1521 memset(&request, 0, sizeof(request));
1522
1523 DBG2(DBG_KNL, "querying replay state from SAD entry with SPI %.8x",
1524 ntohl(spi));
1525
1526 hdr = (struct nlmsghdr*)request;
1527 hdr->nlmsg_flags = NLM_F_REQUEST;
1528 hdr->nlmsg_type = XFRM_MSG_GETAE;
1529 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_aevent_id));
1530
1531 aevent_id = (struct xfrm_aevent_id*)NLMSG_DATA(hdr);
1532 aevent_id->flags = XFRM_AE_RVAL;
1533
1534 host2xfrm(dst, &aevent_id->sa_id.daddr);
1535 aevent_id->sa_id.spi = spi;
1536 aevent_id->sa_id.proto = protocol;
1537 aevent_id->sa_id.family = dst->get_family(dst);
1538
1539 if (!add_mark(hdr, sizeof(request), mark))
1540 {
1541 return;
1542 }
1543
1544 if (this->socket_xfrm->send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
1545 {
1546 hdr = out;
1547 while (NLMSG_OK(hdr, len))
1548 {
1549 switch (hdr->nlmsg_type)
1550 {
1551 case XFRM_MSG_NEWAE:
1552 {
1553 out_aevent = NLMSG_DATA(hdr);
1554 break;
1555 }
1556 case NLMSG_ERROR:
1557 {
1558 struct nlmsgerr *err = NLMSG_DATA(hdr);
1559 DBG1(DBG_KNL, "querying replay state from SAD entry "
1560 "failed: %s (%d)", strerror(-err->error),
1561 -err->error);
1562 break;
1563 }
1564 default:
1565 hdr = NLMSG_NEXT(hdr, len);
1566 continue;
1567 case NLMSG_DONE:
1568 break;
1569 }
1570 break;
1571 }
1572 }
1573
1574 if (out_aevent)
1575 {
1576 rta = XFRM_RTA(out, struct xfrm_aevent_id);
1577 rtasize = XFRM_PAYLOAD(out, struct xfrm_aevent_id);
1578 while (RTA_OK(rta, rtasize))
1579 {
1580 if (rta->rta_type == XFRMA_REPLAY_VAL &&
1581 RTA_PAYLOAD(rta) == sizeof(**replay))
1582 {
1583 *replay = malloc(RTA_PAYLOAD(rta));
1584 memcpy(*replay, RTA_DATA(rta), RTA_PAYLOAD(rta));
1585 break;
1586 }
1587 if (rta->rta_type == XFRMA_REPLAY_ESN_VAL &&
1588 RTA_PAYLOAD(rta) >= sizeof(**replay_esn) + this->replay_bmp)
1589 {
1590 *replay_esn = malloc(RTA_PAYLOAD(rta));
1591 memcpy(*replay_esn, RTA_DATA(rta), RTA_PAYLOAD(rta));
1592 break;
1593 }
1594 rta = RTA_NEXT(rta, rtasize);
1595 }
1596 }
1597 free(out);
1598 }
1599
1600 METHOD(kernel_ipsec_t, query_sa, status_t,
1601 private_kernel_netlink_ipsec_t *this, host_t *src, host_t *dst,
1602 u_int32_t spi, u_int8_t protocol, mark_t mark,
1603 u_int64_t *bytes, u_int64_t *packets, u_int32_t *time)
1604 {
1605 netlink_buf_t request;
1606 struct nlmsghdr *out = NULL, *hdr;
1607 struct xfrm_usersa_id *sa_id;
1608 struct xfrm_usersa_info *sa = NULL;
1609 status_t status = FAILED;
1610 size_t len;
1611
1612 memset(&request, 0, sizeof(request));
1613
1614 DBG2(DBG_KNL, "querying SAD entry with SPI %.8x (mark %u/0x%08x)",
1615 ntohl(spi), mark.value, mark.mask);
1616
1617 hdr = (struct nlmsghdr*)request;
1618 hdr->nlmsg_flags = NLM_F_REQUEST;
1619 hdr->nlmsg_type = XFRM_MSG_GETSA;
1620 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_id));
1621
1622 sa_id = (struct xfrm_usersa_id*)NLMSG_DATA(hdr);
1623 host2xfrm(dst, &sa_id->daddr);
1624 sa_id->spi = spi;
1625 sa_id->proto = protocol;
1626 sa_id->family = dst->get_family(dst);
1627
1628 if (!add_mark(hdr, sizeof(request), mark))
1629 {
1630 return FAILED;
1631 }
1632
1633 if (this->socket_xfrm->send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
1634 {
1635 hdr = out;
1636 while (NLMSG_OK(hdr, len))
1637 {
1638 switch (hdr->nlmsg_type)
1639 {
1640 case XFRM_MSG_NEWSA:
1641 {
1642 sa = (struct xfrm_usersa_info*)NLMSG_DATA(hdr);
1643 break;
1644 }
1645 case NLMSG_ERROR:
1646 {
1647 struct nlmsgerr *err = NLMSG_DATA(hdr);
1648
1649 if (mark.value)
1650 {
1651 DBG1(DBG_KNL, "querying SAD entry with SPI %.8x "
1652 "(mark %u/0x%08x) failed: %s (%d)",
1653 ntohl(spi), mark.value, mark.mask,
1654 strerror(-err->error), -err->error);
1655 }
1656 else
1657 {
1658 DBG1(DBG_KNL, "querying SAD entry with SPI %.8x "
1659 "failed: %s (%d)", ntohl(spi),
1660 strerror(-err->error), -err->error);
1661 }
1662 break;
1663 }
1664 default:
1665 hdr = NLMSG_NEXT(hdr, len);
1666 continue;
1667 case NLMSG_DONE:
1668 break;
1669 }
1670 break;
1671 }
1672 }
1673
1674 if (sa == NULL)
1675 {
1676 DBG2(DBG_KNL, "unable to query SAD entry with SPI %.8x", ntohl(spi));
1677 }
1678 else
1679 {
1680 if (bytes)
1681 {
1682 *bytes = sa->curlft.bytes;
1683 }
1684 if (packets)
1685 {
1686 *packets = sa->curlft.packets;
1687 }
1688 if (time)
1689 { /* curlft contains an "use" time, but that contains a timestamp
1690 * of the first use, not the last. Last use time must be queried
1691 * on the policy on Linux */
1692 *time = 0;
1693 }
1694 status = SUCCESS;
1695 }
1696 memwipe(out, len);
1697 free(out);
1698 return status;
1699 }
1700
1701 METHOD(kernel_ipsec_t, del_sa, status_t,
1702 private_kernel_netlink_ipsec_t *this, host_t *src, host_t *dst,
1703 u_int32_t spi, u_int8_t protocol, u_int16_t cpi, mark_t mark)
1704 {
1705 netlink_buf_t request;
1706 struct nlmsghdr *hdr;
1707 struct xfrm_usersa_id *sa_id;
1708
1709 /* if IPComp was used, we first delete the additional IPComp SA */
1710 if (cpi)
1711 {
1712 del_sa(this, src, dst, htonl(ntohs(cpi)), IPPROTO_COMP, 0, mark);
1713 }
1714
1715 memset(&request, 0, sizeof(request));
1716
1717 DBG2(DBG_KNL, "deleting SAD entry with SPI %.8x (mark %u/0x%08x)",
1718 ntohl(spi), mark.value, mark.mask);
1719
1720 hdr = (struct nlmsghdr*)request;
1721 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
1722 hdr->nlmsg_type = XFRM_MSG_DELSA;
1723 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_id));
1724
1725 sa_id = (struct xfrm_usersa_id*)NLMSG_DATA(hdr);
1726 host2xfrm(dst, &sa_id->daddr);
1727 sa_id->spi = spi;
1728 sa_id->proto = protocol;
1729 sa_id->family = dst->get_family(dst);
1730
1731 if (!add_mark(hdr, sizeof(request), mark))
1732 {
1733 return FAILED;
1734 }
1735
1736 switch (this->socket_xfrm->send_ack(this->socket_xfrm, hdr))
1737 {
1738 case SUCCESS:
1739 DBG2(DBG_KNL, "deleted SAD entry with SPI %.8x (mark %u/0x%08x)",
1740 ntohl(spi), mark.value, mark.mask);
1741 return SUCCESS;
1742 case NOT_FOUND:
1743 return NOT_FOUND;
1744 default:
1745 if (mark.value)
1746 {
1747 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x "
1748 "(mark %u/0x%08x)", ntohl(spi), mark.value, mark.mask);
1749 }
1750 else
1751 {
1752 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x",
1753 ntohl(spi));
1754 }
1755 return FAILED;
1756 }
1757 }
1758
1759 METHOD(kernel_ipsec_t, update_sa, status_t,
1760 private_kernel_netlink_ipsec_t *this, u_int32_t spi, u_int8_t protocol,
1761 u_int16_t cpi, host_t *src, host_t *dst, host_t *new_src, host_t *new_dst,
1762 bool old_encap, bool new_encap, mark_t mark)
1763 {
1764 netlink_buf_t request;
1765 struct nlmsghdr *hdr, *out = NULL;
1766 struct xfrm_usersa_id *sa_id;
1767 struct xfrm_usersa_info *out_sa = NULL, *sa;
1768 size_t len;
1769 struct rtattr *rta;
1770 size_t rtasize;
1771 struct xfrm_encap_tmpl* tmpl = NULL;
1772 struct xfrm_replay_state *replay = NULL;
1773 struct xfrm_replay_state_esn *replay_esn = NULL;
1774 status_t status = FAILED;
1775
1776 /* if IPComp is used, we first update the IPComp SA */
1777 if (cpi)
1778 {
1779 update_sa(this, htonl(ntohs(cpi)), IPPROTO_COMP, 0,
1780 src, dst, new_src, new_dst, FALSE, FALSE, mark);
1781 }
1782
1783 memset(&request, 0, sizeof(request));
1784
1785 DBG2(DBG_KNL, "querying SAD entry with SPI %.8x for update", ntohl(spi));
1786
1787 /* query the existing SA first */
1788 hdr = (struct nlmsghdr*)request;
1789 hdr->nlmsg_flags = NLM_F_REQUEST;
1790 hdr->nlmsg_type = XFRM_MSG_GETSA;
1791 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_id));
1792
1793 sa_id = (struct xfrm_usersa_id*)NLMSG_DATA(hdr);
1794 host2xfrm(dst, &sa_id->daddr);
1795 sa_id->spi = spi;
1796 sa_id->proto = protocol;
1797 sa_id->family = dst->get_family(dst);
1798
1799 if (!add_mark(hdr, sizeof(request), mark))
1800 {
1801 return FAILED;
1802 }
1803
1804 if (this->socket_xfrm->send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
1805 {
1806 hdr = out;
1807 while (NLMSG_OK(hdr, len))
1808 {
1809 switch (hdr->nlmsg_type)
1810 {
1811 case XFRM_MSG_NEWSA:
1812 {
1813 out_sa = NLMSG_DATA(hdr);
1814 break;
1815 }
1816 case NLMSG_ERROR:
1817 {
1818 struct nlmsgerr *err = NLMSG_DATA(hdr);
1819 DBG1(DBG_KNL, "querying SAD entry failed: %s (%d)",
1820 strerror(-err->error), -err->error);
1821 break;
1822 }
1823 default:
1824 hdr = NLMSG_NEXT(hdr, len);
1825 continue;
1826 case NLMSG_DONE:
1827 break;
1828 }
1829 break;
1830 }
1831 }
1832 if (out_sa == NULL)
1833 {
1834 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x", ntohl(spi));
1835 goto failed;
1836 }
1837
1838 get_replay_state(this, spi, protocol, dst, mark, &replay_esn, &replay);
1839
1840 /* delete the old SA (without affecting the IPComp SA) */
1841 if (del_sa(this, src, dst, spi, protocol, 0, mark) != SUCCESS)
1842 {
1843 DBG1(DBG_KNL, "unable to delete old SAD entry with SPI %.8x",
1844 ntohl(spi));
1845 goto failed;
1846 }
1847
1848 DBG2(DBG_KNL, "updating SAD entry with SPI %.8x from %#H..%#H to %#H..%#H",
1849 ntohl(spi), src, dst, new_src, new_dst);
1850 /* copy over the SA from out to request */
1851 hdr = (struct nlmsghdr*)request;
1852 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
1853 hdr->nlmsg_type = XFRM_MSG_NEWSA;
1854 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_info));
1855 sa = NLMSG_DATA(hdr);
1856 memcpy(sa, NLMSG_DATA(out), sizeof(struct xfrm_usersa_info));
1857 sa->family = new_dst->get_family(new_dst);
1858
1859 if (!src->ip_equals(src, new_src))
1860 {
1861 host2xfrm(new_src, &sa->saddr);
1862 }
1863 if (!dst->ip_equals(dst, new_dst))
1864 {
1865 host2xfrm(new_dst, &sa->id.daddr);
1866 }
1867
1868 rta = XFRM_RTA(out, struct xfrm_usersa_info);
1869 rtasize = XFRM_PAYLOAD(out, struct xfrm_usersa_info);
1870 while (RTA_OK(rta, rtasize))
1871 {
1872 /* copy all attributes, but not XFRMA_ENCAP if we are disabling it */
1873 if (rta->rta_type != XFRMA_ENCAP || new_encap)
1874 {
1875 if (rta->rta_type == XFRMA_ENCAP)
1876 { /* update encap tmpl */
1877 tmpl = RTA_DATA(rta);
1878 tmpl->encap_sport = ntohs(new_src->get_port(new_src));
1879 tmpl->encap_dport = ntohs(new_dst->get_port(new_dst));
1880 }
1881 netlink_add_attribute(hdr, rta->rta_type,
1882 chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta)),
1883 sizeof(request));
1884 }
1885 rta = RTA_NEXT(rta, rtasize);
1886 }
1887
1888 if (tmpl == NULL && new_encap)
1889 { /* add tmpl if we are enabling it */
1890 tmpl = netlink_reserve(hdr, sizeof(request), XFRMA_ENCAP, sizeof(*tmpl));
1891 if (!tmpl)
1892 {
1893 goto failed;
1894 }
1895 tmpl->encap_type = UDP_ENCAP_ESPINUDP;
1896 tmpl->encap_sport = ntohs(new_src->get_port(new_src));
1897 tmpl->encap_dport = ntohs(new_dst->get_port(new_dst));
1898 memset(&tmpl->encap_oa, 0, sizeof (xfrm_address_t));
1899 }
1900
1901 if (replay_esn)
1902 {
1903 struct xfrm_replay_state_esn *state;
1904
1905 state = netlink_reserve(hdr, sizeof(request), XFRMA_REPLAY_ESN_VAL,
1906 sizeof(*state) + this->replay_bmp);
1907 if (!state)
1908 {
1909 goto failed;
1910 }
1911 memcpy(state, replay_esn, sizeof(*state) + this->replay_bmp);
1912 }
1913 else if (replay)
1914 {
1915 struct xfrm_replay_state *state;
1916
1917 state = netlink_reserve(hdr, sizeof(request), XFRMA_REPLAY_VAL,
1918 sizeof(*state));
1919 if (!state)
1920 {
1921 goto failed;
1922 }
1923 memcpy(state, replay, sizeof(*state));
1924 }
1925 else
1926 {
1927 DBG1(DBG_KNL, "unable to copy replay state from old SAD entry "
1928 "with SPI %.8x", ntohl(spi));
1929 }
1930
1931 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
1932 {
1933 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x", ntohl(spi));
1934 goto failed;
1935 }
1936
1937 status = SUCCESS;
1938 failed:
1939 free(replay);
1940 free(replay_esn);
1941 memwipe(out, len);
1942 memwipe(request, sizeof(request));
1943 free(out);
1944
1945 return status;
1946 }
1947
1948 METHOD(kernel_ipsec_t, flush_sas, status_t,
1949 private_kernel_netlink_ipsec_t *this)
1950 {
1951 netlink_buf_t request;
1952 struct nlmsghdr *hdr;
1953 struct xfrm_usersa_flush *flush;
1954
1955 memset(&request, 0, sizeof(request));
1956
1957 DBG2(DBG_KNL, "flushing all SAD entries");
1958
1959 hdr = (struct nlmsghdr*)request;
1960 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
1961 hdr->nlmsg_type = XFRM_MSG_FLUSHSA;
1962 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_flush));
1963
1964 flush = (struct xfrm_usersa_flush*)NLMSG_DATA(hdr);
1965 flush->proto = IPSEC_PROTO_ANY;
1966
1967 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
1968 {
1969 DBG1(DBG_KNL, "unable to flush SAD entries");
1970 return FAILED;
1971 }
1972 return SUCCESS;
1973 }
1974
1975 /**
1976 * Add or update a policy in the kernel.
1977 *
1978 * Note: The mutex has to be locked when entering this function
1979 * and is unlocked here in any case.
1980 */
1981 static status_t add_policy_internal(private_kernel_netlink_ipsec_t *this,
1982 policy_entry_t *policy, policy_sa_t *mapping, bool update)
1983 {
1984 netlink_buf_t request;
1985 policy_entry_t clone;
1986 ipsec_sa_t *ipsec = mapping->sa;
1987 struct xfrm_userpolicy_info *policy_info;
1988 struct nlmsghdr *hdr;
1989 int i;
1990
1991 /* clone the policy so we are able to check it out again later */
1992 memcpy(&clone, policy, sizeof(policy_entry_t));
1993
1994 memset(&request, 0, sizeof(request));
1995 hdr = (struct nlmsghdr*)request;
1996 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
1997 hdr->nlmsg_type = update ? XFRM_MSG_UPDPOLICY : XFRM_MSG_NEWPOLICY;
1998 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_info));
1999
2000 policy_info = (struct xfrm_userpolicy_info*)NLMSG_DATA(hdr);
2001 policy_info->sel = policy->sel;
2002 policy_info->dir = policy->direction;
2003
2004 /* calculate priority based on selector size, small size = high prio */
2005 policy_info->priority = mapping->priority;
2006 policy_info->action = mapping->type != POLICY_DROP ? XFRM_POLICY_ALLOW
2007 : XFRM_POLICY_BLOCK;
2008 policy_info->share = XFRM_SHARE_ANY;
2009
2010 /* policies don't expire */
2011 policy_info->lft.soft_byte_limit = XFRM_INF;
2012 policy_info->lft.soft_packet_limit = XFRM_INF;
2013 policy_info->lft.hard_byte_limit = XFRM_INF;
2014 policy_info->lft.hard_packet_limit = XFRM_INF;
2015 policy_info->lft.soft_add_expires_seconds = 0;
2016 policy_info->lft.hard_add_expires_seconds = 0;
2017 policy_info->lft.soft_use_expires_seconds = 0;
2018 policy_info->lft.hard_use_expires_seconds = 0;
2019
2020 if (mapping->type == POLICY_IPSEC)
2021 {
2022 struct xfrm_user_tmpl *tmpl;
2023 struct {
2024 u_int8_t proto;
2025 bool use;
2026 } protos[] = {
2027 { IPPROTO_COMP, ipsec->cfg.ipcomp.transform != IPCOMP_NONE },
2028 { IPPROTO_ESP, ipsec->cfg.esp.use },
2029 { IPPROTO_AH, ipsec->cfg.ah.use },
2030 };
2031 ipsec_mode_t proto_mode = ipsec->cfg.mode;
2032 int count = 0;
2033
2034 for (i = 0; i < countof(protos); i++)
2035 {
2036 if (protos[i].use)
2037 {
2038 count++;
2039 }
2040 }
2041 tmpl = netlink_reserve(hdr, sizeof(request), XFRMA_TMPL,
2042 count * sizeof(*tmpl));
2043 if (!tmpl)
2044 {
2045 this->mutex->unlock(this->mutex);
2046 return FAILED;
2047 }
2048
2049 for (i = 0; i < countof(protos); i++)
2050 {
2051 if (!protos[i].use)
2052 {
2053 continue;
2054 }
2055 tmpl->reqid = policy->reqid;
2056 tmpl->id.proto = protos[i].proto;
2057 tmpl->aalgos = tmpl->ealgos = tmpl->calgos = ~0;
2058 tmpl->mode = mode2kernel(proto_mode);
2059 tmpl->optional = protos[i].proto == IPPROTO_COMP &&
2060 policy->direction != POLICY_OUT;
2061 tmpl->family = ipsec->src->get_family(ipsec->src);
2062
2063 if (proto_mode == MODE_TUNNEL || proto_mode == MODE_BEET)
2064 { /* only for tunnel mode */
2065 host2xfrm(ipsec->src, &tmpl->saddr);
2066 host2xfrm(ipsec->dst, &tmpl->id.daddr);
2067 }
2068
2069 tmpl++;
2070
2071 /* use transport mode for other SAs */
2072 proto_mode = MODE_TRANSPORT;
2073 }
2074 }
2075
2076 if (!add_mark(hdr, sizeof(request), ipsec->mark))
2077 {
2078 this->mutex->unlock(this->mutex);
2079 return FAILED;
2080 }
2081 this->mutex->unlock(this->mutex);
2082
2083 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
2084 {
2085 return FAILED;
2086 }
2087
2088 /* find the policy again */
2089 this->mutex->lock(this->mutex);
2090 policy = this->policies->get(this->policies, &clone);
2091 if (!policy ||
2092 policy->used_by->find_first(policy->used_by,
2093 NULL, (void**)&mapping) != SUCCESS)
2094 { /* policy or mapping is already gone, ignore */
2095 this->mutex->unlock(this->mutex);
2096 return SUCCESS;
2097 }
2098
2099 /* install a route, if:
2100 * - this is a forward policy (to just get one for each child)
2101 * - we are in tunnel/BEET mode or install a bypass policy
2102 * - routing is not disabled via strongswan.conf
2103 */
2104 if (policy->direction == POLICY_FWD && this->install_routes &&
2105 (mapping->type != POLICY_IPSEC || ipsec->cfg.mode != MODE_TRANSPORT))
2106 {
2107 policy_sa_fwd_t *fwd = (policy_sa_fwd_t*)mapping;
2108 route_entry_t *route;
2109 host_t *iface;
2110
2111 INIT(route,
2112 .prefixlen = policy->sel.prefixlen_s,
2113 );
2114
2115 if (hydra->kernel_interface->get_address_by_ts(hydra->kernel_interface,
2116 fwd->dst_ts, &route->src_ip, NULL) == SUCCESS)
2117 {
2118 /* get the nexthop to src (src as we are in POLICY_FWD) */
2119 route->gateway = hydra->kernel_interface->get_nexthop(
2120 hydra->kernel_interface, ipsec->src,
2121 ipsec->dst);
2122 route->dst_net = chunk_alloc(policy->sel.family == AF_INET ? 4 : 16);
2123 memcpy(route->dst_net.ptr, &policy->sel.saddr, route->dst_net.len);
2124
2125 /* get the interface to install the route for. If we have a local
2126 * address, use it. Otherwise (for shunt policies) use the
2127 * routes source address. */
2128 iface = ipsec->dst;
2129 if (iface->is_anyaddr(iface))
2130 {
2131 iface = route->src_ip;
2132 }
2133 /* install route via outgoing interface */
2134 if (!hydra->kernel_interface->get_interface(hydra->kernel_interface,
2135 iface, &route->if_name))
2136 {
2137 this->mutex->unlock(this->mutex);
2138 route_entry_destroy(route);
2139 return SUCCESS;
2140 }
2141
2142 if (policy->route)
2143 {
2144 route_entry_t *old = policy->route;
2145 if (route_entry_equals(old, route))
2146 {
2147 this->mutex->unlock(this->mutex);
2148 route_entry_destroy(route);
2149 return SUCCESS;
2150 }
2151 /* uninstall previously installed route */
2152 if (hydra->kernel_interface->del_route(hydra->kernel_interface,
2153 old->dst_net, old->prefixlen, old->gateway,
2154 old->src_ip, old->if_name) != SUCCESS)
2155 {
2156 DBG1(DBG_KNL, "error uninstalling route installed with "
2157 "policy %R === %R %N", fwd->src_ts,
2158 fwd->dst_ts, policy_dir_names,
2159 policy->direction);
2160 }
2161 route_entry_destroy(old);
2162 policy->route = NULL;
2163 }
2164
2165 DBG2(DBG_KNL, "installing route: %R via %H src %H dev %s",
2166 fwd->src_ts, route->gateway, route->src_ip, route->if_name);
2167 switch (hydra->kernel_interface->add_route(
2168 hydra->kernel_interface, route->dst_net,
2169 route->prefixlen, route->gateway,
2170 route->src_ip, route->if_name))
2171 {
2172 default:
2173 DBG1(DBG_KNL, "unable to install source route for %H",
2174 route->src_ip);
2175 /* FALL */
2176 case ALREADY_DONE:
2177 /* route exists, do not uninstall */
2178 route_entry_destroy(route);
2179 break;
2180 case SUCCESS:
2181 /* cache the installed route */
2182 policy->route = route;
2183 break;
2184 }
2185 }
2186 else
2187 {
2188 free(route);
2189 }
2190 }
2191 this->mutex->unlock(this->mutex);
2192 return SUCCESS;
2193 }
2194
2195 METHOD(kernel_ipsec_t, add_policy, status_t,
2196 private_kernel_netlink_ipsec_t *this, host_t *src, host_t *dst,
2197 traffic_selector_t *src_ts, traffic_selector_t *dst_ts,
2198 policy_dir_t direction, policy_type_t type, ipsec_sa_cfg_t *sa,
2199 mark_t mark, policy_priority_t priority)
2200 {
2201 policy_entry_t *policy, *current;
2202 policy_sa_t *assigned_sa, *current_sa;
2203 enumerator_t *enumerator;
2204 bool found = FALSE, update = TRUE;
2205
2206 /* create a policy */
2207 INIT(policy,
2208 .sel = ts2selector(src_ts, dst_ts),
2209 .mark = mark.value & mark.mask,
2210 .direction = direction,
2211 .reqid = sa->reqid,
2212 );
2213
2214 /* find the policy, which matches EXACTLY */
2215 this->mutex->lock(this->mutex);
2216 current = this->policies->get(this->policies, policy);
2217 if (current)
2218 {
2219 if (current->reqid != sa->reqid)
2220 {
2221 DBG1(DBG_CFG, "unable to install policy %R === %R %N (mark "
2222 "%u/0x%08x) for reqid %u, the same policy for reqid %u exists",
2223 src_ts, dst_ts, policy_dir_names, direction,
2224 mark.value, mark.mask, sa->reqid, current->reqid);
2225 policy_entry_destroy(this, policy);
2226 this->mutex->unlock(this->mutex);
2227 return INVALID_STATE;
2228 }
2229 /* use existing policy */
2230 DBG2(DBG_KNL, "policy %R === %R %N (mark %u/0x%08x) "
2231 "already exists, increasing refcount",
2232 src_ts, dst_ts, policy_dir_names, direction,
2233 mark.value, mark.mask);
2234 policy_entry_destroy(this, policy);
2235 policy = current;
2236 found = TRUE;
2237 }
2238 else
2239 { /* use the new one, if we have no such policy */
2240 policy->used_by = linked_list_create();
2241 this->policies->put(this->policies, policy, policy);
2242 }
2243
2244 /* cache the assigned IPsec SA */
2245 assigned_sa = policy_sa_create(this, direction, type, src, dst, src_ts,
2246 dst_ts, mark, sa);
2247 assigned_sa->priority = get_priority(policy, priority);
2248
2249 if (this->policy_history)
2250 { /* insert the SA according to its priority */
2251 enumerator = policy->used_by->create_enumerator(policy->used_by);
2252 while (enumerator->enumerate(enumerator, (void**)&current_sa))
2253 {
2254 if (current_sa->priority >= assigned_sa->priority)
2255 {
2256 break;
2257 }
2258 update = FALSE;
2259 }
2260 policy->used_by->insert_before(policy->used_by, enumerator,
2261 assigned_sa);
2262 enumerator->destroy(enumerator);
2263 }
2264 else
2265 { /* simply insert it last and only update if it is not installed yet */
2266 policy->used_by->insert_last(policy->used_by, assigned_sa);
2267 update = !found;
2268 }
2269
2270 if (!update)
2271 { /* we don't update the policy if the priority is lower than that of
2272 * the currently installed one */
2273 this->mutex->unlock(this->mutex);
2274 return SUCCESS;
2275 }
2276
2277 DBG2(DBG_KNL, "%s policy %R === %R %N (mark %u/0x%08x)",
2278 found ? "updating" : "adding", src_ts, dst_ts,
2279 policy_dir_names, direction, mark.value, mark.mask);
2280
2281 if (add_policy_internal(this, policy, assigned_sa, found) != SUCCESS)
2282 {
2283 DBG1(DBG_KNL, "unable to %s policy %R === %R %N",
2284 found ? "update" : "add", src_ts, dst_ts,
2285 policy_dir_names, direction);
2286 return FAILED;
2287 }
2288 return SUCCESS;
2289 }
2290
2291 METHOD(kernel_ipsec_t, query_policy, status_t,
2292 private_kernel_netlink_ipsec_t *this, traffic_selector_t *src_ts,
2293 traffic_selector_t *dst_ts, policy_dir_t direction, mark_t mark,
2294 u_int32_t *use_time)
2295 {
2296 netlink_buf_t request;
2297 struct nlmsghdr *out = NULL, *hdr;
2298 struct xfrm_userpolicy_id *policy_id;
2299 struct xfrm_userpolicy_info *policy = NULL;
2300 size_t len;
2301
2302 memset(&request, 0, sizeof(request));
2303
2304 DBG2(DBG_KNL, "querying policy %R === %R %N (mark %u/0x%08x)",
2305 src_ts, dst_ts, policy_dir_names, direction,
2306 mark.value, mark.mask);
2307
2308 hdr = (struct nlmsghdr*)request;
2309 hdr->nlmsg_flags = NLM_F_REQUEST;
2310 hdr->nlmsg_type = XFRM_MSG_GETPOLICY;
2311 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_id));
2312
2313 policy_id = (struct xfrm_userpolicy_id*)NLMSG_DATA(hdr);
2314 policy_id->sel = ts2selector(src_ts, dst_ts);
2315 policy_id->dir = direction;
2316
2317 if (!add_mark(hdr, sizeof(request), mark))
2318 {
2319 return FAILED;
2320 }
2321
2322 if (this->socket_xfrm->send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
2323 {
2324 hdr = out;
2325 while (NLMSG_OK(hdr, len))
2326 {
2327 switch (hdr->nlmsg_type)
2328 {
2329 case XFRM_MSG_NEWPOLICY:
2330 {
2331 policy = (struct xfrm_userpolicy_info*)NLMSG_DATA(hdr);
2332 break;
2333 }
2334 case NLMSG_ERROR:
2335 {
2336 struct nlmsgerr *err = NLMSG_DATA(hdr);
2337 DBG1(DBG_KNL, "querying policy failed: %s (%d)",
2338 strerror(-err->error), -err->error);
2339 break;
2340 }
2341 default:
2342 hdr = NLMSG_NEXT(hdr, len);
2343 continue;
2344 case NLMSG_DONE:
2345 break;
2346 }
2347 break;
2348 }
2349 }
2350
2351 if (policy == NULL)
2352 {
2353 DBG2(DBG_KNL, "unable to query policy %R === %R %N", src_ts, dst_ts,
2354 policy_dir_names, direction);
2355 free(out);
2356 return FAILED;
2357 }
2358
2359 if (policy->curlft.use_time)
2360 {
2361 /* we need the monotonic time, but the kernel returns system time. */
2362 *use_time = time_monotonic(NULL) - (time(NULL) - policy->curlft.use_time);
2363 }
2364 else
2365 {
2366 *use_time = 0;
2367 }
2368
2369 free(out);
2370 return SUCCESS;
2371 }
2372
2373 METHOD(kernel_ipsec_t, del_policy, status_t,
2374 private_kernel_netlink_ipsec_t *this, traffic_selector_t *src_ts,
2375 traffic_selector_t *dst_ts, policy_dir_t direction, u_int32_t reqid,
2376 mark_t mark, policy_priority_t prio)
2377 {
2378 policy_entry_t *current, policy;
2379 enumerator_t *enumerator;
2380 policy_sa_t *mapping;
2381 netlink_buf_t request;
2382 struct nlmsghdr *hdr;
2383 struct xfrm_userpolicy_id *policy_id;
2384 bool is_installed = TRUE;
2385 u_int32_t priority;
2386
2387 DBG2(DBG_KNL, "deleting policy %R === %R %N (mark %u/0x%08x)",
2388 src_ts, dst_ts, policy_dir_names, direction,
2389 mark.value, mark.mask);
2390
2391 /* create a policy */
2392 memset(&policy, 0, sizeof(policy_entry_t));
2393 policy.sel = ts2selector(src_ts, dst_ts);
2394 policy.mark = mark.value & mark.mask;
2395 policy.direction = direction;
2396
2397 /* find the policy */
2398 this->mutex->lock(this->mutex);
2399 current = this->policies->get(this->policies, &policy);
2400 if (!current || current->reqid != reqid)
2401 {
2402 if (mark.value)
2403 {
2404 DBG1(DBG_KNL, "deleting policy %R === %R %N (mark %u/0x%08x) "
2405 "failed, not found", src_ts, dst_ts, policy_dir_names,
2406 direction, mark.value, mark.mask);
2407 }
2408 else
2409 {
2410 DBG1(DBG_KNL, "deleting policy %R === %R %N failed, not found",
2411 src_ts, dst_ts, policy_dir_names, direction);
2412 }
2413 this->mutex->unlock(this->mutex);
2414 return NOT_FOUND;
2415 }
2416
2417 if (this->policy_history)
2418 { /* remove mapping to SA by reqid and priority */
2419 priority = get_priority(current, prio);
2420 enumerator = current->used_by->create_enumerator(current->used_by);
2421 while (enumerator->enumerate(enumerator, (void**)&mapping))
2422 {
2423 if (priority == mapping->priority)
2424 {
2425 current->used_by->remove_at(current->used_by, enumerator);
2426 policy_sa_destroy(mapping, &direction, this);
2427 break;
2428 }
2429 is_installed = FALSE;
2430 }
2431 enumerator->destroy(enumerator);
2432 }
2433 else
2434 { /* remove one of the SAs but don't update the policy */
2435 current->used_by->remove_last(current->used_by, (void**)&mapping);
2436 policy_sa_destroy(mapping, &direction, this);
2437 is_installed = FALSE;
2438 }
2439
2440 if (current->used_by->get_count(current->used_by) > 0)
2441 { /* policy is used by more SAs, keep in kernel */
2442 DBG2(DBG_KNL, "policy still used by another CHILD_SA, not removed");
2443 if (!is_installed)
2444 { /* no need to update as the policy was not installed for this SA */
2445 this->mutex->unlock(this->mutex);
2446 return SUCCESS;
2447 }
2448
2449 DBG2(DBG_KNL, "updating policy %R === %R %N (mark %u/0x%08x)",
2450 src_ts, dst_ts, policy_dir_names, direction,
2451 mark.value, mark.mask);
2452
2453 current->used_by->get_first(current->used_by, (void**)&mapping);
2454 if (add_policy_internal(this, current, mapping, TRUE) != SUCCESS)
2455 {
2456 DBG1(DBG_KNL, "unable to update policy %R === %R %N",
2457 src_ts, dst_ts, policy_dir_names, direction);
2458 return FAILED;
2459 }
2460 return SUCCESS;
2461 }
2462
2463 memset(&request, 0, sizeof(request));
2464
2465 hdr = (struct nlmsghdr*)request;
2466 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2467 hdr->nlmsg_type = XFRM_MSG_DELPOLICY;
2468 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_id));
2469
2470 policy_id = (struct xfrm_userpolicy_id*)NLMSG_DATA(hdr);
2471 policy_id->sel = current->sel;
2472 policy_id->dir = direction;
2473
2474 if (!add_mark(hdr, sizeof(request), mark))
2475 {
2476 return FAILED;
2477 }
2478
2479 if (current->route)
2480 {
2481 route_entry_t *route = current->route;
2482 if (hydra->kernel_interface->del_route(hydra->kernel_interface,
2483 route->dst_net, route->prefixlen, route->gateway,
2484 route->src_ip, route->if_name) != SUCCESS)
2485 {
2486 DBG1(DBG_KNL, "error uninstalling route installed with "
2487 "policy %R === %R %N", src_ts, dst_ts,
2488 policy_dir_names, direction);
2489 }
2490 }
2491
2492 this->policies->remove(this->policies, current);
2493 policy_entry_destroy(this, current);
2494 this->mutex->unlock(this->mutex);
2495
2496 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
2497 {
2498 if (mark.value)
2499 {
2500 DBG1(DBG_KNL, "unable to delete policy %R === %R %N "
2501 "(mark %u/0x%08x)", src_ts, dst_ts, policy_dir_names,
2502 direction, mark.value, mark.mask);
2503 }
2504 else
2505 {
2506 DBG1(DBG_KNL, "unable to delete policy %R === %R %N",
2507 src_ts, dst_ts, policy_dir_names, direction);
2508 }
2509 return FAILED;
2510 }
2511 return SUCCESS;
2512 }
2513
2514 METHOD(kernel_ipsec_t, flush_policies, status_t,
2515 private_kernel_netlink_ipsec_t *this)
2516 {
2517 netlink_buf_t request;
2518 struct nlmsghdr *hdr;
2519
2520 memset(&request, 0, sizeof(request));
2521
2522 DBG2(DBG_KNL, "flushing all policies from SPD");
2523
2524 hdr = (struct nlmsghdr*)request;
2525 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2526 hdr->nlmsg_type = XFRM_MSG_FLUSHPOLICY;
2527 hdr->nlmsg_len = NLMSG_LENGTH(0); /* no data associated */
2528
2529 /* by adding an rtattr of type XFRMA_POLICY_TYPE we could restrict this
2530 * to main or sub policies (default is main) */
2531
2532 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
2533 {
2534 DBG1(DBG_KNL, "unable to flush SPD entries");
2535 return FAILED;
2536 }
2537 return SUCCESS;
2538 }
2539
2540
2541 METHOD(kernel_ipsec_t, bypass_socket, bool,
2542 private_kernel_netlink_ipsec_t *this, int fd, int family)
2543 {
2544 struct xfrm_userpolicy_info policy;
2545 u_int sol, ipsec_policy;
2546
2547 switch (family)
2548 {
2549 case AF_INET:
2550 sol = SOL_IP;
2551 ipsec_policy = IP_XFRM_POLICY;
2552 break;
2553 case AF_INET6:
2554 sol = SOL_IPV6;
2555 ipsec_policy = IPV6_XFRM_POLICY;
2556 break;
2557 default:
2558 return FALSE;
2559 }
2560
2561 memset(&policy, 0, sizeof(policy));
2562 policy.action = XFRM_POLICY_ALLOW;
2563 policy.sel.family = family;
2564
2565 policy.dir = XFRM_POLICY_OUT;
2566 if (setsockopt(fd, sol, ipsec_policy, &policy, sizeof(policy)) < 0)
2567 {
2568 DBG1(DBG_KNL, "unable to set IPSEC_POLICY on socket: %s",
2569 strerror(errno));
2570 return FALSE;
2571 }
2572 policy.dir = XFRM_POLICY_IN;
2573 if (setsockopt(fd, sol, ipsec_policy, &policy, sizeof(policy)) < 0)
2574 {
2575 DBG1(DBG_KNL, "unable to set IPSEC_POLICY on socket: %s",
2576 strerror(errno));
2577 return FALSE;
2578 }
2579 return TRUE;
2580 }
2581
2582 METHOD(kernel_ipsec_t, enable_udp_decap, bool,
2583 private_kernel_netlink_ipsec_t *this, int fd, int family, u_int16_t port)
2584 {
2585 int type = UDP_ENCAP_ESPINUDP;
2586
2587 if (setsockopt(fd, SOL_UDP, UDP_ENCAP, &type, sizeof(type)) < 0)
2588 {
2589 DBG1(DBG_KNL, "unable to set UDP_ENCAP: %s", strerror(errno));
2590 return FALSE;
2591 }
2592 return TRUE;
2593 }
2594
2595 METHOD(kernel_ipsec_t, destroy, void,
2596 private_kernel_netlink_ipsec_t *this)
2597 {
2598 enumerator_t *enumerator;
2599 policy_entry_t *policy;
2600
2601 if (this->socket_xfrm_events > 0)
2602 {
2603 lib->watcher->remove(lib->watcher, this->socket_xfrm_events);
2604 close(this->socket_xfrm_events);
2605 }
2606 DESTROY_IF(this->socket_xfrm);
2607 enumerator = this->policies->create_enumerator(this->policies);
2608 while (enumerator->enumerate(enumerator, &policy, &policy))
2609 {
2610 policy_entry_destroy(this, policy);
2611 }
2612 enumerator->destroy(enumerator);
2613 this->policies->destroy(this->policies);
2614 this->sas->destroy(this->sas);
2615 this->mutex->destroy(this->mutex);
2616 free(this);
2617 }
2618
2619 /*
2620 * Described in header.
2621 */
2622 kernel_netlink_ipsec_t *kernel_netlink_ipsec_create()
2623 {
2624 private_kernel_netlink_ipsec_t *this;
2625 bool register_for_events = TRUE;
2626 int fd;
2627
2628 INIT(this,
2629 .public = {
2630 .interface = {
2631 .get_features = _get_features,
2632 .get_spi = _get_spi,
2633 .get_cpi = _get_cpi,
2634 .add_sa = _add_sa,
2635 .update_sa = _update_sa,
2636 .query_sa = _query_sa,
2637 .del_sa = _del_sa,
2638 .flush_sas = _flush_sas,
2639 .add_policy = _add_policy,
2640 .query_policy = _query_policy,
2641 .del_policy = _del_policy,
2642 .flush_policies = _flush_policies,
2643 .bypass_socket = _bypass_socket,
2644 .enable_udp_decap = _enable_udp_decap,
2645 .destroy = _destroy,
2646 },
2647 },
2648 .policies = hashtable_create((hashtable_hash_t)policy_hash,
2649 (hashtable_equals_t)policy_equals, 32),
2650 .sas = hashtable_create((hashtable_hash_t)ipsec_sa_hash,
2651 (hashtable_equals_t)ipsec_sa_equals, 32),
2652 .mutex = mutex_create(MUTEX_TYPE_DEFAULT),
2653 .policy_history = TRUE,
2654 .install_routes = lib->settings->get_bool(lib->settings,
2655 "%s.install_routes", TRUE, hydra->daemon),
2656 .replay_window = lib->settings->get_int(lib->settings,
2657 "%s.replay_window", DEFAULT_REPLAY_WINDOW, hydra->daemon),
2658 );
2659
2660 this->replay_bmp = (this->replay_window + sizeof(u_int32_t) * 8 - 1) /
2661 (sizeof(u_int32_t) * 8);
2662
2663 if (streq(hydra->daemon, "starter"))
2664 { /* starter has no threads, so we do not register for kernel events */
2665 register_for_events = FALSE;
2666 }
2667
2668 /* disable lifetimes for allocated SPIs in kernel */
2669 fd = open("/proc/sys/net/core/xfrm_acq_expires", O_WRONLY);
2670 if (fd > 0)
2671 {
2672 ignore_result(write(fd, "165", 3));
2673 close(fd);
2674 }
2675
2676 this->socket_xfrm = netlink_socket_create(NETLINK_XFRM);
2677 if (!this->socket_xfrm)
2678 {
2679 destroy(this);
2680 return NULL;
2681 }
2682
2683 if (register_for_events)
2684 {
2685 struct sockaddr_nl addr;
2686
2687 memset(&addr, 0, sizeof(addr));
2688 addr.nl_family = AF_NETLINK;
2689
2690 /* create and bind XFRM socket for ACQUIRE, EXPIRE, MIGRATE & MAPPING */
2691 this->socket_xfrm_events = socket(AF_NETLINK, SOCK_RAW, NETLINK_XFRM);
2692 if (this->socket_xfrm_events <= 0)
2693 {
2694 DBG1(DBG_KNL, "unable to create XFRM event socket");
2695 destroy(this);
2696 return NULL;
2697 }
2698 addr.nl_groups = XFRMNLGRP(ACQUIRE) | XFRMNLGRP(EXPIRE) |
2699 XFRMNLGRP(MIGRATE) | XFRMNLGRP(MAPPING);
2700 if (bind(this->socket_xfrm_events, (struct sockaddr*)&addr, sizeof(addr)))
2701 {
2702 DBG1(DBG_KNL, "unable to bind XFRM event socket");
2703 destroy(this);
2704 return NULL;
2705 }
2706 lib->watcher->add(lib->watcher, this->socket_xfrm_events, WATCHER_READ,
2707 (watcher_cb_t)receive_events, this);
2708 }
2709
2710 return &this->public;
2711 }