OpenVPN
interactive.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) 2012-2026 Heiko Hund <heiko.hund@sophos.com>
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, see <https://www.gnu.org/licenses/>.
21 */
22
23
24#include "service.h"
25
26#include <ws2tcpip.h>
27#include <iphlpapi.h>
28#include <userenv.h>
29#include <accctrl.h>
30#include <aclapi.h>
31#include <stdio.h>
32#include <sddl.h>
33#include <shellapi.h>
34#include <mstcpip.h>
35#include <inttypes.h>
36#include <malloc.h>
37
38#include <versionhelpers.h>
39
40#include "openvpn-msg.h"
41#include "validate.h"
42#include "wfp_block.h"
43
44#define IO_TIMEOUT 2000 /*ms*/
45
46#define ERROR_OPENVPN_STARTUP 0x20000000
47#define ERROR_STARTUP_DATA 0x20000001
48#define ERROR_MESSAGE_DATA 0x20000002
49#define ERROR_MESSAGE_TYPE 0x20000003
50
51static SERVICE_STATUS_HANDLE service;
52static SERVICE_STATUS status = { .dwServiceType = SERVICE_WIN32_SHARE_PROCESS };
53static HANDLE exit_event = NULL;
55static HANDLE rdns_semaphore = NULL;
56#define RDNS_TIMEOUT 600 /* seconds to wait for the semaphore */
57
58#define TUN_IOCTL_REGISTER_RINGS \
59 CTL_CODE(51820U, 0x970U, METHOD_BUFFERED, FILE_READ_DATA | FILE_WRITE_DATA)
60
62 _L(PACKAGE_NAME) L" Interactive Service",
63 SERVICE_DEPENDENCIES, SERVICE_AUTO_START };
64
65
66typedef struct
67{
68 WCHAR *directory;
69 WCHAR *options;
70 WCHAR *std_input;
72
73
74/* Datatype for linked lists */
75typedef struct _list_item
76{
78 LPVOID data;
80
81
82/* Datatypes for undo information */
96
97typedef struct
98{
99 HANDLE engine;
100 DWORD index;
104
105typedef struct
106{
107 char itf_name[256];
108 PWSTR domains;
110
125
126typedef struct
127{
128 CHAR addresses[NRPT_ADDR_NUM * NRPT_ADDR_SIZE];
129 WCHAR domains[512]; /* MULTI_SZ string */
130 DWORD domains_size; /* bytes in domains */
132
133
134static DWORD
135AddListItem(list_item_t **pfirst, LPVOID data)
136{
137 list_item_t *new_item = malloc(sizeof(list_item_t));
138 if (new_item == NULL)
139 {
140 return ERROR_OUTOFMEMORY;
141 }
142
143 new_item->next = *pfirst;
144 new_item->data = data;
145
146 *pfirst = new_item;
147 return NO_ERROR;
148}
149
150typedef BOOL (*match_fn_t)(LPVOID item, LPVOID ctx);
151
152static LPVOID
153RemoveListItem(list_item_t **pfirst, match_fn_t match, LPVOID ctx)
154{
155 LPVOID data = NULL;
156 list_item_t **pnext;
157
158 for (pnext = pfirst; *pnext; pnext = &(*pnext)->next)
159 {
160 list_item_t *item = *pnext;
161 if (!match(item->data, ctx))
162 {
163 continue;
164 }
165
166 /* Found item, remove from the list and free memory */
167 *pnext = item->next;
168 data = item->data;
169 free(item);
170 break;
171 }
172 return data;
173}
174
175
176static HANDLE
177CloseHandleEx(LPHANDLE handle)
178{
179 if (handle && *handle && *handle != INVALID_HANDLE_VALUE)
180 {
181 CloseHandle(*handle);
182 *handle = INVALID_HANDLE_VALUE;
183 }
184 return INVALID_HANDLE_VALUE;
185}
186
187static HANDLE
188InitOverlapped(LPOVERLAPPED overlapped)
189{
190 ZeroMemory(overlapped, sizeof(OVERLAPPED));
191 overlapped->hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
192 return overlapped->hEvent;
193}
194
195static BOOL
196ResetOverlapped(LPOVERLAPPED overlapped)
197{
198 HANDLE io_event = overlapped->hEvent;
199 if (!ResetEvent(io_event))
200 {
201 return FALSE;
202 }
203 ZeroMemory(overlapped, sizeof(OVERLAPPED));
204 overlapped->hEvent = io_event;
205 return TRUE;
206}
207
208
216
217static DWORD
218AsyncPipeOp(async_op_t op, HANDLE pipe, LPVOID buffer, DWORD size, DWORD count, LPHANDLE events)
219{
220 DWORD i;
221 BOOL success;
222 HANDLE io_event;
223 DWORD res, bytes = 0;
224 OVERLAPPED overlapped;
225 LPHANDLE handles = NULL;
226
227 io_event = InitOverlapped(&overlapped);
228 if (!io_event)
229 {
230 goto out;
231 }
232
233 handles = malloc((count + 1) * sizeof(HANDLE));
234 if (!handles)
235 {
236 goto out;
237 }
238
239 if (op == write)
240 {
241 success = WriteFile(pipe, buffer, size, NULL, &overlapped);
242 }
243 else
244 {
245 success = ReadFile(pipe, buffer, size, NULL, &overlapped);
246 }
247 if (!success && GetLastError() != ERROR_IO_PENDING && GetLastError() != ERROR_MORE_DATA)
248 {
249 goto out;
250 }
251
252 handles[0] = io_event;
253 for (i = 0; i < count; i++)
254 {
255 handles[i + 1] = events[i];
256 }
257
258 res = WaitForMultipleObjects(count + 1, handles, FALSE, op == peek ? INFINITE : IO_TIMEOUT);
259 if (res != WAIT_OBJECT_0)
260 {
261 CancelIo(pipe);
262 goto out;
263 }
264
265 if (op == peek || op == peek_timed)
266 {
267 PeekNamedPipe(pipe, NULL, 0, NULL, &bytes, NULL);
268 }
269 else
270 {
271 GetOverlappedResult(pipe, &overlapped, &bytes, TRUE);
272 }
273
274out:
275 CloseHandleEx(&io_event);
276 free(handles);
277 return bytes;
278}
279
280static DWORD
281PeekNamedPipeAsync(HANDLE pipe, DWORD count, LPHANDLE events)
282{
283 return AsyncPipeOp(peek, pipe, NULL, 0, count, events);
284}
285
286static DWORD
287PeekNamedPipeAsyncTimed(HANDLE pipe, DWORD count, LPHANDLE events)
288{
289 return AsyncPipeOp(peek_timed, pipe, NULL, 0, count, events);
290}
291
292static DWORD
293ReadPipeAsync(HANDLE pipe, LPVOID buffer, DWORD size, DWORD count, LPHANDLE events)
294{
295 return AsyncPipeOp(read, pipe, buffer, size, count, events);
296}
297
298static DWORD
299WritePipeAsync(HANDLE pipe, LPVOID data, DWORD size, DWORD count, LPHANDLE events)
300{
301 return AsyncPipeOp(write, pipe, data, size, count, events);
302}
303
304static VOID
305ReturnProcessId(HANDLE pipe, DWORD pid, DWORD count, LPHANDLE events)
306{
307 const WCHAR msg[] = L"Process ID";
308 WCHAR buf[22 + _countof(msg)]; /* 10 chars each for error and PID and 2 for line breaks */
309
310 /*
311 * Same format as error messages (3 line string) with error = 0 in
312 * 0x%08x format, PID on line 2 and a description "Process ID" on line 3
313 */
314 swprintf(buf, _countof(buf), L"0x%08x\n0x%08lx\n%ls", 0, pid, msg);
315
316 WritePipeAsync(pipe, buf, (DWORD)(wcslen(buf) * 2), count, events);
317}
318
319static VOID
320ReturnError(HANDLE pipe, DWORD error, LPCWSTR func, DWORD count, LPHANDLE events)
321{
322 DWORD result_len;
323 LPWSTR result = L"0xffffffff\nFormatMessage failed\nCould not return result";
324 DWORD_PTR args[] = { (DWORD_PTR)error, (DWORD_PTR)func, (DWORD_PTR) "" };
325
326 if (error != ERROR_OPENVPN_STARTUP)
327 {
328 FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER
329 | FORMAT_MESSAGE_IGNORE_INSERTS,
330 0, error, 0, (LPWSTR)&args[2], 0, NULL);
331 }
332
333 result_len = FormatMessageW(
334 FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_ARGUMENT_ARRAY,
335 L"0x%1!08x!\n%2!s!\n%3!s!", 0, 0, (LPWSTR)&result, 0, (va_list *)args);
336
337 WritePipeAsync(pipe, result, (DWORD)(wcslen(result) * 2), count, events);
339
340 if (error != ERROR_OPENVPN_STARTUP)
341 {
342 LocalFree((LPVOID)args[2]);
343 }
344 if (result_len)
345 {
346 LocalFree(result);
347 }
348}
349
350
351static VOID
352ReturnLastError(HANDLE pipe, LPCWSTR func)
353{
354 ReturnError(pipe, GetLastError(), func, 1, &exit_event);
355}
356
368static BOOL
369StartsWithNonOption(const WCHAR *cmdline)
370{
371 int argc;
372 WCHAR **argv = CommandLineToArgvW(cmdline, &argc);
373 /* "openvpn --msg-channel <handle> <arg>..." */
374 BOOL ret = argv && argc > 3 && !IsOption(argv[3]);
375
376 LocalFree(argv);
377 return ret;
378}
379
380/*
381 * Validate options against a white list. Also check the config_file is
382 * inside the config_dir. The white list is defined in validate.c
383 * The options are taken from the command line openvpn is started with,
384 * so that they are split exactly like openvpn.exe does it.
385 * Returns true on success, false on error with reason set in errmsg.
386 */
387static BOOL
388ValidateOptions(HANDLE pipe, const WCHAR *workdir, const WCHAR *cmdline, WCHAR *errmsg,
389 DWORD capacity)
390{
391 WCHAR **argv;
392 int argc;
393 BOOL ret = FALSE;
394 int i;
395 const WCHAR *msg1 = L"You have specified a config file location (%ls relative to %ls)"
396 L" that requires admin approval. This error may be avoided"
397 L" by adding your account to the \"%ls\" group";
398
399 const WCHAR *msg2 = L"You have specified an option (%ls) that may be used"
400 L" only with admin approval. This error may be avoided"
401 L" by adding your account to the \"%ls\" group";
402
403 /* Skip "openvpn --msg-channel <handle>" added by the service */
404 const int first = 3;
405
406 argv = CommandLineToArgvW(cmdline, &argc);
407
408 if (!argv)
409 {
410 swprintf(errmsg, capacity,
411 L"Cannot validate options: CommandLineToArgvW failed with error = 0x%08lx",
412 GetLastError());
413 goto out;
414 }
415
416 if (argc <= first) /* no options */
417 {
418 ret = TRUE;
419 goto out;
420 }
421
422 for (i = first; i < argc; ++i)
423 {
424 if (!IsOption(argv[i]))
425 {
426 continue;
427 }
428
429 if (!CheckOption(workdir, argc - i, &argv[i], &settings))
430 {
431 if (wcscmp(L"--config", argv[i]) == 0 && argc - i > 1)
432 {
433 swprintf(errmsg, capacity, msg1, argv[i + 1], workdir, settings.ovpn_admin_group);
434 }
435 else
436 {
437 swprintf(errmsg, capacity, msg2, argv[i], settings.ovpn_admin_group);
438 }
439 goto out;
440 }
441 }
442
443 /* all options passed */
444 ret = TRUE;
445
446out:
447 if (argv)
448 {
449 LocalFree(argv);
450 }
451 return ret;
452}
453
454static BOOL
455GetStartupData(HANDLE pipe, STARTUP_DATA *sud)
456{
457 size_t size, len;
458 WCHAR *data = NULL;
459 DWORD bytes, read;
460
461 bytes = PeekNamedPipeAsyncTimed(pipe, 1, &exit_event);
462 if (bytes == 0)
463 {
464 MsgToEventLog(M_ERR, L"Timeout waiting for startup data");
465 ReturnError(pipe, ERROR_STARTUP_DATA, L"GetStartupData (timeout)", 1, &exit_event);
466 goto err;
467 }
468
469 size = bytes / sizeof(*data);
470 if ((size == 0) || (size > 4096)) /* our startup data is 1024 wchars at the moment */
471 {
472 MsgToEventLog(M_SYSERR, L"malformed startup data: %lu bytes received", size);
473 ReturnError(pipe, ERROR_STARTUP_DATA, L"GetStartupData", 1, &exit_event);
474 goto err;
475 }
476
477 data = malloc(bytes);
478 if (data == NULL)
479 {
480 MsgToEventLog(M_SYSERR, L"malloc failed");
481 ReturnLastError(pipe, L"malloc");
482 goto err;
483 }
484
485 read = ReadPipeAsync(pipe, data, bytes, 1, &exit_event);
486 if (bytes != read)
487 {
488 MsgToEventLog(M_SYSERR, L"ReadPipeAsync failed");
489 ReturnLastError(pipe, L"ReadPipeAsync");
490 goto err;
491 }
492
493 if (data[size - 1] != 0)
494 {
495 MsgToEventLog(M_ERR, L"Startup data is not NULL terminated");
496 ReturnError(pipe, ERROR_STARTUP_DATA, L"GetStartupData", 1, &exit_event);
497 goto err;
498 }
499
500 sud->directory = data;
501 len = wcslen(sud->directory) + 1;
502 size -= len;
503 if (size == 0)
504 {
505 MsgToEventLog(M_ERR, L"Startup data ends at working directory");
506 ReturnError(pipe, ERROR_STARTUP_DATA, L"GetStartupData", 1, &exit_event);
507 goto err;
508 }
509
510 sud->options = sud->directory + len;
511 len = wcslen(sud->options) + 1;
512 size -= len;
513 if (size == 0)
514 {
515 MsgToEventLog(M_ERR, L"Startup data ends at command line options");
516 ReturnError(pipe, ERROR_STARTUP_DATA, L"GetStartupData", 1, &exit_event);
517 goto err;
518 }
519
520 sud->std_input = sud->options + len;
521 return TRUE;
522
523err:
524 sud->directory = NULL; /* caller must not free() */
525 free(data);
526 return FALSE;
527}
528
529
530static VOID
532{
533 free(sud->directory);
534}
535
536#if defined(__GNUC__) || defined(__clang__)
537#pragma GCC diagnostic push
538#pragma GCC diagnostic ignored "-Wsign-conversion"
539#endif
540
541static SOCKADDR_INET
542sockaddr_inet(short family, const inet_address_t *addr)
543{
544 SOCKADDR_INET sa_inet;
545 ZeroMemory(&sa_inet, sizeof(sa_inet));
546 sa_inet.si_family = family;
547 if (family == AF_INET)
548 {
549 sa_inet.Ipv4.sin_addr = addr->ipv4;
550 }
551 else if (family == AF_INET6)
552 {
553 sa_inet.Ipv6.sin6_addr = addr->ipv6;
554 }
555 return sa_inet;
556}
557
558static DWORD
559InterfaceLuid(const char *iface_name, PNET_LUID luid)
560{
561 NETIO_STATUS convert_status;
562 LPWSTR wide_name = utf8to16(iface_name);
563
564 if (wide_name)
565 {
566 convert_status = ConvertInterfaceAliasToLuid(wide_name, luid);
567 free(wide_name);
568 }
569 else
570 {
571 convert_status = ERROR_OUTOFMEMORY;
572 }
573 return convert_status;
574}
575
576static BOOL
577CmpAddress(LPVOID item, LPVOID address)
578{
579 return memcmp(item, address, sizeof(MIB_UNICASTIPADDRESS_ROW)) == 0 ? TRUE : FALSE;
580}
581
582static DWORD
583DeleteAddress(PMIB_UNICASTIPADDRESS_ROW addr_row)
584{
585 return DeleteUnicastIpAddressEntry(addr_row);
586}
587
588static DWORD
590{
591 DWORD err;
592 PMIB_UNICASTIPADDRESS_ROW addr_row;
593 BOOL add = msg->header.type == msg_add_address;
594
595 /* enforce null-termination of the interface name from client */
596 msg->iface.name[_countof(msg->iface.name) - 1] = '\0';
597
598 addr_row = malloc(sizeof(*addr_row));
599 if (addr_row == NULL)
600 {
601 return ERROR_OUTOFMEMORY;
602 }
603
604 InitializeUnicastIpAddressEntry(addr_row);
605 addr_row->Address = sockaddr_inet(msg->family, &msg->address);
606 addr_row->OnLinkPrefixLength = (UINT8)msg->prefix_len;
607
608 if (msg->iface.index != TUN_ADAPTER_INDEX_INVALID)
609 {
610 addr_row->InterfaceIndex = msg->iface.index;
611 }
612 else
613 {
614 NET_LUID luid;
615 err = InterfaceLuid(msg->iface.name, &luid);
616 if (err)
617 {
618 goto out;
619 }
620 addr_row->InterfaceLuid = luid;
621 }
622
623 if (add)
624 {
625 err = CreateUnicastIpAddressEntry(addr_row);
626 if (err)
627 {
628 goto out;
629 }
630
631 err = AddListItem(&(*lists)[address], addr_row);
632 if (err)
633 {
634 DeleteAddress(addr_row);
635 }
636 }
637 else
638 {
639 err = DeleteAddress(addr_row);
640 if (err)
641 {
642 goto out;
643 }
644
645 free(RemoveListItem(&(*lists)[address], CmpAddress, addr_row));
646 }
647
648out:
649 if (!add || err)
650 {
651 free(addr_row);
652 }
653
654 return err;
655}
656
657static BOOL
658CmpRoute(LPVOID item, LPVOID route)
659{
660 return memcmp(item, route, sizeof(MIB_IPFORWARD_ROW2)) == 0 ? TRUE : FALSE;
661}
662
663static DWORD
664DeleteRoute(PMIB_IPFORWARD_ROW2 fwd_row)
665{
666 return DeleteIpForwardEntry2(fwd_row);
667}
668
669static DWORD
671{
672 DWORD err;
673 PMIB_IPFORWARD_ROW2 fwd_row;
674 BOOL add = msg->header.type == msg_add_route;
675
676 /* enforce null-termination of the interface name from client */
677 msg->iface.name[_countof(msg->iface.name) - 1] = '\0';
678
679 fwd_row = malloc(sizeof(*fwd_row));
680 if (fwd_row == NULL)
681 {
682 return ERROR_OUTOFMEMORY;
683 }
684
685 ZeroMemory(fwd_row, sizeof(*fwd_row));
686 fwd_row->ValidLifetime = 0xffffffff;
687 fwd_row->PreferredLifetime = 0xffffffff;
688 fwd_row->Protocol = MIB_IPPROTO_NETMGMT;
689 fwd_row->Metric = msg->metric;
690 fwd_row->DestinationPrefix.Prefix = sockaddr_inet(msg->family, &msg->prefix);
691 fwd_row->DestinationPrefix.PrefixLength = (UINT8)msg->prefix_len;
692 fwd_row->NextHop = sockaddr_inet(msg->family, &msg->gateway);
693
694 if (msg->iface.index != TUN_ADAPTER_INDEX_INVALID)
695 {
696 fwd_row->InterfaceIndex = msg->iface.index;
697 }
698 else if (strlen(msg->iface.name))
699 {
700 NET_LUID luid;
701 err = InterfaceLuid(msg->iface.name, &luid);
702 if (err)
703 {
704 goto out;
705 }
706 fwd_row->InterfaceLuid = luid;
707 }
708
709 if (add)
710 {
711 err = CreateIpForwardEntry2(fwd_row);
712 if (err)
713 {
714 goto out;
715 }
716
717 err = AddListItem(&(*lists)[route], fwd_row);
718 if (err)
719 {
720 DeleteRoute(fwd_row);
721 }
722 }
723 else
724 {
725 err = DeleteRoute(fwd_row);
726 if (err)
727 {
728 goto out;
729 }
730
731 free(RemoveListItem(&(*lists)[route], CmpRoute, fwd_row));
732 }
733
734out:
735 if (!add || err)
736 {
737 free(fwd_row);
738 }
739
740 return err;
741}
742
743
744static DWORD
746{
747 if (msg->family == AF_INET)
748 {
749 return FlushIpNetTable(msg->iface.index);
750 }
751
752 return FlushIpNetTable2(msg->family, msg->iface.index);
753}
754
755static void
756BlockDNSErrHandler(DWORD err, const char *msg)
757{
758 WCHAR buf[256];
759 LPCWSTR err_str;
760
761 if (!err)
762 {
763 return;
764 }
765
766 err_str = L"Unknown Win32 Error";
767
768 if (FormatMessageW(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
769 NULL, err, 0, buf, _countof(buf), NULL))
770 {
771 err_str = buf;
772 }
773
774 MsgToEventLog(M_ERR, L"%hs (status = %lu): %ls", msg, err, err_str);
775}
776
777/* Use an always-true match_fn to get the head of the list */
778static BOOL
779CmpAny(LPVOID item, LPVOID any)
780{
781 return TRUE;
782}
783
784static DWORD
786{
787 DWORD err = 0;
788 wfp_block_data_t *block_data = RemoveListItem(&(*lists)[wfp_block], CmpAny, NULL);
789
790 if (block_data)
791 {
792 err = delete_wfp_block_filters(block_data->engine);
793 if (block_data->metric_v4 >= 0)
794 {
795 set_interface_metric(block_data->index, AF_INET, block_data->metric_v4);
796 }
797 if (block_data->metric_v6 >= 0)
798 {
799 set_interface_metric(block_data->index, AF_INET6, block_data->metric_v6);
800 }
801 free(block_data);
802 }
803 else
804 {
805 MsgToEventLog(M_ERR, L"No previous block filters to delete");
806 }
807
808 return err;
809}
810
811static DWORD
813{
814 DWORD err = 0;
815 wfp_block_data_t *block_data = NULL;
816 HANDLE engine = NULL;
817 LPCWSTR exe_path;
818 BOOL dns_only;
819
820 exe_path = settings.exe_path;
821 dns_only = (msg->flags == wfp_block_dns);
822
823 err = add_wfp_block_filters(&engine, msg->iface.index, exe_path, BlockDNSErrHandler, dns_only);
824 if (!err)
825 {
826 block_data = malloc(sizeof(wfp_block_data_t));
827 if (!block_data)
828 {
829 err = ERROR_OUTOFMEMORY;
830 goto out;
831 }
832 block_data->engine = engine;
833 block_data->index = msg->iface.index;
834 int is_auto = 0;
835 block_data->metric_v4 = get_interface_metric(msg->iface.index, AF_INET, &is_auto);
836 if (is_auto)
837 {
838 block_data->metric_v4 = 0;
839 }
840 block_data->metric_v6 = get_interface_metric(msg->iface.index, AF_INET6, &is_auto);
841 if (is_auto)
842 {
843 block_data->metric_v6 = 0;
844 }
845
846 err = AddListItem(&(*lists)[wfp_block], block_data);
847 if (!err)
848 {
849 err = set_interface_metric(msg->iface.index, AF_INET, WFP_BLOCK_IFACE_METRIC);
850 if (!err)
851 {
852 /* for IPv6, we intentionally ignore errors, because
853 * otherwise block-dns activation will fail if a user or
854 * admin has disabled IPv6 on the tun/tap/dco interface
855 * (if OpenVPN wants IPv6 ifconfig, we'll fail there)
856 */
857 set_interface_metric(msg->iface.index, AF_INET6, WFP_BLOCK_IFACE_METRIC);
858 }
859 if (err)
860 {
861 /* delete the filters, remove undo item and free interface data */
862 DeleteWfpBlock(lists);
863 engine = NULL;
864 }
865 }
866 }
867
868out:
869 if (err && engine)
870 {
872 free(block_data);
873 }
874
875 return err;
876}
877
878static DWORD
880{
881 if (msg->header.type == msg_add_wfp_block)
882 {
883 return AddWfpBlock(msg, lists);
884 }
885 else
886 {
887 return DeleteWfpBlock(lists);
888 }
889}
890
891/*
892 * Execute a command and return its exit code. If timeout > 0, terminate
893 * the process if still running after timeout milliseconds. In that case
894 * the return value is the windows error code WAIT_TIMEOUT = 0x102
895 */
896static DWORD
897ExecCommand(const WCHAR *argv0, const WCHAR *cmdline, DWORD timeout)
898{
899 DWORD exit_code;
900 STARTUPINFOW si;
901 PROCESS_INFORMATION pi;
902 DWORD proc_flags = CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT;
903 WCHAR *cmdline_dup = NULL;
904
905 ZeroMemory(&si, sizeof(si));
906 ZeroMemory(&pi, sizeof(pi));
907
908 si.cb = sizeof(si);
909
910 /* CreateProcess needs a modifiable cmdline: make a copy */
911 cmdline_dup = _wcsdup(cmdline);
912 if (cmdline_dup
913 && CreateProcessW(argv0, cmdline_dup, NULL, NULL, FALSE, proc_flags, NULL, NULL, &si, &pi))
914 {
915 WaitForSingleObject(pi.hProcess, timeout ? timeout : INFINITE);
916 if (!GetExitCodeProcess(pi.hProcess, &exit_code))
917 {
918 MsgToEventLog(M_SYSERR, L"ExecCommand: Error getting exit_code:");
919 exit_code = GetLastError();
920 }
921 else if (exit_code == STILL_ACTIVE)
922 {
923 exit_code = WAIT_TIMEOUT; /* Windows error code 0x102 */
924
925 /* kill without impunity */
926 TerminateProcess(pi.hProcess, exit_code);
927 MsgToEventLog(M_ERR, L"ExecCommand: \"%ls %ls\" killed after timeout", argv0, cmdline);
928 }
929 else if (exit_code)
930 {
931 MsgToEventLog(M_ERR, L"ExecCommand: \"%ls %ls\" exited with status = %lu", argv0,
932 cmdline, exit_code);
933 }
934 else
935 {
936 MsgToEventLog(M_INFO, L"ExecCommand: \"%ls %ls\" completed", argv0, cmdline);
937 }
938
939 CloseHandle(pi.hProcess);
940 CloseHandle(pi.hThread);
941 }
942 else
943 {
944 exit_code = GetLastError();
945 MsgToEventLog(M_SYSERR, L"ExecCommand: could not run \"%ls %ls\" :", argv0, cmdline);
946 }
947
948 free(cmdline_dup);
949 return exit_code;
950}
951
952/*
953 * Entry point for register-dns thread.
954 */
955static DWORD WINAPI
956RegisterDNS(LPVOID unused)
957{
958 DWORD err;
959 DWORD timeout = RDNS_TIMEOUT * 1000; /* in milliseconds */
960
961 /* path of ipconfig command */
962 WCHAR ipcfg[MAX_PATH];
963
964 struct
965 {
966 WCHAR *argv0;
967 WCHAR *cmdline;
968 DWORD timeout;
969 } cmds[] = {
970 { ipcfg, L"ipconfig /flushdns", timeout },
971 { ipcfg, L"ipconfig /registerdns", timeout },
972 };
973
974 HANDLE wait_handles[2] = { rdns_semaphore, exit_event };
975
976 swprintf(ipcfg, MAX_PATH, L"%ls\\%ls", get_win_sys_path(), L"ipconfig.exe");
977
978 if (WaitForMultipleObjects(2, wait_handles, FALSE, timeout) == WAIT_OBJECT_0)
979 {
980 /* Semaphore locked */
981 for (size_t i = 0; i < _countof(cmds); ++i)
982 {
983 ExecCommand(cmds[i].argv0, cmds[i].cmdline, cmds[i].timeout);
984 }
985 err = 0;
986 if (!ReleaseSemaphore(rdns_semaphore, 1, NULL))
987 {
988 err =
989 MsgToEventLog(M_SYSERR, L"RegisterDNS: Failed to release regsiter-dns semaphore:");
990 }
991 }
992 else
993 {
994 MsgToEventLog(M_ERR, L"RegisterDNS: Failed to lock register-dns semaphore");
995 err = ERROR_SEM_TIMEOUT; /* Windows error code 0x79 */
996 }
997 return err;
998}
999
1000static DWORD
1002{
1003 DWORD err;
1004 HANDLE thread = NULL;
1005
1006 /* Delegate this job to a sub-thread */
1007 thread = CreateThread(NULL, 0, RegisterDNS, NULL, 0, NULL);
1008
1009 /*
1010 * We don't add these thread handles to the undo list -- the thread and
1011 * processes it spawns are all supposed to terminate or timeout by themselves.
1012 */
1013 if (thread)
1014 {
1015 err = 0;
1016 CloseHandle(thread);
1017 }
1018 else
1019 {
1020 err = GetLastError();
1021 }
1022
1023 return err;
1024}
1025
1035static DWORD
1036netsh_wins_cmd(const wchar_t *action, DWORD if_index, const wchar_t *addr)
1037{
1038 DWORD err = 0;
1039 int timeout = 30000; /* in msec */
1040 wchar_t argv0[MAX_PATH];
1041 wchar_t *cmdline = NULL;
1042 const wchar_t *addr_static = (wcscmp(action, L"set") == 0) ? L"static" : L"";
1043
1044 if (!addr)
1045 {
1046 if (wcscmp(action, L"delete") == 0)
1047 {
1048 addr = L"all";
1049 }
1050 else /* nothing to do -- return success*/
1051 {
1052 goto out;
1053 }
1054 }
1055
1056 /* Path of netsh */
1057 swprintf(argv0, _countof(argv0), L"%ls\\%ls", get_win_sys_path(), L"netsh.exe");
1058
1059 /* cmd template:
1060 * netsh interface ip $action wins $if_name $static $addr
1061 */
1062 const wchar_t *fmt = L"netsh interface ip %ls wins %lu %ls %ls";
1063
1064 /* max cmdline length in wchars -- include room for worst case and some */
1065 size_t ncmdline = wcslen(fmt) + 11 /*if_index*/ + wcslen(action) + wcslen(addr)
1066 + wcslen(addr_static) + 32 + 1;
1067 cmdline = malloc(ncmdline * sizeof(wchar_t));
1068 if (!cmdline)
1069 {
1070 err = ERROR_OUTOFMEMORY;
1071 goto out;
1072 }
1073
1074 swprintf(cmdline, ncmdline, fmt, action, if_index, addr_static, addr);
1075
1076 err = ExecCommand(argv0, cmdline, timeout);
1077
1078out:
1079 free(cmdline);
1080 return err;
1081}
1082
1089static BOOL
1091{
1092 typedef NTSTATUS(__stdcall * publish_fn_t)(DWORD StateNameLo, DWORD StateNameHi, DWORD TypeId,
1093 DWORD Buffer, DWORD Length, DWORD ExplicitScope);
1094 publish_fn_t RtlPublishWnfStateData;
1095 const DWORD WNF_GPOL_SYSTEM_CHANGES_HI = 0x0D891E2A;
1096 const DWORD WNF_GPOL_SYSTEM_CHANGES_LO = 0xA3BC0875;
1097 BOOL ret = FALSE;
1098
1099 HMODULE ntdll = LoadLibraryA("ntdll.dll");
1100 if (ntdll == NULL)
1101 {
1102 return FALSE;
1103 }
1104
1105 RtlPublishWnfStateData = (publish_fn_t)GetProcAddress(ntdll, "RtlPublishWnfStateData");
1106 if (RtlPublishWnfStateData == NULL)
1107 {
1108 goto cleanup;
1109 }
1110
1111 if (RtlPublishWnfStateData(WNF_GPOL_SYSTEM_CHANGES_LO, WNF_GPOL_SYSTEM_CHANGES_HI, 0, 0, 0, 0)
1112 != ERROR_SUCCESS)
1113 {
1114 goto cleanup;
1115 }
1116
1117 ret = TRUE;
1118cleanup:
1119 FreeLibrary(ntdll);
1120 return ret;
1121}
1122
1129static BOOL
1131{
1132 typedef NTSTATUS (*publish_fn_t)(INT64 StateName, INT64 TypeId, INT64 Buffer,
1133 unsigned int Length, INT64 ExplicitScope);
1134 publish_fn_t RtlPublishWnfStateData;
1135 const INT64 WNF_GPOL_SYSTEM_CHANGES = 0x0D891E2AA3BC0875;
1136 BOOL ret = FALSE;
1137
1138 HMODULE ntdll = LoadLibraryA("ntdll.dll");
1139 if (ntdll == NULL)
1140 {
1141 return FALSE;
1142 }
1143
1144 RtlPublishWnfStateData = (publish_fn_t)GetProcAddress(ntdll, "RtlPublishWnfStateData");
1145 if (RtlPublishWnfStateData == NULL)
1146 {
1147 goto cleanup;
1148 }
1149
1150 if (RtlPublishWnfStateData(WNF_GPOL_SYSTEM_CHANGES, 0, 0, 0, 0) != ERROR_SUCCESS)
1151 {
1152 goto cleanup;
1153 }
1154
1155 ret = TRUE;
1156cleanup:
1157 FreeLibrary(ntdll);
1158 return ret;
1159}
1160
1166static BOOL
1168{
1169 SYSTEM_INFO si;
1170 GetSystemInfo(&si);
1171 const BOOL win_32bit = si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL;
1172 return win_32bit ? ApplyGpolSettings32() : ApplyGpolSettings64();
1173}
1174
1182static BOOL
1183ApplyDnsSettings(BOOL apply_gpol)
1184{
1185 BOOL res = FALSE;
1186 SC_HANDLE scm = NULL;
1187 SC_HANDLE dnssvc = NULL;
1188
1189 if (apply_gpol && ApplyGpolSettings() == FALSE)
1190 {
1191 MsgToEventLog(M_ERR, L"%S: sending GPOL notification failed", __func__);
1192 }
1193
1194 scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
1195 if (scm == NULL)
1196 {
1197 MsgToEventLog(M_ERR, L"%S: OpenSCManager call failed (%lu)", __func__, GetLastError());
1198 goto out;
1199 }
1200
1201 dnssvc = OpenServiceA(scm, "Dnscache", SERVICE_PAUSE_CONTINUE);
1202 if (dnssvc == NULL)
1203 {
1204 MsgToEventLog(M_ERR, L"%S: OpenService call failed (%lu)", __func__, GetLastError());
1205 goto out;
1206 }
1207
1208 SERVICE_STATUS control_status;
1209 if (ControlService(dnssvc, SERVICE_CONTROL_PARAMCHANGE, &control_status) == 0)
1210 {
1211 MsgToEventLog(M_ERR, L"%S: ControlService call failed (%lu)", __func__, GetLastError());
1212 goto out;
1213 }
1214
1215 res = TRUE;
1216
1217out:
1218 if (dnssvc)
1219 {
1220 CloseServiceHandle(dnssvc);
1221 }
1222 if (scm)
1223 {
1224 CloseServiceHandle(scm);
1225 }
1226 return res;
1227}
1228
1238static DWORD
1239InterfaceIdString(PCSTR itf_name, PWSTR str, size_t len)
1240{
1241 DWORD err;
1242 GUID guid;
1243 NET_LUID luid;
1244 PWSTR iid_str = NULL;
1245
1246 err = InterfaceLuid(itf_name, &luid);
1247 if (err)
1248 {
1249 PWSTR wide_name = utf8to16(itf_name);
1250 MsgToEventLog(M_ERR, L"%S: failed to convert itf alias '%s'", __func__, wide_name);
1251 free(wide_name);
1252 goto out;
1253 }
1254 err = ConvertInterfaceLuidToGuid(&luid, &guid);
1255 if (err)
1256 {
1257 PWSTR wide_name = utf8to16(itf_name);
1258 MsgToEventLog(M_ERR, L"%S: Failed to convert itf '%s' LUID", __func__, wide_name);
1259 free(wide_name);
1260 goto out;
1261 }
1262
1263 if (StringFromIID(&guid, &iid_str) != S_OK)
1264 {
1265 PWSTR wide_name = utf8to16(itf_name);
1266 MsgToEventLog(M_ERR, L"%S: Failed to convert itf '%s' IID", __func__, wide_name);
1267 free(wide_name);
1268 err = ERROR_OUTOFMEMORY;
1269 goto out;
1270 }
1271 if (wcslen(iid_str) + 1 > len)
1272 {
1273 err = ERROR_INVALID_PARAMETER;
1274 goto out;
1275 }
1276
1277 wcsncpy(str, iid_str, len);
1278
1279out:
1280 if (iid_str)
1281 {
1282 CoTaskMemFree(iid_str);
1283 }
1284 return err;
1285}
1286
1300static BOOL
1302{
1303 char data[64];
1304 DWORD size = sizeof(data);
1305 LSTATUS err = RegGetValueA(key, NULL, "SearchList", RRF_RT_REG_SZ, NULL, (PBYTE)data, &size);
1306 if (!err || err == ERROR_MORE_DATA)
1307 {
1308 data[sizeof(data) - 1] = '\0';
1309 for (size_t i = 0; i < strlen(data); ++i)
1310 {
1311 if (isalnum(data[i]) || data[i] == '-' || data[i] == '.')
1312 {
1313 return TRUE;
1314 }
1315 }
1316 }
1317 return FALSE;
1318}
1319
1337static BOOL
1338GetDnsSearchListKey(PCSTR itf_name, PBOOL gpol, PHKEY key)
1339{
1340 LSTATUS err;
1341
1342 *gpol = FALSE;
1343
1344 /* Try the group policy search list */
1345 err = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Policies\\Microsoft\\Windows NT\\DNSClient",
1346 0, KEY_ALL_ACCESS, key);
1347 if (!err)
1348 {
1349 if (HasValidSearchList(*key))
1350 {
1351 *gpol = TRUE;
1352 return TRUE;
1353 }
1354 RegCloseKey(*key);
1355 }
1356
1357 /* Try the system-wide search list */
1358 err =
1359 RegOpenKeyExA(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\TCPIP\\Parameters",
1360 0, KEY_ALL_ACCESS, key);
1361 if (!err)
1362 {
1363 if (HasValidSearchList(*key))
1364 {
1365 return TRUE;
1366 }
1367 RegCloseKey(*key);
1368 }
1369
1370 if (itf_name)
1371 {
1372 /* Always return the VPN interface key (if it exists) */
1373 WCHAR iid[64];
1374 DWORD iid_err = InterfaceIdString(itf_name, iid, _countof(iid));
1375 if (!iid_err)
1376 {
1377 HKEY itfs;
1378 err =
1379 RegOpenKeyExA(HKEY_LOCAL_MACHINE,
1380 "System\\CurrentControlSet\\Services\\TCPIP\\Parameters\\Interfaces",
1381 0, KEY_ALL_ACCESS, &itfs);
1382 if (!err)
1383 {
1384 err = RegOpenKeyExW(itfs, iid, 0, KEY_ALL_ACCESS, key);
1385 RegCloseKey(itfs);
1386 if (!err)
1387 {
1388 return FALSE; /* No need to preserve the VPN itf search list */
1389 }
1390 }
1391 }
1392 }
1393
1394 *key = INVALID_HANDLE_VALUE;
1395 return FALSE;
1396}
1397
1405static BOOL
1407{
1408 LSTATUS err;
1409
1410 err = RegGetValueA(key, NULL, "InitialSearchList", RRF_RT_REG_SZ, NULL, NULL, NULL);
1411 if (err)
1412 {
1413 if (err == ERROR_FILE_NOT_FOUND)
1414 {
1415 return FALSE;
1416 }
1417 MsgToEventLog(M_ERR, L"%S: failed to get InitialSearchList (%lu)", __func__, err);
1418 }
1419
1420 return TRUE;
1421}
1422
1427static DWORD
1428RegWStringSize(PCWSTR string)
1429{
1430 size_t length = (wcslen(string) + 1) * sizeof(wchar_t);
1431 if (length > UINT_MAX)
1432 {
1433 length = UINT_MAX;
1434 }
1435 return (DWORD)length;
1436}
1437
1448static BOOL
1450{
1451 if (!list || wcslen(list) == 0)
1452 {
1453 MsgToEventLog(M_ERR, L"%S: empty search list", __func__);
1454 return FALSE;
1455 }
1456
1458 {
1459 /* Initial list had already been stored */
1460 return TRUE;
1461 }
1462
1463 DWORD size = RegWStringSize(list);
1464 LSTATUS err = RegSetValueExW(key, L"InitialSearchList", 0, REG_SZ, (PBYTE)list, size);
1465 if (err)
1466 {
1467 MsgToEventLog(M_ERR, L"%S: failed to set InitialSearchList value (%lu)", __func__, err);
1468 return FALSE;
1469 }
1470
1471 return TRUE;
1472}
1473
1488static BOOL
1489AppendSearchList(PWSTR list, size_t list_cap, PCWSTR add)
1490{
1491 size_t list_len = wcslen(list);
1492 size_t add_len = wcslen(add);
1493 if (add_len == 0)
1494 {
1495 return TRUE;
1496 }
1497
1498 size_t sep_len = (list_len > 0) ? 1 : 0;
1499 if (list_len + sep_len + add_len + 1 > list_cap)
1500 {
1501 return FALSE;
1502 }
1503
1504 if (sep_len)
1505 {
1506 list[list_len++] = L',';
1507 }
1508 wmemcpy(list + list_len, add, add_len + 1);
1509 return TRUE;
1510}
1511
1535static size_t
1536RemoveSearchListTokens(PWSTR list, PCWSTR remove)
1537{
1538 size_t removed = 0;
1539 PCWSTR domain = remove;
1540 while (*domain)
1541 {
1542 PCWSTR comma = wcschr(domain, L',');
1543 size_t domain_len = comma ? (size_t)(comma - domain) : wcslen(domain);
1544 if (domain_len > 0)
1545 {
1546 /* Find the last token in @p list that exactly equals @p domain. */
1547 PWSTR match = NULL;
1548 PWSTR match_end = NULL;
1549 for (PWSTR p = list; *p;)
1550 {
1551 PWSTR tok_end = wcschr(p, L',');
1552 size_t tok_len = tok_end ? (size_t)(tok_end - p) : wcslen(p);
1553 if (tok_len == domain_len && wcsncmp(p, domain, domain_len) == 0)
1554 {
1555 match = p;
1556 match_end = tok_end;
1557 }
1558 if (!tok_end)
1559 {
1560 break;
1561 }
1562 p = tok_end + 1;
1563 }
1564 if (match)
1565 {
1566 /* Splice the token out, eating its leading comma if it has
1567 * one, otherwise its trailing comma. */
1568 PWSTR cut_start, cut_end;
1569 if (match == list)
1570 {
1571 cut_start = match;
1572 cut_end = match_end ? match_end + 1 : match + domain_len;
1573 }
1574 else
1575 {
1576 cut_start = match - 1;
1577 cut_end = match + domain_len;
1578 }
1579 wmemmove(cut_start, cut_end, wcslen(cut_end) + 1);
1580 removed++;
1581 }
1582 }
1583 if (!comma)
1584 {
1585 break;
1586 }
1587 domain = comma + 1;
1588 }
1589 return removed;
1590}
1591
1608static BOOL
1609AddDnsSearchDomains(HKEY key, BOOL have_list, PCWSTR domains)
1610{
1611 WCHAR list[2048] = { 0 };
1612
1613 if (have_list)
1614 {
1615 DWORD size = sizeof(list);
1616 LSTATUS err =
1617 RegGetValueW(key, NULL, L"SearchList", RRF_RT_REG_SZ, NULL, list, &size);
1618 if (err)
1619 {
1620 MsgToEventLog(M_SYSERR, L"%S: could not get SearchList from registry (%lu)", __func__,
1621 err);
1622 return FALSE;
1623 }
1624
1625 if (!StoreInitialDnsSearchList(key, list))
1626 {
1627 return FALSE;
1628 }
1629 }
1630
1631 if (!AppendSearchList(list, _countof(list), domains))
1632 {
1633 MsgToEventLog(M_SYSERR, L"%S: not enough space in list for search domains", __func__);
1634 return FALSE;
1635 }
1636
1637 DWORD size = RegWStringSize(list);
1638 LSTATUS err = RegSetValueExW(key, L"SearchList", 0, REG_SZ, (PBYTE)list, size);
1639 if (err)
1640 {
1641 MsgToEventLog(M_SYSERR, L"%S: could not set SearchList to registry (%lu)", __func__, err);
1642 return FALSE;
1643 }
1644
1645 return TRUE;
1646}
1647
1659static BOOL
1661{
1662 LSTATUS err;
1663 BOOL ret = FALSE;
1664 WCHAR list[2048];
1665 DWORD size = sizeof(list);
1666
1667 err = RegGetValueW(key, NULL, L"InitialSearchList", RRF_RT_REG_SZ, NULL, list, &size);
1668 if (err)
1669 {
1670 if (err != ERROR_FILE_NOT_FOUND)
1671 {
1672 MsgToEventLog(M_SYSERR, L"%S: could not get InitialSearchList from registry (%lu)",
1673 __func__, err);
1674 }
1675 goto out;
1676 }
1677
1678 size = RegWStringSize(list);
1679 err = RegSetValueExW(key, L"SearchList", 0, REG_SZ, (PBYTE)list, size);
1680 if (err)
1681 {
1682 MsgToEventLog(M_SYSERR, L"%S: could not set SearchList in registry (%lu)", __func__, err);
1683 goto out;
1684 }
1685
1686 RegDeleteValueA(key, "InitialSearchList");
1687 ret = TRUE;
1688
1689out:
1690 return ret;
1691}
1692
1707static void
1708RemoveDnsSearchDomains(HKEY key, PCWSTR domains)
1709{
1710 WCHAR list[2048];
1711 DWORD size = sizeof(list);
1712 LSTATUS err = RegGetValueW(key, NULL, L"SearchList", RRF_RT_REG_SZ, NULL, list, &size);
1713 if (err)
1714 {
1715 MsgToEventLog(M_SYSERR, L"%S: could not get SearchList from registry (%lu)", __func__, err);
1716 return;
1717 }
1718
1719 if (RemoveSearchListTokens(list, domains) == 0)
1720 {
1721 MsgToEventLog(M_ERR, L"%S: could not find domains in search list", __func__);
1722 return;
1723 }
1724
1725 if (list[0] != L'\0')
1726 {
1727 /* If the shortened list equals the snapshot we took at first
1728 * touch, the user's pre-VPN state is fully restored -- wipe both
1729 * SearchList and InitialSearchList. */
1730 WCHAR initial[2048];
1731 size = sizeof(initial);
1732 err = RegGetValueW(key, NULL, L"InitialSearchList", RRF_RT_REG_SZ, NULL, initial, &size);
1733 if (!err && wcscmp(list, initial) == 0)
1734 {
1736 return;
1737 }
1738 if (err && err != ERROR_FILE_NOT_FOUND)
1739 {
1740 MsgToEventLog(M_SYSERR, L"%S: could not get InitialSearchList from registry (%lu)",
1741 __func__, err);
1742 return;
1743 }
1744 }
1745
1746 size = RegWStringSize(list);
1747 err = RegSetValueExW(key, L"SearchList", 0, REG_SZ, (PBYTE)list, size);
1748 if (err)
1749 {
1750 MsgToEventLog(M_SYSERR, L"%S: could not set SearchList in registry (%lu)", __func__, err);
1751 }
1752}
1753
1759static void
1761{
1762 BOOL gpol;
1763 HKEY dns_searchlist_key;
1764 GetDnsSearchListKey(undo_data->itf_name, &gpol, &dns_searchlist_key);
1765 if (dns_searchlist_key != INVALID_HANDLE_VALUE)
1766 {
1767 RemoveDnsSearchDomains(dns_searchlist_key, undo_data->domains);
1768 RegCloseKey(dns_searchlist_key);
1769 ApplyDnsSettings(gpol);
1770 }
1771
1772 free(undo_data->domains);
1773 undo_data->domains = NULL;
1774}
1775
1797static DWORD
1798SetDnsSearchDomains(PCSTR itf_name, PCSTR domains, PBOOL gpol, undo_lists_t *lists)
1799{
1800 DWORD err = ERROR_OUTOFMEMORY;
1801
1802 HKEY list_key;
1803 BOOL have_list = GetDnsSearchListKey(itf_name, gpol, &list_key);
1804 if (list_key == INVALID_HANDLE_VALUE)
1805 {
1806 MsgToEventLog(M_SYSERR, L"%S: could not get search list registry key", __func__);
1807 return ERROR_FILE_NOT_FOUND;
1808 }
1809
1810 /* Remove previously installed search domains */
1811 dns_domains_undo_data_t *undo_data = RemoveListItem(&(*lists)[undo_domains], CmpAny, NULL);
1812 if (undo_data)
1813 {
1814 RemoveDnsSearchDomains(list_key, undo_data->domains);
1815 free(undo_data->domains);
1816 free(undo_data);
1817 undo_data = NULL;
1818 }
1819
1820 /* If there are search domains, add them */
1821 if (domains && *domains)
1822 {
1823 wchar_t *wide_domains = utf8to16(domains); /* utf8 to wide-char */
1824 if (!wide_domains)
1825 {
1826 goto out;
1827 }
1828
1829 undo_data = malloc(sizeof(*undo_data));
1830 if (!undo_data)
1831 {
1832 free(wide_domains);
1833 wide_domains = NULL;
1834 goto out;
1835 }
1836 strncpy_s(undo_data->itf_name, sizeof(undo_data->itf_name), itf_name, _TRUNCATE);
1837 undo_data->domains = wide_domains;
1838
1839 /* Add undo information first in case there's no heap left */
1840 if (AddListItem(&(*lists)[undo_domains], undo_data) != NO_ERROR)
1841 {
1842 free(wide_domains);
1843 free(undo_data);
1844 goto out;
1845 }
1846
1847 if (!AddDnsSearchDomains(list_key, have_list, wide_domains))
1848 {
1849 RemoveListItem(&(*lists)[undo_domains], CmpAny, NULL);
1850 free(wide_domains);
1851 free(undo_data);
1852 goto out;
1853 }
1854 }
1855
1856 err = NO_ERROR;
1857
1858out:
1859 RegCloseKey(list_key);
1860 return err;
1861}
1862
1870static BOOL
1871GetInterfacesKey(short family, PHKEY key)
1872{
1873 PCSTR itfs_key = family == AF_INET6
1874 ? "SYSTEM\\CurrentControlSet\\Services\\Tcpip6\\Parameters\\Interfaces"
1875 : "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces";
1876
1877 LSTATUS err = RegOpenKeyExA(HKEY_LOCAL_MACHINE, itfs_key, 0, KEY_ALL_ACCESS, key);
1878 if (err)
1879 {
1880 *key = INVALID_HANDLE_VALUE;
1881 MsgToEventLog(M_SYSERR, L"%S: could not open interfaces registry key for family %d (%lu)",
1882 __func__, family, err);
1883 }
1884
1885 return err ? FALSE : TRUE;
1886}
1887
1897static DWORD
1898SetNameServersValue(PCWSTR itf_id, short family, PCSTR value)
1899{
1900 DWORD err;
1901
1902 HKEY itfs;
1903 if (!GetInterfacesKey(family, &itfs))
1904 {
1905 return ERROR_FILE_NOT_FOUND;
1906 }
1907
1908 HKEY itf = INVALID_HANDLE_VALUE;
1909 err = RegOpenKeyExW(itfs, itf_id, 0, KEY_ALL_ACCESS, &itf);
1910 if (err)
1911 {
1912 MsgToEventLog(M_SYSERR, L"%S: could not open interface key for %s family %d (%lu)",
1913 __func__, itf_id, family, err);
1914 goto out;
1915 }
1916
1917 err = RegSetValueExA(itf, "NameServer", 0, REG_SZ, (PBYTE)value, (DWORD)strlen(value) + 1);
1918 if (err)
1919 {
1920 MsgToEventLog(M_SYSERR, L"%S: could not set name servers '%S' for %s family %d (%lu)",
1921 __func__, value, itf_id, family, err);
1922 }
1923
1924out:
1925 if (itf != INVALID_HANDLE_VALUE)
1926 {
1927 RegCloseKey(itf);
1928 }
1929 if (itfs != INVALID_HANDLE_VALUE)
1930 {
1931 RegCloseKey(itfs);
1932 }
1933 return err;
1934}
1935
1945static DWORD
1946SetNameServers(PCWSTR itf_id, short family, PCSTR addrs)
1947{
1948 return SetNameServersValue(itf_id, family, addrs);
1949}
1950
1959static DWORD
1960ResetNameServers(PCWSTR itf_id, short family)
1961{
1962 return SetNameServersValue(itf_id, family, "");
1963}
1964
1965static DWORD
1967{
1968 DWORD err = 0;
1969 undo_type_t undo_type = (msg->family == AF_INET6) ? undo_dns6 : undo_dns4;
1970 unsigned int addr_len = msg->addr_len;
1971
1972 /* sanity check */
1973 const unsigned int max_addrs = _countof(msg->addr);
1974 if (addr_len > max_addrs)
1975 {
1976 addr_len = max_addrs;
1977 }
1978
1979 if (!msg->iface.name[0]) /* interface name is required */
1980 {
1981 return ERROR_MESSAGE_DATA;
1982 }
1983
1984 /* use a non-const reference with limited scope to enforce null-termination of strings from
1985 * client */
1986 {
1988 msgptr->iface.name[_countof(msg->iface.name) - 1] = '\0';
1989 msgptr->domains[_countof(msg->domains) - 1] = '\0';
1990 }
1991
1992 WCHAR iid[64];
1993 err = InterfaceIdString(msg->iface.name, iid, _countof(iid));
1994 if (err)
1995 {
1996 return err;
1997 }
1998
1999 /* We delete all current addresses before adding any
2000 * OR if the message type is del_dns_cfg
2001 */
2002 if (addr_len > 0 || msg->header.type == msg_del_dns_cfg)
2003 {
2004 err = ResetNameServers(iid, msg->family);
2005 if (err)
2006 {
2007 return err;
2008 }
2009 free(RemoveListItem(&(*lists)[undo_type], CmpAny, iid));
2010 }
2011
2012 if (msg->header.type == msg_del_dns_cfg)
2013 {
2014 BOOL gpol = FALSE;
2015 if (msg->domains[0])
2016 {
2017 /* setting an empty domain list removes any previous value */
2018 err = SetDnsSearchDomains(msg->iface.name, NULL, &gpol, lists);
2019 }
2020 ApplyDnsSettings(gpol);
2021 return err; /* job done */
2022 }
2023
2024 if (addr_len > 0)
2025 {
2026 /* prepare the comma separated address list */
2027 /* cannot use max_addrs here as that is not considered compile
2028 * time constant by all compilers and constexpr is C23 */
2029 CHAR addrs[_countof(msg->addr) * 64]; /* 64 is enough for one IPv4/6 address */
2030 size_t offset = 0;
2031 for (unsigned int i = 0; i < addr_len; ++i)
2032 {
2033 if (i != 0)
2034 {
2035 addrs[offset++] = ',';
2036 }
2037 if (msg->family == AF_INET6)
2038 {
2039 RtlIpv6AddressToStringA(&msg->addr[i].ipv6, addrs + offset);
2040 }
2041 else
2042 {
2043 RtlIpv4AddressToStringA(&msg->addr[i].ipv4, addrs + offset);
2044 }
2045 offset = strlen(addrs);
2046 }
2047
2048 err = SetNameServers(iid, msg->family, addrs);
2049 if (err)
2050 {
2051 return err;
2052 }
2053
2054 wchar_t *tmp_iid = _wcsdup(iid);
2055 if (!tmp_iid || AddListItem(&(*lists)[undo_type], tmp_iid))
2056 {
2057 free(tmp_iid);
2058 ResetNameServers(iid, msg->family);
2059 return ERROR_OUTOFMEMORY;
2060 }
2061 }
2062
2063 BOOL gpol = FALSE;
2064 if (msg->domains[0])
2065 {
2066 err = SetDnsSearchDomains(msg->iface.name, msg->domains, &gpol, lists);
2067 }
2068 ApplyDnsSettings(gpol);
2069
2070 return err;
2071}
2072
2081static BOOL
2083{
2084 DWORD dhcp;
2085 DWORD size = sizeof(dhcp);
2086 LSTATUS err;
2087
2088 err = RegGetValueA(key, NULL, "EnableDHCP", RRF_RT_REG_DWORD, NULL, (PBYTE)&dhcp, &size);
2089 if (err != NO_ERROR)
2090 {
2091 MsgToEventLog(M_SYSERR, L"%S: Could not read DHCP status (%lu)", __func__, err);
2092 return FALSE;
2093 }
2094
2095 return dhcp ? TRUE : FALSE;
2096}
2097
2106static LSTATUS
2107SetNameServerAddresses(PWSTR itf_id, const nrpt_address_t *addresses)
2108{
2109 const short families[] = { AF_INET, AF_INET6 };
2110 for (size_t i = 0; i < _countof(families); i++)
2111 {
2112 short family = families[i];
2113
2114 /* Create a comma sparated list of addresses of this family */
2115 size_t offset = 0;
2116 char addr_list[NRPT_ADDR_SIZE * NRPT_ADDR_NUM];
2117 for (int j = 0; j < NRPT_ADDR_NUM && addresses[j][0]; j++)
2118 {
2119 if ((family == AF_INET6 && strchr(addresses[j], ':') == NULL)
2120 || (family == AF_INET && strchr(addresses[j], ':') != NULL))
2121 {
2122 /* Address family doesn't match, skip this one */
2123 continue;
2124 }
2125 if (offset)
2126 {
2127 addr_list[offset++] = ',';
2128 }
2129 strcpy(addr_list + offset, addresses[j]);
2130 offset += strlen(addresses[j]);
2131 }
2132
2133 if (offset == 0)
2134 {
2135 /* No address for this family to set */
2136 continue;
2137 }
2138
2139 /* Set name server addresses */
2140 LSTATUS err = SetNameServers(itf_id, family, addr_list);
2141 if (err)
2142 {
2143 return err;
2144 }
2145 }
2146 return NO_ERROR;
2147}
2148
2156static DWORD
2158{
2159 size_t len = strlen(addrs);
2160 while (len && (addrs[len - 1] == ',' || addrs[len - 1] == ' '))
2161 {
2162 addrs[--len] = '\0';
2163 }
2164 return (DWORD)len + 1;
2165}
2166
2177static LSTATUS
2178GetItfDnsServersV4(HKEY itf_key, PSTR addrs, PDWORD size)
2179{
2180 addrs[0] = '\0';
2181 addrs[*size - 1] = '\0';
2182
2183 LSTATUS err;
2184 DWORD s = *size;
2185 err = RegGetValueA(itf_key, NULL, "NameServer", RRF_RT_REG_SZ, NULL, (PBYTE)addrs, &s);
2186 if (err && err != ERROR_FILE_NOT_FOUND)
2187 {
2188 *size = 0;
2189 return err;
2190 }
2191
2192 /* Try DHCP addresses if we don't have some already */
2193 if (!strchr(addrs, '.') && IsDhcpEnabled(itf_key))
2194 {
2195 s = *size;
2196 err = RegGetValueA(itf_key, NULL, "DhcpNameServer", RRF_RT_REG_SZ, NULL, (PBYTE)addrs, &s);
2197 if (err)
2198 {
2199 *size = 0;
2200 return err;
2201 }
2202 }
2203
2204 if (strchr(addrs, '.'))
2205 {
2206 *size = TrimNameServers(addrs);
2207 return NO_ERROR;
2208 }
2209
2210 *size = 0;
2211 return ERROR_FILE_NOT_FOUND;
2212}
2213
2224static LSTATUS
2225GetItfDnsServersV6(HKEY itf_key, PSTR addrs, PDWORD size)
2226{
2227 addrs[0] = '\0';
2228 addrs[*size - 1] = '\0';
2229
2230 LSTATUS err;
2231 DWORD s = *size;
2232 err = RegGetValueA(itf_key, NULL, "NameServer", RRF_RT_REG_SZ, NULL, (PBYTE)addrs, &s);
2233 if (err && err != ERROR_FILE_NOT_FOUND)
2234 {
2235 *size = 0;
2236 return err;
2237 }
2238
2239 /* Try DHCP addresses if we don't have some already */
2240 if (!strchr(addrs, ':') && IsDhcpEnabled(itf_key))
2241 {
2242 IN6_ADDR in_addrs[8];
2243 DWORD in_addrs_size = sizeof(in_addrs);
2244 err = RegGetValueA(itf_key, NULL, "Dhcpv6DNSServers", RRF_RT_REG_BINARY, NULL,
2245 (PBYTE)in_addrs, &in_addrs_size);
2246 if (err)
2247 {
2248 *size = 0;
2249 return err;
2250 }
2251
2252 s = *size;
2253 PSTR pos = addrs;
2254 size_t in_addrs_read = in_addrs_size / sizeof(IN6_ADDR);
2255 for (size_t i = 0; i < in_addrs_read; ++i)
2256 {
2257 if (i != 0)
2258 {
2259 /* Add separator */
2260 *pos++ = ',';
2261 s--;
2262 }
2263
2264 if (inet_ntop(AF_INET6, &in_addrs[i], pos, s) == NULL)
2265 {
2266 *size = 0;
2267 return ERROR_MORE_DATA;
2268 }
2269
2270 size_t addr_len = strlen(pos);
2271 pos += addr_len;
2272 s -= (DWORD)addr_len;
2273 }
2274 }
2275
2276 if (strchr(addrs, ':'))
2277 {
2278 *size = TrimNameServers(addrs);
2279 return NO_ERROR;
2280 }
2281
2282 *size = 0;
2283 return ERROR_FILE_NOT_FOUND;
2284}
2285
2295static BOOL
2296ListContainsDomain(PCWSTR list, PCWSTR domain, size_t len)
2297{
2298 PCWSTR entry = list;
2299 while (entry && *entry)
2300 {
2301 PCWSTR comma = wcschr(entry, L',');
2302 size_t entry_len = comma ? (size_t)(comma - entry) : wcslen(entry);
2303 if (entry_len == len && wcsncmp(entry, domain, len) == 0)
2304 {
2305 return TRUE;
2306 }
2307 if (!comma)
2308 {
2309 break;
2310 }
2311 entry = comma + 1;
2312 }
2313 return FALSE;
2314}
2315
2339static LSTATUS
2340ConvertItfDnsDomains(PCWSTR search_domains, PWSTR domains, PDWORD size, const DWORD capacity)
2341{
2342 const size_t glyph_size = sizeof(*domains);
2343 const size_t max_len = (size_t)capacity / glyph_size;
2344
2345 /* Space required for leading dot and two terminating zeros */
2346 const size_t dot_len = 1;
2347 const size_t term_len = 2;
2348
2349 LSTATUS ret = NO_ERROR;
2350 size_t tmp_len = 0;
2351 WCHAR *tmp = malloc(capacity);
2352 if (tmp == NULL)
2353 {
2354 ret = ERROR_OUTOFMEMORY;
2355 goto done;
2356 }
2357
2358 PWCHAR tmp_pos = tmp;
2359 PCWCHAR domain = domains;
2360
2361 while (domain && *domain)
2362 {
2363 PWCHAR comma = wcschr(domain, L',');
2364 size_t domain_len = comma ? (size_t)(comma - domain) : wcslen(domain);
2365
2366 if (domain_len == 0 || ListContainsDomain(search_domains, domain, domain_len))
2367 {
2368 /* Skip this domain */
2369 domain = comma ? comma + 1 : domain + domain_len;
2370 continue;
2371 }
2372
2373 /* Check for enough space to convert this domain */
2374 if (tmp_len + dot_len + domain_len + term_len > max_len)
2375 {
2376 /* Domain doesn't fit, bad luck if it's the first one */
2377 *tmp_pos = L'\0';
2378 if (tmp_len > 0)
2379 {
2380 tmp_len += 1;
2381 }
2382 ret = ERROR_MORE_DATA;
2383 goto done;
2384 }
2385
2386 /* Write leading dot and domain into tmp buffer */
2387 *tmp_pos++ = L'.';
2388 wcsncpy(tmp_pos, domain, domain_len);
2389 tmp_pos += domain_len;
2390 *tmp_pos++ = L'\0';
2391 tmp_len += dot_len + domain_len + 1;
2392
2393 domain = comma ? comma + 1 : domain + domain_len;
2394 }
2395
2396 if (tmp_len == 0)
2397 {
2398 ret = ERROR_FILE_NOT_FOUND;
2399 goto done;
2400 }
2401
2402 /* REG_MULTI_SZ second zero terminator */
2403 *tmp_pos = L'\0';
2404 tmp_len += 1;
2405
2406done:
2407 if (tmp)
2408 {
2409 wmemcpy(domains, tmp, tmp_len);
2410 free(tmp);
2411 }
2412 *size = (DWORD)(tmp_len * glyph_size);
2413 return ret;
2414}
2415
2437static LSTATUS
2438GetItfDnsDomains(HKEY itf, PCWSTR search_domains, PWSTR domains, PDWORD size)
2439{
2440 if (domains == NULL || size == NULL || *size == 0)
2441 {
2442 return ERROR_INVALID_PARAMETER;
2443 }
2444
2445 LSTATUS err = ERROR_FILE_NOT_FOUND;
2446 const DWORD buf_size = *size;
2447 const DWORD glyph_size = sizeof(*domains);
2448 PWSTR values[] = { L"SearchList", L"Domain", L"DhcpDomainSearchList", L"DhcpDomain", NULL };
2449
2450 for (int i = 0; values[i]; i++)
2451 {
2452 *size = buf_size;
2453 err = RegGetValueW(itf, NULL, values[i], RRF_RT_REG_SZ, NULL, (PBYTE)domains, size);
2454 if (!err && *size > glyph_size && domains[(*size / glyph_size) - 1] == '\0' && wcschr(domains, '.'))
2455 {
2456 return ConvertItfDnsDomains(search_domains, domains, size, buf_size);
2457 }
2458 }
2459
2460 *size = 0;
2461 return err;
2462}
2463
2472static BOOL
2474{
2475 GUID iid;
2476 BOOL res = FALSE;
2477 MIB_IF_ROW2 itf_row;
2478
2479 /* Get GUID from string */
2480 if (IIDFromString(iid_str, &iid) != S_OK)
2481 {
2482 MsgToEventLog(M_SYSERR, L"%S: could not convert interface %s GUID string", __func__,
2483 iid_str);
2484 goto out;
2485 }
2486
2487 /* Get LUID from GUID */
2488 if (ConvertInterfaceGuidToLuid(&iid, &itf_row.InterfaceLuid) != NO_ERROR)
2489 {
2490 goto out;
2491 }
2492
2493 /* Look up interface status */
2494 if (GetIfEntry2(&itf_row) != NO_ERROR)
2495 {
2496 MsgToEventLog(M_SYSERR, L"%S: could not get interface %s status", __func__, iid_str);
2497 goto out;
2498 }
2499
2500 if (itf_row.MediaConnectState == MediaConnectStateConnected
2501 && itf_row.OperStatus == IfOperStatusUp)
2502 {
2503 res = TRUE;
2504 }
2505
2506out:
2507 return res;
2508}
2509
2519static void
2520GetNrptExcludeData(PCWSTR search_domains, nrpt_exclude_data_t *data, size_t data_size)
2521{
2522 HKEY v4_itfs = INVALID_HANDLE_VALUE;
2523 HKEY v6_itfs = INVALID_HANDLE_VALUE;
2524
2525 if (!GetInterfacesKey(AF_INET, &v4_itfs) || !GetInterfacesKey(AF_INET6, &v6_itfs))
2526 {
2527 goto out;
2528 }
2529
2530 size_t i = 0;
2531 DWORD enum_index = 0;
2532 while (i < data_size)
2533 {
2534 WCHAR itf_guid[MAX_PATH];
2535 DWORD itf_guid_len = _countof(itf_guid);
2536 LSTATUS err =
2537 RegEnumKeyExW(v4_itfs, enum_index++, itf_guid, &itf_guid_len, NULL, NULL, NULL, NULL);
2538 if (err)
2539 {
2540 if (err != ERROR_NO_MORE_ITEMS)
2541 {
2542 MsgToEventLog(M_SYSERR, L"%S: could not enumerate interfaces (%lu)", __func__, err);
2543 }
2544 goto out;
2545 }
2546
2547 /* Ignore interfaces that are not connected or disabled */
2548 if (!IsInterfaceConnected(itf_guid))
2549 {
2550 continue;
2551 }
2552
2553 HKEY v4_itf;
2554 if (RegOpenKeyExW(v4_itfs, itf_guid, 0, KEY_READ, &v4_itf) != NO_ERROR)
2555 {
2556 MsgToEventLog(M_SYSERR, L"%S: could not open interface %s v4 registry key", __func__,
2557 itf_guid);
2558 goto out;
2559 }
2560
2561 /* Get the DNS domain(s) for exclude routing */
2562 data[i].domains_size = sizeof(data[0].domains);
2563 memset(data[i].domains, 0, data[i].domains_size);
2564 err = GetItfDnsDomains(v4_itf, search_domains, data[i].domains, &data[i].domains_size);
2565 if (err)
2566 {
2567 if (err != ERROR_FILE_NOT_FOUND)
2568 {
2569 MsgToEventLog(M_SYSERR, L"%S: could not read interface %s domain suffix", __func__,
2570 itf_guid);
2571 }
2572 goto next_itf;
2573 }
2574
2575 /* Get the IPv4 DNS servers */
2576 DWORD v4_addrs_size = sizeof(data[0].addresses);
2577 err = GetItfDnsServersV4(v4_itf, data[i].addresses, &v4_addrs_size);
2578 if (err && err != ERROR_FILE_NOT_FOUND)
2579 {
2580 MsgToEventLog(M_SYSERR, L"%S: could not read interface %s v4 name servers (%ld)",
2581 __func__, itf_guid, err);
2582 goto next_itf;
2583 }
2584
2585 /* Get the IPv6 DNS servers, if there's space left */
2586 PSTR v6_addrs = data[i].addresses + v4_addrs_size;
2587 DWORD v6_addrs_size = sizeof(data[0].addresses) - v4_addrs_size;
2588 if (v6_addrs_size > NRPT_ADDR_SIZE)
2589 {
2590 HKEY v6_itf;
2591 if (RegOpenKeyExW(v6_itfs, itf_guid, 0, KEY_READ, &v6_itf) != NO_ERROR)
2592 {
2593 MsgToEventLog(M_SYSERR, L"%S: could not open interface %s v6 registry key",
2594 __func__, itf_guid);
2595 goto next_itf;
2596 }
2597 err = GetItfDnsServersV6(v6_itf, v6_addrs, &v6_addrs_size);
2598 RegCloseKey(v6_itf);
2599 if (err && err != ERROR_FILE_NOT_FOUND)
2600 {
2601 MsgToEventLog(M_SYSERR, L"%S: could not read interface %s v6 name servers (%ld)",
2602 __func__, itf_guid, err);
2603 goto next_itf;
2604 }
2605 if (v4_addrs_size && v6_addrs_size)
2606 {
2607 /* Join the lists: replace the v4 terminating NUL with a delimiter */
2608 data[i].addresses[v4_addrs_size - 1] = ',';
2609 }
2610 }
2611
2612 if (v4_addrs_size || v6_addrs_size)
2613 {
2614 /* Replace delimiters with semicolons, as required by NRPT */
2615 for (size_t j = 0; j < sizeof(data[0].addresses) && data[i].addresses[j]; j++)
2616 {
2617 if (data[i].addresses[j] == ',' || data[i].addresses[j] == ' ')
2618 {
2619 data[i].addresses[j] = ';';
2620 }
2621 }
2622 ++i;
2623 }
2624
2625next_itf:
2626 RegCloseKey(v4_itf);
2627 }
2628
2629out:
2630 RegCloseKey(v6_itfs);
2631 RegCloseKey(v4_itfs);
2632}
2633
2646static DWORD
2647SetNrptRule(HKEY nrpt_key, PCWSTR subkey, PCSTR address, PCWSTR domains, DWORD dom_size,
2648 BOOL dnssec)
2649{
2650 /* Create rule subkey */
2651 DWORD err = NO_ERROR;
2652 HKEY rule_key;
2653 err = RegCreateKeyExW(nrpt_key, subkey, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &rule_key, NULL);
2654 if (err)
2655 {
2656 return err;
2657 }
2658
2659 /* Set name(s) for DNS routing */
2660 err = RegSetValueExW(rule_key, L"Name", 0, REG_MULTI_SZ, (PBYTE)domains, dom_size);
2661 if (err)
2662 {
2663 goto out;
2664 }
2665
2666 /* Set DNS Server address */
2667 err = RegSetValueExA(rule_key, "GenericDNSServers", 0, REG_SZ, (PBYTE)address,
2668 (DWORD)strlen(address) + 1);
2669 if (err)
2670 {
2671 goto out;
2672 }
2673
2674 DWORD reg_val;
2675 /* Set DNSSEC if required */
2676 if (dnssec)
2677 {
2678 reg_val = 1;
2679 err = RegSetValueExA(rule_key, "DNSSECValidationRequired", 0, REG_DWORD, (PBYTE)&reg_val,
2680 sizeof(reg_val));
2681 if (err)
2682 {
2683 goto out;
2684 }
2685
2686 reg_val = 0;
2687 err = RegSetValueExA(rule_key, "DNSSECQueryIPSECRequired", 0, REG_DWORD, (PBYTE)&reg_val,
2688 sizeof(reg_val));
2689 if (err)
2690 {
2691 goto out;
2692 }
2693
2694 reg_val = 0;
2695 err = RegSetValueExA(rule_key, "DNSSECQueryIPSECEncryption", 0, REG_DWORD, (PBYTE)&reg_val,
2696 sizeof(reg_val));
2697 if (err)
2698 {
2699 goto out;
2700 }
2701 }
2702
2703 /* Set NRPT config options */
2704 reg_val = dnssec ? 0x0000000A : 0x00000008;
2705 err = RegSetValueExA(rule_key, "ConfigOptions", 0, REG_DWORD, (const PBYTE)&reg_val,
2706 sizeof(reg_val));
2707 if (err)
2708 {
2709 goto out;
2710 }
2711
2712 /* Mandatory NRPT version */
2713 reg_val = 2;
2714 err = RegSetValueExA(rule_key, "Version", 0, REG_DWORD, (const PBYTE)&reg_val, sizeof(reg_val));
2715 if (err)
2716 {
2717 goto out;
2718 }
2719
2720out:
2721 if (err)
2722 {
2723 RegDeleteKeyW(nrpt_key, subkey);
2724 }
2725 RegCloseKey(rule_key);
2726 return err;
2727}
2728
2738static void
2739SetNrptExcludeRules(HKEY nrpt_key, DWORD ovpn_pid, PCWSTR search_domains)
2740{
2741 nrpt_exclude_data_t data[8]; /* data from up to 8 interfaces */
2742 memset(data, 0, sizeof(data));
2743 GetNrptExcludeData(search_domains, data, _countof(data));
2744
2745 unsigned n = 0;
2746 for (size_t i = 0; i < _countof(data); ++i)
2747 {
2748 const nrpt_exclude_data_t *d = &data[i];
2749 if (d->domains_size == 0)
2750 {
2751 break;
2752 }
2753
2754 DWORD err;
2755 WCHAR subkey[48];
2756 swprintf(subkey, _countof(subkey), L"OpenVPNDNSRoutingX-%02x-%lu", ++n, ovpn_pid);
2757 err = SetNrptRule(nrpt_key, subkey, d->addresses, d->domains, d->domains_size, FALSE);
2758 if (err)
2759 {
2760 MsgToEventLog(M_ERR, L"%S: failed to set rule %s (%lu)", __func__, subkey, err);
2761 }
2762 }
2763}
2764
2777static DWORD
2778SetNrptRules(HKEY nrpt_key, const nrpt_address_t *addresses, const char *domains,
2779 const char *search_domains, BOOL dnssec, DWORD ovpn_pid)
2780{
2781 DWORD err = NO_ERROR;
2782 PWSTR wide_domains = L".\0"; /* DNS route everything by default */
2783 DWORD dom_size = 6;
2784
2785 /* Prepare DNS routing domains / split DNS */
2786 if (domains[0])
2787 {
2788 size_t domains_len = strlen(domains);
2789 dom_size = (DWORD)domains_len + 2; /* len + the trailing NULs */
2790
2791 wide_domains = utf8to16_size(domains, dom_size);
2792 if (!wide_domains)
2793 {
2794 return ERROR_OUTOFMEMORY;
2795 }
2796 domains_len = wcslen(wide_domains);
2797 dom_size = (DWORD)(domains_len + 2) * sizeof(*wide_domains);
2798
2799 /* Make a MULTI_SZ from a comma separated list */
2800 for (size_t i = 0; i < domains_len; ++i)
2801 {
2802 if (wide_domains[i] == ',')
2803 {
2804 wide_domains[i] = 0;
2805 }
2806 }
2807 }
2808 else
2809 {
2810 PWSTR wide_search_domains;
2811 wide_search_domains = utf8to16(search_domains);
2812 if (!wide_search_domains)
2813 {
2814 return ERROR_OUTOFMEMORY;
2815 }
2816 SetNrptExcludeRules(nrpt_key, ovpn_pid, wide_search_domains);
2817 free(wide_search_domains);
2818 }
2819
2820 if (addresses[0][0])
2821 {
2822 /* Create address string list */
2823 CHAR addr_list[NRPT_ADDR_NUM * NRPT_ADDR_SIZE];
2824 PSTR pos = addr_list;
2825 for (int i = 0; i < NRPT_ADDR_NUM && addresses[i][0]; ++i)
2826 {
2827 if (i != 0)
2828 {
2829 *pos++ = ';';
2830 }
2831 strcpy(pos, addresses[i]);
2832 pos += strlen(pos);
2833 }
2834
2835 WCHAR subkey[MAX_PATH];
2836 swprintf(subkey, _countof(subkey), L"OpenVPNDNSRouting-%lu", ovpn_pid);
2837 err = SetNrptRule(nrpt_key, subkey, addr_list, wide_domains, dom_size, dnssec);
2838 if (err)
2839 {
2840 MsgToEventLog(M_ERR, L"%S: failed to set rule %s (%lu)", __func__, subkey, err);
2841 }
2842 }
2843
2844 if (domains[0])
2845 {
2846 free(wide_domains);
2847 }
2848 return err;
2849}
2850
2859static LSTATUS
2860OpenNrptBaseKey(PHKEY key, PBOOL gpol)
2861{
2862 /*
2863 * Registry keys Name Service Policy Table (NRPT) rules can be stored at.
2864 * When the group policy key exists, NRPT rules must be placed there.
2865 * It is created when NRPT rules are pushed via group policy and it
2866 * remains in the registry even if the last GP-NRPT rule is deleted.
2867 */
2868 static PCSTR gpol_key = "SOFTWARE\\Policies\\Microsoft\\Windows NT\\DNSClient\\DnsPolicyConfig";
2869 static PCSTR sys_key =
2870 "SYSTEM\\CurrentControlSet\\Services\\Dnscache\\Parameters\\DnsPolicyConfig";
2871
2872 HKEY nrpt;
2873 *gpol = TRUE;
2874 LSTATUS err = RegOpenKeyExA(HKEY_LOCAL_MACHINE, gpol_key, 0, KEY_ALL_ACCESS, &nrpt);
2875 if (err == ERROR_FILE_NOT_FOUND)
2876 {
2877 *gpol = FALSE;
2878 err = RegCreateKeyExA(HKEY_LOCAL_MACHINE, sys_key, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &nrpt,
2879 NULL);
2880 if (err)
2881 {
2882 nrpt = INVALID_HANDLE_VALUE;
2883 }
2884 }
2885 *key = nrpt;
2886 return err;
2887}
2888
2900static BOOL
2901DeleteNrptRules(DWORD pid, PBOOL gpol)
2902{
2903 HKEY key;
2904 LSTATUS err = OpenNrptBaseKey(&key, gpol);
2905 if (err)
2906 {
2907 MsgToEventLog(M_SYSERR, L"%S: could not open NRPT base key (%lu)", __func__, err);
2908 return FALSE;
2909 }
2910
2911 /* PID suffix string to compare against later */
2912 WCHAR pid_str[16];
2913 size_t pidlen = 0;
2914 if (pid)
2915 {
2916 swprintf(pid_str, _countof(pid_str), L"-%lu", pid);
2917 pidlen = wcslen(pid_str);
2918 }
2919
2920 int deleted = 0;
2921 DWORD enum_index = 0;
2922 while (TRUE)
2923 {
2924 WCHAR name[MAX_PATH];
2925 DWORD namelen = _countof(name);
2926 err = RegEnumKeyExW(key, enum_index++, name, &namelen, NULL, NULL, NULL, NULL);
2927 if (err)
2928 {
2929 if (err != ERROR_NO_MORE_ITEMS)
2930 {
2931 MsgToEventLog(M_SYSERR, L"%S: could not enumerate NRPT rules (%lu)", __func__, err);
2932 }
2933 break;
2934 }
2935
2936 /* Keep rule if name doesn't match */
2937 if (wcsncmp(name, L"OpenVPNDNSRouting", 17) != 0
2938 || (pid && wcsncmp(name + namelen - pidlen, pid_str, pidlen) != 0))
2939 {
2940 continue;
2941 }
2942
2943 if (RegDeleteKeyW(key, name) == NO_ERROR)
2944 {
2945 enum_index--;
2946 deleted++;
2947 }
2948 }
2949
2950 RegCloseKey(key);
2951 return deleted ? TRUE : FALSE;
2952}
2953
2959static void
2960UndoNrptRules(DWORD ovpn_pid)
2961{
2962 BOOL gpol;
2963 if (DeleteNrptRules(ovpn_pid, &gpol))
2964 {
2965 ApplyDnsSettings(gpol);
2966 }
2967}
2968
2980static DWORD
2982{
2983 /*
2984 * Use a non-const reference with limited scope to
2985 * enforce null-termination of strings from client
2986 */
2987 {
2989 msgptr->iface.name[_countof(msg->iface.name) - 1] = '\0';
2990 msgptr->search_domains[_countof(msg->search_domains) - 1] = '\0';
2991 msgptr->resolve_domains[_countof(msg->resolve_domains) - 1] = '\0';
2992 for (size_t i = 0; i < NRPT_ADDR_NUM; ++i)
2993 {
2994 msgptr->addresses[i][_countof(msg->addresses[0]) - 1] = '\0';
2995 }
2996 }
2997
2998 /* Make sure we have the VPN interface name */
2999 if (msg->iface.name[0] == 0)
3000 {
3001 return ERROR_MESSAGE_DATA;
3002 }
3003
3004 /* Some sanity checks on the add message data */
3005 if (msg->header.type == msg_add_nrpt_cfg)
3006 {
3007 /* At least one name server address is set */
3008 if (msg->addresses[0][0] == 0)
3009 {
3010 return ERROR_MESSAGE_DATA;
3011 }
3012 /* Resolve domains are double zero terminated (MULTI_SZ) */
3013 const char *rdom = msg->resolve_domains;
3014 size_t rdom_size = sizeof(msg->resolve_domains);
3015 size_t rdom_len = strlen(rdom);
3016 if (rdom_len && (rdom_len + 1 >= rdom_size || rdom[rdom_len + 1] != 0))
3017 {
3018 return ERROR_MESSAGE_DATA;
3019 }
3020 }
3021
3022 BOOL gpol_nrpt = FALSE;
3023 BOOL gpol_list = FALSE;
3024
3025 WCHAR iid[64];
3026 DWORD iid_err = InterfaceIdString(msg->iface.name, iid, _countof(iid));
3027 if (iid_err)
3028 {
3029 return iid_err;
3030 }
3031
3032 /* Delete previously set values for this instance first, if any */
3033 PDWORD undo_pid = RemoveListItem(&(*lists)[undo_nrpt], CmpAny, NULL);
3034 if (undo_pid)
3035 {
3036 if (*undo_pid != ovpn_pid)
3037 {
3039 L"%S: PID stored for undo doesn't match: %lu vs %lu. "
3040 "This is likely an error. Cleaning up anyway.",
3041 __func__, *undo_pid, ovpn_pid);
3042 }
3043 DeleteNrptRules(*undo_pid, &gpol_nrpt);
3044 free(undo_pid);
3045
3046 ResetNameServers(iid, AF_INET);
3047 ResetNameServers(iid, AF_INET6);
3048 }
3049 SetDnsSearchDomains(msg->iface.name, NULL, &gpol_list, lists);
3050
3051 if (msg->header.type == msg_del_nrpt_cfg)
3052 {
3053 ApplyDnsSettings(gpol_nrpt || gpol_list);
3054 return NO_ERROR; /* Done dealing with del message */
3055 }
3056
3057 HKEY key;
3058 LSTATUS err = OpenNrptBaseKey(&key, &gpol_nrpt);
3059 if (err)
3060 {
3061 return err;
3062 }
3063
3064 /* Add undo information first in case there's no heap left */
3065 PDWORD pid = malloc(sizeof(ovpn_pid));
3066 if (!pid)
3067 {
3068 err = ERROR_OUTOFMEMORY;
3069 goto out;
3070 }
3071 *pid = ovpn_pid;
3072 if (AddListItem(&(*lists)[undo_nrpt], pid))
3073 {
3074 err = ERROR_OUTOFMEMORY;
3075 free(pid);
3076 goto out;
3077 }
3078
3079 /* Set NRPT rules */
3080 BOOL dnssec = (msg->flags & nrpt_dnssec) != 0;
3081 err = SetNrptRules(key, msg->addresses, msg->resolve_domains, msg->search_domains, dnssec,
3082 ovpn_pid);
3083 if (err)
3084 {
3085 goto out;
3086 }
3087
3088 /*
3089 * Set DNS on the adapter for search domains to be considered.
3090 * If split DNS is configured, do this only when search domains
3091 * are given, so that look-ups for other domains do not go over
3092 * the VPN all the time.
3093 */
3094 if (msg->search_domains[0] || !msg->resolve_domains[0])
3095 {
3096 err = SetNameServerAddresses(iid, msg->addresses);
3097 if (err)
3098 {
3099 goto out;
3100 }
3101 }
3102
3103 /* Set search domains, if any */
3104 if (msg->search_domains[0])
3105 {
3106 err = SetDnsSearchDomains(msg->iface.name, msg->search_domains, &gpol_list, lists);
3107 }
3108
3109 ApplyDnsSettings(gpol_nrpt || gpol_list);
3110
3111out:
3112 RegCloseKey(key);
3113 return err;
3114}
3115
3116static DWORD
3118{
3119 DWORD err = NO_ERROR;
3120 wchar_t addr[16]; /* large enough to hold string representation of an ipv4 */
3121 unsigned int addr_len = msg->addr_len;
3122
3123 /* sanity check */
3124 if (addr_len > _countof(msg->addr))
3125 {
3126 addr_len = _countof(msg->addr);
3127 }
3128
3129 if (!msg->iface.index) /* interface index is required */
3130 {
3131 return ERROR_MESSAGE_DATA;
3132 }
3133
3134 /* We delete all current addresses before adding any
3135 * OR if the message type is del_wins_cfg
3136 */
3137 if (addr_len > 0 || msg->header.type == msg_del_wins_cfg)
3138 {
3139 err = netsh_wins_cmd(L"delete", msg->iface.index, NULL);
3140 if (err)
3141 {
3142 goto out;
3143 }
3144 free(RemoveListItem(&(*lists)[undo_wins], CmpAny, NULL));
3145 }
3146
3147 if (addr_len == 0 || msg->header.type == msg_del_wins_cfg)
3148 {
3149 goto out; /* job done */
3150 }
3151
3152 for (unsigned int i = 0; i < addr_len; ++i)
3153 {
3154 RtlIpv4AddressToStringW(&msg->addr[i].ipv4, addr);
3155 err = netsh_wins_cmd(i == 0 ? L"set" : L"add", msg->iface.index, addr);
3156 if (i == 0 && err)
3157 {
3158 goto out;
3159 }
3160 /* We do not check for duplicate addresses, so any error in adding
3161 * additional addresses is ignored.
3162 */
3163 }
3164
3165 PDWORD if_index = malloc(sizeof(msg->iface.index));
3166 if (if_index)
3167 {
3168 *if_index = msg->iface.index;
3169 }
3170
3171 if (!if_index || AddListItem(&(*lists)[undo_wins], if_index))
3172 {
3173 free(if_index);
3174 netsh_wins_cmd(L"delete", msg->iface.index, NULL);
3175 err = ERROR_OUTOFMEMORY;
3176 goto out;
3177 }
3178
3179 err = 0;
3180
3181out:
3182 return err;
3183}
3184
3185static DWORD
3187{
3188 DWORD err = 0;
3189 DWORD timeout = 5000; /* in milli seconds */
3190 wchar_t argv0[MAX_PATH];
3191
3192 /* Path of netsh */
3193 swprintf(argv0, _countof(argv0), L"%ls\\%ls", get_win_sys_path(), L"netsh.exe");
3194
3195 /* cmd template:
3196 * netsh interface ipv4 set address name=$if_index source=dhcp
3197 */
3198 const wchar_t *fmt = L"netsh interface ipv4 set address name=\"%lu\" source=dhcp";
3199
3200 /* max cmdline length in wchars -- include room for if index:
3201 * 10 chars for 32 bit int in decimal and +1 for NUL
3202 */
3203 size_t ncmdline = wcslen(fmt) + 10 + 1;
3204 wchar_t *cmdline = malloc(ncmdline * sizeof(wchar_t));
3205 if (!cmdline)
3206 {
3207 err = ERROR_OUTOFMEMORY;
3208 return err;
3209 }
3210
3211 swprintf(cmdline, ncmdline, fmt, dhcp->iface.index);
3212
3213 err = ExecCommand(argv0, cmdline, timeout);
3214
3215 /* Note: This could fail if dhcp is already enabled, so the caller
3216 * may not want to treat errors as FATAL.
3217 */
3218
3219 free(cmdline);
3220 return err;
3221}
3222
3223static DWORD
3225{
3226 DWORD err = 0;
3227 MIB_IPINTERFACE_ROW ipiface;
3228 InitializeIpInterfaceEntry(&ipiface);
3229 ipiface.Family = mtu->family;
3230 ipiface.InterfaceIndex = mtu->iface.index;
3231 err = GetIpInterfaceEntry(&ipiface);
3232 if (err != NO_ERROR)
3233 {
3234 return err;
3235 }
3236 if (mtu->family == AF_INET)
3237 {
3238 ipiface.SitePrefixLength = 0;
3239 }
3240 ipiface.NlMtu = mtu->mtu;
3241
3242 err = SetIpInterfaceEntry(&ipiface);
3243 return err;
3244}
3245
3253static DWORD
3255{
3256 const WCHAR *hwid;
3257
3258 switch (msg->adapter_type)
3259 {
3260 case ADAPTER_TYPE_DCO:
3261 hwid = L"ovpn-dco";
3262 break;
3263
3264 case ADAPTER_TYPE_TAP:
3265 hwid = L"root\\tap0901";
3266 break;
3267
3268 default:
3269 return ERROR_INVALID_PARAMETER;
3270 }
3271
3272 WCHAR cmd[MAX_PATH];
3273 WCHAR args[MAX_PATH];
3274
3275 if (swprintf_s(cmd, _countof(cmd), L"%s\\tapctl.exe", settings.bin_dir) < 0)
3276 {
3277 return ERROR_BUFFER_OVERFLOW;
3278 }
3279
3280 if (swprintf_s(args, _countof(args), L"tapctl create --hwid %s", hwid) < 0)
3281 {
3282 return ERROR_BUFFER_OVERFLOW;
3283 }
3284
3285 return ExecCommand(cmd, args, 10000);
3286}
3287
3288static VOID
3289HandleMessage(HANDLE pipe, PPROCESS_INFORMATION proc_info, DWORD bytes, DWORD count,
3290 LPHANDLE events, undo_lists_t *lists)
3291{
3293 ack_message_t ack = {
3294 .header = { .type = msg_acknowledgement, .size = sizeof(ack), .message_id = -1 },
3295 .error_number = ERROR_MESSAGE_DATA
3296 };
3297
3298 DWORD read = ReadPipeAsync(pipe, &msg, bytes, count, events);
3299 if (read != bytes || read < sizeof(msg.header) || read != msg.header.size)
3300 {
3301 goto out;
3302 }
3303
3304 ack.header.message_id = msg.header.message_id;
3305
3306 switch (msg.header.type)
3307 {
3308 case msg_add_address:
3309 case msg_del_address:
3310 if (msg.header.size == sizeof(msg.address))
3311 {
3312 ack.error_number = HandleAddressMessage(&msg.address, lists);
3313 }
3314 break;
3315
3316 case msg_add_route:
3317 case msg_del_route:
3318 if (msg.header.size == sizeof(msg.route))
3319 {
3320 ack.error_number = HandleRouteMessage(&msg.route, lists);
3321 }
3322 break;
3323
3325 if (msg.header.size == sizeof(msg.flush_neighbors))
3326 {
3327 ack.error_number = HandleFlushNeighborsMessage(&msg.flush_neighbors);
3328 }
3329 break;
3330
3331 case msg_add_wfp_block:
3332 case msg_del_wfp_block:
3333 if (msg.header.size == sizeof(msg.wfp_block))
3334 {
3335 ack.error_number = HandleWfpBlockMessage(&msg.wfp_block, lists);
3336 }
3337 break;
3338
3339 case msg_register_dns:
3341 break;
3342
3343 case msg_add_dns_cfg:
3344 case msg_del_dns_cfg:
3345 if (msg.header.size == sizeof(msg.dns))
3346 {
3347 ack.error_number = HandleDNSConfigMessage(&msg.dns, lists);
3348 }
3349 break;
3350
3351 case msg_add_nrpt_cfg:
3352 case msg_del_nrpt_cfg:
3353 if (msg.header.size == sizeof(msg.nrpt_dns))
3354 {
3355 DWORD ovpn_pid = proc_info->dwProcessId;
3356 ack.error_number = HandleDNSConfigNrptMessage(&msg.nrpt_dns, ovpn_pid, lists);
3357 }
3358 break;
3359
3360 case msg_add_wins_cfg:
3361 case msg_del_wins_cfg:
3362 if (msg.header.size == sizeof(msg.wins))
3363 {
3364 ack.error_number = HandleWINSConfigMessage(&msg.wins, lists);
3365 }
3366 break;
3367
3368 case msg_enable_dhcp:
3369 if (msg.header.size == sizeof(msg.dhcp))
3370 {
3372 }
3373 break;
3374
3375 case msg_set_mtu:
3376 if (msg.header.size == sizeof(msg.mtu))
3377 {
3378 ack.error_number = HandleMTUMessage(&msg.mtu);
3379 }
3380 break;
3381
3382 case msg_create_adapter:
3383 if (msg.header.size == sizeof(msg.create_adapter))
3384 {
3385 ack.error_number = HandleCreateAdapterMessage(&msg.create_adapter);
3386 }
3387 break;
3388
3389 default:
3391 MsgToEventLog(MSG_FLAGS_ERROR, L"Unknown message type %d", msg.header.type);
3392 break;
3393 }
3394
3395out:
3396 WritePipeAsync(pipe, &ack, sizeof(ack), count, events);
3397}
3398
3399
3400static VOID
3402{
3403 undo_type_t type;
3404 wfp_block_data_t *interface_data;
3405 for (type = 0; type < _undo_type_max; type++)
3406 {
3407 list_item_t **pnext = &(*lists)[type];
3408 while (*pnext)
3409 {
3410 list_item_t *item = *pnext;
3411 switch (type)
3412 {
3413 case address:
3414 DeleteAddress(item->data);
3415 break;
3416
3417 case route:
3418 DeleteRoute(item->data);
3419 break;
3420
3421 case undo_dns4:
3422 ResetNameServers(item->data, AF_INET);
3423 break;
3424
3425 case undo_dns6:
3426 ResetNameServers(item->data, AF_INET6);
3427 break;
3428
3429 case undo_nrpt:
3430 UndoNrptRules(*(PDWORD)item->data);
3431 break;
3432
3433 case undo_domains:
3435 break;
3436
3437 case undo_wins:
3438 netsh_wins_cmd(L"delete", *(PDWORD)item->data, NULL);
3439 break;
3440
3441 case wfp_block:
3442 interface_data = (wfp_block_data_t *)(item->data);
3443 delete_wfp_block_filters(interface_data->engine);
3444 if (interface_data->metric_v4 >= 0)
3445 {
3446 set_interface_metric(interface_data->index, AF_INET,
3447 interface_data->metric_v4);
3448 }
3449 if (interface_data->metric_v6 >= 0)
3450 {
3451 set_interface_metric(interface_data->index, AF_INET6,
3452 interface_data->metric_v6);
3453 }
3454 break;
3455
3456 case _undo_type_max:
3457 /* unreachable */
3458 break;
3459 }
3460
3461 /* Remove from the list and free memory */
3462 *pnext = item->next;
3463 free(item->data);
3464 free(item);
3465 }
3466 }
3467}
3468
3476static BOOL
3477IsUserEnvVar(PCWSTR var)
3478{
3479 static PCWSTR user_vars[] = { L"APPDATA=", L"LOCALAPPDATA=", L"TEMP=", L"TMP=",
3480 L"USERDOMAIN=", L"USERNAME=", L"USERPROFILE=" };
3481
3482 for (size_t i = 0; i < _countof(user_vars); ++i)
3483 {
3484 if (wcsncmp(var, user_vars[i], wcslen(user_vars[i])) == 0)
3485 {
3486 return TRUE;
3487 }
3488 }
3489 return FALSE;
3490}
3491
3499static size_t
3500EnvBlockSize(PCWSTR env)
3501{
3502 PCWSTR var = env;
3503 while (*var)
3504 {
3505 var += wcslen(var) + 1;
3506 }
3507 return ((size_t)(var - env) + 1) * sizeof(*env);
3508}
3509
3524static PWSTR
3525MergeOpenvpnEnvironment(PCWSTR sys_env, PCWSTR usr_env)
3526{
3527 PWSTR block = malloc(EnvBlockSize(sys_env) + EnvBlockSize(usr_env));
3528 if (!block)
3529 {
3530 return NULL;
3531 }
3532
3533 PWSTR pos = block;
3534 for (PCWSTR var = sys_env; *var; var += wcslen(var) + 1)
3535 {
3536 if (!IsUserEnvVar(var))
3537 {
3538 size_t len = wcslen(var) + 1;
3539 wmemcpy(pos, var, len);
3540 pos += len;
3541 }
3542 }
3543 for (PCWSTR var = usr_env; *var; var += wcslen(var) + 1)
3544 {
3545 if (IsUserEnvVar(var))
3546 {
3547 size_t len = wcslen(var) + 1;
3548 wmemcpy(pos, var, len);
3549 pos += len;
3550 }
3551 }
3552 *pos = L'\0';
3553
3554 return block;
3555}
3556
3569static BOOL
3570CreateOpenvpnEnvironment(HANDLE token, PWSTR *env)
3571{
3572 LPVOID sys_env = NULL;
3573 LPVOID usr_env = NULL;
3574 BOOL ret = FALSE;
3575
3576 if (!CreateEnvironmentBlock(&sys_env, NULL, FALSE)
3577 || !CreateEnvironmentBlock(&usr_env, token, FALSE))
3578 {
3579 goto out;
3580 }
3581
3582 *env = MergeOpenvpnEnvironment(sys_env, usr_env);
3583 if (!*env)
3584 {
3585 SetLastError(ERROR_OUTOFMEMORY);
3586 goto out;
3587 }
3588 ret = TRUE;
3589
3590out:
3591 DestroyEnvironmentBlock(sys_env);
3592 DestroyEnvironmentBlock(usr_env);
3593 return ret;
3594}
3595
3596static DWORD WINAPI
3597RunOpenvpn(LPVOID p)
3598{
3599 HANDLE pipe = p;
3600 HANDLE ovpn_pipe = NULL, svc_pipe = NULL;
3601 PTOKEN_USER svc_user = NULL, ovpn_user = NULL;
3602 HANDLE svc_token = NULL, imp_token = NULL, pri_token = NULL;
3603 HANDLE stdin_read = NULL, stdin_write = NULL;
3604 HANDLE stdout_write = NULL;
3605 DWORD pipe_mode, len, exit_code = 0;
3606 STARTUP_DATA sud = { 0, 0, 0 };
3607 STARTUPINFOW startup_info;
3608 PROCESS_INFORMATION proc_info;
3609 PWSTR ovpn_env = NULL;
3610 WCHAR ovpn_pipe_name[256]; /* The entire pipe name string can be up to 256 characters long
3611 according to MSDN. */
3612 LPCWSTR exe_path;
3613 WCHAR *cmdline = NULL;
3614 size_t cmdline_size;
3615 undo_lists_t undo_lists;
3616 WCHAR errmsg[512] = L"";
3617 BOOL flush_pipe = TRUE;
3618
3619 SECURITY_ATTRIBUTES inheritable = { .nLength = sizeof(inheritable),
3620 .lpSecurityDescriptor = NULL,
3621 .bInheritHandle = TRUE };
3622
3623 PACL ovpn_dacl = NULL;
3624 PSECURITY_DESCRIPTOR pSD = NULL;
3625 EXPLICIT_ACCESS ea[2];
3626 SECURITY_DESCRIPTOR ovpn_sd;
3627 SECURITY_ATTRIBUTES ovpn_sa = { .nLength = sizeof(ovpn_sa),
3628 .lpSecurityDescriptor = &ovpn_sd,
3629 .bInheritHandle = FALSE };
3630
3631 ZeroMemory(&ea, sizeof(ea));
3632 ZeroMemory(&startup_info, sizeof(startup_info));
3633 ZeroMemory(&undo_lists, sizeof(undo_lists));
3634 ZeroMemory(&proc_info, sizeof(proc_info));
3635
3636 if (!GetStartupData(pipe, &sud))
3637 {
3638 flush_pipe = FALSE; /* client did not provide startup data */
3639 goto out;
3640 }
3641
3642 if (!InitializeSecurityDescriptor(&ovpn_sd, SECURITY_DESCRIPTOR_REVISION))
3643 {
3644 ReturnLastError(pipe, L"InitializeSecurityDescriptor");
3645 goto out;
3646 }
3647
3648 /* Get SID of user the service is running under */
3649 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &svc_token))
3650 {
3651 ReturnLastError(pipe, L"OpenProcessToken");
3652 goto out;
3653 }
3654 len = 0;
3655 while (!GetTokenInformation(svc_token, TokenUser, svc_user, len, &len))
3656 {
3657 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
3658 {
3659 ReturnLastError(pipe, L"GetTokenInformation (service token)");
3660 goto out;
3661 }
3662 free(svc_user);
3663 svc_user = malloc(len);
3664 if (svc_user == NULL)
3665 {
3666 ReturnLastError(pipe, L"malloc (service token user)");
3667 goto out;
3668 }
3669 }
3670 if (!IsValidSid(svc_user->User.Sid))
3671 {
3672 ReturnLastError(pipe, L"IsValidSid (service token user)");
3673 goto out;
3674 }
3675
3676 if (!ImpersonateNamedPipeClient(pipe))
3677 {
3678 ReturnLastError(pipe, L"ImpersonateNamedPipeClient");
3679 goto out;
3680 }
3681 if (!OpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS, FALSE, &imp_token))
3682 {
3683 ReturnLastError(pipe, L"OpenThreadToken");
3684 goto out;
3685 }
3686 len = 0;
3687 while (!GetTokenInformation(imp_token, TokenUser, ovpn_user, len, &len))
3688 {
3689 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
3690 {
3691 ReturnLastError(pipe, L"GetTokenInformation (impersonation token)");
3692 goto out;
3693 }
3694 free(ovpn_user);
3695 ovpn_user = malloc(len);
3696 if (ovpn_user == NULL)
3697 {
3698 ReturnLastError(pipe, L"malloc (impersonation token user)");
3699 goto out;
3700 }
3701 }
3702 if (!IsValidSid(ovpn_user->User.Sid))
3703 {
3704 ReturnLastError(pipe, L"IsValidSid (impersonation token user)");
3705 goto out;
3706 }
3707
3708 /* OpenVPN process DACL entry for access by service and user */
3709 ea[0].grfAccessPermissions = SPECIFIC_RIGHTS_ALL | STANDARD_RIGHTS_ALL;
3710 ea[0].grfAccessMode = SET_ACCESS;
3711 ea[0].grfInheritance = NO_INHERITANCE;
3712 ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
3713 ea[0].Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;
3714 ea[0].Trustee.ptstrName = (LPWSTR)svc_user->User.Sid;
3715 ea[1].grfAccessPermissions = READ_CONTROL | PROCESS_VM_READ | SYNCHRONIZE
3716 | PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION;
3717 ea[1].grfAccessMode = SET_ACCESS;
3718 ea[1].grfInheritance = NO_INHERITANCE;
3719 ea[1].Trustee.TrusteeForm = TRUSTEE_IS_SID;
3720 ea[1].Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;
3721 ea[1].Trustee.ptstrName = (LPWSTR)ovpn_user->User.Sid;
3722
3723 /* Set owner and DACL of OpenVPN security descriptor */
3724 if (!SetSecurityDescriptorOwner(&ovpn_sd, svc_user->User.Sid, FALSE))
3725 {
3726 ReturnLastError(pipe, L"SetSecurityDescriptorOwner");
3727 goto out;
3728 }
3729 if (SetEntriesInAcl(2, ea, NULL, &ovpn_dacl) != ERROR_SUCCESS)
3730 {
3731 ReturnLastError(pipe, L"SetEntriesInAcl");
3732 goto out;
3733 }
3734 if (!SetSecurityDescriptorDacl(&ovpn_sd, TRUE, ovpn_dacl, FALSE))
3735 {
3736 ReturnLastError(pipe, L"SetSecurityDescriptorDacl");
3737 goto out;
3738 }
3739
3740 /*
3741 * Add a SACL to the openvpn security descriptor with a medium integrity label ACE.
3742 * This makes it possible to still query the process info and terminate the process
3743 * from the GUI. The high integrity label assigned to the process' primary token
3744 * would otherwise prevent this.
3745 */
3746 BYTE medium_sid[SECURITY_MAX_SID_SIZE];
3747 DWORD medium_sid_size = sizeof(medium_sid);
3748 DWORD sacl_buf[(sizeof(ACL) + sizeof(SYSTEM_MANDATORY_LABEL_ACE) + SECURITY_MAX_SID_SIZE) / sizeof(DWORD) + 1]; /* must be DWORD aligned */
3749 PACL sacl = (PACL)sacl_buf;
3750 if (!CreateWellKnownSid(WinMediumLabelSid, NULL, medium_sid, &medium_sid_size)
3751 || !InitializeAcl(sacl, (DWORD)sizeof(sacl_buf), ACL_REVISION)
3752 || !AddMandatoryAce(sacl, ACL_REVISION, 0, SYSTEM_MANDATORY_LABEL_NO_WRITE_UP, medium_sid)
3753 || !SetSecurityDescriptorSacl(&ovpn_sd, TRUE, sacl, FALSE))
3754 {
3755 ReturnLastError(pipe, L"SetSecurityDescriptorSacl");
3756 goto out;
3757 }
3758
3759 /* Create primary token from impersonation token */
3760 if (!DuplicateTokenEx(imp_token, TOKEN_ALL_ACCESS, NULL, 0, TokenPrimary, &pri_token))
3761 {
3762 ReturnLastError(pipe, L"DuplicateTokenEx");
3763 goto out;
3764 }
3765
3766 /*
3767 * Run openvpn at high integrity, so that the user cannot write to its threads.
3768 * Raising the level requires the privileges of the service, so stop
3769 * impersonating the user while doing it.
3770 */
3771 BYTE high_sid[SECURITY_MAX_SID_SIZE];
3772 DWORD high_sid_size = sizeof(high_sid);
3773 if (!RevertToSelf())
3774 {
3775 ReturnLastError(pipe, L"RevertToSelf");
3776 goto out;
3777 }
3778 if (!CreateWellKnownSid(WinHighLabelSid, NULL, high_sid, &high_sid_size))
3779 {
3780 ReturnLastError(pipe, L"CreateWellKnownSid");
3781 goto out;
3782 }
3783 TOKEN_MANDATORY_LABEL label = { .Label = { .Sid = high_sid, .Attributes = SE_GROUP_INTEGRITY } };
3784 DWORD label_size = sizeof(label) + GetLengthSid(high_sid);
3785 if (!SetTokenInformation(pri_token, TokenIntegrityLevel, &label, label_size))
3786 {
3787 ReturnLastError(pipe, L"SetTokenInformation");
3788 goto out;
3789 }
3790 if (!SetThreadToken(NULL, imp_token))
3791 {
3792 ReturnLastError(pipe, L"SetThreadToken");
3793 goto out;
3794 }
3795
3796 /* use /dev/null for stdout of openvpn (client should use --log for output) */
3797 stdout_write = CreateFile(_L("NUL"), GENERIC_WRITE, FILE_SHARE_WRITE, &inheritable,
3798 OPEN_EXISTING, 0, NULL);
3799 if (stdout_write == INVALID_HANDLE_VALUE)
3800 {
3801 ReturnLastError(pipe, L"CreateFile for stdout");
3802 goto out;
3803 }
3804
3805 if (!CreatePipe(&stdin_read, &stdin_write, &inheritable, 0)
3806 || !SetHandleInformation(stdin_write, HANDLE_FLAG_INHERIT, 0))
3807 {
3808 ReturnLastError(pipe, L"CreatePipe");
3809 goto out;
3810 }
3811
3812 UUID pipe_uuid;
3813 RPC_STATUS rpc_stat = UuidCreate(&pipe_uuid);
3814 if (rpc_stat != RPC_S_OK)
3815 {
3816 ReturnError(pipe, rpc_stat, L"UuidCreate", 1, &exit_event);
3817 goto out;
3818 }
3819
3820 RPC_WSTR pipe_uuid_str = NULL;
3821 rpc_stat = UuidToStringW(&pipe_uuid, &pipe_uuid_str);
3822 if (rpc_stat != RPC_S_OK)
3823 {
3824 ReturnError(pipe, rpc_stat, L"UuidToString", 1, &exit_event);
3825 goto out;
3826 }
3827 swprintf(ovpn_pipe_name, _countof(ovpn_pipe_name),
3828 // cppcheck-suppress unknownMacro ; FP, complains about _L only here...
3829 L"\\\\.\\pipe\\" _L(PACKAGE) L"%ls\\service_%lu_%ls", service_instance,
3830 GetCurrentThreadId(), pipe_uuid_str);
3831 RpcStringFreeW(&pipe_uuid_str);
3832
3833 /* make a security descriptor for the named pipe with access
3834 * restricted to the user and SYSTEM
3835 */
3836
3837 SECURITY_ATTRIBUTES sa;
3838 LPCWSTR szSDDL = L"D:(A;;GA;;;SY)(A;;GA;;;OW)";
3839 if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(
3840 szSDDL, SDDL_REVISION_1, &pSD, NULL))
3841 {
3842 ReturnLastError(pipe, L"ConvertSDDL");
3843 goto out;
3844 }
3845 sa.nLength = sizeof(sa);
3846 sa.lpSecurityDescriptor = pSD;
3847 sa.bInheritHandle = FALSE;
3848
3849 ovpn_pipe = CreateNamedPipe(
3850 ovpn_pipe_name, PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE | FILE_FLAG_OVERLAPPED,
3851 PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS, 1, 128, 128, 0, &sa);
3852 if (ovpn_pipe == INVALID_HANDLE_VALUE)
3853 {
3854 ReturnLastError(pipe, L"CreateNamedPipe");
3855 goto out;
3856 }
3857
3858 svc_pipe = CreateFile(ovpn_pipe_name, GENERIC_READ | GENERIC_WRITE, 0, &inheritable,
3859 OPEN_EXISTING, 0, NULL);
3860 if (svc_pipe == INVALID_HANDLE_VALUE)
3861 {
3862 ReturnLastError(pipe, L"CreateFile");
3863 goto out;
3864 }
3865
3866 pipe_mode = PIPE_READMODE_MESSAGE;
3867 if (!SetNamedPipeHandleState(svc_pipe, &pipe_mode, NULL, NULL))
3868 {
3869 ReturnLastError(pipe, L"SetNamedPipeHandleState");
3870 goto out;
3871 }
3872
3873 cmdline_size = wcslen(sud.options) + 128;
3874 cmdline = malloc(cmdline_size * sizeof(*cmdline));
3875 if (cmdline == NULL)
3876 {
3877 ReturnLastError(pipe, L"malloc");
3878 goto out;
3879 }
3880 /* there seem to be no common printf specifier that works on all
3881 * mingw/msvc platforms without trickery, so convert to void* and use
3882 * PRIuPTR to print that as best compromise */
3883 swprintf(cmdline, cmdline_size, L"openvpn --msg-channel %" PRIuPTR L" %ls",
3884 (uintptr_t)svc_pipe, sud.options);
3885
3886 if (StartsWithNonOption(cmdline))
3887 {
3889 L"Options must start with an option, pass the config file with --config", 1,
3890 &exit_event);
3891 goto out;
3892 }
3893
3894 /*
3895 * Only authorized users are allowed to use any command line options or
3896 * have the config file in locations other than the global config directory.
3897 *
3898 * Check options are white-listed and config is in the global directory
3899 * OR user is authorized to run any config.
3900 */
3901 if (!ValidateOptions(pipe, sud.directory, cmdline, errmsg, _countof(errmsg))
3902 && !IsAuthorizedUser(ovpn_user->User.Sid, imp_token, settings.ovpn_admin_group,
3904 {
3905 ReturnError(pipe, ERROR_STARTUP_DATA, errmsg, 1, &exit_event);
3906 goto out;
3907 }
3908
3909 if (!CreateOpenvpnEnvironment(imp_token, &ovpn_env))
3910 {
3911 ReturnLastError(pipe, L"CreateOpenvpnEnvironment");
3912 goto out;
3913 }
3914
3915 startup_info.cb = sizeof(startup_info);
3916 startup_info.dwFlags = STARTF_USESTDHANDLES;
3917 startup_info.hStdInput = stdin_read;
3918 startup_info.hStdOutput = stdout_write;
3919 startup_info.hStdError = stdout_write;
3920
3921 exe_path = settings.exe_path;
3922
3923 /* TODO: make sure HKCU is correct or call LoadUserProfile() */
3924 if (!CreateProcessAsUserW(pri_token, exe_path, cmdline, &ovpn_sa, NULL, TRUE,
3925 settings.priority | CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT,
3926 ovpn_env, sud.directory, &startup_info, &proc_info))
3927 {
3928 ReturnLastError(pipe, L"CreateProcessAsUser");
3929 goto out;
3930 }
3931
3932 if (!RevertToSelf())
3933 {
3934 TerminateProcess(proc_info.hProcess, 1);
3935 ReturnLastError(pipe, L"RevertToSelf");
3936 goto out;
3937 }
3938
3939 ReturnProcessId(pipe, proc_info.dwProcessId, 1, &exit_event);
3940
3941 CloseHandleEx(&stdout_write);
3942 CloseHandleEx(&stdin_read);
3943 CloseHandleEx(&svc_pipe);
3944
3945 DWORD input_size = WideCharToMultiByte(CP_UTF8, 0, sud.std_input, -1, NULL, 0, NULL, NULL);
3946 LPSTR input = NULL;
3947 if (input_size && (input = malloc(input_size)))
3948 {
3949 DWORD written;
3950 WideCharToMultiByte(CP_UTF8, 0, sud.std_input, -1, input, input_size, NULL, NULL);
3951 WriteFile(stdin_write, input, (DWORD)strlen(input), &written, NULL);
3952 free(input);
3953 }
3954
3955 while (TRUE)
3956 {
3957 DWORD bytes = PeekNamedPipeAsync(ovpn_pipe, 1, &exit_event);
3958 if (bytes == 0)
3959 {
3960 break;
3961 }
3962
3963 if (bytes > sizeof(pipe_message_t))
3964 {
3965 /* process at the other side of the pipe is misbehaving, shut it down */
3968 L"OpenVPN process sent too large payload length to the pipe (%lu bytes), it will be terminated",
3969 bytes);
3970 break;
3971 }
3972
3973 HandleMessage(ovpn_pipe, &proc_info, bytes, 1, &exit_event, &undo_lists);
3974 }
3975
3976 WaitForSingleObject(proc_info.hProcess, IO_TIMEOUT);
3977 GetExitCodeProcess(proc_info.hProcess, &exit_code);
3978 if (exit_code == STILL_ACTIVE)
3979 {
3980 TerminateProcess(proc_info.hProcess, 1);
3981 }
3982 else if (exit_code != 0)
3983 {
3984 WCHAR buf[256];
3985 swprintf(buf, _countof(buf), L"OpenVPN exited with error: exit code = %lu", exit_code);
3987 }
3988 Undo(&undo_lists);
3989
3990out:
3991 if (flush_pipe)
3992 {
3993 FlushFileBuffers(pipe);
3994 }
3995 DisconnectNamedPipe(pipe);
3996
3997 free(ovpn_user);
3998 free(svc_user);
3999 free(cmdline);
4000 LocalFree(pSD);
4001 LocalFree(ovpn_dacl);
4002 free(ovpn_env);
4003 FreeStartupData(&sud);
4004 CloseHandleEx(&proc_info.hProcess);
4005 CloseHandleEx(&proc_info.hThread);
4006 CloseHandleEx(&stdin_read);
4007 CloseHandleEx(&stdin_write);
4008 CloseHandleEx(&stdout_write);
4009 CloseHandleEx(&svc_token);
4010 CloseHandleEx(&imp_token);
4011 CloseHandleEx(&pri_token);
4012 CloseHandleEx(&ovpn_pipe);
4013 CloseHandleEx(&svc_pipe);
4014 CloseHandleEx(&pipe);
4015
4016 return 0;
4017}
4018
4019#if defined(__GNUC__) || defined(__clang__)
4020#pragma GCC diagnostic pop
4021#endif
4022
4023static DWORD WINAPI
4024ServiceCtrlInteractive(DWORD ctrl_code, DWORD event, LPVOID data, LPVOID ctx)
4025{
4026 SERVICE_STATUS *svc_status = ctx;
4027 switch (ctrl_code)
4028 {
4029 case SERVICE_CONTROL_STOP:
4030 svc_status->dwCurrentState = SERVICE_STOP_PENDING;
4031 ReportStatusToSCMgr(service, svc_status);
4032 if (exit_event)
4033 {
4034 SetEvent(exit_event);
4035 }
4036 return NO_ERROR;
4037
4038 case SERVICE_CONTROL_INTERROGATE:
4039 return NO_ERROR;
4040
4041 default:
4042 return ERROR_CALL_NOT_IMPLEMENTED;
4043 }
4044}
4045
4046
4047static HANDLE
4049{
4050 /*
4051 * allow all access for local system
4052 * deny FILE_CREATE_PIPE_INSTANCE for everyone
4053 * allow read/write for authenticated users
4054 * deny all access to anonymous
4055 */
4056 const WCHAR *sddlString =
4057 L"D:(A;OICI;GA;;;S-1-5-18)(D;OICI;0x4;;;S-1-1-0)(A;OICI;GRGW;;;S-1-5-11)(D;;GA;;;S-1-5-7)";
4058
4059 PSECURITY_DESCRIPTOR sd = NULL;
4060 if (!ConvertStringSecurityDescriptorToSecurityDescriptor(sddlString, SDDL_REVISION_1, &sd,
4061 NULL))
4062 {
4063 MsgToEventLog(M_SYSERR, L"ConvertStringSecurityDescriptorToSecurityDescriptor failed.");
4064 return INVALID_HANDLE_VALUE;
4065 }
4066
4067 /* Set up SECURITY_ATTRIBUTES */
4068 SECURITY_ATTRIBUTES sa = { 0 };
4069 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4070 sa.lpSecurityDescriptor = sd;
4071 sa.bInheritHandle = FALSE;
4072
4073 DWORD flags = PIPE_ACCESS_DUPLEX | WRITE_DAC | FILE_FLAG_OVERLAPPED;
4074
4075 static BOOL first = TRUE;
4076 if (first)
4077 {
4078 flags |= FILE_FLAG_FIRST_PIPE_INSTANCE;
4079 first = FALSE;
4080 }
4081
4082 WCHAR pipe_name[256]; /* The entire pipe name string can be up to 256 characters long according
4083 to MSDN. */
4084 swprintf(pipe_name, _countof(pipe_name), L"\\\\.\\pipe\\" _L(PACKAGE) L"%ls\\service",
4086 HANDLE pipe = CreateNamedPipe(
4087 pipe_name, flags, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_REJECT_REMOTE_CLIENTS,
4088 PIPE_UNLIMITED_INSTANCES, 1024, 1024, 0, &sa);
4089
4090 LocalFree(sd);
4091
4092 if (pipe == INVALID_HANDLE_VALUE)
4093 {
4094 MsgToEventLog(M_SYSERR, L"Could not create named pipe");
4095 return INVALID_HANDLE_VALUE;
4096 }
4097
4098 return pipe;
4099}
4100
4101
4102static DWORD
4103UpdateWaitHandles(LPHANDLE *handles_ptr, LPDWORD count, HANDLE io_event,
4104 const list_item_t *threads)
4105{
4106 static DWORD size = 10;
4107 static LPHANDLE handles = NULL;
4108 DWORD pos = 0;
4109
4110 if (handles == NULL)
4111 {
4112 handles = malloc(size * sizeof(HANDLE));
4113 *handles_ptr = handles;
4114 if (handles == NULL)
4115 {
4116 return ERROR_OUTOFMEMORY;
4117 }
4118 }
4119
4120 handles[pos++] = io_event;
4121
4122 if (!threads)
4123 {
4124 handles[pos++] = exit_event;
4125 }
4126
4127 while (threads)
4128 {
4129 if (pos == size)
4130 {
4131 LPHANDLE tmp;
4132 size += 10;
4133 tmp = realloc(handles, size * sizeof(HANDLE));
4134 if (tmp == NULL)
4135 {
4136 size -= 10;
4137 *count = pos;
4138 return ERROR_OUTOFMEMORY;
4139 }
4140 handles = tmp;
4141 *handles_ptr = handles;
4142 }
4143 handles[pos++] = threads->data;
4144 threads = threads->next;
4145 }
4146
4147 *count = pos;
4148 return NO_ERROR;
4149}
4150
4151
4152static VOID
4154{
4155 free(h);
4156}
4157
4158static BOOL
4159CmpHandle(LPVOID item, LPVOID hnd)
4160{
4161 return item == hnd;
4162}
4163
4164
4165VOID WINAPI
4166ServiceStartInteractiveOwn(DWORD dwArgc, LPWSTR *lpszArgv)
4167{
4168 status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
4169 ServiceStartInteractive(dwArgc, lpszArgv);
4170}
4171
4177static void
4179{
4180 BOOL changed = FALSE;
4181
4182 /* Clean up leftover NRPT rules */
4183 BOOL gpol_nrpt;
4184 changed = DeleteNrptRules(0, &gpol_nrpt);
4185
4186 /* Clean up leftover DNS search list fragments */
4187 HKEY key;
4188 BOOL gpol_list;
4189 GetDnsSearchListKey(NULL, &gpol_list, &key);
4190 if (key != INVALID_HANDLE_VALUE)
4191 {
4193 {
4194 changed = TRUE;
4195 }
4196 RegCloseKey(key);
4197 }
4198
4199 if (changed)
4200 {
4201 ApplyDnsSettings(gpol_nrpt || gpol_list);
4202 }
4203}
4204
4205VOID WINAPI
4206ServiceStartInteractive(DWORD dwArgc, LPWSTR *lpszArgv)
4207{
4208 HANDLE pipe, io_event = NULL;
4209 OVERLAPPED overlapped;
4210 DWORD error = NO_ERROR;
4211 list_item_t *threads = NULL;
4212 PHANDLE handles = NULL;
4213 DWORD handle_count;
4214
4215 service =
4216 RegisterServiceCtrlHandlerEx(interactive_service.name, ServiceCtrlInteractive, &status);
4217 if (!service)
4218 {
4219 return;
4220 }
4221
4222 status.dwCurrentState = SERVICE_START_PENDING;
4223 status.dwServiceSpecificExitCode = NO_ERROR;
4224 status.dwWin32ExitCode = NO_ERROR;
4225 status.dwWaitHint = 3000;
4227
4228 /* Clean up potentially left over registry values */
4230
4231 /* Read info from registry in key HKLM\SOFTWARE\OpenVPN */
4232 error = GetOpenvpnSettings(&settings);
4233 if (error != ERROR_SUCCESS)
4234 {
4235 goto out;
4236 }
4237
4238 io_event = InitOverlapped(&overlapped);
4239 exit_event = CreateEvent(NULL, TRUE, FALSE, NULL);
4240 if (!exit_event || !io_event)
4241 {
4242 error = MsgToEventLog(M_SYSERR, L"Could not create event");
4243 goto out;
4244 }
4245
4246 rdns_semaphore = CreateSemaphoreW(NULL, 1, 1, NULL);
4247 if (!rdns_semaphore)
4248 {
4249 error = MsgToEventLog(M_SYSERR, L"Could not create semaphore for register-dns");
4250 goto out;
4251 }
4252
4253 error = UpdateWaitHandles(&handles, &handle_count, io_event, threads);
4254 if (error != NO_ERROR)
4255 {
4256 goto out;
4257 }
4258
4259 pipe = CreateClientPipeInstance();
4260 if (pipe == INVALID_HANDLE_VALUE)
4261 {
4262 goto out;
4263 }
4264
4265 status.dwCurrentState = SERVICE_RUNNING;
4266 status.dwWaitHint = 0;
4268
4269 while (TRUE)
4270 {
4271 if (!ConnectNamedPipe(pipe, &overlapped))
4272 {
4273 DWORD connect_error = GetLastError();
4274 if (connect_error == ERROR_NO_DATA)
4275 {
4276 /*
4277 * Client connected and disconnected before we could process it.
4278 * Disconnect and retry instead of aborting the service.
4279 */
4280 MsgToEventLog(M_ERR, L"ConnectNamedPipe returned ERROR_NO_DATA (client dropped)");
4281 DisconnectNamedPipe(pipe);
4282 ResetOverlapped(&overlapped);
4283 continue;
4284 }
4285 else if (connect_error == ERROR_PIPE_CONNECTED)
4286 {
4287 /* No async I/O pending in this case; signal manually. */
4288 SetEvent(overlapped.hEvent);
4289 }
4290 else if (connect_error != ERROR_IO_PENDING)
4291 {
4292 MsgToEventLog(M_SYSERR, L"Could not connect pipe");
4293 break;
4294 }
4295 }
4296
4297 error = WaitForMultipleObjects(handle_count, handles, FALSE, INFINITE);
4298 if (error == WAIT_OBJECT_0)
4299 {
4300 /* Client connected, spawn a worker thread for it */
4301 HANDLE next_pipe = CreateClientPipeInstance();
4302
4303 /* Avoid exceeding WaitForMultipleObjects MAXIMUM_WAIT_OBJECTS */
4304 if (handle_count + 1 > MAXIMUM_WAIT_OBJECTS)
4305 {
4306 ReturnError(pipe, ERROR_CANT_WAIT, L"Too many concurrent clients", 1, &exit_event);
4307 CloseHandleEx(&pipe);
4308 pipe = next_pipe;
4309 ResetOverlapped(&overlapped);
4310 continue;
4311 }
4312
4313 HANDLE thread = CreateThread(NULL, 0, RunOpenvpn, pipe, CREATE_SUSPENDED, NULL);
4314 if (thread)
4315 {
4316 error = AddListItem(&threads, thread);
4317 if (!error)
4318 {
4319 error =
4320 UpdateWaitHandles(&handles, &handle_count, io_event, threads);
4321 }
4322 if (error)
4323 {
4324 ReturnError(pipe, error, L"Insufficient resources to service new clients", 1,
4325 &exit_event);
4326 /* Update wait handles again after removing the last worker thread */
4327 RemoveListItem(&threads, CmpHandle, thread);
4328 UpdateWaitHandles(&handles, &handle_count, io_event, threads);
4329 TerminateThread(thread, 1);
4330 CloseHandleEx(&thread);
4331 CloseHandleEx(&pipe);
4332 }
4333 else
4334 {
4335 ResumeThread(thread);
4336 }
4337 }
4338 else
4339 {
4340 CloseHandleEx(&pipe);
4341 }
4342
4343 ResetOverlapped(&overlapped);
4344 pipe = next_pipe;
4345 }
4346 else
4347 {
4348 CancelIo(pipe);
4349 if (error == WAIT_FAILED)
4350 {
4351 MsgToEventLog(M_SYSERR, L"WaitForMultipleObjects failed");
4352 SetEvent(exit_event);
4353 /* Give some time for worker threads to exit and then terminate */
4354 Sleep(1000);
4355 break;
4356 }
4357 if (!threads)
4358 {
4359 /* exit event signaled */
4360 CloseHandleEx(&pipe);
4361 ResetEvent(exit_event);
4362 error = NO_ERROR;
4363 break;
4364 }
4365
4366 /* Worker thread ended */
4367 HANDLE thread = RemoveListItem(&threads, CmpHandle, handles[error]);
4368 UpdateWaitHandles(&handles, &handle_count, io_event, threads);
4369 CloseHandleEx(&thread);
4370 }
4371 }
4372
4373out:
4374 FreeWaitHandles(handles);
4375 CloseHandleEx(&io_event);
4378
4379 status.dwCurrentState = SERVICE_STOPPED;
4380 status.dwWin32ExitCode = error;
4382}
wchar_t * utf8to16_size(const char *utf8, int size)
Convert a UTF-8 string to UTF-16.
Definition common.c:301
DWORD MsgToEventLog(DWORD flags, LPCWSTR format,...)
Definition common.c:259
LPCWSTR service_instance
Definition common.c:30
DWORD GetOpenvpnSettings(settings_t *s)
Definition common.c:82
#define PACKAGE_NAME
Definition config.h:492
#define PACKAGE
Definition config.h:486
#define M_INFO
Definition errlevel.h:54
static LSTATUS GetItfDnsServersV4(HKEY itf_key, PSTR addrs, PDWORD size)
Get DNS server IPv4 addresses of an interface.
static LSTATUS SetNameServerAddresses(PWSTR itf_id, const nrpt_address_t *addresses)
Set name servers from a NRPT address list.
static BOOL ValidateOptions(HANDLE pipe, const WCHAR *workdir, const WCHAR *cmdline, WCHAR *errmsg, DWORD capacity)
static VOID ReturnLastError(HANDLE pipe, LPCWSTR func)
static BOOL GetInterfacesKey(short family, PHKEY key)
Return the interfaces registry key for the specified address family.
static DWORD ReadPipeAsync(HANDLE pipe, LPVOID buffer, DWORD size, DWORD count, LPHANDLE events)
static void UndoNrptRules(DWORD ovpn_pid)
Delete a process' NRPT rules and apply the reduced set of rules.
static BOOL ApplyGpolSettings(void)
Signal the DNS resolver (and others potentially) to reload the group policy (DNS) settings.
static VOID ReturnProcessId(HANDLE pipe, DWORD pid, DWORD count, LPHANDLE events)
static BOOL GetDnsSearchListKey(PCSTR itf_name, PBOOL gpol, PHKEY key)
Find the registry key for storing the DNS domains for the VPN interface.
static DWORD HandleWINSConfigMessage(const wins_cfg_message_t *msg, undo_lists_t *lists)
static BOOL CmpAddress(LPVOID item, LPVOID address)
static LSTATUS GetItfDnsDomains(HKEY itf, PCWSTR search_domains, PWSTR domains, PDWORD size)
Return interface specific domain suffix(es)
static DWORD PeekNamedPipeAsyncTimed(HANDLE pipe, DWORD count, LPHANDLE events)
static DWORD PeekNamedPipeAsync(HANDLE pipe, DWORD count, LPHANDLE events)
static BOOL ResetOverlapped(LPOVERLAPPED overlapped)
static DWORD SetNameServers(PCWSTR itf_id, short family, PCSTR addrs)
Set the DNS name servers in a registry interface configuration.
static void SetNrptExcludeRules(HKEY nrpt_key, DWORD ovpn_pid, PCWSTR search_domains)
Set NRPT exclude rules to accompany a catch all rule.
static DWORD ExecCommand(const WCHAR *argv0, const WCHAR *cmdline, DWORD timeout)
static DWORD HandleEnableDHCPMessage(const enable_dhcp_message_t *dhcp)
static BOOL ResetDnsSearchDomains(HKEY key)
Reset the DNS search list to its original value.
static DWORD AddWfpBlock(const wfp_block_message_t *msg, undo_lists_t *lists)
static HANDLE CreateClientPipeInstance(VOID)
static DWORD DeleteWfpBlock(undo_lists_t *lists)
static void GetNrptExcludeData(PCWSTR search_domains, nrpt_exclude_data_t *data, size_t data_size)
Collect interface DNS settings to be used in excluding NRPT rules.
static DWORD SetNameServersValue(PCWSTR itf_id, short family, PCSTR value)
Set the DNS name servers in a registry interface configuration.
static BOOL GetStartupData(HANDLE pipe, STARTUP_DATA *sud)
static BOOL DeleteNrptRules(DWORD pid, PBOOL gpol)
Delete OpenVPN NRPT rules from the registry.
static VOID Undo(undo_lists_t *lists)
static BOOL ApplyDnsSettings(BOOL apply_gpol)
Signal the DNS resolver to reload its settings.
#define ERROR_STARTUP_DATA
Definition interactive.c:47
static DWORD WINAPI RunOpenvpn(LPVOID p)
static settings_t settings
Definition interactive.c:54
VOID WINAPI ServiceStartInteractive(DWORD dwArgc, LPWSTR *lpszArgv)
static BOOL IsUserEnvVar(PCWSTR var)
Check if an environment variable is user-specific.
static PWSTR MergeOpenvpnEnvironment(PCWSTR sys_env, PCWSTR usr_env)
Merge the environment for the openvpn process.
static DWORD DeleteRoute(PMIB_IPFORWARD_ROW2 fwd_row)
static SERVICE_STATUS status
Definition interactive.c:52
static DWORD HandleDNSConfigNrptMessage(const nrpt_dns_cfg_message_t *msg, DWORD ovpn_pid, undo_lists_t *lists)
Add Name Resolution Policy Table (NRPT) rules as documented in https://msdn.microsoft....
static DWORD SetDnsSearchDomains(PCSTR itf_name, PCSTR domains, PBOOL gpol, undo_lists_t *lists)
Add or remove DNS search domains.
static void CleanupRegistry(void)
Clean up remains of previous sessions in registry.
static DWORD netsh_wins_cmd(const wchar_t *action, DWORD if_index, const wchar_t *addr)
Run the command: netsh interface ip $action wins $if_index [static] $addr.
#define ERROR_MESSAGE_TYPE
Definition interactive.c:49
static LPVOID RemoveListItem(list_item_t **pfirst, match_fn_t match, LPVOID ctx)
static BOOL CmpHandle(LPVOID item, LPVOID hnd)
static BOOL ApplyGpolSettings64(void)
Signal the DNS resolver (and others potentially) to reload the group policy (DNS) settings on 64 bit ...
static DWORD HandleAddressMessage(address_message_t *msg, undo_lists_t *lists)
static VOID ReturnError(HANDLE pipe, DWORD error, LPCWSTR func, DWORD count, LPHANDLE events)
static DWORD AddListItem(list_item_t **pfirst, LPVOID data)
static void BlockDNSErrHandler(DWORD err, const char *msg)
static DWORD ResetNameServers(PCWSTR itf_id, short family)
Delete all DNS name servers from a registry interface configuration.
static LSTATUS OpenNrptBaseKey(PHKEY key, PBOOL gpol)
Return the registry key where NRPT rules are stored.
#define RDNS_TIMEOUT
Definition interactive.c:56
undo_type_t
Definition interactive.c:84
@ wfp_block
Definition interactive.c:87
@ _undo_type_max
Definition interactive.c:93
@ undo_dns6
Definition interactive.c:89
@ undo_dns4
Definition interactive.c:88
@ undo_wins
Definition interactive.c:92
@ route
Definition interactive.c:86
@ undo_nrpt
Definition interactive.c:90
@ address
Definition interactive.c:85
@ undo_domains
Definition interactive.c:91
static BOOL HasValidSearchList(HKEY key)
Check for a valid search list in a certain key of the registry.
static DWORD HandleRouteMessage(route_message_t *msg, undo_lists_t *lists)
static DWORD WINAPI RegisterDNS(LPVOID unused)
static HANDLE InitOverlapped(LPOVERLAPPED overlapped)
BOOL(* match_fn_t)(LPVOID item, LPVOID ctx)
static HANDLE CloseHandleEx(LPHANDLE handle)
static DWORD WINAPI ServiceCtrlInteractive(DWORD ctrl_code, DWORD event, LPVOID data, LPVOID ctx)
static BOOL StoreInitialDnsSearchList(HKEY key, PCWSTR list)
Prepare DNS domain "SearchList" registry value, so additional VPN domains can be added and its origin...
struct _list_item list_item_t
static DWORD RegWStringSize(PCWSTR string)
Return correct size for registry value to set for string.
static DWORD DeleteAddress(PMIB_UNICASTIPADDRESS_ROW addr_row)
static BOOL IsInterfaceConnected(PWSTR iid_str)
Check if an interface is connected and up.
#define ERROR_OPENVPN_STARTUP
Definition interactive.c:46
static DWORD SetNrptRules(HKEY nrpt_key, const nrpt_address_t *addresses, const char *domains, const char *search_domains, BOOL dnssec, DWORD ovpn_pid)
Set NRPT rules for a openvpn process.
static LSTATUS GetItfDnsServersV6(HKEY itf_key, PSTR addrs, PDWORD size)
Get DNS server IPv6 addresses of an interface.
static size_t EnvBlockSize(PCWSTR env)
Return the size of an environment block.
static BOOL AppendSearchList(PWSTR list, size_t list_cap, PCWSTR add)
Append a comma-separated list of domains to another comma-separated list, in place.
static BOOL StartsWithNonOption(const WCHAR *cmdline)
Check whether the user options start with a non-option.
static DWORD SetNrptRule(HKEY nrpt_key, PCWSTR subkey, PCSTR address, PCWSTR domains, DWORD dom_size, BOOL dnssec)
Set a NRPT rule (subkey) and its values in the registry.
static BOOL AddDnsSearchDomains(HKEY key, BOOL have_list, PCWSTR domains)
Append domain suffixes to an existing search list.
static VOID FreeWaitHandles(LPHANDLE h)
openvpn_service_t interactive_service
Definition interactive.c:61
VOID WINAPI ServiceStartInteractiveOwn(DWORD dwArgc, LPWSTR *lpszArgv)
static size_t RemoveSearchListTokens(PWSTR list, PCWSTR remove)
Remove tokens from a comma-separated search list with multiset semantics: for each comma-separated to...
static DWORD AsyncPipeOp(async_op_t op, HANDLE pipe, LPVOID buffer, DWORD size, DWORD count, LPHANDLE events)
#define IO_TIMEOUT
Definition interactive.c:44
static BOOL ListContainsDomain(PCWSTR list, PCWSTR domain, size_t len)
Check if a domain is contained in a comma separated list of domains.
static BOOL IsDhcpEnabled(HKEY key)
Checks if DHCP is enabled for an interface.
static BOOL CreateOpenvpnEnvironment(HANDLE token, PWSTR *env)
Create the environment for the openvpn process.
static DWORD HandleFlushNeighborsMessage(flush_neighbors_message_t *msg)
static BOOL ApplyGpolSettings32(void)
Signal the DNS resolver (and others potentially) to reload the group policy (DNS) settings on 32 bit ...
static DWORD HandleMTUMessage(const set_mtu_message_t *mtu)
list_item_t * undo_lists_t[_undo_type_max]
Definition interactive.c:95
static VOID HandleMessage(HANDLE pipe, PPROCESS_INFORMATION proc_info, DWORD bytes, DWORD count, LPHANDLE events, undo_lists_t *lists)
static DWORD HandleRegisterDNSMessage(void)
static void RemoveDnsSearchDomains(HKEY key, PCWSTR domains)
Remove domain suffixes from an existing search list.
static BOOL InitialSearchListExists(HKEY key)
Check if a initial list had already been created.
#define ERROR_MESSAGE_DATA
Definition interactive.c:48
static HANDLE exit_event
Definition interactive.c:53
static VOID FreeStartupData(STARTUP_DATA *sud)
static DWORD HandleWfpBlockMessage(const wfp_block_message_t *msg, undo_lists_t *lists)
static HANDLE rdns_semaphore
Definition interactive.c:55
static DWORD UpdateWaitHandles(LPHANDLE *handles_ptr, LPDWORD count, HANDLE io_event, const list_item_t *threads)
static DWORD InterfaceLuid(const char *iface_name, PNET_LUID luid)
static LSTATUS ConvertItfDnsDomains(PCWSTR search_domains, PWSTR domains, PDWORD size, const DWORD capacity)
Convert interface specific domain suffix(es) from comma-separated string to MULTI_SZ string.
static BOOL CmpRoute(LPVOID item, LPVOID route)
static DWORD HandleDNSConfigMessage(const dns_cfg_message_t *msg, undo_lists_t *lists)
static DWORD TrimNameServers(PSTR addrs)
Remove trailing delimiters from a name server list.
static BOOL CmpAny(LPVOID item, LPVOID any)
async_op_t
@ peek
@ write
@ peek_timed
@ read
static DWORD HandleCreateAdapterMessage(const create_adapter_message_t *msg)
Creates a VPN adapter of the specified type by invoking tapctl.exe.
static DWORD InterfaceIdString(PCSTR itf_name, PWSTR str, size_t len)
Get the string interface UUID (with braces) for an interface alias name.
static SERVICE_STATUS_HANDLE service
Definition interactive.c:51
static DWORD WritePipeAsync(HANDLE pipe, LPVOID data, DWORD size, DWORD count, LPHANDLE events)
static SOCKADDR_INET sockaddr_inet(short family, const inet_address_t *addr)
static void UndoDnsSearchDomains(dns_domains_undo_data_t *undo_data)
Removes DNS domains from a search list they were previously added to.
@ nrpt_dnssec
@ wfp_block_dns
Definition openvpn-msg.h:77
#define TUN_ADAPTER_INDEX_INVALID
Definition openvpn-msg.h:69
char nrpt_address_t[NRPT_ADDR_SIZE]
@ msg_add_nrpt_cfg
Definition openvpn-msg.h:38
@ msg_del_address
Definition openvpn-msg.h:33
@ msg_add_wins_cfg
Definition openvpn-msg.h:49
@ msg_add_address
Definition openvpn-msg.h:32
@ msg_del_wfp_block
Definition openvpn-msg.h:44
@ msg_enable_dhcp
Definition openvpn-msg.h:46
@ msg_add_wfp_block
Definition openvpn-msg.h:43
@ msg_add_route
Definition openvpn-msg.h:34
@ msg_create_adapter
Definition openvpn-msg.h:51
@ msg_del_wins_cfg
Definition openvpn-msg.h:50
@ msg_acknowledgement
Definition openvpn-msg.h:31
@ msg_add_dns_cfg
Definition openvpn-msg.h:36
@ msg_register_dns
Definition openvpn-msg.h:45
@ msg_del_nrpt_cfg
Definition openvpn-msg.h:39
@ msg_del_route
Definition openvpn-msg.h:35
@ msg_set_mtu
Definition openvpn-msg.h:48
@ msg_flush_neighbors
Definition openvpn-msg.h:42
@ msg_del_dns_cfg
Definition openvpn-msg.h:37
@ ADAPTER_TYPE_DCO
@ ADAPTER_TYPE_TAP
#define NRPT_ADDR_SIZE
#define NRPT_ADDR_NUM
#define M_ERR
Definition error.h:106
#define msg(flags,...)
Definition error.h:152
BOOL ReportStatusToSCMgr(SERVICE_STATUS_HANDLE service, SERVICE_STATUS *status)
Definition service.c:22
#define SERVICE_DEPENDENCIES
Definition service.h:37
#define M_SYSERR
Definition service.h:45
#define MSG_FLAGS_ERROR
Definition service.h:42
@ interactive
Definition service.h:50
static wchar_t * utf8to16(const char *utf8)
Convert a zero terminated UTF-8 string to UTF-16.
Definition service.h:122
static int pos(char c)
Definition base64.c:104
LPVOID data
Definition interactive.c:78
struct _list_item * next
Definition interactive.c:77
WCHAR * directory
Definition interactive.c:68
WCHAR * options
Definition interactive.c:69
WCHAR * std_input
Definition interactive.c:70
message_header_t header
Definition argv.h:35
Wrapper structure for dynamically allocated memory.
Definition buffer.h:71
Definition dhcp.h:62
interface_t iface
char name[256]
Definition openvpn-msg.h:71
Container for unidirectional cipher and HMAC key material.
Definition crypto.h:145
message_type_t type
Definition openvpn-msg.h:56
nrpt_address_t addresses[NRPT_ADDR_NUM]
CHAR addresses[NRPT_ADDR_NUM *NRPT_ADDR_SIZE]
interface_t iface
WCHAR ovpn_admin_group[MAX_NAME]
Definition service.h:71
WCHAR bin_dir[MAX_PATH]
Definition service.h:68
WCHAR ovpn_service_user[MAX_NAME]
Definition service.h:72
DWORD priority
Definition service.h:73
WCHAR exe_path[MAX_PATH]
Definition service.h:66
#define _L(q)
Definition basic.h:38
static int cleanup(void **state)
const char * msg2
const char * msg1
struct in6_addr ipv6
Definition openvpn-msg.h:64
struct in_addr ipv4
Definition openvpn-msg.h:63
dns_cfg_message_t dns
address_message_t address
flush_neighbors_message_t flush_neighbors
wfp_block_message_t wfp_block
message_header_t header
wins_cfg_message_t wins
enable_dhcp_message_t dhcp
route_message_t route
nrpt_dns_cfg_message_t nrpt_dns
set_mtu_message_t mtu
create_adapter_message_t create_adapter
BOOL IsAuthorizedUser(PSID sid, const HANDLE token, const WCHAR *ovpn_admin_group, const WCHAR *ovpn_service_user)
Definition validate.c:149
BOOL CheckOption(const WCHAR *workdir, int argc, WCHAR *argv[], const settings_t *s)
Definition validate.c:329
static BOOL IsOption(const WCHAR *o)
Definition validate.h:46
int get_interface_metric(const NET_IFINDEX index, const ADDRESS_FAMILY family, int *is_auto)
Return interface metric value for the specified interface index.
Definition wfp_block.c:378
DWORD set_interface_metric(const NET_IFINDEX index, const ADDRESS_FAMILY family, const ULONG metric)
Sets interface metric value for specified interface index.
Definition wfp_block.c:417
DWORD delete_wfp_block_filters(HANDLE engine_handle)
Definition wfp_block.c:353
DWORD add_wfp_block_filters(HANDLE *engine_handle, int index, const WCHAR *exe_path, wfp_block_msg_handler_t msg_handler, BOOL dns_only)
Definition wfp_block.c:158
#define WFP_BLOCK_IFACE_METRIC
Definition wfp_block.h:33
char * get_win_sys_path(void)
Definition win32.c:1162