Using File Server Resource Manager to Screen for Ransomware

Table of contents

The File Server Resource Manager role provides many features. File screening, in particular, can be used to help mitigate damage from a ransomware attack. With file screening, file servers can be configured to perform real time auditing on all shares for any files that become modified to any known ransomware extensions. In the event of a user getting infected with ransomware, the file screen will detect the modification of the files and deny that user access to the file shares, preventing them from damaging any other files. This can save hours of downtime and clean up.

I have created a script that will set up and configure all of this within minutes. The script performs the following actions:

  • Installs the file server resource manager role if it is not installed.
  • Configures file server resource manager to screen for known ransomware file extensions.
  • Configures the file screen to execute a script whenever a file is modified to a known ransomware extension. The script then blocks SMB share access to all shared files on the file server and sends an email message to whatever email specified.

The script requires the following prerequisites:

  • Windows Server 2012 – in order to use the cmdlet that blocks SMB share access.
  • Mail Relay Server – Used to configure email alert.

To create the powershell script, copy the code below into a notepad and save it as a .ps1 (for example, Install-FSRMRansomeware.ps1):

Update- Edited script to restart FSRM service after blocking SMB permissions. Ran into issue where the task was only triggering once.
function Install-FSRMRansomware {
<#
.SYNOPSIS
Installs the File Server Resource Manager role if not installed and then configured a file screen on all drives other than C. 
The file screen screens for possible ransomware infections and then deny's SMB access to the user who trigged the screen.
.PARAMETER SMTPServer
Specify the address of an email relay server. This is used to send the alert emails that generate when the file screen is triggered.
.PARAMETER EmailTO
Specify the email address to send the alerts to.
.PARAMETER EmailFrom
Specify the email address that the email alerts are sent from. 
#>
    [CmdletBinding()]
    param(
         [Parameter(Mandatory=$True,
                    HelpMessage="Please input the address for an accessible email relay server.")]
        [String]$SMTPServer,
        [Parameter(Mandatory=$True,
                   HelpMessage="Please input a valid Email address to send the email alerts to.")]
        [String]$EmailTo,
        [Parameter(Mandatory=$True,
                   HelpMessage="Please specify an email address to recieve alerts from.")]
        [String]$EmailFrom


    )
    
    Process{

            #add the FSRM role if it doesnt exist
            If ((Get-WindowsFeature fs-resource-manager).installed -like "False"){
                Write-Verbose "Installing File Server Resource Manage Role"
                Install-WindowsFeature fs-resource-manager
            }
            If ((Get-WindowsFeature RSAT-FSRM-Mgmt).installed -like "False"){
                Write-Verbose "Installed FSRM RSAT Tools"
                install-windowsfeature RSAT-FSRM-Mgmt
            }

            #Set notifications limit to 0
            Set-FsrmSetting -EmailNotificationLimit 0 -EventNotificationLimit 0 -CommandNotificationLimit 0 -ReportNotificationLimit 0

            #Create File Group for FSRM
            New-FsrmFileGroup -name "Ransomware Files" -IncludePattern @( "*DECRYPT_INSTRUCTION.HTML*",
                              "*HELP_DECRYPT.HTML*", 
                              "*decrypt all files*.bmp*", 
                              "*.ecc",
                              "*.ezz", 
                              "*.exx", 
                              "*.zzz", 
                              "*.xyz", 
                              "*.aaa",
                              "*.abc",
                              "*.ccc", 
                              "*.vvv",
                              "*.xxx", 
                              "*.ttt",
                              "*.micro",
                              "*.encrypted",
                              "*.locked",
                              "*.crypto"
                              "*_crypt",
                              "*.crinf", 
                              "*.r5a", 
                              "*.XRNT", 
                              "*.XTBL", 
                              "*.crypt", 
                              "*.R16M01D05", 
                              "*.pzdc", 
                              "*.good", 
                              "*.LOL!", 
                              "*.OMG*", 
                              "*.RDM", 
                              "*.RRK", 
                              "*.encryptedRSA", 
                              "*.crjoker", 
                              "*.EnCiPhErEd", 
                              "*.LeChiffre", 
                              "*.keybtc@inbox_com", 
                              "*.0x0", 
                              "*.bleep", 
                              "*.1999", 
                              "*.vault", 
                              "*.HA3", 
                              "*.toxcrypt", 
                              "*.magic", 
                              "*.SUPERCRYPT", 
                              "*.CTBL", 
                              "*.CTB2", 
                              "*.locky" )




            #Create FSRM Template xml file and import template then remove xml file
            $FSRMTemplate = @"
<?xml version="1.0" ?><Root ><Header DatabaseVersion = '2.0' ></Header><QuotaTemplates ></QuotaTemplates><DatascreenTemplates ><DatascreenTemplate Name = 'RansomwareCheck' Id = '{122F5AB4-9DF0-4F09-B89E-0F7BDC9D46CC}' Flags = '1' Description = '' ><BlockedGroups ><FileGroup FileGroupId = '{82D08F60-7319-4BE2-8621-066DB91A958E}' Name = 'Ransomware%sFiles' ></FileGroup></BlockedGroups><FileGroupActions ><Action Type="1" Id="{73AFB339-FF17-42DC-B9B9-E7C9A8E7C9A9}" EventType="2" MessageText="User%s[Source%sIo%sOwner]%sattempted%sto%ssave%s[Source%sFile%sPath]%sto%s[File%sScreen%sPath]%son%sthe%s[Server]%sserver.%sThis%sfile%sis%sin%sthe%s[Violated%sFile%sGroup]%sfile%sgroup,%swhich%sis%snot%spermitted%son%sthe%sserver." /><Action Type="3" Id="{D0B80CC5-E6DD-481C-9534-19944A851A72}" ExecutablePath="C:WindowsSystem32WindowsPowerShellv1.0powershell.exe" Arguments="&quot;C:ScriptsScriptToDenyPermissions.PS1&quot;" WorkingDirectory="C:WindowsSystem32WindowsPowerShellv1.0" Account="3" MonitorCommand="0" KillTimeOut="0" LogResult="1" CurrentSid="S-1-5-21-3468280891-3112941812-1175424509-500" /></FileGroupActions></DatascreenTemplate></DatascreenTemplates><FileGroups ></FileGroups></Root>
"@
            $FSRMTemplate | Out-File -FilePath C:userspublicFSRMTemplate.xml 

            Filescrn template import /file:C:userspublicFSRMTemplate.xml 

            Remove-Item -path C:UsersPublicFSRMTemplate.xml 


            #Creates Script Block to perform email message and block SMB Permissions. Exports script block to a PS1 for the File Screen Template.
            $DenyPermissionsScript = @"
                                        
                                        #One second delay to give script enough time to grab newest event logs
                                        sleep -Seconds 1

                                        #Looks in event log for the custom event message generated by the file screen audit. Input's username of the offender into a variable.
                                        `$RansomwareEvents = get-eventlog -logname Application -message "*ransomware*" -newest 50 | where {`$_.eventid -eq 8215}
                                        `$username = (`$RansomwareEvents.message).split()[1]
                                        `$username = `$username -replace ".*\"

                                        #Blocks SMB share access for user
                                        Get-SmbShare | Where-Object currentusers -gt 0 | Block-SmbShareAccess -AccountName `$username -force

                                        #get name of computer and domain name for email message
                                        `$computername = Hostname
                                        `$domain = (Get-WmiObject win32_computersystem).domain

                                        #Send Email Report to servicedesk with information
                                       
                                        `$client = hostname
                                        `$messageSubject = "Server `$computername on the domain `$domain is Infected being attacked by Ransomware"
                                        `$messagebody= "The User `$username has infected the server. They have been denied access to all file shares. Please open a ticket to disinfect their machine. Once they have been disinfected, run the following powershell command on the server `$computername to unblock the user from file shares: get-smbshare | unblock-smbshareaccess -accountname `$username -force "
                                        `$message = New-Object System.Net.Mail.MailMessage "$EmailFrom", "$EmailTo"
                                        `$message.Subject = `$messageSubject
                                        `$message.IsBodyHTML = `$true
                                        `$message.Body =  `$messagebody
                                        `$smtp = New-Object Net.Mail.SmtpClient("$smtpserver")
                                        `$smtp.Send(`$message)

                                        
                                     
