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