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