- PVSM.RU - https://www.pvsm.ru -

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

Коллеги, доброго времени суток.

В связи с шумихой вокруг 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:Windowsperfc) -eq $true)
{
    try
    {
    Remove-Item -Path C:Windowsperfc -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:Windowsperfc.dll) -eq $true)
{
    try
    {
    Remove-Item -Path C:Windowsperfc.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:Windowsperfc.dat) -eq $true)
{
    try
    {
    Remove-Item -Path C:Windowsperfc.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:WindowsPerfc
$acl2 = Get-acl  C:WindowsPerfc.dll
$acl3 = Get-acl  C:WindowsPerfc.dat

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

$accrule1 = New-Object System.Security.AccessControl.FileSystemAccessRule("NT AUTHORITYSYSTEM","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:WindowsPerfc -ea SilentlyContinue
Set-Acl -AclObject $acl2 -Path C:WindowsPerfc.dll -ea SilentlyContinue
Set-Acl -AclObject $acl2 -Path C:WindowsPerfc.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+"AppDataLocal"
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")

Автор: djipa

Источник [1]


Сайт-источник PVSM.RU: https://www.pvsm.ru

Путь до страницы источника: https://www.pvsm.ru/powershell/259346

Ссылки в тексте:

[1] Источник: https://habrahabr.ru/post/332068/?utm_source=habrahabr&utm_medium=rss&utm_campaign=best