Vidar Stealer

Illustration of a bearded Viking-style warrior in a horned helmet and dark armor with a fur collar

Vidar Stealer - The End of its Malware Life Cycle

Introduction

In this post we delve into a recent phishing campaign targeting content creators by masquerading as a prominent brand and proposing collaboration opportunities. Classic Malvertising with a .zip with a poor choice of .scr file to social engineer the victim into executing the Vidar binary. Please note the .scr was inflated > 650mb to prevent virustotal & any.run analysis.

Context

A .scr file is a Windows screensaver, which is an ordinary PE executable: double-clicking one runs it. With file extensions hidden (the Windows default), a name ending in .pdf.scr appears to end in .pdf. Padding a file with junk bytes (binary padding, MITRE ATT&CK T1027.001) pushes it past the upload limits of online sandboxes and scanners, and past the size some antivirus engines will scan. The padding is usually zeros or other repetitive bytes, so a padded file still compresses into a small archive.

The Sample

The phishing email sent to the target describes a collaboration opportunity with the company, detailing the required promotional video post’s duration and the promised payment.

At the email’s bottom, a link to the promotional materials and a personal password are provided:

Phishing email posing as H&M, subject Ads in your video H&M, offering a YouTuber $4000 to $7000 for a 30 to 60 second promo, with a Google Drive link and the personal password HM0223

The link directs the recipient to Google Drive, instructing them to download an archive named H&M Corporation Advertising Contract.zip.

Within the archive are several decoy files related to H&M and a >600MB .scr file named H&M Advertising Contract and Payment Information.pdf.scr.

Archive listing: decoy folders (Dress, Hoodie, Logotype & Pictures, Shoes), the H&M Advertising contract and Payment information screen saver file at 688,709,072 bytes (1,131,329 packed), a promo MP4, and the note Archive password: HM0223

Managed .NET Loader

Analyzing the loader with Detect It Easy (DiE), we found a 32-bit .NET assembly protected by Smart Assembly:

Detect It Easy on the loader: PE32, protector Smart Assembly, library .NET v4.0.30319, Microsoft Linker 8.0, binary overlay

Opening the loader in dnSpy, we confirmed the Smart Assembly protection from the static information fields:

dnSpy showing the loader's assembly attributes, with PoweredBy: Powered by SmartAssembly 6.9.0.114 highlighted

Looking at the entry point, we could see that working with the loader in its current obfuscated state would be inefficient:

Obfuscated entry point in dnSpy: Unicode-escaped type and method names and junk conditions such as if (!false) and if (8 != 0)

To deobfuscate the code, we used Simple Assembly Explorer (SAE):

Simple Assembly Explorer context menu for the loader, with Deobfuscator highlighted

Reopening the deobfuscated file in dnSpy, we got clearer code:

Deobfuscated Main in dnSpy: it creates a c000009 object and passes it to c000066.m000022, with an exception handler calling c000066.m000092

Payload Extraction

The loader executes several critical actions:

  • Creates an instance of c000009, with an internal field containing the path to the injected process.
    The c000009 constructor in dnSpy: field f000001 is set to the .NET runtime directory combined with the result of c000066.m00003e, called with the strings fInckSommmenn and ophKfkG1liw=
  • Passes this instance to the method c000066.m000022, which calls c000066.m00007b with the string fInckSommmenn.
  • The method c000066.m00007b retrieves resource content from the binary resources:
    c000066.m00007b in dnSpy loads a named resource as a byte array through a ResourceManager; below, the resources tree lists fInckSommmenn.resources containing fInckSommmenn
  • The extracted resource content, the string fInckSommmenn, and the c000009 instance are passed to c000066.m000019, which decrypts the payload using an XOR routine and returns the decrypted binary:
    c000066.m000019 in dnSpy: a loop that XORs each payload byte with a key array and subtracts the following byte, modulo 256, then shrinks the array by one byte
  • The decrypted binary and the full path to the injected process are passed to c000066.m00002a for process injection with the decrypted binary content:
    c000066.m000022 in dnSpy with its calls annotated: m00007b as the resource fetching method, m000019 as the resource content decryption method, and m00002a as the injection method

We wrote a PowerShell script to extract the decrypted binary:

# Load the file.
$assembly = [System.Reflection.Assembly]::LoadFile("C:\Users\igal\Desktop\loader.exe")

#Initialize "NS005.c000009" object.
$ini = [Activator]::CreateInstance($assembly.Modules[0].GetType("NS005.c000009"),@())

