Имя пользователя:
Пароль:  
Помощь | Регистрация | Забыли пароль?  

Показать сообщение отдельно

Аватара для El Sanchez

Ветеран


Contributor


Сообщения: 1217
Благодарности: 955

Профиль | Отправить PM | Цитировать


Цитата Nordek:
El Sanchez, Поправь код в #1361 сообщении.
Там отсутствует: »
Nordek, я, пожалуй, его совсем заменю, т.к. содержит ошибки: не проверяется первый процесс из слепка процессов (некритично); ненужный VirtualAllocEx (некритично); неверная декларация GetProcAddress, из-за чего не отработало бы закрытие процесса по истечении таймаута (критично).
читать дальше »

Код: Выделить весь код
[Code]
#define A = (Defined UNICODE) ? "W" : "A"
const
    TH32CS_SNAPPROCESS = $2;
    INVALID_HANDLE_VALUE = -1;
    PROCESS_TERMINATE = $1;
    PROCESS_CREATE_THREAD = $2;
    PROCESS_QUERY_INFORMATION = $400;
    SYNCHRONIZE = $100000;
    TOKEN_QUERY = $8;
    TOKEN_ADJUST_PRIVILEGES = $20;
    SE_PRIVILEGE_ENABLED = $2;
    TA_FAILED = 0;
    TA_SUCCESS_CLEAN = 1;
    TA_SUCCESS_KILL = 2;
    WM_CLOSE = $10;
    WAIT_OBJECT_0 = $0;
    WAIT_TIMEOUT = $102;
    WAIT_FAILED = $FFFFFFFF;
    SMTO_BLOCK = $1;
    SMTO_ABORTIFHUNG = $2;

type
    TPROCESSENTRY32 = record
        dwSize, cntUsage, th32ProcessID: DWORD;
        th32DefaultHeapID: Longint;
        th32ModuleID, cntThreads, th32ParentProcessID: DWORD;
        pcPriClassBase: Longint;
        dwFlags: DWORD;
        szExeFile: array [0..259] of Char;
    end;

    LUID = record
        LowPart: DWORD;
        HighPart: Longint;
    end;

    LUID_AND_ATTRIBUTES = record
        Luid: LUID;
        Attributes: DWORD;
    end;

    TOKEN_PRIVILEGES = record
        PrivilegeCount: DWORD;
        Privileges: array [0..0] of LUID_AND_ATTRIBUTES;
    end;

