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