swima-collector: Fix compile error if SWID_DIRECTORY is not defined
[strongswan.git] / src / libcharon / plugins / kernel_netlink / kernel_netlink_ipsec.c
1 /*
2 * Copyright (C) 2006-2017 Tobias Brunner
3 * Copyright (C) 2005-2009 Martin Willi
4 * Copyright (C) 2008-2016 Andreas Steffen
5 * Copyright (C) 2006-2007 Fabian Hartmann, Noah Heusser
6 * Copyright (C) 2006 Daniel Roethlisberger
7 * Copyright (C) 2005 Jan Hutter
8 * HSR Hochschule fuer Technik Rapperswil
9 *
10 * This program is free software; you can redistribute it and/or modify it
11 * under the terms of the GNU General Public License as published by the
12 * Free Software Foundation; either version 2 of the License, or (at your
13 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
14 *
15 * This program is distributed in the hope that it will be useful, but
16 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
18 * for more details.
19 */
20
21 #define _GNU_SOURCE
22 #include <sys/types.h>
23 #include <sys/socket.h>
24 #include <stdint.h>
25 #include <linux/ipsec.h>
26 #include <linux/netlink.h>
27 #include <linux/rtnetlink.h>
28 #include <linux/xfrm.h>
29 #include <linux/udp.h>
30 #include <net/if.h>
31 #include <unistd.h>
32 #include <time.h>
33 #include <errno.h>
34 #include <string.h>
35 #include <fcntl.h>
36 #include <dlfcn.h>
37
38 #include "kernel_netlink_ipsec.h"
39 #include "kernel_netlink_shared.h"
40
41 #include <daemon.h>
42 #include <utils/debug.h>
43 #include <threading/mutex.h>
44 #include <threading/condvar.h>
45 #include <collections/array.h>
46 #include <collections/hashtable.h>
47 #include <collections/linked_list.h>
48
49 /** Required for Linux 2.6.26 kernel and later */
50 #ifndef XFRM_STATE_AF_UNSPEC
51 #define XFRM_STATE_AF_UNSPEC 32
52 #endif
53
54 /** From linux/in.h */
55 #ifndef IP_XFRM_POLICY
56 #define IP_XFRM_POLICY 17
57 #endif
58
59 /** Missing on uclibc */
60 #ifndef IPV6_XFRM_POLICY
61 #define IPV6_XFRM_POLICY 34
62 #endif /*IPV6_XFRM_POLICY*/
63
64 /* from linux/udp.h */
65 #ifndef UDP_ENCAP
66 #define UDP_ENCAP 100
67 #endif
68
69 #ifndef UDP_ENCAP_ESPINUDP
70 #define UDP_ENCAP_ESPINUDP 2
71 #endif
72
73 /* this is not defined on some platforms */
74 #ifndef SOL_UDP
75 #define SOL_UDP IPPROTO_UDP
76 #endif
77
78 /** Base priority for installed policies */
79 #define PRIO_BASE 200000
80
81 /** 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: separate trap and regular policies (0..1) 1 bit
657 * bits 1-1: restriction to network interface (0..1) 1 bit
658 * bits 2-7: src + dst port mask bits (2 * 0..16) 6 bits
659 * bits 8-8: restriction to protocol (0..1) 1 bit
660 * bits 9-17: src + dst network mask bits (2 * 0..128) 9 bits
661 * 18 bits
662 *
663 * smallest value: 000000000 0 000000 0 0: 0, lowest priority = 200'000
664 * largest value : 100000000 1 100000 1 1: 131'459, highst priority = 68'541
665 */
666 static uint32_t get_priority(policy_entry_t *policy, policy_priority_t prio,
667 char *interface)
668 {
669 uint32_t priority = PRIO_BASE, sport_mask_bits, dport_mask_bits;
670
671 switch (prio)
672 {
673 case POLICY_PRIORITY_FALLBACK:
674 priority += PRIO_BASE;
675 /* fall-through to next case */
676 case POLICY_PRIORITY_ROUTED:
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) * 512;
688 priority -= policy->sel.proto ? 256 : 0;
689 priority -= (sport_mask_bits + dport_mask_bits) * 4;
690 priority -= (interface != NULL) * 2;
691 priority -= (prio != POLICY_PRIORITY_ROUTED);
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 uint32_t spi_min, spi_max;
1215
1216 spi_min = lib->settings->get_int(lib->settings, "%s.spi_min",
1217 KERNEL_SPI_MIN, lib->ns);
1218 spi_max = lib->settings->get_int(lib->settings, "%s.spi_max",
1219 KERNEL_SPI_MAX, lib->ns);
1220
1221 if (get_spi_internal(this, src, dst, protocol, min(spi_min, spi_max),
1222 max(spi_min, spi_max), spi) != SUCCESS)
1223 {
1224 DBG1(DBG_KNL, "unable to get SPI");
1225 return FAILED;
1226 }
1227
1228 DBG2(DBG_KNL, "got SPI %.8x", ntohl(*spi));
1229 return SUCCESS;
1230 }
1231
1232 METHOD(kernel_ipsec_t, get_cpi, status_t,
1233 private_kernel_netlink_ipsec_t *this, host_t *src, host_t *dst,
1234 uint16_t *cpi)
1235 {
1236 uint32_t received_spi = 0;
1237
1238 if (get_spi_internal(this, src, dst, IPPROTO_COMP,
1239 0x100, 0xEFFF, &received_spi) != SUCCESS)
1240 {
1241 DBG1(DBG_KNL, "unable to get CPI");
1242 return FAILED;
1243 }
1244
1245 *cpi = htons((uint16_t)ntohl(received_spi));
1246
1247 DBG2(DBG_KNL, "got CPI %.4x", ntohs(*cpi));
1248 return SUCCESS;
1249 }
1250
1251 /**
1252 * Format the mark for debug messages
1253 */
1254 static void format_mark(char *buf, int buflen, mark_t mark)
1255 {
1256 if (mark.value | mark.mask)
1257 {
1258 snprintf(buf, buflen, " (mark %u/0x%08x)", mark.value, mark.mask);
1259 }
1260 }
1261
1262 /**
1263 * Add a XFRM mark to message if required
1264 */
1265 static bool add_mark(struct nlmsghdr *hdr, int buflen, mark_t mark)
1266 {
1267 if (mark.value | mark.mask)
1268 {
1269 struct xfrm_mark *xmrk;
1270
1271 xmrk = netlink_reserve(hdr, buflen, XFRMA_MARK, sizeof(*xmrk));
1272 if (!xmrk)
1273 {
1274 return FALSE;
1275 }
1276 xmrk->v = mark.value;
1277 xmrk->m = mark.mask;
1278 }
1279 return TRUE;
1280 }
1281
1282 METHOD(kernel_ipsec_t, add_sa, status_t,
1283 private_kernel_netlink_ipsec_t *this, kernel_ipsec_sa_id_t *id,
1284 kernel_ipsec_add_sa_t *data)
1285 {
1286 netlink_buf_t request;
1287 const char *alg_name;
1288 char markstr[32] = "";
1289 struct nlmsghdr *hdr;
1290 struct xfrm_usersa_info *sa;
1291 uint16_t icv_size = 64, ipcomp = data->ipcomp;
1292 ipsec_mode_t mode = data->mode, original_mode = data->mode;
1293 traffic_selector_t *first_src_ts, *first_dst_ts;
1294 status_t status = FAILED;
1295
1296 /* if IPComp is used, we install an additional IPComp SA. if the cpi is 0
1297 * we are in the recursive call below */
1298 if (ipcomp != IPCOMP_NONE && data->cpi != 0)
1299 {
1300 lifetime_cfg_t lft = {{0,0,0},{0,0,0},{0,0,0}};
1301 kernel_ipsec_sa_id_t ipcomp_id = {
1302 .src = id->src,
1303 .dst = id->dst,
1304 .spi = htonl(ntohs(data->cpi)),
1305 .proto = IPPROTO_COMP,
1306 .mark = id->mark,
1307 };
1308 kernel_ipsec_add_sa_t ipcomp_sa = {
1309 .reqid = data->reqid,
1310 .mode = data->mode,
1311 .src_ts = data->src_ts,
1312 .dst_ts = data->dst_ts,
1313 .lifetime = &lft,
1314 .enc_alg = ENCR_UNDEFINED,
1315 .int_alg = AUTH_UNDEFINED,
1316 .tfc = data->tfc,
1317 .ipcomp = data->ipcomp,
1318 .initiator = data->initiator,
1319 .inbound = data->inbound,
1320 .update = data->update,
1321 };
1322 add_sa(this, &ipcomp_id, &ipcomp_sa);
1323 ipcomp = IPCOMP_NONE;
1324 /* use transport mode ESP SA, IPComp uses tunnel mode */
1325 mode = MODE_TRANSPORT;
1326 }
1327
1328 memset(&request, 0, sizeof(request));
1329 format_mark(markstr, sizeof(markstr), id->mark);
1330
1331 DBG2(DBG_KNL, "adding SAD entry with SPI %.8x and reqid {%u}%s",
1332 ntohl(id->spi), data->reqid, markstr);
1333
1334 hdr = &request.hdr;
1335 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
1336 hdr->nlmsg_type = data->update ? XFRM_MSG_UPDSA : XFRM_MSG_NEWSA;
1337 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_info));
1338
1339 sa = NLMSG_DATA(hdr);
1340 host2xfrm(id->src, &sa->saddr);
1341 host2xfrm(id->dst, &sa->id.daddr);
1342 sa->id.spi = id->spi;
1343 sa->id.proto = id->proto;
1344 sa->family = id->src->get_family(id->src);
1345 sa->mode = mode2kernel(mode);
1346 switch (mode)
1347 {
1348 case MODE_TUNNEL:
1349 sa->flags |= XFRM_STATE_AF_UNSPEC;
1350 break;
1351 case MODE_BEET:
1352 case MODE_TRANSPORT:
1353 if (original_mode == MODE_TUNNEL)
1354 { /* don't install selectors for switched SAs. because only one
1355 * selector can be installed other traffic would get dropped */
1356 break;
1357 }
1358 if (data->src_ts->get_first(data->src_ts,
1359 (void**)&first_src_ts) == SUCCESS &&
1360 data->dst_ts->get_first(data->dst_ts,
1361 (void**)&first_dst_ts) == SUCCESS)
1362 {
1363 sa->sel = ts2selector(first_src_ts, first_dst_ts,
1364 data->interface);
1365 if (!this->proto_port_transport)
1366 {
1367 /* don't install proto/port on SA. This would break
1368 * potential secondary SAs for the same address using a
1369 * different prot/port. */
1370 sa->sel.proto = 0;
1371 sa->sel.dport = sa->sel.dport_mask = 0;
1372 sa->sel.sport = sa->sel.sport_mask = 0;
1373 }
1374 }
1375 break;
1376 default:
1377 break;
1378 }
1379 if (id->proto == IPPROTO_AH && sa->family == AF_INET)
1380 { /* use alignment to 4 bytes for IPv4 instead of the incorrect 8 byte
1381 * alignment that's used by default but is only valid for IPv6 */
1382 sa->flags |= XFRM_STATE_ALIGN4;
1383 }
1384
1385 sa->reqid = data->reqid;
1386 sa->lft.soft_byte_limit = XFRM_LIMIT(data->lifetime->bytes.rekey);
1387 sa->lft.hard_byte_limit = XFRM_LIMIT(data->lifetime->bytes.life);
1388 sa->lft.soft_packet_limit = XFRM_LIMIT(data->lifetime->packets.rekey);
1389 sa->lft.hard_packet_limit = XFRM_LIMIT(data->lifetime->packets.life);
1390 /* we use lifetimes since added, not since used */
1391 sa->lft.soft_add_expires_seconds = data->lifetime->time.rekey;
1392 sa->lft.hard_add_expires_seconds = data->lifetime->time.life;
1393 sa->lft.soft_use_expires_seconds = 0;
1394 sa->lft.hard_use_expires_seconds = 0;
1395
1396 switch (data->enc_alg)
1397 {
1398 case ENCR_UNDEFINED:
1399 /* no encryption */
1400 break;
1401 case ENCR_AES_CCM_ICV16:
1402 case ENCR_AES_GCM_ICV16:
1403 case ENCR_NULL_AUTH_AES_GMAC:
1404 case ENCR_CAMELLIA_CCM_ICV16:
1405 case ENCR_CHACHA20_POLY1305:
1406 icv_size += 32;
1407 /* FALL */
1408 case ENCR_AES_CCM_ICV12:
1409 case ENCR_AES_GCM_ICV12:
1410 case ENCR_CAMELLIA_CCM_ICV12:
1411 icv_size += 32;
1412 /* FALL */
1413 case ENCR_AES_CCM_ICV8:
1414 case ENCR_AES_GCM_ICV8:
1415 case ENCR_CAMELLIA_CCM_ICV8:
1416 {
1417 struct xfrm_algo_aead *algo;
1418
1419 alg_name = lookup_algorithm(ENCRYPTION_ALGORITHM, data->enc_alg);
1420 if (alg_name == NULL)
1421 {
1422 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1423 encryption_algorithm_names, data->enc_alg);
1424 goto failed;
1425 }
1426 DBG2(DBG_KNL, " using encryption algorithm %N with key size %d",
1427 encryption_algorithm_names, data->enc_alg,
1428 data->enc_key.len * 8);
1429
1430 algo = netlink_reserve(hdr, sizeof(request), XFRMA_ALG_AEAD,
1431 sizeof(*algo) + data->enc_key.len);
1432 if (!algo)
1433 {
1434 goto failed;
1435 }
1436 algo->alg_key_len = data->enc_key.len * 8;
1437 algo->alg_icv_len = icv_size;
1438 strncpy(algo->alg_name, alg_name, sizeof(algo->alg_name));
1439 algo->alg_name[sizeof(algo->alg_name) - 1] = '\0';
1440 memcpy(algo->alg_key, data->enc_key.ptr, data->enc_key.len);
1441 break;
1442 }
1443 default:
1444 {
1445 struct xfrm_algo *algo;
1446
1447 alg_name = lookup_algorithm(ENCRYPTION_ALGORITHM, data->enc_alg);
1448 if (alg_name == NULL)
1449 {
1450 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1451 encryption_algorithm_names, data->enc_alg);
1452 goto failed;
1453 }
1454 DBG2(DBG_KNL, " using encryption algorithm %N with key size %d",
1455 encryption_algorithm_names, data->enc_alg,
1456 data->enc_key.len * 8);
1457
1458 algo = netlink_reserve(hdr, sizeof(request), XFRMA_ALG_CRYPT,
1459 sizeof(*algo) + data->enc_key.len);
1460 if (!algo)
1461 {
1462 goto failed;
1463 }
1464 algo->alg_key_len = data->enc_key.len * 8;
1465 strncpy(algo->alg_name, alg_name, sizeof(algo->alg_name));
1466 algo->alg_name[sizeof(algo->alg_name) - 1] = '\0';
1467 memcpy(algo->alg_key, data->enc_key.ptr, data->enc_key.len);
1468 }
1469 }
1470
1471 if (data->int_alg != AUTH_UNDEFINED)
1472 {
1473 u_int trunc_len = 0;
1474
1475 alg_name = lookup_algorithm(INTEGRITY_ALGORITHM, data->int_alg);
1476 if (alg_name == NULL)
1477 {
1478 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1479 integrity_algorithm_names, data->int_alg);
1480 goto failed;
1481 }
1482 DBG2(DBG_KNL, " using integrity algorithm %N with key size %d",
1483 integrity_algorithm_names, data->int_alg, data->int_key.len * 8);
1484
1485 switch (data->int_alg)
1486 {
1487 case AUTH_HMAC_MD5_128:
1488 case AUTH_HMAC_SHA2_256_128:
1489 trunc_len = 128;
1490 break;
1491 case AUTH_HMAC_SHA1_160:
1492 trunc_len = 160;
1493 break;
1494 default:
1495 break;
1496 }
1497
1498 if (trunc_len)
1499 {
1500 struct xfrm_algo_auth* algo;
1501
1502 /* the kernel uses SHA256 with 96 bit truncation by default,
1503 * use specified truncation size supported by newer kernels.
1504 * also use this for untruncated MD5 and SHA1. */
1505 algo = netlink_reserve(hdr, sizeof(request), XFRMA_ALG_AUTH_TRUNC,
1506 sizeof(*algo) + data->int_key.len);
1507 if (!algo)
1508 {
1509 goto failed;
1510 }
1511 algo->alg_key_len = data->int_key.len * 8;
1512 algo->alg_trunc_len = trunc_len;
1513 strncpy(algo->alg_name, alg_name, sizeof(algo->alg_name));
1514 algo->alg_name[sizeof(algo->alg_name) - 1] = '\0';
1515 memcpy(algo->alg_key, data->int_key.ptr, data->int_key.len);
1516 }
1517 else
1518 {
1519 struct xfrm_algo* algo;
1520
1521 algo = netlink_reserve(hdr, sizeof(request), XFRMA_ALG_AUTH,
1522 sizeof(*algo) + data->int_key.len);
1523 if (!algo)
1524 {
1525 goto failed;
1526 }
1527 algo->alg_key_len = data->int_key.len * 8;
1528 strncpy(algo->alg_name, alg_name, sizeof(algo->alg_name));
1529 algo->alg_name[sizeof(algo->alg_name) - 1] = '\0';
1530 memcpy(algo->alg_key, data->int_key.ptr, data->int_key.len);
1531 }
1532 }
1533
1534 if (ipcomp != IPCOMP_NONE)
1535 {
1536 struct xfrm_algo* algo;
1537
1538 alg_name = lookup_algorithm(COMPRESSION_ALGORITHM, ipcomp);
1539 if (alg_name == NULL)
1540 {
1541 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1542 ipcomp_transform_names, ipcomp);
1543 goto failed;
1544 }
1545 DBG2(DBG_KNL, " using compression algorithm %N",
1546 ipcomp_transform_names, ipcomp);
1547
1548 algo = netlink_reserve(hdr, sizeof(request), XFRMA_ALG_COMP,
1549 sizeof(*algo));
1550 if (!algo)
1551 {
1552 goto failed;
1553 }
1554 algo->alg_key_len = 0;
1555 strncpy(algo->alg_name, alg_name, sizeof(algo->alg_name));
1556 algo->alg_name[sizeof(algo->alg_name) - 1] = '\0';
1557 }
1558
1559 if (data->encap)
1560 {
1561 struct xfrm_encap_tmpl *tmpl;
1562
1563 tmpl = netlink_reserve(hdr, sizeof(request), XFRMA_ENCAP, sizeof(*tmpl));
1564 if (!tmpl)
1565 {
1566 goto failed;
1567 }
1568 tmpl->encap_type = UDP_ENCAP_ESPINUDP;
1569 tmpl->encap_sport = htons(id->src->get_port(id->src));
1570 tmpl->encap_dport = htons(id->dst->get_port(id->dst));
1571 memset(&tmpl->encap_oa, 0, sizeof (xfrm_address_t));
1572 /* encap_oa could probably be derived from the
1573 * traffic selectors [rfc4306, p39]. In the netlink kernel
1574 * implementation pluto does the same as we do here but it uses
1575 * encap_oa in the pfkey implementation.
1576 * BUT as /usr/src/linux/net/key/af_key.c indicates the kernel ignores
1577 * it anyway
1578 * -> does that mean that NAT-T encap doesn't work in transport mode?
1579 * No. The reason the kernel ignores NAT-OA is that it recomputes
1580 * (or, rather, just ignores) the checksum. If packets pass the IPsec
1581 * checks it marks them "checksum ok" so OA isn't needed. */
1582 }
1583
1584 if (!add_mark(hdr, sizeof(request), id->mark))
1585 {
1586 goto failed;
1587 }
1588
1589 if (data->tfc && id->proto == IPPROTO_ESP && mode == MODE_TUNNEL)
1590 { /* the kernel supports TFC padding only for tunnel mode ESP SAs */
1591 uint32_t *tfcpad;
1592
1593 tfcpad = netlink_reserve(hdr, sizeof(request), XFRMA_TFCPAD,
1594 sizeof(*tfcpad));
1595 if (!tfcpad)
1596 {
1597 goto failed;
1598 }
1599 *tfcpad = data->tfc;
1600 }
1601
1602 if (id->proto != IPPROTO_COMP)
1603 {
1604 /* generally, we don't need a replay window for outbound SAs, however,
1605 * when using ESN the kernel rejects the attribute if it is 0 */
1606 if (!data->inbound && data->replay_window)
1607 {
1608 data->replay_window = data->esn ? 1 : 0;
1609 }
1610 if (data->replay_window != 0 && (data->esn || data->replay_window > 32))
1611 {
1612 /* for ESN or larger replay windows we need the new
1613 * XFRMA_REPLAY_ESN_VAL attribute to configure a bitmap */
1614 struct xfrm_replay_state_esn *replay;
1615 uint32_t bmp_size;
1616
1617 bmp_size = round_up(data->replay_window, sizeof(uint32_t) * 8) / 8;
1618 replay = netlink_reserve(hdr, sizeof(request), XFRMA_REPLAY_ESN_VAL,
1619 sizeof(*replay) + bmp_size);
1620 if (!replay)
1621 {
1622 goto failed;
1623 }
1624 /* bmp_len contains number uf __u32's */
1625 replay->bmp_len = bmp_size / sizeof(uint32_t);
1626 replay->replay_window = data->replay_window;
1627 DBG2(DBG_KNL, " using replay window of %u packets",
1628 data->replay_window);
1629
1630 if (data->esn)
1631 {
1632 DBG2(DBG_KNL, " using extended sequence numbers (ESN)");
1633 sa->flags |= XFRM_STATE_ESN;
1634 }
1635 }
1636 else
1637 {
1638 DBG2(DBG_KNL, " using replay window of %u packets",
1639 data->replay_window);
1640 sa->replay_window = data->replay_window;
1641 }
1642 }
1643
1644 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
1645 {
1646 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x%s", ntohl(id->spi),
1647 markstr);
1648 goto failed;
1649 }
1650
1651 status = SUCCESS;
1652
1653 failed:
1654 memwipe(&request, sizeof(request));
1655 return status;
1656 }
1657
1658 /**
1659 * Get the ESN replay state (i.e. sequence numbers) of an SA.
1660 *
1661 * Allocates into one the replay state structure we get from the kernel.
1662 */
1663 static void get_replay_state(private_kernel_netlink_ipsec_t *this,
1664 kernel_ipsec_sa_id_t *sa,
1665 struct xfrm_replay_state_esn **replay_esn,
1666 uint32_t *replay_esn_len,
1667 struct xfrm_replay_state **replay,
1668 struct xfrm_lifetime_cur **lifetime)
1669 {
1670 netlink_buf_t request;
1671 struct nlmsghdr *hdr, *out = NULL;
1672 struct xfrm_aevent_id *out_aevent = NULL, *aevent_id;
1673 size_t len;
1674 struct rtattr *rta;
1675 size_t rtasize;
1676
1677 memset(&request, 0, sizeof(request));
1678
1679 DBG2(DBG_KNL, "querying replay state from SAD entry with SPI %.8x",
1680 ntohl(sa->spi));
1681
1682 hdr = &request.hdr;
1683 hdr->nlmsg_flags = NLM_F_REQUEST;
1684 hdr->nlmsg_type = XFRM_MSG_GETAE;
1685 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_aevent_id));
1686
1687 aevent_id = NLMSG_DATA(hdr);
1688 aevent_id->flags = XFRM_AE_RVAL;
1689
1690 host2xfrm(sa->dst, &aevent_id->sa_id.daddr);
1691 aevent_id->sa_id.spi = sa->spi;
1692 aevent_id->sa_id.proto = sa->proto;
1693 aevent_id->sa_id.family = sa->dst->get_family(sa->dst);
1694
1695 if (!add_mark(hdr, sizeof(request), sa->mark))
1696 {
1697 return;
1698 }
1699
1700 if (this->socket_xfrm->send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
1701 {
1702 hdr = out;
1703 while (NLMSG_OK(hdr, len))
1704 {
1705 switch (hdr->nlmsg_type)
1706 {
1707 case XFRM_MSG_NEWAE:
1708 {
1709 out_aevent = NLMSG_DATA(hdr);
1710 break;
1711 }
1712 case NLMSG_ERROR:
1713 {
1714 struct nlmsgerr *err = NLMSG_DATA(hdr);
1715 DBG1(DBG_KNL, "querying replay state from SAD entry "
1716 "failed: %s (%d)", strerror(-err->error), -err->error);
1717 break;
1718 }
1719 default:
1720 hdr = NLMSG_NEXT(hdr, len);
1721 continue;
1722 case NLMSG_DONE:
1723 break;
1724 }
1725 break;
1726 }
1727 }
1728
1729 if (out_aevent)
1730 {
1731 rta = XFRM_RTA(out, struct xfrm_aevent_id);
1732 rtasize = XFRM_PAYLOAD(out, struct xfrm_aevent_id);
1733 while (RTA_OK(rta, rtasize))
1734 {
1735 if (rta->rta_type == XFRMA_LTIME_VAL &&
1736 RTA_PAYLOAD(rta) == sizeof(**lifetime))
1737 {
1738 free(*lifetime);
1739 *lifetime = malloc(RTA_PAYLOAD(rta));
1740 memcpy(*lifetime, RTA_DATA(rta), RTA_PAYLOAD(rta));
1741 }
1742 if (rta->rta_type == XFRMA_REPLAY_VAL &&
1743 RTA_PAYLOAD(rta) == sizeof(**replay))
1744 {
1745 free(*replay);
1746 *replay = malloc(RTA_PAYLOAD(rta));
1747 memcpy(*replay, RTA_DATA(rta), RTA_PAYLOAD(rta));
1748 }
1749 if (rta->rta_type == XFRMA_REPLAY_ESN_VAL &&
1750 RTA_PAYLOAD(rta) >= sizeof(**replay_esn))
1751 {
1752 free(*replay_esn);
1753 *replay_esn = malloc(RTA_PAYLOAD(rta));
1754 *replay_esn_len = RTA_PAYLOAD(rta);
1755 memcpy(*replay_esn, RTA_DATA(rta), RTA_PAYLOAD(rta));
1756 }
1757 rta = RTA_NEXT(rta, rtasize);
1758 }
1759 }
1760 free(out);
1761 }
1762
1763 METHOD(kernel_ipsec_t, query_sa, status_t,
1764 private_kernel_netlink_ipsec_t *this, kernel_ipsec_sa_id_t *id,
1765 kernel_ipsec_query_sa_t *data, uint64_t *bytes, uint64_t *packets,
1766 time_t *time)
1767 {
1768 netlink_buf_t request;
1769 struct nlmsghdr *out = NULL, *hdr;
1770 struct xfrm_usersa_id *sa_id;
1771 struct xfrm_usersa_info *sa = NULL;
1772 status_t status = FAILED;
1773 size_t len;
1774 char markstr[32] = "";
1775
1776 memset(&request, 0, sizeof(request));
1777 format_mark(markstr, sizeof(markstr), id->mark);
1778
1779 DBG2(DBG_KNL, "querying SAD entry with SPI %.8x%s", ntohl(id->spi),
1780 markstr);
1781
1782 hdr = &request.hdr;
1783 hdr->nlmsg_flags = NLM_F_REQUEST;
1784 hdr->nlmsg_type = XFRM_MSG_GETSA;
1785 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_id));
1786
1787 sa_id = NLMSG_DATA(hdr);
1788 host2xfrm(id->dst, &sa_id->daddr);
1789 sa_id->spi = id->spi;
1790 sa_id->proto = id->proto;
1791 sa_id->family = id->dst->get_family(id->dst);
1792
1793 if (!add_mark(hdr, sizeof(request), id->mark))
1794 {
1795 return FAILED;
1796 }
1797
1798 if (this->socket_xfrm->send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
1799 {
1800 hdr = out;
1801 while (NLMSG_OK(hdr, len))
1802 {
1803 switch (hdr->nlmsg_type)
1804 {
1805 case XFRM_MSG_NEWSA:
1806 {
1807 sa = NLMSG_DATA(hdr);
1808 break;
1809 }
1810 case NLMSG_ERROR:
1811 {
1812 struct nlmsgerr *err = NLMSG_DATA(hdr);
1813
1814 DBG1(DBG_KNL, "querying SAD entry with SPI %.8x%s failed: "
1815 "%s (%d)", ntohl(id->spi), markstr,
1816 strerror(-err->error), -err->error);
1817 break;
1818 }
1819 default:
1820 hdr = NLMSG_NEXT(hdr, len);
1821 continue;
1822 case NLMSG_DONE:
1823 break;
1824 }
1825 break;
1826 }
1827 }
1828
1829 if (sa == NULL)
1830 {
1831 DBG2(DBG_KNL, "unable to query SAD entry with SPI %.8x%s",
1832 ntohl(id->spi), markstr);
1833 }
1834 else
1835 {
1836 if (bytes)
1837 {
1838 *bytes = sa->curlft.bytes;
1839 }
1840 if (packets)
1841 {
1842 *packets = sa->curlft.packets;
1843 }
1844 if (time)
1845 { /* curlft contains an "use" time, but that contains a timestamp
1846 * of the first use, not the last. Last use time must be queried
1847 * on the policy on Linux */
1848 *time = 0;
1849 }
1850 status = SUCCESS;
1851 }
1852 memwipe(out, len);
1853 free(out);
1854 return status;
1855 }
1856
1857 METHOD(kernel_ipsec_t, del_sa, status_t,
1858 private_kernel_netlink_ipsec_t *this, kernel_ipsec_sa_id_t *id,
1859 kernel_ipsec_del_sa_t *data)
1860 {
1861 netlink_buf_t request;
1862 struct nlmsghdr *hdr;
1863 struct xfrm_usersa_id *sa_id;
1864 char markstr[32] = "";
1865
1866 /* if IPComp was used, we first delete the additional IPComp SA */
1867 if (data->cpi)
1868 {
1869 kernel_ipsec_sa_id_t ipcomp_id = {
1870 .src = id->src,
1871 .dst = id->dst,
1872 .spi = htonl(ntohs(data->cpi)),
1873 .proto = IPPROTO_COMP,
1874 .mark = id->mark,
1875 };
1876 kernel_ipsec_del_sa_t ipcomp = {};
1877 del_sa(this, &ipcomp_id, &ipcomp);
1878 }
1879
1880 memset(&request, 0, sizeof(request));
1881 format_mark(markstr, sizeof(markstr), id->mark);
1882
1883 DBG2(DBG_KNL, "deleting SAD entry with SPI %.8x%s", ntohl(id->spi),
1884 markstr);
1885
1886 hdr = &request.hdr;
1887 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
1888 hdr->nlmsg_type = XFRM_MSG_DELSA;
1889 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_id));
1890
1891 sa_id = NLMSG_DATA(hdr);
1892 host2xfrm(id->dst, &sa_id->daddr);
1893 sa_id->spi = id->spi;
1894 sa_id->proto = id->proto;
1895 sa_id->family = id->dst->get_family(id->dst);
1896
1897 if (!add_mark(hdr, sizeof(request), id->mark))
1898 {
1899 return FAILED;
1900 }
1901
1902 switch (this->socket_xfrm->send_ack(this->socket_xfrm, hdr))
1903 {
1904 case SUCCESS:
1905 DBG2(DBG_KNL, "deleted SAD entry with SPI %.8x%s",
1906 ntohl(id->spi), markstr);
1907 return SUCCESS;
1908 case NOT_FOUND:
1909 return NOT_FOUND;
1910 default:
1911 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x%s",
1912 ntohl(id->spi), markstr);
1913 return FAILED;
1914 }
1915 }
1916
1917 METHOD(kernel_ipsec_t, update_sa, status_t,
1918 private_kernel_netlink_ipsec_t *this, kernel_ipsec_sa_id_t *id,
1919 kernel_ipsec_update_sa_t *data)
1920 {
1921 netlink_buf_t request;
1922 struct nlmsghdr *hdr, *out = NULL;
1923 struct xfrm_usersa_id *sa_id;
1924 struct xfrm_usersa_info *out_sa = NULL, *sa;
1925 size_t len;
1926 struct rtattr *rta;
1927 size_t rtasize;
1928 struct xfrm_encap_tmpl* tmpl = NULL;
1929 struct xfrm_replay_state *replay = NULL;
1930 struct xfrm_replay_state_esn *replay_esn = NULL;
1931 struct xfrm_lifetime_cur *lifetime = NULL;
1932 uint32_t replay_esn_len = 0;
1933 kernel_ipsec_del_sa_t del = { 0 };
1934 status_t status = FAILED;
1935 char markstr[32] = "";
1936
1937 /* if IPComp is used, we first update the IPComp SA */
1938 if (data->cpi)
1939 {
1940 kernel_ipsec_sa_id_t ipcomp_id = {
1941 .src = id->src,
1942 .dst = id->dst,
1943 .spi = htonl(ntohs(data->cpi)),
1944 .proto = IPPROTO_COMP,
1945 .mark = id->mark,
1946 };
1947 kernel_ipsec_update_sa_t ipcomp = {
1948 .new_src = data->new_src,
1949 .new_dst = data->new_dst,
1950 };
1951 update_sa(this, &ipcomp_id, &ipcomp);
1952 }
1953
1954 memset(&request, 0, sizeof(request));
1955 format_mark(markstr, sizeof(markstr), id->mark);
1956
1957 DBG2(DBG_KNL, "querying SAD entry with SPI %.8x%s for update",
1958 ntohl(id->spi), markstr);
1959
1960 /* query the existing SA first */
1961 hdr = &request.hdr;
1962 hdr->nlmsg_flags = NLM_F_REQUEST;
1963 hdr->nlmsg_type = XFRM_MSG_GETSA;
1964 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_id));
1965
1966 sa_id = NLMSG_DATA(hdr);
1967 host2xfrm(id->dst, &sa_id->daddr);
1968 sa_id->spi = id->spi;
1969 sa_id->proto = id->proto;
1970 sa_id->family = id->dst->get_family(id->dst);
1971
1972 if (!add_mark(hdr, sizeof(request), id->mark))
1973 {
1974 return FAILED;
1975 }
1976
1977 if (this->socket_xfrm->send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
1978 {
1979 hdr = out;
1980 while (NLMSG_OK(hdr, len))
1981 {
1982 switch (hdr->nlmsg_type)
1983 {
1984 case XFRM_MSG_NEWSA:
1985 {
1986 out_sa = NLMSG_DATA(hdr);
1987 break;
1988 }
1989 case NLMSG_ERROR:
1990 {
1991 struct nlmsgerr *err = NLMSG_DATA(hdr);
1992 DBG1(DBG_KNL, "querying SAD entry failed: %s (%d)",
1993 strerror(-err->error), -err->error);
1994 break;
1995 }
1996 default:
1997 hdr = NLMSG_NEXT(hdr, len);
1998 continue;
1999 case NLMSG_DONE:
2000 break;
2001 }
2002 break;
2003 }
2004 }
2005 if (out_sa == NULL)
2006 {
2007 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x%s",
2008 ntohl(id->spi), markstr);
2009 goto failed;
2010 }
2011
2012 get_replay_state(this, id, &replay_esn, &replay_esn_len, &replay,
2013 &lifetime);
2014
2015 /* delete the old SA (without affecting the IPComp SA) */
2016 if (del_sa(this, id, &del) != SUCCESS)
2017 {
2018 DBG1(DBG_KNL, "unable to delete old SAD entry with SPI %.8x%s",
2019 ntohl(id->spi), markstr);
2020 goto failed;
2021 }
2022
2023 DBG2(DBG_KNL, "updating SAD entry with SPI %.8x%s from %#H..%#H to "
2024 "%#H..%#H", ntohl(id->spi), markstr, id->src, id->dst, data->new_src,
2025 data->new_dst);
2026 /* copy over the SA from out to request */
2027 hdr = &request.hdr;
2028 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2029 hdr->nlmsg_type = XFRM_MSG_NEWSA;
2030 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_info));
2031 sa = NLMSG_DATA(hdr);
2032 memcpy(sa, NLMSG_DATA(out), sizeof(struct xfrm_usersa_info));
2033 sa->family = data->new_dst->get_family(data->new_dst);
2034
2035 if (!id->src->ip_equals(id->src, data->new_src))
2036 {
2037 host2xfrm(data->new_src, &sa->saddr);
2038 }
2039 if (!id->dst->ip_equals(id->dst, data->new_dst))
2040 {
2041 host2xfrm(data->new_dst, &sa->id.daddr);
2042 }
2043
2044 rta = XFRM_RTA(out, struct xfrm_usersa_info);
2045 rtasize = XFRM_PAYLOAD(out, struct xfrm_usersa_info);
2046 while (RTA_OK(rta, rtasize))
2047 {
2048 /* copy all attributes, but not XFRMA_ENCAP if we are disabling it */
2049 if (rta->rta_type != XFRMA_ENCAP || data->new_encap)
2050 {
2051 if (rta->rta_type == XFRMA_ENCAP)
2052 { /* update encap tmpl */
2053 tmpl = RTA_DATA(rta);
2054 tmpl->encap_sport = ntohs(data->new_src->get_port(data->new_src));
2055 tmpl->encap_dport = ntohs(data->new_dst->get_port(data->new_dst));
2056 }
2057 netlink_add_attribute(hdr, rta->rta_type,
2058 chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta)),
2059 sizeof(request));
2060 }
2061 rta = RTA_NEXT(rta, rtasize);
2062 }
2063
2064 if (tmpl == NULL && data->new_encap)
2065 { /* add tmpl if we are enabling it */
2066 tmpl = netlink_reserve(hdr, sizeof(request), XFRMA_ENCAP, sizeof(*tmpl));
2067 if (!tmpl)
2068 {
2069 goto failed;
2070 }
2071 tmpl->encap_type = UDP_ENCAP_ESPINUDP;
2072 tmpl->encap_sport = ntohs(data->new_src->get_port(data->new_src));
2073 tmpl->encap_dport = ntohs(data->new_dst->get_port(data->new_dst));
2074 memset(&tmpl->encap_oa, 0, sizeof (xfrm_address_t));
2075 }
2076
2077 if (replay_esn)
2078 {
2079 struct xfrm_replay_state_esn *state;
2080
2081 state = netlink_reserve(hdr, sizeof(request), XFRMA_REPLAY_ESN_VAL,
2082 replay_esn_len);
2083 if (!state)
2084 {
2085 goto failed;
2086 }
2087 memcpy(state, replay_esn, replay_esn_len);
2088 }
2089 else if (replay)
2090 {
2091 struct xfrm_replay_state *state;
2092
2093 state = netlink_reserve(hdr, sizeof(request), XFRMA_REPLAY_VAL,
2094 sizeof(*state));
2095 if (!state)
2096 {
2097 goto failed;
2098 }
2099 memcpy(state, replay, sizeof(*state));
2100 }
2101 else
2102 {
2103 DBG1(DBG_KNL, "unable to copy replay state from old SAD entry with "
2104 "SPI %.8x%s", ntohl(id->spi), markstr);
2105 }
2106 if (lifetime)
2107 {
2108 struct xfrm_lifetime_cur *state;
2109
2110 state = netlink_reserve(hdr, sizeof(request), XFRMA_LTIME_VAL,
2111 sizeof(*state));
2112 if (!state)
2113 {
2114 goto failed;
2115 }
2116 memcpy(state, lifetime, sizeof(*state));
2117 }
2118 else
2119 {
2120 DBG1(DBG_KNL, "unable to copy usage stats from old SAD entry with "
2121 "SPI %.8x%s", ntohl(id->spi), markstr);
2122 }
2123
2124 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
2125 {
2126 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x%s",
2127 ntohl(id->spi), markstr);
2128 goto failed;
2129 }
2130
2131 status = SUCCESS;
2132 failed:
2133 free(replay);
2134 free(replay_esn);
2135 free(lifetime);
2136 memwipe(out, len);
2137 memwipe(&request, sizeof(request));
2138 free(out);
2139
2140 return status;
2141 }
2142
2143 METHOD(kernel_ipsec_t, flush_sas, status_t,
2144 private_kernel_netlink_ipsec_t *this)
2145 {
2146 netlink_buf_t request;
2147 struct nlmsghdr *hdr;
2148 struct xfrm_usersa_flush *flush;
2149 struct {
2150 uint8_t proto;
2151 char *name;
2152 } protos[] = {
2153 { IPPROTO_AH, "AH" },
2154 { IPPROTO_ESP, "ESP" },
2155 { IPPROTO_COMP, "IPComp" },
2156 };
2157 int i;
2158
2159 memset(&request, 0, sizeof(request));
2160
2161 hdr = &request.hdr;
2162 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2163 hdr->nlmsg_type = XFRM_MSG_FLUSHSA;
2164 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_flush));
2165
2166 flush = NLMSG_DATA(hdr);
2167
2168 for (i = 0; i < countof(protos); i++)
2169 {
2170 DBG2(DBG_KNL, "flushing all %s SAD entries", protos[i].name);
2171
2172 flush->proto = protos[i].proto;
2173
2174 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
2175 {
2176 DBG1(DBG_KNL, "unable to flush %s SAD entries", protos[i].name);
2177 return FAILED;
2178 }
2179 }
2180 return SUCCESS;
2181 }
2182
2183 /**
2184 * Unlock the mutex and signal waiting threads
2185 */
2186 static void policy_change_done(private_kernel_netlink_ipsec_t *this,
2187 policy_entry_t *policy)
2188 {
2189 policy->working = FALSE;
2190 if (policy->waiting)
2191 { /* don't need to wake threads waiting for other policies */
2192 this->condvar->broadcast(this->condvar);
2193 }
2194 this->mutex->unlock(this->mutex);
2195 }
2196
2197 /**
2198 * Install a route for the given policy if enabled and required
2199 */
2200 static void install_route(private_kernel_netlink_ipsec_t *this,
2201 policy_entry_t *policy, policy_sa_t *mapping, ipsec_sa_t *ipsec)
2202 {
2203 policy_sa_out_t *out = (policy_sa_out_t*)mapping;
2204 route_entry_t *route;
2205 host_t *iface;
2206
2207 INIT(route,
2208 .prefixlen = policy->sel.prefixlen_d,
2209 );
2210
2211 if (charon->kernel->get_address_by_ts(charon->kernel, out->src_ts,
2212 &route->src_ip, NULL) == SUCCESS)
2213 {
2214 if (!ipsec->dst->is_anyaddr(ipsec->dst))
2215 {
2216 route->gateway = charon->kernel->get_nexthop(charon->kernel,
2217 ipsec->dst, -1, ipsec->src,
2218 &route->if_name);
2219 }
2220 else
2221 { /* for shunt policies */
2222 iface = xfrm2host(policy->sel.family, &policy->sel.daddr, 0);
2223 route->gateway = charon->kernel->get_nexthop(charon->kernel,
2224 iface, policy->sel.prefixlen_d,
2225 route->src_ip, &route->if_name);
2226 iface->destroy(iface);
2227 }
2228 route->dst_net = chunk_alloc(policy->sel.family == AF_INET ? 4 : 16);
2229 memcpy(route->dst_net.ptr, &policy->sel.daddr, route->dst_net.len);
2230
2231 /* get the interface to install the route for, if we haven't one yet.
2232 * If we have a local address, use it. Otherwise (for shunt policies)
2233 * use the route's source address. */
2234 if (!route->if_name)
2235 {
2236 iface = ipsec->src;
2237 if (iface->is_anyaddr(iface))
2238 {
2239 iface = route->src_ip;
2240 }
2241 if (!charon->kernel->get_interface(charon->kernel, iface,
2242 &route->if_name))
2243 {
2244 route_entry_destroy(route);
2245 return;
2246 }
2247 }
2248 if (policy->route)
2249 {
2250 route_entry_t *old = policy->route;
2251 if (route_entry_equals(old, route))
2252 {
2253 route_entry_destroy(route);
2254 return;
2255 }
2256 /* uninstall previously installed route */
2257 if (charon->kernel->del_route(charon->kernel, old->dst_net,
2258 old->prefixlen, old->gateway,
2259 old->src_ip, old->if_name) != SUCCESS)
2260 {
2261 DBG1(DBG_KNL, "error uninstalling route installed with policy "
2262 "%R === %R %N", out->src_ts, out->dst_ts, policy_dir_names,
2263 policy->direction);
2264 }
2265 route_entry_destroy(old);
2266 policy->route = NULL;
2267 }
2268
2269 DBG2(DBG_KNL, "installing route: %R via %H src %H dev %s", out->dst_ts,
2270 route->gateway, route->src_ip, route->if_name);
2271 switch (charon->kernel->add_route(charon->kernel, route->dst_net,
2272 route->prefixlen, route->gateway,
2273 route->src_ip, route->if_name))
2274 {
2275 default:
2276 DBG1(DBG_KNL, "unable to install source route for %H",
2277 route->src_ip);
2278 /* FALL */
2279 case ALREADY_DONE:
2280 /* route exists, do not uninstall */
2281 route_entry_destroy(route);
2282 break;
2283 case SUCCESS:
2284 /* cache the installed route */
2285 policy->route = route;
2286 break;
2287 }
2288 }
2289 else
2290 {
2291 free(route);
2292 }
2293 }
2294
2295 /**
2296 * Add or update a policy in the kernel.
2297 *
2298 * Note: The mutex has to be locked when entering this function
2299 * and is unlocked here in any case.
2300 */
2301 static status_t add_policy_internal(private_kernel_netlink_ipsec_t *this,
2302 policy_entry_t *policy, policy_sa_t *mapping, bool update)
2303 {
2304 netlink_buf_t request;
2305 policy_entry_t clone;
2306 ipsec_sa_t *ipsec = mapping->sa;
2307 struct xfrm_userpolicy_info *policy_info;
2308 struct nlmsghdr *hdr;
2309 status_t status;
2310 int i;
2311
2312 /* clone the policy so we are able to check it out again later */
2313 memcpy(&clone, policy, sizeof(policy_entry_t));
2314
2315 memset(&request, 0, sizeof(request));
2316 hdr = &request.hdr;
2317 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2318 hdr->nlmsg_type = update ? XFRM_MSG_UPDPOLICY : XFRM_MSG_NEWPOLICY;
2319 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_info));
2320
2321 policy_info = NLMSG_DATA(hdr);
2322 policy_info->sel = policy->sel;
2323 policy_info->dir = policy->direction;
2324
2325 /* calculate priority based on selector size, small size = high prio */
2326 policy_info->priority = mapping->priority;
2327 policy_info->action = mapping->type != POLICY_DROP ? XFRM_POLICY_ALLOW
2328 : XFRM_POLICY_BLOCK;
2329 policy_info->share = XFRM_SHARE_ANY;
2330
2331 /* policies don't expire */
2332 policy_info->lft.soft_byte_limit = XFRM_INF;
2333 policy_info->lft.soft_packet_limit = XFRM_INF;
2334 policy_info->lft.hard_byte_limit = XFRM_INF;
2335 policy_info->lft.hard_packet_limit = XFRM_INF;
2336 policy_info->lft.soft_add_expires_seconds = 0;
2337 policy_info->lft.hard_add_expires_seconds = 0;
2338 policy_info->lft.soft_use_expires_seconds = 0;
2339 policy_info->lft.hard_use_expires_seconds = 0;
2340
2341 if (mapping->type == POLICY_IPSEC && ipsec->cfg.reqid)
2342 {
2343 struct xfrm_user_tmpl *tmpl;
2344 struct {
2345 uint8_t proto;
2346 bool use;
2347 } protos[] = {
2348 { IPPROTO_COMP, ipsec->cfg.ipcomp.transform != IPCOMP_NONE },
2349 { IPPROTO_ESP, ipsec->cfg.esp.use },
2350 { IPPROTO_AH, ipsec->cfg.ah.use },
2351 };
2352 ipsec_mode_t proto_mode = ipsec->cfg.mode;
2353 int count = 0;
2354
2355 for (i = 0; i < countof(protos); i++)
2356 {
2357 if (protos[i].use)
2358 {
2359 count++;
2360 }
2361 }
2362 tmpl = netlink_reserve(hdr, sizeof(request), XFRMA_TMPL,
2363 count * sizeof(*tmpl));
2364 if (!tmpl)
2365 {
2366 policy_change_done(this, policy);
2367 return FAILED;
2368 }
2369
2370 for (i = 0; i < countof(protos); i++)
2371 {
2372 if (!protos[i].use)
2373 {
2374 continue;
2375 }
2376 tmpl->reqid = ipsec->cfg.reqid;
2377 tmpl->id.proto = protos[i].proto;
2378 tmpl->aalgos = tmpl->ealgos = tmpl->calgos = ~0;
2379 tmpl->mode = mode2kernel(proto_mode);
2380 tmpl->optional = protos[i].proto == IPPROTO_COMP &&
2381 policy->direction != POLICY_OUT;
2382 tmpl->family = ipsec->src->get_family(ipsec->src);
2383
2384 if (proto_mode == MODE_TUNNEL || proto_mode == MODE_BEET)
2385 { /* only for tunnel mode */
2386 host2xfrm(ipsec->src, &tmpl->saddr);
2387 host2xfrm(ipsec->dst, &tmpl->id.daddr);
2388 }
2389
2390 tmpl++;
2391
2392 /* use transport mode for other SAs */
2393 proto_mode = MODE_TRANSPORT;
2394 }
2395 }
2396
2397 if (!add_mark(hdr, sizeof(request), ipsec->mark))
2398 {
2399 policy_change_done(this, policy);
2400 return FAILED;
2401 }
2402 this->mutex->unlock(this->mutex);
2403
2404 status = this->socket_xfrm->send_ack(this->socket_xfrm, hdr);
2405 if (status == ALREADY_DONE && !update)
2406 {
2407 DBG1(DBG_KNL, "policy already exists, try to update it");
2408 hdr->nlmsg_type = XFRM_MSG_UPDPOLICY;
2409 status = this->socket_xfrm->send_ack(this->socket_xfrm, hdr);
2410 }
2411
2412 this->mutex->lock(this->mutex);
2413 if (status != SUCCESS)
2414 {
2415 policy_change_done(this, policy);
2416 return FAILED;
2417 }
2418 /* install a route, if:
2419 * - this is an outbound policy (to just get one for each child)
2420 * - routing is not disabled via strongswan.conf
2421 * - the selector is not for a specific protocol/port
2422 * - we are in tunnel/BEET mode or install a bypass policy
2423 */
2424 if (policy->direction == POLICY_OUT && this->install_routes &&
2425 !policy->sel.proto && !policy->sel.dport && !policy->sel.sport)
2426 {
2427 if (mapping->type == POLICY_PASS ||
2428 (mapping->type == POLICY_IPSEC && ipsec->cfg.mode != MODE_TRANSPORT))
2429 {
2430 install_route(this, policy, mapping, ipsec);
2431 }
2432 }
2433 policy_change_done(this, policy);
2434 return SUCCESS;
2435 }
2436
2437 METHOD(kernel_ipsec_t, add_policy, status_t,
2438 private_kernel_netlink_ipsec_t *this, kernel_ipsec_policy_id_t *id,
2439 kernel_ipsec_manage_policy_t *data)
2440 {
2441 policy_entry_t *policy, *current;
2442 policy_sa_t *assigned_sa, *current_sa;
2443 enumerator_t *enumerator;
2444 bool found = FALSE, update = TRUE;
2445 char markstr[32] = "";
2446 uint32_t cur_priority = 0;
2447 int use_count;
2448
2449 /* create a policy */
2450 INIT(policy,
2451 .sel = ts2selector(id->src_ts, id->dst_ts, id->interface),
2452 .mark = id->mark.value & id->mark.mask,
2453 .direction = id->dir,
2454 .reqid = data->sa->reqid,
2455 );
2456 format_mark(markstr, sizeof(markstr), id->mark);
2457
2458 /* find the policy, which matches EXACTLY */
2459 this->mutex->lock(this->mutex);
2460 current = this->policies->get(this->policies, policy);
2461 if (current)
2462 {
2463 if (current->reqid && data->sa->reqid &&
2464 current->reqid != data->sa->reqid)
2465 {
2466 DBG1(DBG_CFG, "unable to install policy %R === %R %N%s for reqid "
2467 "%u, the same policy for reqid %u exists",
2468 id->src_ts, id->dst_ts, policy_dir_names, id->dir, markstr,
2469 data->sa->reqid, current->reqid);
2470 policy_entry_destroy(this, policy);
2471 this->mutex->unlock(this->mutex);
2472 return INVALID_STATE;
2473 }
2474 /* use existing policy */
2475 DBG2(DBG_KNL, "policy %R === %R %N%s already exists, increasing "
2476 "refcount", id->src_ts, id->dst_ts, policy_dir_names, id->dir,
2477 markstr);
2478 policy_entry_destroy(this, policy);
2479 policy = current;
2480 found = TRUE;
2481
2482 policy->waiting++;
2483 while (policy->working)
2484 {
2485 this->condvar->wait(this->condvar, this->mutex);
2486 }
2487 policy->waiting--;
2488 policy->working = TRUE;
2489 }
2490 else
2491 { /* use the new one, if we have no such policy */
2492 policy->used_by = linked_list_create();
2493 this->policies->put(this->policies, policy, policy);
2494 }
2495
2496 /* cache the assigned IPsec SA */
2497 assigned_sa = policy_sa_create(this, id->dir, data->type, data->src,
2498 data->dst, id->src_ts, id->dst_ts, id->mark, data->sa);
2499 assigned_sa->auto_priority = get_priority(policy, data->prio, id->interface);
2500 assigned_sa->priority = this->get_priority ? this->get_priority(id, data)
2501 : data->manual_prio;
2502 assigned_sa->priority = assigned_sa->priority ?: assigned_sa->auto_priority;
2503
2504 /* insert the SA according to its priority */
2505 enumerator = policy->used_by->create_enumerator(policy->used_by);
2506 while (enumerator->enumerate(enumerator, (void**)&current_sa))
2507 {
2508 if (current_sa->priority > assigned_sa->priority)
2509 {
2510 break;
2511 }
2512 if (current_sa->priority == assigned_sa->priority)
2513 {
2514 /* in case of equal manual prios order SAs by automatic priority */
2515 if (current_sa->auto_priority > assigned_sa->auto_priority)
2516 {
2517 break;
2518 }
2519 /* prefer SAs with a reqid over those without */
2520 if (current_sa->auto_priority == assigned_sa->auto_priority &&
2521 (!current_sa->sa->cfg.reqid || assigned_sa->sa->cfg.reqid))
2522 {
2523 break;
2524 }
2525 }
2526 if (update)
2527 {
2528 cur_priority = current_sa->priority;
2529 update = FALSE;
2530 }
2531 }
2532 policy->used_by->insert_before(policy->used_by, enumerator, assigned_sa);
2533 enumerator->destroy(enumerator);
2534
2535 use_count = policy->used_by->get_count(policy->used_by);
2536 if (!update)
2537 { /* we don't update the policy if the priority is lower than that of
2538 * the currently installed one */
2539 policy_change_done(this, policy);
2540 DBG2(DBG_KNL, "not updating policy %R === %R %N%s [priority %u, "
2541 "refcount %d]", id->src_ts, id->dst_ts, policy_dir_names,
2542 id->dir, markstr, cur_priority, use_count);
2543 return SUCCESS;
2544 }
2545 policy->reqid = assigned_sa->sa->cfg.reqid;
2546
2547 if (this->policy_update)
2548 {
2549 found = TRUE;
2550 }
2551
2552 DBG2(DBG_KNL, "%s policy %R === %R %N%s [priority %u, refcount %d]",
2553 found ? "updating" : "adding", id->src_ts, id->dst_ts,
2554 policy_dir_names, id->dir, markstr, assigned_sa->priority, use_count);
2555
2556 if (add_policy_internal(this, policy, assigned_sa, found) != SUCCESS)
2557 {
2558 DBG1(DBG_KNL, "unable to %s policy %R === %R %N%s",
2559 found ? "update" : "add", id->src_ts, id->dst_ts,
2560 policy_dir_names, id->dir, markstr);
2561 return FAILED;
2562 }
2563 return SUCCESS;
2564 }
2565
2566 METHOD(kernel_ipsec_t, query_policy, status_t,
2567 private_kernel_netlink_ipsec_t *this, kernel_ipsec_policy_id_t *id,
2568 kernel_ipsec_query_policy_t *data, time_t *use_time)
2569 {
2570 netlink_buf_t request;
2571 struct nlmsghdr *out = NULL, *hdr;
2572 struct xfrm_userpolicy_id *policy_id;
2573 struct xfrm_userpolicy_info *policy = NULL;
2574 size_t len;
2575 char markstr[32] = "";
2576
2577 memset(&request, 0, sizeof(request));
2578 format_mark(markstr, sizeof(markstr), id->mark);
2579
2580 DBG2(DBG_KNL, "querying policy %R === %R %N%s", id->src_ts, id->dst_ts,
2581 policy_dir_names, id->dir, markstr);
2582
2583 hdr = &request.hdr;
2584 hdr->nlmsg_flags = NLM_F_REQUEST;
2585 hdr->nlmsg_type = XFRM_MSG_GETPOLICY;
2586 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_id));
2587
2588 policy_id = NLMSG_DATA(hdr);
2589 policy_id->sel = ts2selector(id->src_ts, id->dst_ts, id->interface);
2590 policy_id->dir = id->dir;
2591
2592 if (!add_mark(hdr, sizeof(request), id->mark))
2593 {
2594 return FAILED;
2595 }
2596
2597 if (this->socket_xfrm->send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
2598 {
2599 hdr = out;
2600 while (NLMSG_OK(hdr, len))
2601 {
2602 switch (hdr->nlmsg_type)
2603 {
2604 case XFRM_MSG_NEWPOLICY:
2605 {
2606 policy = NLMSG_DATA(hdr);
2607 break;
2608 }
2609 case NLMSG_ERROR:
2610 {
2611 struct nlmsgerr *err = NLMSG_DATA(hdr);
2612 DBG1(DBG_KNL, "querying policy failed: %s (%d)",
2613 strerror(-err->error), -err->error);
2614 break;
2615 }
2616 default:
2617 hdr = NLMSG_NEXT(hdr, len);
2618 continue;
2619 case NLMSG_DONE:
2620 break;
2621 }
2622 break;
2623 }
2624 }
2625
2626 if (policy == NULL)
2627 {
2628 DBG2(DBG_KNL, "unable to query policy %R === %R %N%s", id->src_ts,
2629 id->dst_ts, policy_dir_names, id->dir, markstr);
2630 free(out);
2631 return FAILED;
2632 }
2633
2634 if (policy->curlft.use_time)
2635 {
2636 /* we need the monotonic time, but the kernel returns system time. */
2637 *use_time = time_monotonic(NULL) - (time(NULL) - policy->curlft.use_time);
2638 }
2639 else
2640 {
2641 *use_time = 0;
2642 }
2643
2644 free(out);
2645 return SUCCESS;
2646 }
2647
2648 METHOD(kernel_ipsec_t, del_policy, status_t,
2649 private_kernel_netlink_ipsec_t *this, kernel_ipsec_policy_id_t *id,
2650 kernel_ipsec_manage_policy_t *data)
2651 {
2652 policy_entry_t *current, policy;
2653 enumerator_t *enumerator;
2654 policy_sa_t *mapping;
2655 netlink_buf_t request;
2656 struct nlmsghdr *hdr;
2657 struct xfrm_userpolicy_id *policy_id;
2658 bool is_installed = TRUE;
2659 uint32_t priority, auto_priority, cur_priority;
2660 ipsec_sa_t assigned_sa = {
2661 .src = data->src,
2662 .dst = data->dst,
2663 .mark = id->mark,
2664 .cfg = *data->sa,
2665 };
2666 char markstr[32] = "";
2667 int use_count;
2668 status_t status = SUCCESS;
2669
2670 format_mark(markstr, sizeof(markstr), id->mark);
2671
2672 DBG2(DBG_KNL, "deleting policy %R === %R %N%s", id->src_ts, id->dst_ts,
2673 policy_dir_names, id->dir, markstr);
2674
2675 /* create a policy */
2676 memset(&policy, 0, sizeof(policy_entry_t));
2677 policy.sel = ts2selector(id->src_ts, id->dst_ts, id->interface);
2678 policy.mark = id->mark.value & id->mark.mask;
2679 policy.direction = id->dir;
2680
2681 /* find the policy */
2682 this->mutex->lock(this->mutex);
2683 current = this->policies->get(this->policies, &policy);
2684 if (!current)
2685 {
2686 DBG1(DBG_KNL, "deleting policy %R === %R %N%s failed, not found",
2687 id->src_ts, id->dst_ts, policy_dir_names, id->dir, markstr);
2688 this->mutex->unlock(this->mutex);
2689 return NOT_FOUND;
2690 }
2691 current->waiting++;
2692 while (current->working)
2693 {
2694 this->condvar->wait(this->condvar, this->mutex);
2695 }
2696 current->working = TRUE;
2697 current->waiting--;
2698
2699 /* remove mapping to SA by reqid and priority */
2700 auto_priority = get_priority(current, data->prio,id->interface);
2701 priority = this->get_priority ? this->get_priority(id, data)
2702 : data->manual_prio;
2703 priority = priority ?: auto_priority;
2704
2705 enumerator = current->used_by->create_enumerator(current->used_by);
2706 while (enumerator->enumerate(enumerator, (void**)&mapping))
2707 {
2708 if (priority == mapping->priority &&
2709 auto_priority == mapping->auto_priority &&
2710 data->type == mapping->type &&
2711 ipsec_sa_equals(mapping->sa, &assigned_sa))
2712 {
2713 current->used_by->remove_at(current->used_by, enumerator);
2714 policy_sa_destroy(mapping, &id->dir, this);
2715 break;
2716 }
2717 if (is_installed)
2718 {
2719 cur_priority = mapping->priority;
2720 is_installed = FALSE;
2721 }
2722 }
2723 enumerator->destroy(enumerator);
2724
2725 use_count = current->used_by->get_count(current->used_by);
2726 if (use_count > 0)
2727 { /* policy is used by more SAs, keep in kernel */
2728 DBG2(DBG_KNL, "policy still used by another CHILD_SA, not removed");
2729 if (!is_installed)
2730 { /* no need to update as the policy was not installed for this SA */
2731 policy_change_done(this, current);
2732 DBG2(DBG_KNL, "not updating policy %R === %R %N%s [priority %u, "
2733 "refcount %d]", id->src_ts, id->dst_ts, policy_dir_names,
2734 id->dir, markstr, cur_priority, use_count);
2735 return SUCCESS;
2736 }
2737 current->used_by->get_first(current->used_by, (void**)&mapping);
2738 current->reqid = mapping->sa->cfg.reqid;
2739
2740 DBG2(DBG_KNL, "updating policy %R === %R %N%s [priority %u, "
2741 "refcount %d]", id->src_ts, id->dst_ts, policy_dir_names, id->dir,
2742 markstr, mapping->priority, use_count);
2743
2744 if (add_policy_internal(this, current, mapping, TRUE) != SUCCESS)
2745 {
2746 DBG1(DBG_KNL, "unable to update policy %R === %R %N%s",
2747 id->src_ts, id->dst_ts, policy_dir_names, id->dir, markstr);
2748 return FAILED;
2749 }
2750 return SUCCESS;
2751 }
2752
2753 memset(&request, 0, sizeof(request));
2754
2755 hdr = &request.hdr;
2756 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2757 hdr->nlmsg_type = XFRM_MSG_DELPOLICY;
2758 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_id));
2759
2760 policy_id = NLMSG_DATA(hdr);
2761 policy_id->sel = current->sel;
2762 policy_id->dir = id->dir;
2763
2764 if (!add_mark(hdr, sizeof(request), id->mark))
2765 {
2766 policy_change_done(this, current);
2767 return FAILED;
2768 }
2769
2770 if (current->route)
2771 {
2772 route_entry_t *route = current->route;
2773 if (charon->kernel->del_route(charon->kernel, route->dst_net,
2774 route->prefixlen, route->gateway,
2775 route->src_ip, route->if_name) != SUCCESS)
2776 {
2777 DBG1(DBG_KNL, "error uninstalling route installed with policy "
2778 "%R === %R %N%s", id->src_ts, id->dst_ts, policy_dir_names,
2779 id->dir, markstr);
2780 }
2781 }
2782 this->mutex->unlock(this->mutex);
2783
2784 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
2785 {
2786 DBG1(DBG_KNL, "unable to delete policy %R === %R %N%s", id->src_ts,
2787 id->dst_ts, policy_dir_names, id->dir, markstr);
2788 status = FAILED;
2789 }
2790
2791 this->mutex->lock(this->mutex);
2792 if (!current->waiting)
2793 { /* only if no other thread still needs the policy */
2794 this->policies->remove(this->policies, current);
2795 policy_entry_destroy(this, current);
2796 this->mutex->unlock(this->mutex);
2797 }
2798 else
2799 {
2800 policy_change_done(this, current);
2801 }
2802 return status;
2803 }
2804
2805 METHOD(kernel_ipsec_t, flush_policies, status_t,
2806 private_kernel_netlink_ipsec_t *this)
2807 {
2808 netlink_buf_t request;
2809 struct nlmsghdr *hdr;
2810
2811 memset(&request, 0, sizeof(request));
2812
2813 DBG2(DBG_KNL, "flushing all policies from SPD");
2814
2815 hdr = &request.hdr;
2816 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2817 hdr->nlmsg_type = XFRM_MSG_FLUSHPOLICY;
2818 hdr->nlmsg_len = NLMSG_LENGTH(0); /* no data associated */
2819
2820 /* by adding an rtattr of type XFRMA_POLICY_TYPE we could restrict this
2821 * to main or sub policies (default is main) */
2822
2823 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
2824 {
2825 DBG1(DBG_KNL, "unable to flush SPD entries");
2826 return FAILED;
2827 }
2828 return SUCCESS;
2829 }
2830
2831 /**
2832 * Bypass socket using a per-socket policy
2833 */
2834 static bool add_socket_bypass(private_kernel_netlink_ipsec_t *this,
2835 int fd, int family)
2836 {
2837 struct xfrm_userpolicy_info policy;
2838 u_int sol, ipsec_policy;
2839
2840 switch (family)
2841 {
2842 case AF_INET:
2843 sol = SOL_IP;
2844 ipsec_policy = IP_XFRM_POLICY;
2845 break;
2846 case AF_INET6:
2847 sol = SOL_IPV6;
2848 ipsec_policy = IPV6_XFRM_POLICY;
2849 break;
2850 default:
2851 return FALSE;
2852 }
2853
2854 memset(&policy, 0, sizeof(policy));
2855 policy.action = XFRM_POLICY_ALLOW;
2856 policy.sel.family = family;
2857
2858 policy.dir = XFRM_POLICY_OUT;
2859 if (setsockopt(fd, sol, ipsec_policy, &policy, sizeof(policy)) < 0)
2860 {
2861 DBG1(DBG_KNL, "unable to set IPSEC_POLICY on socket: %s (%d)",
2862 strerror(errno), errno);
2863 return FALSE;
2864 }
2865 policy.dir = XFRM_POLICY_IN;
2866 if (setsockopt(fd, sol, ipsec_policy, &policy, sizeof(policy)) < 0)
2867 {
2868 DBG1(DBG_KNL, "unable to set IPSEC_POLICY on socket: %s (%d)",
2869 strerror(errno), errno);
2870 return FALSE;
2871 }
2872 return TRUE;
2873 }
2874
2875 /**
2876 * Port based IKE bypass policy
2877 */
2878 typedef struct {
2879 /** address family */
2880 int family;
2881 /** layer 4 protocol */
2882 int proto;
2883 /** port number, network order */
2884 uint16_t port;
2885 } bypass_t;
2886
2887 /**
2888 * Add or remove a bypass policy from/to kernel
2889 */
2890 static bool manage_bypass(private_kernel_netlink_ipsec_t *this,
2891 int type, policy_dir_t dir, bypass_t *bypass)
2892 {
2893 netlink_buf_t request;
2894 struct xfrm_selector *sel;
2895 struct nlmsghdr *hdr;
2896
2897 memset(&request, 0, sizeof(request));
2898 hdr = &request.hdr;
2899 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2900 hdr->nlmsg_type = type;
2901
2902 if (type == XFRM_MSG_NEWPOLICY)
2903 {
2904 struct xfrm_userpolicy_info *policy;
2905
2906 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_info));
2907
2908 policy = NLMSG_DATA(hdr);
2909 policy->dir = dir;
2910 policy->priority = 32;
2911 policy->action = XFRM_POLICY_ALLOW;
2912 policy->share = XFRM_SHARE_ANY;
2913
2914 policy->lft.soft_byte_limit = XFRM_INF;
2915 policy->lft.soft_packet_limit = XFRM_INF;
2916 policy->lft.hard_byte_limit = XFRM_INF;
2917 policy->lft.hard_packet_limit = XFRM_INF;
2918
2919 sel = &policy->sel;
2920 }
2921 else /* XFRM_MSG_DELPOLICY */
2922 {
2923 struct xfrm_userpolicy_id *policy;
2924
2925 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_id));
2926
2927 policy = NLMSG_DATA(hdr);
2928 policy->dir = dir;
2929
2930 sel = &policy->sel;
2931 }
2932
2933 sel->family = bypass->family;
2934 sel->proto = bypass->proto;
2935 if (dir == POLICY_IN)
2936 {
2937 sel->dport = bypass->port;
2938 sel->dport_mask = 0xffff;
2939 }
2940 else
2941 {
2942 sel->sport = bypass->port;
2943 sel->sport_mask = 0xffff;
2944 }
2945 return this->socket_xfrm->send_ack(this->socket_xfrm, hdr) == SUCCESS;
2946 }
2947
2948 /**
2949 * Bypass socket using a port-based bypass policy
2950 */
2951 static bool add_port_bypass(private_kernel_netlink_ipsec_t *this,
2952 int fd, int family)
2953 {
2954 union {
2955 struct sockaddr sa;
2956 struct sockaddr_in in;
2957 struct sockaddr_in6 in6;
2958 } saddr;
2959 socklen_t len;
2960 bypass_t bypass = {
2961 .family = family,
2962 };
2963
2964 len = sizeof(saddr);
2965 if (getsockname(fd, &saddr.sa, &len) != 0)
2966 {
2967 return FALSE;
2968 }
2969 #ifdef SO_PROTOCOL /* since 2.6.32 */
2970 len = sizeof(bypass.proto);
2971 if (getsockopt(fd, SOL_SOCKET, SO_PROTOCOL, &bypass.proto, &len) != 0)
2972 #endif
2973 { /* assume UDP if SO_PROTOCOL not supported */
2974 bypass.proto = IPPROTO_UDP;
2975 }
2976 switch (family)
2977 {
2978 case AF_INET:
2979 bypass.port = saddr.in.sin_port;
2980 break;
2981 case AF_INET6:
2982 bypass.port = saddr.in6.sin6_port;
2983 break;
2984 default:
2985 return FALSE;
2986 }
2987
2988 if (!manage_bypass(this, XFRM_MSG_NEWPOLICY, POLICY_IN, &bypass))
2989 {
2990 return FALSE;
2991 }
2992 if (!manage_bypass(this, XFRM_MSG_NEWPOLICY, POLICY_OUT, &bypass))
2993 {
2994 manage_bypass(this, XFRM_MSG_DELPOLICY, POLICY_IN, &bypass);
2995 return FALSE;
2996 }
2997 array_insert(this->bypass, ARRAY_TAIL, &bypass);
2998
2999 return TRUE;
3000 }
3001
3002 /**
3003 * Remove installed port based bypass policy
3004 */
3005 static void remove_port_bypass(bypass_t *bypass, int idx,
3006 private_kernel_netlink_ipsec_t *this)
3007 {
3008 manage_bypass(this, XFRM_MSG_DELPOLICY, POLICY_OUT, bypass);
3009 manage_bypass(this, XFRM_MSG_DELPOLICY, POLICY_IN, bypass);
3010 }
3011
3012 METHOD(kernel_ipsec_t, bypass_socket, bool,
3013 private_kernel_netlink_ipsec_t *this, int fd, int family)
3014 {
3015 if (lib->settings->get_bool(lib->settings,
3016 "%s.plugins.kernel-netlink.port_bypass", FALSE, lib->ns))
3017 {
3018 return add_port_bypass(this, fd, family);
3019 }
3020 return add_socket_bypass(this, fd, family);
3021 }
3022
3023 METHOD(kernel_ipsec_t, enable_udp_decap, bool,
3024 private_kernel_netlink_ipsec_t *this, int fd, int family, uint16_t port)
3025 {
3026 int type = UDP_ENCAP_ESPINUDP;
3027
3028 if (setsockopt(fd, SOL_UDP, UDP_ENCAP, &type, sizeof(type)) < 0)
3029 {
3030 DBG1(DBG_KNL, "unable to set UDP_ENCAP: %s", strerror(errno));
3031 return FALSE;
3032 }
3033 return TRUE;
3034 }
3035
3036 METHOD(kernel_ipsec_t, destroy, void,
3037 private_kernel_netlink_ipsec_t *this)
3038 {
3039 enumerator_t *enumerator;
3040 policy_entry_t *policy;
3041
3042 array_destroy_function(this->bypass,
3043 (array_callback_t)remove_port_bypass, this);
3044 if (this->socket_xfrm_events > 0)
3045 {
3046 lib->watcher->remove(lib->watcher, this->socket_xfrm_events);
3047 close(this->socket_xfrm_events);
3048 }
3049 DESTROY_IF(this->socket_xfrm);
3050 enumerator = this->policies->create_enumerator(this->policies);
3051 while (enumerator->enumerate(enumerator, &policy, &policy))
3052 {
3053 policy_entry_destroy(this, policy);
3054 }
3055 enumerator->destroy(enumerator);
3056 this->policies->destroy(this->policies);
3057 this->sas->destroy(this->sas);
3058 this->condvar->destroy(this->condvar);
3059 this->mutex->destroy(this->mutex);
3060 free(this);
3061 }
3062
3063 /**
3064 * Get the currently configured SPD hashing thresholds for an address family
3065 */
3066 static bool get_spd_hash_thresh(private_kernel_netlink_ipsec_t *this,
3067 int type, uint8_t *lbits, uint8_t *rbits)
3068 {
3069 netlink_buf_t request;
3070 struct nlmsghdr *hdr, *out;
3071 struct xfrmu_spdhthresh *thresh;
3072 struct rtattr *rta;
3073 size_t len, rtasize;
3074 bool success = FALSE;
3075
3076 memset(&request, 0, sizeof(request));
3077
3078 hdr = &request.hdr;
3079 hdr->nlmsg_flags = NLM_F_REQUEST;
3080 hdr->nlmsg_type = XFRM_MSG_GETSPDINFO;
3081 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(uint32_t));
3082
3083 if (this->socket_xfrm->send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
3084 {
3085 hdr = out;
3086 while (NLMSG_OK(hdr, len))
3087 {
3088 switch (hdr->nlmsg_type)
3089 {
3090 case XFRM_MSG_NEWSPDINFO:
3091 {
3092 rta = XFRM_RTA(hdr, uint32_t);
3093 rtasize = XFRM_PAYLOAD(hdr, uint32_t);
3094 while (RTA_OK(rta, rtasize))
3095 {
3096 if (rta->rta_type == type &&
3097 RTA_PAYLOAD(rta) == sizeof(*thresh))
3098 {
3099 thresh = RTA_DATA(rta);
3100 *lbits = thresh->lbits;
3101 *rbits = thresh->rbits;
3102 success = TRUE;
3103 break;
3104 }
3105 rta = RTA_NEXT(rta, rtasize);
3106 }
3107 break;
3108 }
3109 case NLMSG_ERROR:
3110 {
3111 struct nlmsgerr *err = NLMSG_DATA(hdr);
3112 DBG1(DBG_KNL, "getting SPD hash threshold failed: %s (%d)",
3113 strerror(-err->error), -err->error);
3114 break;
3115 }
3116 default:
3117 hdr = NLMSG_NEXT(hdr, len);
3118 continue;
3119 case NLMSG_DONE:
3120 break;
3121 }
3122 break;
3123 }
3124 free(out);
3125 }
3126 return success;<