"@
     

            #Creates file path to store block smb script that is called by the FSRM template
            New-Item -Path "C:scripts" -Force -Type directory
            $DenyPermissionsScript | Out-File -FilePath "C:scriptsScriptToDenyPermissions.PS1"

            #unblocks the script to allow for execution 
            Unblock-file "C:scriptsScriptToDenyPermissions.PS1"

            #find all drives that are not the C drive and create file screen for those drives. Essentially all drives except the C drive will be monitored for crypto locker files.
            $disks = GET-WMIOBJECT win32_logicaldisk -filter "DriveType='3'" | Where {$_.deviceid -ne "C:"}
            ForEach($disk in $disks) {
                                        $DRIVE = $DISK.DeviceID

                                        New-FSRMFILEScreen -path "$DRIVE" -template "RansomwareCheck"

                                     }

            restart-service "File Server Resource Manager" -force
  
        }
   
}
Install-FSRMRansomware -SMTPServer InsertValidMailRelayServer -EmailTo InsertEmailToSendAlertsTo -EmailFrom InsertEmailToSendEmailFrom

How to Run the Script

Running the script is really simple. I’ve created an advanced function that includes all the parameters necessary to set up the email alerts. All we need to do is edit the parameters for the function being called at the end of the script:

1-Editing Script

 

