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