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