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