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