avoid too many alloca()s in netlink send, problematic on MIPS
[strongswan.git] / src / charon / kernel / kernel_interface.c
1 /*
2 * Copyright (C) 2006-2008 Tobias Brunner
3 * Copyright (C) 2005-2007 Martin Willi
4 * Copyright (C) 2006-2007 Fabian Hartmann, Noah Heusser
5 * Copyright (C) 2006 Daniel Roethlisberger
6 * Copyright (C) 2005 Jan Hutter
7 * Hochschule fuer Technik Rapperswil
8 *
9 * This program is free software; you can redistribute it and/or modify it
10 * under the terms of the GNU General Public License as published by the
11 * Free Software Foundation; either version 2 of the License, or (at your
12 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
13 *
14 * This program is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
16 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 * for more details.
18 *
19 * $Id$
20 */
21
22 #include <sys/types.h>
23 #include <sys/socket.h>
24 #include <sys/time.h>
25 #include <linux/netlink.h>
26 #include <linux/rtnetlink.h>
27 #include <linux/xfrm.h>
28 #include <linux/udp.h>
29 #include <netinet/in.h>
30 #include <pthread.h>
31 #include <unistd.h>
32 #include <fcntl.h>
33 #include <errno.h>
34 #include <string.h>
35 #include <net/if.h>
36 #include <sys/ioctl.h>
37
38 #include "kernel_interface.h"
39
40 #include <daemon.h>
41 #include <utils/linked_list.h>
42 #include <processing/jobs/delete_child_sa_job.h>
43 #include <processing/jobs/rekey_child_sa_job.h>
44 #include <processing/jobs/acquire_job.h>
45 #include <processing/jobs/callback_job.h>
46 #include <processing/jobs/roam_job.h>
47
48 /** required for Linux 2.6.26 kernel and later */
49 #ifndef XFRM_STATE_AF_UNSPEC
50 #define XFRM_STATE_AF_UNSPEC 32
51 #endif
52
53 /** routing table for routes installed by us */
54 #ifndef IPSEC_ROUTING_TABLE
55 #define IPSEC_ROUTING_TABLE 100
56 #endif
57 #ifndef IPSEC_ROUTING_TABLE_PRIO
58 #define IPSEC_ROUTING_TABLE_PRIO 100
59 #endif
60
61 /** default priority of installed policies */
62 #define PRIO_LOW 3000
63 #define PRIO_HIGH 2000
64
65 /** delay before firing roam jobs (ms) */
66 #define ROAM_DELAY 100
67
68 #define BUFFER_SIZE 1024
69
70 /**
71 * returns a pointer to the first rtattr following the nlmsghdr *nlh and the
72 * 'usual' netlink data x like 'struct xfrm_usersa_info'
73 */
74 #define XFRM_RTA(nlh, x) ((struct rtattr*)(NLMSG_DATA(nlh) + NLMSG_ALIGN(sizeof(x))))
75 /**
76 * returns a pointer to the next rtattr following rta.
77 * !!! do not use this to parse messages. use RTA_NEXT and RTA_OK instead !!!
78 */
79 #define XFRM_RTA_NEXT(rta) ((struct rtattr*)(((char*)(rta)) + RTA_ALIGN((rta)->rta_len)))
80 /**
81 * returns the total size of attached rta data
82 * (after 'usual' netlink data x like 'struct xfrm_usersa_info')
83 */
84 #define XFRM_PAYLOAD(nlh, x) NLMSG_PAYLOAD(nlh, sizeof(x))
85
86 typedef struct kernel_algorithm_t kernel_algorithm_t;
87
88 /**
89 * Mapping from the algorithms defined in IKEv2 to
90 * kernel level algorithm names and their key length
91 */
92 struct kernel_algorithm_t {
93 /**
94 * Identifier specified in IKEv2
95 */
96 int ikev2_id;
97
98 /**
99 * Name of the algorithm, as used as kernel identifier
100 */
101 char *name;
102
103 /**
104 * Key length in bits, if fixed size
105 */
106 u_int key_size;
107 };
108
109 ENUM(policy_dir_names, POLICY_IN, POLICY_FWD,
110 "in",
111 "out",
112 "fwd"
113 );
114
115 #define END_OF_LIST -1
116
117 /**
118 * Algorithms for encryption
119 */
120 static kernel_algorithm_t encryption_algs[] = {
121 /* {ENCR_DES_IV64, "***", 0}, */
122 {ENCR_DES, "des", 64},
123 {ENCR_3DES, "des3_ede", 192},
124 /* {ENCR_RC5, "***", 0}, */
125 /* {ENCR_IDEA, "***", 0}, */
126 {ENCR_CAST, "cast128", 0},
127 {ENCR_BLOWFISH, "blowfish", 0},
128 /* {ENCR_3IDEA, "***", 0}, */
129 /* {ENCR_DES_IV32, "***", 0}, */
130 {ENCR_NULL, "cipher_null", 0},
131 {ENCR_AES_CBC, "aes", 0},
132 /* {ENCR_AES_CTR, "***", 0}, */
133 {ENCR_AES_CCM_ICV8, "rfc4309(ccm(aes))", 64}, /* key_size = ICV size */
134 {ENCR_AES_CCM_ICV12, "rfc4309(ccm(aes))", 96}, /* key_size = ICV size */
135 {ENCR_AES_CCM_ICV16, "rfc4309(ccm(aes))", 128}, /* key_size = ICV size */
136 {ENCR_AES_GCM_ICV8, "rfc4106(gcm(aes))", 64}, /* key_size = ICV size */
137 {ENCR_AES_GCM_ICV12, "rfc4106(gcm(aes))", 96}, /* key_size = ICV size */
138 {ENCR_AES_GCM_ICV16, "rfc4106(gcm(aes))", 128}, /* key_size = ICV size */
139 {END_OF_LIST, NULL, 0},
140 };
141
142 /**
143 * Algorithms for integrity protection
144 */
145 static kernel_algorithm_t integrity_algs[] = {
146 {AUTH_HMAC_MD5_96, "md5", 128},
147 {AUTH_HMAC_SHA1_96, "sha1", 160},
148 {AUTH_HMAC_SHA2_256_128, "sha256", 256},
149 {AUTH_HMAC_SHA2_384_192, "sha384", 384},
150 {AUTH_HMAC_SHA2_512_256, "sha512", 512},
151 /* {AUTH_DES_MAC, "***", 0}, */
152 /* {AUTH_KPDK_MD5, "***", 0}, */
153 {AUTH_AES_XCBC_96, "xcbc(aes)", 128},
154 {END_OF_LIST, NULL, 0},
155 };
156
157 /**
158 * Algorithms for IPComp
159 */
160 static kernel_algorithm_t compression_algs[] = {
161 /* {IPCOMP_OUI, "***", 0}, */
162 {IPCOMP_DEFLATE, "deflate", 0},
163 {IPCOMP_LZS, "lzs", 0},
164 {IPCOMP_LZJH, "lzjh", 0},
165 {END_OF_LIST, NULL, 0},
166 };
167
168 /**
169 * Look up a kernel algorithm name and its key size
170 */
171 static char* lookup_algorithm(kernel_algorithm_t *kernel_algo,
172 u_int16_t ikev2_algo, u_int16_t *key_size)
173 {
174 while (kernel_algo->ikev2_id != END_OF_LIST)
175 {
176 if (ikev2_algo == kernel_algo->ikev2_id)
177 {
178 /* match, evaluate key length */
179 if (key_size && *key_size == 0)
180 { /* update key size if not set */
181 *key_size = kernel_algo->key_size;
182 }
183 return kernel_algo->name;
184 }
185 kernel_algo++;
186 }
187 return NULL;
188 }
189
190 typedef struct route_entry_t route_entry_t;
191
192 /**
193 * installed routing entry
194 */
195 struct route_entry_t {
196
197 /** Index of the interface the route is bound to */
198 int if_index;
199
200 /** Source ip of the route */
201 host_t *src_ip;
202
203 /** gateway for this route */
204 host_t *gateway;
205
206 /** Destination net */
207 chunk_t dst_net;
208
209 /** Destination net prefixlen */
210 u_int8_t prefixlen;
211 };
212
213 /**
214 * destroy an route_entry_t object
215 */
216 static void route_entry_destroy(route_entry_t *this)
217 {
218 this->src_ip->destroy(this->src_ip);
219 this->gateway->destroy(this->gateway);
220 chunk_free(&this->dst_net);
221 free(this);
222 }
223
224 typedef struct policy_entry_t policy_entry_t;
225
226 /**
227 * installed kernel policy.
228 */
229 struct policy_entry_t {
230
231 /** direction of this policy: in, out, forward */
232 u_int8_t direction;
233
234 /** reqid of the policy */
235 u_int32_t reqid;
236
237 /** parameters of installed policy */
238 struct xfrm_selector sel;
239
240 /** associated route installed for this policy */
241 route_entry_t *route;
242
243 /** by how many CHILD_SA's this policy is used */
244 u_int refcount;
245 };
246
247 typedef struct addr_entry_t addr_entry_t;
248
249 /**
250 * IP address in an inface_entry_t
251 */
252 struct addr_entry_t {
253
254 /** The ip address */
255 host_t *ip;
256
257 /** virtual IP managed by us */
258 bool virtual;
259
260 /** scope of the address */
261 u_char scope;
262
263 /** Number of times this IP is used, if virtual */
264 u_int refcount;
265 };
266
267 /**
268 * destroy a addr_entry_t object
269 */
270 static void addr_entry_destroy(addr_entry_t *this)
271 {
272 this->ip->destroy(this->ip);
273 free(this);
274 }
275
276 typedef struct iface_entry_t iface_entry_t;
277
278 /**
279 * A network interface on this system, containing addr_entry_t's
280 */
281 struct iface_entry_t {
282
283 /** interface index */
284 int ifindex;
285
286 /** name of the interface */
287 char ifname[IFNAMSIZ];
288
289 /** interface flags, as in netdevice(7) SIOCGIFFLAGS */
290 u_int flags;
291
292 /** list of addresses as host_t */
293 linked_list_t *addrs;
294 };
295
296 /**
297 * destroy an interface entry
298 */
299 static void iface_entry_destroy(iface_entry_t *this)
300 {
301 this->addrs->destroy_function(this->addrs, (void*)addr_entry_destroy);
302 free(this);
303 }
304
305 typedef struct private_kernel_interface_t private_kernel_interface_t;
306
307 /**
308 * Private variables and functions of kernel_interface class.
309 */
310 struct private_kernel_interface_t {
311 /**
312 * Public part of the kernel_interface_t object.
313 */
314 kernel_interface_t public;
315
316 /**
317 * mutex to lock access to netlink socket
318 */
319 pthread_mutex_t nl_mutex;
320
321 /**
322 * mutex to lock access to various lists
323 */
324 pthread_mutex_t mutex;
325
326 /**
327 * condition variable to signal virtual IP add/removal
328 */
329 pthread_cond_t cond;
330
331 /**
332 * List of installed policies (policy_entry_t)
333 */
334 linked_list_t *policies;
335
336 /**
337 * Cached list of interfaces and its adresses (iface_entry_t)
338 */
339 linked_list_t *ifaces;
340
341 /**
342 * iterator used in hook()
343 */
344 iterator_t *hiter;
345
346 /**
347 * job receiving netlink events
348 */
349 callback_job_t *job;
350
351 /**
352 * current sequence number for netlink request
353 */
354 int seq;
355
356 /**
357 * Netlink xfrm socket (IPsec)
358 */
359 int socket_xfrm;
360
361 /**
362 * netlink xfrm socket to receive acquire and expire events
363 */
364 int socket_xfrm_events;
365
366 /**
367 * Netlink rt socket (routing)
368 */
369 int socket_rt;
370
371 /**
372 * Netlink rt socket to receive address change events
373 */
374 int socket_rt_events;
375
376 /**
377 * time of the last roam_job
378 */
379 struct timeval last_roam;
380
381 /**
382 * whether to install routes along policies
383 */
384 bool install_routes;
385
386 /**
387 * routing table to install routes
388 */
389 int routing_table;
390
391 /**
392 * priority of used routing table
393 */
394 int routing_table_prio;
395 };
396
397 /**
398 * convert a IKEv2 specific protocol identifier to the kernel one
399 */
400 static u_int8_t proto_ike2kernel(protocol_id_t proto)
401 {
402 switch (proto)
403 {
404 case PROTO_ESP:
405 return IPPROTO_ESP;
406 case PROTO_AH:
407 return IPPROTO_AH;
408 default:
409 return proto;
410 }
411 }
412
413 /**
414 * reverse of ike2kernel
415 */
416 static protocol_id_t proto_kernel2ike(u_int8_t proto)
417 {
418 switch (proto)
419 {
420 case IPPROTO_ESP:
421 return PROTO_ESP;
422 case IPPROTO_AH:
423 return PROTO_AH;
424 default:
425 return proto;
426 }
427 }
428
429 /**
430 * convert a host_t to a struct xfrm_address
431 */
432 static void host2xfrm(host_t *host, xfrm_address_t *xfrm)
433 {
434 chunk_t chunk = host->get_address(host);
435 memcpy(xfrm, chunk.ptr, min(chunk.len, sizeof(xfrm_address_t)));
436 }
437
438 /**
439 * convert a traffic selector address range to subnet and its mask.
440 */
441 static void ts2subnet(traffic_selector_t* ts,
442 xfrm_address_t *net, u_int8_t *mask)
443 {
444 /* there is no way to do this cleanly, as the address range may
445 * be anything else but a subnet. We use from_addr as subnet
446 * and try to calculate a usable subnet mask.
447 */
448 int byte, bit;
449 bool found = FALSE;
450 chunk_t from, to;
451 size_t size = (ts->get_type(ts) == TS_IPV4_ADDR_RANGE) ? 4 : 16;
452
453 from = ts->get_from_address(ts);
454 to = ts->get_to_address(ts);
455
456 *mask = (size * 8);
457 /* go trough all bits of the addresses, beginning in the front.
458 * as long as they are equal, the subnet gets larger
459 */
460 for (byte = 0; byte < size; byte++)
461 {
462 for (bit = 7; bit >= 0; bit--)
463 {
464 if ((1<<bit & from.ptr[byte]) != (1<<bit & to.ptr[byte]))
465 {
466 *mask = ((7 - bit) + (byte * 8));
467 found = TRUE;
468 break;
469 }
470 }
471 if (found)
472 {
473 break;
474 }
475 }
476 memcpy(net, from.ptr, from.len);
477 chunk_free(&from);
478 chunk_free(&to);
479 }
480
481 /**
482 * convert a traffic selector port range to port/portmask
483 */
484 static void ts2ports(traffic_selector_t* ts,
485 u_int16_t *port, u_int16_t *mask)
486 {
487 /* linux does not seem to accept complex portmasks. Only
488 * any or a specific port is allowed. We set to any, if we have
489 * a port range, or to a specific, if we have one port only.
490 */
491 u_int16_t from, to;
492
493 from = ts->get_from_port(ts);
494 to = ts->get_to_port(ts);
495
496 if (from == to)
497 {
498 *port = htons(from);
499 *mask = ~0;
500 }
501 else
502 {
503 *port = 0;
504 *mask = 0;
505 }
506 }
507
508 /**
509 * convert a pair of traffic_selectors to a xfrm_selector
510 */
511 static struct xfrm_selector ts2selector(traffic_selector_t *src,
512 traffic_selector_t *dst)
513 {
514 struct xfrm_selector sel;
515
516 memset(&sel, 0, sizeof(sel));
517 sel.family = (src->get_type(src) == TS_IPV4_ADDR_RANGE) ? AF_INET : AF_INET6;
518 /* src or dest proto may be "any" (0), use more restrictive one */
519 sel.proto = max(src->get_protocol(src), dst->get_protocol(dst));
520 ts2subnet(dst, &sel.daddr, &sel.prefixlen_d);
521 ts2subnet(src, &sel.saddr, &sel.prefixlen_s);
522 ts2ports(dst, &sel.dport, &sel.dport_mask);
523 ts2ports(src, &sel.sport, &sel.sport_mask);
524 sel.ifindex = 0;
525 sel.user = 0;
526
527 return sel;
528 }
529
530 /**
531 * Creates an rtattr and adds it to the netlink message
532 */
533 static void add_attribute(struct nlmsghdr *hdr, int rta_type, chunk_t data,
534 size_t buflen)
535 {
536 struct rtattr *rta;
537
538 if (NLMSG_ALIGN(hdr->nlmsg_len) + RTA_ALIGN(data.len) > buflen)
539 {
540 DBG1(DBG_KNL, "unable to add attribute, buffer too small");
541 return;
542 }
543
544 rta = (struct rtattr*)(((char*)hdr) + NLMSG_ALIGN(hdr->nlmsg_len));
545 rta->rta_type = rta_type;
546 rta->rta_len = RTA_LENGTH(data.len);
547 memcpy(RTA_DATA(rta), data.ptr, data.len);
548 hdr->nlmsg_len = NLMSG_ALIGN(hdr->nlmsg_len) + rta->rta_len;
549 }
550
551 /**
552 * process a XFRM_MSG_ACQUIRE from kernel
553 */
554 static void process_acquire(private_kernel_interface_t *this, struct nlmsghdr *hdr)
555 {
556 u_int32_t reqid = 0;
557 int proto = 0;
558 job_t *job;
559 struct rtattr *rtattr = XFRM_RTA(hdr, struct xfrm_user_acquire);
560 size_t rtsize = XFRM_PAYLOAD(hdr, struct xfrm_user_tmpl);
561
562 if (RTA_OK(rtattr, rtsize))
563 {
564 if (rtattr->rta_type == XFRMA_TMPL)
565 {
566 struct xfrm_user_tmpl* tmpl = (struct xfrm_user_tmpl*)RTA_DATA(rtattr);
567 reqid = tmpl->reqid;
568 proto = tmpl->id.proto;
569 }
570 }
571 switch (proto)
572 {
573 case 0:
574 case IPPROTO_ESP:
575 case IPPROTO_AH:
576 break;
577 default:
578 /* acquire for AH/ESP only, not for IPCOMP */
579 return;
580 }
581 if (reqid == 0)
582 {
583 DBG1(DBG_KNL, "received a XFRM_MSG_ACQUIRE, but no reqid found");
584 return;
585 }
586 DBG2(DBG_KNL, "received a XFRM_MSG_ACQUIRE");
587 DBG1(DBG_KNL, "creating acquire job for CHILD_SA with reqid {%d}", reqid);
588 job = (job_t*)acquire_job_create(reqid);
589 charon->processor->queue_job(charon->processor, job);
590 }
591
592 /**
593 * process a XFRM_MSG_EXPIRE from kernel
594 */
595 static void process_expire(private_kernel_interface_t *this, struct nlmsghdr *hdr)
596 {
597 job_t *job;
598 protocol_id_t protocol;
599 u_int32_t spi, reqid;
600 struct xfrm_user_expire *expire;
601
602 expire = (struct xfrm_user_expire*)NLMSG_DATA(hdr);
603 protocol = proto_kernel2ike(expire->state.id.proto);
604 spi = expire->state.id.spi;
605 reqid = expire->state.reqid;
606
607 DBG2(DBG_KNL, "received a XFRM_MSG_EXPIRE");
608
609 if (protocol != PROTO_ESP && protocol != PROTO_AH)
610 {
611 DBG2(DBG_KNL, "ignoring XFRM_MSG_EXPIRE for SA with SPI %.8x and reqid {%d} "
612 "which is not a CHILD_SA", ntohl(spi), reqid);
613 return;
614 }
615
616 DBG1(DBG_KNL, "creating %s job for %N CHILD_SA with SPI %.8x and reqid {%d}",
617 expire->hard ? "delete" : "rekey", protocol_id_names,
618 protocol, ntohl(spi), reqid);
619 if (expire->hard)
620 {
621 job = (job_t*)delete_child_sa_job_create(reqid, protocol, spi);
622 }
623 else
624 {
625 job = (job_t*)rekey_child_sa_job_create(reqid, protocol, spi);
626 }
627 charon->processor->queue_job(charon->processor, job);
628 }
629
630 /**
631 * start a roaming job. We delay it for a second and fire only one job
632 * for multiple events. Otherwise we would create two many jobs.
633 */
634 static void fire_roam_job(private_kernel_interface_t *this, bool address)
635 {
636 struct timeval now;
637
638 if (gettimeofday(&now, NULL) == 0)
639 {
640 if (timercmp(&now, &this->last_roam, >))
641 {
642 now.tv_usec += ROAM_DELAY * 1000;
643 while (now.tv_usec > 1000000)
644 {
645 now.tv_sec++;
646 now.tv_usec -= 1000000;
647 }
648 this->last_roam = now;
649 charon->scheduler->schedule_job(charon->scheduler,
650 (job_t*)roam_job_create(address), ROAM_DELAY);
651 }
652 }
653 }
654
655 /**
656 * get the refcount of a virtual ip
657 */
658 static int get_vip_refcount(private_kernel_interface_t *this, host_t* ip)
659 {
660 iterator_t *ifaces, *addrs;
661 iface_entry_t *iface;
662 addr_entry_t *addr;
663 int refcount = 0;
664
665 ifaces = this->ifaces->create_iterator(this->ifaces, TRUE);
666 while (ifaces->iterate(ifaces, (void**)&iface))
667 {
668 addrs = iface->addrs->create_iterator(iface->addrs, TRUE);
669 while (addrs->iterate(addrs, (void**)&addr))
670 {
671 if (addr->virtual && (iface->flags & IFF_UP) &&
672 ip->ip_equals(ip, addr->ip))
673 {
674 refcount = addr->refcount;
675 break;
676 }
677 }
678 addrs->destroy(addrs);
679 if (refcount)
680 {
681 break;
682 }
683 }
684 ifaces->destroy(ifaces);
685
686 return refcount;
687 }
688
689 /**
690 * process RTM_NEWLINK/RTM_DELLINK from kernel
691 */
692 static void process_link(private_kernel_interface_t *this,
693 struct nlmsghdr *hdr, bool event)
694 {
695 struct ifinfomsg* msg = (struct ifinfomsg*)(NLMSG_DATA(hdr));
696 struct rtattr *rta = IFLA_RTA(msg);
697 size_t rtasize = IFLA_PAYLOAD (hdr);
698 iterator_t *iterator;
699 iface_entry_t *current, *entry = NULL;
700 char *name = NULL;
701 bool update = FALSE;
702
703 while(RTA_OK(rta, rtasize))
704 {
705 switch (rta->rta_type)
706 {
707 case IFLA_IFNAME:
708 name = RTA_DATA(rta);
709 break;
710 }
711 rta = RTA_NEXT(rta, rtasize);
712 }
713 if (!name)
714 {
715 name = "(unknown)";
716 }
717
718 switch (hdr->nlmsg_type)
719 {
720 case RTM_NEWLINK:
721 {
722 if (msg->ifi_flags & IFF_LOOPBACK)
723 { /* ignore loopback interfaces */
724 break;
725 }
726 iterator = this->ifaces->create_iterator_locked(this->ifaces,
727 &this->mutex);
728 while (iterator->iterate(iterator, (void**)&current))
729 {
730 if (current->ifindex == msg->ifi_index)
731 {
732 entry = current;
733 break;
734 }
735 }
736 if (!entry)
737 {
738 entry = malloc_thing(iface_entry_t);
739 entry->ifindex = msg->ifi_index;
740 entry->flags = 0;
741 entry->addrs = linked_list_create();
742 this->ifaces->insert_last(this->ifaces, entry);
743 }
744 memcpy(entry->ifname, name, IFNAMSIZ);
745 entry->ifname[IFNAMSIZ-1] = '\0';
746 if (event)
747 {
748 if (!(entry->flags & IFF_UP) && (msg->ifi_flags & IFF_UP))
749 {
750 update = TRUE;
751 DBG1(DBG_KNL, "interface %s activated", name);
752 }
753 if ((entry->flags & IFF_UP) && !(msg->ifi_flags & IFF_UP))
754 {
755 update = TRUE;
756 DBG1(DBG_KNL, "interface %s deactivated", name);
757 }
758 }
759 entry->flags = msg->ifi_flags;
760 iterator->destroy(iterator);
761 break;
762 }
763 case RTM_DELLINK:
764 {
765 iterator = this->ifaces->create_iterator_locked(this->ifaces,
766 &this->mutex);
767 while (iterator->iterate(iterator, (void**)&current))
768 {
769 if (current->ifindex == msg->ifi_index)
770 {
771 /* we do not remove it, as an address may be added to a
772 * "down" interface and we wan't to know that. */
773 current->flags = msg->ifi_flags;
774 break;
775 }
776 }
777 iterator->destroy(iterator);
778 break;
779 }
780 }
781
782 /* send an update to all IKE_SAs */
783 if (update && event)
784 {
785 fire_roam_job(this, TRUE);
786 }
787 }
788
789 /**
790 * process RTM_NEWADDR/RTM_DELADDR from kernel
791 */
792 static void process_addr(private_kernel_interface_t *this,
793 struct nlmsghdr *hdr, bool event)
794 {
795 struct ifaddrmsg* msg = (struct ifaddrmsg*)(NLMSG_DATA(hdr));
796 struct rtattr *rta = IFA_RTA(msg);
797 size_t rtasize = IFA_PAYLOAD (hdr);
798 host_t *host = NULL;
799 iterator_t *ifaces, *addrs;
800 iface_entry_t *iface;
801 addr_entry_t *addr;
802 chunk_t local = chunk_empty, address = chunk_empty;
803 bool update = FALSE, found = FALSE, changed = FALSE;
804
805 while(RTA_OK(rta, rtasize))
806 {
807 switch (rta->rta_type)
808 {
809 case IFA_LOCAL:
810 local.ptr = RTA_DATA(rta);
811 local.len = RTA_PAYLOAD(rta);
812 break;
813 case IFA_ADDRESS:
814 address.ptr = RTA_DATA(rta);
815 address.len = RTA_PAYLOAD(rta);
816 break;
817 }
818 rta = RTA_NEXT(rta, rtasize);
819 }
820
821 /* For PPP interfaces, we need the IFA_LOCAL address,
822 * IFA_ADDRESS is the peers address. But IFA_LOCAL is
823 * not included in all cases (IPv6?), so fallback to IFA_ADDRESS. */
824 if (local.ptr)
825 {
826 host = host_create_from_chunk(msg->ifa_family, local, 0);
827 }
828 else if (address.ptr)
829 {
830 host = host_create_from_chunk(msg->ifa_family, address, 0);
831 }
832
833 if (host == NULL)
834 { /* bad family? */
835 return;
836 }
837
838 ifaces = this->ifaces->create_iterator_locked(this->ifaces, &this->mutex);
839 while (ifaces->iterate(ifaces, (void**)&iface))
840 {
841 if (iface->ifindex == msg->ifa_index)
842 {
843 addrs = iface->addrs->create_iterator(iface->addrs, TRUE);
844 while (addrs->iterate(addrs, (void**)&addr))
845 {
846 if (host->ip_equals(host, addr->ip))
847 {
848 found = TRUE;
849 if (hdr->nlmsg_type == RTM_DELADDR)
850 {
851 addrs->remove(addrs);
852 if (!addr->virtual)
853 {
854 changed = TRUE;
855 DBG1(DBG_KNL, "%H disappeared from %s",
856 host, iface->ifname);
857 }
858 addr_entry_destroy(addr);
859 }
860 else if (hdr->nlmsg_type == RTM_NEWADDR && addr->virtual)
861 {
862 addr->refcount = 1;
863 }
864 }
865 }
866 addrs->destroy(addrs);
867
868 if (hdr->nlmsg_type == RTM_NEWADDR)
869 {
870 if (!found)
871 {
872 found = TRUE;
873 changed = TRUE;
874 addr = malloc_thing(addr_entry_t);
875 addr->ip = host->clone(host);
876 addr->virtual = FALSE;
877 addr->refcount = 1;
878 addr->scope = msg->ifa_scope;
879
880 iface->addrs->insert_last(iface->addrs, addr);
881 if (event)
882 {
883 DBG1(DBG_KNL, "%H appeared on %s", host, iface->ifname);
884 }
885 }
886 }
887 if (found && (iface->flags & IFF_UP))
888 {
889 update = TRUE;
890 }
891 break;
892 }
893 }
894 ifaces->destroy(ifaces);
895 host->destroy(host);
896
897 /* send an update to all IKE_SAs */
898 if (update && event && changed)
899 {
900 fire_roam_job(this, TRUE);
901 }
902 }
903
904 /**
905 * process RTM_NEWROUTE from kernel
906 */
907 static void process_route(private_kernel_interface_t *this, struct nlmsghdr *hdr)
908 {
909 struct rtmsg* msg = (struct rtmsg*)(NLMSG_DATA(hdr));
910 struct rtattr *rta = RTM_RTA(msg);
911 size_t rtasize = RTM_PAYLOAD(hdr);
912 host_t *host = NULL;
913
914 while(RTA_OK(rta, rtasize))
915 {
916 switch (rta->rta_type)
917 {
918 case RTA_PREFSRC:
919 host = host_create_from_chunk(msg->rtm_family,
920 chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta)), 0);
921 break;
922 }
923 rta = RTA_NEXT(rta, rtasize);
924 }
925 if (host)
926 {
927 if (!get_vip_refcount(this, host))
928 { /* ignore routes added for virtual IPs */
929 fire_roam_job(this, FALSE);
930 }
931 host->destroy(host);
932 }
933 }
934
935 /**
936 * Receives events from kernel
937 */
938 static job_requeue_t receive_events(private_kernel_interface_t *this)
939 {
940 char response[1024];
941 struct nlmsghdr *hdr = (struct nlmsghdr*)response;
942 struct sockaddr_nl addr;
943 socklen_t addr_len = sizeof(addr);
944 int len, oldstate, maxfd, selected;
945 fd_set rfds;
946
947 FD_ZERO(&rfds);
948 FD_SET(this->socket_xfrm_events, &rfds);
949 FD_SET(this->socket_rt_events, &rfds);
950 maxfd = max(this->socket_xfrm_events, this->socket_rt_events);
951
952 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate);
953 selected = select(maxfd + 1, &rfds, NULL, NULL, NULL);
954 pthread_setcancelstate(oldstate, NULL);
955 if (selected <= 0)
956 {
957 DBG1(DBG_KNL, "selecting on sockets failed: %s", strerror(errno));
958 return JOB_REQUEUE_FAIR;
959 }
960 if (FD_ISSET(this->socket_xfrm_events, &rfds))
961 {
962 selected = this->socket_xfrm_events;
963 }
964 else if (FD_ISSET(this->socket_rt_events, &rfds))
965 {
966 selected = this->socket_rt_events;
967 }
968 else
969 {
970 return JOB_REQUEUE_DIRECT;
971 }
972
973 len = recvfrom(selected, response, sizeof(response), MSG_DONTWAIT,
974 (struct sockaddr*)&addr, &addr_len);
975 if (len < 0)
976 {
977 switch (errno)
978 {
979 case EINTR:
980 /* interrupted, try again */
981 return JOB_REQUEUE_DIRECT;
982 case EAGAIN:
983 /* no data ready, select again */
984 return JOB_REQUEUE_DIRECT;
985 default:
986 DBG1(DBG_KNL, "unable to receive from xfrm event socket");
987 sleep(1);
988 return JOB_REQUEUE_FAIR;
989 }
990 }
991 if (addr.nl_pid != 0)
992 { /* not from kernel. not interested, try another one */
993 return JOB_REQUEUE_DIRECT;
994 }
995
996 while (NLMSG_OK(hdr, len))
997 {
998 /* looks good so far, dispatch netlink message */
999 if (selected == this->socket_xfrm_events)
1000 {
1001 switch (hdr->nlmsg_type)
1002 {
1003 case XFRM_MSG_ACQUIRE:
1004 process_acquire(this, hdr);
1005 break;
1006 case XFRM_MSG_EXPIRE:
1007 process_expire(this, hdr);
1008 break;
1009 default:
1010 break;
1011 }
1012 }
1013 else if (selected == this->socket_rt_events)
1014 {
1015 switch (hdr->nlmsg_type)
1016 {
1017 case RTM_NEWADDR:
1018 case RTM_DELADDR:
1019 process_addr(this, hdr, TRUE);
1020 pthread_cond_broadcast(&this->cond);
1021 break;
1022 case RTM_NEWLINK:
1023 case RTM_DELLINK:
1024 process_link(this, hdr, TRUE);
1025 pthread_cond_broadcast(&this->cond);
1026 break;
1027 case RTM_NEWROUTE:
1028 case RTM_DELROUTE:
1029 process_route(this, hdr);
1030 break;
1031 default:
1032 break;
1033 }
1034 }
1035 hdr = NLMSG_NEXT(hdr, len);
1036 }
1037 return JOB_REQUEUE_DIRECT;
1038 }
1039
1040 /**
1041 * send a netlink message and wait for a reply
1042 */
1043 static status_t netlink_send(private_kernel_interface_t *this,
1044 int socket, struct nlmsghdr *in,
1045 struct nlmsghdr **out, size_t *out_len)
1046 {
1047 int len, addr_len;
1048 struct sockaddr_nl addr;
1049 chunk_t result = chunk_empty, tmp;
1050 struct nlmsghdr *msg, peek;
1051
1052 pthread_mutex_lock(&this->nl_mutex);
1053
1054 in->nlmsg_seq = ++this->seq;
1055 in->nlmsg_pid = getpid();
1056
1057 memset(&addr, 0, sizeof(addr));
1058 addr.nl_family = AF_NETLINK;
1059 addr.nl_pid = 0;
1060 addr.nl_groups = 0;
1061
1062 while (TRUE)
1063 {
1064 len = sendto(socket, in, in->nlmsg_len, 0,
1065 (struct sockaddr*)&addr, sizeof(addr));
1066
1067 if (len != in->nlmsg_len)
1068 {
1069 if (errno == EINTR)
1070 {
1071 /* interrupted, try again */
1072 continue;
1073 }
1074 pthread_mutex_unlock(&this->nl_mutex);
1075 DBG1(DBG_KNL, "error sending to netlink socket: %s", strerror(errno));
1076 return FAILED;
1077 }
1078 break;
1079 }
1080
1081 while (TRUE)
1082 {
1083 char buf[4096];
1084 tmp.len = sizeof(buf);
1085 tmp.ptr = buf;
1086 msg = (struct nlmsghdr*)tmp.ptr;
1087
1088 memset(&addr, 0, sizeof(addr));
1089 addr.nl_family = AF_NETLINK;
1090 addr.nl_pid = getpid();
1091 addr.nl_groups = 0;
1092 addr_len = sizeof(addr);
1093
1094 len = recvfrom(socket, tmp.ptr, tmp.len, 0,
1095 (struct sockaddr*)&addr, &addr_len);
1096
1097 if (len < 0)
1098 {
1099 if (errno == EINTR)
1100 {
1101 DBG1(DBG_KNL, "got interrupted");
1102 /* interrupted, try again */
1103 continue;
1104 }
1105 DBG1(DBG_KNL, "error reading from netlink socket: %s", strerror(errno));
1106 pthread_mutex_unlock(&this->nl_mutex);
1107 free(result.ptr);
1108 return FAILED;
1109 }
1110 if (!NLMSG_OK(msg, len))
1111 {
1112 DBG1(DBG_KNL, "received corrupted netlink message");
1113 pthread_mutex_unlock(&this->nl_mutex);
1114 free(result.ptr);
1115 return FAILED;
1116 }
1117 if (msg->nlmsg_seq != this->seq)
1118 {
1119 DBG1(DBG_KNL, "received invalid netlink sequence number");
1120 if (msg->nlmsg_seq < this->seq)
1121 {
1122 continue;
1123 }
1124 pthread_mutex_unlock(&this->nl_mutex);
1125 free(result.ptr);
1126 return FAILED;
1127 }
1128
1129 tmp.len = len;
1130 result.ptr = realloc(result.ptr, result.len + tmp.len);
1131 memcpy(result.ptr + result.len, tmp.ptr, tmp.len);
1132 result.len += tmp.len;
1133
1134 /* NLM_F_MULTI flag does not seem to be set correctly, we use sequence
1135 * numbers to detect multi header messages */
1136 len = recvfrom(socket, &peek, sizeof(peek), MSG_PEEK | MSG_DONTWAIT,
1137 (struct sockaddr*)&addr, &addr_len);
1138
1139 if (len == sizeof(peek) && peek.nlmsg_seq == this->seq)
1140 {
1141 /* seems to be multipart */
1142 continue;
1143 }
1144 break;
1145 }
1146
1147 *out_len = result.len;
1148 *out = (struct nlmsghdr*)result.ptr;
1149
1150 pthread_mutex_unlock(&this->nl_mutex);
1151
1152 return SUCCESS;
1153 }
1154
1155 /**
1156 * send a netlink message and wait for its acknowlegde
1157 */
1158 static status_t netlink_send_ack(private_kernel_interface_t *this,
1159 int socket, struct nlmsghdr *in)
1160 {
1161 struct nlmsghdr *out, *hdr;
1162 size_t len;
1163
1164 if (netlink_send(this, socket, in, &out, &len) != SUCCESS)
1165 {
1166 return FAILED;
1167 }
1168 hdr = out;
1169 while (NLMSG_OK(hdr, len))
1170 {
1171 switch (hdr->nlmsg_type)
1172 {
1173 case NLMSG_ERROR:
1174 {
1175 struct nlmsgerr* err = (struct nlmsgerr*)NLMSG_DATA(hdr);
1176
1177 if (err->error)
1178 {
1179 if (-err->error == EEXIST)
1180 { /* do not report existing routes */
1181 free(out);
1182 return ALREADY_DONE;
1183 }
1184 DBG1(DBG_KNL, "received netlink error: %s (%d)",
1185 strerror(-err->error), -err->error);
1186 free(out);
1187 return FAILED;
1188 }
1189 free(out);
1190 return SUCCESS;
1191 }
1192 default:
1193 hdr = NLMSG_NEXT(hdr, len);
1194 continue;
1195 case NLMSG_DONE:
1196 break;
1197 }
1198 break;
1199 }
1200 DBG1(DBG_KNL, "netlink request not acknowlegded");
1201 free(out);
1202 return FAILED;
1203 }
1204
1205 /**
1206 * Initialize a list of local addresses.
1207 */
1208 static status_t init_address_list(private_kernel_interface_t *this)
1209 {
1210 char request[BUFFER_SIZE];
1211 struct nlmsghdr *out, *current, *in;
1212 struct rtgenmsg *msg;
1213 size_t len;
1214 iterator_t *ifaces, *addrs;
1215 iface_entry_t *iface;
1216 addr_entry_t *addr;
1217
1218 DBG1(DBG_KNL, "listening on interfaces:");
1219
1220 memset(&request, 0, sizeof(request));
1221
1222 in = (struct nlmsghdr*)&request;
1223 in->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg));
1224 in->nlmsg_flags = NLM_F_REQUEST | NLM_F_MATCH | NLM_F_ROOT;
1225 msg = (struct rtgenmsg*)NLMSG_DATA(in);
1226 msg->rtgen_family = AF_UNSPEC;
1227
1228 /* get all links */
1229 in->nlmsg_type = RTM_GETLINK;
1230 if (netlink_send(this, this->socket_rt, in, &out, &len) != SUCCESS)
1231 {
1232 return FAILED;
1233 }
1234 current = out;
1235 while (NLMSG_OK(current, len))
1236 {
1237 switch (current->nlmsg_type)
1238 {
1239 case NLMSG_DONE:
1240 break;
1241 case RTM_NEWLINK:
1242 process_link(this, current, FALSE);
1243 /* fall through */
1244 default:
1245 current = NLMSG_NEXT(current, len);
1246 continue;
1247 }
1248 break;
1249 }
1250 free(out);
1251
1252 /* get all interface addresses */
1253 in->nlmsg_type = RTM_GETADDR;
1254 if (netlink_send(this, this->socket_rt, in, &out, &len) != SUCCESS)
1255 {
1256 return FAILED;
1257 }
1258 current = out;
1259 while (NLMSG_OK(current, len))
1260 {
1261 switch (current->nlmsg_type)
1262 {
1263 case NLMSG_DONE:
1264 break;
1265 case RTM_NEWADDR:
1266 process_addr(this, current, FALSE);
1267 /* fall through */
1268 default:
1269 current = NLMSG_NEXT(current, len);
1270 continue;
1271 }
1272 break;
1273 }
1274 free(out);
1275
1276 ifaces = this->ifaces->create_iterator_locked(this->ifaces, &this->mutex);
1277 while (ifaces->iterate(ifaces, (void**)&iface))
1278 {
1279 if (iface->flags & IFF_UP)
1280 {
1281 DBG1(DBG_KNL, " %s", iface->ifname);
1282 addrs = iface->addrs->create_iterator(iface->addrs, TRUE);
1283 while (addrs->iterate(addrs, (void**)&addr))
1284 {
1285 DBG1(DBG_KNL, " %H", addr->ip);
1286 }
1287 addrs->destroy(addrs);
1288 }
1289 }
1290 ifaces->destroy(ifaces);
1291 return SUCCESS;
1292 }
1293
1294 /**
1295 * iterator hook to iterate over addrs
1296 */
1297 static hook_result_t addr_hook(private_kernel_interface_t *this,
1298 addr_entry_t *in, host_t **out)
1299 {
1300 if (in->virtual)
1301 { /* skip virtual interfaces added by us */
1302 return HOOK_SKIP;
1303 }
1304 if (in->scope >= RT_SCOPE_LINK)
1305 { /* skip addresses with a unusable scope */
1306 return HOOK_SKIP;
1307 }
1308 *out = in->ip;
1309 return HOOK_NEXT;
1310 }
1311
1312 /**
1313 * iterator hook to iterate over ifaces
1314 */
1315 static hook_result_t iface_hook(private_kernel_interface_t *this,
1316 iface_entry_t *in, host_t **out)
1317 {
1318 if (!(in->flags & IFF_UP))
1319 { /* skip interfaces not up */
1320 return HOOK_SKIP;
1321 }
1322
1323 if (this->hiter == NULL)
1324 {
1325 this->hiter = in->addrs->create_iterator(in->addrs, TRUE);
1326 this->hiter->set_iterator_hook(this->hiter,
1327 (iterator_hook_t*)addr_hook, this);
1328 }
1329 while (this->hiter->iterate(this->hiter, (void**)out))
1330 {
1331 return HOOK_AGAIN;
1332 }
1333 this->hiter->destroy(this->hiter);
1334 this->hiter = NULL;
1335 return HOOK_SKIP;
1336 }
1337
1338 /**
1339 * Implements kernel_interface_t.create_address_iterator.
1340 */
1341 static iterator_t *create_address_iterator(private_kernel_interface_t *this)
1342 {
1343 iterator_t *iterator;
1344
1345 /* This iterator is not only hooked, is is double-hooked. As we have stored
1346 * our addresses in iface_entry->addr_entry->ip, we need to iterate the
1347 * entries in each interface we iterate. This does the iface_hook. The
1348 * addr_hook returns the ip instead of the addr_entry. */
1349
1350 iterator = this->ifaces->create_iterator_locked(this->ifaces, &this->mutex);
1351 iterator->set_iterator_hook(iterator, (iterator_hook_t*)iface_hook, this);
1352 return iterator;
1353 }
1354
1355 /**
1356 * implementation of kernel_interface_t.get_interface_name
1357 */
1358 static char *get_interface_name(private_kernel_interface_t *this, host_t* ip)
1359 {
1360 iterator_t *ifaces, *addrs;
1361 iface_entry_t *iface;
1362 addr_entry_t *addr;
1363 char *name = NULL;
1364
1365 DBG2(DBG_KNL, "getting interface name for %H", ip);
1366
1367 ifaces = this->ifaces->create_iterator_locked(this->ifaces, &this->mutex);
1368 while (ifaces->iterate(ifaces, (void**)&iface))
1369 {
1370 addrs = iface->addrs->create_iterator(iface->addrs, TRUE);
1371 while (addrs->iterate(addrs, (void**)&addr))
1372 {
1373 if (ip->ip_equals(ip, addr->ip))
1374 {
1375 name = strdup(iface->ifname);
1376 break;
1377 }
1378 }
1379 addrs->destroy(addrs);
1380 if (name)
1381 {
1382 break;
1383 }
1384 }
1385 ifaces->destroy(ifaces);
1386
1387 if (name)
1388 {
1389 DBG2(DBG_KNL, "%H is on interface %s", ip, name);
1390 }
1391 else
1392 {
1393 DBG2(DBG_KNL, "%H is not a local address", ip);
1394 }
1395 return name;
1396 }
1397
1398 /**
1399 * Tries to find an ip address of a local interface that is included in the
1400 * supplied traffic selector.
1401 */
1402 static status_t get_address_by_ts(private_kernel_interface_t *this,
1403 traffic_selector_t *ts, host_t **ip)
1404 {
1405 iterator_t *ifaces, *addrs;
1406 iface_entry_t *iface;
1407 addr_entry_t *addr;
1408 host_t *host;
1409 int family;
1410 bool found = FALSE;
1411
1412 DBG2(DBG_KNL, "getting a local address in traffic selector %R", ts);
1413
1414 /* if we have a family which includes localhost, we do not
1415 * search for an IP, we use the default */
1416 family = ts->get_type(ts) == TS_IPV4_ADDR_RANGE ? AF_INET : AF_INET6;
1417
1418 if (family == AF_INET)
1419 {
1420 host = host_create_from_string("127.0.0.1", 0);
1421 }
1422 else
1423 {
1424 host = host_create_from_string("::1", 0);
1425 }
1426
1427 if (ts->includes(ts, host))
1428 {
1429 *ip = host_create_any(family);
1430 host->destroy(host);
1431 DBG2(DBG_KNL, "using host %H", *ip);
1432 return SUCCESS;
1433 }
1434 host->destroy(host);
1435
1436 ifaces = this->ifaces->create_iterator_locked(this->ifaces, &this->mutex);
1437 while (ifaces->iterate(ifaces, (void**)&iface))
1438 {
1439 addrs = iface->addrs->create_iterator(iface->addrs, TRUE);
1440 while (addrs->iterate(addrs, (void**)&addr))
1441 {
1442 if (ts->includes(ts, addr->ip))
1443 {
1444 found = TRUE;
1445 *ip = addr->ip->clone(addr->ip);
1446 break;
1447 }
1448 }
1449 addrs->destroy(addrs);
1450 if (found)
1451 {
1452 break;
1453 }
1454 }
1455 ifaces->destroy(ifaces);
1456
1457 if (!found)
1458 {
1459 DBG1(DBG_KNL, "no local address found in traffic selector %R", ts);
1460 return FAILED;
1461 }
1462 DBG2(DBG_KNL, "using host %H", *ip);
1463 return SUCCESS;
1464 }
1465
1466 /**
1467 * get the interface of a local address
1468 */
1469 static int get_interface_index(private_kernel_interface_t *this, host_t* ip)
1470 {
1471 iterator_t *ifaces, *addrs;
1472 iface_entry_t *iface;
1473 addr_entry_t *addr;
1474 int ifindex = 0;
1475
1476 DBG2(DBG_KNL, "getting iface for %H", ip);
1477
1478 ifaces = this->ifaces->create_iterator_locked(this->ifaces, &this->mutex);
1479 while (ifaces->iterate(ifaces, (void**)&iface))
1480 {
1481 addrs = iface->addrs->create_iterator(iface->addrs, TRUE);
1482 while (addrs->iterate(addrs, (void**)&addr))
1483 {
1484 if (ip->ip_equals(ip, addr->ip))
1485 {
1486 ifindex = iface->ifindex;
1487 break;
1488 }
1489 }
1490 addrs->destroy(addrs);
1491 if (ifindex)
1492 {
1493 break;
1494 }
1495 }
1496 ifaces->destroy(ifaces);
1497
1498 if (ifindex == 0)
1499 {
1500 DBG1(DBG_KNL, "unable to get interface for %H", ip);
1501 }
1502 return ifindex;
1503 }
1504
1505 /**
1506 * Manages the creation and deletion of ip addresses on an interface.
1507 * By setting the appropriate nlmsg_type, the ip will be set or unset.
1508 */
1509 static status_t manage_ipaddr(private_kernel_interface_t *this, int nlmsg_type,
1510 int flags, int if_index, host_t *ip)
1511 {
1512 unsigned char request[BUFFER_SIZE];
1513 struct nlmsghdr *hdr;
1514 struct ifaddrmsg *msg;
1515 chunk_t chunk;
1516
1517 memset(&request, 0, sizeof(request));
1518
1519 chunk = ip->get_address(ip);
1520
1521 hdr = (struct nlmsghdr*)request;
1522 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags;
1523 hdr->nlmsg_type = nlmsg_type;
1524 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrmsg));
1525
1526 msg = (struct ifaddrmsg*)NLMSG_DATA(hdr);
1527 msg->ifa_family = ip->get_family(ip);
1528 msg->ifa_flags = 0;
1529 msg->ifa_prefixlen = 8 * chunk.len;
1530 msg->ifa_scope = RT_SCOPE_UNIVERSE;
1531 msg->ifa_index = if_index;
1532
1533 add_attribute(hdr, IFA_LOCAL, chunk, sizeof(request));
1534
1535 return netlink_send_ack(this, this->socket_rt, hdr);
1536 }
1537
1538 /**
1539 * Manages source routes in the routing table.
1540 * By setting the appropriate nlmsg_type, the route added or r.
1541 */
1542 static status_t manage_srcroute(private_kernel_interface_t *this, int nlmsg_type,
1543 int flags, route_entry_t *route)
1544 {
1545 unsigned char request[BUFFER_SIZE];
1546 struct nlmsghdr *hdr;
1547 struct rtmsg *msg;
1548 chunk_t chunk;
1549
1550 /* if route is 0.0.0.0/0, we can't install it, as it would
1551 * overwrite the default route. Instead, we add two routes:
1552 * 0.0.0.0/1 and 128.0.0.0/1 */
1553 if (this->routing_table == 0 && route->prefixlen == 0)
1554 {
1555 route_entry_t half;
1556 status_t status;
1557
1558 half.dst_net = chunk_alloca(route->dst_net.len);
1559 memset(half.dst_net.ptr, 0, half.dst_net.len);
1560 half.src_ip = route->src_ip;
1561 half.gateway = route->gateway;
1562 half.if_index = route->if_index;
1563 half.prefixlen = 1;
1564
1565 status = manage_srcroute(this, nlmsg_type, flags, &half);
1566 half.dst_net.ptr[0] |= 0x80;
1567 status = manage_srcroute(this, nlmsg_type, flags, &half);
1568 return status;
1569 }
1570
1571 memset(&request, 0, sizeof(request));
1572
1573 hdr = (struct nlmsghdr*)request;
1574 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags;
1575 hdr->nlmsg_type = nlmsg_type;
1576 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
1577
1578 msg = (struct rtmsg*)NLMSG_DATA(hdr);
1579 msg->rtm_family = route->src_ip->get_family(route->src_ip);
1580 msg->rtm_dst_len = route->prefixlen;
1581 msg->rtm_table = this->routing_table;
1582 msg->rtm_protocol = RTPROT_STATIC;
1583 msg->rtm_type = RTN_UNICAST;
1584 msg->rtm_scope = RT_SCOPE_UNIVERSE;
1585
1586 add_attribute(hdr, RTA_DST, route->dst_net, sizeof(request));
1587 chunk = route->src_ip->get_address(route->src_ip);
1588 add_attribute(hdr, RTA_PREFSRC, chunk, sizeof(request));
1589 chunk = route->gateway->get_address(route->gateway);
1590 add_attribute(hdr, RTA_GATEWAY, chunk, sizeof(request));
1591 chunk.ptr = (char*)&route->if_index;
1592 chunk.len = sizeof(route->if_index);
1593 add_attribute(hdr, RTA_OIF, chunk, sizeof(request));
1594
1595 return netlink_send_ack(this, this->socket_rt, hdr);
1596 }
1597
1598 /**
1599 * create or delete an rule to use our routing table
1600 */
1601 static status_t manage_rule(private_kernel_interface_t *this, int nlmsg_type,
1602 u_int32_t table, u_int32_t prio)
1603 {
1604 unsigned char request[BUFFER_SIZE];
1605 struct nlmsghdr *hdr;
1606 struct rtmsg *msg;
1607 chunk_t chunk;
1608
1609 memset(&request, 0, sizeof(request));
1610 hdr = (struct nlmsghdr*)request;
1611 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
1612 hdr->nlmsg_type = nlmsg_type;
1613 if (nlmsg_type == RTM_NEWRULE)
1614 {
1615 hdr->nlmsg_flags |= NLM_F_CREATE | NLM_F_EXCL;
1616 }
1617 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
1618
1619 msg = (struct rtmsg*)NLMSG_DATA(hdr);
1620 msg->rtm_table = table;
1621 msg->rtm_family = AF_INET;
1622 msg->rtm_protocol = RTPROT_BOOT;
1623 msg->rtm_scope = RT_SCOPE_UNIVERSE;
1624 msg->rtm_type = RTN_UNICAST;
1625
1626 chunk = chunk_from_thing(prio);
1627 add_attribute(hdr, RTA_PRIORITY, chunk, sizeof(request));
1628
1629 return netlink_send_ack(this, this->socket_rt, hdr);
1630 }
1631
1632 /**
1633 * check if an address (chunk) addr is in subnet (net with net_len net bits)
1634 */
1635 static bool addr_in_subnet(chunk_t addr, chunk_t net, int net_len)
1636 {
1637 int bit, byte;
1638
1639 if (addr.len != net.len)
1640 {
1641 return FALSE;
1642 }
1643 /* scan through all bits, beginning in the front */
1644 for (byte = 0; byte < addr.len; byte++)
1645 {
1646 for (bit = 7; bit >= 0; bit--)
1647 {
1648 /* check if bits are equal (or we reached the end of the net) */
1649 if (bit + byte * 8 > net_len)
1650 {
1651 return TRUE;
1652 }
1653 if (((1<<bit) & addr.ptr[byte]) != ((1<<bit) & net.ptr[byte]))
1654 {
1655 return FALSE;
1656 }
1657 }
1658 }
1659 return TRUE;
1660 }
1661
1662 /**
1663 * Get a route: If "nexthop", the nexthop is returned. source addr otherwise.
1664 */
1665 static host_t *get_route(private_kernel_interface_t *this, host_t *dest,
1666 bool nexthop)
1667 {
1668 unsigned char request[BUFFER_SIZE];
1669 struct nlmsghdr *hdr, *out, *current;
1670 struct rtmsg *msg;
1671 chunk_t chunk;
1672 size_t len;
1673 int best = -1;
1674 host_t *src = NULL, *gtw = NULL;
1675
1676 DBG2(DBG_KNL, "getting address to reach %H", dest);
1677
1678 memset(&request, 0, sizeof(request));
1679
1680 hdr = (struct nlmsghdr*)request;
1681 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP | NLM_F_ROOT;
1682 hdr->nlmsg_type = RTM_GETROUTE;
1683 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
1684
1685 msg = (struct rtmsg*)NLMSG_DATA(hdr);
1686 msg->rtm_family = dest->get_family(dest);
1687
1688 chunk = dest->get_address(dest);
1689 add_attribute(hdr, RTA_DST, chunk, sizeof(request));
1690
1691 if (netlink_send(this, this->socket_rt, hdr, &out, &len) != SUCCESS)
1692 {
1693 DBG1(DBG_KNL, "getting address to %H failed", dest);
1694 return NULL;
1695 }
1696 current = out;
1697 while (NLMSG_OK(current, len))
1698 {
1699 switch (current->nlmsg_type)
1700 {
1701 case NLMSG_DONE:
1702 break;
1703 case RTM_NEWROUTE:
1704 {
1705 struct rtattr *rta;
1706 size_t rtasize;
1707 chunk_t rta_gtw, rta_src, rta_dst;
1708 u_int32_t rta_oif = 0;
1709
1710 rta_gtw = rta_src = rta_dst = chunk_empty;
1711 msg = (struct rtmsg*)(NLMSG_DATA(current));
1712 rta = RTM_RTA(msg);
1713 rtasize = RTM_PAYLOAD(current);
1714 while (RTA_OK(rta, rtasize))
1715 {
1716 switch (rta->rta_type)
1717 {
1718 case RTA_PREFSRC:
1719 rta_src = chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta));
1720 break;
1721 case RTA_GATEWAY:
1722 rta_gtw = chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta));
1723 break;
1724 case RTA_DST:
1725 rta_dst = chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta));
1726 break;
1727 case RTA_OIF:
1728 if (RTA_PAYLOAD(rta) == sizeof(rta_oif))
1729 {
1730 rta_oif = *(u_int32_t*)RTA_DATA(rta);
1731 }
1732 break;
1733 }
1734 rta = RTA_NEXT(rta, rtasize);
1735 }
1736
1737 /* apply the route if:
1738 * - it is not from our own ipsec routing table
1739 * - is better than a previous one
1740 * - is the default route or
1741 * - its destination net contains our destination
1742 */
1743 if ((this->routing_table == 0 ||msg->rtm_table != this->routing_table)
1744 && msg->rtm_dst_len > best
1745 && (msg->rtm_dst_len == 0 || /* default route */
1746 (rta_dst.ptr && addr_in_subnet(chunk, rta_dst, msg->rtm_dst_len))))
1747 {
1748 iterator_t *ifaces, *addrs;
1749 iface_entry_t *iface;
1750 addr_entry_t *addr;
1751
1752 best = msg->rtm_dst_len;
1753 if (nexthop)
1754 {
1755 DESTROY_IF(gtw);
1756 gtw = host_create_from_chunk(msg->rtm_family, rta_gtw, 0);
1757 }
1758 else if (rta_src.ptr)
1759 {
1760 DESTROY_IF(src);
1761 src = host_create_from_chunk(msg->rtm_family, rta_src, 0);
1762 if (get_vip_refcount(this, src))
1763 { /* skip source address if it is installed by us */
1764 DESTROY_IF(src);
1765 src = NULL;
1766 current = NLMSG_NEXT(current, len);
1767 continue;
1768 }
1769 }
1770 else
1771 {
1772 /* no source addr, get one from the interfaces */
1773 ifaces = this->ifaces->create_iterator_locked(
1774 this->ifaces, &this->mutex);
1775 while (ifaces->iterate(ifaces, (void**)&iface))
1776 {
1777 if (iface->ifindex == rta_oif)
1778 {
1779 addrs = iface->addrs->create_iterator(
1780 iface->addrs, TRUE);
1781 while (addrs->iterate(addrs, (void**)&addr))
1782 {
1783 chunk_t ip = addr->ip->get_address(addr->ip);
1784 if (msg->rtm_dst_len == 0
1785 || addr_in_subnet(ip, rta_dst, msg->rtm_dst_len))
1786 {
1787 DESTROY_IF(src);
1788 src = addr->ip->clone(addr->ip);
1789 break;
1790 }
1791 }
1792 addrs->destroy(addrs);
1793 }
1794 }
1795 ifaces->destroy(ifaces);
1796 }
1797 }
1798 /* FALL through */
1799 }
1800 default:
1801 current = NLMSG_NEXT(current, len);
1802 continue;
1803 }
1804 break;
1805 }
1806 free(out);
1807
1808 if (nexthop)
1809 {
1810 if (gtw)
1811 {
1812 return gtw;
1813 }
1814 return dest->clone(dest);
1815 }
1816 return src;
1817 }
1818
1819 /**
1820 * Implementation of kernel_interface_t.get_source_addr.
1821 */
1822 static host_t* get_source_addr(private_kernel_interface_t *this, host_t *dest)
1823 {
1824 return get_route(this, dest, FALSE);
1825 }
1826
1827 /**
1828 * Implementation of kernel_interface_t.add_ip.
1829 */
1830 static status_t add_ip(private_kernel_interface_t *this,
1831 host_t *virtual_ip, host_t *iface_ip)
1832 {
1833 iface_entry_t *iface;
1834 addr_entry_t *addr;
1835 iterator_t *addrs, *ifaces;
1836 int ifindex;
1837
1838 DBG2(DBG_KNL, "adding virtual IP %H", virtual_ip);
1839
1840 ifaces = this->ifaces->create_iterator_locked(this->ifaces, &this->mutex);
1841 while (ifaces->iterate(ifaces, (void**)&iface))
1842 {
1843 bool iface_found = FALSE;
1844
1845 addrs = iface->addrs->create_iterator(iface->addrs, TRUE);
1846 while (addrs->iterate(addrs, (void**)&addr))
1847 {
1848 if (iface_ip->ip_equals(iface_ip, addr->ip))
1849 {
1850 iface_found = TRUE;
1851 }
1852 else if (virtual_ip->ip_equals(virtual_ip, addr->ip))
1853 {
1854 addr->refcount++;
1855 DBG2(DBG_KNL, "virtual IP %H already installed on %s",
1856 virtual_ip, iface->ifname);
1857 addrs->destroy(addrs);
1858 ifaces->destroy(ifaces);
1859 return SUCCESS;
1860 }
1861 }
1862 addrs->destroy(addrs);
1863
1864 if (iface_found)
1865 {
1866 ifindex = iface->ifindex;
1867 addr = malloc_thing(addr_entry_t);
1868 addr->ip = virtual_ip->clone(virtual_ip);
1869 addr->refcount = 0;
1870 addr->virtual = TRUE;
1871 addr->scope = RT_SCOPE_UNIVERSE;
1872 iface->addrs->insert_last(iface->addrs, addr);
1873
1874 if (manage_ipaddr(this, RTM_NEWADDR, NLM_F_CREATE | NLM_F_EXCL,
1875 ifindex, virtual_ip) == SUCCESS)
1876 {
1877 while (get_vip_refcount(this, virtual_ip) == 0)
1878 { /* wait until address appears */
1879 pthread_cond_wait(&this->cond, &this->mutex);
1880 }
1881 ifaces->destroy(ifaces);
1882 return SUCCESS;
1883 }
1884 ifaces->destroy(ifaces);
1885 DBG1(DBG_KNL, "adding virtual IP %H failed", virtual_ip);
1886 return FAILED;
1887 }
1888 }
1889 ifaces->destroy(ifaces);
1890
1891 DBG1(DBG_KNL, "interface address %H not found, unable to install"
1892 "virtual IP %H", iface_ip, virtual_ip);
1893 return FAILED;
1894 }
1895
1896 /**
1897 * Implementation of kernel_interface_t.del_ip.
1898 */
1899 static status_t del_ip(private_kernel_interface_t *this, host_t *virtual_ip)
1900 {
1901 iface_entry_t *iface;
1902 addr_entry_t *addr;
1903 iterator_t *addrs, *ifaces;
1904 status_t status;
1905 int ifindex;
1906
1907 DBG2(DBG_KNL, "deleting virtual IP %H", virtual_ip);
1908
1909 ifaces = this->ifaces->create_iterator_locked(this->ifaces, &this->mutex);
1910 while (ifaces->iterate(ifaces, (void**)&iface))
1911 {
1912 addrs = iface->addrs->create_iterator(iface->addrs, TRUE);
1913 while (addrs->iterate(addrs, (void**)&addr))
1914 {
1915 if (virtual_ip->ip_equals(virtual_ip, addr->ip))
1916 {
1917 ifindex = iface->ifindex;
1918 if (addr->refcount == 1)
1919 {
1920 status = manage_ipaddr(this, RTM_DELADDR, 0,
1921 ifindex, virtual_ip);
1922 if (status == SUCCESS)
1923 { /* wait until the address is really gone */
1924 while (get_vip_refcount(this, virtual_ip) > 0)
1925 {
1926 pthread_cond_wait(&this->cond, &this->mutex);
1927 }
1928 }
1929 addrs->destroy(addrs);
1930 ifaces->destroy(ifaces);
1931 return status;
1932 }
1933 else
1934 {
1935 addr->refcount--;
1936 }
1937 DBG2(DBG_KNL, "virtual IP %H used by other SAs, not deleting",
1938 virtual_ip);
1939 addrs->destroy(addrs);
1940 ifaces->destroy(ifaces);
1941 return SUCCESS;
1942 }
1943 }
1944 addrs->destroy(addrs);
1945 }
1946 ifaces->destroy(ifaces);
1947
1948 DBG2(DBG_KNL, "virtual IP %H not cached, unable to delete", virtual_ip);
1949 return FAILED;
1950 }
1951
1952 /**
1953 * Get an SPI for a specific protocol from the kernel.
1954 */
1955 static status_t get_spi_internal(private_kernel_interface_t *this,
1956 host_t *src, host_t *dst, u_int8_t proto, u_int32_t min, u_int32_t max,
1957 u_int32_t reqid, u_int32_t *spi)
1958 {
1959 unsigned char request[BUFFER_SIZE];
1960 struct nlmsghdr *hdr, *out;
1961 struct xfrm_userspi_info *userspi;
1962 u_int32_t received_spi = 0;
1963 size_t len;
1964
1965 memset(&request, 0, sizeof(request));
1966
1967 hdr = (struct nlmsghdr*)request;
1968 hdr->nlmsg_flags = NLM_F_REQUEST;
1969 hdr->nlmsg_type = XFRM_MSG_ALLOCSPI;
1970 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userspi_info));
1971
1972 userspi = (struct xfrm_userspi_info*)NLMSG_DATA(hdr);
1973 host2xfrm(src, &userspi->info.saddr);
1974 host2xfrm(dst, &userspi->info.id.daddr);
1975 userspi->info.id.proto = proto;
1976 userspi->info.mode = TRUE; /* tunnel mode */
1977 userspi->info.reqid = reqid;
1978 userspi->info.family = src->get_family(src);
1979 userspi->min = min;
1980 userspi->max = max;
1981
1982 if (netlink_send(this, this->socket_xfrm, hdr, &out, &len) == SUCCESS)
1983 {
1984 hdr = out;
1985 while (NLMSG_OK(hdr, len))
1986 {
1987 switch (hdr->nlmsg_type)
1988 {
1989 case XFRM_MSG_NEWSA:
1990 {
1991 struct xfrm_usersa_info* usersa = NLMSG_DATA(hdr);
1992 received_spi = usersa->id.spi;
1993 break;
1994 }
1995 case NLMSG_ERROR:
1996 {
1997 struct nlmsgerr *err = NLMSG_DATA(hdr);
1998
1999 DBG1(DBG_KNL, "allocating SPI failed: %s (%d)",
2000 strerror(-err->error), -err->error);
2001 break;
2002 }
2003 default:
2004 hdr = NLMSG_NEXT(hdr, len);
2005 continue;
2006 case NLMSG_DONE:
2007 break;
2008 }
2009 break;
2010 }
2011 free(out);
2012 }
2013
2014 if (received_spi == 0)
2015 {
2016 return FAILED;
2017 }
2018
2019 *spi = received_spi;
2020 return SUCCESS;
2021 }
2022
2023 /**
2024 * Implementation of kernel_interface_t.get_spi.
2025 */
2026 static status_t get_spi(private_kernel_interface_t *this,
2027 host_t *src, host_t *dst,
2028 protocol_id_t protocol, u_int32_t reqid,
2029 u_int32_t *spi)
2030 {
2031 DBG2(DBG_KNL, "getting SPI for reqid {%d}", reqid);
2032
2033 if (get_spi_internal(this, src, dst, proto_ike2kernel(protocol),
2034 0xc0000000, 0xcFFFFFFF, reqid, spi) != SUCCESS)
2035 {
2036 DBG1(DBG_KNL, "unable to get SPI for reqid {%d}", reqid);
2037 return FAILED;
2038 }
2039
2040 DBG2(DBG_KNL, "got SPI %.8x for reqid {%d}", ntohl(*spi), reqid);
2041
2042 return SUCCESS;
2043 }
2044
2045 /**
2046 * Implementation of kernel_interface_t.get_cpi.
2047 */
2048 static status_t get_cpi(private_kernel_interface_t *this,
2049 host_t *src, host_t *dst,
2050 u_int32_t reqid, u_int16_t *cpi)
2051 {
2052 u_int32_t received_spi = 0;
2053
2054 DBG2(DBG_KNL, "getting CPI for reqid {%d}", reqid);
2055
2056 if (get_spi_internal(this, src, dst,
2057 IPPROTO_COMP, 0x100, 0xEFFF, reqid, &received_spi) != SUCCESS)
2058 {
2059 DBG1(DBG_KNL, "unable to get CPI for reqid {%d}", reqid);
2060 return FAILED;
2061 }
2062
2063 *cpi = htons((u_int16_t)ntohl(received_spi));
2064
2065 DBG2(DBG_KNL, "got CPI %.4x for reqid {%d}", ntohs(*cpi), reqid);
2066
2067 return SUCCESS;
2068 }
2069
2070 /**
2071 * Implementation of kernel_interface_t.add_sa.
2072 */
2073 static status_t add_sa(private_kernel_interface_t *this,
2074 host_t *src, host_t *dst, u_int32_t spi,
2075 protocol_id_t protocol, u_int32_t reqid,
2076 u_int64_t expire_soft, u_int64_t expire_hard,
2077 u_int16_t enc_alg, u_int16_t enc_size,
2078 u_int16_t int_alg, u_int16_t int_size,
2079 prf_plus_t *prf_plus, mode_t mode,
2080 u_int16_t ipcomp, bool encap,
2081 bool replace)
2082 {
2083 unsigned char request[BUFFER_SIZE];
2084 char *alg_name;
2085 /* additional 4 octets KEYMAT required for AES-GCM as of RFC4106 8.1. */
2086 u_int16_t add_keymat = 32;
2087 struct nlmsghdr *hdr;
2088 struct xfrm_usersa_info *sa;
2089
2090 memset(&request, 0, sizeof(request));
2091
2092 DBG2(DBG_KNL, "adding SAD entry with SPI %.8x and reqid {%d}", ntohl(spi), reqid);
2093
2094 hdr = (struct nlmsghdr*)request;
2095 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2096 hdr->nlmsg_type = replace ? XFRM_MSG_UPDSA : XFRM_MSG_NEWSA;
2097 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_info));
2098
2099 sa = (struct xfrm_usersa_info*)NLMSG_DATA(hdr);
2100 host2xfrm(src, &sa->saddr);
2101 host2xfrm(dst, &sa->id.daddr);
2102 sa->id.spi = spi;
2103 sa->id.proto = proto_ike2kernel(protocol);
2104 sa->family = src->get_family(src);
2105 sa->mode = mode;
2106 if (mode == MODE_TUNNEL)
2107 {
2108 sa->flags |= XFRM_STATE_AF_UNSPEC;
2109 }
2110 sa->replay_window = (protocol == IPPROTO_COMP) ? 0 : 32;
2111 sa->reqid = reqid;
2112 /* we currently do not expire SAs by volume/packet count */
2113 sa->lft.soft_byte_limit = XFRM_INF;
2114 sa->lft.hard_byte_limit = XFRM_INF;
2115 sa->lft.soft_packet_limit = XFRM_INF;
2116 sa->lft.hard_packet_limit = XFRM_INF;
2117 /* we use lifetimes since added, not since used */
2118 sa->lft.soft_add_expires_seconds = expire_soft;
2119 sa->lft.hard_add_expires_seconds = expire_hard;
2120 sa->lft.soft_use_expires_seconds = 0;
2121 sa->lft.hard_use_expires_seconds = 0;
2122
2123 struct rtattr *rthdr = XFRM_RTA(hdr, struct xfrm_usersa_info);
2124
2125 switch (enc_alg)
2126 {
2127 case ENCR_UNDEFINED:
2128 /* no encryption */
2129 break;
2130 case ENCR_AES_CCM_ICV8:
2131 case ENCR_AES_CCM_ICV12:
2132 case ENCR_AES_CCM_ICV16:
2133 /* AES-CCM needs only 3 additional octets KEYMAT as of RFC 4309 7.1. */
2134 add_keymat = 24;
2135 /* fall-through */
2136 case ENCR_AES_GCM_ICV8:
2137 case ENCR_AES_GCM_ICV12:
2138 case ENCR_AES_GCM_ICV16:
2139 {
2140 u_int16_t icv_size = 0;
2141 rthdr->rta_type = XFRMA_ALG_AEAD;
2142 alg_name = lookup_algorithm(encryption_algs, enc_alg, &icv_size);
2143 if (alg_name == NULL)
2144 {
2145 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
2146 encryption_algorithm_names, enc_alg);
2147 return FAILED;
2148 }
2149 DBG2(DBG_KNL, " using encryption algorithm %N with key size %d",
2150 encryption_algorithm_names, enc_alg, enc_size);
2151
2152 /* additional KEYMAT required */
2153 enc_size += add_keymat;
2154
2155 rthdr->rta_len = RTA_LENGTH(sizeof(struct xfrm_algo_aead) + enc_size / 8);
2156 hdr->nlmsg_len += rthdr->rta_len;
2157 if (hdr->nlmsg_len > sizeof(request))
2158 {
2159 return FAILED;
2160 }
2161
2162 struct xfrm_algo_aead* algo = (struct xfrm_algo_aead*)RTA_DATA(rthdr);
2163 algo->alg_key_len = enc_size;
2164 algo->alg_icv_len = icv_size;
2165 strcpy(algo->alg_name, alg_name);
2166 prf_plus->get_bytes(prf_plus, enc_size / 8, algo->alg_key);
2167
2168 rthdr = XFRM_RTA_NEXT(rthdr);
2169 break;
2170 }
2171 default:
2172 {
2173 rthdr->rta_type = XFRMA_ALG_CRYPT;
2174 alg_name = lookup_algorithm(encryption_algs, enc_alg, &enc_size);
2175 if (alg_name == NULL)
2176 {
2177 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
2178 encryption_algorithm_names, enc_alg);
2179 return FAILED;
2180 }
2181 DBG2(DBG_KNL, " using encryption algorithm %N with key size %d",
2182 encryption_algorithm_names, enc_alg, enc_size);
2183
2184 rthdr->rta_len = RTA_LENGTH(sizeof(struct xfrm_algo) + enc_size / 8);
2185 hdr->nlmsg_len += rthdr->rta_len;
2186 if (hdr->nlmsg_len > sizeof(request))
2187 {
2188 return FAILED;
2189 }
2190
2191 struct xfrm_algo* algo = (struct xfrm_algo*)RTA_DATA(rthdr);
2192 algo->alg_key_len = enc_size;
2193 strcpy(algo->alg_name, alg_name);
2194 prf_plus->get_bytes(prf_plus, enc_size / 8, algo->alg_key);
2195
2196 rthdr = XFRM_RTA_NEXT(rthdr);
2197 break;
2198 }
2199 }
2200
2201 if (int_alg != AUTH_UNDEFINED)
2202 {
2203 rthdr->rta_type = XFRMA_ALG_AUTH;
2204 alg_name = lookup_algorithm(integrity_algs, int_alg, &int_size);
2205 if (alg_name == NULL)
2206 {
2207 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
2208 integrity_algorithm_names, int_alg);
2209 return FAILED;
2210 }
2211 DBG2(DBG_KNL, " using integrity algorithm %N with key size %d",
2212 integrity_algorithm_names, int_alg, int_size);
2213
2214 rthdr->rta_len = RTA_LENGTH(sizeof(struct xfrm_algo) + int_size / 8);
2215 hdr->nlmsg_len += rthdr->rta_len;
2216 if (hdr->nlmsg_len > sizeof(request))
2217 {
2218 return FAILED;
2219 }
2220
2221 struct xfrm_algo* algo = (struct xfrm_algo*)RTA_DATA(rthdr);
2222 algo->alg_key_len = int_size;
2223 strcpy(algo->alg_name, alg_name);
2224 prf_plus->get_bytes(prf_plus, int_size / 8, algo->alg_key);
2225
2226 rthdr = XFRM_RTA_NEXT(rthdr);
2227 }
2228
2229 if (ipcomp != IPCOMP_NONE)
2230 {
2231 rthdr->rta_type = XFRMA_ALG_COMP;
2232 alg_name = lookup_algorithm(compression_algs, ipcomp, NULL);
2233 if (alg_name == NULL)
2234 {
2235 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
2236 ipcomp_transform_names, ipcomp);
2237 return FAILED;
2238 }
2239 DBG2(DBG_KNL, " using compression algorithm %N",
2240 ipcomp_transform_names, ipcomp);
2241
2242 rthdr->rta_len = RTA_LENGTH(sizeof(struct xfrm_algo));
2243 hdr->nlmsg_len += rthdr->rta_len;
2244 if (hdr->nlmsg_len > sizeof(request))
2245 {
2246 return FAILED;
2247 }
2248
2249 struct xfrm_algo* algo = (struct xfrm_algo*)RTA_DATA(rthdr);
2250 algo->alg_key_len = 0;
2251 strcpy(algo->alg_name, alg_name);
2252
2253 rthdr = XFRM_RTA_NEXT(rthdr);
2254 }
2255
2256 if (encap)
2257 {
2258 rthdr->rta_type = XFRMA_ENCAP;
2259 rthdr->rta_len = RTA_LENGTH(sizeof(struct xfrm_encap_tmpl));
2260
2261 hdr->nlmsg_len += rthdr->rta_len;
2262 if (hdr->nlmsg_len > sizeof(request))
2263 {
2264 return FAILED;
2265 }
2266
2267 struct xfrm_encap_tmpl* tmpl = (struct xfrm_encap_tmpl*)RTA_DATA(rthdr);
2268 tmpl->encap_type = UDP_ENCAP_ESPINUDP;
2269 tmpl->encap_sport = htons(src->get_port(src));
2270 tmpl->encap_dport = htons(dst->get_port(dst));
2271 memset(&tmpl->encap_oa, 0, sizeof (xfrm_address_t));
2272 /* encap_oa could probably be derived from the
2273 * traffic selectors [rfc4306, p39]. In the netlink kernel implementation
2274 * pluto does the same as we do here but it uses encap_oa in the
2275 * pfkey implementation. BUT as /usr/src/linux/net/key/af_key.c indicates
2276 * the kernel ignores it anyway
2277 * -> does that mean that NAT-T encap doesn't work in transport mode?
2278 * No. The reason the kernel ignores NAT-OA is that it recomputes
2279 * (or, rather, just ignores) the checksum. If packets pass
2280 * the IPsec checks it marks them "checksum ok" so OA isn't needed. */
2281 rthdr = XFRM_RTA_NEXT(rthdr);
2282 }
2283
2284 if (netlink_send_ack(this, this->socket_xfrm, hdr) != SUCCESS)
2285 {
2286 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x", ntohl(spi));
2287 return FAILED;
2288 }
2289 return SUCCESS;
2290 }
2291
2292 /**
2293 * Get the replay state (i.e. sequence numbers) of an SA.
2294 */
2295 static status_t get_replay_state(private_kernel_interface_t *this,
2296 u_int32_t spi, protocol_id_t protocol, host_t *dst,
2297 struct xfrm_replay_state *replay)
2298 {
2299 unsigned char request[BUFFER_SIZE];
2300 struct nlmsghdr *hdr, *out = NULL;
2301 struct xfrm_aevent_id *out_aevent = NULL, *aevent_id;
2302 size_t len;
2303 struct rtattr *rta;
2304 size_t rtasize;
2305
2306 memset(&request, 0, sizeof(request));
2307
2308 DBG2(DBG_KNL, "querying replay state from SAD entry with SPI %.8x", ntohl(spi));
2309
2310 hdr = (struct nlmsghdr*)request;
2311 hdr->nlmsg_flags = NLM_F_REQUEST;
2312 hdr->nlmsg_type = XFRM_MSG_GETAE;
2313 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_aevent_id));
2314
2315 aevent_id = (struct xfrm_aevent_id*)NLMSG_DATA(hdr);
2316 aevent_id->flags = XFRM_AE_RVAL;
2317
2318 host2xfrm(dst, &aevent_id->sa_id.daddr);
2319 aevent_id->sa_id.spi = spi;
2320 aevent_id->sa_id.proto = proto_ike2kernel(protocol);
2321 aevent_id->sa_id.family = dst->get_family(dst);
2322
2323 if (netlink_send(this, this->socket_xfrm, hdr, &out, &len) == SUCCESS)
2324 {
2325 hdr = out;
2326 while (NLMSG_OK(hdr, len))
2327 {
2328 switch (hdr->nlmsg_type)
2329 {
2330 case XFRM_MSG_NEWAE:
2331 {
2332 out_aevent = NLMSG_DATA(hdr);
2333 break;
2334 }
2335 case NLMSG_ERROR:
2336 {
2337 struct nlmsgerr *err = NLMSG_DATA(hdr);
2338 DBG1(DBG_KNL, "querying replay state from SAD entry failed: %s (%d)",
2339 strerror(-err->error), -err->error);
2340 break;
2341 }
2342 default:
2343 hdr = NLMSG_NEXT(hdr, len);
2344 continue;
2345 case NLMSG_DONE:
2346 break;
2347 }
2348 break;
2349 }
2350 }
2351
2352 if (out_aevent == NULL)
2353 {
2354 DBG1(DBG_KNL, "unable to query replay state from SAD entry with SPI %.8x",
2355 ntohl(spi));
2356 free(out);
2357 return FAILED;
2358 }
2359
2360 rta = XFRM_RTA(out, struct xfrm_aevent_id);
2361 rtasize = XFRM_PAYLOAD(out, struct xfrm_aevent_id);
2362 while(RTA_OK(rta, rtasize))
2363 {
2364 if (rta->rta_type == XFRMA_REPLAY_VAL)
2365 {
2366 memcpy(replay, RTA_DATA(rta), rta->rta_len);
2367 free(out);
2368 return SUCCESS;
2369 }
2370 rta = RTA_NEXT(rta, rtasize);
2371 }
2372
2373 DBG1(DBG_KNL, "unable to query replay state from SAD entry with SPI %.8x",
2374 ntohl(spi));
2375 free(out);
2376 return FAILED;
2377 }
2378
2379 /**
2380 * Implementation of kernel_interface_t.update_sa.
2381 */
2382 static status_t update_sa(private_kernel_interface_t *this,
2383 u_int32_t spi, protocol_id_t protocol,
2384 host_t *src, host_t *dst,
2385 host_t *new_src, host_t *new_dst, bool encap)
2386 {
2387 unsigned char request[BUFFER_SIZE], *pos;
2388 struct nlmsghdr *hdr, *out = NULL;
2389 struct xfrm_usersa_id *sa_id;
2390 struct xfrm_usersa_info *out_sa = NULL, *sa;
2391 size_t len;
2392 struct rtattr *rta;
2393 size_t rtasize;
2394 struct xfrm_encap_tmpl* tmpl = NULL;
2395 bool got_replay_state;
2396 struct xfrm_replay_state replay;
2397
2398 memset(&request, 0, sizeof(request));
2399
2400 DBG2(DBG_KNL, "querying SAD entry with SPI %.8x for update", ntohl(spi));
2401
2402 /* query the exisiting SA first */
2403 hdr = (struct nlmsghdr*)request;
2404 hdr->nlmsg_flags = NLM_F_REQUEST;
2405 hdr->nlmsg_type = XFRM_MSG_GETSA;
2406 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_id));
2407
2408 sa_id = (struct xfrm_usersa_id*)NLMSG_DATA(hdr);
2409 host2xfrm(dst, &sa_id->daddr);
2410 sa_id->spi = spi;
2411 sa_id->proto = proto_ike2kernel(protocol);
2412 sa_id->family = dst->get_family(dst);
2413
2414 if (netlink_send(this, this->socket_xfrm, hdr, &out, &len) == SUCCESS)
2415 {
2416 hdr = out;
2417 while (NLMSG_OK(hdr, len))
2418 {
2419 switch (hdr->nlmsg_type)
2420 {
2421 case XFRM_MSG_NEWSA:
2422 {
2423 out_sa = NLMSG_DATA(hdr);
2424 break;
2425 }
2426 case NLMSG_ERROR:
2427 {
2428 struct nlmsgerr *err = NLMSG_DATA(hdr);
2429 DBG1(DBG_KNL, "querying SAD entry failed: %s (%d)",
2430 strerror(-err->error), -err->error);
2431 break;
2432 }
2433 default:
2434 hdr = NLMSG_NEXT(hdr, len);
2435 continue;
2436 case NLMSG_DONE:
2437 break;
2438 }
2439 break;
2440 }
2441 }
2442 if (out_sa == NULL)
2443 {
2444 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x", ntohl(spi));
2445 free(out);
2446 return FAILED;
2447 }
2448
2449 /* try to get the replay state */
2450 got_replay_state = (get_replay_state(
2451 this, spi, protocol, dst, &replay) == SUCCESS);
2452
2453 /* delete the old SA */
2454 if (this->public.del_sa(&this->public, dst, spi, protocol) != SUCCESS)
2455 {
2456 DBG1(DBG_KNL, "unable to delete old SAD entry with SPI %.8x", ntohl(spi));
2457 free(out);
2458 return FAILED;
2459 }
2460
2461 DBG2(DBG_KNL, "updating SAD entry with SPI %.8x from %#H..%#H to %#H..%#H",
2462 ntohl(spi), src, dst, new_src, new_dst);
2463
2464 /* copy over the SA from out to request */
2465 hdr = (struct nlmsghdr*)request;
2466 memcpy(hdr, out, min(out->nlmsg_len, sizeof(request)));
2467 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2468 hdr->nlmsg_type = XFRM_MSG_NEWSA;
2469 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_info));
2470 sa = NLMSG_DATA(hdr);
2471 sa->family = new_dst->get_family(new_dst);
2472
2473 if (!src->ip_equals(src, new_src))
2474 {
2475 host2xfrm(new_src, &sa->saddr);
2476 }
2477 if (!dst->ip_equals(dst, new_dst))
2478 {
2479 host2xfrm(new_dst, &sa->id.daddr);
2480 }
2481
2482 rta = XFRM_RTA(out, struct xfrm_usersa_info);
2483 rtasize = XFRM_PAYLOAD(out, struct xfrm_usersa_info);
2484 pos = (u_char*)XFRM_RTA(hdr, struct xfrm_usersa_info);
2485 while(RTA_OK(rta, rtasize))
2486 {
2487 /* copy all attributes, but not XFRMA_ENCAP if we are disabling it */
2488 if (rta->rta_type != XFRMA_ENCAP || encap)
2489 {
2490 if (rta->rta_type == XFRMA_ENCAP)
2491 { /* update encap tmpl */
2492 tmpl = (struct xfrm_encap_tmpl*)RTA_DATA(rta);
2493 tmpl->encap_sport = ntohs(new_src->get_port(new_src));
2494 tmpl->encap_dport = ntohs(new_dst->get_port(new_dst));
2495 }
2496 memcpy(pos, rta, rta->rta_len);
2497 pos += RTA_ALIGN(rta->rta_len);
2498 hdr->nlmsg_len += RTA_ALIGN(rta->rta_len);
2499 }
2500 rta = RTA_NEXT(rta, rtasize);
2501 }
2502
2503 rta = (struct rtattr*)pos;
2504 if (tmpl == NULL && encap)
2505 { /* add tmpl if we are enabling it */
2506 rta->rta_type = XFRMA_ENCAP;
2507 rta->rta_len = RTA_LENGTH(sizeof(struct xfrm_encap_tmpl));
2508
2509 hdr->nlmsg_len += rta->rta_len;
2510 if (hdr->nlmsg_len > sizeof(request))
2511 {
2512 return FAILED;
2513 }
2514
2515 tmpl = (struct xfrm_encap_tmpl*)RTA_DATA(rta);
2516 tmpl->encap_type = UDP_ENCAP_ESPINUDP;
2517 tmpl->encap_sport = ntohs(new_src->get_port(new_src));
2518 tmpl->encap_dport = ntohs(new_dst->get_port(new_dst));
2519 memset(&tmpl->encap_oa, 0, sizeof (xfrm_address_t));
2520
2521 rta = XFRM_RTA_NEXT(rta);
2522 }
2523
2524 if (got_replay_state)
2525 { /* copy the replay data if available */
2526 rta->rta_type = XFRMA_REPLAY_VAL;
2527 rta->rta_len = RTA_LENGTH(sizeof(struct xfrm_replay_state));
2528
2529 hdr->nlmsg_len += rta->rta_len;
2530 if (hdr->nlmsg_len > sizeof(request))
2531 {
2532 return FAILED;
2533 }
2534 memcpy(RTA_DATA(rta), &replay, sizeof(replay));
2535
2536 rta = XFRM_RTA_NEXT(rta);
2537 }
2538
2539 if (netlink_send_ack(this, this->socket_xfrm, hdr) != SUCCESS)
2540 {
2541 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x", ntohl(spi));
2542 free(out);
2543 return FAILED;
2544 }
2545 free(out);
2546
2547 return SUCCESS;
2548 }
2549
2550 /**
2551 * Implementation of kernel_interface_t.query_sa.
2552 */
2553 static status_t query_sa(private_kernel_interface_t *this, host_t *dst,
2554 u_int32_t spi, protocol_id_t protocol,
2555 u_int32_t *use_time)
2556 {
2557 unsigned char request[BUFFER_SIZE];
2558 struct nlmsghdr *out = NULL, *hdr;
2559 struct xfrm_usersa_id *sa_id;
2560 struct xfrm_usersa_info *sa = NULL;
2561 size_t len;
2562
2563 DBG2(DBG_KNL, "querying SAD entry with SPI %.8x", ntohl(spi));
2564 memset(&request, 0, sizeof(request));
2565
2566 hdr = (struct nlmsghdr*)request;
2567 hdr->nlmsg_flags = NLM_F_REQUEST;
2568 hdr->nlmsg_type = XFRM_MSG_GETSA;
2569 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_info));
2570
2571 sa_id = (struct xfrm_usersa_id*)NLMSG_DATA(hdr);
2572 host2xfrm(dst, &sa_id->daddr);
2573 sa_id->spi = spi;
2574 sa_id->proto = proto_ike2kernel(protocol);
2575 sa_id->family = dst->get_family(dst);
2576
2577 if (netlink_send(this, this->socket_xfrm, hdr, &out, &len) == SUCCESS)
2578 {
2579 hdr = out;
2580 while (NLMSG_OK(hdr, len))
2581 {
2582 switch (hdr->nlmsg_type)
2583 {
2584 case XFRM_MSG_NEWSA:
2585 {
2586 sa = NLMSG_DATA(hdr);
2587 break;
2588 }
2589 case NLMSG_ERROR:
2590 {
2591 struct nlmsgerr *err = NLMSG_DATA(hdr);
2592 DBG1(DBG_KNL, "querying SAD entry failed: %s (%d)",
2593 strerror(-err->error), -err->error);
2594 break;
2595 }
2596 default:
2597 hdr = NLMSG_NEXT(hdr, len);
2598 continue;
2599 case NLMSG_DONE:
2600 break;
2601 }
2602 break;
2603 }
2604 }
2605
2606 if (sa == NULL)
2607 {
2608 DBG1(DBG_KNL, "unable to query SAD entry with SPI %.8x", ntohl(spi));
2609 free(out);
2610 return FAILED;
2611 }
2612
2613 *use_time = sa->curlft.use_time;
2614 free (out);
2615 return SUCCESS;
2616 }
2617
2618 /**
2619 * Implementation of kernel_interface_t.del_sa.
2620 */
2621 static status_t del_sa(private_kernel_interface_t *this, host_t *dst,
2622 u_int32_t spi, protocol_id_t protocol)
2623 {
2624 unsigned char request[BUFFER_SIZE];
2625 struct nlmsghdr *hdr;
2626 struct xfrm_usersa_id *sa_id;
2627
2628 memset(&request, 0, sizeof(request));
2629
2630 DBG2(DBG_KNL, "deleting SAD entry with SPI %.8x", ntohl(spi));
2631
2632 hdr = (struct nlmsghdr*)request;
2633 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2634 hdr->nlmsg_type = XFRM_MSG_DELSA;
2635 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_id));
2636
2637 sa_id = (struct xfrm_usersa_id*)NLMSG_DATA(hdr);
2638 host2xfrm(dst, &sa_id->daddr);
2639 sa_id->spi = spi;
2640 sa_id->proto = proto_ike2kernel(protocol);
2641 sa_id->family = dst->get_family(dst);
2642
2643 if (netlink_send_ack(this, this->socket_xfrm, hdr) != SUCCESS)
2644 {
2645 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x", ntohl(spi));
2646 return FAILED;
2647 }
2648 DBG2(DBG_KNL, "deleted SAD entry with SPI %.8x", ntohl(spi));
2649 return SUCCESS;
2650 }
2651
2652 /**
2653 * Implementation of kernel_interface_t.add_policy.
2654 */
2655 static status_t add_policy(private_kernel_interface_t *this,
2656 host_t *src, host_t *dst,
2657 traffic_selector_t *src_ts,
2658 traffic_selector_t *dst_ts,
2659 policy_dir_t direction, protocol_id_t protocol,
2660 u_int32_t reqid, bool high_prio, mode_t mode,
2661 u_int16_t ipcomp)
2662 {
2663 iterator_t *iterator;
2664 policy_entry_t *current, *policy;
2665 bool found = FALSE;
2666 unsigned char request[BUFFER_SIZE];
2667 struct xfrm_userpolicy_info *policy_info;
2668 struct nlmsghdr *hdr;
2669
2670 /* create a policy */
2671 policy = malloc_thing(policy_entry_t);
2672 memset(policy, 0, sizeof(policy_entry_t));
2673 policy->sel = ts2selector(src_ts, dst_ts);
2674 policy->direction = direction;
2675
2676 /* find the policy, which matches EXACTLY */
2677 pthread_mutex_lock(&this->mutex);
2678 iterator = this->policies->create_iterator(this->policies, TRUE);
2679 while (iterator->iterate(iterator, (void**)&current))
2680 {
2681 if (memeq(&current->sel, &policy->sel, sizeof(struct xfrm_selector)) &&
2682 policy->direction == current->direction)
2683 {
2684 /* use existing policy */
2685 current->refcount++;
2686 DBG2(DBG_KNL, "policy %R === %R %N already exists, increasing "
2687 "refcount", src_ts, dst_ts,
2688 policy_dir_names, direction);
2689 free(policy);
2690 policy = current;
2691 found = TRUE;
2692 break;
2693 }
2694 }
2695 iterator->destroy(iterator);
2696 if (!found)
2697 { /* apply the new one, if we have no such policy */
2698 this->policies->insert_last(this->policies, policy);
2699 policy->refcount = 1;
2700 }
2701
2702 DBG2(DBG_KNL, "adding policy %R === %R %N", src_ts, dst_ts,
2703 policy_dir_names, direction);
2704
2705 memset(&request, 0, sizeof(request));
2706 hdr = (struct nlmsghdr*)request;
2707 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2708 hdr->nlmsg_type = found ? XFRM_MSG_UPDPOLICY : XFRM_MSG_NEWPOLICY;
2709 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_info));
2710
2711 policy_info = (struct xfrm_userpolicy_info*)NLMSG_DATA(hdr);
2712 policy_info->sel = policy->sel;
2713 policy_info->dir = policy->direction;
2714 /* calculate priority based on source selector size, small size = high prio */
2715 policy_info->priority = high_prio ? PRIO_HIGH : PRIO_LOW;
2716 policy_info->priority -= policy->sel.prefixlen_s * 10;
2717 policy_info->priority -= policy->sel.proto ? 2 : 0;
2718 policy_info->priority -= policy->sel.sport_mask ? 1 : 0;
2719 policy_info->action = XFRM_POLICY_ALLOW;
2720 policy_info->share = XFRM_SHARE_ANY;
2721 pthread_mutex_unlock(&this->mutex);
2722
2723 /* policies don't expire */
2724 policy_info->lft.soft_byte_limit = XFRM_INF;
2725 policy_info->lft.soft_packet_limit = XFRM_INF;
2726 policy_info->lft.hard_byte_limit = XFRM_INF;
2727 policy_info->lft.hard_packet_limit = XFRM_INF;
2728 policy_info->lft.soft_add_expires_seconds = 0;
2729 policy_info->lft.hard_add_expires_seconds = 0;
2730 policy_info->lft.soft_use_expires_seconds = 0;
2731 policy_info->lft.hard_use_expires_seconds = 0;
2732
2733 struct rtattr *rthdr = XFRM_RTA(hdr, struct xfrm_userpolicy_info);
2734 rthdr->rta_type = XFRMA_TMPL;
2735 rthdr->rta_len = RTA_LENGTH(sizeof(struct xfrm_user_tmpl));
2736
2737 hdr->nlmsg_len += rthdr->rta_len;
2738 if (hdr->nlmsg_len > sizeof(request))
2739 {
2740 return FAILED;
2741 }
2742
2743 struct xfrm_user_tmpl *tmpl = (struct xfrm_user_tmpl*)RTA_DATA(rthdr);
2744
2745 if (ipcomp != IPCOMP_NONE)
2746 {
2747 tmpl->reqid = reqid;
2748 tmpl->id.proto = IPPROTO_COMP;
2749 tmpl->aalgos = tmpl->ealgos = tmpl->calgos = ~0;
2750 tmpl->mode = mode;
2751 tmpl->optional = direction != POLICY_OUT;
2752 tmpl->family = src->get_family(src);
2753
2754 host2xfrm(src, &tmpl->saddr);
2755 host2xfrm(dst, &tmpl->id.daddr);
2756
2757 /* add an additional xfrm_user_tmpl */
2758 rthdr->rta_len += RTA_LENGTH(sizeof(struct xfrm_user_tmpl));
2759 hdr->nlmsg_len += RTA_LENGTH(sizeof(struct xfrm_user_tmpl));
2760 if (hdr->nlmsg_len > sizeof(request))
2761 {
2762 return FAILED;
2763 }
2764
2765 tmpl++;
2766 }
2767
2768 tmpl->reqid = reqid;
2769 tmpl->id.proto = proto_ike2kernel(protocol);
2770 tmpl->aalgos = tmpl->ealgos = tmpl->calgos = ~0;
2771 tmpl->mode = mode;
2772 tmpl->family = src->get_family(src);
2773
2774 host2xfrm(src, &tmpl->saddr);
2775 host2xfrm(dst, &tmpl->id.daddr);
2776
2777 if (netlink_send_ack(this, this->socket_xfrm, hdr) != SUCCESS)
2778 {
2779 DBG1(DBG_KNL, "unable to add policy %R === %R %N", src_ts, dst_ts,
2780 policy_dir_names, direction);
2781 return FAILED;
2782 }
2783
2784 /* install a route, if:
2785 * - we are NOT updating a policy
2786 * - this is a forward policy (to just get one for each child)
2787 * - we are in tunnel mode
2788 * - we are not using IPv6 (does not work correctly yet!)
2789 * - routing is not disabled via strongswan.conf
2790 */
2791 if (policy->route == NULL && direction == POLICY_FWD &&
2792 mode != MODE_TRANSPORT && src->get_family(src) != AF_INET6 &&
2793 this->install_routes)
2794 {
2795 policy->route = malloc_thing(route_entry_t);
2796 if (get_address_by_ts(this, dst_ts, &policy->route->src_ip) == SUCCESS)
2797 {
2798 /* get the nexthop to src (src as we are in POLICY_FWD).*/
2799 policy->route->gateway = get_route(this, src, TRUE);
2800 policy->route->if_index = get_interface_index(this, dst);
2801 policy->route->dst_net = chunk_alloc(
2802 policy->sel.family == AF_INET ? 4 : 16);
2803 memcpy(policy->route->dst_net.ptr, &policy->sel.saddr,
2804 policy->route->dst_net.len);
2805 policy->route->prefixlen = policy->sel.prefixlen_s;
2806
2807 switch (manage_srcroute(this, RTM_NEWROUTE,
2808 NLM_F_CREATE | NLM_F_EXCL, policy->route))
2809 {
2810 default:
2811 DBG1(DBG_KNL, "unable to install source route for %H",
2812 policy->route->src_ip);
2813 /* FALL */
2814 case ALREADY_DONE:
2815 /* route exists, do not uninstall */
2816 route_entry_destroy(policy->route);
2817 policy->route = NULL;
2818 break;
2819 case SUCCESS:
2820 break;
2821 }
2822 }
2823 else
2824 {
2825 free(policy->route);
2826 policy->route = NULL;
2827 }
2828 }
2829
2830 return SUCCESS;
2831 }
2832
2833 /**
2834 * Implementation of kernel_interface_t.query_policy.
2835 */
2836 static status_t query_policy(private_kernel_interface_t *this,
2837 traffic_selector_t *src_ts,
2838 traffic_selector_t *dst_ts,
2839 policy_dir_t direction, u_int32_t *use_time)
2840 {
2841 unsigned char request[BUFFER_SIZE];
2842 struct nlmsghdr *out = NULL, *hdr;
2843 struct xfrm_userpolicy_id *policy_id;
2844 struct xfrm_userpolicy_info *policy = NULL;
2845 size_t len;
2846
2847 memset(&request, 0, sizeof(request));
2848
2849 DBG2(DBG_KNL, "querying policy %R === %R %N", src_ts, dst_ts,
2850 policy_dir_names, direction);
2851
2852 hdr = (struct nlmsghdr*)request;
2853 hdr->nlmsg_flags = NLM_F_REQUEST;
2854 hdr->nlmsg_type = XFRM_MSG_GETPOLICY;
2855 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_id));
2856
2857 policy_id = (struct xfrm_userpolicy_id*)NLMSG_DATA(hdr);
2858 policy_id->sel = ts2selector(src_ts, dst_ts);
2859 policy_id->dir = direction;
2860
2861 if (netlink_send(this, this->socket_xfrm, hdr, &out, &len) == SUCCESS)
2862 {
2863 hdr = out;
2864 while (NLMSG_OK(hdr, len))
2865 {
2866 switch (hdr->nlmsg_type)
2867 {
2868 case XFRM_MSG_NEWPOLICY:
2869 {
2870 policy = (struct xfrm_userpolicy_info*)NLMSG_DATA(hdr);
2871 break;
2872 }
2873 case NLMSG_ERROR:
2874 {
2875 struct nlmsgerr *err = NLMSG_DATA(hdr);
2876 DBG1(DBG_KNL, "querying policy failed: %s (%d)",
2877 strerror(-err->error), -err->error);
2878 break;
2879 }
2880 default:
2881 hdr = NLMSG_NEXT(hdr, len);
2882 continue;
2883 case NLMSG_DONE:
2884 break;
2885 }
2886 break;
2887 }
2888 }
2889
2890 if (policy == NULL)
2891 {
2892 DBG2(DBG_KNL, "unable to query policy %R === %R %N", src_ts, dst_ts,
2893 policy_dir_names, direction);
2894 free(out);
2895 return FAILED;
2896 }
2897 *use_time = (time_t)policy->curlft.use_time;
2898
2899 free(out);
2900 return SUCCESS;
2901 }
2902
2903 /**
2904 * Implementation of kernel_interface_t.del_policy.
2905 */
2906 static status_t del_policy(private_kernel_interface_t *this,
2907 traffic_selector_t *src_ts,
2908 traffic_selector_t *dst_ts,
2909 policy_dir_t direction)
2910 {
2911 policy_entry_t *current, policy, *to_delete = NULL;
2912 route_entry_t *route;
2913 unsigned char request[BUFFER_SIZE];
2914 struct nlmsghdr *hdr;
2915 struct xfrm_userpolicy_id *policy_id;
2916 iterator_t *iterator;
2917
2918 DBG2(DBG_KNL, "deleting policy %R === %R %N", src_ts, dst_ts,
2919 policy_dir_names, direction);
2920
2921 /* create a policy */
2922 memset(&policy, 0, sizeof(policy_entry_t));
2923 policy.sel = ts2selector(src_ts, dst_ts);
2924 policy.direction = direction;
2925
2926 /* find the policy */
2927 iterator = this->policies->create_iterator_locked(this->policies, &this->mutex);
2928 while (iterator->iterate(iterator, (void**)&current))
2929 {
2930 if (memcmp(&current->sel, &policy.sel, sizeof(struct xfrm_selector)) == 0 &&
2931 policy.direction == current->direction)
2932 {
2933 to_delete = current;
2934 if (--to_delete->refcount > 0)
2935 {
2936 /* is used by more SAs, keep in kernel */
2937 DBG2(DBG_KNL, "policy still used by another CHILD_SA, not removed");
2938 iterator->destroy(iterator);
2939 return SUCCESS;
2940 }
2941 /* remove if last reference */
2942 iterator->remove(iterator);
2943 break;
2944 }
2945 }
2946 iterator->destroy(iterator);
2947 if (!to_delete)
2948 {
2949 DBG1(DBG_KNL, "deleting policy %R === %R %N failed, not found", src_ts,
2950 dst_ts, policy_dir_names, direction);
2951 return NOT_FOUND;
2952 }
2953
2954 memset(&request, 0, sizeof(request));
2955
2956 hdr = (struct nlmsghdr*)request;
2957 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2958 hdr->nlmsg_type = XFRM_MSG_DELPOLICY;
2959 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_id));
2960
2961 policy_id = (struct xfrm_userpolicy_id*)NLMSG_DATA(hdr);
2962 policy_id->sel = to_delete->sel;
2963 policy_id->dir = direction;
2964
2965 route = to_delete->route;
2966 free(to_delete);
2967
2968 if (netlink_send_ack(this, this->socket_xfrm, hdr) != SUCCESS)
2969 {
2970 DBG1(DBG_KNL, "unable to delete policy %R === %R %N", src_ts, dst_ts,
2971 policy_dir_names, direction);
2972 return FAILED;
2973 }
2974
2975 if (route)
2976 {
2977 if (manage_srcroute(this, RTM_DELROUTE, 0, route) != SUCCESS)
2978 {
2979 DBG1(DBG_KNL, "error uninstalling route installed with "
2980 "policy %R === %R %N", src_ts, dst_ts,
2981 policy_dir_names, direction);
2982 }
2983 route_entry_destroy(route);
2984 }
2985 return SUCCESS;
2986 }
2987
2988 /**
2989 * Implementation of kernel_interface_t.destroy.
2990 */
2991 static void destroy(private_kernel_interface_t *this)
2992 {
2993 if (this->routing_table)
2994 {
2995 manage_rule(this, RTM_DELRULE, this->routing_table,
2996 this->routing_table_prio);
2997 }
2998
2999 this->job->cancel(this->job);
3000 close(this->socket_xfrm_events);
3001 close(this->socket_xfrm);
3002 close(this->socket_rt_events);
3003 close(this->socket_rt);
3004 this->policies->destroy(this->policies);
3005 this->ifaces->destroy_function(this->ifaces, (void*)iface_entry_destroy);
3006 free(this);
3007 }
3008
3009 /*
3010 * Described in header.
3011 */
3012 kernel_interface_t *kernel_interface_create()
3013 {
3014 private_kernel_interface_t *this = malloc_thing(private_kernel_interface_t);
3015 struct sockaddr_nl addr;
3016
3017 /* public functions */
3018 this->public.get_spi = (status_t(*)(kernel_interface_t*,host_t*,host_t*,protocol_id_t,u_int32_t,u_int32_t*))get_spi;
3019 this->public.get_cpi = (status_t(*)(kernel_interface_t*,host_t*,host_t*,u_int32_t,u_int16_t*))get_cpi;
3020 this->public.add_sa = (status_t(*)(kernel_interface_t *,host_t*,host_t*,u_int32_t,protocol_id_t,u_int32_t,u_int64_t,u_int64_t,u_int16_t,u_int16_t,u_int16_t,u_int16_t,prf_plus_t*,mode_t,u_int16_t,bool,bool))add_sa;
3021 this->public.update_sa = (status_t(*)(kernel_interface_t*,u_int32_t,protocol_id_t,host_t*,host_t*,host_t*,host_t*,bool