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