Solved

Snifing specific Win32 API calls (system wide)

Posted on 1998-08-05
13
447 Views
Last Modified: 2013-12-03
I need to catch specific Win32 API calls to winmm.dll (system wide). I'd appritiate any ideas,

Sencerely,
Vladip (mailto:vladip@usa.net)
0
Comment
Question by:vladip
  • 4
  • 3
  • 2
  • +3
13 Comments
 
LVL 7

Expert Comment

by:faster
ID: 1413082
One easy way is to get SoftICE from Numega, it is a powerful debug tool, allow you to trace any API (and much more...)

http://www.numega.com
0
 
LVL 11

Expert Comment

by:alexo
ID: 1413083
I think vladip wanted to do it programmatically.
0
 
LVL 22

Expert Comment

by:nietod
ID: 1413084
Programmatically?  Easy, you write soft ice.
0
 
LVL 11

Expert Comment

by:alexo
ID: 1413085
I remember seing a description of how to do it.  Unfortunately, lost the reference (sysinternals?)
0
 

Author Comment

by:vladip
ID: 1413086
I need to do sniffing by myself in my aplication, so it doesn't help too much that SoftICE is doing it.
The only solution I'm thinking about is to inject all processes with my dll which will snif each process independently. But for that I need to be notified each time process is going to be created. I don't know how to do it.
0
 
LVL 4

Expert Comment

by:agreen
ID: 1413087
For hooking the process and thread creation or deletion see PMon http://www.sysinternals.com/ntpmon.htm
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 

Author Comment

by:vladip
ID: 1413088
Pmon is not  good enough.
First, in order to inject dll I need to be called by Loader BEFORE application is started. And second, I need soution for both 95 and NT.

Thanks for your help guys. Don't give up!!!!
0
 
LVL 22

Expert Comment

by:nietod
ID: 1413089
>> The only solution I'm thinking about is to inject all processes with my dll
I'm not sure how that is going to help you.  I'm curious though.

If you use a system hook, set by SetWindowsHook(), you can get your DLL mapped into every process.  The event you hook doesn't matter and what you do to handle (ignore) the event doesn't matter.

Now this maps the DLL into the process after it loads, not before.  But I can't see how that matters.
0
 
LVL 22

Expert Comment

by:nietod
ID: 1413090
A solution, sort of like the one employed by numga, is to replace the system DLLs with your own DLLs.  These new DLLs do your work and forward the call on to the original system DLLs.  To do this, you have to install your DLLs before windows propper loads.   In 95 this can be done using a DOS program called from the autoexec (if you want to do this each time you boot), or by a DOS install program that is run from DOS compatibility mode.
0
 
LVL 22

Expert Comment

by:nietod
ID: 1413091
Note to other experts:  This is in response to an e-mail sent to be me by vladip.  

>> I think thatyour idea (with WindowsHook) will work
Test it first, before you close this question.  

>>The only question I still have is how can I give you points for your answer
If you grade the question with an A - D, then the expert who has the question locked gets the points.  Currently that is faster.  If you want the points to go to a different expert, reject the current answer and ask that expert you want to get the points to submit a "dummy" answer.

>> (BTW how much points should I give for such answer)
You've already committed 200 points.  You can raise that if you wish, but you can't lower it.  If an expert answers a question that is at a particular  point value, then they feel that it is worth that point value, so you are not obligated to raise the value.  

Most importantly, always try to get a working solution before you accept an answer.
0
 
LVL 3

Accepted Solution

by:
xyu earned 200 total points
ID: 1413092
I've put sample if intercepting API call at
http://www.geocities.com/SiliconValley/1741/miscprog/intercept.zip...
and here is listing:

/****************************************************************************/
/** intercept.cpp                                                          **/
/** ---------------------------------------------------------------------- **/
/** Example of interception of an API or any DLL function call             **/
/** ---------------------------------------------------------------------- **/
/** The method shown here may be very impressive in conjunction with       **/
/** CreateRemoteThread API                                                 **/
/** ---------------------------------------------------------------------- **/
/** July 23, 1998 by Oleg Kagan                                            **/
/****************************************************************************/

/****************************************************************************/

//============================================================================
#include <windows.h>

// Switch all optimizations off
// (Visual C specific... For any other compiler do the same thing)
//============================================================================
#pragma optimize("", off)

