Как я могу подключить функции Windows в C / C ++?

Вы можете использовать метку, основанную на использовании .loc или индекса, основанного на методе .iloc для обработки столбцов, включая диапазоны столбцов:

In [50]: import pandas as pd

In [51]: import numpy as np

In [52]: df = pd.DataFrame(np.random.rand(4,4), columns = list('abcd'))

In [53]: df
Out[53]: 
          a         b         c         d
0  0.806811  0.187630  0.978159  0.317261
1  0.738792  0.862661  0.580592  0.010177
2  0.224633  0.342579  0.214512  0.375147
3  0.875262  0.151867  0.071244  0.893735

In [54]: df.loc[:, ["a", "b", "d"]] ### Selective columns based slicing
Out[54]: 
          a         b         d
0  0.806811  0.187630  0.317261
1  0.738792  0.862661  0.010177
2  0.224633  0.342579  0.375147
3  0.875262  0.151867  0.893735

In [55]: df.loc[:, "a":"c"] ### Selective label based column ranges slicing
Out[55]: 
          a         b         c
0  0.806811  0.187630  0.978159
1  0.738792  0.862661  0.580592
2  0.224633  0.342579  0.214512
3  0.875262  0.151867  0.071244

In [56]: df.iloc[:, 0:3] ### Selective index based column ranges slicing
Out[56]: 
          a         b         c
0  0.806811  0.187630  0.978159
1  0.738792  0.862661  0.580592
2  0.224633  0.342579  0.214512
3  0.875262  0.151867  0.071244
30
задан AstroCB 30 August 2014 в 22:22
поделиться

5 ответов

Взгляните на Объезды , он идеально подходит для такого рода вещей.


Для общесистемного подключения прочтите эту статью из MSDN .


Сначала создайте DLL, которая обрабатывает перехват функций. В приведенном ниже примере перехватываются функции отправки и получения сокета.

#include <windows.h>
#include <detours.h>

#pragma comment( lib, "Ws2_32.lib" )
#pragma comment( lib, "detours.lib" )
#pragma comment( lib, "detoured.lib" )

int ( WINAPI *Real_Send )( SOCKET s, const char *buf, int len, int flags ) = send;
int ( WINAPI *Real_Recv )( SOCKET s, char *buf, int len, int flags ) = recv;  
int WINAPI Mine_Send( SOCKET s, const char* buf, int len, int flags );
int WINAPI Mine_Recv( SOCKET s, char *buf, int len, int flags );

int WINAPI Mine_Send( SOCKET s, const char *buf, int len, int flags ) {
    // .. do stuff ..

    return Real_Send( s, buf, len, flags );
}

int WINAPI Mine_Recv( SOCKET s, char *buf, int len, int flags ) {
    // .. do stuff ..

    return Real_Recv( s, buf, len, flags );
}

BOOL WINAPI DllMain( HINSTANCE, DWORD dwReason, LPVOID ) {
    switch ( dwReason ) {
        case DLL_PROCESS_ATTACH:       
            DetourTransactionBegin();
            DetourUpdateThread( GetCurrentThread() );
            DetourAttach( &(PVOID &)Real_Send, Mine_Send );
            DetourAttach( &(PVOID &)Real_Recv, Mine_Recv );
            DetourTransactionCommit();
            break;

        case DLL_PROCESS_DETACH:
            DetourTransactionBegin();
            DetourUpdateThread( GetCurrentThread() );
            DetourDetach( &(PVOID &)Real_Send, Mine_Send );
            DetourDetach( &(PVOID &)Real_Recv, Mine_Recv );
            DetourTransactionCommit(); 
        break;
    }

    return TRUE;
}

Затем создайте программу для внедрения библиотеки DLL в целевое приложение.

#include <cstdio>
#include <windows.h>
#include <tlhelp32.h>

void EnableDebugPriv() {
    HANDLE hToken;
    LUID luid;
    TOKEN_PRIVILEGES tkp;

    OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken );

    LookupPrivilegeValue( NULL, SE_DEBUG_NAME, &luid );

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

    AdjustTokenPrivileges( hToken, false, &tkp, sizeof( tkp ), NULL, NULL );

    CloseHandle( hToken ); 
}

int main( int, char *[] ) {
    PROCESSENTRY32 entry;
    entry.dwSize = sizeof( PROCESSENTRY32 );

    HANDLE snapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, NULL );

    if ( Process32First( snapshot, &entry ) == TRUE ) {
        while ( Process32Next( snapshot, &entry ) == TRUE ) {
            if ( stricmp( entry.szExeFile, "target.exe" ) == 0 ) {
                EnableDebugPriv();

                char dirPath[MAX_PATH];
                char fullPath[MAX_PATH];

                GetCurrentDirectory( MAX_PATH, dirPath );

                sprintf_s( fullPath, MAX_PATH, "%s\\DllToInject.dll", dirPath );

                HANDLE hProcess = OpenProcess( PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION | PROCESS_VM_WRITE, FALSE, entry.th32ProcessID );
                LPVOID libAddr = (LPVOID)GetProcAddress( GetModuleHandle( "kernel32.dll" ), "LoadLibraryA" );
                LPVOID llParam = (LPVOID)VirtualAllocEx( hProcess, NULL, strlen( fullPath ), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE );

                WriteProcessMemory( hProcess, llParam, fullPath, strlen( fullPath ), NULL );
                CreateRemoteThread( hProcess, NULL, NULL, (LPTHREAD_START_ROUTINE)libAddr, llParam, NULL, NULL );
                CloseHandle( hProcess );
            }
        }
    }

    CloseHandle( snapshot );

    return 0;
}

