kernel-netlink: Use strncpy to copy interface name when configuring HW offload
[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 switch (mode)
1590 {
1591 case MODE_TUNNEL:
1592 sa->flags |= XFRM_STATE_AF_UNSPEC;
1593 break;
1594 case MODE_BEET:
1595 case MODE_TRANSPORT:
1596 if (original_mode == MODE_TUNNEL)
1597 { /* don't install selectors for switched SAs. because only one
1598 * selector can be installed other traffic would get dropped */
1599 break;
1600 }
1601 if (data->src_ts->get_first(data->src_ts,
1602 (void**)&first_src_ts) == SUCCESS &&
1603 data->dst_ts->get_first(data->dst_ts,
1604 (void**)&first_dst_ts) == SUCCESS)
1605 {
1606 sa->sel = ts2selector(first_src_ts, first_dst_ts,
1607 data->interface);
1608 if (!this->proto_port_transport)
1609 {
1610 /* don't install proto/port on SA. This would break
1611 * potential secondary SAs for the same address using a
1612 * different prot/port. */
1613 sa->sel.proto = 0;
1614 sa->sel.dport = sa->sel.dport_mask = 0;
1615 sa->sel.sport = sa->sel.sport_mask = 0;
1616 }
1617 }
1618 break;
1619 default:
1620 break;
1621 }
1622 if (id->proto == IPPROTO_AH && sa->family == AF_INET)
1623 { /* use alignment to 4 bytes for IPv4 instead of the incorrect 8 byte
1624 * alignment that's used by default but is only valid for IPv6 */
1625 sa->flags |= XFRM_STATE_ALIGN4;
1626 }
1627
1628 sa->reqid = data->reqid;
1629 sa->lft.soft_byte_limit = XFRM_LIMIT(data->lifetime->bytes.rekey);
1630 sa->lft.hard_byte_limit = XFRM_LIMIT(data->lifetime->bytes.life);
1631 sa->lft.soft_packet_limit = XFRM_LIMIT(data->lifetime->packets.rekey);
1632 sa->lft.hard_packet_limit = XFRM_LIMIT(data->lifetime->packets.life);
1633 /* we use lifetimes since added, not since used */
1634 sa->lft.soft_add_expires_seconds = data->lifetime->time.rekey;
1635 sa->lft.hard_add_expires_seconds = data->lifetime->time.life;
1636 sa->lft.soft_use_expires_seconds = 0;
1637 sa->lft.hard_use_expires_seconds = 0;
1638
1639 switch (data->enc_alg)
1640 {
1641 case ENCR_UNDEFINED:
1642 /* no encryption */
1643 break;
1644 case ENCR_AES_CCM_ICV16:
1645 case ENCR_AES_GCM_ICV16:
1646 case ENCR_NULL_AUTH_AES_GMAC:
1647 case ENCR_CAMELLIA_CCM_ICV16:
1648 case ENCR_CHACHA20_POLY1305:
1649 icv_size += 32;
1650 /* FALL */
1651 case ENCR_AES_CCM_ICV12:
1652 case ENCR_AES_GCM_ICV12:
1653 case ENCR_CAMELLIA_CCM_ICV12:
1654 icv_size += 32;
1655 /* FALL */
1656 case ENCR_AES_CCM_ICV8:
1657 case ENCR_AES_GCM_ICV8:
1658 case ENCR_CAMELLIA_CCM_ICV8:
1659 {
1660 struct xfrm_algo_aead *algo;
1661
1662 alg_name = lookup_algorithm(ENCRYPTION_ALGORITHM, data->enc_alg);
1663 if (alg_name == NULL)
1664 {
1665 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1666 encryption_algorithm_names, data->enc_alg);
1667 goto failed;
1668 }
1669 DBG2(DBG_KNL, " using encryption algorithm %N with key size %d",
1670 encryption_algorithm_names, data->enc_alg,
1671 data->enc_key.len * 8);
1672
1673 algo = netlink_reserve(hdr, sizeof(request), XFRMA_ALG_AEAD,
1674 sizeof(*algo) + data->enc_key.len);
1675 if (!algo)
1676 {
1677 goto failed;
1678 }
1679 algo->alg_key_len = data->enc_key.len * 8;
1680 algo->alg_icv_len = icv_size;
1681 strncpy(algo->alg_name, alg_name, sizeof(algo->alg_name));
1682 algo->alg_name[sizeof(algo->alg_name) - 1] = '\0';
1683 memcpy(algo->alg_key, data->enc_key.ptr, data->enc_key.len);
1684 break;
1685 }
1686 default:
1687 {
1688 struct xfrm_algo *algo;
1689
1690 alg_name = lookup_algorithm(ENCRYPTION_ALGORITHM, data->enc_alg);
1691 if (alg_name == NULL)
1692 {
1693 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1694 encryption_algorithm_names, data->enc_alg);
1695 goto failed;
1696 }
1697 DBG2(DBG_KNL, " using encryption algorithm %N with key size %d",
1698 encryption_algorithm_names, data->enc_alg,
1699 data->enc_key.len * 8);
1700
1701 algo = netlink_reserve(hdr, sizeof(request), XFRMA_ALG_CRYPT,
1702 sizeof(*algo) + data->enc_key.len);
1703 if (!algo)
1704 {
1705 goto failed;
1706 }
1707 algo->alg_key_len = data->enc_key.len * 8;
1708 strncpy(algo->alg_name, alg_name, sizeof(algo->alg_name));
1709 algo->alg_name[sizeof(algo->alg_name) - 1] = '\0';
1710 memcpy(algo->alg_key, data->enc_key.ptr, data->enc_key.len);
1711 }
1712 }
1713
1714 if (data->int_alg != AUTH_UNDEFINED)
1715 {
1716 u_int trunc_len = 0;
1717
1718 alg_name = lookup_algorithm(INTEGRITY_ALGORITHM, data->int_alg);
1719 if (alg_name == NULL)
1720 {
1721 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1722 integrity_algorithm_names, data->int_alg);
1723 goto failed;
1724 }
1725 DBG2(DBG_KNL, " using integrity algorithm %N with key size %d",
1726 integrity_algorithm_names, data->int_alg, data->int_key.len * 8);
1727
1728 switch (data->int_alg)
1729 {
1730 case AUTH_HMAC_MD5_128:
1731 case AUTH_HMAC_SHA2_256_128:
1732 trunc_len = 128;
1733 break;
1734 case AUTH_HMAC_SHA1_160:
1735 trunc_len = 160;
1736 break;
1737 default:
1738 break;
1739 }
1740
1741 if (trunc_len)
1742 {
1743 struct xfrm_algo_auth* algo;
1744
1745 /* the kernel uses SHA256 with 96 bit truncation by default,
1746 * use specified truncation size supported by newer kernels.
1747 * also use this for untruncated MD5 and SHA1. */
1748 algo = netlink_reserve(hdr, sizeof(request), XFRMA_ALG_AUTH_TRUNC,
1749 sizeof(*algo) + data->int_key.len);
1750 if (!algo)
1751 {
1752 goto failed;
1753 }
1754 algo->alg_key_len = data->int_key.len * 8;
1755 algo->alg_trunc_len = trunc_len;
1756 strncpy(algo->alg_name, alg_name, sizeof(algo->alg_name));
1757 algo->alg_name[sizeof(algo->alg_name) - 1] = '\0';
1758 memcpy(algo->alg_key, data->int_key.ptr, data->int_key.len);
1759 }
1760 else
1761 {
1762 struct xfrm_algo* algo;
1763
1764 algo = netlink_reserve(hdr, sizeof(request), XFRMA_ALG_AUTH,
1765 sizeof(*algo) + data->int_key.len);
1766 if (!algo)
1767 {
1768 goto failed;
1769 }
1770 algo->alg_key_len = data->int_key.len * 8;
1771 strncpy(algo->alg_name, alg_name, sizeof(algo->alg_name));
1772 algo->alg_name[sizeof(algo->alg_name) - 1] = '\0';
1773 memcpy(algo->alg_key, data->int_key.ptr, data->int_key.len);
1774 }
1775 }
1776
1777 if (ipcomp != IPCOMP_NONE)
1778 {
1779 struct xfrm_algo* algo;
1780
1781 alg_name = lookup_algorithm(COMPRESSION_ALGORITHM, ipcomp);
1782 if (alg_name == NULL)
1783 {
1784 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1785 ipcomp_transform_names, ipcomp);
1786 goto failed;
1787 }
1788 DBG2(DBG_KNL, " using compression algorithm %N",
1789 ipcomp_transform_names, ipcomp);
1790
1791 algo = netlink_reserve(hdr, sizeof(request), XFRMA_ALG_COMP,
1792 sizeof(*algo));
1793 if (!algo)
1794 {
1795 goto failed;
1796 }
1797 algo->alg_key_len = 0;
1798 strncpy(algo->alg_name, alg_name, sizeof(algo->alg_name));
1799 algo->alg_name[sizeof(algo->alg_name) - 1] = '\0';
1800 }
1801
1802 if (data->encap)
1803 {
1804 struct xfrm_encap_tmpl *tmpl;
1805
1806 tmpl = netlink_reserve(hdr, sizeof(request), XFRMA_ENCAP, sizeof(*tmpl));
1807 if (!tmpl)
1808 {
1809 goto failed;
1810 }
1811 tmpl->encap_type = UDP_ENCAP_ESPINUDP;
1812 tmpl->encap_sport = htons(id->src->get_port(id->src));
1813 tmpl->encap_dport = htons(id->dst->get_port(id->dst));
1814 memset(&tmpl->encap_oa, 0, sizeof (xfrm_address_t));
1815 /* encap_oa could probably be derived from the
1816 * traffic selectors [rfc4306, p39]. In the netlink kernel
1817 * implementation pluto does the same as we do here but it uses
1818 * encap_oa in the pfkey implementation.
1819 * BUT as /usr/src/linux/net/key/af_key.c indicates the kernel ignores
1820 * it anyway
1821 * -> does that mean that NAT-T encap doesn't work in transport mode?
1822 * No. The reason the kernel ignores NAT-OA is that it recomputes
1823 * (or, rather, just ignores) the checksum. If packets pass the IPsec
1824 * checks it marks them "checksum ok" so OA isn't needed. */
1825 }
1826
1827 if (!add_mark(hdr, sizeof(request), id->mark))
1828 {
1829 goto failed;
1830 }
1831
1832 if (data->tfc && id->proto == IPPROTO_ESP && mode == MODE_TUNNEL)
1833 { /* the kernel supports TFC padding only for tunnel mode ESP SAs */
1834 uint32_t *tfcpad;
1835
1836 tfcpad = netlink_reserve(hdr, sizeof(request), XFRMA_TFCPAD,
1837 sizeof(*tfcpad));
1838 if (!tfcpad)
1839 {
1840 goto failed;
1841 }
1842 *tfcpad = data->tfc;
1843 }
1844
1845 if (id->proto != IPPROTO_COMP)
1846 {
1847 /* generally, we don't need a replay window for outbound SAs, however,
1848 * when using ESN the kernel rejects the attribute if it is 0 */
1849 if (!data->inbound && data->replay_window)
1850 {
1851 data->replay_window = data->esn ? 1 : 0;
1852 }
1853 if (data->replay_window != 0 && (data->esn || data->replay_window > 32))
1854 {
1855 /* for ESN or larger replay windows we need the new
1856 * XFRMA_REPLAY_ESN_VAL attribute to configure a bitmap */
1857 struct xfrm_replay_state_esn *replay;
1858 uint32_t bmp_size;
1859
1860 bmp_size = round_up(data->replay_window, sizeof(uint32_t) * 8) / 8;
1861 replay = netlink_reserve(hdr, sizeof(request), XFRMA_REPLAY_ESN_VAL,
1862 sizeof(*replay) + bmp_size);
1863 if (!replay)
1864 {
1865 goto failed;
1866 }
1867 /* bmp_len contains number uf __u32's */
1868 replay->bmp_len = bmp_size / sizeof(uint32_t);
1869 replay->replay_window = data->replay_window;
1870 DBG2(DBG_KNL, " using replay window of %u packets",
1871 data->replay_window);
1872
1873 if (data->esn)
1874 {
1875 DBG2(DBG_KNL, " using extended sequence numbers (ESN)");
1876 sa->flags |= XFRM_STATE_ESN;
1877 }
1878 }
1879 else
1880 {
1881 DBG2(DBG_KNL, " using replay window of %u packets",
1882 data->replay_window);
1883 sa->replay_window = data->replay_window;
1884 }
1885
1886 DBG2(DBG_KNL, " HW offload: %N", hw_offload_names, data->hw_offload);
1887 if (!config_hw_offload(id, data, hdr, sizeof(request)))
1888 {
1889 DBG1(DBG_KNL, "failed to configure HW offload");
1890 goto failed;
1891 }
1892 }
1893
1894 status = this->socket_xfrm->send_ack(this->socket_xfrm, hdr);
1895 if (status == NOT_FOUND && data->update)
1896 {
1897 DBG1(DBG_KNL, "allocated SPI not found anymore, try to add SAD entry");
1898 hdr->nlmsg_type = XFRM_MSG_NEWSA;
1899 status = this->socket_xfrm->send_ack(this->socket_xfrm, hdr);
1900 }
1901
1902 if (status != SUCCESS)
1903 {
1904 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x%s (%N)", ntohl(id->spi),
1905 markstr, status_names, status);
1906 status = FAILED;
1907 goto failed;
1908 }
1909
1910 status = SUCCESS;
1911
1912 failed:
1913 memwipe(&request, sizeof(request));
1914 return status;
1915 }
1916
1917 /**
1918 * Get the ESN replay state (i.e. sequence numbers) of an SA.
1919 *
1920 * Allocates into one the replay state structure we get from the kernel.
1921 */
1922 static void get_replay_state(private_kernel_netlink_ipsec_t *this,
1923 kernel_ipsec_sa_id_t *sa,
1924 struct xfrm_replay_state_esn **replay_esn,
1925 uint32_t *replay_esn_len,
1926 struct xfrm_replay_state **replay,
1927 struct xfrm_lifetime_cur **lifetime)
1928 {
1929 netlink_buf_t request;
1930 struct nlmsghdr *hdr, *out = NULL;
1931 struct xfrm_aevent_id *out_aevent = NULL, *aevent_id;
1932 size_t len;
1933 struct rtattr *rta;
1934 size_t rtasize;
1935
1936 memset(&request, 0, sizeof(request));
1937
1938 DBG2(DBG_KNL, "querying replay state from SAD entry with SPI %.8x",
1939 ntohl(sa->spi));
1940
1941 hdr = &request.hdr;
1942 hdr->nlmsg_flags = NLM_F_REQUEST;
1943 hdr->nlmsg_type = XFRM_MSG_GETAE;
1944 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_aevent_id));
1945
1946 aevent_id = NLMSG_DATA(hdr);
1947 aevent_id->flags = XFRM_AE_RVAL;
1948
1949 host2xfrm(sa->dst, &aevent_id->sa_id.daddr);
1950 aevent_id->sa_id.spi = sa->spi;
1951 aevent_id->sa_id.proto = sa->proto;
1952 aevent_id->sa_id.family = sa->dst->get_family(sa->dst);
1953
1954 if (!add_mark(hdr, sizeof(request), sa->mark))
1955 {
1956 return;
1957 }
1958
1959 if (this->socket_xfrm->send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
1960 {
1961 hdr = out;
1962 while (NLMSG_OK(hdr, len))
1963 {
1964 switch (hdr->nlmsg_type)
1965 {
1966 case XFRM_MSG_NEWAE:
1967 {
1968 out_aevent = NLMSG_DATA(hdr);
1969 break;
1970 }
1971 case NLMSG_ERROR:
1972 {
1973 struct nlmsgerr *err = NLMSG_DATA(hdr);
1974 DBG1(DBG_KNL, "querying replay state from SAD entry "
1975 "failed: %s (%d)", strerror(-err->error), -err->error);
1976 break;
1977 }
1978 default:
1979 hdr = NLMSG_NEXT(hdr, len);
1980 continue;
1981 case NLMSG_DONE:
1982 break;
1983 }
1984 break;
1985 }
1986 }
1987
1988 if (out_aevent)
1989 {
1990 rta = XFRM_RTA(out, struct xfrm_aevent_id);
1991 rtasize = XFRM_PAYLOAD(out, struct xfrm_aevent_id);
1992 while (RTA_OK(rta, rtasize))
1993 {
1994 if (rta->rta_type == XFRMA_LTIME_VAL &&
1995 RTA_PAYLOAD(rta) == sizeof(**lifetime))
1996 {
1997 free(*lifetime);
1998 *lifetime = malloc(RTA_PAYLOAD(rta));
1999 memcpy(*lifetime, RTA_DATA(rta), RTA_PAYLOAD(rta));
2000 }
2001 if (rta->rta_type == XFRMA_REPLAY_VAL &&
2002 RTA_PAYLOAD(rta) == sizeof(**replay))
2003 {
2004 free(*replay);
2005 *replay = malloc(RTA_PAYLOAD(rta));
2006 memcpy(*replay, RTA_DATA(rta), RTA_PAYLOAD(rta));
2007 }
2008 if (rta->rta_type == XFRMA_REPLAY_ESN_VAL &&
2009 RTA_PAYLOAD(rta) >= sizeof(**replay_esn))
2010 {
2011 free(*replay_esn);
2012 *replay_esn = malloc(RTA_PAYLOAD(rta));
2013 *replay_esn_len = RTA_PAYLOAD(rta);
2014 memcpy(*replay_esn, RTA_DATA(rta), RTA_PAYLOAD(rta));
2015 }
2016 rta = RTA_NEXT(rta, rtasize);
2017 }
2018 }
2019 free(out);
2020 }
2021
2022 METHOD(kernel_ipsec_t, query_sa, status_t,
2023 private_kernel_netlink_ipsec_t *this, kernel_ipsec_sa_id_t *id,
2024 kernel_ipsec_query_sa_t *data, uint64_t *bytes, uint64_t *packets,
2025 time_t *time)
2026 {
2027 netlink_buf_t request;
2028 struct nlmsghdr *out = NULL, *hdr;
2029 struct xfrm_usersa_id *sa_id;
2030 struct xfrm_usersa_info *sa = NULL;
2031 status_t status = FAILED;
2032 size_t len;
2033 char markstr[32] = "";
2034
2035 memset(&request, 0, sizeof(request));
2036 format_mark(markstr, sizeof(markstr), id->mark);
2037
2038 DBG2(DBG_KNL, "querying SAD entry with SPI %.8x%s", ntohl(id->spi),
2039 markstr);
2040
2041 hdr = &request.hdr;
2042 hdr->nlmsg_flags = NLM_F_REQUEST;
2043 hdr->nlmsg_type = XFRM_MSG_GETSA;
2044 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_id));
2045
2046 sa_id = NLMSG_DATA(hdr);
2047 host2xfrm(id->dst, &sa_id->daddr);
2048 sa_id->spi = id->spi;
2049 sa_id->proto = id->proto;
2050 sa_id->family = id->dst->get_family(id->dst);
2051
2052 if (!add_mark(hdr, sizeof(request), id->mark))
2053 {
2054 return FAILED;
2055 }
2056
2057 if (this->socket_xfrm->send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
2058 {
2059 hdr = out;
2060 while (NLMSG_OK(hdr, len))
2061 {
2062 switch (hdr->nlmsg_type)
2063 {
2064 case XFRM_MSG_NEWSA:
2065 {
2066 sa = NLMSG_DATA(hdr);
2067 break;
2068 }
2069 case NLMSG_ERROR:
2070 {
2071 struct nlmsgerr *err = NLMSG_DATA(hdr);
2072
2073 DBG1(DBG_KNL, "querying SAD entry with SPI %.8x%s failed: "
2074 "%s (%d)", ntohl(id->spi), markstr,
2075 strerror(-err->error), -err->error);
2076 break;
2077 }
2078 default:
2079 hdr = NLMSG_NEXT(hdr, len);
2080 continue;
2081 case NLMSG_DONE:
2082 break;
2083 }
2084 break;
2085 }
2086 }
2087
2088 if (sa == NULL)
2089 {
2090 DBG2(DBG_KNL, "unable to query SAD entry with SPI %.8x%s",
2091 ntohl(id->spi), markstr);
2092 }
2093 else
2094 {
2095 if (bytes)
2096 {
2097 *bytes = sa->curlft.bytes;
2098 }
2099 if (packets)
2100 {
2101 *packets = sa->curlft.packets;
2102 }
2103 if (time)
2104 { /* curlft contains an "use" time, but that contains a timestamp
2105 * of the first use, not the last. Last use time must be queried
2106 * on the policy on Linux */
2107 *time = 0;
2108 }
2109 status = SUCCESS;
2110 }
2111 memwipe(out, len);
2112 free(out);
2113 return status;
2114 }
2115
2116 METHOD(kernel_ipsec_t, del_sa, status_t,
2117 private_kernel_netlink_ipsec_t *this, kernel_ipsec_sa_id_t *id,
2118 kernel_ipsec_del_sa_t *data)
2119 {
2120 netlink_buf_t request;
2121 struct nlmsghdr *hdr;
2122 struct xfrm_usersa_id *sa_id;
2123 char markstr[32] = "";
2124
2125 /* if IPComp was used, we first delete the additional IPComp SA */
2126 if (data->cpi)
2127 {
2128 kernel_ipsec_sa_id_t ipcomp_id = {
2129 .src = id->src,
2130 .dst = id->dst,
2131 .spi = htonl(ntohs(data->cpi)),
2132 .proto = IPPROTO_COMP,
2133 .mark = id->mark,
2134 };
2135 kernel_ipsec_del_sa_t ipcomp = {};
2136 del_sa(this, &ipcomp_id, &ipcomp);
2137 }
2138
2139 memset(&request, 0, sizeof(request));
2140 format_mark(markstr, sizeof(markstr), id->mark);
2141
2142 DBG2(DBG_KNL, "deleting SAD entry with SPI %.8x%s", ntohl(id->spi),
2143 markstr);
2144
2145 hdr = &request.hdr;
2146 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2147 hdr->nlmsg_type = XFRM_MSG_DELSA;
2148 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_id));
2149
2150 sa_id = NLMSG_DATA(hdr);
2151 host2xfrm(id->dst, &sa_id->daddr);
2152 sa_id->spi = id->spi;
2153 sa_id->proto = id->proto;
2154 sa_id->family = id->dst->get_family(id->dst);
2155
2156 if (!add_mark(hdr, sizeof(request), id->mark))
2157 {
2158 return FAILED;
2159 }
2160
2161 switch (this->socket_xfrm->send_ack(this->socket_xfrm, hdr))
2162 {
2163 case SUCCESS:
2164 DBG2(DBG_KNL, "deleted SAD entry with SPI %.8x%s",
2165 ntohl(id->spi), markstr);
2166 return SUCCESS;
2167 case NOT_FOUND:
2168 return NOT_FOUND;
2169 default:
2170 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x%s",
2171 ntohl(id->spi), markstr);
2172 return FAILED;
2173 }
2174 }
2175
2176 METHOD(kernel_ipsec_t, update_sa, status_t,
2177 private_kernel_netlink_ipsec_t *this, kernel_ipsec_sa_id_t *id,
2178 kernel_ipsec_update_sa_t *data)
2179 {
2180 netlink_buf_t request;
2181 struct nlmsghdr *hdr, *out_hdr = NULL, *out = NULL;
2182 struct xfrm_usersa_id *sa_id;
2183 struct xfrm_usersa_info *sa;
2184 size_t len;
2185 struct rtattr *rta;
2186 size_t rtasize;
2187 struct xfrm_encap_tmpl* encap = NULL;
2188 struct xfrm_replay_state *replay = NULL;
2189 struct xfrm_replay_state_esn *replay_esn = NULL;
2190 struct xfrm_lifetime_cur *lifetime = NULL;
2191 uint32_t replay_esn_len = 0;
2192 kernel_ipsec_del_sa_t del = { 0 };
2193 status_t status = FAILED;
2194 char markstr[32] = "";
2195
2196 /* if IPComp is used, we first update the IPComp SA */
2197 if (data->cpi)
2198 {
2199 kernel_ipsec_sa_id_t ipcomp_id = {
2200 .src = id->src,
2201 .dst = id->dst,
2202 .spi = htonl(ntohs(data->cpi)),
2203 .proto = IPPROTO_COMP,
2204 .mark = id->mark,
2205 };
2206 kernel_ipsec_update_sa_t ipcomp = {
2207 .new_src = data->new_src,
2208 .new_dst = data->new_dst,
2209 };
2210 update_sa(this, &ipcomp_id, &ipcomp);
2211 }
2212
2213 memset(&request, 0, sizeof(request));
2214 format_mark(markstr, sizeof(markstr), id->mark);
2215
2216 DBG2(DBG_KNL, "querying SAD entry with SPI %.8x%s for update",
2217 ntohl(id->spi), markstr);
2218
2219 /* query the existing SA first */
2220 hdr = &request.hdr;
2221 hdr->nlmsg_flags = NLM_F_REQUEST;
2222 hdr->nlmsg_type = XFRM_MSG_GETSA;
2223 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_id));
2224
2225 sa_id = NLMSG_DATA(hdr);
2226 host2xfrm(id->dst, &sa_id->daddr);
2227 sa_id->spi = id->spi;
2228 sa_id->proto = id->proto;
2229 sa_id->family = id->dst->get_family(id->dst);
2230
2231 if (!add_mark(hdr, sizeof(request), id->mark))
2232 {
2233 return FAILED;
2234 }
2235
2236 if (this->socket_xfrm->send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
2237 {
2238 hdr = out;
2239 while (NLMSG_OK(hdr, len))
2240 {
2241 switch (hdr->nlmsg_type)
2242 {
2243 case XFRM_MSG_NEWSA:
2244 {
2245 out_hdr = hdr;
2246 break;
2247 }
2248 case NLMSG_ERROR:
2249 {
2250 struct nlmsgerr *err = NLMSG_DATA(hdr);
2251 DBG1(DBG_KNL, "querying SAD entry failed: %s (%d)",
2252 strerror(-err->error), -err->error);
2253 break;
2254 }
2255 default:
2256 hdr = NLMSG_NEXT(hdr, len);
2257 continue;
2258 case NLMSG_DONE:
2259 break;
2260 }
2261 break;
2262 }
2263 }
2264 if (!out_hdr)
2265 {
2266 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x%s",
2267 ntohl(id->spi), markstr);
2268 goto failed;
2269 }
2270
2271 get_replay_state(this, id, &replay_esn, &replay_esn_len, &replay,
2272 &lifetime);
2273
2274 /* delete the old SA (without affecting the IPComp SA) */
2275 if (del_sa(this, id, &del) != SUCCESS)
2276 {
2277 DBG1(DBG_KNL, "unable to delete old SAD entry with SPI %.8x%s",
2278 ntohl(id->spi), markstr);
2279 goto failed;
2280 }
2281
2282 DBG2(DBG_KNL, "updating SAD entry with SPI %.8x%s from %#H..%#H to "
2283 "%#H..%#H", ntohl(id->spi), markstr, id->src, id->dst, data->new_src,
2284 data->new_dst);
2285 /* copy over the SA from out to request */
2286 hdr = &request.hdr;
2287 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2288 hdr->nlmsg_type = XFRM_MSG_NEWSA;
2289 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_info));
2290 sa = NLMSG_DATA(hdr);
2291 memcpy(sa, NLMSG_DATA(out_hdr), sizeof(struct xfrm_usersa_info));
2292 sa->family = data->new_dst->get_family(data->new_dst);
2293
2294 if (!id->src->ip_equals(id->src, data->new_src))
2295 {
2296 host2xfrm(data->new_src, &sa->saddr);
2297 }
2298 if (!id->dst->ip_equals(id->dst, data->new_dst))
2299 {
2300 host2xfrm(data->new_dst, &sa->id.daddr);
2301 }
2302
2303 rta = XFRM_RTA(out_hdr, struct xfrm_usersa_info);
2304 rtasize = XFRM_PAYLOAD(out_hdr, struct xfrm_usersa_info);
2305 while (RTA_OK(rta, rtasize))
2306 {
2307 /* copy all attributes, but not XFRMA_ENCAP if we are disabling it */
2308 if (rta->rta_type != XFRMA_ENCAP || data->new_encap)
2309 {
2310 if (rta->rta_type == XFRMA_ENCAP)
2311 { /* update encap tmpl */
2312 encap = RTA_DATA(rta);
2313 encap->encap_sport = ntohs(data->new_src->get_port(data->new_src));
2314 encap->encap_dport = ntohs(data->new_dst->get_port(data->new_dst));
2315 }
2316 if (rta->rta_type == XFRMA_OFFLOAD_DEV)
2317 { /* update offload device */
2318 struct xfrm_user_offload *offload;
2319 host_t *local;
2320 char *ifname;
2321
2322 offload = RTA_DATA(rta);
2323 local = offload->flags & XFRM_OFFLOAD_INBOUND ? data->new_dst
2324 : data->new_src;
2325
2326 if (charon->kernel->get_interface(charon->kernel, local,
2327 &ifname))
2328 {
2329 offload->ifindex = if_nametoindex(ifname);
2330 if (local->get_family(local) == AF_INET6)
2331 {
2332 offload->flags |= XFRM_OFFLOAD_IPV6;
2333 }
2334 else
2335 {
2336 offload->flags &= ~XFRM_OFFLOAD_IPV6;
2337 }
2338 free(ifname);
2339 }
2340 }
2341 netlink_add_attribute(hdr, rta->rta_type,
2342 chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta)),
2343 sizeof(request));
2344 }
2345 rta = RTA_NEXT(rta, rtasize);
2346 }
2347
2348 if (encap == NULL && data->new_encap)
2349 { /* add tmpl if we are enabling it */
2350 encap = netlink_reserve(hdr, sizeof(request), XFRMA_ENCAP,
2351 sizeof(*encap));
2352 if (!encap)
2353 {
2354 goto failed;
2355 }
2356 encap->encap_type = UDP_ENCAP_ESPINUDP;
2357 encap->encap_sport = ntohs(data->new_src->get_port(data->new_src));
2358 encap->encap_dport = ntohs(data->new_dst->get_port(data->new_dst));
2359 memset(&encap->encap_oa, 0, sizeof (xfrm_address_t));
2360 }
2361
2362 if (replay_esn)
2363 {
2364 struct xfrm_replay_state_esn *state;
2365
2366 state = netlink_reserve(hdr, sizeof(request), XFRMA_REPLAY_ESN_VAL,
2367 replay_esn_len);
2368 if (!state)
2369 {
2370 goto failed;
2371 }
2372 memcpy(state, replay_esn, replay_esn_len);
2373 }
2374 else if (replay)
2375 {
2376 struct xfrm_replay_state *state;
2377
2378 state = netlink_reserve(hdr, sizeof(request), XFRMA_REPLAY_VAL,
2379 sizeof(*state));
2380 if (!state)
2381 {
2382 goto failed;
2383 }
2384 memcpy(state, replay, sizeof(*state));
2385 }
2386 else
2387 {
2388 DBG1(DBG_KNL, "unable to copy replay state from old SAD entry with "
2389 "SPI %.8x%s", ntohl(id->spi), markstr);
2390 }
2391 if (lifetime)
2392 {
2393 struct xfrm_lifetime_cur *state;
2394
2395 state = netlink_reserve(hdr, sizeof(request), XFRMA_LTIME_VAL,
2396 sizeof(*state));
2397 if (!state)
2398 {
2399 goto failed;
2400 }
2401 memcpy(state, lifetime, sizeof(*state));
2402 }
2403 else
2404 {
2405 DBG1(DBG_KNL, "unable to copy usage stats from old SAD entry with "
2406 "SPI %.8x%s", ntohl(id->spi), markstr);
2407 }
2408
2409 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
2410 {
2411 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x%s",
2412 ntohl(id->spi), markstr);
2413 goto failed;
2414 }
2415
2416 status = SUCCESS;
2417 failed:
2418 free(replay);
2419 free(replay_esn);
2420 free(lifetime);
2421 memwipe(out, len);
2422 memwipe(&request, sizeof(request));
2423 free(out);
2424
2425 return status;
2426 }
2427
2428 METHOD(kernel_ipsec_t, flush_sas, status_t,
2429 private_kernel_netlink_ipsec_t *this)
2430 {
2431 netlink_buf_t request;
2432 struct nlmsghdr *hdr;
2433 struct xfrm_usersa_flush *flush;
2434 struct {
2435 uint8_t proto;
2436 char *name;
2437 } protos[] = {
2438 { IPPROTO_AH, "AH" },
2439 { IPPROTO_ESP, "ESP" },
2440 { IPPROTO_COMP, "IPComp" },
2441 };
2442 int i;
2443
2444 memset(&request, 0, sizeof(request));
2445
2446 hdr = &request.hdr;
2447 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2448 hdr->nlmsg_type = XFRM_MSG_FLUSHSA;
2449 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_flush));
2450
2451 flush = NLMSG_DATA(hdr);
2452
2453 for (i = 0; i < countof(protos); i++)
2454 {
2455 DBG2(DBG_KNL, "flushing all %s SAD entries", protos[i].name);
2456
2457 flush->proto = protos[i].proto;
2458
2459 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
2460 {
2461 DBG1(DBG_KNL, "unable to flush %s SAD entries", protos[i].name);
2462 return FAILED;
2463 }
2464 }
2465 return SUCCESS;
2466 }
2467
2468 /**
2469 * Unlock the mutex and signal waiting threads
2470 */
2471 static void policy_change_done(private_kernel_netlink_ipsec_t *this,
2472 policy_entry_t *policy)
2473 {
2474 policy->working = FALSE;
2475 if (policy->waiting)
2476 { /* don't need to wake threads waiting for other policies */
2477 this->condvar->broadcast(this->condvar);
2478 }
2479 this->mutex->unlock(this->mutex);
2480 }
2481
2482 /**
2483 * Install a route for the given policy if enabled and required
2484 */
2485 static void install_route(private_kernel_netlink_ipsec_t *this,
2486 policy_entry_t *policy, policy_sa_t *mapping, ipsec_sa_t *ipsec)
2487 {
2488 policy_sa_out_t *out = (policy_sa_out_t*)mapping;
2489 route_entry_t *route;
2490 host_t *iface;
2491
2492 INIT(route,
2493 .prefixlen = policy->sel.prefixlen_d,
2494 );
2495
2496 if (charon->kernel->get_address_by_ts(charon->kernel, out->src_ts,
2497 &route->src_ip, NULL) == SUCCESS)
2498 {
2499 if (!ipsec->dst->is_anyaddr(ipsec->dst))
2500 {
2501 route->gateway = charon->kernel->get_nexthop(charon->kernel,
2502 ipsec->dst, -1, ipsec->src,
2503 &route->if_name);
2504 }
2505 else
2506 { /* for shunt policies */
2507 iface = xfrm2host(policy->sel.family, &policy->sel.daddr, 0);
2508 route->gateway = charon->kernel->get_nexthop(charon->kernel,
2509 iface, policy->sel.prefixlen_d,
2510 route->src_ip, &route->if_name);
2511 iface->destroy(iface);
2512 }
2513 route->dst_net = chunk_alloc(policy->sel.family == AF_INET ? 4 : 16);
2514 memcpy(route->dst_net.ptr, &policy->sel.daddr, route->dst_net.len);
2515
2516 /* get the interface to install the route for, if we haven't one yet.
2517 * If we have a local address, use it. Otherwise (for shunt policies)
2518 * use the route's source address. */
2519 if (!route->if_name)
2520 {
2521 iface = ipsec->src;
2522 if (iface->is_anyaddr(iface))
2523 {
2524 iface = route->src_ip;
2525 }
2526 if (!charon->kernel->get_interface(charon->kernel, iface,
2527 &route->if_name))
2528 {
2529 route_entry_destroy(route);
2530 return;
2531 }
2532 }
2533 if (policy->route)
2534 {
2535 route_entry_t *old = policy->route;
2536 if (route_entry_equals(old, route))
2537 {
2538 route_entry_destroy(route);
2539 return;
2540 }
2541 /* uninstall previously installed route */
2542 if (charon->kernel->del_route(charon->kernel, old->dst_net,
2543 old->prefixlen, old->gateway,
2544 old->src_ip, old->if_name) != SUCCESS)
2545 {
2546 DBG1(DBG_KNL, "error uninstalling route installed with policy "
2547 "%R === %R %N", out->src_ts, out->dst_ts, policy_dir_names,
2548 policy->direction);
2549 }
2550 route_entry_destroy(old);
2551 policy->route = NULL;
2552 }
2553
2554 DBG2(DBG_KNL, "installing route: %R via %H src %H dev %s", out->dst_ts,
2555 route->gateway, route->src_ip, route->if_name);
2556 switch (charon->kernel->add_route(charon->kernel, route->dst_net,
2557 route->prefixlen, route->gateway,
2558 route->src_ip, route->if_name))
2559 {
2560 default:
2561 DBG1(DBG_KNL, "unable to install source route for %H",
2562 route->src_ip);
2563 /* FALL */
2564 case ALREADY_DONE:
2565 /* route exists, do not uninstall */
2566 route_entry_destroy(route);
2567 break;
2568 case SUCCESS:
2569 /* cache the installed route */
2570 policy->route = route;
2571 break;
2572 }
2573 }
2574 else
2575 {
2576 free(route);
2577 }
2578 }
2579
2580 /**
2581 * Add or update a policy in the kernel.
2582 *
2583 * Note: The mutex has to be locked when entering this function
2584 * and is unlocked here in any case.
2585 */
2586 static status_t add_policy_internal(private_kernel_netlink_ipsec_t *this,
2587 policy_entry_t *policy, policy_sa_t *mapping, bool update)
2588 {
2589 netlink_buf_t request;
2590 policy_entry_t clone;
2591 ipsec_sa_t *ipsec = mapping->sa;
2592 struct xfrm_userpolicy_info *policy_info;
2593 struct nlmsghdr *hdr;
2594 status_t status;
2595 int i;
2596
2597 /* clone the policy so we are able to check it out again later */
2598 memcpy(&clone, policy, sizeof(policy_entry_t));
2599
2600 memset(&request, 0, sizeof(request));
2601 hdr = &request.hdr;
2602 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2603 hdr->nlmsg_type = update ? XFRM_MSG_UPDPOLICY : XFRM_MSG_NEWPOLICY;
2604 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_info));
2605
2606 policy_info = NLMSG_DATA(hdr);
2607 policy_info->sel = policy->sel;
2608 policy_info->dir = policy->direction;
2609
2610 /* calculate priority based on selector size, small size = high prio */
2611 policy_info->priority = mapping->priority;
2612 policy_info->action = mapping->type != POLICY_DROP ? XFRM_POLICY_ALLOW
2613 : XFRM_POLICY_BLOCK;
2614 policy_info->share = XFRM_SHARE_ANY;
2615
2616 /* policies don't expire */
2617 policy_info->lft.soft_byte_limit = XFRM_INF;
2618 policy_info->lft.soft_packet_limit = XFRM_INF;
2619 policy_info->lft.hard_byte_limit = XFRM_INF;
2620 policy_info->lft.hard_packet_limit = XFRM_INF;
2621 policy_info->lft.soft_add_expires_seconds = 0;
2622 policy_info->lft.hard_add_expires_seconds = 0;
2623 policy_info->lft.soft_use_expires_seconds = 0;
2624 policy_info->lft.hard_use_expires_seconds = 0;
2625
2626 if (mapping->type == POLICY_IPSEC && ipsec->cfg.reqid)
2627 {
2628 struct xfrm_user_tmpl *tmpl;
2629 struct {
2630 uint8_t proto;
2631 uint32_t spi;
2632 bool use;
2633 } protos[] = {
2634 { IPPROTO_COMP, htonl(ntohs(ipsec->cfg.ipcomp.cpi)),
2635 ipsec->cfg.ipcomp.transform != IPCOMP_NONE },
2636 { IPPROTO_ESP, ipsec->cfg.esp.spi, ipsec->cfg.esp.use },
2637 { IPPROTO_AH, ipsec->cfg.ah.spi, ipsec->cfg.ah.use },
2638 };
2639 ipsec_mode_t proto_mode = ipsec->cfg.mode;
2640 int count = 0;
2641
2642 for (i = 0; i < countof(protos); i++)
2643 {
2644 if (protos[i].use)
2645 {
2646 count++;
2647 }
2648 }
2649 tmpl = netlink_reserve(hdr, sizeof(request), XFRMA_TMPL,
2650 count * sizeof(*tmpl));
2651 if (!tmpl)
2652 {
2653 policy_change_done(this, policy);
2654 return FAILED;
2655 }
2656
2657 for (i = 0; i < countof(protos); i++)
2658 {
2659 if (!protos[i].use)
2660 {
2661 continue;
2662 }
2663 tmpl->reqid = ipsec->cfg.reqid;
2664 tmpl->id.proto = protos[i].proto;
2665 if (policy->direction == POLICY_OUT)
2666 {
2667 tmpl->id.spi = protos[i].spi;
2668 }
2669 tmpl->aalgos = tmpl->ealgos = tmpl->calgos = ~0;
2670 tmpl->mode = mode2kernel(proto_mode);
2671 tmpl->optional = protos[i].proto == IPPROTO_COMP &&
2672 policy->direction != POLICY_OUT;
2673 tmpl->family = ipsec->src->get_family(ipsec->src);
2674
2675 if (proto_mode == MODE_TUNNEL || proto_mode == MODE_BEET)
2676 { /* only for tunnel mode */
2677 host2xfrm(ipsec->src, &tmpl->saddr);
2678 host2xfrm(ipsec->dst, &tmpl->id.daddr);
2679 }
2680
2681 tmpl++;
2682
2683 /* use transport mode for other SAs */
2684 proto_mode = MODE_TRANSPORT;
2685 }
2686 }
2687
2688 if (!add_mark(hdr, sizeof(request), ipsec->mark))
2689 {
2690 policy_change_done(this, policy);
2691 return FAILED;
2692 }
2693 this->mutex->unlock(this->mutex);
2694
2695 status = this->socket_xfrm->send_ack(this->socket_xfrm, hdr);
2696 if (status == ALREADY_DONE && !update)
2697 {
2698 DBG1(DBG_KNL, "policy already exists, try to update it");
2699 hdr->nlmsg_type = XFRM_MSG_UPDPOLICY;
2700 status = this->socket_xfrm->send_ack(this->socket_xfrm, hdr);
2701 }
2702
2703 this->mutex->lock(this->mutex);
2704 if (status != SUCCESS)
2705 {
2706 policy_change_done(this, policy);
2707 return FAILED;
2708 }
2709 /* install a route, if:
2710 * - this is an outbound policy (to just get one for each child)
2711 * - routing is not disabled via strongswan.conf
2712 * - the selector is not for a specific protocol/port
2713 * - we are in tunnel/BEET mode or install a bypass policy
2714 */
2715 if (policy->direction == POLICY_OUT && this->install_routes &&
2716 !policy->sel.proto && !policy->sel.dport && !policy->sel.sport)
2717 {
2718 if (mapping->type == POLICY_PASS ||
2719 (mapping->type == POLICY_IPSEC && ipsec->cfg.mode != MODE_TRANSPORT))
2720 {
2721 install_route(this, policy, mapping, ipsec);
2722 }
2723 }
2724 policy_change_done(this, policy);
2725 return SUCCESS;
2726 }
2727
2728 METHOD(kernel_ipsec_t, add_policy, status_t,
2729 private_kernel_netlink_ipsec_t *this, kernel_ipsec_policy_id_t *id,
2730 kernel_ipsec_manage_policy_t *data)
2731 {
2732 policy_entry_t *policy, *current;
2733 policy_sa_t *assigned_sa, *current_sa;
2734 enumerator_t *enumerator;
2735 bool found = FALSE, update = TRUE;
2736 char markstr[32] = "";
2737 uint32_t cur_priority = 0;
2738 int use_count;
2739
2740 /* create a policy */
2741 INIT(policy,
2742 .sel = ts2selector(id->src_ts, id->dst_ts, id->interface),
2743 .mark = id->mark.value & id->mark.mask,
2744 .direction = id->dir,
2745 .reqid = data->sa->reqid,
2746 );
2747 format_mark(markstr, sizeof(markstr), id->mark);
2748
2749 /* find the policy, which matches EXACTLY */
2750 this->mutex->lock(this->mutex);
2751 current = this->policies->get(this->policies, policy);
2752 if (current)
2753 {
2754 if (current->reqid && data->sa->reqid &&
2755 current->reqid != data->sa->reqid)
2756 {
2757 DBG1(DBG_CFG, "unable to install policy %R === %R %N%s for reqid "
2758 "%u, the same policy for reqid %u exists",
2759 id->src_ts, id->dst_ts, policy_dir_names, id->dir, markstr,
2760 data->sa->reqid, current->reqid);
2761 policy_entry_destroy(this, policy);
2762 this->mutex->unlock(this->mutex);
2763 return INVALID_STATE;
2764 }
2765 /* use existing policy */
2766 DBG2(DBG_KNL, "policy %R === %R %N%s already exists, increasing "
2767 "refcount", id->src_ts, id->dst_ts, policy_dir_names, id->dir,
2768 markstr);
2769 policy_entry_destroy(this, policy);
2770 policy = current;
2771 found = TRUE;
2772
2773 policy->waiting++;
2774 while (policy->working)
2775 {
2776 this->condvar->wait(this->condvar, this->mutex);
2777 }
2778 policy->waiting--;
2779 policy->working = TRUE;
2780 }
2781 else
2782 { /* use the new one, if we have no such policy */
2783 policy->used_by = linked_list_create();
2784 this->policies->put(this->policies, policy, policy);
2785 }
2786
2787 /* cache the assigned IPsec SA */
2788 assigned_sa = policy_sa_create(this, id->dir, data->type, data->src,
2789 data->dst, id->src_ts, id->dst_ts, id->mark, data->sa);
2790 assigned_sa->auto_priority = get_priority(policy, data->prio, id->interface);
2791 assigned_sa->priority = this->get_priority ? this->get_priority(id, data)
2792 : data->manual_prio;
2793 assigned_sa->priority = assigned_sa->priority ?: assigned_sa->auto_priority;
2794
2795 /* insert the SA according to its priority */
2796 enumerator = policy->used_by->create_enumerator(policy->used_by);
2797 while (enumerator->enumerate(enumerator, (void**)&current_sa))
2798 {
2799 if (current_sa->priority > assigned_sa->priority)
2800 {
2801 break;
2802 }
2803 if (current_sa->priority == assigned_sa->priority)
2804 {
2805 /* in case of equal manual prios order SAs by automatic priority */
2806 if (current_sa->auto_priority > assigned_sa->auto_priority)
2807 {
2808 break;
2809 }
2810 /* prefer SAs with a reqid over those without */
2811 if (current_sa->auto_priority == assigned_sa->auto_priority &&
2812 (!current_sa->sa->cfg.reqid || assigned_sa->sa->cfg.reqid))
2813 {
2814 break;
2815 }
2816 }
2817 if (update)
2818 {
2819 cur_priority = current_sa->priority;
2820 update = FALSE;
2821 }
2822 }
2823 policy->used_by->insert_before(policy->used_by, enumerator, assigned_sa);
2824 enumerator->destroy(enumerator);
2825
2826 use_count = policy->used_by->get_count(policy->used_by);
2827 if (!update)
2828 { /* we don't update the policy if the priority is lower than that of
2829 * the currently installed one */
2830 policy_change_done(this, policy);
2831 DBG2(DBG_KNL, "not updating policy %R === %R %N%s [priority %u, "
2832 "refcount %d]", id->src_ts, id->dst_ts, policy_dir_names,
2833 id->dir, markstr, cur_priority, use_count);
2834 return SUCCESS;
2835 }
2836 policy->reqid = assigned_sa->sa->cfg.reqid;
2837
2838 if (this->policy_update)
2839 {
2840 found = TRUE;
2841 }
2842
2843 DBG2(DBG_KNL, "%s policy %R === %R %N%s [priority %u, refcount %d]",
2844 found ? "updating" : "adding", id->src_ts, id->dst_ts,
2845 policy_dir_names, id->dir, markstr, assigned_sa->priority, use_count);
2846
2847 if (add_policy_internal(this, policy, assigned_sa, found) != SUCCESS)
2848 {
2849 DBG1(DBG_KNL, "unable to %s policy %R === %R %N%s",
2850 found ? "update" : "add", id->src_ts, id->dst_ts,
2851 policy_dir_names, id->dir, markstr);
2852 return FAILED;
2853 }
2854 return SUCCESS;
2855 }