cover image for post 'A new Murofet seed'

A new Murofet seed

Advent of DGAs - Day 2
Table of Contents
Advent of DGAs

This blog post is part of the Advent of DGAs series where I publish one post daily about a sample that looks like it uses a Domain Generation Algorithm.

I don't expect any sample to be relevant anymore and spend very little time on each sample, so don't expect the quality to be amazing.

Of course I'm also using AI to assist with the analysis and unpacking of the malware samples.

Disclaimer

These are just unpolished notes. The content likely lacks clarity and structure; and the results might not be adequately verified and/or incomplete.

DGArchive

The DGA in this blog post has been implemented by the DGArchive project.

Malpedia

For more information about the malware in this blog post see the Malpedia entry on Zeus.

Related Posts This is one of two blog posts on "Advent of DGAs". Check out the other parts here:

Today I’m hunting on Netlab 360s DGA Github repository. It lists suspicious samples from PassiveDNS.cn and the 360 Sandbox. The oldest open issue turned out be quite disappointing, so I’m keeping that for later when I eventually run out of samples. But the second oldest could be interesting:

FieldValue
MD59690bee17e9d4b83ae584f5d91849a6e
SHA107e596acc5f4247b4cba4b391abad73eefa7389d
SHA256c07576f00f7bb97e525c59b2f3d19c2a31a392228b4273ad3d74f75b4d786325
File size514560 bytes
FormatPE32 executable (GUI)
Architecturex86 (i386)
LanguageNative code; hand-written x86 in the loader, C/C++ in the payload
RuntimeNot applicable
VirusTotalView sample on VirusTotal

It produces domains like these

  • kpjprkqhsmqrmsj[.]org
  • iieqqoytgohjytil[.]info
  • iieqqoytgohjytil[.]com
  • qwdlnpptqrgsdprf[.]net
  • qwdlnpptqrgsdprf[.]org
  • wtgtpbrzogowkjt[.]biz
  • wtgtpbrzogowkjt[.]com
  • njpqlupthfhwxqns[.]org
  • njpqlupthfhwxqns[.]com

The sample is over 10 years old now, but the domains are not yet listed on DGArchive. The first, kpjprkqhsmqrmsj[.]org, is not generated at all. It is a hostname stored encrypted inside the final payload and used as the first connection target. The other eight come from a domain generation algorithm that I already documented in 2015: Three Variants of Murofet’s DGA.

Of course, it was only after I finished the analysis that I realised I’d already looked at this DGA. The original post covered only my reimplementation, so this time I’ll take a closer look at the ancient sample itself. A few things stand out:

  1. The payload is hidden behind a loader that reads the return value of a deliberately failing Windows API call to decode its next stage, which breaks naive emulation.

  2. The DGA walks its candidate list sequentially from a starting point derived from the current minute, which gives defenders an unusually crisp DNS pattern.

  3. And two consecutive candidates always share the same second-level label and differ only in the TLD.

Unpacking

The sample is a small PE file that is almost entirely padding. Nearly two thirds of it are zero bytes, which are there to inflate the file and the .rdata section, whose virtual size is sixteen megabytes. The only live content is a short loader in the code section, a compressed blob at the start of .rdata, and a block of shellcode in .data:

Unpacking chain of the sample

The above illustration shows the chain on one linear scale. The first layer is the loader’s own decoding routine. It decodes the 1,444-byte shellcode in .data in place with a four byte XOR. The key is a constant taken from the loader’s own bytes, reduced by a descending counter. The detail that matters is that the number of DWORDs, and the addresses used by the routine, are all calculated from the return value of WmiNotificationRegistrationA, which the loader calls with invalid arguments. On a real Windows system the call fails with the invalid-parameter error code. Only that value yields a block count of 361 DWORDs and coherent code. An emulator that returns zero or a different error decodes garbage.

Stage 0 decoding loop: the key DWORD comes from the loader’s own code and is combined with a counter.

