-
Notifications
You must be signed in to change notification settings - Fork 519
/
Packet32.cpp
3795 lines (3250 loc) · 114 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 (https://npcap.com) is a Windows packet sniffing driver and library and
* is copyright (c) 2013-2023 by Nmap Software 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 used in other software
* without special permission from the Nmap Project. The standard (free) version
* is usually limited to installation on five systems. For more details, see the
* LICENSE file included with Npcap and also available at
* https://github.com/nmap/npcap/blob/master/LICENSE. This header file
* summarizes a few important aspects of the Npcap license, but is not a
* substitute for that full Npcap license agreement.
*
* We fund the Npcap project by selling two types of commercial licenses to a
* special Npcap OEM edition:
*
* 1) The Npcap OEM Redistribution License allows companies distribute Npcap OEM
* within their products. Licensees generally use the Npcap OEM silent
* installer, ensuring a seamless experience for end users. Licensees may choose
* between a perpetual unlimited license or a quarterly term license, along with
* options for commercial support and updates. Prices and details:
* https://npcap.com/oem/redist.html
*
* 2) The Npcap OEM Internal-Use License is for organizations that wish to use
* Npcap OEM internally, without redistribution outside their organization. This
* allows them to bypass the 5-system usage cap of the Npcap free edition. It
* includes commercial support and update options, and provides the extra Npcap
* OEM features such as the silent installer for automated deployment. Prices
* and details: https://npcap.com/oem/internal.html
*
* Both of these licenses include updates and support as well as a warranty.
* Npcap OEM also includes a silent installer for unattended installation.
* Further details about Npcap OEM are available from https://npcap.com/oem/,
* and you are also welcome to contact us at sales@nmap.com to ask any questions
* or set up a license for your organization.
*
* 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. It will be
* free for them if they need 5 or fewer copies.
*
* If the Nmap Project (directly or through one of our commercial licensing
* customers) has granted you additional rights to Npcap or Npcap OEM, those
* additional rights take precedence where they conflict with the terms of the
* license agreement.
*
* 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 relicense 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. Warranty rights and commercial support are
* available for the OEM Edition described above.
*
* 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.
*
***************************************************************************/
/*
* 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
#include "Packet32-Int.h"
#include <tchar.h>
#include <strsafe.h>
#include <string>
#include <ntddndis.h>
#include "../npf/npf/ioctls.h"
#include "../../version.h"
#include <ws2ipdef.h>
#include <winternl.h>
#include <ip2string.h>
#include <map>
using namespace std;
#define BUFSIZE 512
#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[ADAPTER_NAME_LENGTH] = "\0"; // The name of legacy "Npcap Loopback Adapter" from registry.
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
#include <iphlpapi.h>
#include <WpcapNames.h>
//
// Current packet.dll version. It can be retrieved directly or through the PacketGetVersion() function.
//
__declspec(dllexport) const char PacketLibraryVersion[] = WINPCAP_VER_STRING;
//
// Current driver version. It can be retrieved directly or through the PacketGetDriverVersion() function.
//
static char PacketDriverVersion[64];
//
// Current driver name ("NPF" or "NPCAP"). It can be retrieved directly or through the PacketGetDriverName() function.
//
static const char PacketDriverName[] = NPF_DRIVER_NAME;
//
// Global adapters list related variables
//
extern ADINFO_LIST g_AdaptersInfoList;
extern HANDLE g_AdaptersInfoMutex;
#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;
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
//---------------------------------------------------------------------------
_Success_(return != 0)
static BOOL PacketGetFileVersion(_In_ LPCTSTR FileName, _Out_writes_(VersionBuffLen) PCHAR VersionBuff, _In_ UINT VersionBuffLen);
static BOOL NpcapCreatePipe(const char *pipeName, HANDLE moduleName)
{
const int pid = GetCurrentProcessId();
char params[BUFSIZE];
SHELLEXECUTEINFOA shExInfo = {};
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)
{
nResult = GetLastError();
TRACE_PRINT1("GetModuleFileNameA failed. GLE=%d\n", nResult);
TRACE_EXIT();
SetLastError(nResult);
return FALSE;
}
_splitpath_s(lpFilename, szDrive, BUFSIZE, szDir, BUFSIZE, NULL, 0, NULL, 0);
_makepath_s(lpFilename, BUFSIZE, szDrive, szDir, "NpcapHelper", ".exe");
nResult = GetFileAttributesA(lpFilename);
if (nResult == INVALID_FILE_ATTRIBUTES)
{
nResult = GetLastError();
TRACE_PRINT2("GetFileAttributesA(%s) failed: %d", lpFilename, nResult);
TRACE_EXIT();
SetLastError(nResult);
return FALSE;
}
if (nResult & FILE_ATTRIBUTE_DIRECTORY)
{
TRACE_PRINT1("%s is a directory.", lpFilename);
TRACE_EXIT();
SetLastError(ERROR_DIRECTORY_NOT_SUPPORTED);
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))
{
const DWORD dwError = GetLastError();
if (dwError == ERROR_CANCELLED)
{
// The user refused to allow privileges elevation.
// Do nothing ...
}
TRACE_EXIT();
SetLastError(dwError);
return FALSE;
}
else
{
TRACE_EXIT();
if (shExInfo.hProcess)
CloseHandle(shExInfo.hProcess);
return TRUE;
}
}
static HANDLE NpcapConnect(const char *pipeName)
{
HANDLE hPipe = INVALID_HANDLE_VALUE;
int tryTime = 0;
char lpszPipename[BUFSIZE];
DWORD err = ERROR_SUCCESS;
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)
{
err = ERROR_SUCCESS;
break;
}
else
{
err = GetLastError();
tryTime++;
Sleep(SLEEP_TIME);
}
}
TRACE_EXIT();
SetLastError(err);
return hPipe;
}
static HANDLE NpcapRequestHandle(const char *sMsg, DWORD *pdwError)
{
HANDLE hd = INVALID_HANDLE_VALUE;
LPCSTR lpvMessage = sMsg;
char chBuf[BUFSIZE] = { 0 };
BOOL fSuccess = FALSE;
DWORD cbRead, cbToWrite, cbWritten, dwMode;
HANDLE hPipe = g_hNpcapHelperPipe;
TRACE_ENTER();
if (hPipe == INVALID_HANDLE_VALUE)
{
*pdwError = ERROR_PIPE_NOT_CONNECTED;
goto Exit;
}
// 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)
{
*pdwError = GetLastError();
TRACE_PRINT1("SetNamedPipeHandleState failed. GLE=%d\n", *pdwError);
goto Exit;
}
// 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)
{
*pdwError = GetLastError();
TRACE_PRINT1("WriteFile to pipe failed. GLE=%d\n", *pdwError);
goto Exit;
}
// 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)
{
*pdwError = GetLastError();
TRACE_PRINT1("ReadFile from pipe failed. GLE=%d\n", *pdwError);
goto Exit;
}
if (cbRead == 0)
{
*pdwError = ERROR_NO_DATA;
goto Exit;
}
int nFields = _snscanf_s(chBuf, cbRead, "%p,%lu", &hd, pdwError);
if (nFields != 2)
{
*pdwError = ERROR_OPEN_FAILED;
hd = INVALID_HANDLE_VALUE;
goto Exit;
}
TRACE_PRINT1("Received Driver Handle: %0p\n", hd);
Exit:
TRACE_EXIT();
return hd;
}
static 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 we support loopback
if (g_bLoopbackSupport
// and there's a loopback adapter device name recorded
&& RegQueryValueExA(hKey, "LoopbackAdapter", 0, &type, (LPBYTE)buffer, &size) == ERROR_SUCCESS
// and the type matches and it's an appropriate size
&& type == REG_SZ && size < ADAPTER_NAME_LENGTH + sizeof(DEVICE_PREFIX) && size > sizeof(DEVICE_PREFIX))
{
// Try to copy the adapter ID (skip the "\\Device\\" prefix)
if (FAILED(StringCchCopyA(g_strLoopbackAdapterName, sizeof(g_strLoopbackAdapterName), buffer + sizeof(DEVICE_PREFIX) - 1))) {
// Failed? Null it out and ignore.
g_strLoopbackAdapterName[0] = '\0';
}
}
RegCloseKey(hKey);
}
TRACE_EXIT();
}
static BOOL NpcapIsAdminOnlyMode()
{
TRACE_ENTER();
static BOOLEAN cached = FALSE;
static DWORD dwAdminOnlyMode = 0;
DWORD size = sizeof(DWORD);
LSTATUS status = ERROR_SUCCESS;
if (!cached) {
status = RegGetValue(HKEY_LOCAL_MACHINE, _T(NPCAP_SERVICE_REGISTRY_KEY "\\Parameters"), _T("AdminOnly"), RRF_RT_REG_DWORD, NULL, &dwAdminOnlyMode, &size);
if (status != ERROR_SUCCESS) {
TRACE_PRINT1("RegGetValue(Services\\Npcap\\Parameters\\AdminOnly) failed: %#x\n", status);
}
cached = TRUE;
}
TRACE_EXIT();
return (dwAdminOnlyMode != 0);
}
static BOOL NpcapIsRunByAdmin()
{
static BOOLEAN cached = FALSE;
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 (cached) {
return bIsRunAsAdmin;
}
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;
}
cached = TRUE;
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();
SetLastError(dwError);
return bIsRunAsAdmin;
}
static 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];
const 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();
}
static void NpcapStopHelper()
{
TRACE_ENTER();
if (g_hNpcapHelperPipe != INVALID_HANDLE_VALUE)
{
CloseHandle(g_hNpcapHelperPipe);
g_hNpcapHelperPipe = INVALID_HANDLE_VALUE;
}
TRACE_EXIT();
}
/* Copies the adapter ID (GUID, or whatever comes after "NPF_" in the name) to a new string.
* Canonicalizes capitalization for the monitor-mode map (not needed otherwise).
* Returned string is a dup and must be freed.
* NpfOpenFlags will be set to an appropriate value based on any tags found (e.g. "WIFI_")
*/
_Success_(return != NULL)
_Must_inspect_result_
static PCHAR NpcapGetAdapterID(_In_ LPCSTR AdapterName, _Out_opt_ PULONG pNpfOpenFlags)
{
PCHAR outstr = NULL;
const char *src = NULL;
ULONG NpfOpenFlags = 0;
if (0 == _strnicmp(AdapterName, WINPCAP_COMPAT_DEVICE_PREFIX, sizeof(WINPCAP_COMPAT_DEVICE_PREFIX) - 1)) {
src = AdapterName + sizeof(WINPCAP_COMPAT_DEVICE_PREFIX) - 1;
}
else if (0 == _strnicmp(AdapterName, NPF_DRIVER_COMPLETE_DEVICE_PREFIX, sizeof(NPF_DRIVER_COMPLETE_DEVICE_PREFIX) - 1)) {
src = AdapterName + sizeof(NPF_DRIVER_COMPLETE_DEVICE_PREFIX) - 1;
}
else {
// Not expected format
SetLastError(ERROR_INVALID_NAME);
return NULL;
}
// Look for tags (case sensitive)
// First the most common case: no tag or it's loopback
if (src[0] == '{' || 0 == _stricmp(src, NPCAP_LOOPBACK_ADAPTER_BUILTIN)) {
;// Do nothing
}
// WIFI_ tag check
else if (0 == strncmp(src, NPF_DEVICE_NAMES_TAG_WIFI, sizeof(NPF_DEVICE_NAMES_TAG_WIFI) - 1)) {
src += sizeof(NPF_DEVICE_NAMES_TAG_WIFI) - 1;
NpfOpenFlags |= NPF_OPEN_FLAG_WIFI;
}
size_t NameLen = strnlen(AdapterName, ADAPTER_NAME_LENGTH);
if (NameLen >= ADAPTER_NAME_LENGTH) {
TRACE_PRINT("Unterminated or too-long adapter name");
SetLastError(ERROR_INVALID_NAME);
return NULL;
}
outstr = (PCHAR)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, NameLen + 1);
if (!outstr) {
TRACE_PRINT("HeapAlloc failed");
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return NULL;
}
for (UINT i=0; i <= NameLen && src[i] != '\0'; i++) {
outstr[i] = (char) toupper(src[i]);
}
if (pNpfOpenFlags != NULL) {
*pNpfOpenFlags = NpfOpenFlags;
}
return outstr;
}
/*!
\brief The main dll function.
*/
BOOL APIENTRY DllMain(HANDLE DllHandle, DWORD Reason, LPVOID lpReserved)
{
TRACE_ENTER();
PADAPTER_INFO NewAdInfo;
g_hDllHandle = DllHandle;
UNUSED(lpReserved);
switch(Reason)
{
case DLL_PROCESS_ATTACH:
TRACE_PRINT("************Packet32: DllMain************");
// 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 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));
// Get the name for "Npcap Loopback Adapter"
NpcapGetLoopbackInterfaceName();
break;
case DLL_PROCESS_DETACH:
CloseHandle(g_AdaptersInfoMutex);
while(g_AdaptersInfoList.Adapters != NULL)
{
NewAdInfo = g_AdaptersInfoList.Adapters->Next;
HeapFree(GetProcessHeap(), 0, g_AdaptersInfoList.Adapters);
g_AdaptersInfoList.Adapters = NewAdInfo;
}
// NpcapHelper De-Initialization.
NpcapStopHelper();
#ifdef WPCAP_OEM_UNLOAD_H
if(g_WoemLeaveDllH)
{
g_WoemLeaveDllH();
}
#endif // WPCAP_OEM_UNLOAD_H
break;
default:
break;
}
TRACE_EXIT();
return TRUE;
}
#ifdef LOAD_OPTIONAL_LIBRARIES
//
// 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
//
static HMODULE LoadLibrarySafe(LPCTSTR lpFileName)
{
TRACE_ENTER();
TCHAR path[MAX_PATH+1] = { 0 };
TCHAR fullFileName[MAX_PATH+1];
UINT res;
HMODULE hModule = NULL;
DWORD err = ERROR_SUCCESS;
do
{
res = GetSystemDirectory(path, MAX_PATH);
if (res == 0)
{
//
// some bad failure occurred;
//
err = GetLastError();
break;
}
if (res > MAX_PATH)
{
//
// the buffer was not big enough
//
err = (ERROR_INSUFFICIENT_BUFFER);
break;
}
if (_tcslen(lpFileName) + 1 + res + 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);
err = GetLastError();
}
else
{
err = (ERROR_INSUFFICIENT_BUFFER);
}
}while(FALSE);
TRACE_EXIT();
SetLastError(err);
return hModule;
}
/*!
\brief This function is used to dynamically load some of the libraries winpcap depends on,
and that are not guaranteed to be in the system
\param cp A string containing the address.
\return the converted 32-bit numeric address.
Doesn't check to make sure the address is valid.
*/
VOID PacketLoadLibrariesDynamically()
{
#ifdef HAVE_AIRPCAP_API
HMODULE AirpcapLib;
#endif // HAVE_AIRPCAP_API
TRACE_ENTER();
//
// Acquire the global mutex, so we wait until other threads are done
//
WaitForSingleObject(g_DynamicLibrariesMutex, INFINITE);
//
// Only the first thread should do the initialization
//
g_DynamicLibrariesLoaded++;
if(g_DynamicLibrariesLoaded != 1)
{
ReleaseMutex(g_DynamicLibrariesMutex);
TRACE_EXIT();
return;
}
#ifdef HAVE_AIRPCAP_API
/* We dinamically load the airpcap library in order link it only when it's present on the system */
if((AirpcapLib = LoadLibrarySafe(TEXT("airpcap.dll"))) == NULL)
{
// Report the error but go on
TRACE_PRINT("AirPcap library not found on this system");
}
else
{
//
// Find the exports
//
g_PAirpcapGetLastError = (AirpcapGetLastErrorHandler) GetProcAddress(AirpcapLib, "AirpcapGetLastError");
g_PAirpcapGetDeviceList = (AirpcapGetDeviceListHandler) GetProcAddress(AirpcapLib, "AirpcapGetDeviceList");
g_PAirpcapFreeDeviceList = (AirpcapFreeDeviceListHandler) GetProcAddress(AirpcapLib, "AirpcapFreeDeviceList");
g_PAirpcapOpen = (AirpcapOpenHandler) GetProcAddress(AirpcapLib, "AirpcapOpen");
g_PAirpcapClose = (AirpcapCloseHandler) GetProcAddress(AirpcapLib, "AirpcapClose");
g_PAirpcapGetLinkType = (AirpcapGetLinkTypeHandler) GetProcAddress(AirpcapLib, "AirpcapGetLinkType");
g_PAirpcapSetKernelBuffer = (AirpcapSetKernelBufferHandler) GetProcAddress(AirpcapLib, "AirpcapSetKernelBuffer");
g_PAirpcapSetFilter = (AirpcapSetFilterHandler) GetProcAddress(AirpcapLib, "AirpcapSetFilter");
g_PAirpcapSetMinToCopy = (AirpcapSetMinToCopyHandler) GetProcAddress(AirpcapLib, "AirpcapSetMinToCopy");
g_PAirpcapGetReadEvent = (AirpcapGetReadEventHandler) GetProcAddress(AirpcapLib, "AirpcapGetReadEvent");
g_PAirpcapRead = (AirpcapReadHandler) GetProcAddress(AirpcapLib, "AirpcapRead");
g_PAirpcapGetStats = (AirpcapGetStatsHandler) GetProcAddress(AirpcapLib, "AirpcapGetStats");
g_PAirpcapWrite = (AirpcapWriteHandler) GetProcAddress(AirpcapLib, "AirpcapWrite");
//
// Make sure that we found everything
//
if(g_PAirpcapGetLastError == NULL ||
g_PAirpcapGetDeviceList == NULL ||
g_PAirpcapFreeDeviceList == NULL ||
g_PAirpcapClose == NULL ||
g_PAirpcapGetLinkType == NULL ||
g_PAirpcapSetKernelBuffer == NULL ||
g_PAirpcapSetFilter == NULL ||
g_PAirpcapSetMinToCopy == NULL ||
g_PAirpcapGetReadEvent == NULL ||
g_PAirpcapRead == NULL ||
g_PAirpcapGetStats == NULL)
{
// No, something missing. A NULL g_PAirpcapOpen will disable airpcap adapters check
g_PAirpcapOpen = NULL;
}
}
#endif // HAVE_AIRPCAP_API
//
// Done. Release the mutex and return
//
ReleaseMutex(g_DynamicLibrariesMutex);
TRACE_EXIT();
return;
}
#endif
/*!
\brief Converts an UNICODE string to ASCII. Uses the WideCharToMultiByte() system function.
\param string The string to convert.
\return The converted string.
*/
_Success_(return != NULL)
_Must_inspect_result_
static PCHAR WChar2SChar(_In_ LPCWCH string)
{
PCHAR TmpStr;
TmpStr = (CHAR*) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (DWORD)(wcslen(string)+2));
if (TmpStr == NULL) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return NULL;
}
if (!WideCharToMultiByte(CP_ACP, 0, string, -1, TmpStr, (DWORD)(wcslen(string)+2), NULL, NULL)) {
DWORD err = GetLastError();
HeapFree(GetProcessHeap(), 0, TmpStr);
SetLastError(err);
return NULL;
}
return TmpStr;
}
/*!
\brief Sets the maximum possible lookahead buffer for the driver's Packet_tap() function.
\param AdapterObject Handle to the service control manager.
\return If the function succeeds, the return value is nonzero.
The lookahead buffer is the portion of packet that Packet_tap() can access from the NIC driver's memory
without performing a copy. This function tries to increase the size of that buffer.
NOTE: this function is used for NPF adapters, only.
Npcap NOTE: This may no longer be necessary. Testing required.
*/
BOOLEAN PacketSetMaxLookaheadsize (LPADAPTER AdapterObject)
{
BOOLEAN Status;
CHAR IoCtlBuffer[sizeof(PACKET_OID_DATA) + sizeof(ULONG) - 1] = { 0 };
PPACKET_OID_DATA OidData = (PPACKET_OID_DATA)IoCtlBuffer;
DWORD err = ERROR_SUCCESS;
TRACE_ENTER();
assert(!(AdapterObject->Flags & INFO_FLAG_MASK_NOT_NPF));
if (AdapterObject->Flags & INFO_FLAG_NPCAP_LOOPBACK) {
// Loopback adapter doesn't support this; fake success
TRACE_EXIT();
SetLastError(ERROR_SUCCESS);
return TRUE;
}
//set the size of the lookahead buffer to the maximum available by the the NIC driver
OidData->Oid=OID_GEN_MAXIMUM_LOOKAHEAD;
OidData->Length=sizeof(ULONG);
Status=PacketRequest(AdapterObject,FALSE,OidData);
if (!Status) {
err = GetLastError();
TRACE_EXIT();
SetLastError(err);
return FALSE;
}
OidData->Oid=OID_GEN_CURRENT_LOOKAHEAD;
Status=PacketRequest(AdapterObject,TRUE,OidData);
if (!Status) {
err = GetLastError();
}
TRACE_EXIT();
SetLastError(err);
return Status;
}
/*!
\brief Allocates the read event associated with the capture instance, passes it down to the kernel driver
and stores it in an _ADAPTER structure.
\param AdapterObject Handle to the adapter.
\return If the function succeeds, the return value is nonzero.
This function is used by PacketOpenAdapter() to allocate the read event and pass it to the driver by means of an ioctl
call and set it in the _ADAPTER structure pointed by AdapterObject.
NOTE: this function is used for NPF adapters, only.
*/
BOOLEAN PacketSetReadEvt(LPADAPTER AdapterObject)
{
DWORD BytesReturned;
HANDLE hEvent;
DWORD err = ERROR_SUCCESS;
TRACE_ENTER();
assert(!(AdapterObject->Flags & INFO_FLAG_MASK_NOT_NPF));
if (AdapterObject->ReadEvent != NULL)
{
TRACE_PRINT("ReadEvent is not NULL");
SetLastError(ERROR_INVALID_FUNCTION);
return FALSE;
}
hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (hEvent == NULL)
{
err = GetLastError();
TRACE_PRINT("Error in CreateEvent");
TRACE_EXIT();
SetLastError(err);