31ca7171835df536925bb533b19b762e151277ea
[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
326 */
327 u_int32_t replay_window;
328
329 /**
330 * Size of the replay window bitmap, in bytes
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 bytes",
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 sa->replay_window = DEFAULT_REPLAY_WINDOW;
1504 }
1505 }
1506
1507 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
1508 {
1509 if (mark.value)
1510 {
1511 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x "
1512 "(mark %u/0x%08x)", ntohl(spi), mark.value, mark.mask);
1513 }
1514 else
1515 {
1516 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x", ntohl(spi));
1517 }
1518 goto failed;
1519 }
1520
1521 status = SUCCESS;
1522
1523 failed:
1524 memwipe(request, sizeof(request));
1525 return status;
1526 }
1527
1528 /**
1529 * Get the ESN replay state (i.e. sequence numbers) of an SA.
1530 *
1531 * Allocates into one the replay state structure we get from the kernel.
1532 */
1533 static void get_replay_state(private_kernel_netlink_ipsec_t *this,
1534 u_int32_t spi, u_int8_t protocol, host_t *dst,
1535 struct xfrm_replay_state_esn **replay_esn,
1536 struct xfrm_replay_state **replay)
1537 {
1538 netlink_buf_t request;
1539 struct nlmsghdr *hdr, *out = NULL;
1540 struct xfrm_aevent_id *out_aevent = NULL, *aevent_id;
1541 size_t len;
1542 struct rtattr *rta;
1543 size_t rtasize;
1544
1545 memset(&request, 0, sizeof(request));
1546
1547 DBG2(DBG_KNL, "querying replay state from SAD entry with SPI %.8x",
1548 ntohl(spi));
1549
1550 hdr = (struct nlmsghdr*)request;
1551 hdr->nlmsg_flags = NLM_F_REQUEST;
1552 hdr->nlmsg_type = XFRM_MSG_GETAE;
1553 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_aevent_id));
1554
1555 aevent_id = (struct xfrm_aevent_id*)NLMSG_DATA(hdr);
1556 aevent_id->flags = XFRM_AE_RVAL;
1557
1558 host2xfrm(dst, &aevent_id->sa_id.daddr);
1559 aevent_id->sa_id.spi = spi;
1560 aevent_id->sa_id.proto = protocol;
1561 aevent_id->sa_id.family = dst->get_family(dst);
1562
1563 if (this->socket_xfrm->send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
1564 {
1565 hdr = out;
1566 while (NLMSG_OK(hdr, len))
1567 {
1568 switch (hdr->nlmsg_type)
1569 {
1570 case XFRM_MSG_NEWAE:
1571 {
1572 out_aevent = NLMSG_DATA(hdr);
1573 break;
1574 }
1575 case NLMSG_ERROR:
1576 {
1577 struct nlmsgerr *err = NLMSG_DATA(hdr);
1578 DBG1(DBG_KNL, "querying replay state from SAD entry "
1579 "failed: %s (%d)", strerror(-err->error),
1580 -err->error);
1581 break;
1582 }
1583 default:
1584 hdr = NLMSG_NEXT(hdr, len);
1585 continue;
1586 case NLMSG_DONE:
1587 break;
1588 }
1589 break;
1590 }
1591 }
1592
1593 if (out_aevent)
1594 {
1595 rta = XFRM_RTA(out, struct xfrm_aevent_id);
1596 rtasize = XFRM_PAYLOAD(out, struct xfrm_aevent_id);
1597 while (RTA_OK(rta, rtasize))
1598 {
1599 if (rta->rta_type == XFRMA_REPLAY_VAL &&
1600 RTA_PAYLOAD(rta) == sizeof(**replay))
1601 {
1602 *replay = malloc(RTA_PAYLOAD(rta));
1603 memcpy(*replay, RTA_DATA(rta), RTA_PAYLOAD(rta));
1604 break;
1605 }
1606 if (rta->rta_type == XFRMA_REPLAY_ESN_VAL &&
1607 RTA_PAYLOAD(rta) >= sizeof(**replay_esn) + this->replay_bmp)
1608 {
1609 *replay_esn = malloc(RTA_PAYLOAD(rta));
1610 memcpy(*replay_esn, RTA_DATA(rta), RTA_PAYLOAD(rta));
1611 break;
1612 }
1613 rta = RTA_NEXT(rta, rtasize);
1614 }
1615 }
1616 free(out);
1617 }
1618
1619 METHOD(kernel_ipsec_t, query_sa, status_t,
1620 private_kernel_netlink_ipsec_t *this, host_t *src, host_t *dst,
1621 u_int32_t spi, u_int8_t protocol, mark_t mark, u_int64_t *bytes)
1622 {
1623 netlink_buf_t request;
1624 struct nlmsghdr *out = NULL, *hdr;
1625 struct xfrm_usersa_id *sa_id;
1626 struct xfrm_usersa_info *sa = NULL;
1627 status_t status = FAILED;
1628 size_t len;
1629
1630 memset(&request, 0, sizeof(request));
1631
1632 DBG2(DBG_KNL, "querying SAD entry with SPI %.8x (mark %u/0x%08x)",
1633 ntohl(spi), mark.value, mark.mask);
1634
1635 hdr = (struct nlmsghdr*)request;
1636 hdr->nlmsg_flags = NLM_F_REQUEST;
1637 hdr->nlmsg_type = XFRM_MSG_GETSA;
1638 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_id));
1639
1640 sa_id = (struct xfrm_usersa_id*)NLMSG_DATA(hdr);
1641 host2xfrm(dst, &sa_id->daddr);
1642 sa_id->spi = spi;
1643 sa_id->proto = protocol;
1644 sa_id->family = dst->get_family(dst);
1645
1646 if (mark.value)
1647 {
1648 struct xfrm_mark *mrk;
1649 struct rtattr *rthdr = XFRM_RTA(hdr, struct xfrm_usersa_id);
1650
1651 rthdr->rta_type = XFRMA_MARK;
1652 rthdr->rta_len = RTA_LENGTH(sizeof(struct xfrm_mark));
1653 hdr->nlmsg_len += RTA_ALIGN(rthdr->rta_len);
1654 if (hdr->nlmsg_len > sizeof(request))
1655 {
1656 return FAILED;
1657 }
1658
1659 mrk = (struct xfrm_mark*)RTA_DATA(rthdr);
1660 mrk->v = mark.value;
1661 mrk->m = mark.mask;
1662 }
1663
1664 if (this->socket_xfrm->send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
1665 {
1666 hdr = out;
1667 while (NLMSG_OK(hdr, len))
1668 {
1669 switch (hdr->nlmsg_type)
1670 {
1671 case XFRM_MSG_NEWSA:
1672 {
1673 sa = (struct xfrm_usersa_info*)NLMSG_DATA(hdr);
1674 break;
1675 }
1676 case NLMSG_ERROR:
1677 {
1678 struct nlmsgerr *err = NLMSG_DATA(hdr);
1679
1680 if (mark.value)
1681 {
1682 DBG1(DBG_KNL, "querying SAD entry with SPI %.8x "
1683 "(mark %u/0x%08x) failed: %s (%d)",
1684 ntohl(spi), mark.value, mark.mask,
1685 strerror(-err->error), -err->error);
1686 }
1687 else
1688 {
1689 DBG1(DBG_KNL, "querying SAD entry with SPI %.8x "
1690 "failed: %s (%d)", ntohl(spi),
1691 strerror(-err->error), -err->error);
1692 }
1693 break;
1694 }
1695 default:
1696 hdr = NLMSG_NEXT(hdr, len);
1697 continue;
1698 case NLMSG_DONE:
1699 break;
1700 }
1701 break;
1702 }
1703 }
1704
1705 if (sa == NULL)
1706 {
1707 DBG2(DBG_KNL, "unable to query SAD entry with SPI %.8x", ntohl(spi));
1708 }
1709 else
1710 {
1711 *bytes = sa->curlft.bytes;
1712 status = SUCCESS;
1713 }
1714 memwipe(out, len);
1715 free(out);
1716 return status;
1717 }
1718
1719 METHOD(kernel_ipsec_t, del_sa, status_t,
1720 private_kernel_netlink_ipsec_t *this, host_t *src, host_t *dst,
1721 u_int32_t spi, u_int8_t protocol, u_int16_t cpi, mark_t mark)
1722 {
1723 netlink_buf_t request;
1724 struct nlmsghdr *hdr;
1725 struct xfrm_usersa_id *sa_id;
1726
1727 /* if IPComp was used, we first delete the additional IPComp SA */
1728 if (cpi)
1729 {
1730 del_sa(this, src, dst, htonl(ntohs(cpi)), IPPROTO_COMP, 0, mark);
1731 }
1732
1733 memset(&request, 0, sizeof(request));
1734
1735 DBG2(DBG_KNL, "deleting SAD entry with SPI %.8x (mark %u/0x%08x)",
1736 ntohl(spi), mark.value, mark.mask);
1737
1738 hdr = (struct nlmsghdr*)request;
1739 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
1740 hdr->nlmsg_type = XFRM_MSG_DELSA;
1741 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_id));
1742
1743 sa_id = (struct xfrm_usersa_id*)NLMSG_DATA(hdr);
1744 host2xfrm(dst, &sa_id->daddr);
1745 sa_id->spi = spi;
1746 sa_id->proto = protocol;
1747 sa_id->family = dst->get_family(dst);
1748
1749 if (mark.value)
1750 {
1751 struct xfrm_mark *mrk;
1752 struct rtattr *rthdr = XFRM_RTA(hdr, struct xfrm_usersa_id);
1753
1754 rthdr->rta_type = XFRMA_MARK;
1755 rthdr->rta_len = RTA_LENGTH(sizeof(struct xfrm_mark));
1756 hdr->nlmsg_len += RTA_ALIGN(rthdr->rta_len);
1757 if (hdr->nlmsg_len > sizeof(request))
1758 {
1759 return FAILED;
1760 }
1761
1762 mrk = (struct xfrm_mark*)RTA_DATA(rthdr);
1763 mrk->v = mark.value;
1764 mrk->m = mark.mask;
1765 }
1766
1767 switch (this->socket_xfrm->send_ack(this->socket_xfrm, hdr))
1768 {
1769 case SUCCESS:
1770 DBG2(DBG_KNL, "deleted SAD entry with SPI %.8x (mark %u/0x%08x)",
1771 ntohl(spi), mark.value, mark.mask);
1772 return SUCCESS;
1773 case NOT_FOUND:
1774 return NOT_FOUND;
1775 default:
1776 if (mark.value)
1777 {
1778 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x "
1779 "(mark %u/0x%08x)", ntohl(spi), mark.value, mark.mask);
1780 }
1781 else
1782 {
1783 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x",
1784 ntohl(spi));
1785 }
1786 return FAILED;
1787 }
1788 }
1789
1790 METHOD(kernel_ipsec_t, update_sa, status_t,
1791 private_kernel_netlink_ipsec_t *this, u_int32_t spi, u_int8_t protocol,
1792 u_int16_t cpi, host_t *src, host_t *dst, host_t *new_src, host_t *new_dst,
1793 bool old_encap, bool new_encap, mark_t mark)
1794 {
1795 netlink_buf_t request;
1796 u_char *pos;
1797 struct nlmsghdr *hdr, *out = NULL;
1798 struct xfrm_usersa_id *sa_id;
1799 struct xfrm_usersa_info *out_sa = NULL, *sa;
1800 size_t len;
1801 struct rtattr *rta;
1802 size_t rtasize;
1803 struct xfrm_encap_tmpl* tmpl = NULL;
1804 struct xfrm_replay_state *replay = NULL;
1805 struct xfrm_replay_state_esn *replay_esn = NULL;
1806 status_t status = FAILED;
1807
1808 /* if IPComp is used, we first update the IPComp SA */
1809 if (cpi)
1810 {
1811 update_sa(this, htonl(ntohs(cpi)), IPPROTO_COMP, 0,
1812 src, dst, new_src, new_dst, FALSE, FALSE, mark);
1813 }
1814
1815 memset(&request, 0, sizeof(request));
1816
1817 DBG2(DBG_KNL, "querying SAD entry with SPI %.8x for update", ntohl(spi));
1818
1819 /* query the existing SA first */
1820 hdr = (struct nlmsghdr*)request;
1821 hdr->nlmsg_flags = NLM_F_REQUEST;
1822 hdr->nlmsg_type = XFRM_MSG_GETSA;
1823 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_id));
1824
1825 sa_id = (struct xfrm_usersa_id*)NLMSG_DATA(hdr);
1826 host2xfrm(dst, &sa_id->daddr);
1827 sa_id->spi = spi;
1828 sa_id->proto = protocol;
1829 sa_id->family = dst->get_family(dst);
1830
1831 if (this->socket_xfrm->send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
1832 {
1833 hdr = out;
1834 while (NLMSG_OK(hdr, len))
1835 {
1836 switch (hdr->nlmsg_type)
1837 {
1838 case XFRM_MSG_NEWSA:
1839 {
1840 out_sa = NLMSG_DATA(hdr);
1841 break;
1842 }
1843 case NLMSG_ERROR:
1844 {
1845 struct nlmsgerr *err = NLMSG_DATA(hdr);
1846 DBG1(DBG_KNL, "querying SAD entry failed: %s (%d)",
1847 strerror(-err->error), -err->error);
1848 break;
1849 }
1850 default:
1851 hdr = NLMSG_NEXT(hdr, len);
1852 continue;
1853 case NLMSG_DONE:
1854 break;
1855 }
1856 break;
1857 }
1858 }
1859 if (out_sa == NULL)
1860 {
1861 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x", ntohl(spi));
1862 goto failed;
1863 }
1864
1865 get_replay_state(this, spi, protocol, dst, &replay_esn, &replay);
1866
1867 /* delete the old SA (without affecting the IPComp SA) */
1868 if (del_sa(this, src, dst, spi, protocol, 0, mark) != SUCCESS)
1869 {
1870 DBG1(DBG_KNL, "unable to delete old SAD entry with SPI %.8x",
1871 ntohl(spi));
1872 goto failed;
1873 }
1874
1875 DBG2(DBG_KNL, "updating SAD entry with SPI %.8x from %#H..%#H to %#H..%#H",
1876 ntohl(spi), src, dst, new_src, new_dst);
1877 /* copy over the SA from out to request */
1878 hdr = (struct nlmsghdr*)request;
1879 memcpy(hdr, out, min(out->nlmsg_len, sizeof(request)));
1880 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
1881 hdr->nlmsg_type = XFRM_MSG_NEWSA;
1882 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_info));
1883 sa = NLMSG_DATA(hdr);
1884 sa->family = new_dst->get_family(new_dst);
1885
1886 if (!src->ip_equals(src, new_src))
1887 {
1888 host2xfrm(new_src, &sa->saddr);
1889 }
1890 if (!dst->ip_equals(dst, new_dst))
1891 {
1892 host2xfrm(new_dst, &sa->id.daddr);
1893 }
1894
1895 rta = XFRM_RTA(out, struct xfrm_usersa_info);
1896 rtasize = XFRM_PAYLOAD(out, struct xfrm_usersa_info);
1897 pos = (u_char*)XFRM_RTA(hdr, struct xfrm_usersa_info);
1898 while(RTA_OK(rta, rtasize))
1899 {
1900 /* copy all attributes, but not XFRMA_ENCAP if we are disabling it */
1901 if (rta->rta_type != XFRMA_ENCAP || new_encap)
1902 {
1903 if (rta->rta_type == XFRMA_ENCAP)
1904 { /* update encap tmpl */
1905 tmpl = (struct xfrm_encap_tmpl*)RTA_DATA(rta);
1906 tmpl->encap_sport = ntohs(new_src->get_port(new_src));
1907 tmpl->encap_dport = ntohs(new_dst->get_port(new_dst));
1908 }
1909 memcpy(pos, rta, rta->rta_len);
1910 pos += RTA_ALIGN(rta->rta_len);
1911 hdr->nlmsg_len += RTA_ALIGN(rta->rta_len);
1912 }
1913 rta = RTA_NEXT(rta, rtasize);
1914 }
1915
1916 rta = (struct rtattr*)pos;
1917 if (tmpl == NULL && new_encap)
1918 { /* add tmpl if we are enabling it */
1919 rta->rta_type = XFRMA_ENCAP;
1920 rta->rta_len = RTA_LENGTH(sizeof(struct xfrm_encap_tmpl));
1921
1922 hdr->nlmsg_len += RTA_ALIGN(rta->rta_len);
1923 if (hdr->nlmsg_len > sizeof(request))
1924 {
1925 goto failed;
1926 }
1927
1928 tmpl = (struct xfrm_encap_tmpl*)RTA_DATA(rta);
1929 tmpl->encap_type = UDP_ENCAP_ESPINUDP;
1930 tmpl->encap_sport = ntohs(new_src->get_port(new_src));
1931 tmpl->encap_dport = ntohs(new_dst->get_port(new_dst));
1932 memset(&tmpl->encap_oa, 0, sizeof (xfrm_address_t));
1933
1934 rta = XFRM_RTA_NEXT(rta);
1935 }
1936
1937 if (replay_esn)
1938 {
1939 rta->rta_type = XFRMA_REPLAY_ESN_VAL;
1940 rta->rta_len = RTA_LENGTH(sizeof(struct xfrm_replay_state_esn) +
1941 this->replay_bmp);
1942
1943 hdr->nlmsg_len += RTA_ALIGN(rta->rta_len);
1944 if (hdr->nlmsg_len > sizeof(request))
1945 {
1946 goto failed;
1947 }
1948 memcpy(RTA_DATA(rta), replay_esn,
1949 sizeof(struct xfrm_replay_state_esn) + this->replay_bmp);
1950
1951 rta = XFRM_RTA_NEXT(rta);
1952 }
1953 else if (replay)
1954 {
1955 rta->rta_type = XFRMA_REPLAY_VAL;
1956 rta->rta_len = RTA_LENGTH(sizeof(struct xfrm_replay_state));
1957
1958 hdr->nlmsg_len += RTA_ALIGN(rta->rta_len);
1959 if (hdr->nlmsg_len > sizeof(request))
1960 {
1961 goto failed;
1962 }
1963 memcpy(RTA_DATA(rta), replay, sizeof(replay));
1964
1965 rta = XFRM_RTA_NEXT(rta);
1966 }
1967 else
1968 {
1969 DBG1(DBG_KNL, "unable to copy replay state from old SAD entry "
1970 "with SPI %.8x", ntohl(spi));
1971 }
1972
1973 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
1974 {
1975 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x", ntohl(spi));
1976 goto failed;
1977 }
1978
1979 status = SUCCESS;
1980 failed:
1981 free(replay);
1982 free(replay_esn);
1983 memwipe(out, len);
1984 memwipe(request, sizeof(request));
1985 free(out);
1986
1987 return status;
1988 }
1989
1990 METHOD(kernel_ipsec_t, flush_sas, status_t,
1991 private_kernel_netlink_ipsec_t *this)
1992 {
1993 netlink_buf_t request;
1994 struct nlmsghdr *hdr;
1995 struct xfrm_usersa_flush *flush;
1996
1997 memset(&request, 0, sizeof(request));
1998
1999 DBG2(DBG_KNL, "flushing all SAD entries");
2000
2001 hdr = (struct nlmsghdr*)request;
2002 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2003 hdr->nlmsg_type = XFRM_MSG_FLUSHSA;
2004 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_flush));
2005
2006 flush = (struct xfrm_usersa_flush*)NLMSG_DATA(hdr);
2007 flush->proto = IPSEC_PROTO_ANY;
2008
2009 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
2010 {
2011 DBG1(DBG_KNL, "unable to flush SAD entries");
2012 return FAILED;
2013 }
2014 return SUCCESS;
2015 }
2016
2017 /**
2018 * Add or update a policy in the kernel.
2019 *
2020 * Note: The mutex has to be locked when entering this function
2021 * and is unlocked here in any case.
2022 */
2023 static status_t add_policy_internal(private_kernel_netlink_ipsec_t *this,
2024 policy_entry_t *policy, policy_sa_t *mapping, bool update)
2025 {
2026 netlink_buf_t request;
2027 policy_entry_t clone;
2028 ipsec_sa_t *ipsec = mapping->sa;
2029 struct xfrm_userpolicy_info *policy_info;
2030 struct nlmsghdr *hdr;
2031 int i;
2032
2033 /* clone the policy so we are able to check it out again later */
2034 memcpy(&clone, policy, sizeof(policy_entry_t));
2035
2036 memset(&request, 0, sizeof(request));
2037 hdr = (struct nlmsghdr*)request;
2038 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2039 hdr->nlmsg_type = update ? XFRM_MSG_UPDPOLICY : XFRM_MSG_NEWPOLICY;
2040 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_info));
2041
2042 policy_info = (struct xfrm_userpolicy_info*)NLMSG_DATA(hdr);
2043 policy_info->sel = policy->sel;
2044 policy_info->dir = policy->direction;
2045
2046 /* calculate priority based on selector size, small size = high prio */
2047 policy_info->priority = mapping->priority;
2048 policy_info->action = mapping->type != POLICY_DROP ? XFRM_POLICY_ALLOW
2049 : XFRM_POLICY_BLOCK;
2050 policy_info->share = XFRM_SHARE_ANY;
2051
2052 /* policies don't expire */
2053 policy_info->lft.soft_byte_limit = XFRM_INF;
2054 policy_info->lft.soft_packet_limit = XFRM_INF;
2055 policy_info->lft.hard_byte_limit = XFRM_INF;
2056 policy_info->lft.hard_packet_limit = XFRM_INF;
2057 policy_info->lft.soft_add_expires_seconds = 0;
2058 policy_info->lft.hard_add_expires_seconds = 0;
2059 policy_info->lft.soft_use_expires_seconds = 0;
2060 policy_info->lft.hard_use_expires_seconds = 0;
2061
2062 struct rtattr *rthdr = XFRM_RTA(hdr, struct xfrm_userpolicy_info);
2063
2064 if (mapping->type == POLICY_IPSEC)
2065 {
2066 struct xfrm_user_tmpl *tmpl = (struct xfrm_user_tmpl*)RTA_DATA(rthdr);
2067 struct {
2068 u_int8_t proto;
2069 bool use;
2070 } protos[] = {
2071 { IPPROTO_COMP, ipsec->cfg.ipcomp.transform != IPCOMP_NONE },
2072 { IPPROTO_ESP, ipsec->cfg.esp.use },
2073 { IPPROTO_AH, ipsec->cfg.ah.use },
2074 };
2075 ipsec_mode_t proto_mode = ipsec->cfg.mode;
2076
2077 rthdr->rta_type = XFRMA_TMPL;
2078 rthdr->rta_len = 0; /* actual length is set below */
2079
2080 for (i = 0; i < countof(protos); i++)
2081 {
2082 if (!protos[i].use)
2083 {
2084 continue;
2085 }
2086
2087 rthdr->rta_len += RTA_LENGTH(sizeof(struct xfrm_user_tmpl));
2088 hdr->nlmsg_len += RTA_ALIGN(RTA_LENGTH(sizeof(struct xfrm_user_tmpl)));
2089 if (hdr->nlmsg_len > sizeof(request))
2090 {
2091 this->mutex->unlock(this->mutex);
2092 return FAILED;
2093 }
2094
2095 tmpl->reqid = ipsec->cfg.reqid;
2096 tmpl->id.proto = protos[i].proto;
2097 tmpl->aalgos = tmpl->ealgos = tmpl->calgos = ~0;
2098 tmpl->mode = mode2kernel(proto_mode);
2099 tmpl->optional = protos[i].proto == IPPROTO_COMP &&
2100 policy->direction != POLICY_OUT;
2101 tmpl->family = ipsec->src->get_family(ipsec->src);
2102
2103 if (proto_mode == MODE_TUNNEL)
2104 { /* only for tunnel mode */
2105 host2xfrm(ipsec->src, &tmpl->saddr);
2106 host2xfrm(ipsec->dst, &tmpl->id.daddr);
2107 }
2108
2109 tmpl++;
2110
2111 /* use transport mode for other SAs */
2112 proto_mode = MODE_TRANSPORT;
2113 }
2114
2115 rthdr = XFRM_RTA_NEXT(rthdr);
2116 }
2117
2118 if (ipsec->mark.value)
2119 {
2120 struct xfrm_mark *mrk;
2121
2122 rthdr->rta_type = XFRMA_MARK;
2123 rthdr->rta_len = RTA_LENGTH(sizeof(struct xfrm_mark));
2124
2125 hdr->nlmsg_len += RTA_ALIGN(rthdr->rta_len);
2126 if (hdr->nlmsg_len > sizeof(request))
2127 {
2128 this->mutex->unlock(this->mutex);
2129 return FAILED;
2130 }
2131
2132 mrk = (struct xfrm_mark*)RTA_DATA(rthdr);
2133 mrk->v = ipsec->mark.value;
2134 mrk->m = ipsec->mark.mask;
2135 }
2136 this->mutex->unlock(this->mutex);
2137
2138 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
2139 {
2140 return FAILED;
2141 }
2142
2143 /* find the policy again */
2144 this->mutex->lock(this->mutex);
2145 policy = this->policies->get(this->policies, &clone);
2146 if (!policy ||
2147 policy->used_by->find_first(policy->used_by,
2148 NULL, (void**)&mapping) != SUCCESS)
2149 { /* policy or mapping is already gone, ignore */
2150 this->mutex->unlock(this->mutex);
2151 return SUCCESS;
2152 }
2153
2154 /* install a route, if:
2155 * - this is a forward policy (to just get one for each child)
2156 * - we are in tunnel/BEET mode
2157 * - routing is not disabled via strongswan.conf
2158 */
2159 if (policy->direction == POLICY_FWD &&
2160 ipsec->cfg.mode != MODE_TRANSPORT && this->install_routes)
2161 {
2162 route_entry_t *route = malloc_thing(route_entry_t);
2163 policy_sa_fwd_t *fwd = (policy_sa_fwd_t*)mapping;
2164
2165 if (hydra->kernel_interface->get_address_by_ts(hydra->kernel_interface,
2166 fwd->dst_ts, &route->src_ip) == SUCCESS)
2167 {
2168 /* get the nexthop to src (src as we are in POLICY_FWD) */
2169 route->gateway = hydra->kernel_interface->get_nexthop(
2170 hydra->kernel_interface, ipsec->src,
2171 ipsec->dst);
2172 /* install route via outgoing interface */
2173 route->if_name = hydra->kernel_interface->get_interface(
2174 hydra->kernel_interface, ipsec->dst);
2175 route->dst_net = chunk_alloc(policy->sel.family == AF_INET ? 4 : 16);
2176 memcpy(route->dst_net.ptr, &policy->sel.saddr, route->dst_net.len);
2177 route->prefixlen = policy->sel.prefixlen_s;
2178
2179 if (!route->if_name)
2180 {
2181 this->mutex->unlock(this->mutex);
2182 route_entry_destroy(route);
2183 return SUCCESS;
2184 }
2185
2186 if (policy->route)
2187 {
2188 route_entry_t *old = policy->route;
2189 if (route_entry_equals(old, route))
2190 {
2191 this->mutex->unlock(this->mutex);
2192 route_entry_destroy(route);
2193 return SUCCESS;
2194 }
2195 /* uninstall previously installed route */
2196 if (hydra->kernel_interface->del_route(hydra->kernel_interface,
2197 old->dst_net, old->prefixlen, old->gateway,
2198 old->src_ip, old->if_name) != SUCCESS)
2199 {
2200 DBG1(DBG_KNL, "error uninstalling route installed with "
2201 "policy %R === %R %N", fwd->src_ts,
2202 fwd->dst_ts, policy_dir_names,
2203 policy->direction);
2204 }
2205 route_entry_destroy(old);
2206 policy->route = NULL;
2207 }
2208
2209 DBG2(DBG_KNL, "installing route: %R via %H src %H dev %s",
2210 fwd->src_ts, route->gateway, route->src_ip, route->if_name);
2211 switch (hydra->kernel_interface->add_route(
2212 hydra->kernel_interface, route->dst_net,
2213 route->prefixlen, route->gateway,
2214 route->src_ip, route->if_name))
2215 {
2216 default:
2217 DBG1(DBG_KNL, "unable to install source route for %H",
2218 route->src_ip);
2219 /* FALL */
2220 case ALREADY_DONE:
2221 /* route exists, do not uninstall */
2222 route_entry_destroy(route);
2223 break;
2224 case SUCCESS:
2225 /* cache the installed route */
2226 policy->route = route;
2227 break;
2228 }
2229 }
2230 else
2231 {
2232 free(route);
2233 }
2234 }
2235 this->mutex->unlock(this->mutex);
2236 return SUCCESS;
2237 }
2238
2239 METHOD(kernel_ipsec_t, add_policy, status_t,
2240 private_kernel_netlink_ipsec_t *this, host_t *src, host_t *dst,
2241 traffic_selector_t *src_ts, traffic_selector_t *dst_ts,
2242 policy_dir_t direction, policy_type_t type, ipsec_sa_cfg_t *sa,
2243 mark_t mark, policy_priority_t priority)
2244 {
2245 policy_entry_t *policy, *current;
2246 policy_sa_t *assigned_sa, *current_sa;
2247 enumerator_t *enumerator;
2248 bool found = FALSE, update = TRUE;
2249
2250 /* create a policy */
2251 INIT(policy,
2252 .sel = ts2selector(src_ts, dst_ts),
2253 .mark = mark.value & mark.mask,
2254 .direction = direction,
2255 );
2256
2257 /* find the policy, which matches EXACTLY */
2258 this->mutex->lock(this->mutex);
2259 current = this->policies->get(this->policies, policy);
2260 if (current)
2261 {
2262 /* use existing policy */
2263 DBG2(DBG_KNL, "policy %R === %R %N (mark %u/0x%08x) "
2264 "already exists, increasing refcount",
2265 src_ts, dst_ts, policy_dir_names, direction,
2266 mark.value, mark.mask);
2267 policy_entry_destroy(this, policy);
2268 policy = current;
2269 found = TRUE;
2270 }
2271 else
2272 { /* use the new one, if we have no such policy */
2273 policy->used_by = linked_list_create();
2274 this->policies->put(this->policies, policy, policy);
2275 }
2276
2277 /* cache the assigned IPsec SA */
2278 assigned_sa = policy_sa_create(this, direction, type, src, dst, src_ts,
2279 dst_ts, mark, sa);
2280 assigned_sa->priority = get_priority(policy, priority);
2281
2282 if (this->policy_history)
2283 { /* insert the SA according to its priority */
2284 enumerator = policy->used_by->create_enumerator(policy->used_by);
2285 while (enumerator->enumerate(enumerator, (void**)&current_sa))
2286 {
2287 if (current_sa->priority >= assigned_sa->priority)
2288 {
2289 break;
2290 }
2291 update = FALSE;
2292 }
2293 policy->used_by->insert_before(policy->used_by, enumerator,
2294 assigned_sa);
2295 enumerator->destroy(enumerator);
2296 }
2297 else
2298 { /* simply insert it last and only update if it is not installed yet */
2299 policy->used_by->insert_last(policy->used_by, assigned_sa);
2300 update = !found;
2301 }
2302
2303 if (!update)
2304 { /* we don't update the policy if the priority is lower than that of
2305 * the currently installed one */
2306 this->mutex->unlock(this->mutex);
2307 return SUCCESS;
2308 }
2309
2310 DBG2(DBG_KNL, "%s policy %R === %R %N (mark %u/0x%08x)",
2311 found ? "updating" : "adding", src_ts, dst_ts,
2312 policy_dir_names, direction, mark.value, mark.mask);
2313
2314 if (add_policy_internal(this, policy, assigned_sa, found) != SUCCESS)
2315 {
2316 DBG1(DBG_KNL, "unable to %s policy %R === %R %N",
2317 found ? "update" : "add", src_ts, dst_ts,
2318 policy_dir_names, direction);
2319 return FAILED;
2320 }
2321 return SUCCESS;
2322 }
2323
2324 METHOD(kernel_ipsec_t, query_policy, status_t,
2325 private_kernel_netlink_ipsec_t *this, traffic_selector_t *src_ts,
2326 traffic_selector_t *dst_ts, policy_dir_t direction, mark_t mark,
2327 u_int32_t *use_time)
2328 {
2329 netlink_buf_t request;
2330 struct nlmsghdr *out = NULL, *hdr;
2331 struct xfrm_userpolicy_id *policy_id;
2332 struct xfrm_userpolicy_info *policy = NULL;
2333 size_t len;
2334
2335 memset(&request, 0, sizeof(request));
2336
2337 DBG2(DBG_KNL, "querying policy %R === %R %N (mark %u/0x%08x)",
2338 src_ts, dst_ts, policy_dir_names, direction,
2339 mark.value, mark.mask);
2340
2341 hdr = (struct nlmsghdr*)request;
2342 hdr->nlmsg_flags = NLM_F_REQUEST;
2343 hdr->nlmsg_type = XFRM_MSG_GETPOLICY;
2344 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_id));
2345
2346 policy_id = (struct xfrm_userpolicy_id*)NLMSG_DATA(hdr);
2347 policy_id->sel = ts2selector(src_ts, dst_ts);
2348 policy_id->dir = direction;
2349
2350 if (mark.value)
2351 {
2352 struct xfrm_mark *mrk;
2353 struct rtattr *rthdr = XFRM_RTA(hdr, struct xfrm_userpolicy_id);
2354
2355 rthdr->rta_type = XFRMA_MARK;
2356 rthdr->rta_len = RTA_LENGTH(sizeof(struct xfrm_mark));
2357
2358 hdr->nlmsg_len += RTA_ALIGN(rthdr->rta_len);
2359 if (hdr->nlmsg_len > sizeof(request))
2360 {
2361 return FAILED;
2362 }
2363
2364 mrk = (struct xfrm_mark*)RTA_DATA(rthdr);
2365 mrk->v = mark.value;
2366 mrk->m = mark.mask;
2367 }
2368
2369 if (this->socket_xfrm->send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
2370 {
2371 hdr = out;
2372 while (NLMSG_OK(hdr, len))
2373 {
2374 switch (hdr->nlmsg_type)
2375 {
2376 case XFRM_MSG_NEWPOLICY:
2377 {
2378 policy = (struct xfrm_userpolicy_info*)NLMSG_DATA(hdr);
2379 break;
2380 }
2381 case NLMSG_ERROR:
2382 {
2383 struct nlmsgerr *err = NLMSG_DATA(hdr);
2384 DBG1(DBG_KNL, "querying policy failed: %s (%d)",
2385 strerror(-err->error), -err->error);
2386 break;
2387 }
2388 default:
2389 hdr = NLMSG_NEXT(hdr, len);
2390 continue;
2391 case NLMSG_DONE:
2392 break;
2393 }
2394 break;
2395 }
2396 }
2397
2398 if (policy == NULL)
2399 {
2400 DBG2(DBG_KNL, "unable to query policy %R === %R %N", src_ts, dst_ts,
2401 policy_dir_names, direction);
2402 free(out);
2403 return FAILED;
2404 }
2405
2406 if (policy->curlft.use_time)
2407 {
2408 /* we need the monotonic time, but the kernel returns system time. */
2409 *use_time = time_monotonic(NULL) - (time(NULL) - policy->curlft.use_time);
2410 }
2411 else
2412 {
2413 *use_time = 0;
2414 }
2415
2416 free(out);
2417 return SUCCESS;
2418 }
2419
2420 METHOD(kernel_ipsec_t, del_policy, status_t,
2421 private_kernel_netlink_ipsec_t *this, traffic_selector_t *src_ts,
2422 traffic_selector_t *dst_ts, policy_dir_t direction, u_int32_t reqid,
2423 mark_t mark, policy_priority_t prio)
2424 {
2425 policy_entry_t *current, policy;
2426 enumerator_t *enumerator;
2427 policy_sa_t *mapping;
2428 netlink_buf_t request;
2429 struct nlmsghdr *hdr;
2430 struct xfrm_userpolicy_id *policy_id;
2431 bool is_installed = TRUE;
2432 u_int32_t priority;
2433
2434 DBG2(DBG_KNL, "deleting policy %R === %R %N (mark %u/0x%08x)",
2435 src_ts, dst_ts, policy_dir_names, direction,
2436 mark.value, mark.mask);
2437
2438 /* create a policy */
2439 memset(&policy, 0, sizeof(policy_entry_t));
2440 policy.sel = ts2selector(src_ts, dst_ts);
2441 policy.mark = mark.value & mark.mask;
2442 policy.direction = direction;
2443
2444 /* find the policy */
2445 this->mutex->lock(this->mutex);
2446 current = this->policies->get(this->policies, &policy);
2447 if (!current)
2448 {
2449 if (mark.value)
2450 {
2451 DBG1(DBG_KNL, "deleting policy %R === %R %N (mark %u/0x%08x) "
2452 "failed, not found", src_ts, dst_ts, policy_dir_names,
2453 direction, mark.value, mark.mask);
2454 }
2455 else
2456 {
2457 DBG1(DBG_KNL, "deleting policy %R === %R %N failed, not found",
2458 src_ts, dst_ts, policy_dir_names, direction);
2459 }
2460 this->mutex->unlock(this->mutex);
2461 return NOT_FOUND;
2462 }
2463
2464 if (this->policy_history)
2465 { /* remove mapping to SA by reqid and priority */
2466 priority = get_priority(current, prio);
2467 enumerator = current->used_by->create_enumerator(current->used_by);
2468 while (enumerator->enumerate(enumerator, (void**)&mapping))
2469 {
2470 if (reqid == mapping->sa->cfg.reqid &&
2471 priority == mapping->priority)
2472 {
2473 current->used_by->remove_at(current->used_by, enumerator);
2474 policy_sa_destroy(mapping, &direction, this);
2475 break;
2476 }
2477 is_installed = FALSE;
2478 }
2479 enumerator->destroy(enumerator);
2480 }
2481 else
2482 { /* remove one of the SAs but don't update the policy */
2483 current->used_by->remove_last(current->used_by, (void**)&mapping);
2484 policy_sa_destroy(mapping, &direction, this);
2485 is_installed = FALSE;
2486 }
2487
2488 if (current->used_by->get_count(current->used_by) > 0)
2489 { /* policy is used by more SAs, keep in kernel */
2490 DBG2(DBG_KNL, "policy still used by another CHILD_SA, not removed");
2491 if (!is_installed)
2492 { /* no need to update as the policy was not installed for this SA */
2493 this->mutex->unlock(this->mutex);
2494 return SUCCESS;
2495 }
2496
2497 DBG2(DBG_KNL, "updating policy %R === %R %N (mark %u/0x%08x)",
2498 src_ts, dst_ts, policy_dir_names, direction,
2499 mark.value, mark.mask);
2500
2501 current->used_by->get_first(current->used_by, (void**)&mapping);
2502 if (add_policy_internal(this, current, mapping, TRUE) != SUCCESS)
2503 {
2504 DBG1(DBG_KNL, "unable to update policy %R === %R %N",
2505 src_ts, dst_ts, policy_dir_names, direction);
2506 return FAILED;
2507 }
2508 return SUCCESS;
2509 }
2510
2511 memset(&request, 0, sizeof(request));
2512
2513 hdr = (struct nlmsghdr*)request;
2514 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2515 hdr->nlmsg_type = XFRM_MSG_DELPOLICY;
2516 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_id));
2517
2518 policy_id = (struct xfrm_userpolicy_id*)NLMSG_DATA(hdr);
2519 policy_id->sel = current->sel;
2520 policy_id->dir = direction;
2521
2522 if (mark.value)
2523 {
2524 struct xfrm_mark *mrk;
2525 struct rtattr *rthdr = XFRM_RTA(hdr, struct xfrm_userpolicy_id);
2526
2527 rthdr->rta_type = XFRMA_MARK;
2528 rthdr->rta_len = RTA_LENGTH(sizeof(struct xfrm_mark));
2529 hdr->nlmsg_len += RTA_ALIGN(rthdr->rta_len);
2530 if (hdr->nlmsg_len > sizeof(request))
2531 {
2532 this->mutex->unlock(this->mutex);
2533 return FAILED;
2534 }
2535
2536 mrk = (struct xfrm_mark*)RTA_DATA(rthdr);
2537 mrk->v = mark.value;
2538 mrk->m = mark.mask;
2539 }
2540
2541 if (current->route)
2542 {
2543 route_entry_t *route = current->route;
2544 if (hydra->kernel_interface->del_route(hydra->kernel_interface,
2545 route->dst_net, route->prefixlen, route->gateway,
2546 route->src_ip, route->if_name) != SUCCESS)
2547 {
2548 DBG1(DBG_KNL, "error uninstalling route installed with "
2549 "policy %R === %R %N", src_ts, dst_ts,
2550 policy_dir_names, direction);
2551 }
2552 }
2553
2554 this->policies->remove(this->policies, current);
2555 policy_entry_destroy(this, current);
2556 this->mutex->unlock(this->mutex);
2557
2558 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
2559 {
2560 if (mark.value)
2561 {
2562 DBG1(DBG_KNL, "unable to delete policy %R === %R %N "
2563 "(mark %u/0x%08x)", src_ts, dst_ts, policy_dir_names,
2564 direction, mark.value, mark.mask);
2565 }
2566 else
2567 {
2568 DBG1(DBG_KNL, "unable to delete policy %R === %R %N",
2569 src_ts, dst_ts, policy_dir_names, direction);
2570 }
2571 return FAILED;
2572 }
2573 return SUCCESS;
2574 }
2575
2576 METHOD(kernel_ipsec_t, flush_policies, status_t,
2577 private_kernel_netlink_ipsec_t *this)
2578 {
2579 netlink_buf_t request;
2580 struct nlmsghdr *hdr;
2581
2582 memset(&request, 0, sizeof(request));
2583
2584 DBG2(DBG_KNL, "flushing all policies from SPD");
2585
2586 hdr = (struct nlmsghdr*)request;
2587 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2588 hdr->nlmsg_type = XFRM_MSG_FLUSHPOLICY;
2589 hdr->nlmsg_len = NLMSG_LENGTH(0); /* no data associated */
2590
2591 /* by adding an rtattr of type XFRMA_POLICY_TYPE we could restrict this
2592 * to main or sub policies (default is main) */
2593
2594 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
2595 {
2596 DBG1(DBG_KNL, "unable to flush SPD entries");
2597 return FAILED;
2598 }
2599 return SUCCESS;
2600 }
2601
2602
2603 METHOD(kernel_ipsec_t, bypass_socket, bool,
2604 private_kernel_netlink_ipsec_t *this, int fd, int family)
2605 {
2606 struct xfrm_userpolicy_info policy;
2607 u_int sol, ipsec_policy;
2608
2609 switch (family)
2610 {
2611 case AF_INET:
2612 sol = SOL_IP;
2613 ipsec_policy = IP_XFRM_POLICY;
2614 break;
2615 case AF_INET6:
2616 sol = SOL_IPV6;
2617 ipsec_policy = IPV6_XFRM_POLICY;
2618 break;
2619 default:
2620 return FALSE;
2621 }
2622
2623 memset(&policy, 0, sizeof(policy));
2624 policy.action = XFRM_POLICY_ALLOW;
2625 policy.sel.family = family;
2626
2627 policy.dir = XFRM_POLICY_OUT;
2628 if (setsockopt(fd, sol, ipsec_policy, &policy, sizeof(policy)) < 0)
2629 {
2630 DBG1(DBG_KNL, "unable to set IPSEC_POLICY on socket: %s",
2631 strerror(errno));
2632 return FALSE;
2633 }
2634 policy.dir = XFRM_POLICY_IN;
2635 if (setsockopt(fd, sol, ipsec_policy, &policy, sizeof(policy)) < 0)
2636 {
2637 DBG1(DBG_KNL, "unable to set IPSEC_POLICY on socket: %s",
2638 strerror(errno));
2639 return FALSE;
2640 }
2641 return TRUE;
2642 }
2643
2644 METHOD(kernel_ipsec_t, enable_udp_decap, bool,
2645 private_kernel_netlink_ipsec_t *this, int fd, int family, u_int16_t port)
2646 {
2647 int type = UDP_ENCAP_ESPINUDP;
2648
2649 if (setsockopt(fd, SOL_UDP, UDP_ENCAP, &type, sizeof(type)) < 0)
2650 {
2651 DBG1(DBG_KNL, "unable to set UDP_ENCAP: %s", strerror(errno));
2652 return FALSE;
2653 }
2654 return TRUE;
2655 }
2656
2657 METHOD(kernel_ipsec_t, destroy, void,
2658 private_kernel_netlink_ipsec_t *this)
2659 {
2660 enumerator_t *enumerator;
2661 policy_entry_t *policy;
2662
2663 if (this->socket_xfrm_events > 0)
2664 {
2665 close(this->socket_xfrm_events);
2666 }
2667 DESTROY_IF(this->socket_xfrm);
2668 enumerator = this->policies->create_enumerator(this->policies);
2669 while (enumerator->enumerate(enumerator, &policy, &policy))
2670 {
2671 policy_entry_destroy(this, policy);
2672 }
2673 enumerator->destroy(enumerator);
2674 this->policies->destroy(this->policies);
2675 this->sas->destroy(this->sas);
2676 this->mutex->destroy(this->mutex);
2677 free(this);
2678 }
2679
2680 /*
2681 * Described in header.
2682 */
2683 kernel_netlink_ipsec_t *kernel_netlink_ipsec_create()
2684 {
2685 private_kernel_netlink_ipsec_t *this;
2686 bool register_for_events = TRUE;
2687 int fd;
2688
2689 INIT(this,
2690 .public = {
2691 .interface = {
2692 .get_spi = _get_spi,
2693 .get_cpi = _get_cpi,
2694 .add_sa = _add_sa,
2695 .update_sa = _update_sa,
2696 .query_sa = _query_sa,
2697 .del_sa = _del_sa,
2698 .flush_sas = _flush_sas,
2699 .add_policy = _add_policy,
2700 .query_policy = _query_policy,
2701 .del_policy = _del_policy,
2702 .flush_policies = _flush_policies,
2703 .bypass_socket = _bypass_socket,
2704 .enable_udp_decap = _enable_udp_decap,
2705 .destroy = _destroy,
2706 },
2707 },
2708 .policies = hashtable_create((hashtable_hash_t)policy_hash,
2709 (hashtable_equals_t)policy_equals, 32),
2710 .sas = hashtable_create((hashtable_hash_t)ipsec_sa_hash,
2711 (hashtable_equals_t)ipsec_sa_equals, 32),
2712 .mutex = mutex_create(MUTEX_TYPE_DEFAULT),
2713 .policy_history = TRUE,
2714 .install_routes = lib->settings->get_bool(lib->settings,
2715 "%s.install_routes", TRUE, hydra->daemon),
2716 .replay_window = lib->settings->get_int(lib->settings,
2717 "%s.replay_window", DEFAULT_REPLAY_WINDOW, hydra->daemon),
2718 );
2719
2720 this->replay_bmp = (this->replay_window + sizeof(u_int32_t) * 8 - 1) /
2721 (sizeof(u_int32_t) * 8);
2722
2723 if (streq(hydra->daemon, "pluto"))
2724 { /* no routes for pluto, they are installed via updown script */
2725 this->install_routes = FALSE;
2726 /* no policy history for pluto */
2727 this->policy_history = FALSE;
2728 }
2729 else if (streq(hydra->daemon, "starter"))
2730 { /* starter has no threads, so we do not register for kernel events */
2731 register_for_events = FALSE;
2732 }
2733
2734 /* disable lifetimes for allocated SPIs in kernel */
2735 fd = open("/proc/sys/net/core/xfrm_acq_expires", O_WRONLY);
2736 if (fd)
2737 {
2738 ignore_result(write(fd, "165", 3));
2739 close(fd);
2740 }
2741
2742 this->socket_xfrm = netlink_socket_create(NETLINK_XFRM);
2743 if (!this->socket_xfrm)
2744 {
2745 destroy(this);
2746 return NULL;
2747 }
2748
2749 if (register_for_events)
2750 {
2751 struct sockaddr_nl addr;
2752
2753 memset(&addr, 0, sizeof(addr));
2754 addr.nl_family = AF_NETLINK;
2755
2756 /* create and bind XFRM socket for ACQUIRE, EXPIRE, MIGRATE & MAPPING */
2757 this->socket_xfrm_events = socket(AF_NETLINK, SOCK_RAW, NETLINK_XFRM);
2758 if (this->socket_xfrm_events <= 0)
2759 {
2760 DBG1(DBG_KNL, "unable to create XFRM event socket");
2761 destroy(this);
2762 return NULL;
2763 }
2764 addr.nl_groups = XFRMNLGRP(ACQUIRE) | XFRMNLGRP(EXPIRE) |
2765 XFRMNLGRP(MIGRATE) | XFRMNLGRP(MAPPING);
2766 if (bind(this->socket_xfrm_events, (struct sockaddr*)&addr, sizeof(addr)))
2767 {
2768 DBG1(DBG_KNL, "unable to bind XFRM event socket");
2769 destroy(this);
2770 return NULL;
2771 }
2772 lib->processor->queue_job(lib->processor,
2773 (job_t*)callback_job_create_with_prio(
2774 (callback_job_cb_t)receive_events, this, NULL,
2775 (callback_job_cancel_t)return_false, JOB_PRIO_CRITICAL));
2776 }
2777
2778 return &this->public;
2779 }
2780