5 Star 1 Fork 5

肖子衿/software_security

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
for_file.cpp 16.69 KB
一键复制 编辑 原始数据 按行查看 历史
周愈轩 提交于 2024-02-28 09:10 . add for_file.cpp.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
#include "pch.h"
#include "framework.h"
#include "stdio.h"
#include "stdarg.h"
#include "windows.h"
#include "nlohmann/json.hpp"
#include "detour/detours.h"
#include "libcurl/include/curl/curl.h"
#include "base64.h"
#include <iostream>
#include <string>
#include <stdlib.h>
#include <unordered_map>
#include <WinSock2.h>
#include <set>
#pragma comment(lib, "wldap32.lib")
#pragma comment(lib, "crypt32.lib")
#pragma comment(lib, "advapi32.lib")
#pragma comment(lib, "winmm.lib")
#pragma comment(lib, "Normaliz.lib")
#pragma comment(lib, "libcurl/lib/libcurl_a_debug.lib")
#pragma comment(lib, "detour/detours.lib")
#pragma comment(lib, "ws2_32.lib") //加载 ws2_32.dll
//共享数据:
#pragma data_seg("MySeg")
char seg[1000][256] = {};
char seg2[1000][256] = {};
int count = 0;
int count2 = 0;
volatile int HeapAllocnum = 0;
volatile int HeapAllocnum2 = 0;
#pragma data_seg()
#pragma comment(linker,"/section:MySeg,RWS")
#define ChangeSeg(shape)\
do{\
mtx.lock();\
count++;\
if(count>=1000)\
{count--;}\
else\
{\
sprintf(seg[count] , shape); }\
mtx.unlock();\
} while (0)
#define ChangeSeg2(shape)\
do{\
mtx.lock();\
count2++;\
if(count2>=1000)\
{count2--;}\
else\
{\
sprintf(seg2[count2] , shape); }\
mtx.unlock();\
} while (0)
#define StrChange(shape)\
do{\
std::stringstream ss;\
ss<<shape;\
str=ss.str();\
}while(0)
using json = nlohmann::json;
using namespace std;
const int APINUM = 22;
//set<int> isExistedHeapHandler;
map<int, int> isExistedHeapHandler;
SYSTEMTIME st;
void attachAllDetours();
void detachAllDetours();
int sendApiInformation(json&);
/* File Handling */
/* CreateFile (the same as CreateFileW) */
int Find_Last_X(char* Name)
{
//ChangeSeg("Find_Last_X start\r\r\n");
for (int i = GetLen(Name); i > 0; i--)
{
if (Name[i] == '\\')
{
return i;
}
}
}
int Find_Last_Point(char* Name)
{
//ChangeSeg("Find_Last_X start\r\r\n");
for (int i = GetLen(Name); i > 0; i--)
{
if (Name[i] == '.')
{
return i;
}
}
}
void GetFileName(char* Name)
{
int n = 0;
int length = GetLen(Name);
for (int i = Find_Last_X(Name) + 1; i < length; i++)
{
CrtName[nx][n++] = Name[i];
}
CrtName[nx][n] = '\0';
ChangeSeg2("\r\nIniName is OK:");
ChangeSeg2(CrtName[nx]);//无法输出;
nx++;
}
int M_StrCmp(char* A, char* B) {
int i = 0;
if (GetLen(A) != GetLen(B)) return 0;
while (A[i] != '\0') {
if (A[i] != B[i]) return 0;
i++;
}
return 1;
}//一样返回1,不一样返回0
void Copy_or_Not()
{
int flag = 0;
for (int i = 0; i < nx; i++)
{
for (int j = i + 1; j < nx; j++)
{
if (M_StrCmp(CrtName[i], CrtName[j]) == 1)
{
flag = 1;
ChangeSeg2("存在自我复制,文件名为:");
StrChange(CrtName[i]);
ChangeSeg2(str.data());
ChangeSeg2("\r\n");
}
}
}
if (!flag)
ChangeSeg2("迄今为止未检测到自我复制\r\n");
}
void IniName(char* pchar)
{
//ChangeSeg("IniPath is working\r\r\n\r\r\n");
ChangeSeg2("IniAbsPath is:");
ChangeSeg2(pchar);
GetFileName(pchar);
return;
}
//写入共享数据
int GetLen(char* Name)
{
int i = 0;
int res = 0;
while (Name[i] != '\0')
{
res++;
i++;
}
return res;
}
void MultiPath_or_Not()
{
if (mx > 1)
{
ChangeSeg2("存在多个路径,所有路径如下:\r\n");
for (int i = 0; i < mx; i++)
{
ChangeSeg2(FilePath[i]);
ChangeSeg2("\r\n");
}
}
else
{
ChangeSeg2("没有多个文件夹");
}
}
void SelfCopy_or_Not()
{
ChangeSeg2("所有文件名如下:\r\n");
for (int i = 0; i < nx; i++)
{
ChangeSeg2(CrtName[i]);
ChangeSeg2("\r\n");
}
Copy_or_Not();
ChangeSeg2("\r\n");
}
int t = 0;
static HANDLE(WINAPI* OldCreateFile)
(
LPCTSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile
) = CreateFile;
extern "C" __declspec(dllexport)HANDLE WINAPI NewCreateFile(
LPCTSTR lpFileName,
//文件名
DWORD dwDesiredAccess,
// 访问模式
DWORD dwShareMode,
// 共享模式
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
// 安全属性(也即销毁方式)
DWORD dwCreationDisposition,
// / how to create
DWORD dwFlagsAndAttributes,
//文件属性
HANDLE hTemplateFile
//模板文件句柄
)
{
ChangeSeg("\r\n\r\n * ***************************************\r\n");
ChangeSeg("CreateFile Hooked\r\n");
// HANDLE hHeapx = OldCreateFile(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
// GetFileNameFromHandle(hHeapx);
// ChangeSeg("我是下一行\r\n");
//hTemplateFile
GetLocalTime(&st);
Dllprint(st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
//printf("DLL日志输出: %d-%d-%d %02d: %02d: %02d: %03d\r\n", st.wYear,st.wMonth,st.wDay, st.wHour, st.wMinute,st.wSecond, st.wMilliseconds);
int num = WideCharToMultiByte(CP_OEMCP, NULL, lpFileName, -1, NULL, 0, NULL, FALSE);
//int num = WideCharToMultiByte(CP_0EMCP, NULL, lpFileName, -1, NULL, 0, NULL, FALSE);
char* pchar = new char[num];
WideCharToMultiByte(CP_OEMCP, NULL, lpFileName, -1, pchar, num, NULL, FALSE);
IniName(pchar);
IniPath(pchar);
//ChangeSeg("\r\n");
ChangeSeg(pchar);
ChangeSeg("\r\n");
WCHAR szFileName[_MAX_PATH];
memset(szFileName, 0, sizeof(szFileName));
GetModuleFileName(GetModuleHandle(NULL), szFileName, _MAX_PATH);
char CurrentExeName[1000];
sprintf(CurrentExeName, "%ws", szFileName);
Itemprint(CurrentExeName, str);
/*ChangeSeg("回到函数中\r\n");
char a[10][5];
a[0][0] = 'a';
a[0][1] = 'b';
a[0][2] = '\0';
ChangeSeg(a[0]);
ChangeSeg("try is ok\r\n");*/
// ChangeSeg(CrtPath[0]);
Itemprint(dwDesiredAccess, str);
Itemprint(dwShareMode, str);
Itemprint(lpSecurityAttributes, str);
Itemprint(dwCreationDisposition, str);
Itemprint(dwFlagsAndAttributes, str);
Itemprint(hTemplateFile, str);
/* std::cout << "1pFileName :" << pchar << std::endl;
std::cout << "dwDesiredAccess :0x" << std::hex << dwDesiredAccess << std::endl;
std::cout << "dwShareMode : 0x" << std::hex << dwShareMode << std::endl;
std::cout << "lpSecurityAttributes : 0x" << std::hex << lpSecurityAttributes << std::endl;
std::cout << "dwCreationDispositon : 0x" << std::hex << dwCreationDisposition << std::endl;
std::cout << "dwFlagsAndAttributes : 0x" << std::hex << dwFlagsAndAttributes << std::endl;
std::cout << "hTemplateFile : 0x" << std::hex << hTemplateFile << std::endl;*/
ChangeSeg(" *************************************\r\n\r\n");
return OldCreateFile(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
}
unordered_map<wstring, pair<time_t, size_t>> fileAttributes; // 用于存储文件属性信息
// 新的 CreateFile 函数 检测是否自我复制,这里似乎用不到,两种不同的实现路径
extern "C" __declspec(dllexport) HANDLE WINAPI NewCreateFileSelf(
LPCWSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile
) {
HANDLE hFile = OldCreateFile(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
// 检查文件是否磁盘文件
if (GetFileType(hFile) == FILE_TYPE_DISK) {
// 获取文件属性
WIN32_FILE_ATTRIBUTE_DATA fileData;
if (GetFileAttributesEx(lpFileName, GetFileExInfoStandard, &fileData)) {
// 检查文件是否已存在
if (fileAttributes.find(lpFileName) != fileAttributes.end()) {
// 比较文件的大小和创建时间
if (fileAttributes[lpFileName].second == fileData.nFileSizeLow && fileAttributes[lpFileName].first == fileData.ftCreationTime.dwLowDateTime) {
// 文件自我复制事件
wcout << L"Detected self-replication of file: " << lpFileName << endl;
// 可以将事件信息记录到日志文件或发送到远程服务器
}
} else {
// 添加文件属性信息
fileAttributes[lpFileName] = make_pair(fileData.ftCreationTime.dwLowDateTime, fileData.nFileSizeLow);
}
}
}
return hFile;
}
/* OpenFile
* 如果函数成功,返回值指定一个文件句柄
* 如果函数失败,返回值为HFILE_ERROR
*/
static HFILE(WINAPI* OldOpenFile)(LPCSTR lpFileName, LPOFSTRUCT lpReOpenBuff, UINT uStyle) = OpenFile;
extern "C" __declspec(dllexport) HFILE WINAPI NewOpenFile(
LPCSTR lpFileName, //指向文件名的指针
LPOFSTRUCT lpReOpenBuff, //指向缓冲区的文件信息
UINT uStyle //动作和属性
)
{
detachAllDetours();
auto hFile = OldOpenFile(lpFileName, lpReOpenBuff, uStyle);
json info;
info["OpenFile"]["Name"] = "OpenFile";
info["OpenFile"]["lpFileName"] = string(lpFileName);
char tmp[20];
sprintf_s(tmp, "%08X", lpReOpenBuff);
info["OpenFile"]["lpReOpenBuff"] = string("0x") + string(tmp);
info["OpenFile"]["uStyle"] = uStyle;
if (hFile == HFILE_ERROR) {
info["OpenFile"]["return"] = "HFILE_ERROR";
info["OpenFile"]["err"] = GetLastError();
}
else {
info["OpenFile"]["return"] = hFile;
info["OpenFile"]["err"] = NULL;
}
sendApiInformation(info);
attachAllDetours();
return hFile;
}
static BOOL(WINAPI* OldCloseHandle)(HANDLE hObject) = CloseHandle;
extern "C" __declspec(dllexport) BOOL WINAPI NewCloseHandle(HANDLE hObject) {
BOOL result = OldCloseHandle(hObject);
if (GetFileType(hObject) != FILE_TYPE_DISK)
return result;
json info;
info["CloseHandle"]["Name"] = "CloseHandle";
char tmp[20];
sprintf_s(tmp, "%08X", hObject);
info["CloseHandle"]["hObject"] = string("0x") + string(tmp);
info["CloseHandle"]["return"] = result;
if (result == 0) {
info["CloseHandle"]["err"] = GetLastError();
}
else {
info["CloseHandle"]["err"] = "NULL";
}
sendApiInformation(info);
return result;
}
static BOOL(WINAPI* OldReadFile)(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped) = ReadFile;
extern "C" __declspec(dllexport) BOOL WINAPI NewReadFile(
HANDLE hFile, //要处理的文件
LPVOID lpBuffer, //接收数据的缓冲区的地址
DWORD nNumberOfBytesToRead, //要读取的字节数
LPDWORD lpNumberOfBytesRead, //读取的字节数的地址,指向读取的字节数
LPOVERLAPPED lpOverlapped //数据结构的地址
) {
detachAllDetours();
auto result = OldReadFile(hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped);
if (GetFileType(hFile) != FILE_TYPE_DISK)
return result;
json info;
info["ReadFile"]["Name"] = "ReadFile";
char tmp[20];
sprintf_s(tmp, "%08X", hFile);
info["ReadFile"]["hFile"] = string("0x") + string(tmp);
sprintf_s(tmp, "%08X", lpBuffer);
info["ReadFile"]["lpBuffer"] = string("0x") + string(tmp);//要读取的字节数
info["ReadFile"]["nNumberOfBytesToRead"] = nNumberOfBytesToRead;
//if (lpNumberOfBytesRead != NULL) {
// info["ReadFile"]["ReadFile"]["lpNumberOfBytesReadValue"] = *lpNumberOfBytesRead;
// info["ReadFile"]["ReadFile"]["lpBufferValue"] = base64_encode((const unsigned char*)lpBuffer, (unsigned int)*lpNumberOfBytesRead);
//}
//else {
// info["ReadFile"]["lpNumberOfBytesReadValue"] = 0;
// info["ReadFile"]["lpBufferValue"] = NULL;
//}
info["ReadFile"]["lpOverlapped"] = int(lpOverlapped);
info["ReadFile"]["return"] = result;
if (result == FALSE) {
info["ReadFile"]["errorCode"] = GetLastError();
}
else {
info["ReadFile"]["err"] = "NULL";
}
sendApiInformation(info);
attachAllDetours();
return result;
}
static BOOL(WINAPI* OldWriteFile)(HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped) = WriteFile;
extern "C" __declspec(dllexport) BOOL WINAPI NewWriteFile(
HANDLE hFile, //处理要写入的文件
LPCVOID lpBuffer, //指向要写入文件的数据的指针
DWORD nNumberOfBytesToWrite, //要写入的字节数
LPDWORD lpNumberOfBytesWritten, //指向写入字节数的指针
LPOVERLAPPED lpOverlapped //指向重叠 I/O 所需的结构的指针
) {
detachAllDetours();
BOOL result = OldWriteFile(hFile, lpBuffer, nNumberOfBytesToWrite, lpNumberOfBytesWritten, lpOverlapped);
if (GetFileType(hFile) != FILE_TYPE_DISK)
return result;
json info;
info["WriteFile"]["Name"] = "WriteFile";
char tmp[20];
sprintf_s(tmp, "%08X", hFile);
info["WriteFile"]["hFile"] = string("0x") + string(tmp);
sprintf_s(tmp, "%08X", lpBuffer);
info["WriteFile"]["lpBuffer"] = string("0x") + string(tmp);
info["WriteFile"]["nNumberOfBytesToWrite"] = nNumberOfBytesToWrite;
sprintf_s(tmp, "%08X", lpNumberOfBytesWritten);
info["WriteFile"]["lpNumberOfBytesWritten"] = string("0x") + string(tmp);
info["WriteFile"]["lpOverlapped"] = int(lpOverlapped);
info["WriteFile"]["return"] = result;
if (result == FALSE) {
info["WriteFile"]["err"] = GetLastError();
}
else if (nNumberOfBytesToWrite==5) {
info["WriteFile"]["err"] = "Try to change .exe file";
}
else if (nNumberOfBytesToWrite == 6) {
info["WriteFile"]["err"] = "Try to change .dll file";
}
else if (nNumberOfBytesToWrite == 7) {
info["WriteFile"]["err"] = "Try to change .ocx file";
}
else {
info["WriteFile"]["err"] = "NULL";
}
sendApiInformation(info);
attachAllDetours();
return result;
}
static BOOL(WINAPI* OldBeep)(DWORD dwFreq, DWORD dwDuration) = Beep;
extern "C" __declspec(dllexport)BOOL WINAPI NewBeep(DWORD dwFreq, DWORD dwDuration) {
ChangeSeg2(" *************************************\r\n\r\n");
ChangeSeg2("\r\n\r\n***********************\r\n");
ChangeSeg2("判断是否复制:\r\n");
SelfCopy_or_Not();
ChangeSeg2("判断是否存在多文件夹:\r\n");
MultiPath_or_Not();
return OldBeep(dwFreq, dwDuration);
}
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
char module_filename[MAX_PATH];
GetModuleFileNameA(NULL, module_filename, MAX_PATH);
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH: {DisableThreadLibraryCalls(hModule);
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
// DetourAttach(&(PVOID&)OldMessageBoxW, NewMessageBoxW);
// DetourAttach(&(PVOID&)OldMessageBoxA, NewMessageBoxA);
DetourAttach(&(PVOID&)OldCreateFile, NewCreateFile);
DetourAttach(&(PVOID&)OldWriteFile, NewWriteFile);
DetourAttach(&(PVOID&)OldCloseHandle, NewCloseHandle);
DetourAttach(&(PVOID&)OldReadFile, NewReadFile);
DetourAttach(&(PVOID&)OldBeep, NewBeep);
DetourTransactionCommit();
break;
}
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH: {
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
ChangeSeg2("\r\n***********************\r\n");
ChangeSeg2("复制检测:\r\n");
SelfCopy_or_Not();
ChangeSeg2("多文件夹检测:\r\n");
MultiPath_or_Not();
// DetourDetach(&(PVOID&)OldMessageBoxW, NewMessageBoxW);
// DetourDetach(&(PVOID&)OldMessageBoxA, NewMessageBoxA);
DetourDetach(&(PVOID&)OldCreateFile, NewCreateFile);
DetourDetach(&(PVOID&)OldWriteFile, NewWriteFile);
DetourDetach(&(PVOID&)OldCloseHandle, NewCloseHandle);
DetourDetach(&(PVOID&)OldReadFile, NewReadFile);
DetourDetach(&(PVOID&)OldBeep, NewBeep);
DetourTransactionCommit();
//ChangeSeg("over\n");
break;
}
}
return TRUE;
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/xia_ziyan/software_security.git
git@gitee.com:xia_ziyan/software_security.git
xia_ziyan
software_security
software_security
master

搜索帮助

23e8dbc6 1850385 7e0993f3 1850385