//============================================================================
#define MakePtr(Type, Base, Offset) ((Type)(DWORD(Base) + (DWORD)(Offset)))

//============================================================================
BOOL InterceptDllCall(

      HMODULE hLocalModule,
      const char* c_szDllName,
      const char* c_szApiName,
      PVOID pApiNew,
      PVOID* p_pApiOrg,
      PVOID pApiToChange
      
){
    PIMAGE_DOS_HEADER pDOSHeader = (PIMAGE_DOS_HEADER)hLocalModule;
    PIMAGE_NT_HEADERS pNTHeader;
    PIMAGE_IMPORT_DESCRIPTOR pImportDesc;
    DWORD dwProtect;
      BOOL bSuccess = FALSE;
   
    DWORD dwAddressToIntercept;

      if (pApiToChange) {
            dwAddressToIntercept = (DWORD)pApiToChange;
      }
      else {
            dwAddressToIntercept = (DWORD)GetProcAddress(
                  GetModuleHandle((char*)c_szDllName), (char*)c_szApiName
            ) /*GetProcAddress*/;
      } /*iff*/;

    if (IsBadReadPtr(hLocalModule, sizeof(PIMAGE_NT_HEADERS)))
        return FALSE;
   
    if (pDOSHeader->e_magic != IMAGE_DOS_SIGNATURE)
        return FALSE;
   
    pNTHeader = MakePtr(PIMAGE_NT_HEADERS, pDOSHeader, pDOSHeader->e_lfanew);
    if (pNTHeader->Signature != IMAGE_NT_SIGNATURE)
        return FALSE;
   
    pImportDesc = MakePtr(
            PIMAGE_IMPORT_DESCRIPTOR, hLocalModule,
        pNTHeader->OptionalHeader.DataDirectory[
                  IMAGE_DIRECTORY_ENTRY_IMPORT
            ] /*pNTHeader->OptionalHeader.DataDirectory*/.VirtualAddress
      ) /*MakePtr*/;
   
    if (pImportDesc == (PIMAGE_IMPORT_DESCRIPTOR)pNTHeader) return FALSE;
   
      while (pImportDesc->Name) {
            PIMAGE_THUNK_DATA pThunk;
   
            pThunk = MakePtr(
                  PIMAGE_THUNK_DATA, hLocalModule, pImportDesc->FirstThunk
            ) /*MakePtr*/;
   
            while (pThunk->u1.Function) {
                  if (DWORD(pThunk->u1.Function) == dwAddressToIntercept) {      
                        if (
                              !IsBadWritePtr(
                                    (LPVOID)pThunk->u1.Function, sizeof(DWORD)
                              ) /*!IsBadWritePtr*/
                        ){
                              if (p_pApiOrg)
                                    *p_pApiOrg = PVOID(pThunk->u1.Function);
                              (PDWORD)pThunk->u1.Function = (PDWORD)pApiNew;
                              bSuccess = TRUE;
                        }
                        else {
                              if (
                                    VirtualProtect(
                                          (LPVOID)(&pThunk->u1.Function), sizeof(DWORD),
                                          PAGE_EXECUTE_READWRITE, &dwProtect
                                    ) /*VirtualProtect*/
                              ){
                                    DWORD dwNewProtect;

                                    if (p_pApiOrg)
                                          *p_pApiOrg = PVOID(pThunk->u1.Function);
                                    pThunk->u1.Function = (PDWORD)pApiNew;
                                    bSuccess = TRUE;

                                    dwNewProtect = dwProtect;
                                    VirtualProtect(
                                          (LPVOID)(&pThunk->u1.Function), sizeof(DWORD),
                                          dwNewProtect, &dwProtect
                                    ) /*VirtualProtect*/;
                              } /*if*/
                        } /*iff*/
                  } /*if*/
                  pThunk++;
            } /*while*/
            pImportDesc++;
      } /*while*/

    return bSuccess;
} /*InterceptDllCall(HMODULE, const char*, const char*, PVOID,PVOID*,PVOID)*/

//============================================================================
BOOL Win32IsNT()
{
      static unsigned uIsNT = 2;
      if (uIsNT > 1) {
            // Check NT or Win95/98
            //----------------------
            OSVERSIONINFO VersionInfo; {
                  VersionInfo.dwOSVersionInfoSize = sizeof(VersionInfo);
                  GetVersionEx(&VersionInfo);
            } /*VersionInfo*/

            uIsNT = (VersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT);
      } /*if*/
      return (uIsNT != 0);
} /*Win32IsNT()*/

