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