Once you have inserted your own parameters, save the script. To execute the script, hold down SHIFT and RIGHT CLICK on the .ps1 file. Select COPY AS PATH:

2-Cpypath

Open up an administrative powershell prompt, type in “powershell” and paste in the path we copied, press ENTER to run the script:

PSRun

The script will start to run, if the File Server Resource Manager role is not installed it will begin installing.Once the script finishes, we can look at what was done by opening up Server Manager and clicking on Tools and then selecting File Server Resource Manager:

4-servermanager

If we select the File Groups in the left window pane, we can see our newly created file group called “Ransomware files” that contains all of our known ransomware extensions to screen for:

5-filegroup

If we select File Screen Templates in the left window pane, we can see our “RansomwareCheck” template has been created. Right click and select Edit to look at the configurations. We can see that the Ransomeware Files file group is selected:

6-template

 

If we select the Command tab we can see that the script has been created in the C:Scripts directory on the server. This is the script that performs the SMB blocking action and sends the alert email through the email relay server specified in the script parameters:

7-edittemplate

If we selec the file screens section in the left window pane,  we can see that there is an active file screen on our F drive. By default the script will scan for all available volumes besides the C drive and will create a file screen for that volume. This can be manually modified if desired:

8-filescreen

Testing the Script

If we wanted to test this out, we can go to a workstation and browse out to a shared folder on the newly configured file server. We will mimic the extension change that occurs when a file is encrypted by the cryptolocker virus by renaming the extension of a file to “.crypto”. We can see that the change gets denied:

9-Permissions

 

Also our user’s access to their mapped drive on the file server is now denied access:

10-SMB Blocked

An email is then sent to the email address that we configured in the scripts parameters. We get the information on the user that was infected and the server being attacked. We also get the command that can be run to enable access once again for the user:

11-Alert

If we paste in that command into an administrative powershell prompt on the infected file server, that user can now access their shared folders again:

12-unblock

Keeping Updated on Known Ransomware Extensions

You will want to do your due diligence on making sure the extensions being screened are kept up to date, you can easily edit the file group and add in the extensions at any time. Tripwire has been doing an amazing job at producing security awareness posts that include the most recently discovered ransomware flavors and the extensions they use. Check out their most recent post here. This is great way to protect your organizations data by mitigating the damage done during a ransomware attack. Also, it is free which makes it even better.

Share this post