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