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