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