1 /*
2 * OpenVPN -- An application to securely tunnel IP networks
3 * over a single TCP/UDP port, with support for SSL/TLS-based
4 * session authentication and key exchange,
5 * packet encryption, packet authentication, and
6 * packet compression.
7 *
8 * Copyright (C) 2002-2022 OpenVPN Inc <sales@openvpn.net>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2
12 * as published by the Free Software Foundation.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 */
23
24 /*
25 * Support routines for configuring and accessing TUN/TAP
26 * virtual network adapters.
27 *
28 * This file is based on the TUN/TAP driver interface routines
29 * from VTun by Maxim Krasnyansky <max_mk@yahoo.com>.
30 */
31
32 #ifdef HAVE_CONFIG_H
33 #include "config.h"
34 #elif defined(_MSC_VER)
35 #include "config-msvc.h"
36 #endif
37
38 #include "syshead.h"
39
40 #include "tun.h"
41 #include "fdmisc.h"
42 #include "common.h"
43 #include "run_command.h"
44 #include "socket.h"
45 #include "manage.h"
46 #include "route.h"
47 #include "win32.h"
48 #include "block_dns.h"
49 #include "networking.h"
50
51 #include "memdbg.h"
52
53 #ifdef _WIN32
54 #include "openvpn-msg.h"
55 #endif
56
57 #include <string.h>
58
59 #ifdef _WIN32
60
61 const static GUID GUID_DEVCLASS_NET = { 0x4d36e972L, 0xe325, 0x11ce, { 0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18 } };
62 const static GUID GUID_DEVINTERFACE_NET = { 0xcac88484, 0x7515, 0x4c03, { 0x82, 0xe6, 0x71, 0xa8, 0x7a, 0xba, 0xc3, 0x61 } };
63
64 /* #define SIMULATE_DHCP_FAILED */ /* simulate bad DHCP negotiation */
65
66 #define NI_TEST_FIRST (1<<0)
67 #define NI_IP_NETMASK (1<<1)
68 #define NI_OPTIONS (1<<2)
69
70 static void netsh_ifconfig(const struct tuntap_options *to,
71 DWORD adapter_index,
72 const in_addr_t ip,
73 const in_addr_t netmask,
74 const unsigned int flags);
75
76 static void windows_set_mtu(const int iface_index,
77 const short family,
78 const int mtu);
79
80 static void netsh_set_dns6_servers(const struct in6_addr *addr_list,
81 const int addr_len,
82 DWORD adapter_index);
83
84 static void netsh_command(const struct argv *a, int n, int msglevel);
85
86 static const char *netsh_get_id(const char *dev_node, struct gc_arena *gc);
87
88 static DWORD get_adapter_index_flexible(const char *name);
89
90 static bool
do_address_service(const bool add,const short family,const struct tuntap * tt)91 do_address_service(const bool add, const short family, const struct tuntap *tt)
92 {
93 bool ret = false;
94 ack_message_t ack;
95 struct gc_arena gc = gc_new();
96 HANDLE pipe = tt->options.msg_channel;
97
98 address_message_t addr = {
99 .header = {
100 (add ? msg_add_address : msg_del_address),
101 sizeof(address_message_t),
102 0
103 },
104 .family = family,
105 .iface = { .index = tt->adapter_index, .name = "" }
106 };
107
108 if (addr.iface.index == TUN_ADAPTER_INDEX_INVALID)
109 {
110 strncpy(addr.iface.name, tt->actual_name, sizeof(addr.iface.name));
111 addr.iface.name[sizeof(addr.iface.name) - 1] = '\0';
112 }
113
114 if (addr.family == AF_INET)
115 {
116 addr.address.ipv4.s_addr = htonl(tt->local);
117 addr.prefix_len = netmask_to_netbits2(tt->adapter_netmask);
118 msg(D_IFCONFIG, "INET address service: %s %s/%d",
119 add ? "add" : "remove",
120 print_in_addr_t(tt->local, 0, &gc), addr.prefix_len);
121 }
122 else
123 {
124 addr.address.ipv6 = tt->local_ipv6;
125 addr.prefix_len = (tt->type == DEV_TYPE_TUN) ? 128 : tt->netbits_ipv6;
126 msg(D_IFCONFIG, "INET6 address service: %s %s/%d",
127 add ? "add" : "remove",
128 print_in6_addr(tt->local_ipv6, 0, &gc), addr.prefix_len);
129 }
130
131 if (!send_msg_iservice(pipe, &addr, sizeof(addr), &ack, "TUN"))
132 {
133 goto out;
134 }
135
136 if (ack.error_number != NO_ERROR)
137 {
138 msg(M_WARN, "TUN: %s address failed using service: %s [status=%u if_index=%d]",
139 (add ? "adding" : "deleting"), strerror_win32(ack.error_number, &gc),
140 ack.error_number, addr.iface.index);
141 goto out;
142 }
143
144 ret = true;
145
146 out:
147 gc_free(&gc);
148 return ret;
149 }
150
151 static bool
do_dns_domain_service(bool add,const struct tuntap * tt)152 do_dns_domain_service(bool add, const struct tuntap *tt)
153 {
154 bool ret = false;
155 ack_message_t ack;
156 struct gc_arena gc = gc_new();
157 HANDLE pipe = tt->options.msg_channel;
158
159 if (!tt->options.domain) /* no domain to add or delete */
160 {
161 return true;
162 }
163
164 /* Use dns_cfg_msg with addr_len = 0 for setting only the DOMAIN */
165 dns_cfg_message_t dns = {
166 .header = {
167 (add ? msg_add_dns_cfg : msg_del_dns_cfg),
168 sizeof(dns_cfg_message_t),
169 0
170 },
171 .iface = { .index = tt->adapter_index, .name = "" },
172 .domains = "", /* set below */
173 .family = AF_INET, /* unused */
174 .addr_len = 0 /* add/delete only the domain, not DNS servers */
175 };
176
177 strncpynt(dns.iface.name, tt->actual_name, sizeof(dns.iface.name));
178 strncpynt(dns.domains, tt->options.domain, sizeof(dns.domains));
179 /* truncation of domain name is not checked as it can't happen
180 * with 512 bytes room in dns.domains.
181 */
182
183 msg(D_LOW, "%s dns domain on '%s' (if_index = %d) using service",
184 (add ? "Setting" : "Deleting"), dns.iface.name, dns.iface.index);
185 if (!send_msg_iservice(pipe, &dns, sizeof(dns), &ack, "TUN"))
186 {
187 goto out;
188 }
189
190 if (ack.error_number != NO_ERROR)
191 {
192 msg(M_WARN, "TUN: %s dns domain failed using service: %s [status=%u if_name=%s]",
193 (add ? "adding" : "deleting"), strerror_win32(ack.error_number, &gc),
194 ack.error_number, dns.iface.name);
195 goto out;
196 }
197
198 msg(M_INFO, "DNS domain %s using service", (add ? "set" : "deleted"));
199 ret = true;
200
201 out:
202 gc_free(&gc);
203 return ret;
204 }
205
206 static bool
do_dns_service(bool add,const short family,const struct tuntap * tt)207 do_dns_service(bool add, const short family, const struct tuntap *tt)
208 {
209 bool ret = false;
210 ack_message_t ack;
211 struct gc_arena gc = gc_new();
212 HANDLE pipe = tt->options.msg_channel;
213 int len = family == AF_INET6 ? tt->options.dns6_len : tt->options.dns_len;
214 int addr_len = add ? len : 0;
215 const char *ip_proto_name = family == AF_INET6 ? "IPv6" : "IPv4";
216
217 if (addr_len == 0 && add) /* no addresses to add */
218 {
219 return true;
220 }
221
222 /* Use dns_cfg_msg with domain = "" for setting only the DNS servers */
223 dns_cfg_message_t dns = {
224 .header = {
225 (add ? msg_add_dns_cfg : msg_del_dns_cfg),
226 sizeof(dns_cfg_message_t),
227 0
228 },
229 .iface = { .index = tt->adapter_index, .name = "" },
230 .domains = "",
231 .family = family,
232 .addr_len = addr_len
233 };
234
235 /* interface name is required */
236 strncpy(dns.iface.name, tt->actual_name, sizeof(dns.iface.name));
237 dns.iface.name[sizeof(dns.iface.name) - 1] = '\0';
238
239 if (addr_len > _countof(dns.addr))
240 {
241 addr_len = _countof(dns.addr);
242 dns.addr_len = addr_len;
243 msg(M_WARN, "Number of %s DNS addresses sent to service truncated to %d",
244 ip_proto_name, addr_len);
245 }
246
247 for (int i = 0; i < addr_len; ++i)
248 {
249 if (family == AF_INET6)
250 {
251 dns.addr[i].ipv6 = tt->options.dns6[i];
252 }
253 else
254 {
255 dns.addr[i].ipv4.s_addr = htonl(tt->options.dns[i]);
256 }
257 }
258
259 msg(D_LOW, "%s %s dns servers on '%s' (if_index = %d) using service",
260 (add ? "Setting" : "Deleting"), ip_proto_name, dns.iface.name, dns.iface.index);
261
262 if (!send_msg_iservice(pipe, &dns, sizeof(dns), &ack, "TUN"))
263 {
264 goto out;
265 }
266
267 if (ack.error_number != NO_ERROR)
268 {
269 msg(M_WARN, "TUN: %s %s dns failed using service: %s [status=%u if_name=%s]",
270 (add ? "adding" : "deleting"), ip_proto_name, strerror_win32(ack.error_number, &gc),
271 ack.error_number, dns.iface.name);
272 goto out;
273 }
274
275 msg(M_INFO, "%s dns servers %s using service", ip_proto_name, (add ? "set" : "deleted"));
276 ret = true;
277
278 out:
279 gc_free(&gc);
280 return ret;
281 }
282
283 static bool
do_set_mtu_service(const struct tuntap * tt,const short family,const int mtu)284 do_set_mtu_service(const struct tuntap *tt, const short family, const int mtu)
285 {
286 DWORD len;
287 bool ret = false;
288 ack_message_t ack;
289 struct gc_arena gc = gc_new();
290 HANDLE pipe = tt->options.msg_channel;
291 const char *family_name = (family == AF_INET6) ? "IPv6" : "IPv4";
292 set_mtu_message_t mtu_msg = {
293 .header = {
294 msg_set_mtu,
295 sizeof(set_mtu_message_t),
296 0
297 },
298 .iface = {.index = tt->adapter_index},
299 .mtu = mtu,
300 .family = family
301 };
302 strncpynt(mtu_msg.iface.name, tt->actual_name, sizeof(mtu_msg.iface.name));
303 if (family == AF_INET6 && mtu < 1280)
304 {
305 msg(M_INFO, "NOTE: IPv6 interface MTU < 1280 conflicts with IETF standards and might not work");
306 }
307
308 if (!send_msg_iservice(pipe, &mtu_msg, sizeof(mtu_msg), &ack, "Set_mtu"))
309 {
310 goto out;
311 }
312
313 if (ack.error_number != NO_ERROR)
314 {
315 msg(M_NONFATAL, "TUN: setting %s mtu using service failed: %s [status=%u if_index=%d]",
316 family_name, strerror_win32(ack.error_number, &gc), ack.error_number, mtu_msg.iface.index);
317 }
318 else
319 {
320 msg(M_INFO, "%s MTU set to %d on interface %d using service", family_name, mtu, mtu_msg.iface.index);
321 ret = true;
322 }
323
324 out:
325 gc_free(&gc);
326 return ret;
327 }
328
329 #endif /* ifdef _WIN32 */
330
331 #ifdef TARGET_SOLARIS
332 static void solaris_error_close(struct tuntap *tt, const struct env_set *es, const char *actual, bool unplumb_inet6);
333
334 #include <stropts.h>
335 #endif
336
337 #if defined(TARGET_DARWIN) && HAVE_NET_IF_UTUN_H
338 #include <sys/kern_control.h>
339 #include <net/if_utun.h>
340 #include <sys/sys_domain.h>
341 #endif
342
343 static void clear_tuntap(struct tuntap *tuntap);
344
345 bool
is_dev_type(const char * dev,const char * dev_type,const char * match_type)346 is_dev_type(const char *dev, const char *dev_type, const char *match_type)
347 {
348 ASSERT(match_type);
349 if (!dev)
350 {
351 return false;
352 }
353 if (dev_type)
354 {
355 return !strcmp(dev_type, match_type);
356 }
357 else
358 {
359 return !strncmp(dev, match_type, strlen(match_type));
360 }
361 }
362
363 int
dev_type_enum(const char * dev,const char * dev_type)364 dev_type_enum(const char *dev, const char *dev_type)
365 {
366 if (is_dev_type(dev, dev_type, "tun"))
367 {
368 return DEV_TYPE_TUN;
369 }
370 else if (is_dev_type(dev, dev_type, "tap"))
371 {
372 return DEV_TYPE_TAP;
373 }
374 else if (is_dev_type(dev, dev_type, "null"))
375 {
376 return DEV_TYPE_NULL;
377 }
378 else
379 {
380 return DEV_TYPE_UNDEF;
381 }
382 }
383
384 const char *
dev_type_string(const char * dev,const char * dev_type)385 dev_type_string(const char *dev, const char *dev_type)
386 {
387 switch (dev_type_enum(dev, dev_type))
388 {
389 case DEV_TYPE_TUN:
390 return "tun";
391
392 case DEV_TYPE_TAP:
393 return "tap";
394
395 case DEV_TYPE_NULL:
396 return "null";
397
398 default:
399 return "[unknown-dev-type]";
400 }
401 }
402
403 /*
404 * Try to predict the actual TUN/TAP device instance name,
405 * before the device is actually opened.
406 */
407 const char *
guess_tuntap_dev(const char * dev,const char * dev_type,const char * dev_node,struct gc_arena * gc)408 guess_tuntap_dev(const char *dev,
409 const char *dev_type,
410 const char *dev_node,
411 struct gc_arena *gc)
412 {
413 #ifdef _WIN32
414 const int dt = dev_type_enum(dev, dev_type);
415 if (dt == DEV_TYPE_TUN || dt == DEV_TYPE_TAP)
416 {
417 return netsh_get_id(dev_node, gc);
418 }
419 #endif
420
421 /* default case */
422 return dev;
423 }
424
425
426 /* --ifconfig-nowarn disables some options sanity checking */
427 static const char ifconfig_warn_how_to_silence[] = "(silence this warning with --ifconfig-nowarn)";
428
429 /*
430 * If !tun, make sure ifconfig_remote_netmask looks
431 * like a netmask.
432 *
433 * If tun, make sure ifconfig_remote_netmask looks
434 * like an IPv4 address.
435 */
436 static void
ifconfig_sanity_check(bool tun,in_addr_t addr,int topology)437 ifconfig_sanity_check(bool tun, in_addr_t addr, int topology)
438 {
439 struct gc_arena gc = gc_new();
440 const bool looks_like_netmask = ((addr & 0xFF000000) == 0xFF000000);
441 if (tun)
442 {
443 if (looks_like_netmask && (topology == TOP_NET30 || topology == TOP_P2P))
444 {
445 msg(M_WARN, "WARNING: Since you are using --dev tun with a point-to-point topology, the second argument to --ifconfig must be an IP address. You are using something (%s) that looks more like a netmask. %s",
446 print_in_addr_t(addr, 0, &gc),
447 ifconfig_warn_how_to_silence);
448 }
449 }
450 else /* tap */
451 {
452 if (!looks_like_netmask)
453 {
454 msg(M_WARN, "WARNING: Since you are using --dev tap, the second argument to --ifconfig must be a netmask, for example something like 255.255.255.0. %s",
455 ifconfig_warn_how_to_silence);
456 }
457 }
458 gc_free(&gc);
459 }
460
461 /*
462 * Check that --local and --remote addresses do not
463 * clash with ifconfig addresses or subnet.
464 */
465 static void
check_addr_clash(const char * name,int type,in_addr_t public,in_addr_t local,in_addr_t remote_netmask)466 check_addr_clash(const char *name,
467 int type,
468 in_addr_t public,
469 in_addr_t local,
470 in_addr_t remote_netmask)
471 {
472 struct gc_arena gc = gc_new();
473 #if 0
474 msg(M_INFO, "CHECK_ADDR_CLASH type=%d public=%s local=%s, remote_netmask=%s",
475 type,
476 print_in_addr_t(public, 0, &gc),
477 print_in_addr_t(local, 0, &gc),
478 print_in_addr_t(remote_netmask, 0, &gc));
479 #endif
480
481 if (public)
482 {
483 if (type == DEV_TYPE_TUN)
484 {
485 const in_addr_t test_netmask = 0xFFFFFF00;
486 const in_addr_t public_net = public & test_netmask;
487 const in_addr_t local_net = local & test_netmask;
488 const in_addr_t remote_net = remote_netmask & test_netmask;
489
490 if (public == local || public == remote_netmask)
491 {
492 msg(M_WARN,
493 "WARNING: --%s address [%s] conflicts with --ifconfig address pair [%s, %s]. %s",
494 name,
495 print_in_addr_t(public, 0, &gc),
496 print_in_addr_t(local, 0, &gc),
497 print_in_addr_t(remote_netmask, 0, &gc),
498 ifconfig_warn_how_to_silence);
499 }
500
501 if (public_net == local_net || public_net == remote_net)
502 {
503 msg(M_WARN,
504 "WARNING: potential conflict between --%s address [%s] and --ifconfig address pair [%s, %s] -- this is a warning only that is triggered when local/remote addresses exist within the same /24 subnet as --ifconfig endpoints. %s",
505 name,
506 print_in_addr_t(public, 0, &gc),
507 print_in_addr_t(local, 0, &gc),
508 print_in_addr_t(remote_netmask, 0, &gc),
509 ifconfig_warn_how_to_silence);
510 }
511 }
512 else if (type == DEV_TYPE_TAP)
513 {
514 const in_addr_t public_network = public & remote_netmask;
515 const in_addr_t virtual_network = local & remote_netmask;
516 if (public_network == virtual_network)
517 {
518 msg(M_WARN,
519 "WARNING: --%s address [%s] conflicts with --ifconfig subnet [%s, %s] -- local and remote addresses cannot be inside of the --ifconfig subnet. %s",
520 name,
521 print_in_addr_t(public, 0, &gc),
522 print_in_addr_t(local, 0, &gc),
523 print_in_addr_t(remote_netmask, 0, &gc),
524 ifconfig_warn_how_to_silence);
525 }
526 }
527 }
528 gc_free(&gc);
529 }
530
531 /*
532 * Issue a warning if ip/netmask (on the virtual IP network) conflicts with
533 * the settings on the local LAN. This is designed to flag issues where
534 * (for example) the OpenVPN server LAN is running on 192.168.1.x, but then
535 * an OpenVPN client tries to connect from a public location that is also running
536 * off of a router set to 192.168.1.x.
537 */
538 void
check_subnet_conflict(const in_addr_t ip,const in_addr_t netmask,const char * prefix)539 check_subnet_conflict(const in_addr_t ip,
540 const in_addr_t netmask,
541 const char *prefix)
542 {
543 #if 0 /* too many false positives */
544 struct gc_arena gc = gc_new();
545 in_addr_t lan_gw = 0;
546 in_addr_t lan_netmask = 0;
547
548 if (get_default_gateway(&lan_gw, &lan_netmask) && lan_netmask)
549 {
550 const in_addr_t lan_network = lan_gw & lan_netmask;
551 const in_addr_t network = ip & netmask;
552
553 /* do the two subnets defined by network/netmask and lan_network/lan_netmask intersect? */
554 if ((network & lan_netmask) == lan_network
555 || (lan_network & netmask) == network)
556 {
557 msg(M_WARN, "WARNING: potential %s subnet conflict between local LAN [%s/%s] and remote VPN [%s/%s]",
558 prefix,
559 print_in_addr_t(lan_network, 0, &gc),
560 print_in_addr_t(lan_netmask, 0, &gc),
561 print_in_addr_t(network, 0, &gc),
562 print_in_addr_t(netmask, 0, &gc));
563 }
564 }
565 gc_free(&gc);
566 #endif /* if 0 */
567 }
568
569 void
warn_on_use_of_common_subnets(openvpn_net_ctx_t * ctx)570 warn_on_use_of_common_subnets(openvpn_net_ctx_t *ctx)
571 {
572 struct gc_arena gc = gc_new();
573 struct route_gateway_info rgi;
574 const int needed = (RGI_ADDR_DEFINED|RGI_NETMASK_DEFINED);
575
576 get_default_gateway(&rgi, ctx);
577 if ((rgi.flags & needed) == needed)
578 {
579 const in_addr_t lan_network = rgi.gateway.addr & rgi.gateway.netmask;
580 if (lan_network == 0xC0A80000 || lan_network == 0xC0A80100)
581 {
582 msg(M_WARN, "NOTE: your local LAN uses the extremely common subnet address 192.168.0.x or 192.168.1.x. Be aware that this might create routing conflicts if you connect to the VPN server from public locations such as internet cafes that use the same subnet.");
583 }
584 }
585 gc_free(&gc);
586 }
587
588 /*
589 * Return a string to be used for options compatibility check
590 * between peers.
591 */
592 const char *
ifconfig_options_string(const struct tuntap * tt,bool remote,bool disable,struct gc_arena * gc)593 ifconfig_options_string(const struct tuntap *tt, bool remote, bool disable, struct gc_arena *gc)
594 {
595 struct buffer out = alloc_buf_gc(256, gc);
596 if (tt->did_ifconfig_setup && !disable)
597 {
598 if (tt->type == DEV_TYPE_TAP || (tt->type == DEV_TYPE_TUN && tt->topology == TOP_SUBNET))
599 {
600 buf_printf(&out, "%s %s",
601 print_in_addr_t(tt->local & tt->remote_netmask, 0, gc),
602 print_in_addr_t(tt->remote_netmask, 0, gc));
603 }
604 else if (tt->type == DEV_TYPE_TUN)
605 {
606 const char *l, *r;
607 if (remote)
608 {
609 r = print_in_addr_t(tt->local, 0, gc);
610 l = print_in_addr_t(tt->remote_netmask, 0, gc);
611 }
612 else
613 {
614 l = print_in_addr_t(tt->local, 0, gc);
615 r = print_in_addr_t(tt->remote_netmask, 0, gc);
616 }
617 buf_printf(&out, "%s %s", r, l);
618 }
619 else
620 {
621 buf_printf(&out, "[undef]");
622 }
623 }
624 return BSTR(&out);
625 }
626
627 /*
628 * Return a status string describing wait state.
629 */
630 const char *
tun_stat(const struct tuntap * tt,unsigned int rwflags,struct gc_arena * gc)631 tun_stat(const struct tuntap *tt, unsigned int rwflags, struct gc_arena *gc)
632 {
633 struct buffer out = alloc_buf_gc(64, gc);
634 if (tt)
635 {
636 if (rwflags & EVENT_READ)
637 {
638 buf_printf(&out, "T%s",
639 (tt->rwflags_debug & EVENT_READ) ? "R" : "r");
640 #ifdef _WIN32
641 buf_printf(&out, "%s",
642 overlapped_io_state_ascii(&tt->reads));
643 #endif
644 }
645 if (rwflags & EVENT_WRITE)
646 {
647 buf_printf(&out, "T%s",
648 (tt->rwflags_debug & EVENT_WRITE) ? "W" : "w");
649 #ifdef _WIN32
650 buf_printf(&out, "%s",
651 overlapped_io_state_ascii(&tt->writes));
652 #endif
653 }
654 }
655 else
656 {
657 buf_printf(&out, "T?");
658 }
659 return BSTR(&out);
660 }
661
662 /*
663 * Return true for point-to-point topology, false for subnet topology
664 */
665 bool
is_tun_p2p(const struct tuntap * tt)666 is_tun_p2p(const struct tuntap *tt)
667 {
668 bool tun = false;
669
670 if (tt->type == DEV_TYPE_TAP
671 || (tt->type == DEV_TYPE_TUN && tt->topology == TOP_SUBNET)
672 || tt->type == DEV_TYPE_NULL)
673 {
674 tun = false;
675 }
676 else if (tt->type == DEV_TYPE_TUN)
677 {
678 tun = true;
679 }
680 else
681 {
682 msg(M_FATAL, "Error: problem with tun vs. tap setting"); /* JYFIXME -- needs to be caught earlier, in init_tun? */
683
684 }
685 return tun;
686 }
687
688 /*
689 * Set the ifconfig_* environment variables, both for IPv4 and IPv6
690 */
691 void
do_ifconfig_setenv(const struct tuntap * tt,struct env_set * es)692 do_ifconfig_setenv(const struct tuntap *tt, struct env_set *es)
693 {
694 struct gc_arena gc = gc_new();
695 const char *ifconfig_local = print_in_addr_t(tt->local, 0, &gc);
696 const char *ifconfig_remote_netmask = print_in_addr_t(tt->remote_netmask, 0, &gc);
697
698 /*
699 * Set environmental variables with ifconfig parameters.
700 */
701 if (tt->did_ifconfig_setup)
702 {
703 bool tun = is_tun_p2p(tt);
704
705 setenv_str(es, "ifconfig_local", ifconfig_local);
706 if (tun)
707 {
708 setenv_str(es, "ifconfig_remote", ifconfig_remote_netmask);
709 }
710 else
711 {
712 setenv_str(es, "ifconfig_netmask", ifconfig_remote_netmask);
713 }
714 }
715
716 if (tt->did_ifconfig_ipv6_setup)
717 {
718 const char *ifconfig_ipv6_local = print_in6_addr(tt->local_ipv6, 0, &gc);
719 const char *ifconfig_ipv6_remote = print_in6_addr(tt->remote_ipv6, 0, &gc);
720
721 setenv_str(es, "ifconfig_ipv6_local", ifconfig_ipv6_local);
722 setenv_int(es, "ifconfig_ipv6_netbits", tt->netbits_ipv6);
723 setenv_str(es, "ifconfig_ipv6_remote", ifconfig_ipv6_remote);
724 }
725
726 gc_free(&gc);
727 }
728
729 /*
730 * Init tun/tap object.
731 *
732 * Set up tuntap structure for ifconfig,
733 * but don't execute yet.
734 */
735 struct tuntap *
init_tun(const char * dev,const char * dev_type,int topology,const char * ifconfig_local_parm,const char * ifconfig_remote_netmask_parm,const char * ifconfig_ipv6_local_parm,int ifconfig_ipv6_netbits_parm,const char * ifconfig_ipv6_remote_parm,struct addrinfo * local_public,struct addrinfo * remote_public,const bool strict_warn,struct env_set * es,openvpn_net_ctx_t * ctx)736 init_tun(const char *dev, /* --dev option */
737 const char *dev_type, /* --dev-type option */
738 int topology, /* one of the TOP_x values */
739 const char *ifconfig_local_parm, /* --ifconfig parm 1 */
740 const char *ifconfig_remote_netmask_parm, /* --ifconfig parm 2 */
741 const char *ifconfig_ipv6_local_parm, /* --ifconfig parm 1 IPv6 */
742 int ifconfig_ipv6_netbits_parm,
743 const char *ifconfig_ipv6_remote_parm, /* --ifconfig parm 2 IPv6 */
744 struct addrinfo *local_public,
745 struct addrinfo *remote_public,
746 const bool strict_warn,
747 struct env_set *es,
748 openvpn_net_ctx_t *ctx)
749 {
750 struct gc_arena gc = gc_new();
751 struct tuntap *tt;
752
753 ALLOC_OBJ(tt, struct tuntap);
754 clear_tuntap(tt);
755
756 tt->type = dev_type_enum(dev, dev_type);
757 tt->topology = topology;
758
759 if (ifconfig_local_parm && ifconfig_remote_netmask_parm)
760 {
761 bool tun = false;
762
763 /*
764 * We only handle TUN/TAP devices here, not --dev null devices.
765 */
766 tun = is_tun_p2p(tt);
767
768 /*
769 * Convert arguments to binary IPv4 addresses.
770 */
771
772 tt->local = getaddr(
773 GETADDR_RESOLVE
774 | GETADDR_HOST_ORDER
775 | GETADDR_FATAL_ON_SIGNAL
776 | GETADDR_FATAL,
777 ifconfig_local_parm,
778 0,
779 NULL,
780 NULL);
781
782 tt->remote_netmask = getaddr(
783 (tun ? GETADDR_RESOLVE : 0)
784 | GETADDR_HOST_ORDER
785 | GETADDR_FATAL_ON_SIGNAL
786 | GETADDR_FATAL,
787 ifconfig_remote_netmask_parm,
788 0,
789 NULL,
790 NULL);
791
792 /*
793 * Look for common errors in --ifconfig parms
794 */
795 if (strict_warn)
796 {
797 struct addrinfo *curele;
798 ifconfig_sanity_check(tt->type == DEV_TYPE_TUN, tt->remote_netmask, tt->topology);
799
800 /*
801 * If local_public or remote_public addresses are defined,
802 * make sure they do not clash with our virtual subnet.
803 */
804
805 for (curele = local_public; curele; curele = curele->ai_next)
806 {
807 if (curele->ai_family == AF_INET)
808 {
809 check_addr_clash("local",
810 tt->type,
811 ((struct sockaddr_in *)curele->ai_addr)->sin_addr.s_addr,
812 tt->local,
813 tt->remote_netmask);
814 }
815 }
816
817 for (curele = remote_public; curele; curele = curele->ai_next)
818 {
819 if (curele->ai_family == AF_INET)
820 {
821 check_addr_clash("remote",
822 tt->type,
823 ((struct sockaddr_in *)curele->ai_addr)->sin_addr.s_addr,
824 tt->local,
825 tt->remote_netmask);
826 }
827 }
828
829 if (tt->type == DEV_TYPE_TAP || (tt->type == DEV_TYPE_TUN && tt->topology == TOP_SUBNET))
830 {
831 check_subnet_conflict(tt->local, tt->remote_netmask, "TUN/TAP adapter");
832 }
833 else if (tt->type == DEV_TYPE_TUN)
834 {
835 check_subnet_conflict(tt->local, IPV4_NETMASK_HOST, "TUN/TAP adapter");
836 }
837 }
838
839 #ifdef _WIN32
840 /*
841 * Make sure that both ifconfig addresses are part of the
842 * same .252 subnet.
843 */
844 if (tun)
845 {
846 verify_255_255_255_252(tt->local, tt->remote_netmask);
847 tt->adapter_netmask = ~3;
848 }
849 else
850 {
851 tt->adapter_netmask = tt->remote_netmask;
852 }
853 #endif
854
855 tt->did_ifconfig_setup = true;
856 }
857
858 if (ifconfig_ipv6_local_parm && ifconfig_ipv6_remote_parm)
859 {
860
861 /*
862 * Convert arguments to binary IPv6 addresses.
863 */
864
865 if (inet_pton( AF_INET6, ifconfig_ipv6_local_parm, &tt->local_ipv6 ) != 1
866 || inet_pton( AF_INET6, ifconfig_ipv6_remote_parm, &tt->remote_ipv6 ) != 1)
867 {
868 msg( M_FATAL, "init_tun: problem converting IPv6 ifconfig addresses %s and %s to binary", ifconfig_ipv6_local_parm, ifconfig_ipv6_remote_parm );
869 }
870 tt->netbits_ipv6 = ifconfig_ipv6_netbits_parm;
871
872 tt->did_ifconfig_ipv6_setup = true;
873 }
874
875 /*
876 * Set environmental variables with ifconfig parameters.
877 */
878 if (es)
879 {
880 do_ifconfig_setenv(tt, es);
881 }
882
883 gc_free(&gc);
884 return tt;
885 }
886
887 /*
888 * Platform specific tun initializations
889 */
890 void
init_tun_post(struct tuntap * tt,const struct frame * frame,const struct tuntap_options * options)891 init_tun_post(struct tuntap *tt,
892 const struct frame *frame,
893 const struct tuntap_options *options)
894 {
895 tt->options = *options;
896 #ifdef _WIN32
897 overlapped_io_init(&tt->reads, frame, FALSE, true);
898 overlapped_io_init(&tt->writes, frame, TRUE, true);
899 tt->adapter_index = TUN_ADAPTER_INDEX_INVALID;
900
901 if (tt->windows_driver == WINDOWS_DRIVER_WINTUN)
902 {
903 tt->wintun_send_ring_handle = CreateFileMapping(INVALID_HANDLE_VALUE, NULL,
904 PAGE_READWRITE,
905 0,
906 sizeof(struct tun_ring),
907 NULL);
908 tt->wintun_receive_ring_handle = CreateFileMapping(INVALID_HANDLE_VALUE,
909 NULL,
910 PAGE_READWRITE,
911 0,
912 sizeof(struct tun_ring),
913 NULL);
914 if ((tt->wintun_send_ring_handle == NULL) || (tt->wintun_receive_ring_handle == NULL))
915 {
916 msg(M_FATAL, "Cannot allocate memory for ring buffer");
917 }
918
919 tt->rw_handle.read = CreateEvent(NULL, FALSE, FALSE, NULL);
920 tt->rw_handle.write = CreateEvent(NULL, FALSE, FALSE, NULL);
921
922 if ((tt->rw_handle.read == NULL) || (tt->rw_handle.write == NULL))
923 {
924 msg(M_FATAL, "Cannot create events for ring buffer");
925 }
926 }
927 else
928 {
929 tt->rw_handle.read = tt->reads.overlapped.hEvent;
930 tt->rw_handle.write = tt->writes.overlapped.hEvent;
931 }
932 #endif /* ifdef _WIN32 */
933 }
934
935 #if defined(_WIN32) \
936 || defined(TARGET_DARWIN) || defined(TARGET_NETBSD) || defined(TARGET_OPENBSD)
937
938 /* some of the platforms will auto-add a "network route" pointing
939 * to the interface on "ifconfig tunX 2001:db8::1/64", others need
940 * an extra call to "route add..."
941 * -> helper function to simplify code below
942 */
943 static void
add_route_connected_v6_net(struct tuntap * tt,const struct env_set * es)944 add_route_connected_v6_net(struct tuntap *tt,
945 const struct env_set *es)
946 {
947 struct route_ipv6 r6;
948
949 CLEAR(r6);
950 r6.network = tt->local_ipv6;
951 r6.netbits = tt->netbits_ipv6;
952 r6.gateway = tt->local_ipv6;
953 r6.metric = 0; /* connected route */
954 r6.flags = RT_DEFINED | RT_METRIC_DEFINED;
955 add_route_ipv6(&r6, tt, 0, es, NULL);
956 }
957
958 void
delete_route_connected_v6_net(const struct tuntap * tt)959 delete_route_connected_v6_net(const struct tuntap *tt)
960 {
961 struct route_ipv6 r6;
962
963 CLEAR(r6);
964 r6.network = tt->local_ipv6;
965 r6.netbits = tt->netbits_ipv6;
966 r6.gateway = tt->local_ipv6;
967 r6.metric = 0; /* connected route */
968 r6.flags = RT_DEFINED | RT_ADDED | RT_METRIC_DEFINED;
969 route_ipv6_clear_host_bits(&r6);
970 delete_route_ipv6(&r6, tt, 0, NULL, NULL);
971 }
972 #endif /* if defined(_WIN32) || defined(TARGET_DARWIN) || defined(TARGET_NETBSD) || defined(TARGET_OPENBSD) */
973
974 #if defined(TARGET_FREEBSD) || defined(TARGET_DRAGONFLY) \
975 || defined(TARGET_NETBSD) || defined(TARGET_OPENBSD)
976 /* we can't use true subnet mode on tun on all platforms, as that
977 * conflicts with IPv6 (wants to use ND then, which we don't do),
978 * but the OSes want "a remote address that is different from ours"
979 * - so we construct one, normally the first in the subnet, but if
980 * this is the same as ours, use the second one.
981 * The actual address does not matter at all, as the tun interface
982 * is still point to point and no layer 2 resolution is done...
983 */
984
985 in_addr_t
create_arbitrary_remote(struct tuntap * tt)986 create_arbitrary_remote( struct tuntap *tt )
987 {
988 in_addr_t remote;
989
990 remote = (tt->local & tt->remote_netmask) +1;
991
992 if (remote == tt->local)
993 {
994 remote++;
995 }
996
997 return remote;
998 }
999 #endif
1000
1001 /**
1002 * do_ifconfig_ipv6 - perform platform specific ifconfig6 commands
1003 *
1004 * @param tt the tuntap interface context
1005 * @param ifname the human readable interface name
1006 * @param mtu the MTU value to set the interface to
1007 * @param es the environment to be used when executing the commands
1008 * @param ctx the networking API opaque context
1009 */
1010 static void
do_ifconfig_ipv6(struct tuntap * tt,const char * ifname,int tun_mtu,const struct env_set * es,openvpn_net_ctx_t * ctx)1011 do_ifconfig_ipv6(struct tuntap *tt, const char *ifname, int tun_mtu,
1012 const struct env_set *es, openvpn_net_ctx_t *ctx)
1013 {
1014 #if !defined(TARGET_LINUX)
1015 struct argv argv = argv_new();
1016 struct gc_arena gc = gc_new();
1017 const char *ifconfig_ipv6_local = print_in6_addr(tt->local_ipv6, 0, &gc);
1018 #endif
1019
1020 #if defined(TARGET_LINUX)
1021 if (net_iface_mtu_set(ctx, ifname, tun_mtu) < 0)
1022 {
1023 msg(M_FATAL, "Linux can't set mtu (%d) on %s", tun_mtu, ifname);
1024 }
1025
1026 if (net_iface_up(ctx, ifname, true) < 0)
1027 {
1028 msg(M_FATAL, "Linux can't bring %s up", ifname);
1029 }
1030
1031 if (net_addr_v6_add(ctx, ifname, &tt->local_ipv6,
1032 tt->netbits_ipv6) < 0)
1033 {
1034 msg(M_FATAL, "Linux can't add IPv6 to interface %s", ifname);
1035 }
1036 #elif defined(TARGET_ANDROID)
1037 char out6[64];
1038
1039 openvpn_snprintf(out6, sizeof(out6), "%s/%d %d",
1040 ifconfig_ipv6_local, tt->netbits_ipv6, tun_mtu);
1041 management_android_control(management, "IFCONFIG6", out6);
1042 #elif defined(TARGET_SOLARIS)
1043 argv_printf(&argv, "%s %s inet6 unplumb", IFCONFIG_PATH, ifname);
1044 argv_msg(M_INFO, &argv);
1045 openvpn_execve_check(&argv, es, 0, NULL);
1046
1047 if (tt->type == DEV_TYPE_TUN)
1048 {
1049 const char *ifconfig_ipv6_remote = print_in6_addr(tt->remote_ipv6, 0, &gc);
1050
1051 argv_printf(&argv, "%s %s inet6 plumb %s/%d %s mtu %d up",
1052 IFCONFIG_PATH, ifname, ifconfig_ipv6_local,
1053 tt->netbits_ipv6, ifconfig_ipv6_remote, tun_mtu);
1054 }
1055 else /* tap mode */
1056 {
1057 /* base IPv6 tap interface needs to be brought up first */
1058 argv_printf(&argv, "%s %s inet6 plumb up", IFCONFIG_PATH, ifname);
1059 argv_msg(M_INFO, &argv);
1060
1061 if (!openvpn_execve_check(&argv, es, 0,
1062 "Solaris ifconfig IPv6 (prepare) failed"))
1063 {
1064 solaris_error_close(tt, es, ifname, true);
1065 }
1066
1067 /* we might need to do "ifconfig %s inet6 auto-dhcp drop"
1068 * after the system has noticed the interface and fired up
1069 * the DHCPv6 client - but this takes quite a while, and the
1070 * server will ignore the DHCPv6 packets anyway. So we don't.
1071 */
1072
1073 /* static IPv6 addresses need to go to a subinterface (tap0:1)
1074 * and we cannot set an mtu here (must go to the "parent")
1075 */
1076 argv_printf(&argv, "%s %s inet6 addif %s/%d up", IFCONFIG_PATH,
1077 ifname, ifconfig_ipv6_local, tt->netbits_ipv6 );
1078 }
1079 argv_msg(M_INFO, &argv);
1080
1081 if (!openvpn_execve_check(&argv, es, 0, "Solaris ifconfig IPv6 failed"))
1082 {
1083 solaris_error_close(tt, es, ifname, true);
1084 }
1085
1086 if (tt->type != DEV_TYPE_TUN)
1087 {
1088 argv_printf(&argv, "%s %s inet6 mtu %d", IFCONFIG_PATH,
1089 ifname, tun_mtu);
1090 argv_msg(M_INFO, &argv);
1091 openvpn_execve_check(&argv, es, 0, "Solaris ifconfig IPv6 mtu failed");
1092 }
1093 #elif defined(TARGET_OPENBSD) || defined(TARGET_NETBSD) \
1094 || defined(TARGET_DARWIN) || defined(TARGET_FREEBSD) \
1095 || defined(TARGET_DRAGONFLY)
1096 argv_printf(&argv, "%s %s inet6 %s/%d mtu %d up", IFCONFIG_PATH, ifname,
1097 ifconfig_ipv6_local, tt->netbits_ipv6, tun_mtu);
1098 argv_msg(M_INFO, &argv);
1099
1100 openvpn_execve_check(&argv, es, S_FATAL,
1101 "generic BSD ifconfig inet6 failed");
1102
1103 #if defined(TARGET_FREEBSD) && __FreeBSD_version >= 1200000
1104 /* On FreeBSD 12 and up, there is ipv6_activate_all_interfaces="YES"
1105 * in rc.conf, which is not set by default. If it is *not* set,
1106 * "all new interfaces that are not already up" are configured by
1107 * devd + /etc/pccard_ether as "inet6 ifdisabled".
1108 *
1109 * The "is this interface already up?" test is a non-zero time window
1110 * which we manage to hit with our ifconfig often enough to cause
1111 * frequent fails in the openvpn test environment.
1112 *
1113 * Thus: assume that the system might interfere, wait for things to
1114 * settle (it's a very short time window), and remove -ifdisable again.
1115 *
1116 * See: https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=248172
1117 */
1118 sleep(1);
1119 argv_printf(&argv, "%s %s inet6 -ifdisabled", IFCONFIG_PATH, ifname);
1120 argv_msg(M_INFO, &argv);
1121
1122 openvpn_execve_check(&argv, es, S_FATAL,
1123 "FreeBSD BSD 'ifconfig inet6 -ifdisabled' failed");
1124 #endif
1125
1126 #if defined(TARGET_OPENBSD) || defined(TARGET_NETBSD) \
1127 || defined(TARGET_DARWIN)
1128 /* and, hooray, we explicitly need to add a route... */
1129 add_route_connected_v6_net(tt, es);
1130 #endif
1131 #elif defined(TARGET_AIX)
1132 argv_printf(&argv, "%s %s inet6 %s/%d mtu %d up", IFCONFIG_PATH, ifname,
1133 ifconfig_ipv6_local, tt->netbits_ipv6, tun_mtu);
1134 argv_msg(M_INFO, &argv);
1135
1136 /* AIX ifconfig will complain if it can't find ODM path in env */
1137 es = env_set_create(NULL);
1138 env_set_add(es, "ODMDIR=/etc/objrepos");
1139
1140 openvpn_execve_check(&argv, es, S_FATAL,
1141 "generic BSD ifconfig inet6 failed");
1142
1143 env_set_destroy(es);
1144 #elif defined (_WIN32)
1145 if (tt->options.ip_win32_type == IPW32_SET_MANUAL)
1146 {
1147 msg(M_INFO, "******** NOTE: Please manually set the v6 IP of '%s' to %s (if it is not already set)",
1148 ifname, ifconfig_ipv6_local);
1149 }
1150 else if (tt->options.msg_channel)
1151 {
1152 do_address_service(true, AF_INET6, tt);
1153 if (tt->type == DEV_TYPE_TUN)
1154 {
1155 add_route_connected_v6_net(tt, es);
1156 }
1157 do_dns_service(true, AF_INET6, tt);
1158 do_set_mtu_service(tt, AF_INET6, tun_mtu);
1159 /* If IPv4 is not enabled, set DNS domain here */
1160 if (!tt->did_ifconfig_setup)
1161 {
1162 do_dns_domain_service(true, tt);
1163 }
1164 }
1165 else
1166 {
1167 /* example: netsh interface ipv6 set address 42
1168 * 2001:608:8003::d/bits store=active
1169 */
1170
1171 /* in TUN mode, we only simulate a subnet, so the interface
1172 * is configured with /128 + a route to fe80::8. In TAP mode,
1173 * the correct netbits must be set, and no on-link route
1174 */
1175 int netbits = (tt->type == DEV_TYPE_TUN) ? 128 : tt->netbits_ipv6;
1176
1177 argv_printf(&argv, "%s%s interface ipv6 set address %lu %s/%d store=active",
1178 get_win_sys_path(), NETSH_PATH_SUFFIX, tt->adapter_index,
1179 ifconfig_ipv6_local, netbits);
1180 netsh_command(&argv, 4, M_FATAL);
1181 if (tt->type == DEV_TYPE_TUN)
1182 {
1183 add_route_connected_v6_net(tt, es);
1184 }
1185 /* set ipv6 dns servers if any are specified */
1186 netsh_set_dns6_servers(tt->options.dns6, tt->options.dns6_len, tt->adapter_index);
1187 windows_set_mtu(tt->adapter_index, AF_INET6, tun_mtu);
1188 }
1189 #else /* platforms we have no IPv6 code for */
1190 msg(M_FATAL, "Sorry, but I don't know how to do IPv6 'ifconfig' commands on this operating system. You should ifconfig your TUN/TAP device manually or use an --up script.");
1191 #endif /* outer "if defined(TARGET_xxx)" conditional */
1192
1193 #if !defined(TARGET_LINUX)
1194 gc_free(&gc);
1195 argv_free(&argv);
1196 #endif
1197 }
1198
1199 /**
1200 * do_ifconfig_ipv4 - perform platform specific ifconfig commands
1201 *
1202 * @param tt the tuntap interface context
1203 * @param ifname the human readable interface name
1204 * @param mtu the MTU value to set the interface to
1205 * @param es the environment to be used when executing the commands
1206 * @param ctx the networking API opaque context
1207 */
1208 static void
do_ifconfig_ipv4(struct tuntap * tt,const char * ifname,int tun_mtu,const struct env_set * es,openvpn_net_ctx_t * ctx)1209 do_ifconfig_ipv4(struct tuntap *tt, const char *ifname, int tun_mtu,
1210 const struct env_set *es, openvpn_net_ctx_t *ctx)
1211 {
1212 /*
1213 * We only handle TUN/TAP devices here, not --dev null devices.
1214 */
1215 bool tun = is_tun_p2p(tt);
1216
1217 #if !defined(TARGET_LINUX)
1218 const char *ifconfig_local = NULL;
1219 const char *ifconfig_remote_netmask = NULL;
1220 struct argv argv = argv_new();
1221 struct gc_arena gc = gc_new();
1222
1223 /*
1224 * Set ifconfig parameters
1225 */
1226 ifconfig_local = print_in_addr_t(tt->local, 0, &gc);
1227 ifconfig_remote_netmask = print_in_addr_t(tt->remote_netmask, 0, &gc);
1228 #endif
1229
1230 #if defined(TARGET_LINUX)
1231 if (net_iface_mtu_set(ctx, ifname, tun_mtu) < 0)
1232 {
1233 msg(M_FATAL, "Linux can't set mtu (%d) on %s", tun_mtu, ifname);
1234 }
1235
1236 if (net_iface_up(ctx, ifname, true) < 0)
1237 {
1238 msg(M_FATAL, "Linux can't bring %s up", ifname);
1239 }
1240
1241 if (tun)
1242 {
1243 if (net_addr_ptp_v4_add(ctx, ifname, &tt->local,
1244 &tt->remote_netmask) < 0)
1245 {
1246 msg(M_FATAL, "Linux can't add IP to interface %s", ifname);
1247 }
1248 }
1249 else
1250 {
1251 if (net_addr_v4_add(ctx, ifname, &tt->local,
1252 netmask_to_netbits2(tt->remote_netmask)) < 0)
1253 {
1254 msg(M_FATAL, "Linux can't add IP to interface %s", ifname);
1255 }
1256 }
1257 #elif defined(TARGET_ANDROID)
1258 char out[64];
1259
1260 char *top;
1261 switch (tt->topology)
1262 {
1263 case TOP_NET30:
1264 top = "net30";
1265 break;
1266
1267 case TOP_P2P:
1268 top = "p2p";
1269 break;
1270
1271 case TOP_SUBNET:
1272 top = "subnet";
1273 break;
1274
1275 default:
1276 top = "undef";
1277 }
1278
1279 openvpn_snprintf(out, sizeof(out), "%s %s %d %s", ifconfig_local,
1280 ifconfig_remote_netmask, tun_mtu, top);
1281 management_android_control(management, "IFCONFIG", out);
1282
1283 #elif defined(TARGET_SOLARIS)
1284 /* Solaris 2.6 (and 7?) cannot set all parameters in one go...
1285 * example:
1286 * ifconfig tun2 10.2.0.2 10.2.0.1 mtu 1450 up
1287 * ifconfig tun2 netmask 255.255.255.255
1288 */
1289 if (tun)
1290 {
1291 argv_printf(&argv, "%s %s %s %s mtu %d up", IFCONFIG_PATH, ifname,
1292 ifconfig_local, ifconfig_remote_netmask, tun_mtu);
1293
1294 argv_msg(M_INFO, &argv);
1295 if (!openvpn_execve_check(&argv, es, 0, "Solaris ifconfig phase-1 failed"))
1296 {
1297 solaris_error_close(tt, es, ifname, false);
1298 }
1299
1300 argv_printf(&argv, "%s %s netmask 255.255.255.255", IFCONFIG_PATH,
1301 ifname);
1302 }
1303 else if (tt->type == DEV_TYPE_TUN && tt->topology == TOP_SUBNET)
1304 {
1305 argv_printf(&argv, "%s %s %s %s netmask %s mtu %d up", IFCONFIG_PATH,
1306 ifname, ifconfig_local, ifconfig_local,
1307 ifconfig_remote_netmask, tun_mtu);
1308 }
1309 else
1310 {
1311 argv_printf(&argv, "%s %s %s netmask %s up",
1312 IFCONFIG_PATH, ifname, ifconfig_local,
1313 ifconfig_remote_netmask);
1314 }
1315
1316 argv_msg(M_INFO, &argv);
1317 if (!openvpn_execve_check(&argv, es, 0, "Solaris ifconfig phase-2 failed"))
1318 {
1319 solaris_error_close(tt, es, ifname, false);
1320 }
1321
1322 if (!tun && tt->type == DEV_TYPE_TUN && tt->topology == TOP_SUBNET)
1323 {
1324 /* Add a network route for the local tun interface */
1325 struct route_ipv4 r;
1326 CLEAR(r);
1327 r.flags = RT_DEFINED | RT_METRIC_DEFINED;
1328 r.network = tt->local & tt->remote_netmask;
1329 r.netmask = tt->remote_netmask;
1330 r.gateway = tt->local;
1331 r.metric = 0;
1332 add_route(&r, tt, 0, NULL, es, NULL);
1333 }
1334
1335 #elif defined(TARGET_OPENBSD)
1336
1337 in_addr_t remote_end; /* for "virtual" subnet topology */
1338
1339 /*
1340 * On OpenBSD, tun interfaces are persistent if created with
1341 * "ifconfig tunX create", and auto-destroyed if created by
1342 * opening "/dev/tunX" (so we just use the /dev/tunX)
1343 */
1344
1345 /* example: ifconfig tun2 10.2.0.2 10.2.0.1 mtu 1450 netmask 255.255.255.255 up */
1346 if (tun)
1347 {
1348 argv_printf(&argv,
1349 "%s %s %s %s mtu %d netmask 255.255.255.255 up -link0",
1350 IFCONFIG_PATH, ifname, ifconfig_local,
1351 ifconfig_remote_netmask, tun_mtu);
1352 }
1353 else if (tt->type == DEV_TYPE_TUN && tt->topology == TOP_SUBNET)
1354 {
1355 remote_end = create_arbitrary_remote( tt );
1356 argv_printf(&argv, "%s %s %s %s mtu %d netmask %s up -link0",
1357 IFCONFIG_PATH, ifname, ifconfig_local,
1358 print_in_addr_t(remote_end, 0, &gc), tun_mtu,
1359 ifconfig_remote_netmask);
1360 }
1361 else
1362 {
1363 argv_printf(&argv, "%s %s %s netmask %s mtu %d link0",
1364 IFCONFIG_PATH, ifname, ifconfig_local,
1365 ifconfig_remote_netmask, tun_mtu);
1366 }
1367 argv_msg(M_INFO, &argv);
1368 openvpn_execve_check(&argv, es, S_FATAL, "OpenBSD ifconfig failed");
1369
1370 /* Add a network route for the local tun interface */
1371 if (!tun && tt->type == DEV_TYPE_TUN && tt->topology == TOP_SUBNET)
1372 {
1373 struct route_ipv4 r;
1374 CLEAR(r);
1375 r.flags = RT_DEFINED;
1376 r.network = tt->local & tt->remote_netmask;
1377 r.netmask = tt->remote_netmask;
1378 r.gateway = remote_end;
1379 add_route(&r, tt, 0, NULL, es, NULL);
1380 }
1381
1382 #elif defined(TARGET_NETBSD)
1383 in_addr_t remote_end; /* for "virtual" subnet topology */
1384
1385 if (tun)
1386 {
1387 argv_printf(&argv, "%s %s %s %s mtu %d netmask 255.255.255.255 up",
1388 IFCONFIG_PATH, ifname, ifconfig_local,
1389 ifconfig_remote_netmask, tun_mtu);
1390 }
1391 else if (tt->type == DEV_TYPE_TUN && tt->topology == TOP_SUBNET)
1392 {
1393 remote_end = create_arbitrary_remote(tt);
1394 argv_printf(&argv, "%s %s %s %s mtu %d netmask %s up", IFCONFIG_PATH,
1395 ifname, ifconfig_local, print_in_addr_t(remote_end, 0, &gc),
1396 tun_mtu, ifconfig_remote_netmask);
1397 }
1398 else
1399 {
1400 /*
1401 * NetBSD has distinct tun and tap devices
1402 * so we don't need the "link0" extra parameter to specify we want to do
1403 * tunneling at the ethernet level
1404 */
1405 argv_printf(&argv, "%s %s %s netmask %s mtu %d",
1406 IFCONFIG_PATH, ifname, ifconfig_local,
1407 ifconfig_remote_netmask, tun_mtu);
1408 }
1409 argv_msg(M_INFO, &argv);
1410 openvpn_execve_check(&argv, es, S_FATAL, "NetBSD ifconfig failed");
1411
1412 /* Add a network route for the local tun interface */
1413 if (!tun && tt->type == DEV_TYPE_TUN && tt->topology == TOP_SUBNET)
1414 {
1415 struct route_ipv4 r;
1416 CLEAR(r);
1417 r.flags = RT_DEFINED;
1418 r.network = tt->local & tt->remote_netmask;
1419 r.netmask = tt->remote_netmask;
1420 r.gateway = remote_end;
1421 add_route(&r, tt, 0, NULL, es, NULL);
1422 }
1423
1424 #elif defined(TARGET_DARWIN)
1425 /*
1426 * Darwin (i.e. Mac OS X) seems to exhibit similar behaviour to OpenBSD...
1427 */
1428
1429 argv_printf(&argv, "%s %s delete", IFCONFIG_PATH, ifname);
1430 argv_msg(M_INFO, &argv);
1431 openvpn_execve_check(&argv, es, 0, NULL);
1432 msg(M_INFO,
1433 "NOTE: Tried to delete pre-existing tun/tap instance -- No Problem if failure");
1434
1435
1436 /* example: ifconfig tun2 10.2.0.2 10.2.0.1 mtu 1450 netmask 255.255.255.255 up */
1437 if (tun)
1438 {
1439 argv_printf(&argv, "%s %s %s %s mtu %d netmask 255.255.255.255 up",
1440 IFCONFIG_PATH, ifname, ifconfig_local,
1441 ifconfig_remote_netmask, tun_mtu);
1442 }
1443 else
1444 {
1445 if (tt->type == DEV_TYPE_TUN && tt->topology == TOP_SUBNET)
1446 {
1447 argv_printf(&argv, "%s %s %s %s netmask %s mtu %d up",
1448 IFCONFIG_PATH, ifname, ifconfig_local, ifconfig_local,
1449 ifconfig_remote_netmask, tun_mtu);
1450 }
1451 else
1452 {
1453 argv_printf(&argv, "%s %s %s netmask %s mtu %d up", IFCONFIG_PATH,
1454 ifname, ifconfig_local, ifconfig_remote_netmask,
1455 tun_mtu);
1456 }
1457 }
1458
1459 argv_msg(M_INFO, &argv);
1460 openvpn_execve_check(&argv, es, S_FATAL, "Mac OS X ifconfig failed");
1461
1462 /* Add a network route for the local tun interface */
1463 if (!tun && tt->type == DEV_TYPE_TUN && tt->topology == TOP_SUBNET)
1464 {
1465 struct route_ipv4 r;
1466 CLEAR(r);
1467 r.flags = RT_DEFINED;
1468 r.network = tt->local & tt->remote_netmask;
1469 r.netmask = tt->remote_netmask;
1470 r.gateway = tt->local;
1471 add_route(&r, tt, 0, NULL, es, NULL);
1472 }
1473
1474 #elif defined(TARGET_FREEBSD) || defined(TARGET_DRAGONFLY)
1475
1476 in_addr_t remote_end; /* for "virtual" subnet topology */
1477
1478 /* example: ifconfig tun2 10.2.0.2 10.2.0.1 mtu 1450 netmask 255.255.255.255 up */
1479 if (tun)
1480 {
1481 argv_printf(&argv, "%s %s %s %s mtu %d netmask 255.255.255.255 up",
1482 IFCONFIG_PATH, ifname, ifconfig_local,
1483 ifconfig_remote_netmask, tun_mtu);
1484 }
1485 else if (tt->type == DEV_TYPE_TUN && tt->topology == TOP_SUBNET)
1486 {
1487 remote_end = create_arbitrary_remote( tt );
1488 argv_printf(&argv, "%s %s %s %s mtu %d netmask %s up", IFCONFIG_PATH,
1489 ifname, ifconfig_local, print_in_addr_t(remote_end, 0, &gc),
1490 tun_mtu, ifconfig_remote_netmask);
1491 }
1492 else
1493 {
1494 argv_printf(&argv, "%s %s %s netmask %s mtu %d up", IFCONFIG_PATH,
1495 ifname, ifconfig_local, ifconfig_remote_netmask, tun_mtu);
1496 }
1497
1498 argv_msg(M_INFO, &argv);
1499 openvpn_execve_check(&argv, es, S_FATAL, "FreeBSD ifconfig failed");
1500
1501 /* Add a network route for the local tun interface */
1502 if (!tun && tt->type == DEV_TYPE_TUN && tt->topology == TOP_SUBNET)
1503 {
1504 struct route_ipv4 r;
1505 CLEAR(r);
1506 r.flags = RT_DEFINED;
1507 r.network = tt->local & tt->remote_netmask;
1508 r.netmask = tt->remote_netmask;
1509 r.gateway = remote_end;
1510 add_route(&r, tt, 0, NULL, es, NULL);
1511 }
1512
1513 #elif defined(TARGET_AIX)
1514 {
1515 /* AIX ifconfig will complain if it can't find ODM path in env */
1516 struct env_set *aix_es = env_set_create(NULL);
1517 env_set_add( aix_es, "ODMDIR=/etc/objrepos" );
1518
1519 if (tun)
1520 {
1521 msg(M_FATAL, "no tun support on AIX (canthappen)");
1522 }
1523
1524 /* example: ifconfig tap0 172.30.1.1 netmask 255.255.254.0 up */
1525 argv_printf(&argv, "%s %s %s netmask %s mtu %d up", IFCONFIG_PATH,
1526 ifname, ifconfig_local, ifconfig_remote_netmask, tun_mtu);
1527
1528 argv_msg(M_INFO, &argv);
1529 openvpn_execve_check(&argv, aix_es, S_FATAL, "AIX ifconfig failed");
1530
1531 env_set_destroy(aix_es);
1532 }
1533 #elif defined (_WIN32)
1534 if (tt->options.ip_win32_type == IPW32_SET_MANUAL)
1535 {
1536 msg(M_INFO,
1537 "******** NOTE: Please manually set the IP/netmask of '%s' to %s/%s (if it is not already set)",
1538 ifname, ifconfig_local,
1539 print_in_addr_t(tt->adapter_netmask, 0, &gc));
1540 }
1541 else if (tt->options.ip_win32_type == IPW32_SET_DHCP_MASQ || tt->options.ip_win32_type == IPW32_SET_ADAPTIVE)
1542 {
1543 /* Let the DHCP configure the interface. */
1544 }
1545 else if (tt->options.msg_channel)
1546 {
1547 do_address_service(true, AF_INET, tt);
1548 do_dns_service(true, AF_INET, tt);
1549 do_dns_domain_service(true, tt);
1550 }
1551 else if (tt->options.ip_win32_type == IPW32_SET_NETSH)
1552 {
1553 netsh_ifconfig(&tt->options, tt->adapter_index, tt->local,
1554 tt->adapter_netmask, NI_IP_NETMASK|NI_OPTIONS);
1555 }
1556 if (tt->options.msg_channel)
1557 {
1558 do_set_mtu_service(tt, AF_INET, tun_mtu);
1559 }
1560 else
1561 {
1562 windows_set_mtu(tt->adapter_index, AF_INET, tun_mtu);
1563 }
1564 #else /* if defined(TARGET_LINUX) */
1565 msg(M_FATAL, "Sorry, but I don't know how to do 'ifconfig' commands on this operating system. You should ifconfig your TUN/TAP device manually or use an --up script.");
1566 #endif /* if defined(TARGET_LINUX) */
1567
1568 #if !defined(TARGET_LINUX)
1569 gc_free(&gc);
1570 argv_free(&argv);
1571 #endif
1572 }
1573
1574 /* execute the ifconfig command through the shell */
1575 void
do_ifconfig(struct tuntap * tt,const char * ifname,int tun_mtu,const struct env_set * es,openvpn_net_ctx_t * ctx)1576 do_ifconfig(struct tuntap *tt, const char *ifname, int tun_mtu,
1577 const struct env_set *es, openvpn_net_ctx_t *ctx)
1578 {
1579 msg(D_LOW, "do_ifconfig, ipv4=%d, ipv6=%d", tt->did_ifconfig_setup,
1580 tt->did_ifconfig_ipv6_setup);
1581
1582 #ifdef ENABLE_MANAGEMENT
1583 if (management)
1584 {
1585 management_set_state(management,
1586 OPENVPN_STATE_ASSIGN_IP,
1587 NULL,
1588 &tt->local,
1589 &tt->local_ipv6,
1590 NULL,
1591 NULL);
1592 }
1593 #endif
1594
1595 if (tt->did_ifconfig_setup)
1596 {
1597 do_ifconfig_ipv4(tt, ifname, tun_mtu, es, ctx);
1598 }
1599
1600 if (tt->did_ifconfig_ipv6_setup)
1601 {
1602 do_ifconfig_ipv6(tt, ifname, tun_mtu, es, ctx);
1603 }
1604
1605 /* release resources potentially allocated during interface setup */
1606 net_ctx_free(ctx);
1607 }
1608
1609 static void
clear_tuntap(struct tuntap * tuntap)1610 clear_tuntap(struct tuntap *tuntap)
1611 {
1612 CLEAR(*tuntap);
1613 #ifdef _WIN32
1614 tuntap->hand = NULL;
1615 #else
1616 tuntap->fd = -1;
1617 #endif
1618 #ifdef TARGET_SOLARIS
1619 tuntap->ip_fd = -1;
1620 #endif
1621 }
1622
1623 static void
open_null(struct tuntap * tt)1624 open_null(struct tuntap *tt)
1625 {
1626 tt->actual_name = string_alloc("null", NULL);
1627 }
1628
1629
1630 #if defined (TARGET_OPENBSD) || (defined(TARGET_DARWIN) && HAVE_NET_IF_UTUN_H)
1631
1632 /*
1633 * OpenBSD and Mac OS X when using utun
1634 * have a slightly incompatible TUN device from
1635 * the rest of the world, in that it prepends a
1636 * uint32 to the beginning of the IP header
1637 * to designate the protocol (why not just
1638 * look at the version field in the IP header to
1639 * determine v4 or v6?).
1640 *
1641 * We strip off this field on reads and
1642 * put it back on writes.
1643 *
1644 * I have not tested TAP devices on OpenBSD,
1645 * but I have conditionalized the special
1646 * TUN handling code described above to
1647 * go away for TAP devices.
1648 */
1649
1650 #include <netinet/ip.h>
1651 #include <sys/uio.h>
1652
1653 static inline int
header_modify_read_write_return(int len)1654 header_modify_read_write_return(int len)
1655 {
1656 if (len > 0)
1657 {
1658 return len > sizeof(u_int32_t) ? len - sizeof(u_int32_t) : 0;
1659 }
1660 else
1661 {
1662 return len;
1663 }
1664 }
1665
1666 int
write_tun_header(struct tuntap * tt,uint8_t * buf,int len)1667 write_tun_header(struct tuntap *tt, uint8_t *buf, int len)
1668 {
1669 if (tt->type == DEV_TYPE_TUN)
1670 {
1671 u_int32_t type;
1672 struct iovec iv[2];
1673 struct openvpn_iphdr *iph;
1674
1675 iph = (struct openvpn_iphdr *) buf;
1676
1677 if (OPENVPN_IPH_GET_VER(iph->version_len) == 6)
1678 {
1679 type = htonl(AF_INET6);
1680 }
1681 else
1682 {
1683 type = htonl(AF_INET);
1684 }
1685
1686 iv[0].iov_base = &type;
1687 iv[0].iov_len = sizeof(type);
1688 iv[1].iov_base = buf;
1689 iv[1].iov_len = len;
1690
1691 return header_modify_read_write_return(writev(tt->fd, iv, 2));
1692 }
1693 else
1694 {
1695 return write(tt->fd, buf, len);
1696 }
1697 }
1698
1699 int
read_tun_header(struct tuntap * tt,uint8_t * buf,int len)1700 read_tun_header(struct tuntap *tt, uint8_t *buf, int len)
1701 {
1702 if (tt->type == DEV_TYPE_TUN)
1703 {
1704 u_int32_t type;
1705 struct iovec iv[2];
1706
1707 iv[0].iov_base = &type;
1708 iv[0].iov_len = sizeof(type);
1709 iv[1].iov_base = buf;
1710 iv[1].iov_len = len;
1711
1712 return header_modify_read_write_return(readv(tt->fd, iv, 2));
1713 }
1714 else
1715 {
1716 return read(tt->fd, buf, len);
1717 }
1718 }
1719 #endif /* if defined (TARGET_OPENBSD) || (defined(TARGET_DARWIN) && HAVE_NET_IF_UTUN_H) */
1720
1721
1722 #if !(defined(_WIN32) || defined(TARGET_LINUX))
1723 static void
open_tun_generic(const char * dev,const char * dev_type,const char * dev_node,bool dynamic,struct tuntap * tt)1724 open_tun_generic(const char *dev, const char *dev_type, const char *dev_node,
1725 bool dynamic, struct tuntap *tt)
1726 {
1727 char tunname[256];
1728 char dynamic_name[256];
1729 bool dynamic_opened = false;
1730
1731 if (tt->type == DEV_TYPE_NULL)
1732 {
1733 open_null(tt);
1734 }
1735 else
1736 {
1737 /*
1738 * --dev-node specified, so open an explicit device node
1739 */
1740 if (dev_node)
1741 {
1742 openvpn_snprintf(tunname, sizeof(tunname), "%s", dev_node);
1743 }
1744 else
1745 {
1746 /*
1747 * dynamic open is indicated by --dev specified without
1748 * explicit unit number. Try opening /dev/[dev]n
1749 * where n = [0, 255].
1750 */
1751 #ifdef TARGET_NETBSD
1752 /* on NetBSD, tap (but not tun) devices are opened by
1753 * opening /dev/tap and then querying the system about the
1754 * actual device name (tap0, tap1, ...) assigned
1755 */
1756 if (dynamic && strcmp( dev, "tap" ) == 0)
1757 {
1758 struct ifreq ifr;
1759 if ((tt->fd = open( "/dev/tap", O_RDWR)) < 0)
1760 {
1761 msg(M_FATAL, "Cannot allocate NetBSD TAP dev dynamically");
1762 }
1763 if (ioctl( tt->fd, TAPGIFNAME, (void *)&ifr ) < 0)
1764 {
1765 msg(M_FATAL, "Cannot query NetBSD TAP device name");
1766 }
1767 CLEAR(dynamic_name);
1768 strncpy( dynamic_name, ifr.ifr_name, sizeof(dynamic_name)-1 );
1769 dynamic_opened = true;
1770 openvpn_snprintf(tunname, sizeof(tunname), "/dev/%s", dynamic_name );
1771 }
1772 else
1773 #endif
1774
1775 if (dynamic && !has_digit((unsigned char *)dev))
1776 {
1777 int i;
1778 for (i = 0; i < 256; ++i)
1779 {
1780 openvpn_snprintf(tunname, sizeof(tunname),
1781 "/dev/%s%d", dev, i);
1782 openvpn_snprintf(dynamic_name, sizeof(dynamic_name),
1783 "%s%d", dev, i);
1784 if ((tt->fd = open(tunname, O_RDWR)) > 0)
1785 {
1786 dynamic_opened = true;
1787 break;
1788 }
1789 msg(D_READ_WRITE | M_ERRNO, "Tried opening %s (failed)", tunname);
1790 }
1791 if (!dynamic_opened)
1792 {
1793 msg(M_FATAL, "Cannot allocate TUN/TAP dev dynamically");
1794 }
1795 }
1796 /*
1797 * explicit unit number specified
1798 */
1799 else
1800 {
1801 openvpn_snprintf(tunname, sizeof(tunname), "/dev/%s", dev);
1802 }
1803 }
1804
1805 if (!dynamic_opened)
1806 {
1807 /* has named device existed before? if so, don't destroy at end */
1808 if (if_nametoindex( dev ) > 0)
1809 {
1810 msg(M_INFO, "TUN/TAP device %s exists previously, keep at program end", dev );
1811 tt->persistent_if = true;
1812 }
1813
1814 if ((tt->fd = open(tunname, O_RDWR)) < 0)
1815 {
1816 msg(M_ERR, "Cannot open TUN/TAP dev %s", tunname);
1817 }
1818 }
1819
1820 set_nonblock(tt->fd);
1821 set_cloexec(tt->fd); /* don't pass fd to scripts */
1822 msg(M_INFO, "TUN/TAP device %s opened", tunname);
1823
1824 /* tt->actual_name is passed to up and down scripts and used as the ifconfig dev name */
1825 tt->actual_name = string_alloc(dynamic_opened ? dynamic_name : dev, NULL);
1826 }
1827 }
1828 #endif /* !_WIN32 && !TARGET_LINUX */
1829
1830 #if !defined(_WIN32)
1831 static void
close_tun_generic(struct tuntap * tt)1832 close_tun_generic(struct tuntap *tt)
1833 {
1834 if (tt->fd >= 0)
1835 {
1836 close(tt->fd);
1837 }
1838 if (tt->actual_name)
1839 {
1840 free(tt->actual_name);
1841 }
1842 clear_tuntap(tt);
1843 }
1844 #endif /* !_WIN32 */
1845
1846 #if defined (TARGET_ANDROID)
1847 void
open_tun(const char * dev,const char * dev_type,const char * dev_node,struct tuntap * tt)1848 open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
1849 {
1850 #define ANDROID_TUNNAME "vpnservice-tun"
1851 struct user_pass up;
1852 struct gc_arena gc = gc_new();
1853 bool opentun;
1854
1855 int oldtunfd = tt->fd;
1856
1857 /* Prefer IPv6 DNS servers,
1858 * Android will use the DNS server in the order we specify*/
1859 for (int i = 0; i < tt->options.dns6_len; i++)
1860 {
1861 management_android_control(management, "DNS6SERVER",
1862 print_in6_addr(tt->options.dns6[i], 0, &gc));
1863 }
1864
1865 for (int i = 0; i < tt->options.dns_len; i++)
1866 {
1867 management_android_control(management, "DNSSERVER",
1868 print_in_addr_t(tt->options.dns[i], 0, &gc));
1869 }
1870
1871 if (tt->options.domain)
1872 {
1873 management_android_control(management, "DNSDOMAIN", tt->options.domain);
1874 }
1875
1876 int android_method = managment_android_persisttun_action(management);
1877
1878 /* Android 4.4 workaround */
1879 if (oldtunfd >=0 && android_method == ANDROID_OPEN_AFTER_CLOSE)
1880 {
1881 close(oldtunfd);
1882 management_sleep(2);
1883 }
1884
1885 if (oldtunfd >=0 && android_method == ANDROID_KEEP_OLD_TUN)
1886 {
1887 /* keep the old fd */
1888 opentun = true;
1889 }
1890 else
1891 {
1892 opentun = management_android_control(management, "OPENTUN", dev);
1893 /* Pick up the fd from management interface after calling the
1894 * OPENTUN command */
1895 tt->fd = management->connection.lastfdreceived;
1896 management->connection.lastfdreceived = -1;
1897 }
1898
1899 if (oldtunfd>=0 && android_method == ANDROID_OPEN_BEFORE_CLOSE)
1900 {
1901 close(oldtunfd);
1902 }
1903
1904 /* Set the actual name to a dummy name */
1905 tt->actual_name = string_alloc(ANDROID_TUNNAME, NULL);
1906
1907 if ((tt->fd < 0) || !opentun)
1908 {
1909 msg(M_ERR, "ERROR: Cannot open TUN");
1910 }
1911
1912 gc_free(&gc);
1913 }
1914
1915 void
close_tun(struct tuntap * tt,openvpn_net_ctx_t * ctx)1916 close_tun(struct tuntap *tt, openvpn_net_ctx_t *ctx)
1917 {
1918 ASSERT(tt);
1919
1920 close_tun_generic(tt);
1921 free(tt);
1922 }
1923
1924 int
write_tun(struct tuntap * tt,uint8_t * buf,int len)1925 write_tun(struct tuntap *tt, uint8_t *buf, int len)
1926 {
1927 return write(tt->fd, buf, len);
1928 }
1929
1930 int
read_tun(struct tuntap * tt,uint8_t * buf,int len)1931 read_tun(struct tuntap *tt, uint8_t *buf, int len)
1932 {
1933 return read(tt->fd, buf, len);
1934 }
1935
1936 #elif defined(TARGET_LINUX)
1937
1938 #ifndef HAVE_LINUX_SOCKIOS_H
1939 #error header file linux/sockios.h required
1940 #endif
1941
1942 #if !PEDANTIC
1943
1944 void
open_tun(const char * dev,const char * dev_type,const char * dev_node,struct tuntap * tt)1945 open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
1946 {
1947 struct ifreq ifr;
1948
1949 /*
1950 * We handle --dev null specially, we do not open /dev/null for this.
1951 */
1952 if (tt->type == DEV_TYPE_NULL)
1953 {
1954 open_null(tt);
1955 }
1956 else
1957 {
1958 /*
1959 * Process --dev-node
1960 */
1961 const char *node = dev_node;
1962 if (!node)
1963 {
1964 node = "/dev/net/tun";
1965 }
1966
1967 /*
1968 * Open the interface
1969 */
1970 if ((tt->fd = open(node, O_RDWR)) < 0)
1971 {
1972 msg(M_ERR, "ERROR: Cannot open TUN/TAP dev %s", node);
1973 }
1974
1975 /*
1976 * Process --tun-ipv6
1977 */
1978 CLEAR(ifr);
1979 ifr.ifr_flags = IFF_NO_PI;
1980
1981 #if defined(IFF_ONE_QUEUE) && defined(SIOCSIFTXQLEN)
1982 ifr.ifr_flags |= IFF_ONE_QUEUE;
1983 #endif
1984
1985 /*
1986 * Figure out if tun or tap device
1987 */
1988 if (tt->type == DEV_TYPE_TUN)
1989 {
1990 ifr.ifr_flags |= IFF_TUN;
1991 }
1992 else if (tt->type == DEV_TYPE_TAP)
1993 {
1994 ifr.ifr_flags |= IFF_TAP;
1995 }
1996 else
1997 {
1998 msg(M_FATAL, "I don't recognize device %s as a tun or tap device",
1999 dev);
2000 }
2001
2002 /*
2003 * Set an explicit name, if --dev is not tun or tap
2004 */
2005 if (strcmp(dev, "tun") && strcmp(dev, "tap"))
2006 {
2007 strncpynt(ifr.ifr_name, dev, IFNAMSIZ);
2008 }
2009
2010 /*
2011 * Use special ioctl that configures tun/tap device with the parms
2012 * we set in ifr
2013 */
2014 if (ioctl(tt->fd, TUNSETIFF, (void *) &ifr) < 0)
2015 {
2016 msg(M_ERR, "ERROR: Cannot ioctl TUNSETIFF %s", dev);
2017 }
2018
2019 msg(M_INFO, "TUN/TAP device %s opened", ifr.ifr_name);
2020
2021 /*
2022 * Try making the TX send queue bigger
2023 */
2024 #if defined(IFF_ONE_QUEUE) && defined(SIOCSIFTXQLEN)
2025 if (tt->options.txqueuelen)
2026 {
2027 struct ifreq netifr;
2028 int ctl_fd;
2029
2030 if ((ctl_fd = socket(AF_INET, SOCK_DGRAM, 0)) >= 0)
2031 {
2032 CLEAR(netifr);
2033 strncpynt(netifr.ifr_name, ifr.ifr_name, IFNAMSIZ);
2034 netifr.ifr_qlen = tt->options.txqueuelen;
2035 if (ioctl(ctl_fd, SIOCSIFTXQLEN, (void *) &netifr) >= 0)
2036 {
2037 msg(D_OSBUF, "TUN/TAP TX queue length set to %d", tt->options.txqueuelen);
2038 }
2039 else
2040 {
2041 msg(M_WARN | M_ERRNO, "Note: Cannot set tx queue length on %s", ifr.ifr_name);
2042 }
2043 close(ctl_fd);
2044 }
2045 else
2046 {
2047 msg(M_WARN | M_ERRNO, "Note: Cannot open control socket on %s", ifr.ifr_name);
2048 }
2049 }
2050 #endif /* if defined(IFF_ONE_QUEUE) && defined(SIOCSIFTXQLEN) */
2051
2052 set_nonblock(tt->fd);
2053 set_cloexec(tt->fd);
2054 tt->actual_name = string_alloc(ifr.ifr_name, NULL);
2055 }
2056 return;
2057 }
2058
2059 #else /* if !PEDANTIC */
2060
2061 void
open_tun(const char * dev,const char * dev_type,const char * dev_node,struct tuntap * tt)2062 open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
2063 {
2064 ASSERT(0);
2065 }
2066
2067 #endif /* !PEDANTIC */
2068
2069 #ifdef ENABLE_FEATURE_TUN_PERSIST
2070
2071 /* TUNSETGROUP appeared in 2.6.23 */
2072 #ifndef TUNSETGROUP
2073 # define TUNSETGROUP _IOW('T', 206, int)
2074 #endif
2075
2076 void
tuncfg(const char * dev,const char * dev_type,const char * dev_node,int persist_mode,const char * username,const char * groupname,const struct tuntap_options * options,openvpn_net_ctx_t * ctx)2077 tuncfg(const char *dev, const char *dev_type, const char *dev_node,
2078 int persist_mode, const char *username, const char *groupname,
2079 const struct tuntap_options *options, openvpn_net_ctx_t *ctx)
2080 {
2081 struct tuntap *tt;
2082
2083 ALLOC_OBJ(tt, struct tuntap);
2084 clear_tuntap(tt);
2085 tt->type = dev_type_enum(dev, dev_type);
2086 tt->options = *options;
2087 open_tun(dev, dev_type, dev_node, tt);
2088 if (ioctl(tt->fd, TUNSETPERSIST, persist_mode) < 0)
2089 {
2090 msg(M_ERR, "Cannot ioctl TUNSETPERSIST(%d) %s", persist_mode, dev);
2091 }
2092 if (username != NULL)
2093 {
2094 struct platform_state_user platform_state_user;
2095
2096 if (!platform_user_get(username, &platform_state_user))
2097 {
2098 msg(M_ERR, "Cannot get user entry for %s", username);
2099 }
2100 else if (ioctl(tt->fd, TUNSETOWNER, platform_state_user.pw->pw_uid) < 0)
2101 {
2102 msg(M_ERR, "Cannot ioctl TUNSETOWNER(%s) %s", username, dev);
2103 }
2104 }
2105 if (groupname != NULL)
2106 {
2107 struct platform_state_group platform_state_group;
2108
2109 if (!platform_group_get(groupname, &platform_state_group))
2110 {
2111 msg(M_ERR, "Cannot get group entry for %s", groupname);
2112 }
2113 else if (ioctl(tt->fd, TUNSETGROUP, platform_state_group.gr->gr_gid) < 0)
2114 {
2115 msg(M_ERR, "Cannot ioctl TUNSETGROUP(%s) %s", groupname, dev);
2116 }
2117 }
2118 close_tun(tt, ctx);
2119 msg(M_INFO, "Persist state set to: %s", (persist_mode ? "ON" : "OFF"));
2120 }
2121
2122 #endif /* ENABLE_FEATURE_TUN_PERSIST */
2123
2124 static void
undo_ifconfig_ipv4(struct tuntap * tt,openvpn_net_ctx_t * ctx)2125 undo_ifconfig_ipv4(struct tuntap *tt, openvpn_net_ctx_t *ctx)
2126 {
2127 #if defined(TARGET_LINUX)
2128 int netbits = netmask_to_netbits2(tt->remote_netmask);
2129
2130 if (is_tun_p2p(tt))
2131 {
2132 if (net_addr_ptp_v4_del(ctx, tt->actual_name, &tt->local,
2133 &tt->remote_netmask) < 0)
2134 {
2135 msg(M_WARN, "Linux can't del IP from iface %s",
2136 tt->actual_name);
2137 }
2138 }
2139 else
2140 {
2141 if (net_addr_v4_del(ctx, tt->actual_name, &tt->local, netbits) < 0)
2142 {
2143 msg(M_WARN, "Linux can't del IP from iface %s",
2144 tt->actual_name);
2145 }
2146 }
2147 #else /* ifndef TARGET_LINUX */
2148 struct argv argv = argv_new();
2149
2150 argv_printf(&argv, "%s %s 0.0.0.0", IFCONFIG_PATH, tt->actual_name);
2151
2152 argv_msg(M_INFO, &argv);
2153 openvpn_execve_check(&argv, NULL, 0, "Generic ip addr del failed");
2154
2155 argv_free(&argv);
2156 #endif /* ifdef TARGET_LINUX */
2157 }
2158
2159 static void
undo_ifconfig_ipv6(struct tuntap * tt,openvpn_net_ctx_t * ctx)2160 undo_ifconfig_ipv6(struct tuntap *tt, openvpn_net_ctx_t *ctx)
2161 {
2162 #if defined(TARGET_LINUX)
2163 if (net_addr_v6_del(ctx, tt->actual_name, &tt->local_ipv6,
2164 tt->netbits_ipv6) < 0)
2165 {
2166 msg(M_WARN, "Linux can't del IPv6 from iface %s", tt->actual_name);
2167 }
2168 #else /* ifndef TARGET_LINUX */
2169 struct gc_arena gc = gc_new();
2170 const char *ifconfig_ipv6_local = print_in6_addr(tt->local_ipv6, 0, gc);
2171 struct argv argv = argv_new();
2172
2173 argv_printf(&argv, "%s %s del %s/%d", IFCONFIG_PATH, tt->actual_name,
2174 ifconfig_ipv6_local, tt->netbits_ipv6);
2175
2176 argv_msg(M_INFO, &argv);
2177 openvpn_execve_check(&argv, NULL, 0, "Linux ip -6 addr del failed");
2178
2179 argv_free(&argv);
2180 gc_free(&gc);
2181 #endif /* ifdef TARGET_LINUX */
2182 }
2183
2184 void
close_tun(struct tuntap * tt,openvpn_net_ctx_t * ctx)2185 close_tun(struct tuntap *tt, openvpn_net_ctx_t *ctx)
2186 {
2187 ASSERT(tt);
2188
2189 if (tt->type != DEV_TYPE_NULL)
2190 {
2191 if (tt->did_ifconfig_setup)
2192 {
2193 undo_ifconfig_ipv4(tt, ctx);
2194 }
2195
2196 if (tt->did_ifconfig_ipv6_setup)
2197 {
2198 undo_ifconfig_ipv6(tt, ctx);
2199 }
2200
2201 /* release resources potentially allocated during undo */
2202 net_ctx_reset(ctx);
2203 }
2204
2205 close_tun_generic(tt);
2206 free(tt);
2207 }
2208
2209 int
write_tun(struct tuntap * tt,uint8_t * buf,int len)2210 write_tun(struct tuntap *tt, uint8_t *buf, int len)
2211 {
2212 return write(tt->fd, buf, len);
2213 }
2214
2215 int
read_tun(struct tuntap * tt,uint8_t * buf,int len)2216 read_tun(struct tuntap *tt, uint8_t *buf, int len)
2217 {
2218 return read(tt->fd, buf, len);
2219 }
2220
2221 #elif defined(TARGET_SOLARIS)
2222
2223 #ifndef TUNNEWPPA
2224 #error I need the symbol TUNNEWPPA from net/if_tun.h
2225 #endif
2226
2227 void
open_tun(const char * dev,const char * dev_type,const char * dev_node,struct tuntap * tt)2228 open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
2229 {
2230 int if_fd, ip_muxid, arp_muxid, arp_fd, ppa = -1;
2231 struct lifreq ifr;
2232 const char *ptr;
2233 const char *ip_node, *arp_node;
2234 const char *dev_tuntap_type;
2235 int link_type;
2236 bool is_tun;
2237 struct strioctl strioc_if, strioc_ppa;
2238
2239 /* improved generic TUN/TAP driver from
2240 * http://www.whiteboard.ne.jp/~admin2/tuntap/
2241 * has IPv6 support
2242 */
2243 CLEAR(ifr);
2244
2245 if (tt->type == DEV_TYPE_NULL)
2246 {
2247 open_null(tt);
2248 return;
2249 }
2250
2251 if (tt->type == DEV_TYPE_TUN)
2252 {
2253 ip_node = "/dev/udp";
2254 if (!dev_node)
2255 {
2256 dev_node = "/dev/tun";
2257 }
2258 dev_tuntap_type = "tun";
2259 link_type = I_PLINK;
2260 is_tun = true;
2261 }
2262 else if (tt->type == DEV_TYPE_TAP)
2263 {
2264 ip_node = "/dev/udp";
2265 if (!dev_node)
2266 {
2267 dev_node = "/dev/tap";
2268 }
2269 arp_node = dev_node;
2270 dev_tuntap_type = "tap";
2271 link_type = I_PLINK; /* was: I_LINK */
2272 is_tun = false;
2273 }
2274 else
2275 {
2276 msg(M_FATAL, "I don't recognize device %s as a tun or tap device",
2277 dev);
2278 }
2279
2280 if ((tt->ip_fd = open(ip_node, O_RDWR, 0)) < 0)
2281 {
2282 msg(M_ERR, "Can't open %s", ip_node);
2283 }
2284
2285 if ((tt->fd = open(dev_node, O_RDWR, 0)) < 0)
2286 {
2287 msg(M_ERR, "Can't open %s", dev_node);
2288 }
2289
2290 /* get unit number */
2291 if (*dev)
2292 {
2293 ptr = dev;
2294 while (*ptr && !isdigit((int) *ptr))
2295 {
2296 ptr++;
2297 }
2298 ppa = atoi(ptr);
2299 }
2300
2301 /* Assign a new PPA and get its unit number. */
2302 strioc_ppa.ic_cmd = TUNNEWPPA;
2303 strioc_ppa.ic_timout = 0;
2304 strioc_ppa.ic_len = sizeof(ppa);
2305 strioc_ppa.ic_dp = (char *)&ppa;
2306
2307 if (*ptr == '\0') /* no number given, try dynamic */
2308 {
2309 bool found_one = false;
2310 while (!found_one && ppa < 64)
2311 {
2312 int new_ppa = ioctl(tt->fd, I_STR, &strioc_ppa);
2313 if (new_ppa >= 0)
2314 {
2315 msg( M_INFO, "open_tun: got dynamic interface '%s%d'", dev_tuntap_type, new_ppa );
2316 ppa = new_ppa;
2317 found_one = true;
2318 break;
2319 }
2320 if (errno != EEXIST)
2321 {
2322 msg(M_ERR, "open_tun: unexpected error trying to find free %s interface", dev_tuntap_type );
2323 }
2324 ppa++;
2325 }
2326 if (!found_one)
2327 {
2328 msg(M_ERR, "open_tun: could not find free %s interface, give up.", dev_tuntap_type );
2329 }
2330 }
2331 else /* try this particular one */
2332 {
2333 if ((ppa = ioctl(tt->fd, I_STR, &strioc_ppa)) < 0)
2334 {
2335 msg(M_ERR, "Can't assign PPA for new interface (%s%d)", dev_tuntap_type, ppa );
2336 }
2337 }
2338
2339 if ((if_fd = open(dev_node, O_RDWR, 0)) < 0)
2340 {
2341 msg(M_ERR, "Can't open %s (2)", dev_node);
2342 }
2343
2344 if (ioctl(if_fd, I_PUSH, "ip") < 0)
2345 {
2346 msg(M_ERR, "Can't push IP module");
2347 }
2348
2349 if (tt->type == DEV_TYPE_TUN)
2350 {
2351 /* Assign ppa according to the unit number returned by tun device */
2352 if (ioctl(if_fd, IF_UNITSEL, (char *) &ppa) < 0)
2353 {
2354 msg(M_ERR, "Can't set PPA %d", ppa);
2355 }
2356 }
2357
2358 tt->actual_name = (char *) malloc(32);
2359 check_malloc_return(tt->actual_name);
2360
2361 openvpn_snprintf(tt->actual_name, 32, "%s%d", dev_tuntap_type, ppa);
2362
2363 if (tt->type == DEV_TYPE_TAP)
2364 {
2365 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
2366 {
2367 msg(M_ERR, "Can't get flags\n");
2368 }
2369 strncpynt(ifr.lifr_name, tt->actual_name, sizeof(ifr.lifr_name));
2370 ifr.lifr_ppa = ppa;
2371 /* Assign ppa according to the unit number returned by tun device */
2372 if (ioctl(if_fd, SIOCSLIFNAME, &ifr) < 0)
2373 {
2374 msg(M_ERR, "Can't set PPA %d", ppa);
2375 }
2376 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
2377 {
2378 msg(M_ERR, "Can't get flags\n");
2379 }
2380 /* Push arp module to if_fd */
2381 if (ioctl(if_fd, I_PUSH, "arp") < 0)
2382 {
2383 msg(M_ERR, "Can't push ARP module");
2384 }
2385
2386 /* Pop any modules on the stream */
2387 while (true)
2388 {
2389 if (ioctl(tt->ip_fd, I_POP, NULL) < 0)
2390 {
2391 break;
2392 }
2393 }
2394 /* Push arp module to ip_fd */
2395 if (ioctl(tt->ip_fd, I_PUSH, "arp") < 0)
2396 {
2397 msg(M_ERR, "Can't push ARP module\n");
2398 }
2399
2400 /* Open arp_fd */
2401 if ((arp_fd = open(arp_node, O_RDWR, 0)) < 0)
2402 {
2403 msg(M_ERR, "Can't open %s\n", arp_node);
2404 }
2405 /* Push arp module to arp_fd */
2406 if (ioctl(arp_fd, I_PUSH, "arp") < 0)
2407 {
2408 msg(M_ERR, "Can't push ARP module\n");
2409 }
2410
2411 /* Set ifname to arp */
2412 strioc_if.ic_cmd = SIOCSLIFNAME;
2413 strioc_if.ic_timout = 0;
2414 strioc_if.ic_len = sizeof(ifr);
2415 strioc_if.ic_dp = (char *)𝔦
2416 if (ioctl(arp_fd, I_STR, &strioc_if) < 0)
2417 {
2418 msg(M_ERR, "Can't set ifname to arp\n");
2419 }
2420 }
2421
2422 if ((ip_muxid = ioctl(tt->ip_fd, link_type, if_fd)) < 0)
2423 {
2424 msg(M_ERR, "Can't link %s device to IP", dev_tuntap_type);
2425 }
2426
2427 if (tt->type == DEV_TYPE_TAP)
2428 {
2429 if ((arp_muxid = ioctl(tt->ip_fd, link_type, arp_fd)) < 0)
2430 {
2431 msg(M_ERR, "Can't link %s device to ARP", dev_tuntap_type);
2432 }
2433 close(arp_fd);
2434 }
2435
2436 CLEAR(ifr);
2437 strncpynt(ifr.lifr_name, tt->actual_name, sizeof(ifr.lifr_name));
2438 ifr.lifr_ip_muxid = ip_muxid;
2439 if (tt->type == DEV_TYPE_TAP)
2440 {
2441 ifr.lifr_arp_muxid = arp_muxid;
2442 }
2443
2444 if (ioctl(tt->ip_fd, SIOCSLIFMUXID, &ifr) < 0)
2445 {
2446 if (tt->type == DEV_TYPE_TAP)
2447 {
2448 ioctl(tt->ip_fd, I_PUNLINK, arp_muxid);
2449 }
2450 ioctl(tt->ip_fd, I_PUNLINK, ip_muxid);
2451 msg(M_ERR, "Can't set multiplexor id");
2452 }
2453
2454 set_nonblock(tt->fd);
2455 set_cloexec(tt->fd);
2456 set_cloexec(tt->ip_fd);
2457
2458 msg(M_INFO, "TUN/TAP device %s opened", tt->actual_name);
2459 }
2460
2461 static void
solaris_close_tun(struct tuntap * tt)2462 solaris_close_tun(struct tuntap *tt)
2463 {
2464 /* IPv6 interfaces need to be 'manually' de-configured */
2465 if (tt->did_ifconfig_ipv6_setup)
2466 {
2467 struct argv argv = argv_new();
2468 argv_printf( &argv, "%s %s inet6 unplumb",
2469 IFCONFIG_PATH, tt->actual_name );
2470 argv_msg(M_INFO, &argv);
2471 openvpn_execve_check(&argv, NULL, 0, "Solaris ifconfig inet6 unplumb failed");
2472 argv_free(&argv);
2473 }
2474
2475 if (tt->ip_fd >= 0)
2476 {
2477 struct lifreq ifr;
2478 CLEAR(ifr);
2479 strncpynt(ifr.lifr_name, tt->actual_name, sizeof(ifr.lifr_name));
2480
2481 if (ioctl(tt->ip_fd, SIOCGLIFFLAGS, &ifr) < 0)
2482 {
2483 msg(M_WARN | M_ERRNO, "Can't get iface flags");
2484 }
2485
2486 if (ioctl(tt->ip_fd, SIOCGLIFMUXID, &ifr) < 0)
2487 {
2488 msg(M_WARN | M_ERRNO, "Can't get multiplexor id");
2489 }
2490
2491 if (tt->type == DEV_TYPE_TAP)
2492 {
2493 if (ioctl(tt->ip_fd, I_PUNLINK, ifr.lifr_arp_muxid) < 0)
2494 {
2495 msg(M_WARN | M_ERRNO, "Can't unlink interface(arp)");
2496 }
2497 }
2498
2499 if (ioctl(tt->ip_fd, I_PUNLINK, ifr.lifr_ip_muxid) < 0)
2500 {
2501 msg(M_WARN | M_ERRNO, "Can't unlink interface(ip)");
2502 }
2503
2504 close(tt->ip_fd);
2505 tt->ip_fd = -1;
2506 }
2507
2508 if (tt->fd >= 0)
2509 {
2510 close(tt->fd);
2511 tt->fd = -1;
2512 }
2513 }
2514
2515 /*
2516 * Close TUN device.
2517 */
2518 void
close_tun(struct tuntap * tt,openvpn_net_ctx_t * ctx)2519 close_tun(struct tuntap *tt, openvpn_net_ctx_t *ctx)
2520 {
2521 ASSERT(tt);
2522
2523 solaris_close_tun(tt);
2524
2525 if (tt->actual_name)
2526 {
2527 free(tt->actual_name);
2528 }
2529
2530 clear_tuntap(tt);
2531 free(tt);
2532 }
2533
2534 static void
solaris_error_close(struct tuntap * tt,const struct env_set * es,const char * actual,bool unplumb_inet6)2535 solaris_error_close(struct tuntap *tt, const struct env_set *es,
2536 const char *actual, bool unplumb_inet6 )
2537 {
2538 struct argv argv = argv_new();
2539
2540 if (unplumb_inet6)
2541 {
2542 argv_printf( &argv, "%s %s inet6 unplumb",
2543 IFCONFIG_PATH, actual );
2544 argv_msg(M_INFO, &argv);
2545 openvpn_execve_check(&argv, es, 0, "Solaris ifconfig inet6 unplumb failed");
2546 }
2547
2548 argv_printf(&argv,
2549 "%s %s unplumb",
2550 IFCONFIG_PATH,
2551 actual);
2552
2553 argv_msg(M_INFO, &argv);
2554 openvpn_execve_check(&argv, es, 0, "Solaris ifconfig unplumb failed");
2555 close_tun(tt, NULL);
2556 msg(M_FATAL, "Solaris ifconfig failed");
2557 argv_free(&argv);
2558 }
2559
2560 int
write_tun(struct tuntap * tt,uint8_t * buf,int len)2561 write_tun(struct tuntap *tt, uint8_t *buf, int len)
2562 {
2563 struct strbuf sbuf;
2564 sbuf.len = len;
2565 sbuf.buf = (char *)buf;
2566 return putmsg(tt->fd, NULL, &sbuf, 0) >= 0 ? sbuf.len : -1;
2567 }
2568
2569 int
read_tun(struct tuntap * tt,uint8_t * buf,int len)2570 read_tun(struct tuntap *tt, uint8_t *buf, int len)
2571 {
2572 struct strbuf sbuf;
2573 int f = 0;
2574
2575 sbuf.maxlen = len;
2576 sbuf.buf = (char *)buf;
2577 return getmsg(tt->fd, NULL, &sbuf, &f) >= 0 ? sbuf.len : -1;
2578 }
2579
2580 #elif defined(TARGET_OPENBSD)
2581
2582 void
open_tun(const char * dev,const char * dev_type,const char * dev_node,struct tuntap * tt)2583 open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
2584 {
2585 open_tun_generic(dev, dev_type, dev_node, true, tt);
2586
2587 /* Enable multicast on the interface */
2588 if (tt->fd >= 0)
2589 {
2590 struct tuninfo info;
2591
2592 if (ioctl(tt->fd, TUNGIFINFO, &info) < 0)
2593 {
2594 msg(M_WARN | M_ERRNO, "Can't get interface info");
2595 }
2596
2597 #ifdef IFF_MULTICAST /* openbsd 4.x doesn't have this */
2598 info.flags |= IFF_MULTICAST;
2599 #endif
2600
2601 if (ioctl(tt->fd, TUNSIFINFO, &info) < 0)
2602 {
2603 msg(M_WARN | M_ERRNO, "Can't set interface info");
2604 }
2605 }
2606 }
2607
2608 /* tun(4): "If the device was created by opening /dev/tunN, it will be
2609 * automatically destroyed. Devices created via ifconfig(8) are
2610 * only marked as not running and traffic will be dropped
2611 * returning EHOSTDOWN."
2612 * --> no special handling should be needed - *but* OpenBSD is misbehaving
2613 * here: if the interface was put in tap mode ("ifconfig tunN link0"), it
2614 * *will* stay around, and needs to be cleaned up manually
2615 */
2616
2617 void
close_tun(struct tuntap * tt,openvpn_net_ctx_t * ctx)2618 close_tun(struct tuntap *tt, openvpn_net_ctx_t *ctx)
2619 {
2620 ASSERT(tt);
2621
2622 /* only *TAP* devices need destroying, tun devices auto-self-destruct
2623 */
2624 if (tt->type == DEV_TYPE_TUN || tt->persistent_if)
2625 {
2626 close_tun_generic(tt);
2627 free(tt);
2628 return;
2629 }
2630
2631 struct argv argv = argv_new();
2632
2633 /* setup command, close tun dev (clears tt->actual_name!), run command
2634 */
2635
2636 argv_printf(&argv, "%s %s destroy",
2637 IFCONFIG_PATH, tt->actual_name);
2638
2639 close_tun_generic(tt);
2640
2641 argv_msg(M_INFO, &argv);
2642 openvpn_execve_check(&argv, NULL, 0, "OpenBSD 'destroy tun interface' failed (non-critical)");
2643
2644 free(tt);
2645 argv_free(&argv);
2646 }
2647
2648 int
write_tun(struct tuntap * tt,uint8_t * buf,int len)2649 write_tun(struct tuntap *tt, uint8_t *buf, int len)
2650 {
2651 return write_tun_header(tt, buf, len);
2652 }
2653
2654 int
read_tun(struct tuntap * tt,uint8_t * buf,int len)2655 read_tun(struct tuntap *tt, uint8_t *buf, int len)
2656 {
2657 return read_tun_header(tt, buf, len);
2658 }
2659
2660 #elif defined(TARGET_NETBSD)
2661
2662 /*
2663 * NetBSD before 4.0 does not support IPv6 on tun out of the box,
2664 * but there exists a patch (sys/net/if_tun.c, 1.79->1.80, see PR 32944).
2665 *
2666 * NetBSD 4.0 and up do, but we need to put the tun interface into
2667 * "multi_af" mode, which will prepend the address family to all packets
2668 * (same as OpenBSD and FreeBSD). If this is not enabled, the kernel
2669 * silently drops all IPv6 packets on output and gets confused on input.
2670 *
2671 * On earlier versions, multi_af is not available at all, so we have
2672 * two different NetBSD code variants here :-(
2673 *
2674 */
2675
2676 void
open_tun(const char * dev,const char * dev_type,const char * dev_node,struct tuntap * tt)2677 open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
2678 {
2679 open_tun_generic(dev, dev_type, dev_node, true, tt);
2680
2681 if (tt->fd >= 0)
2682 {
2683 int i = IFF_POINTOPOINT|IFF_MULTICAST;
2684 ioctl(tt->fd, TUNSIFMODE, &i); /* multicast on */
2685 i = 0;
2686 ioctl(tt->fd, TUNSLMODE, &i); /* link layer mode off */
2687
2688 if (tt->type == DEV_TYPE_TUN)
2689 {
2690 i = 1;
2691 if (ioctl(tt->fd, TUNSIFHEAD, &i) < 0) /* multi-af mode on */
2692 {
2693 msg(M_WARN | M_ERRNO, "ioctl(TUNSIFHEAD)");
2694 }
2695 }
2696 }
2697 }
2698
2699 /* the current way OpenVPN handles tun devices on NetBSD leads to
2700 * lingering tunX interfaces after close -> for a full cleanup, they
2701 * need to be explicitly destroyed
2702 */
2703 void
close_tun(struct tuntap * tt,openvpn_net_ctx_t * ctx)2704 close_tun(struct tuntap *tt, openvpn_net_ctx_t *ctx)
2705 {
2706 ASSERT(tt);
2707
2708 /* only tun devices need destroying, tap devices auto-self-destruct
2709 */
2710 if (tt->type != DEV_TYPE_TUN || tt->persistent_if)
2711 {
2712 close_tun_generic(tt);
2713 free(tt);
2714 return;
2715 }
2716
2717 struct argv argv = argv_new();
2718
2719 /* setup command, close tun dev (clears tt->actual_name!), run command
2720 */
2721
2722 argv_printf(&argv, "%s %s destroy",
2723 IFCONFIG_PATH, tt->actual_name);
2724
2725 close_tun_generic(tt);
2726
2727 argv_msg(M_INFO, &argv);
2728 openvpn_execve_check(&argv, NULL, 0, "NetBSD 'destroy tun interface' failed (non-critical)");
2729
2730 free(tt);
2731 argv_free(&argv);
2732 }
2733
2734 static inline int
netbsd_modify_read_write_return(int len)2735 netbsd_modify_read_write_return(int len)
2736 {
2737 if (len > 0)
2738 {
2739 return len > sizeof(u_int32_t) ? len - sizeof(u_int32_t) : 0;
2740 }
2741 else
2742 {
2743 return len;
2744 }
2745 }
2746
2747 int
write_tun(struct tuntap * tt,uint8_t * buf,int len)2748 write_tun(struct tuntap *tt, uint8_t *buf, int len)
2749 {
2750 if (tt->type == DEV_TYPE_TUN)
2751 {
2752 u_int32_t type;
2753 struct iovec iv[2];
2754 struct openvpn_iphdr *iph;
2755
2756 iph = (struct openvpn_iphdr *) buf;
2757
2758 if (OPENVPN_IPH_GET_VER(iph->version_len) == 6)
2759 {
2760 type = htonl(AF_INET6);
2761 }
2762 else
2763 {
2764 type = htonl(AF_INET);
2765 }
2766
2767 iv[0].iov_base = (char *)&type;
2768 iv[0].iov_len = sizeof(type);
2769 iv[1].iov_base = buf;
2770 iv[1].iov_len = len;
2771
2772 return netbsd_modify_read_write_return(writev(tt->fd, iv, 2));
2773 }
2774 else
2775 {
2776 return write(tt->fd, buf, len);
2777 }
2778 }
2779
2780 int
read_tun(struct tuntap * tt,uint8_t * buf,int len)2781 read_tun(struct tuntap *tt, uint8_t *buf, int len)
2782 {
2783 if (tt->type == DEV_TYPE_TUN)
2784 {
2785 u_int32_t type;
2786 struct iovec iv[2];
2787
2788 iv[0].iov_base = (char *)&type;
2789 iv[0].iov_len = sizeof(type);
2790 iv[1].iov_base = buf;
2791 iv[1].iov_len = len;
2792
2793 return netbsd_modify_read_write_return(readv(tt->fd, iv, 2));
2794 }
2795 else
2796 {
2797 return read(tt->fd, buf, len);
2798 }
2799 }
2800
2801 #elif defined(TARGET_FREEBSD)
2802
2803 static inline int
freebsd_modify_read_write_return(int len)2804 freebsd_modify_read_write_return(int len)
2805 {
2806 if (len > 0)
2807 {
2808 return len > sizeof(u_int32_t) ? len - sizeof(u_int32_t) : 0;
2809 }
2810 else
2811 {
2812 return len;
2813 }
2814 }
2815
2816 void
open_tun(const char * dev,const char * dev_type,const char * dev_node,struct tuntap * tt)2817 open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
2818 {
2819 open_tun_generic(dev, dev_type, dev_node, true, tt);
2820
2821 if (tt->fd >= 0 && tt->type == DEV_TYPE_TUN)
2822 {
2823 int i = IFF_POINTOPOINT | IFF_MULTICAST;
2824
2825 if (ioctl(tt->fd, TUNSIFMODE, &i) < 0)
2826 {
2827 msg(M_WARN | M_ERRNO, "ioctl(TUNSIFMODE)");
2828 }
2829 i = 1;
2830 if (ioctl(tt->fd, TUNSIFHEAD, &i) < 0)
2831 {
2832 msg(M_WARN | M_ERRNO, "ioctl(TUNSIFHEAD)");
2833 }
2834 }
2835 }
2836
2837 /* tun(4): "These network interfaces persist until the if_tun.ko module is
2838 * unloaded, or until removed with the ifconfig(8) command."
2839 * (verified for FreeBSD 6.3, 7.4, 8.2 and 9, same for tap(4))
2840 *
2841 * so, to avoid lingering tun/tap interfaces after OpenVPN quits,
2842 * we need to call "ifconfig ... destroy" for cleanup
2843 */
2844 void
close_tun(struct tuntap * tt,openvpn_net_ctx_t * ctx)2845 close_tun(struct tuntap *tt, openvpn_net_ctx_t *ctx)
2846 {
2847 ASSERT(tt);
2848
2849 if (tt->persistent_if) /* keep pre-existing if around */
2850 {
2851 close_tun_generic(tt);
2852 free(tt);
2853 return;
2854 }
2855
2856 /* close and destroy */
2857 struct argv argv = argv_new();
2858
2859 /* setup command, close tun dev (clears tt->actual_name!), run command
2860 */
2861
2862 argv_printf(&argv, "%s %s destroy",
2863 IFCONFIG_PATH, tt->actual_name);
2864
2865 close_tun_generic(tt);
2866
2867 argv_msg(M_INFO, &argv);
2868 openvpn_execve_check(&argv, NULL, 0,
2869 "FreeBSD 'destroy tun interface' failed (non-critical)");
2870
2871 free(tt);
2872 argv_free(&argv);
2873 }
2874
2875 int
write_tun(struct tuntap * tt,uint8_t * buf,int len)2876 write_tun(struct tuntap *tt, uint8_t *buf, int len)
2877 {
2878 if (tt->type == DEV_TYPE_TUN)
2879 {
2880 u_int32_t type;
2881 struct iovec iv[2];
2882 struct ip *iph;
2883
2884 iph = (struct ip *) buf;
2885
2886 if (iph->ip_v == 6)
2887 {
2888 type = htonl(AF_INET6);
2889 }
2890 else
2891 {
2892 type = htonl(AF_INET);
2893 }
2894
2895 iv[0].iov_base = (char *)&type;
2896 iv[0].iov_len = sizeof(type);
2897 iv[1].iov_base = buf;
2898 iv[1].iov_len = len;
2899
2900 return freebsd_modify_read_write_return(writev(tt->fd, iv, 2));
2901 }
2902 else
2903 {
2904 return write(tt->fd, buf, len);
2905 }
2906 }
2907
2908 int
read_tun(struct tuntap * tt,uint8_t * buf,int len)2909 read_tun(struct tuntap *tt, uint8_t *buf, int len)
2910 {
2911 if (tt->type == DEV_TYPE_TUN)
2912 {
2913 u_int32_t type;
2914 struct iovec iv[2];
2915
2916 iv[0].iov_base = (char *)&type;
2917 iv[0].iov_len = sizeof(type);
2918 iv[1].iov_base = buf;
2919 iv[1].iov_len = len;
2920
2921 return freebsd_modify_read_write_return(readv(tt->fd, iv, 2));
2922 }
2923 else
2924 {
2925 return read(tt->fd, buf, len);
2926 }
2927 }
2928
2929 #elif defined(TARGET_DRAGONFLY)
2930
2931 static inline int
dragonfly_modify_read_write_return(int len)2932 dragonfly_modify_read_write_return(int len)
2933 {
2934 if (len > 0)
2935 {
2936 return len > sizeof(u_int32_t) ? len - sizeof(u_int32_t) : 0;
2937 }
2938 else
2939 {
2940 return len;
2941 }
2942 }
2943
2944 void
open_tun(const char * dev,const char * dev_type,const char * dev_node,struct tuntap * tt)2945 open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
2946 {
2947 open_tun_generic(dev, dev_type, dev_node, true, tt);
2948
2949 if (tt->fd >= 0)
2950 {
2951 int i = 0;
2952
2953 /* Disable extended modes */
2954 ioctl(tt->fd, TUNSLMODE, &i);
2955 i = 1;
2956 ioctl(tt->fd, TUNSIFHEAD, &i);
2957 }
2958 }
2959
2960 void
close_tun(struct tuntap * tt,openvpn_net_ctx_t * ctx)2961 close_tun(struct tuntap *tt, openvpn_net_ctx_t *ctx)
2962 {
2963 ASSERT(tt);
2964
2965 close_tun_generic(tt);
2966 free(tt);
2967 }
2968
2969 int
write_tun(struct tuntap * tt,uint8_t * buf,int len)2970 write_tun(struct tuntap *tt, uint8_t *buf, int len)
2971 {
2972 if (tt->type == DEV_TYPE_TUN)
2973 {
2974 u_int32_t type;
2975 struct iovec iv[2];
2976 struct ip *iph;
2977
2978 iph = (struct ip *) buf;
2979
2980 if (iph->ip_v == 6)
2981 {
2982 type = htonl(AF_INET6);
2983 }
2984 else
2985 {
2986 type = htonl(AF_INET);
2987 }
2988
2989 iv[0].iov_base = (char *)&type;
2990 iv[0].iov_len = sizeof(type);
2991 iv[1].iov_base = buf;
2992 iv[1].iov_len = len;
2993
2994 return dragonfly_modify_read_write_return(writev(tt->fd, iv, 2));
2995 }
2996 else
2997 {
2998 return write(tt->fd, buf, len);
2999 }
3000 }
3001
3002 int
read_tun(struct tuntap * tt,uint8_t * buf,int len)3003 read_tun(struct tuntap *tt, uint8_t *buf, int len)
3004 {
3005 if (tt->type == DEV_TYPE_TUN)
3006 {
3007 u_int32_t type;
3008 struct iovec iv[2];
3009
3010 iv[0].iov_base = (char *)&type;
3011 iv[0].iov_len = sizeof(type);
3012 iv[1].iov_base = buf;
3013 iv[1].iov_len = len;
3014
3015 return dragonfly_modify_read_write_return(readv(tt->fd, iv, 2));
3016 }
3017 else
3018 {
3019 return read(tt->fd, buf, len);
3020 }
3021 }
3022
3023 #elif defined(TARGET_DARWIN)
3024
3025 /* Darwin (MacOS X) is mostly "just use the generic stuff", but there
3026 * is always one caveat...:
3027 *
3028 * If IPv6 is configured, and the tun device is closed, the IPv6 address
3029 * configured to the tun interface changes to a lingering /128 route
3030 * pointing to lo0. Need to unconfigure... (observed on 10.5)
3031 */
3032
3033 /*
3034 * utun is the native Darwin tun driver present since at least 10.7
3035 * Thanks goes to Jonathan Levin for providing an example how to utun
3036 * (http://newosxbook.com/src.jl?tree=listings&file=17-15-utun.c)
3037 */
3038
3039 #ifdef HAVE_NET_IF_UTUN_H
3040
3041 /* Helper functions that tries to open utun device
3042 * return -2 on early initialization failures (utun not supported
3043 * at all (old OS X) and -1 on initlization failure of utun
3044 * device (utun works but utunX is already used */
3045 static
3046 int
utun_open_helper(struct ctl_info ctlInfo,int utunnum)3047 utun_open_helper(struct ctl_info ctlInfo, int utunnum)
3048 {
3049 struct sockaddr_ctl sc;
3050 int fd;
3051
3052 fd = socket(PF_SYSTEM, SOCK_DGRAM, SYSPROTO_CONTROL);
3053
3054 if (fd < 0)
3055 {
3056 msg(M_INFO | M_ERRNO, "Opening utun%d failed (socket(SYSPROTO_CONTROL))",
3057 utunnum);
3058 return -2;
3059 }
3060
3061 if (ioctl(fd, CTLIOCGINFO, &ctlInfo) == -1)
3062 {
3063 close(fd);
3064 msg(M_INFO | M_ERRNO, "Opening utun%d failed (ioctl(CTLIOCGINFO))",
3065 utunnum);
3066 return -2;
3067 }
3068
3069
3070 sc.sc_id = ctlInfo.ctl_id;
3071 sc.sc_len = sizeof(sc);
3072 sc.sc_family = AF_SYSTEM;
3073 sc.ss_sysaddr = AF_SYS_CONTROL;
3074
3075 sc.sc_unit = utunnum+1;
3076
3077
3078 /* If the connect is successful, a utun%d device will be created, where "%d"
3079 * is (sc.sc_unit - 1) */
3080
3081 if (connect(fd, (struct sockaddr *)&sc, sizeof(sc)) < 0)
3082 {
3083 msg(M_INFO | M_ERRNO, "Opening utun%d failed (connect(AF_SYS_CONTROL))",
3084 utunnum);
3085 close(fd);
3086 return -1;
3087 }
3088
3089 set_nonblock(fd);
3090 set_cloexec(fd); /* don't pass fd to scripts */
3091
3092 return fd;
3093 }
3094
3095 void
open_darwin_utun(const char * dev,const char * dev_type,const char * dev_node,struct tuntap * tt)3096 open_darwin_utun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
3097 {
3098 struct ctl_info ctlInfo;
3099 int fd;
3100 char utunname[20];
3101 int utunnum = -1;
3102 socklen_t utunname_len = sizeof(utunname);
3103
3104 /* dev_node is simply utun, do the normal dynamic utun
3105 * otherwise try to parse the utun number */
3106 if (dev_node && (strcmp("utun", dev_node) != 0 ))
3107 {
3108 if (sscanf(dev_node, "utun%d", &utunnum) != 1)
3109 {
3110 msg(M_FATAL, "Cannot parse 'dev-node %s' please use 'dev-node utunX'"
3111 "to use a utun device number X", dev_node);
3112 }
3113 }
3114
3115
3116
3117 CLEAR(ctlInfo);
3118 if (strlcpy(ctlInfo.ctl_name, UTUN_CONTROL_NAME, sizeof(ctlInfo.ctl_name)) >=
3119 sizeof(ctlInfo.ctl_name))
3120 {
3121 msg(M_ERR, "Opening utun: UTUN_CONTROL_NAME too long");
3122 }
3123
3124 /* try to open first available utun device if no specific utun is requested */
3125 if (utunnum == -1)
3126 {
3127 for (utunnum = 0; utunnum < 255; utunnum++)
3128 {
3129 char ifname[20];
3130 /* if the interface exists silently skip it */
3131 ASSERT(snprintf(ifname, sizeof(ifname), "utun%d", utunnum) > 0);
3132 if (if_nametoindex(ifname))
3133 {
3134 continue;
3135 }
3136 fd = utun_open_helper(ctlInfo, utunnum);
3137 /* Break if the fd is valid,
3138 * or if early initialization failed (-2) */
3139 if (fd !=-1)
3140 {
3141 break;
3142 }
3143 }
3144 }
3145 else
3146 {
3147 fd = utun_open_helper(ctlInfo, utunnum);
3148 }
3149
3150 /* opening an utun device failed */
3151 tt->fd = fd;
3152
3153 if (fd < 0)
3154 {
3155 return;
3156 }
3157
3158 /* Retrieve the assigned interface name. */
3159 if (getsockopt(fd, SYSPROTO_CONTROL, UTUN_OPT_IFNAME, utunname, &utunname_len))
3160 {
3161 msg(M_ERR | M_ERRNO, "Error retrieving utun interface name");
3162 }
3163
3164 tt->actual_name = string_alloc(utunname, NULL);
3165
3166 msg(M_INFO, "Opened utun device %s", utunname);
3167 tt->is_utun = true;
3168 }
3169
3170 #endif /* ifdef HAVE_NET_IF_UTUN_H */
3171
3172 void
open_tun(const char * dev,const char * dev_type,const char * dev_node,struct tuntap * tt)3173 open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
3174 {
3175 #ifdef HAVE_NET_IF_UTUN_H
3176 /* If dev_node does not start start with utun assume regular tun/tap */
3177 if ((!dev_node && tt->type==DEV_TYPE_TUN)
3178 || (dev_node && !strncmp(dev_node, "utun", 4)))
3179 {
3180
3181 /* Check if user has specific dev_type tap and forced utun with
3182 * dev-node utun */
3183 if (tt->type!=DEV_TYPE_TUN)
3184 {
3185 msg(M_FATAL, "Cannot use utun devices with --dev-type %s",
3186 dev_type_string(dev, dev_type));
3187 }
3188
3189 /* Try utun first and fall back to normal tun if utun fails
3190 * and dev_node is not specified */
3191 open_darwin_utun(dev, dev_type, dev_node, tt);
3192
3193 if (!tt->is_utun)
3194 {
3195 if (!dev_node)
3196 {
3197 /* No explicit utun and utun failed, try the generic way) */
3198 msg(M_INFO, "Failed to open utun device. Falling back to /dev/tun device");
3199 open_tun_generic(dev, dev_type, NULL, true, tt);
3200 }
3201 else
3202 {
3203 /* Specific utun device or generic utun request with no tun
3204 * fall back failed, consider this a fatal failure */
3205 msg(M_FATAL, "Cannot open utun device");
3206 }
3207 }
3208 }
3209 else
3210 #endif /* ifdef HAVE_NET_IF_UTUN_H */
3211 {
3212
3213 /* Use plain dev-node tun to select /dev/tun style
3214 * Unset dev_node variable prior to passing to open_tun_generic to
3215 * let open_tun_generic pick the first available tun device */
3216
3217 if (dev_node && strcmp(dev_node, "tun")==0)
3218 {
3219 dev_node = NULL;
3220 }
3221
3222 open_tun_generic(dev, dev_type, dev_node, true, tt);
3223 }
3224 }
3225
3226 void
close_tun(struct tuntap * tt,openvpn_net_ctx_t * ctx)3227 close_tun(struct tuntap *tt, openvpn_net_ctx_t *ctx)
3228 {
3229 ASSERT(tt);
3230
3231 struct gc_arena gc = gc_new();
3232 struct argv argv = argv_new();
3233
3234 if (tt->did_ifconfig_ipv6_setup)
3235 {
3236 const char *ifconfig_ipv6_local =
3237 print_in6_addr(tt->local_ipv6, 0, &gc);
3238
3239 argv_printf(&argv, "%s delete -inet6 %s",
3240 ROUTE_PATH, ifconfig_ipv6_local );
3241 argv_msg(M_INFO, &argv);
3242 openvpn_execve_check(&argv, NULL, 0, "MacOS X 'remove inet6 route' failed (non-critical)");
3243 }
3244
3245 close_tun_generic(tt);
3246 free(tt);
3247 argv_free(&argv);
3248 gc_free(&gc);
3249 }
3250
3251 int
write_tun(struct tuntap * tt,uint8_t * buf,int len)3252 write_tun(struct tuntap *tt, uint8_t *buf, int len)
3253 {
3254 #ifdef HAVE_NET_IF_UTUN_H
3255 if (tt->is_utun)
3256 {
3257 return write_tun_header(tt, buf, len);
3258 }
3259 else
3260 #endif
3261 return write(tt->fd, buf, len);
3262 }
3263
3264 int
read_tun(struct tuntap * tt,uint8_t * buf,int len)3265 read_tun(struct tuntap *tt, uint8_t *buf, int len)
3266 {
3267 #ifdef HAVE_NET_IF_UTUN_H
3268 if (tt->is_utun)
3269 {
3270 return read_tun_header(tt, buf, len);
3271 }
3272 else
3273 #endif
3274 return read(tt->fd, buf, len);
3275 }
3276
3277 #elif defined(TARGET_AIX)
3278
3279 void
open_tun(const char * dev,const char * dev_type,const char * dev_node,struct tuntap * tt)3280 open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
3281 {
3282 char tunname[256];
3283 char dynamic_name[20];
3284 const char *p;
3285
3286 if (tt->type == DEV_TYPE_NULL)
3287 {
3288 open_null(tt);
3289 return;
3290 }
3291
3292 if (tt->type == DEV_TYPE_TUN)
3293 {
3294 msg(M_FATAL, "no support for 'tun' devices on AIX" );
3295 }
3296
3297 if (strncmp( dev, "tap", 3 ) != 0 || dev_node)
3298 {
3299 msg(M_FATAL, "'--dev %s' and/or '--dev-node' not supported on AIX, use '--dev tap0', 'tap1', etc.", dev );
3300 }
3301
3302 if (strcmp( dev, "tap" ) == 0) /* find first free tap dev */
3303 { /* (= no /dev/tapN node) */
3304 int i;
3305 for (i = 0; i<99; i++)
3306 {
3307 openvpn_snprintf(tunname, sizeof(tunname), "/dev/tap%d", i);
3308 if (access( tunname, F_OK ) < 0 && errno == ENOENT)
3309 {
3310 break;
3311 }
3312 }
3313 if (i >= 99)
3314 {
3315 msg( M_FATAL, "cannot find unused tap device" );
3316 }
3317
3318 openvpn_snprintf( dynamic_name, sizeof(dynamic_name), "tap%d", i );
3319 dev = dynamic_name;
3320 }
3321 else /* name given, sanity check */
3322 {
3323 /* ensure that dev name is "tap+<digits>" *only* */
3324 p = &dev[3];
3325 while (isdigit(*p) )
3326 {
3327 p++;
3328 }
3329 if (*p != '\0')
3330 {
3331 msg( M_FATAL, "TAP device name must be '--dev tapNNNN'" );
3332 }
3333
3334 openvpn_snprintf(tunname, sizeof(tunname), "/dev/%s", dev);
3335 }
3336
3337 /* pre-existing device?
3338 */
3339 if (access( tunname, F_OK ) < 0 && errno == ENOENT)
3340 {
3341
3342 /* tunnel device must be created with 'ifconfig tapN create'
3343 */
3344 struct argv argv = argv_new();
3345 struct env_set *es = env_set_create(NULL);
3346 argv_printf(&argv, "%s %s create", IFCONFIG_PATH, dev);
3347 argv_msg(M_INFO, &argv);
3348 env_set_add( es, "ODMDIR=/etc/objrepos" );
3349 openvpn_execve_check(&argv, es, S_FATAL, "AIX 'create tun interface' failed");
3350 env_set_destroy(es);
3351 argv_free(&argv);
3352 }
3353 else
3354 {
3355 /* we didn't make it, we're not going to break it */
3356 tt->persistent_if = TRUE;
3357 }
3358
3359 if ((tt->fd = open(tunname, O_RDWR)) < 0)
3360 {
3361 msg(M_ERR, "Cannot open TAP device '%s'", tunname);
3362 }
3363
3364 set_nonblock(tt->fd);
3365 set_cloexec(tt->fd); /* don't pass fd to scripts */
3366 msg(M_INFO, "TUN/TAP device %s opened", tunname);
3367
3368 /* tt->actual_name is passed to up and down scripts and used as the ifconfig dev name */
3369 tt->actual_name = string_alloc(dev, NULL);
3370 }
3371
3372 /* tap devices need to be manually destroyed on AIX
3373 */
3374 void
close_tun(struct tuntap * tt,openvpn_net_ctx_t * ctx)3375 close_tun(struct tuntap *tt, openvpn_net_ctx_t *ctx)
3376 {
3377 ASSERT(tt);
3378
3379 struct argv argv = argv_new();
3380 struct env_set *es = env_set_create(NULL);
3381
3382 /* persistent devices need IP address unconfig, others need destroyal
3383 */
3384 if (tt->persistent_if)
3385 {
3386 argv_printf(&argv, "%s %s 0.0.0.0 down",
3387 IFCONFIG_PATH, tt->actual_name);
3388 }
3389 else
3390 {
3391 argv_printf(&argv, "%s %s destroy",
3392 IFCONFIG_PATH, tt->actual_name);
3393 }
3394
3395 close_tun_generic(tt);
3396 argv_msg(M_INFO, &argv);
3397 env_set_add( es, "ODMDIR=/etc/objrepos" );
3398 openvpn_execve_check(&argv, es, 0, "AIX 'destroy tap interface' failed (non-critical)");
3399
3400 free(tt);
3401 env_set_destroy(es);
3402 argv_free(&argv);
3403 }
3404
3405 int
write_tun(struct tuntap * tt,uint8_t * buf,int len)3406 write_tun(struct tuntap *tt, uint8_t *buf, int len)
3407 {
3408 return write(tt->fd, buf, len);
3409 }
3410
3411 int
read_tun(struct tuntap * tt,uint8_t * buf,int len)3412 read_tun(struct tuntap *tt, uint8_t *buf, int len)
3413 {
3414 return read(tt->fd, buf, len);
3415 }
3416
3417 #elif defined(_WIN32)
3418
3419 static const char *
print_windows_driver(enum windows_driver_type windows_driver)3420 print_windows_driver(enum windows_driver_type windows_driver)
3421 {
3422 switch (windows_driver)
3423 {
3424 case WINDOWS_DRIVER_TAP_WINDOWS6:
3425 return "tap-windows6";
3426
3427 case WINDOWS_DRIVER_WINTUN:
3428 return "wintun";
3429
3430 default:
3431 return "unspecified";
3432 }
3433 }
3434
3435 int
tun_read_queue(struct tuntap * tt,int maxsize)3436 tun_read_queue(struct tuntap *tt, int maxsize)
3437 {
3438 if (tt->reads.iostate == IOSTATE_INITIAL)
3439 {
3440 DWORD len;
3441 BOOL status;
3442 int err;
3443
3444 /* reset buf to its initial state */
3445 tt->reads.buf = tt->reads.buf_init;
3446
3447 len = maxsize ? maxsize : BLEN(&tt->reads.buf);
3448 ASSERT(len <= BLEN(&tt->reads.buf));
3449
3450 /* the overlapped read will signal this event on I/O completion */
3451 ASSERT(ResetEvent(tt->reads.overlapped.hEvent));
3452
3453 status = ReadFile(
3454 tt->hand,
3455 BPTR(&tt->reads.buf),
3456 len,
3457 &tt->reads.size,
3458 &tt->reads.overlapped
3459 );
3460
3461 if (status) /* operation completed immediately? */
3462 {
3463 /* since we got an immediate return, we must signal the event object ourselves */
3464 ASSERT(SetEvent(tt->reads.overlapped.hEvent));
3465
3466 tt->reads.iostate = IOSTATE_IMMEDIATE_RETURN;
3467 tt->reads.status = 0;
3468
3469 dmsg(D_WIN32_IO, "WIN32 I/O: TAP Read immediate return [%d,%d]",
3470 (int) len,
3471 (int) tt->reads.size);
3472 }
3473 else
3474 {
3475 err = GetLastError();
3476 if (err == ERROR_IO_PENDING) /* operation queued? */
3477 {
3478 tt->reads.iostate = IOSTATE_QUEUED;
3479 tt->reads.status = err;
3480 dmsg(D_WIN32_IO, "WIN32 I/O: TAP Read queued [%d]",
3481 (int) len);
3482 }
3483 else /* error occurred */
3484 {
3485 struct gc_arena gc = gc_new();
3486 ASSERT(SetEvent(tt->reads.overlapped.hEvent));
3487 tt->reads.iostate = IOSTATE_IMMEDIATE_RETURN;
3488 tt->reads.status = err;
3489 dmsg(D_WIN32_IO, "WIN32 I/O: TAP Read error [%d] : %s",
3490 (int) len,
3491 strerror_win32(status, &gc));
3492 gc_free(&gc);
3493 }
3494 }
3495 }
3496 return tt->reads.iostate;
3497 }
3498
3499 int
tun_write_queue(struct tuntap * tt,struct buffer * buf)3500 tun_write_queue(struct tuntap *tt, struct buffer *buf)
3501 {
3502 if (tt->writes.iostate == IOSTATE_INITIAL)
3503 {
3504 BOOL status;
3505 int err;
3506
3507 /* make a private copy of buf */
3508 tt->writes.buf = tt->writes.buf_init;
3509 tt->writes.buf.len = 0;
3510 ASSERT(buf_copy(&tt->writes.buf, buf));
3511
3512 /* the overlapped write will signal this event on I/O completion */
3513 ASSERT(ResetEvent(tt->writes.overlapped.hEvent));
3514
3515 status = WriteFile(
3516 tt->hand,
3517 BPTR(&tt->writes.buf),
3518 BLEN(&tt->writes.buf),
3519 &tt->writes.size,
3520 &tt->writes.overlapped
3521 );
3522
3523 if (status) /* operation completed immediately? */
3524 {
3525 tt->writes.iostate = IOSTATE_IMMEDIATE_RETURN;
3526
3527 /* since we got an immediate return, we must signal the event object ourselves */
3528 ASSERT(SetEvent(tt->writes.overlapped.hEvent));
3529
3530 tt->writes.status = 0;
3531
3532 dmsg(D_WIN32_IO, "WIN32 I/O: TAP Write immediate return [%d,%d]",
3533 BLEN(&tt->writes.buf),
3534 (int) tt->writes.size);
3535 }
3536 else
3537 {
3538 err = GetLastError();
3539 if (err == ERROR_IO_PENDING) /* operation queued? */
3540 {
3541 tt->writes.iostate = IOSTATE_QUEUED;
3542 tt->writes.status = err;
3543 dmsg(D_WIN32_IO, "WIN32 I/O: TAP Write queued [%d]",
3544 BLEN(&tt->writes.buf));
3545 }
3546 else /* error occurred */
3547 {
3548 struct gc_arena gc = gc_new();
3549 ASSERT(SetEvent(tt->writes.overlapped.hEvent));
3550 tt->writes.iostate = IOSTATE_IMMEDIATE_RETURN;
3551 tt->writes.status = err;
3552 dmsg(D_WIN32_IO, "WIN32 I/O: TAP Write error [%d] : %s",
3553 BLEN(&tt->writes.buf),
3554 strerror_win32(err, &gc));
3555 gc_free(&gc);
3556 }
3557 }
3558 }
3559 return tt->writes.iostate;
3560 }
3561
3562 int
tun_finalize(HANDLE h,struct overlapped_io * io,struct buffer * buf)3563 tun_finalize(
3564 HANDLE h,
3565 struct overlapped_io *io,
3566 struct buffer *buf)
3567 {
3568 int ret = -1;
3569 BOOL status;
3570
3571 switch (io->iostate)
3572 {
3573 case IOSTATE_QUEUED:
3574 status = GetOverlappedResult(
3575 h,
3576 &io->overlapped,
3577 &io->size,
3578 FALSE
3579 );
3580 if (status)
3581 {
3582 /* successful return for a queued operation */
3583 if (buf)
3584 {
3585 *buf = io->buf;
3586 }
3587 ret = io->size;
3588 io->iostate = IOSTATE_INITIAL;
3589 ASSERT(ResetEvent(io->overlapped.hEvent));
3590 dmsg(D_WIN32_IO, "WIN32 I/O: TAP Completion success [%d]", ret);
3591 }
3592 else
3593 {
3594 /* error during a queued operation */
3595 ret = -1;
3596 if (GetLastError() != ERROR_IO_INCOMPLETE)
3597 {
3598 /* if no error (i.e. just not finished yet),
3599 * then DON'T execute this code */
3600 io->iostate = IOSTATE_INITIAL;
3601 ASSERT(ResetEvent(io->overlapped.hEvent));
3602 msg(D_WIN32_IO | M_ERRNO, "WIN32 I/O: TAP Completion error");
3603 }
3604 }
3605 break;
3606
3607 case IOSTATE_IMMEDIATE_RETURN:
3608 io->iostate = IOSTATE_INITIAL;
3609 ASSERT(ResetEvent(io->overlapped.hEvent));
3610 if (io->status)
3611 {
3612 /* error return for a non-queued operation */
3613 SetLastError(io->status);
3614 ret = -1;
3615 msg(D_WIN32_IO | M_ERRNO, "WIN32 I/O: TAP Completion non-queued error");
3616 }
3617 else
3618 {
3619 /* successful return for a non-queued operation */
3620 if (buf)
3621 {
3622 *buf = io->buf;
3623 }
3624 ret = io->size;
3625 dmsg(D_WIN32_IO, "WIN32 I/O: TAP Completion non-queued success [%d]", ret);
3626 }
3627 break;
3628
3629 case IOSTATE_INITIAL: /* were we called without proper queueing? */
3630 SetLastError(ERROR_INVALID_FUNCTION);
3631 ret = -1;
3632 dmsg(D_WIN32_IO, "WIN32 I/O: TAP Completion BAD STATE");
3633 break;
3634
3635 default:
3636 ASSERT(0);
3637 }
3638
3639 if (buf)
3640 {
3641 buf->len = ret;
3642 }
3643 return ret;
3644 }
3645
3646 static const struct device_instance_id_interface *
get_device_instance_id_interface(struct gc_arena * gc)3647 get_device_instance_id_interface(struct gc_arena *gc)
3648 {
3649 HDEVINFO dev_info_set;
3650 DWORD err;
3651 struct device_instance_id_interface *first = NULL;
3652 struct device_instance_id_interface *last = NULL;
3653
3654 dev_info_set = SetupDiGetClassDevsEx(&GUID_DEVCLASS_NET, NULL, NULL, DIGCF_PRESENT, NULL, NULL, NULL);
3655 if (dev_info_set == INVALID_HANDLE_VALUE)
3656 {
3657 err = GetLastError();
3658 msg(M_FATAL, "Error [%u] opening device information set key: %s", (unsigned int)err, strerror_win32(err, gc));
3659 }
3660
3661 for (DWORD i = 0;; ++i)
3662 {
3663 SP_DEVINFO_DATA device_info_data;
3664 BOOL res;
3665 HKEY dev_key;
3666 char net_cfg_instance_id_string[] = "NetCfgInstanceId";
3667 char net_cfg_instance_id[256];
3668 char device_instance_id[256];
3669 DWORD len;
3670 DWORD data_type;
3671 LONG status;
3672 ULONG dev_interface_list_size;
3673 CONFIGRET cr;
3674 struct buffer dev_interface_list;
3675
3676 ZeroMemory(&device_info_data, sizeof(SP_DEVINFO_DATA));
3677 device_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
3678 res = SetupDiEnumDeviceInfo(dev_info_set, i, &device_info_data);
3679 if (!res)
3680 {
3681 if (GetLastError() == ERROR_NO_MORE_ITEMS)
3682 {
3683 break;
3684 }
3685 else
3686 {
3687 continue;
3688 }
3689 }
3690
3691 dev_key = SetupDiOpenDevRegKey(dev_info_set, &device_info_data, DICS_FLAG_GLOBAL, 0, DIREG_DRV, KEY_QUERY_VALUE);
3692 if (dev_key == INVALID_HANDLE_VALUE)
3693 {
3694 continue;
3695 }
3696
3697 len = sizeof(net_cfg_instance_id);
3698 data_type = REG_SZ;
3699 status = RegQueryValueEx(dev_key,
3700 net_cfg_instance_id_string,
3701 NULL,
3702 &data_type,
3703 net_cfg_instance_id,
3704 &len);
3705 if (status != ERROR_SUCCESS)
3706 {
3707 goto next;
3708 }
3709
3710 len = sizeof(device_instance_id);
3711 res = SetupDiGetDeviceInstanceId(dev_info_set, &device_info_data, device_instance_id, len, &len);
3712 if (!res)
3713 {
3714 goto next;
3715 }
3716
3717 cr = CM_Get_Device_Interface_List_Size(&dev_interface_list_size,
3718 (LPGUID)&GUID_DEVINTERFACE_NET,
3719 device_instance_id,
3720 CM_GET_DEVICE_INTERFACE_LIST_PRESENT);
3721
3722 if (cr != CR_SUCCESS)
3723 {
3724 goto next;
3725 }
3726
3727 dev_interface_list = alloc_buf_gc(dev_interface_list_size, gc);
3728 cr = CM_Get_Device_Interface_List((LPGUID)&GUID_DEVINTERFACE_NET, device_instance_id,
3729 BPTR(&dev_interface_list),
3730 dev_interface_list_size,
3731 CM_GET_DEVICE_INTERFACE_LIST_PRESENT);
3732 if (cr != CR_SUCCESS)
3733 {
3734 goto next;
3735 }
3736
3737 struct device_instance_id_interface *dev_if;
3738 ALLOC_OBJ_CLEAR_GC(dev_if, struct device_instance_id_interface, gc);
3739 dev_if->net_cfg_instance_id = string_alloc(net_cfg_instance_id, gc);
3740 dev_if->device_interface_list = string_alloc(BSTR(&dev_interface_list), gc);
3741
3742 /* link into return list */
3743 if (!first)
3744 {
3745 first = dev_if;
3746 }
3747 if (last)
3748 {
3749 last->next = dev_if;
3750 }
3751 last = dev_if;
3752
3753 next:
3754 RegCloseKey(dev_key);
3755 }
3756
3757 SetupDiDestroyDeviceInfoList(dev_info_set);
3758
3759 return first;
3760 }
3761
3762 static const struct tap_reg *
get_tap_reg(struct gc_arena * gc)3763 get_tap_reg(struct gc_arena *gc)
3764 {
3765 HKEY adapter_key;
3766 LONG status;
3767 DWORD len;
3768 struct tap_reg *first = NULL;
3769 struct tap_reg *last = NULL;
3770 int i = 0;
3771
3772 status = RegOpenKeyEx(
3773 HKEY_LOCAL_MACHINE,
3774 ADAPTER_KEY,
3775 0,
3776 KEY_READ,
3777 &adapter_key);
3778
3779 if (status != ERROR_SUCCESS)
3780 {
3781 msg(M_FATAL, "Error opening registry key: %s", ADAPTER_KEY);
3782 }
3783
3784 while (true)
3785 {
3786 char enum_name[256];
3787 char unit_string[256];
3788 HKEY unit_key;
3789 char component_id_string[] = "ComponentId";
3790 char component_id[256];
3791 char net_cfg_instance_id_string[] = "NetCfgInstanceId";
3792 char net_cfg_instance_id[256];
3793 DWORD data_type;
3794
3795 len = sizeof(enum_name);
3796 status = RegEnumKeyEx(
3797 adapter_key,
3798 i,
3799 enum_name,
3800 &len,
3801 NULL,
3802 NULL,
3803 NULL,
3804 NULL);
3805 if (status == ERROR_NO_MORE_ITEMS)
3806 {
3807 break;
3808 }
3809 else if (status != ERROR_SUCCESS)
3810 {
3811 msg(M_FATAL, "Error enumerating registry subkeys of key: %s",
3812 ADAPTER_KEY);
3813 }
3814
3815 openvpn_snprintf(unit_string, sizeof(unit_string), "%s\\%s",
3816 ADAPTER_KEY, enum_name);
3817
3818 status = RegOpenKeyEx(
3819 HKEY_LOCAL_MACHINE,
3820 unit_string,
3821 0,
3822 KEY_READ,
3823 &unit_key);
3824
3825 if (status != ERROR_SUCCESS)
3826 {
3827 dmsg(D_REGISTRY, "Error opening registry key: %s", unit_string);
3828 }
3829 else
3830 {
3831 len = sizeof(component_id);
3832 status = RegQueryValueEx(
3833 unit_key,
3834 component_id_string,
3835 NULL,
3836 &data_type,
3837 component_id,
3838 &len);
3839
3840 if (status != ERROR_SUCCESS || data_type != REG_SZ)
3841 {
3842 dmsg(D_REGISTRY, "Error opening registry key: %s\\%s",
3843 unit_string, component_id_string);
3844 }
3845 else
3846 {
3847 len = sizeof(net_cfg_instance_id);
3848 status = RegQueryValueEx(
3849 unit_key,
3850 net_cfg_instance_id_string,
3851 NULL,
3852 &data_type,
3853 net_cfg_instance_id,
3854 &len);
3855
3856 if (status == ERROR_SUCCESS && data_type == REG_SZ)
3857 {
3858 /* Is this adapter supported? */
3859 enum windows_driver_type windows_driver = WINDOWS_DRIVER_UNSPECIFIED;
3860 if (strcasecmp(component_id, TAP_WIN_COMPONENT_ID) == 0
3861 || strcasecmp(component_id, "root\\" TAP_WIN_COMPONENT_ID) == 0)
3862 {
3863 windows_driver = WINDOWS_DRIVER_TAP_WINDOWS6;
3864 }
3865 else if (strcasecmp(component_id, WINTUN_COMPONENT_ID) == 0)
3866 {
3867 windows_driver = WINDOWS_DRIVER_WINTUN;
3868 }
3869
3870 if (windows_driver != WINDOWS_DRIVER_UNSPECIFIED)
3871 {
3872 struct tap_reg *reg;
3873 ALLOC_OBJ_CLEAR_GC(reg, struct tap_reg, gc);
3874 reg->guid = string_alloc(net_cfg_instance_id, gc);
3875 reg->windows_driver = windows_driver;
3876
3877 /* link into return list */
3878 if (!first)
3879 {
3880 first = reg;
3881 }
3882 if (last)
3883 {
3884 last->next = reg;
3885 }
3886 last = reg;
3887 }
3888 }
3889 }
3890 RegCloseKey(unit_key);
3891 }
3892 ++i;
3893 }
3894
3895 RegCloseKey(adapter_key);
3896 return first;
3897 }
3898
3899 static const struct panel_reg *
get_panel_reg(struct gc_arena * gc)3900 get_panel_reg(struct gc_arena *gc)
3901 {
3902 LONG status;
3903 HKEY network_connections_key;
3904 DWORD len;
3905 struct panel_reg *first = NULL;
3906 struct panel_reg *last = NULL;
3907 int i = 0;
3908
3909 status = RegOpenKeyEx(
3910 HKEY_LOCAL_MACHINE,
3911 NETWORK_CONNECTIONS_KEY,
3912 0,
3913 KEY_READ,
3914 &network_connections_key);
3915
3916 if (status != ERROR_SUCCESS)
3917 {
3918 msg(M_FATAL, "Error opening registry key: %s", NETWORK_CONNECTIONS_KEY);
3919 }
3920
3921 while (true)
3922 {
3923 char enum_name[256];
3924 char connection_string[256];
3925 HKEY connection_key;
3926 WCHAR name_data[256];
3927 DWORD name_type;
3928 const WCHAR name_string[] = L"Name";
3929
3930 len = sizeof(enum_name);
3931 status = RegEnumKeyEx(
3932 network_connections_key,
3933 i,
3934 enum_name,
3935 &len,
3936 NULL,
3937 NULL,
3938 NULL,
3939 NULL);
3940 if (status == ERROR_NO_MORE_ITEMS)
3941 {
3942 break;
3943 }
3944 else if (status != ERROR_SUCCESS)
3945 {
3946 msg(M_FATAL, "Error enumerating registry subkeys of key: %s",
3947 NETWORK_CONNECTIONS_KEY);
3948 }
3949
3950 openvpn_snprintf(connection_string, sizeof(connection_string),
3951 "%s\\%s\\Connection",
3952 NETWORK_CONNECTIONS_KEY, enum_name);
3953
3954 status = RegOpenKeyEx(
3955 HKEY_LOCAL_MACHINE,
3956 connection_string,
3957 0,
3958 KEY_READ,
3959 &connection_key);
3960
3961 if (status != ERROR_SUCCESS)
3962 {
3963 dmsg(D_REGISTRY, "Error opening registry key: %s", connection_string);
3964 }
3965 else
3966 {
3967 len = sizeof(name_data);
3968 status = RegQueryValueExW(
3969 connection_key,
3970 name_string,
3971 NULL,
3972 &name_type,
3973 (LPBYTE) name_data,
3974 &len);
3975
3976 if (status != ERROR_SUCCESS || name_type != REG_SZ)
3977 {
3978 dmsg(D_REGISTRY, "Error opening registry key: %s\\%s\\%ls",
3979 NETWORK_CONNECTIONS_KEY, connection_string, name_string);
3980 }
3981 else
3982 {
3983 int n;
3984 LPSTR name;
3985 struct panel_reg *reg;
3986
3987 ALLOC_OBJ_CLEAR_GC(reg, struct panel_reg, gc);
3988 n = WideCharToMultiByte(CP_UTF8, 0, name_data, -1, NULL, 0, NULL, NULL);
3989 name = gc_malloc(n, false, gc);
3990 WideCharToMultiByte(CP_UTF8, 0, name_data, -1, name, n, NULL, NULL);
3991 reg->name = name;
3992 reg->guid = string_alloc(enum_name, gc);
3993
3994 /* link into return list */
3995 if (!first)
3996 {
3997 first = reg;
3998 }
3999 if (last)
4000 {
4001 last->next = reg;
4002 }
4003 last = reg;
4004 }
4005 RegCloseKey(connection_key);
4006 }
4007 ++i;
4008 }
4009
4010 RegCloseKey(network_connections_key);
4011
4012 return first;
4013 }
4014
4015 /*
4016 * Check that two addresses are part of the same 255.255.255.252 subnet.
4017 */
4018 void
verify_255_255_255_252(in_addr_t local,in_addr_t remote)4019 verify_255_255_255_252(in_addr_t local, in_addr_t remote)
4020 {
4021 struct gc_arena gc = gc_new();
4022 const unsigned int mask = 3;
4023 const char *err = NULL;
4024
4025 if (local == remote)
4026 {
4027 err = "must be different";
4028 goto error;
4029 }
4030 if ((local & (~mask)) != (remote & (~mask)))
4031 {
4032 err = "must exist within the same 255.255.255.252 subnet. This is a limitation of --dev tun when used with the TAP-WIN32 driver";
4033 goto error;
4034 }
4035 if ((local & mask) == 0
4036 || (local & mask) == 3
4037 || (remote & mask) == 0
4038 || (remote & mask) == 3)
4039 {
4040 err = "cannot use the first or last address within a given 255.255.255.252 subnet. This is a limitation of --dev tun when used with the TAP-WIN32 driver";
4041 goto error;
4042 }
4043
4044 gc_free(&gc);
4045 return;
4046
4047 error:
4048 msg(M_FATAL, "There is a problem in your selection of --ifconfig endpoints [local=%s, remote=%s]. The local and remote VPN endpoints %s. Try '" PACKAGE " --show-valid-subnets' option for more info.",
4049 print_in_addr_t(local, 0, &gc),
4050 print_in_addr_t(remote, 0, &gc),
4051 err);
4052 gc_free(&gc);
4053 }
4054
4055 void
show_valid_win32_tun_subnets(void)4056 show_valid_win32_tun_subnets(void)
4057 {
4058 int i;
4059 int col = 0;
4060
4061 printf("On Windows, point-to-point IP support (i.e. --dev tun)\n");
4062 printf("is emulated by the TAP-Windows driver. The major limitation\n");
4063 printf("imposed by this approach is that the --ifconfig local and\n");
4064 printf("remote endpoints must be part of the same 255.255.255.252\n");
4065 printf("subnet. The following list shows examples of endpoint\n");
4066 printf("pairs which satisfy this requirement. Only the final\n");
4067 printf("component of the IP address pairs is at issue.\n\n");
4068 printf("As an example, the following option would be correct:\n");
4069 printf(" --ifconfig 10.7.0.5 10.7.0.6 (on host A)\n");
4070 printf(" --ifconfig 10.7.0.6 10.7.0.5 (on host B)\n");
4071 printf("because [5,6] is part of the below list.\n\n");
4072
4073 for (i = 0; i < 256; i += 4)
4074 {
4075 printf("[%3d,%3d] ", i+1, i+2);
4076 if (++col > 4)
4077 {
4078 col = 0;
4079 printf("\n");
4080 }
4081 }
4082 if (col)
4083 {
4084 printf("\n");
4085 }
4086 }
4087
4088 void
show_tap_win_adapters(int msglev,int warnlev)4089 show_tap_win_adapters(int msglev, int warnlev)
4090 {
4091 struct gc_arena gc = gc_new();
4092
4093 bool warn_panel_null = false;
4094 bool warn_panel_dup = false;
4095 bool warn_tap_dup = false;
4096
4097 int links;
4098
4099 const struct tap_reg *tr;
4100 const struct tap_reg *tr1;
4101 const struct panel_reg *pr;
4102
4103 const struct tap_reg *tap_reg = get_tap_reg(&gc);
4104 const struct panel_reg *panel_reg = get_panel_reg(&gc);
4105
4106 msg(msglev, "Available TAP-WIN32 / Wintun adapters [name, GUID, driver]:");
4107
4108 /* loop through each TAP-Windows adapter registry entry */
4109 for (tr = tap_reg; tr != NULL; tr = tr->next)
4110 {
4111 links = 0;
4112
4113 /* loop through each network connections entry in the control panel */
4114 for (pr = panel_reg; pr != NULL; pr = pr->next)
4115 {
4116 if (!strcmp(tr->guid, pr->guid))
4117 {
4118 msg(msglev, "'%s' %s %s", pr->name, tr->guid, print_windows_driver(tr->windows_driver));
4119 ++links;
4120 }
4121 }
4122
4123 if (links > 1)
4124 {
4125 warn_panel_dup = true;
4126 }
4127 else if (links == 0)
4128 {
4129 /* a TAP adapter exists without a link from the network
4130 * connections control panel */
4131 warn_panel_null = true;
4132 msg(msglev, "[NULL] %s", tr->guid);
4133 }
4134 }
4135
4136 /* check for TAP-Windows adapter duplicated GUIDs */
4137 for (tr = tap_reg; tr != NULL; tr = tr->next)
4138 {
4139 for (tr1 = tap_reg; tr1 != NULL; tr1 = tr1->next)
4140 {
4141 if (tr != tr1 && !strcmp(tr->guid, tr1->guid))
4142 {
4143 warn_tap_dup = true;
4144 }
4145 }
4146 }
4147
4148 /* warn on registry inconsistencies */
4149 if (warn_tap_dup)
4150 {
4151 msg(warnlev, "WARNING: Some TAP-Windows adapters have duplicate GUIDs");
4152 }
4153
4154 if (warn_panel_dup)
4155 {
4156 msg(warnlev, "WARNING: Some TAP-Windows adapters have duplicate links from the Network Connections control panel");
4157 }
4158
4159 if (warn_panel_null)
4160 {
4161 msg(warnlev, "WARNING: Some TAP-Windows adapters have no link from the Network Connections control panel");
4162 }
4163
4164 gc_free(&gc);
4165 }
4166
4167 /*
4168 * Lookup a TAP-Windows or Wintun adapter by GUID.
4169 */
4170 static const struct tap_reg *
get_adapter_by_guid(const char * guid,const struct tap_reg * tap_reg)4171 get_adapter_by_guid(const char *guid, const struct tap_reg *tap_reg)
4172 {
4173 const struct tap_reg *tr;
4174
4175 for (tr = tap_reg; tr != NULL; tr = tr->next)
4176 {
4177 if (guid && !strcmp(tr->guid, guid))
4178 {
4179 return tr;
4180 }
4181 }
4182
4183 return NULL;
4184 }
4185
4186 static const char *
guid_to_name(const char * guid,const struct panel_reg * panel_reg)4187 guid_to_name(const char *guid, const struct panel_reg *panel_reg)
4188 {
4189 const struct panel_reg *pr;
4190
4191 for (pr = panel_reg; pr != NULL; pr = pr->next)
4192 {
4193 if (guid && !strcmp(pr->guid, guid))
4194 {
4195 return pr->name;
4196 }
4197 }
4198
4199 return NULL;
4200 }
4201
4202 static const struct tap_reg *
get_adapter_by_name(const char * name,const struct tap_reg * tap_reg,const struct panel_reg * panel_reg)4203 get_adapter_by_name(const char *name, const struct tap_reg *tap_reg, const struct panel_reg *panel_reg)
4204 {
4205 const struct panel_reg *pr;
4206
4207 for (pr = panel_reg; pr != NULL; pr = pr->next)
4208 {
4209 if (name && !strcmp(pr->name, name))
4210 {
4211 return get_adapter_by_guid(pr->guid, tap_reg);
4212 }
4213 }
4214
4215 return NULL;
4216 }
4217
4218 static void
at_least_one_tap_win(const struct tap_reg * tap_reg)4219 at_least_one_tap_win(const struct tap_reg *tap_reg)
4220 {
4221 if (!tap_reg)
4222 {
4223 msg(M_FATAL, "There are no TAP-Windows nor Wintun adapters on this system. You should be able to create an adapter by using tapctl.exe utility.");
4224 }
4225 }
4226
4227 /*
4228 * Get an adapter GUID and optional actual_name from the
4229 * registry for the TAP device # = device_number.
4230 */
4231 static const char *
get_unspecified_device_guid(const int device_number,char * actual_name,int actual_name_size,const struct tap_reg * tap_reg_src,const struct panel_reg * panel_reg_src,enum windows_driver_type * windows_driver,struct gc_arena * gc)4232 get_unspecified_device_guid(const int device_number,
4233 char *actual_name,
4234 int actual_name_size,
4235 const struct tap_reg *tap_reg_src,
4236 const struct panel_reg *panel_reg_src,
4237 enum windows_driver_type *windows_driver,
4238 struct gc_arena *gc)
4239 {
4240 const struct tap_reg *tap_reg = tap_reg_src;
4241 struct buffer ret = clear_buf();
4242 struct buffer actual = clear_buf();
4243 int i;
4244
4245 ASSERT(device_number >= 0);
4246
4247 /* Make sure we have at least one TAP adapter */
4248 if (!tap_reg)
4249 {
4250 return NULL;
4251 }
4252
4253 /* The actual_name output buffer may be NULL */
4254 if (actual_name)
4255 {
4256 ASSERT(actual_name_size > 0);
4257 buf_set_write(&actual, actual_name, actual_name_size);
4258 }
4259
4260 /* Move on to specified device number */
4261 for (i = 0; i < device_number; i++)
4262 {
4263 tap_reg = tap_reg->next;
4264 if (!tap_reg)
4265 {
4266 return NULL;
4267 }
4268 }
4269
4270 /* Save Network Panel name (if exists) in actual_name */
4271 if (actual_name)
4272 {
4273 const char *act = guid_to_name(tap_reg->guid, panel_reg_src);
4274 if (act)
4275 {
4276 buf_printf(&actual, "%s", act);
4277 }
4278 else
4279 {
4280 buf_printf(&actual, "%s", tap_reg->guid);
4281 }
4282 }
4283
4284 /* Save GUID for return value */
4285 ret = alloc_buf_gc(256, gc);
4286 buf_printf(&ret, "%s", tap_reg->guid);
4287 if (windows_driver != NULL)
4288 {
4289 *windows_driver = tap_reg->windows_driver;
4290 }
4291 return BSTR(&ret);
4292 }
4293
4294 /*
4295 * Lookup a --dev-node adapter name in the registry
4296 * returning the GUID and optional actual_name and device type
4297 */
4298 static const char *
get_device_guid(const char * name,char * actual_name,int actual_name_size,enum windows_driver_type * windows_driver,const struct tap_reg * tap_reg,const struct panel_reg * panel_reg,struct gc_arena * gc)4299 get_device_guid(const char *name,
4300 char *actual_name,
4301 int actual_name_size,
4302 enum windows_driver_type *windows_driver,
4303 const struct tap_reg *tap_reg,
4304 const struct panel_reg *panel_reg,
4305 struct gc_arena *gc)
4306 {
4307 struct buffer ret = alloc_buf_gc(256, gc);
4308 struct buffer actual = clear_buf();
4309 const struct tap_reg *tr;
4310
4311 /* Make sure we have at least one TAP adapter */
4312 if (!tap_reg)
4313 {
4314 return NULL;
4315 }
4316
4317 /* The actual_name output buffer may be NULL */
4318 if (actual_name)
4319 {
4320 ASSERT(actual_name_size > 0);
4321 buf_set_write(&actual, actual_name, actual_name_size);
4322 }
4323
4324 /* Check if GUID was explicitly specified as --dev-node parameter */
4325 tr = get_adapter_by_guid(name, tap_reg);
4326 if (tr)
4327 {
4328 const char *act = guid_to_name(name, panel_reg);
4329 buf_printf(&ret, "%s", name);
4330 if (act)
4331 {
4332 buf_printf(&actual, "%s", act);
4333 }
4334 else
4335 {
4336 buf_printf(&actual, "%s", name);
4337 }
4338 if (windows_driver)
4339 {
4340 *windows_driver = tr->windows_driver;
4341 }
4342 return BSTR(&ret);
4343 }
4344
4345 /* Lookup TAP adapter in network connections list */
4346 {
4347 tr = get_adapter_by_name(name, tap_reg, panel_reg);
4348 if (tr)
4349 {
4350 buf_printf(&actual, "%s", name);
4351 if (windows_driver)
4352 {
4353 *windows_driver = tr->windows_driver;
4354 }
4355 buf_printf(&ret, "%s", tr->guid);
4356 return BSTR(&ret);
4357 }
4358 }
4359
4360 return NULL;
4361 }
4362
4363 /*
4364 * Get adapter info list
4365 */
4366 const IP_ADAPTER_INFO *
get_adapter_info_list(struct gc_arena * gc)4367 get_adapter_info_list(struct gc_arena *gc)
4368 {
4369 ULONG size = 0;
4370 IP_ADAPTER_INFO *pi = NULL;
4371 DWORD status;
4372
4373 if ((status = GetAdaptersInfo(NULL, &size)) != ERROR_BUFFER_OVERFLOW)
4374 {
4375 msg(M_INFO, "GetAdaptersInfo #1 failed (status=%u) : %s",
4376 (unsigned int)status,
4377 strerror_win32(status, gc));
4378 }
4379 else
4380 {
4381 pi = (PIP_ADAPTER_INFO) gc_malloc(size, false, gc);
4382 if ((status = GetAdaptersInfo(pi, &size)) != NO_ERROR)
4383 {
4384 msg(M_INFO, "GetAdaptersInfo #2 failed (status=%u) : %s",
4385 (unsigned int)status,
4386 strerror_win32(status, gc));
4387 pi = NULL;
4388 }
4389 }
4390 return pi;
4391 }
4392
4393 const IP_PER_ADAPTER_INFO *
get_per_adapter_info(const DWORD index,struct gc_arena * gc)4394 get_per_adapter_info(const DWORD index, struct gc_arena *gc)
4395 {
4396 ULONG size = 0;
4397 IP_PER_ADAPTER_INFO *pi = NULL;
4398 DWORD status;
4399
4400 if (index != TUN_ADAPTER_INDEX_INVALID)
4401 {
4402 if ((status = GetPerAdapterInfo(index, NULL, &size)) != ERROR_BUFFER_OVERFLOW)
4403 {
4404 msg(M_INFO, "GetPerAdapterInfo #1 failed (status=%u) : %s",
4405 (unsigned int)status,
4406 strerror_win32(status, gc));
4407 }
4408 else
4409 {
4410 pi = (PIP_PER_ADAPTER_INFO) gc_malloc(size, false, gc);
4411 if ((status = GetPerAdapterInfo((ULONG)index, pi, &size)) == ERROR_SUCCESS)
4412 {
4413 return pi;
4414 }
4415 else
4416 {
4417 msg(M_INFO, "GetPerAdapterInfo #2 failed (status=%u) : %s",
4418 (unsigned int)status,
4419 strerror_win32(status, gc));
4420 }
4421 }
4422 }
4423 return pi;
4424 }
4425
4426 static const IP_INTERFACE_INFO *
get_interface_info_list(struct gc_arena * gc)4427 get_interface_info_list(struct gc_arena *gc)
4428 {
4429 ULONG size = 0;
4430 IP_INTERFACE_INFO *ii = NULL;
4431 DWORD status;
4432
4433 if ((status = GetInterfaceInfo(NULL, &size)) != ERROR_INSUFFICIENT_BUFFER)
4434 {
4435 msg(M_INFO, "GetInterfaceInfo #1 failed (status=%u) : %s",
4436 (unsigned int)status,
4437 strerror_win32(status, gc));
4438 }
4439 else
4440 {
4441 ii = (PIP_INTERFACE_INFO) gc_malloc(size, false, gc);
4442 if ((status = GetInterfaceInfo(ii, &size)) == NO_ERROR)
4443 {
4444 return ii;
4445 }
4446 else
4447 {
4448 msg(M_INFO, "GetInterfaceInfo #2 failed (status=%u) : %s",
4449 (unsigned int)status,
4450 strerror_win32(status, gc));
4451 }
4452 }
4453 return ii;
4454 }
4455
4456 static const IP_ADAPTER_INDEX_MAP *
get_interface_info(DWORD index,struct gc_arena * gc)4457 get_interface_info(DWORD index, struct gc_arena *gc)
4458 {
4459 const IP_INTERFACE_INFO *list = get_interface_info_list(gc);
4460 if (list)
4461 {
4462 int i;
4463 for (i = 0; i < list->NumAdapters; ++i)
4464 {
4465 const IP_ADAPTER_INDEX_MAP *inter = &list->Adapter[i];
4466 if (index == inter->Index)
4467 {
4468 return inter;
4469 }
4470 }
4471 }
4472 return NULL;
4473 }
4474
4475 /*
4476 * Given an adapter index, return a pointer to the
4477 * IP_ADAPTER_INFO structure for that adapter.
4478 */
4479
4480 const IP_ADAPTER_INFO *
get_adapter(const IP_ADAPTER_INFO * ai,DWORD index)4481 get_adapter(const IP_ADAPTER_INFO *ai, DWORD index)
4482 {
4483 if (ai && index != TUN_ADAPTER_INDEX_INVALID)
4484 {
4485 const IP_ADAPTER_INFO *a;
4486
4487 /* find index in the linked list */
4488 for (a = ai; a != NULL; a = a->Next)
4489 {
4490 if (a->Index == index)
4491 {
4492 return a;
4493 }
4494 }
4495 }
4496 return NULL;
4497 }
4498
4499 const IP_ADAPTER_INFO *
get_adapter_info(DWORD index,struct gc_arena * gc)4500 get_adapter_info(DWORD index, struct gc_arena *gc)
4501 {
4502 return get_adapter(get_adapter_info_list(gc), index);
4503 }
4504
4505 static int
get_adapter_n_ip_netmask(const IP_ADAPTER_INFO * ai)4506 get_adapter_n_ip_netmask(const IP_ADAPTER_INFO *ai)
4507 {
4508 if (ai)
4509 {
4510 int n = 0;
4511 const IP_ADDR_STRING *ip = &ai->IpAddressList;
4512
4513 while (ip)
4514 {
4515 ++n;
4516 ip = ip->Next;
4517 }
4518 return n;
4519 }
4520 else
4521 {
4522 return 0;
4523 }
4524 }
4525
4526 static bool
get_adapter_ip_netmask(const IP_ADAPTER_INFO * ai,const int n,in_addr_t * ip,in_addr_t * netmask)4527 get_adapter_ip_netmask(const IP_ADAPTER_INFO *ai, const int n, in_addr_t *ip, in_addr_t *netmask)
4528 {
4529 bool ret = false;
4530 *ip = 0;
4531 *netmask = 0;
4532
4533 if (ai)
4534 {
4535 const IP_ADDR_STRING *iplist = &ai->IpAddressList;
4536 int i = 0;
4537
4538 while (iplist)
4539 {
4540 if (i == n)
4541 {
4542 break;
4543 }
4544 ++i;
4545 iplist = iplist->Next;
4546 }
4547
4548 if (iplist)
4549 {
4550 const unsigned int getaddr_flags = GETADDR_HOST_ORDER;
4551 const char *ip_str = iplist->IpAddress.String;
4552 const char *netmask_str = iplist->IpMask.String;
4553 bool succeed1 = false;
4554 bool succeed2 = false;
4555
4556 if (ip_str && netmask_str && strlen(ip_str) && strlen(netmask_str))
4557 {
4558 *ip = getaddr(getaddr_flags, ip_str, 0, &succeed1, NULL);
4559 *netmask = getaddr(getaddr_flags, netmask_str, 0, &succeed2, NULL);
4560 ret = (succeed1 == true && succeed2 == true);
4561 }
4562 }
4563 }
4564
4565 return ret;
4566 }
4567
4568 static bool
test_adapter_ip_netmask(const IP_ADAPTER_INFO * ai,const in_addr_t ip,const in_addr_t netmask)4569 test_adapter_ip_netmask(const IP_ADAPTER_INFO *ai, const in_addr_t ip, const in_addr_t netmask)
4570 {
4571 if (ai)
4572 {
4573 in_addr_t ip_adapter = 0;
4574 in_addr_t netmask_adapter = 0;
4575 const bool status = get_adapter_ip_netmask(ai, 0, &ip_adapter, &netmask_adapter);
4576 return (status && ip_adapter == ip && netmask_adapter == netmask);
4577 }
4578 else
4579 {
4580 return false;
4581 }
4582 }
4583
4584 const IP_ADAPTER_INFO *
get_tun_adapter(const struct tuntap * tt,const IP_ADAPTER_INFO * list)4585 get_tun_adapter(const struct tuntap *tt, const IP_ADAPTER_INFO *list)
4586 {
4587 if (list && tt)
4588 {
4589 return get_adapter(list, tt->adapter_index);
4590 }
4591 else
4592 {
4593 return NULL;
4594 }
4595 }
4596
4597 bool
is_adapter_up(const struct tuntap * tt,const IP_ADAPTER_INFO * list)4598 is_adapter_up(const struct tuntap *tt, const IP_ADAPTER_INFO *list)
4599 {
4600 int i;
4601 bool ret = false;
4602
4603 const IP_ADAPTER_INFO *ai = get_tun_adapter(tt, list);
4604
4605 if (ai)
4606 {
4607 const int n = get_adapter_n_ip_netmask(ai);
4608
4609 /* loop once for every IP/netmask assigned to adapter */
4610 for (i = 0; i < n; ++i)
4611 {
4612 in_addr_t ip, netmask;
4613 if (get_adapter_ip_netmask(ai, i, &ip, &netmask))
4614 {
4615 if (tt->local && tt->adapter_netmask)
4616 {
4617 /* wait for our --ifconfig parms to match the actual adapter parms */
4618 if (tt->local == ip && tt->adapter_netmask == netmask)
4619 {
4620 ret = true;
4621 }
4622 }
4623 else
4624 {
4625 /* --ifconfig was not defined, maybe using a real DHCP server */
4626 if (ip && netmask)
4627 {
4628 ret = true;
4629 }
4630 }
4631 }
4632 }
4633 }
4634 else
4635 {
4636 ret = true; /* this can occur when TAP adapter is bridged */
4637
4638 }
4639 return ret;
4640 }
4641
4642 bool
is_ip_in_adapter_subnet(const IP_ADAPTER_INFO * ai,const in_addr_t ip,in_addr_t * highest_netmask)4643 is_ip_in_adapter_subnet(const IP_ADAPTER_INFO *ai, const in_addr_t ip, in_addr_t *highest_netmask)
4644 {
4645 int i;
4646 bool ret = false;
4647
4648 if (highest_netmask)
4649 {
4650 *highest_netmask = 0;
4651 }
4652
4653 if (ai)
4654 {
4655 const int n = get_adapter_n_ip_netmask(ai);
4656 for (i = 0; i < n; ++i)
4657 {
4658 in_addr_t adapter_ip, adapter_netmask;
4659 if (get_adapter_ip_netmask(ai, i, &adapter_ip, &adapter_netmask))
4660 {
4661 if (adapter_ip && adapter_netmask && (ip & adapter_netmask) == (adapter_ip & adapter_netmask))
4662 {
4663 if (highest_netmask && adapter_netmask > *highest_netmask)
4664 {
4665 *highest_netmask = adapter_netmask;
4666 }
4667 ret = true;
4668 }
4669 }
4670 }
4671 }
4672 return ret;
4673 }
4674
4675 DWORD
adapter_index_of_ip(const IP_ADAPTER_INFO * list,const in_addr_t ip,int * count,in_addr_t * netmask)4676 adapter_index_of_ip(const IP_ADAPTER_INFO *list,
4677 const in_addr_t ip,
4678 int *count,
4679 in_addr_t *netmask)
4680 {
4681 struct gc_arena gc = gc_new();
4682 DWORD ret = TUN_ADAPTER_INDEX_INVALID;
4683 in_addr_t highest_netmask = 0;
4684 int lowest_metric = INT_MAX;
4685 bool first = true;
4686
4687 if (count)
4688 {
4689 *count = 0;
4690 }
4691
4692 while (list)
4693 {
4694 in_addr_t hn;
4695
4696 if (is_ip_in_adapter_subnet(list, ip, &hn))
4697 {
4698 int metric = get_interface_metric(list->Index, AF_INET, NULL);
4699 if (first || hn > highest_netmask)
4700 {
4701 highest_netmask = hn;
4702 if (metric >= 0)
4703 {
4704 lowest_metric = metric;
4705 }
4706 if (count)
4707 {
4708 *count = 1;
4709 }
4710 ret = list->Index;
4711 first = false;
4712 }
4713 else if (hn == highest_netmask)
4714 {
4715 if (count)
4716 {
4717 ++*count;
4718 }
4719 if (metric >= 0 && metric < lowest_metric)
4720 {
4721 ret = list->Index;
4722 lowest_metric = metric;
4723 }
4724 }
4725 }
4726 list = list->Next;
4727 }
4728
4729 dmsg(D_ROUTE_DEBUG, "DEBUG: IP Locate: ip=%s nm=%s index=%d count=%d metric=%d",
4730 print_in_addr_t(ip, 0, &gc),
4731 print_in_addr_t(highest_netmask, 0, &gc),
4732 (int)ret,
4733 count ? *count : -1,
4734 lowest_metric);
4735
4736 if (ret == TUN_ADAPTER_INDEX_INVALID && count)
4737 {
4738 *count = 0;
4739 }
4740
4741 if (netmask)
4742 {
4743 *netmask = highest_netmask;
4744 }
4745
4746 gc_free(&gc);
4747 return ret;
4748 }
4749
4750 /*
4751 * Given an adapter index, return true if the adapter
4752 * is DHCP disabled.
4753 */
4754
4755 #define DHCP_STATUS_UNDEF 0
4756 #define DHCP_STATUS_ENABLED 1
4757 #define DHCP_STATUS_DISABLED 2
4758
4759 static int
dhcp_status(DWORD index)4760 dhcp_status(DWORD index)
4761 {
4762 struct gc_arena gc = gc_new();
4763 int ret = DHCP_STATUS_UNDEF;
4764 if (index != TUN_ADAPTER_INDEX_INVALID)
4765 {
4766 const IP_ADAPTER_INFO *ai = get_adapter_info(index, &gc);
4767
4768 if (ai)
4769 {
4770 if (ai->DhcpEnabled)
4771 {
4772 ret = DHCP_STATUS_ENABLED;
4773 }
4774 else
4775 {
4776 ret = DHCP_STATUS_DISABLED;
4777 }
4778 }
4779 }
4780 gc_free(&gc);
4781 return ret;
4782 }
4783
4784 /*
4785 * Delete all temporary address/netmask pairs which were added
4786 * to adapter (given by index) by previous calls to AddIPAddress.
4787 */
4788 static void
delete_temp_addresses(DWORD index)4789 delete_temp_addresses(DWORD index)
4790 {
4791 struct gc_arena gc = gc_new();
4792 const IP_ADAPTER_INFO *a = get_adapter_info(index, &gc);
4793
4794 if (a)
4795 {
4796 const IP_ADDR_STRING *ip = &a->IpAddressList;
4797 while (ip)
4798 {
4799 DWORD status;
4800 const DWORD context = ip->Context;
4801
4802 if ((status = DeleteIPAddress((ULONG) context)) == NO_ERROR)
4803 {
4804 msg(M_INFO, "Successfully deleted previously set dynamic IP/netmask: %s/%s",
4805 ip->IpAddress.String,
4806 ip->IpMask.String);
4807 }
4808 else
4809 {
4810 const char *empty = "0.0.0.0";
4811 if (strcmp(ip->IpAddress.String, empty)
4812 || strcmp(ip->IpMask.String, empty))
4813 {
4814 msg(M_INFO, "NOTE: could not delete previously set dynamic IP/netmask: %s/%s (status=%u)",
4815 ip->IpAddress.String,
4816 ip->IpMask.String,
4817 (unsigned int)status);
4818 }
4819 }
4820 ip = ip->Next;
4821 }
4822 }
4823 gc_free(&gc);
4824 }
4825
4826 /*
4827 * Get interface index for use with IP Helper API functions.
4828 */
4829 static DWORD
get_adapter_index_method_1(const char * guid)4830 get_adapter_index_method_1(const char *guid)
4831 {
4832 DWORD index;
4833 ULONG aindex;
4834 wchar_t wbuf[256];
4835 openvpn_swprintf(wbuf, SIZE(wbuf), L"\\DEVICE\\TCPIP_%S", guid);
4836 if (GetAdapterIndex(wbuf, &aindex) != NO_ERROR)
4837 {
4838 index = TUN_ADAPTER_INDEX_INVALID;
4839 }
4840 else
4841 {
4842 index = (DWORD)aindex;
4843 }
4844 return index;
4845 }
4846
4847 static DWORD
get_adapter_index_method_2(const char * guid)4848 get_adapter_index_method_2(const char *guid)
4849 {
4850 struct gc_arena gc = gc_new();
4851 DWORD index = TUN_ADAPTER_INDEX_INVALID;
4852
4853 const IP_ADAPTER_INFO *list = get_adapter_info_list(&gc);
4854
4855 while (list)
4856 {
4857 if (!strcmp(guid, list->AdapterName))
4858 {
4859 index = list->Index;
4860 break;
4861 }
4862 list = list->Next;
4863 }
4864
4865 gc_free(&gc);
4866 return index;
4867 }
4868
4869 static DWORD
get_adapter_index(const char * guid)4870 get_adapter_index(const char *guid)
4871 {
4872 DWORD index;
4873 index = get_adapter_index_method_1(guid);
4874 if (index == TUN_ADAPTER_INDEX_INVALID)
4875 {
4876 index = get_adapter_index_method_2(guid);
4877 }
4878 if (index == TUN_ADAPTER_INDEX_INVALID)
4879 {
4880 msg(M_INFO, "NOTE: could not get adapter index for %s", guid);
4881 }
4882 return index;
4883 }
4884
4885 static DWORD
get_adapter_index_flexible(const char * name)4886 get_adapter_index_flexible(const char *name) /* actual name or GUID */
4887 {
4888 struct gc_arena gc = gc_new();
4889 DWORD index;
4890 index = get_adapter_index_method_1(name);
4891 if (index == TUN_ADAPTER_INDEX_INVALID)
4892 {
4893 index = get_adapter_index_method_2(name);
4894 }
4895 if (index == TUN_ADAPTER_INDEX_INVALID)
4896 {
4897 const struct tap_reg *tap_reg = get_tap_reg(&gc);
4898 const struct panel_reg *panel_reg = get_panel_reg(&gc);
4899 const struct tap_reg *tr = get_adapter_by_name(name, tap_reg, panel_reg);
4900 if (tr)
4901 {
4902 index = get_adapter_index_method_1(tr->guid);
4903 if (index == TUN_ADAPTER_INDEX_INVALID)
4904 {
4905 index = get_adapter_index_method_2(tr->guid);
4906 }
4907 }
4908 }
4909 if (index == TUN_ADAPTER_INDEX_INVALID)
4910 {
4911 msg(M_INFO, "NOTE: could not get adapter index for name/GUID '%s'", name);
4912 }
4913 gc_free(&gc);
4914 return index;
4915 }
4916
4917 /*
4918 * Return a string representing a PIP_ADDR_STRING
4919 */
4920 static const char *
format_ip_addr_string(const IP_ADDR_STRING * ip,struct gc_arena * gc)4921 format_ip_addr_string(const IP_ADDR_STRING *ip, struct gc_arena *gc)
4922 {
4923 struct buffer out = alloc_buf_gc(256, gc);
4924 while (ip)
4925 {
4926 buf_printf(&out, "%s", ip->IpAddress.String);
4927 if (strlen(ip->IpMask.String))
4928 {
4929 buf_printf(&out, "/");
4930 buf_printf(&out, "%s", ip->IpMask.String);
4931 }
4932 buf_printf(&out, " ");
4933 ip = ip->Next;
4934 }
4935 return BSTR(&out);
4936 }
4937
4938 /*
4939 * Show info for a single adapter
4940 */
4941 static void
show_adapter(int msglev,const IP_ADAPTER_INFO * a,struct gc_arena * gc)4942 show_adapter(int msglev, const IP_ADAPTER_INFO *a, struct gc_arena *gc)
4943 {
4944 msg(msglev, "%s", a->Description);
4945 msg(msglev, " Index = %d", (int)a->Index);
4946 msg(msglev, " GUID = %s", a->AdapterName);
4947 msg(msglev, " IP = %s", format_ip_addr_string(&a->IpAddressList, gc));
4948 msg(msglev, " MAC = %s", format_hex_ex(a->Address, a->AddressLength, 0, 1, ":", gc));
4949 msg(msglev, " GATEWAY = %s", format_ip_addr_string(&a->GatewayList, gc));
4950 if (a->DhcpEnabled)
4951 {
4952 msg(msglev, " DHCP SERV = %s", format_ip_addr_string(&a->DhcpServer, gc));
4953 msg(msglev, " DHCP LEASE OBTAINED = %s", time_string(a->LeaseObtained, 0, false, gc));
4954 msg(msglev, " DHCP LEASE EXPIRES = %s", time_string(a->LeaseExpires, 0, false, gc));
4955 }
4956 if (a->HaveWins)
4957 {
4958 msg(msglev, " PRI WINS = %s", format_ip_addr_string(&a->PrimaryWinsServer, gc));
4959 msg(msglev, " SEC WINS = %s", format_ip_addr_string(&a->SecondaryWinsServer, gc));
4960 }
4961
4962 {
4963 const IP_PER_ADAPTER_INFO *pai = get_per_adapter_info(a->Index, gc);
4964 if (pai)
4965 {
4966 msg(msglev, " DNS SERV = %s", format_ip_addr_string(&pai->DnsServerList, gc));
4967 }
4968 }
4969 }
4970
4971 /*
4972 * Show current adapter list
4973 */
4974 void
show_adapters(int msglev)4975 show_adapters(int msglev)
4976 {
4977 struct gc_arena gc = gc_new();
4978 const IP_ADAPTER_INFO *ai = get_adapter_info_list(&gc);
4979
4980 msg(msglev, "SYSTEM ADAPTER LIST");
4981 if (ai)
4982 {
4983 const IP_ADAPTER_INFO *a;
4984
4985 /* find index in the linked list */
4986 for (a = ai; a != NULL; a = a->Next)
4987 {
4988 show_adapter(msglev, a, &gc);
4989 }
4990 }
4991 gc_free(&gc);
4992 }
4993
4994 /*
4995 * Set a particular TAP-Windows adapter (or all of them if
4996 * adapter_name == NULL) to allow it to be opened from
4997 * a non-admin account. This setting will only persist
4998 * for the lifetime of the device object.
4999 */
5000
5001 static void
tap_allow_nonadmin_access_handle(const char * device_path,HANDLE hand)5002 tap_allow_nonadmin_access_handle(const char *device_path, HANDLE hand)
5003 {
5004 struct security_attributes sa;
5005 BOOL status;
5006
5007 if (!init_security_attributes_allow_all(&sa))
5008 {
5009 msg(M_ERR, "Error: init SA failed");
5010 }
5011
5012 status = SetKernelObjectSecurity(hand, DACL_SECURITY_INFORMATION, &sa.sd);
5013 if (!status)
5014 {
5015 msg(M_ERRNO, "Error: SetKernelObjectSecurity failed on %s", device_path);
5016 }
5017 else
5018 {
5019 msg(M_INFO|M_NOPREFIX, "TAP-Windows device: %s [Non-admin access allowed]", device_path);
5020 }
5021 }
5022
5023 void
tap_allow_nonadmin_access(const char * dev_node)5024 tap_allow_nonadmin_access(const char *dev_node)
5025 {
5026 struct gc_arena gc = gc_new();
5027 const struct tap_reg *tap_reg = get_tap_reg(&gc);
5028 const struct panel_reg *panel_reg = get_panel_reg(&gc);
5029 const char *device_guid = NULL;
5030 HANDLE hand;
5031 char actual_buffer[256];
5032 char device_path[256];
5033
5034 at_least_one_tap_win(tap_reg);
5035
5036 if (dev_node)
5037 {
5038 /* Get the device GUID for the device specified with --dev-node. */
5039 device_guid = get_device_guid(dev_node, actual_buffer, sizeof(actual_buffer), NULL, tap_reg, panel_reg, &gc);
5040
5041 if (!device_guid)
5042 {
5043 msg(M_FATAL, "TAP-Windows adapter '%s' not found", dev_node);
5044 }
5045
5046 /* Open Windows TAP-Windows adapter */
5047 openvpn_snprintf(device_path, sizeof(device_path), "%s%s%s",
5048 USERMODEDEVICEDIR,
5049 device_guid,
5050 TAP_WIN_SUFFIX);
5051
5052 hand = CreateFile(
5053 device_path,
5054 MAXIMUM_ALLOWED,
5055 0, /* was: FILE_SHARE_READ */
5056 0,
5057 OPEN_EXISTING,
5058 FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
5059 0
5060 );
5061
5062 if (hand == INVALID_HANDLE_VALUE)
5063 {
5064 msg(M_ERR, "CreateFile failed on TAP device: %s", device_path);
5065 }
5066
5067 tap_allow_nonadmin_access_handle(device_path, hand);
5068 CloseHandle(hand);
5069 }
5070 else
5071 {
5072 int device_number = 0;
5073
5074 /* Try opening all TAP devices */
5075 while (true)
5076 {
5077 device_guid = get_unspecified_device_guid(device_number,
5078 actual_buffer,
5079 sizeof(actual_buffer),
5080 tap_reg,
5081 panel_reg,
5082 NULL,
5083 &gc);
5084
5085 if (!device_guid)
5086 {
5087 break;
5088 }
5089
5090 /* Open Windows TAP-Windows adapter */
5091 openvpn_snprintf(device_path, sizeof(device_path), "%s%s%s",
5092 USERMODEDEVICEDIR,
5093 device_guid,
5094 TAP_WIN_SUFFIX);
5095
5096 hand = CreateFile(
5097 device_path,
5098 MAXIMUM_ALLOWED,
5099 0, /* was: FILE_SHARE_READ */
5100 0,
5101 OPEN_EXISTING,
5102 FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
5103 0
5104 );
5105
5106 if (hand == INVALID_HANDLE_VALUE)
5107 {
5108 msg(M_WARN, "CreateFile failed on TAP device: %s", device_path);
5109 }
5110 else
5111 {
5112 tap_allow_nonadmin_access_handle(device_path, hand);
5113 CloseHandle(hand);
5114 }
5115
5116 device_number++;
5117 }
5118 }
5119 gc_free(&gc);
5120 }
5121
5122 /*
5123 * DHCP release/renewal
5124 */
5125 bool
dhcp_release_by_adapter_index(const DWORD adapter_index)5126 dhcp_release_by_adapter_index(const DWORD adapter_index)
5127 {
5128 struct gc_arena gc = gc_new();
5129 bool ret = false;
5130 const IP_ADAPTER_INDEX_MAP *inter = get_interface_info(adapter_index, &gc);
5131
5132 if (inter)
5133 {
5134 DWORD status = IpReleaseAddress((IP_ADAPTER_INDEX_MAP *)inter);
5135 if (status == NO_ERROR)
5136 {
5137 msg(D_TUNTAP_INFO, "TAP: DHCP address released");
5138 ret = true;
5139 }
5140 else
5141 {
5142 msg(M_WARN, "NOTE: Release of DHCP-assigned IP address lease on TAP-Windows adapter failed: %s (code=%u)",
5143 strerror_win32(status, &gc),
5144 (unsigned int)status);
5145 }
5146 }
5147
5148 gc_free(&gc);
5149 return ret;
5150 }
5151
5152 static bool
dhcp_release(const struct tuntap * tt)5153 dhcp_release(const struct tuntap *tt)
5154 {
5155 if (tt && tt->options.ip_win32_type == IPW32_SET_DHCP_MASQ && tt->adapter_index != TUN_ADAPTER_INDEX_INVALID)
5156 {
5157 return dhcp_release_by_adapter_index(tt->adapter_index);
5158 }
5159 else
5160 {
5161 return false;
5162 }
5163 }
5164
5165 bool
dhcp_renew_by_adapter_index(const DWORD adapter_index)5166 dhcp_renew_by_adapter_index(const DWORD adapter_index)
5167 {
5168 struct gc_arena gc = gc_new();
5169 bool ret = false;
5170 const IP_ADAPTER_INDEX_MAP *inter = get_interface_info(adapter_index, &gc);
5171
5172 if (inter)
5173 {
5174 DWORD status = IpRenewAddress((IP_ADAPTER_INDEX_MAP *)inter);
5175 if (status == NO_ERROR)
5176 {
5177 msg(D_TUNTAP_INFO, "TAP: DHCP address renewal succeeded");
5178 ret = true;
5179 }
5180 else
5181 {
5182 msg(M_WARN, "WARNING: Failed to renew DHCP IP address lease on TAP-Windows adapter: %s (code=%u)",
5183 strerror_win32(status, &gc),
5184 (unsigned int)status);
5185 }
5186 }
5187 gc_free(&gc);
5188 return ret;
5189 }
5190
5191 static bool
dhcp_renew(const struct tuntap * tt)5192 dhcp_renew(const struct tuntap *tt)
5193 {
5194 if (tt && tt->options.ip_win32_type == IPW32_SET_DHCP_MASQ && tt->adapter_index != TUN_ADAPTER_INDEX_INVALID)
5195 {
5196 return dhcp_renew_by_adapter_index(tt->adapter_index);
5197 }
5198 else
5199 {
5200 return false;
5201 }
5202 }
5203
5204 /*
5205 * netsh functions
5206 */
5207
5208 static void
netsh_command(const struct argv * a,int n,int msglevel)5209 netsh_command(const struct argv *a, int n, int msglevel)
5210 {
5211 int i;
5212 for (i = 0; i < n; ++i)
5213 {
5214 bool status;
5215 management_sleep(0);
5216 netcmd_semaphore_lock();
5217 argv_msg_prefix(M_INFO, a, "NETSH");
5218 status = openvpn_execve_check(a, NULL, 0, "ERROR: netsh command failed");
5219 netcmd_semaphore_release();
5220 if (status)
5221 {
5222 return;
5223 }
5224 management_sleep(4);
5225 }
5226 msg(msglevel, "NETSH: command failed");
5227 }
5228
5229 void
ipconfig_register_dns(const struct env_set * es)5230 ipconfig_register_dns(const struct env_set *es)
5231 {
5232 struct argv argv = argv_new();
5233 const char err[] = "ERROR: Windows ipconfig command failed";
5234
5235 msg(D_TUNTAP_INFO, "Start ipconfig commands for register-dns...");
5236 netcmd_semaphore_lock();
5237
5238 argv_printf(&argv, "%s%s /flushdns",
5239 get_win_sys_path(),
5240 WIN_IPCONFIG_PATH_SUFFIX);
5241 argv_msg(D_TUNTAP_INFO, &argv);
5242 openvpn_execve_check(&argv, es, 0, err);
5243
5244 argv_printf(&argv, "%s%s /registerdns",
5245 get_win_sys_path(),
5246 WIN_IPCONFIG_PATH_SUFFIX);
5247 argv_msg(D_TUNTAP_INFO, &argv);
5248 openvpn_execve_check(&argv, es, 0, err);
5249 argv_free(&argv);
5250
5251 netcmd_semaphore_release();
5252 msg(D_TUNTAP_INFO, "End ipconfig commands for register-dns...");
5253 }
5254
5255 void
ip_addr_string_to_array(in_addr_t * dest,int * dest_len,const IP_ADDR_STRING * src)5256 ip_addr_string_to_array(in_addr_t *dest, int *dest_len, const IP_ADDR_STRING *src)
5257 {
5258 int i = 0;
5259 while (src)
5260 {
5261 const unsigned int getaddr_flags = GETADDR_HOST_ORDER;
5262 const char *ip_str = src->IpAddress.String;
5263 in_addr_t ip = 0;
5264 bool succeed = false;
5265
5266 if (i >= *dest_len)
5267 {
5268 break;
5269 }
5270 if (!ip_str || !strlen(ip_str))
5271 {
5272 break;
5273 }
5274
5275 ip = getaddr(getaddr_flags, ip_str, 0, &succeed, NULL);
5276 if (!succeed)
5277 {
5278 break;
5279 }
5280 dest[i++] = ip;
5281
5282 src = src->Next;
5283 }
5284 *dest_len = i;
5285
5286 #if 0
5287 {
5288 struct gc_arena gc = gc_new();
5289 msg(M_INFO, "ip_addr_string_to_array [%d]", *dest_len);
5290 for (i = 0; i < *dest_len; ++i)
5291 {
5292 msg(M_INFO, "%s", print_in_addr_t(dest[i], 0, &gc));
5293 }
5294 gc_free(&gc);
5295 }
5296 #endif
5297 }
5298
5299 static bool
ip_addr_one_to_one(const in_addr_t * a1,const int a1len,const IP_ADDR_STRING * ias)5300 ip_addr_one_to_one(const in_addr_t *a1, const int a1len, const IP_ADDR_STRING *ias)
5301 {
5302 in_addr_t a2[8];
5303 int a2len = SIZE(a2);
5304 int i;
5305
5306 ip_addr_string_to_array(a2, &a2len, ias);
5307 /*msg (M_INFO, "a1len=%d a2len=%d", a1len, a2len);*/
5308 if (a1len != a2len)
5309 {
5310 return false;
5311 }
5312
5313 for (i = 0; i < a1len; ++i)
5314 {
5315 if (a1[i] != a2[i])
5316 {
5317 return false;
5318 }
5319 }
5320 return true;
5321 }
5322
5323 static bool
ip_addr_member_of(const in_addr_t addr,const IP_ADDR_STRING * ias)5324 ip_addr_member_of(const in_addr_t addr, const IP_ADDR_STRING *ias)
5325 {
5326 in_addr_t aa[8];
5327 int len = SIZE(aa);
5328 int i;
5329
5330 ip_addr_string_to_array(aa, &len, ias);
5331 for (i = 0; i < len; ++i)
5332 {
5333 if (addr == aa[i])
5334 {
5335 return true;
5336 }
5337 }
5338 return false;
5339 }
5340
5341 /**
5342 * Set the ipv6 dns servers on the specified interface.
5343 * The list of dns servers currently set on the interface
5344 * are cleared first.
5345 */
5346 static void
netsh_set_dns6_servers(const struct in6_addr * addr_list,const int addr_len,DWORD adapter_index)5347 netsh_set_dns6_servers(const struct in6_addr *addr_list,
5348 const int addr_len,
5349 DWORD adapter_index)
5350 {
5351 struct gc_arena gc = gc_new();
5352 struct argv argv = argv_new();
5353
5354 /* delete existing DNS settings from TAP interface */
5355 argv_printf(&argv, "%s%s interface ipv6 delete dns %lu all",
5356 get_win_sys_path(),
5357 NETSH_PATH_SUFFIX,
5358 adapter_index);
5359 netsh_command(&argv, 2, M_FATAL);
5360
5361 for (int i = 0; i < addr_len; ++i)
5362 {
5363 const char *fmt = (i == 0) ?
5364 "%s%s interface ipv6 set dns %lu static %s"
5365 : "%s%s interface ipv6 add dns %lu %s";
5366 argv_printf(&argv, fmt, get_win_sys_path(),
5367 NETSH_PATH_SUFFIX, adapter_index,
5368 print_in6_addr(addr_list[i], 0, &gc));
5369
5370 /* disable slow address validation on Windows 7 and higher */
5371 if (win32_version_info() >= WIN_7)
5372 {
5373 argv_printf_cat(&argv, "%s", "validate=no");
5374 }
5375
5376 /* Treat errors while adding as non-fatal as we do not check for duplicates */
5377 netsh_command(&argv, 1, (i==0) ? M_FATAL : M_NONFATAL);
5378 }
5379
5380 argv_free(&argv);
5381 gc_free(&gc);
5382 }
5383
5384 static void
netsh_ifconfig_options(const char * type,const in_addr_t * addr_list,const int addr_len,const IP_ADDR_STRING * current,DWORD adapter_index,const bool test_first)5385 netsh_ifconfig_options(const char *type,
5386 const in_addr_t *addr_list,
5387 const int addr_len,
5388 const IP_ADDR_STRING *current,
5389 DWORD adapter_index,
5390 const bool test_first)
5391 {
5392 struct gc_arena gc = gc_new();
5393 struct argv argv = argv_new();
5394 bool delete_first = false;
5395 bool is_dns = !strcmp(type, "dns");
5396
5397 /* first check if we should delete existing DNS/WINS settings from TAP interface */
5398 if (test_first)
5399 {
5400 if (!ip_addr_one_to_one(addr_list, addr_len, current))
5401 {
5402 delete_first = true;
5403 }
5404 }
5405 else
5406 {
5407 delete_first = true;
5408 }
5409
5410 /* delete existing DNS/WINS settings from TAP interface */
5411 if (delete_first)
5412 {
5413 argv_printf(&argv, "%s%s interface ip delete %s %lu all",
5414 get_win_sys_path(),
5415 NETSH_PATH_SUFFIX,
5416 type,
5417 adapter_index);
5418 netsh_command(&argv, 2, M_FATAL);
5419 }
5420
5421 /* add new DNS/WINS settings to TAP interface */
5422 {
5423 int count = 0;
5424 int i;
5425 for (i = 0; i < addr_len; ++i)
5426 {
5427 if (delete_first || !test_first || !ip_addr_member_of(addr_list[i], current))
5428 {
5429 const char *fmt = count ?
5430 "%s%s interface ip add %s %lu %s"
5431 : "%s%s interface ip set %s %lu static %s";
5432
5433 argv_printf(&argv, fmt,
5434 get_win_sys_path(),
5435 NETSH_PATH_SUFFIX,
5436 type,
5437 adapter_index,
5438 print_in_addr_t(addr_list[i], 0, &gc));
5439
5440 /* disable slow address validation on Windows 7 and higher */
5441 /* only for DNS */
5442 if (is_dns && win32_version_info() >= WIN_7)
5443 {
5444 argv_printf_cat(&argv, "%s", "validate=no");
5445 }
5446
5447 netsh_command(&argv, 2, M_FATAL);
5448
5449 ++count;
5450 }
5451 else
5452 {
5453 msg(M_INFO, "NETSH: %lu %s %s [already set]",
5454 adapter_index,
5455 type,
5456 print_in_addr_t(addr_list[i], 0, &gc));
5457 }
5458 }
5459 }
5460
5461 argv_free(&argv);
5462 gc_free(&gc);
5463 }
5464
5465 static void
init_ip_addr_string2(IP_ADDR_STRING * dest,const IP_ADDR_STRING * src1,const IP_ADDR_STRING * src2)5466 init_ip_addr_string2(IP_ADDR_STRING *dest, const IP_ADDR_STRING *src1, const IP_ADDR_STRING *src2)
5467 {
5468 CLEAR(dest[0]);
5469 CLEAR(dest[1]);
5470 if (src1)
5471 {
5472 dest[0] = *src1;
5473 dest[0].Next = NULL;
5474 }
5475 if (src2)
5476 {
5477 dest[1] = *src2;
5478 dest[0].Next = &dest[1];
5479 dest[1].Next = NULL;
5480 }
5481 }
5482
5483 static void
netsh_ifconfig(const struct tuntap_options * to,DWORD adapter_index,const in_addr_t ip,const in_addr_t netmask,const unsigned int flags)5484 netsh_ifconfig(const struct tuntap_options *to,
5485 DWORD adapter_index,
5486 const in_addr_t ip,
5487 const in_addr_t netmask,
5488 const unsigned int flags)
5489 {
5490 struct gc_arena gc = gc_new();
5491 struct argv argv = argv_new();
5492 const IP_ADAPTER_INFO *ai = NULL;
5493 const IP_PER_ADAPTER_INFO *pai = NULL;
5494
5495 if (flags & NI_TEST_FIRST)
5496 {
5497 const IP_ADAPTER_INFO *list = get_adapter_info_list(&gc);
5498 ai = get_adapter(list, adapter_index);
5499 pai = get_per_adapter_info(adapter_index, &gc);
5500 }
5501
5502 if (flags & NI_IP_NETMASK)
5503 {
5504 if (test_adapter_ip_netmask(ai, ip, netmask))
5505 {
5506 msg(M_INFO, "NETSH: %lu %s/%s [already set]",
5507 adapter_index,
5508 print_in_addr_t(ip, 0, &gc),
5509 print_in_addr_t(netmask, 0, &gc));
5510 }
5511 else
5512 {
5513 /* example: netsh interface ip set address 42 static 10.3.0.1 255.255.255.0 */
5514 argv_printf(&argv, "%s%s interface ip set address %lu static %s %s",
5515 get_win_sys_path(),
5516 NETSH_PATH_SUFFIX,
5517 adapter_index,
5518 print_in_addr_t(ip, 0, &gc),
5519 print_in_addr_t(netmask, 0, &gc));
5520
5521 netsh_command(&argv, 4, M_FATAL);
5522 }
5523 }
5524
5525 /* set WINS/DNS options */
5526 if (flags & NI_OPTIONS)
5527 {
5528 IP_ADDR_STRING wins[2];
5529 CLEAR(wins[0]);
5530 CLEAR(wins[1]);
5531
5532 netsh_ifconfig_options("dns",
5533 to->dns,
5534 to->dns_len,
5535 pai ? &pai->DnsServerList : NULL,
5536 adapter_index,
5537 BOOL_CAST(flags & NI_TEST_FIRST));
5538 if (ai && ai->HaveWins)
5539 {
5540 init_ip_addr_string2(wins, &ai->PrimaryWinsServer, &ai->SecondaryWinsServer);
5541 }
5542
5543 netsh_ifconfig_options("wins",
5544 to->wins,
5545 to->wins_len,
5546 ai ? wins : NULL,
5547 adapter_index,
5548 BOOL_CAST(flags & NI_TEST_FIRST));
5549 }
5550
5551 argv_free(&argv);
5552 gc_free(&gc);
5553 }
5554
5555 static void
netsh_enable_dhcp(DWORD adapter_index)5556 netsh_enable_dhcp(DWORD adapter_index)
5557 {
5558 struct argv argv = argv_new();
5559
5560 /* example: netsh interface ip set address 42 dhcp */
5561 argv_printf(&argv,
5562 "%s%s interface ip set address %lu dhcp",
5563 get_win_sys_path(),
5564 NETSH_PATH_SUFFIX,
5565 adapter_index);
5566
5567 netsh_command(&argv, 4, M_FATAL);
5568
5569 argv_free(&argv);
5570 }
5571
5572 /* Enable dhcp on tap adapter using iservice */
5573 static bool
service_enable_dhcp(const struct tuntap * tt)5574 service_enable_dhcp(const struct tuntap *tt)
5575 {
5576 bool ret = false;
5577 ack_message_t ack;
5578 struct gc_arena gc = gc_new();
5579 HANDLE pipe = tt->options.msg_channel;
5580
5581 enable_dhcp_message_t dhcp = {
5582 .header = {
5583 msg_enable_dhcp,
5584 sizeof(enable_dhcp_message_t),
5585 0
5586 },
5587 .iface = { .index = tt->adapter_index, .name = "" }
5588 };
5589
5590 if (!send_msg_iservice(pipe, &dhcp, sizeof(dhcp), &ack, "Enable_dhcp"))
5591 {
5592 goto out;
5593 }
5594
5595 if (ack.error_number != NO_ERROR)
5596 {
5597 msg(M_NONFATAL, "TUN: enabling dhcp using service failed: %s [status=%u if_index=%d]",
5598 strerror_win32(ack.error_number, &gc), ack.error_number, dhcp.iface.index);
5599 }
5600 else
5601 {
5602 msg(M_INFO, "DHCP enabled on interface %d using service", dhcp.iface.index);
5603 ret = true;
5604 }
5605
5606 out:
5607 gc_free(&gc);
5608 return ret;
5609 }
5610
5611 static void
windows_set_mtu(const int iface_index,const short family,const int mtu)5612 windows_set_mtu(const int iface_index, const short family,
5613 const int mtu)
5614 {
5615 DWORD err = 0;
5616 struct gc_arena gc = gc_new();
5617 MIB_IPINTERFACE_ROW ipiface;
5618 InitializeIpInterfaceEntry(&ipiface);
5619 const char *family_name = (family == AF_INET6) ? "IPv6" : "IPv4";
5620 ipiface.Family = family;
5621 ipiface.InterfaceIndex = iface_index;
5622 if (family == AF_INET6 && mtu < 1280)
5623 {
5624 msg(M_INFO, "NOTE: IPv6 interface MTU < 1280 conflicts with IETF standards and might not work");
5625 }
5626
5627 err = GetIpInterfaceEntry(&ipiface);
5628 if (err == NO_ERROR)
5629 {
5630 if (family == AF_INET)
5631 {
5632 ipiface.SitePrefixLength = 0;
5633 }
5634 ipiface.NlMtu = mtu;
5635 err = SetIpInterfaceEntry(&ipiface);
5636 }
5637
5638 if (err != NO_ERROR)
5639 {
5640 msg(M_WARN, "TUN: Setting %s mtu failed: %s [status=%u if_index=%d]",
5641 family_name, strerror_win32(err, &gc), err, iface_index);
5642 }
5643 else
5644 {
5645 msg(M_INFO, "%s MTU set to %d on interface %d using SetIpInterfaceEntry()", family_name, mtu, iface_index);
5646 }
5647 }
5648
5649
5650 /*
5651 * Return a TAP name for netsh commands.
5652 */
5653 static const char *
netsh_get_id(const char * dev_node,struct gc_arena * gc)5654 netsh_get_id(const char *dev_node, struct gc_arena *gc)
5655 {
5656 const struct tap_reg *tap_reg = get_tap_reg(gc);
5657 const struct panel_reg *panel_reg = get_panel_reg(gc);
5658 struct buffer actual = alloc_buf_gc(256, gc);
5659 const char *guid;
5660
5661 at_least_one_tap_win(tap_reg);
5662
5663 if (dev_node)
5664 {
5665 guid = get_device_guid(dev_node, BPTR(&actual), BCAP(&actual), NULL, tap_reg, panel_reg, gc);
5666 }
5667 else
5668 {
5669 guid = get_unspecified_device_guid(0, BPTR(&actual), BCAP(&actual), tap_reg, panel_reg, NULL, gc);
5670
5671 if (get_unspecified_device_guid(1, NULL, 0, tap_reg, panel_reg, NULL, gc)) /* ambiguous if more than one TAP-Windows adapter */
5672 {
5673 guid = NULL;
5674 }
5675 }
5676
5677 if (!guid)
5678 {
5679 return "NULL"; /* not found */
5680 }
5681 else if (strcmp(BPTR(&actual), "NULL"))
5682 {
5683 return BPTR(&actual); /* control panel name */
5684 }
5685 else
5686 {
5687 return guid; /* no control panel name, return GUID instead */
5688 }
5689 }
5690
5691 /*
5692 * Called iteratively on TAP-Windows wait-for-initialization polling loop
5693 */
5694 void
tun_standby_init(struct tuntap * tt)5695 tun_standby_init(struct tuntap *tt)
5696 {
5697 tt->standby_iter = 0;
5698 }
5699
5700 bool
tun_standby(struct tuntap * tt)5701 tun_standby(struct tuntap *tt)
5702 {
5703 bool ret = true;
5704 ++tt->standby_iter;
5705 if (tt->options.ip_win32_type == IPW32_SET_ADAPTIVE)
5706 {
5707 if (tt->standby_iter == IPW32_SET_ADAPTIVE_TRY_NETSH)
5708 {
5709 msg(M_INFO, "NOTE: now trying netsh (this may take some time)");
5710 netsh_ifconfig(&tt->options,
5711 tt->adapter_index,
5712 tt->local,
5713 tt->adapter_netmask,
5714 NI_TEST_FIRST|NI_IP_NETMASK|NI_OPTIONS);
5715 }
5716 else if (tt->standby_iter >= IPW32_SET_ADAPTIVE_TRY_NETSH*2)
5717 {
5718 ret = false;
5719 }
5720 }
5721 return ret;
5722 }
5723
5724 /*
5725 * Convert DHCP options from the command line / config file
5726 * into a raw DHCP-format options string.
5727 */
5728
5729 static void
write_dhcp_u8(struct buffer * buf,const int type,const int data,bool * error)5730 write_dhcp_u8(struct buffer *buf, const int type, const int data, bool *error)
5731 {
5732 if (!buf_safe(buf, 3))
5733 {
5734 *error = true;
5735 msg(M_WARN, "write_dhcp_u8: buffer overflow building DHCP options");
5736 return;
5737 }
5738 buf_write_u8(buf, type);
5739 buf_write_u8(buf, 1);
5740 buf_write_u8(buf, data);
5741 }
5742
5743 static void
write_dhcp_u32_array(struct buffer * buf,const int type,const uint32_t * data,const unsigned int len,bool * error)5744 write_dhcp_u32_array(struct buffer *buf, const int type, const uint32_t *data, const unsigned int len, bool *error)
5745 {
5746 if (len > 0)
5747 {
5748 int i;
5749 const int size = len * sizeof(uint32_t);
5750
5751 if (!buf_safe(buf, 2 + size))
5752 {
5753 *error = true;
5754 msg(M_WARN, "write_dhcp_u32_array: buffer overflow building DHCP options");
5755 return;
5756 }
5757 if (size < 1 || size > 255)
5758 {
5759 *error = true;
5760 msg(M_WARN, "write_dhcp_u32_array: size (%d) must be > 0 and <= 255", size);
5761 return;
5762 }
5763 buf_write_u8(buf, type);
5764 buf_write_u8(buf, size);
5765 for (i = 0; i < len; ++i)
5766 {
5767 buf_write_u32(buf, data[i]);
5768 }
5769 }
5770 }
5771
5772 static void
write_dhcp_str(struct buffer * buf,const int type,const char * str,bool * error)5773 write_dhcp_str(struct buffer *buf, const int type, const char *str, bool *error)
5774 {
5775 const int len = strlen(str);
5776 if (!buf_safe(buf, 2 + len))
5777 {
5778 *error = true;
5779 msg(M_WARN, "write_dhcp_str: buffer overflow building DHCP options");
5780 return;
5781 }
5782 if (len < 1 || len > 255)
5783 {
5784 *error = true;
5785 msg(M_WARN, "write_dhcp_str: string '%s' must be > 0 bytes and <= 255 bytes", str);
5786 return;
5787 }
5788 buf_write_u8(buf, type);
5789 buf_write_u8(buf, len);
5790 buf_write(buf, str, len);
5791 }
5792
5793 /*
5794 * RFC3397 states that multiple searchdomains are encoded as follows:
5795 * - at start the length of the entire option is given
5796 * - each subdomain is preceded by its length
5797 * - each searchdomain is separated by a NUL character
5798 * e.g. if you want "openvpn.net" and "duckduckgo.com" then you end up with
5799 * 0x1D 0x7 openvpn 0x3 net 0x00 0x0A duckduckgo 0x3 com 0x00
5800 */
5801 static void
write_dhcp_search_str(struct buffer * buf,const int type,const char * const * str_array,int array_len,bool * error)5802 write_dhcp_search_str(struct buffer *buf, const int type, const char * const *str_array,
5803 int array_len, bool *error)
5804 {
5805 char tmp_buf[256];
5806 int i;
5807 int len = 0;
5808 int label_length_pos;
5809
5810 for (i=0; i < array_len; i++)
5811 {
5812 const char *ptr = str_array[i];
5813
5814 if (strlen(ptr) + len + 1 > sizeof(tmp_buf))
5815 {
5816 *error = true;
5817 msg(M_WARN, "write_dhcp_search_str: temp buffer overflow building DHCP options");
5818 return;
5819 }
5820 /* Loop over all subdomains separated by a dot and replace the dot
5821 with the length of the subdomain */
5822
5823 /* label_length_pos points to the byte to be replaced by the length
5824 * of the following domain label */
5825 label_length_pos = len++;
5826
5827 while (true)
5828 {
5829 if (*ptr == '.' || *ptr == '\0' )
5830 {
5831 tmp_buf[label_length_pos] = (len-label_length_pos)-1;
5832 label_length_pos = len;
5833 if (*ptr == '\0')
5834 {
5835 break;
5836 }
5837 }
5838 tmp_buf[len++] = *ptr++;
5839 }
5840 /* And close off with an extra NUL char */
5841 tmp_buf[len++] = 0;
5842 }
5843
5844 if (!buf_safe(buf, 2 + len))
5845 {
5846 *error = true;
5847 msg(M_WARN, "write_search_dhcp_str: buffer overflow building DHCP options");
5848 return;
5849 }
5850 if (len > 255)
5851 {
5852 *error = true;
5853 msg(M_WARN, "write_dhcp_search_str: search domain string must be <= 255 bytes");
5854 return;
5855 }
5856
5857 buf_write_u8(buf, type);
5858 buf_write_u8(buf, len);
5859 buf_write(buf, tmp_buf, len);
5860 }
5861
5862 static bool
build_dhcp_options_string(struct buffer * buf,const struct tuntap_options * o)5863 build_dhcp_options_string(struct buffer *buf, const struct tuntap_options *o)
5864 {
5865 bool error = false;
5866 if (o->domain)
5867 {
5868 write_dhcp_str(buf, 15, o->domain, &error);
5869 }
5870
5871 if (o->netbios_scope)
5872 {
5873 write_dhcp_str(buf, 47, o->netbios_scope, &error);
5874 }
5875
5876 if (o->netbios_node_type)
5877 {
5878 write_dhcp_u8(buf, 46, o->netbios_node_type, &error);
5879 }
5880
5881 write_dhcp_u32_array(buf, 6, (uint32_t *)o->dns, o->dns_len, &error);
5882 write_dhcp_u32_array(buf, 44, (uint32_t *)o->wins, o->wins_len, &error);
5883 write_dhcp_u32_array(buf, 42, (uint32_t *)o->ntp, o->ntp_len, &error);
5884 write_dhcp_u32_array(buf, 45, (uint32_t *)o->nbdd, o->nbdd_len, &error);
5885
5886 if (o->domain_search_list_len > 0)
5887 {
5888 write_dhcp_search_str(buf, 119, o->domain_search_list,
5889 o->domain_search_list_len,
5890 &error);
5891 }
5892
5893 /* the MS DHCP server option 'Disable Netbios-over-TCP/IP
5894 * is implemented as vendor option 001, value 002.
5895 * A value of 001 means 'leave NBT alone' which is the default */
5896 if (o->disable_nbt)
5897 {
5898 if (!buf_safe(buf, 8))
5899 {
5900 msg(M_WARN, "build_dhcp_options_string: buffer overflow building DHCP options");
5901 return false;
5902 }
5903 buf_write_u8(buf, 43);
5904 buf_write_u8(buf, 6);/* total length field */
5905 buf_write_u8(buf, 0x001);
5906 buf_write_u8(buf, 4);/* length of the vendor specified field */
5907 buf_write_u32(buf, 0x002);
5908 }
5909 return !error;
5910 }
5911
5912 static void
fork_dhcp_action(struct tuntap * tt)5913 fork_dhcp_action(struct tuntap *tt)
5914 {
5915 if (tt->options.dhcp_pre_release || tt->options.dhcp_renew)
5916 {
5917 struct gc_arena gc = gc_new();
5918 struct buffer cmd = alloc_buf_gc(256, &gc);
5919 const int verb = 3;
5920 const int pre_sleep = 1;
5921
5922 buf_printf(&cmd, "openvpn --verb %d --tap-sleep %d", verb, pre_sleep);
5923 if (tt->options.dhcp_pre_release)
5924 {
5925 buf_printf(&cmd, " --dhcp-pre-release");
5926 }
5927 if (tt->options.dhcp_renew)
5928 {
5929 buf_printf(&cmd, " --dhcp-renew");
5930 }
5931 buf_printf(&cmd, " --dhcp-internal %lu", tt->adapter_index);
5932
5933 fork_to_self(BSTR(&cmd));
5934 gc_free(&gc);
5935 }
5936 }
5937
5938 static void
register_dns_service(const struct tuntap * tt)5939 register_dns_service(const struct tuntap *tt)
5940 {
5941 HANDLE msg_channel = tt->options.msg_channel;
5942 ack_message_t ack;
5943 struct gc_arena gc = gc_new();
5944
5945 message_header_t rdns = { msg_register_dns, sizeof(message_header_t), 0 };
5946
5947 if (!send_msg_iservice(msg_channel, &rdns, sizeof(rdns), &ack, "Register_dns"))
5948 {
5949 gc_free(&gc);
5950 return;
5951 }
5952
5953 else if (ack.error_number != NO_ERROR)
5954 {
5955 msg(M_WARN, "Register_dns failed using service: %s [status=0x%x]",
5956 strerror_win32(ack.error_number, &gc), ack.error_number);
5957 }
5958
5959 else
5960 {
5961 msg(M_INFO, "Register_dns request sent to the service");
5962 }
5963
5964 gc_free(&gc);
5965 }
5966
5967 static bool
service_register_ring_buffers(const struct tuntap * tt)5968 service_register_ring_buffers(const struct tuntap *tt)
5969 {
5970 HANDLE msg_channel = tt->options.msg_channel;
5971 ack_message_t ack;
5972 bool ret = true;
5973 struct gc_arena gc = gc_new();
5974
5975 register_ring_buffers_message_t msg = {
5976 .header = {
5977 msg_register_ring_buffers,
5978 sizeof(register_ring_buffers_message_t),
5979 0
5980 },
5981 .device = tt->hand,
5982 .send_ring_handle = tt->wintun_send_ring_handle,
5983 .receive_ring_handle = tt->wintun_receive_ring_handle,
5984 .send_tail_moved = tt->rw_handle.read,
5985 .receive_tail_moved = tt->rw_handle.write
5986 };
5987
5988 if (!send_msg_iservice(msg_channel, &msg, sizeof(msg), &ack, "Register ring buffers"))
5989 {
5990 ret = false;
5991 }
5992 else if (ack.error_number != NO_ERROR)
5993 {
5994 msg(M_NONFATAL, "Register ring buffers failed using service: %s [status=0x%x]",
5995 strerror_win32(ack.error_number, &gc), ack.error_number);
5996 ret = false;
5997 }
5998 else
5999 {
6000 msg(M_INFO, "Ring buffers registered via service");
6001 }
6002
6003 gc_free(&gc);
6004 return ret;
6005 }
6006
6007 void
fork_register_dns_action(struct tuntap * tt)6008 fork_register_dns_action(struct tuntap *tt)
6009 {
6010 if (tt && tt->options.register_dns && tt->options.msg_channel)
6011 {
6012 register_dns_service(tt);
6013 }
6014 else if (tt && tt->options.register_dns)
6015 {
6016 struct gc_arena gc = gc_new();
6017 struct buffer cmd = alloc_buf_gc(256, &gc);
6018 const int verb = 3;
6019
6020 buf_printf(&cmd, "openvpn --verb %d --register-dns --rdns-internal", verb);
6021 fork_to_self(BSTR(&cmd));
6022 gc_free(&gc);
6023 }
6024 }
6025
6026 static uint32_t
dhcp_masq_addr(const in_addr_t local,const in_addr_t netmask,const int offset)6027 dhcp_masq_addr(const in_addr_t local, const in_addr_t netmask, const int offset)
6028 {
6029 struct gc_arena gc = gc_new();
6030 in_addr_t dsa; /* DHCP server addr */
6031
6032 if (offset < 0)
6033 {
6034 dsa = (local | (~netmask)) + offset;
6035 }
6036 else
6037 {
6038 dsa = (local & netmask) + offset;
6039 }
6040
6041 if (dsa == local)
6042 {
6043 msg(M_FATAL, "ERROR: There is a clash between the --ifconfig local address and the internal DHCP server address -- both are set to %s -- please use the --ip-win32 dynamic option to choose a different free address from the --ifconfig subnet for the internal DHCP server", print_in_addr_t(dsa, 0, &gc));
6044 }
6045
6046 if ((local & netmask) != (dsa & netmask))
6047 {
6048 msg(M_FATAL, "ERROR: --ip-win32 dynamic [offset] : offset is outside of --ifconfig subnet");
6049 }
6050
6051 gc_free(&gc);
6052 return htonl(dsa);
6053 }
6054
6055 static void
tuntap_get_version_info(const struct tuntap * tt)6056 tuntap_get_version_info(const struct tuntap *tt)
6057 {
6058 ULONG info[3];
6059 DWORD len;
6060 CLEAR(info);
6061 if (DeviceIoControl(tt->hand, TAP_WIN_IOCTL_GET_VERSION,
6062 &info, sizeof(info),
6063 &info, sizeof(info), &len, NULL))
6064 {
6065 msg(D_TUNTAP_INFO, "TAP-Windows Driver Version %d.%d %s",
6066 (int)info[0],
6067 (int)info[1],
6068 (info[2] ? "(DEBUG)" : ""));
6069
6070 }
6071 if (!(info[0] == TAP_WIN_MIN_MAJOR && info[1] >= TAP_WIN_MIN_MINOR))
6072 {
6073 msg(M_FATAL, "ERROR: This version of " PACKAGE_NAME " requires a TAP-Windows driver that is at least version %d.%d -- If you recently upgraded your " PACKAGE_NAME " distribution, a reboot is probably required at this point to get Windows to see the new driver.",
6074 TAP_WIN_MIN_MAJOR,
6075 TAP_WIN_MIN_MINOR);
6076 }
6077
6078 /* usage of numeric constants is ugly, but this is really tied to
6079 * *this* version of the driver
6080 */
6081 if (tt->type == DEV_TYPE_TUN
6082 && info[0] == 9 && info[1] < 8)
6083 {
6084 msg(M_INFO, "WARNING: Tap-Win32 driver version %d.%d does not support IPv6 in TUN mode. IPv6 will not work. Upgrade your Tap-Win32 driver.", (int)info[0], (int)info[1]);
6085 }
6086
6087 /* tap driver 9.8 (2.2.0 and 2.2.1 release) is buggy
6088 */
6089 if (tt->type == DEV_TYPE_TUN
6090 && info[0] == 9 && info[1] == 8)
6091 {
6092 msg(M_FATAL, "ERROR: Tap-Win32 driver version %d.%d is buggy regarding small IPv4 packets in TUN mode. Upgrade your Tap-Win32 driver.", (int)info[0], (int)info[1]);
6093 }
6094 }
6095
6096 static void
tuntap_get_mtu(struct tuntap * tt)6097 tuntap_get_mtu(struct tuntap *tt)
6098 {
6099 ULONG mtu = 0;
6100 DWORD len;
6101 if (DeviceIoControl(tt->hand, TAP_WIN_IOCTL_GET_MTU,
6102 &mtu, sizeof(mtu),
6103 &mtu, sizeof(mtu), &len, NULL))
6104 {
6105 tt->post_open_mtu = (int)mtu;
6106 msg(D_MTU_INFO, "TAP-Windows MTU=%d", (int)mtu);
6107 }
6108 }
6109
6110 static void
tuntap_set_ip_addr(struct tuntap * tt,const char * device_guid,bool dhcp_masq_post)6111 tuntap_set_ip_addr(struct tuntap *tt,
6112 const char *device_guid,
6113 bool dhcp_masq_post)
6114 {
6115 struct gc_arena gc = gc_new();
6116 const DWORD index = tt->adapter_index;
6117
6118 /* flush arp cache */
6119 if (tt->windows_driver == WINDOWS_DRIVER_TAP_WINDOWS6
6120 && index != TUN_ADAPTER_INDEX_INVALID)
6121 {
6122 DWORD status = -1;
6123
6124 if (tt->options.msg_channel)
6125 {
6126 ack_message_t ack;
6127 flush_neighbors_message_t msg = {
6128 .header = {
6129 msg_flush_neighbors,
6130 sizeof(flush_neighbors_message_t),
6131 0
6132 },
6133 .family = AF_INET,
6134 .iface = {.index = index, .name = "" }
6135 };
6136
6137 if (send_msg_iservice(tt->options.msg_channel, &msg, sizeof(msg),
6138 &ack, "TUN"))
6139 {
6140 status = ack.error_number;
6141 }
6142 }
6143 else
6144 {
6145 status = FlushIpNetTable(index);
6146 }
6147
6148 if (status == NO_ERROR)
6149 {
6150 msg(M_INFO, "Successful ARP Flush on interface [%lu] %s",
6151 index,
6152 device_guid);
6153 }
6154 else if (status != -1)
6155 {
6156 msg(D_TUNTAP_INFO, "NOTE: FlushIpNetTable failed on interface [%lu] %s (status=%lu) : %s",
6157 index,
6158 device_guid,
6159 status,
6160 strerror_win32(status, &gc));
6161 }
6162
6163 /*
6164 * If the TAP-Windows driver is masquerading as a DHCP server
6165 * make sure the TCP/IP properties for the adapter are
6166 * set correctly.
6167 */
6168 if (dhcp_masq_post)
6169 {
6170 /* check dhcp enable status */
6171 if (dhcp_status(index) == DHCP_STATUS_DISABLED)
6172 {
6173 msg(M_WARN, "WARNING: You have selected '--ip-win32 dynamic', which will not work unless the TAP-Windows TCP/IP properties are set to 'Obtain an IP address automatically'");
6174 }
6175
6176 /* force an explicit DHCP lease renewal on TAP adapter? */
6177 if (tt->options.dhcp_pre_release)
6178 {
6179 dhcp_release(tt);
6180 }
6181 if (tt->options.dhcp_renew)
6182 {
6183 dhcp_renew(tt);
6184 }
6185 }
6186 else
6187 {
6188 fork_dhcp_action(tt);
6189 }
6190 }
6191
6192 if (tt->did_ifconfig_setup && tt->options.ip_win32_type == IPW32_SET_IPAPI)
6193 {
6194 DWORD status;
6195 const char *error_suffix = "I am having trouble using the Windows 'IP helper API' to automatically set the IP address -- consider using other --ip-win32 methods (not 'ipapi')";
6196
6197 /* couldn't get adapter index */
6198 if (index == TUN_ADAPTER_INDEX_INVALID)
6199 {
6200 msg(M_FATAL, "ERROR: unable to get adapter index for interface %s -- %s",
6201 device_guid,
6202 error_suffix);
6203 }
6204
6205 /* check dhcp enable status */
6206 if (dhcp_status(index) == DHCP_STATUS_DISABLED)
6207 {
6208 msg(M_WARN, "NOTE: You have selected (explicitly or by default) '--ip-win32 ipapi', which has a better chance of working correctly if the TAP-Windows TCP/IP properties are set to 'Obtain an IP address automatically'");
6209 }
6210
6211 /* delete previously added IP addresses which were not
6212 * correctly deleted */
6213 delete_temp_addresses(index);
6214
6215 /* add a new IP address */
6216 if ((status = AddIPAddress(htonl(tt->local),
6217 htonl(tt->adapter_netmask),
6218 index,
6219 &tt->ipapi_context,
6220 &tt->ipapi_instance)) == NO_ERROR)
6221 {
6222 msg(M_INFO, "Succeeded in adding a temporary IP/netmask of %s/%s to interface %s using the Win32 IP Helper API",
6223 print_in_addr_t(tt->local, 0, &gc),
6224 print_in_addr_t(tt->adapter_netmask, 0, &gc),
6225 device_guid
6226 );
6227 }
6228 else
6229 {
6230 msg(M_FATAL, "ERROR: AddIPAddress %s/%s failed on interface %s, index=%lu, status=%lu (windows error: '%s') -- %s",
6231 print_in_addr_t(tt->local, 0, &gc),
6232 print_in_addr_t(tt->adapter_netmask, 0, &gc),
6233 device_guid,
6234 index,
6235 status,
6236 strerror_win32(status, &gc),
6237 error_suffix);
6238 }
6239 tt->ipapi_context_defined = true;
6240 }
6241
6242 gc_free(&gc);
6243 }
6244
6245 static bool
wintun_register_ring_buffer(struct tuntap * tt,const char * device_guid)6246 wintun_register_ring_buffer(struct tuntap *tt, const char *device_guid)
6247 {
6248 bool ret = true;
6249
6250 tt->wintun_send_ring = (struct tun_ring *)MapViewOfFile(tt->wintun_send_ring_handle,
6251 FILE_MAP_ALL_ACCESS,
6252 0,
6253 0,
6254 sizeof(struct tun_ring));
6255
6256 tt->wintun_receive_ring = (struct tun_ring *)MapViewOfFile(tt->wintun_receive_ring_handle,
6257 FILE_MAP_ALL_ACCESS,
6258 0,
6259 0,
6260 sizeof(struct tun_ring));
6261
6262 if (tt->options.msg_channel)
6263 {
6264 ret = service_register_ring_buffers(tt);
6265 }
6266 else
6267 {
6268 if (!register_ring_buffers(tt->hand,
6269 tt->wintun_send_ring,
6270 tt->wintun_receive_ring,
6271 tt->rw_handle.read,
6272 tt->rw_handle.write))
6273 {
6274 switch (GetLastError())
6275 {
6276 case ERROR_ACCESS_DENIED:
6277 msg(M_FATAL, "ERROR: Wintun requires SYSTEM privileges and therefore "
6278 "should be used with interactive service. If you want to "
6279 "use openvpn from command line, you need to do SYSTEM "
6280 "elevation yourself (for example with psexec).");
6281 break;
6282
6283 case ERROR_ALREADY_INITIALIZED:
6284 msg(M_NONFATAL, "Adapter %s is already in use", device_guid);
6285 break;
6286
6287 default:
6288 msg(M_NONFATAL | M_ERRNO, "Failed to register ring buffers");
6289 }
6290 ret = false;
6291 }
6292
6293 }
6294 return ret;
6295 }
6296
6297 static void
tuntap_set_connected(const struct tuntap * tt)6298 tuntap_set_connected(const struct tuntap *tt)
6299 {
6300 ULONG status = TRUE;
6301 DWORD len;
6302 if (!DeviceIoControl(tt->hand, TAP_WIN_IOCTL_SET_MEDIA_STATUS,
6303 &status, sizeof(status),
6304 &status, sizeof(status), &len, NULL))
6305 {
6306 msg(M_WARN, "WARNING: The TAP-Windows driver rejected a TAP_WIN_IOCTL_SET_MEDIA_STATUS DeviceIoControl call.");
6307 }
6308
6309 int s = tt->options.tap_sleep;
6310 if (s > 0)
6311 {
6312 msg(M_INFO, "Sleeping for %d seconds...", s);
6313 management_sleep(s);
6314 }
6315 }
6316
6317 static void
tuntap_set_ptp(const struct tuntap * tt)6318 tuntap_set_ptp(const struct tuntap *tt)
6319 {
6320 DWORD len;
6321 struct gc_arena gc = gc_new();
6322
6323 if (!tt->did_ifconfig_setup && !tt->did_ifconfig_ipv6_setup)
6324 {
6325 msg(M_FATAL, "ERROR: --dev tun also requires --ifconfig");
6326 }
6327
6328 /* send 0/0/0 to the TAP driver even if we have no IPv4 configured to
6329 * ensure it is somehow initialized.
6330 */
6331 if (!tt->did_ifconfig_setup || tt->topology == TOP_SUBNET)
6332 {
6333 in_addr_t ep[3];
6334 BOOL status;
6335
6336 ep[0] = htonl(tt->local);
6337 ep[1] = htonl(tt->local & tt->remote_netmask);
6338 ep[2] = htonl(tt->remote_netmask);
6339
6340 status = DeviceIoControl(tt->hand, TAP_WIN_IOCTL_CONFIG_TUN,
6341 ep, sizeof(ep),
6342 ep, sizeof(ep), &len, NULL);
6343
6344 if (tt->did_ifconfig_setup)
6345 {
6346 msg(status ? M_INFO : M_FATAL, "Set TAP-Windows TUN subnet mode network/local/netmask = %s/%s/%s [%s]",
6347 print_in_addr_t(ep[1], IA_NET_ORDER, &gc),
6348 print_in_addr_t(ep[0], IA_NET_ORDER, &gc),
6349 print_in_addr_t(ep[2], IA_NET_ORDER, &gc),
6350 status ? "SUCCEEDED" : "FAILED");
6351 }
6352 else
6353 {
6354 msg(status ? M_INFO : M_FATAL, "Set TAP-Windows TUN with fake IPv4 [%s]",
6355 status ? "SUCCEEDED" : "FAILED");
6356 }
6357 }
6358 else
6359 {
6360 in_addr_t ep[2];
6361 ep[0] = htonl(tt->local);
6362 ep[1] = htonl(tt->remote_netmask);
6363
6364 if (!DeviceIoControl(tt->hand, TAP_WIN_IOCTL_CONFIG_POINT_TO_POINT,
6365 ep, sizeof(ep),
6366 ep, sizeof(ep), &len, NULL))
6367 {
6368 msg(M_FATAL, "ERROR: The TAP-Windows driver rejected a DeviceIoControl call to set Point-to-Point mode, which is required for --dev tun");
6369 }
6370 }
6371
6372 gc_free(&gc);
6373 }
6374
6375 static void
tuntap_dhcp_mask(const struct tuntap * tt,const char * device_guid)6376 tuntap_dhcp_mask(const struct tuntap *tt, const char *device_guid)
6377 {
6378 struct gc_arena gc = gc_new();
6379 DWORD len;
6380 uint32_t ep[4];
6381
6382 /* We will answer DHCP requests with a reply to set IP/subnet to these values */
6383 ep[0] = htonl(tt->local);
6384 ep[1] = htonl(tt->adapter_netmask);
6385
6386 /* At what IP address should the DHCP server masquerade at? */
6387 if (tt->type == DEV_TYPE_TUN)
6388 {
6389 if (tt->topology == TOP_SUBNET)
6390 {
6391 ep[2] = dhcp_masq_addr(tt->local, tt->remote_netmask, tt->options.dhcp_masq_custom_offset ? tt->options.dhcp_masq_offset : 0);
6392 }
6393 else
6394 {
6395 ep[2] = htonl(tt->remote_netmask);
6396 }
6397 }
6398 else
6399 {
6400 ASSERT(tt->type == DEV_TYPE_TAP);
6401 ep[2] = dhcp_masq_addr(tt->local, tt->adapter_netmask, tt->options.dhcp_masq_custom_offset ? tt->options.dhcp_masq_offset : 0);
6402 }
6403
6404 /* lease time in seconds */
6405 ep[3] = (uint32_t)tt->options.dhcp_lease_time;
6406
6407 ASSERT(ep[3] > 0);
6408
6409 #ifndef SIMULATE_DHCP_FAILED /* this code is disabled to simulate bad DHCP negotiation */
6410 if (!DeviceIoControl(tt->hand, TAP_WIN_IOCTL_CONFIG_DHCP_MASQ,
6411 ep, sizeof(ep),
6412 ep, sizeof(ep), &len, NULL))
6413 {
6414 msg(M_FATAL, "ERROR: The TAP-Windows driver rejected a DeviceIoControl call to set TAP_WIN_IOCTL_CONFIG_DHCP_MASQ mode");
6415 }
6416
6417 msg(M_INFO, "Notified TAP-Windows driver to set a DHCP IP/netmask of %s/%s on interface %s [DHCP-serv: %s, lease-time: %d]",
6418 print_in_addr_t(tt->local, 0, &gc),
6419 print_in_addr_t(tt->adapter_netmask, 0, &gc),
6420 device_guid,
6421 print_in_addr_t(ep[2], IA_NET_ORDER, &gc),
6422 ep[3]
6423 );
6424
6425 /* user-supplied DHCP options capability */
6426 if (tt->options.dhcp_options)
6427 {
6428 struct buffer buf = alloc_buf(256);
6429 if (build_dhcp_options_string(&buf, &tt->options))
6430 {
6431 msg(D_DHCP_OPT, "DHCP option string: %s", format_hex(BPTR(&buf), BLEN(&buf), 0, &gc));
6432 if (!DeviceIoControl(tt->hand, TAP_WIN_IOCTL_CONFIG_DHCP_SET_OPT,
6433 BPTR(&buf), BLEN(&buf),
6434 BPTR(&buf), BLEN(&buf), &len, NULL))
6435 {
6436 msg(M_FATAL, "ERROR: The TAP-Windows driver rejected a TAP_WIN_IOCTL_CONFIG_DHCP_SET_OPT DeviceIoControl call");
6437 }
6438 }
6439 else
6440 {
6441 msg(M_WARN, "DHCP option string not set due to error");
6442 }
6443 free_buf(&buf);
6444 }
6445 #endif /* ifndef SIMULATE_DHCP_FAILED */
6446
6447 gc_free(&gc);
6448 }
6449
6450 static bool
tun_try_open_device(struct tuntap * tt,const char * device_guid,const struct device_instance_id_interface * device_instance_id_interface)6451 tun_try_open_device(struct tuntap *tt, const char *device_guid, const struct device_instance_id_interface *device_instance_id_interface)
6452 {
6453 const char *path = NULL;
6454 char tuntap_device_path[256];
6455
6456 if (tt->windows_driver == WINDOWS_DRIVER_WINTUN)
6457 {
6458 const struct device_instance_id_interface *dev_if;
6459
6460 /* Open Wintun adapter */
6461 for (dev_if = device_instance_id_interface; dev_if != NULL; dev_if = dev_if->next)
6462 {
6463 if (strcmp(dev_if->net_cfg_instance_id, device_guid) == 0)
6464 {
6465 path = dev_if->device_interface_list;
6466 break;
6467 }
6468 }
6469 if (path == NULL)
6470 {
6471 return false;
6472 }
6473 }
6474 else
6475 {
6476 /* Open TAP-Windows adapter */
6477 openvpn_snprintf(tuntap_device_path, sizeof(tuntap_device_path), "%s%s%s",
6478 USERMODEDEVICEDIR,
6479 device_guid,
6480 TAP_WIN_SUFFIX);
6481 path = tuntap_device_path;
6482 }
6483
6484 tt->hand = CreateFile(path,
6485 GENERIC_READ | GENERIC_WRITE,
6486 0, /* was: FILE_SHARE_READ */
6487 0,
6488 OPEN_EXISTING,
6489 FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
6490 0);
6491 if (tt->hand == INVALID_HANDLE_VALUE)
6492 {
6493 msg(D_TUNTAP_INFO, "CreateFile failed on %s device: %s", print_windows_driver(tt->windows_driver), path);
6494 return false;
6495 }
6496
6497 if (tt->windows_driver == WINDOWS_DRIVER_WINTUN)
6498 {
6499 /* Wintun adapter may be considered "open" after ring buffers are successfuly registered. */
6500 if (!wintun_register_ring_buffer(tt, device_guid))
6501 {
6502 msg(D_TUNTAP_INFO, "Failed to register %s adapter ring buffers", device_guid);
6503 CloseHandle(tt->hand);
6504 tt->hand = NULL;
6505 return false;
6506 }
6507 }
6508
6509 return true;
6510 }
6511
6512 static void
tun_open_device(struct tuntap * tt,const char * dev_node,const char ** device_guid,struct gc_arena * gc)6513 tun_open_device(struct tuntap *tt, const char *dev_node, const char **device_guid, struct gc_arena *gc)
6514 {
6515 const struct tap_reg *tap_reg = get_tap_reg(gc);
6516 const struct panel_reg *panel_reg = get_panel_reg(gc);
6517 const struct device_instance_id_interface *device_instance_id_interface = get_device_instance_id_interface(gc);
6518 char actual_buffer[256];
6519
6520 at_least_one_tap_win(tap_reg);
6521
6522 /*
6523 * Lookup the device name in the registry, using the --dev-node high level name.
6524 */
6525 if (dev_node)
6526 {
6527 enum windows_driver_type windows_driver = WINDOWS_DRIVER_UNSPECIFIED;
6528
6529 /* Get the device GUID for the device specified with --dev-node. */
6530 *device_guid = get_device_guid(dev_node, actual_buffer, sizeof(actual_buffer), &windows_driver, tap_reg, panel_reg, gc);
6531
6532 if (!*device_guid)
6533 {
6534 msg(M_FATAL, "Adapter '%s' not found", dev_node);
6535 }
6536
6537 if (tt->windows_driver != windows_driver)
6538 {
6539 msg(M_FATAL, "Adapter '%s' is using %s driver, %s expected. If you want to use this device, adjust --windows-driver.",
6540 dev_node, print_windows_driver(windows_driver), print_windows_driver(tt->windows_driver));
6541 }
6542
6543 if (!tun_try_open_device(tt, *device_guid, device_instance_id_interface))
6544 {
6545 msg(M_FATAL, "Failed to open %s adapter: %s", print_windows_driver(tt->windows_driver), dev_node);
6546 }
6547 }
6548 else
6549 {
6550 int device_number = 0;
6551
6552 /* Try opening all TAP devices until we find one available */
6553 while (true)
6554 {
6555 enum windows_driver_type windows_driver = WINDOWS_DRIVER_UNSPECIFIED;
6556 *device_guid = get_unspecified_device_guid(device_number,
6557 actual_buffer,
6558 sizeof(actual_buffer),
6559 tap_reg,
6560 panel_reg,
6561 &windows_driver,
6562 gc);
6563
6564 if (!*device_guid)
6565 {
6566 msg(M_FATAL, "All %s adapters on this system are currently in use or disabled.", print_windows_driver(tt->windows_driver));
6567 }
6568
6569 if (tt->windows_driver != windows_driver)
6570 {
6571 goto next;
6572 }
6573
6574 if (tun_try_open_device(tt, *device_guid, device_instance_id_interface))
6575 {
6576 break;
6577 }
6578
6579 next:
6580 device_number++;
6581 }
6582 }
6583
6584 /* translate high-level device name into a device instance
6585 * GUID using the registry */
6586 tt->actual_name = string_alloc(actual_buffer, NULL);
6587
6588 msg(M_INFO, "%s device [%s] opened", print_windows_driver(tt->windows_driver), tt->actual_name);
6589 tt->adapter_index = get_adapter_index(*device_guid);
6590 }
6591
6592 static void
tuntap_set_ip_props(const struct tuntap * tt,bool * dhcp_masq,bool * dhcp_masq_post)6593 tuntap_set_ip_props(const struct tuntap *tt, bool *dhcp_masq, bool *dhcp_masq_post)
6594 {
6595 if (tt->options.ip_win32_type == IPW32_SET_DHCP_MASQ)
6596 {
6597 /*
6598 * If adapter is set to non-DHCP, set to DHCP mode.
6599 */
6600 if (dhcp_status(tt->adapter_index) == DHCP_STATUS_DISABLED)
6601 {
6602 /* try using the service if available, else directly execute netsh */
6603 if (tt->options.msg_channel)
6604 {
6605 service_enable_dhcp(tt);
6606 }
6607 else
6608 {
6609 netsh_enable_dhcp(tt->adapter_index);
6610 }
6611 }
6612 *dhcp_masq = true;
6613 *dhcp_masq_post = true;
6614 }
6615 else if (tt->options.ip_win32_type == IPW32_SET_ADAPTIVE)
6616 {
6617 /*
6618 * If adapter is set to non-DHCP, use netsh right away.
6619 */
6620 if (dhcp_status(tt->adapter_index) != DHCP_STATUS_ENABLED)
6621 {
6622 netsh_ifconfig(&tt->options,
6623 tt->adapter_index,
6624 tt->local,
6625 tt->adapter_netmask,
6626 NI_TEST_FIRST | NI_IP_NETMASK | NI_OPTIONS);
6627 }
6628 else
6629 {
6630 *dhcp_masq = true;
6631 }
6632 }
6633 }
6634
6635 static void
tuntap_post_open(struct tuntap * tt,const char * device_guid)6636 tuntap_post_open(struct tuntap *tt, const char *device_guid)
6637 {
6638 bool dhcp_masq = false;
6639 bool dhcp_masq_post = false;
6640
6641 if (tt->windows_driver == WINDOWS_DRIVER_TAP_WINDOWS6)
6642 {
6643 /* get driver version info */
6644 tuntap_get_version_info(tt);
6645
6646 /* get driver MTU */
6647 tuntap_get_mtu(tt);
6648
6649 /*
6650 * Preliminaries for setting TAP-Windows adapter TCP/IP
6651 * properties via --ip-win32 dynamic or --ip-win32 adaptive.
6652 */
6653 if (tt->did_ifconfig_setup)
6654 {
6655 tuntap_set_ip_props(tt, &dhcp_masq, &dhcp_masq_post);
6656 }
6657
6658 /* set point-to-point mode if TUN device */
6659 if (tt->type == DEV_TYPE_TUN)
6660 {
6661 tuntap_set_ptp(tt);
6662 }
6663
6664 /* should we tell the TAP-Windows driver to masquerade as a DHCP server as a means
6665 * of setting the adapter address? */
6666 if (dhcp_masq)
6667 {
6668 tuntap_dhcp_mask(tt, device_guid);
6669 }
6670
6671 /* set driver media status to 'connected' */
6672 tuntap_set_connected(tt);
6673 }
6674
6675 /* possibly use IP Helper API to set IP address on adapter */
6676 tuntap_set_ip_addr(tt, device_guid, dhcp_masq_post);
6677 }
6678
6679 void
open_tun(const char * dev,const char * dev_type,const char * dev_node,struct tuntap * tt)6680 open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
6681 {
6682 const char *device_guid = NULL;
6683
6684 /*netcmd_semaphore_lock ();*/
6685
6686 msg( M_INFO, "open_tun");
6687
6688 if (tt->type == DEV_TYPE_NULL)
6689 {
6690 open_null(tt);
6691 return;
6692 }
6693 else if (tt->type != DEV_TYPE_TAP && tt->type != DEV_TYPE_TUN)
6694 {
6695 msg(M_FATAL|M_NOPREFIX, "Unknown virtual device type: '%s'", dev);
6696 }
6697
6698 struct gc_arena gc = gc_new(); /* used also for device_guid allocation */
6699 tun_open_device(tt, dev_node, &device_guid, &gc);
6700
6701 tuntap_post_open(tt, device_guid);
6702
6703 gc_free(&gc);
6704
6705 /*netcmd_semaphore_release ();*/
6706 }
6707
6708 const char *
tap_win_getinfo(const struct tuntap * tt,struct gc_arena * gc)6709 tap_win_getinfo(const struct tuntap *tt, struct gc_arena *gc)
6710 {
6711 if (tt->windows_driver == WINDOWS_DRIVER_TAP_WINDOWS6)
6712 {
6713 struct buffer out = alloc_buf_gc(256, gc);
6714 DWORD len;
6715 if (DeviceIoControl(tt->hand, TAP_WIN_IOCTL_GET_INFO,
6716 BSTR(&out), BCAP(&out),
6717 BSTR(&out), BCAP(&out),
6718 &len, NULL))
6719 {
6720 return BSTR(&out);
6721 }
6722 }
6723 return NULL;
6724 }
6725
6726 void
tun_show_debug(struct tuntap * tt)6727 tun_show_debug(struct tuntap *tt)
6728 {
6729 if (tt->windows_driver == WINDOWS_DRIVER_TAP_WINDOWS6)
6730 {
6731 struct buffer out = alloc_buf(1024);
6732 DWORD len;
6733 while (DeviceIoControl(tt->hand, TAP_WIN_IOCTL_GET_LOG_LINE,
6734 BSTR(&out), BCAP(&out),
6735 BSTR(&out), BCAP(&out),
6736 &len, NULL))
6737 {
6738 msg(D_TAP_WIN_DEBUG, "TAP-Windows: %s", BSTR(&out));
6739 }
6740 free_buf(&out);
6741 }
6742 }
6743
6744 static void
netsh_delete_address_dns(const struct tuntap * tt,bool ipv6,struct gc_arena * gc)6745 netsh_delete_address_dns(const struct tuntap *tt, bool ipv6, struct gc_arena *gc)
6746 {
6747 const char *ifconfig_ip_local;
6748 struct argv argv = argv_new();
6749
6750 /* delete ipvX dns servers if any were set */
6751 int len = ipv6 ? tt->options.dns6_len : tt->options.dns_len;
6752 if (len > 0)
6753 {
6754 argv_printf(&argv,
6755 "%s%s interface %s delete dns %lu all",
6756 get_win_sys_path(),
6757 NETSH_PATH_SUFFIX,
6758 ipv6 ? "ipv6" : "ipv4",
6759 tt->adapter_index);
6760 netsh_command(&argv, 1, M_WARN);
6761 }
6762
6763 if (!ipv6 && tt->options.wins_len > 0)
6764 {
6765 argv_printf(&argv,
6766 "%s%s interface ipv4 delete winsservers %lu all",
6767 get_win_sys_path(),
6768 NETSH_PATH_SUFFIX,
6769 tt->adapter_index);
6770 netsh_command(&argv, 1, M_WARN);
6771 }
6772
6773 if (ipv6 && tt->type == DEV_TYPE_TUN)
6774 {
6775 delete_route_connected_v6_net(tt);
6776 }
6777
6778 /* "store=active" is needed in Windows 8(.1) to delete the
6779 * address we added (pointed out by Cedric Tabary).
6780 */
6781
6782 /* netsh interface ipvX delete address %lu %s */
6783 if (ipv6)
6784 {
6785 ifconfig_ip_local = print_in6_addr(tt->local_ipv6, 0, gc);
6786 }
6787 else
6788 {
6789 ifconfig_ip_local = print_in_addr_t(tt->local, 0, gc);
6790 }
6791 argv_printf(&argv,
6792 "%s%s interface %s delete address %lu %s store=active",
6793 get_win_sys_path(),
6794 NETSH_PATH_SUFFIX,
6795 ipv6 ? "ipv6" : "ipv4",
6796 tt->adapter_index,
6797 ifconfig_ip_local);
6798 netsh_command(&argv, 1, M_WARN);
6799
6800 argv_free(&argv);
6801 }
6802
6803 void
close_tun(struct tuntap * tt,openvpn_net_ctx_t * ctx)6804 close_tun(struct tuntap *tt, openvpn_net_ctx_t *ctx)
6805 {
6806 ASSERT(tt);
6807
6808 struct gc_arena gc = gc_new();
6809
6810 if (tt->did_ifconfig_ipv6_setup)
6811 {
6812 if (tt->options.ip_win32_type == IPW32_SET_MANUAL)
6813 {
6814 /* We didn't do ifconfig. */
6815 }
6816 else if (tt->options.msg_channel)
6817 {
6818 /* If IPv4 is not enabled, delete DNS domain here */
6819 if (!tt->did_ifconfig_setup)
6820 {
6821 do_dns_domain_service(false, tt);
6822 }
6823 if (tt->options.dns6_len > 0)
6824 {
6825 do_dns_service(false, AF_INET6, tt);
6826 }
6827 delete_route_connected_v6_net(tt);
6828 do_address_service(false, AF_INET6, tt);
6829 }
6830 else
6831 {
6832 netsh_delete_address_dns(tt, true, &gc);
6833 }
6834 }
6835
6836 if (tt->did_ifconfig_setup)
6837 {
6838 if (tt->options.ip_win32_type == IPW32_SET_MANUAL)
6839 {
6840 /* We didn't do ifconfig. */
6841 }
6842 else if (tt->options.ip_win32_type == IPW32_SET_DHCP_MASQ || tt->options.ip_win32_type == IPW32_SET_ADAPTIVE)
6843 {
6844 /* We don't have to clean the configuration with DHCP. */
6845 }
6846 else if (tt->options.msg_channel)
6847 {
6848 do_dns_domain_service(false, tt);
6849 do_dns_service(false, AF_INET, tt);
6850 do_address_service(false, AF_INET, tt);
6851 }
6852 else if (tt->options.ip_win32_type == IPW32_SET_NETSH)
6853 {
6854 netsh_delete_address_dns(tt, false, &gc);
6855 }
6856 }
6857
6858 if (tt->ipapi_context_defined)
6859 {
6860 DWORD status;
6861 if ((status = DeleteIPAddress(tt->ipapi_context)) != NO_ERROR)
6862 {
6863 msg(M_WARN, "Warning: DeleteIPAddress[%u] failed on TAP-Windows adapter, status=%u : %s",
6864 (unsigned int)tt->ipapi_context,
6865 (unsigned int)status,
6866 strerror_win32(status, &gc));
6867 }
6868 }
6869
6870 dhcp_release(tt);
6871
6872 if (tt->hand != NULL)
6873 {
6874 dmsg(D_WIN32_IO_LOW, "Attempting CancelIO on TAP-Windows adapter");
6875 if (!CancelIo(tt->hand))
6876 {
6877 msg(M_WARN | M_ERRNO, "Warning: CancelIO failed on TAP-Windows adapter");
6878 }
6879 }
6880
6881 dmsg(D_WIN32_IO_LOW, "Attempting close of overlapped read event on TAP-Windows adapter");
6882 overlapped_io_close(&tt->reads);
6883
6884 dmsg(D_WIN32_IO_LOW, "Attempting close of overlapped write event on TAP-Windows adapter");
6885 overlapped_io_close(&tt->writes);
6886
6887 if (tt->hand != NULL)
6888 {
6889 dmsg(D_WIN32_IO_LOW, "Attempting CloseHandle on TAP-Windows adapter");
6890 if (!CloseHandle(tt->hand))
6891 {
6892 msg(M_WARN | M_ERRNO, "Warning: CloseHandle failed on TAP-Windows adapter");
6893 }
6894 }
6895
6896 if (tt->actual_name)
6897 {
6898 free(tt->actual_name);
6899 }
6900
6901 if (tt->windows_driver == WINDOWS_DRIVER_WINTUN)
6902 {
6903 CloseHandle(tt->rw_handle.read);
6904 CloseHandle(tt->rw_handle.write);
6905 UnmapViewOfFile(tt->wintun_send_ring);
6906 UnmapViewOfFile(tt->wintun_receive_ring);
6907 CloseHandle(tt->wintun_send_ring_handle);
6908 CloseHandle(tt->wintun_receive_ring_handle);
6909 }
6910
6911
6912 clear_tuntap(tt);
6913 free(tt);
6914 gc_free(&gc);
6915 }
6916
6917 /*
6918 * Convert --ip-win32 constants between index and ascii form.
6919 */
6920
6921 struct ipset_names {
6922 const char *short_form;
6923 };
6924
6925 /* Indexed by IPW32_SET_x */
6926 static const struct ipset_names ipset_names[] = {
6927 {"manual"},
6928 {"netsh"},
6929 {"ipapi"},
6930 {"dynamic"},
6931 {"adaptive"}
6932 };
6933
6934 int
ascii2ipset(const char * name)6935 ascii2ipset(const char *name)
6936 {
6937 int i;
6938 ASSERT(IPW32_SET_N == SIZE(ipset_names));
6939 for (i = 0; i < IPW32_SET_N; ++i)
6940 {
6941 if (!strcmp(name, ipset_names[i].short_form))
6942 {
6943 return i;
6944 }
6945 }
6946 return -1;
6947 }
6948
6949 const char *
ipset2ascii(int index)6950 ipset2ascii(int index)
6951 {
6952 ASSERT(IPW32_SET_N == SIZE(ipset_names));
6953 if (index < 0 || index >= IPW32_SET_N)
6954 {
6955 return "[unknown --ip-win32 type]";
6956 }
6957 else
6958 {
6959 return ipset_names[index].short_form;
6960 }
6961 }
6962
6963 const char *
ipset2ascii_all(struct gc_arena * gc)6964 ipset2ascii_all(struct gc_arena *gc)
6965 {
6966 struct buffer out = alloc_buf_gc(256, gc);
6967 int i;
6968
6969 ASSERT(IPW32_SET_N == SIZE(ipset_names));
6970 for (i = 0; i < IPW32_SET_N; ++i)
6971 {
6972 if (i)
6973 {
6974 buf_printf(&out, " ");
6975 }
6976 buf_printf(&out, "[%s]", ipset2ascii(i));
6977 }
6978 return BSTR(&out);
6979 }
6980
6981 #else /* generic */
6982
6983 void
open_tun(const char * dev,const char * dev_type,const char * dev_node,struct tuntap * tt)6984 open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
6985 {
6986 open_tun_generic(dev, dev_type, dev_node, true, tt);
6987 }
6988
6989 void
close_tun(struct tuntap * tt,openvpn_net_ctx_t * ctx)6990 close_tun(struct tuntap *tt, openvpn_net_ctx_t *ctx)
6991 {
6992 ASSERT(tt);
6993
6994 close_tun_generic(tt);
6995 free(tt);
6996 }
6997
6998 int
write_tun(struct tuntap * tt,uint8_t * buf,int len)6999 write_tun(struct tuntap *tt, uint8_t *buf, int len)
7000 {
7001 return write(tt->fd, buf, len);
7002 }
7003
7004 int
read_tun(struct tuntap * tt,uint8_t * buf,int len)7005 read_tun(struct tuntap *tt, uint8_t *buf, int len)
7006 {
7007 return read(tt->fd, buf, len);
7008 }
7009
7010 #endif /* if defined (TARGET_ANDROID) */
7011