/
Packet.c
2429 lines (2057 loc) · 73.4 KB
/
Packet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***********************IMPORTANT NPCAP LICENSE TERMS***********************
* *
* Npcap is a Windows packet sniffing driver and library and is copyright *
* (c) 2013-2016 by Insecure.Com LLC ("The Nmap Project"). All rights *
* reserved. *
* *
* Even though Npcap source code is publicly available for review, it is *
* not open source software and may not be redistributed or incorporated *
* into other software without special permission from the Nmap Project. *
* We fund the Npcap project by selling a commercial license which allows *
* companies to redistribute Npcap with their products and also provides *
* for support, warranty, and indemnification rights. For details on *
* obtaining such a license, please contact: *
* *
* sales@nmap.com *
* *
* Free and open source software producers are also welcome to contact us *
* for redistribution requests. However, we normally recommend that such *
* authors instead ask your users to download and install Npcap *
* themselves. *
* *
* Since the Npcap source code is available for download and review, *
* users sometimes contribute code patches to fix bugs or add new *
* features. By sending these changes to the Nmap Project (including *
* through direct email or our mailing lists or submitting pull requests *
* through our source code repository), it is understood unless you *
* specify otherwise that you are offering the Nmap Project the *
* unlimited, non-exclusive right to reuse, modify, and relicence your *
* code contribution so that we may (but are not obligated to) *
* incorporate it into Npcap. If you wish to specify special license *
* conditions or restrictions on your contributions, just say so when you *
* send them. *
* *
* This software 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. *
* *
* Other copyright notices and attribution may appear below this license *
* header. We have kept those for attribution purposes, but any license *
* terms granted by those notices apply only to their original work, and *
* not to any changes made by the Nmap Project or to this entire file. *
* *
* This header summarizes a few important aspects of the Npcap license, *
* but is not a substitute for the full Npcap license agreement, which is *
* in the LICENSE file included with Npcap and also available at *
* https://github.com/nmap/npcap/blob/master/LICENSE. *
* *
***************************************************************************/
/*
* Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)
* Copyright (c) 2005 - 2010 CACE Technologies, Davis (California)
* Copyright (c) 2010 - 2013 Riverbed Technology, San Francisco (California), Yang Luo (China)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Politecnico di Torino, CACE Technologies
* nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "stdafx.h"
#include <ntddk.h>
#include <ndis.h>
#include "Loopback.h"
#include "Lo_send.h"
#include "debug.h"
#include "packet.h"
#include "win_bpf.h"
#include "ioctls.h"
#include "..\..\..\Common\WpcapNames.h"
#ifdef ALLOC_PRAGMA
#pragma NDIS_INIT_FUNCTION(DriverEntry)
#endif // ALLOC_PRAGMA
#if DBG
// Declare the global debug flag for this driver.
ULONG PacketDebugFlag = PACKET_DEBUG_LOUD;
#endif
PDEVICE_EXTENSION GlobalDeviceExtension;
//
// Global strings
//
WCHAR g_NPF_PrefixBuffer[MAX_WINPCAP_KEY_CHARS] = NPF_DEVICE_NAMES_PREFIX_WIDECHAR;
WCHAR g_NPF_PrefixBuffer_Wifi[MAX_WINPCAP_KEY_CHARS] = NPF_DEVICE_NAMES_PREFIX_WIDECHAR_WIFI;
POPEN_INSTANCE g_arrOpen = NULL; //Adapter OPEN_INSTANCE list head, each list item is a group head.
NDIS_SPIN_LOCK g_OpenArrayLock; //The lock for adapter OPEN_INSTANCE list.
#ifdef HAVE_WFP_LOOPBACK_SUPPORT
//
// Global variables used by WFP
//
POPEN_INSTANCE g_LoopbackOpenGroupHead = NULL; // Loopback adapter open_instance group head, this pointer points to one item in g_arrOpen list.
PDEVICE_OBJECT g_LoopbackDevObj = NULL;
NDIS_STRING g_LoopbackAdapterName;
NDIS_STRING g_LoopbackRegValueName = NDIS_STRING_CONST("LoopbackAdapter");
extern HANDLE g_WFPEngineHandle;
#endif
#ifdef HAVE_RX_SUPPORT
NDIS_STRING g_SendToRxAdapterName;
NDIS_STRING g_SendToRxRegValueName = NDIS_STRING_CONST("SendToRxAdapters");
NDIS_STRING g_BlockRxAdapterName;
NDIS_STRING g_BlockRxRegValueName = NDIS_STRING_CONST("BlockRxAdapters");
#endif
NDIS_STRING g_NPF_Prefix;
NDIS_STRING g_NPF_Prefix_WIFI;
NDIS_STRING devicePrefix = NDIS_STRING_CONST("\\Device\\");
NDIS_STRING symbolicLinkPrefix = NDIS_STRING_CONST("\\DosDevices\\");
NDIS_STRING tcpLinkageKeyName = NDIS_STRING_CONST("\\Registry\\Machine\\System"
L"\\CurrentControlSet\\Services\\Tcpip\\Linkage");
NDIS_STRING AdapterListKey = NDIS_STRING_CONST("\\Registry\\Machine\\System"
L"\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}");
NDIS_STRING bindValueName = NDIS_STRING_CONST("Bind");
NDIS_STRING g_AdminOnlyRegValueName = NDIS_STRING_CONST("AdminOnly");
NDIS_STRING g_DltNullRegValueName = NDIS_STRING_CONST("DltNull");
NDIS_STRING g_Dot11SupportRegValueName = NDIS_STRING_CONST("Dot11Support");
NDIS_STRING g_VlanSupportRegValueName = NDIS_STRING_CONST("VlanSupport");
NDIS_STRING g_TimestampRegValueName = NDIS_STRING_CONST("TimestampMode");
ULONG g_AdminOnlyMode = 0;
ULONG g_DltNullMode = 0;
ULONG g_Dot11SupportMode = 0;
ULONG g_VlanSupportMode = 0;
ULONG g_TimestampMode = 0;
/// Global variable that points to the names of the bound adapters
WCHAR* bindP = NULL;
ULONG g_NCpu;
//
// Global variables
//
NDIS_HANDLE FilterDriverHandle = NULL; // NDIS handle for filter driver
NDIS_HANDLE FilterDriverHandle_WiFi = NULL; // NDIS handle for WiFi filter driver
NDIS_HANDLE FilterDriverObject; // Driver object for filter driver
NDIS_EVENT evtFilterDetached; // Signal that a filter module has detached
typedef ULONG (*NDISGROUPMAXPROCESSORCOUNT)(
USHORT Group
);
//KeGetCurrentProcessorNumberEx
typedef ULONG (*KEGETCURRENTPROCESSORNUMBEREX)(
PPROCESSOR_NUMBER ProcNumber
);
NDISGROUPMAXPROCESSORCOUNT g_My_NdisGroupMaxProcessorCount = NULL;
KEGETCURRENTPROCESSORNUMBEREX g_My_KeGetCurrentProcessorNumberEx = NULL;
//-------------------------------------------------------------------
ULONG
My_NdisGroupMaxProcessorCount(
)
{
ULONG Cpu;
if (g_My_NdisGroupMaxProcessorCount) // for NDIS620 and later (Win7 and later).
{
Cpu = g_My_NdisGroupMaxProcessorCount(ALL_PROCESSOR_GROUPS);
if (Cpu > NPF_MAX_CPU_NUMBER - 1)
{
Cpu = NPF_MAX_CPU_NUMBER - 1;
}
}
else // for NDIS6 (Vista)
{
Cpu = NdisSystemProcessorCount();
}
return Cpu;
}
//-------------------------------------------------------------------
ULONG
My_KeGetCurrentProcessorNumber(
)
{
ULONG Cpu;
if (g_My_KeGetCurrentProcessorNumberEx) // for NDIS620 and later (Win7 and later).
{
Cpu = g_My_KeGetCurrentProcessorNumberEx(NULL);
if (Cpu > NPF_MAX_CPU_NUMBER - 1)
{
Cpu = NPF_MAX_CPU_NUMBER - 1;
}
}
else // for NDIS6 (Vista)
{
Cpu = KeGetCurrentProcessorNumber();
}
return Cpu;
}
//-------------------------------------------------------------------
//
// Packet Driver's entry routine.
//
_Use_decl_annotations_
NTSTATUS
DriverEntry(
IN PDRIVER_OBJECT DriverObject,
IN PUNICODE_STRING RegistryPath
)
{
NDIS_FILTER_DRIVER_CHARACTERISTICS FChars; // The specification for the filter.
NDIS_FILTER_DRIVER_CHARACTERISTICS FChars_WiFi; // The specification for the WiFi filter.
UNICODE_STRING parametersPath;
NTSTATUS Status = STATUS_SUCCESS;
// Use NonPaged Pool instead of No-Execute (NX) Nonpaged Pool for Win8 and later, this is for security purpose.
ExInitializeDriverRuntime(DrvRtPoolNxOptIn);
WCHAR* bindT;
PKEY_VALUE_PARTIAL_INFORMATION tcpBindingsP;
UNICODE_STRING AdapterName;
ULONG OsMajorVersion, OsMinorVersion;
NDIS_STRING strNdisGroupMaxProcessorCount;
NDIS_STRING strKeGetCurrentProcessorNumberEx;
NDIS_STRING strKeGetProcessorIndexFromNumber;
UNREFERENCED_PARAMETER(RegistryPath);
TRACE_ENTER();
FilterDriverObject = DriverObject;
PsGetVersion(&OsMajorVersion, &OsMinorVersion, NULL, NULL);
TRACE_MESSAGE2(PACKET_DEBUG_LOUD, "OS Version: %d.%d\n", OsMajorVersion, OsMinorVersion);
RtlInitUnicodeString(¶metersPath, NULL);
parametersPath.MaximumLength=RegistryPath->Length+wcslen(L"\\Parameters")*sizeof(WCHAR)+sizeof(UNICODE_NULL);
parametersPath.Buffer=ExAllocatePoolWithTag(PagedPool, parametersPath.MaximumLength, '4PWA');
if (!parametersPath.Buffer) {
return STATUS_INSUFFICIENT_RESOURCES;
}
RtlZeroMemory(parametersPath.Buffer, parametersPath.MaximumLength);
RtlCopyUnicodeString(¶metersPath, RegistryPath);
RtlAppendUnicodeToString(¶metersPath, L"\\Parameters");
Status = RtlCheckRegistryKey(RTL_REGISTRY_ABSOLUTE,
parametersPath.Buffer);
if (NT_SUCCESS(Status)) {
// Get the AdminOnly option, if AdminOnly=1, devices will be created with the safe SDDL, to make sure only Administrators can use Npcap driver.
// If the registry key doesn't exist, we view it as AdminOnly=0, so no protect to the driver access.
g_AdminOnlyMode = NPF_GetRegistryOption_Integer(¶metersPath, &g_AdminOnlyRegValueName);
// Get the DltNull option, if DltNull=1, loopback traffic will be DLT_NULL/DLT_LOOP style, including captured and sent packets.
// If the registry key doesn't exist, we view it as DltNull=0, so loopback traffic are Ethernet packets.
g_DltNullMode = NPF_GetRegistryOption_Integer(¶metersPath, &g_DltNullRegValueName);
// Get the Dot11Support option, if Dot11Support=1, Npcap driver will enable the raw 802.11 functions.
// If the registry key doesn't exist, we view it as Dot11Support=1, so has raw 802.11 support.
g_Dot11SupportMode = NPF_GetRegistryOption_Integer(¶metersPath, &g_Dot11SupportRegValueName);
// Get the VlanSupport option, if VlanSupport=1, Npcap driver will try to recognize 802.1Q VLAN tag when capturing and sending data.
// If the registry key doesn't exist, we view it as VlanSupport=0, so no VLAN support.
g_VlanSupportMode = NPF_GetRegistryOption_Integer(¶metersPath, &g_VlanSupportRegValueName);
// Get the TimestampMode option. The meanings of its values is described in time_calls.h.
// If the registry key doesn't exist, we view it as TimestampMode=0, so the default "QueryPerformanceCounter" timestamp gathering method.
g_TimestampMode = NPF_GetRegistryOption_Integer(¶metersPath, &g_TimestampRegValueName);
#ifdef HAVE_WFP_LOOPBACK_SUPPORT
NPF_GetRegistryOption_String(¶metersPath, &g_LoopbackRegValueName, &g_LoopbackAdapterName);
if (g_LoopbackAdapterName.Buffer != NULL && g_LoopbackAdapterName.Length != ADAPTER_NAME_SIZE * 2)
{
TRACE_MESSAGE2(PACKET_DEBUG_LOUD, "g_LoopbackAdapterName is invalid, g_LoopbackAdapterName.Length = %d, ADAPTER_NAME_SIZE * 2 = %d\n",
g_LoopbackAdapterName.Length, ADAPTER_NAME_SIZE * 2);
ExFreePool(g_LoopbackAdapterName.Buffer);
g_LoopbackAdapterName.Buffer = NULL;
g_LoopbackAdapterName.Length = 0;
g_LoopbackAdapterName.MaximumLength = 0;
}
#endif
#ifdef HAVE_RX_SUPPORT
NPF_GetRegistryOption_String(¶metersPath, &g_SendToRxRegValueName, &g_SendToRxAdapterName);
NPF_GetRegistryOption_String(¶metersPath, &g_BlockRxRegValueName, &g_BlockRxAdapterName);
#endif
}
if (parametersPath.Buffer) ExFreePool(parametersPath.Buffer);
// RegistryPath = "\REGISTRY\MACHINE\SYSTEM\ControlSet001\Services\npcap" for standard driver
// RegistryPath = "\REGISTRY\MACHINE\SYSTEM\ControlSet001\Services\npcap_wifi" for WiFi driver
//
// The Dot11 support is determined by whether the service is "npcap" or "npcap_wifi"
//
// g_Dot11SupportMode = 0;
// for (USHORT i = 0; i < RegistryPath->Length / 2; i ++)
// {
// if (RegistryPath->Buffer[i] == L'_')
// {
// g_Dot11SupportMode = 1;
// break;
// }
// }
// TRACE_MESSAGE1(PACKET_DEBUG_LOUD, "g_Dot11SupportMode (based on RegistryPath) = %d\n", g_Dot11SupportMode);
// g_NPF_PrefixBuffer = "NPCAP_"
NdisInitUnicodeString(&g_NPF_Prefix, g_NPF_PrefixBuffer);
// g_NPF_PrefixBuffer_Wifi = "NPCAP_WIFI_"
if (g_Dot11SupportMode)
NdisInitUnicodeString(&g_NPF_Prefix_WIFI, g_NPF_PrefixBuffer_Wifi);
//
// Initialize several CPU-related functions.
//
RtlInitUnicodeString(&strNdisGroupMaxProcessorCount, L"NdisGroupMaxProcessorCount");
g_My_NdisGroupMaxProcessorCount = (NDISGROUPMAXPROCESSORCOUNT) NdisGetRoutineAddress(&strNdisGroupMaxProcessorCount);
RtlInitUnicodeString(&strKeGetCurrentProcessorNumberEx, L"KeGetCurrentProcessorNumberEx");
g_My_KeGetCurrentProcessorNumberEx = (KEGETCURRENTPROCESSORNUMBEREX) NdisGetRoutineAddress(&strKeGetCurrentProcessorNumberEx);
//
// Get number of CPUs and save it
//
g_NCpu = My_NdisGroupMaxProcessorCount();
TRACE_MESSAGE3(PACKET_DEBUG_LOUD, "g_NCpu: %d, NPF_MAX_CPU_NUMBER: %d, g_My_NdisGroupMaxProcessorCount: %x\n", g_NCpu, NPF_MAX_CPU_NUMBER, g_My_NdisGroupMaxProcessorCount);
//
// Register as a service with NDIS
//
NPF_registerLWF(&FChars, FALSE);
if (g_Dot11SupportMode)
NPF_registerLWF(&FChars_WiFi, TRUE);
DriverObject->DriverUnload = NPF_Unload;
//
// Standard device driver entry points stuff.
//
DriverObject->MajorFunction[IRP_MJ_CREATE] = NPF_OpenAdapter;
DriverObject->MajorFunction[IRP_MJ_CLOSE] = NPF_CloseAdapter;
DriverObject->MajorFunction[IRP_MJ_CLEANUP] = NPF_Cleanup;
DriverObject->MajorFunction[IRP_MJ_READ] = NPF_Read;
DriverObject->MajorFunction[IRP_MJ_WRITE] = NPF_Write;
DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = NPF_IoControl;
bindP = getAdaptersList();
if (bindP == NULL)
{
TRACE_MESSAGE(PACKET_DEBUG_LOUD, "Adapters not found in the registry, try to copy the bindings of TCP-IP.");
tcpBindingsP = getTcpBindings();
if (tcpBindingsP == NULL)
{
TRACE_MESSAGE(PACKET_DEBUG_LOUD, "TCP-IP not found, quitting.");
goto RegistryError;
}
bindP = (WCHAR *)tcpBindingsP;
bindT = (WCHAR *)(tcpBindingsP->Data);
}
else
{
bindT = bindP;
}
for (; *bindT != UNICODE_NULL; bindT += (AdapterName.Length + sizeof(UNICODE_NULL)) / sizeof(WCHAR))
{
RtlInitUnicodeString(&AdapterName, bindT);
NPF_CreateDevice(DriverObject, &AdapterName, &g_NPF_Prefix, FALSE);
if (g_Dot11SupportMode)
NPF_CreateDevice(DriverObject, &AdapterName, &g_NPF_Prefix_WIFI, TRUE);
}
// Register the filter to NDIS.
Status = NdisFRegisterFilterDriver(DriverObject,
(NDIS_HANDLE) FilterDriverObject,
&FChars,
&FilterDriverHandle);
if (Status != NDIS_STATUS_SUCCESS)
{
TRACE_MESSAGE1(PACKET_DEBUG_LOUD, "NdisFRegisterFilterDriver: failed to register filter with NDIS, Status = %x", Status);
TRACE_EXIT();
return Status;
}
else
{
TRACE_MESSAGE2(PACKET_DEBUG_LOUD, "NdisFRegisterFilterDriver: succeed to register filter with NDIS, Status = %x, FilterDriverHandle = %p", Status, FilterDriverHandle);
}
if (g_Dot11SupportMode)
{
// Register the WiFi filter to NDIS.
Status = NdisFRegisterFilterDriver(DriverObject,
(NDIS_HANDLE)FilterDriverObject,
&FChars_WiFi,
&FilterDriverHandle_WiFi);
if (Status != NDIS_STATUS_SUCCESS)
{
TRACE_MESSAGE1(PACKET_DEBUG_LOUD, "NdisFRegisterFilterDriver: failed to register filter (WiFi) with NDIS, Status = %x", Status);
// We still run the driver even with the 2nd filter doesn't work.
TRACE_MESSAGE1(PACKET_DEBUG_LOUD, "We only use the 1st Filter Handle now, FilterDriverHandle_WiFi = %p.", FilterDriverHandle_WiFi);
// NdisFDeregisterFilterDriver(FilterDriverHandle);
// TRACE_MESSAGE1(PACKET_DEBUG_LOUD, "Deleting the 1st Filter Handle = %p", FilterDriverHandle);
// TRACE_EXIT();
// return Status;
}
else
{
TRACE_MESSAGE2(PACKET_DEBUG_LOUD, "NdisFRegisterFilterDriver: succeed to register filter (WiFi) with NDIS, Status = %x, FilterDriverHandle_WiFi = %p", Status, FilterDriverHandle_WiFi);
}
}
#ifdef HAVE_WFP_LOOPBACK_SUPPORT
// Use Winsock Kernel (WSK) to send loopback packets.
Status = NPF_WSKStartup();
if (!NT_SUCCESS(Status))
{
TRACE_EXIT();
return Status;
}
Status = NPF_WSKInitSockets();
if (!NT_SUCCESS(Status))
{
TRACE_EXIT();
return Status;
}
#endif
NdisAllocateSpinLock(&g_OpenArrayLock);
NdisInitializeEvent(&evtFilterDetached);
TRACE_EXIT();
return STATUS_SUCCESS;
RegistryError:
Status = STATUS_UNSUCCESSFUL;
TRACE_EXIT();
return(Status);
}
//-------------------------------------------------------------------
VOID
NPF_registerLWF(
PNDIS_FILTER_DRIVER_CHARACTERISTICS pFChars,
BOOLEAN bWiFiOrNot
)
{
NDIS_STRING FriendlyName = RTL_CONSTANT_STRING(NPF_SERVICE_DESC_WIDECHAR); // display name
NDIS_STRING UniqueName = RTL_CONSTANT_STRING(FILTER_UNIQUE_NAME); // unique name, quid name
NDIS_STRING ServiceName = RTL_CONSTANT_STRING(NPF_DRIVER_NAME_SMALL_WIDECHAR); // this to match the service name in the INF
NDIS_STRING FriendlyName_WiFi = RTL_CONSTANT_STRING(NPF_SERVICE_DESC_WIDECHAR_WIFI); // display name
NDIS_STRING UniqueName_WiFi = RTL_CONSTANT_STRING(FILTER_UNIQUE_NAME_WIFI); // unique name, quid name
NDIS_STRING ServiceName_WiFi = RTL_CONSTANT_STRING(NPF_DRIVER_NAME_SMALL_WIDECHAR_WIFI); // this to match the service name in the INF
NdisZeroMemory(pFChars, sizeof(NDIS_FILTER_DRIVER_CHARACTERISTICS));
pFChars->Header.Type = NDIS_OBJECT_TYPE_FILTER_DRIVER_CHARACTERISTICS;
pFChars->Header.Size = sizeof(NDIS_FILTER_DRIVER_CHARACTERISTICS);
#if NDIS_SUPPORT_NDIS61
pFChars->Header.Revision = NDIS_FILTER_CHARACTERISTICS_REVISION_2;
#else
pFChars->Header.Revision = NDIS_FILTER_CHARACTERISTICS_REVISION_1;
#endif
pFChars->MajorNdisVersion = NDIS_FILTER_MAJOR_VERSION; // NDIS version is 6.2 (Windows 7)
pFChars->MinorNdisVersion = NDIS_FILTER_MINOR_VERSION;
pFChars->MajorDriverVersion = 1; // Driver version is 1.0
pFChars->MinorDriverVersion = 0;
pFChars->Flags = 0;
// Use different names for the WiFi driver.
if (bWiFiOrNot)
{
pFChars->FriendlyName = FriendlyName_WiFi;
pFChars->UniqueName = UniqueName_WiFi;
pFChars->ServiceName = ServiceName_WiFi;
}
else
{
pFChars->FriendlyName = FriendlyName;
pFChars->UniqueName = UniqueName;
pFChars->ServiceName = ServiceName;
}
pFChars->SetOptionsHandler = NPF_RegisterOptions;
pFChars->AttachHandler = NPF_AttachAdapter;
pFChars->DetachHandler = NPF_DetachAdapter;
pFChars->RestartHandler = NPF_Restart;
pFChars->PauseHandler = NPF_Pause;
pFChars->SetFilterModuleOptionsHandler = NPF_SetModuleOptions;
pFChars->OidRequestHandler = NPF_OidRequest;
pFChars->OidRequestCompleteHandler = NPF_OidRequestComplete;
pFChars->CancelOidRequestHandler = NPF_CancelOidRequest;
pFChars->SendNetBufferListsHandler = NPF_SendEx;
pFChars->ReturnNetBufferListsHandler = NPF_ReturnEx;
pFChars->SendNetBufferListsCompleteHandler = NPF_SendCompleteEx;
pFChars->ReceiveNetBufferListsHandler = NPF_TapEx;
pFChars->DevicePnPEventNotifyHandler = NPF_DevicePnPEventNotify;
pFChars->NetPnPEventHandler = NPF_NetPnPEvent;
pFChars->StatusHandler = NPF_Status;
pFChars->CancelSendNetBufferListsHandler = NPF_CancelSendNetBufferLists;
}
//-------------------------------------------------------------------
PWCHAR
getAdaptersList(
)
{
PKEY_VALUE_PARTIAL_INFORMATION result = NULL;
OBJECT_ATTRIBUTES objAttrs;
NTSTATUS status;
HANDLE keyHandle;
UINT BufPos = 0;
UINT BufLen = 4096;
PWCHAR DeviceNames = (PWCHAR)ExAllocatePoolWithTag(NonPagedPool, BufLen, '0PWA');
TRACE_ENTER();
if (DeviceNames == NULL)
{
IF_LOUD(DbgPrint("Unable the allocate the buffer for the list of the network adapters\n");)
TRACE_EXIT();
return NULL;
}
InitializeObjectAttributes(&objAttrs, &AdapterListKey, OBJ_CASE_INSENSITIVE, NULL, NULL);
status = ZwOpenKey(&keyHandle, KEY_READ, &objAttrs);
if (!NT_SUCCESS(status))
{
IF_LOUD(DbgPrint("\n\nStatus of %x opening %ws\n", status, tcpLinkageKeyName.Buffer);)
}
else //OK
{
ULONG resultLength;
KEY_VALUE_PARTIAL_INFORMATION valueInfo;
CHAR AdapInfo[1024];
UINT i = 0;
IF_LOUD(DbgPrint("getAdaptersList: scanning the list of the adapters in the registry, DeviceNames=%p\n", DeviceNames);)
// Scan the list of the devices
while((status = ZwEnumerateKey(keyHandle, i, KeyBasicInformation, AdapInfo, sizeof(AdapInfo), &resultLength)) == STATUS_SUCCESS)
{
WCHAR ExportKeyName[512];
PWCHAR ExportKeyPrefix = L"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\";
UINT ExportKeyPrefixSize = sizeof(L"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}");
PWCHAR LinkageKeyPrefix = L"\\Linkage";
UINT LinkageKeyPrefixSize = sizeof(L"\\Linkage");
NDIS_STRING FinalExportKey = NDIS_STRING_CONST("Export");
PKEY_BASIC_INFORMATION tInfo = (PKEY_BASIC_INFORMATION)AdapInfo;
UNICODE_STRING AdapterKeyName;
HANDLE ExportKeyHandle;
RtlCopyMemory(ExportKeyName, ExportKeyPrefix, ExportKeyPrefixSize);
RtlCopyMemory((PCHAR)ExportKeyName + ExportKeyPrefixSize, tInfo->Name, tInfo->NameLength + 2);
RtlCopyMemory((PCHAR)ExportKeyName + ExportKeyPrefixSize + tInfo->NameLength, LinkageKeyPrefix, LinkageKeyPrefixSize);
IF_LOUD(DbgPrint("Key name=%ws\n", ExportKeyName);)
RtlInitUnicodeString(&AdapterKeyName, ExportKeyName);
InitializeObjectAttributes(&objAttrs, &AdapterKeyName, OBJ_CASE_INSENSITIVE, NULL, NULL);
status = ZwOpenKey(&ExportKeyHandle, KEY_READ, &objAttrs);
if (!NT_SUCCESS(status))
{
IF_LOUD(DbgPrint("OpenKey Failed, %d!\n", status);)
i++;
continue;
}
status = ZwQueryValueKey(ExportKeyHandle,
&FinalExportKey,
KeyValuePartialInformation,
&valueInfo,
sizeof(valueInfo),
&resultLength);
if (!NT_SUCCESS(status) && (status != STATUS_BUFFER_OVERFLOW))
{
IF_LOUD(DbgPrint("\n\nStatus of %x querying key value for size\n", status);)
}
else
{
// We know how big it needs to be.
ULONG valueInfoLength = valueInfo.DataLength + FIELD_OFFSET(KEY_VALUE_PARTIAL_INFORMATION, Data[0]);
PKEY_VALUE_PARTIAL_INFORMATION valueInfoP = (PKEY_VALUE_PARTIAL_INFORMATION)ExAllocatePoolWithTag(NonPagedPool, valueInfoLength, '1PWA');
if (valueInfoP != NULL)
{
status = ZwQueryValueKey(ExportKeyHandle,
&FinalExportKey,
KeyValuePartialInformation,
valueInfoP,
valueInfoLength,
&resultLength);
if (!NT_SUCCESS(status))
{
IF_LOUD(DbgPrint("Status of %x querying key value\n", status);)
}
else
{
IF_LOUD(DbgPrint("Device %d = %ws\n", i, valueInfoP->Data);)
if(BufPos + valueInfoP->DataLength > BufLen)
{
// double the buffer size
PWCHAR DeviceNames2 = (PWCHAR)ExAllocatePoolWithTag(NonPagedPool, BufLen << 1, '0PWA');
if (DeviceNames2)
{
RtlCopyMemory((PCHAR)DeviceNames2, (PCHAR)DeviceNames, BufLen);
BufLen <<= 1;
ExFreePool(DeviceNames);
DeviceNames = DeviceNames2;
}
}
if (BufPos + valueInfoP->DataLength < BufLen)
{
RtlCopyMemory((PCHAR)DeviceNames + BufPos,
valueInfoP->Data,
valueInfoP->DataLength);
BufPos += valueInfoP->DataLength - 2;
}
}
ExFreePool(valueInfoP);
}
else
{
IF_LOUD(DbgPrint("Error Allocating the buffer for the device name\n");)
}
}
// terminate the buffer
DeviceNames[BufPos / 2] = 0;
DeviceNames[BufPos / 2 + 1] = 0;
ZwClose(ExportKeyHandle);
i++;
}
ZwClose(keyHandle);
}
if (BufPos == 0)
{
if (DeviceNames)
{
ExFreePool(DeviceNames);
}
TRACE_EXIT();
return NULL;
}
TRACE_EXIT();
return DeviceNames;
}
#define ABSOLUTE(wait) (wait)
#define RELATIVE(wait) (-(wait))
#define NANOSECONDS(nanos) (((signed __int64)(nanos)) / 100L)
#define MICROSECONDS(micros) (((signed __int64)(micros)) * NANOSECONDS(1000L))
#define MILLISECONDS(milli) (((signed __int64)(milli)) * MICROSECONDS(1000L))
#define SECONDS(seconds) (((signed __int64)(seconds)) * MILLISECONDS(1000L))
//-------------------------------------------------------------------
PKEY_VALUE_PARTIAL_INFORMATION
getTcpBindings(
)
{
PKEY_VALUE_PARTIAL_INFORMATION result = NULL;
OBJECT_ATTRIBUTES objAttrs;
NTSTATUS status;
HANDLE keyHandle;
InitializeObjectAttributes(&objAttrs, &tcpLinkageKeyName, OBJ_CASE_INSENSITIVE, NULL, NULL);
status = ZwOpenKey(&keyHandle, KEY_READ, &objAttrs);
if (!NT_SUCCESS(status))
{
IF_LOUD(DbgPrint("\n\nStatus of %x opening %ws\n", status, tcpLinkageKeyName.Buffer);)
}
else
{
ULONG resultLength;
KEY_VALUE_PARTIAL_INFORMATION valueInfo;
IF_LOUD(DbgPrint("\n\nOpened %ws\n", tcpLinkageKeyName.Buffer);)
status = ZwQueryValueKey(keyHandle,
&bindValueName,
KeyValuePartialInformation,
&valueInfo,
sizeof(valueInfo),
&resultLength);
if (!NT_SUCCESS(status) && (status != STATUS_BUFFER_OVERFLOW))
{
IF_LOUD(DbgPrint("\n\nStatus of %x querying key value for size\n", status);)
}
else
{
// We know how big it needs to be.
ULONG valueInfoLength = valueInfo.DataLength + FIELD_OFFSET(KEY_VALUE_PARTIAL_INFORMATION, Data[0]);
PKEY_VALUE_PARTIAL_INFORMATION valueInfoP = (PKEY_VALUE_PARTIAL_INFORMATION)ExAllocatePoolWithTag(NonPagedPool, valueInfoLength, '2PWA');
if (valueInfoP != NULL)
{
status = ZwQueryValueKey(keyHandle,
&bindValueName,
KeyValuePartialInformation,
valueInfoP,
valueInfoLength,
&resultLength);
if (!NT_SUCCESS(status))
{
IF_LOUD(DbgPrint("\n\nStatus of %x querying key value\n", status);)
ExFreePool(valueInfoP);
}
else
{
if (valueInfoLength != resultLength)
{
IF_LOUD(DbgPrint("\n\nQuerying key value result len = %u "
"but previous len = %u\n", resultLength, valueInfoLength);)
ExFreePool(valueInfoP);
}
else
{
if (valueInfoP->Type != REG_MULTI_SZ)
{
IF_LOUD(DbgPrint("\n\nTcpip bind value not REG_MULTI_SZ but %u\n", valueInfoP->Type);)
ExFreePool(valueInfoP);
}
else
{
// It's OK
#if DBG
ULONG i;
WCHAR* dataP = (WCHAR*)(&valueInfoP->Data[0]);
IF_LOUD (DbgPrint("\n\nBind value:\n");)for(i = 0; *dataP != UNICODE_NULL; i++)
{
UNICODE_STRING macName;
RtlInitUnicodeString(&macName, dataP);
IF_LOUD(DbgPrint("\n\nMac %u = %ws\n", i, macName.Buffer);)
dataP += (macName.Length + sizeof(UNICODE_NULL)) / sizeof(WCHAR);
}
#endif // DBG
result = valueInfoP;
}
}
}
}
}
ZwClose(keyHandle);
}
return result;
}
//-------------------------------------------------------------------
ULONG
NPF_GetRegistryOption_Integer(
PUNICODE_STRING RegistryPath,
PUNICODE_STRING RegValueName
)
{
ULONG returnValue = 0;
OBJECT_ATTRIBUTES objAttrs;
NTSTATUS status;
HANDLE keyHandle;
TRACE_ENTER();
IF_LOUD(DbgPrint("\nRegistryPath: %ws, RegValueName: %ws\n", RegistryPath->Buffer, RegValueName->Buffer);)
InitializeObjectAttributes(&objAttrs, RegistryPath, OBJ_CASE_INSENSITIVE, NULL, NULL);
status = ZwOpenKey(&keyHandle, KEY_READ, &objAttrs);
if (!NT_SUCCESS(status))
{
IF_LOUD(DbgPrint("\nStatus of %x opening %ws\n", status, RegistryPath->Buffer);)
}
else //OK
{
BOOLEAN bTried = FALSE;
ULONG resultLength;
KEY_VALUE_PARTIAL_INFORMATION valueInfo;
IF_LOUD(DbgPrint("\nStatus of %x opening %ws\n", status, RegistryPath->Buffer);)
REGISTRY_QUERY_VALUE_KEY:
status = ZwQueryValueKey(keyHandle,
RegValueName,
KeyValuePartialInformation,
&valueInfo,
sizeof(valueInfo),
&resultLength);
if (status == STATUS_OBJECT_NAME_NOT_FOUND && bTried == FALSE)
{
LARGE_INTEGER delayTime;
delayTime.QuadPart = RELATIVE(MILLISECONDS(500));
IF_LOUD(DbgPrint("\nCalled KeDelayExecutionThread() to delay 500ms\n"););
KeDelayExecutionThread(KernelMode, FALSE, &delayTime);
bTried = TRUE;
goto REGISTRY_QUERY_VALUE_KEY;
}
if (!NT_SUCCESS(status) && (status != STATUS_BUFFER_OVERFLOW))
{
IF_LOUD(DbgPrint("\nStatus of %x querying key value for size\n", status);)
}
else
{
// We know how big it needs to be.
ULONG valueInfoLength = valueInfo.DataLength + FIELD_OFFSET(KEY_VALUE_PARTIAL_INFORMATION, Data[0]);
PKEY_VALUE_PARTIAL_INFORMATION valueInfoP = (PKEY_VALUE_PARTIAL_INFORMATION)ExAllocatePoolWithTag(PagedPool, valueInfoLength, '1PWA');
if (valueInfoP != NULL)
{
status = ZwQueryValueKey(keyHandle,
RegValueName,
KeyValuePartialInformation,
valueInfoP,
valueInfoLength,
&resultLength);
if (!NT_SUCCESS(status))
{
IF_LOUD(DbgPrint("Status of %x querying key value\n", status);)
}
else
{
IF_LOUD(DbgPrint("\"%ws\" Key = %08X\n", RegValueName->Buffer, *((DWORD *)valueInfoP->Data));)
if (valueInfoP->DataLength == 4)
{
returnValue = *((DWORD *) valueInfoP->Data);
}
}
ExFreePool(valueInfoP);
}
else
{
IF_LOUD(DbgPrint("Error Allocating the buffer for the NPF_GetRegistryOption_Integer function\n");)
}
}
ZwClose(keyHandle);
}
TRACE_EXIT();
return returnValue;
}
//-------------------------------------------------------------------
VOID
NPF_GetRegistryOption_String(
PUNICODE_STRING RegistryPath,
PUNICODE_STRING RegValueName,
PNDIS_STRING g_OutputString
)
{
OBJECT_ATTRIBUTES objAttrs;
NTSTATUS status;
HANDLE keyHandle;
TRACE_ENTER();
IF_LOUD(DbgPrint("\nRegistryPath: %ws, RegValueName: %ws\n", RegistryPath->Buffer, RegValueName->Buffer);)
InitializeObjectAttributes(&objAttrs, RegistryPath, OBJ_CASE_INSENSITIVE, NULL, NULL);
status = ZwOpenKey(&keyHandle, KEY_READ, &objAttrs);
if (!NT_SUCCESS(status))
{
IF_LOUD(DbgPrint("\nStatus of %x opening %ws\n", status, RegistryPath->Buffer);)
}
else //OK
{
ULONG resultLength;
KEY_VALUE_PARTIAL_INFORMATION valueInfo;
status = ZwQueryValueKey(keyHandle,
RegValueName,
KeyValuePartialInformation,
&valueInfo,
sizeof(valueInfo),
&resultLength);
if (!NT_SUCCESS(status) && (status != STATUS_BUFFER_OVERFLOW))
{
IF_LOUD(DbgPrint("\nStatus of %x querying key value for size\n", status);)
}
else
{
// We know how big it needs to be.
ULONG valueInfoLength = valueInfo.DataLength + FIELD_OFFSET(KEY_VALUE_PARTIAL_INFORMATION, Data[0]);
PKEY_VALUE_PARTIAL_INFORMATION valueInfoP = (PKEY_VALUE_PARTIAL_INFORMATION)ExAllocatePoolWithTag(PagedPool, valueInfoLength, '1PWA');
if (valueInfoP != NULL)
{
status = ZwQueryValueKey(keyHandle,
RegValueName,
KeyValuePartialInformation,
valueInfoP,
valueInfoLength,
&resultLength);
if (!NT_SUCCESS(status))
{
IF_LOUD(DbgPrint("Status of %x querying key value\n", status);)
}
else
{
IF_LOUD(DbgPrint("\"%ws\" Key = %ws\n", RegValueName->Buffer, valueInfoP->Data);)
g_OutputString->Length = (USHORT)(valueInfoP->DataLength - sizeof(UNICODE_NULL));
g_OutputString->MaximumLength = (USHORT)(valueInfoP->DataLength);
g_OutputString->Buffer = ExAllocatePoolWithTag(NonPagedPool, g_OutputString->MaximumLength, '3PWA');
if (g_OutputString->Buffer)
RtlCopyMemory(g_OutputString->Buffer, valueInfoP->Data, valueInfoP->DataLength);
}
ExFreePool(valueInfoP);
}
else
{
IF_LOUD(DbgPrint("Error Allocating the buffer for the NPF_GetRegistryOption_String function\n");)
}
}
ZwClose(keyHandle);
}
TRACE_EXIT();
}
//-------------------------------------------------------------------
BOOLEAN
NPF_CreateDevice(
IN OUT PDRIVER_OBJECT DriverObject,
IN PUNICODE_STRING AdapterName,
IN PUNICODE_STRING NPF_Prefix,
IN BOOLEAN Dot11
)
{
NTSTATUS status;
PDEVICE_OBJECT devObjP;
UNICODE_STRING deviceName;
UNICODE_STRING deviceSymLink;
TRACE_ENTER();
IF_LOUD(DbgPrint("\n\ncreateDevice for MAC %ws\n", AdapterName->Buffer););
if (RtlCompareMemory(AdapterName->Buffer, devicePrefix.Buffer, devicePrefix.Length) < devicePrefix.Length)
{
TRACE_EXIT();
return FALSE;
}
deviceName.Length = 0;
deviceName.MaximumLength = (USHORT)(AdapterName->Length + NPF_Prefix->Length + sizeof(UNICODE_NULL));
deviceName.Buffer = ExAllocatePoolWithTag(PagedPool, deviceName.MaximumLength, '3PWA');
if (deviceName.Buffer == NULL)
{
TRACE_EXIT();
return FALSE;
}
deviceSymLink.Length = 0;
deviceSymLink.MaximumLength = (USHORT)(AdapterName->Length - devicePrefix.Length + symbolicLinkPrefix.Length + NPF_Prefix->Length + sizeof(UNICODE_NULL));
deviceSymLink.Buffer = ExAllocatePoolWithTag(NonPagedPool, deviceSymLink.MaximumLength, '3PWA');