Cheat Engine Forum Index Cheat Engine
The Official Site of Cheat Engine
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 


How do I hook the winsock send, recv, and connect in c#

 
Post new topic   Reply to topic    Cheat Engine Forum Index -> General programming
View previous topic :: View next topic  
Author Message
selethd
How do I cheat?
Reputation: 0

Joined: 20 May 2009
Posts: 3

PostPosted: Wed Apr 20, 2011 7:45 pm    Post subject: How do I hook the winsock send, recv, and connect in c# Reply with quote

I have been injecting a c++ .dll that is able to hook the send, recv functions of winsock, so that I can manipulate the data.

However, I have recenly learned how to get a Windows Form created in a C# dll (By injecting a c++ .dll that acts as a loader, and loads the CLR, then calls a method on my managed C# class library)

In this method, I need to hook the winsock functions for send and recv. I know how to do this in C++, but I have never found any instructions to do this in c#

Here is my c++ code, so to better illustrate what I am trying to do.

Code:


typedef SOCKET (WINAPI *PSOCKET)(int af, int type, int protocol);
typedef int (WINAPI *PCONNECT)(SOCKET s, const struct sockaddr *address, int namelen);
typedef int (WINAPI *PSEND)(SOCKET s, const char* buf, int len, int flags);

PSOCKET  OrigSocket;
PCONNECT OrigConnect;
PSEND    OrigSend;

int WINAPI __stdcall MyConnect(SOCKET s, const struct sockaddr *address, int namelen)
{
}

int WINAPI __stdcall MySend(SOCKET s, const char* buf, int len, int flags)
{
}

DWORD APIHook(DWORD HookFunc, DWORD MyFunc, DWORD OrigFunc)
{
   unsigned char NewData[5], DetourJump[5], OldData[5];
   DWORD OldProtect;
   int i;
   unsigned char* HookFuncPtr = (unsigned char*) HookFunc;
   unsigned char* HookDetour = (unsigned char*)new char[(25)];
   for(i = 0; i < 25; i++)
      HookDetour[i] = 0x90; //NOP
   NewData[0] = 0xE9; //JMP (near)
   *(PDWORD)&NewData[1] = (DWORD)((DWORD)MyFunc - ((DWORD)HookFunc + 5));
   DetourJump[0] = 0xE9;
   *(PDWORD)&DetourJump[1] = (DWORD)((DWORD)HookFunc - ((DWORD)HookDetour + 14 + 5));
   VirtualProtectEx(GetCurrentProcess(), (void*)HookFunc, 10, PAGE_EXECUTE_WRITECOPY, &OldProtect);
   for(i = 0; i < 5; i++)
   {
      OldData[i] = HookFuncPtr[i];
      HookFuncPtr[i] = NewData[i];
   }
   VirtualProtectEx(GetCurrentProcess(), (void*)HookFunc, 10, OldProtect, NULL);
   VirtualProtectEx(GetCurrentProcess(), (void*)HookDetour, 25, PAGE_EXECUTE_WRITECOPY, &OldProtect);
   for(i = 0; i < 5; i++)
      HookDetour[i] = OldData[i];
   HookDetour[24-5] = DetourJump[0];
   HookDetour[24-4] = DetourJump[1];
   HookDetour[24-3] = DetourJump[2];
   HookDetour[24-2] = DetourJump[3];
   HookDetour[24-1] = DetourJump[4];
   HookDetour[24] = 0xC3; //RET
   VirtualProtectEx(GetCurrentProcess(), (void*)HookDetour, 25, OldProtect, NULL);
   OrigFunc = (DWORD)HookDetour;
   return OrigFunc;
}



DWORD WINAPI Inject(HINSTANCE hInst /*LPVOID lparam*/)
{
   WSADATA wsaData;
   WSAStartup(MAKEWORD(1,1), &wsaData);
   *(PDWORD)&OrigConnect = APIHook((DWORD)GetProcAddress(GetModuleHandle((LPCSTR)"Ws2_32.dll"), "connect"), (DWORD)MyConnect, (DWORD)OrigConnect);
   *(PDWORD)&OrigSend = APIHook((DWORD)GetProcAddress(GetModuleHandle((LPCSTR)"Ws2_32.dll"), "send"), (DWORD)MySend, (DWORD)OrigSend);
}


Last edited by selethd on Fri Apr 22, 2011 9:16 am; edited 1 time in total
Back to top
View user's profile Send private message
Innovation
Grandmaster Cheater
Reputation: 12

Joined: 14 Aug 2008
Posts: 617

PostPosted: Wed Apr 20, 2011 10:25 pm    Post subject: Reply with quote

The unsafe keyword allows usage of pointers, but the detour functions themselves must be unmanaged. One solution to this is to write the functions (assembly code) to dynamically allocated memory.

Last edited by Innovation on Wed Apr 20, 2011 10:32 pm; edited 1 time in total
Back to top
View user's profile Send private message
selethd
How do I cheat?
Reputation: 0

Joined: 20 May 2009
Posts: 3

PostPosted: Thu Apr 21, 2011 7:06 am    Post subject: Reply with quote

Maybe im too nooby on the subject to completely understand. Is there any pseudo code you could give, or a link to a good example?

I really appreciate it. Thanks
Back to top
View user's profile Send private message
atom0s
Moderator
Reputation: 205

Joined: 25 Jan 2006
Posts: 8587
Location: 127.0.0.1

PostPosted: Thu Apr 21, 2011 2:45 pm    Post subject: Reply with quote

You can inject a bootstrap DLL to force the CLR to load into the process. Which you can then force your managed DLLs to load afterward. Check out this article:

http://www.codingthewheel.com/archives/how-to-inject-a-managed-assembly-dll

This isn't updated for .NET 4.0 so if you are using newer versions you may need to adjust some things. But it isn't hard to follow and understand as long as you don't just copy paste things.

Innovation wrote:
The unsafe keyword allows usage of pointers, but the detour functions themselves must be unmanaged. One solution to this is to write the functions (assembly code) to dynamically allocated memory.

You don't need to use unsafe as long as you are marshaling everything that requires pointers and stuff as well. You can also do Detours inside of .NET

_________________
- Retired.
Back to top
View user's profile Send private message Visit poster's website
Innovation
Grandmaster Cheater
Reputation: 12

Joined: 14 Aug 2008
Posts: 617

PostPosted: Thu Apr 21, 2011 2:55 pm    Post subject: Reply with quote

Wiccaan wrote:
You can inject a bootstrap DLL to force the CLR to load into the process. Which you can then force your managed DLLs to load afterward.

selethd wrote:
I have recenly learned how to get a Windows Form created in a C# dll (By injecting a c++ .dll that acts as a loader, and loads the CLR, then calls a method on my managed C# class library)

Isn't selethd already doing this?

Wiccaan wrote:
You don't need to use unsafe as long as you are marshaling everything that requires pointers and stuff as well.

Don't you need the unsafe keyword to dereference in C#?

Wiccaan wrote:
You can also do Detours inside of .NET

I was referring to the functions that "are" the detours (MyConnect, MySend, MyRecv, MyWSASend, MyWSARecv) rather than the functions that "create" the detours (Inject, APIHook) when I stated that the functions must be unmanaged. This is assuming that an abstraction such as EasyHook is not to be used.
Back to top
View user's profile Send private message
atom0s
Moderator
Reputation: 205

Joined: 25 Jan 2006
Posts: 8587
Location: 127.0.0.1

PostPosted: Thu Apr 21, 2011 10:59 pm    Post subject: This post has 1 review(s) Reply with quote

Unsafe is only needed if you plan to use direct access. You can read and write to pointers using the Marshal class and not have to touch unsafe at all. Basically if you were wanting to deal with the pointers like C++ does and such. But you can do the same things using Marshaling if you are injected.

Think of it as memcpy/memset.

Quote:
I was referring to the functions that "are" the detours (MyConnect, MySend, MyRecv, MyWSASend, MyWSARecv) rather than the functions that "create" the detours (Inject, APIHook) when I stated that the functions must be unmanaged. This is assuming that an abstraction such as EasyHook is not to be used.


You can do all these in C# / managed code as well. The detours can be written in managed code without issue. I was writing a Direct3D hook / wrapper that does this, for example the Direct3DCreate9 detour:

Code:

        /// <summary>
        /// Direct3DCreate9 Hook
        /// </summary>
        /// <param name="SDKVersion"></param>
        /// <returns></returns>
        [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Auto, SetLastError = true)]
        delegate IntPtr delegate_Direct3DCreate9(ushort SDKVersion);
        public IntPtr Mine_Direct3DCreate9(ushort SDKVersion)
        {
            Debug.Write("[Mine_Direct3DCreate9] Hooked Direct3DCreate9 called.");

            this.m_vDirect3D = (IntPtr)DetourManager.Instance["Direct3DCreate9"].CallOriginal(SDKVersion);
            return this.m_vDirect3D;
        }


Placement:
Code:

            // Detour Direct3DCreate9
            bool bAttached = DetourManager.Instance.DetourAttach(
                "d3d9.dll", "Direct3DCreate9", new delegate_Direct3DCreate9(Mine_Direct3DCreate9), true
                );


Then the detour code creates the patch in the function as:
PUSH <func_address> 0x68 0xFF 0xFF 0xFF 0xFF
RETN 0xC3

Which my Detour manager uses delegate pointers to call the original functions. All of which are using Marshal calls instead of having to touch unsafe.

You can create delegates to the real function like:
Code:
Delegate realFunction = Marshal.GetDelegateForFunctionPointer(lpFunctionAddress, lpFunctionDelegate.GetType())


Which you can call with:
Code:

object ret = realFunction.DynamicInvoke(params_here);


Pretty fun stuff to dive into, the Marshal class is nice for stuff like this if you haven't taken a chance to look into it much: Marshal

_________________
- Retired.
Back to top
View user's profile Send private message Visit poster's website
Display posts from previous:   
Post new topic   Reply to topic    Cheat Engine Forum Index -> General programming All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum


Powered by phpBB © 2001, 2005 phpBB Group

CE Wiki   IRC (#CEF)   Twitter
Third party websites