4 * Copyright (C) 2019 Daniel Wagner. All rights reserved.
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License version 2 as
8 * published by the Free Software Foundation.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
29 #include <arpa/inet.h>
30 #include <sys/types.h>
31 #include <sys/socket.h>
36 #define CONNMAN_API_SUBJECT_TO_CHANGE
37 #include <connman/plugin.h>
38 #include <connman/log.h>
39 #include <connman/task.h>
40 #include <connman/ipconfig.h>
41 #include <connman/inet.h>
42 #include <connman/dbus.h>
43 #include <connman/setting.h>
44 #include <connman/vpn-dbus.h>
46 #include "../vpn-provider.h"
50 #include "wireguard.h"
52 #define DNS_RERESOLVE_TIMEOUT 20
54 #define ADD_ALLOWED_IP_ROUTE_TIMEOUT 2
55 #endif /* TIZEN_EXT */
57 struct wireguard_info {
58 struct wg_device device;
64 int allowed_ip_route_id;
65 #endif /* TIZEN_EXT */
71 struct sockaddr_in sin;
72 struct sockaddr_in6 sin6;
76 static int parse_key(const char *str, wg_key key)
81 buf = g_base64_decode(str, &len);
94 static int parse_allowed_ips(const char *allowed_ips, wg_peer *peer)
96 struct wg_allowedip *curaip, *allowedip;
97 char buf[INET6_ADDRSTRLEN];
98 char **tokens, **toks;
103 #if defined TIZEN_EXT
105 * Note: At API level we donot check Wireguard specific configurations,
106 * User can provide any space separated string for IP.
107 * Ideally it should be using "10.0.0.2/32, 10.0.0.3/32"
108 * However there can be cases like "10.0.0.2/32,10.0.0.3/32"
110 * So we need to parse the allowed_ips configuration properly.
112 tokens = g_strsplit(allowed_ips, ",", -1);
114 tokens = g_strsplit(allowed_ips, ", ", -1);
116 for (i = 0; tokens[i]; i++) {
117 #if defined TIZEN_EXT
118 int len = strlen(tokens[i]);
119 char *ptr = tokens[i];
122 //skip forward spaces
123 while (++j < len && ptr[j] == ' ')
129 toks = g_strsplit(ptr + j, "/", -1);
130 if (g_strv_length(toks) != 2) {
131 DBG("Ignore AllowedIPs value [%s]", ptr + j);
136 DBG("Parsed AllowedIPs [%s]", ptr + j);
139 toks = g_strsplit(tokens[i], "/", -1);
140 if (g_strv_length(toks) != 2) {
141 DBG("Ignore AllowedIPs value %s", tokens[i]);
147 allowedip = g_malloc0(sizeof(*allowedip));
149 if (inet_pton(AF_INET, toks[0], buf) == 1) {
150 allowedip->family = AF_INET;
151 memcpy(&allowedip->ip4, buf, sizeof(allowedip->ip4));
152 } else if (inet_pton(AF_INET6, toks[0], buf) == 1) {
153 allowedip->family = AF_INET6;
154 memcpy(&allowedip->ip6, buf, sizeof(allowedip->ip6));
156 #if defined TIZEN_EXT
157 DBG("Ignore AllowedIPs value [%s]", ptr + j);
159 DBG("Ignore AllowedIPs value %s", tokens[i]);
166 allowedip->cidr = g_ascii_strtoull(toks[1], &send, 10);
169 peer->first_allowedip = allowedip;
171 curaip->next_allowedip = allowedip;
176 peer->last_allowedip = curaip;
182 static int parse_endpoint(const char *host, const char *port, struct sockaddr_u *addr)
184 struct addrinfo hints;
185 struct addrinfo *result, *rp;
188 memset(&hints, 0, sizeof(struct addrinfo));
189 hints.ai_family = AF_UNSPEC;
190 hints.ai_socktype = SOCK_DGRAM;
192 hints.ai_protocol = 0;
194 if (getaddrinfo(host, port, &hints, &result) < 0) {
195 DBG("Failed to resolve host address");
199 for (rp = result; rp; rp = rp->ai_next) {
200 sk = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
203 if (connect(sk, rp->ai_addr, rp->ai_addrlen) != -1) {
213 freeaddrinfo(result);
217 memcpy(addr, rp->ai_addr, rp->ai_addrlen);
218 freeaddrinfo(result);
223 static int parse_address(const char *address, const char *gateway,
224 struct connman_ipaddress **ipaddress)
226 char buf[INET6_ADDRSTRLEN];
227 unsigned char prefixlen;
232 tokens = g_strsplit(address, "/", -1);
233 if (g_strv_length(tokens) != 2) {
238 prefixlen = g_ascii_strtoull(tokens[1], &end, 10);
240 if (inet_pton(AF_INET, tokens[0], buf) == 1) {
241 netmask = g_strdup_printf("%d.%d.%d.%d",
242 ((0xffffffff << (32 - prefixlen)) >> 24) & 0xff,
243 ((0xffffffff << (32 - prefixlen)) >> 16) & 0xff,
244 ((0xffffffff << (32 - prefixlen)) >> 8) & 0xff,
245 ((0xffffffff << (32 - prefixlen)) >> 0) & 0xff);
247 *ipaddress = connman_ipaddress_alloc(AF_INET);
248 err = connman_ipaddress_set_ipv4(*ipaddress, tokens[0],
251 } else if (inet_pton(AF_INET6, tokens[0], buf) == 1) {
252 *ipaddress = connman_ipaddress_alloc(AF_INET6);
253 err = connman_ipaddress_set_ipv6(*ipaddress, tokens[0],
256 DBG("Invalid Wireguard.Address value");
262 connman_ipaddress_free(*ipaddress);
272 static void ifname_check_cb(int index, void *user_data)
274 struct ifname_data *data = (struct ifname_data *)user_data;
277 ifname = connman_inet_ifname(index);
279 if (!g_strcmp0(ifname, data->ifname))
283 static char *get_ifname(void)
285 struct ifname_data data;
288 for (i = 0; i < 256; i++) {
289 data.ifname = g_strdup_printf("wg%d", i);
291 vpn_ipconfig_foreach(ifname_check_cb, &data);
302 static bool sockaddr_cmp_addr(struct sockaddr_u *a, struct sockaddr_u *b)
304 if (a->sa.sa_family != b->sa.sa_family)
307 if (a->sa.sa_family == AF_INET)
308 return !memcmp(&a->sin, &b->sin, sizeof(struct sockaddr_in));
309 else if (a->sa.sa_family == AF_INET6)
310 return !memcmp(a->sin6.sin6_addr.s6_addr,
311 b->sin6.sin6_addr.s6_addr,
312 sizeof(a->sin6.sin6_addr.s6_addr));
317 #if defined TIZEN_EXT
319 #include <sys/types.h>
320 #include <sys/wait.h>
323 #define MAX_SIZE_ERROR_BUFFER 256
324 #define MAX_CMD_SIZE 80
327 struct vpn_provider *provider;
328 struct wireguard_info *info;
329 } wg_allowed_ip_route_cb_data_s;
331 static int wg_execute_cmd(const char *format, ...)
335 char cmd[MAX_CMD_SIZE] = { 0, };
336 char error_buf[MAX_SIZE_ERROR_BUFFER] = {0, };
341 va_start(va_ptr, format);
342 vsnprintf(cmd, (unsigned int) MAX_CMD_SIZE, format, va_ptr);
345 if (strlen(cmd) == 0)
348 DBG("command: %s", cmd);
350 args = g_strsplit_set(cmd, " ", -1);
353 if (!(pid = fork())) {
354 DBG("pid(%d), ppid (%d)", getpid(), getppid());
357 if (execv(args[0], args) == -1) {
358 DBG("Fail to execute command (%s)",
359 strerror_r(errno, error_buf, MAX_SIZE_ERROR_BUFFER));
363 } else if (pid > 0) {
364 if (waitpid(pid, &status, 0) == -1)
365 DBG("wait pid (%u) status (%d)", pid, status);
367 if (WIFEXITED(status)) {
368 rv = WEXITSTATUS(status);
369 DBG("exited, status=%d", rv);
371 } else if (WIFSIGNALED(status)) {
372 DBG("killed by signal %d", WTERMSIG(status));
374 } else if (WIFSTOPPED(status)) {
375 DBG("stopped by signal %d", WSTOPSIG(status));
377 } else if (WIFCONTINUED(status)) {
385 DBG("failed to fork(%s)", strerror_r(errno, error_buf, MAX_SIZE_ERROR_BUFFER));
391 static gboolean wg_add_allowed_ip_route_cb(gpointer user_data)
393 wg_allowed_ip_route_cb_data_s *cb_data = user_data;
394 const char *allowed_ips;
395 char **tokens = NULL;
401 allowed_ips = vpn_provider_get_string(cb_data->provider, "WireGuard.AllowedIPs");
403 DBG("WireGuard.AllowedIPs is missing");
407 tokens = g_strsplit(allowed_ips, ",", -1);
408 if (g_strv_length(tokens) == 0)
411 for (i = 0; tokens[i]; i++) {
412 int len = strlen(tokens[i]);
413 char *ptr = tokens[i];
416 //skip forward spaces
417 while (++j < len && ptr[j] == ' ')
423 toks = g_strsplit(ptr + j, "/", -1);
424 if (g_strv_length(toks) != 2) {
425 DBG("Ignore AllowedIPs value [%s]", ptr + j);
431 DBG("Allowed IP: [%s], Device Name: [%s]", ptr + j, cb_data->info->device.name);
433 // TODO: Remove system call to add route entry present in wg_execute_cmd()
434 if (!g_strcmp0("0.0.0.0/0", ptr + j)) {
435 // TODO: Update default route because user wants all data to be routed from wg0,
436 // when 0.0.0.0/0 is passed in allowed ips list.
437 // Should we replace the default route?
438 // If yes, then how to recover default route when wg0 tunnel is removed.
440 wg_execute_cmd("/usr/sbin/ip route add %s dev %s", ptr + j, cb_data->info->device.name);
452 #endif /* TIZEN_EXT */
454 static gboolean wg_dns_reresolve_cb(gpointer user_data)
456 struct wireguard_info *info = user_data;
457 struct sockaddr_u addr;
462 err = parse_endpoint(info->endpoint_fqdn,
467 if (sockaddr_cmp_addr(&addr,
468 (struct sockaddr_u *)&info->peer.endpoint.addr))
471 if (addr.sa.sa_family == AF_INET)
472 memcpy(&info->peer.endpoint.addr, &addr.sin,
473 sizeof(info->peer.endpoint.addr4));
475 memcpy(&info->peer.endpoint.addr, &addr.sin6,
476 sizeof(info->peer.endpoint.addr6));
478 DBG("Endpoint address has changed, udpate WireGuard device");
479 err = wg_set_device(&info->device);
481 DBG("Failed to update Endpoint address for WireGuard device %s",
487 static int wg_connect(struct vpn_provider *provider,
488 struct connman_task *task, const char *if_name,
489 vpn_provider_connect_cb_t cb,
490 const char *dbus_sender, void *user_data)
492 struct connman_ipaddress *ipaddress = NULL;
493 struct wireguard_info *info;
494 const char *option, *gateway;
498 info = g_malloc0(sizeof(struct wireguard_info));
499 info->peer.flags = WGPEER_HAS_PUBLIC_KEY | WGPEER_REPLACE_ALLOWEDIPS;
500 info->device.flags = WGDEVICE_HAS_PRIVATE_KEY;
501 info->device.first_peer = &info->peer;
502 info->device.last_peer = &info->peer;
504 vpn_provider_set_plugin_data(provider, info);
506 option = vpn_provider_get_string(provider, "WireGuard.ListenPort");
509 info->device.listen_port = g_ascii_strtoull(option, &end, 10);
510 info->device.flags |= WGDEVICE_HAS_LISTEN_PORT;
513 option = vpn_provider_get_string(provider, "WireGuard.DNS");
515 err = vpn_provider_set_nameservers(provider, option);
520 option = vpn_provider_get_string(provider, "WireGuard.PrivateKey");
522 DBG("WireGuard.PrivateKey is missing");
525 err = parse_key(option, info->device.private_key);
529 option = vpn_provider_get_string(provider, "WireGuard.PublicKey");
531 DBG("WireGuard.PublicKey is missing");
534 err = parse_key(option, info->peer.public_key);
538 option = vpn_provider_get_string(provider, "WireGuard.PresharedKey");
540 info->peer.flags |= WGPEER_HAS_PRESHARED_KEY;
541 err = parse_key(option, info->peer.preshared_key);
546 option = vpn_provider_get_string(provider, "WireGuard.AllowedIPs");
548 DBG("WireGuard.AllowedIPs is missing");
551 err = parse_allowed_ips(option, &info->peer);
555 option = vpn_provider_get_string(provider,
556 "WireGuard.PersistentKeepalive");
559 info->peer.persistent_keepalive_interval =
560 g_ascii_strtoull(option, &end, 10);
561 info->peer.flags |= WGPEER_HAS_PERSISTENT_KEEPALIVE_INTERVAL;
564 option = vpn_provider_get_string(provider, "WireGuard.EndpointPort");
568 gateway = vpn_provider_get_string(provider, "Host");
569 err = parse_endpoint(gateway, option,
570 (struct sockaddr_u *)&info->peer.endpoint.addr);
574 info->endpoint_fqdn = g_strdup(gateway);
575 info->port = g_strdup(option);
577 option = vpn_provider_get_string(provider, "WireGuard.Address");
579 DBG("Missing WireGuard.Address configuration");
582 err = parse_address(option, gateway, &ipaddress);
586 ifname = get_ifname();
588 DBG("Failed to find an usable device name");
592 stpncpy(info->device.name, ifname, sizeof(info->device.name) - 1);
595 err = wg_add_device(info->device.name);
597 DBG("Failed to creating WireGuard device %s", info->device.name);
601 err = wg_set_device(&info->device);
603 DBG("Failed to configure WireGuard device %s", info->device.name);
604 wg_del_device(info->device.name);
607 vpn_set_ifname(provider, info->device.name);
609 vpn_provider_set_ipaddress(provider, ipaddress);
613 cb(provider, user_data, err);
615 connman_ipaddress_free(ipaddress);
617 #if defined TIZEN_EXT
619 const char *allowed_ips = vpn_provider_get_string(provider, "WireGuard.AllowedIPs");
621 wg_allowed_ip_route_cb_data_s *cb_data =
622 (wg_allowed_ip_route_cb_data_s *) calloc(1, sizeof(wg_allowed_ip_route_cb_data_s));
624 cb_data->provider = provider;
625 cb_data->info = info;
627 info->allowed_ip_route_id =
628 g_timeout_add_seconds(ADD_ALLOWED_IP_ROUTE_TIMEOUT,
629 wg_add_allowed_ip_route_cb, cb_data);
633 #endif /* TIZEN_EXT */
637 g_timeout_add_seconds(DNS_RERESOLVE_TIMEOUT,
638 wg_dns_reresolve_cb, info);
643 static void wg_disconnect(struct vpn_provider *provider)
645 struct wireguard_info *info;
647 info = vpn_provider_get_plugin_data(provider);
651 #if defined TIZEN_EXT
652 if (info->allowed_ip_route_id > 0)
653 g_source_remove(info->allowed_ip_route_id);
654 #endif /* TIZEN_EXT */
656 if (info->reresolve_id > 0)
657 g_source_remove(info->reresolve_id);
659 vpn_provider_set_plugin_data(provider, NULL);
661 wg_del_device(info->device.name);
663 g_free(info->endpoint_fqdn);
668 #if defined TIZEN_EXT
669 static int wg_save(struct vpn_provider *provider, GKeyFile *keyfile)
676 * The client/own device listen port.
678 option = vpn_provider_get_string(provider, "WireGuard.ListenPort");
680 g_key_file_set_string(keyfile,
681 vpn_provider_get_save_group(provider),
682 "WireGuard.ListenPort",
686 * comma separated DNS.
688 option = vpn_provider_get_string(provider, "WireGuard.DNS");
690 g_key_file_set_string(keyfile,
691 vpn_provider_get_save_group(provider),
696 * The client private key.
698 option = vpn_provider_get_string(provider, "WireGuard.PrivateKey");
700 g_key_file_set_string(keyfile,
701 vpn_provider_get_save_group(provider),
702 "WireGuard.PrivateKey",
706 * The server public key.
708 option = vpn_provider_get_string(provider, "WireGuard.PublicKey");
710 g_key_file_set_string(keyfile,
711 vpn_provider_get_save_group(provider),
712 "WireGuard.PublicKey",
718 option = vpn_provider_get_string(provider, "WireGuard.PresharedKey");
720 g_key_file_set_string(keyfile,
721 vpn_provider_get_save_group(provider),
722 "WireGuard.PresharedKey",
726 * Subnets accessed via VPN tunnel, 0.0.0.0/0 routes all traffic.
728 option = vpn_provider_get_string(provider, "WireGuard.AllowedIPs");
730 g_key_file_set_string(keyfile,
731 vpn_provider_get_save_group(provider),
732 "WireGuard.AllowedIPs",
736 * The time in seconds to emit periodic keep alive message.
738 option = vpn_provider_get_string(provider, "WireGuard.PersistentKeepalive");
740 g_key_file_set_string(keyfile,
741 vpn_provider_get_save_group(provider),
742 "WireGuard.PersistentKeepalive",
746 * The server listen port, default: 51820
748 option = vpn_provider_get_string(provider, "WireGuard.EndpointPort");
750 g_key_file_set_string(keyfile,
751 vpn_provider_get_save_group(provider),
752 "WireGuard.EndpointPort",
756 * Save Address: The internal IP of the client node
758 option = vpn_provider_get_string(provider, "WireGuard.Address");
760 g_key_file_set_string(keyfile,
761 vpn_provider_get_save_group(provider),
769 static struct vpn_driver vpn_driver = {
770 .flags = VPN_FLAG_NO_TUN | VPN_FLAG_NO_DAEMON,
771 .connect = wg_connect,
772 .disconnect = wg_disconnect,
773 #if defined TIZEN_EXT
778 static int wg_init(void)
780 return vpn_register("wireguard", &vpn_driver, NULL);
783 static void wg_exit(void)
785 vpn_unregister("wireguard");
788 CONNMAN_PLUGIN_DEFINE(wireguard, "WireGuard VPN plugin", VERSION,
789 CONNMAN_PLUGIN_PRIORITY_DEFAULT, wg_init, wg_exit)