9751933e36d94d78d5744d63498943c1f301e351
[strongswan.git] / src / libcharon / plugins / kernel_netlink / kernel_netlink_ipsec.c
1 /*
2 * Copyright (C) 2006-2018 Tobias Brunner
3 * Copyright (C) 2005-2009 Martin Willi
4 * Copyright (C) 2008-2016 Andreas Steffen
5 * Copyright (C) 2006-2007 Fabian Hartmann, Noah Heusser
6 * Copyright (C) 2006 Daniel Roethlisberger
7 * Copyright (C) 2005 Jan Hutter
8 * HSR 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 * Copyright (C) 2018 Mellanox Technologies.
22 *
23 * Permission is hereby granted, free of charge, to any person obtaining a copy
24 * of this software and associated documentation files (the "Software"), to deal
25 * in the Software without restriction, including without limitation the rights
26 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
27 * copies of the Software, and to permit persons to whom the Software is
28 * furnished to do so, subject to the following conditions:
29 *
30 * The above copyright notice and this permission notice shall be included in
31 * all copies or substantial portions of the Software.
32 *
33 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
34 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
35 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
36 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
37 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
38 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
39 * THE SOFTWARE.
40 */
41
42 #define _GNU_SOURCE
43 #include <sys/types.h>
44 #include <sys/socket.h>
45 #include <sys/ioctl.h>
46 #include <stdint.h>
47 #include <linux/ipsec.h>
48 #include <linux/netlink.h>
49 #include <linux/rtnetlink.h>
50 #include <linux/xfrm.h>
51 #include <linux/udp.h>
52 #include <linux/ethtool.h>
53 #include <linux/sockios.h>
54 #include <net/if.h>
55 #include <unistd.h>
56 #include <time.h>
57 #include <errno.h>
58 #include <string.h>
59 #include <fcntl.h>
60 #include <dlfcn.h>
61
62 #include "kernel_netlink_ipsec.h"
63 #include "kernel_netlink_shared.h"
64
65 #include <daemon.h>
66 #include <utils/debug.h>
67 #include <threading/mutex.h>
68 #include <threading/condvar.h>
69 #include <collections/array.h>
70 #include <collections/hashtable.h>
71 #include <collections/linked_list.h>
72
73 /** Required for Linux 2.6.26 kernel and later */
74 #ifndef XFRM_STATE_AF_UNSPEC
75 #define XFRM_STATE_AF_UNSPEC 32
76 #endif
77
78 /** From linux/in.h */
79 #ifndef IP_XFRM_POLICY
80 #define IP_XFRM_POLICY 17
81 #endif
82
83 /** Missing on uclibc */
84 #ifndef IPV6_XFRM_POLICY
85 #define IPV6_XFRM_POLICY 34
86 #endif /*IPV6_XFRM_POLICY*/
87
88 /* from linux/udp.h */
89 #ifndef UDP_ENCAP
90 #define UDP_ENCAP 100
91 #endif
92
93 #ifndef UDP_ENCAP_ESPINUDP
94 #define UDP_ENCAP_ESPINUDP 2
95 #endif
96
97 /* this is not defined on some platforms */
98 #ifndef SOL_UDP
99 #define SOL_UDP IPPROTO_UDP
100 #endif
101
102 /** Base priority for installed policies */
103 #define PRIO_BASE 200000
104
105 /**
106 * Map the limit for bytes and packets to XFRM_INF by default
107 */
108 #define XFRM_LIMIT(x) ((x) == 0 ? XFRM_INF : (x))
109
110 /**
111 * Create ORable bitfield of XFRM NL groups
112 */
113 #define XFRMNLGRP(x) (1<<(XFRMNLGRP_##x-1))
114
115 /**
116 * Returns a pointer to the first rtattr following the nlmsghdr *nlh and the
117 * 'usual' netlink data x like 'struct xfrm_usersa_info'
118 */
119 #define XFRM_RTA(nlh, x) ((struct rtattr*)(NLMSG_DATA(nlh) + \
120 NLMSG_ALIGN(sizeof(x))))
121 /**
122 * Returns the total size of attached rta data
123 * (after 'usual' netlink data x like 'struct xfrm_usersa_info')
124 */
125 #define XFRM_PAYLOAD(nlh, x) NLMSG_PAYLOAD(nlh, sizeof(x))
126
127 typedef struct kernel_algorithm_t kernel_algorithm_t;
128
129 /**
130 * Mapping of IKEv2 kernel identifier to linux crypto API names
131 */
132 struct kernel_algorithm_t {
133 /**
134 * Identifier specified in IKEv2
135 */
136 int ikev2;
137
138 /**
139 * Name of the algorithm in linux crypto API
140 */
141 const char *name;
142 };
143
144 ENUM(xfrm_msg_names, XFRM_MSG_NEWSA, XFRM_MSG_MAPPING,
145 "XFRM_MSG_NEWSA",
146 "XFRM_MSG_DELSA",
147 "XFRM_MSG_GETSA",
148 "XFRM_MSG_NEWPOLICY",
149 "XFRM_MSG_DELPOLICY",
150 "XFRM_MSG_GETPOLICY",
151 "XFRM_MSG_ALLOCSPI",
152 "XFRM_MSG_ACQUIRE",
153 "XFRM_MSG_EXPIRE",
154 "XFRM_MSG_UPDPOLICY",
155 "XFRM_MSG_UPDSA",
156 "XFRM_MSG_POLEXPIRE",
157 "XFRM_MSG_FLUSHSA",
158 "XFRM_MSG_FLUSHPOLICY",
159 "XFRM_MSG_NEWAE",
160 "XFRM_MSG_GETAE",
161 "XFRM_MSG_REPORT",
162 "XFRM_MSG_MIGRATE",
163 "XFRM_MSG_NEWSADINFO",
164 "XFRM_MSG_GETSADINFO",
165 "XFRM_MSG_NEWSPDINFO",
166 "XFRM_MSG_GETSPDINFO",
167 "XFRM_MSG_MAPPING"
168 );
169
170 ENUM(xfrm_attr_type_names, XFRMA_UNSPEC, XFRMA_OFFLOAD_DEV,
171 "XFRMA_UNSPEC",
172 "XFRMA_ALG_AUTH",
173 "XFRMA_ALG_CRYPT",
174 "XFRMA_ALG_COMP",
175 "XFRMA_ENCAP",
176 "XFRMA_TMPL",
177 "XFRMA_SA",
178 "XFRMA_POLICY",
179 "XFRMA_SEC_CTX",
180 "XFRMA_LTIME_VAL",
181 "XFRMA_REPLAY_VAL",
182 "XFRMA_REPLAY_THRESH",
183 "XFRMA_ETIMER_THRESH",
184 "XFRMA_SRCADDR",
185 "XFRMA_COADDR",
186 "XFRMA_LASTUSED",
187 "XFRMA_POLICY_TYPE",
188 "XFRMA_MIGRATE",
189 "XFRMA_ALG_AEAD",
190 "XFRMA_KMADDRESS",
191 "XFRMA_ALG_AUTH_TRUNC",
192 "XFRMA_MARK",
193 "XFRMA_TFCPAD",
194 "XFRMA_REPLAY_ESN_VAL",
195 "XFRMA_SA_EXTRA_FLAGS",
196 "XFRMA_PROTO",
197 "XFRMA_ADDRESS_FILTER",
198 "XFRMA_PAD",
199 "XFRMA_OFFLOAD_DEV",
200 );
201
202 /**
203 * Algorithms for encryption
204 */
205 static kernel_algorithm_t encryption_algs[] = {
206 /* {ENCR_DES_IV64, "***" }, */
207 {ENCR_DES, "des" },
208 {ENCR_3DES, "des3_ede" },
209 /* {ENCR_RC5, "***" }, */
210 /* {ENCR_IDEA, "***" }, */
211 {ENCR_CAST, "cast5" },
212 {ENCR_BLOWFISH, "blowfish" },
213 /* {ENCR_3IDEA, "***" }, */
214 /* {ENCR_DES_IV32, "***" }, */
215 {ENCR_NULL, "cipher_null" },
216 {ENCR_AES_CBC, "aes" },
217 {ENCR_AES_CTR, "rfc3686(ctr(aes))" },
218 {ENCR_AES_CCM_ICV8, "rfc4309(ccm(aes))" },
219 {ENCR_AES_CCM_ICV12, "rfc4309(ccm(aes))" },
220 {ENCR_AES_CCM_ICV16, "rfc4309(ccm(aes))" },
221 {ENCR_AES_GCM_ICV8, "rfc4106(gcm(aes))" },
222 {ENCR_AES_GCM_ICV12, "rfc4106(gcm(aes))" },
223 {ENCR_AES_GCM_ICV16, "rfc4106(gcm(aes))" },
224 {ENCR_NULL_AUTH_AES_GMAC, "rfc4543(gcm(aes))" },
225 {ENCR_CAMELLIA_CBC, "cbc(camellia)" },
226 /* {ENCR_CAMELLIA_CTR, "***" }, */
227 /* {ENCR_CAMELLIA_CCM_ICV8, "***" }, */
228 /* {ENCR_CAMELLIA_CCM_ICV12, "***" }, */
229 /* {ENCR_CAMELLIA_CCM_ICV16, "***" }, */
230 {ENCR_SERPENT_CBC, "serpent" },
231 {ENCR_TWOFISH_CBC, "twofish" },
232 {ENCR_CHACHA20_POLY1305, "rfc7539esp(chacha20,poly1305)"},
233 };
234
235 /**
236 * Algorithms for integrity protection
237 */
238 static kernel_algorithm_t integrity_algs[] = {
239 {AUTH_HMAC_MD5_96, "md5" },
240 {AUTH_HMAC_MD5_128, "hmac(md5)" },
241 {AUTH_HMAC_SHA1_96, "sha1" },
242 {AUTH_HMAC_SHA1_160, "hmac(sha1)" },
243 {AUTH_HMAC_SHA2_256_96, "sha256" },
244 {AUTH_HMAC_SHA2_256_128, "hmac(sha256)" },
245 {AUTH_HMAC_SHA2_384_192, "hmac(sha384)" },
246 {AUTH_HMAC_SHA2_512_256, "hmac(sha512)" },
247 /* {AUTH_DES_MAC, "***" }, */
248 /* {AUTH_KPDK_MD5, "***" }, */
249 {AUTH_AES_XCBC_96, "xcbc(aes)" },
250 {AUTH_AES_CMAC_96, "cmac(aes)" },
251 };
252
253 /**
254 * Algorithms for IPComp
255 */
256 static kernel_algorithm_t compression_algs[] = {
257 /* {IPCOMP_OUI, "***" }, */
258 {IPCOMP_DEFLATE, "deflate" },
259 {IPCOMP_LZS, "lzs" },
260 {IPCOMP_LZJH, "lzjh" },
261 };
262
263 /**
264 * IPsec HW offload state in kernel
265 */
266 typedef enum {
267 NL_OFFLOAD_UNKNOWN,
268 NL_OFFLOAD_UNSUPPORTED,
269 NL_OFFLOAD_SUPPORTED
270 } nl_offload_state_t;
271
272 /**
273 * Global metadata used for IPsec HW offload
274 */
275 static struct {
276 /** bit in feature set */
277 u_int bit;
278 /** total number of device feature blocks */
279 u_int total_blocks;
280 /** determined HW offload state */
281 nl_offload_state_t state;
282 } netlink_hw_offload;
283
284 /**
285 * Look up a kernel algorithm name and its key size
286 */
287 static const char* lookup_algorithm(transform_type_t type, int ikev2)
288 {
289 kernel_algorithm_t *list;
290 int i, count;
291 char *name;
292
293 switch (type)
294 {
295 case ENCRYPTION_ALGORITHM:
296 list = encryption_algs;
297 count = countof(encryption_algs);
298 break;
299 case INTEGRITY_ALGORITHM:
300 list = integrity_algs;
301 count = countof(integrity_algs);
302 break;
303 case COMPRESSION_ALGORITHM:
304 list = compression_algs;
305 count = countof(compression_algs);
306 break;
307 default:
308 return NULL;
309 }
310 for (i = 0; i < count; i++)
311 {
312 if (list[i].ikev2 == ikev2)
313 {
314 return list[i].name;
315 }
316 }
317 if (charon->kernel->lookup_algorithm(charon->kernel, ikev2, type, NULL,
318 &name))
319 {
320 return name;
321 }
322 return NULL;
323 }
324
325 typedef struct private_kernel_netlink_ipsec_t private_kernel_netlink_ipsec_t;
326
327 /**
328 * Private variables and functions of kernel_netlink class.
329 */
330 struct private_kernel_netlink_ipsec_t {
331 /**
332 * Public part of the kernel_netlink_t object
333 */
334 kernel_netlink_ipsec_t public;
335
336 /**
337 * Mutex to lock access to installed policies
338 */
339 mutex_t *mutex;
340
341 /**
342 * Condvar to synchronize access to individual policies
343 */
344 condvar_t *condvar;
345
346 /**
347 * Hash table of installed policies (policy_entry_t)
348 */
349 hashtable_t *policies;
350
351 /**
352 * Hash table of IPsec SAs using policies (ipsec_sa_t)
353 */
354 hashtable_t *sas;
355
356 /**
357 * Netlink xfrm socket (IPsec)
358 */
359 netlink_socket_t *socket_xfrm;
360
361 /**
362 * Netlink xfrm socket to receive acquire and expire events
363 */
364 int socket_xfrm_events;
365
366 /**
367 * Whether to install routes along policies
368 */
369 bool install_routes;
370
371 /**
372 * Whether to set protocol and ports on selector installed with transport
373 * mode IPsec SAs
374 */
375 bool proto_port_transport;
376
377 /**
378 * Whether to always use UPDATE to install policies
379 */
380 bool policy_update;
381
382 /**
383 * Installed port based IKE bypass policies, as bypass_t
384 */
385 array_t *bypass;
386
387 /**
388 * Custom priority calculation function
389 */
390 uint32_t (*get_priority)(kernel_ipsec_policy_id_t *id,
391 kernel_ipsec_manage_policy_t *data);
392 };
393
394 typedef struct route_entry_t route_entry_t;
395
396 /**
397 * Installed routing entry
398 */
399 struct route_entry_t {
400 /** Name of the interface the route is bound to */
401 char *if_name;
402
403 /** Source ip of the route */
404 host_t *src_ip;
405
406 /** Gateway for this route */
407 host_t *gateway;
408
409 /** Destination net */
410 chunk_t dst_net;
411
412 /** Destination net prefixlen */
413 uint8_t prefixlen;
414 };
415
416 /**
417 * Destroy a route_entry_t object
418 */
419 static void route_entry_destroy(route_entry_t *this)
420 {
421 free(this->if_name);
422 this->src_ip->destroy(this->src_ip);
423 DESTROY_IF(this->gateway);
424 chunk_free(&this->dst_net);
425 free(this);
426 }
427
428 /**
429 * Compare two route_entry_t objects
430 */
431 static bool route_entry_equals(route_entry_t *a, route_entry_t *b)
432 {
433 return a->if_name && b->if_name && streq(a->if_name, b->if_name) &&
434 a->src_ip->ip_equals(a->src_ip, b->src_ip) &&
435 a->gateway->ip_equals(a->gateway, b->gateway) &&
436 chunk_equals(a->dst_net, b->dst_net) && a->prefixlen == b->prefixlen;
437 }
438
439 typedef struct ipsec_sa_t ipsec_sa_t;
440
441 /**
442 * IPsec SA assigned to a policy.
443 */
444 struct ipsec_sa_t {
445 /** Source address of this SA */
446 host_t *src;
447
448 /** Destination address of this SA */
449 host_t *dst;
450
451 /** Optional mark */
452 mark_t mark;
453
454 /** Description of this SA */
455 ipsec_sa_cfg_t cfg;
456
457 /** Reference count for this SA */
458 refcount_t refcount;
459 };
460
461 /**
462 * Hash function for ipsec_sa_t objects
463 */
464 static u_int ipsec_sa_hash(ipsec_sa_t *sa)
465 {
466 return chunk_hash_inc(sa->src->get_address(sa->src),
467 chunk_hash_inc(sa->dst->get_address(sa->dst),
468 chunk_hash_inc(chunk_from_thing(sa->mark),
469 chunk_hash(chunk_from_thing(sa->cfg)))));
470 }
471
472 /**
473 * Equality function for ipsec_sa_t objects
474 */
475 static bool ipsec_sa_equals(ipsec_sa_t *sa, ipsec_sa_t *other_sa)
476 {
477 return sa->src->ip_equals(sa->src, other_sa->src) &&
478 sa->dst->ip_equals(sa->dst, other_sa->dst) &&
479 sa->mark.value == other_sa->mark.value &&
480 sa->mark.mask == other_sa->mark.mask &&
481 ipsec_sa_cfg_equals(&sa->cfg, &other_sa->cfg);
482 }
483
484 /**
485 * Allocate or reference an IPsec SA object
486 */
487 static ipsec_sa_t *ipsec_sa_create(private_kernel_netlink_ipsec_t *this,
488 host_t *src, host_t *dst, mark_t mark,
489 ipsec_sa_cfg_t *cfg)
490 {
491 ipsec_sa_t *sa, *found;
492 INIT(sa,
493 .src = src,
494 .dst = dst,
495 .mark = mark,
496 .cfg = *cfg,
497 );
498 found = this->sas->get(this->sas, sa);
499 if (!found)
500 {
501 sa->src = src->clone(src);
502 sa->dst = dst->clone(dst);
503 this->sas->put(this->sas, sa, sa);
504 }
505 else
506 {
507 free(sa);
508 sa = found;
509 }
510 ref_get(&sa->refcount);
511 return sa;
512 }
513
514 /**
515 * Release and destroy an IPsec SA object
516 */
517 static void ipsec_sa_destroy(private_kernel_netlink_ipsec_t *this,
518 ipsec_sa_t *sa)
519 {
520 if (ref_put(&sa->refcount))
521 {
522 this->sas->remove(this->sas, sa);
523 DESTROY_IF(sa->src);
524 DESTROY_IF(sa->dst);
525 free(sa);
526 }
527 }
528
529 typedef struct policy_sa_t policy_sa_t;
530 typedef struct policy_sa_out_t policy_sa_out_t;
531
532 /**
533 * Mapping between a policy and an IPsec SA.
534 */
535 struct policy_sa_t {
536 /** Priority assigned to the policy when installed with this SA */
537 uint32_t priority;
538
539 /** Automatic priority assigned to the policy when installed with this SA */
540 uint32_t auto_priority;
541
542 /** Type of the policy */
543 policy_type_t type;
544
545 /** Assigned SA */
546 ipsec_sa_t *sa;
547 };
548
549 /**
550 * For outbound policies we also cache the traffic selectors in order to install
551 * the route.
552 */
553 struct policy_sa_out_t {
554 /** Generic interface */
555 policy_sa_t generic;
556
557 /** Source traffic selector of this policy */
558 traffic_selector_t *src_ts;
559
560 /** Destination traffic selector of this policy */
561 traffic_selector_t *dst_ts;
562 };
563
564 /**
565 * Create a policy_sa(_in)_t object
566 */
567 static policy_sa_t *policy_sa_create(private_kernel_netlink_ipsec_t *this,
568 policy_dir_t dir, policy_type_t type, host_t *src, host_t *dst,
569 traffic_selector_t *src_ts, traffic_selector_t *dst_ts, mark_t mark,
570 ipsec_sa_cfg_t *cfg)
571 {
572 policy_sa_t *policy;
573
574 if (dir == POLICY_OUT)
575 {
576 policy_sa_out_t *out;
577 INIT(out,
578 .src_ts = src_ts->clone(src_ts),
579 .dst_ts = dst_ts->clone(dst_ts),
580 );
581 policy = &out->generic;
582 }
583 else
584 {
585 INIT(policy, .priority = 0);
586 }
587 policy->type = type;
588 policy->sa = ipsec_sa_create(this, src, dst, mark, cfg);
589 return policy;
590 }
591
592 /**
593 * Destroy a policy_sa(_in)_t object
594 */
595 static void policy_sa_destroy(policy_sa_t *policy, policy_dir_t dir,
596 private_kernel_netlink_ipsec_t *this)
597 {
598 if (dir == POLICY_OUT)
599 {
600 policy_sa_out_t *out = (policy_sa_out_t*)policy;
601 out->src_ts->destroy(out->src_ts);
602 out->dst_ts->destroy(out->dst_ts);
603 }
604 ipsec_sa_destroy(this, policy->sa);
605 free(policy);
606 }
607
608 CALLBACK(policy_sa_destroy_cb, void,
609 policy_sa_t *policy, va_list args)
610 {
611 private_kernel_netlink_ipsec_t *this;
612 policy_dir_t dir;
613
614 VA_ARGS_VGET(args, dir, this);
615 policy_sa_destroy(policy, dir, this);
616 }
617
618 typedef struct policy_entry_t policy_entry_t;
619
620 /**
621 * Installed kernel policy.
622 */
623 struct policy_entry_t {
624
625 /** Direction of this policy: in, out, forward */
626 uint8_t direction;
627
628 /** Parameters of installed policy */
629 struct xfrm_selector sel;
630
631 /** Optional mark */
632 uint32_t mark;
633
634 /** Associated route installed for this policy */
635 route_entry_t *route;
636
637 /** List of SAs this policy is used by, ordered by priority */
638 linked_list_t *used_by;
639
640 /** reqid for this policy */
641 uint32_t reqid;
642
643 /** Number of threads waiting to work on this policy */
644 int waiting;
645
646 /** TRUE if a thread is working on this policy */
647 bool working;
648 };
649
650 /**
651 * Destroy a policy_entry_t object
652 */
653 static void policy_entry_destroy(private_kernel_netlink_ipsec_t *this,
654 policy_entry_t *policy)
655 {
656 if (policy->route)
657 {
658 route_entry_destroy(policy->route);
659 }
660 if (policy->used_by)
661 {
662 policy->used_by->invoke_function(policy->used_by, policy_sa_destroy_cb,
663 policy->direction, this);
664 policy->used_by->destroy(policy->used_by);
665 }
666 free(policy);
667 }
668
669 /**
670 * Hash function for policy_entry_t objects
671 */
672 static u_int policy_hash(policy_entry_t *key)
673 {
674 chunk_t chunk = chunk_from_thing(key->sel);
675 return chunk_hash_inc(chunk, chunk_hash(chunk_from_thing(key->mark)));
676 }
677
678 /**
679 * Equality function for policy_entry_t objects
680 */
681 static bool policy_equals(policy_entry_t *key, policy_entry_t *other_key)
682 {
683 return memeq(&key->sel, &other_key->sel, sizeof(struct xfrm_selector)) &&
684 key->mark == other_key->mark &&
685 key->direction == other_key->direction;
686 }
687
688 /**
689 * Determine number of set bits in 16 bit port mask
690 */
691 static inline uint32_t port_mask_bits(uint16_t port_mask)
692 {
693 uint32_t bits;
694 uint16_t bit_mask = 0x8000;
695
696 port_mask = ntohs(port_mask);
697
698 for (bits = 0; bits < 16; bits++)
699 {
700 if (!(port_mask & bit_mask))
701 {
702 break;
703 }
704 bit_mask >>= 1;
705 }
706 return bits;
707 }
708
709 /**
710 * Calculate the priority of a policy
711 *
712 * bits 0-0: separate trap and regular policies (0..1) 1 bit
713 * bits 1-1: restriction to network interface (0..1) 1 bit
714 * bits 2-7: src + dst port mask bits (2 * 0..16) 6 bits
715 * bits 8-8: restriction to protocol (0..1) 1 bit
716 * bits 9-17: src + dst network mask bits (2 * 0..128) 9 bits
717 * 18 bits
718 *
719 * smallest value: 000000000 0 000000 0 0: 0, lowest priority = 200'000
720 * largest value : 100000000 1 100000 1 1: 131'459, highst priority = 68'541
721 */
722 static uint32_t get_priority(policy_entry_t *policy, policy_priority_t prio,
723 char *interface)
724 {
725 uint32_t priority = PRIO_BASE, sport_mask_bits, dport_mask_bits;
726
727 switch (prio)
728 {
729 case POLICY_PRIORITY_FALLBACK:
730 priority += PRIO_BASE;
731 /* fall-through to next case */
732 case POLICY_PRIORITY_ROUTED:
733 case POLICY_PRIORITY_DEFAULT:
734 priority += PRIO_BASE;
735 /* fall-through to next case */
736 case POLICY_PRIORITY_PASS:
737 break;
738 }
739 sport_mask_bits = port_mask_bits(policy->sel.sport_mask);
740 dport_mask_bits = port_mask_bits(policy->sel.dport_mask);
741
742 /* calculate priority */
743 priority -= (policy->sel.prefixlen_s + policy->sel.prefixlen_d) * 512;
744 priority -= policy->sel.proto ? 256 : 0;
745 priority -= (sport_mask_bits + dport_mask_bits) * 4;
746 priority -= (interface != NULL) * 2;
747 priority -= (prio != POLICY_PRIORITY_ROUTED);
748
749 return priority;
750 }
751
752 /**
753 * Convert the general ipsec mode to the one defined in xfrm.h
754 */
755 static uint8_t mode2kernel(ipsec_mode_t mode)
756 {
757 switch (mode)
758 {
759 case MODE_TRANSPORT:
760 return XFRM_MODE_TRANSPORT;
761 case MODE_TUNNEL:
762 return XFRM_MODE_TUNNEL;
763 case MODE_BEET:
764 return XFRM_MODE_BEET;
765 default:
766 return mode;
767 }
768 }
769
770 /**
771 * Convert a host_t to a struct xfrm_address
772 */
773 static void host2xfrm(host_t *host, xfrm_address_t *xfrm)
774 {
775 chunk_t chunk = host->get_address(host);
776 memcpy(xfrm, chunk.ptr, min(chunk.len, sizeof(xfrm_address_t)));
777 }
778
779 /**
780 * Convert a struct xfrm_address to a host_t
781 */
782 static host_t* xfrm2host(int family, xfrm_address_t *xfrm, uint16_t port)
783 {
784 chunk_t chunk;
785
786 switch (family)
787 {
788 case AF_INET:
789 chunk = chunk_create((u_char*)&xfrm->a4, sizeof(xfrm->a4));
790 break;
791 case AF_INET6:
792 chunk = chunk_create((u_char*)&xfrm->a6, sizeof(xfrm->a6));
793 break;
794 default:
795 return NULL;
796 }
797 return host_create_from_chunk(family, chunk, ntohs(port));
798 }
799
800 /**
801 * Convert a traffic selector address range to subnet and its mask.
802 */
803 static void ts2subnet(traffic_selector_t* ts,
804 xfrm_address_t *net, uint8_t *mask)
805 {
806 host_t *net_host;
807 chunk_t net_chunk;
808
809 ts->to_subnet(ts, &net_host, mask);
810 net_chunk = net_host->get_address(net_host);
811 memcpy(net, net_chunk.ptr, net_chunk.len);
812 net_host->destroy(net_host);
813 }
814
815 /**
816 * Convert a traffic selector port range to port/portmask
817 */
818 static void ts2ports(traffic_selector_t* ts,
819 uint16_t *port, uint16_t *mask)
820 {
821 uint16_t from, to, bitmask;
822 int bit;
823
824 from = ts->get_from_port(ts);
825 to = ts->get_to_port(ts);
826
827 /* Quick check for a single port */
828 if (from == to)
829 {
830 *port = htons(from);
831 *mask = ~0;
832 }
833 else
834 {
835 /* Compute the port mask for port ranges */
836 *mask = 0;
837
838 for (bit = 15; bit >= 0; bit--)
839 {
840 bitmask = 1 << bit;
841
842 if ((bitmask & from) != (bitmask & to))
843 {
844 *port = htons(from & *mask);
845 *mask = htons(*mask);
846 return;
847 }
848 *mask |= bitmask;
849 }
850 }
851 return;
852 }
853
854 /**
855 * Convert a pair of traffic_selectors to an xfrm_selector
856 */
857 static struct xfrm_selector ts2selector(traffic_selector_t *src,
858 traffic_selector_t *dst,
859 char *interface)
860 {
861 struct xfrm_selector sel;
862 uint16_t port;
863
864 memset(&sel, 0, sizeof(sel));
865 sel.family = (src->get_type(src) == TS_IPV4_ADDR_RANGE) ? AF_INET : AF_INET6;
866 /* src or dest proto may be "any" (0), use more restrictive one */
867 sel.proto = max(src->get_protocol(src), dst->get_protocol(dst));
868 ts2subnet(dst, &sel.daddr, &sel.prefixlen_d);
869 ts2subnet(src, &sel.saddr, &sel.prefixlen_s);
870 ts2ports(dst, &sel.dport, &sel.dport_mask);
871 ts2ports(src, &sel.sport, &sel.sport_mask);
872 if ((sel.proto == IPPROTO_ICMP || sel.proto == IPPROTO_ICMPV6) &&
873 (sel.dport || sel.sport))
874 {
875 /* the kernel expects the ICMP type and code in the source and
876 * destination port fields, respectively. */
877 port = ntohs(max(sel.dport, sel.sport));
878 sel.sport = htons(traffic_selector_icmp_type(port));
879 sel.sport_mask = sel.sport ? ~0 : 0;
880 sel.dport = htons(traffic_selector_icmp_code(port));
881 sel.dport_mask = sel.dport ? ~0 : 0;
882 }
883 sel.ifindex = interface ? if_nametoindex(interface) : 0;
884 sel.user = 0;
885
886 return sel;
887 }
888
889 /**
890 * Convert an xfrm_selector to a src|dst traffic_selector
891 */
892 static traffic_selector_t* selector2ts(struct xfrm_selector *sel, bool src)
893 {
894 u_char *addr;
895 uint8_t prefixlen;
896 uint16_t port = 0;
897 host_t *host = NULL;
898
899 if (src)
900 {
901 addr = (u_char*)&sel->saddr;
902 prefixlen = sel->prefixlen_s;
903 if (sel->sport_mask)
904 {
905 port = ntohs(sel->sport);
906 }
907 }
908 else
909 {
910 addr = (u_char*)&sel->daddr;
911 prefixlen = sel->prefixlen_d;
912 if (sel->dport_mask)
913 {
914 port = ntohs(sel->dport);
915 }
916 }
917 if (sel->proto == IPPROTO_ICMP || sel->proto == IPPROTO_ICMPV6)
918 { /* convert ICMP[v6] message type and code as supplied by the kernel in
919 * source and destination ports (both in network order) */
920 port = (sel->sport >> 8) | (sel->dport & 0xff00);
921 port = ntohs(port);
922 }
923 /* The Linux 2.6 kernel does not set the selector's family field,
924 * so as a kludge we additionally test the prefix length.
925 */
926 if (sel->family == AF_INET || sel->prefixlen_s == 32)
927 {
928 host = host_create_from_chunk(AF_INET, chunk_create(addr, 4), 0);
929 }
930 else if (sel->family == AF_INET6 || sel->prefixlen_s == 128)
931 {
932 host = host_create_from_chunk(AF_INET6, chunk_create(addr, 16), 0);
933 }
934
935 if (host)
936 {
937 return traffic_selector_create_from_subnet(host, prefixlen,
938 sel->proto, port, port ?: 65535);
939 }
940 return NULL;
941 }
942
943 /**
944 * Process a XFRM_MSG_ACQUIRE from kernel
945 */
946 static void process_acquire(private_kernel_netlink_ipsec_t *this,
947 struct nlmsghdr *hdr)
948 {
949 struct xfrm_user_acquire *acquire;
950 struct rtattr *rta;
951 size_t rtasize;
952 traffic_selector_t *src_ts, *dst_ts;
953 uint32_t reqid = 0;
954 int proto = 0;
955
956 acquire = NLMSG_DATA(hdr);
957 rta = XFRM_RTA(hdr, struct xfrm_user_acquire);
958 rtasize = XFRM_PAYLOAD(hdr, struct xfrm_user_acquire);
959
960 DBG2(DBG_KNL, "received a XFRM_MSG_ACQUIRE");
961
962 while (RTA_OK(rta, rtasize))
963 {
964 DBG2(DBG_KNL, " %N", xfrm_attr_type_names, rta->rta_type);
965
966 if (rta->rta_type == XFRMA_TMPL)
967 {
968 struct xfrm_user_tmpl* tmpl;
969 tmpl = (struct xfrm_user_tmpl*)RTA_DATA(rta);
970 reqid = tmpl->reqid;
971 proto = tmpl->id.proto;
972 }
973 rta = RTA_NEXT(rta, rtasize);
974 }
975 switch (proto)
976 {
977 case 0:
978 case IPPROTO_ESP:
979 case IPPROTO_AH:
980 break;
981 default:
982 /* acquire for AH/ESP only, not for IPCOMP */
983 return;
984 }
985 src_ts = selector2ts(&acquire->sel, TRUE);
986 dst_ts = selector2ts(&acquire->sel, FALSE);
987
988 charon->kernel->acquire(charon->kernel, reqid, src_ts, dst_ts);
989 }
990
991 /**
992 * Process a XFRM_MSG_EXPIRE from kernel
993 */
994 static void process_expire(private_kernel_netlink_ipsec_t *this,
995 struct nlmsghdr *hdr)
996 {
997 struct xfrm_user_expire *expire;
998 uint32_t spi;
999 uint8_t protocol;
1000 host_t *dst;
1001
1002 expire = NLMSG_DATA(hdr);
1003 protocol = expire->state.id.proto;
1004 spi = expire->state.id.spi;
1005
1006 DBG2(DBG_KNL, "received a XFRM_MSG_EXPIRE");
1007
1008 if (protocol == IPPROTO_ESP || protocol == IPPROTO_AH)
1009 {
1010 dst = xfrm2host(expire->state.family, &expire->state.id.daddr, 0);
1011 if (dst)
1012 {
1013 charon->kernel->expire(charon->kernel, protocol, spi, dst,
1014 expire->hard != 0);
1015 dst->destroy(dst);
1016 }
1017 }
1018 }
1019
1020 /**
1021 * Process a XFRM_MSG_MIGRATE from kernel
1022 */
1023 static void process_migrate(private_kernel_netlink_ipsec_t *this,
1024 struct nlmsghdr *hdr)
1025 {
1026 struct xfrm_userpolicy_id *policy_id;
1027 struct rtattr *rta;
1028 size_t rtasize;
1029 traffic_selector_t *src_ts, *dst_ts;
1030 host_t *local = NULL, *remote = NULL;
1031 host_t *old_src = NULL, *old_dst = NULL;
1032 host_t *new_src = NULL, *new_dst = NULL;
1033 uint32_t reqid = 0;
1034 policy_dir_t dir;
1035
1036 policy_id = NLMSG_DATA(hdr);
1037 rta = XFRM_RTA(hdr, struct xfrm_userpolicy_id);
1038 rtasize = XFRM_PAYLOAD(hdr, struct xfrm_userpolicy_id);
1039
1040 DBG2(DBG_KNL, "received a XFRM_MSG_MIGRATE");
1041
1042 src_ts = selector2ts(&policy_id->sel, TRUE);
1043 dst_ts = selector2ts(&policy_id->sel, FALSE);
1044 dir = (policy_dir_t)policy_id->dir;
1045
1046 DBG2(DBG_KNL, " policy: %R === %R %N", src_ts, dst_ts, policy_dir_names);
1047
1048 while (RTA_OK(rta, rtasize))
1049 {
1050 DBG2(DBG_KNL, " %N", xfrm_attr_type_names, rta->rta_type);
1051 if (rta->rta_type == XFRMA_KMADDRESS)
1052 {
1053 struct xfrm_user_kmaddress *kmaddress;
1054
1055 kmaddress = (struct xfrm_user_kmaddress*)RTA_DATA(rta);
1056 local = xfrm2host(kmaddress->family, &kmaddress->local, 0);
1057 remote = xfrm2host(kmaddress->family, &kmaddress->remote, 0);
1058 DBG2(DBG_KNL, " kmaddress: %H...%H", local, remote);
1059 }
1060 else if (rta->rta_type == XFRMA_MIGRATE)
1061 {
1062 struct xfrm_user_migrate *migrate;
1063
1064 migrate = (struct xfrm_user_migrate*)RTA_DATA(rta);
1065 old_src = xfrm2host(migrate->old_family, &migrate->old_saddr, 0);
1066 old_dst = xfrm2host(migrate->old_family, &migrate->old_daddr, 0);
1067 new_src = xfrm2host(migrate->new_family, &migrate->new_saddr, 0);
1068 new_dst = xfrm2host(migrate->new_family, &migrate->new_daddr, 0);
1069 reqid = migrate->reqid;
1070 DBG2(DBG_KNL, " migrate %H...%H to %H...%H, reqid {%u}",
1071 old_src, old_dst, new_src, new_dst, reqid);
1072 DESTROY_IF(old_src);
1073 DESTROY_IF(old_dst);
1074 DESTROY_IF(new_src);
1075 DESTROY_IF(new_dst);
1076 }
1077 rta = RTA_NEXT(rta, rtasize);
1078 }
1079
1080 if (src_ts && dst_ts && local && remote)
1081 {
1082 charon->kernel->migrate(charon->kernel, reqid, src_ts, dst_ts, dir,
1083 local, remote);
1084 }
1085 else
1086 {
1087 DESTROY_IF(src_ts);
1088 DESTROY_IF(dst_ts);
1089 DESTROY_IF(local);
1090 DESTROY_IF(remote);
1091 }
1092 }
1093
1094 /**
1095 * Process a XFRM_MSG_MAPPING from kernel
1096 */
1097 static void process_mapping(private_kernel_netlink_ipsec_t *this,
1098 struct nlmsghdr *hdr)
1099 {
1100 struct xfrm_user_mapping *mapping;
1101 uint32_t spi;
1102
1103 mapping = NLMSG_DATA(hdr);
1104 spi = mapping->id.spi;
1105
1106 DBG2(DBG_KNL, "received a XFRM_MSG_MAPPING");
1107
1108 if (mapping->id.proto == IPPROTO_ESP)
1109 {
1110 host_t *dst, *new;
1111
1112 dst = xfrm2host(mapping->id.family, &mapping->id.daddr, 0);
1113 if (dst)
1114 {
1115 new = xfrm2host(mapping->id.family, &mapping->new_saddr,
1116 mapping->new_sport);
1117 if (new)
1118 {
1119 charon->kernel->mapping(charon->kernel, IPPROTO_ESP, spi, dst,
1120 new);
1121 new->destroy(new);
1122 }
1123 dst->destroy(dst);
1124 }
1125 }
1126 }
1127
1128 /**
1129 * Receives events from kernel
1130 */
1131 static bool receive_events(private_kernel_netlink_ipsec_t *this, int fd,
1132 watcher_event_t event)
1133 {
1134 char response[1024];
1135 struct nlmsghdr *hdr = (struct nlmsghdr*)response;
1136 struct sockaddr_nl addr;
1137 socklen_t addr_len = sizeof(addr);
1138 int len;
1139
1140 len = recvfrom(this->socket_xfrm_events, response, sizeof(response),
1141 MSG_DONTWAIT, (struct sockaddr*)&addr, &addr_len);
1142 if (len < 0)
1143 {
1144 switch (errno)
1145 {
1146 case EINTR:
1147 /* interrupted, try again */
1148 return TRUE;
1149 case EAGAIN:
1150 /* no data ready, select again */
1151 return TRUE;
1152 default:
1153 DBG1(DBG_KNL, "unable to receive from XFRM event socket: %s "
1154 "(%d)", strerror(errno), errno);
1155 sleep(1);
1156 return TRUE;
1157 }
1158 }
1159
1160 if (addr.nl_pid != 0)
1161 { /* not from kernel. not interested, try another one */
1162 return TRUE;
1163 }
1164
1165 while (NLMSG_OK(hdr, len))
1166 {
1167 switch (hdr->nlmsg_type)
1168 {
1169 case XFRM_MSG_ACQUIRE:
1170 process_acquire(this, hdr);
1171 break;
1172 case XFRM_MSG_EXPIRE:
1173 process_expire(this, hdr);
1174 break;
1175 case XFRM_MSG_MIGRATE:
1176 process_migrate(this, hdr);
1177 break;
1178 case XFRM_MSG_MAPPING:
1179 process_mapping(this, hdr);
1180 break;
1181 default:
1182 DBG1(DBG_KNL, "received unknown event from XFRM event "
1183 "socket: %d", hdr->nlmsg_type);
1184 break;
1185 }
1186 hdr = NLMSG_NEXT(hdr, len);
1187 }
1188 return TRUE;
1189 }
1190
1191 METHOD(kernel_ipsec_t, get_features, kernel_feature_t,
1192 private_kernel_netlink_ipsec_t *this)
1193 {
1194 return KERNEL_ESP_V3_TFC | KERNEL_POLICY_SPI;
1195 }
1196
1197 /**
1198 * Get an SPI for a specific protocol from the kernel.
1199 */
1200 static status_t get_spi_internal(private_kernel_netlink_ipsec_t *this,
1201 host_t *src, host_t *dst, uint8_t proto, uint32_t min, uint32_t max,
1202 uint32_t *spi)
1203 {
1204 netlink_buf_t request;
1205 struct nlmsghdr *hdr, *out;
1206 struct xfrm_userspi_info *userspi;
1207 uint32_t received_spi = 0;
1208 size_t len;
1209
1210 memset(&request, 0, sizeof(request));
1211
1212 hdr = &request.hdr;
1213 hdr->nlmsg_flags = NLM_F_REQUEST;
1214 hdr->nlmsg_type = XFRM_MSG_ALLOCSPI;
1215 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userspi_info));
1216
1217 userspi = NLMSG_DATA(hdr);
1218 host2xfrm(src, &userspi->info.saddr);
1219 host2xfrm(dst, &userspi->info.id.daddr);
1220 userspi->info.id.proto = proto;
1221 userspi->info.mode = XFRM_MODE_TUNNEL;
1222 userspi->info.family = src->get_family(src);
1223 userspi->min = min;
1224 userspi->max = max;
1225
1226 if (this->socket_xfrm->send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
1227 {
1228 hdr = out;
1229 while (NLMSG_OK(hdr, len))
1230 {
1231 switch (hdr->nlmsg_type)
1232 {
1233 case XFRM_MSG_NEWSA:
1234 {
1235 struct xfrm_usersa_info* usersa = NLMSG_DATA(hdr);
1236 received_spi = usersa->id.spi;
1237 break;
1238 }
1239 case NLMSG_ERROR:
1240 {
1241 struct nlmsgerr *err = NLMSG_DATA(hdr);
1242 DBG1(DBG_KNL, "allocating SPI failed: %s (%d)",
1243 strerror(-err->error), -err->error);
1244 break;
1245 }
1246 default:
1247 hdr = NLMSG_NEXT(hdr, len);
1248 continue;
1249 case NLMSG_DONE:
1250 break;
1251 }
1252 break;
1253 }
1254 free(out);
1255 }
1256
1257 if (received_spi == 0)
1258 {
1259 return FAILED;
1260 }
1261
1262 *spi = received_spi;
1263 return SUCCESS;
1264 }
1265
1266 METHOD(kernel_ipsec_t, get_spi, status_t,
1267 private_kernel_netlink_ipsec_t *this, host_t *src, host_t *dst,
1268 uint8_t protocol, uint32_t *spi)
1269 {
1270 uint32_t spi_min, spi_max;
1271
1272 spi_min = lib->settings->get_int(lib->settings, "%s.spi_min",
1273 KERNEL_SPI_MIN, lib->ns);
1274 spi_max = lib->settings->get_int(lib->settings, "%s.spi_max",
1275 KERNEL_SPI_MAX, lib->ns);
1276
1277 if (get_spi_internal(this, src, dst, protocol, min(spi_min, spi_max),
1278 max(spi_min, spi_max), spi) != SUCCESS)
1279 {
1280 DBG1(DBG_KNL, "unable to get SPI");
1281 return FAILED;
1282 }
1283
1284 DBG2(DBG_KNL, "got SPI %.8x", ntohl(*spi));
1285 return SUCCESS;
1286 }
1287
1288 METHOD(kernel_ipsec_t, get_cpi, status_t,
1289 private_kernel_netlink_ipsec_t *this, host_t *src, host_t *dst,
1290 uint16_t *cpi)
1291 {
1292 uint32_t received_spi = 0;
1293
1294 if (get_spi_internal(this, src, dst, IPPROTO_COMP,
1295 0x100, 0xEFFF, &received_spi) != SUCCESS)
1296 {
1297 DBG1(DBG_KNL, "unable to get CPI");
1298 return FAILED;
1299 }
1300
1301 *cpi = htons((uint16_t)ntohl(received_spi));
1302
1303 DBG2(DBG_KNL, "got CPI %.4x", ntohs(*cpi));
1304 return SUCCESS;
1305 }
1306
1307 /**
1308 * Format the mark for debug messages
1309 */
1310 static void format_mark(char *buf, int buflen, mark_t mark)
1311 {
1312 if (mark.value | mark.mask)
1313 {
1314 snprintf(buf, buflen, " (mark %u/0x%08x)", mark.value, mark.mask);
1315 }
1316 }
1317
1318 /**
1319 * Add a XFRM mark to message if required
1320 */
1321 static bool add_mark(struct nlmsghdr *hdr, int buflen, mark_t mark)
1322 {
1323 if (mark.value | mark.mask)
1324 {
1325 struct xfrm_mark *xmrk;
1326
1327 xmrk = netlink_reserve(hdr, buflen, XFRMA_MARK, sizeof(*xmrk));
1328 if (!xmrk)
1329 {
1330 return FALSE;
1331 }
1332 xmrk->v = mark.value;
1333 xmrk->m = mark.mask;
1334 }
1335 return TRUE;
1336 }
1337
1338 /**
1339 * Check if kernel supports HW offload
1340 */
1341 static void netlink_find_offload_feature(const char *ifname, int query_socket)
1342 {
1343 struct ethtool_sset_info *sset_info;
1344 struct ethtool_gstrings *cmd = NULL;
1345 struct ifreq ifr;
1346 uint32_t sset_len, i;
1347 char *str;
1348 int err;
1349
1350 netlink_hw_offload.state = NL_OFFLOAD_UNSUPPORTED;
1351
1352 /* determine number of device features */
1353 INIT_EXTRA(sset_info, sizeof(uint32_t),
1354 .cmd = ETHTOOL_GSSET_INFO,
1355 .sset_mask = 1ULL << ETH_SS_FEATURES,
1356 );
1357 strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
1358 ifr.ifr_name[IFNAMSIZ-1] = '\0';
1359 ifr.ifr_data = (void*)sset_info;
1360
1361 err = ioctl(query_socket, SIOCETHTOOL, &ifr);
1362 if (err || sset_info->sset_mask != 1ULL << ETH_SS_FEATURES)
1363 {
1364 goto out;
1365 }
1366 sset_len = sset_info->data[0];
1367
1368 /* retrieve names of device features */
1369 INIT_EXTRA(cmd, ETH_GSTRING_LEN * sset_len,
1370 .cmd = ETHTOOL_GSTRINGS,
1371 .string_set = ETH_SS_FEATURES,
1372 );
1373 strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
1374 ifr.ifr_name[IFNAMSIZ-1] = '\0';
1375 ifr.ifr_data = (void*)cmd;
1376
1377 err = ioctl(query_socket, SIOCETHTOOL, &ifr);
1378 if (err)
1379 {
1380 goto out;
1381 }
1382
1383 /* look for the ESP_HW feature bit */
1384 str = (char*)cmd->data;
1385 for (i = 0; i < cmd->len; i++)
1386 {
1387 if (strneq(str, "esp-hw-offload", ETH_GSTRING_LEN))
1388 {
1389 netlink_hw_offload.bit = i;
1390 netlink_hw_offload.total_blocks = (sset_len + 31) / 32;
1391 netlink_hw_offload.state = NL_OFFLOAD_SUPPORTED;
1392 break;
1393 }
1394 str += ETH_GSTRING_LEN;
1395 }
1396
1397 out:
1398 free(sset_info);
1399 free(cmd);
1400 }
1401
1402 /**
1403 * Check if interface supported HW offload
1404 */
1405 static bool netlink_detect_offload(const char *ifname)
1406 {
1407 struct ethtool_gfeatures *cmd;
1408 uint32_t feature_bit;
1409 struct ifreq ifr;
1410 int query_socket;
1411 int block;
1412 bool ret = FALSE;
1413
1414 query_socket = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_XFRM);
1415 if (query_socket < 0)
1416 {
1417 return FALSE;
1418 }
1419
1420 /* kernel requires a real interface in order to query the kernel-wide
1421 * capability, so we do it here on first invocation.
1422 */
1423 if (netlink_hw_offload.state == NL_OFFLOAD_UNKNOWN)
1424 {
1425 netlink_find_offload_feature(ifname, query_socket);
1426 }
1427 if (netlink_hw_offload.state == NL_OFFLOAD_UNSUPPORTED)
1428 {
1429 DBG1(DBG_KNL, "HW offload is not supported by kernel");
1430 goto out;
1431 }
1432
1433 /* feature is supported by kernel, query device features */
1434 INIT_EXTRA(cmd, sizeof(cmd->features[0]) * netlink_hw_offload.total_blocks,
1435 .cmd = ETHTOOL_GFEATURES,
1436 .size = netlink_hw_offload.total_blocks,
1437 );
1438 strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
1439 ifr.ifr_name[IFNAMSIZ-1] = '\0';
1440 ifr.ifr_data = (void*)cmd;
1441
1442 if (ioctl(query_socket, SIOCETHTOOL, &ifr))
1443 {
1444 goto out_free;
1445 }
1446
1447 block = netlink_hw_offload.bit / 32;
1448 feature_bit = 1U << (netlink_hw_offload.bit % 32);
1449 if (cmd->features[block].active & feature_bit)
1450 {
1451 ret = TRUE;
1452 }
1453
1454 out_free:
1455 free(cmd);
1456 if (!ret)
1457 {
1458 DBG1(DBG_KNL, "HW offload is not supported by device");
1459 }
1460 out:
1461 close(query_socket);
1462 return ret;
1463 }
1464
1465 /**
1466 * There are 3 HW offload configuration values:
1467 * 1. HW_OFFLOAD_NO : Do not configure HW offload.
1468 * 2. HW_OFFLOAD_YES : Configure HW offload.
1469 * Fail SA addition if offload is not supported.
1470 * 3. HW_OFFLOAD_AUTO : Configure HW offload if supported by the kernel
1471 * and device.
1472 * Do not fail SA addition otherwise.
1473 */
1474 static bool config_hw_offload(kernel_ipsec_sa_id_t *id,
1475 kernel_ipsec_add_sa_t *data, struct nlmsghdr *hdr,
1476 int buflen)
1477 {
1478 host_t *local = data->inbound ? id->dst : id->src;
1479 struct xfrm_user_offload *offload;
1480 bool hw_offload_yes, ret = FALSE;
1481 char *ifname;
1482
1483 /* do Ipsec configuration without offload */
1484 if (data->hw_offload == HW_OFFLOAD_NO)
1485 {
1486 return TRUE;
1487 }
1488
1489 hw_offload_yes = (data->hw_offload == HW_OFFLOAD_YES);
1490
1491 if (!charon->kernel->get_interface(charon->kernel, local, &ifname))
1492 {
1493 return !hw_offload_yes;
1494 }
1495
1496 /* check if interface supports hw_offload */
1497 if (!netlink_detect_offload(ifname))
1498 {
1499 ret = !hw_offload_yes;
1500 goto out;
1501 }
1502
1503 /* activate HW offload */
1504 offload = netlink_reserve(hdr, buflen,
1505 XFRMA_OFFLOAD_DEV, sizeof(*offload));
1506 if (!offload)
1507 {
1508 ret = !hw_offload_yes;
1509 goto out;
1510 }
1511 offload->ifindex = if_nametoindex(ifname);
1512 if (local->get_family(local) == AF_INET6)
1513 {
1514 offload->flags |= XFRM_OFFLOAD_IPV6;
1515 }
1516 offload->flags |= data->inbound ? XFRM_OFFLOAD_INBOUND : 0;
1517
1518 ret = TRUE;
1519
1520 out:
1521 free(ifname);
1522 return ret;
1523 }
1524
1525 METHOD(kernel_ipsec_t, add_sa, status_t,
1526 private_kernel_netlink_ipsec_t *this, kernel_ipsec_sa_id_t *id,
1527 kernel_ipsec_add_sa_t *data)
1528 {
1529 netlink_buf_t request;
1530 const char *alg_name;
1531 char markstr[32] = "";
1532 struct nlmsghdr *hdr;
1533 struct xfrm_usersa_info *sa;
1534 uint16_t icv_size = 64, ipcomp = data->ipcomp;
1535 ipsec_mode_t mode = data->mode, original_mode = data->mode;
1536 traffic_selector_t *first_src_ts, *first_dst_ts;
1537 status_t status = FAILED;
1538
1539 /* if IPComp is used, we install an additional IPComp SA. if the cpi is 0
1540 * we are in the recursive call below */
1541 if (ipcomp != IPCOMP_NONE && data->cpi != 0)
1542 {
1543 lifetime_cfg_t lft = {{0,0,0},{0,0,0},{0,0,0}};
1544 kernel_ipsec_sa_id_t ipcomp_id = {
1545 .src = id->src,
1546 .dst = id->dst,
1547 .spi = htonl(ntohs(data->cpi)),
1548 .proto = IPPROTO_COMP,
1549 .mark = id->mark,
1550 };
1551 kernel_ipsec_add_sa_t ipcomp_sa = {
1552 .reqid = data->reqid,
1553 .mode = data->mode,
1554 .src_ts = data->src_ts,
1555 .dst_ts = data->dst_ts,
1556 .lifetime = &lft,
1557 .enc_alg = ENCR_UNDEFINED,
1558 .int_alg = AUTH_UNDEFINED,
1559 .tfc = data->tfc,
1560 .ipcomp = data->ipcomp,
1561 .initiator = data->initiator,
1562 .inbound = data->inbound,
1563 .update = data->update,
1564 };
1565 add_sa(this, &ipcomp_id, &ipcomp_sa);
1566 ipcomp = IPCOMP_NONE;
1567 /* use transport mode ESP SA, IPComp uses tunnel mode */
1568 mode = MODE_TRANSPORT;
1569 }
1570
1571 memset(&request, 0, sizeof(request));
1572 format_mark(markstr, sizeof(markstr), id->mark);
1573
1574 DBG2(DBG_KNL, "adding SAD entry with SPI %.8x and reqid {%u}%s",
1575 ntohl(id->spi), data->reqid, markstr);
1576
1577 hdr = &request.hdr;
1578 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
1579 hdr->nlmsg_type = data->update ? XFRM_MSG_UPDSA : XFRM_MSG_NEWSA;
1580 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_info));
1581
1582 sa = NLMSG_DATA(hdr);
1583 host2xfrm(id->src, &sa->saddr);
1584 host2xfrm(id->dst, &sa->id.daddr);
1585 sa->id.spi = id->spi;
1586 sa->id.proto = id->proto;
1587 sa->family = id->src->get_family(id->src);
1588 sa->mode = mode2kernel(mode);
1589
1590 if (!data->copy_df)
1591 {
1592 sa->flags |= XFRM_STATE_NOPMTUDISC;
1593 }
1594
1595 if (!data->copy_ecn)
1596 {
1597 sa->flags |= XFRM_STATE_NOECN;
1598 }
1599
1600 switch (mode)
1601 {
1602 case MODE_TUNNEL:
1603 sa->flags |= XFRM_STATE_AF_UNSPEC;
1604 break;
1605 case MODE_BEET:
1606 case MODE_TRANSPORT:
1607 if (original_mode == MODE_TUNNEL)
1608 { /* don't install selectors for switched SAs. because only one
1609 * selector can be installed other traffic would get dropped */
1610 break;
1611 }
1612 if (data->src_ts->get_first(data->src_ts,
1613 (void**)&first_src_ts) == SUCCESS &&
1614 data->dst_ts->get_first(data->dst_ts,
1615 (void**)&first_dst_ts) == SUCCESS)
1616 {
1617 sa->sel = ts2selector(first_src_ts, first_dst_ts,
1618 data->interface);
1619 if (!this->proto_port_transport)
1620 {
1621 /* don't install proto/port on SA. This would break
1622 * potential secondary SAs for the same address using a
1623 * different prot/port. */
1624 sa->sel.proto = 0;
1625 sa->sel.dport = sa->sel.dport_mask = 0;
1626 sa->sel.sport = sa->sel.sport_mask = 0;
1627 }
1628 }
1629 break;
1630 default:
1631 break;
1632 }
1633 if (id->proto == IPPROTO_AH && sa->family == AF_INET)
1634 { /* use alignment to 4 bytes for IPv4 instead of the incorrect 8 byte
1635 * alignment that's used by default but is only valid for IPv6 */
1636 sa->flags |= XFRM_STATE_ALIGN4;
1637 }
1638
1639 sa->reqid = data->reqid;
1640 sa->lft.soft_byte_limit = XFRM_LIMIT(data->lifetime->bytes.rekey);
1641 sa->lft.hard_byte_limit = XFRM_LIMIT(data->lifetime->bytes.life);
1642 sa->lft.soft_packet_limit = XFRM_LIMIT(data->lifetime->packets.rekey);
1643 sa->lft.hard_packet_limit = XFRM_LIMIT(data->lifetime->packets.life);
1644 /* we use lifetimes since added, not since used */
1645 sa->lft.soft_add_expires_seconds = data->lifetime->time.rekey;
1646 sa->lft.hard_add_expires_seconds = data->lifetime->time.life;
1647 sa->lft.soft_use_expires_seconds = 0;
1648 sa->lft.hard_use_expires_seconds = 0;
1649
1650 switch (data->enc_alg)
1651 {
1652 case ENCR_UNDEFINED:
1653 /* no encryption */
1654 break;
1655 case ENCR_AES_CCM_ICV16:
1656 case ENCR_AES_GCM_ICV16:
1657 case ENCR_NULL_AUTH_AES_GMAC:
1658 case ENCR_CAMELLIA_CCM_ICV16:
1659 case ENCR_CHACHA20_POLY1305:
1660 icv_size += 32;
1661 /* FALL */
1662 case ENCR_AES_CCM_ICV12:
1663 case ENCR_AES_GCM_ICV12:
1664 case ENCR_CAMELLIA_CCM_ICV12:
1665 icv_size += 32;
1666 /* FALL */
1667 case ENCR_AES_CCM_ICV8:
1668 case ENCR_AES_GCM_ICV8:
1669 case ENCR_CAMELLIA_CCM_ICV8:
1670 {
1671 struct xfrm_algo_aead *algo;
1672
1673 alg_name = lookup_algorithm(ENCRYPTION_ALGORITHM, data->enc_alg);
1674 if (alg_name == NULL)
1675 {
1676 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1677 encryption_algorithm_names, data->enc_alg);
1678 goto failed;
1679 }
1680 DBG2(DBG_KNL, " using encryption algorithm %N with key size %d",
1681 encryption_algorithm_names, data->enc_alg,
1682 data->enc_key.len * 8);
1683
1684 algo = netlink_reserve(hdr, sizeof(request), XFRMA_ALG_AEAD,
1685 sizeof(*algo) + data->enc_key.len);
1686 if (!algo)
1687 {
1688 goto failed;
1689 }
1690 algo->alg_key_len = data->enc_key.len * 8;
1691 algo->alg_icv_len = icv_size;
1692 strncpy(algo->alg_name, alg_name, sizeof(algo->alg_name));
1693 algo->alg_name[sizeof(algo->alg_name) - 1] = '\0';
1694 memcpy(algo->alg_key, data->enc_key.ptr, data->enc_key.len);
1695 break;
1696 }
1697 default:
1698 {
1699 struct xfrm_algo *algo;
1700
1701 alg_name = lookup_algorithm(ENCRYPTION_ALGORITHM, data->enc_alg);
1702 if (alg_name == NULL)
1703 {
1704 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1705 encryption_algorithm_names, data->enc_alg);
1706 goto failed;
1707 }
1708 DBG2(DBG_KNL, " using encryption algorithm %N with key size %d",
1709 encryption_algorithm_names, data->enc_alg,
1710 data->enc_key.len * 8);
1711
1712 algo = netlink_reserve(hdr, sizeof(request), XFRMA_ALG_CRYPT,
1713 sizeof(*algo) + data->enc_key.len);
1714 if (!algo)
1715 {
1716 goto failed;
1717 }
1718 algo->alg_key_len = data->enc_key.len * 8;
1719 strncpy(algo->alg_name, alg_name, sizeof(algo->alg_name));
1720 algo->alg_name[sizeof(algo->alg_name) - 1] = '\0';
1721 memcpy(algo->alg_key, data->enc_key.ptr, data->enc_key.len);
1722 }
1723 }
1724
1725 if (data->int_alg != AUTH_UNDEFINED)
1726 {
1727 u_int trunc_len = 0;
1728
1729 alg_name = lookup_algorithm(INTEGRITY_ALGORITHM, data->int_alg);
1730 if (alg_name == NULL)
1731 {
1732 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1733 integrity_algorithm_names, data->int_alg);
1734 goto failed;
1735 }
1736 DBG2(DBG_KNL, " using integrity algorithm %N with key size %d",
1737 integrity_algorithm_names, data->int_alg, data->int_key.len * 8);
1738
1739 switch (data->int_alg)
1740 {
1741 case AUTH_HMAC_MD5_128:
1742 case AUTH_HMAC_SHA2_256_128:
1743 trunc_len = 128;
1744 break;
1745 case AUTH_HMAC_SHA1_160:
1746 trunc_len = 160;
1747 break;
1748 default:
1749 break;
1750 }
1751
1752 if (trunc_len)
1753 {
1754 struct xfrm_algo_auth* algo;
1755
1756 /* the kernel uses SHA256 with 96 bit truncation by default,
1757 * use specified truncation size supported by newer kernels.
1758 * also use this for untruncated MD5 and SHA1. */
1759 algo = netlink_reserve(hdr, sizeof(request), XFRMA_ALG_AUTH_TRUNC,
1760 sizeof(*algo) + data->int_key.len);
1761 if (!algo)
1762 {
1763 goto failed;
1764 }
1765 algo->alg_key_len = data->int_key.len * 8;
1766 algo->alg_trunc_len = trunc_len;
1767 strncpy(algo->alg_name, alg_name, sizeof(algo->alg_name));
1768 algo->alg_name[sizeof(algo->alg_name) - 1] = '\0';
1769 memcpy(algo->alg_key, data->int_key.ptr, data->int_key.len);
1770 }
1771 else
1772 {
1773 struct xfrm_algo* algo;
1774
1775 algo = netlink_reserve(hdr, sizeof(request), XFRMA_ALG_AUTH,
1776 sizeof(*algo) + data->int_key.len);
1777 if (!algo)
1778 {
1779 goto failed;
1780 }
1781 algo->alg_key_len = data->int_key.len * 8;
1782 strncpy(algo->alg_name, alg_name, sizeof(algo->alg_name));
1783 algo->alg_name[sizeof(algo->alg_name) - 1] = '\0';
1784 memcpy(algo->alg_key, data->int_key.ptr, data->int_key.len);
1785 }
1786 }
1787
1788 if (ipcomp != IPCOMP_NONE)
1789 {
1790 struct xfrm_algo* algo;
1791
1792 alg_name = lookup_algorithm(COMPRESSION_ALGORITHM, ipcomp);
1793 if (alg_name == NULL)
1794 {
1795 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1796 ipcomp_transform_names, ipcomp);
1797 goto failed;
1798 }
1799 DBG2(DBG_KNL, " using compression algorithm %N",
1800 ipcomp_transform_names, ipcomp);
1801
1802 algo = netlink_reserve(hdr, sizeof(request), XFRMA_ALG_COMP,
1803 sizeof(*algo));
1804 if (!algo)
1805 {
1806 goto failed;
1807 }
1808 algo->alg_key_len = 0;
1809 strncpy(algo->alg_name, alg_name, sizeof(algo->alg_name));
1810 algo->alg_name[sizeof(algo->alg_name) - 1] = '\0';
1811 }
1812
1813 if (data->encap)
1814 {
1815 struct xfrm_encap_tmpl *tmpl;
1816
1817 tmpl = netlink_reserve(hdr, sizeof(request), XFRMA_ENCAP, sizeof(*tmpl));
1818 if (!tmpl)
1819 {
1820 goto failed;
1821 }
1822 tmpl->encap_type = UDP_ENCAP_ESPINUDP;
1823 tmpl->encap_sport = htons(id->src->get_port(id->src));
1824 tmpl->encap_dport = htons(id->dst->get_port(id->dst));
1825 memset(&tmpl->encap_oa, 0, sizeof (xfrm_address_t));
1826 /* encap_oa could probably be derived from the
1827 * traffic selectors [rfc4306, p39]. In the netlink kernel
1828 * implementation pluto does the same as we do here but it uses
1829 * encap_oa in the pfkey implementation.
1830 * BUT as /usr/src/linux/net/key/af_key.c indicates the kernel ignores
1831 * it anyway
1832 * -> does that mean that NAT-T encap doesn't work in transport mode?
1833 * No. The reason the kernel ignores NAT-OA is that it recomputes
1834 * (or, rather, just ignores) the checksum. If packets pass the IPsec
1835 * checks it marks them "checksum ok" so OA isn't needed. */
1836 }
1837
1838 if (!add_mark(hdr, sizeof(request), id->mark))
1839 {
1840 goto failed;
1841 }
1842
1843 if (data->tfc && id->proto == IPPROTO_ESP && mode == MODE_TUNNEL)
1844 { /* the kernel supports TFC padding only for tunnel mode ESP SAs */
1845 uint32_t *tfcpad;
1846
1847 tfcpad = netlink_reserve(hdr, sizeof(request), XFRMA_TFCPAD,
1848 sizeof(*tfcpad));
1849 if (!tfcpad)
1850 {
1851 goto failed;
1852 }
1853 *tfcpad = data->tfc;
1854 }
1855
1856 if (id->proto != IPPROTO_COMP)
1857 {
1858 /* generally, we don't need a replay window for outbound SAs, however,
1859 * when using ESN the kernel rejects the attribute if it is 0 */
1860 if (!data->inbound && data->replay_window)
1861 {
1862 data->replay_window = data->esn ? 1 : 0;
1863 }
1864 if (data->replay_window != 0 && (data->esn || data->replay_window > 32))
1865 {
1866 /* for ESN or larger replay windows we need the new
1867 * XFRMA_REPLAY_ESN_VAL attribute to configure a bitmap */
1868 struct xfrm_replay_state_esn *replay;
1869 uint32_t bmp_size;
1870
1871 bmp_size = round_up(data->replay_window, sizeof(uint32_t) * 8) / 8;
1872 replay = netlink_reserve(hdr, sizeof(request), XFRMA_REPLAY_ESN_VAL,
1873 sizeof(*replay) + bmp_size);
1874 if (!replay)
1875 {
1876 goto failed;
1877 }
1878 /* bmp_len contains number uf __u32's */
1879 replay->bmp_len = bmp_size / sizeof(uint32_t);
1880 replay->replay_window = data->replay_window;
1881 DBG2(DBG_KNL, " using replay window of %u packets",
1882 data->replay_window);
1883
1884 if (data->esn)
1885 {
1886 DBG2(DBG_KNL, " using extended sequence numbers (ESN)");
1887 sa->flags |= XFRM_STATE_ESN;
1888 }
1889 }
1890 else
1891 {
1892 DBG2(DBG_KNL, " using replay window of %u packets",
1893 data->replay_window);
1894 sa->replay_window = data->replay_window;
1895 }
1896
1897 DBG2(DBG_KNL, " HW offload: %N", hw_offload_names, data->hw_offload);
1898 if (!config_hw_offload(id, data, hdr, sizeof(request)))
1899 {
1900 DBG1(DBG_KNL, "failed to configure HW offload");
1901 goto failed;
1902 }
1903 }
1904
1905 status = this->socket_xfrm->send_ack(this->socket_xfrm, hdr);
1906 if (status == NOT_FOUND && data->update)
1907 {
1908 DBG1(DBG_KNL, "allocated SPI not found anymore, try to add SAD entry");
1909 hdr->nlmsg_type = XFRM_MSG_NEWSA;
1910 status = this->socket_xfrm->send_ack(this->socket_xfrm, hdr);
1911 }
1912
1913 if (status != SUCCESS)
1914 {
1915 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x%s (%N)", ntohl(id->spi),
1916 markstr, status_names, status);
1917 status = FAILED;
1918 goto failed;
1919 }
1920
1921 status = SUCCESS;
1922
1923 failed:
1924 memwipe(&request, sizeof(request));
1925 return status;
1926 }
1927
1928 /**
1929 * Get the ESN replay state (i.e. sequence numbers) of an SA.
1930 *
1931 * Allocates into one the replay state structure we get from the kernel.
1932 */
1933 static void get_replay_state(private_kernel_netlink_ipsec_t *this,
1934 kernel_ipsec_sa_id_t *sa,
1935 struct xfrm_replay_state_esn **replay_esn,
1936 uint32_t *replay_esn_len,
1937 struct xfrm_replay_state **replay,
1938 struct xfrm_lifetime_cur **lifetime)
1939 {
1940 netlink_buf_t request;
1941 struct nlmsghdr *hdr, *out = NULL;
1942 struct xfrm_aevent_id *out_aevent = NULL, *aevent_id;
1943 size_t len;
1944 struct rtattr *rta;
1945 size_t rtasize;
1946
1947 memset(&request, 0, sizeof(request));
1948
1949 DBG2(DBG_KNL, "querying replay state from SAD entry with SPI %.8x",
1950 ntohl(sa->spi));
1951
1952 hdr = &request.hdr;
1953 hdr->nlmsg_flags = NLM_F_REQUEST;
1954 hdr->nlmsg_type = XFRM_MSG_GETAE;
1955 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_aevent_id));
1956
1957 aevent_id = NLMSG_DATA(hdr);
1958 aevent_id->flags = XFRM_AE_RVAL;
1959
1960 host2xfrm(sa->dst, &aevent_id->sa_id.daddr);
1961 aevent_id->sa_id.spi = sa->spi;
1962 aevent_id->sa_id.proto = sa->proto;
1963 aevent_id->sa_id.family = sa->dst->get_family(sa->dst);
1964
1965 if (!add_mark(hdr, sizeof(request), sa->mark))
1966 {
1967 return;
1968 }
1969
1970 if (this->socket_xfrm->send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
1971 {
1972 hdr = out;
1973 while (NLMSG_OK(hdr, len))
1974 {
1975 switch (hdr->nlmsg_type)
1976 {
1977 case XFRM_MSG_NEWAE:
1978 {
1979 out_aevent = NLMSG_DATA(hdr);
1980 break;
1981 }
1982 case NLMSG_ERROR:
1983 {
1984 struct nlmsgerr *err = NLMSG_DATA(hdr);
1985 DBG1(DBG_KNL, "querying replay state from SAD entry "
1986 "failed: %s (%d)", strerror(-err->error), -err->error);
1987 break;
1988 }
1989 default:
1990 hdr = NLMSG_NEXT(hdr, len);
1991 continue;
1992 case NLMSG_DONE:
1993 break;
1994 }
1995 break;
1996 }
1997 }
1998
1999 if (out_aevent)
2000 {
2001 rta = XFRM_RTA(out, struct xfrm_aevent_id);
2002 rtasize = XFRM_PAYLOAD(out, struct xfrm_aevent_id);
2003 while (RTA_OK(rta, rtasize))
2004 {
2005 if (rta->rta_type == XFRMA_LTIME_VAL &&
2006 RTA_PAYLOAD(rta) == sizeof(**lifetime))
2007 {
2008 free(*lifetime);
2009 *lifetime = malloc(RTA_PAYLOAD(rta));
2010 memcpy(*lifetime, RTA_DATA(rta), RTA_PAYLOAD(rta));
2011 }
2012 if (rta->rta_type == XFRMA_REPLAY_VAL &&
2013 RTA_PAYLOAD(rta) == sizeof(**replay))
2014 {
2015 free(*replay);
2016 *replay = malloc(RTA_PAYLOAD(rta));
2017 memcpy(*replay, RTA_DATA(rta), RTA_PAYLOAD(rta));
2018 }
2019 if (rta->rta_type == XFRMA_REPLAY_ESN_VAL &&
2020 RTA_PAYLOAD(rta) >= sizeof(**replay_esn))
2021 {
2022 free(*replay_esn);
2023 *replay_esn = malloc(RTA_PAYLOAD(rta));
2024 *replay_esn_len = RTA_PAYLOAD(rta);
2025 memcpy(*replay_esn, RTA_DATA(rta), RTA_PAYLOAD(rta));
2026 }
2027 rta = RTA_NEXT(rta, rtasize);
2028 }
2029 }
2030 free(out);
2031 }
2032
2033 METHOD(kernel_ipsec_t, query_sa, status_t,
2034 private_kernel_netlink_ipsec_t *this, kernel_ipsec_sa_id_t *id,
2035 kernel_ipsec_query_sa_t *data, uint64_t *bytes, uint64_t *packets,
2036 time_t *time)
2037 {
2038 netlink_buf_t request;
2039 struct nlmsghdr *out = NULL, *hdr;
2040 struct xfrm_usersa_id *sa_id;
2041 struct xfrm_usersa_info *sa = NULL;
2042 status_t status = FAILED;
2043 size_t len;
2044 char markstr[32] = "";
2045
2046 memset(&request, 0, sizeof(request));
2047 format_mark(markstr, sizeof(markstr), id->mark);
2048
2049 DBG2(DBG_KNL, "querying SAD entry with SPI %.8x%s", ntohl(id->spi),
2050 markstr);
2051
2052 hdr = &request.hdr;
2053 hdr->nlmsg_flags = NLM_F_REQUEST;
2054 hdr->nlmsg_type = XFRM_MSG_GETSA;
2055 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_id));
2056
2057 sa_id = NLMSG_DATA(hdr);
2058 host2xfrm(id->dst, &sa_id->daddr);
2059 sa_id->spi = id->spi;
2060 sa_id->proto = id->proto;
2061 sa_id->family = id->dst->get_family(id->dst);
2062
2063 if (!add_mark(hdr, sizeof(request), id->mark))
2064 {
2065 return FAILED;
2066 }
2067
2068 if (this->socket_xfrm->send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
2069 {
2070 hdr = out;
2071 while (NLMSG_OK(hdr, len))
2072 {
2073 switch (hdr->nlmsg_type)
2074 {
2075 case XFRM_MSG_NEWSA:
2076 {
2077 sa = NLMSG_DATA(hdr);
2078 break;
2079 }
2080 case NLMSG_ERROR:
2081 {
2082 struct nlmsgerr *err = NLMSG_DATA(hdr);
2083
2084 DBG1(DBG_KNL, "querying SAD entry with SPI %.8x%s failed: "
2085 "%s (%d)", ntohl(id->spi), markstr,
2086 strerror(-err->error), -err->error);
2087 break;
2088 }
2089 default:
2090 hdr = NLMSG_NEXT(hdr, len);
2091 continue;
2092 case NLMSG_DONE:
2093 break;
2094 }
2095 break;
2096 }
2097 }
2098
2099 if (sa == NULL)
2100 {
2101 DBG2(DBG_KNL, "unable to query SAD entry with SPI %.8x%s",
2102 ntohl(id->spi), markstr);
2103 }
2104 else
2105 {
2106 if (bytes)
2107 {
2108 *bytes = sa->curlft.bytes;
2109 }
2110 if (packets)
2111 {
2112 *packets = sa->curlft.packets;
2113 }
2114 if (time)
2115 { /* curlft contains an "use" time, but that contains a timestamp
2116 * of the first use, not the last. Last use time must be queried
2117 * on the policy on Linux */
2118 *time = 0;
2119 }
2120 status = SUCCESS;
2121 }
2122 memwipe(out, len);
2123 free(out);
2124 return status;
2125 }
2126
2127 METHOD(kernel_ipsec_t, del_sa, status_t,
2128 private_kernel_netlink_ipsec_t *this, kernel_ipsec_sa_id_t *id,
2129 kernel_ipsec_del_sa_t *data)
2130 {
2131 netlink_buf_t request;
2132 struct nlmsghdr *hdr;
2133 struct xfrm_usersa_id *sa_id;
2134 char markstr[32] = "";
2135
2136 /* if IPComp was used, we first delete the additional IPComp SA */
2137 if (data->cpi)
2138 {
2139 kernel_ipsec_sa_id_t ipcomp_id = {
2140 .src = id->src,
2141 .dst = id->dst,
2142 .spi = htonl(ntohs(data->cpi)),
2143 .proto = IPPROTO_COMP,
2144 .mark = id->mark,
2145 };
2146 kernel_ipsec_del_sa_t ipcomp = {};
2147 del_sa(this, &ipcomp_id, &ipcomp);
2148 }
2149
2150 memset(&request, 0, sizeof(request));
2151 format_mark(markstr, sizeof(markstr), id->mark);
2152
2153 DBG2(DBG_KNL, "deleting SAD entry with SPI %.8x%s", ntohl(id->spi),
2154 markstr);
2155
2156 hdr = &request.hdr;
2157 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2158 hdr->nlmsg_type = XFRM_MSG_DELSA;
2159 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_id));
2160
2161 sa_id = NLMSG_DATA(hdr);
2162 host2xfrm(id->dst, &sa_id->daddr);
2163 sa_id->spi = id->spi;
2164 sa_id->proto = id->proto;
2165 sa_id->family = id->dst->get_family(id->dst);
2166
2167 if (!add_mark(hdr, sizeof(request), id->mark))
2168 {
2169 return FAILED;
2170 }
2171
2172 switch (this->socket_xfrm->send_ack(this->socket_xfrm, hdr))
2173 {
2174 case SUCCESS:
2175 DBG2(DBG_KNL, "deleted SAD entry with SPI %.8x%s",
2176 ntohl(id->spi), markstr);
2177 return SUCCESS;
2178 case NOT_FOUND:
2179 return NOT_FOUND;
2180 default:
2181 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x%s",
2182 ntohl(id->spi), markstr);
2183 return FAILED;
2184 }
2185 }
2186
2187 METHOD(kernel_ipsec_t, update_sa, status_t,
2188 private_kernel_netlink_ipsec_t *this, kernel_ipsec_sa_id_t *id,
2189 kernel_ipsec_update_sa_t *data)
2190 {
2191 netlink_buf_t request;
2192 struct nlmsghdr *hdr, *out_hdr = NULL, *out = NULL;
2193 struct xfrm_usersa_id *sa_id;
2194 struct xfrm_usersa_info *sa;
2195 size_t len;
2196 struct rtattr *rta;
2197 size_t rtasize;
2198 struct xfrm_encap_tmpl* encap = NULL;
2199 struct xfrm_replay_state *replay = NULL;
2200 struct xfrm_replay_state_esn *replay_esn = NULL;
2201 struct xfrm_lifetime_cur *lifetime = NULL;
2202 uint32_t replay_esn_len = 0;
2203 kernel_ipsec_del_sa_t del = { 0 };
2204 status_t status = FAILED;
2205 char markstr[32] = "";
2206
2207 /* if IPComp is used, we first update the IPComp SA */
2208 if (data->cpi)
2209 {
2210 kernel_ipsec_sa_id_t ipcomp_id = {
2211 .src = id->src,
2212 .dst = id->dst,
2213 .spi = htonl(ntohs(data->cpi)),
2214 .proto = IPPROTO_COMP,
2215 .mark = id->mark,
2216 };
2217 kernel_ipsec_update_sa_t ipcomp = {
2218 .new_src = data->new_src,
2219 .new_dst = data->new_dst,
2220 };
2221 update_sa(this, &ipcomp_id, &ipcomp);
2222 }
2223
2224 memset(&request, 0, sizeof(request));
2225 format_mark(markstr, sizeof(markstr), id->mark);
2226
2227 DBG2(DBG_KNL, "querying SAD entry with SPI %.8x%s for update",
2228 ntohl(id->spi), markstr);
2229
2230 /* query the existing SA first */
2231 hdr = &request.hdr;
2232 hdr->nlmsg_flags = NLM_F_REQUEST;
2233 hdr->nlmsg_type = XFRM_MSG_GETSA;
2234 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_id));
2235
2236 sa_id = NLMSG_DATA(hdr);
2237 host2xfrm(id->dst, &sa_id->daddr);
2238 sa_id->spi = id->spi;
2239 sa_id->proto = id->proto;
2240 sa_id->family = id->dst->get_family(id->dst);
2241
2242 if (!add_mark(hdr, sizeof(request), id->mark))
2243 {
2244 return FAILED;
2245 }
2246
2247 if (this->socket_xfrm->send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
2248 {
2249 hdr = out;
2250 while (NLMSG_OK(hdr, len))
2251 {
2252 switch (hdr->nlmsg_type)
2253 {
2254 case XFRM_MSG_NEWSA:
2255 {
2256 out_hdr = hdr;
2257 break;
2258 }
2259 case NLMSG_ERROR:
2260 {
2261 struct nlmsgerr *err = NLMSG_DATA(hdr);
2262 DBG1(DBG_KNL, "querying SAD entry failed: %s (%d)",
2263 strerror(-err->error), -err->error);
2264 break;
2265 }
2266 default:
2267 hdr = NLMSG_NEXT(hdr, len);
2268 continue;
2269 case NLMSG_DONE:
2270 break;
2271 }
2272 break;
2273 }
2274 }
2275 if (!out_hdr)
2276 {
2277 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x%s",
2278 ntohl(id->spi), markstr);
2279 goto failed;
2280 }
2281
2282 get_replay_state(this, id, &replay_esn, &replay_esn_len, &replay,
2283 &lifetime);
2284
2285 /* delete the old SA (without affecting the IPComp SA) */
2286 if (del_sa(this, id, &del) != SUCCESS)
2287 {
2288 DBG1(DBG_KNL, "unable to delete old SAD entry with SPI %.8x%s",
2289 ntohl(id->spi), markstr);
2290 goto failed;
2291 }
2292
2293 DBG2(DBG_KNL, "updating SAD entry with SPI %.8x%s from %#H..%#H to "
2294 "%#H..%#H", ntohl(id->spi), markstr, id->src, id->dst, data->new_src,
2295 data->new_dst);
2296 /* copy over the SA from out to request */
2297 hdr = &request.hdr;
2298 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2299 hdr->nlmsg_type = XFRM_MSG_NEWSA;
2300 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_info));
2301 sa = NLMSG_DATA(hdr);
2302 memcpy(sa, NLMSG_DATA(out_hdr), sizeof(struct xfrm_usersa_info));
2303 sa->family = data->new_dst->get_family(data->new_dst);
2304
2305 if (!id->src->ip_equals(id->src, data->new_src))
2306 {
2307 host2xfrm(data->new_src, &sa->saddr);
2308 }
2309 if (!id->dst->ip_equals(id->dst, data->new_dst))
2310 {
2311 host2xfrm(data->new_dst, &sa->id.daddr);
2312 }
2313
2314 rta = XFRM_RTA(out_hdr, struct xfrm_usersa_info);
2315 rtasize = XFRM_PAYLOAD(out_hdr, struct xfrm_usersa_info);
2316 while (RTA_OK(rta, rtasize))
2317 {
2318 /* copy all attributes, but not XFRMA_ENCAP if we are disabling it */
2319 if (rta->rta_type != XFRMA_ENCAP || data->new_encap)
2320 {
2321 if (rta->rta_type == XFRMA_ENCAP)
2322 { /* update encap tmpl */
2323 encap = RTA_DATA(rta);
2324 encap->encap_sport = ntohs(data->new_src->get_port(data->new_src));
2325 encap->encap_dport = ntohs(data->new_dst->get_port(data->new_dst));
2326 }
2327 if (rta->rta_type == XFRMA_OFFLOAD_DEV)
2328 { /* update offload device */
2329 struct xfrm_user_offload *offload;
2330 host_t *local;
2331 char *ifname;
2332
2333 offload = RTA_DATA(rta);
2334 local = offload->flags & XFRM_OFFLOAD_INBOUND ? data->new_dst
2335 : data->new_src;
2336
2337 if (charon->kernel->get_interface(charon->kernel, local,
2338 &ifname))
2339 {
2340 offload->ifindex = if_nametoindex(ifname);
2341 if (local->get_family(local) == AF_INET6)
2342 {
2343 offload->flags |= XFRM_OFFLOAD_IPV6;
2344 }
2345 else
2346 {
2347 offload->flags &= ~XFRM_OFFLOAD_IPV6;
2348 }
2349 free(ifname);
2350 }
2351 }
2352 netlink_add_attribute(hdr, rta->rta_type,
2353 chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta)),
2354 sizeof(request));
2355 }
2356 rta = RTA_NEXT(rta, rtasize);
2357 }
2358
2359 if (encap == NULL && data->new_encap)
2360 { /* add tmpl if we are enabling it */
2361 encap = netlink_reserve(hdr, sizeof(request), XFRMA_ENCAP,
2362 sizeof(*encap));
2363 if (!encap)
2364 {
2365 goto failed;
2366 }
2367 encap->encap_type = UDP_ENCAP_ESPINUDP;
2368 encap->encap_sport = ntohs(data->new_src->get_port(data->new_src));
2369 encap->encap_dport = ntohs(data->new_dst->get_port(data->new_dst));
2370 memset(&encap->encap_oa, 0, sizeof (xfrm_address_t));
2371 }
2372
2373 if (replay_esn)
2374 {
2375 struct xfrm_replay_state_esn *state;
2376
2377 state = netlink_reserve(hdr, sizeof(request), XFRMA_REPLAY_ESN_VAL,
2378 replay_esn_len);
2379 if (!state)
2380 {
2381 goto failed;
2382 }
2383 memcpy(state, replay_esn, replay_esn_len);
2384 }
2385 else if (replay)
2386 {
2387 struct xfrm_replay_state *state;
2388
2389 state = netlink_reserve(hdr, sizeof(request), XFRMA_REPLAY_VAL,
2390 sizeof(*state));
2391 if (!state)
2392 {
2393 goto failed;
2394 }
2395 memcpy(state, replay, sizeof(*state));
2396 }
2397 else
2398 {
2399 DBG1(DBG_KNL, "unable to copy replay state from old SAD entry with "
2400 "SPI %.8x%s", ntohl(id->spi), markstr);
2401 }
2402 if (lifetime)
2403 {
2404 struct xfrm_lifetime_cur *state;
2405
2406 state = netlink_reserve(hdr, sizeof(request), XFRMA_LTIME_VAL,
2407 sizeof(*state));
2408 if (!state)
2409 {
2410 goto failed;
2411 }
2412 memcpy(state, lifetime, sizeof(*state));
2413 }
2414 else
2415 {
2416 DBG1(DBG_KNL, "unable to copy usage stats from old SAD entry with "
2417 "SPI %.8x%s", ntohl(id->spi), markstr);
2418 }
2419
2420 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
2421 {
2422 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x%s",
2423 ntohl(id->spi), markstr);
2424 goto failed;
2425 }
2426
2427 status = SUCCESS;
2428 failed:
2429 free(replay);
2430 free(replay_esn);
2431 free(lifetime);
2432 memwipe(out, len);
2433 memwipe(&request, sizeof(request));
2434 free(out);
2435
2436 return status;
2437 }
2438
2439 METHOD(kernel_ipsec_t, flush_sas, status_t,
2440 private_kernel_netlink_ipsec_t *this)
2441 {
2442 netlink_buf_t request;
2443 struct nlmsghdr *hdr;
2444 struct xfrm_usersa_flush *flush;
2445 struct {
2446 uint8_t proto;
2447 char *name;
2448 } protos[] = {
2449 { IPPROTO_AH, "AH" },
2450 { IPPROTO_ESP, "ESP" },
2451 { IPPROTO_COMP, "IPComp" },
2452 };
2453 int i;
2454
2455 memset(&request, 0, sizeof(request));
2456
2457 hdr = &request.hdr;
2458 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2459 hdr->nlmsg_type = XFRM_MSG_FLUSHSA;
2460 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_flush));
2461
2462 flush = NLMSG_DATA(hdr);
2463
2464 for (i = 0; i < countof(protos); i++)
2465 {
2466 DBG2(DBG_KNL, "flushing all %s SAD entries", protos[i].name);
2467
2468 flush->proto = protos[i].proto;
2469
2470 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
2471 {
2472 DBG1(DBG_KNL, "unable to flush %s SAD entries", protos[i].name);
2473 return FAILED;
2474 }
2475 }
2476 return SUCCESS;
2477 }
2478
2479 /**
2480 * Unlock the mutex and signal waiting threads
2481 */
2482 static void policy_change_done(private_kernel_netlink_ipsec_t *this,
2483 policy_entry_t *policy)
2484 {
2485 policy->working = FALSE;
2486 if (policy->waiting)
2487 { /* don't need to wake threads waiting for other policies */
2488 this->condvar->broadcast(this->condvar);
2489 }
2490 this->mutex->unlock(this->mutex);
2491 }
2492
2493 /**
2494 * Install a route for the given policy if enabled and required
2495 */
2496 static void install_route(private_kernel_netlink_ipsec_t *this,
2497 policy_entry_t *policy, policy_sa_t *mapping, ipsec_sa_t *ipsec)
2498 {
2499 policy_sa_out_t *out = (policy_sa_out_t*)mapping;
2500 route_entry_t *route;
2501 host_t *iface;
2502
2503 INIT(route,
2504 .prefixlen = policy->sel.prefixlen_d,
2505 );
2506
2507 if (charon->kernel->get_address_by_ts(charon->kernel, out->src_ts,
2508 &route->src_ip, NULL) == SUCCESS)
2509 {
2510 if (!ipsec->dst->is_anyaddr(ipsec->dst))
2511 {
2512 route->gateway = charon->kernel->get_nexthop(charon->kernel,
2513 ipsec->dst, -1, ipsec->src,
2514 &route->if_name);
2515 }
2516 else
2517 { /* for shunt policies */
2518 iface = xfrm2host(policy->sel.family, &policy->sel.daddr, 0);
2519 route->gateway = charon->kernel->get_nexthop(charon->kernel,
2520 iface, policy->sel.prefixlen_d,
2521 route->src_ip, &route->if_name);
2522 iface->destroy(iface);
2523 }
2524 route->dst_net = chunk_alloc(policy->sel.family == AF_INET ? 4 : 16);
2525 memcpy(route->dst_net.ptr, &policy->sel.daddr, route->dst_net.len);
2526
2527 /* get the interface to install the route for, if we haven't one yet.
2528 * If we have a local address, use it. Otherwise (for shunt policies)
2529 * use the route's source address. */
2530 if (!route->if_name)
2531 {
2532 iface = ipsec->src;
2533 if (iface->is_anyaddr(iface))
2534 {
2535 iface = route->src_ip;
2536 }
2537 if (!charon->kernel->get_interface(charon->kernel, iface,
2538 &route->if_name))
2539 {
2540 route_entry_destroy(route);
2541 return;
2542 }
2543 }
2544 if (policy->route)
2545 {
2546 route_entry_t *old = policy->route;
2547 if (route_entry_equals(old, route))
2548 {
2549 route_entry_destroy(route);
2550 return;
2551 }
2552 /* uninstall previously installed route */
2553 if (charon->kernel->del_route(charon->kernel, old->dst_net,
2554 old->prefixlen, old->gateway,
2555 old->src_ip, old->if_name) != SUCCESS)
2556 {
2557 DBG1(DBG_KNL, "error uninstalling route installed with policy "
2558 "%R === %R %N", out->src_ts, out->dst_ts, policy_dir_names,
2559 policy->direction);
2560 }
2561 route_entry_destroy(old);
2562 policy->route = NULL;
2563 }
2564
2565 DBG2(DBG_KNL, "installing route: %R via %H src %H dev %s", out->dst_ts,
2566 route->gateway, route->src_ip, route->if_name);
2567 switch (charon->kernel->add_route(charon->kernel, route->dst_net,
2568 route->prefixlen, route->gateway,
2569 route->src_ip, route->if_name))
2570 {
2571 default:
2572 DBG1(DBG_KNL, "unable to install source route for %H",
2573 route->src_ip);
2574 /* FALL */
2575 case ALREADY_DONE:
2576 /* route exists, do not uninstall */
2577 route_entry_destroy(route);
2578 break;
2579 case SUCCESS:
2580 /* cache the installed route */
2581 policy->route = route;
2582 break;
2583 }
2584 }
2585 else
2586 {
2587 free(route);
2588 }
2589 }
2590
2591 /**
2592 * Add or update a policy in the kernel.
2593 *
2594 * Note: The mutex has to be locked when entering this function
2595 * and is unlocked here in any case.
2596 */
2597 static status_t add_policy_internal(private_kernel_netlink_ipsec_t *this,
2598 policy_entry_t *policy, policy_sa_t *mapping, bool update)
2599 {
2600 netlink_buf_t request;
2601 policy_entry_t clone;
2602 ipsec_sa_t *ipsec = mapping->sa;
2603 struct xfrm_userpolicy_info *policy_info;
2604 struct nlmsghdr *hdr;
2605 status_t status;
2606 int i;
2607
2608 /* clone the policy so we are able to check it out again later */
2609 memcpy(&clone, policy, sizeof(policy_entry_t));
2610
2611 memset(&request, 0, sizeof(request));
2612 hdr = &request.hdr;
2613 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2614 hdr->nlmsg_type = update ? XFRM_MSG_UPDPOLICY : XFRM_MSG_NEWPOLICY;
2615 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_info));
2616
2617 policy_info = NLMSG_DATA(hdr);
2618 policy_info->sel = policy->sel;
2619 policy_info->dir = policy->direction;
2620
2621 /* calculate priority based on selector size, small size = high prio */
2622 policy_info->priority = mapping->priority;
2623 policy_info->action = mapping->type != POLICY_DROP ? XFRM_POLICY_ALLOW
2624 : XFRM_POLICY_BLOCK;
2625 policy_info->share = XFRM_SHARE_ANY;
2626
2627 /* policies don't expire */
2628 policy_info->lft.soft_byte_limit = XFRM_INF;
2629 policy_info->lft.soft_packet_limit = XFRM_INF;
2630 policy_info->lft.hard_byte_limit = XFRM_INF;
2631 policy_info->lft.hard_packet_limit = XFRM_INF;
2632 policy_info->lft.soft_add_expires_seconds = 0;
2633 policy_info->lft.hard_add_expires_seconds = 0;
2634 policy_info->lft.soft_use_expires_seconds = 0;
2635 policy_info->lft.hard_use_expires_seconds = 0;
2636
2637 if (mapping->type == POLICY_IPSEC && ipsec->cfg.reqid)
2638 {
2639 struct xfrm_user_tmpl *tmpl;
2640 struct {
2641 uint8_t proto;
2642 uint32_t spi;
2643 bool use;
2644 } protos[] = {
2645 { IPPROTO_COMP, htonl(ntohs(ipsec->cfg.ipcomp.cpi)),
2646 ipsec->cfg.ipcomp.transform != IPCOMP_NONE },
2647 { IPPROTO_ESP, ipsec->cfg.esp.spi, ipsec->cfg.esp.use },
2648 { IPPROTO_AH, ipsec->cfg.ah.spi, ipsec->cfg.ah.use },
2649 };
2650 ipsec_mode_t proto_mode = ipsec->cfg.mode;
2651 int count = 0;
2652
2653 for (i = 0; i < countof(protos); i++)
2654 {
2655 if (protos[i].use)
2656 {
2657 count++;
2658 }
2659 }
2660 tmpl = netlink_reserve(hdr, sizeof(request), XFRMA_TMPL,
2661 count * sizeof(*tmpl));
2662 if (!tmpl)
2663 {
2664 policy_change_done(this, policy);
2665 return FAILED;
2666 }
2667
2668 for (i = 0; i < countof(protos); i++)
2669 {
2670 if (!protos[i].use)
2671 {
2672 continue;
2673 }
2674 tmpl->reqid = ipsec->cfg.reqid;
2675 tmpl->id.proto = protos[i].proto;
2676 if (policy->direction == POLICY_OUT)
2677 {
2678 tmpl->id.spi = protos[i].spi;
2679 }
2680 tmpl->aalgos = tmpl->ealgos = tmpl->calgos = ~0;
2681 tmpl->mode = mode2kernel(proto_mode);
2682 tmpl->optional = protos[i].proto == IPPROTO_COMP &&
2683 policy->direction != POLICY_OUT;
2684 tmpl->family = ipsec->src->get_family(ipsec->src);
2685
2686 if (proto_mode == MODE_TUNNEL || proto_mode == MODE_BEET)
2687 { /* only for tunnel mode */
2688 host2xfrm(ipsec->src, &tmpl->saddr);
2689 host2xfrm(ipsec->dst, &tmpl->id.daddr);
2690 }
2691
2692 tmpl++;
2693
2694 /* use transport mode for other SAs */
2695 proto_mode = MODE_TRANSPORT;
2696 }
2697 }
2698
2699 if (!add_mark(hdr, sizeof(request), ipsec->mark))
2700 {
2701 policy_change_done(this, policy);
2702 return FAILED;
2703 }
2704 this->mutex->unlock(this->mutex);
2705
2706 status = this->socket_xfrm->send_ack(this->socket_xfrm, hdr);
2707 if (status == ALREADY_DONE && !update)
2708 {
2709 DBG1(DBG_KNL, "policy already exists, try to update it");
2710 hdr->nlmsg_type = XFRM_MSG_UPDPOLICY;
2711 status = this->socket_xfrm->send_ack(this->socket_xfrm, hdr);
2712 }
2713
2714 this->mutex->lock(this->mutex);
2715 if (status != SUCCESS)
2716 {
2717 policy_change_done(this, policy);
2718 return FAILED;
2719 }
2720 /* install a route, if:
2721 * - this is an outbound policy (to just get one for each child)
2722 * - routing is not disabled via strongswan.conf
2723 * - the selector is not for a specific protocol/port
2724 * - we are in tunnel/BEET mode or install a bypass policy
2725 */
2726 if (policy->direction == POLICY_OUT && this->install_routes &&
2727 !policy->sel.proto && !policy->sel.dport && !policy->sel.sport)
2728 {
2729 if (mapping->type == POLICY_PASS ||
2730 (mapping->type == POLICY_IPSEC && ipsec->cfg.mode != MODE_TRANSPORT))
2731 {
2732 install_route(this, policy, mapping, ipsec);
2733 }
2734 }
2735 policy_change_done(this, policy);
2736 return SUCCESS;
2737 }
2738
2739 METHOD(kernel_ipsec_t, add_policy, status_t,
2740 private_kernel_netlink_ipsec_t *this, kernel_ipsec_policy_id_t *id,
2741 kernel_ipsec_manage_policy_t *data)
2742 {
2743 policy_entry_t *policy, *current;
2744 policy_sa_t *assigned_sa, *current_sa;
2745 enumerator_t *enumerator;
2746 bool found = FALSE, update = TRUE;
2747 char markstr[32] = "";
2748 uint32_t cur_priority = 0;
2749 int use_count;
2750
2751 /* create a policy */
2752 INIT(policy,
2753 .sel = ts2selector(id->src_ts, id->dst_ts, id->interface),
2754 .mark = id->mark.value & id->mark.mask,
2755 .direction = id->dir,
2756 .reqid = data->sa->reqid,
2757 );
2758 format_mark(markstr, sizeof(markstr), id->mark);
2759
2760 /* find the policy, which matches EXACTLY */
2761 this->mutex->lock(this->mutex);
2762 current = this->policies->get(this->policies, policy);
2763 if (current)
2764 {
2765 if (current->reqid && data->sa->reqid &&
2766 current->reqid != data->sa->reqid)
2767 {
2768 DBG1(DBG_CFG, "unable to install policy %R === %R %N%s for reqid "
2769 "%u, the same policy for reqid %u exists",
2770 id->src_ts, id->dst_ts, policy_dir_names, id->dir, markstr,
2771 data->sa->reqid, current->reqid);
2772 policy_entry_destroy(this, policy);
2773 this->mutex->unlock(this->mutex);
2774 return INVALID_STATE;
2775 }
2776 /* use existing policy */
2777 DBG2(DBG_KNL, "policy %R === %R %N%s already exists, increasing "
2778 "refcount", id->src_ts, id->dst_ts, policy_dir_names, id->dir,
2779 markstr);
2780 policy_entry_destroy(this, policy);
2781 policy = current;
2782 found = TRUE;
2783
2784 policy->waiting++;
2785 while (policy->working)
2786 {
2787 this->condvar->wait(this->condvar, this->mutex);
2788 }
2789 policy->waiting--;
2790 policy->working = TRUE;
2791 }
2792 else
2793 { /* use the new one, if we have no such policy */
2794 policy->used_by = linked_list_create();
2795 this->policies->put(this->policies, policy, policy);
2796 }
2797
2798 /* cache the assigned IPsec SA */
2799 assigned_sa = policy_sa_create(this, id->dir, data->type, data->src,
2800 data->dst, id->src_ts, id->dst_ts, id->mark, data->sa);
2801 assigned_sa->auto_priority = get_priority(policy, data->prio, id->interface);
2802 assigned_sa->priority = this->get_priority ? this->get_priority(id, data)
2803 : data->manual_prio;
2804 assigned_sa->priority = assigned_sa->priority ?: assigned_sa->auto_priority;
2805
2806 /* insert the SA according to its priority */
2807 enumerator = policy->used_by->create_enumerator(policy->used_by);
2808 while (enumerator->enumerate(enumerator, (void**)&current_sa))
2809 {
2810 if (current_sa->priority > assigned_sa->priority)
2811 {
2812 break;
2813 }
2814 if (current_sa->priority == assigned_sa->priority)
2815 {
2816 /* in case of equal manual prios order SAs by automatic priority */
2817 if (current_sa->auto_priority > assigned_sa->auto_priority)
2818 {
2819 break;
2820 }
2821 /* prefer SAs with a reqid over those without */
2822 if (current_sa->auto_priority == assigned_sa->auto_priority &&
2823 (!current_sa->sa->cfg.reqid || assigned_sa->sa->cfg.reqid))
2824 {
2825 break;
2826 }
2827 }
2828 if (update)
2829 {
2830 cur_priority = current_sa->priority;
2831 update = FALSE;
2832 }
2833 }
2834 policy->used_by->insert_before(policy->used_by, enumerator, assigned_sa);
2835 enumerator->destroy(enumerator);
2836
2837 use_count = policy->used_by->get_count(policy->used_by);
2838 if (!update)
2839 { /* we don't update the policy if the priority is lower than that of
2840 * the currently installed one */
2841 policy_change_done(this, policy);
2842 DBG2(DBG_KNL, "not updating policy %R === %R %N%s [priority %u, "
2843 "refcount %d]", id->src_ts, id->dst_ts, policy_dir_names,
2844 id->dir, markstr, cur_priority, use_count);
2845 return SUCCESS;
2846 }
2847 policy->reqid = assigned_sa->sa->cfg.reqid;
2848
2849 if (this->policy_update)
2850 {
2851 found = TRUE;
2852 }
2853
2854 DBG2(DBG_KNL, "%s policy %R === %R %N%s [priority %u, refcount %d]",
2855 found ? "updating" : "adding", id->src_ts, id->dst_ts,
2856 policy_dir_names, id->dir, markstr, assigned_sa->priority, use_count);
2857
2858 if (add_policy_internal(this, policy, assigned_sa, found) != SUCCESS)
2859 {
2860 DBG1(DBG_KNL, "unable to %s policy %R === %R %N%s",
2861 found ? "update" : "add", id->src_ts, id->dst_ts,
2862 policy_dir_names, id->dir, markstr);
2863 return FAILED;
2864 }
2865 return SUCCESS;
2866 }
2867
2868 METHOD(kernel_ipsec_t, query_policy, status_t,
2869 private_kernel_netlink_ipsec_t *this, kernel_ipsec_policy_id_t *id,
2870 kernel_ipsec_query_policy_t *data, time_t *use_time)
2871 {
2872 netlink_buf_t request;
2873 struct nlmsghdr *out = NULL, *hdr;
2874 struct xfrm_userpolicy_id *policy_id;
2875 struct xfrm_userpolicy_info *policy = NULL;
2876 size_t len;
2877 char markstr[32] = "";
2878
2879 memset(&request, 0, sizeof(request));
2880 format_mark(markstr, sizeof(markstr), id->mark);
2881
2882 DBG2(DBG_KNL, "querying policy %R === %R %N%s", id->src_ts, id->dst_ts,
2883 policy_dir_names, id->dir, markstr);
2884
2885 hdr = &request.hdr;
2886 hdr->nlmsg_flags = NLM_F_REQUEST;
2887 hdr->nlmsg_type = XFRM_MSG_GETPOLICY;
2888 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_id));
2889
2890 policy_id = NLMSG_DATA(hdr);
2891 policy_id->sel = ts2selector(id->src_ts, id->dst_ts, id->interface);
2892 policy_id->dir = id->dir;
2893
2894 if (!add_mark(hdr, sizeof(request), id->mark))
2895 {
2896 return FAILED;
2897 }
2898
2899 if (this->socket_xfrm->send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
2900 {
2901 hdr = out;
2902 while (NLMSG_OK(hdr, len))
2903 {
2904 switch (hdr->nlmsg_type)
2905 {
2906 case XFRM_MSG_NEWPOLICY:
2907 {
2908 policy = NLMSG_DATA(hdr);
2909 break;
2910 }
2911 case NLMSG_ERROR:
2912 {
2913 struct nlmsgerr *err = NLMSG_DATA(hdr);
2914 DBG1(DBG_KNL, "querying policy failed: %s (%d)",
2915 strerror(-err->error), -err->error);
2916 break;
2917 }
2918 default:
2919 hdr = NLMSG_NEXT(hdr, len);
2920 continue;
2921 case NLMSG_DONE:
2922 break;
2923 }
2924 break;
2925 }
2926 }
2927
2928 if (policy == NULL)
2929 {
2930 DBG2(DBG_KNL, "unable to query policy %R === %R %N%s", id->src_ts,
2931 id->dst_ts, policy_dir_names, id->dir, markstr);
2932 free(out);
2933 return FAILED;
2934 }
2935
2936 if (policy->curlft.use_time)
2937 {
2938 /* we need the monotonic time, but the kernel returns system time. */
2939 *use_time = time_monotonic(NULL) - (time(NULL) - policy->curlft.use_time);
2940 }
2941 else
2942 {
2943 *use_time = 0;
2944 }
2945
2946 free(out);
2947 return SUCCESS;
2948 }
2949
2950 METHOD(kernel_ipsec_t, del_policy, status_t,
2951 private_kernel_netlink_ipsec_t *this, kernel_ipsec_policy_id_t *id,
2952 kernel_ipsec_manage_policy_t *data)
2953 {
2954 policy_entry_t *current, policy;
2955 enumerator_t *enumerator;
2956 policy_sa_t *mapping;
2957 netlink_buf_t request;
2958 struct nlmsghdr *hdr;
2959 struct xfrm_userpolicy_id *policy_id;
2960 bool is_installed = TRUE;
2961 uint32_t priority, auto_priority, cur_priority;
2962 ipsec_sa_t assigned_sa = {
2963 .src = data->src,
2964 .dst = data->dst,
2965 .mark = id->mark,
2966 .cfg = *data->sa,
2967 };
2968 char markstr[32] = "";
2969 int use_count;
2970 status_t status = SUCCESS;
2971
2972 format_mark(markstr, sizeof(markstr), id->mark);
2973
2974 DBG2(DBG_KNL, "deleting policy %R === %R %N%s", id->src_ts, id->dst_ts,
2975 policy_dir_names, id->dir, markstr);
2976
2977 /* create a policy */
2978 memset(&policy, 0, sizeof(policy_entry_t));
2979 policy.sel = ts2selector(id->src_ts, id->dst_ts, id->interface);
2980 policy.mark = id->mark.value & id->mark.mask;
2981 policy.direction = id->dir;
2982
2983 /* find the policy */
2984 this->mutex->lock(this->mutex);
2985 current = this->policies->get(this->policies, &policy);
2986 if (!current)
2987 {
2988 DBG1(DBG_KNL, "deleting policy %R === %R %N%s failed, not found",
2989 id->src_ts, id->dst_ts, policy_dir_names, id->dir, markstr);
2990 this->mutex->unlock(this->mutex);
2991 return NOT_FOUND;
2992 }
2993 current->waiting++;
2994 while (current->working)
2995 {
2996 this->condvar->wait(this->condvar, this->mutex);
2997 }
2998 current->working = TRUE;
2999 current->waiting--;
3000
3001 /* remove mapping to SA by reqid and priority */
3002 auto_priority = get_priority(current, data->prio,id->interface);
3003 priority = this->get_priority ? this->get_priority(id, data)
3004 : data->manual_prio;
3005 priority = priority ?: auto_priority;
3006
3007 enumerator = current->used_by->create_enumerator(current->used_by);
3008 while (enumerator->enumerate(enumerator, (void**)&mapping))
3009 {
3010 if (priority == mapping->priority &&
3011 auto_priority == mapping->auto_priority &&
3012 data->type == mapping->type &&
3013 ipsec_sa_equals(mapping->sa, &assigned_sa))
3014 {
3015 current->used_by->remove_at(current->used_by, enumerator);
3016 policy_sa_destroy(mapping, id->dir, this);
3017 break;
3018 }
3019 if (is_installed)
3020 {
3021 cur_priority = mapping->priority;
3022 is_installed = FALSE;
3023 }
3024 }
3025 enumerator->destroy(enumerator);
3026
3027 use_count = current->used_by->get_count(current->used_by);
3028 if (use_count > 0)
3029 { /* policy is used by more SAs, keep in kernel */
3030 DBG2(DBG_KNL, "policy still used by another CHILD_SA, not removed");
3031 if (!is_installed)
3032 { /* no need to update as the policy was not installed for this SA */
3033 policy_change_done(this, current);
3034 DBG2(DBG_KNL, "not updating policy %R === %R %N%s [priority %u, "
3035 "refcount %d]", id->src_ts, id->dst_ts, policy_dir_names,
3036 id->dir, markstr, cur_priority, use_count);
3037 return SUCCESS;
3038 }
3039 current->used_by->get_first(current->used_by, (void**)&mapping);
3040 current->reqid = mapping->sa->cfg.reqid;
3041
3042 DBG2(DBG_KNL, "updating policy %R === %R %N%s [priority %u, "
3043 "refcount %d]", id->src_ts, id->dst_ts, policy_dir_names, id->dir,
3044 markstr, mapping->priority, use_count);
3045
3046 if (add_policy_internal(this, current, mapping, TRUE) != SUCCESS)
3047 {
3048 DBG1(DBG_KNL, "unable to update policy %R === %R %N%s",
3049 id->src_ts, id->dst_ts, policy_dir_names, id->dir, markstr);
3050 return FAILED;
3051 }
3052 return SUCCESS;
3053 }
3054
3055 memset(&request, 0, sizeof(request));
3056
3057 hdr = &request.hdr;
3058 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
3059 hdr->nlmsg_type = XFRM_MSG_DELPOLICY;
3060 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_id));
3061
3062 policy_id = NLMSG_DATA(hdr);
3063 policy_id->sel = current->sel;
3064 policy_id->dir = id->dir;
3065
3066 if (!add_mark(hdr, sizeof(request), id->mark))
3067 {
3068 policy_change_done(this, current);
3069 return FAILED;
3070 }
3071
3072 if (current->route)
3073 {
3074 route_entry_t *route = current->route;
3075 if (charon->kernel->del_route(charon->kernel, route->dst_net,
3076 route->prefixlen, route->gateway,
3077 route->src_ip, route->if_name) != SUCCESS)
3078 {
3079 DBG1(DBG_KNL, "error uninstalling route installed with policy "
3080 "%R === %R %N%s", id->src_ts, id->dst_ts, policy_dir_names,
3081 id->dir, markstr);
3082 }
3083 }
3084 this->mutex->unlock(this->mutex);
3085
3086 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
3087 {
3088 DBG1(DBG_KNL, "unable to delete policy %R === %R %N%s", id->src_ts,
3089 id->dst_ts, policy_dir_names, id->dir, markstr);
3090 status = FAILED;
3091 }
3092
3093 this->mutex->lock(this->mutex);
3094 if (!current->waiting)
3095 { /* only if no other thread still needs the policy */
3096 this->policies->remove(this->policies, current);
3097 policy_entry_destroy(this, current);
3098 this->mutex->unlock(this->mutex);
3099 }
3100 else
3101 {
3102 policy_change_done(this, current);
3103 }
3104 return status;
3105 }
3106
3107 METHOD(kernel_ipsec_t, flush_policies, status_t,
3108 private_kernel_netlink_ipsec_t *this)
3109 {
3110 netlink_buf_t request;
3111 struct nlmsghdr *hdr;
3112
3113 memset(&request, 0, sizeof(request));
3114
3115 DBG2(DBG_KNL, "flushing all policies from SPD");
3116
3117 hdr = &request.hdr;
3118 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
3119 hdr->nlmsg_type = XFRM_MSG_FLUSHPOLICY;
3120 hdr->nlmsg_len = NLMSG_LENGTH(0); /* no data associated */
3121
3122 /* by adding an rtattr of type XFRMA_POLICY_TYPE we could restrict this
3123 * to main or sub policies (default is main) */
3124
3125 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
3126 {
3127 DBG1(DBG_KNL, "unable to flush SPD entries");
3128 return FAILED;
3129 }
3130 return SUCCESS;
3131 }
3132
3133 /**
3134 * Bypass socket using a per-socket policy
3135 */
3136 static bool add_socket_bypass(private_kernel_netlink_ipsec_t *this,
3137 int fd, int family)
3138 {
3139 struct xfrm_userpolicy_info policy;
3140 u_int sol, ipsec_policy;
3141
3142 switch (family)
3143 {
3144 case AF_INET:
3145 sol = SOL_IP;
3146 ipsec_policy = IP_XFRM_POLICY;
3147 break;
3148 case AF_INET6:
3149 sol = SOL_IPV6;
3150 ipsec_policy = IPV6_XFRM_POLICY;
3151 break;
3152 default:
3153 return FALSE;
3154 }
3155
3156 memset(&policy, 0, sizeof(policy));
3157 policy.action = XFRM_POLICY_ALLOW;
3158 policy.sel.family = family;
3159
3160 policy.dir = XFRM_POLICY_OUT;
3161 if (setsockopt(fd, sol, ipsec_policy, &policy, sizeof(policy)) < 0)
3162 {
3163 DBG1(DBG_KNL, "unable to set IPSEC_POLICY on socket: %s (%d)",
3164 strerror(errno), errno);
3165 return FALSE;
3166 }
3167 policy.dir = XFRM_POLICY_IN;
3168 if (setsockopt(fd, sol, ipsec_policy, &policy, sizeof(policy)) < 0)
3169 {
3170 DBG1(DBG_KNL, "unable to set IPSEC_POLICY on socket: %s (%d)",
3171 strerror(errno), errno);
3172 return FALSE;
3173 }
3174 return TRUE;
3175 }
3176
3177 /**
3178 * Port based IKE bypass policy
3179 */
3180 typedef struct {
3181 /** address family */
3182 int family;
3183 /** layer 4 protocol */
3184 int proto;
3185 /** port number, network order */
3186 uint16_t port;
3187 } bypass_t;
3188
3189 /**
3190 * Add or remove a bypass policy from/to kernel
3191 */
3192 static bool manage_bypass(private_kernel_netlink_ipsec_t *this,
3193 int type, policy_dir_t dir, bypass_t *bypass)
3194 {
3195 netlink_buf_t request;
3196 struct xfrm_selector *sel;
3197 struct nlmsghdr *hdr;
3198
3199 memset(&request, 0, sizeof(request));
3200 hdr = &request.hdr;
3201 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
3202 hdr->nlmsg_type = type;
3203
3204 if (type == XFRM_MSG_NEWPOLICY)
3205 {
3206 struct xfrm_userpolicy_info *policy;
3207
3208 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_info));
3209
3210 policy = NLMSG_DATA(hdr);
3211 policy->dir = dir;
3212 policy->priority = 32;
3213 policy->action = XFRM_POLICY_ALLOW;
3214 policy->share = XFRM_SHARE_ANY;
3215
3216 policy->lft.soft_byte_limit = XFRM_INF;
3217 policy->lft.soft_packet_limit = XFRM_INF;
3218 policy->lft.hard_byte_limit = XFRM_INF;
3219 policy->lft.hard_packet_limit = XFRM_INF;
3220
3221 sel = &policy->sel;
3222 }
3223 else /* XFRM_MSG_DELPOLICY */
3224 {
3225 struct xfrm_userpolicy_id *policy;
3226
3227 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_id));
3228
3229 policy = NLMSG_DATA(hdr);
3230 policy->dir = dir;
3231
3232 sel = &policy->sel;
3233 }
3234
3235 sel->family = bypass->family;
3236 sel->proto = bypass->proto;
3237 if (dir == POLICY_IN)
3238 {
3239 sel->dport = bypass->port;
3240 sel->dport_mask = 0xffff;
3241 }