-
Notifications
You must be signed in to change notification settings - Fork 508
/
Packet32.cpp
4258 lines (3558 loc) · 124 KB
/
Packet32.cpp
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-2020 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)
* 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.
*
*/
#define UNICODE 1
#pragma warning (disable : 4127) //conditional expression is constant. Used for do{}while(FALSE) loops.
#if (MSC_VER < 1300)
#pragma warning (disable : 4710) // inline function not expanded. used for strsafe functions
#endif
#include <Packet32.h>
#include <tchar.h>
#include <strsafe.h>
#include <Shlwapi.h>
#include <wlanapi.h>
#include <string>
#include "ProtInstall.h"
#include "Packet32-Int.h"
#include "../npf/npf/ioctls.h"
#include <map>
using namespace std;
#include "debug.h"
#define BUFSIZE 512
#define MAX_SEM_COUNT 10
#define MAX_TRY_TIME 50
#define SLEEP_TIME 50
HANDLE g_hNpcapHelperPipe = INVALID_HANDLE_VALUE; // Handle for NpcapHelper named pipe.
HANDLE g_hDllHandle = NULL; // The handle to this DLL.
CHAR g_strLoopbackAdapterName[BUFSIZE] = ""; // The name of "Npcap Loopback Adapter".
#define NPCAP_LOOPBACK_ADAPTER_BUILTIN "NPF_Loopback"
BOOLEAN g_bLoopbackSupport = TRUE;
map<string, int> g_nbAdapterMonitorModes; // The states for all the wireless adapters that show whether it is in the monitor mode.
#define SERVICES_REG_KEY "SYSTEM\\CurrentControlSet\\Services\\"
#define NPCAP_SERVICE_REGISTRY_KEY SERVICES_REG_KEY NPF_DRIVER_NAME
#ifdef HAVE_AIRPCAP_API
#pragma message ("Compiling Packet.dll with support for AirPcap")
#endif
#if defined(HAVE_AIRPCAP_API)
#define LOAD_OPTIONAL_LIBRARIES
VOID PacketLoadLibrariesDynamically();
#endif
#ifndef UNUSED
#define UNUSED(_x) (_x)
#endif
#ifdef _DEBUG_TO_FILE
LONG PacketDumpRegistryKey(PCHAR KeyName, PCHAR FileName);
#endif //_DEBUG_TO_FILE
#include <windows.h>
#include <windowsx.h>
#include <iphlpapi.h>
#include <ipifcons.h>
#include <WpcapNames.h>
//
// Current packet.dll version. It can be retrieved directly or through the PacketGetVersion() function.
//
char PacketLibraryVersion[64];
//
// Current driver version. It can be retrieved directly or through the PacketGetVersion() function.
//
char PacketDriverVersion[64];
//
// Current driver name ("NPF" or "NPCAP"). It can be retrieved directly or through the PacketGetVersion() function.
//
char PacketDriverName[64];
//
// WinPcap global registry key
//
//WCHAR g_WinPcapKeyBuffer[MAX_WINPCAP_KEY_CHARS];
//HKEY g_WinpcapKey = NULL;
//
// Global adapters list related variables
//
extern PADAPTER_INFO g_AdaptersInfoList;
extern HANDLE g_AdaptersInfoMutex;
HINSTANCE hinstLib = NULL;
typedef DWORD
(WINAPI *MY_WLANOPENHANDLE)(
_In_ DWORD dwClientVersion,
_Reserved_ PVOID pReserved,
_Out_ PDWORD pdwNegotiatedVersion,
_Out_ PHANDLE phClientHandle
);
typedef DWORD
(WINAPI *MY_WLANCLOSEHANDLE)(
_In_ HANDLE hClientHandle,
_Reserved_ PVOID pReserved
);
typedef DWORD
(WINAPI *MY_WLANENUMINTERFACES)(
_In_ HANDLE hClientHandle,
_Reserved_ PVOID pReserved,
_Outptr_ PWLAN_INTERFACE_INFO_LIST *ppInterfaceList
);
typedef VOID
(WINAPI *MY_WLANFREEMEMORY)(
_In_ PVOID pMemory
);
typedef DWORD
(WINAPI *MY_WLANSETINTERFACE)(
_In_ HANDLE hClientHandle,
_In_ CONST GUID *pInterfaceGuid,
_In_ WLAN_INTF_OPCODE OpCode,
_In_ DWORD dwDataSize,
_In_reads_bytes_(dwDataSize) CONST PVOID pData,
_Reserved_ PVOID pReserved
);
typedef DWORD
(WINAPI *My_WLANQUERYINTERFACE)(
_In_ HANDLE hClientHandle,
_In_ CONST GUID *pInterfaceGuid,
_In_ WLAN_INTF_OPCODE OpCode,
_Reserved_ PVOID pReserved,
_Out_ PDWORD pdwDataSize,
_Outptr_result_bytebuffer_(*pdwDataSize) PVOID *ppData,
_Out_opt_ PWLAN_OPCODE_VALUE_TYPE pWlanOpcodeValueType
);
typedef DWORD
(WINAPI *My_WLANGETINTERFACECAPABILITY)(
_In_ HANDLE hClientHandle,
_In_ const GUID *pInterfaceGuid,
_Reserved_ PVOID pReserved,
_Out_ PWLAN_INTERFACE_CAPABILITY *ppCapability
);
MY_WLANOPENHANDLE My_WlanOpenHandle = NULL;
MY_WLANCLOSEHANDLE My_WlanCloseHandle = NULL;
MY_WLANENUMINTERFACES My_WlanEnumInterfaces = NULL;
MY_WLANFREEMEMORY My_WlanFreeMemory = NULL;
MY_WLANSETINTERFACE My_WlanSetInterface = NULL;
My_WLANQUERYINTERFACE My_WlanQueryInterface = NULL;
My_WLANGETINTERFACECAPABILITY My_WlanGetInterfaceCapability = NULL;
BOOL initWlanFunctions()
{
BOOL bRet;
TRACE_ENTER();
// If these functions are already available, we don't import them again.
if (My_WlanOpenHandle != NULL &&
My_WlanCloseHandle != NULL &&
My_WlanEnumInterfaces != NULL &&
My_WlanFreeMemory != NULL &&
My_WlanSetInterface != NULL &&
My_WlanQueryInterface != NULL &&
My_WlanGetInterfaceCapability != NULL)
{
return TRUE;
}
// Get a handle to the packet DLL module.
hinstLib = LoadLibrary(TEXT("wlanapi.dll"));
// If the handle is valid, try to get the function address.
if (hinstLib != NULL)
{
My_WlanOpenHandle = (MY_WLANOPENHANDLE)GetProcAddress(hinstLib, "WlanOpenHandle");
My_WlanCloseHandle = (MY_WLANCLOSEHANDLE)GetProcAddress(hinstLib, "WlanCloseHandle");
My_WlanEnumInterfaces = (MY_WLANENUMINTERFACES)GetProcAddress(hinstLib, "WlanEnumInterfaces");
My_WlanFreeMemory = (MY_WLANFREEMEMORY)GetProcAddress(hinstLib, "WlanFreeMemory");
My_WlanSetInterface = (MY_WLANSETINTERFACE)GetProcAddress(hinstLib, "WlanSetInterface");
My_WlanQueryInterface = (My_WLANQUERYINTERFACE)GetProcAddress(hinstLib, "WlanQueryInterface");
My_WlanGetInterfaceCapability = (My_WLANGETINTERFACECAPABILITY)GetProcAddress(hinstLib, "WlanGetInterfaceCapability");
// If the function address is valid, call the function.
if (My_WlanOpenHandle != NULL &&
My_WlanCloseHandle != NULL &&
My_WlanEnumInterfaces != NULL &&
My_WlanFreeMemory != NULL &&
My_WlanSetInterface != NULL &&
My_WlanQueryInterface != NULL &&
My_WlanGetInterfaceCapability != NULL)
{
bRet = TRUE;
}
else
{
TRACE_PRINT1("GetProcAddress: error, errCode = 0x%08x.", GetLastError());
bRet = FALSE;
}
}
else
{
TRACE_PRINT1("LoadLibrary: error, errCode = 0x%08x.", GetLastError());
bRet = FALSE;
}
TRACE_EXIT();
return bRet;
}
#ifdef LOAD_OPTIONAL_LIBRARIES
//
// Dynamic dependencies variables and declarations
//
volatile LONG g_DynamicLibrariesLoaded = 0;
HANDLE g_DynamicLibrariesMutex;
#endif
#ifdef HAVE_AIRPCAP_API
// We dynamically load the Airpcap library in order link it only when it's present on the system
AirpcapGetLastErrorHandler g_PAirpcapGetLastError;
AirpcapGetDeviceListHandler g_PAirpcapGetDeviceList;
AirpcapFreeDeviceListHandler g_PAirpcapFreeDeviceList;
AirpcapOpenHandler g_PAirpcapOpen;
AirpcapCloseHandler g_PAirpcapClose;
AirpcapGetLinkTypeHandler g_PAirpcapGetLinkType;
AirpcapSetKernelBufferHandler g_PAirpcapSetKernelBuffer;
AirpcapSetFilterHandler g_PAirpcapSetFilter;
AirpcapGetMacAddressHandler g_PAirpcapGetMacAddress;
AirpcapSetMinToCopyHandler g_PAirpcapSetMinToCopy;
AirpcapGetReadEventHandler g_PAirpcapGetReadEvent;
AirpcapReadHandler g_PAirpcapRead;
AirpcapGetStatsHandler g_PAirpcapGetStats;
AirpcapWriteHandler g_PAirpcapWrite;
#endif // HAVE_AIRPCAP_API
//
// Additions for WinPcap OEM
//
#ifdef WPCAP_OEM_UNLOAD_H
typedef BOOL (*WoemLeaveDllHandler)(void);
WoemLeaveDllHandler g_WoemLeaveDllH = NULL;
__declspec (dllexport) VOID PacketRegWoemLeaveHandler(PVOID Handler)
{
g_WoemLeaveDllH = Handler;
}
#endif // WPCAP_OEM_UNLOAD_H
//---------------------------------------------------------------------------
//
// This wrapper around loadlibrary appends the system folder (usually c:\windows\system32)
// to the relative path of the DLL, so that the DLL is always loaded from an absolute path
// (It's no longer possible to load airpcap.dll from the application folder).
// This solves the DLL Hijacking issue discovered in August 2010
// http://blog.metasploit.com/2010/08/exploiting-dll-hijacking-flaws.html
//
HMODULE LoadLibrarySafe(LPCTSTR lpFileName)
{
TRACE_ENTER();
TCHAR path[MAX_PATH] = { 0 };
TCHAR fullFileName[MAX_PATH];
UINT res;
HMODULE hModule = NULL;
do
{
res = GetSystemDirectory(path, MAX_PATH);
if (res == 0)
{
//
// some bad failure occurred;
//
break;
}
if (res > MAX_PATH)
{
//
// the buffer was not big enough
//
SetLastError(ERROR_INSUFFICIENT_BUFFER);
break;
}
if (res + 1 + _tcslen(lpFileName) + 1 < MAX_PATH)
{
memcpy(fullFileName, path, res * sizeof(TCHAR));
fullFileName[res] = _T('\\');
memcpy(&fullFileName[res + 1], lpFileName, (_tcslen(lpFileName) + 1) * sizeof(TCHAR));
hModule = LoadLibrary(fullFileName);
}
else
{
SetLastError(ERROR_INSUFFICIENT_BUFFER);
}
}while(FALSE);
TRACE_EXIT();
return hModule;
}
BOOL NpcapCreatePipe(const char *pipeName, HANDLE moduleName)
{
int pid = GetCurrentProcessId();
char params[BUFSIZE];
SHELLEXECUTEINFOA shExInfo = { 0 };
DWORD nResult;
char lpFilename[BUFSIZE];
char szDrive[BUFSIZE];
char szDir[BUFSIZE];
TRACE_ENTER();
// Get Path to This Module
nResult = GetModuleFileNameA((HMODULE) moduleName, lpFilename, BUFSIZE);
if (nResult == 0)
{
TRACE_PRINT1("GetModuleFileNameA failed. GLE=%d\n", GetLastError());
TRACE_EXIT();
return FALSE;
}
_splitpath_s(lpFilename, szDrive, BUFSIZE, szDir, BUFSIZE, NULL, 0, NULL, 0);
_makepath_s(lpFilename, BUFSIZE, szDrive, szDir, "NpcapHelper", ".exe");
if (!PathFileExistsA(lpFilename))
{
TRACE_PRINT1("PathFileExistsA failed. GLE=%d\n", GetLastError());
TRACE_EXIT();
return FALSE;
}
sprintf_s(params, BUFSIZE, "%s %d", pipeName, pid);
shExInfo.cbSize = sizeof(shExInfo);
shExInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
shExInfo.hwnd = 0;
shExInfo.lpVerb = "runas"; // Operation to perform
shExInfo.lpFile = lpFilename; // Application to start
shExInfo.lpParameters = params; // Additional parameters
shExInfo.lpDirectory = 0;
shExInfo.nShow = SW_SHOW;
shExInfo.hInstApp = 0;
if (!ShellExecuteExA(&shExInfo))
{
DWORD dwError = GetLastError();
if (dwError == ERROR_CANCELLED)
{
// The user refused to allow privileges elevation.
// Do nothing ...
}
TRACE_EXIT();
return FALSE;
}
else
{
TRACE_EXIT();
if (shExInfo.hProcess)
CloseHandle(shExInfo.hProcess);
return TRUE;
}
}
HANDLE NpcapConnect(const char *pipeName)
{
HANDLE hPipe = INVALID_HANDLE_VALUE;
int tryTime = 0;
char lpszPipename[BUFSIZE];
TRACE_ENTER();
sprintf_s(lpszPipename, BUFSIZE, "\\\\.\\pipe\\%s", pipeName);
// Try to open a named pipe; wait for it, if necessary.
while (tryTime < MAX_TRY_TIME)
{
hPipe = CreateFileA(
lpszPipename, // pipe name
GENERIC_READ | // read and write access
GENERIC_WRITE,
0, // no sharing
NULL, // default security attributes
OPEN_EXISTING, // opens existing pipe
0, // default attributes
NULL); // no template file
// Break if the pipe handle is valid.
if (hPipe != INVALID_HANDLE_VALUE)
{
break;
}
else
{
tryTime++;
Sleep(SLEEP_TIME);
}
}
TRACE_EXIT();
return hPipe;
}
HANDLE NpcapRequestHandle(const char *sMsg, DWORD *pdwError)
{
LPCSTR lpvMessage = sMsg;
char chBuf[BUFSIZE];
BOOL fSuccess = FALSE;
DWORD cbRead, cbToWrite, cbWritten, dwMode;
HANDLE hPipe = g_hNpcapHelperPipe;
TRACE_ENTER();
if (hPipe == INVALID_HANDLE_VALUE)
{
TRACE_EXIT();
return INVALID_HANDLE_VALUE;
}
// The pipe connected; change to message-read mode.
dwMode = PIPE_READMODE_MESSAGE;
fSuccess = SetNamedPipeHandleState(
hPipe, // pipe handle
&dwMode, // new pipe mode
NULL, // don't set maximum bytes
NULL); // don't set maximum time
if (!fSuccess)
{
TRACE_PRINT1("SetNamedPipeHandleState failed. GLE=%d\n", GetLastError());
TRACE_EXIT();
return INVALID_HANDLE_VALUE;
}
// Send a message to the pipe server.
cbToWrite = (DWORD) (strlen(lpvMessage) + 1)*sizeof(char);
TRACE_PRINT2("\nSending %d byte message: \"%hs\"\n", cbToWrite, lpvMessage);
fSuccess = WriteFile(
hPipe, // pipe handle
lpvMessage, // message
cbToWrite, // message length
&cbWritten, // bytes written
NULL); // not overlapped
if (!fSuccess)
{
TRACE_PRINT1("WriteFile to pipe failed. GLE=%d\n", GetLastError());
TRACE_EXIT();
return INVALID_HANDLE_VALUE;
}
TRACE_PRINT("Message sent to server, receiving reply as follows:\n");
do
{
// Read from the pipe.
fSuccess = ReadFile(
hPipe, // pipe handle
chBuf, // buffer to receive reply
BUFSIZE*sizeof(char), // size of buffer
&cbRead, // number of bytes read
NULL); // not overlapped
if (!fSuccess && GetLastError() != ERROR_MORE_DATA)
break;
//printf("\"%s\"\n", chBuf );
} while (!fSuccess); // repeat loop if ERROR_MORE_DATA
if (!fSuccess)
{
TRACE_PRINT1("ReadFile from pipe failed. GLE=%d\n", GetLastError());
TRACE_EXIT();
return INVALID_HANDLE_VALUE;
}
//printf("\n<End of message, press ENTER to terminate connection and exit\n>");
if (cbRead != 0)
{
HANDLE hd;
sscanf_s(chBuf, "%p,%lu", &hd, pdwError);
TRACE_PRINT1("Received Driver Handle: %0p\n", hd);
TRACE_EXIT();
return hd;
}
else
{
TRACE_EXIT();
return INVALID_HANDLE_VALUE;
}
}
void NpcapGetLoopbackInterfaceName()
{
TRACE_ENTER();
HKEY hKey;
DWORD type;
char buffer[BUFSIZE];
DWORD size = sizeof(buffer);
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, NPCAP_SERVICE_REGISTRY_KEY "\\Parameters", 0, KEY_READ, &hKey) == ERROR_SUCCESS)
{
if (RegQueryValueExA(hKey, "LoopbackSupport", 0, &type, (LPBYTE)buffer, &size) == ERROR_SUCCESS && type == REG_DWORD)
{
g_bLoopbackSupport = (0 != *((DWORD *) buffer));
}
size = sizeof(buffer);
if (g_bLoopbackSupport && RegQueryValueExA(hKey, "LoopbackAdapter", 0, &type, (LPBYTE)buffer, &size) == ERROR_SUCCESS && type == REG_SZ)
{
strncpy_s(g_strLoopbackAdapterName, 512, buffer, sizeof(g_strLoopbackAdapterName)/ sizeof(g_strLoopbackAdapterName[0]) - 1);
}
RegCloseKey(hKey);
}
TRACE_EXIT();
}
BOOL NpcapIsAdminOnlyMode()
{
TRACE_ENTER();
HKEY hKey;
DWORD type;
char buffer[BUFSIZE];
DWORD size = sizeof(buffer);
DWORD dwAdminOnlyMode = 0;
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, NPCAP_SERVICE_REGISTRY_KEY "\\Parameters", 0, KEY_READ, &hKey) == ERROR_SUCCESS)
{
if (RegQueryValueExA(hKey, "AdminOnly", 0, &type, (LPBYTE)buffer, &size) == ERROR_SUCCESS && type == REG_DWORD)
{
dwAdminOnlyMode = *((DWORD *) buffer);
}
else
{
TRACE_PRINT1("RegQueryValueExA(AdminOnly) failed or not REG_DWORD: %#x\n", GetLastError());
dwAdminOnlyMode = 0;
}
RegCloseKey(hKey);
}
else
{
TRACE_PRINT1("RegOpenKeyExA(Services\\Npcap\\Parameters) failed: %#x\n", GetLastError());
dwAdminOnlyMode = 0;
}
TRACE_EXIT();
return (dwAdminOnlyMode != 0);
}
BOOL NpcapIsRunByAdmin()
{
BOOL bIsRunAsAdmin = FALSE;
DWORD dwError = ERROR_SUCCESS;
PSID pAdministratorsGroup = NULL;
// Allocate and initialize a SID of the administrators group.
SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
TRACE_ENTER();
if (!AllocateAndInitializeSid(
&NtAuthority,
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0,
&pAdministratorsGroup))
{
dwError = GetLastError();
goto Cleanup;
}
// Determine whether the SID of administrators group is enabled in
// the primary access token of the process.
if (!CheckTokenMembership(NULL, pAdministratorsGroup, &bIsRunAsAdmin))
{
dwError = GetLastError();
goto Cleanup;
}
Cleanup:
// Centralized cleanup for all allocated resources.
if (pAdministratorsGroup)
{
FreeSid(pAdministratorsGroup);
pAdministratorsGroup = NULL;
}
// Throw the error if something failed in the function.
if (ERROR_SUCCESS != dwError)
{
TRACE_PRINT1("IsProcessRunningAsAdminMode failed. GLE=%d\n", dwError);
}
TRACE_PRINT1("IsProcessRunningAsAdminMode result: %hs\n", bIsRunAsAdmin ? "yes" : "no");
TRACE_EXIT();
return bIsRunAsAdmin;
}
void NpcapStartHelper()
{
TRACE_ENTER();
// Only run this function once.
// This may be a mistake; what if the helper gets killed?
static BOOL NpcapHelperTried = FALSE;
if (NpcapHelperTried)
{
TRACE_PRINT("NpcapHelper already tried\n");
TRACE_EXIT();
return;
}
// Don't try again.
NpcapHelperTried = TRUE;
// If it's already started, use that instead
if (g_hNpcapHelperPipe != INVALID_HANDLE_VALUE)
{
TRACE_PRINT("NpcapHelper already started\n");
TRACE_EXIT();
return;
}
// Check if this process is running in Administrator mode.
if (NpcapIsRunByAdmin())
{
TRACE_PRINT("Already running as admin.\n");
TRACE_EXIT();
return;
}
char pipeName[BUFSIZE];
int pid = GetCurrentProcessId();
sprintf_s(pipeName, BUFSIZE, "npcap-%d", pid);
if (NpcapCreatePipe(pipeName, g_hDllHandle))
{
g_hNpcapHelperPipe = NpcapConnect(pipeName);
if (g_hNpcapHelperPipe == INVALID_HANDLE_VALUE)
{
TRACE_PRINT("Failed to connect to NpcapHelper.\n");
}
}
else
{
TRACE_PRINT("NpcapCreatePipe failed.\n");
}
TRACE_EXIT();
}
void NpcapStopHelper()
{
TRACE_ENTER();
if (g_hNpcapHelperPipe != INVALID_HANDLE_VALUE)
{
CloseHandle(g_hNpcapHelperPipe);
g_hNpcapHelperPipe = INVALID_HANDLE_VALUE;
}
TRACE_EXIT();
}
// find [substr] from a fixed-length buffer
// [full_data] will be treated as binary data buffer)
// return NULL if not found
static const char* memstr(const char* full_data, size_t full_data_len, const char* substr)
{
size_t sublen;
const char* cur;
size_t last_possible;
if (full_data == NULL || full_data_len <= 0 || substr == NULL)
{
return NULL;
}
if (*substr == '\0')
{
return NULL;
}
sublen = strlen(substr);
cur = full_data;
last_possible = full_data_len - sublen + 1;
for (size_t i = 0; i < last_possible; i++)
{
if (*cur == *substr)
{
//assert(full_data_len - i >= sublen);
if (memcmp(cur, substr, sublen) == 0)
{
//found
return cur;
}
}
cur ++;
}
return NULL;
}
// For memory block [mem], substitute all [source] strings with [destination], return the new memory block (need to free), if not found, return NULL.
PCHAR NpcapReplaceMemory(LPCSTR buf, int buf_size, LPCSTR source, LPCSTR destination)
{
PCHAR tmp;
PCHAR newbuf;
PCHAR retbuf;
LPCCH sk;
size_t size;
sk = memstr(buf, buf_size, source);
if (sk == NULL)
return NULL;
size = 2 * buf_size + strlen(destination) + 1;
newbuf = (PCHAR) calloc(1, size);
if (newbuf == NULL)
return NULL;
retbuf = (PCHAR) calloc(1, size);
if (retbuf == NULL)
{
free (newbuf);
return NULL;
}
memcpy_s(newbuf, size - 1, buf, buf_size);
sk = memstr(newbuf, size, source);
while (sk != NULL)
{
size_t pos = 0;
memcpy(retbuf + pos, newbuf, sk - newbuf);
pos += sk - newbuf;
sk += strlen(source);
memcpy(retbuf + pos, destination, strlen(destination));
pos += strlen(destination);
memcpy(retbuf + pos, sk, newbuf + size - sk);
tmp = newbuf;
newbuf = retbuf;
retbuf = tmp;
memset(retbuf, 0, size);
sk = memstr(newbuf, size, source);
}
free(retbuf);
return newbuf;
}
// For [string], substitute all [source] strings with [destination], return the new string (need to free), if not found, return NULL.
static PCHAR NpcapReplaceString(LPCSTR string, LPCSTR source, LPCSTR destination)
{
PCHAR tmp;
PCHAR newstr;
PCHAR retstr;
LPCCH sk;
size_t size;
sk = strstr(string, source);
if (sk == NULL)
return NULL;
size = 2 * strlen(string) + strlen(destination) + 1;
newstr = (PCHAR) calloc(1, size);
if (newstr == NULL)
return NULL;
retstr = (PCHAR) calloc(1, size);
if (retstr == NULL)
{
free (newstr);
return NULL;
}
sprintf_s(newstr, size - 1, "%s", string);
sk = strstr(newstr, source);
while (sk != NULL)
{
size_t pos = 0;
memcpy(retstr + pos, newstr, sk - newstr);
pos += sk - newstr;
sk += strlen(source);
memcpy(retstr + pos, destination, strlen(destination));
pos += strlen(destination);
memcpy(retstr + pos, sk, strlen(sk));
tmp = newstr;
newstr = retstr;
retstr = tmp;
memset(retstr, 0, size);
sk = strstr(newstr, source);
// We just need to replace only one substring, so we break here.
break;
}
free(retstr);
return newstr;
}
static PCHAR NpcapTranslateAdapterName_Standard2Wifi(LPCSTR AdapterName)
{
TRACE_ENTER();
TRACE_EXIT();
return NpcapReplaceString(AdapterName, "{", NPF_DEVICE_NAMES_TAG_WIFI "{");
}
static PCHAR NpcapTranslateAdapterName_Npf2Npcap(LPCSTR AdapterName)
{
return NpcapReplaceString(AdapterName, "NPF_", NPF_DEVICE_NAMES_PREFIX);
}
static PCHAR NpcapTranslateMemory_Npcap2Npf(LPCSTR pStr, int iBufSize)
{
return NpcapReplaceMemory(pStr, iBufSize, NPF_DEVICE_NAMES_PREFIX, "NPF_");
}
/*!
\brief The main dll function.
*/
BOOL APIENTRY DllMain(HANDLE DllHandle, DWORD Reason, LPVOID lpReserved)
{
TRACE_ENTER();
BOOLEAN Status=TRUE;
PADAPTER_INFO NewAdInfo;
TCHAR DllFileName[MAX_PATH];
g_hDllHandle = DllHandle;
UNUSED(lpReserved);
switch(Reason)
{
case DLL_PROCESS_ATTACH:
TRACE_PRINT("************Packet32: DllMain************");
#ifdef _DEBUG_TO_FILE
PacketDumpRegistryKey("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\" NPF_DRIVER_NAME,"npf.reg");
// dump a bunch of registry keys useful for debug to file
PacketDumpRegistryKey("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}",
"adapters.reg");
PacketDumpRegistryKey("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Tcpip",
"tcpip.reg");
PacketDumpRegistryKey("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services",
"services.reg");
#endif
// Create the mutex that will protect the adapter information list
g_AdaptersInfoMutex = CreateMutex(NULL, FALSE, NULL);
#ifdef LOAD_OPTIONAL_LIBRARIES
// Create the mutex that will protect the PacketLoadLibrariesDynamically() function
g_DynamicLibrariesMutex = CreateMutex(NULL, FALSE, NULL);
#endif
//
// Retrieve packet.dll version information from the file
//
// XXX We want to replace this with a constant. We leave it out for the moment
if(GetModuleFileName((HMODULE) DllHandle, DllFileName, sizeof(DllFileName) / sizeof(DllFileName[0])) > 0)
{
PacketGetFileVersion(DllFileName, PacketLibraryVersion, sizeof(PacketLibraryVersion));
}
//
// Retrieve NPF.sys version information from the file
//
// XXX We want to replace this with a constant. We leave it out for the moment
// TODO fixme. Those hardcoded strings are terrible...
PacketGetFileVersion(TEXT("drivers\\") TEXT(NPF_DRIVER_NAME) TEXT(".sys"), PacketDriverVersion, sizeof(PacketDriverVersion));
strcpy_s(PacketDriverName, 64, NPF_DRIVER_NAME);
// Get the name for "Npcap Loopback Adapter"
NpcapGetLoopbackInterfaceName();
break;
case DLL_PROCESS_DETACH:
CloseHandle(g_AdaptersInfoMutex);
while(g_AdaptersInfoList != NULL)
{
PNPF_IF_ADDRESS_ITEM pCursor, pNext;
NewAdInfo = g_AdaptersInfoList->Next;
pCursor = g_AdaptersInfoList->pNetworkAddresses;
while(pCursor != NULL)