⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fport.cpp

📁 很多人都知道端口到进程映射的一个免费工具FoundStone的Fport
💻 CPP
字号:
// FPort.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

BOOL GetProcessModule (DWORD dwPID, DWORD dwModuleID, 
					   LPMODULEENTRY32 lpMe32, DWORD cbMe32) 
{ 
    BOOL          bRet        = FALSE; 
    BOOL          bFound      = FALSE; 
    HANDLE        hModuleSnap = NULL; 
    MODULEENTRY32 me32        = {0}; 

    hModuleSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, dwPID); 
    if (hModuleSnap == INVALID_HANDLE_VALUE) 
        return (FALSE); 

    me32.dwSize = sizeof(MODULEENTRY32); 

    if (Module32First(hModuleSnap, &me32)) 
    { 
        do 
        { 
            if (me32.th32ModuleID == dwModuleID) 
            { 
                CopyMemory (lpMe32, &me32, cbMe32); 
                bFound = TRUE; 
            } 
        } 
        while (!bFound && Module32Next(hModuleSnap, &me32)); 
		
        bRet = bFound;

    } 
    else 
        bRet = FALSE;
	
    CloseHandle (hModuleSnap); 
	
    return (bRet); 
}

PCHAR ProcessPidToName(HANDLE hProcessSnap, DWORD ProcessId, PCHAR ProcessName)
{
	PROCESSENTRY32 processEntry = { 0 };
	processEntry.dwSize = sizeof(PROCESSENTRY32); 

	lstrcpy(ProcessName, "???");
	
	if (!Process32First(hProcessSnap, &processEntry)) 
	{
		return ProcessName;
	}
	
	do 
	{
		if (processEntry.th32ProcessID == ProcessId)
		{
			MODULEENTRY32 me32       = {0}; 
			GetProcessModule(processEntry.th32ProcessID, 
					1, &me32, sizeof(MODULEENTRY32)); 
				
			if (lstrlen(me32.szExePath) != 0)
			{
				lstrcpy(ProcessName, me32.szExePath);
			}
			else
			{
				lstrcpy(ProcessName, processEntry.szExeFile);
			}
			return ProcessName;
		}
		
	} while(Process32Next(hProcessSnap, &processEntry));
	
	return ProcessName;
}

HANDLE OpenPhysicalMemory(HANDLE& hSection)
{
    NTSTATUS          status;
    UNICODE_STRING    physmemString;
    OBJECT_ATTRIBUTES attributes;
	HANDLE            hMemory;
  
    RtlInitUnicodeString(&physmemString, L"\\Device\\PhysicalMemory"); 

    InitializeObjectAttributes(&attributes, &physmemString,
		OBJ_CASE_INSENSITIVE, NULL, NULL); 

    status = ZwOpenSection(&hSection, SECTION_MAP_READ, &attributes ); 
   

	if (!NT_SUCCESS(status))	return NULL;

    hMemory = MapViewOfFile(hSection, FILE_MAP_READ,
		0, 0x30000, 0x1000);
 
    if (GetLastError() != 0)	return NULL;     
	
    return hMemory;
}

void AdjustDacl(HANDLE hProcess)
{
	SID world = { SID_REVISION,1, SECURITY_WORLD_SID_AUTHORITY, 0 }; 

	LPTSTR ptstrName   = (LPTSTR)&world;
	EXPLICIT_ACCESS ea = { STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL, SET_ACCESS, NO_INHERITANCE,
		{ 0, NO_MULTIPLE_TRUSTEE, TRUSTEE_IS_SID, TRUSTEE_IS_USER, ptstrName}};
	
	ACL * pdacl = 0;
	if (SetEntriesInAcl(1, &ea, 0, &pdacl) != ERROR_SUCCESS)
	{
		printf( "SetEntriesInAcl Error:%d", GetLastError());
	}

	if (SetSecurityInfo(hProcess, SE_KERNEL_OBJECT,
			DACL_SECURITY_INFORMATION, 0, 0, pdacl, 0) != ERROR_SUCCESS)
	{
		printf( "SetSecurityInfo Error:%d", GetLastError());
	}

	LocalFree(pdacl);
}

