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