function CreateToolhelp32Snapshot(dwFlags, th32ProcessID: DWORD): THandle; external 'CreateToolhelp32Snapshot@kernel32.dll stdcall';
#ifdef UNICODE
function Process32First(hSnapshot: THandle; var lppe: TPROCESSENTRY32): Boolean; external 'Process32First{#A}@kernel32.dll stdcall';
function Process32Next(hSnapshot: THandle; var lppe: TPROCESSENTRY32): Boolean; external 'Process32Next{#A}@kernel32.dll stdcall';
#else
function Process32First(hSnapshot: THandle; var lppe: TPROCESSENTRY32): Boolean; external 'Process32First@kernel32.dll stdcall';
function Process32Next(hSnapshot: THandle; var lppe: TPROCESSENTRY32): Boolean; external 'Process32Next@kernel32.dll stdcall';
#endif
function OpenProcess(dwDesiredAccess: DWORD; bInheritHandle: BOOL; dwProcessId: DWORD): THandle; external 'OpenProcess@kernel32.dll stdcall';
function OpenProcessToken(ProcessHandle: THandle; DesiredAccess: DWORD; var TokenHandle: THandle): BOOL; external 'OpenProcessToken@advapi32.dll stdcall';
function GetCurrentProcess(): THandle; external 'GetCurrentProcess@kernel32.dll stdcall';
function LookupPrivilegeValue(lpSystemName, lpName: String; var lpLuid: LUID): BOOL; external 'LookupPrivilegeValue{#A}@advapi32.dll stdcall';
function AdjustTokenPrivileges(TokenHandle: THandle; DisableAllPrivileges: BOOL; NewState: TOKEN_PRIVILEGES; BufferLength: DWORD; var PreviousState: TOKEN_PRIVILEGES; var ReturnLength: Longint): BOOL; external 'AdjustTokenPrivileges@advapi32.dll stdcall';
function CloseHandle(hObject: THandle): BOOL; external 'CloseHandle@kernel32.dll stdcall';
function GetProcessImageFileName(hProcess: THandle; var lpImageFileName: Char; nSize: DWORD): DWORD; external 'GetProcessImageFileName{#A}@psapi.dll stdcall';
function GetLogicalDrives(): DWORD; external 'GetLogicalDrives@kernel32.dll stdcall';
function QueryDosDevice(lpDeviceName: String; var lpTargetPath: Char; ucchMax: DWORD): DWORD; external 'QueryDosDevice{#A}@kernel32.dll stdcall';
function EnumWindows(lpEnumFunc, lParam: Longint): BOOL; external 'EnumWindows@user32.dll stdcall';
function WaitForSingleObject(hHandle: THandle; dwMilliseconds: DWORD): DWORD; external 'WaitForSingleObject@kernel32.dll stdcall';
function GetProcAddress(hModule: THandle; lpProcName: AnsiString): Longint; external 'GetProcAddress@kernel32.dll stdcall';
function GetModuleHandle(lpModuleName: String): THandle; external 'GetModuleHandle{#A}@kernel32.dll stdcall';
function CreateRemoteThread(hProcess: THandle; lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags: DWORD; var lpThreadId: DWORD): THandle; external 'CreateRemoteThread@kernel32.dll stdcall';
function TerminateProcess(hProcess: THandle; uExitCode: UINT): BOOL; external 'TerminateProcess@kernel32.dll stdcall';
function GetWindowThreadProcessId(hWnd: HWND; var lpdwProcessId: DWORD): DWORD; external 'GetWindowThreadProcessId@user32.dll stdcall';
function SendMessageTimeout(hWnd: HWND; Msg: UINT; wParam, lParam: Longint; fuFlags, uTimeout: UINT; var lpdwResult: Longint): Longint; external 'SendMessageTimeout{#A}@user32.dll stdcall';

/////////////////////////////////////////////////////////
function CharArrayToString(aChar: array of Char): String;
begin
    Result := '';
    while aChar[Length(Result)] <> #0 do Insert(aChar[Length(Result)], Result, Length(Result)+1);
end;

////////////////////////////////////////////////////////////
function EnumWindowsProc(hwnd: HWND; lParam: Longint): BOOL;
var
    dwID: DWORD;
    lResult: Longint;
begin
    Result := True;
    GetWindowThreadProcessId(hwnd, dwID);
    if dwID = lParam then
        Result := SendMessageTimeout(hwnd, WM_CLOSE, 0, 0, SMTO_BLOCK or SMTO_ABORTIFHUNG, 5000, lResult) <> 0;
end;

//////////////////////////////////////////////////////////////////////////////////
function TerminateApp(const szProcessList: String; const dwTimeout: DWORD): DWORD;
// szProcessList :  process names or full paths of processes delimited by vertical bar, e.g. calc.exe|notepad.exe|c:\hungtest.exe
// dwTimeout.....:  kill timeout in ms
var
    hProcessSnap, hProc, hToken, hThread, lpProcName: THandle;
    pe32: TPROCESSENTRY32;
    aBuf: array [0..259] of Char;
    bProcFind: Boolean;
    szExeFile, szExePath, szFileName, szDeviceName: String;
    tkp: TOKEN_PRIVILEGES;
    SeDebugNameValue: LUID;
    i, ret: Longint;
    lpThreadId, dwDrives: DWORD;
