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