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