HANDLE OpenDeviceTcpUdp(WCHAR * deviceName)
{
    UNICODE_STRING    physmemString;
    OBJECT_ATTRIBUTES attributes;
    IO_STATUS_BLOCK   iosb;
    HANDLE            hDeviceHandle;
	
    RtlInitUnicodeString(&physmemString, deviceName);    

    if (GetLastError() != 0)	return NULL;

    InitializeObjectAttributes(&attributes, &physmemString,
		OBJ_CASE_INSENSITIVE, 0, NULL);

    NTSTATUS status = ZwOpenFile(&hDeviceHandle, 0x100000, &attributes, &iosb, 3, 0);

    if (!NT_SUCCESS(status))	return NULL;

	return hDeviceHandle;
}

PULONG GetHandleList()
{
    ULONG  cbBuffer = 0x1000;               
    PULONG pBuffer  = new ULONG[cbBuffer]; 
    NTSTATUS Status;
	
    do
	{
        Status = ZwQuerySystemInformation(
			SystemHandleInformation,
			pBuffer,
			cbBuffer * sizeof(ULONG), 
			NULL
			);
		
        if (Status == STATUS_INFO_LENGTH_MISMATCH)
        {
            delete [] pBuffer;
            pBuffer = new ULONG[cbBuffer *= 2];
        }
        else if (!NT_SUCCESS(Status))
        {
            delete [] pBuffer;
            return NULL;
        }
	}while (Status == STATUS_INFO_LENGTH_MISMATCH);

    return pBuffer;
}

PVOID GetTcpUdpObject(PULONG pBuffer, HANDLE hHandle, DWORD ProcessId)
{
	int nCount = *pBuffer;
    PSYSTEM_HANDLE_INFORMATION pProcesses = (PSYSTEM_HANDLE_INFORMATION)(pBuffer + 1);
	
    for (int i = 0; i < nCount; i++)
    {
        if (pProcesses->ProcessId == ProcessId && pProcesses->Handle == (int)hHandle)
        {
           return (PVOID)pProcesses;
		}
		pProcesses++;
	}
	return NULL;
}

BOOL GetPTE(PVOID objAddress, HANDLE hMapPhysicalMemory, HANDLE hSection, PTE& pte)
{
	DWORD dwPhysMemBuf = (DWORD)hMapPhysicalMemory, dwAddress = (DWORD)objAddress;
    LPVOID pNewMapPhy  = NULL;
	DWORD dwNewAddress = *((LPDWORD)(dwPhysMemBuf + (dwAddress >> 0x16) * 4));
	
	if ((dwNewAddress & 0x000000ff) < 0x01)
	{
		return FALSE;
	}
	if ((dwNewAddress & 0x000000ff) < 0x80)
	{
		pNewMapPhy = MapViewOfFile(hSection, 4, 0, dwNewAddress & 0xFFFFF000, 0x1000);
		dwNewAddress = (dwAddress >> 0x0c) & 0x3ff; 
		dwNewAddress = *((LPDWORD)((DWORD)pNewMapPhy + 4 * dwNewAddress)) & 0xFFFFF000;
		UnmapViewOfFile(pNewMapPhy);
		pNewMapPhy = NULL;
	}
	else
	{
		dwNewAddress = (dwNewAddress & 0xFFFFF000) + (dwAddress & 0x003ff000);
	}

	pNewMapPhy = MapViewOfFile(hSection, FILE_MAP_READ,
		0, dwNewAddress, 0x1000);

	if (pNewMapPhy == NULL)	
	{
		long lError = GetLastError();
		return FALSE;
	}
	else
	{
		memcpy(&pte, (char *)pNewMapPhy + (dwAddress & 0x00000FFF), sizeof(PTE));
	}

	UnmapViewOfFile(pNewMapPhy);
	return TRUE;
}

BOOL RaisePrivleges( HANDLE hToken, char *pPriv )
{
	TOKEN_PRIVILEGES tkp; 

	tkp.PrivilegeCount              = 1;
	tkp.Privileges[0].Attributes    = SE_PRIVILEGE_ENABLED;
	tkp.Privileges[0].Luid.HighPart = 0;
	tkp.Privileges[0].Luid.LowPart  = 0;

	if (!LookupPrivilegeValue(NULL, pPriv, &tkp.Privileges[0].Luid))
	{
		printf("LookupPrivilegeValue Error:%d\n", GetLastError()); 
		return FALSE; 
	}

	int iRet = AdjustTokenPrivileges(hToken, FALSE, &tkp, 0x10, (PTOKEN_PRIVILEGES)NULL, 0);
	if (iRet == NULL)
	{
		printf( "AdjustTokenPrivileges Error:%d\n", GetLastError());
		return TRUE;
	}
	else 
	{
		iRet = GetLastError();

		switch (iRet)
		{
		case ERROR_NOT_ALL_ASSIGNED: 
			{ 
				printf("AdjustTokenPrivileges ERROR_NOT_ALL_ASSIGNED\n" );
				return FALSE;
			}
		case ERROR_SUCCESS:       
			{ 
				return TRUE;
			}
		default:    
			{
				printf("AdjustTokenPrivileges Unknow Error:%d\n", iRet);
				return FALSE;
			}
		}
	}
}

