Pull to refresh

Автоматизация блокирования Petya/NonPetya

Reading time 4 min
Views 14K
Коллеги, доброго времени суток.

В связи с шумихой вокруг Petya/NonPetya, моим коллегой Владиславом Ковалевым был разработан скрипт на PowerShell для борьбы с вредителем, за что ему огромное спасибо. Надеюсь кому-то будет полезен. Если кому интересно, прошу под кат

Скрипт petya_youshellnotpass выполняет следующее:

— создает правила в фаерволе, блокирующее уязвимые порты;
— ищет в C:\Windows файлы perfc и удаляет при обнаружении;
— создает новые файлы perfc и устанавливает на них запрет для всех;
— ищет в папке Temp для каждого пользователя exe-файлы и выводит список найденных, нужно просмотреть и удалить подозрительные файлы (вручную, самим)

Правило запуска:
Выполняется в обычном режиме Windows (не безопасном и не PE).

1.Запустить powershell console от админа и прописать:
Set-executionpolicy unrestricted -force

2.Выполнить скрипт petya_youshellnotpass. Внимательно следить за выводом скрипта. Проверить файлы, которые он найдет в папке Temp.

3.В powershell console ввести команду:
Set-executionpolicy restricted -force

Код:

# Get the ID and security principal of the current user account
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
 
# Get the security principal for the Administrator role
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
 
# Check to see if we are currently running "as Administrator"
if ($myWindowsPrincipal.IsInRole($adminRole))
   {
   # We are running "as Administrator" - so change the title and background color to indicate this
   $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
   $Host.UI.RawUI.BackgroundColor = "DarkBlue"
   clear-host
   }
else
   {
   # We are not running "as Administrator" - so relaunch as administrator
   
   # Create a new process object that starts PowerShell
   $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
   
   # Specify the current script path and name as a parameter
   $newProcess.Arguments = $myInvocation.MyCommand.Definition;
   
   # Indicate that the process should be elevated
   $newProcess.Verb = "runas";
   
   # Start the new process
   [System.Diagnostics.Process]::Start($newProcess);
   
   # Exit from the current, unelevated, process
   exit
   }

$Compname = Get-WmiObject -Class win32_computersystem | select -expa name
$Cred = $Compname+"\admin"

Write-Verbose -Message "Start process" -Verbose
Write-Verbose -Message "Adding firewall rule" -Verbose

try{New-NetFirewallRule -Action Block -Description Peta.A -Direction Inbound -DisplayName Peta.A_Block -Profile Any -Protocol TCP -LocalPort 135,139,445,1024-1035}
catch{netsh advfirewall firewall add rule name="Petya.A_Block" protocol=TCP dir=in localport=135,139,445,1024-1035 action=block}



if((Test-Path -Path C:\Windows\perfc) -eq $true)
{
    try
    {
    Remove-Item -Path C:\Windows\perfc -Force -ea Stop
    Write-Verbose -Message "File perfc was already exist" -Verbose
    }
    catch {Write-Verbose -Message "File perfc already fixed" -Verbose}
}

if((Test-Path -Path C:\Windows\perfc.dll) -eq $true)
{
    try
    {
    Remove-Item -Path C:\Windows\perfc.dll -Force -ea Stop
     Write-Verbose -Message "File perfc.dll was already exist" -Verbose
     }
      catch {Write-Verbose -Message "File perfc.dll already fixed" -Verbose}
}

if((Test-Path -Path C:\Windows\perfc.dat) -eq $true)
{
    try
    {
    Remove-Item -Path C:\Windows\perfc.dat -Force -ea stop
    Write-Verbose -Message "File perfc.dat was already exist" -Verbose
    }
     catch {Write-Verbose -Message "File perfc.dat already fixed" -Verbose}
}

try{
New-item -Path C:\Windows -ItemType File -Name Perfc -Force -ea Stop
New-item -Path C:\Windows -ItemType File -Name Perfc.dll -Force -ea Stop
New-item -Path C:\Windows -ItemType File -Name Perfc.dat -Force -ea stop
}catch{Write-Verbose -Message "Dont need to create new files"}

Write-Verbose -Message "Successfully created" -Verbose
$acl1 = Get-acl  C:\Windows\Perfc
$acl2 = Get-acl  C:\Windows\Perfc.dll
$acl3 = Get-acl  C:\Windows\Perfc.dat

$acl1.SetAccessRuleProtection($true,$true)
$acl2.SetAccessRuleProtection($true,$true)
$acl3.SetAccessRuleProtection($true,$true)

$accrule1 = New-Object System.Security.AccessControl.FileSystemAccessRule("NT AUTHORITY\SYSTEM","FullControl","Deny")
$accrule2 = New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Администраторы","FullControl","Deny")
$accrule3 = New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Администраторы","ReadAndExecute","Allow")
$accrule4 = New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Администраторы","ReadAndExecute","Allow")

$acl1.SetAccessRule($accrule1)
$acl1.SetAccessRule($accrule2)
$acl1.SetAccessRule($accrule3)
$acl1.SetAccessRule($accrule4)

$acl2.SetAccessRule($accrule1)
$acl2.SetAccessRule($accrule2)
$acl2.SetAccessRule($accrule3)
$acl2.SetAccessRule($accrule4)

$acl3.SetAccessRule($accrule1)
$acl3.SetAccessRule($accrule2)
$acl3.SetAccessRule($accrule3)
$acl3.SetAccessRule($accrule4)

Set-Acl -AclObject $acl1 -Path C:\Windows\Perfc -ea SilentlyContinue
Set-Acl -AclObject $acl2 -Path C:\Windows\Perfc.dll -ea SilentlyContinue
Set-Acl -AclObject $acl2 -Path C:\Windows\Perfc.dat -ea SilentlyContinue

Write-Verbose -Message "Searching for exe files in temp" -Verbose

$Prof= Get-ChildItem -Path "C:\Users" -Force |where {!($_.Name -like "Все пользователи")-or!($_.Name -like "Public")}| select -expa fullname

[array]$TempFiles = $null
[array]$TempPath = $nell

Foreach ($P in $Prof)
{

$TempPath = $P+"\AppData\Local"
Get-ChildItem -Path "$TempPath" -Force -Recurse -ErrorAction SilentlyContinue | where {$_.name -like "*.exe"} | select name,fullname | Format-Table -HideTableHeaders

}

if ($TempFiles -eq $null){Write-Verbose -Message "None exe file was found" -Verbose}
else{Write-Warning -Message "$TempFiles" -Verbose}



Write-Host "Press any key to continue ..."

$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Tags:
Hubs:
+4
Comments 27
Comments Comments 27

Articles