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