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