static IntPtr CreateFileWDetour(
            String InFileName,
            UInt32 InDesiredAccess,
            UInt32 InShareMode,
            IntPtr InSecurityAttributes,
            UInt32 InCreationDisposition,
            UInt32 InFlagsAndAttributes,
            IntPtr InTemplateFile)
        {
            string fileName = String.Empty, pathName = String.Empty;

            try {
                fileName = Path.GetFileName(InFileName);
                pathName = Path.GetDirectoryName(InFileName);
            } catch (Exception e) {
                HookManager.Log("CreateFileWDetour - Exception:  " + e.ToString());
            }



            if (HookManager.IsBacklistedDirectory(pathName))
            {
                HookManager.Log("[-----BLACKLISTED-----] CreateFileWDetour-lpFileName: " + pathName + "\\" + fileName + " Desired Access: " + InDesiredAccess.ToString());
                //return new IntPtr(-1);
            }

            if ((IsRead(InDesiredAccess) && HookManager.IsWhiteListedReadDirectory(pathName)))
            {
                //	HookManager.Log("[Whitelisted] CreateFileWDetour-lpFileName(READ): " + pathName + "\\" + fileName + " Desired Access: " + InDesiredAccess.ToString());
            }
            else
            {
                if (IsWrite(InDesiredAccess) && HookManager.IsWhiteListedWriteDirectory(pathName))
                {
                    //	HookManager.Log("[Whitelisted] CreateFileWDetour-lpFileName(WRITE): " + pathName + "\\" + fileName + " Desired Access: " + InDesiredAccess.ToString());
                }

                else
                {
                    if (InDesiredAccess != 0)
                    {
                        HookManager.Log("[not Whitelisted] CreateFileWDetour-lpFileName: " + pathName + "\\" + fileName + " Desired Access: " + InDesiredAccess.ToString());
                        //return new IntPtr(-1);
                    }
                }
            }

            IntPtr tmp = CreateFile(InFileName, InDesiredAccess, InShareMode, InSecurityAttributes, InCreationDisposition, InFlagsAndAttributes, InTemplateFile);

            return(tmp);
        }
 private IntPtr HInternetConnectADetour(IntPtr hInternet, string lpszServerName, short nServerPort, string lpszUsername, string lpszPassword, int dwService, int dwFlags, IntPtr dwContext)
 {
     try
     {
         HINTERNET structure = (HINTERNET)Marshal.PtrToStructure(hInternet, typeof(HINTERNET));
         HookManager.Log("[" + Name + "] [" + lpszServerName + "][" + nServerPort + "][" + dwService + "]");
     }
     catch (Exception e)
     {
         this.Error = true;
         HookManager.Log("[" + Name + "] Exception: " + e);
     }
     return(IntPtr.Zero);
 }
Exemplo n.º 3
0
        private bool GlobalMemoryStatusDetour(IntPtr memStruct)
        {
            if (_struct == null)
            {
                var result = GlobalMemoryStatusEx(memStruct);
                _struct = (MEMORYSTATUSEX)Marshal.PtrToStructure(memStruct, typeof(MEMORYSTATUSEX));
                var before = ((_struct.ullTotalPhys / 1024) / 1024);
                _struct.ullTotalPhys = _totalPhys * 1024 * 1024;
                var after = ((_struct.ullTotalPhys / 1024) / 1024);
                HookManager.Log("[GlobalMemoryStatusDetour] Memorysize was called. Before: " + before.ToString() + " After: " + after.ToString(), Color.Orange);
            }

            Marshal.StructureToPtr(_struct, memStruct, true);
            return(true);
        }
        public InternetConnectWController()
        {
            Name = "InternetConnectWHook_" + "wininet.dll";

            try
            {
                _hook = LocalHook.Create(LocalHook.GetProcAddress("wininet.dll", "InternetConnectW"), new HInternetConnectWDelegate(HInternetConnectWDetour), this);
                _hook.ThreadACL.SetExclusiveACL(new Int32[] { 1 });
                this.Error = false;
            }
            catch (Exception e)
            {
                this.Error = true;
                HookManager.Log("[" + Name + "] Exception: " + e);
            }
        }
