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