
![]() |
Наши проекты:
Журнал · Discuz!ML · Wiki · DRKB · Помощь проекту |
|
ПРАВИЛА | FAQ | Помощь | Поиск | Участники | Календарь | Избранное | RSS |
[216.73.216.207] |
![]() |
|
Страницы: (9) [1] 2 3 ... 8 9 все ( Перейти к последнему сообщению ) |
Сообщ.
#1
,
|
|
|
Как можно отловить процесс удаление файлов под windows, и если можно запретить програмно удаление файлов некоторого типа или просто нескольких произвольных файлов. Например при запущеной программе, при попытке удаления файла или папки выведется msgbox c надписью "не тронь!".
|
Сообщ.
#2
,
|
|
|
Нужно перехватить АПИшную функцию DeleteFile()...
|
Сообщ.
#3
,
|
|
|
А можно ,пожалуйста, простенький примерчик.
|
Сообщ.
#4
,
|
|
|
Для контроля одного процесса я могу подкинуть, а вот для всей системы вцелом, наверное, .alex даст =) мэй би
|
Сообщ.
#5
,
|
|
|
Ну дайти тогда хотябы для одного процесса.
|
Сообщ.
#6
,
|
|
|
С те бя идет!
DLL: ![]() ![]() library Mouse_mes; uses sysutils, windows, messages; type TImageImportDescriptor=packed record OriginalFirstThunk : DWORD; TimeDateStamp : DWORD; ForwarderChain : DWORD; Name : DWORD; FirstThunk : DWORD; end; PImageImportDescriptor=^TImageImportDescriptor; var filename:array[0..max_path-1] of char; hook:HHook=0; PEHeader:PImageNtHeaders; ImageBase:cardinal; function MyHookProcedure(hWnd: HWND; lpText, lpCaption: PWideChar; uType: UINT): Integer; stdcall; begin result:=MessageBoxA(0, 'Notepad', 'my hook', 0); //Но уже через нашу табл. импорта end; procedure ProcessImports(PImports:PImageImportDescriptor); Var PImport:PImageImportDescriptor; PRVA_Import:LPDWORD; ProcAddress:pointer; Temp_Cardinal:cardinal; begin{1} ProcAddress:=GetProcAddress(GetModuleHandle('USER32.DLL'), 'MessageBoxA'); PImport:=PImports; while PImport.Name<>0 do begin{2} PRVA_Import:=LPDWORD(pImport.FirstThunk+ImageBase); while PRVA_Import^<>0 do begin{3} if PPointer(PRVA_Import)^=ProcAddress then begin{4} VirtualProtect(PPointer(PRVA_Import),4,PAGE_READWRITE,Temp_Cardinal); PPointer(PRVA_Import)^:=@MyHookProcedure; //пишем свою... VirtualProtect(PPointer(PRVA_Import),4,Temp_Cardinal,Temp_Cardinal); end;{1} Inc(PRVA_Import); end;{2} Inc(PImport); end;{3} end;{4} procedure DllEntryPoint(reson:longint);stdcall; begin case reson of DLL_PROCESS_ATTACH: begin DisableThreadLibraryCalls(hInstance); ZeroMemory(@FileName, SizeOf(FileName)); GetModuleFileName(GetModuleHandle(nil), @FileName, SizeOf(FileName)); if Pos('NOTEPAD.EXE',AnsiUpper(@FileName))<>0 then //сейчас я хочу попробовать все это дело надо нотепадом begin ImageBase:=GetModuleHandle(nil); PEHeader:=pointer(int64(ImageBase)+PImageDosHeader(ImageBase)._lfanew);//pe header ProcessImports(pointer(PEHeader.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress+ImageBase)); end; end; end; end; function nexthook(code:integer;wParam,lParam:longint):longint;stdcall; begin result:=callnexthookex(hook,code,wParam,lParam); end; procedure sethook(flag:bool);export; stdcall; begin if flag then hook:=setwindowshookex(wh_getmessage,@nexthook,hInstance,0) else begin unhookwindowshookex(hook); hook:=0; end; end; exports sethook; begin DLLProc:=@DllEntryPoint; DllEntryPoint(DLL_PROCESS_ATTACH) end. EXE: ![]() ![]() program Project2; uses windows; var sethook:procedure(flag:bool)stdcall; hDll:hModule; begin hDll:=LoadLibrary('Mouse_mes.dll'); @sethook:=GetProcAddress(hDll, 'sethook'); sethook(true); messagebox(0,'Не закрывай, пока идет работа','',0); sethook(false); FreeLibrary(hDll); end. Думаю сам разберешься, что там надо заменить, если что то спрашивай и готовь .... ээээ ммм, ладно шутю =) |
Сообщ.
#7
,
|
|
|
Цитата xZero, 4.01.04, 20:25 и готовь .... ээээ ммм, ладно шутю =) Да правильно-правильно, пусть готовит ![]() |
Сообщ.
#8
,
|
|
|
А можно ли не просто отловить процесс, а еще и запретить его выполнение. Кстати а в каком модуле лежит эта замечательная функция DeleteFile?
Готовлю! ![]() |
Сообщ.
#9
,
|
|
|
![]() ![]() function DeleteFile(const FileName: string): Boolean; begin {$IFDEF MSWINDOWS} Result := Windows.DeleteFile(PChar(FileName)); {$ENDIF} {$IFDEF LINUX} Result := remove(PChar(FileName)) <> -1; {$ENDIF} end; Прости, не понял что надо! Если хочешь остановить процесс - Terminate используй! Добавлено в : ![]() ![]() const {$IFDEF MSWINDOWS} advapi32 = 'advapi32.dll'; kernel32 = 'kernel32.dll'; mpr = 'mpr.dll'; {$EXTERNALSYM version} version = 'version.dll'; comctl32 = 'comctl32.dll'; gdi32 = 'gdi32.dll'; opengl32 = 'opengl32.dll'; user32 = 'user32.dll'; wintrust = 'wintrust.dll'; msimg32 = 'msimg32.dll'; function DeleteFile; external kernel32 name 'DeleteFileA'; Отсюда точно понятно где храгится. |
Сообщ.
#10
,
|
|
|
А если я прокручу эту функцию для всех текущих процессов, у меня компютер не задымится, или она не требует много ресурсов?
И как поступить с Terminate? Application.Terminate; - понимаю, а здесь как? |
Сообщ.
#11
,
|
|
|
Я че-то немогу понять - что тебе надо?
Ты хочешь убить какой-то процесс? Если да, то используй ![]() ![]() TerminateProcess The TerminateProcess function terminates the specified process and all of its threads. BOOL TerminateProcess( HANDLE hProcess, // handle to the process UINT uExitCode // exit code for the process ); Parameters hProcess Handle to the process to terminate. Windows NT: The handle must have PROCESS_TERMINATE access. uExitCode Specifies the exit code for the process and for all threads terminated as a result of this call. Use the GetExitCodeProcess function to retrieve the process's exit value. Use the GetExitCodeThread function to retrieve a thread's exit value. Return Values If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError. Remarks The TerminateProcess function is used to unconditionally cause a process to exit. Use it only in extreme circumstances. The state of global data maintained by dynamic-link libraries (DLLs) may be compromised if TerminateProcess is used rather than ExitProcess. TerminateProcess causes all threads within a process to terminate, and causes a process to exit, but DLLs attached to the process are not notified that the process is terminating. Terminating a process causes the following: All of the object handles opened by the process are closed. All of the threads in the process terminate their execution. The state of the process object becomes signaled, satisfying any threads that had been waiting for the process to terminate. The states of all threads of the process become signaled, satisfying any threads that had been waiting for the threads to terminate. The termination status of the process changes from STILL_ACTIVE to the exit value of the process. Terminating a process does not cause child processes to be terminated. Terminating a process does not necessarily remove the process object from the system. A process object is deleted when the last handle to the process is closed. Windows CE: Windows CE does not support exit codes for processes, so the uExitCode parameter is ignored. QuickInfo Windows NT: Requires version 3.1 or later. Windows: Requires Windows 95 or later. Windows CE: Requires version 1.0 or later. Header: Declared in winbase.h. Import Library: Use kernel32.lib. Или ты имел в виду что-то другое?! |
Сообщ.
#12
,
|
|
|
Цитата xZero, 4.01.04, 19:09 а вот для всей системы вцелом, наверное, .alex даст =) мэй би Просто в длл не делай проверку на то, что это notepad.exe, вот и будет тебе для всей системы. Хотя комп децл залипать будет ![]() |
Сообщ.
#13
,
|
|
|
.alex, кинь мне.
|
Сообщ.
#14
,
|
|
|
Да мне для Melleniuma хватит, я не хочу писать супер прогу, я всего лишь хочу защитить мой компьютер от друзей, которые скоро соберутся у меня и будут тыкать на все подряд, но без компьютера тоже незьзя, музыка вся там -> скучно будет. Вот по этому Вас и мучаю вопросами.
И всеже я не понял как похоронить этот процесс. Ну например как нам получить Handle процесса удаления файла? И кстати при удалении папки с файлами система использует этуже функцию многократно или нет, может у нее есть другие способы, а то они и папками покосить могут. И разве мы не перехватываем удаление в Kernel32.dll или я что-то путаю? |
Сообщ.
#15
,
|
|
|
Сам не пробовал! Попробуй как сказал .alex убрать проверку на имя файла, и переоформи мою MyHookProc для DeleteFile (например), а резалт оставь пустой.
Мне кажется для твоих целей можно придумать что то не такое извращенское!!! |