Exemplo n.º 5
0
        private IntPtr Recieve(IntPtr socket, int len)
        {
            var buffer = Marshal.AllocHGlobal(len);

            allocatedMemory.Add(buffer);

            var result = recv(socket, buffer, len, 0);

            if (result == -1)
            {
                HookManager.Log("Error2: " + WSAGetLastError());
                return(IntPtr.Zero);
            }

            return(buffer);
        }
        private bool EnumProcessesDetour([In][Out] IntPtr processIds, uint arrayBytesSize, [In][Out] IntPtr bytesCopied)
        {
            HookManager.Log("---------EnumProcessesDetourStart------");
            bool       success     = EnumProcesses(processIds, arrayBytesSize, bytesCopied);
            List <int> exeFilePids = new List <int>();

            foreach (string exeName in HookManager.ExeNamesToHide)
            {
                Process [] exeFiles = Process.GetProcessesByName(exeName);
                foreach (Process exeFile in exeFiles)
                {
                    if (exeFile.Id != currentEvePID)
                    {
                        exeFilePids.Add(exeFile.Id);
                    }
                }
            }

            uint bytesCopiedUint = (uint)Marshal.ReadIntPtr(bytesCopied);
            uint pIDsCopied      = bytesCopiedUint / sizeof(uint);
            uint pidsDeleted     = 0;

            uint i = 0;

            while (i < pIDsCopied)
            {
                uint currentPID = (uint)Marshal.ReadIntPtr(processIds, (int)i * sizeof(uint));
                if (exeFilePids.Contains((int)currentPID))
                {
                    pidsDeleted++;
                    Marshal.WriteIntPtr(processIds, sizeof(uint) * (int)i, (IntPtr)0);


                    for (uint b = i; b < (pIDsCopied - 1); b++)
                    {
                        uint nextPID = (uint)Marshal.ReadIntPtr(processIds, (int)(b + 1) * sizeof(uint));
                        Marshal.WriteIntPtr(processIds, sizeof(uint) * (int)b, (IntPtr)nextPID);
                    }
                    continue;
                }
                i++;
            }
            Marshal.WriteIntPtr(bytesCopied, 0, (IntPtr)((pIDsCopied - pidsDeleted) * sizeof(uint)));
            HookManager.Log("---------EnumProcessesDetourEnd------");
            return(success);
        }
Exemplo n.º 7
0
        private bool VerifyBindResponse(IntPtr buffer)
        {
            var recvBytes = new byte[10] {
                Marshal.ReadByte(buffer), Marshal.ReadByte(buffer, 1), Marshal.ReadByte(buffer, 2), Marshal.ReadByte(buffer, 3), Marshal.ReadByte(buffer, 4), Marshal.ReadByte(buffer, 5), Marshal.ReadByte(buffer, 6), Marshal.ReadByte(buffer, 7), Marshal.ReadByte(buffer, 8), Marshal.ReadByte(buffer, 9)
            };

            if (recvBytes[1] != 0)
            {
                if (recvBytes[1] == 1)
                {
                    HookManager.Log("General failure");
                }
                if (recvBytes[1] == 2)
                {
                    HookManager.Log("connection not allowed by ruleset");
                }
                if (recvBytes[1] == 3)
                {
                    HookManager.Log("network unreachable");
                }
                if (recvBytes[1] == 4)
                {
                    HookManager.Log("host unreachable");
                }
                if (recvBytes[1] == 5)
                {
                    HookManager.Log("connection refused by destination host");
                }
                if (recvBytes[1] == 6)
                {
                    HookManager.Log("TTL expired");
                }
                if (recvBytes[1] == 7)
                {
                    HookManager.Log("command not supported / protocol error");
                }
                if (recvBytes[1] == 8)
                {
                    HookManager.Log("address type not supported");
                }

                HookManager.Log("Proxy: Connection error binding eve server");
                return(false);
            }
            return(true);
        }
        public SHGetFolderPathWController()
        {
            this.Error = false;
            this.Name  = typeof(SHGetFolderPathWController).Name;
            try {
                this._hook = LocalHook.Create(
                    LocalHook.GetProcAddress("shell32.dll", "SHGetFolderPathW"),
                    new Win32Hooks.SHGetFolderPathWController.SHGetFolderPathWDelegate(SHGetFolderPathWDetour),
                    this);

                _hook.ThreadACL.SetExclusiveACL(new Int32[] { 1 });
                this.Error = false;
            } catch (Exception e) {
                HookManager.Log("SHGetFolderPathWController Exception: " + e.ToString());
                this.Error = true;
            }
        }
        public LoadLibraryAController()
        {
            this.Error = false;
            this.Name  = typeof(LoadLibraryAController).Name;
            HookManager.Log(this.Name);

            try {
                this._hook = LocalHook.Create(
                    LocalHook.GetProcAddress("Kernel32.dll", "LoadLibraryA"),
                    new Win32Hooks.LoadLibraryAController.LoadLibraryADelegate(LoadLibraryADetour),
                    this);

                _hook.ThreadACL.SetExclusiveACL(new Int32[] { 1 });
                this.Error = false;
            } catch (Exception) {
                this.Error = true;
            }
        }