#Retrieve the resource fetching method and invoke it.
$classType2 = $assembly.GetType("NS004.c000066")
$array = $classType2.GetMethod("m00007b").Invoke($null,@("fInckSommmenn", "fInckSommmenn"))

#Invoke the decryption method with the necessary arguments.
$fixedArray = $classType2.GetMethod("m000019").Invoke($null,@($array, "fInckSommmenn", $ini))

#Write the output to a file.
[io.file]::WriteAllBytes('C:\Users\igal\Desktop\payload.bin',$fixedArray)

Context

.NET reflection lets any .NET program, PowerShell included, load an assembly at run time and call its types and methods by name. Assembly.LoadFile brings the loader into the PowerShell process without running its entry point, so the script can call the resource and decryption methods itself and write the decrypted payload to disk; the injection method is never called. Constructors and static initializers of the types it touches do run, so this is still a job for an isolated analysis VM.

Vidar Core Payload

In this section we examine the Vidar stealer’s capabilities, evasion techniques, and anti-analysis methods. DiE identifies the payload as a 32-bit C/C++ binary:

Detect It Easy on the payload: 32-bit GUI PE built with Visual C/C++ 16.00.30319 and Microsoft Linker 10.00 (Visual Studio 2010 RTM)

Anti-Analysis Measures

When we opened the payload in IDA, the WinMain function was not immediately recognized and appeared as an instruction instead:

IDA View-A with WinMain at 0x4156B0 shown as loose instructions rather than a function, including a jz and jnz pair that both target loc_4156F0+1

Converting the data to code reveals some chunks not correctly interpreted:

IDA listing in which the bytes from 0x41580F onward are still defined as data (db and dd directives) instead of code

After converting the data to code, we marked the instructions from the beginning of WinMain to the relevant mov - pop - return sequence, defining the function’s end (in this case, instructions ranged from 0x4156B0 to 0x415891).

The decompiled view initially shows broken code:

Broken Hex-Rays output for WinMain: impossible conditions such as if (!v7 && v7), MEMORY[...] writes, repeated v6(String1) calls and JUMPOUT(0x41580F)

Opaque predicates are employed to confuse the decompiler:

IDA graph view of two opaque predicates: a jz (74 03) followed by a jnz (75 01), both targeting loc_415748+1, one byte into the next mov eax instruction, and the same pattern at loc_4158B3

Context

An opaque predicate is a conditional branch that always goes the same way, although a static tool cannot easily tell. The pattern here is a JZ immediately followed by a JNZ (or the reverse) to the same address: one of the two always fires, so together they act as an unconditional jump, yet IDA also decodes the fall-through bytes as instructions. The shared target is often one byte inside the next instruction, so real and fake code overlap. IDA’s decompiler shows a jump whose target is not an instruction in the current function, such as the middle of an instruction, as JUMPOUT. The script below rewrites the first jump as a short JMP (opcode 0xEB, same displacement) and overwrites the second with two NOP instructions (0x90).

With a script by @_n1ghtw0lf, we made the decompiled code clearer:

import idc

ea = 0
while True:
    ea =  min(idc.find_binary(ea, idc.SEARCH_NEXT | idc.SEARCH_DOWN, "74 ? 75 ?"),  # JZ / JNZ
              idc.find_binary(ea, idc.SEARCH_NEXT | idc.SEARCH_DOWN, "75 ? 74 ?"))  # JNZ / JZ
    if ea == idc.BADADDR:
    	break
    idc.patch_byte(ea, 0xEB)	# JMP
    idc.patch_byte(ea+2, 0x90)	# NOP
    idc.patch_byte(ea+3, 0x90)	# NOP
Hex-Rays output after the patch script: WinMain now shows memset, lstrcatW with a long English sentence, sub_401060, repeated lstrlenW calls and JUMPOUT(0x415749)

We see some JUMP OUT instruction that suggests more illusive code.

mov     eax, 0FEB912E8h

Undefine EAX:

IDA listing at loc_415749 (call sub_401060, then a jmp to loc_415752+1, where another mov eax, 0FEB9C8E8h sits), beside pseudocode ending in JUMPOUT(0x415753)

Scrubbing another EAX move;

mov     eax, 0FEB9C8E8h

Clear class;

Cleaned-up WinMain pseudocode: junk lstrlenW calls between the real calls mwAllocEXNumaAlloc, mwCheckPhysMem and mwStringDec1

The author added useless calls to deter reverse engineers or confuse them.

Self Termination Trigger / MELT and ANTI-VM

