baf87ae1cc21d22dd0a975f8d5c946c250fea2c4
[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 lib->ns);
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 u_int16_t 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, u_int32_t replay_window,
1686 bool initiator, bool encap, bool esn, bool inbound,
1687 traffic_selector_t *src_ts, traffic_selector_t *dst_ts)
1688 {
1689 unsigned char request[PFKEY_BUFFER_SIZE];
1690 struct sadb_msg *msg, *out;
1691 struct sadb_sa *sa;
1692 struct sadb_key *key;
1693 size_t len;
1694
1695 if (inbound)
1696 {
1697 /* for inbound SAs we allocated an SPI via get_spi, so we first check
1698 * whether that SPI has already expired (race condition) */
1699 sa_entry_t *alloc_spi;
1700 this->mutex->lock(this->mutex);
1701 if (this->allocated_spis->find_first(this->allocated_spis,
1702 (linked_list_match_t)sa_entry_match_byid, (void**)&alloc_spi,
1703 &protocol, &spi, &reqid) != SUCCESS)
1704 {
1705 this->mutex->unlock(this->mutex);
1706 DBG1(DBG_KNL, "allocated SPI %.8x has already expired", ntohl(spi));
1707 return FAILED;
1708 }
1709 else
1710 {
1711 this->allocated_spis->remove(this->allocated_spis, alloc_spi, NULL);
1712 sa_entry_destroy(alloc_spi);
1713 }
1714 this->mutex->unlock(this->mutex);
1715 }
1716
1717 memset(&request, 0, sizeof(request));
1718
1719 DBG2(DBG_KNL, "adding SAD entry with SPI %.8x and reqid {%d}", ntohl(spi), reqid);
1720
1721 msg = (struct sadb_msg*)request;
1722 msg->sadb_msg_version = PF_KEY_V2;
1723 msg->sadb_msg_type = SADB_ADD;
1724 msg->sadb_msg_satype = proto2satype(protocol);
1725 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1726
1727 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1728 sa->sadb_sa_exttype = SADB_EXT_SA;
1729 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1730 sa->sadb_sa_spi = spi;
1731 sa->sadb_sa_state = SADB_SASTATE_MATURE;
1732 sa->sadb_sa_replay = (protocol == IPPROTO_COMP) ? 0 : 32;
1733 sa->sadb_sa_auth = lookup_algorithm(INTEGRITY_ALGORITHM, int_alg);
1734 sa->sadb_sa_encrypt = lookup_algorithm(ENCRYPTION_ALGORITHM, enc_alg);
1735 PFKEY_EXT_ADD(msg, sa);
1736
1737 add_addr_ext(msg, src, SADB_EXT_ADDRESS_SRC);
1738 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST);
1739
1740 if (enc_alg != ENCR_UNDEFINED)
1741 {
1742 if (!sa->sadb_sa_encrypt)
1743 {
1744 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1745 encryption_algorithm_names, enc_alg);
1746 return FAILED;
1747 }
1748 DBG2(DBG_KNL, " using encryption algorithm %N with key size %d",
1749 encryption_algorithm_names, enc_alg, enc_key.len * 8);
1750
1751 key = (struct sadb_key*)PFKEY_EXT_ADD_NEXT(msg);
1752 key->sadb_key_exttype = SADB_EXT_KEY_ENCRYPT;
1753 key->sadb_key_bits = enc_key.len * 8;
1754 key->sadb_key_len = PFKEY_LEN(sizeof(struct sadb_key) + enc_key.len);
1755 memcpy(key + 1, enc_key.ptr, enc_key.len);
1756
1757 PFKEY_EXT_ADD(msg, key);
1758 }
1759
1760 if (int_alg != AUTH_UNDEFINED)
1761 {
1762 if (!sa->sadb_sa_auth)
1763 {
1764 DBG1(DBG_KNL, "algorithm %N not supported by kernel!",
1765 integrity_algorithm_names, int_alg);
1766 return FAILED;
1767 }
1768 DBG2(DBG_KNL, " using integrity algorithm %N with key size %d",
1769 integrity_algorithm_names, int_alg, int_key.len * 8);
1770
1771 key = (struct sadb_key*)PFKEY_EXT_ADD_NEXT(msg);
1772 key->sadb_key_exttype = SADB_EXT_KEY_AUTH;
1773 key->sadb_key_bits = int_key.len * 8;
1774 key->sadb_key_len = PFKEY_LEN(sizeof(struct sadb_key) + int_key.len);
1775 memcpy(key + 1, int_key.ptr, int_key.len);
1776
1777 PFKEY_EXT_ADD(msg, key);
1778 }
1779
1780 if (ipcomp != IPCOMP_NONE)
1781 {
1782 /*TODO*/
1783 }
1784
1785 if (encap)
1786 {
1787 add_encap_ext(msg, src, dst, FALSE);
1788 }
1789
1790 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1791 {
1792 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x", ntohl(spi));
1793 return FAILED;
1794 }
1795 else if (out->sadb_msg_errno)
1796 {
1797 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x: %s (%d)",
1798 ntohl(spi), strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1799 free(out);
1800 return FAILED;
1801 }
1802 free(out);
1803
1804 /* for tunnel mode SAs we have to install an additional IPIP SA and
1805 * group the two SAs together */
1806 if (mode == MODE_TUNNEL)
1807 {
1808 if (add_ipip_sa(this, src, dst, spi, reqid) != SUCCESS ||
1809 group_ipip_sa(this, src, dst, spi, protocol, reqid) != SUCCESS)
1810 {
1811 DBG1(DBG_KNL, "unable to add SAD entry with SPI %.8x", ntohl(spi));
1812 return FAILED;
1813 }
1814 }
1815
1816 this->mutex->lock(this->mutex);
1817 /* we cache this SA for two reasons:
1818 * - in case an SADB_X_NAT_T_MAPPING_NEW event occurs (we need to find the reqid then)
1819 * - to decide if an expired SA is still installed */
1820 this->installed_sas->insert_last(this->installed_sas,
1821 create_sa_entry(protocol, spi, reqid, src, dst, encap, inbound));
1822 this->mutex->unlock(this->mutex);
1823
1824 /* Although KLIPS supports SADB_EXT_LIFETIME_SOFT/HARD, we handle the lifetime
1825 * of SAs manually in the plugin. Refer to the comments in receive_events()
1826 * for details. */
1827 if (lifetime->time.rekey)
1828 {
1829 schedule_expire(this, protocol, spi, reqid, EXPIRE_TYPE_SOFT, lifetime->time.rekey);
1830 }
1831
1832 if (lifetime->time.life)
1833 {
1834 schedule_expire(this, protocol, spi, reqid, EXPIRE_TYPE_HARD, lifetime->time.life);
1835 }
1836
1837 return SUCCESS;
1838 }
1839
1840 METHOD(kernel_ipsec_t, update_sa, status_t,
1841 private_kernel_klips_ipsec_t *this, u_int32_t spi, u_int8_t protocol,
1842 u_int16_t cpi, host_t *src, host_t *dst, host_t *new_src, host_t *new_dst,
1843 bool encap, bool new_encap, mark_t mark)
1844 {
1845 unsigned char request[PFKEY_BUFFER_SIZE];
1846 struct sadb_msg *msg, *out;
1847 struct sadb_sa *sa;
1848 size_t len;
1849
1850 /* we can't update the SA if any of the ip addresses have changed.
1851 * that's because we can't use SADB_UPDATE and by deleting and readding the
1852 * SA the sequence numbers would get lost */
1853 if (!src->ip_equals(src, new_src) ||
1854 !dst->ip_equals(dst, new_dst))
1855 {
1856 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x: address changes"
1857 " are not supported", ntohl(spi));
1858 return NOT_SUPPORTED;
1859 }
1860
1861 /* because KLIPS does not allow us to change the NAT-T type in an SADB_UPDATE,
1862 * we can't update the SA if the encap flag has changed since installing it */
1863 if (encap != new_encap)
1864 {
1865 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x: change of UDP"
1866 " encapsulation is not supported", ntohl(spi));
1867 return NOT_SUPPORTED;
1868 }
1869
1870 DBG2(DBG_KNL, "updating SAD entry with SPI %.8x from %#H..%#H to %#H..%#H",
1871 ntohl(spi), src, dst, new_src, new_dst);
1872
1873 memset(&request, 0, sizeof(request));
1874
1875 msg = (struct sadb_msg*)request;
1876 msg->sadb_msg_version = PF_KEY_V2;
1877 msg->sadb_msg_type = SADB_UPDATE;
1878 msg->sadb_msg_satype = proto2satype(protocol);
1879 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1880
1881 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1882 sa->sadb_sa_exttype = SADB_EXT_SA;
1883 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1884 sa->sadb_sa_spi = spi;
1885 sa->sadb_sa_encrypt = SADB_EALG_AESCBC; /* ignored */
1886 sa->sadb_sa_auth = SADB_AALG_SHA1HMAC; /* ignored */
1887 sa->sadb_sa_state = SADB_SASTATE_MATURE;
1888 PFKEY_EXT_ADD(msg, sa);
1889
1890 add_addr_ext(msg, src, SADB_EXT_ADDRESS_SRC);
1891 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST);
1892
1893 add_encap_ext(msg, new_src, new_dst, TRUE);
1894
1895 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1896 {
1897 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x", ntohl(spi));
1898 return FAILED;
1899 }
1900 else if (out->sadb_msg_errno)
1901 {
1902 DBG1(DBG_KNL, "unable to update SAD entry with SPI %.8x: %s (%d)",
1903 ntohl(spi), strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1904 free(out);
1905 return FAILED;
1906 }
1907 free(out);
1908
1909 return SUCCESS;
1910 }
1911
1912 METHOD(kernel_ipsec_t, query_sa, status_t,
1913 private_kernel_klips_ipsec_t *this, host_t *src, host_t *dst,
1914 u_int32_t spi, u_int8_t protocol, mark_t mark,
1915 u_int64_t *bytes, u_int64_t *packets, time_t *time)
1916 {
1917 return NOT_SUPPORTED; /* TODO */
1918 }
1919
1920 METHOD(kernel_ipsec_t, del_sa, status_t,
1921 private_kernel_klips_ipsec_t *this, host_t *src, host_t *dst,
1922 u_int32_t spi, u_int8_t protocol, u_int16_t cpi, mark_t mark)
1923 {
1924 unsigned char request[PFKEY_BUFFER_SIZE];
1925 struct sadb_msg *msg, *out;
1926 struct sadb_sa *sa;
1927 sa_entry_t *cached_sa;
1928 size_t len;
1929
1930 memset(&request, 0, sizeof(request));
1931
1932 /* all grouped SAs are automatically deleted by KLIPS as soon as
1933 * one of them is deleted, therefore we delete only the main one */
1934 DBG2(DBG_KNL, "deleting SAD entry with SPI %.8x", ntohl(spi));
1935
1936 this->mutex->lock(this->mutex);
1937 /* this should not fail, but we don't care if it does, let the kernel decide
1938 * whether this SA exists or not */
1939 if (this->installed_sas->find_first(this->installed_sas,
1940 (linked_list_match_t)sa_entry_match_bydst, (void**)&cached_sa,
1941 &protocol, &spi, dst) == SUCCESS)
1942 {
1943 this->installed_sas->remove(this->installed_sas, cached_sa, NULL);
1944 sa_entry_destroy(cached_sa);
1945 }
1946 this->mutex->unlock(this->mutex);
1947
1948 msg = (struct sadb_msg*)request;
1949 msg->sadb_msg_version = PF_KEY_V2;
1950 msg->sadb_msg_type = SADB_DELETE;
1951 msg->sadb_msg_satype = proto2satype(protocol);
1952 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
1953
1954 sa = (struct sadb_sa*)PFKEY_EXT_ADD_NEXT(msg);
1955 sa->sadb_sa_exttype = SADB_EXT_SA;
1956 sa->sadb_sa_len = PFKEY_LEN(sizeof(struct sadb_sa));
1957 sa->sadb_sa_spi = spi;
1958 PFKEY_EXT_ADD(msg, sa);
1959
1960 /* the kernel wants an SADB_EXT_ADDRESS_SRC to be present even though
1961 * it is not used for anything. */
1962 add_anyaddr_ext(msg, dst->get_family(dst), SADB_EXT_ADDRESS_SRC);
1963 add_addr_ext(msg, dst, SADB_EXT_ADDRESS_DST);
1964
1965 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
1966 {
1967 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x", ntohl(spi));
1968 return FAILED;
1969 }
1970 else if (out->sadb_msg_errno)
1971 {
1972 DBG1(DBG_KNL, "unable to delete SAD entry with SPI %.8x: %s (%d)",
1973 ntohl(spi), strerror(out->sadb_msg_errno), out->sadb_msg_errno);
1974 free(out);
1975 return FAILED;
1976 }
1977
1978 DBG2(DBG_KNL, "deleted SAD entry with SPI %.8x", ntohl(spi));
1979 free(out);
1980 return SUCCESS;
1981 }
1982
1983 METHOD(kernel_ipsec_t, add_policy, status_t,
1984 private_kernel_klips_ipsec_t *this, host_t *src, host_t *dst,
1985 traffic_selector_t *src_ts, traffic_selector_t *dst_ts,
1986 policy_dir_t direction, policy_type_t type, ipsec_sa_cfg_t *sa,
1987 mark_t mark, policy_priority_t priority)
1988 {
1989 unsigned char request[PFKEY_BUFFER_SIZE];
1990 struct sadb_msg *msg, *out;
1991 policy_entry_t *policy, *found = NULL;
1992 u_int32_t spi;
1993 u_int8_t satype;
1994 size_t len;
1995
1996 if (direction == POLICY_FWD)
1997 {
1998 /* no forward policies for KLIPS */
1999 return SUCCESS;
2000 }
2001
2002 /* tunnel mode policies direct the packets into the pseudo IPIP SA */
2003 satype = (sa->mode == MODE_TUNNEL) ? SADB_X_SATYPE_IPIP
2004 : proto2satype(sa->esp.use ? IPPROTO_ESP
2005 : IPPROTO_AH);
2006 spi = sa->esp.use ? sa->esp.spi : sa->ah.spi;
2007
2008 /* create a policy */
2009 policy = create_policy_entry(src_ts, dst_ts, direction);
2010
2011 /* find a matching policy */
2012 this->mutex->lock(this->mutex);
2013 if (this->policies->find_first(this->policies,
2014 (linked_list_match_t)policy_entry_equals, (void**)&found, policy) == SUCCESS)
2015 {
2016 /* use existing policy */
2017 DBG2(DBG_KNL, "policy %R === %R %N already exists, increasing"
2018 " refcount", src_ts, dst_ts,
2019 policy_dir_names, direction);
2020 policy_entry_destroy(policy);
2021 policy = found;
2022 }
2023 else
2024 {
2025 /* apply the new one, if we have no such policy */
2026 this->policies->insert_first(this->policies, policy);
2027 }
2028
2029 if (priority == POLICY_PRIORITY_ROUTED)
2030 {
2031 /* we install this as a %trap eroute in the kernel, later to be
2032 * triggered by packets matching the policy (-> ACQUIRE). */
2033 spi = htonl(SPI_TRAP);
2034 satype = SADB_X_SATYPE_INT;
2035
2036 /* the reqid is always set to the latest child SA that trapped this
2037 * policy. we will need this reqid upon receiving an acquire. */
2038 policy->reqid = sa->reqid;
2039
2040 /* increase the trap counter */
2041 policy->trapcount++;
2042
2043 if (policy->activecount)
2044 {
2045 /* we do not replace the current policy in the kernel while a
2046 * policy is actively used */
2047 this->mutex->unlock(this->mutex);
2048 return SUCCESS;
2049 }
2050 }
2051 else
2052 {
2053 /* increase the reference counter */
2054 policy->activecount++;
2055 }
2056
2057 DBG2(DBG_KNL, "adding policy %R === %R %N", src_ts, dst_ts,
2058 policy_dir_names, direction);
2059
2060 memset(&request, 0, sizeof(request));
2061
2062 msg = (struct sadb_msg*)request;
2063
2064 /* FIXME: SADB_X_SAFLAGS_INFLOW may be required, if we add an inbound policy for an IPIP SA */
2065 build_addflow(msg, satype, spi,
2066 priority == POLICY_PRIORITY_ROUTED ? NULL : src,
2067 priority == POLICY_PRIORITY_ROUTED ? NULL : dst,
2068 policy->src.net, policy->src.mask, policy->dst.net,
2069 policy->dst.mask, policy->src.proto, found != NULL);
2070
2071 this->mutex->unlock(this->mutex);
2072
2073 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2074 {
2075 DBG1(DBG_KNL, "unable to add policy %R === %R %N", src_ts, dst_ts,
2076 policy_dir_names, direction);
2077 return FAILED;
2078 }
2079 else if (out->sadb_msg_errno)
2080 {
2081 DBG1(DBG_KNL, "unable to add policy %R === %R %N: %s (%d)", src_ts, dst_ts,
2082 policy_dir_names, direction,
2083 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2084 free(out);
2085 return FAILED;
2086 }
2087 free(out);
2088
2089 this->mutex->lock(this->mutex);
2090
2091 /* we try to find the policy again and install the route if needed */
2092 if (this->policies->find_first(this->policies, NULL,
2093 (void**)&policy) != SUCCESS)
2094 {
2095 this->mutex->unlock(this->mutex);
2096 DBG2(DBG_KNL, "the policy %R === %R %N is already gone, ignoring",
2097 src_ts, dst_ts, policy_dir_names, direction);
2098 return SUCCESS;
2099 }
2100
2101 /* KLIPS requires a special route that directs traffic that matches this
2102 * policy to one of the virtual ipsec interfaces. The virtual interface
2103 * has to be attached to the physical one the traffic runs over.
2104 * This is a special case of the source route we install in other kernel
2105 * interfaces.
2106 * In the following cases we do NOT install a source route (but just a
2107 * regular route):
2108 * - we are not in tunnel mode
2109 * - we are using IPv6 (does not work correctly yet!)
2110 * - routing is disabled via strongswan.conf
2111 */
2112 if (policy->route == NULL && direction == POLICY_OUT)
2113 {
2114 char *iface = NULL;
2115 ipsec_dev_t *dev;
2116 route_entry_t *route = malloc_thing(route_entry_t);
2117 route->src_ip = NULL;
2118
2119 if (sa->mode != MODE_TRANSPORT && src->get_family(src) != AF_INET6 &&
2120 this->install_routes)
2121 {
2122 hydra->kernel_interface->get_address_by_ts(hydra->kernel_interface,
2123 src_ts, &route->src_ip, NULL);
2124 }
2125
2126 if (!route->src_ip)
2127 {
2128 route->src_ip = host_create_any(src->get_family(src));
2129 }
2130
2131 /* find the virtual interface */
2132 hydra->kernel_interface->get_interface(hydra->kernel_interface,
2133 src, &iface);
2134 if (find_ipsec_dev(this, iface, &dev) == SUCCESS)
2135 {
2136 /* above, we got either the name of a virtual or a physical
2137 * interface. for both cases it means we already have the devices
2138 * properly attached (assuming that we are exclusively attaching
2139 * ipsec devices). */
2140 dev->refcount++;
2141 }
2142 else
2143 {
2144 /* there is no record of a mapping with the returned interface.
2145 * thus, we attach the first free virtual interface we find to
2146 * it. As above we assume we are the only client fiddling with
2147 * ipsec devices. */
2148 if (this->ipsec_devices->find_first(this->ipsec_devices,
2149 (linked_list_match_t)ipsec_dev_match_free,
2150 (void**)&dev) == SUCCESS)
2151 {
2152 if (attach_ipsec_dev(dev->name, iface) == SUCCESS)
2153 {
2154 strncpy(dev->phys_name, iface, IFNAMSIZ);
2155 dev->refcount = 1;
2156 }
2157 else
2158 {
2159 DBG1(DBG_KNL, "failed to attach virtual interface %s"
2160 " to %s", dev->name, iface);
2161 this->mutex->unlock(this->mutex);
2162 free(iface);
2163 return FAILED;
2164 }
2165 }
2166 else
2167 {
2168 this->mutex->unlock(this->mutex);
2169 DBG1(DBG_KNL, "failed to attach a virtual interface to %s: no"
2170 " virtual interfaces left", iface);
2171 free(iface);
2172 return FAILED;
2173 }
2174 }
2175 free(iface);
2176 route->if_name = strdup(dev->name);
2177
2178 /* get the nexthop to dst */
2179 route->gateway = hydra->kernel_interface->get_nexthop(
2180 hydra->kernel_interface, dst, route->src_ip);
2181 route->dst_net = chunk_clone(policy->dst.net->get_address(policy->dst.net));
2182 route->prefixlen = policy->dst.mask;
2183
2184 switch (hydra->kernel_interface->add_route(hydra->kernel_interface,
2185 route->dst_net, route->prefixlen, route->gateway,
2186 route->src_ip, route->if_name))
2187 {
2188 default:
2189 DBG1(DBG_KNL, "unable to install route for policy %R === %R",
2190 src_ts, dst_ts);
2191 /* FALL */
2192 case ALREADY_DONE:
2193 /* route exists, do not uninstall */
2194 route_entry_destroy(route);
2195 break;
2196 case SUCCESS:
2197 /* cache the installed route */
2198 policy->route = route;
2199 break;
2200 }
2201 }
2202
2203 this->mutex->unlock(this->mutex);
2204
2205 return SUCCESS;
2206 }
2207
2208 METHOD(kernel_ipsec_t, query_policy, status_t,
2209 private_kernel_klips_ipsec_t *this, traffic_selector_t *src_ts,
2210 traffic_selector_t *dst_ts, policy_dir_t direction, mark_t mark,
2211 time_t *use_time)
2212 {
2213 #define IDLE_PREFIX "idle="
2214 static const char *path_eroute = "/proc/net/ipsec_eroute";
2215 static const char *path_spi = "/proc/net/ipsec_spi";
2216 FILE *file;
2217 char line[1024], src[INET6_ADDRSTRLEN + 9], dst[INET6_ADDRSTRLEN + 9];
2218 char *said = NULL, *pos;
2219 policy_entry_t *policy, *found = NULL;
2220 status_t status = FAILED;
2221
2222 if (direction == POLICY_FWD)
2223 {
2224 /* we do not install forward policies */
2225 return FAILED;
2226 }
2227
2228 DBG2(DBG_KNL, "querying policy %R === %R %N", src_ts, dst_ts,
2229 policy_dir_names, direction);
2230
2231 /* create a policy */
2232 policy = create_policy_entry(src_ts, dst_ts, direction);
2233
2234 /* find a matching policy */
2235 this->mutex->lock(this->mutex);
2236 if (this->policies->find_first(this->policies,
2237 (linked_list_match_t)policy_entry_equals, (void**)&found, policy) != SUCCESS)
2238 {
2239 this->mutex->unlock(this->mutex);
2240 DBG1(DBG_KNL, "querying policy %R === %R %N failed, not found", src_ts,
2241 dst_ts, policy_dir_names, direction);
2242 policy_entry_destroy(policy);
2243 return NOT_FOUND;
2244 }
2245 policy_entry_destroy(policy);
2246 policy = found;
2247
2248 /* src and dst selectors in KLIPS are of the form NET_ADDR/NETBITS:PROTO */
2249 snprintf(src, sizeof(src), "%H/%d:%d", policy->src.net, policy->src.mask,
2250 policy->src.proto);
2251 src[sizeof(src) - 1] = '\0';
2252 snprintf(dst, sizeof(dst), "%H/%d:%d", policy->dst.net, policy->dst.mask,
2253 policy->dst.proto);
2254 dst[sizeof(dst) - 1] = '\0';
2255
2256 this->mutex->unlock(this->mutex);
2257
2258 /* we try to find the matching eroute first */
2259 file = fopen(path_eroute, "r");
2260 if (file == NULL)
2261 {
2262 DBG1(DBG_KNL, "unable to query policy %R === %R %N: %s (%d)", src_ts,
2263 dst_ts, policy_dir_names, direction, strerror(errno), errno);
2264 return FAILED;
2265 }
2266
2267 /* read line by line where each line looks like:
2268 * packets src -> dst => said */
2269 while (fgets(line, sizeof(line), file))
2270 {
2271 enumerator_t *enumerator;
2272 char *token;
2273 int i = 0;
2274
2275 enumerator = enumerator_create_token(line, " \t", " \t\n");
2276 while (enumerator->enumerate(enumerator, &token))
2277 {
2278 switch (i++)
2279 {
2280 case 0: /* packets */
2281 continue;
2282 case 1: /* src */
2283 if (streq(token, src))
2284 {
2285 continue;
2286 }
2287 break;
2288 case 2: /* -> */
2289 continue;
2290 case 3: /* dst */
2291 if (streq(token, dst))
2292 {
2293 continue;
2294 }
2295 break;
2296 case 4: /* => */
2297 continue;
2298 case 5: /* said */
2299 said = strdup(token);
2300 break;
2301 }
2302 break;
2303 }
2304 enumerator->destroy(enumerator);
2305
2306 if (i == 5)
2307 {
2308 /* eroute matched */
2309 break;
2310 }
2311 }
2312 fclose(file);
2313
2314 if (said == NULL)
2315 {
2316 DBG1(DBG_KNL, "unable to query policy %R === %R %N: found no matching"
2317 " eroute", src_ts, dst_ts, policy_dir_names, direction);
2318 return FAILED;
2319 }
2320
2321 /* compared with the one in the spi entry the SA ID from the eroute entry
2322 * has an additional ":PROTO" appended, which we need to cut off */
2323 pos = strrchr(said, ':');
2324 *pos = '\0';
2325
2326 /* now we try to find the matching spi entry */
2327 file = fopen(path_spi, "r");
2328 if (file == NULL)
2329 {
2330 DBG1(DBG_KNL, "unable to query policy %R === %R %N: %s (%d)", src_ts,
2331 dst_ts, policy_dir_names, direction, strerror(errno), errno);
2332 return FAILED;
2333 }
2334
2335 while (fgets(line, sizeof(line), file))
2336 {
2337 if (strpfx(line, said))
2338 {
2339 /* fine we found the correct line, now find the idle time */
2340 u_int32_t idle_time;
2341 pos = strstr(line, IDLE_PREFIX);
2342 if (pos == NULL)
2343 {
2344 /* no idle time, i.e. this SA has not been used yet */
2345 break;
2346 }
2347 if (sscanf(pos, IDLE_PREFIX"%u", &idle_time) <= 0)
2348 {
2349 /* idle time not valid */
2350 break;
2351 }
2352
2353 *use_time = time_monotonic(NULL) - idle_time;
2354 status = SUCCESS;
2355 break;
2356 }
2357 }
2358 fclose(file);
2359 free(said);
2360
2361 return status;
2362 }
2363
2364 METHOD(kernel_ipsec_t, del_policy, status_t,
2365 private_kernel_klips_ipsec_t *this, traffic_selector_t *src_ts,
2366 traffic_selector_t *dst_ts, policy_dir_t direction, u_int32_t reqid,
2367 mark_t mark, policy_priority_t priority)
2368 {
2369 unsigned char request[PFKEY_BUFFER_SIZE];
2370 struct sadb_msg *msg = (struct sadb_msg*)request, *out;
2371 policy_entry_t *policy, *found = NULL;
2372 route_entry_t *route;
2373 size_t len;
2374
2375 if (direction == POLICY_FWD)
2376 {
2377 /* no forward policies for KLIPS */
2378 return SUCCESS;
2379 }
2380
2381 DBG2(DBG_KNL, "deleting policy %R === %R %N", src_ts, dst_ts,
2382 policy_dir_names, direction);
2383
2384 /* create a policy */
2385 policy = create_policy_entry(src_ts, dst_ts, direction);
2386
2387 /* find a matching policy */
2388 this->mutex->lock(this->mutex);
2389 if (this->policies->find_first(this->policies,
2390 (linked_list_match_t)policy_entry_equals, (void**)&found, policy) != SUCCESS)
2391 {
2392 this->mutex->unlock(this->mutex);
2393 DBG1(DBG_KNL, "deleting policy %R === %R %N failed, not found", src_ts,
2394 dst_ts, policy_dir_names, direction);
2395 policy_entry_destroy(policy);
2396 return NOT_FOUND;
2397 }
2398 policy_entry_destroy(policy);
2399
2400 /* decrease appropriate counter */
2401 priority == POLICY_PRIORITY_ROUTED ? found->trapcount--
2402 : found->activecount--;
2403
2404 if (found->trapcount == 0)
2405 {
2406 /* if this policy is finally unrouted, we reset the reqid because it
2407 * may still be actively used and there might be a pending acquire for
2408 * this policy. */
2409 found->reqid = 0;
2410 }
2411
2412 if (found->activecount > 0)
2413 {
2414 /* is still used by SAs, keep in kernel */
2415 this->mutex->unlock(this->mutex);
2416 DBG2(DBG_KNL, "policy still used by another CHILD_SA, not removed");
2417 return SUCCESS;
2418 }
2419 else if (found->activecount == 0 && found->trapcount > 0)
2420 {
2421 /* for a policy that is not used actively anymore, but is still trapped
2422 * by another child SA we replace the current eroute with a %trap eroute */
2423 DBG2(DBG_KNL, "policy still routed by another CHILD_SA, not removed");
2424 memset(&request, 0, sizeof(request));
2425 build_addflow(msg, SADB_X_SATYPE_INT, htonl(SPI_TRAP), NULL, NULL,
2426 found->src.net, found->src.mask, found->dst.net,
2427 found->dst.mask, found->src.proto, TRUE);
2428 this->mutex->unlock(this->mutex);
2429 return pfkey_send_ack(this, msg);
2430 }
2431
2432 /* remove if last reference */
2433 this->policies->remove(this->policies, found, NULL);
2434 policy = found;
2435
2436 this->mutex->unlock(this->mutex);
2437
2438 memset(&request, 0, sizeof(request));
2439
2440 build_delflow(msg, 0, policy->src.net, policy->src.mask, policy->dst.net,
2441 policy->dst.mask, policy->src.proto);
2442
2443 route = policy->route;
2444 policy->route = NULL;
2445 policy_entry_destroy(policy);
2446
2447 if (pfkey_send(this, msg, &out, &len) != SUCCESS)
2448 {
2449 DBG1(DBG_KNL, "unable to delete policy %R === %R %N", src_ts, dst_ts,
2450 policy_dir_names, direction);
2451 return FAILED;
2452 }
2453 else if (out->sadb_msg_errno)
2454 {
2455 DBG1(DBG_KNL, "unable to delete policy %R === %R %N: %s (%d)", src_ts,
2456 dst_ts, policy_dir_names, direction,
2457 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2458 free(out);
2459 return FAILED;
2460 }
2461 free(out);
2462
2463 if (route)
2464 {
2465 ipsec_dev_t *dev;
2466
2467 if (hydra->kernel_interface->del_route(hydra->kernel_interface,
2468 route->dst_net, route->prefixlen, route->gateway,
2469 route->src_ip, route->if_name) != SUCCESS)
2470 {
2471 DBG1(DBG_KNL, "error uninstalling route installed with"
2472 " policy %R === %R %N", src_ts, dst_ts,
2473 policy_dir_names, direction);
2474 }
2475
2476 /* we have to detach the ipsec interface from the physical one over which
2477 * this SA ran (if it is not used by any other) */
2478 this->mutex->lock(this->mutex);
2479
2480 if (find_ipsec_dev(this, route->if_name, &dev) == SUCCESS)
2481 {
2482 /* fine, we found a matching device object, let's check if we have
2483 * to detach it. */
2484 if (--dev->refcount == 0)
2485 {
2486 if (detach_ipsec_dev(dev->name, dev->phys_name) != SUCCESS)
2487 {
2488 DBG1(DBG_KNL, "failed to detach virtual interface %s"
2489 " from %s", dev->name, dev->phys_name);
2490 }
2491 dev->phys_name[0] = '\0';
2492 }
2493 }
2494
2495 this->mutex->unlock(this->mutex);
2496
2497 route_entry_destroy(route);
2498 }
2499
2500 return SUCCESS;
2501 }
2502
2503 /**
2504 * Initialize the list of ipsec devices
2505 */
2506 static void init_ipsec_devices(private_kernel_klips_ipsec_t *this)
2507 {
2508 int i, count = lib->settings->get_int(lib->settings,
2509 "%s.plugins.kernel-klips.ipsec_dev_count",
2510 DEFAULT_IPSEC_DEV_COUNT, lib->ns);
2511
2512 for (i = 0; i < count; ++i)
2513 {
2514 ipsec_dev_t *dev = malloc_thing(ipsec_dev_t);
2515 snprintf(dev->name, IFNAMSIZ, IPSEC_DEV_PREFIX"%d", i);
2516 dev->name[IFNAMSIZ - 1] = '\0';
2517 dev->phys_name[0] = '\0';
2518 dev->refcount = 0;
2519 this->ipsec_devices->insert_last(this->ipsec_devices, dev);
2520
2521 /* detach any previously attached ipsec device */
2522 detach_ipsec_dev(dev->name, dev->phys_name);
2523 }
2524 }
2525
2526 /**
2527 * Register a socket for ACQUIRE/EXPIRE messages
2528 */
2529 static status_t register_pfkey_socket(private_kernel_klips_ipsec_t *this, u_int8_t satype)
2530 {
2531 unsigned char request[PFKEY_BUFFER_SIZE];
2532 struct sadb_msg *msg, *out;
2533 size_t len;
2534
2535 memset(&request, 0, sizeof(request));
2536
2537 msg = (struct sadb_msg*)request;
2538 msg->sadb_msg_version = PF_KEY_V2;
2539 msg->sadb_msg_type = SADB_REGISTER;
2540 msg->sadb_msg_satype = satype;
2541 msg->sadb_msg_len = PFKEY_LEN(sizeof(struct sadb_msg));
2542
2543 if (pfkey_send_socket(this, this->socket_events, msg, &out, &len) != SUCCESS)
2544 {
2545 DBG1(DBG_KNL, "unable to register PF_KEY socket");
2546 return FAILED;
2547 }
2548 else if (out->sadb_msg_errno)
2549 {
2550 DBG1(DBG_KNL, "unable to register PF_KEY socket: %s (%d)",
2551 strerror(out->sadb_msg_errno), out->sadb_msg_errno);
2552 free(out);
2553 return FAILED;
2554 }
2555 free(out);
2556 return SUCCESS;
2557 }
2558
2559 METHOD(kernel_ipsec_t, destroy, void,
2560 private_kernel_klips_ipsec_t *this)
2561 {
2562 if (this->socket > 0)
2563 {
2564 close(this->socket);
2565 }
2566 if (this->socket_events > 0)
2567 {
2568 close(this->socket_events);
2569 }
2570 this->mutex_pfkey->destroy(this->mutex_pfkey);
2571 this->mutex->destroy(this->mutex);
2572 this->ipsec_devices->destroy_function(this->ipsec_devices, (void*)ipsec_dev_destroy);
2573 this->installed_sas->destroy_function(this->installed_sas, (void*)sa_entry_destroy);
2574 this->allocated_spis->destroy_function(this->allocated_spis, (void*)sa_entry_destroy);
2575 this->policies->destroy_function(this->policies, (void*)policy_entry_destroy);
2576 free(this);
2577 }
2578
2579 /*
2580 * Described in header.
2581 */
2582 kernel_klips_ipsec_t *kernel_klips_ipsec_create()
2583 {
2584 private_kernel_klips_ipsec_t *this;
2585
2586 INIT(this,
2587 .public = {
2588 .interface = {
2589 .get_spi = _get_spi,
2590 .get_cpi = _get_cpi,
2591 .add_sa = _add_sa,
2592 .update_sa = _update_sa,
2593 .query_sa = _query_sa,
2594 .del_sa = _del_sa,
2595 .flush_sas = (void*)return_failed,
2596 .add_policy = _add_policy,
2597 .query_policy = _query_policy,
2598 .del_policy = _del_policy,
2599 .flush_policies = (void*)return_failed,
2600 /* KLIPS does not need a bypass policy for IKE */
2601 .bypass_socket = (void*)return_true,
2602 /* KLIPS does not need enabling UDP decap explicitly */
2603 .enable_udp_decap = (void*)return_true,
2604 .destroy = _destroy,
2605 },
2606 },
2607 .policies = linked_list_create(),
2608 .allocated_spis = linked_list_create(),
2609 .installed_sas = linked_list_create(),
2610 .ipsec_devices = linked_list_create(),
2611 .mutex = mutex_create(MUTEX_TYPE_DEFAULT),
2612 .mutex_pfkey = mutex_create(MUTEX_TYPE_DEFAULT),
2613 .install_routes = lib->settings->get_bool(lib->settings,
2614 "%s.install_routes", TRUE,
2615 lib->ns),
2616 );
2617
2618 /* initialize ipsec devices */
2619 init_ipsec_devices(this);
2620
2621 /* create a PF_KEY socket to communicate with the kernel */
2622 this->socket = socket(PF_KEY, SOCK_RAW, PF_KEY_V2);
2623 if (this->socket <= 0)
2624 {
2625 DBG1(DBG_KNL, "unable to create PF_KEY socket");
2626 destroy(this);
2627 return NULL;
2628 }
2629
2630 /* create a PF_KEY socket for ACQUIRE & EXPIRE */
2631 this->socket_events = socket(PF_KEY, SOCK_RAW, PF_KEY_V2);
2632 if (this->socket_events <= 0)
2633 {
2634 DBG1(DBG_KNL, "unable to create PF_KEY event socket");
2635 destroy(this);
2636 return NULL;
2637 }
2638
2639 /* register the event socket */
2640 if (register_pfkey_socket(this, SADB_SATYPE_ESP) != SUCCESS ||
2641 register_pfkey_socket(this, SADB_SATYPE_AH) != SUCCESS)
2642 {
2643 DBG1(DBG_KNL, "unable to register PF_KEY event socket");
2644 destroy(this);
2645 return NULL;
2646 }
2647
2648 lib->processor->queue_job(lib->processor,
2649 (job_t*)callback_job_create_with_prio((callback_job_cb_t)receive_events,
2650 this, NULL, (callback_job_cancel_t)return_false, JOB_PRIO_CRITICAL));
2651
2652 return &this->public;
2653 }