The shellcode is a classic reflective loader. It resolves its APIs from strings built on the stack, removes the protection from the process’s own image, decompresses the blob from .rdata with RtlDecompressBuffer using LZNT1, and then XORs every byte of the result with 0x4C, skipping bytes that are 0x00 or 0x4C. The resulting PE is mapped over the original image. The loader fixes relocations and imports, patches the image base in the PEB and the loader list, and jumps to the entry point. The sample therefore never writes the payload to disk, and the process that runs the bot is the original process with a replaced image.

Source of the Domains

The URLs for Murofet to phone home are built from an encoded template of the form http://<host>/news/. Like all of the bot’s strings, the template is stored in a table whose entries carry a one-byte key and a length, and each character is XORed with that key and its own position. Decoding the table gives the full string inventory and also shows what the bot uses as a clock: Two entries are the URLs www.google.com/webhp and www.bing.com. The selection loop requests them in this order, and stops at the first one that answers. The response is read through HttpQueryInfo with the flag that returns the Date header as a SYSTEMTIME structure. If neither request produces a plausible year, the bot falls back to the local UTC system time. The DGA therefore runs on UTC dates, and a victim with a wrong local clock still computes the same domains as everyone else as long as the web request succeeds.

The first hostname source is the encrypted fallback. An 888-byte blob in the code section is XORed with a key of the same length stored in the relocation section, an odd place for data that the loader never touches. The result starts with the NUL-terminated string kpjprkqhsmqrmsj.org. The bot copies the hostname into the working buffer when the buffer is empty and the name is shorter than 30 characters, so this is the first attempt of every connection cycle. A registry-based cache of a previously working host also exists, and it takes priority if it supplies a name. The short routine that XORs the stored configuration with its key and yields the fallback hostname is shown below:

The short routine that XORs the stored configuration with its key and yields the fallback hostname.

The second source of hostnames is a DGA. The date from the previous step is reduced to three bytes: the low byte of the year plus 0x30, the month and the day, followed by a zero byte. This DWORD is XORed with the constant 0x4522F701. A second DWORD is the candidate index with its lowest bit cleared, XORed with the same constant. The eight resulting bytes are hashed with MD5 through the Windows CryptoAPI. Each of the 16 digest bytes is then turned into a letter by adding its high and low nibble and adding the sum to a. Sums above 25 do not map to a letter and are dropped, so the label has between 9 and 16 characters, in practice 13 to 16 characters in most cases. The TLD depends on the original index and is chosen in a fixed order: .biz for multiples of five, then .info for multiples of four, then .org for multiples of three, and finally .net for even and .com for odd indices. The seed constant is stored as a plain immediate in the code, so there is no configuration dependency and every bot in this build computes identical domains.