Этого должно быть более чем достаточно, чтобы вы начали!

35
ответ дан 27 November 2019 в 23:50
поделиться

EASYHOOK http://www.codeplex.com/easyhook

Dominate's all aformentioned techniques in simpleicty, flexability and functionality.

It was not discussed previously on Hook processes either. I've read all leaf's of this thread and with absolute certanty, EASYHOOK is vastly superiour. No matter if your using C, C++, CLR, whatever.

I'll paste a bit from the codeplex homepage, to ensure sufficient omage being paid.

The following is an incomplete list of features:

  1. A so called "Thread Deadlock Barrier" will get rid of many core problems when hooking unknown APIs; this technology is unique to EasyHook
  2. You can write managed hook handlers for unmanaged APIs
  3. You can use all the convenience managed code provides, like NET Remoting, WPF and WCF for example
  4. A documented, pure unmanaged hooking API
  5. Support for 32- and 64-bit kernel mode hooking (also check out my PatchGuard 3 bypass driver which can be found in the release list)
  6. No resource or memory leaks are left in the target
  7. Experimental stealth injection mechanism that won't raise attention of any current AV Software
  8. EasyHook32.dll and EasyHook64.dll are pure unmanaged modules and can be used without any NET framework installed!
  9. All hooks are installed and automatically removed in a stable manner
  10. Support for Windows Vista SP1 x64 and Windows Server 2008 SP1 x64 by utilizing totally undocumented APIs, to still allow hooking into any terminal session.
  11. Managed/Unmanaged module stack trace inside a hook handler
  12. Get calling managed/unmanaged module inside a hook handler
  13. Create custom stack traces inside a hook handler
  14. You will be able to write injection libraries and host processes compiled for AnyCPU, which will allow you to inject your code into 32- and 64-Bit processes from 64- and 32-Bit processes by using the very same assembly in all cases.
  15. EasyHook supports RIP-relative addressing relocation for 64-Bit targets.
  16. No unpacking/installation necessary.
  17. The Visual Studio Redistributable is not required.

I'm happy that my hooker's still know a few tricks in comparison that makes me keep them around. But to be sure, when you need a HOOK, 99 times of 100, EASYHOOK'r will get you there faster. And it's quite actively maintained.

11
ответ дан 27 November 2019 в 23:50
поделиться

Please give more details of the function you want to hook! There are several ways to get your own code called in such a case, for instance:

  • You can build a fake DLL with the same name as the DLL that contains the function you want to hook (and copy it in the folder of foo.exe). This library would expose exactly the same functions as the original DLL. Each exposed function just bypasses the call to the original DLL, with the exception of the function you want to hook.

  • You can change the function pointer table during run-time, for instance with the (commercial) Detour package that has been mentioned by "kitchen". However, doing such hooking can be done easily by your own, see this article to learn how.

  • You can find out where the specific function is called in foo.exe and just replace the assembly code that calls the function with a code that "returns true". Basically, you're patching "foo.exe"..

  • For specific functions, Windows offers automatic hooking, e.g. for keys and mouse events. Check the function SetWindowsHook for this.

8
ответ дан 27 November 2019 в 23:50
поделиться

Это в некоторой степени зависит от версии Windows, на которую вы хотите ориентироваться. Тем не менее, если вы играете в Pre-Vista, вы можете просто использовать SetWindowsHookEx для внедрения вашей DLL в каждый запущенный процесс. Затем вашей DLL потребуется перехватить соответствующую функцию с помощью обходных путей или подобного.

3
ответ дан 27 November 2019 в 23:50
поделиться

Если вы пишете ловушку на ассемблере и не используете обходные пути (по какой-либо причине), тогда вам понадобится некоторая ключевая информация о возврате FALSE:

  • Win32 установите EAX на 0
  • Win64, установите RAX на 0

Вам нужно установить EAX или RAX (в зависимости от платформы) на ноль в качестве последнего действия, которое выполняет функция, которую вы подключаете. Это приведет к тому, что вызывающий код получит 0 в качестве возвращаемого значения (при условии, что они возвращают значение типа int или указателя).

-1
ответ дан 27 November 2019 в 23:50
поделиться
Другие вопросы по тегам:

Похожие вопросы: