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;
174 #if defined TIZEN_EXT
179 peer->last_allowedip = curaip;
185 static int parse_endpoint(const char *host, const char *port, struct sockaddr_u *addr)
187 struct addrinfo hints;
188 struct addrinfo *result, *rp;
191 memset(&hints, 0, sizeof(struct addrinfo));
192 hints.ai_family = AF_UNSPEC;
193 hints.ai_socktype = SOCK_DGRAM;
195 hints.ai_protocol = 0;
197 if (getaddrinfo(host, port, &hints, &result) < 0) {
198 DBG("Failed to resolve host address");
202 for (rp = result; rp; rp = rp->ai_next) {
203 sk = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
206 if (connect(sk, rp->ai_addr, rp->ai_addrlen) != -1) {
216 freeaddrinfo(result);
220 memcpy(addr, rp->ai_addr, rp->ai_addrlen);
221 freeaddrinfo(result);
226 static int parse_address(const char *address, const char *gateway,
227 struct connman_ipaddress **ipaddress)
229 char buf[INET6_ADDRSTRLEN];
230 unsigned char prefixlen;
235 tokens = g_strsplit(address, "/", -1);
236 if (g_strv_length(tokens) != 2) {
241 prefixlen = g_ascii_strtoull(tokens[1], &end, 10);
243 if (inet_pton(AF_INET, tokens[0], buf) == 1) {
244 netmask = g_strdup_printf("%d.%d.%d.%d",
245 ((0xffffffff << (32 - prefixlen)) >> 24) & 0xff,
246 ((0xffffffff << (32 - prefixlen)) >> 16) & 0xff,
247 ((0xffffffff << (32 - prefixlen)) >> 8) & 0xff,
248 ((0xffffffff << (32 - prefixlen)) >> 0) & 0xff);
250 *ipaddress = connman_ipaddress_alloc(AF_INET);
251 err = connman_ipaddress_set_ipv4(*ipaddress, tokens[0],
254 } else if (inet_pton(AF_INET6, tokens[0], buf) == 1) {
255 *ipaddress = connman_ipaddress_alloc(AF_INET6);
256 err = connman_ipaddress_set_ipv6(*ipaddress, tokens[0],
259 DBG("Invalid Wireguard.Address value");
265 connman_ipaddress_free(*ipaddress);
275 static void ifname_check_cb(int index, void *user_data)
277 struct ifname_data *data = (struct ifname_data *)user_data;
280 ifname = connman_inet_ifname(index);
282 if (!g_strcmp0(ifname, data->ifname))
286 static char *get_ifname(void)
288 struct ifname_data data;
291 for (i = 0; i < 256; i++) {
292 data.ifname = g_strdup_printf("wg%d", i);
294 vpn_ipconfig_foreach(ifname_check_cb, &data);
305 static bool sockaddr_cmp_addr(struct sockaddr_u *a, struct sockaddr_u *b)
307 if (a->sa.sa_family != b->sa.sa_family)
310 if (a->sa.sa_family == AF_INET)
311 return !memcmp(&a->sin, &b->sin, sizeof(struct sockaddr_in));
312 else if (a->sa.sa_family == AF_INET6)
313 return !memcmp(a->sin6.sin6_addr.s6_addr,
314 b->sin6.sin6_addr.s6_addr,
315 sizeof(a->sin6.sin6_addr.s6_addr));
320 #if defined TIZEN_EXT
322 #include <sys/types.h>
323 #include <sys/wait.h>
326 #define MAX_SIZE_ERROR_BUFFER 256
327 #define MAX_CMD_SIZE 80
330 struct vpn_provider *provider;
331 struct wireguard_info *info;
332 } wg_allowed_ip_route_cb_data_s;
334 static int wg_execute_cmd(const char *format, ...)
338 char cmd[MAX_CMD_SIZE] = { 0, };
339 char error_buf[MAX_SIZE_ERROR_BUFFER] = {0, };
344 va_start(va_ptr, format);
345 vsnprintf(cmd, (unsigned int) MAX_CMD_SIZE, format, va_ptr);
348 if (strlen(cmd) == 0)
351 DBG("command: %s", cmd);
353 args = g_strsplit_set(cmd, " ", -1);
356 if (!(pid = fork())) {
357 DBG("pid(%d), ppid (%d)", getpid(), getppid());
360 if (execv(args[0], args) == -1) {
361 DBG("Fail to execute command (%s)",
362 strerror_r(errno, error_buf, MAX_SIZE_ERROR_BUFFER));
366 } else if (pid > 0) {
367 if (waitpid(pid, &status, 0) == -1)
368 DBG("wait pid (%u) status (%d)", pid, status);
370 if (WIFEXITED(status)) {
371 rv = WEXITSTATUS(status);
372 DBG("exited, status=%d", rv);
374 } else if (WIFSIGNALED(status)) {
375 DBG("killed by signal %d", WTERMSIG(status));
377 } else if (WIFSTOPPED(status)) {
378 DBG("stopped by signal %d", WSTOPSIG(status));
380 } else if (WIFCONTINUED(status)) {
388 DBG("failed to fork(%s)", strerror_r(errno, error_buf, MAX_SIZE_ERROR_BUFFER));
394 static gboolean wg_add_allowed_ip_route_cb(gpointer user_data)
396 wg_allowed_ip_route_cb_data_s *cb_data = user_data;
397 const char *allowed_ips;
398 char **tokens = NULL;
404 allowed_ips = vpn_provider_get_string(cb_data->provider, "WireGuard.AllowedIPs");
406 DBG("WireGuard.AllowedIPs is missing");
410 tokens = g_strsplit(allowed_ips, ",", -1);
411 if (g_strv_length(tokens) == 0)
414 for (i = 0; tokens[i]; i++) {
415 int len = strlen(tokens[i]);
416 char *ptr = tokens[i];
419 //skip forward spaces
420 while (++j < len && ptr[j] == ' ')
426 toks = g_strsplit(ptr + j, "/", -1);
427 if (g_strv_length(toks) != 2) {
428 DBG("Ignore AllowedIPs value [%s]", ptr + j);
434 DBG("Allowed IP: [%s], Device Name: [%s]", ptr + j, cb_data->info->device.name);
436 // TODO: Remove system call to add route entry present in wg_execute_cmd()
437 if (!g_strcmp0("0.0.0.0/0", ptr + j)) {
438 // TODO: Update default route because user wants all data to be routed from wg0,
439 // when 0.0.0.0/0 is passed in allowed ips list.
440 // Should we replace the default route?
441 // If yes, then how to recover default route when wg0 tunnel is removed.
443 wg_execute_cmd("/usr/sbin/ip route add %s dev %s", ptr + j, cb_data->info->device.name);
455 #endif /* TIZEN_EXT */
457 static gboolean wg_dns_reresolve_cb(gpointer user_data)
459 struct wireguard_info *info = user_data;
460 struct sockaddr_u addr;
465 err = parse_endpoint(info->endpoint_fqdn,
470 if (sockaddr_cmp_addr(&addr,
471 (struct sockaddr_u *)&info->peer.endpoint.addr))
474 if (addr.sa.sa_family == AF_INET)
475 memcpy(&info->peer.endpoint.addr, &addr.sin,
476 sizeof(info->peer.endpoint.addr4));
478 memcpy(&info->peer.endpoint.addr, &addr.sin6,
479 sizeof(info->peer.endpoint.addr6));
481 DBG("Endpoint address has changed, udpate WireGuard device");
482 err = wg_set_device(&info->device);
484 DBG("Failed to update Endpoint address for WireGuard device %s",
490 static int wg_connect(struct vpn_provider *provider,
491 struct connman_task *task, const char *if_name,
492 vpn_provider_connect_cb_t cb,
493 const char *dbus_sender, void *user_data)
495 struct connman_ipaddress *ipaddress = NULL;
496 struct wireguard_info *info;
497 const char *option, *gateway;
501 info = g_malloc0(sizeof(struct wireguard_info));
502 info->peer.flags = WGPEER_HAS_PUBLIC_KEY | WGPEER_REPLACE_ALLOWEDIPS;
503 info->device.flags = WGDEVICE_HAS_PRIVATE_KEY;
504 info->device.first_peer = &info->peer;
505 info->device.last_peer = &info->peer;
507 vpn_provider_set_plugin_data(provider, info);
509 option = vpn_provider_get_string(provider, "WireGuard.ListenPort");
512 info->device.listen_port = g_ascii_strtoull(option, &end, 10);
513 info->device.flags |= WGDEVICE_HAS_LISTEN_PORT;
516 option = vpn_provider_get_string(provider, "WireGuard.DNS");
518 err = vpn_provider_set_nameservers(provider, option);
523 option = vpn_provider_get_string(provider, "WireGuard.PrivateKey");
525 DBG("WireGuard.PrivateKey is missing");
528 err = parse_key(option, info->device.private_key);
532 option = vpn_provider_get_string(provider, "WireGuard.PublicKey");
534 DBG("WireGuard.PublicKey is missing");
537 err = parse_key(option, info->peer.public_key);
541 option = vpn_provider_get_string(provider, "WireGuard.PresharedKey");
543 info->peer.flags |= WGPEER_HAS_PRESHARED_KEY;
544 err = parse_key(option, info->peer.preshared_key);
549 option = vpn_provider_get_string(provider, "WireGuard.AllowedIPs");
551 DBG("WireGuard.AllowedIPs is missing");
554 err = parse_allowed_ips(option, &info->peer);
558 option = vpn_provider_get_string(provider,
559 "WireGuard.PersistentKeepalive");
562 info->peer.persistent_keepalive_interval =
563 g_ascii_strtoull(option, &end, 10);
564 info->peer.flags |= WGPEER_HAS_PERSISTENT_KEEPALIVE_INTERVAL;
567 option = vpn_provider_get_string(provider, "WireGuard.EndpointPort");
571 gateway = vpn_provider_get_string(provider, "Host");
572 err = parse_endpoint(gateway, option,
573 (struct sockaddr_u *)&info->peer.endpoint.addr);
577 info->endpoint_fqdn = g_strdup(gateway);
578 info->port = g_strdup(option);
580 option = vpn_provider_get_string(provider, "WireGuard.Address");
582 DBG("Missing WireGuard.Address configuration");
585 err = parse_address(option, gateway, &ipaddress);
589 ifname = get_ifname();
591 DBG("Failed to find an usable device name");
595 stpncpy(info->device.name, ifname, sizeof(info->device.name) - 1);
598 err = wg_add_device(info->device.name);
600 DBG("Failed to creating WireGuard device %s", info->device.name);
604 err = wg_set_device(&info->device);
606 DBG("Failed to configure WireGuard device %s", info->device.name);
607 wg_del_device(info->device.name);
610 vpn_set_ifname(provider, info->device.name);
612 vpn_provider_set_ipaddress(provider, ipaddress);
616 cb(provider, user_data, err);
618 connman_ipaddress_free(ipaddress);
620 #if defined TIZEN_EXT
622 const char *allowed_ips = vpn_provider_get_string(provider, "WireGuard.AllowedIPs");
624 wg_allowed_ip_route_cb_data_s *cb_data =
625 (wg_allowed_ip_route_cb_data_s *) calloc(1, sizeof(wg_allowed_ip_route_cb_data_s));
627 cb_data->provider = provider;
628 cb_data->info = info;
630 info->allowed_ip_route_id =
631 g_timeout_add_seconds(ADD_ALLOWED_IP_ROUTE_TIMEOUT,
632 wg_add_allowed_ip_route_cb, cb_data);
636 #endif /* TIZEN_EXT */
640 g_timeout_add_seconds(DNS_RERESOLVE_TIMEOUT,
641 wg_dns_reresolve_cb, info);
646 static void wg_disconnect(struct vpn_provider *provider)
648 struct wireguard_info *info;
650 info = vpn_provider_get_plugin_data(provider);
654 #if defined TIZEN_EXT
655 if (info->allowed_ip_route_id > 0)
656 g_source_remove(info->allowed_ip_route_id);
657 #endif /* TIZEN_EXT */
659 if (info->reresolve_id > 0)
660 g_source_remove(info->reresolve_id);
662 vpn_provider_set_plugin_data(provider, NULL);
664 wg_del_device(info->device.name);
666 g_free(info->endpoint_fqdn);
671 #if defined TIZEN_EXT
672 static int wg_save(struct vpn_provider *provider, GKeyFile *keyfile)
679 * The client/own device listen port.
681 option = vpn_provider_get_string(provider, "WireGuard.ListenPort");
683 g_key_file_set_string(keyfile,
684 vpn_provider_get_save_group(provider),
685 "WireGuard.ListenPort",
689 * comma separated DNS.
691 option = vpn_provider_get_string(provider, "WireGuard.DNS");
693 g_key_file_set_string(keyfile,
694 vpn_provider_get_save_group(provider),
699 * The client private key.
701 option = vpn_provider_get_string(provider, "WireGuard.PrivateKey");
703 g_key_file_set_string(keyfile,
704 vpn_provider_get_save_group(provider),
705 "WireGuard.PrivateKey",
709 * The server public key.
711 option = vpn_provider_get_string(provider, "WireGuard.PublicKey");
713 g_key_file_set_string(keyfile,
714 vpn_provider_get_save_group(provider),
715 "WireGuard.PublicKey",
721 option = vpn_provider_get_string(provider, "WireGuard.PresharedKey");
723 g_key_file_set_string(keyfile,
724 vpn_provider_get_save_group(provider),
725 "WireGuard.PresharedKey",
729 * Subnets accessed via VPN tunnel, 0.0.0.0/0 routes all traffic.
731 option = vpn_provider_get_string(provider, "WireGuard.AllowedIPs");
733 g_key_file_set_string(keyfile,
734 vpn_provider_get_save_group(provider),
735 "WireGuard.AllowedIPs",
739 * The time in seconds to emit periodic keep alive message.
741 option = vpn_provider_get_string(provider, "WireGuard.PersistentKeepalive");
743 g_key_file_set_string(keyfile,
744 vpn_provider_get_save_group(provider),
745 "WireGuard.PersistentKeepalive",
749 * The server listen port, default: 51820
751 option = vpn_provider_get_string(provider, "WireGuard.EndpointPort");
753 g_key_file_set_string(keyfile,
754 vpn_provider_get_save_group(provider),
755 "WireGuard.EndpointPort",
759 * Save Address: The internal IP of the client node
761 option = vpn_provider_get_string(provider, "WireGuard.Address");
763 g_key_file_set_string(keyfile,
764 vpn_provider_get_save_group(provider),
772 static struct vpn_driver vpn_driver = {
773 .flags = VPN_FLAG_NO_TUN | VPN_FLAG_NO_DAEMON,
774 .connect = wg_connect,
775 .disconnect = wg_disconnect,
776 #if defined TIZEN_EXT
781 static int wg_init(void)
783 return vpn_register("wireguard", &vpn_driver, NULL);
786 static void wg_exit(void)
788 vpn_unregister("wireguard");
791 CONNMAN_PLUGIN_DEFINE(wireguard, "WireGuard VPN plugin", VERSION,
792 CONNMAN_PLUGIN_PRIORITY_DEFAULT, wg_init, wg_exit)