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