unsigned __int8 __userpurge dga_generate_domain@<al>(_BYTE *systemtime@<eax>, int out_domain, unsigned int index)
{
  BYTE month_byte; // cl
  BYTE *xor_ptr; // eax
  int xor_count; // ecx
  int digest_bytes_left; // edi
  unsigned __int8 label_len; // bl
  BYTE *digest_ptr; // edx
  unsigned __int8 letter; // al
  unsigned __int8 dot_pos; // bl
  _DWORD *tld_ptr; // ecx
  unsigned __int8 domain_len; // bl
  BYTE md5_digest[16]; // [esp+10h] [ebp-28h] BYREF
  BYTE md5_input[4]; // [esp+20h] [ebp-18h] BYREF
  unsigned int md5_input_index_word; // [esp+24h] [ebp-14h]
  HCRYPTPROV hProv; // [esp+28h] [ebp-10h] BYREF
  DWORD digest_len; // [esp+2Ch] [ebp-Ch] BYREF
  HCRYPTHASH hHash; // [esp+30h] [ebp-8h] BYREF
  char hash_ok; // [esp+37h] [ebp-1h]

  md5_input[0] = *systemtime + 48;
  month_byte = systemtime[2];
  md5_input[2] = systemtime[6];
  md5_input[1] = month_byte;
  md5_input_index_word = index & 0xFFFFFFFE;
  md5_input[3] = 0;
  xor_ptr = md5_input;
  for ( xor_count = 2; xor_count != 0; --xor_count )
  {
    *xor_ptr ^= 0x4522F701u;
    xor_ptr += 4;
  }
  hash_ok = 0;
  if ( !CryptAcquireContextW(
          phProv: &hProv,
          szContainer: nullptr,
          szProvider: nullptr,
          dwProvType: 1u,
          dwFlags: 0xF0000040) )
    return 0;
  digest_bytes_left = 16;
  if ( CryptCreateHash(hProv, Algid: 0x8003u, hKey: 0, dwFlags: 0, phHash: &hHash) )
  {
    digest_len = 16;
    if ( CryptHashData(hHash, pbData: md5_input, dwDataLen: 8u, dwFlags: 0)
      && CryptGetHashParam(hHash, dwParam: 2u, pbData: md5_digest, pdwDataLen: &digest_len, dwFlags: 0)
      && digest_len == 16 )
    {
      hash_ok = 1;
    }
    CryptDestroyHash(hHash);
  }
  CryptReleaseContext(hProv, dwFlags: 0);
  if ( hash_ok == 0 )
    return 0;
  label_len = 0;
  digest_ptr = md5_digest;
  do
  {
    letter = (*digest_ptr >> 4) + (*digest_ptr & 0xF) + 97;
    if ( letter <= 0x7Au )
      *(label_len++ + out_domain) = letter;
    ++digest_ptr;
    --digest_bytes_left;
  }
  while ( digest_bytes_left != 0 );
  *(label_len + out_domain) = 46;
  dot_pos = label_len + 1;
  tld_ptr = (out_domain + dot_pos);
  domain_len = dot_pos + 3;
  if ( index % 5 != 0 )
  {
    if ( (index & 3) != 0 )
    {
      if ( index % 3 != 0 )
        *tld_ptr = (index & 1) != 0 ? 7171939 : 7628142;
      else
        *tld_ptr = 6779503;
    }
    else
    {
      *tld_ptr = 1868983913;
      ++domain_len;
    }
  }
  else
  {
    *tld_ptr = 8022370;
  }
  *(domain_len + out_domain) = 0;
  return domain_len;
}

Clearing the lowest bit before hashing has a visible consequence: indices 2k and 2k+1 produce the same label. They differ only in the TLD, and the pair is always tried back to back. That is what the capture in the introduction shows.

The outer loop starts at the index from the current minute, up to 257 attempts, with a random wait of 4 to 6 seconds between attempts:

BOOL __stdcall sub_40D74B(int (__fastcall *a1)(CHAR *, int, int), int a2)
{
  unsigned __int8 i; // bl
  int v3; // eax
  LPVOID *v4; // edi
  void *v5; // esi
  __int64 v6; // rax
  __int64 v7; // rax
  int v8; // ecx
  unsigned __int8 v9; // al
  int v10; // eax
  DWORD v11; // eax
  int v12; // ecx
  int v14; // [esp+Ch] [ebp-544h]
  unsigned int v15; // [esp+10h] [ebp-540h]
  _DWORD v16[2]; // [esp+14h] [ebp-53Ch] BYREF
  DWORD v17; // [esp+1Ch] [ebp-534h]
  struct _SYSTEMTIME SystemTime; // [esp+20h] [ebp-530h] BYREF
  _BYTE v19[32]; // [esp+30h] [ebp-520h] BYREF
  _BYTE v20[16]; // [esp+50h] [ebp-500h] BYREF
  CHAR v21[48]; // [esp+60h] [ebp-4F0h] BYREF
  _BYTE v22[328]; // [esp+90h] [ebp-4C0h] BYREF
  _BYTE v23[741]; // [esp+1D8h] [ebp-378h] BYREF
  _BYTE v24[147]; // [esp+4BDh] [ebp-93h] BYREF

  v16[0] = 253;
  v16[1] = 254;
  sub_408E94(a1: &SystemTime, a2: 0, a3: 16);
  for ( i = 0; i < 2u; ++i )
  {
    XOR_THING(a1: v16[i], a2: v22);
    v17 = sub_4075BA(a1: &SystemTime, a2: v22, a3: hHandle);
    if ( v17 != 0 )
      break;
  }
  if ( SystemTime.wYear < 0x7DBu )
    GetSystemTime(lpSystemTime: &SystemTime);
  XOR_THING(a1: 0xCu, a2: v20);
  v19[0] = 0;
  v3 = sub_4194BB();
  v4 = v3;
  if ( v3 != 0 )
  {
    v5 = sub_424F27(a1: v16, a2: v3, a3: 5, a4: 0x20000000);
    if ( v5 != nullptr )
    {
      LODWORD(v6) = v16[0];
      if ( (v16[0] - 5) <= 0x18 )
      {
        HIDWORD(v6) = v19;
        sub_41D84C(a1: v6, a2: v5);
      }
      sub_408D92(lpMem: v5);
    }
    sub_408D92(lpMem: *v4);
    sub_408D92(lpMem: v4);
  }
  if ( v19[0] == 0 )
  {
    sub_40D959(a1: v23);
    LODWORD(v7) = sub_41D9DC(this: v24);
    if ( v7 < 0x1E )
    {
      HIDWORD(v7) = v19;
      sub_41D84C(a1: v7, a2: v8);
    }
    sub_408E94(a1: v23, a2: 0, a3: 888);
  }
  v16[0] = 0;
  v14 = 0;
  v15 = 17 * SystemTime.wMinute % 0x3FC;
  while ( 1 )
  {
    if ( v14 == 0 && v19[0] != 0 || (v9 = sub_42034F(a1: &SystemTime, a2: v19, a3: v15 % 0x3FC), ++v15, v9 != 0) )
    {
      if ( sub_41E194(a1: 46, a2: v21, a3: v20, v19) > 0 )
        break;
    }
LABEL_23:
    v11 = sub_4169B4(result: 6000, a2: 4000);
    if ( WaitForSingleObject(hHandle: hHandle, dwMilliseconds: v11) == 258 && ++v14 <= 0x100 )
      continue;
    return v16[0] > 0;
  }
  v10 = a1(a1: v21, a2: v17, a3: a2);
  v16[0] = v10;
  if ( v10 <= 0 )
  {
    if ( v10 < 0 )
      return v16[0] > 0;
    goto LABEL_23;
  }
  if ( sub_419562() != 0 )
  {
    sub_41D9DC(this: v19);
    sub_424D79(a1: 5, a2: 537001984, a3: v12);
    sub_4195CD();
  }
  return v16[0] > 0;
}

The start index is 17 times the current minute modulo 1,020, and each failed attempt advances the index by one. A cycle makes at most 257 attempts: the stored hostname first, then up to 256 generated ones. Between attempts the bot waits a random time between four and six seconds on a handle whose signalling ends the cycle. A negative result from the connection callback ends the cycle at once, and a positive one stores the working host and ends it as well. The capture therefore shows what a sandbox sees when the C2 is gone: the embedded name, then the generated names one after another. The sample was observed for only eight generated names, so the run was cut short before the full 256 were tried.

Python Reimplementation

The script prints all 1,020 candidates of one day in index order. It takes the date with -d (UTC today by default) and the seed with -s (default is the value from the sample).

#!/usr/bin/env python3
import argparse
import hashlib
import struct
from datetime import datetime, timezone

DEFAULT_SEED = 0x4522F701
DOMAINS_PER_DAY = 1020  # index range used by the sample: 0..1019


