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