Exemplo n.º 10
0
        private int RegQueryValueExADetour(UIntPtr hKey, IntPtr lpValueName, int lpReserved, IntPtr lpType, IntPtr lpData, IntPtr lpcbData)
        {
            var result = RegQueryValueExA(hKey, lpValueName, lpReserved, lpType, lpData, lpcbData);

            var  keyValue     = Marshal.PtrToStringAnsi(lpValueName);
            var  lpDataString = Marshal.PtrToStringAnsi(lpData);
            bool log          = false;

            if (keyValue == "ProductId")
            {
                log = true;
                var    returnValue = Marshal.PtrToStringAnsi(lpData);
                IntPtr newValue    = IntPtr.Zero;
                try
                {
                    newValue = Marshal.StringToHGlobalAnsi(_prodKey);
                    var size = Marshal.ReadInt32(lpcbData);
                    Utility.Utility.CopyMemory(lpData, newValue, (uint)size);
                }
                finally
                {
                    if (newValue != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(newValue);
                    }
                }
            }
            var lpDataStringAfter = Marshal.PtrToStringAnsi(lpData);

            if (log)
            {
                HookManager.Log("[RegQueryValueExADetour] Before: " + lpDataString.ToString(), Color.Orange);
                HookManager.Log("[RegQueryValueExADetour] After: " + lpDataStringAfter.ToString(), Color.Orange);
            }
            return(result);
        }
Exemplo n.º 11
0
        public static void Test()
        {
            HookManager.Log("[Stealthtest] Starting Stealthtest.");
            HookManager.Log("[Stealthtest] Enumprocesses start.");

            UInt32 arraySize      = 200;
            UInt32 arrayBytesSize = arraySize * sizeof(UInt32);

            UInt32[] processIds         = new UInt32[arraySize];
            UInt32[] processIdsToReturn = new UInt32[arraySize];
            UInt32   bytesCopied;


            bool success = EnumProcesses(processIds, arrayBytesSize, out bytesCopied);

            if (!success)
            {
                return;
            }
            if (0 == bytesCopied)
            {
                return;
            }

            int numIdsCopied  = Convert.ToInt32(bytesCopied / 4);
            int currentEvePID = Process.GetCurrentProcess().Id;

            int processID = 0;


            for (int i = 0; i < numIdsCopied; i++)
            {
                processID = Convert.ToInt32(processIds[i]);
                HookManager.Log("ProcID i: (" + i + ") " + processID + " ExeName: " + Process.GetProcessById(processID).ProcessName);
            }

            HookManager.Log("[Stealthtest] Enumprocesses end.");

            string[] dllNames = { "EveDiscovery", "Utility.dll", "EasyHook.dll", "AppDomainHandler.dll", "NotExisting.dll", "HookManager.exe", "Questor.exe", "DirectEve.dll" };

            foreach (string dllName in dllNames)
            {
                IntPtr ptr = LoadLibrary(dllName);
                if (ptr != IntPtr.Zero)
                {
                    HookManager.Log("[Stealthtest-LoadLibrary] Handle found for " + dllName);
                }
                else
                {
                    HookManager.Log("[Stealthtest-LoadLibrary] Handle NOT found for " + dllName);
                }

                ptr = IntPtr.Zero;


                ptr = GetModuleHandle(dllName);
                if (ptr != IntPtr.Zero)
                {
                    HookManager.Log("[Stealthtest-GetModuleHandle] Handle found for: " + dllName);
                }
                else
                {
                    HookManager.Log("[Stealthtest-GetModuleHandle] Handle not found for: " + dllName);
                }

                ptr = IntPtr.Zero;
            }
        }
