schedule_job uses seconds to support time values larger than 49 days
[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 #if 0
816 /**
817 * Algorithms for IPComp, unused yet
818 */
819 static kernel_algorithm_t compression_algs[] = {
820 /* {IPCOMP_OUI, 0 }, */
821 {IPCOMP_DEFLATE, SADB_X_CALG_DEFLATE },
822 {IPCOMP_LZS, SADB_X_CALG_LZS },
823 /* {IPCOMP_LZJH, 0 }, */
824 {END_OF_LIST, 0 },
825 };
826 #endif
827
828 /**
829 * Look up a kernel algorithm ID and its key size
830 */
831 static int lookup_algorithm(kernel_algorithm_t *list, int ikev2)
832 {
833 while (list->ikev2 != END_OF_LIST)
834 {
835 if (ikev2 == list->ikev2)
836 {
837 return list->kernel;
838 }
839 list++;
840 }
841 return 0;
842 }
843
844 /**
845 * add a host behind a sadb_address extension
846 */
847 static void host2ext(host_t *host, struct sadb_address *ext)
848 {
849 sockaddr_t *host_addr = host->get_sockaddr(host);
850 socklen_t *len = host->get_sockaddr_len(host);
851 memcpy((char*)(ext + 1), host_addr, *len);
852 ext->sadb_address_len = PFKEY_LEN(sizeof(*ext) + *len);
853 }
854
855 /**
856 * add a host to the given sadb_msg
857 */
858 static void add_addr_ext(struct sadb_msg *msg, host_t *host, u_int16_t type)
859 {
860 struct sadb_address *addr = (struct sadb_address*)PFKEY_EXT_ADD_NEXT(msg);
861 addr->sadb_address_exttype = type;
862 host2ext(host, addr);
863 PFKEY_EXT_ADD(msg, addr);
864 }
865
866 /**
867 * adds an empty address extension to the given sadb_msg
868 */
869 static void add_anyaddr_ext(struct sadb_msg *msg, int family, u_int8_t type)
870 {
871 socklen_t len = (family == AF_INET) ? sizeof(struct sockaddr_in) :
872 sizeof(struct sockaddr_in6);
873 struct sadb_address *addr = (struct sadb_address*)PFKEY_EXT_ADD_NEXT(msg);
874 addr->sadb_address_exttype = type;
875 sockaddr_t *saddr = (sockaddr_t*)(addr + 1);
876 saddr->sa_family = family;
877 addr->sadb_address_len = PFKEY_LEN(sizeof(*addr) + len);
878 PFKEY_EXT_ADD(msg, addr);
879 }
880
881 /**
882 * add udp encap extensions to a sadb_msg
883 */
884 static void add_encap_ext(struct sadb_msg *msg, host_t *src, host_t *dst,
885 bool ports_only)
886 {
887 struct sadb_x_nat_t_type* nat_type;
888 struct sadb_x_nat_t_port* nat_port;
889
890 if (!ports_only)
891 {
892 nat_type = (struct sadb_x_nat_t_type*)PFKEY_EXT_ADD_NEXT(msg);
893 nat_type->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
894 nat_type->sadb_x_nat_t_type_len = PFKEY_LEN(sizeof(struct sadb_x_nat_t_type));
895 nat_type->sadb_x_nat_t_type_type = UDP_ENCAP_ESPINUDP;
896 PFKEY_EXT_ADD(msg, nat_type);
897 }
898
899 nat_port = (struct sadb_x_nat_t_port*)PFKEY_EXT_ADD_NEXT(msg);
900 nat_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_SPORT;
901 nat_port->sadb_x_nat_t_port_len = PFKEY_LEN(sizeof(struct sadb_x_nat_t_port));
902 nat_port->sadb_x_nat_t_port_port = src->get_port(src);
903 PFKEY_EXT_ADD(msg, nat_port);
904
905 nat_port = (struct sadb_x_nat_t_port*)PFKEY_EXT_ADD_NEXT(msg);
906 nat_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_DPORT;
907 nat_port->sadb_x_nat_t_port_len = PFKEY_LEN(sizeof(struct sadb_x_nat_t_port));
908 nat_port->sadb_x_nat_t_port_port = dst->get_port(dst);
909 PFKEY_EXT_ADD(msg, nat_port);
910 }
911
912 /**
913 * build an SADB_X_ADDFLOW msg
914 */
915 static void build_addflow(struct sadb_msg *msg, u_int8_t satype, u_int32_t spi,
916 host_t *src, host_t *dst, host_t *src_net, u_int8_t src_mask,
917 host_t *dst_net, u_int8_t dst_mask, u_int8_t protocol, bool replace)
918 {
919 struct sadb_sa *sa;
920 struct sadb_protocol *proto;
921 host_t *host;
922
923 msg->sadb_msg_version = PF_KEY_V2;
924 msg->sadb_msg_type = SADB_X_ADDFLOW;
925 msg->sadb_msg_satype = satype;
926 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
927
928 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
929 sa->sadb_sa_exttype = SADB_EXT_SA;
930 sa->sadb_sa_spi = spi;
931 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
932 sa->sadb_sa_flags = replace ? SADB_X_SAFLAGS_REPLACEFLOW : 0;
933 PFKEY_EXT_ADD(msg, sa);
934
935 if (!src)
936 {
937 add_anyaddr_ext(msg, src_net->get_family(src_net), SADB_EXT_ADDRESS_SRC);
938 }
939 else
940 {
941 add_addr_ext(msg, src, SADB_EXT_ADDRESS_SRC);
942 }
943
944 if (!dst)
945 {
946 add_anyaddr_ext(msg, dst_net->get_family(dst_net), SADB_EXT_ADDRESS_DST);
947 }
948 else
949 {
950 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST);
951 }
952
953 add_addr_ext(msg, src_net, SADB_X_EXT_ADDRESS_SRC_FLOW);
954 add_addr_ext(msg, dst_net, SADB_X_EXT_ADDRESS_DST_FLOW);
955
956 host = mask2host(src_net->get_family(src_net), src_mask);
957 add_addr_ext(msg, host, SADB_X_EXT_ADDRESS_SRC_MASK);
958 host->destroy(host);
959
960 host = mask2host(dst_net->get_family(dst_net), dst_mask);
961 add_addr_ext(msg, host, SADB_X_EXT_ADDRESS_DST_MASK);
962 host->destroy(host);
963
964 proto = (struct sadb_protocol*)PFKEY_EXT_ADD_NEXT(msg);
965 proto->sadb_protocol_exttype = SADB_X_EXT_PROTOCOL;
966 proto->sadb_protocol_len = PFKEY_LEN(sizeof(struct sadb_protocol));
967 proto->sadb_protocol_proto = protocol;
968 PFKEY_EXT_ADD(msg, proto);
969 }
970
971 /**
972 * build an SADB_X_DELFLOW msg
973 */
974 static void build_delflow(struct sadb_msg *msg, u_int8_t satype,
975 host_t *src_net, u_int8_t src_mask, host_t *dst_net, u_int8_t dst_mask,
976 u_int8_t protocol)
977 {
978 struct sadb_protocol *proto;
979 host_t *host;
980
981 msg->sadb_msg_version = PF_KEY_V2;
982 msg->sadb_msg_type = SADB_X_DELFLOW;
983 msg->sadb_msg_satype = satype;
984 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
985
986 add_addr_ext(msg, src_net, SADB_X_EXT_ADDRESS_SRC_FLOW);
987 add_addr_ext(msg, dst_net, SADB_X_EXT_ADDRESS_DST_FLOW);
988
989 host = mask2host(src_net->get_family(src_net),
990 src_mask);
991 add_addr_ext(msg, host, SADB_X_EXT_ADDRESS_SRC_MASK);
992 host->destroy(host);
993
994 host = mask2host(dst_net->get_family(dst_net),
995 dst_mask);
996 add_addr_ext(msg, host, SADB_X_EXT_ADDRESS_DST_MASK);
997 host->destroy(host);
998
999 proto = (struct sadb_protocol*)PFKEY_EXT_ADD_NEXT(msg);
1000 proto->sadb_protocol_exttype = SADB_X_EXT_PROTOCOL;
1001 proto->sadb_protocol_len = PFKEY_LEN(sizeof(struct sadb_protocol));
1002 proto->sadb_protocol_proto = protocol;
1003 PFKEY_EXT_ADD(msg, proto);
1004 }
1005
1006 /**
1007 * Parses a pfkey message received from the kernel
1008 */
1009 static status_t parse_pfkey_message(struct sadb_msg *msg, pfkey_msg_t *out)
1010 {
1011 struct sadb_ext* ext;
1012 size_t len;
1013
1014 memset(out, 0, sizeof(pfkey_msg_t));
1015 out->msg = msg;
1016
1017 len = msg->sadb_msg_len;
1018 len -= PFKEY_LEN(sizeof(struct sadb_msg));
1019
1020 ext = (struct sadb_ext*)(((char*)msg) + sizeof(struct sadb_msg));
1021
1022 while (len >= PFKEY_LEN(sizeof(struct sadb_ext)))
1023 {
1024 if (ext->sadb_ext_len < PFKEY_LEN(sizeof(struct sadb_ext)) ||
1025 ext->sadb_ext_len > len)
1026 {
1027 DBG1(DBG_KNL, "length of PF_KEY extension (%d) is invalid", ext->sadb_ext_type);
1028 break;
1029 }
1030
1031 if ((ext->sadb_ext_type > SADB_EXT_MAX) || (!ext->sadb_ext_type))
1032 {
1033 DBG1(DBG_KNL, "type of PF_KEY extension (%d) is invalid", ext->sadb_ext_type);
1034 break;
1035 }
1036
1037 if (out->ext[ext->sadb_ext_type])
1038 {
1039 DBG1(DBG_KNL, "duplicate PF_KEY extension of type (%d)", ext->sadb_ext_type);
1040 break;
1041 }
1042
1043 out->ext[ext->sadb_ext_type] = ext;
1044 ext = PFKEY_EXT_NEXT_LEN(ext, len);
1045 }
1046
1047 if (len)
1048 {
1049 DBG1(DBG_KNL, "PF_KEY message length is invalid");
1050 return FAILED;
1051 }
1052
1053 return SUCCESS;
1054 }
1055
1056 /**
1057 * Send a message to a specific PF_KEY socket and handle the response.
1058 */
1059 static status_t pfkey_send_socket(private_kernel_klips_ipsec_t *this, int socket,
1060 struct sadb_msg *in, struct sadb_msg **out, size_t *out_len)
1061 {
1062 unsigned char buf[PFKEY_BUFFER_SIZE];
1063 struct sadb_msg *msg;
1064 int in_len, len;
1065
1066 this->mutex_pfkey->lock(this->mutex_pfkey);
1067
1068 in->sadb_msg_seq = ++this->seq;
1069 in->sadb_msg_pid = getpid();
1070
1071 in_len = PFKEY_USER_LEN(in->sadb_msg_len);
1072
1073 while (TRUE)
1074 {
1075 len = send(socket, in, in_len, 0);
1076
1077 if (len != in_len)
1078 {
1079 switch (errno)
1080 {
1081 case EINTR:
1082 /* interrupted, try again */
1083 continue;
1084 case EINVAL:
1085 case EEXIST:
1086 case ESRCH:
1087 /* we should also get a response for these from KLIPS */
1088 break;
1089 default:
1090 this->mutex_pfkey->unlock(this->mutex_pfkey);
1091 DBG1(DBG_KNL, "error sending to PF_KEY socket: %s (%d)",
1092 strerror(errno), errno);
1093 return FAILED;
1094 }
1095 }
1096 break;
1097 }
1098
1099 while (TRUE)
1100 {
1101 msg = (struct sadb_msg*)buf;
1102
1103 len = recv(socket, buf, sizeof(buf), 0);
1104
1105 if (len < 0)
1106 {
1107 if (errno == EINTR)
1108 {
1109 DBG1(DBG_KNL, "got interrupted");
1110 /* interrupted, try again */
1111 continue;
1112 }
1113 this->mutex_pfkey->unlock(this->mutex_pfkey);
1114 DBG1(DBG_KNL, "error reading from PF_KEY socket: %s", strerror(errno));
1115 return FAILED;
1116 }
1117 if (len < sizeof(struct sadb_msg) ||
1118 msg->sadb_msg_len < PFKEY_LEN(sizeof(struct sadb_msg)))
1119 {
1120 this->mutex_pfkey->unlock(this->mutex_pfkey);
1121 DBG1(DBG_KNL, "received corrupted PF_KEY message");
1122 return FAILED;
1123 }
1124 if (msg->sadb_msg_len > len / PFKEY_ALIGNMENT)
1125 {
1126 this->mutex_pfkey->unlock(this->mutex_pfkey);
1127 DBG1(DBG_KNL, "buffer was too small to receive the complete PF_KEY message");
1128 return FAILED;
1129 }
1130 if (msg->sadb_msg_pid != in->sadb_msg_pid)
1131 {
1132 DBG2(DBG_KNL, "received PF_KEY message is not intended for us");
1133 continue;
1134 }
1135 if (msg->sadb_msg_seq != this->seq)
1136 {
1137 DBG1(DBG_KNL, "received PF_KEY message with invalid sequence number,"
1138 " was %d expected %d", msg->sadb_msg_seq, this->seq);
1139 if (msg->sadb_msg_seq < this->seq)
1140 {
1141 continue;
1142 }
1143 this->mutex_pfkey->unlock(this->mutex_pfkey);
1144 return FAILED;
1145 }
1146 if (msg->sadb_msg_type != in->sadb_msg_type)
1147 {
1148 DBG2(DBG_KNL, "received PF_KEY message of wrong type,"
1149 " was %d expected %d, ignoring",
1150 msg->sadb_msg_type, in->sadb_msg_type);
1151 }
1152 break;
1153 }
1154
1155 *out_len = len;
1156 *out = (struct sadb_msg*)malloc(len);
1157 memcpy(*out, buf, len);
1158
1159 this->mutex_pfkey->unlock(this->mutex_pfkey);
1160
1161 return SUCCESS;
1162 }
1163
1164 /**
1165 * Send a message to the default PF_KEY socket.
1166 */
1167 static status_t pfkey_send(private_kernel_klips_ipsec_t *this,
1168 struct sadb_msg *in, struct sadb_msg **out, size_t *out_len)
1169 {
1170 return pfkey_send_socket(this, this->socket, in, out, out_len);
1171 }
1172
1173 /**
1174 * Send a message to the default PF_KEY socket and handle the response.
1175 */
1176 static status_t pfkey_send_ack(private_kernel_klips_ipsec_t *this, struct sadb_msg *in)
1177 {
1178 struct sadb_msg *out;
1179 size_t len;
1180
1181 if (pfkey_send(this, in, &out, &len) != SUCCESS)
1182 {
1183 return FAILED;
1184 }
1185 else if (out->sadb_msg_errno)
1186 {
1187 DBG1(DBG_KNL, "PF_KEY error: %s (%d)",
1188 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1189 free(out);
1190 return FAILED;
1191 }
1192 free(out);
1193 return SUCCESS;
1194 }
1195
1196 /**
1197 * Add an eroute to KLIPS
1198 */
1199 static status_t add_eroute(private_kernel_klips_ipsec_t *this, u_int8_t satype,
1200 u_int32_t spi, host_t *src, host_t *dst, host_t *src_net, u_int8_t src_mask,
1201 host_t *dst_net, u_int8_t dst_mask, u_int8_t protocol, bool replace)
1202 {
1203 unsigned char request[PFKEY_BUFFER_SIZE];
1204 struct sadb_msg *msg = (struct sadb_msg*)request;
1205
1206 memset(&request, 0, sizeof(request));
1207
1208 build_addflow(msg, satype, spi, src, dst, src_net, src_mask,
1209 dst_net, dst_mask, protocol, replace);
1210
1211 return pfkey_send_ack(this, msg);
1212 }
1213
1214 /**
1215 * Delete an eroute fom KLIPS
1216 */
1217 static status_t del_eroute(private_kernel_klips_ipsec_t *this, u_int8_t satype,
1218 host_t *src_net, u_int8_t src_mask, host_t *dst_net, u_int8_t dst_mask,
1219 u_int8_t protocol)
1220 {
1221 unsigned char request[PFKEY_BUFFER_SIZE];
1222 struct sadb_msg *msg = (struct sadb_msg*)request;
1223
1224 memset(&request, 0, sizeof(request));
1225
1226 build_delflow(msg, satype, src_net, src_mask, dst_net, dst_mask, protocol);
1227
1228 return pfkey_send_ack(this, msg);
1229 }
1230
1231 /**
1232 * Process a SADB_ACQUIRE message from the kernel
1233 */
1234 static void process_acquire(private_kernel_klips_ipsec_t *this, struct sadb_msg* msg)
1235 {
1236 pfkey_msg_t response;
1237 host_t *src, *dst;
1238 u_int32_t reqid;
1239 u_int8_t proto;
1240 policy_entry_t *policy;
1241 job_t *job;
1242
1243 switch (msg->sadb_msg_satype)
1244 {
1245 case SADB_SATYPE_UNSPEC:
1246 case SADB_SATYPE_ESP:
1247 case SADB_SATYPE_AH:
1248 break;
1249 default:
1250 /* acquire for AH/ESP only */
1251 return;
1252 }
1253
1254 if (parse_pfkey_message(msg, &response) != SUCCESS)
1255 {
1256 DBG1(DBG_KNL, "parsing SADB_ACQUIRE from kernel failed");
1257 return;
1258 }
1259
1260 /* KLIPS provides us only with the source and destination address,
1261 * and the transport protocol of the packet that triggered the policy.
1262 * we use this information to find a matching policy in our cache.
1263 * because KLIPS installs a narrow %hold eroute covering only this information,
1264 * we replace both the %trap and this %hold eroutes with a broader %hold
1265 * eroute covering the whole policy */
1266 src = host_create_from_sockaddr((sockaddr_t*)(response.src + 1));
1267 dst = host_create_from_sockaddr((sockaddr_t*)(response.dst + 1));
1268 proto = response.src->sadb_address_proto;
1269 if (!src || !dst || src->get_family(src) != dst->get_family(dst))
1270 {
1271 DBG1(DBG_KNL, "received an SADB_ACQUIRE with invalid hosts");
1272 return;
1273 }
1274
1275 DBG2(DBG_KNL, "received an SADB_ACQUIRE for %H == %H : %d", src, dst, proto);
1276 this->mutex->lock(this->mutex);
1277 if (this->policies->find_first(this->policies,
1278 (linked_list_match_t)policy_entry_match_byaddrs,
1279 (void**)&policy, src, dst) != SUCCESS)
1280 {
1281 this->mutex->unlock(this->mutex);
1282 DBG1(DBG_KNL, "received an SADB_ACQUIRE, but found no matching policy");
1283 return;
1284 }
1285 if ((reqid = policy->reqid) == 0)
1286 {
1287 this->mutex->unlock(this->mutex);
1288 DBG1(DBG_KNL, "received an SADB_ACQUIRE, but policy is not routed anymore");
1289 return;
1290 }
1291
1292 /* add a broad %hold eroute that replaces the %trap eroute */
1293 add_eroute(this, SADB_X_SATYPE_INT, htonl(SPI_HOLD), NULL, NULL,
1294 policy->src.net, policy->src.mask, policy->dst.net, policy->dst.mask,
1295 policy->src.proto, TRUE);
1296
1297 /* remove the narrow %hold eroute installed by KLIPS */
1298 del_eroute(this, SADB_X_SATYPE_INT, src, 32, dst, 32, proto);
1299
1300 this->mutex->unlock(this->mutex);
1301
1302 DBG2(DBG_KNL, "received an SADB_ACQUIRE");
1303 DBG1(DBG_KNL, "creating acquire job for CHILD_SA with reqid {%d}", reqid);
1304 job = (job_t*)acquire_job_create(reqid, NULL, NULL);
1305 charon->processor->queue_job(charon->processor, job);
1306 }
1307
1308 /**
1309 * Process a SADB_X_NAT_T_NEW_MAPPING message from the kernel
1310 */
1311 static void process_mapping(private_kernel_klips_ipsec_t *this, struct sadb_msg* msg)
1312 {
1313 pfkey_msg_t response;
1314 u_int32_t spi, reqid;
1315 host_t *old_src, *new_src;
1316 job_t *job;
1317
1318 DBG2(DBG_KNL, "received an SADB_X_NAT_T_NEW_MAPPING");
1319
1320 if (parse_pfkey_message(msg, &response) != SUCCESS)
1321 {
1322 DBG1(DBG_KNL, "parsing SADB_X_NAT_T_NEW_MAPPING from kernel failed");
1323 return;
1324 }
1325
1326 spi = response.sa->sadb_sa_spi;
1327
1328 if (proto_satype2ike(msg->sadb_msg_satype) == PROTO_ESP)
1329 {
1330 sa_entry_t *sa;
1331 sockaddr_t *addr = (sockaddr_t*)(response.src + 1);
1332 old_src = host_create_from_sockaddr(addr);
1333
1334 this->mutex->lock(this->mutex);
1335 if (!old_src || this->installed_sas->find_first(this->installed_sas,
1336 (linked_list_match_t)sa_entry_match_encapbysrc,
1337 (void**)&sa, &spi, old_src) != SUCCESS)
1338 {
1339 this->mutex->unlock(this->mutex);
1340 DBG1(DBG_KNL, "received an SADB_X_NAT_T_NEW_MAPPING, but found no matching SA");
1341 return;
1342 }
1343 reqid = sa->reqid;
1344 this->mutex->unlock(this->mutex);
1345
1346 addr = (sockaddr_t*)(response.dst + 1);
1347 switch (addr->sa_family)
1348 {
1349 case AF_INET:
1350 {
1351 struct sockaddr_in *sin = (struct sockaddr_in*)addr;
1352 sin->sin_port = htons(response.x_natt_dport->sadb_x_nat_t_port_port);
1353 }
1354 case AF_INET6:
1355 {
1356 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)addr;
1357 sin6->sin6_port = htons(response.x_natt_dport->sadb_x_nat_t_port_port);
1358 }
1359 default:
1360 break;
1361 }
1362 new_src = host_create_from_sockaddr(addr);
1363 if (new_src)
1364 {
1365 DBG1(DBG_KNL, "NAT mappings of ESP CHILD_SA with SPI %.8x and"
1366 " reqid {%d} changed, queuing update job", ntohl(spi), reqid);
1367 job = (job_t*)update_sa_job_create(reqid, new_src);
1368 charon->processor->queue_job(charon->processor, job);
1369 }
1370 }
1371 }
1372
1373 /**
1374 * Receives events from kernel
1375 */
1376 static job_requeue_t receive_events(private_kernel_klips_ipsec_t *this)
1377 {
1378 unsigned char buf[PFKEY_BUFFER_SIZE];
1379 struct sadb_msg *msg = (struct sadb_msg*)buf;
1380 int len, oldstate;
1381
1382 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate);
1383 len = recv(this->socket_events, buf, sizeof(buf), 0);
1384 pthread_setcancelstate(oldstate, NULL);
1385
1386 if (len < 0)
1387 {
1388 switch (errno)
1389 {
1390 case EINTR:
1391 /* interrupted, try again */
1392 return JOB_REQUEUE_DIRECT;
1393 case EAGAIN:
1394 /* no data ready, select again */
1395 return JOB_REQUEUE_DIRECT;
1396 default:
1397 DBG1(DBG_KNL, "unable to receive from PF_KEY event socket");
1398 sleep(1);
1399 return JOB_REQUEUE_FAIR;
1400 }
1401 }
1402
1403 if (len < sizeof(struct sadb_msg) ||
1404 msg->sadb_msg_len < PFKEY_LEN(sizeof(struct sadb_msg)))
1405 {
1406 DBG2(DBG_KNL, "received corrupted PF_KEY message");
1407 return JOB_REQUEUE_DIRECT;
1408 }
1409 if (msg->sadb_msg_pid != 0)
1410 { /* not from kernel. not interested, try another one */
1411 return JOB_REQUEUE_DIRECT;
1412 }
1413 if (msg->sadb_msg_len > len / PFKEY_ALIGNMENT)
1414 {
1415 DBG1(DBG_KNL, "buffer was too small to receive the complete PF_KEY message");
1416 return JOB_REQUEUE_DIRECT;
1417 }
1418
1419 switch (msg->sadb_msg_type)
1420 {
1421 case SADB_ACQUIRE:
1422 process_acquire(this, msg);
1423 break;
1424 case SADB_EXPIRE:
1425 /* SADB_EXPIRE events in KLIPS are only triggered by traffic (even for
1426 * the time based limits). So if there is no traffic for a longer
1427 * period than configured as hard limit, we wouldn't be able to rekey
1428 * the SA and just receive the hard expire and thus delete the SA.
1429 * To avoid this behavior and to make charon behave as with the other
1430 * kernel plugins, we implement the expiration of SAs ourselves. */
1431 break;
1432 case SADB_X_NAT_T_NEW_MAPPING:
1433 process_mapping(this, msg);
1434 break;
1435 default:
1436 break;
1437 }
1438
1439 return JOB_REQUEUE_DIRECT;
1440 }
1441
1442 typedef enum {
1443 /** an SPI has expired */
1444 EXPIRE_TYPE_SPI,
1445 /** a CHILD_SA has to be rekeyed */
1446 EXPIRE_TYPE_SOFT,
1447 /** a CHILD_SA has to be deleted */
1448 EXPIRE_TYPE_HARD
1449 } expire_type_t;
1450
1451 typedef struct sa_expire_t sa_expire_t;
1452
1453 struct sa_expire_t {
1454 /** kernel interface */
1455 private_kernel_klips_ipsec_t *this;
1456 /** the SPI of the expiring SA */
1457 u_int32_t spi;
1458 /** the protocol of the expiring SA */
1459 protocol_id_t protocol;
1460 /** the reqid of the expiring SA*/
1461 u_int32_t reqid;
1462 /** what type of expire this is */
1463 expire_type_t type;
1464 };
1465
1466 /**
1467 * Called when an SA expires
1468 */
1469 static job_requeue_t sa_expires(sa_expire_t *expire)
1470 {
1471 private_kernel_klips_ipsec_t *this = expire->this;
1472 protocol_id_t protocol = expire->protocol;
1473 u_int32_t spi = expire->spi, reqid = expire->reqid;
1474 bool hard = expire->type != EXPIRE_TYPE_SOFT;
1475 sa_entry_t *cached_sa;
1476 linked_list_t *list;
1477 job_t *job;
1478
1479 /* for an expired SPI we first check whether the CHILD_SA got installed
1480 * in the meantime, for expired SAs we check whether they are still installed */
1481 list = expire->type == EXPIRE_TYPE_SPI ? this->allocated_spis : this->installed_sas;
1482
1483 this->mutex->lock(this->mutex);
1484 if (list->find_first(list, (linked_list_match_t)sa_entry_match_byid,
1485 (void**)&cached_sa, &protocol, &spi, &reqid) != SUCCESS)
1486 {
1487 /* we found no entry:
1488 * - for SPIs, a CHILD_SA has been installed
1489 * - for SAs, the CHILD_SA has already been deleted */
1490 this->mutex->unlock(this->mutex);
1491 return JOB_REQUEUE_NONE;
1492 }
1493 else
1494 {
1495 list->remove(list, cached_sa, NULL);
1496 sa_entry_destroy(cached_sa);
1497 }
1498 this->mutex->unlock(this->mutex);
1499
1500 DBG2(DBG_KNL, "%N CHILD_SA with SPI %.8x and reqid {%d} expired",
1501 protocol_id_names, protocol, ntohl(spi), reqid);
1502
1503 DBG1(DBG_KNL, "creating %s job for %N CHILD_SA with SPI %.8x and reqid {%d}",
1504 hard ? "delete" : "rekey", protocol_id_names,
1505 protocol, ntohl(spi), reqid);
1506 if (hard)
1507 {
1508 job = (job_t*)delete_child_sa_job_create(reqid, protocol, spi);
1509 }
1510 else
1511 {
1512 job = (job_t*)rekey_child_sa_job_create(reqid, protocol, spi);
1513 }
1514 charon->processor->queue_job(charon->processor, job);
1515 return JOB_REQUEUE_NONE;
1516 }
1517
1518 /**
1519 * Schedule an expire job for an SA. Time is in seconds.
1520 */
1521 static void schedule_expire(private_kernel_klips_ipsec_t *this,
1522 protocol_id_t protocol, u_int32_t spi,
1523 u_int32_t reqid, expire_type_t type, u_int32_t time)
1524 {
1525 callback_job_t *job;
1526 sa_expire_t *expire = malloc_thing(sa_expire_t);
1527 expire->this = this;
1528 expire->protocol = protocol;
1529 expire->spi = spi;
1530 expire->reqid = reqid;
1531 expire->type = type;
1532 job = callback_job_create((callback_job_cb_t)sa_expires, expire, free, NULL);
1533 charon->scheduler->schedule_job(charon->scheduler, (job_t*)job, time);
1534 }
1535
1536 /**
1537 * Implementation of kernel_interface_t.get_spi.
1538 */
1539 static status_t get_spi(private_kernel_klips_ipsec_t *this,
1540 host_t *src, host_t *dst,
1541 protocol_id_t protocol, u_int32_t reqid,
1542 u_int32_t *spi)
1543 {
1544 /* we cannot use SADB_GETSPI because KLIPS does not allow us to set the
1545 * NAT-T type in an SADB_UPDATE which we would have to use to update the
1546 * implicitly created SA.
1547 */
1548 rng_t *rng;
1549 u_int32_t spi_gen;
1550
1551 rng = lib->crypto->create_rng(lib->crypto, RNG_WEAK);
1552 if (!rng)
1553 {
1554 DBG1(DBG_KNL, "allocating SPI failed: no RNG");
1555 return FAILED;
1556 }
1557 rng->get_bytes(rng, sizeof(spi_gen), (void*)&spi_gen);
1558 rng->destroy(rng);
1559
1560 /* charon's SPIs lie within the range from 0xc0000000 to 0xcFFFFFFF */
1561 spi_gen = 0xc0000000 | (spi_gen & 0x0FFFFFFF);
1562
1563 DBG2(DBG_KNL, "allocated SPI %.8x for %N SA between %#H..%#H",
1564 spi_gen, protocol_id_names, protocol, src, dst);
1565
1566 *spi = htonl(spi_gen);
1567
1568 this->mutex->lock(this->mutex);
1569 this->allocated_spis->insert_last(this->allocated_spis,
1570 create_sa_entry(protocol, *spi, reqid, NULL, NULL, FALSE, TRUE));
1571 this->mutex->unlock(this->mutex);
1572 schedule_expire(this, protocol, *spi, reqid, EXPIRE_TYPE_SPI, SPI_TIMEOUT);
1573
1574 return SUCCESS;
1575 }
1576
1577 /**
1578 * Implementation of kernel_interface_t.get_cpi.
1579 */
1580 static status_t get_cpi(private_kernel_klips_ipsec_t *this,
1581 host_t *src, host_t *dst,
1582 u_int32_t reqid, u_int16_t *cpi)
1583 {
1584 return FAILED;
1585 }
1586
1587 /**
1588 * Add a pseudo IPIP SA for tunnel mode with KLIPS.
1589 */
1590 static status_t add_ipip_sa(private_kernel_klips_ipsec_t *this,
1591 host_t *src, host_t *dst, u_int32_t spi, u_int32_t reqid)
1592 {
1593 unsigned char request[PFKEY_BUFFER_SIZE];
1594 struct sadb_msg *msg, *out;
1595 struct sadb_sa *sa;
1596 size_t len;
1597
1598 memset(&request, 0, sizeof(request));
1599
1600 DBG2(DBG_KNL, "adding pseudo IPIP SA with SPI %.8x and reqid {%d}", ntohl(spi), reqid);
1601
1602 msg = (struct sadb_msg*)request;
1603 msg->sadb_msg_version = PF_KEY_V2;
1604 msg->sadb_msg_type = SADB_ADD;
1605 msg->sadb_msg_satype = SADB_X_SATYPE_IPIP;
1606 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1607
1608 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1609 sa->sadb_sa_exttype = SADB_EXT_SA;
1610 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1611 sa->sadb_sa_spi = spi;
1612 sa->sadb_sa_state = SADB_SASTATE_MATURE;
1613 PFKEY_EXT_ADD(msg, sa);
1614
1615 add_addr_ext(msg, src, SADB_EXT_ADDRESS_SRC);
1616 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST);
1617
1618 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1619 {
1620 DBG1(DBG_KNL, "unable to add pseudo IPIP SA with SPI %.8x", ntohl(spi));
1621 return FAILED;
1622 }
1623 else if (out->sadb_msg_errno)
1624 {
1625 DBG1(DBG_KNL, "unable to add pseudo IPIP SA with SPI %.8x: %s (%d)",
1626 ntohl(spi), strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1627 free(out);
1628 return FAILED;
1629 }
1630
1631 free(out);
1632 return SUCCESS;
1633 }
1634
1635 /**
1636 * group the IPIP SA required for tunnel mode with the outer SA
1637 */
1638 static status_t group_ipip_sa(private_kernel_klips_ipsec_t *this,
1639 host_t *src, host_t *dst, u_int32_t spi,
1640 protocol_id_t protocol, u_int32_t reqid)
1641 {
1642 unsigned char request[PFKEY_BUFFER_SIZE];
1643 struct sadb_msg *msg, *out;
1644 struct sadb_sa *sa;
1645 struct sadb_x_satype *satype;
1646 size_t len;
1647
1648 memset(&request, 0, sizeof(request));
1649
1650 DBG2(DBG_KNL, "grouping SAs with SPI %.8x and reqid {%d}", ntohl(spi), reqid);
1651
1652 msg = (struct sadb_msg*)request;
1653 msg->sadb_msg_version = PF_KEY_V2;
1654 msg->sadb_msg_type = SADB_X_GRPSA;
1655 msg->sadb_msg_satype = SADB_X_SATYPE_IPIP;
1656 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1657
1658 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1659 sa->sadb_sa_exttype = SADB_EXT_SA;
1660 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1661 sa->sadb_sa_spi = spi;
1662 sa->sadb_sa_state = SADB_SASTATE_MATURE;
1663 PFKEY_EXT_ADD(msg, sa);
1664
1665 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST);
1666
1667 satype = (struct sadb_x_satype*)PFKEY_EXT_ADD_NEXT(msg);
1668 satype->sadb_x_satype_exttype = SADB_X_EXT_SATYPE2;
1669 satype->sadb_x_satype_len = PFKEY_LEN(sizeof(struct sadb_x_satype));
1670 satype->sadb_x_satype_satype = proto_ike2satype(protocol);
1671 PFKEY_EXT_ADD(msg, satype);
1672
1673 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1674 sa->sadb_sa_exttype = SADB_X_EXT_SA2;
1675 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1676 sa->sadb_sa_spi = spi;
1677 sa->sadb_sa_state = SADB_SASTATE_MATURE;
1678 PFKEY_EXT_ADD(msg, sa);
1679
1680 add_addr_ext(msg, dst, SADB_X_EXT_ADDRESS_DST2);
1681
1682 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1683 {
1684 DBG1(DBG_KNL, "unable to group SAs with SPI %.8x", ntohl(spi));
1685 return FAILED;
1686 }
1687 else if (out->sadb_msg_errno)
1688 {
1689 DBG1(DBG_KNL, "unable to group SAs with SPI %.8x: %s (%d)",
1690 ntohl(spi), strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1691 free(out);
1692 return FAILED;
1693 }
1694
1695 free(out);
1696 return SUCCESS;
1697 }
1698
1699 /**
1700 * Implementation of kernel_interface_t.add_sa.
1701 */
1702 static status_t add_sa(private_kernel_klips_ipsec_t *this,
1703 host_t *src, host_t *dst, u_int32_t spi,
1704 protocol_id_t protocol, u_int32_t reqid,
1705 u_int64_t expire_soft, u_int64_t expire_hard,
1706 u_int16_t enc_alg, chunk_t enc_key,
1707 u_int16_t int_alg, chunk_t int_key,
1708 ipsec_mode_t mode, u_int16_t ipcomp, u_int16_t cpi,
1709 bool encap, bool inbound)
1710 {
1711 unsigned char request[PFKEY_BUFFER_SIZE];
1712 struct sadb_msg *msg, *out;
1713 struct sadb_sa *sa;
1714 struct sadb_key *key;
1715 size_t len;
1716
1717 if (inbound)
1718 {
1719 /* for inbound SAs we allocated an SPI via get_spi, so we first check
1720 * whether that SPI has already expired (race condition) */
1721 sa_entry_t *alloc_spi;
1722 this->mutex->lock(this->mutex);
1723 if (this->allocated_spis->find_first(this->allocated_spis,
1724 (linked_list_match_t)sa_entry_match_byid, (void**)&alloc_spi,
1725 &protocol, &spi, &reqid) != SUCCESS)
1726 {
1727 this->mutex->unlock(this->mutex);
1728 DBG1(DBG_KNL, "allocated SPI %.8x has already expired", ntohl(spi));
1729 return FAILED;
1730 }
1731 else
1732 {
1733 this->allocated_spis->remove(this->allocated_spis, alloc_spi, NULL);
1734 sa_entry_destroy(alloc_spi);
1735 }
1736 this->mutex->unlock(this->mutex);
1737 }
1738
1739 memset(&request, 0, sizeof(request));
1740
1741 DBG2(DBG_KNL, "adding SAD entry with SPI %.8x and reqid {%d}", ntohl(spi), reqid);
1742
1743 msg = (struct sadb_msg*)request;
1744 msg->sadb_msg_version = PF_KEY_V2;
1745 msg->sadb_msg_type = SADB_ADD;
1746 msg->sadb_msg_satype = proto_ike2satype(protocol);
1747 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1748
1749 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1750 sa->sadb_sa_exttype = SADB_EXT_SA;
1751 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1752 sa->sadb_sa_spi = spi;
1753 sa->sadb_sa_state = SADB_SASTATE_MATURE;
1754 sa->sadb_sa_replay = (protocol == IPPROTO_COMP) ? 0 : 32;
1755 sa->sadb_sa_auth = lookup_algorithm(integrity_algs, int_alg);
1756 sa->sadb_sa_encrypt = lookup_algorithm(encryption_algs, enc_alg);
1757 PFKEY_EXT_ADD(msg, sa);
1758
1759 add_addr_ext(msg, src, SADB_EXT_ADDRESS_SRC);
1760 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST);
1761
1762 if (enc_alg != ENCR_UNDEFINED)
1763 {
1764 if (!sa->sadb_sa_encrypt)
1765 {
1766 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1767 encryption_algorithm_names, enc_alg);
1768 return FAILED;
1769 }
1770 DBG2(DBG_KNL, " using encryption algorithm %N with key size %d",
1771 encryption_algorithm_names, enc_alg, enc_key.len * 8);
1772
1773 key = (struct sadb_key*)PFKEY_EXT_ADD_NEXT(msg);
1774 key->sadb_key_exttype = SADB_EXT_KEY_ENCRYPT;
1775 key->sadb_key_bits = enc_key.len * 8;
1776 key->sadb_key_len = PFKEY_LEN(sizeof(struct sadb_key) + enc_key.len);
1777 memcpy(key + 1, enc_key.ptr, enc_key.len);
1778
1779 PFKEY_EXT_ADD(msg, key);
1780 }
1781
1782 if (int_alg != AUTH_UNDEFINED)
1783 {
1784 if (!sa->sadb_sa_auth)
1785 {
1786 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1787 integrity_algorithm_names, int_alg);
1788 return FAILED;
1789 }
1790 DBG2(DBG_KNL, " using integrity algorithm %N with key size %d",
1791 integrity_algorithm_names, int_alg, int_key.len * 8);
1792
1793 key = (struct sadb_key*)PFKEY_EXT_ADD_NEXT(msg);
1794 key->sadb_key_exttype = SADB_EXT_KEY_AUTH;
1795 key->sadb_key_bits = int_key.len * 8;
1796 key->sadb_key_len = PFKEY_LEN(sizeof(struct sadb_key) + int_key.len);
1797 memcpy(key + 1, int_key.ptr, int_key.len);
1798
1799 PFKEY_EXT_ADD(msg, key);
1800 }
1801
1802 if (ipcomp != IPCOMP_NONE)
1803 {
1804 /*TODO*/
1805 }
1806
1807 if (encap)
1808 {
1809 add_encap_ext(msg, src, dst, FALSE);
1810 }
1811
1812 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1813 {
1814 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x", ntohl(spi));
1815 return FAILED;
1816 }
1817 else if (out->sadb_msg_errno)
1818 {
1819 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x: %s (%d)",
1820 ntohl(spi), strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1821 free(out);
1822 return FAILED;
1823 }
1824 free(out);
1825
1826 /* for tunnel mode SAs we have to install an additional IPIP SA and
1827 * group the two SAs together */
1828 if (mode == MODE_TUNNEL)
1829 {
1830 if (add_ipip_sa(this, src, dst, spi, reqid) != SUCCESS ||
1831 group_ipip_sa(this, src, dst, spi, protocol, reqid) != SUCCESS)
1832 {
1833 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x", ntohl(spi));
1834 return FAILED;
1835 }
1836 }
1837
1838 this->mutex->lock(this->mutex);
1839 /* we cache this SA for two reasons:
1840 * - in case an SADB_X_NAT_T_MAPPING_NEW event occurs (we need to find the reqid then)
1841 * - to decide if an expired SA is still installed */
1842 this->installed_sas->insert_last(this->installed_sas,
1843 create_sa_entry(protocol, spi, reqid, src, dst, encap, inbound));
1844 this->mutex->unlock(this->mutex);
1845
1846 /* Although KLIPS supports SADB_EXT_LIFETIME_SOFT/HARD, we handle the lifetime
1847 * of SAs manually in the plugin. Refer to the comments in receive_events()
1848 * for details. */
1849 if (expire_soft)
1850 {
1851 schedule_expire(this, protocol, spi, reqid, EXPIRE_TYPE_SOFT, expire_soft);
1852 }
1853
1854 if (expire_hard)
1855 {
1856 schedule_expire(this, protocol, spi, reqid, EXPIRE_TYPE_HARD, expire_hard);
1857 }
1858
1859 return SUCCESS;
1860 }
1861
1862 /**
1863 * Implementation of kernel_interface_t.update_sa.
1864 */
1865 static status_t update_sa(private_kernel_klips_ipsec_t *this,
1866 u_int32_t spi, protocol_id_t protocol, u_int16_t cpi,
1867 host_t *src, host_t *dst,
1868 host_t *new_src, host_t *new_dst,
1869 bool encap, bool new_encap)
1870 {
1871 unsigned char request[PFKEY_BUFFER_SIZE];
1872 struct sadb_msg *msg, *out;
1873 struct sadb_sa *sa;
1874 size_t len;
1875
1876 /* we can't update the SA if any of the ip addresses have changed.
1877 * that's because we can't use SADB_UPDATE and by deleting and readding the
1878 * SA the sequence numbers would get lost */
1879 if (!src->ip_equals(src, new_src) ||
1880 !dst->ip_equals(dst, new_dst))
1881 {
1882 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x: address changes"
1883 " are not supported", ntohl(spi));
1884 return NOT_SUPPORTED;
1885 }
1886
1887 /* because KLIPS does not allow us to change the NAT-T type in an SADB_UPDATE,
1888 * we can't update the SA if the encap flag has changed since installing it */
1889 if (encap != new_encap)
1890 {
1891 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x: change of UDP"
1892 " encapsulation is not supported", ntohl(spi));
1893 return NOT_SUPPORTED;
1894 }
1895
1896 DBG2(DBG_KNL, "updating SAD entry with SPI %.8x from %#H..%#H to %#H..%#H",
1897 ntohl(spi), src, dst, new_src, new_dst);
1898
1899 memset(&request, 0, sizeof(request));
1900
1901 msg = (struct sadb_msg*)request;
1902 msg->sadb_msg_version = PF_KEY_V2;
1903 msg->sadb_msg_type = SADB_UPDATE;
1904 msg->sadb_msg_satype = proto_ike2satype(protocol);
1905 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1906
1907 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1908 sa->sadb_sa_exttype = SADB_EXT_SA;
1909 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1910 sa->sadb_sa_spi = spi;
1911 sa->sadb_sa_encrypt = SADB_EALG_AESCBC; /* ignored */
1912 sa->sadb_sa_auth = SADB_AALG_SHA1HMAC; /* ignored */
1913 sa->sadb_sa_state = SADB_SASTATE_MATURE;
1914 PFKEY_EXT_ADD(msg, sa);
1915
1916 add_addr_ext(msg, src, SADB_EXT_ADDRESS_SRC);
1917 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST);
1918
1919 add_encap_ext(msg, new_src, new_dst, TRUE);
1920
1921 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1922 {
1923 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x", ntohl(spi));
1924 return FAILED;
1925 }
1926 else if (out->sadb_msg_errno)
1927 {
1928 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x: %s (%d)",
1929 ntohl(spi), strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1930 free(out);
1931 return FAILED;
1932 }
1933 free(out);
1934
1935 return SUCCESS;
1936 }
1937
1938 /**
1939 * Implementation of kernel_interface_t.del_sa.
1940 */
1941 static status_t del_sa(private_kernel_klips_ipsec_t *this, host_t *dst,
1942 u_int32_t spi, protocol_id_t protocol, u_int16_t cpi)
1943 {
1944 unsigned char request[PFKEY_BUFFER_SIZE];
1945 struct sadb_msg *msg, *out;
1946 struct sadb_sa *sa;
1947 sa_entry_t *cached_sa;
1948 size_t len;
1949
1950 memset(&request, 0, sizeof(request));
1951
1952 /* all grouped SAs are automatically deleted by KLIPS as soon as
1953 * one of them is deleted, therefore we delete only the main one */
1954 DBG2(DBG_KNL, "deleting SAD entry with SPI %.8x", ntohl(spi));
1955
1956 this->mutex->lock(this->mutex);
1957 /* this should not fail, but we don't care if it does, let the kernel decide
1958 * whether this SA exists or not */
1959 if (this->installed_sas->find_first(this->installed_sas,
1960 (linked_list_match_t)sa_entry_match_bydst, (void**)&cached_sa,
1961 &protocol, &spi, dst) == SUCCESS)
1962 {
1963 this->installed_sas->remove(this->installed_sas, cached_sa, NULL);
1964 sa_entry_destroy(cached_sa);
1965 }
1966 this->mutex->unlock(this->mutex);
1967
1968 msg = (struct sadb_msg*)request;
1969 msg->sadb_msg_version = PF_KEY_V2;
1970 msg->sadb_msg_type = SADB_DELETE;
1971 msg->sadb_msg_satype = proto_ike2satype(protocol);
1972 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1973
1974 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1975 sa->sadb_sa_exttype = SADB_EXT_SA;
1976 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1977 sa->sadb_sa_spi = spi;
1978 PFKEY_EXT_ADD(msg, sa);
1979
1980 /* the kernel wants an SADB_EXT_ADDRESS_SRC to be present even though
1981 * it is not used for anything. */
1982 add_anyaddr_ext(msg, dst->get_family(dst), SADB_EXT_ADDRESS_SRC);
1983 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST);
1984
1985 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1986 {
1987 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x", ntohl(spi));
1988 return FAILED;
1989 }
1990 else if (out->sadb_msg_errno)
1991 {
1992 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x: %s (%d)",
1993 ntohl(spi), strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1994 free(out);
1995 return FAILED;
1996 }
1997
1998 DBG2(DBG_KNL, "deleted SAD entry with SPI %.8x", ntohl(spi));
1999 free(out);
2000 return SUCCESS;
2001 }
2002
2003 /**
2004 * Implementation of kernel_interface_t.add_policy.
2005 */
2006 static status_t add_policy(private_kernel_klips_ipsec_t *this,
2007 host_t *src, host_t *dst,
2008 traffic_selector_t *src_ts,
2009 traffic_selector_t *dst_ts,
2010 policy_dir_t direction, u_int32_t spi,
2011 protocol_id_t protocol, u_int32_t reqid,
2012 ipsec_mode_t mode, u_int16_t ipcomp, u_int16_t cpi,
2013 bool routed)
2014 {
2015 unsigned char request[PFKEY_BUFFER_SIZE];
2016 struct sadb_msg *msg, *out;
2017 policy_entry_t *policy, *found = NULL;
2018 u_int8_t satype;
2019 size_t len;
2020
2021 if (direction == POLICY_FWD)
2022 {
2023 /* no forward policies for KLIPS */
2024 return SUCCESS;
2025 }
2026
2027 /* tunnel mode policies direct the packets into the pseudo IPIP SA */
2028 satype = (mode == MODE_TUNNEL) ? SADB_X_SATYPE_IPIP :
2029 proto_ike2satype(protocol);
2030
2031 /* create a policy */
2032 policy = create_policy_entry(src_ts, dst_ts, direction);
2033
2034 /* find a matching policy */
2035 this->mutex->lock(this->mutex);
2036 if (this->policies->find_first(this->policies,
2037 (linked_list_match_t)policy_entry_equals, (void**)&found, policy) == SUCCESS)
2038 {
2039 /* use existing policy */
2040 DBG2(DBG_KNL, "policy %R === %R %N already exists, increasing"
2041 " refcount", src_ts, dst_ts,
2042 policy_dir_names, direction);
2043 policy_entry_destroy(policy);
2044 policy = found;
2045 }
2046 else
2047 {
2048 /* apply the new one, if we have no such policy */
2049 this->policies->insert_last(this->policies, policy);
2050 }
2051
2052 if (routed)
2053 {
2054 /* we install this as a %trap eroute in the kernel, later to be
2055 * triggered by packets matching the policy (-> ACQUIRE). */
2056 spi = htonl(SPI_TRAP);
2057 satype = SADB_X_SATYPE_INT;
2058
2059 /* the reqid is always set to the latest child SA that trapped this
2060 * policy. we will need this reqid upon receiving an acquire. */
2061 policy->reqid = reqid;
2062
2063 /* increase the trap counter */
2064 policy->trapcount++;
2065
2066 if (policy->activecount)
2067 {
2068 /* we do not replace the current policy in the kernel while a
2069 * policy is actively used */
2070 this->mutex->unlock(this->mutex);
2071 return SUCCESS;
2072 }
2073 }
2074 else
2075 {
2076 /* increase the reference counter */
2077 policy->activecount++;
2078 }
2079
2080 DBG2(DBG_KNL, "adding policy %R === %R %N", src_ts, dst_ts,
2081 policy_dir_names, direction);
2082
2083 memset(&request, 0, sizeof(request));
2084
2085 msg = (struct sadb_msg*)request;
2086
2087 /* FIXME: SADB_X_SAFLAGS_INFLOW may be required, if we add an inbound policy for an IPIP SA */
2088 build_addflow(msg, satype, spi, routed ? NULL : src, routed ? NULL : dst,
2089 policy->src.net, policy->src.mask, policy->dst.net, policy->dst.mask,
2090 policy->src.proto, found != NULL);
2091
2092 this->mutex->unlock(this->mutex);
2093
2094 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2095 {
2096 DBG1(DBG_KNL, "unable to add policy %R === %R %N", src_ts, dst_ts,
2097 policy_dir_names, direction);
2098 return FAILED;
2099 }
2100 else if (out->sadb_msg_errno)
2101 {
2102 DBG1(DBG_KNL, "unable to add policy %R === %R %N: %s (%d)", src_ts, dst_ts,
2103 policy_dir_names, direction,
2104 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2105 free(out);
2106 return FAILED;
2107 }
2108 free(out);
2109
2110 this->mutex->lock(this->mutex);
2111
2112 /* we try to find the policy again and install the route if needed */
2113 if (this->policies->find_last(this->policies, NULL, (void**)&policy) != SUCCESS)
2114 {
2115 this->mutex->unlock(this->mutex);
2116 DBG2(DBG_KNL, "the policy %R === %R %N is already gone, ignoring",
2117 src_ts, dst_ts, policy_dir_names, direction);
2118 return SUCCESS;
2119 }
2120
2121 /* KLIPS requires a special route that directs traffic that matches this
2122 * policy to one of the virtual ipsec interfaces. The virtual interface
2123 * has to be attached to the physical one the traffic runs over.
2124 * This is a special case of the source route we install in other kernel
2125 * interfaces.
2126 * In the following cases we do NOT install a source route (but just a
2127 * regular route):
2128 * - we are not in tunnel mode
2129 * - we are using IPv6 (does not work correctly yet!)
2130 * - routing is disabled via strongswan.conf
2131 */
2132 if (policy->route == NULL && direction == POLICY_OUT)
2133 {
2134 char *iface;
2135 ipsec_dev_t *dev;
2136 route_entry_t *route = malloc_thing(route_entry_t);
2137 route->src_ip = NULL;
2138
2139 if (mode != MODE_TRANSPORT && src->get_family(src) != AF_INET6 &&
2140 this->install_routes)
2141 {
2142 charon->kernel_interface->get_address_by_ts(charon->kernel_interface,
2143 src_ts, &route->src_ip);
2144 }
2145
2146 if (!route->src_ip)
2147 {
2148 route->src_ip = host_create_any(src->get_family(src));
2149 }
2150
2151 /* find the virtual interface */
2152 iface = charon->kernel_interface->get_interface(charon->kernel_interface,
2153 src);
2154 if (find_ipsec_dev(this, iface, &dev) == SUCCESS)
2155 {
2156 /* above, we got either the name of a virtual or a physical
2157 * interface. for both cases it means we already have the devices
2158 * properly attached (assuming that we are exclusively attaching
2159 * ipsec devices). */
2160 dev->refcount++;
2161 }
2162 else
2163 {
2164 /* there is no record of a mapping with the returned interface.
2165 * thus, we attach the first free virtual interface we find to
2166 * it. As above we assume we are the only client fiddling with
2167 * ipsec devices. */
2168 if (this->ipsec_devices->find_first(this->ipsec_devices,
2169 (linked_list_match_t)ipsec_dev_match_free,
2170 (void**)&dev) == SUCCESS)
2171 {
2172 if (attach_ipsec_dev(dev->name, iface) == SUCCESS)
2173 {
2174 strncpy(dev->phys_name, iface, IFNAMSIZ);
2175 dev->refcount = 1;
2176 }
2177 else
2178 {
2179 DBG1(DBG_KNL, "failed to attach virtual interface %s"
2180 " to %s", dev->name, iface);
2181 this->mutex->unlock(this->mutex);
2182 free(iface);
2183 return FAILED;
2184 }
2185 }
2186 else
2187 {
2188 this->mutex->unlock(this->mutex);
2189 DBG1(DBG_KNL, "failed to attach a virtual interface to %s: no"
2190 " virtual interfaces left", iface);
2191 free(iface);
2192 return FAILED;
2193 }
2194 }
2195 free(iface);
2196 route->if_name = strdup(dev->name);
2197
2198 /* get the nexthop to dst */
2199 route->gateway = charon->kernel_interface->get_nexthop(
2200 charon->kernel_interface, dst);
2201 route->dst_net = chunk_clone(policy->dst.net->get_address(policy->dst.net));
2202 route->prefixlen = policy->dst.mask;
2203
2204 switch (charon->kernel_interface->add_route(charon->kernel_interface,
2205 route->dst_net, route->prefixlen, route->gateway,
2206 route->src_ip, route->if_name))
2207 {
2208 default:
2209 DBG1(DBG_KNL, "unable to install route for policy %R === %R",
2210 src_ts, dst_ts);
2211 /* FALL */
2212 case ALREADY_DONE:
2213 /* route exists, do not uninstall */
2214 route_entry_destroy(route);
2215 break;
2216 case SUCCESS:
2217 /* cache the installed route */
2218 policy->route = route;
2219 break;
2220 }
2221 }
2222
2223 this->mutex->unlock(this->mutex);
2224
2225 return SUCCESS;
2226 }
2227
2228 /**
2229 * Implementation of kernel_interface_t.query_policy.
2230 */
2231 static status_t query_policy(private_kernel_klips_ipsec_t *this,
2232 traffic_selector_t *src_ts,
2233 traffic_selector_t *dst_ts,
2234 policy_dir_t direction, u_int32_t *use_time)
2235 {
2236 #define IDLE_PREFIX "idle="
2237 static const char *path_eroute = "/proc/net/ipsec_eroute";
2238 static const char *path_spi = "/proc/net/ipsec_spi";
2239 FILE *file;
2240 char line[1024], src[INET6_ADDRSTRLEN + 9], dst[INET6_ADDRSTRLEN + 9];
2241 char *said = NULL, *pos;
2242 policy_entry_t *policy, *found = NULL;
2243 status_t status = FAILED;
2244
2245 if (direction == POLICY_FWD)
2246 {
2247 /* we do not install forward policies */
2248 return FAILED;
2249 }
2250
2251 DBG2(DBG_KNL, "querying policy %R === %R %N", src_ts, dst_ts,
2252 policy_dir_names, direction);
2253
2254 /* create a policy */
2255 policy = create_policy_entry(src_ts, dst_ts, direction);
2256
2257 /* find a matching policy */
2258 this->mutex->lock(this->mutex);
2259 if (this->policies->find_first(this->policies,
2260 (linked_list_match_t)policy_entry_equals, (void**)&found, policy) != SUCCESS)
2261 {
2262 this->mutex->unlock(this->mutex);
2263 DBG1(DBG_KNL, "querying policy %R === %R %N failed, not found", src_ts,
2264 dst_ts, policy_dir_names, direction);
2265 policy_entry_destroy(policy);
2266 return NOT_FOUND;
2267 }
2268 policy_entry_destroy(policy);
2269 policy = found;
2270
2271 /* src and dst selectors in KLIPS are of the form NET_ADDR/NETBITS:PROTO */
2272 snprintf(src, sizeof(src), "%H/%d:%d", policy->src.net, policy->src.mask,
2273 policy->src.proto);
2274 src[sizeof(src) - 1] = '\0';
2275 snprintf(dst, sizeof(dst), "%H/%d:%d", policy->dst.net, policy->dst.mask,
2276 policy->dst.proto);
2277 dst[sizeof(dst) - 1] = '\0';
2278
2279 this->mutex->unlock(this->mutex);
2280
2281 /* we try to find the matching eroute first */
2282 file = fopen(path_eroute, "r");
2283 if (file == NULL)
2284 {
2285 DBG1(DBG_KNL, "unable to query policy %R === %R %N: %s (%d)", src_ts,
2286 dst_ts, policy_dir_names, direction, strerror(errno), errno);
2287 return FAILED;
2288 }
2289
2290 /* read line by line where each line looks like:
2291 * packets src -> dst => said */
2292 while (fgets(line, sizeof(line), file))
2293 {
2294 enumerator_t *enumerator;
2295 char *token;
2296 int i = 0;
2297
2298 enumerator = enumerator_create_token(line, " \t", " \t\n");
2299 while (enumerator->enumerate(enumerator, &token))
2300 {
2301 switch (i++)
2302 {
2303 case 0: /* packets */
2304 continue;
2305 case 1: /* src */
2306 if (streq(token, src))
2307 {
2308 continue;
2309 }
2310 break;
2311 case 2: /* -> */
2312 continue;
2313 case 3: /* dst */
2314 if (streq(token, dst))
2315 {
2316 continue;
2317 }
2318 break;
2319 case 4: /* => */
2320 continue;
2321 case 5: /* said */
2322 said = strdup(token);
2323 break;
2324 }
2325 break;
2326 }
2327 enumerator->destroy(enumerator);
2328
2329 if (i == 5)
2330 {
2331 /* eroute matched */
2332 break;
2333 }
2334 }
2335 fclose(file);
2336
2337 if (said == NULL)
2338 {
2339 DBG1(DBG_KNL, "unable to query policy %R === %R %N: found no matching"
2340 " eroute", src_ts, dst_ts, policy_dir_names, direction);
2341 return FAILED;
2342 }
2343
2344 /* compared with the one in the spi entry the SA ID from the eroute entry
2345 * has an additional ":PROTO" appended, which we need to cut off */
2346 pos = strrchr(said, ':');
2347 *pos = '\0';
2348
2349 /* now we try to find the matching spi entry */
2350 file = fopen(path_spi, "r");
2351 if (file == NULL)
2352 {
2353 DBG1(DBG_KNL, "unable to query policy %R === %R %N: %s (%d)", src_ts,
2354 dst_ts, policy_dir_names, direction, strerror(errno), errno);
2355 return FAILED;
2356 }
2357
2358 while (fgets(line, sizeof(line), file))
2359 {
2360 if (strneq(line, said, strlen(said)))
2361 {
2362 /* fine we found the correct line, now find the idle time */
2363 u_int32_t idle_time;
2364 pos = strstr(line, IDLE_PREFIX);
2365 if (pos == NULL)
2366 {
2367 /* no idle time, i.e. this SA has not been used yet */
2368 break;
2369 }
2370 if (sscanf(pos, IDLE_PREFIX"%u", &idle_time) <= 0)
2371 {
2372 /* idle time not valid */
2373 break;
2374 }
2375
2376 *use_time = time(NULL) - idle_time;
2377 status = SUCCESS;
2378 break;
2379 }
2380 }
2381 fclose(file);
2382 free(said);
2383
2384 return status;
2385 }
2386
2387 /**
2388 * Implementation of kernel_interface_t.del_policy.
2389 */
2390 static status_t del_policy(private_kernel_klips_ipsec_t *this,
2391 traffic_selector_t *src_ts,
2392 traffic_selector_t *dst_ts,
2393 policy_dir_t direction, bool unrouted)
2394 {
2395 unsigned char request[PFKEY_BUFFER_SIZE];
2396 struct sadb_msg *msg = (struct sadb_msg*)request, *out;
2397 policy_entry_t *policy, *found = NULL;
2398 route_entry_t *route;
2399 size_t len;
2400
2401 if (direction == POLICY_FWD)
2402 {
2403 /* no forward policies for KLIPS */
2404 return SUCCESS;
2405 }
2406
2407 DBG2(DBG_KNL, "deleting policy %R === %R %N", src_ts, dst_ts,
2408 policy_dir_names, direction);
2409
2410 /* create a policy */
2411 policy = create_policy_entry(src_ts, dst_ts, direction);
2412
2413 /* find a matching policy */
2414 this->mutex->lock(this->mutex);
2415 if (this->policies->find_first(this->policies,
2416 (linked_list_match_t)policy_entry_equals, (void**)&found, policy) != SUCCESS)
2417 {
2418 this->mutex->unlock(this->mutex);
2419 DBG1(DBG_KNL, "deleting policy %R === %R %N failed, not found", src_ts,
2420 dst_ts, policy_dir_names, direction);
2421 policy_entry_destroy(policy);
2422 return NOT_FOUND;
2423 }
2424 policy_entry_destroy(policy);
2425
2426 /* decrease appropriate counter */
2427 unrouted ? found->trapcount-- : found->activecount--;
2428
2429 if (found->trapcount == 0)
2430 {
2431 /* if this policy is finally unrouted, we reset the reqid because it
2432 * may still be actively used and there might be a pending acquire for
2433 * this policy. */
2434 found->reqid = 0;
2435 }
2436
2437 if (found->activecount > 0)
2438 {
2439 /* is still used by SAs, keep in kernel */
2440 this->mutex->unlock(this->mutex);
2441 DBG2(DBG_KNL, "policy still used by another CHILD_SA, not removed");
2442 return SUCCESS;
2443 }
2444 else if (found->activecount == 0 && found->trapcount > 0)
2445 {
2446 /* for a policy that is not used actively anymore, but is still trapped
2447 * by another child SA we replace the current eroute with a %trap eroute */
2448 DBG2(DBG_KNL, "policy still routed by another CHILD_SA, not removed");
2449 memset(&request, 0, sizeof(request));
2450 build_addflow(msg, SADB_X_SATYPE_INT, htonl(SPI_TRAP), NULL, NULL,
2451 found->src.net, found->src.mask, found->dst.net,
2452 found->dst.mask, found->src.proto, TRUE);
2453 this->mutex->unlock(this->mutex);
2454 return pfkey_send_ack(this, msg);
2455 }
2456
2457 /* remove if last reference */
2458 this->policies->remove(this->policies, found, NULL);
2459 policy = found;
2460
2461 this->mutex->unlock(this->mutex);
2462
2463 memset(&request, 0, sizeof(request));
2464
2465 build_delflow(msg, 0, policy->src.net, policy->src.mask, policy->dst.net,
2466 policy->dst.mask, policy->src.proto);
2467
2468 route = policy->route;
2469 policy->route = NULL;
2470 policy_entry_destroy(policy);
2471
2472 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2473 {
2474 DBG1(DBG_KNL, "unable to delete policy %R === %R %N", src_ts, dst_ts,
2475 policy_dir_names, direction);
2476 return FAILED;
2477 }
2478 else if (out->sadb_msg_errno)
2479 {
2480 DBG1(DBG_KNL, "unable to delete policy %R === %R %N: %s (%d)", src_ts,
2481 dst_ts, policy_dir_names, direction,
2482 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2483 free(out);
2484 return FAILED;
2485 }
2486 free(out);
2487
2488 if (route)
2489 {
2490 ipsec_dev_t *dev;
2491
2492 if (charon->kernel_interface->del_route(charon->kernel_interface,
2493 route->dst_net, route->prefixlen, route->gateway,
2494 route->src_ip, route->if_name) != SUCCESS)
2495 {
2496 DBG1(DBG_KNL, "error uninstalling route installed with"
2497 " policy %R === %R %N", src_ts, dst_ts,
2498 policy_dir_names, direction);
2499 }
2500
2501 /* we have to detach the ipsec interface from the physical one over which
2502 * this SA ran (if it is not used by any other) */
2503 this->mutex->lock(this->mutex);
2504
2505 if (find_ipsec_dev(this, route->if_name, &dev) == SUCCESS)
2506 {
2507 /* fine, we found a matching device object, let's check if we have
2508 * to detach it. */
2509 if (--dev->refcount == 0)
2510 {
2511 if (detach_ipsec_dev(dev->name, dev->phys_name) != SUCCESS)
2512 {
2513 DBG1(DBG_KNL, "failed to detach virtual interface %s"
2514 " from %s", dev->name, dev->phys_name);
2515 }
2516 dev->phys_name[0] = '\0';
2517 }
2518 }
2519
2520 this->mutex->unlock(this->mutex);
2521
2522 route_entry_destroy(route);
2523 }
2524
2525 return SUCCESS;
2526 }
2527
2528 /**
2529 * Initialize the list of ipsec devices
2530 */
2531 static void init_ipsec_devices(private_kernel_klips_ipsec_t *this)
2532 {
2533 int i, count = lib->settings->get_int(lib->settings,
2534 "charon.plugins.kernel_klips.ipsec_dev_count",
2535 DEFAULT_IPSEC_DEV_COUNT);
2536
2537 for (i = 0; i < count; ++i)
2538 {
2539 ipsec_dev_t *dev = malloc_thing(ipsec_dev_t);
2540 snprintf(dev->name, IFNAMSIZ, IPSEC_DEV_PREFIX"%d", i);
2541 dev->name[IFNAMSIZ - 1] = '\0';
2542 dev->phys_name[0] = '\0';
2543 dev->refcount = 0;
2544 this->ipsec_devices->insert_last(this->ipsec_devices, dev);
2545
2546 /* detach any previously attached ipsec device */
2547 detach_ipsec_dev(dev->name, dev->phys_name);
2548 }
2549 }
2550
2551 /**
2552 * Register a socket for AQUIRE/EXPIRE messages
2553 */
2554 static status_t register_pfkey_socket(private_kernel_klips_ipsec_t *this, u_int8_t satype)
2555 {
2556 unsigned char request[PFKEY_BUFFER_SIZE];
2557 struct sadb_msg *msg, *out;
2558 size_t len;
2559
2560 memset(&request, 0, sizeof(request));
2561
2562 msg = (struct sadb_msg*)request;
2563 msg->sadb_msg_version = PF_KEY_V2;
2564 msg->sadb_msg_type = SADB_REGISTER;
2565 msg->sadb_msg_satype = satype;
2566 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2567
2568 if (pfkey_send_socket(this, this->socket_events, msg, &out, &len) != SUCCESS)
2569 {
2570 DBG1(DBG_KNL, "unable to register PF_KEY socket");
2571 return FAILED;
2572 }
2573 else if (out->sadb_msg_errno)
2574 {
2575 DBG1(DBG_KNL, "unable to register PF_KEY socket: %s (%d)",
2576 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2577 free(out);
2578 return FAILED;
2579 }
2580 free(out);
2581 return SUCCESS;
2582 }
2583
2584 /**
2585 * Implementation of kernel_interface_t.destroy.
2586 */
2587 static void destroy(private_kernel_klips_ipsec_t *this)
2588 {
2589 this->job->cancel(this->job);
2590 close(this->socket);
2591 close(this->socket_events);
2592 this->mutex_pfkey->destroy(this->mutex_pfkey);
2593 this->mutex->destroy(this->mutex);
2594 this->ipsec_devices->destroy_function(this->ipsec_devices, (void*)ipsec_dev_destroy);
2595 this->installed_sas->destroy_function(this->installed_sas, (void*)sa_entry_destroy);
2596 this->allocated_spis->destroy_function(this->allocated_spis, (void*)sa_entry_destroy);
2597 this->policies->destroy_function(this->policies, (void*)policy_entry_destroy);
2598 free(this);
2599 }
2600
2601 /*
2602 * Described in header.
2603 */
2604 kernel_klips_ipsec_t *kernel_klips_ipsec_create()
2605 {
2606 private_kernel_klips_ipsec_t *this = malloc_thing(private_kernel_klips_ipsec_t);
2607
2608 /* public functions */
2609 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;
2610 this->public.interface.get_cpi = (status_t(*)(kernel_ipsec_t*,host_t*,host_t*,u_int32_t,u_int16_t*))get_cpi;
2611 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;
2612 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;
2613 this->public.interface.del_sa = (status_t(*)(kernel_ipsec_t*,host_t*,u_int32_t,protocol_id_t,u_int16_t))del_sa;
2614 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;
2615 this->public.interface.query_policy = (status_t(*)(kernel_ipsec_t*,traffic_selector_t*,traffic_selector_t*,policy_dir_t,u_int32_t*))query_policy;
2616 this->public.interface.del_policy = (status_t(*)(kernel_ipsec_t*,traffic_selector_t*,traffic_selector_t*,policy_dir_t,bool))del_policy;
2617
2618 this->public.interface.destroy = (void(*)(kernel_ipsec_t*)) destroy;
2619
2620 /* private members */
2621 this->policies = linked_list_create();
2622 this->allocated_spis = linked_list_create();
2623 this->installed_sas = linked_list_create();
2624 this->ipsec_devices = linked_list_create();
2625 this->mutex = mutex_create(MUTEX_DEFAULT);
2626 this->mutex_pfkey = mutex_create(MUTEX_DEFAULT);
2627 this->install_routes = lib->settings->get_bool(lib->settings, "charon.install_routes", TRUE);
2628 this->seq = 0;
2629
2630 /* initialize ipsec devices */
2631 init_ipsec_devices(this);
2632
2633 /* create a PF_KEY socket to communicate with the kernel */
2634 this->socket = socket(PF_KEY, SOCK_RAW, PF_KEY_V2);
2635 if (this->socket <= 0)
2636 {
2637 charon->kill(charon, "unable to create PF_KEY socket");
2638 }
2639
2640 /* create a PF_KEY socket for ACQUIRE & EXPIRE */
2641 this->socket_events = socket(PF_KEY, SOCK_RAW, PF_KEY_V2);
2642 if (this->socket_events <= 0)
2643 {
2644 charon->kill(charon, "unable to create PF_KEY event socket");
2645 }
2646
2647 /* register the event socket */
2648 if (register_pfkey_socket(this, SADB_SATYPE_ESP) != SUCCESS ||
2649 register_pfkey_socket(this, SADB_SATYPE_AH) != SUCCESS)
2650 {
2651 charon->kill(charon, "unable to register PF_KEY event socket");
2652 }
2653
2654 this->job = callback_job_create((callback_job_cb_t)receive_events,
2655 this, NULL, NULL);
2656 charon->processor->queue_job(charon->processor, (job_t*)this->job);
2657
2658 return &this->public;
2659 }