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