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