Exemplo n.º 12
0
        private int WinsockConnectDetour(IntPtr s, IntPtr addr, int addrsize)
        {
            lock (winsockLock)
            {
                //System.Diagnostics.Debugger.Launch();
                if (ip != null && !ip.Equals("ip"))
                {
                    ////Get EVE IP
                    sockaddr_in structure = (sockaddr_in)Marshal.PtrToStructure(addr, typeof(sockaddr_in));
                    string      eveIp     = new System.Net.IPAddress(structure.sin_addr.S_addr).ToString();
                    ushort      evePort   = ntohs(structure.sin_port);

                    ////Connect to Socks5 server
                    SetAddr(s, addr, ip, port);
                    var result = Connect(s, addr, addrsize);
                    if (result == -1)
                    {
                        return(-1);
                    }

                    ////Send Protocol Socks5
                    IntPtr socksProtocolRequest = SetUpSocks5Request();
                    result = send(s, socksProtocolRequest, 4, 0);
                    if (result == -1)
                    {
                        return(-1);
                    }

                    ////Response
                    var response = Recieve(s, 2);
                    if (response == IntPtr.Zero)
                    {
                        return(-1);
                    }

                    byte[] recvBytes = new byte[2] {
                        Marshal.ReadByte(response), Marshal.ReadByte(response, 1)
                    };
                    if (recvBytes[1] == 255)
                    {
                        HookManager.Log("No authentication method was accepted by the proxy server");
                        return(-1);
                    }
                    if (recvBytes[0] != 5)
                    {
                        HookManager.Log("No SOCKS5 proxy");
                        return(-1);
                    }

                    ////If authenticaterequest response, send authenicate request
                    if (recvBytes[1] == 2)
                    {
                        int length = 0;
                        var authenticateRequest = SetUpAuthenticateRequest(user, pass, out length);
                        result = Send(s, authenticateRequest, length);

                        ////Response
                        response = Recieve(s, 2);
                        if (response == IntPtr.Zero)
                        {
                            return(-1);
                        }

                        recvBytes = new byte[2] {
                            Marshal.ReadByte(response), Marshal.ReadByte(response, 1)
                        };
                        if (recvBytes[1] != 0)
                        {
                            HookManager.Log("Proxy: incorrect username/password");
                            return(-1);
                        }
                    }

                    ////Request bind with eve server
                    var bindRequest = SetUpBindWithEve(eveIp, evePort);
                    result = Send(s, bindRequest, 10);
                    if (result == -1)
                    {
                        return(-1);
                    }
                    ////Reponse
                    response = Recieve(s, 10);
                    if (response == IntPtr.Zero)
                    {
                        return(-1);
                    }
                    if (!VerifyBindResponse(response))
                    {
                        return(-1);
                    }

                    ////Setup success
                    WSASetLastError(0);
                    SetLastError(0);

                    ////Clean memory
                    foreach (var ptr in allocatedMemory)
                    {
                        Marshal.FreeHGlobal(ptr);
                    }

                    allocatedMemory.Clear();
                    return(0);
                }
                else
                {
                    var result = connect(s, addr, addrsize);
                    return(result);
                }
            }
        }