//============================================================================
void ChangeText(

      char* szText
      
){
      size_t nLength = strlen(szText);
      for (size_t i = 0; i < nLength; ++i) {
            szText[i] = char((i % 2) ? tolower(szText[i]) : toupper(szText[i]));
      } /*for (size_t i)*/
} /*ChangeText(char*)*/

//============================================================================
typedef int (*TMessageBoxFuncPtr)(HWND, LPCTSTR, LPCTSTR, UINT);
TMessageBoxFuncPtr p_fnMessageBoxOrg = NULL;

//============================================================================
int WINAPI MyMessageBox(

      HWND hWnd,          // handle of owner window
      LPCTSTR lpText,     // address of text in message box
      LPCTSTR lpCaption,  // address of title of message box
      UINT uType          // style of message box

){
      if (!p_fnMessageBoxOrg) return 0;
      ChangeText((char*)lpText); ChangeText((char*)lpCaption);
      int nResult = (*p_fnMessageBoxOrg)(hWnd, lpText, lpCaption, uType);
      return nResult;
} /*MyMessageBox(HWND, LPCTSTR, LPCTSTR, UINT)*/

//============================================================================
extern "C" int WINAPI WinMain(

      HINSTANCE hInstance,  // handle to current instance
      HINSTANCE /*hPrevInstance*/,  // handle to previous instance
      LPSTR szCmdLine,  // pointer to command line
      int /*nCmdShow*/  // show state of window

){
      char* c_szTitle = "API Call Interception";
      UINT uStyle = MB_OK | MB_ICONHAND | MB_SYSTEMMODAL;

      if (!Win32IsNT()) {
            MessageBox(
                  NULL,
                  "Sorry, but this example works under Microsoft Windows NT only",
                  c_szTitle, uStyle
            ) /*MessageBox*/;
            return EXIT_FAILURE;
      } /*if*/

      MessageBox(NULL, "Here it is normal                 ", c_szTitle, uStyle);

      // Lets Change it
      //----------------
      InterceptDllCall(
            hInstance, "user32.dll", "MessageBoxA",
            (PVOID)&MyMessageBox, (PVOID*)&p_fnMessageBoxOrg,
            NULL
      ) /*InterceptDllCall*/;

      MessageBox(NULL, "Beware of the mad hackers         ", c_szTitle, uStyle);

      InterceptDllCall(
            hInstance, "user32.dll", "MessageBoxA",
            (PVOID)p_fnMessageBoxOrg, NULL, (PVOID)MyMessageBox
      ) /*InterceptDllCall*/;

      MessageBox(NULL, "Here it is almoust normal again :)", c_szTitle, uStyle);

      return EXIT_SUCCESS;
} /*WinMain(HINSTANCE, HINSTANCE, LPSTR, int)*/

0
 
LVL 3

Expert Comment

by:xyu
ID: 1413093
System wide injection is comming soon as DLL with the function like:

BOOL InjectDllIntoProcess(
    HPROCESS hProcess, // Process to inject into :)
    const wchar_t* c_wszDllToInject, // name of the DLL that contain Your code
    const wchar_t* c_wszStartupFunction // name of the void WINAPI Foo(HPROCESS hProcess) function that is going to receive control
);

0
 
LVL 3

Expert Comment

by:xyu
ID: 1413094
vladip... I did it... i can sent to You dll that can help You to inject Your dll into any process and intercept any API... so afterwards You need just to intercept LoadLibrary and/or CreateProcess, etc. APIs and "infect" resulting modules again :)
I still working on simple tool do to do system wide "infection" :) but You can make Your own using the tools i developed already... its easy :) give me Your email and i'll send it to You

Good Luck
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

This tutorial is about how to put some of your C++ program's functionality into a standard DLL, and how to make working with the EXE and the DLL simple and seamless.   We'll be using Microsoft Visual Studio 2008 and we will cut out the noise; that i…
This article shows how to make a Windows 7 gadget that extends its U/I with a flyout panel -- a window that pops out next to the gadget.  The example gadget shows several additional techniques:  How to automatically resize a gadget or flyout panel t…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now