begin
    hProcessSnap := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if hProcessSnap = INVALID_HANDLE_VALUE then Exit;
    try
        with TStringList.Create do
        try
            StringChangeEx(szProcessList, '|', #13#10, True);
            Text := szProcessList;
            //
            pe32.dwSize := SizeOf(pe32);
            if not Process32First(hProcessSnap, pe32) then Exit;
            repeat
                bProcFind := False;
                szExeFile := CharArrayToString(pe32.szExeFile);
                for i := 0 to Count-1 do
                begin
                    if CompareText(szExeFile, ExtractFileName(Strings[i])) = 0 then
                    begin
                        bProcFind := True;
                        szExePath := Strings[i];
                        Break;
                    end;
                end;
                if not bProcFind then Continue;

                // try open process
                hProc := OpenProcess(PROCESS_TERMINATE or PROCESS_CREATE_THREAD or PROCESS_QUERY_INFORMATION or SYNCHRONIZE, False, pe32.th32ProcessID);
                if hProc = TA_FAILED then
                begin
                    // open process token adjust privileges
                    if not OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken) then Exit;
                    if not LookupPrivilegeValue('', 'SeDebugPrivilege', SeDebugNameValue) then Exit;
                    try
                        // fill token privileges struct
                        tkp.PrivilegeCount := 1;
                        tkp.Privileges[0].Luid := SeDebugNameValue;
                        tkp.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;

                        // set debug privileges
                        if not AdjustTokenPrivileges(hToken, False, tkp, SizeOf(tkp), tkp, ret) then Exit;

                        // try open process with debug privileges
                        hProc := OpenProcess(PROCESS_TERMINATE or PROCESS_CREATE_THREAD or PROCESS_QUERY_INFORMATION or SYNCHRONIZE, False, pe32.th32ProcessID);
                        if hProc = TA_FAILED then Exit;
                    finally
                        tkp.Privileges[0].Attributes := 0;
                        AdjustTokenPrivileges(hToken, False, tkp, SizeOf(tkp), tkp, ret);
                        CloseHandle(hToken);
                    end;
                 end;

                // if szProcess is full path
                if CompareText(szExePath, szExeFile) <> 0 then
                begin
                    GetProcessImageFileName(hProc, aBuf[0], SizeOf(aBuf));
                    szFileName := CharArrayToString(aBuf);
                    dwDrives := GetLogicalDrives();
                    for i := 2 to 25 do if dwDrives and (1 shl i) <> 0 then
                    begin
                        QueryDosDevice(Format('%s:', [Chr(Ord('A') + i)]), aBuf[0], SizeOf(aBuf));
                        szDeviceName := CharArrayToString(aBuf);
                        if Pos(szDeviceName, szFileName) = 0 then Continue;
                        StringChangeEx(szFileName, szDeviceName, Format('%s:', [Chr(Ord('A') + i)]), True);
                        if CompareText(szExePath, szFileName) = 0 then Break;
                    end;
                    if CompareText(szExePath, szFileName) <> 0 then
                    begin
                        CloseHandle(hProc);
                        Continue;
                    end;
                end;

                // try stop process
                try
                    if not EnumWindows(CallbackAddr('EnumWindowsProc'), pe32.th32ProcessID) then
                    begin
                        if TerminateProcess(hProc, 0) then Result := TA_SUCCESS_KILL;
                    end else case WaitForSingleObject(hProc, dwTimeout) of
                        WAIT_OBJECT_0: Result := TA_SUCCESS_CLEAN;
                        WAIT_TIMEOUT: try
                            lpProcName := GetProcAddress(GetModuleHandle('kernel32.dll'), 'ExitProcess');
                            if lpProcName = 0 then Exit;
                            hThread := CreateRemoteThread(hProc, 0, 0, lpProcName, 0, 0, lpThreadId);
                            case WaitForSingleObject(hThread, dwTimeout) of
                                WAIT_OBJECT_0: Result := TA_SUCCESS_CLEAN;
                                WAIT_TIMEOUT, WAIT_FAILED: if TerminateProcess(hProc, 0) then Result := TA_SUCCESS_KILL;
                            end;
                        finally
                            CloseHandle(hThread);
                        end;
                    end;
                finally
                    CloseHandle(hProc);
                end;
            until not Process32Next(hProcessSnap, pe32);
        finally
            Free;
        end;
    finally
        CloseHandle(hProcessSnap);
    end;
end;

/////////////////////////////
procedure InitializeWizard();
begin
    TerminateApp('NvXDSync.exe', 5000);
end;
Это сообщение посчитали полезным следующие участники:

Отправлено: 09:22, 12-09-2014 | #1524