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