Hacking:TheArtofExploitation,2ndEdition
byJonErickson
Publisher:NoStarch
PubDate:January15,2008
PrintISBN-13:978-1-59-327144-2
Pages:480
TableofContents|Index
Overview
Hackingistheartofcreativeproblemsolving,whetherthat
meansfindinganunconventionalsolutiontoadifficultproblem
orexploitingholesinsloppyprogramming.Manypeoplecall
themselveshackers,butfewhavethestrongtechnical
foundationneededtoreallypushtheenvelope.
Ratherthanmerelyshowinghowtorunexistingexploits,author
JonEricksonexplainshowarcanehackingtechniquesactually
work.Tosharetheartandscienceofhackinginawaythatis
accessibletoeveryone,Hacking:TheArtofExploitation,2nd
EditionintroducesthefundamentalsofCprogrammingfroma
hacker'sperspective.
TheincludedLiveCDprovidesacompleteLinuxprogramming
anddebuggingenvironment-allwithoutmodifyingyourcurrent
operatingsystem.Useittofollowalongwiththebook's
examplesasyoufillgapsinyourknowledgeandexplore
hackingtechniquesonyourown.Getyourhandsdirty
debuggingcode,overflowingbuffers,hijackingnetwork
communications,bypassingprotections,exploiting
cryptographicweaknesses,andperhapseveninventingnew
exploits.Thisbookwillteachyouhowto:
ProgramcomputersusingC,assemblylanguage,andshell
scripts
Corruptsystemmemorytorunarbitrarycodeusingbuffer
overflowsandformatstrings
Inspectprocessorregistersandsystemmemorywitha
debuggertogainarealunderstandingofwhatishappening
Outsmartcommonsecuritymeasureslikenonexecutable
stacksandintrusiondetectionsystems
Gainaccesstoaremoteserverusingport-bindingor
connect-backshellcode,andalteraserver'slogging
behaviortohideyourpresence
Redirectnetworktraffic,concealopenports,andhijackTCP
connections
CrackencryptedwirelesstrafficusingtheFMSattack,and
speedupbrute-forceattacksusingapasswordprobability
matrix
Hackersarealwayspushingtheboundaries,investigatingthe
unknown,andevolvingtheirart.Evenifyoudon'talreadyknow
howtoprogram,Hacking:TheArtofExploitation,2ndEdition
willgiveyouacompletepictureofprogramming,machine
architecture,networkcommunications,andexistinghacking
techniques.CombinethisknowledgewiththeincludedLinux
environment,andallyouneedisyourowncreativity.
Hacking:TheArtofExploitation,2ndEdition
byJonErickson
Publisher:NoStarch
PubDate:January15,2008
PrintISBN-13:978-1-59-327144-2
Pages:480
TableofContents|Index
HACKING:THEARTOFEXPLOITATION,2NDEDITION.
ACKNOWLEDGMENTS
PREFACE
Chapter0x100.INTRODUCTION
Chapter0x200.PROGRAMMING
Section0x210.WhatIsProgramming?
Section0x220.Pseudo-code
Section0x230.ControlStructures
Section0x240.MoreFundamentalProgrammingConcepts
Section0x250.GettingYourHandsDirty
Section0x260.BacktoBasics
Section0x270.MemorySegmentation
Section0x280.BuildingonBasics
Chapter0x300.EXPLOITATION
Section0x310.GeneralizedExploitTechniques
Section0x320.BufferOverflows
Section0x330.ExperimentingwithBASH
Section0x340.OverflowsinOtherSegments
Section0x350.FormatStrings
Chapter0x400.NETWORKING
Section0x410.OSIModel
Section0x420.Sockets
Section0x430.PeelingBacktheLowerLayers
Section0x440.NetworkSniffing
Section0x450.DenialofService
Section0x460.TCP/IPHijacking
Section0x470.PortScanning
Section0x480.ReachOutandHackSomeone
Chapter0x500.SHELLCODE
Section0x510.Assemblyvs.C
Section0x520.ThePathtoShellcode
Section0x530.Shell-SpawningShellcode
Section0x540.Port-BindingShellcode
Section0x550.Connect-BackShellcode
Chapter0x600.COUNTERMEASURES
Section0x610.CountermeasuresThatDetect
Section0x620.SystemDaemons
Section0x630.ToolsoftheTrade
Section0x640.LogFiles
Section0x650.OverlookingtheObvious
Section0x660.AdvancedCamouflage
Section0x670.TheWholeInfrastructure
Section0x680.PayloadSmuggling
Section0x690.BufferRestrictions
Section0x6a0.HardeningCountermeasures
Section0x6b0.NonexecutableStack
Section0x6c0.RandomizedStackSpace
Chapter0x700.CRYPTOLOGY
Section0x710.InformationTheory
Section0x720.AlgorithmicRunTime
Section0x730.SymmetricEncryption
Section0x740.AsymmetricEncryption
Section0x750.HybridCiphers
Section0x760.PasswordCracking
Section0x770.Wireless802.11bEncryption
Section0x780.WEPAttacks
Chapter0x800.CONCLUSION
Section0x810.References
Section0x820.Sources
COLOPHON
Index
HACKING:THEARTOFEXPLOITATION,
2NDEDITION.
Copyright©2008byJonErickson.
Allrightsreserved.Nopartofthisworkmaybereproducedor
transmittedinanyformorbyanymeans,electronicor
mechanical,includingphotocopying,recording,orbyany
informationstorageorretrievalsystem,withouttheprior
writtenpermissionofthecopyrightownerandthepublisher.
PrintedonrecycledpaperintheUnitedStatesofAmerica
1110090807
123456789
ISBN-10:1-59327-144-1
ISBN-13:978-1-59327-144-2
Publisher:
WilliamPollock
ProductionEditors:
ChristinaSamuellandMeganDunchak
CoverDesign:
OctopodStudios
DevelopmentalEditor: TylerOrtman
TechnicalReviewer:
AaronAdams
Copyeditors:
DmitryKirsanovandMeganDunchak
Compositors:
ChristinaSamuellandKathleenMish
Proofreader:
JimBrook
Indexer:
NancyGuenther
Forinformationonbookdistributorsortranslations,please
contactNoStarchPress,Inc.directly:
NoStarchPress,Inc.
555DeHaroStreet,Suite250,SanFrancisco,CA94107
phone:415.863.9900;fax:415.863.9950;;
LibraryofCongressCataloging-in-PublicationData
CodeView:
Erickson,Jon,1977Hacking:theartofexploitation/JonErickson.--2nded.
p.cm.
ISBN-13:978-1-59327-144-2
ISBN-10:1-59327-144-1
1.Computersecurity.2.Computerhackers.3.Computernetwo
I.Title.
QA76.9.A25E752008
005.8--dc22
200
NoStarchPressandtheNoStarchPresslogoareregistered
trademarksofNoStarchPress,Inc.Otherproductandcompany
namesmentionedhereinmaybethetrademarksoftheir
respectiveowners.Ratherthanuseatrademarksymbolwith
everyoccurrenceofatrademarkedname,weareusingthe
namesonlyinaneditorialfashionandtothebenefitofthe
trademarkowner,withnointentionofinfringementofthe
trademark.
Theinformationinthisbookisdistributedonan"AsIs"basis,
withoutwarranty.Whileeveryprecautionhasbeentakeninthe
preparationofthiswork,neithertheauthornorNoStarch
Press,Inc.shallhaveanyliabilitytoanypersonorentitywith
respecttoanylossordamagecausedorallegedtobecaused
directlyorindirectlybytheinformationcontainedinit.
ACKNOWLEDGMENTS
IwouldliketothankBillPollockandeveryoneelseatNoStarch
Pressformakingthisbookapossibilityandallowingmetohave
somuchcreativecontrolintheprocess.Also,Iwouldliketo
thankmyfriendsSethBensonandAaronAdamsfor
proofreadingandediting,JackMathesonforhelpingmewith
assembly,Dr.Seidelforkeepingmeinterestedinthescienceof
computerscience,myparentsforbuyingthatfirstCommodore
VIC-20,andthehackercommunityfortheinnovationand
creativitythatproducedthetechniquesexplainedinthisbook.
PREFACE
Thegoalofthisbookistosharetheartofhackingwith
everyone.Understandinghackingtechniquesisoftendifficult,
sinceitrequiresbothbreadthanddepthofknowledge.Many
hackingtextsseemesotericandconfusingbecauseofjustafew
gapsinthisprerequisiteeducation.Thissecondeditionof
Hacking:TheArtofExploitationmakestheworldofhacking
moreaccessiblebyprovidingthecompletepicture—from
programmingtomachinecodetoexploitation.Inaddition,this
editionfeaturesabootableLiveCDbasedonUbuntuLinuxthat
canbeusedinanycomputerwithanx86processor,without
modifyingthecomputer'sexistingOS.ThisCDcontainsallthe
sourcecodeinthebookandprovidesadevelopmentand
exploitationenvironmentyoucanusetofollowalongwiththe
book'sexamplesandexperimentalongtheway.
Chapter0x100.INTRODUCTION
Theideaofhackingmayconjurestylizedimagesofelectronic
vandalism,espionage,dyedhair,andbodypiercings.Most
peopleassociatehackingwithbreakingthelawandassumethat
everyonewhoengagesinhackingactivitiesisacriminal.
Granted,therearepeopleouttherewhousehacking
techniquestobreakthelaw,buthackingisn'treallyaboutthat.
Infact,hackingismoreaboutfollowingthelawthanbreaking
it.Theessenceofhackingisfindingunintendedoroverlooked
usesforthelawsandpropertiesofagivensituationandthen
applyingtheminnewandinventivewaystosolveaproblem—
whateveritmaybe.
Thefollowingmathproblemillustratestheessenceofhacking:
Useeachofthenumbers1,3,4,and6exactlyoncewith
anyofthefourbasicmathoperations(addition,subtraction,
multiplication,anddivision)tototal24.Eachnumbermust
beusedonceandonlyonce,andyoumaydefinetheorder
ofoperations;forexample,3*(4+6)+1=31isvalid,
howeverincorrect,sinceitdoesn'ttotal24.
Therulesforthisproblemarewelldefinedandsimple,yetthe
answereludesmany.Likethesolutiontothisproblem(shown
onthelastpageofthisbook),hackedsolutionsfollowtherules
ofthesystem,buttheyusethoserulesincounterintuitive
ways.Thisgiveshackerstheiredge,allowingthemtosolve
problemsinwaysunimaginableforthoseconfinedto
conventionalthinkingandmethodologies.
Sincetheinfancyofcomputers,hackershavebeencreatively
solvingproblems.Inthelate1950s,theMITmodelrailroadclub
wasgivenadonationofparts,mostlyoldtelephoneequipment.
Theclub'smembersusedthisequipmenttorigupacomplex
systemthatallowedmultipleoperatorstocontroldifferentparts
ofthetrackbydialingintotheappropriatesections.They
calledthisnewandinventiveuseoftelephoneequipment
hacking;manypeopleconsiderthisgrouptobetheoriginal
hackers.Thegroupmovedontoprogrammingonpunchcards
andtickertapeforearlycomputersliketheIBM704andthe
TX-0.Whileotherswerecontentwithwritingprogramsthatjust
solvedproblems,theearlyhackerswereobsessedwithwriting
programsthatsolvedproblemswell.Anewprogramthatcould
achievethesameresultasanexistingonebutusedfewer
punchcardswasconsideredbetter,eventhoughitdidthesame
thing.Thekeydifferencewashowtheprogramachievedits
results—elegance.
Beingabletoreducethenumberofpunchcardsneededfora
programshowedanartisticmasteryoverthecomputer.Anicely
craftedtablecanholdavasejustaswellasamilkcratecan,
butonesurelooksalotbetterthantheother.Earlyhackers
provedthattechnicalproblemscanhaveartisticsolutions,and
theytherebytransformedprogrammingfromamere
engineeringtaskintoanartform.
Likemanyotherformsofart,hackingwasoftenmisunderstood.
Thefewwhogotitformedaninformalsubculturethatremained
intenselyfocusedonlearningandmasteringtheirart.They
believedthatinformationshouldbefreeandanythingthat
stoodinthewayofthatfreedomshouldbecircumvented.Such
obstructionsincludedauthorityfigures,thebureaucracyof
collegeclasses,anddiscrimination.Inaseaofgraduationdrivenstudents,thisunofficialgroupofhackersdefied
conventionalgoalsandinsteadpursuedknowledgeitself.This
drivetocontinuallylearnandexploretranscendedeventhe
conventionalboundariesdrawnbydiscrimination,evidentinthe
MITmodelrailroadclub'sacceptanceof12-year-oldPeter
DeutschwhenhedemonstratedhisknowledgeoftheTX-0and
hisdesiretolearn.Age,race,gender,appearance,academic
degrees,andsocialstatuswerenotprimarycriteriaforjudging
another'sworth—notbecauseofadesireforequality,but
becauseofadesiretoadvancetheemergingartofhacking.
Theoriginalhackersfoundsplendorandeleganceinthe
conventionallydrysciencesofmathandelectronics.Theysaw
programmingasaformofartisticexpressionandthecomputer
asaninstrumentofthatart.Theirdesiretodissectand
understandwasn'tintendedtodemystifyartisticendeavors;it
wassimplyawaytoachieveagreaterappreciationofthem.
Theseknowledge-drivenvalueswouldeventuallybecalledthe
HackerEthic:theappreciationoflogicasanartformandthe
promotionofthefreeflowofinformation,surmounting
conventionalboundariesandrestrictionsforthesimplegoalof
betterunderstandingtheworld.Thisisnotanewculturaltrend;
thePythagoreansinancientGreecehadasimilarethicand
subculture,despitenotowningcomputers.Theysawbeautyin
mathematicsanddiscoveredmanycoreconceptsingeometry.
Thatthirstforknowledgeanditsbeneficialbyproductswould
continueonthroughhistory,fromthePythagoreanstoAda
LovelacetoAlanTuringtothehackersoftheMITmodelrailroad
club.ModernhackerslikeRichardStallmanandSteveWozniak
havecontinuedthehackinglegacy,bringingusmodern
operatingsystems,programminglanguages,personal
computers,andmanyothertechnologiesthatweuseeveryday.
Howdoesonedistinguishbetweenthegoodhackerswhobring
usthewondersoftechnologicaladvancementandtheevil
hackerswhostealourcreditcardnumbers?Thetermcracker
wascoinedtodistinguishevilhackersfromthegoodones.
Journalistsweretoldthatcrackersweresupposedtobethebad
guys,whilehackerswerethegoodguys.Hackersstayedtrueto
theHackerEthic,whilecrackerswereonlyinterestedin
breakingthelawandmakingaquickbuck.Crackerswere
consideredtobemuchlesstalentedthantheelitehackers,as
theysimplymadeuseofhacker-writtentoolsandscripts
withoutunderstandinghowtheyworked.Crackerwasmeantto
bethecatch-alllabelforanyonedoinganythingunscrupulous
withacomputer—piratingsoftware,defacingwebsites,and
worstofall,notunderstandingwhattheyweredoing.Butvery
fewpeopleusethistermtoday.
Theterm'slackofpopularitymightbeduetoitsconfusing
etymology—crackeroriginallydescribedthosewhocrack
softwarecopyrightsandreverseengineercopy-protection
schemes.Itscurrentunpopularitymightsimplyresultfromits
twoambiguousnewdefinitions:agroupofpeoplewhoengage
inillegalactivitywithcomputersorpeoplewhoarerelatively
unskilledhackers.Fewtechnologyjournalistsfeelcompelledto
usetermsthatmostoftheirreadersareunfamiliarwith.In
contrast,mostpeopleareawareofthemysteryandskill
associatedwiththetermhacker,soforajournalist,thedecision
tousethetermhackeriseasy.Similarly,thetermscriptkiddie
issometimesusedtorefertocrackers,butitjustdoesn'thave
thesamezingastheshadowyhacker.Therearesomewhowill
stillarguethatthereisadistinctlinebetweenhackersand
crackers,butIbelievethatanyonewhohasthehackerspiritis
ahacker,despiteanylawsheorshemaybreak.
Thecurrentlawsrestrictingcryptographyandcryptographic
researchfurtherblurthelinebetweenhackersandcrackers.In
2001,ProfessorEdwardFeltenandhisresearchteamfrom
PrincetonUniversitywereabouttopublishapaperthat
discussedtheweaknessesofvariousdigitalwatermarking
schemes.Thispaperrespondedtoachallengeissuedbythe
SecureDigitalMusicInitiative(SDMI)intheSDMIPublic
Challenge,whichencouragedthepublictoattempttobreak
thesewatermarkingschemes.BeforeFeltenandhisteamcould
publishthepaper,though,theywerethreatenedbyboththe
SDMIFoundationandtheRecordingIndustryAssociationof
America(RIAA).TheDigitalMillenniumCopyrightAct(DCMA)of
1998makesitillegaltodiscussorprovidetechnologythat
mightbeusedtobypassindustryconsumercontrols.Thissame
lawwasusedagainstDmitrySklyarov,aRussiancomputer
programmerandhacker.Hehadwrittensoftwaretocircumvent
overlysimplisticencryptioninAdobesoftwareandpresentedhis
findingsatahackerconventionintheUnitedStates.TheFBI
swoopedinandarrestedhim,leadingtoalengthylegalbattle.
Underthelaw,thecomplexityoftheindustryconsumercontrols
doesn'tmatter—itwouldbetechnicallyillegaltoreverse
engineerorevendiscussPigLatinifitwereusedasanindustry
consumercontrol.Whoarethehackersandwhoarethe
crackersnow?Whenlawsseemtointerferewithfreespeech,do
thegoodguyswhospeaktheirmindssuddenlybecomebad?I
believethatthespiritofthehackertranscendsgovernmental
laws,asopposedtobeingdefinedbythem.
Thesciencesofnuclearphysicsandbiochemistrycanbeusedto
kill,yettheyalsoprovideuswithsignificantscientific
advancementandmodernmedicine.There'snothinggoodor
badaboutknowledgeitself;moralityliesintheapplicationof
knowledge.Evenifwewantedto,wecouldn'tsuppressthe
knowledgeofhowtoconvertmatterintoenergyorstopthe
continuedtechnologicalprogressofsociety.Inthesameway,
thehackerspiritcanneverbestopped,norcanitbeeasily
categorizedordissected.Hackerswillconstantlybepushingthe
limitsofknowledgeandacceptablebehavior,forcingusto
explorefurtherandfurther.
Partofthisdriveresultsinanultimatelybeneficialco-evolution
ofsecuritythroughcompetitionbetweenattackinghackersand
defendinghackers.Justasthespeedygazelleadaptedfrom
beingchasedbythecheetah,andthecheetahbecameeven
fasterfromchasingthegazelle,thecompetitionbetween
hackersprovidescomputeruserswithbetterandstronger
security,aswellasmorecomplexandsophisticatedattack
techniques.Theintroductionandprogressionofintrusion
detectionsystems(IDSs)isaprimeexampleofthiscoevolutionaryprocess.ThedefendinghackerscreateIDSstoadd
totheirarsenal,whiletheattackinghackersdevelopIDSevasiontechniques,whichareeventuallycompensatedforin
biggerandbetterIDSproducts.Thenetresultofthis
interactionispositive,asitproducessmarterpeople,improved
security,morestablesoftware,inventiveproblem-solving
techniques,andevenaneweconomy.
Theintentofthisbookistoteachyouaboutthetruespiritof
hacking.Wewilllookatvarioushackertechniques,fromthe
pasttothepresent,dissectingthemtolearnhowandwhythey
work.IncludedwiththisbookisabootableLiveCDcontaining
allthesourcecodeusedhereinaswellasapreconfiguredLinux
environment.Explorationandinnovationarecriticaltotheartof
hacking,sothisCDwillletyoufollowalongandexperimenton
yourown.Theonlyrequirementisanx86processor,whichis
usedbyallMicrosoftWindowsmachinesandthenewer
Macintoshcomputers—justinserttheCDandreboot.This
alternateLinuxenvironmentwillnotdisturbyourexistingOS,
sowhenyou'redone,justrebootagainandremovetheCD.
Thisway,youwillgainahands-onunderstandingand
appreciationforhackingthatmayinspireyoutoimproveupon
existingtechniquesoreventoinventnewones.Hopefully,this
bookwillstimulatethecurioushackernatureinyouandprompt
youtocontributetotheartofhackinginsomeway,regardless
ofwhichsideofthefenceyouchoosetobeon.
Chapter0x200.PROGRAMMING
Hackerisatermforboththosewhowritecodeandthosewho
exploitit.Eventhoughthesetwogroupsofhackershave
differentendgoals,bothgroupsusesimilarproblem-solving
techniques.Sinceanunderstandingofprogramminghelps
thosewhoexploit,andanunderstandingofexploitationhelps
thosewhoprogram,manyhackersdoboth.Thereare
interestinghacksfoundinboththetechniquesusedtowrite
elegantcodeandthetechniquesusedtoexploitprograms.
Hackingisreallyjusttheactoffindingacleverand
counterintuitivesolutiontoaproblem.
Thehacksfoundinprogramexploitsusuallyusetherulesofthe
computertobypasssecurityinwaysneverintended.
Programminghacksaresimilarinthattheyalsousetherulesof
thecomputerinnewandinventiveways,butthefinalgoalis
efficiencyorsmallersourcecode,notnecessarilyasecurity
compromise.Thereareactuallyaninfinitenumberofprograms
thatcanbewrittentoaccomplishanygiventask,butmostof
thesesolutionsareunnecessarilylarge,complex,andsloppy.
Thefewsolutionsthatremainaresmall,efficient,andneat.
Programsthathavethesequalitiesaresaidtohaveelegance,
andthecleverandinventivesolutionsthattendtoleadtothis
efficiencyarecalledhacks.Hackersonbothsidesof
programmingappreciateboththebeautyofelegantcodeand
theingenuityofcleverhacks.
Inthebusinessworld,moreimportanceisplacedonchurning
outfunctionalcodethanonachievingcleverhacksand
elegance.Becauseofthetremendousexponentialgrowthof
computationalpowerandmemory,spendinganextrafivehours
tocreateaslightlyfasterandmorememoryefficientpieceof
codejustdoesn'tmakebusinesssensewhendealingwith
moderncomputersthathavegigahertzofprocessingcyclesand
gigabytesofmemory.Whiletimeandmemoryoptimizationsgo
withoutnoticebyallbutthemostsophisticatedofusers,anew
featureismarketable.Whenthebottomlineismoney,spending
timeoncleverhacksforoptimizationjustdoesn'tmakesense.
Trueappreciationofprogrammingeleganceisleftforthe
hackers:computerhobbyistswhoseendgoalisn'ttomakea
profitbuttosqueezeeverypossiblebitoffunctionalityoutof
theiroldCommodore64s,exploitwriterswhoneedtowritetiny
andamazingpiecesofcodetoslipthroughnarrowsecurity
cracks,andanyoneelsewhoappreciatesthepursuitandthe
challengeoffindingthebestpossiblesolution.Thesearethe
peoplewhogetexcitedaboutprogrammingandreally
appreciatethebeautyofanelegantpieceofcodeorthe
ingenuityofacleverhack.Sinceanunderstandingof
programmingisaprerequisitetounderstandinghowprograms
canbeexploited,programmingisanaturalstartingpoint.
0x210.WhatIsProgramming?
Programmingisaverynaturalandintuitiveconcept.Aprogram
isnothingmorethanaseriesofstatementswritteninaspecific
language.Programsareeverywhere,andeventhe
technophobesoftheworlduseprogramseveryday.Driving
directions,cookingrecipes,footballplays,andDNAarealltypes
ofprograms.Atypicalprogramfordrivingdirectionsmightlook
somethinglikethis:
CodeView:
StartoutdownMainStreetheadedeast.ContinueonMainStreet
achurchonyourright.Ifthestreetisblockedbecauseofcon
rightthereat15thStreet,turnleftonPineStreet,andthen
16thStreet.Otherwise,youcanjustcontinueandmakearight
Continueon16thStreet,andturnleftontoDestinationRoad.D
downDestinationRoadfor5miles,andthenyou'llseethehous
Theaddressis743DestinationRoad.
AnyonewhoknowsEnglishcanunderstandandfollowthese
drivingdirections,sincethey'rewritteninEnglish.Granted,
they'renoteloquent,buteachinstructionisclearandeasyto
understand,atleastforsomeonewhoreadsEnglish.
Butacomputerdoesn'tnativelyunderstandEnglish;itonly
understandsmachinelanguage.Toinstructacomputertodo
something,theinstructionsmustbewritteninitslanguage.
However,machinelanguageisarcaneanddifficulttoworkwith
—itconsistsofrawbitsandbytes,anditdiffersfrom
architecturetoarchitecture.Towriteaprograminmachine
languageforanIntelx86processor,youwouldhavetofigure
outthevalueassociatedwitheachinstruction,howeach
instructioninteracts,andmyriadlow-leveldetails.Programming
likethisispainstakingandcumbersome,anditiscertainlynot
intuitive.
What'sneededtoovercomethecomplicationofwritingmachine
languageisatranslator.Anassemblerisoneformofmachinelanguagetranslator—itisaprogramthattranslatesassembly
languageintomachine-readablecode.Assemblylanguageis
lesscrypticthanmachinelanguage,sinceitusesnamesforthe
differentinstructionsandvariables,insteadofjustusing
numbers.However,assemblylanguageisstillfarfromintuitive.
Theinstructionnamesareveryesoteric,andthelanguageis
architecturespecific.JustasmachinelanguageforIntelx86
processorsisdifferentfrommachinelanguageforSparc
processors,x86assemblylanguageisdifferentfromSparc
assemblylanguage.Anyprogramwrittenusingassembly
languageforoneprocessor'sarchitecturewillnotworkon
anotherprocessor'sarchitecture.Ifaprogramiswritteninx86
assemblylanguage,itmustberewrittentorunonSparc
architecture.Inaddition,inordertowriteaneffectiveprogram
inassemblylanguage,youmuststillknowmanylow-level
detailsoftheprocessorarchitectureyouarewritingfor.
Theseproblemscanbemitigatedbyyetanotherformof
translatorcalledacompiler.Acompilerconvertsahigh-level
languageintomachinelanguage.High-levellanguagesare
muchmoreintuitivethanassemblylanguageandcanbe
convertedintomanydifferenttypesofmachinelanguagefor
differentprocessorarchitectures.Thismeansthatifaprogram
iswritteninahighlevellanguage,theprogramonlyneedsto
bewrittenonce;thesamepieceofprogramcodecanbe
compiledintomachinelanguageforvariousspecific
architectures.C,C++,andFortranareallexamplesofhighlevellanguages.Aprogramwritteninahigh-levellanguageis
muchmorereadableandEnglish-likethanassemblylanguage
ormachinelanguage,butitstillmustfollowverystrictrules
abouthowtheinstructionsareworded,orthecompilerwon'tbe
abletounderstandit.
Chapter0x200.PROGRAMMING
Hackerisatermforboththosewhowritecodeandthosewho
exploitit.Eventhoughthesetwogroupsofhackershave
differentendgoals,bothgroupsusesimilarproblem-solving
techniques.Sinceanunderstandingofprogramminghelps
thosewhoexploit,andanunderstandingofexploitationhelps
thosewhoprogram,manyhackersdoboth.Thereare
interestinghacksfoundinboththetechniquesusedtowrite
elegantcodeandthetechniquesusedtoexploitprograms.
Hackingisreallyjusttheactoffindingacleverand
counterintuitivesolutiontoaproblem.
Thehacksfoundinprogramexploitsusuallyusetherulesofthe
computertobypasssecurityinwaysneverintended.
Programminghacksaresimilarinthattheyalsousetherulesof
thecomputerinnewandinventiveways,butthefinalgoalis
efficiencyorsmallersourcecode,notnecessarilyasecurity
compromise.Thereareactuallyaninfinitenumberofprograms
thatcanbewrittentoaccomplishanygiventask,butmostof
thesesolutionsareunnecessarilylarge,complex,andsloppy.
Thefewsolutionsthatremainaresmall,efficient,andneat.
Programsthathavethesequalitiesaresaidtohaveelegance,
andthecleverandinventivesolutionsthattendtoleadtothis
efficiencyarecalledhacks.Hackersonbothsidesof
programmingappreciateboththebeautyofelegantcodeand
theingenuityofcleverhacks.
Inthebusinessworld,moreimportanceisplacedonchurning
outfunctionalcodethanonachievingcleverhacksand
elegance.Becauseofthetremendousexponentialgrowthof
computationalpowerandmemory,spendinganextrafivehours
tocreateaslightlyfasterandmorememoryefficientpieceof
codejustdoesn'tmakebusinesssensewhendealingwith
moderncomputersthathavegigahertzofprocessingcyclesand
gigabytesofmemory.Whiletimeandmemoryoptimizationsgo
withoutnoticebyallbutthemostsophisticatedofusers,anew
featureismarketable.Whenthebottomlineismoney,spending
timeoncleverhacksforoptimizationjustdoesn'tmakesense.
Trueappreciationofprogrammingeleganceisleftforthe
hackers:computerhobbyistswhoseendgoalisn'ttomakea
profitbuttosqueezeeverypossiblebitoffunctionalityoutof
theiroldCommodore64s,exploitwriterswhoneedtowritetiny
andamazingpiecesofcodetoslipthroughnarrowsecurity
cracks,andanyoneelsewhoappreciatesthepursuitandthe
challengeoffindingthebestpossiblesolution.Thesearethe
peoplewhogetexcitedaboutprogrammingandreally
appreciatethebeautyofanelegantpieceofcodeorthe
ingenuityofacleverhack.Sinceanunderstandingof
programmingisaprerequisitetounderstandinghowprograms
canbeexploited,programmingisanaturalstartingpoint.
0x210.WhatIsProgramming?
Programmingisaverynaturalandintuitiveconcept.Aprogram
isnothingmorethanaseriesofstatementswritteninaspecific
language.Programsareeverywhere,andeventhe
technophobesoftheworlduseprogramseveryday.Driving
directions,cookingrecipes,footballplays,andDNAarealltypes
ofprograms.Atypicalprogramfordrivingdirectionsmightlook
somethinglikethis:
CodeView:
StartoutdownMainStreetheadedeast.ContinueonMainStreet
achurchonyourright.Ifthestreetisblockedbecauseofcon
rightthereat15thStreet,turnleftonPineStreet,andthen
16thStreet.Otherwise,youcanjustcontinueandmakearight
Continueon16thStreet,andturnleftontoDestinationRoad.D
downDestinationRoadfor5miles,andthenyou'llseethehous
Theaddressis743DestinationRoad.
AnyonewhoknowsEnglishcanunderstandandfollowthese
drivingdirections,sincethey'rewritteninEnglish.Granted,
they'renoteloquent,buteachinstructionisclearandeasyto
understand,atleastforsomeonewhoreadsEnglish.
Butacomputerdoesn'tnativelyunderstandEnglish;itonly
understandsmachinelanguage.Toinstructacomputertodo
something,theinstructionsmustbewritteninitslanguage.
However,machinelanguageisarcaneanddifficulttoworkwith
—itconsistsofrawbitsandbytes,anditdiffersfrom
architecturetoarchitecture.Towriteaprograminmachine
languageforanIntelx86processor,youwouldhavetofigure
outthevalueassociatedwitheachinstruction,howeach
instructioninteracts,andmyriadlow-leveldetails.Programming
likethisispainstakingandcumbersome,anditiscertainlynot
intuitive.
What'sneededtoovercomethecomplicationofwritingmachine
languageisatranslator.Anassemblerisoneformofmachinelanguagetranslator—itisaprogramthattranslatesassembly
languageintomachine-readablecode.Assemblylanguageis
lesscrypticthanmachinelanguage,sinceitusesnamesforthe
differentinstructionsandvariables,insteadofjustusing
numbers.However,assemblylanguageisstillfarfromintuitive.
Theinstructionnamesareveryesoteric,andthelanguageis
architecturespecific.JustasmachinelanguageforIntelx86
processorsisdifferentfrommachinelanguageforSparc
processors,x86assemblylanguageisdifferentfromSparc
assemblylanguage.Anyprogramwrittenusingassembly
languageforoneprocessor'sarchitecturewillnotworkon
anotherprocessor'sarchitecture.Ifaprogramiswritteninx86
assemblylanguage,itmustberewrittentorunonSparc
architecture.Inaddition,inordertowriteaneffectiveprogram
inassemblylanguage,youmuststillknowmanylow-level
detailsoftheprocessorarchitectureyouarewritingfor.
Theseproblemscanbemitigatedbyyetanotherformof
translatorcalledacompiler.Acompilerconvertsahigh-level
languageintomachinelanguage.High-levellanguagesare
muchmoreintuitivethanassemblylanguageandcanbe
convertedintomanydifferenttypesofmachinelanguagefor
differentprocessorarchitectures.Thismeansthatifaprogram
iswritteninahighlevellanguage,theprogramonlyneedsto
bewrittenonce;thesamepieceofprogramcodecanbe
compiledintomachinelanguageforvariousspecific
architectures.C,C++,andFortranareallexamplesofhighlevellanguages.Aprogramwritteninahigh-levellanguageis
muchmorereadableandEnglish-likethanassemblylanguage
ormachinelanguage,butitstillmustfollowverystrictrules
abouthowtheinstructionsareworded,orthecompilerwon'tbe
abletounderstandit.
0x220.Pseudo-code
Programmershaveyetanotherformofprogramminglanguage
calledpseudo-code.Pseudo-codeissimplyEnglisharranged
withageneralstructuresimilartoahigh-levellanguage.Itisn't
understoodbycompilers,assemblers,oranycomputers,butit
isausefulwayforaprogrammertoarrangeinstructions.
Pseudo-codeisn'twelldefined;infact,mostpeoplewrite
pseudo-codeslightlydifferently.It'ssortofthenebulous
missinglinkbetweenEnglishandhigh-levelprogramming
languageslikeC.Pseudo-codemakesforanexcellent
introductiontocommonuniversalprogrammingconcepts.