Exemplo n.º 13
0
        private int WinsockConnectDetour(IntPtr s, IntPtr sockAddr, int addrsize)
        {
            lock (wSockLock)
            {
                // retrieve remote ip
                sockaddr_in structure  = (sockaddr_in)Marshal.PtrToStructure(sockAddr, typeof(sockaddr_in));
                string      remoteIp   = new System.Net.IPAddress(structure.sin_addr.S_addr).ToString();
                ushort      remotePort = ntohs(structure.sin_port);
                HookManager.Log("Ip: " + remoteIp + " Port: " + remotePort.ToString() + " Addrsize: " + addrsize);

                if (!remoteIp.Contains("127.0.0.1"))
                {
                    // connect to socks5 server
                    //IntPtr test = CreateAddr(proxyIp,proxyPort.ToString());
                    SetAddr(sockAddr, proxyIp, proxyPort.ToString());
                    var result = connect(s, sockAddr, addrsize);

                    // send socks 5 request
                    IntPtr socksProtocolRequest = SetUpSocks5Request();

                    result = -1;
                    while (result == -1)
                    {
                        result = send(s, socksProtocolRequest, 4, 0);
                        var errorcode = WSAGetLastError();
                        if (errorcode != WSAENOTCONN && errorcode != WSANOERROR)
                        {
                            HookManager.Log("Send failed, Error: + " + errorcode);
                            return(-1);
                        }
                        Thread.Sleep(1);
                    }


                    // retrieve server repsonse
                    var response = IntPtr.Zero;
                    while (response == IntPtr.Zero)
                    {
                        response = Recieve(s, 2);
                        var errorcode = WSAGetLastError();
                        if (errorcode != WSAEWOULDBLOCK && errorcode != WSANOERROR)
                        {
                            HookManager.Log("Recieve FAILED response == IntPtr.Zero! Lasterror: " + errorcode.ToString());
                            return(-1);
                        }
                        Thread.Sleep(1);
                    }

                    byte[] recvBytes = new byte[2] {
                        Marshal.ReadByte(response), Marshal.ReadByte(response, 1)
                    };
                    if (recvBytes[1] == 255)
                    {
                        HookManager.Log("No authentication method was accepted by the proxy server");
                        return(-1);
                    }
                    if (recvBytes[0] != 5)
                    {
                        HookManager.Log("No SOCKS5 proxy");
                        return(-1);
                    }

                    // if auth request response, send authenicate request
                    if (recvBytes[1] == 2)
                    {
                        int length = 0;
                        var authenticateRequest = SetUpAuthenticateRequest(proxyUser, proxyPass, out length);
                        result = -1;
                        while (result == -1)
                        {
                            result = send(s, authenticateRequest, length, 0);
                            var errorcode = WSAGetLastError();
                            if (errorcode != WSAENOTCONN && errorcode != WSANOERROR)
                            {
                                HookManager.Log("Send failed, Error: + " + errorcode);
                                return(-1);
                            }
                            Thread.Sleep(1);
                        }


                        response = IntPtr.Zero;
                        while (response == IntPtr.Zero)
                        {
                            response = Recieve(s, 2);
                            var errorcode = WSAGetLastError();
                            if (errorcode != WSAEWOULDBLOCK && errorcode != WSANOERROR)
                            {
                                HookManager.Log("Recieve FAILED response == IntPtr.Zero! Lasterror: " + errorcode.ToString());
                                return(-1);
                            }
                            Thread.Sleep(1);
                        }

                        recvBytes = new byte[2] {
                            Marshal.ReadByte(response), Marshal.ReadByte(response, 1)
                        };
                        if (recvBytes[1] != 0)
                        {
                            //HookManager.Log("Proxy: incorrect username/password");
                            HookManager.Log("Proxy: incorrect username/password");
                            return(-1);
                        }
                    }

                    // request bind with server
                    var bindRequest = SetUpBindWithRemoteHost(remoteIp, remotePort);
                    result = -1;
                    while (result == -1)
                    {
                        result = send(s, bindRequest, 10, 0);
                        var errorcode = WSAGetLastError();
                        if (errorcode != WSAENOTCONN && errorcode != WSANOERROR)
                        {
                            HookManager.Log("Send failed (bindRequest), Error: + " + errorcode);
                            return(-1);
                        }
                        Thread.Sleep(1);
                    }


                    // bind response
                    response = IntPtr.Zero;
                    while (response == IntPtr.Zero)
                    {
                        response = Recieve(s, 10);
                        var errorcode = WSAGetLastError();
                        if (errorcode != WSAEWOULDBLOCK && errorcode != WSANOERROR)
                        {
                            HookManager.Log("Recieve FAILED response == IntPtr.Zero! Lasterror: " + errorcode.ToString());
                            return(-1);
                        }
                        Thread.Sleep(1);
                    }


                    if (!VerifyBindResponse(response))
                    {
                        HookManager.Log("VerifyBindResponse failed!");
                        return(-1);
                    }

                    // success
                    WSASetLastError(0);
                    SetLastError(0);

                    // clean memory
                    foreach (var ptr in allocatedMemory)
                    {
                        Marshal.FreeHGlobal(ptr);
                    }

                    allocatedMemory.Clear();
                    return(0);
                }
                else
                {
                    return(connect(s, sockAddr, addrsize));
                }
            }
        }