Vidar incorporates several self-termination triggers:

  • VirtualAllocExNuma: Checks for systems with more than one physical CPU:
    Decompiled mwAllocEXNumaAlloc: it calls VirtualAllocExNuma on the current process and calls ExitProcess(0) if the allocation fails
  • Physical Memory Check: Terminates if system memory is below 769MB:
    Decompiled mwCheckPhysMem: it calls GlobalMemoryStatusEx and calls ExitProcess(0) if that fails or ullTotalPhys >> 20 is below 0x309
  • Computer Name Check: Terminates if the computer name is HAL9TH or the user name is JohnDoe:
    Decompiled mwCheckCompUserName: a nested check that compares the computer name with STR_HAL9TH and the user name from GetUserNameA with STR_JohnDoe, then calls API_ExitProcess(0)

HAL9TH and JohnDoe are the computer and user names that Microsoft Defender’s antivirus emulator reports to the programs it runs, so the last check looks for emulation.

String Decryption

Vidar’s strings are encrypted using XOR. The decryption function requires three parameters: Length, XOR key, and Encrypted string. Encrypting strings keeps API names and other telltale text out of a simple strings dump, and because XOR is its own inverse, XORing with the same key again restores the plaintext.

Decompiled mwXorDecrypt(len, a2, xorKey, encString): it allocates len + 1 bytes and XORs xorKey with encString byte by byte, padded with junk wcslen(Destination) calls

We used a modified script by @eln0ty to decrypt these strings:

import idc

START = 0x401190
END = 0x40134D
TEMP = 0x0
FLAG = True
'''
[0] = Encrypted String.
[1] = Xor Key.
[2] = Length.
'''
VALUES = [] 

ea = START

# XOR decryption helper function.
def xorDecrypt(encString, xorKey, keyLen):
    decoded = []
    for i in range(0,len(encString)):
        decoded.append(encString[i] ^ xorKey[i % keyLen])
    return bytes(decoded)



while ea <= END:
    # get argument values 
    if idc.get_operand_type(ea, 0) == idc.o_imm:
        VALUES.append(idc.get_operand_value(ea, 0))
    
    if len(VALUES) == 2:
        if idc.get_operand_type(ea, 0) == idc.o_reg:
            VALUES.append(idc.get_operand_value(ea, 1))
    
    if idc.print_insn_mnem(ea) == "call":
        length = VALUES[2]
        data = idc.get_bytes(VALUES[0], length)
        key = idc.get_bytes(VALUES[1], length)
        VALUES = []
        TEMP = ea
        while FLAG:
            ea = idc.next_head(ea, END)
            if (idc.print_insn_mnem(ea) == "mov") and (idc.get_operand_type(ea, 0) == idc.o_mem) and (idc.get_operand_type(ea, 1) == idc.o_reg):
                dec = xorDecrypt(data, key, length).decode('ISO-8859-1')
                print(f'current location:{hex(ea)}, value will be: {dec}')
                dwordVar = idc.get_operand_value(ea, 0)
                idc.set_cmt(ea, dec, 1)
                idc.set_name(dwordVar, "STR_" + dec, SN_NOWARN)
                FLAG = False
                ea = TEMP
                break


    # move to next instruction
    FLAG = True
    ea = idc.next_head(ea, END)

e.g; Some string names will not be properly staged. IDA parsing issues do not allow foreign language intricacies, so adding a plain common string rectifies the issue:

A mwXorDecrypt call site: the global dword_458DA8 receives the result and carries the decrypted string config.vdf as a comment

The decrypted strings output:

Decompiled string setup after the script ran: globals renamed STR_HAL9TH, STR_JohnDoe, STR_LoadLibraryA, STR_GetProcAddress, STR_kernel32_dll and others, each assigned from a mwXorDecrypt call

DynAPI Resolution

Vidar uses LoadLibraryA and GetProcAddress to resolve necessary APIs along with decrypted strings:

Decompiled mwResolveAPI1: LoadLibraryA on the decrypted kernel32 and advapi32 names, then GetProcAddress for each decrypted API name, stored in globals named API_*

We used another script by @eln0ty to replace variable names for easier analysis:

import idc

start = 0x420874
end = 0x420901
ea = start

api_names = []

