]> git.ipfire.org Git - thirdparty/strongswan.git/blob - src/charon/threads/kernel_interface.c
4a70d2ecf75e8919a3f9167433c18c632cc602d8
[thirdparty/strongswan.git] / src / charon / threads / 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 <queues/jobs/delete_child_sa_job.h>
49 #include <queues/jobs/rekey_child_sa_job.h>
50 #include <queues/jobs/acquire_job.h>
51
52 /** kernel level protocol identifiers */
53 #define KERNEL_ESP 50
54 #define KERNEL_AH 51
55
56 /** default priority of installed policies */
57 #define PRIO_LOW 3000
58 #define PRIO_HIGH 2000
59
60 #define BUFFER_SIZE 1024
61
62 /**
63 * returns a pointer to the first rtattr following the nlmsghdr *nlh and the
64 * 'usual' netlink data x like 'struct xfrm_usersa_info'
65 */
66 #define XFRM_RTA(nlh, x) ((struct rtattr*)(NLMSG_DATA(nlh) + NLMSG_ALIGN(sizeof(x))))
67 /**
68 * returns a pointer to the next rtattr following rta.
69 * !!! do not use this to parse messages. use RTA_NEXT and RTA_OK instead !!!
70 */
71 #define XFRM_RTA_NEXT(rta) ((struct rtattr*)(((char*)(rta)) + RTA_ALIGN((rta)->rta_len)))
72 /**
73 * returns the total size of attached rta data
74 * (after 'usual' netlink data x like 'struct xfrm_usersa_info')
75 */
76 #define XFRM_PAYLOAD(nlh, x) NLMSG_PAYLOAD(nlh, sizeof(x))
77
78 typedef struct kernel_algorithm_t kernel_algorithm_t;
79
80 /**
81 * Mapping from the algorithms defined in IKEv2 to
82 * kernel level algorithm names and their key length
83 */
84 struct kernel_algorithm_t {
85 /**
86 * Identifier specified in IKEv2
87 */
88 int ikev2_id;
89
90 /**
91 * Name of the algorithm, as used as kernel identifier
92 */
93 char *name;
94
95 /**
96 * Key length in bits, if fixed size
97 */
98 u_int key_size;
99 };
100 #define END_OF_LIST -1
101
102 /**
103 * Algorithms for encryption
104 */
105 kernel_algorithm_t encryption_algs[] = {
106 /* {ENCR_DES_IV64, "***", 0}, */
107 {ENCR_DES, "des", 64},
108 {ENCR_3DES, "des3_ede", 192},
109 /* {ENCR_RC5, "***", 0}, */
110 /* {ENCR_IDEA, "***", 0}, */
111 {ENCR_CAST, "cast128", 0},
112 {ENCR_BLOWFISH, "blowfish", 0},
113 /* {ENCR_3IDEA, "***", 0}, */
114 /* {ENCR_DES_IV32, "***", 0}, */
115 {ENCR_NULL, "cipher_null", 0},
116 {ENCR_AES_CBC, "aes", 0},
117 /* {ENCR_AES_CTR, "***", 0}, */
118 {END_OF_LIST, NULL, 0},
119 };
120
121 /**
122 * Algorithms for integrity protection
123 */
124 kernel_algorithm_t integrity_algs[] = {
125 {AUTH_HMAC_MD5_96, "md5", 128},
126 {AUTH_HMAC_SHA1_96, "sha1", 160},
127 {AUTH_HMAC_SHA2_256_128, "sha256", 256},
128 {AUTH_HMAC_SHA2_384_192, "sha384", 384},
129 {AUTH_HMAC_SHA2_512_256, "sha512", 512},
130 /* {AUTH_DES_MAC, "***", 0}, */
131 /* {AUTH_KPDK_MD5, "***", 0}, */
132 /* {AUTH_AES_XCBC_96, "***", 0}, */
133 {END_OF_LIST, NULL, 0},
134 };
135
136 /**
137 * Look up a kernel algorithm name and its key size
138 */
139 char* lookup_algorithm(kernel_algorithm_t *kernel_algo,
140 algorithm_t *ikev2_algo, u_int *key_size)
141 {
142 while (kernel_algo->ikev2_id != END_OF_LIST)
143 {
144 if (ikev2_algo->algorithm == kernel_algo->ikev2_id)
145 {
146 /* match, evaluate key length */
147 if (ikev2_algo->key_size)
148 { /* variable length */
149 *key_size = ikev2_algo->key_size;
150 }
151 else
152 { /* fixed length */
153 *key_size = kernel_algo->key_size;
154 }
155 return kernel_algo->name;
156 }
157 kernel_algo++;
158 }
159 return NULL;
160 }
161
162 typedef struct route_entry_t route_entry_t;
163
164 /**
165 * installed routing entry
166 */
167 struct route_entry_t {
168
169 /** Index of the interface the route is bound to */
170 int if_index;
171
172 /** Source ip of the route */
173 host_t *src_ip;
174
175 /** Destination net */
176 chunk_t dst_net;
177
178 /** Destination net prefixlen */
179 u_int8_t prefixlen;
180 };
181
182 /**
183 * destroy an route_entry_t object
184 */
185 static void route_entry_destroy(route_entry_t *this)
186 {
187 this->src_ip->destroy(this->src_ip);
188 chunk_free(&this->dst_net);
189 free(this);
190 }
191
192 typedef struct policy_entry_t policy_entry_t;
193
194 /**
195 * installed kernel policy.
196 */
197 struct policy_entry_t {
198
199 /** direction of this policy: in, out, forward */
200 u_int8_t direction;
201
202 /** reqid of the policy */
203 u_int32_t reqid;
204
205 /** parameters of installed policy */
206 struct xfrm_selector sel;
207
208 /** associated route installed for this policy */
209 route_entry_t *route;
210
211 /** by how many CHILD_SA's this policy is used */
212 u_int refcount;
213 };
214
215 typedef struct vip_entry_t vip_entry_t;
216
217 /**
218 * Installed virtual ip
219 */
220 struct vip_entry_t {
221 /** Index of the interface the ip is bound to */
222 u_int8_t if_index;
223
224 /** The ip address */
225 host_t *ip;
226
227 /** Number of times this IP is used */
228 u_int refcount;
229 };
230
231 /**
232 * destroy a vip_entry_t object
233 */
234 static void vip_entry_destroy(vip_entry_t *this)
235 {
236 this->ip->destroy(this->ip);
237 free(this);
238 }
239
240 typedef struct address_entry_t address_entry_t;
241
242 /**
243 * an address found on the system, containg address and interface info
244 */
245 struct address_entry_t {
246
247 /** address of this entry */
248 host_t *host;
249
250 /** interface index */
251 int ifindex;
252
253 /** name of the index */
254 char ifname[IFNAMSIZ];
255 };
256
257 /**
258 * destroy an address entry
259 */
260 static void address_entry_destroy(address_entry_t *this)
261 {
262 this->host->destroy(this->host);
263 free(this);
264 }
265
266 typedef struct private_kernel_interface_t private_kernel_interface_t;
267
268 /**
269 * Private variables and functions of kernel_interface class.
270 */
271 struct private_kernel_interface_t {
272 /**
273 * Public part of the kernel_interface_t object.
274 */
275 kernel_interface_t public;
276
277 /**
278 * List of installed policies (kernel_entry_t)
279 */
280 linked_list_t *policies;
281
282 /**
283 * Mutex locks access to policies
284 */
285 pthread_mutex_t policies_mutex;
286
287 /**
288 * List of installed virtual IPs. (vip_entry_t)
289 */
290 linked_list_t *vips;
291
292 /**
293 * Mutex to lock access to vips.
294 */
295 pthread_mutex_t vips_mutex;
296
297 /**
298 * netlink xfrm socket to receive acquire and expire events
299 */
300 int socket_xfrm_events;
301
302 /**
303 * Netlink xfrm socket (IPsec)
304 */
305 int socket_xfrm;
306
307 /**
308 * Netlink rt socket (routing)
309 */
310 int socket_rt;
311
312 /**
313 * Thread receiving events from kernel
314 */
315 pthread_t event_thread;
316 };
317
318 /**
319 * convert a host_t to a struct xfrm_address
320 */
321 static void host2xfrm(host_t *host, xfrm_address_t *xfrm)
322 {
323 chunk_t chunk = host->get_address(host);
324 memcpy(xfrm, chunk.ptr, min(chunk.len, sizeof(xfrm_address_t)));
325 }
326
327 /**
328 * convert a traffic selector address range to subnet and its mask.
329 */
330 static void ts2subnet(traffic_selector_t* ts,
331 xfrm_address_t *net, u_int8_t *mask)
332 {
333 /* there is no way to do this cleanly, as the address range may
334 * be anything else but a subnet. We use from_addr as subnet
335 * and try to calculate a usable subnet mask.
336 */
337 int byte, bit;
338 bool found = FALSE;
339 chunk_t from, to;
340 size_t size = (ts->get_type(ts) == TS_IPV4_ADDR_RANGE) ? 4 : 16;
341
342 from = ts->get_from_address(ts);
343 to = ts->get_to_address(ts);
344
345 *mask = (size * 8);
346 /* go trough all bits of the addresses, beginning in the front.
347 * as long as they are equal, the subnet gets larger
348 */
349 for (byte = 0; byte < size; byte++)
350 {
351 for (bit = 7; bit >= 0; bit--)
352 {
353 if ((1<<bit & from.ptr[byte]) != (1<<bit & to.ptr[byte]))
354 {
355 *mask = ((7 - bit) + (byte * 8));
356 found = TRUE;
357 break;
358 }
359 }
360 if (found)
361 {
362 break;
363 }
364 }
365 memcpy(net, from.ptr, from.len);
366 chunk_free(&from);
367 chunk_free(&to);
368 }
369
370 /**
371 * convert a traffic selector port range to port/portmask
372 */
373 static void ts2ports(traffic_selector_t* ts,
374 u_int16_t *port, u_int16_t *mask)
375 {
376 /* linux does not seem to accept complex portmasks. Only
377 * any or a specific port is allowed. We set to any, if we have
378 * a port range, or to a specific, if we have one port only.
379 */
380 u_int16_t from, to;
381
382 from = ts->get_from_port(ts);
383 to = ts->get_to_port(ts);
384
385 if (from == to)
386 {
387 *port = htons(from);
388 *mask = ~0;
389 }
390 else
391 {
392 *port = 0;
393 *mask = 0;
394 }
395 }
396
397 /**
398 * convert a pair of traffic_selectors to a xfrm_selector
399 */
400 static struct xfrm_selector ts2selector(traffic_selector_t *src,
401 traffic_selector_t *dst)
402 {
403 struct xfrm_selector sel;
404
405 memset(&sel, 0, sizeof(sel));
406 sel.family = src->get_type(src) == TS_IPV4_ADDR_RANGE ? AF_INET : AF_INET6;
407 /* src or dest proto may be "any" (0), use more restrictive one */
408 sel.proto = max(src->get_protocol(src), dst->get_protocol(dst));
409 ts2subnet(dst, &sel.daddr, &sel.prefixlen_d);
410 ts2subnet(src, &sel.saddr, &sel.prefixlen_s);
411 ts2ports(dst, &sel.dport, &sel.dport_mask);
412 ts2ports(src, &sel.sport, &sel.sport_mask);
413 sel.ifindex = 0;
414 sel.user = 0;
415
416 return sel;
417 }
418
419 /**
420 * Creates an rtattr and adds it to the netlink message
421 */
422 static void add_attribute(struct nlmsghdr *hdr, int rta_type, chunk_t data,
423 size_t buflen)
424 {
425 struct rtattr *rta;
426
427 if (NLMSG_ALIGN(hdr->nlmsg_len) + RTA_ALIGN(data.len) > buflen)
428 {
429 DBG1(DBG_KNL, "unable to add attribute, buffer too small");
430 return;
431 }
432
433 rta = (struct rtattr*)(((char*)hdr) + NLMSG_ALIGN(hdr->nlmsg_len));
434 rta->rta_type = rta_type;
435 rta->rta_len = RTA_LENGTH(data.len);
436 memcpy(RTA_DATA(rta), data.ptr, data.len);
437 hdr->nlmsg_len = NLMSG_ALIGN(hdr->nlmsg_len) + rta->rta_len;
438 }
439
440 /**
441 * Receives events from kernel
442 */
443 static void receive_events(private_kernel_interface_t *this)
444 {
445 while(TRUE)
446 {
447 unsigned char response[512];
448 struct nlmsghdr *hdr;
449 struct sockaddr_nl addr;
450 socklen_t addr_len = sizeof(addr);
451 int len;
452
453 hdr = (struct nlmsghdr*)response;
454 len = recvfrom(this->socket_xfrm_events, response, sizeof(response),
455 0, (struct sockaddr*)&addr, &addr_len);
456 if (len < 0)
457 {
458 if (errno == EINTR)
459 {
460 /* interrupted, try again */
461 continue;
462 }
463 charon->kill(charon, "unable to receive netlink events");
464 }
465
466 if (!NLMSG_OK(hdr, len))
467 {
468 /* bad netlink message */
469 continue;
470 }
471
472 if (addr.nl_pid != 0)
473 {
474 /* not from kernel. not interested, try another one */
475 continue;
476 }
477
478 /* we handle ACQUIRE and EXPIRE messages directly */
479 if (hdr->nlmsg_type == XFRM_MSG_ACQUIRE)
480 {
481 u_int32_t reqid = 0;
482 job_t *job;
483 struct rtattr *rtattr = XFRM_RTA(hdr, struct xfrm_user_acquire);
484 size_t rtsize = XFRM_PAYLOAD(hdr, struct xfrm_user_tmpl);
485 if (RTA_OK(rtattr, rtsize))
486 {
487 if (rtattr->rta_type == XFRMA_TMPL)
488 {
489 struct xfrm_user_tmpl* tmpl = (struct xfrm_user_tmpl*)RTA_DATA(rtattr);
490 reqid = tmpl->reqid;
491 }
492 }
493 if (reqid == 0)
494 {
495 DBG1(DBG_KNL, "received a XFRM_MSG_ACQUIRE, but no reqid found");
496 }
497 else
498 {
499 DBG2(DBG_KNL, "received a XFRM_MSG_ACQUIRE");
500 DBG1(DBG_KNL, "creating acquire job for CHILD_SA with reqid %d",
501 reqid);
502 job = (job_t*)acquire_job_create(reqid);
503 charon->job_queue->add(charon->job_queue, job);
504 }
505 }
506 else if (hdr->nlmsg_type == XFRM_MSG_EXPIRE)
507 {
508 job_t *job;
509 protocol_id_t protocol;
510 u_int32_t spi, reqid;
511 struct xfrm_user_expire *expire;
512
513 expire = (struct xfrm_user_expire*)NLMSG_DATA(hdr);
514 protocol = expire->state.id.proto == KERNEL_ESP ?
515 PROTO_ESP : PROTO_AH;
516 spi = expire->state.id.spi;
517 reqid = expire->state.reqid;
518
519 DBG2(DBG_KNL, "received a XFRM_MSG_EXPIRE");
520 DBG1(DBG_KNL, "creating %s job for %N CHILD_SA 0x%x (reqid %d)",
521 expire->hard ? "delete" : "rekey", protocol_id_names,
522 protocol, ntohl(spi), reqid);
523 if (expire->hard)
524 {
525 job = (job_t*)delete_child_sa_job_create(reqid, protocol, spi);
526 }
527 else
528 {
529 job = (job_t*)rekey_child_sa_job_create(reqid, protocol, spi);
530 }
531 charon->job_queue->add(charon->job_queue, job);
532 }
533 }
534 }
535
536 /**
537 * send a netlink message and wait for a reply
538 */
539 static status_t netlink_send(int socket, struct nlmsghdr *in,
540 struct nlmsghdr **out, size_t *out_len)
541 {
542 int len, addr_len;
543 struct sockaddr_nl addr;
544 chunk_t result = chunk_empty, tmp;
545 struct nlmsghdr *msg, peek;
546
547 static int seq = 200;
548 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
549
550
551 pthread_mutex_lock(&mutex);
552
553 in->nlmsg_seq = ++seq;
554 in->nlmsg_pid = getpid();
555
556 memset(&addr, 0, sizeof(addr));
557 addr.nl_family = AF_NETLINK;
558 addr.nl_pid = 0;
559 addr.nl_groups = 0;
560
561 while (TRUE)
562 {
563 len = sendto(socket, in, in->nlmsg_len, 0,
564 (struct sockaddr*)&addr, sizeof(addr));
565
566 if (len != in->nlmsg_len)
567 {
568 if (errno == EINTR)
569 {
570 /* interrupted, try again */
571 continue;
572 }
573 pthread_mutex_unlock(&mutex);
574 DBG1(DBG_KNL, "error sending to netlink socket: %m");
575 return FAILED;
576 }
577 break;
578 }
579
580 while (TRUE)
581 {
582 char buf[1024];
583 tmp.len = sizeof(buf);
584 tmp.ptr = buf;
585 msg = (struct nlmsghdr*)tmp.ptr;
586
587 memset(&addr, 0, sizeof(addr));
588 addr.nl_family = AF_NETLINK;
589 addr.nl_pid = getpid();
590 addr.nl_groups = 0;
591 addr_len = sizeof(addr);
592
593 len = recvfrom(socket, tmp.ptr, tmp.len, 0,
594 (struct sockaddr*)&addr, &addr_len);
595
596 if (len < 0)
597 {
598 if (errno == EINTR)
599 {
600 DBG1(DBG_IKE, "got interrupted");
601 /* interrupted, try again */
602 continue;
603 }
604 DBG1(DBG_IKE, "error reading from netlink socket: %m");
605 pthread_mutex_unlock(&mutex);
606 return FAILED;
607 }
608 if (!NLMSG_OK(msg, len))
609 {
610 DBG1(DBG_IKE, "received corrupted netlink message");
611 pthread_mutex_unlock(&mutex);
612 return FAILED;
613 }
614 if (msg->nlmsg_seq != seq)
615 {
616 DBG1(DBG_IKE, "received invalid netlink sequence number");
617 if (msg->nlmsg_seq < seq)
618 {
619 continue;
620 }
621 pthread_mutex_unlock(&mutex);
622 return FAILED;
623 }
624
625 tmp.len = len;
626 result = chunk_cata("cc", result, tmp);
627
628 /* NLM_F_MULTI flag does not seem to be set correctly, we use sequence
629 * numbers to detect multi header messages */
630 len = recvfrom(socket, &peek, sizeof(peek), MSG_PEEK | MSG_DONTWAIT,
631 (struct sockaddr*)&addr, &addr_len);
632
633 if (len == sizeof(peek) && peek.nlmsg_seq == seq)
634 {
635 /* seems to be multipart */
636 continue;
637 }
638 break;
639 }
640
641 *out_len = result.len;
642 *out = (struct nlmsghdr*)clalloc(result.ptr, result.len);
643
644 pthread_mutex_unlock(&mutex);
645
646 return SUCCESS;
647 }
648
649 /**
650 * send a netlink message and wait for its acknowlegde
651 */
652 static status_t netlink_send_ack(int socket, struct nlmsghdr *in)
653 {
654 struct nlmsghdr *out, *hdr;
655 size_t len;
656
657 if (netlink_send(socket, in, &out, &len) != SUCCESS)
658 {
659 return FAILED;
660 }
661 hdr = out;
662 while (NLMSG_OK(hdr, len))
663 {
664 switch (hdr->nlmsg_type)
665 {
666 case NLMSG_ERROR:
667 {
668 struct nlmsgerr* err = (struct nlmsgerr*)NLMSG_DATA(hdr);
669
670 if (err->error)
671 {
672 DBG1(DBG_KNL, "received netlink error: %s (%d)",
673 strerror(-err->error), -err->error);
674 free(out);
675 return FAILED;
676 }
677 free(out);
678 return SUCCESS;
679 }
680 default:
681 hdr = NLMSG_NEXT(hdr, len);
682 continue;
683 case NLMSG_DONE:
684 break;
685 }
686 break;
687 }
688 DBG1(DBG_KNL, "netlink request not acknowlegded");
689 free(out);
690 return FAILED;
691 }
692
693 /**
694 * Create a list of local addresses.
695 */
696 static linked_list_t *create_address_list(private_kernel_interface_t *this)
697 {
698 char request[BUFFER_SIZE];
699 struct nlmsghdr *out, *hdr;
700 struct rtgenmsg *msg;
701 size_t len;
702 linked_list_t *list;
703
704 DBG2(DBG_IKE, "getting local address list");
705
706 list = linked_list_create();
707
708 memset(&request, 0, sizeof(request));
709
710 hdr = (struct nlmsghdr*)&request;
711 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg));
712 hdr->nlmsg_type = RTM_GETADDR;
713 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_MATCH | NLM_F_ROOT;
714 msg = (struct rtgenmsg*)NLMSG_DATA(hdr);
715 msg->rtgen_family = AF_UNSPEC;
716
717 if (netlink_send(this->socket_rt, hdr, &out, &len) == SUCCESS)
718 {
719 hdr = out;
720 while (NLMSG_OK(hdr, len))
721 {
722 switch (hdr->nlmsg_type)
723 {
724 case RTM_NEWADDR:
725 {
726 struct ifaddrmsg* msg = (struct ifaddrmsg*)(NLMSG_DATA(hdr));
727 struct rtattr *rta = IFA_RTA(msg);
728 size_t rtasize = IFA_PAYLOAD (hdr);
729 host_t *host = NULL;
730 char *name = NULL;
731 chunk_t local = chunk_empty, address = chunk_empty;
732
733 while(RTA_OK(rta, rtasize))
734 {
735 switch (rta->rta_type)
736 {
737 case IFA_LOCAL:
738 local.ptr = RTA_DATA(rta);
739 local.len = RTA_PAYLOAD(rta);
740 break;
741 case IFA_ADDRESS:
742 address.ptr = RTA_DATA(rta);
743 address.len = RTA_PAYLOAD(rta);
744 break;
745 case IFA_LABEL:
746 name = RTA_DATA(rta);
747 break;
748 }
749 rta = RTA_NEXT(rta, rtasize);
750 }
751
752 /* For PPP interfaces, we need the IFA_LOCAL address,
753 * IFA_ADDRESS is the peers address. But IFA_LOCAL is
754 * not included in all cases, so fallback to IFA_ADDRESS. */
755 if (local.ptr)
756 {
757 host = host_create_from_chunk(msg->ifa_family, local, 0);
758 }
759 else if (address.ptr)
760 {
761 host = host_create_from_chunk(msg->ifa_family, address, 0);
762 }
763
764 if (host)
765 {
766 address_entry_t *entry;
767
768 entry = malloc_thing(address_entry_t);
769 entry->host = host;
770 entry->ifindex = msg->ifa_index;
771 if (name)
772 {
773 memcpy(entry->ifname, name, IFNAMSIZ);
774 }
775 else
776 {
777 strcpy(entry->ifname, "(unknown)");
778 }
779 list->insert_last(list, entry);
780 }
781 hdr = NLMSG_NEXT(hdr, len);
782 continue;
783 }
784 default:
785 hdr = NLMSG_NEXT(hdr, len);
786 continue;
787 case NLMSG_DONE:
788 break;
789 }
790 break;
791 }
792 free(out);
793 }
794 else
795 {
796 DBG1(DBG_IKE, "unable to get local address list");
797 }
798
799 return list;
800 }
801
802 /**
803 * Implements kernel_interface_t.create_address_list.
804 */
805 static linked_list_t *create_address_list_public(private_kernel_interface_t *this)
806 {
807 linked_list_t *result, *list;
808 address_entry_t *entry;
809
810 result = linked_list_create();
811 list = create_address_list(this);
812 while (list->remove_last(list, (void**)&entry) == SUCCESS)
813 {
814 result->insert_last(result, entry->host);
815 free(entry);
816 }
817 list->destroy(list);
818
819 return result;
820 }
821
822 /**
823 * implementation of kernel_interface_t.get_interface_name
824 */
825 static char *get_interface_name(private_kernel_interface_t *this, host_t* ip)
826 {
827 linked_list_t *list;
828 address_entry_t *entry;
829 char *name = NULL;
830
831 DBG2(DBG_IKE, "getting interface name for %H", ip);
832
833 list = create_address_list(this);
834 while (!name && list->remove_last(list, (void**)&entry) == SUCCESS)
835 {
836 if (ip->ip_equals(ip, entry->host))
837 {
838 name = strdup(entry->ifname);
839 }
840 address_entry_destroy(entry);
841 }
842 list->destroy_function(list, (void*)address_entry_destroy);
843
844 if (name)
845 {
846 DBG2(DBG_IKE, "%H is on interface %s", ip, name);
847 }
848 else
849 {
850 DBG2(DBG_IKE, "%H is not a local address", ip);
851 }
852 return name;
853 }
854
855 /**
856 * Tries to find an ip address of a local interface that is included in the
857 * supplied traffic selector.
858 */
859 static status_t get_address_by_ts(private_kernel_interface_t *this,
860 traffic_selector_t *ts, host_t **ip)
861 {
862 address_entry_t *entry;
863 host_t *host;
864 int family;
865 linked_list_t *list;
866 bool found = FALSE;
867
868 DBG2(DBG_IKE, "getting a local address in traffic selector %R", ts);
869
870 /* if we have a family which includes localhost, we do not
871 * search for an IP, we use the default */
872 family = ts->get_type(ts) == TS_IPV4_ADDR_RANGE ? AF_INET : AF_INET6;
873
874 if (family == AF_INET)
875 {
876 host = host_create_from_string("127.0.0.1", 0);
877 }
878 else
879 {
880 host = host_create_from_string("::1", 0);
881 }
882
883 if (ts->includes(ts, host))
884 {
885 *ip = host_create_any(family);
886 host->destroy(host);
887 DBG2(DBG_IKE, "using host %H", *ip);
888 return SUCCESS;
889 }
890 host->destroy(host);
891
892 list = create_address_list(this);
893 while (!found && list->remove_last(list, (void**)&entry) == SUCCESS)
894 {
895 if (ts->includes(ts, entry->host))
896 {
897 found = TRUE;
898 *ip = entry->host->clone(entry->host);
899 }
900 address_entry_destroy(entry);
901 }
902 list->destroy_function(list, (void*)address_entry_destroy);
903
904 if (!found)
905 {
906 DBG1(DBG_IKE, "no local address found in traffic selector %R", ts);
907 return FAILED;
908 }
909 DBG2(DBG_IKE, "using host %H", *ip);
910 return SUCCESS;
911 }
912
913 /**
914 * get the interface of a local address
915 */
916 static int get_interface_index(private_kernel_interface_t *this, host_t* ip)
917 {
918 linked_list_t *list;
919 address_entry_t *entry;
920 int ifindex = 0;
921
922 DBG2(DBG_IKE, "getting iface for %H", ip);
923
924 list = create_address_list(this);
925 while (!ifindex && list->remove_last(list, (void**)&entry) == SUCCESS)
926 {
927 if (ip->ip_equals(ip, entry->host))
928 {
929 ifindex = entry->ifindex;
930 }
931 address_entry_destroy(entry);
932 }
933 list->destroy_function(list, (void*)address_entry_destroy);
934
935 if (ifindex == 0)
936 {
937 DBG1(DBG_IKE, "unable to get interface for %H", ip);
938 }
939 return ifindex;
940 }
941
942 /**
943 * Manages the creation and deletion of ip addresses on an interface.
944 * By setting the appropriate nlmsg_type, the ip will be set or unset.
945 */
946 static status_t manage_ipaddr(private_kernel_interface_t *this, int nlmsg_type,
947 int flags, int if_index, host_t *ip)
948 {
949 unsigned char request[BUFFER_SIZE];
950 struct nlmsghdr *hdr;
951 struct ifaddrmsg *msg;
952 chunk_t chunk;
953
954 memset(&request, 0, sizeof(request));
955
956 chunk = ip->get_address(ip);
957
958 hdr = (struct nlmsghdr*)request;
959 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags;
960 hdr->nlmsg_type = nlmsg_type;
961 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrmsg));
962
963 msg = (struct ifaddrmsg*)NLMSG_DATA(hdr);
964 msg->ifa_family = ip->get_family(ip);
965 msg->ifa_flags = 0;
966 msg->ifa_prefixlen = 8 * chunk.len;
967 msg->ifa_scope = RT_SCOPE_UNIVERSE;
968 msg->ifa_index = if_index;
969
970 add_attribute(hdr, IFA_LOCAL, chunk, sizeof(request));
971
972 return netlink_send_ack(this->socket_rt, hdr);
973 }
974
975 /**
976 * Manages source routes in the routing table.
977 * By setting the appropriate nlmsg_type, the route added or r.
978 */
979 static status_t manage_srcroute(private_kernel_interface_t *this, int nlmsg_type,
980 int flags, route_entry_t *route)
981 {
982 unsigned char request[BUFFER_SIZE];
983 struct nlmsghdr *hdr;
984 struct rtmsg *msg;
985 chunk_t chunk;
986
987 /* if route is 0.0.0.0/0, we can't install it, as it would
988 * overwrite the default route. Instead, we add two routes:
989 * 0.0.0.0/1 and 128.0.0.0/1
990 * TODO: use metrics instead */
991 if (route->prefixlen == 0)
992 {
993 route_entry_t half;
994 status_t status;
995
996 half.dst_net = chunk_alloca(route->dst_net.len);
997 memset(half.dst_net.ptr, 0, half.dst_net.len);
998 half.src_ip = route->src_ip;
999 half.if_index = route->if_index;
1000 half.prefixlen = 1;
1001
1002 status = manage_srcroute(this, nlmsg_type, flags, &half);
1003 half.dst_net.ptr[0] |= 0x80;
1004 status = manage_srcroute(this, nlmsg_type, flags, &half);
1005 return status;
1006 }
1007
1008 memset(&request, 0, sizeof(request));
1009
1010 hdr = (struct nlmsghdr*)request;
1011 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags;
1012 hdr->nlmsg_type = nlmsg_type;
1013 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
1014
1015 msg = (struct rtmsg*)NLMSG_DATA(hdr);
1016 msg->rtm_family = route->src_ip->get_family(route->src_ip);
1017 msg->rtm_dst_len = route->prefixlen;
1018 msg->rtm_table = RT_TABLE_MAIN;
1019 msg->rtm_protocol = RTPROT_STATIC;
1020 msg->rtm_type = RTN_UNICAST;
1021 msg->rtm_scope = RT_SCOPE_UNIVERSE;
1022
1023 add_attribute(hdr, RTA_DST, route->dst_net, sizeof(request));
1024 chunk = route->src_ip->get_address(route->src_ip);
1025 add_attribute(hdr, RTA_PREFSRC, chunk, sizeof(request));
1026 chunk.ptr = (char*)&route->if_index;
1027 chunk.len = sizeof(route->if_index);
1028 add_attribute(hdr, RTA_OIF, chunk, sizeof(request));
1029
1030 return netlink_send_ack(this->socket_rt, hdr);
1031 }
1032
1033
1034 /**
1035 * Implementation of kernel_interface_t.add_ip.
1036 */
1037 static status_t add_ip(private_kernel_interface_t *this,
1038 host_t *virtual_ip, host_t *iface_ip)
1039 {
1040 int targetif;
1041 vip_entry_t *listed;
1042 iterator_t *iterator;
1043
1044 DBG2(DBG_KNL, "adding virtual IP %H", virtual_ip);
1045
1046 targetif = get_interface_index(this, iface_ip);
1047 if (targetif == 0)
1048 {
1049 DBG1(DBG_KNL, "unable to add virtual IP %H, no iface found for %H",
1050 virtual_ip, iface_ip);
1051 return FAILED;
1052 }
1053
1054 /* beware of deadlocks (e.g. send/receive packets while holding the lock) */
1055 iterator = this->vips->create_iterator_locked(this->vips, &(this->vips_mutex));
1056 while (iterator->iterate(iterator, (void**)&listed))
1057 {
1058 if (listed->if_index == targetif &&
1059 virtual_ip->ip_equals(virtual_ip, listed->ip))
1060 {
1061 listed->refcount++;
1062 iterator->destroy(iterator);
1063 DBG2(DBG_KNL, "virtual IP %H already added to iface %d reusing it",
1064 virtual_ip, targetif);
1065 return SUCCESS;
1066 }
1067 }
1068 iterator->destroy(iterator);
1069
1070 if (manage_ipaddr(this, RTM_NEWADDR, NLM_F_CREATE | NLM_F_EXCL,
1071 targetif, virtual_ip) == SUCCESS)
1072 {
1073 listed = malloc_thing(vip_entry_t);
1074 listed->ip = virtual_ip->clone(virtual_ip);
1075 listed->if_index = targetif;
1076 listed->refcount = 1;
1077 this->vips->insert_last(this->vips, listed);
1078 DBG2(DBG_KNL, "virtual IP %H added to iface %d",
1079 virtual_ip, targetif);
1080 return SUCCESS;
1081 }
1082
1083 DBG2(DBG_KNL, "unable to add virtual IP %H to iface %d",
1084 virtual_ip, targetif);
1085 return FAILED;
1086 }
1087
1088 /**
1089 * Implementation of kernel_interface_t.del_ip.
1090 */
1091 static status_t del_ip(private_kernel_interface_t *this,
1092 host_t *virtual_ip, host_t *iface_ip)
1093 {
1094 int targetif;
1095 vip_entry_t *listed;
1096 iterator_t *iterator;
1097
1098 DBG2(DBG_KNL, "deleting virtual IP %H", virtual_ip);
1099
1100 targetif = get_interface_index(this, iface_ip);
1101 if (targetif == 0)
1102 {
1103 DBG1(DBG_KNL, "unable to delete virtual IP %H, no iface found for %H",
1104 virtual_ip, iface_ip);
1105 return FAILED;
1106 }
1107
1108 /* beware of deadlocks (e.g. send/receive packets while holding the lock) */
1109 iterator = this->vips->create_iterator_locked(this->vips, &(this->vips_mutex));
1110 while (iterator->iterate(iterator, (void**)&listed))
1111 {
1112 if (listed->if_index == targetif &&
1113 virtual_ip->ip_equals(virtual_ip, listed->ip))
1114 {
1115 listed->refcount--;
1116 if (listed->refcount == 0)
1117 {
1118 iterator->remove(iterator);
1119 vip_entry_destroy(listed);
1120 iterator->destroy(iterator);
1121 return manage_ipaddr(this, RTM_DELADDR, 0, targetif, virtual_ip);
1122 }
1123 iterator->destroy(iterator);
1124 DBG2(DBG_KNL, "virtual IP %H used by other SAs, not deleting",
1125 virtual_ip);
1126 return SUCCESS;
1127 }
1128 }
1129 iterator->destroy(iterator);
1130
1131 DBG2(DBG_KNL, "virtual IP %H not cached, unable to delete", virtual_ip);
1132 return FAILED;
1133 }
1134
1135 /**
1136 * Implementation of kernel_interface_t.get_spi.
1137 */
1138 static status_t get_spi(private_kernel_interface_t *this,
1139 host_t *src, host_t *dst,
1140 protocol_id_t protocol, u_int32_t reqid,
1141 u_int32_t *spi)
1142 {
1143 unsigned char request[BUFFER_SIZE];
1144 struct nlmsghdr *hdr, *out;
1145 struct xfrm_userspi_info *userspi;
1146 u_int32_t received_spi = 0;
1147 size_t len;
1148
1149 memset(&request, 0, sizeof(request));
1150
1151 DBG2(DBG_KNL, "getting SPI for reqid %d", reqid);
1152
1153 hdr = (struct nlmsghdr*)request;
1154 hdr->nlmsg_flags = NLM_F_REQUEST;
1155 hdr->nlmsg_type = XFRM_MSG_ALLOCSPI;
1156 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userspi_info));
1157
1158 userspi = (struct xfrm_userspi_info*)NLMSG_DATA(hdr);
1159 host2xfrm(src, &userspi->info.saddr);
1160 host2xfrm(dst, &userspi->info.id.daddr);
1161 userspi->info.id.proto = (protocol == PROTO_ESP) ? KERNEL_ESP : KERNEL_AH;
1162 userspi->info.mode = TRUE; /* tunnel mode */
1163 userspi->info.reqid = reqid;
1164 userspi->info.family = src->get_family(src);
1165 userspi->min = 0xc0000000;
1166 userspi->max = 0xcFFFFFFF;
1167
1168 if (netlink_send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
1169 {
1170 hdr = out;
1171 while (NLMSG_OK(hdr, len))
1172 {
1173 switch (hdr->nlmsg_type)
1174 {
1175 case XFRM_MSG_NEWSA:
1176 {
1177 struct xfrm_usersa_info* usersa = NLMSG_DATA(hdr);
1178 received_spi = usersa->id.spi;
1179 break;
1180 }
1181 case NLMSG_ERROR:
1182 {
1183 struct nlmsgerr *err = NLMSG_DATA(hdr);
1184
1185 DBG1(DBG_KNL, "allocating SPI failed: %s (%d)",
1186 strerror(-err->error), -err->error);
1187 break;
1188 }
1189 default:
1190 hdr = NLMSG_NEXT(hdr, len);
1191 continue;
1192 case NLMSG_DONE:
1193 break;
1194 }
1195 break;
1196 }
1197 free(out);
1198 }
1199
1200 if (received_spi == 0)
1201 {
1202 DBG1(DBG_KNL, "unable to get SPI for reqid %d", reqid);
1203 return FAILED;
1204 }
1205
1206 DBG2(DBG_KNL, "got SPI 0x%x for reqid %d", received_spi, reqid);
1207
1208 *spi = received_spi;
1209 return SUCCESS;
1210 }
1211
1212 /**
1213 * Implementation of kernel_interface_t.add_sa.
1214 */
1215 static status_t add_sa(private_kernel_interface_t *this,
1216 host_t *src, host_t *dst, u_int32_t spi,
1217 protocol_id_t protocol, u_int32_t reqid,
1218 u_int64_t expire_soft, u_int64_t expire_hard,
1219 algorithm_t *enc_alg, algorithm_t *int_alg,
1220 prf_plus_t *prf_plus, natt_conf_t *natt, mode_t mode,
1221 bool replace)
1222 {
1223 unsigned char request[BUFFER_SIZE];
1224 char *alg_name;
1225 u_int key_size;
1226 struct nlmsghdr *hdr;
1227 struct xfrm_usersa_info *sa;
1228
1229 memset(&request, 0, sizeof(request));
1230
1231 DBG2(DBG_KNL, "adding SAD entry with SPI 0x%x", spi);
1232
1233 hdr = (struct nlmsghdr*)request;
1234 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
1235 hdr->nlmsg_type = replace ? XFRM_MSG_UPDSA : XFRM_MSG_NEWSA;
1236 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_info));
1237
1238 sa = (struct xfrm_usersa_info*)NLMSG_DATA(hdr);
1239 host2xfrm(src, &sa->saddr);
1240 host2xfrm(dst, &sa->id.daddr);
1241 sa->id.spi = spi;
1242 sa->id.proto = (protocol == PROTO_ESP) ? KERNEL_ESP : KERNEL_AH;
1243 sa->family = src->get_family(src);
1244 sa->mode = mode;
1245 sa->replay_window = 32;
1246 sa->reqid = reqid;
1247 /* we currently do not expire SAs by volume/packet count */
1248 sa->lft.soft_byte_limit = XFRM_INF;
1249 sa->lft.hard_byte_limit = XFRM_INF;
1250 sa->lft.soft_packet_limit = XFRM_INF;
1251 sa->lft.hard_packet_limit = XFRM_INF;
1252 /* we use lifetimes since added, not since used */
1253 sa->lft.soft_add_expires_seconds = expire_soft;
1254 sa->lft.hard_add_expires_seconds = expire_hard;
1255 sa->lft.soft_use_expires_seconds = 0;
1256 sa->lft.hard_use_expires_seconds = 0;
1257
1258 struct rtattr *rthdr = XFRM_RTA(hdr, struct xfrm_usersa_info);
1259
1260 if (enc_alg->algorithm != ENCR_UNDEFINED)
1261 {
1262 rthdr->rta_type = XFRMA_ALG_CRYPT;
1263 alg_name = lookup_algorithm(encryption_algs, enc_alg, &key_size);
1264 if (alg_name == NULL)
1265 {
1266 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1267 encryption_algorithm_names, enc_alg->algorithm);
1268 return FAILED;
1269 }
1270 DBG2(DBG_KNL, " using encryption algorithm %N with key size %d",
1271 encryption_algorithm_names, enc_alg->algorithm, key_size);
1272
1273 rthdr->rta_len = RTA_LENGTH(sizeof(struct xfrm_algo) + key_size);
1274 hdr->nlmsg_len += rthdr->rta_len;
1275 if (hdr->nlmsg_len > sizeof(request))
1276 {
1277 return FAILED;
1278 }
1279
1280 struct xfrm_algo* algo = (struct xfrm_algo*)RTA_DATA(rthdr);
1281 algo->alg_key_len = key_size;
1282 strcpy(algo->alg_name, alg_name);
1283 prf_plus->get_bytes(prf_plus, key_size / 8, algo->alg_key);
1284
1285 rthdr = XFRM_RTA_NEXT(rthdr);
1286 }
1287
1288 if (int_alg->algorithm != AUTH_UNDEFINED)
1289 {
1290 rthdr->rta_type = XFRMA_ALG_AUTH;
1291 alg_name = lookup_algorithm(integrity_algs, int_alg, &key_size);
1292 if (alg_name == NULL)
1293 {
1294 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1295 integrity_algorithm_names, int_alg->algorithm);
1296 return FAILED;
1297 }
1298 DBG2(DBG_KNL, " using integrity algorithm %N with key size %d",
1299 integrity_algorithm_names, int_alg->algorithm, key_size);
1300
1301 rthdr->rta_len = RTA_LENGTH(sizeof(struct xfrm_algo) + key_size);
1302 hdr->nlmsg_len += rthdr->rta_len;
1303 if (hdr->nlmsg_len > sizeof(request))
1304 {
1305 return FAILED;
1306 }
1307
1308 struct xfrm_algo* algo = (struct xfrm_algo*)RTA_DATA(rthdr);
1309 algo->alg_key_len = key_size;
1310 strcpy(algo->alg_name, alg_name);
1311 prf_plus->get_bytes(prf_plus, key_size / 8, algo->alg_key);
1312
1313 rthdr = XFRM_RTA_NEXT(rthdr);
1314 }
1315
1316 /* TODO: add IPComp here */
1317
1318 if (natt)
1319 {
1320 rthdr->rta_type = XFRMA_ENCAP;
1321 rthdr->rta_len = RTA_LENGTH(sizeof(struct xfrm_encap_tmpl));
1322
1323 hdr->nlmsg_len += rthdr->rta_len;
1324 if (hdr->nlmsg_len > sizeof(request))
1325 {
1326 return FAILED;
1327 }
1328
1329 struct xfrm_encap_tmpl* encap = (struct xfrm_encap_tmpl*)RTA_DATA(rthdr);
1330 encap->encap_type = UDP_ENCAP_ESPINUDP;
1331 encap->encap_sport = htons(natt->sport);
1332 encap->encap_dport = htons(natt->dport);
1333 memset(&encap->encap_oa, 0, sizeof (xfrm_address_t));
1334 /* encap_oa could probably be derived from the
1335 * traffic selectors [rfc4306, p39]. In the netlink kernel implementation
1336 * pluto does the same as we do here but it uses encap_oa in the
1337 * pfkey implementation. BUT as /usr/src/linux/net/key/af_key.c indicates
1338 * the kernel ignores it anyway
1339 * -> does that mean that NAT-T encap doesn't work in transport mode?
1340 * No. The reason the kernel ignores NAT-OA is that it recomputes
1341 * (or, rather, just ignores) the checksum. If packets pass
1342 * the IPsec checks it marks them "checksum ok" so OA isn't needed. */
1343 rthdr = XFRM_RTA_NEXT(rthdr);
1344 }
1345
1346 if (netlink_send_ack(this->socket_xfrm, hdr) != SUCCESS)
1347 {
1348 DBG1(DBG_KNL, "unalbe to add SAD entry with SPI 0x%x", spi);
1349 return FAILED;
1350 }
1351 return SUCCESS;
1352 }
1353
1354 /**
1355 * Implementation of kernel_interface_t.update_sa.
1356 */
1357 static status_t update_sa(private_kernel_interface_t *this,
1358 host_t *src, host_t *dst,
1359 host_t *new_src, host_t *new_dst,
1360 host_diff_t src_changes, host_diff_t dst_changes,
1361 u_int32_t spi, protocol_id_t protocol)
1362 {
1363 unsigned char request[BUFFER_SIZE];
1364 struct nlmsghdr *hdr, *out = NULL;
1365 struct xfrm_usersa_id *sa_id;
1366 struct xfrm_usersa_info *sa = NULL;
1367 size_t len;
1368
1369 memset(&request, 0, sizeof(request));
1370
1371 DBG2(DBG_KNL, "querying SAD entry with SPI 0x%x", spi);
1372
1373 hdr = (struct nlmsghdr*)request;
1374 hdr->nlmsg_flags = NLM_F_REQUEST;
1375 hdr->nlmsg_type = XFRM_MSG_GETSA;
1376 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_id));
1377
1378 sa_id = (struct xfrm_usersa_id*)NLMSG_DATA(hdr);
1379 host2xfrm(dst, &sa_id->daddr);
1380 sa_id->spi = spi;
1381 sa_id->proto = (protocol == PROTO_ESP) ? KERNEL_ESP : KERNEL_AH;
1382 sa_id->family = dst->get_family(dst);
1383
1384 if (netlink_send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
1385 {
1386 hdr = out;
1387 while (NLMSG_OK(hdr, len))
1388 {
1389 switch (hdr->nlmsg_type)
1390 {
1391 case XFRM_MSG_NEWSA:
1392 {
1393 sa = NLMSG_DATA(hdr);
1394 break;
1395 }
1396 case NLMSG_ERROR:
1397 {
1398 struct nlmsgerr *err = NLMSG_DATA(hdr);
1399 DBG1(DBG_KNL, "querying SAD entry failed: %s (%d)",
1400 strerror(-err->error), -err->error);
1401 break;
1402 }
1403 default:
1404 hdr = NLMSG_NEXT(hdr, len);
1405 continue;
1406 case NLMSG_DONE:
1407 break;
1408 }
1409 break;
1410 }
1411 }
1412 if (sa == NULL)
1413 {
1414 DBG1(DBG_KNL, "unable to update SAD entry with SPI 0x%x", spi);
1415 free(out);
1416 return FAILED;
1417 }
1418
1419 DBG2(DBG_KNL, "updating SAD entry with SPI 0x%x", spi);
1420
1421 hdr = out;
1422 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
1423 hdr->nlmsg_type = XFRM_MSG_UPDSA;
1424
1425 if (src_changes & HOST_DIFF_ADDR)
1426 {
1427 host2xfrm(new_src, &sa->saddr);
1428 }
1429
1430 if (dst_changes & HOST_DIFF_ADDR)
1431 {
1432 hdr->nlmsg_type = XFRM_MSG_NEWSA;
1433 host2xfrm(new_dst, &sa->id.daddr);
1434 }
1435
1436 if (src_changes & HOST_DIFF_PORT || dst_changes & HOST_DIFF_PORT)
1437 {
1438 struct rtattr *rtattr = XFRM_RTA(hdr, struct xfrm_usersa_info);
1439 size_t rtsize = XFRM_PAYLOAD(hdr, struct xfrm_usersa_info);
1440 while (RTA_OK(rtattr, rtsize))
1441 {
1442 if (rtattr->rta_type == XFRMA_ENCAP)
1443 {
1444 struct xfrm_encap_tmpl* encap;
1445 encap = (struct xfrm_encap_tmpl*)RTA_DATA(rtattr);
1446 encap->encap_sport = ntohs(new_src->get_port(new_src));
1447 encap->encap_dport = ntohs(new_dst->get_port(new_dst));
1448 break;
1449 }
1450 rtattr = RTA_NEXT(rtattr, rtsize);
1451 }
1452 }
1453 if (netlink_send_ack(this->socket_xfrm, hdr) != SUCCESS)
1454 {
1455 DBG1(DBG_KNL, "unalbe to update SAD entry with SPI 0x%x", spi);
1456 free(out);
1457 return FAILED;
1458 }
1459 free(out);
1460
1461 if (dst_changes & HOST_DIFF_ADDR)
1462 {
1463 return this->public.del_sa(&this->public, dst, spi, protocol);
1464 }
1465 return SUCCESS;
1466 }
1467
1468 /**
1469 * Implementation of kernel_interface_t.query_sa.
1470 */
1471 static status_t query_sa(private_kernel_interface_t *this, host_t *dst,
1472 u_int32_t spi, protocol_id_t protocol,
1473 u_int32_t *use_time)
1474 {
1475 unsigned char request[BUFFER_SIZE];
1476 struct nlmsghdr *out = NULL, *hdr;
1477 struct xfrm_usersa_id *sa_id;
1478 struct xfrm_usersa_info *sa = NULL;
1479 size_t len;
1480
1481 DBG2(DBG_KNL, "querying SAD entry with SPI 0x%x", spi);
1482 memset(&request, 0, sizeof(request));
1483
1484 hdr = (struct nlmsghdr*)request;
1485 hdr->nlmsg_flags = NLM_F_REQUEST;
1486 hdr->nlmsg_type = XFRM_MSG_GETSA;
1487 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_info));
1488
1489 sa_id = (struct xfrm_usersa_id*)NLMSG_DATA(hdr);
1490 host2xfrm(dst, &sa_id->daddr);
1491 sa_id->spi = spi;
1492 sa_id->proto = (protocol == PROTO_ESP) ? KERNEL_ESP : KERNEL_AH;
1493 sa_id->family = dst->get_family(dst);
1494
1495 if (netlink_send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
1496 {
1497 hdr = out;
1498 while (NLMSG_OK(hdr, len))
1499 {
1500 switch (hdr->nlmsg_type)
1501 {
1502 case XFRM_MSG_NEWSA:
1503 {
1504 sa = NLMSG_DATA(hdr);
1505 break;
1506 }
1507 case NLMSG_ERROR:
1508 {
1509 struct nlmsgerr *err = NLMSG_DATA(hdr);
1510 DBG1(DBG_KNL, "querying SAD entry failed: %s (%d)",
1511 strerror(-err->error), -err->error);
1512 break;
1513 }
1514 default:
1515 hdr = NLMSG_NEXT(hdr, len);
1516 continue;
1517 case NLMSG_DONE:
1518 break;
1519 }
1520 break;
1521 }
1522 }
1523
1524 if (sa == NULL)
1525 {
1526 DBG1(DBG_KNL, "unable to query SAD entry with SPI 0x%x", spi);
1527 free(out);
1528 return FAILED;
1529 }
1530
1531 *use_time = sa->curlft.use_time;
1532 free (out);
1533 return SUCCESS;
1534 }
1535
1536 /**
1537 * Implementation of kernel_interface_t.del_sa.
1538 */
1539 static status_t del_sa(private_kernel_interface_t *this, host_t *dst,
1540 u_int32_t spi, protocol_id_t protocol)
1541 {
1542 unsigned char request[BUFFER_SIZE];
1543 struct nlmsghdr *hdr;
1544 struct xfrm_usersa_id *sa_id;
1545
1546 memset(&request, 0, sizeof(request));
1547
1548 DBG2(DBG_KNL, "deleting SAD entry with SPI 0x%x", spi);
1549
1550 hdr = (struct nlmsghdr*)request;
1551 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
1552 hdr->nlmsg_type = XFRM_MSG_DELSA;
1553 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_id));
1554
1555 sa_id = (struct xfrm_usersa_id*)NLMSG_DATA(hdr);
1556 host2xfrm(dst, &sa_id->daddr);
1557 sa_id->spi = spi;
1558 sa_id->proto = (protocol == PROTO_ESP) ? KERNEL_ESP : KERNEL_AH;
1559 sa_id->family = dst->get_family(dst);
1560
1561 if (netlink_send_ack(this->socket_xfrm, hdr) != SUCCESS)
1562 {
1563 DBG1(DBG_KNL, "unalbe to delete SAD entry with SPI 0x%x", spi);
1564 return FAILED;
1565 }
1566 DBG2(DBG_KNL, "deleted SAD entry with SPI 0x%x", spi);
1567 return SUCCESS;
1568 }
1569
1570 /**
1571 * Implementation of kernel_interface_t.add_policy.
1572 */
1573 static status_t add_policy(private_kernel_interface_t *this,
1574 host_t *src, host_t *dst,
1575 traffic_selector_t *src_ts,
1576 traffic_selector_t *dst_ts,
1577 policy_dir_t direction, protocol_id_t protocol,
1578 u_int32_t reqid, bool high_prio, mode_t mode,
1579 bool update)
1580 {
1581 iterator_t *iterator;
1582 policy_entry_t *current, *policy;
1583 bool found = FALSE;
1584 unsigned char request[BUFFER_SIZE];
1585 struct xfrm_userpolicy_info *policy_info;
1586 struct nlmsghdr *hdr;
1587
1588 /* create a policy */
1589 policy = malloc_thing(policy_entry_t);
1590 memset(policy, 0, sizeof(policy_entry_t));
1591 policy->sel = ts2selector(src_ts, dst_ts);
1592 policy->direction = direction;
1593
1594 /* find the policy, which matches EXACTLY */
1595 pthread_mutex_lock(&this->policies_mutex);
1596 iterator = this->policies->create_iterator(this->policies, TRUE);
1597 while (iterator->iterate(iterator, (void**)&current))
1598 {
1599 if (memcmp(&current->sel, &policy->sel, sizeof(struct xfrm_selector)) == 0 &&
1600 policy->direction == current->direction)
1601 {
1602 /* use existing policy */
1603 if (!update)
1604 {
1605 current->refcount++;
1606 DBG2(DBG_KNL, "policy %R===%R already exists, increasing ",
1607 "refcount", src_ts, dst_ts);
1608 }
1609 free(policy);
1610 policy = current;
1611 found = TRUE;
1612 break;
1613 }
1614 }
1615 iterator->destroy(iterator);
1616 if (!found)
1617 { /* apply the new one, if we have no such policy */
1618 this->policies->insert_last(this->policies, policy);
1619 policy->refcount = 1;
1620 }
1621
1622 DBG2(DBG_KNL, "adding policy %R===%R", src_ts, dst_ts);
1623
1624 memset(&request, 0, sizeof(request));
1625 hdr = (struct nlmsghdr*)request;
1626 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
1627 hdr->nlmsg_type = XFRM_MSG_UPDPOLICY;
1628 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_info));
1629
1630 policy_info = (struct xfrm_userpolicy_info*)NLMSG_DATA(hdr);
1631 policy_info->sel = policy->sel;
1632 policy_info->dir = policy->direction;
1633 /* calculate priority based on source selector size, small size = high prio */
1634 policy_info->priority = high_prio ? PRIO_HIGH : PRIO_LOW;
1635 policy_info->priority -= policy->sel.prefixlen_s * 10;
1636 policy_info->priority -= policy->sel.proto ? 2 : 0;
1637 policy_info->priority -= policy->sel.sport_mask ? 1 : 0;
1638 policy_info->action = XFRM_POLICY_ALLOW;
1639 policy_info->share = XFRM_SHARE_ANY;
1640 pthread_mutex_unlock(&this->policies_mutex);
1641
1642 /* policies don't expire */
1643 policy_info->lft.soft_byte_limit = XFRM_INF;
1644 policy_info->lft.soft_packet_limit = XFRM_INF;
1645 policy_info->lft.hard_byte_limit = XFRM_INF;
1646 policy_info->lft.hard_packet_limit = XFRM_INF;
1647 policy_info->lft.soft_add_expires_seconds = 0;
1648 policy_info->lft.hard_add_expires_seconds = 0;
1649 policy_info->lft.soft_use_expires_seconds = 0;
1650 policy_info->lft.hard_use_expires_seconds = 0;
1651
1652 struct rtattr *rthdr = XFRM_RTA(hdr, struct xfrm_userpolicy_info);
1653 rthdr->rta_type = XFRMA_TMPL;
1654
1655 rthdr->rta_len = sizeof(struct xfrm_user_tmpl);
1656 rthdr->rta_len = RTA_LENGTH(rthdr->rta_len);
1657
1658 hdr->nlmsg_len += rthdr->rta_len;
1659 if (hdr->nlmsg_len > sizeof(request))
1660 {
1661 return FAILED;
1662 }
1663
1664 struct xfrm_user_tmpl *tmpl = (struct xfrm_user_tmpl*)RTA_DATA(rthdr);
1665 tmpl->reqid = reqid;
1666 tmpl->id.proto = (protocol == PROTO_AH) ? KERNEL_AH : KERNEL_ESP;
1667 tmpl->aalgos = tmpl->ealgos = tmpl->calgos = ~0;
1668 tmpl->mode = mode;
1669 tmpl->family = src->get_family(src);
1670
1671 host2xfrm(src, &tmpl->saddr);
1672 host2xfrm(dst, &tmpl->id.daddr);
1673
1674 if (netlink_send_ack(this->socket_xfrm, hdr) != SUCCESS)
1675 {
1676 DBG1(DBG_KNL, "unable to add policy %R===%R", src_ts, dst_ts);
1677 return FAILED;
1678 }
1679
1680 /* install a route, if:
1681 * - we are NOT updating a policy
1682 * - this is a forward policy (to just get one for each child)
1683 * - we are in tunnel mode
1684 * - we are not using IPv6 (does not work correctly yet!)
1685 */
1686 if (policy->route == NULL && direction == POLICY_FWD &&
1687 mode != MODE_TRANSPORT && src->get_family(src) != AF_INET6)
1688 {
1689 policy->route = malloc_thing(route_entry_t);
1690 if (get_address_by_ts(this, dst_ts, &policy->route->src_ip) == SUCCESS)
1691 {
1692 policy->route->if_index = get_interface_index(this, dst);
1693 policy->route->dst_net = chunk_alloc(policy->sel.family == AF_INET ? 4 : 16);
1694 memcpy(policy->route->dst_net.ptr, &policy->sel.saddr, policy->route->dst_net.len);
1695 policy->route->prefixlen = policy->sel.prefixlen_s;
1696
1697 if (manage_srcroute(this, RTM_NEWROUTE, NLM_F_CREATE | NLM_F_EXCL,
1698 policy->route) != SUCCESS)
1699 {
1700 DBG1(DBG_KNL, "unable to install source route for %H",
1701 policy->route->src_ip);
1702 route_entry_destroy(policy->route);
1703 policy->route = NULL;
1704 }
1705 }
1706 else
1707 {
1708 free(policy->route);
1709 policy->route = NULL;
1710 }
1711 }
1712
1713 return SUCCESS;
1714 }
1715
1716 /**
1717 * Implementation of kernel_interface_t.query_policy.
1718 */
1719 static status_t query_policy(private_kernel_interface_t *this,
1720 traffic_selector_t *src_ts,
1721 traffic_selector_t *dst_ts,
1722 policy_dir_t direction, u_int32_t *use_time)
1723 {
1724 unsigned char request[BUFFER_SIZE];
1725 struct nlmsghdr *out = NULL, *hdr;
1726 struct xfrm_userpolicy_id *policy_id;
1727 struct xfrm_userpolicy_info *policy = NULL;
1728 size_t len;
1729
1730 memset(&request, 0, sizeof(request));
1731
1732 DBG2(DBG_KNL, "querying policy %R===%R", src_ts, dst_ts);
1733
1734 hdr = (struct nlmsghdr*)request;
1735 hdr->nlmsg_flags = NLM_F_REQUEST;
1736 hdr->nlmsg_type = XFRM_MSG_GETPOLICY;
1737 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_id));
1738
1739 policy_id = (struct xfrm_userpolicy_id*)NLMSG_DATA(hdr);
1740 policy_id->sel = ts2selector(src_ts, dst_ts);
1741 policy_id->dir = direction;
1742
1743 if (netlink_send(this->socket_xfrm, hdr, &out, &len) == SUCCESS)
1744 {
1745 hdr = out;
1746 while (NLMSG_OK(hdr, len))
1747 {
1748 switch (hdr->nlmsg_type)
1749 {
1750 case XFRM_MSG_NEWPOLICY:
1751 {
1752 policy = (struct xfrm_userpolicy_info*)NLMSG_DATA(hdr);
1753 break;
1754 }
1755 case NLMSG_ERROR:
1756 {
1757 struct nlmsgerr *err = NLMSG_DATA(hdr);
1758 DBG1(DBG_KNL, "querying policy failed: %s (%d)",
1759 strerror(-err->error), -err->error);
1760 break;
1761 }
1762 default:
1763 hdr = NLMSG_NEXT(hdr, len);
1764 continue;
1765 case NLMSG_DONE:
1766 break;
1767 }
1768 break;
1769 }
1770 }
1771
1772 if (policy == NULL)
1773 {
1774 DBG2(DBG_KNL, "unable to query policy %R===%R", src_ts, dst_ts);
1775 free(out);
1776 return FAILED;
1777 }
1778 *use_time = (time_t)policy->curlft.use_time;
1779
1780 free(out);
1781 return SUCCESS;
1782 }
1783
1784 /**
1785 * Implementation of kernel_interface_t.del_policy.
1786 */
1787 static status_t del_policy(private_kernel_interface_t *this,
1788 traffic_selector_t *src_ts,
1789 traffic_selector_t *dst_ts,
1790 policy_dir_t direction)
1791 {
1792 policy_entry_t *current, policy, *to_delete = NULL;
1793 route_entry_t *route;
1794 unsigned char request[BUFFER_SIZE];
1795 struct nlmsghdr *hdr;
1796 struct xfrm_userpolicy_id *policy_id;
1797 iterator_t *iterator;
1798
1799 DBG2(DBG_KNL, "deleting policy %R===%R", src_ts, dst_ts);
1800
1801 /* create a policy */
1802 memset(&policy, 0, sizeof(policy_entry_t));
1803 policy.sel = ts2selector(src_ts, dst_ts);
1804 policy.direction = direction;
1805
1806 /* find the policy */
1807 pthread_mutex_lock(&this->policies_mutex);
1808 iterator = this->policies->create_iterator(this->policies, TRUE);
1809 while (iterator->iterate(iterator, (void**)&current))
1810 {
1811 if (memcmp(&current->sel, &policy.sel, sizeof(struct xfrm_selector)) == 0 &&
1812 policy.direction == current->direction)
1813 {
1814 to_delete = current;
1815 if (--to_delete->refcount > 0)
1816 {
1817 /* is used by more SAs, keep in kernel */
1818 DBG2(DBG_KNL, "policy still used by another CHILD_SA, not removed");
1819 iterator->destroy(iterator);
1820 pthread_mutex_unlock(&this->policies_mutex);
1821 return SUCCESS;
1822 }
1823 /* remove if last reference */
1824 iterator->remove(iterator);
1825 break;
1826 }
1827 }
1828 iterator->destroy(iterator);
1829 pthread_mutex_unlock(&this->policies_mutex);
1830 if (!to_delete)
1831 {
1832 DBG1(DBG_KNL, "deleting policy %R===%R failed, not found", src_ts, dst_ts);
1833 return NOT_FOUND;
1834 }
1835
1836 memset(&request, 0, sizeof(request));
1837
1838 hdr = (struct nlmsghdr*)request;
1839 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
1840 hdr->nlmsg_type = XFRM_MSG_DELPOLICY;
1841 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_id));
1842
1843 policy_id = (struct xfrm_userpolicy_id*)NLMSG_DATA(hdr);
1844 policy_id->sel = to_delete->sel;
1845 policy_id->dir = direction;
1846
1847 route = to_delete->route;
1848 free(to_delete);
1849
1850 if (netlink_send_ack(this->socket_xfrm, hdr) != SUCCESS)
1851 {
1852 DBG1(DBG_KNL, "unable to delete policy %R===%R", src_ts, dst_ts);
1853 return FAILED;
1854 }
1855
1856 if (route)
1857 {
1858 if (manage_srcroute(this, RTM_DELROUTE, 0, route) != SUCCESS)
1859 {
1860 DBG1(DBG_KNL, "error uninstalling route installed with "
1861 "policy %R===%R", src_ts, dst_ts);
1862 }
1863 route_entry_destroy(route);
1864 }
1865 return SUCCESS;
1866 }
1867
1868 /**
1869 * Implementation of kernel_interface_t.destroy.
1870 */
1871 static void destroy(private_kernel_interface_t *this)
1872 {
1873 pthread_cancel(this->event_thread);
1874 pthread_join(this->event_thread, NULL);
1875 close(this->socket_xfrm_events);
1876 close(this->socket_xfrm);
1877 close(this->socket_rt);
1878 this->vips->destroy(this->vips);
1879 this->policies->destroy(this->policies);
1880 free(this);
1881 }
1882
1883 /*
1884 * Described in header.
1885 */
1886 kernel_interface_t *kernel_interface_create()
1887 {
1888 private_kernel_interface_t *this = malloc_thing(private_kernel_interface_t);
1889 struct sockaddr_nl addr;
1890
1891 /* public functions */
1892 this->public.get_spi = (status_t(*)(kernel_interface_t*,host_t*,host_t*,protocol_id_t,u_int32_t,u_int32_t*))get_spi;
1893 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*,natt_conf_t*,mode_t,bool))add_sa;
1894 this->public.update_sa = (status_t(*)(kernel_interface_t*,host_t*,u_int32_t,protocol_id_t,host_t*,host_t*,host_diff_t,host_diff_t))update_sa;
1895 this->public.query_sa = (status_t(*)(kernel_interface_t*,host_t*,u_int32_t,protocol_id_t,u_int32_t*))query_sa;
1896 this->public.del_sa = (status_t(*)(kernel_interface_t*,host_t*,u_int32_t,protocol_id_t))del_sa;
1897 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,bool))add_policy;
1898 this->public.query_policy = (status_t(*)(kernel_interface_t*,traffic_selector_t*,traffic_selector_t*,policy_dir_t,u_int32_t*))query_policy;
1899 this->public.del_policy = (status_t(*)(kernel_interface_t*,traffic_selector_t*,traffic_selector_t*,policy_dir_t))del_policy;
1900
1901 this->public.get_interface = (char*(*)(kernel_interface_t*,host_t*))get_interface_name;
1902 this->public.create_address_list = (linked_list_t*(*)(kernel_interface_t*))create_address_list_public;
1903 this->public.add_ip = (status_t(*)(kernel_interface_t*,host_t*,host_t*)) add_ip;
1904 this->public.del_ip = (status_t(*)(kernel_interface_t*,host_t*,host_t*)) del_ip;
1905 this->public.destroy = (void(*)(kernel_interface_t*)) destroy;
1906
1907 /* private members */
1908 this->vips = linked_list_create();
1909 this->policies = linked_list_create();
1910 pthread_mutex_init(&this->policies_mutex,NULL);
1911 pthread_mutex_init(&this->vips_mutex,NULL);
1912
1913 addr.nl_family = AF_NETLINK;
1914 addr.nl_pid = 0;
1915 addr.nl_groups = 0;
1916
1917 /* create and bind XFRM socket */
1918 this->socket_xfrm = socket(AF_NETLINK, SOCK_RAW, NETLINK_XFRM);
1919 if (this->socket_xfrm <= 0)
1920 {
1921 charon->kill(charon, "unable to create XFRM netlink socket");
1922 }
1923
1924 if (bind(this->socket_xfrm, (struct sockaddr*)&addr, sizeof(addr)))
1925 {
1926 charon->kill(charon, "unable to bind XFRM netlink socket");
1927 }
1928
1929 /* create and bind RT socket */
1930 this->socket_rt = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
1931 if (this->socket_rt <= 0)
1932 {
1933 charon->kill(charon, "unable to create RT netlink socket");
1934 }
1935
1936 if (bind(this->socket_rt, (struct sockaddr*)&addr, sizeof(addr)))
1937 {
1938 charon->kill(charon, "unable to bind RT netlink socket");
1939 }
1940
1941 /* create and bind XFRM socket for ACQUIRE & EXPIRE */
1942 addr.nl_groups = XFRMGRP_ACQUIRE | XFRMGRP_EXPIRE;
1943 this->socket_xfrm_events = socket(AF_NETLINK, SOCK_RAW, NETLINK_XFRM);
1944 if (this->socket_xfrm_events <= 0)
1945 {
1946 charon->kill(charon, "unable to create XFRM event socket");
1947 }
1948
1949 if (bind(this->socket_xfrm_events, (struct sockaddr*)&addr, sizeof(addr)))
1950 {
1951 charon->kill(charon, "unable to bind XFRM event socket");
1952 }
1953
1954 /* create a thread receiving ACQUIRE & EXPIRE events */
1955 if (pthread_create(&this->event_thread, NULL,
1956 (void*(*)(void*))receive_events, this))
1957 {
1958 charon->kill(charon, "unable to create xfrm event dispatcher thread");
1959 }
1960
1961 return &this->public;
1962 }
1963
1964 /* vim: set ts=4 sw=4 noet: */