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