diff options
author | Jason A. Donenfeld <Jason@zx2c4.com> | 2019-03-08 22:33:15 +0100 |
---|---|---|
committer | Jason A. Donenfeld <Jason@zx2c4.com> | 2019-03-22 16:52:31 -0600 |
commit | 03479caf9db3447310f33a6711416a63bf6b0001 (patch) | |
tree | 23039eab9707d3ad244266f605506ea0f22eca71 | |
download | wintun-03479caf9db3447310f33a6711416a63bf6b0001.tar.xz wintun-03479caf9db3447310f33a6711416a63bf6b0001.zip |
Initial commit
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
Signed-off-by: Simon Rozman <simon@rozman.si>
-rw-r--r-- | .editorconfig | 3 | ||||
-rw-r--r-- | .gitignore | 6 | ||||
-rw-r--r-- | COPYING | 341 | ||||
-rw-r--r-- | README.md | 31 | ||||
-rw-r--r-- | wintun.c | 1140 | ||||
-rw-r--r-- | wintun.inf | 66 | ||||
-rw-r--r-- | wintun.rc | bin | 0 -> 1964 bytes | |||
-rw-r--r-- | wintun.vcxproj | 183 | ||||
-rw-r--r-- | wintun.vcxproj.filters | 32 |
9 files changed, 1802 insertions, 0 deletions
diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..faf7cbf --- /dev/null +++ b/.editorconfig @@ -0,0 +1,3 @@ +[*.{c,h,inf}] +indent_style = tab +indent_size = 8 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a7322c9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.vs/ +*.user +/Release +/Debug +/x64/Release +/x64/Debug @@ -0,0 +1,341 @@ +This program is Copyright (C) 2018-2019 WireGuard LLC. +------------------------------------------------------------------------------ + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License version 2 + as published by the Free Software Foundation. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + <signature of Ty Coon>, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..248eda0 --- /dev/null +++ b/README.md @@ -0,0 +1,31 @@ +# Wintun Network Adapter +### TUN Device Driver for Windows + +This is a layer 3 TUN driver for Windows 7, 8, 8.1, and 10. Originally created for [WireGuard](https://www.wireguard.com/), it is intended to be useful to a wide variety of projects that require layer 3 tunneling devices with implementations primarily in userspace. + +## Build Requirements + +- [Visual Studio 2017](https://visualstudio.microsoft.com/downloads/) +- [Windows Driver Kit for Windows 10](https://docs.microsoft.com/en-us/windows-hardware/drivers/download-the-wdk) + + +## Digital Signing + +Digital signing is integral part of the build process. By default, the driver will be test-signed using a certificate that the WDK should automatically generate. To subsequently load the driver, you will need to put your computer into test mode by executing as Administrator `bcdedit /set testsigning on`. + +If you possess an EV certificate for kernel mode code signing you should switch TUN driver digital signing from test-signing to production-signing by authoring your `wintun.vcxproj.user` file to look something like this: + +```xml +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup> + <SignMode>ProductionSign</SignMode> + <CrossCertificateFile>$(WDKContentRoot)CrossCertificates\DigiCert_High_Assurance_EV_Root_CA.crt</CrossCertificateFile> + <ProductionCertificate>CN=WireGuard LLC, O=WireGuard LLC, L=Boulder, S=Colorado, C=US, SERIALNUMBER=4227913, OID.2.5.4.15=Private Organization, OID.1.3.6.1.4.1.311.60.2.1.2=Ohio, OID.1.3.6.1.4.1.311.60.2.1.3=US | DF98E075A012ED8C86FBCF14854B8F9555CB3D45</ProductionCertificate> + </PropertyGroup> +</Project> +``` + +Modify the `<CrossCertificateFile>` to contain the full path to the cross-signing certificate of CA that issued your certificate. You should be able to find its `.crt` file in `C:\Program Files (x86)\Windows Kits\10\CrossCertificates`. Note that the `$(WDKContentRoot)` expands to `C:\Program Files (x86)\Windows Kits\10\`. + +If you already have `wintun.vcxproj.user` file, just add the `<PropertyGroup>` section. diff --git a/wintun.c b/wintun.c new file mode 100644 index 0000000..b777fc4 --- /dev/null +++ b/wintun.c @@ -0,0 +1,1140 @@ +/* SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2018-2019 WireGuard LLC. All Rights Reserved. + */ + +#define NDIS_MINIPORT_DRIVER +#define NDIS620_MINIPORT +#define NDIS_SUPPORT_NDIS620 1 +#define NDIS_WDM 1 + +#include <stdio.h> +#include <string.h> +#include <wdm.h> +#include <wdmsec.h> +#include <ndis.h> +#include <bcrypt.h> +#include <ntstrsafe.h> + +#pragma warning(disable : 4100) // unreferenced formal parameter +#pragma warning(disable : 4200) // nonstandard extension used: zero-sized array in struct/union +#pragma warning(disable : 4204) // nonstandard extension used: non-constant aggregate initializer +#pragma warning(disable : 4221) // nonstandard extension used: <member>: cannot be initialized using address of automatic variable <variable> + +#define TUN_DEVICE_NAME L"WINTUN%u" + +#define TUN_VENDOR_NAME "Wintun Tunnel" +#define TUN_VENDOR_ID 0xFFFFFF00 +#define TUN_LINK_SPEED 100000000000ULL // 100gbps + +#define TUN_EXCH_MAX_PACKETS 256 // Maximum number of exchange packets that can be exchanged in a single read/write +#define TUN_EXCH_MAX_PACKET_SIZE 0xF000 // Maximum exchange packet size - empirically determined by net buffer list (pool) limitations +#define TUN_EXCH_ALIGNMENT 16 // Memory alignment in exchange buffers +#define TUN_EXCH_MAX_IP_PACKET_SIZE (TUN_EXCH_MAX_PACKET_SIZE - sizeof(TUN_PACKET)) // Maximum IP packet size (headers + payload) +#define TUN_EXCH_MAX_BUFFER_SIZE (TUN_EXCH_MAX_PACKETS * TUN_EXCH_MAX_PACKET_SIZE) // Maximum size of read/write exchange buffer +#define TUN_QUEUE_MAX_NBLS 4096 + +typedef struct _TUN_PACKET { + ULONG Size; // Size of packet data (TUN_EXCH_MAX_IP_PACKET_SIZE max) + _Field_size_bytes_(Size) + __declspec(align(TUN_EXCH_ALIGNMENT)) + UCHAR Data[]; // Packet data +} TUN_PACKET; + +typedef struct _TUN_EVENT { + KEVENT *Event; + HANDLE Handle; +} TUN_EVENT; + +typedef struct _TUN_NBL_POOL { + NDIS_HANDLE Handle; + NET_BUFFER_LIST *List; +} TUN_NBL_POOL; + +typedef enum _TUN_STATE { + TUN_STATE_HALTED = 0, // The Halted state is the initial state of all adapters. When an adapter is in the Halted state, NDIS can call the driver's MiniportInitializeEx function to initialize the adapter. + TUN_STATE_SHUTDOWN, // In the Shutdown state, a system shutdown and restart must occur before the system can use the adapter again + TUN_STATE_INITIALIZING, // In the Initializing state, a miniport driver completes any operations that are required to initialize an adapter. + TUN_STATE_PAUSED, // In the Paused state, the adapter does not indicate received network data or accept send requests. + TUN_STATE_RESTARTING, // In the Restarting state, a miniport driver completes any operations that are required to restart send and receive operations for an adapter. + TUN_STATE_RUNNING, // In the Running state, a miniport driver performs send and receive processing for an adapter. + TUN_STATE_PAUSING, // In the Pausing state, a miniport driver completes any operations that are required to stop send and receive operations for an adapter. +} TUN_STATE; + +typedef struct _TUN_CTX { + volatile TUN_STATE State; + + volatile NDIS_DEVICE_POWER_STATE PowerState; + + NDIS_HANDLE MiniportAdapterHandle; + NDIS_STATISTICS_INFO Statistics; + + volatile LONG64 ActiveNBLCount; + + struct { + NDIS_HANDLE Handle; + DEVICE_OBJECT *Object; + volatile LONG64 RefCount; + IRP volatile *ActiveIrp; + } Device; + + struct { + NDIS_SPIN_LOCK Lock; + NET_BUFFER_LIST *Head, *Tail; + NET_BUFFER *Buffer; + UINT Count; + } PacketQueue; + + NDIS_HANDLE NBLPool; +} TUN_CTX; + +static NDIS_HANDLE NdisMiniportDriverHandle = NULL; + +#if REG_DWORD == REG_DWORD_BIG_ENDIAN +#define TUN_MEMORY_TAG 'wtun' +#define TunHtons(x) ((USHORT)(x)) +#define TunHtonl(x) ((ULONG)(x)) +#elif REG_DWORD == REG_DWORD_LITTLE_ENDIAN +#define TUN_MEMORY_TAG 'nutw' +#define TunHtons(x) RtlUshortByteSwap(x) +#define TunHtonl(x) RtlUlongByteSwap(x) +#else +#error "Unable to determine endianess" +#endif + +#define InterlockedGet(val) (InterlockedAdd((val), 0)) +#define InterlockedGet64(val) (InterlockedAdd64((val), 0)) +#define InterlockedSubtract64(val, n) (InterlockedAdd64((val), -(LONG64)(n))) +#define TunPacketAlign(size) (((UINT)(size) + (UINT)(TUN_EXCH_ALIGNMENT - 1)) & ~(UINT)(TUN_EXCH_ALIGNMENT - 1)) +#define TunInitUnicodeString(str, buf) { (str)->Length = 0; (str)->MaximumLength = sizeof(buf); (str)->Buffer = buf; } + +_IRQL_requires_same_ +static void TunAppendNBL(_Inout_ NET_BUFFER_LIST **head, _Inout_ NET_BUFFER_LIST **tail, __drv_aliasesMem _In_ NET_BUFFER_LIST *nbl) +{ + *(*tail ? &NET_BUFFER_LIST_NEXT_NBL(*tail) : head) = nbl; + *tail = nbl; + NET_BUFFER_LIST_NEXT_NBL(nbl) = NULL; +} + +_IRQL_requires_max_(DISPATCH_LEVEL) +_IRQL_requires_same_ +static void TunIndicateStatus(_In_ TUN_CTX *ctx) +{ + NDIS_LINK_STATE state = { + .Header = { + .Type = NDIS_OBJECT_TYPE_DEFAULT, + .Revision = NDIS_LINK_STATE_REVISION_1, + .Size = NDIS_SIZEOF_LINK_STATE_REVISION_1 + }, + .MediaConnectState = ctx->Device.RefCount > 0 ? MediaConnectStateConnected : MediaConnectStateDisconnected, + .MediaDuplexState = MediaDuplexStateFull, + .XmitLinkSpeed = TUN_LINK_SPEED, + .RcvLinkSpeed = TUN_LINK_SPEED, + .PauseFunctions = NdisPauseFunctionsUnsupported + }; + + NDIS_STATUS_INDICATION t = { + .Header = { + .Type = NDIS_OBJECT_TYPE_STATUS_INDICATION, + .Revision = NDIS_STATUS_INDICATION_REVISION_1, + .Size = NDIS_SIZEOF_STATUS_INDICATION_REVISION_1 + }, + .SourceHandle = ctx->MiniportAdapterHandle, + .StatusCode = NDIS_STATUS_LINK_STATE, + .StatusBuffer = &state, + .StatusBufferSize = sizeof(state) + }; + + NdisMIndicateStatusEx(ctx->MiniportAdapterHandle, &t); +} + +_IRQL_requires_max_(HIGH_LEVEL) +static TUN_CTX *TunGetContext(_In_ DEVICE_OBJECT *DeviceObject) +{ + TUN_CTX **control_device_extension = (TUN_CTX **)NdisGetDeviceReservedExtension(DeviceObject); + return control_device_extension ? *control_device_extension : NULL; +} + +_IRQL_requires_max_(DISPATCH_LEVEL) +static void TunCompleteRequest(_Inout_ IRP *Irp, _In_ ULONG_PTR Information, _In_ NTSTATUS Status) +{ + Irp->IoStatus.Information = Information; + Irp->IoStatus.Status = Status; + IoCompleteRequest(Irp, IO_NO_INCREMENT); +} + +_IRQL_requires_max_(DISPATCH_LEVEL) +static void TunCompletePausing(_Inout_ TUN_CTX *ctx, _In_ LONG64 decrement) +{ + if (!InterlockedSubtract64(&ctx->ActiveNBLCount, decrement) && + InterlockedCompareExchange((LONG *)&ctx->State, TUN_STATE_PAUSED, TUN_STATE_PAUSING) == TUN_STATE_PAUSING) + NdisMPauseComplete(ctx->MiniportAdapterHandle); +} + +_IRQL_requires_same_ +static ULONG TunSetNBLStatus(_Inout_opt_ NET_BUFFER_LIST *nbl, _In_ NDIS_STATUS status) +{ + ULONG nbl_count = 0; + for (; nbl; nbl = NET_BUFFER_LIST_NEXT_NBL(nbl), nbl_count++) + NET_BUFFER_LIST_STATUS(nbl) = status; + return nbl_count; +} + +_IRQL_requires_max_(DISPATCH_LEVEL) +static NTSTATUS TunGetIRPBuffer(_Inout_ IRP *Irp, _Out_ UCHAR **buffer, _Out_ ULONG *size) +{ + /* Get and validate request parameters. */ + ULONG priority; + IO_STACK_LOCATION *stack = IoGetCurrentIrpStackLocation(Irp); + switch (stack->MajorFunction) { + case IRP_MJ_READ: + *size = stack->Parameters.Read.Length; + priority = NormalPagePriority; + break; + + case IRP_MJ_WRITE: + *size = stack->Parameters.Write.Length; + priority = NormalPagePriority | MdlMappingNoWrite; + break; + + default: + return STATUS_INVALID_PARAMETER; + } + if (*size > TUN_EXCH_MAX_BUFFER_SIZE) + return STATUS_INVALID_USER_BUFFER; + + /* Get buffer size and address. */ + if (!Irp->MdlAddress) + return STATUS_INVALID_PARAMETER; + ULONG sizeMdl; + NdisQueryMdl(Irp->MdlAddress, buffer, &sizeMdl, priority); + if (!buffer) + return STATUS_INSUFFICIENT_RESOURCES; + if (sizeMdl < *size) + *size = sizeMdl; + + return STATUS_SUCCESS; +} + +_Requires_lock_not_held_(ctx->PacketQueue.Lock.SpinLock) +_IRQL_requires_max_(DISPATCH_LEVEL) +static void TunProcessPacketQueue(_Inout_ TUN_CTX *ctx, _Inout_ IRP *Irp) +{ + /* Prepare IRP for read. */ + CCHAR PriorityBoost = IO_NO_INCREMENT; + ULONG SendCompleteFlags = 0; + ULONG nbl_count = 0; + NET_BUFFER_LIST *nbl_head = NULL, *nbl_tail = NULL; + UCHAR *buffer = NULL; + ULONG size = 0; + Irp->IoStatus.Information = 0; + Irp->IoStatus.Status = TunGetIRPBuffer(Irp, &buffer, &size); + if (Irp->IoStatus.Status != STATUS_SUCCESS) + goto cleanup_complete_req; + + UCHAR *b = buffer, *b_end = buffer + size; + LONG64 stat_size = 0, stat_p_ok = 0, stat_p_err = 0; + + /* Transfer packets from NBL queue to IRP. */ + NdisAcquireSpinLock(&ctx->PacketQueue.Lock); + if (ctx->PacketQueue.Lock.OldIrql >= DISPATCH_LEVEL) + SendCompleteFlags |= NDIS_SEND_COMPLETE_FLAGS_DISPATCH_LEVEL; + while (ctx->PacketQueue.Head) { + for (; ctx->PacketQueue.Buffer; ctx->PacketQueue.Buffer = NET_BUFFER_NEXT_NB(ctx->PacketQueue.Buffer)) { + ULONG p_size = NET_BUFFER_DATA_LENGTH(ctx->PacketQueue.Buffer); + if (p_size > TUN_EXCH_MAX_IP_PACKET_SIZE) { + NET_BUFFER_LIST_STATUS(ctx->PacketQueue.Head) = NDIS_STATUS_INVALID_LENGTH; + goto error; + } + + UCHAR *b_next = b + TunPacketAlign(sizeof(TUN_PACKET) + p_size); + if (b_next > b_end) + goto cleanup_NdisReleaseSpinLock; + + TUN_PACKET *p = (TUN_PACKET *)b; + p->Size = p_size; + void *ptr = NdisGetDataBuffer(ctx->PacketQueue.Buffer, p_size, p->Data, 1, 0); + if (!ptr) { + NET_BUFFER_LIST_STATUS(ctx->PacketQueue.Head) = NDIS_STATUS_RESOURCES; + goto error; + } + if (ptr != p->Data) + NdisMoveMemory(p->Data, ptr, p_size); + + stat_size += p_size; + stat_p_ok++; + b = b_next; + continue; + + error: + stat_p_err++; + } + + /* NBL depleted: Relocate it to the "completed" queue. */ + NET_BUFFER_LIST *nbl_next = NET_BUFFER_LIST_NEXT_NBL(ctx->PacketQueue.Head); + TunAppendNBL(&nbl_head, &nbl_tail, ctx->PacketQueue.Head); + nbl_count++; + ctx->PacketQueue.Head = nbl_next; + if (ctx->PacketQueue.Head) + ctx->PacketQueue.Buffer = NET_BUFFER_LIST_FIRST_NB(ctx->PacketQueue.Head); + else + ctx->PacketQueue.Tail = NULL; + } +cleanup_NdisReleaseSpinLock: + ctx->PacketQueue.Count -= nbl_count; + NdisReleaseSpinLock(&ctx->PacketQueue.Lock); + + Irp->IoStatus.Information = b - buffer; + PriorityBoost = IO_NETWORK_INCREMENT; + + InterlockedAdd64((LONG64 *)&ctx->Statistics.ifHCOutOctets, stat_size); + InterlockedAdd64((LONG64 *)&ctx->Statistics.ifHCOutUcastOctets, stat_size); + InterlockedAdd64((LONG64 *)&ctx->Statistics.ifHCOutUcastPkts, stat_p_ok); + InterlockedAdd64((LONG64 *)&ctx->Statistics.ifOutErrors, stat_p_err); + +cleanup_complete_req: + IoCompleteRequest(Irp, PriorityBoost); + IoStartNextPacket(ctx->Device.Object, FALSE); + + if (nbl_head) { + NdisMSendNetBufferListsComplete(ctx->MiniportAdapterHandle, nbl_head, SendCompleteFlags); + TunCompletePausing(ctx, nbl_count); + } +} + +static DRIVER_STARTIO TunStartIo; +_Use_decl_annotations_ +VOID TunStartIo(_Inout_ DEVICE_OBJECT *DeviceObject, _Inout_ IRP *Irp) +{ + TUN_CTX *ctx = TunGetContext(DeviceObject); + if (!ctx) { + TunCompleteRequest(Irp, 0, STATUS_CANCELLED); + IoStartNextPacket(DeviceObject, FALSE); + return; + } + + NdisAcquireSpinLock(&ctx->PacketQueue.Lock); + if (!ctx->PacketQueue.Head) { + /* Set active IRP before releasing the spin lock. If this thread would be interrupted after ctx->PacketQueue.Lock + * release and before ctx->Device.ActiveIrp is set, and TunSendNetBufferLists() is called meanwhile, the later + * will not notice pending IRP and not call TunProcessPacketQueue() causing read to stall until next + * TunSendNetBufferLists() call. */ + InterlockedExchangePointer((PVOID volatile *)&ctx->Device.ActiveIrp, Irp); + NdisReleaseSpinLock(&ctx->PacketQueue.Lock); + return; + } + NdisReleaseSpinLock(&ctx->PacketQueue.Lock); + + TunProcessPacketQueue(ctx, Irp); +} + +static DRIVER_DISPATCH TunDispatchCreate; +_Use_decl_annotations_ +static NTSTATUS TunDispatchCreate(DEVICE_OBJECT *DeviceObject, IRP *Irp) +{ + NTSTATUS status = STATUS_UNSUCCESSFUL; + + TUN_CTX *ctx = TunGetContext(DeviceObject); + if (!ctx) { + status = STATUS_INVALID_HANDLE; + goto cleanup_complete_req; + } + + InterlockedIncrement64(&ctx->Device.RefCount); + TunIndicateStatus(ctx); + status = STATUS_SUCCESS; + +cleanup_complete_req: + TunCompleteRequest(Irp, 0, status); + return status; +} + +static DRIVER_DISPATCH TunDispatchClose; +_Use_decl_annotations_ +static NTSTATUS TunDispatchClose(DEVICE_OBJECT *DeviceObject, IRP *Irp) +{ + NTSTATUS status = STATUS_UNSUCCESSFUL; + + TUN_CTX *ctx = TunGetContext(DeviceObject); + if (!ctx) { + status = STATUS_INVALID_HANDLE; + goto cleanup_complete_req; + } + + InterlockedDecrement64(&ctx->Device.RefCount); + TunIndicateStatus(ctx); + status = STATUS_SUCCESS; + +cleanup_complete_req: + TunCompleteRequest(Irp, 0, status); + return status; +} + +static DRIVER_DISPATCH TunDispatchRead; +_Use_decl_annotations_ +static NTSTATUS TunDispatchRead(DEVICE_OBJECT *DeviceObject, IRP *Irp) +{ + NTSTATUS status = STATUS_UNSUCCESSFUL; + + TUN_CTX *ctx = TunGetContext(DeviceObject); + if (!ctx) { + status = STATUS_INVALID_HANDLE; + goto cleanup_complete_req; + } + + IoMarkIrpPending(Irp); + IoStartPacket(DeviceObject, Irp, NULL, NULL); + return STATUS_PENDING; + +cleanup_complete_req: + TunCompleteRequest(Irp, 0, status); + return status; +} + +static DRIVER_DISPATCH TunDispatchWrite; +_Use_decl_annotations_ +static NTSTATUS TunDispatchWrite(DEVICE_OBJECT *DeviceObject, IRP *Irp) +{ + NTSTATUS status = STATUS_UNSUCCESSFUL; + ULONG_PTR information = 0; + + TUN_CTX *ctx = TunGetContext(DeviceObject); + if (!ctx) { + status = STATUS_INVALID_HANDLE; + goto cleanup_complete_req; + } + + UCHAR *buffer = NULL; + ULONG size = 0; + status = TunGetIRPBuffer(Irp, &buffer, &size); + if (status != STATUS_SUCCESS) + goto cleanup_complete_req; + + const UCHAR *b = buffer, *b_end = buffer + size; + ULONG nbl_count = 0; + NET_BUFFER_LIST *nbl_head = NULL, *nbl_tail = NULL; + LONG64 stat_p_err = 0; + while (b < b_end) { + TUN_PACKET *p = (TUN_PACKET *)b; + if (p->Size > TUN_EXCH_MAX_IP_PACKET_SIZE) + break; + UINT p_size = TunPacketAlign(sizeof(TUN_PACKET) + p->Size); + if (b + p_size > b_end) + break; + + ULONG nbl_flags; + USHORT nbl_proto; + if (p->Size >= 20 && p->Data[0] >> 4 == 4) { + nbl_flags = NDIS_NBL_FLAGS_IS_IPV4; + nbl_proto = NDIS_ETH_TYPE_IPV4; + } else if (p->Size >= 40 && p->Data[0] >> 4 == 6) { + nbl_flags = NDIS_NBL_FLAGS_IS_IPV6; + nbl_proto = NDIS_ETH_TYPE_IPV6; + } else { + goto skip_packet; + } + + MDL *mdl = NdisAllocateMdl(ctx->MiniportAdapterHandle, p->Data, p->Size); + if (!mdl) + goto skip_packet; + + #pragma warning(suppress: 6014) /* Leaking memory 'nbl'. Note: 'nbl' is aliased in nbl_head/tail list and freed in TunReturnNetBufferLists. */ + NET_BUFFER_LIST *nbl = NdisAllocateNetBufferAndNetBufferList(ctx->NBLPool, 0, 0, mdl, 0, p->Size); + if (!nbl) + goto cleanup_NdisFreeMdl; + + nbl->SourceHandle = ctx->MiniportAdapterHandle; + NdisSetNblFlag(nbl, nbl_flags); + NET_BUFFER_LIST_INFO(nbl, NetBufferListFrameType) = (PVOID)TunHtons(nbl_proto); + NET_BUFFER_LIST_STATUS(nbl) = NDIS_STATUS_SUCCESS; + TunAppendNBL(&nbl_head, &nbl_tail, nbl); + nbl_count++; + goto next_packet; + + cleanup_NdisFreeMdl: + NdisFreeMdl(mdl); + skip_packet: + stat_p_err++; + next_packet: + b += p_size; + } + + InterlockedAdd64((LONG64 *)&ctx->Statistics.ifInErrors, stat_p_err); + + if ((status = STATUS_NDIS_PAUSED, InterlockedGet((LONG *)&ctx->State) != TUN_STATE_RUNNING) || + (status = STATUS_NDIS_LOW_POWER_STATE, ctx->PowerState >= NdisDeviceStateD1)) { + for (NET_BUFFER_LIST *nbl = nbl_head, *nbl_next; nbl; nbl = nbl_next) { + nbl_next = NET_BUFFER_LIST_NEXT_NBL(nbl); + NET_BUFFER_LIST_NEXT_NBL(nbl) = NULL; + NdisFreeMdl(NET_BUFFER_FIRST_MDL(NET_BUFFER_LIST_FIRST_NB(nbl))); + NdisFreeNetBufferList(nbl); + } + goto cleanup_complete_req; + } + + if (!nbl_head) + goto finish; + + InterlockedAdd64(&ctx->ActiveNBLCount, 1i64 + nbl_count); + NdisMIndicateReceiveNetBufferLists(ctx->MiniportAdapterHandle, nbl_head, NDIS_DEFAULT_PORT_NUMBER, nbl_count, 0); + TunCompletePausing(ctx, 1); + +finish: + information = b - buffer; + status = STATUS_SUCCESS; + +cleanup_complete_req: + TunCompleteRequest(Irp, information, status); + return status; +} + +static MINIPORT_SET_OPTIONS TunSetOptions; +_Use_decl_annotations_ +static NDIS_STATUS TunSetOptions(NDIS_HANDLE NdisDriverHandle, NDIS_HANDLE DriverContext) +{ + /* TODO: This handler is optional. See if it can be removed. */ + return NDIS_STATUS_SUCCESS; +} + +static MINIPORT_PAUSE TunPause; +_Use_decl_annotations_ +static NDIS_STATUS TunPause(NDIS_HANDLE MiniportAdapterContext, PNDIS_MINIPORT_PAUSE_PARAMETERS MiniportPauseParameters) +{ + TUN_CTX *ctx = (TUN_CTX *)MiniportAdapterContext; + if (InterlockedCompareExchange((LONG *)&ctx->State, TUN_STATE_PAUSING, TUN_STATE_RUNNING) != TUN_STATE_RUNNING) + return NDIS_STATUS_FAILURE; + + ULONG nbl_count = 0; + NdisAcquireSpinLock(&ctx->PacketQueue.Lock); + if (ctx->PacketQueue.Head) { + NET_BUFFER_LIST *nbl = ctx->PacketQueue.Head; + ctx->PacketQueue.Head = NULL; + ctx->PacketQueue.Buffer = NULL; + ctx->PacketQueue.Tail = NULL; + ctx->PacketQueue.Count = 0; + NdisReleaseSpinLock(&ctx->PacketQueue.Lock); + + nbl_count += TunSetNBLStatus(nbl, NDIS_STATUS_PAUSED); + NdisMSendNetBufferListsComplete(ctx->MiniportAdapterHandle, nbl, 0); + } else + NdisReleaseSpinLock(&ctx->PacketQueue.Lock); + + TunIndicateStatus(ctx); + + if (InterlockedSubtract64(&ctx->ActiveNBLCount, nbl_count)) + return NDIS_STATUS_PENDING; + + InterlockedExchange((LONG *)&ctx->State, TUN_STATE_PAUSED); + return NDIS_STATUS_SUCCESS; +} + +static MINIPORT_RESTART TunRestart; +_Use_decl_annotations_ +static NDIS_STATUS TunRestart(NDIS_HANDLE MiniportAdapterContext, PNDIS_MINIPORT_RESTART_PARAMETERS MiniportRestartParameters) +{ + TUN_CTX *ctx = (TUN_CTX *)MiniportAdapterContext; + if (InterlockedCompareExchange((LONG *)&ctx->State, TUN_STATE_RESTARTING, TUN_STATE_PAUSED) != TUN_STATE_PAUSED) + return NDIS_STATUS_FAILURE; + + TunIndicateStatus(ctx); + + InterlockedExchange((LONG *)&ctx->State, TUN_STATE_RUNNING); + return NDIS_STATUS_SUCCESS; +} + +static MINIPORT_RETURN_NET_BUFFER_LISTS TunReturnNetBufferLists; +_Use_decl_annotations_ +static void TunReturnNetBufferLists(NDIS_HANDLE MiniportAdapterContext, PNET_BUFFER_LIST NetBufferLists, ULONG ReturnFlags) +{ + TUN_CTX *ctx = (TUN_CTX *)MiniportAdapterContext; + LONG64 stat_size = 0, stat_p_ok = 0, stat_p_err = 0; + ULONG nbl_count = 0; + + for (NET_BUFFER_LIST *nbl = NetBufferLists, *nbl_next; nbl; nbl = nbl_next, nbl_count++) { + nbl_next = NET_BUFFER_LIST_NEXT_NBL(nbl); + NET_BUFFER_LIST_NEXT_NBL(nbl) = NULL; + + MDL *mdl = NET_BUFFER_FIRST_MDL(NET_BUFFER_LIST_FIRST_NB(nbl)); + if (NET_BUFFER_LIST_STATUS(nbl) == NDIS_STATUS_SUCCESS) { + ULONG size = MmGetMdlByteCount(mdl); + stat_size += size; + stat_p_ok++; + } else + stat_p_err++; + + NdisFreeMdl(mdl); + NdisFreeNetBufferList(nbl); + } + + InterlockedAdd64((LONG64 *)&ctx->Statistics.ifHCInOctets, stat_size); + InterlockedAdd64((LONG64 *)&ctx->Statistics.ifHCInUcastOctets, stat_size); + InterlockedAdd64((LONG64 *)&ctx->Statistics.ifHCInUcastPkts, stat_p_ok); + InterlockedAdd64((LONG64 *)&ctx->Statistics.ifInErrors, stat_p_err); + + TunCompletePausing(ctx, nbl_count); +} + +static MINIPORT_CANCEL_SEND TunCancelSend; +_Use_decl_annotations_ +static void TunCancelSend(NDIS_HANDLE MiniportAdapterContext, PVOID CancelId) +{ + TUN_CTX *ctx = (TUN_CTX *)MiniportAdapterContext; + ULONG nbl_drop_count = 0; + NET_BUFFER_LIST *nbl_keep_head = NULL, *nbl_keep_tail = NULL, *nbl_drop_head = NULL, *nbl_drop_tail = NULL; + + NdisAcquireSpinLock(&ctx->PacketQueue.Lock); + ULONG SendCompleteFlags = ctx->PacketQueue.Lock.OldIrql >= DISPATCH_LEVEL ? NDIS_SEND_COMPLETE_FLAGS_DISPATCH_LEVEL : 0; + + /* Split NBL queue into two queues: one with NBLs to keep, one with NBLs to drop. */ + for (NET_BUFFER_LIST *nbl = ctx->PacketQueue.Head, *nbl_next; nbl; nbl = nbl_next) { + nbl_next = NET_BUFFER_LIST_NEXT_NBL(nbl); + if (NDIS_GET_NET_BUFFER_LIST_CANCEL_ID(nbl) == CancelId) { + NET_BUFFER_LIST_STATUS(nbl) = NDIS_STATUS_SEND_ABORTED; + TunAppendNBL(&nbl_drop_head, &nbl_drop_tail, nbl); + nbl_drop_count++; + } else + TunAppendNBL(&nbl_keep_head, &nbl_keep_tail, nbl); + } + + if (ctx->PacketQueue.Head != nbl_keep_head) { + ctx->PacketQueue.Buffer = nbl_keep_head ? NET_BUFFER_LIST_FIRST_NB(nbl_keep_head) : NULL; + ctx->PacketQueue.Head = nbl_keep_head; + } + + ctx->PacketQueue.Count -= nbl_drop_count; + NdisReleaseSpinLock(&ctx->PacketQueue.Lock); + + if (nbl_drop_head) { + NdisMSendNetBufferListsComplete(ctx->MiniportAdapterHandle, nbl_drop_head, SendCompleteFlags); + TunCompletePausing(ctx, nbl_drop_count); + } +} + +static MINIPORT_DEVICE_PNP_EVENT_NOTIFY TunDevicePnPEventNotify; +_Use_decl_annotations_ +static void TunDevicePnPEventNotify(NDIS_HANDLE MiniportAdapterContext, PNET_DEVICE_PNP_EVENT NetDevicePnPEvent) +{ +} + +static MINIPORT_SHUTDOWN TunShutdownEx; +_Use_decl_annotations_ +static void TunShutdownEx(NDIS_HANDLE MiniportAdapterContext, NDIS_SHUTDOWN_ACTION ShutdownAction) +{ + TUN_CTX *ctx = (TUN_CTX *)MiniportAdapterContext; + + if (ShutdownAction == NdisShutdownBugCheck) + return; + + InterlockedExchange((LONG *)&ctx->State, TUN_STATE_SHUTDOWN); +} + +static MINIPORT_CANCEL_DIRECT_OID_REQUEST TunCancelDirectOidRequest; +_Use_decl_annotations_ +static void TunCancelDirectOidRequest(NDIS_HANDLE MiniportAdapterContext, PVOID RequestId) +{ +} + +static MINIPORT_CANCEL_OID_REQUEST TunCancelOidRequest; +_Use_decl_annotations_ +static void TunCancelOidRequest(NDIS_HANDLE MiniportAdapterContext, PVOID RequestId) +{ +} + +static MINIPORT_INITIALIZE TunInitializeEx; +_Use_decl_annotations_ +static NDIS_STATUS TunInitializeEx(NDIS_HANDLE MiniportAdapterHandle, NDIS_HANDLE MiniportDriverContext, PNDIS_MINIPORT_INIT_PARAMETERS MiniportInitParameters) +{ + NDIS_STATUS status; + + if (!MiniportAdapterHandle) + return NDIS_STATUS_FAILURE; + + TUN_CTX *ctx; + #pragma warning(suppress: 6014) /* Leaking memory 'ctx'. Note: 'ctx' is aliased in attr.MiniportAdapterContext; or freed on failure. */ + if (NdisAllocateMemoryWithTag(&ctx, sizeof(TUN_CTX), TUN_MEMORY_TAG) != NDIS_STATUS_SUCCESS) + return NDIS_STATUS_FAILURE; + + NdisZeroMemory(ctx, sizeof(*ctx)); + ctx->State = TUN_STATE_INITIALIZING; + ctx->PowerState = NdisDeviceStateD0; + ctx->MiniportAdapterHandle = MiniportAdapterHandle; + + ctx->Statistics.Header.Type = NDIS_OBJECT_TYPE_DEFAULT; + ctx->Statistics.Header.Revision = NDIS_STATISTICS_INFO_REVISION_1; + ctx->Statistics.Header.Size = NDIS_SIZEOF_STATISTICS_INFO_REVISION_1; + ctx->Statistics.SupportedStatistics = + NDIS_STATISTICS_FLAGS_VALID_DIRECTED_FRAMES_RCV | + NDIS_STATISTICS_FLAGS_VALID_MULTICAST_FRAMES_RCV | + NDIS_STATISTICS_FLAGS_VALID_BROADCAST_FRAMES_RCV | + NDIS_STATISTICS_FLAGS_VALID_BYTES_RCV | + NDIS_STATISTICS_FLAGS_VALID_RCV_DISCARDS | + NDIS_STATISTICS_FLAGS_VALID_RCV_ERROR | + NDIS_STATISTICS_FLAGS_VALID_DIRECTED_FRAMES_XMIT | + NDIS_STATISTICS_FLAGS_VALID_MULTICAST_FRAMES_XMIT | + NDIS_STATISTICS_FLAGS_VALID_BROADCAST_FRAMES_XMIT | + NDIS_STATISTICS_FLAGS_VALID_BYTES_XMIT | + NDIS_STATISTICS_FLAGS_VALID_XMIT_ERROR | + NDIS_STATISTICS_FLAGS_VALID_XMIT_DISCARDS | + NDIS_STATISTICS_FLAGS_VALID_DIRECTED_BYTES_RCV | + NDIS_STATISTICS_FLAGS_VALID_MULTICAST_BYTES_RCV | + NDIS_STATISTICS_FLAGS_VALID_BROADCAST_BYTES_RCV | + NDIS_STATISTICS_FLAGS_VALID_DIRECTED_BYTES_XMIT | + NDIS_STATISTICS_FLAGS_VALID_MULTICAST_BYTES_XMIT | + NDIS_STATISTICS_FLAGS_VALID_BROADCAST_BYTES_XMIT; + + NDIS_MINIPORT_ADAPTER_REGISTRATION_ATTRIBUTES attr = { + .Header = { + .Type = NDIS_OBJECT_TYPE_MINIPORT_ADAPTER_REGISTRATION_ATTRIBUTES, + .Revision = NDIS_MINIPORT_ADAPTER_REGISTRATION_ATTRIBUTES_REVISION_1, + .Size = NDIS_SIZEOF_MINIPORT_ADAPTER_REGISTRATION_ATTRIBUTES_REVISION_1 + }, + .AttributeFlags = NDIS_MINIPORT_ATTRIBUTES_NO_HALT_ON_SUSPEND, + .InterfaceType = NdisInterfaceInternal, + .MiniportAdapterContext = ctx + }; + if (NdisMSetMiniportAttributes(MiniportAdapterHandle, (PNDIS_MINIPORT_ADAPTER_ATTRIBUTES)&attr) != NDIS_STATUS_SUCCESS) { + status = NDIS_STATUS_FAILURE; + goto cleanup_ctx; + } + + NDIS_PM_CAPABILITIES pmcap = { + .Header = { + .Type = NDIS_OBJECT_TYPE_DEFAULT, + .Revision = NDIS_PM_CAPABILITIES_REVISION_1, + .Size = NDIS_SIZEOF_NDIS_PM_CAPABILITIES_REVISION_1 + }, + .MinMagicPacketWakeUp = NdisDeviceStateUnspecified, + .MinPatternWakeUp = NdisDeviceStateUnspecified, + .MinLinkChangeWakeUp = NdisDeviceStateUnspecified + }; + static NDIS_OID suported_oids[] = { + OID_GEN_MAXIMUM_TOTAL_SIZE, + OID_GEN_CURRENT_LOOKAHEAD, + OID_GEN_TRANSMIT_BUFFER_SPACE, + OID_GEN_RECEIVE_BUFFER_SPACE, + OID_GEN_TRANSMIT_BLOCK_SIZE, + OID_GEN_RECEIVE_BLOCK_SIZE, + OID_GEN_VENDOR_DESCRIPTION, + OID_GEN_VENDOR_ID, + OID_GEN_VENDOR_DRIVER_VERSION, + OID_GEN_XMIT_OK, + OID_GEN_RCV_OK, + OID_GEN_CURRENT_PACKET_FILTER, + OID_GEN_STATISTICS, + OID_GEN_INTERRUPT_MODERATION, + OID_GEN_LINK_PARAMETERS, + OID_PNP_SET_POWER, + OID_PNP_QUERY_POWER + }; + NDIS_MINIPORT_ADAPTER_GENERAL_ATTRIBUTES gen = { + .Header = { + .Type = NDIS_OBJECT_TYPE_MINIPORT_ADAPTER_GENERAL_ATTRIBUTES, + .Revision = NDIS_MINIPORT_ADAPTER_GENERAL_ATTRIBUTES_REVISION_2, + .Size = NDIS_SIZEOF_MINIPORT_ADAPTER_GENERAL_ATTRIBUTES_REVISION_2 + }, + .MediaType = NdisMediumIP, + .PhysicalMediumType = NdisPhysicalMediumUnspecified, + .MtuSize = TUN_EXCH_MAX_IP_PACKET_SIZE, + .MaxXmitLinkSpeed = TUN_LINK_SPEED, + .MaxRcvLinkSpeed = TUN_LINK_SPEED, + .RcvLinkSpeed = TUN_LINK_SPEED, + .XmitLinkSpeed = TUN_LINK_SPEED, + .MediaConnectState = MediaConnectStateDisconnected, + .LookaheadSize = TUN_EXCH_MAX_IP_PACKET_SIZE, + .MacOptions = + NDIS_MAC_OPTION_TRANSFERS_NOT_PEND | + NDIS_MAC_OPTION_COPY_LOOKAHEAD_DATA | + NDIS_MAC_OPTION_NO_LOOPBACK, + .SupportedPacketFilters = + NDIS_PACKET_TYPE_DIRECTED | + NDIS_PACKET_TYPE_ALL_MULTICAST | + NDIS_PACKET_TYPE_BROADCAST | + NDIS_PACKET_TYPE_ALL_LOCAL | + NDIS_PACKET_TYPE_ALL_FUNCTIONAL, + .AccessType = NET_IF_ACCESS_BROADCAST, + .DirectionType = NET_IF_DIRECTION_SENDRECEIVE, + .ConnectionType = NET_IF_CONNECTION_DEDICATED, + .IfType = IF_TYPE_PROP_VIRTUAL, + .IfConnectorPresent = FALSE, + .SupportedStatistics = ctx->Statistics.SupportedStatistics, + .SupportedPauseFunctions = NdisPauseFunctionsUnsupported, + .AutoNegotiationFlags = + NDIS_LINK_STATE_XMIT_LINK_SPEED_AUTO_NEGOTIATED | + NDIS_LINK_STATE_RCV_LINK_SPEED_AUTO_NEGOTIATED | + NDIS_LINK_STATE_DUPLEX_AUTO_NEGOTIATED | + NDIS_LINK_STATE_PAUSE_FUNCTIONS_AUTO_NEGOTIATED, + .SupportedOidList = suported_oids, + .SupportedOidListLength = sizeof(suported_oids), + .PowerManagementCapabilitiesEx = &pmcap + }; + if (NdisMSetMiniportAttributes(MiniportAdapterHandle, (PNDIS_MINIPORT_ADAPTER_ATTRIBUTES)&gen) != NDIS_STATUS_SUCCESS) { + status = NDIS_STATUS_FAILURE; + goto cleanup_ctx; + } + + NdisAllocateSpinLock(&ctx->PacketQueue.Lock); + + /* A miniport driver can call NdisMIndicateStatusEx after setting its + * registration attributes even if the driver is still in the context + * of the MiniportInitializeEx function. + */ + TunIndicateStatus(ctx); + + NET_BUFFER_LIST_POOL_PARAMETERS nbl_pool_param = { + .Header = { + .Type = NDIS_OBJECT_TYPE_DEFAULT, + .Revision = NET_BUFFER_LIST_POOL_PARAMETERS_REVISION_1, + .Size = NDIS_SIZEOF_NET_BUFFER_LIST_POOL_PARAMETERS_REVISION_1 + }, + .ProtocolId = NDIS_PROTOCOL_ID_DEFAULT, + .fAllocateNetBuffer = TRUE, + .PoolTag = TUN_MEMORY_TAG + }; + #pragma warning(suppress: 6014) /* Leaking memory 'ctx->NBLPool'. Note: 'ctx->NBLPool' is freed in TunHaltEx; or freed on failure. */ + ctx->NBLPool = NdisAllocateNetBufferListPool(MiniportAdapterHandle, &nbl_pool_param); + if (!ctx->NBLPool) { + status = NDIS_STATUS_FAILURE; + goto cleanup_NdisFreeSpinLock; + } + + WCHAR device_name[(sizeof(L"\\Device\\" TUN_DEVICE_NAME) + 10/*MAXULONG as string*/) / sizeof(WCHAR)]; + UNICODE_STRING unicode_device_name; + TunInitUnicodeString(&unicode_device_name, device_name); + RtlUnicodeStringPrintf(&unicode_device_name, L"\\Device\\" TUN_DEVICE_NAME, (ULONG)MiniportInitParameters->NetLuid.Info.NetLuidIndex); + + WCHAR symbolic_name[(sizeof(L"\\DosDevices\\" TUN_DEVICE_NAME) + 10/*MAXULONG as string*/) / sizeof(WCHAR)]; + UNICODE_STRING unicode_symbolic_name; + TunInitUnicodeString(&unicode_symbolic_name, symbolic_name); + RtlUnicodeStringPrintf(&unicode_symbolic_name, L"\\DosDevices\\" TUN_DEVICE_NAME, (ULONG)MiniportInitParameters->NetLuid.Info.NetLuidIndex); + + static PDRIVER_DISPATCH dispatch_table[IRP_MJ_MAXIMUM_FUNCTION + 1] = { + TunDispatchCreate, /* IRP_MJ_CREATE */ + NULL, /* IRP_MJ_CREATE_NAMED_PIPE */ + TunDispatchClose, /* IRP_MJ_CLOSE */ + TunDispatchRead, /* IRP_MJ_READ */ + TunDispatchWrite, /* IRP_MJ_WRITE */ + }; + NDIS_DEVICE_OBJECT_ATTRIBUTES t = { + .Header = { + .Type = NDIS_OBJECT_TYPE_DEVICE_OBJECT_ATTRIBUTES, + .Revision = NDIS_DEVICE_OBJECT_ATTRIBUTES_REVISION_1, + .Size = NDIS_SIZEOF_DEVICE_OBJECT_ATTRIBUTES_REVISION_1 + }, + .DeviceName = &unicode_device_name, + .SymbolicName = &unicode_symbolic_name, + .MajorFunctions = dispatch_table, + .ExtensionSize = sizeof(TUN_CTX *), + .DefaultSDDLString = &SDDL_DEVOBJ_SYS_ALL /* Kernel, and SYSTEM: full control. Others: none */ + }; + if (NdisRegisterDeviceEx(NdisMiniportDriverHandle, &t, &ctx->Device.Object, &ctx->Device.Handle) != NDIS_STATUS_SUCCESS) { + status = NDIS_STATUS_FAILURE; + goto cleanup_NdisFreeNetBufferListPool; + } + + ctx->Device.Object->Flags &= ~DO_BUFFERED_IO; + ctx->Device.Object->Flags |= DO_DIRECT_IO; + + IoSetStartIoAttributes(ctx->Device.Object, TRUE, TRUE); + + TUN_CTX **control_device_extension = (TUN_CTX **)NdisGetDeviceReservedExtension(ctx->Device.Object); + if (!control_device_extension) { + status = NDIS_STATUS_FAILURE; + goto cleanup_NdisDeregisterDeviceEx; + } + InterlockedExchangePointer(control_device_extension, ctx); + + ctx->State = TUN_STATE_PAUSED; + return NDIS_STATUS_SUCCESS; + +cleanup_NdisDeregisterDeviceEx: + NdisDeregisterDeviceEx(ctx->Device.Handle); +cleanup_NdisFreeNetBufferListPool: + NdisFreeNetBufferListPool(ctx->NBLPool); +cleanup_NdisFreeSpinLock: + NdisFreeSpinLock(&ctx->PacketQueue.Lock); +cleanup_ctx: + NdisFreeMemory(ctx, 0, 0); + return status; +} + +static MINIPORT_UNLOAD TunDriverUnload; +_Use_decl_annotations_ +static VOID TunDriverUnload(PDRIVER_OBJECT DriverObject) +{ + NdisMDeregisterMiniportDriver(NdisMiniportDriverHandle); +} + +static MINIPORT_HALT TunHaltEx; +_Use_decl_annotations_ +static void TunHaltEx(NDIS_HANDLE MiniportAdapterContext, NDIS_HALT_ACTION HaltAction) +{ + TUN_CTX *ctx = (TUN_CTX *)MiniportAdapterContext; + if (InterlockedGet((LONG *)&ctx->State) != TUN_STATE_PAUSED) + return; + + /* Reset adapter context in device object, as Windows keep calling dispatch handlers even after NdisDeregisterDeviceEx(). */ + TUN_CTX **control_device_extension = (TUN_CTX **)NdisGetDeviceReservedExtension(ctx->Device.Object); + if (control_device_extension) + InterlockedExchangePointer(control_device_extension, NULL); + + /* Cancel pending IRP to unblock waiting clients. */ + IRP *Irp = InterlockedExchangePointer((PVOID volatile *)&ctx->Device.ActiveIrp, NULL); + if (Irp) + TunCompleteRequest(Irp, 0, STATUS_CANCELLED); + + /* Release resources. */ + NdisDeregisterDeviceEx(ctx->Device.Handle); + NdisFreeNetBufferListPool(ctx->NBLPool); + NdisFreeSpinLock(&ctx->PacketQueue.Lock); + NdisFreeMemory(ctx, 0, 0); +} + +_IRQL_requires_max_(PASSIVE_LEVEL) +_IRQL_requires_same_ +static NDIS_STATUS TunOidSet(_Inout_ TUN_CTX *ctx, _In_ NDIS_OID Oid, _In_bytecount_(InformationBufferLength) const void *InformationBuffer, _In_ UINT InformationBufferLength, _Out_ UINT *BytesRead, _Out_ UINT *BytesNeeded) +{ + *BytesRead = 0; + *BytesNeeded = 0; + + switch (Oid) { + case OID_GEN_CURRENT_PACKET_FILTER: + case OID_GEN_CURRENT_LOOKAHEAD: + if (InformationBufferLength != 4) { + *BytesNeeded = 4; + return NDIS_STATUS_INVALID_LENGTH; + } + *BytesRead = 4; + return NDIS_STATUS_SUCCESS; + + case OID_GEN_LINK_PARAMETERS: + *BytesRead = InformationBufferLength; + return NDIS_STATUS_SUCCESS; + + case OID_GEN_INTERRUPT_MODERATION: + return NDIS_STATUS_INVALID_DATA; + + case OID_PNP_SET_POWER: + if (InformationBufferLength != sizeof(NDIS_DEVICE_POWER_STATE)) { + *BytesNeeded = sizeof(NDIS_DEVICE_POWER_STATE); + return NDIS_STATUS_INVALID_LENGTH; + } + *BytesRead = sizeof(NDIS_DEVICE_POWER_STATE); + ctx->PowerState = *((NDIS_DEVICE_POWER_STATE *)InformationBuffer); + return NDIS_STATUS_SUCCESS; + } + + return NDIS_STATUS_INVALID_OID; +} + +_IRQL_requires_max_(APC_LEVEL) +_IRQL_requires_same_ +static NDIS_STATUS TunOidQuery(_Inout_ TUN_CTX *ctx, _In_ NDIS_OID Oid, _Out_bytecap_post_bytecount_(InformationBufferLength, *BytesWritten) void *InformationBuffer, _In_ UINT InformationBufferLength, _Out_ UINT *BytesWritten, _Out_ UINT *BytesNeeded) +{ + UINT value32; + UINT size = sizeof(value32); + const void *buf = &value32; + + switch (Oid) { + case OID_GEN_MAXIMUM_TOTAL_SIZE: + case OID_GEN_TRANSMIT_BLOCK_SIZE: + case OID_GEN_RECEIVE_BLOCK_SIZE: + value32 = TUN_EXCH_MAX_IP_PACKET_SIZE; + break; + + case OID_GEN_TRANSMIT_BUFFER_SPACE: + case OID_GEN_RECEIVE_BUFFER_SPACE: + value32 = TUN_EXCH_MAX_IP_PACKET_SIZE * TUN_EXCH_MAX_PACKETS; + break; + + case OID_GEN_VENDOR_ID: + value32 = TunHtonl(TUN_VENDOR_ID); + break; + + case OID_GEN_VENDOR_DESCRIPTION: + size = (UINT)sizeof(TUN_VENDOR_NAME); + buf = TUN_VENDOR_NAME; + break; + + case OID_GEN_VENDOR_DRIVER_VERSION: + value32 = (WINTUN_VERSION_MAJ << 16) | WINTUN_VERSION_MIN; + break; + + case OID_GEN_XMIT_OK: + value32 = (UINT)( + InterlockedGet64((LONG64 *)&ctx->Statistics.ifHCOutUcastPkts ) + + InterlockedGet64((LONG64 *)&ctx->Statistics.ifHCOutMulticastPkts) + + InterlockedGet64((LONG64 *)&ctx->Statistics.ifHCOutBroadcastPkts)); + break; + + case OID_GEN_RCV_OK: + value32 = (UINT)( + InterlockedGet64((LONG64 *)&ctx->Statistics.ifHCInUcastPkts ) + + InterlockedGet64((LONG64 *)&ctx->Statistics.ifHCInMulticastPkts) + + InterlockedGet64((LONG64 *)&ctx->Statistics.ifHCInBroadcastPkts)); + break; + + case OID_GEN_STATISTICS: + size = (UINT)sizeof(ctx->Statistics); + buf = &ctx->Statistics; + break; + + case OID_GEN_INTERRUPT_MODERATION: { + static const NDIS_INTERRUPT_MODERATION_PARAMETERS intp = { + .Header = { + .Type = NDIS_OBJECT_TYPE_DEFAULT, + .Revision = NDIS_INTERRUPT_MODERATION_PARAMETERS_REVISION_1, + .Size = NDIS_SIZEOF_INTERRUPT_MODERATION_PARAMETERS_REVISION_1 + }, + .InterruptModeration = NdisInterruptModerationNotSupported + }; + size = (UINT)sizeof(intp); + buf = &intp; + break; + } + + case OID_PNP_QUERY_POWER: + size = 0; + break; + + default: + *BytesWritten = 0; + return NDIS_STATUS_INVALID_OID; + } + + if (size > InformationBufferLength) { + *BytesNeeded = size; + *BytesWritten = 0; + return NDIS_STATUS_INVALID_LENGTH; + } + + NdisMoveMemory(InformationBuffer, buf, size); + *BytesNeeded = *BytesWritten = size; + + return NDIS_STATUS_SUCCESS; +} + +static MINIPORT_OID_REQUEST TunOidRequest; +_Use_decl_annotations_ +static NDIS_STATUS TunOidRequest(NDIS_HANDLE MiniportAdapterContext, PNDIS_OID_REQUEST OidRequest) +{ + switch (OidRequest->RequestType) { + case NdisRequestQueryInformation: + case NdisRequestQueryStatistics: + return TunOidQuery(MiniportAdapterContext, OidRequest->DATA.QUERY_INFORMATION.Oid, OidRequest->DATA.QUERY_INFORMATION.InformationBuffer, OidRequest->DATA.QUERY_INFORMATION.InformationBufferLength, &OidRequest->DATA.QUERY_INFORMATION.BytesWritten, &OidRequest->DATA.QUERY_INFORMATION.BytesNeeded); + + case NdisRequestSetInformation: + return TunOidSet(MiniportAdapterContext, OidRequest->DATA.SET_INFORMATION.Oid, OidRequest->DATA.SET_INFORMATION.InformationBuffer, OidRequest->DATA.SET_INFORMATION.InformationBufferLength, &OidRequest->DATA.SET_INFORMATION.BytesRead, &OidRequest->DATA.SET_INFORMATION.BytesNeeded); + + default: + return NDIS_STATUS_NOT_SUPPORTED; + } +} + +static MINIPORT_DIRECT_OID_REQUEST TunDirectOidRequest; +_Use_decl_annotations_ +static NDIS_STATUS TunDirectOidRequest(NDIS_HANDLE MiniportAdapterContext, PNDIS_OID_REQUEST OidRequest) +{ + switch (OidRequest->RequestType) { + case NdisRequestQueryInformation: + case NdisRequestQueryStatistics: + case NdisRequestSetInformation: + return NDIS_STATUS_INVALID_OID; + + default: + return NDIS_STATUS_NOT_SUPPORTED; + } +} + +static MINIPORT_SEND_NET_BUFFER_LISTS TunSendNetBufferLists; +_Use_decl_annotations_ +static void TunSendNetBufferLists(NDIS_HANDLE MiniportAdapterContext, NET_BUFFER_LIST *NetBufferLists, NDIS_PORT_NUMBER PortNumber, ULONG SendFlags) +{ + TUN_CTX *ctx = (TUN_CTX *)MiniportAdapterContext; + ULONG nbl_count; + + InterlockedIncrement64(&ctx->ActiveNBLCount); + + NDIS_STATUS status; + if ((status = NDIS_STATUS_PAUSED, InterlockedGet((LONG *)&ctx->State) != TUN_STATE_RUNNING) || + (status = NDIS_STATUS_LOW_POWER_STATE, ctx->PowerState >= NdisDeviceStateD1)) { + TunSetNBLStatus(NetBufferLists, status); + goto cleanup_NdisMSendNetBufferListsComplete; + } + + /* Append NBL(s) to the queue. */ + NdisAcquireSpinLock(&ctx->PacketQueue.Lock); + if (ctx->PacketQueue.Tail) + NET_BUFFER_LIST_NEXT_NBL(ctx->PacketQueue.Tail) = NetBufferLists; + else { + ctx->PacketQueue.Head = NetBufferLists; + ctx->PacketQueue.Buffer = NET_BUFFER_LIST_FIRST_NB(NetBufferLists); + } + for (nbl_count = 0; NetBufferLists; NetBufferLists = NET_BUFFER_LIST_NEXT_NBL(NetBufferLists), nbl_count++) + ctx->PacketQueue.Tail = NetBufferLists; + ctx->PacketQueue.Count += nbl_count; + NdisReleaseSpinLock(&ctx->PacketQueue.Lock); + InterlockedAdd64(&ctx->ActiveNBLCount, nbl_count); + + IRP *Irp = InterlockedExchangePointer((PVOID volatile *)&ctx->Device.ActiveIrp, NULL); + if (Irp) + TunProcessPacketQueue(ctx, Irp); + + /* Prevent accumulation of NBLs by keeping only TUN_QUEUE_MAX_NBLS most recent ones. */ + NdisAcquireSpinLock(&ctx->PacketQueue.Lock); + for (nbl_count = 0; ctx->PacketQueue.Count > TUN_QUEUE_MAX_NBLS; ctx->PacketQueue.Count--, nbl_count++) { + _Analysis_assume_(ctx->PacketQueue.Head); /* ctx->PacketQueue.Count > 0 => ctx->PacketQueue.Head != NULL. */ + NET_BUFFER_LIST *nbl = ctx->PacketQueue.Head; + ctx->PacketQueue.Head = NET_BUFFER_LIST_NEXT_NBL(ctx->PacketQueue.Head); + NET_BUFFER_LIST_NEXT_NBL(nbl) = NetBufferLists; + NetBufferLists = nbl; + } + NdisReleaseSpinLock(&ctx->PacketQueue.Lock); + InterlockedSubtract64(&ctx->ActiveNBLCount, nbl_count); + +cleanup_NdisMSendNetBufferListsComplete: + if (NetBufferLists) + NdisMSendNetBufferListsComplete(ctx->MiniportAdapterHandle, NetBufferLists, SendFlags & NDIS_SEND_FLAGS_DISPATCH_LEVEL ? NDIS_SEND_COMPLETE_FLAGS_DISPATCH_LEVEL : 0); + + TunCompletePausing(ctx, 1); +} + +DRIVER_INITIALIZE DriverEntry; +_Use_decl_annotations_ +NTSTATUS DriverEntry(DRIVER_OBJECT *DriverObject, UNICODE_STRING *RegistryPath) +{ + NDIS_MINIPORT_DRIVER_CHARACTERISTICS miniport = { + .Header = { + .Type = NDIS_OBJECT_TYPE_MINIPORT_DRIVER_CHARACTERISTICS, + .Revision = NDIS_MINIPORT_DRIVER_CHARACTERISTICS_REVISION_2, + .Size = NDIS_SIZEOF_MINIPORT_DRIVER_CHARACTERISTICS_REVISION_2 + }, + + .MajorNdisVersion = NDIS_MINIPORT_MAJOR_VERSION, + .MinorNdisVersion = NDIS_MINIPORT_MINOR_VERSION, + + .MajorDriverVersion = WINTUN_VERSION_MAJ, + .MinorDriverVersion = WINTUN_VERSION_MIN, + + .SetOptionsHandler = TunSetOptions, + .InitializeHandlerEx = TunInitializeEx, + .HaltHandlerEx = TunHaltEx, + .UnloadHandler = TunDriverUnload, + .PauseHandler = TunPause, + .RestartHandler = TunRestart, + .OidRequestHandler = TunOidRequest, + .SendNetBufferListsHandler = TunSendNetBufferLists, + .ReturnNetBufferListsHandler = TunReturnNetBufferLists, + .CancelSendHandler = TunCancelSend, + .DevicePnPEventNotifyHandler = TunDevicePnPEventNotify, + .ShutdownHandlerEx = TunShutdownEx, + .CancelOidRequestHandler = TunCancelOidRequest, + .DirectOidRequestHandler = TunDirectOidRequest, + .CancelDirectOidRequestHandler = TunCancelDirectOidRequest + }; + NTSTATUS status = NdisMRegisterMiniportDriver(DriverObject, RegistryPath, NULL, &miniport, &NdisMiniportDriverHandle); + if (status != STATUS_SUCCESS) + return status; + + DriverObject->DriverStartIo = TunStartIo; + return STATUS_SUCCESS; +} diff --git a/wintun.inf b/wintun.inf new file mode 100644 index 0000000..090878b --- /dev/null +++ b/wintun.inf @@ -0,0 +1,66 @@ +; SPDX-License-Identifier: GPL-2.0 +; +; Copyright (C) 2018-2019 WireGuard LLC. All Rights Reserved. + +[Version] +Signature = "$Windows NT$" +Class = Net +ClassGUID = {4D36E972-E325-11CE-BFC1-08002BE10318} +Provider = %Wintun.CompanyName% +CatalogFile.NT = wintun.cat + +[Manufacturer] +%Wintun.CompanyName% = %Wintun.Name%, NT$ARCH$ + +[SourceDisksNames] +1 = %Wintun.DiskDesc%, "", , + +[SourceDisksFiles] +wintun.sys = 1 + +[DestinationDirs] +DefaultDestDir = 12 +Wintun.CopyFiles.Sys = 12 + +[Wintun.CopyFiles.Sys] +wintun.sys, , , 0x00004002 ; COPYFLG_IN_USE_RENAME | COPYFLG_NOSKIP + +[Wintun.NT$ARCH$] +%Wintun.DeviceDesc% = Wintun.Install, Wintun + +[Wintun.Install] +Characteristics = 0x1 ; NCF_VIRTUAL +AddReg = Wintun.Ndi +CopyFiles = Wintun.CopyFiles.Sys +*IfType = 53 ; IF_TYPE_PROP_VIRTUAL +*MediaType = 19 ; NdisMediumIP +*PhysicalMediaType = 0 ; NdisPhysicalMediumUnspecified +EnableDhcp = 0 ; Disable DHCP + +[Wintun.Install.Services] +AddService = %Wintun.Name%, 2, Wintun.Service, Wintun.EventLog, , %Wintun.Name% + +[Wintun.Ndi] +HKR, , DeviceVxDs, , wintun.sys +HKR, Ndi, Service, 0, Wintun.Name +HKR, Ndi\Interfaces, UpperRange, , "ndis5" +HKR, Ndi\Interfaces, LowerRange, , "nolower" + +[Wintun.Service] +DisplayName = %Wintun.Name% +Description = %Wintun.DeviceDesc% +ServiceType = 1 +StartType = 3 +ErrorControl = 1 +ServiceBinary = %12%\wintun.sys +LoadOrderGroup = NDIS + +[Wintun.EventLog] +HKR, , EventMessageFile, 0x00020000, "%11%\IoLogMsg.dll;%12%\wintun.sys" +HKR, , TypesSupported, 0x00010001, 7 + +[Strings] +Wintun.Name = "Wintun" +Wintun.DiskDesc = "Wintun Driver Install Disk" +Wintun.DeviceDesc = "Wintun Userspace Tunnel" +Wintun.CompanyName = "WireGuard LLC" diff --git a/wintun.rc b/wintun.rc Binary files differnew file mode 100644 index 0000000..f0b6a80 --- /dev/null +++ b/wintun.rc diff --git a/wintun.vcxproj b/wintun.vcxproj new file mode 100644 index 0000000..40ee336 --- /dev/null +++ b/wintun.vcxproj @@ -0,0 +1,183 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup Label="ProjectConfigurations"> + <ProjectConfiguration Include="Debug|Win32"> + <Configuration>Debug</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|x64"> + <Configuration>Debug</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|Win32"> + <Configuration>Release</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|x64"> + <Configuration>Release</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + </ItemGroup> + <PropertyGroup Label="Globals"> + <ProjectGuid>{F7679B65-2FEC-469A-8BAC-B07BF4439422}</ProjectGuid> + <RootNamespace>wintun</RootNamespace> + <WindowsTargetPlatformVersion>$(LatestTargetPlatformVersion)</WindowsTargetPlatformVersion> + <ProjectName>wintun</ProjectName> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> + <TargetVersion>Windows7</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Driver</ConfigurationType> + <DriverType>WDM</DriverType> + <SpectreMitigation>false</SpectreMitigation> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> + <TargetVersion>Windows7</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Driver</ConfigurationType> + <DriverType>WDM</DriverType> + <SpectreMitigation>false</SpectreMitigation> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> + <TargetVersion>Windows7</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Driver</ConfigurationType> + <DriverType>WDM</DriverType> + <SpectreMitigation>false</SpectreMitigation> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> + <TargetVersion>Windows7</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Driver</ConfigurationType> + <DriverType>WDM</DriverType> + <SpectreMitigation>false</SpectreMitigation> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> + <ImportGroup Label="ExtensionSettings"> + </ImportGroup> + <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <PropertyGroup Label="UserMacros"> + <WintunVersionMaj>0</WintunVersionMaj> + <WintunVersionMin>0</WintunVersionMin> + <WintunVersionRev>2019</WintunVersionRev> + <WintunVersionBuild>0128</WintunVersionBuild> + <WintunVersionStr>0.0.20190128</WintunVersionStr> + </PropertyGroup> + <PropertyGroup> + <_ProjectFileVersion>15.0.28127.55</_ProjectFileVersion> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <RunCodeAnalysis>true</RunCodeAnalysis> + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <RunCodeAnalysis>true</RunCodeAnalysis> + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> + </PropertyGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <ClCompile> + <PreprocessorDefinitions>WINTUN_VERSION_MAJ=$(WintunVersionMaj);WINTUN_VERSION_MIN=$(WintunVersionMin);WINTUN_VERSION_REV=$(WintunVersionRev);WINTUN_VERSION_BUILD=$(WintunVersionBuild);WINTUN_VERSION_STR="$(WintunVersionStr)";%(PreprocessorDefinitions)</PreprocessorDefinitions> + <WarningLevel>Level4</WarningLevel> + </ClCompile> + <ResourceCompile> + <PreprocessorDefinitions>WINTUN_VERSION_MAJ=$(WintunVersionMaj);WINTUN_VERSION_MIN=$(WintunVersionMin);WINTUN_VERSION_REV=$(WintunVersionRev);WINTUN_VERSION_BUILD=$(WintunVersionBuild);WINTUN_VERSION_STR="$(WintunVersionStr)";%(PreprocessorDefinitions)</PreprocessorDefinitions> + </ResourceCompile> + <Link> + <AdditionalDependencies>ndis.lib;wdmsec.lib;%(AdditionalDependencies)</AdditionalDependencies> + </Link> + <Inf> + <TimeStamp>$(WintunVersionMaj).$(WintunVersionMin).$(WintunVersionRev).$(WintunVersionBuild)</TimeStamp> + </Inf> + <DriverSign> + <FileDigestAlgorithm>sha256</FileDigestAlgorithm> + </DriverSign> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <ClCompile> + <PreprocessorDefinitions>WINTUN_VERSION_MAJ=$(WintunVersionMaj);WINTUN_VERSION_MIN=$(WintunVersionMin);WINTUN_VERSION_REV=$(WintunVersionRev);WINTUN_VERSION_BUILD=$(WintunVersionBuild);WINTUN_VERSION_STR="$(WintunVersionStr)";%(PreprocessorDefinitions)</PreprocessorDefinitions> + <WarningLevel>Level4</WarningLevel> + <EnablePREfast>true</EnablePREfast> + <Optimization>Disabled</Optimization> + </ClCompile> + <ResourceCompile> + <PreprocessorDefinitions>WINTUN_VERSION_MAJ=$(WintunVersionMaj);WINTUN_VERSION_MIN=$(WintunVersionMin);WINTUN_VERSION_REV=$(WintunVersionRev);WINTUN_VERSION_BUILD=$(WintunVersionBuild);WINTUN_VERSION_STR="$(WintunVersionStr)";%(PreprocessorDefinitions)</PreprocessorDefinitions> + </ResourceCompile> + <Link> + <AdditionalDependencies>ndis.lib;wdmsec.lib;%(AdditionalDependencies)</AdditionalDependencies> + </Link> + <Inf> + <TimeStamp>*</TimeStamp> + </Inf> + <DriverSign> + <FileDigestAlgorithm>sha256</FileDigestAlgorithm> + </DriverSign> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <ClCompile> + <PreprocessorDefinitions>WINTUN_VERSION_MAJ=$(WintunVersionMaj);WINTUN_VERSION_MIN=$(WintunVersionMin);WINTUN_VERSION_REV=$(WintunVersionRev);WINTUN_VERSION_BUILD=$(WintunVersionBuild);WINTUN_VERSION_STR="$(WintunVersionStr)";%(PreprocessorDefinitions)</PreprocessorDefinitions> + <WarningLevel>Level4</WarningLevel> + </ClCompile> + <ResourceCompile> + <PreprocessorDefinitions>WINTUN_VERSION_MAJ=$(WintunVersionMaj);WINTUN_VERSION_MIN=$(WintunVersionMin);WINTUN_VERSION_REV=$(WintunVersionRev);WINTUN_VERSION_BUILD=$(WintunVersionBuild);WINTUN_VERSION_STR="$(WintunVersionStr)";%(PreprocessorDefinitions)</PreprocessorDefinitions> + </ResourceCompile> + <Link> + <AdditionalDependencies>ndis.lib;wdmsec.lib;%(AdditionalDependencies)</AdditionalDependencies> + </Link> + <Inf> + <TimeStamp>$(WintunVersionMaj).$(WintunVersionMin).$(WintunVersionRev).$(WintunVersionBuild)</TimeStamp> + </Inf> + <DriverSign> + <FileDigestAlgorithm>sha256</FileDigestAlgorithm> + </DriverSign> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <ClCompile> + <PreprocessorDefinitions>WINTUN_VERSION_MAJ=$(WintunVersionMaj);WINTUN_VERSION_MIN=$(WintunVersionMin);WINTUN_VERSION_REV=$(WintunVersionRev);WINTUN_VERSION_BUILD=$(WintunVersionBuild);WINTUN_VERSION_STR="$(WintunVersionStr)";%(PreprocessorDefinitions)</PreprocessorDefinitions> + <WarningLevel>Level4</WarningLevel> + <EnablePREfast>true</EnablePREfast> + <Optimization>Disabled</Optimization> + </ClCompile> + <ResourceCompile> + <PreprocessorDefinitions>WINTUN_VERSION_MAJ=$(WintunVersionMaj);WINTUN_VERSION_MIN=$(WintunVersionMin);WINTUN_VERSION_REV=$(WintunVersionRev);WINTUN_VERSION_BUILD=$(WintunVersionBuild);WINTUN_VERSION_STR="$(WintunVersionStr)";%(PreprocessorDefinitions)</PreprocessorDefinitions> + </ResourceCompile> + <Link> + <AdditionalDependencies>ndis.lib;wdmsec.lib;%(AdditionalDependencies)</AdditionalDependencies> + </Link> + <Inf> + <TimeStamp>*</TimeStamp> + </Inf> + <DriverSign> + <FileDigestAlgorithm>sha256</FileDigestAlgorithm> + </DriverSign> + </ItemDefinitionGroup> + <ItemGroup> + <ClCompile Include="wintun.c" /> + </ItemGroup> + <ItemGroup> + <ResourceCompile Include="wintun.rc" /> + </ItemGroup> + <ItemGroup> + <Inf Include="wintun.inf" /> + <FilesToPackage Include="$(TargetPath)" Condition="'$(ConfigurationType)'=='Driver' or '$(ConfigurationType)'=='DynamicLibrary'" /> + </ItemGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> + <ImportGroup Label="ExtensionTargets" /> +</Project>
\ No newline at end of file diff --git a/wintun.vcxproj.filters b/wintun.vcxproj.filters new file mode 100644 index 0000000..7077380 --- /dev/null +++ b/wintun.vcxproj.filters @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup> + <Filter Include="Source Files"> + <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier> + <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions> + </Filter> + <Filter Include="Header Files"> + <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier> + <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions> + </Filter> + <Filter Include="Resource Files"> + <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier> + <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions> + </Filter> + </ItemGroup> + <ItemGroup> + <ClCompile Include="wintun.c"> + <Filter>Source Files</Filter> + </ClCompile> + </ItemGroup> + <ItemGroup> + <ResourceCompile Include="wintun.rc"> + <Filter>Resource Files</Filter> + </ResourceCompile> + </ItemGroup> + <ItemGroup> + <Inf Include="wintun.inf"> + <Filter>Source Files</Filter> + </Inf> + </ItemGroup> +</Project>
\ No newline at end of file |