while ea <= end:
    # get GetProcAddress API name
    if (idc.print_insn_mnem(ea) == "mov") and (idc.get_operand_type(ea, 0) == idc.o_reg) and (idc.get_operand_type(ea, 1) == idc.o_mem):
        addr = idc.get_operand_value(ea, 1)
        name = idc.get_name(addr)
        if name.startswith("STR_"):
            api_names.append(name)

    # assign GetProcAddress result to global var
    if (idc.print_insn_mnem(ea) == "mov") and (idc.get_operand_type(ea, 0) == idc.o_mem) and (idc.print_operand(ea, 1) == "eax"):
        addr = idc.get_operand_value(ea, 0)
        name = api_names.pop(0)
        idc.set_name(addr, "API_" + name[4:])

    # move to next instruction
    ea = idc.next_head(ea, end)

Core C2 Communication

A DOWNLOADER is used to obtain crucial .dlls for VIDAR Stealer communication.

DLL NameDescription
freebl3.dllNetwork Security Services (NSS) from Mozilla Foundation
mozglue.dllMemory management for Mozilla applications
msvcp140.dllMicrosoft Visual C++ library for C++ programming
nss3.dllNetwork security services for SSL/TLS encryption
softokn3.dllCryptographic library for key management and encryption/decryption
sqlite3.dllAccessing and managing SQLite databases
vcruntime140.dllMicrosoft Visual C++ library for memory management and I/O

In this case, strangely enough, Vidar used external services as shim/gaskets/DynDNS to point to their host. We see this as bad practice given that it exposes the core IP in plain text… and puts the operators DynDNS in control of abuse-rejecting entities.

Surprising considering how much effort the development team has placed into obfuscation..

This would suggest heuristic detections over SSL/TLS are heavily detected, thus in turn suggesting the end of the product (VIDAR) life cycle.

Context

Using a legitimate service this way is known as a dead drop resolver (MITRE ATT&CK T1102.001). The malware downloads a public page, here a Telegram channel and a Steam community profile, and reads the C2 address from text on it, such as the channel description or the profile name. The operator can move the C2 by editing that text, without rebuilding the malware, and the first connection goes to a reputable domain rather than to the C2.

  • Telegram:
    Telegram channel gurutist (2 subscribers) whose description reads kebap hxxp://23.88.36[.]149:80
    Decompiled mwTelegramC2: it assigns the string hxxps://t[.]me/gurutist
  • Steam:
    Decompiled mwSteamC2: it assigns the string hxxps://steamcommunity[.]com/profiles/76561199476091435
    Steam community profile whose display name reads kebap hxxp://195.201.44[.]125

Trigger check would suggest a plain C2 as a backup.

Decompiled mwPlainC2: it assigns the hard-coded string hxxp://95.216.164[.]28:80

After retrieving the C2 Vidar will send a POST request to the URI:

{C2}/{BOT_ID}

In my case the bot id is: 907 which is also assigned a plain string:

Decompiled mwBotnetID: it assigns the string 907

After that first request was made the client will receive a response from the server;

1,1,1,1,1,b36abae611984b4404a903d57724b39e,1,1,1,1,0,123;%DOCUMENTS%\;*.txt;50;true;movies:music:mp3:exe;

Each operation is split with ; delimiter

Conclusion

Though illusive, the VIDAR Stealer is heavily bound to heuristic detections. The Development team is attempting to squeeze the final bit by acquiring reputable services as a C2 for their outputs to evade heuristic analysis. This suggests the end for Vidar stealer and its product life cycle.

YARA Rule

rule win_Vidar
{
	meta:
        author = "dBouLabs"
        description = "Vidar Stealer Obfuscation"
        Date = "18-02-2023"
		
	strings:
		$dll1 = "vcruntime140.dll" ascii wide
		$dll2 = "softokn3.dll" ascii wide
		$dll3 = "nss3.dll" ascii wide
		$dll4 = "msvcp140.dll" ascii wide
		$dll5 = "mozglue.dll" ascii wide
		$dll6 = "freebl3.dll" ascii wide
		$dll7 = "sqlite3.dll" ascii wide
		$c2Fetch1 = "t.me" ascii wide
		$c2Fetch2 = "steamcommunity.com" ascii wide
		$stringDec = {
			68 ?? ?? ?? 00
			68 ?? ?? ?? 00
			B9 ?? ?? 00 00
			E8 ?? ?? ?? ??
			68 ?? ?? ?? 00
			68 ?? ?? ?? 00
			B9 ?? ?? 00 00
			A3 ?? ?? ?? ??
		}
	condition:
		uint16(0) == 0x5a4d and 3 of ($dll*) and 1 of ($c2Fetch*) and #stringDec >= 15
}

References

Co-analysed with Igal Lytzki.

Posted in Write-UpsTags: