OpenVPN
dco_win.c
Go to the documentation of this file.
1/*
2 * Interface to ovpn-win-dco networking code
3 *
4 * Copyright (C) 2020-2026 Arne Schwabe <arne@rfc2549.org>
5 * Copyright (C) 2020-2026 OpenVPN Inc <sales@openvpn.net>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2
9 * as published by the Free Software Foundation.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program (see the file COPYING included with this
18 * distribution); if not, see <https://www.gnu.org/licenses/>.
19 */
20
21#ifdef HAVE_CONFIG_H
22#include "config.h"
23#endif
24
25#if defined(_WIN32)
26
27#include "syshead.h"
28
29#include "dco.h"
30#include "dco_win.h"
31#include "forward.h"
32#include "tun.h"
33#include "crypto.h"
34#include "multi.h"
35#include "ssl_common.h"
36#include "openvpn.h"
37
38#include <bcrypt.h>
39#include <ioapiset.h>
40#include <winsock2.h>
41#include <ws2tcpip.h>
42
43#if defined(__MINGW32__)
44const IN_ADDR in4addr_any = { 0 };
45#endif
46
47/* Sometimes IP Helper API, which we use for setting IP address etc,
48 * complains that interface is not found. Give it some time to settle
49 */
50static void
52{
53 for (int i = 0; i < 20; ++i)
54 {
55 MIB_IPINTERFACE_ROW row = { .InterfaceIndex = idx, .Family = AF_INET };
56 if (GetIpInterfaceEntry(&row) != ERROR_NOT_FOUND)
57 {
58 break;
59 }
60 msg(D_DCO_DEBUG, "interface %lu not yet ready, retrying", idx);
61 Sleep(50);
62 }
63}
64
74static bool
76{
77 CLEAR(*version);
78
79 bool res = false;
80
81 HANDLE h = CreateFile("\\\\.\\ovpn-dco-ver", GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
82
83 if (h == INVALID_HANDLE_VALUE)
84 {
85 /* fallback to a "normal" device, this will fail if device is already in use */
86 h = CreateFile("\\\\.\\ovpn-dco", GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
87 }
88
89 if (h == INVALID_HANDLE_VALUE)
90 {
91 goto done;
92 }
93
94 DWORD bytes_returned = 0;
95 if (!DeviceIoControl(h, OVPN_IOCTL_GET_VERSION, NULL, 0, version, sizeof(*version),
96 &bytes_returned, NULL))
97 {
98 goto done;
99 }
100
101 res = true;
102
103done:
104 if (h != INVALID_HANDLE_VALUE)
105 {
106 CloseHandle(h);
107 }
108
109 msg(D_DCO_DEBUG, "dco version: %ld.%ld.%ld", version->Major, version->Minor, version->Patch);
110
111 return res;
112}
113
123void
124ovpn_dco_init_mp(dco_context_t *dco, const char *dev_node)
125{
126 ASSERT(dco->ifmode == DCO_MODE_UNINIT);
127 dco->ifmode = DCO_MODE_MP;
128
129 /* Use manual reset event so it remains signalled until
130 * explicitly reset. This way we won't lose notifications
131 */
132 dco->ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
133 if (dco->ov.hEvent == NULL)
134 {
135 msg(M_ERR, "Error: ovpn_dco_init: CreateEvent failed");
136 }
137
138 dco->rwhandle.read = dco->ov.hEvent;
139
140 /* open DCO device */
141 struct gc_arena gc = gc_new();
142 const char *device_guid;
143 tun_open_device(dco->tt, dev_node, &device_guid, &gc);
144 gc_free(&gc);
145
146 /* set mp mode */
148 DWORD bytes_returned = 0;
149 if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_SET_MODE, &m, sizeof(m), NULL, 0,
150 &bytes_returned, NULL))
151 {
152 msg(M_ERR, "DeviceIoControl(OVPN_IOCTL_SET_MODE) failed");
153 }
154
155 dco_wait_ready(dco->tt->adapter_index);
156}
157
166void
168{
169 DWORD bytes_returned = 0;
170 if (!DeviceIoControl(tt->hand, OVPN_IOCTL_START_VPN, NULL, 0, NULL, 0, &bytes_returned, NULL))
171 {
172 msg(M_ERR, "DeviceIoControl(OVPN_IOCTL_START_VPN) failed");
173 }
174
175 /* Sometimes IP Helper API, which we use for setting IP address etc,
176 * complains that interface is not found. Give it some time to settle
177 */
179}
180
181
191bool
193{
194 dco_context_t *dco = &c->c1.tuntap->dco;
195
196 dco->c = c;
197
198 switch (c->mode)
199 {
201 dco->ifmode = DCO_MODE_P2P;
202 dco_p2p_start_vpn(dco->tt);
203 break;
204
205 case MODE_SERVER:
207 break;
208
209 default:
210 ASSERT(false);
211 }
212
213 return true;
214}
215
216int
217open_tun_dco(struct tuntap *tt, openvpn_net_ctx_t *ctx, const char *dev)
218{
219 ASSERT(0);
220 return 0;
221}
222
223#if defined(__GNUC__) || defined(__clang__)
224#pragma GCC diagnostic push
225#pragma GCC diagnostic ignored "-Wsign-conversion"
226#endif
227
228static void
229dco_connect_wait(HANDLE handle, OVERLAPPED *ov, int timeout, struct signal_info *sig_info)
230{
231 volatile int *signal_received = &sig_info->signal_received;
232 DWORD timeout_msec = timeout * 1000;
233 const int poll_interval_ms = 50;
234
235 while (timeout_msec > 0)
236 {
237 timeout_msec -= poll_interval_ms;
238
239 DWORD transferred;
240 if (GetOverlappedResultEx(handle, ov, &transferred, poll_interval_ms, FALSE) != 0)
241 {
242 /* TCP connection established by dco */
243 return;
244 }
245
246 DWORD err = GetLastError();
247 if ((err != WAIT_TIMEOUT) && (err != ERROR_IO_INCOMPLETE))
248 {
249 /* dco reported connection error */
250 msg(M_NONFATAL | M_ERRNO, "dco connect error");
251 register_signal(sig_info, SIGUSR1, "dco-connect-error");
252 return;
253 }
254
255 get_signal(signal_received);
256 if (*signal_received)
257 {
258 return;
259 }
260
262 }
263
264 /* we end up here when timeout occurs in userspace */
265 msg(M_NONFATAL, "dco connect timeout");
266 register_signal(sig_info, SIGUSR1, "dco-connect-timeout");
267}
268
278void
279dco_mp_start_vpn(HANDLE handle, struct link_socket *sock)
280{
281 msg(D_DCO_DEBUG, "%s", __func__);
282
283 int ai_family = sock->info.lsa->bind_local->ai_family;
284 const struct addrinfo *local = sock->info.lsa->bind_local;
285 const struct addrinfo *cur = NULL;
286
287 for (cur = local; cur; cur = cur->ai_next)
288 {
289 if (cur->ai_family == ai_family)
290 {
291 break;
292 }
293 }
294 if (!cur)
295 {
296 msg(M_FATAL, "%s: Socket bind failed: Addr to bind has no %s record", __func__,
297 addr_family_name(ai_family));
298 }
299
300 OVPN_MP_START_VPN in, out;
301 in.IPv6Only = sock->info.bind_ipv6_only ? 1 : 0;
302 if (ai_family == AF_INET)
303 {
304 memcpy(&in.ListenAddress.Addr4, cur->ai_addr, sizeof(struct sockaddr_in));
305 }
306 else
307 {
308 memcpy(&in.ListenAddress.Addr6, cur->ai_addr, sizeof(struct sockaddr_in6));
309 }
310
311 /* in multipeer mode control channel packets are prepended with remote peer's sockaddr */
312 sock->sockflags |= SF_PREPEND_SA;
313
314 DWORD bytes_returned = 0;
315 if (!DeviceIoControl(handle, OVPN_IOCTL_MP_START_VPN, &in, sizeof(in), &out, sizeof(out),
316 &bytes_returned, NULL))
317 {
318 msg(M_ERR, "DeviceIoControl(OVPN_IOCTL_MP_START_VPN) failed");
319 }
320}
321
322void
323dco_p2p_new_peer(HANDLE handle, OVERLAPPED *ov, struct link_socket *sock,
324 struct signal_info *sig_info)
325{
326 msg(D_DCO_DEBUG, "%s", __func__);
327
328 OVPN_NEW_PEER peer = { 0 };
329
330 struct addrinfo *remoteaddr = sock->info.lsa->current_remote;
331
332 struct sockaddr *local = NULL;
333 const struct sockaddr *remote = remoteaddr->ai_addr;
334
335 if (remoteaddr->ai_protocol == IPPROTO_TCP || remoteaddr->ai_socktype == SOCK_STREAM)
336 {
337 peer.Proto = OVPN_PROTO_TCP;
338 }
339 else
340 {
341 peer.Proto = OVPN_PROTO_UDP;
342 }
343
344 if (sock->bind_local)
345 {
346 /* Use first local address with correct address family */
347 const struct addrinfo *bind = sock->info.lsa->bind_local;
348 while (bind && !local)
349 {
350 if (bind->ai_family == remote->sa_family)
351 {
352 local = bind->ai_addr;
353 }
354 bind = bind->ai_next;
355 }
356 }
357
358 if (sock->bind_local && !local)
359 {
360 msg(M_FATAL, "DCO: Socket bind failed: Address to bind lacks %s record",
361 addr_family_name(remote->sa_family));
362 }
363
364 if (remote->sa_family == AF_INET6)
365 {
366 peer.Remote.Addr6 = *((SOCKADDR_IN6 *)(remoteaddr->ai_addr));
367 if (local)
368 {
369 peer.Local.Addr6 = *((SOCKADDR_IN6 *)local);
370 }
371 else
372 {
373 peer.Local.Addr6.sin6_addr = in6addr_any;
374 peer.Local.Addr6.sin6_port = 0;
375 peer.Local.Addr6.sin6_family = AF_INET6;
376 }
377 }
378 else if (remote->sa_family == AF_INET)
379 {
380 peer.Remote.Addr4 = *((SOCKADDR_IN *)(remoteaddr->ai_addr));
381 if (local)
382 {
383 peer.Local.Addr4 = *((SOCKADDR_IN *)local);
384 }
385 else
386 {
387 peer.Local.Addr4.sin_addr = in4addr_any;
388 peer.Local.Addr4.sin_port = 0;
389 peer.Local.Addr4.sin_family = AF_INET;
390 }
391 }
392 else
393 {
394 ASSERT(0);
395 }
396
397 CLEAR(*ov);
398 if (!DeviceIoControl(handle, OVPN_IOCTL_NEW_PEER, &peer, sizeof(peer), NULL, 0, NULL, ov))
399 {
400 DWORD err = GetLastError();
401 if (err != ERROR_IO_PENDING)
402 {
403 msg(M_ERR, "DeviceIoControl(OVPN_IOCTL_NEW_PEER) failed");
404 }
405 else
406 {
408 sig_info);
409 }
410 }
411}
412
413int
414dco_new_peer(dco_context_t *dco, unsigned int peerid, socket_descriptor_t sd,
415 struct sockaddr *localaddr, struct sockaddr *remoteaddr,
416 const struct in_addr *vpn_ipv4, const struct in6_addr *vpn_ipv6)
417{
418 msg(D_DCO_DEBUG, "%s: peer-id %u, fd " SOCKET_PRINTF, __func__, peerid, sd);
419
420 if (dco->ifmode == DCO_MODE_P2P)
421 {
422 /* no-op for p2p */
423 return 0;
424 }
425
426 OVPN_MP_NEW_PEER newPeer = { 0 };
427
428 if (remoteaddr)
429 {
430 /* while the driver doesn't use the local address yet it requires its AF to be valid */
431 newPeer.Local.Addr4.sin_family = remoteaddr->sa_family;
432
433 if (remoteaddr->sa_family == AF_INET)
434 {
435 memcpy(&newPeer.Remote.Addr4, remoteaddr, sizeof(struct sockaddr_in));
436 }
437 else
438 {
439 memcpy(&newPeer.Remote.Addr6, remoteaddr, sizeof(struct sockaddr_in6));
440 }
441 }
442
443 if (vpn_ipv4)
444 {
445 newPeer.VpnAddr4 = *vpn_ipv4;
446 }
447
448 if (vpn_ipv6)
449 {
450 newPeer.VpnAddr6 = *vpn_ipv6;
451 }
452
453 newPeer.PeerId = peerid;
454
455 DWORD bytesReturned;
456 if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_MP_NEW_PEER, &newPeer, sizeof(newPeer), NULL, 0,
457 &bytesReturned, NULL))
458 {
459 msg(M_WARN | M_ERRNO, "DeviceIoControl(OVPN_IOCTL_MP_NEW_PEER) failed");
460 return -1;
461 }
462
463 return 0;
464}
465
466int
467dco_del_peer(dco_context_t *dco, unsigned int peerid)
468{
469 msg(D_DCO_DEBUG, "%s: peer-id %u", __func__, peerid);
470
471 OVPN_MP_DEL_PEER del_peer = { peerid };
472 VOID *buf = NULL;
473 DWORD len = 0;
474 DWORD ioctl = OVPN_IOCTL_DEL_PEER;
475
476 if (dco->ifmode == DCO_MODE_MP)
477 {
479 buf = &del_peer;
480 len = sizeof(del_peer);
481 }
482
483 DWORD bytes_returned = 0;
484 if (!DeviceIoControl(dco->tt->hand, ioctl, buf, len, NULL, 0, &bytes_returned, NULL))
485 {
486 msg(M_WARN | M_ERRNO, "DeviceIoControl(OVPN_IOCTL_DEL_PEER) failed");
487 return -1;
488 }
489 return 0;
490}
491
492int
493dco_set_peer(dco_context_t *dco, unsigned int peerid, int keepalive_interval, int keepalive_timeout,
494 int mss)
495{
496 msg(D_DCO_DEBUG, "%s: peer-id %u, keepalive %d/%d, mss %d", __func__, peerid,
497 keepalive_interval, keepalive_timeout, mss);
498
499 OVPN_MP_SET_PEER mp_peer = { peerid, keepalive_interval, keepalive_timeout, mss };
500 OVPN_SET_PEER peer = { keepalive_interval, keepalive_timeout, mss };
501 VOID *buf = NULL;
502 DWORD len = 0;
503 DWORD ioctl = (dco->ifmode == DCO_MODE_MP) ? OVPN_IOCTL_MP_SET_PEER : OVPN_IOCTL_SET_PEER;
504
505 if (dco->ifmode == DCO_MODE_MP)
506 {
507 buf = &mp_peer;
508 len = sizeof(OVPN_MP_SET_PEER);
509 }
510 else
511 {
512 buf = &peer;
513 len = sizeof(OVPN_SET_PEER);
514 }
515
516 DWORD bytes_returned = 0;
517 if (!DeviceIoControl(dco->tt->hand, ioctl, buf, len, NULL, 0, &bytes_returned, NULL))
518 {
519 msg(M_WARN | M_ERRNO, "DeviceIoControl(OVPN_IOCTL_MP_SET_PEER) failed");
520 return -1;
521 }
522
523 return 0;
524}
525
526int
527dco_new_key(dco_context_t *dco, unsigned int peerid, int keyid, dco_key_slot_t slot,
528 const uint8_t *encrypt_key, const uint8_t *encrypt_iv, const uint8_t *decrypt_key,
529 const uint8_t *decrypt_iv, const char *ciphername, bool epoch)
530{
531 msg(D_DCO_DEBUG, "%s: slot %d, key-id %d, peer-id %u, cipher %s", __func__, slot, keyid, peerid,
532 ciphername);
533
534 const int nonce_len = 8;
535 size_t key_len = cipher_kt_key_size(ciphername);
536 ASSERT(key_len <= 32);
537
538 OVPN_CRYPTO_DATA_V2 crypto_data;
539 ZeroMemory(&crypto_data, sizeof(crypto_data));
540
541 OVPN_CRYPTO_DATA *v1 = &crypto_data.V1;
542
543 v1->CipherAlg = dco_get_cipher(ciphername);
544 ASSERT(keyid >= 0 && keyid <= UCHAR_MAX);
545 v1->KeyId = (unsigned char)keyid;
546 v1->PeerId = peerid;
547 v1->KeySlot = slot;
548
549 /* for epoch we use key material as a seed, no as actual key */
550 CopyMemory(v1->Encrypt.Key, encrypt_key, epoch ? 32 : key_len);
551 v1->Encrypt.KeyLen = (unsigned char)key_len;
552 CopyMemory(v1->Encrypt.NonceTail, encrypt_iv, nonce_len);
553
554 CopyMemory(v1->Decrypt.Key, decrypt_key, epoch ? 32 : key_len);
555 v1->Decrypt.KeyLen = (unsigned char)key_len;
556 CopyMemory(v1->Decrypt.NonceTail, decrypt_iv, nonce_len);
557
558 ASSERT(v1->CipherAlg > 0);
559
560 DWORD ioctl = OVPN_IOCTL_NEW_KEY;
561 VOID *buf = &crypto_data.V1;
562 DWORD bufSize = sizeof(crypto_data.V1);
563 if (epoch)
564 {
565 ioctl = OVPN_IOCTL_NEW_KEY_V2;
566 crypto_data.CryptoOptions |= CRYPTO_OPTIONS_EPOCH;
567 buf = &crypto_data;
568 bufSize = sizeof(crypto_data);
569 }
570
571 DWORD bytes_returned = 0;
572
573 if (!DeviceIoControl(dco->tt->hand, ioctl, buf, bufSize, NULL, 0, &bytes_returned, NULL))
574 {
575 msg(M_WARN | M_ERRNO, "DeviceIoControl(OVPN_IOCTL_NEW_KEY) failed");
576 return -1;
577 }
578 return 0;
579}
580
581int
582dco_del_key(dco_context_t *dco, unsigned int peerid, dco_key_slot_t slot)
583{
584 msg(D_DCO, "%s: peer-id %u, slot %d called but ignored", __func__, peerid, slot);
585 /* FIXME: Implement in driver first */
586 return 0;
587}
588
589int
590dco_swap_keys(dco_context_t *dco, unsigned int peer_id)
591{
592 msg(D_DCO_DEBUG, "%s: peer-id %u", __func__, peer_id);
593
594 OVPN_MP_SWAP_KEYS swap = { peer_id };
595 DWORD ioctl = OVPN_IOCTL_SWAP_KEYS;
596 VOID *buf = NULL;
597 DWORD len = 0;
598
599 if (dco->ifmode == DCO_MODE_MP)
600 {
602 buf = &swap;
603 len = sizeof(swap);
604 }
605
606 DWORD bytes_returned = 0;
607 if (!DeviceIoControl(dco->tt->hand, ioctl, buf, len, NULL, 0, &bytes_returned, NULL))
608 {
609 msg(M_WARN | M_ERRNO, "DeviceIoControl(OVPN_IOCTL_SWAP_KEYS) failed");
610 return -1;
611 }
612 return 0;
613}
614
615bool
617{
618 /* try to open device by symbolic name */
619 HANDLE h = CreateFile("\\\\.\\ovpn-dco", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
620 FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, NULL);
621
622 if (h != INVALID_HANDLE_VALUE)
623 {
624 CloseHandle(h);
625 return true;
626 }
627
628 DWORD err = GetLastError();
629 if (err == ERROR_ACCESS_DENIED)
630 {
631 /* this likely means that device exists but is already in use,
632 * don't bail out since later we try to open all existing dco
633 * devices and then bail out if all devices are in use
634 */
635 return true;
636 }
637
638 msg(msglevel, "Note: ovpn-dco-win driver is missing, disabling data channel offload.");
639 return false;
640}
641
642const char *
644{
645 OVPN_VERSION version = { 0 };
646 if (dco_get_version(&version))
647 {
648 struct buffer out = alloc_buf_gc(256, gc);
649 buf_printf(&out, "%ld.%ld.%ld", version.Major, version.Minor, version.Patch);
650 return BSTR(&out);
651 }
652 else
653 {
654 return "N/A";
655 }
656}
657
669static void
671{
672 DWORD bytes_read = 0;
673 BOOL res = GetOverlappedResult(dco->tt->hand, &dco->ov, &bytes_read, FALSE);
674 if (res)
675 {
676 msg(D_DCO_DEBUG, "%s: completion%s success [%lu]", __func__, queued ? "" : " non-queued",
677 bytes_read);
678
679 dco->dco_message_peer_id = dco->notif_buf.PeerId;
680 dco->dco_message_type = dco->notif_buf.Cmd;
681 dco->dco_del_peer_reason = dco->notif_buf.DelPeerReason;
682 dco->dco_float_peer_ss = dco->notif_buf.FloatAddress;
683 }
684 else
685 {
686 msg(D_DCO_DEBUG | M_ERRNO, "%s: completion%s error", __func__, queued ? "" : " non-queued");
687 }
688}
689
690int
692{
693 if (dco->ifmode != DCO_MODE_MP)
694 {
695 ASSERT(false);
696 }
697
698 dco->dco_message_peer_id = -1;
699 dco->dco_message_type = 0;
700
701 switch (dco->iostate)
702 {
703 case IOSTATE_QUEUED:
705
706 ASSERT(ResetEvent(dco->ov.hEvent));
707 dco->iostate = IOSTATE_INITIAL;
708
709 break;
710
712 dco->iostate = IOSTATE_INITIAL;
713 ASSERT(ResetEvent(dco->ov.hEvent));
714
715 if (dco->ov_ret == ERROR_SUCCESS)
716 {
718 }
719 else
720 {
721 SetLastError(dco->ov_ret);
722 msg(D_DCO_DEBUG | M_ERRNO, "%s: completion non-queued error", __func__);
723 }
724
725 break;
726 }
727
728 if (dco->c->mode == CM_TOP)
729 {
731 }
732 else
733 {
735 }
736
737 return 0;
738}
739
740int
742{
743 struct gc_arena gc = gc_new();
744
745 int ret = 0;
746 const struct tuntap *tt = dco->tt;
747
748 if (!tuntap_defined(tt))
749 {
750 ret = -1;
751 goto done;
752 }
753
755 .PeerId = -1
756 };
757
758 DWORD required_size = 0, bytes_returned = 0;
759 /* first, figure out buffer size */
760 if (!DeviceIoControl(tt->hand, OVPN_IOCTL_GET_PEER_STATS, &ps, sizeof(ps), &required_size, sizeof(DWORD), &bytes_returned, NULL))
761 {
762 if (GetLastError() == ERROR_MORE_DATA)
763 {
764 if (bytes_returned != sizeof(DWORD))
765 {
766 msg(M_WARN, "%s: invalid bytes returned for size query (%lu, expected %zu)", __func__, bytes_returned, sizeof(DWORD));
767 ret = -1;
768 goto done;
769 }
770 /* required_size now contains the size written by the driver */
771 if (required_size == 0)
772 {
773 ret = 0; /* no peers to process */
774 goto done;
775 }
776 if (required_size < sizeof(OVPN_PEER_STATS))
777 {
778 msg(M_WARN, "%s: invalid required size %lu (minimum %zu)", __func__, required_size, sizeof(OVPN_PEER_STATS));
779 ret = -1;
780 goto done;
781 }
782 }
783 else
784 {
785 msg(M_WARN | M_ERRNO, "%s: failed to fetch required buffer size", __func__);
786 ret = -1;
787 goto done;
788 }
789 }
790 else
791 {
792 /* unexpected success? */
793 if (bytes_returned == 0)
794 {
795 ret = 0; /* no peers to process */
796 goto done;
797 }
798
799 msg(M_WARN, "%s: first DeviceIoControl call succeeded unexpectedly (%lu bytes returned)", __func__, bytes_returned);
800 ret = -1;
801 goto done;
802 }
803
804
805 /* allocate the buffer and fetch stats */
806 OVPN_PEER_STATS *peer_stats = gc_malloc(required_size, true, &gc);
807 if (!peer_stats)
808 {
809 msg(M_WARN, "%s: failed to allocate buffer of size %lu", __func__, required_size);
810 ret = -1;
811 goto done;
812 }
813
814 if (!DeviceIoControl(tt->hand, OVPN_IOCTL_GET_PEER_STATS, &ps, sizeof(ps), peer_stats, required_size, &bytes_returned, NULL))
815 {
816 /* unlikely case when a peer has been added since fetching buffer size, not an error! */
817 if (GetLastError() == ERROR_MORE_DATA)
818 {
819 msg(M_WARN, "%s: peer has been added, skip fetching stats", __func__);
820 ret = 0;
821 goto done;
822 }
823
824 msg(M_WARN | M_ERRNO, "%s: failed to fetch multipeer stats", __func__);
825 ret = -1;
826 goto done;
827 }
828
829 /* iterate over stats and update peers */
830 for (size_t i = 0; i < bytes_returned / sizeof(OVPN_PEER_STATS); ++i)
831 {
832 OVPN_PEER_STATS *stat = &peer_stats[i];
833
834 if (stat->PeerId >= (int)dco->c->multi->max_clients)
835 {
836 msg(M_WARN, "%s: received out of bound peer_id %d (max=%u)", __func__, stat->PeerId,
837 dco->c->multi->max_clients);
838 continue;
839 }
840
841 struct multi_instance *mi = dco->c->multi->instances[stat->PeerId];
842 if (!mi)
843 {
844 msg(M_WARN, "%s: received data for a non-existing peer %d", __func__, stat->PeerId);
845 continue;
846 }
847
848 /* update peer stats */
849 struct context_2 *c2 = &mi->context.c2;
850 c2->dco_read_bytes = stat->LinkRxBytes;
851 c2->dco_write_bytes = stat->LinkTxBytes;
852 c2->tun_read_bytes = stat->VpnRxBytes;
853 c2->tun_write_bytes = stat->VpnTxBytes;
854 }
855
856done:
857 gc_free(&gc);
858
859 if (raise_sigusr1_on_err && ret < 0)
860 {
861 register_signal(dco->c->sig, SIGUSR1, "dco peer stats error");
862 }
863
864 return ret;
865}
866
867int
868dco_get_peer_stats_fallback(struct context *c, const bool raise_sigusr1_on_err)
869{
870 const struct tuntap *tt = c->c1.tuntap;
871
872 if (!tuntap_defined(tt))
873 {
874 return -1;
875 }
876
877 OVPN_STATS stats;
878 ZeroMemory(&stats, sizeof(OVPN_STATS));
879
880 DWORD bytes_returned = 0;
881 if (!DeviceIoControl(tt->hand, OVPN_IOCTL_GET_STATS, NULL, 0, &stats, sizeof(stats),
882 &bytes_returned, NULL))
883 {
884 msg(M_WARN | M_ERRNO, "DeviceIoControl(OVPN_IOCTL_GET_STATS) failed");
885 return -1;
886 }
887
892
893 return 0;
894}
895
896int
897dco_get_peer_stats(struct context *c, const bool raise_sigusr1_on_err)
898{
899 const struct tuntap *tt = c->c1.tuntap;
900
901 if (!tuntap_defined(tt))
902 {
903 return -1;
904 }
905
906 /* first, try a new ioctl */
908
909 OVPN_PEER_STATS peer_stats = { 0 };
910 DWORD bytes_returned = 0;
911 if (!DeviceIoControl(tt->hand, OVPN_IOCTL_GET_PEER_STATS, &ps, sizeof(ps), &peer_stats, sizeof(peer_stats),
912 &bytes_returned, NULL))
913 {
914 if (GetLastError() == ERROR_INVALID_FUNCTION)
915 {
916 /* are we using the old driver? */
917 return dco_get_peer_stats_fallback(c, raise_sigusr1_on_err);
918 }
919
920 msg(M_WARN | M_ERRNO, "%s: DeviceIoControl(OVPN_IOCTL_GET_PEER_STATS) failed", __func__);
921 return -1;
922 }
923
924 if (bytes_returned != sizeof(OVPN_PEER_STATS))
925 {
926 msg(M_WARN | M_ERRNO, "%s: DeviceIoControl(OVPN_IOCTL_GET_PEER_STATS) returned invalid size", __func__);
927 return -1;
928 }
929
930 c->c2.dco_read_bytes = peer_stats.LinkRxBytes;
931 c->c2.dco_write_bytes = peer_stats.LinkTxBytes;
932 c->c2.tun_read_bytes = peer_stats.VpnRxBytes;
933 c->c2.tun_write_bytes = peer_stats.VpnTxBytes;
934
935 return 0;
936}
937
938void
939dco_event_set(dco_context_t *dco, struct event_set *es, void *arg)
940{
941 if (dco->ifmode != DCO_MODE_MP)
942 {
943 /* mp only */
944 return;
945 }
946
947 event_ctl(es, &dco->rwhandle, EVENT_READ, arg);
948
949 if (dco->iostate == IOSTATE_INITIAL)
950 {
951 /* the overlapped IOCTL will signal this event on I/O completion */
952 ASSERT(ResetEvent(dco->ov.hEvent));
953
954 if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_NOTIFY_EVENT, NULL, 0, &dco->notif_buf,
955 sizeof(dco->notif_buf), NULL, &dco->ov))
956 {
957 DWORD err = GetLastError();
958 if (err == ERROR_IO_PENDING) /* operation queued? */
959 {
960 dco->iostate = IOSTATE_QUEUED;
961 dco->ov_ret = ERROR_SUCCESS;
962
963 msg(D_DCO_DEBUG, "%s: notify ioctl queued", __func__);
964 }
965 else
966 {
967 /* error occured */
968 ASSERT(SetEvent(dco->ov.hEvent));
969 dco->iostate = IOSTATE_IMMEDIATE_RETURN;
970 dco->ov_ret = err;
971
972 msg(D_DCO_DEBUG | M_ERRNO, "%s: notify ioctl error", __func__);
973 }
974 }
975 else
976 {
977 ASSERT(SetEvent(dco->ov.hEvent));
978 dco->iostate = IOSTATE_IMMEDIATE_RETURN;
979 dco->ov_ret = ERROR_SUCCESS;
980
981 msg(D_DCO_DEBUG, "%s: notify ioctl immediate return", __func__);
982 }
983 }
984}
985
986const char *
988{
989 /*
990 * this API can be called either from user mode or kernel mode,
991 * which enables us to probe driver's chachapoly support
992 * (available starting from Windows 11)
993 */
994
995 BCRYPT_ALG_HANDLE h;
996 NTSTATUS status = BCryptOpenAlgorithmProvider(&h, L"CHACHA20_POLY1305", NULL, 0);
997 if (BCRYPT_SUCCESS(status))
998 {
999 BCryptCloseAlgorithmProvider(h, 0);
1000 return "AES-128-GCM:AES-256-GCM:AES-192-GCM:CHACHA20-POLY1305";
1001 }
1002 else
1003 {
1004 return "AES-128-GCM:AES-256-GCM:AES-192-GCM";
1005 }
1006}
1007
1008bool
1010{
1011 OVPN_VERSION ver = { 0 };
1012 return dco_get_version(&ver) && ver.Major >= 2;
1013}
1014
1015void
1017 unsigned int peer_id)
1018{
1019 struct gc_arena gc = gc_new();
1020
1022 .Addr.Addr4.S_un.S_addr = dst, .Netbits = netbits, .PeerId = peer_id, .IPv6 = 0
1023 };
1024
1025 msg(D_DCO_DEBUG, "%s: %s/%u -> peer %u", __func__, print_in_addr_t(dst, IA_NET_ORDER, &gc),
1026 netbits, peer_id);
1027
1028 DWORD bytes_returned = 0;
1029 if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_MP_ADD_IROUTE, &route, sizeof(route), NULL, 0,
1030 &bytes_returned, NULL))
1031 {
1032 msg(M_WARN | M_ERRNO, "DeviceIoControl(OVPN_IOCTL_MP_ADD_IROUTE) failed");
1033 }
1034
1035 gc_free(&gc);
1036}
1037
1038void
1039dco_win_add_iroute_ipv6(dco_context_t *dco, struct in6_addr dst, unsigned int netbits,
1040 unsigned int peer_id)
1041{
1042 struct gc_arena gc = gc_new();
1043
1044 OVPN_MP_IROUTE route = { .Addr.Addr6 = dst, .Netbits = netbits, .PeerId = peer_id, .IPv6 = 1 };
1045
1046 msg(D_DCO_DEBUG, "%s: %s/%u -> peer %u", __func__, print_in6_addr(dst, IA_NET_ORDER, &gc),
1047 netbits, peer_id);
1048
1049 DWORD bytes_returned = 0;
1050 if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_MP_ADD_IROUTE, &route, sizeof(route), NULL, 0,
1051 &bytes_returned, NULL))
1052 {
1053 msg(M_WARN | M_ERRNO, "DeviceIoControl(OVPN_IOCTL_MP_ADD_IROUTE) failed");
1054 }
1055
1056 gc_free(&gc);
1057}
1058
1059void
1060dco_win_del_iroute_ipv4(dco_context_t *dco, in_addr_t dst, unsigned int netbits)
1061{
1062 struct gc_arena gc = gc_new();
1063
1065 .Addr.Addr4.S_un.S_addr = dst, .Netbits = netbits, .PeerId = -1, .IPv6 = 0
1066 };
1067
1068 msg(D_DCO_DEBUG, "%s: %s/%u", __func__, print_in_addr_t(dst, IA_NET_ORDER, &gc), netbits);
1069
1070 DWORD bytes_returned = 0;
1071 if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_MP_DEL_IROUTE, &route, sizeof(route), NULL, 0,
1072 &bytes_returned, NULL))
1073 {
1074 msg(M_WARN | M_ERRNO, "DeviceIoControl(OVPN_IOCTL_MP_DEL_IROUTE) failed");
1075 }
1076
1077 gc_free(&gc);
1078}
1079
1080void
1081dco_win_del_iroute_ipv6(dco_context_t *dco, struct in6_addr dst, unsigned int netbits)
1082{
1083 struct gc_arena gc = gc_new();
1084
1085 OVPN_MP_IROUTE route = { .Addr.Addr6 = dst, .Netbits = netbits, .PeerId = -1, .IPv6 = 1 };
1086
1087 msg(D_DCO_DEBUG, "%s: %s/%u", __func__, print_in6_addr(dst, IA_NET_ORDER, &gc), netbits);
1088
1089 DWORD bytes_returned = 0;
1090 if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_MP_DEL_IROUTE, &route, sizeof(route), NULL, 0,
1091 &bytes_returned, NULL))
1092 {
1093 msg(M_WARN | M_ERRNO, "DeviceIoControl(OVPN_IOCTL_MP_DEL_IROUTE) failed");
1094 }
1095
1096 gc_free(&gc);
1097}
1098
1099#if defined(__GNUC__) || defined(__clang__)
1100#pragma GCC diagnostic pop
1101#endif
1102
1103bool
1105{
1106 OVPN_VERSION ver = { 0 };
1107 return dco_get_version(&ver) && ((ver.Major == 2 && ver.Minor >= 8) || (ver.Major > 2));
1108}
1109
1110#endif /* defined(_WIN32) */
bool buf_printf(struct buffer *buf, const char *format,...)
printf-style append to a buffer with overflow check.
Definition buffer.c:231
void * gc_malloc(size_t size, bool clear, struct gc_arena *a)
Allocate memory and, optionally, zero it.
Definition buffer.c:321
struct buffer alloc_buf_gc(size_t size, struct gc_arena *gc)
Allocate a buffer of the given size under garbage collection.
Definition buffer.c:77
#define BSTR(buf)
Return the buffer content pointer cast to char *.
Definition buffer.h:157
static void gc_free(struct gc_arena *a)
Free all allocations in a garbage collection arena.
Definition buffer.h:1974
static struct gc_arena gc_new(void)
Allocate and return a new, empty garbage collection arena.
Definition buffer.h:1958
Data Channel Cryptography Module.
unsigned int cipher_kt_key_size(const char *ciphername)
Returns the size of keys used by the cipher, in bytes.
void * dco_context_t
Definition dco.h:259
int open_tun_dco(struct tuntap *tt, openvpn_net_ctx_t *ctx, const char *dev)
Definition dco_win.c:217
int dco_del_key(dco_context_t *dco, unsigned int peerid, dco_key_slot_t slot)
Definition dco_win.c:582
bool dco_available(msglvl_t msglevel)
Definition dco_win.c:616
void dco_mp_start_vpn(HANDLE handle, struct link_socket *sock)
Initializes and binds the kernel UDP transport socket for multipeer mode.
Definition dco_win.c:279
int dco_del_peer(dco_context_t *dco, unsigned int peerid)
Definition dco_win.c:467
void dco_win_add_iroute_ipv6(dco_context_t *dco, struct in6_addr dst, unsigned int netbits, unsigned int peer_id)
Definition dco_win.c:1039
const char * dco_version_string(struct gc_arena *gc)
Definition dco_win.c:643
void dco_p2p_start_vpn(struct tuntap *tt)
Transitions the DCO adapter to the connected state in P2P mode.
Definition dco_win.c:167
bool dco_supports_epoch_data(const struct context *c)
Definition dco_win.c:1104
int dco_read_and_process(dco_context_t *dco)
Definition dco_win.c:691
const char * dco_get_supported_ciphers(void)
Definition dco_win.c:987
bool ovpn_dco_init(struct context *c)
Initializes DCO depends on mode
Definition dco_win.c:192
static void dco_connect_wait(HANDLE handle, OVERLAPPED *ov, int timeout, struct signal_info *sig_info)
Definition dco_win.c:229
void dco_win_del_iroute_ipv4(dco_context_t *dco, in_addr_t dst, unsigned int netbits)
Definition dco_win.c:1060
bool dco_win_supports_multipeer(void)
Definition dco_win.c:1009
int dco_get_peer_stats_multi(dco_context_t *dco, const bool raise_sigusr1_on_err)
Definition dco_win.c:741
void dco_win_del_iroute_ipv6(dco_context_t *dco, struct in6_addr dst, unsigned int netbits)
Definition dco_win.c:1081
int dco_get_peer_stats_fallback(struct context *c, const bool raise_sigusr1_on_err)
Definition dco_win.c:868
static void dco_wait_ready(DWORD idx)
Definition dco_win.c:51
int dco_set_peer(dco_context_t *dco, unsigned int peerid, int keepalive_interval, int keepalive_timeout, int mss)
Definition dco_win.c:493
int dco_swap_keys(dco_context_t *dco, unsigned int peer_id)
Definition dco_win.c:590
void ovpn_dco_init_mp(dco_context_t *dco, const char *dev_node)
Initializes the DCO adapter in multipeer mode and sets it to "connected" state.
Definition dco_win.c:124
int dco_new_peer(dco_context_t *dco, unsigned int peerid, socket_descriptor_t sd, struct sockaddr *localaddr, struct sockaddr *remoteaddr, const struct in_addr *vpn_ipv4, const struct in6_addr *vpn_ipv6)
Definition dco_win.c:414
int dco_get_peer_stats(struct context *c, const bool raise_sigusr1_on_err)
Definition dco_win.c:897
static void dco_handle_overlapped_success(dco_context_t *dco, bool queued)
Handles successful completion of overlapped operation.
Definition dco_win.c:670
static bool dco_get_version(OVPN_VERSION *version)
Gets version of dco-win driver.
Definition dco_win.c:75
void dco_p2p_new_peer(HANDLE handle, OVERLAPPED *ov, struct link_socket *sock, struct signal_info *sig_info)
Definition dco_win.c:323
void dco_win_add_iroute_ipv4(dco_context_t *dco, in_addr_t dst, unsigned int netbits, unsigned int peer_id)
Definition dco_win.c:1016
void dco_event_set(dco_context_t *dco, struct event_set *es, void *arg)
Definition dco_win.c:939
int dco_new_key(dco_context_t *dco, unsigned int peerid, int keyid, dco_key_slot_t slot, const uint8_t *encrypt_key, const uint8_t *encrypt_iv, const uint8_t *decrypt_key, const uint8_t *decrypt_iv, const char *ciphername, bool epoch)
Definition dco_win.c:527
#define D_DCO
Definition errlevel.h:92
#define D_DCO_DEBUG
Definition errlevel.h:115
#define EVENT_READ
Definition event.h:37
static void event_ctl(struct event_set *es, event_t event, unsigned int rwflags, void *arg)
Definition event.h:180
int get_server_poll_remaining_time(const struct event_timeout *server_poll_timeout)
Definition forward.c:520
void process_incoming_dco(dco_context_t *dco)
Process an incoming DCO message (from kernel space).
Definition forward.c:1264
Interface functions to the internal and external multiplexers.
static SERVICE_STATUS status
Definition interactive.c:52
@ route
Definition interactive.c:86
void management_sleep(const int n)
A sleep function that services the management layer for n seconds rather than doing nothing.
Definition manage.c:4335
Header file for server-mode related structures and functions.
void multi_process_incoming_dco(dco_context_t *dco)
Process an incoming DCO message (from kernel space).
void * openvpn_net_ctx_t
Definition networking.h:38
#define CLEAR(x)
Definition basic.h:32
#define M_FATAL
Definition error.h:90
#define M_NONFATAL
Definition error.h:91
#define M_ERR
Definition error.h:106
#define msg(flags,...)
Definition error.h:152
unsigned int msglvl_t
Definition error.h:77
#define ASSERT(x)
Definition error.h:221
#define M_WARN
Definition error.h:92
#define M_ERRNO
Definition error.h:95
#define CM_TOP
Definition openvpn.h:454
#define MODE_POINT_TO_POINT
Definition options.h:264
#define MODE_SERVER
Definition options.h:265
#define OVPN_SET_PEER
#define OVPN_IOCTL_GET_STATS
#define OVPN_IOCTL_NEW_KEY_V2
#define OVPN_IOCTL_GET_VERSION
@ OVPN_PROTO_UDP
@ OVPN_PROTO_TCP
#define OVPN_IOCTL_SWAP_KEYS
#define OVPN_IOCTL_NEW_KEY
#define OVPN_IOCTL_NOTIFY_EVENT
#define OVPN_IOCTL_MP_DEL_IROUTE
OVPN_MODE
@ OVPN_MODE_MP
#define OVPN_IOCTL_MP_SET_PEER
#define OVPN_IOCTL_MP_SWAP_KEYS
#define OVPN_IOCTL_GET_PEER_STATS
#define OVPN_IOCTL_SET_PEER
#define OVPN_IOCTL_NEW_PEER
#define OVPN_IOCTL_MP_ADD_IROUTE
#define CRYPTO_OPTIONS_EPOCH
#define OVPN_IOCTL_START_VPN
#define OVPN_IOCTL_MP_NEW_PEER
#define OVPN_IOCTL_SET_MODE
#define OVPN_IOCTL_DEL_PEER
#define OVPN_IOCTL_MP_START_VPN
struct _OVPN_MP_SET_PEER OVPN_MP_SET_PEER
#define OVPN_IOCTL_MP_DEL_PEER
struct _OVPN_PEER_STATS OVPN_PEER_STATS
void register_signal(struct signal_info *si, int signum, const char *signal_text)
Register a soft signal in the signal_info struct si respecting priority.
Definition sig.c:228
static void get_signal(volatile int *sig)
Copy the global signal_received (if non-zero) to the passed-in argument sig.
Definition sig.h:109
#define SF_PREPEND_SA
Definition socket.h:205
const char * print_in6_addr(struct in6_addr a6, unsigned int flags, struct gc_arena *gc)
const char * print_in_addr_t(in_addr_t addr, unsigned int flags, struct gc_arena *gc)
const char * addr_family_name(int af)
#define IA_NET_ORDER
Definition socket_util.h:90
Control Channel Common Data Structures.
OVPN_CRYPTO_DATA V1
OVPN_KEY_SLOT KeySlot
unsigned char KeyId
OVPN_KEY_DIRECTION Decrypt
OVPN_KEY_DIRECTION Encrypt
OVPN_CIPHER_ALG CipherAlg
unsigned char Key[32]
unsigned char NonceTail[8]
unsigned char KeyLen
union _OVPN_MP_IROUTE::@20 Addr
union _OVPN_MP_NEW_PEER::@17 Local
SOCKADDR_IN6 Addr6
SOCKADDR_IN Addr4
union _OVPN_MP_NEW_PEER::@18 Remote
SOCKADDR_IN6 Addr6
union _OVPN_MP_START_VPN::@19 ListenAddress
SOCKADDR_IN6 Addr6
union _OVPN_NEW_PEER::@15 Local
SOCKADDR_IN Addr4
union _OVPN_NEW_PEER::@16 Remote
OVPN_PROTO Proto
LONG64 TunBytesSent
LONG64 TransportBytesSent
LONG64 TunBytesReceived
LONG64 TransportBytesReceived
Wrapper structure for dynamically allocated memory.
Definition buffer.h:71
int len
Length in bytes of the actual content within the allocated memory.
Definition buffer.h:76
struct tuntap * tuntap
Tun/tap virtual network interface.
Definition openvpn.h:155
Level 2 context containing state that is reset on both SIGHUP and SIGUSR1 restarts.
Definition openvpn.h:207
counter_type dco_read_bytes
Definition openvpn.h:250
counter_type tun_read_bytes
Definition openvpn.h:247
counter_type dco_write_bytes
Definition openvpn.h:253
struct tls_multi * tls_multi
TLS state structure for this VPN tunnel.
Definition openvpn.h:300
counter_type tun_write_bytes
Definition openvpn.h:248
Contains all state information for one tunnel.
Definition openvpn.h:445
int mode
Role of this context within the OpenVPN process.
Definition openvpn.h:458
struct context_2 c2
Level 2 context.
Definition openvpn.h:490
struct options options
Options loaded from command line or configuration file.
Definition openvpn.h:446
struct context_1 c1
Level 1 context.
Definition openvpn.h:489
Garbage collection arena used to keep track of dynamically allocated memory.
Definition buffer.h:127
Server-mode state structure for one single VPN tunnel.
Definition multi.h:102
struct context context
The context structure storing state for this VPN tunnel.
Definition multi.h:150
const char * dev_node
Definition options.h:324
volatile int signal_received
Definition sig.h:42
int dco_peer_id
This is the handle that DCO uses to identify this session with the kernel.
Definition ssl_common.h:733
Definition tun.h:181
DWORD adapter_index
Definition tun.h:232
HANDLE hand
Definition tun.h:216
dco_context_t dco
Definition tun.h:247
#define SOCKET_PRINTF
Definition syshead.h:440
SOCKET socket_descriptor_t
Definition syshead.h:441
#define SIGUSR1
Definition syshead.h:57
uint32_t in_addr_t
Definition syshead.h:52
struct gc_arena gc
Definition test_ssl.c:138
void tun_open_device(struct tuntap *tt, const char *dev_node, const char **device_guid, struct gc_arena *gc)
Definition tun.c:5919
static bool tuntap_defined(const struct tuntap *tt)
Definition tun.h:252
#define IOSTATE_IMMEDIATE_RETURN
Definition win32.h:208
#define IOSTATE_INITIAL
Definition win32.h:206
#define IOSTATE_QUEUED
Definition win32.h:207