def generate(year, month, day, seed, index):
    # SYSTEMTIME bytes: low byte of (year + 0x30), month, day, 0
    date_word = ((year + 0x30) & 0xFF) | (month << 8) | (day << 16)
    # the low bit of the index is cleared before hashing
    block = struct.pack("<II", date_word ^ seed, (index & 0xFFFFFFFE) ^ seed)
    digest = hashlib.md5(block).digest()
    label = ""
    for b in digest:
        s = (b >> 4) + (b & 0xF)
        if s <= 25:
            label += chr(97 + s)
    if index % 5 == 0:
        tld = "biz"
    elif index % 4 == 0:
        tld = "info"
    elif index % 3 == 0:
        tld = "org"
    elif index % 2 == 0:
        tld = "net"
    else:
        tld = "com"
    return label + "." + tld


def main():
    p = argparse.ArgumentParser(description="DGA of Murofet variant 2")
    p.add_argument("-d", "--date", help="YYYY-MM-DD (default: today, UTC)")
    p.add_argument("-s", "--seed", default=hex(DEFAULT_SEED),
                   help="32-bit XOR constant (default: %(default)s)")
    a = p.parse_args()
    if a.date:
        d = datetime.strptime(a.date, "%Y-%m-%d")
    else:
        d = datetime.now(timezone.utc)
    seed = int(a.seed, 0) & 0xFFFFFFFF
    for i in range(DOMAINS_PER_DAY):
        print(generate(d.year, d.month, d.day, seed, i))


if __name__ == "__main__":
    main()

The domains from the introduction are covered by date 2016-05-26 (except the first, hardcoded one of course).

Characteristics

propertyvalue
typeTDD-H-N
seedingtime-dependent: UTC date from the HTTP Date header of Google or Bing, local UTC clock as fallback
generation schemehashing (MD5 over date and index, digest bytes mapped to letters by nibble sum)
seedhardcoded magic constant 0x4522F701, combined with the date
domain change frequencyevery day
unique domains (per day)1020 (510 distinct labels, each with two TLDs)
sequencesequential indices, starting at 17 × minute mod 1020, wrapping at 1020
wait time between domainsrandom 4 to 6 seconds; at most 257 attempts per cycle (stored host first)
top level domains.biz, .info, .org, .net, .com
second level characterslowercase a–z only; derived from nibble sums of MD5 bytes, bytes with a sum above 25 are skipped
regex^[a-z]{9,16}\.(biz|info|org|net|com)$
second level domain lengthvariable, 9 to 16 characters (usually 14 to 16)

Comparison with the Murofet DGA Write-Up

As mentioned in the introduction, I already wrote about Murofet’s many DGA variants in Three Variants of Murofet’s DGA. So what is different this time? As the following table shows, almost everything is the same apart from the seed (XOR key) and the number of iterations per run (the latter could also be a mistake in the original writeup).

AspectWrite-up, variant 2This sample
Start indexCurrent minute times 17same
Index rangeIndex taken modulo 60 × 17 = 1,020same
Date bytesLow byte of the year plus 0x30, monthsame
GranularityOne daysame
Padding byteOne zero byte after the datesame
Index in the hash inputFour bytes, rounded down to a multiple of twosame
Hash input length8 bytessame
XOR keyobserved keys 0xD6D7A4BE and 0xDEADC2DENew XOR key 0x4522F701
HashMD5same
Second-level charactersFor each digest byte: low nibble plus high nibble plus a, kept if not above zsame
Alphabeta to zsame
Label length0 to 16, expected 15.1, usually 14 to 16same
Letter distributionFrequent around p, rare at both endssame
Domains in pairsYessame
TLDs.biz, .info, .org, .net, .comsame
TLD selectionMultiples of 5 give .biz, then multiples of 4 .info, multiples of 3 .org, even .net, otherwise .comsame
Iterations per runUp to 800At most 257 attempts
Index progressionIncremented by one, wrapping at 1,020same
Date sourceUTC date from the HTTP Date header of Google, then Bing; local UTC time as fallbacksame
Wait between attemptsRandom 4 to 6 secondssame

References