int main(int argc, char* argv[])
{
	HANDLE hToken;
	HANDLE hTcpHandle;
	HANDLE hUdpHandle;
	HANDLE hSection;

    printf("---[ FPort, by Phiger  ]---\n");
    printf("---[ Date : 2003-12-30 ]---\n\n");
	
	HANDLE hMapPhysicalMemory = OpenPhysicalMemory(hSection);

	HANDLE hCurrentProc = GetCurrentProcess();
	
	if (!OpenProcessToken(hCurrentProc,
		TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
		&hToken))
	{
		printf( "OpenProcessToken Error:%d\n", GetLastError());
	}
	else
	{
		if (!RaisePrivleges(hToken, (char*)SE_DEBUG_NAME))
			printf( "SetPrivlegesSE_DEBUG_NAME Error:%d\n", GetLastError());
	} 
	
	if (hToken) CloseHandle(hToken); 
	
	hTcpHandle = OpenDeviceTcpUdp(L"\\Device\\TCP");
	hUdpHandle = OpenDeviceTcpUdp(L"\\Device\\UDP");

    PULONG pBuffer = GetHandleList();

	if (pBuffer == NULL)	return 0;

	PSYSTEM_HANDLE_INFORMATION objTcpAddress = NULL;
	PSYSTEM_HANDLE_INFORMATION objUdpAddress = NULL;

	objTcpAddress = (PSYSTEM_HANDLE_INFORMATION)GetTcpUdpObject(pBuffer, hTcpHandle, GetCurrentProcessId());

	PTE pteTCPCur;
	if (!GetPTE(objTcpAddress->Object, hMapPhysicalMemory, hSection, pteTCPCur))
	{
		return 0;
	}

	objUdpAddress = (PSYSTEM_HANDLE_INFORMATION)GetTcpUdpObject(pBuffer, hUdpHandle, GetCurrentProcessId());
	
	PTE pteUDPCur;
	if (!GetPTE(objUdpAddress->Object, hMapPhysicalMemory, hSection, pteUDPCur))
	{
		return 0;
	}

	OVERLAPPED    Overlap;

	HANDLE hEvent = CreateEvent(0, 1, 0, 0);
	
	Overlap.Internal     = 0;
	Overlap.InternalHigh = 0;
	Overlap.Offset       = 0;
	Overlap.OffsetHigh   = 0;
	Overlap.hEvent       = hEvent;

	HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (hProcessSnap == INVALID_HANDLE_VALUE) 
	{
		printf("Failed to take process snapshot. Process names will not be shown.\n\n");
	}	

	int nCount = *pBuffer;
    PSYSTEM_HANDLE_INFORMATION pProcesses = (PSYSTEM_HANDLE_INFORMATION)(pBuffer + 1);

    for (int i = 0; i < nCount; i++)
    {
		if (pProcesses->ObjectTypeNumber == objTcpAddress->ObjectTypeNumber)
		{
			PTE pte;
			if (!GetPTE(pProcesses->Object, hMapPhysicalMemory, hSection, pte))
			{
				pProcesses++;
				continue;
			}

			if ((pte.NoCache == 1 || pte.NoCache == 2) &&
				(pteTCPCur.WriteTable == pte.WriteTable))
			{
				HANDLE hProc = NULL, DupHandle=NULL;
				int  i = 0, portflag = 0;
				u_short openport;
				
				hProc = OpenProcess(PROCESS_DUP_HANDLE,
					0,
					pProcesses->ProcessId);

				if (hProc)
				{
					DuplicateHandle(hProc,
						(HANDLE)pProcesses->Handle,
						GetCurrentProcess(),
						&DupHandle,
						0,
						FALSE,
						2);

					CloseHandle(hProc);

					if (DupHandle)
					{
						TDI_CONNECTION_INFO    TdiConnInfo={0};
						TDI_CONNECTION_INFORMATION TdiConnInformation = {0};
						DWORD dwRetu=0;    
						
						if (pte.NoCache == 0x02)
						{
							TdiConnInformation.RemoteAddressLength = 4; 
							if (DeviceIoControl(
								DupHandle,
								0x210012,
								&TdiConnInformation,
								sizeof(TdiConnInformation),
								&TdiConnInfo,
								sizeof(TdiConnInfo),
								NULL,
								&Overlap))
							{	
								char szProcName[256];
								openport = ntohs((u_short)TdiConnInfo.ReceivedTsdus);
								if (openport != 0)
								{
									printf("TCP  PID = %4d PORT = %6d %s\n", pProcesses->ProcessId, openport, ProcessPidToName(hProcessSnap, pProcesses->ProcessId, szProcName));
								}
							}
							else
							{
								long lError = GetLastError();
							}
						}
						else if (pte.NoCache == 0x01)
						{
							TdiConnInformation.RemoteAddressLength = 3; 
							if (DeviceIoControl(DupHandle, 0x210012,
								&TdiConnInformation, sizeof(TdiConnInformation),
								&TdiConnInfo, sizeof(TdiConnInfo),
								NULL, &Overlap))
							{
								char szProcName[256];
								openport = ntohs((u_short)TdiConnInfo.ReceivedTsdus);
								if (openport != 0)
								{
									printf("TCP  PID = %4d PORT = %6d  %s\n", pProcesses->ProcessId, openport, ProcessPidToName(hProcessSnap, pProcesses->ProcessId, szProcName));
								}
							}
							else
							{
								long lError = GetLastError();
							}
						}
						CloseHandle(DupHandle);
					}
				}
			}
		}
		pProcesses++;
	}

	nCount = *pBuffer;
    pProcesses = (PSYSTEM_HANDLE_INFORMATION)(pBuffer + 1);
	
    for (i = 0; i < nCount; i++)
    {
		if (pProcesses->ObjectTypeNumber == objUdpAddress->ObjectTypeNumber)
		{
			PTE pte;
			if (!GetPTE(pProcesses->Object, hMapPhysicalMemory, hSection, pte))
			{
				pProcesses++;
				continue;
			}
			
			if ((pte.NoCache == 1 || pte.NoCache == 2) &&
				(pteUDPCur.WriteTable == pte.WriteTable))
			{
				HANDLE hProc = NULL, DupHandle=NULL;
				int  i = 0, portflag = 0;
				u_short openport;
				
				hProc = OpenProcess(PROCESS_DUP_HANDLE,
					0,
					pProcesses->ProcessId);
				
				if (hProc)
				{
					DuplicateHandle(hProc,
						(HANDLE)pProcesses->Handle,
						GetCurrentProcess(),
						&DupHandle,
						0,
						FALSE,
						2);
					
					CloseHandle(hProc);
					
					if (DupHandle)
					{
						TDI_CONNECTION_INFO    TdiConnInfo={0};
						TDI_CONNECTION_INFORMATION TdiConnInformation = {0};
						DWORD dwRetu=0;    
						
						if (pte.NoCache == 0x02)
						{
							TdiConnInformation.RemoteAddressLength = 4; 
							if (DeviceIoControl(
								DupHandle,
								0x210012,
								&TdiConnInformation,
								sizeof(TdiConnInformation),
								&TdiConnInfo,
								sizeof(TdiConnInfo),
								NULL,
								&Overlap))
							{
								char szProcName[256];								
								openport = ntohs((u_short)TdiConnInfo.ReceivedTsdus);
								if (openport != 0)
								{
									printf("UDP  PID = %4d PORT = %6d  %s\n", pProcesses->ProcessId, openport, ProcessPidToName(hProcessSnap, pProcesses->ProcessId, szProcName));
								}
							}
							else
							{
								long lError = GetLastError();
							}
						}
						else if (pte.NoCache == 0x01)
						{
							TdiConnInformation.RemoteAddressLength = 3; 
							if (DeviceIoControl(DupHandle, 0x210012,
								&TdiConnInformation, sizeof(TdiConnInformation),
								&TdiConnInfo, sizeof(TdiConnInfo),
								NULL, &Overlap))
							{
								char szProcName[256];
								openport = ntohs((u_short)TdiConnInfo.ReceivedTsdus);
								if (openport != 0)
								{
									printf("UDP  PID = %4d PORT = %6d  %s\n", pProcesses->ProcessId, openport, ProcessPidToName(hProcessSnap, pProcesses->ProcessId, szProcName));
								}
							}
							else
							{
								long lError = GetLastError();
							}
						}
						CloseHandle(DupHandle);
					}
				}
			}
		}
		pProcesses++;
	}

	CloseHandle(hEvent);
	CloseHandle(hProcessSnap);
	
	return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -