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