Simulating A Ransomware Attack With PowerShell

Ransomware issues have escalated as of late.  While there is a common belief that there is no sure fire way of guaranteeing your organization will never be hit by a ransomware attack, IT administrators should be prepared to detect, stop, and recover from it when it strikes.

But how does one test for ransomware detection?

While it is ill advised to purposely install ransomware, there are ways to emulate its effects. Conditions that detection software look for include:

  • A user that renames more than 100 files

  • A user that modifies more than 100 files
     

  • 1 and 2 happen in under 60 seconds

Once the above happens, ransomware will usually encrypt, modify and append the file extension very quickly.
 
NOTE: Many ransomware variants behave in many different ways. The conditions listed above are the  more common behaviors documented.
 
The following PowerShell script can be used to emulate the above conditions within your lab environment:
 

$strDir="C:\temp\test1\"

GCI$strDir|Remove-Item-Force

1..200|%{$strPath=$strDir+$_+".txt";"something"|Out-File$strPath|Out-Null}

Measure-Command{1..101|%{$strPath=$strDir+$_+".txt";$strNewPath=$strPath+".chng";"changed"|Out-File-Append$strPath;Rename-Item-Path$strPath-NewName$strNewPath}}

The breakdown of this script is as follows:

  • Lines 1, 2 and 3 setup the environment. 
     
  • Line 1 assigns $strDir with the the test directory to be monitored for ransomware attacks
     
  • Line 2 empties the test directory which you probably don’t want to do indiscriminately in a production area but I want to do in my test area
     
  • Line 3 creates 200 txt files in $strDir. 1..200 is a slick way of writing all the numbers between 1 and 200 inclusive. Try it yourself in a PowerShell console. Then, for each of those numbers, we’re creating a file and suppressing the output.
     
  • Line 4 simulates the ransomware condition. For 101 files, we’re making a variable $strPath which is an individual file we created in line 3. We’re also crafting a new path stored in $strNewPath which is the same file but with an extension. Then I’m changing the contents of the file by writing “changed” inside it. Finally, I rename the file. The whole thing is wrapped in a Measure-Command block so I can see how long it takes.

During my previous test the ransomware part took 688 ms.

1 2 3 4 5 6 7 8 9 10 11 Days              : 0 Hours             : 0 Minutes           : 0 Seconds           : 0 Milliseconds      : 688 Ticks             : 6887630 TotalDays         : 7.97179398148148E-06 TotalHours        : 0.000191323055555556 TotalMinutes      : 0.0114793833333333 TotalSeconds      : 0.688763 TotalMilliseconds : 688.763

Test this in lab for yourself and see if you can detect this simulated ransomware attack.