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