display transmitted bytes per SA
[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 <pthread.h>
25 #include <stdio.h>
26 #include <string.h>
27 #include <time.h>
28 #include <errno.h>
29
30 #include "kernel_klips_ipsec.h"
31
32 #include <daemon.h>
33 #include <utils/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, oldstate;
1379
1380 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate);
1381 len = recv(this->socket_events, buf, sizeof(buf), 0);
1382 pthread_setcancelstate(oldstate, NULL);
1383
1384 if (len < 0)
1385 {
1386 switch (errno)
1387 {
1388 case EINTR:
1389 /* interrupted, try again */
1390 return JOB_REQUEUE_DIRECT;
1391 case EAGAIN:
1392 /* no data ready, select again */
1393 return JOB_REQUEUE_DIRECT;
1394 default:
1395 DBG1(DBG_KNL, "unable to receive from PF_KEY event socket");
1396 sleep(1);
1397 return JOB_REQUEUE_FAIR;
1398 }
1399 }
1400
1401 if (len < sizeof(struct sadb_msg) ||
1402 msg->sadb_msg_len < PFKEY_LEN(sizeof(struct sadb_msg)))
1403 {
1404 DBG2(DBG_KNL, "received corrupted PF_KEY message");
1405 return JOB_REQUEUE_DIRECT;
1406 }
1407 if (msg->sadb_msg_pid != 0)
1408 { /* not from kernel. not interested, try another one */
1409 return JOB_REQUEUE_DIRECT;
1410 }
1411 if (msg->sadb_msg_len > len / PFKEY_ALIGNMENT)
1412 {
1413 DBG1(DBG_KNL, "buffer was too small to receive the complete PF_KEY message");
1414 return JOB_REQUEUE_DIRECT;
1415 }
1416
1417 switch (msg->sadb_msg_type)
1418 {
1419 case SADB_ACQUIRE:
1420 process_acquire(this, msg);
1421 break;
1422 case SADB_EXPIRE:
1423 /* SADB_EXPIRE events in KLIPS are only triggered by traffic (even for
1424 * the time based limits). So if there is no traffic for a longer
1425 * period than configured as hard limit, we wouldn't be able to rekey
1426 * the SA and just receive the hard expire and thus delete the SA.
1427 * To avoid this behavior and to make charon behave as with the other
1428 * kernel plugins, we implement the expiration of SAs ourselves. */
1429 break;
1430 case SADB_X_NAT_T_NEW_MAPPING:
1431 process_mapping(this, msg);
1432 break;
1433 default:
1434 break;
1435 }
1436
1437 return JOB_REQUEUE_DIRECT;
1438 }
1439
1440 typedef enum {
1441 /** an SPI has expired */
1442 EXPIRE_TYPE_SPI,
1443 /** a CHILD_SA has to be rekeyed */
1444 EXPIRE_TYPE_SOFT,
1445 /** a CHILD_SA has to be deleted */
1446 EXPIRE_TYPE_HARD
1447 } expire_type_t;
1448
1449 typedef struct sa_expire_t sa_expire_t;
1450
1451 struct sa_expire_t {
1452 /** kernel interface */
1453 private_kernel_klips_ipsec_t *this;
1454 /** the SPI of the expiring SA */
1455 u_int32_t spi;
1456 /** the protocol of the expiring SA */
1457 protocol_id_t protocol;
1458 /** the reqid of the expiring SA*/
1459 u_int32_t reqid;
1460 /** what type of expire this is */
1461 expire_type_t type;
1462 };
1463
1464 /**
1465 * Called when an SA expires
1466 */
1467 static job_requeue_t sa_expires(sa_expire_t *expire)
1468 {
1469 private_kernel_klips_ipsec_t *this = expire->this;
1470 protocol_id_t protocol = expire->protocol;
1471 u_int32_t spi = expire->spi, reqid = expire->reqid;
1472 bool hard = expire->type != EXPIRE_TYPE_SOFT;
1473 sa_entry_t *cached_sa;
1474 linked_list_t *list;
1475 job_t *job;
1476
1477 /* for an expired SPI we first check whether the CHILD_SA got installed
1478 * in the meantime, for expired SAs we check whether they are still installed */
1479 list = expire->type == EXPIRE_TYPE_SPI ? this->allocated_spis : this->installed_sas;
1480
1481 this->mutex->lock(this->mutex);
1482 if (list->find_first(list, (linked_list_match_t)sa_entry_match_byid,
1483 (void**)&cached_sa, &protocol, &spi, &reqid) != SUCCESS)
1484 {
1485 /* we found no entry:
1486 * - for SPIs, a CHILD_SA has been installed
1487 * - for SAs, the CHILD_SA has already been deleted */
1488 this->mutex->unlock(this->mutex);
1489 return JOB_REQUEUE_NONE;
1490 }
1491 else
1492 {
1493 list->remove(list, cached_sa, NULL);
1494 sa_entry_destroy(cached_sa);
1495 }
1496 this->mutex->unlock(this->mutex);
1497
1498 DBG2(DBG_KNL, "%N CHILD_SA with SPI %.8x and reqid {%d} expired",
1499 protocol_id_names, protocol, ntohl(spi), reqid);
1500
1501 DBG1(DBG_KNL, "creating %s job for %N CHILD_SA with SPI %.8x and reqid {%d}",
1502 hard ? "delete" : "rekey", protocol_id_names,
1503 protocol, ntohl(spi), reqid);
1504 if (hard)
1505 {
1506 job = (job_t*)delete_child_sa_job_create(reqid, protocol, spi);
1507 }
1508 else
1509 {
1510 job = (job_t*)rekey_child_sa_job_create(reqid, protocol, spi);
1511 }
1512 charon->processor->queue_job(charon->processor, job);
1513 return JOB_REQUEUE_NONE;
1514 }
1515
1516 /**
1517 * Schedule an expire job for an SA. Time is in seconds.
1518 */
1519 static void schedule_expire(private_kernel_klips_ipsec_t *this,
1520 protocol_id_t protocol, u_int32_t spi,
1521 u_int32_t reqid, expire_type_t type, u_int32_t time)
1522 {
1523 callback_job_t *job;
1524 sa_expire_t *expire = malloc_thing(sa_expire_t);
1525 expire->this = this;
1526 expire->protocol = protocol;
1527 expire->spi = spi;
1528 expire->reqid = reqid;
1529 expire->type = type;
1530 job = callback_job_create((callback_job_cb_t)sa_expires, expire, free, NULL);
1531 charon->scheduler->schedule_job(charon->scheduler, (job_t*)job, time);
1532 }
1533
1534 /**
1535 * Implementation of kernel_interface_t.get_spi.
1536 */
1537 static status_t get_spi(private_kernel_klips_ipsec_t *this,
1538 host_t *src, host_t *dst,
1539 protocol_id_t protocol, u_int32_t reqid,
1540 u_int32_t *spi)
1541 {
1542 /* we cannot use SADB_GETSPI because KLIPS does not allow us to set the
1543 * NAT-T type in an SADB_UPDATE which we would have to use to update the
1544 * implicitly created SA.
1545 */
1546 rng_t *rng;
1547 u_int32_t spi_gen;
1548
1549 rng = lib->crypto->create_rng(lib->crypto, RNG_WEAK);
1550 if (!rng)
1551 {
1552 DBG1(DBG_KNL, "allocating SPI failed: no RNG");
1553 return FAILED;
1554 }
1555 rng->get_bytes(rng, sizeof(spi_gen), (void*)&spi_gen);
1556 rng->destroy(rng);
1557
1558 /* charon's SPIs lie within the range from 0xc0000000 to 0xcFFFFFFF */
1559 spi_gen = 0xc0000000 | (spi_gen & 0x0FFFFFFF);
1560
1561 DBG2(DBG_KNL, "allocated SPI %.8x for %N SA between %#H..%#H",
1562 spi_gen, protocol_id_names, protocol, src, dst);
1563
1564 *spi = htonl(spi_gen);
1565
1566 this->mutex->lock(this->mutex);
1567 this->allocated_spis->insert_last(this->allocated_spis,
1568 create_sa_entry(protocol, *spi, reqid, NULL, NULL, FALSE, TRUE));
1569 this->mutex->unlock(this->mutex);
1570 schedule_expire(this, protocol, *spi, reqid, EXPIRE_TYPE_SPI, SPI_TIMEOUT);
1571
1572 return SUCCESS;
1573 }
1574
1575 /**
1576 * Implementation of kernel_interface_t.get_cpi.
1577 */
1578 static status_t get_cpi(private_kernel_klips_ipsec_t *this,
1579 host_t *src, host_t *dst,
1580 u_int32_t reqid, u_int16_t *cpi)
1581 {
1582 return FAILED;
1583 }
1584
1585 /**
1586 * Add a pseudo IPIP SA for tunnel mode with KLIPS.
1587 */
1588 static status_t add_ipip_sa(private_kernel_klips_ipsec_t *this,
1589 host_t *src, host_t *dst, u_int32_t spi, u_int32_t reqid)
1590 {
1591 unsigned char request[PFKEY_BUFFER_SIZE];
1592 struct sadb_msg *msg, *out;
1593 struct sadb_sa *sa;
1594 size_t len;
1595
1596 memset(&request, 0, sizeof(request));
1597
1598 DBG2(DBG_KNL, "adding pseudo IPIP SA with SPI %.8x and reqid {%d}", ntohl(spi), reqid);
1599
1600 msg = (struct sadb_msg*)request;
1601 msg->sadb_msg_version = PF_KEY_V2;
1602 msg->sadb_msg_type = SADB_ADD;
1603 msg->sadb_msg_satype = SADB_X_SATYPE_IPIP;
1604 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1605
1606 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1607 sa->sadb_sa_exttype = SADB_EXT_SA;
1608 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1609 sa->sadb_sa_spi = spi;
1610 sa->sadb_sa_state = SADB_SASTATE_MATURE;
1611 PFKEY_EXT_ADD(msg, sa);
1612
1613 add_addr_ext(msg, src, SADB_EXT_ADDRESS_SRC);
1614 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST);
1615
1616 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1617 {
1618 DBG1(DBG_KNL, "unable to add pseudo IPIP SA with SPI %.8x", ntohl(spi));
1619 return FAILED;
1620 }
1621 else if (out->sadb_msg_errno)
1622 {
1623 DBG1(DBG_KNL, "unable to add pseudo IPIP SA with SPI %.8x: %s (%d)",
1624 ntohl(spi), strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1625 free(out);
1626 return FAILED;
1627 }
1628
1629 free(out);
1630 return SUCCESS;
1631 }
1632
1633 /**
1634 * group the IPIP SA required for tunnel mode with the outer SA
1635 */
1636 static status_t group_ipip_sa(private_kernel_klips_ipsec_t *this,
1637 host_t *src, host_t *dst, u_int32_t spi,
1638 protocol_id_t protocol, u_int32_t reqid)
1639 {
1640 unsigned char request[PFKEY_BUFFER_SIZE];
1641 struct sadb_msg *msg, *out;
1642 struct sadb_sa *sa;
1643 struct sadb_x_satype *satype;
1644 size_t len;
1645
1646 memset(&request, 0, sizeof(request));
1647
1648 DBG2(DBG_KNL, "grouping SAs with SPI %.8x and reqid {%d}", ntohl(spi), reqid);
1649
1650 msg = (struct sadb_msg*)request;
1651 msg->sadb_msg_version = PF_KEY_V2;
1652 msg->sadb_msg_type = SADB_X_GRPSA;
1653 msg->sadb_msg_satype = SADB_X_SATYPE_IPIP;
1654 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1655
1656 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1657 sa->sadb_sa_exttype = SADB_EXT_SA;
1658 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1659 sa->sadb_sa_spi = spi;
1660 sa->sadb_sa_state = SADB_SASTATE_MATURE;
1661 PFKEY_EXT_ADD(msg, sa);
1662
1663 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST);
1664
1665 satype = (struct sadb_x_satype*)PFKEY_EXT_ADD_NEXT(msg);
1666 satype->sadb_x_satype_exttype = SADB_X_EXT_SATYPE2;
1667 satype->sadb_x_satype_len = PFKEY_LEN(sizeof(struct sadb_x_satype));
1668 satype->sadb_x_satype_satype = proto_ike2satype(protocol);
1669 PFKEY_EXT_ADD(msg, satype);
1670
1671 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1672 sa->sadb_sa_exttype = SADB_X_EXT_SA2;
1673 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1674 sa->sadb_sa_spi = spi;
1675 sa->sadb_sa_state = SADB_SASTATE_MATURE;
1676 PFKEY_EXT_ADD(msg, sa);
1677
1678 add_addr_ext(msg, dst, SADB_X_EXT_ADDRESS_DST2);
1679
1680 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1681 {
1682 DBG1(DBG_KNL, "unable to group SAs with SPI %.8x", ntohl(spi));
1683 return FAILED;
1684 }
1685 else if (out->sadb_msg_errno)
1686 {
1687 DBG1(DBG_KNL, "unable to group SAs with SPI %.8x: %s (%d)",
1688 ntohl(spi), strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1689 free(out);
1690 return FAILED;
1691 }
1692
1693 free(out);
1694 return SUCCESS;
1695 }
1696
1697 /**
1698 * Implementation of kernel_interface_t.add_sa.
1699 */
1700 static status_t add_sa(private_kernel_klips_ipsec_t *this,
1701 host_t *src, host_t *dst, u_int32_t spi,
1702 protocol_id_t protocol, u_int32_t reqid,
1703 u_int64_t expire_soft, u_int64_t expire_hard,
1704 u_int16_t enc_alg, chunk_t enc_key,
1705 u_int16_t int_alg, chunk_t int_key,
1706 ipsec_mode_t mode, u_int16_t ipcomp, u_int16_t cpi,
1707 bool encap, bool inbound)
1708 {
1709 unsigned char request[PFKEY_BUFFER_SIZE];
1710 struct sadb_msg *msg, *out;
1711 struct sadb_sa *sa;
1712 struct sadb_key *key;
1713 size_t len;
1714
1715 if (inbound)
1716 {
1717 /* for inbound SAs we allocated an SPI via get_spi, so we first check
1718 * whether that SPI has already expired (race condition) */
1719 sa_entry_t *alloc_spi;
1720 this->mutex->lock(this->mutex);
1721 if (this->allocated_spis->find_first(this->allocated_spis,
1722 (linked_list_match_t)sa_entry_match_byid, (void**)&alloc_spi,
1723 &protocol, &spi, &reqid) != SUCCESS)
1724 {
1725 this->mutex->unlock(this->mutex);
1726 DBG1(DBG_KNL, "allocated SPI %.8x has already expired", ntohl(spi));
1727 return FAILED;
1728 }
1729 else
1730 {
1731 this->allocated_spis->remove(this->allocated_spis, alloc_spi, NULL);
1732 sa_entry_destroy(alloc_spi);
1733 }
1734 this->mutex->unlock(this->mutex);
1735 }
1736
1737 memset(&request, 0, sizeof(request));
1738
1739 DBG2(DBG_KNL, "adding SAD entry with SPI %.8x and reqid {%d}", ntohl(spi), reqid);
1740
1741 msg = (struct sadb_msg*)request;
1742 msg->sadb_msg_version = PF_KEY_V2;
1743 msg->sadb_msg_type = SADB_ADD;
1744 msg->sadb_msg_satype = proto_ike2satype(protocol);
1745 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1746
1747 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1748 sa->sadb_sa_exttype = SADB_EXT_SA;
1749 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1750 sa->sadb_sa_spi = spi;
1751 sa->sadb_sa_state = SADB_SASTATE_MATURE;
1752 sa->sadb_sa_replay = (protocol == IPPROTO_COMP) ? 0 : 32;
1753 sa->sadb_sa_auth = lookup_algorithm(integrity_algs, int_alg);
1754 sa->sadb_sa_encrypt = lookup_algorithm(encryption_algs, enc_alg);
1755 PFKEY_EXT_ADD(msg, sa);
1756
1757 add_addr_ext(msg, src, SADB_EXT_ADDRESS_SRC);
1758 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST);
1759
1760 if (enc_alg != ENCR_UNDEFINED)
1761 {
1762 if (!sa->sadb_sa_encrypt)
1763 {
1764 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1765 encryption_algorithm_names, enc_alg);
1766 return FAILED;
1767 }
1768 DBG2(DBG_KNL, " using encryption algorithm %N with key size %d",
1769 encryption_algorithm_names, enc_alg, enc_key.len * 8);
1770
1771 key = (struct sadb_key*)PFKEY_EXT_ADD_NEXT(msg);
1772 key->sadb_key_exttype = SADB_EXT_KEY_ENCRYPT;
1773 key->sadb_key_bits = enc_key.len * 8;
1774 key->sadb_key_len = PFKEY_LEN(sizeof(struct sadb_key) + enc_key.len);
1775 memcpy(key + 1, enc_key.ptr, enc_key.len);
1776
1777 PFKEY_EXT_ADD(msg, key);
1778 }
1779
1780 if (int_alg != AUTH_UNDEFINED)
1781 {
1782 if (!sa->sadb_sa_auth)
1783 {
1784 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1785 integrity_algorithm_names, int_alg);
1786 return FAILED;
1787 }
1788 DBG2(DBG_KNL, " using integrity algorithm %N with key size %d",
1789 integrity_algorithm_names, int_alg, int_key.len * 8);
1790
1791 key = (struct sadb_key*)PFKEY_EXT_ADD_NEXT(msg);
1792 key->sadb_key_exttype = SADB_EXT_KEY_AUTH;
1793 key->sadb_key_bits = int_key.len * 8;
1794 key->sadb_key_len = PFKEY_LEN(sizeof(struct sadb_key) + int_key.len);
1795 memcpy(key + 1, int_key.ptr, int_key.len);
1796
1797 PFKEY_EXT_ADD(msg, key);
1798 }
1799
1800 if (ipcomp != IPCOMP_NONE)
1801 {
1802 /*TODO*/
1803 }
1804
1805 if (encap)
1806 {
1807 add_encap_ext(msg, src, dst, FALSE);
1808 }
1809
1810 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1811 {
1812 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x", ntohl(spi));
1813 return FAILED;
1814 }
1815 else if (out->sadb_msg_errno)
1816 {
1817 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x: %s (%d)",
1818 ntohl(spi), strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1819 free(out);
1820 return FAILED;
1821 }
1822 free(out);
1823
1824 /* for tunnel mode SAs we have to install an additional IPIP SA and
1825 * group the two SAs together */
1826 if (mode == MODE_TUNNEL)
1827 {
1828 if (add_ipip_sa(this, src, dst, spi, reqid) != SUCCESS ||
1829 group_ipip_sa(this, src, dst, spi, protocol, reqid) != SUCCESS)
1830 {
1831 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x", ntohl(spi));
1832 return FAILED;
1833 }
1834 }
1835
1836 this->mutex->lock(this->mutex);
1837 /* we cache this SA for two reasons:
1838 * - in case an SADB_X_NAT_T_MAPPING_NEW event occurs (we need to find the reqid then)
1839 * - to decide if an expired SA is still installed */
1840 this->installed_sas->insert_last(this->installed_sas,
1841 create_sa_entry(protocol, spi, reqid, src, dst, encap, inbound));
1842 this->mutex->unlock(this->mutex);
1843
1844 /* Although KLIPS supports SADB_EXT_LIFETIME_SOFT/HARD, we handle the lifetime
1845 * of SAs manually in the plugin. Refer to the comments in receive_events()
1846 * for details. */
1847 if (expire_soft)
1848 {
1849 schedule_expire(this, protocol, spi, reqid, EXPIRE_TYPE_SOFT, expire_soft);
1850 }
1851
1852 if (expire_hard)
1853 {
1854 schedule_expire(this, protocol, spi, reqid, EXPIRE_TYPE_HARD, expire_hard);
1855 }
1856
1857 return SUCCESS;
1858 }
1859
1860 /**
1861 * Implementation of kernel_interface_t.update_sa.
1862 */
1863 static status_t update_sa(private_kernel_klips_ipsec_t *this,
1864 u_int32_t spi, protocol_id_t protocol, u_int16_t cpi,
1865 host_t *src, host_t *dst,
1866 host_t *new_src, host_t *new_dst,
1867 bool encap, bool new_encap)
1868 {
1869 unsigned char request[PFKEY_BUFFER_SIZE];
1870 struct sadb_msg *msg, *out;
1871 struct sadb_sa *sa;
1872 size_t len;
1873
1874 /* we can't update the SA if any of the ip addresses have changed.
1875 * that's because we can't use SADB_UPDATE and by deleting and readding the
1876 * SA the sequence numbers would get lost */
1877 if (!src->ip_equals(src, new_src) ||
1878 !dst->ip_equals(dst, new_dst))
1879 {
1880 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x: address changes"
1881 " are not supported", ntohl(spi));
1882 return NOT_SUPPORTED;
1883 }
1884
1885 /* because KLIPS does not allow us to change the NAT-T type in an SADB_UPDATE,
1886 * we can't update the SA if the encap flag has changed since installing it */
1887 if (encap != new_encap)
1888 {
1889 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x: change of UDP"
1890 " encapsulation is not supported", ntohl(spi));
1891 return NOT_SUPPORTED;
1892 }
1893
1894 DBG2(DBG_KNL, "updating SAD entry with SPI %.8x from %#H..%#H to %#H..%#H",
1895 ntohl(spi), src, dst, new_src, new_dst);
1896
1897 memset(&request, 0, sizeof(request));
1898
1899 msg = (struct sadb_msg*)request;
1900 msg->sadb_msg_version = PF_KEY_V2;
1901 msg->sadb_msg_type = SADB_UPDATE;
1902 msg->sadb_msg_satype = proto_ike2satype(protocol);
1903 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1904
1905 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1906 sa->sadb_sa_exttype = SADB_EXT_SA;
1907 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1908 sa->sadb_sa_spi = spi;
1909 sa->sadb_sa_encrypt = SADB_EALG_AESCBC; /* ignored */
1910 sa->sadb_sa_auth = SADB_AALG_SHA1HMAC; /* ignored */
1911 sa->sadb_sa_state = SADB_SASTATE_MATURE;
1912 PFKEY_EXT_ADD(msg, sa);
1913
1914 add_addr_ext(msg, src, SADB_EXT_ADDRESS_SRC);
1915 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST);
1916
1917 add_encap_ext(msg, new_src, new_dst, TRUE);
1918
1919 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1920 {
1921 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x", ntohl(spi));
1922 return FAILED;
1923 }
1924 else if (out->sadb_msg_errno)
1925 {
1926 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x: %s (%d)",
1927 ntohl(spi), strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1928 free(out);
1929 return FAILED;
1930 }
1931 free(out);
1932
1933 return SUCCESS;
1934 }
1935
1936 /**
1937 * Implementation of kernel_interface_t.query_sa.
1938 */
1939 static status_t query_sa(private_kernel_klips_ipsec_t *this, host_t *src,
1940 host_t *dst, u_int32_t spi, protocol_id_t protocol,
1941 u_int64_t *bytes)
1942 {
1943 return NOT_SUPPORTED; /* TODO */
1944 }
1945
1946 /**
1947 * Implementation of kernel_interface_t.del_sa.
1948 */
1949 static status_t del_sa(private_kernel_klips_ipsec_t *this, host_t *src,
1950 host_t *dst, u_int32_t spi, protocol_id_t protocol,
1951 u_int16_t cpi)
1952 {
1953 unsigned char request[PFKEY_BUFFER_SIZE];
1954 struct sadb_msg *msg, *out;
1955 struct sadb_sa *sa;
1956 sa_entry_t *cached_sa;
1957 size_t len;
1958
1959 memset(&request, 0, sizeof(request));
1960
1961 /* all grouped SAs are automatically deleted by KLIPS as soon as
1962 * one of them is deleted, therefore we delete only the main one */
1963 DBG2(DBG_KNL, "deleting SAD entry with SPI %.8x", ntohl(spi));
1964
1965 this->mutex->lock(this->mutex);
1966 /* this should not fail, but we don't care if it does, let the kernel decide
1967 * whether this SA exists or not */
1968 if (this->installed_sas->find_first(this->installed_sas,
1969 (linked_list_match_t)sa_entry_match_bydst, (void**)&cached_sa,
1970 &protocol, &spi, dst) == SUCCESS)
1971 {
1972 this->installed_sas->remove(this->installed_sas, cached_sa, NULL);
1973 sa_entry_destroy(cached_sa);
1974 }
1975 this->mutex->unlock(this->mutex);
1976
1977 msg = (struct sadb_msg*)request;
1978 msg->sadb_msg_version = PF_KEY_V2;
1979 msg->sadb_msg_type = SADB_DELETE;
1980 msg->sadb_msg_satype = proto_ike2satype(protocol);
1981 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1982
1983 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1984 sa->sadb_sa_exttype = SADB_EXT_SA;
1985 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1986 sa->sadb_sa_spi = spi;
1987 PFKEY_EXT_ADD(msg, sa);
1988
1989 /* the kernel wants an SADB_EXT_ADDRESS_SRC to be present even though
1990 * it is not used for anything. */
1991 add_anyaddr_ext(msg, dst->get_family(dst), SADB_EXT_ADDRESS_SRC);
1992 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST);
1993
1994 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1995 {
1996 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x", ntohl(spi));
1997 return FAILED;
1998 }
1999 else if (out->sadb_msg_errno)
2000 {
2001 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x: %s (%d)",
2002 ntohl(spi), strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2003 free(out);
2004 return FAILED;
2005 }
2006
2007 DBG2(DBG_KNL, "deleted SAD entry with SPI %.8x", ntohl(spi));
2008 free(out);
2009 return SUCCESS;
2010 }
2011
2012 /**
2013 * Implementation of kernel_interface_t.add_policy.
2014 */
2015 static status_t add_policy(private_kernel_klips_ipsec_t *this,
2016 host_t *src, host_t *dst,
2017 traffic_selector_t *src_ts,
2018 traffic_selector_t *dst_ts,
2019 policy_dir_t direction, u_int32_t spi,
2020 protocol_id_t protocol, u_int32_t reqid,
2021 ipsec_mode_t mode, u_int16_t ipcomp, u_int16_t cpi,
2022 bool routed)
2023 {
2024 unsigned char request[PFKEY_BUFFER_SIZE];
2025 struct sadb_msg *msg, *out;
2026 policy_entry_t *policy, *found = NULL;
2027 u_int8_t satype;
2028 size_t len;
2029
2030 if (direction == POLICY_FWD)
2031 {
2032 /* no forward policies for KLIPS */
2033 return SUCCESS;
2034 }
2035
2036 /* tunnel mode policies direct the packets into the pseudo IPIP SA */
2037 satype = (mode == MODE_TUNNEL) ? SADB_X_SATYPE_IPIP :
2038 proto_ike2satype(protocol);
2039
2040 /* create a policy */
2041 policy = create_policy_entry(src_ts, dst_ts, direction);
2042
2043 /* find a matching policy */
2044 this->mutex->lock(this->mutex);
2045 if (this->policies->find_first(this->policies,
2046 (linked_list_match_t)policy_entry_equals, (void**)&found, policy) == SUCCESS)
2047 {
2048 /* use existing policy */
2049 DBG2(DBG_KNL, "policy %R === %R %N already exists, increasing"
2050 " refcount", src_ts, dst_ts,
2051 policy_dir_names, direction);
2052 policy_entry_destroy(policy);
2053 policy = found;
2054 }
2055 else
2056 {
2057 /* apply the new one, if we have no such policy */
2058 this->policies->insert_last(this->policies, policy);
2059 }
2060
2061 if (routed)
2062 {
2063 /* we install this as a %trap eroute in the kernel, later to be
2064 * triggered by packets matching the policy (-> ACQUIRE). */
2065 spi = htonl(SPI_TRAP);
2066 satype = SADB_X_SATYPE_INT;
2067
2068 /* the reqid is always set to the latest child SA that trapped this
2069 * policy. we will need this reqid upon receiving an acquire. */
2070 policy->reqid = reqid;
2071
2072 /* increase the trap counter */
2073 policy->trapcount++;
2074
2075 if (policy->activecount)
2076 {
2077 /* we do not replace the current policy in the kernel while a
2078 * policy is actively used */
2079 this->mutex->unlock(this->mutex);
2080 return SUCCESS;
2081 }
2082 }
2083 else
2084 {
2085 /* increase the reference counter */
2086 policy->activecount++;
2087 }
2088
2089 DBG2(DBG_KNL, "adding policy %R === %R %N", src_ts, dst_ts,
2090 policy_dir_names, direction);
2091
2092 memset(&request, 0, sizeof(request));
2093
2094 msg = (struct sadb_msg*)request;
2095
2096 /* FIXME: SADB_X_SAFLAGS_INFLOW may be required, if we add an inbound policy for an IPIP SA */
2097 build_addflow(msg, satype, spi, routed ? NULL : src, routed ? NULL : dst,
2098 policy->src.net, policy->src.mask, policy->dst.net, policy->dst.mask,
2099 policy->src.proto, found != NULL);
2100
2101 this->mutex->unlock(this->mutex);
2102
2103 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2104 {
2105 DBG1(DBG_KNL, "unable to add policy %R === %R %N", src_ts, dst_ts,
2106 policy_dir_names, direction);
2107 return FAILED;
2108 }
2109 else if (out->sadb_msg_errno)
2110 {
2111 DBG1(DBG_KNL, "unable to add policy %R === %R %N: %s (%d)", src_ts, dst_ts,
2112 policy_dir_names, direction,
2113 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2114 free(out);
2115 return FAILED;
2116 }
2117 free(out);
2118
2119 this->mutex->lock(this->mutex);
2120
2121 /* we try to find the policy again and install the route if needed */
2122 if (this->policies->find_last(this->policies, NULL, (void**)&policy) != SUCCESS)
2123 {
2124 this->mutex->unlock(this->mutex);
2125 DBG2(DBG_KNL, "the policy %R === %R %N is already gone, ignoring",
2126 src_ts, dst_ts, policy_dir_names, direction);
2127 return SUCCESS;
2128 }
2129
2130 /* KLIPS requires a special route that directs traffic that matches this
2131 * policy to one of the virtual ipsec interfaces. The virtual interface
2132 * has to be attached to the physical one the traffic runs over.
2133 * This is a special case of the source route we install in other kernel
2134 * interfaces.
2135 * In the following cases we do NOT install a source route (but just a
2136 * regular route):
2137 * - we are not in tunnel mode
2138 * - we are using IPv6 (does not work correctly yet!)
2139 * - routing is disabled via strongswan.conf
2140 */
2141 if (policy->route == NULL && direction == POLICY_OUT)
2142 {
2143 char *iface;
2144 ipsec_dev_t *dev;
2145 route_entry_t *route = malloc_thing(route_entry_t);
2146 route->src_ip = NULL;
2147
2148 if (mode != MODE_TRANSPORT && src->get_family(src) != AF_INET6 &&
2149 this->install_routes)
2150 {
2151 charon->kernel_interface->get_address_by_ts(charon->kernel_interface,
2152 src_ts, &route->src_ip);
2153 }
2154
2155 if (!route->src_ip)
2156 {
2157 route->src_ip = host_create_any(src->get_family(src));
2158 }
2159
2160 /* find the virtual interface */
2161 iface = charon->kernel_interface->get_interface(charon->kernel_interface,
2162 src);
2163 if (find_ipsec_dev(this, iface, &dev) == SUCCESS)
2164 {
2165 /* above, we got either the name of a virtual or a physical
2166 * interface. for both cases it means we already have the devices
2167 * properly attached (assuming that we are exclusively attaching
2168 * ipsec devices). */
2169 dev->refcount++;
2170 }
2171 else
2172 {
2173 /* there is no record of a mapping with the returned interface.
2174 * thus, we attach the first free virtual interface we find to
2175 * it. As above we assume we are the only client fiddling with
2176 * ipsec devices. */
2177 if (this->ipsec_devices->find_first(this->ipsec_devices,
2178 (linked_list_match_t)ipsec_dev_match_free,
2179 (void**)&dev) == SUCCESS)
2180 {
2181 if (attach_ipsec_dev(dev->name, iface) == SUCCESS)
2182 {
2183 strncpy(dev->phys_name, iface, IFNAMSIZ);
2184 dev->refcount = 1;
2185 }
2186 else
2187 {
2188 DBG1(DBG_KNL, "failed to attach virtual interface %s"
2189 " to %s", dev->name, iface);
2190 this->mutex->unlock(this->mutex);
2191 free(iface);
2192 return FAILED;
2193 }
2194 }
2195 else
2196 {
2197 this->mutex->unlock(this->mutex);
2198 DBG1(DBG_KNL, "failed to attach a virtual interface to %s: no"
2199 " virtual interfaces left", iface);
2200 free(iface);
2201 return FAILED;
2202 }
2203 }
2204 free(iface);
2205 route->if_name = strdup(dev->name);
2206
2207 /* get the nexthop to dst */
2208 route->gateway = charon->kernel_interface->get_nexthop(
2209 charon->kernel_interface, dst);
2210 route->dst_net = chunk_clone(policy->dst.net->get_address(policy->dst.net));
2211 route->prefixlen = policy->dst.mask;
2212
2213 switch (charon->kernel_interface->add_route(charon->kernel_interface,
2214 route->dst_net, route->prefixlen, route->gateway,
2215 route->src_ip, route->if_name))
2216 {
2217 default:
2218 DBG1(DBG_KNL, "unable to install route for policy %R === %R",
2219 src_ts, dst_ts);
2220 /* FALL */
2221 case ALREADY_DONE:
2222 /* route exists, do not uninstall */
2223 route_entry_destroy(route);
2224 break;
2225 case SUCCESS:
2226 /* cache the installed route */
2227 policy->route = route;
2228 break;
2229 }
2230 }
2231
2232 this->mutex->unlock(this->mutex);
2233
2234 return SUCCESS;
2235 }
2236
2237 /**
2238 * Implementation of kernel_interface_t.query_policy.
2239 */
2240 static status_t query_policy(private_kernel_klips_ipsec_t *this,
2241 traffic_selector_t *src_ts,
2242 traffic_selector_t *dst_ts,
2243 policy_dir_t direction, u_int32_t *use_time)
2244 {
2245 #define IDLE_PREFIX "idle="
2246 static const char *path_eroute = "/proc/net/ipsec_eroute";
2247 static const char *path_spi = "/proc/net/ipsec_spi";
2248 FILE *file;
2249 char line[1024], src[INET6_ADDRSTRLEN + 9], dst[INET6_ADDRSTRLEN + 9];
2250 char *said = NULL, *pos;
2251 policy_entry_t *policy, *found = NULL;
2252 status_t status = FAILED;
2253
2254 if (direction == POLICY_FWD)
2255 {
2256 /* we do not install forward policies */
2257 return FAILED;
2258 }
2259
2260 DBG2(DBG_KNL, "querying policy %R === %R %N", src_ts, dst_ts,
2261 policy_dir_names, direction);
2262
2263 /* create a policy */
2264 policy = create_policy_entry(src_ts, dst_ts, direction);
2265
2266 /* find a matching policy */
2267 this->mutex->lock(this->mutex);
2268 if (this->policies->find_first(this->policies,
2269 (linked_list_match_t)policy_entry_equals, (void**)&found, policy) != SUCCESS)
2270 {
2271 this->mutex->unlock(this->mutex);
2272 DBG1(DBG_KNL, "querying policy %R === %R %N failed, not found", src_ts,
2273 dst_ts, policy_dir_names, direction);
2274 policy_entry_destroy(policy);
2275 return NOT_FOUND;
2276 }
2277 policy_entry_destroy(policy);
2278 policy = found;
2279
2280 /* src and dst selectors in KLIPS are of the form NET_ADDR/NETBITS:PROTO */
2281 snprintf(src, sizeof(src), "%H/%d:%d", policy->src.net, policy->src.mask,
2282 policy->src.proto);
2283 src[sizeof(src) - 1] = '\0';
2284 snprintf(dst, sizeof(dst), "%H/%d:%d", policy->dst.net, policy->dst.mask,
2285 policy->dst.proto);
2286 dst[sizeof(dst) - 1] = '\0';
2287
2288 this->mutex->unlock(this->mutex);
2289
2290 /* we try to find the matching eroute first */
2291 file = fopen(path_eroute, "r");
2292 if (file == NULL)
2293 {
2294 DBG1(DBG_KNL, "unable to query policy %R === %R %N: %s (%d)", src_ts,
2295 dst_ts, policy_dir_names, direction, strerror(errno), errno);
2296 return FAILED;
2297 }
2298
2299 /* read line by line where each line looks like:
2300 * packets src -> dst => said */
2301 while (fgets(line, sizeof(line), file))
2302 {
2303 enumerator_t *enumerator;
2304 char *token;
2305 int i = 0;
2306
2307 enumerator = enumerator_create_token(line, " \t", " \t\n");
2308 while (enumerator->enumerate(enumerator, &token))
2309 {
2310 switch (i++)
2311 {
2312 case 0: /* packets */
2313 continue;
2314 case 1: /* src */
2315 if (streq(token, src))
2316 {
2317 continue;
2318 }
2319 break;
2320 case 2: /* -> */
2321 continue;
2322 case 3: /* dst */
2323 if (streq(token, dst))
2324 {
2325 continue;
2326 }
2327 break;
2328 case 4: /* => */
2329 continue;
2330 case 5: /* said */
2331 said = strdup(token);
2332 break;
2333 }
2334 break;
2335 }
2336 enumerator->destroy(enumerator);
2337
2338 if (i == 5)
2339 {
2340 /* eroute matched */
2341 break;
2342 }
2343 }
2344 fclose(file);
2345
2346 if (said == NULL)
2347 {
2348 DBG1(DBG_KNL, "unable to query policy %R === %R %N: found no matching"
2349 " eroute", src_ts, dst_ts, policy_dir_names, direction);
2350 return FAILED;
2351 }
2352
2353 /* compared with the one in the spi entry the SA ID from the eroute entry
2354 * has an additional ":PROTO" appended, which we need to cut off */
2355 pos = strrchr(said, ':');
2356 *pos = '\0';
2357
2358 /* now we try to find the matching spi entry */
2359 file = fopen(path_spi, "r");
2360 if (file == NULL)
2361 {
2362 DBG1(DBG_KNL, "unable to query policy %R === %R %N: %s (%d)", src_ts,
2363 dst_ts, policy_dir_names, direction, strerror(errno), errno);
2364 return FAILED;
2365 }
2366
2367 while (fgets(line, sizeof(line), file))
2368 {
2369 if (strneq(line, said, strlen(said)))
2370 {
2371 /* fine we found the correct line, now find the idle time */
2372 u_int32_t idle_time;
2373 pos = strstr(line, IDLE_PREFIX);
2374 if (pos == NULL)
2375 {
2376 /* no idle time, i.e. this SA has not been used yet */
2377 break;
2378 }
2379 if (sscanf(pos, IDLE_PREFIX"%u", &idle_time) <= 0)
2380 {
2381 /* idle time not valid */
2382 break;
2383 }
2384
2385 *use_time = time(NULL) - idle_time;
2386 status = SUCCESS;
2387 break;
2388 }
2389 }
2390 fclose(file);
2391 free(said);
2392
2393 return status;
2394 }
2395
2396 /**
2397 * Implementation of kernel_interface_t.del_policy.
2398 */
2399 static status_t del_policy(private_kernel_klips_ipsec_t *this,
2400 traffic_selector_t *src_ts,
2401 traffic_selector_t *dst_ts,
2402 policy_dir_t direction, bool unrouted)
2403 {
2404 unsigned char request[PFKEY_BUFFER_SIZE];
2405 struct sadb_msg *msg = (struct sadb_msg*)request, *out;
2406 policy_entry_t *policy, *found = NULL;
2407 route_entry_t *route;
2408 size_t len;
2409
2410 if (direction == POLICY_FWD)
2411 {
2412 /* no forward policies for KLIPS */
2413 return SUCCESS;
2414 }
2415
2416 DBG2(DBG_KNL, "deleting policy %R === %R %N", src_ts, dst_ts,
2417 policy_dir_names, direction);
2418
2419 /* create a policy */
2420 policy = create_policy_entry(src_ts, dst_ts, direction);
2421
2422 /* find a matching policy */
2423 this->mutex->lock(this->mutex);
2424 if (this->policies->find_first(this->policies,
2425 (linked_list_match_t)policy_entry_equals, (void**)&found, policy) != SUCCESS)
2426 {
2427 this->mutex->unlock(this->mutex);
2428 DBG1(DBG_KNL, "deleting policy %R === %R %N failed, not found", src_ts,
2429 dst_ts, policy_dir_names, direction);
2430 policy_entry_destroy(policy);
2431 return NOT_FOUND;
2432 }
2433 policy_entry_destroy(policy);
2434
2435 /* decrease appropriate counter */
2436 unrouted ? found->trapcount-- : found->activecount--;
2437
2438 if (found->trapcount == 0)
2439 {
2440 /* if this policy is finally unrouted, we reset the reqid because it
2441 * may still be actively used and there might be a pending acquire for
2442 * this policy. */
2443 found->reqid = 0;
2444 }
2445
2446 if (found->activecount > 0)
2447 {
2448 /* is still used by SAs, keep in kernel */
2449 this->mutex->unlock(this->mutex);
2450 DBG2(DBG_KNL, "policy still used by another CHILD_SA, not removed");
2451 return SUCCESS;
2452 }
2453 else if (found->activecount == 0 && found->trapcount > 0)
2454 {
2455 /* for a policy that is not used actively anymore, but is still trapped
2456 * by another child SA we replace the current eroute with a %trap eroute */
2457 DBG2(DBG_KNL, "policy still routed by another CHILD_SA, not removed");
2458 memset(&request, 0, sizeof(request));
2459 build_addflow(msg, SADB_X_SATYPE_INT, htonl(SPI_TRAP), NULL, NULL,
2460 found->src.net, found->src.mask, found->dst.net,
2461 found->dst.mask, found->src.proto, TRUE);
2462 this->mutex->unlock(this->mutex);
2463 return pfkey_send_ack(this, msg);
2464 }
2465
2466 /* remove if last reference */
2467 this->policies->remove(this->policies, found, NULL);
2468 policy = found;
2469
2470 this->mutex->unlock(this->mutex);
2471
2472 memset(&request, 0, sizeof(request));
2473
2474 build_delflow(msg, 0, policy->src.net, policy->src.mask, policy->dst.net,
2475 policy->dst.mask, policy->src.proto);
2476
2477 route = policy->route;
2478 policy->route = NULL;
2479 policy_entry_destroy(policy);
2480
2481 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2482 {
2483 DBG1(DBG_KNL, "unable to delete policy %R === %R %N", src_ts, dst_ts,
2484 policy_dir_names, direction);
2485 return FAILED;
2486 }
2487 else if (out->sadb_msg_errno)
2488 {
2489 DBG1(DBG_KNL, "unable to delete policy %R === %R %N: %s (%d)", src_ts,
2490 dst_ts, policy_dir_names, direction,
2491 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2492 free(out);
2493 return FAILED;
2494 }
2495 free(out);
2496
2497 if (route)
2498 {
2499 ipsec_dev_t *dev;
2500
2501 if (charon->kernel_interface->del_route(charon->kernel_interface,
2502 route->dst_net, route->prefixlen, route->gateway,
2503 route->src_ip, route->if_name) != SUCCESS)
2504 {
2505 DBG1(DBG_KNL, "error uninstalling route installed with"
2506 " policy %R === %R %N", src_ts, dst_ts,
2507 policy_dir_names, direction);
2508 }
2509
2510 /* we have to detach the ipsec interface from the physical one over which
2511 * this SA ran (if it is not used by any other) */
2512 this->mutex->lock(this->mutex);
2513
2514 if (find_ipsec_dev(this, route->if_name, &dev) == SUCCESS)
2515 {
2516 /* fine, we found a matching device object, let's check if we have
2517 * to detach it. */
2518 if (--dev->refcount == 0)
2519 {
2520 if (detach_ipsec_dev(dev->name, dev->phys_name) != SUCCESS)
2521 {
2522 DBG1(DBG_KNL, "failed to detach virtual interface %s"
2523 " from %s", dev->name, dev->phys_name);
2524 }
2525 dev->phys_name[0] = '\0';
2526 }
2527 }
2528
2529 this->mutex->unlock(this->mutex);
2530
2531 route_entry_destroy(route);
2532 }
2533
2534 return SUCCESS;
2535 }
2536
2537 /**
2538 * Initialize the list of ipsec devices
2539 */
2540 static void init_ipsec_devices(private_kernel_klips_ipsec_t *this)
2541 {
2542 int i, count = lib->settings->get_int(lib->settings,
2543 "charon.plugins.kernel_klips.ipsec_dev_count",
2544 DEFAULT_IPSEC_DEV_COUNT);
2545
2546 for (i = 0; i < count; ++i)
2547 {
2548 ipsec_dev_t *dev = malloc_thing(ipsec_dev_t);
2549 snprintf(dev->name, IFNAMSIZ, IPSEC_DEV_PREFIX"%d", i);
2550 dev->name[IFNAMSIZ - 1] = '\0';
2551 dev->phys_name[0] = '\0';
2552 dev->refcount = 0;
2553 this->ipsec_devices->insert_last(this->ipsec_devices, dev);
2554
2555 /* detach any previously attached ipsec device */
2556 detach_ipsec_dev(dev->name, dev->phys_name);
2557 }
2558 }
2559
2560 /**
2561 * Register a socket for AQUIRE/EXPIRE messages
2562 */
2563 static status_t register_pfkey_socket(private_kernel_klips_ipsec_t *this, u_int8_t satype)
2564 {
2565 unsigned char request[PFKEY_BUFFER_SIZE];
2566 struct sadb_msg *msg, *out;
2567 size_t len;
2568
2569 memset(&request, 0, sizeof(request));
2570
2571 msg = (struct sadb_msg*)request;
2572 msg->sadb_msg_version = PF_KEY_V2;
2573 msg->sadb_msg_type = SADB_REGISTER;
2574 msg->sadb_msg_satype = satype;
2575 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2576
2577 if (pfkey_send_socket(this, this->socket_events, msg, &out, &len) != SUCCESS)
2578 {
2579 DBG1(DBG_KNL, "unable to register PF_KEY socket");
2580 return FAILED;
2581 }
2582 else if (out->sadb_msg_errno)
2583 {
2584 DBG1(DBG_KNL, "unable to register PF_KEY socket: %s (%d)",
2585 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2586 free(out);
2587 return FAILED;
2588 }
2589 free(out);
2590 return SUCCESS;
2591 }
2592
2593 /**
2594 * Implementation of kernel_interface_t.destroy.
2595 */
2596 static void destroy(private_kernel_klips_ipsec_t *this)
2597 {
2598 this->job->cancel(this->job);
2599 close(this->socket);
2600 close(this->socket_events);
2601 this->mutex_pfkey->destroy(this->mutex_pfkey);
2602 this->mutex->destroy(this->mutex);
2603 this->ipsec_devices->destroy_function(this->ipsec_devices, (void*)ipsec_dev_destroy);
2604 this->installed_sas->destroy_function(this->installed_sas, (void*)sa_entry_destroy);
2605 this->allocated_spis->destroy_function(this->allocated_spis, (void*)sa_entry_destroy);
2606 this->policies->destroy_function(this->policies, (void*)policy_entry_destroy);
2607 free(this);
2608 }
2609
2610 /*
2611 * Described in header.
2612 */
2613 kernel_klips_ipsec_t *kernel_klips_ipsec_create()
2614 {
2615 private_kernel_klips_ipsec_t *this = malloc_thing(private_kernel_klips_ipsec_t);
2616
2617 /* public functions */
2618 this->public.interface.get_spi = (status_t(*)(kernel_ipsec_t*,host_t*,host_t*,protocol_id_t,u_int32_t,u_int32_t*))get_spi;
2619 this->public.interface.get_cpi = (status_t(*)(kernel_ipsec_t*,host_t*,host_t*,u_int32_t,u_int16_t*))get_cpi;
2620 this->public.interface.add_sa = (status_t(*)(kernel_ipsec_t *,host_t*,host_t*,u_int32_t,protocol_id_t,u_int32_t,u_int64_t,u_int64_t,u_int16_t,chunk_t,u_int16_t,chunk_t,ipsec_mode_t,u_int16_t,u_int16_t,bool,bool))add_sa;
2621 this->public.interface.update_sa = (status_t(*)(kernel_ipsec_t*,u_int32_t,protocol_id_t,u_int16_t,host_t*,host_t*,host_t*,host_t*,bool,bool))update_sa;
2622 this->public.interface.query_sa = (status_t(*)(kernel_ipsec_t*,host_t*,host_t*,u_int32_t,protocol_id_t,u_int64_t*))query_sa;
2623 this->public.interface.del_sa = (status_t(*)(kernel_ipsec_t*,host_t*,host_t*,u_int32_t,protocol_id_t,u_int16_t))del_sa;
2624 this->public.interface.add_policy = (status_t(*)(kernel_ipsec_t*,host_t*,host_t*,traffic_selector_t*,traffic_selector_t*,policy_dir_t,u_int32_t,protocol_id_t,u_int32_t,ipsec_mode_t,u_int16_t,u_int16_t,bool))add_policy;
2625 this->public.interface.query_policy = (status_t(*)(kernel_ipsec_t*,traffic_selector_t*,traffic_selector_t*,policy_dir_t,u_int32_t*))query_policy;
2626 this->public.interface.del_policy = (status_t(*)(kernel_ipsec_t*,traffic_selector_t*,traffic_selector_t*,policy_dir_t,bool))del_policy;
2627
2628 this->public.interface.destroy = (void(*)(kernel_ipsec_t*)) destroy;
2629
2630 /* private members */
2631 this->policies = linked_list_create();
2632 this->allocated_spis = linked_list_create();
2633 this->installed_sas = linked_list_create();
2634 this->ipsec_devices = linked_list_create();
2635 this->mutex = mutex_create(MUTEX_DEFAULT);
2636 this->mutex_pfkey = mutex_create(MUTEX_DEFAULT);
2637 this->install_routes = lib->settings->get_bool(lib->settings, "charon.install_routes", TRUE);
2638 this->seq = 0;
2639
2640 /* initialize ipsec devices */
2641 init_ipsec_devices(this);
2642
2643 /* create a PF_KEY socket to communicate with the kernel */
2644 this->socket = socket(PF_KEY, SOCK_RAW, PF_KEY_V2);
2645 if (this->socket <= 0)
2646 {
2647 charon->kill(charon, "unable to create PF_KEY socket");
2648 }
2649
2650 /* create a PF_KEY socket for ACQUIRE & EXPIRE */
2651 this->socket_events = socket(PF_KEY, SOCK_RAW, PF_KEY_V2);
2652 if (this->socket_events <= 0)
2653 {
2654 charon->kill(charon, "unable to create PF_KEY event socket");
2655 }
2656
2657 /* register the event socket */
2658 if (register_pfkey_socket(this, SADB_SATYPE_ESP) != SUCCESS ||
2659 register_pfkey_socket(this, SADB_SATYPE_AH) != SUCCESS)
2660 {
2661 charon->kill(charon, "unable to register PF_KEY event socket");
2662 }
2663
2664 this->job = callback_job_create((callback_job_cb_t)receive_events,
2665 this, NULL, NULL);
2666 charon->processor->queue_job(charon->processor, (job_t*)this->job);
2667
2668 return &this->public;
2669 }