892572a68f87cb98a95bc150a5e19da0fb41663f
[strongswan.git] / src / charon / plugins / kernel_klips / kernel_klips_ipsec.c
1 /*
2 * Copyright (C) 2008 Tobias Brunner
3 * Hochschule fuer Technik Rapperswil
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 *
15 * $Id$
16 */
17
18 #include <sys/types.h>
19 #include <sys/socket.h>
20 #include <sys/ioctl.h>
21 #include <stdint.h>
22 #include "pfkeyv2.h"
23 #include <linux/udp.h>
24 #include <net/if.h>
25 #include <unistd.h>
26 #include <pthread.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <time.h>
30 #include <errno.h>
31
32 #include "kernel_klips_ipsec.h"
33
34 #include <daemon.h>
35 #include <utils/mutex.h>
36 #include <processing/jobs/callback_job.h>
37 #include <processing/jobs/acquire_job.h>
38 #include <processing/jobs/rekey_child_sa_job.h>
39 #include <processing/jobs/delete_child_sa_job.h>
40 #include <processing/jobs/update_sa_job.h>
41
42 /** default timeout for generated SPIs (in seconds) */
43 #define SPI_TIMEOUT 30
44
45 /** buffer size for PF_KEY messages */
46 #define PFKEY_BUFFER_SIZE 2048
47
48 /** PF_KEY messages are 64 bit aligned */
49 #define PFKEY_ALIGNMENT 8
50 /** aligns len to 64 bits */
51 #define PFKEY_ALIGN(len) (((len) + PFKEY_ALIGNMENT - 1) & ~(PFKEY_ALIGNMENT - 1))
52 /** calculates the properly padded length in 64 bit chunks */
53 #define PFKEY_LEN(len) ((PFKEY_ALIGN(len) / PFKEY_ALIGNMENT))
54 /** calculates user mode length i.e. in bytes */
55 #define PFKEY_USER_LEN(len) ((len) * PFKEY_ALIGNMENT)
56
57 /** given a PF_KEY message header and an extension this updates the length in the header */
58 #define PFKEY_EXT_ADD(msg, ext) ((msg)->sadb_msg_len += ((struct sadb_ext*)ext)->sadb_ext_len)
59 /** given a PF_KEY message header this returns a pointer to the next extension */
60 #define PFKEY_EXT_ADD_NEXT(msg) ((struct sadb_ext*)(((char*)(msg)) + PFKEY_USER_LEN((msg)->sadb_msg_len)))
61 /** copy an extension and append it to a PF_KEY message */
62 #define PFKEY_EXT_COPY(msg, ext) (PFKEY_EXT_ADD(msg, memcpy(PFKEY_EXT_ADD_NEXT(msg), ext, PFKEY_USER_LEN(((struct sadb_ext*)ext)->sadb_ext_len))))
63 /** given a PF_KEY extension this returns a pointer to the next extension */
64 #define PFKEY_EXT_NEXT(ext) ((struct sadb_ext*)(((char*)(ext)) + PFKEY_USER_LEN(((struct sadb_ext*)ext)->sadb_ext_len)))
65 /** given a PF_KEY extension this returns a pointer to the next extension also updates len (len in 64 bit words) */
66 #define PFKEY_EXT_NEXT_LEN(ext,len) ((len) -= (ext)->sadb_ext_len, PFKEY_EXT_NEXT(ext))
67 /** true if ext has a valid length and len is large enough to contain ext (assuming len in 64 bit words) */
68 #define PFKEY_EXT_OK(ext,len) ((len) >= PFKEY_LEN(sizeof(struct sadb_ext)) && \
69 (ext)->sadb_ext_len >= PFKEY_LEN(sizeof(struct sadb_ext)) && \
70 (ext)->sadb_ext_len <= (len))
71
72 /** special SPI values used for policies in KLIPS */
73 #define SPI_PASS 256
74 #define SPI_DROP 257
75 #define SPI_REJECT 258
76 #define SPI_HOLD 259
77 #define SPI_TRAP 260
78 #define SPI_TRAPSUBNET 261
79
80 /** the prefix of the name of KLIPS ipsec devices */
81 #define IPSEC_DEV_PREFIX "ipsec"
82 /** this is the default number of ipsec devices */
83 #define DEFAULT_IPSEC_DEV_COUNT 4
84 /** TRUE if the given name matches an ipsec device */
85 #define IS_IPSEC_DEV(name) (strneq((name), IPSEC_DEV_PREFIX, sizeof(IPSEC_DEV_PREFIX) - 1))
86
87 /** the following stuff is from ipsec_tunnel.h */
88 struct ipsectunnelconf
89 {
90 __u32 cf_cmd;
91 union
92 {
93 char cfu_name[12];
94 } cf_u;
95 #define cf_name cf_u.cfu_name
96 };
97
98 #define IPSEC_SET_DEV (SIOCDEVPRIVATE)
99 #define IPSEC_DEL_DEV (SIOCDEVPRIVATE + 1)
100 #define IPSEC_CLR_DEV (SIOCDEVPRIVATE + 2)
101
102 typedef struct private_kernel_klips_ipsec_t private_kernel_klips_ipsec_t;
103
104 /**
105 * Private variables and functions of kernel_klips class.
106 */
107 struct private_kernel_klips_ipsec_t
108 {
109 /**
110 * Public part of the kernel_klips_t object.
111 */
112 kernel_klips_ipsec_t public;
113
114 /**
115 * mutex to lock access to various lists
116 */
117 mutex_t *mutex;
118
119 /**
120 * List of installed policies (policy_entry_t)
121 */
122 linked_list_t *policies;
123
124 /**
125 * List of allocated SPIs without installed SA (sa_entry_t)
126 */
127 linked_list_t *allocated_spis;
128
129 /**
130 * List of installed SAs (sa_entry_t)
131 */
132 linked_list_t *installed_sas;
133
134 /**
135 * whether to install routes along policies
136 */
137 bool install_routes;
138
139 /**
140 * List of ipsec devices (ipsec_dev_t)
141 */
142 linked_list_t *ipsec_devices;
143
144 /**
145 * job receiving PF_KEY events
146 */
147 callback_job_t *job;
148
149 /**
150 * mutex to lock access to the PF_KEY socket
151 */
152 mutex_t *mutex_pfkey;
153
154 /**
155 * PF_KEY socket to communicate with the kernel
156 */
157 int socket;
158
159 /**
160 * PF_KEY socket to receive acquire and expire events
161 */
162 int socket_events;
163
164 /**
165 * sequence number for messages sent to the kernel
166 */
167 int seq;
168
169 };
170
171
172 typedef struct ipsec_dev_t ipsec_dev_t;
173
174 /**
175 * ipsec device
176 */
177 struct ipsec_dev_t {
178 /** name of the virtual ipsec interface */
179 char name[IFNAMSIZ];
180
181 /** name of the physical interface */
182 char phys_name[IFNAMSIZ];
183
184 /** by how many CHILD_SA's this ipsec device is used */
185 u_int refcount;
186 };
187
188 /**
189 * compare the given name with the virtual device name
190 */
191 static inline bool ipsec_dev_match_byname(ipsec_dev_t *current, char *name)
192 {
193 return name && streq(current->name, name);
194 }
195
196 /**
197 * compare the given name with the physical device name
198 */
199 static inline bool ipsec_dev_match_byphys(ipsec_dev_t *current, char *name)
200 {
201 return name && streq(current->phys_name, name);
202 }
203
204 /**
205 * matches free ipsec devices
206 */
207 static inline bool ipsec_dev_match_free(ipsec_dev_t *current)
208 {
209 return current->refcount == 0;
210 }
211
212 /**
213 * tries to find an ipsec_dev_t object by name
214 */
215 static status_t find_ipsec_dev(private_kernel_klips_ipsec_t *this, char *name,
216 ipsec_dev_t **dev)
217 {
218 linked_list_match_t match = (linked_list_match_t)(IS_IPSEC_DEV(name) ?
219 ipsec_dev_match_byname : ipsec_dev_match_byphys);
220 return this->ipsec_devices->find_first(this->ipsec_devices, match,
221 (void**)dev, name);
222 }
223
224 /**
225 * attach an ipsec device to a physical interface
226 */
227 static status_t attach_ipsec_dev(char* name, char *phys_name)
228 {
229 int sock;
230 struct ifreq req;
231 struct ipsectunnelconf *itc = (struct ipsectunnelconf*)&req.ifr_data;
232 short phys_flags;
233 int mtu;
234
235 DBG2(DBG_KNL, "attaching virtual interface %s to %s", name, phys_name);
236
237 if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) <= 0)
238 {
239 return FAILED;
240 }
241
242 strncpy(req.ifr_name, phys_name, IFNAMSIZ);
243 if (ioctl(sock, SIOCGIFFLAGS, &req) < 0)
244 {
245 close(sock);
246 return FAILED;
247 }
248 phys_flags = req.ifr_flags;
249
250 strncpy(req.ifr_name, name, IFNAMSIZ);
251 if (ioctl(sock, SIOCGIFFLAGS, &req) < 0)
252 {
253 close(sock);
254 return FAILED;
255 }
256
257 if (req.ifr_flags & IFF_UP)
258 {
259 /* if it's already up, it is already attached, detach it first */
260 ioctl(sock, IPSEC_DEL_DEV, &req);
261 }
262
263 /* attach it */
264 strncpy(req.ifr_name, name, IFNAMSIZ);
265 strncpy(itc->cf_name, phys_name, sizeof(itc->cf_name));
266 ioctl(sock, IPSEC_SET_DEV, &req);
267
268 /* copy address from physical to virtual */
269 strncpy(req.ifr_name, phys_name, IFNAMSIZ);
270 if (ioctl(sock, SIOCGIFADDR, &req) == 0)
271 {
272 strncpy(req.ifr_name, name, IFNAMSIZ);
273 ioctl(sock, SIOCSIFADDR, &req);
274 }
275
276 /* copy net mask from physical to virtual */
277 strncpy(req.ifr_name, phys_name, IFNAMSIZ);
278 if (ioctl(sock, SIOCGIFNETMASK, &req) == 0)
279 {
280 strncpy(req.ifr_name, name, IFNAMSIZ);
281 ioctl(sock, SIOCSIFNETMASK, &req);
282 }
283
284 /* copy other flags and addresses */
285 strncpy(req.ifr_name, name, IFNAMSIZ);
286 if (ioctl(sock, SIOCGIFFLAGS, &req) == 0)
287 {
288 if (phys_flags & IFF_POINTOPOINT)
289 {
290 req.ifr_flags |= IFF_POINTOPOINT;
291 req.ifr_flags &= ~IFF_BROADCAST;
292 ioctl(sock, SIOCSIFFLAGS, &req);
293
294 strncpy(req.ifr_name, phys_name, IFNAMSIZ);
295 if (ioctl(sock, SIOCGIFDSTADDR, &req) == 0)
296 {
297 strncpy(req.ifr_name, name, IFNAMSIZ);
298 ioctl(sock, SIOCSIFDSTADDR, &req);
299 }
300 }
301 else if (phys_flags & IFF_BROADCAST)
302 {
303 req.ifr_flags &= ~IFF_POINTOPOINT;
304 req.ifr_flags |= IFF_BROADCAST;
305 ioctl(sock, SIOCSIFFLAGS, &req);
306
307 strncpy(req.ifr_name, phys_name, IFNAMSIZ);
308 if (ioctl(sock, SIOCGIFBRDADDR, &req)==0)
309 {
310 strncpy(req.ifr_name, name, IFNAMSIZ);
311 ioctl(sock, SIOCSIFBRDADDR, &req);
312 }
313 }
314 else
315 {
316 req.ifr_flags &= ~IFF_POINTOPOINT;
317 req.ifr_flags &= ~IFF_BROADCAST;
318 ioctl(sock, SIOCSIFFLAGS, &req);
319 }
320 }
321
322 mtu = lib->settings->get_int(lib->settings,
323 "charon.plugins.kernel_klips.ipsec_dev_mtu", 0);
324 if (mtu <= 0)
325 {
326 /* guess MTU as physical MTU - ESP overhead [- NAT-T overhead]
327 * ESP overhead : 73 bytes
328 * NAT-T overhead : 8 bytes ==> 81 bytes
329 *
330 * assuming tunnel mode with AES encryption and integrity
331 * outer IP header : 20 bytes
332 * (NAT-T UDP header: 8 bytes)
333 * ESP header : 8 bytes
334 * IV : 16 bytes
335 * padding : 15 bytes (worst-case)
336 * pad len / NH : 2 bytes
337 * auth data : 12 bytes
338 */
339 strncpy(req.ifr_name, phys_name, IFNAMSIZ);
340 ioctl(sock, SIOCGIFMTU, &req);
341 mtu = req.ifr_mtu - 81;
342 }
343
344 /* set MTU */
345 strncpy(req.ifr_name, name, IFNAMSIZ);
346 req.ifr_mtu = mtu;
347 ioctl(sock, SIOCSIFMTU, &req);
348
349 /* bring ipsec device UP */
350 if (ioctl(sock, SIOCGIFFLAGS, &req) == 0)
351 {
352 req.ifr_flags |= IFF_UP;
353 ioctl(sock, SIOCSIFFLAGS, &req);
354 }
355
356 close(sock);
357 return SUCCESS;
358 }
359
360 /**
361 * detach an ipsec device from a physical interface
362 */
363 static status_t detach_ipsec_dev(char* name, char *phys_name)
364 {
365 int sock;
366 struct ifreq req;
367
368 DBG2(DBG_KNL, "detaching virtual interface %s from %s", name,
369 strlen(phys_name) ? phys_name : "any physical interface");
370
371 if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) <= 0)
372 {
373 return FAILED;
374 }
375
376 strncpy(req.ifr_name, name, IFNAMSIZ);
377 if (ioctl(sock, SIOCGIFFLAGS, &req) < 0)
378 {
379 close(sock);
380 return FAILED;
381 }
382
383 /* shutting interface down */
384 if (req.ifr_flags & IFF_UP)
385 {
386 req.ifr_flags &= ~IFF_UP;
387 ioctl(sock, SIOCSIFFLAGS, &req);
388 }
389
390 /* unset address */
391 memset(&req.ifr_addr, 0, sizeof(req.ifr_addr));
392 req.ifr_addr.sa_family = AF_INET;
393 ioctl(sock, SIOCSIFADDR, &req);
394
395 /* detach interface */
396 ioctl(sock, IPSEC_DEL_DEV, &req);
397
398 close(sock);
399 return SUCCESS;
400 }
401
402 /**
403 * destroy an ipsec_dev_t object
404 */
405 static void ipsec_dev_destroy(ipsec_dev_t *this)
406 {
407 detach_ipsec_dev(this->name, this->phys_name);
408 free(this);
409 }
410
411
412 typedef struct route_entry_t route_entry_t;
413
414 /**
415 * installed routing entry
416 */
417 struct route_entry_t {
418 /** Name of the interface the route is bound to */
419 char *if_name;
420
421 /** Source ip of the route */
422 host_t *src_ip;
423
424 /** Gateway for this route */
425 host_t *gateway;
426
427 /** Destination net */
428 chunk_t dst_net;
429
430 /** Destination net prefixlen */
431 u_int8_t prefixlen;
432 };
433
434 /**
435 * destroy an route_entry_t object
436 */
437 static void route_entry_destroy(route_entry_t *this)
438 {
439 free(this->if_name);
440 this->src_ip->destroy(this->src_ip);
441 this->gateway->destroy(this->gateway);
442 chunk_free(&this->dst_net);
443 free(this);
444 }
445
446 typedef struct policy_entry_t policy_entry_t;
447
448 /**
449 * installed kernel policy.
450 */
451 struct policy_entry_t {
452
453 /** reqid of this policy, if setup as trap */
454 u_int32_t reqid;
455
456 /** direction of this policy: in, out, forward */
457 u_int8_t direction;
458
459 /** parameters of installed policy */
460 struct {
461 /** subnet and port */
462 host_t *net;
463 /** subnet mask */
464 u_int8_t mask;
465 /** protocol */
466 u_int8_t proto;
467 } src, dst;
468
469 /** associated route installed for this policy */
470 route_entry_t *route;
471
472 /** by how many CHILD_SA's this policy is actively used */
473 u_int activecount;
474
475 /** by how many CHILD_SA's this policy is trapped */
476 u_int trapcount;
477 };
478
479 /**
480 * convert a numerical netmask to a host_t
481 */
482 static host_t *mask2host(int family, u_int8_t mask)
483 {
484 static const u_char bitmask[] = { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
485 chunk_t chunk = chunk_alloca(family == AF_INET ? 4 : 16);
486 int bytes = mask / 8, bits = mask % 8;
487 memset(chunk.ptr, 0xFF, bytes);
488 memset(chunk.ptr + bytes, 0, chunk.len - bytes);
489 if (bits)
490 {
491 chunk.ptr[bytes] = bitmask[bits];
492 }
493 return host_create_from_chunk(family, chunk, 0);
494 }
495
496 /**
497 * check if a host is in a subnet (host with netmask in bits)
498 */
499 static bool is_host_in_net(host_t *host, host_t *net, u_int8_t mask)
500 {
501 static const u_char bitmask[] = { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
502 chunk_t host_chunk, net_chunk;
503 int bytes = mask / 8, bits = mask % 8;
504
505 host_chunk = host->get_address(host);
506 net_chunk = net->get_address(net);
507
508 if (host_chunk.len != net_chunk.len)
509 {
510 return FALSE;
511 }
512
513 if (memeq(host_chunk.ptr, net_chunk.ptr, bytes))
514 {
515 return (bits == 0) ||
516 (host_chunk.ptr[bytes] & bitmask[bits]) ==
517 (net_chunk.ptr[bytes] & bitmask[bits]);
518 }
519
520 return FALSE;
521 }
522
523 /**
524 * create a policy_entry_t object
525 */
526 static policy_entry_t *create_policy_entry(traffic_selector_t *src_ts,
527 traffic_selector_t *dst_ts, policy_dir_t dir)
528 {
529 policy_entry_t *policy = malloc_thing(policy_entry_t);
530 policy->reqid = 0;
531 policy->direction = dir;
532 policy->route = NULL;
533 policy->activecount = 0;
534 policy->trapcount = 0;
535
536 src_ts->to_subnet(src_ts, &policy->src.net, &policy->src.mask);
537 dst_ts->to_subnet(dst_ts, &policy->dst.net, &policy->dst.mask);
538
539 /* src or dest proto may be "any" (0), use more restrictive one */
540 policy->src.proto = max(src_ts->get_protocol(src_ts), dst_ts->get_protocol(dst_ts));
541 policy->src.proto = policy->src.proto ? policy->src.proto : 0;
542 policy->dst.proto = policy->src.proto;
543
544 return policy;
545 }
546
547 /**
548 * destroy a policy_entry_t object
549 */
550 static void policy_entry_destroy(policy_entry_t *this)
551 {
552 DESTROY_IF(this->src.net);
553 DESTROY_IF(this->dst.net);
554 if (this->route)
555 {
556 route_entry_destroy(this->route);
557 }
558 free(this);
559 }
560
561 /**
562 * compares two policy_entry_t
563 */
564 static inline bool policy_entry_equals(policy_entry_t *current, policy_entry_t *policy)
565 {
566 return current->direction == policy->direction &&
567 current->src.proto == policy->src.proto &&
568 current->dst.proto == policy->dst.proto &&
569 current->src.mask == policy->src.mask &&
570 current->dst.mask == policy->dst.mask &&
571 current->src.net->equals(current->src.net, policy->src.net) &&
572 current->dst.net->equals(current->dst.net, policy->dst.net);
573 }
574
575 static inline bool policy_entry_match_byaddrs(policy_entry_t *current, host_t *src,
576 host_t *dst)
577 {
578 return is_host_in_net(src, current->src.net, current->src.mask) &&
579 is_host_in_net(dst, current->dst.net, current->dst.mask);
580 }
581
582 typedef struct sa_entry_t sa_entry_t;
583
584 /**
585 * used for two things:
586 * - allocated SPIs that have not yet resulted in an installed SA
587 * - installed inbound SAs with enabled UDP encapsulation
588 */
589 struct sa_entry_t {
590
591 /** protocol of this SA */
592 protocol_id_t protocol;
593
594 /** reqid of this SA */
595 u_int32_t reqid;
596
597 /** SPI of this SA */
598 u_int32_t spi;
599
600 /** src address of this SA */
601 host_t *src;
602
603 /** dst address of this SA */
604 host_t *dst;
605
606 /** TRUE if this SA uses UDP encapsulation */
607 bool encap;
608
609 /** TRUE if this SA is inbound */
610 bool inbound;
611 };
612
613 /**
614 * create an sa_entry_t object
615 */
616 static sa_entry_t *create_sa_entry(protocol_id_t protocol, u_int32_t spi,
617 u_int32_t reqid, host_t *src, host_t *dst,
618 bool encap, bool inbound)
619 {
620 sa_entry_t *sa = malloc_thing(sa_entry_t);
621 sa->protocol = protocol;
622 sa->reqid = reqid;
623 sa->spi = spi;
624 sa->src = src ? src->clone(src) : NULL;
625 sa->dst = dst ? dst->clone(dst) : NULL;
626 sa->encap = encap;
627 sa->inbound = inbound;
628 return sa;
629 }
630
631 /**
632 * destroy an sa_entry_t object
633 */
634 static void sa_entry_destroy(sa_entry_t *this)
635 {
636 DESTROY_IF(this->src);
637 DESTROY_IF(this->dst);
638 free(this);
639 }
640
641 /**
642 * match an sa_entry_t for an inbound SA that uses UDP encapsulation by spi and src (remote) address
643 */
644 static inline bool sa_entry_match_encapbysrc(sa_entry_t *current, u_int32_t *spi,
645 host_t *src)
646 {
647 return current->encap && current->inbound &&
648 current->spi == *spi && src->ip_equals(src, current->src);
649 }
650
651 /**
652 * match an sa_entry_t by protocol, spi and dst address (as the kernel does it)
653 */
654 static inline bool sa_entry_match_bydst(sa_entry_t *current, protocol_id_t *protocol,
655 u_int32_t *spi, host_t *dst)
656 {
657 return current->protocol == *protocol && current->spi == *spi && dst->ip_equals(dst, current->dst);
658 }
659
660 /**
661 * match an sa_entry_t by protocol, reqid and spi
662 */
663 static inline bool sa_entry_match_byid(sa_entry_t *current, protocol_id_t *protocol,
664 u_int32_t *spi, u_int32_t *reqid)
665 {
666 return current->protocol == *protocol && current->spi == *spi && current->reqid == *reqid;
667 }
668
669 typedef struct pfkey_msg_t pfkey_msg_t;
670
671 struct pfkey_msg_t
672 {
673 /**
674 * PF_KEY message base
675 */
676 struct sadb_msg *msg;
677
678
679 /**
680 * PF_KEY message extensions
681 */
682 union {
683 struct sadb_ext *ext[SADB_EXT_MAX + 1];
684 struct {
685 struct sadb_ext *reserved; /* SADB_EXT_RESERVED */
686 struct sadb_sa *sa; /* SADB_EXT_SA */
687 struct sadb_lifetime *lft_current; /* SADB_EXT_LIFETIME_CURRENT */
688 struct sadb_lifetime *lft_hard; /* SADB_EXT_LIFETIME_HARD */
689 struct sadb_lifetime *lft_soft; /* SADB_EXT_LIFETIME_SOFT */
690 struct sadb_address *src; /* SADB_EXT_ADDRESS_SRC */
691 struct sadb_address *dst; /* SADB_EXT_ADDRESS_DST */
692 struct sadb_address *proxy; /* SADB_EXT_ADDRESS_PROXY */
693 struct sadb_key *key_auth; /* SADB_EXT_KEY_AUTH */
694 struct sadb_key *key_encr; /* SADB_EXT_KEY_ENCRYPT */
695 struct sadb_ident *id_src; /* SADB_EXT_IDENTITY_SRC */
696 struct sadb_ident *id_dst; /* SADB_EXT_IDENTITY_DST */
697 struct sadb_sens *sensitivity; /* SADB_EXT_SENSITIVITY */
698 struct sadb_prop *proposal; /* SADB_EXT_PROPOSAL */
699 struct sadb_supported *supported_auth; /* SADB_EXT_SUPPORTED_AUTH */
700 struct sadb_supported *supported_encr; /* SADB_EXT_SUPPORTED_ENCRYPT */
701 struct sadb_spirange *spirange; /* SADB_EXT_SPIRANGE */
702 struct sadb_x_kmprivate *x_kmprivate; /* SADB_X_EXT_KMPRIVATE */
703 struct sadb_ext *x_policy; /* SADB_X_EXT_SATYPE2 */
704 struct sadb_ext *x_sa2; /* SADB_X_EXT_SA2 */
705 struct sadb_address *x_dst2; /* SADB_X_EXT_ADDRESS_DST2 */
706 struct sadb_address *x_src_flow; /* SADB_X_EXT_ADDRESS_SRC_FLOW */
707 struct sadb_address *x_dst_flow; /* SADB_X_EXT_ADDRESS_DST_FLOW */
708 struct sadb_address *x_src_mask; /* SADB_X_EXT_ADDRESS_SRC_MASK */
709 struct sadb_address *x_dst_mask; /* SADB_X_EXT_ADDRESS_DST_MASK */
710 struct sadb_x_debug *x_debug; /* SADB_X_EXT_DEBUG */
711 struct sadb_protocol *x_protocol; /* SADB_X_EXT_PROTOCOL */
712 struct sadb_x_nat_t_type *x_natt_type; /* SADB_X_EXT_NAT_T_TYPE */
713 struct sadb_x_nat_t_port *x_natt_sport; /* SADB_X_EXT_NAT_T_SPORT */
714 struct sadb_x_nat_t_port *x_natt_dport; /* SADB_X_EXT_NAT_T_DPORT */
715 struct sadb_address *x_natt_oa; /* SADB_X_EXT_NAT_T_OA */
716 } __attribute__((__packed__));
717 };
718 };
719
720 /**
721 * convert a IKEv2 specific protocol identifier to the PF_KEY sa type
722 */
723 static u_int8_t proto_ike2satype(protocol_id_t proto)
724 {
725 switch (proto)
726 {
727 case PROTO_ESP:
728 return SADB_SATYPE_ESP;
729 case PROTO_AH:
730 return SADB_SATYPE_AH;
731 case IPPROTO_COMP:
732 return SADB_X_SATYPE_COMP;
733 default:
734 return proto;
735 }
736 }
737
738 /**
739 * convert a PF_KEY sa type to a IKEv2 specific protocol identifier
740 */
741 static protocol_id_t proto_satype2ike(u_int8_t proto)
742 {
743 switch (proto)
744 {
745 case SADB_SATYPE_ESP:
746 return PROTO_ESP;
747 case SADB_SATYPE_AH:
748 return PROTO_AH;
749 case SADB_X_SATYPE_COMP:
750 return IPPROTO_COMP;
751 default:
752 return proto;
753 }
754 }
755
756 typedef struct kernel_algorithm_t kernel_algorithm_t;
757
758 /**
759 * Mapping of IKEv2 algorithms to PF_KEY algorithms
760 */
761 struct kernel_algorithm_t {
762 /**
763 * Identifier specified in IKEv2
764 */
765 int ikev2;
766
767 /**
768 * Identifier as defined in pfkeyv2.h
769 */
770 int kernel;
771 };
772
773 #define END_OF_LIST -1
774
775 /**
776 * Algorithms for encryption
777 */
778 static kernel_algorithm_t encryption_algs[] = {
779 /* {ENCR_DES_IV64, 0 }, */
780 {ENCR_DES, SADB_EALG_DESCBC },
781 {ENCR_3DES, SADB_EALG_3DESCBC },
782 /* {ENCR_RC5, 0 }, */
783 /* {ENCR_IDEA, 0 }, */
784 /* {ENCR_CAST, 0 }, */
785 {ENCR_BLOWFISH, SADB_EALG_BFCBC },
786 /* {ENCR_3IDEA, 0 }, */
787 /* {ENCR_DES_IV32, 0 }, */
788 {ENCR_NULL, SADB_EALG_NULL },
789 {ENCR_AES_CBC, SADB_EALG_AESCBC },
790 /* {ENCR_AES_CTR, 0 }, */
791 /* {ENCR_AES_CCM_ICV8, 0 }, */
792 /* {ENCR_AES_CCM_ICV12, 0 }, */
793 /* {ENCR_AES_CCM_ICV16, 0 }, */
794 /* {ENCR_AES_GCM_ICV8, 0 }, */
795 /* {ENCR_AES_GCM_ICV12, 0 }, */
796 /* {ENCR_AES_GCM_ICV16, 0 }, */
797 {END_OF_LIST, 0 },
798 };
799
800 /**
801 * Algorithms for integrity protection
802 */
803 static kernel_algorithm_t integrity_algs[] = {
804 {AUTH_HMAC_MD5_96, SADB_AALG_MD5HMAC },
805 {AUTH_HMAC_SHA1_96, SADB_AALG_SHA1HMAC },
806 {AUTH_HMAC_SHA2_256_128, SADB_AALG_SHA256_HMAC },
807 {AUTH_HMAC_SHA2_384_192, SADB_AALG_SHA384_HMAC },
808 {AUTH_HMAC_SHA2_512_256, SADB_AALG_SHA512_HMAC },
809 /* {AUTH_DES_MAC, 0, }, */
810 /* {AUTH_KPDK_MD5, 0, }, */
811 /* {AUTH_AES_XCBC_96, 0, }, */
812 {END_OF_LIST, 0, },
813 };
814
815 /**
816 * Algorithms for IPComp
817 */
818 static kernel_algorithm_t compression_algs[] = {
819 /* {IPCOMP_OUI, 0 }, */
820 {IPCOMP_DEFLATE, SADB_X_CALG_DEFLATE },
821 {IPCOMP_LZS, SADB_X_CALG_LZS },
822 /* {IPCOMP_LZJH, 0 }, */
823 {END_OF_LIST, 0 },
824 };
825
826 /**
827 * Look up a kernel algorithm ID and its key size
828 */
829 static int lookup_algorithm(kernel_algorithm_t *list, int ikev2)
830 {
831 while (list->ikev2 != END_OF_LIST)
832 {
833 if (ikev2 == list->ikev2)
834 {
835 return list->kernel;
836 }
837 list++;
838 }
839 return 0;
840 }
841
842 /**
843 * add a host behind a sadb_address extension
844 */
845 static void host2ext(host_t *host, struct sadb_address *ext)
846 {
847 sockaddr_t *host_addr = host->get_sockaddr(host);
848 socklen_t *len = host->get_sockaddr_len(host);
849 memcpy((char*)(ext + 1), host_addr, *len);
850 ext->sadb_address_len = PFKEY_LEN(sizeof(*ext) + *len);
851 }
852
853 /**
854 * add a host behind a sadb_address extension
855 */
856 static void add_addr_ext(struct sadb_msg *msg, host_t *host, u_int16_t type)
857 {
858 struct sadb_address *addr = (struct sadb_address*)PFKEY_EXT_ADD_NEXT(msg);
859 addr->sadb_address_exttype = type;
860 host2ext(host, addr);
861 PFKEY_EXT_ADD(msg, addr);
862 }
863
864 /**
865 * adds an empty address extension to the given sadb_msg
866 */
867 static void add_anyaddr_ext(struct sadb_msg *msg, int family, u_int8_t type)
868 {
869 socklen_t len = (family == AF_INET) ? sizeof(struct sockaddr_in) :
870 sizeof(struct sockaddr_in6);
871 struct sadb_address *addr = (struct sadb_address*)PFKEY_EXT_ADD_NEXT(msg);
872 addr->sadb_address_exttype = type;
873 sockaddr_t *saddr = (sockaddr_t*)(addr + 1);
874 saddr->sa_family = family;
875 addr->sadb_address_len = PFKEY_LEN(sizeof(*addr) + len);
876 PFKEY_EXT_ADD(msg, addr);
877 }
878
879 /**
880 * add udp encap extensions to a sadb_msg
881 */
882 static void add_encap_ext(struct sadb_msg *msg, host_t *src, host_t *dst,
883 bool ports_only)
884 {
885 struct sadb_x_nat_t_type* nat_type;
886 struct sadb_x_nat_t_port* nat_port;
887
888 if (!ports_only)
889 {
890 nat_type = (struct sadb_x_nat_t_type*)PFKEY_EXT_ADD_NEXT(msg);
891 nat_type->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
892 nat_type->sadb_x_nat_t_type_len = PFKEY_LEN(sizeof(struct sadb_x_nat_t_type));
893 nat_type->sadb_x_nat_t_type_type = UDP_ENCAP_ESPINUDP;
894 PFKEY_EXT_ADD(msg, nat_type);
895 }
896
897 nat_port = (struct sadb_x_nat_t_port*)PFKEY_EXT_ADD_NEXT(msg);
898 nat_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_SPORT;
899 nat_port->sadb_x_nat_t_port_len = PFKEY_LEN(sizeof(struct sadb_x_nat_t_port));
900 nat_port->sadb_x_nat_t_port_port = src->get_port(src);
901 PFKEY_EXT_ADD(msg, nat_port);
902
903 nat_port = (struct sadb_x_nat_t_port*)PFKEY_EXT_ADD_NEXT(msg);
904 nat_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_DPORT;
905 nat_port->sadb_x_nat_t_port_len = PFKEY_LEN(sizeof(struct sadb_x_nat_t_port));
906 nat_port->sadb_x_nat_t_port_port = dst->get_port(dst);
907 PFKEY_EXT_ADD(msg, nat_port);
908 }
909
910 /**
911 * build an SADB_X_ADDFLOW msg
912 */
913 static void build_addflow(struct sadb_msg *msg, u_int8_t satype, u_int32_t spi,
914 host_t *src, host_t *dst, host_t *src_net, u_int8_t src_mask,
915 host_t *dst_net, u_int8_t dst_mask, u_int8_t protocol, bool replace)
916 {
917 struct sadb_sa *sa;
918 struct sadb_protocol *proto;
919 host_t *host;
920
921 msg->sadb_msg_version = PF_KEY_V2;
922 msg->sadb_msg_type = SADB_X_ADDFLOW;
923 msg->sadb_msg_satype = satype;
924 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
925
926 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
927 sa->sadb_sa_exttype = SADB_EXT_SA;
928 sa->sadb_sa_spi = spi;
929 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
930 sa->sadb_sa_flags = replace ? SADB_X_SAFLAGS_REPLACEFLOW : 0;
931 PFKEY_EXT_ADD(msg, sa);
932
933 if (!src)
934 {
935 add_anyaddr_ext(msg, src_net->get_family(src_net), SADB_EXT_ADDRESS_SRC);
936 }
937 else
938 {
939 add_addr_ext(msg, src, SADB_EXT_ADDRESS_SRC);
940 }
941
942 if (!dst)
943 {
944 add_anyaddr_ext(msg, dst_net->get_family(dst_net), SADB_EXT_ADDRESS_DST);
945 }
946 else
947 {
948 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST);
949 }
950
951 add_addr_ext(msg, src_net, SADB_X_EXT_ADDRESS_SRC_FLOW);
952 add_addr_ext(msg, dst_net, SADB_X_EXT_ADDRESS_DST_FLOW);
953
954 host = mask2host(src_net->get_family(src_net), src_mask);
955 add_addr_ext(msg, host, SADB_X_EXT_ADDRESS_SRC_MASK);
956 host->destroy(host);
957
958 host = mask2host(dst_net->get_family(dst_net), dst_mask);
959 add_addr_ext(msg, host, SADB_X_EXT_ADDRESS_DST_MASK);
960 host->destroy(host);
961
962 proto = (struct sadb_protocol*)PFKEY_EXT_ADD_NEXT(msg);
963 proto->sadb_protocol_exttype = SADB_X_EXT_PROTOCOL;
964 proto->sadb_protocol_len = PFKEY_LEN(sizeof(struct sadb_protocol));
965 proto->sadb_protocol_proto = protocol;
966 PFKEY_EXT_ADD(msg, proto);
967 }
968
969 /**
970 * build an SADB_X_DELFLOW msg
971 */
972 static void build_delflow(struct sadb_msg *msg, u_int8_t satype,
973 host_t *src_net, u_int8_t src_mask, host_t *dst_net, u_int8_t dst_mask,
974 u_int8_t protocol)
975 {
976 struct sadb_protocol *proto;
977 host_t *host;
978
979 msg->sadb_msg_version = PF_KEY_V2;
980 msg->sadb_msg_type = SADB_X_DELFLOW;
981 msg->sadb_msg_satype = satype;
982 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
983
984 add_addr_ext(msg, src_net, SADB_X_EXT_ADDRESS_SRC_FLOW);
985 add_addr_ext(msg, dst_net, SADB_X_EXT_ADDRESS_DST_FLOW);
986
987 host = mask2host(src_net->get_family(src_net),
988 src_mask);
989 add_addr_ext(msg, host, SADB_X_EXT_ADDRESS_SRC_MASK);
990 host->destroy(host);
991
992 host = mask2host(dst_net->get_family(dst_net),
993 dst_mask);
994 add_addr_ext(msg, host, SADB_X_EXT_ADDRESS_DST_MASK);
995 host->destroy(host);
996
997 proto = (struct sadb_protocol*)PFKEY_EXT_ADD_NEXT(msg);
998 proto->sadb_protocol_exttype = SADB_X_EXT_PROTOCOL;
999 proto->sadb_protocol_len = PFKEY_LEN(sizeof(struct sadb_protocol));
1000 proto->sadb_protocol_proto = protocol;
1001 PFKEY_EXT_ADD(msg, proto);
1002 }
1003
1004 /**
1005 * Parses a pfkey message received from the kernel
1006 */
1007 static status_t parse_pfkey_message(struct sadb_msg *msg, pfkey_msg_t *out)
1008 {
1009 struct sadb_ext* ext;
1010 size_t len;
1011
1012 memset(out, 0, sizeof(pfkey_msg_t));
1013 out->msg = msg;
1014
1015 len = msg->sadb_msg_len;
1016 len -= PFKEY_LEN(sizeof(struct sadb_msg));
1017
1018 ext = (struct sadb_ext*)(((char*)msg) + sizeof(struct sadb_msg));
1019
1020 while (len >= PFKEY_LEN(sizeof(struct sadb_ext)))
1021 {
1022 if (ext->sadb_ext_len < PFKEY_LEN(sizeof(struct sadb_ext)) ||
1023 ext->sadb_ext_len > len)
1024 {
1025 DBG1(DBG_KNL, "length of PF_KEY extension (%d) is invalid", ext->sadb_ext_type);
1026 break;
1027 }
1028
1029 if ((ext->sadb_ext_type > SADB_EXT_MAX) || (!ext->sadb_ext_type))
1030 {
1031 DBG1(DBG_KNL, "type of PF_KEY extension (%d) is invalid", ext->sadb_ext_type);
1032 break;
1033 }
1034
1035 if (out->ext[ext->sadb_ext_type])
1036 {
1037 DBG1(DBG_KNL, "duplicate PF_KEY extension of type (%d)", ext->sadb_ext_type);
1038 break;
1039 }
1040
1041 out->ext[ext->sadb_ext_type] = ext;
1042 ext = PFKEY_EXT_NEXT_LEN(ext, len);
1043 }
1044
1045 if (len)
1046 {
1047 DBG1(DBG_KNL, "PF_KEY message length is invalid");
1048 return FAILED;
1049 }
1050
1051 return SUCCESS;
1052 }
1053
1054 /**
1055 * Send a message to a specific PF_KEY socket and handle the response.
1056 */
1057 static status_t pfkey_send_socket(private_kernel_klips_ipsec_t *this, int socket,
1058 struct sadb_msg *in, struct sadb_msg **out, size_t *out_len)
1059 {
1060 unsigned char buf[PFKEY_BUFFER_SIZE];
1061 struct sadb_msg *msg;
1062 int in_len, len;
1063
1064 this->mutex_pfkey->lock(this->mutex_pfkey);
1065
1066 in->sadb_msg_seq = ++this->seq;
1067 in->sadb_msg_pid = getpid();
1068
1069 in_len = PFKEY_USER_LEN(in->sadb_msg_len);
1070
1071 while (TRUE)
1072 {
1073 len = send(socket, in, in_len, 0);
1074
1075 if (len != in_len)
1076 {
1077 switch (errno)
1078 {
1079 case EINTR:
1080 /* interrupted, try again */
1081 continue;
1082 case EINVAL:
1083 case EEXIST:
1084 case ESRCH:
1085 /* we should also get a response for these from KLIPS */
1086 break;
1087 default:
1088 this->mutex_pfkey->unlock(this->mutex_pfkey);
1089 DBG1(DBG_KNL, "error sending to PF_KEY socket: %s (%d)",
1090 strerror(errno), errno);
1091 return FAILED;
1092 }
1093 }
1094 break;
1095 }
1096
1097 while (TRUE)
1098 {
1099 msg = (struct sadb_msg*)buf;
1100
1101 len = recv(socket, buf, sizeof(buf), 0);
1102
1103 if (len < 0)
1104 {
1105 if (errno == EINTR)
1106 {
1107 DBG1(DBG_KNL, "got interrupted");
1108 /* interrupted, try again */
1109 continue;
1110 }
1111 this->mutex_pfkey->unlock(this->mutex_pfkey);
1112 DBG1(DBG_KNL, "error reading from PF_KEY socket: %s", strerror(errno));
1113 return FAILED;
1114 }
1115 if (len < sizeof(struct sadb_msg) ||
1116 msg->sadb_msg_len < PFKEY_LEN(sizeof(struct sadb_msg)))
1117 {
1118 this->mutex_pfkey->unlock(this->mutex_pfkey);
1119 DBG1(DBG_KNL, "received corrupted PF_KEY message");
1120 return FAILED;
1121 }
1122 if (msg->sadb_msg_len > len / PFKEY_ALIGNMENT)
1123 {
1124 this->mutex_pfkey->unlock(this->mutex_pfkey);
1125 DBG1(DBG_KNL, "buffer was too small to receive the complete PF_KEY message");
1126 return FAILED;
1127 }
1128 if (msg->sadb_msg_pid != in->sadb_msg_pid)
1129 {
1130 DBG2(DBG_KNL, "received PF_KEY message is not intended for us");
1131 continue;
1132 }
1133 if (msg->sadb_msg_seq != this->seq)
1134 {
1135 DBG1(DBG_KNL, "received PF_KEY message with invalid sequence number,"
1136 " was %d expected %d", msg->sadb_msg_seq, this->seq);
1137 if (msg->sadb_msg_seq < this->seq)
1138 {
1139 continue;
1140 }
1141 this->mutex_pfkey->unlock(this->mutex_pfkey);
1142 return FAILED;
1143 }
1144 if (msg->sadb_msg_type != in->sadb_msg_type)
1145 {
1146 DBG2(DBG_KNL, "received PF_KEY message of wrong type,"
1147 " was %d expected %d, ignoring",
1148 msg->sadb_msg_type, in->sadb_msg_type);
1149 }
1150 break;
1151 }
1152
1153 *out_len = len;
1154 *out = (struct sadb_msg*)malloc(len);
1155 memcpy(*out, buf, len);
1156
1157 this->mutex_pfkey->unlock(this->mutex_pfkey);
1158
1159 return SUCCESS;
1160 }
1161
1162 /**
1163 * Send a message to the default PF_KEY socket.
1164 */
1165 static status_t pfkey_send(private_kernel_klips_ipsec_t *this,
1166 struct sadb_msg *in, struct sadb_msg **out, size_t *out_len)
1167 {
1168 return pfkey_send_socket(this, this->socket, in, out, out_len);
1169 }
1170
1171 /**
1172 * Send a message to the default PF_KEY socket and handle the response.
1173 */
1174 static status_t pfkey_send_ack(private_kernel_klips_ipsec_t *this, struct sadb_msg *in)
1175 {
1176 struct sadb_msg *out;
1177 size_t len;
1178
1179 if (pfkey_send(this, in, &out, &len) != SUCCESS)
1180 {
1181 return FAILED;
1182 }
1183 else if (out->sadb_msg_errno)
1184 {
1185 DBG1(DBG_KNL, "PF_KEY error: %s (%d)",
1186 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1187 free(out);
1188 return FAILED;
1189 }
1190 free(out);
1191 return SUCCESS;
1192 }
1193
1194 /**
1195 * Add an eroute to KLIPS
1196 */
1197 static status_t add_eroute(private_kernel_klips_ipsec_t *this, u_int8_t satype,
1198 u_int32_t spi, host_t *src, host_t *dst, host_t *src_net, u_int8_t src_mask,
1199 host_t *dst_net, u_int8_t dst_mask, u_int8_t protocol, bool replace)
1200 {
1201 unsigned char request[PFKEY_BUFFER_SIZE];
1202 struct sadb_msg *msg = (struct sadb_msg*)request;
1203
1204 memset(&request, 0, sizeof(request));
1205
1206 build_addflow(msg, satype, spi, src, dst, src_net, src_mask,
1207 dst_net, dst_mask, protocol, replace);
1208
1209 return pfkey_send_ack(this, msg);
1210 }
1211
1212 /**
1213 * Delete an eroute fom KLIPS
1214 */
1215 static status_t del_eroute(private_kernel_klips_ipsec_t *this, u_int8_t satype,
1216 host_t *src_net, u_int8_t src_mask, host_t *dst_net, u_int8_t dst_mask,
1217 u_int8_t protocol)
1218 {
1219 unsigned char request[PFKEY_BUFFER_SIZE];
1220 struct sadb_msg *msg = (struct sadb_msg*)request;
1221
1222 memset(&request, 0, sizeof(request));
1223
1224 build_delflow(msg, satype, src_net, src_mask, dst_net, dst_mask, protocol);
1225
1226 return pfkey_send_ack(this, msg);
1227 }
1228
1229 /**
1230 * Process a SADB_ACQUIRE message from the kernel
1231 */
1232 static void process_acquire(private_kernel_klips_ipsec_t *this, struct sadb_msg* msg)
1233 {
1234 pfkey_msg_t response;
1235 host_t *src, *dst;
1236 u_int32_t reqid;
1237 u_int8_t proto;
1238 policy_entry_t *policy;
1239 job_t *job;
1240
1241 switch (msg->sadb_msg_satype)
1242 {
1243 case SADB_SATYPE_UNSPEC:
1244 case SADB_SATYPE_ESP:
1245 case SADB_SATYPE_AH:
1246 break;
1247 default:
1248 /* acquire for AH/ESP only */
1249 return;
1250 }
1251
1252 if (parse_pfkey_message(msg, &response) != SUCCESS)
1253 {
1254 DBG1(DBG_KNL, "parsing SADB_ACQUIRE from kernel failed");
1255 return;
1256 }
1257
1258 /* KLIPS provides us only with the source and destination address,
1259 * and the transport protocol of the packet that triggered the policy.
1260 * we use this information to find a matching policy in our cache.
1261 * because KLIPS installs a narrow %hold eroute covering only this information,
1262 * we replace both the %trap and this %hold eroutes with a broader %hold
1263 * eroute covering the whole policy */
1264 src = host_create_from_sockaddr((sockaddr_t*)(response.src + 1));
1265 dst = host_create_from_sockaddr((sockaddr_t*)(response.dst + 1));
1266 proto = response.src->sadb_address_proto;
1267 if (!src || !dst || src->get_family(src) != dst->get_family(dst))
1268 {
1269 DBG1(DBG_KNL, "received an SADB_ACQUIRE with invalid hosts");
1270 return;
1271 }
1272
1273 DBG2(DBG_KNL, "received an SADB_ACQUIRE for %H == %H : %d", src, dst, proto);
1274 this->mutex->lock(this->mutex);
1275 if (this->policies->find_first(this->policies,
1276 (linked_list_match_t)policy_entry_match_byaddrs,
1277 (void**)&policy, src, dst) != SUCCESS)
1278 {
1279 this->mutex->unlock(this->mutex);
1280 DBG1(DBG_KNL, "received an SADB_ACQUIRE, but found no matching policy");
1281 return;
1282 }
1283 if ((reqid = policy->reqid) == 0)
1284 {
1285 this->mutex->unlock(this->mutex);
1286 DBG1(DBG_KNL, "received an SADB_ACQUIRE, but policy is not routed anymore");
1287 return;
1288 }
1289
1290 /* add a broad %hold eroute that replaces the %trap eroute */
1291 add_eroute(this, SADB_X_SATYPE_INT, htonl(SPI_HOLD), NULL, NULL,
1292 policy->src.net, policy->src.mask, policy->dst.net, policy->dst.mask,
1293 policy->src.proto, TRUE);
1294
1295 /* remove the narrow %hold eroute installed by KLIPS */
1296 del_eroute(this, SADB_X_SATYPE_INT, src, 32, dst, 32, proto);
1297
1298 this->mutex->unlock(this->mutex);
1299
1300 DBG2(DBG_KNL, "received an SADB_ACQUIRE");
1301 DBG1(DBG_KNL, "creating acquire job for CHILD_SA with reqid {%d}", reqid);
1302 job = (job_t*)acquire_job_create(reqid, NULL, NULL);
1303 charon->processor->queue_job(charon->processor, job);
1304 }
1305
1306 /**
1307 * Process a SADB_X_NAT_T_NEW_MAPPING message from the kernel
1308 */
1309 static void process_mapping(private_kernel_klips_ipsec_t *this, struct sadb_msg* msg)
1310 {
1311 pfkey_msg_t response;
1312 u_int32_t spi, reqid;
1313 host_t *old_src, *new_src;
1314 job_t *job;
1315
1316 DBG2(DBG_KNL, "received an SADB_X_NAT_T_NEW_MAPPING");
1317
1318 if (parse_pfkey_message(msg, &response) != SUCCESS)
1319 {
1320 DBG1(DBG_KNL, "parsing SADB_X_NAT_T_NEW_MAPPING from kernel failed");
1321 return;
1322 }
1323
1324 spi = response.sa->sadb_sa_spi;
1325
1326 if (proto_satype2ike(msg->sadb_msg_satype) == PROTO_ESP)
1327 {
1328 sa_entry_t *sa;
1329 sockaddr_t *addr = (sockaddr_t*)(response.src + 1);
1330 old_src = host_create_from_sockaddr(addr);
1331
1332 this->mutex->lock(this->mutex);
1333 if (!old_src || this->installed_sas->find_first(this->installed_sas,
1334 (linked_list_match_t)sa_entry_match_encapbysrc,
1335 (void**)&sa, &spi, old_src) != SUCCESS)
1336 {
1337 this->mutex->unlock(this->mutex);
1338 DBG1(DBG_KNL, "received an SADB_X_NAT_T_NEW_MAPPING, but found no matching SA");
1339 return;
1340 }
1341 reqid = sa->reqid;
1342 this->mutex->unlock(this->mutex);
1343
1344 addr = (sockaddr_t*)(response.dst + 1);
1345 switch (addr->sa_family)
1346 {
1347 case AF_INET:
1348 {
1349 struct sockaddr_in *sin = (struct sockaddr_in*)addr;
1350 sin->sin_port = htons(response.x_natt_dport->sadb_x_nat_t_port_port);
1351 }
1352 case AF_INET6:
1353 {
1354 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)addr;
1355 sin6->sin6_port = htons(response.x_natt_dport->sadb_x_nat_t_port_port);
1356 }
1357 default:
1358 break;
1359 }
1360 new_src = host_create_from_sockaddr(addr);
1361 if (new_src)
1362 {
1363 DBG1(DBG_KNL, "NAT mappings of ESP CHILD_SA with SPI %.8x and"
1364 " reqid {%d} changed, queuing update job", ntohl(spi), reqid);
1365 job = (job_t*)update_sa_job_create(reqid, new_src);
1366 charon->processor->queue_job(charon->processor, job);
1367 }
1368 }
1369 }
1370
1371 /**
1372 * Receives events from kernel
1373 */
1374 static job_requeue_t receive_events(private_kernel_klips_ipsec_t *this)
1375 {
1376 unsigned char buf[PFKEY_BUFFER_SIZE];
1377 struct sadb_msg *msg = (struct sadb_msg*)buf;
1378 int len, oldstate;
1379
1380 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate);
1381 len = recv(this->socket_events, buf, sizeof(buf), 0);
1382 pthread_setcancelstate(oldstate, NULL);
1383
1384 if (len < 0)
1385 {
1386 switch (errno)
1387 {
1388 case EINTR:
1389 /* interrupted, try again */
1390 return JOB_REQUEUE_DIRECT;
1391 case EAGAIN:
1392 /* no data ready, select again */
1393 return JOB_REQUEUE_DIRECT;
1394 default:
1395 DBG1(DBG_KNL, "unable to receive from PF_KEY event socket");
1396 sleep(1);
1397 return JOB_REQUEUE_FAIR;
1398 }
1399 }
1400
1401 if (len < sizeof(struct sadb_msg) ||
1402 msg->sadb_msg_len < PFKEY_LEN(sizeof(struct sadb_msg)))
1403 {
1404 DBG2(DBG_KNL, "received corrupted PF_KEY message");
1405 return JOB_REQUEUE_DIRECT;
1406 }
1407 if (msg->sadb_msg_pid != 0)
1408 { /* not from kernel. not interested, try another one */
1409 return JOB_REQUEUE_DIRECT;
1410 }
1411 if (msg->sadb_msg_len > len / PFKEY_ALIGNMENT)
1412 {
1413 DBG1(DBG_KNL, "buffer was too small to receive the complete PF_KEY message");
1414 return JOB_REQUEUE_DIRECT;
1415 }
1416
1417 switch (msg->sadb_msg_type)
1418 {
1419 case SADB_ACQUIRE:
1420 process_acquire(this, msg);
1421 break;
1422 case SADB_EXPIRE:
1423 /* SADB_EXPIRE events in KLIPS are only triggered by traffic (even for
1424 * the time based limits). So if there is no traffic for a longer
1425 * period than configured as hard limit, we wouldn't be able to rekey
1426 * the SA and just receive the hard expire and thus delete the SA.
1427 * To avoid this behavior and to make charon behave as with the other
1428 * kernel plugins, we implement the expiration of SAs ourselves. */
1429 break;
1430 case SADB_X_NAT_T_NEW_MAPPING:
1431 process_mapping(this, msg);
1432 break;
1433 default:
1434 break;
1435 }
1436
1437 return JOB_REQUEUE_DIRECT;
1438 }
1439
1440 typedef enum {
1441 /** an SPI has expired */
1442 EXPIRE_TYPE_SPI,
1443 /** a CHILD_SA has to be rekeyed */
1444 EXPIRE_TYPE_SOFT,
1445 /** a CHILD_SA has to be deleted */
1446 EXPIRE_TYPE_HARD
1447 } expire_type_t;
1448
1449 typedef struct sa_expire_t sa_expire_t;
1450
1451 struct sa_expire_t {
1452 /** kernel interface */
1453 private_kernel_klips_ipsec_t *this;
1454 /** the SPI of the expiring SA */
1455 u_int32_t spi;
1456 /** the protocol of the expiring SA */
1457 protocol_id_t protocol;
1458 /** the reqid of the expiring SA*/
1459 u_int32_t reqid;
1460 /** what type of expire this is */
1461 expire_type_t type;
1462 };
1463
1464 /**
1465 * Called when an SA expires
1466 */
1467 static job_requeue_t sa_expires(sa_expire_t *expire)
1468 {
1469 private_kernel_klips_ipsec_t *this = expire->this;
1470 protocol_id_t protocol = expire->protocol;
1471 u_int32_t spi = expire->spi, reqid = expire->reqid;
1472 bool hard = expire->type != EXPIRE_TYPE_SOFT;
1473 sa_entry_t *cached_sa;
1474 linked_list_t *list;
1475 job_t *job;
1476
1477 /* for an expired SPI we first check whether the CHILD_SA got installed
1478 * in the meantime, for expired SAs we check whether they are still installed */
1479 list = expire->type == EXPIRE_TYPE_SPI ? this->allocated_spis : this->installed_sas;
1480
1481 this->mutex->lock(this->mutex);
1482 if (list->find_first(list, (linked_list_match_t)sa_entry_match_byid,
1483 (void**)&cached_sa, &protocol, &spi, &reqid) != SUCCESS)
1484 {
1485 /* we found no entry:
1486 * - for SPIs, a CHILD_SA has been installed
1487 * - for SAs, the CHILD_SA has already been deleted */
1488 this->mutex->unlock(this->mutex);
1489 return JOB_REQUEUE_NONE;
1490 }
1491 else
1492 {
1493 list->remove(list, cached_sa, NULL);
1494 sa_entry_destroy(cached_sa);
1495 }
1496 this->mutex->unlock(this->mutex);
1497
1498 DBG2(DBG_KNL, "%N CHILD_SA with SPI %.8x and reqid {%d} expired",
1499 protocol_id_names, protocol, ntohl(spi), reqid);
1500
1501 DBG1(DBG_KNL, "creating %s job for %N CHILD_SA with SPI %.8x and reqid {%d}",
1502 hard ? "delete" : "rekey", protocol_id_names,
1503 protocol, ntohl(spi), reqid);
1504 if (hard)
1505 {
1506 job = (job_t*)delete_child_sa_job_create(reqid, protocol, spi);
1507 }
1508 else
1509 {
1510 job = (job_t*)rekey_child_sa_job_create(reqid, protocol, spi);
1511 }
1512 charon->processor->queue_job(charon->processor, job);
1513 return JOB_REQUEUE_NONE;
1514 }
1515
1516 /**
1517 * Schedule an expire job for an SA. Time is in seconds.
1518 */
1519 static void schedule_expire(private_kernel_klips_ipsec_t *this,
1520 protocol_id_t protocol, u_int32_t spi,
1521 u_int32_t reqid, expire_type_t type, u_int32_t time)
1522 {
1523 callback_job_t *job;
1524 sa_expire_t *expire = malloc_thing(sa_expire_t);
1525 expire->this = this;
1526 expire->protocol = protocol;
1527 expire->spi = spi;
1528 expire->reqid = reqid;
1529 expire->type = type;
1530 job = callback_job_create((callback_job_cb_t)sa_expires, expire, free, NULL);
1531 charon->scheduler->schedule_job(charon->scheduler, (job_t*)job, time * 1000);
1532 }
1533
1534 /**
1535 * Implementation of kernel_interface_t.get_spi.
1536 */
1537 static status_t get_spi(private_kernel_klips_ipsec_t *this,
1538 host_t *src, host_t *dst,
1539 protocol_id_t protocol, u_int32_t reqid,
1540 u_int32_t *spi)
1541 {
1542 /* we cannot use SADB_GETSPI because KLIPS does not allow us to set the
1543 * NAT-T type in an SADB_UPDATE which we would have to use to update the
1544 * implicitly created SA.
1545 */
1546 rng_t *rng;
1547 u_int32_t spi_gen;
1548
1549 rng = lib->crypto->create_rng(lib->crypto, RNG_WEAK);
1550 if (!rng)
1551 {
1552 DBG1(DBG_KNL, "allocating SPI failed: no RNG");
1553 return FAILED;
1554 }
1555 rng->get_bytes(rng, sizeof(spi_gen), (void*)&spi_gen);
1556 rng->destroy(rng);
1557
1558 /* charon's SPIs lie within the range from 0xc0000000 to 0xcFFFFFFF */
1559 spi_gen = 0xc0000000 | (spi_gen & 0x0FFFFFFF);
1560
1561 DBG2(DBG_KNL, "allocated SPI %.8x for %N SA between %#H..%#H",
1562 spi_gen, protocol_id_names, protocol, src, dst);
1563
1564 *spi = htonl(spi_gen);
1565
1566 this->mutex->lock(this->mutex);
1567 this->allocated_spis->insert_last(this->allocated_spis,
1568 create_sa_entry(protocol, *spi, reqid, NULL, NULL, FALSE, TRUE));
1569 this->mutex->unlock(this->mutex);
1570 schedule_expire(this, protocol, *spi, reqid, EXPIRE_TYPE_SPI, SPI_TIMEOUT);
1571
1572 return SUCCESS;
1573 }
1574
1575 /**
1576 * Implementation of kernel_interface_t.get_cpi.
1577 */
1578 static status_t get_cpi(private_kernel_klips_ipsec_t *this,
1579 host_t *src, host_t *dst,
1580 u_int32_t reqid, u_int16_t *cpi)
1581 {
1582 return FAILED;
1583 }
1584
1585 /**
1586 * Add a pseudo IPIP SA for tunnel mode with KLIPS.
1587 */
1588 static status_t add_ipip_sa(private_kernel_klips_ipsec_t *this,
1589 host_t *src, host_t *dst, u_int32_t spi, u_int32_t reqid)
1590 {
1591 unsigned char request[PFKEY_BUFFER_SIZE];
1592 struct sadb_msg *msg, *out;
1593 struct sadb_sa *sa;
1594 size_t len;
1595
1596 memset(&request, 0, sizeof(request));
1597
1598 DBG2(DBG_KNL, "adding pseudo IPIP SA with SPI %.8x and reqid {%d}", ntohl(spi), reqid);
1599
1600 msg = (struct sadb_msg*)request;
1601 msg->sadb_msg_version = PF_KEY_V2;
1602 msg->sadb_msg_type = SADB_ADD;
1603 msg->sadb_msg_satype = SADB_X_SATYPE_IPIP;
1604 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1605
1606 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1607 sa->sadb_sa_exttype = SADB_EXT_SA;
1608 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1609 sa->sadb_sa_spi = spi;
1610 sa->sadb_sa_state = SADB_SASTATE_MATURE;
1611 PFKEY_EXT_ADD(msg, sa);
1612
1613 add_addr_ext(msg, src, SADB_EXT_ADDRESS_SRC);
1614 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST);
1615
1616 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1617 {
1618 DBG1(DBG_KNL, "unable to add pseudo IPIP SA with SPI %.8x", ntohl(spi));
1619 return FAILED;
1620 }
1621 else if (out->sadb_msg_errno)
1622 {
1623 DBG1(DBG_KNL, "unable to add pseudo IPIP SA with SPI %.8x: %s (%d)",
1624 ntohl(spi), strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1625 free(out);
1626 return FAILED;
1627 }
1628
1629 free(out);
1630 return SUCCESS;
1631 }
1632
1633 /**
1634 * group the IPIP SA required for tunnel mode with the outer SA
1635 */
1636 static status_t group_ipip_sa(private_kernel_klips_ipsec_t *this,
1637 host_t *src, host_t *dst, u_int32_t spi,
1638 protocol_id_t protocol, u_int32_t reqid)
1639 {
1640 unsigned char request[PFKEY_BUFFER_SIZE];
1641 struct sadb_msg *msg, *out;
1642 struct sadb_sa *sa;
1643 struct sadb_x_satype *satype;
1644 size_t len;
1645
1646 memset(&request, 0, sizeof(request));
1647
1648 DBG2(DBG_KNL, "grouping SAs with SPI %.8x and reqid {%d}", ntohl(spi), reqid);
1649
1650 msg = (struct sadb_msg*)request;
1651 msg->sadb_msg_version = PF_KEY_V2;
1652 msg->sadb_msg_type = SADB_X_GRPSA;
1653 msg->sadb_msg_satype = SADB_X_SATYPE_IPIP;
1654 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1655
1656 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1657 sa->sadb_sa_exttype = SADB_EXT_SA;
1658 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1659 sa->sadb_sa_spi = spi;
1660 sa->sadb_sa_state = SADB_SASTATE_MATURE;
1661 PFKEY_EXT_ADD(msg, sa);
1662
1663 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST);
1664
1665 satype = (struct sadb_x_satype*)PFKEY_EXT_ADD_NEXT(msg);
1666 satype->sadb_x_satype_exttype = SADB_X_EXT_SATYPE2;
1667 satype->sadb_x_satype_len = PFKEY_LEN(sizeof(struct sadb_x_satype));
1668 satype->sadb_x_satype_satype = proto_ike2satype(protocol);
1669 PFKEY_EXT_ADD(msg, satype);
1670
1671 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1672 sa->sadb_sa_exttype = SADB_X_EXT_SA2;
1673 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1674 sa->sadb_sa_spi = spi;
1675 sa->sadb_sa_state = SADB_SASTATE_MATURE;
1676 PFKEY_EXT_ADD(msg, sa);
1677
1678 add_addr_ext(msg, dst, SADB_X_EXT_ADDRESS_DST2);
1679
1680 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1681 {
1682 DBG1(DBG_KNL, "unable to group SAs with SPI %.8x", ntohl(spi));
1683 return FAILED;
1684 }
1685 else if (out->sadb_msg_errno)
1686 {
1687 DBG1(DBG_KNL, "unable to group SAs with SPI %.8x: %s (%d)",
1688 ntohl(spi), strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1689 free(out);
1690 return FAILED;
1691 }
1692
1693 free(out);
1694 return SUCCESS;
1695 }
1696
1697 /**
1698 * Implementation of kernel_interface_t.add_sa.
1699 */
1700 static status_t add_sa(private_kernel_klips_ipsec_t *this,
1701 host_t *src, host_t *dst, u_int32_t spi,
1702 protocol_id_t protocol, u_int32_t reqid,
1703 u_int64_t expire_soft, u_int64_t expire_hard,
1704 u_int16_t enc_alg, chunk_t enc_key,
1705 u_int16_t int_alg, chunk_t int_key,
1706 ipsec_mode_t mode, u_int16_t ipcomp, u_int16_t cpi,
1707 bool encap, bool inbound)
1708 {
1709 unsigned char request[PFKEY_BUFFER_SIZE];
1710 struct sadb_msg *msg, *out;
1711 struct sadb_sa *sa;
1712 struct sadb_key *key;
1713 size_t len;
1714
1715 if (inbound)
1716 {
1717 /* for inbound SAs we allocated an SPI via get_spi, so we first check
1718 * whether that SPI has already expired (race condition) */
1719 sa_entry_t *alloc_spi;
1720 this->mutex->lock(this->mutex);
1721 if (this->allocated_spis->find_first(this->allocated_spis,
1722 (linked_list_match_t)sa_entry_match_byid, (void**)&alloc_spi,
1723 &protocol, &spi, &reqid) != SUCCESS)
1724 {
1725 this->mutex->unlock(this->mutex);
1726 DBG1(DBG_KNL, "allocated SPI %.8x has already expired", ntohl(spi));
1727 return FAILED;
1728 }
1729 else
1730 {
1731 this->allocated_spis->remove(this->allocated_spis, alloc_spi, NULL);
1732 sa_entry_destroy(alloc_spi);
1733 }
1734 this->mutex->unlock(this->mutex);
1735 }
1736
1737 memset(&request, 0, sizeof(request));
1738
1739 DBG2(DBG_KNL, "adding SAD entry with SPI %.8x and reqid {%d}", ntohl(spi), reqid);
1740
1741 msg = (struct sadb_msg*)request;
1742 msg->sadb_msg_version = PF_KEY_V2;
1743 msg->sadb_msg_type = SADB_ADD;
1744 msg->sadb_msg_satype = proto_ike2satype(protocol);
1745 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1746
1747 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1748 sa->sadb_sa_exttype = SADB_EXT_SA;
1749 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1750 sa->sadb_sa_spi = spi;
1751 sa->sadb_sa_state = SADB_SASTATE_MATURE;
1752 sa->sadb_sa_replay = (protocol == IPPROTO_COMP) ? 0 : 32;
1753 sa->sadb_sa_auth = lookup_algorithm(integrity_algs, int_alg);
1754 sa->sadb_sa_encrypt = lookup_algorithm(encryption_algs, enc_alg);
1755 PFKEY_EXT_ADD(msg, sa);
1756
1757 add_addr_ext(msg, src, SADB_EXT_ADDRESS_SRC);
1758 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST);
1759
1760 if (enc_alg != ENCR_UNDEFINED)
1761 {
1762 if (!sa->sadb_sa_encrypt)
1763 {
1764 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1765 encryption_algorithm_names, enc_alg);
1766 return FAILED;
1767 }
1768 DBG2(DBG_KNL, " using encryption algorithm %N with key size %d",
1769 encryption_algorithm_names, enc_alg, enc_key.len * 8);
1770
1771 key = (struct sadb_key*)PFKEY_EXT_ADD_NEXT(msg);
1772 key->sadb_key_exttype = SADB_EXT_KEY_ENCRYPT;
1773 key->sadb_key_bits = enc_key.len * 8;
1774 key->sadb_key_len = PFKEY_LEN(sizeof(struct sadb_key) + enc_key.len);
1775 memcpy(key + 1, enc_key.ptr, enc_key.len);
1776
1777 PFKEY_EXT_ADD(msg, key);
1778 }
1779
1780 if (int_alg != AUTH_UNDEFINED)
1781 {
1782 if (!sa->sadb_sa_auth)
1783 {
1784 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1785 integrity_algorithm_names, int_alg);
1786 return FAILED;
1787 }
1788 DBG2(DBG_KNL, " using integrity algorithm %N with key size %d",
1789 integrity_algorithm_names, int_alg, int_key.len * 8);
1790
1791 key = (struct sadb_key*)PFKEY_EXT_ADD_NEXT(msg);
1792 key->sadb_key_exttype = SADB_EXT_KEY_AUTH;
1793 key->sadb_key_bits = int_key.len * 8;
1794 key->sadb_key_len = PFKEY_LEN(sizeof(struct sadb_key) + int_key.len);
1795 memcpy(key + 1, int_key.ptr, int_key.len);
1796
1797 PFKEY_EXT_ADD(msg, key);
1798 }
1799
1800 if (ipcomp != IPCOMP_NONE)
1801 {
1802 /*TODO*/
1803 }
1804
1805 if (encap)
1806 {
1807 add_encap_ext(msg, src, dst, FALSE);
1808 }
1809
1810 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1811 {
1812 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x", ntohl(spi));
1813 return FAILED;
1814 }
1815 else if (out->sadb_msg_errno)
1816 {
1817 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x: %s (%d)",
1818 ntohl(spi), strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1819 free(out);
1820 return FAILED;
1821 }
1822 free(out);
1823
1824 /* for tunnel mode SAs we have to install an additional IPIP SA and
1825 * group the two SAs together */
1826 if (mode == MODE_TUNNEL)
1827 {
1828 if (add_ipip_sa(this, src, dst, spi, reqid) != SUCCESS ||
1829 group_ipip_sa(this, src, dst, spi, protocol, reqid) != SUCCESS)
1830 {
1831 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x", ntohl(spi));
1832 return FAILED;
1833 }
1834 }
1835
1836 this->mutex->lock(this->mutex);
1837 /* we cache this SA for two reasons:
1838 * - in case an SADB_X_NAT_T_MAPPING_NEW event occurs (we need to find the reqid then)
1839 * - to decide if an expired SA is still installed */
1840 this->installed_sas->insert_last(this->installed_sas,
1841 create_sa_entry(protocol, spi, reqid, src, dst, encap, inbound));
1842 this->mutex->unlock(this->mutex);
1843
1844 /* Although KLIPS supports SADB_EXT_LIFETIME_SOFT/HARD, we handle the lifetime
1845 * of SAs manually in the plugin. Refer to the comments in receive_events()
1846 * for details. */
1847 if (expire_soft)
1848 {
1849 schedule_expire(this, protocol, spi, reqid, EXPIRE_TYPE_SOFT, expire_soft);
1850 }
1851
1852 if (expire_hard)
1853 {
1854 schedule_expire(this, protocol, spi, reqid, EXPIRE_TYPE_HARD, expire_hard);
1855 }
1856
1857 return SUCCESS;
1858 }
1859
1860 /**
1861 * Implementation of kernel_interface_t.update_sa.
1862 */
1863 static status_t update_sa(private_kernel_klips_ipsec_t *this,
1864 u_int32_t spi, protocol_id_t protocol, u_int16_t cpi,
1865 host_t *src, host_t *dst,
1866 host_t *new_src, host_t *new_dst,
1867 bool encap, bool new_encap)
1868 {
1869 unsigned char request[PFKEY_BUFFER_SIZE];
1870 struct sadb_msg *msg, *out;
1871 struct sadb_sa *sa;
1872 size_t len;
1873
1874 /* we can't update the SA if any of the ip addresses have changed.
1875 * that's because we can't use SADB_UPDATE and by deleting and readding the
1876 * SA the sequence numbers would get lost */
1877 if (!src->ip_equals(src, new_src) ||
1878 !dst->ip_equals(dst, new_dst))
1879 {
1880 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x: address changes"
1881 " are not supported", ntohl(spi));
1882 return NOT_SUPPORTED;
1883 }
1884
1885 /* because KLIPS does not allow us to change the NAT-T type in an SADB_UPDATE,
1886 * we can't update the SA if the encap flag has changed since installing it */
1887 if (encap != new_encap)
1888 {
1889 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x: change of UDP"
1890 " encapsulation is not supported", ntohl(spi));
1891 return NOT_SUPPORTED;
1892 }
1893
1894 DBG2(DBG_KNL, "updating SAD entry with SPI %.8x from %#H..%#H to %#H..%#H",
1895 ntohl(spi), src, dst, new_src, new_dst);
1896
1897 memset(&request, 0, sizeof(request));
1898
1899 msg = (struct sadb_msg*)request;
1900 msg->sadb_msg_version = PF_KEY_V2;
1901 msg->sadb_msg_type = SADB_UPDATE;
1902 msg->sadb_msg_satype = proto_ike2satype(protocol);
1903 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1904
1905 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1906 sa->sadb_sa_exttype = SADB_EXT_SA;
1907 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1908 sa->sadb_sa_spi = spi;
1909 sa->sadb_sa_encrypt = SADB_EALG_AESCBC; /* ignored */
1910 sa->sadb_sa_auth = SADB_AALG_SHA1HMAC; /* ignored */
1911 sa->sadb_sa_state = SADB_SASTATE_MATURE;
1912 PFKEY_EXT_ADD(msg, sa);
1913
1914 add_addr_ext(msg, src, SADB_EXT_ADDRESS_SRC);
1915 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST);
1916
1917 add_encap_ext(msg, new_src, new_dst, TRUE);
1918
1919 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1920 {
1921 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x", ntohl(spi));
1922 return FAILED;
1923 }
1924 else if (out->sadb_msg_errno)
1925 {
1926 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x: %s (%d)",
1927 ntohl(spi), strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1928 free(out);
1929 return FAILED;
1930 }
1931 free(out);
1932
1933 return SUCCESS;
1934 }
1935
1936 /**
1937 * Implementation of kernel_interface_t.del_sa.
1938 */
1939 static status_t del_sa(private_kernel_klips_ipsec_t *this, host_t *dst,
1940 u_int32_t spi, protocol_id_t protocol, u_int16_t cpi)
1941 {
1942 unsigned char request[PFKEY_BUFFER_SIZE];
1943 struct sadb_msg *msg, *out;
1944 struct sadb_sa *sa;
1945 sa_entry_t *cached_sa;
1946 size_t len;
1947
1948 memset(&request, 0, sizeof(request));
1949
1950 /* all grouped SAs are automatically deleted by KLIPS as soon as
1951 * one of them is deleted, therefore we delete only the main one */
1952 DBG2(DBG_KNL, "deleting SAD entry with SPI %.8x", ntohl(spi));
1953
1954 this->mutex->lock(this->mutex);
1955 /* this should not fail, but we don't care if it does, let the kernel decide
1956 * whether this SA exists or not */
1957 if (this->installed_sas->find_first(this->installed_sas,
1958 (linked_list_match_t)sa_entry_match_bydst, (void**)&cached_sa,
1959 &protocol, &spi, dst) == SUCCESS)
1960 {
1961 this->installed_sas->remove(this->installed_sas, cached_sa, NULL);
1962 sa_entry_destroy(cached_sa);
1963 }
1964 this->mutex->unlock(this->mutex);
1965
1966 msg = (struct sadb_msg*)request;
1967 msg->sadb_msg_version = PF_KEY_V2;
1968 msg->sadb_msg_type = SADB_DELETE;
1969 msg->sadb_msg_satype = proto_ike2satype(protocol);
1970 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1971
1972 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1973 sa->sadb_sa_exttype = SADB_EXT_SA;
1974 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1975 sa->sadb_sa_spi = spi;
1976 PFKEY_EXT_ADD(msg, sa);
1977
1978 /* the kernel wants an SADB_EXT_ADDRESS_SRC to be present even though
1979 * it is not used for anything. */
1980 add_anyaddr_ext(msg, dst->get_family(dst), SADB_EXT_ADDRESS_SRC);
1981 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST);
1982
1983 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1984 {
1985 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x", ntohl(spi));
1986 return FAILED;
1987 }
1988 else if (out->sadb_msg_errno)
1989 {
1990 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x: %s (%d)",
1991 ntohl(spi), strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1992 free(out);
1993 return FAILED;
1994 }
1995
1996 DBG2(DBG_KNL, "deleted SAD entry with SPI %.8x", ntohl(spi));
1997 free(out);
1998 return SUCCESS;
1999 }
2000
2001 /**
2002 * Implementation of kernel_interface_t.add_policy.
2003 */
2004 static status_t add_policy(private_kernel_klips_ipsec_t *this,
2005 host_t *src, host_t *dst,
2006 traffic_selector_t *src_ts,
2007 traffic_selector_t *dst_ts,
2008 policy_dir_t direction, u_int32_t spi,
2009 protocol_id_t protocol, u_int32_t reqid,
2010 ipsec_mode_t mode, u_int16_t ipcomp, u_int16_t cpi,
2011 bool routed)
2012 {
2013 unsigned char request[PFKEY_BUFFER_SIZE];
2014 struct sadb_msg *msg, *out;
2015 policy_entry_t *policy, *found = NULL;
2016 u_int8_t satype;
2017 size_t len;
2018
2019 if (direction == POLICY_FWD)
2020 {
2021 /* no forward policies for KLIPS */
2022 return SUCCESS;
2023 }
2024
2025 /* tunnel mode policies direct the packets into the pseudo IPIP SA */
2026 satype = (mode == MODE_TUNNEL) ? SADB_X_SATYPE_IPIP :
2027 proto_ike2satype(protocol);
2028
2029 /* create a policy */
2030 policy = create_policy_entry(src_ts, dst_ts, direction);
2031
2032 /* find a matching policy */
2033 this->mutex->lock(this->mutex);
2034 if (this->policies->find_first(this->policies,
2035 (linked_list_match_t)policy_entry_equals, (void**)&found, policy) == SUCCESS)
2036 {
2037 /* use existing policy */
2038 DBG2(DBG_KNL, "policy %R === %R %N already exists, increasing"
2039 " refcount", src_ts, dst_ts,
2040 policy_dir_names, direction);
2041 policy_entry_destroy(policy);
2042 policy = found;
2043 }
2044 else
2045 {
2046 /* apply the new one, if we have no such policy */
2047 this->policies->insert_last(this->policies, policy);
2048 }
2049
2050 if (routed)
2051 {
2052 /* we install this as a %trap eroute in the kernel, later to be
2053 * triggered by packets matching the policy (-> ACQUIRE). */
2054 spi = htonl(SPI_TRAP);
2055 satype = SADB_X_SATYPE_INT;
2056
2057 /* the reqid is always set to the latest child SA that trapped this
2058 * policy. we will need this reqid upon receiving an acquire. */
2059 policy->reqid = reqid;
2060
2061 /* increase the trap counter */
2062 policy->trapcount++;
2063
2064 if (policy->activecount)
2065 {
2066 /* we do not replace the current policy in the kernel while a
2067 * policy is actively used */
2068 this->mutex->unlock(this->mutex);
2069 return SUCCESS;
2070 }
2071 }
2072 else
2073 {
2074 /* increase the reference counter */
2075 policy->activecount++;
2076 }
2077
2078 DBG2(DBG_KNL, "adding policy %R === %R %N", src_ts, dst_ts,
2079 policy_dir_names, direction);
2080
2081 memset(&request, 0, sizeof(request));
2082
2083 msg = (struct sadb_msg*)request;
2084
2085 /* FIXME: SADB_X_SAFLAGS_INFLOW may be required, if we add an inbound policy for an IPIP SA */
2086 build_addflow(msg, satype, spi, routed ? NULL : src, routed ? NULL : dst,
2087 policy->src.net, policy->src.mask, policy->dst.net, policy->dst.mask,
2088 policy->src.proto, found != NULL);
2089
2090 this->mutex->unlock(this->mutex);
2091
2092 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2093 {
2094 DBG1(DBG_KNL, "unable to add policy %R === %R %N", src_ts, dst_ts,
2095 policy_dir_names, direction);
2096 return FAILED;
2097 }
2098 else if (out->sadb_msg_errno)
2099 {
2100 DBG1(DBG_KNL, "unable to add policy %R === %R %N: %s (%d)", src_ts, dst_ts,
2101 policy_dir_names, direction,
2102 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2103 free(out);
2104 return FAILED;
2105 }
2106 free(out);
2107
2108 this->mutex->lock(this->mutex);
2109
2110 /* we try to find the policy again and install the route if needed */
2111 if (this->policies->find_last(this->policies, NULL, (void**)&policy) != SUCCESS)
2112 {
2113 this->mutex->unlock(this->mutex);
2114 DBG2(DBG_KNL, "the policy %R === %R %N is already gone, ignoring",
2115 src_ts, dst_ts, policy_dir_names, direction);
2116 return SUCCESS;
2117 }
2118
2119 /* KLIPS requires a special route that directs traffic that matches this
2120 * policy to one of the virtual ipsec interfaces. The virtual interface
2121 * has to be attached to the physical one the traffic runs over.
2122 * This is a special case of the source route we install in other kernel
2123 * interfaces.
2124 * In the following cases we do NOT install a source route (but just a
2125 * regular route):
2126 * - we are not in tunnel mode
2127 * - we are using IPv6 (does not work correctly yet!)
2128 * - routing is disabled via strongswan.conf
2129 */
2130 if (policy->route == NULL && direction == POLICY_OUT)
2131 {
2132 char *iface;
2133 ipsec_dev_t *dev;
2134 route_entry_t *route = malloc_thing(route_entry_t);
2135 route->src_ip = NULL;
2136
2137 if (mode != MODE_TRANSPORT && src->get_family(src) != AF_INET6 &&
2138 this->install_routes)
2139 {
2140 charon->kernel_interface->get_address_by_ts(charon->kernel_interface,
2141 src_ts, &route->src_ip);
2142 }
2143
2144 if (!route->src_ip)
2145 {
2146 route->src_ip = host_create_any(src->get_family(src));
2147 }
2148
2149 /* find the virtual interface */
2150 iface = charon->kernel_interface->get_interface(charon->kernel_interface,
2151 src);
2152 if (find_ipsec_dev(this, iface, &dev) == SUCCESS)
2153 {
2154 /* above, we got either the name of a virtual or a physical
2155 * interface. for both cases it means we already have the devices
2156 * properly attached (assuming that we are exclusively attaching
2157 * ipsec devices). */
2158 dev->refcount++;
2159 }
2160 else
2161 {
2162 /* there is no record of a mapping with the returned interface.
2163 * thus, we attach the first free virtual interface we find to
2164 * it. As above we assume we are the only client fiddling with
2165 * ipsec devices. */
2166 if (this->ipsec_devices->find_first(this->ipsec_devices,
2167 (linked_list_match_t)ipsec_dev_match_free,
2168 (void**)&dev) == SUCCESS)
2169 {
2170 if (attach_ipsec_dev(dev->name, iface) == SUCCESS)
2171 {
2172 strncpy(dev->phys_name, iface, IFNAMSIZ);
2173 dev->refcount = 1;
2174 }
2175 else
2176 {
2177 DBG1(DBG_KNL, "failed to attach virtual interface %s"
2178 " to %s", dev->name, iface);
2179 this->mutex->unlock(this->mutex);
2180 free(iface);
2181 return FAILED;
2182 }
2183 }
2184 else
2185 {
2186 this->mutex->unlock(this->mutex);
2187 DBG1(DBG_KNL, "failed to attach a virtual interface to %s: no"
2188 " virtual interfaces left", iface);
2189 free(iface);
2190 return FAILED;
2191 }
2192 }
2193 free(iface);
2194 route->if_name = strdup(dev->name);
2195
2196 /* get the nexthop to dst */
2197 route->gateway = charon->kernel_interface->get_nexthop(
2198 charon->kernel_interface, dst);
2199 route->dst_net = chunk_clone(policy->dst.net->get_address(policy->dst.net));
2200 route->prefixlen = policy->dst.mask;
2201
2202 switch (charon->kernel_interface->add_route(charon->kernel_interface,
2203 route->dst_net, route->prefixlen, route->gateway,
2204 route->src_ip, route->if_name))
2205 {
2206 default:
2207 DBG1(DBG_KNL, "unable to install route for policy %R === %R",
2208 src_ts, dst_ts);
2209 /* FALL */
2210 case ALREADY_DONE:
2211 /* route exists, do not uninstall */
2212 route_entry_destroy(route);
2213 break;
2214 case SUCCESS:
2215 /* cache the installed route */
2216 policy->route = route;
2217 break;
2218 }
2219 }
2220
2221 this->mutex->unlock(this->mutex);
2222
2223 return SUCCESS;
2224 }
2225
2226 /**
2227 * Implementation of kernel_interface_t.query_policy.
2228 */
2229 static status_t query_policy(private_kernel_klips_ipsec_t *this,
2230 traffic_selector_t *src_ts,
2231 traffic_selector_t *dst_ts,
2232 policy_dir_t direction, u_int32_t *use_time)
2233 {
2234 #define IDLE_PREFIX "idle="
2235 static const char *path_eroute = "/proc/net/ipsec_eroute";
2236 static const char *path_spi = "/proc/net/ipsec_spi";
2237 FILE *file;
2238 char line[1024], src[INET6_ADDRSTRLEN + 9], dst[INET6_ADDRSTRLEN + 9];
2239 char *said = NULL, *pos;
2240 policy_entry_t *policy, *found = NULL;
2241 status_t status = FAILED;
2242
2243 if (direction == POLICY_FWD)
2244 {
2245 /* we do not install forward policies */
2246 return FAILED;
2247 }
2248
2249 DBG2(DBG_KNL, "querying policy %R === %R %N", src_ts, dst_ts,
2250 policy_dir_names, direction);
2251
2252 /* create a policy */
2253 policy = create_policy_entry(src_ts, dst_ts, direction);
2254
2255 /* find a matching policy */
2256 this->mutex->lock(this->mutex);
2257 if (this->policies->find_first(this->policies,
2258 (linked_list_match_t)policy_entry_equals, (void**)&found, policy) != SUCCESS)
2259 {
2260 this->mutex->unlock(this->mutex);
2261 DBG1(DBG_KNL, "querying policy %R === %R %N failed, not found", src_ts,
2262 dst_ts, policy_dir_names, direction);
2263 policy_entry_destroy(policy);
2264 return NOT_FOUND;
2265 }
2266 policy_entry_destroy(policy);
2267 policy = found;
2268
2269 /* src and dst selectors in KLIPS are of the form NET_ADDR/NETBITS:PROTO */
2270 snprintf(src, sizeof(src), "%H/%d:%d", policy->src.net, policy->src.mask,
2271 policy->src.proto);
2272 src[sizeof(src) - 1] = '\0';
2273 snprintf(dst, sizeof(dst), "%H/%d:%d", policy->dst.net, policy->dst.mask,
2274 policy->dst.proto);
2275 dst[sizeof(dst) - 1] = '\0';
2276
2277 this->mutex->unlock(this->mutex);
2278
2279 /* we try to find the matching eroute first */
2280 file = fopen(path_eroute, "r");
2281 if (file == NULL)
2282 {
2283 DBG1(DBG_KNL, "unable to query policy %R === %R %N: %s (%d)", src_ts,
2284 dst_ts, policy_dir_names, direction, strerror(errno), errno);
2285 return FAILED;
2286 }
2287
2288 /* read line by line where each line looks like:
2289 * packets src -> dst => said */
2290 while (fgets(line, sizeof(line), file))
2291 {
2292 enumerator_t *enumerator;
2293 char *token;
2294 int i = 0;
2295
2296 enumerator = enumerator_create_token(line, " \t", " \t\n");
2297 while (enumerator->enumerate(enumerator, &token))
2298 {
2299 switch (i++)
2300 {
2301 case 0: /* packets */
2302 continue;
2303 case 1: /* src */
2304 if (streq(token, src))
2305 {
2306 continue;
2307 }
2308 break;
2309 case 2: /* -> */
2310 continue;
2311 case 3: /* dst */
2312 if (streq(token, dst))
2313 {
2314 continue;
2315 }
2316 break;
2317 case 4: /* => */
2318 continue;
2319 case 5: /* said */
2320 said = strdup(token);
2321 break;
2322 }
2323 break;
2324 }
2325 enumerator->destroy(enumerator);
2326
2327 if (i == 5)
2328 {
2329 /* eroute matched */
2330 break;
2331 }
2332 }
2333 fclose(file);
2334
2335 if (said == NULL)
2336 {
2337 DBG1(DBG_KNL, "unable to query policy %R === %R %N: found no matching"
2338 " eroute", src_ts, dst_ts, policy_dir_names, direction);
2339 return FAILED;
2340 }
2341
2342 /* compared with the one in the spi entry the SA ID from the eroute entry
2343 * has an additional ":PROTO" appended, which we need to cut off */
2344 pos = strrchr(said, ':');
2345 *pos = '\0';
2346
2347 /* now we try to find the matching spi entry */
2348 file = fopen(path_spi, "r");
2349 if (file == NULL)
2350 {
2351 DBG1(DBG_KNL, "unable to query policy %R === %R %N: %s (%d)", src_ts,
2352 dst_ts, policy_dir_names, direction, strerror(errno), errno);
2353 return FAILED;
2354 }
2355
2356 while (fgets(line, sizeof(line), file))
2357 {
2358 if (strneq(line, said, strlen(said)))
2359 {
2360 /* fine we found the correct line, now find the idle time */
2361 u_int32_t idle_time;
2362 pos = strstr(line, IDLE_PREFIX);
2363 if (pos == NULL)
2364 {
2365 /* no idle time, i.e. this SA has not been used yet */
2366 break;
2367 }
2368 if (sscanf(pos, IDLE_PREFIX"%u", &idle_time) <= 0)
2369 {
2370 /* idle time not valid */
2371 break;
2372 }
2373
2374 *use_time = time(NULL) - idle_time;
2375 status = SUCCESS;
2376 break;
2377 }
2378 }
2379 fclose(file);
2380 free(said);
2381
2382 return status;
2383 }
2384
2385 /**
2386 * Implementation of kernel_interface_t.del_policy.
2387 */
2388 static status_t del_policy(private_kernel_klips_ipsec_t *this,
2389 traffic_selector_t *src_ts,
2390 traffic_selector_t *dst_ts,
2391 policy_dir_t direction, bool unrouted)
2392 {
2393 unsigned char request[PFKEY_BUFFER_SIZE];
2394 struct sadb_msg *msg = (struct sadb_msg*)request, *out;
2395 policy_entry_t *policy, *found = NULL;
2396 route_entry_t *route;
2397 size_t len;
2398
2399 if (direction == POLICY_FWD)
2400 {
2401 /* no forward policies for KLIPS */
2402 return SUCCESS;
2403 }
2404
2405 DBG2(DBG_KNL, "deleting policy %R === %R %N", src_ts, dst_ts,
2406 policy_dir_names, direction);
2407
2408 /* create a policy */
2409 policy = create_policy_entry(src_ts, dst_ts, direction);
2410
2411 /* find a matching policy */
2412 this->mutex->lock(this->mutex);
2413 if (this->policies->find_first(this->policies,
2414 (linked_list_match_t)policy_entry_equals, (void**)&found, policy) != SUCCESS)
2415 {
2416 this->mutex->unlock(this->mutex);
2417 DBG1(DBG_KNL, "deleting policy %R === %R %N failed, not found", src_ts,
2418 dst_ts, policy_dir_names, direction);
2419 policy_entry_destroy(policy);
2420 return NOT_FOUND;
2421 }
2422 policy_entry_destroy(policy);
2423
2424 /* decrease appropriate counter */
2425 unrouted ? found->trapcount-- : found->activecount--;
2426
2427 if (found->trapcount == 0)
2428 {
2429 /* if this policy is finally unrouted, we reset the reqid because it
2430 * may still be actively used and there might be a pending acquire for
2431 * this policy. */
2432 found->reqid = 0;
2433 }
2434
2435 if (found->activecount > 0)
2436 {
2437 /* is still used by SAs, keep in kernel */
2438 this->mutex->unlock(this->mutex);
2439 DBG2(DBG_KNL, "policy still used by another CHILD_SA, not removed");
2440 return SUCCESS;
2441 }
2442 else if (found->activecount == 0 && found->trapcount > 0)
2443 {
2444 /* for a policy that is not used actively anymore, but is still trapped
2445 * by another child SA we replace the current eroute with a %trap eroute */
2446 DBG2(DBG_KNL, "policy still routed by another CHILD_SA, not removed");
2447 memset(&request, 0, sizeof(request));
2448 build_addflow(msg, SADB_X_SATYPE_INT, htonl(SPI_TRAP), NULL, NULL,
2449 found->src.net, found->src.mask, found->dst.net,
2450 found->dst.mask, found->src.proto, TRUE);
2451 this->mutex->unlock(this->mutex);
2452 return pfkey_send_ack(this, msg);
2453 }
2454
2455 /* remove if last reference */
2456 this->policies->remove(this->policies, found, NULL);
2457 policy = found;
2458
2459 this->mutex->unlock(this->mutex);
2460
2461 memset(&request, 0, sizeof(request));
2462
2463 build_delflow(msg, 0, policy->src.net, policy->src.mask, policy->dst.net,
2464 policy->dst.mask, policy->src.proto);
2465
2466 route = policy->route;
2467 policy->route = NULL;
2468 policy_entry_destroy(policy);
2469
2470 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2471 {
2472 DBG1(DBG_KNL, "unable to delete policy %R === %R %N", src_ts, dst_ts,
2473 policy_dir_names, direction);
2474 return FAILED;
2475 }
2476 else if (out->sadb_msg_errno)
2477 {
2478 DBG1(DBG_KNL, "unable to delete policy %R === %R %N: %s (%d)", src_ts,
2479 dst_ts, policy_dir_names, direction,
2480 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2481 free(out);
2482 return FAILED;
2483 }
2484 free(out);
2485
2486 if (route)
2487 {
2488 ipsec_dev_t *dev;
2489
2490 if (charon->kernel_interface->del_route(charon->kernel_interface,
2491 route->dst_net, route->prefixlen, route->gateway,
2492 route->src_ip, route->if_name) != SUCCESS)
2493 {
2494 DBG1(DBG_KNL, "error uninstalling route installed with"
2495 " policy %R === %R %N", src_ts, dst_ts,
2496 policy_dir_names, direction);
2497 }
2498
2499 /* we have to detach the ipsec interface from the physical one over which
2500 * this SA ran (if it is not used by any other) */
2501 this->mutex->lock(this->mutex);
2502
2503 if (find_ipsec_dev(this, route->if_name, &dev) == SUCCESS)
2504 {
2505 /* fine, we found a matching device object, let's check if we have
2506 * to detach it. */
2507 if (--dev->refcount == 0)
2508 {
2509 if (detach_ipsec_dev(dev->name, dev->phys_name) != SUCCESS)
2510 {
2511 DBG1(DBG_KNL, "failed to detach virtual interface %s"
2512 " from %s", dev->name, dev->phys_name);
2513 }
2514 dev->phys_name[0] = '\0';
2515 }
2516 }
2517
2518 this->mutex->unlock(this->mutex);
2519
2520 route_entry_destroy(route);
2521 }
2522
2523 return SUCCESS;
2524 }
2525
2526 /**
2527 * Initialize the list of ipsec devices
2528 */
2529 static void init_ipsec_devices(private_kernel_klips_ipsec_t *this)
2530 {
2531 int i, count = lib->settings->get_int(lib->settings,
2532 "charon.plugins.kernel_klips.ipsec_dev_count",
2533 DEFAULT_IPSEC_DEV_COUNT);
2534
2535 for (i = 0; i < count; ++i)
2536 {
2537 ipsec_dev_t *dev = malloc_thing(ipsec_dev_t);
2538 snprintf(dev->name, IFNAMSIZ, IPSEC_DEV_PREFIX"%d", i);
2539 dev->name[IFNAMSIZ - 1] = '\0';
2540 dev->phys_name[0] = '\0';
2541 dev->refcount = 0;
2542 this->ipsec_devices->insert_last(this->ipsec_devices, dev);
2543
2544 /* detach any previously attached ipsec device */
2545 detach_ipsec_dev(dev->name, dev->phys_name);
2546 }
2547 }
2548
2549 /**
2550 * Register a socket for AQUIRE/EXPIRE messages
2551 */
2552 static status_t register_pfkey_socket(private_kernel_klips_ipsec_t *this, u_int8_t satype)
2553 {
2554 unsigned char request[PFKEY_BUFFER_SIZE];
2555 struct sadb_msg *msg, *out;
2556 size_t len;
2557
2558 memset(&request, 0, sizeof(request));
2559
2560 msg = (struct sadb_msg*)request;
2561 msg->sadb_msg_version = PF_KEY_V2;
2562 msg->sadb_msg_type = SADB_REGISTER;
2563 msg->sadb_msg_satype = satype;
2564 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2565
2566 if (pfkey_send_socket(this, this->socket_events, msg, &out, &len) != SUCCESS)
2567 {
2568 DBG1(DBG_KNL, "unable to register PF_KEY socket");
2569 return FAILED;
2570 }
2571 else if (out->sadb_msg_errno)
2572 {
2573 DBG1(DBG_KNL, "unable to register PF_KEY socket: %s (%d)",
2574 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2575 free(out);
2576 return FAILED;
2577 }
2578 free(out);
2579 return SUCCESS;
2580 }
2581
2582 /**
2583 * Implementation of kernel_interface_t.destroy.
2584 */
2585 static void destroy(private_kernel_klips_ipsec_t *this)
2586 {
2587 this->job->cancel(this->job);
2588 close(this->socket);
2589 close(this->socket_events);
2590 this->mutex_pfkey->destroy(this->mutex_pfkey);
2591 this->mutex->destroy(this->mutex);
2592 this->ipsec_devices->destroy_function(this->ipsec_devices, (void*)ipsec_dev_destroy);
2593 this->installed_sas->destroy_function(this->installed_sas, (void*)sa_entry_destroy);
2594 this->allocated_spis->destroy_function(this->allocated_spis, (void*)sa_entry_destroy);
2595 this->policies->destroy_function(this->policies, (void*)policy_entry_destroy);
2596 free(this);
2597 }
2598
2599 /*
2600 * Described in header.
2601 */
2602 kernel_klips_ipsec_t *kernel_klips_ipsec_create()
2603 {
2604 private_kernel_klips_ipsec_t *this = malloc_thing(private_kernel_klips_ipsec_t);
2605
2606 /* public functions */
2607 this->public.interface.get_spi = (status_t(*)(kernel_ipsec_t*,host_t*,host_t*,protocol_id_t,u_int32_t,u_int32_t*))get_spi;
2608 this->public.interface.get_cpi = (status_t(*)(kernel_ipsec_t*,host_t*,host_t*,u_int32_t,u_int16_t*))get_cpi;
2609 this->public.interface.add_sa = (status_t(*)(kernel_ipsec_t *,host_t*,host_t*,u_int32_t,protocol_id_t,u_int32_t,u_int64_t,u_int64_t,u_int16_t,chunk_t,u_int16_t,chunk_t,ipsec_mode_t,u_int16_t,u_int16_t,bool,bool))add_sa;
2610 this->public.interface.update_sa = (status_t(*)(kernel_ipsec_t*,u_int32_t,protocol_id_t,u_int16_t,host_t*,host_t*,host_t*,host_t*,bool,bool))update_sa;
2611 this->public.interface.del_sa = (status_t(*)(kernel_ipsec_t*,host_t*,u_int32_t,protocol_id_t,u_int16_t))del_sa;
2612 this->public.interface.add_policy = (status_t(*)(kernel_ipsec_t*,host_t*,host_t*,traffic_selector_t*,traffic_selector_t*,policy_dir_t,u_int32_t,protocol_id_t,u_int32_t,ipsec_mode_t,u_int16_t,u_int16_t,bool))add_policy;
2613 this->public.interface.query_policy = (status_t(*)(kernel_ipsec_t*,traffic_selector_t*,traffic_selector_t*,policy_dir_t,u_int32_t*))query_policy;
2614 this->public.interface.del_policy = (status_t(*)(kernel_ipsec_t*,traffic_selector_t*,traffic_selector_t*,policy_dir_t,bool))del_policy;
2615
2616 this->public.interface.destroy = (void(*)(kernel_ipsec_t*)) destroy;
2617
2618 /* private members */
2619 this->policies = linked_list_create();
2620 this->allocated_spis = linked_list_create();
2621 this->installed_sas = linked_list_create();
2622 this->ipsec_devices = linked_list_create();
2623 this->mutex = mutex_create(MUTEX_DEFAULT);
2624 this->mutex_pfkey = mutex_create(MUTEX_DEFAULT);
2625 this->install_routes = lib->settings->get_bool(lib->settings, "charon.install_routes", TRUE);
2626 this->seq = 0;
2627
2628 /* initialize ipsec devices */
2629 init_ipsec_devices(this);
2630
2631 /* create a PF_KEY socket to communicate with the kernel */
2632 this->socket = socket(PF_KEY, SOCK_RAW, PF_KEY_V2);
2633 if (this->socket <= 0)
2634 {
2635 charon->kill(charon, "unable to create PF_KEY socket");
2636 }
2637
2638 /* create a PF_KEY socket for ACQUIRE & EXPIRE */
2639 this->socket_events = socket(PF_KEY, SOCK_RAW, PF_KEY_V2);
2640 if (this->socket_events <= 0)
2641 {
2642 charon->kill(charon, "unable to create PF_KEY event socket");
2643 }
2644
2645 /* register the event socket */
2646 if (register_pfkey_socket(this, SADB_SATYPE_ESP) != SUCCESS ||
2647 register_pfkey_socket(this, SADB_SATYPE_AH) != SUCCESS)
2648 {
2649 charon->kill(charon, "unable to register PF_KEY event socket");
2650 }
2651
2652 this->job = callback_job_create((callback_job_cb_t)receive_events,
2653 this, NULL, NULL);
2654 charon->processor->queue_job(charon->processor, (job_t*)this->job);
2655
2656 return &this->public;
2657 }