f747121bdd81e0849ad189c324dc42eff568254f
[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 free(out);
1961
1962 return status;
1963 }
1964
1965 METHOD(kernel_ipsec_t, flush_sas, status_t,
1966 private_kernel_netlink_ipsec_t *this)
1967 {
1968 netlink_buf_t request;
1969 struct nlmsghdr *hdr;
1970 struct xfrm_usersa_flush *flush;
1971
1972 memset(&request, 0, sizeof(request));
1973
1974 DBG2(DBG_KNL, "flushing all SAD entries");
1975
1976 hdr = (struct nlmsghdr*)request;
1977 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
1978 hdr->nlmsg_type = XFRM_MSG_FLUSHSA;
1979 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_flush));
1980
1981 flush = (struct xfrm_usersa_flush*)NLMSG_DATA(hdr);
1982 flush->proto = IPSEC_PROTO_ANY;
1983
1984 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
1985 {
1986 DBG1(DBG_KNL, "unable to flush SAD entries");
1987 return FAILED;
1988 }
1989 return SUCCESS;
1990 }
1991
1992 /**
1993 * Add or update a policy in the kernel.
1994 *
1995 * Note: The mutex has to be locked when entering this function.
1996 */
1997 static status_t add_policy_internal(private_kernel_netlink_ipsec_t *this,
1998 policy_entry_t *policy, policy_sa_t *mapping, bool update)
1999 {
2000 netlink_buf_t request;
2001 policy_entry_t clone;
2002 ipsec_sa_t *ipsec = mapping->sa;
2003 struct xfrm_userpolicy_info *policy_info;
2004 struct nlmsghdr *hdr;
2005 int i;
2006
2007 /* clone the policy so we are able to check it out again later */
2008 memcpy(&clone, policy, sizeof(policy_entry_t));
2009
2010 memset(&request, 0, sizeof(request));
2011 hdr = (struct nlmsghdr*)request;
2012 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2013 hdr->nlmsg_type = update ? XFRM_MSG_UPDPOLICY : XFRM_MSG_NEWPOLICY;
2014 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_info));
2015
2016 policy_info = (struct xfrm_userpolicy_info*)NLMSG_DATA(hdr);
2017 policy_info->sel = policy->sel;
2018 policy_info->dir = policy->direction;
2019
2020 /* calculate priority based on selector size, small size = high prio */
2021 policy_info->priority = mapping->priority;
2022 policy_info->action = mapping->type != POLICY_DROP ? XFRM_POLICY_ALLOW
2023 : XFRM_POLICY_BLOCK;
2024 policy_info->share = XFRM_SHARE_ANY;
2025
2026 /* policies don't expire */
2027 policy_info->lft.soft_byte_limit = XFRM_INF;
2028 policy_info->lft.soft_packet_limit = XFRM_INF;
2029 policy_info->lft.hard_byte_limit = XFRM_INF;
2030 policy_info->lft.hard_packet_limit = XFRM_INF;
2031 policy_info->lft.soft_add_expires_seconds = 0;
2032 policy_info->lft.hard_add_expires_seconds = 0;
2033 policy_info->lft.soft_use_expires_seconds = 0;
2034 policy_info->lft.hard_use_expires_seconds = 0;
2035
2036 struct rtattr *rthdr = XFRM_RTA(hdr, struct xfrm_userpolicy_info);
2037
2038 if (mapping->type == POLICY_IPSEC)
2039 {
2040 struct xfrm_user_tmpl *tmpl = (struct xfrm_user_tmpl*)RTA_DATA(rthdr);
2041 struct {
2042 u_int8_t proto;
2043 bool use;
2044 } protos[] = {
2045 { IPPROTO_COMP, ipsec->cfg.ipcomp.transform != IPCOMP_NONE },
2046 { IPPROTO_ESP, ipsec->cfg.esp.use },
2047 { IPPROTO_AH, ipsec->cfg.ah.use },
2048 };
2049 ipsec_mode_t proto_mode = ipsec->cfg.mode;
2050
2051 rthdr->rta_type = XFRMA_TMPL;
2052 rthdr->rta_len = 0; /* actual length is set below */
2053
2054 for (i = 0; i < countof(protos); i++)
2055 {
2056 if (!protos[i].use)
2057 {
2058 continue;
2059 }
2060
2061 rthdr->rta_len += RTA_LENGTH(sizeof(struct xfrm_user_tmpl));
2062 hdr->nlmsg_len += RTA_ALIGN(RTA_LENGTH(sizeof(struct xfrm_user_tmpl)));
2063 if (hdr->nlmsg_len > sizeof(request))
2064 {
2065 return FAILED;
2066 }
2067
2068 tmpl->reqid = ipsec->cfg.reqid;
2069 tmpl->id.proto = protos[i].proto;
2070 tmpl->aalgos = tmpl->ealgos = tmpl->calgos = ~0;
2071 tmpl->mode = mode2kernel(proto_mode);
2072 tmpl->optional = protos[i].proto == IPPROTO_COMP &&
2073 policy->direction != POLICY_OUT;
2074 tmpl->family = ipsec->src->get_family(ipsec->src);
2075
2076 if (proto_mode == MODE_TUNNEL)
2077 { /* only for tunnel mode */
2078 host2xfrm(ipsec->src, &tmpl->saddr);
2079 host2xfrm(ipsec->dst, &tmpl->id.daddr);
2080 }
2081
2082 tmpl++;
2083
2084 /* use transport mode for other SAs */
2085 proto_mode = MODE_TRANSPORT;
2086 }
2087
2088 rthdr = XFRM_RTA_NEXT(rthdr);
2089 }
2090
2091 if (ipsec->mark.value)
2092 {
2093 struct xfrm_mark *mrk;
2094
2095 rthdr->rta_type = XFRMA_MARK;
2096 rthdr->rta_len = RTA_LENGTH(sizeof(struct xfrm_mark));
2097
2098 hdr->nlmsg_len += RTA_ALIGN(rthdr->rta_len);
2099 if (hdr->nlmsg_len > sizeof(request))
2100 {
2101 return FAILED;
2102 }
2103
2104 mrk = (struct xfrm_mark*)RTA_DATA(rthdr);
2105 mrk->v = ipsec->mark.value;
2106 mrk->m = ipsec->mark.mask;
2107 }
2108 this->mutex->unlock(this->mutex);
2109
2110 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
2111 {
2112 return FAILED;
2113 }
2114
2115 /* find the policy again */
2116 this->mutex->lock(this->mutex);
2117 policy = this->policies->get(this->policies, &clone);
2118 if (!policy ||
2119 policy->used_by->find_first(policy->used_by,
2120 NULL, (void**)&mapping) != SUCCESS)
2121 { /* policy or mapping is already gone, ignore */
2122 this->mutex->unlock(this->mutex);
2123 return SUCCESS;
2124 }
2125
2126 /* install a route, if:
2127 * - this is a forward policy (to just get one for each child)
2128 * - we are in tunnel/BEET mode
2129 * - routing is not disabled via strongswan.conf
2130 */
2131 if (policy->direction == POLICY_FWD &&
2132 ipsec->cfg.mode != MODE_TRANSPORT && this->install_routes)
2133 {
2134 route_entry_t *route = malloc_thing(route_entry_t);
2135 policy_sa_fwd_t *fwd = (policy_sa_fwd_t*)mapping;
2136
2137 if (hydra->kernel_interface->get_address_by_ts(hydra->kernel_interface,
2138 fwd->dst_ts, &route->src_ip) == SUCCESS)
2139 {
2140 /* get the nexthop to src (src as we are in POLICY_FWD) */
2141 route->gateway = hydra->kernel_interface->get_nexthop(
2142 hydra->kernel_interface, ipsec->src);
2143 /* install route via outgoing interface */
2144 route->if_name = hydra->kernel_interface->get_interface(
2145 hydra->kernel_interface, ipsec->dst);
2146 route->dst_net = chunk_alloc(policy->sel.family == AF_INET ? 4 : 16);
2147 memcpy(route->dst_net.ptr, &policy->sel.saddr, route->dst_net.len);
2148 route->prefixlen = policy->sel.prefixlen_s;
2149
2150 if (!route->if_name)
2151 {
2152 this->mutex->unlock(this->mutex);
2153 route_entry_destroy(route);
2154 return SUCCESS;
2155 }
2156
2157 if (policy->route)
2158 {
2159 route_entry_t *old = policy->route;
2160 if (route_entry_equals(old, route))
2161 { /* keep previously installed route. since it might have
2162 * still been removed by an address change, we install it
2163 * again but ignore the result */
2164 hydra->kernel_interface->add_route(hydra->kernel_interface,
2165 route->dst_net, route->prefixlen, route->gateway,
2166 route->src_ip, route->if_name);
2167 this->mutex->unlock(this->mutex);
2168 route_entry_destroy(route);
2169 return SUCCESS;
2170 }
2171 /* uninstall previously installed route */
2172 if (hydra->kernel_interface->del_route(hydra->kernel_interface,
2173 old->dst_net, old->prefixlen, old->gateway,
2174 old->src_ip, old->if_name) != SUCCESS)
2175 {
2176 DBG1(DBG_KNL, "error uninstalling route installed with "
2177 "policy %R === %R %N", fwd->src_ts,
2178 fwd->dst_ts, policy_dir_names,
2179 policy->direction);
2180 }
2181 route_entry_destroy(old);
2182 policy->route = NULL;
2183 }
2184
2185 DBG2(DBG_KNL, "installing route: %R via %H src %H dev %s",
2186 fwd->src_ts, route->gateway, route->src_ip, route->if_name);
2187 switch (hydra->kernel_interface->add_route(
2188 hydra->kernel_interface, route->dst_net,
2189 route->prefixlen, route->gateway,
2190 route->src_ip, route->if_name))
2191 {
2192 default:
2193 DBG1(DBG_KNL, "unable to install source route for %H",
2194 route->src_ip);
2195 /* FALL */
2196 case ALREADY_DONE:
2197 /* route exists, do not uninstall */
2198 route_entry_destroy(route);
2199 break;
2200 case SUCCESS:
2201 /* cache the installed route */
2202 policy->route = route;
2203 break;
2204 }
2205 }
2206 else
2207 {
2208 free(route);
2209 }
2210 }
2211 this->mutex->unlock(this->mutex);
2212 return SUCCESS;
2213 }
2214
2215 METHOD(kernel_ipsec_t, add_policy, status_t,
2216 private_kernel_netlink_ipsec_t *this, host_t *src, host_t *dst,
2217 traffic_selector_t *src_ts, traffic_selector_t *dst_ts,
2218 policy_dir_t direction, policy_type_t type, ipsec_sa_cfg_t *sa,
2219 mark_t mark, policy_priority_t priority)
2220 {
2221 policy_entry_t *policy, *current;
2222 policy_sa_t *assigned_sa, *current_sa;
2223 enumerator_t *enumerator;
2224 bool found = FALSE, update = TRUE;
2225
2226 /* create a policy */
2227 INIT(policy,
2228 .sel = ts2selector(src_ts, dst_ts),
2229 .mark = mark.value & mark.mask,
2230 .direction = direction,
2231 );
2232
2233 /* find the policy, which matches EXACTLY */
2234 this->mutex->lock(this->mutex);
2235 current = this->policies->get(this->policies, policy);
2236 if (current)
2237 {
2238 /* use existing policy */
2239 if (mark.value)
2240 {
2241 DBG2(DBG_KNL, "policy %R === %R %N (mark %u/0x%8x) "
2242 "already exists, increasing refcount",
2243 src_ts, dst_ts, policy_dir_names, direction,
2244 mark.value, mark.mask);
2245 }
2246 else
2247 {
2248 DBG2(DBG_KNL, "policy %R === %R %N "
2249 "already exists, increasing refcount",
2250 src_ts, dst_ts, policy_dir_names, direction);
2251 }
2252 policy_entry_destroy(this, policy);
2253 policy = current;
2254 found = TRUE;
2255 }
2256 else
2257 { /* use the new one, if we have no such policy */
2258 policy->used_by = linked_list_create();
2259 this->policies->put(this->policies, policy, policy);
2260 }
2261
2262 /* cache the assigned IPsec SA */
2263 assigned_sa = policy_sa_create(this, direction, type, src, dst, src_ts,
2264 dst_ts, mark, sa);
2265 assigned_sa->priority = get_priority(policy, priority);
2266
2267 if (this->policy_history)
2268 { /* insert the SA according to its priority */
2269 enumerator = policy->used_by->create_enumerator(policy->used_by);
2270 while (enumerator->enumerate(enumerator, (void**)&current_sa))
2271 {
2272 if (current_sa->priority >= assigned_sa->priority)
2273 {
2274 break;
2275 }
2276 update = FALSE;
2277 }
2278 policy->used_by->insert_before(policy->used_by, enumerator,
2279 assigned_sa);
2280 enumerator->destroy(enumerator);
2281 }
2282 else
2283 { /* simply insert it last and only update if it is not installed yet */
2284 policy->used_by->insert_last(policy->used_by, assigned_sa);
2285 update = !found;
2286 }
2287
2288 if (!update)
2289 { /* we don't update the policy if the priority is lower than that of
2290 * the currently installed one */
2291 this->mutex->unlock(this->mutex);
2292 return SUCCESS;
2293 }
2294
2295 if (mark.value)
2296 {
2297 DBG2(DBG_KNL, "%s policy %R === %R %N (mark %u/0x%8x)",
2298 found ? "updating" : "adding", src_ts, dst_ts,
2299 policy_dir_names, direction, mark.value, mark.mask);
2300 }
2301 else
2302 {
2303 DBG2(DBG_KNL, "%s policy %R === %R %N",
2304 found ? "updating" : "adding", src_ts, dst_ts,
2305 policy_dir_names, direction);
2306 }
2307
2308 if (add_policy_internal(this, policy, assigned_sa, found) != SUCCESS)
2309 {
2310 DBG1(DBG_KNL, "unable to %s policy %R === %R %N",
2311 found ? "update" : "add", src_ts, dst_ts,
2312 policy_dir_names, direction);
2313 return FAILED;
2314 }
2315 return SUCCESS;
2316 }
2317
2318 METHOD(kernel_ipsec_t, query_policy, status_t,
2319 private_kernel_netlink_ipsec_t *this, traffic_selector_t *src_ts,
2320 traffic_selector_t *dst_ts, policy_dir_t direction, mark_t mark,
2321 u_int32_t *use_time)
2322 {
2323 netlink_buf_t request;
2324 struct nlmsghdr *out = NULL, *hdr;
2325 struct xfrm_userpolicy_id *policy_id;
2326 struct xfrm_userpolicy_info *policy = NULL;
2327 size_t len;
2328
2329 memset(&request, 0, sizeof(request));
2330
2331 if (mark.value)
2332 {
2333 DBG2(DBG_KNL, "querying policy %R === %R %N (mark %u/0x%8x)",
2334 src_ts, dst_ts, policy_dir_names, direction,
2335 mark.value, mark.mask);
2336 }
2337 else
2338 {
2339 DBG2(DBG_KNL, "querying policy %R === %R %N", src_ts, dst_ts,
2340 policy_dir_names, direction);
2341 }
2342 hdr = (struct nlmsghdr*)request;
2343 hdr->nlmsg_flags = NLM_F_REQUEST;
2344 hdr->nlmsg_type = XFRM_MSG_GETPOLICY;
2345 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_id));
2346
2347 policy_id = (struct xfrm_userpolicy_id*)NLMSG_DATA(hdr);
2348 policy_id->sel = ts2selector(src_ts, dst_ts);
2349 policy_id->dir = direction;
2350
2351 if (mark.value)
2352 {
2353 struct xfrm_mark *mrk;
2354 struct rtattr *rthdr = XFRM_RTA(hdr, struct xfrm_userpolicy_id);
2355
2356 rthdr->rta_type = XFRMA_MARK;
2357 rthdr->rta_len = RTA_LENGTH(sizeof(struct xfrm_mark));
2358
2359 hdr->nlmsg_len += RTA_ALIGN(rthdr->rta_len);
2360 if (hdr->nlmsg_len > sizeof(request))
2361 {
2362 return FAILED;
2363 }
2364
2365 mrk = (struct xfrm_mark*)RTA_DATA(rthdr);
2366 mrk->v = mark.value;
2367 mrk->m = mark.mask;
2368 }
2369
2370 if (this->socket_xfrm->send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
2371 {
2372 hdr = out;
2373 while (NLMSG_OK(hdr, len))
2374 {
2375 switch (hdr->nlmsg_type)
2376 {
2377 case XFRM_MSG_NEWPOLICY:
2378 {
2379 policy = (struct xfrm_userpolicy_info*)NLMSG_DATA(hdr);
2380 break;
2381 }
2382 case NLMSG_ERROR:
2383 {
2384 struct nlmsgerr *err = NLMSG_DATA(hdr);
2385 DBG1(DBG_KNL, "querying policy failed: %s (%d)",
2386 strerror(-err->error), -err->error);
2387 break;
2388 }
2389 default:
2390 hdr = NLMSG_NEXT(hdr, len);
2391 continue;
2392 case NLMSG_DONE:
2393 break;
2394 }
2395 break;
2396 }
2397 }
2398
2399 if (policy == NULL)
2400 {
2401 DBG2(DBG_KNL, "unable to query policy %R === %R %N", src_ts, dst_ts,
2402 policy_dir_names, direction);
2403 free(out);
2404 return FAILED;
2405 }
2406
2407 if (policy->curlft.use_time)
2408 {
2409 /* we need the monotonic time, but the kernel returns system time. */
2410 *use_time = time_monotonic(NULL) - (time(NULL) - policy->curlft.use_time);
2411 }
2412 else
2413 {
2414 *use_time = 0;
2415 }
2416
2417 free(out);
2418 return SUCCESS;
2419 }
2420
2421 METHOD(kernel_ipsec_t, del_policy, status_t,
2422 private_kernel_netlink_ipsec_t *this, traffic_selector_t *src_ts,
2423 traffic_selector_t *dst_ts, policy_dir_t direction, u_int32_t reqid,
2424 mark_t mark, policy_priority_t prio)
2425 {
2426 policy_entry_t *current, policy;
2427 enumerator_t *enumerator;
2428 policy_sa_t *mapping;
2429 netlink_buf_t request;
2430 struct nlmsghdr *hdr;
2431 struct xfrm_userpolicy_id *policy_id;
2432 bool is_installed = TRUE;
2433 u_int32_t priority;
2434
2435 if (mark.value)
2436 {
2437 DBG2(DBG_KNL, "deleting policy %R === %R %N (mark %u/0x%8x)",
2438 src_ts, dst_ts, policy_dir_names, direction,
2439 mark.value, mark.mask);
2440 }
2441 else
2442 {
2443 DBG2(DBG_KNL, "deleting policy %R === %R %N",
2444 src_ts, dst_ts, policy_dir_names, direction);
2445 }
2446
2447 /* create a policy */
2448 memset(&policy, 0, sizeof(policy_entry_t));
2449 policy.sel = ts2selector(src_ts, dst_ts);
2450 policy.mark = mark.value & mark.mask;
2451 policy.direction = direction;
2452
2453 /* find the policy */
2454 this->mutex->lock(this->mutex);
2455 current = this->policies->get(this->policies, &policy);
2456 if (!current)
2457 {
2458 if (mark.value)
2459 {
2460 DBG1(DBG_KNL, "deleting policy %R === %R %N (mark %u/0x%8x) "
2461 "failed, not found", src_ts, dst_ts, policy_dir_names,
2462 direction, mark.value, mark.mask);
2463 }
2464 else
2465 {
2466 DBG1(DBG_KNL, "deleting policy %R === %R %N failed, not found",
2467 src_ts, dst_ts, policy_dir_names, direction);
2468 }
2469 this->mutex->unlock(this->mutex);
2470 return NOT_FOUND;
2471 }
2472
2473 if (this->policy_history)
2474 { /* remove mapping to SA by reqid and priority */
2475 priority = get_priority(current, prio);
2476 enumerator = current->used_by->create_enumerator(current->used_by);
2477 while (enumerator->enumerate(enumerator, (void**)&mapping))
2478 {
2479 if (reqid == mapping->sa->cfg.reqid &&
2480 priority == mapping->priority)
2481 {
2482 current->used_by->remove_at(current->used_by, enumerator);
2483 policy_sa_destroy(mapping, &direction, this);
2484 break;
2485 }
2486 is_installed = FALSE;
2487 }
2488 enumerator->destroy(enumerator);
2489 }
2490 else
2491 { /* remove one of the SAs but don't update the policy */
2492 current->used_by->remove_last(current->used_by, (void**)&mapping);
2493 policy_sa_destroy(mapping, &direction, this);
2494 is_installed = FALSE;
2495 }
2496
2497 if (current->used_by->get_count(current->used_by) > 0)
2498 { /* policy is used by more SAs, keep in kernel */
2499 DBG2(DBG_KNL, "policy still used by another CHILD_SA, not removed");
2500 if (!is_installed)
2501 { /* no need to update as the policy was not installed for this SA */
2502 this->mutex->unlock(this->mutex);
2503 return SUCCESS;
2504 }
2505
2506 if (mark.value)
2507 {
2508 DBG2(DBG_KNL, "updating policy %R === %R %N (mark %u/0x%8x)",
2509 src_ts, dst_ts, policy_dir_names, direction,
2510 mark.value, mark.mask);
2511 }
2512 else
2513 {
2514 DBG2(DBG_KNL, "updating policy %R === %R %N",
2515 src_ts, dst_ts, policy_dir_names, direction);
2516 }
2517
2518 current->used_by->get_first(current->used_by, (void**)&mapping);
2519 if (add_policy_internal(this, current, mapping, TRUE) != SUCCESS)
2520 {
2521 DBG1(DBG_KNL, "unable to update policy %R === %R %N",
2522 src_ts, dst_ts, policy_dir_names, direction);
2523 return FAILED;
2524 }
2525 return SUCCESS;
2526 }
2527
2528 memset(&request, 0, sizeof(request));
2529
2530 hdr = (struct nlmsghdr*)request;
2531 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2532 hdr->nlmsg_type = XFRM_MSG_DELPOLICY;
2533 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_id));
2534
2535 policy_id = (struct xfrm_userpolicy_id*)NLMSG_DATA(hdr);
2536 policy_id->sel = current->sel;
2537 policy_id->dir = direction;
2538
2539 if (mark.value)
2540 {
2541 struct xfrm_mark *mrk;
2542 struct rtattr *rthdr = XFRM_RTA(hdr, struct xfrm_userpolicy_id);
2543
2544 rthdr->rta_type = XFRMA_MARK;
2545 rthdr->rta_len = RTA_LENGTH(sizeof(struct xfrm_mark));
2546 hdr->nlmsg_len += RTA_ALIGN(rthdr->rta_len);
2547 if (hdr->nlmsg_len > sizeof(request))
2548 {
2549 return FAILED;
2550 }
2551
2552 mrk = (struct xfrm_mark*)RTA_DATA(rthdr);
2553 mrk->v = mark.value;
2554 mrk->m = mark.mask;
2555 }
2556
2557 if (current->route)
2558 {
2559 route_entry_t *route = current->route;
2560 if (hydra->kernel_interface->del_route(hydra->kernel_interface,
2561 route->dst_net, route->prefixlen, route->gateway,
2562 route->src_ip, route->if_name) != SUCCESS)
2563 {
2564 DBG1(DBG_KNL, "error uninstalling route installed with "
2565 "policy %R === %R %N", src_ts, dst_ts,
2566 policy_dir_names, direction);
2567 }
2568 }
2569
2570 this->policies->remove(this->policies, current);
2571 policy_entry_destroy(this, current);
2572 this->mutex->unlock(this->mutex);
2573
2574 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
2575 {
2576 if (mark.value)
2577 {
2578 DBG1(DBG_KNL, "unable to delete policy %R === %R %N "
2579 "(mark %u/0x%8x)", src_ts, dst_ts, policy_dir_names,
2580 direction, mark.value, mark.mask);
2581 }
2582 else
2583 {
2584 DBG1(DBG_KNL, "unable to delete policy %R === %R %N",
2585 src_ts, dst_ts, policy_dir_names, direction);
2586 }
2587 return FAILED;
2588 }
2589 return SUCCESS;
2590 }
2591
2592 METHOD(kernel_ipsec_t, flush_policies, status_t,
2593 private_kernel_netlink_ipsec_t *this)
2594 {
2595 netlink_buf_t request;
2596 struct nlmsghdr *hdr;
2597
2598 memset(&request, 0, sizeof(request));
2599
2600 DBG2(DBG_KNL, "flushing all policies from SPD");
2601
2602 hdr = (struct nlmsghdr*)request;
2603 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2604 hdr->nlmsg_type = XFRM_MSG_FLUSHPOLICY;
2605 hdr->nlmsg_len = NLMSG_LENGTH(0); /* no data associated */
2606
2607 /* by adding an rtattr of type XFRMA_POLICY_TYPE we could restrict this
2608 * to main or sub policies (default is main) */
2609
2610 if (this->socket_xfrm->send_ack(this->socket_xfrm, hdr) != SUCCESS)
2611 {
2612 DBG1(DBG_KNL, "unable to flush SPD entries");
2613 return FAILED;
2614 }
2615 return SUCCESS;
2616 }
2617
2618
2619 METHOD(kernel_ipsec_t, bypass_socket, bool,
2620 private_kernel_netlink_ipsec_t *this, int fd, int family)
2621 {
2622 struct xfrm_userpolicy_info policy;
2623 u_int sol, ipsec_policy;
2624
2625 switch (family)
2626 {
2627 case AF_INET:
2628 sol = SOL_IP;
2629 ipsec_policy = IP_XFRM_POLICY;
2630 break;
2631 case AF_INET6:
2632 sol = SOL_IPV6;
2633 ipsec_policy = IPV6_XFRM_POLICY;
2634 break;
2635 default:
2636 return FALSE;
2637 }
2638
2639 memset(&policy, 0, sizeof(policy));
2640 policy.action = XFRM_POLICY_ALLOW;
2641 policy.sel.family = family;
2642
2643 policy.dir = XFRM_POLICY_OUT;
2644 if (setsockopt(fd, sol, ipsec_policy, &policy, sizeof(policy)) < 0)
2645 {
2646 DBG1(DBG_KNL, "unable to set IPSEC_POLICY on socket: %s",
2647 strerror(errno));
2648 return FALSE;
2649 }
2650 policy.dir = XFRM_POLICY_IN;
2651 if (setsockopt(fd, sol, ipsec_policy, &policy, sizeof(policy)) < 0)
2652 {
2653 DBG1(DBG_KNL, "unable to set IPSEC_POLICY on socket: %s",
2654 strerror(errno));
2655 return FALSE;
2656 }
2657 return TRUE;
2658 }
2659
2660 METHOD(kernel_ipsec_t, destroy, void,
2661 private_kernel_netlink_ipsec_t *this)
2662 {
2663 enumerator_t *enumerator;
2664 policy_entry_t *policy;
2665
2666 if (this->job)
2667 {
2668 this->job->cancel(this->job);
2669 }
2670 if (this->socket_xfrm_events > 0)
2671 {
2672 close(this->socket_xfrm_events);
2673 }
2674 DESTROY_IF(this->socket_xfrm);
2675 enumerator = this->policies->create_enumerator(this->policies);
2676 while (enumerator->enumerate(enumerator, &policy, &policy))
2677 {
2678 policy_entry_destroy(this, policy);
2679 }
2680 enumerator->destroy(enumerator);
2681 this->policies->destroy(this->policies);
2682 this->sas->destroy(this->sas);
2683 this->mutex->destroy(this->mutex);
2684 free(this);
2685 }
2686
2687 /*
2688 * Described in header.
2689 */
2690 kernel_netlink_ipsec_t *kernel_netlink_ipsec_create()
2691 {
2692 private_kernel_netlink_ipsec_t *this;
2693 struct sockaddr_nl addr;
2694 int fd;
2695
2696 INIT(this,
2697 .public = {
2698 .interface = {
2699 .get_spi = _get_spi,
2700 .get_cpi = _get_cpi,
2701 .add_sa = _add_sa,
2702 .update_sa = _update_sa,
2703 .query_sa = _query_sa,
2704 .del_sa = _del_sa,
2705 .flush_sas = _flush_sas,
2706 .add_policy = _add_policy,
2707 .query_policy = _query_policy,
2708 .del_policy = _del_policy,
2709 .flush_policies = _flush_policies,
2710 .bypass_socket = _bypass_socket,
2711 .destroy = _destroy,
2712 },
2713 },
2714 .policies = hashtable_create((hashtable_hash_t)policy_hash,
2715 (hashtable_equals_t)policy_equals, 32),
2716 .sas = hashtable_create((hashtable_hash_t)ipsec_sa_hash,
2717 (hashtable_equals_t)ipsec_sa_equals, 32),
2718 .mutex = mutex_create(MUTEX_TYPE_DEFAULT),
2719 .policy_history = TRUE,
2720 .install_routes = lib->settings->get_bool(lib->settings,
2721 "%s.install_routes", TRUE, hydra->daemon),
2722 .replay_window = lib->settings->get_int(lib->settings,
2723 "%s.replay_window", DEFAULT_REPLAY_WINDOW, hydra->daemon),
2724 );
2725
2726 this->replay_bmp = (this->replay_window + sizeof(u_int32_t) * 8 - 1) /
2727 (sizeof(u_int32_t) * 8);
2728
2729 if (streq(hydra->daemon, "pluto"))
2730 { /* no routes for pluto, they are installed via updown script */
2731 this->install_routes = FALSE;
2732 /* no policy history for pluto */
2733 this->policy_history = FALSE;
2734 }
2735
2736 /* disable lifetimes for allocated SPIs in kernel */
2737 fd = open("/proc/sys/net/core/xfrm_acq_expires", O_WRONLY);
2738 if (fd)
2739 {
2740 ignore_result(write(fd, "165", 3));
2741 close(fd);
2742 }
2743
2744 this->socket_xfrm = netlink_socket_create(NETLINK_XFRM);
2745 if (!this->socket_xfrm)
2746 {
2747 destroy(this);
2748 return NULL;
2749 }
2750
2751 memset(&addr, 0, sizeof(addr));
2752 addr.nl_family = AF_NETLINK;
2753
2754 /* create and bind XFRM socket for ACQUIRE, EXPIRE, MIGRATE & MAPPING */
2755 this->socket_xfrm_events = socket(AF_NETLINK, SOCK_RAW, NETLINK_XFRM);
2756 if (this->socket_xfrm_events <= 0)
2757 {
2758 DBG1(DBG_KNL, "unable to create XFRM event socket");
2759 destroy(this);
2760 return NULL;
2761 }
2762 addr.nl_groups = XFRMNLGRP(ACQUIRE) | XFRMNLGRP(EXPIRE) |
2763 XFRMNLGRP(MIGRATE) | XFRMNLGRP(MAPPING);
2764 if (bind(this->socket_xfrm_events, (struct sockaddr*)&addr, sizeof(addr)))
2765 {
2766 DBG1(DBG_KNL, "unable to bind XFRM event socket");
2767 destroy(this);
2768 return NULL;
2769 }
2770 this->job = callback_job_create_with_prio((callback_job_cb_t)receive_events,
2771 this, NULL, NULL, JOB_PRIO_CRITICAL);
2772 lib->processor->queue_job(lib->processor, (job_t*)this->job);
2773
2774 return &this->public;
2775 }
2776