You are on page 1of 280
PU) FORENSICS 610 RevERSE-ENGINEERING Anatysis Toots AND . TECHNIQUES Malicious Code Analysis The right security training for your staff, at the right time, in the right location. Copyright © 2015, The SANS Institue. All rights reserved. The entire contents of th publication ate the property ofthe SANS Institut, IMPORTANT-READ CAREFULLY: This Courseware License Agreement ("CLA") isa legal agreement between you (either tn individual cra single entity; henceforth User) and the SANS Institute forthe personal, ‘on-ansferable use oF this courseware. User auroes thatthe CLA is the complete and ‘exclusive statement of agreement between The SANS Institute and you and tat this CLA, supersedes any oral or writen proposal, agreement or other communication relating to ‘the subject mater ofthis CLA. If any provision ofthis CLA is declared unenforceable in any jurisdiction, then such provision shall be deemed to be severable fom this CLA and shall not affect the remainder thereof. An amendment or addendum to this CLA may ‘accompany this courseware. BY ACCEPTING THIS COURSEWARE YOU AGREE TO BE BOUND BY THE TERMS OF THIS CLA. IF YOU DO NOT AGREE YOU MAY. RETURN IT TO THE SANS INSTITUTE FOR A FULL REFUND, IF APPLICABLE. The SANS Insitute hereby grants User a non-exclusive license to use the material contained in tis courseware subject tothe terms ofthis agrozment. User may not copy, reproduce, republish, distribute, display, modify or create derivative works based upon all orany portion ofthis publication in any medium whether printed, electronic oF otherwise, forany purpose without the express writen consent ofthe SANS Institute ‘Additionally, user may not sll rent, lease, trade, or otherwise transfer the courseware in “any way, shape, o form without the express written consent of the SANS Insitute. “The SANS Institute eserves the Fight to terminate the above lease at any time, Upon termination ofthe lease, user is obligated vo return all materials covered by the lease ‘within a reasonable amount of time SANS acknowledges that any and al software and/or tools presented inthis courseware are the sole property oftheir respective rademarktegisterdicopyright owners AirDrop, AirPort, AirPort Time Capsule, Apple, Apple Remote Desktop, Apple TV, App ap, Back to My Mac, Boot Camp, Cocoa, FaceTitme,FileVault, Fi FireWire logo, Cal, iChat, iLife, Mac, ‘Message, iPad, iPad Air, ‘Photo, iPod, iPod classic, iPod shutMe, iPod nano iPod touch, ‘Funes, iTunes logo, ‘Work, Keychain, Keynote, Mac, Mac Logo, MacBook, MacBook Ar, MacBook Pro, Macintosh, Mac OS, Mac Pro, Numbers, OS X, Pages, Passbook, Retina, Safari, Siri, Spaces, Spotlight, There's an app for tht, Time Capsule, Time Machine, Touch ID, Xeode, Xserve, App Store, and iCloud are registered trademarks of Apple Inc For610_2_A02 no FOR610.2; Malicious Code Analysis SANS Institute FOR102 fous on examining malicious eosutabe the asenbly eel. You wl never apeoaches for studying inne-werkings of specie by looking through a discs and ies wth th lp ‘of debugger The secon begin wth ap overview of ey eae reversing concepts an presents ie on “sonia assembly concept, sich aircon, function all varabls and jump. You wl alo learn ow tnecamine common assembly conse sich as fits oop and conta stem. The reminig artofthe section cies alare nplemeres amon circa, such 5 heylegin tnd DLL inject, he asemby evel You wl earn how wo reounize so carctrstis I SESS ‘Windows exeouble ies, “The materials in is section were ret ty Michel Murr and ke Willams an incuporte edack and ‘ecommendations am FORGIO course patkipans To lex abot Mie’ tackreund apd experts, {deans ine snsainanuctertnichet- ur, Vou ear fllom Michee on Tier et Fain iterseminikemar To ler aout aks background and experi, please 0 Fpvinlworgab oespotsom, Vou an flo ake on itera pit com/malwarjke FOR610.2 Goals * Comfortable reading code ~ Don't need to be a coder © General understanding of language and environment ~ x86 assembly on Win32 platform = Similar concepts for other languages/platforms Understand techniques used by malware (ou gaa ar the FOR61O2 covese mode is pt you cefonable reading code and understanding Wt youre ‘ooking at While yu dont need ae a oftware developer, defaly dost hr ‘The foes ofthe muiious cove nhs couse wl be 86 ase fr the Win8? plato. This sone of themes popular pltoms in basinesses today, and hess Wea of alate hens While we do fois fon ses plat, any ofthe concepts and etnias exist fr thr lng and patos i, theres sme very popula alae tt has Bee ton Vin Banc and Deh ‘This couse int "couse about assembly ated its about understanding how alisius cade works fm low level I guitesfen that mare aa fin hemsoivos sitingin a dasssembler or debugger king st assem, examining the various stem calls ete To bel itt andor, we il ever seme of he {schmgucs wed hy "ook rl ter pes of nai ode FOR610.2 Roadmap i Core Reversing Concepts * Assembly Primer * User-Mode Rootkits « Keyloggers © Sniffers and Downloaders © HTTP C2 Channels This ona sds dese to hep you raven hough the course mses, Core Reversing Concepts ‘Weill nw go cierto core concepts eat te rove ening ede How compilers, linkers, loaders relate to one another. ‘= Compilers translate languages = Typkally from high level to low level = Resuin object fles Linkers take output from compiler and combine with dependencies Usualyreslt in executable fles = Static has no dependences, dynamic does Loaders load executables into memory ~ Locate and resolve dependencies = Can happen at bot load and run ume Rte loading ete, pump to frst instruction (entry point) = Malicous cade may medfy entry poe (Called orginal entry point or OFF) Letsace how soltuare goes fom the developent phase al he way io how it asin memory. This wil ive souan understanding of sms of what happens "nehnd the seen.” Sometines suet "Unk ike ‘Super in odero derstand whats happening _Acompilr is a that wastes fo oe language tance. Whon malicious code is dvoloped tis en ‘ein ns igh evel guage sch ax Micro Visual Basie, oe Bond Delph competes he high Teel language adnate ne low level language ich as machine code The resting machine ees called sr obec inking ste net step in the proces. ike takes a series bjt fies (asl the outa rom a eanpile) nccombines he bj es foete. with hi depedecies extra aris a al exe Gererly speaking, an eaccuuble can be staal or ayraneally hiked. A sacaly Inked executable iain he depenences, wile dyaamcalyUaked executable dos One ali chu Sto ‘amie he enteral dependencies of dynamically inked ks Some packers amps swat this analysis ‘ectegue by (emporarly) btuscaing the depetdeney bles ‘oor ar ses load a executable il ino meer One of the emmon tsk oder erfrms to ete ‘std reslve ay dpendences am excel hx. The dependency revlon prose can happen he ‘eecutble Hie st ving loaded meron. oF wet isruning One a fader as lode an eectahe Flint ocmoryttaer coro the Bat traction he prea by perorming aug. The fist insueton exec called he“oty posit” Malicious ode nach vines and packer wil fen modi the ety point sessction stare withthe malicious code In he nance. the program's iil ey pon ‘en refered tothe “OF The code life cycle illustrated. eres high eel overview ofthe various sips cade wes tough ko sure fal destination, ‘The sours coe tasted nto objet code by «compiler, The objet ade then combined wih Irae, anda excouabe fil i ceated ‘To the le, he cpering sysem din aos informa fm the exec fil allcates mer) dead eid varies ina memory Filly, ont ensfored ote code ene Libris may bs loud during the programs xceton, sr leading teat this Sal sage hat we pal examine te cide wi debug Resize shat at each ep soe ination i estan some ne infomation i une. There ae asa seer ‘lcs whow utr of malicious code can ake stop onder analy. or insane, there was 4 "Tiny PL ‘taleng hat ened a 97 bye executable I would abut tilted many ofthe speciation for Parable Exccumbe (PE) le The process address space is 4G on 32-bit systems. + Each process has 4GB of space ~ Even less than 4GB physical memory = Accomplished by processor and OS cooperation = Protected mede (a.k.a. flat memory mode!) © Addresses are 32-bits for x86 architecture * Divided into contiguous chunks called segments ~ Use to ld cole and data = Permissions describe what memory in segments can 40 Renate When program uns tfas memory sacle ofr use. Tis memory sealed the proces adress pace Many of today’s programs ro in protected mode” (sometines called th Ml memory Mode In protected mods each process has an aes space tha ashes large and is separate fom another, proces addres space This accepted (ven are is es than igs of RAM) By cooperation enween he CPU an the opstating stm ‘What proce mode means is hat any aes, whether it efor an inseuton a fnetion, pty, dat, iy Sots fora 32-bit ait Ths a simpler model for devlopers than oreo the ther modls aia, ‘abl separ code and ds, fom vais ives ax wel asthe progsam sel the paces ade apace soon divided to eorigut blocks of mem called segment ‘Segments can hid ther cde data a have acess pemisins Te permissions pclae ead wi and exec Fer xample, may sack tas bul verlow atacks tke adantage ofthe fc thatthe stack ms ‘stan in a merorysement marked as exectble One rotestion mechanism fr sacked Baer ‘vero attacks sto pure stk ina menor Semon thal ot marked as excel Flow of execution is sequential until branching instructions are reached. * Order that instructions are executed © Sequential, until a branch instruction = E.g. function call, conditional jump, etc. * Code block: group of consecutive instructions, logically grouped together = Perform computations +E, Loops, crypt, ete ~ Interact with environment (OS) + £9, Read les and network, DLL injection, et ‘Once te program has stat executing. the CPU execu insttons quell one ight af the ote. However thee arealoisiretion tha lhe CPt jump te anothe ation in memory (somites ony spoiis condition are met and continu exeutng cde at he ne lesion. Thi selled rani A series of qu nsrations is tpially ord io a "lok" of code (or "code Weck") When rowan ns piel pertiems one oo pba activites, Han perform various types oF empath ince mathemati, Boolean operations oops, jus, ey poaraph. eats poet Insrutos ce. The program can also iret with is nvitoomet, seh a5 edad writing Mle, network ‘fae or een pafoming acuvies suc 8 DLL nection Example of code branching (from Agobot.ct) Here isa graphic example of pram few. This seven sho was ken fom the Azo. ado. For insane, Knight se ver 410250 stead of 04410250), Incest ‘Osi nes hesevare racket ntation This 8 seri erence, bo presets ea Ihe sane thing Examples of addressing operands. « Instr w/immediate Operand —mov eax, 0x6453 * Instr w/register operand ~imul eax Instr w/direct mem operand —mov ebx, dword_403028 -mov ebx, [DS:403028] ere are tne eles of dierent eprand aes modes. The bold operand eomesponds tothe ype of addressing mode lescribed Inthe fist exami. tbe operand 0x64 is a ned opera. ie Sven example te operat ea 2 regi pera 1 he thidenamplethe values dverd 403025 (for IDA Pra an [DS405028] are cet memory operands Memory may also be addressed by reference (indirectly). * Address is calculated (or in register) —Called "Effective Address” « Efficiently work with data structures « Format: Base + (Index * Scale) + Disp ace Tndex Scale Displacement AK EDL exe 1 None coreox] , fecxex, 2 |, | sttvate se eoP cores * 4 16 value st et m8 2-5 vale “Ta complement cet maaryadesting, thes sind mamoy sting Inthi case the adres ofthe estnatonsealied or sides ina reste The calelted aes scaled th eective ass (EA). Wt ass sit na reine. this sil iret than dct memory dressing, where the repr the estintion. srt memory addressing th reser hols the aes ofthe desination, (ne very lane advantage of indiret memory adres isthe ity ecotly work wth da ster Incemnting tv of single reper canbe wed ep rough elk oa data ruc, ethene Feld ofan aay fda stature. he perl ora tort memory sores tre # iden * sale) + placerat Whore the values ean come fom the columns isplyed onthe sie. Any vale can blot ase) wih the xcpton that scale asd ah ine reise mst also Be used ‘Yow wll encoaerthisadesing made fry en when reversing Examples of indirectly addressing memory. * [EAX] = Access dynamically allocated memory (base) + [EBP + Ox10] — Access data on the stack (base + displacement) + [EAX + EBX * 8] ~ Array with 8-byte structures (base + index * scale) + [EAX+ EBX + OxC] — Access fields of a two dimensional array of structures (base + index + displacement) re eee ar some eames. The ist zs onthe base esr. One common sear fr this ype oF memory aces he ser wil ol the adres of dynamical allacasd menor, “Te second example ses oth a se eter and a numer displacement. This is carmen sed with sceshing local viable and paramere sick tne scal. This cn be used when ascessing a 7 ‘The thie example uses bse and nde esters with ery with yt ructues sah san ay of oi “The ial exampleuos hoe andes rogers witha nani dsplaccment. Thien be done when -sroring te felt oF ae Srernonl ery of dts arses 46 There are several types of assembly instructions. * Data Manipulation —Arithmetic, Boolean, other ADD, SUB, SHR, AND, OR, etc. « Data transfer —MOV, XCHG, etc. « Branching and conditionals —JMP, CALL, CMP, etc. ‘Whe working wih assembly code, shareare a narber of dent insteutions. Inston pial fil ie neo bre categorie “Th fc categoy data maniplton, Isto inthis category woul inch aithstie (ee a8, ‘mal ete) Boolean eg and obit manipulation ea sh, sl and other miscolangous commands “The scond eatery is dats alr naan thi categry would nade mow chy, te. “Th thid category consists of branching an condition insists, Exanple of his inlet jp, call cp lst ats. ar Branching instructions transfer flow of execution to a new location. * Change execution to new location in memory = Update the value in EIP * Common uses = Jumps. * Conctonal (e-0, jae) + Unconditional (9. np) ~ Call a function (CALL), return (RET) Branching is transterng contol execution to anateleatin (ads in memory. Essent he valu a IPs updated, aoa depenng on bow the ranch itd (ale rp), ther acon ay He ake wel ‘There are several isanes where branching fused. Fist are unconora ard condionl jumps Branching also eceurs when fanctin ia (al) retrial, looping aso an example of ranching. Jumps are an example of a branching instruction. « Jump to a new location in memory to execute code —Transfer of control « Unconditional: always jump IMP, CALL, RET instructions * Conditional: only jump if condition is met Jec, Loop instructions jump insrtion tls th CPU star exseting code ra Icon in memory. Hi arte of nie “There are we ipso jumps, uncontonl and onion jumps, Unondonal ange always branch 18 ‘nom losaton in mary, Examples would be the peal and et netutons. Canina jays only brash ow action in momar faces conn cmt, Examples of ondinal empath Je lop istrtons. 49, Some branching instructions are conditional; e.g. jump only if X is true. * Evaluate a condition, jump if true * Arithmetic or Boolean instructions ~ Side effects stored in flags register — add eax, ecx ‘IF results Ze then ZF biti set inthe fags egiter ¢ What if you don't want to modify? — CMP is implied SUB ~ TEST is implied AND “The dea behind cndtonal jumps sta specie condition mist Fit he evant. and he jumps alowed cal the conto was Examples of eondions cold be Boolean isto such ao. no, addon arhmetic insructions canbe considered endo eth ese, he side eets ofthe operation ae sore nthe Mags este For amples he istration "ak nk, een ea in 2 Inthe EAR eter than te 20 Nag (2 ie ein the Rg oer. ‘There isone large sodantage of wing artic or Boolean nstraconsto cal a sont, They rod the value isthe dination eperand To ease wonton without alin the vale oan ‘pant the cmp sad et inrctons xis. The ep into prfons ipled sbracon xb) {plied means whe the vl of the destination not changed he er inthe Rags oir a 8 sation isrucion fa actuals been executed Wiseman tose wep nso fll by one of "he contin jump isstons ‘Simi. the testnstuctonperfoms an inplied Boolean (and) Jec instructions are used for conditional jumps. * Jump if condition is met # Form: Jec A= above, B = below, E = equal, N = not equal, G = greater than, L = less'than, Z = zero = Above / Below for unsigned comparison ~ Greater than / Less than for signed comparison * Examples: = JA = jump if above INGE = jump if not greater than or equal = 3NZ = jump if not zero A contin jmp thes plse if pei corition met. The er fend jump imran spicy Inte fom of ce, where the dseribe the condos, Te flloing value are a er sono Asjmpifaove Jump el jump fea (6:jamp if are than jump ites than 2: jump ifr [N:jump iret conn (eg. JN is jmp if eo) hp instructions wits abve/elow conan code eve the arguments ihe were signed Jam inametons eth pens than cotion ces evalate the arena They were signed. the developer, netihe proceso. Getrmines if dia sine e sane, by selecting th appropriate jump suction shove fr usiged daa, fea th sine dat) “The conton associated witha jump is eshte ty examining sn she Mags Siete proces dos nano ida sighed or unsigned when it peroems corypuatins, ists sf bth signed ad sian ‘The prvesor examines the lowing isto evaluate the cmepondig certo: Wisi): Tew if Cay ag = | JA: Tre ath Cay and Zero lag =O {Siete JL: Tre Sgn ag = Overow fz 4G: Te iTZero flag ~O and IZ Te Zero t= 1 Sion az ~ Overtow tae Some examples of cocina jumps ie: Gump if above. jp Gump ieee tan or ual same as Jewthan sh jo Gump to), 51 Example of conditional jumps (DoS.Win32.Synflood.e) oowerses Jim short 1oc_401809 Unconditional jump soneaee: edx, [eax] ‘99ne9882 eax, edx ones short 1oc_¥0 ecx, [edx=8] onese89 eck eouesesa short 1oc_wessBe “This sercen shot shows ce jump rm he yong ao at (DoS, Wink? Synod) “The firs jump is an unconditional jmp to adress Ox4018D9. The second ad hed jus are contin Jump. The st ietrction offi fgs reser ithe et istcton (which perform a mpd ‘oolan “ad Recall tht ool “an iste f and ony i Bath luce re Wither alc 0, teh a ‘oon “ae” i ae. Thee isrstion il hen jump th esl of fe tt nston was by ceamining the sists ofthe ZF tin he Hag oer The nsueton tates the laps eit forthe thie jamp i th "dc ex which decrement the ain {EEC register Fy oe. The inition thal follows jumps ECX wae decanted 19760 IMPORTANT Conditional jumps (such 5 12) operate based on the ontns othe FLAGS register, The Fath akon by condioal jmp isnction cant be determine by exnining he jump isrcton, When Presented with conitionl ump nstraction, examine revo isto to ste the ast nstton sk oe the Nagin te EFLAGS register being checked you ae utsre wheter an eit tie 8 pila Ma, tha infomation eas be ete ine nel Assembly Language manta Inet Assembly Mans re thn you ever ard t kno) can be dovnload fr fs ro hap tcon/cnten usin pocesrorsarchiectirersoftware-evsoper- mia | Numbers can be stored as signed or unsigned. + A 32 bit register or memory location can hold a range of values * 0 to 4,294,967,295 (unsigned) + -2,147,483,648 to 2,147,483,647 (signed) « The values in the register don’t change — The instructions used give the value meaning A-32 bt storage heaton (sich a register or emery lection simply ld eres of Ue and The “alue thr these ad D's represent dependent on whether he 1's nd 0's shuld interpre as signed ‘runsipnt ae ‘Tho isetons wee to refvence the values ofen give elves aso whether he values ae signed a used ‘Wert tok at some examples othe next sie 53 Is OXFFFFFFFF -1 or 4.2 billion? Depends on signed vs. unsigned. * In signed numbers, the MSB determines the sign (positive or negative) = OxOBEEF123 (MSB not set, positive) * Signed: 200,208,675 + Unsigned: 200,208,675 — OxFFFFFFFF (MSB set, negative) ‘+ Unsigned: 4,294,967,295 '* Signed: -1 SUT sa very common AP return valle ‘A method named two's complement is wed conver a binary sting ts sgned negative quant. The soe tits ha when examining the bern binary if th mat iia bi se (a 1) hee vale ogative ithe vel shouldbe nteted es a sighed ber IT the vale shouldbe irete aon unsigned ‘umber, hen we kev the numb lr tan 2.1 lin, When looking at stenbly code, how do you know wheter ota a namber signed a unszned? Content, conten conte Axsmbyisnations provide good clus since some insncons have dilren mnemonics lpending on where ey ate cating 0 shane ce nse vac you examine API doctmentation yeu wil se ha the ret cae is of ust represent an err raion. Yoo souk rere tht OXFEFFFFEP in 232 bi rg or memory lca he signed ale Theres an awesome tutorial on Bray math in geerl and w's emplement operations pill ip: pherisoxide- wordpress con/2C08109 29) adn subtracton-won-omplensntorial Exercise 2: Examine Conditional Jumps « Examine several conditional jump statements —Goal: Identify condition and when branch will be followed « Examine an trojan application: —delta.exe Please tert Eris 2 in th lb guide for dei nstsions. Feet xersne you will examine sever coitiona juno the goa of his exes so out become onfoable Mey ing condone nd when brinch willbe lle. Tiss key coroner of aa ie oe "he specimen you wil be aalying is 8 wan program, deka ve 55 Questions 1. Identify the number of conditional jumps in sub_416148. Do not count unconditional jumps (those Using the jmp mnemonic) . Examine the jnz instruction at 0x461DF, What condition is being evaluated? . Examine the je instruction at Ox41617D, What condition Is being evaluated? Examine the jz instruction at 0x416173. What Condition is being evaluated? ‘Load the sample dace it IDA Proand ry o answer the following questions: Werf he numberof conditional ups in sub 416148. Do at count uncoritona jmp thse sing thejmp mocrens) "Examine he jn insintont x61. What condoning eat? Examine hee istration a Ox41617D, What condoning eat? "Examine istetion a 04416175. What eodton eng evaat? Hints Examine Conditional Jumps ‘© Conditional jumps are in the form Joc = exis the condition ~ Condition codes 5 sides 290 = jmp isnot a condtional jump ‘+ CMP and TEST instructions Perform implied SUB and AND = Modify flags w/o modifying other registers = Mathematics (e., in, dec) ako modiy Mags ‘© To describe the condition = Look at arguments to the instruction ofthe condition = Look a conten cede for jump = Combine the 00 Here are se hints to asi you in case you some sic, or a hving cl ine Remember tha canon jmp are inthe frm Ae, when the "pat i cnn (what te tie forte jumpto be tke) The contin eves ae Tis ve sides bck. Doi forget hat ep Instruction 913 codtiona jump (and heeore Gest cout owards he our contra jumps) ‘When oakng the iaseusns hat eal contin, meer a Jeu ae ooking fr mathe epeaions eritretc ard boolean), These instutons modify thes res aswel the destination ‘suite. The em and ts isto eto an impli sub asl bookcun and, Ths means testis ‘moi the Mags ester, nl do not mith destnaon reauters, ‘when deseibingthe when the jam is taen, xaine the contin, th arguments te con, well as ‘he canon cos inthe cena junp. Then te lage cemine tet sr Answers (1) Examine Conditional Jumps * Qu: There are 8 conditional jumps in sub_416148. 2: The condition evaluated for the jnz at ix41610F is whether the ‘dec eax’ instruction ‘causes eax to equal zero. ins * Binpeneenararsie a is. esi, ". jump is feats ess than OF Saul i Oxi00. NP (1: Usethe pho in DA Proto jump to adess 16148. Scroll though he ncn (best done in txt ‘iow, pre the sue bar ifn gph view). Count he numberof onion jump nthe ntion, There re eal 8 cononal jumps nas 161A consiTs jx shot 416168 cone! fle sbatioe 1618C 00816187 jh shotle 1613 c04161BB je shortloe 41613 OOIN6IBF jp shrt oe a161e9 oost6iD0 jt shatloe 161E1 oou16IDA je shart foe 4161DD. OouGIDE jar sho ae 416105 (02; Use the hoe in IDA Prot jump adress Ox41GIDF. Note he de an insrction medi hove. Idec the yl in ea eats the vaio en bing eo, thn the er Ma seh ‘ondition ofthe jmp sto jmp 9 OC416IDS any tne he 26 Mag 8NOT st (03: seth ghey ia IDA Prot jump toads Ox41617D. Observe the emp instruction opting on the ‘ious itumedatly above Temp 6 Ost 6I8C wile taken fe xs han eq ONL (256), Answers (2) Examine Conditional Jumps * The condition evaluated for the jz at 0x416173 is the emp [ebp var}, 0% The jump i taken this stack variable is equal to Zero. (4 Use the ghatkey ia IDA Prot jump o adress Ot 1673. lnmediatly above thers isa compare fnsarusion. THsinsrucsion is comparing esl stack hatd variable 0. The jump only taken the vale inthe sack base variable zr. The coin evista forthe jz at Ox416173 ete “a ep var 0 ‘Te jump stake his ack erable ous 0 290. Inferring high level logic from assembly instructions. * Let's put together what we know ~ Start transating back to source language = Easier to understand Branching = Fels, Switch Looping = For, While ‘Compound expressions Not always an exact 1-for-1 ~ Goal sto understand program flow, nat recover code Were no going» star puting wget what we know about conditinals and teancing ob an urdentading of ighorleel oie, Were goin ott arti (r teas weaning) he Now of ‘necator th pespectv ofthe source lang This eds to be eas undead han sembly toe Well eover barching- rte lope constructs, suchas Fee Wel abo cover lopingcae eg ens, schas fr and wil loops. Fialy well examine the logic of compour expressions Remember ha we will nt tte the orignal sence cde. Our gal sto undrstand the Mow of the rogram, \Wevrill provide sample tasaions of sembly and C cade. However he are arly saplen an dent. count or optimiaton st compiler may mate Remaner thar ie move th oe way tra {TUMETOWTTD Inthe fel, you i Ty emcee any oe sare logis cones, ba implemend in 2 are of fea Was If-Else statements are an example of a branching primitive. Execute first code block JF condition is true —Else execute second code block « General form (in C/C++): fC condition > ficst code block } else ¢ Second code bYock continue here after if... “The fstype of igh evel logic onsrct shat Wel eran is the “ioe” teres Ike statements have a endian and code blecks. The fs coe Hck is vested the conditions tne, Other th seven code Hock sexo Nexis the genera fom ofan ils tatement in CIC it coin) fist code block Isle ¢ , Kopin mind tht only one ofthe no code sks ecu et both a Example translation of an If-Else statement from C to assembly. ov eax, vari {amp eax, OxBAADFOO0 Se block? if (ar = oxaasor000 ) ¢ first code block block: first code block else ( ‘mp end econd code blog locke: , Second code block continue here after if ents continue here after if Here ian example of how an ise statement fom CAC col trate assem Inthe C1C+* code. the variable vt checked t se if qua the vale OXBAADFOD. Tis ‘value used ty the Miers mery allen outines 0 nents untied memay. The comparison ea be see nthe ist thee lites oF assembly coe, wher the np nations ‘comparing Ue vale o he EAX rps hte inet aie IXBAADFWD, ‘ew values ae nol eq var oes not equal OXBAADEDOD) the te condition jump is fellowes to he abel ote second ode lk. ‘ode block cacao, Noite atthe end of th fs cae lack thre serio amp the endof the Fee siement Thisisneesuy so that the second eve lock i not exeeted her ‘he frst cods lok finished. 62 If-Elself-Else statements allow for more complex conditionals. * Nest a series of if-else statements ~ Else contains another if-else = IF all conditions are equality, a switch statement * General form (C/C++): FC condition-a ) { coce block #1 } else if ( condition-2 ) { ‘ode block #2 } else 1 ( condition-y ) { ‘code block ¥ p else ( ‘code block z } Ivisposie to nex nil else staeret ogee, eating ebsites The des that ‘rulple conditions can be evaluated, ada single cede block execute depending on the Fist conten thats tnt ITnon ofthe conditions are mete coc block in the le clase (which opin exec Ensen each i lane emai anaher "i satoment the condos are foc equality (hocking svi one variable equa spose vl) then it maybe snitch stament, Whila swith tatement hs» dle sys, ki functionally equnalen to Sees noted te entero “The ane arm frill saan i cont) ode lock #1 1 bet eondion2 ) ¢ co lok #2 leit eonion¥) | codeblock ¥ ) 6 Example translation of Tf-Elself-Else from C to assembly. Sse tt 1) { first code Block, {iss } else 1f(G ==) ( { She ese Excond code block delet jo end Prird code block ; Third code mock continue hore after es ieetaerfelse nti xp, we will show one ransltion ofan esis oasembly co, Inthe CXC codeon he slide ove, the varible "a is chechd o see iit equal the valu I- itdoes, he fist code block s-sevuted. Otherwise the variable "si thom choked see ito he wake 2. I soos, the cond cde block in exceed. inlly ithe variable "docs ot qa lr he hi cod block snus “ho essonbly uation has few more components to it.The ist compariaon (erp eo. I") chesks sit ‘he vale in the EAX rapist Ft jump tthe Seon el tha sal th fs exe Hock excite ind hen jump tthe end ofthe ese clase (the ether ode Wks are ot cexcte). ‘he seed ches to see EA i ult 2. tithe send ood Book exe witha in command tthe edo he esse clase the vale of FAX ws ot 2, conta rans othe Tiel Es, whieh executes he hid od beck, Switch statements are used for complex evaluations. * Execute one code block (of many) based on integer value of a variable ~ Similar to nested iffelsestaternents * General form (C/C++) sviteh¢ variabte > ( [7 (ease) bet fase 0° 7" code executed when variable == 0 */ breaks 7°" coge executed when variable breaks } “The switch tment allows one ff may) cae lack oe execute, bane on the integer ale of sariabe. A Swith atement is intially oyuvelen wa sere of need ele if statements ‘When wesking ih wich statermens, cach codeblock is sted wih he ine “case NX" where NXX isa constant al th he aisble mst mich fr he ede blk to be exceed. The “eae XXX" ine fen filled aber od backs willofen be terminated by a “eek” saoment. The beak scent ls the compe tha the ‘oud nel the smi trent as ied, ad to continue exci ode flr the switch statement Ire rk statements prs thn exscton wil Now fm ore ase coe ack) int the next. While ‘hiss usualy not what the programe wants. Tr exeutin rm oe code book to fo inate there are ef imarees ep 4 Du device) where tha ait can eed Io eicene purpse, 65 Jump tables are used when switch statement conditions are sequential. * Switch statements are equivalent to nested if/else statements * When all case labels are sequential compilers often use jump tables * Address for each code block is stored in an array (table) * Jump to the address: array[variable*4] — Variable is used as an index into the array — 4 bytes for a 32-bit it ‘Switch statereesare functionally equivalent sees of ested ies statements Ths mens tha wie stent have ie same asenbly linge represeristion as nest else sateen ‘When a ofthe cae ae at eet here a opbiztion technique called "jmp ales” Hat compiles often uss ‘jump tbl i st of adresses ofeach cod ak ans). Coto istransfere to the desired code oc ty using the arable o lockup the aes of he codeblock Inthe jump le lwisconsmon tose the aril used w nde the an table multpliodby 4, sine adresses on 32-i ystems sedbyer zt, 668 Example translation of a switch statement from C to assembly. sultan var) ( ‘pov any var cx eax, 1 ja end fase bs 3p code block address_tableLeax4] first code block case.0: (offset Ox1000) ‘fSest code block Sap end case 1: Coftser 032000) T——E second cove tock ties second code block, | Continue here after switch } code_block_address_table: 448 031000 (offset of 1 code block? Continue here after switch dé 012000 (offset of 2 code block) ere isan empl of how switch stent could rants to asserby, sing jmp bles Inthe CC ode, th value of the able “vaI™ deters which cd lack is xse ued, Haris D thenthe frst code bck encuted, far”, then the socod code lock sexeete. Far ther "uss nther oh code Mocks are exacted. Exscton continues afer the eno the wich sateen Inthe ately the vlae of vate moved ints the EAX register The BAX rie then compared tthe ‘ae I. Ithe vale o EAX isabove I, con rarafrs tthe “en” abel, Thichek proven ay vale ‘use the vad range Gin this example D1) frm execting ihe of he cde leks. Beloe we continu, is prin to ote ta the ts code lok festa a acres HH, second ode lek octet aero 200 "hemp code back ress talleax"4insrctinpofoms several actin. Hist he vale of FAX is ruined hy 4 ar then sed inact eres inthe ray "codeblock adress able™ Ifthe vale of FAX TsO. theres of th multiplication sO andthe jump is made vo ses 0100 (it the rst code lok Ifthe value of BAX the rest ofthe mulpcation 4, and he erp is mae vo aes 2000 (sao the sound cade Bec). esas importa to note the “mp nd srcton athe roth it coe ack. When he ce the fist code block has Hise, heap” wil skip over (and not exeete the ode nthe Second ode Beck. er Exercise 3: Examine Jump Tables (Optional) ° Examine a jump table —Goal: Identify the target of a conditional expression using a jump table at Ox41CF16 ¢ Examine an trojan application: ~delta.exe Pease refer Exrise23 in the fb guide fr dete instructions, or this exercise will examine a jump able. The goo this exces is for you to became comfoable ein the ast code hat uses a jump ale ‘The specimen youvill be analying is oan program, deta xe. The aes ofthe jump statements (Os41CF16. You an go there IDA Proty pressings and sexing ds ads, Questions Examine Jump Tables . Identify the maximum entry number in the jump table, Determine the base address of the jump table. . Identify the target address of the jump if eax holds the value 4. ‘eat the sample Sela.ee inte IDA Proand uy to arsine the flowing questions 1. eine maim entry uber inthe jun tbe 2 teem the bas adress fhe jump tbe, 3. Mena te are adres fhe jap ea hols the vale Answers (1) Examine Jump Tables * QL: The ja instruction at 0x41CFOA indicates that the mau entry inthe jump table is Oxo * Q2: The base address of the jump table is ix41CF82. Note the offset in the jmp instruction at oxaicrié. (1: Use the ehothey in IDA Prot jump ladies Ox 4ICFOA, Observe the nstcton ja fe 41DSIE UhsadresThsats on Hag sty the cp struction imei dove, Neha the ep a Insvusions chek wo see Wier ei greater an 10.15, he jump abe naked on, Ths means that ‘hema eny in he jump ables 10 (2 Use the gota in IDA Proto juno addres (x81 CFG. Obsee th inston jmp ff AICESD|ean", The adress in hit insucton the Base aes he jap abl, 70 Answers (2) Examine Jump Tables © Q3: The base address of the jump table is Ordact 82 It eax, then the target vil be the value at Ox41CF92 which is x41 (03: Use dhe ghey ia IDA Proto jump to adressOcAICF6, Double click on the lb ff 41.CFS2 tp tots lation Asides eer, ths the hae oh jump ale. If ex ols tele of thn the imp wil ect 9 peston inthe Jump ale indexed rom 2). Examine he vale aes x81CF92 (Oc41CRRD F474) Note ta th adress Fhe jump wil be O1DO7E n Looping is used to execute a single code block many times. * Repeat code block until some condition is met = Each repetition is called an iteration * Methods = Use a conditional jump. — LOOPcc instructions + Examines ECX regster = 200, E= equal, N= not loop: loop iF EXXs not 0 oop: loop IF EOC snot 0 (used for short jumps) + Automaticaly decrements ECK The conep of acpi septal exccuing Had of cade until vere conto st, sh tin the book of ene sence called an “eto” There are wo was tree opie ising one of he contol ump, hy ung one of the LOOPS Similar J, thee in LOOPEe represent he conden cde hat must be met ede forthe Lop iesrction totranch ithe aes specified. The endions ae: lop ifs + E-toop feu ‘+ Nrinversthe louie th loping condition “The lop inseuction (without a canton code) loops if ECX fs mato ands wd fr braves th re es than 28 tyes aay. All othe oop commands uri dcrmon the alu ofthe ECX regitr. Te lope comand ll ranch (loop ler the deerme, the vale of ECX i er ith ZF bt nee Mage registro n Loops have five major components. ‘+ All loops have 5 components = Control variable +The variable) tat reused to determine if a op exes Loop initialization +The string values for op contra variables Loop body + Thecde bck tat gas exeetad Loop update “+ How the ceo! variables are modified dung each ep Reraton ‘Stopping conditions +The certions to determine fon ets roma igh love perpeaive loping constructs hae five components ‘The sont variable The varies) tht reexamined in the onion, and dtemine ifthe lop repeats ‘Loop inition: The inl values forte con vale) Lop bd The block of ede tha is execu fr cah tration of he oop ‘op update: The aston hat upate he ent variable, ‘Stopping cndons The conditional instructions (pil ee or LOOPCe) dat datenine he oop repeater eis 3 Loop analysis example (1. Analyzing Bagle.ac. Loop ingiaizaton ° conto! ec €— vanable eon, 1 Short Loc 402439 ‘eax, oconae720» “This san cxampleof te lop isto rom the Baglae wom, ‘Adress 0:40342C trough 04403439 comprise dhe lop. You ca see the val oF 9 posed an then ‘pedi the ECX reise. Ths meas the body of the oop wil excited 9 times sen there a seme data rannfrmaton appli the EDX reper aright shi and an exclsive-. ‘When he oop ison encountered, decrements the val of the BCX reese by one and oops if ECX isnt decrerted ozo, ™ Loop analysis example (2): Analyzing strlen() wo toon (ee Le = fo | ey | tes ott) 0) 0036) 0 wa) eax, [east] Gy tee) epee Se rete Shirt toe avons Lor take eae understanding snippet of ete, The ede shown onthe lide above the nied a) Fartion that ne bee “The purpose of sl iso compare the lng ofl erate sting (ht etanthe nl aie). For example srka("ADCA00") would retrn 3. When walling though example, ve ill ase the ‘ing that sory examine is "ABCO™ The sing fut Bytes log (bt tres characters) an For Purposes of his camp Pains at mero adres 1000. Atthe start of theboch, the FAX register point tothe tat ofthe sting (EAN = 1000) The EDX register it ‘ett the adress ofthe scone cater a he sing (EDX. 10). ‘Now starts the man pat ofthe loop. The C. restr se tothe cert charac eng xan The Stan though en is wil ho“ (OA)- Aer thi the BAX reer neremented (EAN ~ 1001) ‘he nexctwo lines check 19 sce fC. 50 (the nl Byte}, and CL. sot ul tans the ody ofthe loop over gala. Shce CL s°A se Toops restated ‘On dhe nex ofthe lo, CL is se.) ad he BAX reir incremented (EAN = 102}, Since CL is "Bard nx the ll emit, the ody of he loops executed again. Inthe nes iron oF the op CL is setto Cand the EAX register i ieremesed (EAX 1003). The sea teat ofthe loop the st oe CL beset to Ox0Dan the LAX roginterneerseried{GAX~ 1001) Sune Cs the jap is ot ker ‘hes ine ofthe block surat EDX (101) fom the current vale of EAX (100 which el in 3, ‘This codeblock works by computing te dsnce between tao addoss in meme 5 There are two common types of loops: for and while. © For loop forCinitialization; stopring condition: update) { code block ) ° While loop initiatization white condivion-is-erue > { code Block pdate contro} variable ‘nary high evel Languages. there are wo comme ype OF op: he” oop an the "whe" lop, ach lop she five componeres mentioned Before an they are fanctionaly equivalent thou hey ay ier insta, {nthe *or oop, inkazaton, opin, and updating condone specif tthe begining. the "illo. te inition sepa From te toppingcondtion, and de upatingofhe eonl Vaiss ‘sin he boy of top ‘The einay difesnce heen whe nd or lop, isthe topping emton The fr loop sates the ‘ion when loop shea ap were the ml oop ere condone he oop shuld Example translation of a for loop from C to assembly. First code block continue here after fFar-T000..= add ene, 1 fen Check Fstop nd continue here after For=Toop.- Here sone example translation fora foro rom CIC 6 assmby Inti example he tart expression st the value of he vail 10. The upat expesson sto ineement the vlc of ay 1 The cad condi sma when as tetra or aul 19S Essent his oop wil toate over the dock 5 times, Iasombiy we ca fst se the valu othe EAX reltrbeng sett zr, Then the er condition ihecks, snd consonal jumps token f EA isl es tha [spree has or eu) the vale 8. thump is ‘ot nthe code Hock sexes. -Ator the ode ack s exceed the vale othe ZAX epstersneemente y | anda unenstionauTP ir made the ChecliSop label, whic chests he end condo n Example translation of a while loop from C to assembly. ‘Stare: mov eax, 0 ine check Fstop: { —{ 5 ‘eno e2h, write Fed > ¢ Sue ea ‘ods block stock eee peer ese oe bine pean add e2x, 1 Sy $s teticrston conn bere fear witTe-Toop ae ‘Continue here after shiie loop. ‘Mere fsan exam translation fo a while eap into assy. rar co staring he wl op. the arable as inaz 0. The lop thon chaks toss the variable es tan th vara ess thn 5. ste cede ack sexs. Atte endo he ede bck te ‘ariabl ais incremented by Youtl nate that he ase rarsltionsdetcalw he for lop. This bec the ae ot tionally ‘quivalet You msy rive tha the end codon I ehacked with ve Gump preter tan areal) a ‘opposedtoa jo Gp if ot ess than). They are actly Serial, and asthe sane opcode nsucton 78 Loops are used for a variety of functions. + Encrypt/decrypt network traffic = Loop over each character in the string to send ‘+ Attempt to connect to a list of IRC servers = Loop over list of IRC servers * Perform a port scan ~ Try to connect to ports 1.65535 * Perform a DDOS attack ~ Keep sending malicious packet # Log keystrokes — Check state for each key code 0...92 Ling is enact to comping an oun in ners pce houghout soa especialy malicious one Forampe, loosing may be we inthe encryption and decryption routines, hat encrypt daa foe sending ‘nove he ior Maliius ce might wea lop f etate over cach sarcomas. modi (encrypting) serch. (ne sono control mechani for bots iso comet oan IRC server Some bats will ty to cnet 19 ‘mus IRC sores, and might use lop erate overs ist oF TRC server to eormect Aerastivly, pot scansr might ep call“atempl conn” unto fr each pt etveeh and (S835, Raho an having 8836 cll traction oop cold he ud sing ques Ba space DOS atacks a elassie examples of loping. Is not uncommon te se loop used Yo epee send races pockets ily, ey stroke loggers wok by chock these foreach ky ede, ose ii hs en depressed 79 Exercise 4: Identify Loop Components * Examine loops ~Goal: Identify different loop components ¢ We'll examine delta.exe Peas refer to Extese 2 the labs fr deed instr, Forthis exercise, yu wll examine loops. The gals or yout be abet enti the diferent components oF 2 oop. ‘The specimen fei idan. Questions @ Identify Loop Components * Loop beginning at 0x4126F9 |. Tdentify addresses and instructions of stopping condition . Identify address and instruction that updates control variable Identify address and instruction of loop initialization 4, Identify address range for loop body . (Extra Credit) Determine the function of the loop code There slop tha pins tae Ox42619, Gio thee ar armwer the lowing five questions 1. ify ates nd nstrtions of oping conn 2. emi ables nso that vps contol varie 2 Memiy ade distro flo ination 44 my addres ange for lop body 5. (Extra Croft) Detenine te funtion fhe lop cae at Hints Identify Loop Components + Loops execute code many times ~ Look for backwards jumps * Stopping condition typically conditional jump ~ May include a comparisan (cmp or test) ‘Control variable update instruction sets bits in lags register ~ cmp, test, and, oF, add, sub, de, in, etc. = Tals you the meray locaton of the control variable ~ Typically close to (and before) stopping condition + When you know end of loop and control variable, look for initialization ere are some bis, incase you get stk, Remember that aps ecu code may ime, an thi meats here wile jmp to prvios adres. The mp wil ea conitional upp which means bere may Bea comparison insetion Sih as emp ote) ete condos jump. ‘malta, the isretons that update the orl variables pial se sn the fags regi. This means thutbesides just erp ang ts isructions you may wan to lok for artnet Inston ea a, sub ee, inc and, o, ct) The sopping codon and uplte ate ply clase ache, and once you deny the sopping conden and update nteutons, yu wll ri te mesylate ofthe cool varia. ‘Once you know the stoping sondions and he eno ail, ca ok forte kp ination, This ‘il peal be amo orpushipop inrctons Loop Exercise: Relevant Code Section vax, [eben] eat, ei aly orreereee Short Voe_4126F9 You can loathe sod by louing des ex in Olly. or IDA Pros jrping to aes 4126F9 se the {ep in IDA Proce CTRL-G ip OlyDbg) Heres wat you wl se you lok a this code lock i IDA Pr, Answers (1): Identify Loop Components 1. QL: Identify addresses and instructions of stopping condition test eax, eax at 01412700 2. ‘dentty address and instruction that updates control varia = add ed, OxFFFFFFFF at Ox412708 3. Identify address and instruction of loop initialization = mov eax, edi at 412708 (1 Use he ghotey in IDA Proto jump o adie x17, Observe the fst jn short lee 4126" thisaddess. This acted on by he est isto mainly shave. Thee an jn inswuctios fer the stopping erin, (02: Use te ose in IDA Prot jump aes 41278, Observe ta the vale of i i moved imo eax. ‘Then es decremented by adling 4-1. This operation vps the vals fe forthe nen iteration dough the oop (8: Use the g hotkey in IDA Proto ju oes 12708, Observe tha te abe of ei is moved io cox. Thon eis decremented by ang a. Theft move of it ak nies the loop, owevee th epi “rina” cach ie tough the lop ony witha ever sale al. 84 Answers (2): Identify Loop Components 4. Identify address range for iaop body Loop body at x4126F9 ~ 041270 5. The loop performs a copy ofa byte array Into 3 Hructare poea toby aoe ame (4: Lethe g hotkey ia IDA Prot emp address 1269, Thin is the begining ness of the Toop tthe lop body actly onan the fap iain code. Th lop ody en at Ona 708 (98: Use the gtk ia IDA Prot jump tars Ot126F9, Thess some Hts pind to by bn. This anton perf hye ry copy goss sing srt, excep tha te so teing nl expt opi). Note ht ious thee no alin ul copied thre ro check fort ui atherso could ho use To ating a well ab aye ea. [eb 8] ps he ‘ase oe destination te aay: feb] points the cre postion nthe ara. The es) ‘else ois tothe source fyi aay. The lero the aay isto copy is hed Compound expressions evaluate multiple expressions in a conditional. * Simple expressions only evaluate a single condition ~ if (<4) {block oF code... } + Compound expressions evaluate multiple conditions ~ if (<4) AND (x> 1) { block of code...) + AND (short circuit) = Negate logic ofeach condition = (¢<4) becomes (x >= 4), (> 1) becomes (x <= 1) = Jump to end of bock if true © OR (short circuit) “Test each condition Jump to code block f true = Negate log of last contion, jump to end of block if true LUpunti now our eumpls have had simple expressions. A single coon (such si variable fess han 4) was cali, Compound ome ale sompie) expressions esate mulple conor. For insance, we might wish 0 heck fa vriabl within a ange o ales, A compound conn could bf he variables reer hn I, bat estan There ae several yay vase compound expresso in assenbl, especialy ven diferent optimizations that acompler can mplement. any compere oe tectniguc calla short tet evaluation, wih ships coe ‘ook forthe first Bean AND ta fis, Shor citi eaten alo exesues ode Bock a oom te i Boolean OR sce, ‘One way o ans an AND (which equ bth expressions woke ra) to negate thea ofeach condition, andthe negated coniton evaluates ob rue jump 10 he ed of te Boek, One wa asl a Boolean OR {ich regues eer ane for bth oF tho expressions ob uo to et each ond and jun ote cae lock A¥any ofthe ovate oe ae. Then negate the logic of he a cotion ndjump othe ed the ead ‘omition ste ‘When you nezate a gical contin, you change the onion sta the ever outcome true. For instance regating te expresso 4 yields >" the lt nthe revere of he emer. Silay. the negation of «> 1 sien 1 Example translation of a compound expression (AND). ote block ing end ? continue hore after Those Blockt: ‘code block end Continue here after ifn {nhs example, fe compound expression checks to see if th vaibl ise than 4 and gestern EMectvely ithe varable char or "Natice on he amb ranlton the lag has boon inven Te i conto tht is hacked isl Gump it nots han) The cortional jump beret tbe end ofthe lack. The second condition also inser, {ne Gump ifn peter than) I the cuinal jan i ood to branches othe andthe eck either condtinal mpi taken, the cl lock sexes, ar Example translation of a compound expression (OR). eoce lock ng En tts Continue here after if. ‘code block end: Continue here after Ini example te compound exresson checks tose if the variables ese than or test ha 10. Enetvely ithe sie saat 45, 6,7, 8. 9,010 Nae onthe assy trast the fog rte fist somparison sno been nse The fst conn ‘hats checked if up i es than), Teco na jump banehes woth code Bock because we Nast ‘vcete he cde Hock ithe val i ks dhan 4 The second cain weve, reed ng Gump i rer than) the condonal ju allwed itranches othe endo the bck. With the OR compound expression, the cde lock is essed if the fst jump taken (duet shat irsting a wean i eer jump is aken (ilar te the AND compu expose). Exercise 5: Reverse engineer a compound expression « Analyze compound expression Goal: Understand / interpret a specific compound expression * Examine delta.exe Plas tert Ese 2 in te lb guide fo detailed nstasins Forthis erie you wil analyse a empoutd expression he goa i for you to Hecome comfortable Jmerpecting and ndrstaing comrpon express ‘Ye wil cous to exmnine dela. fae ab Questions: Reverse engineer a compound expression "If-Else" statement at 0x405571 ‘Identify the number of variables evaluated in the condition, 2. Identify the register examined by the conditional 3. Identity the start of the first code block (For the if"), 4. Identify the addresses of the code block executed if the ‘oncition Is met. 5. Identify the start ofthe second code block (for the "else") 6. Identity the ending address ofthe code block executed if the condition is not met (the “else” statement). 7. Describe the conditions when the fist and second code blocks will be executed, ‘Ther ise “ele semen st 4055: Answer the allowing seven uestons: denis she oumber of variables ested inthe enon, ily there easily th conto ey the star of he Fest ead Back (othe eis theadresseso th ode bck executed ithe cation is mi, Mey the stro the son code Hock (Vorhe"ls") ey the ending adres ofthe code lock excited ifthe condition isnot mst (he “es” samen Hints: Reverse engineer a compound expression “+ Remember the format for an "if-else" statement yee ; Look fr jumps to same address suggests start cr ond of coe Bock Lf eoribon Is not met second code block is executed = amp to sta of second cad bck Second code Dock starts wiere first one finishes Soft one hs to jun over second. AND conditions invert log, jump to second cade block f true (OR conditions jump to first code block ere are soms hint to ep you, in es you gt tack, Remeniber he fmt Foran its siaement the endton sete, the he rs code Hock is ‘seeted,charw ae the wd code Hock fenced. However, ate tht cae the corpler may render ‘ook in erer te optimize, t my note posible t determine which lock isthe iad which lok the ‘ke. Generally, we seme fat he Blok excited when th conditions ina sompound expression ae met thai" and the ae Bock the “ee™ however his not dermis Youimay wat olen for jem tothe sme aes at hee ages ct the sao ed fede bck. thes cde Wks executed there must be aj over the second coe lock, bahar et exceed "hiss hte second code lock stats who the Hest cde ck shes Dor orst pea case of AND ang OR condsions: AND contons inven he Ingo the conto, ae jump othe secrd codebook, ithe inverted) congtions ae met OR cans jmp othe fs coe lack, Ife condense me. The excep ta ne OR condone st coon averted a jumps the second cede eck, ie (ner) coat is met a This is code sample shows a compound conditional expression. Yea locate th ade Indigo n Oly oF IDA Pro, Hers wha yu wil se iyo ook at thse lock inIDA Peo Answers: Reverse engineer a compound expression (1) 1. Only one varabeis acted on inthe condition starting at O05571. - = 2 ‘Qt: Use the g hotkey in IDA Pro a jump to adress 4071. Note that here aren coe leks that ‘opera onthe same eer, i. This mea he sone varie emir (02 Us the shot in IDA Prot jump toads OX40SS71. Notte she te wo code blk a ‘operate on te sme rit, bl. The regia i exmine is the conan 93 Answers: Reverse engineer a compound expression (2) ‘The start ofthe fest code block ('") & Ox40557F (Use the phot in ID Pro jump to ake OXsUSS7F, Note tha here are cde lacks that ‘pea on hese ease, I. Note hat bh ee blocks mp to Oe40SSBS, Th the ation ofthe che Bock. Ifa crits evaluate then he code block at O40SS7F is exceaed This she lok, (Use the eesey in DA ro jump io adess Ox40857F, This isthe sess yu idem inthe Jax question ad isthe beginning he block. The eno he if bck OMAUSSAC. Answers: Reverse engineer a compound expression (3) 5. The start ofthe “else” block is 0405588 6, Theend of the "ele Blocks O40556C 7. The condition: if ~ lis greater than or equal to 330 AND ~ lis ess than 033A then condition is met (frst boc) ~ Ese condition is not met (second block) (05: Use the othe ia IDA Prot jump to aes 40SSB8. The ese Hock is wher thee ‘Sondtonls oh jap, Th she ptem of empound AND condition. (6: Use he 2 hthy in IDA Prot jump to addess 40558, The ending loeaton ofthe blocks stl noe onions jump tO OSSBC. 07: At 405571 the bl etre with he vale pointe a by sep]. Fst the vale i the Bl regi i chacked to se isles than D308), Then the alte Bl reise is checked tee fit above 065157). Pao cde othe expression ould rot > ose and Dl ‘LEAVE moves eb a ops “Tho stack spill sed sre local variables swell as armen pase in tothe fetion The problem ‘eth the vale nthe ESP reir may change during the feos exertion. Referencing values on he ack becomes rater dificult and comple. To alleviate this to ERP rir is used an wchanging reference ton spite par ofthe ack You wll sometne see the EBPs refered he frame oie One of he acti hat accu inthe anton pol i 0 cay the erent le of he ack once {ESP} tothe ERP reper, However. rior to copying ESP to EBP. the EB register mus fst Be saved ont the stack (ites Be resto ater) Thecopy of EP hat Was saved one stack eal the Saved Frame Posner SFP) 1 sting up FP inthe fnstion rong inthis manner. means hat when you see cae reference EP mis some value (ez JEBP-8) i sacessing al varle. When you ste code efeeace EBP pls some vale {Go EDI Of ia efreming vans Ut ma uae ns ee ssh aay ae ‘re orca aah, Wien leaning pte stack, here are a ew es compilers se. Comps may pup variable ff fhe tc. Italo como to ee value added 9 ESP tne une the et inraton tic can lo pop tyes of of ‘he sack) andthe eave inarston. The lene ination eset unde he sack pol. 105, croc veut sonse ae ' on a i 20 ¢—— ees te) lens) 1104 Pos ots ea [ebptvar_4] (eaystne seme) ex —=p|_ sf | feb) [etpra) [ets] 19 IDA Pro 5 took the epoca} ‘cata [eeproxio} (resis ergo acres) er | ich mam (20. 01000) Here isa digas thatshows how pruners and ol variables ae li ut onthe stack. Lower memory addresses (e000) are on the 2p an higher memory addres OR4O0D arn the tom. Parents da were ssc nto the fetien re labeled “arg “arg and “a>. Local variables are abled "ar var ad Nar". The etm aes is ned“ Since both irtion peters ad oa variable ar on the stack, may he tempting to reference he lative to ‘the ESP roger. Homover, the aie af the ESP rier changes with each push and poptruction. Calelating ‘isances fom ESP atime canbe ily. To simpli tis; many comps will wet EBP registra an ‘changing reference ino the sack. Hejeero abe the EBP riser the exsinsvalue mast Fist be saved ote he Se You can seo his inthe digra wih he hosaeled "fp" fave ere ptr). Afr the value in BP as ‘cen sve the vale ESPean be copied into EP EBP wl row rain urchaned (as wl he ave distances "tom EP to pavametas and locl variables while ESP can ary wih eh shoe ‘once thesis has han coigued dsr, acl veabes which are alloc afer EP as ee et) wl Ive smaller adresse (ince te stak “grows” uptonardssmale addresses. Asa est these wil olen be ‘wren as EBP minus value, Function paruneter hich were push eo the sack pro o ERP bet st wil have larger ales. Comeuenly, thee wil fen be eterence a8 FBP pli ais ‘When using IDA Pro the assemble wil provide txt sed names for parameters an variables. The aes fo prunciers ae arg XAX, whee XXX is he elave dss fam EBP. Themes for ribs ae var 33, Srhore XXX she reve stance fom theft lal variable So [spar] usally the fst parameter, ad [etp: var. surly he it eal variable {yeu noe ational lp understandings the stuck, fis feronce has boon made avaible by oe fhe FOR $10 instruct and can bedstead rom the lloing URL pe proupconvtesouresStegrpical-bandou pa 106 An example of stack usage in a small function. push —ebp Save E6P mov ebp, esp Save ESP in E5P push ecx locate space for local mov eax, [ebp+8] wane aa add eax, [ebpeocn} vee parameters pas add eax, [ebp+ 0h} peers mov [ebp="], eax Save result in foca variate mov eax, [ebp- 4] ———— Copy res to EAX (return) mov esp, ebp estore Es pop = ebp > Restore Es etn onen eave? ere san example faction nd how it uses the ack. “Te es thing that hypo tha the FBP eps sve pin ono the sack. Then the ESP eps copied nt tbe EBP reise, Then spe allocated on he tack fra sige local varable- The space [salle ty the “push ex ntreton which ineemerts he ESP reser by 4. Ana esp 4” woul be fret, bat ‘euie more spas New hee ae tee relrences opamp nthe fection, Namely [CBPY Ox, [EtP asc} and [EBP*Ox10. IFyou were view this cxample IDA Pro on your wn syste, you oud lyse ERP arg 8) [EB tan Chand [EBP rare 10] respectively “The is parmser BP 0x i op int the EAX cee. Then th thro parameters re ned the [AX regiter.Alerthe addons the el (in EAN) is ope ito lal variable, [EBP-Du] Tho lel able isthen copied ck mio PAX (This was done as aesutoFtuming opinzains oP you were to view hs o8 ‘your own systom, sou woudlkaly se (EBPsarg 0) estzad of [EBD.Oxi. IDA Pro door hi aia dentanding i ata the variables ar ikly sed oe After the et vate has est stu the ESP registers estore. The ERP ese is ako esto by popping it ‘off ofthe slack Sine hese two sels of lst ec 0 fequely factions poe, her’ so 8 ‘adated rirastion to implement them "ewe" ach ou sameness mpage mae esp. han 709 bp Finally the ireton rus. ‘ooking atts ede can you tel what does? 107 Original ‘C’ source code for the assembly function just shown. int somefuncCint a, int b, int c) { int d; d=atbicg return(d); ‘Ts isthe source ode for she Fanci that was om he previous slide. As you can est takes thee params (4. std) and asthe ogee, string he salt ea variable (2). The retin vale oh Fontion there ofthe atone, wich ore in he local sre Wer ou able figure cut the revies sho? you haves aay doves, take a momento ty and 'enty which inuctions onthe previous pape cova wo arto en thi abe. 108 Exercise 6: Identify Function Components « Examine two small functions ~Goal: identify different components and stack usage « Examine routines to send irc messages in Sdbot ~sdbot.exe Please tet Eerie 2.6 the lb guide for detailed natuctions Forthis erie you wil examines sl fnctions. The gos fr you to bese comfole ening theaeen corponents of fnetions and how the tack uso You will examin the same specimens befre except this tie yo wll examine code inthe fations used toed alc GRC severe Questions Identify Function Components = Functions between ~ Otss72 ~ oosso = GaatS6G2 — OeS6OF = Nether fonction returns anything ‘+ Function prolog: ey amb params, alrite onthe tack, and rege ~ Ment adresses and inaction use to save ol fame pote, ‘ibcate anew ame port St ~ Meaty dresses end rractons sed wo save regstes used in the ‘+ Identify addresses of function body '* Function epilog: aan adoreses of nsructons used to estore registers wed = Tierify adresses and instructions used to reso the fame pointer he fis funeton s between OX405S72 and OMAESSCC. The second funeton sense ASSEN? ant 46D. Neih uncon reunite vale the EAX reir gnored For ach fnction arsner the along besos: he fnetion peta + oni th nanber of ramets, lel variables on the stock a ogists used + enti’ th adresses ad insrtins used to save the old ame pointer, and allocate a ne fame point 1+ Menthe arses and instructions ws to save ers tht re sin the Fnction, ent he ress oe ody of he ton. Inthe intone: deny the addresses of the instructions use a reno mgs, “+ Kdot'y adresses aninstrctons used to restore he Fane potr 110 Hints Identify Function Components + Parameters are EBP+value + Local variables on stack are EBP-value * Registers are saved to the stack ‘© EBP is the frame pointer = Save EBP on stack ~ Allocate new frame pointer (from ESP) ‘* Restore registers from stack * Restore frame pointer from stack + Push and pop save and restore from stack Here ae some hain ease you gat stuck, Paraiso! ni the fst, re erence {ca varies onthe slack reference 9 net that need be Save se save 1 the sts. ie value rom the ame pine ERP va). om ihe ame oimer(EBP-alue) Registers “The EDP rosin we he fame poi, sot too must he saved the ack, To alate ane Frame oie the ale rom the ESP rei sua. ‘mae function el, esters, nluing he eae oir resiore fa he tack, “The push an popinstrstion save an restore values oad fo the tack, wm ‘You can locate th code by lading sdbotex ia Olga IDA Pro, Hers wha you wll se ify ook a this coe lock inIDA Pro, Th ft fnction) 112 You cance te code by long so xen Oly or IDA Pro, Her’ wht you wl se iyo ook a Ihiscode block IDA Peo. (Te send function.) 113 Answers (1) Identify Function Components For fst function ~ 2 parameters (ebp-+0x8, 0p+0xc) Teepe a eb 4) = local vat. on stack (ebp-0x200) Teprau) ~ 2irealsters used (ec, eax) ‘To save frame pointer: push ebp (01405572) nov ebp, esp (0x05573) To save registers: push edi (Ox405S76) (eex not saved) Function body: 0x40557C = Ox4055C5 To restore registers: pop edi (Ox40SSCA) To restore frame pointer: leave (0x40S5CB) Here are the answers oe ext. er the fis fst, there ar wo prasters(ebpOx8 ad ebpO¥C)- cn local variable en these (ebp- ‘0.20 ad we registers tha are se ed and ea) ti of ase w eerie the nner of arms sed fiction by examining the coe hat cal the faetion. In DA Pr, [bps [eb ang | and [esptul are symolie names fr [bp x8, [skp OC and [bp- 08200 | repels. Tie this in IDA Prick om th tex ame and kth eter “Th ram pointers saved wth wo istration. The rt isrstion eat Os405572 (push bp athe send istaton at 40573 a ep ep) Thee reine sve a 45872 (puso). Thee rpner nse “The body ofthe Frtion iesen OASSIC and ONAOSSCS. ‘he ai reger estore at O4055CA op ei. The fame pointer irene a ORAUSSCB (se). Te leave insreton performs two tas. isthe ESP reiter is siord (ihe value inthe EBP reps coped Inno ESP). Second. tbe EAP le eestor y poppin tf the ck. 14 E emeas Best comer Che ‘eu can oat th ad by larg sdbotex in OtlDhg.o IDA Pro. Hees what yu il ee Fy Fok thiscode lock in IDA Pro, with he answers onerai (The Fist urton. | "5 Answers (2) Identify Function Components For second function = 3 parameters: (ebo+0%8, ebp+0sC, ebp+0x10) “eps bose 4) nd eben 6} ~ 1 geal var. on stack: (€op-03200) Teepe) ~ 2registers used: (eal, 224) ‘To save frame pointer: ~ push ebp (0x405682) = mov ebp, esp (0140568) ‘To save registers: push edi (Ox40568B) (eax not saved) Function body: 0x40568C ~ Ox40S6D8 ‘To restore registers: pop edi (0x4056D0) ‘To restore frame pointer: leave (0x4056DE) For the second funtion ter are the parameters (ep OS ep DxC. and ebp x10), oneal vaiable on she stack (e08200) an two risers ae used (ead ea) NIDA Pro eps). ebp a [eoptang. 8 and [ep bul arcsec names fr [ep Ox) ehprOx), (bp 0] an [e5p4200] respectively. To vw sin IDA Pro, click on he ex nae ad Mh eer ‘There re wo rtactons tsa he rame pointer The fit aston a O40S682 path ep The second insrcton sat 405685 (mov ep, ep). The el esters saved a N$DSGRB (pushed). The ea reper mot saved “The bay of the fino shaven OAOSERC and Dx40S6DS, Th el roped a Ox4D6D0. The frame oiatr rested at Ox4OSODE (lav) The eave istrcton pron wo aks, Fst the ESP roger ierestred te vai nthe ENP rei coped into SP) Second te EB values estore by poping ‘Wot the stack, 116 ‘Youca oct code by lun sdb it Olly of IDA Pro. Hers what yu wil se 300 Took at thiscode Blocks IDA Pro wth the anonrs ayer (The wecondVacon) “7 mene 0, 820), fe Seem sone, “sn 2), Frac eaceee ‘ers hea Hok wha the petocode foro ofthe Ftion might on ike “he call to mense aes tre parameters the abies of bllrin memory yt ato il he er its andthe size fhe uf. The des parameers paseo momet are EB but, ard O20. The ‘rig code mi look ike: mers, 0, 04200), “The sprint Tunton kes test wo argue tea ake more). The Fis argument ithe bet Hold te Ferma outp. The second argument ora sing The arent ar the ora sn te ‘erable and depend on th era sing nts, ths Format sting“ fl spe Eat hee shouldbe one mor sring ergnert. The eeumens pase ino spn are EDP bul "us and he Second parameters the fnction (e'l cll sa?) Tas he pin call might lo ike spent ba, Sista) The ealto len aes single paranetay EPYbut, Thus the ilo ston might ok ke: trent, The cao send tks four praetor socket 1 send data, ull he sie of th bul, vile oseribng lps. The argument paseo ser ae theft pratt th ution (ll hr) [EBPs the rest fom sense 0. Ths the cll send gh lk he senate, ‘The box inthe upp ight handeomor oe lide shows what he comple pico fr sis inion ght ok tke (earning af as sek, nda? as sp. Remember, tis pseudocode sd is al mean 0 te sya covet C source ce, 118 Compilers try to optimize C code before turning it into assembly. ‘+ Dead code elimination ~ Dont include what isnt used Use registers instead of local variables Loop unrolling oh looping pver code block 4 times, | Insiead of loping pyr cde lock 4 tines loop over 4 = Spoce vs. time trade-off Reuse variables on the stack ~ Hie functors take the same arguments) no nee Don't use a stack frame pointer = Frees EBP for general purpose use = Often seen on new Microsoft compilers "There ae several etinizaton that a cmplr can ake When tearsfeming source coe int the art langage ‘This iean sctve ano reuch the comple an theoraicl computer sien comm. ‘One example ofa compile optimization st ame ded code Esser his mens tha thre i source cadet eal by the program, te compiler doesn incl tin the quput Some cmp wl nlae ead code, 0 det he spd if youn oe at never aed Anaer comen compiler atiization i use oly estos fo cal variables insted ofthe sch. This works ‘there area fw mer of al ails. ‘netesmae oop unrting aks astanage oe classe ose YS i ae, sepia coe block coped 2 number times andthe te number oles reduce Instead ffoping oer block of ‘ae times make opis othe ende Boek, This saves onthe cvehead ov to ster eon ms. Femmes, ha tie vers si ado Corpirshaye abo boen brown to reise variables on the tack. Aiwa intone the same TENS ee Inno pedo cle up he sik Anther optinizason ist not eens local variables ni ition agama via he se pon (EP), Tis teceigu seer wi ent Iietatuee as Fane Posy Omission (FPO). Using EBP wo esis ew ‘inc flame with ey fimton sno someting he nl rocemcr depends on This tine mn developed tornake he compilers jobeasiee As cmplr ages bins improved ar processing pomer serene ‘heme, sing anew stack ame is gly unnecessary. Local varias and function arguments ean be Caled from ESP. This i harder fir he overs engine lla since th Valo ESP chara with every PUSH POP, CAL, and RET, However the progam ca actly rm fer since therein ational reget {EBP) mailabe told values wthosswapping hem ack wo mere. 19 Compilers use tricks to clear registers and swap values. Any value XOR’d with itself is 0 » Efficient way to zero (clear) a register Faster than mov reg, 0x0 » XCHG exchanges two registers. — Swap the values ¢ Faster than a move ‘he XO instuzion perf bitwise exctusive-or One net mathemati fat eth any valve SOR tise isaays zero, Compilers ake advantage of hs at and sets a Way tele?) eter "actly aster hana “oy feu O° nsvactin. Youll aso see dieting sein shlc ode ‘evelopment. Whe developing shelkade ts nally aviable 1 void he ml Bye (X00) ince many andr C string eetons se 0X00 fo mak the emf tng ‘The XCHG insation exchanges the values of wo reser. In exbence itm the ales oF threes Without eons ied eit, es ar han dig pln move mov). Compilers wills se chs 120 Compilers may multiply and divide using SHR and SHL. ‘* Multiplying and dividing by two is fairly common + SHR: shift bits right — Equivalent to dividing by 2° = shr eax, 3: Divide EAX by 8 * SHL: shift bits left Equivalent to multiplying by 2* —shl eax, 3: Multiply EAX by 8 “The shi (sh) ad hi es nsrcions can be tse or i manipuaton purpose, bt they am ao ewed for cet types of multiplication ae ison, or every bits othe ight tis guivalnt to dividing by 2 the power hon many its were shied For example the struction sh ss, which hi the cote ofthe EAX regia tthe gt hy its ‘quvaont io ding by 20 Smiley, for eva bist tthe el, iis guar to malipying by 210 the pero how any Bits ‘re shied Soest "sl ex, 3° whih shi he contents fhe FAX regatta 3 sie isan io mailing by 2 or Since SHR and SIL ane wd forbs srihmetic a wal a bit nip "ype arithmetic a bit manipalton wa inened Instead yall ave oo sed to ech anelision 121 Compilers may optimize math operations by using LEA. + Load Effective Address = Used to calculate an effective address = Store result in a register = Doesn't care if result is valid memory address * Commonly used for arithmetic operations = Allows more than one calculation in a single instruction = Calculation is the addressing mode — lea ecx, [eaxtebx*4] 3 instructions for the price of one! The LEA instcton (ad ffctive aes) commonly utd theoughaet code, yeti can Be one ofthe os ica isto fal understand, Spy sated, LEA ealvalaes an elective aes and ste the Ades nari: Rca hata efetve ude ia computed adres. The clch sha LEA dbs care ‘the eat sa vale memory ads ora. es common o sete we of LEA with toring the aes oF fsa variable. For sance “ea ex, ebp-4)" stores the adress ofthe ist eal variable inthe EAX est This aster tha hee sation wkd ely require mov ep. eax al sub es, 4° Sine LEA does cre ifthe effeive ares isa vad merory aes oF LEA ca also be uscd for ‘fin caus. For inane the intact Tea x, fen bx" performs amulipcation operation, “nadition operat, and move asin imation. Don ths prtoularisrctions fal or ‘ccs values nanaray 032 bi vale The cx reps corto re adress fhe hae ofthe a “The bx air consis te nde int the arty. Tho vale eb mutpid by # before sing it the ane hoc each vale ft yas (32 Bit) Am ecole icin onthe purpose ofthe LEA inscton and when ts wed isa of tbe MOV insmetion} is lose at npdstchoverlov.com/quetony658299whatihe-pupose-oftheosisrtion For ore example of advanced math check outhe paper se the paper "Division by variant ners Usieg Mukipticaton” Is about optinizaons a compiler can make ithe source cde i cing vison Py A cent vale a this caso, th paper deneribes how ons dso no sais of mulation 122 What's different in 64-Bit assembly? 186-64 builds upon x86 = Code has to be compiled for 64-bit General purpose registers expanded to 64 bit ~ PAR, REX, ROX, RDX, New registers ~ 18, 19,119, 1, 112, 113,114, 05 Instructions (usually) havea’ (eg. mova) ~ Stack operations choose implicitly ‘New addressing (RIP + displacement) = Postion independent code is easir to wrte ‘One qustion often asked is ow 64-bit cde impacts reverse eninstng. Te 86-64 whitetare tills ‘ponte xi ashes. Meaning 3-61 cofe wil stil wor (end rin} on -bprocesors While ode ‘must be specify coped Tor et-birciectures, here are seme difrnees mt. Addo. even Though 6 bit lar snot henry does exit ‘The frst jor deans tetween MS an 86-6 tha hs ofthe gone purpose esters ave been expandol io chs. The now tit vesion of FAX, EBX. ECX, EDX, oe can be ascssed a8 RAK, BX, REX, RDX, cc, There areako Sew rept tocush IS (rcs ‘The 6. vesin af seve nstions have te eter “(Fr quadword appended, The exception is stack rn inarction (ert, ee)ee id The change thou wil ely ee mot len isthe ue fnew adden ede, calle “RIP oan desing The RIP reser (6-58 version a EP can now e sed Wo reference mere Tecan. This adressing node provides a serious advantage 10 postion independent ede (PIC). FIC is cammonly used im DLLs, which may rot aay be loaded at th desired ass To del wih eda rae | DLL layout he O loader includes information abou the loeation of ute variables a instructions ha cess hoe ates. Using RIPelatve aessiag nul of his afocnatin no nge oes ‘rosin both ead pd an ie 123 Do we need to worry about 64-bit malware? + Traditionally, two types of 64-bit malware have been common ~ Browser Helper Objects for 64-bit Internet Explorer — Device Drivers (rootkits) for Windows x64 + 32-bit code runs on x86 and x64 = Malware authors want the most bang for the buck — Only develop 64-bit code when they have to. Ine maare oyster, malware deelopets want the most ang fr ther buck. Cade cried for 8 32-58 cironmen: runsin on Bik and bth enone, Cade compiled for 4 enionmens wil rn ina s2t environment Malware develope have analy focus 6¥-t developnent ffs. on to Key rs in Winns: Brower Helper Objects (BHO) Device Devers uti) “These ae both examples areas wher 32-bit coe wen tothe jo. nme Explee (54a) wil ead 2 S2-ic BHO. Likesse. 68-21 vesionf Windows wll ta a S24 dvi driver These Bath represent “nutes of wheter ila al Sev bine ane pe ‘hole clases of machines Wilh the iodcton of 32-8 version Windows and fal suport fon ey "86 code on Windnws 8 this trends ot elt change far several yar. Windows VistSe-ver 2008 inrducoa new quirement that rivers loaded ino the hen hado be Open > Navigate to c:\malware = Click on knject.exe ~ Need to provide command line options = notepad.exe :\malvare\katilusion cll ~create Toexamine hin specimen, ist creas the dreary cialwar. If this dren ale ens om our ys, thats ok Nes copy te les knjetxe,KNTHunn land fils ene to he cimalvare decoy. Ar you have copied te les, srt pa copy en.ee and change it the eal are dso. ‘Told ijt int Ohh, star Osby and goto le > Open and hen navigate othe eemalware PAGE_EXECUTE_READWRITE ‘his isan example oF AP Hooking om the Vangush oki The upper sreon capture shows de cll GtProcAddes. Tiss done 1 nthe aes ofthe ven sanction ‘The next sree capt shows the alto VinuaPrtcet wo change the story pensions, The val 40 the numeric corn! for PAGE. EXECUTE. READWRITE. 165 Hooking steps: copy bytes from victim function and compute jump. + LebprlpBasendaress) 4 his does ene copy Leoprvar 9}, ede eae, [ebp+aro.C] ee ptr [eax], oc9n¢———Fist bite of a cee, [edptvar 8] rele ump ex, Orrh “The net screen eaptire show the it Shy ing opie from the vit incon Te ition ‘uh TAEIENO fat actly peor the coy. “Then the ne instnctio is compe. The byte OXE isthe opcode far lative junp Gump 0 lesion, rive the curt eucion. 166 Hooking steps: write instruction and reset permissions (Vanquish). 1 L Reset memory permissions “Thea he compu insrction is ope ove theft fie byes ofthe vit anton. Notice tha these fanction that Copied the Eyes or he ict nc als being wed copy tyes the vc, function. asily a geerc memory copy yl fanotion. Ako notice hat oaton [epee] isroveted, compared wo the previous side Finally he mary pensions ne rest with anther cll wo ViewslPrott. The itn function as no eon patches 167 Once a function is hooked, it must execute the original function. * Auser mode rootkit must still execute the original (pre-hooking) function bytes Some rootkits execute a copy of the original bytes elsewhere in memory * Some rootkits (e.g. Vanquish) copy the bytes back to the original location, execute them, and re-hook the function "The ook nde tate jumps to hy the vc Fnton must execute the rig anton. ‘Many wer mode rts ve cope the erin fin bytes to anther cation in memory. Mi hey exert the Nook cde the jump othe lation a meory comaining the oe function tes, exec he Instron andthe up Eck it the Fneion afer the hook, Inthe ase ofthe Vanguish user made rot, rst fist str the rial visti anton byes, sina ‘sey similar proses hore ahs case, he oii tsa coped ove, and anew nstuston does a eed o be cpus. The Ue rial futon needs toe exceed, and ha eshoked, ning these Proved as Boe Hooked function example from Vanquish. ‘offset POF intent seMaavcureaPau_viN2 FL cae er ee pasenddress Seh_anezes1 estore the otetin oytes 4 adress oF Mprary Function oreset 2UFinavextés1euaavennxPAU_ gin? Sthsorzees | this re-noows the apt re isan example othe rs prt af thereat function ite the ouput om he FindNexFil futon, ‘The st seraen ape shows the calla fenton, sab 142261 whch restores the tn bytes. The nes crs cure sus the cl the ele iki anton Finally th call sub IAE2UAL re-hooks the vit API faction, This the function tha the previous roe shots (show the hooking ofthe itn APE fantom were take Fo, 169 FOR610.2 Roadmap * Core Reversing Concepts Assembly Primer User-Mode Rootkits i) Keyloggers ° Sniffers and Downloaders © HTTP C2 Channels “This ead sis designed ep you navi though he couse matra 170 ‘Wella examine ow keylogges work. Keyloggers an Keystroke loggers poll the keyboard or install hooks. + Users type many interesting things ~ Credit card info, passwords, SSNs, etc. + Monitor user key strokes * Many bots and worms do this, = Send the logs to an attacker ® Two most common methods = Install hook for keyboard events = Poll keyboard state with GetAsynckeyState() ‘Users tye many things tha ae otrest tothe tach. Cait ad infomation, social scury numbers srs banking nvamaton tl have potent ve tothe cima errand Since his infomsions yee atthe keyboard, iret malware specimens wil mito ws Keystrokes Many bots and warms have this tye of factional uit eo thn, they see he og wet Key rks totheatacer,sonetines duh ena sametinestoagh web request orev thaugh rey protcols “There ae wo commonly used methods oust, The fs metho sw installa ok or keyboard ‘eld vers, The second method iw polthe ate of ac hey on te hebua sing the GtAsy eK function. 172 Keystroke Logging with Hooks (Trojan-Spy.Win32.Keylogger.be) seteegiooe 7 Mere isan example ofa keystroke logger wing the Set Windows ookEXA( method of nstion This is From he Well componee ofthe Teej Spy. Wiad2Keslogperbe ek, Convenes the farction th performs ths hooking ns exported withthe mame "Sete Hook” Yeu can ce his ‘incton sts up oir ksybord mess, by calling SxWindowsH oA) with he \WH KEYBOARD prance. his ction als sets to ueeope ase messages by calling ‘SaiWindowsltoosExA() wil the WH MOUSE perarcer, Noe te saa Bees this ction and the DDL injection techni hi ako used ks nhs cae, he WHT KEYROARD an WH. MOUSE rmessgs wove meeepod The previous example of wing hoks ineecpadtheWH CBT message 173 Logging keystrokes with GetAsyncKeyState. Cred eae enters peeks arene into) This sie shows hw aKesroke logger hat uses thet Ase Sat facton wort, “The first thing hat happens Step 1) is that ee we sts typing onthe keyed “The rook cde in loop. he eo prety (eg. every SO milisecod) polls the tae ofeach hey 09 the keybnad by cling GerAsyneKeySt. This oop (cll GetsyneKeySie foreach ey) repeated every §Smilneconds or whitever te malware author decide) 174 Key logging with GetAsyncKeyState (Spybot). Wictiey———— "hack Fans pressed 09 Eetnsyncteystate @——— Check to see Fahey depressed eopovar_ feopsiar=8], son 40144C (phedRequesteadersA) ‘Send HTTP request = SsaO14Ct (HpSendequesta) Read server response ercare the answers for he eerie “The function at aes Ox401400 js ned bythe bt for HTTP cont, Do ot cone hs with he front ares 04401200, whieh suse by Ue Dt dig the xp Noe eam Inside he HTP contol anton, he Internet onetion rete by it ling the InerntOpen A) funciona ares O40 142A. The conection othe emt server rete by call the IenerCanmest fanetion a adess 401451 New. the HTTP cect is built by ft ‘Addon! MUD bear a addod by alg he Hip ne HapOpentequestA(Fanstion at aes Ox401476 doth) Fton et adden OuiDI4AC. The HTTP requests sony cling the HupSendRequesA( fnction at adress Ox4O14CI ally the espe ram the servers ready cing tho InemetResd lt intonataddess SADA. 208 Answers (5) Extra Credit Blinky inky .€040825C | ASCII “aysinFor i 8 ky-08406250| ASCII “dovnload” ky 00401820 Linky 00406244 | ASCIT “hete_Flood” Tinky.0e401820 Linky.€2408238 | ASCIT “iene_F ood” Tinky.00401820 | g: Busi Pus cau usH Pus CALL Blin us PUSH cau Push Push erct Hee we ca sao sme othe commands sappy the bat To do this cn bok at the tings ha ae compared th cata erty the mote saree The addres he stat ofthe dt sant byte remot server i red nthe EBX rege, Adress Ox40I3D3, we sea compre 1 the sing sina" Eaminina the seated futon, tans cut ‘ha this command nic the bot ote ase information shou he vit yon, A adress 00156, we se a compar tthe sting “downlo™ Examining he associated Fnetion, ims ‘at that his command srs theo odode oma remote web Atatres a0, ne see carpare ote string “ftp_oo am he asc tO, HM. ‘thats command iss the Bato lich an HT PGT fo gaint rome web sere Ataris 040167C, we ee a compare 0 te sting “leno” Examining the ase function. tums otha thiscorima instr he Dotto neh an ICMP hod (send sere of ICMP packets) seins Answers (6) Extra Credit Blinky ‘y-00408290| ASCIT “execute” ky 00401820 | inky 00406228 | ASCII “wait” inky 00401620 204016091 Socotece| Beso ler E oer eocor60. peso eb Basal | eaeoi 701 80191 Fae Links Tinks 00408224) ASCIT “die” 00401820 aan 2B ‘ade 401A we sea compare to thesis "execut. Examining the sooo futon, ees ‘ut this commandinsrcs the boa excetea file onthe victim system Avadiress O<401€D8, we sea compare the sing “wai Examining the associ urton. tums ut ‘hicommad sss he Bt ope Fora pee perio of tine. Fil, at ares 0401709, we se a compart he tng“, Examining the ascension, sums couthis cenmandinntacs the Botte exit 210 Answers (7) Extra Credit Blinky « Supported commands —“sysinfo" (strcmp at 0x4015D3) —"“download” (strcmp at 0x4015F6) —"http_flood” (stremp at 0x401626) mp_flood'” (stremp at 0x40167C) “execute” (strcmp at 0x4016AF) —“wait” (strcmp at 0x4016D8) "die" (stremp at 0x401707) ‘eae the answers ote cet question The bt spon the following commas + The"sgsinfo" command, hi can be son by asin compare a adds 0153. This ‘rman intact the Ht sn info ab! tn synthe seve we serves + The'Yownload” command, which cam hacen by ating compare dens O15. This commun instr the bo cewoad ile oma remote web ts 1p flood” conan which ea common nsnicshe h o ch Seon by ating compar at ass 0401626. This TTP GET fod agains remote sever + The"iemp_lod” comand, which canbe sin by leg compara adress Ox40167C. Tit +The “execute” comand, which ean be sun bya command srs the Hot lunch an ICRP od again sete see compat st adress CO16AF. This -ommand instr the ba 1 execute eo the olsen, + The wait” command, which can he sce by sng compare at ads OMO1GDS. This command inns the ha as ora pid pid of me +The We" command, which ca be seen by sting compare les Ox401707. This command instr the Dt exy an FOR610.2 Roadmap «Core Reversing Concepts ¢ Assembly Primer User-Mode Rootkits + Keyloggers © Sniffers and Downloaders © HTTP C2 Channels “Tin madmap sds designed to help you navign through the couse materi 212 Conclusions “Tis rings usalnot ote ee ofthis seston, We covere a otf materi and ook at sever aware specimens 213 Where to go from here? © There is a plethora of malicious code to explore — See the websites * Start researching new techniques used for DLL injection, hooking, etc. » Remember: if you get stuck examining a specimen, don't give up! Athi pon. you my be wondering wha options are saiale o you. There ia peter of malicious code, ‘tat youcan downoad and exario Mateos codes consatyevlving she tors lea ne tics, Mi ery nici t tt reseohing re tehnigues and tts used y te computer undef ‘Ahowe all emenkor: Ifyou go stack examining specimen, denise up Websites with good reversing resources. + www.offensivecomputing.net © va.netlux.org + www.rootkit.com + msdn.microsoft.com + http://securityforest.com/wiki/index.php/Cate gory:Maintaining Access + www-hexblog.org + en.wikibooks.org/wiki/Reverse_Engineering + www.openrce.org ee are some wes hat somin good information aout reverse engineering ‘he st oesiecompating.ne also cons milous cae spines he or dona 215 Books that cover core reversing concepts. ‘Rootkits, Seynare/Acware, Keyloggers and Backcoors~ Zaytser ‘Microsoft Windows Intemals Russinovich & Solan Reversing: Secrets of Reverse Engineering ~ Elam ‘Assembly Language for Inte-Based Computers ~ Ivine ‘hacker Debugging Uncovered = Kaspersey ‘Hacker Disassembing Uncovered - Kaspersky Roots, Subverting the Windows Kesnel—Hoglund & Butler Virus Research and Defense Sroe Disassembting Code IDA Pro and SoRICE - Pirogew ‘The IDA PRO Book - Eagle er are some books tht have marl that ic clevan to revere engncring 216 Additional Exercises (Optional) « Here are additional exercises to reinforce the topics we covered « If you'd like even more practice: A few additional specimens for your exploration in extra-malware.zip Ir yu tke more peat. ake a lok t fallowing evercss when you zt the chance Foreven more pponuniteso pactce evene-ngincering, you il nd aden! malicious executables nthe eta malware zip ile nthe DVD you receive for this eons 27 as Exercise 10: Reverse Blinky (Optional) * Understand meaning of a function « Function is at address 0x401188 * Determine flow of execution * Describe what function does ~ In your own words Exe ~ Include error checking or weaknesses Extra credit: write pseudo code for function The pa of his exercise is to unerstand the meaning of fanction. This goes beyond ust acing thew of a program, an recognizing uncon eal During the course ofa revere einer sesso, ening the limits of a mcious cde specimen an be ‘ery useful: For nance, Beng able een als of servers spcimen cova ean Be wed deelop IDS cers. temas, dean weaknesses in cramunicaton proacos wed by raisins coe at ‘sed belp minimize and cont alisiogn cde ination, You wile saying the sme specimen 8 before, inky. Tis ne you wil verse a neti at adress ‘40118. Your tsk so determine the Now of erect for he artion, and desert in your own words, sae fnctondes, When ering ws he incon ds st ayo csigot ws of the fant, Forxva eet. wite up shor poudocode that deserves the Fencin's opration. 218 Hints (1) « Look at system calls « Look at strings referenced Look at how function is called « Identify variables —How are they used « Ask yourself “what is going on?” Here ae some hits to help you understand the purpose of the ation, Fi lok at any system calls sa he Fn makes Ao lok t srngs that re referenced. Be cael though ea plant false sings ce modi stings. As aes sings shoul stl be wed or suite, rather an for defiive concasons. Abo ok how the nein cid, what other pars f the program cal he artim? When do they clit? Try oie ay variables that ar use, ad thie purpose You wil have to dothisby examining how the seviables red, inal atk youelfwhatis going 08?” Sometimes st ansuerng this question is rough fo unertand the Purpose othe tin, 219 Hints (2) * Return values for URLDownloadToFile * 0x0 is S_OK = Success + 0x8007000E is E_OUTOFMEMORY = Insufficient memory to complete operation + 080000008 is INET_E_DOWNLOAD_FATLURE = IF URL to download is invalid + Look at last exercise to determine what function at Here are sme kta inst lp you cm “The URLDownlasd TOF function hast ifn eu vas. They ae + thea ssucessl the valu 0:0 (symbole constant SOK) i eam + thei insiicem memory t compete the operation, he vale 00700 (s)he consuat E OUTOFMEMORY) i retmed + the URL usedto download he ie invalid he vale 800COD8 (symbolic constant INET E DOWNLOAD FAILURE) is eumed ‘The anton at des 440400 called at he ed of he Faction you are examining. Refer othe ast tcc (Exerc) determine wha he Fnton dos 220 Answers (1) Reverse Blinky Function downloads a file using URLDownloadToFile If out of memory sends "Result: out of memory” Tf invalid URL sends "Result: download failure” Tf successful sends "Result: ok” Otherwise sends “Result: " followed by result (as hex) Description = Function downloads 2 fle, checks for various error conditions, and sends esults hack to attacker/controller ere ae the anowers tothe ete. The faption downloud le sing the URL Downloade Faction. checks the result oh anton call fore vals, Ifthe rtur salu OUTOFMEMORY, th furtion sends the ring“Resut tof mem” the rtm ‘ales INET-E- DOWNLOAD. FAILURE, th feton ends he sng"Rewilt downoad fale. the ‘tum salu tS OK. th function sens he sna “Result ok- Othe he Fnction sends hes “ent” followed bythe mers va of theres Gn ex) sheatacker 221 Answers (2) Extra Credit Reverse Blinky eres some pszusocde forthe function. As soca see the precedes eal and undeniable bs many nomprogrammers. Ty ¥noe your vn pecudoce, iel si ( otthe same) asabove 222 Exercise 11: Reverse Spybot (Optional) Reverse other portions of spybot.exe = Same specimen as exercise 7 Multi-functional bot = Built-in HTTP server ~ Spreading capabilities * Determine what various functions do = See if you can build network or host signatures to identify specimen * Spend rest of dass = Continue on your own “he st enriseo the days For you o reverse potonso Sybet You wl oe analyzing he same specimen ised in Exercise 26 Spybot ital Wo, wth many apis lacuna balin HE server and he ably v0 prea 16 multiple erent systems, ‘Your tsk st lose Fnstion and determine what they do. One common goin reverse ennering so velop neturkad hot bed irre to identify te specimen activity sn an ganization While eerse ‘cncering this pvimen, ee if you cou oni sigatures tha ou be une ina exports ernment Trad te spin ‘You wil nether of laste to analyze te specimen. Vou can lo continue to analyze the spin side of a 223 End of FOR610.2 Conrstultins!Youhave reached the end of FORSIO. 224 FOR610.2 Appendix Common x86 Assembly Instructions Kernel-Mode Rootkits FORGIO2 Append posntsrlreceinlommtion or commonly ase N86 assembly istctons and provides “rie onerviwofkamelmads ont, These miele were writen ty Michel Maran are mana by ‘ake Willan. Common x86 Assembly Instructions ‘This section of the Appendix provides erence fr commenly-sed eel x86 sembly instretons, which sore lel to encounter when analyzing malicious software, 2-8 List of Instructions * List of commonly used 80x86 assembly instructions = Not an extensive list, but this is not meant to be a course in assembly programming ~ See references at the end of this appendix for further information Assembly sn ardhiacture-dopondont programing lngungsahowgh eri earan subst amongst ach proscror fly) We'll to jo rractins,skippins oles such the dierent Way oF adding ‘memay- or ening high evel ogc srotres. Fee more norton hee are vars resources te Teer some of hich ae lise the end of tis appeals ‘heoughout this appends the code samples arin courier en. Cnmmeis hing need by the semble) sre recoded witssemicole (";").Anassembly instuton ca be ought of shaving wo pinay Farts "he aserabyinsrctin smeties refered was an pce operation code, whichis sl swell eo, of, oF wosrgmnens whch ae clled eran Arithmetic Instructions * ADD SUB INC DEC —_ * DIV * SHL/SHR: ROL/ROR Lets tke ok stsome of the basie rthmatcinsrustions 4k ADD dest, src * Adds source to destination * Result is stored in destination After the ADD, EAX equals OxOA (10 decimal), EBX is still 0x02 (2 decimal). “The ADD insta te operant (destination and owes} ogther using integrate The rsa estore inthe desinaton operat MOV EAH, 0X03: EA ~ 0x08 (® docimal) MOV ERE, 0x02 1-EBK = Ox02 (2 decimal) Inthe example onthe, ae the ADD operation, EA eu ONDA (10 dein), EBX i stil 002(2 inal 5-A SUB dest, src Subtracts the source from the destination * Result is stored in destination After the SUB, EAX equals 0x06 (6 decimal), EBX is still 0x02 (2 decimal). ‘The SUB isructon sutras the source peridot the destination pend. The eu fthe subraction i stored inthe denon opera MOV EAK, 0x08; BAX ~ 0X08 (8 decimal) ov ERK, x02 BK ~ 0402 (2 decimal} Inthe exampe ons sl, after te SUB operation, EAX esas Ox (6 decimal, EBX i sil 002 (2 ‘ecial. 6-A INC dest * Increments the destination by 1 08 EA = ONDE 1B doetmay After the INC, EAX equals 0x09 (9. decimal). “The INC instru incomes he destinin operand by 1, This isthe same thing doing an ADD insnation withthe sme destination, ar using he sur Mow ERS, 0x08 7 BAX = ODBC decimal) Inhe example ons sie afer he INC operation, EAX equals 0:0 (9 decal. DEC dest * Decrements the destination by 1 After the DEC, EAX equals 0x07 (7, decimal). “The DEC instruction decrements the destin operand by 1. This isthe sae thing as doing» SUB instruction withthe ame destination and using source | MOV ERK, ODE AX = CHOU (0 docins} DEC ax ‘Aer the DEC, EA equals 0x07 (7 dom BA MUL src + Multiplies AL/AX/EAX by source (Unsigned integer multiplication) * Result is stored in AL/DX:AX/EDX:EAX After the MUL, EDX:EAX equals 0x10 (16 decimal), EBX is still 0x02 (2 decimal). ‘The MUL instrston muliphis ither AL, AX, oF EAN by tho operand. Which restr gts mpi i seri the ie (in rantr of his) of the source epcrind the sutce operand ei A. iste. the source operands 1 bits AX sued. the source aera is 32 is, FAX Ts se "he acto f the esl doped onthe se of te source opera Since mulplicsin of two numbers can rest inalargr sed ress eget destination seeded, the ore opera iss eres re ‘AX (6 bis) Ite source operas [6s the est stored nD: AX (92 bits oa the source ran i 32 bis he eal sated in EDXCEAX (6 is tal, Mukper (operand) Mutipiand Prot ois ax. DxAX, site FAX EDXEAX DIV src * Divides AX/DX:AX/EAX:EDX by source (Unsigned integer division) * Quotient is stored in AL/AX/EAX and remainder in AH/DX/EDX After the DIV, EAX equals 0x80 (128 decimal), EDX equals 0x03(3 decimal). “The DIV inseusion divides AX,DX:AX, o¢ EAXIEDX by the sous operand The et sedi iter |AL,AX oF EAX, athe emailer is sore in citer AH, DX, or EDX. The sz ofthe source operand satcminos whats wed or division. whore the quaint and remainder are wore Ihe sour operand is bis AX is divide bythe opera andthe elt sored AL, wih he ronan i AN, Ifthe sce ‘operandi I bits, DXA ir ved y the operan, and the eat stor in AX wth he remain DX, Ifthe sure opr is 32 bis, EDXCEAX is divided bythe pera. nd the gation ir stared in EAX ithe reoninder in EDX. Dividend Drs (opend) Quaiere——Remaindee Ax. his aL at DxAX eae ax px. EDXHEAX 32h FAX. EDX Shifting (SHL/SHR) © SHL dest, src ¢ SHR dest, src ~ Shifts the destination to the left (SHL) or to the right (SHR) by source bits (fill with 0) “The Sit an tiinatractins hit the detination operand the et ih (respectively) source numberof Iie, The dena is ero-pnéded, mening x ow be are node, vero sed Darna SIL the eknost Int(ortherignmes bit nthe case oF SHR) moved in the carry Nag (CF). 0 1 ERK = 003 (3 docinaly Aer the SIL operation, EAX equals 06 (6 decimal) HOV BAK 0x03 2 BAK = OW03 (3 decimal) Afr th SHR pation, EAX equals 0 (1 dima) WA Rotating (ROL/ROR) * ROL dest, src * ROR dest, src = Rotates the destination to the left (SHL) or to the right (SHR) by source bits ‘oxaing bit ce tothe left (ROL) or ight ROR) very sear to shiing except athe case oF ROL, the Jeftmost itis copie! into atthe car Nag (CF) and he ghee BI the ease OF ROR, the inc pied ino both hecary Nag (CF) and he time it. nov AL, 0x01 FAL = G01 (1 decimal) ‘Ae he ROL option AL qual 04 (4 decimal) Wow AL, oxo 2 AL = 0x01 (1 decimal) FOR Aly 2 afer the ROL operon, A equals x40 (64 decimal) 12-4 Boolean Instructions ° AND * NOT *XOR ° CMP Now; le tke sok a some the intact tht deal wth books operation. 13-4 Flags + 16 bit register where each bit has a different meaning Control bits control CPU operation ~ Status bits indicate status of an operation Les talk aout register fra monet. A register ely just namo chip soap action. Since the ‘exierare on-chip thee acas ime fe fx There are ome gene purpose reser: (EA. ERK, ECX, EDX, et an some sats raster (Pgs, tc) The gs register i porant os because he ings bts a register epresen the sds effects of vais nsrctons (2g, ADDSUHMIUI. A few ofthe indus we a tress (O-Overow - Seth result ofa signal athe intton genres number which ther oo age oF ‘oo smal forthe destination. ‘D:Dirctioal Thc bit conrosthe desion tasting istsctons (e.g SCAS) operate ther | fr high remary aese ow mem near lemony aden a hgh emy ase} ‘Sign —TWisbitisst ifthe ists ei a umber tht signed, 27: Fars — Tis it sete nston res na 20 (hers 20). (€:Camy This bits serif the rst ofan signe aittmeticnaracton soo lange fn th destination, AND dest, src * Performs a bitwise AND of the destination and source * Result stored in destination After the AND, EAX equals 0x20 (32 decimal), EBX is still Ox03AC (940 decimal). The AND instruction performs abst lapel “AND ofthe desination and source operands. The esl oF thisopeation istored inthe destination, 1 ERK ~ OxEOR3 (61475 docinaly 1 HOX = OxOBAE (940 decinal) Ae the AND operation, BAX ous 0120 (82 decal, EBX itl Ox03AC (40 dina, 000 9011 10:0 1100 trax) oie 0) 000 9000 00:0 c009 tReswit) ‘9000 9900 00:0 9000 == 0x20 132 decimaty 18-A OR dest, src * Performs a bitwise OR of the destination and source * Result stored in destination After the OR, EAX equals OxF3AF (62383 decimal), EBX is still Ox03AC (940 ‘The OR insructon performs bw logical “OR” of the destination and source operas, The est of hi ‘operation sored te destination ov HAx, OxFoRS 1 BAX = OXF023 (61475 decinal) Woy Ex, 0¥03KC 1 EBX = 0X03HC (010 decimal) Alter th OR operation, EAX equals OXF3AF (62388 decal), EBX isl (X03 (40 dina 1121 0900 0010 oor (eAx} 6000 011 1018 1100 ¢eRKi = (08) 1111 0011 1010 1111 (Result) 2211 0011 1010 1111 = OKFIAF (62389 decimal) NOT dest * Inverts all of the bits in destination * Also called the one’s complement After the NOT, EAX equals 0xOFDC (4060 decimal). “The NOT insrastin invert al ofthe bits inthe destination Thin is ho Kran one's complement. The resulf this operaion fs stored inthe destination, Mov snk, oHFC2s 2 RIK = OORT (GLE7S decimal) Nor Bax. [Aer the NOT epation, FAX equ DFC (4060 dein), 211 9900 0010 ooI (eax? (0000 1112 1101 1100 (Reaute ooo 1111 1401 1200 = ox0FDe (4060 decimal) NEG dest * Negates all of the bits in destination — Invert all of the bits, and then add 1 * Also called the two's complement After the NEG, EAX equals 0x0FDD. (4061 decimal). ‘The NEG insrsion nezates the destination operand. I ogstes the operand sing 40 compliment (essentally itiver al ef the bisa the destination opera, sed then as). The reso is operations Nore inthe desnaion. Nov BAK, OxFO22 1 AK = OxF023 (61475 decinal) ‘ter the NEG epention, FAX equa OXOFDD (061 dim) 3112 0000 018 9011 {AKI ~ ~ (wes) 000 2111 1101 1101 ¢Resuity 000 1111 L201 1101 == oxdFDP (4061 decimal 18-0 XOR dest, src * Performs a bitwise XOR of the destination and source « Result stored in destination BsEO2s 1 BAK cee After the XOR, EAX equals OxF38F (62351 decimal), EBX is still Ox03AC (940 decimal). he NOR insnstion performs iis lia exchsiveor (NOR ofthe destination and source operands ‘The el ofthis poration ‘stored in the desinavon HOV ERK, OXFO23 2} BAX = O¥F023 (61175 decimal) Nov EBX, Ox0IAC 1} EBX = OxO3AC (940 decinal) ter the OR option, EAX equals OXF38F (62383 decimal, EBX isl D.03AC (940 dima. 4000 0011 10:0 1200 EHX) us ~~ (x08) 1211 O11 1000 1111 «ResudL) 1121 0021 1000 1121 —~ OxFSBF (62351 decimal) TEST dest, src * Performs a bitwise AND of the destination and source . ony. changes the status fla After the TEST, EAX is still OxF023 (61475 decimal), EBX is still Ox03AC (940 decimal). ‘The TEST instrutin performs an implied AND beeen the source and destination aperinds. The ess" sored aner etal Ie varius lags wii the as rege ae st ‘You may be ski wba the pono this? Simpl: by examining he various lags, we ean erate contra jms. Tha we an have conditional ranches within eur cade The fsirtion sch as NAL IC ‘well orinal jin that easing the Tags register to determin ump ofa CMP dest, src + Subtracts source from destination * Only changes the status flags After the CMP, EAX is still OxF023 (61475 decimal), EBX is still Ox03AC (940 decimal). The CMP isso similar tthe TEST inatracion. The CMD isrctonperrmsan impli subtraction (SUB) ofthe sourc operand rm the deviation operand. The restored any where tad the varios Mage within te lg eister reset The enone forth ar the sre a withthe TEST ierction. Control Instructions ¢ IMP/Icc PUSH RET/RETN 2 ont + SCAS REP/REPcc ies * NOP Now let's tke a fock some ofthe nsactions that contro he low of progea, 22-4 MOV dest, src * Copies source into destination TaeO2. 2461475 decal) After the MOV, EAX and EBX are both equal to 0x03AC (940 decimal). ‘The MOV insnacton copies the source operand into the destination operand Mov Ene, oxF023 1 BAX ~ OxFO22 (61475 decimal) Mov EK, cx03AC + EBX = Ox03AC (940 docinaly nov BAK, EBX, Aer the MOV operation, EA and EBX ate bth exo ONOSAC (OW decimal, IMP dest * Transfers control to destination (“jumps” to destination) * Always jumps to destination—there is no special condition that needs to be true After the JMP, the processor will start executing instructions at memory location 0x804A8084. ‘The JMP insect allows yu to jun 0 anote portion of ae, IMP wil aay jump tthe nro, thee ae no special eros pei Rg slings) neces, op oxeoane0e Ae the JMP option the processor wl start exec nsttions memory loston OXSDSAKORS, 24-A Conditional Jcc (1) © Jec * Conditionally transfers control to destination (“jumps” to destination) * Only jumps to destination if a specific condition has been met “The ther ype of IMPS ae conto jumps. | efrto hese a th Joe ay. Tse insrctins ae inthe foxm of sono, whore “codon ru two or thee ker shorthand descrigion fe conden rege to,jump to another point in code The nox Few’ shdor wl describe Ie varius Je scons. Jee iseutions ae normlly preceded by @ CMP nsttion, Remember the CMP insrton stands for Comat, tcompare two operands hy pofonning an imped susan ofthe sure opera fom the ‘estnaton operand, Since CMP perfor an mpi suacton, ether operand modad. Hower, th ‘arouse lags reese [Zre Corry. et) are se. A cation determined Yo be met owt based fT ‘ofthe nda fg ha are set inthe Nas eit. 25-A Conditional Jcc (2) * General comparison jumps JE) ~INZ | INE ce INC -IOZ a ~JECXZ ‘The frst clas of eondtona Jc istuton re jumps with cmition tht depen on genera compris. ‘The sitions are Jom if Equal (JE) ump it Zoro (2) Jumps de ee operands ar ual orf they ae ze. This onion sme ifthe Zr Flag (2) inthe Mas reprise Jump if No qual SNE) / Jump it Not Zero GNZ) ‘hms ithe to operas are erento nt 26. This eonditon st if th Zero Flag (Zine Nags roger isset0 0. ump if Carey UC) Sup tere was acer. This coniion fs met the Cae Hag (CH) e110 Jump if No Carry UNC) Dumps ihere was notacarry. This condition met fthe Cary Mags 0. Jumps CX Z4r0(CXZ) ump if FCX is Zero (SECXZ) Samp CX af ECR ee 0, Jump i Pavey Py ‘ums file parity Seven This coitn sme ifthe ary a i Jump if Not Parity NP) Jumps ifthe parity od. This comton met the py Mag is set 19 0, 26-A Conditional Jcc (3) * Unsigned comparison jumps = JA / INBE =JB / JNAE JAE / INB =JBE / JNA ‘he est nly ofc instruction: re jumps wth condton tht depend on emparisons whore bth operands arated as unica Jump if Above (JA) Jump if Not Below or Equal INBE) ‘These insttionsjamp ifthe st operands bizar tan te second operand (operand > operand 2). This ‘operand. This canton ratte Cary Fag (CF) 18D Jump I Below (38) / Jump if Not Above or Equal INAK “Thess ntations jump if th fst operat ses han he secon operand (operand! operand?) This endition met ithe Cary Pag (CF ist Jump i clow or Equal BE) / Jump Not Above INA) "hese insrctions jmp he st operandi ess than oe ual te second operand operand < opeané) This emo met ne Cary Fas (CF) othe Zero Fla (ZF) age 1 27a Conditional Jcc (4) © Signed comparison jumps SaaS delle ING / ILE IGE / INL 38 / INS face JO / INO “The ls set of Jc iestueions are jumps with condtons hat depend on iene comparisons, Jump Greater tan (3G) Jump Not Less than or Equal (INLE) “These instruction janie st operandi eter thn second operand operand > oper). This ‘ondton ismet fhe Zero Flog (ZF) sO and the Sign Fag (equals the Overlow Fig (OF) Jump if Not Greate than (ING) Sump iF Les than or Equal ILE) These instructions jmp the iat operand ies than of exalt cond operand (pean <= operand) This condition in at the Zero Flag (ZF equ or Sign Fag (SF) ine othe Over Fag (OP). sump if Greater tan oF Equal SG) / Jump i Not Les thaw INE) "These ssi jy dhe spear eter no eg 9 he CON opera opera >= ‘psand), Tis colton ist i he Sig Fag (SF) eeu he Overtiow Flat (OF) Jump Signed (1S) Jap it Not Signed INS) ‘he JS isrstion jung ifthe aun issiged. Ths condition fet the Sign Fag (SF) net 1. The INS instruction ump he number ine sans. Ths condition smth Sign Fag (SF) sto. Jump iF Les than UL) / Jump f Not Greater than or Equal GNGE These isrcton jump ithe frst operand cles than the second operand pend < operand). This condos ict i te Sian Flag (SF dos aaa te Overton Hag (OF), Jump i Overflow (10)/ Jump i No Overfow (JNO) “The 10 intructonjnps i tee was an overow. This eas sme ifthe Over Fig (OF) ist ‘The INO nstvetion jumps i tee was nolan overt, This cain is met Ue Over Flag (OF) se we. 28-A LOOP dest + Repeats a segment of code (between dest and the LOOP) CX number of times Will loop from 0x8043A048 to the LOOP 0x08 (8 decimal) times. “The LOOP iran epee etn of code tween the destination oper (an adres in memory) and the “alts ofthe LOOP inition, The name of res that he nop x ace x etry he the CX esr. Fach tne he proces Toepsthrugh the code it decrement CX reste by ane When the CX restr deerme tthe proessr execu he intact imei Zllowing tke LOOP MoV CX, 0208 7 CK =~ 0x08 (8 decimaty onsoasnso4a: ) This is addroas OnB0420008 Wit op frm O47 A048 tthe LOOP 0508 ( desi ines. 29-4 PUSH src * Pushes the source onto the stack —For later retrieval by POP After the PUSH, the value of EAX (0x26 or 38 decimal) will be copied onto the stack. ‘The PUSH insrutin copies the source operand ono the system slack, "These suck sa area of memo thai used to temporary hold dat The stack 3 Last In Fit Out (LIFO) strstr wih mens tha he sk lam pushed onto the stack, ithe item popes off Nov BAK, 0326 1 BAK = (326 (decimal 30) ‘Ate he PUSH opsaton. the value oF EAX (0260 8 ei) wil copied ata the tack

You might also like